gt stringclasses 1
value | context stringlengths 2.05k 161k |
|---|---|
/**
* (c) 2014 Cisco and/or its affiliates. All rights reserved.
*
* This software is released under the Eclipse Public License. The details can be found in the file LICENSE.
* Any dependent libraries supplied by third parties are provided under their own open source licenses as
* described in their own LICENSE files, generally named .LICENSE.txt. The libraries supplied by Cisco as
* part of the Composite Information Server/Cisco Data Virtualization Server, particularly csadmin-XXXX.jar,
* csarchive-XXXX.jar, csbase-XXXX.jar, csclient-XXXX.jar, cscommon-XXXX.jar, csext-XXXX.jar, csjdbc-XXXX.jar,
* csserverutil-XXXX.jar, csserver-XXXX.jar, cswebapi-XXXX.jar, and customproc-XXXX.jar (where -XXXX is an
* optional version number) are provided as a convenience, but are covered under the licensing for the
* Composite Information Server/Cisco Data Virtualization Server. They cannot be used in any way except
* through a valid license for that product.
*
* This software is released AS-IS!. Support for this software is not covered by standard maintenance agreements with Cisco.
* Any support for this software by Cisco would be covered by paid consulting agreements, and would be billable work.
*
*/
package com.cisco.dvbu.ps.deploytool.dao.wsapi;
import java.util.List;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import com.cisco.dvbu.ps.common.exception.ApplicationException;
import com.cisco.dvbu.ps.common.exception.CompositeException;
import com.cisco.dvbu.ps.common.util.CommonUtils;
import com.cisco.dvbu.ps.common.util.CompositeLogger;
import com.cisco.dvbu.ps.common.util.wsapi.CisApiFactory;
import com.cisco.dvbu.ps.common.util.wsapi.CompositeServer;
import com.cisco.dvbu.ps.common.util.wsapi.WsApiHelperObjects;
import com.cisco.dvbu.ps.deploytool.dao.RebindDAO;
import com.cisco.dvbu.ps.deploytool.util.DeployUtil;
import com.compositesw.services.system.admin.RebindResourcesSoapFault;
import com.compositesw.services.system.admin.ResourcePortType;
import com.compositesw.services.system.admin.UpdateBasicTransformProcedureSoapFault;
import com.compositesw.services.system.admin.UpdateExternalSqlProcedureSoapFault;
import com.compositesw.services.system.admin.UpdateSqlScriptProcedureSoapFault;
import com.compositesw.services.system.admin.UpdateSqlTableSoapFault;
import com.compositesw.services.system.admin.UpdateStreamTransformProcedureSoapFault;
import com.compositesw.services.system.admin.UpdateXsltTransformProcedureSoapFault;
import com.compositesw.services.system.admin.resource.Column;
import com.compositesw.services.system.admin.resource.ColumnList;
import com.compositesw.services.system.admin.resource.Model;
import com.compositesw.services.system.admin.resource.MultiPathTypeRequest.Entries;
import com.compositesw.services.system.admin.resource.Parameter;
import com.compositesw.services.system.admin.resource.ParameterList;
import com.compositesw.services.system.admin.resource.PathTypePair;
import com.compositesw.services.system.admin.resource.RebindRule;
import com.compositesw.services.system.admin.resource.RebindRuleList;
import com.compositesw.services.system.admin.resource.ResourceType;
import com.compositesw.services.system.util.common.Attribute;
import com.compositesw.services.system.util.common.DetailLevel;
import com.compositesw.services.system.util.common.AttributeList;
public class RebindWSDAOImpl implements RebindDAO {
private static Log logger = LogFactory.getLog(RebindWSDAOImpl.class);
// @Override
public void rebindResource(String serverId, PathTypePair source, RebindRuleList rebinds, String pathToServersXML) throws CompositeException {
// Set the action name
String actionName = "REBIND";
String command = "rebindResources";
// For debugging
if(logger.isDebugEnabled()) {
logger.debug("RebindWSDAOImpl.rebindResource(serverId, source[path,type], rebinds, pathToServersXML). serverId=\"" + serverId+"\" pathToServersXML=\""+pathToServersXML+"\"");
}
// read target server properties from server xml and build target server object based on target server name
CompositeServer targetServer = WsApiHelperObjects.getServerLogger(serverId, pathToServersXML, "RebindWSDAOImpl.rebindResource", logger);
// Ping the Server to make sure it is alive and the values are correct.
WsApiHelperObjects.pingServer(targetServer, true);
// Construct the resource port based on target server name
ResourcePortType port = CisApiFactory.getResourcePort(targetServer);
try {
// Setup the list of path/type pairs to hold the single source
Entries entries = new Entries();
entries.getEntry().add(source);
// Invoke the rebindResources admin API
logger.info("rebindResources("+source.getPath()+")");
if(logger.isDebugEnabled())
{
String sourceText = "\n Entries:[";
String entryText = "";
if (entries != null && entries.getEntry() != null) {
for (PathTypePair pathType : entries.getEntry()) {
if (entryText.length() != 0)
entryText = entryText + ",\n ";
entryText = entryText + "SRC:\"" + pathType.getPath() + "\", \"" + pathType.getType() + "\"";
}
}
sourceText = sourceText + entryText + "]";
String rebindText = "\n Rebinds:[";
String rebindRuleText = "";
if (rebinds != null && rebinds.getRebindRule() != null) {
for (RebindRule rebindRule : rebinds.getRebindRule()) {
if (rebindRuleText.length() != 0)
rebindRuleText = rebindRuleText + ",\n ";
rebindRuleText = rebindRuleText + "OLD:\"" + rebindRule.getOldPath() + "\", \"" + rebindRule.getOldType() + "\",";
rebindRuleText = rebindRuleText + "\n NEW:\"" + rebindRule.getNewPath() + "\", \"" + rebindRule.getNewType() + "\"";
}
}
rebindText = rebindText + rebindRuleText + "]";
logger.debug("RebindWSDAOImpl.rebindResource(). Invoking port.rebindResources("+sourceText+", "+rebindText+").");
}
// Don't execute if -noop (NO_OPERATION) has been set otherwise execute under normal operation.
if (CommonUtils.isExecOperation())
{
port.rebindResources(entries, rebinds);
if(logger.isDebugEnabled()) {
logger.debug("RebindWSDAOImpl.rebindResource(). Success: port.rebindResources().");
}
} else {
logger.info("\n\nWARNING - NO_OPERATION: COMMAND ["+command+"], ACTION ["+actionName+"] WAS NOT PERFORMED.\n");
}
} catch (RebindResourcesSoapFault e) {
CompositeLogger.logException(e, DeployUtil.constructMessage(DeployUtil.MessageType.ERROR.name(), "rebindResource", "Rebind", source.getType().name(), targetServer),e.getFaultInfo());
throw new ApplicationException(e.getMessage(), e);
}
}
/**
* The following resource types and sub-types are supported:
* resourceType = 'TABLE'
* subtype = 'SQL_TABLE' -- Get Regular View
* port.updateSqlTable(resourcePath, detailLevel, procedureText, model, isExplicitDesign, columns, annotation, attributes);
*
* resourceType = 'PROCEDURE'
* subtype = 'SQL_SCRIPT_PROCEDURE' -- Update Regular Procedure
* port.updateSqlScriptProcedure(resourcePath, detailLevel, procedureText, model, isExplicitDesign, parameters, annotation, attributes);
* subtype = 'EXTERNAL_SQL_PROCEDURE' -- Update Packaged Query Procedure
* port.updateExternalSqlProcedure(resourcePath, detailLevel, procedureText, usedResourcePath, parameters, annotation, attributes);
* subtype = 'BASIC_TRANSFORM_PROCEDURE' -- Update XSLT Basic Transformation definition
* port.updateBasicTransformProcedure(resourcePath, detailLevel, usedResourcePath, resourceType, annotation, attributes);
* subtype = 'XSLT_TRANSFORM_PROCEDURE' -- Update XSLT Transformation text
* port.updateXsltTransformProcedure(resourcePath, detailLevel, usedResourcePath, resourceType, procedureText, model, annotation, isExplicitDesign, parameters, attributes);
* subtype = 'STREAM_TRANSFORM_PROCEDURE' -- Update XSLT Stream Transformation text
* port.updateStreamTransformProcedure(resourcePath, detailLevel, usedResourcePath, resourceType, model, isExplicitDesign, parameters, annotation, attributes);
*/
// @Override
public void takeRebindFolderAction(String serverId, String pathToServersXML, String actionName, String resourcePath, DetailLevel detailLevel, String procedureText, String usedResourcePath, String usedResourceType,
Boolean isExplicitDesign, Model model, ColumnList columns, ParameterList parameters, String annotation, AttributeList attributes) throws CompositeException {
if(logger.isDebugEnabled()){
logger.debug("RebindWSDAOImpl.takeRebindFolderAction(serverId, pathToServersXML, actionName, resourcePath, detailLevel, procedureText, usedResourcePath, usedResourceType, isExplicitDesign, model, columns, parameters, annotation, attributes)."+
" serverId=\"" + serverId + "\" pathToServersXML=\"" + pathToServersXML + "\"");
}
String command = null;
// read target server properties from server xml and build target server object based on target server name
CompositeServer targetServer = WsApiHelperObjects.getServerLogger(serverId, pathToServersXML, "RebindWSDAOImpl.takeRebindFolderAction("+actionName+")", logger);
// Ping the Server to make sure it is alive and the values are correct.
WsApiHelperObjects.pingServer(targetServer, true);
// Construct the resource port based on target server name
ResourcePortType port = CisApiFactory.getResourcePort(targetServer);
ResourceType resourceType = null;
if (usedResourceType != null) {
resourceType = ResourceType.valueOf(usedResourceType);
}
// Invoke the specific API for the action
try {
String annotationStr = (annotation == null) ? null : "\""+annotation+"\"";
String modelType = null;
if (model != null && model.getType() != null)
modelType = model.getType().toString();
int attrSize = 0;
String attrList = "";
int colSize = 0;
String colList = "";
int paramSize = 0;
String paramList = "";
if(logger.isDebugEnabled()) {
if (attributes != null && attributes.getAttribute() != null) {
attrSize = attributes.getAttribute().size();
for (Attribute attr:attributes.getAttribute()) {
if (attrList.length() != 0)
attrList = attrList + ", ";
if (attr.getType().toString().equals("PASSWORD_STRING"))
attrList = attrList + attr.getName() + "=********";
else
attrList = attrList + attr.getName() + "=" + attr.getValue();
}
}
if (columns != null && columns.getColumn() != null) {
colSize = columns.getColumn().size();
for (Column col:columns.getColumn()) {
if (colList.length() != 0)
colList = colList + ", ";
String colType = "UNKNOWN";
if (col.getDataType() != null && col.getDataType().getSqlType() != null && col.getDataType().getSqlType().getDefinition() != null)
colType = col.getDataType().getSqlType().getDefinition();
colList = colList + col.getName() + " " + colType;
}
}
if (parameters != null && parameters.getParameter() != null) {
paramSize = parameters.getParameter().size();
for (Parameter param:parameters.getParameter()) {
if (paramList.length() != 0)
paramList = paramList + ", ";
String paramType = "UNKNOWN";
if (param.getDataType() != null && param.getDataType().getSqlType() != null && param.getDataType().getSqlType().getDefinition() != null)
paramType = param.getDataType().getSqlType().getDefinition();
paramList = paramList + param.getName() + " " + paramType;
}
}
}
if(actionName.equalsIgnoreCase(RebindDAO.action.SQL_TABLE.name()))
{
command = "updateSqlTable";
logger.info("updateSqlTable("+resourcePath+")");
if(logger.isDebugEnabled()) {
logger.debug("RebindWSDAOImpl.takeRebindFolderAction("+actionName+"). Invoking port.updateSqlTable("+
"\n resourcePath=\""+resourcePath+"\","+
"\n detailLevel=\""+detailLevel+"\", "+
"\n SQL_TEXT: \""+procedureText+"\","+
"\n modelType="+modelType+","+
"\n isExplicitDesign="+isExplicitDesign+","+
"\n COLUMNS:["+colList+"],"+
"\n annotation="+ annotationStr+","+
"\n ATTRIBUTES:["+attrList+"])."+
"\n #columns="+colSize+
"\n #attributes="+attrSize);
}
// Don't execute if -noop (NO_OPERATION) has been set otherwise execute under normal operation.
if (CommonUtils.isExecOperation())
{
port.updateSqlTable(resourcePath, detailLevel, procedureText, model, isExplicitDesign, columns, annotation, attributes);
if(logger.isDebugEnabled()) {
logger.debug("RebindWSDAOImpl.takeRebindFolderAction("+actionName+"). Success: port.updateSqlTable().");
}
} else {
logger.info("\n\nWARNING - NO_OPERATION: COMMAND ["+command+"], ACTION ["+actionName+"] WAS NOT PERFORMED.\n");
}
}
else if(actionName.equalsIgnoreCase(RebindDAO.action.SQL_SCRIPT_PROCEDURE.name()))
{
command = "updateSqlScriptProcedure";
logger.info("updateSqlScriptProcedure("+resourcePath+")");
if(logger.isDebugEnabled()) {
logger.debug("RebindWSDAOImpl.takeRebindFolderAction("+actionName+"). Invoking port.updateSqlScriptProcedure("+
"\n resourcePath=\""+resourcePath+"\","+
"\n detailLevel=\""+detailLevel+"\", "+
"\n PROCEDURE_TEXT: \""+procedureText+"\","+
"\n modelType="+modelType+","+
"\n isExplicitDesign="+isExplicitDesign+","+
"\n PARAMETERS:["+paramList+"],"+
"\n annotation="+ annotationStr+","+
"\n ATTRIBUTES:["+attrList+"])."+
"\n #parameters="+paramSize+
"\n #attributes="+attrSize);
}
// Don't execute if -noop (NO_OPERATION) has been set otherwise execute under normal operation.
if (CommonUtils.isExecOperation())
{
port.updateSqlScriptProcedure(resourcePath, detailLevel, procedureText, model, isExplicitDesign, parameters, annotation, attributes);
if(logger.isDebugEnabled()) {
logger.debug("RebindWSDAOImpl.takeRebindFolderAction("+actionName+"). Success: port.updateSqlScriptProcedure().");
}
} else {
logger.info("\n\nWARNING - NO_OPERATION: COMMAND ["+command+"], ACTION ["+actionName+"] WAS NOT PERFORMED.\n");
}
}
else if(actionName.equalsIgnoreCase(RebindDAO.action.EXTERNAL_SQL_PROCEDURE.name()))
{
command = "updateExternalSqlProcedure";
logger.info("updateExternalSqlProcedure("+resourcePath+")");
if(logger.isDebugEnabled()) {
logger.debug("RebindWSDAOImpl.takeRebindFolderAction("+actionName+"). Invoking ort.updateExternalSqlProcedure("+
"\n resourcePath=\""+resourcePath+"\","+
"\n detailLevel=\""+detailLevel+"\", "+
"\n PROCEDURE_TEXT: \""+procedureText+"\","+
"\n usedResourcePath=\""+usedResourcePath+"\","+
"\n PARAMETERS:["+paramList+"],"+
"\n annotation="+ annotationStr+","+
"\n ATTRIBUTES:["+attrList+"])."+
"\n #parameters="+paramSize+
"\n #attributes="+attrSize);
}
// Don't execute if -noop (NO_OPERATION) has been set otherwise execute under normal operation.
if (CommonUtils.isExecOperation())
{
port.updateExternalSqlProcedure(resourcePath, detailLevel, procedureText, usedResourcePath, parameters, annotation, attributes);
if(logger.isDebugEnabled()) {
logger.debug("RebindWSDAOImpl.takeRebindFolderAction("+actionName+"). Success: port.updateExternalSqlProcedure().");
}
} else {
logger.info("\n\nWARNING - NO_OPERATION: COMMAND ["+command+"], ACTION ["+actionName+"] WAS NOT PERFORMED.\n");
}
}
else if(actionName.equalsIgnoreCase(RebindDAO.action.BASIC_TRANSFORM_PROCEDURE.name()))
{
command = "updateBasicTransformProcedure";
logger.info("updateBasicTransformProcedure("+resourcePath+")");
if(logger.isDebugEnabled()) {
logger.debug("RebindWSDAOImpl.takeRebindFolderAction("+actionName+"). Invoking port.updateBasicTransformProcedure("+
"\n resourcePath=\""+resourcePath+"\","+
"\n detailLevel=\""+detailLevel+"\", "+
"\n PROCEDURE_TEXT: \""+procedureText+"\","+
"\n usedResourcePath=\""+usedResourcePath+"\","+
"\n usedResourceType=\""+resourceType+"\","+
"\n annotation="+ annotationStr+","+
"\n ATTRIBUTES:["+attrList+"])."+
"\n #attributes="+attrSize);
}
// Don't execute if -noop (NO_OPERATION) has been set otherwise execute under normal operation.
if (CommonUtils.isExecOperation())
{
port.updateBasicTransformProcedure(resourcePath, detailLevel, usedResourcePath, resourceType, annotation, attributes);
if(logger.isDebugEnabled()) {
logger.debug("RebindWSDAOImpl.takeRebindFolderAction("+actionName+"). Success: port.updateBasicTransformProcedure().");
}
} else {
logger.info("\n\nWARNING - NO_OPERATION: COMMAND ["+command+"], ACTION ["+actionName+"] WAS NOT PERFORMED.\n");
}
}
else if(actionName.equalsIgnoreCase(RebindDAO.action.XSLT_TRANSFORM_PROCEDURE.name()))
{
command = "updateXsltTransformProcedure";
logger.info("updateXsltTransformProcedure("+resourcePath+")");
if(logger.isDebugEnabled()) {
logger.debug("RebindWSDAOImpl.takeRebindFolderAction("+actionName+"). Invoking port.updateXsltTransformProcedure("+
"\n resourcePath=\""+resourcePath+"\","+
"\n detailLevel=\""+detailLevel+"\", "+
"\n usedResourcePath=\""+usedResourcePath+"\","+
"\n usedResourceType=\""+resourceType+"\","+
"\n PROCEDURE_TEXT: \""+procedureText+"\","+
"\n modelType="+modelType+","+
"\n annotation="+ annotationStr+","+
"\n isExplicitDesign="+isExplicitDesign+","+
"\n PARAMETERS:["+paramList+"],"+
"\n ATTRIBUTES:["+attrList+"])."+
"\n #parameters="+paramSize+
"\n #attributes="+attrSize);
}
// Don't execute if -noop (NO_OPERATION) has been set otherwise execute under normal operation.
if (CommonUtils.isExecOperation())
{
port.updateXsltTransformProcedure(resourcePath, detailLevel, usedResourcePath, resourceType, procedureText, model, annotation, isExplicitDesign, parameters, attributes);
if(logger.isDebugEnabled()) {
logger.debug("RebindWSDAOImpl.takeRebindFolderAction("+actionName+"). Success: port.updateXsltTransformProcedure().");
}
} else {
logger.info("\n\nWARNING - NO_OPERATION: COMMAND ["+command+"], ACTION ["+actionName+"] WAS NOT PERFORMED.\n");
}
}
else if(actionName.equalsIgnoreCase(RebindDAO.action.STREAM_TRANSFORM_PROCEDURE.name()))
{
command = "updateStreamTransformProcedure";
logger.info("updateStreamTransformProcedure("+resourcePath+")");
if(logger.isDebugEnabled()) {
logger.debug("RebindWSDAOImpl.takeRebindFolderAction("+actionName+"). Invoking port.updateStreamTransformProcedure("+
"\n resourcePath=\""+resourcePath+"\","+
"\n detailLevel=\""+detailLevel+"\", "+
"\n usedResourcePath=\""+usedResourcePath+"\","+
"\n usedResourceType=\""+resourceType+"\","+
"\n modelType="+modelType+","+
"\n isExplicitDesign="+isExplicitDesign+","+
"\n PARAMETERS:["+paramList+"],"+
"\n annotation="+ annotationStr+","+
"\n ATTRIBUTES:["+attrList+"])."+
"\n #parameters="+paramSize+
"\n #attributes="+attrSize);
}
// Don't execute if -noop (NO_OPERATION) has been set otherwise execute under normal operation.
if (CommonUtils.isExecOperation())
{
port.updateStreamTransformProcedure(resourcePath, detailLevel, usedResourcePath, resourceType, model, isExplicitDesign, parameters, annotation, attributes);
if(logger.isDebugEnabled()) {
logger.debug("RebindWSDAOImpl.takeRebindFolderAction("+actionName+"). Success: port.updateStreamTransformProcedure().");
}
} else {
logger.info("\n\nWARNING - NO_OPERATION: COMMAND ["+command+"], ACTION ["+actionName+"] WAS NOT PERFORMED.\n");
}
} else {
throw new ApplicationException("The action "+actionName+" does not exist.");
}
} catch (UpdateSqlTableSoapFault e) {
CompositeLogger.logException(e, DeployUtil.constructMessage(DeployUtil.MessageType.ERROR.name(), "takeRebindFolderAction", "Rebind", actionName, targetServer),e.getFaultInfo());
throw new ApplicationException(e.getMessage(), e);
} catch (UpdateSqlScriptProcedureSoapFault e) {
CompositeLogger.logException(e, DeployUtil.constructMessage(DeployUtil.MessageType.ERROR.name(), "takeRebindFolderAction", "Rebind", actionName, targetServer),e.getFaultInfo());
throw new ApplicationException(e.getMessage(), e);
} catch (UpdateExternalSqlProcedureSoapFault e) {
CompositeLogger.logException(e, DeployUtil.constructMessage(DeployUtil.MessageType.ERROR.name(), "takeRebindFolderAction", "Rebind", actionName, targetServer),e.getFaultInfo());
throw new ApplicationException(e.getMessage(), e);
} catch (UpdateBasicTransformProcedureSoapFault e) {
CompositeLogger.logException(e, DeployUtil.constructMessage(DeployUtil.MessageType.ERROR.name(), "takeRebindFolderAction", "Rebind", actionName, targetServer),e.getFaultInfo());
throw new ApplicationException(e.getMessage(), e);
} catch (UpdateXsltTransformProcedureSoapFault e) {
CompositeLogger.logException(e, DeployUtil.constructMessage(DeployUtil.MessageType.ERROR.name(), "takeRebindFolderAction", "Rebind", actionName, targetServer),e.getFaultInfo());
throw new ApplicationException(e.getMessage(), e);
} catch (UpdateStreamTransformProcedureSoapFault e) {
CompositeLogger.logException(e, DeployUtil.constructMessage(DeployUtil.MessageType.ERROR.name(), "takeRebindFolderAction", "Rebind", actionName, targetServer),e.getFaultInfo());
throw new ApplicationException(e.getMessage(), e);
}
}
}
| |
/*
* 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 com.alibaba.dubbo.rpc.protocol.dubbo;
import com.alibaba.dubbo.common.Constants;
import com.alibaba.dubbo.common.URL;
import com.alibaba.dubbo.common.utils.NetUtils;
import com.alibaba.dubbo.rpc.Exporter;
import com.alibaba.dubbo.rpc.Invoker;
import com.alibaba.dubbo.rpc.RpcContext;
import com.alibaba.dubbo.rpc.StaticContext;
import com.alibaba.dubbo.rpc.protocol.dubbo.support.ProtocolUtils;
import junit.framework.Assert;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import java.io.Serializable;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
public class ImplicitCallBackTest {
protected Exporter<IDemoService> exporter = null;
protected Invoker<IDemoService> reference = null;
protected URL serviceURL = null;
protected URL consumerUrl = null;
Method onReturnMethod;
Method onThrowMethod;
Method onInvokeMethod;
NofifyImpl notify = new NofifyImpl();
//================================================================================================
IDemoService demoProxy = null;
@Before
public void setUp() throws SecurityException, NoSuchMethodException {
onReturnMethod = Nofify.class.getMethod("onreturn", new Class<?>[]{Person.class, Integer.class});
onThrowMethod = Nofify.class.getMethod("onthrow", new Class<?>[]{Throwable.class, Integer.class});
onInvokeMethod = Nofify.class.getMethod("oninvoke", new Class<?>[]{Integer.class});
}
@After
public void tearDown() {
ProtocolUtils.closeAll();
}
public void initOrResetService() {
destroyService();
exportService();
referService();
}
public void destroyService() {
demoProxy = null;
try {
if (exporter != null) exporter.unexport();
if (reference != null) reference.destroy();
} catch (Exception e) {
}
}
void referService() {
demoProxy = (IDemoService) ProtocolUtils.refer(IDemoService.class, consumerUrl);
}
public void exportService() {
exporter = ProtocolUtils.export(new NormalDemoService(), IDemoService.class, serviceURL);
}
public void exportExService() {
exporter = ProtocolUtils.export(new ExceptionDemoExService(), IDemoService.class, serviceURL);
}
public void initOrResetUrl(boolean isAsync) throws Exception {
int port = NetUtils.getAvailablePort();
consumerUrl = serviceURL = URL.valueOf("dubbo://127.0.0.1:" + port + "/" + IDemoService.class.getName() + "?group=test&async=" + isAsync + "&timeout=100000&reference.filter=future");
StaticContext.getSystemContext().clear();
}
public void initImplicitCallBackURL_onlyOnthrow() throws Exception {
StaticContext.getSystemContext().put(StaticContext.getKey(consumerUrl, "get", Constants.ON_THROW_METHOD_KEY), onThrowMethod);
StaticContext.getSystemContext().put(StaticContext.getKey(consumerUrl, "get", Constants.ON_THROW_INSTANCE_KEY), notify);
}
//================================================================================================
public void initImplicitCallBackURL_onlyOnreturn() throws Exception {
StaticContext.getSystemContext().put(StaticContext.getKey(consumerUrl, "get", Constants.ON_RETURN_METHOD_KEY), onReturnMethod);
StaticContext.getSystemContext().put(StaticContext.getKey(consumerUrl, "get", Constants.ON_RETURN_INSTANCE_KEY), notify);
}
public void initImplicitCallBackURL_onlyOninvoke() throws Exception {
StaticContext.getSystemContext().put(StaticContext.getKey(consumerUrl, "get", Constants.ON_INVOKE_METHOD_KEY), onInvokeMethod);
StaticContext.getSystemContext().put(StaticContext.getKey(consumerUrl, "get", Constants.ON_INVOKE_INSTANCE_KEY), notify);
}
@Test
public void test_CloseCallback() throws Exception {
initOrResetUrl(false);
initOrResetService();
Person ret = demoProxy.get(1);
Assert.assertEquals(1, ret.getId());
destroyService();
}
@Test
public void test_Sync_Onreturn() throws Exception {
initOrResetUrl(false);
initImplicitCallBackURL_onlyOnreturn();
initOrResetService();
int requestId = 2;
Person ret = demoProxy.get(requestId);
Assert.assertEquals(requestId, ret.getId());
for (int i = 0; i < 10; i++) {
if (!notify.ret.containsKey(requestId)) {
Thread.sleep(200);
} else {
break;
}
}
Assert.assertEquals(requestId, notify.ret.get(requestId).getId());
destroyService();
}
@Test
public void test_Ex_OnReturn() throws Exception {
initOrResetUrl(true);
initImplicitCallBackURL_onlyOnreturn();
destroyService();
exportExService();
referService();
int requestId = 2;
Person ret = demoProxy.get(requestId);
Assert.assertEquals(null, ret);
for (int i = 0; i < 10; i++) {
if (!notify.errors.containsKey(requestId)) {
Thread.sleep(200);
} else {
break;
}
}
Assert.assertTrue(!notify.errors.containsKey(requestId));
destroyService();
}
@Test
public void test_Ex_OnInvoke() throws Exception {
initOrResetUrl(true);
initImplicitCallBackURL_onlyOninvoke();
destroyService();
exportExService();
referService();
int requestId = 2;
Person ret = demoProxy.get(requestId);
Assert.assertEquals(null, ret);
for (int i = 0; i < 10; i++) {
if (!notify.inv.contains(requestId)) {
Thread.sleep(200);
} else {
break;
}
}
Assert.assertTrue(notify.inv.contains(requestId));
destroyService();
}
@Test
public void test_Ex_Onthrow() throws Exception {
initOrResetUrl(true);
initImplicitCallBackURL_onlyOnthrow();
destroyService();
exportExService();
referService();
int requestId = 2;
Person ret = demoProxy.get(requestId);
Assert.assertEquals(null, ret);
for (int i = 0; i < 10; i++) {
if (!notify.errors.containsKey(requestId)) {
Thread.sleep(200);
} else {
break;
}
}
Assert.assertTrue(notify.errors.containsKey(requestId));
Assert.assertTrue(notify.errors.get(requestId) instanceof Throwable);
destroyService();
}
@Test
public void test_Sync_NoFuture() throws Exception {
initOrResetUrl(false);
initImplicitCallBackURL_onlyOnreturn();
destroyService();
exportService();
referService();
int requestId = 2;
Person ret = demoProxy.get(requestId);
Assert.assertEquals(requestId, ret.getId());
Future<Person> pFuture = RpcContext.getContext().getFuture();
Assert.assertEquals(null, pFuture);
destroyService();
}
@Test
public void test_Async_Future() throws Exception {
initOrResetUrl(true);
destroyService();
exportService();
referService();
int requestId = 2;
Person ret = demoProxy.get(requestId);
Assert.assertEquals(null, ret);
Future<Person> pFuture = RpcContext.getContext().getFuture();
ret = pFuture.get(1000, TimeUnit.MICROSECONDS);
Assert.assertEquals(requestId, ret.getId());
destroyService();
}
@Test
public void test_Async_Future_Multi() throws Exception {
initOrResetUrl(true);
destroyService();
exportService();
referService();
int requestId1 = 1;
Person ret = demoProxy.get(requestId1);
Assert.assertEquals(null, ret);
Future<Person> p1Future = RpcContext.getContext().getFuture();
int requestId2 = 1;
Person ret2 = demoProxy.get(requestId2);
Assert.assertEquals(null, ret2);
Future<Person> p2Future = RpcContext.getContext().getFuture();
ret = p1Future.get(1000, TimeUnit.MICROSECONDS);
ret2 = p2Future.get(1000, TimeUnit.MICROSECONDS);
Assert.assertEquals(requestId1, ret.getId());
Assert.assertEquals(requestId2, ret.getId());
destroyService();
}
@Test(expected = RuntimeException.class)
public void test_Async_Future_Ex() throws Exception {
try {
initOrResetUrl(true);
destroyService();
exportExService();
referService();
int requestId = 2;
Person ret = demoProxy.get(requestId);
Assert.assertEquals(null, ret);
Future<Person> pFuture = RpcContext.getContext().getFuture();
ret = pFuture.get(1000, TimeUnit.MICROSECONDS);
Assert.assertEquals(requestId, ret.getId());
} finally {
destroyService();
}
}
@Test(expected = RuntimeException.class)
public void test_Normal_Ex() throws Exception {
initOrResetUrl(false);
destroyService();
exportExService();
referService();
int requestId = 2;
Person ret = demoProxy.get(requestId);
Assert.assertEquals(requestId, ret.getId());
}
interface Nofify {
public void onreturn(Person msg, Integer id);
public void onthrow(Throwable ex, Integer id);
public void oninvoke(Integer id);
}
interface IDemoService {
public Person get(int id);
}
public static class Person implements Serializable {
private static final long serialVersionUID = 1L;
private int id;
private String name;
private int age;
public Person(int id, String name, int age) {
this.id = id;
this.name = name;
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
@Override
public String toString() {
return "Person [name=" + name + ", age=" + age + "]";
}
}
class NofifyImpl implements Nofify {
public List<Integer> inv = new ArrayList<Integer>();
public Map<Integer, Person> ret = new HashMap<Integer, Person>();
public Map<Integer, Throwable> errors = new HashMap<Integer, Throwable>();
public boolean exd = false;
public void onreturn(Person msg, Integer id) {
System.out.println("onNotify:" + msg);
ret.put(id, msg);
}
public void onthrow(Throwable ex, Integer id) {
errors.put(id, ex);
// ex.printStackTrace();
}
public void oninvoke(Integer id) {
inv.add(id);
}
}
class NormalDemoService implements IDemoService {
public Person get(int id) {
return new Person(id, "charles", 4);
}
}
class ExceptionDemoExService implements IDemoService {
public Person get(int id) {
throw new RuntimeException("request persion id is :" + id);
}
}
}
| |
/*! ******************************************************************************
*
* Pentaho Data Integration
*
* Copyright (C) 2016-2016 by Pentaho : http://www.pentaho.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 org.pentaho.di.job.entries.googledrive;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.ModifyEvent;
import org.eclipse.swt.events.ModifyListener;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.events.SelectionListener;
import org.eclipse.swt.events.ShellAdapter;
import org.eclipse.swt.events.ShellEvent;
import org.eclipse.swt.layout.FormAttachment;
import org.eclipse.swt.layout.FormData;
import org.eclipse.swt.layout.FormLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Event;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Listener;
import org.eclipse.swt.widgets.MessageBox;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.TableItem;
import org.eclipse.swt.widgets.Text;
import org.pentaho.di.core.Const;
import org.pentaho.di.core.util.Utils;
import org.pentaho.di.i18n.BaseMessages;
import org.pentaho.di.job.JobMeta;
import org.pentaho.di.job.entry.JobEntryDialogInterface;
import org.pentaho.di.job.entry.JobEntryInterface;
import org.pentaho.di.repository.Repository;
import org.pentaho.di.ui.core.gui.WindowProperty;
import org.pentaho.di.ui.core.widget.ColumnInfo;
import org.pentaho.di.ui.core.widget.LabelTextVar;
import org.pentaho.di.ui.core.widget.TableView;
import org.pentaho.di.ui.job.dialog.JobDialog;
import org.pentaho.di.ui.job.entry.JobEntryDialog;
import org.pentaho.di.ui.trans.step.BaseStepDialog;
public class JobEntryGoogleDriveExportDialog extends JobEntryDialog implements JobEntryDialogInterface {
private static final Class<?> PKG = JobEntryAbstractGoogleDrive.class;
private static final String[] YES_NO_COMBO = new String[] {
BaseMessages.getString( PKG, "System.Combo.No" ), BaseMessages.getString( PKG, "System.Combo.Yes" ), };
private JobEntryGoogleDriveExport jobEntry;
private boolean changed;
private Text wName;
private LabelTextVar wApplicationName;
private LabelTextVar wServiceAccountId;
private LabelTextVar wPrivateKeyFile;
private LabelTextVar wTargetDirectory;
private Button wCreateTargetDirectory;
private Button wAddFilesToResult;
private TableView wFilenameList;
private Button wOK, wCancel;
public JobEntryGoogleDriveExportDialog( Shell parent, JobEntryInterface jobEntry, Repository rep, JobMeta jobMeta ) {
super( parent, jobEntry, rep, jobMeta );
this.jobEntry = (JobEntryGoogleDriveExport) jobEntry;
if ( this.jobEntry.getName() == null ) {
this.jobEntry.setName( BaseMessages.getString( PKG, "GoogleDriveExport.Name" ) );
}
}
@Override
public JobEntryInterface open() {
// SWT code for setting up the dialog
Shell parent = getParent();
Display display = parent.getDisplay();
shell = new Shell( parent, props.getJobsDialogStyle() );
props.setLook( shell );
JobDialog.setShellImage( shell, jobEntry );
// save the job entry's changed flag
changed = jobEntry.hasChanged();
// The ModifyListener used on all controls. It will update the meta object to
// indicate that changes are being made.
ModifyListener lsMod = new ModifyListener() {
@Override
public void modifyText( ModifyEvent e ) {
jobEntry.setChanged();
}
};
SelectionListener lsSel = new SelectionAdapter() {
@Override
public void widgetSelected( SelectionEvent e ) {
jobEntry.setChanged();
}
};
// ------------------------------------------------------- //
// SWT code for building the actual settings dialog //
// ------------------------------------------------------- //
FormLayout formLayout = new FormLayout();
formLayout.marginWidth = Const.FORM_MARGIN;
formLayout.marginHeight = Const.FORM_MARGIN;
shell.setLayout( formLayout );
shell.setText( BaseMessages.getString( PKG, "GoogleDriveExport.Name" ) );
int middle = props.getMiddlePct();
int margin = Const.MARGIN;
// Job entry name line
Label wlName = new Label( shell, SWT.RIGHT );
wlName.setText( BaseMessages.getString( PKG, "GoogleDriveExportDialog.JobEntryName.Label" ) );
props.setLook( wlName );
FormData fdlName = new FormData();
fdlName.left = new FormAttachment( 0, 0 );
fdlName.right = new FormAttachment( middle, -margin );
fdlName.top = new FormAttachment( 0, margin );
wlName.setLayoutData( fdlName );
wName = new Text( shell, SWT.SINGLE | SWT.LEFT | SWT.BORDER );
props.setLook( wName );
wName.addModifyListener( lsMod );
FormData fdName = new FormData();
fdName.left = new FormAttachment( middle, 0 );
fdName.top = new FormAttachment( 0, margin );
fdName.right = new FormAttachment( 100, 0 );
wName.setLayoutData( fdName );
// Service Account ID
wApplicationName =
new LabelTextVar( jobMeta, shell,
BaseMessages.getString( PKG, "GoogleDriveExportDialog.ApplicationName.Label" ),
BaseMessages.getString( PKG, "GoogleDriveExportDialog.ApplicationName.Tooltip" ) );
props.setLook( wApplicationName );
wApplicationName.addModifyListener( lsMod );
FormData fdApplicationName = new FormData();
fdApplicationName.left = new FormAttachment( 0, 0 );
fdApplicationName.top = new FormAttachment( wName, margin );
fdApplicationName.right = new FormAttachment( 100, 0 );
wApplicationName.setLayoutData( fdApplicationName );
// Service Account ID
wServiceAccountId =
new LabelTextVar( jobMeta, shell,
BaseMessages.getString( PKG, "GoogleDriveExportDialog.ServiceAccountId.Label" ),
BaseMessages.getString( PKG, "GoogleDriveExportDialog.ServiceAccountId.Tooltip" ) );
props.setLook( wServiceAccountId );
wServiceAccountId.addModifyListener( lsMod );
FormData fdServiceAccountId = new FormData();
fdServiceAccountId.left = new FormAttachment( 0, 0 );
fdServiceAccountId.top = new FormAttachment( wApplicationName, margin );
fdServiceAccountId.right = new FormAttachment( 100, 0 );
wServiceAccountId.setLayoutData( fdServiceAccountId );
// Service Account ID
wPrivateKeyFile =
new LabelTextVar( jobMeta, shell,
BaseMessages.getString( PKG, "GoogleDriveExportDialog.PrivateKeyFile.Label" ),
BaseMessages.getString( PKG, "GoogleDriveExportDialog.PrivateKeyFile.Tooltip" ) );
props.setLook( wPrivateKeyFile );
wPrivateKeyFile.addModifyListener( lsMod );
FormData fdPrivateKeyFile = new FormData();
fdPrivateKeyFile.left = new FormAttachment( 0, 0 );
fdPrivateKeyFile.top = new FormAttachment( wServiceAccountId, margin );
fdPrivateKeyFile.right = new FormAttachment( 100, 0 );
wPrivateKeyFile.setLayoutData( fdPrivateKeyFile );
// Target Directory
wTargetDirectory =
new LabelTextVar( jobMeta, shell,
BaseMessages.getString( PKG, "GoogleDriveExportDialog.TargetDirectory.Label" ),
BaseMessages.getString( PKG, "GoogleDriveExportDialog.TargetDirectory.Tooltip" ) );
props.setLook( wServiceAccountId );
wTargetDirectory.addModifyListener( lsMod );
FormData fdTargetDirectory = new FormData();
fdTargetDirectory.left = new FormAttachment( 0, 0 );
fdTargetDirectory.top = new FormAttachment( wPrivateKeyFile, margin );
fdTargetDirectory.right = new FormAttachment( 100, 0 );
wTargetDirectory.setLayoutData( fdTargetDirectory );
// Create Target Directory
Label wlCreateTargetDirectory = new Label( shell, SWT.RIGHT );
wlCreateTargetDirectory.setText( BaseMessages.getString( PKG, "GoogleDriveExportDialog.CreateTargetDirectory.Label" ) );
wlCreateTargetDirectory.setToolTipText( BaseMessages.getString( PKG, "GoogleDriveExportDialog.CreateTargetDirectory.Tooltip" ) );
props.setLook( wlCreateTargetDirectory );
FormData fdlCreateTargetDirectory = new FormData();
fdlCreateTargetDirectory.left = new FormAttachment( 0, 0 );
fdlCreateTargetDirectory.top = new FormAttachment( wTargetDirectory, margin );
fdlCreateTargetDirectory.right = new FormAttachment( middle, -margin );
wlCreateTargetDirectory.setLayoutData( fdlCreateTargetDirectory );
wCreateTargetDirectory = new Button( shell, SWT.CHECK );
props.setLook( wCreateTargetDirectory );
FormData fdCreateTargetDirectory = new FormData();
fdCreateTargetDirectory.left = new FormAttachment( middle, 0 );
fdCreateTargetDirectory.top = new FormAttachment( wTargetDirectory, margin );
fdCreateTargetDirectory.right = new FormAttachment( 100, 0 );
wCreateTargetDirectory.setLayoutData( fdCreateTargetDirectory );
wCreateTargetDirectory.addSelectionListener( lsSel );
// Add Files to Result
Label wlAddFilesToResult = new Label( shell, SWT.RIGHT );
wlAddFilesToResult.setText( BaseMessages.getString( PKG, "GoogleDriveExportDialog.AddFilesToResult.Label" ) );
wlAddFilesToResult.setToolTipText( BaseMessages.getString( PKG, "GoogleDriveExportDialog.AddFilesToResult.Tooltip" ) );
props.setLook( wlAddFilesToResult );
FormData fdlAddFilesToResult = new FormData();
fdlAddFilesToResult.left = new FormAttachment( 0, 0 );
fdlAddFilesToResult.top = new FormAttachment( wCreateTargetDirectory, margin );
fdlAddFilesToResult.right = new FormAttachment( middle, -margin );
wlAddFilesToResult.setLayoutData( fdlAddFilesToResult );
wAddFilesToResult = new Button( shell, SWT.CHECK );
props.setLook( wAddFilesToResult );
FormData fdAddFilesToResult = new FormData();
fdAddFilesToResult.left = new FormAttachment( middle, 0 );
fdAddFilesToResult.top = new FormAttachment( wCreateTargetDirectory, margin );
fdCreateTargetDirectory.right = new FormAttachment( 100, 0 );
wAddFilesToResult.setLayoutData( fdAddFilesToResult );
wAddFilesToResult.addSelectionListener( lsSel );
// Filename List
ColumnInfo[] colinfo = new ColumnInfo[4];
colinfo[0] = new ColumnInfo( BaseMessages.getString( PKG, "GoogleDriveExportDialog.Column.FileType" ),
ColumnInfo.COLUMN_TYPE_CCOMBO, GoogleDriveFileType.getAllDescriptions().toArray( new String[0] ), false );
colinfo[1] = new ColumnInfo( BaseMessages.getString( PKG, "GoogleDriveExportDialog.Column.ExportType" ),
ColumnInfo.COLUMN_TYPE_CCOMBO, GoogleDriveExportFormat.getAllDescriptions().toArray( new String[0] ), false );
colinfo[2] = new ColumnInfo( BaseMessages.getString( PKG, "GoogleDriveExportDialog.Column.Query" ),
ColumnInfo.COLUMN_TYPE_TEXT, false );
colinfo[3] = new ColumnInfo( BaseMessages.getString( PKG, "GoogleDriveExportDialog.Column.DeleteSource" ),
ColumnInfo.COLUMN_TYPE_CCOMBO, YES_NO_COMBO, false );
int rows = jobEntry.getFileSelections() == null ? 1 : jobEntry.getFileSelections().length;
wFilenameList =
new TableView( jobMeta, shell, SWT.FULL_SELECTION | SWT.SINGLE | SWT.BORDER, colinfo, rows, lsMod, props );
props.setLook( wFilenameList );
FormData fdFilenameList = new FormData();
fdFilenameList.left = new FormAttachment( 0, 0 );
fdFilenameList.right = new FormAttachment( 100, -margin );
fdFilenameList.top = new FormAttachment( wAddFilesToResult, margin );
wFilenameList.setLayoutData( fdFilenameList );
// Add listeners
Listener lsCancel = new Listener() {
@Override
public void handleEvent( Event e ) {
cancel();
}
};
Listener lsOK = new Listener() {
@Override
public void handleEvent( Event e ) {
ok();
}
};
wOK = new Button( shell, SWT.PUSH );
wOK.setText( BaseMessages.getString( PKG, "System.Button.OK" ) );
wCancel = new Button( shell, SWT.PUSH );
wCancel.setText( BaseMessages.getString( PKG, "System.Button.Cancel" ) );
BaseStepDialog.positionBottomButtons( shell, new Button[] { wOK, wCancel }, margin, wFilenameList );
wCancel.addListener( SWT.Selection, lsCancel );
wOK.addListener( SWT.Selection, lsOK );
// Detect X or ALT-F4 or something that kills this window...
shell.addShellListener( new ShellAdapter() {
@Override
public void shellClosed( ShellEvent e ) {
cancel();
}
} );
getData();
BaseStepDialog.setSize( shell );
shell.open();
props.setDialogSize( shell, "JobEntryGoogleDriveExport" );
while ( !shell.isDisposed() ) {
if ( !display.readAndDispatch() ) {
display.sleep();
}
}
return jobEntry;
}
public void dispose() {
WindowProperty winprop = new WindowProperty( shell );
props.setScreen( winprop );
shell.dispose();
}
/**
* Copy information from the meta-data input to the dialog fields.
*/
public void getData() {
wName.setText( Const.NVL( jobEntry.getName(), "" ) );
wApplicationName.setText( Const.NVL( jobEntry.getApplicationName(), "" ) );
wServiceAccountId.setText( Const.NVL( jobEntry.getServiceAccountId(), "" ) );
wPrivateKeyFile.setText( Const.NVL( jobEntry.getPrivateKeyFile(), "" ) );
wTargetDirectory.setText( Const.NVL( jobEntry.getTargetFolder(), "" ) );
wCreateTargetDirectory.setSelection( jobEntry.isCreateTargetFolder() );
wAddFilesToResult.setSelection( jobEntry.isAddFilesToResult() );
if ( jobEntry.getFileSelections() != null ) {
for ( int i = 0; i < jobEntry.getFileSelections().length; i++ ) {
TableItem item = wFilenameList.getTable().getItem( i );
item.setText( 1, Const.NVL( jobEntry.getFileSelections()[i].getFileType().getDescription(), "" ) );
item.setText( 2, Const.NVL( jobEntry.getFileSelections()[i].getExportFormat().getFileExtension(), "" ) );
item.setText( 3, Const.NVL( jobEntry.getFileSelections()[i].getQueryOptions(), "" ) );
item.setText( 4, jobEntry.getFileSelections()[i].isDeleteSourceFile() ? YES_NO_COMBO[1] : YES_NO_COMBO[0] );
}
}
}
private void cancel() {
jobEntry.setChanged( changed );
jobEntry = null;
dispose();
}
/**
* Update jobentry from the dialog values
*/
protected void ok() {
if ( Utils.isEmpty( wName.getText() ) ) {
MessageBox mb = new MessageBox( shell, SWT.OK | SWT.ICON_ERROR );
mb.setText( BaseMessages.getString( PKG, "System.StepJobEntryNameMissing.Title" ) );
mb.setMessage( BaseMessages.getString( PKG, "System.JobEntryNameMissing.Msg" ) );
mb.open();
return;
}
jobEntry.setName( wName.getText() );
jobEntry.setApplicationName( wApplicationName.getText() );
jobEntry.setServiceAccountId( wServiceAccountId.getText() );
jobEntry.setPrivateKeyFile( wPrivateKeyFile.getText() );
jobEntry.setTargetFolder( wTargetDirectory.getText() );
jobEntry.setCreateTargetFolder( wCreateTargetDirectory.getSelection() );
jobEntry.setAddFilesToResult( wAddFilesToResult.getSelection() );
int rows = wFilenameList.nrNonEmpty();
GoogleDriveExportFileSelection[] fileSelections = new GoogleDriveExportFileSelection[rows];
for ( int i = 0; i < rows; i++ ) {
TableItem row = wFilenameList.getNonEmpty( i );
GoogleDriveFileType fileType = GoogleDriveFileType.findByDescription( row.getText( 1 ) );
GoogleDriveExportFormat exportFormat = GoogleDriveExportFormat.findByFileExtension( row.getText( 2 ) );
String customQuery = Const.trim( row.getText( 3 ) );
boolean deleteSourceFile = YES_NO_COMBO[1].equalsIgnoreCase( row.getText( 4 ) );
GoogleDriveExportFileSelection entry =
new GoogleDriveExportFileSelection( fileType, exportFormat, customQuery, deleteSourceFile );
fileSelections[i] = entry;
}
jobEntry.setFileSelections( fileSelections );
dispose();
}
}
| |
package com.salton123.common.util;
import android.text.TextUtils;
import java.io.*;
import java.util.ArrayList;
import java.util.List;
/**
* File Utils
* <ul>
* Read or write file
* <li>{@link #readFile(String, String)} read file</li>
* <li>{@link #readFileToList(String, String)} read file to string list</li>
* <li>{@link #writeFile(String, String, boolean)} write file from String</li>
* <li>{@link #writeFile(String, String)} write file from String</li>
* <li>{@link #writeFile(String, List, boolean)} write file from String List</li>
* <li>{@link #writeFile(String, List)} write file from String List</li>
* <li>{@link #writeFile(String, InputStream)} write file</li>
* <li>{@link #writeFile(String, InputStream, boolean)} write file</li>
* <li>{@link #writeFile(File, InputStream)} write file</li>
* <li>{@link #writeFile(File, InputStream, boolean)} write file</li>
* </ul>
* <ul>
* Operate file
* <li>{@link #moveFile(File, File)} or {@link #moveFile(String, String)}</li>
* <li>{@link #copyFile(String, String)}</li>
* <li>{@link #getFileExtension(String)}</li>
* <li>{@link #getFileName(String)}</li>
* <li>{@link #getFileNameWithoutExtension(String)}</li>
* <li>{@link #getFileSize(String)}</li>
* <li>{@link #deleteFile(String)}</li>
* <li>{@link #isFileExist(String)}</li>
* <li>{@link #isFolderExist(String)}</li>
* <li>{@link #makeFolders(String)}</li>
* <li>{@link #makeDirs(String)}</li>
* </ul>
*
* @author <a href="http://www.trinea.cn" target="_blank">Trinea</a> 2012-5-12
*/
public class FileUtils {
public final static String FILE_EXTENSION_SEPARATOR = ".";
private FileUtils() {
throw new AssertionError();
}
/**
* read file
*
* @param filePath
* @param charsetName The name of a supported {@link java.nio.charset.Charset </code>charset<code>}
* @return if file not exist, return null, else return content of file
* @throws RuntimeException if an error occurs while operator BufferedReader
*/
public static StringBuilder readFile(String filePath, String charsetName) {
File file = new File(filePath);
StringBuilder fileContent = new StringBuilder("");
if (file == null || !file.isFile()) {
return null;
}
BufferedReader reader = null;
try {
InputStreamReader is = new InputStreamReader(new FileInputStream(file), charsetName);
reader = new BufferedReader(is);
String line = null;
while ((line = reader.readLine()) != null) {
if (!fileContent.toString().equals("")) {
fileContent.append("\r\n");
}
fileContent.append(line);
}
return fileContent;
} catch (IOException e) {
throw new RuntimeException("IOException occurred. ", e);
} finally {
IOUtils.close(reader);
}
}
/**
* write file
*
* @param filePath
* @param content
* @param append is append, if true, write to the end of file, else clear content of file and write into it
* @return return false if content is empty, true otherwise
* @throws RuntimeException if an error occurs while operator FileWriter
*/
public static boolean writeFile(String filePath, String content, boolean append) {
if (StringUtils.isEmpty(content)) {
return false;
}
FileWriter fileWriter = null;
try {
makeDirs(filePath);
fileWriter = new FileWriter(filePath, append);
fileWriter.write(content);
return true;
} catch (IOException e) {
throw new RuntimeException("IOException occurred. ", e);
} finally {
IOUtils.close(fileWriter);
}
}
/**
* write file
*
* @param filePath
* @param contentList
* @param append is append, if true, write to the end of file, else clear content of file and write into it
* @return return false if contentList is empty, true otherwise
* @throws RuntimeException if an error occurs while operator FileWriter
*/
public static boolean writeFile(String filePath, List<String> contentList, boolean append) {
if (ListUtils.isEmpty(contentList)) {
return false;
}
FileWriter fileWriter = null;
try {
makeDirs(filePath);
fileWriter = new FileWriter(filePath, append);
int i = 0;
for (String line : contentList) {
if (i++ > 0) {
fileWriter.write("\r\n");
}
fileWriter.write(line);
}
return true;
} catch (IOException e) {
throw new RuntimeException("IOException occurred. ", e);
} finally {
IOUtils.close(fileWriter);
}
}
/**
* write file, the string will be written to the begin of the file
*
* @param filePath
* @param content
* @return
*/
public static boolean writeFile(String filePath, String content) {
return writeFile(filePath, content, false);
}
/**
* write file, the string list will be written to the begin of the file
*
* @param filePath
* @param contentList
* @return
*/
public static boolean writeFile(String filePath, List<String> contentList) {
return writeFile(filePath, contentList, false);
}
/**
* write file, the bytes will be written to the begin of the file
*
* @param filePath
* @param stream
* @return
* @see {@link #writeFile(String, InputStream, boolean)}
*/
public static boolean writeFile(String filePath, InputStream stream) {
return writeFile(filePath, stream, false);
}
/**
* write file
*
* @param filePath the file to be opened for writing.
* @param stream the input stream
* @param append if <code>true</code>, then bytes will be written to the end of the file rather than the beginning
* @return return true
* @throws RuntimeException if an error occurs while operator FileOutputStream
*/
public static boolean writeFile(String filePath, InputStream stream, boolean append) {
return writeFile(filePath != null ? new File(filePath) : null, stream, append);
}
/**
* write file, the bytes will be written to the begin of the file
*
* @param file
* @param stream
* @return
* @see {@link #writeFile(File, InputStream, boolean)}
*/
public static boolean writeFile(File file, InputStream stream) {
return writeFile(file, stream, false);
}
/**
* write file
*
* @param file the file to be opened for writing.
* @param stream the input stream
* @param append if <code>true</code>, then bytes will be written to the end of the file rather than the beginning
* @return return true
* @throws RuntimeException if an error occurs while operator FileOutputStream
*/
public static boolean writeFile(File file, InputStream stream, boolean append) {
OutputStream o = null;
try {
makeDirs(file.getAbsolutePath());
o = new FileOutputStream(file, append);
byte data[] = new byte[1024];
int length = -1;
while ((length = stream.read(data)) != -1) {
o.write(data, 0, length);
}
o.flush();
return true;
} catch (FileNotFoundException e) {
throw new RuntimeException("FileNotFoundException occurred. ", e);
} catch (IOException e) {
throw new RuntimeException("IOException occurred. ", e);
} finally {
IOUtils.close(o);
IOUtils.close(stream);
}
}
/**
* move file
*
* @param sourceFilePath
* @param destFilePath
*/
public static void moveFile(String sourceFilePath, String destFilePath) {
if (TextUtils.isEmpty(sourceFilePath) || TextUtils.isEmpty(destFilePath)) {
throw new RuntimeException("Both sourceFilePath and destFilePath cannot be null.");
}
moveFile(new File(sourceFilePath), new File(destFilePath));
}
/**
* move file
*
* @param srcFile
* @param destFile
*/
public static void moveFile(File srcFile, File destFile) {
boolean rename = srcFile.renameTo(destFile);
if (!rename) {
copyFile(srcFile.getAbsolutePath(), destFile.getAbsolutePath());
deleteFile(srcFile.getAbsolutePath());
}
}
/**
* copy file
*
* @param sourceFilePath
* @param destFilePath
* @return
* @throws RuntimeException if an error occurs while operator FileOutputStream
*/
public static boolean copyFile(String sourceFilePath, String destFilePath) {
InputStream inputStream = null;
try {
inputStream = new FileInputStream(sourceFilePath);
} catch (FileNotFoundException e) {
throw new RuntimeException("FileNotFoundException occurred. ", e);
}
return writeFile(destFilePath, inputStream);
}
/**
* read file to string list, a element of list is a line
*
* @param filePath
* @param charsetName The name of a supported {@link java.nio.charset.Charset </code>charset<code>}
* @return if file not exist, return null, else return content of file
* @throws RuntimeException if an error occurs while operator BufferedReader
*/
public static List<String> readFileToList(String filePath, String charsetName) {
File file = new File(filePath);
List<String> fileContent = new ArrayList<String>();
if (file == null || !file.isFile()) {
return null;
}
BufferedReader reader = null;
try {
InputStreamReader is = new InputStreamReader(new FileInputStream(file), charsetName);
reader = new BufferedReader(is);
String line = null;
while ((line = reader.readLine()) != null) {
fileContent.add(line);
}
return fileContent;
} catch (IOException e) {
throw new RuntimeException("IOException occurred. ", e);
} finally {
IOUtils.close(reader);
}
}
/**
* get file name from path, not include suffix
*
* <pre>
* getFileNameWithoutExtension(null) = null
* getFileNameWithoutExtension("") = ""
* getFileNameWithoutExtension(" ") = " "
* getFileNameWithoutExtension("abc") = "abc"
* getFileNameWithoutExtension("a.mp3") = "a"
* getFileNameWithoutExtension("a.b.rmvb") = "a.b"
* getFileNameWithoutExtension("c:\\") = ""
* getFileNameWithoutExtension("c:\\a") = "a"
* getFileNameWithoutExtension("c:\\a.b") = "a"
* getFileNameWithoutExtension("c:a.txt\\a") = "a"
* getFileNameWithoutExtension("/home/admin") = "admin"
* getFileNameWithoutExtension("/home/admin/a.txt/b.mp3") = "b"
* </pre>
*
* @param filePath
* @return file name from path, not include suffix
* @see
*/
public static String getFileNameWithoutExtension(String filePath) {
if (StringUtils.isEmpty(filePath)) {
return filePath;
}
int extenPosi = filePath.lastIndexOf(FILE_EXTENSION_SEPARATOR);
int filePosi = filePath.lastIndexOf(File.separator);
if (filePosi == -1) {
return (extenPosi == -1 ? filePath : filePath.substring(0, extenPosi));
}
if (extenPosi == -1) {
return filePath.substring(filePosi + 1);
}
return (filePosi < extenPosi ? filePath.substring(filePosi + 1, extenPosi) : filePath.substring(filePosi + 1));
}
/**
* get file name from path, include suffix
*
* <pre>
* getFileName(null) = null
* getFileName("") = ""
* getFileName(" ") = " "
* getFileName("a.mp3") = "a.mp3"
* getFileName("a.b.rmvb") = "a.b.rmvb"
* getFileName("abc") = "abc"
* getFileName("c:\\") = ""
* getFileName("c:\\a") = "a"
* getFileName("c:\\a.b") = "a.b"
* getFileName("c:a.txt\\a") = "a"
* getFileName("/home/admin") = "admin"
* getFileName("/home/admin/a.txt/b.mp3") = "b.mp3"
* </pre>
*
* @param filePath
* @return file name from path, include suffix
*/
public static String getFileName(String filePath) {
if (StringUtils.isEmpty(filePath)) {
return filePath;
}
int filePosi = filePath.lastIndexOf(File.separator);
return (filePosi == -1) ? filePath : filePath.substring(filePosi + 1);
}
/**
* get folder name from path
*
* <pre>
* getFolderName(null) = null
* getFolderName("") = ""
* getFolderName(" ") = ""
* getFolderName("a.mp3") = ""
* getFolderName("a.b.rmvb") = ""
* getFolderName("abc") = ""
* getFolderName("c:\\") = "c:"
* getFolderName("c:\\a") = "c:"
* getFolderName("c:\\a.b") = "c:"
* getFolderName("c:a.txt\\a") = "c:a.txt"
* getFolderName("c:a\\b\\c\\d.txt") = "c:a\\b\\c"
* getFolderName("/home/admin") = "/home"
* getFolderName("/home/admin/a.txt/b.mp3") = "/home/admin/a.txt"
* </pre>
*
* @param filePath
* @return
*/
public static String getFolderName(String filePath) {
if (StringUtils.isEmpty(filePath)) {
return filePath;
}
int filePosi = filePath.lastIndexOf(File.separator);
return (filePosi == -1) ? "" : filePath.substring(0, filePosi);
}
/**
* get suffix of file from path
*
* <pre>
* getFileExtension(null) = ""
* getFileExtension("") = ""
* getFileExtension(" ") = " "
* getFileExtension("a.mp3") = "mp3"
* getFileExtension("a.b.rmvb") = "rmvb"
* getFileExtension("abc") = ""
* getFileExtension("c:\\") = ""
* getFileExtension("c:\\a") = ""
* getFileExtension("c:\\a.b") = "b"
* getFileExtension("c:a.txt\\a") = ""
* getFileExtension("/home/admin") = ""
* getFileExtension("/home/admin/a.txt/b") = ""
* getFileExtension("/home/admin/a.txt/b.mp3") = "mp3"
* </pre>
*
* @param filePath
* @return
*/
public static String getFileExtension(String filePath) {
if (StringUtils.isBlank(filePath)) {
return filePath;
}
int extenPosi = filePath.lastIndexOf(FILE_EXTENSION_SEPARATOR);
int filePosi = filePath.lastIndexOf(File.separator);
if (extenPosi == -1) {
return "";
}
return (filePosi >= extenPosi) ? "" : filePath.substring(extenPosi + 1);
}
/**
* Creates the directory named by the trailing filename of this file, including the complete directory path required
* to create this directory. <br/>
* <br/>
* <ul>
* <strong>Attentions:</strong>
* <li>makeDirs("C:\\Users\\Trinea") can only create users folder</li>
* <li>makeFolder("C:\\Users\\Trinea\\") can create Trinea folder</li>
* </ul>
*
* @param filePath
* @return true if the necessary directories have been created or the target directory already exists, false one of
* the directories can not be created.
* <ul>
* <li>if {@link FileUtils#getFolderName(String)} return null, return false</li>
* <li>if target directory already exists, return true</li>
* <li>return {@link FileUtils#makeFolders(String)}</li>
* </ul>
*/
public static boolean makeDirs(String filePath) {
String folderName = getFolderName(filePath);
if (StringUtils.isEmpty(folderName)) {
return false;
}
File folder = new File(folderName);
return (folder.exists() && folder.isDirectory()) ? true : folder.mkdirs();
}
/**
* @param filePath
* @return
* @see #makeDirs(String)
*/
public static boolean makeFolders(String filePath) {
return makeDirs(filePath);
}
/**
* Indicates if this file represents a file on the underlying file system.
*
* @param filePath
* @return
*/
public static boolean isFileExist(String filePath) {
if (StringUtils.isBlank(filePath)) {
return false;
}
File file = new File(filePath);
return (file.exists() && file.isFile());
}
/**
* Indicates if this file represents a directory on the underlying file system.
*
* @param directoryPath
* @return
*/
public static boolean isFolderExist(String directoryPath) {
if (StringUtils.isBlank(directoryPath)) {
return false;
}
File dire = new File(directoryPath);
return (dire.exists() && dire.isDirectory());
}
/**
* delete file or directory
* <ul>
* <li>if path is null or empty, return true</li>
* <li>if path not exist, return true</li>
* <li>if path exist, delete recursion. return true</li>
* <ul>
*
* @param path
* @return
*/
public static boolean deleteFile(String path) {
if (StringUtils.isBlank(path)) {
return true;
}
File file = new File(path);
if (!file.exists()) {
return true;
}
if (file.isFile()) {
return file.delete();
}
if (!file.isDirectory()) {
return false;
}
for (File f : file.listFiles()) {
if (f.isFile()) {
f.delete();
} else if (f.isDirectory()) {
deleteFile(f.getAbsolutePath());
}
}
return file.delete();
}
/**
* get file size
* <ul>
* <li>if path is null or empty, return -1</li>
* <li>if path exist and it is a file, return file size, else return -1</li>
* <ul>
*
* @param path
* @return returns the length of this file in bytes. returns -1 if the file does not exist.
*/
public static long getFileSize(String path) {
if (StringUtils.isBlank(path)) {
return -1;
}
File file = new File(path);
return (file.exists() && file.isFile() ? file.length() : -1);
}
}
| |
/*
* Copyright 2011 Rod Hyde (rod@badlydrawngames.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.badlydrawngames.veryangryrobots.mobiles;
import com.badlogic.gdx.math.Intersector;
import com.badlogic.gdx.math.Rectangle;
import com.badlogic.gdx.math.Vector2;
import com.badlogic.gdx.utils.Array;
import com.badlydrawngames.general.Config;
import com.badlydrawngames.veryangryrobots.Assets;
import com.badlydrawngames.veryangryrobots.World.FireCommand;
import static com.badlogic.gdx.math.MathUtils.*;
import static com.badlydrawngames.general.MathUtils.*;
public class Robot extends GameObject {
public static final int SCANNING = INACTIVE + 1;
public static final int WALKING_RIGHT = SCANNING + 1;
public static final int WALKING_RIGHT_DIAGONAL = WALKING_RIGHT + 1;
public static final int WALKING_LEFT = WALKING_RIGHT_DIAGONAL + 1;
public static final int WALKING_LEFT_DIAGONAL = WALKING_LEFT + 1;
public static final int WALKING_DOWN = WALKING_LEFT_DIAGONAL + 1;
public static final int WALKING_UP = WALKING_DOWN + 1;
private static final float WALKING_SPEED = Config.asFloat("Robot.speed", 1.25f);
private GameObject player;
private Array<Rectangle> walls;
private final float distance;
private final float fudge;
private FireCommand fireCommand;
private Vector2 firingDirection;
private Vector2 robotPos;
private Vector2 playerPos;
private Vector2 lineStart;
private Vector2 lineEnd;
private float respawnX;
private float respawnY;
public Robot () {
width = Assets.robotWidth;
height = Assets.robotHeight;
distance = max(width, height);
fudge = distance * 0.25f;
setState(INACTIVE);
firingDirection = new Vector2();
robotPos = new Vector2();
playerPos = new Vector2();
lineStart = new Vector2();
lineEnd = new Vector2();
}
public void setPlayer (GameObject player) {
this.player = player;
}
public void setWalls (Array<Rectangle> walls) {
this.walls = walls;
}
public void setFireCommand (FireCommand fireCommand) {
this.fireCommand = fireCommand;
}
@Override
public void update (float delta) {
stateTime += delta;
moveRobot(delta);
if (fireCommand != null && canFire(delta) && canSeePlayer()) {
firingDirection.set(player.x - x, player.y - y);
firingDirection.nor();
fireCommand.fire(this, firingDirection.x, firingDirection.y);
}
}
private boolean canFire (float delta) {
// TODO: remove magic numbers, or possibly switch to expovariate randomness.
return random(100) < 50 * delta;
}
private void moveRobot (float delta) {
float dx = (player.x + player.width / 2) - (x + width / 2);
float dy = (player.y + player.height / 2) - (y + height / 2);
dx = abs(dx) >= 2 ? sgn(dx) : 0.0f;
dy = abs(dy) >= 2 ? sgn(dy) : 0.0f;
float ax = 0.0f;
float ay = 0.0f;
if (!wouldHitWall(dx, dy)) {
ax = dx;
ay = dy;
} else if (dx != 0 && !wouldHitWall(dx, 0)) {
ax = dx;
} else if (dy != 0 && !wouldHitWall(0, dy)) {
ay = dy;
}
dx = ax * WALKING_SPEED;
dy = ay * WALKING_SPEED;
x += dx * delta;
y += dy * delta;
int newState = getMovementState(dx, dy);
if (newState != state) {
setState(newState);
}
}
private int getMovementState (float dx, float dy) {
if (dx == 0.0f && dy == 0.0f) {
return SCANNING;
} else if (dx > 0) {
return (dy == 0) ? WALKING_RIGHT : WALKING_RIGHT_DIAGONAL;
} else if (dx < 0) {
return (dy == 0) ? WALKING_LEFT : WALKING_LEFT_DIAGONAL;
} else if (dy < 0) {
return WALKING_DOWN;
} else {
return WALKING_UP;
}
}
private boolean wouldHitWall (float dx, float dy) {
float x1 = x + width / 2;
float y1 = y + height / 2;
float x2 = x1 + dx * distance;
float y2 = y1 + dy * distance;
for (int i = 0; i < walls.size; i++) {
Rectangle wall = walls.get(i);
if (doesLineHitWall(wall, x1, y1, x2, y2)) {
return true;
}
}
return false;
}
private boolean doesLineHitWall (Rectangle rect, float x1, float y1, float x2, float y2) {
// Does not intersect if minimum y coordinate is below the rectangle.
float minY = min(y1, y2);
if (minY >= rect.y + rect.height + fudge) return false;
// Does not intersect if maximum y coordinate is above the rectangle.
float maxY = max(y1, y2);
if (maxY < rect.y - fudge) return false;
// Does not intersect if minimum x coordinate is to the right of the rectangle.
float minX = min(x1, x2);
if (minX >= rect.x + rect.width + fudge) return false;
// Does not intersect if maximum x coordinate is to the left of the rectangle.
float maxX = max(x1, x2);
if (maxX < rect.x - fudge) return false;
// And that's good enough, because the robots need to be a bit stupid
// when they're near the ends of walls.
return true;
}
private boolean canSeePlayer () {
return hasLineOfSight(this, player);
}
private boolean hasLineOfSight (GameObject a, GameObject b) {
return hasLineOfSight(a.x + a.width / 2, a.y + a.height / 2, b.x + b.width / 2, b.y + b.height / 2);
}
private boolean hasLineOfSight (float x1, float y1, float x2, float y2) {
robotPos.set(x1, y1);
playerPos.set(x2, y2);
for (int i = 0; i < walls.size; i++) {
Rectangle wall = walls.get(i);
if (wall.width > wall.height) {
lineStart.set(wall.x, wall.y + wall.height / 2);
lineEnd.set(wall.x + wall.width, lineStart.y);
} else {
lineStart.set(wall.x + wall.width / 2, wall.y);
lineEnd.set(lineStart.x, wall.y + wall.height);
}
if (Intersector.intersectSegments(robotPos, playerPos, lineStart, lineEnd, null)) {
return false;
}
}
return true;
}
public void setRespawnPoint (float x, float y) {
respawnX = x;
respawnY = y;
}
public void respawn () {
x = respawnX;
y = respawnY;
}
}
| |
/**
* 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.kafka.streams.kstream;
import org.apache.kafka.common.serialization.Deserializer;
import org.apache.kafka.common.serialization.Serializer;
import org.apache.kafka.streams.processor.ProcessorSupplier;
/**
* KStream is an abstraction of a stream of key-value pairs.
*
* @param <K> the type of keys
* @param <V> the type of values
*/
public interface KStream<K, V> {
/**
* Creates a new instance of KStream consists of all elements of this stream which satisfy a predicate
*
* @param predicate the instance of Predicate
* @return the instance of KStream with only those elements that satisfy the predicate
*/
KStream<K, V> filter(Predicate<K, V> predicate);
/**
* Creates a new instance of KStream consists all elements of this stream which do not satisfy a predicate
*
* @param predicate the instance of Predicate
* @return the instance of KStream with only those elements that do not satisfy the predicate
*/
KStream<K, V> filterOut(Predicate<K, V> predicate);
/**
* Creates a new instance of KStream by applying transforming each element in this stream into a different element in the new stream.
*
* @param mapper the instance of KeyValueMapper
* @param <K1> the key type of the new stream
* @param <V1> the value type of the new stream
* @return the instance of KStream
*/
<K1, V1> KStream<K1, V1> map(KeyValueMapper<K, V, KeyValue<K1, V1>> mapper);
/**
* Creates a new instance of KStream by transforming each value in this stream into a different value in the new stream.
*
* @param mapper the instance of ValueMapper
* @param <V1> the value type of the new stream
* @return the instance of KStream
*/
<V1> KStream<K, V1> mapValues(ValueMapper<V, V1> mapper);
/**
* Creates a new instance of KStream by transforming each element in this stream into zero or more elements in the new stream.
*
* @param mapper the instance of KeyValueMapper
* @param <K1> the key type of the new stream
* @param <V1> the value type of the new stream
* @return the instance of KStream
*/
<K1, V1> KStream<K1, V1> flatMap(KeyValueMapper<K, V, Iterable<KeyValue<K1, V1>>> mapper);
/**
* Creates a new stream by transforming each value in this stream into zero or more values in the new stream.
*
* @param processor the instance of Processor
* @param <V1> the value type of the new stream
* @return the instance of KStream
*/
<V1> KStream<K, V1> flatMapValues(ValueMapper<V, Iterable<V1>> processor);
/**
* Creates an array of streams from this stream. Each stream in the array corresponds to a predicate in
* supplied predicates in the same order. Predicates are evaluated in order. An element is streamed to
* a corresponding stream for the first predicate is evaluated true.
* An element will be dropped if none of the predicates evaluate true.
*
* @param predicates the ordered list of Predicate instances
* @return the instances of KStream that each contain those elements for which their Predicate evaluated to true.
*/
KStream<K, V>[] branch(Predicate<K, V>... predicates);
/**
* Sends key-value to a topic, also creates a new instance of KStream from the topic.
* This is equivalent to calling to(topic) and from(topic).
*
* @param topic the topic name
* @return the instance of KStream that consumes the given topic
*/
KStream<K, V> through(String topic);
/**
* Sends key-value to a topic, also creates a new instance of KStream from the topic.
* This is equivalent to calling to(topic) and from(topic).
*
* @param topic the topic name
* @param keySerializer key serializer used to send key-value pairs,
* if not specified the default key serializer defined in the configuration will be used
* @param valSerializer value serializer used to send key-value pairs,
* if not specified the default value serializer defined in the configuration will be used
* @param keyDeserializer key deserializer used to create the new KStream,
* if not specified the default key deserializer defined in the configuration will be used
* @param valDeserializer value deserializer used to create the new KStream,
* if not specified the default value deserializer defined in the configuration will be used
* @return the instance of KStream that consumes the given topic
*/
KStream<K, V> through(String topic, Serializer<K> keySerializer, Serializer<V> valSerializer, Deserializer<K> keyDeserializer, Deserializer<V> valDeserializer);
/**
* Sends key-value to a topic using default serializers specified in the config.
*
* @param topic the topic name
*/
void to(String topic);
/**
* Sends key-value to a topic.
*
* @param topic the topic name
* @param keySerializer key serializer used to send key-value pairs,
* if not specified the default serializer defined in the configs will be used
* @param valSerializer value serializer used to send key-value pairs,
* if not specified the default serializer defined in the configs will be used
*/
void to(String topic, Serializer<K> keySerializer, Serializer<V> valSerializer);
/**
* Applies a stateful transformation to all elements in this stream.
*
* @param transformerSupplier the class of valueTransformerSupplier
* @param stateStoreNames the names of the state store used by the processor
* @return the instance of KStream that contains transformed keys and values
*/
<K1, V1> KStream<K1, V1> transform(TransformerSupplier<K, V, KeyValue<K1, V1>> transformerSupplier, String... stateStoreNames);
/**
* Applies a stateful transformation to all values in this stream.
*
* @param valueTransformerSupplier the class of valueTransformerSupplier
* @param stateStoreNames the names of the state store used by the processor
* @return the instance of KStream that contains the keys and transformed values
*/
<R> KStream<K, R> transformValues(ValueTransformerSupplier<V, R> valueTransformerSupplier, String... stateStoreNames);
/**
* Processes all elements in this stream by applying a processor.
*
* @param processorSupplier the supplier of the Processor to use
* @param stateStoreNames the names of the state store used by the processor
*/
void process(ProcessorSupplier<K, V> processorSupplier, String... stateStoreNames);
/**
* Combines values of this stream with another KStream using Windowed Inner Join.
*
* @param otherStream the instance of KStream joined with this stream
* @param joiner ValueJoiner
* @param windows the specification of the join window
* @param keySerializer key serializer,
* if not specified the default serializer defined in the configs will be used
* @param thisValueSerializer value serializer for this stream,
* if not specified the default serializer defined in the configs will be used
* @param otherValueSerializer value serializer for other stream,
* if not specified the default serializer defined in the configs will be used
* @param keyDeserializer key deserializer,
* if not specified the default serializer defined in the configs will be used
* @param thisValueDeserializer value deserializer for this stream,
* if not specified the default serializer defined in the configs will be used
* @param otherValueDeserializer value deserializer for other stream,
* if not specified the default serializer defined in the configs will be used
* @param <V1> the value type of the other stream
* @param <R> the value type of the new stream
*/
<V1, R> KStream<K, R> join(
KStream<K, V1> otherStream,
ValueJoiner<V, V1, R> joiner,
JoinWindows windows,
Serializer<K> keySerializer,
Serializer<V> thisValueSerializer,
Serializer<V1> otherValueSerializer,
Deserializer<K> keyDeserializer,
Deserializer<V> thisValueDeserializer,
Deserializer<V1> otherValueDeserializer);
/**
* Combines values of this stream with another KStream using Windowed Outer Join.
*
* @param otherStream the instance of KStream joined with this stream
* @param joiner ValueJoiner
* @param windows the specification of the join window
* @param keySerializer key serializer,
* if not specified the default serializer defined in the configs will be used
* @param thisValueSerializer value serializer for this stream,
* if not specified the default serializer defined in the configs will be used
* @param otherValueSerializer value serializer for other stream,
* if not specified the default serializer defined in the configs will be used
* @param keyDeserializer key deserializer,
* if not specified the default serializer defined in the configs will be used
* @param thisValueDeserializer value deserializer for this stream,
* if not specified the default serializer defined in the configs will be used
* @param otherValueDeserializer value deserializer for other stream,
* if not specified the default serializer defined in the configs will be used
* @param <V1> the value type of the other stream
* @param <R> the value type of the new stream
*/
<V1, R> KStream<K, R> outerJoin(
KStream<K, V1> otherStream,
ValueJoiner<V, V1, R> joiner,
JoinWindows windows,
Serializer<K> keySerializer,
Serializer<V> thisValueSerializer,
Serializer<V1> otherValueSerializer,
Deserializer<K> keyDeserializer,
Deserializer<V> thisValueDeserializer,
Deserializer<V1> otherValueDeserializer);
/**
* Combines values of this stream with another KStream using Windowed Left Join.
*
* @param otherStream the instance of KStream joined with this stream
* @param joiner ValueJoiner
* @param windows the specification of the join window
* @param keySerializer key serializer,
* if not specified the default serializer defined in the configs will be used
* @param otherValueSerializer value serializer for other stream,
* if not specified the default serializer defined in the configs will be used
* @param keyDeserializer key deserializer,
* if not specified the default serializer defined in the configs will be used
* @param otherValueDeserializer value deserializer for other stream,
* if not specified the default serializer defined in the configs will be used
* @param <V1> the value type of the other stream
* @param <R> the value type of the new stream
*/
<V1, R> KStream<K, R> leftJoin(
KStream<K, V1> otherStream,
ValueJoiner<V, V1, R> joiner,
JoinWindows windows,
Serializer<K> keySerializer,
Serializer<V1> otherValueSerializer,
Deserializer<K> keyDeserializer,
Deserializer<V1> otherValueDeserializer);
/**
* Combines values of this stream with KTable using Left Join.
*
* @param ktable the instance of KTable joined with this stream
* @param joiner ValueJoiner
* @param <V1> the value type of the table
* @param <V2> the value type of the new stream
*/
<V1, V2> KStream<K, V2> leftJoin(KTable<K, V1> ktable, ValueJoiner<V, V1, V2> joiner);
/**
* Aggregate values of this stream by key on a window basis.
*
* @param aggregatorSupplier the class of aggregatorSupplier
* @param windows the specification of the aggregation window
* @param <T> the value type of the aggregated table
*/
<T, W extends Window> KTable<Windowed<K>, T> aggregateByKey(AggregatorSupplier<K, V, T> aggregatorSupplier,
Windows<W> windows,
Serializer<K> keySerializer,
Serializer<T> aggValueSerializer,
Deserializer<K> keyDeserializer,
Deserializer<T> aggValueDeserializer);
/**
* Sum extracted long integer values of this stream by key on a window basis.
*
* @param valueSelector the class of KeyValueToLongMapper to extract the long integer from value
* @param windows the specification of the aggregation window
*/
<W extends Window> KTable<Windowed<K>, Long> sumByKey(KeyValueToLongMapper<K, V> valueSelector,
Windows<W> windows,
Serializer<K> keySerializer,
Deserializer<K> keyDeserializer);
/**
* Count number of records of this stream by key on a window basis.
*
* @param windows the specification of the aggregation window
*/
<W extends Window> KTable<Windowed<K>, Long> countByKey(Windows<W> windows,
Serializer<K> keySerializer,
Deserializer<K> keyDeserializer);
}
| |
/**
* 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.activemq.artemis.rest.queue;
import javax.ws.rs.DefaultValue;
import javax.ws.rs.HeaderParam;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.UriBuilder;
import javax.ws.rs.core.UriInfo;
import java.net.URI;
import org.apache.activemq.artemis.api.core.ActiveMQException;
import org.apache.activemq.artemis.api.core.client.ClientConsumer;
import org.apache.activemq.artemis.api.core.client.ClientMessage;
import org.apache.activemq.artemis.api.core.client.ClientSession;
import org.apache.activemq.artemis.api.core.client.ClientSessionFactory;
import org.apache.activemq.artemis.rest.ActiveMQRestLogger;
import org.apache.activemq.artemis.rest.util.Constants;
import org.apache.activemq.artemis.rest.util.LinkStrategy;
import org.apache.activemq.artemis.jms.client.SelectorTranslator;
/**
* Auto-acknowleged consumer
*/
public class QueueConsumer
{
protected ClientSessionFactory factory;
protected ClientSession session;
protected ClientConsumer consumer;
protected String destination;
protected boolean closed;
protected String id;
protected long lastPing = System.currentTimeMillis();
protected DestinationServiceManager serviceManager;
protected boolean autoAck = true;
protected String selector;
/**
* token used to create consume-next links
*/
protected long previousIndex = -1;
protected ConsumedMessage lastConsumed;
public long getConsumeIndex()
{
if (lastConsumed == null) return -1;
return lastConsumed.getMessageID();
}
public DestinationServiceManager getServiceManager()
{
return serviceManager;
}
public void setServiceManager(DestinationServiceManager serviceManager)
{
this.serviceManager = serviceManager;
}
public long getLastPingTime()
{
return lastPing;
}
protected void ping(long offsetSecs)
{
lastPing = System.currentTimeMillis() + (offsetSecs * 1000);
}
public QueueConsumer(ClientSessionFactory factory, String destination, String id, DestinationServiceManager serviceManager, String selector) throws ActiveMQException
{
this.factory = factory;
this.destination = destination;
this.id = id;
this.serviceManager = serviceManager;
this.selector = selector;
createSession();
}
public String getId()
{
return id;
}
public boolean isClosed()
{
return closed;
}
public synchronized void shutdown()
{
if (closed) return;
closed = true;
lastConsumed = null;
previousIndex = -2;
try
{
consumer.close();
ActiveMQRestLogger.LOGGER.debug("Closed consumer: " + consumer);
}
catch (Exception e)
{
}
try
{
session.close();
ActiveMQRestLogger.LOGGER.debug("Closed session: " + session);
}
catch (Exception e)
{
}
session = null;
consumer = null;
}
@Path("consume-next{index}")
@POST
public synchronized Response poll(@HeaderParam(Constants.WAIT_HEADER) @DefaultValue("0") long wait,
@PathParam("index") long index,
@Context UriInfo info)
{
ActiveMQRestLogger.LOGGER.debug("Handling POST request for \"" + info.getRequestUri() + "\"");
if (closed)
{
UriBuilder builder = info.getBaseUriBuilder();
builder.path(info.getMatchedURIs().get(1))
.path("consume-next");
String uri = builder.build().toString();
// redirect to another consume-next
return Response.status(307).location(URI.create(uri)).build();
}
return checkIndexAndPoll(wait, info, info.getMatchedURIs().get(1), index);
}
protected Response checkIndexAndPoll(long wait, UriInfo info, String basePath, long index)
{
ping(wait);
if (lastConsumed == null && index > 0)
{
return Response.status(412).entity("You are using an old consume-next link and are out of sync with the JMS session on the server").type("text/plain").build();
}
if (lastConsumed != null)
{
if (index == previousIndex)
{
String token = Long.toString(lastConsumed.getMessageID());
return getMessageResponse(lastConsumed, info, basePath, token).build();
}
if (index != lastConsumed.getMessageID())
{
return Response.status(412).entity("You are using an old consume-next link and are out of sync with the JMS session on the server").type("text/plain").build();
}
}
try
{
return pollWithIndex(wait, info, basePath, index);
}
finally
{
ping(0); // ping again as we don't want wait time included in timeout.
}
}
protected Response pollWithIndex(long wait, UriInfo info, String basePath, long index)
{
try
{
ClientMessage message = receive(wait);
if (message == null)
{
Response.ResponseBuilder builder = Response.status(503).entity("Timed out waiting for message receive.").type("text/plain");
setPollTimeoutLinks(info, basePath, builder, Long.toString(index));
return builder.build();
}
previousIndex = index;
lastConsumed = ConsumedMessage.createConsumedMessage(message);
String token = Long.toString(lastConsumed.getMessageID());
Response response = getMessageResponse(lastConsumed, info, basePath, token).build();
if (autoAck) message.acknowledge();
return response;
}
catch (Exception e)
{
throw new RuntimeException(e);
}
}
protected void createSession() throws ActiveMQException
{
session = factory.createSession(true, true, 0);
ActiveMQRestLogger.LOGGER.debug("Created session: " + session);
if (selector == null)
{
consumer = session.createConsumer(destination);
}
else
{
consumer = session.createConsumer(destination, SelectorTranslator.convertToActiveMQFilterString(selector));
}
ActiveMQRestLogger.LOGGER.debug("Created consumer: " + consumer);
session.start();
}
protected ClientMessage receiveFromConsumer(long timeoutSecs) throws Exception
{
ClientMessage m = null;
if (timeoutSecs <= 0)
{
m = consumer.receive(1);
}
else
{
m = consumer.receive(timeoutSecs * 1000);
}
ActiveMQRestLogger.LOGGER.debug("Returning message " + m + " from consumer: " + consumer);
return m;
}
protected ClientMessage receive(long timeoutSecs) throws Exception
{
return receiveFromConsumer(timeoutSecs);
}
protected void setPollTimeoutLinks(UriInfo info, String basePath, Response.ResponseBuilder builder, String index)
{
setSessionLink(builder, info, basePath);
setConsumeNextLink(serviceManager.getLinkStrategy(), builder, info, basePath, index);
}
protected Response.ResponseBuilder getMessageResponse(ConsumedMessage msg, UriInfo info, String basePath, String index)
{
Response.ResponseBuilder responseBuilder = Response.ok();
setMessageResponseLinks(info, basePath, responseBuilder, index);
msg.build(responseBuilder);
return responseBuilder;
}
protected void setMessageResponseLinks(UriInfo info, String basePath, Response.ResponseBuilder responseBuilder, String index)
{
setConsumeNextLink(serviceManager.getLinkStrategy(), responseBuilder, info, basePath, index);
setSessionLink(responseBuilder, info, basePath);
}
public static void setConsumeNextLink(LinkStrategy linkStrategy, Response.ResponseBuilder response, UriInfo info, String basePath, String index)
{
if (index == null) throw new IllegalArgumentException("index cannot be null");
UriBuilder builder = info.getBaseUriBuilder();
builder.path(basePath)
.path("consume-next" + index);
String uri = builder.build().toString();
linkStrategy.setLinkHeader(response, "consume-next", "consume-next", uri, MediaType.APPLICATION_FORM_URLENCODED);
}
public void setSessionLink(Response.ResponseBuilder response, UriInfo info, String basePath)
{
UriBuilder builder = info.getBaseUriBuilder();
builder.path(basePath);
String uri = builder.build().toString();
serviceManager.getLinkStrategy().setLinkHeader(response, "consumer", "consumer", uri, MediaType.APPLICATION_XML);
}
}
| |
/**
Copyright 2008 University of Rochester
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 edu.ur.tag.table.simple;
import java.util.Collection;
import java.util.LinkedList;
import javax.servlet.jsp.JspException;
import javax.servlet.jsp.JspWriter;
import javax.servlet.jsp.PageContext;
import javax.servlet.jsp.tagext.JspFragment;
import edu.ur.tag.TagUtil;
import edu.ur.tag.base.CommonBaseHtmlTag;
public class TableBodySectionTag extends CommonBaseHtmlTag {
/** collection to create the table around */
@SuppressWarnings("unchecked")
private Collection collection;
/** text alignment in cells */
private String align;
/** character to align text on */
private String aChar;
/** offset to the first character */
private String charOff;
/** vertical alignment */
private String valign;
/** variable to assign the value to */
private String var;
/** row index */
private int rowIndex = 0;
/** Variable to set the row status index value */
private String rowStatus;
/** class to give odd rows */
private String oddRowClass;
/** class to give even rows */
private String evenRowClass;
/** current row class */
private String currentRowClassVar;
@SuppressWarnings("unchecked")
public void doTag() throws JspException {
if (collection == null) {
collection = new LinkedList();
}
String currentClass = "";
JspFragment body = getJspBody();
PageContext pageContext = (PageContext) getJspContext();
JspWriter o = pageContext.getOut();
try {
o.print("<tbody ");
o.print(getAttributes());
o.print(">");
for (Object object : collection) {
if (rowIndex % 2 == 0) {
currentClass = evenRowClass;
} else {
currentClass = oddRowClass;
}
getJspContext().setAttribute(var, object);
getJspContext().setAttribute(currentRowClassVar, currentClass);
if( rowStatus != null )
{
getJspContext().setAttribute(rowStatus, rowIndex);
}
if( body != null)
{
body.invoke(null);
}
rowIndex += 1;
}
o.print("</tbody>");
} catch (Exception e) {
throw new JspException(e);
}
}
public String getAlign() {
return align;
}
public void setAlign(String align) {
this.align = align;
}
public String getAChar() {
return aChar;
}
public void setAChar(String char1) {
aChar = char1;
}
public String getCharOff() {
return charOff;
}
public void setCharOff(String charOff) {
this.charOff = charOff;
}
public String getValign() {
return valign;
}
public void setValign(String valign) {
this.valign = valign;
}
@SuppressWarnings("unchecked")
public Collection getCollection() {
return collection;
}
@SuppressWarnings("unchecked")
public void setCollection(Collection collection) {
this.collection = collection;
}
public StringBuffer getAttributes() {
StringBuffer sb = new StringBuffer();
if (!TagUtil.isEmpty(align)) {
sb.append("align=\"" + align + "\" ");
}
if (!TagUtil.isEmpty(aChar)) {
sb.append("char=\"" + aChar + "\" ");
}
if (!TagUtil.isEmpty(charOff)) {
sb.append("charoff=\"" + charOff + "\" ");
}
if (!TagUtil.isEmpty(valign)) {
sb.append("valign=\"" + valign + "\" ");
}
sb.append(super.getAttributes());
return sb;
}
public String getVar() {
return var;
}
public void setVar(String var) {
this.var = var;
}
public int getRowIndex() {
return rowIndex;
}
public void setRowIndex(int rowIndex) {
this.rowIndex = rowIndex;
}
public String getOddRowClass() {
return oddRowClass;
}
public void setOddRowClass(String oddRowClass) {
this.oddRowClass = oddRowClass;
}
public String getEvenRowClass() {
return evenRowClass;
}
public void setEvenRowClass(String evenRowClass) {
this.evenRowClass = evenRowClass;
}
public String getCurrentRowClassVar() {
return currentRowClassVar;
}
public void setCurrentRowClassVar(String rowClass) {
this.currentRowClassVar = rowClass;
}
public String getRowStatus() {
return rowStatus;
}
public void setRowStatus(String rowStatus) {
this.rowStatus = rowStatus;
}
}
| |
/**
* Copyright (C) 2010 hprange <hprange@gmail.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.webobjects.foundation;
import static org.hamcrest.CoreMatchers.instanceOf;
import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.CoreMatchers.notNullValue;
import static org.junit.Assert.assertThat;
import static org.junit.Assert.fail;
import static org.mockito.Mockito.mock;
import java.lang.reflect.Constructor;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import org.aopalliance.intercept.MethodInterceptor;
import org.aopalliance.intercept.MethodInvocation;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.internal.util.MockUtil;
import org.mockito.runners.MockitoJUnitRunner;
import com.google.inject.AbstractModule;
import com.google.inject.Module;
import com.google.inject.matcher.Matchers;
import com.google.inject.name.Names;
import com.webobjects.appserver.WOContext;
import com.webobjects.appserver.WORequest;
import com.woinject.AbstractInjectableTestCase;
import com.woinject.WOInjectException;
import com.woinject.stubs.StubApplication;
import com.woinject.stubs.StubComponent;
import com.woinject.stubs.StubDirectAction;
import com.woinject.stubs.StubEnterpriseObject;
import com.woinject.stubs.StubObject;
import com.woinject.stubs.StubSession;
/**
* @author <a href="mailto:hprange@gmail.com.br">Henrique Prange</a>
*/
@RunWith(MockitoJUnitRunner.class)
public class TestInstantiationInterceptor extends AbstractInjectableTestCase {
private static class StubModule extends AbstractModule {
@Override
protected void configure() {
bind(String.class).annotatedWith(Names.named("test")).toInstance("expectedText");
bind(StubObjectForBinding.class).toInstance(mock(StubObjectForBinding.class));
}
}
static class StubObjectForBinding {
public StubObjectForBinding() {
}
}
@Mock
private WOContext mockContext;
@Mock
private WORequest mockRequest;
private Object[][] parameters;
@Rule
public final ExpectedException thrown = ExpectedException.none();
@Test
public void doNotThrowExceptionIfNotRequired() throws Exception {
try {
InstantiationInterceptor.instantiateObject(StubComponent.class, new Class<?>[] { WOContext.class }, new Object[] { mockRequest }, false, true);
InstantiationInterceptor.instantiateObject(StubObject.class, new Class<?>[] { String.class, String.class }, null, false, true);
InstantiationInterceptor.instantiateObject(StubObject.class, null, null, false, true);
} catch (Exception exception) {
exception.printStackTrace();
fail("Should not throw an exception");
}
}
@Test
public void injectOrdinaryObjectMembersAfterConstructionWithReflection() throws Exception {
Object result = InstantiationInterceptor.instantiateObject(StubObject.class, new Class<?>[] { String.class, String.class }, new Object[] { "teste", "teste2" }, true, false);
assertThat(result, notNullValue());
assertThat(result, instanceOf(StubObject.class));
assertThat(result.toString(), is("expectedText"));
}
@Test
public void injectOrdinaryObjectMembersAfterConstructionWithReflectionUsingConstructor() throws Exception {
Constructor<StubObject> constructor = StubObject.class.getConstructor(new Class<?>[] { String.class, String.class });
Object result = InstantiationInterceptor.instantiateObjectWithConstructor(constructor, StubObject.class, new Object[] { "teste", "teste2" }, true, false);
assertThat(result, notNullValue());
assertThat(result, instanceOf(StubObject.class));
assertThat(result.toString(), is("expectedText"));
}
@Test
public void injectSpecialObjectsWithConstructorUsingGuice() throws Exception {
for (Object[] parameter : parameters) {
@SuppressWarnings("unchecked")
Object result = InstantiationInterceptor.instantiateObjectWithConstructor((Constructor<Object>) parameter[3], (Class<Object>) parameter[0], (Object[]) parameter[2], true, false);
assertThat(result.toString(), is("expectedText"));
}
}
@Test
public void injectSpecialObjectsWithGuice() throws Exception {
for (Object[] parameter : parameters) {
Object result = InstantiationInterceptor.instantiateObject((Class<?>) parameter[0], (Class<?>[]) parameter[1], (Object[]) parameter[2], true, false);
assertThat(result.toString(), is("expectedText"));
}
}
@Test
public void instantiateObjectWithContructorUsingReflectionIfInjectorIsNull() throws Exception {
application.setReturnNullInjector(true);
Constructor<StubEnterpriseObject> constructor = StubEnterpriseObject.class.getConstructor();
StubEnterpriseObject result = InstantiationInterceptor.instantiateObjectWithConstructor(constructor, StubEnterpriseObject.class, null, true, false);
assertThat(result, notNullValue());
assertThat(result, instanceOf(StubEnterpriseObject.class));
}
@Test
public void instantiateObjectWithReflectionIfApplicationIsNull() throws Exception {
StubApplication.setApplication(null);
StubEnterpriseObject result = InstantiationInterceptor.instantiateObject(StubEnterpriseObject.class, null, null, true, false);
assertThat(result, notNullValue());
assertThat(result, instanceOf(StubEnterpriseObject.class));
}
@Test
public void instantiateObjectWithReflectionIfInjectorIsNull() throws Exception {
application.setReturnNullInjector(true);
StubEnterpriseObject result = InstantiationInterceptor.instantiateObject(StubEnterpriseObject.class, null, null, true, false);
assertThat(result, notNullValue());
assertThat(result, instanceOf(StubEnterpriseObject.class));
}
@Test
public void instantiateSpecialObjectsWithConstructorUsingGuice() throws Exception {
for (Object[] parameter : parameters) {
@SuppressWarnings("unchecked")
Object result = InstantiationInterceptor.instantiateObjectWithConstructor((Constructor<Object>) parameter[3], (Class<Object>) parameter[0], (Object[]) parameter[2], true, false);
assertThat(result, notNullValue());
assertThat(result, instanceOf((Class<?>) parameter[0]));
}
}
@Test
public void instantiateSpecialObjectsWithGuice() throws Exception {
for (Object[] parameter : parameters) {
Object result = InstantiationInterceptor.instantiateObject((Class<?>) parameter[0], (Class<?>[]) parameter[1], (Object[]) parameter[2], true, false);
assertThat(result, notNullValue());
assertThat(result, instanceOf((Class<?>) parameter[0]));
}
}
@Override
@Before
public void setup() throws Exception {
application = new StubApplication() {
@Override
protected Module[] modules() {
List<Module> modules = new ArrayList<Module>(Arrays.asList(super.modules()));
modules.add(new StubModule());
return modules.toArray(new Module[modules.size()]);
}
};
parameters = new Object[][] { { StubEnterpriseObject.class, null, null, StubEnterpriseObject.class.getConstructor() }, { StubComponent.class, new Class<?>[] { WOContext.class }, new Object[] { mockContext }, StubComponent.class.getConstructor(new Class<?>[] { WOContext.class }) }, { StubSession.class, null, null, StubSession.class.getConstructor() }, { StubDirectAction.class, new Class<?>[] { WORequest.class }, new Object[] { mockRequest }, StubDirectAction.class.getConstructor(new Class<?>[] { WORequest.class }) } };
}
@Test
public void throwExceptionIfGuiceUnableToCreateInstance() throws Exception {
thrown.expect(WOInjectException.class);
thrown.expectMessage(is("The instantiation of com.woinject.stubs.StubComponent class has failed."));
WORequest illegalArgument = mockRequest;
InstantiationInterceptor.instantiateObject(StubComponent.class, new Class<?>[] { WOContext.class }, new Object[] { illegalArgument }, true, false);
}
@Test
public void throwExceptionIfIllegalArguments() throws Exception {
thrown.expect(WOInjectException.class);
thrown.expectMessage(is("The instantiation of com.woinject.stubs.StubObject class has failed."));
InstantiationInterceptor.instantiateObject(StubObject.class, new Class<?>[] { String.class, String.class }, null, true, false);
}
@Test
public void throwExceptionIfNoSuitableConstructorFound() throws Exception {
thrown.expect(WOInjectException.class);
thrown.expectMessage(is("The instantiation of com.woinject.stubs.StubObject class has failed."));
InstantiationInterceptor.instantiateObject(StubObject.class, null, null, true, false);
}
@Test
public void useSpecialKeyToAvoidBindingConflictsWithParentInjector() throws Exception {
StubObjectForBinding result = InstantiationInterceptor.instantiateObject(StubObjectForBinding.class, null, null, false, false);
assertThat(new MockUtil().isMock(result), is(false));
}
}
| |
/*
* 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.sling.engine.impl;
import java.io.IOException;
import java.io.PrintWriter;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpServletResponseWrapper;
import org.apache.sling.api.SlingHttpServletResponse;
import org.apache.sling.api.adapter.AdapterManager;
import org.apache.sling.engine.impl.request.RequestData;
import org.apache.sling.engine.servlets.ErrorHandler;
/**
* The <code>SlingHttpServletResponseImpl</code> TODO
*/
public class SlingHttpServletResponseImpl extends HttpServletResponseWrapper implements SlingHttpServletResponse {
// the content type header name
private static final String HEADER_CONTENT_TYPE = "Content-Type";
// the content length header name
private static final String HEADER_CONTENT_LENGTH = "Content-Length";
/** format for RFC 1123 date string -- "Sun, 06 Nov 1994 08:49:37 GMT" */
private final static SimpleDateFormat RFC1123_FORMAT = new SimpleDateFormat(
"EEE, dd MMM yyyy HH:mm:ss z", Locale.US);
/**
* The counter for request gone through this filter. As this is the first
* request level filter hit, this counter should actually count each request
* which at least enters the request level component filter processing.
* <p>
* This counter is reset to zero, when this component is activated. That is,
* each time this component is restarted (system start, bundle start,
* reconfiguration), the request counter restarts at zero.
*/
private static int requestCounter = 0;
// TODO: more content related headers, namely Content-Language should
// probably be supported
// the request counter
private int requestId;
// the system time in ms when the request entered the system, this is
// the time this instance was created
private long requestStart;
// the system time in ms when the request exited the system, this is
// the time of the call to the requestEnd() method
private long requestEnd;
// the output stream wrapper providing the transferred byte count
private LoggerResponseOutputStream out;
// the print writer wrapper providing the transferred character count
private LoggerResponseWriter writer;
// the caches status
private int status = SC_OK;
// the cookies set during the request, indexed by cookie name
private Map<String, Cookie> cookies;
// the headers set during the request, indexed by lower-case header
// name, value is string for single-valued and list for multi-valued
// headers
private Map<String, Object> headers;
private final RequestData requestData;
public SlingHttpServletResponseImpl(RequestData requestData,
HttpServletResponse response) {
super(response);
this.requestData = requestData;
this.requestId = requestCounter++;
this.requestStart = System.currentTimeMillis();
}
/**
* Called to indicate the request processing has ended. This method
* currently sets the request end time returned by {@link #getRequestEnd()}
* and which is used to calculate the request duration.
*/
public void requestEnd() {
this.requestEnd = System.currentTimeMillis();
}
protected final RequestData getRequestData() {
return requestData;
}
//---------- Adaptable interface
public <AdapterType> AdapterType adaptTo(Class<AdapterType> type) {
AdapterManager adapterManager = getRequestData().getAdapterManager();
if (adapterManager != null) {
return adapterManager.getAdapter(this, type);
}
// no adapter manager, nothing to adapt to
return null;
}
//---------- SlingHttpServletResponse interface
@Override
public void flushBuffer() throws IOException {
getRequestData().getContentData().flushBuffer();
}
@Override
public int getBufferSize() {
return getRequestData().getContentData().getBufferSize();
}
@Override
public Locale getLocale() {
// TODO Should use our Locale Resolver and not let the component set the locale, right ??
return getResponse().getLocale();
}
@Override
public ServletOutputStream getOutputStream() throws IOException {
if (this.out == null) {
ServletOutputStream sos = getRequestData().getBufferProvider().getOutputStream();
this.out = new LoggerResponseOutputStream(sos);
}
return this.out;
}
@Override
public PrintWriter getWriter() throws IOException {
if (this.writer == null) {
PrintWriter pw = getRequestData().getBufferProvider().getWriter();
this.writer = new LoggerResponseWriter(pw);
}
return this.writer;
}
@Override
public boolean isCommitted() {
// TODO: integrate with our output catcher
return getResponse().isCommitted();
}
@Override
public void reset() {
// TODO: integrate with our output catcher
getResponse().reset();
}
@Override
public void resetBuffer() {
getRequestData().getContentData().resetBuffer();
}
@Override
public void setBufferSize(int size) {
getRequestData().getContentData().setBufferSize(size);
}
// ---------- Redirection support through PathResolver --------------------
@Override
public String encodeURL(String url) {
// make the path absolute
url = makeAbsolutePath(url);
// resolve the url to as if it would be a resource path
url = map(url);
// have the servlet container to further encodings
return super.encodeURL(url);
}
@Override
public String encodeRedirectURL(String url) {
// make the path absolute
url = makeAbsolutePath(url);
// resolve the url to as if it would be a resource path
url = map(url);
// have the servlet container to further encodings
return super.encodeRedirectURL(url);
}
@Override
@Deprecated
public String encodeUrl(String url) {
return encodeURL(url);
}
@Override
@Deprecated
public String encodeRedirectUrl(String url) {
return encodeRedirectURL(url);
}
// ---------- Error handling through Sling Error Resolver -----------------
@Override
public void sendRedirect(String location) throws IOException {
super.sendRedirect(location);
// replicate the status code of call to base class
this.status = SC_MOVED_TEMPORARILY;
}
@Override
public void sendError(int status) throws IOException {
sendError(status, null);
}
@Override
public void sendError(int status, String message) throws IOException {
checkCommitted();
this.status = status;
ErrorHandler eh = getRequestData().getSlingMainServlet().getErrorHandler();
eh.handleError(status, message, requestData.getSlingRequest(), this);
}
@Override
public void setStatus(int status, String message) {
checkCommitted();
this.status = status;
super.setStatus(status, message);
}
@Override
public void setStatus(int status) {
checkCommitted();
this.status = status;
super.setStatus(status);
}
public void addCookie(Cookie cookie) {
// register the cookie for later use
if (this.cookies == null) {
this.cookies = new HashMap<String, Cookie>();
}
this.cookies.put(cookie.getName(), cookie);
super.addCookie(cookie);
}
public void addDateHeader(String name, long date) {
this.registerHeader(name, toDateString(date), true);
super.addDateHeader(name, date);
}
public void addHeader(String name, String value) {
this.registerHeader(name, value, true);
super.addHeader(name, value);
}
public void addIntHeader(String name, int value) {
this.registerHeader(name, String.valueOf(value), true);
super.addIntHeader(name, value);
}
public void setContentLength(int len) {
this.registerHeader(HEADER_CONTENT_LENGTH, String.valueOf(len), false);
super.setContentLength(len);
}
public void setContentType(String type) {
// SLING-726 No handling required since this seems to be correct
this.registerHeader(HEADER_CONTENT_TYPE, type, false);
super.setContentType(type);
}
@Override
public void setCharacterEncoding(String charset) {
// SLING-726 Ignore call if getWriter() has been called
if (writer == null) {
super.setCharacterEncoding(charset);
}
}
public void setDateHeader(String name, long date) {
this.registerHeader(name, toDateString(date), false);
super.setDateHeader(name, date);
}
public void setHeader(String name, String value) {
this.registerHeader(name, value, false);
super.setHeader(name, value);
}
public void setIntHeader(String name, int value) {
this.registerHeader(name, String.valueOf(value), false);
this.setHeader(name, String.valueOf(value));
}
public void setLocale(Locale loc) {
// TODO: Might want to register the Content-Language header
super.setLocale(loc);
}
// ---------- Retrieving response information ------------------------------
public int getRequestId() {
return this.requestId;
}
public long getRequestStart() {
return this.requestStart;
}
public long getRequestEnd() {
return this.requestEnd;
}
public long getRequestDuration() {
return this.requestEnd - this.requestStart;
}
public int getStatus() {
return this.status;
}
public int getCount() {
if (this.out != null) {
return this.out.getCount();
} else if (this.writer != null) {
return this.writer.getCount();
}
// otherwise return zero
return 0;
}
public Cookie getCookie(String name) {
return (this.cookies != null) ? (Cookie) this.cookies.get(name) : null;
}
public String getHeaders(String name) {
// normalize header name to lower case to support case-insensitive
// headers
name = name.toLowerCase();
Object header = (this.headers != null) ? this.headers.get(name) : null;
if (header == null) {
return null;
} else if (header instanceof String) {
return (String) header;
} else {
StringBuffer headerBuf = new StringBuffer();
for (Iterator<?> hi = ((List<?>) header).iterator(); hi.hasNext();) {
if (headerBuf.length() > 0) {
headerBuf.append(",");
}
headerBuf.append(hi.next());
}
return headerBuf.toString();
}
}
// ---------- Internal helper ---------------------------------------------
private void checkCommitted() {
if (isCommitted()) {
throw new IllegalStateException(
"Response has already been committed");
}
}
private String makeAbsolutePath(String path) {
if (path.startsWith("/")) {
return path;
}
String base = getRequestData().getContentData().getResource().getPath();
int lastSlash = base.lastIndexOf('/');
if (lastSlash >= 0) {
path = base.substring(0, lastSlash+1) + path;
} else {
path = "/" + path;
}
return path;
}
private String map(String url) {
return getRequestData().getResourceResolver().map(url);
}
/**
* Stores the name header-value pair in the header map. The name is
* converted to lower-case before using it as an index in the map.
*
* @param name The name of the header to register
* @param value The value of the header to register
* @param add If <code>true</code> the header value is added to the list
* of potentially existing header values. Otherwise the new value
* replaces any existing values.
*/
private void registerHeader(String name, String value, boolean add) {
// ensure the headers map
if (this.headers == null) {
this.headers = new HashMap<String, Object>();
}
// normalize header name to lower case to support case-insensitive
// headers
name = name.toLowerCase();
// retrieve the current contents if adding, otherwise assume no current
Object current = add ? this.headers.get(name) : null;
if (current == null) {
// set the single value (forced if !add)
this.headers.put(name, value);
} else if (current instanceof String) {
// create list if a single value is already set
List<String> list = new ArrayList<String>();
list.add((String) current);
list.add(value);
this.headers.put(name, list);
} else {
// append to the list of more than one already set
((List<Object>) current).add(value);
}
}
/**
* Converts the time value given as the number of milliseconds since January
* 1, 1970 to a date and time string compliant with RFC 1123 date
* specification. The resulting string is compliant with section 3.3.1, Full
* Date, of <a href="http://www.faqs.org/rfcs/rfc2616.html">RFC 2616</a>
* and may thus be used as the value of date header such as
* <code>Date</code>.
*
* @param date The date value to convert to a string
* @return The string representation of the date and time value.
*/
public static String toDateString(long date) {
synchronized (RFC1123_FORMAT) {
return RFC1123_FORMAT.format(new Date(date));
}
}
//---------- byte/character counting output channels ----------------------
// byte transfer counting ServletOutputStream
private static class LoggerResponseOutputStream extends ServletOutputStream {
private ServletOutputStream delegatee;
private int count;
LoggerResponseOutputStream(ServletOutputStream delegatee) {
this.delegatee = delegatee;
}
public int getCount() {
return this.count;
}
public void write(int b) throws IOException {
this.delegatee.write(b);
this.count++;
}
public void write(byte[] b) throws IOException {
this.delegatee.write(b);
this.count += b.length;
}
public void write(byte[] b, int off, int len) throws IOException {
this.delegatee.write(b, off, len);
this.count += len;
}
public void flush() throws IOException {
this.delegatee.flush();
}
public void close() throws IOException {
this.delegatee.close();
}
}
// character transfer counting PrintWriter
private static class LoggerResponseWriter extends PrintWriter {
private static final int LINE_SEPARATOR_LENGTH = System.getProperty(
"line.separator").length();
private int count;
LoggerResponseWriter(PrintWriter delegatee) {
super(delegatee);
}
public int getCount() {
return this.count;
}
public void write(int c) {
super.write(c);
this.count++;
}
public void write(char[] buf, int off, int len) {
super.write(buf, off, len);
this.count += len;
}
public void write(String s, int off, int len) {
super.write(s, off, len);
this.count += len;
}
public void println() {
super.println();
this.count += LINE_SEPARATOR_LENGTH;
}
}
}
| |
/*
* Copyright 2007 ZXing authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.zxing.datamatrix.decoder;
import com.google.zxing.FormatException;
/**
* The Version object encapsulates attributes about a particular
* size Data Matrix Code.
*
* @author bbrown@google.com (Brian Brown)
*/
public final class Version {
private static final Version[] VERSIONS = buildVersions();
private final int versionNumber;
private final int symbolSizeRows;
private final int symbolSizeColumns;
private final int dataRegionSizeRows;
private final int dataRegionSizeColumns;
private final ECBlocks ecBlocks;
private final int totalCodewords;
private Version(int versionNumber,
int symbolSizeRows,
int symbolSizeColumns,
int dataRegionSizeRows,
int dataRegionSizeColumns,
ECBlocks ecBlocks) {
this.versionNumber = versionNumber;
this.symbolSizeRows = symbolSizeRows;
this.symbolSizeColumns = symbolSizeColumns;
this.dataRegionSizeRows = dataRegionSizeRows;
this.dataRegionSizeColumns = dataRegionSizeColumns;
this.ecBlocks = ecBlocks;
// Calculate the total number of codewords
int total = 0;
int ecCodewords = ecBlocks.getECCodewords();
ECB[] ecbArray = ecBlocks.getECBlocks();
for (ECB ecBlock : ecbArray) {
total += ecBlock.getCount() * (ecBlock.getDataCodewords() + ecCodewords);
}
this.totalCodewords = total;
}
/**
* <p>Deduces version information from Data Matrix dimensions.</p>
*
* @param numRows Number of rows in modules
* @param numColumns Number of columns in modules
* @return Version for a Data Matrix Code of those dimensions
* @throws FormatException if dimensions do correspond to a valid Data Matrix size
*/
public static Version getVersionForDimensions(int numRows, int numColumns) throws FormatException {
if ((numRows & 0x01) != 0 || (numColumns & 0x01) != 0) {
throw FormatException.getFormatInstance();
}
for (Version version : VERSIONS) {
if (version.symbolSizeRows == numRows && version.symbolSizeColumns == numColumns) {
return version;
}
}
throw FormatException.getFormatInstance();
}
/**
* See ISO 16022:2006 5.5.1 Table 7
*/
private static Version[] buildVersions() {
return new Version[]{
new Version(1, 10, 10, 8, 8,
new ECBlocks(5, new ECB(1, 3))),
new Version(2, 12, 12, 10, 10,
new ECBlocks(7, new ECB(1, 5))),
new Version(3, 14, 14, 12, 12,
new ECBlocks(10, new ECB(1, 8))),
new Version(4, 16, 16, 14, 14,
new ECBlocks(12, new ECB(1, 12))),
new Version(5, 18, 18, 16, 16,
new ECBlocks(14, new ECB(1, 18))),
new Version(6, 20, 20, 18, 18,
new ECBlocks(18, new ECB(1, 22))),
new Version(7, 22, 22, 20, 20,
new ECBlocks(20, new ECB(1, 30))),
new Version(8, 24, 24, 22, 22,
new ECBlocks(24, new ECB(1, 36))),
new Version(9, 26, 26, 24, 24,
new ECBlocks(28, new ECB(1, 44))),
new Version(10, 32, 32, 14, 14,
new ECBlocks(36, new ECB(1, 62))),
new Version(11, 36, 36, 16, 16,
new ECBlocks(42, new ECB(1, 86))),
new Version(12, 40, 40, 18, 18,
new ECBlocks(48, new ECB(1, 114))),
new Version(13, 44, 44, 20, 20,
new ECBlocks(56, new ECB(1, 144))),
new Version(14, 48, 48, 22, 22,
new ECBlocks(68, new ECB(1, 174))),
new Version(15, 52, 52, 24, 24,
new ECBlocks(42, new ECB(2, 102))),
new Version(16, 64, 64, 14, 14,
new ECBlocks(56, new ECB(2, 140))),
new Version(17, 72, 72, 16, 16,
new ECBlocks(36, new ECB(4, 92))),
new Version(18, 80, 80, 18, 18,
new ECBlocks(48, new ECB(4, 114))),
new Version(19, 88, 88, 20, 20,
new ECBlocks(56, new ECB(4, 144))),
new Version(20, 96, 96, 22, 22,
new ECBlocks(68, new ECB(4, 174))),
new Version(21, 104, 104, 24, 24,
new ECBlocks(56, new ECB(6, 136))),
new Version(22, 120, 120, 18, 18,
new ECBlocks(68, new ECB(6, 175))),
new Version(23, 132, 132, 20, 20,
new ECBlocks(62, new ECB(8, 163))),
new Version(24, 144, 144, 22, 22,
new ECBlocks(62, new ECB(8, 156), new ECB(2, 155))),
new Version(25, 8, 18, 6, 16,
new ECBlocks(7, new ECB(1, 5))),
new Version(26, 8, 32, 6, 14,
new ECBlocks(11, new ECB(1, 10))),
new Version(27, 12, 26, 10, 24,
new ECBlocks(14, new ECB(1, 16))),
new Version(28, 12, 36, 10, 16,
new ECBlocks(18, new ECB(1, 22))),
new Version(29, 16, 36, 14, 16,
new ECBlocks(24, new ECB(1, 32))),
new Version(30, 16, 48, 14, 22,
new ECBlocks(28, new ECB(1, 49)))
};
}
public int getVersionNumber() {
return versionNumber;
}
public int getSymbolSizeRows() {
return symbolSizeRows;
}
public int getSymbolSizeColumns() {
return symbolSizeColumns;
}
public int getDataRegionSizeRows() {
return dataRegionSizeRows;
}
public int getDataRegionSizeColumns() {
return dataRegionSizeColumns;
}
public int getTotalCodewords() {
return totalCodewords;
}
ECBlocks getECBlocks() {
return ecBlocks;
}
@Override
public String toString() {
return String.valueOf(versionNumber);
}
/**
* <p>Encapsulates a set of error-correction blocks in one symbol version. Most versions will
* use blocks of differing sizes within one version, so, this encapsulates the parameters for
* each set of blocks. It also holds the number of error-correction codewords per block since it
* will be the same across all blocks within one version.</p>
*/
static final class ECBlocks {
private final int ecCodewords;
private final ECB[] ecBlocks;
private ECBlocks(int ecCodewords, ECB ecBlocks) {
this.ecCodewords = ecCodewords;
this.ecBlocks = new ECB[]{ecBlocks};
}
private ECBlocks(int ecCodewords, ECB ecBlocks1, ECB ecBlocks2) {
this.ecCodewords = ecCodewords;
this.ecBlocks = new ECB[]{ecBlocks1, ecBlocks2};
}
int getECCodewords() {
return ecCodewords;
}
ECB[] getECBlocks() {
return ecBlocks;
}
}
/**
* <p>Encapsualtes the parameters for one error-correction block in one symbol version.
* This includes the number of data codewords, and the number of times a block with these
* parameters is used consecutively in the Data Matrix code version's format.</p>
*/
static final class ECB {
private final int count;
private final int dataCodewords;
private ECB(int count, int dataCodewords) {
this.count = count;
this.dataCodewords = dataCodewords;
}
int getCount() {
return count;
}
int getDataCodewords() {
return dataCodewords;
}
}
}
| |
package uk.co.flax.biosolr.pdbe.fasta;
import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.rmi.RemoteException;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import uk.ac.ebi.webservices.axis1.stubs.fasta.InputParameters;
import uk.ac.ebi.webservices.axis1.stubs.fasta.JDispatcherService_PortType;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class FastaJob implements Runnable {
private static final Logger LOG = LoggerFactory.getLogger(FastaJob.class);
private JDispatcherService_PortType fasta;
private String email;
private InputParameters params;
private FastaJobResults results;
// job id created in run()
private String jobId;
// exception caught during run(), if any, and the run status
private IOException exception;
private String status;
private boolean interrupted;
// regexp patterns
private Pattern pattern1 = Pattern.compile("^PDB:(.*?_.*?)\\s+(.+?)\\s+([0-9.e-]+?)$|^PRE_PDB:(\\w{4} Entity)\\s+(.+?)\\s+([0-9.e-]+?)$");
private Pattern pattern2 = Pattern.compile("^>>PDB:(.*?_.*?)\\s+.*?$|^>>PRE_PDB:(\\w{4} Entity).*?$");
private Pattern pattern3 = Pattern.compile("^Smith-Waterman score:.*?\\;(.*?)\\% .*? overlap \\((.*?)\\)$");
private Pattern pattern4 = Pattern.compile("^EMBOS[S ] (\\s*.*?)$");
private Pattern pattern5 = Pattern.compile("^PDB:.*? (\\s*.*?)$|^PRE_PD.*? (\\s*.*?)$");
public IOException getException() {
return exception;
}
public String getStatus() {
return status;
}
public FastaJobResults getResults() throws IOException {
if (results == null) {
byte[] result = getRawResults();
InputStream in = new ByteArrayInputStream(result);
results = parseResults(new BufferedReader(new InputStreamReader(in)));
}
return results;
}
public byte[] getRawResults() throws RemoteException {
String id = fasta.getResultTypes(jobId)[0].getIdentifier();
return fasta.getResult(jobId, id, null);
}
public boolean isInterrupted() {
return interrupted;
}
public boolean resultsOk() {
return exception == null && !interrupted && status.equals(FastaStatus.DONE);
}
public FastaJob(JDispatcherService_PortType fasta, String email, InputParameters params) {
this.fasta = fasta;
this.email = email;
this.params = params;
jobId = null;
results = null;
exception = null;
status = null;
interrupted = false;
}
public String getEmail() {
return email;
}
public InputParameters getParams() {
return params;
}
private int firstGroup(Matcher m) {
for (int n = 1; n <= m.groupCount(); ++n) {
if (m.group(n) != null) {
return n;
}
}
return 0;
}
public void run() {
try {
LOG.debug("FastaJob.run");
jobId = fasta.run(email, "", params);
LOG.debug("jobId=" + jobId);
do {
Thread.sleep(200);
status = fasta.getStatus(jobId);
LOG.debug("status=" + status);
} while (status.equals(FastaStatus.RUNNING));
if (!status.equals(FastaStatus.DONE)) {
LOG.error("Error with job: " + jobId + " (" + status + ")");
}
} catch (InterruptedException e) {
interrupted = true;
} catch (IOException e) {
exception = e;
}
}
// create an Alignment from a matching line
private PDb.Alignment parseAlignment(Matcher matcher) {
int n = firstGroup(matcher);
String pdbIdChain = matcher.group(n);
if (pdbIdChain.contains("Entity")) {
pdbIdChain = pdbIdChain.replaceFirst(" ", "_");
}
String[] s = pdbIdChain.split("_");
double eValue = new Double(matcher.group(n + 2));
return new PDb.Alignment(new PDb.Id(s[0]), s[1], eValue);
}
private FastaJobResults parseResults(BufferedReader reader) throws IOException {
results = new FastaJobResults();
String line = "";
while (line != null) {
Matcher matcher1 = pattern1.matcher(line);
Matcher matcher2 = pattern2.matcher(line);
if (matcher1.find()) {
PDb.Alignment alignment = parseAlignment(matcher1);
results.addAlignment(alignment);
line = reader.readLine();
} else if (matcher2.find()) {
int n = firstGroup(matcher2);
String pdbIdChain = matcher2.group(n);
if (pdbIdChain.contains("Entity")) {
pdbIdChain = pdbIdChain.replaceFirst(" ", "_");
}
String[] bits = pdbIdChain.split("_");
PDb.Alignment a = results.getAlignment(bits[0], bits[1]);
if (a == null) {
throw new RuntimeException("Alignment not yet seen: " + pdbIdChain);
}
// sometimes an alignment appears twice in the results - need to ignore all
// but the first (but still need to consume lines)
boolean complete = a.isComplete();
while ((line = reader.readLine()) != null) {
Matcher m2 = pattern2.matcher(line);
Matcher m3 = pattern3.matcher(line);
Matcher m4 = pattern4.matcher(line);
Matcher m5 = pattern5.matcher(line);
if (m3.find()) {
double identity = new Double(m3.group(1));
String overLap = m3.group(2);
String[] o = overLap.split(":");
String[] oIn = o[0].split("-");
String[] oOut = o[1].split("-");
if (! complete) {
a.setPercentIdentity(identity);
try {
a.setQueryOverlapStart(Integer.valueOf(oIn[0]));
a.setQueryOverlapEnd(Integer.valueOf(oIn[1]));
a.setDbOverlapStart(Integer.valueOf(oOut[0]));
a.setDbOverlapEnd(Integer.valueOf(oOut[1]));
} catch (NumberFormatException e) {
throw new IOException("Error parsing line: " + line);
}
}
} else if (m2.find()) {
break;
} else if (m4.find()) {
if (! complete) {
a.addQuerySequence(m4.group(1));
}
} else if (m5.find()) {
int n4 = firstGroup(m5);
if (! complete) {
a.addReturnSequence(m5.group(n4));
}
}
}
} else {
line = reader.readLine();
}
}
return results;
}
}
| |
/*
* 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
*
* 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.
*/
package com.google.cloud.datafusion.v1;
import com.google.api.core.ApiFuture;
import com.google.api.core.ApiFutures;
import com.google.api.core.BetaApi;
import com.google.api.gax.core.BackgroundResource;
import com.google.api.gax.longrunning.OperationFuture;
import com.google.api.gax.paging.AbstractFixedSizeCollection;
import com.google.api.gax.paging.AbstractPage;
import com.google.api.gax.paging.AbstractPagedListResponse;
import com.google.api.gax.rpc.OperationCallable;
import com.google.api.gax.rpc.PageContext;
import com.google.api.gax.rpc.UnaryCallable;
import com.google.cloud.datafusion.v1.stub.DataFusionStub;
import com.google.cloud.datafusion.v1.stub.DataFusionStubSettings;
import com.google.common.util.concurrent.MoreExecutors;
import com.google.longrunning.Operation;
import com.google.longrunning.OperationsClient;
import com.google.protobuf.Empty;
import com.google.protobuf.FieldMask;
import java.io.IOException;
import java.util.List;
import java.util.concurrent.TimeUnit;
import javax.annotation.Generated;
// AUTO-GENERATED DOCUMENTATION AND CLASS.
/**
* Service Description: Service for creating and managing Data Fusion instances. Data Fusion enables
* ETL developers to build code-free, data integration pipelines via a point-and-click UI.
*
* <p>This class provides the ability to make remote calls to the backing service through method
* calls that map to API methods. Sample code to get started:
*
* <pre>{@code
* try (DataFusionClient dataFusionClient = DataFusionClient.create()) {
* GetInstanceRequest request =
* GetInstanceRequest.newBuilder()
* .setName(InstanceName.of("[PROJECT]", "[LOCATION]", "[INSTANCE]").toString())
* .build();
* Instance response = dataFusionClient.getInstance(request);
* }
* }</pre>
*
* <p>Note: close() needs to be called on the DataFusionClient object to clean up resources such as
* threads. In the example above, try-with-resources is used, which automatically calls close().
*
* <p>The surface of this class includes several types of Java methods for each of the API's
* methods:
*
* <ol>
* <li>A "flattened" method. With this type of method, the fields of the request type have been
* converted into function parameters. It may be the case that not all fields are available as
* parameters, and not every API method will have a flattened method entry point.
* <li>A "request object" method. This type of method only takes one parameter, a request object,
* which must be constructed before the call. Not every API method will have a request object
* method.
* <li>A "callable" method. This type of method takes no parameters and returns an immutable API
* callable object, which can be used to initiate calls to the service.
* </ol>
*
* <p>See the individual methods for example code.
*
* <p>Many parameters require resource names to be formatted in a particular way. To assist with
* these names, this class includes a format method for each type of name, and additionally a parse
* method to extract the individual identifiers contained within names that are returned.
*
* <p>This class can be customized by passing in a custom instance of DataFusionSettings to
* create(). For example:
*
* <p>To customize credentials:
*
* <pre>{@code
* DataFusionSettings dataFusionSettings =
* DataFusionSettings.newBuilder()
* .setCredentialsProvider(FixedCredentialsProvider.create(myCredentials))
* .build();
* DataFusionClient dataFusionClient = DataFusionClient.create(dataFusionSettings);
* }</pre>
*
* <p>To customize the endpoint:
*
* <pre>{@code
* DataFusionSettings dataFusionSettings =
* DataFusionSettings.newBuilder().setEndpoint(myEndpoint).build();
* DataFusionClient dataFusionClient = DataFusionClient.create(dataFusionSettings);
* }</pre>
*
* <p>Please refer to the GitHub repository's samples for more quickstart code snippets.
*/
@Generated("by gapic-generator-java")
public class DataFusionClient implements BackgroundResource {
private final DataFusionSettings settings;
private final DataFusionStub stub;
private final OperationsClient operationsClient;
/** Constructs an instance of DataFusionClient with default settings. */
public static final DataFusionClient create() throws IOException {
return create(DataFusionSettings.newBuilder().build());
}
/**
* Constructs an instance of DataFusionClient, using the given settings. The channels are created
* based on the settings passed in, or defaults for any settings that are not set.
*/
public static final DataFusionClient create(DataFusionSettings settings) throws IOException {
return new DataFusionClient(settings);
}
/**
* Constructs an instance of DataFusionClient, using the given stub for making calls. This is for
* advanced usage - prefer using create(DataFusionSettings).
*/
@BetaApi("A restructuring of stub classes is planned, so this may break in the future")
public static final DataFusionClient create(DataFusionStub stub) {
return new DataFusionClient(stub);
}
/**
* Constructs an instance of DataFusionClient, using the given settings. This is protected so that
* it is easy to make a subclass, but otherwise, the static factory methods should be preferred.
*/
protected DataFusionClient(DataFusionSettings settings) throws IOException {
this.settings = settings;
this.stub = ((DataFusionStubSettings) settings.getStubSettings()).createStub();
this.operationsClient = OperationsClient.create(this.stub.getOperationsStub());
}
@BetaApi("A restructuring of stub classes is planned, so this may break in the future")
protected DataFusionClient(DataFusionStub stub) {
this.settings = null;
this.stub = stub;
this.operationsClient = OperationsClient.create(this.stub.getOperationsStub());
}
public final DataFusionSettings getSettings() {
return settings;
}
@BetaApi("A restructuring of stub classes is planned, so this may break in the future")
public DataFusionStub getStub() {
return stub;
}
/**
* Returns the OperationsClient that can be used to query the status of a long-running operation
* returned by another API method call.
*/
public final OperationsClient getOperationsClient() {
return operationsClient;
}
// AUTO-GENERATED DOCUMENTATION AND METHOD.
/**
* Lists possible versions for Data Fusion instances in the specified project and location.
*
* <p>Sample code:
*
* <pre>{@code
* try (DataFusionClient dataFusionClient = DataFusionClient.create()) {
* LocationName parent = LocationName.of("[PROJECT]", "[LOCATION]");
* for (Version element : dataFusionClient.listAvailableVersions(parent).iterateAll()) {
* // doThingsWith(element);
* }
* }
* }</pre>
*
* @param parent Required. The project and location for which to retrieve instance information in
* the format projects/{project}/locations/{location}.
* @throws com.google.api.gax.rpc.ApiException if the remote call fails
*/
public final ListAvailableVersionsPagedResponse listAvailableVersions(LocationName parent) {
ListAvailableVersionsRequest request =
ListAvailableVersionsRequest.newBuilder()
.setParent(parent == null ? null : parent.toString())
.build();
return listAvailableVersions(request);
}
// AUTO-GENERATED DOCUMENTATION AND METHOD.
/**
* Lists possible versions for Data Fusion instances in the specified project and location.
*
* <p>Sample code:
*
* <pre>{@code
* try (DataFusionClient dataFusionClient = DataFusionClient.create()) {
* String parent = LocationName.of("[PROJECT]", "[LOCATION]").toString();
* for (Version element : dataFusionClient.listAvailableVersions(parent).iterateAll()) {
* // doThingsWith(element);
* }
* }
* }</pre>
*
* @param parent Required. The project and location for which to retrieve instance information in
* the format projects/{project}/locations/{location}.
* @throws com.google.api.gax.rpc.ApiException if the remote call fails
*/
public final ListAvailableVersionsPagedResponse listAvailableVersions(String parent) {
ListAvailableVersionsRequest request =
ListAvailableVersionsRequest.newBuilder().setParent(parent).build();
return listAvailableVersions(request);
}
// AUTO-GENERATED DOCUMENTATION AND METHOD.
/**
* Lists possible versions for Data Fusion instances in the specified project and location.
*
* <p>Sample code:
*
* <pre>{@code
* try (DataFusionClient dataFusionClient = DataFusionClient.create()) {
* ListAvailableVersionsRequest request =
* ListAvailableVersionsRequest.newBuilder()
* .setParent(LocationName.of("[PROJECT]", "[LOCATION]").toString())
* .setPageSize(883849137)
* .setPageToken("pageToken873572522")
* .setLatestPatchOnly(true)
* .build();
* for (Version element : dataFusionClient.listAvailableVersions(request).iterateAll()) {
* // doThingsWith(element);
* }
* }
* }</pre>
*
* @param request The request object containing all of the parameters for the API call.
* @throws com.google.api.gax.rpc.ApiException if the remote call fails
*/
public final ListAvailableVersionsPagedResponse listAvailableVersions(
ListAvailableVersionsRequest request) {
return listAvailableVersionsPagedCallable().call(request);
}
// AUTO-GENERATED DOCUMENTATION AND METHOD.
/**
* Lists possible versions for Data Fusion instances in the specified project and location.
*
* <p>Sample code:
*
* <pre>{@code
* try (DataFusionClient dataFusionClient = DataFusionClient.create()) {
* ListAvailableVersionsRequest request =
* ListAvailableVersionsRequest.newBuilder()
* .setParent(LocationName.of("[PROJECT]", "[LOCATION]").toString())
* .setPageSize(883849137)
* .setPageToken("pageToken873572522")
* .setLatestPatchOnly(true)
* .build();
* ApiFuture<Version> future =
* dataFusionClient.listAvailableVersionsPagedCallable().futureCall(request);
* // Do something.
* for (Version element : future.get().iterateAll()) {
* // doThingsWith(element);
* }
* }
* }</pre>
*/
public final UnaryCallable<ListAvailableVersionsRequest, ListAvailableVersionsPagedResponse>
listAvailableVersionsPagedCallable() {
return stub.listAvailableVersionsPagedCallable();
}
// AUTO-GENERATED DOCUMENTATION AND METHOD.
/**
* Lists possible versions for Data Fusion instances in the specified project and location.
*
* <p>Sample code:
*
* <pre>{@code
* try (DataFusionClient dataFusionClient = DataFusionClient.create()) {
* ListAvailableVersionsRequest request =
* ListAvailableVersionsRequest.newBuilder()
* .setParent(LocationName.of("[PROJECT]", "[LOCATION]").toString())
* .setPageSize(883849137)
* .setPageToken("pageToken873572522")
* .setLatestPatchOnly(true)
* .build();
* while (true) {
* ListAvailableVersionsResponse response =
* dataFusionClient.listAvailableVersionsCallable().call(request);
* for (Version element : response.getResponsesList()) {
* // doThingsWith(element);
* }
* String nextPageToken = response.getNextPageToken();
* if (!Strings.isNullOrEmpty(nextPageToken)) {
* request = request.toBuilder().setPageToken(nextPageToken).build();
* } else {
* break;
* }
* }
* }
* }</pre>
*/
public final UnaryCallable<ListAvailableVersionsRequest, ListAvailableVersionsResponse>
listAvailableVersionsCallable() {
return stub.listAvailableVersionsCallable();
}
// AUTO-GENERATED DOCUMENTATION AND METHOD.
/**
* Lists Data Fusion instances in the specified project and location.
*
* <p>Sample code:
*
* <pre>{@code
* try (DataFusionClient dataFusionClient = DataFusionClient.create()) {
* ListInstancesRequest request =
* ListInstancesRequest.newBuilder()
* .setParent(LocationName.of("[PROJECT]", "[LOCATION]").toString())
* .setPageSize(883849137)
* .setPageToken("pageToken873572522")
* .setFilter("filter-1274492040")
* .setOrderBy("orderBy-1207110587")
* .build();
* for (Instance element : dataFusionClient.listInstances(request).iterateAll()) {
* // doThingsWith(element);
* }
* }
* }</pre>
*
* @param request The request object containing all of the parameters for the API call.
* @throws com.google.api.gax.rpc.ApiException if the remote call fails
*/
public final ListInstancesPagedResponse listInstances(ListInstancesRequest request) {
return listInstancesPagedCallable().call(request);
}
// AUTO-GENERATED DOCUMENTATION AND METHOD.
/**
* Lists Data Fusion instances in the specified project and location.
*
* <p>Sample code:
*
* <pre>{@code
* try (DataFusionClient dataFusionClient = DataFusionClient.create()) {
* ListInstancesRequest request =
* ListInstancesRequest.newBuilder()
* .setParent(LocationName.of("[PROJECT]", "[LOCATION]").toString())
* .setPageSize(883849137)
* .setPageToken("pageToken873572522")
* .setFilter("filter-1274492040")
* .setOrderBy("orderBy-1207110587")
* .build();
* ApiFuture<Instance> future =
* dataFusionClient.listInstancesPagedCallable().futureCall(request);
* // Do something.
* for (Instance element : future.get().iterateAll()) {
* // doThingsWith(element);
* }
* }
* }</pre>
*/
public final UnaryCallable<ListInstancesRequest, ListInstancesPagedResponse>
listInstancesPagedCallable() {
return stub.listInstancesPagedCallable();
}
// AUTO-GENERATED DOCUMENTATION AND METHOD.
/**
* Lists Data Fusion instances in the specified project and location.
*
* <p>Sample code:
*
* <pre>{@code
* try (DataFusionClient dataFusionClient = DataFusionClient.create()) {
* ListInstancesRequest request =
* ListInstancesRequest.newBuilder()
* .setParent(LocationName.of("[PROJECT]", "[LOCATION]").toString())
* .setPageSize(883849137)
* .setPageToken("pageToken873572522")
* .setFilter("filter-1274492040")
* .setOrderBy("orderBy-1207110587")
* .build();
* while (true) {
* ListInstancesResponse response = dataFusionClient.listInstancesCallable().call(request);
* for (Instance element : response.getResponsesList()) {
* // doThingsWith(element);
* }
* String nextPageToken = response.getNextPageToken();
* if (!Strings.isNullOrEmpty(nextPageToken)) {
* request = request.toBuilder().setPageToken(nextPageToken).build();
* } else {
* break;
* }
* }
* }
* }</pre>
*/
public final UnaryCallable<ListInstancesRequest, ListInstancesResponse> listInstancesCallable() {
return stub.listInstancesCallable();
}
// AUTO-GENERATED DOCUMENTATION AND METHOD.
/**
* Gets details of a single Data Fusion instance.
*
* <p>Sample code:
*
* <pre>{@code
* try (DataFusionClient dataFusionClient = DataFusionClient.create()) {
* GetInstanceRequest request =
* GetInstanceRequest.newBuilder()
* .setName(InstanceName.of("[PROJECT]", "[LOCATION]", "[INSTANCE]").toString())
* .build();
* Instance response = dataFusionClient.getInstance(request);
* }
* }</pre>
*
* @param request The request object containing all of the parameters for the API call.
* @throws com.google.api.gax.rpc.ApiException if the remote call fails
*/
public final Instance getInstance(GetInstanceRequest request) {
return getInstanceCallable().call(request);
}
// AUTO-GENERATED DOCUMENTATION AND METHOD.
/**
* Gets details of a single Data Fusion instance.
*
* <p>Sample code:
*
* <pre>{@code
* try (DataFusionClient dataFusionClient = DataFusionClient.create()) {
* GetInstanceRequest request =
* GetInstanceRequest.newBuilder()
* .setName(InstanceName.of("[PROJECT]", "[LOCATION]", "[INSTANCE]").toString())
* .build();
* ApiFuture<Instance> future = dataFusionClient.getInstanceCallable().futureCall(request);
* // Do something.
* Instance response = future.get();
* }
* }</pre>
*/
public final UnaryCallable<GetInstanceRequest, Instance> getInstanceCallable() {
return stub.getInstanceCallable();
}
// AUTO-GENERATED DOCUMENTATION AND METHOD.
/**
* Creates a new Data Fusion instance in the specified project and location.
*
* <p>Sample code:
*
* <pre>{@code
* try (DataFusionClient dataFusionClient = DataFusionClient.create()) {
* LocationName parent = LocationName.of("[PROJECT]", "[LOCATION]");
* Instance instance = Instance.newBuilder().build();
* String instanceId = "instanceId902024336";
* Instance response = dataFusionClient.createInstanceAsync(parent, instance, instanceId).get();
* }
* }</pre>
*
* @param parent Required. The instance's project and location in the format
* projects/{project}/locations/{location}.
* @param instance An instance resource.
* @param instanceId Required. The name of the instance to create.
* @throws com.google.api.gax.rpc.ApiException if the remote call fails
*/
public final OperationFuture<Instance, OperationMetadata> createInstanceAsync(
LocationName parent, Instance instance, String instanceId) {
CreateInstanceRequest request =
CreateInstanceRequest.newBuilder()
.setParent(parent == null ? null : parent.toString())
.setInstance(instance)
.setInstanceId(instanceId)
.build();
return createInstanceAsync(request);
}
// AUTO-GENERATED DOCUMENTATION AND METHOD.
/**
* Creates a new Data Fusion instance in the specified project and location.
*
* <p>Sample code:
*
* <pre>{@code
* try (DataFusionClient dataFusionClient = DataFusionClient.create()) {
* String parent = LocationName.of("[PROJECT]", "[LOCATION]").toString();
* Instance instance = Instance.newBuilder().build();
* String instanceId = "instanceId902024336";
* Instance response = dataFusionClient.createInstanceAsync(parent, instance, instanceId).get();
* }
* }</pre>
*
* @param parent Required. The instance's project and location in the format
* projects/{project}/locations/{location}.
* @param instance An instance resource.
* @param instanceId Required. The name of the instance to create.
* @throws com.google.api.gax.rpc.ApiException if the remote call fails
*/
public final OperationFuture<Instance, OperationMetadata> createInstanceAsync(
String parent, Instance instance, String instanceId) {
CreateInstanceRequest request =
CreateInstanceRequest.newBuilder()
.setParent(parent)
.setInstance(instance)
.setInstanceId(instanceId)
.build();
return createInstanceAsync(request);
}
// AUTO-GENERATED DOCUMENTATION AND METHOD.
/**
* Creates a new Data Fusion instance in the specified project and location.
*
* <p>Sample code:
*
* <pre>{@code
* try (DataFusionClient dataFusionClient = DataFusionClient.create()) {
* CreateInstanceRequest request =
* CreateInstanceRequest.newBuilder()
* .setParent(LocationName.of("[PROJECT]", "[LOCATION]").toString())
* .setInstanceId("instanceId902024336")
* .setInstance(Instance.newBuilder().build())
* .build();
* Instance response = dataFusionClient.createInstanceAsync(request).get();
* }
* }</pre>
*
* @param request The request object containing all of the parameters for the API call.
* @throws com.google.api.gax.rpc.ApiException if the remote call fails
*/
public final OperationFuture<Instance, OperationMetadata> createInstanceAsync(
CreateInstanceRequest request) {
return createInstanceOperationCallable().futureCall(request);
}
// AUTO-GENERATED DOCUMENTATION AND METHOD.
/**
* Creates a new Data Fusion instance in the specified project and location.
*
* <p>Sample code:
*
* <pre>{@code
* try (DataFusionClient dataFusionClient = DataFusionClient.create()) {
* CreateInstanceRequest request =
* CreateInstanceRequest.newBuilder()
* .setParent(LocationName.of("[PROJECT]", "[LOCATION]").toString())
* .setInstanceId("instanceId902024336")
* .setInstance(Instance.newBuilder().build())
* .build();
* OperationFuture<Instance, OperationMetadata> future =
* dataFusionClient.createInstanceOperationCallable().futureCall(request);
* // Do something.
* Instance response = future.get();
* }
* }</pre>
*/
public final OperationCallable<CreateInstanceRequest, Instance, OperationMetadata>
createInstanceOperationCallable() {
return stub.createInstanceOperationCallable();
}
// AUTO-GENERATED DOCUMENTATION AND METHOD.
/**
* Creates a new Data Fusion instance in the specified project and location.
*
* <p>Sample code:
*
* <pre>{@code
* try (DataFusionClient dataFusionClient = DataFusionClient.create()) {
* CreateInstanceRequest request =
* CreateInstanceRequest.newBuilder()
* .setParent(LocationName.of("[PROJECT]", "[LOCATION]").toString())
* .setInstanceId("instanceId902024336")
* .setInstance(Instance.newBuilder().build())
* .build();
* ApiFuture<Operation> future = dataFusionClient.createInstanceCallable().futureCall(request);
* // Do something.
* Operation response = future.get();
* }
* }</pre>
*/
public final UnaryCallable<CreateInstanceRequest, Operation> createInstanceCallable() {
return stub.createInstanceCallable();
}
// AUTO-GENERATED DOCUMENTATION AND METHOD.
/**
* Deletes a single Date Fusion instance.
*
* <p>Sample code:
*
* <pre>{@code
* try (DataFusionClient dataFusionClient = DataFusionClient.create()) {
* InstanceName name = InstanceName.of("[PROJECT]", "[LOCATION]", "[INSTANCE]");
* dataFusionClient.deleteInstanceAsync(name).get();
* }
* }</pre>
*
* @param name Required. The instance resource name in the format
* projects/{project}/locations/{location}/instances/{instance}
* @throws com.google.api.gax.rpc.ApiException if the remote call fails
*/
public final OperationFuture<Empty, OperationMetadata> deleteInstanceAsync(InstanceName name) {
DeleteInstanceRequest request =
DeleteInstanceRequest.newBuilder().setName(name == null ? null : name.toString()).build();
return deleteInstanceAsync(request);
}
// AUTO-GENERATED DOCUMENTATION AND METHOD.
/**
* Deletes a single Date Fusion instance.
*
* <p>Sample code:
*
* <pre>{@code
* try (DataFusionClient dataFusionClient = DataFusionClient.create()) {
* String name = InstanceName.of("[PROJECT]", "[LOCATION]", "[INSTANCE]").toString();
* dataFusionClient.deleteInstanceAsync(name).get();
* }
* }</pre>
*
* @param name Required. The instance resource name in the format
* projects/{project}/locations/{location}/instances/{instance}
* @throws com.google.api.gax.rpc.ApiException if the remote call fails
*/
public final OperationFuture<Empty, OperationMetadata> deleteInstanceAsync(String name) {
DeleteInstanceRequest request = DeleteInstanceRequest.newBuilder().setName(name).build();
return deleteInstanceAsync(request);
}
// AUTO-GENERATED DOCUMENTATION AND METHOD.
/**
* Deletes a single Date Fusion instance.
*
* <p>Sample code:
*
* <pre>{@code
* try (DataFusionClient dataFusionClient = DataFusionClient.create()) {
* DeleteInstanceRequest request =
* DeleteInstanceRequest.newBuilder()
* .setName(InstanceName.of("[PROJECT]", "[LOCATION]", "[INSTANCE]").toString())
* .build();
* dataFusionClient.deleteInstanceAsync(request).get();
* }
* }</pre>
*
* @param request The request object containing all of the parameters for the API call.
* @throws com.google.api.gax.rpc.ApiException if the remote call fails
*/
public final OperationFuture<Empty, OperationMetadata> deleteInstanceAsync(
DeleteInstanceRequest request) {
return deleteInstanceOperationCallable().futureCall(request);
}
// AUTO-GENERATED DOCUMENTATION AND METHOD.
/**
* Deletes a single Date Fusion instance.
*
* <p>Sample code:
*
* <pre>{@code
* try (DataFusionClient dataFusionClient = DataFusionClient.create()) {
* DeleteInstanceRequest request =
* DeleteInstanceRequest.newBuilder()
* .setName(InstanceName.of("[PROJECT]", "[LOCATION]", "[INSTANCE]").toString())
* .build();
* OperationFuture<Empty, OperationMetadata> future =
* dataFusionClient.deleteInstanceOperationCallable().futureCall(request);
* // Do something.
* future.get();
* }
* }</pre>
*/
public final OperationCallable<DeleteInstanceRequest, Empty, OperationMetadata>
deleteInstanceOperationCallable() {
return stub.deleteInstanceOperationCallable();
}
// AUTO-GENERATED DOCUMENTATION AND METHOD.
/**
* Deletes a single Date Fusion instance.
*
* <p>Sample code:
*
* <pre>{@code
* try (DataFusionClient dataFusionClient = DataFusionClient.create()) {
* DeleteInstanceRequest request =
* DeleteInstanceRequest.newBuilder()
* .setName(InstanceName.of("[PROJECT]", "[LOCATION]", "[INSTANCE]").toString())
* .build();
* ApiFuture<Operation> future = dataFusionClient.deleteInstanceCallable().futureCall(request);
* // Do something.
* future.get();
* }
* }</pre>
*/
public final UnaryCallable<DeleteInstanceRequest, Operation> deleteInstanceCallable() {
return stub.deleteInstanceCallable();
}
// AUTO-GENERATED DOCUMENTATION AND METHOD.
/**
* Updates a single Data Fusion instance.
*
* <p>Sample code:
*
* <pre>{@code
* try (DataFusionClient dataFusionClient = DataFusionClient.create()) {
* Instance instance = Instance.newBuilder().build();
* FieldMask updateMask = FieldMask.newBuilder().build();
* Instance response = dataFusionClient.updateInstanceAsync(instance, updateMask).get();
* }
* }</pre>
*
* @param instance Required. The instance resource that replaces the resource on the server.
* Currently, Data Fusion only allows replacing labels, options, and stack driver settings.
* All other fields will be ignored.
* @param updateMask Field mask is used to specify the fields that the update will overwrite in an
* instance resource. The fields specified in the update_mask are relative to the resource,
* not the full request. A field will be overwritten if it is in the mask. If the user does
* not provide a mask, all the supported fields (labels, options, and version currently) will
* be overwritten.
* @throws com.google.api.gax.rpc.ApiException if the remote call fails
*/
public final OperationFuture<Instance, OperationMetadata> updateInstanceAsync(
Instance instance, FieldMask updateMask) {
UpdateInstanceRequest request =
UpdateInstanceRequest.newBuilder().setInstance(instance).setUpdateMask(updateMask).build();
return updateInstanceAsync(request);
}
// AUTO-GENERATED DOCUMENTATION AND METHOD.
/**
* Updates a single Data Fusion instance.
*
* <p>Sample code:
*
* <pre>{@code
* try (DataFusionClient dataFusionClient = DataFusionClient.create()) {
* UpdateInstanceRequest request =
* UpdateInstanceRequest.newBuilder()
* .setInstance(Instance.newBuilder().build())
* .setUpdateMask(FieldMask.newBuilder().build())
* .build();
* Instance response = dataFusionClient.updateInstanceAsync(request).get();
* }
* }</pre>
*
* @param request The request object containing all of the parameters for the API call.
* @throws com.google.api.gax.rpc.ApiException if the remote call fails
*/
public final OperationFuture<Instance, OperationMetadata> updateInstanceAsync(
UpdateInstanceRequest request) {
return updateInstanceOperationCallable().futureCall(request);
}
// AUTO-GENERATED DOCUMENTATION AND METHOD.
/**
* Updates a single Data Fusion instance.
*
* <p>Sample code:
*
* <pre>{@code
* try (DataFusionClient dataFusionClient = DataFusionClient.create()) {
* UpdateInstanceRequest request =
* UpdateInstanceRequest.newBuilder()
* .setInstance(Instance.newBuilder().build())
* .setUpdateMask(FieldMask.newBuilder().build())
* .build();
* OperationFuture<Instance, OperationMetadata> future =
* dataFusionClient.updateInstanceOperationCallable().futureCall(request);
* // Do something.
* Instance response = future.get();
* }
* }</pre>
*/
public final OperationCallable<UpdateInstanceRequest, Instance, OperationMetadata>
updateInstanceOperationCallable() {
return stub.updateInstanceOperationCallable();
}
// AUTO-GENERATED DOCUMENTATION AND METHOD.
/**
* Updates a single Data Fusion instance.
*
* <p>Sample code:
*
* <pre>{@code
* try (DataFusionClient dataFusionClient = DataFusionClient.create()) {
* UpdateInstanceRequest request =
* UpdateInstanceRequest.newBuilder()
* .setInstance(Instance.newBuilder().build())
* .setUpdateMask(FieldMask.newBuilder().build())
* .build();
* ApiFuture<Operation> future = dataFusionClient.updateInstanceCallable().futureCall(request);
* // Do something.
* Operation response = future.get();
* }
* }</pre>
*/
public final UnaryCallable<UpdateInstanceRequest, Operation> updateInstanceCallable() {
return stub.updateInstanceCallable();
}
// AUTO-GENERATED DOCUMENTATION AND METHOD.
/**
* Restart a single Data Fusion instance. At the end of an operation instance is fully restarted.
*
* <p>Sample code:
*
* <pre>{@code
* try (DataFusionClient dataFusionClient = DataFusionClient.create()) {
* RestartInstanceRequest request =
* RestartInstanceRequest.newBuilder()
* .setName(InstanceName.of("[PROJECT]", "[LOCATION]", "[INSTANCE]").toString())
* .build();
* Instance response = dataFusionClient.restartInstanceAsync(request).get();
* }
* }</pre>
*
* @param request The request object containing all of the parameters for the API call.
* @throws com.google.api.gax.rpc.ApiException if the remote call fails
*/
public final OperationFuture<Instance, OperationMetadata> restartInstanceAsync(
RestartInstanceRequest request) {
return restartInstanceOperationCallable().futureCall(request);
}
// AUTO-GENERATED DOCUMENTATION AND METHOD.
/**
* Restart a single Data Fusion instance. At the end of an operation instance is fully restarted.
*
* <p>Sample code:
*
* <pre>{@code
* try (DataFusionClient dataFusionClient = DataFusionClient.create()) {
* RestartInstanceRequest request =
* RestartInstanceRequest.newBuilder()
* .setName(InstanceName.of("[PROJECT]", "[LOCATION]", "[INSTANCE]").toString())
* .build();
* OperationFuture<Instance, OperationMetadata> future =
* dataFusionClient.restartInstanceOperationCallable().futureCall(request);
* // Do something.
* Instance response = future.get();
* }
* }</pre>
*/
public final OperationCallable<RestartInstanceRequest, Instance, OperationMetadata>
restartInstanceOperationCallable() {
return stub.restartInstanceOperationCallable();
}
// AUTO-GENERATED DOCUMENTATION AND METHOD.
/**
* Restart a single Data Fusion instance. At the end of an operation instance is fully restarted.
*
* <p>Sample code:
*
* <pre>{@code
* try (DataFusionClient dataFusionClient = DataFusionClient.create()) {
* RestartInstanceRequest request =
* RestartInstanceRequest.newBuilder()
* .setName(InstanceName.of("[PROJECT]", "[LOCATION]", "[INSTANCE]").toString())
* .build();
* ApiFuture<Operation> future = dataFusionClient.restartInstanceCallable().futureCall(request);
* // Do something.
* Operation response = future.get();
* }
* }</pre>
*/
public final UnaryCallable<RestartInstanceRequest, Operation> restartInstanceCallable() {
return stub.restartInstanceCallable();
}
@Override
public final void close() {
stub.close();
}
@Override
public void shutdown() {
stub.shutdown();
}
@Override
public boolean isShutdown() {
return stub.isShutdown();
}
@Override
public boolean isTerminated() {
return stub.isTerminated();
}
@Override
public void shutdownNow() {
stub.shutdownNow();
}
@Override
public boolean awaitTermination(long duration, TimeUnit unit) throws InterruptedException {
return stub.awaitTermination(duration, unit);
}
public static class ListAvailableVersionsPagedResponse
extends AbstractPagedListResponse<
ListAvailableVersionsRequest,
ListAvailableVersionsResponse,
Version,
ListAvailableVersionsPage,
ListAvailableVersionsFixedSizeCollection> {
public static ApiFuture<ListAvailableVersionsPagedResponse> createAsync(
PageContext<ListAvailableVersionsRequest, ListAvailableVersionsResponse, Version> context,
ApiFuture<ListAvailableVersionsResponse> futureResponse) {
ApiFuture<ListAvailableVersionsPage> futurePage =
ListAvailableVersionsPage.createEmptyPage().createPageAsync(context, futureResponse);
return ApiFutures.transform(
futurePage,
input -> new ListAvailableVersionsPagedResponse(input),
MoreExecutors.directExecutor());
}
private ListAvailableVersionsPagedResponse(ListAvailableVersionsPage page) {
super(page, ListAvailableVersionsFixedSizeCollection.createEmptyCollection());
}
}
public static class ListAvailableVersionsPage
extends AbstractPage<
ListAvailableVersionsRequest,
ListAvailableVersionsResponse,
Version,
ListAvailableVersionsPage> {
private ListAvailableVersionsPage(
PageContext<ListAvailableVersionsRequest, ListAvailableVersionsResponse, Version> context,
ListAvailableVersionsResponse response) {
super(context, response);
}
private static ListAvailableVersionsPage createEmptyPage() {
return new ListAvailableVersionsPage(null, null);
}
@Override
protected ListAvailableVersionsPage createPage(
PageContext<ListAvailableVersionsRequest, ListAvailableVersionsResponse, Version> context,
ListAvailableVersionsResponse response) {
return new ListAvailableVersionsPage(context, response);
}
@Override
public ApiFuture<ListAvailableVersionsPage> createPageAsync(
PageContext<ListAvailableVersionsRequest, ListAvailableVersionsResponse, Version> context,
ApiFuture<ListAvailableVersionsResponse> futureResponse) {
return super.createPageAsync(context, futureResponse);
}
}
public static class ListAvailableVersionsFixedSizeCollection
extends AbstractFixedSizeCollection<
ListAvailableVersionsRequest,
ListAvailableVersionsResponse,
Version,
ListAvailableVersionsPage,
ListAvailableVersionsFixedSizeCollection> {
private ListAvailableVersionsFixedSizeCollection(
List<ListAvailableVersionsPage> pages, int collectionSize) {
super(pages, collectionSize);
}
private static ListAvailableVersionsFixedSizeCollection createEmptyCollection() {
return new ListAvailableVersionsFixedSizeCollection(null, 0);
}
@Override
protected ListAvailableVersionsFixedSizeCollection createCollection(
List<ListAvailableVersionsPage> pages, int collectionSize) {
return new ListAvailableVersionsFixedSizeCollection(pages, collectionSize);
}
}
public static class ListInstancesPagedResponse
extends AbstractPagedListResponse<
ListInstancesRequest,
ListInstancesResponse,
Instance,
ListInstancesPage,
ListInstancesFixedSizeCollection> {
public static ApiFuture<ListInstancesPagedResponse> createAsync(
PageContext<ListInstancesRequest, ListInstancesResponse, Instance> context,
ApiFuture<ListInstancesResponse> futureResponse) {
ApiFuture<ListInstancesPage> futurePage =
ListInstancesPage.createEmptyPage().createPageAsync(context, futureResponse);
return ApiFutures.transform(
futurePage,
input -> new ListInstancesPagedResponse(input),
MoreExecutors.directExecutor());
}
private ListInstancesPagedResponse(ListInstancesPage page) {
super(page, ListInstancesFixedSizeCollection.createEmptyCollection());
}
}
public static class ListInstancesPage
extends AbstractPage<
ListInstancesRequest, ListInstancesResponse, Instance, ListInstancesPage> {
private ListInstancesPage(
PageContext<ListInstancesRequest, ListInstancesResponse, Instance> context,
ListInstancesResponse response) {
super(context, response);
}
private static ListInstancesPage createEmptyPage() {
return new ListInstancesPage(null, null);
}
@Override
protected ListInstancesPage createPage(
PageContext<ListInstancesRequest, ListInstancesResponse, Instance> context,
ListInstancesResponse response) {
return new ListInstancesPage(context, response);
}
@Override
public ApiFuture<ListInstancesPage> createPageAsync(
PageContext<ListInstancesRequest, ListInstancesResponse, Instance> context,
ApiFuture<ListInstancesResponse> futureResponse) {
return super.createPageAsync(context, futureResponse);
}
}
public static class ListInstancesFixedSizeCollection
extends AbstractFixedSizeCollection<
ListInstancesRequest,
ListInstancesResponse,
Instance,
ListInstancesPage,
ListInstancesFixedSizeCollection> {
private ListInstancesFixedSizeCollection(List<ListInstancesPage> pages, int collectionSize) {
super(pages, collectionSize);
}
private static ListInstancesFixedSizeCollection createEmptyCollection() {
return new ListInstancesFixedSizeCollection(null, 0);
}
@Override
protected ListInstancesFixedSizeCollection createCollection(
List<ListInstancesPage> pages, int collectionSize) {
return new ListInstancesFixedSizeCollection(pages, collectionSize);
}
}
}
| |
package com.microsoft.applicationinsights.library;
import android.annotation.TargetApi;
import android.app.Activity;
import android.app.Application;
import android.content.ComponentCallbacks2;
import android.content.res.Configuration;
import android.os.Build;
import android.os.Bundle;
import com.microsoft.applicationinsights.library.config.ISessionConfig;
import com.microsoft.applicationinsights.logging.InternalLogging;
import java.util.Date;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicLong;
@TargetApi(Build.VERSION_CODES.ICE_CREAM_SANDWICH)
class AutoCollection implements Application.ActivityLifecycleCallbacks, ComponentCallbacks2 {
/**
* The activity counter
*/
protected final AtomicInteger activityCount;
/**
* The configuration for tracking sessions
*/
protected ISessionConfig config;
/**
* The timestamp of the last activity
*/
protected final AtomicLong lastBackground;
/**
* The telemetryContext which is needed to renew a session
*/
protected TelemetryContext telemetryContext;
/**
* Volatile boolean for double checked synchronize block
*/
private static volatile boolean isLoaded = false;
/**
* Synchronization LOCK for setting static context
*/
private static final Object LOCK = new Object();
/**
* The singleton INSTANCE of this class
*/
private static AutoCollection instance;
/**
* The tag for logging
*/
private static final String TAG = "AutoCollection";
/**
* A flag which determines whether auto page view tracking has been enabled or not.
*/
private static boolean autoPageViewsEnabled;
/**
* A flag which determines whether session management has been enabled or not.
*/
private static boolean autoSessionManagementEnabled;
protected static boolean isAutoAppearanceTrackingEnabled() {
return autoAppearanceTrackingEnabled;
}
protected static boolean isHasRegisteredComponentCallbacks() {
return hasRegisteredComponentCallbacks;
}
protected static boolean isHasRegisteredLifecycleCallbacks() {
return hasRegisteredLifecycleCallbacks;
}
protected static boolean isAutoPageViewsEnabled() {
return autoPageViewsEnabled;
}
protected static boolean isAutoSessionManagementEnabled() {
return autoSessionManagementEnabled;
}
/**
* A flag that determines whether we want to auto-track events for foregrounding backgrounding
*/
private static boolean autoAppearanceTrackingEnabled;
/**
* A flag that indicates if componentcallbacks have been registered
*/
private static boolean hasRegisteredComponentCallbacks;
/**
* A flag that indicates if lifecyclecallbacks have been already registered
*/
private static boolean hasRegisteredLifecycleCallbacks;
/**
* Create a new INSTANCE of the autocollection event tracking
*
* @param config the session configuration for session tracking
* @param telemetryContext the context, which is needed to renew sessions
*/
protected AutoCollection(ISessionConfig config, TelemetryContext telemetryContext) {
this.activityCount = new AtomicInteger(0);
this.lastBackground = new AtomicLong(this.getTime());
this.config = config;
this.telemetryContext = telemetryContext;
}
/**
* Initialize the INSTANCE of Autocollection event tracking.
*
* @param telemetryContext the context, which is needed to renew sessions
* @param config the session configuration for session tracking
*/
protected static void initialize(TelemetryContext telemetryContext, ISessionConfig config) {
// note: isLoaded must be volatile for the double-checked LOCK to work
if (!AutoCollection.isLoaded) {
synchronized (AutoCollection.LOCK) {
if (!AutoCollection.isLoaded) {
AutoCollection.isLoaded = true;
AutoCollection.hasRegisteredComponentCallbacks = false;
AutoCollection.hasRegisteredLifecycleCallbacks = false;
AutoCollection.instance = new AutoCollection(config, telemetryContext);
}
}
}
}
/**
* @return the INSTANCE of autocollection event tracking or null if not yet initialized
*/
protected static AutoCollection getInstance() {
if (AutoCollection.instance == null) {
InternalLogging.error(TAG, "getSharedInstance was called before initialization");
}
return AutoCollection.instance;
}
/**
* Enables lifecycle event tracking for the provided application
*
* @param application the application object
*/
@TargetApi(Build.VERSION_CODES.ICE_CREAM_SANDWICH)
private static void registerActivityLifecycleCallbacks(Application application) {
if (!hasRegisteredLifecycleCallbacks) {
if ((application != null) && Util.isLifecycleTrackingAvailable()) {
application.registerActivityLifecycleCallbacks(AutoCollection.getInstance());
hasRegisteredLifecycleCallbacks = true;
InternalLogging.info(TAG, "Registered activity lifecycle callbacks");
}
}
}
/**
* Register for component callbacks to enable persisting when backgrounding on devices with API-level 14+
* and persisting when receiving onMemoryLow() on devices with API-level 1+
*
* @param application the application object
*/
private static void registerForComponentCallbacks(Application application) {
if (!hasRegisteredComponentCallbacks) {
if ((application != null) && Util.isLifecycleTrackingAvailable()) {
application.registerComponentCallbacks(AutoCollection.getInstance());
hasRegisteredComponentCallbacks = true;
InternalLogging.info(TAG, "Registered component callbacks");
}
}
}
/**
* Enables page view event tracking for the provided application
*
* @param application the application object
*/
@TargetApi(Build.VERSION_CODES.ICE_CREAM_SANDWICH)
protected static void enableAutoPageViews(Application application) {
if (application != null && Util.isLifecycleTrackingAvailable()) {
synchronized (AutoCollection.LOCK) {
registerActivityLifecycleCallbacks(application);
autoPageViewsEnabled = true;
}
}
}
/**
* Disables page view event tracking for the provided application*
*/
@TargetApi(Build.VERSION_CODES.ICE_CREAM_SANDWICH)
protected static void disableAutoPageViews() {
if (Util.isLifecycleTrackingAvailable()) {
synchronized (AutoCollection.LOCK) {
autoPageViewsEnabled = false;
}
}
}
/**
* Enables session event tracking for the provided application
*
* @param application the application object
*/
@TargetApi(Build.VERSION_CODES.ICE_CREAM_SANDWICH)
protected static void enableAutoSessionManagement(Application application) {
if (application != null && Util.isLifecycleTrackingAvailable()) {
synchronized (AutoCollection.LOCK) {
registerForComponentCallbacks(application);
registerActivityLifecycleCallbacks(application);
autoSessionManagementEnabled = true;
}
}
}
/**
* Disables session event tracking for the provided application
*/
@TargetApi(Build.VERSION_CODES.ICE_CREAM_SANDWICH)
protected static void disableAutoSessionManagement() {
if (Util.isLifecycleTrackingAvailable()) {
synchronized (AutoCollection.LOCK) {
autoSessionManagementEnabled = false;
}
}
}
/**
* Enables auto appearance event tracking for the provided application
*
* @param application the application object
*/
@TargetApi(Build.VERSION_CODES.ICE_CREAM_SANDWICH)
protected static void enableAutoAppearanceTracking(Application application) {
if (application != null && Util.isLifecycleTrackingAvailable()) {
synchronized (AutoCollection.LOCK) {
registerForComponentCallbacks(application);
registerActivityLifecycleCallbacks(application);
autoAppearanceTrackingEnabled = true;
}
}
}
/**
* Disables auto appearance event tracking for the provided application
*/
@TargetApi(Build.VERSION_CODES.ICE_CREAM_SANDWICH)
protected static void disableAutoAppearanceTracking() {
if (Util.isLifecycleTrackingAvailable()) {
synchronized (AutoCollection.LOCK) {
autoAppearanceTrackingEnabled = false;
}
}
}
/**
* This is called each time an activity is created.
*
* @param activity the Android Activity that's created
* @param savedInstanceState the bundle
*/
public void onActivityCreated(Activity activity, Bundle savedInstanceState) {
// unused but required to implement ActivityLifecycleCallbacks
//NOTE:
//We first implemented Session management here. This callback doesn't work for the starting
//activity of the app because the SDK will be setup and initialized in the onCreate, so
//we don't get the very first call to an app activity's onCreate.
//This is why the logic was moved to onActivityResumed below
}
/**
* This is called each time an activity becomes visible
*
* @param activity the activity which entered the foreground
*/
public void onActivityStarted(Activity activity) {
// unused but required to implement ActivityLifecycleCallbacks
}
/**
* This is called each time an activity has been started or was resumed after pause
*
* @param activity the activity which left the foreground
*/
public void onActivityResumed(Activity activity) {
synchronized (AutoCollection.LOCK) {
sessionManagement();
sendPagewView(activity);
}
}
private void sendPagewView(Activity activity) {
if (autoPageViewsEnabled) {
InternalLogging.info(TAG, "New Pageview");
TrackDataOperation pageViewOp = new TrackDataOperation(TrackDataOperation.DataType.PAGE_VIEW, activity.getClass().getName());
new Thread(pageViewOp).start();
}
}
private void sessionManagement() {
int count = this.activityCount.getAndIncrement();
if (count == 0) {
if (autoSessionManagementEnabled) {
InternalLogging.info(TAG, "Starting & tracking session");
TrackDataOperation sessionOp = new TrackDataOperation(TrackDataOperation.DataType.NEW_SESSION);
new Thread(sessionOp).start();
} else {
InternalLogging.info(TAG, "Session management disabled by the developer");
}
if (autoAppearanceTrackingEnabled) {
//TODO track cold start as soon as it's available in new Schema.
}
} else {
//we should already have a session now
//check if the session should be renewed
long now = this.getTime();
long then = this.lastBackground.getAndSet(this.getTime());
boolean shouldRenew = ((now - then) >= this.config.getSessionIntervalMs());
InternalLogging.info(TAG, "Checking if we have to renew a session, time difference is: " + (now-then));
if (autoSessionManagementEnabled && shouldRenew) {
InternalLogging.info(TAG, "Renewing session");
this.telemetryContext.renewSessionId();
TrackDataOperation sessionOp = new TrackDataOperation(TrackDataOperation.DataType.NEW_SESSION);
new Thread(sessionOp).start();
}
}
}
/**
* This is called each time an activity leaves the foreground
*
* @param activity the activity which was paused
*/
public void onActivityPaused(Activity activity) {
//set backgrounding in onTrimMemory
}
public void onActivityStopped(Activity activity) {
// unused but required to implement ActivityLifecycleCallbacks
}
public void onActivitySaveInstanceState(Activity activity, Bundle outState) {
// unused but required to implement ActivityLifecycleCallbacks
}
public void onActivityDestroyed(Activity activity) {
// unused but required to implement ActivityLifecycleCallbacks
}
@Override
public void onTrimMemory(int level) {
if (level == TRIM_MEMORY_UI_HIDDEN) {
InternalLogging.info(TAG, "UI of the app is hidden");
InternalLogging.info(TAG, "Setting background time");
this.lastBackground.set(this.getTime());
}
}
@Override
public void onConfigurationChanged(Configuration newConfig) {
switch (newConfig.orientation) {
case Configuration.ORIENTATION_PORTRAIT:
InternalLogging.info(TAG, "Device Orientation is portrait");
break;
case Configuration.ORIENTATION_LANDSCAPE:
InternalLogging.info(TAG, "Device Orientation is landscape");
break;
case Configuration.ORIENTATION_UNDEFINED:
InternalLogging.info(TAG, "Device Orientation is undefinded");
break;
default:
break;
}
}
@Override
public void onLowMemory() {
// unused but required to implement ComponentCallbacks
}
/**
* Test hook to get the current time
*
* @return the current time in milliseconds
*/
protected long getTime() {
return new Date().getTime();
}
}
| |
package org.commcare.views.widgets;
import android.content.ActivityNotFoundException;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.util.Log;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.Toast;
import org.commcare.CommCareApplication;
import org.commcare.activities.FormEntryActivity;
import org.commcare.activities.components.FormEntryInstanceState;
import org.commcare.dalvik.R;
import org.commcare.logic.PendingCalloutInterface;
import org.commcare.models.encryption.EncryptionIO;
import org.commcare.preferences.HiddenPreferences;
import org.commcare.util.LogTypes;
import org.commcare.utils.FileExtensionNotFoundException;
import org.commcare.utils.FileUtil;
import org.commcare.utils.FormUploadUtil;
import org.commcare.utils.StringUtils;
import org.javarosa.core.io.StreamsUtil;
import org.javarosa.core.model.data.IAnswerData;
import org.javarosa.core.model.data.IntegerData;
import org.javarosa.core.model.data.InvalidData;
import org.javarosa.core.model.data.StringData;
import org.javarosa.core.services.Logger;
import org.javarosa.core.services.locale.Localization;
import org.javarosa.form.api.FormEntryPrompt;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import javax.crypto.spec.SecretKeySpec;
import androidx.annotation.NonNull;
/**
* Generic logic for capturing or choosing audio/video/image media
*
* @author Phillip Mates (pmates@dimagi.com)
*/
public abstract class MediaWidget extends QuestionWidget {
private static final String TAG = MediaWidget.class.getSimpleName();
protected static final String CUSTOM_TAG = "custom";
public static final String AES_EXTENSION = ".aes";
protected Button mCaptureButton;
protected Button mPlayButton;
protected Button mChooseButton;
protected String mBinaryName;
private String mTempBinaryPath;
protected final PendingCalloutInterface pendingCalloutInterface;
protected final String mInstanceFolder;
private int oversizedMediaSize;
protected String customFileTag;
private String destMediaPath;
public MediaWidget(Context context, FormEntryPrompt prompt,
PendingCalloutInterface pendingCalloutInterface) {
super(context, prompt);
this.pendingCalloutInterface = pendingCalloutInterface;
mInstanceFolder = FormEntryInstanceState.getInstanceFolder();
setOrientation(LinearLayout.VERTICAL);
initializeButtons();
setupLayout();
}
@Override
protected void onVisibilityChanged(@NonNull View changedView, int visibility) {
super.onVisibilityChanged(changedView, visibility);
if (visibility == View.VISIBLE) {
loadAnswerFromDataModel();
}
}
private void loadAnswerFromDataModel() {
mBinaryName = mPrompt.getAnswerText();
if (mBinaryName != null) {
reloadFile();
} else {
checkForOversizedMedia(mPrompt.getAnswerValue());
togglePlayButton(false);
}
}
private void reloadFile() {
File f = new File(mInstanceFolder + mBinaryName);
if (f.exists()) {
checkFileSize(f);
} else if (mTempBinaryPath == null) {
File encryptedFile = new File(mInstanceFolder + mBinaryName + AES_EXTENSION);
checkFileSize(encryptedFile);
mTempBinaryPath = decryptMedia(encryptedFile, getSecretKey());
} else {
checkFileSize(new File(mTempBinaryPath));
}
togglePlayButton(true);
}
protected String getSourceFilePathToDisplay() {
File f = new File(mInstanceFolder + mBinaryName);
if (f.exists()) {
return f.getAbsolutePath();
} else {
// file should have been decrypted at the temp path
return mTempBinaryPath;
}
}
// decrypt the given file to a temp path
public static String decryptMedia(File f, SecretKeySpec secretKey) {
if (!f.getName().endsWith(AES_EXTENSION)) {
return null;
}
String tempMediaPath = createTempMediaPath(FileUtil.getExtension(removeAESExtension(f.getName())));
try {
FileOutputStream fos = new FileOutputStream(tempMediaPath);
InputStream is = EncryptionIO.getFileInputStream(f.getPath(), secretKey);
StreamsUtil.writeFromInputToOutputNew(is, fos);
} catch (IOException e) {
throw new RuntimeException("Failed to decrypt media at path " + f.getAbsolutePath()
+ " due to " + e.getMessage(), e);
}
return tempMediaPath;
}
private SecretKeySpec getSecretKey() {
return ((FormEntryActivity)getContext()).getSymetricKey();
}
protected void togglePlayButton(boolean enabled) {
mPlayButton.setEnabled(enabled);
}
protected abstract void initializeButtons();
protected void setupLayout() {
addView(mCaptureButton);
addView(mChooseButton);
addView(mPlayButton);
}
@Override
public IAnswerData getAnswer() {
if (oversizedMediaSize > 0) {
// media was too big to upload, set answer as invalid data to
// allow showing the user a proper warning message.
return new InvalidData("", new IntegerData(oversizedMediaSize));
} else if (mBinaryName != null) {
return new StringData(removeAESExtension(mBinaryName));
}
return null;
}
/**
* @return whether the media file passes the size check
*/
private boolean ifMediaSizeChecks(String binaryPath) {
File source = new File(binaryPath);
boolean isTooLargeToUpload = checkFileSize(source);
if (isTooLargeToUpload) {
oversizedMediaSize = (int)source.length() / (1024 * 1024);
return false;
} else {
oversizedMediaSize = -1;
return true;
}
}
/**
* @return whether the media file has a valid extension
*/
private boolean ifMediaExtensionChecks(String binaryPath) {
String extension = FileUtil.getExtension(binaryPath);
if (!FormUploadUtil.isSupportedMultimediaFile(binaryPath)) {
Toast.makeText(getContext(),
Localization.get("form.attachment.invalid"),
Toast.LENGTH_LONG).show();
Log.e(TAG, String.format(
"Could not save file with URI %s because of bad extension %s.",
binaryPath,
extension
));
return false;
}
return true;
}
@Override
public void clearAnswer() {
deleteMedia();
togglePlayButton(false);
}
private void deleteMedia() {
deleteMediaFiles(mInstanceFolder, mBinaryName);
mBinaryName = null;
mTempBinaryPath = null;
}
// get the file path and delete the file along with the corresponding encrypted file
public static void deleteMediaFiles(String instanceFolder, String binaryName) {
String filePath = instanceFolder + "/" + binaryName;
if (!FileUtil.deleteFileOrDir(filePath)) {
Logger.log(LogTypes.TYPE_FORM_ENTRY, "Failed to delete media at path " + filePath);
}
String encryptedFilePath = filePath + MediaWidget.AES_EXTENSION;
if (!FileUtil.deleteFileOrDir(encryptedFilePath)) {
Logger.log(LogTypes.TYPE_FORM_ENTRY, "Failed to delete media at path " + encryptedFilePath);
}
}
@Override
public void setOnLongClickListener(OnLongClickListener l) {
mCaptureButton.setOnLongClickListener(l);
mChooseButton.setOnLongClickListener(l);
mPlayButton.setOnLongClickListener(l);
}
@Override
public void unsetListeners() {
super.unsetListeners();
mCaptureButton.setOnLongClickListener(null);
mChooseButton.setOnLongClickListener(null);
mPlayButton.setOnLongClickListener(null);
}
@Override
public void cancelLongPress() {
super.cancelLongPress();
mCaptureButton.cancelLongPress();
mChooseButton.cancelLongPress();
mPlayButton.cancelLongPress();
}
@Override
public void setFocus(Context context) {
// Hide the soft keyboard if it's showing.
InputMethodManager inputManager =
(InputMethodManager)context.getSystemService(Context.INPUT_METHOD_SERVICE);
inputManager.hideSoftInputFromWindow(this.getWindowToken(), 0);
}
@Override
public void setBinaryData(Object binaryURI) {
// delete any existing media
if (mBinaryName != null) {
deleteMedia();
}
String binaryPath;
try {
binaryPath = createFilePath(binaryURI);
} catch (FileExtensionNotFoundException e) {
showToast("form.attachment.invalid.extension");
Logger.exception("Error while saving media ", e);
return;
} catch (IOException e) {
e.printStackTrace();
showToast("form.attachment.copy.fail");
Logger.exception("Error while saving media ", e);
return;
}
if (!ifMediaSizeChecks(binaryPath) && !ifMediaExtensionChecks(binaryPath)) {
return;
}
encryptRecordedFileToDestination(binaryPath);
File newMedia = new File(destMediaPath);
if (newMedia.exists()) {
showToast("form.attachment.success");
}
mTempBinaryPath = binaryPath;
mBinaryName = removeAESExtension(newMedia.getName());
}
// removes ".aes" from file name if exists
public static String removeAESExtension(String fileName) {
if (fileName.endsWith(AES_EXTENSION)) {
return fileName.replace(AES_EXTENSION, "");
}
return fileName;
}
private void encryptRecordedFileToDestination(String binaryPath) {
String extension = FileUtil.getExtension(binaryPath);
destMediaPath = mInstanceFolder + System.currentTimeMillis() +
customFileTag + "." + extension;
try {
if (HiddenPreferences.isMediaCaptureEncryptionEnabled()) {
destMediaPath = destMediaPath + AES_EXTENSION;
EncryptionIO.encryptFile(binaryPath, destMediaPath, getSecretKey());
} else {
FileUtil.copyFile(binaryPath, destMediaPath);
}
} catch (IOException e) {
showToast("form.attachment.copy.fail");
Logger.exception(LogTypes.TYPE_MAINTENANCE, e);
}
}
/**
* If file is chosen by user, the file selection intent will return an URI
* If file is auto-selected after recording_fragment, then the recordingfragment will provide a string file path
* Set value of customFileTag if the file is a recent recording from the RecordingFragment
*/
private String createFilePath(Object binaryuri) throws IOException {
String path;
if (binaryuri instanceof Uri) {
// Make a copy to a temporary location
InputStream inputStream = getContext().getContentResolver().openInputStream((Uri)binaryuri);
String fileName = FileUtil.getFileName(getContext(), (Uri)binaryuri);
path = createTempMediaPath(FileUtil.getExtension(fileName));
FileUtil.copyFile(inputStream, new File(path));
customFileTag = "";
} else {
path = (String)binaryuri;
customFileTag = CUSTOM_TAG;
}
return path;
}
private static String createTempMediaPath(String fileExtension) {
return CommCareApplication.instance().getAndroidFsTemp() +
System.currentTimeMillis() + "." + fileExtension;
}
// launches an ACTION_VIEW Intent for the given file
public static void playMedia(Context context, String mediaType, String filePath) {
Intent i = new Intent(Intent.ACTION_VIEW);
File mediaFile = new File(filePath);
Uri mediaUri = FileUtil.getUriForExternalFile(context, mediaFile);
i.setDataAndType(mediaUri, mediaType);
i.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
try {
context.startActivity(i);
} catch (ActivityNotFoundException e) {
Toast.makeText(context,
StringUtils.getStringSpannableRobust(context,
R.string.activity_not_found,
"play " + mediaType.substring(0, mediaType.indexOf("/"))),
Toast.LENGTH_SHORT).show();
}
}
}
| |
package com.jackpf.blockchainsearch.Service;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Locale;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import android.content.Context;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.PorterDuff.Mode;
import android.graphics.RectF;
import android.preference.PreferenceManager;
import com.jackpf.blockchainsearch.R;
import com.jackpf.blockchainsearch.Data.BlockchainData;
import com.jackpf.blockchainsearch.Lib.AddressFormatException;
import com.jackpf.blockchainsearch.Lib.Base58;
/**
* Handy global utils class
*/
public class Utils
{
public static ProcessedTransaction processTransaction(String address, JSONObject tx)
{
Long total = 0L;
String addrIn = "", addrOut = "";
for (Object _in : (JSONArray) tx.get("inputs")) {
JSONObject in = (JSONObject) _in;
JSONObject prev = (JSONObject) in.get("prev_out");
if (prev != null) {
if (address.equals((String) prev.get("addr"))) {
total -= Long.parseLong(prev.get("value").toString());
} else {
addrOut = prev.get("addr").toString();
}
} else {
addrOut = "No inputs (new coins)";
}
}
for (Object _out : (JSONArray) tx.get("out")) {
JSONObject out = (JSONObject) _out;
if (address.equals((String) out.get("addr"))) {
total += Long.parseLong(out.get("value").toString());
} else {
addrIn = out.get("addr").toString();
}
}
return new ProcessedTransaction(total > 0L ? addrOut : addrIn, total);
}
public static class ProcessedTransaction
{
private String address;
private Long amount;
public ProcessedTransaction(String address, Long amount)
{
this.address = address;
this.amount = amount;
}
public String getAddress()
{
return address;
}
public Long getAmount()
{
return amount;
}
}
/**
* Format given value into a bitcoin currency value
*
* @param i
* @return
*/
public static String btcFormat(Long i, Context context)
{
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);
int format = Integer.parseInt(prefs.getString(context.getString(R.string.pref_btc_format_key), context.getString(R.string.pref_btc_format_default)));
return String.format(Locale.getDefault(), BlockchainData.FORMATS[format], i.doubleValue() / BlockchainData.CONVERSIONS[format]);
}
/**
* Draw a confirmation counter
*
* @param confirmations
* @param targetConfirmations
* @param color1
* @param color2
* @param size
* @return
*/
public static Bitmap drawConfirmationsArc(int confirmations, int targetConfirmations, int color1, int color2, int size)
{
Bitmap image = Bitmap.createBitmap(size, size, Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(image);
canvas.drawColor(0, Mode.CLEAR);
Paint paint = new Paint();
paint.setAntiAlias(true);
paint.setStrokeWidth(1);
final RectF oval = new RectF();
oval.set(0, 0, size, size);
float f = (float) confirmations / (float) targetConfirmations;
f = f > 1f ? 1f : f;
int deg = Math.round(f * 360f);
int deg_r = 360 - deg;
paint.setColor(color1);
canvas.drawArc(oval, -90, deg, true, paint);
paint.setColor(color2);
canvas.drawArc(oval, -90 + deg, deg_r, true, paint);
return image;
}
/**
* Validate a bitcoin address
*
* @param address
* @return
*/
public static boolean validAddress(String address)
{
byte[] decoded = new byte[]{};
try {
decoded = Base58.decode(address);
} catch (AddressFormatException e) {
return false;
}
if (decoded.length != 25) {
return false;
}
byte[] digest = getBytes(decoded, 0, 21);
byte[] checksum = getBytes(decoded, 21, 25);
MessageDigest sha256 = null;
try {
sha256 = MessageDigest.getInstance("SHA-256");
} catch (NoSuchAlgorithmException e) { /* Just let it fly, we're pretty f'ked here */ }
byte[] hash = sha256.digest(sha256.digest(digest));
for (int i = 0; i < checksum.length; i++) {
if (checksum[i] != hash[i]) {
return false;
}
}
return true;
}
/**
* Synonymous to Arrays.copyOfRange but rewritten for API level
*
* @param array
* @param start
* @param end
* @return
*/
private static byte[] getBytes(byte[] array, int start, int end)
{
int range = end - start;
byte[] copy = new byte[range];
for (int i = start, j = 0; i < end; i++, j++) {
copy[j] = array[i];
}
return copy;
}
/**
* Validate a transaction hash
*
* @param hash
* @return
*/
public static boolean validTransaction(String hash)
{
return hash.getBytes().length == 64;
}
}
| |
/*
* Copyright (C) 2011 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.architecture.realarchitecture.datasource.net;
import com.android.volley.AuthFailureError;
import com.android.volley.Request;
import com.android.volley.Request.Method;
import com.android.volley.toolbox.HttpStack;
import org.apache.http.Header;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.ProtocolVersion;
import org.apache.http.StatusLine;
import org.apache.http.entity.BasicHttpEntity;
import org.apache.http.message.BasicHeader;
import org.apache.http.message.BasicHttpResponse;
import org.apache.http.message.BasicStatusLine;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import javax.net.ssl.SSLSocketFactory;
import okhttp3.CacheControl;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.RequestBody;
import okhttp3.Response;
import okhttp3.ResponseBody;
/**
* An {@link HttpStack} based on okHttp.
*/
public class OkHttpStack implements HttpStack {
/**
* An interface for transforming URLs before use.
*/
public interface UrlRewriter {
/**
* Returns a URL to use instead of the provided one, or null to indicate
* this URL should not be used at all.
*/
public String rewriteUrl(String originalUrl);
}
private final UrlRewriter mUrlRewriter;
private final SSLSocketFactory mSslSocketFactory;
public OkHttpStack() {
this(null);
}
/**
* @param urlRewriter Rewriter to use for request URLs
*/
public OkHttpStack(UrlRewriter urlRewriter) {
this(urlRewriter, null);
}
/**
* @param urlRewriter Rewriter to use for request URLs
* @param sslSocketFactory SSL factory to use for HTTPS connections
*/
public OkHttpStack(UrlRewriter urlRewriter, SSLSocketFactory sslSocketFactory) {
mUrlRewriter = urlRewriter;
mSslSocketFactory = sslSocketFactory;
}
@Override
public synchronized HttpResponse performRequest(Request<?> request, Map<String, String> additionalHeaders)
throws IOException, AuthFailureError {
String url = request.getUrl();
if (mUrlRewriter != null) {
String rewritten = mUrlRewriter.rewriteUrl(url);
if (rewritten == null) {
throw new IOException("URL blocked by rewriter: " + url);
}
url = rewritten;
}
/*init request builder*/
okhttp3.Request.Builder okRequestBuilder = new okhttp3.Request.Builder().url(url)
.cacheControl(new CacheControl.Builder()
.maxAge(0, TimeUnit.SECONDS)
.build());
/*set request headers*/
HashMap<String, String> map = new HashMap<String, String>();
map.putAll(request.getHeaders());
map.putAll(additionalHeaders);
for (String headerName : map.keySet()) {
okRequestBuilder.addHeader(headerName, map.get(headerName));
}
/*set request method*/
setRequestMethod(okRequestBuilder, request);
okhttp3.Request okRequest = okRequestBuilder.build();
/*init request client*/
int timeoutMs = request.getTimeoutMs();
OkHttpClient.Builder okClientBuilder = new OkHttpClient.Builder();
okClientBuilder.followRedirects(HttpURLConnection.getFollowRedirects())
.followSslRedirects(HttpURLConnection.getFollowRedirects())
.connectTimeout(timeoutMs, TimeUnit.MILLISECONDS)
.readTimeout(timeoutMs, TimeUnit.MILLISECONDS);
if (okRequest.isHttps() && mSslSocketFactory != null) {
okClientBuilder.sslSocketFactory(mSslSocketFactory);
}
// Initialize HttpResponse with data from the HttpURLConnection.
ProtocolVersion protocolVersion = new ProtocolVersion("HTTP", 1, 1);
OkHttpClient okClient = okClientBuilder.build();
Response okResponse = okClient.newCall(okRequest).execute();
int responseCode = okResponse.code();
if (responseCode == -1) {
// -1 is returned by getResponseCode() if the response code could not be retrieved.
// Signal to the caller that something was wrong with the connection.
throw new IOException("Could not retrieve response code from HttpUrlConnection.");
}
StatusLine responseStatus = new BasicStatusLine(protocolVersion,
responseCode, okResponse.message());
BasicHttpResponse response = new BasicHttpResponse(responseStatus);
if (hasResponseBody(request.getMethod(), responseStatus.getStatusCode())) {
response.setEntity(entityFromOkHttp(okResponse));
}
for (int i = 0; i < okResponse.headers().size(); i++) {
String name = okResponse.headers().name(i);
String value = okResponse.headers().value(i);
Header h = new BasicHeader(name, value);
response.addHeader(h);
}
return response;
}
/**
* Checks if a response message contains a body.
*
* @param requestMethod request method
* @param responseCode response status code
* @return whether the response has a body
* @see <a href="https://tools.ietf.org/html/rfc7230#section-3.3">RFC 7230 section 3.3</a>
*/
private static boolean hasResponseBody(int requestMethod, int responseCode) {
return requestMethod != Request.Method.HEAD
&& !(HttpStatus.SC_CONTINUE <= responseCode && responseCode < HttpStatus.SC_OK)
&& responseCode != HttpStatus.SC_NO_CONTENT
&& responseCode != HttpStatus.SC_NOT_MODIFIED;
}
/**
* Initializes an {@link HttpEntity} from the given {@link HttpURLConnection}.
*
* @return an HttpEntity populated with data from <code>connection</code>.
*/
private static HttpEntity entityFromOkHttp(Response okResponse) {
ResponseBody rb = okResponse.body();
BasicHttpEntity entity = new BasicHttpEntity();
InputStream inputStream = rb.byteStream();
entity.setContent(inputStream);
entity.setContentLength(rb.contentLength());
entity.setContentType(rb.contentType().type());
return entity;
}
private void setRequestMethod(okhttp3.Request.Builder builder,
Request<?> request) throws IOException, AuthFailureError {
switch (request.getMethod()) {
case Method.DEPRECATED_GET_OR_POST:
throw new IllegalStateException("unRecognize request method Method.DEPRECATED_GET_OR_POST");
case Method.GET:
builder.get();
break;
case Method.DELETE:
builder.delete();
break;
case Method.POST:
RequestBody body = checkRequestBody(request);
if (body != null) {
builder.post(body);
}
break;
case Method.PUT:
body = checkRequestBody(request);
if (body != null) {
builder.put(body);
}
break;
case Method.HEAD:
builder.head();
break;
case Method.OPTIONS:
throw new IllegalStateException("unRecognize request method Method.OPTIONS");
case Method.TRACE:
throw new IllegalStateException("unRecognize request method Method.TRACE");
case Method.PATCH:
body = checkRequestBody(request);
if (body != null) {
builder.patch(body);
}
break;
default:
throw new IllegalStateException("Unknown method type.");
}
}
private static RequestBody checkRequestBody(Request<?> request)
throws IOException, AuthFailureError {
byte[] body = request.getBody();
if (body != null) {
RequestBody requestBody = RequestBody.create(MediaType.parse(request.getBodyContentType()), body);
return requestBody;
}
return null;
}
}
| |
/*
* 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.
*/
/*
* This code was generated by https://github.com/googleapis/google-api-java-client-services/
* Modify at your own risk.
*/
package com.google.api.services.toolresults.model;
/**
* A Step represents a single operation performed as part of Execution. A step can be used to
* represent the execution of a tool ( for example a test runner execution or an execution of a
* compiler). Steps can overlap (for instance two steps might have the same start time if some
* operations are done in parallel). Here is an example, let's consider that we have a continuous
* build is executing a test runner for each iteration. The workflow would look like: - user creates
* a Execution with id 1 - user creates an TestExecutionStep with id 100 for Execution 1 - user
* update TestExecutionStep with id 100 to add a raw xml log + the service parses the xml logs and
* returns a TestExecutionStep with updated TestResult(s). - user update the status of
* TestExecutionStep with id 100 to COMPLETE A Step can be updated until its state is set to
* COMPLETE at which points it becomes immutable. Next tag: 27
*
* <p> This is the Java data model class that specifies how to parse/serialize into the JSON that is
* transmitted over HTTP when working with the Cloud Tool Results API. For a detailed explanation
* see:
* <a href="https://developers.google.com/api-client-library/java/google-http-java-client/json">https://developers.google.com/api-client-library/java/google-http-java-client/json</a>
* </p>
*
* @author Google, Inc.
*/
@SuppressWarnings("javadoc")
public final class Step extends com.google.api.client.json.GenericJson {
/**
* The time when the step status was set to complete. This value will be set automatically when
* state transitions to COMPLETE. - In response: set if the execution state is COMPLETE. - In
* create/update request: never set
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private Timestamp completionTime;
/**
* The time when the step was created. - In response: always set - In create/update request: never
* set
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private Timestamp creationTime;
/**
* A description of this tool For example: mvn clean package -D skipTests=true - In response:
* present if set by create/update request - In create/update request: optional
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.String description;
/**
* How much the device resource is used to perform the test. This is the device usage used for
* billing purpose, which is different from the run_duration, for example, infrastructure failure
* won't be charged for device usage. PRECONDITION_FAILED will be returned if one attempts to set
* a device_usage on a step which already has this field set. - In response: present if previously
* set. - In create request: optional - In update request: optional
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private Duration deviceUsageDuration;
/**
* If the execution containing this step has any dimension_definition set, then this field allows
* the child to specify the values of the dimensions. The keys must exactly match the
* dimension_definition of the execution. For example, if the execution has `dimension_definition
* = ['attempt', 'device']` then a step must define values for those dimensions, eg.
* `dimension_value = ['attempt': '1', 'device': 'Nexus 6']` If a step does not participate in one
* dimension of the matrix, the value for that dimension should be empty string. For example, if
* one of the tests is executed by a runner which does not support retries, the step could have
* `dimension_value = ['attempt': '', 'device': 'Nexus 6']` If the step does not participate in
* any dimensions of the matrix, it may leave dimension_value unset. A PRECONDITION_FAILED will be
* returned if any of the keys do not exist in the dimension_definition of the execution. A
* PRECONDITION_FAILED will be returned if another step in this execution already has the same
* name and dimension_value, but differs on other data fields, for example, step field is
* different. A PRECONDITION_FAILED will be returned if dimension_value is set, and there is a
* dimension_definition in the execution which is not specified as one of the keys. - In response:
* present if set by create - In create request: optional - In update request: never set
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.util.List<StepDimensionValueEntry> dimensionValue;
/**
* Whether any of the outputs of this step are images whose thumbnails can be fetched with
* ListThumbnails. - In response: always set - In create/update request: never set
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.Boolean hasImages;
/**
* Arbitrary user-supplied key/value pairs that are associated with the step. Users are
* responsible for managing the key namespace such that keys don't accidentally collide. An
* INVALID_ARGUMENT will be returned if the number of labels exceeds 100 or if the length of any
* of the keys or values exceeds 100 characters. - In response: always set - In create request:
* optional - In update request: optional; any new key/value pair will be added to the map, and
* any new value for an existing key will update that key's value
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.util.List<StepLabelsEntry> labels;
/**
* Details when multiple steps are run with the same configuration as a group. These details can
* be used identify which group this step is part of. It also identifies the groups 'primary step'
* which indexes all the group members. - In response: present if previously set. - In create
* request: optional, set iff this step was performed more than once. - In update request:
* optional
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private MultiStep multiStep;
/**
* A short human-readable name to display in the UI. Maximum of 100 characters. For example: Clean
* build A PRECONDITION_FAILED will be returned upon creating a new step if it shares its name and
* dimension_value with an existing step. If two steps represent a similar action, but have
* different dimension values, they should share the same name. For instance, if the same set of
* tests is run on two different platforms, the two steps should have the same name. - In
* response: always set - In create request: always set - In update request: never set
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.String name;
/**
* Classification of the result, for example into SUCCESS or FAILURE - In response: present if set
* by create/update request - In create/update request: optional
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private Outcome outcome;
/**
* How long it took for this step to run. If unset, this is set to the difference between
* creation_time and completion_time when the step is set to the COMPLETE state. In some cases, it
* is appropriate to set this value separately: For instance, if a step is created, but the
* operation it represents is queued for a few minutes before it executes, it would be appropriate
* not to include the time spent queued in its run_duration. PRECONDITION_FAILED will be returned
* if one attempts to set a run_duration on a step which already has this field set. - In
* response: present if previously set; always present on COMPLETE step - In create request:
* optional - In update request: optional
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private Duration runDuration;
/**
* The initial state is IN_PROGRESS. The only legal state transitions are * IN_PROGRESS ->
* COMPLETE A PRECONDITION_FAILED will be returned if an invalid transition is requested. It is
* valid to create Step with a state set to COMPLETE. The state can only be set to COMPLETE once.
* A PRECONDITION_FAILED will be returned if the state is set to COMPLETE multiple times. - In
* response: always set - In create/update request: optional
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.String state;
/**
* A unique identifier within a Execution for this Step. Returns INVALID_ARGUMENT if this field is
* set or overwritten by the caller. - In response: always set - In create/update request: never
* set
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.String stepId;
/**
* An execution of a test runner.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private TestExecutionStep testExecutionStep;
/**
* An execution of a tool (used for steps we don't explicitly support).
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private ToolExecutionStep toolExecutionStep;
/**
* The time when the step status was set to complete. This value will be set automatically when
* state transitions to COMPLETE. - In response: set if the execution state is COMPLETE. - In
* create/update request: never set
* @return value or {@code null} for none
*/
public Timestamp getCompletionTime() {
return completionTime;
}
/**
* The time when the step status was set to complete. This value will be set automatically when
* state transitions to COMPLETE. - In response: set if the execution state is COMPLETE. - In
* create/update request: never set
* @param completionTime completionTime or {@code null} for none
*/
public Step setCompletionTime(Timestamp completionTime) {
this.completionTime = completionTime;
return this;
}
/**
* The time when the step was created. - In response: always set - In create/update request: never
* set
* @return value or {@code null} for none
*/
public Timestamp getCreationTime() {
return creationTime;
}
/**
* The time when the step was created. - In response: always set - In create/update request: never
* set
* @param creationTime creationTime or {@code null} for none
*/
public Step setCreationTime(Timestamp creationTime) {
this.creationTime = creationTime;
return this;
}
/**
* A description of this tool For example: mvn clean package -D skipTests=true - In response:
* present if set by create/update request - In create/update request: optional
* @return value or {@code null} for none
*/
public java.lang.String getDescription() {
return description;
}
/**
* A description of this tool For example: mvn clean package -D skipTests=true - In response:
* present if set by create/update request - In create/update request: optional
* @param description description or {@code null} for none
*/
public Step setDescription(java.lang.String description) {
this.description = description;
return this;
}
/**
* How much the device resource is used to perform the test. This is the device usage used for
* billing purpose, which is different from the run_duration, for example, infrastructure failure
* won't be charged for device usage. PRECONDITION_FAILED will be returned if one attempts to set
* a device_usage on a step which already has this field set. - In response: present if previously
* set. - In create request: optional - In update request: optional
* @return value or {@code null} for none
*/
public Duration getDeviceUsageDuration() {
return deviceUsageDuration;
}
/**
* How much the device resource is used to perform the test. This is the device usage used for
* billing purpose, which is different from the run_duration, for example, infrastructure failure
* won't be charged for device usage. PRECONDITION_FAILED will be returned if one attempts to set
* a device_usage on a step which already has this field set. - In response: present if previously
* set. - In create request: optional - In update request: optional
* @param deviceUsageDuration deviceUsageDuration or {@code null} for none
*/
public Step setDeviceUsageDuration(Duration deviceUsageDuration) {
this.deviceUsageDuration = deviceUsageDuration;
return this;
}
/**
* If the execution containing this step has any dimension_definition set, then this field allows
* the child to specify the values of the dimensions. The keys must exactly match the
* dimension_definition of the execution. For example, if the execution has `dimension_definition
* = ['attempt', 'device']` then a step must define values for those dimensions, eg.
* `dimension_value = ['attempt': '1', 'device': 'Nexus 6']` If a step does not participate in one
* dimension of the matrix, the value for that dimension should be empty string. For example, if
* one of the tests is executed by a runner which does not support retries, the step could have
* `dimension_value = ['attempt': '', 'device': 'Nexus 6']` If the step does not participate in
* any dimensions of the matrix, it may leave dimension_value unset. A PRECONDITION_FAILED will be
* returned if any of the keys do not exist in the dimension_definition of the execution. A
* PRECONDITION_FAILED will be returned if another step in this execution already has the same
* name and dimension_value, but differs on other data fields, for example, step field is
* different. A PRECONDITION_FAILED will be returned if dimension_value is set, and there is a
* dimension_definition in the execution which is not specified as one of the keys. - In response:
* present if set by create - In create request: optional - In update request: never set
* @return value or {@code null} for none
*/
public java.util.List<StepDimensionValueEntry> getDimensionValue() {
return dimensionValue;
}
/**
* If the execution containing this step has any dimension_definition set, then this field allows
* the child to specify the values of the dimensions. The keys must exactly match the
* dimension_definition of the execution. For example, if the execution has `dimension_definition
* = ['attempt', 'device']` then a step must define values for those dimensions, eg.
* `dimension_value = ['attempt': '1', 'device': 'Nexus 6']` If a step does not participate in one
* dimension of the matrix, the value for that dimension should be empty string. For example, if
* one of the tests is executed by a runner which does not support retries, the step could have
* `dimension_value = ['attempt': '', 'device': 'Nexus 6']` If the step does not participate in
* any dimensions of the matrix, it may leave dimension_value unset. A PRECONDITION_FAILED will be
* returned if any of the keys do not exist in the dimension_definition of the execution. A
* PRECONDITION_FAILED will be returned if another step in this execution already has the same
* name and dimension_value, but differs on other data fields, for example, step field is
* different. A PRECONDITION_FAILED will be returned if dimension_value is set, and there is a
* dimension_definition in the execution which is not specified as one of the keys. - In response:
* present if set by create - In create request: optional - In update request: never set
* @param dimensionValue dimensionValue or {@code null} for none
*/
public Step setDimensionValue(java.util.List<StepDimensionValueEntry> dimensionValue) {
this.dimensionValue = dimensionValue;
return this;
}
/**
* Whether any of the outputs of this step are images whose thumbnails can be fetched with
* ListThumbnails. - In response: always set - In create/update request: never set
* @return value or {@code null} for none
*/
public java.lang.Boolean getHasImages() {
return hasImages;
}
/**
* Whether any of the outputs of this step are images whose thumbnails can be fetched with
* ListThumbnails. - In response: always set - In create/update request: never set
* @param hasImages hasImages or {@code null} for none
*/
public Step setHasImages(java.lang.Boolean hasImages) {
this.hasImages = hasImages;
return this;
}
/**
* Arbitrary user-supplied key/value pairs that are associated with the step. Users are
* responsible for managing the key namespace such that keys don't accidentally collide. An
* INVALID_ARGUMENT will be returned if the number of labels exceeds 100 or if the length of any
* of the keys or values exceeds 100 characters. - In response: always set - In create request:
* optional - In update request: optional; any new key/value pair will be added to the map, and
* any new value for an existing key will update that key's value
* @return value or {@code null} for none
*/
public java.util.List<StepLabelsEntry> getLabels() {
return labels;
}
/**
* Arbitrary user-supplied key/value pairs that are associated with the step. Users are
* responsible for managing the key namespace such that keys don't accidentally collide. An
* INVALID_ARGUMENT will be returned if the number of labels exceeds 100 or if the length of any
* of the keys or values exceeds 100 characters. - In response: always set - In create request:
* optional - In update request: optional; any new key/value pair will be added to the map, and
* any new value for an existing key will update that key's value
* @param labels labels or {@code null} for none
*/
public Step setLabels(java.util.List<StepLabelsEntry> labels) {
this.labels = labels;
return this;
}
/**
* Details when multiple steps are run with the same configuration as a group. These details can
* be used identify which group this step is part of. It also identifies the groups 'primary step'
* which indexes all the group members. - In response: present if previously set. - In create
* request: optional, set iff this step was performed more than once. - In update request:
* optional
* @return value or {@code null} for none
*/
public MultiStep getMultiStep() {
return multiStep;
}
/**
* Details when multiple steps are run with the same configuration as a group. These details can
* be used identify which group this step is part of. It also identifies the groups 'primary step'
* which indexes all the group members. - In response: present if previously set. - In create
* request: optional, set iff this step was performed more than once. - In update request:
* optional
* @param multiStep multiStep or {@code null} for none
*/
public Step setMultiStep(MultiStep multiStep) {
this.multiStep = multiStep;
return this;
}
/**
* A short human-readable name to display in the UI. Maximum of 100 characters. For example: Clean
* build A PRECONDITION_FAILED will be returned upon creating a new step if it shares its name and
* dimension_value with an existing step. If two steps represent a similar action, but have
* different dimension values, they should share the same name. For instance, if the same set of
* tests is run on two different platforms, the two steps should have the same name. - In
* response: always set - In create request: always set - In update request: never set
* @return value or {@code null} for none
*/
public java.lang.String getName() {
return name;
}
/**
* A short human-readable name to display in the UI. Maximum of 100 characters. For example: Clean
* build A PRECONDITION_FAILED will be returned upon creating a new step if it shares its name and
* dimension_value with an existing step. If two steps represent a similar action, but have
* different dimension values, they should share the same name. For instance, if the same set of
* tests is run on two different platforms, the two steps should have the same name. - In
* response: always set - In create request: always set - In update request: never set
* @param name name or {@code null} for none
*/
public Step setName(java.lang.String name) {
this.name = name;
return this;
}
/**
* Classification of the result, for example into SUCCESS or FAILURE - In response: present if set
* by create/update request - In create/update request: optional
* @return value or {@code null} for none
*/
public Outcome getOutcome() {
return outcome;
}
/**
* Classification of the result, for example into SUCCESS or FAILURE - In response: present if set
* by create/update request - In create/update request: optional
* @param outcome outcome or {@code null} for none
*/
public Step setOutcome(Outcome outcome) {
this.outcome = outcome;
return this;
}
/**
* How long it took for this step to run. If unset, this is set to the difference between
* creation_time and completion_time when the step is set to the COMPLETE state. In some cases, it
* is appropriate to set this value separately: For instance, if a step is created, but the
* operation it represents is queued for a few minutes before it executes, it would be appropriate
* not to include the time spent queued in its run_duration. PRECONDITION_FAILED will be returned
* if one attempts to set a run_duration on a step which already has this field set. - In
* response: present if previously set; always present on COMPLETE step - In create request:
* optional - In update request: optional
* @return value or {@code null} for none
*/
public Duration getRunDuration() {
return runDuration;
}
/**
* How long it took for this step to run. If unset, this is set to the difference between
* creation_time and completion_time when the step is set to the COMPLETE state. In some cases, it
* is appropriate to set this value separately: For instance, if a step is created, but the
* operation it represents is queued for a few minutes before it executes, it would be appropriate
* not to include the time spent queued in its run_duration. PRECONDITION_FAILED will be returned
* if one attempts to set a run_duration on a step which already has this field set. - In
* response: present if previously set; always present on COMPLETE step - In create request:
* optional - In update request: optional
* @param runDuration runDuration or {@code null} for none
*/
public Step setRunDuration(Duration runDuration) {
this.runDuration = runDuration;
return this;
}
/**
* The initial state is IN_PROGRESS. The only legal state transitions are * IN_PROGRESS ->
* COMPLETE A PRECONDITION_FAILED will be returned if an invalid transition is requested. It is
* valid to create Step with a state set to COMPLETE. The state can only be set to COMPLETE once.
* A PRECONDITION_FAILED will be returned if the state is set to COMPLETE multiple times. - In
* response: always set - In create/update request: optional
* @return value or {@code null} for none
*/
public java.lang.String getState() {
return state;
}
/**
* The initial state is IN_PROGRESS. The only legal state transitions are * IN_PROGRESS ->
* COMPLETE A PRECONDITION_FAILED will be returned if an invalid transition is requested. It is
* valid to create Step with a state set to COMPLETE. The state can only be set to COMPLETE once.
* A PRECONDITION_FAILED will be returned if the state is set to COMPLETE multiple times. - In
* response: always set - In create/update request: optional
* @param state state or {@code null} for none
*/
public Step setState(java.lang.String state) {
this.state = state;
return this;
}
/**
* A unique identifier within a Execution for this Step. Returns INVALID_ARGUMENT if this field is
* set or overwritten by the caller. - In response: always set - In create/update request: never
* set
* @return value or {@code null} for none
*/
public java.lang.String getStepId() {
return stepId;
}
/**
* A unique identifier within a Execution for this Step. Returns INVALID_ARGUMENT if this field is
* set or overwritten by the caller. - In response: always set - In create/update request: never
* set
* @param stepId stepId or {@code null} for none
*/
public Step setStepId(java.lang.String stepId) {
this.stepId = stepId;
return this;
}
/**
* An execution of a test runner.
* @return value or {@code null} for none
*/
public TestExecutionStep getTestExecutionStep() {
return testExecutionStep;
}
/**
* An execution of a test runner.
* @param testExecutionStep testExecutionStep or {@code null} for none
*/
public Step setTestExecutionStep(TestExecutionStep testExecutionStep) {
this.testExecutionStep = testExecutionStep;
return this;
}
/**
* An execution of a tool (used for steps we don't explicitly support).
* @return value or {@code null} for none
*/
public ToolExecutionStep getToolExecutionStep() {
return toolExecutionStep;
}
/**
* An execution of a tool (used for steps we don't explicitly support).
* @param toolExecutionStep toolExecutionStep or {@code null} for none
*/
public Step setToolExecutionStep(ToolExecutionStep toolExecutionStep) {
this.toolExecutionStep = toolExecutionStep;
return this;
}
@Override
public Step set(String fieldName, Object value) {
return (Step) super.set(fieldName, value);
}
@Override
public Step clone() {
return (Step) super.clone();
}
}
| |
/*
* 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.druid.benchmark.query;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.common.io.Files;
import org.apache.commons.io.FileUtils;
import org.apache.druid.benchmark.datagen.BenchmarkDataGenerator;
import org.apache.druid.benchmark.datagen.BenchmarkSchemaInfo;
import org.apache.druid.benchmark.datagen.BenchmarkSchemas;
import org.apache.druid.collections.StupidPool;
import org.apache.druid.data.input.InputRow;
import org.apache.druid.jackson.DefaultObjectMapper;
import org.apache.druid.java.util.common.concurrent.Execs;
import org.apache.druid.java.util.common.granularity.Granularities;
import org.apache.druid.java.util.common.guava.Sequence;
import org.apache.druid.java.util.common.logger.Logger;
import org.apache.druid.offheap.OffheapBufferGenerator;
import org.apache.druid.query.FinalizeResultsQueryRunner;
import org.apache.druid.query.Query;
import org.apache.druid.query.QueryPlus;
import org.apache.druid.query.QueryRunner;
import org.apache.druid.query.QueryRunnerFactory;
import org.apache.druid.query.QueryToolChest;
import org.apache.druid.query.Result;
import org.apache.druid.query.aggregation.AggregatorFactory;
import org.apache.druid.query.aggregation.DoubleMinAggregatorFactory;
import org.apache.druid.query.aggregation.DoubleSumAggregatorFactory;
import org.apache.druid.query.aggregation.LongMaxAggregatorFactory;
import org.apache.druid.query.aggregation.LongSumAggregatorFactory;
import org.apache.druid.query.aggregation.hyperloglog.HyperUniquesAggregatorFactory;
import org.apache.druid.query.aggregation.hyperloglog.HyperUniquesSerde;
import org.apache.druid.query.context.ResponseContext;
import org.apache.druid.query.ordering.StringComparators;
import org.apache.druid.query.spec.MultipleIntervalSegmentSpec;
import org.apache.druid.query.spec.QuerySegmentSpec;
import org.apache.druid.query.topn.DimensionTopNMetricSpec;
import org.apache.druid.query.topn.TopNQuery;
import org.apache.druid.query.topn.TopNQueryBuilder;
import org.apache.druid.query.topn.TopNQueryConfig;
import org.apache.druid.query.topn.TopNQueryQueryToolChest;
import org.apache.druid.query.topn.TopNQueryRunnerFactory;
import org.apache.druid.query.topn.TopNResultValue;
import org.apache.druid.segment.IncrementalIndexSegment;
import org.apache.druid.segment.IndexIO;
import org.apache.druid.segment.IndexMergerV9;
import org.apache.druid.segment.IndexSpec;
import org.apache.druid.segment.QueryableIndex;
import org.apache.druid.segment.QueryableIndexSegment;
import org.apache.druid.segment.column.ColumnConfig;
import org.apache.druid.segment.incremental.IncrementalIndex;
import org.apache.druid.segment.serde.ComplexMetrics;
import org.apache.druid.segment.writeout.OffHeapMemorySegmentWriteOutMediumFactory;
import org.apache.druid.timeline.SegmentId;
import org.openjdk.jmh.annotations.Benchmark;
import org.openjdk.jmh.annotations.BenchmarkMode;
import org.openjdk.jmh.annotations.Fork;
import org.openjdk.jmh.annotations.Measurement;
import org.openjdk.jmh.annotations.Mode;
import org.openjdk.jmh.annotations.OutputTimeUnit;
import org.openjdk.jmh.annotations.Param;
import org.openjdk.jmh.annotations.Scope;
import org.openjdk.jmh.annotations.Setup;
import org.openjdk.jmh.annotations.State;
import org.openjdk.jmh.annotations.TearDown;
import org.openjdk.jmh.annotations.Warmup;
import org.openjdk.jmh.infra.Blackhole;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.TimeUnit;
@State(Scope.Benchmark)
@Fork(value = 1)
@Warmup(iterations = 10)
@Measurement(iterations = 25)
public class TopNBenchmark
{
@Param({"1"})
private int numSegments;
@Param({"750000"})
private int rowsPerSegment;
@Param({"basic.A", "basic.numericSort", "basic.alphanumericSort"})
private String schemaAndQuery;
@Param({"10"})
private int threshold;
private static final Logger log = new Logger(TopNBenchmark.class);
private static final int RNG_SEED = 9999;
private static final IndexMergerV9 INDEX_MERGER_V9;
private static final IndexIO INDEX_IO;
public static final ObjectMapper JSON_MAPPER;
private List<IncrementalIndex> incIndexes;
private List<QueryableIndex> qIndexes;
private QueryRunnerFactory factory;
private BenchmarkSchemaInfo schemaInfo;
private TopNQueryBuilder queryBuilder;
private TopNQuery query;
private File tmpDir;
private ExecutorService executorService;
static {
JSON_MAPPER = new DefaultObjectMapper();
INDEX_IO = new IndexIO(
JSON_MAPPER,
new ColumnConfig()
{
@Override
public int columnCacheSizeBytes()
{
return 0;
}
}
);
INDEX_MERGER_V9 = new IndexMergerV9(JSON_MAPPER, INDEX_IO, OffHeapMemorySegmentWriteOutMediumFactory.instance());
}
private static final Map<String, Map<String, TopNQueryBuilder>> SCHEMA_QUERY_MAP = new LinkedHashMap<>();
private void setupQueries()
{
// queries for the basic schema
Map<String, TopNQueryBuilder> basicQueries = new LinkedHashMap<>();
BenchmarkSchemaInfo basicSchema = BenchmarkSchemas.SCHEMA_MAP.get("basic");
{ // basic.A
QuerySegmentSpec intervalSpec = new MultipleIntervalSegmentSpec(Collections.singletonList(basicSchema.getDataInterval()));
List<AggregatorFactory> queryAggs = new ArrayList<>();
queryAggs.add(new LongSumAggregatorFactory("sumLongSequential", "sumLongSequential"));
queryAggs.add(new LongMaxAggregatorFactory("maxLongUniform", "maxLongUniform"));
queryAggs.add(new DoubleSumAggregatorFactory("sumFloatNormal", "sumFloatNormal"));
queryAggs.add(new DoubleMinAggregatorFactory("minFloatZipf", "minFloatZipf"));
queryAggs.add(new HyperUniquesAggregatorFactory("hyperUniquesMet", "hyper"));
TopNQueryBuilder queryBuilderA = new TopNQueryBuilder()
.dataSource("blah")
.granularity(Granularities.ALL)
.dimension("dimSequential")
.metric("sumFloatNormal")
.intervals(intervalSpec)
.aggregators(queryAggs);
basicQueries.put("A", queryBuilderA);
}
{ // basic.numericSort
QuerySegmentSpec intervalSpec = new MultipleIntervalSegmentSpec(Collections.singletonList(basicSchema.getDataInterval()));
List<AggregatorFactory> queryAggs = new ArrayList<>();
queryAggs.add(new LongSumAggregatorFactory("sumLongSequential", "sumLongSequential"));
TopNQueryBuilder queryBuilderA = new TopNQueryBuilder()
.dataSource("blah")
.granularity(Granularities.ALL)
.dimension("dimUniform")
.metric(new DimensionTopNMetricSpec(null, StringComparators.NUMERIC))
.intervals(intervalSpec)
.aggregators(queryAggs);
basicQueries.put("numericSort", queryBuilderA);
}
{ // basic.alphanumericSort
QuerySegmentSpec intervalSpec = new MultipleIntervalSegmentSpec(Collections.singletonList(basicSchema.getDataInterval()));
List<AggregatorFactory> queryAggs = new ArrayList<>();
queryAggs.add(new LongSumAggregatorFactory("sumLongSequential", "sumLongSequential"));
TopNQueryBuilder queryBuilderA = new TopNQueryBuilder()
.dataSource("blah")
.granularity(Granularities.ALL)
.dimension("dimUniform")
.metric(new DimensionTopNMetricSpec(null, StringComparators.ALPHANUMERIC))
.intervals(intervalSpec)
.aggregators(queryAggs);
basicQueries.put("alphanumericSort", queryBuilderA);
}
SCHEMA_QUERY_MAP.put("basic", basicQueries);
}
@Setup
public void setup() throws IOException
{
log.info("SETUP CALLED AT " + System.currentTimeMillis());
ComplexMetrics.registerSerde("hyperUnique", new HyperUniquesSerde());
executorService = Execs.multiThreaded(numSegments, "TopNThreadPool");
setupQueries();
String[] schemaQuery = schemaAndQuery.split("\\.");
String schemaName = schemaQuery[0];
String queryName = schemaQuery[1];
schemaInfo = BenchmarkSchemas.SCHEMA_MAP.get(schemaName);
queryBuilder = SCHEMA_QUERY_MAP.get(schemaName).get(queryName);
queryBuilder.threshold(threshold);
query = queryBuilder.build();
incIndexes = new ArrayList<>();
for (int i = 0; i < numSegments; i++) {
log.info("Generating rows for segment " + i);
BenchmarkDataGenerator gen = new BenchmarkDataGenerator(
schemaInfo.getColumnSchemas(),
RNG_SEED + i,
schemaInfo.getDataInterval(),
rowsPerSegment
);
IncrementalIndex incIndex = makeIncIndex();
for (int j = 0; j < rowsPerSegment; j++) {
InputRow row = gen.nextRow();
if (j % 10000 == 0) {
log.info(j + " rows generated.");
}
incIndex.add(row);
}
incIndexes.add(incIndex);
}
tmpDir = Files.createTempDir();
log.info("Using temp dir: " + tmpDir.getAbsolutePath());
qIndexes = new ArrayList<>();
for (int i = 0; i < numSegments; i++) {
File indexFile = INDEX_MERGER_V9.persist(
incIndexes.get(i),
tmpDir,
new IndexSpec(),
null
);
QueryableIndex qIndex = INDEX_IO.loadIndex(indexFile);
qIndexes.add(qIndex);
}
factory = new TopNQueryRunnerFactory(
new StupidPool<>(
"TopNBenchmark-compute-bufferPool",
new OffheapBufferGenerator("compute", 250000000),
0,
Integer.MAX_VALUE
),
new TopNQueryQueryToolChest(
new TopNQueryConfig(),
QueryBenchmarkUtil.noopIntervalChunkingQueryRunnerDecorator()
),
QueryBenchmarkUtil.NOOP_QUERYWATCHER
);
}
@TearDown
public void tearDown() throws IOException
{
FileUtils.deleteDirectory(tmpDir);
}
private IncrementalIndex makeIncIndex()
{
return new IncrementalIndex.Builder()
.setSimpleTestingIndexSchema(schemaInfo.getAggsArray())
.setReportParseExceptions(false)
.setMaxRowCount(rowsPerSegment)
.buildOnheap();
}
private static <T> List<T> runQuery(QueryRunnerFactory factory, QueryRunner runner, Query<T> query)
{
QueryToolChest toolChest = factory.getToolchest();
QueryRunner<T> theRunner = new FinalizeResultsQueryRunner<>(
toolChest.mergeResults(toolChest.preMergeQueryDecoration(runner)),
toolChest
);
Sequence<T> queryResult = theRunner.run(QueryPlus.wrap(query), ResponseContext.createEmpty());
return queryResult.toList();
}
@Benchmark
@BenchmarkMode(Mode.AverageTime)
@OutputTimeUnit(TimeUnit.MICROSECONDS)
public void querySingleIncrementalIndex(Blackhole blackhole)
{
QueryRunner<Result<TopNResultValue>> runner = QueryBenchmarkUtil.makeQueryRunner(
factory,
SegmentId.dummy("incIndex"),
new IncrementalIndexSegment(incIndexes.get(0), SegmentId.dummy("incIndex"))
);
List<Result<TopNResultValue>> results = TopNBenchmark.runQuery(factory, runner, query);
blackhole.consume(results);
}
@Benchmark
@BenchmarkMode(Mode.AverageTime)
@OutputTimeUnit(TimeUnit.MICROSECONDS)
public void querySingleQueryableIndex(Blackhole blackhole)
{
final QueryRunner<Result<TopNResultValue>> runner = QueryBenchmarkUtil.makeQueryRunner(
factory,
SegmentId.dummy("qIndex"),
new QueryableIndexSegment(qIndexes.get(0), SegmentId.dummy("qIndex"))
);
List<Result<TopNResultValue>> results = TopNBenchmark.runQuery(factory, runner, query);
blackhole.consume(results);
}
@Benchmark
@BenchmarkMode(Mode.AverageTime)
@OutputTimeUnit(TimeUnit.MICROSECONDS)
public void queryMultiQueryableIndex(Blackhole blackhole)
{
List<QueryRunner<Result<TopNResultValue>>> singleSegmentRunners = new ArrayList<>();
QueryToolChest toolChest = factory.getToolchest();
for (int i = 0; i < numSegments; i++) {
SegmentId segmentId = SegmentId.dummy("qIndex" + i);
QueryRunner<Result<TopNResultValue>> runner = QueryBenchmarkUtil.makeQueryRunner(
factory,
segmentId,
new QueryableIndexSegment(qIndexes.get(i), segmentId)
);
singleSegmentRunners.add(toolChest.preMergeQueryDecoration(runner));
}
QueryRunner theRunner = toolChest.postMergeQueryDecoration(
new FinalizeResultsQueryRunner<>(
toolChest.mergeResults(factory.mergeRunners(executorService, singleSegmentRunners)),
toolChest
)
);
Sequence<Result<TopNResultValue>> queryResult = theRunner.run(
QueryPlus.wrap(query),
ResponseContext.createEmpty()
);
List<Result<TopNResultValue>> results = queryResult.toList();
blackhole.consume(results);
}
}
| |
/**
* Copyright 2014 Groupon.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.arpnetworking.configuration.jackson;
import com.arpnetworking.configuration.Configuration;
import com.arpnetworking.jackson.ObjectMapperFactory;
import com.arpnetworking.logback.annotations.LogValue;
import com.arpnetworking.steno.LogReferenceOnly;
import com.arpnetworking.steno.LogValueMapFactory;
import com.arpnetworking.utility.OvalBuilder;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.type.TypeFactory;
import com.google.common.base.Optional;
import net.sf.oval.constraint.NotNull;
import java.io.IOException;
import java.lang.reflect.Type;
/**
* Common base class for <code>Configuration</code> implementations based on
* Jackson's <code>ObjectMapper</code>.
*
* @author Ville Koskela (vkoskela at groupon dot com)
*/
public abstract class BaseJacksonConfiguration extends com.arpnetworking.configuration.BaseConfiguration {
/**
* {@inheritDoc}
*/
@Override
public Optional<String> getProperty(final String name) {
final Optional<JsonNode> jsonNode = getJsonSource().getValue(name.split("\\."));
if (jsonNode.isPresent()) {
return Optional.fromNullable(jsonNode.get().asText());
}
return Optional.absent();
}
/**
* {@inheritDoc}
*/
@Override
public <T> Optional<T> getPropertyAs(final String name, final Class<? extends T> clazz) throws IllegalArgumentException {
final Optional<String> property = getProperty(name);
if (!property.isPresent()) {
return Optional.absent();
}
try {
return Optional.fromNullable(_objectMapper.readValue(property.get(), clazz));
} catch (final IOException e) {
throw new IllegalArgumentException(
String.format(
"Unable to construct object from configuration; name=%s, class=%s, property=%s",
name,
clazz,
property),
e);
}
}
/**
* {@inheritDoc}
*/
@Override
public <T> Optional<T> getAs(final Class<? extends T> clazz) throws IllegalArgumentException {
final Optional<JsonNode> property = getJsonSource().getValue();
if (!property.isPresent()) {
return Optional.absent();
}
try {
return Optional.fromNullable(_objectMapper.treeToValue(property.get(), clazz));
} catch (final JsonProcessingException e) {
throw new IllegalArgumentException(
String.format(
"Unable to construct object from configuration; class=%s, property=%s",
clazz,
property),
e);
}
}
/**
* {@inheritDoc}
*/
@Override
public <T> Optional<T> getPropertyAs(final String name, final Type type) throws IllegalArgumentException {
final Optional<String> property = getProperty(name);
if (!property.isPresent()) {
return Optional.absent();
}
try {
final TypeFactory typeFactory = _objectMapper.getTypeFactory();
@SuppressWarnings("unchecked")
final Optional<T> value = Optional.fromNullable((T) _objectMapper.readValue(
property.get(),
typeFactory.constructType(type)));
return value;
} catch (final IOException e) {
throw new IllegalArgumentException(
String.format(
"Unable to construct object from configuration; name=%s, type=%s, property=%s",
name,
type,
property),
e);
}
}
/**
* {@inheritDoc}
*/
@Override
public <T> Optional<T> getAs(final Type type) throws IllegalArgumentException {
final Optional<JsonNode> property = getJsonSource().getValue();
if (!property.isPresent()) {
return Optional.absent();
}
try {
final TypeFactory typeFactory = _objectMapper.getTypeFactory();
@SuppressWarnings("unchecked")
final Optional<T> value = Optional.fromNullable((T) _objectMapper.readValue(
_objectMapper.treeAsTokens(property.get()), typeFactory.constructType(type)));
return value;
} catch (final IOException e) {
throw new IllegalArgumentException(
String.format(
"Unable to construct object from configuration; type=%s, property=%s",
type,
property),
e);
}
}
/**
* {@inheritDoc}
*/
@LogValue
@Override
public Object toLogValue() {
return LogValueMapFactory.of(
"super", super.toLogValue(),
"ObjectMapper", LogReferenceOnly.of(_objectMapper));
}
/**
* Accessor for active root <code>JsonSource</code> instance.
*
* @return Instance of <code>JsonSource</code>.
*/
protected abstract JsonNodeSource getJsonSource();
/**
* Protected constructor.
*
* @param builder The <code>Builder</code> instance to construct from.
*/
protected BaseJacksonConfiguration(final Builder<?, ?> builder) {
_objectMapper = builder._objectMapper;
}
protected final ObjectMapper _objectMapper;
/**
* Builder for <code>BaseObjectMapperConfiguration</code>.
*/
protected abstract static class Builder<T extends Builder<?, ?>, S extends Configuration> extends OvalBuilder<S> {
/**
* Protected constructor.
*
* @param clazz The target <code>Class</code> to build.
*/
protected Builder(final Class<S> clazz) {
super(clazz);
}
/**
* Set the <code>ObjectMapper</code> instance. Optional. Default is
* created by <code>ObjectMapperFactory</code>. Cannot be null.
*
* @param value The <code>ObjectMapper</code> instance.
* @return This <code>Builder</code> instance.
*/
public T setObjectMapper(final ObjectMapper value) {
_objectMapper = value;
return self();
}
/**
* Called by setters to always return appropriate subclass of
* <code>Builder</code>, even from setters of base class.
*
* @return instance with correct <code>Builder</code> class type.
*/
protected abstract T self();
@NotNull
private ObjectMapper _objectMapper = ObjectMapperFactory.getInstance();
}
}
| |
/*
* Copyright 2015 Red Hat, Inc. and/or its affiliates.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
*
* 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.kie.scanner;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashSet;
import java.util.List;
import org.appformer.maven.integration.MavenRepository;
import org.appformer.maven.support.DependencyFilter;
import org.drools.compiler.compiler.io.memory.MemoryFileSystem;
import org.drools.compiler.kie.builder.impl.InternalKieModule;
import org.drools.compiler.kie.builder.impl.KieContainerImpl;
import org.drools.compiler.kie.builder.impl.KieRepositoryImpl;
import org.drools.compiler.kie.builder.impl.KieServicesImpl;
import org.drools.core.factmodel.ClassDefinition;
import org.drools.core.factmodel.FieldDefinition;
import org.drools.mvel.asm.DefaultBeanClassBuilder;
import org.junit.Test;
import org.kie.api.KieBase;
import org.kie.api.KieServices;
import org.kie.api.builder.KieBuilder;
import org.kie.api.builder.KieFileSystem;
import org.kie.api.builder.KieModule;
import org.kie.api.builder.KieRepository;
import org.kie.api.builder.ReleaseId;
import org.kie.api.builder.model.KieBaseModel;
import org.kie.api.definition.KiePackage;
import org.kie.api.definition.rule.Rule;
import org.kie.api.runtime.KieContainer;
import org.kie.api.runtime.KieSession;
import org.kie.internal.utils.KieTypeResolver;
import static org.appformer.maven.integration.MavenRepository.getMavenRepository;
import static org.drools.core.util.DroolsAssert.assertEnumerationSize;
import static org.drools.core.util.DroolsAssert.assertUrlEnumerationContainsMatch;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
public class KieModuleMavenTest extends AbstractKieCiTest {
@Test
public void testKieModuleFromMavenNoDependencies() throws Exception {
final KieServices ks = new KieServicesImpl() {
@Override
public KieRepository getRepository() {
return new KieRepositoryImpl(); // override repository to not store the artifact on deploy to trigger load from maven repo
}
};
ReleaseId releaseId = ks.newReleaseId("org.kie", "maven-test", "1.0-SNAPSHOT");
InternalKieModule kJar1 = createKieJar(ks, releaseId, true, "rule1", "rule2");
String pomText = getPom(releaseId);
File pomFile = new File( System.getProperty("java.io.tmpdir"), MavenRepository.toFileName( releaseId, null ) + ".pom");
try {
FileOutputStream fos = new FileOutputStream(pomFile);
fos.write(pomText.getBytes());
fos.flush();
fos.close();
} catch (IOException e) {
throw new RuntimeException(e);
}
KieMavenRepository.getKieMavenRepository().installArtifact(releaseId, kJar1, pomFile);
KieContainer kieContainer = ks.newKieContainer(releaseId);
KieBaseModel kbaseModel = ((KieContainerImpl) kieContainer).getKieProject().getDefaultKieBaseModel();
assertNotNull("Default kbase was not found", kbaseModel);
String kbaseName = kbaseModel.getName();
assertEquals("KBase1", kbaseName);
// Check classloader
assertUrlEnumerationContainsMatch(".*org/kie/maven\\-test/1.0\\-SNAPSHOT.*", kieContainer.getClassLoader().getResources(""));
assertUrlEnumerationContainsMatch(".*org/kie/maven\\-test/1.0\\-SNAPSHOT.*", kieContainer.getClassLoader().getResources("KBase1/org/test"));
assertUrlEnumerationContainsMatch(".*org/kie/maven\\-test/1.0\\-SNAPSHOT.*", kieContainer.getClassLoader().getResources("KBase1/org/test/"));
}
@Test
public void testKieModuleFromMavenWithDependencies() throws Exception {
final KieServices ks = new KieServicesImpl() {
@Override
public KieRepository getRepository() {
return new KieRepositoryImpl(); // override repository to not store the artifact on deploy to trigger load from maven repo
}
};
ReleaseId dependency = ks.newReleaseId("org.drools", "drools-core", "5.5.0.Final");
ReleaseId releaseId = ks.newReleaseId("org.kie", "maven-test", "1.0-SNAPSHOT");
InternalKieModule kJar1 = createKieJar(ks, releaseId, true, "rule1", "rule2");
String pomText = getPom(releaseId, dependency);
File pomFile = new File(System.getProperty("java.io.tmpdir"), MavenRepository.toFileName(releaseId, null) + ".pom");
try {
FileOutputStream fos = new FileOutputStream(pomFile);
fos.write(pomText.getBytes());
fos.flush();
fos.close();
} catch (IOException e) {
throw new RuntimeException(e);
}
KieMavenRepository.getKieMavenRepository().installArtifact(releaseId, kJar1, pomFile);
KieContainer kieContainer = ks.newKieContainer(releaseId);
KieBaseModel kbaseModel = ((KieContainerImpl) kieContainer).getKieProject().getDefaultKieBaseModel();
assertNotNull("Default kbase was not found", kbaseModel);
String kbaseName = kbaseModel.getName();
assertEquals("KBase1", kbaseName);
}
@Test
public void testKieModuleFromMavenWithTransitiveDependencies() throws Exception {
final KieServices ks = new KieServicesImpl() {
@Override
public KieRepository getRepository() {
return new KieRepositoryImpl(); // override repository to not store the artifact on deploy to trigger load from maven repo
}
};
ReleaseId dependency = ks.newReleaseId("org.drools", "drools-core", "5.5.0.Final");
ReleaseId releaseId = ks.newReleaseId("org.kie", "maven-test", "1.0-SNAPSHOT");
String pomText = getPom(releaseId, dependency);
InternalKieModule kJar1 = createKieJar(ks, releaseId, pomText, true, "rule1", "rule2");
File pomFile = new File(System.getProperty("java.io.tmpdir"), MavenRepository.toFileName(releaseId, null) + ".pom");
try {
FileOutputStream fos = new FileOutputStream(pomFile);
fos.write(pomText.getBytes());
fos.flush();
fos.close();
} catch (IOException e) {
throw new RuntimeException(e);
}
KieMavenRepository.getKieMavenRepository().installArtifact(releaseId, kJar1, pomFile);
KieContainer kieContainer = ks.newKieContainer(releaseId);
Collection<ReleaseId> expectedDependencies = new HashSet<ReleaseId>();
expectedDependencies.add(ks.newReleaseId("org.drools", "knowledge-api", "5.5.0.Final"));
expectedDependencies.add(ks.newReleaseId("org.drools", "knowledge-internal-api", "5.5.0.Final"));
expectedDependencies.add(ks.newReleaseId("org.drools", "drools-core", "5.5.0.Final"));
expectedDependencies.add(ks.newReleaseId("org.mvel", "mvel2", "2.1.3.Final"));
expectedDependencies.add(ks.newReleaseId("org.slf4j", "slf4j-api", "1.6.4"));
Collection<ReleaseId> dependencies = ((InternalKieModule)((KieContainerImpl) kieContainer)
.getKieModuleForKBase( "KBase1" ))
.getJarDependencies( DependencyFilter.TAKE_ALL_FILTER );
assertNotNull(dependencies);
assertEquals(5, dependencies.size());
ClassLoader kieContainerCL = kieContainer.getClassLoader();
assertTrue("Kie Container class loader must be of KieTypeResolver type", kieContainerCL instanceof KieTypeResolver);
assertTrue("Kie Container parent class loader must be of KieTypeResolver type", kieContainerCL.getParent() instanceof KieTypeResolver);
boolean matchedAll = dependencies.containsAll(expectedDependencies);
assertTrue(matchedAll);
}
@Test
public void testKieModulePojoDependencies() throws Exception {
KieServices ks = KieServices.Factory.get();
// Create and deploy a standard mavenized pojo jar
String pojoNS = "org.kie.pojos";
ReleaseId pojoID = KieServices.Factory.get().newReleaseId(pojoNS, "pojojar", "2.0.0");
String className = "Message";
ClassDefinition def = new ClassDefinition(pojoNS + "." + className);
def.addField(new FieldDefinition("text", String.class.getName()));
byte[] messageClazz = new DefaultBeanClassBuilder(true).buildClass(def,null);
MemoryFileSystem mfs = new MemoryFileSystem();
mfs.write(pojoNS.replace('.', '/') + "/" + className+".class", messageClazz);
byte[] pomContent = generatePomXml(pojoID).getBytes();
mfs.write("META-INF/maven/" + pojoID.getGroupId() + "/" + pojoID.getArtifactId() + "/pom.xml", pomContent);
mfs.write("META-INF/maven/" + pojoID.getGroupId() + "/" + pojoID.getArtifactId() + "/pom.properties", generatePomProperties(pojoID).getBytes());
byte[] pojojar = mfs.writeAsBytes();
MavenRepository.getMavenRepository().installArtifact(pojoID, pojojar, pomContent);
// Create and deploy a kjar that depends on the previous pojo jar
String kjarNS = "org.kie.test1";
ReleaseId kjarID = KieServices.Factory.get().newReleaseId(kjarNS, "rkjar", "1.0.0");
String rule = getRule(kjarNS, pojoNS, "R1");
String pom = generatePomXml(kjarID, pojoID);
byte[] rkjar = createKJar(ks, kjarID, pom, rule);
KieModule kmodule = deployJar(ks, rkjar);
assertNotNull(kmodule);
KieContainer kContainer = ks.newKieContainer(kjarID);
KieSession kSession = kContainer.newKieSession();
List<?> list = new ArrayList<Object>();
kSession.setGlobal("list", list);
kSession.fireAllRules();
assertEquals(1, list.size());
}
@Test
public void testKieContainerBeforeAndAfterDeployOfSnapshot() throws Exception {
// BZ-1007977
KieServices ks = KieServices.Factory.get();
String group = "org.kie.test";
String artifact = "test-module";
String version = "1.0.0-SNAPSHOT";
ReleaseId releaseId = ks.newReleaseId(group, artifact, version);
String prefix = new File(".").getAbsolutePath().contains("kie-ci") ? "" : "kie-ci/";
File kjar = new File(prefix + "src/test/resources/kjar/kjar-module-before.jar");
File pom = new File(prefix + "src/test/resources/kjar/pom-kjar.xml");
MavenRepository repository = getMavenRepository();
repository.installArtifact(releaseId, kjar, pom);
KieContainer kContainer = ks.newKieContainer(releaseId);
KieBase kbase = kContainer.getKieBase();
assertNotNull(kbase);
Collection<KiePackage> packages = kbase.getKiePackages();
assertNotNull(packages);
assertEquals(1, packages.size());
Collection<Rule> rules = packages.iterator().next().getRules();
assertEquals(2, rules.size());
ks.getRepository().removeKieModule(releaseId);
// deploy new version
File kjar1 = new File(prefix + "src/test/resources/kjar/kjar-module-after.jar");
File pom1 = new File(prefix + "src/test/resources/kjar/pom-kjar.xml");
repository.installArtifact(releaseId, kjar1, pom1);
KieContainer kContainer2 = ks.newKieContainer(releaseId);
KieBase kbase2 = kContainer2.getKieBase();
assertNotNull(kbase2);
Collection<KiePackage> packages2 = kbase2.getKiePackages();
assertNotNull(packages2);
assertEquals(1, packages2.size());
Collection<Rule> rules2 = packages2.iterator().next().getRules();
assertEquals(4, rules2.size());
ks.getRepository().removeKieModule(releaseId);
}
@Test
public void testKieModuleFromMavenWithDependenciesProperties() throws Exception {
final KieServices ks = new KieServicesImpl() {
@Override
public KieRepository getRepository() {
return new KieRepositoryImpl(); // override repository to not store the artifact on deploy to trigger load from maven repo
}
};
ReleaseId dependency = ks.newReleaseId("org.drools", "drools-core", "${version.org.drools}");
ReleaseId releaseId = ks.newReleaseId("org.kie.test", "maven-test", "1.0-SNAPSHOT");
InternalKieModule kJar1 = createKieJarWithProperties(ks, releaseId, true, "5.5.0.Final", new ReleaseId[]{dependency}, "rule1", "rule2");
String pomText = generatePomXmlWithProperties(releaseId, "5.5.0.Final", dependency);
File pomFile = new File(System.getProperty("java.io.tmpdir"), MavenRepository.toFileName(releaseId, null) + ".pom");
try {
FileOutputStream fos = new FileOutputStream(pomFile);
fos.write(pomText.getBytes());
fos.flush();
fos.close();
} catch (IOException e) {
throw new RuntimeException(e);
}
KieMavenRepository.getKieMavenRepository().installArtifact(releaseId, kJar1, pomFile);
KieContainer kieContainer = ks.newKieContainer(releaseId);
KieBaseModel kbaseModel = ((KieContainerImpl) kieContainer).getKieProject().getDefaultKieBaseModel();
assertNotNull("Default kbase was not found", kbaseModel);
String kbaseName = kbaseModel.getName();
assertEquals("KBase1", kbaseName);
}
@Test
public void testResourceTypeInKieModuleReleaseId() throws Exception {
final KieServices ks = new KieServicesImpl() {
@Override
public KieRepository getRepository() {
return new KieRepositoryImpl(); // override repository to not store the artifact on deploy to trigger load from maven repo
}
};
ReleaseId releaseId = ks.newReleaseId("org.kie", "maven-test.drl", "1.0-SNAPSHOT");
InternalKieModule kJar1 = createKieJar(ks, releaseId, true, "rule1", "rule2");
String pomText = getPom(releaseId);
File pomFile = new File(System.getProperty("java.io.tmpdir"), MavenRepository.toFileName(releaseId, null) + ".pom");
try {
FileOutputStream fos = new FileOutputStream(pomFile);
fos.write(pomText.getBytes());
fos.flush();
fos.close();
} catch (IOException e) {
throw new RuntimeException(e);
}
KieMavenRepository.getKieMavenRepository().installArtifact(releaseId, kJar1, pomFile);
KieContainer kieContainer = ks.newKieContainer(releaseId);
KieBase kieBase = kieContainer.getKieBase("KBase1");
assertNotNull(kieBase);
assertEquals("There must be one package built", 1, kieBase.getKiePackages().size());
ClassLoader classLoader = kieContainer.getClassLoader();
assertEnumerationSize(1, classLoader.getResources("KBase1/org/test"));
assertEnumerationSize(1, classLoader.getResources("META-INF/maven/org.kie/maven-test.drl"));
}
public static String generatePomXml(ReleaseId releaseId, ReleaseId... dependencies) {
StringBuilder sBuilder = new StringBuilder();
sBuilder.append("<project xmlns=\"http://maven.apache.org/POM/4.0.0\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" \n");
sBuilder.append(" xsi:schemaLocation=\"http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd\"> \n");
sBuilder.append(" <modelVersion>4.0.0</modelVersion> \n");
sBuilder.append(" <groupId>").append(releaseId.getGroupId()).append("</groupId> \n");
sBuilder.append(" <artifactId>").append(releaseId.getArtifactId()).append("</artifactId> \n");
sBuilder.append(" <version>").append(releaseId.getVersion()).append("</version> \n");
sBuilder.append(" <packaging>jar</packaging> \n");
sBuilder.append(" <name>Default</name> \n");
if (dependencies.length > 0) {
sBuilder.append("<dependencies>\n");
for (ReleaseId dep : dependencies) {
sBuilder.append(" <dependency>\n");
sBuilder.append(" <groupId>").append(dep.getGroupId()).append("</groupId> \n");
sBuilder.append(" <artifactId>").append(dep.getArtifactId()).append("</artifactId> \n");
sBuilder.append(" <version>").append(dep.getVersion()).append("</version> \n");
sBuilder.append(" </dependency>\n");
}
sBuilder.append("</dependencies>\n");
}
sBuilder.append("</project> \n");
return sBuilder.toString();
}
public static String generatePomXmlWithProperties(ReleaseId releaseId, String droolsVersion, ReleaseId... dependencies) {
StringBuilder sBuilder = new StringBuilder();
sBuilder.append("<project xmlns=\"http://maven.apache.org/POM/4.0.0\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" \n");
sBuilder.append(" xsi:schemaLocation=\"http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd\"> \n");
sBuilder.append(" <modelVersion>4.0.0</modelVersion> \n");
sBuilder.append(" <groupId>").append(releaseId.getGroupId()).append("</groupId> \n");
sBuilder.append(" <artifactId>").append(releaseId.getArtifactId()).append("</artifactId> \n");
sBuilder.append(" <version>").append(releaseId.getVersion()).append("</version> \n");
sBuilder.append(" <packaging>jar</packaging> \n");
sBuilder.append(" <name>Default</name> \n");
sBuilder.append(" <properties> \n");
sBuilder.append(" <version.org.drools>"+droolsVersion+"</version.org.drools> \n");
sBuilder.append(" </properties> \n");
if (dependencies.length > 0) {
sBuilder.append("<dependencies>\n");
for (ReleaseId dep : dependencies) {
sBuilder.append(" <dependency>\n");
sBuilder.append(" <groupId>").append(dep.getGroupId()).append("</groupId> \n");
sBuilder.append(" <artifactId>").append(dep.getArtifactId()).append("</artifactId> \n");
sBuilder.append(" <version>").append(dep.getVersion()).append("</version> \n");
sBuilder.append(" </dependency>\n");
}
sBuilder.append("</dependencies>\n");
}
sBuilder.append("</project> \n");
return sBuilder.toString();
}
protected InternalKieModule createKieJarWithProperties(KieServices ks, ReleaseId releaseId, boolean isdefault,
String droolsVersion, ReleaseId[] dependencies, String... rules) throws IOException {
KieFileSystem kfs = createKieFileSystemWithKProject(ks, isdefault);
kfs.writePomXML(generatePomXmlWithProperties(releaseId, droolsVersion, dependencies));
for (String rule : rules) {
String file = "org/test/" + rule + ".drl";
kfs.write("src/main/resources/KBase1/" + file, createDRL(rule));
}
KieBuilder kieBuilder = ks.newKieBuilder(kfs);
assertTrue(kieBuilder.buildAll().getResults().getMessages().isEmpty());
return (InternalKieModule) kieBuilder.getKieModule();
}
public static String generatePomProperties(ReleaseId releaseId) {
StringBuilder sBuilder = new StringBuilder();
sBuilder.append("version=").append(releaseId.getVersion()).append("\n");
sBuilder.append("groupId=").append(releaseId.getGroupId()).append("\n");
sBuilder.append("artifactId=").append(releaseId.getArtifactId()).append("\n");
return sBuilder.toString();
}
public String getRule(String namespace,
String messageNS,
String ruleName) {
String s = "package " + namespace + "\n" +
"import " + messageNS + ".Message\n" +
"global java.util.List list\n" +
"rule " + ruleName + " when \n" +
"then \n" +
" Message msg = new Message('hello');\n" +
" list.add(msg);\n " +
"end \n" +
"";
return s;
}
}
| |
package org.xtuml.bp.ui.canvas.test;
//=====================================================================
// 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.
//=====================================================================
//
//This class is responsible for performing part of the automatic test
//of the Graphics Domain by forcing the canvas source through its error
//paths.
//
import java.io.File;
import java.util.UUID;
import org.eclipse.core.runtime.IPath;
import org.eclipse.core.runtime.Path;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.xtuml.bp.core.Association_c;
import org.xtuml.bp.core.ExternalEntity_c;
import org.xtuml.bp.core.ImportedClass_c;
import org.xtuml.bp.core.InstanceStateMachine_c;
import org.xtuml.bp.core.ModelClass_c;
import org.xtuml.bp.core.Ooaofooa;
import org.xtuml.bp.core.StateMachineState_c;
import org.xtuml.bp.core.Transition_c;
import org.xtuml.bp.core.common.IdAssigner;
import org.xtuml.bp.test.common.BaseTest;
import org.xtuml.bp.test.common.OrderedRunner;
import org.xtuml.bp.ui.canvas.Cl_c;
import junit.framework.TestCase;
@RunWith(OrderedRunner.class)
public class ErrorPathsTest extends TestCase {
Ooaofooa modelRoot = BaseTest.getDefaultTestInstance();
private static String m_logfile_path = "";
public ErrorPathsTest() {
super();
}
@Before
public void setUp() throws Exception {
super.setUp();
if (m_logfile_path == null || m_logfile_path.equals(""))
{
m_logfile_path = System.getProperty("LOGFILE_PATH"); //$NON-NLS-1$
}
assertNotNull( m_logfile_path );
}
private boolean logFilePresent()
{
IPath in_path = new Path(m_logfile_path);
File in_fh = in_path.toFile();
boolean ret_val = in_fh.exists();
if ( ret_val )
{
in_fh.delete();
}
return ret_val;
}
/**
* The following tests are disabled until we remove the comment in
*
* Cl_c.findMethod() -
* // TODO: ClientNotFound operations are ignored right now because
* // OAL added in operations made inside GD_ARS.Reconcile are being made
* @throws Exception
*/
// @Test
// public void testGetConnectorText() throws Exception {
// // Method not implemented
// String text = Cl_c.Getconnectortext(0, IdAssigner.NULL_UUID, false, new Object(), IdAssigner.NULL_UUID);
// assertEquals("", text);
// assertTrue("Log file is not present", logFilePresent());
// // A class created by method is private
// text = Cl_c.Getconnectortext(0, IdAssigner.NULL_UUID, false, new Association_c(modelRoot) {
// public String Get_connector_text(UUID ooa_id, boolean ooa_type, int At, UUID parent_id) {
// try {
// Object testItem = Class.forName("org.xtuml.bp.core.EV_ACCESS_PATH");
// }
// catch (ClassNotFoundException e) {
// // Should find it OK
// }
// return "";
// }}, IdAssigner.NULL_UUID);
// assertEquals("", text);
// assertTrue("Log file is not present", logFilePresent());
// // Method throws an exception
// Tester target = new Tester();
// text = Cl_c.Getconnectortext(0, IdAssigner.NULL_UUID, false, target, IdAssigner.NULL_UUID);
// assertEquals("", text);
// assertTrue("Log file is not present", logFilePresent());
// }
// @Test
// public void testGetCompartmentText() throws Exception {
// // Method not implemented
// String text = Cl_c.Getcompartmenttext(0, 0, 0, new Object());
// assertEquals("", text);
// assertTrue("Log file is not present", logFilePresent());
// // A class created by method is private
// text = Cl_c.Getcompartmenttext(0, 0, 0, new Association_c(modelRoot) {
// public String Get_compartment_text(int comp_id, int entry_id, int At) {
// try {
// Object testItem = Class.forName("org.xtuml.bp.core.EV_ACCESS_PATH");
// }
// catch (ClassNotFoundException e) {
// // Should find it OK
// }
// return "";
// }});
// assertEquals("", text);
// assertTrue("Log file is not present", logFilePresent());
// // Method throws an exception
// Tester target = new Tester();
// text = Cl_c.Getcompartmenttext(0, 0, 0, target);
// assertEquals("", text);
// assertTrue("Log file is not present", logFilePresent());
// }
// @Test
// public void testGetCompartments() throws Exception {
// int testVal = -1;
// testVal = Cl_c.Getcompartments(new Object());
// assertEquals(0, testVal);
// assertTrue("Log file is not present", logFilePresent());
// // A class created by method is private
// testVal = Cl_c.Getcompartments(new Association_c(modelRoot) {
// public String Get_compartments() {
// try {
// Object testItem = Class.forName("org.xtuml.bp.core.EV_ACCESS_PATH");
// }
// catch (ClassNotFoundException e) {
// // Should find it OK
// }
// return "";
// }});
// assertEquals(0, testVal);
// assertTrue("Log file is not present", logFilePresent());
// // Method throws an exception
// Tester target = new Tester();
// testVal = Cl_c.Getcompartments(target);
// assertEquals(0, testVal);
// assertTrue("Log file is not present", logFilePresent());
// }
// @Test
// public void testGetConnectorStyle() throws Exception {
// int testVal = -1;
// testVal = Cl_c.Getconnectorstyle(0, new Object());
// assertEquals(0, testVal);
// assertTrue("Log file is not present", logFilePresent());
// // A class created by method is private
// testVal = Cl_c.Getconnectorstyle(0, new Association_c(modelRoot) {
// public int Get_style(int At) {
// try {
// Object testItem = Class.forName("org.xtuml.bp.core.EV_ACCESS_PATH");
// }
// catch (ClassNotFoundException e) {
// // Should find it OK
// }
// return 0;
// }});
// assertEquals(0, testVal);
// assertTrue("Log file is not present", logFilePresent());
// // Method throws an exception
// Tester target = new Tester();
// testVal = Cl_c.Getconnectorstyle(0, target);
// assertEquals(0, testVal);
// assertTrue("Log file is not present", logFilePresent());
// }
@Test
public void testGetOOA_IDfromInstance() throws Exception {
ExternalEntity_c ee = new ExternalEntity_c(modelRoot);
UUID ee_id = Cl_c.Getooa_idfrominstance(ee);
assertTrue( !ee_id.equals(IdAssigner.MAX_UUID) );
ModelClass_c obj = new ModelClass_c(modelRoot);
UUID obj_id = Cl_c.Getooa_idfrominstance(obj);
assertTrue( !obj_id.equals(IdAssigner.MAX_UUID) );
ImportedClass_c iobj = new ImportedClass_c(modelRoot);
UUID iobj_id = Cl_c.Getooa_idfrominstance(iobj);
assertTrue( !iobj_id.equals(IdAssigner.MAX_UUID) );
Association_c rel = new Association_c(modelRoot);
UUID rel_id = Cl_c.Getooa_idfrominstance(rel);
assertTrue( !rel_id.equals(IdAssigner.MAX_UUID) );
StateMachineState_c sms = new StateMachineState_c(modelRoot);
UUID sm_id = Cl_c.Getooa_idfrominstance(sms);
assertTrue( !sm_id.equals(IdAssigner.MAX_UUID) );
Transition_c tr = new Transition_c(modelRoot);
UUID tr_id = Cl_c.Getooa_idfrominstance(tr);
assertTrue( !tr_id.equals(IdAssigner.MAX_UUID) );
InstanceStateMachine_c ism = new InstanceStateMachine_c(modelRoot);
UUID ism_id = Cl_c.Getooa_idfrominstance(ism);
assertTrue( !ism_id.equals(IdAssigner.MAX_UUID) );
}
}
| |
/**
* Copyright (c) 2016, Geanina Mihalea <geanina.mihalea@gmail.com>.
* 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.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package client.view;
import client.actions.*;
import client.util.ViewConstants;
import javax.swing.*;
import java.awt.*;
import java.util.ArrayList;
/**
* Class that incapsulates the main frame of the application.
*/
public class MatchMeView extends JFrame{
private ArrayList<JLabel> labels = new ArrayList<>();
public MatchMeView() {
initUI();
}
public final void initUI() {
setLayout(null);
setTitle(ViewConstants.MATCH_ME_TITLE);
setSize(ViewConstants.FORM_WIDTH, ViewConstants.FORM_HEIGHT);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLocationRelativeTo(null);
setLocation(ViewConstants.X_TO_START, ViewConstants.Y_TO_START);
setResizable(false);
/**
* Menu Bar
*/
JMenuBar menuBar = new JMenuBar();
setJMenuBar(menuBar);
JMenu fileMenu = new JMenu(ViewConstants.FILE);
JMenu helpMenu = new JMenu(ViewConstants.HELP);
menuBar.add(fileMenu);
menuBar.add(helpMenu);
JMenuItem newAction = new JMenuItem(ViewConstants.NEW);
JMenuItem exitAction = new JMenuItem(ViewConstants.EXIT);
fileMenu.add(newAction);
fileMenu.add(exitAction);
JMenuItem gettingStartedAction = new JMenuItem(ViewConstants.GETTING_STARTED);
JMenuItem aboutAction = new JMenuItem(ViewConstants.ABOUT);
helpMenu.add(gettingStartedAction);
helpMenu.add(aboutAction);
/**
* Labels
*/
JLabel mentorsLabel = new JLabel(ViewConstants.MENTORS);
mentorsLabel.setBounds(ViewConstants.X_POSITION_LAYER_ONE, ViewConstants.Y_POSITION_LAYER_ONE,
ViewConstants.WIDTH, ViewConstants.HEIGHT);
JLabel menteesLabel = new JLabel(ViewConstants.MENTEES);
menteesLabel.setBounds(ViewConstants.X_POSITION_LAYER_ONE + ViewConstants.DISTANCE_HORIZONTAL_BETWEEN_LAYERS,
ViewConstants.Y_POSITION_LAYER_ONE,
ViewConstants.WIDTH, ViewConstants.HEIGHT);
JLabel constraintsLabel = new JLabel(ViewConstants.CONSTRAINTS);
constraintsLabel.setBounds(ViewConstants.X_POSITION_LAYER_ONE
+ 2 * ViewConstants.DISTANCE_HORIZONTAL_BETWEEN_LAYERS, ViewConstants.Y_POSITION_LAYER_ONE,
ViewConstants.WIDTH, ViewConstants.HEIGHT);
JLabel mentorsFileName = new JLabel(ViewConstants.EMPTY_STRING);
mentorsFileName.setBounds(ViewConstants.X_POSITION_LAYER_ONE,
ViewConstants.Y_POSITION_LAYER_ONE + 2 * ViewConstants.DISTANCE_BUTTON_LABEL,
ViewConstants.WIDTH, ViewConstants.HEIGHT);
mentorsFileName.setForeground(Color.GRAY);
this.labels.add(mentorsFileName);
JLabel menteesFileName = new JLabel(ViewConstants.EMPTY_STRING);
menteesFileName.setBounds(ViewConstants.X_POSITION_LAYER_ONE
+ ViewConstants.DISTANCE_HORIZONTAL_BETWEEN_LAYERS,
ViewConstants.Y_POSITION_LAYER_ONE + 2 * ViewConstants.DISTANCE_BUTTON_LABEL,
ViewConstants.WIDTH, ViewConstants.HEIGHT);
menteesFileName.setForeground(Color.GRAY);
this.labels.add(menteesFileName);
JLabel constraintsFileName = new JLabel(ViewConstants.EMPTY_STRING);
constraintsFileName.setBounds(ViewConstants.X_POSITION_LAYER_ONE
+ 2 * ViewConstants.DISTANCE_HORIZONTAL_BETWEEN_LAYERS,
ViewConstants.Y_POSITION_LAYER_ONE + 2 * ViewConstants.DISTANCE_BUTTON_LABEL,
ViewConstants.WIDTH, ViewConstants.HEIGHT);
constraintsFileName.setForeground(Color.GRAY);
this.labels.add(constraintsFileName);
JLabel errorLabel = new JLabel(ViewConstants.EMPTY_STRING);
errorLabel.setBounds(ViewConstants.X_MATCH_BUTTON, ViewConstants.Y_MATCH_BUTTON
+ ViewConstants.DISTANCE_BUTTON_LABEL, 3 * ViewConstants.BUTTON_WIDTH, ViewConstants.HEIGHT);
errorLabel.setForeground(Color.RED);
this.labels.add(errorLabel);
add(mentorsLabel);
add(menteesLabel);
add(constraintsLabel);
add(mentorsFileName);
add(menteesFileName);
add(constraintsFileName);
add(errorLabel);
/**
* Buttons
*/
JButton browseMentorsButton = new JButton(ViewConstants.BROWSE);
browseMentorsButton.setBounds(ViewConstants.X_POSITION_LAYER_ONE,
ViewConstants.Y_POSITION_LAYER_ONE + ViewConstants.DISTANCE_BUTTON_LABEL,
ViewConstants.BUTTON_WIDTH, ViewConstants.HEIGHT);
JButton browseMenteesButton = new JButton(ViewConstants.BROWSE);
browseMenteesButton.setBounds(ViewConstants.X_POSITION_LAYER_ONE
+ ViewConstants.DISTANCE_HORIZONTAL_BETWEEN_LAYERS,
ViewConstants.Y_POSITION_LAYER_ONE + ViewConstants.DISTANCE_BUTTON_LABEL,
ViewConstants.BUTTON_WIDTH, ViewConstants.HEIGHT);
JButton browseConstraintsButton = new JButton(ViewConstants.BROWSE);
browseConstraintsButton.setBounds(ViewConstants.X_POSITION_LAYER_ONE
+ 2 * ViewConstants.DISTANCE_HORIZONTAL_BETWEEN_LAYERS,
ViewConstants.Y_POSITION_LAYER_ONE + ViewConstants.DISTANCE_BUTTON_LABEL,
ViewConstants.BUTTON_WIDTH, ViewConstants.HEIGHT);
JButton matchButton = new JButton(ViewConstants.MATCH);
matchButton.setBounds(ViewConstants.X_MATCH_BUTTON, ViewConstants.Y_MATCH_BUTTON,
2 * ViewConstants.BUTTON_WIDTH, ViewConstants.HEIGHT);
JButton downloadResultsButton = new JButton(ViewConstants.DOWNLOAD_RESULTS);
downloadResultsButton.setBounds(ViewConstants.X_POSITION_LAYER_ONE + ViewConstants.PADDING_X_DOWNLOAD_BUTTON,
ViewConstants.Y_MATCH_BUTTON + ViewConstants.DISTANCE_VERTICAL_BETWEEN_LAYERS
+ ViewConstants.TABLE_HEIGHT + ViewConstants.DISTANCE_BUTTON_BUTTON + 10,
2 * ViewConstants.BUTTON_WIDTH, ViewConstants.HEIGHT);
JButton showStatisticsButton = new JButton(ViewConstants.SHOW_STATISTICS);
showStatisticsButton.setBounds(ViewConstants.X_POSITION_LAYER_ONE + ViewConstants.PADDING_X_STATISTICS_BUTTON,
ViewConstants.Y_MATCH_BUTTON + ViewConstants.DISTANCE_VERTICAL_BETWEEN_LAYERS
+ ViewConstants.TABLE_HEIGHT + ViewConstants.DISTANCE_BUTTON_BUTTON + 10,
2 * ViewConstants.BUTTON_WIDTH, ViewConstants.HEIGHT);
JButton downloadStatisticsButton = new JButton(ViewConstants.EXPORT_STATISTICS);
downloadStatisticsButton.setBounds(ViewConstants.X_POSITION_LAYER_ONE + ViewConstants.PADDING_X_DOWNLOAD_BUTTON,
ViewConstants.Y_MATCH_BUTTON + ViewConstants.DISTANCE_VERTICAL_BETWEEN_LAYERS
+ ViewConstants.TABLE_HEIGHT + ViewConstants.DISTANCE_BUTTON_BUTTON - 10
+ ViewConstants.PADDING_Y_STATISTISC_BUTTON,
2 * ViewConstants.BUTTON_WIDTH, ViewConstants.HEIGHT);
JButton hideStatisticsButton = new JButton(ViewConstants.HIDE_STATISTICS);
hideStatisticsButton.setBounds(ViewConstants.X_POSITION_LAYER_ONE + ViewConstants.PADDING_X_STATISTICS_BUTTON,
ViewConstants.Y_MATCH_BUTTON + ViewConstants.DISTANCE_VERTICAL_BETWEEN_LAYERS
+ ViewConstants.TABLE_HEIGHT + ViewConstants.DISTANCE_BUTTON_BUTTON
+ ViewConstants.PADDING_Y_STATISTISC_BUTTON - 10,
2 * ViewConstants.BUTTON_WIDTH, ViewConstants.HEIGHT);
add(browseMentorsButton);
add(browseMenteesButton);
add(browseConstraintsButton);
add(matchButton);
add(downloadResultsButton);
add(showStatisticsButton);
add(downloadStatisticsButton);
add(hideStatisticsButton);
/**
* Actions
*/
browseMentorsButton.addActionListener(e -> UploadFileAction.selectFile(mentorsFileName,
this, ViewConstants.MENTOR));
browseMenteesButton.addActionListener(e -> UploadFileAction.selectFile(menteesFileName,
this, ViewConstants.MENTEE));
browseConstraintsButton.addActionListener(e -> UploadFileAction.selectFile(constraintsFileName,
this, ViewConstants.CONSTRAINT));
newAction.addActionListener(e -> MenuAction.newAction(this.labels, this));
exitAction.addActionListener(e -> MenuAction.exitAction());
matchButton.addActionListener(e -> MatchDataAction.match(mentorsFileName, menteesFileName,
constraintsFileName, errorLabel, this));
downloadResultsButton.addActionListener(e -> ExportDataAction.saveFile(this,
MatchDataAction.getMatchingTable(), ViewConstants.SUGGESTED_RESULTS_FILE_NAME));
downloadStatisticsButton.addActionListener(e -> ExportDataAction.saveFile(this,
StatisticsAction.getStatisticsTable(), ViewConstants.SUGGESTED_STATISTICS_FILE_NAME));
showStatisticsButton.addActionListener(e -> StatisticsAction.showStatistics(this));
hideStatisticsButton.addActionListener(e -> StatisticsAction.hideStatistics(this));
gettingStartedAction.addActionListener(e -> MenuAction.gettingStarted());
aboutAction.addActionListener(e -> MenuAction.about());
}
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> {
MatchMeView mainForm = new MatchMeView();
mainForm.setVisible(true);
});
}
}
| |
package com.atlassian.maven.plugins.amps.codegen.prompter.common.web;
import java.util.Arrays;
import java.util.SortedMap;
import java.util.TreeMap;
import com.atlassian.maven.plugins.amps.codegen.prompter.PluginModulePrompter;
import com.atlassian.plugins.codegen.modules.common.Condition;
import com.atlassian.plugins.codegen.modules.common.Conditions;
import com.atlassian.plugins.codegen.modules.common.web.WebSectionProperties;
import org.codehaus.plexus.components.interactivity.PrompterException;
import org.junit.Test;
import static com.atlassian.maven.plugins.amps.codegen.prompter.AbstractModulePrompter.MODULE_DESCRIP_PROMPT;
import static com.atlassian.maven.plugins.amps.codegen.prompter.AbstractModulePrompter.MODULE_KEY_PROMPT;
import static org.junit.Assert.assertEquals;
import static org.mockito.Mockito.when;
/**
* @since 3.6
*/
public class WebSectionPrompterTest extends AbstractWebFragmentPrompterTest<WebSectionProperties>
{
public static final String MODULE_NAME = "My Web Section";
public static final String MODULE_KEY = "my-web-section";
public static final String DESCRIPTION = "The My Web Section Plugin";
public static final String I18N_NAME_KEY = "my-web-section.name";
public static final String I18N_DESCRIPTION_KEY = "my-web-section.description";
public static final String ADV_MODULE_KEY = "awesome-module";
public static final String ADV_DESCRIPTION = "The Awesomest Plugin Ever";
public static final String ADV_I18N_NAME_KEY = "awesome-plugin.name";
public static final String ADV_I18N_DESCRIPTION_KEY = "pluginus-awesomeous.description";
public static final String CUSTOM_SECTION = "system.admin/mysection";
public static final String WEIGHT = "20";
public static final String LABEL_KEY = "section.label";
public static final String LABEL_VALUE = "this is my label";
public static final String LABEL_PARAM = "label param";
public static final String TOOLTIP_KEY = "item.toolip";
public static final String TOOLTIP_VALUE = "this is a tooltip";
@Test
public void basicPropertiesAreValid() throws PrompterException
{
when(prompter.prompt("Enter Plugin Module Name", "My Web Section")).thenReturn(MODULE_NAME);
when(prompter.prompt("Enter Location (e.g. system.admin/mynewsection)")).thenReturn(CUSTOM_SECTION);
when(prompter.prompt("Show Advanced Setup?", PluginModulePrompter.YN_ANSWERS, "N")).thenReturn("N");
when(prompter.prompt("Include Example Code?", PluginModulePrompter.YN_ANSWERS, "N")).thenReturn("N");
WebSectionPrompter modulePrompter = new WebSectionPrompter(prompter);
modulePrompter.setUseAnsiColor(false);
setProps((WebSectionProperties) modulePrompter.getModulePropertiesFromInput(moduleLocation));
assertEquals("wrong module name", MODULE_NAME, props.getModuleName());
assertEquals("wrong module key", MODULE_KEY, props.getModuleKey());
assertEquals("wrong description", DESCRIPTION, props.getDescription());
assertEquals("wrong i18n name key", I18N_NAME_KEY, props.getNameI18nKey());
assertEquals("wrong i18n desc key", I18N_DESCRIPTION_KEY, props.getDescriptionI18nKey());
assertEquals("wrong location", CUSTOM_SECTION, props.getLocation());
}
@Test
public void advancedPropertiesAreValid() throws PrompterException
{
when(prompter.prompt("Enter Plugin Module Name", "My Web Section")).thenReturn(MODULE_NAME);
when(prompter.prompt("Enter Location (e.g. system.admin/mynewsection)")).thenReturn(CUSTOM_SECTION);
when(prompter.prompt("Show Advanced Setup?", PluginModulePrompter.YN_ANSWERS, "N")).thenReturn("Y");
when(prompter.prompt(MODULE_KEY_PROMPT, MODULE_KEY)).thenReturn(ADV_MODULE_KEY);
when(prompter.prompt(MODULE_DESCRIP_PROMPT, DESCRIPTION)).thenReturn(ADV_DESCRIPTION);
when(prompter.prompt("i18n Name Key", I18N_NAME_KEY)).thenReturn(ADV_I18N_NAME_KEY);
when(prompter.prompt("i18n Description Key", I18N_DESCRIPTION_KEY)).thenReturn(ADV_I18N_DESCRIPTION_KEY);
when(prompter.prompt("Weight", "1000")).thenReturn(WEIGHT);
when(prompter.prompt("Enter Label Key", "my-web-section.label")).thenReturn(LABEL_KEY);
when(prompter.prompt("Enter Label Value", "My Web Section")).thenReturn(LABEL_VALUE);
when(prompter.prompt("Add Label Param?", PluginModulePrompter.YN_ANSWERS, "N")).thenReturn("Y")
.thenReturn("N");
when(prompter.prompt("values:\nlabel param\nAdd Label Param?", PluginModulePrompter.YN_ANSWERS, "N")).thenReturn("N");
when(prompter.prompt("Enter Param Value")).thenReturn(LABEL_PARAM);
when(prompter.prompt("Add Tooltip?", PluginModulePrompter.YN_ANSWERS, "N")).thenReturn("Y")
.thenReturn("N");
when(prompter.prompt("Enter Tooltip Key", "awesome-module.tooltip")).thenReturn(TOOLTIP_KEY);
when(prompter.prompt("Enter Tooltip Value", "My Web Section Tooltip")).thenReturn(TOOLTIP_VALUE);
when(prompter.prompt("Add Tooltip Param?", PluginModulePrompter.YN_ANSWERS, "N")).thenReturn("N");
when(prompter.prompt("Add Plugin Module Param?", PluginModulePrompter.YN_ANSWERS, "N")).thenReturn("Y")
.thenReturn("N");
when(prompter.prompt("params:\nparamKey->paramVal\nAdd Plugin Module Param?", PluginModulePrompter.YN_ANSWERS, "N")).thenReturn("N");
when(prompter.prompt("Include Example Code?", PluginModulePrompter.YN_ANSWERS, "N")).thenReturn("N");
WebSectionPrompter modulePrompter = new WebSectionPrompter(prompter);
modulePrompter.setUseAnsiColor(false);
setProps((WebSectionProperties) modulePrompter.getModulePropertiesFromInput(moduleLocation));
assertEquals("wrong module name", MODULE_NAME, props.getModuleName());
assertEquals("wrong module key", ADV_MODULE_KEY, props.getModuleKey());
assertEquals("wrong description", ADV_DESCRIPTION, props.getDescription());
assertEquals("wrong i18n name key", ADV_I18N_NAME_KEY, props.getNameI18nKey());
assertEquals("wrong i18n desc key", ADV_I18N_DESCRIPTION_KEY, props.getDescriptionI18nKey());
assertEquals("wrong location", CUSTOM_SECTION, props.getLocation());
assertEquals("wrong weight", WEIGHT, props.getWeight());
assertAdvancedCommonProps();
//custom context-provider name check
assertEquals("wrong context provider", CUSTOM_CONTEXT_PROVIDER, props.getContextProvider());
//custom condition name check
Condition condition = (Condition) ((Conditions) props.getConditions()
.get(0)).getConditions()
.get(0);
assertEquals("wrong condition name", CUSTOM_CONDITION, condition.getFullyQualifiedClassName());
}
@Test
public void providerContextFromListIsValid() throws PrompterException
{
SortedMap<String, String> providersMap = new TreeMap<String, String>();
providersMap.put("HeightContextProvider", "com.atlassian.test.HeightContextProvider");
providersMap.put("WidthContextProvider", "com.atlassian.test.WidthContextProvider");
contextProviderFactory.setProvidersMap(providersMap);
when(prompter.prompt("Enter Plugin Module Name", "My Web Section")).thenReturn(MODULE_NAME);
when(prompter.prompt("Enter Location (e.g. system.admin/mynewsection)")).thenReturn(CUSTOM_SECTION);
when(prompter.prompt("Show Advanced Setup?", PluginModulePrompter.YN_ANSWERS, "N")).thenReturn("Y");
when(prompter.prompt(MODULE_KEY_PROMPT, MODULE_KEY)).thenReturn(ADV_MODULE_KEY);
when(prompter.prompt(MODULE_DESCRIP_PROMPT, DESCRIPTION)).thenReturn(ADV_DESCRIPTION);
when(prompter.prompt("i18n Name Key", I18N_NAME_KEY)).thenReturn(ADV_I18N_NAME_KEY);
when(prompter.prompt("i18n Description Key", I18N_DESCRIPTION_KEY)).thenReturn(ADV_I18N_DESCRIPTION_KEY);
when(prompter.prompt("Weight", "1000")).thenReturn(WEIGHT);
when(prompter.prompt("Enter Label Key", "my-web-section.label")).thenReturn(LABEL_KEY);
when(prompter.prompt("Enter Label Value", "My Web Section")).thenReturn(LABEL_VALUE);
when(prompter.prompt("Add Label Param?", PluginModulePrompter.YN_ANSWERS, "N")).thenReturn("Y")
.thenReturn("N");
when(prompter.prompt("values:\nlabel param\nAdd Label Param?", PluginModulePrompter.YN_ANSWERS, "N")).thenReturn("N");
when(prompter.prompt("Enter Param Value")).thenReturn(LABEL_PARAM);
when(prompter.prompt("Add Tooltip?", PluginModulePrompter.YN_ANSWERS, "N")).thenReturn("Y")
.thenReturn("N");
when(prompter.prompt("Enter Tooltip Key", "awesome-module.tooltip")).thenReturn(TOOLTIP_KEY);
when(prompter.prompt("Enter Tooltip Value", "My Web Section Tooltip")).thenReturn(TOOLTIP_VALUE);
when(prompter.prompt("Add Tooltip Param?", PluginModulePrompter.YN_ANSWERS, "N")).thenReturn("N");
when(prompter.prompt("Add Plugin Module Param?", PluginModulePrompter.YN_ANSWERS, "N")).thenReturn("Y")
.thenReturn("N");
when(prompter.prompt("params:\nparamKey->paramVal\nAdd Plugin Module Param?", PluginModulePrompter.YN_ANSWERS, "N")).thenReturn("N");
when(prompter.prompt("Choose A Context Provider\n1: HeightContextProvider\n2: WidthContextProvider\n3: Custom Context Provider\nChoose a number: ", Arrays.asList("1", "2", "3"), "")).thenReturn("2");
when(prompter.prompt("Include Example Code?", PluginModulePrompter.YN_ANSWERS, "N")).thenReturn("N");
WebSectionPrompter modulePrompter = new WebSectionPrompter(prompter);
modulePrompter.setUseAnsiColor(false);
setProps((WebSectionProperties) modulePrompter.getModulePropertiesFromInput(moduleLocation));
assertEquals("wrong context provider", "com.atlassian.test.WidthContextProvider", props.getContextProvider());
}
@Test
public void conditionFromListIsValid() throws PrompterException
{
SortedMap<String, String> conditionMap = new TreeMap<String, String>();
conditionMap.put("NoFacialHairCondition", "com.atlassian.test.NoFacialHairCondition");
conditionMap.put("HasGlobalAdminPermissionCondition", "com.atlassian.test.HasGlobalAdminPermissionCondition");
conditionFactory.setConditions(conditionMap);
when(prompter.prompt("Enter Plugin Module Name", "My Web Section")).thenReturn(MODULE_NAME);
when(prompter.prompt("Enter Location (e.g. system.admin/mynewsection)")).thenReturn(CUSTOM_SECTION);
when(prompter.prompt("Show Advanced Setup?", PluginModulePrompter.YN_ANSWERS, "N")).thenReturn("Y");
when(prompter.prompt(MODULE_KEY_PROMPT, MODULE_KEY)).thenReturn(ADV_MODULE_KEY);
when(prompter.prompt(MODULE_DESCRIP_PROMPT, DESCRIPTION)).thenReturn(ADV_DESCRIPTION);
when(prompter.prompt("i18n Name Key", I18N_NAME_KEY)).thenReturn(ADV_I18N_NAME_KEY);
when(prompter.prompt("i18n Description Key", I18N_DESCRIPTION_KEY)).thenReturn(ADV_I18N_DESCRIPTION_KEY);
when(prompter.prompt("Weight", "1000")).thenReturn(WEIGHT);
when(prompter.prompt("Enter Label Key", "my-web-section.label")).thenReturn(LABEL_KEY);
when(prompter.prompt("Enter Label Value", "My Web Section")).thenReturn(LABEL_VALUE);
when(prompter.prompt("Add Label Param?", PluginModulePrompter.YN_ANSWERS, "N")).thenReturn("Y")
.thenReturn("N");
when(prompter.prompt("values:\nlabel param\nAdd Label Param?", PluginModulePrompter.YN_ANSWERS, "N")).thenReturn("N");
when(prompter.prompt("Enter Param Value")).thenReturn(LABEL_PARAM);
when(prompter.prompt("Add Tooltip?", PluginModulePrompter.YN_ANSWERS, "N")).thenReturn("Y")
.thenReturn("N");
when(prompter.prompt("Enter Tooltip Key", "awesome-module.tooltip")).thenReturn(TOOLTIP_KEY);
when(prompter.prompt("Enter Tooltip Value", "My Web Section Tooltip")).thenReturn(TOOLTIP_VALUE);
when(prompter.prompt("Add Tooltip Param?", PluginModulePrompter.YN_ANSWERS, "N")).thenReturn("N");
when(prompter.prompt("Add Plugin Module Param?", PluginModulePrompter.YN_ANSWERS, "N")).thenReturn("Y")
.thenReturn("N");
when(prompter.prompt("params:\nparamKey->paramVal\nAdd Plugin Module Param?", PluginModulePrompter.YN_ANSWERS, "N")).thenReturn("N");
when(prompter.prompt("Choose A Condition\n1: HasGlobalAdminPermissionCondition\n2: NoFacialHairCondition\n3: Custom Condition\nChoose a number: ", Arrays.asList("1", "2", "3"), "")).thenReturn("2");
when(prompter.prompt("Include Example Code?", PluginModulePrompter.YN_ANSWERS, "N")).thenReturn("N");
WebSectionPrompter modulePrompter = new WebSectionPrompter(prompter);
modulePrompter.setUseAnsiColor(false);
setProps((WebSectionProperties) modulePrompter.getModulePropertiesFromInput(moduleLocation));
Condition condition = (Condition) ((Conditions) props.getConditions()
.get(0)).getConditions()
.get(0);
assertEquals("wrong condition name", "com.atlassian.test.NoFacialHairCondition", condition.getFullyQualifiedClassName());
}
}
| |
package com.ctrip.hermes.broker.queue;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.atomic.AtomicBoolean;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.unidal.tuple.Pair;
import com.ctrip.hermes.broker.config.BrokerConfig;
import com.ctrip.hermes.core.lease.Lease;
import com.ctrip.hermes.core.log.BizLogger;
import com.ctrip.hermes.core.schedule.ExponentialSchedulePolicy;
import com.ctrip.hermes.core.schedule.SchedulePolicy;
import com.ctrip.hermes.core.transport.command.SendMessageCommand.MessageBatchWithRawData;
import com.ctrip.hermes.core.utils.HermesThreadFactory;
import com.ctrip.hermes.core.utils.PlexusComponentLocator;
import com.google.common.base.Function;
import com.google.common.collect.Collections2;
import com.google.common.util.concurrent.SettableFuture;
/**
* @author Leo Liang(jhliang@ctrip.com)
*
*/
public abstract class AbstractMessageQueueDumper implements MessageQueueDumper {
private static final Logger log = LoggerFactory.getLogger(AbstractMessageQueueDumper.class);
protected BizLogger m_bizLogger;
private BlockingQueue<FutureBatchPriorityWrapper> m_queue = new LinkedBlockingQueue<>();
private AtomicBoolean m_inited = new AtomicBoolean(false);
protected BrokerConfig m_config;
protected String m_topic;
protected int m_partition;
protected Lease m_lease;
private Thread m_workerThread;
protected AtomicBoolean m_stopped = new AtomicBoolean(false);
public AbstractMessageQueueDumper(String topic, int partition, BrokerConfig config, Lease lease) {
m_topic = topic;
m_partition = partition;
m_lease = lease;
m_config = config;
m_bizLogger = PlexusComponentLocator.lookup(BizLogger.class);
String threadName = String.format("MessageQueueDumper-%s-%d", topic, partition);
m_workerThread = HermesThreadFactory.create(threadName, false).newThread(new DumperTask());
}
@Override
public void stop() {
if (m_stopped.compareAndSet(false, true)) {
doStop();
}
}
public Lease getLease() {
return m_lease;
}
private boolean flushMsgs(List<FutureBatchPriorityWrapper> todos) {
if (todos.isEmpty()) {
m_queue.drainTo(todos, m_config.getDumperBatchSize());
}
if (!todos.isEmpty()) {
appendMessageSync(todos);
todos.clear();
return true;
} else {
return false;
}
}
public void submit(SettableFuture<Map<Integer, Boolean>> future, MessageBatchWithRawData batch, boolean isPriority) {
m_queue.offer(new FutureBatchPriorityWrapper(future, batch, isPriority));
}
public void start() {
if (m_inited.compareAndSet(false, true)) {
m_workerThread.start();
}
}
protected void appendMessageSync(List<FutureBatchPriorityWrapper> todos) {
List<FutureBatchResultWrapper> priorityTodos = new ArrayList<>();
List<FutureBatchResultWrapper> nonPriorityTodos = new ArrayList<>();
for (FutureBatchPriorityWrapper todo : todos) {
Map<Integer, Boolean> result = new HashMap<>();
addResults(result, todo.getBatch().getMsgSeqs(), false);
if (todo.isPriority()) {
priorityTodos.add(new FutureBatchResultWrapper(todo.getFuture(), todo.getBatch(), result));
} else {
nonPriorityTodos.add(new FutureBatchResultWrapper(todo.getFuture(), todo.getBatch(), result));
}
}
Function<FutureBatchResultWrapper, Pair<MessageBatchWithRawData, Map<Integer, Boolean>>> transformFucntion = new Function<FutureBatchResultWrapper, Pair<MessageBatchWithRawData, Map<Integer, Boolean>>>() {
@Override
public Pair<MessageBatchWithRawData, Map<Integer, Boolean>> apply(FutureBatchResultWrapper input) {
return new Pair<MessageBatchWithRawData, Map<Integer, Boolean>>(input.getBatch(), input.getResult());
}
};
doAppendMessageSync(true, Collections2.transform(priorityTodos, transformFucntion));
doAppendMessageSync(false, Collections2.transform(nonPriorityTodos, transformFucntion));
for (List<FutureBatchResultWrapper> todo : Arrays.asList(priorityTodos, nonPriorityTodos)) {
for (FutureBatchResultWrapper fbw : todo) {
SettableFuture<Map<Integer, Boolean>> future = fbw.getFuture();
Map<Integer, Boolean> result = fbw.getResult();
future.set(result);
}
}
}
protected void addResults(Map<Integer, Boolean> result, List<Integer> seqs, boolean success) {
for (Integer seq : seqs) {
result.put(seq, success);
}
}
protected void addResults(Map<Integer, Boolean> result, boolean success) {
for (Integer key : result.keySet()) {
result.put(key, success);
}
}
protected abstract void doStop();
protected abstract void doAppendMessageSync(boolean isPriority,
Collection<Pair<MessageBatchWithRawData, Map<Integer, Boolean>>> todos);
private class DumperTask implements Runnable {
@Override
public void run() {
List<FutureBatchPriorityWrapper> todos = new ArrayList<>(m_config.getDumperBatchSize());
int checkIntervalBase = m_config.getDumperNoMessageWaitIntervalBaseMillis();
int checkIntervalMax = m_config.getDumperNoMessageWaitIntervalMaxMillis();
SchedulePolicy schedulePolicy = new ExponentialSchedulePolicy(checkIntervalBase, checkIntervalMax);
while (!m_stopped.get() && !Thread.currentThread().isInterrupted() && !m_lease.isExpired()) {
try {
if (flushMsgs(todos)) {
schedulePolicy.succeess();
} else {
schedulePolicy.fail(true);
}
} catch (Exception e) {
log.error("Exception occurred while dumping data", e);
}
}
// lease is expired or stopped, flush remaining msgs
while (!m_queue.isEmpty() || !todos.isEmpty()) {
flushMsgs(todos);
}
}
}
private static class FutureBatchResultWrapper {
private SettableFuture<Map<Integer, Boolean>> m_future;
private MessageBatchWithRawData m_batch;
private Map<Integer, Boolean> m_result;
public FutureBatchResultWrapper(SettableFuture<Map<Integer, Boolean>> future, MessageBatchWithRawData batch,
Map<Integer, Boolean> result) {
m_future = future;
m_batch = batch;
m_result = result;
}
public SettableFuture<Map<Integer, Boolean>> getFuture() {
return m_future;
}
public MessageBatchWithRawData getBatch() {
return m_batch;
}
public Map<Integer, Boolean> getResult() {
return m_result;
}
}
private static class FutureBatchPriorityWrapper {
private SettableFuture<Map<Integer, Boolean>> m_future;
private MessageBatchWithRawData m_batch;
private boolean m_isPriority;
public FutureBatchPriorityWrapper(SettableFuture<Map<Integer, Boolean>> future, MessageBatchWithRawData batch,
boolean isPriority) {
m_future = future;
m_batch = batch;
m_isPriority = isPriority;
}
public SettableFuture<Map<Integer, Boolean>> getFuture() {
return m_future;
}
public MessageBatchWithRawData getBatch() {
return m_batch;
}
public boolean isPriority() {
return m_isPriority;
}
}
}
| |
/*****************************************************
*
* CheckoutActivity.java
*
*
* Modified MIT License
*
* Copyright (c) 2010-2015 Kite Tech Ltd. https://www.kite.ly
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The software MAY ONLY be used with the Kite Tech Ltd platform and MAY NOT be modified
* to be used with any competitor platforms. This means the software MAY NOT be modified
* to place orders with any competitors to Kite Tech Ltd, all orders MUST go through the
* Kite Tech Ltd platform servers.
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NON INFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*
*****************************************************/
///// Package Declaration /////
package ly.kite.checkout;
///// Import(s) /////
import java.net.SocketTimeoutException;
import java.net.UnknownHostException;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Parcelable;
import android.os.Bundle;
import android.view.MenuItem;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.EditText;
import ly.kite.KiteSDK;
import ly.kite.analytics.Analytics;
import ly.kite.catalogue.Catalogue;
import ly.kite.catalogue.ICatalogueConsumer;
import ly.kite.journey.AKiteActivity;
import ly.kite.pricing.PricingAgent;
import ly.kite.catalogue.PrintJob;
import ly.kite.catalogue.PrintOrder;
import ly.kite.R;
import ly.kite.address.Address;
import ly.kite.address.AddressBookActivity;
import ly.kite.catalogue.CatalogueLoader;
///// Class Declaration /////
/*****************************************************
*
* This class displays the first screen of the check-out
* process - the shipping screen.
*
*****************************************************/
public class CheckoutActivity extends AKiteActivity implements View.OnClickListener
{
////////// Static Constant(s) //////////
@SuppressWarnings( "unused" )
private static final String LOG_TAG = "CheckoutActivity";
public static final String EXTRA_PRINT_ORDER = "ly.kite.EXTRA_PRINT_ORDER";
public static final String EXTRA_PRINT_ENVIRONMENT = "ly.kite.EXTRA_PRINT_ENVIRONMENT";
public static final String EXTRA_PRINT_API_KEY = "ly.kite.EXTRA_PRINT_API_KEY";
public static final String ENVIRONMENT_STAGING = "ly.kite.ENVIRONMENT_STAGING";
public static final String ENVIRONMENT_LIVE = "ly.kite.ENVIRONMENT_LIVE";
public static final String ENVIRONMENT_TEST = "ly.kite.ENVIRONMENT_TEST";
private static final long MAXIMUM_PRODUCT_AGE_MILLIS = 1 * 60 * 60 * 1000;
private static final String SHIPPING_PREFERENCES = "shipping_preferences";
private static final String SHIPPING_PREFERENCE_EMAIL = "shipping_preferences.email";
private static final String SHIPPING_PREFERENCE_PHONE = "shipping_preferences.phone";
private static final int REQUEST_CODE_PAYMENT = 1;
private static final int REQUEST_CODE_ADDRESS_BOOK = 2;
////////// Static Variable(s) //////////
////////// Member Variable(s) //////////
private PrintOrder mPrintOrder;
// private String mAPIKey;
// private KiteSDK.Environment mEnvironment;
private EditText mEmailEditText;
private EditText mPhoneEditText;
private Button mProceedButton;
////////// Static Initialiser(s) //////////
////////// Static Method(s) //////////
static public void start( Activity activity, PrintOrder printOrder, int requestCode )
{
Intent intent = new Intent( activity, CheckoutActivity.class );
intent.putExtra( EXTRA_PRINT_ORDER, (Parcelable) printOrder );
activity.startActivityForResult( intent, requestCode );
}
////////// Constructor(s) //////////
////////// Activity Method(s) //////////
/*****************************************************
*
* Called when the activity is created.
*
*****************************************************/
@Override
public void onCreate( Bundle savedInstanceState )
{
super.onCreate( savedInstanceState );
requestWindowFeature( Window.FEATURE_ACTION_BAR );
setContentView( R.layout.screen_checkout );
mEmailEditText = (EditText)findViewById( R.id.email_edit_text );
mPhoneEditText = (EditText)findViewById( R.id.phone_edit_text );
mProceedButton = (Button)findViewById( R.id.proceed_overlay_button );
// Restore email address and phone number from history
// Restore preferences
SharedPreferences settings = getSharedPreferences( SHIPPING_PREFERENCES, 0 );
String email = settings.getString( SHIPPING_PREFERENCE_EMAIL, null );
String phone = settings.getString( SHIPPING_PREFERENCE_PHONE, null );
if ( email != null ) mEmailEditText.setText( email );
if ( phone != null ) mPhoneEditText.setText( phone );
if ( !KiteSDK.getInstance( this ).getRequestPhoneNumber() )
{
mPhoneEditText.setVisibility( View.GONE );
findViewById(R.id.phone_require_reason).setVisibility( View.GONE );
}
String apiKey = getIntent().getStringExtra( EXTRA_PRINT_API_KEY );
String envString = getIntent().getStringExtra( EXTRA_PRINT_ENVIRONMENT );
mPrintOrder = (PrintOrder) getIntent().getParcelableExtra( EXTRA_PRINT_ORDER );
if ( apiKey == null )
{
apiKey = KiteSDK.getInstance( this ).getAPIKey();
if ( apiKey == null )
{
throw new IllegalArgumentException( "You must specify an API key string extra in the intent used to start the CheckoutActivity or with KitePrintSDK.initialize" );
}
}
if ( mPrintOrder == null )
{
throw new IllegalArgumentException( "You must specify a PrintOrder object extra in the intent used to start the CheckoutActivity" );
}
if ( mPrintOrder.getJobs().size() < 1 )
{
throw new IllegalArgumentException( "You must specify a PrintOrder object extra that actually has some jobs for printing i.e. PrintOrder.getJobs().size() > 0" );
}
// KiteSDK.Environment environment = null;
//
// if ( envString == null )
// {
// environment = KiteSDK.getInstance( this ).getEnvironment();
//
// if ( environment == null )
// {
// throw new IllegalArgumentException( "You must specify an environment string extra in the intent used to start the CheckoutActivity or with KitePrintSDK.initialize" );
// }
// }
// else
// {
// if ( envString.equals( ENVIRONMENT_STAGING ) )
// {
// environment = KiteSDK.DefaultEnvironment.STAGING;
// }
// else if ( envString.equals( ENVIRONMENT_TEST ) )
// {
// environment = KiteSDK.DefaultEnvironment.TEST;
// }
// else if ( envString.equals( ENVIRONMENT_LIVE ) )
// {
// environment = KiteSDK.DefaultEnvironment.LIVE;
// }
// else
// {
// throw new IllegalArgumentException( "Bad print environment extra: " + envString );
// }
// }
//
// mAPIKey = apiKey;
// mEnvironment = environment;
//
// KiteSDK.getInstance( this ).setEnvironment( apiKey, environment );
mProceedButton.setText( R.string.shipping_proceed_button_text );
// hide keyboard initially
this.getWindow().setSoftInputMode( WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN );
// Request the pricing now - even though we don't use it on this screen, and it may change once
// a shipping address has been chosen (if the shipping address country is different to the default
// locale). This is to minimise any delay to the user.
PricingAgent.getInstance().requestPricing( this, mPrintOrder, null );
if ( savedInstanceState == null )
{
Analytics.getInstance( this ).trackShippingScreenViewed( mPrintOrder, Analytics.VARIANT_JSON_PROPERTY_VALUE_CLASSIC_PLUS_ADDRESS_SEARCH, true );
}
mProceedButton.setOnClickListener( this );
}
@Override
protected void onSaveInstanceState( Bundle outState )
{
super.onSaveInstanceState( outState );
outState.putParcelable( EXTRA_PRINT_ORDER, mPrintOrder );
// outState.putString( EXTRA_PRINT_API_KEY, mAPIKey );
// outState.putParcelable( EXTRA_PRINT_ENVIRONMENT, mEnvironment );
}
@Override
protected void onRestoreInstanceState( Bundle savedInstanceState )
{
super.onRestoreInstanceState( savedInstanceState );
mPrintOrder = savedInstanceState.getParcelable( EXTRA_PRINT_ORDER );
// mAPIKey = savedInstanceState.getString( EXTRA_PRINT_API_KEY );
// mEnvironment = (KiteSDK.DefaultEnvironment) savedInstanceState.getSerializable( EXTRA_PRINT_ENVIRONMENT );
//
// KiteSDK.getInstance( this ).setEnvironment( mAPIKey, mEnvironment );
}
@Override
public boolean onMenuItemSelected( int featureId, MenuItem item )
{
if ( item.getItemId() == android.R.id.home )
{
finish();
return ( true );
}
return ( super.onMenuItemSelected( featureId, item ) );
}
@Override
protected void onActivityResult( int requestCode, int resultCode, Intent data )
{
if ( requestCode == REQUEST_CODE_PAYMENT )
{
if ( resultCode == Activity.RESULT_OK )
{
setResult( Activity.RESULT_OK );
finish();
}
}
else if ( requestCode == REQUEST_CODE_ADDRESS_BOOK )
{
if ( resultCode == RESULT_OK )
{
Address address = data.getParcelableExtra( AddressBookActivity.EXTRA_ADDRESS );
mPrintOrder.setShippingAddress( address );
Button chooseAddressButton = (Button) findViewById( R.id.address_picker_button );
chooseAddressButton.setText( address.toString() );
// Re-request the pricing if the shipping address changes, just in case the shipping
// price changes.
PricingAgent.getInstance().requestPricing( this, mPrintOrder, null );
}
}
}
////////// View.OnClickListener Method(s) //////////
@Override
public void onClick( View view )
{
if ( view == mProceedButton )
{
onProceedButtonClicked();
}
}
////////// Method(s) //////////
public void onChooseDeliveryAddressButtonClicked( View view )
{
Intent i = new Intent( this, AddressBookActivity.class );
startActivityForResult( i, REQUEST_CODE_ADDRESS_BOOK );
}
// private String getPaymentActivityEnvironment()
// {
// switch ( mEnvironment )
// {
// case LIVE:
// return PaymentActivity.ENVIRONMENT_LIVE;
// case STAGING:
// return PaymentActivity.ENVIRONMENT_STAGING;
// case TEST:
// return PaymentActivity.ENVIRONMENT_TEST;
// default:
// throw new IllegalStateException( "oops" );
// }
// }
private void showErrorDialog( String title, String message )
{
AlertDialog.Builder builder = new AlertDialog.Builder( this );
builder.setTitle( title ).setMessage( message ).setPositiveButton( "OK", null );
Dialog d = builder.create();
d.show();
}
public void onProceedButtonClicked()
{
String email = mEmailEditText.getText().toString();
String phone = mPhoneEditText.getText().toString();
if ( mPrintOrder.getShippingAddress() == null )
{
showErrorDialog( "Invalid Delivery Address", "Please choose a delivery address" );
return;
}
if ( !isEmailValid( email ) )
{
showErrorDialog( "Invalid Email Address", "Please enter a valid email address" );
return;
}
if ( KiteSDK.getInstance( this ).getRequestPhoneNumber() && phone.length() < 5 )
{
showErrorDialog( "Invalid Phone Number", "Please enter a valid phone number" );
return;
}
JSONObject userData = mPrintOrder.getUserData();
if ( userData == null )
{
userData = new JSONObject();
}
try
{
userData.put( "email", email );
userData.put( "phone", phone );
}
catch ( JSONException ex )
{/* ignore */}
mPrintOrder.setUserData( userData );
mPrintOrder.setNotificationEmail( email );
mPrintOrder.setNotificationPhoneNumber( phone );
SharedPreferences settings = getSharedPreferences( SHIPPING_PREFERENCES, 0 );
SharedPreferences.Editor editor = settings.edit();
editor.putString( SHIPPING_PREFERENCE_EMAIL, email );
editor.putString( SHIPPING_PREFERENCE_PHONE, phone );
editor.commit();
// Make sure we have up-to-date products before we proceed
final ProgressDialog progress = ProgressDialog.show( this, null, "Loading" );
CatalogueLoader.getInstance( this ).requestCatalogue(
MAXIMUM_PRODUCT_AGE_MILLIS,
new ICatalogueConsumer()
{
@Override
public void onCatalogueSuccess( Catalogue catalogue )
{
progress.dismiss();
startPaymentActivity();
}
@Override
public void onCatalogueError( Exception exception )
{
progress.dismiss();
showRetryTemplateSyncDialog( exception );
}
}
);
}
private void showRetryTemplateSyncDialog( Exception error )
{
AlertDialog.Builder builder = new AlertDialog.Builder( CheckoutActivity.this );
builder.setTitle( "Oops" );
builder.setMessage( error.getLocalizedMessage() );
if ( error instanceof UnknownHostException || error instanceof SocketTimeoutException )
{
builder.setMessage( "Please check your internet connectivity and then try again" );
}
builder.setPositiveButton( "Retry", new DialogInterface.OnClickListener()
{
@Override
public void onClick( DialogInterface dialogInterface, int i )
{
onProceedButtonClicked();
}
} );
builder.setNegativeButton( "Cancel", null );
builder.show();
}
private void startPaymentActivity()
{
// Check we have valid templates for every printjob
try
{
// This will return null if there are no products, or they are out of date, but that's
// OK because we catch any exceptions.
Catalogue catalogue = CatalogueLoader.getInstance( this ).getCachedCatalogue( MAXIMUM_PRODUCT_AGE_MILLIS );
// Go through every print job and check that we can get a product from the product id
for ( PrintJob job : mPrintOrder.getJobs() )
{
catalogue.confirmProductIdExistsOrThrow( job.getProduct().getId() );
}
}
catch ( Exception exception )
{
showRetryTemplateSyncDialog( exception );
return;
}
KiteSDK kiteSDK = KiteSDK.getInstance( this );
PaymentActivity.start( this, mPrintOrder, kiteSDK.getAPIKey(), kiteSDK.getEnvironment().getPaymentActivityEnvironment(), REQUEST_CODE_PAYMENT );
}
boolean isEmailValid( CharSequence email )
{
return android.util.Patterns.EMAIL_ADDRESS.matcher( email ).matches();
}
////////// Inner Class(es) //////////
/*****************************************************
*
* ...
*
*****************************************************/
}
| |
/*
*
* 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.hbase.rest.client;
import java.io.IOException;
import java.io.InterruptedIOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.TreeMap;
import java.util.concurrent.TimeUnit;
import org.apache.commons.lang3.NotImplementedException;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.hbase.Cell;
import org.apache.hadoop.hbase.CellUtil;
import org.apache.hadoop.hbase.CompareOperator;
import org.apache.hadoop.hbase.HBaseConfiguration;
import org.apache.hadoop.hbase.HConstants;
import org.apache.hadoop.hbase.KeyValue;
import org.apache.hadoop.hbase.TableName;
import org.apache.hadoop.hbase.client.Append;
import org.apache.hadoop.hbase.client.Delete;
import org.apache.hadoop.hbase.client.Durability;
import org.apache.hadoop.hbase.client.Get;
import org.apache.hadoop.hbase.client.Increment;
import org.apache.hadoop.hbase.client.Put;
import org.apache.hadoop.hbase.client.RegionLocator;
import org.apache.hadoop.hbase.client.Result;
import org.apache.hadoop.hbase.client.ResultScanner;
import org.apache.hadoop.hbase.client.Row;
import org.apache.hadoop.hbase.client.RowMutations;
import org.apache.hadoop.hbase.client.Scan;
import org.apache.hadoop.hbase.client.Table;
import org.apache.hadoop.hbase.client.TableDescriptor;
import org.apache.hadoop.hbase.client.coprocessor.Batch;
import org.apache.hadoop.hbase.client.coprocessor.Batch.Callback;
import org.apache.hadoop.hbase.client.metrics.ScanMetrics;
import org.apache.hadoop.hbase.filter.Filter;
import org.apache.hadoop.hbase.io.TimeRange;
import org.apache.hadoop.hbase.ipc.CoprocessorRpcChannel;
import org.apache.hadoop.hbase.rest.Constants;
import org.apache.hadoop.hbase.rest.model.CellModel;
import org.apache.hadoop.hbase.rest.model.CellSetModel;
import org.apache.hadoop.hbase.rest.model.RowModel;
import org.apache.hadoop.hbase.rest.model.ScannerModel;
import org.apache.hadoop.hbase.rest.model.TableSchemaModel;
import org.apache.hadoop.hbase.util.Bytes;
import org.apache.hadoop.util.StringUtils;
import org.apache.yetus.audience.InterfaceAudience;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.apache.hbase.thirdparty.com.google.common.base.Preconditions;
import org.apache.hbase.thirdparty.com.google.protobuf.Descriptors;
import org.apache.hbase.thirdparty.com.google.protobuf.Message;
import org.apache.hbase.thirdparty.com.google.protobuf.Service;
import org.apache.hbase.thirdparty.com.google.protobuf.ServiceException;
/**
* HTable interface to remote tables accessed via REST gateway
*/
@InterfaceAudience.Public
public class RemoteHTable implements Table {
private static final Logger LOG = LoggerFactory.getLogger(RemoteHTable.class);
final Client client;
final Configuration conf;
final byte[] name;
final int maxRetries;
final long sleepTime;
@SuppressWarnings("rawtypes")
protected String buildRowSpec(final byte[] row, final Map familyMap, final long startTime,
final long endTime, final int maxVersions) {
StringBuffer sb = new StringBuffer();
sb.append('/');
sb.append(Bytes.toString(name));
sb.append('/');
sb.append(toURLEncodedBytes(row));
Set families = familyMap.entrySet();
if (families != null) {
Iterator i = familyMap.entrySet().iterator();
sb.append('/');
while (i.hasNext()) {
Map.Entry e = (Map.Entry) i.next();
Collection quals = (Collection) e.getValue();
if (quals == null || quals.isEmpty()) {
// this is an unqualified family. append the family name and NO ':'
sb.append(toURLEncodedBytes((byte[]) e.getKey()));
} else {
Iterator ii = quals.iterator();
while (ii.hasNext()) {
sb.append(toURLEncodedBytes((byte[]) e.getKey()));
Object o = ii.next();
// Puts use byte[] but Deletes use KeyValue
if (o instanceof byte[]) {
sb.append(':');
sb.append(toURLEncodedBytes((byte[]) o));
} else if (o instanceof KeyValue) {
if (((KeyValue) o).getQualifierLength() != 0) {
sb.append(':');
sb.append(toURLEncodedBytes(CellUtil.cloneQualifier((KeyValue) o)));
}
} else {
throw new RuntimeException("object type not handled");
}
if (ii.hasNext()) {
sb.append(',');
}
}
}
if (i.hasNext()) {
sb.append(',');
}
}
}
if (startTime >= 0 && endTime != Long.MAX_VALUE) {
sb.append('/');
sb.append(startTime);
if (startTime != endTime) {
sb.append(',');
sb.append(endTime);
}
} else if (endTime != Long.MAX_VALUE) {
sb.append('/');
sb.append(endTime);
}
if (maxVersions > 1) {
sb.append("?v=");
sb.append(maxVersions);
}
return sb.toString();
}
protected String buildMultiRowSpec(final byte[][] rows, int maxVersions) {
StringBuilder sb = new StringBuilder();
sb.append('/');
sb.append(Bytes.toString(name));
sb.append("/multiget/");
if (rows == null || rows.length == 0) {
return sb.toString();
}
sb.append("?");
for (int i = 0; i < rows.length; i++) {
byte[] rk = rows[i];
if (i != 0) {
sb.append('&');
}
sb.append("row=");
sb.append(toURLEncodedBytes(rk));
}
sb.append("&v=");
sb.append(maxVersions);
return sb.toString();
}
protected Result[] buildResultFromModel(final CellSetModel model) {
List<Result> results = new ArrayList<>();
for (RowModel row : model.getRows()) {
List<Cell> kvs = new ArrayList<>(row.getCells().size());
for (CellModel cell : row.getCells()) {
byte[][] split = CellUtil.parseColumn(cell.getColumn());
byte[] column = split[0];
byte[] qualifier = null;
if (split.length == 1) {
qualifier = HConstants.EMPTY_BYTE_ARRAY;
} else if (split.length == 2) {
qualifier = split[1];
} else {
throw new IllegalArgumentException("Invalid familyAndQualifier provided.");
}
kvs
.add(new KeyValue(row.getKey(), column, qualifier, cell.getTimestamp(), cell.getValue()));
}
results.add(Result.create(kvs));
}
return results.toArray(new Result[results.size()]);
}
protected CellSetModel buildModelFromPut(Put put) {
RowModel row = new RowModel(put.getRow());
long ts = put.getTimestamp();
for (List<Cell> cells : put.getFamilyCellMap().values()) {
for (Cell cell : cells) {
row.addCell(new CellModel(CellUtil.cloneFamily(cell), CellUtil.cloneQualifier(cell),
ts != HConstants.LATEST_TIMESTAMP ? ts : cell.getTimestamp(), CellUtil.cloneValue(cell)));
}
}
CellSetModel model = new CellSetModel();
model.addRow(row);
return model;
}
/**
* Constructor
*/
public RemoteHTable(Client client, String name) {
this(client, HBaseConfiguration.create(), Bytes.toBytes(name));
}
/**
* Constructor
*/
public RemoteHTable(Client client, Configuration conf, String name) {
this(client, conf, Bytes.toBytes(name));
}
/**
* Constructor
*/
public RemoteHTable(Client client, Configuration conf, byte[] name) {
this.client = client;
this.conf = conf;
this.name = name;
this.maxRetries = conf.getInt("hbase.rest.client.max.retries", 10);
this.sleepTime = conf.getLong("hbase.rest.client.sleep", 1000);
}
public byte[] getTableName() {
return name.clone();
}
@Override
public TableName getName() {
return TableName.valueOf(name);
}
@Override
public Configuration getConfiguration() {
return conf;
}
@Override
public void close() throws IOException {
client.shutdown();
}
@Override
public Result get(Get get) throws IOException {
TimeRange range = get.getTimeRange();
String spec = buildRowSpec(get.getRow(), get.getFamilyMap(), range.getMin(), range.getMax(),
get.getMaxVersions());
if (get.getFilter() != null) {
LOG.warn("filters not supported on gets");
}
Result[] results = getResults(spec);
if (results.length > 0) {
if (results.length > 1) {
LOG.warn("too many results for get (" + results.length + ")");
}
return results[0];
} else {
return new Result();
}
}
@Override
public Result[] get(List<Get> gets) throws IOException {
byte[][] rows = new byte[gets.size()][];
int maxVersions = 1;
int count = 0;
for (Get g : gets) {
if (count == 0) {
maxVersions = g.getMaxVersions();
} else if (g.getMaxVersions() != maxVersions) {
LOG.warn(
"MaxVersions on Gets do not match, using the first in the list (" + maxVersions + ")");
}
if (g.getFilter() != null) {
LOG.warn("filters not supported on gets");
}
rows[count] = g.getRow();
count++;
}
String spec = buildMultiRowSpec(rows, maxVersions);
return getResults(spec);
}
private Result[] getResults(String spec) throws IOException {
for (int i = 0; i < maxRetries; i++) {
Response response = client.get(spec, Constants.MIMETYPE_PROTOBUF);
int code = response.getCode();
switch (code) {
case 200:
CellSetModel model = new CellSetModel();
model.getObjectFromMessage(response.getBody());
Result[] results = buildResultFromModel(model);
if (results.length > 0) {
return results;
}
// fall through
case 404:
return new Result[0];
case 509:
try {
Thread.sleep(sleepTime);
} catch (InterruptedException e) {
throw (InterruptedIOException) new InterruptedIOException().initCause(e);
}
break;
default:
throw new IOException("get request returned " + code);
}
}
throw new IOException("get request timed out");
}
@Override
public boolean exists(Get get) throws IOException {
LOG.warn("exists() is really get(), just use get()");
Result result = get(get);
return (result != null && !(result.isEmpty()));
}
@Override
public boolean[] exists(List<Get> gets) throws IOException {
LOG.warn("exists(List<Get>) is really list of get() calls, just use get()");
boolean[] results = new boolean[gets.size()];
for (int i = 0; i < results.length; i++) {
results[i] = exists(gets.get(i));
}
return results;
}
@Override
public void put(Put put) throws IOException {
CellSetModel model = buildModelFromPut(put);
StringBuilder sb = new StringBuilder();
sb.append('/');
sb.append(Bytes.toString(name));
sb.append('/');
sb.append(toURLEncodedBytes(put.getRow()));
for (int i = 0; i < maxRetries; i++) {
Response response =
client.put(sb.toString(), Constants.MIMETYPE_PROTOBUF, model.createProtobufOutput());
int code = response.getCode();
switch (code) {
case 200:
return;
case 509:
try {
Thread.sleep(sleepTime);
} catch (InterruptedException e) {
throw (InterruptedIOException) new InterruptedIOException().initCause(e);
}
break;
default:
throw new IOException("put request failed with " + code);
}
}
throw new IOException("put request timed out");
}
@Override
public void put(List<Put> puts) throws IOException {
// this is a trick: The gateway accepts multiple rows in a cell set and
// ignores the row specification in the URI
// separate puts by row
TreeMap<byte[], List<Cell>> map = new TreeMap<>(Bytes.BYTES_COMPARATOR);
for (Put put : puts) {
byte[] row = put.getRow();
List<Cell> cells = map.get(row);
if (cells == null) {
cells = new ArrayList<>();
map.put(row, cells);
}
for (List<Cell> l : put.getFamilyCellMap().values()) {
cells.addAll(l);
}
}
// build the cell set
CellSetModel model = new CellSetModel();
for (Map.Entry<byte[], List<Cell>> e : map.entrySet()) {
RowModel row = new RowModel(e.getKey());
for (Cell cell : e.getValue()) {
row.addCell(new CellModel(cell));
}
model.addRow(row);
}
// build path for multiput
StringBuilder sb = new StringBuilder();
sb.append('/');
sb.append(Bytes.toString(name));
sb.append("/$multiput"); // can be any nonexistent row
for (int i = 0; i < maxRetries; i++) {
Response response =
client.put(sb.toString(), Constants.MIMETYPE_PROTOBUF, model.createProtobufOutput());
int code = response.getCode();
switch (code) {
case 200:
return;
case 509:
try {
Thread.sleep(sleepTime);
} catch (InterruptedException e) {
throw (InterruptedIOException) new InterruptedIOException().initCause(e);
}
break;
default:
throw new IOException("multiput request failed with " + code);
}
}
throw new IOException("multiput request timed out");
}
@Override
public void delete(Delete delete) throws IOException {
String spec = buildRowSpec(delete.getRow(), delete.getFamilyCellMap(), delete.getTimestamp(),
delete.getTimestamp(), 1);
for (int i = 0; i < maxRetries; i++) {
Response response = client.delete(spec);
int code = response.getCode();
switch (code) {
case 200:
return;
case 509:
try {
Thread.sleep(sleepTime);
} catch (InterruptedException e) {
throw (InterruptedIOException) new InterruptedIOException().initCause(e);
}
break;
default:
throw new IOException("delete request failed with " + code);
}
}
throw new IOException("delete request timed out");
}
@Override
public void delete(List<Delete> deletes) throws IOException {
for (Delete delete : deletes) {
delete(delete);
}
}
public void flushCommits() throws IOException {
// no-op
}
@Override
public TableDescriptor getDescriptor() throws IOException {
StringBuilder sb = new StringBuilder();
sb.append('/');
sb.append(Bytes.toString(name));
sb.append('/');
sb.append("schema");
for (int i = 0; i < maxRetries; i++) {
Response response = client.get(sb.toString(), Constants.MIMETYPE_PROTOBUF);
int code = response.getCode();
switch (code) {
case 200:
TableSchemaModel schema = new TableSchemaModel();
schema.getObjectFromMessage(response.getBody());
return schema.getTableDescriptor();
case 509:
try {
Thread.sleep(sleepTime);
} catch (InterruptedException e) {
throw (InterruptedIOException) new InterruptedIOException().initCause(e);
}
break;
default:
throw new IOException("schema request returned " + code);
}
}
throw new IOException("schema request timed out");
}
class Scanner implements ResultScanner {
String uri;
public Scanner(Scan scan) throws IOException {
ScannerModel model;
try {
model = ScannerModel.fromScan(scan);
} catch (Exception e) {
throw new IOException(e);
}
StringBuffer sb = new StringBuffer();
sb.append('/');
sb.append(Bytes.toString(name));
sb.append('/');
sb.append("scanner");
for (int i = 0; i < maxRetries; i++) {
Response response =
client.post(sb.toString(), Constants.MIMETYPE_PROTOBUF, model.createProtobufOutput());
int code = response.getCode();
switch (code) {
case 201:
uri = response.getLocation();
return;
case 509:
try {
Thread.sleep(sleepTime);
} catch (InterruptedException e) {
throw (InterruptedIOException) new InterruptedIOException().initCause(e);
}
break;
default:
throw new IOException("scan request failed with " + code);
}
}
throw new IOException("scan request timed out");
}
@Override
public Result[] next(int nbRows) throws IOException {
StringBuilder sb = new StringBuilder(uri);
sb.append("?n=");
sb.append(nbRows);
for (int i = 0; i < maxRetries; i++) {
Response response = client.get(sb.toString(), Constants.MIMETYPE_PROTOBUF);
int code = response.getCode();
switch (code) {
case 200:
CellSetModel model = new CellSetModel();
model.getObjectFromMessage(response.getBody());
return buildResultFromModel(model);
case 204:
case 206:
return null;
case 509:
try {
Thread.sleep(sleepTime);
} catch (InterruptedException e) {
throw (InterruptedIOException) new InterruptedIOException().initCause(e);
}
break;
default:
throw new IOException("scanner.next request failed with " + code);
}
}
throw new IOException("scanner.next request timed out");
}
@Override
public Result next() throws IOException {
Result[] results = next(1);
if (results == null || results.length < 1) {
return null;
}
return results[0];
}
class Iter implements Iterator<Result> {
Result cache;
public Iter() {
try {
cache = Scanner.this.next();
} catch (IOException e) {
LOG.warn(StringUtils.stringifyException(e));
}
}
@Override
public boolean hasNext() {
return cache != null;
}
@Override
public Result next() {
Result result = cache;
try {
cache = Scanner.this.next();
} catch (IOException e) {
LOG.warn(StringUtils.stringifyException(e));
cache = null;
}
return result;
}
@Override
public void remove() {
throw new RuntimeException("remove() not supported");
}
}
@Override
public Iterator<Result> iterator() {
return new Iter();
}
@Override
public void close() {
try {
client.delete(uri);
} catch (IOException e) {
LOG.warn(StringUtils.stringifyException(e));
}
}
@Override
public boolean renewLease() {
throw new RuntimeException("renewLease() not supported");
}
@Override
public ScanMetrics getScanMetrics() {
throw new RuntimeException("getScanMetrics() not supported");
}
}
@Override
public ResultScanner getScanner(Scan scan) throws IOException {
return new Scanner(scan);
}
@Override
public ResultScanner getScanner(byte[] family) throws IOException {
Scan scan = new Scan();
scan.addFamily(family);
return new Scanner(scan);
}
@Override
public ResultScanner getScanner(byte[] family, byte[] qualifier) throws IOException {
Scan scan = new Scan();
scan.addColumn(family, qualifier);
return new Scanner(scan);
}
public boolean isAutoFlush() {
return true;
}
private boolean doCheckAndPut(byte[] row, byte[] family, byte[] qualifier, byte[] value, Put put)
throws IOException {
// column to check-the-value
put.add(new KeyValue(row, family, qualifier, value));
CellSetModel model = buildModelFromPut(put);
StringBuilder sb = new StringBuilder();
sb.append('/');
sb.append(Bytes.toString(name));
sb.append('/');
sb.append(toURLEncodedBytes(put.getRow()));
sb.append("?check=put");
for (int i = 0; i < maxRetries; i++) {
Response response =
client.put(sb.toString(), Constants.MIMETYPE_PROTOBUF, model.createProtobufOutput());
int code = response.getCode();
switch (code) {
case 200:
return true;
case 304: // NOT-MODIFIED
return false;
case 509:
try {
Thread.sleep(sleepTime);
} catch (final InterruptedException e) {
throw (InterruptedIOException) new InterruptedIOException().initCause(e);
}
break;
default:
throw new IOException("checkAndPut request failed with " + code);
}
}
throw new IOException("checkAndPut request timed out");
}
private boolean doCheckAndDelete(byte[] row, byte[] family, byte[] qualifier, byte[] value,
Delete delete) throws IOException {
Put put = new Put(row, HConstants.LATEST_TIMESTAMP, delete.getFamilyCellMap());
// column to check-the-value
put.add(new KeyValue(row, family, qualifier, value));
CellSetModel model = buildModelFromPut(put);
StringBuilder sb = new StringBuilder();
sb.append('/');
sb.append(Bytes.toString(name));
sb.append('/');
sb.append(toURLEncodedBytes(row));
sb.append("?check=delete");
for (int i = 0; i < maxRetries; i++) {
Response response =
client.put(sb.toString(), Constants.MIMETYPE_PROTOBUF, model.createProtobufOutput());
int code = response.getCode();
switch (code) {
case 200:
return true;
case 304: // NOT-MODIFIED
return false;
case 509:
try {
Thread.sleep(sleepTime);
} catch (final InterruptedException e) {
throw (InterruptedIOException) new InterruptedIOException().initCause(e);
}
break;
default:
throw new IOException("checkAndDelete request failed with " + code);
}
}
throw new IOException("checkAndDelete request timed out");
}
@Override
public CheckAndMutateBuilder checkAndMutate(byte[] row, byte[] family) {
return new CheckAndMutateBuilderImpl(row, family);
}
@Override
public CheckAndMutateWithFilterBuilder checkAndMutate(byte[] row, Filter filter) {
throw new NotImplementedException("Implement later");
}
@Override
public Result increment(Increment increment) throws IOException {
throw new IOException("Increment not supported");
}
@Override
public Result append(Append append) throws IOException {
throw new IOException("Append not supported");
}
@Override
public long incrementColumnValue(byte[] row, byte[] family, byte[] qualifier, long amount)
throws IOException {
throw new IOException("incrementColumnValue not supported");
}
@Override
public long incrementColumnValue(byte[] row, byte[] family, byte[] qualifier, long amount,
Durability durability) throws IOException {
throw new IOException("incrementColumnValue not supported");
}
@Override
public void batch(List<? extends Row> actions, Object[] results) throws IOException {
throw new IOException("batch not supported");
}
@Override
public <R> void batchCallback(List<? extends Row> actions, Object[] results,
Batch.Callback<R> callback) throws IOException, InterruptedException {
throw new IOException("batchCallback not supported");
}
@Override
public CoprocessorRpcChannel coprocessorService(byte[] row) {
throw new UnsupportedOperationException("coprocessorService not implemented");
}
@Override
public <T extends Service, R> Map<byte[], R> coprocessorService(Class<T> service, byte[] startKey,
byte[] endKey, Batch.Call<T, R> callable) throws ServiceException, Throwable {
throw new UnsupportedOperationException("coprocessorService not implemented");
}
@Override
public <T extends Service, R> void coprocessorService(Class<T> service, byte[] startKey,
byte[] endKey, Batch.Call<T, R> callable, Batch.Callback<R> callback)
throws ServiceException, Throwable {
throw new UnsupportedOperationException("coprocessorService not implemented");
}
@Override
public void mutateRow(RowMutations rm) throws IOException {
throw new IOException("atomicMutation not supported");
}
@Override
public <R extends Message> Map<byte[], R> batchCoprocessorService(
Descriptors.MethodDescriptor method, Message request, byte[] startKey, byte[] endKey,
R responsePrototype) throws ServiceException, Throwable {
throw new UnsupportedOperationException("batchCoprocessorService not implemented");
}
@Override
public <R extends Message> void batchCoprocessorService(Descriptors.MethodDescriptor method,
Message request, byte[] startKey, byte[] endKey, R responsePrototype, Callback<R> callback)
throws ServiceException, Throwable {
throw new UnsupportedOperationException("batchCoprocessorService not implemented");
}
@Override
public long getReadRpcTimeout(TimeUnit unit) {
throw new UnsupportedOperationException();
}
@Override
public long getRpcTimeout(TimeUnit unit) {
throw new UnsupportedOperationException();
}
@Override
public long getWriteRpcTimeout(TimeUnit unit) {
throw new UnsupportedOperationException();
}
@Override
public long getOperationTimeout(TimeUnit unit) {
throw new UnsupportedOperationException();
}
/*
* Only a small subset of characters are valid in URLs. Row keys, column families, and qualifiers
* cannot be appended to URLs without first URL escaping. Table names are ok because they can only
* contain alphanumeric, ".","_", and "-" which are valid characters in URLs.
*/
private static String toURLEncodedBytes(byte[] row) {
try {
return URLEncoder.encode(new String(row, StandardCharsets.UTF_8), "UTF-8");
} catch (UnsupportedEncodingException e) {
throw new IllegalStateException("URLEncoder doesn't support UTF-8", e);
}
}
private class CheckAndMutateBuilderImpl implements CheckAndMutateBuilder {
private final byte[] row;
private final byte[] family;
private byte[] qualifier;
private byte[] value;
CheckAndMutateBuilderImpl(byte[] row, byte[] family) {
this.row = Preconditions.checkNotNull(row, "row is null");
this.family = Preconditions.checkNotNull(family, "family is null");
}
@Override
public CheckAndMutateBuilder qualifier(byte[] qualifier) {
this.qualifier = Preconditions.checkNotNull(qualifier, "qualifier is null. Consider using" +
" an empty byte array, or just do not call this method if you want a null qualifier");
return this;
}
@Override
public CheckAndMutateBuilder timeRange(TimeRange timeRange) {
throw new UnsupportedOperationException("timeRange not implemented");
}
@Override
public CheckAndMutateBuilder ifNotExists() {
throw new UnsupportedOperationException(
"CheckAndMutate for non-equal comparison " + "not implemented");
}
@Override
public CheckAndMutateBuilder ifMatches(CompareOperator compareOp, byte[] value) {
if (compareOp == CompareOperator.EQUAL) {
this.value = Preconditions.checkNotNull(value, "value is null");
return this;
} else {
throw new UnsupportedOperationException(
"CheckAndMutate for non-equal comparison " + "not implemented");
}
}
@Override
public CheckAndMutateBuilder ifEquals(byte[] value) {
this.value = Preconditions.checkNotNull(value, "value is null");
return this;
}
@Override
public boolean thenPut(Put put) throws IOException {
return doCheckAndPut(row, family, qualifier, value, put);
}
@Override
public boolean thenDelete(Delete delete) throws IOException {
return doCheckAndDelete(row, family, qualifier, value, delete);
}
@Override
public boolean thenMutate(RowMutations mutation) throws IOException {
throw new UnsupportedOperationException("thenMutate not implemented");
}
}
@Override
public RegionLocator getRegionLocator() throws IOException {
throw new UnsupportedOperationException();
}
}
| |
package ecologylab.bigsemantics.documentcache;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.nio.charset.Charset;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.ParseException;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpDelete;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpHead;
import org.apache.http.client.methods.HttpPut;
import org.apache.http.entity.ByteArrayEntity;
import org.apache.http.entity.StringEntity;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import ecologylab.bigsemantics.httpclient.HttpClientFactory;
/**
* This class uses apache's httpclient version 4.2 to interface with a couchdb instance.
*
* @author Zach Brown
*/
public class CouchHttpAccessor implements CouchAccessor
{
private final static Logger logger;
private final static HttpClientFactory httpClientFactory;
static
{
logger = LoggerFactory.getLogger(CouchHttpAccessor.class);
httpClientFactory = new HttpClientFactory();
}
// Where the database service is
private String databaseUrl;
private HttpClient httpclient = httpClientFactory.create();
public CouchHttpAccessor(String databaseUrl)
{
if (!databaseUrl.startsWith("http://"))
{
databaseUrl = "http://" + databaseUrl;
}
this.databaseUrl = databaseUrl;
}
@Override
public String getDoc(String docId, String tableId)
throws CouchAccessorException, ParseException, IOException
{
String location = databaseUrl + "/" + tableId + "/" + docId;
logger.info("docId = {}, tableId = {}", docId, tableId);
HttpGet httpget = new HttpGet(location);
try
{
HttpResponse response = httpclient.execute(httpget);
int status_code = response.getStatusLine().getStatusCode();
if (status_code == 200 || status_code == 201 || status_code == 202)
{
String result = EntityUtils.toString(response.getEntity(), "UTF-8");
return result;
}
else if (status_code == 404)// There's not a major issue, the document just isn't there
{
return null;
}
else
// There was some kind of issue
{
String explaination = EntityUtils.toString(response.getEntity(), "UTF-8");
throw new CouchAccessorException(explaination, status_code, databaseUrl, tableId, docId);
}
}
finally
{
httpget.releaseConnection();
}
}
@Override
public boolean putDoc(String docID, String docContent, String tableID)
throws ParseException, IOException, CouchAccessorException
{
String location = databaseUrl + "/" + tableID + "/" + docID;
HttpPut httpput = new HttpPut(location);
try
{
StringEntity entity = new StringEntity(docContent, "UTF-8");
// System.out.println("docContent " + docContent);
entity.setContentType("application/json");
int size = docContent.length();
httpput.setEntity(entity);
String request = EntityUtils.toString(entity);
// System.out.println(request);
HttpResponse response = httpclient.execute(httpput);
// System.out.println(response);
int status_code = response.getStatusLine().getStatusCode();
if (status_code == 200 || status_code == 201)
{
return true;
}
else if (status_code == 409)
{
return false;
}
else
{
HttpEntity error_entity = response.getEntity();
String error_msg = EntityUtils.toString(error_entity);
throw new CouchAccessorException(error_msg, status_code, databaseUrl, tableID, docID);
}
}
finally
{
httpput.releaseConnection();
}
}
@Override
public boolean updateDoc(String docID, String docContent, String tableID)
throws ClientProtocolException, IOException, CouchAccessorException
{
String rev = "";
String location = databaseUrl + "/" + tableID + "/" + docID;
HttpHead httphead = new HttpHead(location);
try
{
HttpResponse headResponse = httpclient.execute(httphead);
int status_code = headResponse.getStatusLine().getStatusCode();
if (status_code == 404)
return false; // Can't update because the document doesn't exist
rev = headResponse.getHeaders("ETag")[0].getValue();
rev = rev.split("\"")[1];
// This block adds the revision key to the json object, which couchDB requires inorder to
// update documents.
int lastbrace = docContent.lastIndexOf("}");
docContent = docContent.substring(0, lastbrace);
// System.out.println("This is the json without the las brace" + json);
docContent = docContent + " , \"_rev\" : \"" + rev + "\" }";
// System.out.println("This is the json after adding rev " + json);
HttpPut httpput = new HttpPut(location);
StringEntity entity = new StringEntity(docContent, "UTF-8");
entity.setContentType("application/json");
httpput.setEntity(entity);
try
{
HttpResponse updateResponse = httpclient.execute(httpput);
status_code = updateResponse.getStatusLine().getStatusCode();
if (status_code == 200 || status_code == 201)
{
return true;
}
else
{
HttpEntity error_entity = updateResponse.getEntity();
String error_msg = EntityUtils.toString(error_entity);
throw new CouchAccessorException(error_msg, status_code, databaseUrl, tableID, docID);
}
}
finally
{
httpput.releaseConnection();
}
}
finally
{
httphead.releaseConnection();
}
}
@Override
public boolean dropDoc(String docID, String tableID)
throws CouchAccessorException, ClientProtocolException, IOException
{
if (docID.trim().equals(""))
{
throw new CouchAccessorException("Drop Doc should not be used with an empty id that will delete the database!!",
0,
databaseUrl,
tableID,
docID);
}
String rev = "";
String location = databaseUrl + "/" + tableID + "/" + docID;
HttpHead httphead = new HttpHead(location);
try
{
HttpResponse headResponse = httpclient.execute(httphead);
int status_code = headResponse.getStatusLine().getStatusCode();
if (status_code == 404)
return false;
rev = headResponse.getHeaders("ETag")[0].getValue();
rev = rev.split("\"")[1];
// System.out.println("The revision code is " + rev );
location = location + "?rev=" + rev;
HttpDelete httpdelete = new HttpDelete(location);
try
{
HttpResponse delResponse = httpclient.execute(httpdelete);
status_code = delResponse.getStatusLine().getStatusCode();
if (status_code == 200 || status_code == 201)
{
return true;
}
else
{
HttpEntity error_entity = delResponse.getEntity();
String error_msg = EntityUtils.toString(error_entity);
throw new CouchAccessorException(error_msg, status_code, databaseUrl, tableID, docID);
}
}
finally
{
httpdelete.releaseConnection();
}
}
finally
{
httphead.releaseConnection();
}
}
@Override
public boolean putAttach(String docID,
String tableID,
String content,
String mimeType,
String contentTitle)
throws ClientProtocolException, IOException, CouchAccessorException
{
String rev = "";
String location = databaseUrl + "/" + tableID + "/" + docID;
HttpHead httphead = new HttpHead(location);
try
{
HttpResponse headResponse = httpclient.execute(httphead);
// System.out.println("Tried " + httphead );
int status_code = headResponse.getStatusLine().getStatusCode();
// System.out.println("Code of response " + status_code );
if (status_code == 404)
{
return false;
}
rev = headResponse.getHeaders("ETag")[0].getValue();
rev = rev.split("\"")[1];
// This title might cause a problem
location = location + "/" + contentTitle + "/?rev=";
location += rev;
byte[] docContent = content.getBytes(Charset.forName("UTF-8"));
HttpPut httpput = new HttpPut(location);
ByteArrayEntity entity = new ByteArrayEntity(docContent);
entity.setContentType(mimeType);
httpput.setEntity(entity);
try
{
HttpResponse attachResponse = httpclient.execute(httpput);
// System.out.println("Tried " + httpput );
status_code = attachResponse.getStatusLine().getStatusCode();
// System.out.println("Code of response " + status_code );
if (status_code == 200 || status_code == 201)
{
return true;
}
else
{
HttpEntity error_entity = attachResponse.getEntity();
String error_msg = EntityUtils.toString(error_entity);
throw new CouchAccessorException(error_msg, status_code, databaseUrl, tableID, docID);
}
}
finally
{
httpput.releaseConnection();
}
}
finally
{
httphead.releaseConnection();
}
}
@Override
public byte[] getAttach(String docId, String tableId, String title)
{
String location = databaseUrl + "/" + tableId + "/" + docId + "/" + title;
logger.info("docId = {}, tableId = {}", docId, tableId);
HttpGet httpget = new HttpGet(location);
try
{
HttpResponse response = httpclient.execute(httpget);
int status_code = response.getStatusLine().getStatusCode();
if (status_code == 200 || status_code == 201 || status_code == 202)
{
byte[] result = EntityUtils.toByteArray(response.getEntity());
return result;
}
else
{
return null;
}
}
catch (UnsupportedEncodingException e)
{
logger.error("docId = " + docId + ", tableId = " + tableId, e);
}
catch (ParseException e)
{
logger.error("docId = " + docId + ", tableId = " + tableId, e);
}
catch (IOException e)
{
logger.error("docId = " + docId + ", tableId = " + tableId, e);
}
finally
{
httpget.releaseConnection();
}
return null;
}
}
| |
/*
*
* Copyright 2018. AppDynamics LLC and its affiliates.
* All Rights Reserved.
* This is unpublished proprietary source code of AppDynamics LLC and its affiliates.
* The copyright notice above does not evidence any actual or intended publication of such source code.
*
*/
package com.appdynamics.extensions.apache;
import com.appdynamics.extensions.AMonitorJob;
import com.appdynamics.extensions.MetricWriteHelper;
import com.appdynamics.extensions.TasksExecutionServiceProvider;
import com.appdynamics.extensions.apache.input.Stat;
import com.appdynamics.extensions.apache.metrics.JKStats;
import com.appdynamics.extensions.conf.MonitorContextConfiguration;
import com.appdynamics.extensions.http.HttpClientUtils;
import com.appdynamics.extensions.logging.ExtensionsLoggerFactory;
import com.appdynamics.extensions.metrics.Metric;
import com.appdynamics.extensions.util.PathResolver;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.common.collect.Maps;
import com.singularity.ee.agent.systemagent.api.AManagedMonitor;
import com.singularity.ee.agent.systemagent.api.exception.TaskExecutionException;
import org.apache.commons.io.FileUtils;
import org.apache.http.impl.client.CloseableHttpClient;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.Mockito;
import org.mockito.invocation.InvocationOnMock;
import org.mockito.stubbing.Answer;
import org.powermock.api.mockito.PowerMockito;
import org.powermock.core.classloader.annotations.PowerMockIgnore;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.junit4.PowerMockRunner;
import org.slf4j.Logger;
import java.io.File;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.Phaser;
import static org.mockito.Matchers.any;
import static org.mockito.Matchers.anyString;
@RunWith(PowerMockRunner.class)
@PrepareForTest(HttpClientUtils.class)
@PowerMockIgnore("javax.net.ssl.*")
public class JKStatsTest {
public static final Logger logger = ExtensionsLoggerFactory.getLogger(JKStatsTest.class);
@Mock
private TasksExecutionServiceProvider serviceProvider;
@Mock
private MetricWriteHelper metricWriter;
@Mock
private Phaser phaser;
private Stat.Stats stat;
private MonitorContextConfiguration monitorConfiguration = new MonitorContextConfiguration("Apache", "Custom Metrics|Apache|", PathResolver.resolveDirectory(AManagedMonitor.class), Mockito.mock(AMonitorJob.class));
private Map<String, String> expectedValueMap;
private JKStats jkStats;
@Before
public void before(){
monitorConfiguration.setConfigYml("src/test/resources/test-config.yml");
monitorConfiguration.setMetricXml("src/test/resources/test-metrics.xml", Stat.Stats.class);
//Mockito.when(serviceProvider.getMonitorConfiguration()).thenReturn(monitorConfiguration);
Mockito.when(serviceProvider.getMetricWriteHelper()).thenReturn(metricWriter);
stat = (Stat.Stats) monitorConfiguration.getMetricsXml();
jkStats = Mockito.spy(new JKStats(stat.getStats()[1], monitorConfiguration.getContext(), new HashMap<String, String>(), metricWriter,
monitorConfiguration.getMetricPrefix(), phaser));
PowerMockito.mockStatic(HttpClientUtils.class);
PowerMockito.mockStatic(CloseableHttpClient.class);
PowerMockito.when(HttpClientUtils.getResponseAsLines(any(CloseableHttpClient.class), anyString())).thenAnswer(
new Answer() {
public Object answer(InvocationOnMock invocationOnMock) throws Throwable {
ObjectMapper mapper = new ObjectMapper();
List<String> list = FileUtils.readLines(new File("src/test/resources/jk-status.txt"), "utf-8");
logger.info("Returning the mocked data for the api ");
return list;
}
});
}
@Test
public void testServerStats() throws TaskExecutionException {
expectedValueMap = getExpectedValueMap();
jkStats.run();
validateMetrics();
Assert.assertTrue("The expected values were not send. The missing values are " + expectedValueMap
, expectedValueMap.isEmpty());
}
private Map<String, String> getExpectedValueMap() {
Map<String, String> map = Maps.newHashMap();
map.put("Custom Metrics|Apache|worker|worker1|connection_pool_timeout","0");
map.put("Custom Metrics|Apache|worker|worker2|connection_pool_timeout","0");
map.put("Custom Metrics|Apache|worker|worker1|ping_timeout","10000");
map.put("Custom Metrics|Apache|worker|worker2|ping_timeout","10000");
map.put("Custom Metrics|Apache|worker|worker1|connect_timeout","0");
map.put("Custom Metrics|Apache|worker|worker2|connect_timeout","0");
map.put("Custom Metrics|Apache|worker|worker1|prepost_timeout","0");
map.put("Custom Metrics|Apache|worker|worker2|prepost_timeout","0");
map.put("Custom Metrics|Apache|worker|worker1|reply_timeout","0");
map.put("Custom Metrics|Apache|worker|worker2|reply_timeout","0");
map.put("Custom Metrics|Apache|worker|worker1|retries","2");
map.put("Custom Metrics|Apache|worker|worker2|retries","2");
map.put("Custom Metrics|Apache|worker|worker1|connection_ping_interval","0");
map.put("Custom Metrics|Apache|worker|worker2|connection_ping_interval","0");
map.put("Custom Metrics|Apache|worker|worker1|recovery_options","0");
map.put("Custom Metrics|Apache|worker|worker2|recovery_options","0");
map.put("Custom Metrics|Apache|worker|worker1|max_packet_size","8192");
map.put("Custom Metrics|Apache|worker|worker2|max_packet_size","8192");
map.put("Custom Metrics|Apache|worker|worker1|activation","STP");
map.put("Custom Metrics|Apache|worker|worker2|activation","STP");
map.put("Custom Metrics|Apache|worker|worker1|lbfactor","100");
map.put("Custom Metrics|Apache|worker|worker2|lbfactor","100");
map.put("Custom Metrics|Apache|worker|worker1|lbmult","1");
map.put("Custom Metrics|Apache|worker|worker2|lbmult","1");
map.put("Custom Metrics|Apache|worker|worker1|distance","0");
map.put("Custom Metrics|Apache|worker|worker2|distance","0");
map.put("Custom Metrics|Apache|worker|worker1|lbvalue","0");
map.put("Custom Metrics|Apache|worker|worker2|lbvalue","0");
map.put("Custom Metrics|Apache|worker|worker1|elected","0");
map.put("Custom Metrics|Apache|worker|worker2|elected","0");
map.put("Custom Metrics|Apache|worker|worker1|sessions","0");
map.put("Custom Metrics|Apache|worker|worker2|sessions","0");
map.put("Custom Metrics|Apache|worker|worker1|errors","0");
map.put("Custom Metrics|Apache|worker|worker2|errors","0");
map.put("Custom Metrics|Apache|worker|worker1|client_errors","0");
map.put("Custom Metrics|Apache|worker|worker2|client_errors","0");
map.put("Custom Metrics|Apache|worker|worker1|reply_timeouts","0");
map.put("Custom Metrics|Apache|worker|worker2|reply_timeouts","0");
map.put("Custom Metrics|Apache|worker|worker1|transferred","0");
map.put("Custom Metrics|Apache|worker|worker2|transferred","0");
map.put("Custom Metrics|Apache|worker|worker1|read","0");
map.put("Custom Metrics|Apache|worker|worker2|read","0");
map.put("Custom Metrics|Apache|worker|worker1|busy","0");
map.put("Custom Metrics|Apache|worker|worker2|busy","0");
map.put("Custom Metrics|Apache|worker|worker1|max_busy","0");
map.put("Custom Metrics|Apache|worker|worker2|max_busy","0");
map.put("Custom Metrics|Apache|worker|worker1|connected","0");
map.put("Custom Metrics|Apache|worker|worker2|connected","0");
map.put("Custom Metrics|Apache|worker|worker1|time_to_recover_min","0");
map.put("Custom Metrics|Apache|worker|worker2|time_to_recover_min","0");
map.put("Custom Metrics|Apache|worker|worker1|time_to_recover_max","0");
map.put("Custom Metrics|Apache|worker|worker2|time_to_recover_max","0");
map.put("Custom Metrics|Apache|worker|worker1|used","0");
map.put("Custom Metrics|Apache|worker|worker2|used","0");
map.put("Custom Metrics|Apache|worker|worker1|map_count","0");
map.put("Custom Metrics|Apache|worker|worker2|map_count","0");
map.put("Custom Metrics|Apache|worker|worker1|last_reset_ago","518");
map.put("Custom Metrics|Apache|worker|worker2|last_reset_ago","518");
return map;
}
private void validateMetrics(){
for(Metric metric: jkStats.getMetrics()) {
String actualValue = metric.getMetricValue();
String metricName = metric.getMetricPath();
if (expectedValueMap.containsKey(metricName)) {
String expectedValue = expectedValueMap.get(metricName);
Assert.assertEquals("The value of the metric " + metricName + " failed", expectedValue, actualValue);
expectedValueMap.remove(metricName);
} else {
System.out.println("\"" + metricName + "\",\"" + actualValue + "\"");
Assert.fail("Unknown Metric " + metricName);
}
}
}
@Test
public void testBigDecimalToString() {
JKStats.toBigDecimal("33227844900").toString().equals("33227844900");
JKStats.toBigDecimal("332278.900").toString().equals("332278.900");
JKStats.toBigDecimal("33").toString().equals("33");
}
@Test(expected = NullPointerException.class)
public void testInvalidNumberToBigDecimal() {
JKStats.toBigDecimal("23asf").toString().equals("23asf");
}
}
| |
/*
* Licensed to Elasticsearch under one or more contributor
* license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright
* ownership. Elasticsearch 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.elasticsearch.index;
import com.google.common.collect.ImmutableMap;
import org.apache.lucene.util.Accountable;
import org.apache.lucene.util.IOUtils;
import org.elasticsearch.ElasticsearchException;
import org.elasticsearch.cluster.metadata.IndexMetaData;
import org.elasticsearch.cluster.routing.ShardRouting;
import org.elasticsearch.common.Nullable;
import org.elasticsearch.common.Strings;
import org.elasticsearch.common.inject.CreationException;
import org.elasticsearch.common.inject.Inject;
import org.elasticsearch.common.inject.Injector;
import org.elasticsearch.common.inject.Injectors;
import org.elasticsearch.common.inject.Module;
import org.elasticsearch.common.inject.ModulesBuilder;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.env.NodeEnvironment;
import org.elasticsearch.env.ShardLock;
import org.elasticsearch.index.aliases.IndexAliasesService;
import org.elasticsearch.index.analysis.AnalysisService;
import org.elasticsearch.index.cache.IndexCache;
import org.elasticsearch.index.cache.bitset.BitsetFilterCache;
import org.elasticsearch.index.fielddata.FieldDataType;
import org.elasticsearch.index.fielddata.IndexFieldDataCache;
import org.elasticsearch.index.fielddata.IndexFieldDataService;
import org.elasticsearch.index.mapper.MappedFieldType;
import org.elasticsearch.index.mapper.MapperService;
import org.elasticsearch.index.query.IndexQueryParserService;
import org.elasticsearch.index.settings.IndexSettings;
import org.elasticsearch.index.settings.IndexSettingsService;
import org.elasticsearch.index.shard.IndexShard;
import org.elasticsearch.index.shard.IndexShardModule;
import org.elasticsearch.index.shard.ShardId;
import org.elasticsearch.index.shard.ShardNotFoundException;
import org.elasticsearch.index.shard.ShardPath;
import org.elasticsearch.index.similarity.SimilarityService;
import org.elasticsearch.index.store.IndexStore;
import org.elasticsearch.index.store.Store;
import org.elasticsearch.index.store.StoreModule;
import org.elasticsearch.indices.IndicesLifecycle;
import org.elasticsearch.indices.IndicesService;
import org.elasticsearch.indices.InternalIndicesLifecycle;
import org.elasticsearch.indices.cache.query.IndicesQueryCache;
import org.elasticsearch.plugins.PluginsService;
import java.io.Closeable;
import java.io.IOException;
import java.nio.file.Path;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;
import static org.elasticsearch.common.collect.MapBuilder.newMapBuilder;
/**
*
*/
public class IndexService extends AbstractIndexComponent implements IndexComponent, Iterable<IndexShard> {
private final Injector injector;
private final Settings indexSettings;
private final PluginsService pluginsService;
private final InternalIndicesLifecycle indicesLifecycle;
private final AnalysisService analysisService;
private final MapperService mapperService;
private final IndexQueryParserService queryParserService;
private final SimilarityService similarityService;
private final IndexAliasesService aliasesService;
private final IndexCache indexCache;
private final IndexFieldDataService indexFieldData;
private final BitsetFilterCache bitsetFilterCache;
private final IndexSettingsService settingsService;
private final NodeEnvironment nodeEnv;
private final IndicesService indicesServices;
private volatile ImmutableMap<Integer, IndexShardInjectorPair> shards = ImmutableMap.of();
private static class IndexShardInjectorPair {
private final IndexShard indexShard;
private final Injector injector;
public IndexShardInjectorPair(IndexShard indexShard, Injector injector) {
this.indexShard = indexShard;
this.injector = injector;
}
public IndexShard getIndexShard() {
return indexShard;
}
public Injector getInjector() {
return injector;
}
}
private final AtomicBoolean closed = new AtomicBoolean(false);
private final AtomicBoolean deleted = new AtomicBoolean(false);
@Inject
public IndexService(Injector injector, Index index, @IndexSettings Settings indexSettings, NodeEnvironment nodeEnv,
AnalysisService analysisService, MapperService mapperService, IndexQueryParserService queryParserService,
SimilarityService similarityService, IndexAliasesService aliasesService, IndexCache indexCache,
IndexSettingsService settingsService,
IndexFieldDataService indexFieldData, BitsetFilterCache bitSetFilterCache, IndicesService indicesServices) {
super(index, indexSettings);
this.injector = injector;
this.indexSettings = indexSettings;
this.analysisService = analysisService;
this.mapperService = mapperService;
this.queryParserService = queryParserService;
this.similarityService = similarityService;
this.aliasesService = aliasesService;
this.indexCache = indexCache;
this.indexFieldData = indexFieldData;
this.settingsService = settingsService;
this.bitsetFilterCache = bitSetFilterCache;
this.pluginsService = injector.getInstance(PluginsService.class);
this.indicesServices = indicesServices;
this.indicesLifecycle = (InternalIndicesLifecycle) injector.getInstance(IndicesLifecycle.class);
// inject workarounds for cyclic dep
indexFieldData.setListener(new FieldDataCacheListener(this));
bitSetFilterCache.setListener(new BitsetCacheListener(this));
this.nodeEnv = nodeEnv;
}
public int numberOfShards() {
return shards.size();
}
public InternalIndicesLifecycle indicesLifecycle() {
return this.indicesLifecycle;
}
@Override
public Iterator<IndexShard> iterator() {
return shards.values().stream().map((p) -> p.getIndexShard()).iterator();
}
public boolean hasShard(int shardId) {
return shards.containsKey(shardId);
}
/**
* Return the shard with the provided id, or null if there is no such shard.
*/
@Nullable
public IndexShard shard(int shardId) {
IndexShardInjectorPair indexShardInjectorPair = shards.get(shardId);
if (indexShardInjectorPair != null) {
return indexShardInjectorPair.getIndexShard();
}
return null;
}
/**
* Return the shard with the provided id, or throw an exception if it doesn't exist.
*/
public IndexShard shardSafe(int shardId) {
IndexShard indexShard = shard(shardId);
if (indexShard == null) {
throw new ShardNotFoundException(new ShardId(index, shardId));
}
return indexShard;
}
public Set<Integer> shardIds() {
return shards.keySet();
}
public Injector injector() {
return injector;
}
public IndexSettingsService settingsService() {
return this.settingsService;
}
public IndexCache cache() {
return indexCache;
}
public IndexFieldDataService fieldData() {
return indexFieldData;
}
public BitsetFilterCache bitsetFilterCache() {
return bitsetFilterCache;
}
public AnalysisService analysisService() {
return this.analysisService;
}
public MapperService mapperService() {
return mapperService;
}
public IndexQueryParserService queryParserService() {
return queryParserService;
}
public SimilarityService similarityService() {
return similarityService;
}
public IndexAliasesService aliasesService() {
return aliasesService;
}
public synchronized void close(final String reason, boolean delete) {
if (closed.compareAndSet(false, true)) {
deleted.compareAndSet(false, delete);
final Set<Integer> shardIds = shardIds();
for (final int shardId : shardIds) {
try {
removeShard(shardId, reason);
} catch (Throwable t) {
logger.warn("failed to close shard", t);
}
}
}
}
/**
* Return the shard injector for the provided id, or throw an exception if there is no such shard.
*/
public Injector shardInjectorSafe(int shardId) {
IndexShardInjectorPair indexShardInjectorPair = shards.get(shardId);
if (indexShardInjectorPair == null) {
throw new ShardNotFoundException(new ShardId(index, shardId));
}
return indexShardInjectorPair.getInjector();
}
public String indexUUID() {
return indexSettings.get(IndexMetaData.SETTING_INDEX_UUID, IndexMetaData.INDEX_UUID_NA_VALUE);
}
// NOTE: O(numShards) cost, but numShards should be smallish?
private long getAvgShardSizeInBytes() throws IOException {
long sum = 0;
int count = 0;
for(IndexShard indexShard : this) {
sum += indexShard.store().stats().sizeInBytes();
count++;
}
if (count == 0) {
return -1L;
} else {
return sum / count;
}
}
public synchronized IndexShard createShard(int sShardId, ShardRouting routing) {
final boolean primary = routing.primary();
/*
* TODO: we execute this in parallel but it's a synced method. Yet, we might
* be able to serialize the execution via the cluster state in the future. for now we just
* keep it synced.
*/
if (closed.get()) {
throw new IllegalStateException("Can't create shard [" + index.name() + "][" + sShardId + "], closed");
}
final ShardId shardId = new ShardId(index, sShardId);
ShardLock lock = null;
boolean success = false;
Injector shardInjector = null;
try {
lock = nodeEnv.shardLock(shardId, TimeUnit.SECONDS.toMillis(5));
indicesLifecycle.beforeIndexShardCreated(shardId, indexSettings);
ShardPath path;
try {
path = ShardPath.loadShardPath(logger, nodeEnv, shardId, indexSettings);
} catch (IllegalStateException ex) {
logger.warn("{} failed to load shard path, trying to remove leftover", shardId);
try {
ShardPath.deleteLeftoverShardDirectory(logger, nodeEnv, lock, indexSettings);
path = ShardPath.loadShardPath(logger, nodeEnv, shardId, indexSettings);
} catch (Throwable t) {
t.addSuppressed(ex);
throw t;
}
}
if (path == null) {
// TODO: we should, instead, hold a "bytes reserved" of how large we anticipate this shard will be, e.g. for a shard
// that's being relocated/replicated we know how large it will become once it's done copying:
// Count up how many shards are currently on each data path:
Map<Path,Integer> dataPathToShardCount = new HashMap<>();
for(IndexShard shard : this) {
Path dataPath = shard.shardPath().getRootStatePath();
Integer curCount = dataPathToShardCount.get(dataPath);
if (curCount == null) {
curCount = 0;
}
dataPathToShardCount.put(dataPath, curCount+1);
}
path = ShardPath.selectNewPathForShard(nodeEnv, shardId, indexSettings, routing.getExpectedShardSize() == ShardRouting.UNAVAILABLE_EXPECTED_SHARD_SIZE ? getAvgShardSizeInBytes() : routing.getExpectedShardSize(),
dataPathToShardCount);
logger.debug("{} creating using a new path [{}]", shardId, path);
} else {
logger.debug("{} creating using an existing path [{}]", shardId, path);
}
if (shards.containsKey(shardId.id())) {
throw new IndexShardAlreadyExistsException(shardId + " already exists");
}
logger.debug("creating shard_id {}", shardId);
// if we are on a shared FS we only own the shard (ie. we can safely delete it) if we are the primary.
final boolean canDeleteShardContent = IndexMetaData.isOnSharedFilesystem(indexSettings) == false ||
(primary && IndexMetaData.isOnSharedFilesystem(indexSettings));
ModulesBuilder modules = new ModulesBuilder();
// plugin modules must be added here, before others or we can get crazy injection errors...
for (Module pluginModule : pluginsService.shardModules(indexSettings)) {
modules.add(pluginModule);
}
modules.add(new IndexShardModule(shardId, primary, indexSettings));
modules.add(new StoreModule(injector.getInstance(IndexStore.class).shardDirectory(), lock,
new StoreCloseListener(shardId, canDeleteShardContent, new Closeable() {
@Override
public void close() throws IOException {
injector.getInstance(IndicesQueryCache.class).onClose(shardId);
}
}), path));
pluginsService.processModules(modules);
try {
shardInjector = modules.createChildInjector(injector);
} catch (CreationException e) {
ElasticsearchException ex = new ElasticsearchException("failed to create shard", Injectors.getFirstErrorFailure(e));
ex.setShard(shardId);
throw ex;
} catch (Throwable e) {
ElasticsearchException ex = new ElasticsearchException("failed to create shard", e);
ex.setShard(shardId);
throw ex;
}
IndexShard indexShard = shardInjector.getInstance(IndexShard.class);
indicesLifecycle.indexShardStateChanged(indexShard, null, "shard created");
indicesLifecycle.afterIndexShardCreated(indexShard);
shards = newMapBuilder(shards).put(shardId.id(), new IndexShardInjectorPair(indexShard, shardInjector)).immutableMap();
success = true;
return indexShard;
} catch (IOException e) {
ElasticsearchException ex = new ElasticsearchException("failed to create shard", e);
ex.setShard(shardId);
throw ex;
} finally {
if (success == false) {
IOUtils.closeWhileHandlingException(lock);
if (shardInjector != null) {
IndexShard indexShard = shardInjector.getInstance(IndexShard.class);
closeShardInjector("initialization failed", shardId, shardInjector, indexShard);
}
}
}
}
public synchronized void removeShard(int shardId, String reason) {
final ShardId sId = new ShardId(index, shardId);
final Injector shardInjector;
final IndexShard indexShard;
if (shards.containsKey(shardId) == false) {
return;
}
logger.debug("[{}] closing... (reason: [{}])", shardId, reason);
HashMap<Integer, IndexShardInjectorPair> tmpShardsMap = new HashMap<>(shards);
IndexShardInjectorPair indexShardInjectorPair = tmpShardsMap.remove(shardId);
indexShard = indexShardInjectorPair.getIndexShard();
shardInjector = indexShardInjectorPair.getInjector();
shards = ImmutableMap.copyOf(tmpShardsMap);
closeShardInjector(reason, sId, shardInjector, indexShard);
logger.debug("[{}] closed (reason: [{}])", shardId, reason);
}
private void closeShardInjector(String reason, ShardId sId, Injector shardInjector, IndexShard indexShard) {
final int shardId = sId.id();
try {
try {
indicesLifecycle.beforeIndexShardClosed(sId, indexShard, indexSettings);
} finally {
// close everything else even if the beforeIndexShardClosed threw an exception
for (Class<? extends Closeable> closeable : pluginsService.shardServices()) {
try {
shardInjector.getInstance(closeable).close();
} catch (Throwable e) {
logger.debug("[{}] failed to clean plugin shard service [{}]", e, shardId, closeable);
}
}
// this logic is tricky, we want to close the engine so we rollback the changes done to it
// and close the shard so no operations are allowed to it
if (indexShard != null) {
try {
final boolean flushEngine = deleted.get() == false && closed.get(); // only flush we are we closed (closed index or shutdown) and if we are not deleted
indexShard.close(reason, flushEngine);
} catch (Throwable e) {
logger.debug("[{}] failed to close index shard", e, shardId);
// ignore
}
}
// call this before we close the store, so we can release resources for it
indicesLifecycle.afterIndexShardClosed(sId, indexShard, indexSettings);
}
} finally {
try {
shardInjector.getInstance(Store.class).close();
} catch (Throwable e) {
logger.warn("[{}] failed to close store on shard removal (reason: [{}])", e, shardId, reason);
}
}
}
/**
* This method gets an instance for each of the given classes passed and calls #close() on the returned instance.
* NOTE: this method swallows all exceptions thrown from the close method of the injector and logs them as debug log
*/
private void closeInjectorResource(ShardId shardId, Injector shardInjector, Class<? extends Closeable>... toClose) {
for (Class<? extends Closeable> closeable : toClose) {
if (closeInjectorOptionalResource(shardId, shardInjector, closeable) == false) {
logger.warn("[{}] no instance available for [{}], ignoring... ", shardId, closeable.getSimpleName());
}
}
}
/**
* Closes an optional resource. Returns true if the resource was found;
* NOTE: this method swallows all exceptions thrown from the close method of the injector and logs them as debug log
*/
private boolean closeInjectorOptionalResource(ShardId shardId, Injector shardInjector, Class<? extends Closeable> toClose) {
try {
final Closeable instance = shardInjector.getInstance(toClose);
if (instance == null) {
return false;
}
IOUtils.close(instance);
} catch (Throwable t) {
logger.debug("{} failed to close {}", t, shardId, Strings.toUnderscoreCase(toClose.getSimpleName()));
}
return true;
}
private void onShardClose(ShardLock lock, boolean ownsShard) {
if (deleted.get()) { // we remove that shards content if this index has been deleted
try {
if (ownsShard) {
try {
indicesLifecycle.beforeIndexShardDeleted(lock.getShardId(), indexSettings);
} finally {
indicesServices.deleteShardStore("delete index", lock, indexSettings);
indicesLifecycle.afterIndexShardDeleted(lock.getShardId(), indexSettings);
}
}
} catch (IOException e) {
indicesServices.addPendingDelete(lock.getShardId(), indexSettings);
logger.debug("[{}] failed to delete shard content - scheduled a retry", e, lock.getShardId().id());
}
}
}
private class StoreCloseListener implements Store.OnClose {
private final ShardId shardId;
private final boolean ownsShard;
private final Closeable[] toClose;
public StoreCloseListener(ShardId shardId, boolean ownsShard, Closeable... toClose) {
this.shardId = shardId;
this.ownsShard = ownsShard;
this.toClose = toClose;
}
@Override
public void handle(ShardLock lock) {
try {
assert lock.getShardId().equals(shardId) : "shard id mismatch, expected: " + shardId + " but got: " + lock.getShardId();
onShardClose(lock, ownsShard);
} finally {
try {
IOUtils.close(toClose);
} catch (IOException ex) {
logger.debug("failed to close resource", ex);
}
}
}
}
public Settings getIndexSettings() {
return indexSettings;
}
private static final class BitsetCacheListener implements BitsetFilterCache.Listener {
final IndexService indexService;
private BitsetCacheListener(IndexService indexService) {
this.indexService = indexService;
}
@Override
public void onCache(ShardId shardId, Accountable accountable) {
if (shardId != null) {
final IndexShard shard = indexService.shard(shardId.id());
if (shard != null) {
long ramBytesUsed = accountable != null ? accountable.ramBytesUsed() : 0l;
shard.shardBitsetFilterCache().onCached(ramBytesUsed);
}
}
}
@Override
public void onRemoval(ShardId shardId, Accountable accountable) {
if (shardId != null) {
final IndexShard shard = indexService.shard(shardId.id());
if (shard != null) {
long ramBytesUsed = accountable != null ? accountable.ramBytesUsed() : 0l;
shard.shardBitsetFilterCache().onRemoval(ramBytesUsed);
}
}
}
}
private final class FieldDataCacheListener implements IndexFieldDataCache.Listener {
final IndexService indexService;
public FieldDataCacheListener(IndexService indexService) {
this.indexService = indexService;
}
@Override
public void onCache(ShardId shardId, MappedFieldType.Names fieldNames, FieldDataType fieldDataType, Accountable ramUsage) {
if (shardId != null) {
final IndexShard shard = indexService.shard(shardId.id());
if (shard != null) {
shard.fieldData().onCache(shardId, fieldNames, fieldDataType, ramUsage);
}
}
}
@Override
public void onRemoval(ShardId shardId, MappedFieldType.Names fieldNames, FieldDataType fieldDataType, boolean wasEvicted, long sizeInBytes) {
if (shardId != null) {
final IndexShard shard = indexService.shard(shardId.id());
if (shard != null) {
shard.fieldData().onRemoval(shardId, fieldNames, fieldDataType, wasEvicted, sizeInBytes);
}
}
}
}
}
| |
/*
* Copyright (C) 2006 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.common.util.concurrent;
import static com.google.common.base.Preconditions.checkNotNull;
import static java.util.concurrent.TimeUnit.NANOSECONDS;
import java.lang.reflect.UndeclaredThrowableException;
import java.util.concurrent.CancellationException;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Executor;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import java.util.concurrent.atomic.AtomicBoolean;
import androidcollections.annotations.Nullable;
import com.google.common.annotations.Beta;
import com.google.common.base.Function;
/**
* Static utility methods pertaining to the {@link Future} interface.
*
* @author Kevin Bourrillion
* @author Nishant Thakkar
* @author Sven Mawson
* @since 1
*/
@Beta
public class Futures {
private Futures() {}
/**
* Returns an uninterruptible view of a {@code Future}. If a thread is
* interrupted during an attempt to {@code get()} from the returned future, it
* continues to wait on the result until it is available or the timeout
* elapses, and only then re-interrupts the thread.
*/
public static <V> UninterruptibleFuture<V> makeUninterruptible(
final Future<V> future) {
checkNotNull(future);
if (future instanceof UninterruptibleFuture) {
return (UninterruptibleFuture<V>) future;
}
return new UninterruptibleFuture<V>() {
public boolean cancel(boolean mayInterruptIfRunning) {
return future.cancel(mayInterruptIfRunning);
}
public boolean isCancelled() {
return future.isCancelled();
}
public boolean isDone() {
return future.isDone();
}
public V get(long timeoutDuration, TimeUnit timeoutUnit)
throws TimeoutException, ExecutionException {
boolean interrupted = false;
try {
long timeoutNanos = timeoutUnit.toNanos(timeoutDuration);
long end = System.nanoTime() + timeoutNanos;
while (true) {
try {
return future.get(timeoutNanos, NANOSECONDS);
} catch (InterruptedException e) {
// Future treats negative timeouts just like zero.
timeoutNanos = end - System.nanoTime();
interrupted = true;
}
}
} finally {
if (interrupted) {
Thread.currentThread().interrupt();
}
}
}
public V get() throws ExecutionException {
boolean interrupted = false;
try {
while (true) {
try {
return future.get();
} catch (InterruptedException ignored) {
interrupted = true;
}
}
} finally {
if (interrupted) {
Thread.currentThread().interrupt();
}
}
}
};
}
/**
* Creates a {@link ListenableFuture} out of a normal {@link Future}. The
* returned future will create a thread to wait for the source future to
* complete before executing the listeners.
*
* <p>Callers who have a future that subclasses
* {@link java.util.concurrent.FutureTask} may want to instead subclass
* {@link ListenableFutureTask}, which adds the {@link ListenableFuture}
* functionality to the standard {@code FutureTask} implementation.
*/
public static <T> ListenableFuture<T> makeListenable(Future<T> future) {
if (future instanceof ListenableFuture) {
return (ListenableFuture<T>) future;
}
return new ListenableFutureAdapter<T>(future);
}
/**
* Creates a {@link CheckedFuture} out of a normal {@link Future} and a
* {@link Function} that maps from {@link Exception} instances into the
* appropriate checked type.
*
* <p>The given mapping function will be applied to an
* {@link InterruptedException}, a {@link CancellationException}, or an
* {@link ExecutionException} with the actual cause of the exception.
* See {@link Future#get()} for details on the exceptions thrown.
*/
public static <T, E extends Exception> CheckedFuture<T, E> makeChecked(
Future<T> future, Function<Exception, E> mapper) {
return new MappingCheckedFuture<T, E>(makeListenable(future), mapper);
}
/**
* Creates a {@code ListenableFuture} which has its value set immediately upon
* construction. The getters just return the value. This {@code Future} can't
* be canceled or timed out and its {@code isDone()} method always returns
* {@code true}. It's useful for returning something that implements the
* {@code ListenableFuture} interface but already has the result.
*/
public static <T> ListenableFuture<T> immediateFuture(@Nullable T value) {
ValueFuture<T> future = ValueFuture.create();
future.set(value);
return future;
}
/**
* Creates a {@code CheckedFuture} which has its value set immediately upon
* construction. The getters just return the value. This {@code Future} can't
* be canceled or timed out and its {@code isDone()} method always returns
* {@code true}. It's useful for returning something that implements the
* {@code CheckedFuture} interface but already has the result.
*/
public static <T, E extends Exception> CheckedFuture<T, E>
immediateCheckedFuture(@Nullable T value) {
ValueFuture<T> future = ValueFuture.create();
future.set(value);
return Futures.makeChecked(future, new Function<Exception, E>() {
public E apply(Exception e) {
throw new AssertionError("impossible");
}
});
}
/**
* Creates a {@code ListenableFuture} which has an exception set immediately
* upon construction. The getters just return the value. This {@code Future}
* can't be canceled or timed out and its {@code isDone()} method always
* returns {@code true}. It's useful for returning something that implements
* the {@code ListenableFuture} interface but already has a failed
* result. Calling {@code get()} will throw the provided {@code Throwable}
* (wrapped in an {@code ExecutionException}).
*
* @throws Error if the throwable was an {@link Error}.
*/
public static <T> ListenableFuture<T> immediateFailedFuture(
Throwable throwable) {
checkNotNull(throwable);
ValueFuture<T> future = ValueFuture.create();
future.setException(throwable);
return future;
}
/**
* Creates a {@code CheckedFuture} which has an exception set immediately
* upon construction. The getters just return the value. This {@code Future}
* can't be canceled or timed out and its {@code isDone()} method always
* returns {@code true}. It's useful for returning something that implements
* the {@code CheckedFuture} interface but already has a failed result.
* Calling {@code get()} will throw the provided {@code Throwable} (wrapped in
* an {@code ExecutionException}) and calling {@code checkedGet()} will throw
* the provided exception itself.
*
* @throws Error if the throwable was an {@link Error}.
*/
public static <T, E extends Exception> CheckedFuture<T, E>
immediateFailedCheckedFuture(final E exception) {
checkNotNull(exception);
return makeChecked(Futures.<T>immediateFailedFuture(exception),
new Function<Exception, E>() {
public E apply(Exception e) {
return exception;
}
});
}
/**
* Creates a new {@code ListenableFuture} that wraps another
* {@code ListenableFuture}. The result of the new future is the result of
* the provided function called on the result of the provided future.
* The resulting future doesn't interrupt when aborted.
*
* <p>TODO: Add a version that accepts a normal {@code Future}
*
* <p>The typical use for this method would be when a RPC call is dependent on
* the results of another RPC. One would call the first RPC (input), create a
* function that calls another RPC based on input's result, and then call
* chain on input and that function to get a {@code ListenableFuture} of
* the result.
*
* @param input The future to chain
* @param function A function to chain the results of the provided future
* to the results of the returned future. This will be run in the thread
* that notifies input it is complete.
* @return A future that holds result of the chain.
*/
public static <I, O> ListenableFuture<O> chain(ListenableFuture<I> input,
Function<? super I, ? extends ListenableFuture<? extends O>> function) {
return chain(input, function, MoreExecutors.sameThreadExecutor());
}
/**
* Creates a new {@code ListenableFuture} that wraps another
* {@code ListenableFuture}. The result of the new future is the result of
* the provided function called on the result of the provided future.
* The resulting future doesn't interrupt when aborted.
*
* <p>This version allows an arbitrary executor to be passed in for running
* the chained Function. When using {@link MoreExecutors#sameThreadExecutor},
* the thread chained Function executes in will be whichever thread set the
* result of the input Future, which may be the network thread in the case of
* RPC-based Futures.
*
* @param input The future to chain
* @param function A function to chain the results of the provided future
* to the results of the returned future.
* @param exec Executor to run the function in.
* @return A future that holds result of the chain.
*/
public static <I, O> ListenableFuture<O> chain(ListenableFuture<I> input,
Function<? super I, ? extends ListenableFuture<? extends O>> function,
Executor exec) {
ChainingListenableFuture<I, O> chain =
new ChainingListenableFuture<I, O>(function, input);
input.addListener(chain, exec);
return chain;
}
/**
* Creates a new {@code ListenableFuture} that wraps another
* {@code ListenableFuture}. The result of the new future is the result of
* the provided function called on the result of the provided future.
* The resulting future doesn't interrupt when aborted.
*
* <p>An example use of this method is to convert a serializable object
* returned from an RPC into a POJO.
*
* @param future The future to compose
* @param function A Function to compose the results of the provided future
* to the results of the returned future. This will be run in the thread
* that notifies input it is complete.
* @return A future that holds result of the composition.
*/
public static <I, O> ListenableFuture<O> compose(ListenableFuture<I> future,
final Function<? super I, ? extends O> function) {
return compose(future, function, MoreExecutors.sameThreadExecutor());
}
/**
* Creates a new {@code ListenableFuture} that wraps another
* {@code ListenableFuture}. The result of the new future is the result of
* the provided function called on the result of the provided future.
* The resulting future doesn't interrupt when aborted.
*
* <p>An example use of this method is to convert a serializable object
* returned from an RPC into a POJO.
*
* <p>This version allows an arbitrary executor to be passed in for running
* the chained Function. When using {@link MoreExecutors#sameThreadExecutor},
* the thread chained Function executes in will be whichever thread set the
* result of the input Future, which may be the network thread in the case of
* RPC-based Futures.
*
* @param future The future to compose
* @param function A Function to compose the results of the provided future
* to the results of the returned future.
* @param exec Executor to run the function in.
* @return A future that holds result of the composition.
* @since 2
*/
public static <I, O> ListenableFuture<O> compose(ListenableFuture<I> future,
final Function<? super I, ? extends O> function, Executor exec) {
checkNotNull(function);
Function<I, ListenableFuture<O>> wrapperFunction
= new Function<I, ListenableFuture<O>>() {
public ListenableFuture<O> apply(I input) {
O output = function.apply(input);
return immediateFuture(output);
}
};
return chain(future, wrapperFunction, exec);
}
/**
* Creates a new {@code Future} that wraps another {@code Future}.
* The result of the new future is the result of the provided function called
* on the result of the provided future.
*
* <p>An example use of this method is to convert a Future that produces a
* handle to an object to a future that produces the object itself.
*
* <p>Each call to {@code Future<O>.get(*)} results in a call to
* {@code Future<I>.get(*)}, but {@code function} is only applied once, so it
* is assumed that {@code Future<I>.get(*)} is idempotent.
*
* <p>When calling {@link Future#get(long, TimeUnit)} on the returned
* future, the timeout only applies to the future passed in to this method.
* Any additional time taken by applying {@code function} is not considered.
*
* @param future The future to compose
* @param function A Function to compose the results of the provided future
* to the results of the returned future. This will be run in the thread
* that calls one of the varieties of {@code get()}.
* @return A future that computes result of the composition.
*/
public static <I, O> Future<O> compose(final Future<I> future,
final Function<? super I, ? extends O> function) {
checkNotNull(future);
checkNotNull(function);
return new Future<O>() {
/*
* Concurrency detail:
*
* <p>To preserve the idempotency of calls to this.get(*) calls to the
* function are only applied once. A lock is required to prevent multiple
* applications of the function. The calls to future.get(*) are performed
* outside the lock, as is required to prevent calls to
* get(long, TimeUnit) to persist beyond their timeout.
*
* <p>Calls to future.get(*) on every call to this.get(*) also provide
* the cancellation behavior for this.
*
* <p>(Consider: in thread A, call get(), in thread B call get(long,
* TimeUnit). Thread B may have to wait for Thread A to finish, which
* would be unacceptable.)
*
* <p>Note that each call to Future<O>.get(*) results in a call to
* Future<I>.get(*), but the function is only applied once, so
* Future<I>.get(*) is assumed to be idempotent.
*/
private final Object lock = new Object();
private boolean set = false;
private O value = null;
public O get() throws InterruptedException, ExecutionException {
return apply(future.get());
}
public O get(long timeout, TimeUnit unit) throws InterruptedException,
ExecutionException, TimeoutException {
return apply(future.get(timeout, unit));
}
private O apply(I raw) {
synchronized(lock) {
if (!set) {
value = function.apply(raw);
set = true;
}
return value;
}
}
public boolean cancel(boolean mayInterruptIfRunning) {
return future.cancel(mayInterruptIfRunning);
}
public boolean isCancelled() {
return future.isCancelled();
}
public boolean isDone() {
return future.isDone();
}
};
}
/**
* An implementation of {@code ListenableFuture} that also implements
* {@code Runnable} so that it can be used to nest ListenableFutures.
* Once the passed-in {@code ListenableFuture} is complete, it calls the
* passed-in {@code Function} to generate the result.
* The resulting future doesn't interrupt when aborted.
*
* <p>If the function throws any checked exceptions, they should be wrapped
* in a {@code UndeclaredThrowableException} so that this class can get
* access to the cause.
*/
private static class ChainingListenableFuture<I, O>
extends AbstractListenableFuture<O> implements Runnable {
private Function<? super I, ? extends ListenableFuture<? extends O>>
function;
private UninterruptibleFuture<? extends I> inputFuture;
private ChainingListenableFuture(
Function<? super I, ? extends ListenableFuture<? extends O>> function,
ListenableFuture<? extends I> inputFuture) {
this.function = checkNotNull(function);
this.inputFuture = makeUninterruptible(inputFuture);
}
@Override
public boolean cancel(boolean mayInterruptIfRunning) {
Future<? extends I> future = inputFuture;
if (future != null) {
return future.cancel(mayInterruptIfRunning);
}
return false;
}
public void run() {
try {
I sourceResult;
try {
sourceResult = inputFuture.get();
} catch (CancellationException e) {
// Cancel this future and return.
cancel();
return;
} catch (ExecutionException e) {
// Set the cause of the exception as this future's exception
setException(e.getCause());
return;
}
final ListenableFuture<? extends O> outputFuture =
function.apply(sourceResult);
outputFuture.addListener(new Runnable() {
public void run() {
try {
// Here it would have been nice to have had an
// UninterruptibleListenableFuture, but we don't want to start a
// combinatorial explosion of interfaces, so we have to make do.
set(makeUninterruptible(outputFuture).get());
} catch (ExecutionException e) {
// Set the cause of the exception as this future's exception
setException(e.getCause());
}
}
}, MoreExecutors.sameThreadExecutor());
} catch (UndeclaredThrowableException e) {
// Set the cause of the exception as this future's exception
setException(e.getCause());
} catch (RuntimeException e) {
// This exception is irrelevant in this thread, but useful for the
// client
setException(e);
} catch (Error e) {
// This seems evil, but the client needs to know an error occured and
// the error needs to be propagated ASAP.
setException(e);
throw e;
} finally {
// Don't pin inputs beyond completion
function = null;
inputFuture = null;
}
}
}
/**
* A checked future that uses a function to map from exceptions to the
* appropriate checked type.
*/
private static class MappingCheckedFuture<T, E extends Exception> extends
AbstractCheckedFuture<T, E> {
final Function<Exception, E> mapper;
MappingCheckedFuture(ListenableFuture<T> delegate,
Function<Exception, E> mapper) {
super(delegate);
this.mapper = checkNotNull(mapper);
}
@Override
protected E mapException(Exception e) {
return mapper.apply(e);
}
}
/**
* An adapter to turn a {@link Future} into a {@link ListenableFuture}. This
* will wait on the future to finish, and when it completes, run the
* listeners. This implementation will wait on the source future
* indefinitely, so if the source future never completes, the adapter will
* never complete either.
*
* <p>If the delegate future is interrupted or throws an unexpected unchecked
* exception, the listeners will not be invoked.
*/
private static class ListenableFutureAdapter<T> extends ForwardingFuture<T>
implements ListenableFuture<T> {
private static final Executor adapterExecutor =
java.util.concurrent.Executors.newCachedThreadPool();
// The execution list to hold our listeners.
private final ExecutionList executionList = new ExecutionList();
// This allows us to only start up a thread waiting on the delegate future
// when the first listener is added.
private final AtomicBoolean hasListeners = new AtomicBoolean(false);
// The delegate future.
private final Future<T> delegate;
ListenableFutureAdapter(final Future<T> delegate) {
this.delegate = checkNotNull(delegate);
}
@Override
protected Future<T> delegate() {
return delegate;
}
public void addListener(Runnable listener, Executor exec) {
// When a listener is first added, we run a task that will wait for
// the delegate to finish, and when it is done will run the listeners.
if (!hasListeners.get() && hasListeners.compareAndSet(false, true)) {
adapterExecutor.execute(new Runnable() {
public void run() {
try {
delegate.get();
} catch (CancellationException e) {
// The task was cancelled, so it is done, run the listeners.
} catch (InterruptedException e) {
// This thread was interrupted. This should never happen, so we
// throw an IllegalStateException.
throw new IllegalStateException("Adapter thread interrupted!", e);
} catch (ExecutionException e) {
// The task caused an exception, so it is done, run the listeners.
}
executionList.run();
}
});
}
executionList.add(listener, exec);
}
}
}
| |
package com.cloud.api.command.admin.vlan;
import com.cloud.api.APICommand;
import com.cloud.api.APICommandGroup;
import com.cloud.api.ApiConstants;
import com.cloud.api.ApiErrorCode;
import com.cloud.api.BaseCmd;
import com.cloud.api.Parameter;
import com.cloud.api.ServerApiException;
import com.cloud.api.response.DomainResponse;
import com.cloud.api.response.NetworkResponse;
import com.cloud.api.response.PhysicalNetworkResponse;
import com.cloud.api.response.PodResponse;
import com.cloud.api.response.ProjectResponse;
import com.cloud.api.response.VlanIpRangeResponse;
import com.cloud.api.response.ZoneResponse;
import com.cloud.legacymodel.dc.Vlan;
import com.cloud.legacymodel.exceptions.ConcurrentOperationException;
import com.cloud.legacymodel.exceptions.InsufficientCapacityException;
import com.cloud.legacymodel.exceptions.ResourceAllocationException;
import com.cloud.legacymodel.exceptions.ResourceUnavailableException;
import com.cloud.legacymodel.user.Account;
import com.cloud.utils.net.NetUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@APICommand(name = "createVlanIpRange", group = APICommandGroup.VLANService, description = "Creates a VLAN IP range.", responseObject = VlanIpRangeResponse.class,
requestHasSensitiveInfo = false, responseHasSensitiveInfo = false)
public class CreateVlanIpRangeCmd extends BaseCmd {
public static final Logger s_logger = LoggerFactory.getLogger(CreateVlanIpRangeCmd.class.getName());
private static final String s_name = "createvlaniprangeresponse";
/////////////////////////////////////////////////////
//////////////// API parameters /////////////////////
/////////////////////////////////////////////////////
@Parameter(name = ApiConstants.ACCOUNT,
type = CommandType.STRING,
description = "account who will own the VLAN. If VLAN is Zone wide, this parameter should be ommited")
private String accountName;
@Parameter(name = ApiConstants.PROJECT_ID,
type = CommandType.UUID,
entityType = ProjectResponse.class,
description = "project who will own the VLAN. If VLAN is Zone wide, this parameter should be ommited")
private Long projectId;
@Parameter(name = ApiConstants.DOMAIN_ID, type = CommandType.UUID, entityType = DomainResponse.class, description = "domain ID of the account owning a VLAN")
private Long domainId;
@Parameter(name = ApiConstants.END_IP, type = CommandType.STRING, description = "the ending IP address in the VLAN IP range")
private String endIp;
@Parameter(name = ApiConstants.FOR_VIRTUAL_NETWORK, type = CommandType.BOOLEAN, description = "true if VLAN is of Virtual type, false if Direct")
private Boolean forVirtualNetwork;
@Parameter(name = ApiConstants.GATEWAY, type = CommandType.STRING, description = "the gateway of the VLAN IP range")
private String gateway;
@Parameter(name = ApiConstants.NETMASK, type = CommandType.STRING, description = "the netmask of the VLAN IP range")
private String netmask;
@Parameter(name = ApiConstants.POD_ID,
type = CommandType.UUID,
entityType = PodResponse.class,
description = "optional parameter. Have to be specified for Direct Untagged vlan only.")
private Long podId;
@Parameter(name = ApiConstants.START_IP, type = CommandType.STRING, description = "the beginning IP address in the VLAN IP range")
private String startIp;
@Parameter(name = ApiConstants.VLAN, type = CommandType.STRING, description = "the ID or VID of the VLAN. If not specified,"
+ " will be defaulted to the vlan of the network or if vlan of the network is null - to Untagged")
private String vlan;
@Parameter(name = ApiConstants.ZONE_ID, type = CommandType.UUID, entityType = ZoneResponse.class, description = "the Zone ID of the VLAN IP range")
private Long zoneId;
@Parameter(name = ApiConstants.NETWORK_ID, type = CommandType.UUID, entityType = NetworkResponse.class, description = "the network id")
private Long networkID;
@Parameter(name = ApiConstants.PHYSICAL_NETWORK_ID, type = CommandType.UUID, entityType = PhysicalNetworkResponse.class, description = "the physical network id")
private Long physicalNetworkId;
@Parameter(name = ApiConstants.START_IPV6, type = CommandType.STRING, description = "the beginning IPv6 address in the IPv6 network range")
private String startIpv6;
@Parameter(name = ApiConstants.END_IPV6, type = CommandType.STRING, description = "the ending IPv6 address in the IPv6 network range")
private String endIpv6;
@Parameter(name = ApiConstants.IP6_GATEWAY, type = CommandType.STRING, description = "the gateway of the IPv6 network. Required "
+ "for Shared networks and Isolated networks when it belongs to VPC")
private String ip6Gateway;
@Parameter(name = ApiConstants.IP6_CIDR, type = CommandType.STRING, description = "the CIDR of IPv6 network, must be at least /64")
private String ip6Cidr;
/////////////////////////////////////////////////////
/////////////////// Accessors ///////////////////////
/////////////////////////////////////////////////////
public String getAccountName() {
return accountName;
}
public Long getDomainId() {
return domainId;
}
public String getEndIp() {
return endIp;
}
public Boolean isForVirtualNetwork() {
return forVirtualNetwork == null ? Boolean.TRUE : forVirtualNetwork;
}
public String getGateway() {
return gateway;
}
public String getNetmask() {
return netmask;
}
public Long getPodId() {
return podId;
}
public String getStartIp() {
return startIp;
}
public String getVlan() {
if (vlan == null || vlan.isEmpty()) {
vlan = "untagged";
}
return vlan;
}
public Long getZoneId() {
return zoneId;
}
public Long getProjectId() {
return projectId;
}
public String getStartIpv6() {
if (startIpv6 == null) {
return null;
}
return NetUtils.standardizeIp6Address(startIpv6);
}
public String getEndIpv6() {
if (endIpv6 == null) {
return null;
}
return NetUtils.standardizeIp6Address(endIpv6);
}
public String getIp6Gateway() {
if (ip6Gateway == null) {
return null;
}
return NetUtils.standardizeIp6Address(ip6Gateway);
}
public String getIp6Cidr() {
if (ip6Cidr == null) {
return null;
}
return NetUtils.standardizeIp6Cidr(ip6Cidr);
}
/////////////////////////////////////////////////////
/////////////// API Implementation///////////////////
/////////////////////////////////////////////////////
public Long getNetworkID() {
return networkID;
}
public Long getPhysicalNetworkId() {
return physicalNetworkId;
}
@Override
public void execute() throws ResourceUnavailableException, ResourceAllocationException {
try {
final Vlan result = _configService.createVlanAndPublicIpRange(this);
if (result != null) {
final VlanIpRangeResponse response = _responseGenerator.createVlanIpRangeResponse(result);
response.setResponseName(getCommandName());
this.setResponseObject(response);
} else {
throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, "Failed to create vlan ip range");
}
} catch (final ConcurrentOperationException ex) {
s_logger.warn("Exception: ", ex);
throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, ex.getMessage());
} catch (final InsufficientCapacityException ex) {
s_logger.info(ex.toString());
throw new ServerApiException(ApiErrorCode.INSUFFICIENT_CAPACITY_ERROR, ex.getMessage());
}
}
@Override
public String getCommandName() {
return s_name;
}
@Override
public long getEntityOwnerId() {
return Account.ACCOUNT_ID_SYSTEM;
}
}
| |
package evaluation.evalBench.panel;
import java.awt.BorderLayout;
import java.awt.GridLayout;
import javax.swing.JComponent;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JSlider;
import javax.swing.JSpinner;
import javax.swing.JTextField;
import javax.swing.SpinnerNumberModel;
import javax.swing.SwingConstants;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
import evaluation.evalBench.EvaluationResources;
import evaluation.evalBench.task.QuantitativeQuestion;
import evaluation.evalBench.task.QuantitativeQuestion.UI;
/**
* Subclass of {@link QuantitativeQuestionPanelStrategy} Task Panel Strategy for
* a {@link QuantitativeQuestion} with a JTextField for the answer
*
* @author Stephan Hoffmann
*/
public class QuantitativeQuestionPanelStrategy extends QuestionPanelStrategy {
//private JTextField textField;
private JComponent inputComponent;
private JLabel currentLabel;
private double sliderFactor = 1;
/**
* constructor taking a {@link QuantitativeQuestion}
*
* @param aQuestion
* {@link QuantitativeQuestion}
*/
public QuantitativeQuestionPanelStrategy(QuantitativeQuestion aQuestion) {
super(aQuestion);
}
/**
* checks for correct input for this task and sets the answer value
*
* @return false if empty false if {@link QuantitativeQuestion} is integer
* and input was not an integer false if
* {@link QuantitativeQuestion} is not integer and the answer does
* not contain a double/float value
*/
@Override
public boolean checkForCorrectInput() {
QuantitativeQuestion quantTask = (QuantitativeQuestion) this.getQuestion();
if (quantTask.isInteger()) {
try {
if (quantTask.getUiComponent() == UI.SPINNER) {
quantTask.setGivenAnswer(Double
.parseDouble(((JSpinner) inputComponent).getValue()
.toString()));
} else if (quantTask.getUiComponent() == UI.SLIDER) {
quantTask.setGivenAnswer((double) ((JSlider) inputComponent)
.getValue()/sliderFactor);
} else {
int answer = Integer.parseInt(((JTextField) inputComponent).getText());
if (answer < quantTask.getMinimum() || answer > quantTask.getMaximum()) {
this.setErrorMessage(
String.format(EvaluationResources.getString("quantitativequestion.errorRangeInt"),
Math.round(quantTask.getMinimum()), Math.round(quantTask.getMaximum())));
return false;
}
quantTask.setGivenAnswer((double) answer);
}
this.setErrorMessage("");
return true;
} catch (NumberFormatException e) {
this.setErrorMessage(EvaluationResources.getString("quantitativequestion.errorInt"));
return false;
}
} else {
try {
if (quantTask.getUiComponent() == UI.SPINNER) {
quantTask.setGivenAnswer(Double
.parseDouble(((JSpinner) inputComponent).getValue()
.toString()));
} else if (quantTask.getUiComponent() == UI.SLIDER) {
quantTask.setGivenAnswer(Double.parseDouble(String
.valueOf(((JSlider) inputComponent).getValue()/sliderFactor)));
} else {
double answer = Double.parseDouble(((JTextField) inputComponent).getText());
if (answer < quantTask.getMinimum() || answer > quantTask.getMaximum()) {
this.setErrorMessage(
String.format(EvaluationResources.getString("quantitativequestion.errorRangeDouble"),
quantTask.getMinimum(), quantTask.getMaximum()));
return false;
}
quantTask.setGivenAnswer(answer);
}
this.setErrorMessage("");
return true;
} catch (NumberFormatException e) {
this.setErrorMessage(EvaluationResources.getString("quantitativequestion.errorDouble"));
}
}
return false;
// if (!(textField.getText().length() > 0)) {
//
// this.errorMessage = (EvaluationResources
// .getString("quanttaskpanel.errorNumber"));
// return false;
// } else {
// QuantitativeQuestion quantTask = (QuantitativeQuestion)
// this.getTask();
//
// if (quantTask.isInteger()) {
// try {
// Integer.parseInt(textField.getText());
//
// } catch (NumberFormatException ex) {
// this.errorMessage = (EvaluationResources
// .getString("quanttaskpanel.errorInt"));
// return false;
// }
// } else {
// try {
// Double.parseDouble(textField.getText());
// //
// quantTask.setAnsweredValue(Double.parseDouble(textField.getText()));
// } catch (NumberFormatException ex) {
// this.errorMessage = (EvaluationResources
// .getString("quanttaskpanel.errorNumber"));
// return false;
// }
// }
//
// }
//
// return true;
}
private void updateSliderLabel() {
if (sliderFactor == 1.0) {
currentLabel.setText(Integer.toString(((JSlider) inputComponent).getValue()));
} else {
currentLabel.setText(Double.toString(((JSlider) inputComponent).getValue() / sliderFactor));
}
}
/**
* provides an answering field (JPanel) with a JTextField
*
* @return an answering field
*/
@Override
public JComponent getNewAnsweringPanel() {
QuantitativeQuestion quantitativeTask = (QuantitativeQuestion) super
.getQuestion();
// System.err.println("spinner " + quantitativeTask.getUseSpinner() + " ui " + quantitativeTask.getUiComponent());
if (quantitativeTask.getUiComponent() == UI.SLIDER) {
if (quantitativeTask.isInteger()) {
sliderFactor = 1;
} else {
sliderFactor = 10;
}
int min = (int) (quantitativeTask.getMinimum() * sliderFactor);
int max = (int) (quantitativeTask.getMaximum() * sliderFactor);
int value = (min + max) / 2;
inputComponent = new JSlider(min, max, value);
// ((JSlider) inputComponent).setMajorTickSpacing(20);;
// ((JSlider) inputComponent).setPaintLabels(true);
// ((JSlider) inputComponent).setPaintLabels(true);
String minStr = quantitativeTask.getMinimumString();
if (minStr == null) {
if (quantitativeTask.isInteger()) {
minStr = Integer.toString((int) quantitativeTask.getMinimum());
} else {
minStr = Double.toString(quantitativeTask.getMinimum());
}
}
JLabel minLabel = new JLabel(minStr);
String maxStr = quantitativeTask.getMaximumString();
if (maxStr == null) {
if (quantitativeTask.isInteger()) {
maxStr = Integer.toString((int) quantitativeTask.getMaximum());
} else {
maxStr = Double.toString(quantitativeTask.getMaximum());
}
}
JLabel maxLabel = new JLabel(maxStr, SwingConstants.RIGHT);
this.currentLabel = new JLabel("", SwingConstants.CENTER);
updateSliderLabel();
((JSlider) inputComponent).addChangeListener(new ChangeListener() {
@Override
public void stateChanged(ChangeEvent e) {
updateSliderLabel();
}
});
// JPanel innerPanel = new JPanel();
// innerPanel.setLayout(new BorderLayout());
// innerPanel.add(inputComponent, BorderLayout.CENTER);
JPanel labels = new JPanel(new GridLayout(1, 3));
labels.add(minLabel);
labels.add(currentLabel);
labels.add(maxLabel);
JPanel answeringPanel = new JPanel(new BorderLayout(5, 15));
answeringPanel.add(labels, BorderLayout.SOUTH);
answeringPanel.add(inputComponent, BorderLayout.CENTER);
return answeringPanel;
} else if (quantitativeTask.getUiComponent() == UI.SPINNER) {
inputComponent = new JSpinner();
((JSpinner) inputComponent).setModel(new SpinnerNumberModel(
(quantitativeTask.getMaximum() + quantitativeTask
.getMinimum()) / 2, quantitativeTask.getMinimum(),
quantitativeTask.getMaximum(), quantitativeTask
.getStepsize()));
// ((JSpinner) inputComponent).setEditor(new JFormattedTextField(java.text.NumberFormat.getNumberInstance()));
JPanel answeringPanel = new JPanel(new BorderLayout(0, 0));
answeringPanel.add(inputComponent, BorderLayout.WEST);
return answeringPanel;
} else {
JTextField text = new JTextField(6);
text.setHorizontalAlignment(JTextField.TRAILING);
inputComponent = text;
JPanel answeringPanel = new JPanel(new BorderLayout(0, 0));
answeringPanel.add(inputComponent, BorderLayout.WEST);
return answeringPanel;
}
// textField = new JTextField(5);
//
// textField.setMinimumSize(new Dimension(50, 20));
// textField.setPreferredSize(new Dimension(50, 20));
// textField.setMaximumSize(new Dimension(100,
// Short.MAX_VALUE));
//
// JPanel answeringPanel = new JPanel();
//
// answeringPanel.setLayout(new BoxLayout(answeringPanel,
// BoxLayout.X_AXIS));
//
// {
// JLabel jLabel1 = new JLabel();
//
// QuantitativeQuestion quantTask =
// (QuantitativeQuestion)this.getTask();
// jLabel1.setText(quantTask.getUnit());
//
// answeringPanel.add(Box.createRigidArea(new Dimension(5, 5)));
// answeringPanel.add(textField);
// answeringPanel.add(Box.createRigidArea(new Dimension(15, 5)));
// answeringPanel.add(jLabel1);
// answeringPanel.add(Box.createHorizontalGlue());
//
//
//
// jLabel1.setBackground(Color.WHITE);
// }
}
@Override
public void inputFinished() {
// if (quantTask.isInteger()){
// try{
// quantTask.setAnsweredValue(Integer.parseInt(textField.getText()));
// }catch (NumberFormatException ignored){
//
// }
// }else {
// try{
//
// quantTask.setAnsweredValue(Double.parseDouble(textField.getText()));
// }catch (NumberFormatException ignored){
//
// }
// }
}
}
| |
/*
* Copyright (C) 2014 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.example.android.sunshine.app.data;
import android.content.ComponentName;
import android.content.ContentUris;
import android.content.ContentValues;
import android.content.pm.PackageManager;
import android.content.pm.ProviderInfo;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.net.Uri;
import android.os.Build;
import android.test.AndroidTestCase;
import android.util.Log;
import com.example.android.sunshine.app.data.WeatherContract.LocationEntry;
import com.example.android.sunshine.app.data.WeatherContract.WeatherEntry;
/*
Note: This is not a complete set of tests of the Sunshine ContentProvider, but it does test
that at least the basic functionality has been implemented correctly.
Students: Uncomment the tests in this class as you implement the functionality in your
ContentProvider to make sure that you've implemented things reasonably correctly.
*/
public class TestProvider extends AndroidTestCase {
public static final String LOG_TAG = TestProvider.class.getSimpleName();
/*
This helper function deletes all records from both database tables using the ContentProvider.
It also queries the ContentProvider to make sure that the database has been successfully
deleted, so it cannot be used until the Query and Delete functions have been written
in the ContentProvider.
Students: Replace the calls to deleteAllRecordsFromDB with this one after you have written
the delete functionality in the ContentProvider.
*/
public void deleteAllRecordsFromProvider() {
mContext.getContentResolver().delete(
WeatherEntry.CONTENT_URI,
null,
null
);
mContext.getContentResolver().delete(
LocationEntry.CONTENT_URI,
null,
null
);
Cursor cursor = mContext.getContentResolver().query(
WeatherEntry.CONTENT_URI,
null,
null,
null,
null
);
assertEquals("Error: Records not deleted from Weather table during delete", 0, cursor.getCount());
cursor.close();
cursor = mContext.getContentResolver().query(
LocationEntry.CONTENT_URI,
null,
null,
null,
null
);
assertEquals("Error: Records not deleted from Location table during delete", 0, cursor.getCount());
cursor.close();
}
/*
This helper function deletes all records from both database tables using the database
functions only. This is designed to be used to reset the state of the database until the
delete functionality is available in the ContentProvider.
*/
public void deleteAllRecordsFromDB() {
WeatherDbHelper dbHelper = new WeatherDbHelper(mContext);
SQLiteDatabase db = dbHelper.getWritableDatabase();
db.delete(WeatherEntry.TABLE_NAME, null, null);
db.delete(LocationEntry.TABLE_NAME, null, null);
db.close();
}
/*
Student: Refactor this function to use the deleteAllRecordsFromProvider functionality once
you have implemented delete functionality there.
*/
public void deleteAllRecords() {
deleteAllRecordsFromDB();
}
// Since we want each test to start with a clean slate, run deleteAllRecords
// in setUp (called by the test runner before each test).
@Override
protected void setUp() throws Exception {
super.setUp();
deleteAllRecords();
}
/*
This test checks to make sure that the content provider is registered correctly.
Students: Uncomment this test to make sure you've correctly registered the WeatherProvider.
*/
public void testProviderRegistry() {
PackageManager pm = mContext.getPackageManager();
// We define the component name based on the package name from the context and the
// WeatherProvider class.
ComponentName componentName = new ComponentName(mContext.getPackageName(),
WeatherProvider.class.getName());
try {
// Fetch the provider info using the component name from the PackageManager
// This throws an exception if the provider isn't registered.
ProviderInfo providerInfo = pm.getProviderInfo(componentName, 0);
// Make sure that the registered authority matches the authority from the Contract.
assertEquals("Error: WeatherProvider registered with authority: " + providerInfo.authority +
" instead of authority: " + WeatherContract.CONTENT_AUTHORITY,
providerInfo.authority, WeatherContract.CONTENT_AUTHORITY);
} catch (PackageManager.NameNotFoundException e) {
// I guess the provider isn't registered correctly.
assertTrue("Error: WeatherProvider not registered at " + mContext.getPackageName(),
false);
}
}
/*
This test doesn't touch the database. It verifies that the ContentProvider returns
the correct type for each type of URI that it can handle.
Students: Uncomment this test to verify that your implementation of GetType is
functioning correctly.
*/
public void testGetType() {
// content://com.example.android.sunshine.app/weather/
String type = mContext.getContentResolver().getType(WeatherEntry.CONTENT_URI);
// vnd.android.cursor.dir/com.example.android.sunshine.app/weather
assertEquals("Error: the WeatherEntry CONTENT_URI should return WeatherEntry.CONTENT_TYPE",
WeatherEntry.CONTENT_TYPE, type);
String testLocation = "94074";
// content://com.example.android.sunshine.app/weather/94074
type = mContext.getContentResolver().getType(
WeatherEntry.buildWeatherLocation(testLocation));
// vnd.android.cursor.dir/com.example.android.sunshine.app/weather
assertEquals("Error: the WeatherEntry CONTENT_URI with location should return WeatherEntry.CONTENT_TYPE",
WeatherEntry.CONTENT_TYPE, type);
long testDate = 1419120000L; // December 21st, 2014
// content://com.example.android.sunshine.app/weather/94074/20140612
type = mContext.getContentResolver().getType(
WeatherEntry.buildWeatherLocationWithDate(testLocation, testDate));
// vnd.android.cursor.item/com.example.android.sunshine.app/weather/1419120000
assertEquals("Error: the WeatherEntry CONTENT_URI with location and date should return WeatherEntry.CONTENT_ITEM_TYPE",
WeatherEntry.CONTENT_ITEM_TYPE, type);
// content://com.example.android.sunshine.app/location/
type = mContext.getContentResolver().getType(LocationEntry.CONTENT_URI);
// vnd.android.cursor.dir/com.example.android.sunshine.app/location
assertEquals("Error: the LocationEntry CONTENT_URI should return LocationEntry.CONTENT_TYPE",
LocationEntry.CONTENT_TYPE, type);
}
/*
This test uses the database directly to insert and then uses the ContentProvider to
read out the data. Uncomment this test to see if the basic weather query functionality
given in the ContentProvider is working correctly.
*/
public void testBasicWeatherQuery() {
// insert our test records into the database
WeatherDbHelper dbHelper = new WeatherDbHelper(mContext);
SQLiteDatabase db = dbHelper.getWritableDatabase();
ContentValues testValues = TestUtilities.createNorthPoleLocationValues();
long locationRowId = TestUtilities.insertNorthPoleLocationValues(mContext);
// Fantastic. Now that we have a location, add some weather!
ContentValues weatherValues = TestUtilities.createWeatherValues(locationRowId);
long weatherRowId = db.insert(WeatherEntry.TABLE_NAME, null, weatherValues);
assertTrue("Unable to Insert WeatherEntry into the Database", weatherRowId != -1);
db.close();
// Test the basic content provider query
Cursor weatherCursor = mContext.getContentResolver().query(
WeatherEntry.CONTENT_URI,
null,
null,
null,
null
);
// Make sure we get the correct cursor out of the database
TestUtilities.validateCursor("testBasicWeatherQuery", weatherCursor, weatherValues);
}
/*
This test uses the database directly to insert and then uses the ContentProvider to
read out the data. Uncomment this test to see if your location queries are
performing correctly.
*/
public void testBasicLocationQueries() {
// insert our test records into the database
WeatherDbHelper dbHelper = new WeatherDbHelper(mContext);
SQLiteDatabase db = dbHelper.getWritableDatabase();
//
ContentValues testValues = TestUtilities.createNorthPoleLocationValues();
long locationRowId = TestUtilities.insertNorthPoleLocationValues(mContext);
// Test the basic content provider query
Cursor locationCursor = mContext.getContentResolver().query(
LocationEntry.CONTENT_URI,
null,
null,
null,
null
);
// Make sure we get the correct cursor out of the database
TestUtilities.validateCursor("testBasicLocationQueries, location query", locationCursor, testValues);
// Has the NotificationUri been set correctly? --- we can only test this easily against API
// level 19 or greater because getNotificationUri was added in API level 19.
if ( Build.VERSION.SDK_INT >= 19 ) {
assertEquals("Error: Location Query did not properly set NotificationUri",
locationCursor.getNotificationUri(), LocationEntry.CONTENT_URI);
}
}
/*
This test uses the provider to insert and then update the data. Uncomment this test to
see if your update location is functioning correctly.
*/
public void testUpdateLocation() {
// Create a new map of values, where column names are the keys
ContentValues values = TestUtilities.createNorthPoleLocationValues();
Uri locationUri = mContext.getContentResolver().
insert(LocationEntry.CONTENT_URI, values);
long locationRowId = ContentUris.parseId(locationUri);
// Verify we got a row back.
assertTrue(locationRowId != -1);
Log.d(LOG_TAG, "New row id: " + locationRowId);
ContentValues updatedValues = new ContentValues(values);
updatedValues.put(LocationEntry._ID, locationRowId);
updatedValues.put(LocationEntry.COLUMN_CITY_NAME, "Santa's Village");
// Create a cursor with observer to make sure that the content provider is notifying
// the observers as expected
Cursor locationCursor = mContext.getContentResolver().query(LocationEntry.CONTENT_URI, null, null, null, null);
TestUtilities.TestContentObserver tco = TestUtilities.getTestContentObserver();
locationCursor.registerContentObserver(tco);
int count = mContext.getContentResolver().update(
LocationEntry.CONTENT_URI, updatedValues, LocationEntry._ID + "= ?",
new String[] { Long.toString(locationRowId)});
assertEquals(count, 1);
// Test to make sure our observer is called. If not, we throw an assertion.
//
// Students: If your code is failing here, it means that your content provider
// isn't calling getContext().getContentResolver().notifyChange(uri, null);
tco.waitForNotificationOrFail();
locationCursor.unregisterContentObserver(tco);
locationCursor.close();
// A cursor is your primary interface to the query results.
Cursor cursor = mContext.getContentResolver().query(
LocationEntry.CONTENT_URI,
null, // projection
LocationEntry._ID + " = " + locationRowId,
null, // Values for the "where" clause
null // sort order
);
TestUtilities.validateCursor("testUpdateLocation. Error validating location entry update.",
cursor, updatedValues);
cursor.close();
}
// Make sure we can still delete after adding/updating stuff
//
// Student: Uncomment this test after you have completed writing the insert functionality
// in your provider. It relies on insertions with testInsertReadProvider, so insert and
// query functionality must also be complete before this test can be used.
public void testInsertReadProvider() {
ContentValues testValues = TestUtilities.createNorthPoleLocationValues();
// Register a content observer for our insert. This time, directly with the content resolver
TestUtilities.TestContentObserver tco = TestUtilities.getTestContentObserver();
mContext.getContentResolver().registerContentObserver(LocationEntry.CONTENT_URI, true, tco);
Uri locationUri = mContext.getContentResolver().insert(LocationEntry.CONTENT_URI, testValues);
// Did our content observer get called? Students: If this fails, your insert location
// isn't calling getContext().getContentResolver().notifyChange(uri, null);
tco.waitForNotificationOrFail();
mContext.getContentResolver().unregisterContentObserver(tco);
long locationRowId = ContentUris.parseId(locationUri);
// Verify we got a row back.
assertTrue(locationRowId != -1);
// Data's inserted. IN THEORY. Now pull some out to stare at it and verify it made
// the round trip.
// A cursor is your primary interface to the query results.
Cursor cursor = mContext.getContentResolver().query(
LocationEntry.CONTENT_URI,
null, // leaving "columns" null just returns all the columns.
null, // cols for "where" clause
null, // values for "where" clause
null // sort order
);
TestUtilities.validateCursor("testInsertReadProvider. Error validating LocationEntry.",
cursor, testValues);
// Fantastic. Now that we have a location, add some weather!
ContentValues weatherValues = TestUtilities.createWeatherValues(locationRowId);
// The TestContentObserver is a one-shot class
tco = TestUtilities.getTestContentObserver();
mContext.getContentResolver().registerContentObserver(WeatherEntry.CONTENT_URI, true, tco);
Uri weatherInsertUri = mContext.getContentResolver()
.insert(WeatherEntry.CONTENT_URI, weatherValues);
assertTrue(weatherInsertUri != null);
// Did our content observer get called? Students: If this fails, your insert weather
// in your ContentProvider isn't calling
// getContext().getContentResolver().notifyChange(uri, null);
tco.waitForNotificationOrFail();
mContext.getContentResolver().unregisterContentObserver(tco);
// A cursor is your primary interface to the query results.
Cursor weatherCursor = mContext.getContentResolver().query(
WeatherEntry.CONTENT_URI, // Table to Query
null, // leaving "columns" null just returns all the columns.
null, // cols for "where" clause
null, // values for "where" clause
null // columns to group by
);
TestUtilities.validateCursor("testInsertReadProvider. Error validating WeatherEntry insert.",
weatherCursor, weatherValues);
// Add the location values in with the weather data so that we can make
// sure that the join worked and we actually get all the values back
weatherValues.putAll(testValues);
// Get the joined Weather and Location data
weatherCursor = mContext.getContentResolver().query(
WeatherEntry.buildWeatherLocation(TestUtilities.TEST_LOCATION),
null, // leaving "columns" null just returns all the columns.
null, // cols for "where" clause
null, // values for "where" clause
null // sort order
);
TestUtilities.validateCursor("testInsertReadProvider. Error validating joined Weather and Location Data.",
weatherCursor, weatherValues);
// Get the joined Weather and Location data with a start date
weatherCursor = mContext.getContentResolver().query(
WeatherEntry.buildWeatherLocationWithStartDate(
TestUtilities.TEST_LOCATION, TestUtilities.TEST_DATE),
null, // leaving "columns" null just returns all the columns.
null, // cols for "where" clause
null, // values for "where" clause
null // sort order
);
TestUtilities.validateCursor("testInsertReadProvider. Error validating joined Weather and Location Data with start date.",
weatherCursor, weatherValues);
// Get the joined Weather data for a specific date
weatherCursor = mContext.getContentResolver().query(
WeatherEntry.buildWeatherLocationWithDate(TestUtilities.TEST_LOCATION, TestUtilities.TEST_DATE),
null,
null,
null,
null
);
TestUtilities.validateCursor("testInsertReadProvider. Error validating joined Weather and Location data for a specific date.",
weatherCursor, weatherValues);
}
// Make sure we can still delete after adding/updating stuff
//
// Student: Uncomment this test after you have completed writing the delete functionality
// in your provider. It relies on insertions with testInsertReadProvider, so insert and
// query functionality must also be complete before this test can be used.
public void testDeleteRecords() {
testInsertReadProvider();
// Register a content observer for our location delete.
TestUtilities.TestContentObserver locationObserver = TestUtilities.getTestContentObserver();
mContext.getContentResolver().registerContentObserver(LocationEntry.CONTENT_URI, true, locationObserver);
// Register a content observer for our weather delete.
TestUtilities.TestContentObserver weatherObserver = TestUtilities.getTestContentObserver();
mContext.getContentResolver().registerContentObserver(WeatherEntry.CONTENT_URI, true, weatherObserver);
deleteAllRecordsFromProvider();
// Students: If either of these fail, you most-likely are not calling the
// getContext().getContentResolver().notifyChange(uri, null); in the ContentProvider
// delete. (only if the insertReadProvider is succeeding)
locationObserver.waitForNotificationOrFail();
weatherObserver.waitForNotificationOrFail();
mContext.getContentResolver().unregisterContentObserver(locationObserver);
mContext.getContentResolver().unregisterContentObserver(weatherObserver);
}
static private final int BULK_INSERT_RECORDS_TO_INSERT = 10;
static ContentValues[] createBulkInsertWeatherValues(long locationRowId) {
long currentTestDate = TestUtilities.TEST_DATE;
long millisecondsInADay = 1000*60*60*24;
ContentValues[] returnContentValues = new ContentValues[BULK_INSERT_RECORDS_TO_INSERT];
for ( int i = 0; i < BULK_INSERT_RECORDS_TO_INSERT; i++, currentTestDate+= millisecondsInADay ) {
ContentValues weatherValues = new ContentValues();
weatherValues.put(WeatherContract.WeatherEntry.COLUMN_LOC_KEY, locationRowId);
weatherValues.put(WeatherContract.WeatherEntry.COLUMN_DATE, currentTestDate);
weatherValues.put(WeatherContract.WeatherEntry.COLUMN_DEGREES, 1.1);
weatherValues.put(WeatherContract.WeatherEntry.COLUMN_HUMIDITY, 1.2 + 0.01 * (float) i);
weatherValues.put(WeatherContract.WeatherEntry.COLUMN_PRESSURE, 1.3 - 0.01 * (float) i);
weatherValues.put(WeatherContract.WeatherEntry.COLUMN_MAX_TEMP, 75 + i);
weatherValues.put(WeatherContract.WeatherEntry.COLUMN_MIN_TEMP, 65 - i);
weatherValues.put(WeatherContract.WeatherEntry.COLUMN_SHORT_DESC, "Asteroids");
weatherValues.put(WeatherContract.WeatherEntry.COLUMN_WIND_SPEED, 5.5 + 0.2 * (float) i);
weatherValues.put(WeatherContract.WeatherEntry.COLUMN_WEATHER_ID, 321);
returnContentValues[i] = weatherValues;
}
return returnContentValues;
}
// Student: Uncomment this test after you have completed writing the BulkInsert functionality
// in your provider. Note that this test will work with the built-in (default) provider
// implementation, which just inserts records one-at-a-time, so really do implement the
// BulkInsert ContentProvider function.
public void testBulkInsert() {
// first, let's create a location value
ContentValues testValues = TestUtilities.createNorthPoleLocationValues();
Uri locationUri = mContext.getContentResolver().insert(LocationEntry.CONTENT_URI, testValues);
long locationRowId = ContentUris.parseId(locationUri);
// Verify we got a row back.
assertTrue(locationRowId != -1);
// Data's inserted. IN THEORY. Now pull some out to stare at it and verify it made
// the round trip.
// A cursor is your primary interface to the query results.
Cursor cursor = mContext.getContentResolver().query(
LocationEntry.CONTENT_URI,
null, // leaving "columns" null just returns all the columns.
null, // cols for "where" clause
null, // values for "where" clause
null // sort order
);
TestUtilities.validateCursor("testBulkInsert. Error validating LocationEntry.",
cursor, testValues);
// Now we can bulkInsert some weather. In fact, we only implement BulkInsert for weather
// entries. With ContentProviders, you really only have to implement the features you
// use, after all.
ContentValues[] bulkInsertContentValues = createBulkInsertWeatherValues(locationRowId);
// Register a content observer for our bulk insert.
TestUtilities.TestContentObserver weatherObserver = TestUtilities.getTestContentObserver();
mContext.getContentResolver().registerContentObserver(WeatherEntry.CONTENT_URI, true, weatherObserver);
int insertCount = mContext.getContentResolver().bulkInsert(WeatherEntry.CONTENT_URI, bulkInsertContentValues);
// Students: If this fails, it means that you most-likely are not calling the
// getContext().getContentResolver().notifyChange(uri, null); in your BulkInsert
// ContentProvider method.
weatherObserver.waitForNotificationOrFail();
mContext.getContentResolver().unregisterContentObserver(weatherObserver);
assertEquals(insertCount, BULK_INSERT_RECORDS_TO_INSERT);
// A cursor is your primary interface to the query results.
cursor = mContext.getContentResolver().query(
WeatherEntry.CONTENT_URI,
null, // leaving "columns" null just returns all the columns.
null, // cols for "where" clause
null, // values for "where" clause
WeatherEntry.COLUMN_DATE + " ASC" // sort order == by DATE ASCENDING
);
// we should have as many records in the database as we've inserted
assertEquals(cursor.getCount(), BULK_INSERT_RECORDS_TO_INSERT);
// and let's make sure they match the ones we created
cursor.moveToFirst();
for ( int i = 0; i < BULK_INSERT_RECORDS_TO_INSERT; i++, cursor.moveToNext() ) {
TestUtilities.validateCurrentRecord("testBulkInsert. Error validating WeatherEntry " + i,
cursor, bulkInsertContentValues[i]);
}
cursor.close();
}
}
| |
package org.ringingmaster.engine.composition;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.Iterators;
import org.junit.Assert;
import org.junit.Test;
import org.ringingmaster.engine.NumberOfBells;
import org.ringingmaster.engine.notation.Notation;
import org.ringingmaster.engine.notation.NotationBuilder;
import java.util.Optional;
import java.util.Set;
import static org.junit.Assert.*;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
/**
* TODO Comments
*
* @author Steve Lake
*/
public class PlaceSetSequenceMutationTest {
public static final Notation METHOD_A_6_BELL = buildNotation(NumberOfBells.BELLS_6, "METHOD A", "12");
public static final Notation METHOD_B_6_BELL = buildNotation(NumberOfBells.BELLS_6, "METHOD B", "14");
public static final Notation METHOD_C_6_BELL = buildNotation(NumberOfBells.BELLS_6, "METHOD C", "16");
public static final Notation METHOD_D_6_BELL = buildNotation(NumberOfBells.BELLS_6, "METHOD D", "34");
public static final Notation METHOD_A_7_BELL = buildNotation(NumberOfBells.BELLS_7, "METHOD A", "1");
public static final Notation METHOD_A_8_BELL = buildNotation(NumberOfBells.BELLS_8, "METHOD A", "12");
public static final Notation METHOD_B_8_BELL = buildNotation(NumberOfBells.BELLS_8, "METHOD B", "14");
public static final Notation METHOD_C_8_BELL = buildNotation(NumberOfBells.BELLS_8, "METHOD C", "16");
public static final Notation METHOD_D_8_BELL = buildNotation(NumberOfBells.BELLS_8, "METHOD D", "18");
private static Notation buildNotation(NumberOfBells bells, String name, String notation1) {
return NotationBuilder.getInstance()
.setNumberOfWorkingBells(bells)
.setName(name)
.setUnfoldedNotationShorthand(notation1)
.build();
}
@Test
public void hasCorrectDefault() throws Exception {
MutableComposition mutableComposition = new MutableComposition();
assertEquals(ImmutableSet.of(), mutableComposition.get().getAllNotations());
}
@Test
public void canAddAndRemoveNotations() {
MutableComposition composition = new MutableComposition();
composition.addNotation(METHOD_A_6_BELL);
Set<Notation> retrievedNotations = composition.get().getAllNotations();
assertEquals(1, retrievedNotations.size());
assertEquals(METHOD_A_6_BELL, Iterators.getOnlyElement(retrievedNotations.iterator()));
composition.addNotation(METHOD_B_6_BELL);
retrievedNotations = composition.get().getAllNotations();
assertEquals(2, retrievedNotations.size());
composition.removeNotation(METHOD_A_6_BELL);
retrievedNotations = composition.get().getAllNotations();
assertEquals(METHOD_B_6_BELL, Iterators.getOnlyElement(retrievedNotations.iterator()));
}
@Test(expected = IllegalArgumentException.class)
public void addingDuplicateNotationNameThrows() {
MutableComposition composition = null;
Notation mockNotation2 = null;
try {
Notation mockNotation1 = mock(Notation.class);
when(mockNotation1.getName()).thenReturn("Duplicate Name");
when(mockNotation1.getNumberOfWorkingBells()).thenReturn(NumberOfBells.BELLS_6);
mockNotation2 = mock(Notation.class);
when(mockNotation2.getName()).thenReturn("Duplicate Name");
when(mockNotation2.getNumberOfWorkingBells()).thenReturn(NumberOfBells.BELLS_6);
composition = new MutableComposition();
composition.addNotation(mockNotation1);
}
catch (Exception e) {
fail();
}
composition.addNotation(mockNotation2);
}
@Test
public void notationCanBeExchanged() {
MutableComposition composition = new MutableComposition();
composition.setNumberOfBells(NumberOfBells.BELLS_6);
composition.addNotation(METHOD_A_6_BELL);
assertEquals(METHOD_A_6_BELL, Iterators.getOnlyElement(composition.get().getAllNotations().iterator()));
composition.exchangeNotation(METHOD_A_6_BELL, METHOD_B_6_BELL);
assertEquals(METHOD_B_6_BELL, Iterators.getOnlyElement(composition.get().getAllNotations().iterator()));
}
@Test
public void addingFirstNotationToNonSplicedSetsDefaultNotation() {
MutableComposition composition = new MutableComposition();
composition.setSpliced(false);
composition.addNotation(METHOD_A_8_BELL);
assertEquals(Optional.of(METHOD_A_8_BELL), composition.get().getNonSplicedActiveNotation());
assertFalse(composition.get().isSpliced());
}
@Test
public void addingFirstNotationToSplicedSetsDefaultNotation() {
MutableComposition composition = new MutableComposition();
composition.setSpliced(true);
composition.addNotation(METHOD_A_8_BELL);
assertEquals(Optional.of(METHOD_A_8_BELL), composition.get().getNonSplicedActiveNotation());
assertFalse(composition.get().isSpliced());
}
@Test
public void removingOnlyNotationRemovesActiveNotation() throws CloneNotSupportedException {
MutableComposition composition = new MutableComposition();
composition.setNumberOfBells(NumberOfBells.BELLS_8);
composition.addNotation(METHOD_A_8_BELL);
composition.removeNotation(METHOD_A_8_BELL);
assertEquals(Optional.empty() ,composition.get().getNonSplicedActiveNotation());
}
@Test
public void removingActiveNotationChoosesNextNotationAlphabetically() {
MutableComposition composition = new MutableComposition();
composition.setSpliced(false);
composition.addNotation(METHOD_A_6_BELL);
composition.addNotation(METHOD_B_6_BELL);
composition.addNotation(METHOD_C_6_BELL);
composition.addNotation(METHOD_D_6_BELL);
composition.setNonSplicedActiveNotation(METHOD_C_6_BELL);
Assert.assertEquals(Optional.of(METHOD_C_6_BELL), composition.get().getNonSplicedActiveNotation());
composition.removeNotation(METHOD_C_6_BELL);
Assert.assertEquals(Optional.of(METHOD_D_6_BELL), composition.get().getNonSplicedActiveNotation());
composition.removeNotation(METHOD_D_6_BELL);
Assert.assertEquals(Optional.of(METHOD_B_6_BELL), composition.get().getNonSplicedActiveNotation());
composition.removeNotation(METHOD_A_6_BELL);
Assert.assertEquals(Optional.of(METHOD_B_6_BELL), composition.get().getNonSplicedActiveNotation());
composition.removeNotation(METHOD_B_6_BELL);
assertFalse(composition.get().getNonSplicedActiveNotation().isPresent());
}
@Test
public void removingActiveNotationOnlyChoosesValidNotations() {
MutableComposition composition = new MutableComposition();
composition.setNumberOfBells(NumberOfBells.BELLS_6);
composition.setSpliced(false);
composition.addNotation(METHOD_A_6_BELL);
composition.addNotation(METHOD_B_8_BELL);//Invalid number of bells
composition.addNotation(METHOD_C_6_BELL);
composition.addNotation(METHOD_D_8_BELL);//Invalid number of bells
composition.setNonSplicedActiveNotation(METHOD_C_6_BELL);
Assert.assertEquals(Optional.of(METHOD_C_6_BELL), composition.get().getNonSplicedActiveNotation());
composition.removeNotation(METHOD_C_6_BELL);
Assert.assertEquals(Optional.of(METHOD_A_6_BELL), composition.get().getNonSplicedActiveNotation());
composition.removeNotation(METHOD_A_6_BELL);
assertFalse(composition.get().getNonSplicedActiveNotation().isPresent());
}
@Test
public void removingNotationSwitchesToLexicographicallyNextActiveNotationWithinClosestNumberOfBells() {
MutableComposition composition = new MutableComposition();
composition.setNumberOfBells(NumberOfBells.BELLS_8);
composition.addNotation(METHOD_A_8_BELL);
composition.addNotation(METHOD_B_8_BELL);
composition.addNotation(METHOD_C_6_BELL);
Assert.assertEquals(Optional.of(METHOD_A_8_BELL), composition.get().getNonSplicedActiveNotation());
composition.setNonSplicedActiveNotation(METHOD_B_8_BELL);
Assert.assertEquals(Optional.of(METHOD_B_8_BELL), composition.get().getNonSplicedActiveNotation());
composition.removeNotation(METHOD_B_8_BELL);
Assert.assertEquals(Optional.of(METHOD_A_8_BELL), composition.get().getNonSplicedActiveNotation());
composition.removeNotation(METHOD_A_8_BELL);
Assert.assertEquals(Optional.of(METHOD_C_6_BELL), composition.get().getNonSplicedActiveNotation());
}
@Test
public void removingNotationSwitchesToClosestNumberOfBellsHighestFirst() {
MutableComposition composition = new MutableComposition();
composition.addNotation(METHOD_A_6_BELL);
composition.addNotation(METHOD_A_7_BELL);
composition.addNotation(METHOD_A_8_BELL);
composition.setNumberOfBells(NumberOfBells.BELLS_8);
Assert.assertEquals(Optional.of(METHOD_A_6_BELL), composition.get().getNonSplicedActiveNotation());
composition.setNonSplicedActiveNotation(METHOD_A_7_BELL);
Assert.assertEquals(Optional.of(METHOD_A_7_BELL), composition.get().getNonSplicedActiveNotation());
composition.removeNotation(METHOD_A_7_BELL);
Assert.assertEquals(Optional.of(METHOD_A_8_BELL), composition.get().getNonSplicedActiveNotation());
composition.removeNotation(METHOD_A_8_BELL);
Assert.assertEquals(Optional.of(METHOD_A_6_BELL), composition.get().getNonSplicedActiveNotation());
}
@Test
public void addingNotationsWithDifferentNumberOfBellsFiltersInappropriateNotations() {
MutableComposition composition = new MutableComposition();
composition.setSpliced(false);
composition.addNotation(METHOD_A_6_BELL);
composition.addNotation(METHOD_B_6_BELL);
composition.addNotation(METHOD_A_8_BELL);
assertEquals(3, composition.get().getAllNotations().size());
assertEquals(1, composition.get().getAvailableNotations().size());
assertEquals(2, composition.get().getValidNotations().size());
composition.setSpliced(true);
assertEquals(3, composition.get().getAllNotations().size());
assertEquals(2, composition.get().getAvailableNotations().size());
assertEquals(2, composition.get().getValidNotations().size());
}
@Test
public void settingActiveNotationUnsetsSpliced() {
MutableComposition composition = new MutableComposition();
composition.addNotation(METHOD_A_6_BELL);
composition.addNotation(METHOD_B_6_BELL);
composition.setSpliced(true);
assertEquals(true, composition.get().isSpliced());
composition.setNonSplicedActiveNotation(METHOD_A_6_BELL);
assertEquals(false, composition.get().isSpliced());
}
}
| |
/*
* Copyright (c) 2008-2021, Hazelcast, 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.hazelcast.internal.monitor.impl;
import com.hazelcast.internal.metrics.Probe;
import com.hazelcast.query.LocalIndexStats;
import static com.hazelcast.internal.metrics.MetricDescriptorConstants.MAP_METRIC_INDEX_AVERAGE_HIT_LATENCY;
import static com.hazelcast.internal.metrics.MetricDescriptorConstants.MAP_METRIC_INDEX_AVERAGE_HIT_SELECTIVITY;
import static com.hazelcast.internal.metrics.MetricDescriptorConstants.MAP_METRIC_INDEX_CREATION_TIME;
import static com.hazelcast.internal.metrics.MetricDescriptorConstants.MAP_METRIC_INDEX_HIT_COUNT;
import static com.hazelcast.internal.metrics.MetricDescriptorConstants.MAP_METRIC_INDEX_INSERT_COUNT;
import static com.hazelcast.internal.metrics.MetricDescriptorConstants.MAP_METRIC_INDEX_MEMORY_COST;
import static com.hazelcast.internal.metrics.MetricDescriptorConstants.MAP_METRIC_INDEX_QUERY_COUNT;
import static com.hazelcast.internal.metrics.MetricDescriptorConstants.MAP_METRIC_INDEX_REMOVE_COUNT;
import static com.hazelcast.internal.metrics.MetricDescriptorConstants.MAP_METRIC_INDEX_TOTAL_INSERT_LATENCY;
import static com.hazelcast.internal.metrics.MetricDescriptorConstants.MAP_METRIC_INDEX_TOTAL_REMOVE_LATENCY;
import static com.hazelcast.internal.metrics.MetricDescriptorConstants.MAP_METRIC_INDEX_TOTAL_UPDATE_LATENCY;
import static com.hazelcast.internal.metrics.MetricDescriptorConstants.MAP_METRIC_INDEX_UPDATE_COUNT;
import static com.hazelcast.internal.metrics.ProbeUnit.BYTES;
import static com.hazelcast.internal.metrics.ProbeUnit.MS;
import static com.hazelcast.internal.metrics.ProbeUnit.NS;
import static com.hazelcast.internal.metrics.ProbeUnit.PERCENT;
/**
* Implementation of local index stats that backs the stats exposed through the
* public API.
*/
@SuppressWarnings("checkstyle:methodcount")
public class LocalIndexStatsImpl implements LocalIndexStats {
@Probe(name = MAP_METRIC_INDEX_CREATION_TIME, unit = MS)
private volatile long creationTime;
@Probe(name = MAP_METRIC_INDEX_QUERY_COUNT)
private volatile long queryCount;
@Probe(name = MAP_METRIC_INDEX_HIT_COUNT)
private volatile long hitCount;
@Probe(name = MAP_METRIC_INDEX_AVERAGE_HIT_LATENCY, unit = NS)
private volatile long averageHitLatency;
@Probe(name = MAP_METRIC_INDEX_AVERAGE_HIT_SELECTIVITY, unit = PERCENT)
private volatile double averageHitSelectivity;
@Probe(name = MAP_METRIC_INDEX_INSERT_COUNT)
private volatile long insertCount;
@Probe(name = MAP_METRIC_INDEX_TOTAL_INSERT_LATENCY, unit = NS)
private volatile long totalInsertLatency;
@Probe(name = MAP_METRIC_INDEX_UPDATE_COUNT)
private volatile long updateCount;
@Probe(name = MAP_METRIC_INDEX_TOTAL_UPDATE_LATENCY, unit = NS)
private volatile long totalUpdateLatency;
@Probe(name = MAP_METRIC_INDEX_REMOVE_COUNT)
private volatile long removeCount;
@Probe(name = MAP_METRIC_INDEX_TOTAL_REMOVE_LATENCY, unit = NS)
private volatile long totalRemoveLatency;
@Probe(name = MAP_METRIC_INDEX_MEMORY_COST, unit = BYTES)
private volatile long memoryCost;
@Override
public long getCreationTime() {
return creationTime;
}
/**
* Sets the creation of this stats to the given creation time.
*
* @param creationTime the creation time to set.
*/
public void setCreationTime(long creationTime) {
this.creationTime = creationTime;
}
@Override
public long getQueryCount() {
return queryCount;
}
/**
* Sets the query count of this stats to the given query count.
*
* @param queryCount the query count to set.
*/
public void setQueryCount(long queryCount) {
this.queryCount = queryCount;
}
@Override
public long getHitCount() {
return hitCount;
}
/**
* Sets the hit count of this stats to the given hit count.
*
* @param hitCount the hit count to set.
*/
public void setHitCount(long hitCount) {
this.hitCount = hitCount;
}
@Override
public long getAverageHitLatency() {
return averageHitLatency;
}
/**
* Sets the average hit latency of this stats to the given average hit
* latency.
*
* @param averageHitLatency the average hit latency to set.
*/
public void setAverageHitLatency(long averageHitLatency) {
this.averageHitLatency = averageHitLatency;
}
@Override
public double getAverageHitSelectivity() {
return averageHitSelectivity;
}
/**
* Sets the average hit selectivity of this stats to the given average hit
* selectivity.
*
* @param averageHitSelectivity the average hit selectivity to set.
*/
public void setAverageHitSelectivity(double averageHitSelectivity) {
this.averageHitSelectivity = averageHitSelectivity;
}
@Override
public long getInsertCount() {
return insertCount;
}
/**
* Sets the insert count of this stats to the given insert count.
*
* @param insertCount the insert count to set.
*/
public void setInsertCount(long insertCount) {
this.insertCount = insertCount;
}
@Override
public long getTotalInsertLatency() {
return totalInsertLatency;
}
/**
* Sets the total insert latency of this stats to the given total insert
* latency.
*
* @param totalInsertLatency the total insert latency to set.
*/
public void setTotalInsertLatency(long totalInsertLatency) {
this.totalInsertLatency = totalInsertLatency;
}
@Override
public long getUpdateCount() {
return updateCount;
}
/**
* Sets the update count of this stats to the given update count.
*
* @param updateCount the update count to set.
*/
public void setUpdateCount(long updateCount) {
this.updateCount = updateCount;
}
@Override
public long getTotalUpdateLatency() {
return totalUpdateLatency;
}
/**
* Sets the total update latency of this stats to the given total update
* latency.
*
* @param totalUpdateLatency the total update latency to set.
*/
public void setTotalUpdateLatency(long totalUpdateLatency) {
this.totalUpdateLatency = totalUpdateLatency;
}
@Override
public long getRemoveCount() {
return removeCount;
}
/**
* Sets the remove count of this stats to the given remove count.
*
* @param removeCount the remove count to set.
*/
public void setRemoveCount(long removeCount) {
this.removeCount = removeCount;
}
@Override
public long getTotalRemoveLatency() {
return totalRemoveLatency;
}
/**
* Sets the total remove latency of this stats to the given total remove
* latency.
*
* @param totalRemoveLatency the total remove latency to set.
*/
public void setTotalRemoveLatency(long totalRemoveLatency) {
this.totalRemoveLatency = totalRemoveLatency;
}
@Override
public long getMemoryCost() {
return memoryCost;
}
/**
* Sets the memory cost of this stats to the given memory cost value.
*
* @param memoryCost the memory cost value to set.
*/
public void setMemoryCost(long memoryCost) {
this.memoryCost = memoryCost;
}
/**
* Sets all the values in this stats to the corresponding values in the
* given on-demand stats.
*
* @param onDemandStats the on-demand stats to fetch the values to set from.
*/
public void setAllFrom(OnDemandIndexStats onDemandStats) {
this.creationTime = onDemandStats.getCreationTime();
this.hitCount = onDemandStats.getHitCount();
this.queryCount = onDemandStats.getQueryCount();
this.averageHitSelectivity = onDemandStats.getAverageHitSelectivity();
this.averageHitLatency = onDemandStats.getAverageHitLatency();
this.insertCount = onDemandStats.getInsertCount();
this.totalInsertLatency = onDemandStats.getTotalInsertLatency();
this.updateCount = onDemandStats.getUpdateCount();
this.totalUpdateLatency = onDemandStats.getTotalUpdateLatency();
this.removeCount = onDemandStats.getRemoveCount();
this.totalRemoveLatency = onDemandStats.getTotalRemoveLatency();
this.memoryCost = onDemandStats.getMemoryCost();
}
@Override
public String toString() {
return "LocalIndexStatsImpl{"
+ "creationTime=" + creationTime
+ ", hitCount=" + hitCount
+ ", queryCount=" + queryCount
+ ", averageHitSelectivity=" + averageHitSelectivity
+ ", averageHitLatency=" + averageHitLatency
+ ", insertCount=" + insertCount
+ ", totalInsertLatency=" + totalInsertLatency
+ ", updateCount=" + updateCount
+ ", totalUpdateLatency=" + totalUpdateLatency
+ ", removeCount=" + removeCount
+ ", totalRemoveLatency=" + totalRemoveLatency
+ ", memoryCost=" + memoryCost
+ '}';
}
}
| |
/*
* dex2jar - Tools to work with android .dex and java .class files
* Copyright (c) 2009-2012 Panxiaobo
*
* 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.googlecode.dex2jar.tools;
import java.io.File;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.nio.charset.StandardCharsets;
import java.nio.file.*;
import java.nio.file.attribute.BasicFileAttributes;
import java.nio.file.spi.FileSystemProvider;
import java.util.*;
public abstract class BaseCmd {
public static String getBaseName(String fn) {
int x = fn.lastIndexOf('.');
return x >= 0 ? fn.substring(0, x) : fn;
}
public static String getBaseName(Path fn) {
return getBaseName(fn.getFileName().toString());
}
public interface FileVisitorX {
// change the relative from Path to String
// java.nio.file.ProviderMismatchException on jdk8
void visitFile(Path file, String relative) throws IOException;
}
public static void walkFileTreeX(final Path base, final FileVisitorX fv) throws IOException {
Files.walkFileTree(base, new SimpleFileVisitor<Path>() {
@Override
public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
fv.visitFile(file, base.relativize(file).toString());
return super.visitFile(file, attrs);
}
});
}
public static void walkJarOrDir(final Path in, final FileVisitorX fv) throws IOException {
if (Files.isDirectory(in)) {
walkFileTreeX(in, fv);
} else {
try (FileSystem inputFileSystem = openZip(in)) {
walkFileTreeX(inputFileSystem.getPath("/"), fv);
}
}
}
public static void createParentDirectories(Path p) throws IOException {
// merge patch from t3stwhat, fix crash on save to windows path like 'C:\\abc.jar'
Path parent = p.getParent();
if (parent != null && !Files.exists(parent)) {
Files.createDirectories(parent);
}
}
public static FileSystem createZip(Path output) throws IOException {
Map<String, Object> env = new HashMap<>();
env.put("create", "true");
Files.deleteIfExists(output);
createParentDirectories(output);
for (FileSystemProvider p : FileSystemProvider.installedProviders()) {
String s = p.getScheme();
if ("jar".equals(s) || "zip".equalsIgnoreCase(s)) {
return p.newFileSystem(output, env);
}
}
throw new IOException("cant find zipfs support");
}
public static FileSystem openZip(Path in) throws IOException {
for (FileSystemProvider p : FileSystemProvider.installedProviders()) {
String s = p.getScheme();
if ("jar".equals(s) || "zip".equalsIgnoreCase(s)) {
return p.newFileSystem(in, new HashMap<String, Object>());
}
}
throw new IOException("cant find zipfs support");
}
@SuppressWarnings("serial")
protected static class HelpException extends RuntimeException {
public HelpException() {
super();
}
public HelpException(String message) {
super(message);
}
}
@Retention(value = RetentionPolicy.RUNTIME)
@Target(value = { ElementType.FIELD })
static public @interface Opt {
String argName() default "";
String description() default "";
boolean hasArg() default true;
String longOpt() default "";
String opt() default "";
boolean required() default false;
}
static protected class Option implements Comparable<Option> {
public String argName = "arg";
public String description;
public Field field;
public boolean hasArg = true;
public String longOpt;
public String opt;
public boolean required = false;
@Override
public int compareTo(Option o) {
int result = s(this.opt, o.opt);
if (result == 0) {
result = s(this.longOpt, o.longOpt);
if (result == 0) {
result = s(this.argName, o.argName);
if (result == 0) {
result = s(this.description, o.description);
}
}
}
return result;
}
private static int s(String a, String b) {
if (a != null && b != null) {
return a.compareTo(b);
} else if (a != null) {
return 1;
} else if (b != null) {
return -1;
} else {
return 0;
}
}
public String getOptAndLongOpt() {
StringBuilder sb = new StringBuilder();
boolean havePrev = false;
if (opt != null && opt.length() > 0) {
sb.append("-").append(opt);
havePrev = true;
}
if (longOpt != null && longOpt.length() > 0) {
if (havePrev) {
sb.append(",");
}
sb.append("--").append(longOpt);
}
return sb.toString();
}
}
@Retention(value = RetentionPolicy.RUNTIME)
@Target(value = { ElementType.TYPE })
static public @interface Syntax {
String cmd();
String desc() default "";
String onlineHelp() default "";
String syntax() default "";
}
private String cmdLineSyntax;
private String cmdName;
private String desc;
private String onlineHelp;
protected Map<String, Option> optMap = new HashMap<String, Option>();
@Opt(opt = "h", longOpt = "help", hasArg = false, description = "Print this help message")
private boolean printHelp = false;
protected String remainingArgs[];
protected String orginalArgs[];
public BaseCmd() {
}
public BaseCmd(String cmdLineSyntax, String header) {
super();
int i = cmdLineSyntax.indexOf(' ');
if (i > 0) {
this.cmdName = cmdLineSyntax.substring(0, i);
this.cmdLineSyntax = cmdLineSyntax.substring(i + 1);
}
this.desc = header;
}
public BaseCmd(String cmdName, String cmdSyntax, String header) {
super();
this.cmdName = cmdName;
this.cmdLineSyntax = cmdSyntax;
this.desc = header;
}
private Set<Option> collectRequriedOptions(Map<String, Option> optMap) {
Set<Option> options = new HashSet<Option>();
for (Map.Entry<String, Option> e : optMap.entrySet()) {
Option option = e.getValue();
if (option.required) {
options.add(option);
}
}
return options;
}
@SuppressWarnings({ "rawtypes", "unchecked" })
protected Object convert(String value, Class type) {
if (type.equals(String.class)) {
return value;
}
if (type.equals(int.class) || type.equals(Integer.class)) {
return Integer.parseInt(value);
}
if (type.equals(long.class) || type.equals(Long.class)) {
return Long.parseLong(value);
}
if (type.equals(float.class) || type.equals(Float.class)) {
return Float.parseFloat(value);
}
if (type.equals(double.class) || type.equals(Double.class)) {
return Double.parseDouble(value);
}
if (type.equals(boolean.class) || type.equals(Boolean.class)) {
return Boolean.parseBoolean(value);
}
if (type.equals(File.class)) {
return new File(value);
}
if (type.equals(Path.class)) {
return new File(value).toPath();
}
try {
type.asSubclass(Enum.class);
return Enum.valueOf(type, value);
} catch (Exception e) {
}
throw new RuntimeException("can't convert [" + value + "] to type " + type);
}
;
protected abstract void doCommandLine() throws Exception;
public void doMain(String... args) {
try {
initOptions();
parseSetArgs(args);
doCommandLine();
} catch (HelpException e) {
String msg = e.getMessage();
if (msg != null && msg.length() > 0) {
System.err.println("ERROR: " + msg);
}
usage();
} catch (Exception e) {
e.printStackTrace(System.err);
}
}
protected String getVersionString() {
return getClass().getPackage().getImplementationVersion();
}
protected void initOptionFromClass(Class<?> clz) {
if (clz == null) {
return;
} else {
initOptionFromClass(clz.getSuperclass());
}
Syntax syntax = clz.getAnnotation(Syntax.class);
if (syntax != null) {
this.cmdLineSyntax = syntax.syntax();
this.cmdName = syntax.cmd();
this.desc = syntax.desc();
this.onlineHelp = syntax.onlineHelp();
}
Field[] fs = clz.getDeclaredFields();
for (Field f : fs) {
Opt opt = f.getAnnotation(Opt.class);
if (opt != null) {
f.setAccessible(true);
if (!opt.hasArg()) {
Class<?> type = f.getType();
if (!type.equals(boolean.class)) {
throw new RuntimeException("the type of " + f
+ " must be boolean, as it is declared as no args");
}
boolean b;
try {
b = (Boolean) f.get(this);
} catch (Exception e) {
throw new RuntimeException(e);
}
if (b) {
throw new RuntimeException("the value of " + f + " must be false, as it is declared as no args");
}
}
Option option = new Option();
option.field = f;
option.description = opt.description();
option.hasArg = opt.hasArg();
option.required = opt.required();
boolean haveLongOpt = false;
if (!"".equals(opt.longOpt())) {
option.longOpt = opt.longOpt();
checkConflict(option, "--" + option.longOpt);
haveLongOpt = true;
}
if (!"".equals(opt.argName())) {
option.argName = opt.argName();
}
if (!"".equals(opt.opt())) {
option.opt = opt.opt();
checkConflict(option, "-" + option.opt);
} else {
if (!haveLongOpt) {
throw new RuntimeException("opt or longOpt is not set in @Opt(...) " + f);
}
}
}
}
}
private void checkConflict(Option option, String key) {
if (optMap.containsKey(key)) {
Option preOption = optMap.get(key);
throw new RuntimeException(String.format("[@Opt(...) %s] conflict with [@Opt(...) %s]",
preOption.field.toString(), option.field
));
}
optMap.put(key, option);
}
protected void initOptions() {
initOptionFromClass(this.getClass());
}
public static void main(String... args) throws Exception {
if (args.length < 1) {
System.err.println("d2j-run <class> [args]");
return;
}
Class<?> clz = Class.forName(args[0]);
String newArgs[] = new String[args.length - 1];
System.arraycopy(args, 1, newArgs, 0, newArgs.length);
if (BaseCmd.class.isAssignableFrom(clz)) {
BaseCmd baseCmd = (BaseCmd) clz.newInstance();
baseCmd.doMain(newArgs);
} else {
Method m = clz.getMethod("main",String[].class);
m.setAccessible(true);
m.invoke(null, (Object)newArgs);
}
}
protected void parseSetArgs(String... args) throws IllegalArgumentException, IllegalAccessException {
this.orginalArgs = args;
List<String> remainsOptions = new ArrayList<String>();
Set<Option> requiredOpts = collectRequriedOptions(optMap);
Option needArgOpt = null;
for (String s : args) {
if (needArgOpt != null) {
needArgOpt.field.set(this, convert(s, needArgOpt.field.getType()));
needArgOpt = null;
} else if (s.startsWith("-")) {// its a short or long option
Option opt = optMap.get(s);
requiredOpts.remove(opt);
if (opt == null) {
System.err.println("ERROR: Unrecognized option: " + s);
throw new HelpException();
} else {
if (opt.hasArg) {
needArgOpt = opt;
} else {
opt.field.set(this, true);
}
}
} else {
remainsOptions.add(s);
}
}
if (needArgOpt != null) {
System.err.println("ERROR: Option " + needArgOpt.getOptAndLongOpt() + " need an argument value");
throw new HelpException();
}
this.remainingArgs = remainsOptions.toArray(new String[remainsOptions.size()]);
if (this.printHelp) {
throw new HelpException();
}
if (!requiredOpts.isEmpty()) {
StringBuilder sb = new StringBuilder();
sb.append("ERROR: Options: ");
boolean first = true;
for (Option option : requiredOpts) {
if (first) {
first = false;
} else {
sb.append(" and ");
}
sb.append(option.getOptAndLongOpt());
}
sb.append(" is required");
System.err.println(sb.toString());
throw new HelpException();
}
}
protected void usage() {
PrintWriter out = new PrintWriter(new OutputStreamWriter(System.err, StandardCharsets.UTF_8), true);
final int maxLength = 80;
final int maxPaLength = 40;
out.println(this.cmdName + " -- " + desc);
out.println("usage: " + this.cmdName + " " + cmdLineSyntax);
if (this.optMap.size() > 0) {
out.println("options:");
}
// [PART.A.........][Part.B
// .-a,--aa.<arg>...desc1
// .................desc2
// .-b,--bb
TreeSet<Option> options = new TreeSet<Option>(this.optMap.values());
int palength = -1;
for (Option option : options) {
int pa = 4 + option.getOptAndLongOpt().length();
if (option.hasArg) {
pa += 3 + option.argName.length();
}
if (pa < maxPaLength) {
if (pa > palength) {
palength = pa;
}
}
}
int pblength = maxLength - palength;
StringBuilder sb = new StringBuilder();
for (Option option : options) {
sb.setLength(0);
sb.append(" ").append(option.getOptAndLongOpt());
if (option.hasArg) {
sb.append(" <").append(option.argName).append(">");
}
String desc = option.description;
if (desc == null || desc.length() == 0) {// no description
out.println(sb);
} else {
for (int i = palength - sb.length(); i > 0; i--) {
sb.append(' ');
}
if (sb.length() > maxPaLength) {// to huge part A
out.println(sb);
sb.setLength(0);
for (int i = 0; i < palength; i++) {
sb.append(' ');
}
}
int nextStart = 0;
while (nextStart < desc.length()) {
if (desc.length() - nextStart < pblength) {// can put in one line
sb.append(desc.substring(nextStart));
out.println(sb);
nextStart = desc.length();
sb.setLength(0);
} else {
sb.append(desc.substring(nextStart, nextStart + pblength));
out.println(sb);
nextStart += pblength;
sb.setLength(0);
if (nextStart < desc.length()) {
for (int i = 0; i < palength; i++) {
sb.append(' ');
}
}
}
}
if (sb.length() > 0) {
out.println(sb);
sb.setLength(0);
}
}
}
String ver = getVersionString();
if (ver != null && !"".equals(ver)) {
out.println("version: " + ver);
}
if (onlineHelp != null && !"".equals(onlineHelp)) {
if (onlineHelp.length() + "online help: ".length() > maxLength) {
out.println("online help: ");
out.println(onlineHelp);
} else {
out.println("online help: " + onlineHelp);
}
}
out.flush();
}
}
| |
/*
* Copyright 2001-2010 Stephen Colebourne
*
* 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.sop4j.base.joda.time;
import com.sop4j.base.joda.convert.FromString;
import com.sop4j.base.joda.convert.ToString;
import com.sop4j.base.joda.time.base.BaseSingleFieldPeriod;
import com.sop4j.base.joda.time.field.FieldUtils;
import com.sop4j.base.joda.time.format.ISOPeriodFormat;
import com.sop4j.base.joda.time.format.PeriodFormatter;
/**
* An immutable time period representing a number of seconds.
* <p>
* <code>Seconds</code> is an immutable period that can only store seconds.
* It does not store years, months or hours for example. As such it is a
* type-safe way of representing a number of seconds in an application.
* <p>
* The number of seconds is set in the constructor, and may be queried using
* <code>getSeconds()</code>. Basic mathematical operations are provided -
* <code>plus()</code>, <code>minus()</code>, <code>multipliedBy()</code> and
* <code>dividedBy()</code>.
* <p>
* <code>Seconds</code> is thread-safe and immutable.
*
* @author Stephen Colebourne
* @since 1.4
*/
public final class Seconds extends BaseSingleFieldPeriod {
/** Constant representing zero seconds. */
public static final Seconds ZERO = new Seconds(0);
/** Constant representing one second. */
public static final Seconds ONE = new Seconds(1);
/** Constant representing two seconds. */
public static final Seconds TWO = new Seconds(2);
/** Constant representing three seconds. */
public static final Seconds THREE = new Seconds(3);
/** Constant representing the maximum number of seconds that can be stored in this object. */
public static final Seconds MAX_VALUE = new Seconds(Integer.MAX_VALUE);
/** Constant representing the minimum number of seconds that can be stored in this object. */
public static final Seconds MIN_VALUE = new Seconds(Integer.MIN_VALUE);
/** The paser to use for this class. */
private static final PeriodFormatter PARSER = ISOPeriodFormat.standard().withParseType(PeriodType.seconds());
/** Serialization version. */
private static final long serialVersionUID = 87525275727380862L;
//-----------------------------------------------------------------------
/**
* Obtains an instance of <code>Seconds</code> that may be cached.
* <code>Seconds</code> is immutable, so instances can be cached and shared.
* This factory method provides access to shared instances.
*
* @param seconds the number of seconds to obtain an instance for
* @return the instance of Seconds
*/
public static Seconds seconds(int seconds) {
switch (seconds) {
case 0:
return ZERO;
case 1:
return ONE;
case 2:
return TWO;
case 3:
return THREE;
case Integer.MAX_VALUE:
return MAX_VALUE;
case Integer.MIN_VALUE:
return MIN_VALUE;
default:
return new Seconds(seconds);
}
}
//-----------------------------------------------------------------------
/**
* Creates a <code>Seconds</code> representing the number of whole seconds
* between the two specified datetimes.
*
* @param start the start instant, must not be null
* @param end the end instant, must not be null
* @return the period in seconds
* @throws IllegalArgumentException if the instants are null or invalid
*/
public static Seconds secondsBetween(ReadableInstant start, ReadableInstant end) {
int amount = BaseSingleFieldPeriod.between(start, end, DurationFieldType.seconds());
return Seconds.seconds(amount);
}
/**
* Creates a <code>Seconds</code> representing the number of whole seconds
* between the two specified partial datetimes.
* <p>
* The two partials must contain the same fields, for example you can specify
* two <code>LocalTime</code> objects.
*
* @param start the start partial date, must not be null
* @param end the end partial date, must not be null
* @return the period in seconds
* @throws IllegalArgumentException if the partials are null or invalid
*/
public static Seconds secondsBetween(ReadablePartial start, ReadablePartial end) {
if (start instanceof LocalTime && end instanceof LocalTime) {
Chronology chrono = DateTimeUtils.getChronology(start.getChronology());
int seconds = chrono.seconds().getDifference(
((LocalTime) end).getLocalMillis(), ((LocalTime) start).getLocalMillis());
return Seconds.seconds(seconds);
}
int amount = BaseSingleFieldPeriod.between(start, end, ZERO);
return Seconds.seconds(amount);
}
/**
* Creates a <code>Seconds</code> representing the number of whole seconds
* in the specified interval.
*
* @param interval the interval to extract seconds from, null returns zero
* @return the period in seconds
* @throws IllegalArgumentException if the partials are null or invalid
*/
public static Seconds secondsIn(ReadableInterval interval) {
if (interval == null) {
return Seconds.ZERO;
}
int amount = BaseSingleFieldPeriod.between(interval.getStart(), interval.getEnd(), DurationFieldType.seconds());
return Seconds.seconds(amount);
}
/**
* Creates a new <code>Seconds</code> representing the number of complete
* standard length seconds in the specified period.
* <p>
* This factory method converts all fields from the period to hours using standardised
* durations for each field. Only those fields which have a precise duration in
* the ISO UTC chronology can be converted.
* <ul>
* <li>One week consists of 7 seconds.
* <li>One day consists of 24 hours.
* <li>One hour consists of 60 minutes.
* <li>One minute consists of 60 seconds.
* <li>One second consists of 1000 milliseconds.
* </ul>
* Months and Years are imprecise and periods containing these values cannot be converted.
*
* @param period the period to get the number of hours from, null returns zero
* @return the period in seconds
* @throws IllegalArgumentException if the period contains imprecise duration values
*/
public static Seconds standardSecondsIn(ReadablePeriod period) {
int amount = BaseSingleFieldPeriod.standardPeriodIn(period, DateTimeConstants.MILLIS_PER_SECOND);
return Seconds.seconds(amount);
}
/**
* Creates a new <code>Seconds</code> by parsing a string in the ISO8601 format 'PTnS'.
* <p>
* The parse will accept the full ISO syntax of PnYnMnWnDTnHnMnS however only the
* seconds component may be non-zero. If any other component is non-zero, an exception
* will be thrown.
*
* @param periodStr the period string, null returns zero
* @return the period in seconds
* @throws IllegalArgumentException if the string format is invalid
*/
@FromString
public static Seconds parseSeconds(String periodStr) {
if (periodStr == null) {
return Seconds.ZERO;
}
Period p = PARSER.parsePeriod(periodStr);
return Seconds.seconds(p.getSeconds());
}
//-----------------------------------------------------------------------
/**
* Creates a new instance representing a number of seconds.
* You should consider using the factory method {@link #seconds(int)}
* instead of the constructor.
*
* @param seconds the number of seconds to represent
*/
private Seconds(int seconds) {
super(seconds);
}
/**
* Resolves singletons.
*
* @return the singleton instance
*/
private Object readResolve() {
return Seconds.seconds(getValue());
}
//-----------------------------------------------------------------------
/**
* Gets the duration field type, which is <code>seconds</code>.
*
* @return the period type
*/
public DurationFieldType getFieldType() {
return DurationFieldType.seconds();
}
/**
* Gets the period type, which is <code>seconds</code>.
*
* @return the period type
*/
public PeriodType getPeriodType() {
return PeriodType.seconds();
}
//-----------------------------------------------------------------------
/**
* Converts this period in seconds to a period in weeks assuming a
* 7 day week, 24 hour day, 60 minute hour and 60 second minute.
* <p>
* This method allows you to convert between different types of period.
* However to achieve this it makes the assumption that all weeks are 7 days
* long, all days are 24 hours long, all hours are 60 minutes long and
* all minutes are 60 seconds long.
* This is not true when daylight savings time is considered, and may also
* not be true for some unusual chronologies. However, it is included as it
* is a useful operation for many applications and business rules.
*
* @return a period representing the number of whole weeks for this number of seconds
*/
public Weeks toStandardWeeks() {
return Weeks.weeks(getValue() / DateTimeConstants.SECONDS_PER_WEEK);
}
/**
* Converts this period in seconds to a period in days assuming a
* 24 hour day, 60 minute hour and 60 second minute.
* <p>
* This method allows you to convert between different types of period.
* However to achieve this it makes the assumption that all days are 24 hours
* long, all hours are 60 minutes long and all minutes are 60 seconds long.
* This is not true when daylight savings is considered and may also not
* be true for some unusual chronologies. However, it is included
* as it is a useful operation for many applications and business rules.
*
* @return a period representing the number of days for this number of seconds
*/
public Days toStandardDays() {
return Days.days(getValue() / DateTimeConstants.SECONDS_PER_DAY);
}
/**
* Converts this period in seconds to a period in hours assuming a
* 60 minute hour and 60 second minute.
* <p>
* This method allows you to convert between different types of period.
* However to achieve this it makes the assumption that all hours are
* 60 minutes long and all minutes are 60 seconds long.
* This may not be true for some unusual chronologies. However, it is included
* as it is a useful operation for many applications and business rules.
*
* @return a period representing the number of hours for this number of seconds
*/
public Hours toStandardHours() {
return Hours.hours(getValue() / DateTimeConstants.SECONDS_PER_HOUR);
}
/**
* Converts this period in seconds to a period in minutes assuming a
* 60 second minute.
* <p>
* This method allows you to convert between different types of period.
* However to achieve this it makes the assumption that all minutes are
* 60 seconds long.
* This may not be true for some unusual chronologies. However, it is included
* as it is a useful operation for many applications and business rules.
*
* @return a period representing the number of minutes for this number of seconds
*/
public Minutes toStandardMinutes() {
return Minutes.minutes(getValue() / DateTimeConstants.SECONDS_PER_MINUTE);
}
//-----------------------------------------------------------------------
/**
* Converts this period in seconds to a duration in milliseconds assuming a
* 24 hour day, 60 minute hour and 60 second minute.
* <p>
* This method allows you to convert from a period to a duration.
* However to achieve this it makes the assumption that all seconds are 24 hours
* long, all hours are 60 minutes and all minutes are 60 seconds.
* This is not true when daylight savings time is considered, and may also
* not be true for some unusual chronologies. However, it is included as it
* is a useful operation for many applications and business rules.
*
* @return a duration equivalent to this number of seconds
*/
public Duration toStandardDuration() {
long seconds = getValue(); // assign to a long
return new Duration(seconds * DateTimeConstants.MILLIS_PER_SECOND);
}
//-----------------------------------------------------------------------
/**
* Gets the number of seconds that this period represents.
*
* @return the number of seconds in the period
*/
public int getSeconds() {
return getValue();
}
//-----------------------------------------------------------------------
/**
* Returns a new instance with the specified number of seconds added.
* <p>
* This instance is immutable and unaffected by this method call.
*
* @param seconds the amount of seconds to add, may be negative
* @return the new period plus the specified number of seconds
* @throws ArithmeticException if the result overflows an int
*/
public Seconds plus(int seconds) {
if (seconds == 0) {
return this;
}
return Seconds.seconds(FieldUtils.safeAdd(getValue(), seconds));
}
/**
* Returns a new instance with the specified number of seconds added.
* <p>
* This instance is immutable and unaffected by this method call.
*
* @param seconds the amount of seconds to add, may be negative, null means zero
* @return the new period plus the specified number of seconds
* @throws ArithmeticException if the result overflows an int
*/
public Seconds plus(Seconds seconds) {
if (seconds == null) {
return this;
}
return plus(seconds.getValue());
}
//-----------------------------------------------------------------------
/**
* Returns a new instance with the specified number of seconds taken away.
* <p>
* This instance is immutable and unaffected by this method call.
*
* @param seconds the amount of seconds to take away, may be negative
* @return the new period minus the specified number of seconds
* @throws ArithmeticException if the result overflows an int
*/
public Seconds minus(int seconds) {
return plus(FieldUtils.safeNegate(seconds));
}
/**
* Returns a new instance with the specified number of seconds taken away.
* <p>
* This instance is immutable and unaffected by this method call.
*
* @param seconds the amount of seconds to take away, may be negative, null means zero
* @return the new period minus the specified number of seconds
* @throws ArithmeticException if the result overflows an int
*/
public Seconds minus(Seconds seconds) {
if (seconds == null) {
return this;
}
return minus(seconds.getValue());
}
//-----------------------------------------------------------------------
/**
* Returns a new instance with the seconds multiplied by the specified scalar.
* <p>
* This instance is immutable and unaffected by this method call.
*
* @param scalar the amount to multiply by, may be negative
* @return the new period multiplied by the specified scalar
* @throws ArithmeticException if the result overflows an int
*/
public Seconds multipliedBy(int scalar) {
return Seconds.seconds(FieldUtils.safeMultiply(getValue(), scalar));
}
/**
* Returns a new instance with the seconds divided by the specified divisor.
* The calculation uses integer division, thus 3 divided by 2 is 1.
* <p>
* This instance is immutable and unaffected by this method call.
*
* @param divisor the amount to divide by, may be negative
* @return the new period divided by the specified divisor
* @throws ArithmeticException if the divisor is zero
*/
public Seconds dividedBy(int divisor) {
if (divisor == 1) {
return this;
}
return Seconds.seconds(getValue() / divisor);
}
//-----------------------------------------------------------------------
/**
* Returns a new instance with the seconds value negated.
*
* @return the new period with a negated value
* @throws ArithmeticException if the result overflows an int
*/
public Seconds negated() {
return Seconds.seconds(FieldUtils.safeNegate(getValue()));
}
//-----------------------------------------------------------------------
/**
* Is this seconds instance greater than the specified number of seconds.
*
* @param other the other period, null means zero
* @return true if this seconds instance is greater than the specified one
*/
public boolean isGreaterThan(Seconds other) {
if (other == null) {
return getValue() > 0;
}
return getValue() > other.getValue();
}
/**
* Is this seconds instance less than the specified number of seconds.
*
* @param other the other period, null means zero
* @return true if this seconds instance is less than the specified one
*/
public boolean isLessThan(Seconds other) {
if (other == null) {
return getValue() < 0;
}
return getValue() < other.getValue();
}
//-----------------------------------------------------------------------
/**
* Gets this instance as a String in the ISO8601 duration format.
* <p>
* For example, "PT4S" represents 4 seconds.
*
* @return the value as an ISO8601 string
*/
@ToString
public String toString() {
return "PT" + String.valueOf(getValue()) + "S";
}
}
| |
/*
* Copyright (C) 2010 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 edu.bupt.calendar;
import static android.provider.CalendarContract.EXTRA_EVENT_BEGIN_TIME;
import static android.provider.CalendarContract.EXTRA_EVENT_END_TIME;
import android.app.ActionBar;
import android.app.Activity;
import android.app.FragmentManager;
import android.app.FragmentTransaction;
import android.app.SearchManager;
import android.content.BroadcastReceiver;
import android.content.ContentResolver;
import android.content.ContentUris;
import android.content.Intent;
import android.database.ContentObserver;
import android.graphics.drawable.LayerDrawable;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.provider.CalendarContract.Events;
import android.provider.SearchRecentSuggestions;
import android.text.format.Time;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.MenuItem.OnActionExpandListener;
import android.widget.SearchView;
import edu.bupt.calendar.CalendarController.EventInfo;
import edu.bupt.calendar.CalendarController.EventType;
import edu.bupt.calendar.CalendarController.ViewType;
import edu.bupt.calendar.agenda.AgendaFragment;
public class SearchActivity extends Activity implements CalendarController.EventHandler,
SearchView.OnQueryTextListener, OnActionExpandListener {
private static final String TAG = SearchActivity.class.getSimpleName();
private static final boolean DEBUG = false;
private static final int HANDLER_KEY = 0;
protected static final String BUNDLE_KEY_RESTORE_TIME = "key_restore_time";
protected static final String BUNDLE_KEY_RESTORE_SEARCH_QUERY =
"key_restore_search_query";
// display event details to the side of the event list
private boolean mShowEventDetailsWithAgenda;
private static boolean mIsMultipane;
private CalendarController mController;
private EventInfoFragment mEventInfoFragment;
private long mCurrentEventId = -1;
private String mQuery;
private SearchView mSearchView;
private DeleteEventHelper mDeleteEventHelper;
private Handler mHandler;
private BroadcastReceiver mTimeChangesReceiver;
private ContentResolver mContentResolver;
private final ContentObserver mObserver = new ContentObserver(new Handler()) {
@Override
public boolean deliverSelfNotifications() {
return true;
}
@Override
public void onChange(boolean selfChange) {
eventsChanged();
}
};
// runs when a timezone was changed and updates the today icon
private final Runnable mTimeChangesUpdater = new Runnable() {
@Override
public void run() {
Utils.setMidnightUpdater(mHandler, mTimeChangesUpdater,
Utils.getTimeZone(SearchActivity.this, mTimeChangesUpdater));
SearchActivity.this.invalidateOptionsMenu();
}
};
@Override
protected void onCreate(Bundle icicle) {
super.onCreate(icicle);
// This needs to be created before setContentView
mController = CalendarController.getInstance(this);
mHandler = new Handler();
mIsMultipane = Utils.getConfigBool(this, R.bool.multiple_pane_config);
mShowEventDetailsWithAgenda =
Utils.getConfigBool(this, R.bool.show_event_details_with_agenda);
setContentView(R.layout.search);
setDefaultKeyMode(DEFAULT_KEYS_SEARCH_LOCAL);
mContentResolver = getContentResolver();
if (mIsMultipane) {
getActionBar().setDisplayOptions(
ActionBar.DISPLAY_HOME_AS_UP, ActionBar.DISPLAY_HOME_AS_UP);
} else {
getActionBar().setDisplayOptions(0,
ActionBar.DISPLAY_HOME_AS_UP | ActionBar.DISPLAY_SHOW_HOME);
}
// Must be the first to register because this activity can modify the
// list of event handlers in it's handle method. This affects who the
// rest of the handlers the controller dispatches to are.
mController.registerEventHandler(HANDLER_KEY, this);
mDeleteEventHelper = new DeleteEventHelper(this, this,
false /* don't exit when done */);
long millis = 0;
if (icicle != null) {
// Returns 0 if key not found
millis = icicle.getLong(BUNDLE_KEY_RESTORE_TIME);
if (DEBUG) {
Log.v(TAG, "Restore value from icicle: " + millis);
}
}
if (millis == 0) {
// Didn't find a time in the bundle, look in intent or current time
millis = Utils.timeFromIntentInMillis(getIntent());
}
Intent intent = getIntent();
if (Intent.ACTION_SEARCH.equals(intent.getAction())) {
String query;
if (icicle != null && icicle.containsKey(BUNDLE_KEY_RESTORE_SEARCH_QUERY)) {
query = icicle.getString(BUNDLE_KEY_RESTORE_SEARCH_QUERY);
} else {
query = intent.getStringExtra(SearchManager.QUERY);
}
initFragments(millis, query);
}
}
@Override
protected void onDestroy() {
super.onDestroy();
mController.deregisterAllEventHandlers();
CalendarController.removeInstance(this);
}
private void initFragments(long timeMillis, String query) {
FragmentManager fragmentManager = getFragmentManager();
FragmentTransaction ft = fragmentManager.beginTransaction();
AgendaFragment searchResultsFragment = new AgendaFragment(timeMillis, true);
ft.replace(R.id.search_results, searchResultsFragment);
mController.registerEventHandler(R.id.search_results, searchResultsFragment);
ft.commit();
Time t = new Time();
t.set(timeMillis);
search(query, t);
}
private void showEventInfo(EventInfo event) {
if (mShowEventDetailsWithAgenda) {
FragmentManager fragmentManager = getFragmentManager();
FragmentTransaction ft = fragmentManager.beginTransaction();
mEventInfoFragment = new EventInfoFragment(this, event.id,
event.startTime.toMillis(false), event.endTime.toMillis(false),
event.getResponse(), false, EventInfoFragment.DIALOG_WINDOW_STYLE);
ft.replace(R.id.agenda_event_info, mEventInfoFragment);
ft.commit();
mController.registerEventHandler(R.id.agenda_event_info, mEventInfoFragment);
} else {
Intent intent = new Intent(Intent.ACTION_VIEW);
Uri eventUri = ContentUris.withAppendedId(Events.CONTENT_URI, event.id);
intent.setData(eventUri);
intent.setClass(this, EventInfoActivity.class);
intent.putExtra(EXTRA_EVENT_BEGIN_TIME,
event.startTime != null ? event.startTime.toMillis(true) : -1);
intent.putExtra(
EXTRA_EVENT_END_TIME, event.endTime != null ? event.endTime.toMillis(true) : -1);
startActivity(intent);
}
mCurrentEventId = event.id;
}
private void search(String searchQuery, Time goToTime) {
// save query in recent queries
SearchRecentSuggestions suggestions = new SearchRecentSuggestions(this,
Utils.getSearchAuthority(this),
CalendarRecentSuggestionsProvider.MODE);
suggestions.saveRecentQuery(searchQuery, null);
EventInfo searchEventInfo = new EventInfo();
searchEventInfo.eventType = EventType.SEARCH;
searchEventInfo.query = searchQuery;
searchEventInfo.viewType = ViewType.AGENDA;
if (goToTime != null) {
searchEventInfo.startTime = goToTime;
}
mController.sendEvent(this, searchEventInfo);
mQuery = searchQuery;
if (mSearchView != null) {
mSearchView.setQuery(mQuery, false);
mSearchView.clearFocus();
}
}
private void deleteEvent(long eventId, long startMillis, long endMillis) {
mDeleteEventHelper.delete(startMillis, endMillis, eventId, -1);
if (mIsMultipane && mEventInfoFragment != null
&& eventId == mCurrentEventId) {
FragmentManager fragmentManager = getFragmentManager();
FragmentTransaction ft = fragmentManager.beginTransaction();
ft.remove(mEventInfoFragment);
ft.commit();
mEventInfoFragment = null;
mController.deregisterEventHandler(R.id.agenda_event_info);
mCurrentEventId = -1;
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
super.onCreateOptionsMenu(menu);
getMenuInflater().inflate(R.menu.search_title_bar, menu);
// replace the default top layer drawable of the today icon with a custom drawable
// that shows the day of the month of today
LayerDrawable icon = (LayerDrawable)menu.findItem(R.id.action_today).getIcon();
Utils.setTodayIcon(icon, this, Utils.getTimeZone(SearchActivity.this, mTimeChangesUpdater));
MenuItem item = menu.findItem(R.id.action_search);
item.expandActionView();
item.setOnActionExpandListener(this);
mSearchView = (SearchView) item.getActionView();
Utils.setUpSearchView(mSearchView, this);
mSearchView.setQuery(mQuery, false);
mSearchView.clearFocus();
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
Time t = null;
switch (item.getItemId()) {
case R.id.action_today:
t = new Time();
t.setToNow();
mController.sendEvent(this, EventType.GO_TO, t, null, -1, ViewType.CURRENT);
return true;
case R.id.action_search:
return false;
case R.id.action_settings:
mController.sendEvent(this, EventType.LAUNCH_SETTINGS, null, null, 0, 0);
return true;
case android.R.id.home:
Utils.returnToCalendarHome(this);
return true;
default:
return false;
}
}
@Override
protected void onNewIntent(Intent intent) {
// From the Android Dev Guide: "It's important to note that when
// onNewIntent(Intent) is called, the Activity has not been restarted,
// so the getIntent() method will still return the Intent that was first
// received with onCreate(). This is why setIntent(Intent) is called
// inside onNewIntent(Intent) (just in case you call getIntent() at a
// later time)."
setIntent(intent);
handleIntent(intent);
}
private void handleIntent(Intent intent) {
if (Intent.ACTION_SEARCH.equals(intent.getAction())) {
String query = intent.getStringExtra(SearchManager.QUERY);
search(query, null);
}
}
@Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putLong(BUNDLE_KEY_RESTORE_TIME, mController.getTime());
outState.putString(BUNDLE_KEY_RESTORE_SEARCH_QUERY, mQuery);
}
@Override
protected void onResume() {
super.onResume();
Utils.setMidnightUpdater(
mHandler, mTimeChangesUpdater, Utils.getTimeZone(this, mTimeChangesUpdater));
// Make sure the today icon is up to date
invalidateOptionsMenu();
mTimeChangesReceiver = Utils.setTimeChangesReceiver(this, mTimeChangesUpdater);
mContentResolver.registerContentObserver(Events.CONTENT_URI, true, mObserver);
// We call this in case the user changed the time zone
eventsChanged();
}
@Override
protected void onPause() {
super.onPause();
Utils.resetMidnightUpdater(mHandler, mTimeChangesUpdater);
Utils.clearTimeChangesReceiver(this, mTimeChangesReceiver);
mContentResolver.unregisterContentObserver(mObserver);
}
@Override
public void eventsChanged() {
mController.sendEvent(this, EventType.EVENTS_CHANGED, null, null, -1, ViewType.CURRENT);
}
@Override
public long getSupportedEventTypes() {
return EventType.VIEW_EVENT | EventType.DELETE_EVENT;
}
@Override
public void handleEvent(EventInfo event) {
long endTime = (event.endTime == null) ? -1 : event.endTime.toMillis(false);
if (event.eventType == EventType.VIEW_EVENT) {
showEventInfo(event);
} else if (event.eventType == EventType.DELETE_EVENT) {
deleteEvent(event.id, event.startTime.toMillis(false), endTime);
}
}
@Override
public boolean onQueryTextChange(String newText) {
return false;
}
@Override
public boolean onQueryTextSubmit(String query) {
mQuery = query;
mController.sendEvent(this, EventType.SEARCH, null, null, -1, ViewType.CURRENT, 0, query,
getComponentName());
return false;
}
@Override
public boolean onMenuItemActionExpand(MenuItem item) {
return true;
}
@Override
public boolean onMenuItemActionCollapse(MenuItem item) {
Utils.returnToCalendarHome(this);
return false;
}
}
| |
/*
* Copyright 2000-2017 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.jetbrains.python.inspections;
import com.google.common.collect.ImmutableList;
import com.intellij.codeInspection.InspectionProfile;
import com.intellij.codeInspection.LocalQuickFix;
import com.intellij.codeInspection.ProblemHighlightType;
import com.intellij.codeInspection.ProblemsHolder;
import com.intellij.ide.util.ElementsChooser;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.roots.ProjectRootManager;
import com.intellij.openapi.util.JDOMExternalizableStringList;
import com.intellij.openapi.util.TextRange;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.profile.codeInspection.InspectionProjectProfileManager;
import com.intellij.psi.*;
import com.intellij.psi.util.PsiTreeUtil;
import com.intellij.psi.util.QualifiedName;
import com.intellij.util.ArrayUtil;
import com.intellij.util.containers.ContainerUtil;
import com.jetbrains.python.PyBundle;
import com.jetbrains.python.PyNames;
import com.jetbrains.python.inspections.quickfix.PyRenameElementQuickFix;
import com.jetbrains.python.psi.*;
import com.jetbrains.python.psi.impl.PyBuiltinCache;
import com.jetbrains.python.psi.types.PyClassType;
import com.jetbrains.python.psi.types.PyType;
import com.jetbrains.python.psi.types.PyTypeChecker;
import com.jetbrains.python.psi.types.TypeEvalContext;
import com.jetbrains.python.validation.CompatibilityVisitor;
import com.jetbrains.python.validation.UnsupportedFeaturesUtil;
import one.util.streamex.StreamEx;
import org.jetbrains.annotations.Nls;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import javax.swing.*;
import java.awt.*;
import java.util.List;
import java.util.*;
/**
* User: catherine
*
* Inspection to detect code incompatibility with python versions
*/
public class PyCompatibilityInspection extends PyInspection {
@NotNull
public static final List<String> BACKPORTED_PACKAGES = ImmutableList.<String>builder()
.add("enum")
.add("typing")
.build();
public static final List<String> COMPATIBILITY_LIBS = Collections.singletonList("six");
public static final int LATEST_INSPECTION_VERSION = 3;
@NotNull
public static final List<LanguageLevel> DEFAULT_PYTHON_VERSIONS = ImmutableList.of(LanguageLevel.PYTHON27, LanguageLevel.getLatest());
@NotNull
public static final List<LanguageLevel> SUPPORTED_LEVELS = StreamEx
.of(LanguageLevel.values())
.filter(v -> v.isPython2() && v.isAtLeast(LanguageLevel.PYTHON26) || v.isAtLeast(LanguageLevel.PYTHON34))
.toImmutableList();
@NotNull
private static final List<String> SUPPORTED_IN_SETTINGS = ContainerUtil.map(SUPPORTED_LEVELS, LanguageLevel::toString);
// Legacy DefaultJDOMExternalizer requires public fields for proper serialization
public JDOMExternalizableStringList ourVersions = new JDOMExternalizableStringList();
public PyCompatibilityInspection () {
if (ApplicationManager.getApplication().isUnitTestMode()) {
ourVersions.addAll(SUPPORTED_IN_SETTINGS);
}
else {
ourVersions.addAll(ContainerUtil.map(DEFAULT_PYTHON_VERSIONS, LanguageLevel::toString));
}
}
@Nullable
public static PyCompatibilityInspection getInstance(@NotNull PsiElement element) {
final InspectionProfile inspectionProfile = InspectionProjectProfileManager.getInstance(element.getProject()).getCurrentProfile();
final String toolName = PyCompatibilityInspection.class.getSimpleName();
return (PyCompatibilityInspection)inspectionProfile.getUnwrappedTool(toolName, element);
}
@Override
public boolean isEnabledByDefault() {
return false;
}
private List<LanguageLevel> updateVersionsToProcess() {
List<LanguageLevel> result = new ArrayList<>();
for (String version : ourVersions) {
if (SUPPORTED_IN_SETTINGS.contains(version)) {
LanguageLevel level = LanguageLevel.fromPythonVersion(version);
result.add(level);
}
}
return result;
}
@Nls
@NotNull
@Override
public String getDisplayName() {
return PyBundle.message("INSP.NAME.compatibility");
}
@Override
public JComponent createOptionsPanel() {
final ElementsChooser<String> chooser = new ElementsChooser<>(true);
chooser.setElements(SUPPORTED_IN_SETTINGS, false);
chooser.markElements(ContainerUtil.filter(ourVersions, SUPPORTED_IN_SETTINGS::contains));
chooser.addElementsMarkListener(new ElementsChooser.ElementsMarkListener<String>() {
@Override
public void elementMarkChanged(String element, boolean isMarked) {
ourVersions.clear();
ourVersions.addAll(chooser.getMarkedElements());
}
});
final JPanel versionPanel = new JPanel(new BorderLayout());
JLabel label = new JLabel("Check for compatibility with python versions:");
label.setLabelFor(chooser);
versionPanel.add(label, BorderLayout.PAGE_START);
versionPanel.add(chooser);
return versionPanel;
}
@NotNull
@Override
public PsiElementVisitor buildVisitor(@NotNull ProblemsHolder holder, boolean isOnTheFly) {
return new Visitor(holder, updateVersionsToProcess());
}
private static class Visitor extends CompatibilityVisitor {
private final ProblemsHolder myHolder;
private final Set<String> myUsedImports = Collections.synchronizedSet(new HashSet<>());
private final Set<String> myFromCompatibilityLibs = Collections.synchronizedSet(new HashSet<>());
Visitor(ProblemsHolder holder, List<LanguageLevel> versionsToProcess) {
super(versionsToProcess);
myHolder = holder;
}
@Override
protected void registerProblem(@NotNull PsiElement element,
@NotNull TextRange range,
@NotNull String message,
@Nullable LocalQuickFix quickFix,
boolean asError) {
if (element.getTextLength() == 0) {
return;
}
range = range.shiftRight(-element.getTextRange().getStartOffset());
if (quickFix != null) {
myHolder.registerProblem(element, range, message, quickFix);
}
else {
myHolder.registerProblem(element, range, message);
}
}
@Override
public void visitPyCallExpression(PyCallExpression node) {
super.visitPyCallExpression(node);
PyExpression callee = node.getCallee();
if (callee != null && importedFromCompatibilityLibs(callee)) {
return;
}
final PsiElement resolvedCallee = Optional
.ofNullable(callee)
.map(PyExpression::getReference)
.map(PsiReference::resolve)
.orElse(null);
if (resolvedCallee instanceof PyFunction) {
final PyFunction function = (PyFunction)resolvedCallee;
final PyClass containingClass = function.getContainingClass();
final String originalFunctionName = function.getName();
final String functionName = containingClass != null && PyNames.INIT.equals(originalFunctionName)
? callee.getText()
: originalFunctionName;
if (containingClass != null) {
final String className = containingClass.getName();
if (UnsupportedFeaturesUtil.CLASS_METHODS.containsKey(className)) {
final Map<LanguageLevel, Set<String>> unsupportedMethods = UnsupportedFeaturesUtil.CLASS_METHODS.get(className);
registerForAllMatchingVersions(level -> unsupportedMethods.getOrDefault(level, Collections.emptySet()).contains(functionName),
" not have method " + functionName,
node);
}
}
if (PyBuiltinCache.getInstance(function).isBuiltin(function) &&
!"print".equals(functionName) &&
!"exec".equals(functionName) &&
!myUsedImports.contains(functionName)) {
registerForAllMatchingVersions(level -> UnsupportedFeaturesUtil.BUILTINS.get(level).contains(functionName),
" not have method " + functionName,
node);
}
}
else if (resolvedCallee instanceof PyTargetExpression) {
final PyTargetExpression target = (PyTargetExpression)resolvedCallee;
if (!target.isQualified() &&
PyNames.TYPE_LONG.equals(target.getName()) &&
PyBuiltinCache.getInstance(resolvedCallee).isBuiltin(resolvedCallee)) {
registerForAllMatchingVersions(level -> UnsupportedFeaturesUtil.BUILTINS.get(level).contains(PyNames.TYPE_LONG),
" not have type long. Use int instead.",
node);
}
}
}
@Override
public void visitPyImportElement(PyImportElement importElement) {
myUsedImports.add(importElement.getVisibleName());
final PyIfStatement ifParent = PsiTreeUtil.getParentOfType(importElement, PyIfStatement.class);
if (ifParent != null) return;
final PyTryExceptStatement tryExceptStatement = PsiTreeUtil.getParentOfType(importElement, PyTryExceptStatement.class);
if (tryExceptStatement != null) {
for (PyExceptPart part : tryExceptStatement.getExceptParts()) {
final PyExpression exceptClass = part.getExceptClass();
if (exceptClass != null && exceptClass.getText().equals("ImportError")) {
return;
}
}
}
final QualifiedName qName = getImportedFullyQName(importElement);
if (qName != null && !qName.matches("builtins") && !qName.matches("__builtin__")) {
if (COMPATIBILITY_LIBS.contains(qName.getFirstComponent())) {
myFromCompatibilityLibs.add(qName.getLastComponent());
}
final String moduleName = qName.toString();
registerForAllMatchingVersions(level -> UnsupportedFeaturesUtil.MODULES.get(level).contains(moduleName) && !BACKPORTED_PACKAGES.contains(moduleName),
" not have module " + moduleName,
importElement);
}
}
@Nullable
private static QualifiedName getImportedFullyQName(@NotNull PyImportElement importElement) {
final QualifiedName importedQName = importElement.getImportedQName();
if (importedQName == null) return null;
final PyStatement containingImportStatement = importElement.getContainingImportStatement();
final QualifiedName importSourceQName = containingImportStatement instanceof PyFromImportStatement
? ((PyFromImportStatement)containingImportStatement).getImportSourceQName()
: null;
return importSourceQName == null ? importedQName : importSourceQName.append(importedQName);
}
@Override
public void visitPyFromImportStatement(PyFromImportStatement node) {
super.visitPyFromImportStatement(node);
if (node.getRelativeLevel() > 0) return;
final QualifiedName name = node.getImportSourceQName();
final PyReferenceExpression source = node.getImportSource();
if (name != null && source != null) {
final String moduleName = name.toString();
registerForAllMatchingVersions(level -> UnsupportedFeaturesUtil.MODULES.get(level).contains(moduleName) && !BACKPORTED_PACKAGES.contains(moduleName),
" not have module " + name,
source);
}
}
@Override
public void visitPyArgumentList(final PyArgumentList node) { //PY-5588
if (node.getParent() instanceof PyClass) {
final boolean isPython2 = LanguageLevel.forElement(node).isPython2();
if (isPython2 || myVersionsToProcess.stream().anyMatch(LanguageLevel::isPython2)) {
Arrays
.stream(node.getArguments())
.filter(PyKeywordArgument.class::isInstance)
.forEach(expression -> myHolder.registerProblem(expression,
"This syntax available only since py3",
!isPython2
? ProblemHighlightType.GENERIC_ERROR_OR_WARNING
: ProblemHighlightType.GENERIC_ERROR));
}
}
}
@Override
public void visitPyReferenceExpression(PyReferenceExpression node) {
super.visitPyElement(node);
if (myVersionsToProcess.stream().anyMatch(LanguageLevel::isPy3K)) {
final String nodeText = node.getText();
if (nodeText.endsWith("iteritems") || nodeText.endsWith("iterkeys") || nodeText.endsWith("itervalues")) {
final PyExpression qualifier = node.getQualifier();
if (qualifier != null) {
final TypeEvalContext context = TypeEvalContext.codeAnalysis(node.getProject(), node.getContainingFile());
final PyType type = context.getType(qualifier);
final PyClassType dictType = PyBuiltinCache.getInstance(node).getDictType();
if (PyTypeChecker.match(dictType, type, context)) {
registerProblem(node, "dict.iterkeys(), dict.iteritems() and dict.itervalues() methods are not available in py3");
}
}
}
if (PyNames.BASESTRING.equals(nodeText)) {
final PsiElement res = node.getReference().resolve();
if (res != null) {
final PsiFile file = res.getContainingFile();
if (file != null) {
final VirtualFile virtualFile = file.getVirtualFile();
if (virtualFile != null && ProjectRootManager.getInstance(node.getProject()).getFileIndex().isInLibraryClasses(virtualFile)) {
registerProblem(node, "basestring type is not available in py3");
}
}
else {
registerProblem(node, "basestring type is not available in py3");
}
}
}
}
}
@Override
public void visitPyTargetExpression(PyTargetExpression node) {
super.visitPyTargetExpression(node);
warnAsyncAndAwaitAreBecomingKeywordsInPy37(node);
}
@Override
public void visitPyClass(PyClass node) {
super.visitPyClass(node);
warnAsyncAndAwaitAreBecomingKeywordsInPy37(node);
}
@Override
public void visitPyFunction(PyFunction node) {
super.visitPyFunction(node);
warnAsyncAndAwaitAreBecomingKeywordsInPy37(node);
}
@Override
protected boolean registerForLanguageLevel(@NotNull LanguageLevel level) {
return level != LanguageLevel.forElement(myHolder.getFile());
}
private void warnAsyncAndAwaitAreBecomingKeywordsInPy37(@NotNull PsiNameIdentifierOwner nameIdentifierOwner) {
final PsiElement nameIdentifier = nameIdentifierOwner.getNameIdentifier();
if (nameIdentifier != null &&
ArrayUtil.contains(nameIdentifierOwner.getName(), PyNames.AWAIT, PyNames.ASYNC) &&
LanguageLevel.forElement(nameIdentifierOwner).isOlderThan(LanguageLevel.PYTHON37)) {
registerForAllMatchingVersions(level -> level.isAtLeast(LanguageLevel.PYTHON37),
" not allow 'async' and 'await' as names",
nameIdentifier,
new PyRenameElementQuickFix(nameIdentifierOwner));
}
}
private boolean importedFromCompatibilityLibs(@NotNull PyExpression callee) {
if (callee instanceof PyQualifiedExpression) {
QualifiedName qualifiedName = ((PyQualifiedExpression) callee).asQualifiedName();
return qualifiedName != null && myFromCompatibilityLibs.contains(qualifiedName.getFirstComponent());
}
return myFromCompatibilityLibs.contains(callee.getName());
}
}
}
| |
/******************************************************************************
*
* 2015 (C) Copyright Open-RnD Sp. z o.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 pl.openrnd.connection.rest;
import org.apache.http.HttpResponse;
import org.apache.http.StatusLine;
import org.apache.http.client.CookieStore;
import org.apache.http.client.methods.HttpUriRequest;
import org.apache.http.cookie.Cookie;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import pl.openrnd.connection.rest.request.Request;
import pl.openrnd.connection.rest.response.Response;
/**
* Class containing communication log data.
*/
public class RestConnectionLog extends ConnectionLog implements Serializable {
private String mRequestName;
private String mRequestUri;
private String mRequestMethod;
private String mRequestContent;
private Header[] mRequestHeaders;
private String mResponseContent;
private Header[] mResponseHeaders;
private Integer mResponseStatusCode;
private String mResponseReasonPhrase;
private Exception mResponseException;
private Date mResponseDate;
private ArrayList<String> mCookies;
private RestConnectionLog(Builder builder) {
super(builder.mRequestDate);
mRequestName = builder.mRequestName;
mRequestUri = builder.mRequestUri;
mRequestMethod = builder.mRequestMethod;
mRequestContent = builder.mRequestContent;
mRequestHeaders = builder.mRequestHeaders;
mResponseContent = builder.mResponseContent;
mResponseHeaders = builder.mResponseHeaders;
mResponseStatusCode = builder.mResponseStatusCode;
mResponseReasonPhrase = builder.mResponseReasonPhrase;
mResponseException = builder.mResponseException;
mResponseDate = builder.mResponseDate;
mCookies = builder.mCookie;
}
/**
* Gets request name.
*
* @see pl.openrnd.connection.rest.request.Request
*
* @return Request name or null when not available.
*/
public String getRequestName() {
return mRequestName;
}
/**
* Gets request uri.
*
* @return Request uri as a String object or null when not available.
*/
public String getRequestUri() {
return mRequestUri;
}
/**
* Gets request method (.e.g. POST, GET).
*
* @return Request method or null when not available.
*/
public String getRequestMethod() {
return mRequestMethod;
}
/**
* Gets request content description.
*
* @see pl.openrnd.connection.rest.request.Request
*
* @return Request content description or null when not available.
*/
public String getRequestContent() {
return mRequestContent;
}
/**
* Gets request headers.
*
* @return Request headers or null when not available.
*/
public Header[] getRequestHeaders() {
return mRequestHeaders != null ? mRequestHeaders.clone() : null;
}
/**
* Gets response content description.
*
* @see pl.openrnd.connection.rest.response.Response
*
* @return Response content description or null when not available.
*/
public String getResponseContent() {
return mResponseContent;
}
/**
* Gets server response headers.
*
* @return Server response headers or null when not available.
*/
public Header[] getResponseHeaders() {
return mResponseHeaders != null ? mResponseHeaders.clone() : null;
}
/**
* Gets server response status code.
*
* @return Server response status code or null when not available.
*/
public Integer getResponseStatusCode() {
return mResponseStatusCode;
}
/**
* Gets server response reason phrase.
*
* @return Server response reason phrase or null when not available.
*/
public String getResponseReasonPhrase() {
return mResponseReasonPhrase;
}
/**
* Gets request execution exception.
*
* @return Request execution exception or null when not available.
*/
public Exception getResponseException() {
return mResponseException;
}
/**
* Gets response time.
*
* @return Date object or null when not available.
*/
public Date getResponseDate() {
return mResponseDate != null ? (Date)mResponseDate.clone() : null;
}
/**
* Gets list of cookies.
*
* The list is taken after request execution.
*
* @return List of cookies or null when not available.
*/
public ArrayList<String> getCookies() {
return mCookies;
}
/**
* Gets response time as String object in "yyyy MMM dd HH:mm:ss.SSS" format.
*
* @return Response time as String object or null when not available.
*/
public String getFormattedResponseDate() {
return mResponseDate != null ? sSimpleDateFormat.format(mResponseDate) : null;
}
static class Builder {
private String mRequestName;
private String mRequestUri;
private String mRequestMethod;
private String mRequestContent;
private Header[] mRequestHeaders;
private Date mRequestDate;
private String mResponseContent;
private Header[] mResponseHeaders;
private Integer mResponseStatusCode;
private String mResponseReasonPhrase;
private Exception mResponseException;
private Date mResponseDate;
private ArrayList<String> mCookie;
Builder() {}
Builder cookies(CookieStore cookieStore){
mCookie = null;
if (cookieStore != null) {
List<Cookie> cookies = cookieStore.getCookies();
if (cookies != null) {
int size = cookies.size();
mCookie = new ArrayList<>(size);
for (int i = 0; i < size; ++i) {
mCookie.add(cookies.get(i).toString());
}
}
}
return this;
}
Builder request(HttpUriRequest request) {
mRequestUri = request.getURI().toString();
mRequestMethod = request.getMethod();
mRequestHeaders = createHeaders(request.getAllHeaders());
mRequestDate = Calendar.getInstance().getTime();
return this;
}
Builder response(HttpResponse response) {
mResponseHeaders = createHeaders(response.getAllHeaders());
mResponseDate = Calendar.getInstance().getTime();
StatusLine statusLine = response.getStatusLine();
if (statusLine != null) {
mResponseStatusCode = statusLine.getStatusCode();
mResponseReasonPhrase = statusLine.getReasonPhrase();
}
return this;
}
Builder request(Request request) {
mRequestName = request.getName();
mRequestContent = request.getContentDescription();
return this;
}
Builder response(Response response) {
mResponseException = response.getException();
mResponseContent = response.getContentDescription();
if (mRequestDate == null) {
mResponseDate = Calendar.getInstance().getTime();
}
return this;
}
RestConnectionLog build() {
return new RestConnectionLog(this);
}
}
private static Header[] createHeaders(org.apache.http.Header[] headers) {
Header[] result = null;
if ((headers != null) && (headers.length > 0)) {
result = new Header[headers.length];
for (int i = 0; i < headers.length; ++i) {
org.apache.http.Header header = headers[i];
result[i] = new Header(header.getName(), header.getValue());
}
}
return result;
}
//org.apache.http.Header does not implement Serializable interface
public static class Header implements Serializable {
private static final long serialVersionUID = -4073612454166266286L;
private String mKey;
private String mValue;
public Header(String key, String value) {
mKey = key;
mValue = value;
}
public String getKey() {
return mKey;
}
public String getValue() {
return mValue;
}
}
}
| |
/*
* Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
* or more contributor license agreements. Licensed under the Elastic License;
* you may not use this file except in compliance with the Elastic License.
*/
package org.elasticsearch.xpack.analytics.topmetrics;
import org.apache.lucene.util.PriorityQueue;
import org.elasticsearch.common.Nullable;
import org.elasticsearch.common.io.stream.StreamInput;
import org.elasticsearch.common.io.stream.StreamOutput;
import org.elasticsearch.common.io.stream.Writeable;
import org.elasticsearch.common.xcontent.ToXContent;
import org.elasticsearch.common.xcontent.XContentBuilder;
import org.elasticsearch.search.DocValueFormat;
import org.elasticsearch.search.aggregations.InternalAggregation;
import org.elasticsearch.search.aggregations.metrics.InternalNumericMetricsAggregation;
import org.elasticsearch.search.sort.SortOrder;
import org.elasticsearch.search.sort.SortValue;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import static java.util.Collections.emptyList;
import static org.elasticsearch.search.builder.SearchSourceBuilder.SORT_FIELD;
import static org.elasticsearch.xpack.analytics.topmetrics.TopMetricsAggregationBuilder.METRIC_FIELD;
public class InternalTopMetrics extends InternalNumericMetricsAggregation.MultiValue {
private final SortOrder sortOrder;
private final int size;
private final List<String> metricNames;
private final List<TopMetric> topMetrics;
public InternalTopMetrics(String name, @Nullable SortOrder sortOrder, List<String> metricNames,
int size, List<TopMetric> topMetrics, Map<String, Object> metadata) {
super(name, metadata);
this.sortOrder = sortOrder;
this.metricNames = metricNames;
/*
* topMetrics.size won't be size when the bucket doesn't have size docs!
*/
this.size = size;
this.topMetrics = topMetrics;
}
static InternalTopMetrics buildEmptyAggregation(String name, List<String> metricNames, Map<String, Object> metadata) {
return new InternalTopMetrics(name, SortOrder.ASC, metricNames, 0, emptyList(), metadata);
}
/**
* Read from a stream.
*/
public InternalTopMetrics(StreamInput in) throws IOException {
super(in);
sortOrder = SortOrder.readFromStream(in);
metricNames = in.readStringList();
size = in.readVInt();
topMetrics = in.readList(TopMetric::new);
}
@Override
protected void doWriteTo(StreamOutput out) throws IOException {
sortOrder.writeTo(out);
out.writeStringCollection(metricNames);
out.writeVInt(size);
out.writeList(topMetrics);
}
@Override
public String getWriteableName() {
return TopMetricsAggregationBuilder.NAME;
}
@Override
public Object getProperty(List<String> path) {
if (path.isEmpty()) {
return this;
}
if (path.size() != 1) {
throw new IllegalArgumentException("path not supported for [" + getName() + "]: " + path);
}
int index = metricNames.indexOf(path.get(0));
if (index < 0) {
throw new IllegalArgumentException("path not supported for [" + getName() + "]: " + path);
}
if (topMetrics.isEmpty()) {
// Unmapped.
return null;
}
assert topMetrics.size() == 1 : "property paths should only resolve against top metrics with size == 1.";
MetricValue metric = topMetrics.get(0).metricValues.get(index);
if (metric == null) {
return Double.NaN;
}
return metric.numberValue();
}
@Override
public InternalTopMetrics reduce(List<InternalAggregation> aggregations, ReduceContext reduceContext) {
if (false == isMapped()) {
return this;
}
List<TopMetric> merged = new ArrayList<>(size);
PriorityQueue<ReduceState> queue = new PriorityQueue<ReduceState>(aggregations.size()) {
@Override
protected boolean lessThan(ReduceState lhs, ReduceState rhs) {
return sortOrder.reverseMul() * lhs.sortValue().compareTo(rhs.sortValue()) < 0;
}
};
for (InternalAggregation agg : aggregations) {
InternalTopMetrics result = (InternalTopMetrics) agg;
if (result.isMapped()) {
queue.add(new ReduceState(result));
}
}
while (queue.size() > 0 && merged.size() < size) {
merged.add(queue.top().topMetric());
queue.top().index++;
if (queue.top().result.topMetrics.size() <= queue.top().index) {
queue.pop();
} else {
queue.updateTop();
}
}
return new InternalTopMetrics(getName(), sortOrder, metricNames, size, merged, getMetadata());
}
@Override
public boolean isMapped() {
return false == topMetrics.isEmpty();
}
@Override
public XContentBuilder doXContentBody(XContentBuilder builder, Params params) throws IOException {
builder.startArray("top");
for (TopMetric top : topMetrics) {
top.toXContent(builder, metricNames);
}
builder.endArray();
return builder;
}
@Override
public int hashCode() {
return Objects.hash(super.hashCode(), sortOrder, metricNames, size, topMetrics);
}
@Override
public boolean equals(Object obj) {
if (super.equals(obj) == false) return false;
InternalTopMetrics other = (InternalTopMetrics) obj;
return sortOrder.equals(other.sortOrder) &&
metricNames.equals(other.metricNames) &&
size == other.size &&
topMetrics.equals(other.topMetrics);
}
@Override
public double value(String name) {
int index = metricNames.indexOf(name);
if (index < 0) {
throw new IllegalArgumentException("unknown metric [" + name + "]");
}
if (topMetrics.isEmpty()) {
return Double.NaN;
}
assert topMetrics.size() == 1 : "property paths should only resolve against top metrics with size == 1.";
// TODO it'd probably be nicer to have "compareTo" instead of assuming a double.
return topMetrics.get(0).metricValues.get(index).numberValue().doubleValue();
}
@Override
public Iterable<String> valueNames() {
return metricNames;
}
SortOrder getSortOrder() {
return sortOrder;
}
int getSize() {
return size;
}
List<String> getMetricNames() {
return metricNames;
}
List<TopMetric> getTopMetrics() {
return topMetrics;
}
private class ReduceState {
private final InternalTopMetrics result;
private int index = 0;
ReduceState(InternalTopMetrics result) {
this.result = result;
}
SortValue sortValue() {
return topMetric().sortValue;
}
TopMetric topMetric() {
return result.topMetrics.get(index);
}
}
static class TopMetric implements Writeable, Comparable<TopMetric> {
private final DocValueFormat sortFormat;
private final SortValue sortValue;
private final List<MetricValue> metricValues;
TopMetric(DocValueFormat sortFormat, SortValue sortValue, List<MetricValue> metricValues) {
this.sortFormat = sortFormat;
this.sortValue = sortValue;
this.metricValues = metricValues;
}
TopMetric(StreamInput in) throws IOException {
sortFormat = in.readNamedWriteable(DocValueFormat.class);
sortValue = in.readNamedWriteable(SortValue.class);
metricValues = in.readList(s -> s.readOptionalWriteable(MetricValue::new));
}
@Override
public void writeTo(StreamOutput out) throws IOException {
out.writeNamedWriteable(sortFormat);
out.writeNamedWriteable(sortValue);
out.writeCollection(metricValues, StreamOutput::writeOptionalWriteable);
}
DocValueFormat getSortFormat() {
return sortFormat;
}
SortValue getSortValue() {
return sortValue;
}
List<MetricValue> getMetricValues() {
return metricValues;
}
public XContentBuilder toXContent(XContentBuilder builder, List<String> metricNames) throws IOException {
builder.startObject();
{
builder.startArray(SORT_FIELD.getPreferredName());
sortValue.toXContent(builder, sortFormat);
builder.endArray();
builder.startObject(METRIC_FIELD.getPreferredName());
for (int i = 0; i < metricValues.size(); i++) {
MetricValue value = metricValues.get(i);
builder.field(metricNames.get(i));
if (value == null) {
builder.nullValue();
} else {
value.toXContent(builder, ToXContent.EMPTY_PARAMS);
}
}
builder.endObject();
}
return builder.endObject();
}
@Override
public int compareTo(TopMetric o) {
return sortValue.compareTo(o.sortValue);
}
@Override
public boolean equals(Object obj) {
if (obj == null || obj.getClass() != getClass()) {
return false;
}
TopMetric other = (TopMetric) obj;
return sortFormat.equals(other.sortFormat)
&& sortValue.equals(other.sortValue)
&& metricValues.equals(other.metricValues);
}
@Override
public int hashCode() {
return Objects.hash(sortFormat, sortValue, metricValues);
}
@Override
public String toString() {
return "TopMetric[" + sortFormat + "," + sortValue + "," + metricValues + "]";
}
}
static class MetricValue implements Writeable, ToXContent {
private final DocValueFormat format;
/**
* It is odd to have a "SortValue" be part of a MetricValue but it is
* a very convenient way to send a type-aware thing across the
* wire though. So here we are.
*/
private final SortValue value;
MetricValue(DocValueFormat format, SortValue value) {
this.format = format;
this.value = value;
}
DocValueFormat getFormat() {
return format;
}
SortValue getValue() {
return value;
}
MetricValue(StreamInput in) throws IOException {
format = in.readNamedWriteable(DocValueFormat.class);
value = in.readNamedWriteable(SortValue.class);
}
Number numberValue() {
return value.numberValue();
}
@Override
public void writeTo(StreamOutput out) throws IOException {
out.writeNamedWriteable(format);
out.writeNamedWriteable(value);
}
@Override
public XContentBuilder toXContent(XContentBuilder builder, Params params) throws IOException {
return value.toXContent(builder, format);
}
@Override
public String toString() {
return format + "," + value;
}
@Override
public boolean equals(Object obj) {
if (obj == null || obj.getClass() != getClass()) {
return false;
}
MetricValue other = (MetricValue) obj;
return format.equals(other.format) && value.equals(other.value);
}
@Override
public int hashCode() {
return Objects.hash(format, value);
}
}
}
| |
/**
* Copyright (C) 2008 10gen 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.
*/
/* Generated By:JavaCC: Do not edit this line. ParseException.java Version 4.1 */
/* JavaCCOptions:KEEP_LINE_COL=null */
package ed.db.mql;
/**
* This exception is thrown when parse errors are encountered.
* You can explicitly create objects of this exception type by
* calling the method generateParseException in the generated
* parser.
* <p/>
* You can modify this class to customize your error reporting
* mechanisms so long as you retain the public fields.
*/
public class ParseException extends Exception {
/**
* This constructor is used by the method "generateParseException"
* in the generated parser. Calling this constructor generates
* a new object of this type with the fields "currentToken",
* "expectedTokenSequences", and "tokenImage" set. The boolean
* flag "specialConstructor" is also set to true to indicate that
* this constructor was used to create this object.
* This constructor calls its super class with the empty string
* to force the "toString" method of parent class "Throwable" to
* print the error message in the form:
* ParseException: <result of getMessage>
*/
public ParseException(Token currentTokenVal,
int[][] expectedTokenSequencesVal,
String[] tokenImageVal
) {
super("");
specialConstructor = true;
currentToken = currentTokenVal;
expectedTokenSequences = expectedTokenSequencesVal;
tokenImage = tokenImageVal;
}
/**
* The following constructors are for use by you for whatever
* purpose you can think of. Constructing the exception in this
* manner makes the exception behave in the normal way - i.e., as
* documented in the class "Throwable". The fields "errorToken",
* "expectedTokenSequences", and "tokenImage" do not contain
* relevant information. The JavaCC generated code does not use
* these constructors.
*/
public ParseException() {
super();
specialConstructor = false;
}
/**
* Constructor with message.
*/
public ParseException(String message) {
super(message);
specialConstructor = false;
}
/**
* This variable determines which constructor was used to create
* this object and thereby affects the semantics of the
* "getMessage" method (see below).
*/
protected boolean specialConstructor;
/**
* This is the last token that has been consumed successfully. If
* this object has been created due to a parse error, the token
* followng this token will (therefore) be the first error token.
*/
public Token currentToken;
/**
* Each entry in this array is an array of integers. Each array
* of integers represents a sequence of tokens (by their ordinal
* values) that is expected at this point of the parse.
*/
public int[][] expectedTokenSequences;
/**
* This is a reference to the "tokenImage" array of the generated
* parser within which the parse error occurred. This array is
* defined in the generated ...Constants interface.
*/
public String[] tokenImage;
/**
* This method has the standard behavior when this object has been
* created using the standard constructors. Otherwise, it uses
* "currentToken" and "expectedTokenSequences" to generate a parse
* error message and returns it. If this object has been created
* due to a parse error, and you do not catch it (it gets thrown
* from the parser), then this method is called during the printing
* of the final stack trace, and hence the correct error message
* gets displayed.
*/
public String getMessage() {
if (!specialConstructor) {
return super.getMessage();
}
StringBuffer expected = new StringBuffer();
int maxSize = 0;
for (int i = 0; i < expectedTokenSequences.length; i++) {
if (maxSize < expectedTokenSequences[i].length) {
maxSize = expectedTokenSequences[i].length;
}
for (int j = 0; j < expectedTokenSequences[i].length; j++) {
expected.append(tokenImage[expectedTokenSequences[i][j]]).append(' ');
}
if (expectedTokenSequences[i][expectedTokenSequences[i].length - 1] != 0) {
expected.append("...");
}
expected.append(eol).append(" ");
}
String retval = "Encountered \"";
Token tok = currentToken.next;
for (int i = 0; i < maxSize; i++) {
if (i != 0) retval += " ";
if (tok.kind == 0) {
retval += tokenImage[0];
break;
}
retval += " " + tokenImage[tok.kind];
retval += " \"";
retval += add_escapes(tok.image);
retval += " \"";
tok = tok.next;
}
retval += "\" at line " + currentToken.next.beginLine + ", column " + currentToken.next.beginColumn;
retval += "." + eol;
if (expectedTokenSequences.length == 1) {
retval += "Was expecting:" + eol + " ";
} else {
retval += "Was expecting one of:" + eol + " ";
}
retval += expected.toString();
return retval;
}
/**
* The end of line string for this machine.
*/
protected String eol = System.getProperty("line.separator", "\n");
/**
* Used to convert raw characters to their escaped version
* when these raw version cannot be used as part of an ASCII
* string literal.
*/
protected String add_escapes(String str) {
StringBuffer retval = new StringBuffer();
char ch;
for (int i = 0; i < str.length(); i++) {
switch (str.charAt(i)) {
case 0:
continue;
case '\b':
retval.append("\\b");
continue;
case '\t':
retval.append("\\t");
continue;
case '\n':
retval.append("\\n");
continue;
case '\f':
retval.append("\\f");
continue;
case '\r':
retval.append("\\r");
continue;
case '\"':
retval.append("\\\"");
continue;
case '\'':
retval.append("\\\'");
continue;
case '\\':
retval.append("\\\\");
continue;
default:
if ((ch = str.charAt(i)) < 0x20 || ch > 0x7e) {
String s = "0000" + Integer.toString(ch, 16);
retval.append("\\u" + s.substring(s.length() - 4, s.length()));
} else {
retval.append(ch);
}
continue;
}
}
return retval.toString();
}
}
/* JavaCC - OriginalChecksum=6eeff0be1694ec980f5cfd375ad56614 (do not edit this line) */
| |
/*
Copyright (c) 2017 Ahome' Innovation Technologies. 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.
*/
// TODO - review DSJ
package com.ait.lienzo.client.core.shape;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import com.ait.lienzo.client.core.Attribute;
import com.ait.lienzo.client.core.animation.AnimationProperties;
import com.ait.lienzo.client.core.animation.AnimationProperty;
import com.ait.lienzo.client.core.animation.AnimationTweener;
import com.ait.lienzo.client.core.event.AttributesChangedEvent;
import com.ait.lienzo.client.core.event.AttributesChangedHandler;
import com.ait.lienzo.client.core.event.NodeDragEndEvent;
import com.ait.lienzo.client.core.event.NodeDragEndHandler;
import com.ait.lienzo.client.core.event.NodeDragMoveEvent;
import com.ait.lienzo.client.core.event.NodeDragMoveHandler;
import com.ait.lienzo.client.core.event.NodeDragStartEvent;
import com.ait.lienzo.client.core.event.NodeDragStartHandler;
import com.ait.lienzo.client.core.event.NodeMouseEnterEvent;
import com.ait.lienzo.client.core.event.NodeMouseEnterHandler;
import com.ait.lienzo.client.core.event.NodeMouseExitEvent;
import com.ait.lienzo.client.core.event.NodeMouseExitHandler;
import com.ait.lienzo.client.core.shape.json.validators.ValidationContext;
import com.ait.lienzo.client.core.shape.json.validators.ValidationException;
import com.ait.lienzo.client.core.shape.wires.AbstractControlHandle;
import com.ait.lienzo.client.core.shape.wires.ControlHandleList;
import com.ait.lienzo.client.core.shape.wires.IControlHandle;
import com.ait.lienzo.client.core.shape.wires.IControlHandle.ControlHandleStandardType;
import com.ait.lienzo.client.core.shape.wires.IControlHandle.ControlHandleType;
import com.ait.lienzo.client.core.shape.wires.IControlHandleFactory;
import com.ait.lienzo.client.core.shape.wires.IControlHandleList;
import com.ait.lienzo.client.core.types.PathPartList;
import com.ait.lienzo.client.core.types.Point2D;
import com.ait.lienzo.shared.core.types.ColorName;
import com.ait.lienzo.shared.core.types.DragMode;
import com.ait.lienzo.shared.core.types.ShapeType;
import com.ait.tooling.nativetools.client.event.HandlerRegistrationManager;
import com.google.gwt.json.client.JSONObject;
public abstract class AbstractMultiPointShape<T extends AbstractMultiPointShape<T> & IMultiPointShape<T>> extends Shape<T> implements IMultiPointShape<T>
{
private final PathPartList m_list = new PathPartList();
protected AbstractMultiPointShape(final ShapeType type)
{
super(type);
}
protected AbstractMultiPointShape(final ShapeType type, final JSONObject node, final ValidationContext ctx) throws ValidationException
{
super(type, node, ctx);
}
@Override
public PathPartList getPathPartList()
{
return m_list;
}
@Override
public boolean isControlPointShape()
{
return false;
}
@Override
public IMultiPointShape<?> asMultiPointShape()
{
return this;
}
@Override
public IOffsetMultiPointShape<?> asOffsetMultiPointShape()
{
return null;
}
@Override
public IDirectionalMultiPointShape<?> asDirectionalMultiPointShape()
{
return null;
}
@Override
public IControlHandleFactory getControlHandleFactory()
{
IControlHandleFactory factory = super.getControlHandleFactory();
if (null != factory)
{
return factory;
}
return new DefaultMultiPointShapeHandleFactory(this);
}
@Override
public T refresh()
{
getPathPartList().clear();
return super.refresh();
}
public static final class DefaultMultiPointShapeHandleFactory implements IControlHandleFactory
{
public static final double R0 = 6;
public static final double R1 = 10;
public static final double SELECTION_OFFSET = R0 * 0.5;
private static final double ANIMATION_DURATION = 100;
private final AbstractMultiPointShape<?> m_shape;
private DragMode m_dmode = DragMode.SAME_LAYER;
private DefaultMultiPointShapeHandleFactory(final AbstractMultiPointShape<?> shape)
{
m_shape = shape;
}
@Override
public Map<ControlHandleType, IControlHandleList> getControlHandles(ControlHandleType... types)
{
return getControlHandles(Arrays.asList(types));
}
@Override
public Map<ControlHandleType, IControlHandleList> getControlHandles(final List<ControlHandleType> types)
{
if ((null == types) || (types.isEmpty()))
{
return null;
}
if (false == types.contains(ControlHandleStandardType.POINT) && false == types.contains(ControlHandleStandardType.HANDLE))
{
return null;
}
HashMap<ControlHandleType, IControlHandleList> map = new HashMap<ControlHandleType, IControlHandleList>();
for (ControlHandleType type : types)
{
if (type == ControlHandleStandardType.HANDLE)
{
IControlHandleList chList = getPointHandles();
map.put(IControlHandle.ControlHandleStandardType.HANDLE, chList);
}
else if (type == ControlHandleStandardType.POINT)
{
IControlHandleList chList = getPointHandles();
map.put(IControlHandle.ControlHandleStandardType.POINT, chList);
}
}
return map;
}
private IControlHandleList getPointHandles()
{
final ControlHandleList chlist = new ControlHandleList(m_shape);
HandlerRegistrationManager manager = chlist.getHandlerRegistrationManager();
ShapeXorYChanged shapeXoYChangedHandler = new ShapeXorYChanged(m_shape, chlist);
manager.register(m_shape.addNodeDragStartHandler(shapeXoYChangedHandler));
manager.register(m_shape.addNodeDragMoveHandler(shapeXoYChangedHandler));
manager.register(m_shape.addNodeDragEndHandler(shapeXoYChangedHandler));
for (Point2D point : m_shape.getPoint2DArray())
{
final Point2D p = point;
final Circle prim = new Circle(R0).setX(m_shape.getX() + p.getX()).setY(m_shape.getY() + p.getY()).setFillColor(ColorName.DARKRED).setFillAlpha(0.8).setStrokeAlpha(0).setDraggable(true).setDragMode(m_dmode);
prim.setSelectionStrokeOffset(SELECTION_OFFSET);
prim.setSelectionBoundsOffset(SELECTION_OFFSET);
prim.setFillBoundsForSelection(true);
chlist.add(new AbstractPointControlHandle()
{
@Override
public AbstractPointControlHandle init()
{
ControlXorYChanged handler = new ControlXorYChanged(chlist, m_shape, p, prim, this, m_shape.getLayer());
register(prim.addNodeDragMoveHandler(handler));
register(prim.addNodeDragStartHandler(handler));
register(prim.addNodeDragEndHandler(handler));
register(prim.addNodeMouseEnterHandler(new NodeMouseEnterHandler()
{
@Override
public void onNodeMouseEnter(NodeMouseEnterEvent event)
{
animate(prim, R1);
}
}));
register(prim.addNodeMouseExitHandler(new NodeMouseExitHandler()
{
@Override
public void onNodeMouseExit(NodeMouseExitEvent event)
{
animate(prim, R0);
}
}));
setPoint(p);
return this;
}
@Override
public IPrimitive<?> getControl()
{
return prim;
}
@Override
public void destroy()
{
super.destroy();
}
}.init());
}
return chlist;
}
private static void animate(final Circle circle, final double radius)
{
circle.animate(AnimationTweener.LINEAR, AnimationProperties.toPropertyList(AnimationProperty.Properties.RADIUS(radius)), ANIMATION_DURATION);
}
}
public static class ShapeXorYChanged implements AttributesChangedHandler, NodeDragStartHandler, NodeDragMoveHandler, NodeDragEndHandler
{
private IControlHandleList m_handleList;
private Shape<?> m_shape;
private boolean m_dragging;
public ShapeXorYChanged(Shape<?> shape, IControlHandleList handleList)
{
m_shape = shape;
m_handleList = handleList;
}
@Override
public void onNodeDragMove(NodeDragMoveEvent event)
{
shapeMoved();
}
@Override
public void onNodeDragStart(NodeDragStartEvent event)
{
m_dragging = true;
}
@Override
public void onAttributesChanged(AttributesChangedEvent event)
{
if (!m_dragging && event.all(Attribute.X, Attribute.Y))
{
shapeMoved();
}
}
@Override
public void onNodeDragEnd(NodeDragEndEvent event)
{
m_dragging = false;
}
private void shapeMoved()
{
for (IControlHandle handle : m_handleList)
{
Point2D p = ((AbstractPointControlHandle) handle).getPoint();
handle.getControl().setX(m_shape.getX() + p.getX());
handle.getControl().setY(m_shape.getY() + p.getY());
}
m_shape.getLayer().batch();
}
}
public static class ControlXorYChanged implements NodeDragStartHandler, NodeDragMoveHandler, NodeDragEndHandler
{
private Shape<?> m_prim;
private AbstractPointControlHandle m_handle;
private Point2D m_point;
private IControlHandleList m_handleList;
private Shape<?> m_shape;
private Layer m_layer;
private boolean m_isDragging;
public ControlXorYChanged(IControlHandleList handleList, Shape<?> shape, Point2D point, Shape<?> prim, AbstractPointControlHandle handle, Layer layer)
{
m_handleList = handleList;
m_shape = shape;
m_layer = layer;
m_prim = prim;
m_point = point;
m_handle = handle;
}
public Layer getLayer()
{
return m_layer;
}
public boolean isDragging()
{
return m_isDragging;
}
@Override
public void onNodeDragStart(NodeDragStartEvent event)
{
m_isDragging = true;
if ((m_handle.isActive()) && (m_handleList.isActive()))
{
m_prim.setFillColor(ColorName.GREEN);
m_prim.getLayer().batch();
}
}
@Override
public void onNodeDragEnd(NodeDragEndEvent event)
{
m_isDragging = false;
if ((m_handle.isActive()) && (m_handleList.isActive()))
{
m_prim.setFillColor(ColorName.DARKRED);
m_prim.getLayer().batch();
}
}
@Override
public void onNodeDragMove(NodeDragMoveEvent event)
{
if ((m_handle.isActive()) && (m_handleList.isActive()))
{
m_point.setX(m_prim.getX() - m_shape.getX());
m_point.setY(m_prim.getY() - m_shape.getY());
m_shape.refresh();
m_shape.getLayer().batch();
}
}
}
private static abstract class AbstractPointControlHandle extends AbstractControlHandle
{
private Point2D m_point;
public abstract AbstractPointControlHandle init();
public Point2D getPoint()
{
return m_point;
}
public void setPoint(Point2D point)
{
m_point = point;
}
@Override
public final ControlHandleType getType()
{
return ControlHandleStandardType.POINT;
}
}
}
| |
/*
* Copyright 2010-2016 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.redshift.model;
import java.io.Serializable;
/**
* <p>
* Describes a subnet group.
* </p>
*/
public class ClusterSubnetGroup implements Serializable, Cloneable {
/**
* <p>
* The name of the cluster subnet group.
* </p>
*/
private String clusterSubnetGroupName;
/**
* <p>
* The description of the cluster subnet group.
* </p>
*/
private String description;
/**
* <p>
* The VPC ID of the cluster subnet group.
* </p>
*/
private String vpcId;
/**
* <p>
* The status of the cluster subnet group. Possible values are
* <code>Complete</code>, <code>Incomplete</code> and <code>Invalid</code>.
* </p>
*/
private String subnetGroupStatus;
/**
* <p>
* A list of the VPC <a>Subnet</a> elements.
* </p>
*/
private com.amazonaws.internal.SdkInternalList<Subnet> subnets;
/**
* <p>
* The list of tags for the cluster subnet group.
* </p>
*/
private com.amazonaws.internal.SdkInternalList<Tag> tags;
/**
* <p>
* The name of the cluster subnet group.
* </p>
*
* @param clusterSubnetGroupName
* The name of the cluster subnet group.
*/
public void setClusterSubnetGroupName(String clusterSubnetGroupName) {
this.clusterSubnetGroupName = clusterSubnetGroupName;
}
/**
* <p>
* The name of the cluster subnet group.
* </p>
*
* @return The name of the cluster subnet group.
*/
public String getClusterSubnetGroupName() {
return this.clusterSubnetGroupName;
}
/**
* <p>
* The name of the cluster subnet group.
* </p>
*
* @param clusterSubnetGroupName
* The name of the cluster subnet group.
* @return Returns a reference to this object so that method calls can be
* chained together.
*/
public ClusterSubnetGroup withClusterSubnetGroupName(
String clusterSubnetGroupName) {
setClusterSubnetGroupName(clusterSubnetGroupName);
return this;
}
/**
* <p>
* The description of the cluster subnet group.
* </p>
*
* @param description
* The description of the cluster subnet group.
*/
public void setDescription(String description) {
this.description = description;
}
/**
* <p>
* The description of the cluster subnet group.
* </p>
*
* @return The description of the cluster subnet group.
*/
public String getDescription() {
return this.description;
}
/**
* <p>
* The description of the cluster subnet group.
* </p>
*
* @param description
* The description of the cluster subnet group.
* @return Returns a reference to this object so that method calls can be
* chained together.
*/
public ClusterSubnetGroup withDescription(String description) {
setDescription(description);
return this;
}
/**
* <p>
* The VPC ID of the cluster subnet group.
* </p>
*
* @param vpcId
* The VPC ID of the cluster subnet group.
*/
public void setVpcId(String vpcId) {
this.vpcId = vpcId;
}
/**
* <p>
* The VPC ID of the cluster subnet group.
* </p>
*
* @return The VPC ID of the cluster subnet group.
*/
public String getVpcId() {
return this.vpcId;
}
/**
* <p>
* The VPC ID of the cluster subnet group.
* </p>
*
* @param vpcId
* The VPC ID of the cluster subnet group.
* @return Returns a reference to this object so that method calls can be
* chained together.
*/
public ClusterSubnetGroup withVpcId(String vpcId) {
setVpcId(vpcId);
return this;
}
/**
* <p>
* The status of the cluster subnet group. Possible values are
* <code>Complete</code>, <code>Incomplete</code> and <code>Invalid</code>.
* </p>
*
* @param subnetGroupStatus
* The status of the cluster subnet group. Possible values are
* <code>Complete</code>, <code>Incomplete</code> and
* <code>Invalid</code>.
*/
public void setSubnetGroupStatus(String subnetGroupStatus) {
this.subnetGroupStatus = subnetGroupStatus;
}
/**
* <p>
* The status of the cluster subnet group. Possible values are
* <code>Complete</code>, <code>Incomplete</code> and <code>Invalid</code>.
* </p>
*
* @return The status of the cluster subnet group. Possible values are
* <code>Complete</code>, <code>Incomplete</code> and
* <code>Invalid</code>.
*/
public String getSubnetGroupStatus() {
return this.subnetGroupStatus;
}
/**
* <p>
* The status of the cluster subnet group. Possible values are
* <code>Complete</code>, <code>Incomplete</code> and <code>Invalid</code>.
* </p>
*
* @param subnetGroupStatus
* The status of the cluster subnet group. Possible values are
* <code>Complete</code>, <code>Incomplete</code> and
* <code>Invalid</code>.
* @return Returns a reference to this object so that method calls can be
* chained together.
*/
public ClusterSubnetGroup withSubnetGroupStatus(String subnetGroupStatus) {
setSubnetGroupStatus(subnetGroupStatus);
return this;
}
/**
* <p>
* A list of the VPC <a>Subnet</a> elements.
* </p>
*
* @return A list of the VPC <a>Subnet</a> elements.
*/
public java.util.List<Subnet> getSubnets() {
if (subnets == null) {
subnets = new com.amazonaws.internal.SdkInternalList<Subnet>();
}
return subnets;
}
/**
* <p>
* A list of the VPC <a>Subnet</a> elements.
* </p>
*
* @param subnets
* A list of the VPC <a>Subnet</a> elements.
*/
public void setSubnets(java.util.Collection<Subnet> subnets) {
if (subnets == null) {
this.subnets = null;
return;
}
this.subnets = new com.amazonaws.internal.SdkInternalList<Subnet>(
subnets);
}
/**
* <p>
* A list of the VPC <a>Subnet</a> elements.
* </p>
* <p>
* <b>NOTE:</b> This method appends the values to the existing list (if
* any). Use {@link #setSubnets(java.util.Collection)} or
* {@link #withSubnets(java.util.Collection)} if you want to override the
* existing values.
* </p>
*
* @param subnets
* A list of the VPC <a>Subnet</a> elements.
* @return Returns a reference to this object so that method calls can be
* chained together.
*/
public ClusterSubnetGroup withSubnets(Subnet... subnets) {
if (this.subnets == null) {
setSubnets(new com.amazonaws.internal.SdkInternalList<Subnet>(
subnets.length));
}
for (Subnet ele : subnets) {
this.subnets.add(ele);
}
return this;
}
/**
* <p>
* A list of the VPC <a>Subnet</a> elements.
* </p>
*
* @param subnets
* A list of the VPC <a>Subnet</a> elements.
* @return Returns a reference to this object so that method calls can be
* chained together.
*/
public ClusterSubnetGroup withSubnets(java.util.Collection<Subnet> subnets) {
setSubnets(subnets);
return this;
}
/**
* <p>
* The list of tags for the cluster subnet group.
* </p>
*
* @return The list of tags for the cluster subnet group.
*/
public java.util.List<Tag> getTags() {
if (tags == null) {
tags = new com.amazonaws.internal.SdkInternalList<Tag>();
}
return tags;
}
/**
* <p>
* The list of tags for the cluster subnet group.
* </p>
*
* @param tags
* The list of tags for the cluster subnet group.
*/
public void setTags(java.util.Collection<Tag> tags) {
if (tags == null) {
this.tags = null;
return;
}
this.tags = new com.amazonaws.internal.SdkInternalList<Tag>(tags);
}
/**
* <p>
* The list of tags for the cluster subnet group.
* </p>
* <p>
* <b>NOTE:</b> This method appends the values to the existing list (if
* any). Use {@link #setTags(java.util.Collection)} or
* {@link #withTags(java.util.Collection)} if you want to override the
* existing values.
* </p>
*
* @param tags
* The list of tags for the cluster subnet group.
* @return Returns a reference to this object so that method calls can be
* chained together.
*/
public ClusterSubnetGroup withTags(Tag... tags) {
if (this.tags == null) {
setTags(new com.amazonaws.internal.SdkInternalList<Tag>(tags.length));
}
for (Tag ele : tags) {
this.tags.add(ele);
}
return this;
}
/**
* <p>
* The list of tags for the cluster subnet group.
* </p>
*
* @param tags
* The list of tags for the cluster subnet group.
* @return Returns a reference to this object so that method calls can be
* chained together.
*/
public ClusterSubnetGroup withTags(java.util.Collection<Tag> tags) {
setTags(tags);
return this;
}
/**
* Returns a string representation of this object; useful for testing and
* debugging.
*
* @return A string representation of this object.
*
* @see java.lang.Object#toString()
*/
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("{");
if (getClusterSubnetGroupName() != null)
sb.append("ClusterSubnetGroupName: " + getClusterSubnetGroupName()
+ ",");
if (getDescription() != null)
sb.append("Description: " + getDescription() + ",");
if (getVpcId() != null)
sb.append("VpcId: " + getVpcId() + ",");
if (getSubnetGroupStatus() != null)
sb.append("SubnetGroupStatus: " + getSubnetGroupStatus() + ",");
if (getSubnets() != null)
sb.append("Subnets: " + getSubnets() + ",");
if (getTags() != null)
sb.append("Tags: " + getTags());
sb.append("}");
return sb.toString();
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (obj instanceof ClusterSubnetGroup == false)
return false;
ClusterSubnetGroup other = (ClusterSubnetGroup) obj;
if (other.getClusterSubnetGroupName() == null
^ this.getClusterSubnetGroupName() == null)
return false;
if (other.getClusterSubnetGroupName() != null
&& other.getClusterSubnetGroupName().equals(
this.getClusterSubnetGroupName()) == false)
return false;
if (other.getDescription() == null ^ this.getDescription() == null)
return false;
if (other.getDescription() != null
&& other.getDescription().equals(this.getDescription()) == false)
return false;
if (other.getVpcId() == null ^ this.getVpcId() == null)
return false;
if (other.getVpcId() != null
&& other.getVpcId().equals(this.getVpcId()) == false)
return false;
if (other.getSubnetGroupStatus() == null
^ this.getSubnetGroupStatus() == null)
return false;
if (other.getSubnetGroupStatus() != null
&& other.getSubnetGroupStatus().equals(
this.getSubnetGroupStatus()) == false)
return false;
if (other.getSubnets() == null ^ this.getSubnets() == null)
return false;
if (other.getSubnets() != null
&& other.getSubnets().equals(this.getSubnets()) == false)
return false;
if (other.getTags() == null ^ this.getTags() == null)
return false;
if (other.getTags() != null
&& other.getTags().equals(this.getTags()) == false)
return false;
return true;
}
@Override
public int hashCode() {
final int prime = 31;
int hashCode = 1;
hashCode = prime
* hashCode
+ ((getClusterSubnetGroupName() == null) ? 0
: getClusterSubnetGroupName().hashCode());
hashCode = prime
* hashCode
+ ((getDescription() == null) ? 0 : getDescription().hashCode());
hashCode = prime * hashCode
+ ((getVpcId() == null) ? 0 : getVpcId().hashCode());
hashCode = prime
* hashCode
+ ((getSubnetGroupStatus() == null) ? 0
: getSubnetGroupStatus().hashCode());
hashCode = prime * hashCode
+ ((getSubnets() == null) ? 0 : getSubnets().hashCode());
hashCode = prime * hashCode
+ ((getTags() == null) ? 0 : getTags().hashCode());
return hashCode;
}
@Override
public ClusterSubnetGroup clone() {
try {
return (ClusterSubnetGroup) super.clone();
} catch (CloneNotSupportedException e) {
throw new IllegalStateException(
"Got a CloneNotSupportedException from Object.clone() "
+ "even though we're Cloneable!", e);
}
}
}
| |
/*
* 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.
*/
import java.awt.Desktop;
import java.awt.GraphicsDevice;
import java.awt.GraphicsEnvironment;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.imageio.ImageIO;
import javax.swing.ImageIcon;
/**
*
* @author FeepFoop
*/
public class Market2_1 extends javax.swing.JFrame implements KeyListener{
/**
* Creates new form Market2
*/
public Market2_1() {
initComponents();
jLayeredPane2.setVisible(false);
jLayeredPane3.setVisible(false);
jLayeredPane5.setVisible(false);
jLayeredPane4.setVisible(false);
}
/**
* 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() {
jLayeredPane2 = new javax.swing.JLayeredPane();
jButton3 = new javax.swing.JButton();
jTextField1 = new javax.swing.JTextField();
jLabel1 = new javax.swing.JLabel();
jLabel2 = new javax.swing.JLabel();
jLabel3 = new javax.swing.JLabel();
jTextField2 = new javax.swing.JTextField();
jLabel5 = new javax.swing.JLabel();
jLayeredPane5 = new javax.swing.JLayeredPane();
jLabel4 = new javax.swing.JLabel();
jLabel9 = new javax.swing.JLabel();
jLabel10 = new javax.swing.JLabel();
jButton5 = new javax.swing.JButton();
jButton6 = new javax.swing.JButton();
jButton7 = new javax.swing.JButton();
jLabel11 = new javax.swing.JLabel();
jLayeredPane3 = new javax.swing.JLayeredPane();
jButton1 = new javax.swing.JButton();
jLabel6 = new javax.swing.JLabel();
jLabel8 = new javax.swing.JLabel();
jLayeredPane1 = new javax.swing.JLayeredPane();
jButton2 = new javax.swing.JButton();
jLabel7 = new javax.swing.JLabel();
jLayeredPane4 = new javax.swing.JLayeredPane();
jButton4 = new javax.swing.JButton();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
jButton3.setText("Ok");
jButton3.setBorderPainted(false);
jButton3.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton3ActionPerformed(evt);
}
});
jTextField1.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jTextField1ActionPerformed(evt);
}
});
jLabel1.setText("Path Varible:");
jLabel2.setText("Upload Video");
jLabel3.setText("Recording Time:");
javax.swing.GroupLayout jLayeredPane2Layout = new javax.swing.GroupLayout(jLayeredPane2);
jLayeredPane2.setLayout(jLayeredPane2Layout);
jLayeredPane2Layout.setHorizontalGroup(
jLayeredPane2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jLayeredPane2Layout.createSequentialGroup()
.addGroup(jLayeredPane2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jLayeredPane2Layout.createSequentialGroup()
.addGap(263, 263, 263)
.addComponent(jButton3))
.addGroup(jLayeredPane2Layout.createSequentialGroup()
.addComponent(jLabel5)
.addGroup(jLayeredPane2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jLayeredPane2Layout.createSequentialGroup()
.addGap(149, 149, 149)
.addComponent(jLabel2))
.addGroup(jLayeredPane2Layout.createSequentialGroup()
.addGap(20, 20, 20)
.addGroup(jLayeredPane2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addGroup(jLayeredPane2Layout.createSequentialGroup()
.addComponent(jLabel1)
.addGap(18, 18, 18)
.addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, 335, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(jLayeredPane2Layout.createSequentialGroup()
.addComponent(jLabel3)
.addGap(18, 18, 18)
.addComponent(jTextField2)))))))
.addContainerGap(197, Short.MAX_VALUE))
);
jLayeredPane2Layout.setVerticalGroup(
jLayeredPane2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jLayeredPane2Layout.createSequentialGroup()
.addGroup(jLayeredPane2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jLayeredPane2Layout.createSequentialGroup()
.addGap(42, 42, 42)
.addComponent(jLabel2)
.addGap(26, 26, 26)
.addGroup(jLayeredPane2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel1)
.addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addComponent(jLabel5, javax.swing.GroupLayout.PREFERRED_SIZE, 106, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(27, 27, 27)
.addComponent(jButton3)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 91, Short.MAX_VALUE)
.addGroup(jLayeredPane2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel3)
.addComponent(jTextField2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(95, 95, 95))
);
jLayeredPane2.setLayer(jButton3, javax.swing.JLayeredPane.DEFAULT_LAYER);
jLayeredPane2.setLayer(jTextField1, javax.swing.JLayeredPane.DEFAULT_LAYER);
jLayeredPane2.setLayer(jLabel1, javax.swing.JLayeredPane.DEFAULT_LAYER);
jLayeredPane2.setLayer(jLabel2, javax.swing.JLayeredPane.DEFAULT_LAYER);
jLayeredPane2.setLayer(jLabel3, javax.swing.JLayeredPane.DEFAULT_LAYER);
jLayeredPane2.setLayer(jTextField2, javax.swing.JLayeredPane.DEFAULT_LAYER);
jLayeredPane2.setLayer(jLabel5, javax.swing.JLayeredPane.DEFAULT_LAYER);
jLabel4.setText("jLabel4");
jLabel9.setText("jLabel9");
jLabel10.setText("jLabel10");
jButton5.setIcon(new javax.swing.ImageIcon(getClass().getResource("/market/Button.png"))); // NOI18N
jButton5.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton5ActionPerformed(evt);
}
});
jButton6.setIcon(new javax.swing.ImageIcon(getClass().getResource("/market/Button.png"))); // NOI18N
jButton7.setIcon(new javax.swing.ImageIcon(getClass().getResource("/market/Button.png"))); // NOI18N
jLabel11.setFont(new java.awt.Font("Lucida Grande", 0, 18)); // NOI18N
jLabel11.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
jLabel11.setText("Please Select The Picture You Would Like To View");
javax.swing.GroupLayout jLayeredPane5Layout = new javax.swing.GroupLayout(jLayeredPane5);
jLayeredPane5.setLayout(jLayeredPane5Layout);
jLayeredPane5Layout.setHorizontalGroup(
jLayeredPane5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jLayeredPane5Layout.createSequentialGroup()
.addContainerGap()
.addGroup(jLayeredPane5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel11, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addGroup(jLayeredPane5Layout.createSequentialGroup()
.addGroup(jLayeredPane5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel4, javax.swing.GroupLayout.PREFERRED_SIZE, 197, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGroup(jLayeredPane5Layout.createSequentialGroup()
.addGap(41, 41, 41)
.addComponent(jButton7)))
.addGroup(jLayeredPane5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jLayeredPane5Layout.createSequentialGroup()
.addGap(18, 18, 18)
.addComponent(jLabel9, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED))
.addGroup(jLayeredPane5Layout.createSequentialGroup()
.addGap(58, 58, 58)
.addComponent(jButton5)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 92, Short.MAX_VALUE)))
.addGroup(jLayeredPane5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel10, javax.swing.GroupLayout.PREFERRED_SIZE, 203, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jLayeredPane5Layout.createSequentialGroup()
.addComponent(jButton6)
.addGap(58, 58, 58)))))
.addContainerGap())
);
jLayeredPane5Layout.setVerticalGroup(
jLayeredPane5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jLayeredPane5Layout.createSequentialGroup()
.addContainerGap()
.addComponent(jLabel11, javax.swing.GroupLayout.PREFERRED_SIZE, 28, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addGroup(jLayeredPane5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(jLabel4, javax.swing.GroupLayout.DEFAULT_SIZE, 224, Short.MAX_VALUE)
.addComponent(jLabel10, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jLabel9, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
.addGroup(jLayeredPane5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jLayeredPane5Layout.createSequentialGroup()
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jButton7)
.addContainerGap())
.addGroup(jLayeredPane5Layout.createSequentialGroup()
.addGap(34, 34, 34)
.addGroup(jLayeredPane5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jLayeredPane5Layout.createSequentialGroup()
.addComponent(jButton6, javax.swing.GroupLayout.PREFERRED_SIZE, 0, Short.MAX_VALUE)
.addContainerGap())
.addGroup(jLayeredPane5Layout.createSequentialGroup()
.addComponent(jButton5, javax.swing.GroupLayout.PREFERRED_SIZE, 72, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))))))
);
jLayeredPane5.setLayer(jLabel4, javax.swing.JLayeredPane.DEFAULT_LAYER);
jLayeredPane5.setLayer(jLabel9, javax.swing.JLayeredPane.DEFAULT_LAYER);
jLayeredPane5.setLayer(jLabel10, javax.swing.JLayeredPane.DEFAULT_LAYER);
jLayeredPane5.setLayer(jButton5, javax.swing.JLayeredPane.DEFAULT_LAYER);
jLayeredPane5.setLayer(jButton6, javax.swing.JLayeredPane.DEFAULT_LAYER);
jLayeredPane5.setLayer(jButton7, javax.swing.JLayeredPane.DEFAULT_LAYER);
jLayeredPane5.setLayer(jLabel11, javax.swing.JLayeredPane.DEFAULT_LAYER);
jButton1.setText("New Test");
jButton1.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton1ActionPerformed(evt);
}
});
jLabel6.setText("jLabel6");
jLabel8.setText("jLabel8");
javax.swing.GroupLayout jLayeredPane3Layout = new javax.swing.GroupLayout(jLayeredPane3);
jLayeredPane3.setLayout(jLayeredPane3Layout);
jLayeredPane3Layout.setHorizontalGroup(
jLayeredPane3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jLayeredPane3Layout.createSequentialGroup()
.addGap(98, 98, 98)
.addComponent(jLabel6)
.addGap(116, 116, 116)
.addGroup(jLayeredPane3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jLayeredPane3Layout.createSequentialGroup()
.addGap(0, 202, Short.MAX_VALUE)
.addComponent(jLabel8)
.addGap(142, 142, 142))
.addGroup(jLayeredPane3Layout.createSequentialGroup()
.addComponent(jButton1)
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))))
);
jLayeredPane3Layout.setVerticalGroup(
jLayeredPane3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jLayeredPane3Layout.createSequentialGroup()
.addGap(139, 139, 139)
.addGroup(jLayeredPane3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel8)
.addComponent(jLabel6))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 192, Short.MAX_VALUE)
.addComponent(jButton1)
.addContainerGap())
);
jLayeredPane3.setLayer(jButton1, javax.swing.JLayeredPane.DEFAULT_LAYER);
jLayeredPane3.setLayer(jLabel6, javax.swing.JLayeredPane.DEFAULT_LAYER);
jLayeredPane3.setLayer(jLabel8, javax.swing.JLayeredPane.DEFAULT_LAYER);
jButton2.setIcon(new javax.swing.ImageIcon(getClass().getResource("/market/Button.png"))); // NOI18N
jButton2.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton2ActionPerformed(evt);
}
});
javax.swing.GroupLayout jLayeredPane1Layout = new javax.swing.GroupLayout(jLayeredPane1);
jLayeredPane1.setLayout(jLayeredPane1Layout);
jLayeredPane1Layout.setHorizontalGroup(
jLayeredPane1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jLayeredPane1Layout.createSequentialGroup()
.addGap(187, 187, 187)
.addComponent(jLabel7)
.addContainerGap(473, Short.MAX_VALUE))
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jLayeredPane1Layout.createSequentialGroup()
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jButton2)
.addGap(43, 43, 43))
);
jLayeredPane1Layout.setVerticalGroup(
jLayeredPane1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jLayeredPane1Layout.createSequentialGroup()
.addContainerGap()
.addComponent(jLabel7)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 270, Short.MAX_VALUE)
.addComponent(jButton2)
.addGap(36, 36, 36))
);
jLayeredPane1.setLayer(jButton2, javax.swing.JLayeredPane.DEFAULT_LAYER);
jLayeredPane1.setLayer(jLabel7, javax.swing.JLayeredPane.DEFAULT_LAYER);
jButton4.setText("Stop");
jButton4.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton4ActionPerformed(evt);
}
});
javax.swing.GroupLayout jLayeredPane4Layout = new javax.swing.GroupLayout(jLayeredPane4);
jLayeredPane4.setLayout(jLayeredPane4Layout);
jLayeredPane4Layout.setHorizontalGroup(
jLayeredPane4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 648, Short.MAX_VALUE)
.addGroup(jLayeredPane4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jLayeredPane4Layout.createSequentialGroup()
.addGap(263, 263, 263)
.addComponent(jButton4)
.addContainerGap(310, Short.MAX_VALUE)))
);
jLayeredPane4Layout.setVerticalGroup(
jLayeredPane4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 382, Short.MAX_VALUE)
.addGroup(jLayeredPane4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jLayeredPane4Layout.createSequentialGroup()
.addGap(167, 167, 167)
.addComponent(jButton4)
.addContainerGap(186, Short.MAX_VALUE)))
);
jLayeredPane4.setLayer(jButton4, javax.swing.JLayeredPane.DEFAULT_LAYER);
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLayeredPane1)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addContainerGap()
.addComponent(jLayeredPane3)
.addContainerGap()))
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addComponent(jLayeredPane2)
.addContainerGap()))
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addComponent(jLayeredPane5)
.addContainerGap()))
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addContainerGap()
.addComponent(jLayeredPane4)
.addContainerGap()))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLayeredPane1)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addComponent(jLayeredPane3)
.addContainerGap()))
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addComponent(jLayeredPane2)
.addContainerGap()))
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addComponent(jLayeredPane5)
.addContainerGap()))
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addComponent(jLayeredPane4)
.addContainerGap()))
);
pack();
}// </editor-fold>//GEN-END:initComponents
public void newScreen(int i)
{
try{
Thread.sleep(i*1000);
}catch(Exception e)
{
}
jLayeredPane2.setVisible(false);
jLayeredPane3.setVisible(true);
jLayeredPane1.setVisible(false);
}
public void makeImage(File f)
{
jLayeredPane5.setVisible(true);
jLabel9.setText(null);
//jLabel9.setIcon(new javax.swing.ImageIcon(getClass().getResource(f.toString())));
String imagePath = f.toString();
ImageIcon ii = new ImageIcon(imagePath);
jLabel9.setIcon(ii);
gd.setFullScreenWindow(this);
this.setUndecorated(true);
}
private void jButton3ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton3ActionPerformed
File f = new File(jTextField1.getText());
try {
makeImage(f);
jLayeredPane3.setVisible(false);
jLayeredPane5.setVisible(true);
jLayeredPane2.setVisible(false);
jLayeredPane1.setVisible(false);
}catch(Exception e)
{
System.out.println("haha");
}
}//GEN-LAST:event_jButton3ActionPerformed
private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton2ActionPerformed
jLayeredPane5.setVisible(true);
jLayeredPane1.setVisible(false);
}//GEN-LAST:event_jButton2ActionPerformed
private void jTextField1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jTextField1ActionPerformed
// TODO add your handling code here:
}//GEN-LAST:event_jTextField1ActionPerformed
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
jLayeredPane2.setVisible(false);
jLayeredPane1.setVisible(true);
jLayeredPane3.setVisible(false);
}//GEN-LAST:event_jButton1ActionPerformed
private void jButton4ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton4ActionPerformed
jLayeredPane2.setVisible(false);
jLayeredPane1.setVisible(false);
jLayeredPane4.setVisible(false);
jLayeredPane3.setVisible(true);
}//GEN-LAST:event_jButton4ActionPerformed
private void jButton5ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton5ActionPerformed
// TODO add your handling code here:
}//GEN-LAST:event_jButton5ActionPerformed
/**
* @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(Market2.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(Market2.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(Market2.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(Market2.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new Market2_1().setVisible(true);
}
});
}
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JButton jButton1;
private javax.swing.JButton jButton2;
private javax.swing.JButton jButton3;
private javax.swing.JButton jButton4;
private javax.swing.JButton jButton5;
private javax.swing.JButton jButton6;
private javax.swing.JButton jButton7;
private javax.swing.JLabel jLabel1;
private javax.swing.JLabel jLabel10;
private javax.swing.JLabel jLabel11;
private javax.swing.JLabel jLabel2;
private javax.swing.JLabel jLabel3;
private javax.swing.JLabel jLabel4;
private javax.swing.JLabel jLabel5;
private javax.swing.JLabel jLabel6;
private javax.swing.JLabel jLabel7;
private javax.swing.JLabel jLabel8;
private javax.swing.JLabel jLabel9;
private javax.swing.JLayeredPane jLayeredPane1;
private javax.swing.JLayeredPane jLayeredPane2;
private javax.swing.JLayeredPane jLayeredPane3;
private javax.swing.JLayeredPane jLayeredPane4;
private javax.swing.JLayeredPane jLayeredPane5;
private javax.swing.JTextField jTextField1;
private javax.swing.JTextField jTextField2;
// End of variables declaration//GEN-END:variables
@Override
public void keyTyped(KeyEvent e) {
if(e.getKeyCode() == KeyEvent.VK_ESCAPE)
{
this.setUndecorated(true);
}
}
@Override
public void keyPressed(KeyEvent e) {
if(e.getKeyCode() == KeyEvent.VK_ESCAPE)
{
this.setUndecorated(true);
}
}
@Override
public void keyReleased(KeyEvent e) {
if(e.getKeyCode() == KeyEvent.VK_ESCAPE)
{
this.setUndecorated(true);
System.out.println("HAHA");
}
}
GraphicsDevice gd = GraphicsEnvironment.getLocalGraphicsEnvironment().getDefaultScreenDevice();
}
| |
/*
Copyright 2007-2010 Selenium committers
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.openqa.selenium.net;
import static org.openqa.selenium.net.NetworkInterface.isIpv6;
import org.openqa.selenium.Platform;
import org.openqa.selenium.WebDriverException;
import java.net.Inet6Address;
import java.net.InetAddress;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
public class NetworkUtils {
private final NetworkInterfaceProvider networkInterfaceProvider;
NetworkUtils(NetworkInterfaceProvider networkInterfaceProvider) {
this.networkInterfaceProvider = networkInterfaceProvider;
}
public NetworkUtils() {
this(new DefaultNetworkInterfaceProvider());
}
public String getPrivateLocalAddress() {
List<InetAddress> addresses = getLocalInterfaceAddress();
if (addresses.isEmpty()) {
return "127.0.0.1";
}
return addresses.get(0).getHostAddress();
}
/**
* Used by the mobile emulators that refuse to access localhost or 127.0.0.1 The IP4/IP6
* requirements of this method are as-of-yet unspecified, but we return the string that is
* associated with the IP4 interface
*
* @return A String representing the host name or non-loopback IP4 address of this machine.
*/
public String getNonLoopbackAddressOfThisMachine() {
return getIp4NonLoopbackAddressOfThisMachine().getHostName();
}
/**
* Returns a non-loopback IP4 hostname of the local host.
*
* @return A string hostName
*/
public InetAddress getIp4NonLoopbackAddressOfThisMachine() {
for (NetworkInterface iface : networkInterfaceProvider.getNetworkInterfaces()) {
final InetAddress ip4NonLoopback = iface.getIp4NonLoopBackOnly();
if (ip4NonLoopback != null) {
return ip4NonLoopback;
}
}
throw new WebDriverException("Could not find a non-loopback ip4 address for this machine");
}
/**
* Returns a single address that is guaranteed to resolve to an ipv4 representation of localhost
* This may either be a hostname or an ip address, dependending if we can guarantee what that the
* hostname will resolve to ip4.
*
* @return The address part og such an address
*/
public String obtainLoopbackIp4Address() {
final NetworkInterface networkInterface = getLoopBackAndIp4Only();
if (networkInterface != null) {
return networkInterface.getIp4LoopbackOnly().getHostName();
}
final String ipOfIp4LoopBack = getIpOfLoopBackIp4();
if (ipOfIp4LoopBack != null) {
return ipOfIp4LoopBack;
}
if (Platform.getCurrent().is(Platform.UNIX)) {
NetworkInterface linuxLoopback = networkInterfaceProvider.getLoInterface();
if (linuxLoopback != null) {
final InetAddress netAddress = linuxLoopback.getIp4LoopbackOnly();
if (netAddress != null) {
return netAddress.getHostAddress();
}
}
}
throw new WebDriverException(
"Unable to resolve local loopback address, please file an issue with the full message of this error:\n"
+
getNetWorkDiags() + "\n==== End of error message");
}
private InetAddress grabFirstNetworkAddress() {
NetworkInterface firstInterface =
networkInterfaceProvider.getNetworkInterfaces().iterator().next();
InetAddress firstAddress = null;
if (firstInterface != null) {
firstAddress = firstInterface.getInetAddresses().iterator().next();
}
if (firstAddress == null) {
throw new WebDriverException("Unable to find any network address for localhost");
}
return firstAddress;
}
public String getIpOfLoopBackIp4() {
for (NetworkInterface iface : networkInterfaceProvider.getNetworkInterfaces()) {
final InetAddress netAddress = iface.getIp4LoopbackOnly();
if (netAddress != null) {
return netAddress.getHostAddress();
}
}
return null;
}
private NetworkInterface getLoopBackAndIp4Only() {
for (NetworkInterface iface : networkInterfaceProvider.getNetworkInterfaces()) {
if (iface.isIp4AddressBindingOnly() && iface.isLoopBack()) {
return iface;
}
}
return null;
}
private List<InetAddress> getLocalInterfaceAddress() {
List<InetAddress> localAddresses = new ArrayList<InetAddress>();
for (NetworkInterface iface : networkInterfaceProvider.getNetworkInterfaces()) {
for (InetAddress addr : iface.getInetAddresses()) {
// filter out Inet6 Addr Entries
if (addr.isLoopbackAddress() && !isIpv6(addr)) {
localAddresses.add(addr);
}
}
}
// On linux, loopback addresses are named "lo". See if we can find that. We do this
// craziness because sometimes the loopback device is given an IP range that falls outside
// of 127/24
if (Platform.getCurrent().is(Platform.UNIX)) {
NetworkInterface linuxLoopback = networkInterfaceProvider.getLoInterface();
if (linuxLoopback != null) {
for (InetAddress inetAddress : linuxLoopback.getInetAddresses()) {
if (!isIpv6(inetAddress)) {
localAddresses.add(inetAddress);
}
}
}
}
if (localAddresses.isEmpty()) {
return Collections.singletonList(grabFirstNetworkAddress());
}
return localAddresses;
}
public static String getNetWorkDiags() {
StringBuilder result = new StringBuilder();
DefaultNetworkInterfaceProvider defaultNetworkInterfaceProvider =
new DefaultNetworkInterfaceProvider();
for (NetworkInterface networkInterface : defaultNetworkInterfaceProvider
.getNetworkInterfaces()) {
dumpToConsole(result, networkInterface);
}
NetworkInterface byName = defaultNetworkInterfaceProvider.getLoInterface();
if (byName != null) {
result.append("Loopback interface LO:\n");
dumpToConsole(result, byName);
}
return result.toString();
}
private static void dumpToConsole(StringBuilder result, NetworkInterface inNetworkInterface) {
if (inNetworkInterface == null) {
return;
}
result.append(inNetworkInterface.getName());
result.append("\n");
dumpAddresses(result, inNetworkInterface.getInetAddresses());
}
private static void dumpAddresses(StringBuilder result, Iterable<InetAddress> inetAddresses) {
for (InetAddress address : inetAddresses) {
result.append(" address.getHostName() = ");
result.append(address.getHostName());
result.append("\n");
result.append(" address.getHostAddress() = ");
result.append(address.getHostAddress());
result.append("\n");
result.append(" address.isLoopbackAddress() = ");
result.append(address.isLoopbackAddress());
result.append("\n");
}
}
@SuppressWarnings({"UseOfSystemOutOrSystemErr"})
public static void main(String[] args) {
System.out.println(getNetWorkDiags());
}
}
| |
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package Gemstone;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.lang.reflect.InvocationTargetException;
import java.util.Collection;
import java.util.Collections;
import java.util.LinkedHashMap;
import java.util.LinkedHashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.SortedMap;
import java.util.SortedSet;
import java.util.TreeMap;
import java.util.TreeSet;
import org.apache.log4j.Logger;
import sagex.UIContext;
/**
*
* @author jusjoken
*/
public class ADMAction {
static private final Logger LOG = Logger.getLogger(ADMAction.class);
private static final String Blank = "admActionBlank";
private static final String VarNull = "VarNull";
private static final String SageADMCustomActionsPropertyLocation = "ADM/custom_actions";
private static final String ActionCategoryFilterPropertyLocation = "ADM/action_category/filter";
private static final String ActionCategoryFilterStickyPropertyLocation = "ADM/action_category/sticky";
private static final String UseAttributeValue = "UseAttributeValue";
private static final String UseAttributeObjectValue = "UseAttributeObjectValue";
private static final String StandardActionListFile = "ADMStandardActions.properties";
public static Map<String,CustomAction> SageMenuActions = new LinkedHashMap<String,CustomAction>();
public static Map<String,String> SageTVRecordingViews = new LinkedHashMap<String,String>();
public static Map<String,String> DynamicLists = new LinkedHashMap<String,String>();
public static final String SageTVRecordingViewsTitlePropertyLocation = "sagetv_recordings/view_title/";
private String Type = "";
private String ButtonText = "";
private String DefaultIcon = "";
private String Attribute = Blank;
private String WidgetSymbol = Blank;
private String FieldTitle = "";
private static final ActionVariable BlankActionVariable = new ActionVariable(Blank, Blank, Blank);
private ActionVariable EvalExpression = BlankActionVariable;
private List<ActionVariable> ActionVariables = new LinkedList<ActionVariable>();
private List<String> ActionCategories = new LinkedList<String>();
private static final String VarTypeGlobal = "VarTypeGlobal";
private static final String VarTypeStatic = "VarTypeStatic";
private static final String VarTypeSetProp = "VarTypeSetProp";
private Boolean AdvancedOnly = Boolean.FALSE;
private Boolean InternalOnly = Boolean.FALSE;
private static Map<String,ADMAction> ActionList = new LinkedHashMap<String,ADMAction>();
public static final String WidgetbySymbol = "ExecuteWidget";
public static final String BrowseVideoFolder = "ExecuteBrowseVideoFolder";
public static final String StandardMenuAction = "ExecuteStandardMenuAction";
public static final String TVRecordingView = "ExecuteTVRecordingView";
public static final String GemstoneFlow = "ExecuteGemstoneFlow";
public static final String BrowseFileFolderLocal = "ExecuteBrowseFileFolderLocal";
public static final String BrowseFileFolderServer = "ExecuteBrowseFileFolderServer";
public static final String BrowseFileFolderImports = "ExecuteBrowseFileFolderImports";
public static final String BrowseFileFolderRecDir = "ExecuteBrowseFileFolderRecDir";
public static final String BrowseFileFolderNetwork = "ExecuteBrowseFileFolderNetwork";
public static final String LaunchExternalApplication = "LaunchExternalApplication";
public static final String LaunchPlayList = "LaunchPlayList";
public static final String DynamicList = "AddDynamicList";
public static final String ActionTypeDefault = "DoNothing";
public static final String DynamicTVRecordingsList = "admDynamicTVRecordingsList";
public static final String DynamicVideoPlaylist = "admDynamicVideoPlaylist";
public static final String DynamicMusicPlaylist = "admDynamicMusicPlaylist";
public static final String DynamicGemstoneFlows = "admDynamicGemstoneFlows";
public static final String ActionCategoryShowAll = "admActionCategoryShowAll";
public static final String ActionCategoryOther = "Other (no category)";
public static enum ActionCats {Video,TV,Gemstone,Music};
public ADMAction(String Type, Boolean AdvancedOnly, String ButtonText){
this(Type,AdvancedOnly,ButtonText,"Action",Blank);
}
public ADMAction(String Type, Boolean AdvancedOnly, String ButtonText, String FieldTitle){
this(Type,AdvancedOnly,ButtonText,FieldTitle,Blank);
}
public ADMAction(String Type, Boolean AdvancedOnly, String ButtonText, String FieldTitle, String WidgetSymbol){
this.Type = Type;
this.AdvancedOnly = AdvancedOnly;
this.ButtonText = ButtonText;
this.FieldTitle = FieldTitle;
this.WidgetSymbol = WidgetSymbol;
}
public static void Init(){
LOG.debug("Init: Menu Manager Action Init started: " + util.LogInfo());
//Clear existing Actions if any
ActionList.clear();
//Create the Actions for ADM to use
ActionList.put(ActionTypeDefault, new ADMAction(ActionTypeDefault,Boolean.FALSE,"None"));
ActionList.put(WidgetbySymbol, new ADMAction(WidgetbySymbol,Boolean.TRUE,"Execute Widget by Symbol", "Action"));
ActionList.put(BrowseVideoFolder, new ADMAction(BrowseVideoFolder,Boolean.FALSE,"Video Browser with specific Folder","Video Browser Folder","OPUS4A-174637"));
ActionList.get(BrowseVideoFolder).ActionVariables.add(new ActionVariable(VarTypeGlobal,"gCurrentVideoBrowserFolder", UseAttributeValue));
ActionList.get(BrowseVideoFolder).ActionCategories.add(ActionCats.Video.toString());
ActionList.put(StandardMenuAction, new ADMAction(StandardMenuAction,Boolean.FALSE,"Execute Standard Sage Menu Action", "Standard Action"));
ActionList.put(TVRecordingView, new ADMAction(TVRecordingView,Boolean.FALSE,"Launch Specific TV Recordings View", "TV Recordings View","OPUS4A-174116"));
ActionList.get(TVRecordingView).ActionVariables.add(new ActionVariable(VarTypeGlobal,"ViewFilter", UseAttributeValue));
ActionList.get(TVRecordingView).ActionCategories.add(ActionCats.TV.toString());
ActionList.put(DynamicList, new ADMAction(DynamicList,Boolean.FALSE,"Dynamic List Item", "Dynamic List Type"));
ActionList.put(DynamicTVRecordingsList, new ADMAction(DynamicTVRecordingsList,Boolean.FALSE,"DynamicTVRecordingsList", "DynamicTVRecordingsList"));
ActionList.get(DynamicTVRecordingsList).InternalOnly = Boolean.TRUE;
ActionList.put(DynamicVideoPlaylist, new ADMAction(DynamicVideoPlaylist,Boolean.FALSE,"DynamicVideoPlaylist", "DynamicVideoPlaylist"));
ActionList.get(DynamicVideoPlaylist).InternalOnly = Boolean.TRUE;
ActionList.put(DynamicMusicPlaylist, new ADMAction(DynamicMusicPlaylist,Boolean.FALSE,"DynamicMusicPlaylist", "DynamicMusicPlaylist"));
ActionList.get(DynamicMusicPlaylist).InternalOnly = Boolean.TRUE;
ActionList.put(DynamicGemstoneFlows, new ADMAction(DynamicGemstoneFlows,Boolean.FALSE,"DynamicGemstoneFlows", "DynamicGemstoneFlows"));
ActionList.get(DynamicGemstoneFlows).InternalOnly = Boolean.TRUE;
ActionList.put(LaunchPlayList, new ADMAction(LaunchPlayList,Boolean.FALSE,"LaunchPlayList", "LaunchPlayList","OPUS4A-183733"));
ActionList.get(LaunchPlayList).InternalOnly = Boolean.TRUE;
ActionList.get(LaunchPlayList).ActionVariables.add(new ActionVariable(VarTypeGlobal,"PlaylistItem", UseAttributeObjectValue));
ActionList.get(LaunchPlayList).ActionVariables.add(new ActionVariable(VarTypeGlobal,"BasePlaylistUnit", UseAttributeValue));
ActionList.put(GemstoneFlow, new ADMAction(GemstoneFlow,Boolean.FALSE,"Gemstone Flow", "Gemstone Flow","AOSCS-679216"));
ActionList.get(GemstoneFlow).ActionVariables.add(new ActionVariable(VarTypeGlobal,"ViewCell", UseAttributeValue));
ActionList.get(GemstoneFlow).ActionCategories.add(ActionCats.Video.toString());
ActionList.get(GemstoneFlow).ActionCategories.add(ActionCats.TV.toString());
ActionList.get(GemstoneFlow).ActionCategories.add(ActionCats.Gemstone.toString());
InitBrowseFileFolder(BrowseFileFolderLocal, "xLocal", "Local","local");
InitBrowseFileFolder(BrowseFileFolderServer, "xServer", "Server","server");
InitBrowseFileFolder(BrowseFileFolderImports, "xImports", "Imports","imports");
InitBrowseFileFolder(BrowseFileFolderRecDir, "xRecDirs", "Recordings","rec_dirs");
InitBrowseFileFolder(BrowseFileFolderNetwork, "xNetwork", "Network","network");
ActionList.put(LaunchExternalApplication, new ADMAction(LaunchExternalApplication,Boolean.FALSE,"Launch External Application", "Application Settings"));
//also load the actions lists - only needs loaded at startup
//clear the lists
SageMenuActions.clear();
CustomAction.ActionListSorted.clear();
CustomAction.CopyModeUniqueIDs.clear();
CustomAction.WidgetSymbols.clear();
CustomAction.AllActionCategories.clear();
CustomAction.AllActionCategories.add(ActionCategoryOther);
CustomAction.AllActionCategories.add("Gemstone");
LoadStandardActionList();
LoadDynamicLists();
LoadSageTVRecordingViews();
LOG.debug("Init: Menu Manager Action Init completed: " + util.LogInfo());
}
private static void InitBrowseFileFolder(String bType, String bTypeKey, String TitleAdd, String FolderAdd){
ActionList.put(bType, new ADMAction(bType,Boolean.FALSE,"File Browser: " + TitleAdd,TitleAdd + " File Path","BASE-51703"));
ActionList.get(bType).ActionVariables.add(new ActionVariable(VarTypeGlobal,"ForceReload", "true"));
ActionList.get(bType).ActionVariables.add(new ActionVariable(VarTypeSetProp,"file_browser/last_style", bTypeKey));
ActionList.get(bType).ActionVariables.add(new ActionVariable(VarTypeSetProp,"file_browser/last_folder/"+FolderAdd, UseAttributeValue));
ActionList.get(bType).ActionCategories.add("File Systems");
}
public static String GetWidgetbySymbol(){ return WidgetbySymbol; }
public static String GetBrowseVideoFolder(){ return BrowseVideoFolder; }
public static String GetStandardMenuAction(){ return StandardMenuAction; }
public static String GetTVRecordingView(){ return TVRecordingView; }
public static String GetGemstoneFlow(){ return GemstoneFlow; }
public static String GetBrowseFileFolderLocal(){ return BrowseFileFolderLocal; }
public static String GetBrowseFileFolderServer(){ return BrowseFileFolderServer; }
public static String GetBrowseFileFolderImports(){ return BrowseFileFolderImports; }
public static String GetBrowseFileFolderRecDir(){ return BrowseFileFolderRecDir; }
public static String GetBrowseFileFolderNetwork(){ return BrowseFileFolderNetwork; }
public static String GetLaunchExternalApplication(){ return LaunchExternalApplication; }
public static String GetLaunchPlayList(){ return LaunchPlayList; }
public static String GetDynamicList(){ return DynamicList; }
public static String GetActionTypeDefault(){ return ActionTypeDefault; }
public static String GetButtonText(String Type){
return ActionList.get(Type).ButtonText;
}
public static String GetDefaultIcon(String MenuItemName){
String IconName = "";
String tActionType = ADMMenuNode.GetMenuItemActionType(MenuItemName);
String tActionAttribute = ADMMenuNode.GetMenuItemAction(MenuItemName);
//LOG.debug("GetDefaultIcon - ActionType = '" + tActionType + "' Action = '" + tActionAttribute + "'");
if (!tActionType.equals(ActionTypeDefault)){
if (tActionType.equals(StandardMenuAction)){
IconName = SageMenuActions.get(tActionAttribute).DefaultIcon;
}
}
//LOG.debug("GetDefaultIcon - MenuItemName: " + MenuItemName + " IconName:" + IconName);
return IconName;
}
public static String GetFieldTitle(String Type){
return ActionList.get(Type).FieldTitle;
}
public static String GetWidgetSymbol(String Type){
return ActionList.get(Type).WidgetSymbol;
}
public static Boolean GetAdvancedOnly(String Type){
return ActionList.get(Type).AdvancedOnly;
}
public static Boolean GetInternalOnly(String Type){
return ActionList.get(Type).InternalOnly;
}
public static List<ActionVariable> GetActionVariables(String Type){
return ActionList.get(Type).ActionVariables;
}
public static Collection<String> GetTypes(){
Collection<String> tempList = new LinkedHashSet<String>();
for (String Item : ActionList.keySet()){
if (GetAdvancedOnly(Item)){
if (ADMutil.IsAdvancedMode()){
tempList.add(Item);
}
}else if (!GetInternalOnly(Item)){
tempList.add(Item);
}
}
return tempList;
}
public static Boolean IsValidAction(String Type){
if (Type.equals(ActionTypeDefault)){
LOG.debug("IsValidAction - FALSE for = '" + Type + "'");
return Boolean.FALSE;
}else{
LOG.debug("IsValidAction - Lookup for = '" + Type + "' = '" + ActionList.containsKey(Type) + "'");
return ActionList.containsKey(Type);
}
}
public static String GetAllActionsAttributeButtonText(String Type, String Attribute){
return GetAllActionsAttributeButtonText(GetAllActionsKey(Type, Attribute), Boolean.FALSE);
}
public static String GetAllActionsAttributeButtonText(String AAType){
return GetAllActionsAttributeButtonText(AAType, Boolean.FALSE);
}
//splits the All Actions Type (Key) using the ListToken to get the Button Text
public static String GetAllActionsAttributeButtonText(String AAType, Boolean IgnoreAdvanced){
//the AAType is made up of the ActionType + ListToken + Attribute (Key)
String tAttribute = GetAllActionsAttribute(AAType);
String tType = GetAllActionsType(AAType);
//LOG.debug("GetAllActionsAttributeButtonText - AAType '" + AAType + "' Type/Attribute '" + tType + "' - '" + tAttribute + "'");
if (tAttribute.equals(ADMutil.OptionNotFound)){
if(tType.equals(ADMutil.OptionNotFound)){
//bad conversion
return ADMutil.OptionNotFound;
}else{
return GetButtonText(tType);
}
}else{
if(tType.equals(TVRecordingView)){
return GetSageTVRecordingViewsActionButtonText(tAttribute);
}else if(tType.equals(GemstoneFlow)){
return GetButtonText(tType) + " - " + GetAttributeButtonText(tType, tAttribute, IgnoreAdvanced);
}else{
return GetAttributeButtonText(tType, tAttribute, IgnoreAdvanced);
}
}
}
public static String GetAttributeButtonText(String Type, String Attribute){
return GetAttributeButtonText(Type, Attribute, Boolean.FALSE);
}
public static String GetAttributeButtonText(String Type, String Attribute, Boolean IgnoreAdvanced){
String retVal;
if (Type.equals(StandardMenuAction)){
//determine if using Advanced options
if (ADMutil.IsAdvancedMode() && !IgnoreAdvanced){
retVal = SageMenuActions.get(Attribute).ButtonText + " \n (" + Attribute + ")";
}else{
retVal = SageMenuActions.get(Attribute).ButtonText;
}
}else if(Type.equals(WidgetbySymbol)){
retVal = Attribute + " - " + GetWidgetName(Attribute);
}else if(Type.equals(BrowseVideoFolder)){
if (Attribute==null){
retVal = "Root";
}else{
retVal = Attribute;
}
}else if(Type.equals(TVRecordingView)){
retVal = GetSageTVRecordingViewsButtonText(Attribute);
}else if(Type.equals(DynamicList)){
retVal = DynamicLists.get(Attribute);
}else if(Type.equals(LaunchPlayList)){
//should not be used as this is an internal only item and should not be displayed
retVal = "Invalid use of this Internal PlayList item";
}else if(Type.equals(GemstoneFlow)){
retVal = Flow.GetFlowName(Attribute);
}else if(Type.equals(LaunchExternalApplication)){
if (Attribute.isEmpty()){
retVal = "Configure";
}else{
retVal = "Configure (" + Attribute + ")";
}
}else if(IsFileBrowserType(Type)){
if (Attribute==null){
retVal = "Choose";
}else{
retVal = Attribute;
}
}else{
retVal = ADMutil.OptionNotFound;
}
return retVal;
}
//execute the Action based on the Menu Item ActionType value
public static void Execute(String MenuItemName){
String tActionType = ADMMenuNode.GetMenuItemActionType(MenuItemName);
String tActionAttribute = ADMMenuNode.GetMenuItemAction(MenuItemName);
LOG.debug("Execute - ActionType = '" + tActionType + "' Action = '" + tActionAttribute + "'");
if (!tActionType.equals(ActionTypeDefault)){
if (tActionType.equals(StandardMenuAction)){
SageMenuActions.get(tActionAttribute).Execute(tActionAttribute);
}else{
//see if there are any ActionVariables that need to be evaluated
for (ActionVariable tActionVar : GetActionVariables(tActionType)){
if (tActionVar.Val.equals(UseAttributeObjectValue)){
tActionVar.EvaluateVariable(ADMMenuNode.GetMenuItemActionObject(MenuItemName));
}else{
tActionVar.EvaluateVariable(tActionAttribute);
}
}
//determine what to execute
if (tActionType.equals(LaunchExternalApplication)){
//launch external application
ExternalAction tExtApp = ADMMenuNode.GetMenuItemActionExternal(MenuItemName);
tExtApp.Execute();
}else{
//either execute the default widget symbol or the one for the Menu Item passed in
if (GetWidgetSymbol(tActionType).equals(Blank)){
ExecuteWidget(tActionAttribute);
}else{
ExecuteWidget(GetWidgetSymbol(tActionType));
}
}
}
}
//else do nothing
}
public static Boolean ExecuteWidget(String WidgetSymbol){
Object[] passvalue = new Object[1];
passvalue[0] = sagex.api.WidgetAPI.FindWidgetBySymbol(new UIContext(sagex.api.Global.GetUIContextName()), WidgetSymbol);
if (passvalue[0]==null){
LOG.debug("ExecuteWidget - FindWidgetSymbol failed for WidgetSymbol = '" + WidgetSymbol + "'");
return Boolean.FALSE;
}else{
LOG.debug("ExecuteWidget - ExecuteWidgetChain called with WidgetSymbol = '" + WidgetSymbol + "'");
try {
sage.SageTV.apiUI(new UIContext(sagex.api.Global.GetUIContextName()).toString(), "ExecuteWidgetChainInCurrentMenuContext", passvalue);
} catch (InvocationTargetException ex) {
LOG.debug("ExecuteWidget: error executing widget" + ADMutil.class.getName() + ex);
return Boolean.FALSE;
}
return Boolean.TRUE;
// sagex.api.WidgetAPI.ExecuteWidgetChain(MyUIContext, WidgetSymbol);
}
}
public static Boolean IsWidgetValid(String WidgetSymbol){
Object[] passvalue = new Object[1];
passvalue[0] = sagex.api.WidgetAPI.FindWidgetBySymbol(new UIContext(sagex.api.Global.GetUIContextName()), WidgetSymbol);
if (passvalue[0]==null){
LOG.debug("IsWidgetValid - FindWidgetSymbol failed for WidgetSymbol = '" + WidgetSymbol + "'");
return Boolean.FALSE;
}else{
LOG.debug("IsWidgetValid - FindWidgetSymbol passed for WidgetSymbol = '" + WidgetSymbol + "'");
return Boolean.TRUE;
}
}
public static String GetWidgetName(String WidgetSymbol){
Object[] passvalue = new Object[1];
passvalue[0] = sagex.api.WidgetAPI.FindWidgetBySymbol(new UIContext(sagex.api.Global.GetUIContextName()), WidgetSymbol);
if (passvalue[0]==null){
LOG.debug("GetWidgetName - FindWidgetSymbol failed for WidgetSymbol = '" + WidgetSymbol + "'");
return ADMutil.OptionNotFound;
}else{
String WidgetName = sagex.api.WidgetAPI.GetWidgetName(new UIContext(sagex.api.Global.GetUIContextName()), WidgetSymbol);
LOG.debug("GetWidgetName for Symbol = '" + WidgetSymbol + "' = '" + WidgetName + "'");
return WidgetName;
}
}
public static void LoadDynamicLists(){
//Dynamic Lists are single menu items that expand themselves into a list of items of a specified type
DynamicLists.clear();
DynamicLists.put(DynamicTVRecordingsList, "TV Recordings List");
ActionList.get(DynamicTVRecordingsList).ActionCategories.add(ActionCats.TV.toString());
DynamicLists.put(DynamicVideoPlaylist, "Video Playlist");
ActionList.get(DynamicVideoPlaylist).ActionCategories.add(ActionCats.Video.toString());
DynamicLists.put(DynamicMusicPlaylist, "Music Playlist");
ActionList.get(DynamicMusicPlaylist).ActionCategories.add(ActionCats.Music.toString());
DynamicLists.put(DynamicGemstoneFlows, "Gemstone Flows");
ActionList.get(DynamicGemstoneFlows).ActionCategories.add(ActionCats.Gemstone.toString());
ActionList.get(DynamicGemstoneFlows).ActionCategories.add(ActionCats.Video.toString());
ActionList.get(DynamicGemstoneFlows).ActionCategories.add(ActionCats.TV.toString());
}
public static Collection<String> GetDynamicListItems(String dParent, String Attribute){
Collection<String> TempMenuItems = new LinkedHashSet<String>();
Integer Counter = 0;
String FirstNameforDefault = Blank;
String ItemName = Blank;
if (Attribute.equals(DynamicTVRecordingsList)){
Integer ViewCount = ADMutil.GetPropertyAsInteger("sagetv_recordings/" + "view_count", 4);
for (String ItemKey : SageTVRecordingViews.keySet()){
//create a temp menu item for each item
//Use a consistent name made up of the Parent + the Counter
ItemName = dParent + Counter.toString();
ADMMenuNode.CreateTempMenuItem(ItemName, dParent, TVRecordingView, ItemKey, GetSageTVRecordingViewsButtonText(ItemKey), Counter);
TempMenuItems.add(ItemName);
if (FirstNameforDefault.equals(Blank)){
FirstNameforDefault = ItemName;
}
Counter++;
if (Counter>=ViewCount){
break;
}
}
if (FirstNameforDefault.equals(Blank)){
ADMMenuNode.ValidateSubMenuDefault(dParent);
}else{
ADMMenuNode.SetMenuItemIsDefault(FirstNameforDefault, Boolean.TRUE);
}
LOG.debug("GetDynamicListItems: Parent '" + dParent + "' Attribute '" + Attribute + "' Items '" + TempMenuItems + "'");
return TempMenuItems;
}else if(Attribute.equals(DynamicVideoPlaylist)){
TempMenuItems = GetPlayList(Boolean.TRUE, dParent);
LOG.debug("GetDynamicListItems: Parent '" + dParent + "' Attribute '" + Attribute + "' Items '" + TempMenuItems + "'");
return TempMenuItems;
}else if(Attribute.equals(DynamicMusicPlaylist)){
TempMenuItems = GetPlayList(Boolean.FALSE, dParent);
LOG.debug("GetDynamicListItems: Parent '" + dParent + "' Attribute '" + Attribute + "' Items '" + TempMenuItems + "'");
return TempMenuItems;
}else if(Attribute.equals(DynamicGemstoneFlows)){
Counter = 0;
//if there are no Flows then add an item to allow the user to generate all default flows
if (Flow.GetFlows().size()>0){
for (String vFlow: Flow.GetFlows()){
ItemName = dParent + Counter.toString();
ADMMenuNode.CreateTempMenuItem(ItemName, dParent, GemstoneFlow, vFlow, GetAttributeButtonText(GemstoneFlow, vFlow, Boolean.TRUE), Counter);
TempMenuItems.add(ItemName);
Counter++;
}
}else{
//calls a specific widget inside the UI to create all default flows plus reset the main menu
ItemName = dParent + Counter.toString();
ADMMenuNode.CreateTempMenuItem(ItemName, dParent, WidgetbySymbol, "JUSJOKEN-7763577", "Create Default Flows", Counter);
TempMenuItems.add(ItemName);
}
return TempMenuItems;
}else{
LOG.debug("GetDynamicListItems: Parent '" + dParent + "' Attribute '" + Attribute + "' Items '" + TempMenuItems + "'");
return TempMenuItems;
}
}
private static Collection<String> GetPlayList(Boolean IsVideo, String dParent){
//based on IsVideo this will create MenuItems for
// true = Vidoes
// false = Music
String ItemName = Blank;
Collection<String> TempMenuItems = new LinkedHashSet<String>();
String PlayListItemType = "";
if (IsVideo){
PlayListItemType = "xVideo";
}else{
PlayListItemType = "xSong";
}
Object[] AllPlayLists = sagex.api.PlaylistAPI.GetPlaylists();
//Create a menu item for each of the playlists
Integer Counter = 0;
for (Object Playlist : AllPlayLists){
if (sagex.api.PlaylistAPI.DoesPlaylistHaveVideo(Playlist)==IsVideo){
//skip specific Playlists
if (sagex.api.PlaylistAPI.GetName(Playlist).equals("DVD BURN PLAYLIST") || sagex.api.PlaylistAPI.GetName(Playlist).equals("Now Playing")){
//skip these playlists
}else{
//now creage a Menu Item for this Playlist
ItemName = dParent + Counter.toString();
ADMMenuNode.CreateTempMenuItem(ItemName, dParent, LaunchPlayList, PlayListItemType, GetPlayListButtonText(Playlist), Counter);
ADMMenuNode.SetMenuItemActionObject(ItemName, Playlist);
TempMenuItems.add(ItemName);
Counter++;
}
}
}
return TempMenuItems;
}
private static String GetPlayListButtonText(Object Playlist){
String PLName = sagex.api.PlaylistAPI.GetName(new UIContext(sagex.api.Global.GetUIContextName()),Playlist);
//Get name after last /, if the string has any.
Integer SlashPos = PLName.lastIndexOf("/");
if (SlashPos!=-1){
PLName = ".." + PLName.substring( SlashPos+1, -1 );
}
return PLName;
}
//returns a sorted list of ALL the actions
private static Integer AllActionsListCount = 0;
public static Collection<String> GetAllActionsList(){
SortedMap<String,String> AllActionsSorted = new TreeMap<String,String>();
for (String aType : GetTypes()){
//do not add Do Nothing to the list
if (!aType.equals(ActionTypeDefault)){
if (HasActionList(aType)){
for (String aAttribute : GetActionList(aType)){
AllActionsListAdd(AllActionsSorted, GetAllActionsAttributeButtonText(aType,aAttribute), aType, aAttribute);
}
}else{
AllActionsListAdd(AllActionsSorted, GetButtonText(aType), aType, Blank);
}
}
}
//LOG.debug("GetAllActionsList: complete List '" + AllActionsSorted.keySet() + "' Values '" + AllActionsSorted.values() + "'");
AllActionsListCount = AllActionsSorted.size();
return AllActionsSorted.values();
}
private static void AllActionsListAdd(SortedMap<String,String> AllActionsSorted, String bButtonText, String bType, String bAttribute){
//filter the list based on the selected Category Filter
if (GetActionCategoryFilter().equals(ActionCategoryShowAll)){
//LOG.debug("AllActionsListAdd: No Filter - adding '" + bButtonText + "' Type/Attribute '" + bType + "' - '" + bAttribute + "'");
AllActionsSorted.put(bButtonText, GetAllActionsKey(bType, bAttribute));
}else{
String tFilter = GetActionCategoryFilter();
//determine if this is a CustomAction
if (SageMenuActions.containsKey(bAttribute)){
if (tFilter.equals(ActionCategoryOther)){
if (SageMenuActions.get(bAttribute).ActionCategories.isEmpty()){
//LOG.debug("AllActionsListAdd: Filter '" + tFilter + "' CustomAction for '" + bAttribute + "' Adding as No Categories and Other");
AllActionsSorted.put(bButtonText, GetAllActionsKey(bType, bAttribute));
}
}else{
if (SageMenuActions.get(bAttribute).HasCategory(tFilter)){
//LOG.debug("AllActionsListAdd: Filter '" + tFilter + "' CustomAction for '" + bType + "' - '" + bAttribute + "' Adding");
AllActionsSorted.put(bButtonText, GetAllActionsKey(bType, bAttribute));
}
}
}else{
//Other Action
if (ActionList.containsKey(bType)){
String CheckType = bType;
if (bType.equals(DynamicList)){
//LOG.debug("AllActionsListAdd: Dynamic List item - Attribute '" + bAttribute + "'");
CheckType = bAttribute;
}
//LOG.debug("AllActionsListAdd: Filter '" + tFilter + "' checking Other Action for '" + bType + "' Attribute '" + bAttribute + "'");
if (tFilter.equals(ActionCategoryOther)){
if (ActionList.get(CheckType).ActionCategories.isEmpty()){
//LOG.debug("AllActionsListAdd: Filter '" + tFilter + "' Other Action for '" + bType + "' Adding as No Categories and Other");
AllActionsSorted.put(bButtonText, GetAllActionsKey(bType, bAttribute));
}
}else{
if (ActionList.get(CheckType).ActionCategories.contains(tFilter)){
//LOG.debug("AllActionsListAdd: Filter '" + tFilter + "' Found Match for Type '" + bType + "' Adding");
AllActionsSorted.put(bButtonText, GetAllActionsKey(bType, bAttribute));
}
}
}else{
//do an Add so you don't miss anything that didn't match either of the above checks - should be nothing
LOG.debug("AllActionsListAdd: Filter '" + tFilter + "' NO MATCH SO ADDING ANYWAY '" + bType + "' ButtonText '" + bButtonText + "'");
AllActionsSorted.put(bButtonText, GetAllActionsKey(bType, bAttribute));
}
}
}
}
public static Integer GetAllActionsListCount(){
return AllActionsListCount;
}
public static String GetAllActionsInitialFocus(String Name){
Collection<String> AllActionsList = GetAllActionsList();
//if the current Action is in the list return it as focus otherwise return the first item
String tKey = GetAllActionsKey(ADMMenuNode.GetMenuItemActionType(Name), ADMMenuNode.GetMenuItemAction(Name));
if (AllActionsList.contains(tKey)){
return tKey;
}else{
String FirstItem = "";
for (String Item : AllActionsList){
FirstItem = Item;
break;
}
return FirstItem;
}
}
public static String GetAllActionsKey(String aType, String aAttribute){
if (HasActionList(aType)){
return aType + ADMutil.ListToken + aAttribute;
}else{
return aType;
}
}
public static String GetAllActionsAttribute(String AAType){
//the AAType is made up of the ActionType + ListToken + Attribute (Key)
List<String> tList = ADMutil.ConvertStringtoList(AAType);
LOG.debug("GetAllActionsAttribute: AAType '" + AAType + "' List '" + tList + "'");
if (tList.size()==2){
return tList.get(1);
}else{
//bad conversion or no attribute
return ADMutil.OptionNotFound;
}
}
public static String GetAllActionsType(String AAType){
//the AAType is made up of the ActionType + ListToken + Attribute (Key)
List<String> tList = ADMutil.ConvertStringtoList(AAType);
if (tList.size()>=1){
return tList.get(0);
}else{
//bad conversion
return ADMutil.OptionNotFound;
}
}
public static Collection<String> GetActionList(String Type){
//TODO: build a AllActions list to provide a search or full list to select from.
if (Type.equals(StandardMenuAction)){
return CustomAction.ActionListSorted.values();
}else if(Type.equals(TVRecordingView)){
return SageTVRecordingViews.keySet();
}else if(Type.equals(DynamicList)){
return DynamicLists.keySet();
}else if(Type.equals(GemstoneFlow)){
return Flow.GetFlows();
}else{
return Collections.emptyList();
}
}
public static Boolean HasActionList(String Type){
if (Type.equals(StandardMenuAction)){
return Boolean.TRUE;
}else if(Type.equals(TVRecordingView)){
return Boolean.TRUE;
}else if(Type.equals(DynamicList)){
return Boolean.TRUE;
}else if(Type.equals(GemstoneFlow)){
return Boolean.TRUE;
}else{
return Boolean.FALSE;
}
}
public static Boolean UseGenericEditBox(String Type){
if (Type.equals(BrowseVideoFolder)){
return Boolean.TRUE;
}else if(IsFileBrowserType(Type)){
return Boolean.TRUE;
}else{
return Boolean.FALSE;
}
}
public static Boolean IsFileBrowserType(String Type){
if (Type.equals(BrowseFileFolderLocal)){
return Boolean.TRUE;
}else if(Type.equals(BrowseFileFolderServer)){
return Boolean.TRUE;
}else if(Type.equals(BrowseFileFolderImports)){
return Boolean.TRUE;
}else if(Type.equals(BrowseFileFolderNetwork)){
return Boolean.TRUE;
}else if(Type.equals(BrowseFileFolderRecDir)){
return Boolean.TRUE;
}else{
return Boolean.FALSE;
}
}
public static String GetFileBrowserType(String Style){
if (Style.equals("xLocal")){
return BrowseFileFolderLocal;
}else if(Style.equals("xServer")){
return BrowseFileFolderServer;
}else if(Style.equals("xImports")){
return BrowseFileFolderImports;
}else if(Style.equals("xRecDirs")){
return BrowseFileFolderRecDir;
}else if(Style.equals("xNetwork")){
return BrowseFileFolderNetwork;
}else{
return ADMutil.OptionNotFound;
}
}
public static String GetGenericEditBoxMessage(String Type){
if (Type.equals(BrowseVideoFolder)){
return "Enter a Folder Name/Path:\nHint: use the same text as displayed\nin the 'Video by Folder' view next to 'Folder (case sensitive):'";
}else if(IsFileBrowserType(Type)){
return "Enter a Folder Name/Path:\nHint: use the same text as displayed\nin the File Browser";
}else if(Type.equals(LaunchExternalApplication)){
return "Enter a command";
}else{
return "";
}
}
public static void LoadStandardActionList(){
Properties CustomActionProps = new Properties();
String CustomActionPropsPath = util.DefaultsLocation() + File.separator + StandardActionListFile;
//read the properties from the properties file
try {
FileInputStream in = new FileInputStream(CustomActionPropsPath);
try {
CustomActionProps.load(in);
} finally {
in.close();
}
} catch (Exception ex) {
LOG.debug("LoadStandardActionList: file not found loading actions " + ADMutil.class.getName() + ex);
return;
}
//write all the custom actions to Sage properties as it is easier to parse them that way - delete them when done
if (CustomActionProps.size()>0){
//clean up existing Custom Actions from the SageTV properties file before writing the new ones
ADMutil.RemovePropertyAndChildren(SageADMCustomActionsPropertyLocation);
for (String tPropertyKey : CustomActionProps.stringPropertyNames()){
ADMutil.SetProperty(tPropertyKey, CustomActionProps.getProperty(tPropertyKey));
}
}
//load custom menu actions from Sage Properties
//find all Custom Action Name entries from the SageTV properties file
String[] CustomActionNames = sagex.api.Configuration.GetSubpropertiesThatAreBranches(new UIContext(sagex.api.Global.GetUIContextName()),SageADMCustomActionsPropertyLocation);
if (CustomActionNames.length>0){
String PropLocation = "";
for (String tCustomActionName : CustomActionNames){
LOG.debug("LoadStandardActionList: loading '" + tCustomActionName + "' Custom Menu Action");
PropLocation = SageADMCustomActionsPropertyLocation + "/" + tCustomActionName;
String tButtonText = ADMutil.GetProperty(PropLocation + "/ButtonText", ADMutil.ButtonTextDefault);
String tDefaultIcon = ADMutil.GetProperty(PropLocation + "/DefaultIcon", "");
String tWidgetSymbol = ADMutil.GetProperty(PropLocation + "/WidgetSymbol", "");
String tCopyModeAttributeVar = ADMutil.GetProperty(PropLocation + "/CopyModeAttributeVar", Blank);
CustomAction tAction = new CustomAction(tCustomActionName,tButtonText, tWidgetSymbol, tCopyModeAttributeVar, tDefaultIcon);
SageMenuActions.put(tCustomActionName,tAction);
//load any action variables
Integer Counter = 0;
Boolean Found = Boolean.TRUE;
do {
Counter++;
//first test if the current action variable is available
String AVPropLocation = PropLocation + "/ActionVariables/" + Counter;
if (ADMutil.HasProperty(AVPropLocation + "/VarType")){
ActionVariable tVar = new ActionVariable();
tVar.VarType = ADMutil.GetProperty(AVPropLocation + "/VarType", VarTypeGlobal);
tVar.Var = ADMutil.GetProperty(AVPropLocation + "/Var", "");
tVar.Val = ADMutil.GetProperty(AVPropLocation + "/Val", "");
SageMenuActions.get(tCustomActionName).ActionVariables.add(tVar);
LOG.debug("LoadStandardActionList: Loading Vars from '" + AVPropLocation + "' VarType='" + tVar.VarType + "' Var='" + tVar.Var + "' Val ='" + tVar.Val + "'");
}else{
Found = Boolean.FALSE;
}
} while (Found);
//load any action categories
Counter = 0;
Found = Boolean.TRUE;
String tCategory = "";
do {
Counter++;
//first test if the current action category is available
String AVPropLocation = PropLocation + "/ActionCategory/" + Counter;
if (ADMutil.HasProperty(AVPropLocation)){
tCategory = ADMutil.GetProperty(AVPropLocation, Blank);
SageMenuActions.get(tCustomActionName).AddCategory(tCategory);
LOG.debug("LoadStandardActionList: Loading Category from '" + AVPropLocation + "' Category='" + tCategory + "' Categories '" + CustomAction.AllActionCategories + "'");
}else{
Found = Boolean.FALSE;
}
} while (Found);
}
}
//clean up existing Custom Actions from the SageTV properties file as they are no longer needed
ADMutil.RemovePropertyAndChildren(SageADMCustomActionsPropertyLocation);
LOG.debug("LoadStandardActionList: completed loading '" + SageMenuActions.size() + "' Custom Menu Actions");
}
private static void LoadSageTVRecordingViews(){
SageTVRecordingViews.clear();
//put the ViewType and Default View Name into a list
SageTVRecordingViews.put("xAll","All Recordings");
SageTVRecordingViews.put("xRecordings","Current Recordings");
SageTVRecordingViews.put("xArchives","Archived Recordings");
SageTVRecordingViews.put("xMovies","Recorded Movies");
//SageTVRecordingViews.put("xPartials","");
SageTVRecordingViews.put("xView5","Recording View5");
SageTVRecordingViews.put("xView6","Recording View6");
SageTVRecordingViews.put("xView7","Recording View7");
SageTVRecordingViews.put("xView8","Recording View8");
}
public static String GetSageTVRecordingViewsButtonText(String Name){
//return the stored name from Sage or the Default Name if nothing is stored
return ADMutil.GetProperty(SageTVRecordingViewsTitlePropertyLocation + Name, SageTVRecordingViews.get(Name));
}
public static String GetSageTVRecordingViewsActionButtonText(String Name){
//return the stored name from Sage or the Default Name if nothing is stored
return "Recordings - " + ADMutil.GetProperty(SageTVRecordingViewsTitlePropertyLocation + Name, SageTVRecordingViews.get(Name));
}
public static void SetSageTVRecordingViewsButtonText(String ViewType, String Name){
//rename the specified TV Recording View
ADMutil.SetProperty(SageTVRecordingViewsTitlePropertyLocation + ViewType, Name);
}
public static Collection<String> GetAllActionCategories(){
return CustomAction.AllActionCategories;
}
public static String GetAllActionCategoriesFooter(String Name){
String Prefix = "Current Action: ";
String tActionType = GetButtonText(ADMMenuNode.GetMenuItemActionType(Name));
String tActionAttribute = ADMMenuNode.GetActionAttributeButtonText(Name);
String ReturnValue = Prefix;
if (tActionType.equals(ActionTypeDefault)){
return "";
}else{
ReturnValue = ReturnValue + tActionType;
if (!tActionAttribute.equals(ADMutil.OptionNotFound)){
ReturnValue = ReturnValue + "\n " + tActionAttribute;
}
}
return ReturnValue;
}
public static void ActionCategoryFilterReset(){
if (GetActionCategoryFilterSticky().equals(ADMutil.TriState.OTHER)){
LOG.debug("ActionCategoryFilterReset: sticky found so no change");
//leave it as is as it is supposed to be sticky
}else{
//reset the Filter to the ShowAll filter
LOG.debug("ActionCategoryFilterReset: reseting to Show All");
ADMutil.SetPropertyAsTriState(ActionCategoryFilterStickyPropertyLocation, ADMutil.TriState.NO);
ADMutil.SetProperty(ActionCategoryFilterPropertyLocation, ActionCategoryShowAll);
}
}
public static String GetActionCategoryFilter(){
return ADMutil.GetProperty(ActionCategoryFilterPropertyLocation, ActionCategoryShowAll);
}
public static String GetActionCategoryFilterButtonText(){
String tFilter = ADMutil.GetProperty(ActionCategoryFilterPropertyLocation, ActionCategoryShowAll);
if (tFilter.equals(ActionCategoryShowAll)){
return "-Not Filtered-";
}else{
return " ";
}
}
public static ADMutil.TriState GetActionCategoryFilterSticky(){
return ADMutil.GetPropertyAsTriState(ActionCategoryFilterStickyPropertyLocation, ADMutil.TriState.NO);
}
public static Boolean GetActionCategoryFilterStickyIsChecked(String Category){
String tCategory = ADMutil.GetProperty(ActionCategoryFilterPropertyLocation, Blank);
if (tCategory.equals(Category)){
ADMutil.TriState tSticky = ADMutil.GetPropertyAsTriState(ActionCategoryFilterStickyPropertyLocation, ADMutil.TriState.NO);
if (tSticky.equals(ADMutil.TriState.OTHER) || tSticky.equals(ADMutil.TriState.YES)){
return Boolean.TRUE;
}else{
return Boolean.FALSE;
}
}else{
return Boolean.FALSE;
}
}
public static Boolean GetActionCategoryFilterStickyIsSticky(String Category){
String tCategory = ADMutil.GetProperty(ActionCategoryFilterPropertyLocation, Blank);
if (tCategory.equals(Category)){
ADMutil.TriState tSticky = ADMutil.GetPropertyAsTriState(ActionCategoryFilterStickyPropertyLocation, ADMutil.TriState.NO);
if (tSticky.equals(ADMutil.TriState.OTHER)){
return Boolean.TRUE;
}else{
return Boolean.FALSE;
}
}else{
return Boolean.FALSE;
}
}
public static void ChangeActionCategoryFilter(String Category){
String prevCategory = ADMutil.GetProperty(ActionCategoryFilterPropertyLocation, Blank);
ADMutil.TriState prevSticky = ADMutil.GetPropertyAsTriState(ActionCategoryFilterStickyPropertyLocation, ADMutil.TriState.NO);
ADMutil.TriState newSticky = ADMutil.TriState.YES;
String newCategory = Category;
if (prevCategory.equals(Category)){
if (prevSticky.equals(ADMutil.TriState.YES)){
newSticky = ADMutil.TriState.OTHER;
}else if (prevSticky.equals(ADMutil.TriState.OTHER)){
newSticky = ADMutil.TriState.NO;
newCategory = ActionCategoryShowAll;
}else{
newSticky = ADMutil.TriState.YES;
}
}
//store the newCategory
ADMutil.SetPropertyAsTriState(ActionCategoryFilterStickyPropertyLocation, newSticky);
ADMutil.SetProperty(ActionCategoryFilterPropertyLocation, newCategory);
}
public static class ActionVariable{
private String Var = "";
private String Val = "";
private String VarType = VarTypeGlobal;
public ActionVariable(){
}
public ActionVariable(String VarType, String Var, String Val ){
this.VarType = VarType;
this.Var = Var;
this.Val = Val;
}
public String getVarType(){
return this.VarType;
}
public String getVar(){
return this.Var;
}
public String getVal(){
return this.Val;
}
//using an Object rather than a string as for PlayLists you need to pass an Object into a Global Variable
public void EvaluateVariable(Object Attribute){
Object tVal = this.Val;
if (this.Val.equals(UseAttributeValue) || this.Val.equals(UseAttributeObjectValue)){
tVal = Attribute;
}else if (this.Val.equals(VarNull)){
tVal = null;
}
if (this.VarType.equals(VarTypeGlobal)){
sagex.api.Global.AddGlobalContext(new UIContext(sagex.api.Global.GetUIContextName()), this.Var, tVal);
}else if (this.VarType.equals(VarTypeStatic)){
sagex.api.Global.AddStaticContext(new UIContext(sagex.api.Global.GetUIContextName()), this.Var, tVal);
}else if (this.VarType.equals(VarTypeSetProp)){
ADMutil.SetProperty(this.Var, tVal.toString());
}
LOG.debug("EvaluateVariable - Type '" + this.VarType + "' setting '" + this.Var + "' to '" + tVal + "' for Attribute '" + Attribute + "' original Val ='" + this.Val + "'");
}
}
public static class CustomAction{
private String Name = "";
private String ButtonText = "";
private String DefaultIcon = "";
private String WidgetSymbol = "";
private String CopyModeAttributeVar = Blank;
private List<ActionVariable> ActionVariables = new LinkedList<ActionVariable>();
private List<String> ActionCategories = new LinkedList<String>();
public static Collection<String> WidgetSymbols = new LinkedHashSet<String>();
//the combination of the Name and CopymodeAttributeVar fields make the CustomAction unique for the CopyMode
public static Collection<String> CopyModeUniqueIDs = new LinkedHashSet<String>();
//need a list of keys that are sorted by the ButtonText
public static SortedMap<String,String> ActionListSorted = new TreeMap<String,String>();
//unique set of All Categories
public static SortedSet<String> AllActionCategories = new TreeSet<String>();
// public CustomAction(String Name, String ButtonText){
// this(Name,ButtonText,"",Blank);
// }
//
public CustomAction(String Name, String ButtonText, String WidgetSymbol){
this(Name,ButtonText,WidgetSymbol,Blank,Blank);
}
public CustomAction(String Name, String ButtonText, String WidgetSymbol, String CopyModeAttributeVar){
this(Name,ButtonText,WidgetSymbol,CopyModeAttributeVar,Blank);
}
public CustomAction(String Name, String ButtonText, String WidgetSymbol, String CopyModeAttributeVar,String DefaultIcon){
this.Name = Name;
this.ButtonText = ButtonText;
if (!(DefaultIcon.equals(Blank)||DefaultIcon.equals(""))){
this.DefaultIcon = DefaultIcon;
} else {
this.DefaultIcon = ADMutil.DefaultIcon;
}
this.WidgetSymbol = WidgetSymbol;
this.CopyModeAttributeVar = CopyModeAttributeVar;
//WidgetSymbols list is used for the copymode function to further refine the item to be copied
//therefore it is not populated for items that do not have a CopyModeAttributeVar
if (!CopyModeAttributeVar.equals(Blank)){
WidgetSymbols.add(WidgetSymbol);
}
CopyModeUniqueIDs.add(UniqueID(CopyModeAttributeVar,Name));
ActionListSorted.put(this.ButtonText, Name);
}
public void AddCategory(String aCategory){
ActionCategories.add(aCategory);
AllActionCategories.add(aCategory);
}
public Boolean HasCategory(String aCategory){
return ActionCategories.contains(aCategory);
}
public void Execute(String Attribute){
//evaluate all the ActionVariables first
for (ActionVariable ActionVar : ActionVariables){
ActionVar.EvaluateVariable(Attribute);
}
//Execute the WidgetSymbol
ADMAction.ExecuteWidget(WidgetSymbol);
}
public static String UniqueID(String Name, String Var){
return Name + ADMutil.ListToken + Var;
}
}
public static class ExternalAction{
//portions borrowed from NielM ExtCommand.java code
private Integer windowType; // (maximised | minimised | hidden | normal | console )
private String command;
private String arguments;
private Boolean waitForExit;
private Integer sageStatus;
private String MenuItemName;
static public final String[] windowTypeStrings = {
"Normal",
"Maximised",
"Minimised",
"Hidden"
};
static public final int WINDOW_NORMAL =0;
static public final int WINDOW_MAXIMISED=1;
static public final int WINDOW_MINIMISED=2;
static public final int WINDOW_HIDDEN=3;
static public final String[] sageStatusStrings = {
"Do nothing with Sage",
"Put Sage in Sleep Mode",
"Exit Sage after application launch"
};
static public final Integer SageStatusNothing = 0;
static public final Integer SageStatusSleep = 1;
static public final Integer SageStatusExit = 2;
public ExternalAction(String MenuItemName){
this.MenuItemName = MenuItemName;
this.command="";
this.windowType=0;
this.arguments="";
this.waitForExit=Boolean.TRUE;
this.sageStatus = SageStatusNothing;
}
public ExternalAction(String MenuItemName, String command, Integer windowType, String arguments, Boolean waitForExit, Integer sageStatus ){
this.MenuItemName = MenuItemName;
this.command=command;
//validate windowType
if (windowType<0 || windowType>windowTypeStrings.length){
this.windowType=0; //default to Normal
}else{
this.windowType=windowType;
}
this.arguments=arguments;
this.waitForExit=waitForExit;
if (sageStatus<0 || sageStatus>sageStatusStrings.length){
this.sageStatus = SageStatusNothing;
}else{
this.sageStatus = sageStatus;
}
}
public String GetApplication(){
return this.command;
}
public void SetApplication(String bApplication){
this.command = bApplication;
this.Save();
}
public String GetArguments(){
return this.arguments;
}
public void SetArguments(String bArguments){
this.arguments = bArguments;
this.Save();
}
public String GetWindowType(){
return windowTypeStrings[windowType];
}
public void ChangeWindowType(Integer Delta){
this.windowType = this.windowType + Delta;
if (windowType>=windowTypeStrings.length){
this.windowType = 0;
}else if(windowType<0){
this.windowType = windowTypeStrings.length-1;
}
this.Save();
}
public String GetWaitForExit(){
if (waitForExit){
return "Wait until Application Exits";
}else{
return "Do not wait";
}
}
public void ChangeWaitForExit(){
this.waitForExit = !this.waitForExit;
this.Save();
}
public String GetSageStatus(){
return sageStatusStrings[sageStatus];
}
public void ChangeSageStatus(Integer Delta){
this.sageStatus = this.sageStatus + Delta;
if (sageStatus>=sageStatusStrings.length){
this.sageStatus = 0;
}else if(sageStatus<0){
this.sageStatus = sageStatusStrings.length-1;
}
this.Save();
}
//TODO: EXTERNAL MENU DONE - External action save
public void Save(){
//set the menuitem as dirty so it can later be saved
ADMMenuNode.SetMenuItemIsDirty(MenuItemName, Boolean.TRUE);
//TODO: EXTERNAL MENU - removed the specific saving of the menu items to the properties
//save all variables to the sage Properties
// ADMMenuNode.Save(MenuItemName, "ExternalAction/Application", command);
// ADMMenuNode.Save(MenuItemName, "ExternalAction/Arguments", arguments);
// ADMMenuNode.Save(MenuItemName, "ExternalAction/WindowType", windowType.toString());
// ADMMenuNode.Save(MenuItemName, "ExternalAction/WaitForExit", waitForExit.toString());
// ADMMenuNode.Save(MenuItemName, "ExternalAction/SageStatus", sageStatus.toString());
}
public void Load(PropertiesExt inProp){
//load all variables from the sage Properties
String PropLocation = ADMutil.SagePropertyLocation + MenuItemName + "/ExternalAction/";
this.command = inProp.getProperty(PropLocation + "Application", "");
this.arguments = inProp.getProperty(PropLocation + "Arguments", "");
this.windowType = inProp.GetPropertyAsInteger(PropLocation + "WindowType", 0);
this.waitForExit = inProp.GetPropertyAsBoolean(PropLocation + "WaitForExit", Boolean.TRUE);
this.sageStatus = inProp.GetPropertyAsInteger(PropLocation + "SageStatus", 0);
}
public void AddProperties(Properties inProp){
String PropLocation = ADMutil.SagePropertyLocation + MenuItemName + "/ExternalAction/";
inProp.setProperty(PropLocation + "Application", command);
inProp.setProperty(PropLocation + "Arguments", arguments);
inProp.setProperty(PropLocation + "WindowType", windowType.toString());
inProp.setProperty(PropLocation + "WaitForExit", waitForExit.toString());
inProp.setProperty(PropLocation + "SageStatus", sageStatus.toString());
}
public void Execute(){
UIContext MyUIContext = new UIContext(sagex.api.Global.GetUIContextName());
try{
String osName = System.getProperty("os.name");
String[] cmd = null;
if ( osName.toLowerCase().startsWith("windows")) {
cmd = new String[3];
if( osName.equals( "Windows 95" ) || osName.equals( "Windows 98" ) ){
cmd[0] = "command.com" ;
cmd[1] = "/C" ;
} else if( osName.toLowerCase().contains("win")){//any newer Windows OS
cmd[0] = "cmd.exe" ;
cmd[1] = "/C" ;
}else {
LOG.debug("ExternalAction.Execute: unknown OS:"+osName+" assuming newer Windows OS");
cmd[0] = "cmd.exe" ;
cmd[1] = "/C" ;
}
cmd[2] = "start \"console\" ";
if ( waitForExit ){
cmd[2]=cmd[2] + "/wait ";
}
//Window Types
if ( windowType == WINDOW_MAXIMISED ){
cmd[2] = cmd[2] +"/max ";
}else if ( windowType == WINDOW_MINIMISED ){
cmd[2] = cmd[2] +"/min ";
}else if ( windowType == WINDOW_HIDDEN ){
cmd[2] = cmd[2] +"/b ";
}
// append command -- first for window title, second for exe name
cmd[2]=cmd[2]+"\""+command+"\" " + arguments;
LOG.debug("ExternalAction.Execute: Command = '" + cmd[0] + " " + cmd[1] + " " + cmd[2] + "'");
} else {
cmd = new String[2];
cmd[0]=command;
cmd[1]=arguments;
LOG.debug("ExternalAction.Execute: for unknown OS '" + osName + "' Command = '" + cmd[0] + " " + cmd[1] + "'" );
}
//determine what to do with Sage - before
Boolean tFullScreen = sagex.api.Global.IsFullScreen(MyUIContext);
if (sageStatus.equals(SageStatusSleep)){
if (tFullScreen){
sagex.api.Global.SetFullScreen(MyUIContext, Boolean.FALSE);
}
sagex.api.Global.SageCommand(MyUIContext,"Power Off");
}else if (sageStatus.equals(SageStatusExit)){
//the exit command would only occur AFTER the External Application is executed - see below
//sagex.api.Global.Exit(new UIContext(sagex.api.Global.GetUIContextName()));
}else{
//do thing assumed
}
Runtime rt = Runtime.getRuntime();
Process proc = rt.exec(cmd);
// any error message?
StreamGobbler errorGobbler = new StreamGobbler(proc.getErrorStream(), "ERROR");
// any output?
StreamGobbler outputGobbler = new StreamGobbler(proc.getInputStream(), "OUTPUT");
// kick them off
errorGobbler.start();
outputGobbler.start();
// any error???
int exitVal = proc.waitFor();
LOG.debug("ExternalAction.Execute: ExitValue: '" + exitVal + "'");
//determine what to do with Sage - after
if (sageStatus.equals(SageStatusSleep)){
sagex.api.Global.SageCommand(MyUIContext,"Power On");
if (tFullScreen){
sagex.api.Global.SetFullScreen(MyUIContext, Boolean.TRUE);
}
}else if (sageStatus.equals(SageStatusExit)){
//exit Sage after starting the External Application
sagex.api.Global.Exit(new UIContext(sagex.api.Global.GetUIContextName()));
}else{
//do thing assumed
}
} catch (Throwable t)
{
LOG.debug("ExternalAction.Execute: ERROR - Exception = '" + t + "'");
//t.printStackTrace();
}
}
//StreamGobbler class from
//http://www.javaworld.com/javaworld/jw-12-2000/jw-1229-traps.html
public static class StreamGobbler extends Thread
{
InputStream is;
String type;
StreamGobbler(InputStream is, String type)
{
this.is = is;
this.type = type;
}
@Override
public void run()
{
try
{
InputStreamReader isr = new InputStreamReader(is);
BufferedReader br = new BufferedReader(isr);
String line=null;
while ( (line = br.readLine()) != null)
System.out.println(type + ">" + line);
} catch (IOException ioe)
{
LOG.debug("ExternalAction.StreamGobbler: ERROR - Exception = '" + ioe + "'");
//ioe.printStackTrace();
}
}
}
}
}
| |
/*
* The MIT License (MIT)
*
* Copyright 2017 Alexander Orlov <alexander.orlov@loxal.net>. All rights reserved.
* Copyright (c) [2016] [ <ether.camp> ]
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*
*/
package org.ethereum.net.swarm;
import org.ethereum.util.ByteUtil;
import org.jetbrains.annotations.NotNull;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Arrays;
import java.util.Collection;
import static java.lang.Math.max;
import static java.lang.Math.min;
/**
* From Go implementation:
*
* The distributed storage implemented in this package requires fix sized chunks of content
* Chunker is the interface to a component that is responsible for disassembling and assembling larger data.
* TreeChunker implements a Chunker based on a tree structure defined as follows:
* 1 each node in the tree including the root and other branching nodes are stored as a chunk.
* 2 branching nodes encode data contents that includes the size of the dataslice covered by its
* entire subtree under the node as well as the hash keys of all its children
* data_{i} := size(subtree_{i}) || key_{j} || key_{j+1} .... || key_{j+n-1}
* 3 Leaf nodes encode an actual subslice of the input data.
* 4 if data size is not more than maximum chunksize, the data is stored in a single chunk
* key = sha256(int64(size) + data)
* 2 if data size is more than chunksize*Branches^l, but no more than
* chunksize*Branches^l length (except the last one).
* key = sha256(int64(size) + key(slice0) + key(slice1) + ...)
* Tree chunker is a concrete implementation of data chunking.
* This chunker works in a simple way, it builds a tree out of the document so that each node either
* represents a chunk of real data or a chunk of data representing an branching non-leaf node of the tree.
* In particular each such non-leaf chunk will represent is a concatenation of the hash of its respective children.
* This scheme simultaneously guarantees data integrity as well as self addressing. Abstract nodes are
* transparent since their represented size component is strictly greater than their maximum data size,
* since they encode a subtree.
* If all is well it is possible to implement this by simply composing readers so that no extra allocation or
* buffering is necessary for the data splitting and joining. This means that in principle there
* can be direct IO between : memory, file system, network socket (bzz peers storage request is
* read from the socket ). In practice there may be need for several stages of internal buffering.
* Unfortunately the hashing itself does use extra copies and allocation though since it does need it.
*/
public class TreeChunker implements Chunker {
public static final MessageDigest DEFAULT_HASHER;
private static final int DEFAULT_BRANCHES = 128;
static {
try {
DEFAULT_HASHER = MessageDigest.getInstance("SHA-256");
} catch (final NoSuchAlgorithmException e) {
throw new RuntimeException(e); // Can't happen.
}
}
private int branches;
private MessageDigest hasher;
private int hashSize;
private long chunkSize;
public TreeChunker() {
this(DEFAULT_BRANCHES, DEFAULT_HASHER);
}
public TreeChunker(final int branches, final MessageDigest hasher) {
this.branches = branches;
this.hasher = hasher;
hashSize = hasher.getDigestLength();
chunkSize = hashSize * branches;
}
public long getChunkSize() {
return chunkSize;
}
@NotNull
@Override
public Key split(@NotNull SectionReader sectionReader, @NotNull Collection<? extends Chunk> consumer) {
final TreeSize ts = new TreeSize(sectionReader.getSize());
return splitImpl(ts.depth, ts.treeSize / branches, sectionReader, (Collection<Chunk>) consumer);
}
private Key splitImpl(int depth, long treeSize, final SectionReader data, final Collection<Chunk> consumer) {
final long size = data.getSize();
final TreeChunk newChunk;
while (depth > 0 && size < treeSize) {
treeSize /= branches;
depth--;
}
if (depth == 0) {
newChunk = new TreeChunk((int) size); // safe to cast since leaf chunk size < 2Gb
data.read(newChunk.getData(), newChunk.getDataOffset());
} else {
// intermediate chunk containing child nodes hashes
final int branchCnt = (int) ((size + treeSize - 1) / treeSize);
final HashesChunk hChunk = new HashesChunk(size);
long pos = 0;
long secSize;
// TODO the loop can be parallelized
for (int i = 0; i < branchCnt; i++) {
// the last item can have shorter data
if (size-pos < treeSize) {
secSize = size - pos;
} else {
secSize = treeSize;
}
// take the section of the data corresponding encoded in the subTree
final SectionReader subTreeData = new SlicedReader(data, pos, secSize);
// the hash of that data
final Key subTreeKey = splitImpl(depth - 1, treeSize / branches, subTreeData, consumer);
hChunk.setKey(i, subTreeKey);
pos += treeSize;
}
// now we got the hashes in the chunk, then hash the chunk
newChunk = hChunk;
}
consumer.add(newChunk);
// report hash of this chunk one level up (keys corresponds to the proper subslice of the parent chunk)x
return newChunk.getKey();
}
@Override
public SectionReader join(final ChunkStore chunkStore, final Key key) {
return new LazyChunkReader(chunkStore, key);
}
@Override
public long keySize() {
return hashSize;
}
// @NotNull
// @Override
// public Key split(@NotNull SectionReader sectionReader, @NotNull Collection<? extends Chunk> consumer) {
// return null;
// }
/**
* A 'subReader'
*/
public static class SlicedReader implements SectionReader {
final SectionReader delegate;
final long offset;
final long len;
public SlicedReader(final SectionReader delegate, final long offset, final long len) {
this.delegate = delegate;
this.offset = offset;
this.len = len;
}
@Override
public long seek(final long offset, final int whence) {
return delegate.seek(this.offset + offset, whence);
}
@Override
public int read(final byte[] dest, final int destOff) {
return delegate.readAt(dest, destOff, offset);
}
@Override
public int readAt(final byte[] dest, final int destOff, final long readerOffset) {
return delegate.readAt(dest, destOff, offset + readerOffset);
}
@Override
public long getSize() {
return len;
}
}
public class TreeChunk extends Chunk {
private static final int DATA_OFFSET = 8;
public TreeChunk(final int dataSize) {
super(null, new byte[DATA_OFFSET + dataSize]);
setSubtreeSize(dataSize);
}
public TreeChunk(final Chunk chunk) {
super(chunk.getKey(), chunk.getData());
}
public long getSubtreeSize() {
return ByteBuffer.wrap(getData()).order(ByteOrder.LITTLE_ENDIAN).getLong(0);
}
public void setSubtreeSize(final long size) {
ByteBuffer.wrap(getData()).order(ByteOrder.LITTLE_ENDIAN).putLong(0, size);
}
public int getDataOffset() {
return DATA_OFFSET;
}
public Key getKey() {
if (key == null) {
key = new Key(hasher.digest(getData()));
}
return key;
}
@Override
public String toString() {
final String dataString = ByteUtil.toHexString(
Arrays.copyOfRange(getData(), getDataOffset(), getDataOffset() + 16)) + "...";
return "TreeChunk[" + getSubtreeSize() + ", " + getKey() + ", " + dataString + "]";
}
}
public class HashesChunk extends TreeChunk {
public HashesChunk(final long subtreeSize) {
super(branches * hashSize);
setSubtreeSize(subtreeSize);
}
public HashesChunk(final Chunk chunk) {
super(chunk);
}
public int getKeyCount() {
return branches;
}
public Key getKey(final int idx) {
final int off = getDataOffset() + idx * hashSize;
return new Key(Arrays.copyOfRange(getData(), off, off + hashSize));
}
public void setKey(final int idx, final Key key) {
final int off = getDataOffset() + idx * hashSize;
System.arraycopy(key.getBytes(), 0, getData(), off, hashSize);
}
@Override
public String toString() {
final StringBuilder hashes = new StringBuilder("{");
for (int i = 0; i < getKeyCount(); i++) {
hashes.append(i == 0 ? "" : ", ").append(getKey(i));
}
hashes.append("}");
return "HashesChunk[" + getSubtreeSize() + ", " + getKey() + ", " + hashes + "]";
}
}
private class TreeSize {
int depth;
long treeSize;
public TreeSize(final long dataSize) {
treeSize = chunkSize;
for (; treeSize < dataSize; treeSize *= branches) {
depth++;
}
}
}
private class LazyChunkReader implements SectionReader {
final long size;
final Chunk root;
final Key key;
final ChunkStore chunkStore;
public LazyChunkReader(final ChunkStore chunkStore, final Key key) {
this.chunkStore = chunkStore;
this.key = key;
root = chunkStore.get(key);
this.size = new TreeChunk(root).getSubtreeSize();
}
@Override
public int readAt(final byte[] dest, final int destOff, final long readerOffset) {
final int size = dest.length - destOff;
final TreeSize ts = new TreeSize(this.size);
return readImpl(dest, destOff, root, ts.treeSize, 0, readerOffset,
readerOffset + min(size, this.size - readerOffset));
}
private int readImpl(final byte[] dest, final int destOff, final Chunk chunk, final long chunkWidth, final long chunkStart,
final long readStart, final long readEnd) {
final long chunkReadStart = max(readStart - chunkStart, 0);
final long chunkReadEnd = min(chunkWidth, readEnd - chunkStart);
int ret = 0;
if (chunkWidth > chunkSize) {
final long subChunkWidth = chunkWidth / branches;
if (chunkReadStart >= chunkWidth || chunkReadEnd <= 0) {
throw new RuntimeException("Not expected.");
}
final int startSubChunk = (int) (chunkReadStart / subChunkWidth);
final int lastSubChunk = (int) ((chunkReadEnd - 1) / subChunkWidth);
// TODO the loop can be parallelized
for (int i = startSubChunk; i <= lastSubChunk; i++) {
final HashesChunk hChunk = new HashesChunk(chunk);
final Chunk subChunk = chunkStore.get(hChunk.getKey(i));
ret += readImpl(dest, (int) (destOff + (i - startSubChunk) * subChunkWidth),
subChunk, subChunkWidth, chunkStart + i * subChunkWidth, readStart, readEnd);
}
} else {
final TreeChunk dataChunk = new TreeChunk(chunk);
ret = (int) (chunkReadEnd - chunkReadStart);
System.arraycopy(dataChunk.getData(), (int) (dataChunk.getDataOffset() + chunkReadStart),
dest, destOff, ret);
}
return ret;
}
@Override
public long seek(final long offset, final int whence) {
throw new RuntimeException("Not implemented");
}
@Override
public long getSize() {
return size;
}
@Override
public int read(final byte[] dest, final int destOff) {
return readAt(dest, destOff, 0);
}
}
}
| |
/*******************************************************************************
* PathVisio, a tool for data visualization and analysis using biological pathways
* Copyright 2006-2021 BiGCaT Bioinformatics, WikiPathways
*
* 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.pathvisio.model;
import java.io.File;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import org.bridgedb.DataSource;
import org.bridgedb.Xref;
import org.pathvisio.event.PathwayModelEvent;
import org.pathvisio.event.PathwayModelListener;
import org.pathvisio.event.PathwayObjectEvent;
import org.pathvisio.event.PathwayObjectListener;
import org.pathvisio.model.GraphLink.LinkableTo;
import org.pathvisio.model.type.DataNodeType;
import junit.framework.TestCase;
/**
*
* @author unknown
*/
public class Test extends TestCase implements PathwayModelListener, PathwayObjectListener {
PathwayModel data;
DataNode o;
List<PathwayModelEvent> received;
List<PathwayObjectEvent> receivedElementEvents;
Interaction l;
public void setUp() {
data = new PathwayModel();
data.addListener(this);
o = new DataNode("", DataNodeType.UNDEFINED);
received = new ArrayList<PathwayModelEvent>();
receivedElementEvents = new ArrayList<PathwayObjectEvent>();
o.addListener(this);
data.add(o);
l = new Interaction();
data.add(l);
received.clear();
receivedElementEvents.clear();
}
public void testFields() {
o.setCenterX(1.0);
assertEquals("test set/get CenterX", 1.0, o.getCenterX(), 0.0001);
assertEquals("Setting CenterX should generate single event", receivedElementEvents.size(), 1);
assertEquals("test getProperty()", 1.0, o.getCenterX(), 0.0001);
// try {
// o.setCenterX(null);
// fail("Setting centerx property to null should generate exception");
// } catch (Exception e) {
// }
// however, you should be able to set graphRef to null
assertNull("graphref null by default", l.getStartElementRef());
l.setStartElementRef(null);
assertNull("can set graphRef to null", l.getStartElementRef());
}
// public void testProperties() throws IOException, ConverterException {
// // set 10 dynamic properties in two ways
// for (int i = 0; i < 5; ++i) {
// o.setDynamicProperty("Hello" + i, "World" + i);
// }
// for (int i = 5; i < 10; ++i) {
// o.setPropertyEx("Hello" + i, "World" + i);
// }
//
// // check contents of dynamic properties
// assertEquals("World0", o.getDynamicProperty("Hello0"));
// for (int i = 0; i < 10; ++i) {
// assertEquals("World" + i, o.getDynamicProperty("Hello" + i));
// }
//
// // check non-existing dynamic property
//
// assertNull(o.getDynamicProperty("NonExistingProperty"));
//
// // check that we have 10 dynamic properties, no more, no less.
// Set<String> dynamicKeys = o.getDynamicPropertyKeys();
// assertEquals(10, dynamicKeys.size());
//
// // check that superset dynamic + static also contains dynamic properties
// assertEquals("World0", o.getPropertyEx("Hello0"));
// for (int i = 0; i < 10; ++i) {
// assertEquals("World" + i, o.getPropertyEx("Hello" + i));
// }
//
// // check setting null property
// try {
// o.setStaticProperty(null, new Object());
// fail("Setting null property should generate exception");
// } catch (NullPointerException e) {
// }
//
// // check setting non string / StaticProperty property
// try {
// o.setPropertyEx(new Object(), new Object());
// fail("Using key that is not String or StaticProperty should generate exception");
// } catch (IllegalArgumentException e) {
// }
//
// // test storage of dynamic properties
// File temp = File.createTempFile("dynaprops.test", ".gpml");
// temp.deleteOnExit();
//
// // set an id on this element so we can find it back easily
// String id = o.setGeneratedElementId();
//
// // store
// data.writeToXml(temp, false);
//
// // and read back
// PathwayModel p2 = new PathwayModel();
// p2.readFromXml(temp, true);
//
// // get same datanode back
// DataNode o2 = (DataNode) p2.getPathwayObject(id);
// // check that it still has the dynamic properties after storing / reading
// assertEquals("World5", o2.getDynamicProperty("Hello5"));
// assertEquals("World3", o2.getPropertyEx("Hello3"));
// // sanity check: no non-existing properties
// assertNull(o2.getDynamicProperty("NonExistingProperty"));
// assertNull(o2.getPropertyEx("NonExistingProperty"));
//
// // check that dynamic properties are copied.
// PathwayElement o3 = o2.copy();
// assertEquals("World7", o3.getPropertyEx("Hello7"));
//
// // check that it's a deep copy
// o2.setDynamicProperty("Hello7", "Something other than 'World7'");
// assertEquals("World7", o3.getPropertyEx("Hello7"));
// assertEquals("Something other than 'World7'", o2.getPropertyEx("Hello7"));
// }
public void testColor() {
try {
o.setTextColor(null);
o.setBorderColor(null);
fail("Shouldn't be able to set color null");
} catch (Exception e) {
}
}
public void testParent() {
// remove
data.remove(o);
assertNull("removing object set parents null", o.getPathwayModel());
assertEquals(received.size(), 1);
assertEquals("Event type should be DELETED", received.get(0).getType(), PathwayModelEvent.DELETED);
// re-add
data.add(o);
assertEquals("adding sets parent", o.getPathwayModel(), data);
assertEquals(received.size(), 2);
assertEquals("Event type should be ADDED", received.get(1).getType(), PathwayModelEvent.ADDED);
}
/**
* Test graphRef's and graphId's
*
*/
public void testRef() {
assertTrue("query non-existing list of ref", data.getReferringLinkableFroms(o).size() == 0);
// create link
l.setStartElementRef(o);
assertTrue("reference created", data.getReferringLinkableFroms(o).contains(l.getStartLinePoint()));
l.setStartElementRef(null);
assertTrue("reference removed", data.getReferringLinkableFroms(o).size() == 0);
DataNode o2 = new DataNode("", DataNodeType.UNDEFINED);
data.add(o2);
// create link in opposite order
l.setEndElementRef(o);
assertTrue("reference created (2)", data.getReferringLinkableFroms(o).contains(l.getEndLinePoint()));
}
/**
* test that Xref and XrefWithSymbol obey the equals contract
*/
public void testXRefEquals() {
Object[] testList = new Object[] { new Xref("1007_at", DataSource.getExistingByFullName("Affy")),
new Xref("3456", DataSource.getExistingByFullName("Affy")),
new Xref("1007_at", DataSource.getExistingByFullName("Entrez Gene")),
new Xref("3456", DataSource.getExistingByFullName("Entrez Gene")),
new Xref("3456", DataSource.getExistingByFullName("Entrez Gene")),
new Xref("3456", DataSource.getExistingByFullName("Entrez Gene")), // TODO
new Xref("3456", DataSource.getExistingByFullName("Entrez Gene")), }; // TODO
for (int i = 0; i < testList.length; ++i) {
Object refi = testList[i];
// equals must be reflexive
assertTrue(refi.equals(refi));
// never equal to null
assertFalse(refi.equals(null));
}
for (int i = 1; i < testList.length; ++i)
for (int j = 0; j < i; ++j) {
// equals must be symmetric
Object refi = testList[i];
Object refj = testList[j];
assertEquals("Symmetry fails for " + refj + " and " + refi, refi.equals(refj), refj.equals(refi));
// hashcode contract
if (refi.equals(refj)) {
assertEquals(refi.hashCode(), refj.hashCode());
}
}
// equals must be transitive
for (int i = 2; i < testList.length; ++i)
for (int j = 1; j < i; ++j)
for (int k = 0; k < j; ++k) {
Object refi = testList[i];
Object refj = testList[j];
Object refk = testList[k];
if (refi.equals(refj) && refj.equals(refk)) {
assertTrue(refk.equals(refi));
}
if (refj.equals(refk) && refk.equals(refi)) {
assertTrue(refi.equals(refj));
}
if (refk.equals(refi) && refi.equals(refj)) {
assertTrue(refk.equals(refj));
}
}
}
// /**
// * Test for maintaining list of unique id's per Pathway.
// *
// */
// public void testRefUniq() {
// String src = "123123";
// String s1 = src.substring(3, 6);
// String s2 = src.substring(0, 3);
// assertFalse("s1 should not be the same reference as s2", s1 == s2);
// assertTrue("s1 should be equal to s2", s1.equals(s2));
//
// // test for uniqueness
// o.setElementId(s1);
//
// PathwayElement o2 = new DataNode("", DataNodeType.UNDEFINED);
// data.add(o2);
// assertSame(o.getPathwayModel(), o2.getPathwayModel());
// assertEquals("Setting graphId on first element", o.getElementId(), "123");
// try {
// o2.setElementId(s2);
// // try setting the same id again
// fail("shouldn't be able to set the same id twice");
// } catch (IllegalArgumentException e) {
// }
//
// // test random id
// String x = data.getUniqueElementId();
// try {
// // test that we can use it as unique id
// o.setElementId(x);
// assertEquals(x, o.getElementId());
// // test that we can't use the same id twice
// o2.setElementId(x);
// fail("shouldn't be able to set the same id twice");
// } catch (IllegalArgumentException e) {
// }
//
// // test that a second random id is unique again
// x = data.getUniqueElementId();
// o2.setElementId(x);
// assertEquals(x, o2.getElementId());
//
// // test setting id first, then parent
// PathwayElement o3 = new DataNode("", DataNodeType.UNDEFINED);
// x = data.getUniqueElementId();
// o3.setElementId(x);
// data.add(o3);
// assertEquals(o3.getElementId(), x);
//
// try {
// PathwayElement o4 = new DataNode("", DataNodeType.UNDEFINED);
// // try setting the same id again
// o4.setElementId(x);
// data.add(o4);
// fail("shouldn't be able to set the same id twice");
// } catch (IllegalArgumentException e) {
// }
// }
public void testRef2() {
o.setElementId("1");
LinkableTo o2 = new DataNode("", DataNodeType.UNDEFINED);
// note: parent not set yet!
data.add((PathwayObject) o2); // reference should now be created
assertNull("default endGraphRef is null", l.getEndElementRef());
l.setEndElementRef(o2);
assertTrue("reference created through adding",
data.getReferringLinkableFroms(o2).contains(l.getEndLinePoint()));
}
public void testWrongFormat() {
try {
String inputFile = "test.mapp";
URL url = Thread.currentThread().getContextClassLoader().getResource(inputFile);
File fTest = new File(url.getPath());
data.readFromXml(fTest, false);
fail("Loading wrong format, Exception expected");
} catch (Exception e) {
}
}
// // bug 440: valid gpml file is rejected
// // because it doesn't contain Pathway.Graphics
// public void testBug440() throws ConverterException {
// try {
// data.readFromXml(new File(PATHVISIO_BASEDIR, "testData/nographics-test.gpml"), false);
// } catch (ConverterException e) {
// fail("No converter exception expected");
// }
// }
/**
* Test that there is one and only one Pathway object
*
*/
public void testMappInfo() {
Pathway mi;
// pathway is created and set when a pathway model is first created.
// pathway is not added to the pathway objects list of the pathway model
mi = data.getPathway();
assertNotNull(mi);
// there should always be one and only one pathway, and it cannot be removed
try {
data.remove(mi);
fail("Shouldn't be able to remove mappinfo object!");
} catch (IllegalArgumentException e) {
}
}
// event listener
// receives events generated on objects o and data
public void gmmlObjectModified(PathwayModelEvent e) {
// store all received events
received.add(e);
}
public void gmmlObjectModified(PathwayObjectEvent e) {
receivedElementEvents.add(e);
}
public void pathwayModified(PathwayModelEvent e) {
gmmlObjectModified(e);
}
}
| |
/*
*
* Copyright 2015 Netflix, 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.netflix.genie.common.model;
import com.netflix.genie.common.exceptions.GeniePreconditionException;
import com.wordnik.swagger.annotations.ApiModelProperty;
import org.hibernate.validator.constraints.NotBlank;
import javax.persistence.Basic;
import javax.persistence.Column;
import javax.persistence.MappedSuperclass;
import java.util.Set;
/**
* The common entity fields for all Genie entities.
*
* @author amsharma
* @author tgianos
*/
@MappedSuperclass
public class CommonEntityFields extends Auditable {
/**
* The namespace to use for genie specific tags.
*/
protected static final String GENIE_TAG_NAMESPACE = "genie.";
/**
* The namespace to use for the id.
*/
protected static final String GENIE_ID_TAG_NAMESPACE = GENIE_TAG_NAMESPACE + "id:";
/**
* The namespace to use for the name.
*/
protected static final String GENIE_NAME_TAG_NAMESPACE = GENIE_TAG_NAMESPACE + "name:";
private static final int MAX_ID_TAG_NAMESPACE = 1;
private static final int MAX_NAME_TAG_NAMESPACE = 1;
private static final int MAX_TAG_GENIE_NAMESPACE = 2;
/**
* Version of this entity.
*/
@Basic(optional = false)
@Column(name = "version")
@ApiModelProperty(
value = "The version number",
required = true
)
@NotBlank(message = "Version is missing and is required.")
private String version;
/**
* User who created this entity.
*/
@Basic(optional = false)
@ApiModelProperty(
value = "User who created/owns this object",
required = true
)
@NotBlank(message = "User name is missing and is required.")
private String user;
/**
* Name of this entity.
*/
@Basic(optional = false)
@ApiModelProperty(
value = "The name to use",
required = true
)
@NotBlank(message = "Name is missing and is required.")
private String name;
/**
* Default constructor.
*/
public CommonEntityFields() {
super();
}
/**
* Construct a new CommonEntity Object with all required parameters.
*
* @param name The name of the entity. Not null/empty/blank.
* @param user The user who created the entity. Not null/empty/blank.
* @param version The version of this entity. Not null/empty/blank.
*/
public CommonEntityFields(
final String name,
final String user,
final String version) {
super();
this.name = name;
this.user = user;
this.version = version;
}
/**
* Gets the version of this entity.
*
* @return version
*/
public String getVersion() {
return this.version;
}
/**
* Sets the version for this entity.
*
* @param version version number for this entity
*/
public void setVersion(final String version) {
this.version = version;
}
/**
* Gets the user that created this entity.
*
* @return user
*/
public String getUser() {
return this.user;
}
/**
* Sets the user who created this entity.
*
* @param user user who created this entity. Not null/empty/blank.
*/
public void setUser(final String user) {
this.user = user;
}
/**
* Gets the name for this entity.
*
* @return name
*/
public String getName() {
return name;
}
/**
* Sets the name for this entity.
*
* @param name the new name of this entity. Not null/empty/blank
*/
public void setName(final String name) {
this.name = name;
}
/**
* Reusable method for adding the system tags to the set of tags.
*
* @param tags The tags to add the system tags to.
* @throws GeniePreconditionException If a precondition is violated.
*/
protected void addAndValidateSystemTags(final Set<String> tags) throws GeniePreconditionException {
if (tags == null) {
throw new GeniePreconditionException("No tags entered. Unable to continue.");
}
// Add Genie tags to the app and make sure if old ones existed they're removed
tags.add(GENIE_ID_TAG_NAMESPACE + this.getId());
String oldNameTag = null;
for (final String tag : tags) {
if (tag.startsWith(GENIE_NAME_TAG_NAMESPACE)
&& !tag.equalsIgnoreCase(GENIE_NAME_TAG_NAMESPACE + this.name)) {
oldNameTag = tag;
break;
}
}
if (oldNameTag != null) {
tags.remove(oldNameTag);
}
tags.add(GENIE_NAME_TAG_NAMESPACE + this.name);
int genieNameSpaceCount = 0;
int genieIdTagCount = 0;
int genieNameTagCount = 0;
for (final String tag : tags) {
if (tag.contains(GENIE_TAG_NAMESPACE)) {
genieNameSpaceCount++;
if (tag.contains(GENIE_ID_TAG_NAMESPACE)) {
genieIdTagCount++;
} else if (tag.contains(GENIE_NAME_TAG_NAMESPACE)) {
genieNameTagCount++;
}
}
}
if (genieIdTagCount > MAX_ID_TAG_NAMESPACE) {
throw new GeniePreconditionException(
"More Genie id namespace tags encountered ("
+ genieIdTagCount
+ ") than expected ("
+ MAX_ID_TAG_NAMESPACE
+ ")."
);
}
if (genieNameTagCount > MAX_NAME_TAG_NAMESPACE) {
throw new GeniePreconditionException(
"More Genie name namespace tags encountered ("
+ genieNameTagCount
+ ") than expected ("
+ MAX_NAME_TAG_NAMESPACE
+ ")."
);
}
if (genieNameSpaceCount > MAX_TAG_GENIE_NAMESPACE) {
throw new GeniePreconditionException(
"More Genie namespace tags encountered ("
+ genieNameSpaceCount
+ ") than expected ("
+ MAX_TAG_GENIE_NAMESPACE
+ ")."
);
}
}
}
| |
/*
* Copyright (C) 2017 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 io.codetail.animation;
import android.os.Looper;
import android.util.AndroidRuntimeException;
/**
* SpringAnimation is an animation that is driven by a {@link SpringForce}. The spring force defines
* the spring's stiffness, damping ratio, as well as the rest position. Once the SpringAnimation is
* started, on each frame the spring force will update the animation's value and velocity.
* The animation will continue to run until the spring force reaches equilibrium. If the spring used
* in the animation is undamped, the animation will never reach equilibrium. Instead, it will
* oscillate forever.
*/
final class SpringAnimation extends DynamicAnimation<SpringAnimation> {
private SpringForce mSpring = null;
private float mPendingPosition = UNSET;
private static final float UNSET = Float.MAX_VALUE;
/**
* This creates a SpringAnimation that animates the property of the given view.
* Note, a spring will need to setup through {@link #setSpring(SpringForce)} before
* the animation starts.
*
* @param v The View whose property will be animated
* @param property the property index of the view
*/
public <T> SpringAnimation(T v, Property<T> property) {
super(v, property);
}
/**
* This creates a SpringAnimation that animates the property of the given view. A Spring will be
* created with the given final position and default stiffness and damping ratio.
* This spring can be accessed and reconfigured through {@link #setSpring(SpringForce)}.
*
* @param v The View whose property will be animated
* @param property the property index of the view
* @param finalPosition the final position of the spring to be created.
*/
public <T> SpringAnimation(T v, Property<T> property, float finalPosition) {
super(v, property);
mSpring = new SpringForce(finalPosition);
setSpringThreshold();
}
/**
* Returns the spring that the animation uses for animations.
*
* @return the spring that the animation uses for animations
*/
public SpringForce getSpring() {
return mSpring;
}
/**
* Uses the given spring as the force that drives this animation. If this spring force has its
* parameters re-configured during the animation, the new configuration will be reflected in the
* animation immediately.
*
* @param force a pre-defined spring force that drives the animation
* @return the animation that the spring force is set on
*/
public SpringAnimation setSpring(SpringForce force) {
mSpring = force;
setSpringThreshold();
return this;
}
@Override
public void start() {
sanityCheck();
super.start();
}
/**
* Updates the final position of the spring.
* <p/>
* When the animation is running, calling this method would assume the position change of the
* spring as a continuous movement since last frame, which yields more accurate results than
* changing the spring position directly through {@link SpringForce#setFinalPosition(float)}.
* <p/>
* If the animation hasn't started, calling this method will change the spring position, and
* immediately start the animation.
*
* @param finalPosition rest position of the spring
*/
public void animateToFinalPosition(float finalPosition) {
if (isRunning()) {
mPendingPosition = finalPosition;
} else {
if (mSpring == null) {
mSpring = new SpringForce(finalPosition);
}
mSpring.setFinalPosition(finalPosition);
start();
}
}
/**
* Skips to the end of the animation. If the spring is undamped, an
* {@link IllegalStateException} will be thrown, as the animation would never reach to an end.
* It is recommended to check {@link #canSkipToEnd()} before calling this method. This method
* should only be called on main thread. If animation is not running, no-op.
*
* @throws IllegalStateException if the spring is undamped (i.e. damping ratio = 0)
* @throws AndroidRuntimeException if this method is not called on the main thread
*/
public void skipToEnd() {
if (!canSkipToEnd()) {
throw new UnsupportedOperationException("Spring animations can only come to an end"
+ " when there is damping");
}
if (Looper.myLooper() != Looper.getMainLooper()) {
throw new AndroidRuntimeException("Animations may only be started on the main thread");
}
if (mRunning) {
if (mPendingPosition != UNSET) {
mSpring.setFinalPosition(mPendingPosition);
mPendingPosition = UNSET;
}
mValue = mSpring.getFinalPosition();
mVelocity = 0;
cancel();
}
}
/**
* Queries whether the spring can eventually come to the rest position.
*
* @return {@code true} if the spring is damped, otherwise {@code false}
*/
public boolean canSkipToEnd() {
return mSpring.mDampingRatio > 0;
}
/************************ Below are private APIs *************************/
private void setSpringThreshold() {
if (mViewProperty == ROTATION || mViewProperty == ROTATION_X
|| mViewProperty == ROTATION_Y) {
mSpring.setDefaultThreshold(SpringForce.VALUE_THRESHOLD_ROTATION);
} else if (mViewProperty == ALPHA) {
mSpring.setDefaultThreshold(SpringForce.VALUE_THRESHOLD_ALPHA);
} else if (mViewProperty == SCALE_X || mViewProperty == SCALE_Y) {
mSpring.setDefaultThreshold(SpringForce.VALUE_THRESHOLD_SCALE);
} else {
mSpring.setDefaultThreshold(SpringForce.VALUE_THRESHOLD_IN_PIXEL);
}
}
private void sanityCheck() {
if (mSpring == null) {
throw new UnsupportedOperationException("Incomplete SpringAnimation: Either final"
+ " position or a spring force needs to be set.");
}
double finalPosition = mSpring.getFinalPosition();
if (finalPosition > mMaxValue) {
throw new UnsupportedOperationException("Final position of the spring cannot be greater"
+ " than the max value.");
} else if (finalPosition < mMinValue) {
throw new UnsupportedOperationException("Final position of the spring cannot be less"
+ " than the min value.");
}
}
@Override
boolean updateValueAndVelocity(long deltaT) {
if (mPendingPosition != UNSET) {
double lastPosition = mSpring.getFinalPosition();
// Approximate by considering half of the time spring position stayed at the old
// position, half of the time it's at the new position.
SpringForce.MassState massState = mSpring.updateValues(mValue, mVelocity, deltaT / 2);
mSpring.setFinalPosition(mPendingPosition);
mPendingPosition = UNSET;
massState = mSpring.updateValues(massState.mValue, massState.mVelocity, deltaT / 2);
mValue = massState.mValue;
mVelocity = massState.mVelocity;
} else {
SpringForce.MassState massState = mSpring.updateValues(mValue, mVelocity, deltaT);
mValue = massState.mValue;
mVelocity = massState.mVelocity;
}
mValue = Math.max(mValue, mMinValue);
mValue = Math.min(mValue, mMaxValue);
if (isAtEquilibrium(mValue, mVelocity)) {
mValue = mSpring.getFinalPosition();
mVelocity = 0f;
return true;
}
return false;
}
@Override
float getAcceleration(float value, float velocity) {
return mSpring.getAcceleration(value, velocity);
}
@Override
boolean isAtEquilibrium(float value, float velocity) {
return mSpring.isAtEquilibrium(value, velocity);
}
}
| |
/**
* 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.hbase.snapshot;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import java.io.IOException;
import java.net.URI;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.HashSet;
import java.util.Set;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.FileStatus;
import org.apache.hadoop.fs.FileUtil;
import org.apache.hadoop.fs.FSDataOutputStream;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.hbase.HBaseTestingUtility;
import org.apache.hadoop.hbase.HColumnDescriptor;
import org.apache.hadoop.hbase.HConstants;
import org.apache.hadoop.hbase.HRegionInfo;
import org.apache.hadoop.hbase.HTableDescriptor;
import org.apache.hadoop.hbase.KeyValue;
import org.apache.hadoop.hbase.MediumTests;
import org.apache.hadoop.hbase.MiniHBaseCluster;
import org.apache.hadoop.hbase.master.snapshot.SnapshotManager;
import org.apache.hadoop.hbase.client.HBaseAdmin;
import org.apache.hadoop.hbase.client.HTable;
import org.apache.hadoop.hbase.util.Bytes;
import org.apache.hadoop.hbase.util.FSUtils;
import org.apache.hadoop.hbase.util.Pair;
import org.apache.hadoop.hbase.protobuf.generated.HBaseProtos.SnapshotDescription;
import org.apache.hadoop.hbase.regionserver.HRegion;
import org.apache.hadoop.hbase.snapshot.ExportSnapshot;
import org.apache.hadoop.hbase.snapshot.SnapshotReferenceUtil;
import org.apache.hadoop.mapreduce.Job;
import org.junit.After;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import org.junit.experimental.categories.Category;
/**
* Test Export Snapshot Tool
*/
@Category(MediumTests.class)
public class TestExportSnapshot {
private final Log LOG = LogFactory.getLog(getClass());
private final static HBaseTestingUtility TEST_UTIL = new HBaseTestingUtility();
private final static byte[] FAMILY = Bytes.toBytes("cf");
private byte[] emptySnapshotName;
private byte[] snapshotName;
private byte[] tableName;
private HBaseAdmin admin;
@BeforeClass
public static void setUpBeforeClass() throws Exception {
TEST_UTIL.getConfiguration().setBoolean(SnapshotManager.HBASE_SNAPSHOT_ENABLED, true);
TEST_UTIL.getConfiguration().setInt("hbase.regionserver.msginterval", 100);
TEST_UTIL.getConfiguration().setInt("hbase.client.pause", 250);
TEST_UTIL.getConfiguration().setInt("hbase.client.retries.number", 6);
TEST_UTIL.getConfiguration().setBoolean("hbase.master.enabletable.roundrobin", true);
TEST_UTIL.startMiniCluster(3);
}
@AfterClass
public static void tearDownAfterClass() throws Exception {
TEST_UTIL.shutdownMiniCluster();
}
/**
* Create a table and take a snapshot of the table used by the export test.
*/
@Before
public void setUp() throws Exception {
this.admin = TEST_UTIL.getHBaseAdmin();
long tid = System.currentTimeMillis();
tableName = Bytes.toBytes("testtb-" + tid);
snapshotName = Bytes.toBytes("snaptb0-" + tid);
emptySnapshotName = Bytes.toBytes("emptySnaptb0-" + tid);
// create Table
HTableDescriptor htd = new HTableDescriptor(tableName);
htd.addFamily(new HColumnDescriptor(FAMILY));
admin.createTable(htd, null);
// Take an empty snapshot
admin.snapshot(emptySnapshotName, tableName);
// Add some rows
HTable table = new HTable(TEST_UTIL.getConfiguration(), tableName);
TEST_UTIL.loadTable(table, FAMILY);
// take a snapshot
admin.snapshot(snapshotName, tableName);
}
@After
public void tearDown() throws Exception {
admin.disableTable(tableName);
admin.deleteSnapshot(snapshotName);
admin.deleteSnapshot(emptySnapshotName);
admin.deleteTable(tableName);
admin.close();
}
/**
* Verfy the result of getBalanceSplits() method.
* The result are groups of files, used as input list for the "export" mappers.
* All the groups should have similar amount of data.
*
* The input list is a pair of file path and length.
* The getBalanceSplits() function sort it by length,
* and assign to each group a file, going back and forth through the groups.
*/
@Test
public void testBalanceSplit() throws Exception {
// Create a list of files
List<Pair<Path, Long>> files = new ArrayList<Pair<Path, Long>>();
for (long i = 0; i <= 20; i++) {
files.add(new Pair<Path, Long>(new Path("file-" + i), i));
}
// Create 5 groups (total size 210)
// group 0: 20, 11, 10, 1 (total size: 42)
// group 1: 19, 12, 9, 2 (total size: 42)
// group 2: 18, 13, 8, 3 (total size: 42)
// group 3: 17, 12, 7, 4 (total size: 42)
// group 4: 16, 11, 6, 5 (total size: 42)
List<List<Path>> splits = ExportSnapshot.getBalancedSplits(files, 5);
assertEquals(5, splits.size());
assertEquals(Arrays.asList(new Path("file-20"), new Path("file-11"),
new Path("file-10"), new Path("file-1"), new Path("file-0")), splits.get(0));
assertEquals(Arrays.asList(new Path("file-19"), new Path("file-12"),
new Path("file-9"), new Path("file-2")), splits.get(1));
assertEquals(Arrays.asList(new Path("file-18"), new Path("file-13"),
new Path("file-8"), new Path("file-3")), splits.get(2));
assertEquals(Arrays.asList(new Path("file-17"), new Path("file-14"),
new Path("file-7"), new Path("file-4")), splits.get(3));
assertEquals(Arrays.asList(new Path("file-16"), new Path("file-15"),
new Path("file-6"), new Path("file-5")), splits.get(4));
}
/**
* Verify if exported snapshot and copied files matches the original one.
*/
@Test
public void testExportFileSystemState() throws Exception {
testExportFileSystemState(tableName, snapshotName, 2);
}
@Test
public void testEmptyExportFileSystemState() throws Exception {
testExportFileSystemState(tableName, emptySnapshotName, 1);
}
/**
* Mock a snapshot with files in the archive dir,
* two regions, and one reference file.
*/
@Test
public void testSnapshotWithRefsExportFileSystemState() throws Exception {
Configuration conf = TEST_UTIL.getConfiguration();
final byte[] tableWithRefsName = Bytes.toBytes("tableWithRefs");
final String snapshotName = "tableWithRefs";
final String TEST_FAMILY = Bytes.toString(FAMILY);
final String TEST_HFILE = "abc";
final SnapshotDescription sd = SnapshotDescription.newBuilder()
.setName(snapshotName).setTable(Bytes.toString(tableWithRefsName)).build();
FileSystem fs = TEST_UTIL.getHBaseCluster().getMaster().getMasterFileSystem().getFileSystem();
Path rootDir = TEST_UTIL.getHBaseCluster().getMaster().getMasterFileSystem().getRootDir();
Path archiveDir = new Path(rootDir, HConstants.HFILE_ARCHIVE_DIRECTORY);
HTableDescriptor htd = new HTableDescriptor(tableWithRefsName);
htd.addFamily(new HColumnDescriptor(TEST_FAMILY));
// First region, simple with one plain hfile.
HRegion r0 = HRegion.createHRegion(new HRegionInfo(htd.getName()), archiveDir,
conf, htd, null, true, true);
Path storeFile = new Path(new Path(r0.getRegionDir(), TEST_FAMILY), TEST_HFILE);
FSDataOutputStream out = fs.create(storeFile);
out.write(Bytes.toBytes("Test Data"));
out.close();
r0.close();
// Second region, used to test the split case.
// This region contains a reference to the hfile in the first region.
HRegion r1 = HRegion.createHRegion(new HRegionInfo(htd.getName()), archiveDir,
conf, htd, null, true, true);
out = fs.create(new Path(new Path(r1.getRegionDir(), TEST_FAMILY),
storeFile.getName() + '.' + r0.getRegionInfo().getEncodedName()));
out.write(Bytes.toBytes("Test Data"));
out.close();
r1.close();
Path tableDir = HTableDescriptor.getTableDir(archiveDir, tableWithRefsName);
Path snapshotDir = SnapshotDescriptionUtils.getCompletedSnapshotDir(snapshotName, rootDir);
FileUtil.copy(fs, tableDir, fs, snapshotDir, false, conf);
SnapshotDescriptionUtils.writeSnapshotInfo(sd, snapshotDir, fs);
testExportFileSystemState(tableWithRefsName, Bytes.toBytes(snapshotName), 2);
}
/**
* Test ExportSnapshot
*/
private void testExportFileSystemState(final byte[] tableName, final byte[] snapshotName,
int filesExpected) throws Exception {
Path copyDir = TEST_UTIL.getDataTestDir("export-" + System.currentTimeMillis());
URI hdfsUri = FileSystem.get(TEST_UTIL.getConfiguration()).getUri();
FileSystem fs = FileSystem.get(copyDir.toUri(), new Configuration());
copyDir = copyDir.makeQualified(fs);
// Export Snapshot
int res = ExportSnapshot.innerMain(TEST_UTIL.getConfiguration(), new String[] {
"-snapshot", Bytes.toString(snapshotName),
"-copy-to", copyDir.toString()
});
assertEquals(0, res);
// Verify File-System state
FileStatus[] rootFiles = fs.listStatus(copyDir);
assertEquals(filesExpected, rootFiles.length);
for (FileStatus fileStatus: rootFiles) {
String name = fileStatus.getPath().getName();
assertTrue(fileStatus.isDir());
assertTrue(name.equals(HConstants.SNAPSHOT_DIR_NAME) || name.equals(".archive"));
}
// compare the snapshot metadata and verify the hfiles
final FileSystem hdfs = FileSystem.get(hdfsUri, TEST_UTIL.getConfiguration());
final Path snapshotDir = new Path(HConstants.SNAPSHOT_DIR_NAME, Bytes.toString(snapshotName));
verifySnapshot(hdfs, new Path(TEST_UTIL.getDefaultRootDirPath(), snapshotDir),
fs, new Path(copyDir, snapshotDir));
verifyArchive(fs, copyDir, tableName, Bytes.toString(snapshotName));
FSUtils.logFileSystemState(hdfs, snapshotDir, LOG);
// Remove the exported dir
fs.delete(copyDir, true);
}
/*
* verify if the snapshot folder on file-system 1 match the one on file-system 2
*/
private void verifySnapshot(final FileSystem fs1, final Path root1,
final FileSystem fs2, final Path root2) throws IOException {
Set<String> s = new HashSet<String>();
assertEquals(listFiles(fs1, root1, root1), listFiles(fs2, root2, root2));
}
/*
* Verify if the files exists
*/
private void verifyArchive(final FileSystem fs, final Path rootDir,
final byte[] tableName, final String snapshotName) throws IOException {
final Path exportedSnapshot = new Path(rootDir,
new Path(HConstants.SNAPSHOT_DIR_NAME, snapshotName));
final Path exportedArchive = new Path(rootDir, HConstants.HFILE_ARCHIVE_DIRECTORY);
LOG.debug(listFiles(fs, exportedArchive, exportedArchive));
SnapshotReferenceUtil.visitReferencedFiles(fs, exportedSnapshot,
new SnapshotReferenceUtil.FileVisitor() {
public void storeFile (final String region, final String family, final String hfile)
throws IOException {
verifyNonEmptyFile(new Path(exportedArchive,
new Path(Bytes.toString(tableName), new Path(region, new Path(family, hfile)))));
}
public void recoveredEdits (final String region, final String logfile)
throws IOException {
verifyNonEmptyFile(new Path(exportedSnapshot,
new Path(Bytes.toString(tableName), new Path(region, logfile))));
}
public void logFile (final String server, final String logfile)
throws IOException {
verifyNonEmptyFile(new Path(exportedSnapshot, new Path(server, logfile)));
}
private void verifyNonEmptyFile(final Path path) throws IOException {
assertTrue(path + " should exist", fs.exists(path));
assertTrue(path + " should not be empty", fs.getFileStatus(path).getLen() > 0);
}
});
}
private Set<String> listFiles(final FileSystem fs, final Path root, final Path dir)
throws IOException {
Set<String> files = new HashSet<String>();
int rootPrefix = root.toString().length();
FileStatus[] list = FSUtils.listStatus(fs, dir);
if (list != null) {
for (FileStatus fstat: list) {
LOG.debug(fstat.getPath());
if (fstat.isDir()) {
files.addAll(listFiles(fs, root, fstat.getPath()));
} else {
files.add(fstat.getPath().toString().substring(rootPrefix));
}
}
}
return files;
}
}
| |
/*
* Copyright 2015-present Facebook, 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.facebook.buck.parser;
import static com.facebook.buck.parser.ParserConfig.DEFAULT_BUILD_FILE_NAME;
import static org.junit.Assert.assertThat;
import static org.junit.Assume.assumeTrue;
import com.facebook.buck.event.BuckEventBus;
import com.facebook.buck.event.BuckEventBusForTests;
import com.facebook.buck.event.ConsoleEvent;
import com.facebook.buck.io.WatchmanDiagnosticEvent;
import com.facebook.buck.json.PythonDslProjectBuildFileParser;
import com.facebook.buck.parser.exceptions.BuildFileParseException;
import com.facebook.buck.parser.options.ProjectBuildFileParserOptions;
import com.facebook.buck.plugin.impl.BuckPluginManagerFactory;
import com.facebook.buck.rules.Cell;
import com.facebook.buck.rules.DefaultKnownBuildRuleTypesFactory;
import com.facebook.buck.rules.KnownBuildRuleTypes;
import com.facebook.buck.rules.KnownBuildRuleTypesFactory;
import com.facebook.buck.rules.TestCellBuilder;
import com.facebook.buck.rules.coercer.DefaultTypeCoercerFactory;
import com.facebook.buck.sandbox.TestSandboxExecutionStrategyFactory;
import com.facebook.buck.testutil.TestConsole;
import com.facebook.buck.util.DefaultProcessExecutor;
import com.facebook.buck.util.FakeProcess;
import com.facebook.buck.util.FakeProcessExecutor;
import com.facebook.buck.util.ObjectMappers;
import com.facebook.buck.util.ProcessExecutor;
import com.facebook.buck.util.environment.Platform;
import com.facebook.buck.util.timing.FakeClock;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.ImmutableSet;
import com.google.common.eventbus.Subscribe;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.concurrent.atomic.AtomicLong;
import org.hamcrest.Matchers;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
public class PythonDslProjectBuildFileParserTest {
private Cell cell;
private KnownBuildRuleTypes knownBuildRuleTypes;
@Rule public ExpectedException thrown = ExpectedException.none();
@Before
public void createCell() {
cell = new TestCellBuilder().build();
KnownBuildRuleTypesFactory knownBuildRuleTypesFactory =
DefaultKnownBuildRuleTypesFactory.of(
new DefaultProcessExecutor(new TestConsole()),
BuckPluginManagerFactory.createPluginManager(),
new TestSandboxExecutionStrategyFactory());
knownBuildRuleTypes = knownBuildRuleTypesFactory.create(cell);
}
private static FakeProcess fakeProcessWithJsonOutput(
int returnCode,
List<Object> values,
Optional<List<Object>> diagnostics,
Optional<String> stdout) {
Map<String, Object> outputToSerialize = new LinkedHashMap<>();
outputToSerialize.put("values", values);
if (diagnostics.isPresent()) {
outputToSerialize.put("diagnostics", diagnostics.get());
}
byte[] serialized;
try {
serialized = ObjectMappers.WRITER.writeValueAsBytes(outputToSerialize);
} catch (IOException e) {
throw new RuntimeException(e);
}
return new FakeProcess(
returnCode,
new ByteArrayOutputStream(),
new ByteArrayInputStream(serialized),
new ByteArrayInputStream(stdout.orElse("").getBytes(StandardCharsets.UTF_8)));
}
@Test
public void whenSubprocessReturnsSuccessThenProjectBuildFileParserClosesCleanly()
throws IOException, BuildFileParseException, InterruptedException {
TestProjectBuildFileParserFactory buildFileParserFactory =
new TestProjectBuildFileParserFactory(cell.getRoot(), knownBuildRuleTypes);
try (PythonDslProjectBuildFileParser buildFileParser =
buildFileParserFactory.createNoopParserThatAlwaysReturnsSuccess()) {
buildFileParser.initIfNeeded();
// close() is called implicitly at the end of this block. It must not throw.
}
}
@Test(expected = BuildFileParseException.class)
public void whenSubprocessReturnsFailureThenProjectBuildFileParserThrowsOnClose()
throws IOException, BuildFileParseException, InterruptedException {
TestProjectBuildFileParserFactory buildFileParserFactory =
new TestProjectBuildFileParserFactory(cell.getRoot(), knownBuildRuleTypes);
try (PythonDslProjectBuildFileParser buildFileParser =
buildFileParserFactory.createNoopParserThatAlwaysReturnsError()) {
buildFileParser.initIfNeeded();
// close() is called implicitly at the end of this block. It must throw.
}
}
@Test
public void whenSubprocessPrintsWarningToStderrThenConsoleEventPublished()
throws IOException, BuildFileParseException, InterruptedException {
// This test depends on unix utilities that don't exist on Windows.
assumeTrue(Platform.detect() != Platform.WINDOWS);
TestProjectBuildFileParserFactory buildFileParserFactory =
new TestProjectBuildFileParserFactory(cell.getRoot(), knownBuildRuleTypes);
BuckEventBus buckEventBus = BuckEventBusForTests.newInstance(FakeClock.doNotCare());
final List<ConsoleEvent> consoleEvents = new ArrayList<>();
class EventListener {
@Subscribe
public void onConsoleEvent(ConsoleEvent consoleEvent) {
consoleEvents.add(consoleEvent);
}
}
EventListener eventListener = new EventListener();
buckEventBus.register(eventListener);
try (PythonDslProjectBuildFileParser buildFileParser =
buildFileParserFactory.createNoopParserThatAlwaysReturnsSuccessAndPrintsToStderr(
buckEventBus)) {
buildFileParser.initIfNeeded();
buildFileParser.getAllRulesAndMetaRules(Paths.get("foo"), new AtomicLong());
}
assertThat(consoleEvents.get(1).getMessage(), Matchers.containsString("| Don't Panic!"));
}
@Test
public void whenSubprocessReturnsWarningThenConsoleEventPublished()
throws IOException, BuildFileParseException, InterruptedException {
// This test depends on unix utilities that don't exist on Windows.
assumeTrue(Platform.detect() != Platform.WINDOWS);
TestProjectBuildFileParserFactory buildFileParserFactory =
new TestProjectBuildFileParserFactory(cell.getRoot(), knownBuildRuleTypes);
BuckEventBus buckEventBus = BuckEventBusForTests.newInstance(FakeClock.doNotCare());
final List<ConsoleEvent> consoleEvents = new ArrayList<>();
final List<WatchmanDiagnosticEvent> watchmanDiagnosticEvents = new ArrayList<>();
class EventListener {
@Subscribe
public void on(ConsoleEvent consoleEvent) {
consoleEvents.add(consoleEvent);
}
@Subscribe
public void on(WatchmanDiagnosticEvent event) {
watchmanDiagnosticEvents.add(event);
}
}
EventListener eventListener = new EventListener();
buckEventBus.register(eventListener);
try (PythonDslProjectBuildFileParser buildFileParser =
buildFileParserFactory.createNoopParserThatAlwaysReturnsSuccessWithWarning(
buckEventBus, "This is a warning", "parser")) {
buildFileParser.initIfNeeded();
buildFileParser.getAllRulesAndMetaRules(Paths.get("foo"), new AtomicLong());
}
assertThat(
consoleEvents,
Matchers.contains(
Matchers.hasToString("Warning raised by BUCK file parser: This is a warning")));
assertThat(
"Should not receive any watchman diagnostic events",
watchmanDiagnosticEvents,
Matchers.empty());
}
@Test
public void whenSubprocessReturnsNewWatchmanWarningThenDiagnosticEventPublished()
throws IOException, BuildFileParseException, InterruptedException {
// This test depends on unix utilities that don't exist on Windows.
assumeTrue(Platform.detect() != Platform.WINDOWS);
TestProjectBuildFileParserFactory buildFileParserFactory =
new TestProjectBuildFileParserFactory(cell.getRoot(), knownBuildRuleTypes);
BuckEventBus buckEventBus = BuckEventBusForTests.newInstance(FakeClock.doNotCare());
final List<WatchmanDiagnosticEvent> watchmanDiagnosticEvents = new ArrayList<>();
class EventListener {
@Subscribe
public void on(WatchmanDiagnosticEvent consoleEvent) {
watchmanDiagnosticEvents.add(consoleEvent);
}
}
EventListener eventListener = new EventListener();
buckEventBus.register(eventListener);
try (PythonDslProjectBuildFileParser buildFileParser =
buildFileParserFactory.createNoopParserThatAlwaysReturnsSuccessWithWarning(
buckEventBus, "This is a watchman warning", "watchman")) {
buildFileParser.initIfNeeded();
buildFileParser.getAllRulesAndMetaRules(Paths.get("foo"), new AtomicLong());
}
assertThat(
watchmanDiagnosticEvents,
Matchers.contains(
Matchers.hasToString(Matchers.containsString("This is a watchman warning"))));
}
@Test
public void whenSubprocessReturnsErrorThenConsoleEventPublished()
throws IOException, BuildFileParseException, InterruptedException {
// This test depends on unix utilities that don't exist on Windows.
assumeTrue(Platform.detect() != Platform.WINDOWS);
TestProjectBuildFileParserFactory buildFileParserFactory =
new TestProjectBuildFileParserFactory(cell.getRoot(), knownBuildRuleTypes);
BuckEventBus buckEventBus = BuckEventBusForTests.newInstance(FakeClock.doNotCare());
final List<ConsoleEvent> consoleEvents = new ArrayList<>();
class EventListener {
@Subscribe
public void onConsoleEvent(ConsoleEvent consoleEvent) {
consoleEvents.add(consoleEvent);
}
}
EventListener eventListener = new EventListener();
buckEventBus.register(eventListener);
try (PythonDslProjectBuildFileParser buildFileParser =
buildFileParserFactory.createNoopParserThatAlwaysReturnsSuccessWithError(
buckEventBus, "This is an error", "parser")) {
buildFileParser.initIfNeeded();
buildFileParser.getAllRulesAndMetaRules(Paths.get("foo"), new AtomicLong());
}
assertThat(
consoleEvents,
Matchers.contains(
Matchers.hasToString("Error raised by BUCK file parser: This is an error")));
}
@Test
public void whenSubprocessReturnsSyntaxErrorInFileBeingParsedThenExceptionContainsFileNameOnce()
throws IOException, BuildFileParseException, InterruptedException {
// This test depends on unix utilities that don't exist on Windows.
assumeTrue(Platform.detect() != Platform.WINDOWS);
TestProjectBuildFileParserFactory buildFileParserFactory =
new TestProjectBuildFileParserFactory(cell.getRoot(), knownBuildRuleTypes);
thrown.expect(BuildFileParseException.class);
thrown.expectMessage(
"Buck wasn't able to parse foo/BUCK:\n"
+ "Syntax error on line 23, column 16:\n"
+ "java_test(name=*@!&#(!@&*()\n"
+ " ^");
try (PythonDslProjectBuildFileParser buildFileParser =
buildFileParserFactory.createNoopParserThatAlwaysReturnsErrorWithException(
BuckEventBusForTests.newInstance(FakeClock.doNotCare()),
"This is an error",
"parser",
ImmutableMap.<String, Object>builder()
.put("type", "SyntaxError")
.put("value", "You messed up")
.put("filename", "foo/BUCK")
.put("lineno", 23)
.put("offset", 16)
.put("text", "java_test(name=*@!&#(!@&*()\n")
.put(
"traceback",
ImmutableList.of(
ImmutableMap.of(
"filename", "foo/BUCK",
"line_number", 23,
"function_name", "<module>",
"text", "java_test(name=*@!&#(!@&*()\n")))
.build())) {
buildFileParser.initIfNeeded();
buildFileParser.getAllRulesAndMetaRules(Paths.get("foo/BUCK"), new AtomicLong());
}
}
@Test
public void whenSubprocessReturnsSyntaxErrorWithoutOffsetThenExceptionIsFormattedWithoutColumn()
throws IOException, BuildFileParseException, InterruptedException {
// This test depends on unix utilities that don't exist on Windows.
assumeTrue(Platform.detect() != Platform.WINDOWS);
TestProjectBuildFileParserFactory buildFileParserFactory =
new TestProjectBuildFileParserFactory(cell.getRoot(), knownBuildRuleTypes);
thrown.expect(BuildFileParseException.class);
thrown.expectMessage(
"Buck wasn't able to parse foo/BUCK:\n"
+ "Syntax error on line 23:\n"
+ "java_test(name=*@!&#(!@&*()");
try (PythonDslProjectBuildFileParser buildFileParser =
buildFileParserFactory.createNoopParserThatAlwaysReturnsErrorWithException(
BuckEventBusForTests.newInstance(FakeClock.doNotCare()),
"This is an error",
"parser",
ImmutableMap.<String, Object>builder()
.put("type", "SyntaxError")
.put("value", "You messed up")
.put("filename", "foo/BUCK")
.put("lineno", 23)
.put("text", "java_test(name=*@!&#(!@&*()\n")
.put(
"traceback",
ImmutableList.of(
ImmutableMap.of(
"filename", "foo/BUCK",
"line_number", 23,
"function_name", "<module>",
"text", "java_test(name=*@!&#(!@&*()\n")))
.build())) {
buildFileParser.initIfNeeded();
buildFileParser.getAllRulesAndMetaRules(Paths.get("foo/BUCK"), new AtomicLong());
}
}
@Test
public void whenSubprocessReturnsSyntaxErrorInDifferentFileThenExceptionContainsTwoFileNames()
throws IOException, BuildFileParseException, InterruptedException {
// This test depends on unix utilities that don't exist on Windows.
assumeTrue(Platform.detect() != Platform.WINDOWS);
TestProjectBuildFileParserFactory buildFileParserFactory =
new TestProjectBuildFileParserFactory(cell.getRoot(), knownBuildRuleTypes);
BuckEventBus buckEventBus = BuckEventBusForTests.newInstance(FakeClock.doNotCare());
final List<ConsoleEvent> consoleEvents = new ArrayList<>();
class EventListener {
@Subscribe
public void onConsoleEvent(ConsoleEvent consoleEvent) {
consoleEvents.add(consoleEvent);
}
}
EventListener eventListener = new EventListener();
buckEventBus.register(eventListener);
thrown.expect(BuildFileParseException.class);
thrown.expectMessage(
"Buck wasn't able to parse foo/BUCK:\n"
+ "Syntax error in bar/BUCK\n"
+ "Line 42, column 24:\n"
+ "def some_helper_method(!@87*@!#\n"
+ " ^");
try (PythonDslProjectBuildFileParser buildFileParser =
buildFileParserFactory.createNoopParserThatAlwaysReturnsErrorWithException(
buckEventBus,
"This is an error",
"parser",
ImmutableMap.<String, Object>builder()
.put("type", "SyntaxError")
.put("value", "You messed up")
.put("filename", "bar/BUCK")
.put("lineno", 42)
.put("offset", 24)
.put("text", "def some_helper_method(!@87*@!#\n")
.put(
"traceback",
ImmutableList.of(
ImmutableMap.of(
"filename", "bar/BUCK",
"line_number", 42,
"function_name", "<module>",
"text", "def some_helper_method(!@87*@!#\n"),
ImmutableMap.of(
"filename", "foo/BUCK",
"line_number", 23,
"function_name", "<module>",
"text", "some_helper_method(name=*@!&#(!@&*()\n")))
.build())) {
buildFileParser.initIfNeeded();
buildFileParser.getAllRulesAndMetaRules(Paths.get("foo/BUCK"), new AtomicLong());
}
}
@Test
public void whenSubprocessReturnsNonSyntaxErrorThenExceptionContainsFullStackTrace()
throws IOException, BuildFileParseException, InterruptedException {
// This test depends on unix utilities that don't exist on Windows.
assumeTrue(Platform.detect() != Platform.WINDOWS);
TestProjectBuildFileParserFactory buildFileParserFactory =
new TestProjectBuildFileParserFactory(cell.getRoot(), knownBuildRuleTypes);
thrown.expect(BuildFileParseException.class);
thrown.expectMessage(
"Buck wasn't able to parse foo/BUCK:\n"
+ "ZeroDivisionError: integer division or modulo by zero\n"
+ "Call stack:\n"
+ " File \"bar/BUCK\", line 42, in lets_divide_by_zero\n"
+ " foo / bar\n"
+ "\n"
+ " File \"foo/BUCK\", line 23\n"
+ " lets_divide_by_zero()\n"
+ "\n");
try (PythonDslProjectBuildFileParser buildFileParser =
buildFileParserFactory.createNoopParserThatAlwaysReturnsErrorWithException(
BuckEventBusForTests.newInstance(FakeClock.doNotCare()),
"This is an error",
"parser",
ImmutableMap.<String, Object>builder()
.put("type", "ZeroDivisionError")
.put("value", "integer division or modulo by zero")
.put("filename", "bar/BUCK")
.put("lineno", 42)
.put("offset", 24)
.put("text", "foo / bar\n")
.put(
"traceback",
ImmutableList.of(
ImmutableMap.of(
"filename", "bar/BUCK",
"line_number", 42,
"function_name", "lets_divide_by_zero",
"text", "foo / bar\n"),
ImmutableMap.of(
"filename", "foo/BUCK",
"line_number", 23,
"function_name", "<module>",
"text", "lets_divide_by_zero()\n")))
.build())) {
buildFileParser.initIfNeeded();
buildFileParser.getAllRulesAndMetaRules(Paths.get("foo/BUCK"), new AtomicLong());
}
}
/**
* ProjectBuildFileParser test double which counts the number of times rules are parsed to test
* caching logic in Parser.
*/
private static class TestProjectBuildFileParserFactory {
private final Path projectRoot;
private final KnownBuildRuleTypes buildRuleTypes;
public TestProjectBuildFileParserFactory(Path projectRoot, KnownBuildRuleTypes buildRuleTypes) {
this.projectRoot = projectRoot;
this.buildRuleTypes = buildRuleTypes;
}
public PythonDslProjectBuildFileParser createNoopParserThatAlwaysReturnsError() {
return new TestPythonDslProjectBuildFileParser(
"fake-python",
new FakeProcessExecutor(
params ->
fakeProcessWithJsonOutput(
1, ImmutableList.of(), Optional.empty(), Optional.empty()),
new TestConsole()),
BuckEventBusForTests.newInstance());
}
public PythonDslProjectBuildFileParser createNoopParserThatAlwaysReturnsSuccess() {
return new TestPythonDslProjectBuildFileParser(
"fake-python",
new FakeProcessExecutor(
params ->
fakeProcessWithJsonOutput(
0, ImmutableList.of(), Optional.empty(), Optional.empty()),
new TestConsole()),
BuckEventBusForTests.newInstance());
}
public PythonDslProjectBuildFileParser
createNoopParserThatAlwaysReturnsSuccessAndPrintsToStderr(BuckEventBus buckEventBus) {
return new TestPythonDslProjectBuildFileParser(
"fake-python",
new FakeProcessExecutor(
params ->
fakeProcessWithJsonOutput(
0, ImmutableList.of(), Optional.empty(), Optional.of("Don't Panic!")),
new TestConsole()),
buckEventBus);
}
public PythonDslProjectBuildFileParser createNoopParserThatAlwaysReturnsSuccessWithWarning(
BuckEventBus buckEventBus, final String warning, final String source) {
return new TestPythonDslProjectBuildFileParser(
"fake-python",
new FakeProcessExecutor(
params ->
fakeProcessWithJsonOutput(
0,
ImmutableList.of(),
Optional.of(
ImmutableList.of(
ImmutableMap.of(
"level", "warning", "message", warning, "source", source))),
Optional.empty()),
new TestConsole()),
buckEventBus);
}
public PythonDslProjectBuildFileParser createNoopParserThatAlwaysReturnsSuccessWithError(
BuckEventBus buckEventBus, final String error, final String source) {
return new TestPythonDslProjectBuildFileParser(
"fake-python",
new FakeProcessExecutor(
params ->
fakeProcessWithJsonOutput(
0,
ImmutableList.of(),
Optional.of(
ImmutableList.of(
ImmutableMap.of(
"level", "error", "message", error, "source", source))),
Optional.empty()),
new TestConsole()),
buckEventBus);
}
public PythonDslProjectBuildFileParser createNoopParserThatAlwaysReturnsErrorWithException(
BuckEventBus buckEventBus,
final String error,
final String source,
final ImmutableMap<String, Object> exception) {
return new TestPythonDslProjectBuildFileParser(
"fake-python",
new FakeProcessExecutor(
params ->
fakeProcessWithJsonOutput(
1,
ImmutableList.of(),
Optional.of(
ImmutableList.of(
ImmutableMap.of(
"level",
"fatal",
"message",
error,
"source",
source,
"exception",
exception))),
Optional.empty()),
new TestConsole()),
buckEventBus);
}
private class TestPythonDslProjectBuildFileParser extends PythonDslProjectBuildFileParser {
public TestPythonDslProjectBuildFileParser(
String pythonInterpreter, ProcessExecutor processExecutor, BuckEventBus buckEventBus) {
super(
ProjectBuildFileParserOptions.builder()
.setProjectRoot(projectRoot)
.setPythonInterpreter(pythonInterpreter)
.setAllowEmptyGlobs(ParserConfig.DEFAULT_ALLOW_EMPTY_GLOBS)
.setIgnorePaths(ImmutableSet.of())
.setBuildFileName(DEFAULT_BUILD_FILE_NAME)
.setDefaultIncludes(ImmutableSet.of("//java/com/facebook/defaultIncludeFile"))
.setDescriptions(buildRuleTypes.getDescriptions())
.setBuildFileImportWhitelist(ImmutableList.of())
.build(),
new DefaultTypeCoercerFactory(),
ImmutableMap.of(),
buckEventBus,
processExecutor);
}
}
}
}
| |
/**
* 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.lens.cli.commands;
import java.io.*;
import java.nio.charset.Charset;
import java.util.List;
import java.util.UUID;
import javax.ws.rs.core.Response;
import org.apache.lens.api.query.*;
import org.apache.lens.api.result.PrettyPrintable;
import org.apache.lens.cli.commands.annotations.UserDocumentation;
import org.apache.lens.client.LensClient;
import org.apache.lens.client.exceptions.LensAPIException;
import org.apache.lens.client.exceptions.LensBriefErrorException;
import org.apache.lens.client.model.BriefError;
import org.apache.lens.client.model.IdBriefErrorTemplate;
import org.apache.lens.client.model.IdBriefErrorTemplateKey;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.shell.core.annotation.CliCommand;
import org.springframework.shell.core.annotation.CliOption;
import org.springframework.stereotype.Component;
import com.google.common.base.Joiner;
/**
* The Class LensQueryCommands.
* SUSPEND CHECKSTYLE CHECK InnerAssignmentCheck
*/
@Component
@UserDocumentation(title = "Query Management",
description = "This section provides commands for query life cycle - "
+ "submit, check status,\n"
+ " fetch results, kill or list all the queries. Also provides commands for\n"
+ " prepare a query, destroy a prepared query and list all prepared queries.\n"
+ "\n"
+ " Please note that, character <<<\">>> is used as delimiter by the Spring Shell\n"
+ " framework, which is used to build lens cli. So queries which require <<<\">>>,\n"
+ " should be prefixed with another double quote. For example\n"
+ " <<<query execute cube select id,name from dim_table where name != \"\"first\"\">>>,\n"
+ " will be parsed as <<<cube select id,name from dim_table where name != \"first\">>>")
public class LensQueryCommands extends BaseLensCommand {
/**
* Execute query.
*
* @param sql the sql
* @param async the asynch
* @param queryName the query name
* @return the string
*/
@CliCommand(value = "query execute",
help = "Execute query <query-string>."
+
" If <async> is true, The query is launched in async manner and query handle is returned. It's by default false."
+ " <query name> can also be provided, though not required")
public String executeQuery(
@CliOption(key = {"", "query"}, mandatory = true, help = "<query-string>") String sql,
@CliOption(key = {"async"}, mandatory = false, unspecifiedDefaultValue = "false",
specifiedDefaultValue = "true", help = "<async>") boolean async,
@CliOption(key = {"name"}, mandatory = false, help = "<query-name>") String queryName) {
PrettyPrintable cliOutput;
try {
if (async) {
QueryHandle queryHandle = getClient().executeQueryAsynch(sql, queryName).getData();
return queryHandle.getHandleIdString();
} else {
return formatResultSet(getClient().getResults(sql, queryName));
}
} catch (final LensAPIException e) {
BriefError briefError = new BriefError(e.getLensAPIErrorCode(), e.getLensAPIErrorMessage());
cliOutput = new IdBriefErrorTemplate(IdBriefErrorTemplateKey.REQUEST_ID, e.getLensAPIRequestId(), briefError);
} catch (final LensBriefErrorException e) {
cliOutput = e.getIdBriefErrorTemplate();
}
return cliOutput.toPrettyString();
}
/**
* Format result set.
*
* @param rs the rs
* @return the string
*/
private String formatResultSet(LensClient.LensClientResultSetWithStats rs) {
StringBuilder b = new StringBuilder();
int numRows = 0;
if (rs.getResultSet() != null) {
QueryResultSetMetadata resultSetMetadata = rs.getResultSet().getResultSetMetadata();
for (ResultColumn column : resultSetMetadata.getColumns()) {
b.append(column.getName()).append("\t");
}
b.append("\n");
QueryResult r = rs.getResultSet().getResult();
if (r instanceof InMemoryQueryResult) {
InMemoryQueryResult temp = (InMemoryQueryResult) r;
for (ResultRow row : temp.getRows()) {
for (Object col : row.getValues()) {
b.append(col).append("\t");
}
numRows++;
b.append("\n");
}
b.append(numRows + " rows ");
} else {
PersistentQueryResult temp = (PersistentQueryResult) r;
b.append("Results of query stored at : ").append(temp.getPersistedURI()).append(" ");
if (null != temp.getNumRows()) {
b.append(temp.getNumRows() + " rows ");
}
}
}
if (rs.getQuery() != null) {
long submissionTime = rs.getQuery().getSubmissionTime();
long endTime = rs.getQuery().getFinishTime();
b.append("processed in (").append(endTime > 0 ? ((endTime - submissionTime) / 1000) : 0)
.append(") seconds.\n");
}
return b.toString();
}
/**
* Gets the status.
*
* @param qh the qh
* @return the status
*/
@CliCommand(value = "query status", help = "Fetch status of executed query having query handle <query_handle>")
public String getStatus(
@CliOption(key = {"", "query_handle"}, mandatory = true, help = "<query_handle>") String qh) {
QueryStatus status = getClient().getQueryStatus(new QueryHandle(UUID.fromString(qh)));
StringBuilder sb = new StringBuilder();
if (status == null) {
return "Unable to find status for " + qh;
}
sb.append("Status : ").append(status.getStatus()).append("\n");
if (status.getStatusMessage() != null) {
sb.append("Message : ").append(status.getStatusMessage()).append("\n");
}
if (status.getProgress() != 0) {
sb.append("Progress : ").append(status.getProgress()).append("\n");
if (status.getProgressMessage() != null) {
sb.append("Progress Message : ").append(status.getProgressMessage()).append("\n");
}
}
if (status.getErrorMessage() != null) {
sb.append("Error : ").append(status.getErrorMessage()).append("\n");
}
return sb.toString();
}
/**
* Gets the query details.
*
* @param qh the qh
* @return the query
*/
@CliCommand(value = "query details", help = "Get query details of query with handle <query_handle>")
public String getDetails(
@CliOption(key = {"", "query_handle"}, mandatory = true, help
= "<query_handle>") String qh) {
LensQuery query = getClient().getQueryDetails(qh);
if (query == null) {
return "Unable to find query for " + qh;
}
try {
return formatJson(mapper.writer(pp).writeValueAsString(query));
} catch (IOException e) {
throw new IllegalArgumentException(e);
}
}
/**
* Explain query.
*
* @param sql the sql
* @param location the location
* @return the string
* @throws LensAPIException
* @throws UnsupportedEncodingException the unsupported encoding exception
*/
@CliCommand(value = "query explain", help = "Explain execution plan of query <query-string>. "
+ "Can optionally save the plan to a file by providing <save_location>")
public String explainQuery(@CliOption(key = { "", "query" }, mandatory = true, help = "<query-string>") String sql,
@CliOption(key = { "save_location" }, mandatory = false, help = "<save_location>") final File path)
throws IOException, LensAPIException {
PrettyPrintable cliOutput;
try {
QueryPlan plan = getClient().getQueryPlan(sql).getData();
if (path != null && StringUtils.isNotBlank(path.getPath())) {
String validPath = getValidPath(path, false, false);
try (OutputStreamWriter osw = new OutputStreamWriter(new FileOutputStream(validPath),
Charset.defaultCharset())) {
osw.write(plan.getPlanString());
}
return "Saved to " + validPath;
}
return plan.getPlanString();
} catch (final LensAPIException e) {
BriefError briefError = new BriefError(e.getLensAPIErrorCode(), e.getLensAPIErrorMessage());
cliOutput = new IdBriefErrorTemplate(IdBriefErrorTemplateKey.REQUEST_ID, e.getLensAPIRequestId(), briefError);
} catch (final LensBriefErrorException e) {
cliOutput = e.getIdBriefErrorTemplate();
}
return cliOutput.toPrettyString();
}
/**
* Gets the all queries.
*
* @param state the state
* @param queryName the query name
* @param user the user
* @param fromDate the from date
* @param toDate the to date
* @return the all queries
*/
@CliCommand(value = "query list",
help = "Get all queries. Various filter options can be provided(optionally), "
+ " as can be seen from the command syntax")
public String getAllQueries(
@CliOption(key = {"state"}, mandatory = false, help = "<query-status>") String state,
@CliOption(key = {"name"}, mandatory = false, help = "<query-name>") String queryName,
@CliOption(key = {"user"}, mandatory = false, help = "<user-who-submitted-query>") String user,
@CliOption(key = {"fromDate"}, mandatory = false, unspecifiedDefaultValue = "-1", help
= "<submission-time-is-after>") long fromDate,
@CliOption(key = {"toDate"}, mandatory = false, unspecifiedDefaultValue = "" + Long.MAX_VALUE, help
= "<submission-time-is-before>") long toDate) {
List<QueryHandle> handles = getClient().getQueries(state, queryName, user, fromDate, toDate);
if (handles != null && !handles.isEmpty()) {
return Joiner.on("\n").skipNulls().join(handles).concat("\n").concat("Total number of queries: "
+ handles.size());
} else {
return "No queries";
}
}
/**
* Kill query.
*
* @param qh the qh
* @return the string
*/
@CliCommand(value = "query kill", help = "Kill query with handle <query_handle>")
public String killQuery(
@CliOption(key = {"", "query_handle"}, mandatory = true, help = "<query_handle>") String qh) {
boolean status = getClient().killQuery(new QueryHandle(UUID.fromString(qh)));
if (status) {
return "Successfully killed " + qh;
} else {
return "Failed in killing " + qh;
}
}
/**
* Gets the query results.
*
* @param qh the qh
* @return the query results
*/
@CliCommand(value = "query results",
help = "get results of query with query handle <query_handle>. If async is false "
+ "then wait till the query execution is completed, it's by default true. "
+ "Can optionally save the results to a file by providing <save_location>.")
public String getQueryResults(
@CliOption(key = {"", "query_handle"}, mandatory = true, help = "<query_handle>") String qh,
@CliOption(key = {"save_location"}, mandatory = false, help = "<save_location>") final File path,
@CliOption(key = {"async"}, mandatory = false, unspecifiedDefaultValue = "true",
help = "<async>") boolean async) {
QueryHandle queryHandle = new QueryHandle(UUID.fromString(qh));
LensClient.LensClientResultSetWithStats results;
String location = path != null ? path.getPath() : null;
try {
String prefix = "";
if (StringUtils.isNotBlank(location)) {
location = getValidPath(path, true, true);
Response response = getClient().getHttpResults(queryHandle);
if (response.getStatus() == Response.Status.OK.getStatusCode()) {
String disposition = (String) response.getHeaders().get("content-disposition").get(0);
String fileName = disposition.split("=")[1].trim();
location = getValidPath(new File(location + File.separator + fileName), false, false);
try (InputStream stream = response.readEntity(InputStream.class);
FileOutputStream outStream = new FileOutputStream(new File(location))) {
IOUtils.copy(stream, outStream);
}
return "Saved to " + location;
} else {
if (async) {
results = getClient().getAsyncResults(queryHandle);
} else {
results = getClient().getSyncResults(queryHandle);
}
if (results.getResultSet() == null) {
return "Resultset not yet available";
} else if (results.getResultSet().getResult() instanceof InMemoryQueryResult) {
location = getValidPath(new File(location + File.separator + qh + ".csv"), false, false);
try (OutputStreamWriter osw = new OutputStreamWriter(new FileOutputStream(location),
Charset.defaultCharset())) {
osw.write(formatResultSet(results));
}
return "Saved to " + location;
} else {
return "Can't download the result because it's available in driver's persistence.\n"
+ formatResultSet(results);
}
}
} else if (async) {
return formatResultSet(getClient().getAsyncResults(queryHandle));
} else {
return formatResultSet(getClient().getSyncResults(queryHandle));
}
} catch (Throwable t) {
return t.getMessage();
}
}
/**
* Gets the all prepared queries.
*
* @param userName the user name
* @param queryName the query name
* @param fromDate the from date
* @param toDate the to date
* @return the all prepared queries
*/
@CliCommand(value = "prepQuery list",
help = "Get all prepared queries. Various filters can be provided(optionally)"
+ " as can be seen from command syntax")
public String getAllPreparedQueries(
@CliOption(key = {"name"}, mandatory = false, help = "<query-name>") String queryName,
@CliOption(key = {"user"}, mandatory = false, help = "<user-who-submitted-query>") String userName,
@CliOption(key = {"fromDate"}, mandatory = false, unspecifiedDefaultValue = "-1", help
= "<submission-time-is-after>") long fromDate,
@CliOption(key = {"toDate"}, mandatory = false, unspecifiedDefaultValue = "" + Long.MAX_VALUE, help
= "<submission-time-is-before>") long toDate) {
List<QueryPrepareHandle> handles = getClient().getPreparedQueries(userName, queryName, fromDate, toDate);
if (handles != null && !handles.isEmpty()) {
return Joiner.on("\n").skipNulls().join(handles);
} else {
return "No prepared queries";
}
}
/**
* Gets the prepared status.
*
* @param ph the ph
* @return the prepared status
*/
@CliCommand(value = "prepQuery details", help = "Get prepared query with handle <prepare_handle>")
public String getPreparedStatus(
@CliOption(key = {"", "prepare_handle"}, mandatory = true, help = "<prepare_handle>") String ph) {
LensPreparedQuery prepared = getClient().getPreparedQuery(QueryPrepareHandle.fromString(ph));
if (prepared != null) {
StringBuilder sb = new StringBuilder()
.append("User query:").append(prepared.getUserQuery()).append("\n")
.append("Prepare handle:").append(prepared.getPrepareHandle()).append("\n")
.append("User:" + prepared.getPreparedUser()).append("\n")
.append("Prepared at:").append(prepared.getPreparedTime()).append("\n")
.append("Selected driver :").append(prepared.getSelectedDriverClassName()).append("\n")
.append("Driver query:").append(prepared.getDriverQuery()).append("\n");
if (prepared.getConf() != null) {
sb.append("Conf:").append(prepared.getConf().getProperties()).append("\n");
}
return sb.toString();
} else {
return "No such handle";
}
}
/**
* Destroy prepared query.
*
* @param ph the ph
* @return the string
*/
@CliCommand(value = "prepQuery destroy", help = "Destroy prepared query with handle <prepare_handle>")
public String destroyPreparedQuery(
@CliOption(key = {"", "prepare_handle"}, mandatory = true, help = "<prepare_handle>") String ph) {
boolean status = getClient().destroyPrepared(new QueryPrepareHandle(UUID.fromString(ph)));
if (status) {
return "Successfully destroyed " + ph;
} else {
return "Failed in destroying " + ph;
}
}
/**
* Execute prepared query.
*
* @param phandle the phandle
* @param async the asynch
* @param queryName the query name
* @return the string
*/
@CliCommand(value = "prepQuery execute",
help = "Execute prepared query with handle <prepare_handle>."
+ " If <async> is supplied and is true, query is run in async manner and query handle is returned immediately."
+ " Optionally, <query-name> can be provided, though not required.")
public String executePreparedQuery(
@CliOption(key = {"", "prepare_handle"}, mandatory = true, help = "Prepare handle to execute") String phandle,
@CliOption(key = {"async"}, mandatory = false, unspecifiedDefaultValue = "false",
specifiedDefaultValue = "true", help = "<async>") boolean async,
@CliOption(key = {"name"}, mandatory = false, help = "<query-name>") String queryName) {
if (async) {
QueryHandle handle = getClient().executePrepared(QueryPrepareHandle.fromString(phandle), queryName);
return handle.getHandleId().toString();
} else {
try {
LensClient.LensClientResultSetWithStats result = getClient().getResultsFromPrepared(
QueryPrepareHandle.fromString(phandle), queryName);
return formatResultSet(result);
} catch (Throwable t) {
return t.getMessage();
}
}
}
/**
* Prepare.
*
* @param sql the sql
* @param queryName the query name
* @return the string
* @throws UnsupportedEncodingException the unsupported encoding exception
* @throws LensAPIException
*/
@CliCommand(value = "prepQuery prepare",
help = "Prepapre query <query-string> and return prepare handle. Can optionaly provide <query-name>")
public String prepare(@CliOption(key = {"", "query"}, mandatory = true, help = "<query-string>") String sql,
@CliOption(key = {"name"}, mandatory = false, help = "<query-name>") String queryName)
throws UnsupportedEncodingException, LensAPIException {
return getClient().prepare(sql, queryName).getData().toString();
}
/**
* Explain and prepare.
*
* @param sql
* the sql
* @param queryName
* the query name
* @return the string
* @throws UnsupportedEncodingException
* the unsupported encoding exception
* @throws LensAPIException
*/
@CliCommand(value = "prepQuery explain", help = "Explain and prepare query <query-string>. "
+ "Can optionally provide <query-name>")
public String explainAndPrepare(
@CliOption(key = { "", "query" }, mandatory = true, help = "<query-string>") String sql,
@CliOption(key = { "name" }, mandatory = false, help = "<query-name>") String queryName)
throws UnsupportedEncodingException, LensAPIException {
PrettyPrintable cliOutput;
try {
QueryPlan plan = getClient().explainAndPrepare(sql, queryName).getData();
StringBuilder planStr = new StringBuilder(plan.getPlanString());
planStr.append("\n").append("Prepare handle:").append(plan.getPrepareHandle());
return planStr.toString();
} catch (final LensAPIException e) {
BriefError briefError = new BriefError(e.getLensAPIErrorCode(), e.getLensAPIErrorMessage());
cliOutput = new IdBriefErrorTemplate(IdBriefErrorTemplateKey.REQUEST_ID, e.getLensAPIRequestId(), briefError);
} catch (final LensBriefErrorException e) {
cliOutput = e.getIdBriefErrorTemplate();
}
return cliOutput.toPrettyString();
}
}
| |
/*
* 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.cassandra.cql;
import java.nio.ByteBuffer;
import java.util.HashMap;
import java.util.Map;
import org.apache.cassandra.cache.CachingOptions;
import org.apache.cassandra.config.CFMetaData;
import org.apache.cassandra.config.ColumnDefinition;
import org.apache.cassandra.config.Schema;
import org.apache.cassandra.db.marshal.TypeParser;
import org.apache.cassandra.exceptions.ConfigurationException;
import org.apache.cassandra.exceptions.InvalidRequestException;
import org.apache.cassandra.exceptions.RequestValidationException;
import org.apache.cassandra.exceptions.SyntaxException;
import org.apache.cassandra.io.compress.CompressionParameters;
public class AlterTableStatement
{
public static enum OperationType
{
ADD, ALTER, DROP, OPTS
}
public final OperationType oType;
public final String columnFamily, columnName, validator;
private final CFPropDefs cfProps = new CFPropDefs();
public AlterTableStatement(String columnFamily, OperationType type, String columnName)
{
this(columnFamily, type, columnName, null);
}
public AlterTableStatement(String columnFamily, OperationType type, String columnName, String validator)
{
this(columnFamily, type, columnName, validator, null);
}
public AlterTableStatement(String columnFamily, OperationType type, String columnName, String validator, Map<String, String> propertyMap)
{
this.columnFamily = columnFamily;
this.oType = type;
this.columnName = columnName;
this.validator = CFPropDefs.comparators.get(validator); // used only for ADD/ALTER commands
if (propertyMap != null)
{
for (Map.Entry<String, String> prop : propertyMap.entrySet())
{
cfProps.addProperty(prop.getKey(), prop.getValue());
}
}
}
public CFMetaData getCFMetaData(String keyspace) throws ConfigurationException, InvalidRequestException, SyntaxException
{
CFMetaData meta = Schema.instance.getCFMetaData(keyspace, columnFamily);
CFMetaData cfm = meta.copy();
ByteBuffer columnName = this.oType == OperationType.OPTS ? null
: meta.comparator.subtype(0).fromStringCQL2(this.columnName);
switch (oType)
{
case ADD:
cfm.addColumnDefinition(ColumnDefinition.regularDef(cfm, columnName, TypeParser.parse(validator), null));
break;
case ALTER:
// We only look for the first key alias which is ok for CQL2
ColumnDefinition partionKeyDef = cfm.partitionKeyColumns().get(0);
if (partionKeyDef.name.bytes.equals(columnName))
{
cfm.keyValidator(TypeParser.parse(validator));
}
else
{
ColumnDefinition toUpdate = null;
for (ColumnDefinition columnDef : cfm.regularColumns())
{
if (columnDef.name.bytes.equals(columnName))
{
toUpdate = columnDef;
break;
}
}
if (toUpdate == null)
throw new InvalidRequestException(String.format("Column '%s' was not found in CF '%s'",
this.columnName,
columnFamily));
cfm.addOrReplaceColumnDefinition(toUpdate.withNewType(TypeParser.parse(validator)));
}
break;
case DROP:
ColumnDefinition toDelete = null;
for (ColumnDefinition columnDef : cfm.regularColumns())
{
if (columnDef.name.bytes.equals(columnName))
{
toDelete = columnDef;
}
}
if (toDelete == null)
throw new InvalidRequestException(String.format("Column '%s' was not found in CF '%s'",
this.columnName,
columnFamily));
cfm.removeColumnDefinition(toDelete);
break;
case OPTS:
if (cfProps == null)
throw new InvalidRequestException(String.format("ALTER COLUMNFAMILY WITH invoked, but no parameters found"));
cfProps.validate();
applyPropertiesToCFMetadata(cfm, cfProps);
break;
}
return cfm;
}
public String toString()
{
return String.format("AlterTableStatement(cf=%s, type=%s, column=%s, validator=%s)",
columnFamily,
oType,
columnName,
validator);
}
public static void applyPropertiesToCFMetadata(CFMetaData cfm, CFPropDefs cfProps) throws InvalidRequestException, ConfigurationException
{
if (cfProps.hasProperty(CFPropDefs.KW_COMPACTION_STRATEGY_CLASS))
cfm.compactionStrategyClass(cfProps.compactionStrategyClass);
if (cfProps.hasProperty(CFPropDefs.KW_COMPARATOR))
throw new InvalidRequestException("Can't change CF comparator after creation");
if (cfProps.hasProperty(CFPropDefs.KW_COMMENT))
cfm.comment(cfProps.getProperty(CFPropDefs.KW_COMMENT));
if (cfProps.hasProperty(CFPropDefs.KW_DEFAULTVALIDATION))
{
try
{
cfm.defaultValidator(cfProps.getValidator());
}
catch (RequestValidationException e)
{
throw new InvalidRequestException(String.format("Invalid validation type %s",
cfProps.getProperty(CFPropDefs.KW_DEFAULTVALIDATION)));
}
}
cfm.readRepairChance(cfProps.getPropertyDouble(CFPropDefs.KW_READREPAIRCHANCE, cfm.getReadRepairChance()));
cfm.dcLocalReadRepairChance(cfProps.getPropertyDouble(CFPropDefs.KW_DCLOCALREADREPAIRCHANCE, cfm.getDcLocalReadRepair()));
cfm.gcGraceSeconds(cfProps.getPropertyInt(CFPropDefs.KW_GCGRACESECONDS, cfm.getGcGraceSeconds()));
int minCompactionThreshold = cfProps.getPropertyInt(CFPropDefs.KW_MINCOMPACTIONTHRESHOLD, cfm.getMinCompactionThreshold());
int maxCompactionThreshold = cfProps.getPropertyInt(CFPropDefs.KW_MAXCOMPACTIONTHRESHOLD, cfm.getMaxCompactionThreshold());
if (minCompactionThreshold <= 0 || maxCompactionThreshold <= 0)
throw new ConfigurationException("Disabling compaction by setting compaction thresholds to 0 has been deprecated, set the compaction option 'enabled' to false instead.");
cfm.minCompactionThreshold(minCompactionThreshold);
cfm.maxCompactionThreshold(maxCompactionThreshold);
cfm.caching(CachingOptions.fromString(cfProps.getPropertyString(CFPropDefs.KW_CACHING, cfm.getCaching().toString())));
cfm.defaultTimeToLive(cfProps.getPropertyInt(CFPropDefs.KW_DEFAULT_TIME_TO_LIVE, cfm.getDefaultTimeToLive()));
cfm.speculativeRetry(CFMetaData.SpeculativeRetry.fromString(cfProps.getPropertyString(CFPropDefs.KW_SPECULATIVE_RETRY, cfm.getSpeculativeRetry().toString())));
cfm.bloomFilterFpChance(cfProps.getPropertyDouble(CFPropDefs.KW_BF_FP_CHANCE, cfm.getBloomFilterFpChance()));
cfm.memtableFlushPeriod(cfProps.getPropertyInt(CFPropDefs.KW_MEMTABLE_FLUSH_PERIOD, cfm.getMemtableFlushPeriod()));
if (!cfProps.compactionStrategyOptions.isEmpty())
{
cfm.compactionStrategyOptions(new HashMap<String, String>());
for (Map.Entry<String, String> entry : cfProps.compactionStrategyOptions.entrySet())
cfm.compactionStrategyOptions.put(entry.getKey(), entry.getValue());
}
if (!cfProps.compressionParameters.isEmpty())
{
cfm.compressionParameters(CompressionParameters.create(cfProps.compressionParameters));
}
}
}
| |
package org.sagebionetworks.repo.model.dbo.persistence;
import static org.sagebionetworks.repo.model.query.jdo.SqlConstants.COL_BACKUP_ERORR_MESSAGE;
import static org.sagebionetworks.repo.model.query.jdo.SqlConstants.COL_BACKUP_ERROR_DETAILS;
import static org.sagebionetworks.repo.model.query.jdo.SqlConstants.COL_BACKUP_ID;
import static org.sagebionetworks.repo.model.query.jdo.SqlConstants.COL_BACKUP_LOG;
import static org.sagebionetworks.repo.model.query.jdo.SqlConstants.COL_BACKUP_PROGRESS_MESSAGE;
import static org.sagebionetworks.repo.model.query.jdo.SqlConstants.COL_BACKUP_PROGRESS_TOTAL;
import static org.sagebionetworks.repo.model.query.jdo.SqlConstants.COL_BACKUP_RUNTIME;
import static org.sagebionetworks.repo.model.query.jdo.SqlConstants.COL_BACKUP_STARTED_BY;
import static org.sagebionetworks.repo.model.query.jdo.SqlConstants.COL_BACKUP_STARTED_ON;
import static org.sagebionetworks.repo.model.query.jdo.SqlConstants.COL_BACKUP_STATUS;
import static org.sagebionetworks.repo.model.query.jdo.SqlConstants.COL_BACKUP_TYPE;
import static org.sagebionetworks.repo.model.query.jdo.SqlConstants.COL_BACKUP_URL;
import static org.sagebionetworks.repo.model.query.jdo.SqlConstants.COL_BAKUP_PROGRESS_CURRENT;
import static org.sagebionetworks.repo.model.query.jdo.SqlConstants.DDL_DAEMON_STATUS;
import static org.sagebionetworks.repo.model.query.jdo.SqlConstants.TABLE_BACKUP_STATUS;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Arrays;
import org.sagebionetworks.repo.model.dbo.AutoIncrementDatabaseObject;
import org.sagebionetworks.repo.model.dbo.FieldColumn;
import org.sagebionetworks.repo.model.dbo.TableMapping;
public class DBODaemonStatus implements AutoIncrementDatabaseObject<DBODaemonStatus> {
private static FieldColumn[] FIELDS = new FieldColumn[] {
new FieldColumn("id", COL_BACKUP_ID, true),
new FieldColumn("status", COL_BACKUP_STATUS),
new FieldColumn("type", COL_BACKUP_TYPE),
new FieldColumn("startedBy", COL_BACKUP_STARTED_BY),
new FieldColumn("startedOn", COL_BACKUP_STARTED_ON),
new FieldColumn("progresssMessage", COL_BACKUP_PROGRESS_MESSAGE),
new FieldColumn("progresssCurrent", COL_BAKUP_PROGRESS_CURRENT),
new FieldColumn("progresssTotal", COL_BACKUP_PROGRESS_TOTAL),
new FieldColumn("errorMessage", COL_BACKUP_ERORR_MESSAGE),
new FieldColumn("errorDetails", COL_BACKUP_ERROR_DETAILS),
new FieldColumn("log", COL_BACKUP_LOG),
new FieldColumn("backupUrl", COL_BACKUP_URL),
new FieldColumn("totalRunTimeMS", COL_BACKUP_RUNTIME), };
@Override
public TableMapping<DBODaemonStatus> getTableMapping() {
return new TableMapping<DBODaemonStatus>() {
@Override
public DBODaemonStatus mapRow(ResultSet rs, int index)
throws SQLException {
DBODaemonStatus status = new DBODaemonStatus();
status.setId(rs.getLong(COL_BACKUP_ID));
status.setStatus(rs.getString(COL_BACKUP_STATUS));
status.setType(rs.getString(COL_BACKUP_TYPE));
status.setStartedBy(rs.getLong(COL_BACKUP_STARTED_BY));
status.setStartedOn(rs.getLong(COL_BACKUP_STARTED_ON));
status.setProgresssMessage(rs.getString(COL_BACKUP_PROGRESS_MESSAGE));
status.setProgresssCurrent(rs.getLong(COL_BAKUP_PROGRESS_CURRENT));
status.setProgresssTotal(rs.getLong(COL_BACKUP_PROGRESS_TOTAL));
status.setErrorMessage(rs.getString(COL_BACKUP_ERORR_MESSAGE));
if(rs.wasNull()){
status.setErrorMessage(null);
}
java.sql.Blob blob = rs.getBlob(COL_BACKUP_ERROR_DETAILS);
if(blob != null){
status.setErrorDetails(blob.getBytes(1, (int) blob.length()));
}
blob = rs.getBlob(COL_BACKUP_LOG);
if(blob != null){
status.setLog(blob.getBytes(1, (int) blob.length()));
}
status.setBackupUrl(rs.getString(COL_BACKUP_URL));
if(rs.wasNull()){
status.setBackupUrl(null);
}
status.setTotalRunTimeMS(rs.getLong(COL_BACKUP_RUNTIME));
return status;
}
@Override
public String getTableName() {
return TABLE_BACKUP_STATUS;
}
@Override
public String getDDLFileName() {
return DDL_DAEMON_STATUS;
}
@Override
public FieldColumn[] getFieldColumns() {
return FIELDS;
}
@Override
public Class<? extends DBODaemonStatus> getDBOClass() {
return DBODaemonStatus.class;
}
};
}
private Long id;
private String status;
private String type;
private Long startedBy;
private Long startedOn;
private String progresssMessage;
private Long progresssCurrent;
private Long progresssTotal;
private String errorMessage;
private byte[] errorDetails;
private byte[] log;
private String backupUrl;
private Long totalRunTimeMS;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public Long getStartedBy() {
return startedBy;
}
public void setStartedBy(Long startedBy) {
this.startedBy = startedBy;
}
public Long getStartedOn() {
return startedOn;
}
public void setStartedOn(Long startedOn) {
this.startedOn = startedOn;
}
public String getProgresssMessage() {
return progresssMessage;
}
public void setProgresssMessage(String progresssMessage) {
this.progresssMessage = progresssMessage;
}
public Long getProgresssCurrent() {
return progresssCurrent;
}
public void setProgresssCurrent(Long progresssCurrent) {
this.progresssCurrent = progresssCurrent;
}
public Long getProgresssTotal() {
return progresssTotal;
}
public void setProgresssTotal(Long progresssTotal) {
this.progresssTotal = progresssTotal;
}
public String getErrorMessage() {
return errorMessage;
}
public void setErrorMessage(String errorMessage) {
this.errorMessage = errorMessage;
}
public byte[] getErrorDetails() {
return errorDetails;
}
public void setErrorDetails(byte[] errorDetails) {
this.errorDetails = errorDetails;
}
public String getBackupUrl() {
return backupUrl;
}
public void setBackupUrl(String backupUrl) {
this.backupUrl = backupUrl;
}
public Long getTotalRunTimeMS() {
return totalRunTimeMS;
}
public void setTotalRunTimeMS(Long totalRunTimeMS) {
this.totalRunTimeMS = totalRunTimeMS;
}
public byte[] getLog() {
return log;
}
public void setLog(byte[] notes) {
this.log = notes;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result
+ ((backupUrl == null) ? 0 : backupUrl.hashCode());
result = prime * result + Arrays.hashCode(errorDetails);
result = prime * result
+ ((errorMessage == null) ? 0 : errorMessage.hashCode());
result = prime * result + ((id == null) ? 0 : id.hashCode());
result = prime * result + Arrays.hashCode(log);
result = prime
* result
+ ((progresssCurrent == null) ? 0 : progresssCurrent.hashCode());
result = prime
* result
+ ((progresssMessage == null) ? 0 : progresssMessage.hashCode());
result = prime * result
+ ((progresssTotal == null) ? 0 : progresssTotal.hashCode());
result = prime * result
+ ((startedBy == null) ? 0 : startedBy.hashCode());
result = prime * result
+ ((startedOn == null) ? 0 : startedOn.hashCode());
result = prime * result + ((status == null) ? 0 : status.hashCode());
result = prime * result
+ ((totalRunTimeMS == null) ? 0 : totalRunTimeMS.hashCode());
result = prime * result + ((type == null) ? 0 : type.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
DBODaemonStatus other = (DBODaemonStatus) obj;
if (backupUrl == null) {
if (other.backupUrl != null)
return false;
} else if (!backupUrl.equals(other.backupUrl))
return false;
if (!Arrays.equals(errorDetails, other.errorDetails))
return false;
if (errorMessage == null) {
if (other.errorMessage != null)
return false;
} else if (!errorMessage.equals(other.errorMessage))
return false;
if (id == null) {
if (other.id != null)
return false;
} else if (!id.equals(other.id))
return false;
if (!Arrays.equals(log, other.log))
return false;
if (progresssCurrent == null) {
if (other.progresssCurrent != null)
return false;
} else if (!progresssCurrent.equals(other.progresssCurrent))
return false;
if (progresssMessage == null) {
if (other.progresssMessage != null)
return false;
} else if (!progresssMessage.equals(other.progresssMessage))
return false;
if (progresssTotal == null) {
if (other.progresssTotal != null)
return false;
} else if (!progresssTotal.equals(other.progresssTotal))
return false;
if (startedBy == null) {
if (other.startedBy != null)
return false;
} else if (!startedBy.equals(other.startedBy))
return false;
if (startedOn == null) {
if (other.startedOn != null)
return false;
} else if (!startedOn.equals(other.startedOn))
return false;
if (status == null) {
if (other.status != null)
return false;
} else if (!status.equals(other.status))
return false;
if (totalRunTimeMS == null) {
if (other.totalRunTimeMS != null)
return false;
} else if (!totalRunTimeMS.equals(other.totalRunTimeMS))
return false;
if (type == null) {
if (other.type != null)
return false;
} else if (!type.equals(other.type))
return false;
return true;
}
@Override
public String toString() {
return "DBODaemonStatus [id=" + id + ", status=" + status + ", type="
+ type + ", startedBy=" + startedBy + ", startedOn="
+ startedOn + ", progresssMessage=" + progresssMessage
+ ", progresssCurrent=" + progresssCurrent
+ ", progresssTotal=" + progresssTotal + ", errorMessage="
+ errorMessage + ", errorDetails="
+ Arrays.toString(errorDetails) + ", log="
+ Arrays.toString(log) + ", backupUrl=" + backupUrl
+ ", totalRunTimeMS=" + totalRunTimeMS + "]";
}
}
| |
// 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 com.google.cloud.spanner.pgadapter;
import static org.hamcrest.CoreMatchers.equalTo;
import static org.hamcrest.CoreMatchers.is;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertThat;
import static org.junit.Assert.assertTrue;
import com.google.cloud.spanner.pgadapter.ProxyServer.DataFormat;
import com.google.cloud.spanner.pgadapter.parsers.ArrayParser;
import com.google.cloud.spanner.pgadapter.parsers.BinaryParser;
import com.google.cloud.spanner.pgadapter.parsers.BooleanParser;
import com.google.cloud.spanner.pgadapter.parsers.DateParser;
import com.google.cloud.spanner.pgadapter.parsers.DoubleParser;
import com.google.cloud.spanner.pgadapter.parsers.LongParser;
import com.google.cloud.spanner.pgadapter.parsers.Parser;
import com.google.cloud.spanner.pgadapter.parsers.StringParser;
import com.google.cloud.spanner.pgadapter.parsers.TimestampParser;
import java.sql.Array;
import java.sql.Date;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Timestamp;
import java.sql.Types;
import java.time.ZonedDateTime;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
import org.mockito.Mockito;
import org.postgresql.util.ByteConverter;
/**
* Testing for data format parsing; specifically anything that inherits from the {@link Parser}
* Class.
*/
@RunWith(JUnit4.class)
public class ParserTest {
private void validate(
Parser parser,
byte[] byteResult,
byte[] stringResult,
byte[] spannerResult) {
// 1. Parse to Binary
assertThat(parser.parse(DataFormat.POSTGRESQL_BINARY),
is(equalTo(byteResult)));
// 2. Parse to SpannerBinary
assertThat(parser.parse(DataFormat.POSTGRESQL_TEXT),
is(equalTo(stringResult)));
// 3. Parse to StringBinary
assertThat(parser.parse(DataFormat.SPANNER),
is(equalTo(spannerResult)));
}
@Test
public void testPositiveLongParsing() {
long value = 1234567890L;
byte[] byteResult = {0, 0, 0, 0, 73, -106, 2, -46};
byte[] stringResult = {'1', '2', '3', '4', '5', '6', '7', '8', '9', '0'};
Parser parsedValue = new LongParser(value);
validate(parsedValue, byteResult, stringResult, stringResult);
}
@Test
public void testNegativeLongParsing() {
long value = -1234567890L;
byte[] byteResult = {-1, -1, -1, -1, -74, 105, -3, 46};
byte[] stringResult = {'-', '1', '2', '3', '4', '5', '6', '7', '8', '9', '0'};
Parser parsedValue = new LongParser(value);
validate(parsedValue, byteResult, stringResult, stringResult);
}
@Test
public void testPositiveDoubleParsing() {
double value = 1234.56789d;
byte[] byteResult = {64, -109, 74, 69, -124, -12, -58, -25};
byte[] stringResult = {'1', '2', '3', '4', '.', '5', '6', '7', '8', '9'};
Parser parsedValue = new DoubleParser(value);
validate(parsedValue, byteResult, stringResult, stringResult);
}
@Test
public void testNegativeDoubleParsing() {
double value = -1234.56789d;
byte[] byteResult = {-64, -109, 74, 69, -124, -12, -58, -25};
byte[] stringResult = {'-', '1', '2', '3', '4', '.', '5', '6', '7', '8', '9'};
Parser parsedValue = new DoubleParser(value);
validate(parsedValue, byteResult, stringResult, stringResult);
}
@Test
public void testFalseBooleanParsing() {
boolean value = false;
byte[] stringResult = {'f'};
byte[] spannerResult = {'f', 'a', 'l', 's', 'e'};
Parser parsedValue = new BooleanParser(value);
validate(parsedValue, stringResult, stringResult, spannerResult);
}
@Test
public void testTrueBooleanParsing() {
boolean value = true;
byte[] stringResult = {'t'};
byte[] spannerResult = {'t', 'r', 'u', 'e'};
Parser parsedValue = new BooleanParser(value);
validate(parsedValue, stringResult, stringResult, spannerResult);
}
@Test
public void testDateParsing() {
Date value = new Date(904910400000L); // Google founding date :)
byte[] byteResult = {-1, -1, -2, 28};
byte[] stringResult = {'1', '9', '9', '8', '-', '0', '9', '-', '0', '4'};
Parser parsedValue = new DateParser(value);
validate(parsedValue, byteResult, stringResult, stringResult);
}
@Test(expected = IllegalArgumentException.class)
public void testDateParsingRejectsInvalidDateTooLong() {
byte[] result = new byte[4];
ByteConverter.int4(result, 0, Integer.MAX_VALUE);
new DateParser(result);
}
@Test
public void testDateParsingDateValidityChecks() {
assertTrue(DateParser.isDate("1998-09-01 00:00"));
assertTrue(DateParser.isDate("1998-09-01 +00:00"));
assertTrue(DateParser.isDate("1998-09-01 -00:00"));
assertFalse(DateParser.isDate("This is not a date right?"));
assertFalse(DateParser.isDate("1998-09-01 *00:00"));
assertFalse(DateParser.isDate("1998-a-01 00:00"));
assertFalse(DateParser.isDate("1998-01-a 00:00"));
assertFalse(DateParser.isDate("1998-01-01 a:00"));
assertFalse(DateParser.isDate("1998-01-01 00:a"));
assertFalse(DateParser.isDate("1998-01 00:00"));
}
@Test
public void testStringParsing() {
String value = "This is a String.";
byte[] stringResult = {'T', 'h', 'i', 's', ' ', 'i', 's', ' ', 'a', ' ', 'S', 't', 'r', 'i',
'n', 'g', '.'};
Parser parsedValue = new StringParser(value);
validate(parsedValue, stringResult, stringResult, stringResult);
}
@Test
public void testTimestampParsingBytePart() {
Timestamp value = new Timestamp(904910400000L);
byte[] byteResult = {-1, -1, -38, 1, -93, -70, 48, 0};
Parser parsedValue = new TimestampParser(value);
assertThat(parsedValue.parse(DataFormat.POSTGRESQL_BINARY),
is(equalTo(byteResult)));
}
@Test
public void testTimestampParsingTimestampValidityChecks() {
assertTrue(TimestampParser.isTimestamp("1998-09-01 00:00:00"));
assertTrue(TimestampParser.isTimestamp("1998-09-01 00:00:00.0"));
assertTrue(TimestampParser.isTimestamp("1998-09-01 00:00:00.000000000"));
assertTrue(TimestampParser.isTimestamp("1998-09-01 00:00:00.000000000Z"));
assertTrue(TimestampParser.isTimestamp("1998-09-01 00:00:00.000000000z"));
assertTrue(TimestampParser.isTimestamp("1998-09-01 00:00:00.000000000+00"));
assertTrue(TimestampParser.isTimestamp("1998-09-01 00:00:00.000000000+00:00"));
assertTrue(TimestampParser.isTimestamp("1998-09-01 00:00:00.000000000-00:00"));
assertFalse(TimestampParser.isTimestamp("This is not a timestamp right?"));
assertFalse(TimestampParser.isTimestamp("1998-09-01 00:00:00.000000000z00"));
assertFalse(TimestampParser.isTimestamp("1998-09-01 00:00:00.000000000z00:00"));
assertFalse(TimestampParser.isTimestamp("1998-09-01 00:00:00.000000000+"));
assertFalse(TimestampParser.isTimestamp("1998-09-01 00:00:00.000000000-"));
assertFalse(TimestampParser.isTimestamp("99999-09-01 00:00:00.000000000+00:00"));
assertFalse(TimestampParser.isTimestamp("aaaa-09-01 00:00:00.000000000+00:00"));
assertFalse(TimestampParser.isTimestamp("1998-aa-01 00:00:00.000000000+00:00"));
assertFalse(TimestampParser.isTimestamp("1998-09-aa 00:00:00.000000000+00:00"));
assertFalse(TimestampParser.isTimestamp("1998-09-01 aa:00:00.000000000+00:00"));
assertFalse(TimestampParser.isTimestamp("1998-09-01 00:aa:00.000000000+00:00"));
assertFalse(TimestampParser.isTimestamp("1998-09-01 00:00:aa.000000000+00:00"));
assertFalse(TimestampParser.isTimestamp("1998-09-01 00:00:00.a+00:00"));
assertFalse(TimestampParser.isTimestamp("1998-09-01 00:00:00.000000000+aa:00"));
assertFalse(TimestampParser.isTimestamp("1998-09-01 00:00:00.000000000+00:aa"));
assertFalse(TimestampParser.isTimestamp("1998-09-01 00:00:00.000000000*00:00"));
}
@Test
public void testBinaryParsing() {
byte[] value = {(byte) 0b01010101, (byte) 0b10101010};
byte[] byteResult = {(byte) 0b01010101, (byte) 0b10101010};
byte[] stringResult = {'U', '\\', '2', '5', '2'};
Parser parsedValue = new BinaryParser(value);
validate(parsedValue, byteResult, stringResult, byteResult);
}
@Test
public void testStringArrayParsing() throws SQLException {
String[] value = {"abc", "def", "jhi"};
byte[] byteResult = {
0, 0, 0, 1, 0, 0, 0, 1,
-1, -1, -1, -9, 0, 0, 0,
3, 0, 0, 0, 0, 0, 0, 0,
3, 97, 98, 99, 0, 0, 0,
3, 100, 101, 102, 0, 0,
0, 3, 106, 104, 105
};
byte[] stringResult = {'{', '"', 'a', 'b', 'c', '"', ',', '"', 'd', 'e', 'f', '"', ',', '"',
'j', 'h', 'i', '"', '}'};
byte[] spannerResult = {'[', '"', 'a', 'b', 'c', '"', ',', '"', 'd', 'e', 'f', '"', ',', '"',
'j', 'h', 'i', '"', ']'};
Array sqlArray = Mockito.mock(Array.class);
ResultSet resultSet = Mockito.mock(ResultSet.class);
Mockito.when(sqlArray.getBaseType()).thenReturn(Types.NVARCHAR);
Mockito.when(sqlArray.getArray()).thenReturn(value);
Mockito.when(resultSet.getArray(0)).thenReturn(sqlArray);
Parser parser = new ArrayParser(resultSet, 0);
validate(parser, byteResult, stringResult, spannerResult);
}
@Test
public void testLongArrayParsing() throws SQLException {
Long[] value = {1L, 2L, 3L};
byte[] byteResult = {
0, 0, 0, 1, 0, 0, 0, 1,
-1, -1, -1, -5, 0, 0, 0,
3, 0, 0, 0, 0, 0, 0, 0,
8, 0, 0, 0, 0, 0, 0, 0,
1, 0, 0, 0, 8, 0, 0, 0,
0, 0, 0, 0, 2, 0, 0, 0,
8, 0, 0, 0, 0, 0, 0, 0,
3};
byte[] stringResult = {'{', '1', ',', '2', ',', '3', '}'};
byte[] spannerResult = {'[', '1', ',', '2', ',', '3', ']'};
Array sqlArray = Mockito.mock(Array.class);
ResultSet resultSet = Mockito.mock(ResultSet.class);
Mockito.when(sqlArray.getBaseType()).thenReturn(Types.BIGINT);
Mockito.when(sqlArray.getArray()).thenReturn(value);
Mockito.when(resultSet.getArray(0)).thenReturn(sqlArray);
Parser parser = new ArrayParser(resultSet, 0);
validate(parser, byteResult, stringResult, spannerResult);
}
@Test(expected = IllegalArgumentException.class)
public void testArrayArrayParsingFails() throws SQLException {
Long[] value = {1L, 2L, 3L};
Array sqlArray = Mockito.mock(Array.class);
ResultSet resultSet = Mockito.mock(ResultSet.class);
Mockito.when(sqlArray.getBaseType()).thenReturn(Types.ARRAY);
Mockito.when(sqlArray.getArray()).thenReturn(value);
Mockito.when(resultSet.getArray(0)).thenReturn(sqlArray);
new ArrayParser(resultSet, 0);
}
}
| |
package com.atlassian.jira.plugins.dvcs.dao.impl;
import com.atlassian.activeobjects.external.ActiveObjects;
import com.atlassian.event.api.EventPublisher;
import com.atlassian.jira.plugins.dvcs.activeobjects.v3.SyncAuditLogMapping;
import com.atlassian.jira.plugins.dvcs.analytics.event.DvcsSyncEndAnalyticsEvent;
import com.atlassian.jira.plugins.dvcs.dao.SyncAuditLogDao;
import com.atlassian.jira.plugins.dvcs.util.ActiveObjectsUtils;
import com.atlassian.plugin.spring.scanner.annotation.imports.ComponentImport;
import com.atlassian.sal.api.transaction.TransactionCallback;
import net.java.ao.Query;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.exception.ExceptionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.Callable;
import static com.google.common.base.Preconditions.checkNotNull;
@Component
public class SyncAuditLogDaoImpl implements SyncAuditLogDao
{
private static final int BIG_DATA_PAGESIZE = 200;
private static final int ROTATION_PERIOD = 1000 * 60 * 60 * 24 * 7;
private final ActiveObjects ao;
private static final Logger log = LoggerFactory.getLogger(SyncAuditLogDaoImpl.class);
private EventPublisher eventPublisher;
@Autowired
public SyncAuditLogDaoImpl(@ComponentImport ActiveObjects ao, @ComponentImport EventPublisher publisher)
{
super();
this.ao = checkNotNull(ao);
this.eventPublisher = checkNotNull(publisher);
}
@Override
public SyncAuditLogMapping newSyncAuditLog(final int repoId, final String syncType, final Date startDate)
{
return doTxQuietly(new Callable<SyncAuditLogMapping>(){
@Override
public SyncAuditLogMapping call() throws Exception
{
//
rotate(repoId);
//
Map<String, Object> data = new HashMap<String, Object>();
data.put(SyncAuditLogMapping.REPO_ID, repoId);
data.put(SyncAuditLogMapping.SYNC_TYPE, syncType);
data.put(SyncAuditLogMapping.START_DATE, startDate);
data.put(SyncAuditLogMapping.SYNC_STATUS, SyncAuditLogMapping.SYNC_STATUS_RUNNING);
data.put(SyncAuditLogMapping.TOTAL_ERRORS , 0);
return ao.create(SyncAuditLogMapping.class, data);
}
private void rotate(int repoId)
{
ActiveObjectsUtils.delete(ao, SyncAuditLogMapping.class,
Query.select().from(SyncAuditLogMapping.class).where(SyncAuditLogMapping.REPO_ID + " = ? AND " + SyncAuditLogMapping.START_DATE + " < ?" , repoId, new Date(System.currentTimeMillis() - ROTATION_PERIOD))
);
}
});
}
@Override
public SyncAuditLogMapping finish(final int syncId, final Date firstRequestDate, final int numRequests, final int flightTimeMs, final Date finishDate)
{
return doTxQuietly(new Callable<SyncAuditLogMapping>(){
@Override
public SyncAuditLogMapping call() throws Exception
{
SyncAuditLogMapping mapping = find(syncId);
if (mapping != null)
{
mapping.setFirstRequestDate(firstRequestDate);
mapping.setEndDate(finishDate);
mapping.setNumRequests(numRequests);
mapping.setFlightTimeMs(flightTimeMs);
if (StringUtils.isNotBlank(mapping.getExcTrace()))
{
mapping.setSyncStatus(SyncAuditLogMapping.SYNC_STATUS_FAILED);
} else
{
mapping.setSyncStatus(SyncAuditLogMapping.SYNC_STATUS_SUCCESS);
}
mapping.save();
fireAnalyticsEvent(mapping);
}
return mapping;
}
});
}
private void fireAnalyticsEvent(SyncAuditLogMapping sync)
{
String syncTypeString = sync.getSyncType() == null ? "" : sync.getSyncType();
boolean soft = syncTypeString.contains(SyncAuditLogMapping.SYNC_TYPE_SOFT);
boolean commits = syncTypeString.contains(SyncAuditLogMapping.SYNC_TYPE_CHANGESETS);
boolean pullRequests = syncTypeString.contains(SyncAuditLogMapping.SYNC_TYPE_PULLREQUESTS);
boolean webhook = syncTypeString.contains(SyncAuditLogMapping.SYNC_TYPE_WEBHOOKS);
eventPublisher.publish(new DvcsSyncEndAnalyticsEvent(soft, commits, pullRequests, webhook, sync.getEndDate(),
sync.getEndDate().getTime() - sync.getStartDate().getTime()));
}
@Override
public SyncAuditLogMapping pause(final int syncId)
{
return status(syncId);
}
protected SyncAuditLogMapping status(final int syncId)
{
return doTxQuietly(new Callable<SyncAuditLogMapping>(){
@Override
public SyncAuditLogMapping call() throws Exception
{
SyncAuditLogMapping mapping = find(syncId);
if (mapping != null)
{
mapping.setSyncStatus(SyncAuditLogMapping.SYNC_STATUS_SLEEPING);
mapping.save();
}
return mapping;
}
});
}
@Override
public SyncAuditLogMapping resume(final int syncId)
{
return doTxQuietly(new Callable<SyncAuditLogMapping>(){
@Override
public SyncAuditLogMapping call() throws Exception
{
SyncAuditLogMapping mapping = find(syncId);
if (mapping != null)
{
if (SyncAuditLogMapping.SYNC_STATUS_SLEEPING.equals(mapping.getSyncStatus()))
{
mapping.setSyncStatus(SyncAuditLogMapping.SYNC_STATUS_RUNNING);
mapping.save();
}
}
return mapping;
}
});
}
@Override
public int removeAllForRepo(final int repoId)
{
Integer ret = doTxQuietly(new Callable<Integer>(){
@Override
public Integer call() throws Exception
{
return ActiveObjectsUtils.delete(ao, SyncAuditLogMapping.class, repoQuery(repoId).q());
}
});
return ret == null ? -1 : ret;
}
@Override
public SyncAuditLogMapping setException(final int syncId, final Throwable t, final boolean overwriteOld)
{
return doTxQuietly(new Callable<SyncAuditLogMapping>(){
@Override
public SyncAuditLogMapping call() throws Exception
{
SyncAuditLogMapping found = find(syncId);
boolean noExceptionYet = StringUtils.isBlank(found.getExcTrace());
if (t != null && (overwriteOld || noExceptionYet))
{
found.setExcTrace(ExceptionUtils.getStackTrace(t));
}
found.setTotalErrors(found.getTotalErrors() + 1);
found.save();
return found;
}
});
}
@Override
public SyncAuditLogMapping[] getAllForRepo(final int repoId, final Integer page)
{
return doTxQuietly(new Callable<SyncAuditLogMapping []>(){
@Override
public SyncAuditLogMapping [] call() throws Exception
{
return ao.find(SyncAuditLogMapping.class, repoQuery(repoId).page(page).order(SyncAuditLogMapping.START_DATE + " DESC"));
}
});
}
@Override
public SyncAuditLogMapping[] getAll(final Integer page)
{
return doTxQuietly(new Callable<SyncAuditLogMapping []>(){
@Override
public SyncAuditLogMapping [] call() throws Exception
{
return ao.find(SyncAuditLogMapping.class, pageQuery(Query.select().order(SyncAuditLogMapping.START_DATE + " DESC"), page));
}
});
}
@Override
public SyncAuditLogMapping getLastForRepo(final int repoId)
{
return doTxQuietly(new Callable<SyncAuditLogMapping>(){
@Override
public SyncAuditLogMapping call() throws Exception
{
SyncAuditLogMapping[] found = ao.find(SyncAuditLogMapping.class,
repoQuery(repoId).q().limit(1).order(SyncAuditLogMapping.START_DATE + " DESC"));
return found.length == 1 ? found[0] : null;
}
});
}
@Override
public SyncAuditLogMapping getLastSuccessForRepo(final int repoId)
{
return doTxQuietly(new Callable<SyncAuditLogMapping>(){
@Override
public SyncAuditLogMapping call() throws Exception
{
Query query = statusQueryLimitOne(repoId, SyncAuditLogMapping.SYNC_STATUS_SUCCESS);
SyncAuditLogMapping[] found = ao.find(SyncAuditLogMapping.class, query);
return found.length == 1 ? found[0] : null;
}
});
}
@Override
public SyncAuditLogMapping getLastFailedForRepo(final int repoId)
{
return doTxQuietly(new Callable<SyncAuditLogMapping>(){
@Override
public SyncAuditLogMapping call() throws Exception
{
Query query = statusQueryLimitOne(repoId, SyncAuditLogMapping.SYNC_STATUS_FAILED);
SyncAuditLogMapping[] found = ao.find(SyncAuditLogMapping.class, query);
return found.length == 1 ? found[0] : null;
}
});
}
@Override
public boolean hasException(final int syncId)
{
Boolean ret = doTxQuietly(new Callable<Boolean>(){
@Override
public Boolean call() throws Exception
{
SyncAuditLogMapping found = find(syncId);
return found != null && StringUtils.isNotBlank(found.getExcTrace());
}
});
return ret == null ? false : ret;
}
private SyncAuditLogMapping find(int syncId)
{
return ao.get(SyncAuditLogMapping.class, syncId);
}
private PageableQuery repoQuery(final int repoId)
{
return new PageableQuery(repoId);
}
private Query statusQueryLimitOne(int repoId, String status)
{
return Query.select()
.from(SyncAuditLogMapping.class)
.where(SyncAuditLogMapping.REPO_ID + " = ? AND " + SyncAuditLogMapping.SYNC_STATUS + " = ?", repoId, status)
.limit(1)
.order(SyncAuditLogMapping.START_DATE + " DESC");
}
private <RET> RET doTxQuietly(final Callable<RET> callable) {
return
ao.executeInTransaction(new TransactionCallback<RET>()
{
@Override
public RET doInTransaction()
{
try
{
return callable.call();
} catch (Throwable e)
{
log.warn("Problem during sync audit log. " + e.getMessage());
if (log.isDebugEnabled())
{
log.debug("Sync audit log.", e);
}
return null;
}
}
});
}
class PageableQuery {
private Query q;
private PageableQuery(int repoId)
{
super();
this.q = Query.select().from(SyncAuditLogMapping.class).where(SyncAuditLogMapping.REPO_ID + " = ?", repoId);
}
PageableQuery offset(int offset)
{
q.setOffset(offset);
return this;
}
PageableQuery limit (int limit) {
q.setLimit(limit);
return this;
}
Query page(Integer page) {
pageQuery(q, page);
return q;
}
Query q() {
return q;
}
}
private static Query pageQuery(Query q, Integer page)
{
q.setLimit(BIG_DATA_PAGESIZE);
if (page == null)
{
q.setOffset(0);
} else {
q.setOffset(BIG_DATA_PAGESIZE * page);
}
return q;
}
}
| |
/**
* Copyright (C) 2009-2013 Dell, Inc.
* See annotations for authorship information
*
* ====================================================================
* 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.dasein.cloud.aws.identity;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Locale;
import java.util.Map;
import org.apache.log4j.Logger;
import org.dasein.cloud.CloudException;
import org.dasein.cloud.InternalException;
import org.dasein.cloud.ProviderContext;
import org.dasein.cloud.Requirement;
import org.dasein.cloud.aws.AWSCloud;
import org.dasein.cloud.aws.compute.EC2Exception;
import org.dasein.cloud.aws.compute.EC2Method;
import org.dasein.cloud.identity.SSHKeypair;
import org.dasein.cloud.identity.ServiceAction;
import org.dasein.cloud.identity.ShellKeyCapabilities;
import org.dasein.cloud.identity.ShellKeySupport;
import org.dasein.cloud.util.APITrace;
import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
public class Keypairs implements ShellKeySupport {
static private final Logger logger = AWSCloud.getLogger(Keypairs.class);
private AWSCloud provider = null;
private volatile transient KeypairsCapabilities capabilities;
public Keypairs(@Nonnull AWSCloud provider) {
this.provider = provider;
}
@Override
public @Nonnull SSHKeypair createKeypair(@Nonnull String name) throws InternalException, CloudException {
APITrace.begin(provider, "Keypair.createKeypair");
try {
ProviderContext ctx = provider.getContext();
if( ctx == null ) {
throw new CloudException("No context was established for this call.");
}
String regionId = ctx.getRegionId();
if( regionId == null ) {
throw new CloudException("No region was set for this request.");
}
Map<String,String> parameters = provider.getStandardParameters(provider.getContext(), EC2Method.CREATE_KEY_PAIR);
EC2Method method;
NodeList blocks;
Document doc;
parameters.put("KeyName", name);
method = new EC2Method(provider, provider.getEc2Url(), parameters);
try {
doc = method.invoke();
}
catch( EC2Exception e ) {
logger.error(e.getSummary());
throw new CloudException(e);
}
String material = null, fingerprint = null;
blocks = doc.getElementsByTagName("CreateKeyPairResponse");
for( int i=0; i<blocks.getLength(); i++ ) {
Node item = blocks.item(i);
NodeList attrs = item.getChildNodes();
for( int j=0; j<attrs.getLength(); j++ ) {
Node attr = attrs.item(j);
if( attr.getNodeName().equalsIgnoreCase("keyMaterial")) {
material = attr.getFirstChild().getNodeValue();
}
else if( attr.getNodeName().equalsIgnoreCase("keyFingerPrint")) {
fingerprint = attr.getFirstChild().getNodeValue();
}
}
}
if( fingerprint == null || material == null ) {
throw new CloudException("Invalid response to attempt to create the keypair");
}
SSHKeypair key = new SSHKeypair();
try {
key.setPrivateKey(material.getBytes("utf-8"));
}
catch( UnsupportedEncodingException e ) {
throw new InternalException(e);
}
key.setFingerprint(fingerprint);
key.setName(name);
key.setProviderKeypairId(name);
key.setProviderOwnerId(ctx.getAccountNumber());
key.setProviderRegionId(regionId);
return key;
}
finally {
APITrace.end();
}
}
@Override
public void deleteKeypair(@Nonnull String name) throws InternalException, CloudException {
APITrace.begin(provider, "Keypair.deleteKeypair");
try {
Map<String,String> parameters = provider.getStandardParameters(provider.getContext(), EC2Method.DELETE_KEY_PAIR);
EC2Method method;
NodeList blocks;
Document doc;
parameters.put("KeyName", name);
method = new EC2Method(provider, provider.getEc2Url(), parameters);
try {
doc = method.invoke();
}
catch( EC2Exception e ) {
String code = e.getCode();
if( code != null && code.startsWith("InvalidKeyPair") ) {
return;
}
logger.error(e.getSummary());
throw new CloudException(e);
}
blocks = doc.getElementsByTagName("return");
if( blocks.getLength() > 0 ) {
if( !blocks.item(0).getFirstChild().getNodeValue().equalsIgnoreCase("true") ) {
throw new CloudException("Deletion of keypair denied.");
}
}
}
finally {
APITrace.end();
}
}
@Override
public @Nullable String getFingerprint(@Nonnull String name) throws InternalException, CloudException {
APITrace.begin(provider, "Keypair.getFingerprint");
try {
ProviderContext ctx = provider.getContext();
if( ctx == null ) {
throw new InternalException("No context was established for this call.");
}
Map<String,String> parameters = provider.getStandardParameters(provider.getContext(), EC2Method.DESCRIBE_KEY_PAIRS);
EC2Method method;
NodeList blocks;
Document doc;
parameters.put("KeyName.1", name);
method = new EC2Method(provider, provider.getEc2Url(), parameters);
try {
doc = method.invoke();
}
catch( EC2Exception e ) {
String code = e.getCode();
if( code != null && code.startsWith("InvalidKeyPair") ) {
return null;
}
logger.error(e.getSummary());
throw new CloudException(e);
}
blocks = doc.getElementsByTagName("keyFingerprint");
if( blocks.getLength() > 0 ) {
return blocks.item(0).getFirstChild().getNodeValue().trim();
}
return null;
}
finally {
APITrace.end();
}
}
@Override
public Requirement getKeyImportSupport() throws CloudException, InternalException {
return Requirement.OPTIONAL;
}
@Override
public @Nullable SSHKeypair getKeypair(@Nonnull String name) throws InternalException, CloudException {
APITrace.begin(provider, "Keypair.getKeypair");
try {
ProviderContext ctx = provider.getContext();
if( ctx == null ) {
throw new CloudException("No context was established for this call.");
}
String regionId = ctx.getRegionId();
if( regionId == null ) {
throw new CloudException("No region was set for this request.");
}
Map<String,String> parameters = provider.getStandardParameters(provider.getContext(), EC2Method.DESCRIBE_KEY_PAIRS);
EC2Method method;
NodeList blocks;
Document doc;
parameters.put("KeyName.1", name);
method = new EC2Method(provider, provider.getEc2Url(), parameters);
try {
doc = method.invoke();
}
catch( EC2Exception e ) {
String code = e.getCode();
if( code != null && code.startsWith("InvalidKeyPair") ) {
return null;
}
logger.error(e.getSummary());
throw new CloudException(e);
}
blocks = doc.getElementsByTagName("item");
for( int i=0; i<blocks.getLength(); i++ ) {
Node item = blocks.item(i);
NodeList attrs = item.getChildNodes();
String fingerprint = null;
String keyName = null;
for( int j=0; j<attrs.getLength(); j++ ) {
Node attr = attrs.item(j);
if( attr.getNodeName().equalsIgnoreCase("keyFingerprint") && attr.hasChildNodes() ) {
fingerprint = attr.getFirstChild().getNodeValue().trim();
}
else if( attr.getNodeName().equalsIgnoreCase("keyName") && attr.hasChildNodes() ) {
keyName = attr.getFirstChild().getNodeValue().trim();
}
}
if( keyName != null && keyName.equals(name) && fingerprint != null ) {
SSHKeypair kp = new SSHKeypair();
kp.setFingerprint(fingerprint);
kp.setName(keyName);
kp.setPrivateKey(null);
kp.setPublicKey(null);
kp.setProviderKeypairId(keyName);
kp.setProviderOwnerId(ctx.getAccountNumber());
kp.setProviderRegionId(regionId);
return kp;
}
}
return null;
}
finally {
APITrace.end();
}
}
@Override
public @Nonnull String getProviderTermForKeypair(@Nonnull Locale locale) {
return "keypair";
}
@Override
public @Nonnull ShellKeyCapabilities getCapabilities() throws CloudException, InternalException {
if( capabilities == null ) {
capabilities = new KeypairsCapabilities(provider);
}
return capabilities;
}
@Override
public @Nonnull SSHKeypair importKeypair(@Nonnull String name, @Nonnull String material) throws InternalException, CloudException {
APITrace.begin(provider, "Keypair.importKeypair");
try {
ProviderContext ctx = provider.getContext();
if( ctx == null ) {
throw new CloudException("No context was established for this call.");
}
String regionId = ctx.getRegionId();
if( regionId == null ) {
throw new CloudException("No region was set for this request.");
}
Map<String,String> parameters = provider.getStandardParameters(provider.getContext(), EC2Method.IMPORT_KEY_PAIR);
EC2Method method;
NodeList blocks;
Document doc;
parameters.put("KeyName", name);
parameters.put("PublicKeyMaterial", material);
method = new EC2Method(provider, provider.getEc2Url(), parameters);
try {
doc = method.invoke();
}
catch( EC2Exception e ) {
logger.error(e.getSummary());
throw new CloudException(e);
}
String fingerprint = null;
blocks = doc.getElementsByTagName("ImportKeyPairResponse");
for( int i=0; i<blocks.getLength(); i++ ) {
Node item = blocks.item(i);
NodeList attrs = item.getChildNodes();
for( int j=0; j<attrs.getLength(); j++ ) {
Node attr = attrs.item(j);
if( attr.getNodeName().equalsIgnoreCase("keyFingerPrint")) {
fingerprint = attr.getFirstChild().getNodeValue();
}
}
}
if( fingerprint == null ) {
throw new CloudException("Invalid response to attempt to create the keypair");
}
SSHKeypair key = new SSHKeypair();
try {
key.setPrivateKey(material.getBytes("utf-8"));
}
catch( UnsupportedEncodingException e ) {
throw new InternalException(e);
}
key.setFingerprint(fingerprint);
key.setName(name);
key.setProviderKeypairId(name);
key.setProviderOwnerId(ctx.getAccountNumber());
key.setProviderRegionId(regionId);
return key;
}
finally {
APITrace.end();
}
}
@Override
public boolean isSubscribed() throws CloudException, InternalException {
APITrace.begin(provider, "Keypair.isSubscribed");
try {
provider.testContext();
return true;
}
finally {
APITrace.end();
}
}
@Override
public @Nonnull Collection<SSHKeypair> list() throws InternalException, CloudException {
APITrace.begin(provider, "Keypair.list");
try {
ProviderContext ctx = provider.getContext();
if( ctx == null ) {
throw new CloudException("No context was established for this call.");
}
String regionId = ctx.getRegionId();
if( regionId == null ) {
throw new CloudException("No region was set for this request.");
}
Map<String,String> parameters = provider.getStandardParameters(provider.getContext(), EC2Method.DESCRIBE_KEY_PAIRS);
ArrayList<SSHKeypair> keypairs = new ArrayList<SSHKeypair>();
EC2Method method;
NodeList blocks;
Document doc;
method = new EC2Method(provider, provider.getEc2Url(), parameters);
try {
doc = method.invoke();
}
catch( EC2Exception e ) {
String code = e.getCode();
if( code != null && code.startsWith("InvalidKeyPair") ) {
return Collections.emptyList();
}
logger.error(e.getSummary());
throw new CloudException(e);
}
blocks = doc.getElementsByTagName("item");
for( int i=0; i<blocks.getLength(); i++ ) {
Node item = blocks.item(i);
if( item.hasChildNodes() ) {
NodeList attrs = item.getChildNodes();
String fingerprint = null;
String keyName = null;
for( int j=0; j<attrs.getLength(); j++ ) {
Node attr = attrs.item(j);
if( attr.getNodeName().equalsIgnoreCase("keyName") && attr.hasChildNodes() ) {
keyName = attr.getFirstChild().getNodeValue().trim();
}
else if( attr.getNodeName().equalsIgnoreCase("keyFingerprint") && attr.hasChildNodes() ) {
fingerprint = attr.getFirstChild().getNodeValue().trim();
}
}
if( keyName != null && fingerprint != null ) {
SSHKeypair keypair = new SSHKeypair();
keypair.setName(keyName);
keypair.setProviderKeypairId(keyName);
keypair.setFingerprint(fingerprint);
keypair.setProviderOwnerId(ctx.getAccountNumber());
keypair.setProviderRegionId(regionId);
keypairs.add(keypair);
}
}
}
return keypairs;
}
finally {
APITrace.end();
}
}
@Override
public @Nonnull String[] mapServiceAction(@Nonnull ServiceAction action) {
if( action.equals(ShellKeySupport.ANY) ) {
return new String[] { EC2Method.EC2_PREFIX + "*" };
}
if( action.equals(ShellKeySupport.CREATE_KEYPAIR) ) {
return new String[] { EC2Method.EC2_PREFIX + EC2Method.CREATE_KEY_PAIR, EC2Method.EC2_PREFIX + EC2Method.IMPORT_KEY_PAIR };
}
else if( action.equals(ShellKeySupport.GET_KEYPAIR) || action.equals(ShellKeySupport.LIST_KEYPAIR) ) {
return new String[] { EC2Method.EC2_PREFIX + EC2Method.DESCRIBE_KEY_PAIRS };
}
else if( action.equals(ShellKeySupport.REMOVE_KEYPAIR) ) {
return new String[] { EC2Method.EC2_PREFIX + EC2Method.DELETE_KEY_PAIR };
}
return new String[0];
}
}
| |
package net.yorch;
import static spark.Spark.get;
import static spark.Spark.halt;
import static spark.Spark.post;
import java.io.File;
import java.io.FilenameFilter;
import java.io.IOException;
import java.io.StringWriter;
import java.io.UnsupportedEncodingException;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import javax.servlet.MultipartConfigElement;
import javax.servlet.ServletException;
import javax.servlet.http.Part;
import org.zeroturnaround.zip.ZipUtil;
import spark.Request;
import spark.Response;
import spark.Route;
import spark.Spark;
/**
* WebApp<br>
*
* Web Application<br><br>
*
* Copyright 2017 Jorge Alberto Ponce Turrubiates
*
* 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.
*
* @version 1.0.0, 2017-02-03
* @author <a href="mailto:the.yorch@gmail.com">Jorge Alberto Ponce Turrubiates</a>
*/
public class WebApp {
/**
* Application User
*
* VAR String appUser Application User
* @access private
*/
private String appUser = "";
/**
* User Password
*
* VAR String appPassword User Password
* @access private
*/
private String appPassword = "";
/**
* Directory Base
*
* VAR String basedir Directory Base
* @access private
*/
private String basedir = "";
/**
* Default Database Connection
*
* VAR OgrConnection dftDb Default Database Connection
* @access private
*/
private OgrConnection dftDb;
/**
* Constructor of WebApp
*
* @param port int Application Port
* @param user String Application User
* @param password String Application Password
* @param basedir String Directory Base
* @param db OgrConnection Database Connection
* @see WebApp
*/
public WebApp(int port, String user, String password, String basedir, OgrConnection db) {
this.appUser = user;
this.appPassword = password;
this.basedir = basedir;
this.dftDb = db;
// Set Port
Spark.port(port);
// Set Public Files
Spark.staticFileLocation("/public");
// External Dir
Spark.externalStaticFileLocation(this.basedir);
// Path /
get("/", new Route() {
@Override
public Object handle(Request request, Response response) {
StringWriter template = null;
if (existsSession(request)){
request.session().attribute("appdir", getBaseDir());
template = getOgrTemplate();
}
else{
String LoginError = request.session().attribute("loginerror");
template = getLoginTemplate(LoginError);
}
if (template == null)
halt(500, "Internal Error");
response.status(200);
// Returns Template
return template;
}
});
// Path Exit
get("/exit", new Route() {
@Override
public Object handle(Request request, Response response) {
request.session().removeAttribute("appuser");
request.session().removeAttribute("loginerror");
response.redirect("/");
return "exit";
}
});
// Path getfiles
post("/getfiles", new Route() {
@Override
public Object handle(Request request, Response response) {
String dir = request.queryParams("dir");
String fs = getFiles(dir);
return fs;
}
});
// Upload Zip file
post("/upload", new Route() {
@Override
public Object handle(Request request, Response response) {
String selDir = request.session().attribute("appdir");
MultipartConfigElement multipartConfigElement = new MultipartConfigElement(selDir);
request.raw().setAttribute("org.eclipse.multipartConfig", multipartConfigElement);
String retResponse = "";
try {
Part file = (Part) request.raw().getPart("file");
String fileName = UUID.randomUUID().toString().replace("-", "") + ".zip";
retResponse = fileName;
file.write(fileName);
} catch (IOException | ServletException e) {
e.printStackTrace();
}
return retResponse;
}
});
// Set Selected Directory
post("/setdir", new Route() {
@Override
public Object handle(Request request, Response response) {
String dir = request.queryParams("dir");
request.session().attribute("appdir", dir);
response.status(200);
return dir;
}
});
// Unzip Zip File
post("/unzip", new Route() {
@Override
public Object handle(Request request, Response response) {
String retResponse = "OK";
String dir = request.queryParams("dir");
String zip = request.queryParams("zip");
String curDir = request.session().attribute("appdir");
dir = curDir + dir;
if (WebApp.dirExists(dir)){
retResponse = "BAD";
}
else {
// create Dir
new File(dir).mkdir();
// Unzip File
ZipUtil.unpack(new File(zip), new File(dir));
}
response.status(200);
return retResponse;
}
});
// Zip Folder
post("/zip", new Route() {
@Override
public Object handle(Request request, Response response) {
String retResponse = "OK";
String dir = request.queryParams("dir");
String zip = request.queryParams("zipname");
String curDir = request.session().attribute("appdir");
zip = curDir + "../" + zip;
if (WebApp.fileExists(zip)){
retResponse = "BAD";
}
else {
// Zip Directory
ZipUtil.pack(new File(dir), new File(zip));
}
response.status(200);
return retResponse;
}
});
// Get OGR Tables
get("/gettables", new Route() {
@Override
public Object handle(Request request, Response response) {
OgrConnection conn = getDftDb();
response.status(200);
String jsonTab = conn.getOgrTables();
return jsonTab;
}
});
// Import Shapefile
post("/import", new Route() {
@Override
public Object handle(Request request, Response response) {
String retResponse = "OK";
String sf = request.queryParams("file");
String tn = request.queryParams("table");
String pj = request.queryParams("proj");
WOgr ogr = new WOgr();
if (! ogr.importToDb(getDftDb(), tn, sf, pj, pj))
retResponse = "BAD";
ogr = null;
response.status(200);
return retResponse;
}
});
// Export Table to Shapefile
post("/export", new Route() {
@Override
public Object handle(Request request, Response response) {
String retResponse = "OK";
String sf = request.queryParams("file");
String tn = request.queryParams("table");
String pj = request.queryParams("proj");
String curDir = request.session().attribute("appdir");
sf = curDir + sf;
WOgr ogr = new WOgr();
if (! ogr.exportFromDb(getDftDb(), tn, sf, pj, pj))
retResponse = "BAD";
ogr = null;
response.status(200);
return retResponse;
}
});
// Make Directory
post("/mkdir", new Route() {
@Override
public Object handle(Request request, Response response) {
String retResponse = "OK";
String dir = request.queryParams("dir");
String curDir = request.session().attribute("appdir");
dir = curDir + dir;
if (WebApp.dirExists(dir)){
retResponse = "BAD";
}
else {
// create Dir
new File(dir).mkdir();
}
response.status(200);
return retResponse;
}
});
// Web Login
post("/webauth", new Route() {
@Override
public Object handle(Request request, Response response) {
String user = request.queryParams("txtUser");
String password = request.queryParams("txtPassword");
if (login(user, password)){
request.session().attribute("appuser", user);
response.redirect("/");
return "";
}
else{
request.session().attribute("loginerror", "Could not login with credentials");
response.status(401);
response.redirect("/");
return "Could not login with credentials";
}
}
});
}
/**
* Return Login Template
*
* @param loginError String Error Login if Exits
* @return StringWriter
*/
private StringWriter getLoginTemplate(String loginError) {
Map<String, Object> tempData = new HashMap<String, Object>();
tempData.put("loginError", loginError);
FMTemplate loginTemp = new FMTemplate("login.ftl", tempData);
StringWriter swLogin = loginTemp.get();
loginTemp = null;
return swLogin;
}
/**
* Get Ogr Template
*
* @return StringWriter
*/
private StringWriter getOgrTemplate() {
Map<String, Object> tempData = new HashMap<String, Object>();
tempData.put("baseDir", this.basedir);
FMTemplate ogrTemp = new FMTemplate("webogr.ftl", tempData);
StringWriter swOgr = ogrTemp.get();
ogrTemp = null;
return swOgr;
}
/**
* Checks login of user and password
*
* @param user User Application
* @param password Password User
* @return boolean
*/
private boolean login(String user, String password){
if (user.equals(this.appUser) && password.equals(this.appPassword))
return true;
else
return false;
}
/**
* Gets Base Directory
*
* @return String
*/
private String getBaseDir(){
return this.basedir;
}
/**
* Get Default Database Connection
*
* @return OgrConnection
*/
private OgrConnection getDftDb(){
return this.dftDb;
}
/**
* Checks if Session Exists
*
* @return boolean
*/
private boolean existsSession(Request request){
boolean retValue = false;
String user = request.session().attribute("appuser");
if (user != null){
retValue = true;
}
return retValue;
}
/**
* Check if Directory exists
*
* @param dir String Directory
* @return boolean
*/
public static boolean dirExists(String dir){
File dirFile = new File(dir);
return dirFile.exists();
}
/**
* Check if File Exists
*
* @param filePath String File Full Name
* @return boolean
*/
public static boolean fileExists(String filePath){
File file = new File(filePath);
return file.exists();
}
/**
* Return Files Structure
*
* @param dir String Subdirectory
* @return String Files Structure
*/
private String getFiles(String dir){
StringBuffer fs = new StringBuffer("");
if (dir == null) {
return "";
}
if (dir.charAt(dir.length()-1) == '\\') {
dir = dir.substring(0, dir.length()-1) + "/";
} else if (dir.charAt(dir.length()-1) != '/') {
dir += "/";
}
try {
dir = java.net.URLDecoder.decode(dir, "UTF-8");
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
if (dir.equals("./")){
dir = this.basedir;
}
if (new File(dir).exists()) {
String[] files = new File(dir).list(new FilenameFilter() {
public boolean accept(File dir, String name) {
return name.charAt(0) != '.';
}
});
Arrays.sort(files, String.CASE_INSENSITIVE_ORDER);
fs.append("<ul class=\"jqueryFileTree\" style=\"display: none;\">");
// All dirs
for (String file : files) {
if (new File(dir, file).isDirectory()) {
fs.append("<li class=\"directory collapsed\"><a href=\"#\" rel=\"" + dir + file + "/\">"
+ file + "</a></li>");
}
}
// All files
for (String file : files) {
if (!new File(dir, file).isDirectory()) {
int dotIndex = file.lastIndexOf('.');
String ext = dotIndex > 0 ? file.substring(dotIndex + 1) : "";
fs.append("<li class=\"file ext_" + ext + "\"><a href=\"#\" rel=\"" + dir + file + "\">"
+ file + "</a></li>");
}
}
fs.append("</ul>");
}
return fs.toString();
}
}
| |
// Generated by the protocol buffer compiler. DO NOT EDIT!
// source: google/ads/googleads/v10/common/simulation.proto
package com.google.ads.googleads.v10.common;
/**
* <pre>
* A container for simulation points for simulations of type CPC_BID.
* </pre>
*
* Protobuf type {@code google.ads.googleads.v10.common.CpcBidSimulationPointList}
*/
public final class CpcBidSimulationPointList extends
com.google.protobuf.GeneratedMessageV3 implements
// @@protoc_insertion_point(message_implements:google.ads.googleads.v10.common.CpcBidSimulationPointList)
CpcBidSimulationPointListOrBuilder {
private static final long serialVersionUID = 0L;
// Use CpcBidSimulationPointList.newBuilder() to construct.
private CpcBidSimulationPointList(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) {
super(builder);
}
private CpcBidSimulationPointList() {
points_ = java.util.Collections.emptyList();
}
@java.lang.Override
@SuppressWarnings({"unused"})
protected java.lang.Object newInstance(
UnusedPrivateParameter unused) {
return new CpcBidSimulationPointList();
}
@java.lang.Override
public final com.google.protobuf.UnknownFieldSet
getUnknownFields() {
return this.unknownFields;
}
private CpcBidSimulationPointList(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
this();
if (extensionRegistry == null) {
throw new java.lang.NullPointerException();
}
int mutable_bitField0_ = 0;
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: {
if (!((mutable_bitField0_ & 0x00000001) != 0)) {
points_ = new java.util.ArrayList<com.google.ads.googleads.v10.common.CpcBidSimulationPoint>();
mutable_bitField0_ |= 0x00000001;
}
points_.add(
input.readMessage(com.google.ads.googleads.v10.common.CpcBidSimulationPoint.parser(), extensionRegistry));
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 {
if (((mutable_bitField0_ & 0x00000001) != 0)) {
points_ = java.util.Collections.unmodifiableList(points_);
}
this.unknownFields = unknownFields.build();
makeExtensionsImmutable();
}
}
public static final com.google.protobuf.Descriptors.Descriptor
getDescriptor() {
return com.google.ads.googleads.v10.common.SimulationProto.internal_static_google_ads_googleads_v10_common_CpcBidSimulationPointList_descriptor;
}
@java.lang.Override
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return com.google.ads.googleads.v10.common.SimulationProto.internal_static_google_ads_googleads_v10_common_CpcBidSimulationPointList_fieldAccessorTable
.ensureFieldAccessorsInitialized(
com.google.ads.googleads.v10.common.CpcBidSimulationPointList.class, com.google.ads.googleads.v10.common.CpcBidSimulationPointList.Builder.class);
}
public static final int POINTS_FIELD_NUMBER = 1;
private java.util.List<com.google.ads.googleads.v10.common.CpcBidSimulationPoint> points_;
/**
* <pre>
* Projected metrics for a series of CPC bid amounts.
* </pre>
*
* <code>repeated .google.ads.googleads.v10.common.CpcBidSimulationPoint points = 1;</code>
*/
@java.lang.Override
public java.util.List<com.google.ads.googleads.v10.common.CpcBidSimulationPoint> getPointsList() {
return points_;
}
/**
* <pre>
* Projected metrics for a series of CPC bid amounts.
* </pre>
*
* <code>repeated .google.ads.googleads.v10.common.CpcBidSimulationPoint points = 1;</code>
*/
@java.lang.Override
public java.util.List<? extends com.google.ads.googleads.v10.common.CpcBidSimulationPointOrBuilder>
getPointsOrBuilderList() {
return points_;
}
/**
* <pre>
* Projected metrics for a series of CPC bid amounts.
* </pre>
*
* <code>repeated .google.ads.googleads.v10.common.CpcBidSimulationPoint points = 1;</code>
*/
@java.lang.Override
public int getPointsCount() {
return points_.size();
}
/**
* <pre>
* Projected metrics for a series of CPC bid amounts.
* </pre>
*
* <code>repeated .google.ads.googleads.v10.common.CpcBidSimulationPoint points = 1;</code>
*/
@java.lang.Override
public com.google.ads.googleads.v10.common.CpcBidSimulationPoint getPoints(int index) {
return points_.get(index);
}
/**
* <pre>
* Projected metrics for a series of CPC bid amounts.
* </pre>
*
* <code>repeated .google.ads.googleads.v10.common.CpcBidSimulationPoint points = 1;</code>
*/
@java.lang.Override
public com.google.ads.googleads.v10.common.CpcBidSimulationPointOrBuilder getPointsOrBuilder(
int index) {
return points_.get(index);
}
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 {
for (int i = 0; i < points_.size(); i++) {
output.writeMessage(1, points_.get(i));
}
unknownFields.writeTo(output);
}
@java.lang.Override
public int getSerializedSize() {
int size = memoizedSize;
if (size != -1) return size;
size = 0;
for (int i = 0; i < points_.size(); i++) {
size += com.google.protobuf.CodedOutputStream
.computeMessageSize(1, points_.get(i));
}
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.ads.googleads.v10.common.CpcBidSimulationPointList)) {
return super.equals(obj);
}
com.google.ads.googleads.v10.common.CpcBidSimulationPointList other = (com.google.ads.googleads.v10.common.CpcBidSimulationPointList) obj;
if (!getPointsList()
.equals(other.getPointsList())) 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();
if (getPointsCount() > 0) {
hash = (37 * hash) + POINTS_FIELD_NUMBER;
hash = (53 * hash) + getPointsList().hashCode();
}
hash = (29 * hash) + unknownFields.hashCode();
memoizedHashCode = hash;
return hash;
}
public static com.google.ads.googleads.v10.common.CpcBidSimulationPointList parseFrom(
java.nio.ByteBuffer data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.ads.googleads.v10.common.CpcBidSimulationPointList parseFrom(
java.nio.ByteBuffer data,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static com.google.ads.googleads.v10.common.CpcBidSimulationPointList parseFrom(
com.google.protobuf.ByteString data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.ads.googleads.v10.common.CpcBidSimulationPointList 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.ads.googleads.v10.common.CpcBidSimulationPointList parseFrom(byte[] data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.ads.googleads.v10.common.CpcBidSimulationPointList parseFrom(
byte[] data,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static com.google.ads.googleads.v10.common.CpcBidSimulationPointList parseFrom(java.io.InputStream input)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3
.parseWithIOException(PARSER, input);
}
public static com.google.ads.googleads.v10.common.CpcBidSimulationPointList 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.ads.googleads.v10.common.CpcBidSimulationPointList parseDelimitedFrom(java.io.InputStream input)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3
.parseDelimitedWithIOException(PARSER, input);
}
public static com.google.ads.googleads.v10.common.CpcBidSimulationPointList 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.ads.googleads.v10.common.CpcBidSimulationPointList parseFrom(
com.google.protobuf.CodedInputStream input)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3
.parseWithIOException(PARSER, input);
}
public static com.google.ads.googleads.v10.common.CpcBidSimulationPointList 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.ads.googleads.v10.common.CpcBidSimulationPointList 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>
* A container for simulation points for simulations of type CPC_BID.
* </pre>
*
* Protobuf type {@code google.ads.googleads.v10.common.CpcBidSimulationPointList}
*/
public static final class Builder extends
com.google.protobuf.GeneratedMessageV3.Builder<Builder> implements
// @@protoc_insertion_point(builder_implements:google.ads.googleads.v10.common.CpcBidSimulationPointList)
com.google.ads.googleads.v10.common.CpcBidSimulationPointListOrBuilder {
public static final com.google.protobuf.Descriptors.Descriptor
getDescriptor() {
return com.google.ads.googleads.v10.common.SimulationProto.internal_static_google_ads_googleads_v10_common_CpcBidSimulationPointList_descriptor;
}
@java.lang.Override
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return com.google.ads.googleads.v10.common.SimulationProto.internal_static_google_ads_googleads_v10_common_CpcBidSimulationPointList_fieldAccessorTable
.ensureFieldAccessorsInitialized(
com.google.ads.googleads.v10.common.CpcBidSimulationPointList.class, com.google.ads.googleads.v10.common.CpcBidSimulationPointList.Builder.class);
}
// Construct using com.google.ads.googleads.v10.common.CpcBidSimulationPointList.newBuilder()
private Builder() {
maybeForceBuilderInitialization();
}
private Builder(
com.google.protobuf.GeneratedMessageV3.BuilderParent parent) {
super(parent);
maybeForceBuilderInitialization();
}
private void maybeForceBuilderInitialization() {
if (com.google.protobuf.GeneratedMessageV3
.alwaysUseFieldBuilders) {
getPointsFieldBuilder();
}
}
@java.lang.Override
public Builder clear() {
super.clear();
if (pointsBuilder_ == null) {
points_ = java.util.Collections.emptyList();
bitField0_ = (bitField0_ & ~0x00000001);
} else {
pointsBuilder_.clear();
}
return this;
}
@java.lang.Override
public com.google.protobuf.Descriptors.Descriptor
getDescriptorForType() {
return com.google.ads.googleads.v10.common.SimulationProto.internal_static_google_ads_googleads_v10_common_CpcBidSimulationPointList_descriptor;
}
@java.lang.Override
public com.google.ads.googleads.v10.common.CpcBidSimulationPointList getDefaultInstanceForType() {
return com.google.ads.googleads.v10.common.CpcBidSimulationPointList.getDefaultInstance();
}
@java.lang.Override
public com.google.ads.googleads.v10.common.CpcBidSimulationPointList build() {
com.google.ads.googleads.v10.common.CpcBidSimulationPointList result = buildPartial();
if (!result.isInitialized()) {
throw newUninitializedMessageException(result);
}
return result;
}
@java.lang.Override
public com.google.ads.googleads.v10.common.CpcBidSimulationPointList buildPartial() {
com.google.ads.googleads.v10.common.CpcBidSimulationPointList result = new com.google.ads.googleads.v10.common.CpcBidSimulationPointList(this);
int from_bitField0_ = bitField0_;
if (pointsBuilder_ == null) {
if (((bitField0_ & 0x00000001) != 0)) {
points_ = java.util.Collections.unmodifiableList(points_);
bitField0_ = (bitField0_ & ~0x00000001);
}
result.points_ = points_;
} else {
result.points_ = pointsBuilder_.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.ads.googleads.v10.common.CpcBidSimulationPointList) {
return mergeFrom((com.google.ads.googleads.v10.common.CpcBidSimulationPointList)other);
} else {
super.mergeFrom(other);
return this;
}
}
public Builder mergeFrom(com.google.ads.googleads.v10.common.CpcBidSimulationPointList other) {
if (other == com.google.ads.googleads.v10.common.CpcBidSimulationPointList.getDefaultInstance()) return this;
if (pointsBuilder_ == null) {
if (!other.points_.isEmpty()) {
if (points_.isEmpty()) {
points_ = other.points_;
bitField0_ = (bitField0_ & ~0x00000001);
} else {
ensurePointsIsMutable();
points_.addAll(other.points_);
}
onChanged();
}
} else {
if (!other.points_.isEmpty()) {
if (pointsBuilder_.isEmpty()) {
pointsBuilder_.dispose();
pointsBuilder_ = null;
points_ = other.points_;
bitField0_ = (bitField0_ & ~0x00000001);
pointsBuilder_ =
com.google.protobuf.GeneratedMessageV3.alwaysUseFieldBuilders ?
getPointsFieldBuilder() : null;
} else {
pointsBuilder_.addAllMessages(other.points_);
}
}
}
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.ads.googleads.v10.common.CpcBidSimulationPointList parsedMessage = null;
try {
parsedMessage = PARSER.parsePartialFrom(input, extensionRegistry);
} catch (com.google.protobuf.InvalidProtocolBufferException e) {
parsedMessage = (com.google.ads.googleads.v10.common.CpcBidSimulationPointList) e.getUnfinishedMessage();
throw e.unwrapIOException();
} finally {
if (parsedMessage != null) {
mergeFrom(parsedMessage);
}
}
return this;
}
private int bitField0_;
private java.util.List<com.google.ads.googleads.v10.common.CpcBidSimulationPoint> points_ =
java.util.Collections.emptyList();
private void ensurePointsIsMutable() {
if (!((bitField0_ & 0x00000001) != 0)) {
points_ = new java.util.ArrayList<com.google.ads.googleads.v10.common.CpcBidSimulationPoint>(points_);
bitField0_ |= 0x00000001;
}
}
private com.google.protobuf.RepeatedFieldBuilderV3<
com.google.ads.googleads.v10.common.CpcBidSimulationPoint, com.google.ads.googleads.v10.common.CpcBidSimulationPoint.Builder, com.google.ads.googleads.v10.common.CpcBidSimulationPointOrBuilder> pointsBuilder_;
/**
* <pre>
* Projected metrics for a series of CPC bid amounts.
* </pre>
*
* <code>repeated .google.ads.googleads.v10.common.CpcBidSimulationPoint points = 1;</code>
*/
public java.util.List<com.google.ads.googleads.v10.common.CpcBidSimulationPoint> getPointsList() {
if (pointsBuilder_ == null) {
return java.util.Collections.unmodifiableList(points_);
} else {
return pointsBuilder_.getMessageList();
}
}
/**
* <pre>
* Projected metrics for a series of CPC bid amounts.
* </pre>
*
* <code>repeated .google.ads.googleads.v10.common.CpcBidSimulationPoint points = 1;</code>
*/
public int getPointsCount() {
if (pointsBuilder_ == null) {
return points_.size();
} else {
return pointsBuilder_.getCount();
}
}
/**
* <pre>
* Projected metrics for a series of CPC bid amounts.
* </pre>
*
* <code>repeated .google.ads.googleads.v10.common.CpcBidSimulationPoint points = 1;</code>
*/
public com.google.ads.googleads.v10.common.CpcBidSimulationPoint getPoints(int index) {
if (pointsBuilder_ == null) {
return points_.get(index);
} else {
return pointsBuilder_.getMessage(index);
}
}
/**
* <pre>
* Projected metrics for a series of CPC bid amounts.
* </pre>
*
* <code>repeated .google.ads.googleads.v10.common.CpcBidSimulationPoint points = 1;</code>
*/
public Builder setPoints(
int index, com.google.ads.googleads.v10.common.CpcBidSimulationPoint value) {
if (pointsBuilder_ == null) {
if (value == null) {
throw new NullPointerException();
}
ensurePointsIsMutable();
points_.set(index, value);
onChanged();
} else {
pointsBuilder_.setMessage(index, value);
}
return this;
}
/**
* <pre>
* Projected metrics for a series of CPC bid amounts.
* </pre>
*
* <code>repeated .google.ads.googleads.v10.common.CpcBidSimulationPoint points = 1;</code>
*/
public Builder setPoints(
int index, com.google.ads.googleads.v10.common.CpcBidSimulationPoint.Builder builderForValue) {
if (pointsBuilder_ == null) {
ensurePointsIsMutable();
points_.set(index, builderForValue.build());
onChanged();
} else {
pointsBuilder_.setMessage(index, builderForValue.build());
}
return this;
}
/**
* <pre>
* Projected metrics for a series of CPC bid amounts.
* </pre>
*
* <code>repeated .google.ads.googleads.v10.common.CpcBidSimulationPoint points = 1;</code>
*/
public Builder addPoints(com.google.ads.googleads.v10.common.CpcBidSimulationPoint value) {
if (pointsBuilder_ == null) {
if (value == null) {
throw new NullPointerException();
}
ensurePointsIsMutable();
points_.add(value);
onChanged();
} else {
pointsBuilder_.addMessage(value);
}
return this;
}
/**
* <pre>
* Projected metrics for a series of CPC bid amounts.
* </pre>
*
* <code>repeated .google.ads.googleads.v10.common.CpcBidSimulationPoint points = 1;</code>
*/
public Builder addPoints(
int index, com.google.ads.googleads.v10.common.CpcBidSimulationPoint value) {
if (pointsBuilder_ == null) {
if (value == null) {
throw new NullPointerException();
}
ensurePointsIsMutable();
points_.add(index, value);
onChanged();
} else {
pointsBuilder_.addMessage(index, value);
}
return this;
}
/**
* <pre>
* Projected metrics for a series of CPC bid amounts.
* </pre>
*
* <code>repeated .google.ads.googleads.v10.common.CpcBidSimulationPoint points = 1;</code>
*/
public Builder addPoints(
com.google.ads.googleads.v10.common.CpcBidSimulationPoint.Builder builderForValue) {
if (pointsBuilder_ == null) {
ensurePointsIsMutable();
points_.add(builderForValue.build());
onChanged();
} else {
pointsBuilder_.addMessage(builderForValue.build());
}
return this;
}
/**
* <pre>
* Projected metrics for a series of CPC bid amounts.
* </pre>
*
* <code>repeated .google.ads.googleads.v10.common.CpcBidSimulationPoint points = 1;</code>
*/
public Builder addPoints(
int index, com.google.ads.googleads.v10.common.CpcBidSimulationPoint.Builder builderForValue) {
if (pointsBuilder_ == null) {
ensurePointsIsMutable();
points_.add(index, builderForValue.build());
onChanged();
} else {
pointsBuilder_.addMessage(index, builderForValue.build());
}
return this;
}
/**
* <pre>
* Projected metrics for a series of CPC bid amounts.
* </pre>
*
* <code>repeated .google.ads.googleads.v10.common.CpcBidSimulationPoint points = 1;</code>
*/
public Builder addAllPoints(
java.lang.Iterable<? extends com.google.ads.googleads.v10.common.CpcBidSimulationPoint> values) {
if (pointsBuilder_ == null) {
ensurePointsIsMutable();
com.google.protobuf.AbstractMessageLite.Builder.addAll(
values, points_);
onChanged();
} else {
pointsBuilder_.addAllMessages(values);
}
return this;
}
/**
* <pre>
* Projected metrics for a series of CPC bid amounts.
* </pre>
*
* <code>repeated .google.ads.googleads.v10.common.CpcBidSimulationPoint points = 1;</code>
*/
public Builder clearPoints() {
if (pointsBuilder_ == null) {
points_ = java.util.Collections.emptyList();
bitField0_ = (bitField0_ & ~0x00000001);
onChanged();
} else {
pointsBuilder_.clear();
}
return this;
}
/**
* <pre>
* Projected metrics for a series of CPC bid amounts.
* </pre>
*
* <code>repeated .google.ads.googleads.v10.common.CpcBidSimulationPoint points = 1;</code>
*/
public Builder removePoints(int index) {
if (pointsBuilder_ == null) {
ensurePointsIsMutable();
points_.remove(index);
onChanged();
} else {
pointsBuilder_.remove(index);
}
return this;
}
/**
* <pre>
* Projected metrics for a series of CPC bid amounts.
* </pre>
*
* <code>repeated .google.ads.googleads.v10.common.CpcBidSimulationPoint points = 1;</code>
*/
public com.google.ads.googleads.v10.common.CpcBidSimulationPoint.Builder getPointsBuilder(
int index) {
return getPointsFieldBuilder().getBuilder(index);
}
/**
* <pre>
* Projected metrics for a series of CPC bid amounts.
* </pre>
*
* <code>repeated .google.ads.googleads.v10.common.CpcBidSimulationPoint points = 1;</code>
*/
public com.google.ads.googleads.v10.common.CpcBidSimulationPointOrBuilder getPointsOrBuilder(
int index) {
if (pointsBuilder_ == null) {
return points_.get(index); } else {
return pointsBuilder_.getMessageOrBuilder(index);
}
}
/**
* <pre>
* Projected metrics for a series of CPC bid amounts.
* </pre>
*
* <code>repeated .google.ads.googleads.v10.common.CpcBidSimulationPoint points = 1;</code>
*/
public java.util.List<? extends com.google.ads.googleads.v10.common.CpcBidSimulationPointOrBuilder>
getPointsOrBuilderList() {
if (pointsBuilder_ != null) {
return pointsBuilder_.getMessageOrBuilderList();
} else {
return java.util.Collections.unmodifiableList(points_);
}
}
/**
* <pre>
* Projected metrics for a series of CPC bid amounts.
* </pre>
*
* <code>repeated .google.ads.googleads.v10.common.CpcBidSimulationPoint points = 1;</code>
*/
public com.google.ads.googleads.v10.common.CpcBidSimulationPoint.Builder addPointsBuilder() {
return getPointsFieldBuilder().addBuilder(
com.google.ads.googleads.v10.common.CpcBidSimulationPoint.getDefaultInstance());
}
/**
* <pre>
* Projected metrics for a series of CPC bid amounts.
* </pre>
*
* <code>repeated .google.ads.googleads.v10.common.CpcBidSimulationPoint points = 1;</code>
*/
public com.google.ads.googleads.v10.common.CpcBidSimulationPoint.Builder addPointsBuilder(
int index) {
return getPointsFieldBuilder().addBuilder(
index, com.google.ads.googleads.v10.common.CpcBidSimulationPoint.getDefaultInstance());
}
/**
* <pre>
* Projected metrics for a series of CPC bid amounts.
* </pre>
*
* <code>repeated .google.ads.googleads.v10.common.CpcBidSimulationPoint points = 1;</code>
*/
public java.util.List<com.google.ads.googleads.v10.common.CpcBidSimulationPoint.Builder>
getPointsBuilderList() {
return getPointsFieldBuilder().getBuilderList();
}
private com.google.protobuf.RepeatedFieldBuilderV3<
com.google.ads.googleads.v10.common.CpcBidSimulationPoint, com.google.ads.googleads.v10.common.CpcBidSimulationPoint.Builder, com.google.ads.googleads.v10.common.CpcBidSimulationPointOrBuilder>
getPointsFieldBuilder() {
if (pointsBuilder_ == null) {
pointsBuilder_ = new com.google.protobuf.RepeatedFieldBuilderV3<
com.google.ads.googleads.v10.common.CpcBidSimulationPoint, com.google.ads.googleads.v10.common.CpcBidSimulationPoint.Builder, com.google.ads.googleads.v10.common.CpcBidSimulationPointOrBuilder>(
points_,
((bitField0_ & 0x00000001) != 0),
getParentForChildren(),
isClean());
points_ = null;
}
return pointsBuilder_;
}
@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.ads.googleads.v10.common.CpcBidSimulationPointList)
}
// @@protoc_insertion_point(class_scope:google.ads.googleads.v10.common.CpcBidSimulationPointList)
private static final com.google.ads.googleads.v10.common.CpcBidSimulationPointList DEFAULT_INSTANCE;
static {
DEFAULT_INSTANCE = new com.google.ads.googleads.v10.common.CpcBidSimulationPointList();
}
public static com.google.ads.googleads.v10.common.CpcBidSimulationPointList getDefaultInstance() {
return DEFAULT_INSTANCE;
}
private static final com.google.protobuf.Parser<CpcBidSimulationPointList>
PARSER = new com.google.protobuf.AbstractParser<CpcBidSimulationPointList>() {
@java.lang.Override
public CpcBidSimulationPointList parsePartialFrom(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return new CpcBidSimulationPointList(input, extensionRegistry);
}
};
public static com.google.protobuf.Parser<CpcBidSimulationPointList> parser() {
return PARSER;
}
@java.lang.Override
public com.google.protobuf.Parser<CpcBidSimulationPointList> getParserForType() {
return PARSER;
}
@java.lang.Override
public com.google.ads.googleads.v10.common.CpcBidSimulationPointList getDefaultInstanceForType() {
return DEFAULT_INSTANCE;
}
}
| |
/*
* 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;
import java.io.Serializable;
import javax.annotation.Generated;
@Generated("com.amazonaws:aws-java-sdk-code-generator")
public class CreateStreamResult extends com.amazonaws.AmazonWebServiceResult<com.amazonaws.ResponseMetadata> implements Serializable, Cloneable {
/**
* <p>
* The stream ID.
* </p>
*/
private String streamId;
/**
* <p>
* The stream ARN.
* </p>
*/
private String streamArn;
/**
* <p>
* A description of the stream.
* </p>
*/
private String description;
/**
* <p>
* The version of the stream.
* </p>
*/
private Integer streamVersion;
/**
* <p>
* The stream ID.
* </p>
*
* @param streamId
* The stream ID.
*/
public void setStreamId(String streamId) {
this.streamId = streamId;
}
/**
* <p>
* The stream ID.
* </p>
*
* @return The stream ID.
*/
public String getStreamId() {
return this.streamId;
}
/**
* <p>
* The stream ID.
* </p>
*
* @param streamId
* The stream ID.
* @return Returns a reference to this object so that method calls can be chained together.
*/
public CreateStreamResult withStreamId(String streamId) {
setStreamId(streamId);
return this;
}
/**
* <p>
* The stream ARN.
* </p>
*
* @param streamArn
* The stream ARN.
*/
public void setStreamArn(String streamArn) {
this.streamArn = streamArn;
}
/**
* <p>
* The stream ARN.
* </p>
*
* @return The stream ARN.
*/
public String getStreamArn() {
return this.streamArn;
}
/**
* <p>
* The stream ARN.
* </p>
*
* @param streamArn
* The stream ARN.
* @return Returns a reference to this object so that method calls can be chained together.
*/
public CreateStreamResult withStreamArn(String streamArn) {
setStreamArn(streamArn);
return this;
}
/**
* <p>
* A description of the stream.
* </p>
*
* @param description
* A description of the stream.
*/
public void setDescription(String description) {
this.description = description;
}
/**
* <p>
* A description of the stream.
* </p>
*
* @return A description of the stream.
*/
public String getDescription() {
return this.description;
}
/**
* <p>
* A description of the stream.
* </p>
*
* @param description
* A description of the stream.
* @return Returns a reference to this object so that method calls can be chained together.
*/
public CreateStreamResult withDescription(String description) {
setDescription(description);
return this;
}
/**
* <p>
* The version of the stream.
* </p>
*
* @param streamVersion
* The version of the stream.
*/
public void setStreamVersion(Integer streamVersion) {
this.streamVersion = streamVersion;
}
/**
* <p>
* The version of the stream.
* </p>
*
* @return The version of the stream.
*/
public Integer getStreamVersion() {
return this.streamVersion;
}
/**
* <p>
* The version of the stream.
* </p>
*
* @param streamVersion
* The version of the stream.
* @return Returns a reference to this object so that method calls can be chained together.
*/
public CreateStreamResult withStreamVersion(Integer streamVersion) {
setStreamVersion(streamVersion);
return this;
}
/**
* Returns a string representation of this object. This is useful for testing and debugging. Sensitive data will be
* redacted from this string using a placeholder value.
*
* @return A string representation of this object.
*
* @see java.lang.Object#toString()
*/
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("{");
if (getStreamId() != null)
sb.append("StreamId: ").append(getStreamId()).append(",");
if (getStreamArn() != null)
sb.append("StreamArn: ").append(getStreamArn()).append(",");
if (getDescription() != null)
sb.append("Description: ").append(getDescription()).append(",");
if (getStreamVersion() != null)
sb.append("StreamVersion: ").append(getStreamVersion());
sb.append("}");
return sb.toString();
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (obj instanceof CreateStreamResult == false)
return false;
CreateStreamResult other = (CreateStreamResult) obj;
if (other.getStreamId() == null ^ this.getStreamId() == null)
return false;
if (other.getStreamId() != null && other.getStreamId().equals(this.getStreamId()) == false)
return false;
if (other.getStreamArn() == null ^ this.getStreamArn() == null)
return false;
if (other.getStreamArn() != null && other.getStreamArn().equals(this.getStreamArn()) == false)
return false;
if (other.getDescription() == null ^ this.getDescription() == null)
return false;
if (other.getDescription() != null && other.getDescription().equals(this.getDescription()) == false)
return false;
if (other.getStreamVersion() == null ^ this.getStreamVersion() == null)
return false;
if (other.getStreamVersion() != null && other.getStreamVersion().equals(this.getStreamVersion()) == false)
return false;
return true;
}
@Override
public int hashCode() {
final int prime = 31;
int hashCode = 1;
hashCode = prime * hashCode + ((getStreamId() == null) ? 0 : getStreamId().hashCode());
hashCode = prime * hashCode + ((getStreamArn() == null) ? 0 : getStreamArn().hashCode());
hashCode = prime * hashCode + ((getDescription() == null) ? 0 : getDescription().hashCode());
hashCode = prime * hashCode + ((getStreamVersion() == null) ? 0 : getStreamVersion().hashCode());
return hashCode;
}
@Override
public CreateStreamResult clone() {
try {
return (CreateStreamResult) super.clone();
} catch (CloneNotSupportedException e) {
throw new IllegalStateException("Got a CloneNotSupportedException from Object.clone() " + "even though we're Cloneable!", e);
}
}
}
| |
/*
* 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.
*/
/**
* @author Yuri A. Kropachev
* @version $Revision$
*/
package org.apache.harmony.security.provider.crypto;
/**
* This class contains methods providing SHA-1 functionality to use in classes. <BR>
* The methods support the algorithm described in "SECURE HASH STANDARD", FIPS PUB 180-2, <BR>
* "http://csrc.nist.gov/publications/fips/fips180-2/fips180-2.pdf" <BR>
* <BR>
* The class contains two package level access methods, -
* "void updateHash(int[], byte[], int, int)" and "void computeHash(int[])", -
* performing the following operations. <BR>
* <BR>
* The "updateHash(..)" method appends new bytes to existing ones
* within limit of a frame of 64 bytes (16 words).
* Once a length of accumulated bytes reaches the limit
* the "computeHash(int[])" method is invoked on the frame to compute updated hash,
* and the number of bytes in the frame is set to 0.
* Thus, after appending all bytes, the frame contain only those bytes
* that were not used in computing final hash value yet. <BR>
* <BR>
* The "computeHash(..)" method generates a 160 bit hash value using
* a 512 bit message stored in first 16 words of int[] array argument and
* current hash value stored in five words, beginning HASH_OFFSET, of the array argument.
* Computation is done according to SHA-1 algorithm. <BR>
* <BR>
* The resulting hash value replaces the previous hash value in the array;
* original bits of the message are not preserved.
*/
public class SHA1Impl implements SHA1_Data {
/**
* The method generates a 160 bit hash value using
* a 512 bit message stored in first 16 words of int[] array argument and
* current hash value stored in five words, beginning OFFSET+1, of the array argument.
* Computation is done according to SHA-1 algorithm.
*
* The resulting hash value replaces the previous hash value in the array;
* original bits of the message are not preserved.
*
* No checks on argument supplied, that is,
* a calling method is responsible for such checks.
* In case of incorrect array passed to the method
* either NPE or IndexOutOfBoundException gets thrown by JVM.
*
* @params
* arrW - integer array; arrW.length >= (BYTES_OFFSET+6); <BR>
* only first (BYTES_OFFSET+6) words are used
*/
static void computeHash(int[] arrW) {
int a = arrW[HASH_OFFSET ];
int b = arrW[HASH_OFFSET +1];
int c = arrW[HASH_OFFSET +2];
int d = arrW[HASH_OFFSET +3];
int e = arrW[HASH_OFFSET +4];
int temp;
// In this implementation the "d. For t = 0 to 79 do" loop
// is split into four loops. The following constants:
// K = 5A827999 0 <= t <= 19
// K = 6ED9EBA1 20 <= t <= 39
// K = 8F1BBCDC 40 <= t <= 59
// K = CA62C1D6 60 <= t <= 79
// are hex literals in the loops.
for ( int t = 16; t < 80 ; t++ ) {
temp = arrW[t-3] ^ arrW[t-8] ^ arrW[t-14] ^ arrW[t-16];
arrW[t] = ( temp<<1 ) | ( temp>>>31 );
}
for ( int t = 0 ; t < 20 ; t++ ) {
temp = ( ( a<<5 ) | ( a>>>27 ) ) +
( ( b & c) | ((~b) & d) ) +
( e + arrW[t] + 0x5A827999 ) ;
e = d;
d = c;
c = ( b<<30 ) | ( b>>>2 ) ;
b = a;
a = temp;
}
for ( int t = 20 ; t < 40 ; t++ ) {
temp = ((( a<<5 ) | ( a>>>27 ))) + (b ^ c ^ d) + (e + arrW[t] + 0x6ED9EBA1) ;
e = d;
d = c;
c = ( b<<30 ) | ( b>>>2 ) ;
b = a;
a = temp;
}
for ( int t = 40 ; t < 60 ; t++ ) {
temp = (( a<<5 ) | ( a>>>27 )) + ((b & c) | (b & d) | (c & d)) +
(e + arrW[t] + 0x8F1BBCDC) ;
e = d;
d = c;
c = ( b<<30 ) | ( b>>>2 ) ;
b = a;
a = temp;
}
for ( int t = 60 ; t < 80 ; t++ ) {
temp = ((( a<<5 ) | ( a>>>27 ))) + (b ^ c ^ d) + (e + arrW[t] + 0xCA62C1D6) ;
e = d;
d = c;
c = ( b<<30 ) | ( b>>>2 ) ;
b = a;
a = temp;
}
arrW[HASH_OFFSET ] += a;
arrW[HASH_OFFSET +1] += b;
arrW[HASH_OFFSET +2] += c;
arrW[HASH_OFFSET +3] += d;
arrW[HASH_OFFSET +4] += e;
}
/**
* The method appends new bytes to existing ones
* within limit of a frame of 64 bytes (16 words).
*
* Once a length of accumulated bytes reaches the limit
* the "computeHash(int[])" method is invoked on the array to compute updated hash,
* and the number of bytes in the frame is set to 0.
* Thus, after appending all bytes, the array contain only those bytes
* that were not used in computing final hash value yet.
*
* No checks on arguments passed to the method, that is,
* a calling method is responsible for such checks.
*
* @params
* intArray - int array containing bytes to which to append;
* intArray.length >= (BYTES_OFFSET+6)
* @params
* byteInput - array of bytes to use for the update
* @params
* from - the offset to start in the "byteInput" array
* @params
* to - a number of the last byte in the input array to use,
* that is, for first byte "to"==0, for last byte "to"==input.length-1
*/
static void updateHash(int[] intArray, byte[] byteInput, int fromByte, int toByte) {
// As intArray contains a packed bytes
// the buffer's index is in the intArray[BYTES_OFFSET] element
int index = intArray[BYTES_OFFSET];
int i = fromByte;
int maxWord;
int nBytes;
int wordIndex = index >>2;
int byteIndex = index & 0x03;
intArray[BYTES_OFFSET] = ( index + toByte - fromByte + 1 ) & 077 ;
// In general case there are 3 stages :
// - appending bytes to non-full word,
// - writing 4 bytes into empty words,
// - writing less than 4 bytes in last word
if ( byteIndex != 0 ) { // appending bytes in non-full word (as if)
for ( ; ( i <= toByte ) && ( byteIndex < 4 ) ; i++ ) {
intArray[wordIndex] |= ( byteInput[i] & 0xFF ) << ((3 - byteIndex)<<3) ;
byteIndex++;
}
if ( byteIndex == 4 ) {
wordIndex++;
if ( wordIndex == 16 ) { // intArray is full, computing hash
computeHash(intArray);
wordIndex = 0;
}
}
if ( i > toByte ) { // all input bytes appended
return ;
}
}
// writing full words
maxWord = (toByte - i + 1) >> 2; // # of remaining full words, may be "0"
for ( int k = 0; k < maxWord ; k++ ) {
intArray[wordIndex] = ( ((int) byteInput[i ] & 0xFF) <<24 ) |
( ((int) byteInput[i +1] & 0xFF) <<16 ) |
( ((int) byteInput[i +2] & 0xFF) <<8 ) |
( ((int) byteInput[i +3] & 0xFF) ) ;
i += 4;
wordIndex++;
if ( wordIndex < 16 ) { // buffer is not full yet
continue;
}
computeHash(intArray); // buffer is full, computing hash
wordIndex = 0;
}
// writing last incomplete word
// after writing free byte positions are set to "0"s
nBytes = toByte - i +1;
if ( nBytes != 0 ) {
int w = ((int) byteInput[i] & 0xFF) <<24 ;
if ( nBytes != 1 ) {
w |= ((int) byteInput[i +1] & 0xFF) <<16 ;
if ( nBytes != 2) {
w |= ((int) byteInput[i +2] & 0xFF) <<8 ;
}
}
intArray[wordIndex] = w;
}
return ;
}
}
| |
/*
* Copyright 2000-2014 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.jetbrains.python.packaging;
import com.intellij.execution.ExecutionException;
import com.intellij.execution.RunCanceledByUserException;
import com.intellij.icons.AllIcons;
import com.intellij.notification.Notification;
import com.intellij.notification.NotificationListener;
import com.intellij.notification.NotificationType;
import com.intellij.notification.NotificationsManager;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.application.ModalityState;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.progress.ProgressIndicator;
import com.intellij.openapi.progress.ProgressManager;
import com.intellij.openapi.progress.Task;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.projectRoots.Sdk;
import com.intellij.openapi.ui.Messages;
import com.intellij.openapi.util.Ref;
import com.intellij.openapi.util.text.StringUtil;
import com.intellij.webcore.packaging.PackageManagementService;
import com.intellij.webcore.packaging.PackagesNotificationPanel;
import com.jetbrains.python.packaging.ui.PyPackageManagementService;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import javax.swing.event.HyperlinkEvent;
import java.util.*;
/**
* @author vlan
*/
public class PyPackageManagerUI {
@NotNull private static final Logger LOG = Logger.getInstance(PyPackageManagerUI.class);
@Nullable private final Listener myListener;
@NotNull private final Project myProject;
@NotNull private final Sdk mySdk;
public interface Listener {
void started();
void finished(List<ExecutionException> exceptions);
}
public PyPackageManagerUI(@NotNull Project project, @NotNull Sdk sdk, @Nullable Listener listener) {
myProject = project;
mySdk = sdk;
myListener = listener;
}
public void installManagement() {
ProgressManager.getInstance().run(new InstallManagementTask(myProject, mySdk, myListener));
}
public void install(@Nullable final List<PyRequirement> requirements, @NotNull final List<String> extraArgs) {
ProgressManager.getInstance().run(new InstallTask(myProject, mySdk, requirements, extraArgs, myListener));
}
public void uninstall(@NotNull final List<PyPackage> packages) {
if (checkDependents(packages)) {
return;
}
ProgressManager.getInstance().run(new UninstallTask(myProject, mySdk, myListener, packages));
}
private boolean checkDependents(@NotNull final List<PyPackage> packages) {
try {
final Map<String, Set<PyPackage>> dependentPackages = collectDependents(packages, mySdk);
final int[] warning = {0};
if (!dependentPackages.isEmpty()) {
ApplicationManager.getApplication().invokeAndWait(() -> {
if (dependentPackages.size() == 1) {
String message = "You are attempting to uninstall ";
List<String> dep = new ArrayList<>();
int size = 1;
for (Map.Entry<String, Set<PyPackage>> entry : dependentPackages.entrySet()) {
final Set<PyPackage> value = entry.getValue();
size = value.size();
dep.add(entry.getKey() + " package which is required for " + StringUtil.join(value, ", "));
}
message += StringUtil.join(dep, "\n");
message += size == 1 ? " package" : " packages";
message += "\n\nDo you want to proceed?";
warning[0] = Messages.showYesNoDialog(message, "Warning",
AllIcons.General.BalloonWarning);
}
else {
String message = "You are attempting to uninstall packages which are required for another packages.\n\n";
List<String> dep = new ArrayList<>();
for (Map.Entry<String, Set<PyPackage>> entry : dependentPackages.entrySet()) {
dep.add(entry.getKey() + " -> " + StringUtil.join(entry.getValue(), ", "));
}
message += StringUtil.join(dep, "\n");
message += "\n\nDo you want to proceed?";
warning[0] = Messages.showYesNoDialog(message, "Warning",
AllIcons.General.BalloonWarning);
}
}, ModalityState.current());
}
if (warning[0] != Messages.YES) return true;
}
catch (ExecutionException e) {
LOG.info("Error loading packages dependents: " + e.getMessage(), e);
}
return false;
}
private static Map<String, Set<PyPackage>> collectDependents(@NotNull final List<PyPackage> packages,
Sdk sdk) throws ExecutionException {
Map<String, Set<PyPackage>> dependentPackages = new HashMap<>();
for (PyPackage pkg : packages) {
final Set<PyPackage> dependents = PyPackageManager.getInstance(sdk).getDependents(pkg);
if (!dependents.isEmpty()) {
for (PyPackage dependent : dependents) {
if (!packages.contains(dependent)) {
dependentPackages.put(pkg.getName(), dependents);
}
}
}
}
return dependentPackages;
}
private abstract static class PackagingTask extends Task.Backgroundable {
private static final String PACKAGING_GROUP_ID = "Packaging";
@NotNull protected final Sdk mySdk;
@Nullable protected final Listener myListener;
PackagingTask(@Nullable Project project, @NotNull Sdk sdk, @NotNull String title, @Nullable Listener listener) {
super(project, title);
mySdk = sdk;
myListener = listener;
}
@Override
public void run(@NotNull ProgressIndicator indicator) {
taskStarted(indicator);
taskFinished(runTask(indicator));
}
@NotNull
protected abstract List<ExecutionException> runTask(@NotNull ProgressIndicator indicator);
@NotNull
protected abstract String getSuccessTitle();
@NotNull
protected abstract String getSuccessDescription();
@NotNull
protected abstract String getFailureTitle();
protected void taskStarted(@NotNull ProgressIndicator indicator) {
final PackagingNotification[] notifications =
NotificationsManager.getNotificationsManager().getNotificationsOfType(PackagingNotification.class, getProject());
for (PackagingNotification notification : notifications) {
notification.expire();
}
indicator.setText(getTitle() + "...");
if (myListener != null) {
ApplicationManager.getApplication().invokeLater(() -> myListener.started());
}
}
protected void taskFinished(@NotNull final List<ExecutionException> exceptions) {
final Ref<Notification> notificationRef = new Ref<>(null);
if (exceptions.isEmpty()) {
notificationRef.set(new PackagingNotification(PACKAGING_GROUP_ID, getSuccessTitle(), getSuccessDescription(),
NotificationType.INFORMATION, null));
}
else {
final PackageManagementService.ErrorDescription description = PyPackageManagementService.toErrorDescription(exceptions, mySdk);
if (description != null) {
final String firstLine = getTitle() + ": error occurred.";
final NotificationListener listener = new NotificationListener() {
@Override
public void hyperlinkUpdate(@NotNull Notification notification,
@NotNull HyperlinkEvent event) {
assert myProject != null;
final String title = StringUtil.capitalizeWords(getFailureTitle(), true);
PackagesNotificationPanel.showError(title, description);
}
};
notificationRef.set(new PackagingNotification(PACKAGING_GROUP_ID, getFailureTitle(), firstLine + " <a href=\"xxx\">Details...</a>",
NotificationType.ERROR, listener));
}
}
ApplicationManager.getApplication().invokeLater(() -> {
if (myListener != null) {
myListener.finished(exceptions);
}
final Notification notification = notificationRef.get();
if (notification != null) {
notification.notify(myProject);
}
});
}
private static class PackagingNotification extends Notification{
PackagingNotification(@NotNull String groupDisplayId,
@NotNull String title,
@NotNull String content,
@NotNull NotificationType type, @Nullable NotificationListener listener) {
super(groupDisplayId, title, content, type, listener);
}
}
}
private static class InstallTask extends PackagingTask {
@Nullable private final List<PyRequirement> myRequirements;
@NotNull private final List<String> myExtraArgs;
InstallTask(@Nullable Project project,
@NotNull Sdk sdk,
@Nullable List<PyRequirement> requirements,
@NotNull List<String> extraArgs,
@Nullable Listener listener) {
super(project, sdk, "Installing packages", listener);
myRequirements = requirements;
myExtraArgs = extraArgs;
}
@NotNull
@Override
protected List<ExecutionException> runTask(@NotNull ProgressIndicator indicator) {
final List<ExecutionException> exceptions = new ArrayList<>();
final PyPackageManager manager = PyPackageManagers.getInstance().forSdk(mySdk);
if (myRequirements == null) {
indicator.setText("Installing packages...");
indicator.setIndeterminate(true);
try {
manager.install(null, myExtraArgs);
}
catch (RunCanceledByUserException e) {
exceptions.add(e);
}
catch (ExecutionException e) {
exceptions.add(e);
}
}
else {
final int size = myRequirements.size();
for (int i = 0; i < size; i++) {
final PyRequirement requirement = myRequirements.get(i);
indicator.setText(String.format("Installing package '%s'...", requirement.getPresentableText()));
if (i == 0) {
indicator.setIndeterminate(true);
}
else {
indicator.setIndeterminate(false);
indicator.setFraction((double)i / size);
}
try {
manager.install(Collections.singletonList(requirement), myExtraArgs);
}
catch (RunCanceledByUserException e) {
exceptions.add(e);
break;
}
catch (ExecutionException e) {
exceptions.add(e);
}
}
}
manager.refresh();
return exceptions;
}
@NotNull
@Override
protected String getSuccessTitle() {
return "Packages installed successfully";
}
@NotNull
@Override
protected String getSuccessDescription() {
return myRequirements != null ?
"Installed packages: " + PyPackageUtil.requirementsToString(myRequirements) :
"Installed all requirements";
}
@NotNull
@Override
protected String getFailureTitle() {
return "Install packages failed";
}
}
private static class InstallManagementTask extends InstallTask {
InstallManagementTask(@Nullable Project project,
@NotNull Sdk sdk,
@Nullable Listener listener) {
super(project, sdk, Collections.emptyList(), Collections.emptyList(), listener);
}
@NotNull
@Override
protected List<ExecutionException> runTask(@NotNull ProgressIndicator indicator) {
final List<ExecutionException> exceptions = new ArrayList<>();
final PyPackageManager manager = PyPackageManagers.getInstance().forSdk(mySdk);
indicator.setText("Installing packaging tools...");
indicator.setIndeterminate(true);
try {
manager.installManagement();
}
catch (ExecutionException e) {
exceptions.add(e);
}
manager.refresh();
return exceptions;
}
@NotNull
@Override
protected String getSuccessDescription() {
return "Installed Python packaging tools";
}
}
private static class UninstallTask extends PackagingTask {
@NotNull private final List<PyPackage> myPackages;
UninstallTask(@Nullable Project project,
@NotNull Sdk sdk,
@Nullable Listener listener,
@NotNull List<PyPackage> packages) {
super(project, sdk, "Uninstalling packages", listener);
myPackages = packages;
}
@NotNull
@Override
protected List<ExecutionException> runTask(@NotNull ProgressIndicator indicator) {
final PyPackageManager manager = PyPackageManagers.getInstance().forSdk(mySdk);
indicator.setIndeterminate(true);
try {
manager.uninstall(myPackages);
return Collections.emptyList();
}
catch (ExecutionException e) {
return Collections.singletonList(e);
}
finally {
manager.refresh();
}
}
@NotNull
@Override
protected String getSuccessTitle() {
return "Packages uninstalled successfully";
}
@NotNull
@Override
protected String getSuccessDescription() {
final String packagesString = StringUtil.join(myPackages, pkg -> "'" + pkg.getName() + "'", ", ");
return "Uninstalled packages: " + packagesString;
}
@NotNull
@Override
protected String getFailureTitle() {
return "Uninstall packages failed";
}
}
}
| |
/**
* Copyright (C) 2016 - present by OpenGamma Inc. and the OpenGamma group of companies
*
* Please see distribution for license.
*/
package com.opengamma.strata.product.capfloor;
import java.io.Serializable;
import java.time.LocalDate;
import java.util.Map;
import java.util.NoSuchElementException;
import java.util.Optional;
import java.util.Set;
import java.util.function.Function;
import org.joda.beans.Bean;
import org.joda.beans.BeanDefinition;
import org.joda.beans.ImmutableBean;
import org.joda.beans.ImmutableConstructor;
import org.joda.beans.ImmutableDefaults;
import org.joda.beans.JodaBeanUtils;
import org.joda.beans.MetaProperty;
import org.joda.beans.Property;
import org.joda.beans.PropertyDefinition;
import org.joda.beans.impl.direct.DirectFieldsBeanBuilder;
import org.joda.beans.impl.direct.DirectMetaBean;
import org.joda.beans.impl.direct.DirectMetaProperty;
import org.joda.beans.impl.direct.DirectMetaPropertyMap;
import com.google.common.collect.ImmutableList;
import com.opengamma.strata.basics.ReferenceData;
import com.opengamma.strata.basics.Resolvable;
import com.opengamma.strata.basics.currency.Currency;
import com.opengamma.strata.basics.date.AdjustableDate;
import com.opengamma.strata.basics.date.DateAdjuster;
import com.opengamma.strata.basics.date.DaysAdjustment;
import com.opengamma.strata.basics.index.IborIndex;
import com.opengamma.strata.basics.index.IborIndexObservation;
import com.opengamma.strata.basics.schedule.PeriodicSchedule;
import com.opengamma.strata.basics.schedule.Schedule;
import com.opengamma.strata.basics.schedule.SchedulePeriod;
import com.opengamma.strata.basics.schedule.StubConvention;
import com.opengamma.strata.basics.value.ValueSchedule;
import com.opengamma.strata.collect.ArgChecker;
import com.opengamma.strata.collect.array.DoubleArray;
import com.opengamma.strata.product.common.PayReceive;
import com.opengamma.strata.product.rate.IborRateComputation;
import com.opengamma.strata.product.swap.FixingRelativeTo;
import com.opengamma.strata.product.swap.IborRateCalculation;
/**
* An Ibor cap/floor leg of a cap/floor product.
* <p>
* This defines a single cap/floor leg for an Ibor cap/floor product.
* The cap/floor instruments are defined as a set of call/put options on successive Ibor index rates,
* known as Ibor caplets/floorlets.
* <p>
* The periodic payments in the resolved leg are caplets or floorlets depending on the data in this leg.
* The {@code capSchedule} field is used to represent strike values of individual caplets,
* whereas {@code floorSchedule} is used to represent strike values of individual floorlets.
* Either {@code capSchedule} or {@code floorSchedule} must be present, and not both.
*/
@BeanDefinition
public final class IborCapFloorLeg
implements Resolvable<ResolvedIborCapFloorLeg>, ImmutableBean, Serializable {
/**
* Whether the leg is pay or receive.
* <p>
* A value of 'Pay' implies that the resulting amount is paid to the counterparty.
* A value of 'Receive' implies that the resulting amount is received from the counterparty.
*/
@PropertyDefinition(validate = "notNull")
private final PayReceive payReceive;
/**
* The periodic payment schedule.
* <p>
* This is used to define the periodic payment periods.
* These are used directly or indirectly to determine other dates in the leg.
*/
@PropertyDefinition(validate = "notNull")
private final PeriodicSchedule paymentSchedule;
/**
* The offset of payment from the base calculation period date, defaulted to 'None'.
* <p>
* The offset is applied to the adjusted end date of each payment period.
* Offset can be based on calendar days or business days.
*/
@PropertyDefinition(validate = "notNull")
private final DaysAdjustment paymentDateOffset;
/**
* The currency of the leg associated with the notional.
* <p>
* This is the currency of the leg and the currency that payoff calculation is made in.
* The amounts of the notional are expressed in terms of this currency.
*/
@PropertyDefinition(validate = "notNull")
private final Currency currency;
/**
* The notional amount, must be non-negative.
* <p>
* The notional amount applicable during the period.
* The currency of the notional is specified by {@code currency}.
*/
@PropertyDefinition(validate = "notNull")
private final ValueSchedule notional;
/**
* The interest rate accrual calculation.
* <p>
* The interest rate accrual is based on Ibor index.
*/
@PropertyDefinition(validate = "notNull")
private final IborRateCalculation calculation;
/**
* The cap schedule, optional.
* <p>
* This defines the strike value of a cap as an initial value and a list of adjustments.
* Thus individual caplets may have different strike values.
* The cap rate is only allowed to change at payment period boundaries.
* <p>
* If the product is not a cap, the cap schedule will be absent.
*/
@PropertyDefinition(get = "optional")
private final ValueSchedule capSchedule;
/**
* The floor schedule, optional.
* <p>
* This defines the strike value of a floor as an initial value and a list of adjustments.
* Thus individual floorlets may have different strike values.
* The floor rate is only allowed to change at payment period boundaries.
* <p>
* If the product is not a floor, the floor schedule will be absent.
*/
@PropertyDefinition(get = "optional")
private final ValueSchedule floorSchedule;
//-------------------------------------------------------------------------
@ImmutableDefaults
private static void applyDefaults(Builder builder) {
builder.paymentDateOffset(DaysAdjustment.NONE);
}
@ImmutableConstructor
private IborCapFloorLeg(
PayReceive payReceive,
PeriodicSchedule paymentSchedule,
DaysAdjustment paymentDateOffset,
Currency currency,
ValueSchedule notional,
IborRateCalculation calculation,
ValueSchedule capSchedule,
ValueSchedule floorSchedule) {
this.payReceive = ArgChecker.notNull(payReceive, "payReceive");
this.paymentSchedule = ArgChecker.notNull(paymentSchedule, "paymentSchedule");
this.paymentDateOffset = ArgChecker.notNull(paymentDateOffset, "paymentDateOffset");
this.currency = currency != null ? currency : calculation.getIndex().getCurrency();
this.notional = notional;
this.calculation = ArgChecker.notNull(calculation, "calculation");
this.capSchedule = capSchedule;
this.floorSchedule = floorSchedule;
ArgChecker.isTrue(!this.getPaymentSchedule().getStubConvention().isPresent() ||
this.getPaymentSchedule().getStubConvention().get().equals(StubConvention.NONE), "Stub period is not allowed");
ArgChecker.isFalse(this.getCapSchedule().isPresent() == this.getFloorSchedule().isPresent(),
"One of cap schedule and floor schedule should be empty");
ArgChecker.isTrue(this.getCalculation().getIndex().getTenor().getPeriod().equals(this.getPaymentSchedule()
.getFrequency().getPeriod()), "Payment frequency period should be the same as index tenor period");
}
//-------------------------------------------------------------------------
/**
* Gets the accrual start date of the leg.
* <p>
* This is the first accrual date in the leg, often known as the effective date.
*
* @return the start date of the leg
*/
public AdjustableDate getStartDate() {
return paymentSchedule.calculatedStartDate();
}
/**
* Gets the accrual end date of the leg.
* <p>
* This is the last accrual date in the leg, often known as the termination date.
*
* @return the end date of the leg
*/
public AdjustableDate getEndDate() {
return paymentSchedule.calculatedEndDate();
}
/**
* Gets the Ibor index.
* <p>
* The rate to be paid is based on this index
* It will be a well known market index such as 'GBP-LIBOR-3M'.
*
* @return the Ibor index
*/
public IborIndex getIndex() {
return calculation.getIndex();
}
//-------------------------------------------------------------------------
@Override
public ResolvedIborCapFloorLeg resolve(ReferenceData refData) {
Schedule adjustedSchedule = paymentSchedule.createSchedule(refData);
DoubleArray cap = getCapSchedule().isPresent() ? capSchedule.resolveValues(adjustedSchedule) : null;
DoubleArray floor = getFloorSchedule().isPresent() ? floorSchedule.resolveValues(adjustedSchedule) : null;
DoubleArray notionals = notional.resolveValues(adjustedSchedule);
DateAdjuster fixingDateAdjuster = calculation.getFixingDateOffset().resolve(refData);
DateAdjuster paymentDateAdjuster = paymentDateOffset.resolve(refData);
Function<LocalDate, IborIndexObservation> obsFn = calculation.getIndex().resolve(refData);
ImmutableList.Builder<IborCapletFloorletPeriod> periodsBuild = ImmutableList.builder();
for (int i = 0; i < adjustedSchedule.size(); i++) {
SchedulePeriod period = adjustedSchedule.getPeriod(i);
LocalDate paymentDate = paymentDateAdjuster.adjust(period.getEndDate());
LocalDate fixingDate = fixingDateAdjuster.adjust(
(calculation.getFixingRelativeTo().equals(FixingRelativeTo.PERIOD_START)) ?
period.getStartDate() : period.getEndDate());
double signedNotional = payReceive.normalize(notionals.get(i));
periodsBuild.add(IborCapletFloorletPeriod.builder()
.unadjustedStartDate(period.getUnadjustedStartDate())
.unadjustedEndDate(period.getUnadjustedEndDate())
.startDate(period.getStartDate())
.endDate(period.getEndDate())
.iborRate(IborRateComputation.of(obsFn.apply(fixingDate)))
.paymentDate(paymentDate)
.notional(signedNotional)
.currency(currency)
.yearFraction(period.yearFraction(calculation.getDayCount(), adjustedSchedule))
.caplet(cap != null ? cap.get(i) : null)
.floorlet(floor != null ? floor.get(i) : null)
.build());
}
return ResolvedIborCapFloorLeg.builder()
.capletFloorletPeriods(periodsBuild.build())
.payReceive(payReceive)
.build();
}
//------------------------- AUTOGENERATED START -------------------------
///CLOVER:OFF
/**
* The meta-bean for {@code IborCapFloorLeg}.
* @return the meta-bean, not null
*/
public static IborCapFloorLeg.Meta meta() {
return IborCapFloorLeg.Meta.INSTANCE;
}
static {
JodaBeanUtils.registerMetaBean(IborCapFloorLeg.Meta.INSTANCE);
}
/**
* The serialization version id.
*/
private static final long serialVersionUID = 1L;
/**
* Returns a builder used to create an instance of the bean.
* @return the builder, not null
*/
public static IborCapFloorLeg.Builder builder() {
return new IborCapFloorLeg.Builder();
}
@Override
public IborCapFloorLeg.Meta metaBean() {
return IborCapFloorLeg.Meta.INSTANCE;
}
@Override
public <R> Property<R> property(String propertyName) {
return metaBean().<R>metaProperty(propertyName).createProperty(this);
}
@Override
public Set<String> propertyNames() {
return metaBean().metaPropertyMap().keySet();
}
//-----------------------------------------------------------------------
/**
* Gets whether the leg is pay or receive.
* <p>
* A value of 'Pay' implies that the resulting amount is paid to the counterparty.
* A value of 'Receive' implies that the resulting amount is received from the counterparty.
* @return the value of the property, not null
*/
public PayReceive getPayReceive() {
return payReceive;
}
//-----------------------------------------------------------------------
/**
* Gets the periodic payment schedule.
* <p>
* This is used to define the periodic payment periods.
* These are used directly or indirectly to determine other dates in the leg.
* @return the value of the property, not null
*/
public PeriodicSchedule getPaymentSchedule() {
return paymentSchedule;
}
//-----------------------------------------------------------------------
/**
* Gets the offset of payment from the base calculation period date, defaulted to 'None'.
* <p>
* The offset is applied to the adjusted end date of each payment period.
* Offset can be based on calendar days or business days.
* @return the value of the property, not null
*/
public DaysAdjustment getPaymentDateOffset() {
return paymentDateOffset;
}
//-----------------------------------------------------------------------
/**
* Gets the currency of the leg associated with the notional.
* <p>
* This is the currency of the leg and the currency that payoff calculation is made in.
* The amounts of the notional are expressed in terms of this currency.
* @return the value of the property, not null
*/
public Currency getCurrency() {
return currency;
}
//-----------------------------------------------------------------------
/**
* Gets the notional amount, must be non-negative.
* <p>
* The notional amount applicable during the period.
* The currency of the notional is specified by {@code currency}.
* @return the value of the property, not null
*/
public ValueSchedule getNotional() {
return notional;
}
//-----------------------------------------------------------------------
/**
* Gets the interest rate accrual calculation.
* <p>
* The interest rate accrual is based on Ibor index.
* @return the value of the property, not null
*/
public IborRateCalculation getCalculation() {
return calculation;
}
//-----------------------------------------------------------------------
/**
* Gets the cap schedule, optional.
* <p>
* This defines the strike value of a cap as an initial value and a list of adjustments.
* Thus individual caplets may have different strike values.
* The cap rate is only allowed to change at payment period boundaries.
* <p>
* If the product is not a cap, the cap schedule will be absent.
* @return the optional value of the property, not null
*/
public Optional<ValueSchedule> getCapSchedule() {
return Optional.ofNullable(capSchedule);
}
//-----------------------------------------------------------------------
/**
* Gets the floor schedule, optional.
* <p>
* This defines the strike value of a floor as an initial value and a list of adjustments.
* Thus individual floorlets may have different strike values.
* The floor rate is only allowed to change at payment period boundaries.
* <p>
* If the product is not a floor, the floor schedule will be absent.
* @return the optional value of the property, not null
*/
public Optional<ValueSchedule> getFloorSchedule() {
return Optional.ofNullable(floorSchedule);
}
//-----------------------------------------------------------------------
/**
* Returns a builder that allows this bean to be mutated.
* @return the mutable builder, not null
*/
public Builder toBuilder() {
return new Builder(this);
}
@Override
public boolean equals(Object obj) {
if (obj == this) {
return true;
}
if (obj != null && obj.getClass() == this.getClass()) {
IborCapFloorLeg other = (IborCapFloorLeg) obj;
return JodaBeanUtils.equal(payReceive, other.payReceive) &&
JodaBeanUtils.equal(paymentSchedule, other.paymentSchedule) &&
JodaBeanUtils.equal(paymentDateOffset, other.paymentDateOffset) &&
JodaBeanUtils.equal(currency, other.currency) &&
JodaBeanUtils.equal(notional, other.notional) &&
JodaBeanUtils.equal(calculation, other.calculation) &&
JodaBeanUtils.equal(capSchedule, other.capSchedule) &&
JodaBeanUtils.equal(floorSchedule, other.floorSchedule);
}
return false;
}
@Override
public int hashCode() {
int hash = getClass().hashCode();
hash = hash * 31 + JodaBeanUtils.hashCode(payReceive);
hash = hash * 31 + JodaBeanUtils.hashCode(paymentSchedule);
hash = hash * 31 + JodaBeanUtils.hashCode(paymentDateOffset);
hash = hash * 31 + JodaBeanUtils.hashCode(currency);
hash = hash * 31 + JodaBeanUtils.hashCode(notional);
hash = hash * 31 + JodaBeanUtils.hashCode(calculation);
hash = hash * 31 + JodaBeanUtils.hashCode(capSchedule);
hash = hash * 31 + JodaBeanUtils.hashCode(floorSchedule);
return hash;
}
@Override
public String toString() {
StringBuilder buf = new StringBuilder(288);
buf.append("IborCapFloorLeg{");
buf.append("payReceive").append('=').append(payReceive).append(',').append(' ');
buf.append("paymentSchedule").append('=').append(paymentSchedule).append(',').append(' ');
buf.append("paymentDateOffset").append('=').append(paymentDateOffset).append(',').append(' ');
buf.append("currency").append('=').append(currency).append(',').append(' ');
buf.append("notional").append('=').append(notional).append(',').append(' ');
buf.append("calculation").append('=').append(calculation).append(',').append(' ');
buf.append("capSchedule").append('=').append(capSchedule).append(',').append(' ');
buf.append("floorSchedule").append('=').append(JodaBeanUtils.toString(floorSchedule));
buf.append('}');
return buf.toString();
}
//-----------------------------------------------------------------------
/**
* The meta-bean for {@code IborCapFloorLeg}.
*/
public static final class Meta extends DirectMetaBean {
/**
* The singleton instance of the meta-bean.
*/
static final Meta INSTANCE = new Meta();
/**
* The meta-property for the {@code payReceive} property.
*/
private final MetaProperty<PayReceive> payReceive = DirectMetaProperty.ofImmutable(
this, "payReceive", IborCapFloorLeg.class, PayReceive.class);
/**
* The meta-property for the {@code paymentSchedule} property.
*/
private final MetaProperty<PeriodicSchedule> paymentSchedule = DirectMetaProperty.ofImmutable(
this, "paymentSchedule", IborCapFloorLeg.class, PeriodicSchedule.class);
/**
* The meta-property for the {@code paymentDateOffset} property.
*/
private final MetaProperty<DaysAdjustment> paymentDateOffset = DirectMetaProperty.ofImmutable(
this, "paymentDateOffset", IborCapFloorLeg.class, DaysAdjustment.class);
/**
* The meta-property for the {@code currency} property.
*/
private final MetaProperty<Currency> currency = DirectMetaProperty.ofImmutable(
this, "currency", IborCapFloorLeg.class, Currency.class);
/**
* The meta-property for the {@code notional} property.
*/
private final MetaProperty<ValueSchedule> notional = DirectMetaProperty.ofImmutable(
this, "notional", IborCapFloorLeg.class, ValueSchedule.class);
/**
* The meta-property for the {@code calculation} property.
*/
private final MetaProperty<IborRateCalculation> calculation = DirectMetaProperty.ofImmutable(
this, "calculation", IborCapFloorLeg.class, IborRateCalculation.class);
/**
* The meta-property for the {@code capSchedule} property.
*/
private final MetaProperty<ValueSchedule> capSchedule = DirectMetaProperty.ofImmutable(
this, "capSchedule", IborCapFloorLeg.class, ValueSchedule.class);
/**
* The meta-property for the {@code floorSchedule} property.
*/
private final MetaProperty<ValueSchedule> floorSchedule = DirectMetaProperty.ofImmutable(
this, "floorSchedule", IborCapFloorLeg.class, ValueSchedule.class);
/**
* The meta-properties.
*/
private final Map<String, MetaProperty<?>> metaPropertyMap$ = new DirectMetaPropertyMap(
this, null,
"payReceive",
"paymentSchedule",
"paymentDateOffset",
"currency",
"notional",
"calculation",
"capSchedule",
"floorSchedule");
/**
* Restricted constructor.
*/
private Meta() {
}
@Override
protected MetaProperty<?> metaPropertyGet(String propertyName) {
switch (propertyName.hashCode()) {
case -885469925: // payReceive
return payReceive;
case -1499086147: // paymentSchedule
return paymentSchedule;
case -716438393: // paymentDateOffset
return paymentDateOffset;
case 575402001: // currency
return currency;
case 1585636160: // notional
return notional;
case -934682935: // calculation
return calculation;
case -596212599: // capSchedule
return capSchedule;
case -1562227005: // floorSchedule
return floorSchedule;
}
return super.metaPropertyGet(propertyName);
}
@Override
public IborCapFloorLeg.Builder builder() {
return new IborCapFloorLeg.Builder();
}
@Override
public Class<? extends IborCapFloorLeg> beanType() {
return IborCapFloorLeg.class;
}
@Override
public Map<String, MetaProperty<?>> metaPropertyMap() {
return metaPropertyMap$;
}
//-----------------------------------------------------------------------
/**
* The meta-property for the {@code payReceive} property.
* @return the meta-property, not null
*/
public MetaProperty<PayReceive> payReceive() {
return payReceive;
}
/**
* The meta-property for the {@code paymentSchedule} property.
* @return the meta-property, not null
*/
public MetaProperty<PeriodicSchedule> paymentSchedule() {
return paymentSchedule;
}
/**
* The meta-property for the {@code paymentDateOffset} property.
* @return the meta-property, not null
*/
public MetaProperty<DaysAdjustment> paymentDateOffset() {
return paymentDateOffset;
}
/**
* The meta-property for the {@code currency} property.
* @return the meta-property, not null
*/
public MetaProperty<Currency> currency() {
return currency;
}
/**
* The meta-property for the {@code notional} property.
* @return the meta-property, not null
*/
public MetaProperty<ValueSchedule> notional() {
return notional;
}
/**
* The meta-property for the {@code calculation} property.
* @return the meta-property, not null
*/
public MetaProperty<IborRateCalculation> calculation() {
return calculation;
}
/**
* The meta-property for the {@code capSchedule} property.
* @return the meta-property, not null
*/
public MetaProperty<ValueSchedule> capSchedule() {
return capSchedule;
}
/**
* The meta-property for the {@code floorSchedule} property.
* @return the meta-property, not null
*/
public MetaProperty<ValueSchedule> floorSchedule() {
return floorSchedule;
}
//-----------------------------------------------------------------------
@Override
protected Object propertyGet(Bean bean, String propertyName, boolean quiet) {
switch (propertyName.hashCode()) {
case -885469925: // payReceive
return ((IborCapFloorLeg) bean).getPayReceive();
case -1499086147: // paymentSchedule
return ((IborCapFloorLeg) bean).getPaymentSchedule();
case -716438393: // paymentDateOffset
return ((IborCapFloorLeg) bean).getPaymentDateOffset();
case 575402001: // currency
return ((IborCapFloorLeg) bean).getCurrency();
case 1585636160: // notional
return ((IborCapFloorLeg) bean).getNotional();
case -934682935: // calculation
return ((IborCapFloorLeg) bean).getCalculation();
case -596212599: // capSchedule
return ((IborCapFloorLeg) bean).capSchedule;
case -1562227005: // floorSchedule
return ((IborCapFloorLeg) bean).floorSchedule;
}
return super.propertyGet(bean, propertyName, quiet);
}
@Override
protected void propertySet(Bean bean, String propertyName, Object newValue, boolean quiet) {
metaProperty(propertyName);
if (quiet) {
return;
}
throw new UnsupportedOperationException("Property cannot be written: " + propertyName);
}
}
//-----------------------------------------------------------------------
/**
* The bean-builder for {@code IborCapFloorLeg}.
*/
public static final class Builder extends DirectFieldsBeanBuilder<IborCapFloorLeg> {
private PayReceive payReceive;
private PeriodicSchedule paymentSchedule;
private DaysAdjustment paymentDateOffset;
private Currency currency;
private ValueSchedule notional;
private IborRateCalculation calculation;
private ValueSchedule capSchedule;
private ValueSchedule floorSchedule;
/**
* Restricted constructor.
*/
private Builder() {
applyDefaults(this);
}
/**
* Restricted copy constructor.
* @param beanToCopy the bean to copy from, not null
*/
private Builder(IborCapFloorLeg beanToCopy) {
this.payReceive = beanToCopy.getPayReceive();
this.paymentSchedule = beanToCopy.getPaymentSchedule();
this.paymentDateOffset = beanToCopy.getPaymentDateOffset();
this.currency = beanToCopy.getCurrency();
this.notional = beanToCopy.getNotional();
this.calculation = beanToCopy.getCalculation();
this.capSchedule = beanToCopy.capSchedule;
this.floorSchedule = beanToCopy.floorSchedule;
}
//-----------------------------------------------------------------------
@Override
public Object get(String propertyName) {
switch (propertyName.hashCode()) {
case -885469925: // payReceive
return payReceive;
case -1499086147: // paymentSchedule
return paymentSchedule;
case -716438393: // paymentDateOffset
return paymentDateOffset;
case 575402001: // currency
return currency;
case 1585636160: // notional
return notional;
case -934682935: // calculation
return calculation;
case -596212599: // capSchedule
return capSchedule;
case -1562227005: // floorSchedule
return floorSchedule;
default:
throw new NoSuchElementException("Unknown property: " + propertyName);
}
}
@Override
public Builder set(String propertyName, Object newValue) {
switch (propertyName.hashCode()) {
case -885469925: // payReceive
this.payReceive = (PayReceive) newValue;
break;
case -1499086147: // paymentSchedule
this.paymentSchedule = (PeriodicSchedule) newValue;
break;
case -716438393: // paymentDateOffset
this.paymentDateOffset = (DaysAdjustment) newValue;
break;
case 575402001: // currency
this.currency = (Currency) newValue;
break;
case 1585636160: // notional
this.notional = (ValueSchedule) newValue;
break;
case -934682935: // calculation
this.calculation = (IborRateCalculation) newValue;
break;
case -596212599: // capSchedule
this.capSchedule = (ValueSchedule) newValue;
break;
case -1562227005: // floorSchedule
this.floorSchedule = (ValueSchedule) newValue;
break;
default:
throw new NoSuchElementException("Unknown property: " + propertyName);
}
return this;
}
@Override
public Builder set(MetaProperty<?> property, Object value) {
super.set(property, value);
return this;
}
@Override
public Builder setString(String propertyName, String value) {
setString(meta().metaProperty(propertyName), value);
return this;
}
@Override
public Builder setString(MetaProperty<?> property, String value) {
super.setString(property, value);
return this;
}
@Override
public Builder setAll(Map<String, ? extends Object> propertyValueMap) {
super.setAll(propertyValueMap);
return this;
}
@Override
public IborCapFloorLeg build() {
return new IborCapFloorLeg(
payReceive,
paymentSchedule,
paymentDateOffset,
currency,
notional,
calculation,
capSchedule,
floorSchedule);
}
//-----------------------------------------------------------------------
/**
* Sets whether the leg is pay or receive.
* <p>
* A value of 'Pay' implies that the resulting amount is paid to the counterparty.
* A value of 'Receive' implies that the resulting amount is received from the counterparty.
* @param payReceive the new value, not null
* @return this, for chaining, not null
*/
public Builder payReceive(PayReceive payReceive) {
JodaBeanUtils.notNull(payReceive, "payReceive");
this.payReceive = payReceive;
return this;
}
/**
* Sets the periodic payment schedule.
* <p>
* This is used to define the periodic payment periods.
* These are used directly or indirectly to determine other dates in the leg.
* @param paymentSchedule the new value, not null
* @return this, for chaining, not null
*/
public Builder paymentSchedule(PeriodicSchedule paymentSchedule) {
JodaBeanUtils.notNull(paymentSchedule, "paymentSchedule");
this.paymentSchedule = paymentSchedule;
return this;
}
/**
* Sets the offset of payment from the base calculation period date, defaulted to 'None'.
* <p>
* The offset is applied to the adjusted end date of each payment period.
* Offset can be based on calendar days or business days.
* @param paymentDateOffset the new value, not null
* @return this, for chaining, not null
*/
public Builder paymentDateOffset(DaysAdjustment paymentDateOffset) {
JodaBeanUtils.notNull(paymentDateOffset, "paymentDateOffset");
this.paymentDateOffset = paymentDateOffset;
return this;
}
/**
* Sets the currency of the leg associated with the notional.
* <p>
* This is the currency of the leg and the currency that payoff calculation is made in.
* The amounts of the notional are expressed in terms of this currency.
* @param currency the new value, not null
* @return this, for chaining, not null
*/
public Builder currency(Currency currency) {
JodaBeanUtils.notNull(currency, "currency");
this.currency = currency;
return this;
}
/**
* Sets the notional amount, must be non-negative.
* <p>
* The notional amount applicable during the period.
* The currency of the notional is specified by {@code currency}.
* @param notional the new value, not null
* @return this, for chaining, not null
*/
public Builder notional(ValueSchedule notional) {
JodaBeanUtils.notNull(notional, "notional");
this.notional = notional;
return this;
}
/**
* Sets the interest rate accrual calculation.
* <p>
* The interest rate accrual is based on Ibor index.
* @param calculation the new value, not null
* @return this, for chaining, not null
*/
public Builder calculation(IborRateCalculation calculation) {
JodaBeanUtils.notNull(calculation, "calculation");
this.calculation = calculation;
return this;
}
/**
* Sets the cap schedule, optional.
* <p>
* This defines the strike value of a cap as an initial value and a list of adjustments.
* Thus individual caplets may have different strike values.
* The cap rate is only allowed to change at payment period boundaries.
* <p>
* If the product is not a cap, the cap schedule will be absent.
* @param capSchedule the new value
* @return this, for chaining, not null
*/
public Builder capSchedule(ValueSchedule capSchedule) {
this.capSchedule = capSchedule;
return this;
}
/**
* Sets the floor schedule, optional.
* <p>
* This defines the strike value of a floor as an initial value and a list of adjustments.
* Thus individual floorlets may have different strike values.
* The floor rate is only allowed to change at payment period boundaries.
* <p>
* If the product is not a floor, the floor schedule will be absent.
* @param floorSchedule the new value
* @return this, for chaining, not null
*/
public Builder floorSchedule(ValueSchedule floorSchedule) {
this.floorSchedule = floorSchedule;
return this;
}
//-----------------------------------------------------------------------
@Override
public String toString() {
StringBuilder buf = new StringBuilder(288);
buf.append("IborCapFloorLeg.Builder{");
buf.append("payReceive").append('=').append(JodaBeanUtils.toString(payReceive)).append(',').append(' ');
buf.append("paymentSchedule").append('=').append(JodaBeanUtils.toString(paymentSchedule)).append(',').append(' ');
buf.append("paymentDateOffset").append('=').append(JodaBeanUtils.toString(paymentDateOffset)).append(',').append(' ');
buf.append("currency").append('=').append(JodaBeanUtils.toString(currency)).append(',').append(' ');
buf.append("notional").append('=').append(JodaBeanUtils.toString(notional)).append(',').append(' ');
buf.append("calculation").append('=').append(JodaBeanUtils.toString(calculation)).append(',').append(' ');
buf.append("capSchedule").append('=').append(JodaBeanUtils.toString(capSchedule)).append(',').append(' ');
buf.append("floorSchedule").append('=').append(JodaBeanUtils.toString(floorSchedule));
buf.append('}');
return buf.toString();
}
}
///CLOVER:ON
//-------------------------- AUTOGENERATED END --------------------------
}
| |
// Copyright 2000-2017 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.jetbrains.python.psi.impl.references;
import com.google.common.collect.Lists;
import com.intellij.codeInsight.completion.CompletionUtil;
import com.intellij.codeInsight.controlflow.Instruction;
import com.intellij.codeInsight.lookup.LookupElement;
import com.intellij.codeInsight.lookup.LookupElementBuilder;
import com.intellij.lang.ASTNode;
import com.intellij.lang.annotation.HighlightSeverity;
import com.intellij.openapi.extensions.Extensions;
import com.intellij.openapi.util.Comparing;
import com.intellij.openapi.util.Pair;
import com.intellij.openapi.util.TextRange;
import com.intellij.openapi.util.text.StringUtil;
import com.intellij.psi.*;
import com.intellij.psi.impl.source.resolve.ResolveCache;
import com.intellij.psi.util.PsiTreeUtil;
import com.intellij.util.IncorrectOperationException;
import com.intellij.util.PlatformIcons;
import com.intellij.util.ProcessingContext;
import com.intellij.util.containers.ContainerUtil;
import com.jetbrains.python.PyNames;
import com.jetbrains.python.codeInsight.controlflow.ControlFlowCache;
import com.jetbrains.python.codeInsight.controlflow.ScopeOwner;
import com.jetbrains.python.codeInsight.dataflow.scope.Scope;
import com.jetbrains.python.codeInsight.dataflow.scope.ScopeUtil;
import com.jetbrains.python.psi.*;
import com.jetbrains.python.psi.impl.*;
import com.jetbrains.python.psi.resolve.*;
import com.jetbrains.python.psi.types.PyModuleType;
import com.jetbrains.python.psi.types.PyType;
import com.jetbrains.python.psi.types.TypeEvalContext;
import com.jetbrains.python.pyi.PyiUtil;
import com.jetbrains.python.refactoring.PyDefUseUtil;
import one.util.streamex.StreamEx;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.util.*;
import java.util.concurrent.atomic.AtomicInteger;
/**
* @author yole
*/
public class PyReferenceImpl implements PsiReferenceEx, PsiPolyVariantReference {
protected final PyQualifiedExpression myElement;
protected final PyResolveContext myContext;
public PyReferenceImpl(PyQualifiedExpression element, @NotNull PyResolveContext context) {
myElement = element;
myContext = context;
}
@Override
public TextRange getRangeInElement() {
final ASTNode nameElement = myElement.getNameElement();
final TextRange range = nameElement != null ? nameElement.getTextRange() : myElement.getNode().getTextRange();
return range.shiftRight(-myElement.getNode().getStartOffset());
}
@Override
public PsiElement getElement() {
return myElement;
}
/**
* Resolves reference to the most obvious point.
* Imported module names: to module file (or directory for a qualifier).
* Other identifiers: to most recent definition before this reference.
* This implementation is cached.
*
* @see #resolveInner().
*/
@Override
@Nullable
public PsiElement resolve() {
final ResolveResult[] results = multiResolve(false);
return results.length >= 1 && !(results[0] instanceof ImplicitResolveResult) ? results[0].getElement() : null;
}
// it is *not* final so that it can be changed in debug time. if set to false, caching is off
@SuppressWarnings("FieldCanBeLocal")
private static final boolean USE_CACHE = true;
/**
* Resolves reference to possible referred elements.
* First element is always what resolve() would return.
* Imported module names: to module file, or {directory, '__init__.py}' for a qualifier.
* todo Local identifiers: a list of definitions in the most recent compound statement
* (e.g. {@code if X: a = 1; else: a = 2} has two definitions of {@code a}.).
* todo Identifiers not found locally: similar definitions in imported files and builtins.
*
* @see PsiPolyVariantReference#multiResolve(boolean)
*/
@Override
@NotNull
public ResolveResult[] multiResolve(final boolean incompleteCode) {
if (USE_CACHE) {
final ResolveCache cache = ResolveCache.getInstance(getElement().getProject());
return cache.resolveWithCaching(this, CachingResolver.INSTANCE, true, incompleteCode);
}
else {
return multiResolveInner();
}
}
// sorts and modifies results of resolveInner
@NotNull
private ResolveResult[] multiResolveInner() {
final String referencedName = myElement.getReferencedName();
if (referencedName == null) return ResolveResult.EMPTY_ARRAY;
final List<RatedResolveResult> targets = resolveInner();
if (targets.isEmpty()) return ResolveResult.EMPTY_ARRAY;
// change class results to constructor results if there are any
if (myElement.getParent() instanceof PyCallExpression) { // we're a call
final ListIterator<RatedResolveResult> iterator = targets.listIterator();
while (iterator.hasNext()) {
final RatedResolveResult rrr = iterator.next();
final PsiElement element = rrr.getElement();
if (element instanceof PyClass) {
final PyClass cls = (PyClass)element;
final List<PyFunction> ownInits = cls.multiFindMethodByName(PyNames.INIT, false, null);
if (!ownInits.isEmpty()) {
// replace
iterator.remove();
ownInits.forEach(init -> iterator.add(rrr.replace(init)));
}
else {// init not found; maybe it's ancestor's
for (PyClass ancestor : cls.getAncestorClasses(myContext.getTypeEvalContext())) {
final List<PyFunction> ancestorInits = ancestor.multiFindMethodByName(PyNames.INIT, false, null);
if (!ancestorInits.isEmpty()) {
// add to results as low priority
ancestorInits.forEach(init -> iterator.add(new RatedResolveResult(RatedResolveResult.RATE_LOW, init)));
break;
}
}
}
}
}
}
return RatedResolveResult.sorted(targets).toArray(ResolveResult.EMPTY_ARRAY);
}
@NotNull
private static ResolveResultList resolveToLatestDefs(@NotNull List<Instruction> instructions,
@NotNull PsiElement element,
@NotNull String name,
@NotNull TypeEvalContext context) {
final ResolveResultList ret = new ResolveResultList();
for (Instruction instruction : instructions) {
final PsiElement definition = instruction.getElement();
// TODO: This check may slow down resolving, but it is the current solution to the comprehension scopes problem
if (isInnerComprehension(element, definition)) continue;
if (definition instanceof PyImportedNameDefiner && !(definition instanceof PsiNamedElement)) {
final PyImportedNameDefiner definer = (PyImportedNameDefiner)definition;
final List<RatedResolveResult> resolvedResults = definer.multiResolveName(name);
for (RatedResolveResult result : resolvedResults) {
ret.add(new ImportedResolveResult(result.getElement(), result.getRate(), definer));
}
if (resolvedResults.isEmpty()) {
ret.add(new ImportedResolveResult(null, RatedResolveResult.RATE_NORMAL, definer));
}
else {
// TODO this kind of resolve contract is quite stupid
ret.poke(definer, RatedResolveResult.RATE_LOW);
}
}
else {
ret.poke(definition, getRate(definition, context));
}
}
final ResolveResultList results = new ResolveResultList();
for (RatedResolveResult r : ret) {
final PsiElement e = r.getElement();
if (e == element || element instanceof PyTargetExpression && e != null && PyPsiUtils.isBefore(element, e)) {
continue;
}
results.add(changePropertyMethodToSameNameGetter(r, name));
}
return results;
}
private static boolean isInnerComprehension(PsiElement referenceElement, PsiElement definition) {
final PyComprehensionElement definitionComprehension = PsiTreeUtil.getParentOfType(definition, PyComprehensionElement.class);
if (definitionComprehension != null && PyUtil.isOwnScopeComprehension(definitionComprehension)) {
final PyComprehensionElement elementComprehension = PsiTreeUtil.getParentOfType(referenceElement, PyComprehensionElement.class);
if (elementComprehension == null || !PsiTreeUtil.isAncestor(definitionComprehension, elementComprehension, false)) {
return true;
}
}
return false;
}
@NotNull
private static RatedResolveResult changePropertyMethodToSameNameGetter(@NotNull RatedResolveResult resolveResult, @NotNull String name) {
final PsiElement element = resolveResult.getElement();
if (element instanceof PyFunction) {
final Property property = ((PyFunction)element).getProperty();
if (property != null) {
final PyCallable getter = property.getGetter().valueOrNull();
final PyCallable setter = property.getSetter().valueOrNull();
final PyCallable deleter = property.getDeleter().valueOrNull();
if (getter != null && name.equals(getter.getName()) &&
(setter == null || name.equals(setter.getName())) &&
(deleter == null || name.equals(deleter.getName()))) {
return resolveResult.replace(getter);
}
}
}
return resolveResult;
}
private boolean isInOwnScopeComprehension(@Nullable PsiElement uexpr) {
if (uexpr == null || !myContext.getTypeEvalContext().maySwitchToAST(uexpr)) {
return false;
}
final PyComprehensionElement comprehensionElement = PsiTreeUtil.getParentOfType(uexpr, PyComprehensionElement.class);
return comprehensionElement != null && PyUtil.isOwnScopeComprehension(comprehensionElement);
}
/**
* Does actual resolution of resolve().
*
* @return resolution result.
* @see #resolve()
*/
@NotNull
protected List<RatedResolveResult> resolveInner() {
final ResolveResultList overriddenResult = resolveByOverridingReferenceResolveProviders();
if (!overriddenResult.isEmpty()) {
return overriddenResult;
}
final String referencedName = myElement.getReferencedName();
if (referencedName == null) return Collections.emptyList();
if (myElement instanceof PyTargetExpression && PsiTreeUtil.getParentOfType(myElement, PyComprehensionElement.class) != null) {
return ResolveResultList.to(myElement);
}
// here we have an unqualified expr. it may be defined:
// ...in current file
final PyResolveProcessor processor = new PyResolveProcessor(referencedName);
// Use real context here to enable correct completion and resolve in case of PyExpressionCodeFragment
final PsiElement realContext = PyPsiUtils.getRealContext(myElement);
final PsiElement roof = findResolveRoof(referencedName, realContext);
PyResolveUtil.scopeCrawlUp(processor, myElement, referencedName, roof);
return getResultsFromProcessor(referencedName, processor, realContext, roof);
}
protected List<RatedResolveResult> getResultsFromProcessor(@NotNull String referencedName,
@NotNull PyResolveProcessor processor,
@Nullable PsiElement realContext,
@Nullable PsiElement resolveRoof) {
boolean unreachableLocalDeclaration = false;
boolean resolveInParentScope = false;
final ResolveResultList resultList = new ResolveResultList();
final ScopeOwner referenceOwner = ScopeUtil.getScopeOwner(realContext);
final TypeEvalContext typeEvalContext = myContext.getTypeEvalContext();
ScopeOwner resolvedOwner = processor.getOwner();
if (resolvedOwner != null && !processor.getResults().isEmpty()) {
final Collection<PsiElement> resolvedElements = processor.getElements();
final Scope resolvedScope = ControlFlowCache.getScope(resolvedOwner);
if (!resolvedScope.isGlobal(referencedName)) {
if (resolvedOwner == referenceOwner) {
final List<Instruction> instructions = PyDefUseUtil.getLatestDefs(resolvedOwner, referencedName, realContext, false, true);
// TODO: Use the results from the processor as a cache for resolving to latest defs
final ResolveResultList latestDefs = resolveToLatestDefs(instructions, realContext, referencedName, typeEvalContext);
if (!latestDefs.isEmpty()) {
if (ContainerUtil.exists(latestDefs, result -> result.getElement() instanceof PyCallable)) {
return StreamEx
.of(processor.getResults().keySet())
.nonNull()
.filter(element -> PyiUtil.isOverload(element, typeEvalContext))
.map(element -> new RatedResolveResult(getRate(element, typeEvalContext), element))
.prepend(latestDefs)
.toList();
}
return latestDefs;
}
else if (resolvedOwner instanceof PyClass || instructions.isEmpty() && allInOwnScopeComprehensions(resolvedElements)) {
resolveInParentScope = true;
}
else if (PyiUtil.isInsideStubAnnotation(myElement)) {
for (PsiElement element : resolvedElements) {
resultList.poke(element, getRate(element, typeEvalContext));
}
return resultList;
}
else {
unreachableLocalDeclaration = true;
}
}
else if (referenceOwner != null) {
if (!allowsForwardOutgoingReferencesInClass(myElement)) {
final PyClass outermostNestedClass = outermostNestedClass(referenceOwner, resolvedOwner);
if (outermostNestedClass != null) {
final List<Instruction> instructions =
PyDefUseUtil.getLatestDefs(resolvedOwner, referencedName, outermostNestedClass, false, true);
return resolveToLatestDefs(instructions, outermostNestedClass, referencedName, typeEvalContext);
}
}
final Scope referenceScope = ControlFlowCache.getScope(referenceOwner);
if (referenceScope.containsDeclaration(referencedName)) {
unreachableLocalDeclaration = true;
}
}
}
}
// TODO: Try resolve to latest defs for outer scopes starting from the last element in CFG (=> no need for a special rate for globals)
if (!unreachableLocalDeclaration) {
if (resolveInParentScope) {
processor = new PyResolveProcessor(referencedName);
resolvedOwner = ScopeUtil.getScopeOwner(resolvedOwner);
if (resolvedOwner != null) {
PyResolveUtil.scopeCrawlUp(processor, resolvedOwner, referencedName, resolveRoof);
}
}
for (Map.Entry<PsiElement, PyImportedNameDefiner> entry : processor.getResults().entrySet()) {
final PsiElement resolved = entry.getKey();
final PyImportedNameDefiner definer = entry.getValue();
if (resolved != null) {
if (typeEvalContext.maySwitchToAST(resolved) && isInnerComprehension(realContext, resolved)) {
continue;
}
if (skipClassForwardReferences(referenceOwner, resolved)) {
continue;
}
if (definer == null) {
resultList.poke(resolved, getRate(resolved, typeEvalContext));
}
else {
resultList.poke(definer, getRate(definer, typeEvalContext));
resultList.add(new ImportedResolveResult(resolved, getRate(resolved, typeEvalContext), definer));
}
}
else if (definer != null) {
resultList.add(new ImportedResolveResult(null, RatedResolveResult.RATE_LOW, definer));
}
}
if (!resultList.isEmpty()) {
return resultList;
}
}
return resolveByReferenceResolveProviders();
}
private boolean skipClassForwardReferences(@Nullable ScopeOwner referenceOwner, @NotNull PsiElement resolved) {
return resolved == referenceOwner && referenceOwner instanceof PyClass && !PyiUtil.isInsideStubAnnotation(myElement);
}
private boolean allInOwnScopeComprehensions(@NotNull Collection<PsiElement> elements) {
return StreamEx.of(elements).allMatch(this::isInOwnScopeComprehension);
}
private static boolean allowsForwardOutgoingReferencesInClass(@NotNull PyQualifiedExpression element) {
return ContainerUtil.exists(Extensions.getExtensions(PyReferenceResolveProvider.EP_NAME),
provider -> provider.allowsForwardOutgoingReferencesInClass(element));
}
@Nullable
private static PyClass outermostNestedClass(@NotNull ScopeOwner referenceOwner, @NotNull ScopeOwner resolvedOwner) {
PyClass current = PyUtil.as(referenceOwner, PyClass.class);
ScopeOwner outer = ScopeUtil.getScopeOwner(current);
while (outer != resolvedOwner) {
current = PyUtil.as(outer, PyClass.class);
if (current == null) return null;
outer = ScopeUtil.getScopeOwner(outer);
}
return current;
}
@NotNull
private ResolveResultList resolveByOverridingReferenceResolveProviders() {
final ResolveResultList results = new ResolveResultList();
final TypeEvalContext context = myContext.getTypeEvalContext();
Arrays
.stream(Extensions.getExtensions(PyReferenceResolveProvider.EP_NAME))
.filter(PyOverridingReferenceResolveProvider.class::isInstance)
.map(provider -> provider.resolveName(myElement, context))
.forEach(results::addAll);
return results;
}
@NotNull
private ResolveResultList resolveByReferenceResolveProviders() {
final ResolveResultList results = new ResolveResultList();
final TypeEvalContext context = myContext.getTypeEvalContext();
for (PyReferenceResolveProvider provider : Extensions.getExtensions(PyReferenceResolveProvider.EP_NAME)) {
if (provider instanceof PyOverridingReferenceResolveProvider) {
continue;
}
results.addAll(provider.resolveName(myElement, context));
}
return results;
}
private PsiElement findResolveRoof(String referencedName, PsiElement realContext) {
if (PyUtil.isClassPrivateName(referencedName)) {
// a class-private name; limited by either class or this file
PsiElement one = myElement;
do {
one = ScopeUtil.getScopeOwner(one);
}
while (one instanceof PyFunction);
if (one instanceof PyClass) {
PyArgumentList superClassExpressionList = ((PyClass)one).getSuperClassExpressionList();
if (superClassExpressionList == null || !PsiTreeUtil.isAncestor(superClassExpressionList, myElement, false)) {
return one;
}
}
}
if (myElement instanceof PyTargetExpression) {
final ScopeOwner scopeOwner = PsiTreeUtil.getParentOfType(myElement, ScopeOwner.class);
final Scope scope;
if (scopeOwner != null) {
scope = ControlFlowCache.getScope(scopeOwner);
final String name = myElement.getName();
if (scope.isNonlocal(name)) {
final ScopeOwner nonlocalOwner = ScopeUtil.getDeclarationScopeOwner(myElement, referencedName);
if (nonlocalOwner != null && !(nonlocalOwner instanceof PyFile)) {
return nonlocalOwner;
}
}
if (!scope.isGlobal(name)) {
return scopeOwner;
}
}
}
return realContext.getContainingFile();
}
public static int getRate(@Nullable PsiElement elt, @NotNull TypeEvalContext context) {
final int rate;
if (elt instanceof PyTargetExpression && context.maySwitchToAST(elt)) {
final PsiElement parent = elt.getParent();
if (parent instanceof PyGlobalStatement || parent instanceof PyNonlocalStatement) {
rate = RatedResolveResult.RATE_LOW;
}
else {
rate = RatedResolveResult.RATE_NORMAL;
}
}
else if (elt instanceof PyImportedNameDefiner || elt instanceof PyReferenceExpression) {
rate = RatedResolveResult.RATE_LOW;
}
else if (elt instanceof PyFile) {
rate = RatedResolveResult.RATE_HIGH;
}
else if (elt != null && !PyiUtil.isInsideStub(elt) && PyiUtil.isOverload(elt, context)) {
rate = RatedResolveResult.RATE_LOW;
}
else {
rate = RatedResolveResult.RATE_NORMAL;
}
return rate;
}
@Override
@NotNull
public String getCanonicalText() {
return getRangeInElement().substring(getElement().getText());
}
@Override
public PsiElement handleElementRename(String newElementName) throws IncorrectOperationException {
ASTNode nameElement = myElement.getNameElement();
newElementName = StringUtil.trimEnd(newElementName, PyNames.DOT_PY);
if (nameElement != null && PyNames.isIdentifier(newElementName)) {
final ASTNode newNameElement = PyUtil.createNewName(myElement, newElementName);
myElement.getNode().replaceChild(nameElement, newNameElement);
}
return myElement;
}
@Override
@Nullable
public PsiElement bindToElement(@NotNull PsiElement element) throws IncorrectOperationException {
return null;
}
@Override
public boolean isReferenceTo(PsiElement element) {
if (element instanceof PsiFileSystemItem) {
// may be import via alias, so don't check if names match, do simple resolve check instead
PsiElement resolveResult = resolve();
if (resolveResult instanceof PyImportedModule) {
resolveResult = resolveResult.getNavigationElement();
}
if (element instanceof PsiDirectory) {
if (resolveResult instanceof PyFile) {
final PyFile file = (PyFile)resolveResult;
if (PyUtil.isPackage(file) && file.getContainingDirectory() == element) {
return true;
}
}
else if (resolveResult instanceof PsiDirectory) {
final PsiDirectory directory = (PsiDirectory)resolveResult;
if (PyUtil.isPackage(directory, null) && directory == element) {
return true;
}
}
}
return resolveResult == element;
}
if (element instanceof PsiNamedElement) {
final String elementName = ((PsiNamedElement)element).getName();
if ((Comparing.equal(myElement.getReferencedName(), elementName) || PyNames.INIT.equals(elementName))) {
if (!haveQualifiers(element)) {
final ScopeOwner ourScopeOwner = ScopeUtil.getScopeOwner(getElement());
final ScopeOwner theirScopeOwner = ScopeUtil.getScopeOwner(element);
if (element instanceof PyParameter || element instanceof PyTargetExpression) {
// Check if the reference is in the same or inner scope of the element scope, not shadowed by an intermediate declaration
if (resolvesToSameLocal(element, elementName, ourScopeOwner, theirScopeOwner)) {
return true;
}
}
final List<PsiElement> resolveResults = StreamEx.of(multiResolve(false))
.filter(r -> !(r instanceof ImplicitResolveResult))
.map(r -> r.getElement())
.toList();
for (PsiElement resolveResult : resolveResults) {
if (resolveResult == element) {
return true;
}
if (!haveQualifiers(element) && ourScopeOwner != null && theirScopeOwner != null) {
if (resolvesToSameGlobal(element, elementName, ourScopeOwner, theirScopeOwner, resolveResult)) return true;
}
if (resolvesToWrapper(element, resolveResult)) {
return true;
}
}
}
if (element instanceof PyExpression) {
final PyExpression expr = (PyExpression)element;
if (PyUtil.isClassAttribute(myElement) && (PyUtil.isClassAttribute(expr) || PyUtil.isInstanceAttribute(expr))) {
final PyClass c1 = PsiTreeUtil.getParentOfType(element, PyClass.class);
final PyClass c2 = PsiTreeUtil.getParentOfType(myElement, PyClass.class);
final TypeEvalContext context = myContext.getTypeEvalContext();
if (c1 != null && c2 != null && (c1.isSubclass(c2, context) || c2.isSubclass(c1, context))) {
return true;
}
}
}
}
}
return false;
}
private boolean resolvesToSameLocal(PsiElement element, String elementName, ScopeOwner ourScopeOwner, ScopeOwner theirScopeOwner) {
final PsiElement ourContainer = findContainer(getElement());
final PsiElement theirContainer = findContainer(element);
if (ourContainer != null) {
if (ourContainer == theirContainer) {
return true;
}
if (PsiTreeUtil.isAncestor(theirContainer, ourContainer, true)) {
if (ourContainer instanceof PyComprehensionElement && containsDeclaration((PyComprehensionElement)ourContainer, elementName)) {
return false;
}
ScopeOwner owner = ourScopeOwner;
while (owner != theirScopeOwner && owner != null) {
if (ControlFlowCache.getScope(owner).containsDeclaration(elementName)) {
return false;
}
owner = ScopeUtil.getScopeOwner(owner);
}
return true;
}
}
return false;
}
@Nullable
private static PsiElement findContainer(@NotNull PsiElement element) {
final PyElement parent = PsiTreeUtil.getParentOfType(element, ScopeOwner.class, PyComprehensionElement.class);
if (parent instanceof PyListCompExpression && LanguageLevel.forElement(element).isPython2()) {
return findContainer(parent);
}
return parent;
}
private static boolean containsDeclaration(@NotNull PyComprehensionElement comprehensionElement, @NotNull String variableName) {
for (PyComprehensionForComponent forComponent : comprehensionElement.getForComponents()) {
final PyExpression iteratorVariable = forComponent.getIteratorVariable();
if (iteratorVariable instanceof PyTupleExpression) {
for (PyExpression variable : (PyTupleExpression)iteratorVariable) {
if (variable instanceof PyTargetExpression && variableName.equals(variable.getName())) {
return true;
}
}
}
else if (iteratorVariable instanceof PyTargetExpression && variableName.equals(iteratorVariable.getName())) {
return true;
}
}
return false;
}
private boolean resolvesToSameGlobal(PsiElement element, String elementName, ScopeOwner ourScopeOwner, ScopeOwner theirScopeOwner,
PsiElement resolveResult) {
// Handle situations when there is no top-level declaration for globals and transitive resolve doesn't help
final PsiFile ourFile = getElement().getContainingFile();
final PsiFile theirFile = element.getContainingFile();
if (ourFile == theirFile) {
final boolean ourIsGlobal = ControlFlowCache.getScope(ourScopeOwner).isGlobal(elementName);
final boolean theirIsGlobal = ControlFlowCache.getScope(theirScopeOwner).isGlobal(elementName);
if (ourIsGlobal && theirIsGlobal) {
return true;
}
}
if (ScopeUtil.getScopeOwner(resolveResult) == ourFile && ControlFlowCache.getScope(theirScopeOwner).isGlobal(elementName)) {
return true;
}
return false;
}
protected boolean resolvesToWrapper(PsiElement element, PsiElement resolveResult) {
if (element instanceof PyFunction && ((PyFunction) element).getContainingClass() != null && resolveResult instanceof PyTargetExpression) {
final PyExpression assignedValue = ((PyTargetExpression)resolveResult).findAssignedValue();
if (assignedValue instanceof PyCallExpression) {
final PyCallExpression call = (PyCallExpression)assignedValue;
final Pair<String,PyFunction> functionPair = PyCallExpressionHelper.interpretAsModifierWrappingCall(call);
if (functionPair != null && functionPair.second == element) {
return true;
}
}
}
return false;
}
private boolean haveQualifiers(PsiElement element) {
if (myElement.isQualified()) {
return true;
}
if (element instanceof PyQualifiedExpression && ((PyQualifiedExpression)element).isQualified()) {
return true;
}
return false;
}
@Override
@NotNull
public Object[] getVariants() {
final List<LookupElement> ret = Lists.newArrayList();
// Use real context here to enable correct completion and resolve in case of PyExpressionCodeFragment!!!
final PyQualifiedExpression originalElement = CompletionUtil.getOriginalElement(myElement);
final PyQualifiedExpression element = originalElement != null ? originalElement : myElement;
final PsiElement realContext = PyPsiUtils.getRealContext(element);
// include our own names
final int underscores = PyUtil.getInitialUnderscores(element.getName());
final PyBuiltinCache builtinCache = PyBuiltinCache.getInstance(element);
final CompletionVariantsProcessor processor = new CompletionVariantsProcessor(element, e -> {
if (builtinCache.isBuiltin(e)) {
final String name = e instanceof PyElement ? ((PyElement)e).getName() : null;
if (e instanceof PyImportElement) {
return false;
}
if (name != null && PyUtil.getInitialUnderscores(name) == 1) {
return false;
}
}
return true;
}, null);
final ScopeOwner owner = realContext instanceof ScopeOwner ? (ScopeOwner)realContext : ScopeUtil.getScopeOwner(realContext);
if (owner != null) {
PyResolveUtil.scopeCrawlUp(processor, owner, null, null);
}
// This method is probably called for completion, so use appropriate context here
// in a call, include function's arg names
KeywordArgumentCompletionUtil.collectFunctionArgNames(element, ret, TypeEvalContext.codeCompletion(element.getProject(), element.getContainingFile()));
// include builtin names
final PyFile builtinsFile = builtinCache.getBuiltinsFile();
if (builtinsFile != null) {
PyResolveUtil.scopeCrawlUp(processor, builtinsFile, null, null);
}
if (underscores >= 2) {
// if we're a normal module, add module's attrs
if (realContext.getContainingFile() instanceof PyFile) {
for (String name : PyModuleType.getPossibleInstanceMembers()) {
ret.add(LookupElementBuilder.create(name).withIcon(PlatformIcons.FIELD_ICON));
}
}
// if we're inside method, add implicit __class__
if (!LanguageLevel.forElement(myElement).isPython2()) {
Optional
.ofNullable(PsiTreeUtil.getParentOfType(myElement, PyFunction.class))
.map(PyFunction::getContainingClass)
.ifPresent(pyClass -> ret.add(LookupElementBuilder.create(PyNames.__CLASS__)));
}
}
ret.addAll(getOriginalElements(processor));
return ret.toArray();
}
/**
* Throws away fake elements used for completion internally.
*/
protected List<LookupElement> getOriginalElements(@NotNull CompletionVariantsProcessor processor) {
final List<LookupElement> ret = Lists.newArrayList();
for (LookupElement item : processor.getResultList()) {
final PsiElement e = item.getPsiElement();
if (e != null) {
final PsiElement original = CompletionUtil.getOriginalElement(e);
if (original == null) {
continue;
}
}
ret.add(item);
}
return ret;
}
@Override
public boolean isSoft() {
return false;
}
@Override
public HighlightSeverity getUnresolvedHighlightSeverity(TypeEvalContext context) {
if (isBuiltInConstant()) return null;
final PyExpression qualifier = myElement.getQualifier();
if (qualifier == null) {
return HighlightSeverity.ERROR;
}
if (context.getType(qualifier) != null) {
return HighlightSeverity.WARNING;
}
return null;
}
private boolean isBuiltInConstant() {
// TODO: generalize
String name = myElement.getReferencedName();
return PyNames.NONE.equals(name) || "True".equals(name) || "False".equals(name) || PyNames.DEBUG.equals(name);
}
@Override
@Nullable
public String getUnresolvedDescription() {
return null;
}
// our very own caching resolver
private static class CachingResolver implements ResolveCache.PolyVariantResolver<PyReferenceImpl> {
public static CachingResolver INSTANCE = new CachingResolver();
private final ThreadLocal<AtomicInteger> myNesting = new ThreadLocal<AtomicInteger>() {
@Override
protected AtomicInteger initialValue() {
return new AtomicInteger();
}
};
private static final int MAX_NESTING_LEVEL = 30;
@Override
@NotNull
public ResolveResult[] resolve(@NotNull final PyReferenceImpl ref, final boolean incompleteCode) {
if (myNesting.get().getAndIncrement() >= MAX_NESTING_LEVEL) {
System.out.println("Stack overflow pending");
}
try {
return ref.multiResolveInner();
}
finally {
myNesting.get().getAndDecrement();
}
}
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
PyReferenceImpl that = (PyReferenceImpl)o;
if (!myElement.equals(that.myElement)) return false;
if (!myContext.equals(that.myContext)) return false;
return true;
}
@Override
public int hashCode() {
return myElement.hashCode();
}
protected static Object[] getTypeCompletionVariants(PyExpression pyExpression, PyType type) {
ProcessingContext context = new ProcessingContext();
context.put(PyType.CTX_NAMES, new HashSet<>());
return type.getCompletionVariants(pyExpression.getName(), pyExpression, context);
}
}
| |
/*
* Copyright 2000-2014 Vaadin 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.vaadin.client.ui;
import java.util.ArrayList;
import com.google.gwt.core.client.Scheduler.ScheduledCommand;
import com.google.gwt.dom.client.Element;
import com.google.gwt.event.dom.client.HasScrollHandlers;
import com.google.gwt.event.dom.client.ScrollEvent;
import com.google.gwt.event.dom.client.ScrollHandler;
import com.google.gwt.event.logical.shared.HasResizeHandlers;
import com.google.gwt.event.logical.shared.ResizeEvent;
import com.google.gwt.event.logical.shared.ResizeHandler;
import com.google.gwt.event.logical.shared.ValueChangeEvent;
import com.google.gwt.event.logical.shared.ValueChangeHandler;
import com.google.gwt.event.shared.HandlerRegistration;
import com.google.gwt.http.client.URL;
import com.google.gwt.user.client.History;
import com.google.gwt.user.client.Timer;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.ui.SimplePanel;
import com.vaadin.client.ApplicationConnection;
import com.vaadin.client.BrowserInfo;
import com.vaadin.client.ComponentConnector;
import com.vaadin.client.ConnectorMap;
import com.vaadin.client.Focusable;
import com.vaadin.client.LayoutManager;
import com.vaadin.client.Profiler;
import com.vaadin.client.VConsole;
import com.vaadin.client.WidgetUtil;
import com.vaadin.client.ui.ShortcutActionHandler.ShortcutActionHandlerOwner;
import com.vaadin.client.ui.TouchScrollDelegate.TouchScrollHandler;
import com.vaadin.client.ui.ui.UIConnector;
import com.vaadin.shared.ApplicationConstants;
import com.vaadin.shared.ui.ui.UIConstants;
/**
*
*/
public class VUI extends SimplePanel implements ResizeHandler,
Window.ClosingHandler, ShortcutActionHandlerOwner, Focusable,
com.google.gwt.user.client.ui.Focusable, HasResizeHandlers,
HasScrollHandlers {
private static int MONITOR_PARENT_TIMER_INTERVAL = 1000;
/** For internal use only. May be removed or replaced in the future. */
public String id;
/** For internal use only. May be removed or replaced in the future. */
public ShortcutActionHandler actionHandler;
/*
* Last known window size used to detect whether VView should be layouted
* again. Detection must check window size, because the VView size might be
* fixed and thus not automatically adapt to changed window sizes.
*/
private int windowWidth;
private int windowHeight;
/*
* Last know view size used to detect whether new dimensions should be sent
* to the server.
*/
private int viewWidth;
private int viewHeight;
/** For internal use only. May be removed or replaced in the future. */
public ApplicationConnection connection;
/**
* Keep track of possible parent size changes when an embedded application.
*
* Uses {@link #parentWidth} and {@link #parentHeight} as an optimization to
* keep track of when there is a real change.
*/
private Timer resizeTimer;
/** stored width of parent for embedded application auto-resize */
private int parentWidth;
/** stored height of parent for embedded application auto-resize */
private int parentHeight;
/** For internal use only. May be removed or replaced in the future. */
public boolean immediate;
/** For internal use only. May be removed or replaced in the future. */
public boolean resizeLazy = false;
private HandlerRegistration historyHandlerRegistration;
private TouchScrollHandler touchScrollHandler;
/**
* The current URI fragment, used to avoid sending updates if nothing has
* changed.
* <p>
* For internal use only. May be removed or replaced in the future.
*/
public String currentFragment;
/**
* Listener for URI fragment changes. Notifies the server of the new value
* whenever the value changes.
*/
private final ValueChangeHandler<String> historyChangeHandler = new ValueChangeHandler<String>() {
@Override
public void onValueChange(ValueChangeEvent<String> event) {
String newFragment = event.getValue();
// Send the location to the server if the fragment has changed
// and flush active connectors in UI.
if (!newFragment.equals(currentFragment) && connection != null) {
/*
* Ensure the fragment is properly encoded in all browsers
* (#10769)
*
* createUrlBuilder does not properly pass an empty fragment to
* UrlBuilder on Webkit browsers so do it manually (#11686)
*/
String location = Window.Location
.createUrlBuilder()
.setHash(
URL.decodeQueryString(Window.Location.getHash()))
.buildString();
currentFragment = newFragment;
connection.flushActiveConnector();
connection.updateVariable(id, UIConstants.LOCATION_VARIABLE,
location, true);
}
}
};
private VLazyExecutor delayedResizeExecutor = new VLazyExecutor(200,
new ScheduledCommand() {
@Override
public void execute() {
performSizeCheck();
}
});
private Element storedFocus;
public VUI() {
super();
// Allow focusing the view by using the focus() method, the view
// should not be in the document focus flow
getElement().setTabIndex(-1);
makeScrollable();
}
/**
* Start to periodically monitor for parent element resizes if embedded
* application (e.g. portlet).
*/
@Override
protected void onLoad() {
super.onLoad();
if (isMonitoringParentSize()) {
resizeTimer = new Timer() {
@Override
public void run() {
// trigger check to see if parent size has changed,
// recalculate layouts
performSizeCheck();
resizeTimer.schedule(MONITOR_PARENT_TIMER_INTERVAL);
}
};
resizeTimer.schedule(MONITOR_PARENT_TIMER_INTERVAL);
}
}
@Override
protected void onAttach() {
super.onAttach();
historyHandlerRegistration = History
.addValueChangeHandler(historyChangeHandler);
currentFragment = History.getToken();
}
@Override
protected void onDetach() {
super.onDetach();
historyHandlerRegistration.removeHandler();
historyHandlerRegistration = null;
}
/**
* Stop monitoring for parent element resizes.
*/
@Override
protected void onUnload() {
if (resizeTimer != null) {
resizeTimer.cancel();
resizeTimer = null;
}
super.onUnload();
}
/**
* Called when the window or parent div might have been resized.
*
* This immediately checks the sizes of the window and the parent div (if
* monitoring it) and triggers layout recalculation if they have changed.
*/
protected void performSizeCheck() {
windowSizeMaybeChanged(Window.getClientWidth(),
Window.getClientHeight());
}
/**
* Called when the window or parent div might have been resized.
*
* This immediately checks the sizes of the window and the parent div (if
* monitoring it) and triggers layout recalculation if they have changed.
*
* @param newWindowWidth
* The new width of the window
* @param newWindowHeight
* The new height of the window
*
* @deprecated use {@link #performSizeCheck()}
*/
@Deprecated
protected void windowSizeMaybeChanged(int newWindowWidth,
int newWindowHeight) {
if (connection == null) {
// Connection is null if the timer fires before the first UIDL
// update
return;
}
boolean changed = false;
ComponentConnector connector = ConnectorMap.get(connection)
.getConnector(this);
if (windowWidth != newWindowWidth) {
windowWidth = newWindowWidth;
changed = true;
connector.getLayoutManager().reportOuterWidth(connector,
newWindowWidth);
VConsole.log("New window width: " + windowWidth);
}
if (windowHeight != newWindowHeight) {
windowHeight = newWindowHeight;
changed = true;
connector.getLayoutManager().reportOuterHeight(connector,
newWindowHeight);
VConsole.log("New window height: " + windowHeight);
}
Element parentElement = getElement().getParentElement();
if (isMonitoringParentSize() && parentElement != null) {
// check also for parent size changes
int newParentWidth = parentElement.getClientWidth();
int newParentHeight = parentElement.getClientHeight();
if (parentWidth != newParentWidth) {
parentWidth = newParentWidth;
changed = true;
VConsole.log("New parent width: " + parentWidth);
}
if (parentHeight != newParentHeight) {
parentHeight = newParentHeight;
changed = true;
VConsole.log("New parent height: " + parentHeight);
}
}
if (changed) {
/*
* If the window size has changed, layout the VView again and send
* new size to the server if the size changed. (Just checking VView
* size would cause us to ignore cases when a relatively sized VView
* should shrink as the content's size is fixed and would thus not
* automatically shrink.)
*/
VConsole.log("Running layout functions due to window or parent resize");
// update size to avoid (most) redundant re-layout passes
// there can still be an extra layout recalculation if webkit
// overflow fix updates the size in a deferred block
if (isMonitoringParentSize() && parentElement != null) {
parentWidth = parentElement.getClientWidth();
parentHeight = parentElement.getClientHeight();
}
sendClientResized();
LayoutManager layoutManager = connector.getLayoutManager();
if (layoutManager.isLayoutRunning()) {
layoutManager.layoutLater();
} else {
layoutManager.layoutNow();
}
}
}
/**
* @return the name of the theme in use by this UI.
* @deprecated as of 7.3. Use {@link UIConnector#getActiveTheme()} instead.
*/
@Deprecated
public String getTheme() {
return ((UIConnector) ConnectorMap.get(connection).getConnector(this))
.getActiveTheme();
}
/**
* Returns true if the body is NOT generated, i.e if someone else has made
* the page that we're running in. Otherwise we're in charge of the whole
* page.
*
* @return true if we're running embedded
*/
public boolean isEmbedded() {
return !getElement().getOwnerDocument().getBody().getClassName()
.contains(ApplicationConstants.GENERATED_BODY_CLASSNAME);
}
/**
* Returns true if the size of the parent should be checked periodically and
* the application should react to its changes.
*
* @return true if size of parent should be tracked
*/
protected boolean isMonitoringParentSize() {
// could also perform a more specific check (Liferay portlet)
return isEmbedded();
}
/*
* (non-Javadoc)
*
* @see
* com.google.gwt.event.logical.shared.ResizeHandler#onResize(com.google
* .gwt.event.logical.shared.ResizeEvent)
*/
@Override
public void onResize(ResizeEvent event) {
triggerSizeChangeCheck();
}
/**
* Called when a resize event is received.
*
* This may trigger a lazy refresh or perform the size check immediately
* depending on the browser used and whether the server side requests
* resizes to be lazy.
*/
private void triggerSizeChangeCheck() {
/*
* IE (pre IE9 at least) will give us some false resize events due to
* problems with scrollbars. Firefox 3 might also produce some extra
* events. We postpone both the re-layouting and the server side event
* for a while to deal with these issues.
*
* We may also postpone these events to avoid slowness when resizing the
* browser window. Constantly recalculating the layout causes the resize
* operation to be really slow with complex layouts.
*/
boolean lazy = resizeLazy || BrowserInfo.get().isIE8();
if (lazy) {
delayedResizeExecutor.trigger();
} else {
performSizeCheck();
}
}
/**
* Send new dimensions to the server.
* <p>
* For internal use only. May be removed or replaced in the future.
*/
public void sendClientResized() {
Profiler.enter("VUI.sendClientResized");
Element parentElement = getElement().getParentElement();
int viewHeight = parentElement.getClientHeight();
int viewWidth = parentElement.getClientWidth();
ResizeEvent.fire(this, viewWidth, viewHeight);
Profiler.leave("VUI.sendClientResized");
}
public native static void goTo(String url)
/*-{
$wnd.location = url;
}-*/;
@Override
public void onWindowClosing(Window.ClosingEvent event) {
// Change focus on this window in order to ensure that all state is
// collected from textfields
// TODO this is a naive hack, that only works with text fields and may
// cause some odd issues. Should be replaced with a decent solution, see
// also related BeforeShortcutActionListener interface. Same interface
// might be usable here.
VTextField.flushChangesFromFocusedTextField();
}
private native static void loadAppIdListFromDOM(ArrayList<String> list)
/*-{
var j;
for(j in $wnd.vaadin.vaadinConfigurations) {
// $entry not needed as function is not exported
list.@java.util.Collection::add(Ljava/lang/Object;)(j);
}
}-*/;
@Override
public ShortcutActionHandler getShortcutActionHandler() {
return actionHandler;
}
@Override
public void focus() {
setFocus(true);
}
/**
* Ensures the widget is scrollable eg. after style name changes.
* <p>
* For internal use only. May be removed or replaced in the future.
*/
public void makeScrollable() {
if (touchScrollHandler == null) {
touchScrollHandler = TouchScrollDelegate.enableTouchScrolling(this);
}
touchScrollHandler.addElement(getElement());
}
@Override
public HandlerRegistration addResizeHandler(ResizeHandler resizeHandler) {
return addHandler(resizeHandler, ResizeEvent.getType());
}
@Override
public HandlerRegistration addScrollHandler(ScrollHandler scrollHandler) {
return addHandler(scrollHandler, ScrollEvent.getType());
}
@Override
public int getTabIndex() {
return FocusUtil.getTabIndex(this);
}
@Override
public void setAccessKey(char key) {
FocusUtil.setAccessKey(this, key);
}
@Override
public void setFocus(boolean focused) {
FocusUtil.setFocus(this, focused);
}
@Override
public void setTabIndex(int index) {
FocusUtil.setTabIndex(this, index);
}
/**
* Allows to store the currently focused Element.
*
* Current use case is to store the focus when a Window is opened. Does
* currently handle only a single value. Needs to be extended for #12158
*
* @param focusedElement
*/
public void storeFocus() {
storedFocus = WidgetUtil.getFocusedElement();
}
/**
* Restores the previously stored focus Element.
*
* Current use case is to restore the focus when a Window is closed. Does
* currently handle only a single value. Needs to be extended for #12158
*
* @return the lastFocusElementBeforeDialogOpened
*/
public void focusStoredElement() {
if (storedFocus != null) {
storedFocus.focus();
}
}
}
| |
/*
* 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.myfaces.view.facelets.tag.composite;
import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.event.AbortProcessingException;
import javax.faces.event.ActionEvent;
import javax.faces.event.ActionListener;
import javax.faces.event.ValueChangeEvent;
import javax.faces.validator.ValidatorException;
public class MockAttributeBean
{
public String getStyle()
{
return "style1";
}
public String getStyleClass()
{
return "styleclass1";
}
public String getJavaProperty()
{
return "javaproperty1";
}
public String doSomethingFunny(String a)
{
return "somethingFunny"+a;
}
public String doSomeAction()
{
return "someAction";
}
private boolean actionListener1Called = false;
public boolean isActionListener1Called()
{
return actionListener1Called;
}
public void setActionListener1Called(boolean value)
{
actionListener1Called = value;
}
public void doSomeActionListener1()
{
actionListener1Called = true;
}
private boolean actionListener2Called = false;
public boolean isActionListener2Called()
{
return actionListener2Called;
}
public void setActionListener2Called(boolean value)
{
actionListener2Called = value;
}
public void doSomeActionListener2(ActionEvent evt)
{
actionListener2Called = true;
}
private boolean valueChangeListener1Called = false;
public boolean isValueChangeListener1Called()
{
return valueChangeListener1Called;
}
public void setValueChangeListener1Called(boolean value)
{
valueChangeListener1Called = value;
}
public void doSomeValueChangeListener1() throws AbortProcessingException
{
valueChangeListener1Called = true;
}
private boolean valueChangeListener2Called = false;
public boolean isValueChangeListener2Called()
{
return valueChangeListener2Called;
}
public void setValueChangeListener2Called(boolean value)
{
valueChangeListener2Called = value;
}
public void doSomeValueChangeListener2(ValueChangeEvent evt) throws AbortProcessingException
{
valueChangeListener2Called = true;
}
private boolean validator1Called = false;
public boolean isValidator1Called()
{
return validator1Called;
}
public void setValidator1Called(boolean value)
{
validator1Called = value;
}
public void doSomeValidator1(FacesContext context, UIComponent component, Object value) throws ValidatorException
{
validator1Called = true;
}
private ActionListener submitActionListener;
private ActionListener cancelActionListener;
private boolean submitActionListenerCalled = false;
private boolean cancelActionListenerCalled = false;
public ActionListener getSubmitActionListener()
{
if (submitActionListener == null)
{
submitActionListener = new ActionListener(){
public void processAction(ActionEvent actionEvent)
throws AbortProcessingException
{
//System.out.println("Submit ActionListener executed");
//FacesContext.getCurrentInstance().addMessage(null, new FacesMessage("Submit ActionListener executed"));
submitActionListenerCalled = true;
}
};
}
return submitActionListener;
}
public ActionListener getCancelActionListener()
{
if (cancelActionListener == null)
{
cancelActionListener = new ActionListener()
{
public void processAction(ActionEvent actionEvent)
throws AbortProcessingException
{
//System.out.println("Cancel ActionListener executed");
//FacesContext.getCurrentInstance().addMessage(null, new FacesMessage("Cancel ActionListener executed"));
cancelActionListenerCalled = true;
}
};
}
return cancelActionListener;
}
public String cancelAction()
{
return "testActionMethodTypeCancel";
}
public boolean isSubmitActionListenerCalled()
{
return submitActionListenerCalled;
}
public boolean isCancelActionListenerCalled()
{
return cancelActionListenerCalled;
}
public void setSubmitActionListenerCalled(boolean submitActionListenerCalled)
{
this.submitActionListenerCalled = submitActionListenerCalled;
}
public void setCancelActionListenerCalled(boolean cancelActionListenerCalled)
{
this.cancelActionListenerCalled = cancelActionListenerCalled;
}
private String name;
public String getName()
{
return name;
}
public void setName(String name)
{
this.name = name;
}
}
| |
package com.thoughtworks.go.config;
import com.rits.cloning.Cloner;
import com.thoughtworks.go.config.materials.*;
import com.thoughtworks.go.config.materials.dependency.DependencyMaterialConfig;
import com.thoughtworks.go.config.materials.git.GitMaterialConfig;
import com.thoughtworks.go.config.materials.mercurial.HgMaterialConfig;
import com.thoughtworks.go.config.materials.perforce.P4MaterialConfig;
import com.thoughtworks.go.config.materials.svn.SvnMaterialConfig;
import com.thoughtworks.go.config.materials.tfs.TfsMaterialConfig;
import com.thoughtworks.go.config.pluggabletask.PluggableTask;
import com.thoughtworks.go.config.remote.PartialConfig;
import com.thoughtworks.go.domain.ArtifactType;
import com.thoughtworks.go.domain.RunIfConfigs;
import com.thoughtworks.go.domain.config.Arguments;
import com.thoughtworks.go.domain.config.Configuration;
import com.thoughtworks.go.domain.config.PluginConfiguration;
import com.thoughtworks.go.domain.materials.MaterialConfig;
import com.thoughtworks.go.domain.packagerepository.PackageDefinition;
import com.thoughtworks.go.domain.packagerepository.PackageRepository;
import com.thoughtworks.go.domain.scm.SCM;
import com.thoughtworks.go.domain.scm.SCMs;
import com.thoughtworks.go.plugin.access.configrepo.contract.*;
import com.thoughtworks.go.plugin.access.configrepo.contract.material.*;
import com.thoughtworks.go.plugin.access.configrepo.contract.tasks.*;
import com.thoughtworks.go.security.GoCipher;
import com.thoughtworks.go.util.StringUtil;
import com.thoughtworks.go.util.command.HgUrlArgument;
import com.thoughtworks.go.util.command.UrlArgument;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.*;
/**
* Helper to transform config repo classes to config-api classes
*/
public class ConfigConverter {
private static final Logger LOGGER = LoggerFactory.getLogger(ConfigConverter.class);
private final GoCipher cipher;
private final CachedGoConfig cachedGoConfig;
private Cloner cloner = new Cloner();
public ConfigConverter(GoCipher goCipher, CachedGoConfig cachedGoConfig) {
this.cipher = goCipher;
this.cachedGoConfig = cachedGoConfig;
}
public PartialConfig toPartialConfig(CRParseResult crPartialConfig, PartialConfigLoadContext context) {
PartialConfig partialConfig = new PartialConfig();
for (CREnvironment crEnvironment : crPartialConfig.getEnvironments()) {
EnvironmentConfig environment = toEnvironmentConfig(crEnvironment);
partialConfig.getEnvironments().add(environment);
}
Map<String, List<CRPipeline>> pipesByGroup = groupPipelinesByGroupName(crPartialConfig.getPipelines());
for (Map.Entry<String, List<CRPipeline>> crPipelineGroup : pipesByGroup.entrySet()) {
BasicPipelineConfigs pipelineConfigs = toBasicPipelineConfigs(crPipelineGroup, context);
partialConfig.getGroups().add(pipelineConfigs);
}
return partialConfig;
}
public Map<String, List<CRPipeline>> groupPipelinesByGroupName(Collection<CRPipeline> pipelines) {
Map<String, List<CRPipeline>> map = new HashMap<>();
for (CRPipeline pipe : pipelines) {
String key = pipe.getGroupName();
if (map.get(key) == null) {
map.put(key, new ArrayList<CRPipeline>());
}
map.get(key).add(pipe);
}
return map;
}
public BasicPipelineConfigs toBasicPipelineConfigs(Map.Entry<String, List<CRPipeline>> crPipelineGroup, PartialConfigLoadContext context) {
String name = crPipelineGroup.getKey();
BasicPipelineConfigs pipelineConfigs = new BasicPipelineConfigs();
pipelineConfigs.setGroup(name);
for (CRPipeline crPipeline : crPipelineGroup.getValue()) {
pipelineConfigs.add(toPipelineConfig(crPipeline,context));
}
return pipelineConfigs;
}
public BasicEnvironmentConfig toEnvironmentConfig(CREnvironment crEnvironment) {
BasicEnvironmentConfig basicEnvironmentConfig =
new BasicEnvironmentConfig(new CaseInsensitiveString(crEnvironment.getName()));
for (String pipeline : crEnvironment.getPipelines()) {
basicEnvironmentConfig.addPipeline(new CaseInsensitiveString(pipeline));
}
for (String agent : crEnvironment.getAgents()) {
basicEnvironmentConfig.addAgent(agent);
}
for (CREnvironmentVariable var : crEnvironment.getEnvironmentVariables()) {
basicEnvironmentConfig.getVariables().add(toEnvironmentVariableConfig(var));
}
return basicEnvironmentConfig;
}
public EnvironmentVariableConfig toEnvironmentVariableConfig(CREnvironmentVariable crEnvironmentVariable) {
if (crEnvironmentVariable.hasEncryptedValue()) {
return new EnvironmentVariableConfig(cipher, crEnvironmentVariable.getName(), crEnvironmentVariable.getEncryptedValue());
} else {
return new EnvironmentVariableConfig(crEnvironmentVariable.getName(), crEnvironmentVariable.getValue());
}
}
public PluggableTask toPluggableTask(CRPluggableTask pluggableTask) {
PluginConfiguration pluginConfiguration = toPluginConfiguration(pluggableTask.getPluginConfiguration());
Configuration configuration = toConfiguration(pluggableTask.getConfiguration());
PluggableTask task = new PluggableTask(pluginConfiguration, configuration);
setCommonTaskMembers(task, pluggableTask);
return task;
}
private void setCommonTaskMembers(AbstractTask task, CRTask crTask) {
CRTask crTaskOnCancel = crTask.getOnCancel();
task.setCancelTask(crTaskOnCancel != null ? toAbstractTask(crTaskOnCancel) : null);
task.runIfConfigs = toRunIfConfigs(crTask.getRunIf());
}
private RunIfConfigs toRunIfConfigs(CRRunIf runIf) {
if (runIf == null)
return new RunIfConfigs(RunIfConfig.PASSED);
switch (runIf) {
case any:
return new RunIfConfigs(RunIfConfig.ANY);
case passed:
return new RunIfConfigs(RunIfConfig.PASSED);
case failed:
return new RunIfConfigs(RunIfConfig.FAILED);
default:
throw new RuntimeException(
String.format("unknown run if condition '%s'", runIf));
}
}
public AbstractTask toAbstractTask(CRTask crTask) {
if (crTask == null)
throw new ConfigConvertionException("task cannot be null");
if (crTask instanceof CRPluggableTask)
return toPluggableTask((CRPluggableTask) crTask);
else if (crTask instanceof CRBuildTask) {
return toBuildTask((CRBuildTask) crTask);
} else if (crTask instanceof CRExecTask) {
return toExecTask((CRExecTask) crTask);
} else if (crTask instanceof CRFetchArtifactTask) {
return toFetchTask((CRFetchArtifactTask) crTask);
} else
throw new RuntimeException(
String.format("unknown type of task '%s'", crTask));
}
public FetchTask toFetchTask(CRFetchArtifactTask crTask) {
FetchTask fetchTask = new FetchTask(
new CaseInsensitiveString(crTask.getPipelineName() == null ? "" : crTask.getPipelineName()),
new CaseInsensitiveString(crTask.getStage()),
new CaseInsensitiveString(crTask.getJob()),
crTask.getSource(),
crTask.getDestination());
if (crTask.sourceIsDirectory()) {
fetchTask.setSrcdir(crTask.getSource());
fetchTask.setSrcfile(null);
}
setCommonTaskMembers(fetchTask, crTask);
return fetchTask;
}
public ExecTask toExecTask(CRExecTask crTask) {
ExecTask execTask = new ExecTask(crTask.getCommand(), toArgList(crTask.getArgs()), crTask.getWorkingDirectory());
if (crTask.getTimeout() != null)
execTask.setTimeout(crTask.getTimeout());
// else default global-wide time
setCommonTaskMembers(execTask, crTask);
return execTask;
}
private Arguments toArgList(List<String> args) {
Arguments arguments = new Arguments();
if (args != null)
for (String arg : args) {
arguments.add(new Argument(arg));
}
return arguments;
}
public BuildTask toBuildTask(CRBuildTask crBuildTask) {
BuildTask buildTask;
switch (crBuildTask.getType()) {
case rake:
buildTask = new RakeTask();
break;
case ant:
buildTask = new AntTask();
break;
case nant:
buildTask = new NantTask();
break;
default:
throw new RuntimeException(
String.format("unknown type of build task '%s'", crBuildTask.getType()));
}
setCommonBuildTaskMembers(buildTask, crBuildTask);
setCommonTaskMembers(buildTask, crBuildTask);
return buildTask;
}
private void setCommonBuildTaskMembers(BuildTask buildTask, CRBuildTask crBuildTask) {
buildTask.buildFile = crBuildTask.getBuildFile();
buildTask.target = crBuildTask.getTarget();
buildTask.workingDirectory = crBuildTask.getWorkingDirectory();
}
private Configuration toConfiguration(Collection<CRConfigurationProperty> properties) {
Configuration configuration = new Configuration();
for (CRConfigurationProperty p : properties) {
if (p.getValue() != null)
configuration.addNewConfigurationWithValue(p.getKey(), p.getValue(), false);
else
configuration.addNewConfigurationWithValue(p.getKey(), p.getEncryptedValue(), true);
}
return configuration;
}
public PluginConfiguration toPluginConfiguration(CRPluginConfiguration pluginConfiguration) {
return new PluginConfiguration(pluginConfiguration.getId(), pluginConfiguration.getVersion());
}
public DependencyMaterialConfig toDependencyMaterialConfig(CRDependencyMaterial crDependencyMaterial) {
DependencyMaterialConfig dependencyMaterialConfig = new DependencyMaterialConfig(
new CaseInsensitiveString(crDependencyMaterial.getPipelineName()),
new CaseInsensitiveString(crDependencyMaterial.getStageName()));
setCommonMaterialMembers(dependencyMaterialConfig, crDependencyMaterial);
return dependencyMaterialConfig;
}
private void setCommonMaterialMembers(AbstractMaterialConfig materialConfig, CRMaterial crMaterial) {
materialConfig.setName(toMaterialName(crMaterial.getName()));
}
public MaterialConfig toMaterialConfig(CRMaterial crMaterial,PartialConfigLoadContext context) {
if (crMaterial == null)
throw new ConfigConvertionException("material cannot be null");
if (crMaterial instanceof CRDependencyMaterial)
return toDependencyMaterialConfig((CRDependencyMaterial) crMaterial);
else if (crMaterial instanceof CRScmMaterial) {
CRScmMaterial crScmMaterial = (CRScmMaterial) crMaterial;
return toScmMaterialConfig(crScmMaterial);
} else if (crMaterial instanceof CRPluggableScmMaterial) {
CRPluggableScmMaterial crPluggableScmMaterial = (CRPluggableScmMaterial) crMaterial;
return toPluggableScmMaterialConfig(crPluggableScmMaterial);
} else if (crMaterial instanceof CRPackageMaterial) {
CRPackageMaterial crPackageMaterial = (CRPackageMaterial) crMaterial;
return toPackageMaterial(crPackageMaterial);
} else if(crMaterial instanceof CRConfigMaterial) {
CRConfigMaterial crConfigMaterial = (CRConfigMaterial)crMaterial;
MaterialConfig repoMaterial = cloner.deepClone(context.configMaterial());
if(StringUtils.isNotEmpty(crConfigMaterial.getName()))
repoMaterial.setName(new CaseInsensitiveString(crConfigMaterial.getName()));
if(StringUtils.isNotEmpty(crConfigMaterial.getDestination()))
setDestination(repoMaterial,crConfigMaterial.getDestination());
if(crConfigMaterial.getFilter() != null && !crConfigMaterial.getFilter().isEmpty()) {
if(repoMaterial instanceof ScmMaterialConfig) {
ScmMaterialConfig scmMaterialConfig = (ScmMaterialConfig)repoMaterial;
scmMaterialConfig.setFilter(toFilter(crConfigMaterial.getFilter().getList()));
scmMaterialConfig.setInvertFilter(crConfigMaterial.getFilter().isWhitelist());
}
else //must be a pluggable SCM
{
PluggableSCMMaterialConfig pluggableSCMMaterial = (PluggableSCMMaterialConfig)repoMaterial;
pluggableSCMMaterial.setFilter(toFilter(crConfigMaterial.getFilter().getList()));
if(crConfigMaterial.getFilter().isWhitelist())
throw new ConfigConvertionException("Plugable SCMs do not support whitelisting");
}
}
return repoMaterial;
} else
throw new ConfigConvertionException(
String.format("unknown material type '%s'", crMaterial));
}
private void setDestination(MaterialConfig repoMaterial, String destination) {
if(repoMaterial instanceof ScmMaterialConfig)
{
((ScmMaterialConfig)repoMaterial).setFolder(destination);
}
else if(repoMaterial instanceof PluggableSCMMaterialConfig)
{
((PluggableSCMMaterialConfig)repoMaterial).setFolder(destination);
}
else
LOGGER.warn("Unknown material type " + repoMaterial.getTypeForDisplay());
}
public PackageMaterialConfig toPackageMaterial(CRPackageMaterial crPackageMaterial) {
PackageDefinition packageDefinition = getPackageDefinition(crPackageMaterial.getPackageId());
return new PackageMaterialConfig(toMaterialName(crPackageMaterial.getName()), crPackageMaterial.getPackageId(), packageDefinition);
}
private PackageDefinition getPackageDefinition(String packageId) {
PackageRepository packageRepositoryHaving = this.cachedGoConfig.currentConfig().getPackageRepositories().findPackageRepositoryHaving(packageId);
if (packageRepositoryHaving == null)
throw new ConfigConvertionException(
String.format("Failed to find package repository with package id '%s'", packageId));
return packageRepositoryHaving.findPackage(packageId);
}
private PluggableSCMMaterialConfig toPluggableScmMaterialConfig(CRPluggableScmMaterial crPluggableScmMaterial) {
SCMs scms = getSCMs();
String id = crPluggableScmMaterial.getScmId();
SCM scmConfig = scms.find(id);
if (scmConfig == null)
throw new ConfigConvertionException(
String.format("Failed to find referenced scm '%s'", id));
return new PluggableSCMMaterialConfig(toMaterialName(crPluggableScmMaterial.getName()),
scmConfig, crPluggableScmMaterial.getDirectory(),
toFilter(crPluggableScmMaterial.getFilterList()));
}
private SCMs getSCMs() {
return this.cachedGoConfig.currentConfig().getSCMs();
}
private ScmMaterialConfig toScmMaterialConfig(CRScmMaterial crScmMaterial) {
String materialName = crScmMaterial.getName();
if (crScmMaterial instanceof CRGitMaterial) {
CRGitMaterial git = (CRGitMaterial) crScmMaterial;
String gitBranch = git.getBranch();
if (StringUtils.isBlank(gitBranch))
gitBranch = GitMaterialConfig.DEFAULT_BRANCH;
GitMaterialConfig gitConfig = new GitMaterialConfig(git.getUrl(), gitBranch, git.shallowClone());
setCommonMaterialMembers(gitConfig, crScmMaterial);
setCommonScmMaterialMembers(gitConfig, git);
return gitConfig;
} else if (crScmMaterial instanceof CRHgMaterial) {
CRHgMaterial hg = (CRHgMaterial) crScmMaterial;
return new HgMaterialConfig(new HgUrlArgument(hg.getUrl()),
hg.isAutoUpdate(), toFilter(crScmMaterial), false, hg.getDirectory(),
toMaterialName(materialName));
} else if (crScmMaterial instanceof CRP4Material) {
CRP4Material crp4Material = (CRP4Material) crScmMaterial;
P4MaterialConfig p4MaterialConfig = new P4MaterialConfig(crp4Material.getServerAndPort(), crp4Material.getView(), cipher);
if (crp4Material.getEncryptedPassword() != null) {
p4MaterialConfig.setEncryptedPassword(crp4Material.getEncryptedPassword());
} else {
p4MaterialConfig.setPassword(crp4Material.getPassword());
}
p4MaterialConfig.setUserName(crp4Material.getUserName());
p4MaterialConfig.setUseTickets(crp4Material.getUseTickets());
setCommonMaterialMembers(p4MaterialConfig, crScmMaterial);
setCommonScmMaterialMembers(p4MaterialConfig, crp4Material);
return p4MaterialConfig;
} else if (crScmMaterial instanceof CRSvnMaterial) {
CRSvnMaterial crSvnMaterial = (CRSvnMaterial) crScmMaterial;
SvnMaterialConfig svnMaterialConfig = new SvnMaterialConfig(
crSvnMaterial.getUrl(), crSvnMaterial.getUserName(), crSvnMaterial.isCheckExternals(), cipher);
if (crSvnMaterial.getEncryptedPassword() != null) {
svnMaterialConfig.setEncryptedPassword(crSvnMaterial.getEncryptedPassword());
} else {
svnMaterialConfig.setPassword(crSvnMaterial.getPassword());
}
setCommonMaterialMembers(svnMaterialConfig, crScmMaterial);
setCommonScmMaterialMembers(svnMaterialConfig, crSvnMaterial);
return svnMaterialConfig;
} else if (crScmMaterial instanceof CRTfsMaterial) {
CRTfsMaterial crTfsMaterial = (CRTfsMaterial) crScmMaterial;
TfsMaterialConfig tfsMaterialConfig = new TfsMaterialConfig(cipher,
new UrlArgument(crTfsMaterial.getUrl()),
crTfsMaterial.getUserName(),
crTfsMaterial.getDomain(),
crTfsMaterial.getProjectPath());
if (crTfsMaterial.getEncryptedPassword() != null) {
tfsMaterialConfig.setEncryptedPassword(crTfsMaterial.getEncryptedPassword());
} else {
tfsMaterialConfig.setPassword(crTfsMaterial.getPassword());
}
setCommonMaterialMembers(tfsMaterialConfig, crTfsMaterial);
setCommonScmMaterialMembers(tfsMaterialConfig, crTfsMaterial);
return tfsMaterialConfig;
} else
throw new ConfigConvertionException(
String.format("unknown scm material type '%s'", crScmMaterial));
}
private CaseInsensitiveString toMaterialName(String materialName) {
if (StringUtils.isBlank(materialName))
return null;
return new CaseInsensitiveString(materialName);
}
private void setCommonScmMaterialMembers(ScmMaterialConfig scmMaterialConfig, CRScmMaterial crScmMaterial) {
scmMaterialConfig.setFolder(crScmMaterial.getDirectory());
scmMaterialConfig.setAutoUpdate(crScmMaterial.isAutoUpdate());
scmMaterialConfig.setFilter(toFilter(crScmMaterial));
scmMaterialConfig.setInvertFilter(crScmMaterial.isWhitelist());
}
private Filter toFilter(CRScmMaterial crScmMaterial) {
List<String> filterList = crScmMaterial.getFilterList();
return toFilter(filterList);
}
private Filter toFilter(List<String> filterList) {
Filter filter = new Filter();
if (filterList == null)
return filter;
for (String pattern : filterList) {
filter.add(new IgnoredFiles(pattern));
}
return filter;
}
public JobConfig toJobConfig(CRJob crJob) {
JobConfig jobConfig = new JobConfig(crJob.getName());
if (crJob.getEnvironmentVariables() != null)
for (CREnvironmentVariable crEnvironmentVariable : crJob.getEnvironmentVariables()) {
jobConfig.getVariables().add(toEnvironmentVariableConfig(crEnvironmentVariable));
}
List<CRTask> crTasks = crJob.getTasks();
Tasks tasks = jobConfig.getTasks();
if (crTasks != null)
for (CRTask crTask : crTasks) {
tasks.add(toAbstractTask(crTask));
}
Tabs tabs = jobConfig.getTabs();
if (crJob.getTabs() != null)
for (CRTab crTab : crJob.getTabs()) {
tabs.add(toTab(crTab));
}
Resources resources = jobConfig.resources();
if (crJob.getResources() != null)
for (String crResource : crJob.getResources()) {
resources.add(new Resource(crResource));
}
if(crJob.getElasticProfileId() != null)
jobConfig.setElasticProfileId(crJob.getElasticProfileId());
ArtifactPlans artifactPlans = jobConfig.artifactPlans();
if (crJob.getArtifacts() != null)
for (CRArtifact crArtifact : crJob.getArtifacts()) {
artifactPlans.add(toArtifactPlan(crArtifact));
}
ArtifactPropertiesGenerators artifactPropertiesGenerators = jobConfig.getProperties();
if (crJob.getArtifactPropertiesGenerators() != null)
for (CRPropertyGenerator crPropertyGenerator : crJob.getArtifactPropertiesGenerators()) {
artifactPropertiesGenerators.add(new ArtifactPropertiesGenerator(
crPropertyGenerator.getName(), crPropertyGenerator.getSrc(), crPropertyGenerator.getXpath()));
}
if (crJob.isRunOnAllAgents())
jobConfig.setRunOnAllAgents(true);
else {
Integer count = crJob.getRunInstanceCount();
if (count != null)
jobConfig.setRunInstanceCount(count);
// else null - meaning simple job
}
if (crJob.getTimeout() != null)
jobConfig.setTimeout(Integer.toString(crJob.getTimeout()));
//else null - means default server-wide timeout
return jobConfig;
}
public ArtifactPlan toArtifactPlan(CRArtifact crArtifact) {
ArtifactType artType = crArtifact.getType() == CRArtifactType.build ?
ArtifactType.file : ArtifactType.unit;
if (crArtifact.getDestination() != null)
return new ArtifactPlan(artType, crArtifact.getSource(), crArtifact.getDestination());
else
return new ArtifactPlan(artType, crArtifact.getSource());
}
private Tab toTab(CRTab crTab) {
return new Tab(crTab.getName(), crTab.getPath());
}
public StageConfig toStage(CRStage crStage) {
Approval approval = toApproval(crStage.getApproval());
StageConfig stageConfig = new StageConfig(new CaseInsensitiveString(crStage.getName()), crStage.isFetchMaterials(),
crStage.isCleanWorkingDir(), approval, crStage.isArtifactCleanupProhibited(), toJobConfigs(crStage.getJobs()));
EnvironmentVariablesConfig environmentVariableConfigs = stageConfig.getVariables();
for (CREnvironmentVariable crEnvironmentVariable : crStage.getEnvironmentVariables()) {
environmentVariableConfigs.add(toEnvironmentVariableConfig(crEnvironmentVariable));
}
return stageConfig;
}
public Approval toApproval(CRApproval crApproval) {
if (crApproval == null)
return Approval.automaticApproval();
Approval approval;
if (crApproval.getType() == CRApprovalCondition.manual)
approval = Approval.manualApproval();
else
approval = Approval.automaticApproval();
AuthConfig authConfig = approval.getAuthConfig();
for (String user : crApproval.getAuthorizedUsers()) {
authConfig.add(new AdminUser(new CaseInsensitiveString(user)));
}
for (String user : crApproval.getAuthorizedRoles()) {
authConfig.add(new AdminRole(new CaseInsensitiveString(user)));
}
return approval;
}
private JobConfigs toJobConfigs(Collection<CRJob> jobs) {
JobConfigs jobConfigs = new JobConfigs();
for (CRJob crJob : jobs) {
jobConfigs.add(toJobConfig(crJob));
}
return jobConfigs;
}
public PipelineConfig toPipelineConfig(CRPipeline crPipeline,PartialConfigLoadContext context) {
MaterialConfigs materialConfigs = new MaterialConfigs();
for (CRMaterial crMaterial : crPipeline.getMaterials()) {
materialConfigs.add(toMaterialConfig(crMaterial,context));
}
PipelineConfig pipelineConfig = new PipelineConfig(new CaseInsensitiveString(crPipeline.getName()), materialConfigs);
for (CRStage crStage : crPipeline.getStages()) {
pipelineConfig.add(toStage(crStage));
}
if (crPipeline.getLabelTemplate() != null)
pipelineConfig.setLabelTemplate(crPipeline.getLabelTemplate());
CRTrackingTool crTrackingTool = crPipeline.getTrackingTool();
if (crTrackingTool != null) {
pipelineConfig.setTrackingTool(toTrackingTool(crTrackingTool));
}
CRMingle crMingle = crPipeline.getMingle();
if (crMingle != null) {
pipelineConfig.setMingleConfig(toMingleConfig(crMingle));
}
CRTimer crTimer = crPipeline.getTimer();
if (crTimer != null) {
pipelineConfig.setTimer(toTimerConfig(crTimer));
}
EnvironmentVariablesConfig variables = pipelineConfig.getVariables();
for (CREnvironmentVariable crEnvironmentVariable : crPipeline.getEnvironmentVariables()) {
variables.add(toEnvironmentVariableConfig(crEnvironmentVariable));
}
pipelineConfig.setLock(crPipeline.isLocked());
return pipelineConfig;
}
public TimerConfig toTimerConfig(CRTimer crTimer) {
String spec = crTimer.getTimerSpec();
if(StringUtil.isBlank(spec))
throw new RuntimeException("timer schedule is not specified");
return new TimerConfig(spec, crTimer.isOnlyOnChanges() == null ? false : crTimer.isOnlyOnChanges());
}
private MingleConfig toMingleConfig(CRMingle crMingle) {
return new MingleConfig(crMingle.getBaseUrl(), crMingle.getProjectIdentifier(), crMingle.getMqlGroupingConditions());
}
private TrackingTool toTrackingTool(CRTrackingTool crTrackingTool) {
return new TrackingTool(crTrackingTool.getLink(), crTrackingTool.getRegex());
}
}
| |
/*
* Copyright (c) 2016, Salesforce.com, Inc.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* 3. Neither the name of Salesforce.com nor the names of its contributors may
* be used to endorse or promote products derived from this software without
* specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
package com.salesforce.dva.argus.sdk.entity;
import java.util.List;
import java.util.Objects;
/**
* Batch query object.
*
* @author Tom Valine (tvaline@salesforce.com)
*/
public class Batch {
//~ Instance fields ******************************************************************************************************************************
private String status;
private int ttl;
private long createdDate;
private String ownerName;
private List<Query> queries;
//~ Methods **************************************************************************************************************************************
/**
* Sets the batch status.
*
* @param status The batch status.
*/
public void setStatus(String status) {
this.status = status;
}
/**
* Sets the time to live for the batch.
*
* @param ttl The time to live in seconds.
*/
public void setTtl(int ttl) {
this.ttl = ttl;
}
/**
* Sets the created date for the batch.
*
* @param createdDate The created date.
*/
public void setCreatedDate(long createdDate) {
this.createdDate = createdDate;
}
/**
* Sets the name of the batch owner.
*
* @param ownerName The name of the batch owner.
*/
public void setOwnerName(String ownerName) {
this.ownerName = ownerName;
}
/**
* Sets the queries associated with the batch.
*
* @param queries The queries associated with the batch.
*/
public void setQueries(List<Query> queries) {
this.queries = queries;
}
/**
* Returns the batch status.
*
* @return The batch status.
*/
public String getStatus() {
return status;
}
/**
* Returns the time to live for the batch.
*
* @return The time to live.
*/
public int getTtl() {
return ttl;
}
/**
* Returns the time the batch was created in milliseconds from the epoch.
*
* @return The time the batch was created.
*/
public long getCreatedDate() {
return createdDate;
}
/**
* Returns the name of the batch owner.
*
* @return The name of the batch owner.
*/
public String getOwnerName() {
return ownerName;
}
/**
* Returns the list of queries associated with the batch.
*
* @return The queries associated with the batch.
*/
public List<Query> getQueries() {
return queries;
}
@Override
public int hashCode() {
int hash = 7;
hash = 59 * hash + Objects.hashCode(this.status);
hash = 59 * hash + this.ttl;
hash = 59 * hash + (int) (this.createdDate ^ (this.createdDate >>> 32));
hash = 59 * hash + Objects.hashCode(this.ownerName);
hash = 59 * hash + Objects.hashCode(this.queries);
return hash;
}
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
final Batch other = (Batch) obj;
if (this.ttl != other.ttl) {
return false;
}
if (this.createdDate != other.createdDate) {
return false;
}
if (!Objects.equals(this.status, other.status)) {
return false;
}
if (!Objects.equals(this.ownerName, other.ownerName)) {
return false;
}
if (!Objects.equals(this.queries, other.queries)) {
return false;
}
return true;
}
//~ Inner Classes ********************************************************************************************************************************
/**
* The batch query object.
*
* @author Tom Valine (tvaline@salesforce.com)
*/
public static class Query {
private String expression;
private Metric result;
private String message;
/**
* Creates a new Query object.
*
* @param expression The query expression.
* @param result The query result.
* @param message The status message.
*/
public Query(String expression, Metric result, String message) {
this.expression = expression;
this.result = result;
this.message = message;
}
private Query() { }
/**
* Returns the expression.
*
* @return The expression.
*/
public String getExpression() {
return expression;
}
/**
* Sets the expression.
*
* @param expression The expression.
*/
public void setExpression(String expression) {
this.expression = expression;
}
/**
* Returns the query result.
*
* @return The query result.
*/
public Metric getResult() {
return result;
}
/**
* Sets the query result.
*
* @param result The query result.
*/
public void setResult(Metric result) {
this.result = result;
}
/**
* Returns the status message.
*
* @return The status message.
*/
public String getMessage() {
return message;
}
/**
* Sets the status message.
*
* @param message The status message.
*/
public void setMessage(String message) {
this.message = message;
}
@Override
public int hashCode() {
int hash = 5;
hash = 79 * hash + Objects.hashCode(this.expression);
hash = 79 * hash + Objects.hashCode(this.result);
hash = 79 * hash + Objects.hashCode(this.message);
return hash;
}
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
final Query other = (Query) obj;
if (!Objects.equals(this.expression, other.expression)) {
return false;
}
if (!Objects.equals(this.message, other.message)) {
return false;
}
if (!Objects.equals(this.result, other.result)) {
return false;
}
return true;
}
}
}
/* Copyright (c) 2016, Salesforce.com, Inc. All rights reserved. */
| |
/**
* <pre>
* Copyright 2015 Soulwolf Ching
* Copyright 2015 The Android Open Source Project for Android-RatioLayout
*
* 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.
* </pre>
*/
package net.soulwolf.widget.ratiolayout.sample;
import android.annotation.SuppressLint;
import android.annotation.TargetApi;
import android.app.Activity;
import android.content.Context;
import android.content.res.Configuration;
import android.content.res.Resources;
import android.content.res.TypedArray;
import android.graphics.drawable.Drawable;
import android.os.Build;
import android.util.DisplayMetrics;
import android.util.TypedValue;
import android.view.Gravity;
import android.view.View;
import android.view.ViewConfiguration;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.FrameLayout;
import android.widget.FrameLayout.LayoutParams;
import android.widget.LinearLayout;
import java.lang.reflect.Method;
/**
* author: Soulwolf Created on 2015/8/8 1:10.
* email : Ching.Soulwolf@gmail.com
*/
public class SystemBarTintManager {
static {
// Android allows a system property to override the presence of the navigation bar.
// Used by the emulator.
// See https://github.com/android/platform_frameworks_base/blob/master/policy/src/com/android/internal/policy/impl/PhoneWindowManager.java#L1076
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
try {
Class c = Class.forName("android.os.SystemProperties");
Method m = c.getDeclaredMethod("get", String.class);
m.setAccessible(true);
sNavBarOverride = (String) m.invoke(null, "qemu.hw.mainkeys");
} catch (Throwable e) {
sNavBarOverride = null;
}
}
}
/**
* The default system bar tint color value.
*/
public static final int DEFAULT_TINT_COLOR = 0x99000000;
private static String sNavBarOverride;
private final SystemBarConfig mConfig;
private boolean mStatusBarAvailable;
private boolean mNavBarAvailable;
private boolean mStatusBarTintEnabled;
private boolean mNavBarTintEnabled;
private View mStatusBarTintView;
private View mNavBarTintView;
/**
* Constructor. Call this in the host activity onCreate method after its
* content view has been set. You should always create new instances when
* the host activity is recreated.
*
* @param activity The host activity.
*/
@TargetApi(Build.VERSION_CODES.KITKAT)
public SystemBarTintManager(Activity activity) {
Window win = activity.getWindow();
ViewGroup decorViewGroup = (ViewGroup) win.getDecorView();
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
// check theme attrs
int[] attrs = {android.R.attr.windowTranslucentStatus,
android.R.attr.windowTranslucentNavigation};
TypedArray a = activity.obtainStyledAttributes(attrs);
try {
mStatusBarAvailable = a.getBoolean(0, false);
mNavBarAvailable = a.getBoolean(1, false);
} finally {
a.recycle();
}
// check window flags
WindowManager.LayoutParams winParams = win.getAttributes();
int bits = WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS;
if ((winParams.flags & bits) != 0) {
mStatusBarAvailable = true;
}
bits = WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION;
if ((winParams.flags & bits) != 0) {
mNavBarAvailable = true;
}
}
mConfig = new SystemBarConfig(activity, mStatusBarAvailable, mNavBarAvailable);
// device might not have virtual navigation keys
if (!mConfig.hasNavigtionBar()) {
mNavBarAvailable = false;
}
View childRoot = decorViewGroup.getChildAt(0);
decorViewGroup.removeView(childRoot);
LinearLayout rootView = new LinearLayout(activity);
rootView.setOrientation(LinearLayout.VERTICAL);
if (mStatusBarAvailable) {
setupStatusBarView(activity, rootView);
}
rootView.addView(childRoot,generateLayoutParams(LinearLayout.LayoutParams.MATCH_PARENT,
0,1.0f));
if (mNavBarAvailable) {
setupNavBarView(activity, rootView);
}
decorViewGroup.addView(rootView,LayoutParams.MATCH_PARENT,LayoutParams.MATCH_PARENT);
}
protected LinearLayout.LayoutParams generateLayoutParams(int width,int height,float weight) {
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(width,height);
if(weight != 0){
params.weight = weight;
}
return params;
}
/**
* Enable tinting of the system status bar.
*
* If the platform is running Jelly Bean or earlier, or translucent system
* UI modes have not been enabled in either the theme or via window flags,
* then this method does nothing.
*
* @param enabled True to enable tinting, false to disable it (default).
*/
public void setStatusBarTintEnabled(boolean enabled) {
mStatusBarTintEnabled = enabled;
if (mStatusBarAvailable) {
mStatusBarTintView.setVisibility(enabled ? View.VISIBLE : View.GONE);
}
}
/**
* Enable tinting of the system navigation bar.
*
* If the platform does not have soft navigation keys, is running Jelly Bean
* or earlier, or translucent system UI modes have not been enabled in either
* the theme or via window flags, then this method does nothing.
*
* @param enabled True to enable tinting, false to disable it (default).
*/
public void setNavigationBarTintEnabled(boolean enabled) {
mNavBarTintEnabled = enabled;
if (mNavBarAvailable) {
mNavBarTintView.setVisibility(enabled ? View.VISIBLE : View.GONE);
}
}
/**
* Apply the specified color tint to all system UI bars.
*
* @param color The color of the background tint.
*/
public void setTintColor(int color) {
setStatusBarTintColor(color);
setNavigationBarTintColor(color);
}
/**
* Apply the specified drawable or color resource to all system UI bars.
*
* @param res The identifier of the resource.
*/
public void setTintResource(int res) {
setStatusBarTintResource(res);
setNavigationBarTintResource(res);
}
/**
* Apply the specified drawable to all system UI bars.
*
* @param drawable The drawable to use as the background, or null to remove it.
*/
public void setTintDrawable(Drawable drawable) {
setStatusBarTintDrawable(drawable);
setNavigationBarTintDrawable(drawable);
}
/**
* Apply the specified alpha to all system UI bars.
*
* @param alpha The alpha to use
*/
public void setTintAlpha(float alpha) {
setStatusBarAlpha(alpha);
setNavigationBarAlpha(alpha);
}
/**
* Apply the specified color tint to the system status bar.
*
* @param color The color of the background tint.
*/
public void setStatusBarTintColor(int color) {
if (mStatusBarAvailable) {
mStatusBarTintView.setBackgroundColor(color);
}
}
/**
* Apply the specified drawable or color resource to the system status bar.
*
* @param res The identifier of the resource.
*/
public void setStatusBarTintResource(int res) {
if (mStatusBarAvailable) {
mStatusBarTintView.setBackgroundResource(res);
}
}
/**
* Apply the specified drawable to the system status bar.
*
* @param drawable The drawable to use as the background, or null to remove it.
*/
@SuppressWarnings("deprecation")
public void setStatusBarTintDrawable(Drawable drawable) {
if (mStatusBarAvailable) {
mStatusBarTintView.setBackgroundDrawable(drawable);
}
}
/**
* Apply the specified alpha to the system status bar.
*
* @param alpha The alpha to use
*/
@TargetApi(Build.VERSION_CODES.HONEYCOMB)
public void setStatusBarAlpha(float alpha) {
if (mStatusBarAvailable && Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
mStatusBarTintView.setAlpha(alpha);
}
}
/**
* Apply the specified color tint to the system navigation bar.
*
* @param color The color of the background tint.
*/
public void setNavigationBarTintColor(int color) {
if (mNavBarAvailable) {
mNavBarTintView.setBackgroundColor(color);
}
}
/**
* Apply the specified drawable or color resource to the system navigation bar.
*
* @param res The identifier of the resource.
*/
public void setNavigationBarTintResource(int res) {
if (mNavBarAvailable) {
mNavBarTintView.setBackgroundResource(res);
}
}
/**
* Apply the specified drawable to the system navigation bar.
*
* @param drawable The drawable to use as the background, or null to remove it.
*/
@SuppressWarnings("deprecation")
public void setNavigationBarTintDrawable(Drawable drawable) {
if (mNavBarAvailable) {
mNavBarTintView.setBackgroundDrawable(drawable);
}
}
/**
* Apply the specified alpha to the system navigation bar.
*
* @param alpha The alpha to use
*/
@TargetApi(Build.VERSION_CODES.HONEYCOMB)
public void setNavigationBarAlpha(float alpha) {
if (mNavBarAvailable && Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
mNavBarTintView.setAlpha(alpha);
}
}
/**
* Get the system bar configuration.
*
* @return The system bar configuration for the current device configuration.
*/
public SystemBarConfig getConfig() {
return mConfig;
}
/**
* Is tinting enabled for the system status bar?
*
* @return True if enabled, False otherwise.
*/
public boolean isStatusBarTintEnabled() {
return mStatusBarTintEnabled;
}
/**
* Is tinting enabled for the system navigation bar?
*
* @return True if enabled, False otherwise.
*/
public boolean isNavBarTintEnabled() {
return mNavBarTintEnabled;
}
private void setupStatusBarView(Context context, ViewGroup decorViewGroup) {
mStatusBarTintView = new View(context);
LinearLayout.LayoutParams params = generateLayoutParams(LinearLayout.LayoutParams.MATCH_PARENT
, mConfig.getStatusBarHeight(),0);
if (mNavBarAvailable && !mConfig.isNavigationAtBottom()) {
params.rightMargin = mConfig.getNavigationBarWidth();
}
mStatusBarTintView.setLayoutParams(params);
mStatusBarTintView.setBackgroundColor(DEFAULT_TINT_COLOR);
mStatusBarTintView.setVisibility(View.GONE);
decorViewGroup.addView(mStatusBarTintView);
}
private void setupNavBarView(Context context, ViewGroup decorViewGroup) {
mNavBarTintView = new View(context);
LinearLayout.LayoutParams params;
if (mConfig.isNavigationAtBottom()) {
params = generateLayoutParams(LinearLayout.LayoutParams.MATCH_PARENT
, mConfig.getNavigationBarHeight(),0);
} else {
params = generateLayoutParams(mConfig.getNavigationBarWidth(),
LinearLayout.LayoutParams.MATCH_PARENT,0);
}
mNavBarTintView.setLayoutParams(params);
mNavBarTintView.setBackgroundColor(DEFAULT_TINT_COLOR);
mNavBarTintView.setVisibility(View.GONE);
decorViewGroup.addView(mNavBarTintView);
}
/**
* Class which describes system bar sizing and other characteristics for the current
* device configuration.
*
*/
public static class SystemBarConfig {
private static final String STATUS_BAR_HEIGHT_RES_NAME = "status_bar_height";
private static final String NAV_BAR_HEIGHT_RES_NAME = "navigation_bar_height";
private static final String NAV_BAR_HEIGHT_LANDSCAPE_RES_NAME = "navigation_bar_height_landscape";
private static final String NAV_BAR_WIDTH_RES_NAME = "navigation_bar_width";
private static final String SHOW_NAV_BAR_RES_NAME = "config_showNavigationBar";
private final boolean mTranslucentStatusBar;
private final boolean mTranslucentNavBar;
private final int mStatusBarHeight;
private final int mActionBarHeight;
private final boolean mHasNavigationBar;
private final int mNavigationBarHeight;
private final int mNavigationBarWidth;
private final boolean mInPortrait;
private final float mSmallestWidthDp;
private SystemBarConfig(Activity activity, boolean translucentStatusBar, boolean traslucentNavBar) {
Resources res = activity.getResources();
mInPortrait = (res.getConfiguration().orientation == Configuration.ORIENTATION_PORTRAIT);
mSmallestWidthDp = getSmallestWidthDp(activity);
mStatusBarHeight = getInternalDimensionSize(res, STATUS_BAR_HEIGHT_RES_NAME);
mActionBarHeight = getActionBarHeight(activity);
mNavigationBarHeight = getNavigationBarHeight(activity);
mNavigationBarWidth = getNavigationBarWidth(activity);
mHasNavigationBar = (mNavigationBarHeight > 0);
mTranslucentStatusBar = translucentStatusBar;
mTranslucentNavBar = traslucentNavBar;
}
@TargetApi(Build.VERSION_CODES.ICE_CREAM_SANDWICH)
private int getActionBarHeight(Context context) {
int result = 0;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH) {
TypedValue tv = new TypedValue();
context.getTheme().resolveAttribute(android.R.attr.actionBarSize, tv, true);
result = TypedValue.complexToDimensionPixelSize(tv.data, context.getResources().getDisplayMetrics());
}
return result;
}
@TargetApi(Build.VERSION_CODES.ICE_CREAM_SANDWICH)
private int getNavigationBarHeight(Context context) {
Resources res = context.getResources();
int result = 0;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH) {
if (hasNavBar(context)) {
String key;
if (mInPortrait) {
key = NAV_BAR_HEIGHT_RES_NAME;
} else {
key = NAV_BAR_HEIGHT_LANDSCAPE_RES_NAME;
}
return getInternalDimensionSize(res, key);
}
}
return result;
}
@TargetApi(14)
private int getNavigationBarWidth(Context context) {
Resources res = context.getResources();
int result = 0;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH) {
if (hasNavBar(context)) {
return getInternalDimensionSize(res, NAV_BAR_WIDTH_RES_NAME);
}
}
return result;
}
@TargetApi(Build.VERSION_CODES.ICE_CREAM_SANDWICH)
private boolean hasNavBar(Context context) {
// Resources res = context.getResources();
// int resourceId = res.getIdentifier(SHOW_NAV_BAR_RES_NAME, "bool", "android");
// if (resourceId != 0) {
// boolean hasNav = res.getBoolean(resourceId);
// // check override flag (see static block)
// if ("1".equals(sNavBarOverride)) {
// hasNav = false;
// } else if ("0".equals(sNavBarOverride)) {
// hasNav = true;
// }
// return hasNav;
// } else { // fallback
return !ViewConfiguration.get(context).hasPermanentMenuKey();
// }
}
private int getInternalDimensionSize(Resources res, String key) {
int result = 0;
int resourceId = res.getIdentifier(key, "dimen", "android");
if (resourceId > 0) {
result = res.getDimensionPixelSize(resourceId);
}
return result;
}
@SuppressLint("NewApi")
private float getSmallestWidthDp(Activity activity) {
DisplayMetrics metrics = new DisplayMetrics();
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
activity.getWindowManager().getDefaultDisplay().getRealMetrics(metrics);
} else {
// TODO this is not correct, but we don't really care pre-kitkat
activity.getWindowManager().getDefaultDisplay().getMetrics(metrics);
}
float widthDp = metrics.widthPixels / metrics.density;
float heightDp = metrics.heightPixels / metrics.density;
return Math.min(widthDp, heightDp);
}
/**
* Should a navigation bar appear at the bottom of the screen in the current
* device configuration? A navigation bar may appear on the right side of
* the screen in certain configurations.
*
* @return True if navigation should appear at the bottom of the screen, False otherwise.
*/
public boolean isNavigationAtBottom() {
return (mSmallestWidthDp >= 600 || mInPortrait);
}
/**
* Get the height of the system status bar.
*
* @return The height of the status bar (in pixels).
*/
public int getStatusBarHeight() {
return mStatusBarHeight;
}
/**
* Get the height of the action bar.
*
* @return The height of the action bar (in pixels).
*/
public int getActionBarHeight() {
return mActionBarHeight;
}
/**
* Does this device have a system navigation bar?
*
* @return True if this device uses soft key navigation, False otherwise.
*/
public boolean hasNavigtionBar() {
return mHasNavigationBar;
}
/**
* Get the height of the system navigation bar.
*
* @return The height of the navigation bar (in pixels). If the device does not have
* soft navigation keys, this will always return 0.
*/
public int getNavigationBarHeight() {
return mNavigationBarHeight;
}
/**
* Get the width of the system navigation bar when it is placed vertically on the screen.
*
* @return The width of the navigation bar (in pixels). If the device does not have
* soft navigation keys, this will always return 0.
*/
public int getNavigationBarWidth() {
return mNavigationBarWidth;
}
/**
* Get the layout inset for any system UI that appears at the top of the screen.
*
* @param withActionBar True to include the height of the action bar, False otherwise.
* @return The layout inset (in pixels).
*/
public int getPixelInsetTop(boolean withActionBar) {
return (mTranslucentStatusBar ? mStatusBarHeight : 0) + (withActionBar ? mActionBarHeight : 0);
}
/**
* Get the layout inset for any system UI that appears at the bottom of the screen.
*
* @return The layout inset (in pixels).
*/
public int getPixelInsetBottom() {
if (mTranslucentNavBar && isNavigationAtBottom()) {
return mNavigationBarHeight;
} else {
return 0;
}
}
/**
* Get the layout inset for any system UI that appears at the right of the screen.
*
* @return The layout inset (in pixels).
*/
public int getPixelInsetRight() {
if (mTranslucentNavBar && !isNavigationAtBottom()) {
return mNavigationBarWidth;
} else {
return 0;
}
}
}
}
| |
/**
* Code contributed to the Learning Layers project
* http://www.learning-layers.eu
* Development is partly funded by the FP7 Programme of the European Commission under
* Grant Agreement FP7-ICT-318209.
* Copyright (c) 2015, Graz University of Technology - KTI (Knowledge Technologies Institute).
* For a list of contributors see the AUTHORS file at the top-level directory of this distribution.
*
* 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 at.tugraz.sss.adapter.rest.v3.disc;
import at.kc.tugraz.ss.service.disc.api.*;
import at.tugraz.sss.adapter.rest.v3.SSRESTCommons;
import at.tugraz.sss.serv.conf.SSConf;
import at.kc.tugraz.ss.service.disc.datatypes.pars.SSDiscEntryAcceptPar;
import at.kc.tugraz.ss.service.disc.datatypes.pars.SSDiscEntryAddFromClientPar;
import at.kc.tugraz.ss.service.disc.datatypes.pars.SSDiscEntryAddPar;
import at.kc.tugraz.ss.service.disc.datatypes.pars.SSDiscEntryUpdatePar;
import at.kc.tugraz.ss.service.disc.datatypes.pars.SSDiscGetPar;
import at.kc.tugraz.ss.service.disc.datatypes.pars.SSDiscTargetsAddPar;
import at.kc.tugraz.ss.service.disc.datatypes.pars.SSDiscUpdatePar;
import at.kc.tugraz.ss.service.disc.datatypes.pars.SSDiscsGetPar;
import at.kc.tugraz.ss.service.disc.datatypes.ret.SSDiscEntryAcceptRet;
import at.kc.tugraz.ss.service.disc.datatypes.ret.SSDiscEntryAddRet;
import at.kc.tugraz.ss.service.disc.datatypes.ret.SSDiscEntryUpdateRet;
import at.kc.tugraz.ss.service.disc.datatypes.ret.SSDiscGetRet;
import at.kc.tugraz.ss.service.disc.datatypes.ret.SSDiscTargetsAddRet;
import at.kc.tugraz.ss.service.disc.datatypes.ret.SSDiscUpdateRet;
import at.kc.tugraz.ss.service.disc.datatypes.ret.SSDiscsGetRet;
import at.tugraz.sss.serv.util.*;
import at.tugraz.sss.serv.datatype.*;
import at.tugraz.sss.serv.datatype.enums.*;
import at.tugraz.sss.serv.datatype.par.*;
import at.tugraz.sss.serv.db.api.*;
import at.tugraz.sss.serv.reg.*;
import io.swagger.annotations.*;
import java.sql.*;
import javax.annotation.*;
import javax.ws.rs.*;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.HttpHeaders;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
@Path("rest/discs")
@Api( value = "discs")
public class SSRESTDisc{
@PostConstruct
public void createRESTResource(){
}
@PreDestroy
public void destroyRESTResource(){
}
@POST
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
@Path("/filtered")
@ApiOperation(
value = "retrieve discussions",
response = SSDiscsGetRet.class)
public Response discsGet(
@Context
final HttpHeaders headers,
final SSDiscsGetRESTPar input){
final SSDiscsGetPar par;
Connection sqlCon = null;
try{
try{
sqlCon = ((SSDBSQLI) SSServReg.getServ(SSDBSQLI.class)).createConnection();
}catch(Exception error){
return SSRESTCommons.prepareErrorResponse(error);
}
try{
par =
new SSDiscsGetPar(
new SSServPar(sqlCon),
null, //user,
input.setEntries, //setEntries,
input.forUser, //forUser,
null, //discs,
null, //target,
true, //withUserRestriction,
true); //invokeEntityHandlers
par.setCircleTypes = input.setCircleTypes;
par.setComments = input.setComments;
par.setLikes = input.setLikes;
par.setTags = input.setTags;
par.setAttachedEntities = input.setAttachedEntities;
par.setReads = input.setReads;
}catch(Exception error){
return Response.status(422).entity(SSRESTCommons.prepareErrorJSON(error)).build();
}
try{
par.key = SSRESTCommons.getBearer(headers);
}catch(Exception error){
return Response.status(401).entity(SSRESTCommons.prepareErrorJSON(error)).build();
}
try{
final SSDiscClientI discServ = (SSDiscClientI) SSServReg.getClientServ(SSDiscClientI.class);
return Response.status(200).entity(discServ.discsGet(SSClientE.rest, par)).build();
}catch(Exception error){
return SSRESTCommons.prepareErrorResponse(error);
}
}finally{
try{
if(sqlCon != null){
sqlCon.close();
}
}catch(Exception error){
SSLogU.err(error);
}
}
}
@POST
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
@ApiOperation(
value = "add a textual comment/answer/opinion to a discussion [for given entity] or create a new discussion",
response = SSDiscEntryAddRet.class)
public Response discEntryAdd(
@Context
final HttpHeaders headers,
final SSDiscEntryAddRESTPar input){
final SSDiscEntryAddPar par;
Connection sqlCon = null;
try{
try{
sqlCon = ((SSDBSQLI) SSServReg.getServ(SSDBSQLI.class)).createConnection();
}catch(Exception error){
return SSRESTCommons.prepareErrorResponse(error);
}
try{
par =
new SSDiscEntryAddFromClientPar(
new SSServPar(sqlCon),
input.disc, //disc
input.targets, //targets,
input.entry, //entry
input.addNewDisc, //addNewDisc
input.type, //type
input.label, //label
input.description, //description
input.users, //users
input.circles, //circles
input.entities, //entities
input.entityLabels); //entityLabels);
}catch(Exception error){
return Response.status(422).entity(SSRESTCommons.prepareErrorJSON(error)).build();
}
try{
par.key = SSRESTCommons.getBearer(headers);
}catch(Exception error){
return Response.status(401).entity(SSRESTCommons.prepareErrorJSON(error)).build();
}
try{
final SSDiscClientI discServ = (SSDiscClientI) SSServReg.getClientServ(SSDiscClientI.class);
return Response.status(200).entity(discServ.discEntryAdd(SSClientE.rest, par)).build();
}catch(Exception error){
return SSRESTCommons.prepareErrorResponse(error);
}
}finally{
try{
if(sqlCon != null){
sqlCon.close();
}
}catch(Exception error){
SSLogU.err(error);
}
}
}
@PUT
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
@Path("/{disc}")
@ApiOperation(
value = "update discussion",
response = SSDiscUpdateRet.class)
public Response discUpdate(
@Context
final HttpHeaders headers,
@PathParam (SSVarNames.disc)
final String disc,
final SSDiscUpdateRESTPar input){
final SSDiscUpdatePar par;
Connection sqlCon = null;
try{
try{
sqlCon = ((SSDBSQLI) SSServReg.getServ(SSDBSQLI.class)).createConnection();
}catch(Exception error){
return SSRESTCommons.prepareErrorResponse(error);
}
try{
par =
new SSDiscUpdatePar(
new SSServPar(sqlCon),
null,
SSUri.get(disc, SSConf.sssUri),
input.label,
input.content,
input.entitiesToRemove,
input.entitiesToAttach,
input.entityLabels,
input.read,
true, //withUserRestriction,
true);//shouldCommit);
}catch(Exception error){
return Response.status(422).entity(SSRESTCommons.prepareErrorJSON(error)).build();
}
try{
par.key = SSRESTCommons.getBearer(headers);
}catch(Exception error){
return Response.status(401).entity(SSRESTCommons.prepareErrorJSON(error)).build();
}
try{
final SSDiscClientI discServ = (SSDiscClientI) SSServReg.getClientServ(SSDiscClientI.class);
return Response.status(200).entity(discServ.discUpdate(SSClientE.rest, par)).build();
}catch(Exception error){
return SSRESTCommons.prepareErrorResponse(error);
}
}finally{
try{
if(sqlCon != null){
sqlCon.close();
}
}catch(Exception error){
SSLogU.err(error);
}
}
}
@PUT
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
@Path("/entries/{entry}")
@ApiOperation(
value = "update a textual comment/answer/opinion of a discussion",
response = SSDiscEntryUpdateRet.class)
public Response discEntryUpdate(
@Context
final HttpHeaders headers,
@PathParam (SSVarNames.entry)
final String entry,
final SSDiscEntryUpdateRESTPar input){
final SSDiscEntryUpdatePar par;
Connection sqlCon = null;
try{
try{
sqlCon = ((SSDBSQLI) SSServReg.getServ(SSDBSQLI.class)).createConnection();
}catch(Exception error){
return SSRESTCommons.prepareErrorResponse(error);
}
try{
par =
new SSDiscEntryUpdatePar(
new SSServPar(sqlCon),
null,
SSUri.get(entry, SSConf.sssUri),
input.content,
input.entitiesToRemove,
input.entitiesToAttach,
input.entityLabels,
true, //withUserRestriction,
true);//shouldCommit);
}catch(Exception error){
return Response.status(422).entity(SSRESTCommons.prepareErrorJSON(error)).build();
}
try{
par.key = SSRESTCommons.getBearer(headers);
}catch(Exception error){
return Response.status(401).entity(SSRESTCommons.prepareErrorJSON(error)).build();
}
try{
final SSDiscClientI discServ = (SSDiscClientI) SSServReg.getClientServ(SSDiscClientI.class);
return Response.status(200).entity(discServ.discEntryUpdate(SSClientE.rest, par)).build();
}catch(Exception error){
return SSRESTCommons.prepareErrorResponse(error);
}
}finally{
try{
if(sqlCon != null){
sqlCon.close();
}
}catch(Exception error){
SSLogU.err(error);
}
}
}
@POST
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
@Path("/filtered/{disc}")
@ApiOperation(
value = "retrieve a discussion with its entries",
response = SSDiscGetRet.class)
public Response discWithEntriesGet(
@Context
final HttpHeaders headers,
@PathParam (SSVarNames.disc)
final String disc,
final SSDiscGetRESTPar input){
final SSDiscGetPar par;
Connection sqlCon = null;
try{
try{
sqlCon = ((SSDBSQLI) SSServReg.getServ(SSDBSQLI.class)).createConnection();
}catch(Exception error){
return SSRESTCommons.prepareErrorResponse(error);
}
try{
par =
new SSDiscGetPar(
new SSServPar(sqlCon),
null, //user
SSUri.get(disc, SSConf.sssUri), //disc
input.setEntries, //setEntries
true, //withUserRestriction
true); //invokeEntityHandlers
par.setCircleTypes = input.setCircleTypes;
par.setComments = input.setComments;
par.setLikes = input.setLikes;
par.setTags = input.setTags;
par.setAttachedEntities = input.setAttachedEntities;
par.setReads = input.setReads;
}catch(Exception error){
return Response.status(422).entity(SSRESTCommons.prepareErrorJSON(error)).build();
}
try{
par.key = SSRESTCommons.getBearer(headers);
}catch(Exception error){
return Response.status(401).entity(SSRESTCommons.prepareErrorJSON(error)).build();
}
try{
final SSDiscClientI discServ = (SSDiscClientI) SSServReg.getClientServ(SSDiscClientI.class);
return Response.status(200).entity(discServ.discGet(SSClientE.rest, par)).build();
}catch(Exception error){
return SSRESTCommons.prepareErrorResponse(error);
}
}finally{
try{
if(sqlCon != null){
sqlCon.close();
}
}catch(Exception error){
SSLogU.err(error);
}
}
}
@GET
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
@Path("/targets/{targets}")
@ApiOperation(
value = "retrieve discussions for certain entities, i.e., targets",
response = SSDiscsGetRet.class)
public Response discsForTargetsGet(
@Context
final HttpHeaders headers,
@PathParam (SSVarNames.targets)
final String targets){
final SSDiscsGetPar par;
Connection sqlCon = null;
try{
try{
sqlCon = ((SSDBSQLI) SSServReg.getServ(SSDBSQLI.class)).createConnection();
}catch(Exception error){
return SSRESTCommons.prepareErrorResponse(error);
}
try{
par =
new SSDiscsGetPar(
new SSServPar(sqlCon),
null, //user
true, //setEntries
null, //forUser
null, //discs
SSUri.get(SSStrU.splitDistinctWithoutEmptyAndNull(targets, SSStrU.comma), SSConf.sssUri), //targets
true, //withUserRestriction
true); //invokeEntityHandlers
}catch(Exception error){
return Response.status(422).entity(SSRESTCommons.prepareErrorJSON(error)).build();
}
try{
par.key = SSRESTCommons.getBearer(headers);
}catch(Exception error){
return Response.status(401).entity(SSRESTCommons.prepareErrorJSON(error)).build();
}
try{
final SSDiscClientI discServ = (SSDiscClientI) SSServReg.getClientServ(SSDiscClientI.class);
return Response.status(200).entity(discServ.discsGet(SSClientE.rest, par)).build();
}catch(Exception error){
return SSRESTCommons.prepareErrorResponse(error);
}
}finally{
try{
if(sqlCon != null){
sqlCon.close();
}
}catch(Exception error){
SSLogU.err(error);
}
}
}
@POST
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
@Path("/filtered/targets/{targets}")
@ApiOperation(
value = "retrieve discussions for certain entities, i.e., targets",
response = SSDiscsGetRet.class)
public Response discsForTargetsFilteredGet(
@Context
final HttpHeaders headers,
@PathParam (SSVarNames.targets)
final String targets,
final SSDiscsForTargetsFilteredGetRESTPar input){
final SSDiscsGetPar par;
Connection sqlCon = null;
try{
try{
sqlCon = ((SSDBSQLI) SSServReg.getServ(SSDBSQLI.class)).createConnection();
}catch(Exception error){
return SSRESTCommons.prepareErrorResponse(error);
}
try{
par =
new SSDiscsGetPar(
new SSServPar(sqlCon),
null, //user
true, //setEntries
input.forUser, //forUser
null, //discs
SSUri.get(SSStrU.splitDistinctWithoutEmptyAndNull(targets, SSStrU.comma), SSConf.sssUri), //targets
true, //withUserRestriction
true); //invokeEntityHandlers
par.setCircleTypes = input.setCircleTypes;
par.setComments = input.setComments;
par.setLikes = input.setLikes;
par.setTags = input.setTags;
par.setAttachedEntities = input.setAttachedEntities;
par.setReads = input.setReads;
}catch(Exception error){
return Response.status(422).entity(SSRESTCommons.prepareErrorJSON(error)).build();
}
try{
par.key = SSRESTCommons.getBearer(headers);
}catch(Exception error){
return Response.status(401).entity(SSRESTCommons.prepareErrorJSON(error)).build();
}
try{
final SSDiscClientI discServ = (SSDiscClientI) SSServReg.getClientServ(SSDiscClientI.class);
return Response.status(200).entity(discServ.discsGet(SSClientE.rest, par)).build();
}catch(Exception error){
return SSRESTCommons.prepareErrorResponse(error);
}
}finally{
try{
if(sqlCon != null){
sqlCon.close();
}
}catch(Exception error){
SSLogU.err(error);
}
}
}
@PUT
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
@Path("/entry/{entry}/accept")
@ApiOperation(
value = "accept a qa answer",
response = SSDiscEntryAcceptRet.class)
public Response discEntryAccept(
@Context
final HttpHeaders headers,
@PathParam (SSVarNames.entry)
final String entry){
final SSDiscEntryAcceptPar par;
Connection sqlCon = null;
try{
try{
sqlCon = ((SSDBSQLI) SSServReg.getServ(SSDBSQLI.class)).createConnection();
}catch(Exception error){
return SSRESTCommons.prepareErrorResponse(error);
}
try{
par =
new SSDiscEntryAcceptPar(
new SSServPar(sqlCon),
null, //user
SSUri.get(entry, SSConf.sssUri), //entry
true, //withUserRestriction,
true); //shouldComit
}catch(Exception error){
return Response.status(422).entity(SSRESTCommons.prepareErrorJSON(error)).build();
}
try{
par.key = SSRESTCommons.getBearer(headers);
}catch(Exception error){
return Response.status(401).entity(SSRESTCommons.prepareErrorJSON(error)).build();
}
try{
final SSDiscClientI discServ = (SSDiscClientI) SSServReg.getClientServ(SSDiscClientI.class);
return Response.status(200).entity(discServ.discEntryAccept(SSClientE.rest, par)).build();
}catch(Exception error){
return SSRESTCommons.prepareErrorResponse(error);
}
}finally{
try{
if(sqlCon != null){
sqlCon.close();
}
}catch(Exception error){
SSLogU.err(error);
}
}
}
@PUT
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
@Path("/{disc}/targets/{targets}")
@ApiOperation(
value = "add targets to a discussion",
response = SSDiscTargetsAddRet.class)
public Response discTargetsAdd(
@Context
final HttpHeaders headers,
@PathParam (SSVarNames.disc)
final String disc,
@PathParam (SSVarNames.targets)
final String targets){
final SSDiscTargetsAddPar par;
Connection sqlCon = null;
try{
try{
sqlCon = ((SSDBSQLI) SSServReg.getServ(SSDBSQLI.class)).createConnection();
}catch(Exception error){
return SSRESTCommons.prepareErrorResponse(error);
}
try{
par =
new SSDiscTargetsAddPar(
new SSServPar(sqlCon),
null, //user,
SSUri.get(disc, SSConf.sssUri),
SSUri.get(SSStrU.splitDistinctWithoutEmptyAndNull(targets, SSStrU.comma), SSConf.sssUri),
true, //withUserRestriction,
true); //shouldCommit
}catch(Exception error){
return Response.status(422).entity(SSRESTCommons.prepareErrorJSON(error)).build();
}
try{
par.key = SSRESTCommons.getBearer(headers);
}catch(Exception error){
return Response.status(401).entity(SSRESTCommons.prepareErrorJSON(error)).build();
}
try{
final SSDiscClientI discServ = (SSDiscClientI) SSServReg.getClientServ(SSDiscClientI.class);
return Response.status(200).entity(discServ.discTargetsAdd(SSClientE.rest, par)).build();
}catch(Exception error){
return SSRESTCommons.prepareErrorResponse(error);
}
}finally{
try{
if(sqlCon != null){
sqlCon.close();
}
}catch(Exception error){
SSLogU.err(error);
}
}
}
}
| |
package Mod.Models;
import org.lwjgl.opengl.GL11;
import net.minecraft.client.model.ModelBase;
import net.minecraft.client.model.ModelRenderer;
import net.minecraft.entity.Entity;
public class TeleporterModel extends ModelBase
{
//fields
ModelRenderer Shape1;
ModelRenderer Shape2;
ModelRenderer Shape3;
ModelRenderer Shape4;
ModelRenderer Shape5;
ModelRenderer Shape6;
ModelRenderer Shape7;
ModelRenderer Shape8;
ModelRenderer PlateUnder;
ModelRenderer MainPlate;
ModelRenderer Shape11;
ModelRenderer Shape12;
ModelRenderer Shape13;
ModelRenderer Shape14;
ModelRenderer Shape9;
ModelRenderer Shape10;
ModelRenderer Shape15;
ModelRenderer Shape16;
ModelRenderer Light;
public TeleporterModel()
{
textureWidth = 64;
textureHeight = 32;
Shape1 = new ModelRenderer(this, 0, 0);
Shape1.addBox(0F, 0F, 0F, 2, 1, 2);
Shape1.setRotationPoint(4F, 23F, -6F);
Shape1.setTextureSize(64, 32);
Shape1.mirror = true;
setRotation(Shape1, 0F, 0F, 0F);
Shape2 = new ModelRenderer(this, 0, 0);
Shape2.addBox(0F, 0F, 0F, 2, 1, 2);
Shape2.setRotationPoint(-6F, 23F, -6F);
Shape2.setTextureSize(64, 32);
Shape2.mirror = true;
setRotation(Shape2, 0F, 0F, 0F);
Shape3 = new ModelRenderer(this, 0, 0);
Shape3.addBox(0F, 0F, 0F, 2, 1, 2);
Shape3.setRotationPoint(-6F, 23F, 4F);
Shape3.setTextureSize(64, 32);
Shape3.mirror = true;
setRotation(Shape3, 0F, 0F, 0F);
Shape4 = new ModelRenderer(this, 0, 0);
Shape4.addBox(0F, 0F, 0F, 2, 1, 2);
Shape4.setRotationPoint(4F, 23F, 4F);
Shape4.setTextureSize(64, 32);
Shape4.mirror = true;
setRotation(Shape4, 0F, 0F, 0F);
Shape5 = new ModelRenderer(this, 0, 0);
Shape5.addBox(0F, 0F, 0F, 2, 2, 2);
Shape5.setRotationPoint(3F, 21F, 3F);
Shape5.setTextureSize(64, 32);
Shape5.mirror = true;
setRotation(Shape5, 0F, 0F, 0F);
Shape6 = new ModelRenderer(this, 0, 0);
Shape6.addBox(0F, 0F, 0F, 2, 2, 2);
Shape6.setRotationPoint(-5F, 21F, -5F);
Shape6.setTextureSize(64, 32);
Shape6.mirror = true;
setRotation(Shape6, 0F, 0F, 0F);
Shape7 = new ModelRenderer(this, 0, 0);
Shape7.addBox(0F, 0F, 0F, 2, 2, 2);
Shape7.setRotationPoint(3F, 21F, -5F);
Shape7.setTextureSize(64, 32);
Shape7.mirror = true;
setRotation(Shape7, 0F, 0F, 0F);
Shape8 = new ModelRenderer(this, 0, 0);
Shape8.addBox(0F, 0F, 0F, 2, 2, 2);
Shape8.setRotationPoint(-5F, 21F, 3F);
Shape8.setTextureSize(64, 32);
Shape8.mirror = true;
setRotation(Shape8, 0F, 0F, 0F);
PlateUnder = new ModelRenderer(this, 0, 4);
PlateUnder.addBox(0F, 0F, 0F, 8, 1, 8);
PlateUnder.setRotationPoint(-4F, 20F, -4F);
PlateUnder.setTextureSize(64, 32);
PlateUnder.mirror = true;
setRotation(PlateUnder, 0F, 0F, 0F);
MainPlate = new ModelRenderer(this, 0, 20);
MainPlate.addBox(0F, 0F, 0F, 10, 2, 10);
MainPlate.setRotationPoint(-5F, 18F, -5F);
MainPlate.setTextureSize(64, 32);
MainPlate.mirror = true;
setRotation(MainPlate, 0F, 0F, 0F);
Shape11 = new ModelRenderer(this, 42, 19);
Shape11.addBox(0F, 0F, 0F, 10, 3, 1);
Shape11.setRotationPoint(-5F, 17F, -6F);
Shape11.setTextureSize(64, 32);
Shape11.mirror = true;
setRotation(Shape11, 0F, 0F, 0F);
Shape12 = new ModelRenderer(this, 42, 19);
Shape12.addBox(0F, 0F, 0F, 1, 3, 10);
Shape12.setRotationPoint(-6F, 17F, -5F);
Shape12.setTextureSize(64, 32);
Shape12.mirror = true;
setRotation(Shape12, 0F, 0F, 0F);
Shape13 = new ModelRenderer(this, 42, 19);
Shape13.addBox(0F, 0F, 0F, 1, 3, 10);
Shape13.setRotationPoint(5F, 17F, -5F);
Shape13.setTextureSize(64, 32);
Shape13.mirror = true;
setRotation(Shape13, 0F, 0F, 0F);
Shape14 = new ModelRenderer(this, 42, 19);
Shape14.addBox(0F, 0F, 0F, 10, 3, 1);
Shape14.setRotationPoint(-5F, 17F, 5F);
Shape14.setTextureSize(64, 32);
Shape14.mirror = true;
setRotation(Shape14, 0F, 0F, 0F);
Shape9 = new ModelRenderer(this, 19, 0);
Shape9.addBox(0F, 0F, 0F, 4, 1, 1);
Shape9.setRotationPoint(1F, 17F, 4F);
Shape9.setTextureSize(64, 32);
Shape9.mirror = true;
setRotation(Shape9, -0.2974289F, 0F, 0F);
Shape10 = new ModelRenderer(this, 29, 0);
Shape10.addBox(0F, 0F, 0F, 1, 3, 1);
Shape10.setRotationPoint(1F, 14.2F, 5F);
Shape10.setTextureSize(64, 32);
Shape10.mirror = true;
setRotation(Shape10, -0.3346083F, 0F, 0F);
Shape15 = new ModelRenderer(this, 29, 0);
Shape15.addBox(0F, 0F, 0F, 1, 3, 1);
Shape15.setRotationPoint(4F, 14.2F, 5F);
Shape15.setTextureSize(64, 32);
Shape15.mirror = true;
setRotation(Shape15, -0.3346083F, 0F, 0F);
Shape16 = new ModelRenderer(this, 19, 0);
Shape16.addBox(0F, 0F, 0F, 4, 1, 1);
Shape16.setRotationPoint(1F, 13.3F, 5.3F);
Shape16.setTextureSize(64, 32);
Shape16.mirror = true;
setRotation(Shape16, -0.3346075F, 0F, 0F);
Light = new ModelRenderer(this, 35, 0);
Light.addBox(0F, 0F, 0F, 2, 3, 1);
Light.setRotationPoint(2F, 14.2F, 5F);
Light.setTextureSize(64, 32);
Light.mirror = true;
setRotation(Light, -0.3346145F, 0F, 0F);
}
public void render(Entity entity, float f, float f1, float f2, float f3, float f4, float f5, int Mode)
{
super.render(entity, f, f1, f2, f3, f4, f5);
setRotationAngles(f, f1, f2, f3, f4, f5, entity);
Shape1.render(f5);
Shape2.render(f5);
Shape3.render(f5);
Shape4.render(f5);
Shape5.render(f5);
Shape6.render(f5);
Shape7.render(f5);
Shape8.render(f5);
PlateUnder.render(f5);
MainPlate.render(f5);
Shape11.render(f5);
Shape12.render(f5);
Shape13.render(f5);
Shape14.render(f5);
Shape9.render(f5);
Shape10.render(f5);
Shape15.render(f5);
Shape16.render(f5);
if(Mode == 1){
GL11.glColor4f(0.0F, 1.0F, 0.0F, 1.0F);
}else if (Mode == 2){
GL11.glColor4f(0.0F, 0.0F, 1.0F, 1.0F);
}else{
GL11.glColor4f(1.0F, 0.0F, 0.0F, 1.0F);
}
Light.render(f5);
}
private void setRotation(ModelRenderer model, float x, float y, float z)
{
model.rotateAngleX = x;
model.rotateAngleY = y;
model.rotateAngleZ = z;
}
public void setRotationAngles(float f, float f1, float f2, float f3, float f4, float f5, Entity entity)
{
super.setRotationAngles(f, f1, f2, f3, f4, f5, entity);
}
}
| |
// AtlantisEngine.java - Copyright (C) Yannick Comte.
// This file is subject to the terms and conditions defined in
// file 'LICENSE', which is part of this source code package.
package atlantis.framework;
/**
* A matrix 4x4
* Some methods has been ported from the open source project SharpDX.
* Check this project here : https://github.com/sharpdx/SharpDX
* @author Yannick
*/
public class Matrix {
public float M11;
public float M12;
public float M13;
public float M14;
public float M21;
public float M22;
public float M23;
public float M24;
public float M31;
public float M32;
public float M33;
public float M34;
public float M41;
public float M42;
public float M43;
public float M44;
/**
* Create an empty matrix with all field at 0.0f.
*/
public Matrix() {
float[] values = {
0.0f, 0.0f, 0.0f, 0.0f,
0.0f, 0.0f, 0.0f, 0.0f,
0.0f, 0.0f, 0.0f, 0.0f,
0.0f, 0.0f, 0.0f, 0.0f
};
this.set(values);
}
/**
* Create a matrix with an existing matrix. Values are copied.
* @param matrix A matrix.
*/
public Matrix(Matrix matrix) {
this.set(matrix.toArray());
}
/**
* Create a matrix with an array of 16 values.
* @param values An array of 16 float values.
* @throws Exception Thrown if the array hasn't 16 values.
*/
public Matrix(float[] values) throws Exception {
if (values.length != 16) {
throw new Exception("The array of values must contains 16 float values");
}
this.set(values);
}
/**
* Set all values of the matrix
* @param values An array of 16 values who start at M11 and stop at M44
*/
public void set(float [] values) {
if (values.length == 16) {
this.M11 = values[0]; this.M12 = values[1]; this.M13 = values[2]; this.M14 = values[3];
this.M21 = values[4]; this.M22 = values[5]; this.M23 = values[6]; this.M24 = values[7];
this.M31 = values[8]; this.M32 = values[9]; this.M33 = values[10]; this.M34 = values[11];
this.M41 = values[12]; this.M42 = values[13]; this.M43 = values[14]; this.M44 = values[15];
}
}
// ---
// --- Getters and setters
// ---
/**
* Sets the matrix to identity
*/
public void setIdentity () {
set(getIdentityValues());
}
/**
* Gets identity value for push it into matrix.
* @return Return an array that correspond of identity matrix.
*/
public float[] getIdentityValues() {
float [] values = {
1, 0, 0, 0,
0, 1, 0, 0,
0, 0, 1, 0,
0, 0, 0, 1
};
return values;
}
/**
* Gets an array of values setted to 0.
* @return
*/
public float[] getZeroValues() {
float[] values = new float[16];
for (int i = 0; i < 16; i++) {
values[i] = 0.0f;
}
return values;
}
/**
* Gets an identity matrix.
* @return Return an identity matrix.
*/
public static Matrix getMatrixIdentity() {
Matrix matrix = new Matrix();
matrix.setIdentity();
return matrix;
}
/**
* Sets the left of the matrix.
* @param vector
*/
public void setLeft(Vector3 vector) {
this.M11 = -vector.x;
this.M12 = -vector.y;
this.M13 = -vector.z;
}
/**
* Gets the left of the matrix.
* @return Return a the left vector of the matrix.
*/
public Vector3 getLeft() {
Vector3 vector = new Vector3();
vector.x = -this.M11;
vector.y = -this.M12;
vector.z = -this.M13;
return vector;
}
/**
* Sets the right of the matrix.
* @param vector
*/
public void setRight(Vector3 vector) {
this.M11 = vector.x;
this.M12 = vector.y;
this.M13 = vector.z;
}
/**
* Gets the right of the matrix.
* @return Return a the right vector of the matrix.
*/
public Vector3 getRight() {
Vector3 vector = new Vector3();
vector.x = this.M11;
vector.y = this.M12;
vector.z = this.M13;
return vector;
}
/**
* Sets the up of the matrix.
* @param vector
*/
public void setUp(Vector3 vector) {
this.M21 = vector.x;
this.M22 = vector.y;
this.M23 = vector.z;
}
/**
* Gets the up of the matrix.
* @return Return a the up vector of the matrix.
*/
public Vector3 getUp() {
Vector3 vector = new Vector3();
vector.x = this.M21;
vector.y = this.M22;
vector.z = this.M23;
return vector;
}
/**
* Sets the down of the matrix.
* @param vector
*/
public void setDown(Vector3 vector) {
this.M21 = -vector.x;
this.M22 = -vector.y;
this.M23 = -vector.z;
}
/**
* Gets the down of the matrix.
* @return Return a the down vector of the matrix.
*/
public Vector3 getDown() {
Vector3 vector = new Vector3();
vector.x = -this.M21;
vector.y = -this.M22;
vector.z = -this.M23;
return vector;
}
/**
* Sets the backward of the matrix.
* @param vector
*/
public void setBackward(Vector3 vector) {
this.M31 = vector.x;
this.M32 = vector.y;
this.M33 = vector.z;
}
/**
* Gets the backward of the matrix.
* @return Return a the backward vector of the matrix.
*/
public Vector3 getBackward() {
Vector3 vector = new Vector3();
vector.x = this.M31;
vector.y = this.M32;
vector.z = this.M33;
return vector;
}
/**
* Sets the forward of the matrix.
* @param vector
*/
public void setForward(Vector3 vector) {
this.M31 = -vector.x;
this.M32 = -vector.y;
this.M33 = -vector.z;
}
/**
* Gets the forward of the matrix.
* @return Return a the forward vector of the matrix.
*/
public Vector3 getForward() {
Vector3 vector = new Vector3();
vector.x = -this.M31;
vector.y = -this.M32;
vector.z = -this.M33;
return vector;
}
/**
* Sets translation
* @param position The position to set.
*/
public void setTranslation(Vector3 position) {
this.M41 = position.x;
this.M42 = position.y;
this.M43 = position.z;
}
public Vector3 getTranslation() {
Vector3 vector = new Vector3();
vector.x = M41;
vector.y = M42;
vector.z = M43;
return vector;
}
public void setScale(Vector3 scale) {
this.M11 = scale.x;
this.M22 = scale.y;
this.M33 = scale.z;
}
public Vector3 getScale() {
Vector3 vector = new Vector3();
vector.x = this.M11;
vector.y = this.M22;
vector.z = this.M33;
return vector;
}
/**
* Gets values of matrix in array. Start at M11 to M44.
* @return An array of values.
*/
public float[] toArray() {
float[] values =
{
M11, M12, M13, M14,
M21, M22, M23, M24,
M31, M32, M33, M34,
M41, M42, M43, M44,
};
return values;
}
// ---
// --- Methods declaration
// ---
/**
* Add a matrix to this matrix.
* @param matrix A matrix to add.
*/
public void add(Matrix matrix) {
float [] mValues = this.toArray();
float [] eValues = matrix.toArray();
for(int i = 0; i < 16; i++) {
mValues[i] += eValues[i];
}
this.set(mValues);
}
/**
* Add two matrix.
* @param matA A matrix
* @param matB Another matrix to add with the first
* @return Return a new matrix.
*/
public static Matrix add(Matrix matA, Matrix matB) {
Matrix matrix = new Matrix(matA);
matrix.add(matB);
return matrix;
}
public static Matrix createFromQuaternion(Quaternion quaternion) {
Matrix result = Matrix.getMatrixIdentity();
float xx = quaternion.x * quaternion.x;
float yy = quaternion.y * quaternion.y;
float zz = quaternion.z * quaternion.z;
float xy = quaternion.x * quaternion.y;
float zw = quaternion.z * quaternion.w;
float zx = quaternion.z * quaternion.x;
float yw = quaternion.y * quaternion.w;
float yz = quaternion.y * quaternion.z;
float xw = quaternion.x * quaternion.w;
result.M11 = 1.0f - (2.0f * (yy + zz));
result.M12 = 2.0f * (xy + zw);
result.M13 = 2.0f * (zx - yw);
result.M21 = 2.0f * (xy - zw);
result.M22 = 1.0f - (2.0f * (zz + xx));
result.M23 = 2.0f * (yz + xw);
result.M31 = 2.0f * (zx + yw);
result.M32 = 2.0f * (yz - xw);
result.M33 = 1.0f - (2.0f * (yy + xx));
return result;
}
/**
* Create a rotation matrix on X axis.
* @param rotation An angle in radians
* @return Return a rotation matrix on X axis.
*/
public static Matrix createRotationX(float rotation) {
Matrix matrix = getMatrixIdentity();
float cos = (float)Math.cos(rotation);
float sin = (float)Math.sin(rotation);
matrix.M22 = cos;
matrix.M23 = sin;
matrix.M32 = -sin;
matrix.M33 = cos;
return matrix;
}
/**
* Create a rotation matrix on Y axis.
* @param rotation An angle in radians
* @return Return a rotation matrix on Y axis.
*/
public static Matrix createRotationY(float rotation) {
Matrix matrix = getMatrixIdentity();
float cos = (float)Math.cos(rotation);
float sin = (float)Math.sin(rotation);
matrix.M11 = cos;
matrix.M13 = -sin;
matrix.M31 = sin;
matrix.M33 = cos;
return matrix;
}
/**
* Create a rotation matrix on Z axis.
* @param rotation An angle in radians
* @return Return a rotation matrix on Z axis.
*/
public static Matrix createRotationZ(float rotation) {
Matrix matrix = getMatrixIdentity();
float cos = (float)Math.cos(rotation);
float sin = (float)Math.sin(rotation);
matrix.M11 = cos;
matrix.M13 = sin;
matrix.M31 = -sin;
matrix.M33 = cos;
return matrix;
}
/**
* Create a rotation matrix from a quaternion
* @param quaternion A quaternion to use
* @return Return a rotation matrix.
*/
public static Matrix createRotationFromQuaternion(Quaternion quaternion) {
Matrix result = new Matrix();
result.setIdentity();
float xx = quaternion.x * quaternion.x;
float yy = quaternion.y * quaternion.y;
float zz = quaternion.z * quaternion.z;
float xy = quaternion.x * quaternion.y;
float zw = quaternion.z * quaternion.w;
float zx = quaternion.z * quaternion.x;
float yw = quaternion.y * quaternion.w;
float yz = quaternion.y * quaternion.z;
float xw = quaternion.x * quaternion.w;
result.M11 = 1.0f - (2.0f * (yy + zz));
result.M12 = 2.0f * (xy + zw);
result.M13 = 2.0f * (zx - yw);
result.M21 = 2.0f * (xy - zw);
result.M22 = 1.0f - (2.0f * (zz + xx));
result.M23 = 2.0f * (yz + xw);
result.M31 = 2.0f * (zx + yw);
result.M32 = 2.0f * (yz - xw);
result.M33 = 1.0f - (2.0f * (yy + xx));
return result;
}
/**
* Create a rotation matrix with three rotations.
* @param yaw
* @param pitch
* @param roll
* @return
*/
public static Matrix createRotationYawPitchRoll(float yaw, float pitch, float roll) {
Quaternion quaternion = Quaternion.createFromYawPitchRoll(yaw, pitch, roll);
return createRotationFromQuaternion(quaternion);
}
/**
* Create a scale matrix.
* @param scale Scale to use.
* @return Return a scale matrix.
*/
public static Matrix createScale(float scale) {
return createScale(scale, scale, scale);
}
/**
* Create a scale matrix.
* @param scale Scale to use.
* @return Return a scale matrix.
*/
public static Matrix createScale(Vector3 scale) {
return createScale(scale.x, scale.y, scale.z);
}
/**
* Create a scale matrix.
* @param sx Desired scale on X axis.
* @param sy Desired scale on Y axis.
* @param sz Desired scale on Z axis.
* @return Return a scale matrix.
*/
public static Matrix createScale(float sx, float sy, float sz) {
Matrix matrix = getMatrixIdentity();
matrix.M11 = sx;
matrix.M22 = sy;
matrix.M33 = sz;
return matrix;
}
/**
* Create a translation matrix.
* @param x Position on X axis.
* @param y Position on Y axis.
* @param z Position on Z axis.
* @return Return a matrix translation.
*/
public static Matrix createTranslation(float x, float y, float z) {
Matrix matrix = getMatrixIdentity();
matrix.M41 = x;
matrix.M42 = y;
matrix.M43 = z;
return matrix;
}
/**
* Create a translation matrix.
* @param vector A vector to use for translation.
* @return Return a matrix translation.
*/
public static Matrix createTranslation(Vector3 vector) {
return createTranslation(vector.x, vector.y, vector.z);
}
/**
* Create a world matrix.
* @param position
* @param forward
* @param upVector
* @return Return a world matrix.
*/
public static Matrix createWorld(Vector3 position, Vector3 forward, Vector3 upVector) {
Matrix matrix = new Matrix();
Vector3 x = Vector3.cross(forward, upVector);
Vector3 y = Vector3.cross(x, forward);
Vector3 z = Vector3.normalize(forward);
x.normalize();
y.normalize();
matrix.setRight(x);
matrix.setUp(y);
matrix.setForward(z);
matrix.setTranslation(position);
matrix.M44 = 1.0f;
return matrix;
}
/**
* Create a view matrix
* @param position The position of the camera.
* @param target The target of the camera.
* @param upVector Vector up
* @return Return a view camera.
*/
public static Matrix createLookAt(Vector3 position, Vector3 target, Vector3 upVector) {
Vector3 zAxis = Vector3.subtract(target, position);
zAxis.normalize();
Vector3 xAxis = Vector3.cross(upVector, zAxis);
xAxis.normalize();
Vector3 yAxis = Vector3.cross(zAxis, xAxis);
yAxis.normalize();
Matrix matrix = getMatrixIdentity();
matrix.M11 = xAxis.x;
matrix.M21 = xAxis.y;
matrix.M31 = xAxis.z;
matrix.M12 = yAxis.x;
matrix.M22 = yAxis.y;
matrix.M32 = yAxis.z;
matrix.M13 = zAxis.x;
matrix.M23 = zAxis.y;
matrix.M33 = zAxis.z;
matrix.M41 = -Vector3.dot(xAxis, position);
matrix.M42 = -Vector3.dot(yAxis, position);
matrix.M43 = -Vector3.dot(zAxis, position);
return matrix;
}
/**
* Create an orthogonal projection matrix.
* @param width
* @param height
* @param zNear
* @param zFar
* @return
*/
public static Matrix createOrthographic(float width, float height, float zNear, float zFar) {
Matrix matrix = new Matrix();
matrix.M11 = 2.0f / width;
matrix.M12 = matrix.M13 = matrix.M14 = 0.0f;
matrix.M22 = 2.0f / height;
matrix.M21 = matrix.M23 = matrix.M24 = 0.0f;
matrix.M33 = 1.0f / (zNear - zFar);
matrix.M31 = matrix.M32 = matrix.M34 = 0.0f;
matrix.M41 = matrix.M42 = 0.0f;
matrix.M43 = zNear / (zNear - zFar);
matrix.M44 = 1.0f;
return matrix;
}
/**
* Create a customized orthogonal projection matrix.
* @param width
* @param height
* @param zNear
* @param zFar
* @return
*/
public static Matrix createOrthographicOffCenter(float left, float right, float bottom, float top, float zNear, float zFar) {
Matrix matrix = new Matrix();
matrix.M11 = (float)(2.0 / ((double)right - (double)left));
matrix.M12 = 0.0f;
matrix.M13 = 0.0f;
matrix.M14 = 0.0f;
matrix.M21 = 0.0f;
matrix.M22 = (float)(2.0 / ((double)top - (double)bottom));
matrix.M23 = 0.0f;
matrix.M24 = 0.0f;
matrix.M31 = 0.0f;
matrix.M32 = 0.0f;
matrix.M33 = (float)(1.0 / ((double)zNear - (double)zFar));
matrix.M34 = 0.0f;
matrix.M41 = (float)(((double)left + (double)right) / ((double)left - (double)right));
matrix.M42 = (float)(((double)top + (double)bottom) / ((double)bottom - (double)top));
matrix.M43 = (float)((double)zNear / ((double)zNear - (double)zFar));
matrix.M44 = 1.0f;
return matrix;
};
/**
* Create a perspective field of view matrix with Left hand notation.
* @param fov Desired field of view (Math.PI / 4 is a good value)
* @param aspect Desired aspect ratio (Screen width / height)
* @param near Near clip
* @param far Far clip
* @return Return a matrix of this type of perspective.
*/
public static Matrix createPerspectiveFieldOfView(float fov, float aspect, float zNear, float zFar) {
float yScale = (float)(1.0f / Math.tan(fov * 0.5f));
float xScale = yScale / aspect;
float halfWidth = zNear / xScale;
float halfHeight = zNear / yScale;
return createPerspectiveOffCenter(-halfWidth, halfWidth, -halfHeight, halfHeight, zNear, zFar);
}
/**
* Create a perspective field of view matrix with Right hand notation.
* @param fov Desired field of view (Math.PI / 4 is a good value)
* @param aspect Desired aspect ratio (Screen width / height)
* @param near Near clip
* @param far Far clip
* @return Return a matrix of this type of perspective.
*/
public static Matrix createPerspectiveFieldOfViewRH(float fov, float aspect, float zNear, float zFar) {
float yScale = (float)(1.0f / Math.tan(fov * 0.5f));
float xScale = yScale / aspect;
float halfWidth = zNear / xScale;
float halfHeight = zNear / yScale;
return createPerspectiveOffCenterRH(-halfWidth, halfWidth, -halfHeight, halfHeight, zNear, zFar);
}
/**
* Create a custom perspective matrix.
* @param left Minimum X value of the viewing volume.
* @param right Maximum X value of the viewing volume.
* @param bottom Minimum Y value of the viewing volume.
* @param top Maximum Y value of the viewing volume.
* @param zNear Minimum Z value of the viewing volume.
* @param zFar Maximum Z value of the viewing volume.
* @return Return a new custom perspective matrix.
*/
public static Matrix createPerspectiveOffCenter(float left, float right, float bottom, float top, float zNear, float zFar) {
float zRange = zFar / (zFar - zNear);
Matrix matrix = new Matrix();
matrix.M11 = 2.0f * zNear / (right - left);
matrix.M22 = 2.0f * zNear / (top - bottom);
matrix.M31 = (left + right) / (left - right);
matrix.M32 = (top + bottom) / (bottom - top);
matrix.M33 = zRange;
matrix.M34 = 1.0f;
matrix.M43 = -zNear * zRange;
return matrix;
}
public static Matrix createPerspectiveOffCenterRH(float left, float right, float bottom, float top, float zNear, float zFar) {
Matrix matrix = createPerspectiveOffCenter(left, right, bottom, top, zNear, zFar);
matrix.M31 *= -1.0f;
matrix.M32 *= -1.0f;
matrix.M33 *= -1.0f;
matrix.M34 *= -1.0f;
return matrix;
}
/**
* Invert the current Matrix.
*/
public void invert() {
float b0 = (this.M31 * this.M42) - (this.M32 * this.M41);
float b1 = (this.M31 * this.M43) - (this.M33 * this.M41);
float b2 = (this.M34 * this.M41) - (this.M31 * this.M44);
float b3 = (this.M32 * this.M43) - (this.M33 * this.M42);
float b4 = (this.M34 * this.M42) - (this.M32 * this.M44);
float b5 = (this.M33 * this.M44) - (this.M34 * this.M43);
float d11 = this.M22 * b5 + this.M23 * b4 + this.M24 * b3;
float d12 = this.M21 * b5 + this.M23 * b2 + this.M24 * b1;
float d13 = this.M21 * -b4 + this.M22 * b2 + this.M24 * b0;
float d14 = this.M21 * b3 + this.M22 * -b1 + this.M23 * b0;
float det = this.M11 * d11 - this.M12 * d12 + this.M13 * d13 - this.M14 * d14;
if (Math.abs(det) == 0.0f) {
this.set(this.getZeroValues());
return;
}
det = 1.0f / det;
float a0 = (this.M11 * this.M22) - (this.M12 * this.M21);
float a1 = (this.M11 * this.M23) - (this.M13 * this.M21);
float a2 = (this.M14 * this.M21) - (this.M11 * this.M24);
float a3 = (this.M12 * this.M23) - (this.M13 * this.M22);
float a4 = (this.M14 * this.M22) - (this.M12 * this.M24);
float a5 = (this.M13 * this.M24) - (this.M14 * this.M23);
float d21 = this.M12 * b5 + this.M13 * b4 + this.M14 * b3;
float d22 = this.M11 * b5 + this.M13 * b2 + this.M14 * b1;
float d23 = this.M11 * -b4 + this.M12 * b2 + this.M14 * b0;
float d24 = this.M11 * b3 + this.M12 * -b1 + this.M13 * b0;
float d31 = this.M42 * a5 + this.M43 * a4 + this.M44 * a3;
float d32 = this.M41 * a5 + this.M43 * a2 + this.M44 * a1;
float d33 = this.M41 * -a4 + this.M42 * a2 + this.M44 * a0;
float d34 = this.M41 * a3 + this.M42 * -a1 + this.M43 * a0;
float d41 = this.M32 * a5 + this.M33 * a4 + this.M34 * a3;
float d42 = this.M31 * a5 + this.M33 * a2 + this.M34 * a1;
float d43 = this.M31 * -a4 + this.M32 * a2 + this.M34 * a0;
float d44 = this.M31 * a3 + this.M32 * -a1 + this.M33 * a0;
this.M11 = +d11 * det; this.M12 = -d21 * det; this.M13 = +d31 * det; this.M14 = -d41 * det;
this.M21 = -d12 * det; this.M22 = +d22 * det; this.M23 = -d32 * det; this.M24 = +d42 * det;
this.M31 = +d13 * det; this.M32 = -d23 * det; this.M33 = +d33 * det; this.M34 = -d43 * det;
this.M41 = -d14 * det; this.M42 = +d24 * det; this.M43 = -d34 * det; this.M44 = +d44 * det;
}
/**
* Calculate the inverse of the specified matrix.
* @param matrix The matrix to use.
* @return Return the inverse of the matrix.
*/
public static Matrix invert(Matrix matrix) {
Matrix mat = new Matrix(matrix);
mat.invert();
return mat;
}
/**
* Multiply this matrix by another matrix.
* @param matrix A matrix to multiply.
*/
public void multiply(Matrix matrix) {
float m11 = (((this.M11 * matrix.M11) + (this.M12 * matrix.M21)) + (this.M13 * matrix.M31)) + (this.M14 * matrix.M41);
float m12 = (((this.M11 * matrix.M12) + (this.M12 * matrix.M22)) + (this.M13 * matrix.M32)) + (this.M14 * matrix.M42);
float m13 = (((this.M11 * matrix.M13) + (this.M12 * matrix.M23)) + (this.M13 * matrix.M33)) + (this.M14 * matrix.M43);
float m14 = (((this.M11 * matrix.M14) + (this.M12 * matrix.M24)) + (this.M13 * matrix.M34)) + (this.M14 * matrix.M44);
float m21 = (((this.M21 * matrix.M11) + (this.M22 * matrix.M21)) + (this.M23 * matrix.M31)) + (this.M24 * matrix.M41);
float m22 = (((this.M21 * matrix.M12) + (this.M22 * matrix.M22)) + (this.M23 * matrix.M32)) + (this.M24 * matrix.M42);
float m23 = (((this.M21 * matrix.M13) + (this.M22 * matrix.M23)) + (this.M23 * matrix.M33)) + (this.M24 * matrix.M43);
float m24 = (((this.M21 * matrix.M14) + (this.M22 * matrix.M24)) + (this.M23 * matrix.M34)) + (this.M24 * matrix.M44);
float m31 = (((this.M31 * matrix.M11) + (this.M32 * matrix.M21)) + (this.M33 * matrix.M31)) + (this.M34 * matrix.M41);
float m32 = (((this.M31 * matrix.M12) + (this.M32 * matrix.M22)) + (this.M33 * matrix.M32)) + (this.M34 * matrix.M42);
float m33 = (((this.M31 * matrix.M13) + (this.M32 * matrix.M23)) + (this.M33 * matrix.M33)) + (this.M34 * matrix.M43);
float m34 = (((this.M31 * matrix.M14) + (this.M32 * matrix.M24)) + (this.M33 * matrix.M34)) + (this.M34 * matrix.M44);
float m41 = (((this.M41 * matrix.M11) + (this.M42 * matrix.M21)) + (this.M43 * matrix.M31)) + (this.M44 * matrix.M41);
float m42 = (((this.M41 * matrix.M12) + (this.M42 * matrix.M22)) + (this.M43 * matrix.M32)) + (this.M44 * matrix.M42);
float m43 = (((this.M41 * matrix.M13) + (this.M42 * matrix.M23)) + (this.M43 * matrix.M33)) + (this.M44 * matrix.M43);
float m44 = (((this.M41 * matrix.M14) + (this.M42 * matrix.M24)) + (this.M43 * matrix.M34)) + (this.M44 * matrix.M44);
this.M11 = m11;
this.M12 = m12;
this.M13 = m13;
this.M14 = m14;
this.M21 = m21;
this.M22 = m22;
this.M23 = m23;
this.M24 = m24;
this.M31 = m31;
this.M32 = m32;
this.M33 = m33;
this.M34 = m34;
this.M41 = m41;
this.M42 = m42;
this.M43 = m43;
this.M44 = m44;
}
/**
* Multiply a two matrix.
* @param matrixA A matrix.
* @param matrixB Another matrix.
* @return Return a new matrix.
*/
public static Matrix multiply(Matrix matrixA, Matrix matrixB) {
Matrix matrix = new Matrix(matrixA);
matrix.multiply(matrixB);
return matrix;
}
/**
* Multiply three matrix.
* @param matrixA
* @param matrixB
* @param matrixC
* @return A new matrix.
*/
public static Matrix multiply(Matrix matrixA, Matrix matrixB, Matrix matrixC) {
Matrix multMatrix = new Matrix(matrixA);
multMatrix.multiply(matrixB);
multMatrix.multiply(matrixC);
return multMatrix;
}
/**
* Subtract a matrix to this matrix.
* @param matrix A matrix to add.
*/
public void subtract(Matrix matrix) {
float [] mValues = this.toArray();
float [] eValues = matrix.toArray();
for(int i = 0; i < 16; i++) {
mValues[i] -= eValues[i];
}
this.set(mValues);
}
/**
* Subtract two matrix.
* @param matA A matrix.
* @param matB Another matrix to use to subtract with the first matrix.
* @return Return a new matrix.
*/
public static Matrix subtract(Matrix matA, Matrix matB) {
Matrix mat = new Matrix(matA);
mat.subtract(matB);
return mat;
}
public String toString() {
float[] values = this.toArray();
StringBuilder builder = new StringBuilder();
for (int i = 0; i < 16; i += 4) {
builder.append("[");
builder.append(values[i] + " ");
builder.append(values[i + 1] + " ");
builder.append(values[i + 2] + " ");
builder.append(values[i + 3]);
builder.append("] ");
}
return builder.toString();
}
}
| |
package com.deguet.gutils.permutation;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
/**
* Helps represent a set of positive Integer with one using the uniqueness of prime decomposition.
* 4 ::: [0, 2] as 1^0 * 2^2
* 3 ::: [0, 0, 1] as 1^0 * 2^0 * 3^1
* 2 ::: [0, 1]
* 1 ::: [1]
* 0 ::: []
* each number in the array corresponds to the exponent of the corresponding prime number
*
* @author joris
*
*/
public class PrimeBase {
public int[] to(long source){
//System.out.println("====================================== "+source);
if (source == 0) return new int[]{};
if (source == 1) return new int[]{1};
long n = source;
List<Integer> factors = new ArrayList<Integer>();
for (int i = 2; i <= n; i++) {
while (n % i == 0) {
factors.add(i);
n = n / i;
}
}
//System.out.println("List " + factors);
int maxFactor = Collections.max(factors).intValue();
int size = primeIndex(maxFactor);
//System.out.println("size " + size);
int[] result = new int[size];
for (int f = 0 ; f < size ; f++){
int prime = nthPrime(f+1);
//System.out.println("Prime is "+prime);
result[f] = Collections.frequency(factors, prime);
}
return result;
}
private int primeIndex(int prime){
if (!isPrime(prime)) throw new IllegalArgumentException();
if (prime == 1) return 1;
if (prime == 2) return 2;
int i = 0 ;
while(true){
int p = nthPrime(i);
if (prime == p) return i;
i++;
}
}
/**
* Converts a prime base code (exponents for given positions) into its long value.
*/
public long from(int[] digits){
if (digits.length == 0 ) return 0;
if (Arrays.equals(digits, new int[]{1})) return 1;
long result = 1;
for (int i = 0; i < digits.length; i++) {
int prime = nthPrime(i+1);
int expon = (int)digits[i];
//System.out.println("Res " + result +" prime " + prime+" exp " +expon);
result *= Math.pow(prime, expon);
}
return result;
}
// Count number of set bits in an int
private static int popCount(int n) {
n -= (n >>> 1) & 0x55555555;
n = ((n >>> 2) & 0x33333333) + (n & 0x33333333);
n = ((n >> 4) & 0x0F0F0F0F) + (n & 0x0F0F0F0F);
return (n * 0x01010101) >> 24;
}
private int nthPrime(int n){
if (n==1) return 1;
if (n==2) return 2;
return nthprime(n-1);
}
/**
* https://bitbucket.org/dafis/javaprimes
* @param n
* @return
*/
private int nthprime(int n) {
if (n < 2) return 2;
if (n == 2) return 3;
if (n == 3) return 5;
int limit, root, count = 2;
limit = (int)(n*(Math.log(n) + Math.log(Math.log(n)))) + 3;
root = (int)Math.sqrt(limit);
switch(limit%6) {
case 0:
limit = 2*(limit/6) - 1;
break;
case 5:
limit = 2*(limit/6) + 1;
break;
default:
limit = 2*(limit/6);
}
switch(root%6) {
case 0:
root = 2*(root/6) - 1;
break;
case 5:
root = 2*(root/6) + 1;
break;
default:
root = 2*(root/6);
}
int dim = (limit+31) >> 5;
int[] sieve = new int[dim];
for(int i = 0; i < root; ++i) {
if ((sieve[i >> 5] & (1 << (i&31))) == 0) {
int start, s1, s2;
if ((i & 1) == 1) {
start = i*(3*i+8)+4;
s1 = 4*i+5;
s2 = 2*i+3;
} else {
start = i*(3*i+10)+7;
s1 = 2*i+3;
s2 = 4*i+7;
}
for(int j = start; j < limit; j += s2) {
sieve[j >> 5] |= 1 << (j&31);
j += s1;
if (j >= limit) break;
sieve[j >> 5] |= 1 << (j&31);
}
}
}
int i;
for(i = 0; count < n; ++i) {
count += popCount(~sieve[i]);
}
--i;
int mask = ~sieve[i];
int p;
for(p = 31; count >= n; --p) {
count -= (mask >> p) & 1;
}
return 3*(p+(i<<5))+7+(p&1);
}
private static final int[] TEST_BASE = { 2, 7, 61 };
private static final int NUM_BASES = 3;
private static boolean isPrime(int n) {
if ((n & 1) == 0) return n == 2;
if (n % 3 == 0) return n == 3;
int step = 4, m;
boolean onlyTD;
if (n < 40000) {
m = (int)Math.sqrt(n) + 1;
onlyTD = true;
} else {
m = 100;
onlyTD = false;
}
for(int i = 5; i < m; step = 6-step, i += step) {
if (n % i == 0) {
return false;
}
}
if (onlyTD) {
return true;
}
long md = n, n1 = n-1, exp = n-1;
int s = 0;
do {
++s;
exp >>= 1;
}while((exp & 1) == 0);
// now n-1 = 2^s * exp
for(int i = 0; i < NUM_BASES; ++i) {
long r = modPow(TEST_BASE[i],exp,md);
if (r == 1) continue;
int j;
for(j = s; j > 0; --j){
if (r == n1) break;
r = (r * r) % md;
}
if (j == 0) return false;
}
return true;
}
private static long modPow(long base, long exponent, long modulus) {
if (exponent == 0) return 1;
if (exponent < 0) throw new IllegalArgumentException("Can't handle negative exponents");
if (modulus < 0) modulus = -modulus;
base %= modulus;
if (base < 0) base += modulus;
long aux = 1;
while(exponent > 1) {
if ((exponent & 1) == 1) {
aux = (aux * base) % modulus;
}
base = (base * base) % modulus;
exponent >>= 1;
}
return (aux * base) % modulus;
}
}
| |
/*
* Copyright 2013 S. Webber
*
* 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.projog.core.predicate.builtin.io;
import static org.projog.core.term.EmptyList.EMPTY_LIST;
import static org.projog.core.term.ListUtils.toJavaUtilList;
import static org.projog.core.term.TermUtils.toLong;
import java.util.List;
import org.projog.core.predicate.AbstractSingleResultPredicate;
import org.projog.core.term.ListUtils;
import org.projog.core.term.Term;
import org.projog.core.term.TermFormatter;
import org.projog.core.term.TermUtils;
/* TEST
%?- writef('%s%n %t%r', [[h,e,l,l,o], 44, world, !, 3])
%OUTPUT hello, world!!!
%YES
%?- writef('.%7l.\\n.%7l.\\n.%7l.\\n.%7l.\\n.%7l.', [a, abc, abcd, abcdefg, abcdefgh])
%OUTPUT
%.a .
%.abc .
%.abcd .
%.abcdefg.
%.abcdefgh.
%OUTPUT
%YES
%?- writef('.%7r.\\n.%7r.\\n.%7r.\\n.%7r.\\n.%7r.', [a, abc, abcd, abcdefg, abcdefgh])
%OUTPUT
%. a.
%. abc.
%. abcd.
%.abcdefg.
%.abcdefgh.
%OUTPUT
%YES
%?- writef('.%7c.\\n.%7c.\\n.%7c.\\n.%7c.\\n.%7c.', [a, abc, abcd, abcdefg, abcdefgh])
%OUTPUT
%. a .
%. abc .
%. abcd .
%.abcdefg.
%.abcdefgh.
%OUTPUT
%YES
%?- writef('%w %d', [1+1, 1+1])
%OUTPUT 1 + 1 +(1, 1)
%YES
%?- writef('\\%\\%%q\\\\\\\\\\r\\n\\u0048',[abc])
%OUTPUT
%%%abc\\
%H
%OUTPUT
%YES
% Note: calling writef with only 1 argument is the same as calling it with an empty list for the second argument:
%?- writef('\\u0048\\u0065\\u006C\\u006c\\u006F', [])
%OUTPUT Hello
%YES
%?- writef('\\u0048\\u0065\\u006C\\u006c\\u006F')
%OUTPUT Hello
%YES
*/
/**
* <code>writef(X,Y)</code> - writes formatted text to the output stream.
* <p>
* The first argument is an atom representing the text to be output. The text can contain special character sequences
* which specify formatting and substitution rules.
* </p>
* <p>
* Supported special character sequences are:
* </p>
* <table>
* <tr>
* <th>Sequence</th>
* <th>Action</th>
* </tr>
* <tr>
* <td>\n</td>
* <td>Output a 'new line' character (ASCII code 10).</td>
* </tr>
* <tr>
* <td>\l</td>
* <td>Same as <code>\n</code>.</td>
* </tr>
* <tr>
* <td>\r</td>
* <td>Output a 'carriage return' character (ASCII code 13).</td>
* </tr>
* <tr>
* <td>\t</td>
* <td>Output a tab character (ASCII code 9).</td>
* </tr>
* <tr>
* <td>\\</td>
* <td>Output the <code>\</code> character.</td>
* </tr>
* <tr>
* <td>\%</td>
* <td>Output the <code>%</code> character.</td>
* </tr>
* <tr>
* <td>\\u<i>NNNN</i></td>
* <td>Output the unicode character represented by the hex digits <i>NNNN</i>.</td>
* </tr>
* <tr>
* <td>%t</td>
* <td>Output the next term - in same format as <code>write/1</code>.</td>
* </tr>
* <tr>
* <td>%w</td>
* <td>Same as <code>\t</code>.</td>
* </tr>
* <tr>
* <td>%q</td>
* <td>Same as <code>\t</code>.</td>
* </tr>
* <tr>
* <td>%p</td>
* <td>Same as <code>\t</code>.</td>
* </tr>
* <tr>
* <td>%d</td>
* <td>Output the next term - in same format as <code>write_canonical/1</code>.</td>
* </tr>
* <tr>
* <td>%f</td>
* <td>Ignored (only included to support compatibility with other Prologs).</td>
* </tr>
* <tr>
* <td>%s</td>
* <td>Output the elements contained in the list represented by the next term.</td>
* </tr>
* <tr>
* <td>%n</td>
* <td>Output the character code of the next term.</td>
* </tr>
* <tr>
* <td>%r</td>
* <td>Write the next term <i>N</i> times, where <i>N</i> is the value of the second term.</td>
* </tr>
* <tr>
* <td>%<i>N</i>c</td>
* <td>Write the next term centered in <i>N</i> columns.</td>
* </tr>
* <tr>
* <td>%<i>N</i>l</td>
* <td>Write the next term left-aligned in <i>N</i> columns.</td>
* </tr>
* <tr>
* <td>%<i>N</i>r</td>
* <td>Write the next term right-aligned in <i>N</i> columns.</td>
* </tr>
* </table>
* <p>
* <code>writef(X)</code> produces the same results as <code>writef(X, [])</code>.
* </p>
*/
public final class Writef extends AbstractSingleResultPredicate {
@Override
protected boolean evaluate(Term atom) {
return evaluate(atom, EMPTY_LIST);
}
@Override
protected boolean evaluate(Term atom, Term list) {
final String text = TermUtils.getAtomName(atom);
final List<Term> args = toJavaUtilList(list);
if (args == null) {
return false;
}
final StringBuilder sb = format(text, args);
print(sb);
return true;
}
private StringBuilder format(final String text, final List<Term> args) {
final Formatter f = new Formatter(text, args, getTermFormatter());
while (f.hasMore()) {
final int c = f.pop();
if (c == '%') {
parsePercentEscapeSequence(f);
} else if (c == '\\') {
parseSlashEscapeSequence(f);
} else {
f.writeChar(c);
}
}
return f.output;
}
private void parsePercentEscapeSequence(final Formatter f) {
final int next = f.pop();
if (next == 'f') {
// flush - not supported, so ignore
return;
}
final Term arg = f.nextArg();
final String output;
switch (next) {
case 't':
case 'w':
case 'q':
case 'p':
output = f.format(arg);
break;
case 'n':
long charCode = toLong(getArithmeticOperators(), arg);
output = Character.toString((char) charCode);
break;
case 'r':
long timesToRepeat = toLong(getArithmeticOperators(), f.nextArg());
output = repeat(f.format(arg), timesToRepeat);
break;
case 's':
output = concat(f, arg);
break;
case 'd':
// Write the term, ignoring operators.
output = arg.toString();
break;
default:
f.rewind();
output = align(f, arg);
}
f.writeString(output);
}
private String repeat(final String text, long timesToRepeat) {
StringBuilder sb = new StringBuilder();
for (long i = 0; i < timesToRepeat; i++) {
sb.append(text);
}
return sb.toString();
}
private String concat(final Formatter f, final Term t) {
List<Term> l = ListUtils.toJavaUtilList(t);
if (l == null) {
throw new IllegalArgumentException("Expected list but got: " + t);
}
StringBuilder sb = new StringBuilder();
for (Term e : l) {
sb.append(f.format(e));
}
return sb.toString();
}
private String align(final Formatter f, final Term t) {
String s = f.format(t);
int actualWidth = s.length();
int requiredWidth = parseNumber(f);
int diff = Math.max(0, requiredWidth - actualWidth);
int alignmentChar = f.pop();
switch (alignmentChar) {
case 'l':
return s + getWhitespace(diff);
case 'r':
return getWhitespace(diff) + s;
case 'c':
String prefix = getWhitespace(diff / 2);
String suffix = diff % 2 == 0 ? prefix : prefix + " ";
return prefix + s + suffix;
default:
throw new IllegalArgumentException("? " + alignmentChar);
}
}
private String getWhitespace(int diff) {
String s = "";
for (int i = 0; i < diff; i++) {
s += " ";
}
return s;
}
private int parseNumber(Formatter f) {
int next = 0;
while (isNumber(f.peek())) {
next = (next * 10) + (f.pop() - '0');
}
return next;
}
private void parseSlashEscapeSequence(final Formatter f) {
final int next = f.pop();
final int output;
switch (next) {
case 'l':
case 'n':
output = '\n';
break;
case 'r':
output = '\r';
break;
case 't':
output = '\t';
break;
case '\\':
output = '\\';
break;
case '%':
output = '%';
break;
case 'u':
output = parseUnicode(f);
break;
default:
throw new IllegalArgumentException("? " + next);
}
f.writeChar(output);
}
private int parseUnicode(final Formatter f) {
final StringBuilder sb = new StringBuilder();
sb.append((char) f.pop());
sb.append((char) f.pop());
sb.append((char) f.pop());
sb.append((char) f.pop());
return Integer.parseInt(sb.toString(), 16);
}
private boolean isNumber(int c) {
return c >= '0' && c <= '9';
}
private void print(final StringBuilder sb) {
getFileHandles().getCurrentOutputStream().print(sb);
}
private static class Formatter {
final StringBuilder output = new StringBuilder();
final char[] chars;
final List<Term> args;
final TermFormatter termFormatter;
int charIdx;
int argIdx;
Formatter(String text, List<Term> args, TermFormatter termFormatter) {
this.chars = text.toCharArray();
this.args = args;
this.termFormatter = termFormatter;
}
public void rewind() {
charIdx--;
}
Term nextArg() {
return args.get(argIdx++);
}
String format(Term t) {
return termFormatter.formatTerm(t);
}
int peek() {
if (hasMore()) {
return chars[charIdx];
} else {
return -1;
}
}
int pop() {
int c = peek();
charIdx++;
return c;
}
boolean hasMore() {
return charIdx < chars.length;
}
void writeChar(int c) {
output.append((char) c);
}
void writeString(String s) {
output.append(s);
}
}
}
| |
/*
* Copyright 2016 Red Hat, Inc. and/or its affiliates
* and other 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 org.keycloak.storage.adapter;
import org.keycloak.common.util.MultivaluedHashMap;
import org.keycloak.component.ComponentModel;
import org.keycloak.models.ClientModel;
import org.keycloak.models.GroupModel;
import org.keycloak.models.KeycloakSession;
import org.keycloak.models.RealmModel;
import org.keycloak.models.RoleContainerModel;
import org.keycloak.models.RoleModel;
import org.keycloak.models.UserModel;
import org.keycloak.models.UserModelDefaultMethods;
import org.keycloak.models.utils.DefaultRoles;
import org.keycloak.models.utils.RoleUtils;
import org.keycloak.storage.ReadOnlyException;
import org.keycloak.storage.StorageId;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
/**
* This abstract class provides implementations for everything but getUsername(). getId() returns a default value
* of "f:" + providerId + ":" + getUsername(). isEnabled() returns true. getRoleMappings() will return default roles.
* getGroups() will return default groups.
*
* All other read methods return null, an empty collection, or false depending
* on the type. All update methods throw a ReadOnlyException.
*
* Provider implementors should override the methods for attributes, properties, and mappings they support.
*
* @author <a href="mailto:bill@burkecentral.com">Bill Burke</a>
* @version $Revision: 1 $
*/
public abstract class AbstractUserAdapter extends UserModelDefaultMethods {
protected KeycloakSession session;
protected RealmModel realm;
protected ComponentModel storageProviderModel;
public AbstractUserAdapter(KeycloakSession session, RealmModel realm, ComponentModel storageProviderModel) {
this.session = session;
this.realm = realm;
this.storageProviderModel = storageProviderModel;
}
@Override
public Set<String> getRequiredActions() {
return Collections.emptySet();
}
@Override
public void addRequiredAction(String action) {
throw new ReadOnlyException("user is read only for this update");
}
@Override
public void removeRequiredAction(String action) {
throw new ReadOnlyException("user is read only for this update");
}
@Override
public void addRequiredAction(RequiredAction action) {
throw new ReadOnlyException("user is read only for this update");
}
@Override
public void removeRequiredAction(RequiredAction action) {
throw new ReadOnlyException("user is read only for this update");
}
/**
* Get group membership mappings that are managed by this storage provider
*
* @return
*/
protected Set<GroupModel> getGroupsInternal() {
return Collections.emptySet();
}
/**
* Should the realm's default groups be appended to getGroups() call?
* If your storage provider is not managing group mappings then it is recommended that
* this method return true
*
* @return
*/
protected boolean appendDefaultGroups() {
return true;
}
@Override
public Set<GroupModel> getGroups() {
Set<GroupModel> set = new HashSet<>();
if (appendDefaultGroups()) set.addAll(realm.getDefaultGroups());
set.addAll(getGroupsInternal());
return set;
}
@Override
public void joinGroup(GroupModel group) {
throw new ReadOnlyException("user is read only for this update");
}
@Override
public void leaveGroup(GroupModel group) {
throw new ReadOnlyException("user is read only for this update");
}
@Override
public boolean isMemberOf(GroupModel group) {
Set<GroupModel> roles = getGroups();
return RoleUtils.isMember(roles, group);
}
@Override
public Set<RoleModel> getRealmRoleMappings() {
Set<RoleModel> roleMappings = getRoleMappings();
Set<RoleModel> realmRoles = new HashSet<>();
for (RoleModel role : roleMappings) {
RoleContainerModel container = role.getContainer();
if (container instanceof RealmModel) {
realmRoles.add(role);
}
}
return realmRoles;
}
@Override
public Set<RoleModel> getClientRoleMappings(ClientModel app) {
Set<RoleModel> roleMappings = getRoleMappings();
Set<RoleModel> roles = new HashSet<>();
for (RoleModel role : roleMappings) {
RoleContainerModel container = role.getContainer();
if (container instanceof ClientModel) {
ClientModel appModel = (ClientModel) container;
if (appModel.getId().equals(app.getId())) {
roles.add(role);
}
}
}
return roles;
}
@Override
public boolean hasRole(RoleModel role) {
Set<RoleModel> roles = getRoleMappings();
return RoleUtils.hasRole(roles, role)
|| RoleUtils.hasRoleFromGroup(getGroups(), role, true);
}
@Override
public void grantRole(RoleModel role) {
throw new ReadOnlyException("user is read only for this update");
}
/**
* Should the realm's default roles be appended to getRoleMappings() call?
* If your storage provider is not managing all role mappings then it is recommended that
* this method return true
*
* @return
*/
protected boolean appendDefaultRolesToRoleMappings() {
return true;
}
protected Set<RoleModel> getRoleMappingsInternal() {
return Collections.emptySet();
}
@Override
public Set<RoleModel> getRoleMappings() {
Set<RoleModel> set = new HashSet<>();
if (appendDefaultRolesToRoleMappings()) set.addAll(DefaultRoles.getDefaultRoles(realm));
set.addAll(getRoleMappingsInternal());
return set;
}
@Override
public void deleteRoleMapping(RoleModel role) {
throw new ReadOnlyException("user is read only for this update");
}
@Override
public boolean isEnabled() {
return true;
}
@Override
public void setEnabled(boolean enabled) {
throw new ReadOnlyException("user is read only for this update");
}
/**
* This method should not be overriden
*
* @return
*/
@Override
public String getFederationLink() {
return null;
}
/**
* This method should not be overriden
*
* @return
*/
@Override
public void setFederationLink(String link) {
throw new ReadOnlyException("user is read only for this update");
}
/**
* This method should not be overriden
*
* @return
*/
@Override
public String getServiceAccountClientLink() {
return null;
}
/**
* This method should not be overriden
*
* @return
*/
@Override
public void setServiceAccountClientLink(String clientInternalId) {
throw new ReadOnlyException("user is read only for this update");
}
protected StorageId storageId;
/**
* Defaults to 'f:' + storageProvider.getId() + ':' + getUsername()
*
* @return
*/
@Override
public String getId() {
if (storageId == null) {
storageId = new StorageId(storageProviderModel.getId(), getUsername());
}
return storageId.getId();
}
@Override
public void setUsername(String username) {
throw new ReadOnlyException("user is read only for this update");
}
protected long created = System.currentTimeMillis();
@Override
public Long getCreatedTimestamp() {
return created;
}
@Override
public void setCreatedTimestamp(Long timestamp) {
throw new ReadOnlyException("user is read only for this update");
}
@Override
public void setSingleAttribute(String name, String value) {
throw new ReadOnlyException("user is read only for this update");
}
@Override
public void removeAttribute(String name) {
throw new ReadOnlyException("user is read only for this update");
}
@Override
public void setAttribute(String name, List<String> values) {
throw new ReadOnlyException("user is read only for this update");
}
@Override
public String getFirstAttribute(String name) {
if (name.equals(UserModel.USERNAME)) {
return getUsername();
}
return null;
}
@Override
public Map<String, List<String>> getAttributes() {
MultivaluedHashMap<String, String> attributes = new MultivaluedHashMap<>();
attributes.add(UserModel.USERNAME, getUsername());
return attributes;
}
@Override
public List<String> getAttribute(String name) {
if (name.equals(UserModel.USERNAME)) {
return Collections.singletonList(getUsername());
}
return Collections.emptyList();
}
@Override
public String getFirstName() {
return null;
}
@Override
public void setFirstName(String firstName) {
throw new ReadOnlyException("user is read only for this update");
}
@Override
public String getLastName() {
return null;
}
@Override
public void setLastName(String lastName) {
throw new ReadOnlyException("user is read only for this update");
}
@Override
public String getEmail() {
return null;
}
@Override
public void setEmail(String email) {
throw new ReadOnlyException("user is read only for this update");
}
@Override
public boolean isEmailVerified() {
return false;
}
@Override
public void setEmailVerified(boolean verified) {
throw new ReadOnlyException("user is read only for this update");
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || !(o instanceof UserModel)) return false;
UserModel that = (UserModel) o;
return that.getId().equals(getId());
}
@Override
public int hashCode() {
return getId().hashCode();
}
}
| |
/*
* 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.datasketches.hash;
import static org.apache.datasketches.hash.MurmurHash3Adaptor.asDouble;
import static org.apache.datasketches.hash.MurmurHash3Adaptor.asInt;
import static org.apache.datasketches.hash.MurmurHash3Adaptor.hashToBytes;
import static org.apache.datasketches.hash.MurmurHash3Adaptor.hashToLongs;
import static org.apache.datasketches.hash.MurmurHash3Adaptor.modulo;
import org.testng.Assert;
import org.testng.annotations.Test;
import org.apache.datasketches.SketchesArgumentException;
/**
* @author Lee Rhodes
*/
@SuppressWarnings("javadoc")
public class MurmurHash3AdaptorTest {
@Test
public void checkToBytesLong() {
byte[] result = hashToBytes(2L, 0L);
for (int i = 8; i-- > 0;) {
Assert.assertNotEquals(result[i], 0);
}
}
@Test
public void checkToBytesLongArr() {
long[] arr = { 1L, 2L };
byte[] result = hashToBytes(arr, 0L);
for (int i = 8; i-- > 0;) {
Assert.assertNotEquals(result[i], 0);
}
arr = null;
result = hashToBytes(arr, 0L);
Assert.assertEquals(result, null);
arr = new long[0];
result = hashToBytes(arr, 0L);
Assert.assertEquals(result, null);
}
@Test
public void checkToBytesIntArr() {
int[] arr = { 1, 2 };
byte[] result = hashToBytes(arr, 0L);
for (int i = 8; i-- > 0;) {
Assert.assertNotEquals(result[i], 0);
}
arr = null;
result = hashToBytes(arr, 0L);
Assert.assertEquals(result, null);
arr = new int[0];
result = hashToBytes(arr, 0L);
Assert.assertEquals(result, null);
}
@Test
public void checkToBytesCharArr() {
char[] arr = { 1, 2 };
byte[] result = hashToBytes(arr, 0L);
for (int i = 8; i-- > 0;) {
Assert.assertNotEquals(result[i], 0);
}
arr = null;
result = hashToBytes(arr, 0L);
Assert.assertEquals(result, null);
arr = new char[0];
result = hashToBytes(arr, 0L);
Assert.assertEquals(result, null);
}
@Test
public void checkToBytesByteArr() {
byte[] arr = { 1, 2 };
byte[] result = hashToBytes(arr, 0L);
for (int i = 8; i-- > 0;) {
Assert.assertNotEquals(result[i], 0);
}
arr = null;
result = hashToBytes(arr, 0L);
Assert.assertEquals(result, null);
arr = new byte[0];
result = hashToBytes(arr, 0L);
Assert.assertEquals(result, null);
}
@Test
public void checkToBytesDouble() {
byte[] result = hashToBytes(1.0, 0L);
for (int i = 8; i-- > 0;) {
Assert.assertNotEquals(result[i], 0);
}
result = hashToBytes(0.0, 0L);
for (int i = 8; i-- > 0;) {
Assert.assertNotEquals(result[i], 0);
}
result = hashToBytes( -0.0, 0L);
for (int i = 8; i-- > 0;) {
Assert.assertNotEquals(result[i], 0);
}
}
@Test
public void checkToBytesString() {
byte[] result = hashToBytes("1", 0L);
for (int i = 8; i-- > 0;) {
Assert.assertNotEquals(result[i], 0);
}
result = hashToBytes("", 0L);
Assert.assertEquals(result, null);
String s = null;
result = hashToBytes(s, 0L);
Assert.assertEquals(result, null);
}
/************/
@Test
public void checkToLongsLong() {
long[] result = hashToLongs(2L, 0L);
for (int i = 2; i-- > 0;) {
Assert.assertNotEquals(result[i], 0);
}
}
@Test
public void checkToLongsLongArr() {
long[] arr = { 1L, 2L };
long[] result = hashToLongs(arr, 0L);
for (int i = 2; i-- > 0;) {
Assert.assertNotEquals(result[i], 0);
}
arr = null;
result = hashToLongs(arr, 0L);
Assert.assertEquals(result, null);
arr = new long[0];
result = hashToLongs(arr, 0L);
Assert.assertEquals(result, null);
}
@Test
public void checkToLongsIntArr() {
int[] arr = { 1, 2 };
long[] result = hashToLongs(arr, 0L);
for (int i = 2; i-- > 0;) {
Assert.assertNotEquals(result[i], 0);
}
arr = null;
result = hashToLongs(arr, 0L);
Assert.assertEquals(result, null);
arr = new int[0];
result = hashToLongs(arr, 0L);
Assert.assertEquals(result, null);
}
@Test
public void checkToLongsCharArr() {
char[] arr = { 1, 2 };
long[] result = hashToLongs(arr, 0L);
for (int i = 2; i-- > 0;) {
Assert.assertNotEquals(result[i], 0);
}
arr = null;
result = hashToLongs(arr, 0L);
Assert.assertEquals(result, null);
arr = new char[0];
result = hashToLongs(arr, 0L);
Assert.assertEquals(result, null);
}
@Test
public void checkToLongsByteArr() {
byte[] arr = { 1, 2 };
long[] result = hashToLongs(arr, 0L);
for (int i = 2; i-- > 0;) {
Assert.assertNotEquals(result[i], 0);
}
arr = null;
result = hashToLongs(arr, 0L);
Assert.assertEquals(result, null);
arr = new byte[0];
result = hashToLongs(arr, 0L);
Assert.assertEquals(result, null);
}
@Test
public void checkToLongsDouble() {
long[] result = hashToLongs(1.0, 0L);
for (int i = 2; i-- > 0;) {
Assert.assertNotEquals(result[i], 0);
}
result = hashToLongs(0.0, 0L);
for (int i = 2; i-- > 0;) {
Assert.assertNotEquals(result[i], 0);
}
result = hashToLongs( -0.0, 0L);
for (int i = 2; i-- > 0;) {
Assert.assertNotEquals(result[i], 0);
}
}
@Test
public void checkToLongsString() {
long[] result = hashToLongs("1", 0L);
for (int i = 2; i-- > 0;) {
Assert.assertNotEquals(result[i], 0);
}
result = hashToLongs("", 0L);
Assert.assertEquals(result, null);
String s = null;
result = hashToLongs(s, 0L);
Assert.assertEquals(result, null);
}
/*************/
@Test
public void checkModulo() {
int div = 7;
for (int i = 20; i-- > 0;) {
long[] out = hashToLongs(i, 9001);
int mod = modulo(out[0], out[1], div);
Assert.assertTrue((mod < div) && (mod >= 0));
mod = modulo(out, div);
Assert.assertTrue((mod < div) && (mod >= 0));
}
}
@Test
public void checkAsDouble() {
for (int i = 0; i < 10000; i++ ) {
double result = asDouble(hashToLongs(i, 0));
Assert.assertTrue((result >= 0) && (result < 1.0));
}
}
//Check asInt() functions
@Test
public void checkAsInt() {
int lo = (3 << 28);
int hi = (1 << 30) + 1;
for (byte i = 0; i < 126; i++ ) {
long[] longArr = {i, i+1}; //long[]
int result = asInt(longArr, lo);
Assert.assertTrue((result >= 0) && (result < lo));
result = asInt(longArr, hi);
Assert.assertTrue((result >= 0) && (result < hi));
int[] intArr = {i, i+1}; //int[]
result = asInt(intArr, lo);
Assert.assertTrue((result >= 0) && (result < lo));
result = asInt(intArr, hi);
Assert.assertTrue((result >= 0) && (result < hi));
byte[] byteArr = {i, (byte)(i+1)}; //byte[]
result = asInt(byteArr, lo);
Assert.assertTrue((result >= 0) && (result < lo));
result = asInt(byteArr, hi);
Assert.assertTrue((result >= 0) && (result < hi));
long longV = i; //long
result = asInt(longV, lo);
Assert.assertTrue((result >= 0) && (result < lo));
result = asInt(longV, hi);
Assert.assertTrue((result >= 0) && (result < hi));
double v = i; //double
result = asInt(v, lo);
Assert.assertTrue((result >= 0) && (result < lo));
result = asInt(v, hi);
Assert.assertTrue((result >= 0) && (result < hi));
String s = Integer.toString(i); //String
result = asInt(s, lo);
Assert.assertTrue((result >= 0) && (result < lo));
result = asInt(s, hi);
Assert.assertTrue((result >= 0) && (result < hi));
}
}
@Test (expectedExceptions = SketchesArgumentException.class)
public void checkAsIntCornerCaseLongNull() {
long[] arr = null;
asInt(arr, 1000);
}
@Test (expectedExceptions = SketchesArgumentException.class)
public void checkAsIntCornerCaseLongEmpty() {
long[] arr = new long[0];
asInt(arr, 1000);
}
@Test (expectedExceptions = SketchesArgumentException.class)
public void checkAsIntCornerCaseIntNull() {
int[] arr = null;
asInt(arr, 1000);
}
@Test (expectedExceptions = SketchesArgumentException.class)
public void checkAsIntCornerCaseIntEmpty() {
int[] arr = new int[0];
asInt(arr, 1000);
}
@Test (expectedExceptions = SketchesArgumentException.class)
public void checkAsIntCornerCaseByteNull() {
byte[] arr = null;
asInt(arr, 1000);
}
@Test (expectedExceptions = SketchesArgumentException.class)
public void checkAsIntCornerCaseByteEmpty() {
byte[] arr = new byte[0];
asInt(arr, 1000);
}
@Test (expectedExceptions = SketchesArgumentException.class)
public void checkAsIntCornerCaseStringNull() {
String s = null;
asInt(s, 1000);
}
@Test (expectedExceptions = SketchesArgumentException.class)
public void checkAsIntCornerCaseStringEmpty() {
String s = "";
asInt(s, 1000);
}
@Test (expectedExceptions = SketchesArgumentException.class)
public void checkAsIntCornerCaseNTooSmall() {
String s = "abc";
asInt(s, 1);
}
@Test
public void printlnTest() {
println("PRINTING: "+this.getClass().getName());
}
/**
* @param s value to print
*/
static void println(String s) {
//System.out.println(s); //disable here
}
}
| |
/*
* 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.client.http2;
import java.io.IOException;
import java.lang.reflect.Method;
import java.net.InetSocketAddress;
import java.net.URI;
import java.nio.ByteBuffer;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import javax.net.ssl.SSLEngine;
import io.undertow.protocols.ssl.UndertowXnioSsl;
import org.eclipse.jetty.alpn.ALPN;
import org.xnio.ChannelListener;
import org.xnio.IoFuture;
import org.xnio.OptionMap;
import org.xnio.Options;
import org.xnio.Pool;
import org.xnio.StreamConnection;
import org.xnio.XnioIoThread;
import org.xnio.XnioWorker;
import org.xnio.channels.StreamSourceChannel;
import org.xnio.conduits.PushBackStreamSourceConduit;
import org.xnio.ssl.SslConnection;
import org.xnio.ssl.XnioSsl;
import io.undertow.UndertowLogger;
import io.undertow.UndertowMessages;
import io.undertow.client.ClientCallback;
import io.undertow.client.ClientConnection;
import io.undertow.client.ClientProvider;
import io.undertow.protocols.http2.Http2Channel;
import io.undertow.util.ImmediatePooled;
/**
* Plaintext HTTP2 client provider that works using HTTP upgrade
*
* @author Stuart Douglas
*/
public class Http2ClientProvider implements ClientProvider {
private static final String PROTOCOL_KEY = Http2ClientProvider.class.getName() + ".protocol";
private static final String HTTP2 = "h2";
private static final String HTTP_1_1 = "http/1.1";
private static final List<String> PROTOCOLS = Collections.unmodifiableList(Arrays.asList(HTTP2, HTTP_1_1));
private static final Method ALPN_PUT_METHOD;
static {
Method npnPutMethod;
try {
Class<?> npnClass = Class.forName("org.eclipse.jetty.alpn.ALPN", false, Http2ClientProvider.class.getClassLoader());
npnPutMethod = npnClass.getDeclaredMethod("put", SSLEngine.class, Class.forName("org.eclipse.jetty.alpn.ALPN$Provider", false, Http2ClientProvider.class.getClassLoader()));
} catch (Exception e) {
UndertowLogger.CLIENT_LOGGER.jettyALPNNotFound("HTTP2");
npnPutMethod = null;
}
ALPN_PUT_METHOD = npnPutMethod;
}
@Override
public void connect(final ClientCallback<ClientConnection> listener, final URI uri, final XnioWorker worker, final XnioSsl ssl, final Pool<ByteBuffer> bufferPool, final OptionMap options) {
connect(listener, null, uri, worker, ssl, bufferPool, options);
}
@Override
public void connect(final ClientCallback<ClientConnection> listener, final URI uri, final XnioIoThread ioThread, final XnioSsl ssl, final Pool<ByteBuffer> bufferPool, final OptionMap options) {
connect(listener, null, uri, ioThread, ssl, bufferPool, options);
}
@Override
public Set<String> handlesSchemes() {
return new HashSet<>(Arrays.asList(new String[]{"h2"}));
}
@Override
public void connect(final ClientCallback<ClientConnection> listener, InetSocketAddress bindAddress, final URI uri, final XnioWorker worker, final XnioSsl ssl, final Pool<ByteBuffer> bufferPool, final OptionMap options) {
if(ALPN_PUT_METHOD == null) {
listener.failed(UndertowMessages.MESSAGES.jettyNPNNotAvailable());
return;
}
if (ssl == null) {
listener.failed(UndertowMessages.MESSAGES.sslWasNull());
return;
}
OptionMap tlsOptions = OptionMap.builder().addAll(options).set(Options.SSL_STARTTLS, true).getMap();
if(bindAddress == null) {
ssl.openSslConnection(worker, new InetSocketAddress(uri.getHost(), uri.getPort() == -1 ? 443 : uri.getPort()), createOpenListener(listener, uri, ssl, bufferPool, tlsOptions), tlsOptions).addNotifier(createNotifier(listener), null);
} else {
ssl.openSslConnection(worker, bindAddress, new InetSocketAddress(uri.getHost(), uri.getPort() == -1 ? 443 : uri.getPort()), createOpenListener(listener, uri, ssl, bufferPool, tlsOptions), tlsOptions).addNotifier(createNotifier(listener), null);
}
}
@Override
public void connect(final ClientCallback<ClientConnection> listener, InetSocketAddress bindAddress, final URI uri, final XnioIoThread ioThread, final XnioSsl ssl, final Pool<ByteBuffer> bufferPool, final OptionMap options) {
if(ALPN_PUT_METHOD == null) {
listener.failed(UndertowMessages.MESSAGES.jettyNPNNotAvailable());
return;
}
if (ssl == null) {
listener.failed(UndertowMessages.MESSAGES.sslWasNull());
return;
}
if(bindAddress == null) {
OptionMap tlsOptions = OptionMap.builder().addAll(options).set(Options.SSL_STARTTLS, true).getMap();
ssl.openSslConnection(ioThread, new InetSocketAddress(uri.getHost(), uri.getPort() == -1 ? 443 : uri.getPort()), createOpenListener(listener, uri, ssl, bufferPool, tlsOptions), options).addNotifier(createNotifier(listener), null);
} else {
ssl.openSslConnection(ioThread, bindAddress, new InetSocketAddress(uri.getHost(), uri.getPort() == -1 ? 443 : uri.getPort()), createOpenListener(listener, uri, ssl, bufferPool, options), options).addNotifier(createNotifier(listener), null);
}
}
private IoFuture.Notifier<StreamConnection, Object> createNotifier(final ClientCallback<ClientConnection> listener) {
return new IoFuture.Notifier<StreamConnection, Object>() {
@Override
public void notify(IoFuture<? extends StreamConnection> ioFuture, Object o) {
if (ioFuture.getStatus() == IoFuture.Status.FAILED) {
listener.failed(ioFuture.getException());
}
}
};
}
private ChannelListener<StreamConnection> createOpenListener(final ClientCallback<ClientConnection> listener, final URI uri, final XnioSsl ssl, final Pool<ByteBuffer> bufferPool, final OptionMap options) {
return new ChannelListener<StreamConnection>() {
@Override
public void handleEvent(StreamConnection connection) {
handleConnected(connection, listener, uri, ssl, bufferPool, options);
}
};
}
private void handleConnected(StreamConnection connection, final ClientCallback<ClientConnection> listener, URI uri, XnioSsl ssl, Pool<ByteBuffer> bufferPool, OptionMap options) {
handlePotentialHttp2Connection(connection, listener, bufferPool, options, new ChannelListener<SslConnection>() {
@Override
public void handleEvent(SslConnection channel) {
listener.failed(UndertowMessages.MESSAGES.spdyNotSupported());
}
}, uri);
}
public static boolean isEnabled() {
return ALPN_PUT_METHOD != null;
}
/**
* Not really part of the public API, but is used by the HTTP client to initiate a HTTP2 connection for HTTPS requests.
*/
public static void handlePotentialHttp2Connection(final StreamConnection connection, final ClientCallback<ClientConnection> listener, final Pool<ByteBuffer> bufferPool, final OptionMap options, final ChannelListener<SslConnection> http2FailedListener, final URI uri) {
final SslConnection sslConnection = (SslConnection) connection;
final SSLEngine sslEngine = UndertowXnioSsl.getSslEngine(sslConnection);
final Http2SelectionProvider http2SelectionProvider = new Http2SelectionProvider(sslEngine);
try {
ALPN_PUT_METHOD.invoke(null, sslEngine, http2SelectionProvider);
} catch (Exception e) {
http2FailedListener.handleEvent(sslConnection);
return;
}
try {
sslConnection.startHandshake();
sslConnection.getSourceChannel().getReadSetter().set(new ChannelListener<StreamSourceChannel>() {
@Override
public void handleEvent(StreamSourceChannel channel) {
if (http2SelectionProvider.selected != null) {
if (http2SelectionProvider.selected.equals(HTTP_1_1)) {
sslConnection.getSourceChannel().suspendReads();
http2FailedListener.handleEvent(sslConnection);
return;
} else if (http2SelectionProvider.selected.equals(HTTP2)) {
listener.completed(createHttp2Channel(connection, bufferPool, options, uri.getHost()));
}
} else {
ByteBuffer buf = ByteBuffer.allocate(100);
try {
int read = channel.read(buf);
if (read > 0) {
buf.flip();
PushBackStreamSourceConduit pb = new PushBackStreamSourceConduit(connection.getSourceChannel().getConduit());
pb.pushBack(new ImmediatePooled<>(buf));
connection.getSourceChannel().setConduit(pb);
}
if (http2SelectionProvider.selected == null) {
http2SelectionProvider.selected = (String) sslEngine.getSession().getValue(PROTOCOL_KEY);
}
if ((http2SelectionProvider.selected == null && read > 0) || HTTP_1_1.equals(http2SelectionProvider.selected)) {
sslConnection.getSourceChannel().suspendReads();
http2FailedListener.handleEvent(sslConnection);
return;
} else if (http2SelectionProvider.selected != null) {
//we have spdy
if (http2SelectionProvider.selected.equals(HTTP2)) {
listener.completed(createHttp2Channel(connection, bufferPool, options, uri.getHost()));
}
}
} catch (IOException e) {
listener.failed(e);
}
}
}
});
sslConnection.getSourceChannel().resumeReads();
} catch (IOException e) {
listener.failed(e);
} catch (Throwable e) {
listener.failed(new IOException(e));
}
}
private static Http2ClientConnection createHttp2Channel(StreamConnection connection, Pool<ByteBuffer> bufferPool, OptionMap options, String defaultHost) {
Http2Channel http2Channel = new Http2Channel(connection, null, bufferPool, null, true, false, options);
return new Http2ClientConnection(http2Channel, false, defaultHost);
}
private static class Http2SelectionProvider implements ALPN.ClientProvider {
private String selected;
private final SSLEngine sslEngine;
private Http2SelectionProvider(SSLEngine sslEngine) {
this.sslEngine = sslEngine;
}
@Override
public boolean supports() {
return true;
}
@Override
public List<String> protocols() {
return PROTOCOLS;
}
@Override
public void unsupported() {
selected = HTTP_1_1;
}
@Override
public void selected(String s) {
ALPN.remove(sslEngine);
selected = s;
sslEngine.getHandshakeSession().putValue(PROTOCOL_KEY, selected);
}
private String getSelected() {
return selected;
}
}
}
| |
package ab.biol498.ACRD;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import com.clcbio.api.base.algorithm.Algo;
import com.clcbio.api.base.algorithm.AlgoException;
import com.clcbio.api.base.algorithm.CallableExecutor;
import com.clcbio.api.base.algorithm.OutputHandler;
import com.clcbio.api.base.algorithm.parameter.keys.Keys;
import com.clcbio.api.base.session.ApplicationContext;
import com.clcbio.api.base.util.NoRemovalIterator;
import com.clcbio.api.base.util.iterator.MovableIntegerIterator;
import com.clcbio.api.free.datatypes.ClcObject;
import com.clcbio.api.free.datatypes.GeneralClcTabular;
import com.clcbio.api.free.datatypes.Tabular;
import com.clcbio.api.free.datatypes.bioinformatics.sequence.BasicSequenceAccessible;
import com.clcbio.api.free.datatypes.bioinformatics.sequence.BasicSequenceAccessor;
import com.clcbio.api.free.datatypes.bioinformatics.sequence.NucleotideSequence;
import com.clcbio.api.free.datatypes.bioinformatics.sequence.Sequence;
import com.clcbio.api.free.datatypes.bioinformatics.sequence.alignment.AlignmentSequenceIndexer;
import com.clcbio.api.free.datatypes.bioinformatics.sequence.alphabet.Alphabet;
import com.clcbio.api.free.datatypes.bioinformatics.sequence.index.BasicIndexer;
import com.clcbio.api.free.datatypes.bioinformatics.sequence.index.DefaultBasicIndexer;
import com.clcbio.api.free.datatypes.bioinformatics.sequence.index.DefaultSingleIndexer;
import com.clcbio.api.free.datatypes.bioinformatics.sequence.index.IndexSequenceLocator;
import com.clcbio.api.free.datatypes.bioinformatics.sequence.index.MultiIndexer;
import com.clcbio.api.free.datatypes.bioinformatics.sequence.index.SingleIndexer;
import com.clcbio.api.free.datatypes.bioinformatics.sequence.list.NucleotideSequenceList;
import com.clcbio.api.free.datatypes.bioinformatics.sequence.region.Region;
import com.clcbio.api.free.datatypes.bioinformatics.sequencecluster.AssemblySequenceCluster;
import com.clcbio.api.free.datatypes.bioinformatics.sequencecluster.AssemblySequenceClusterSource;
import com.clcbio.api.free.datatypes.bioinformatics.sequencecluster.BasicLocalAlignment;
import com.clcbio.api.free.datatypes.bioinformatics.sequencecluster.ScatteredLocalAlignment;
import com.clcbio.api.free.datatypes.bioinformatics.sequencecluster.SequenceCluster;
import com.clcbio.api.free.datatypes.bioinformatics.sequencecluster.SequenceClusterConsensus;
import com.clcbio.api.free.datatypes.bioinformatics.sequencecluster.index.SequenceClusterIndexer;
import com.clcbio.api.free.datatypes.framework.permission.PermissionController;
import com.clcbio.api.free.datatypes.framework.permission.Permissions;
import com.clcbio.api.free.gui.dialog.ClcMessages;
import com.clcbio.api.free.workbench.WorkbenchManager;
import com.clcbio.api.free.datatypes.bioinformatics.sequence.feature.Feature;
public class ACRDAlgo extends Algo implements PermissionController {
WorkbenchManager workbookManager;
NucleotideSequence annotatedSequence;
List<String> names;
List<Region> regions;
List<Integer> errorCounts;
public ACRDAlgo(WorkbenchManager wm) {
super(wm);
workbookManager = wm;
}
@Override
public void calculate(OutputHandler handler, CallableExecutor executor)
throws AlgoException, InterruptedException {
if (this.getInputObjectsCount() != 2) {
displayError("Please select one annotated nucleotide sequence, and the corresponding consensus sequence (containing the mapped reads).");
return;
}
names = new ArrayList<String>();
regions = new ArrayList<Region>();
errorCounts = new ArrayList<Integer>();
NucleotideSequence annotatedSequence = null;
SequenceCluster consensusWithMappedReads = null;
for (ClcObject o: this.getInputObjectsIteratorProvider()) {
if (o instanceof NucleotideSequence) {
annotatedSequence = (NucleotideSequence) o;
}
}
for (ClcObject o: this.getInputObjectsIteratorProvider()) {
if (o instanceof SequenceCluster) {
consensusWithMappedReads = (SequenceCluster)o;
}
}
if (annotatedSequence == null) {
displayError("Please select an annotated version of the consensus sequence.");
return;
}
if (consensusWithMappedReads == null) {
displayError("Please select an the consensus sequence (containing the mapped reads).");
return;
}
processAnnotations(annotatedSequence);
processConsensus(consensusWithMappedReads, handler);
}
private void processAnnotations(NucleotideSequence annotatedSequence) {
Iterator<Feature> it = annotatedSequence.getFeatureIterator();
while (it.hasNext()) {
Feature f = it.next();
names.add(f.getName());
regions.add(f.getRegion());
errorCounts.add(0);
}
}
private void processConsensus(SequenceCluster sc, OutputHandler handler)
throws AlgoException, InterruptedException {
Sequence s = sc.getMainSequence();
for(ScatteredLocalAlignment match : sc.getMatches()) {
for (int i = 0; i < match.getChildLocalAlignmentCount(); i++) {
BasicLocalAlignment alignment = match.getChildLocalAlignment(i);
MovableIntegerIterator itAlignment = alignment.getMatchSequencePositionIterator();
MovableIntegerIterator itMain = alignment.getMainSequencePositionIterator();
Sequence matchSequence = match.getSequence();
while (itMain.hasNext()) {
int consensusIndex = itMain.next();
int alignmentIndex = itAlignment.next();
if (alignmentIndex >= 0 && consensusIndex >= 0) {
int consensusSymbol = s.getSymbolIndexAt(consensusIndex);
int alignedSymbol = matchSequence.getSymbolIndexAt(alignmentIndex);
if (consensusSymbol != alignedSymbol) {
incrementTouched(consensusIndex);
}
}
}
}
}
handler.postOutputObjects(Collections.singletonList(renderTable()), this);
}
private GeneralClcTabular renderTable() {
GeneralClcTabular.Builder builder = GeneralClcTabular.createBuilder(
"ACRD Results",
"Number of different residues, per annotated region, between consensus and mapped reads",
new String[] {
"Annotation",
"Difference Count",
"Length",
"Differences/Length",
});
for (int i = 0; i < names.size(); i++) {
builder.addRow(
names.get(i),
errorCounts.get(i),
regions.get(i).getSize(),
((double)errorCounts.get(i))/((double)regions.get(i).getSize()));
}
return builder.finish();
}
private void incrementTouched(int pos) {
for (int i = 0; i < names.size(); i++) {
if (regions.get(i).isInRegion(pos, false)) {
errorCounts.set(i, 1 + errorCounts.get(i));
}
}
}
private void displayError(String msg) {
ClcMessages.showInformation(
workbookManager.getCurrentMainFrame(),
msg,
"ACRD Plugin - Error");
}
public Permissions getDeniedPermissions(ClcObject clcObject, Object permissionSeeker) {
return Permissions.union(Permissions.SEQUENCE_CHANGE_RESIDUES, Permissions.SEQUENCE_INSERT_DELETE_RESIDUES);
}
public Permissions getReservedPermissions(ClcObject clcObject, Object permissionSeeker) {
return Permissions.NO_PERMISSIONS;
}
public String getReason() {
return "Searching for Open Reading Frames";
}
@Override
public String getClassKey() {
return "acrd_algo";
}
@Override
public String getName() {
return "ACRD";
}
@Override
public double getVersion() {
return 0.0;
}
@Override
public Permissions getNotifyPermissions(ClcObject clcObject,
Object permissionSeeker) {
return Permissions.NO_PERMISSIONS;
}
@Override
public Permissions getWarnPermissions(ClcObject clcObject,
Object permissionSeeker) {
return Permissions.NO_PERMISSIONS;
}
}
| |
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package com.laytonsmith.core.functions;
import com.laytonsmith.abstraction.MCItemMeta;
import com.laytonsmith.abstraction.MCItemStack;
import com.laytonsmith.abstraction.MCLeatherArmorMeta;
import com.laytonsmith.abstraction.MCPlayer;
import com.laytonsmith.annotations.api;
import com.laytonsmith.core.CHVersion;
import com.laytonsmith.core.ObjectGenerator;
import com.laytonsmith.core.Static;
import com.laytonsmith.core.constructs.CArray;
import com.laytonsmith.core.constructs.CBoolean;
import com.laytonsmith.core.constructs.CNull;
import com.laytonsmith.core.constructs.CVoid;
import com.laytonsmith.core.constructs.Construct;
import com.laytonsmith.core.constructs.Target;
import com.laytonsmith.core.environments.CommandHelperEnvironment;
import com.laytonsmith.core.environments.Environment;
import com.laytonsmith.core.exceptions.ConfigCompileException;
import com.laytonsmith.core.exceptions.ConfigRuntimeException;
import com.laytonsmith.core.functions.Exceptions.ExceptionType;
/**
*
*/
public class ItemMeta {
public static String docs(){
return "These functions manipulate an item's meta data. The items are modified in a player's inventory.";
}
private static final String applicableItemMeta = "<ul>"
+ "<li>All items - display (string), lore (array of strings), enchants (array of enchantment arrays),"
+ " repair (int, repair cost)</li><li>Books - title (string), author (string), pages (array of strings)</li>"
+ "<li>EnchantedBooks - stored (array of enchantment arrays (see Example))</li>"
+ "<li>Leather Armor - color (color array (see Example))</li>"
+ "<li>Skulls - owner (string) NOTE: the visual change only applies to player skulls</li>"
+ "<li>Potions - potions (array of potion arrays), main(int, the id of the main effect)</li>"
+ "</ul>";
@api(environments={CommandHelperEnvironment.class})
public static class get_itemmeta extends AbstractFunction {
@Override
public ExceptionType[] thrown() {
return new ExceptionType[]{ExceptionType.PlayerOfflineException, ExceptionType.CastException};
}
@Override
public boolean isRestricted() {
return true;
}
@Override
public Boolean runAsync() {
return false;
}
@Override
public Construct exec(Target t, Environment environment, Construct... args) throws ConfigRuntimeException {
MCPlayer p = environment.getEnv(CommandHelperEnvironment.class).GetPlayer();
MCItemStack is;
Construct slot;
if(args.length == 2){
p = Static.GetPlayer(args[0], t);
slot = args[1];
} else {
slot = args[0];
}
Static.AssertPlayerNonNull(p, t);
if (slot instanceof CNull) {
is = p.getItemInHand();
} else {
is = p.getItemAt(Static.getInt32(slot, t));
}
if (is == null) {
throw new Exceptions.CastException("There is no item at slot " + slot, t);
}
return ObjectGenerator.GetGenerator().itemMeta(is, t);
}
@Override
public String getName() {
return "get_itemmeta";
}
@Override
public Integer[] numArgs() {
return new Integer[]{1, 2};
}
@Override
public String docs() {
return "mixed {[player,] inventorySlot} Returns an associative array of known ItemMeta for the slot given,"
+ " or null if there isn't any. All items can have a display(name), lore, and/or enchants, "
+ " and more info will be available for the items that have it. ---- Returned keys: "
+ applicableItemMeta;
}
@Override
public CHVersion since() {
return CHVersion.V3_3_1;
}
@Override
public ExampleScript[] examples() throws ConfigCompileException {
return new ExampleScript[]{
new ExampleScript("Demonstrates a generic item without meta", "msg(get_itemmeta(null))",
"null"),
new ExampleScript("Demonstrates a generic item with meta", "msg(get_itemmeta(null))",
"{display: AmazingSword, enchants: {}, lore: {Look at my sword, my sword is amazing}}"),
new ExampleScript("Demonstrates a written book", "msg(get_itemmeta(null))",
"{author: Notch, display: null, enchants: {}, lore: null,"
+ " pages: {This is page 1, This is page 2}, title: Example Book}"),
new ExampleScript("Demonstrates an EnchantedBook", "msg(get_itemmeta(null))",
"{display: null, enchants: {}, lore: null, stored: {{elevel: 1, etype: ARROW_FIRE}}}"),
new ExampleScript("Demonstrates a piece of leather armor", "msg(get_itemmeta(null))",
"{color: {b: 106, g: 160, r: 64}, display: null, enchants: {}, lore: null}"),
new ExampleScript("Demonstrates a skull", "msg(get_itemmeta(null))",
"{display: null, enchants: {}, lore: null, owner: Herobrine}"),
new ExampleScript("Demonstrates a custom potion", "msg(get_itemmeta(null))",
"{display: null, enchants: {}, lore: null, main: 8,"
+ " potions: {{ambient: true, id: 8, seconds: 180, strength: 5}}}")
};
}
}
@api(environments={CommandHelperEnvironment.class})
public static class set_itemmeta extends AbstractFunction {
@Override
public ExceptionType[] thrown() {
return new ExceptionType[]{ExceptionType.PlayerOfflineException, ExceptionType.FormatException, ExceptionType.CastException};
}
@Override
public boolean isRestricted() {
return true;
}
@Override
public Boolean runAsync() {
return false;
}
@Override
public Construct exec(Target t, Environment environment, Construct... args) throws ConfigRuntimeException {
MCPlayer p = environment.getEnv(CommandHelperEnvironment.class).GetPlayer();
Construct slot, meta;
MCItemStack is;
if(args.length == 3){
p = Static.GetPlayer(args[0], t);
slot = args[1];
meta = args[2];
} else {
slot = args[0];
meta = args[1];
}
Static.AssertPlayerNonNull(p, t);
if (slot instanceof CNull) {
is = p.getItemInHand();
} else {
is = p.getItemAt(Static.getInt32(slot, t));
}
if (is == null) {
throw new Exceptions.CastException("There is no item at slot " + slot, t);
}
is.setItemMeta(ObjectGenerator.GetGenerator().itemMeta(meta, is.getType(), t));
return CVoid.VOID;
}
@Override
public String getName() {
return "set_itemmeta";
}
@Override
public Integer[] numArgs() {
return new Integer[]{2, 3};
}
@Override
public String docs() {
return "void {[player,] inventorySlot, ItemMetaArray} Applies the data from the given array to the item at the"
+ " specified slot. Unused fields will be ignored. If null or an empty array is supplied, or if none of"
+ " the given fields are applicable, the item will become default, as this function overwrites any"
+ " existing data. ---- Available fields: " + applicableItemMeta;
}
@Override
public CHVersion since() {
return CHVersion.V3_3_1;
}
@Override
public ExampleScript[] examples() throws ConfigCompileException {
return new ExampleScript[]{
new ExampleScript("Demonstrates removing all meta", "set_itemmeta(null, null)",
"This will make the item in your hand completely ordinary"),
new ExampleScript("Demonstrates a generic item with meta",
"set_itemmeta(null, array(display: 'Amazing Sword', lore: array('Look at my sword', 'my sword is amazing')))",
"The item in your hands is now amazing"),
new ExampleScript("Demonstrates a written book",
"set_itemmeta(null, array(author: 'Writer', pages: array('Once upon a time', 'The end.'), title: 'Epic Story'))",
"This will write a very short story"),
new ExampleScript("Demonstrates an EnchantedBook",
"set_itemmeta(null, array(stored: array(array(elevel: 25, etype: DAMAGE_ALL), array(etype: DURABILITY, elevel: 3))))",
"This book now contains Unbreaking 3 and Sharpness 25"),
new ExampleScript("Demonstrates coloring leather armor",
"set_itemmeta(102, array(color: array(r: 50 b: 150, g: 100)))",
"This will make your chestplate blue-ish"),
new ExampleScript("Demonstrates a skull", "set_itemmeta(103, array(owner: 'Notch'))",
"This puts Notch's skin on the skull you are wearing"),
new ExampleScript("Demonstrates making a custom potion",
"set_itemmeta(5, array(potions: array(id: 8, strength: 4, seconds: 90, ambient: true)))",
"Turns the potion in slot 5 into a Potion of Leaping V")
};
}
}
@api(environments={CommandHelperEnvironment.class})
public static class get_armor_color extends AbstractFunction{
@Override
public ExceptionType[] thrown() {
return new ExceptionType[]{ExceptionType.CastException, ExceptionType.PlayerOfflineException};
}
@Override
public boolean isRestricted() {
return true;
}
@Override
public Boolean runAsync() {
return false;
}
@Override
public Construct exec(Target t, Environment environment, Construct... args) throws ConfigRuntimeException {
MCPlayer p = environment.getEnv(CommandHelperEnvironment.class).GetPlayer();
int slot;
if(args.length == 2){
p = Static.GetPlayer(args[0], t);
slot = Static.getInt32(args[1], t);
} else {
slot = Static.getInt32(args[0], t);
}
Static.AssertPlayerNonNull(p, t);
MCItemStack is = p.getItemAt(slot);
if (is == null) {
throw new Exceptions.CastException("There is no item at slot " + slot, t);
}
MCItemMeta im = is.getItemMeta();
if(im instanceof MCLeatherArmorMeta){
return ObjectGenerator.GetGenerator().color(((MCLeatherArmorMeta)im).getColor(), t);
} else {
throw new Exceptions.CastException("The item at slot " + slot + " is not leather armor.", t);
}
}
@Override
public String getName() {
return "get_armor_color";
}
@Override
public Integer[] numArgs() {
return new Integer[]{1, 2};
}
@Override
public String docs() {
return "colorArray {[player], inventorySlot} Returns a color array for the color of the leather armor at"
+ " the given slot. A CastException is thrown if this is not leather armor at that slot. The color"
+ " array returned will look like: array(r: 0, g: 0, b: 0)";
}
@Override
public CHVersion since() {
return CHVersion.V3_3_1;
}
}
@api(environments={CommandHelperEnvironment.class})
public static class set_armor_color extends AbstractFunction{
@Override
public ExceptionType[] thrown() {
return new ExceptionType[]{ExceptionType.CastException, ExceptionType.PlayerOfflineException, ExceptionType.FormatException};
}
@Override
public boolean isRestricted() {
return true;
}
@Override
public Boolean runAsync() {
return false;
}
@Override
public Construct exec(Target t, Environment environment, Construct... args) throws ConfigRuntimeException {
MCPlayer p = environment.getEnv(CommandHelperEnvironment.class).GetPlayer();
int slot;
CArray color;
if(args.length == 3){
p = Static.GetPlayer(args[0], t);
slot = Static.getInt32(args[1], t);
if (args[2] instanceof CArray) {
color = (CArray)args[2];
} else {
throw new Exceptions.FormatException("Expected an array but recieved " + args[2] + " instead.", t);
}
} else {
slot = Static.getInt32(args[0], t);
if (args[1] instanceof CArray) {
color = (CArray)args[1];
} else {
throw new Exceptions.FormatException("Expected an array but recieved " + args[1] + " instead.", t);
}
}
Static.AssertPlayerNonNull(p, t);
MCItemStack is = p.getItemAt(slot);
if (is == null) {
throw new Exceptions.CastException("There is no item at slot " + slot, t);
}
MCItemMeta im = is.getItemMeta();
if(im instanceof MCLeatherArmorMeta){
((MCLeatherArmorMeta)im).setColor(ObjectGenerator.GetGenerator().color(color, t));
is.setItemMeta(im);
} else {
throw new Exceptions.CastException("The item at slot " + slot + " is not leather armor", t);
}
return CVoid.VOID;
}
@Override
public String getName() {
return "set_armor_color";
}
@Override
public Integer[] numArgs() {
return new Integer[]{2, 3};
}
@Override
public String docs() {
return "void {[player], slot, colorArray} Sets the color of the leather armor at the given slot. colorArray"
+ " should be an array that matches one of the formats: array(r: 0, g: 0, b: 0)"
+ " array(red: 0, green: 0, blue: 0)"
+ " array(0, 0, 0)";
}
@Override
public CHVersion since() {
return CHVersion.V3_3_1;
}
}
@api(environments={CommandHelperEnvironment.class})
public static class is_leather_armor extends AbstractFunction{
@Override
public ExceptionType[] thrown() {
return new ExceptionType[]{ExceptionType.CastException, ExceptionType.PlayerOfflineException};
}
@Override
public boolean isRestricted() {
return true;
}
@Override
public Boolean runAsync() {
return false;
}
@Override
public Construct exec(Target t, Environment environment, Construct... args) throws ConfigRuntimeException {
MCPlayer p = environment.getEnv(CommandHelperEnvironment.class).GetPlayer();
int slot;
if(args.length == 2){
p = Static.GetPlayer(args[0], t);
slot = Static.getInt32(args[1], t);
} else {
slot = Static.getInt32(args[0], t);
}
Static.AssertPlayerNonNull(p, t);
return CBoolean.get(p.getItemAt(slot).getItemMeta() instanceof MCLeatherArmorMeta);
}
@Override
public String getName() {
return "is_leather_armor";
}
@Override
public Integer[] numArgs() {
return new Integer[]{1, 2};
}
@Override
public String docs() {
return "boolean {[player], itemSlot} Returns true if the item at the given slot is a piece of leather"
+ " armor, that is, if dying it is allowed.";
}
@Override
public CHVersion since() {
return CHVersion.V3_3_1;
}
}
}
| |
/*
* Copyright 2016 Flynn van Os
*
* 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.oxapps.tradenotifications;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.support.v4.app.NotificationCompat;
import com.google.android.gms.gcm.GcmNetworkManager;
import com.google.android.gms.gcm.GcmTaskService;
import com.google.android.gms.gcm.TaskParams;
import com.oxapps.tradenotifications.main.MainActivity;
import com.oxapps.tradenotifications.model.ApplicationSettings;
import com.oxapps.tradenotifications.model.ApplicationSettingsImpl;
import com.oxapps.tradenotifications.model.BackgroundTaskScheduler;
import com.oxapps.tradenotifications.model.ConnectionUtils;
import com.oxapps.tradenotifications.model.IntentConsts;
import com.oxapps.tradenotifications.steamapi.TradeOffer;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
public class BackgroundTaskService extends GcmTaskService {
private static final String TAG = "BackgroundTaskService";
private static final String TIME_CREATED_KEY = "time_created";
private static final String OFFER_STATE_KEY = "trade_offer_state";
private String ORIGINAL_URL = "https://api.steampowered.com/IEconService/GetTradeOffers/v1/?key=";
private String URL_OPTIONS_NEW_TRADES = "&format=json&get_sent_offers=0&get_received_offers=1&get_descriptions=0&active_only=1&historical_only=0";
OkHttpClient client = new OkHttpClient();
private ApplicationSettings applicationSettings;
private ConnectionUtils connectionUtils;
@Override
public void onCreate() {
super.onCreate();
applicationSettings = new ApplicationSettingsImpl(this);
connectionUtils = new ConnectionUtils(this);
}
@Override
public void onInitializeTasks() {
super.onInitializeTasks();
long delay = applicationSettings.getNotificationRefreshDelay();
String apiKey = applicationSettings.getApiKey();
if(apiKey.length() == 32 && delay != 0) {
BackgroundTaskScheduler scheduler = new BackgroundTaskScheduler(this);
scheduler.scheduleTask(delay);
}
}
@Override
public int onRunTask(TaskParams taskParams) {
if(!connectionUtils.isInternetAvailable()) {
stopSelf();
return GcmNetworkManager.RESULT_FAILURE;
}
long lastDeleteTime = applicationSettings.getLastDeleteTime();
long lastCheckTime = applicationSettings.getLastCheckTime();
long currentTime = System.currentTimeMillis() / 1000;
String apiKey = applicationSettings.getApiKey();
applicationSettings.setLastCheckTime(currentTime);
getReceivedOffers(apiKey, lastCheckTime, lastDeleteTime);
return GcmNetworkManager.RESULT_SUCCESS;
}
private void removeNotification() {
//No more trade offers so we don't want to be lying to the user
NotificationManager notificationManager =
(NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.cancelAll();
}
private void getReceivedOffers(String apiKey, long lastCheckTime, long lastDeleteTime) {
String url = ORIGINAL_URL + apiKey + URL_OPTIONS_NEW_TRADES;
int newOfferCount = 0;
int newSinceLastCheckCount = 0;
int totalOfferCount = 0;
try {
List<TradeOffer> tradeOffers = getTradeOffers(url);
if (tradeOffers.isEmpty()) {
removeNotification();
return;
}
for (TradeOffer tradeOffer : tradeOffers) {
if(tradeOffer.getTimeCreated() > lastDeleteTime) {
if(tradeOffer.getState() == TradeOffer.STATE_ACTIVE) {
newOfferCount++;
if (tradeOffer.getTimeCreated() > lastCheckTime) {
newSinceLastCheckCount++;
}
}
} else {
break;
}
}
} catch(IOException | JSONException exception) {
exception.printStackTrace();
}
boolean vibrate = newSinceLastCheckCount > 0;
showNewTradeNotification(totalOfferCount, newOfferCount, vibrate);
}
private List<TradeOffer> getTradeOffers(String url) throws IOException, JSONException {
Request request = new Request.Builder()
.url(url)
.build();
Response response = client.newCall(request).execute();
List<TradeOffer> tradeOfferList = new ArrayList<>();
if(response.isSuccessful()) {
JSONObject jsonResponse = new JSONObject(response.body().string()).getJSONObject("response");
if(jsonResponse.length() == 0 ) {
return new ArrayList<>();
}
JSONArray tradeOffers = jsonResponse.getJSONArray("trade_offers_received");
for (int i = 0; i < tradeOffers.length(); i++) {
JSONObject tradeOfferJson = tradeOffers.getJSONObject(i);
long timeCreated = tradeOfferJson.getLong(TIME_CREATED_KEY);
int state = tradeOfferJson.getInt(OFFER_STATE_KEY);
TradeOffer tradeOffer = new TradeOffer(timeCreated, state);
tradeOfferList.add(tradeOffer);
}
} else {
if (response.code() == 403) {
handleBadApiKeyError();
}
}
return tradeOfferList;
}
private void showNewTradeNotification(int totalOfferCount, int newOfferCount, boolean vibrate) {
String titleText = String.valueOf(newOfferCount) + " new trade offer" + ((newOfferCount == 1) ? "" : "s");
String contentText = "You now have " + String.valueOf(totalOfferCount) + " active trade offer" + ((totalOfferCount == 1) ? "" : "s");
Intent deleteIntent = new Intent(this, NotificationDeleteReceiver.class);
PendingIntent pendingDeleteIntent = PendingIntent.getBroadcast(this.getApplicationContext(), 5, deleteIntent, PendingIntent.FLAG_UPDATE_CURRENT);
Intent clickIntent = new Intent(this, NotificationDeleteReceiver.class);
clickIntent.putExtra(IntentConsts.NOTIFICATION_CLICKED, true);
PendingIntent pendingContentIntent = PendingIntent.getBroadcast(this.getApplicationContext(), 6, clickIntent, PendingIntent.FLAG_UPDATE_CURRENT);
NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this)
.setSmallIcon(R.drawable.ic_notif_trade)
.setContentTitle(titleText)
.setContentText(contentText)
.setAutoCancel(true)
.setDeleteIntent(pendingDeleteIntent)
.setContentIntent(pendingContentIntent);
if(vibrate) {
notificationBuilder.setVibrate(new long[]{300, 300, 300, 300, 300});
}
NotificationManager notificationManager =
(NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.notify(10101, notificationBuilder.build());
}
private void handleBadApiKeyError() {
showErrorNotification();
//Cancel scheduled task so we don't get 100s of error notifications
GcmNetworkManager gcmNetworkManager = GcmNetworkManager.getInstance(this);
gcmNetworkManager.cancelAllTasks(BackgroundTaskService.class);
}
private void showErrorNotification() {
Intent clickIntent = new Intent(this, MainActivity.class);
clickIntent.putExtra(IntentConsts.NOTIFICATION_CLICKED, true);
PendingIntent pendingContentIntent = PendingIntent.getActivity(this.getApplicationContext(), 6, clickIntent, 0);
NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this)
.setSmallIcon(R.drawable.ic_notif_error)
.setContentTitle("Error fetching trade offers")
.setContentText("Steam API Key incorrect")
.setAutoCancel(true)
.setContentIntent(pendingContentIntent);
NotificationManager notificationManager =
(NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.notify(403, notificationBuilder.build());
}
}
| |
/*
* 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.cassandra.db.compaction;
import java.io.File;
import java.io.IOException;
import java.util.Arrays;
import java.util.Collection;
import java.util.List;
import java.util.Set;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.Iterables;
import com.google.common.util.concurrent.RateLimiter;
import org.junit.BeforeClass;
import org.junit.After;
import org.junit.Test;
import org.apache.cassandra.config.CFMetaData;
import org.apache.cassandra.db.*;
import org.apache.cassandra.db.lifecycle.LifecycleTransaction;
import org.apache.cassandra.db.rows.EncodingStats;
import org.apache.cassandra.db.lifecycle.SSTableSet;
import org.apache.cassandra.db.rows.UnfilteredRowIterator;
import org.apache.cassandra.dht.ByteOrderedPartitioner.BytesToken;
import org.apache.cassandra.dht.Range;
import org.apache.cassandra.dht.Token;
import org.apache.cassandra.exceptions.ConfigurationException;
import org.apache.cassandra.io.sstable.*;
import org.apache.cassandra.io.sstable.format.SSTableReader;
import org.apache.cassandra.schema.KeyspaceParams;
import org.apache.cassandra.service.ActiveRepairService;
import org.apache.cassandra.SchemaLoader;
import org.apache.cassandra.utils.ByteBufferUtil;
import org.apache.cassandra.utils.concurrent.Refs;
import org.apache.cassandra.UpdateBuilder;
import static org.hamcrest.CoreMatchers.is;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertThat;
import static org.junit.Assert.assertTrue;
public class AntiCompactionTest
{
private static final String KEYSPACE1 = "AntiCompactionTest";
private static final String CF = "AntiCompactionTest";
private static CFMetaData cfm;
@BeforeClass
public static void defineSchema() throws ConfigurationException
{
SchemaLoader.prepareServer();
cfm = SchemaLoader.standardCFMD(KEYSPACE1, CF);
SchemaLoader.createKeyspace(KEYSPACE1,
KeyspaceParams.simple(1),
cfm);
}
@After
public void truncateCF()
{
Keyspace keyspace = Keyspace.open(KEYSPACE1);
ColumnFamilyStore store = keyspace.getColumnFamilyStore(CF);
store.truncateBlocking();
}
@Test
public void antiCompactOne() throws Exception
{
ColumnFamilyStore store = prepareColumnFamilyStore();
Collection<SSTableReader> sstables = getUnrepairedSSTables(store);
assertEquals(store.getLiveSSTables().size(), sstables.size());
Range<Token> range = new Range<Token>(new BytesToken("0".getBytes()), new BytesToken("4".getBytes()));
List<Range<Token>> ranges = Arrays.asList(range);
int repairedKeys = 0;
int nonRepairedKeys = 0;
try (LifecycleTransaction txn = store.getTracker().tryModify(sstables, OperationType.ANTICOMPACTION);
Refs<SSTableReader> refs = Refs.ref(sstables))
{
if (txn == null)
throw new IllegalStateException();
long repairedAt = 1000;
CompactionManager.instance.performAnticompaction(store, ranges, refs, txn, repairedAt);
}
assertEquals(2, store.getLiveSSTables().size());
for (SSTableReader sstable : store.getLiveSSTables())
{
try (ISSTableScanner scanner = sstable.getScanner())
{
while (scanner.hasNext())
{
UnfilteredRowIterator row = scanner.next();
if (sstable.isRepaired())
{
assertTrue(range.contains(row.partitionKey().getToken()));
repairedKeys++;
}
else
{
assertFalse(range.contains(row.partitionKey().getToken()));
nonRepairedKeys++;
}
}
}
}
for (SSTableReader sstable : store.getLiveSSTables())
{
assertFalse(sstable.isMarkedCompacted());
assertEquals(1, sstable.selfRef().globalCount());
}
assertEquals(0, store.getTracker().getCompacting().size());
assertEquals(repairedKeys, 4);
assertEquals(nonRepairedKeys, 6);
}
@Test
public void antiCompactionSizeTest() throws InterruptedException, IOException
{
Keyspace keyspace = Keyspace.open(KEYSPACE1);
ColumnFamilyStore cfs = keyspace.getColumnFamilyStore(CF);
cfs.disableAutoCompaction();
SSTableReader s = writeFile(cfs, 1000);
cfs.addSSTable(s);
long origSize = s.bytesOnDisk();
Range<Token> range = new Range<Token>(new BytesToken(ByteBufferUtil.bytes(0)), new BytesToken(ByteBufferUtil.bytes(500)));
Collection<SSTableReader> sstables = cfs.getLiveSSTables();
try (LifecycleTransaction txn = cfs.getTracker().tryModify(sstables, OperationType.ANTICOMPACTION);
Refs<SSTableReader> refs = Refs.ref(sstables))
{
CompactionManager.instance.performAnticompaction(cfs, Arrays.asList(range), refs, txn, 12345);
}
long sum = 0;
long rows = 0;
for (SSTableReader x : cfs.getLiveSSTables())
{
sum += x.bytesOnDisk();
rows += x.getTotalRows();
}
assertEquals(sum, cfs.metric.liveDiskSpaceUsed.getCount());
assertEquals(rows, 1000 * (1000 * 5));//See writeFile for how this number is derived
assertEquals(origSize, cfs.metric.liveDiskSpaceUsed.getCount(), 16000000);
}
private SSTableReader writeFile(ColumnFamilyStore cfs, int count)
{
File dir = cfs.getDirectories().getDirectoryForNewSSTables();
Descriptor desc = cfs.newSSTableDescriptor(dir);
try (SSTableTxnWriter writer = SSTableTxnWriter.create(cfs, desc, 0, 0, new SerializationHeader(true, cfm, cfm.partitionColumns(), EncodingStats.NO_STATS)))
{
for (int i = 0; i < count; i++)
{
UpdateBuilder builder = UpdateBuilder.create(cfm, ByteBufferUtil.bytes(i));
for (int j = 0; j < count * 5; j++)
builder.newRow("c" + j).add("val", "value1");
writer.append(builder.build().unfilteredIterator());
}
Collection<SSTableReader> sstables = writer.finish(true);
assertNotNull(sstables);
assertEquals(1, sstables.size());
return sstables.iterator().next();
}
}
public void generateSStable(ColumnFamilyStore store, String Suffix)
{
for (int i = 0; i < 10; i++)
{
String localSuffix = Integer.toString(i);
new RowUpdateBuilder(cfm, System.currentTimeMillis(), localSuffix + "-" + Suffix)
.clustering("c")
.add("val", "val" + localSuffix)
.build()
.applyUnsafe();
}
store.forceBlockingFlush();
}
@Test
public void antiCompactTenSTC() throws InterruptedException, IOException
{
antiCompactTen("SizeTieredCompactionStrategy");
}
@Test
public void antiCompactTenLC() throws InterruptedException, IOException
{
antiCompactTen("LeveledCompactionStrategy");
}
public void antiCompactTen(String compactionStrategy) throws InterruptedException, IOException
{
Keyspace keyspace = Keyspace.open(KEYSPACE1);
ColumnFamilyStore store = keyspace.getColumnFamilyStore(CF);
store.disableAutoCompaction();
for (int table = 0; table < 10; table++)
{
generateSStable(store,Integer.toString(table));
}
Collection<SSTableReader> sstables = getUnrepairedSSTables(store);
assertEquals(store.getLiveSSTables().size(), sstables.size());
Range<Token> range = new Range<Token>(new BytesToken("0".getBytes()), new BytesToken("4".getBytes()));
List<Range<Token>> ranges = Arrays.asList(range);
long repairedAt = 1000;
try (LifecycleTransaction txn = store.getTracker().tryModify(sstables, OperationType.ANTICOMPACTION);
Refs<SSTableReader> refs = Refs.ref(sstables))
{
CompactionManager.instance.performAnticompaction(store, ranges, refs, txn, repairedAt);
}
/*
Anticompaction will be anti-compacting 10 SSTables but will be doing this two at a time
so there will be no net change in the number of sstables
*/
assertEquals(10, store.getLiveSSTables().size());
int repairedKeys = 0;
int nonRepairedKeys = 0;
for (SSTableReader sstable : store.getLiveSSTables())
{
try (ISSTableScanner scanner = sstable.getScanner())
{
while (scanner.hasNext())
{
try (UnfilteredRowIterator row = scanner.next())
{
if (sstable.isRepaired())
{
assertTrue(range.contains(row.partitionKey().getToken()));
assertEquals(repairedAt, sstable.getSSTableMetadata().repairedAt);
repairedKeys++;
}
else
{
assertFalse(range.contains(row.partitionKey().getToken()));
assertEquals(ActiveRepairService.UNREPAIRED_SSTABLE, sstable.getSSTableMetadata().repairedAt);
nonRepairedKeys++;
}
}
}
}
}
assertEquals(repairedKeys, 40);
assertEquals(nonRepairedKeys, 60);
}
@Test
public void shouldMutateRepairedAt() throws InterruptedException, IOException
{
ColumnFamilyStore store = prepareColumnFamilyStore();
Collection<SSTableReader> sstables = getUnrepairedSSTables(store);
assertEquals(store.getLiveSSTables().size(), sstables.size());
Range<Token> range = new Range<Token>(new BytesToken("0".getBytes()), new BytesToken("9999".getBytes()));
List<Range<Token>> ranges = Arrays.asList(range);
try (LifecycleTransaction txn = store.getTracker().tryModify(sstables, OperationType.ANTICOMPACTION);
Refs<SSTableReader> refs = Refs.ref(sstables))
{
CompactionManager.instance.performAnticompaction(store, ranges, refs, txn, 1);
}
assertThat(store.getLiveSSTables().size(), is(1));
assertThat(Iterables.get(store.getLiveSSTables(), 0).isRepaired(), is(true));
assertThat(Iterables.get(store.getLiveSSTables(), 0).selfRef().globalCount(), is(1));
assertThat(store.getTracker().getCompacting().size(), is(0));
}
@Test
public void shouldSkipAntiCompactionForNonIntersectingRange() throws InterruptedException, IOException
{
Keyspace keyspace = Keyspace.open(KEYSPACE1);
ColumnFamilyStore store = keyspace.getColumnFamilyStore(CF);
store.disableAutoCompaction();
for (int table = 0; table < 10; table++)
{
generateSStable(store,Integer.toString(table));
}
Collection<SSTableReader> sstables = getUnrepairedSSTables(store);
assertEquals(store.getLiveSSTables().size(), sstables.size());
Range<Token> range = new Range<Token>(new BytesToken("-1".getBytes()), new BytesToken("-10".getBytes()));
List<Range<Token>> ranges = Arrays.asList(range);
try (LifecycleTransaction txn = store.getTracker().tryModify(sstables, OperationType.ANTICOMPACTION);
Refs<SSTableReader> refs = Refs.ref(sstables))
{
CompactionManager.instance.performAnticompaction(store, ranges, refs, txn, 1);
}
assertThat(store.getLiveSSTables().size(), is(10));
assertThat(Iterables.get(store.getLiveSSTables(), 0).isRepaired(), is(false));
}
private ColumnFamilyStore prepareColumnFamilyStore()
{
Keyspace keyspace = Keyspace.open(KEYSPACE1);
ColumnFamilyStore store = keyspace.getColumnFamilyStore(CF);
store.disableAutoCompaction();
for (int i = 0; i < 10; i++)
{
new RowUpdateBuilder(cfm, System.currentTimeMillis(), Integer.toString(i))
.clustering("c")
.add("val", "val")
.build()
.applyUnsafe();
}
store.forceBlockingFlush();
return store;
}
@After
public void truncateCfs()
{
Keyspace keyspace = Keyspace.open(KEYSPACE1);
ColumnFamilyStore store = keyspace.getColumnFamilyStore(CF);
store.truncateBlocking();
}
private static Set<SSTableReader> getUnrepairedSSTables(ColumnFamilyStore cfs)
{
return ImmutableSet.copyOf(cfs.getTracker().getView().sstables(SSTableSet.LIVE, (s) -> !s.isRepaired()));
}
}
| |
package controlP5;
/**
* controlP5 is a processing gui library.
*
* 2006-2012 by Andreas Schlegel
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public License
* as published by the Free Software Foundation; either version 2.1
* of the License, or (at your option) any later version.
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General
* Public License along with this library; if not, write to the
* Free Software Foundation, Inc., 59 Temple Place, Suite 330,
* Boston, MA 02111-1307 USA
*
* @author Andreas Schlegel (http://www.sojamo.de)
* @modified 07/30/2015
* @version 2.2.5
*
*/
import java.util.ArrayList;
import java.util.logging.Level;
import processing.core.PApplet;
import processing.core.PGraphics;
import processing.core.PVector;
import controlP5.ControlP5.Invisible;
/**
* A range slider works just like a slider but can be adjusted on both ends.
*
* @see Slider
* @example controllers/ControlP5range
* @nosuperclasses Controller Controller
*/
public class Range extends Controller< Range > {
/* TODO if range value is int, value labels do initialize as floats. first click makes them
* display as ints without decimal point */
protected static final int HORIZONTAL = 0;
protected static final int VERTICAL = 1;
protected int _myDirection;
protected float _myValuePosition;
protected boolean isDragging;
protected boolean isDraggable = true;
protected boolean isFirstClick;
protected Label _myHighValueLabel;
protected float _myValueRange;
protected boolean isMinHandle;
protected boolean isMaxHandle;
protected boolean isMoveHandle;
protected float distanceHandle;
protected int handleSize = 10;
protected int minHandle = 0;
protected int maxHandle = 0;
protected int mr = 0;
protected final ArrayList< TickMark > _myTickMarks = new ArrayList< TickMark >( );
protected boolean isShowTickMarks;
protected boolean isSnapToTickMarks;
public static int autoWidth = 99;
public static int autoHeight = 9;
public static PVector autoSpacing = new PVector( 0 , 5 , 0 );
public int alignValueLabel = CENTER;
protected int _myColorTickMark = 0xffffffff;
private int mode = -1;
/**
* Convenience constructor to extend Range.
*
* @example use/ControlP5extendController
* @param theControlP5
* @param theName
*/
public Range( ControlP5 theControlP5 , String theName ) {
this( theControlP5 , theControlP5.getDefaultTab( ) , theName , 0 , 100 , 0 , 100 , 0 , 0 , 99 , 9 );
theControlP5.register( theControlP5.papplet , theName , this );
}
/**
*
* @param theControlP5 ControlP5
* @param theParent ControllerGroup
* @param theName String
* @param theMin float
* @param theMax float
* @param theDefaultValue float
* @param theX int
* @param theY int
* @param theWidth int
* @param theHeight int
*/
@ControlP5.Invisible public Range( ControlP5 theControlP5 , ControllerGroup< ? > theParent , String theName , float theMin , float theMax , float theDefaultMinValue , float theDefaultMaxValue , int theX , int theY , int theWidth , int theHeight ) {
super( theControlP5 , theParent , theName , theX , theY , theWidth , theHeight );
_myArrayValue = new float[] { theDefaultMinValue , theDefaultMaxValue };
_myMin = theMin;
_myMax = theMax;
_myValueRange = _myMax - _myMin;
minHandle = ( int ) PApplet.map( theDefaultMinValue , _myMin , _myMax , handleSize , getWidth( ) - handleSize );
maxHandle = ( int ) PApplet.map( theDefaultMaxValue , _myMin , _myMax , handleSize , getWidth( ) - handleSize );
mr = maxHandle - minHandle;
_myCaptionLabel = new Label( cp5 , theName ).setColor( color.getCaptionLabel( ) ).align( RIGHT_OUTSIDE , CENTER );
_myValueLabel = new Label( cp5 , "" + adjustValue( _myMin ) ).setColor( color.getValueLabel( ) ).set( "" + adjustValue( theDefaultMinValue ) ).align( LEFT , CENTER );
_myHighValueLabel = new Label( cp5 , adjustValue( _myMax ) ).setColor( color.getValueLabel( ) ).set( "" + adjustValue( theDefaultMaxValue ) ).align( RIGHT , CENTER );
_myValue = theDefaultMinValue;
_myDirection = HORIZONTAL;
update( );
}
@Override public Range setColorValueLabel( int theColor ) {
_myValueLabel.setColor( theColor );
_myHighValueLabel.setColor( theColor );
return this;
}
@Override public Range setColorCaptionLabel( int theColor ) {
_myCaptionLabel.setColor( theColor );
return this;
}
public Range setHighValueLabel( final String theLabel ) {
_myHighValueLabel.set( theLabel );
return this;
}
public Range setLowValueLabel( final String theLabel ) {
_myValueLabel.set( theLabel );
return this;
}
@ControlP5.Invisible public Range setSliderMode( int theMode ) {
return this;
}
public Range setHandleSize( int theSize ) {
handleSize = theSize;
setLowValue( _myArrayValue[ 0 ] , false );
setHighValue( _myArrayValue[ 1 ] , false );
mr = maxHandle - minHandle;
return this;
}
@ControlP5.Invisible public Range updateInternalEvents( PApplet theApplet ) {
if ( isVisible ) {
int c = _myControlWindow.mouseX - _myControlWindow.pmouseX;
if ( c == 0 ) {
return this;
}
if ( isMousePressed && !cp5.isAltDown( ) ) {
switch ( mode ) {
case ( LEFT ):
minHandle = PApplet.max( handleSize , PApplet.min( maxHandle , minHandle + c ) );
break;
case ( RIGHT ):
maxHandle = PApplet.max( minHandle , PApplet.min( getWidth( ) - handleSize , maxHandle + c ) );
break;
case ( CENTER ):
minHandle = PApplet.max( handleSize , PApplet.min( getWidth( ) - mr - handleSize , minHandle + c ) );
maxHandle = PApplet.max( minHandle , PApplet.min( getWidth( ) - handleSize , minHandle + mr ) );
break;
}
update( );
}
}
return this;
}
@Override @Invisible public void mousePressed( ) {
final float posX = x( _myParent.getAbsolutePosition( ) ) + x( position );
final float posY = y( _myParent.getAbsolutePosition( ) ) + y( position );
if ( _myControlWindow.mouseY < posY || _myControlWindow.mouseY > posY + getHeight( ) ) {
mode = -1;
isMinHandle = isMaxHandle = false;
return;
}
int x0 = ( int ) ( posX + minHandle );
int x1 = ( int ) ( posX + maxHandle );
if ( _myControlWindow.mouseX >= x0 - handleSize && _myControlWindow.mouseX < x0 ) {
mode = LEFT;
isMinHandle = true;
} else if ( _myControlWindow.mouseX >= x1 && _myControlWindow.mouseX < x1 + handleSize ) {
mode = RIGHT;
isMaxHandle = true;
} else if ( _myControlWindow.mouseX > x0 && _myControlWindow.mouseX < x1 && isDraggable ) {
mode = CENTER;
}
}
/**
* set the value of the range-slider. to set the low and high value, use setLowValue and
* setHighValue or setRangeValues
*
* @see #setLowValue(float)
* @see #setHighValue(float)
* @see #setRangeValues(float, float)
*
* @param theValue float
* @return Range
*/
@Override @ControlP5.Invisible public Range setValue( float theValue ) {
_myValue = theValue;
broadcast( ARRAY );
return this;
}
/**
* @exclude
*/
@Override @ControlP5.Invisible public Range update( ) {
_myArrayValue[ 0 ] = PApplet.map( minHandle , handleSize , getWidth( ) - handleSize , _myMin , _myMax );
_myArrayValue[ 1 ] = PApplet.map( maxHandle , handleSize , getWidth( ) - handleSize , _myMin , _myMax );
mr = maxHandle - minHandle;
_myHighValueLabel.set( adjustValue( _myArrayValue[ 1 ] ) );
_myValueLabel.set( adjustValue( _myArrayValue[ 0 ] ) );
return setValue( _myValue );
}
@ControlP5.Invisible public Range setDraggable( boolean theFlag ) {
isDraggable = theFlag;
isDragging = ( theFlag == false ) ? false : isDragging;
return this;
}
public float[] getArrayValue( ) {
return _myArrayValue;
}
@Override public Range setArrayValue( float[] theArray ) {
setLowValue( theArray[ 0 ] , false );
setHighValue( theArray[ 1 ] , false );
return update( );
}
@Override public Range setMin( float theValue ) {
_myMin = theValue;
_myValueRange = _myMax - _myMin;
return setLowValue( _myArrayValue[ 0 ] );
}
@Override public Range setMax( float theValue ) {
_myMax = theValue;
_myValueRange = _myMax - _myMin;
return setHighValue( _myArrayValue[ 1 ] );
}
public float getLowValue( ) {
return _myArrayValue[ 0 ];
}
public float getHighValue( ) {
return _myArrayValue[ 1 ];
}
@Override public Range setWidth( int theValue ) {
super.setWidth( theValue );
return this;
}
@Override public Range setHeight( int theValue ) {
super.setHeight( theValue );
return this;
}
@Override @ControlP5.Invisible public void mouseReleased( ) {
isDragging = isMinHandle = isMaxHandle = isMoveHandle = false;
mode = -1;
}
@Override @ControlP5.Invisible public void mouseReleasedOutside( ) {
mouseReleased( );
}
@Override @ControlP5.Invisible public void onLeave( ) {
isMinHandle = false;
isMaxHandle = false;
}
protected void setTickMarks( ) {
System.out.println( "Range Tickmarks not yet supported" );
}
public Range setColorTickMark( int theColor ) {
_myColorTickMark = theColor;
return this;
}
public Range showTickMarks( boolean theFlag ) {
isShowTickMarks = theFlag;
return this;
}
public Range snapToTickMarks( boolean theFlag ) {
isSnapToTickMarks = theFlag;
System.out.println( "Range Tickmarks not yet supported" );
return this;
}
@ControlP5.Invisible public TickMark getTickMark( ) {
System.out.println( "Range Tickmarks not yet supported" );
return null;
}
public ArrayList< TickMark > getTickMarks( ) {
return _myTickMarks;
}
public Range setNumberOfTickMarks( int theNumber ) {
System.out.println( "Range Tickmarks not yet supported" );
_myTickMarks.clear( );
if ( theNumber > 0 ) {
for ( int i = 0 ; i < theNumber ; i++ ) {
_myTickMarks.add( new TickMark( this ) );
}
showTickMarks( true );
snapToTickMarks( true );
} else {
showTickMarks( false );
snapToTickMarks( false );
}
_myUnit = ( _myMax - _myMin ) / ( ( getWidth( ) > getHeight( ) ) ? getWidth( ) - 1 : getHeight( ) - 1 );
setLowValue( _myArrayValue[ 0 ] , false );
setHighValue( _myArrayValue[ 1 ] , false );
return update( );
}
public Range setRange( float theMinValue , float theMaxValue ) {
setMin( theMinValue );
setMax( theMaxValue );
return this;
}
public Range setRangeValues( float theLowValue , float theHighValue ) {
return setArrayValue( new float[] { theLowValue , theHighValue } );
}
private Range setLowValue( float theValue , boolean isUpdate ) {
_myArrayValue[ 0 ] = PApplet.max( _myMin , snapValue( theValue ) );
minHandle = ( int ) PApplet.map( _myArrayValue[ 0 ] , _myMin , _myMax , handleSize , getWidth( ) - handleSize );
return ( isUpdate ) ? update( ) : this;
}
public Range setLowValue( float theValue ) {
return setLowValue( theValue , true );
}
private Range setHighValue( float theValue , boolean isUpdate ) {
_myArrayValue[ 1 ] = PApplet.min( _myMax , snapValue( theValue ) );
maxHandle = ( int ) PApplet.map( _myArrayValue[ 1 ] , _myMin , _myMax , handleSize , getWidth( ) - handleSize );
return ( isUpdate ) ? update( ) : this;
}
public Range setHighValue( float theValue ) {
return setHighValue( theValue , true );
}
protected float snapValue( float theValue ) {
if ( isMousePressed ) {
return theValue;
}
if ( isSnapToTickMarks ) {
_myValuePosition = ( ( theValue - _myMin ) / _myUnit );
float n = PApplet.round( PApplet.map( _myValuePosition , 0 , ( _myDirection == HORIZONTAL ) ? getWidth( ) : getHeight( ) , 0 , _myTickMarks.size( ) - 1 ) );
theValue = PApplet.map( n , 0 , _myTickMarks.size( ) - 1 , _myMin , _myMax );
}
return theValue;
}
@Override @ControlP5.Invisible public Range updateDisplayMode( int theMode ) {
_myDisplayMode = theMode;
switch ( theMode ) {
case ( DEFAULT ):
_myControllerView = new RangeView( );
break;
case ( SPRITE ):
_myControllerView = new RangeSpriteView( );
break;
case ( IMAGE ):
_myControllerView = new RangeImageView( );
break;
case ( CUSTOM ):
default:
break;
}
return this;
}
class RangeSpriteView implements ControllerView< Range > {
public void display( PGraphics theGraphics , Range theController ) {
ControlP5.logger( ).log( Level.INFO , "RangeSpriteDisplay not available." );
}
}
class RangeView implements ControllerView< Range > {
public void display( PGraphics theGraphics , Range theController ) {
int high = mode;
final float posX = x( _myParent.getAbsolutePosition( ) ) + x( position );
int x0 = ( int ) ( posX + minHandle );
int x1 = ( int ) ( posX + maxHandle );
if ( isInside( ) && high < 0 ) {
if ( _myControlWindow.mouseX >= x0 - handleSize && _myControlWindow.mouseX < x0 ) {
high = LEFT;
} else if ( _myControlWindow.mouseX >= x1 && _myControlWindow.mouseX < x1 + handleSize ) {
high = RIGHT;
} else if ( _myControlWindow.mouseX > x0 && _myControlWindow.mouseX < x1 && isDraggable ) {
high = CENTER;
}
}
theGraphics.pushMatrix( );
theGraphics.fill( color.getBackground( ) );
theGraphics.noStroke( );
theGraphics.rect( 0 , 0 , getWidth( ) , getHeight( ) );
theGraphics.fill( high == CENTER ? color.getActive( ) : color.getForeground( ) );
if ( isShowTickMarks ) {
int n = handleSize / 2;
theGraphics.rect( minHandle - n , 0 , mr + handleSize , getHeight( ) );
theGraphics.fill( ( isMinHandle || high == LEFT ) ? color.getActive( ) : color.getForeground( ) );
theGraphics.triangle( minHandle - handleSize , 0 , minHandle , 0 , minHandle - n , getHeight( ) );
theGraphics.fill( ( isMaxHandle || high == RIGHT ) ? color.getActive( ) : color.getForeground( ) );
theGraphics.triangle( maxHandle , 0 , maxHandle + handleSize , 0 , maxHandle + n , getHeight( ) );
} else {
theGraphics.rect( minHandle , 0 , mr , getHeight( ) );
theGraphics.fill( ( isMinHandle || high == LEFT ) ? color.getActive( ) : color.getForeground( ) );
theGraphics.rect( ( minHandle - handleSize ) , 0 , handleSize , getHeight( ) );
theGraphics.fill( ( isMaxHandle || high == RIGHT ) ? color.getActive( ) : color.getForeground( ) );
theGraphics.rect( maxHandle , 0 , handleSize , getHeight( ) );
}
if ( isLabelVisible ) {
_myCaptionLabel.draw( theGraphics , 0 , 0 , theController );
_myValueLabel.draw( theGraphics , 0 , 0 , theController );
_myHighValueLabel.draw( theGraphics , 0 , 0 , theController );
}
theGraphics.popMatrix( );
if ( isShowTickMarks ) {
theGraphics.pushMatrix( );
float x = ( getWidth( ) - handleSize ) / ( getTickMarks( ).size( ) - 1 );
theGraphics.translate( handleSize / 2 , getHeight( ) );
theGraphics.fill( _myColorTickMark );
for ( TickMark tm : getTickMarks( ) ) {
tm.draw( theGraphics );
theGraphics.translate( x , 0 );
}
theGraphics.popMatrix( );
}
}
}
class RangeImageView implements ControllerView< Range > {
public void display( PGraphics theGraphics , Range theController ) {
ControlP5.logger( ).log( Level.INFO , "RangeImageDisplay not implemented." );
}
}
@Override @ControlP5.Invisible public String toString( ) {
return "type:\tRange\n" + super.toString( );
}
@Deprecated public float lowValue( ) {
return getLowValue( );
}
@Deprecated public float highValue( ) {
return getHighValue( );
}
@Deprecated public float[] arrayValue( ) {
return _myArrayValue;
}
}
| |
package com.hazelcast.simulator.agent.workerprocess;
import com.hazelcast.simulator.common.FailureType;
import com.hazelcast.simulator.protocol.Server;
import com.hazelcast.simulator.protocol.core.SimulatorAddress;
import com.hazelcast.simulator.utils.AssertTask;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.mockito.verification.VerificationMode;
import java.io.File;
import static com.hazelcast.simulator.TestEnvironmentUtils.setupFakeEnvironment;
import static com.hazelcast.simulator.TestEnvironmentUtils.tearDownFakeEnvironment;
import static com.hazelcast.simulator.common.FailureType.WORKER_ABNORMAL_EXIT;
import static com.hazelcast.simulator.common.FailureType.WORKER_EXCEPTION;
import static com.hazelcast.simulator.common.FailureType.WORKER_NORMAL_EXIT;
import static com.hazelcast.simulator.common.FailureType.WORKER_OOME;
import static com.hazelcast.simulator.common.FailureType.WORKER_TIMEOUT;
import static com.hazelcast.simulator.protocol.core.SimulatorAddress.workerAddress;
import static com.hazelcast.simulator.utils.CommonUtils.sleepMillis;
import static com.hazelcast.simulator.utils.CommonUtils.throwableToString;
import static com.hazelcast.simulator.utils.FileUtils.appendText;
import static com.hazelcast.simulator.utils.FileUtils.ensureExistingDirectory;
import static com.hazelcast.simulator.utils.FileUtils.ensureExistingFile;
import static com.hazelcast.simulator.utils.FileUtils.rename;
import static com.hazelcast.simulator.utils.FormatUtils.NEW_LINE;
import static com.hazelcast.simulator.utils.TestUtils.assertTrueEventually;
import static java.lang.System.currentTimeMillis;
import static java.util.concurrent.TimeUnit.HOURS;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import static org.mockito.Matchers.any;
import static org.mockito.Matchers.anyString;
import static org.mockito.Matchers.eq;
import static org.mockito.Mockito.atLeastOnce;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.reset;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.verifyNoMoreInteractions;
import static org.mockito.Mockito.verifyZeroInteractions;
import static org.mockito.Mockito.when;
public class WorkerProcessFailureMonitorTest {
private static final int DEFAULT_TIMEOUT = 30000;
private static final int DEFAULT_LAST_SEEN_TIMEOUT_SECONDS = 30;
private static final int DEFAULT_CHECK_INTERVAL = 30;
private static final int DEFAULT_SLEEP_TIME = 100;
private static int addressIndex;
private WorkerProcessFailureHandler failureHandler;
private WorkerProcessManager workerProcessManager;
private WorkerProcessFailureMonitor workerProcessFailureMonitor;
private File workersHome;
@Before
public void before() {
File simulatorHome = setupFakeEnvironment();
workersHome = new File(simulatorHome, "workers");
failureHandler = mock(WorkerProcessFailureHandler.class);
Server server = mock(Server.class);
workerProcessManager = new WorkerProcessManager(server, SimulatorAddress.fromString("A1"), "127.0.0.1");
workerProcessFailureMonitor = new WorkerProcessFailureMonitor(
failureHandler,
workerProcessManager,
DEFAULT_LAST_SEEN_TIMEOUT_SECONDS,
DEFAULT_CHECK_INTERVAL);
workerProcessFailureMonitor.start();
}
@After
public void after() {
workerProcessFailureMonitor.shutdown();
tearDownFakeEnvironment();
}
@Test
public void testConstructor() {
workerProcessFailureMonitor = new WorkerProcessFailureMonitor(failureHandler, workerProcessManager,
DEFAULT_LAST_SEEN_TIMEOUT_SECONDS);
workerProcessFailureMonitor.start();
verifyZeroInteractions(failureHandler);
}
@Test
public void testRun_shouldSendNoFailures() {
sleepMillis(DEFAULT_SLEEP_TIME);
verifyZeroInteractions(failureHandler);
}
@Test(timeout = DEFAULT_TIMEOUT)
public void testRun_shouldContinueAfterExceptionDuringDetection() {
WorkerProcess workerProcess = addRunningWorkerProcess();
Process process = workerProcess.getProcess();
reset(process);
when(process.exitValue()).thenThrow(new IllegalArgumentException("expected exception"));
sleepMillis(5 * DEFAULT_SLEEP_TIME);
// when we place an oome file; the processing will stop
ensureExistingFile(workerProcess.getWorkerHome(), "worker.oome");
assertTrueEventually(new AssertTask() {
@Override
public void run() throws Exception {
assertFailureType(failureHandler, WORKER_OOME);
}
});
}
@Test
public void testRun_shouldDetectException_withTestId() {
WorkerProcess workerProcess = addRunningWorkerProcess();
String cause = throwableToString(new RuntimeException());
File exceptionFile = createExceptionFile(workerProcess.getWorkerHome(), "WorkerProcessFailureMonitorTest", cause);
System.out.println("ExceptionFile: " + exceptionFile.getAbsolutePath());
sleepMillis(DEFAULT_SLEEP_TIME);
assertFailureTypeAtLeastOnce(failureHandler, WORKER_EXCEPTION);
assertThatExceptionFileDoesNotExist(exceptionFile);
}
@Test
public void testRun_shouldDetectException_withEmptyTestId() {
WorkerProcess workerProcess = addRunningWorkerProcess();
String cause = throwableToString(new RuntimeException());
File exceptionFile = createExceptionFile(workerProcess.getWorkerHome(), "", cause);
sleepMillis(DEFAULT_SLEEP_TIME);
assertFailureTypeAtLeastOnce(failureHandler, WORKER_EXCEPTION);
assertThatExceptionFileDoesNotExist(exceptionFile);
}
@Test
public void testRun_shouldDetectException_withNullTestId() {
WorkerProcess workerProcess = addRunningWorkerProcess();
String cause = throwableToString(new RuntimeException());
File exceptionFile = createExceptionFile(workerProcess.getWorkerHome(), "null", cause);
sleepMillis(DEFAULT_SLEEP_TIME);
assertFailureTypeAtLeastOnce(failureHandler, WORKER_EXCEPTION);
assertThatExceptionFileDoesNotExist(exceptionFile);
}
@Test
public void testRun_shouldDetectOomeFailure_withOomeFile() {
WorkerProcess workerProcess = addRunningWorkerProcess();
ensureExistingFile(workerProcess.getWorkerHome(), "worker.oome");
sleepMillis(DEFAULT_SLEEP_TIME);
assertFailureType(failureHandler, WORKER_OOME);
}
@Test
public void testRun_shouldDetectOomeFailure_withHprofFile() {
WorkerProcess workerProcess = addRunningWorkerProcess();
ensureExistingFile(workerProcess.getWorkerHome(), "java_pid3140.hprof");
sleepMillis(DEFAULT_SLEEP_TIME);
assertFailureType(failureHandler, WORKER_OOME);
}
//@Test
public void testRun_shouldDetectInactivity() {
WorkerProcess workerProcess = addRunningWorkerProcess();
workerProcessFailureMonitor.startTimeoutDetection();
workerProcess.setLastSeen(currentTimeMillis() - HOURS.toMillis(1));
sleepMillis(DEFAULT_SLEEP_TIME);
assertFailureTypeAtLeastOnce(failureHandler, WORKER_TIMEOUT);
}
@Test
public void testRun_shouldNotDetectInactivity_ifDetectionDisabled() {
WorkerProcess workerProcess = addRunningWorkerProcess();
workerProcessFailureMonitor = new WorkerProcessFailureMonitor(failureHandler, workerProcessManager, -1,
DEFAULT_CHECK_INTERVAL);
workerProcessFailureMonitor.start();
workerProcessFailureMonitor.startTimeoutDetection();
workerProcess.setLastSeen(currentTimeMillis() - HOURS.toMillis(1));
sleepMillis(DEFAULT_SLEEP_TIME);
workerProcessFailureMonitor.stopTimeoutDetection();
workerProcess.setLastSeen(currentTimeMillis() - HOURS.toMillis(1));
sleepMillis(DEFAULT_SLEEP_TIME);
verifyZeroInteractions(failureHandler);
}
@Test
public void testRun_shouldNotDetectInactivity_ifDetectionNotStarted() {
WorkerProcess workerProcess = addRunningWorkerProcess();
workerProcess.setLastSeen(currentTimeMillis() - HOURS.toMillis(1));
sleepMillis(DEFAULT_SLEEP_TIME);
verifyZeroInteractions(failureHandler);
}
@Test
public void testRun_shouldNotDetectInactivity_afterDetectionIsStopped() {
WorkerProcess workerProcess = addRunningWorkerProcess();
workerProcessFailureMonitor.startTimeoutDetection();
sleepMillis(DEFAULT_SLEEP_TIME);
workerProcessFailureMonitor.stopTimeoutDetection();
workerProcess.setLastSeen(currentTimeMillis() - HOURS.toMillis(1));
sleepMillis(DEFAULT_SLEEP_TIME);
verifyZeroInteractions(failureHandler);
}
@Test(timeout = DEFAULT_TIMEOUT)
public void testRun_shouldDetectWorkerFinished_whenExitValueIsZero() {
WorkerProcess workerProcess = addWorkerProcess(0);
do {
sleepMillis(DEFAULT_SLEEP_TIME);
} while (!workerProcess.isFinished());
assertTrue(workerProcess.isFinished());
assertFailureType(failureHandler, WORKER_NORMAL_EXIT);
}
@Test
public void testRun_shouldDetectUnexpectedExit_whenExitValueIsNonZero() {
WorkerProcess workerProcess = addWorkerProcess(34);
sleepMillis(DEFAULT_SLEEP_TIME);
assertFalse(workerProcess.isFinished());
assertFailureType(failureHandler, WORKER_ABNORMAL_EXIT);
}
@Test
public void testExceptionExtensionFilter_shouldReturnEmptyFileListIfDirectoryDoesNotExist() {
File[] files = WorkerProcessFailureMonitor.ExceptionExtensionFilter.listFiles(new File("notFound"));
assertEquals(0, files.length);
}
@Test
public void testHProfExtensionFilter_shouldReturnEmptyFileListIfDirectoryDoesNotExist() {
File[] files = WorkerProcessFailureMonitor.HProfExtensionFilter.listFiles(new File("notFound"));
assertEquals(0, files.length);
}
private SimulatorAddress createWorkerAddress() {
return workerAddress(1, ++addressIndex);
}
private WorkerProcess addRunningWorkerProcess() {
return addWorkerProcess(null);
}
private WorkerProcess addWorkerProcess(Integer exitCode) {
SimulatorAddress address = createWorkerAddress();
File sessionHome = new File(workersHome, "sessions");
File workerHome = new File(sessionHome, "worker" + address.getAddressIndex());
ensureExistingDirectory(workerHome);
WorkerProcess workerProcess = new WorkerProcess(address, "WorkerProcessFailureMonitorTest" + address.getAddressIndex(), workerHome);
Process process = mock(Process.class);
if (exitCode == null) {
// this is needed for the failure monitor to believe the process is still running.
when(process.exitValue()).thenThrow(new IllegalThreadStateException());
} else {
when(process.exitValue()).thenReturn(exitCode);
}
workerProcess.setProcess(process);
workerProcessManager.add(address, workerProcess);
return workerProcess;
}
private static File createExceptionFile(File workerHome, String testId, String cause) {
String targetFileName = "1.exception";
File tmpFile = ensureExistingFile(workerHome, targetFileName + "tmp");
File exceptionFile = new File(workerHome, targetFileName);
appendText(testId + NEW_LINE + cause, tmpFile);
rename(tmpFile, exceptionFile);
return exceptionFile;
}
private void assertFailureType(WorkerProcessFailureHandler failureHandler, FailureType failureType) {
assertFailureTypeAtLeastOnce(failureHandler, failureType, times(1));
}
private void assertFailureTypeAtLeastOnce(WorkerProcessFailureHandler failureHandler, FailureType failureType) {
assertFailureTypeAtLeastOnce(failureHandler, failureType, atLeastOnce());
}
private void assertFailureTypeAtLeastOnce(WorkerProcessFailureHandler failureHandler, FailureType failureType, VerificationMode mode) {
verify(failureHandler, mode).handle(anyString(),
eq(failureType),
any(WorkerProcess.class),
any(String.class),
any(String.class));
verifyNoMoreInteractions(failureHandler);
}
private static void assertThatExceptionFileDoesNotExist(final File firstExceptionFile) {
// we use assertTrueEventually because the deletion happens on another thread.
assertTrueEventually(new AssertTask() {
@Override
public void run() throws Exception {
assertFalse("Exception file should be deleted: " + firstExceptionFile, firstExceptionFile.exists());
}
});
}
private static void assertThatRenamedExceptionFileExists(File exceptionFile) {
File expectedFile = new File(exceptionFile.getParentFile(), exceptionFile.getName() + ".sendFailure");
assertTrue("Exception file should be renamed: " + expectedFile.getName(), expectedFile.exists());
}
}
| |
package jp.gauzau.MikuMikuDroid;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map.Entry;
public class MikuMotion implements Serializable {
private static final long serialVersionUID = -6980450493306185580L;
// private static final long serialVersionUID = -7581376490687593200L;
public transient String mFileName;
private transient int mMaxFrame;
private transient HashMap<String, MotionIndexA> mMotion;
private transient HashMap<String, FaceIndexA> mFace;
private transient ArrayList<CameraIndex> mCamera;
private transient HashMap<String, MotionIndexA> mIKMotion;
public boolean mIsTextureLoaded = false;
public MikuMotion(VMDParser vmd) {
mIKMotion = null;
attachVMD(vmd);
}
public void attachVMD(VMDParser vmd) {
mFileName = vmd.getFileName();
if(vmd.getMotion() != null) {
mMotion = new HashMap<String, MotionIndexA>();
for(Entry<String, ArrayList<MotionIndex>> m: vmd.getMotion().entrySet()) {
mMotion.put(m.getKey(), toMotionIndexA(m.getValue()));
}
} else {
mMotion = null;
}
if(vmd.getFace() != null) {
mFace = new HashMap<String, FaceIndexA>();
for(Entry<String, ArrayList<FaceIndex>> f: vmd.getFace().entrySet()) {
mFace.put(f.getKey(), toFaceIndexA(f.getValue()));
}
} else {
mFace = null;
}
mCamera = vmd.getCamera();
mMaxFrame = vmd.maxFrame();
}
public void attachModel(ArrayList<Bone> ba, ArrayList<Face> fa) {
if(ba != null && mMotion != null) {
for(Bone b: ba) {
if(mIKMotion != null) {
b.motion = mIKMotion.get(b.name);
if(b.motion == null) {
b.motion = mMotion.get(b.name);
}
} else {
b.motion = mMotion.get(b.name);
}
b.current_motion = 0;
}
}
if(fa != null && mFace != null) {
for(Face f: fa) {
f.motion = mFace.get(f.name);
f.current_motion = 0;
}
}
}
public static MotionIndexA toMotionIndexA(ArrayList<MotionIndex> m) {
if(m != null) {
boolean nullp = m.get(1).interp == null;
MotionIndexA mia = new MotionIndexA(m.size(), !nullp);
for(int i = 0; i < m.size(); i++) {
MotionIndex mi = m.get(i);
mia.frame_no[i] = mi.frame_no;
System.arraycopy(mi.location, 0, mia.location, i*3, 3);
System.arraycopy(mi.rotation, 0, mia.rotation, i*4, 4);
for(int j = 0; j < 3; j++) {
mia.location_b[i * 3 + j] = (byte) (mi.location[j] * 16);
mia.rotation_b[i * 3 + j] = (byte) (mi.rotation[j] * 256);
}
mia.location_b[i * 3 + 3] = (byte) mi.frame_no;
mia.rotation_b[i * 3 + 3] = (byte) (mi.rotation[3] * 256);
if(mia.interp_x != null) {
if(mi.interp != null) {
for(int j = 0; j < 4; j++) {
mia.interp_x[i * 4 + j] = mi.interp[j * 4 + 0];
mia.interp_y[i * 4 + j] = mi.interp[j * 4 + 1];
mia.interp_z[i * 4 + j] = mi.interp[j * 4 + 2];
mia.interp_a[i * 4 + j] = mi.interp[j * 4 + 3];
}
// System.arraycopy(mi.interp, 0, mia.interp, i*16, 16);
} else {
mia.interp_x[i * 4] = -1; // magic number indicates null
}
}
}
return mia;
} else {
return null;
}
}
public static FaceIndexA toFaceIndexA(ArrayList<FaceIndex> m) {
if(m != null) {
FaceIndexA mia = new FaceIndexA(m.size());
for(int i = 0; i < m.size(); i++) {
FaceIndex mi = m.get(i);
mia.frame_no[i] = mi.frame_no;
mia.weight[i] = mi.weight;
}
return mia;
} else {
return null;
}
}
public int maxFrame() {
return mMaxFrame;
}
public HashMap<String, MotionIndexA> getMotion() {
return mMotion;
}
public HashMap<String, FaceIndexA> getFace() {
return mFace;
}
public HashMap<String, MotionIndexA> getIKMotion() {
return mIKMotion;
}
public void setIKMotion(HashMap<String, ArrayList<MotionIndex>> m) {
mIKMotion = new HashMap<String, MotionIndexA>();
for(Entry<String, ArrayList<MotionIndex>> mi: m.entrySet()) {
mIKMotion.put(mi.getKey(), toMotionIndexA(mi.getValue()));
}
// mIKMotion = toMotionIndexA(m);
}
public MotionPair findMotion(Bone b, float frame, MotionPair mp) {
if (b != null && b.motion != null) {
int[] frame_no = b.motion.frame_no;
mp.m0 = 0;
mp.m1 = b.motion.frame_no.length - 1;
if(frame >= frame_no[mp.m1]) {
mp.m0 = mp.m1;
b.current_motion = mp.m1;
mp.m1 = -1;
return mp;
}
while(true) {
int center = (mp.m0 + mp.m1) / 2;
if(center == mp.m0) {
b.current_motion = center;
return mp;
}
if(frame_no[center] == frame) {
mp.m0 = center;
mp.m1 = -1;
b.current_motion = center;
return mp;
} else if(frame_no[center] > frame) {
mp.m1 = center;
} else {
mp.m0 = center;
}
}
}
return null;
}
public MotionIndex interpolateLinear(MotionPair mp, MotionIndexA mi, float frame, MotionIndex m) {
if (mp == null) {
return null;
} else if (mp.m1 == -1) {
System.arraycopy(mi.location, mp.m0 * 3, m.location, 0, 3);
System.arraycopy(mi.rotation, mp.m0 * 4, m.rotation, 0, 4);
return m;
} else {
int dif = mi.frame_no[mp.m1] - mi.frame_no[mp.m0];
float a0 = frame - mi.frame_no[mp.m0];
float ratio = a0 / dif;
if (mi.interp_x == null || mi.interp_x[mp.m0 * 4] == -1) { // calcurated in preCalcIK
float t = ratio;
m.location[0] = mi.location[mp.m0 * 3 + 0] + (mi.location[mp.m1 * 3 + 0] - mi.location[mp.m0 * 3 + 0]) * t;
m.location[1] = mi.location[mp.m0 * 3 + 1] + (mi.location[mp.m1 * 3 + 1] - mi.location[mp.m0 * 3 + 1]) * t;
m.location[2] = mi.location[mp.m0 * 3 + 2] + (mi.location[mp.m1 * 3 + 2] - mi.location[mp.m0 * 3 + 2]) * t;
slerp(m.rotation, mi.rotation, mi.rotation, mp.m0 * 4, mp.m1 * 4, t);
} else {
double t = bazier(mi.interp_x, mp.m0 * 4, 1, ratio);
m.location[0] = (float) (mi.location[mp.m0 * 3 + 0] + (mi.location[mp.m1 * 3 + 0] - mi.location[mp.m0 * 3 + 0]) * t);
t = bazier(mi.interp_y, mp.m0 * 4, 1, ratio);
m.location[1] = (float) (mi.location[mp.m0 * 3 + 1] + (mi.location[mp.m1 * 3 + 1] - mi.location[mp.m0 * 3 + 1]) * t);
t = bazier(mi.interp_z, mp.m0 * 4, 1, ratio);
m.location[2] = (float) (mi.location[mp.m0 * 3 + 2] + (mi.location[mp.m1 * 3 + 2] - mi.location[mp.m0 * 3 + 2]) * t);
slerp(m.rotation, mi.rotation, mi.rotation, mp.m0 * 4, mp.m1 * 4, bazier(mi.interp_a, mp.m0 * 4, 1, ratio));
}
return m;
}
}
public FacePair findFace(Face b, float frame, FacePair mp) {
if (b != null && b.motion != null) {
int[] frame_no = b.motion.frame_no;
mp.m0 = 0;
mp.m1 = b.motion.frame_no.length - 1;
if(frame >= frame_no[mp.m1]) {
mp.m0 = mp.m1;
b.current_motion = mp.m1;
mp.m1 = -1;
return mp;
}
while(true) {
int center = (mp.m0 + mp.m1) / 2;
if(center == mp.m0) {
b.current_motion = center;
return mp;
}
if(frame_no[center] == frame) {
mp.m0 = center;
mp.m1 = -1;
b.current_motion = center;
return mp;
} else if(frame_no[center] > frame) {
mp.m1 = center;
} else {
mp.m0 = center;
}
}
}
return null;
}
public FaceIndex interpolateLinear(FacePair mp, FaceIndexA mi, float frame, FaceIndex m) {
if (mp == null) {
return null;
} else if (mp.m1 == -1) {
m.frame_no = mi.frame_no[mp.m0];
m.weight = mi.weight[mp.m0];
return m;
} else {
int dif = mi.frame_no[mp.m1] - mi.frame_no[mp.m0];
float a0 = frame - mi.frame_no[mp.m0];
float ratio = a0 / dif;
m.weight = mi.weight[mp.m0] + (mi.weight[mp.m1] - mi.weight[mp.m0]) * ratio;
return m;
}
}
public CameraPair findCamera(float frame, CameraPair mp) {
if (mCamera != null) {
int m0 = 0;
int m1 = mCamera.size() - 1;
mp.m0 = mCamera.get(m0);
mp.m1 = mCamera.get(m1);
if(frame >= mp.m1.frame_no) {
mp.m0 = mp.m1;
mp.m1 = null;
return mp;
}
while(true) {
int center = (m0 + m1) / 2;
if(center == m0) {
return mp;
}
CameraIndex m = mCamera.get(center);
if(m.frame_no == frame) {
mp.m0 = m;
mp.m1 = null;
return mp;
} else if(m.frame_no > frame) {
mp.m1 = m;
m1 = center;
} else {
mp.m0 = m;
m0 = center;
}
}
}
return null;
}
public CameraIndex interpolateLinear(CameraPair mp, float frame, CameraIndex m) {
if (mp == null) {
return null;
} else if (mp.m1 == null) {
return mp.m0;
} else {
int dif = mp.m1.frame_no - mp.m0.frame_no;
if (dif <= 1) { // assume that scene is changed
System.arraycopy(mp.m0.location, 0, m.location, 0, 3);
System.arraycopy(mp.m0.rotation, 0, m.rotation, 0, 3);
m.length = mp.m0.length;
m.view_angle = mp.m0.view_angle;
} else {
float a0 = frame - mp.m0.frame_no;
float ratio = a0 / dif;
double t = bazier(mp.m0.interp, 0, 6, ratio);
m.location[0] = (float) (mp.m0.location[0] + (mp.m1.location[0] - mp.m0.location[0]) * t);
t = bazier(mp.m0.interp, 1, 6, ratio);
m.location[1] = (float) (mp.m0.location[1] + (mp.m1.location[1] - mp.m0.location[1]) * t);
t = bazier(mp.m0.interp, 2, 6, ratio);
m.location[2] = (float) (mp.m0.location[2] + (mp.m1.location[2] - mp.m0.location[2]) * t);
t = bazier(mp.m0.interp, 3, 6, ratio);
m.rotation[0] = (float) (mp.m0.rotation[0] + (mp.m1.rotation[0] - mp.m0.rotation[0]) * t);
m.rotation[1] = (float) (mp.m0.rotation[1] + (mp.m1.rotation[1] - mp.m0.rotation[1]) * t);
m.rotation[2] = (float) (mp.m0.rotation[2] + (mp.m1.rotation[2] - mp.m0.rotation[2]) * t);
t = bazier(mp.m0.interp, 4, 6, ratio);
m.length = (float) (mp.m0.length + (mp.m1.length - mp.m0.length) * t);
t = bazier(mp.m0.interp, 5, 6, ratio);
m.view_angle = (float) (mp.m0.view_angle + (mp.m1.view_angle - mp.m0.view_angle) * t);
}
return m;
}
}
private void slerp(float p[], float[] q, float[] r, int m0, int m1, double t) {
double qr = q[m0 + 0] * r[m1 + 0] + q[m0 + 1] * r[m1 + 1] + q[m0 + 2] * r[m1 + 2] + q[m0 + 3] * r[m1 + 3];
double ss = 1.0 - qr * qr;
if (qr < 0) {
qr = -qr;
double sp = Math.sqrt(ss);
double ph = Math.acos(qr);
double pt = ph * t;
double t1 = Math.sin(pt) / sp;
double t0 = Math.sin(ph - pt) / sp;
if (Double.isNaN(t0) || Double.isNaN(t1)) {
p[0] = q[m0 + 0];
p[1] = q[m0 + 1];
p[2] = q[m0 + 2];
p[3] = q[m0 + 3];
} else {
p[0] = (float) (q[m0 + 0] * t0 - r[m1 + 0] * t1);
p[1] = (float) (q[m0 + 1] * t0 - r[m1 + 1] * t1);
p[2] = (float) (q[m0 + 2] * t0 - r[m1 + 2] * t1);
p[3] = (float) (q[m0 + 3] * t0 - r[m1 + 3] * t1);
}
} else {
double sp = Math.sqrt(ss);
double ph = Math.acos(qr);
double pt = ph * t;
double t1 = Math.sin(pt) / sp;
double t0 = Math.sin(ph - pt) / sp;
if (Double.isNaN(t0) || Double.isNaN(t1)) {
p[0] = q[m0 + 0];
p[1] = q[m0 + 1];
p[2] = q[m0 + 2];
p[3] = q[m0 + 3];
} else {
p[0] = (float) (q[m0 + 0] * t0 + r[m1 + 0] * t1);
p[1] = (float) (q[m0 + 1] * t0 + r[m1 + 1] * t1);
p[2] = (float) (q[m0 + 2] * t0 + r[m1 + 2] * t1);
p[3] = (float) (q[m0 + 3] * t0 + r[m1 + 3] * t1);
}
}
}
private double bazier(byte[] ip, int ofs, int size, float t) {
double xa = ip[ofs] / 256;
double xb = ip[size * 2 + ofs] / 256;
double ya = ip[size + ofs] / 256;
double yb = ip[size * 3 + ofs] / 256;
double min = 0;
double max = 1;
double ct = t;
while (true) {
double x11 = xa * ct;
double x12 = xa + (xb - xa) * ct;
double x13 = xb + (1 - xb) * ct;
double x21 = x11 + (x12 - x11) * ct;
double x22 = x12 + (x13 - x12) * ct;
double x3 = x21 + (x22 - x21) * ct;
if (Math.abs(x3 - t) < 0.0001) {
double y11 = ya * ct;
double y12 = ya + (yb - ya) * ct;
double y13 = yb + (1 - yb) * ct;
double y21 = y11 + (y12 - y11) * ct;
double y22 = y12 + (y13 - y12) * ct;
double y3 = y21 + (y22 - y21) * ct;
return y3;
} else if (x3 < t) {
min = ct;
} else {
max = ct;
}
ct = min * 0.5 + max * 0.5;
}
}
private void writeObject(ObjectOutputStream os) throws IOException {
os.defaultWriteObject();
if(mIKMotion == null) {
os.writeInt(0);
} else {
os.writeInt(mIKMotion.size());
for(Entry<String, MotionIndexA> i: mIKMotion.entrySet()) {
os.writeUTF(i.getKey());
i.getValue().write(os);
}
}
}
private void readObject(ObjectInputStream is) throws IOException, ClassNotFoundException {
is.defaultReadObject();
int hsize = is.readInt();
if(hsize == 0) {
mIKMotion = null;
} else {
mIKMotion = new HashMap<String, MotionIndexA>(hsize);
for(int i = 0; i < hsize; i++) {
String name = is.readUTF();
MotionIndexA mi = new MotionIndexA();
mi.read(is);
mIKMotion.put(name, mi);
}
}
}
}
| |
/*L
* Copyright Washington University at St. Louis
*
* Distributed under the OSI-approved BSD 3-Clause License.
* See http://ncip.github.com/geneconnect/LICENSE.txt for details.
*/
/**
*<p>ClassName: java com.dataminer.server.parser.ExternalParserInvoker</p>
*/
package com.dataminer.server.parser;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.Vector;
import com.dataminer.server.exception.FatalException;
import com.dataminer.server.ftp.FileInfo;
import com.dataminer.server.globals.Utility;
import com.dataminer.server.globals.Variables;
import com.dataminer.server.jobmanager.DPQueue;
import com.dataminer.server.log.Logger;
import com.dataminer.server.parser.Parser;
/**
* This class is used to invoke the external parsers which are plug-in to
* Annotation parser library.
* The external parser command is invoke as :
*
* externalParserCommand -f Configuraion_File
*
* -f The Configuration File containing key value pair of
* BASEDIR
* INPUTFILE
* OUTPUTFILE
* EXTRA_ARGS_IF_ANY
*
* command will be invoked either with -f -option.
*
* The output file should contain the list of filenames
* which has to be load (parsed data) in database by caFE's Database loader.
*
* Base on the configuration it adds the output file names of external parser to queue
* or ignore if writeTODB parameter is set to 'true'.
*
* @author Sachin Lale
* @version 1.0
*/
public class ExternalParserInvoker extends Parser
{
/** Data source being parsed */
private String m_dbType = null;
/** File Info Object describing file or list of files in the same base directory to be parsed*/
private FileInfo m_fileInfo;
protected DPQueue m_filesParsed;
/**
* Constructor method
* @param fileInfo Information of the file to parse
* @param filesParsed List of parsed files
*/
public ExternalParserInvoker(FileInfo fileInfo, DPQueue filesParsed)
{
super(fileInfo, filesParsed);
m_fileInfo=fileInfo;
m_filesParsed = filesParsed;
m_dbType = fileInfo.getDatabaseType();
}
/**
* Method to parse file by invoking external parser command.
* This method builds the argument ot be pass to external parser and
* invokes the command specified in CommandFile.xml
* as <ExternalParser> element.
* Then pushes the parsed data file in queue for DataLoader.
* @param file Information of the file to parse
* @exception FatalException throws exception if error during parsing
*/
public void parse(FileInfo file) throws FatalException
{
try
{
/**Base directory of applcaiton. This is a directory where
* applicatiom stores all output files*/
String baseDir = Variables.currentDir;
baseDir = baseDir.replace('\\','/');
/** Comma separated list of input file names in the same base directory to be passed to the parser*/
String fileNames = file.getFileNames();
/** File Name prefix to be used for config and output file names */
String fileNamePrefix = (String) file.getFiles().firstElement();
/**output file of parser which will contain list of parsed data filr name*/
String outputFile = null;
/**Configuration file name passed as arg with -f option to parser**/
String config_file = fileNamePrefix + ".config";
/**List of Extra arguments to parser*/
Vector extraArgs= m_fileInfo.getExternalParserArg();
FileWriter configWriter = new FileWriter(new File(baseDir+Variables.fileSep+config_file));
configWriter.write("BASEDIR="+baseDir+"\n");
configWriter.write("INPUTFILE="+fileNames+"\n");
if(false==m_fileInfo.IsWriteToDB())
{
outputFile = fileNamePrefix + ".op";
configWriter.write("OUTPUTFILE=" + outputFile+"\n");
}
for(int i=0;i<extraArgs.size();i++)
{
configWriter.write((String)extraArgs.get(i)+"\n");
}
configWriter.close();
StringBuffer parseCommandArguments = new StringBuffer();
parseCommandArguments.append(" -f " + baseDir+Variables.fileSep+config_file);
String parseCommandToExecute= Variables.currentDir + Variables.fileSep +
m_fileInfo.getExternalParserCommanFile() + parseCommandArguments;
/**
* Execute the external parser command
*/
long startTime = System.currentTimeMillis();
System.out.println("Executing Parser: "+parseCommandToExecute);
Process p = Runtime.getRuntime().exec(parseCommandToExecute);
long endTime = System.currentTimeMillis();
Logger.log((endTime-startTime)+" ms. required time(in ms.) to parser files " + fileNames,Logger.INFO);
/**
* Print the output get by executing external parser
*/
InputStream in = p.getInputStream();
InputStreamReader inR = new InputStreamReader( in );
BufferedReader buf = new BufferedReader( inR );
String line;
while ( ( line = buf.readLine() ) != null )
{
//System.out.println("O/P: "+line );
}
buf.close();
inR.close();
in.close();
/** Push parsed data filenames in queue*/
if(outputFile!=null)
{
FileInputStream fileInputStream = new FileInputStream(new File(baseDir+Variables.fileSep+outputFile));
InputStreamReader fileInReader = new InputStreamReader( fileInputStream );
BufferedReader fileReader = new BufferedReader( fileInReader );
String fileNameToPushInQueue;
while ( ( fileNameToPushInQueue = fileReader.readLine() ) != null )
{
m_filesParsed.add(fileNameToPushInQueue);
//System.out.println("fileNameToPushInQueue: "+fileNameToPushInQueue );
}
fileReader.close();
fileInReader.close();
fileInputStream.close();
}
Utility.deleteFile(baseDir+Variables.fileSep+outputFile);
System.out.println("Finished parsing files " + fileNames);
}
catch(Exception e)
{
System.out.println("Exception Invoker: " +e.getMessage());
}
}
/**
* Empty inplementation of super.Open()
*/
protected void open(String fileName)
throws IOException, FileNotFoundException
{
// Emtpy implementation
}
/**
* Empty implemtatation of super.close()
* @throws IOException Throws exception if error during closing file
*/
protected void close() throws IOException
{
// Emtpy implementation
}
/**
* Main Method
* @param arg
*/
static public void main(String arg[])
{
try
{
long st = System.currentTimeMillis();
Runtime run = Runtime.getRuntime();
Process p = run.exec("perl D:/Eclipse/workspace/caFEServer/PerlScripts/Ensembl.pl E:/in.txt E:/ensembl.txt");
InputStream in = p.getInputStream();
InputStreamReader inR = new InputStreamReader( in );
BufferedReader buf = new BufferedReader( inR );
String line;
while ( ( line = buf.readLine() ) != null ) {
System.out.println( line );
}
long et = System.currentTimeMillis();
System.out.println("Time(in ms.):" + (et-st));
StringBuffer cmd = new StringBuffer();
cmd.append("mysqlimport ");
cmd.append("-h " +
"localhost" +
" -u root" +
" --password=mysql123" +
" --fields-terminated-by=###" + " " +
"new"//+" --ignore"
+ " -L "
+ "E:/ensembl.txt");
System.out.println("cmd "+cmd.toString());
//Process sqlldr = run.exec(cmd.toString());
// String filename = "D:/Eclipse/workspace/GeneConnect/sachin.txt";
// FileInputStream fileInputStream = new FileInputStream(new File(filename));
// InputStreamReader fileInReader = new InputStreamReader( fileInputStream );
// BufferedReader fileReader = new BufferedReader( fileInReader );
// String fileNameToPushInQueue;
// while ( ( fileNameToPushInQueue = fileReader.readLine() ) != null )
// {
// System.out.println("fileNameToPushInQueue: "+fileNameToPushInQueue );
// }
// fileReader.close();
// fileInReader.close();
// fileInputStream.close();
System.out.println("Finished");
}
catch(Exception e)
{
System.out.println(e);
}
}
}
| |
package org.gearvrf.widgetlib.widget;
import android.view.GestureDetector;
import android.view.KeyEvent;
import android.view.MotionEvent;
import org.gearvrf.GVRPicker;
import org.gearvrf.GVRSceneObject;
import org.gearvrf.IPickEvents;
import org.gearvrf.ITouchEvents;
import org.gearvrf.io.GVRCursorController;
import org.gearvrf.io.GVRInputManager;
import org.gearvrf.widgetlib.log.Log;
import org.gearvrf.widgetlib.main.WidgetLib;
import org.joml.Vector3f;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import static android.view.MotionEvent.ACTION_DOWN;
import static android.view.MotionEvent.ACTION_MOVE;
import static android.view.MotionEvent.ACTION_UP;
class WidgetPickHandler implements GVRInputManager.ICursorControllerSelectListener,
GVRInputManager.ICursorControllerListener {
private PickEventsListener mPickEventListener = new PickEventsListener();
private TouchEventsListener mTouchEventsListener = new TouchEventsListener();
private ControllerEvent mControllerEvent = new ControllerEvent();
@Override
public void onCursorControllerSelected(GVRCursorController newController,
GVRCursorController oldController) {
if (oldController != null) {
Log.d(Log.SUBSYSTEM.INPUT, TAG,
"onCursorControllerSelected(): removing from old controller (%s)",
oldController.getName());
oldController.setEnable(false);
oldController.removePickEventListener(mPickEventListener);
oldController.removePickEventListener(mTouchEventsListener);
oldController.removeControllerEventListener(mControllerEvent);
}
Log.d(Log.SUBSYSTEM.INPUT, TAG,
"onCursorControllerSelected(): adding to new controller \"%s\" (%s)",
newController.getName(), newController.getClass().getSimpleName());
GVRPicker picker = newController.getPicker();
picker.setPickClosest(false);
newController.addPickEventListener(mPickEventListener);
newController.addPickEventListener(mTouchEventsListener);
newController.addControllerEventListener(mControllerEvent);
newController.setEnable(true);
}
private void dispatchKeyEvent(KeyEvent keyEvent) {
switch (keyEvent.getKeyCode()) {
case KeyEvent.KEYCODE_BACK:
WidgetLib.getTouchManager().handleClick(null, KeyEvent.KEYCODE_BACK);
break;
}
}
@Override
public void onCursorControllerAdded(GVRCursorController gvrCursorController) {
Log.d(Log.SUBSYSTEM.INPUT, TAG,"onCursorControllerAdded: %s",
gvrCursorController.getClass().getSimpleName());
}
@Override
public void onCursorControllerRemoved(GVRCursorController gvrCursorController) {
Log.d(Log.SUBSYSTEM.INPUT, TAG,"onCursorControllerRemoved: %s",
gvrCursorController.getClass().getSimpleName());
gvrCursorController.removePickEventListener(mPickEventListener);
gvrCursorController.removePickEventListener(mTouchEventsListener);
gvrCursorController.removeControllerEventListener(mControllerEvent);
}
static private class PickEventsListener implements IPickEvents {
public void onEnter(final GVRSceneObject sceneObj, final GVRPicker.GVRPickedObject collision) {
WidgetLib.getMainThread().runOnMainThread(new Runnable() {
@Override
public void run() {
Widget widget = WidgetBehavior.getTarget(sceneObj);
if (widget != null && widget.isFocusEnabled()) {
mSelected.add(widget);
Log.d(Log.SUBSYSTEM.FOCUS, TAG, "onEnter(%s): select widget %s",
sceneObj.getName(), widget.getName());
}
}
});
}
public void onExit(final GVRSceneObject sceneObj) {
WidgetLib.getMainThread().runOnMainThread(new Runnable() {
@Override
public void run() {
if (sceneObj != null) {
Widget widget = WidgetBehavior.getTarget(sceneObj);
if (widget != null && mSelected.remove(widget) && !hasFocusGroupMatches(widget)) {
widget.dispatchOnFocus(false);
Log.e(Log.SUBSYSTEM.FOCUS, TAG, "onExit(%s) deselect widget = %s", sceneObj.getName(), widget.getName());
}
}
}
});
}
private boolean hasFocusGroupMatches(Widget widget) {
for (Widget sel: mSelected) {
Log.d(TAG, "hasFocusGroupMatches : widget [%s] sel [%s] = %b", widget.getName(), sel.getName(),
widget.isFocusHandlerMatchWith(sel));
if (widget.isFocusHandlerMatchWith(sel)) {
return true;
}
}
return false;
}
public void onPick(final GVRPicker picker) {
if (picker.hasPickListChanged()) {
final List<GVRPicker.GVRPickedObject> pickedList = Arrays.asList(picker.getPicked());
WidgetLib.getMainThread().runOnMainThread(new Runnable() {
@Override
public void run() {
for (GVRPicker.GVRPickedObject hit : pickedList) {
Widget widget = WidgetBehavior.getTarget(hit.hitObject);
if (widget != null && mSelected.contains(widget) &&
(widget.isFocused() ||
widget.dispatchOnFocus(true))) {
Log.d(Log.SUBSYSTEM.FOCUS, TAG, "onPick(%s) widget focused %s",
hit.hitObject.getName(), widget.getName());
break;
}
}
}
});
}
}
public void onNoPick(final GVRPicker picker) {
if (picker.hasPickListChanged()) {
WidgetLib.getMainThread().runOnMainThread(new Runnable() {
@Override
public void run() {
Log.d(Log.SUBSYSTEM.FOCUS, TAG, "onNoPick(): selection cleared");
mSelected.clear();
}
});
}
}
private final Set<Widget> mSelected = new HashSet<>();
public void onInside(GVRSceneObject sceneObj, GVRPicker.GVRPickedObject collision) {
}
}
static private class TouchEventsListener implements ITouchEvents {
public void onTouchStart(final GVRSceneObject sceneObj, final GVRPicker.GVRPickedObject collision) {
WidgetLib.getMainThread().runOnMainThread(new Runnable() {
@Override
public void run() {
Log.d(Log.SUBSYSTEM.INPUT, TAG, "onTouchStart(%s)", sceneObj.getName());
Widget widget = WidgetBehavior.getTarget(sceneObj);
if (widget != null && widget.isTouchable() && !mTouched.contains(widget)) {
Log.d(Log.SUBSYSTEM.INPUT, TAG, "onTouchStart(%s) start touch widget %s",
sceneObj.getName(), widget.getName());
mTouched.add(widget);
}
}
});
}
public void onTouchEnd(final GVRSceneObject sceneObj, final GVRPicker.GVRPickedObject collision) {
WidgetLib.getMainThread().runOnMainThread(new Runnable() {
@Override
public void run() {
Log.d(Log.SUBSYSTEM.INPUT, TAG, "onTouchEnd(%s)", sceneObj.getName());
Widget widget = WidgetBehavior.getTarget(sceneObj);
if (widget != null && widget.isTouchable() && mTouched.contains(widget)) {
if (widget.dispatchOnTouch(sceneObj, collision.hitLocation)) {
Log.d(Log.SUBSYSTEM.INPUT, TAG, "onTouchEnd(%s) end touch widget %s",
sceneObj.getName(), widget.getName());
mTouched.clear();
} else {
mTouched.remove(widget);
}
}
}
});
}
public void onExit(GVRSceneObject sceneObj, GVRPicker.GVRPickedObject collision) {
}
public void onMotionOutside(final GVRPicker picker, final MotionEvent event) {
WidgetLib.getMainThread().runOnMainThread(new Runnable() {
@Override
public void run() {
if (mFlingHandler != null) {
GestureDetector gestureDetector = new GestureDetector(
picker.getGVRContext().getContext(), mGestureListener);
gestureDetector.onTouchEvent(event);
Vector3f pos = new Vector3f();
Log.d(Log.SUBSYSTEM.INPUT, TAG, "onMotionOutside() event = %s mFling = %s", event, mFling);
switch (event.getAction()) {
case ACTION_DOWN:
mFlingHandler.onStartFling(event, picker.getController().getPosition(pos));
break;
case ACTION_MOVE:
mFlingHandler.onFling(event, picker.getController().getPosition(pos));
break;
case ACTION_UP:
mFlingHandler.onEndFling(mFling);
break;
}
}
}
});
}
private final List<Widget> mTouched = new ArrayList<>();
private FlingHandler mFlingHandler;
public void onEnter(GVRSceneObject sceneObj, GVRPicker.GVRPickedObject collision) {
}
public void onInside(GVRSceneObject sceneObj, GVRPicker.GVRPickedObject collision) {
}
private FlingHandler.FlingAction mFling;
private GestureDetector.OnGestureListener mGestureListener = new GestureDetector.OnGestureListener() {
class Fling implements FlingHandler.FlingAction {
MotionEvent startEvent;
MotionEvent endEvent;
float velocityX;
float velocityY;
Fling(MotionEvent e1, MotionEvent e2, float vX, float vY) {
startEvent = MotionEvent.obtain(e1);
endEvent = MotionEvent.obtain(e2);
velocityX = vX;
velocityY = vY;
}
@Override
public String toString() {
return "startEvent: " + startEvent + " endEvemnt = " + endEvent
+ " velocityX = " + velocityX + " velosityY = " + velocityY;
}
@Override
public void clear() {
startEvent.recycle();
endEvent.recycle();
}
@Override
public MotionEvent getStartEvent() {
return startEvent;
}
@Override
public MotionEvent getEndEvent() {
return endEvent;
}
@Override
public float getVelocityX() {
return velocityX;
}
@Override
public float getVelocityY() {
return velocityY;
}
}
private void setFling(MotionEvent e1, MotionEvent e2, float vX, float vY) {
if (e1 != null && e2 != null) {
if (mFling != null) {
mFling.clear();
}
mFling = new Fling(e1, e2, vX, vY);
}
}
public boolean onDown(MotionEvent e) {
Log.d(Log.SUBSYSTEM.INPUT, TAG, "onDown e = %s", e);
return true;
}
public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX,
float velocityY) {
Log.d(Log.SUBSYSTEM.INPUT, TAG, "onFling event1: " + e1 + " event2: " + e2
+ " velocityX = " + velocityX + " velocityY = " + velocityY);
setFling(e1, e2, velocityX, velocityY);
return true;
}
public void onLongPress(MotionEvent e) {
Log.d(Log.SUBSYSTEM.INPUT, TAG, "onLongPress e = %s", e);
}
public boolean onScroll(MotionEvent e1, MotionEvent e2,
float distanceX, float distanceY) {
Log.d(Log.SUBSYSTEM.INPUT, TAG, "onScroll e1 = %s, e2 = %s distanceX = %f, distanceY = %f",
e1, e2, distanceX, distanceY);
return true;
}
public void onShowPress(MotionEvent e) {
Log.d(Log.SUBSYSTEM.INPUT, TAG, "onShowPress e = %s", e);
}
public boolean onSingleTapUp(MotionEvent e) {
Log.d(Log.SUBSYSTEM.INPUT, TAG, "onSingleTapUp e = %s", e);
return true;
}
};
}
private class ControllerEvent implements GVRCursorController.IControllerEvent {
@Override
public void onEvent(GVRCursorController controller, boolean isActive) {
if (controller != null) {
final List<KeyEvent> keyEvents = controller.getKeyEvents();
Log.d(Log.SUBSYSTEM.INPUT, TAG, "onEvent(): Key events:");
for (KeyEvent keyEvent : keyEvents) {
Log.d(Log.SUBSYSTEM.INPUT, TAG, "onEvent(): keyCode: %d",
keyEvent.getKeyCode());
if (keyEvent.getAction() == KeyEvent.ACTION_UP) {
dispatchKeyEvent(keyEvent);
}
}
}
}
}
private static final String TAG = WidgetPickHandler.class.getSimpleName();
void setFlingHandler(FlingHandler flingHandler ) {
mTouchEventsListener.mFlingHandler = flingHandler;
}
FlingHandler getFlingHandler() {
return mTouchEventsListener.mFlingHandler;
}
}
| |
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.http.HC4.impl.io;
import java.io.IOException;
import java.io.InputStream;
import org.apache.http.HC4.ConnectionClosedException;
import org.apache.http.HC4.Header;
import org.apache.http.HC4.HttpException;
import org.apache.http.HC4.MalformedChunkCodingException;
import org.apache.http.HC4.TruncatedChunkException;
import org.apache.http.HC4.annotation.NotThreadSafe;
import org.apache.http.HC4.config.MessageConstraints;
import org.apache.http.HC4.io.BufferInfo;
import org.apache.http.HC4.io.SessionInputBuffer;
import org.apache.http.HC4.util.Args;
import org.apache.http.HC4.impl.io.AbstractMessageParser;
import org.apache.http.HC4.util.CharArrayBuffer;
/**
* Implements chunked transfer coding. The content is received in small chunks.
* Entities transferred using this input stream can be of unlimited length.
* After the stream is read to the end, it provides access to the trailers,
* if any.
* <p>
* Note that this class NEVER closes the underlying stream, even when close
* gets called. Instead, it will read until the "end" of its chunking on
* close, which allows for the seamless execution of subsequent HTTP 1.1
* requests, while not requiring the client to remember to read the entire
* contents of the response.
*
*
* @since 4.0
*
*/
@NotThreadSafe
public class ChunkedInputStream extends InputStream {
private static final int CHUNK_LEN = 1;
private static final int CHUNK_DATA = 2;
private static final int CHUNK_CRLF = 3;
private static final int CHUNK_INVALID = Integer.MAX_VALUE;
private static final int BUFFER_SIZE = 2048;
/** The session input buffer */
private final SessionInputBuffer in;
private final CharArrayBuffer buffer;
private final MessageConstraints constraints;
private int state;
/** The chunk size */
private int chunkSize;
/** The current position within the current chunk */
private int pos;
/** True if we've reached the end of stream */
private boolean eof = false;
/** True if this stream is closed */
private boolean closed = false;
private Header[] footers = new Header[] {};
/**
* Wraps session input stream and reads chunk coded input.
*
* @param in The session input buffer
* @param constraints Message constraints. If {@code null}
* {@link MessageConstraints#DEFAULT} will be used.
*
* @since 4.4
*/
public ChunkedInputStream(final SessionInputBuffer in, final MessageConstraints constraints) {
super();
this.in = Args.notNull(in, "Session input buffer");
this.pos = 0;
this.buffer = new CharArrayBuffer(16);
this.constraints = constraints != null ? constraints : MessageConstraints.DEFAULT;
this.state = CHUNK_LEN;
}
/**
* Wraps session input stream and reads chunk coded input.
*
* @param in The session input buffer
*/
public ChunkedInputStream(final SessionInputBuffer in) {
this(in, null);
}
@Override
public int available() throws IOException {
if (this.in instanceof BufferInfo) {
final int len = ((BufferInfo) this.in).length();
return Math.min(len, this.chunkSize - this.pos);
} else {
return 0;
}
}
/**
* <p> Returns all the data in a chunked stream in coalesced form. A chunk
* is followed by a CRLF. The method returns -1 as soon as a chunksize of 0
* is detected.</p>
*
* <p> Trailer headers are read automatically at the end of the stream and
* can be obtained with the getResponseFooters() method.</p>
*
* @return -1 of the end of the stream has been reached or the next data
* byte
* @throws IOException in case of an I/O error
*/
@Override
public int read() throws IOException {
if (this.closed) {
throw new IOException("Attempted read from closed stream.");
}
if (this.eof) {
return -1;
}
if (state != CHUNK_DATA) {
nextChunk();
if (this.eof) {
return -1;
}
}
final int b = in.read();
if (b != -1) {
pos++;
if (pos >= chunkSize) {
state = CHUNK_CRLF;
}
}
return b;
}
/**
* Read some bytes from the stream.
* @param b The byte array that will hold the contents from the stream.
* @param off The offset into the byte array at which bytes will start to be
* placed.
* @param len the maximum number of bytes that can be returned.
* @return The number of bytes returned or -1 if the end of stream has been
* reached.
* @throws IOException in case of an I/O error
*/
@Override
public int read (final byte[] b, final int off, final int len) throws IOException {
if (closed) {
throw new IOException("Attempted read from closed stream.");
}
if (eof) {
return -1;
}
if (state != CHUNK_DATA) {
nextChunk();
if (eof) {
return -1;
}
}
final int bytesRead = in.read(b, off, Math.min(len, chunkSize - pos));
if (bytesRead != -1) {
pos += bytesRead;
if (pos >= chunkSize) {
state = CHUNK_CRLF;
}
return bytesRead;
} else {
eof = true;
throw new TruncatedChunkException("Truncated chunk "
+ "( expected size: " + chunkSize
+ "; actual size: " + pos + ")");
}
}
/**
* Read some bytes from the stream.
* @param b The byte array that will hold the contents from the stream.
* @return The number of bytes returned or -1 if the end of stream has been
* reached.
* @throws IOException in case of an I/O error
*/
@Override
public int read (final byte[] b) throws IOException {
return read(b, 0, b.length);
}
/**
* Read the next chunk.
* @throws IOException in case of an I/O error
*/
private void nextChunk() throws IOException {
if (state == CHUNK_INVALID) {
throw new MalformedChunkCodingException("Corrupt data stream");
}
try {
chunkSize = getChunkSize();
if (chunkSize < 0) {
throw new MalformedChunkCodingException("Negative chunk size");
}
state = CHUNK_DATA;
pos = 0;
if (chunkSize == 0) {
eof = true;
parseTrailerHeaders();
}
} catch (MalformedChunkCodingException ex) {
state = CHUNK_INVALID;
throw ex;
}
}
/**
* Expects the stream to start with a chunksize in hex with optional
* comments after a semicolon. The line must end with a CRLF: "a3; some
* comment\r\n" Positions the stream at the start of the next line.
*/
private int getChunkSize() throws IOException {
final int st = this.state;
switch (st) {
case CHUNK_CRLF:
this.buffer.clear();
final int bytesRead1 = this.in.readLine(this.buffer);
if (bytesRead1 == -1) {
throw new MalformedChunkCodingException(
"CRLF expected at end of chunk");
}
if (!this.buffer.isEmpty()) {
throw new MalformedChunkCodingException(
"Unexpected content at the end of chunk");
}
state = CHUNK_LEN;
//$FALL-THROUGH$
case CHUNK_LEN:
this.buffer.clear();
final int bytesRead2 = this.in.readLine(this.buffer);
if (bytesRead2 == -1) {
throw new ConnectionClosedException("Premature end of chunk coded message body: " +
"closing chunk expected");
}
int separator = this.buffer.indexOf(';');
if (separator < 0) {
separator = this.buffer.length();
}
try {
return Integer.parseInt(this.buffer.substringTrimmed(0, separator), 16);
} catch (final NumberFormatException e) {
throw new MalformedChunkCodingException("Bad chunk header");
}
default:
throw new IllegalStateException("Inconsistent codec state");
}
}
/**
* Reads and stores the Trailer headers.
* @throws IOException in case of an I/O error
*/
private void parseTrailerHeaders() throws IOException {
try {
this.footers = AbstractMessageParser.parseHeaders(in,
constraints.getMaxHeaderCount(),
constraints.getMaxLineLength(),
null);
} catch (final HttpException ex) {
final IOException ioe = new MalformedChunkCodingException("Invalid footer: "
+ ex.getMessage());
ioe.initCause(ex);
throw ioe;
}
}
/**
* Upon close, this reads the remainder of the chunked message,
* leaving the underlying socket at a position to start reading the
* next response without scanning.
* @throws IOException in case of an I/O error
*/
@Override
public void close() throws IOException {
if (!closed) {
try {
if (!eof && state != CHUNK_INVALID) {
// read and discard the remainder of the message
final byte buff[] = new byte[BUFFER_SIZE];
while (read(buff) >= 0) {
}
}
} finally {
eof = true;
closed = true;
}
}
}
public Header[] getFooters() {
return this.footers.clone();
}
}
| |
package org.spongycastle.openpgp;
import java.io.IOException;
import java.io.OutputStream;
import java.security.SecureRandom;
import java.util.ArrayList;
import java.util.List;
import org.spongycastle.bcpg.BCPGOutputStream;
import org.spongycastle.bcpg.HashAlgorithmTags;
import org.spongycastle.bcpg.PacketTags;
import org.spongycastle.bcpg.SymmetricKeyAlgorithmTags;
import org.spongycastle.openpgp.operator.PBEKeyEncryptionMethodGenerator;
import org.spongycastle.openpgp.operator.PGPDataEncryptor;
import org.spongycastle.openpgp.operator.PGPDataEncryptorBuilder;
import org.spongycastle.openpgp.operator.PGPDigestCalculator;
import org.spongycastle.openpgp.operator.PGPKeyEncryptionMethodGenerator;
import org.spongycastle.util.io.TeeOutputStream;
/**
* Generator for encrypted objects.
*/
public class PGPEncryptedDataGenerator
implements SymmetricKeyAlgorithmTags, StreamGenerator
{
/**
* Specifier for SHA-1 S2K PBE generator.
*/
public static final int S2K_SHA1 = HashAlgorithmTags.SHA1;
/**
* Specifier for SHA-224 S2K PBE generator.
*/
public static final int S2K_SHA224 = HashAlgorithmTags.SHA224;
/**
* Specifier for SHA-256 S2K PBE generator.
*/
public static final int S2K_SHA256 = HashAlgorithmTags.SHA256;
/**
* Specifier for SHA-384 S2K PBE generator.
*/
public static final int S2K_SHA384 = HashAlgorithmTags.SHA384;
/**
* Specifier for SHA-512 S2K PBE generator.
*/
public static final int S2K_SHA512 = HashAlgorithmTags.SHA512;
private BCPGOutputStream pOut;
private OutputStream cOut;
private boolean oldFormat = false;
private PGPDigestCalculator digestCalc;
private OutputStream genOut;
private PGPDataEncryptorBuilder dataEncryptorBuilder;
private List methods = new ArrayList();
private int defAlgorithm;
private SecureRandom rand;
/**
* Base constructor.
*
* @param encryptorBuilder builder to create actual data encryptor.
*/
public PGPEncryptedDataGenerator(PGPDataEncryptorBuilder encryptorBuilder)
{
this(encryptorBuilder, false);
}
/**
* Base constructor with the option to turn on formatting for PGP 2.6.x compatibility.
*
* @param encryptorBuilder builder to create actual data encryptor.
* @param oldFormat PGP 2.6.x compatibility required.
*/
public PGPEncryptedDataGenerator(PGPDataEncryptorBuilder encryptorBuilder, boolean oldFormat)
{
this.dataEncryptorBuilder = encryptorBuilder;
this.oldFormat = oldFormat;
this.defAlgorithm = dataEncryptorBuilder.getAlgorithm();
this.rand = dataEncryptorBuilder.getSecureRandom();
}
/**
* Added a key encryption method to be used to encrypt the session data associated
* with this encrypted data.
*
* @param method key encryption method to use.
*/
public void addMethod(PGPKeyEncryptionMethodGenerator method)
{
methods.add(method);
}
private void addCheckSum(
byte[] sessionInfo)
{
int check = 0;
for (int i = 1; i != sessionInfo.length - 2; i++)
{
check += sessionInfo[i] & 0xff;
}
sessionInfo[sessionInfo.length - 2] = (byte)(check >> 8);
sessionInfo[sessionInfo.length - 1] = (byte)(check);
}
private byte[] createSessionInfo(
int algorithm,
byte[] keyBytes)
{
byte[] sessionInfo = new byte[keyBytes.length + 3];
sessionInfo[0] = (byte) algorithm;
System.arraycopy(keyBytes, 0, sessionInfo, 1, keyBytes.length);
addCheckSum(sessionInfo);
return sessionInfo;
}
/**
* If buffer is non null stream assumed to be partial, otherwise the
* length will be used to output a fixed length packet.
* <p>
* The stream created can be closed off by either calling close()
* on the stream or close() on the generator. Closing the returned
* stream does not close off the OutputStream parameter out.
*
* @param out
* @param length
* @param buffer
* @return
* @throws java.io.IOException
* @throws PGPException
* @throws IllegalStateException
*/
private OutputStream open(
OutputStream out,
long length,
byte[] buffer)
throws IOException, PGPException, IllegalStateException
{
if (cOut != null)
{
throw new IllegalStateException("generator already in open state");
}
if (methods.size() == 0)
{
throw new IllegalStateException("no encryption methods specified");
}
byte[] key = null;
pOut = new BCPGOutputStream(out);
defAlgorithm = dataEncryptorBuilder.getAlgorithm();
rand = dataEncryptorBuilder.getSecureRandom();
if (methods.size() == 1)
{
if (methods.get(0) instanceof PBEKeyEncryptionMethodGenerator)
{
PBEKeyEncryptionMethodGenerator m = (PBEKeyEncryptionMethodGenerator)methods.get(0);
key = m.getKey(dataEncryptorBuilder.getAlgorithm());
pOut.writePacket(((PGPKeyEncryptionMethodGenerator)methods.get(0)).generate(defAlgorithm, null));
}
else
{
key = PGPUtil.makeRandomKey(defAlgorithm, rand);
byte[] sessionInfo = createSessionInfo(defAlgorithm, key);
PGPKeyEncryptionMethodGenerator m = (PGPKeyEncryptionMethodGenerator)methods.get(0);
pOut.writePacket(m.generate(defAlgorithm, sessionInfo));
}
}
else // multiple methods
{
key = PGPUtil.makeRandomKey(defAlgorithm, rand);
byte[] sessionInfo = createSessionInfo(defAlgorithm, key);
for (int i = 0; i != methods.size(); i++)
{
PGPKeyEncryptionMethodGenerator m = (PGPKeyEncryptionMethodGenerator)methods.get(i);
pOut.writePacket(m.generate(defAlgorithm, sessionInfo));
}
}
try
{
PGPDataEncryptor dataEncryptor = dataEncryptorBuilder.build(key);
digestCalc = dataEncryptor.getIntegrityCalculator();
if (buffer == null)
{
//
// we have to add block size + 2 for the generated IV and + 1 + 22 if integrity protected
//
if (digestCalc != null)
{
pOut = new ClosableBCPGOutputStream(out, PacketTags.SYM_ENC_INTEGRITY_PRO, length + dataEncryptor.getBlockSize() + 2 + 1 + 22);
pOut.write(1); // version number
}
else
{
pOut = new ClosableBCPGOutputStream(out, PacketTags.SYMMETRIC_KEY_ENC, length + dataEncryptor.getBlockSize() + 2, oldFormat);
}
}
else
{
if (digestCalc != null)
{
pOut = new ClosableBCPGOutputStream(out, PacketTags.SYM_ENC_INTEGRITY_PRO, buffer);
pOut.write(1); // version number
}
else
{
pOut = new ClosableBCPGOutputStream(out, PacketTags.SYMMETRIC_KEY_ENC, buffer);
}
}
genOut = cOut = dataEncryptor.getOutputStream(pOut);
if (digestCalc != null)
{
genOut = new TeeOutputStream(digestCalc.getOutputStream(), cOut);
}
byte[] inLineIv = new byte[dataEncryptor.getBlockSize() + 2];
rand.nextBytes(inLineIv);
inLineIv[inLineIv.length - 1] = inLineIv[inLineIv.length - 3];
inLineIv[inLineIv.length - 2] = inLineIv[inLineIv.length - 4];
genOut.write(inLineIv);
return new WrappedGeneratorStream(genOut, this);
}
catch (Exception e)
{
throw new PGPException("Exception creating cipher", e);
}
}
/**
* Return an outputstream which will encrypt the data as it is written
* to it.
* <p>
* The stream created can be closed off by either calling close()
* on the stream or close() on the generator. Closing the returned
* stream does not close off the OutputStream parameter out.
*
* @param out
* @param length
* @return OutputStream
* @throws IOException
* @throws PGPException
*/
public OutputStream open(
OutputStream out,
long length)
throws IOException, PGPException
{
return this.open(out, length, null);
}
/**
* Return an outputstream which will encrypt the data as it is written
* to it. The stream will be written out in chunks according to the size of the
* passed in buffer.
* <p>
* The stream created can be closed off by either calling close()
* on the stream or close() on the generator. Closing the returned
* stream does not close off the OutputStream parameter out.
* <p>
* <b>Note</b>: if the buffer is not a power of 2 in length only the largest power of 2
* bytes worth of the buffer will be used.
*
* @param out
* @param buffer the buffer to use.
* @return OutputStream
* @throws IOException
* @throws PGPException
*/
public OutputStream open(
OutputStream out,
byte[] buffer)
throws IOException, PGPException
{
return this.open(out, 0, buffer);
}
/**
* Close off the encrypted object - this is equivalent to calling close on the stream
* returned by the open() method.
* <p>
* <b>Note</b>: This does not close the underlying output stream, only the stream on top of it created by the open() method.
* @throws java.io.IOException
*/
public void close()
throws IOException
{
if (cOut != null)
{
if (digestCalc != null)
{
//
// hand code a mod detection packet
//
BCPGOutputStream bOut = new BCPGOutputStream(genOut, PacketTags.MOD_DETECTION_CODE, 20);
bOut.flush();
byte[] dig = digestCalc.getDigest();
cOut.write(dig);
}
cOut.close();
cOut = null;
pOut = null;
}
}
private class ClosableBCPGOutputStream
extends BCPGOutputStream
{
public ClosableBCPGOutputStream(OutputStream out, int symmetricKeyEnc, byte[] buffer)
throws IOException
{
super(out, symmetricKeyEnc, buffer);
}
public ClosableBCPGOutputStream(OutputStream out, int symmetricKeyEnc, long length, boolean oldFormat)
throws IOException
{
super(out, symmetricKeyEnc, length, oldFormat);
}
public ClosableBCPGOutputStream(OutputStream out, int symEncIntegrityPro, long length)
throws IOException
{
super(out, symEncIntegrityPro, length);
}
public void close()
throws IOException
{
this.finish();
}
}
}
| |
//
// ========================================================================
// Copyright (c) 1995-2013 Mort Bay Consulting Pty. Ltd.
// ------------------------------------------------------------------------
// 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
//
// 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.
// ========================================================================
//
package org.eclipse.jetty.servlets;
import junit.framework.Assert;
import org.eclipse.jetty.client.ContentExchange;
import org.eclipse.jetty.client.HttpClient;
import org.eclipse.jetty.client.HttpExchange;
import org.eclipse.jetty.http.HttpStatus;
import org.eclipse.jetty.http.HttpURI;
import org.eclipse.jetty.io.Buffer;
import org.eclipse.jetty.server.Connector;
import org.eclipse.jetty.server.Server;
import org.eclipse.jetty.server.handler.HandlerCollection;
import org.eclipse.jetty.server.nio.SelectChannelConnector;
import org.eclipse.jetty.servlet.ServletContextHandler;
import org.eclipse.jetty.servlet.ServletHolder;
import org.eclipse.jetty.toolchain.test.MavenTestingUtils;
import org.eclipse.jetty.util.IO;
import org.eclipse.jetty.util.StringUtil;
import org.hamcrest.core.Is;
import org.hamcrest.core.IsEqual;
import org.junit.After;
import org.junit.Test;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.MalformedURLException;
import java.net.Socket;
import java.util.Arrays;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;
import static org.hamcrest.Matchers.equalTo;
import static org.junit.Assert.assertThat;
public class ProxyServletTest
{
private Server _server;
private Connector _connector;
private HttpClient _client;
public void init(HttpServlet servlet) throws Exception
{
_server = new Server();
_connector = new SelectChannelConnector();
_server.addConnector(_connector);
HandlerCollection handlers = new HandlerCollection();
_server.setHandler(handlers);
ServletContextHandler proxyCtx = new ServletContextHandler(handlers, "/proxy", ServletContextHandler.NO_SESSIONS);
ServletHolder proxyServletHolder = new ServletHolder(new ProxyServlet()
{
@Override
protected HttpURI proxyHttpURI(String scheme, String serverName, int serverPort, String uri) throws MalformedURLException
{
// Proxies any call to "/proxy" to "/"
return new HttpURI(scheme + "://" + serverName + ":" + serverPort + uri.substring("/proxy".length()));
}
});
proxyServletHolder.setInitParameter("timeout", String.valueOf(5 * 60 * 1000L));
proxyCtx.addServlet(proxyServletHolder, "/*");
ServletContextHandler appCtx = new ServletContextHandler(handlers, "/", ServletContextHandler.SESSIONS);
ServletHolder appServletHolder = new ServletHolder(servlet);
appCtx.addServlet(appServletHolder, "/*");
handlers.addHandler(proxyCtx);
handlers.addHandler(appCtx);
_server.start();
_client = new HttpClient();
_client.start();
}
@After
public void destroy() throws Exception
{
if (_client != null)
_client.stop();
if (_server != null)
{
_server.stop();
_server.join();
}
}
@Test
public void testXForwardedHostHeader() throws Exception
{
init(new HttpServlet()
{
private static final long serialVersionUID = 1L;
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException
{
PrintWriter writer = resp.getWriter();
writer.write(req.getHeader("X-Forwarded-Host"));
writer.flush();
}
});
String url = "http://localhost:" + _connector.getLocalPort() + "/proxy/test";
ContentExchange exchange = new ContentExchange();
exchange.setURL(url);
_client.send(exchange);
exchange.waitForDone();
assertThat("Response expected to contain content of X-Forwarded-Host Header from the request",exchange.getResponseContent(),equalTo("localhost:"
+ _connector.getLocalPort()));
}
@Test
public void testBigDownloadWithSlowReader() throws Exception
{
// Create a 6 MiB file
final File file = File.createTempFile("test_", null, MavenTestingUtils.getTargetTestingDir());
file.deleteOnExit();
FileOutputStream fos = new FileOutputStream(file);
byte[] buffer = new byte[1024];
Arrays.fill(buffer, (byte)'X');
for (int i = 0; i < 6 * 1024; ++i)
fos.write(buffer);
fos.close();
init(new HttpServlet()
{
private static final long serialVersionUID = 1L;
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
{
FileInputStream fis = new FileInputStream(file);
ServletOutputStream output = response.getOutputStream();
byte[] buffer = new byte[1024];
int read;
while ((read = fis.read(buffer)) >= 0)
output.write(buffer, 0, read);
fis.close();
}
});
String url = "http://localhost:" + _connector.getLocalPort() + "/proxy/test";
ContentExchange exchange = new ContentExchange(true)
{
@Override
protected void onResponseContent(Buffer content) throws IOException
{
try
{
// Slow down the reader
TimeUnit.MILLISECONDS.sleep(10);
super.onResponseContent(content);
}
catch (InterruptedException x)
{
throw (IOException)new IOException().initCause(x);
}
}
};
exchange.setURL(url);
long start = System.nanoTime();
_client.send(exchange);
Assert.assertEquals(HttpExchange.STATUS_COMPLETED, exchange.waitForDone());
long elapsed = System.nanoTime() - start;
Assert.assertEquals(HttpStatus.OK_200, exchange.getResponseStatus());
Assert.assertEquals(file.length(), exchange.getResponseContentBytes().length);
long millis = TimeUnit.NANOSECONDS.toMillis(elapsed);
long rate = file.length() / 1024 * 1000 / millis;
System.out.printf("download rate = %d KiB/s%n", rate);
}
@Test
public void testLessContentThanContentLength() throws Exception {
init(new HttpServlet() {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
byte[] message = "tooshort".getBytes("ascii");
resp.setContentType("text/plain;charset=ascii");
resp.setHeader("Content-Length", Long.toString(message.length+1));
resp.getOutputStream().write(message);
}
});
final AtomicBoolean excepted = new AtomicBoolean(false);
ContentExchange exchange = new ContentExchange(true)
{
@Override
protected void onResponseContent(Buffer content) throws IOException
{
try
{
// Slow down the reader
TimeUnit.MILLISECONDS.sleep(10);
super.onResponseContent(content);
}
catch (InterruptedException x)
{
throw (IOException)new IOException().initCause(x);
}
}
@Override
protected void onException(Throwable x)
{
excepted.set(true);
super.onException(x);
}
};
String url = "http://localhost:" + _connector.getLocalPort() + "/proxy/test";
exchange.setURL(url);
_client.send(exchange);
exchange.waitForDone();
assertThat(excepted.get(),equalTo(true));
}
@Test
public void testChunkedPut() throws Exception
{
init(new HttpServlet()
{
@Override
protected void doPut(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException
{
resp.setContentType("text/plain");
String message=IO.toString(req.getInputStream());
resp.getOutputStream().print(message);
}
});
Socket client = new Socket("localhost",_connector.getLocalPort());
client.setSoTimeout(1000000);
client.getOutputStream().write((
"PUT /proxy/test HTTP/1.1\r\n"+
"Host: localhost:"+_connector.getLocalPort()+"\r\n"+
"Transfer-Encoding: chunked\r\n"+
"Connection: close\r\n"+
"\r\n"+
"A\r\n"+
"0123456789\r\n"+
"9\r\n"+
"ABCDEFGHI\r\n"+
"8\r\n"+
"JKLMNOPQ\r\n"+
"7\r\n"+
"RSTUVWX\r\n"+
"2\r\n"+
"YZ\r\n"+
"0\r\n"
).getBytes(StringUtil.__ISO_8859_1));
String response=IO.toString(client.getInputStream());
Assert.assertTrue(response.contains("200 OK"));
Assert.assertTrue(response.contains("0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"));
}
}
| |
/*
* Licensed to Elasticsearch under one or more contributor
* license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright
* ownership. Elasticsearch 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.elasticsearch.indices.recovery;
import org.elasticsearch.action.admin.cluster.health.ClusterHealthResponse;
import org.elasticsearch.action.admin.cluster.node.stats.NodeStats;
import org.elasticsearch.action.admin.cluster.node.stats.NodesStatsResponse;
import org.elasticsearch.action.admin.cluster.snapshots.create.CreateSnapshotResponse;
import org.elasticsearch.action.admin.cluster.snapshots.restore.RestoreSnapshotResponse;
import org.elasticsearch.action.admin.cluster.state.ClusterStateResponse;
import org.elasticsearch.action.admin.indices.recovery.RecoveryResponse;
import org.elasticsearch.action.admin.indices.stats.CommonStatsFlags;
import org.elasticsearch.action.admin.indices.stats.IndicesStatsResponse;
import org.elasticsearch.action.index.IndexRequestBuilder;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.cluster.ClusterService;
import org.elasticsearch.cluster.metadata.IndexMetaData;
import org.elasticsearch.cluster.node.DiscoveryNode;
import org.elasticsearch.cluster.routing.allocation.command.MoveAllocationCommand;
import org.elasticsearch.cluster.routing.allocation.decider.FilterAllocationDecider;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.unit.ByteSizeUnit;
import org.elasticsearch.common.unit.ByteSizeValue;
import org.elasticsearch.discovery.DiscoveryService;
import org.elasticsearch.index.recovery.RecoveryStats;
import org.elasticsearch.index.shard.ShardId;
import org.elasticsearch.index.store.Store;
import org.elasticsearch.indices.IndicesService;
import org.elasticsearch.indices.recovery.RecoveryState.Stage;
import org.elasticsearch.indices.recovery.RecoveryState.Type;
import org.elasticsearch.plugins.Plugin;
import org.elasticsearch.snapshots.SnapshotState;
import org.elasticsearch.test.ESIntegTestCase;
import org.elasticsearch.test.ESIntegTestCase.ClusterScope;
import org.elasticsearch.test.ESIntegTestCase.Scope;
import org.elasticsearch.test.InternalTestCluster;
import org.elasticsearch.test.junit.annotations.TestLogging;
import org.elasticsearch.test.store.MockFSDirectoryService;
import org.elasticsearch.test.transport.MockTransportService;
import org.elasticsearch.transport.ConnectTransportException;
import org.elasticsearch.transport.Transport;
import org.elasticsearch.transport.TransportException;
import org.elasticsearch.transport.TransportRequest;
import org.elasticsearch.transport.TransportRequestOptions;
import org.elasticsearch.transport.TransportService;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutionException;
import static org.elasticsearch.common.settings.Settings.settingsBuilder;
import static org.elasticsearch.test.hamcrest.ElasticsearchAssertions.assertAcked;
import static org.elasticsearch.test.hamcrest.ElasticsearchAssertions.assertHitCount;
import static org.hamcrest.Matchers.arrayWithSize;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.greaterThan;
import static org.hamcrest.Matchers.greaterThanOrEqualTo;
import static org.hamcrest.Matchers.is;
import static org.hamcrest.Matchers.lessThanOrEqualTo;
import static org.hamcrest.Matchers.not;
/**
*
*/
@ClusterScope(scope = Scope.TEST, numDataNodes = 0)
public class IndexRecoveryIT extends ESIntegTestCase {
private static final String INDEX_NAME = "test-idx-1";
private static final String INDEX_TYPE = "test-type-1";
private static final String REPO_NAME = "test-repo-1";
private static final String SNAP_NAME = "test-snap-1";
private static final int MIN_DOC_COUNT = 500;
private static final int MAX_DOC_COUNT = 1000;
private static final int SHARD_COUNT = 1;
private static final int REPLICA_COUNT = 0;
@Override
protected Collection<Class<? extends Plugin>> nodePlugins() {
return pluginList(MockTransportService.TestPlugin.class);
}
private void assertRecoveryStateWithoutStage(RecoveryState state, int shardId, Type type,
String sourceNode, String targetNode, boolean hasRestoreSource) {
assertThat(state.getShardId().getId(), equalTo(shardId));
assertThat(state.getType(), equalTo(type));
if (sourceNode == null) {
assertNull(state.getSourceNode());
} else {
assertNotNull(state.getSourceNode());
assertThat(state.getSourceNode().getName(), equalTo(sourceNode));
}
if (targetNode == null) {
assertNull(state.getTargetNode());
} else {
assertNotNull(state.getTargetNode());
assertThat(state.getTargetNode().getName(), equalTo(targetNode));
}
if (hasRestoreSource) {
assertNotNull(state.getRestoreSource());
} else {
assertNull(state.getRestoreSource());
}
}
private void assertRecoveryState(RecoveryState state, int shardId, Type type, Stage stage,
String sourceNode, String targetNode, boolean hasRestoreSource) {
assertRecoveryStateWithoutStage(state, shardId, type, sourceNode, targetNode, hasRestoreSource);
assertThat(state.getStage(), equalTo(stage));
}
private void assertOnGoingRecoveryState(RecoveryState state, int shardId, Type type,
String sourceNode, String targetNode, boolean hasRestoreSource) {
assertRecoveryStateWithoutStage(state, shardId, type, sourceNode, targetNode, hasRestoreSource);
assertThat(state.getStage(), not(equalTo(Stage.DONE)));
}
private void slowDownRecovery(ByteSizeValue shardSize) {
long chunkSize = shardSize.bytes() / 10;
assertTrue(client().admin().cluster().prepareUpdateSettings()
.setTransientSettings(Settings.builder()
// one chunk per sec..
.put(RecoverySettings.INDICES_RECOVERY_MAX_BYTES_PER_SEC, chunkSize, ByteSizeUnit.BYTES)
.put(RecoverySettings.INDICES_RECOVERY_FILE_CHUNK_SIZE, chunkSize, ByteSizeUnit.BYTES)
)
.get().isAcknowledged());
}
private void restoreRecoverySpeed() {
assertTrue(client().admin().cluster().prepareUpdateSettings()
.setTransientSettings(Settings.builder()
.put(RecoverySettings.INDICES_RECOVERY_MAX_BYTES_PER_SEC, "20mb")
.put(RecoverySettings.INDICES_RECOVERY_FILE_CHUNK_SIZE, "512kb")
)
.get().isAcknowledged());
}
public void testGatewayRecovery() throws Exception {
logger.info("--> start nodes");
String node = internalCluster().startNode();
createAndPopulateIndex(INDEX_NAME, 1, SHARD_COUNT, REPLICA_COUNT);
logger.info("--> restarting cluster");
internalCluster().fullRestart();
ensureGreen();
logger.info("--> request recoveries");
RecoveryResponse response = client().admin().indices().prepareRecoveries(INDEX_NAME).execute().actionGet();
assertThat(response.shardRecoveryStates().size(), equalTo(SHARD_COUNT));
assertThat(response.shardRecoveryStates().get(INDEX_NAME).size(), equalTo(1));
List<RecoveryState> recoveryStates = response.shardRecoveryStates().get(INDEX_NAME);
assertThat(recoveryStates.size(), equalTo(1));
RecoveryState recoveryState = recoveryStates.get(0);
assertRecoveryState(recoveryState, 0, Type.STORE, Stage.DONE, node, node, false);
validateIndexRecoveryState(recoveryState.getIndex());
}
public void testGatewayRecoveryTestActiveOnly() throws Exception {
logger.info("--> start nodes");
internalCluster().startNode();
createAndPopulateIndex(INDEX_NAME, 1, SHARD_COUNT, REPLICA_COUNT);
logger.info("--> restarting cluster");
internalCluster().fullRestart();
ensureGreen();
logger.info("--> request recoveries");
RecoveryResponse response = client().admin().indices().prepareRecoveries(INDEX_NAME).setActiveOnly(true).execute().actionGet();
List<RecoveryState> recoveryStates = response.shardRecoveryStates().get(INDEX_NAME);
assertThat(recoveryStates.size(), equalTo(0)); // Should not expect any responses back
}
public void testReplicaRecovery() throws Exception {
logger.info("--> start node A");
String nodeA = internalCluster().startNode();
logger.info("--> create index on node: {}", nodeA);
createAndPopulateIndex(INDEX_NAME, 1, SHARD_COUNT, REPLICA_COUNT);
logger.info("--> start node B");
String nodeB = internalCluster().startNode();
ensureGreen();
// force a shard recovery from nodeA to nodeB
logger.info("--> bump replica count");
client().admin().indices().prepareUpdateSettings(INDEX_NAME)
.setSettings(settingsBuilder().put("number_of_replicas", 1)).execute().actionGet();
ensureGreen();
logger.info("--> request recoveries");
RecoveryResponse response = client().admin().indices().prepareRecoveries(INDEX_NAME).execute().actionGet();
// we should now have two total shards, one primary and one replica
List<RecoveryState> recoveryStates = response.shardRecoveryStates().get(INDEX_NAME);
assertThat(recoveryStates.size(), equalTo(2));
List<RecoveryState> nodeAResponses = findRecoveriesForTargetNode(nodeA, recoveryStates);
assertThat(nodeAResponses.size(), equalTo(1));
List<RecoveryState> nodeBResponses = findRecoveriesForTargetNode(nodeB, recoveryStates);
assertThat(nodeBResponses.size(), equalTo(1));
// validate node A recovery
RecoveryState nodeARecoveryState = nodeAResponses.get(0);
assertRecoveryState(nodeARecoveryState, 0, Type.STORE, Stage.DONE, nodeA, nodeA, false);
validateIndexRecoveryState(nodeARecoveryState.getIndex());
// validate node B recovery
RecoveryState nodeBRecoveryState = nodeBResponses.get(0);
assertRecoveryState(nodeBRecoveryState, 0, Type.REPLICA, Stage.DONE, nodeA, nodeB, false);
validateIndexRecoveryState(nodeBRecoveryState.getIndex());
}
@TestLogging("indices.recovery:TRACE")
public void testRerouteRecovery() throws Exception {
logger.info("--> start node A");
final String nodeA = internalCluster().startNode();
logger.info("--> create index on node: {}", nodeA);
ByteSizeValue shardSize = createAndPopulateIndex(INDEX_NAME, 1, SHARD_COUNT, REPLICA_COUNT).getShards()[0].getStats().getStore().size();
logger.info("--> start node B");
final String nodeB = internalCluster().startNode();
ensureGreen();
logger.info("--> slowing down recoveries");
slowDownRecovery(shardSize);
logger.info("--> move shard from: {} to: {}", nodeA, nodeB);
client().admin().cluster().prepareReroute()
.add(new MoveAllocationCommand(new ShardId(INDEX_NAME, 0), nodeA, nodeB))
.execute().actionGet().getState();
logger.info("--> waiting for recovery to start both on source and target");
assertBusy(new Runnable() {
@Override
public void run() {
IndicesService indicesService = internalCluster().getInstance(IndicesService.class, nodeA);
assertThat(indicesService.indexServiceSafe(INDEX_NAME).getShard(0).recoveryStats().currentAsSource(),
equalTo(1));
indicesService = internalCluster().getInstance(IndicesService.class, nodeB);
assertThat(indicesService.indexServiceSafe(INDEX_NAME).getShard(0).recoveryStats().currentAsTarget(),
equalTo(1));
}
});
logger.info("--> request recoveries");
RecoveryResponse response = client().admin().indices().prepareRecoveries(INDEX_NAME).execute().actionGet();
List<RecoveryState> recoveryStates = response.shardRecoveryStates().get(INDEX_NAME);
List<RecoveryState> nodeARecoveryStates = findRecoveriesForTargetNode(nodeA, recoveryStates);
assertThat(nodeARecoveryStates.size(), equalTo(1));
List<RecoveryState> nodeBRecoveryStates = findRecoveriesForTargetNode(nodeB, recoveryStates);
assertThat(nodeBRecoveryStates.size(), equalTo(1));
assertRecoveryState(nodeARecoveryStates.get(0), 0, Type.STORE, Stage.DONE, nodeA, nodeA, false);
validateIndexRecoveryState(nodeARecoveryStates.get(0).getIndex());
assertOnGoingRecoveryState(nodeBRecoveryStates.get(0), 0, Type.RELOCATION, nodeA, nodeB, false);
validateIndexRecoveryState(nodeBRecoveryStates.get(0).getIndex());
logger.info("--> request node recovery stats");
NodesStatsResponse statsResponse = client().admin().cluster().prepareNodesStats().clear().setIndices(new CommonStatsFlags(CommonStatsFlags.Flag.Recovery)).get();
long nodeAThrottling = Long.MAX_VALUE;
long nodeBThrottling = Long.MAX_VALUE;
for (NodeStats nodeStats : statsResponse.getNodes()) {
final RecoveryStats recoveryStats = nodeStats.getIndices().getRecoveryStats();
if (nodeStats.getNode().name().equals(nodeA)) {
assertThat("node A should have ongoing recovery as source", recoveryStats.currentAsSource(), equalTo(1));
assertThat("node A should not have ongoing recovery as target", recoveryStats.currentAsTarget(), equalTo(0));
nodeAThrottling = recoveryStats.throttleTime().millis();
}
if (nodeStats.getNode().name().equals(nodeB)) {
assertThat("node B should not have ongoing recovery as source", recoveryStats.currentAsSource(), equalTo(0));
assertThat("node B should have ongoing recovery as target", recoveryStats.currentAsTarget(), equalTo(1));
nodeBThrottling = recoveryStats.throttleTime().millis();
}
}
logger.info("--> checking throttling increases");
final long finalNodeAThrottling = nodeAThrottling;
final long finalNodeBThrottling = nodeBThrottling;
assertBusy(new Runnable() {
@Override
public void run() {
NodesStatsResponse statsResponse = client().admin().cluster().prepareNodesStats().clear().setIndices(new CommonStatsFlags(CommonStatsFlags.Flag.Recovery)).get();
assertThat(statsResponse.getNodes(), arrayWithSize(2));
for (NodeStats nodeStats : statsResponse.getNodes()) {
final RecoveryStats recoveryStats = nodeStats.getIndices().getRecoveryStats();
if (nodeStats.getNode().name().equals(nodeA)) {
assertThat("node A throttling should increase", recoveryStats.throttleTime().millis(), greaterThan(finalNodeAThrottling));
}
if (nodeStats.getNode().name().equals(nodeB)) {
assertThat("node B throttling should increase", recoveryStats.throttleTime().millis(), greaterThan(finalNodeBThrottling));
}
}
}
});
logger.info("--> speeding up recoveries");
restoreRecoverySpeed();
// wait for it to be finished
ensureGreen();
response = client().admin().indices().prepareRecoveries(INDEX_NAME).execute().actionGet();
recoveryStates = response.shardRecoveryStates().get(INDEX_NAME);
assertThat(recoveryStates.size(), equalTo(1));
assertRecoveryState(recoveryStates.get(0), 0, Type.RELOCATION, Stage.DONE, nodeA, nodeB, false);
validateIndexRecoveryState(recoveryStates.get(0).getIndex());
statsResponse = client().admin().cluster().prepareNodesStats().clear().setIndices(new CommonStatsFlags(CommonStatsFlags.Flag.Recovery)).get();
assertThat(statsResponse.getNodes(), arrayWithSize(2));
for (NodeStats nodeStats : statsResponse.getNodes()) {
final RecoveryStats recoveryStats = nodeStats.getIndices().getRecoveryStats();
assertThat(recoveryStats.currentAsSource(), equalTo(0));
assertThat(recoveryStats.currentAsTarget(), equalTo(0));
if (nodeStats.getNode().name().equals(nodeA)) {
assertThat("node A throttling should be >0", recoveryStats.throttleTime().millis(), greaterThan(0l));
}
if (nodeStats.getNode().name().equals(nodeB)) {
assertThat("node B throttling should be >0 ", recoveryStats.throttleTime().millis(), greaterThan(0l));
}
}
logger.info("--> bump replica count");
client().admin().indices().prepareUpdateSettings(INDEX_NAME)
.setSettings(settingsBuilder().put("number_of_replicas", 1)).execute().actionGet();
ensureGreen();
statsResponse = client().admin().cluster().prepareNodesStats().clear().setIndices(new CommonStatsFlags(CommonStatsFlags.Flag.Recovery)).get();
assertThat(statsResponse.getNodes(), arrayWithSize(2));
for (NodeStats nodeStats : statsResponse.getNodes()) {
final RecoveryStats recoveryStats = nodeStats.getIndices().getRecoveryStats();
assertThat(recoveryStats.currentAsSource(), equalTo(0));
assertThat(recoveryStats.currentAsTarget(), equalTo(0));
if (nodeStats.getNode().name().equals(nodeA)) {
assertThat("node A throttling should be >0", recoveryStats.throttleTime().millis(), greaterThan(0l));
}
if (nodeStats.getNode().name().equals(nodeB)) {
assertThat("node B throttling should be >0 ", recoveryStats.throttleTime().millis(), greaterThan(0l));
}
}
logger.info("--> start node C");
String nodeC = internalCluster().startNode();
assertFalse(client().admin().cluster().prepareHealth().setWaitForNodes("3").get().isTimedOut());
logger.info("--> slowing down recoveries");
slowDownRecovery(shardSize);
logger.info("--> move replica shard from: {} to: {}", nodeA, nodeC);
client().admin().cluster().prepareReroute()
.add(new MoveAllocationCommand(new ShardId(INDEX_NAME, 0), nodeA, nodeC))
.execute().actionGet().getState();
response = client().admin().indices().prepareRecoveries(INDEX_NAME).execute().actionGet();
recoveryStates = response.shardRecoveryStates().get(INDEX_NAME);
nodeARecoveryStates = findRecoveriesForTargetNode(nodeA, recoveryStates);
assertThat(nodeARecoveryStates.size(), equalTo(1));
nodeBRecoveryStates = findRecoveriesForTargetNode(nodeB, recoveryStates);
assertThat(nodeBRecoveryStates.size(), equalTo(1));
List<RecoveryState> nodeCRecoveryStates = findRecoveriesForTargetNode(nodeC, recoveryStates);
assertThat(nodeCRecoveryStates.size(), equalTo(1));
assertRecoveryState(nodeARecoveryStates.get(0), 0, Type.REPLICA, Stage.DONE, nodeB, nodeA, false);
validateIndexRecoveryState(nodeARecoveryStates.get(0).getIndex());
assertRecoveryState(nodeBRecoveryStates.get(0), 0, Type.RELOCATION, Stage.DONE, nodeA, nodeB, false);
validateIndexRecoveryState(nodeBRecoveryStates.get(0).getIndex());
// relocations of replicas are marked as REPLICA and the source node is the node holding the primary (B)
assertOnGoingRecoveryState(nodeCRecoveryStates.get(0), 0, Type.REPLICA, nodeB, nodeC, false);
validateIndexRecoveryState(nodeCRecoveryStates.get(0).getIndex());
logger.info("--> speeding up recoveries");
restoreRecoverySpeed();
ensureGreen();
response = client().admin().indices().prepareRecoveries(INDEX_NAME).execute().actionGet();
recoveryStates = response.shardRecoveryStates().get(INDEX_NAME);
nodeARecoveryStates = findRecoveriesForTargetNode(nodeA, recoveryStates);
assertThat(nodeARecoveryStates.size(), equalTo(0));
nodeBRecoveryStates = findRecoveriesForTargetNode(nodeB, recoveryStates);
assertThat(nodeBRecoveryStates.size(), equalTo(1));
nodeCRecoveryStates = findRecoveriesForTargetNode(nodeC, recoveryStates);
assertThat(nodeCRecoveryStates.size(), equalTo(1));
assertRecoveryState(nodeBRecoveryStates.get(0), 0, Type.RELOCATION, Stage.DONE, nodeA, nodeB, false);
validateIndexRecoveryState(nodeBRecoveryStates.get(0).getIndex());
// relocations of replicas are marked as REPLICA and the source node is the node holding the primary (B)
assertRecoveryState(nodeCRecoveryStates.get(0), 0, Type.REPLICA, Stage.DONE, nodeB, nodeC, false);
validateIndexRecoveryState(nodeCRecoveryStates.get(0).getIndex());
}
public void testSnapshotRecovery() throws Exception {
logger.info("--> start node A");
String nodeA = internalCluster().startNode();
logger.info("--> create repository");
assertAcked(client().admin().cluster().preparePutRepository(REPO_NAME)
.setType("fs").setSettings(Settings.settingsBuilder()
.put("location", randomRepoPath())
.put("compress", false)
).get());
ensureGreen();
logger.info("--> create index on node: {}", nodeA);
createAndPopulateIndex(INDEX_NAME, 1, SHARD_COUNT, REPLICA_COUNT);
logger.info("--> snapshot");
CreateSnapshotResponse createSnapshotResponse = client().admin().cluster().prepareCreateSnapshot(REPO_NAME, SNAP_NAME)
.setWaitForCompletion(true).setIndices(INDEX_NAME).get();
assertThat(createSnapshotResponse.getSnapshotInfo().successfulShards(), greaterThan(0));
assertThat(createSnapshotResponse.getSnapshotInfo().successfulShards(), equalTo(createSnapshotResponse.getSnapshotInfo().totalShards()));
assertThat(client().admin().cluster().prepareGetSnapshots(REPO_NAME).setSnapshots(SNAP_NAME).get()
.getSnapshots().get(0).state(), equalTo(SnapshotState.SUCCESS));
client().admin().indices().prepareClose(INDEX_NAME).execute().actionGet();
logger.info("--> restore");
RestoreSnapshotResponse restoreSnapshotResponse = client().admin().cluster()
.prepareRestoreSnapshot(REPO_NAME, SNAP_NAME).setWaitForCompletion(true).execute().actionGet();
int totalShards = restoreSnapshotResponse.getRestoreInfo().totalShards();
assertThat(totalShards, greaterThan(0));
ensureGreen();
logger.info("--> request recoveries");
RecoveryResponse response = client().admin().indices().prepareRecoveries(INDEX_NAME).execute().actionGet();
for (Map.Entry<String, List<RecoveryState>> indexRecoveryStates : response.shardRecoveryStates().entrySet()) {
assertThat(indexRecoveryStates.getKey(), equalTo(INDEX_NAME));
List<RecoveryState> recoveryStates = indexRecoveryStates.getValue();
assertThat(recoveryStates.size(), equalTo(totalShards));
for (RecoveryState recoveryState : recoveryStates) {
assertRecoveryState(recoveryState, 0, Type.SNAPSHOT, Stage.DONE, null, nodeA, true);
validateIndexRecoveryState(recoveryState.getIndex());
}
}
}
private List<RecoveryState> findRecoveriesForTargetNode(String nodeName, List<RecoveryState> recoveryStates) {
List<RecoveryState> nodeResponses = new ArrayList<>();
for (RecoveryState recoveryState : recoveryStates) {
if (recoveryState.getTargetNode().getName().equals(nodeName)) {
nodeResponses.add(recoveryState);
}
}
return nodeResponses;
}
private IndicesStatsResponse createAndPopulateIndex(String name, int nodeCount, int shardCount, int replicaCount)
throws ExecutionException, InterruptedException {
logger.info("--> creating test index: {}", name);
assertAcked(prepareCreate(name, nodeCount, settingsBuilder().put("number_of_shards", shardCount)
.put("number_of_replicas", replicaCount).put(Store.INDEX_STORE_STATS_REFRESH_INTERVAL, 0)));
ensureGreen();
logger.info("--> indexing sample data");
final int numDocs = between(MIN_DOC_COUNT, MAX_DOC_COUNT);
final IndexRequestBuilder[] docs = new IndexRequestBuilder[numDocs];
for (int i = 0; i < numDocs; i++) {
docs[i] = client().prepareIndex(INDEX_NAME, INDEX_TYPE).
setSource("foo-int", randomInt(),
"foo-string", randomAsciiOfLength(32),
"foo-float", randomFloat());
}
indexRandom(true, docs);
flush();
assertThat(client().prepareSearch(INDEX_NAME).setSize(0).get().getHits().totalHits(), equalTo((long) numDocs));
return client().admin().indices().prepareStats(INDEX_NAME).execute().actionGet();
}
private void validateIndexRecoveryState(RecoveryState.Index indexState) {
assertThat(indexState.time(), greaterThanOrEqualTo(0L));
assertThat(indexState.recoveredFilesPercent(), greaterThanOrEqualTo(0.0f));
assertThat(indexState.recoveredFilesPercent(), lessThanOrEqualTo(100.0f));
assertThat(indexState.recoveredBytesPercent(), greaterThanOrEqualTo(0.0f));
assertThat(indexState.recoveredBytesPercent(), lessThanOrEqualTo(100.0f));
}
public void testDisconnectsWhileRecovering() throws Exception {
final String indexName = "test";
final Settings nodeSettings = Settings.builder()
.put(RecoverySettings.INDICES_RECOVERY_RETRY_DELAY_NETWORK, "100ms")
.put(RecoverySettings.INDICES_RECOVERY_INTERNAL_ACTION_TIMEOUT, "1s")
.put(MockFSDirectoryService.RANDOM_PREVENT_DOUBLE_WRITE, false) // restarted recoveries will delete temp files and write them again
.build();
// start a master node
internalCluster().startNode(nodeSettings);
InternalTestCluster.Async<String> blueFuture = internalCluster().startNodeAsync(Settings.builder().put("node.color", "blue").put(nodeSettings).build());
InternalTestCluster.Async<String> redFuture = internalCluster().startNodeAsync(Settings.builder().put("node.color", "red").put(nodeSettings).build());
final String blueNodeName = blueFuture.get();
final String redNodeName = redFuture.get();
ClusterHealthResponse response = client().admin().cluster().prepareHealth().setWaitForNodes(">=3").get();
assertThat(response.isTimedOut(), is(false));
client().admin().indices().prepareCreate(indexName)
.setSettings(
Settings.builder()
.put(FilterAllocationDecider.INDEX_ROUTING_INCLUDE_GROUP + "color", "blue")
.put(IndexMetaData.SETTING_NUMBER_OF_SHARDS, 1)
.put(IndexMetaData.SETTING_NUMBER_OF_REPLICAS, 0)
).get();
List<IndexRequestBuilder> requests = new ArrayList<>();
int numDocs = scaledRandomIntBetween(25, 250);
for (int i = 0; i < numDocs; i++) {
requests.add(client().prepareIndex(indexName, "type").setCreate(true).setSource("{}"));
}
indexRandom(true, requests);
ensureSearchable(indexName);
ClusterStateResponse stateResponse = client().admin().cluster().prepareState().get();
final String blueNodeId = internalCluster().getInstance(DiscoveryService.class, blueNodeName).localNode().id();
assertFalse(stateResponse.getState().getRoutingNodes().node(blueNodeId).isEmpty());
SearchResponse searchResponse = client().prepareSearch(indexName).get();
assertHitCount(searchResponse, numDocs);
String[] recoveryActions = new String[]{
RecoverySource.Actions.START_RECOVERY,
RecoveryTarget.Actions.FILES_INFO,
RecoveryTarget.Actions.FILE_CHUNK,
RecoveryTarget.Actions.CLEAN_FILES,
//RecoveryTarget.Actions.TRANSLOG_OPS, <-- may not be sent if already flushed
RecoveryTarget.Actions.PREPARE_TRANSLOG,
RecoveryTarget.Actions.FINALIZE
};
final String recoveryActionToBlock = randomFrom(recoveryActions);
final boolean dropRequests = randomBoolean();
logger.info("--> will {} between blue & red on [{}]", dropRequests ? "drop requests" : "break connection", recoveryActionToBlock);
MockTransportService blueMockTransportService = (MockTransportService) internalCluster().getInstance(TransportService.class, blueNodeName);
MockTransportService redMockTransportService = (MockTransportService) internalCluster().getInstance(TransportService.class, redNodeName);
TransportService redTransportService = internalCluster().getInstance(TransportService.class, redNodeName);
TransportService blueTransportService = internalCluster().getInstance(TransportService.class, blueNodeName);
final CountDownLatch requestBlocked = new CountDownLatch(1);
blueMockTransportService.addDelegate(redTransportService, new RecoveryActionBlocker(dropRequests, recoveryActionToBlock, blueMockTransportService.original(), requestBlocked));
redMockTransportService.addDelegate(blueTransportService, new RecoveryActionBlocker(dropRequests, recoveryActionToBlock, redMockTransportService.original(), requestBlocked));
logger.info("--> starting recovery from blue to red");
client().admin().indices().prepareUpdateSettings(indexName).setSettings(
Settings.builder()
.put(FilterAllocationDecider.INDEX_ROUTING_INCLUDE_GROUP + "color", "red,blue")
.put(IndexMetaData.SETTING_NUMBER_OF_REPLICAS, 1)
).get();
requestBlocked.await();
logger.info("--> stopping to block recovery");
blueMockTransportService.clearAllRules();
redMockTransportService.clearAllRules();
ensureGreen();
searchResponse = client(redNodeName).prepareSearch(indexName).setPreference("_local").get();
assertHitCount(searchResponse, numDocs);
}
private class RecoveryActionBlocker extends MockTransportService.DelegateTransport {
private final boolean dropRequests;
private final String recoveryActionToBlock;
private final CountDownLatch requestBlocked;
public RecoveryActionBlocker(boolean dropRequests, String recoveryActionToBlock, Transport delegate, CountDownLatch requestBlocked) {
super(delegate);
this.dropRequests = dropRequests;
this.recoveryActionToBlock = recoveryActionToBlock;
this.requestBlocked = requestBlocked;
}
@Override
public void sendRequest(DiscoveryNode node, long requestId, String action, TransportRequest request, TransportRequestOptions options) throws IOException, TransportException {
if (recoveryActionToBlock.equals(action) || requestBlocked.getCount() == 0) {
logger.info("--> preventing {} request", action);
requestBlocked.countDown();
if (dropRequests) {
return;
}
throw new ConnectTransportException(node, "DISCONNECT: prevented " + action + " request");
}
transport.sendRequest(node, requestId, action, request, options);
}
}
}
| |
package dpnm.tool;
import java.awt.Color;
import java.awt.Dimension;
import java.util.Enumeration;
import java.util.Iterator;
import java.util.Vector;
import javax.swing.*;
import javax.swing.table.AbstractTableModel;
import dpnm.tool.data.*;
import dpnm.comm.CommunicationDevice;
import dpnm.mobiledevice.MobileDevice;
import dpnm.mobiledevice.NetworkProperty;
import dpnm.network.*;
import dpnm.network.device.*;
public class NetworkMonitorView extends JPanel {
private static final String NETWORK_HEADERS[] = {
"Device", "Type", "Connected Mobile Nodes"};
private static final String NETWORK_PARAMETERS[] = {
"Coverage (meter)",
"Bandwidth (kbyte)",
"Delay (ms)",
"Jitter (ms)",
"BER (dB)",
"Throughput (Mbyte/s)",
"Burst Error",
"Packet Loss Ratio",
"Cost Rate ($/min)",
"Power Tx (W)",
"Power Rx (W)",
"Power Idle (W)",
"Max Velocity (km/h)",
"Min Velocity (km/h)"
};
private NetworkDeviceInfo deviceInfo[];
private JTabbedPane mainPane;
private JPanel networkView;
private JTable networkTable;
private JTextArea networkArea;
private NetworkModel networkModel;
private JPanel deviceView[];
public NetworkMonitorView() {
this(null);
}
public NetworkMonitorView(NetworkDeviceInfo deviceInfo[]) {
mainPane = new JTabbedPane();
mainPane.setPreferredSize(new Dimension(Env.MONITOR_WIDTH/2-20, Env.MONITOR_HEIGHT-60));
mainPane.setTabLayoutPolicy(JTabbedPane.SCROLL_TAB_LAYOUT);
mainPane.setTabPlacement(JTabbedPane.LEFT);
add(mainPane);
setDeviceInfo(deviceInfo);
}
public void setDeviceInfo(NetworkDeviceInfo deviceInfo[]) {
this.deviceInfo = deviceInfo;
if (deviceInfo != null)
createUI();
showCurrentNetworkStatus();
}
private void createUI() {
networkView = new JPanel();
networkModel = new NetworkModel();
networkModel.setNetworkInfo(deviceInfo);
networkTable = new JTable(networkModel);
networkArea = new JTextArea();
networkArea.setEditable(false);
networkArea.setFont(Resources.DIALOG_12);
networkTable.setGridColor(Color.black);
JScrollPane scrollPane = new JScrollPane(networkArea);
// scrollPane.setPreferredSize(new Dimension(Env.MONITOR_WIDTH/2-20, Env.MONITOR_HEIGHT-60));
// scrollPane.setBounds(20,160,400,250);
mainPane.addTab("Network(s)", scrollPane);
deviceView = new DeviceView[deviceInfo.length];
for (int i = 0; i < deviceInfo.length; i++) {
deviceView[i] = new DeviceView(deviceInfo[i]);
mainPane.addTab(deviceInfo[i].getDevice().getName(), deviceView[i]);
mainPane.setBackgroundAt(i+1, new Color(deviceInfo[i].getDevice().getNetwork().getColor()));
mainPane.setToolTipTextAt(i+1, deviceInfo[i].getDevice().getNetworkStr());
}
}
void showCurrentNetworkStatus() {
StringBuffer sb = new StringBuffer();
for (int i = 0; deviceInfo != null && i < deviceInfo.length; i++) {
sb.append(deviceInfo[i].getStatus());
sb.append("---------------------------------------------\n\n");
}
networkArea.setText(sb.toString());
}
class NetworkModel extends AbstractTableModel {
NetworkDeviceInfo[] info = null;
public NetworkModel() {
this(null);
}
public NetworkModel(NetworkDeviceInfo[] info) {
setNetworkInfo(info);
}
public void setNetworkInfo(NetworkDeviceInfo[] info) {
this.info = info;
}
public int getColumnCount() {
// TODO Auto-generated method stub
return NETWORK_HEADERS.length;
}
public int getRowCount() {
// TODO Auto-generated method stub
return info.length;
}
public String getColumnName(int col) {
return NETWORK_HEADERS[col];
}
public Object getValueAt(int row, int col) {
// TODO Auto-generated method stub
if (info == null) {
return "";
}
switch(col) {
case 0: return info[row].getDevice().getName();
case 1: return info[row].getDevice().getNetwork().getName();
case 2: return "..";
}
return "";
}
}
/*
* DeviceView
*
* Base station position
* Type
* IPAddr
* Name
* Network information
*/
class DeviceView extends JPanel {
private NetworkDeviceInfo deviceInfo;
private JTextField nameFld = null;
private JTextField positionFld = null;
private JTextField typeFld = null;
private JTextField ipAddrFld = null;
private JTable networkInfoTable = null;
private JList connectedNodeInfoList = null;
private NetworkInfoModel networkInfoModel = null;
private DefaultListModel connectedListModel = null;
public DeviceView(NetworkDeviceInfo deviceInfo) {
this.deviceInfo = deviceInfo;
createUI();
updateData();
}
private void createUI() {
setLayout(null);
// name
JLabel label = new JLabel("Name: ");
label.setFont(Resources.ARIAL_12);
label.setBounds(10, 10, 100, 20);
add(label);
nameFld = new JTextField(20);
nameFld.setBounds(100, 10, 200, 20);
nameFld.setEditable(false);
add(nameFld);
//positionFld
label = new JLabel("Location: ");
label.setFont(Resources.ARIAL_12);
label.setBounds(10, 40, 100, 20);
add(label);
positionFld = new JTextField(20);
positionFld.setBounds(100, 40, 200, 20);
positionFld.setEditable(false);
add(positionFld);
//typeFld
label = new JLabel("Type: ");
label.setFont(Resources.ARIAL_12);
label.setBounds(10, 70, 100, 20);
add(label);
typeFld = new JTextField(20);
typeFld.setBounds(100, 70, 200, 20);
typeFld.setEditable(false);
add(typeFld);
//ipAddrFld
label = new JLabel("IP Address: ");
label.setFont(Resources.ARIAL_12);
label.setBounds(10, 100, 100, 20);
add(label);
ipAddrFld = new JTextField(20);
ipAddrFld.setBounds(100, 100, 200, 20);
ipAddrFld.setEditable(false);
add(ipAddrFld);
//network information
label = new JLabel("Network Information: ");
label.setFont(Resources.ARIAL_12);
label.setBounds(10, 130, 140, 20);
add(label);
networkInfoModel = new NetworkInfoModel();
networkInfoTable = new JTable(networkInfoModel);
networkInfoTable.setGridColor(Color.black);
JScrollPane scrollPane = new JScrollPane(networkInfoTable);
scrollPane.setBounds(20,160,350,250);
add(scrollPane);
//network information
label = new JLabel("Connected Mobile Nodes: ");
label.setFont(Resources.ARIAL_12);
label.setBounds(10, 420, 200, 20);
add(label);
connectedListModel = new DefaultListModel();
connectedNodeInfoList = new JList(connectedListModel);
connectedNodeInfoList.setBounds(20, 450, 200, 60);
scrollPane = new JScrollPane(connectedNodeInfoList);
scrollPane.setBounds(20, 450, 200, 60);
/*
NetworkMobileNodeInfo mnodes[] = new NetworkMobileNodeInfo[test.TestPlayer.MOBILENODES.length];
for (int i = 0; i < mnodes.length; i++) {
NetworkMobileNodeInfo mInfo = new NetworkMobileNodeInfo();
char id = (char) ('A'+((char)i));
MobileDevice device = new MobileDevice(Character.toString(id));
mInfo.setType(test.TestPlayer.MOBILENODES[i][0]);
mInfo.setXpos(test.TestPlayer.MOBILENODES[i][1]+test.TestPlayer.X_GAP);
mInfo.setYpos(test.TestPlayer.MOBILENODES[i][2]+test.TestPlayer.Y_GAP);
mInfo.setDevice(device);
mnodes[i] = mInfo;
}
nodeInfoModel.setMobileNodeInfo(mnodes);
*/
add(scrollPane);
}
void updateConnectedList() {
connectedListModel.removeAllElements();
Vector<ConnectedMobileNode> nodes = deviceInfo.getDevice().getConnectedMobileNodes();
if (nodes != null) {
for (int i = 0; i < nodes.size(); i++) {
connectedListModel.addElement(nodes.elementAt(i));
}
}
connectedNodeInfoList.repaint();
}
private void updateData() {
if (deviceInfo == null)
return;
nameFld.setText(deviceInfo.getDevice().getName());
positionFld.setText(deviceInfo.getXpos() + " , " + deviceInfo.getYpos());
typeFld.setText(deviceInfo.getDevice().getNetwork().getName());
ipAddrFld.setText(deviceInfo.getDevice().getIpAddress());
// networkInfoModel.setNetworkInfo(deviceInfo.getDevice().getNetwork());
networkInfoModel.setNetworkInfo(deviceInfo.getData());
}
class NetworkInfoModel extends AbstractTableModel {
INetwork network;
public NetworkInfoModel() {
this(null);
}
public NetworkInfoModel(INetwork network) {
setNetworkInfo(network);
}
public void setNetworkInfo(INetwork network) {
this.network = network;
}
public int getColumnCount() {
// TODO Auto-generated method stub
return 2;
}
public int getRowCount() {
// TODO Auto-generated method stub
return NETWORK_PARAMETERS.length;
}
public String getColumnName(int col) {
switch(col) {
case 0:
return "Parameter";
case 1:
return "Value";
}
return null;
}
public Object getValueAt(int row, int col) {
// TODO Auto-generated method stub
if (col == 0) {
return NETWORK_PARAMETERS[row];
}
if (col == 1) {
return getNetworkValue(row);
}
return null;
}
/*
* Don't need to implement this method unless your table's
* editable.
*/
public boolean isCellEditable(int row, int col) {
return false;
}
private String getNetworkValue(int v) {
if (network == null)
return "";
switch(v) {
case 0: return Integer.toString(network.getCoverage());
case 1: return Integer.toString(network.getBandwidth());
case 2: return Integer.toString(network.getDelay());
case 3: return Integer.toString(network.getJitter());
case 4: return Double.toString(network.getBER());
case 5: return Double.toString(network.getThroughput());
case 6: return Double.toString(network.getBurstError());
case 7: return Double.toString(network.getPacketLossRatio());
case 8: return Double.toString(network.getCostRate());
case 9: return Double.toString(network.getTxPower());
case 10: return Double.toString(network.getRxPower());
case 11: return Double.toString(network.getRxPower());
case 12: return Double.toString(network.getIdlePower());
case 13: return Integer.toString(network.getMaxVelocity());
case 14: return Integer.toString(network.getMinVelocity());
}
return "";
}
}
}
public synchronized void updateInfo() {
for (int i = 0; i < deviceView.length; i++) {
((DeviceView)deviceView[i]).updateConnectedList();
}
showCurrentNetworkStatus();
}
}
| |
/*
* This file is part of Sponge, licensed under the MIT License (MIT).
*
* Copyright (c) SpongePowered <https://www.spongepowered.org>
* Copyright (c) contributors
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package org.spongepowered.vanilla.applaunch.handler;
import cpw.mods.gross.Java9ClassLoaderUtil;
import cpw.mods.modlauncher.TransformingClassLoader;
import cpw.mods.modlauncher.api.ILaunchHandlerService;
import cpw.mods.modlauncher.api.ITransformingClassLoader;
import cpw.mods.modlauncher.api.ITransformingClassLoaderBuilder;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.spongepowered.common.applaunch.AppLaunch;
import org.spongepowered.plugin.PluginResource;
import org.spongepowered.plugin.builtin.jvm.locator.JVMPluginResource;
import org.spongepowered.plugin.builtin.jvm.locator.ResourceType;
import org.spongepowered.vanilla.applaunch.plugin.VanillaPluginPlatform;
import java.io.File;
import java.io.IOException;
import java.lang.reflect.Field;
import java.net.JarURLConnection;
import java.net.MalformedURLException;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;
import java.net.URLConnection;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Collections;
import java.util.Enumeration;
import java.util.Iterator;
import java.util.List;
import java.util.NoSuchElementException;
import java.util.Optional;
import java.util.Set;
import java.util.concurrent.Callable;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import java.util.function.Function;
import java.util.function.Predicate;
import java.util.jar.JarFile;
import java.util.jar.Manifest;
/**
* The common Sponge {@link ILaunchHandlerService launch handler} for development
* and production environments.
*/
public abstract class AbstractVanillaLaunchHandler implements ILaunchHandlerService {
private static final String JAVA_HOME_PATH = System.getProperty("java.home");
protected final Logger logger = LogManager.getLogger("launch");
/**
* Classes or packages that mark jar files that should be excluded from the transformation path
*/
protected static final String[] NON_TRANSFORMABLE_PATHS = {
"org/spongepowered/asm/", // Mixin (for obvious reasons)
// because NIO Paths use different normalization than Instrumentation.appendToSystemClassLoaderSearch()
// (NIO uses uppercase URL encoding (ex. %2D), Instrumentation does not (ex. %2d)), this cannot appear in the transformer path at all
// This suppresses a warning from LoggerFactory.findPossibleStaticLoggerBinderPathSet
"org/slf4j/impl/", // slf4j
};
/**
* A list of packages to exclude from the {@link TransformingClassLoader transforming class loader},
* to be registered with {@link ITransformingClassLoader#addTargetPackageFilter(Predicate)}.
* <p>
* Packages should be scoped as tightly as possible - for example {@code "com.google.common."} is
* preferred over {@code "com.google."}.
* <p>
* Packages should always include a trailing full stop - for example if {@code "org.neptune"} was
* excluded, classes in {@code "org.neptunepowered"} would also be excluded. The correct usage would
* be to exclude {@code "org.neptune."}.
*/
private static final String[] EXCLUDED_PACKAGES = {
"org.spongepowered.plugin.",
"org.spongepowered.common.applaunch.",
"org.spongepowered.vanilla.applaunch.",
// configurate 4
"io.leangen.geantyref.",
"org.spongepowered.configurate.",
// terminal console bits
"org.jline.",
"org.fusesource.",
"net.minecrell.terminalconsole.",
"org.slf4j.",
// Maven artifacts -- specifically for versioning
"org.apache.maven.artifact."
};
private static final String[] EXCLUSION_EXCEPTIONS = {
"org.spongepowered.configurate.objectmapping.guice.",
"org.spongepowered.configurate.yaml.",
"org.spongepowered.configurate.gson.",
"org.spongepowered.configurate.jackson.",
"org.spongepowered.configurate.xml.",
};
@Override
public void configureTransformationClassLoader(final ITransformingClassLoaderBuilder builder) {
// Specifically requested to be available on the launch loader
final VanillaPluginPlatform platform = AppLaunch.pluginPlatform();
for (final Path path : platform.getStandardEnvironment().blackboard().getOrCreate(VanillaPluginPlatform.EXTRA_TRANSFORMABLE_PATHS, () -> Collections.emptyList())) {
builder.addTransformationPath(path);
}
// Plus everything else on the system loader
// todo: we might be able to eliminate this at some point, but that causes complications
for (final URL url : Java9ClassLoaderUtil.getSystemClassPathURLs()) {
try {
final URI uri = url.toURI();
if (!this.isTransformable(uri)) {
this.logger.debug("Non-transformable system classpath entry: {}", uri);
continue;
}
builder.addTransformationPath(Paths.get(uri));
this.logger.debug("Transformable system classpath entry: {}", uri);
} catch (final URISyntaxException | IOException ex) {
this.logger.error("Failed to add {} to transformation path", url, ex);
}
}
builder.setResourceEnumeratorLocator(this.getResourceLocator());
builder.setManifestLocator(this.getManifestLocator());
}
protected boolean isTransformable(final URI uri) throws URISyntaxException, IOException {
final File file = new File(uri);
// in Java 8 ONLY, the system classpath contains JVM internals
// let's make sure those don't get transformed
if (file.getAbsolutePath().startsWith(AbstractVanillaLaunchHandler.JAVA_HOME_PATH)) {
return false;
}
if (file.isDirectory()) {
for (final String test : AbstractVanillaLaunchHandler.NON_TRANSFORMABLE_PATHS) {
if (new File(file, test).exists()) {
return false;
}
}
} else if (file.isFile()) {
try (final JarFile jf = new JarFile(new File(uri))) {
for (final String test : AbstractVanillaLaunchHandler.NON_TRANSFORMABLE_PATHS) {
if (jf.getEntry(test) != null) {
return false;
}
}
}
}
return true;
}
@Override
public Callable<Void> launchService(final String[] arguments, final ITransformingClassLoader launchClassLoader) {
this.logger.info("Transitioning to Sponge launch, please wait...");
launchClassLoader.addTargetPackageFilter(klass -> {
outer: for (final String pkg : AbstractVanillaLaunchHandler.EXCLUDED_PACKAGES) {
if (klass.startsWith(pkg)) {
for (final String exception : AbstractVanillaLaunchHandler.EXCLUSION_EXCEPTIONS) {
if (klass.startsWith(exception)) {
break outer;
}
}
return false;
}
}
return true;
});
AbstractVanillaLaunchHandler.fixPackageExclusions(launchClassLoader);
return () -> {
this.launchService0(arguments, launchClassLoader);
return null;
};
}
@SuppressWarnings({"rawtypes", "unchecked"})
private static void fixPackageExclusions(final ITransformingClassLoader tcl) {
try {
final Field prefixField = tcl.getClass().getDeclaredField("SKIP_PACKAGE_PREFIXES");
prefixField.setAccessible(true);
((List) prefixField.get(null)).set(1, "__javax__noplswhy.");
} catch (NoSuchFieldException | IllegalAccessException ex) {
throw new RuntimeException("Failed to fix strange transformer exclusions", ex);
}
}
protected Function<String, Enumeration<URL>> getResourceLocator() {
return s -> {
// Save unnecessary searches of plugin classes for things that are definitely not plugins
// In this case: MC and fastutil
if (s.startsWith("net/minecraft") || s.startsWith("it/unimi")) {
return Collections.emptyEnumeration();
}
final URI asUri;
try {
asUri = new URI(null, null, s, null);
} catch (final URISyntaxException ex) {
this.logger.error("Failed to convert resource path {} to a URI", s, ex);
return Collections.emptyEnumeration();
}
return new Enumeration<URL>() {
final Iterator<Set<PluginResource>> serviceResources = ((VanillaPluginPlatform) AppLaunch.pluginPlatform()).getResources()
.values().iterator();
Iterator<PluginResource> resources;
URL next = this.computeNext();
@Override
public boolean hasMoreElements() {
return this.next != null;
}
@Override
public URL nextElement() {
final URL next = this.next;
if (next == null) {
throw new NoSuchElementException();
}
this.next = this.computeNext();
return next;
}
private URL computeNext() {
while (true) {
if (this.resources != null && !this.resources.hasNext()) {
this.resources = null;
}
if (this.resources == null) {
if (!this.serviceResources.hasNext()) {
return null;
}
this.resources = this.serviceResources.next().iterator();
}
if (this.resources.hasNext()) {
final PluginResource resource = this.resources.next();
if (resource instanceof JVMPluginResource) {
if (((JVMPluginResource) resource).type() != ResourceType.JAR) {
continue;
}
}
final Optional<URI> uri = resource.locateResource(asUri);
if (uri.isPresent()) {
try {
return uri.get().toURL();
} catch (final MalformedURLException ex) {
throw new RuntimeException(ex);
}
}
}
}
}
};
};
}
private final ConcurrentMap<URL, Optional<Manifest>> manifestCache = new ConcurrentHashMap<>();
private static final Optional<Manifest> UNKNOWN_MANIFEST = Optional.of(new Manifest());
private Function<URLConnection, Optional<Manifest>> getManifestLocator() {
return connection -> {
if (connection instanceof JarURLConnection) {
final URL jarFileUrl = ((JarURLConnection) connection).getJarFileURL();
final Optional<Manifest> manifest = this.manifestCache.computeIfAbsent(jarFileUrl, key -> {
for (final Set<PluginResource> resources : ((VanillaPluginPlatform) AppLaunch.pluginPlatform()).getResources().values()) {
for (final PluginResource resource : resources) {
if (resource instanceof JVMPluginResource) {
final JVMPluginResource jvmResource = (JVMPluginResource) resource;
try {
if (jvmResource.type() == ResourceType.JAR && ((JVMPluginResource) resource).path().toAbsolutePath().normalize().equals(Paths.get(key.toURI()).toAbsolutePath().normalize())) {
return jvmResource.manifest();
}
} catch (final URISyntaxException ex) {
this.logger.error("Failed to load manifest from jar {}: ", key, ex);
}
}
}
}
return AbstractVanillaLaunchHandler.UNKNOWN_MANIFEST;
});
try {
if (manifest == AbstractVanillaLaunchHandler.UNKNOWN_MANIFEST) {
return Optional.ofNullable(((JarURLConnection) connection).getManifest());
} else {
return manifest;
}
} catch (final IOException ex) {
this.logger.error("Failed to load manifest from jar {}: ", jarFileUrl, ex);
}
}
return Optional.empty();
};
}
/**
* Launch the service (Minecraft).
* <p>
* <strong>Take care</strong> to <strong>ONLY</strong> load classes on the provided
* {@link ClassLoader class loader}, which can be retrieved with {@link ITransformingClassLoader#getInstance()}.
*
* @param arguments The arguments to launch the service with
* @param launchClassLoader The transforming class loader to load classes with
* @throws Exception This can be any exception that occurs during the launch process
*/
protected abstract void launchService0(final String[] arguments, final ITransformingClassLoader launchClassLoader) throws Exception;
}
| |
/*
* 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.logging.log4j.core.util.datetime;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Objects;
import java.util.TimeZone;
import java.util.concurrent.TimeUnit;
/**
* Custom time formatter that trades flexibility for performance. This formatter only supports the date patterns defined
* in {@link FixedFormat}. For any other date patterns use {@link FastDateFormat}.
* <p>
* Related benchmarks: /log4j-perf/src/main/java/org/apache/logging/log4j/perf/jmh/TimeFormatBenchmark.java and
* /log4j-perf/src/main/java/org/apache/logging/log4j/perf/jmh/ThreadsafeDateFormatBenchmark.java
*/
public class FixedDateFormat {
/**
* Enumeration over the supported date/time format patterns.
* <p>
* Package protected for unit tests.
*/
public enum FixedFormat {
/**
* ABSOLUTE time format: {@code "HH:mm:ss,SSS"}.
*/
ABSOLUTE("HH:mm:ss,SSS", null, 0, ':', 1, ',', 1),
/**
* ABSOLUTE time format variation with period separator: {@code "HH:mm:ss.SSS"}.
*/
ABSOLUTE_PERIOD("HH:mm:ss.SSS", null, 0, ':', 1, '.', 1),
/**
* COMPACT time format: {@code "yyyyMMddHHmmssSSS"}.
*/
COMPACT("yyyyMMddHHmmssSSS", "yyyyMMdd", 0, ' ', 0, ' ', 0),
/**
* DATE_AND_TIME time format: {@code "dd MMM yyyy HH:mm:ss,SSS"}.
*/
DATE("dd MMM yyyy HH:mm:ss,SSS", "dd MMM yyyy ", 0, ':', 1, ',', 1),
/**
* DATE_AND_TIME time format variation with period separator: {@code "dd MMM yyyy HH:mm:ss.SSS"}.
*/
DATE_PERIOD("dd MMM yyyy HH:mm:ss.SSS", "dd MMM yyyy ", 0, ':', 1, '.', 1),
/**
* DEFAULT time format: {@code "yyyy-MM-dd HH:mm:ss,SSS"}.
*/
DEFAULT("yyyy-MM-dd HH:mm:ss,SSS", "yyyy-MM-dd ", 0, ':', 1, ',', 1),
/**
* DEFAULT time format variation with period separator: {@code "yyyy-MM-dd HH:mm:ss.SSS"}.
*/
DEFAULT_PERIOD("yyyy-MM-dd HH:mm:ss.SSS", "yyyy-MM-dd ", 0, ':', 1, '.', 1),
/**
* ISO8601_BASIC time format: {@code "yyyyMMdd'T'HHmmss,SSS"}.
*/
ISO8601_BASIC("yyyyMMdd'T'HHmmss,SSS", "yyyyMMdd'T'", 2, ' ', 0, ',', 1),
/**
* ISO8601_BASIC time format: {@code "yyyyMMdd'T'HHmmss.SSS"}.
*/
ISO8601_BASIC_PERIOD("yyyyMMdd'T'HHmmss.SSS", "yyyyMMdd'T'", 2, ' ', 0, '.', 1),
/**
* ISO8601 time format: {@code "yyyy-MM-dd'T'HH:mm:ss,SSS"}.
*/
ISO8601("yyyy-MM-dd'T'HH:mm:ss,SSS", "yyyy-MM-dd'T'", 2, ':', 1, ',', 1),
/**
* ISO8601 time format: {@code "yyyy-MM-dd'T'HH:mm:ss.SSS"}.
*/
ISO8601_PERIOD("yyyy-MM-dd'T'HH:mm:ss.SSS", "yyyy-MM-dd'T'", 2, ':', 1, '.', 1);
private final String pattern;
private final String datePattern;
private final int escapeCount;
private final char timeSeparatorChar;
private final int timeSeparatorLength;
private final char millisSeparatorChar;
private final int millisSeparatorLength;
FixedFormat(final String pattern, final String datePattern, final int escapeCount, final char timeSeparator,
final int timeSepLength, final char millisSeparator, final int millisSepLength) {
this.timeSeparatorChar = timeSeparator;
this.timeSeparatorLength = timeSepLength;
this.millisSeparatorChar = millisSeparator;
this.millisSeparatorLength = millisSepLength;
this.pattern = Objects.requireNonNull(pattern);
this.datePattern = datePattern; // may be null
this.escapeCount = escapeCount;
}
/**
* Returns the full pattern.
*
* @return the full pattern
*/
public String getPattern() {
return pattern;
}
/**
* Returns the date part of the pattern.
*
* @return the date part of the pattern
*/
public String getDatePattern() {
return datePattern;
}
/**
* Returns the FixedFormat with the name or pattern matching the specified string or {@code null} if not found.
*
* @param nameOrPattern the name or pattern to find a FixedFormat for
* @return the FixedFormat with the name or pattern matching the specified string
*/
public static FixedFormat lookup(final String nameOrPattern) {
for (final FixedFormat type : FixedFormat.values()) {
if (type.name().equals(nameOrPattern) || type.getPattern().equals(nameOrPattern)) {
return type;
}
}
return null;
}
/**
* Returns the length of the resulting formatted date and time strings.
*
* @return the length of the resulting formatted date and time strings
*/
public int getLength() {
return pattern.length() - escapeCount;
}
/**
* Returns the length of the date part of the resulting formatted string.
*
* @return the length of the date part of the resulting formatted string
*/
public int getDatePatternLength() {
return getDatePattern() == null ? 0 : getDatePattern().length() - escapeCount;
}
/**
* Returns the {@code FastDateFormat} object for formatting the date part of the pattern or {@code null} if the
* pattern does not have a date part.
*
* @return the {@code FastDateFormat} object for formatting the date part of the pattern or {@code null}
*/
public FastDateFormat getFastDateFormat() {
return getFastDateFormat(null);
}
/**
* Returns the {@code FastDateFormat} object for formatting the date part of the pattern or {@code null} if the
* pattern does not have a date part.
*
* @param tz the time zone to use
* @return the {@code FastDateFormat} object for formatting the date part of the pattern or {@code null}
*/
public FastDateFormat getFastDateFormat(final TimeZone tz) {
return getDatePattern() == null ? null : FastDateFormat.getInstance(getDatePattern(), tz);
}
}
private final FixedFormat fixedFormat;
private final TimeZone timeZone;
private final int length;
private final FastDateFormat fastDateFormat; // may be null
private final char timeSeparatorChar;
private final char millisSeparatorChar;
private final int timeSeparatorLength;
private final int millisSeparatorLength;
private volatile long midnightToday = 0;
private volatile long midnightTomorrow = 0;
private final int[] dstOffsets = new int[25];
// cachedDate does not need to be volatile because
// there is a write to a volatile field *after* cachedDate is modified,
// and there is a read from a volatile field *before* cachedDate is read.
// The Java memory model guarantees that because of the above,
// changes to cachedDate in one thread are visible to other threads.
// See http://g.oswego.edu/dl/jmm/cookbook.html
private char[] cachedDate; // may be null
private int dateLength;
/**
* Constructs a FixedDateFormat for the specified fixed format.
* <p>
* Package protected for unit tests.
*
* @param fixedFormat the fixed format
*/
FixedDateFormat(final FixedFormat fixedFormat, final TimeZone tz) {
this.fixedFormat = Objects.requireNonNull(fixedFormat);
this.timeZone = Objects.requireNonNull(tz);
this.timeSeparatorChar = fixedFormat.timeSeparatorChar;
this.timeSeparatorLength = fixedFormat.timeSeparatorLength;
this.millisSeparatorChar = fixedFormat.millisSeparatorChar;
this.millisSeparatorLength = fixedFormat.millisSeparatorLength;
this.length = fixedFormat.getLength();
this.fastDateFormat = fixedFormat.getFastDateFormat(tz);
}
public static FixedDateFormat createIfSupported(final String... options) {
if (options == null || options.length == 0 || options[0] == null) {
return new FixedDateFormat(FixedFormat.DEFAULT, TimeZone.getDefault());
}
final TimeZone tz;
if (options.length > 1) {
if (options[1] != null){
tz = TimeZone.getTimeZone(options[1]);
} else {
tz = TimeZone.getDefault();
}
} else if (options.length > 2) {
return null;
} else {
tz = TimeZone.getDefault();
}
final FixedFormat type = FixedFormat.lookup(options[0]);
return type == null ? null : new FixedDateFormat(type, tz);
}
/**
* Returns a new {@code FixedDateFormat} object for the specified {@code FixedFormat} and a {@code TimeZone.getDefault()} TimeZone.
*
* @param format the format to use
* @return a new {@code FixedDateFormat} object
*/
public static FixedDateFormat create(final FixedFormat format) {
return new FixedDateFormat(format, TimeZone.getDefault());
}
/**
* Returns a new {@code FixedDateFormat} object for the specified {@code FixedFormat} and TimeZone.
*
* @param format the format to use
* @param tz the time zone to use
* @return a new {@code FixedDateFormat} object
*/
public static FixedDateFormat create(final FixedFormat format, final TimeZone tz) {
return new FixedDateFormat(format, tz != null ? tz : TimeZone.getDefault());
}
/**
* Returns the full pattern of the selected fixed format.
*
* @return the full date-time pattern
*/
public String getFormat() {
return fixedFormat.getPattern();
}
/**
* Returns the time zone.
*
* @return the time zone
*/
public TimeZone getTimeZone() {
return timeZone;
}
/**
* <p>Returns the number of milliseconds since midnight in the time zone that this {@code FixedDateFormat}
* was constructed with for the specified currentTime.</p>
* <p>As a side effect, this method updates the cached formatted date and the cached date demarcation timestamps
* when the specified current time is outside the previously set demarcation timestamps for the start or end
* of the current day.</p>
* @param currentTime the current time in millis since the epoch
* @return the number of milliseconds since midnight for the specified time
*/
// Profiling showed this method is important to log4j performance. Modify with care!
// 30 bytes (allows immediate JVM inlining: <= -XX:MaxInlineSize=35 bytes)
public long millisSinceMidnight(final long currentTime) {
if (currentTime >= midnightTomorrow || currentTime < midnightToday) {
updateMidnightMillis(currentTime);
}
return currentTime - midnightToday;
}
private void updateMidnightMillis(final long now) {
if (now >= midnightTomorrow || now < midnightToday) {
synchronized (this) {
updateCachedDate(now);
midnightToday = calcMidnightMillis(now, 0);
midnightTomorrow = calcMidnightMillis(now, 1);
updateDaylightSavingTime();
}
}
}
private long calcMidnightMillis(final long time, final int addDays) {
final Calendar cal = Calendar.getInstance(timeZone);
cal.setTimeInMillis(time);
cal.set(Calendar.HOUR_OF_DAY, 0);
cal.set(Calendar.MINUTE, 0);
cal.set(Calendar.SECOND, 0);
cal.set(Calendar.MILLISECOND, 0);
cal.add(Calendar.DATE, addDays);
return cal.getTimeInMillis();
}
private void updateDaylightSavingTime() {
Arrays.fill(dstOffsets, 0);
final int ONE_HOUR = (int) TimeUnit.HOURS.toMillis(1);
if (timeZone.getOffset(midnightToday) != timeZone.getOffset(midnightToday + 23 * ONE_HOUR)) {
for (int i = 0; i < dstOffsets.length; i++) {
final long time = midnightToday + i * ONE_HOUR;
dstOffsets[i] = timeZone.getOffset(time) - timeZone.getRawOffset();
}
if (dstOffsets[0] > dstOffsets[23]) { // clock is moved backwards.
// we obtain midnightTonight with Calendar.getInstance(TimeZone), so it already includes raw offset
for (int i = dstOffsets.length - 1; i >= 0; i--) {
dstOffsets[i] -= dstOffsets[0]; //
}
}
}
}
private void updateCachedDate(final long now) {
if (fastDateFormat != null) {
final StringBuilder result = fastDateFormat.format(now, new StringBuilder());
cachedDate = result.toString().toCharArray();
dateLength = result.length();
}
}
// Profiling showed this method is important to log4j performance. Modify with care!
// 28 bytes (allows immediate JVM inlining: <= -XX:MaxInlineSize=35 bytes)
public String format(final long time) {
final char[] result = new char[length << 1]; // double size for locales with lengthy DateFormatSymbols
final int written = format(time, result, 0);
return new String(result, 0, written);
}
// Profiling showed this method is important to log4j performance. Modify with care!
// 31 bytes (allows immediate JVM inlining: <= -XX:MaxInlineSize=35 bytes)
public int format(final long time, final char[] buffer, final int startPos) {
// Calculate values by getting the ms values first and do then
// calculate the hour minute and second values divisions.
// Get daytime in ms: this does fit into an int
// int ms = (int) (time % 86400000);
final int ms = (int) (millisSinceMidnight(time));
writeDate(buffer, startPos);
return writeTime(ms, buffer, startPos + dateLength) - startPos;
}
// Profiling showed this method is important to log4j performance. Modify with care!
// 22 bytes (allows immediate JVM inlining: <= -XX:MaxInlineSize=35 bytes)
private void writeDate(final char[] buffer, final int startPos) {
if (cachedDate != null) {
System.arraycopy(cachedDate, 0, buffer, startPos, dateLength);
}
}
// Profiling showed this method is important to log4j performance. Modify with care!
// 262 bytes (will be inlined when hot enough: <= -XX:FreqInlineSize=325 bytes on Linux)
private int writeTime(int ms, final char[] buffer, int pos) {
final int hourOfDay = ms / 3600000;
final int hours = hourOfDay + daylightSavingTime(hourOfDay) / 3600000;
ms -= 3600000 * hourOfDay;
final int minutes = ms / 60000;
ms -= 60000 * minutes;
final int seconds = ms / 1000;
ms -= 1000 * seconds;
// Hour
int temp = hours / 10;
buffer[pos++] = ((char) (temp + '0'));
// Do subtract to get remainder instead of doing % 10
buffer[pos++] = ((char) (hours - 10 * temp + '0'));
buffer[pos] = timeSeparatorChar;
pos += timeSeparatorLength;
// Minute
temp = minutes / 10;
buffer[pos++] = ((char) (temp + '0'));
// Do subtract to get remainder instead of doing % 10
buffer[pos++] = ((char) (minutes - 10 * temp + '0'));
buffer[pos] = timeSeparatorChar;
pos += timeSeparatorLength;
// Second
temp = seconds / 10;
buffer[pos++] = ((char) (temp + '0'));
buffer[pos++] = ((char) (seconds - 10 * temp + '0'));
buffer[pos] = millisSeparatorChar;
pos += millisSeparatorLength;
// Millisecond
temp = ms / 100;
buffer[pos++] = ((char) (temp + '0'));
ms -= 100 * temp;
temp = ms / 10;
buffer[pos++] = ((char) (temp + '0'));
ms -= 10 * temp;
buffer[pos++] = ((char) (ms + '0'));
return pos;
}
private int daylightSavingTime(final int hourOfDay) {
return hourOfDay > 23 ? dstOffsets[23] : dstOffsets[hourOfDay];
}
}
| |
/*
* Copyright (c) Microsoft. All rights reserved.
* Licensed under the MIT license. See LICENSE file in the project root for full license information.
*/
package com.microsoft.azure.eventhubs;
import java.util.concurrent.*;
import java.util.function.*;
import com.microsoft.azure.servicebus.*;
/**
* This sender class is a logical representation of sending events to a specific EventHub partition. Do not use this class
* if you do not care about sending events to specific partitions. Instead, use {@link EventHubClient#send} method.
* @see EventHubClient#createPartitionSender(String)
* @see EventHubClient#createFromConnectionString(String)
*/
public final class PartitionSender extends ClientEntity
{
private final String partitionId;
private final String eventHubName;
private final MessagingFactory factory;
private MessageSender internalSender;
private PartitionSender(MessagingFactory factory, String eventHubName, String partitionId)
{
super(null);
this.partitionId = partitionId;
this.eventHubName = eventHubName;
this.factory = factory;
}
/**
* Internal-Only: factory pattern to Create EventHubSender
*/
static CompletableFuture<PartitionSender> Create(MessagingFactory factory, String eventHubName, String partitionId) throws ServiceBusException
{
final PartitionSender sender = new PartitionSender(factory, eventHubName, partitionId);
return sender.createInternalSender()
.thenApplyAsync(new Function<Void, PartitionSender>()
{
public PartitionSender apply(Void a)
{
return sender;
}
});
}
private CompletableFuture<Void> createInternalSender() throws ServiceBusException
{
return MessageSender.create(this.factory, StringUtil.getRandomString(),
String.format("%s/Partitions/%s", this.eventHubName, this.partitionId))
.thenAcceptAsync(new Consumer<MessageSender>()
{
public void accept(MessageSender a) { PartitionSender.this.internalSender = a;}
});
}
/**
* Synchronous version of {@link #send(EventData)} Api.
* @param data the {@link EventData} to be sent.
* @throws ServiceBusException if Service Bus service encountered problems during the operation.
*/
public final void sendSync(final EventData data)
throws ServiceBusException
{
try
{
this.send(data).get();
}
catch (InterruptedException|ExecutionException exception)
{
if (exception instanceof InterruptedException)
{
// Re-assert the thread's interrupted status
Thread.currentThread().interrupt();
}
Throwable throwable = exception.getCause();
if (throwable != null)
{
if (throwable instanceof RuntimeException)
{
throw (RuntimeException)throwable;
}
if (throwable instanceof ServiceBusException)
{
throw (ServiceBusException)throwable;
}
throw new ServiceBusException(true, throwable);
}
}
}
/**
* Send {@link EventData} to a specific EventHub partition. The target partition is pre-determined when this PartitionSender was created.
* This send pattern emphasize data correlation over general availability and latency.
* <p>
* There are 3 ways to send to EventHubs, each exposed as a method (along with its sendBatch overload):
* <pre>
* i. {@link EventHubClient#send(EventData)} or {@link EventHubClient#send(Iterable)}
* ii. {@link EventHubClient#send(EventData, String)} or {@link EventHubClient#send(Iterable, String)}
* iii. {@link PartitionSender#send(EventData)} or {@link PartitionSender#send(Iterable)}
* </pre>
*
* Use this type of Send, if:
* <pre>
* i. The client wants to take direct control of distribution of data across partitions. In this case client is responsible for making sure there is at least one sender per event hub partition.
* ii. User cannot use partition key as a mean to direct events to specific partition, yet there is a need for data correlation with partitioning scheme.
* </pre>
*
* @param data the {@link EventData} to be sent.
* @return a CompletableFuture that can be completed when the send operations is done..
* @throws PayloadSizeExceededException if the total size of the {@link EventData} exceeds a pre-defined limit set by the service. Default is 256k bytes.
* @throws ServiceBusException if Service Bus service encountered problems during the operation.
*/
public final CompletableFuture<Void> send(EventData data)
throws ServiceBusException
{
return this.internalSender.send(data.toAmqpMessage());
}
/**
* Synchronous version of {@link #send(Iterable)} .
* @param eventDatas batch of events to send to EventHub
* @throws ServiceBusException if Service Bus service encountered problems during the operation.
*/
public final void sendSync(final Iterable<EventData> eventDatas)
throws ServiceBusException
{
try
{
this.send(eventDatas).get();
}
catch (InterruptedException|ExecutionException exception)
{
if (exception instanceof InterruptedException)
{
// Re-assert the thread's interrupted status
Thread.currentThread().interrupt();
}
Throwable throwable = exception.getCause();
if (throwable != null)
{
if (throwable instanceof RuntimeException)
{
throw (RuntimeException)throwable;
}
if (throwable instanceof ServiceBusException)
{
throw (ServiceBusException)throwable;
}
throw new ServiceBusException(true, throwable);
}
}
}
/**
* Send {@link EventData} to a specific EventHub partition. The targeted partition is pre-determined when this PartitionSender was created.
* <p>
* There are 3 ways to send to EventHubs, to understand this particular type of Send refer to the overload {@link #send(EventData)}, which is the same type of Send and is used to send single {@link EventData}.
* <p>
* Sending a batch of {@link EventData}'s is useful in the following cases:
* <pre>
* i. Efficient send - sending a batch of {@link EventData} maximizes the overall throughput by optimally using the number of sessions created to EventHubs' service.
* ii. Send multiple {@link EventData}'s in a Transaction. To achieve ACID properties, the Gateway Service will forward all {@link EventData}'s in the batch to a single EventHubs' partition.
* </pre>
* <p>
* Sample code (sample uses sync version of the api but concept are identical):
* <pre>
* Gson gson = new GsonBuilder().create();
* EventHubClient client = EventHubClient.createFromConnectionStringSync("__connection__");
* PartitionSender senderToPartitionOne = client.createPartitionSenderSync("1");
*
* while (true)
* {
* LinkedList{@literal<}EventData{@literal>} events = new LinkedList{@literal<}EventData{@literal>}();
* for (int count = 1; count {@literal<} 11; count++)
* {
* PayloadEvent payload = new PayloadEvent(count);
* byte[] payloadBytes = gson.toJson(payload).getBytes(Charset.defaultCharset());
* EventData sendEvent = new EventData(payloadBytes);
* Map{@literal<}String, String{@literal>} applicationProperties = new HashMap{@literal<}String, String{@literal>}();
* applicationProperties.put("from", "javaClient");
* sendEvent.setProperties(applicationProperties);
* events.add(sendEvent);
* }
*
* senderToPartitionOne.sendSync(events);
* System.out.println(String.format("Sent Batch... Size: %s", events.size()));
* }
* </pre>
* @param eventDatas batch of events to send to EventHub
* @return a CompletableFuture that can be completed when the send operations is done..
* @throws PayloadSizeExceededException if the total size of the {@link EventData} exceeds a pre-defined limit set by the service. Default is 256k bytes.
* @throws ServiceBusException if Service Bus service encountered problems during the operation.
*/
public final CompletableFuture<Void> send(Iterable<EventData> eventDatas)
throws ServiceBusException
{
if (eventDatas == null || IteratorUtil.sizeEquals(eventDatas, 0))
{
throw new IllegalArgumentException("EventData batch cannot be empty.");
}
return this.internalSender.send(EventDataUtil.toAmqpMessages(eventDatas));
}
@Override
public CompletableFuture<Void> close()
{
if (this.internalSender == null)
{
return CompletableFuture.completedFuture(null);
}
else
{
return this.internalSender.close();
}
}
}
| |
package com.sciul.recurly.model;
import java.util.List;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlType;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
/**
* The Class Subscription.
*
* @author GauravChawla
*/
@JsonIgnoreProperties
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "", propOrder = { "account", "invoice", "plan", "uuid", "state", "unitAmountInCents", "currency",
"quantity", "activatedAt", "canceledAt", "expiresAt", "currentPeriodStartedAt", "currentPeriodEndsAt",
"trialStartedAt", "trialEndsAt", "taxInCents", "taxType", "taxRegion", "taxRate", "poNumber", "netTerms",
"collectionMethod", "subscriptionAddOns", "a", "planCode" })
@XmlRootElement(name = "subscription")
public class Subscription {
/** The account. */
@XmlElement(required = true)
private Subscription.Account account;
/** The invoice. */
@XmlElement(required = true)
private Invoice invoice;
/** The plan. */
@XmlElement(required = true)
private Plan plan;
/** The uuid. */
@XmlElement(required = true)
private String uuid;
/** The state. */
@XmlElement(required = true)
private String state;
/** The unit amount in cents. */
@XmlElement(name = "unit_amount_in_cents")
private UnitAmountInCents unitAmountInCents;
/** The currency. */
@XmlElement(required = true)
private String currency;
/** The quantity. */
@XmlElement(required = true)
private Quantity quantity;
/** The activated at. */
@XmlElement(name = "activated_at")
private ActivatedAt activatedAt;
/** The canceled at. */
@XmlElement(name = "canceled_at")
private CanceledAt canceledAt;
/** The expires at. */
@XmlElement(name = "expires_at")
private ExpiresAt expiresAt;
/** The current period started at. */
@XmlElement(name = "current_period_started_at")
private CurrentPeriodStartedAt currentPeriodStartedAt;
/** The current period ends at. */
@XmlElement(name = "current_period_ends_at")
private CurrentPeriodEndsAt currentPeriodEndsAt;
/** The trial started at. */
@XmlElement(name = "trial_started_at")
private TrialStartedAt trialStartedAt;
/** The trial ends at. */
@XmlElement(name = "trial_ends_at")
private TrialEndsAt trialEndsAt;
/** The tax in cents. */
@XmlElement(name = "tax_in_cents")
private TaxInCents taxInCents;
/** The tax type. */
@XmlElement(name = "tax_type")
private String taxType;
/** The tax region. */
@XmlElement(name = "tax_region")
private String taxRegion;
/** The tax rate. */
@XmlElement(name = "tax_rate")
private TaxRate taxRate;
/** The po number. */
@XmlElement(name = "po_number")
private PoNumber poNumber;
/** The net terms. */
@XmlElement(name = "net_terms")
private NetTerms netTerms;
/** The collection method. */
@XmlElement(name = "collection_method")
private String collectionMethod;
/** The subscription add ons. */
@XmlElement(name = "subscription_add_ons")
private SubscriptionAddOns subscriptionAddOns;
/** The a. */
@XmlElement
private List<A> a;
/** The href. */
@XmlAttribute(name = "href")
private String href;
/** The plan code. */
@XmlElement(name = "plan_code")
private String planCode;
/**
* Gets the plan code.
*
* @return the plan code
*/
public String getPlanCode() {
return planCode;
}
/**
* Sets the plan code.
*
* @param planCode
* the new plan code
*/
public void setPlanCode(String planCode) {
this.planCode = planCode;
}
/**
* Gets the account.
*
* @return the account
*/
public Account getAccount() {
return account;
}
/**
* Sets the account.
*
* @param account
* the new account
*/
public void setAccount(Account account) {
this.account = account;
}
/**
* Gets the invoice.
*
* @return the invoice
*/
public Invoice getInvoice() {
return invoice;
}
/**
* Sets the invoice.
*
* @param invoice
* the new invoice
*/
public void setInvoice(Invoice invoice) {
this.invoice = invoice;
}
/**
* Gets the plan.
*
* @return the plan
*/
public Plan getPlan() {
return plan;
}
/**
* Sets the plan.
*
* @param plan
* the new plan
*/
public void setPlan(Plan plan) {
this.plan = plan;
}
/**
* Gets the uuid.
*
* @return the uuid
*/
public String getUuid() {
return uuid;
}
/**
* Sets the uuid.
*
* @param uuid
* the new uuid
*/
public void setUuid(String uuid) {
this.uuid = uuid;
}
/**
* Gets the state.
*
* @return the state
*/
public String getState() {
return state;
}
/**
* Sets the state.
*
* @param state
* the new state
*/
public void setState(String state) {
this.state = state;
}
/**
* Gets the unit amount in cents.
*
* @return the unit amount in cents
*/
public UnitAmountInCents getUnitAmountInCents() {
return unitAmountInCents;
}
/**
* Sets the unit amount in cents.
*
* @param unitAmountInCents
* the new unit amount in cents
*/
public void setUnitAmountInCents(UnitAmountInCents unitAmountInCents) {
this.unitAmountInCents = unitAmountInCents;
}
/**
* Gets the currency.
*
* @return the currency
*/
public String getCurrency() {
return currency;
}
/**
* Sets the currency.
*
* @param currency
* the new currency
*/
public void setCurrency(String currency) {
this.currency = currency;
}
/**
* Gets the quantity.
*
* @return the quantity
*/
public Quantity getQuantity() {
return quantity;
}
/**
* Sets the quantity.
*
* @param quantity
* the new quantity
*/
public void setQuantity(Quantity quantity) {
this.quantity = quantity;
}
/**
* Gets the activated at.
*
* @return the activated at
*/
public ActivatedAt getActivatedAt() {
return activatedAt;
}
/**
* Sets the activated at.
*
* @param activatedAt
* the new activated at
*/
public void setActivatedAt(ActivatedAt activatedAt) {
this.activatedAt = activatedAt;
}
/**
* Gets the canceled at.
*
* @return the canceled at
*/
public CanceledAt getCanceledAt() {
return canceledAt;
}
/**
* Sets the canceled at.
*
* @param canceledAt
* the new canceled at
*/
public void setCanceledAt(CanceledAt canceledAt) {
this.canceledAt = canceledAt;
}
/**
* Gets the expires at.
*
* @return the expires at
*/
public ExpiresAt getExpiresAt() {
return expiresAt;
}
/**
* Sets the expires at.
*
* @param expiresAt
* the new expires at
*/
public void setExpiresAt(ExpiresAt expiresAt) {
this.expiresAt = expiresAt;
}
/**
* Gets the current period started at.
*
* @return the current period started at
*/
public CurrentPeriodStartedAt getCurrentPeriodStartedAt() {
return currentPeriodStartedAt;
}
/**
* Sets the current period started at.
*
* @param currentPeriodStartedAt
* the new current period started at
*/
public void setCurrentPeriodStartedAt(CurrentPeriodStartedAt currentPeriodStartedAt) {
this.currentPeriodStartedAt = currentPeriodStartedAt;
}
/**
* Gets the current period ends at.
*
* @return the current period ends at
*/
public CurrentPeriodEndsAt getCurrentPeriodEndsAt() {
return currentPeriodEndsAt;
}
/**
* Sets the current period ends at.
*
* @param currentPeriodEndsAt
* the new current period ends at
*/
public void setCurrentPeriodEndsAt(CurrentPeriodEndsAt currentPeriodEndsAt) {
this.currentPeriodEndsAt = currentPeriodEndsAt;
}
/**
* Gets the trial started at.
*
* @return the trial started at
*/
public TrialStartedAt getTrialStartedAt() {
return trialStartedAt;
}
/**
* Sets the trial started at.
*
* @param trialStartedAt
* the new trial started at
*/
public void setTrialStartedAt(TrialStartedAt trialStartedAt) {
this.trialStartedAt = trialStartedAt;
}
/**
* Gets the trial ends at.
*
* @return the trial ends at
*/
public TrialEndsAt getTrialEndsAt() {
return trialEndsAt;
}
/**
* Sets the trial ends at.
*
* @param trialEndsAt
* the new trial ends at
*/
public void setTrialEndsAt(TrialEndsAt trialEndsAt) {
this.trialEndsAt = trialEndsAt;
}
/**
* Gets the tax in cents.
*
* @return the tax in cents
*/
public TaxInCents getTaxInCents() {
return taxInCents;
}
/**
* Sets the tax in cents.
*
* @param taxInCents
* the new tax in cents
*/
public void setTaxInCents(TaxInCents taxInCents) {
this.taxInCents = taxInCents;
}
/**
* Gets the tax type.
*
* @return the tax type
*/
public String getTaxType() {
return taxType;
}
/**
* Sets the tax type.
*
* @param taxType
* the new tax type
*/
public void setTaxType(String taxType) {
this.taxType = taxType;
}
/**
* Gets the tax region.
*
* @return the tax region
*/
public String getTaxRegion() {
return taxRegion;
}
/**
* Sets the tax region.
*
* @param taxRegion
* the new tax region
*/
public void setTaxRegion(String taxRegion) {
this.taxRegion = taxRegion;
}
/**
* Gets the tax rate.
*
* @return the tax rate
*/
public TaxRate getTaxRate() {
return taxRate;
}
/**
* Sets the tax rate.
*
* @param taxRate
* the new tax rate
*/
public void setTaxRate(TaxRate taxRate) {
this.taxRate = taxRate;
}
/**
* Gets the po number.
*
* @return the po number
*/
public PoNumber getPoNumber() {
return poNumber;
}
/**
* Sets the po number.
*
* @param poNumber
* the new po number
*/
public void setPoNumber(PoNumber poNumber) {
this.poNumber = poNumber;
}
/**
* Gets the net terms.
*
* @return the net terms
*/
public NetTerms getNetTerms() {
return netTerms;
}
/**
* Sets the net terms.
*
* @param netTerms
* the new net terms
*/
public void setNetTerms(NetTerms netTerms) {
this.netTerms = netTerms;
}
/**
* Gets the collection method.
*
* @return the collection method
*/
public String getCollectionMethod() {
return collectionMethod;
}
/**
* Sets the collection method.
*
* @param collectionMethod
* the new collection method
*/
public void setCollectionMethod(String collectionMethod) {
this.collectionMethod = collectionMethod;
}
/**
* Gets the subscription add ons.
*
* @return the subscription add ons
*/
public SubscriptionAddOns getSubscriptionAddOns() {
return subscriptionAddOns;
}
/**
* Sets the subscription add ons.
*
* @param subscriptionAddOns
* the new subscription add ons
*/
public void setSubscriptionAddOns(SubscriptionAddOns subscriptionAddOns) {
this.subscriptionAddOns = subscriptionAddOns;
}
/**
* Gets the a.
*
* @return the a
*/
public List<A> getA() {
return a;
}
/**
* Sets the a.
*
* @param a
* the new a
*/
public void setA(List<A> a) {
this.a = a;
}
/**
* Gets the href.
*
* @return the href
*/
public String getHref() {
return href;
}
/**
* Sets the href.
*
* @param href
* the new href
*/
public void setHref(String href) {
this.href = href;
}
/**
* The Class Account.
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "", propOrder = { "accountCode", "email", "firstName", "lastName" })
public static class Account {
/** The account code. */
@XmlElement(name = "account_code")
protected String accountCode;
/** The email. */
@XmlElement(required = true)
protected String email;
/** The first name. */
@XmlElement(name = "first_name", required = true)
protected String firstName;
/** The last name. */
@XmlElement(name = "last_name", required = true)
protected String lastName;
/**
* Gets the account code.
*
* @return the account code
*/
public String getAccountCode() {
return accountCode;
}
/**
* Sets the account code.
*
* @param accountCode
* the new account code
*/
public void setAccountCode(String accountCode) {
this.accountCode = accountCode;
}
/**
* Gets the email.
*
* @return the email
*/
public String getEmail() {
return email;
}
/**
* Sets the email.
*
* @param email
* the new email
*/
public void setEmail(String email) {
this.email = email;
}
/**
* Gets the first name.
*
* @return the first name
*/
public String getFirstName() {
return firstName;
}
/**
* Sets the first name.
*
* @param firstName
* the new first name
*/
public void setFirstName(String firstName) {
this.firstName = firstName;
}
/**
* Gets the last name.
*
* @return the last name
*/
public String getLastName() {
return lastName;
}
/**
* Sets the last name.
*
* @param lastName
* the new last name
*/
public void setLastName(String lastName) {
this.lastName = lastName;
}
}
}
| |
/**
* 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.pulsar.io;
import static org.apache.pulsar.broker.auth.MockedPulsarServiceBaseTest.retryStrategically;
import static org.apache.pulsar.functions.worker.PulsarFunctionLocalRunTest.getPulsarIOBatchDataGeneratorNar;
import static org.testng.Assert.assertEquals;
import static org.testng.Assert.assertNotNull;
import static org.testng.Assert.assertTrue;
import java.util.Map;
import java.util.Set;
import org.apache.pulsar.client.admin.PulsarAdminException;
import org.apache.pulsar.common.functions.FunctionConfig;
import org.apache.pulsar.common.functions.Utils;
import org.apache.pulsar.common.io.BatchSourceConfig;
import org.apache.pulsar.common.io.SourceConfig;
import org.apache.pulsar.common.policies.data.TopicStats;
import org.apache.pulsar.functions.utils.FunctionCommon;
import org.apache.pulsar.functions.worker.PulsarFunctionTestUtils;
import org.apache.pulsar.io.batchdiscovery.ImmediateTriggerer;
import org.testng.annotations.Test;
import com.google.common.collect.Lists;
import com.google.common.collect.Sets;
@Test(groups = "broker-io")
public class PulsarBatchSourceE2ETest extends AbstractPulsarE2ETest {
private void testPulsarBatchSourceStats(String jarFilePathUrl) throws Exception {
final String namespacePortion = "io";
final String replNamespace = tenant + "/" + namespacePortion;
final String sinkTopic = "persistent://" + replNamespace + "/output";
final String sourceName = "PulsarBatchSource";
admin.namespaces().createNamespace(replNamespace);
Set<String> clusters = Sets.newHashSet(Lists.newArrayList("use"));
admin.namespaces().setNamespaceReplicationClusters(replNamespace, clusters);
SourceConfig sourceConfig = createSourceConfig(tenant, namespacePortion, sourceName, sinkTopic);
sourceConfig.setBatchSourceConfig(createBatchSourceConfig());
retryStrategically((test) -> {
try {
return (admin.topics().getStats(sinkTopic).publishers.size() == 1);
} catch (PulsarAdminException e) {
return false;
}
}, 10, 150);
final String sinkTopic2 = "persistent://" + replNamespace + "/output-" + sourceName;
sourceConfig.setTopicName(sinkTopic2);
if (jarFilePathUrl.startsWith(Utils.BUILTIN)) {
sourceConfig.setArchive(jarFilePathUrl);
admin.sources().createSource(sourceConfig, jarFilePathUrl);
} else {
admin.sources().createSourceWithUrl(sourceConfig, jarFilePathUrl);
}
retryStrategically((test) -> {
try {
TopicStats sourceStats = admin.topics().getStats(sinkTopic2);
return sourceStats.publishers.size() == 1
&& sourceStats.publishers.get(0).metadata != null
&& sourceStats.publishers.get(0).metadata.containsKey("id")
&& sourceStats.publishers.get(0).metadata.get("id").equals(String.format("%s/%s/%s", tenant, namespacePortion, sourceName));
} catch (PulsarAdminException e) {
return false;
}
}, 50, 150);
TopicStats sourceStats = admin.topics().getStats(sinkTopic2);
assertEquals(sourceStats.publishers.size(), 1);
assertNotNull(sourceStats.publishers.get(0).metadata);
assertTrue(sourceStats.publishers.get(0).metadata.containsKey("id"));
assertEquals(sourceStats.publishers.get(0).metadata.get("id"), String.format("%s/%s/%s", tenant, namespacePortion, sourceName));
retryStrategically((test) -> {
try {
return (admin.topics().getStats(sinkTopic2).publishers.size() == 1) && (admin.topics().getInternalStats(sinkTopic2, false).numberOfEntries > 4);
} catch (PulsarAdminException e) {
return false;
}
}, 50, 150);
assertEquals(admin.topics().getStats(sinkTopic2).publishers.size(), 1);
String prometheusMetrics = PulsarFunctionTestUtils.getPrometheusMetrics(pulsar.getListenPortHTTP().get());
log.info("prometheusMetrics: {}", prometheusMetrics);
Map<String, PulsarFunctionTestUtils.Metric> metrics = PulsarFunctionTestUtils.parseMetrics(prometheusMetrics);
PulsarFunctionTestUtils.Metric m = metrics.get("pulsar_source_received_total");
assertEquals(m.tags.get("cluster"), config.getClusterName());
assertEquals(m.tags.get("instance_id"), "0");
assertEquals(m.tags.get("name"), sourceName);
assertEquals(m.tags.get("namespace"), String.format("%s/%s", tenant, namespacePortion));
assertEquals(m.tags.get("fqfn"), FunctionCommon.getFullyQualifiedName(tenant, namespacePortion, sourceName));
assertTrue(m.value > 0.0);
m = metrics.get("pulsar_source_received_total_1min");
assertEquals(m.tags.get("cluster"), config.getClusterName());
assertEquals(m.tags.get("instance_id"), "0");
assertEquals(m.tags.get("name"), sourceName);
assertEquals(m.tags.get("namespace"), String.format("%s/%s", tenant, namespacePortion));
assertEquals(m.tags.get("fqfn"), FunctionCommon.getFullyQualifiedName(tenant, namespacePortion, sourceName));
assertTrue(m.value > 0.0);
m = metrics.get("pulsar_source_written_total");
assertEquals(m.tags.get("cluster"), config.getClusterName());
assertEquals(m.tags.get("instance_id"), "0");
assertEquals(m.tags.get("name"), sourceName);
assertEquals(m.tags.get("namespace"), String.format("%s/%s", tenant, namespacePortion));
assertEquals(m.tags.get("fqfn"), FunctionCommon.getFullyQualifiedName(tenant, namespacePortion, sourceName));
assertTrue(m.value > 0.0);
m = metrics.get("pulsar_source_written_total_1min");
assertEquals(m.tags.get("cluster"), config.getClusterName());
assertEquals(m.tags.get("instance_id"), "0");
assertEquals(m.tags.get("name"), sourceName);
assertEquals(m.tags.get("namespace"), String.format("%s/%s", tenant, namespacePortion));
assertEquals(m.tags.get("fqfn"), FunctionCommon.getFullyQualifiedName(tenant, namespacePortion, sourceName));
assertTrue(m.value > 0.0);
m = metrics.get("pulsar_source_source_exceptions_total");
assertEquals(m.tags.get("cluster"), config.getClusterName());
assertEquals(m.tags.get("instance_id"), "0");
assertEquals(m.tags.get("name"), sourceName);
assertEquals(m.tags.get("namespace"), String.format("%s/%s", tenant, namespacePortion));
assertEquals(m.tags.get("fqfn"), FunctionCommon.getFullyQualifiedName(tenant, namespacePortion, sourceName));
assertEquals(m.value, 0.0);
m = metrics.get("pulsar_source_source_exceptions_total_1min");
assertEquals(m.tags.get("cluster"), config.getClusterName());
assertEquals(m.tags.get("instance_id"), "0");
assertEquals(m.tags.get("name"), sourceName);
assertEquals(m.tags.get("namespace"), String.format("%s/%s", tenant, namespacePortion));
assertEquals(m.tags.get("fqfn"), FunctionCommon.getFullyQualifiedName(tenant, namespacePortion, sourceName));
assertEquals(m.value, 0.0);
m = metrics.get("pulsar_source_system_exceptions_total");
assertEquals(m.tags.get("cluster"), config.getClusterName());
assertEquals(m.tags.get("instance_id"), "0");
assertEquals(m.tags.get("name"), sourceName);
assertEquals(m.tags.get("namespace"), String.format("%s/%s", tenant, namespacePortion));
assertEquals(m.tags.get("fqfn"), FunctionCommon.getFullyQualifiedName(tenant, namespacePortion, sourceName));
assertEquals(m.value, 0.0);
m = metrics.get("pulsar_source_system_exceptions_total_1min");
assertEquals(m.tags.get("cluster"), config.getClusterName());
assertEquals(m.tags.get("instance_id"), "0");
assertEquals(m.tags.get("name"), sourceName);
assertEquals(m.tags.get("namespace"), String.format("%s/%s", tenant, namespacePortion));
assertEquals(m.tags.get("fqfn"), FunctionCommon.getFullyQualifiedName(tenant, namespacePortion, sourceName));
assertEquals(m.value, 0.0);
m = metrics.get("pulsar_source_last_invocation");
assertEquals(m.tags.get("cluster"), config.getClusterName());
assertEquals(m.tags.get("instance_id"), "0");
assertEquals(m.tags.get("name"), sourceName);
assertEquals(m.tags.get("namespace"), String.format("%s/%s", tenant, namespacePortion));
assertEquals(m.tags.get("fqfn"), FunctionCommon.getFullyQualifiedName(tenant, namespacePortion, sourceName));
assertTrue(m.value > 0.0);
tempDirectory.assertThatFunctionDownloadTempFilesHaveBeenDeleted();
admin.sources().deleteSource(tenant, namespacePortion, sourceName);
}
@Test(timeOut = 20000, groups = "builtin")
public void testPulsarBatchSourceStatsBuiltin() throws Exception {
String jarFilePathUrl = String.format("%s://batch-data-generator", Utils.BUILTIN);
testPulsarBatchSourceStats(jarFilePathUrl);
}
@Test(timeOut = 20000)
private void testPulsarBatchSourceStatsWithFile() throws Exception {
String jarFilePathUrl = getPulsarIOBatchDataGeneratorNar().toURI().toString();
testPulsarBatchSourceStats(jarFilePathUrl);
}
@Test(timeOut = 40000)
private void testPulsarBatchSourceStatsWithUrl() throws Exception {
testPulsarBatchSourceStats(fileServer.getUrl("/pulsar-io-batch-data-generator.nar"));
}
private static SourceConfig createSourceConfig(String tenant, String namespace, String functionName, String sinkTopic) {
SourceConfig sourceConfig = new SourceConfig();
sourceConfig.setTenant(tenant);
sourceConfig.setNamespace(namespace);
sourceConfig.setName(functionName);
sourceConfig.setParallelism(1);
sourceConfig.setProcessingGuarantees(FunctionConfig.ProcessingGuarantees.ATLEAST_ONCE);
sourceConfig.setTopicName(sinkTopic);
return sourceConfig;
}
private static BatchSourceConfig createBatchSourceConfig() {
return BatchSourceConfig.builder()
.discoveryTriggererClassName(ImmediateTriggerer.class.getName())
.build();
}
}
| |
package com.fsck.k9.mail.internet;
import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Locale;
import java.util.Map;
import java.util.regex.Pattern;
import android.support.annotation.NonNull;
import com.fsck.k9.mail.Body;
import com.fsck.k9.mail.BodyPart;
import com.fsck.k9.mail.Message;
import com.fsck.k9.mail.MessagingException;
import com.fsck.k9.mail.Multipart;
import com.fsck.k9.mail.Part;
import org.apache.james.mime4j.codec.Base64InputStream;
import org.apache.james.mime4j.codec.QuotedPrintableInputStream;
import org.apache.james.mime4j.util.MimeUtil;
import timber.log.Timber;
public class MimeUtility {
public static final String DEFAULT_ATTACHMENT_MIME_TYPE = "application/octet-stream";
public static final String K9_SETTINGS_MIME_TYPE = "application/x-k9settings";
/*
* http://www.w3schools.com/media/media_mimeref.asp
* +
* http://www.stdicon.com/mimetypes
*/
private static final String[][] MIME_TYPE_BY_EXTENSION_MAP = new String[][] {
//* Do not delete the next three lines
{ "", DEFAULT_ATTACHMENT_MIME_TYPE },
{ "k9s", K9_SETTINGS_MIME_TYPE},
{ "txt", "text/plain"},
//* Do not delete the previous three lines
{ "123", "application/vnd.lotus-1-2-3"},
{ "323", "text/h323"},
{ "3dml", "text/vnd.in3d.3dml"},
{ "3g2", "video/3gpp2"},
{ "3gp", "video/3gpp"},
{ "aab", "application/x-authorware-bin"},
{ "aac", "audio/x-aac"},
{ "aam", "application/x-authorware-map"},
{ "a", "application/octet-stream"},
{ "aas", "application/x-authorware-seg"},
{ "abw", "application/x-abiword"},
{ "acc", "application/vnd.americandynamics.acc"},
{ "ace", "application/x-ace-compressed"},
{ "acu", "application/vnd.acucobol"},
{ "acutc", "application/vnd.acucorp"},
{ "acx", "application/internet-property-stream"},
{ "adp", "audio/adpcm"},
{ "aep", "application/vnd.audiograph"},
{ "afm", "application/x-font-type1"},
{ "afp", "application/vnd.ibm.modcap"},
{ "ai", "application/postscript"},
{ "aif", "audio/x-aiff"},
{ "aifc", "audio/x-aiff"},
{ "aiff", "audio/x-aiff"},
{ "air", "application/vnd.adobe.air-application-installer-package+zip"},
{ "ami", "application/vnd.amiga.ami"},
{ "apk", "application/vnd.android.package-archive"},
{ "application", "application/x-ms-application"},
{ "apr", "application/vnd.lotus-approach"},
{ "asc", "application/pgp-signature"},
{ "asf", "video/x-ms-asf"},
{ "asm", "text/x-asm"},
{ "aso", "application/vnd.accpac.simply.aso"},
{ "asr", "video/x-ms-asf"},
{ "asx", "video/x-ms-asf"},
{ "atc", "application/vnd.acucorp"},
{ "atom", "application/atom+xml"},
{ "atomcat", "application/atomcat+xml"},
{ "atomsvc", "application/atomsvc+xml"},
{ "atx", "application/vnd.antix.game-component"},
{ "au", "audio/basic"},
{ "avi", "video/x-msvideo"},
{ "aw", "application/applixware"},
{ "axs", "application/olescript"},
{ "azf", "application/vnd.airzip.filesecure.azf"},
{ "azs", "application/vnd.airzip.filesecure.azs"},
{ "azw", "application/vnd.amazon.ebook"},
{ "bas", "text/plain"},
{ "bat", "application/x-msdownload"},
{ "bcpio", "application/x-bcpio"},
{ "bdf", "application/x-font-bdf"},
{ "bdm", "application/vnd.syncml.dm+wbxml"},
{ "bh2", "application/vnd.fujitsu.oasysprs"},
{ "bin", "application/octet-stream"},
{ "bmi", "application/vnd.bmi"},
{ "bmp", "image/bmp"},
{ "book", "application/vnd.framemaker"},
{ "box", "application/vnd.previewsystems.box"},
{ "boz", "application/x-bzip2"},
{ "bpk", "application/octet-stream"},
{ "btif", "image/prs.btif"},
{ "bz2", "application/x-bzip2"},
{ "bz", "application/x-bzip"},
{ "c4d", "application/vnd.clonk.c4group"},
{ "c4f", "application/vnd.clonk.c4group"},
{ "c4g", "application/vnd.clonk.c4group"},
{ "c4p", "application/vnd.clonk.c4group"},
{ "c4u", "application/vnd.clonk.c4group"},
{ "cab", "application/vnd.ms-cab-compressed"},
{ "car", "application/vnd.curl.car"},
{ "cat", "application/vnd.ms-pki.seccat"},
{ "cct", "application/x-director"},
{ "cc", "text/x-c"},
{ "ccxml", "application/ccxml+xml"},
{ "cdbcmsg", "application/vnd.contact.cmsg"},
{ "cdf", "application/x-cdf"},
{ "cdkey", "application/vnd.mediastation.cdkey"},
{ "cdx", "chemical/x-cdx"},
{ "cdxml", "application/vnd.chemdraw+xml"},
{ "cdy", "application/vnd.cinderella"},
{ "cer", "application/x-x509-ca-cert"},
{ "cgm", "image/cgm"},
{ "chat", "application/x-chat"},
{ "chm", "application/vnd.ms-htmlhelp"},
{ "chrt", "application/vnd.kde.kchart"},
{ "cif", "chemical/x-cif"},
{ "cii", "application/vnd.anser-web-certificate-issue-initiation"},
{ "cla", "application/vnd.claymore"},
{ "class", "application/java-vm"},
{ "clkk", "application/vnd.crick.clicker.keyboard"},
{ "clkp", "application/vnd.crick.clicker.palette"},
{ "clkt", "application/vnd.crick.clicker.template"},
{ "clkw", "application/vnd.crick.clicker.wordbank"},
{ "clkx", "application/vnd.crick.clicker"},
{ "clp", "application/x-msclip"},
{ "cmc", "application/vnd.cosmocaller"},
{ "cmdf", "chemical/x-cmdf"},
{ "cml", "chemical/x-cml"},
{ "cmp", "application/vnd.yellowriver-custom-menu"},
{ "cmx", "image/x-cmx"},
{ "cod", "application/vnd.rim.cod"},
{ "com", "application/x-msdownload"},
{ "conf", "text/plain"},
{ "cpio", "application/x-cpio"},
{ "cpp", "text/x-c"},
{ "cpt", "application/mac-compactpro"},
{ "crd", "application/x-mscardfile"},
{ "crl", "application/pkix-crl"},
{ "crt", "application/x-x509-ca-cert"},
{ "csh", "application/x-csh"},
{ "csml", "chemical/x-csml"},
{ "csp", "application/vnd.commonspace"},
{ "css", "text/css"},
{ "cst", "application/x-director"},
{ "csv", "text/csv"},
{ "c", "text/plain"},
{ "cu", "application/cu-seeme"},
{ "curl", "text/vnd.curl"},
{ "cww", "application/prs.cww"},
{ "cxt", "application/x-director"},
{ "cxx", "text/x-c"},
{ "daf", "application/vnd.mobius.daf"},
{ "dataless", "application/vnd.fdsn.seed"},
{ "davmount", "application/davmount+xml"},
{ "dcr", "application/x-director"},
{ "dcurl", "text/vnd.curl.dcurl"},
{ "dd2", "application/vnd.oma.dd2+xml"},
{ "ddd", "application/vnd.fujixerox.ddd"},
{ "deb", "application/x-debian-package"},
{ "def", "text/plain"},
{ "deploy", "application/octet-stream"},
{ "der", "application/x-x509-ca-cert"},
{ "dfac", "application/vnd.dreamfactory"},
{ "dic", "text/x-c"},
{ "diff", "text/plain"},
{ "dir", "application/x-director"},
{ "dis", "application/vnd.mobius.dis"},
{ "dist", "application/octet-stream"},
{ "distz", "application/octet-stream"},
{ "djv", "image/vnd.djvu"},
{ "djvu", "image/vnd.djvu"},
{ "dll", "application/x-msdownload"},
{ "dmg", "application/octet-stream"},
{ "dms", "application/octet-stream"},
{ "dna", "application/vnd.dna"},
{ "doc", "application/msword"},
{ "docm", "application/vnd.ms-word.document.macroenabled.12"},
{ "docx", "application/vnd.openxmlformats-officedocument.wordprocessingml.document"},
{ "dot", "application/msword"},
{ "dotm", "application/vnd.ms-word.template.macroenabled.12"},
{ "dotx", "application/vnd.openxmlformats-officedocument.wordprocessingml.template"},
{ "dp", "application/vnd.osgi.dp"},
{ "dpg", "application/vnd.dpgraph"},
{ "dsc", "text/prs.lines.tag"},
{ "dtb", "application/x-dtbook+xml"},
{ "dtd", "application/xml-dtd"},
{ "dts", "audio/vnd.dts"},
{ "dtshd", "audio/vnd.dts.hd"},
{ "dump", "application/octet-stream"},
{ "dvi", "application/x-dvi"},
{ "dwf", "model/vnd.dwf"},
{ "dwg", "image/vnd.dwg"},
{ "dxf", "image/vnd.dxf"},
{ "dxp", "application/vnd.spotfire.dxp"},
{ "dxr", "application/x-director"},
{ "ecelp4800", "audio/vnd.nuera.ecelp4800"},
{ "ecelp7470", "audio/vnd.nuera.ecelp7470"},
{ "ecelp9600", "audio/vnd.nuera.ecelp9600"},
{ "ecma", "application/ecmascript"},
{ "edm", "application/vnd.novadigm.edm"},
{ "edx", "application/vnd.novadigm.edx"},
{ "efif", "application/vnd.picsel"},
{ "ei6", "application/vnd.pg.osasli"},
{ "elc", "application/octet-stream"},
{ "eml", "message/rfc822"},
{ "emma", "application/emma+xml"},
{ "eol", "audio/vnd.digital-winds"},
{ "eot", "application/vnd.ms-fontobject"},
{ "eps", "application/postscript"},
{ "epub", "application/epub+zip"},
{ "es3", "application/vnd.eszigno3+xml"},
{ "esf", "application/vnd.epson.esf"},
{ "espass", "application/vnd.espass-espass+zip"},
{ "et3", "application/vnd.eszigno3+xml"},
{ "etx", "text/x-setext"},
{ "evy", "application/envoy"},
{ "exe", "application/octet-stream"},
{ "ext", "application/vnd.novadigm.ext"},
{ "ez2", "application/vnd.ezpix-album"},
{ "ez3", "application/vnd.ezpix-package"},
{ "ez", "application/andrew-inset"},
{ "f4v", "video/x-f4v"},
{ "f77", "text/x-fortran"},
{ "f90", "text/x-fortran"},
{ "fbs", "image/vnd.fastbidsheet"},
{ "fdf", "application/vnd.fdf"},
{ "fe_launch", "application/vnd.denovo.fcselayout-link"},
{ "fg5", "application/vnd.fujitsu.oasysgp"},
{ "fgd", "application/x-director"},
{ "fh4", "image/x-freehand"},
{ "fh5", "image/x-freehand"},
{ "fh7", "image/x-freehand"},
{ "fhc", "image/x-freehand"},
{ "fh", "image/x-freehand"},
{ "fif", "application/fractals"},
{ "fig", "application/x-xfig"},
{ "fli", "video/x-fli"},
{ "flo", "application/vnd.micrografx.flo"},
{ "flr", "x-world/x-vrml"},
{ "flv", "video/x-flv"},
{ "flw", "application/vnd.kde.kivio"},
{ "flx", "text/vnd.fmi.flexstor"},
{ "fly", "text/vnd.fly"},
{ "fm", "application/vnd.framemaker"},
{ "fnc", "application/vnd.frogans.fnc"},
{ "for", "text/x-fortran"},
{ "fpx", "image/vnd.fpx"},
{ "frame", "application/vnd.framemaker"},
{ "fsc", "application/vnd.fsc.weblaunch"},
{ "fst", "image/vnd.fst"},
{ "ftc", "application/vnd.fluxtime.clip"},
{ "f", "text/x-fortran"},
{ "fti", "application/vnd.anser-web-funds-transfer-initiation"},
{ "fvt", "video/vnd.fvt"},
{ "fzs", "application/vnd.fuzzysheet"},
{ "g3", "image/g3fax"},
{ "gac", "application/vnd.groove-account"},
{ "gdl", "model/vnd.gdl"},
{ "geo", "application/vnd.dynageo"},
{ "gex", "application/vnd.geometry-explorer"},
{ "ggb", "application/vnd.geogebra.file"},
{ "ggt", "application/vnd.geogebra.tool"},
{ "ghf", "application/vnd.groove-help"},
{ "gif", "image/gif"},
{ "gim", "application/vnd.groove-identity-message"},
{ "gmx", "application/vnd.gmx"},
{ "gnumeric", "application/x-gnumeric"},
{ "gph", "application/vnd.flographit"},
{ "gqf", "application/vnd.grafeq"},
{ "gqs", "application/vnd.grafeq"},
{ "gram", "application/srgs"},
{ "gre", "application/vnd.geometry-explorer"},
{ "grv", "application/vnd.groove-injector"},
{ "grxml", "application/srgs+xml"},
{ "gsf", "application/x-font-ghostscript"},
{ "gtar", "application/x-gtar"},
{ "gtm", "application/vnd.groove-tool-message"},
{ "gtw", "model/vnd.gtw"},
{ "gv", "text/vnd.graphviz"},
{ "gz", "application/x-gzip"},
{ "h261", "video/h261"},
{ "h263", "video/h263"},
{ "h264", "video/h264"},
{ "hbci", "application/vnd.hbci"},
{ "hdf", "application/x-hdf"},
{ "hh", "text/x-c"},
{ "hlp", "application/winhlp"},
{ "hpgl", "application/vnd.hp-hpgl"},
{ "hpid", "application/vnd.hp-hpid"},
{ "hps", "application/vnd.hp-hps"},
{ "hqx", "application/mac-binhex40"},
{ "hta", "application/hta"},
{ "htc", "text/x-component"},
{ "h", "text/plain"},
{ "htke", "application/vnd.kenameaapp"},
{ "html", "text/html"},
{ "htm", "text/html"},
{ "htt", "text/webviewhtml"},
{ "hvd", "application/vnd.yamaha.hv-dic"},
{ "hvp", "application/vnd.yamaha.hv-voice"},
{ "hvs", "application/vnd.yamaha.hv-script"},
{ "icc", "application/vnd.iccprofile"},
{ "ice", "x-conference/x-cooltalk"},
{ "icm", "application/vnd.iccprofile"},
{ "ico", "image/x-icon"},
{ "ics", "text/calendar"},
{ "ief", "image/ief"},
{ "ifb", "text/calendar"},
{ "ifm", "application/vnd.shana.informed.formdata"},
{ "iges", "model/iges"},
{ "igl", "application/vnd.igloader"},
{ "igs", "model/iges"},
{ "igx", "application/vnd.micrografx.igx"},
{ "iif", "application/vnd.shana.informed.interchange"},
{ "iii", "application/x-iphone"},
{ "imp", "application/vnd.accpac.simply.imp"},
{ "ims", "application/vnd.ms-ims"},
{ "ins", "application/x-internet-signup"},
{ "in", "text/plain"},
{ "ipk", "application/vnd.shana.informed.package"},
{ "irm", "application/vnd.ibm.rights-management"},
{ "irp", "application/vnd.irepository.package+xml"},
{ "iso", "application/octet-stream"},
{ "isp", "application/x-internet-signup"},
{ "itp", "application/vnd.shana.informed.formtemplate"},
{ "ivp", "application/vnd.immervision-ivp"},
{ "ivu", "application/vnd.immervision-ivu"},
{ "jad", "text/vnd.sun.j2me.app-descriptor"},
{ "jam", "application/vnd.jam"},
{ "jar", "application/java-archive"},
{ "java", "text/x-java-source"},
{ "jfif", "image/pipeg"},
{ "jisp", "application/vnd.jisp"},
{ "jlt", "application/vnd.hp-jlyt"},
{ "jnlp", "application/x-java-jnlp-file"},
{ "joda", "application/vnd.joost.joda-archive"},
{ "jpeg", "image/jpeg"},
{ "jpe", "image/jpeg"},
{ "jpg", "image/jpeg"},
{ "jpgm", "video/jpm"},
{ "jpgv", "video/jpeg"},
{ "jpm", "video/jpm"},
{ "js", "application/x-javascript"},
{ "json", "application/json"},
{ "kar", "audio/midi"},
{ "karbon", "application/vnd.kde.karbon"},
{ "kfo", "application/vnd.kde.kformula"},
{ "kia", "application/vnd.kidspiration"},
{ "kil", "application/x-killustrator"},
{ "kml", "application/vnd.google-earth.kml+xml"},
{ "kmz", "application/vnd.google-earth.kmz"},
{ "kne", "application/vnd.kinar"},
{ "knp", "application/vnd.kinar"},
{ "kon", "application/vnd.kde.kontour"},
{ "kpr", "application/vnd.kde.kpresenter"},
{ "kpt", "application/vnd.kde.kpresenter"},
{ "ksh", "text/plain"},
{ "ksp", "application/vnd.kde.kspread"},
{ "ktr", "application/vnd.kahootz"},
{ "ktz", "application/vnd.kahootz"},
{ "kwd", "application/vnd.kde.kword"},
{ "kwt", "application/vnd.kde.kword"},
{ "latex", "application/x-latex"},
{ "lbd", "application/vnd.llamagraphics.life-balance.desktop"},
{ "lbe", "application/vnd.llamagraphics.life-balance.exchange+xml"},
{ "les", "application/vnd.hhe.lesson-player"},
{ "lha", "application/octet-stream"},
{ "link66", "application/vnd.route66.link66+xml"},
{ "list3820", "application/vnd.ibm.modcap"},
{ "listafp", "application/vnd.ibm.modcap"},
{ "list", "text/plain"},
{ "log", "text/plain"},
{ "lostxml", "application/lost+xml"},
{ "lrf", "application/octet-stream"},
{ "lrm", "application/vnd.ms-lrm"},
{ "lsf", "video/x-la-asf"},
{ "lsx", "video/x-la-asf"},
{ "ltf", "application/vnd.frogans.ltf"},
{ "lvp", "audio/vnd.lucent.voice"},
{ "lwp", "application/vnd.lotus-wordpro"},
{ "lzh", "application/octet-stream"},
{ "m13", "application/x-msmediaview"},
{ "m14", "application/x-msmediaview"},
{ "m1v", "video/mpeg"},
{ "m2a", "audio/mpeg"},
{ "m2v", "video/mpeg"},
{ "m3a", "audio/mpeg"},
{ "m3u", "audio/x-mpegurl"},
{ "m4u", "video/vnd.mpegurl"},
{ "m4v", "video/x-m4v"},
{ "ma", "application/mathematica"},
{ "mag", "application/vnd.ecowin.chart"},
{ "maker", "application/vnd.framemaker"},
{ "man", "text/troff"},
{ "mathml", "application/mathml+xml"},
{ "mb", "application/mathematica"},
{ "mbk", "application/vnd.mobius.mbk"},
{ "mbox", "application/mbox"},
{ "mc1", "application/vnd.medcalcdata"},
{ "mcd", "application/vnd.mcd"},
{ "mcurl", "text/vnd.curl.mcurl"},
{ "mdb", "application/x-msaccess"},
{ "mdi", "image/vnd.ms-modi"},
{ "mesh", "model/mesh"},
{ "me", "text/troff"},
{ "mfm", "application/vnd.mfmp"},
{ "mgz", "application/vnd.proteus.magazine"},
{ "mht", "message/rfc822"},
{ "mhtml", "message/rfc822"},
{ "mid", "audio/midi"},
{ "midi", "audio/midi"},
{ "mif", "application/vnd.mif"},
{ "mime", "message/rfc822"},
{ "mj2", "video/mj2"},
{ "mjp2", "video/mj2"},
{ "mlp", "application/vnd.dolby.mlp"},
{ "mmd", "application/vnd.chipnuts.karaoke-mmd"},
{ "mmf", "application/vnd.smaf"},
{ "mmr", "image/vnd.fujixerox.edmics-mmr"},
{ "mny", "application/x-msmoney"},
{ "mobi", "application/x-mobipocket-ebook"},
{ "movie", "video/x-sgi-movie"},
{ "mov", "video/quicktime"},
{ "mp2a", "audio/mpeg"},
{ "mp2", "video/mpeg"},
{ "mp3", "audio/mpeg"},
{ "mp4a", "audio/mp4"},
{ "mp4s", "application/mp4"},
{ "mp4", "video/mp4"},
{ "mp4v", "video/mp4"},
{ "mpa", "video/mpeg"},
{ "mpc", "application/vnd.mophun.certificate"},
{ "mpeg", "video/mpeg"},
{ "mpe", "video/mpeg"},
{ "mpg4", "video/mp4"},
{ "mpga", "audio/mpeg"},
{ "mpg", "video/mpeg"},
{ "mpkg", "application/vnd.apple.installer+xml"},
{ "mpm", "application/vnd.blueice.multipass"},
{ "mpn", "application/vnd.mophun.application"},
{ "mpp", "application/vnd.ms-project"},
{ "mpt", "application/vnd.ms-project"},
{ "mpv2", "video/mpeg"},
{ "mpy", "application/vnd.ibm.minipay"},
{ "mqy", "application/vnd.mobius.mqy"},
{ "mrc", "application/marc"},
{ "mscml", "application/mediaservercontrol+xml"},
{ "mseed", "application/vnd.fdsn.mseed"},
{ "mseq", "application/vnd.mseq"},
{ "msf", "application/vnd.epson.msf"},
{ "msh", "model/mesh"},
{ "msi", "application/x-msdownload"},
{ "ms", "text/troff"},
{ "msty", "application/vnd.muvee.style"},
{ "mts", "model/vnd.mts"},
{ "mus", "application/vnd.musician"},
{ "musicxml", "application/vnd.recordare.musicxml+xml"},
{ "mvb", "application/x-msmediaview"},
{ "mxf", "application/mxf"},
{ "mxl", "application/vnd.recordare.musicxml"},
{ "mxml", "application/xv+xml"},
{ "mxs", "application/vnd.triscape.mxs"},
{ "mxu", "video/vnd.mpegurl"},
{ "nb", "application/mathematica"},
{ "nc", "application/x-netcdf"},
{ "ncx", "application/x-dtbncx+xml"},
{ "n-gage", "application/vnd.nokia.n-gage.symbian.install"},
{ "ngdat", "application/vnd.nokia.n-gage.data"},
{ "nlu", "application/vnd.neurolanguage.nlu"},
{ "nml", "application/vnd.enliven"},
{ "nnd", "application/vnd.noblenet-directory"},
{ "nns", "application/vnd.noblenet-sealer"},
{ "nnw", "application/vnd.noblenet-web"},
{ "npx", "image/vnd.net-fpx"},
{ "nsf", "application/vnd.lotus-notes"},
{ "nws", "message/rfc822"},
{ "oa2", "application/vnd.fujitsu.oasys2"},
{ "oa3", "application/vnd.fujitsu.oasys3"},
{ "o", "application/octet-stream"},
{ "oas", "application/vnd.fujitsu.oasys"},
{ "obd", "application/x-msbinder"},
{ "obj", "application/octet-stream"},
{ "oda", "application/oda"},
{ "odb", "application/vnd.oasis.opendocument.database"},
{ "odc", "application/vnd.oasis.opendocument.chart"},
{ "odf", "application/vnd.oasis.opendocument.formula"},
{ "odft", "application/vnd.oasis.opendocument.formula-template"},
{ "odg", "application/vnd.oasis.opendocument.graphics"},
{ "odi", "application/vnd.oasis.opendocument.image"},
{ "odp", "application/vnd.oasis.opendocument.presentation"},
{ "ods", "application/vnd.oasis.opendocument.spreadsheet"},
{ "odt", "application/vnd.oasis.opendocument.text"},
{ "oga", "audio/ogg"},
{ "ogg", "audio/ogg"},
{ "ogv", "video/ogg"},
{ "ogx", "application/ogg"},
{ "onepkg", "application/onenote"},
{ "onetmp", "application/onenote"},
{ "onetoc2", "application/onenote"},
{ "onetoc", "application/onenote"},
{ "opf", "application/oebps-package+xml"},
{ "oprc", "application/vnd.palm"},
{ "org", "application/vnd.lotus-organizer"},
{ "osf", "application/vnd.yamaha.openscoreformat"},
{ "osfpvg", "application/vnd.yamaha.openscoreformat.osfpvg+xml"},
{ "otc", "application/vnd.oasis.opendocument.chart-template"},
{ "otf", "application/x-font-otf"},
{ "otg", "application/vnd.oasis.opendocument.graphics-template"},
{ "oth", "application/vnd.oasis.opendocument.text-web"},
{ "oti", "application/vnd.oasis.opendocument.image-template"},
{ "otm", "application/vnd.oasis.opendocument.text-master"},
{ "otp", "application/vnd.oasis.opendocument.presentation-template"},
{ "ots", "application/vnd.oasis.opendocument.spreadsheet-template"},
{ "ott", "application/vnd.oasis.opendocument.text-template"},
{ "oxt", "application/vnd.openofficeorg.extension"},
{ "p10", "application/pkcs10"},
{ "p12", "application/x-pkcs12"},
{ "p7b", "application/x-pkcs7-certificates"},
{ "p7c", "application/x-pkcs7-mime"},
{ "p7m", "application/x-pkcs7-mime"},
{ "p7r", "application/x-pkcs7-certreqresp"},
{ "p7s", "application/x-pkcs7-signature"},
{ "pas", "text/x-pascal"},
{ "pbd", "application/vnd.powerbuilder6"},
{ "pbm", "image/x-portable-bitmap"},
{ "pcf", "application/x-font-pcf"},
{ "pcl", "application/vnd.hp-pcl"},
{ "pclxl", "application/vnd.hp-pclxl"},
{ "pct", "image/x-pict"},
{ "pcurl", "application/vnd.curl.pcurl"},
{ "pcx", "image/x-pcx"},
{ "pdb", "application/vnd.palm"},
{ "pdf", "application/pdf"},
{ "pfa", "application/x-font-type1"},
{ "pfb", "application/x-font-type1"},
{ "pfm", "application/x-font-type1"},
{ "pfr", "application/font-tdpfr"},
{ "pfx", "application/x-pkcs12"},
{ "pgm", "image/x-portable-graymap"},
{ "pgn", "application/x-chess-pgn"},
{ "pgp", "application/pgp-encrypted"},
{ "pic", "image/x-pict"},
{ "pkg", "application/octet-stream"},
{ "pki", "application/pkixcmp"},
{ "pkipath", "application/pkix-pkipath"},
{ "pkpass", "application/vnd-com.apple.pkpass"},
{ "pko", "application/ynd.ms-pkipko"},
{ "plb", "application/vnd.3gpp.pic-bw-large"},
{ "plc", "application/vnd.mobius.plc"},
{ "plf", "application/vnd.pocketlearn"},
{ "pls", "application/pls+xml"},
{ "pl", "text/plain"},
{ "pma", "application/x-perfmon"},
{ "pmc", "application/x-perfmon"},
{ "pml", "application/x-perfmon"},
{ "pmr", "application/x-perfmon"},
{ "pmw", "application/x-perfmon"},
{ "png", "image/png"},
{ "pnm", "image/x-portable-anymap"},
{ "portpkg", "application/vnd.macports.portpkg"},
{ "pot,", "application/vnd.ms-powerpoint"},
{ "pot", "application/vnd.ms-powerpoint"},
{ "potm", "application/vnd.ms-powerpoint.template.macroenabled.12"},
{ "potx", "application/vnd.openxmlformats-officedocument.presentationml.template"},
{ "ppa", "application/vnd.ms-powerpoint"},
{ "ppam", "application/vnd.ms-powerpoint.addin.macroenabled.12"},
{ "ppd", "application/vnd.cups-ppd"},
{ "ppm", "image/x-portable-pixmap"},
{ "pps", "application/vnd.ms-powerpoint"},
{ "ppsm", "application/vnd.ms-powerpoint.slideshow.macroenabled.12"},
{ "ppsx", "application/vnd.openxmlformats-officedocument.presentationml.slideshow"},
{ "ppt", "application/vnd.ms-powerpoint"},
{ "pptm", "application/vnd.ms-powerpoint.presentation.macroenabled.12"},
{ "pptx", "application/vnd.openxmlformats-officedocument.presentationml.presentation"},
{ "pqa", "application/vnd.palm"},
{ "prc", "application/x-mobipocket-ebook"},
{ "pre", "application/vnd.lotus-freelance"},
{ "prf", "application/pics-rules"},
{ "ps", "application/postscript"},
{ "psb", "application/vnd.3gpp.pic-bw-small"},
{ "psd", "image/vnd.adobe.photoshop"},
{ "psf", "application/x-font-linux-psf"},
{ "p", "text/x-pascal"},
{ "ptid", "application/vnd.pvi.ptid1"},
{ "pub", "application/x-mspublisher"},
{ "pvb", "application/vnd.3gpp.pic-bw-var"},
{ "pwn", "application/vnd.3m.post-it-notes"},
{ "pwz", "application/vnd.ms-powerpoint"},
{ "pya", "audio/vnd.ms-playready.media.pya"},
{ "pyc", "application/x-python-code"},
{ "pyo", "application/x-python-code"},
{ "py", "text/x-python"},
{ "pyv", "video/vnd.ms-playready.media.pyv"},
{ "qam", "application/vnd.epson.quickanime"},
{ "qbo", "application/vnd.intu.qbo"},
{ "qfx", "application/vnd.intu.qfx"},
{ "qps", "application/vnd.publishare-delta-tree"},
{ "qt", "video/quicktime"},
{ "qwd", "application/vnd.quark.quarkxpress"},
{ "qwt", "application/vnd.quark.quarkxpress"},
{ "qxb", "application/vnd.quark.quarkxpress"},
{ "qxd", "application/vnd.quark.quarkxpress"},
{ "qxl", "application/vnd.quark.quarkxpress"},
{ "qxt", "application/vnd.quark.quarkxpress"},
{ "ra", "audio/x-pn-realaudio"},
{ "ram", "audio/x-pn-realaudio"},
{ "rar", "application/x-rar-compressed"},
{ "ras", "image/x-cmu-raster"},
{ "rcprofile", "application/vnd.ipunplugged.rcprofile"},
{ "rdf", "application/rdf+xml"},
{ "rdz", "application/vnd.data-vision.rdz"},
{ "rep", "application/vnd.businessobjects"},
{ "res", "application/x-dtbresource+xml"},
{ "rgb", "image/x-rgb"},
{ "rif", "application/reginfo+xml"},
{ "rl", "application/resource-lists+xml"},
{ "rlc", "image/vnd.fujixerox.edmics-rlc"},
{ "rld", "application/resource-lists-diff+xml"},
{ "rm", "application/vnd.rn-realmedia"},
{ "rmi", "audio/midi"},
{ "rmp", "audio/x-pn-realaudio-plugin"},
{ "rms", "application/vnd.jcp.javame.midlet-rms"},
{ "rnc", "application/relax-ng-compact-syntax"},
{ "roff", "text/troff"},
{ "rpm", "application/x-rpm"},
{ "rpss", "application/vnd.nokia.radio-presets"},
{ "rpst", "application/vnd.nokia.radio-preset"},
{ "rq", "application/sparql-query"},
{ "rs", "application/rls-services+xml"},
{ "rsd", "application/rsd+xml"},
{ "rss", "application/rss+xml"},
{ "rtf", "application/rtf"},
{ "rtx", "text/richtext"},
{ "saf", "application/vnd.yamaha.smaf-audio"},
{ "sbml", "application/sbml+xml"},
{ "sc", "application/vnd.ibm.secure-container"},
{ "scd", "application/x-msschedule"},
{ "scm", "application/vnd.lotus-screencam"},
{ "scq", "application/scvp-cv-request"},
{ "scs", "application/scvp-cv-response"},
{ "sct", "text/scriptlet"},
{ "scurl", "text/vnd.curl.scurl"},
{ "sda", "application/vnd.stardivision.draw"},
{ "sdc", "application/vnd.stardivision.calc"},
{ "sdd", "application/vnd.stardivision.impress"},
{ "sdkd", "application/vnd.solent.sdkm+xml"},
{ "sdkm", "application/vnd.solent.sdkm+xml"},
{ "sdp", "application/sdp"},
{ "sdw", "application/vnd.stardivision.writer"},
{ "see", "application/vnd.seemail"},
{ "seed", "application/vnd.fdsn.seed"},
{ "sema", "application/vnd.sema"},
{ "semd", "application/vnd.semd"},
{ "semf", "application/vnd.semf"},
{ "ser", "application/java-serialized-object"},
{ "setpay", "application/set-payment-initiation"},
{ "setreg", "application/set-registration-initiation"},
{ "sfd-hdstx", "application/vnd.hydrostatix.sof-data"},
{ "sfs", "application/vnd.spotfire.sfs"},
{ "sgl", "application/vnd.stardivision.writer-global"},
{ "sgml", "text/sgml"},
{ "sgm", "text/sgml"},
{ "sh", "application/x-sh"},
{ "shar", "application/x-shar"},
{ "shf", "application/shf+xml"},
{ "sic", "application/vnd.wap.sic"},
{ "sig", "application/pgp-signature"},
{ "silo", "model/mesh"},
{ "sis", "application/vnd.symbian.install"},
{ "sisx", "application/vnd.symbian.install"},
{ "sit", "application/x-stuffit"},
{ "si", "text/vnd.wap.si"},
{ "sitx", "application/x-stuffitx"},
{ "skd", "application/vnd.koan"},
{ "skm", "application/vnd.koan"},
{ "skp", "application/vnd.koan"},
{ "skt", "application/vnd.koan"},
{ "slc", "application/vnd.wap.slc"},
{ "sldm", "application/vnd.ms-powerpoint.slide.macroenabled.12"},
{ "sldx", "application/vnd.openxmlformats-officedocument.presentationml.slide"},
{ "slt", "application/vnd.epson.salt"},
{ "sl", "text/vnd.wap.sl"},
{ "smf", "application/vnd.stardivision.math"},
{ "smi", "application/smil+xml"},
{ "smil", "application/smil+xml"},
{ "snd", "audio/basic"},
{ "snf", "application/x-font-snf"},
{ "so", "application/octet-stream"},
{ "spc", "application/x-pkcs7-certificates"},
{ "spf", "application/vnd.yamaha.smaf-phrase"},
{ "spl", "application/x-futuresplash"},
{ "spot", "text/vnd.in3d.spot"},
{ "spp", "application/scvp-vp-response"},
{ "spq", "application/scvp-vp-request"},
{ "spx", "audio/ogg"},
{ "src", "application/x-wais-source"},
{ "srx", "application/sparql-results+xml"},
{ "sse", "application/vnd.kodak-descriptor"},
{ "ssf", "application/vnd.epson.ssf"},
{ "ssml", "application/ssml+xml"},
{ "sst", "application/vnd.ms-pkicertstore"},
{ "stc", "application/vnd.sun.xml.calc.template"},
{ "std", "application/vnd.sun.xml.draw.template"},
{ "s", "text/x-asm"},
{ "stf", "application/vnd.wt.stf"},
{ "sti", "application/vnd.sun.xml.impress.template"},
{ "stk", "application/hyperstudio"},
{ "stl", "application/vnd.ms-pki.stl"},
{ "stm", "text/html"},
{ "str", "application/vnd.pg.format"},
{ "stw", "application/vnd.sun.xml.writer.template"},
{ "sus", "application/vnd.sus-calendar"},
{ "susp", "application/vnd.sus-calendar"},
{ "sv4cpio", "application/x-sv4cpio"},
{ "sv4crc", "application/x-sv4crc"},
{ "svd", "application/vnd.svd"},
{ "svg", "image/svg+xml"},
{ "svgz", "image/svg+xml"},
{ "swa", "application/x-director"},
{ "swf", "application/x-shockwave-flash"},
{ "swi", "application/vnd.arastra.swi"},
{ "sxc", "application/vnd.sun.xml.calc"},
{ "sxd", "application/vnd.sun.xml.draw"},
{ "sxg", "application/vnd.sun.xml.writer.global"},
{ "sxi", "application/vnd.sun.xml.impress"},
{ "sxm", "application/vnd.sun.xml.math"},
{ "sxw", "application/vnd.sun.xml.writer"},
{ "tao", "application/vnd.tao.intent-module-archive"},
{ "t", "application/x-troff"},
{ "tar", "application/x-tar"},
{ "tcap", "application/vnd.3gpp2.tcap"},
{ "tcl", "application/x-tcl"},
{ "teacher", "application/vnd.smart.teacher"},
{ "tex", "application/x-tex"},
{ "texi", "application/x-texinfo"},
{ "texinfo", "application/x-texinfo"},
{ "text", "text/plain"},
{ "tfm", "application/x-tex-tfm"},
{ "tgz", "application/x-gzip"},
{ "tiff", "image/tiff"},
{ "tif", "image/tiff"},
{ "tmo", "application/vnd.tmobile-livetv"},
{ "torrent", "application/x-bittorrent"},
{ "tpl", "application/vnd.groove-tool-template"},
{ "tpt", "application/vnd.trid.tpt"},
{ "tra", "application/vnd.trueapp"},
{ "trm", "application/x-msterminal"},
{ "tr", "text/troff"},
{ "tsv", "text/tab-separated-values"},
{ "ttc", "application/x-font-ttf"},
{ "ttf", "application/x-font-ttf"},
{ "twd", "application/vnd.simtech-mindmapper"},
{ "twds", "application/vnd.simtech-mindmapper"},
{ "txd", "application/vnd.genomatix.tuxedo"},
{ "txf", "application/vnd.mobius.txf"},
{ "txt", "text/plain"},
{ "u32", "application/x-authorware-bin"},
{ "udeb", "application/x-debian-package"},
{ "ufd", "application/vnd.ufdl"},
{ "ufdl", "application/vnd.ufdl"},
{ "uls", "text/iuls"},
{ "umj", "application/vnd.umajin"},
{ "unityweb", "application/vnd.unity"},
{ "uoml", "application/vnd.uoml+xml"},
{ "uris", "text/uri-list"},
{ "uri", "text/uri-list"},
{ "urls", "text/uri-list"},
{ "ustar", "application/x-ustar"},
{ "utz", "application/vnd.uiq.theme"},
{ "uu", "text/x-uuencode"},
{ "vcd", "application/x-cdlink"},
{ "vcf", "text/x-vcard"},
{ "vcg", "application/vnd.groove-vcard"},
{ "vcs", "text/x-vcalendar"},
{ "vcx", "application/vnd.vcx"},
{ "vis", "application/vnd.visionary"},
{ "viv", "video/vnd.vivo"},
{ "vor", "application/vnd.stardivision.writer"},
{ "vox", "application/x-authorware-bin"},
{ "vrml", "x-world/x-vrml"},
{ "vsd", "application/vnd.visio"},
{ "vsf", "application/vnd.vsf"},
{ "vss", "application/vnd.visio"},
{ "vst", "application/vnd.visio"},
{ "vsw", "application/vnd.visio"},
{ "vtu", "model/vnd.vtu"},
{ "vxml", "application/voicexml+xml"},
{ "w3d", "application/x-director"},
{ "wad", "application/x-doom"},
{ "wav", "audio/x-wav"},
{ "wax", "audio/x-ms-wax"},
{ "wbmp", "image/vnd.wap.wbmp"},
{ "wbs", "application/vnd.criticaltools.wbs+xml"},
{ "wbxml", "application/vnd.wap.wbxml"},
{ "wcm", "application/vnd.ms-works"},
{ "wdb", "application/vnd.ms-works"},
{ "wiz", "application/msword"},
{ "wks", "application/vnd.ms-works"},
{ "wma", "audio/x-ms-wma"},
{ "wmd", "application/x-ms-wmd"},
{ "wmf", "application/x-msmetafile"},
{ "wmlc", "application/vnd.wap.wmlc"},
{ "wmlsc", "application/vnd.wap.wmlscriptc"},
{ "wmls", "text/vnd.wap.wmlscript"},
{ "wml", "text/vnd.wap.wml"},
{ "wm", "video/x-ms-wm"},
{ "wmv", "video/x-ms-wmv"},
{ "wmx", "video/x-ms-wmx"},
{ "wmz", "application/x-ms-wmz"},
{ "wpd", "application/vnd.wordperfect"},
{ "wpl", "application/vnd.ms-wpl"},
{ "wps", "application/vnd.ms-works"},
{ "wqd", "application/vnd.wqd"},
{ "wri", "application/x-mswrite"},
{ "wrl", "x-world/x-vrml"},
{ "wrz", "x-world/x-vrml"},
{ "wsdl", "application/wsdl+xml"},
{ "wspolicy", "application/wspolicy+xml"},
{ "wtb", "application/vnd.webturbo"},
{ "wvx", "video/x-ms-wvx"},
{ "x32", "application/x-authorware-bin"},
{ "x3d", "application/vnd.hzn-3d-crossword"},
{ "xaf", "x-world/x-vrml"},
{ "xap", "application/x-silverlight-app"},
{ "xar", "application/vnd.xara"},
{ "xbap", "application/x-ms-xbap"},
{ "xbd", "application/vnd.fujixerox.docuworks.binder"},
{ "xbm", "image/x-xbitmap"},
{ "xdm", "application/vnd.syncml.dm+xml"},
{ "xdp", "application/vnd.adobe.xdp+xml"},
{ "xdw", "application/vnd.fujixerox.docuworks"},
{ "xenc", "application/xenc+xml"},
{ "xer", "application/patch-ops-error+xml"},
{ "xfdf", "application/vnd.adobe.xfdf"},
{ "xfdl", "application/vnd.xfdl"},
{ "xht", "application/xhtml+xml"},
{ "xhtml", "application/xhtml+xml"},
{ "xhvml", "application/xv+xml"},
{ "xif", "image/vnd.xiff"},
{ "xla", "application/vnd.ms-excel"},
{ "xlam", "application/vnd.ms-excel.addin.macroenabled.12"},
{ "xlb", "application/vnd.ms-excel"},
{ "xlc", "application/vnd.ms-excel"},
{ "xlm", "application/vnd.ms-excel"},
{ "xls", "application/vnd.ms-excel"},
{ "xlsb", "application/vnd.ms-excel.sheet.binary.macroenabled.12"},
{ "xlsm", "application/vnd.ms-excel.sheet.macroenabled.12"},
{ "xlsx", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"},
{ "xlt", "application/vnd.ms-excel"},
{ "xltm", "application/vnd.ms-excel.template.macroenabled.12"},
{ "xltx", "application/vnd.openxmlformats-officedocument.spreadsheetml.template"},
{ "xlw", "application/vnd.ms-excel"},
{ "xml", "application/xml"},
{ "xo", "application/vnd.olpc-sugar"},
{ "xof", "x-world/x-vrml"},
{ "xop", "application/xop+xml"},
{ "xpdl", "application/xml"},
{ "xpi", "application/x-xpinstall"},
{ "xpm", "image/x-xpixmap"},
{ "xpr", "application/vnd.is-xpr"},
{ "xps", "application/vnd.ms-xpsdocument"},
{ "xpw", "application/vnd.intercon.formnet"},
{ "xpx", "application/vnd.intercon.formnet"},
{ "xsl", "application/xml"},
{ "xslt", "application/xslt+xml"},
{ "xsm", "application/vnd.syncml+xml"},
{ "xspf", "application/xspf+xml"},
{ "xul", "application/vnd.mozilla.xul+xml"},
{ "xvm", "application/xv+xml"},
{ "xvml", "application/xv+xml"},
{ "xwd", "image/x-xwindowdump"},
{ "xyz", "chemical/x-xyz"},
{ "z", "application/x-compress"},
{ "zaz", "application/vnd.zzazz.deck+xml"},
{ "zip", "application/zip"},
{ "zir", "application/vnd.zul"},
{ "zirz", "application/vnd.zul"},
{ "zmm", "application/vnd.handheld-entertainment+xml"}
};
public static String unfold(String s) {
if (s == null) {
return null;
}
return s.replaceAll("\r|\n", "");
}
private static String decode(String s, Message message) {
if (s == null) {
return null;
} else {
return DecoderUtil.decodeEncodedWords(s, message);
}
}
public static String unfoldAndDecode(String s) {
return unfoldAndDecode(s, null);
}
public static String unfoldAndDecode(String s, Message message) {
return decode(unfold(s), message);
}
// TODO implement proper foldAndEncode
public static String foldAndEncode(String s) {
return s;
}
/**
* Returns the named parameter of a header field. If name is null the first
* parameter is returned, or if there are no additional parameters in the
* field the entire field is returned. Otherwise the named parameter is
* searched for in a case insensitive fashion and returned.
*
* @param headerValue the header value
* @param parameterName the parameter name
* @return the value. if the parameter cannot be found the method returns null.
*/
public static String getHeaderParameter(String headerValue, String parameterName) {
if (headerValue == null) {
return null;
}
headerValue = headerValue.replaceAll("\r|\n", "");
String[] parts = headerValue.split(";");
if (parameterName == null && parts.length > 0) {
return parts[0].trim();
}
for (String part : parts) {
if (parameterName != null &&
part.trim().toLowerCase(Locale.US).startsWith(parameterName.toLowerCase(Locale.US))) {
String[] partParts = part.split("=", 2);
if (partParts.length == 2) {
String parameter = partParts[1].trim();
int len = parameter.length();
if (len >= 2 && parameter.startsWith("\"") && parameter.endsWith("\"")) {
return parameter.substring(1, len - 1);
} else {
return parameter;
}
}
}
}
return null;
}
public static Map<String, String> getAllHeaderParameters(String headerValue) {
Map<String, String> result = new HashMap<>();
headerValue = headerValue.replaceAll("\r|\n", "");
String[] parts = headerValue.split(";");
for (String part : parts) {
String[] partParts = part.split("=", 2);
if (partParts.length == 2) {
String parameterName = partParts[0].trim().toLowerCase(Locale.US);
String parameterValue = partParts[1].trim();
result.put(parameterName, parameterValue);
}
}
return result;
}
public static Part findFirstPartByMimeType(Part part, String mimeType) {
if (part.getBody() instanceof Multipart) {
Multipart multipart = (Multipart) part.getBody();
for (BodyPart bodyPart : multipart.getBodyParts()) {
Part ret = MimeUtility.findFirstPartByMimeType(bodyPart, mimeType);
if (ret != null) {
return ret;
}
}
} else if (isSameMimeType(part.getMimeType(), mimeType)) {
return part;
}
return null;
}
/**
* Returns true if the given mimeType matches the matchAgainst specification.
* @param mimeType A MIME type to check.
* @param matchAgainst A MIME type to check against. May include wildcards such as image/* or
* * /*.
* @return
*/
public static boolean mimeTypeMatches(String mimeType, String matchAgainst) {
Pattern p = Pattern.compile(matchAgainst.replaceAll("\\*", "\\.\\*"), Pattern.CASE_INSENSITIVE);
return p.matcher(mimeType).matches();
}
public static boolean isDefaultMimeType(String mimeType) {
return isSameMimeType(mimeType, DEFAULT_ATTACHMENT_MIME_TYPE);
}
/**
* Get decoded contents of a body.
* <p/>
* Right now only some classes retain the original encoding of the body contents. Those classes have to implement
* the {@link RawDataBody} interface in order for this method to decode the data delivered by
* {@link Body#getInputStream()}.
* <p/>
* The ultimate goal is to get to a point where all classes retain the original data and {@code RawDataBody} can be
* merged into {@link Body}.
*/
public static InputStream decodeBody(Body body) throws MessagingException {
InputStream inputStream;
if (body instanceof RawDataBody) {
RawDataBody rawDataBody = (RawDataBody) body;
String encoding = rawDataBody.getEncoding();
final InputStream rawInputStream = rawDataBody.getInputStream();
if (MimeUtil.ENC_7BIT.equalsIgnoreCase(encoding) || MimeUtil.ENC_8BIT.equalsIgnoreCase(encoding)
|| MimeUtil.ENC_BINARY.equalsIgnoreCase(encoding)) {
inputStream = rawInputStream;
} else if (MimeUtil.ENC_BASE64.equalsIgnoreCase(encoding)) {
inputStream = new Base64InputStream(rawInputStream, false) {
@Override
public void close() throws IOException {
super.close();
closeInputStreamWithoutDeletingTemporaryFiles(rawInputStream);
}
};
} else if (MimeUtil.ENC_QUOTED_PRINTABLE.equalsIgnoreCase(encoding)) {
inputStream = new QuotedPrintableInputStream(rawInputStream) {
@Override
public void close() throws IOException {
super.close();
closeInputStreamWithoutDeletingTemporaryFiles(rawInputStream);
}
};
} else {
Timber.w("Unsupported encoding: %s", encoding);
inputStream = rawInputStream;
}
} else {
inputStream = body.getInputStream();
}
return inputStream;
}
public static void closeInputStreamWithoutDeletingTemporaryFiles(InputStream rawInputStream) throws IOException {
if (rawInputStream instanceof BinaryTempFileBody.BinaryTempFileBodyInputStream) {
((BinaryTempFileBody.BinaryTempFileBodyInputStream) rawInputStream).closeWithoutDeleting();
} else {
rawInputStream.close();
}
}
public static String getMimeTypeByExtension(String filename) {
String returnedType = null;
String extension = null;
if (filename != null && filename.lastIndexOf('.') != -1) {
extension = filename.substring(filename.lastIndexOf('.') + 1).toLowerCase(Locale.US);
returnedType = android.webkit.MimeTypeMap.getSingleton().getMimeTypeFromExtension(extension);
}
// If the MIME type set by the user's mailer is application/octet-stream, try to figure
// out whether there's a sane file type extension.
if (returnedType != null && !isSameMimeType(returnedType, DEFAULT_ATTACHMENT_MIME_TYPE)) {
return returnedType;
} else if (extension != null) {
for (String[] contentTypeMapEntry : MIME_TYPE_BY_EXTENSION_MAP) {
if (contentTypeMapEntry[0].equals(extension)) {
return contentTypeMapEntry[1];
}
}
}
return DEFAULT_ATTACHMENT_MIME_TYPE;
}
public static String getExtensionByMimeType(@NonNull String mimeType) {
String lowerCaseMimeType = mimeType.toLowerCase(Locale.US);
for (String[] contentTypeMapEntry : MIME_TYPE_BY_EXTENSION_MAP) {
if (contentTypeMapEntry[1].equals(lowerCaseMimeType)) {
return contentTypeMapEntry[0];
}
}
return null;
}
/**
* Get a default content-transfer-encoding for use with a given content-type
* when adding an unencoded attachment. It's possible that 8bit encodings
* may later be converted to 7bit for 7bit transport.
* <ul>
* <li>null: base64
* <li>message/rfc822: 8bit
* <li>message/*: 7bit
* <li>multipart/signed: 7bit
* <li>multipart/*: 8bit
* <li>*/*: base64
* </ul>
*
* @param type
* A String representing a MIME content-type
* @return A String representing a MIME content-transfer-encoding
*/
public static String getEncodingforType(String type) {
if (type == null) {
return (MimeUtil.ENC_BASE64);
} else if (MimeUtil.isMessage(type)) {
return (MimeUtil.ENC_8BIT);
} else if (isSameMimeType(type, "multipart/signed") || isMessage(type)) {
return (MimeUtil.ENC_7BIT);
} else if (isMultipart(type)) {
return (MimeUtil.ENC_8BIT);
} else {
return (MimeUtil.ENC_BASE64);
}
}
public static boolean isMultipart(String mimeType) {
return mimeType != null && mimeType.toLowerCase(Locale.US).startsWith("multipart/");
}
public static boolean isMessage(String mimeType) {
return isSameMimeType(mimeType, "message/rfc822");
}
public static boolean isMessageType(String mimeType) {
return mimeType != null && mimeType.toLowerCase(Locale.ROOT).startsWith("message/");
}
public static boolean isSameMimeType(String mimeType, String otherMimeType) {
return mimeType != null && mimeType.equalsIgnoreCase(otherMimeType);
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.