repo_name stringlengths 4 116 | path stringlengths 4 379 | size stringlengths 1 7 | content stringlengths 3 1.05M | license stringclasses 15
values |
|---|---|---|---|---|
tensorflow/gnn | tensorflow_gnn/tools/validate_graph_schema.py | 1049 | """Validate a schema's features and shapes.
This script ensures that a schema is valid, has correct shapes, and isn't
clobbering over reserve feature names.
"""
import sys
from absl import app
from absl import flags
from absl import logging
import tensorflow_gnn as tfgnn
FLAGS = flags.FLAGS
def define_flags():
"""Define program flags."""
flags.DEFINE_string("graph_schema", None,
("A filename to a text-formatted schema proto describing "
"the available graph features."))
flags.mark_flag_as_required("graph_schema")
def app_main(unused_argv):
"""App runner main function."""
schema = tfgnn.read_schema(FLAGS.graph_schema)
try:
warnings = tfgnn.validate_schema(schema)
for warning in warnings:
logging.warning(warning)
logging.info("Schema validated correctly.")
except tfgnn.ValidationError as exc:
logging.error("Schema validation error: %s", exc)
sys.exit(1)
def main():
define_flags()
app.run(app_main)
if __name__ == "__main__":
main()
| apache-2.0 |
camac/DominoDebugPlugin | sources/res/src/com/ibm/notes/java/api/Activator.java | 1301 | /*
* © Copyright IBM Corp. 2012
*
* 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.ibm.notes.java.api;
import org.osgi.framework.BundleActivator;
import org.osgi.framework.BundleContext;
public class Activator implements BundleActivator {
private static BundleContext context;
static BundleContext getContext() {
return context;
}
/*
* (non-Javadoc)
* @see org.osgi.framework.BundleActivator#start(org.osgi.framework.BundleContext)
*/
public void start(BundleContext bundleContext) throws Exception {
Activator.context = bundleContext;
}
/*
* (non-Javadoc)
* @see org.osgi.framework.BundleActivator#stop(org.osgi.framework.BundleContext)
*/
public void stop(BundleContext bundleContext) throws Exception {
Activator.context = null;
}
}
| apache-2.0 |
erezvani1529/azure-storage-net | Lib/AspNet/Microsoft.WindowsAzure.Storage.Facade/FacadeLib/Microsoft.WindowsAzure.Storage.Shared.Protocol.ServiceStats.cs | 580 | using System.Xml.Linq;
namespace Microsoft.WindowsAzure.Storage.Shared.Protocol
{
public sealed class ServiceStats
{
private const string StorageServiceStatsName = "StorageServiceStats";
private const string GeoReplicationName = "GeoReplication";
public GeoReplicationStats GeoReplication
{
get; private set;
}
private ServiceStats()
{
throw new System.NotImplementedException();
}
internal static ServiceStats FromServiceXml(XDocument serviceStatsDocument)
{
throw new System.NotImplementedException();
}
}
} | apache-2.0 |
CvvT/AppTroy | app/src/main/java/org/cc/dexlib2/iface/instruction/formats/Instruction21ih.java | 1846 | /*
* Copyright 2012, Google 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:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following disclaimer
* in the documentation and/or other materials provided with the
* distribution.
* * Neither the name of Google Inc. nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package org.cc.dexlib2.iface.instruction.formats;
import org.cc.dexlib2.iface.instruction.NarrowHatLiteralInstruction;
import org.cc.dexlib2.iface.instruction.OneRegisterInstruction;
public interface Instruction21ih extends OneRegisterInstruction, NarrowHatLiteralInstruction {
}
| apache-2.0 |
marklogic/data-hub-in-a-box | marklogic-data-hub/src/main/java/com/marklogic/hub/deploy/commands/GenerateFunctionMetadataCommand.java | 4669 | package com.marklogic.hub.deploy.commands;
import com.marklogic.appdeployer.command.AbstractCommand;
import com.marklogic.appdeployer.command.CommandContext;
import com.marklogic.client.DatabaseClient;
import com.marklogic.client.datamovement.ApplyTransformListener;
import com.marklogic.client.datamovement.DataMovementManager;
import com.marklogic.client.datamovement.QueryBatcher;
import com.marklogic.client.document.ServerTransform;
import com.marklogic.client.query.StructuredQueryBuilder;
import com.marklogic.hub.DatabaseKind;
import com.marklogic.hub.HubConfig;
import com.marklogic.hub.impl.Versions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import java.util.concurrent.TimeUnit;
@Component
public class GenerateFunctionMetadataCommand extends AbstractCommand {
@Autowired
private HubConfig hubConfig;
@Autowired
private Versions versions;
private Throwable caughtException;
private DatabaseClient modulesClient;
private boolean isCompatibleWithES;
public GenerateFunctionMetadataCommand() {
super();
// Per DHFPROD-3146, need this to run after modules are loaded. LoadUserModulesCommand is configured
// to run after amps are deployed, so need this to run after user modules are loaded.
setExecuteSortOrder(new LoadUserModulesCommand().getExecuteSortOrder() + 1);
}
/**
* @param hubConfig
* @param isCompatibleWithES if it's known that the version of ML supports mapping based on Entity Services, then
* can set this to true
*/
public GenerateFunctionMetadataCommand(HubConfig hubConfig, boolean isCompatibleWithES) {
this.hubConfig = hubConfig;
this.isCompatibleWithES = isCompatibleWithES;
}
public GenerateFunctionMetadataCommand(DatabaseClient modulesClient, Versions versions) {
this();
this.modulesClient = modulesClient;
this.versions = versions;
}
@Override
public void execute(CommandContext context) {
if (isCompatibleWithES || (versions != null && versions.isVersionCompatibleWithES())) {
if (modulesClient == null) {
if (hubConfig == null) {
throw new IllegalStateException("Unable to create a DatabaseClient for the modules database because hubConfig is null");
}
modulesClient = hubConfig.newStagingClient(hubConfig.getDbName(DatabaseKind.MODULES));
}
DataMovementManager dataMovementManager = modulesClient.newDataMovementManager();
StructuredQueryBuilder sb = modulesClient.newQueryManager().newStructuredQueryBuilder();
// This transform needs to be the camelcase prefix instead of the ml: prefix since it is run as part of modules load.
ServerTransform serverTransform = new ServerTransform("mlGenerateFunctionMetadata");
ApplyTransformListener transformListener = new ApplyTransformListener()
.withTransform(serverTransform)
.withApplyResult(ApplyTransformListener.ApplyResult.IGNORE)
.onFailure((batch, throwable) -> {
logger.error(throwable.getMessage());
// throw the first exception
if (caughtException == null) {
caughtException = throwable;
}
});
// Query for uris "/data-hub/5/mapping-functions/" and "/custom-modules/mapping-functions/" which are reserved for mapping functions
QueryBatcher queryBatcher = dataMovementManager.newQueryBatcher(
new StructuredQueryBuilder().or(sb.directory(true, "/data-hub/5/mapping-functions/"), sb.directory(true, "/custom-modules/mapping-functions/")))
.withBatchSize(1)
.withThreadCount(4)
.onUrisReady(transformListener);
dataMovementManager.startJob(queryBatcher);
//Stop batcher if transform takes more than 2 minutes.
try {
queryBatcher.awaitCompletion(2L, TimeUnit.MINUTES);
} catch (InterruptedException e) {
logger.error("Loading function metadata timed out, took longer than 2 minutes");
}
dataMovementManager.stopJob(queryBatcher);
if (caughtException != null) {
throw new RuntimeException(caughtException);
}
} else {
logger.warn("GenerateFunctionMetadataCommand is not supported on this MarkLogic server version ");
}
}
}
| apache-2.0 |
CIRDLES/Squid | squidCore/src/main/java/org/cirdles/squid/shrimp/ShrimpDataLegacyFileInterface.java | 1069 | /*
* Copyright 2018 James F. Bowring and CIRDLES.org.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.cirdles.squid.shrimp;
import org.cirdles.squid.prawnLegacy.PrawnLegacyFile;
import java.util.List;
/**
* @author James F. Bowring, CIRDLES.org, and Earth-Time.org
*/
public interface ShrimpDataLegacyFileInterface {
public int extractCountOfRuns();
public void setSoftwareVersion(String value);
public String getSoftwareVersion();
public List<PrawnLegacyFile.Run> getRun();
public void setRuns(short value);
} | apache-2.0 |
mindie/Cindy | src/main/java/co/mindie/cindy/core/component/debugger/ComponentContextModel.java | 1251 | package co.mindie.cindy.core.component.debugger;
import java.util.List;
/**
* Created by simoncorsin on 24/09/14.
*/
public class ComponentContextModel {
////////////////////////
// VARIABLES
////////////////
private long id;
private Integer ownerId;
private List<ComponentModel> components;
private List<ComponentContextModel> isolatedChildComponentContexts;
////////////////////////
// CONSTRUCTORS
////////////////
////////////////////////
// METHODS
////////////////
////////////////////////
// GETTERS/SETTERS
////////////////
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public Integer getOwnerId() {
return ownerId;
}
public void setOwnerId(Integer ownerId) {
this.ownerId = ownerId;
}
public List<ComponentModel> getComponents() {
return components;
}
public void setComponents(List<ComponentModel> components) {
this.components = components;
}
public List<ComponentContextModel> getIsolatedChildComponentContexts() {
return isolatedChildComponentContexts;
}
public void setIsolatedChildComponentContexts(List<ComponentContextModel> isolatedChildComponentContexts) {
this.isolatedChildComponentContexts = isolatedChildComponentContexts;
}
}
| apache-2.0 |
sarmaHS/casopisInterFON | InterFON/app/src/main/java/com/interfon/android/utils/FlingBehavior.java | 1632 | package com.interfon.android.utils;
import android.content.Context;
import android.support.design.widget.AppBarLayout;
import android.support.design.widget.CoordinatorLayout;
import android.support.v7.widget.RecyclerView;
import android.util.AttributeSet;
import android.view.View;
public final class FlingBehavior extends AppBarLayout.Behavior {
private static final int TOP_CHILD_FLING_THRESHOLD = 3;
private boolean isPositive;
public FlingBehavior() {
}
public FlingBehavior(Context context, AttributeSet attrs) {
super(context, attrs);
}
@Override
public boolean onNestedFling(CoordinatorLayout coordinatorLayout, AppBarLayout child, View target, float velocityX, float velocityY, boolean consumed) {
if (velocityY > 0 && !isPositive || velocityY < 0 && isPositive) {
velocityY = velocityY * -1;
}
if (target instanceof RecyclerView && velocityY < 0) {
final RecyclerView recyclerView = (RecyclerView) target;
final View firstChild = recyclerView.getChildAt(0);
final int childAdapterPosition = recyclerView.getChildAdapterPosition(firstChild);
consumed = childAdapterPosition > TOP_CHILD_FLING_THRESHOLD;
}
return super.onNestedFling(coordinatorLayout, child, target, velocityX, velocityY, consumed);
}
@Override
public void onNestedPreScroll(CoordinatorLayout coordinatorLayout, AppBarLayout child, View target, int dx, int dy, int[] consumed) {
super.onNestedPreScroll(coordinatorLayout, child, target, dx, dy, consumed);
isPositive = dy > 0;
}
} | apache-2.0 |
roncoo/roncoo-pay | roncoo-pay-app-notify/src/main/java/com/roncoo/pay/app/notify/core/NotifyTask.java | 6332 | /*
* Copyright 2015-2102 RonCoo(http://www.roncoo.com) Group.
*
* 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.roncoo.pay.app.notify.core;
import com.alibaba.fastjson.JSONObject;
import com.roncoo.pay.AppNotifyApplication;
import com.roncoo.pay.app.notify.entity.NotifyParam;
import com.roncoo.pay.common.core.exception.BizException;
import com.roncoo.pay.notify.entity.RpNotifyRecord;
import com.roncoo.pay.notify.enums.NotifyStatusEnum;
import com.roncoo.pay.trade.utils.httpclient.SimpleHttpParam;
import com.roncoo.pay.trade.utils.httpclient.SimpleHttpResult;
import com.roncoo.pay.trade.utils.httpclient.SimpleHttpUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import java.util.concurrent.Delayed;
import java.util.concurrent.TimeUnit;
/**
* <b>功能说明:
* </b>
* @author Peter
* <a href="http://www.roncoo.com">龙果学院(www.roncoo.com)</a>
*/
public class NotifyTask implements Runnable, Delayed {
private static final Log LOG = LogFactory.getLog(NotifyTask.class);
private long executeTime;
private RpNotifyRecord notifyRecord;
private NotifyQueue notifyQueue;
private NotifyParam notifyParam;
private NotifyPersist notifyPersist = AppNotifyApplication.cacheNotifyPersist;
public NotifyTask() {
}
public NotifyTask(RpNotifyRecord notifyRecord, NotifyQueue notifyQueue, NotifyParam notifyParam) {
super();
this.notifyRecord = notifyRecord;
this.notifyQueue = notifyQueue;
this.notifyParam = notifyParam;
this.executeTime = getExecuteTime(notifyRecord);
}
private long getExecuteTime(RpNotifyRecord record) {
long lastTime = record.getLastNotifyTime().getTime();
Integer nextNotifyTime = notifyParam.getNotifyParams().get(record.getNotifyTimes());
return (nextNotifyTime == null ? 0 : nextNotifyTime * 1000) + lastTime;
}
public int compareTo(Delayed o) {
NotifyTask task = (NotifyTask) o;
return executeTime > task.executeTime ? 1 : (executeTime < task.executeTime ? -1 : 0);
}
public long getDelay(TimeUnit unit) {
return unit.convert(executeTime - System.currentTimeMillis(), unit.SECONDS);
}
public void run() {
// 得到当前通知对象的通知次数
Integer notifyTimes = notifyRecord.getNotifyTimes();
// 去通知
try {
LOG.info("Notify Url " + notifyRecord.getUrl()+" ;notify id:"+notifyRecord.getId()+";notify times:"+notifyRecord.getNotifyTimes());
/** 采用 httpClient */
SimpleHttpParam param = new SimpleHttpParam(notifyRecord.getUrl());
SimpleHttpResult result = SimpleHttpUtils.httpRequest(param);
/*
* OkHttpClient client = new OkHttpClient(); Request request = new
* Request.Builder().url(notifyRecord.getUrl()).build(); Response
* response = client.newCall(request).execute();
*/
notifyRecord.setNotifyTimes(notifyTimes + 1);
String successValue = notifyParam.getSuccessValue();
String responseMsg = "";
Integer responseStatus = result.getStatusCode();
// 得到返回状态,如果是200,也就是通知成功
if (result != null
&& (responseStatus == 200 || responseStatus == 201 || responseStatus == 202 || responseStatus == 203
|| responseStatus == 204 || responseStatus == 205 || responseStatus == 206)) {
responseMsg = result.getContent().trim();
responseMsg = responseMsg.length() >= 600 ? responseMsg.substring(0, 600) : responseMsg;
LOG.info("订单号: " + notifyRecord.getMerchantOrderNo() + " HTTP_STATUS:" + responseStatus + "请求返回信息:" + responseMsg);
// 通知成功
if (responseMsg.trim().equals(successValue)) {
notifyPersist.updateNotifyRord(notifyRecord.getId(), notifyRecord.getNotifyTimes(), NotifyStatusEnum.SUCCESS.name());
} else {
notifyQueue.addElementToList(notifyRecord);
notifyPersist.updateNotifyRord(notifyRecord.getId(), notifyRecord.getNotifyTimes(),
NotifyStatusEnum.HTTP_REQUEST_SUCCESS.name());
}
LOG.info("Update NotifyRecord:" + JSONObject.toJSONString(notifyRecord)+";responseMsg:"+responseMsg);
} else {
notifyQueue.addElementToList(notifyRecord);
// 再次放到通知列表中,由添加程序判断是否已经通知完毕或者通知失败
notifyPersist.updateNotifyRord(notifyRecord.getId(), notifyRecord.getNotifyTimes(),
NotifyStatusEnum.HTTP_REQUEST_FALIED.name());
}
// 写通知日志表
notifyPersist.saveNotifyRecordLogs(notifyRecord.getId(), notifyRecord.getMerchantNo(), notifyRecord.getMerchantOrderNo(),
notifyRecord.getUrl(), responseMsg, responseStatus);
LOG.info("Insert NotifyRecordLog, merchantNo:" + notifyRecord.getMerchantNo() + ",merchantOrderNo:"
+ notifyRecord.getMerchantOrderNo());
} catch (BizException e) {
LOG.error("NotifyTask", e);
} catch (Exception e) {
LOG.error("NotifyTask", e);
notifyQueue.addElementToList(notifyRecord);
notifyPersist.updateNotifyRord(notifyRecord.getId(), notifyRecord.getNotifyTimes(),
NotifyStatusEnum.HTTP_REQUEST_FALIED.name());
notifyPersist.saveNotifyRecordLogs(notifyRecord.getId(), notifyRecord.getMerchantNo(), notifyRecord.getMerchantOrderNo(),
notifyRecord.getUrl(), "", 0);
}
}
}
| apache-2.0 |
ms123s/simpl4-src | client/common/source/class/ms123/form/AlertOut.js | 2015 | /*
* This file is part of SIMPL4(http://simpl4.org).
*
* Copyright [2017] [Manfred Sattler] <manfred@ms123.org>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
@asset(qx/icon/${qx.icontheme}/22/actions/*)
@asset(qx/icon/${qx.icontheme}/16/places/*)
*/
qx.Class.define("ms123.form.AlertOut", {
extend: qx.ui.container.Composite,
implement: [ qx.ui.form.IStringForm, qx.ui.form.IForm],
include: [qx.ui.form.MForm],
/**
*****************************************************************************
CONSTRUCTOR
*****************************************************************************
*/
construct: function (message) {
this.base(arguments);
var layout = new qx.ui.layout.Grow();
this.setLayout(layout);
var label = new qx.ui.basic.Label( message );
label.setRich( true )
this.add(label);
},
/**
*****************************************************************************
PROPERTIES
*****************************************************************************
*/
properties: {
},
events: {
"changeValue": "qx.event.type.Data"
},
/**
*****************************************************************************
MEMBERS
*****************************************************************************
*/
members: {
setValue : function(value) {
this.fireDataEvent("changeValue", value, this.__value);
this.__value = value;
},
resetValue : function() {},
getValue : function() {
return this.__value;
}
}
});
| apache-2.0 |
iwanders/catkin_tools | catkin_tools/jobs/job.py | 8509 | # Copyright 2014 Open Source Robotics Foundation, 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.
from __future__ import print_function
import os
import stat
from catkin_tools.common import mkdir_p
from catkin_tools.common import get_cached_recursive_build_depends_in_workspace
from catkin_tools.resultspace import get_resultspace_environment
from catkin_tools.execution.jobs import Job
from catkin_tools.execution.stages import CommandStage
from .commands.cmake import CMAKE_EXEC
# Build Environment File
# =============
#
# The Build Environment file is used to create environments to packages built
# in an isolated build scenario. This enables packages to build against other
# packages without sourcing the main workspace setup.sh file.
#
# Due to portability issues, it uses only POSIX-compliant shell features. This
# means that there is no support for BASH-like arrays, and special care needs
# to be taken in order to preserve argument atomicity when passing along to the
# `exec` instruction at the end.
#
# This involves forming a string called `_ARGS` which is composed of tokens
# like `"$_Ai"` for i=0..N-1 for N arguments so that with N=3 arguments, for
# example, `_ARGS` would look like `"$_A0" "$_A1" "$_A2"`. The double-quotes
# are necessary because they define the argument boundaries when the variables
# are expanded by calling `eval`.
ENV_FILE_NAME = 'build_env.sh'
ENV_FILE_TEMPLATE = """\
#!/usr/bin/env sh
# generated from within catkin_tools/verbs/catkin_build/common.py
if [ $# -eq 0 ] ; then
/bin/echo "Usage: build_env.sh COMMANDS"
/bin/echo "Calling build_env.sh without arguments is not supported anymore."
/bin/echo "Instead spawn a subshell and source a setup file manually."
exit 1
fi
# save original args for later
_ARGS=
_ARGI=0
for arg in "$@"; do
# Define placeholder variable
eval "_A$_ARGI=\$arg"
# Add placeholder variable to arg list
_ARGS="$_ARGS \\"\$_A$_ARGI\\""
# Increment arg index
_ARGI=`expr $_ARGI + 1`
#######################
## Uncomment for debug:
#_escaped="$(echo "$arg" | sed -e 's@ @ @g')"
#echo "$_escaped"
#eval "echo '$_ARGI \$_A$_ARGI'"
#######################
done
#######################
## Uncomment for debug:
#echo "exec args:"
#echo "$_ARGS"
#for arg in $_ARGS; do eval echo $arg; done
#echo "-----------"
#####################
# remove all passed in args, resetting $@, $*, $#, $n
shift $#
# set the args for the sourced scripts
set -- $@ "--extend"
# source setup.sh with implicit --extend argument for each direct build depend in the workspace
{sources}
# execute given args
eval exec $_ARGS
"""
def get_env_file_path(package, context):
"""Get the path to a package's build environment file."""
return os.path.abspath(os.path.join(context.build_space_abs, package.name, ENV_FILE_NAME))
def get_env_loaders(package, context):
"""Get a list of env loaders required to build this package."""
sources = []
# If installing to isolated folders or not installing, but devel spaces are not merged
if (context.install and context.isolate_install) or (not context.install and context.isolate_devel):
# Source each package's install or devel space
space = context.install_space_abs if context.install else context.devel_space_abs
# Get the recursive dependcies
depends = get_cached_recursive_build_depends_in_workspace(package, context.packages)
# For each dep add a line to source its setup file
for dep_pth, dep in depends:
source_path = os.path.join(space, dep.name, 'env.sh')
sources.append(source_path)
else:
# Get the actual destination of this package
source_path = os.path.join(context.package_dest_path(package), 'env.sh')
sources = [source_path]
return sources
def get_env_loader(package, context):
"""This function returns a function object which extends a base environment
based on a set of environments to load."""
def load_env(base_env):
# Copy the base environment to extend
job_env = dict(base_env)
# Get the paths to the env loaders
env_loader_paths = get_env_loaders(package, context)
# If DESTDIR is set, set _CATKIN_SETUP_DIR as well
if context.destdir is not None:
job_env['_CATKIN_SETUP_DIR'] = context.package_dest_path(package)
for env_loader_path in env_loader_paths:
# print(' - Loading resultspace env from: {}'.format(env_loader_path))
resultspace_env = get_resultspace_environment(
os.path.split(env_loader_path)[0],
base_env=job_env,
quiet=True,
cached=context.use_env_cache,
strict=False)
job_env.update(resultspace_env)
return job_env
return load_env
def create_env_file(logger, event_queue, package, context, env_file_path):
"""FunctionStage functor for creating a build environment file."""
source_paths = get_env_loaders(package, context)
source_snippet = '. "{source_path}"'
sources = [source_snippet.format(source_path=source_path) for source_path in source_paths]
# Populate the build env file template and write it out
env_file = ENV_FILE_TEMPLATE.format(sources='\n'.join(sources))
if os.path.exists(env_file_path):
with open(env_file_path, 'r') as f:
if env_file == f.read():
return 0
with open(env_file_path, 'w') as f:
f.write(env_file)
# Make the env file executable
os.chmod(env_file_path, stat.S_IXUSR | stat.S_IWUSR | stat.S_IRUSR)
return 0
def get_package_build_space_path(buildspace, package_name):
"""Generates a build space path, does not modify the filesystem.
TODO: Move to common.py
TODO: Get buildspace from context
TODO: Make arguments the same order as get_env_file_path
:param buildspace: folder in which packages are built
:type buildspace: str
:param package_name: name of the package this build space is for
:type package_name: str
:returns: package specific build directory
:rtype: str
"""
return os.path.join(buildspace, package_name)
def create_build_space(logger, event_queue, buildspace, package_name):
"""Creates a build space, if it does not already exist, in the build space
:param buildspace: folder in which packages are built
:type buildspace: str
:param package_name: name of the package this build space is for
:type package_name: str
:returns: package specific build directory
:rtype: str
"""
package_build_dir = get_package_build_space_path(buildspace, package_name)
if not os.path.exists(package_build_dir):
os.makedirs(package_build_dir)
return package_build_dir
def makedirs(logger, event_queue, path):
"""FunctionStage functor that makes a path of directories."""
mkdir_p(path)
return 0
def get_build_type(package):
"""Returns the build type for a given package.
:param package: package object
:type package: :py:class:`catkin_pkg.package.Package`
:returns: build type of the package, e.g. 'catkin' or 'cmake'
:rtype: str
"""
export_tags = [e.tagname for e in package.exports]
if 'build_type' in export_tags:
build_type_tag = [e.content for e in package.exports if e.tagname == 'build_type'][0]
else:
build_type_tag = 'catkin'
return build_type_tag
def create_clean_buildspace_job(context, package_name, dependencies):
build_space = get_package_build_space_path(context.build_space_abs, package_name)
if not os.path.exists(build_space):
# No-op
return Job(jid=package_name, deps=dependencies, stages=[])
stages = []
stages.append(CommandStage(
'rmbuild',
[CMAKE_EXEC, '-E', 'remove_directory', build_space],
cwd=context.build_space_abs))
return Job(
jid=package_name,
deps=dependencies,
stages=stages)
| apache-2.0 |
AlbieLiang/IPCInvoker | ipc-invoker-ag-extension/src/main/java/cc/suitalk/ipcinvoker/ag/extension/MethodCodeBuilder.java | 2532 | /*
* Copyright (C) 2017-present Albie Liang. 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 cc.suitalk.ipcinvoker.ag.extension;
import cc.suitalk.arbitrarygen.base.PlainCodeBlock;
import cc.suitalk.arbitrarygen.block.MethodCodeBlock;
import cc.suitalk.arbitrarygen.block.TypeDefineCodeBlock;
import cc.suitalk.arbitrarygen.core.KeyWords;
import cc.suitalk.arbitrarygen.statement.NormalStatement;
import cc.suitalk.arbitrarygen.utils.Util;
/**
* Created by albieliang on 2017/11/9.
*/
public class MethodCodeBuilder {
public static void addCommonMethods(TypeDefineCodeBlock typeDefineCodeBlock) {
addMethod_getTarget(typeDefineCodeBlock);
}
private static void addMethod_getTarget(TypeDefineCodeBlock typeDefineCodeBlock) {
final String className = typeDefineCodeBlock.getName().getName();
MethodCodeBlock method = new MethodCodeBlock();
method.setCommendBlock("// Get singleton target object");
method.setModifier(KeyWords.V_JAVA_KEYWORDS_PRIVATE);
method.setIsStatic(true);
method.setType(Util.createSimpleTypeName(className));
method.setName(Util.createSimpleTypeName("getTarget"));
PlainCodeBlock plainCodeBlock = new PlainCodeBlock();
plainCodeBlock.addStatement(new NormalStatement(
String.format("%s task = ObjectStore.get(TARGET_CLASS);\n" +
" if (task == null) {\n" +
" synchronized (%s$AG.class) {\n" +
" task = ObjectStore.get(TARGET_CLASS);\n" +
" if (task == null) {\n" +
" task = new %s();\n" +
" ObjectStore.put(task);\n" +
" }\n" +
" }\n" +
" }\n" +
" return task;", className, className, className)));
method.setCodeBlock(plainCodeBlock);
}
}
| apache-2.0 |
KRMAssociatesInc/eHMP | ehmp/product/production/soap-handler/src/main/java/us/vistacore/vxsync/config/VlerConfiguration.java | 2853 | package us.vistacore.vxsync.config;
import com.fasterxml.jackson.annotation.JsonProperty;
public class VlerConfiguration {
@JsonProperty
private String host;
@JsonProperty
private String protocol;
@JsonProperty
private int port;
@JsonProperty
private String docquerypath;
@JsonProperty String docquerypathquery;
@JsonProperty
private String docquerytimeoutms;
@JsonProperty
private String docretrievepath;
@JsonProperty
private String docretrievepathquery;
@JsonProperty
private String docretrievetimeoutms;
@JsonProperty
private String systemusername;
@JsonProperty
private String systemsitecode;
public String getHost() {
return host;
}
public void setHost(String host) {
this.host = host;
}
public String getProtocol() {
return protocol;
}
public void setProtocol(String protocol) {
this.protocol = protocol;
}
public int getPort() {
return port;
}
public void setPort(int port) {
this.port = port;
}
public String getDocquerypath() {
return docquerypath;
}
public void setDocquerypath(String docquerypath) {
this.docquerypath = docquerypath;
}
public String getDocquerypathquery() {
return docquerypathquery;
}
public void setDocquerypathquery(String docquerypathquery) {
this.docquerypathquery = docquerypathquery;
}
public String getDocquerytimeoutms() {
return docquerytimeoutms;
}
public void setDocquerytimeoutms(String docquerytimeoutms) {
this.docquerytimeoutms = docquerytimeoutms;
}
public String getDocretrievepath() {
return docretrievepath;
}
public void setDocretrievepath(String docretrievepath) {
this.docretrievepath = docretrievepath;
}
public String getDocretrievepathquery() {
return docretrievepathquery;
}
public void setDocretrievepathquery(String docretrievepathquery) {
this.docretrievepathquery = docretrievepathquery;
}
public String getDocretrievetimeoutms() {
return docretrievetimeoutms;
}
public void setDocretrievetimeoutms(String docretrievetimeoutms) {
this.docretrievetimeoutms = docretrievetimeoutms;
}
public String getSystemusername() {
return systemusername;
}
public void setSystemusername(String systemusername) {
this.systemusername = systemusername;
}
public String getSystemsitecode() {
return systemsitecode;
}
public void setSystemsitecode(String systemsitecode) {
this.systemsitecode = systemsitecode;
}
}
| apache-2.0 |
roomorama/google-adwords-api | lib/adwords_api/v201008/targeting_idea_service.rb | 1068 | #!/usr/bin/ruby
# This is auto-generated code, changes will be overwritten.
# Copyright:: Copyright 2011, Google Inc. All Rights Reserved.
# License:: Licensed under the Apache License,Version 2.0 (the "License").
#
# Code generated by AdsCommon library 0.5.2 on 2011-10-20 20:33:54.
require 'ads_common/savon_service'
require 'adwords_api/v201008/targeting_idea_service_registry'
module AdwordsApi; module V201008; module TargetingIdeaService
class TargetingIdeaService < AdsCommon::SavonService
def initialize(api, endpoint)
namespace = 'https://adwords.google.com/api/adwords/o/v201008'
super(api, endpoint, namespace, :v201008)
end
def get_bulk_keyword_ideas(*args, &block)
return execute_action('get_bulk_keyword_ideas', args, &block)
end
def get(*args, &block)
return execute_action('get', args, &block)
end
private
def get_service_registry()
return TargetingIdeaServiceRegistry
end
def get_module()
return AdwordsApi::V201008::TargetingIdeaService
end
end
end; end; end
| apache-2.0 |
eugeneiiim/AndroidCollections | src/com/google/common/collect/ImmutableClassToInstanceMap.java | 5253 | /*
* Copyright (C) 2009 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.collect;
import java.util.Map;
import com.google.common.primitives.Primitives;
/**
* A class-to-instance map backed by an {@link ImmutableMap}. See also {@link
* MutableClassToInstanceMap}.
*
* @author Kevin Bourrillion
* @since 2 (imported from Google Collections Library)
*/
public final class ImmutableClassToInstanceMap<B> extends
ForwardingMap<Class<? extends B>, B> implements ClassToInstanceMap<B> {
/**
* Returns a new builder. The generated builder is equivalent to the builder
* created by the {@link Builder} constructor.
*/
public static <B> Builder<B> builder() {
return new Builder<B>();
}
/**
* A builder for creating immutable class-to-instance maps. Example:
* <pre> {@code
*
* static final ImmutableClassToInstanceMap<Handler> HANDLERS =
* new ImmutableClassToInstanceMap.Builder<Handler>()
* .put(FooHandler.class, new FooHandler())
* .put(BarHandler.class, new SubBarHandler())
* .put(Handler.class, new QuuxHandler())
* .build();}</pre>
*
* <p>After invoking {@link #build()} it is still possible to add more
* entries and build again. Thus each map generated by this builder will be
* a superset of any map generated before it.
*/
public static final class Builder<B> {
private final ImmutableMap.Builder<Class<? extends B>, B> mapBuilder
= ImmutableMap.builder();
/**
* Associates {@code key} with {@code value} in the built map. Duplicate
* keys are not allowed, and will cause {@link #build} to fail.
*/
public <T extends B> Builder<B> put(Class<T> type, T value) {
mapBuilder.put(type, value);
return this;
}
/**
* Associates all of {@code map's} keys and values in the built map.
* Duplicate keys are not allowed, and will cause {@link #build} to fail.
*
* @throws NullPointerException if any key or value in {@code map} is null
* @throws ClassCastException if any value is not an instance of the type
* specified by its key
*/
public <T extends B> Builder<B> putAll(
Map<? extends Class<? extends T>, ? extends T> map) {
for (Entry<? extends Class<? extends T>, ? extends T> entry
: map.entrySet()) {
Class<? extends T> type = entry.getKey();
T value = entry.getValue();
mapBuilder.put(type, cast(type, value));
}
return this;
}
private static <B, T extends B> T cast(Class<T> type, B value) {
return Primitives.wrap(type).cast(value);
}
/**
* Returns a new immutable class-to-instance map containing the entries
* provided to this builder.
*
* @throws IllegalArgumentException if duplicate keys were added
*/
public ImmutableClassToInstanceMap<B> build() {
return new ImmutableClassToInstanceMap<B>(mapBuilder.build());
}
}
/**
* Returns an immutable map containing the same entries as {@code map}. If
* {@code map} somehow contains entries with duplicate keys (for example, if
* it is a {@code SortedMap} whose comparator is not <i>consistent with
* equals</i>), the results of this method are undefined.
*
* <p><b>Note:</b> Despite what the method name suggests, if {@code map} is
* an {@code ImmutableClassToInstanceMap}, no copy will actually be performed.
*
* @throws NullPointerException if any key or value in {@code map} is null
* @throws ClassCastException if any value is not an instance of the type
* specified by its key
*/
@SuppressWarnings("unchecked") // covariant casts safe (unmodifiable)
public static <B, S extends B> ImmutableClassToInstanceMap<B> copyOf(
Map<? extends Class<? extends S>, ? extends S> map) {
if (map instanceof ImmutableClassToInstanceMap) {
return (ImmutableClassToInstanceMap<B>) (Map) map;
}
return new Builder<B>().putAll(map).build();
}
private final ImmutableMap<Class<? extends B>, B> delegate;
private ImmutableClassToInstanceMap(
ImmutableMap<Class<? extends B>, B> delegate) {
this.delegate = delegate;
}
@Override protected Map<Class<? extends B>, B> delegate() {
return delegate;
}
@SuppressWarnings("unchecked") // value could not get in if not a T
public <T extends B> T getInstance(Class<T> type) {
return (T) delegate.get(type);
}
/**
* Guaranteed to throw an exception and leave the map unmodified.
*
* @throws UnsupportedOperationException always
*/
public <T extends B> T putInstance(Class<T> type, T value) {
throw new UnsupportedOperationException();
}
}
| apache-2.0 |
EXEM-OSS/flamingo | flamingo-web/src/main/java/org/exem/flamingo/web/oozie/workflow/tree/TreeService.java | 4423 | /**
* Copyright (C) 2011 Flamingo Project (http://www.cloudine.io).
* <p/>
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
* <p/>
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
* <p/>
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.exem.flamingo.web.oozie.workflow.tree;
import org.exem.flamingo.web.model.rest.NodeType;
import org.exem.flamingo.web.model.rest.Tree;
import org.exem.flamingo.web.model.rest.TreeType;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;
import java.util.List;
/**
* Tree Service Interface.
*
* @author Byoung Gon, Kim
* @since 0.1
*/
public interface TreeService {
/**
* 지정한 노드의 이름을 변경한다.
*
* @param tree 이름을 변경할 노드
* @return 이름 변경 여부
*/
int rename(Tree tree);
/**
* 지정한 노드를 삭제한다.
*
* @param id 삭제할 노드의 ID
* @return 삭제 여부
*/
boolean delete(long id);
/**
* 새로운 노드를 부모 노드의 자식 노드로 생성한다.
*
* @param parent 자식 노드의 부모 노드(UI상에서 선택한 노드)
* @param child 생성할 자식 노드
* @param nodeType Node의 유형
* @return Primary Key를 가진 자식 노드
*/
Tree create(Tree parent, Tree child, NodeType nodeType);
/**
* 새로운 Tree 구성을 위한 루트 노드를 생성한다.
* 이미 존재한다면 다시 생성하지 않는다.
*
* @param treeType Tree의 유형
* @param username Username
* @return Primary Key를 가진 자식 노드
*/
Tree createRoot(TreeType treeType, String username);
/**
* 동일한 이름을 가진 자식 노드가 존재하는지 확인한다.
*
* @param parent 자식 노드의 부모 노드(UI상에서 선택한 노드)
* @param child 확인할 자식 노드
* @param treeType Tree의 유형
* @param nodeType Node의 유형
* @return 같은 노드가 존재하는 경우 <tt>true</tt>
*/
boolean checkSameNode(Tree parent, Tree child, TreeType treeType, NodeType nodeType);
/**
* Tree에서 현재 선택한 노드의 자식 노드에 같은 이름을 가진 노드가 있는지 확인한다.
*
* @param selectedNode Tree에서 선택한 노드
* @param name 자식 노드의 이름
* @param treeType Tree의 유형
* @return 같은 이름이 존재하는 경우 <tt>true</tt>
*/
boolean existSubItem(Tree selectedNode, String name, TreeType treeType);
/**
* Tree에서 현재 선택한 노드의 자식 노드에 같은 이름을 가진 폴더가 있는지 확인한다.
*
* @param selectedNode Tree에서 선택한 노드
* @param name 자식 폴더의 이름
* @param treeType Tree의 유형
* @return 같은 이름이 존재하는 경우 <tt>true</tt>
*/
boolean existSubFolder(Tree selectedNode, String name, TreeType treeType);
/**
* Tree의 ROOT 노드를 반환한다.
*
* @param treeType Tree의 유형
* @param username Username
* @return ROOT 노드
*/
Tree getRoot(TreeType treeType, String username);
/**
* 지정한 부모 노드의 자식 노드들을 반환한다.
*
* @param parentId 부모 노드의 ID
* @return 자식 노드
*/
List<Tree> getChilds(long parentId);
/**
* 지정한 Tree를 반환한다.
*
* @param id Tree의 ID
* @return 존재하지 않는 경우 <tt>null</tt>
*/
Tree get(long id);
/**
* 노드를 이동한다.
*
* @param from Source 노드
* @param to Target 노드
* @param type Tree 노드의 유형
*/
void move(String from, String to, TreeType type);
List<Tree> getWorkflowChilds(long id);
}
| apache-2.0 |
alipay/SoloPi | src/common/src/main/java/com/alipay/hulu/common/service/TouchService.java | 2175 | /*
* Copyright (C) 2015-present, Ant Financial Services Group
*
* 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.alipay.hulu.common.service;
import com.alipay.hulu.common.bean.ContinueGesture;
import com.alipay.hulu.common.service.base.ExportService;
/**
* Created by qiaoruikai on 2019/11/26 9:43 PM.
*/
public interface TouchService extends ExportService {
/**
* 点击
* @param x
* @param y
*/
public void click(int x, int y);
/**
* 长按
* @param x
* @param y
* @param pressTime
*/
public void press(int x, int y, int pressTime);
/**
* 滑动
* @param x1
* @param y1
* @param x2
* @param y2
*/
public void scroll(int x1, int y1, int x2, int y2, int scrollTime);
/**
* 拖动
* @param x1
* @param y1
* @param dragTime
* @param x2
* @param y2
* @param scrollTime
*/
public void drag(int x1, int y1, int dragTime, int x2, int y2, int scrollTime);
/**
* 连续手势操作
* @param gesture
*/
public void gesture(ContinueGesture gesture);
/**
* 缩放
* @param x
* @param y
* @param sourceRadio
* @param toRadio
* @param time
*/
public void pinch(int x, int y, int sourceRadio, int toRadio, int time);
/**
* 多手势
* @param gestures
*/
public void multiGesture(ContinueGesture[] gestures);
/**
* 开始
*/
public void start();
/**
* 结束
*/
public void stop();
/**
* 是否支持高级手势
* @return
*/
public boolean supportGesture();
}
| apache-2.0 |
hirohanin/sqoop-1.1.0hadoop21 | src/java/com/cloudera/sqoop/mapreduce/db/DBConfiguration.java | 8526 | /**
* Licensed to Cloudera, Inc. under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. Cloudera, Inc. licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.cloudera.sqoop.mapreduce.db;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.mapreduce.lib.db.DBWritable;
import com.cloudera.sqoop.mapreduce.db.DBInputFormat.NullDBWritable;
/**
* A container for configuration property names for jobs with DB input/output.
*
* The job can be configured using the static methods in this class,
* {@link DBInputFormat}, and {@link DBOutputFormat}.
* Alternatively, the properties can be set in the configuration with proper
* values.
*
* @see DBConfiguration#configureDB(Configuration, String, String, String,
* String)
* @see DBInputFormat#setInput(Job, Class, String, String)
* @see DBInputFormat#setInput(Job, Class, String, String, String, String...)
* @see DBOutputFormat#setOutput(Job, String, String...)
*/
public class DBConfiguration {
/** The JDBC Driver class name. */
public static final String DRIVER_CLASS_PROPERTY =
"mapreduce.jdbc.driver.class";
/** JDBC Database access URL. */
public static final String URL_PROPERTY = "mapreduce.jdbc.url";
/** User name to access the database. */
public static final String USERNAME_PROPERTY = "mapreduce.jdbc.username";
/** Password to access the database. */
public static final String PASSWORD_PROPERTY = "mapreduce.jdbc.password";
/** Input table name. */
public static final String INPUT_TABLE_NAME_PROPERTY =
"mapreduce.jdbc.input.table.name";
/** Field names in the Input table. */
public static final String INPUT_FIELD_NAMES_PROPERTY =
"mapreduce.jdbc.input.field.names";
/** WHERE clause in the input SELECT statement. */
public static final String INPUT_CONDITIONS_PROPERTY =
"mapreduce.jdbc.input.conditions";
/** ORDER BY clause in the input SELECT statement. */
public static final String INPUT_ORDER_BY_PROPERTY =
"mapreduce.jdbc.input.orderby";
/** Whole input query, exluding LIMIT...OFFSET. */
public static final String INPUT_QUERY = "mapreduce.jdbc.input.query";
/** Input query to get the count of records. */
public static final String INPUT_COUNT_QUERY =
"mapreduce.jdbc.input.count.query";
/** Input query to get the max and min values of the jdbc.input.query. */
public static final String INPUT_BOUNDING_QUERY =
"mapred.jdbc.input.bounding.query";
/** Class name implementing DBWritable which will hold input tuples. */
public static final String INPUT_CLASS_PROPERTY =
"mapreduce.jdbc.input.class";
/** Output table name. */
public static final String OUTPUT_TABLE_NAME_PROPERTY =
"mapreduce.jdbc.output.table.name";
/** Field names in the Output table. */
public static final String OUTPUT_FIELD_NAMES_PROPERTY =
"mapreduce.jdbc.output.field.names";
/** Number of fields in the Output table. */
public static final String OUTPUT_FIELD_COUNT_PROPERTY =
"mapreduce.jdbc.output.field.count";
/**
* Sets the DB access related fields in the {@link Configuration}.
* @param conf the configuration
* @param driverClass JDBC Driver class name
* @param dbUrl JDBC DB access URL.
* @param userName DB access username
* @param passwd DB access passwd
*/
public static void configureDB(Configuration conf, String driverClass,
String dbUrl, String userName, String passwd) {
conf.set(DRIVER_CLASS_PROPERTY, driverClass);
conf.set(URL_PROPERTY, dbUrl);
if (userName != null) {
conf.set(USERNAME_PROPERTY, userName);
}
if (passwd != null) {
conf.set(PASSWORD_PROPERTY, passwd);
}
}
/**
* Sets the DB access related fields in the JobConf.
* @param job the job
* @param driverClass JDBC Driver class name
* @param dbUrl JDBC DB access URL.
*/
public static void configureDB(Configuration job, String driverClass,
String dbUrl) {
configureDB(job, driverClass, dbUrl, null, null);
}
private Configuration conf;
public DBConfiguration(Configuration job) {
this.conf = job;
}
/** Returns a connection object to the DB.
* @throws ClassNotFoundException
* @throws SQLException */
public Connection getConnection()
throws ClassNotFoundException, SQLException {
Class.forName(conf.get(DBConfiguration.DRIVER_CLASS_PROPERTY));
if(conf.get(DBConfiguration.USERNAME_PROPERTY) == null) {
return DriverManager.getConnection(
conf.get(DBConfiguration.URL_PROPERTY));
} else {
return DriverManager.getConnection(
conf.get(DBConfiguration.URL_PROPERTY),
conf.get(DBConfiguration.USERNAME_PROPERTY),
conf.get(DBConfiguration.PASSWORD_PROPERTY));
}
}
public Configuration getConf() {
return conf;
}
public String getInputTableName() {
return conf.get(DBConfiguration.INPUT_TABLE_NAME_PROPERTY);
}
public void setInputTableName(String tableName) {
conf.set(DBConfiguration.INPUT_TABLE_NAME_PROPERTY, tableName);
}
public String[] getInputFieldNames() {
return conf.getStrings(DBConfiguration.INPUT_FIELD_NAMES_PROPERTY);
}
public void setInputFieldNames(String... fieldNames) {
conf.setStrings(DBConfiguration.INPUT_FIELD_NAMES_PROPERTY, fieldNames);
}
public String getInputConditions() {
return conf.get(DBConfiguration.INPUT_CONDITIONS_PROPERTY);
}
public void setInputConditions(String conditions) {
if (conditions != null && conditions.length() > 0) {
conf.set(DBConfiguration.INPUT_CONDITIONS_PROPERTY, conditions);
}
}
public String getInputOrderBy() {
return conf.get(DBConfiguration.INPUT_ORDER_BY_PROPERTY);
}
public void setInputOrderBy(String orderby) {
if(orderby != null && orderby.length() >0) {
conf.set(DBConfiguration.INPUT_ORDER_BY_PROPERTY, orderby);
}
}
public String getInputQuery() {
return conf.get(DBConfiguration.INPUT_QUERY);
}
public void setInputQuery(String query) {
if(query != null && query.length() >0) {
conf.set(DBConfiguration.INPUT_QUERY, query);
}
}
public String getInputCountQuery() {
return conf.get(DBConfiguration.INPUT_COUNT_QUERY);
}
public void setInputCountQuery(String query) {
if(query != null && query.length() > 0) {
conf.set(DBConfiguration.INPUT_COUNT_QUERY, query);
}
}
public void setInputBoundingQuery(String query) {
if (query != null && query.length() > 0) {
conf.set(DBConfiguration.INPUT_BOUNDING_QUERY, query);
}
}
public String getInputBoundingQuery() {
return conf.get(DBConfiguration.INPUT_BOUNDING_QUERY);
}
public Class<?> getInputClass() {
return conf.getClass(DBConfiguration.INPUT_CLASS_PROPERTY,
NullDBWritable.class);
}
public void setInputClass(Class<? extends DBWritable> inputClass) {
conf.setClass(DBConfiguration.INPUT_CLASS_PROPERTY, inputClass,
DBWritable.class);
}
public String getOutputTableName() {
return conf.get(DBConfiguration.OUTPUT_TABLE_NAME_PROPERTY);
}
public void setOutputTableName(String tableName) {
conf.set(DBConfiguration.OUTPUT_TABLE_NAME_PROPERTY, tableName);
}
public String[] getOutputFieldNames() {
return conf.getStrings(DBConfiguration.OUTPUT_FIELD_NAMES_PROPERTY);
}
public void setOutputFieldNames(String... fieldNames) {
conf.setStrings(DBConfiguration.OUTPUT_FIELD_NAMES_PROPERTY, fieldNames);
}
public void setOutputFieldCount(int fieldCount) {
conf.setInt(DBConfiguration.OUTPUT_FIELD_COUNT_PROPERTY, fieldCount);
}
public int getOutputFieldCount() {
return conf.getInt(OUTPUT_FIELD_COUNT_PROPERTY, 0);
}
}
| apache-2.0 |
markus1978/citygml4emf | de.hub.citygml.emf.ecore/src/org/w3/_2001/smil20/SyncBehaviorDefaultType.java | 6137 | /**
* <copyright>
* </copyright>
*
* $Id$
*/
package org.w3._2001.smil20;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import org.eclipse.emf.common.util.Enumerator;
/**
* <!-- begin-user-doc -->
* A representation of the literals of the enumeration '<em><b>Sync Behavior Default Type</b></em>',
* and utility methods for working with them.
* <!-- end-user-doc -->
* @see org.w3._2001.smil20.Smil20Package#getSyncBehaviorDefaultType()
* @model extendedMetaData="name='syncBehaviorDefaultType'"
* @generated
*/
public enum SyncBehaviorDefaultType implements Enumerator {
/**
* The '<em><b>Can Slip</b></em>' literal object.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #CAN_SLIP_VALUE
* @generated
* @ordered
*/
CAN_SLIP(0, "canSlip", "canSlip"),
/**
* The '<em><b>Locked</b></em>' literal object.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #LOCKED_VALUE
* @generated
* @ordered
*/
LOCKED(1, "locked", "locked"),
/**
* The '<em><b>Independent</b></em>' literal object.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #INDEPENDENT_VALUE
* @generated
* @ordered
*/
INDEPENDENT(2, "independent", "independent"),
/**
* The '<em><b>Inherit</b></em>' literal object.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #INHERIT_VALUE
* @generated
* @ordered
*/
INHERIT(3, "inherit", "inherit");
/**
* The '<em><b>Can Slip</b></em>' literal value.
* <!-- begin-user-doc -->
* <p>
* If the meaning of '<em><b>Can Slip</b></em>' literal object isn't clear,
* there really should be more of a description here...
* </p>
* <!-- end-user-doc -->
* @see #CAN_SLIP
* @model name="canSlip"
* @generated
* @ordered
*/
public static final int CAN_SLIP_VALUE = 0;
/**
* The '<em><b>Locked</b></em>' literal value.
* <!-- begin-user-doc -->
* <p>
* If the meaning of '<em><b>Locked</b></em>' literal object isn't clear,
* there really should be more of a description here...
* </p>
* <!-- end-user-doc -->
* @see #LOCKED
* @model name="locked"
* @generated
* @ordered
*/
public static final int LOCKED_VALUE = 1;
/**
* The '<em><b>Independent</b></em>' literal value.
* <!-- begin-user-doc -->
* <p>
* If the meaning of '<em><b>Independent</b></em>' literal object isn't clear,
* there really should be more of a description here...
* </p>
* <!-- end-user-doc -->
* @see #INDEPENDENT
* @model name="independent"
* @generated
* @ordered
*/
public static final int INDEPENDENT_VALUE = 2;
/**
* The '<em><b>Inherit</b></em>' literal value.
* <!-- begin-user-doc -->
* <p>
* If the meaning of '<em><b>Inherit</b></em>' literal object isn't clear,
* there really should be more of a description here...
* </p>
* <!-- end-user-doc -->
* @see #INHERIT
* @model name="inherit"
* @generated
* @ordered
*/
public static final int INHERIT_VALUE = 3;
/**
* An array of all the '<em><b>Sync Behavior Default Type</b></em>' enumerators.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
private static final SyncBehaviorDefaultType[] VALUES_ARRAY =
new SyncBehaviorDefaultType[] {
CAN_SLIP,
LOCKED,
INDEPENDENT,
INHERIT,
};
/**
* A public read-only list of all the '<em><b>Sync Behavior Default Type</b></em>' enumerators.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public static final List<SyncBehaviorDefaultType> VALUES = Collections.unmodifiableList(Arrays.asList(VALUES_ARRAY));
/**
* Returns the '<em><b>Sync Behavior Default Type</b></em>' literal with the specified literal value.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public static SyncBehaviorDefaultType get(String literal) {
for (int i = 0; i < VALUES_ARRAY.length; ++i) {
SyncBehaviorDefaultType result = VALUES_ARRAY[i];
if (result.toString().equals(literal)) {
return result;
}
}
return null;
}
/**
* Returns the '<em><b>Sync Behavior Default Type</b></em>' literal with the specified name.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public static SyncBehaviorDefaultType getByName(String name) {
for (int i = 0; i < VALUES_ARRAY.length; ++i) {
SyncBehaviorDefaultType result = VALUES_ARRAY[i];
if (result.getName().equals(name)) {
return result;
}
}
return null;
}
/**
* Returns the '<em><b>Sync Behavior Default Type</b></em>' literal with the specified integer value.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public static SyncBehaviorDefaultType get(int value) {
switch (value) {
case CAN_SLIP_VALUE: return CAN_SLIP;
case LOCKED_VALUE: return LOCKED;
case INDEPENDENT_VALUE: return INDEPENDENT;
case INHERIT_VALUE: return INHERIT;
}
return null;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
private final int value;
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
private final String name;
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
private final String literal;
/**
* Only this class can construct instances.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
private SyncBehaviorDefaultType(int value, String name, String literal) {
this.value = value;
this.name = name;
this.literal = literal;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public int getValue() {
return value;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public String getName() {
return name;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public String getLiteral() {
return literal;
}
/**
* Returns the literal value of the enumerator, which is its string representation.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public String toString() {
return literal;
}
} //SyncBehaviorDefaultType
| apache-2.0 |
floviolleau/vector-android | vector/src/main/java/im/vector/fragments/VectorMessageListFragment.java | 34338 | /*
* Copyright 2015 OpenMarket 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 im.vector.fragments;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.provider.Browser;
import android.support.v4.app.FragmentManager;
import android.content.SharedPreferences;
import android.preference.PreferenceManager;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonElement;
import org.matrix.androidsdk.MXSession;
import org.matrix.androidsdk.adapters.MessageRow;
import org.matrix.androidsdk.adapters.MessagesAdapter;
import org.matrix.androidsdk.data.RoomState;
import org.matrix.androidsdk.db.MXMediasCache;
import org.matrix.androidsdk.fragments.MatrixMessageListFragment;
import org.matrix.androidsdk.fragments.MatrixMessagesFragment;
import org.matrix.androidsdk.listeners.MXMediaDownloadListener;
import org.matrix.androidsdk.rest.callback.ApiCallback;
import org.matrix.androidsdk.rest.callback.SimpleApiCallback;
import org.matrix.androidsdk.rest.model.Event;
import org.matrix.androidsdk.rest.model.FileMessage;
import org.matrix.androidsdk.rest.model.ImageMessage;
import org.matrix.androidsdk.rest.model.MatrixError;
import org.matrix.androidsdk.rest.model.Message;
import org.matrix.androidsdk.rest.model.VideoMessage;
import org.matrix.androidsdk.util.JsonUtils;
import im.vector.Matrix;
import im.vector.R;
import im.vector.VectorApp;
import im.vector.activity.CommonActivityUtils;
import im.vector.activity.MXCActionBarActivity;
import im.vector.activity.VectorHomeActivity;
import im.vector.activity.VectorMemberDetailsActivity;
import im.vector.activity.VectorRoomActivity;
import im.vector.activity.VectorMediasViewerActivity;
import im.vector.adapters.VectorMessagesAdapter;
import im.vector.db.VectorContentProvider;
import im.vector.receiver.VectorUniversalLinkReceiver;
import im.vector.util.SlidableMediaInfo;
import im.vector.util.VectorUtils;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.util.ArrayList;
public class VectorMessageListFragment extends MatrixMessageListFragment implements VectorMessagesAdapter.VectorMessagesAdapterActionsListener {
private static final String LOG_TAG = "VectorMessageListFrg";
public interface IListFragmentEventListener{
void onListTouch();
}
private static final String TAG_FRAGMENT_RECEIPTS_DIALOG = "TAG_FRAGMENT_RECEIPTS_DIALOG";
private IListFragmentEventListener mHostActivityListener;
// onMediaAction actions
// private static final int ACTION_VECTOR_SHARE = R.id.ic_action_vector_share;
private static final int ACTION_VECTOR_FORWARD = R.id.ic_action_vector_forward;
private static final int ACTION_VECTOR_SAVE = R.id.ic_action_vector_save;
public static final int ACTION_VECTOR_OPEN = 123456;
// spinners
private View mBackProgressView;
private View mForwardProgressView;
private View mMainProgressView;
public static VectorMessageListFragment newInstance(String matrixId, String roomId, String eventId, String previewMode, int layoutResId) {
VectorMessageListFragment f = new VectorMessageListFragment();
Bundle args = new Bundle();
args.putInt(ARG_LAYOUT_ID, layoutResId);
args.putString(ARG_MATRIX_ID, matrixId);
args.putString(ARG_ROOM_ID, roomId);
if (null != eventId) {
args.putString(ARG_EVENT_ID, eventId);
}
if (null != previewMode) {
args.putString(ARG_PREVIEW_MODE_ID, previewMode);
}
f.setArguments(args);
return f;
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
Log.d(LOG_TAG, "onCreateView");
View v = super.onCreateView(inflater, container, savedInstanceState);
Bundle args = getArguments();
// when an event id is defined, display a thick green line to its left
if (args.containsKey(ARG_EVENT_ID) && (mAdapter instanceof VectorMessagesAdapter)) {
((VectorMessagesAdapter) mAdapter).setSearchedEventId(args.getString(ARG_EVENT_ID, ""));
}
return v;
}
@Override
public MatrixMessagesFragment createMessagesFragmentInstance(String roomId) {
return VectorMessagesFragment.newInstance(getSession(), roomId, this);
}
/**
* @return the fragment tag to use to restore the matrix messages fragment
*/
protected String getMatrixMessagesFragmentTag() {
return getClass().getName() + ".MATRIX_MESSAGE_FRAGMENT_TAG";
}
/**
* Called when a fragment is first attached to its activity.
* {@link #onCreate(Bundle)} will be called after this.
*
* @param aHostActivity parent activity
*/
@Override
public void onAttach(Activity aHostActivity) {
super.onAttach(aHostActivity);
try {
mHostActivityListener = (IListFragmentEventListener) aHostActivity;
}
catch(ClassCastException e) {
// if host activity does not provide the implementation, just ignore it
Log.w(LOG_TAG,"## onAttach(): host activity does not implement IListFragmentEventListener " + aHostActivity);
mHostActivityListener = null;
}
mBackProgressView = aHostActivity.findViewById(R.id.loading_room_paginate_back_progress);
mForwardProgressView = aHostActivity.findViewById(R.id.loading_room_paginate_forward_progress);
mMainProgressView = aHostActivity.findViewById(R.id.main_progress_layout);
}
@Override
public void onPause() {
super.onPause();
if (mAdapter instanceof VectorMessagesAdapter) {
((VectorMessagesAdapter)mAdapter).onPause();
}
}
/**
* Called when the fragment is no longer attached to its activity. This
* is called after {@link #onDestroy()}.
*/
@Override
public void onDetach() {
super.onDetach();
mHostActivityListener = null;
}
@Override
public MXSession getSession(String matrixId) {
return Matrix.getMXSession(getActivity(), matrixId);
}
@Override
public MXMediasCache getMXMediasCache() {
return Matrix.getInstance(getActivity()).getMediasCache();
}
@Override
public MessagesAdapter createMessagesAdapter() {
VectorMessagesAdapter vectorMessagesAdapter = new VectorMessagesAdapter(mSession, getActivity(), getMXMediasCache());
vectorMessagesAdapter.setVectorMessagesAdapterActionsListener(this);
return vectorMessagesAdapter;
}
/**
* The user scrolls the list.
* Apply an expected behaviour
* @param event the scroll event
*/
@Override
public void onListTouch(MotionEvent event) {
// the user scroll over the keyboard
// hides the keyboard
if (mCheckSlideToHide && (event.getY() > mMessageListView.getHeight())) {
mCheckSlideToHide = false;
MXCActionBarActivity.dismissKeyboard(getActivity());
}
// notify host activity
if(null != mHostActivityListener)
mHostActivityListener.onListTouch();
}
/**
* Cancel the messages selection mode.
*/
public void cancelSelectionMode() {
((VectorMessagesAdapter)mAdapter).cancelSelectionMode();
}
/**
* An action has been triggered on an event.
* @param event the event.
* @param textMsg the event text
* @param action an action ic_action_vector_XXX
*/
public void onEventAction(final Event event, final String textMsg, final int action) {
if (action == R.id.ic_action_vector_resend_message) {
getActivity().runOnUiThread(new Runnable() {
@Override
public void run() {
resend(event);
}
});
} else if (action == R.id.ic_action_vector_redact_message) {
getActivity().runOnUiThread(new Runnable() {
@Override
public void run() {
if (event.isUndeliverable()) {
// delete from the store
mSession.getDataHandler().getStore().deleteEvent(event);
mSession.getDataHandler().getStore().commit();
// remove from the adapter
mAdapter.removeEventById(event.eventId);
mAdapter.notifyDataSetChanged();
mEventSendingListener.onMessageRedacted(event);
} else {
redactEvent(event.eventId);
}
}
});
} else if (action == R.id.ic_action_vector_copy) {
getActivity().runOnUiThread(new Runnable() {
@Override
public void run() {
VectorUtils.copyToClipboard(getActivity(), textMsg);
}
});
} else if ((action == R.id.ic_action_vector_cancel_upload) || (action == R.id.ic_action_vector_cancel_download)) {
getActivity().runOnUiThread(new Runnable() {
@Override
public void run() {
new AlertDialog.Builder(VectorApp.getCurrentActivity())
.setMessage((action == R.id.ic_action_vector_cancel_upload) ? R.string.attachment_cancel_upload : R.string.attachment_cancel_download)
.setPositiveButton(R.string.yes, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
mRoom.cancelEventSending(event);
getActivity().runOnUiThread(new Runnable() {
@Override
public void run() {
mAdapter.notifyDataSetChanged();
}
});
}
})
.setNegativeButton(R.string.no, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
})
.create()
.show();
}
});
} else if (action == R.id.ic_action_vector_quote) {
Activity attachedActivity = getActivity();
if ((null != attachedActivity) && (attachedActivity instanceof VectorRoomActivity)) {
Message message = JsonUtils.toMessage(event.content);
((VectorRoomActivity)attachedActivity).insertQuoteInTextEditor( "> " + textMsg + "\n\n");
}
} else if ((action == R.id.ic_action_vector_share) || (action == R.id.ic_action_vector_forward) || (action == R.id.ic_action_vector_save)) {
//
Message message = JsonUtils.toMessage(event.content);
String mediaUrl = null;
String mediaMimeType = null;
if (message instanceof ImageMessage) {
ImageMessage imageMessage = (ImageMessage) message;
mediaUrl = imageMessage.url;
mediaMimeType = imageMessage.getMimeType();
} else if (message instanceof VideoMessage) {
VideoMessage videoMessage = (VideoMessage) message;
mediaUrl = videoMessage.url;
if (null != videoMessage.info) {
mediaMimeType = videoMessage.info.mimetype;
}
} else if (message instanceof FileMessage) {
FileMessage fileMessage = (FileMessage) message;
mediaUrl = fileMessage.url;
mediaMimeType = fileMessage.getMimeType();
}
// media file ?
if (null != mediaUrl) {
onMediaAction(action, mediaUrl, mediaMimeType, message.body);
} else if ((action == R.id.ic_action_vector_share) || (action == R.id.ic_action_vector_forward) || (action == R.id.ic_action_vector_quote)) {
// use the body
final Intent sendIntent = new Intent();
sendIntent.setAction(Intent.ACTION_SEND);
sendIntent.putExtra(Intent.EXTRA_TEXT, textMsg);
sendIntent.setType("text/plain");
if (action == R.id.ic_action_vector_forward) {
CommonActivityUtils.sendFilesTo(getActivity(), sendIntent);
} else {
startActivity(sendIntent);
}
}
} else if (action == R.id.ic_action_vector_permalink) {
VectorUtils.copyToClipboard(getActivity(), VectorUtils.getPermalink(event.roomId, event.eventId));
} else if (action == R.id.ic_action_vector_report) {
onMessageReport(event);
} else if (action == R.id.ic_action_view_source) {
getActivity().runOnUiThread(new Runnable() {
@Override
public void run() {
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
View view= getActivity().getLayoutInflater().inflate(R.layout.dialog_event_content, null);
TextView textview = (TextView)view.findViewById(R.id.event_content_text_view);
Gson gson = new GsonBuilder().setPrettyPrinting().create();
textview.setText(gson.toJson(JsonUtils.toJson(event)));
builder.setView(view);
builder.setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
}
});
builder.create().show();
}
});
}
}
/**
* The user reports a content problem to the server
* @param event the event to report
*/
private void onMessageReport(final Event event) {
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setTitle(R.string.room_event_action_report_prompt_reason);
// add a text input
final EditText input = new EditText(getActivity());
builder.setView(input);
builder.setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
final String reason = input.getText().toString();
mRoom.report(event.eventId, -100, reason, new SimpleApiCallback<Void>(getActivity()) {
@Override
public void onSuccess(Void info) {
new AlertDialog.Builder(VectorApp.getCurrentActivity())
.setMessage(R.string.room_event_action_report_prompt_ignore_user)
.setPositiveButton(R.string.yes, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
ArrayList<String> userIdsList = new ArrayList<>();
userIdsList.add(event.sender);
mSession.ignoreUsers(userIdsList, new SimpleApiCallback<Void>() {
@Override
public void onSuccess(Void info) {
}
});
}
})
.setNegativeButton(R.string.no, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
})
.create()
.show();
}
});
}
});
builder.setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
builder.show();
}
/***
* Manage save / share / forward actions on a media file
* @param menuAction the menu action ACTION_VECTOR__XXX
* @param mediaUrl the media URL (must be not null)
* @param mediaMimeType the mime type
* @param filename the filename
*/
protected void onMediaAction(final int menuAction, final String mediaUrl, final String mediaMimeType, final String filename) {
MXMediasCache mediasCache = Matrix.getInstance(getActivity()).getMediasCache();
File file = mediasCache.mediaCacheFile(mediaUrl, mediaMimeType);
// check if the media has already been downloaded
if (null != file) {
// download
if ((menuAction == ACTION_VECTOR_SAVE) || (menuAction == ACTION_VECTOR_OPEN)) {
String savedMediaPath = CommonActivityUtils.saveMediaIntoDownloads(getActivity(), file, filename, mediaMimeType);
if (null != savedMediaPath) {
if (menuAction == ACTION_VECTOR_SAVE) {
Toast.makeText(getActivity(), getText(R.string.media_slider_saved), Toast.LENGTH_LONG).show();
} else {
CommonActivityUtils.openMedia(getActivity(), savedMediaPath, mediaMimeType);
}
}
} else {
// shared / forward
Uri mediaUri = null;
File renamedFile = file;
if (!TextUtils.isEmpty(filename)) {
try {
InputStream fin = new FileInputStream(file);
String tmpUrl = mediasCache.saveMedia(fin, filename, mediaMimeType);
if (null != tmpUrl) {
renamedFile = mediasCache.mediaCacheFile(tmpUrl, mediaMimeType);
}
} catch (Exception e) {
Log.e(LOG_TAG, "onMediaAction shared / forward failed : " + e.getLocalizedMessage());
}
}
if (null != renamedFile) {
try {
mediaUri = VectorContentProvider.absolutePathToUri(getActivity(), renamedFile.getAbsolutePath());
} catch (Exception e) {
Log.e(LOG_TAG, "onMediaAction VectorContentProvider.absolutePathToUri: " + e.getLocalizedMessage());
}
}
if (null != mediaUri) {
final Intent sendIntent = new Intent();
sendIntent.setAction(Intent.ACTION_SEND);
sendIntent.setType(mediaMimeType);
sendIntent.putExtra(Intent.EXTRA_STREAM, mediaUri);
if (menuAction == ACTION_VECTOR_FORWARD) {
CommonActivityUtils.sendFilesTo(getActivity(), sendIntent);
} else {
startActivity(sendIntent);
}
}
}
} else {
// else download it
final String downloadId = mediasCache.downloadMedia(getActivity(), mSession.getHomeserverConfig(), mediaUrl, mediaMimeType);
mAdapter.notifyDataSetChanged();
if (null != downloadId) {
mediasCache.addDownloadListener(downloadId, new MXMediaDownloadListener() {
@Override
public void onDownloadError(String downloadId, JsonElement jsonElement) {
MatrixError error = JsonUtils.toMatrixError(jsonElement);
if ((null != error) && error.isSupportedErrorCode()) {
Toast.makeText(VectorMessageListFragment.this.getActivity(), error.getLocalizedMessage(), Toast.LENGTH_LONG).show();
}
}
@Override
public void onDownloadComplete(String aDownloadId) {
if (aDownloadId.equals(downloadId)) {
VectorMessageListFragment.this.getActivity().runOnUiThread(new Runnable() {
@Override
public void run() {
onMediaAction(menuAction, mediaUrl, mediaMimeType, filename);
}
});
}
}
});
}
}
}
/**
* return true to display all the events.
* else the unknown events will be hidden.
*/
@Override
public boolean isDisplayAllEvents() {
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(getActivity());
return preferences.getBoolean(getString(R.string.settings_key_display_all_events), false);
}
private void setViewVisibility(View view, int visibility) {
if ((null != view) && (null != getActivity())) {
view.setVisibility(visibility);
}
}
@Override
public void showLoadingBackProgress() {
setViewVisibility(mBackProgressView, View.VISIBLE);
}
@Override
public void hideLoadingBackProgress() {
setViewVisibility(mBackProgressView, View.GONE);
}
@Override
public void showLoadingForwardProgress() {
setViewVisibility(mForwardProgressView, View.VISIBLE);
}
@Override
public void hideLoadingForwardProgress() {
setViewVisibility(mForwardProgressView, View.GONE);
}
@Override
public void showInitLoading() {
setViewVisibility(mMainProgressView, View.VISIBLE);
}
@Override
public void hideInitLoading() {
setViewVisibility(mMainProgressView, View.GONE);
}
public boolean onRowLongClick(int position) {
return false;
}
/**
* @return the image and video messages list
*/
protected ArrayList<SlidableMediaInfo> listSlidableMessages() {
ArrayList<SlidableMediaInfo> res = new ArrayList<>();
for(int position = 0; position < mAdapter.getCount(); position++) {
MessageRow row = mAdapter.getItem(position);
Message message = JsonUtils.toMessage(row.getEvent().content);
if (Message.MSGTYPE_IMAGE.equals(message.msgtype)) {
ImageMessage imageMessage = (ImageMessage)message;
SlidableMediaInfo info = new SlidableMediaInfo();
info.mMessageType = Message.MSGTYPE_IMAGE;
info.mFileName = imageMessage.body;
info.mMediaUrl = imageMessage.url;
info.mRotationAngle = imageMessage.getRotation();
info.mOrientation = imageMessage.getOrientation();
info.mMimeType = imageMessage.getMimeType();
info.mIdentifier = row.getEvent().eventId;
res.add(info);
} else if (Message.MSGTYPE_VIDEO.equals(message.msgtype)) {
SlidableMediaInfo info = new SlidableMediaInfo();
VideoMessage videoMessage = (VideoMessage)message;
info.mMessageType = Message.MSGTYPE_VIDEO;
info.mFileName = videoMessage.body;
info.mMediaUrl = videoMessage.url;
info.mThumbnailUrl = (null != videoMessage.info) ? videoMessage.info.thumbnail_url : null;
info.mMimeType = videoMessage.getVideoMimeType();
res.add(info);
}
}
return res;
}
/**
* Returns the mediaMessage position in listMediaMessages.
* @param mediaMessagesList the media messages list
* @param mediaMessage the imageMessage
* @return the imageMessage position. -1 if not found.
*/
protected int getMediaMessagePosition(ArrayList<SlidableMediaInfo> mediaMessagesList, Message mediaMessage) {
String url = null;
if (mediaMessage instanceof ImageMessage) {
url = ((ImageMessage)mediaMessage).url;
} else if (mediaMessage instanceof VideoMessage) {
url = ((VideoMessage)mediaMessage).url;
}
// sanity check
if (null == url) {
return -1;
}
for(int index = 0; index < mediaMessagesList.size(); index++) {
if (mediaMessagesList.get(index).mMediaUrl.equals(url)) {
return index;
}
}
return -1;
}
@Override
public void onRowClick(int position) {
MessageRow row = mAdapter.getItem(position);
Event event = row.getEvent();
// switch in section mode
((VectorMessagesAdapter)mAdapter).onEventTap(event.eventId);
}
@Override
public void onContentClick(int position) {
MessageRow row = mAdapter.getItem(position);
Event event = row.getEvent();
VectorMessagesAdapter vectorMessagesAdapter = (VectorMessagesAdapter)mAdapter;
if (vectorMessagesAdapter.isInSelectionMode()) {
// cancel the selection mode.
vectorMessagesAdapter.onEventTap(null);
return;
}
Message message = JsonUtils.toMessage(event.content);
// video and images are displayed inside a medias slider.
if (Message.MSGTYPE_IMAGE.equals(message.msgtype) || (Message.MSGTYPE_VIDEO.equals(message.msgtype))) {
ArrayList<SlidableMediaInfo> mediaMessagesList = listSlidableMessages();
int listPosition = getMediaMessagePosition(mediaMessagesList, message);
if (listPosition >= 0) {
Intent viewImageIntent = new Intent(getActivity(), VectorMediasViewerActivity.class);
viewImageIntent.putExtra(VectorMediasViewerActivity.EXTRA_MATRIX_ID, mSession.getCredentials().userId);
viewImageIntent.putExtra(VectorMediasViewerActivity.KEY_THUMBNAIL_WIDTH, mAdapter.getMaxThumbnailWith());
viewImageIntent.putExtra(VectorMediasViewerActivity.KEY_THUMBNAIL_HEIGHT, mAdapter.getMaxThumbnailHeight());
viewImageIntent.putExtra(VectorMediasViewerActivity.KEY_INFO_LIST, mediaMessagesList);
viewImageIntent.putExtra(VectorMediasViewerActivity.KEY_INFO_LIST_INDEX, listPosition);
getActivity().startActivity(viewImageIntent);
}
} else if (Message.MSGTYPE_FILE.equals(message.msgtype)) {
FileMessage fileMessage = JsonUtils.toFileMessage(event.content);
if (null != fileMessage.url) {
onMediaAction(ACTION_VECTOR_OPEN, fileMessage.url, fileMessage.getMimeType(), fileMessage.body);
}
} else {
// switch in section mode
vectorMessagesAdapter.onEventTap(event.eventId);
}
}
@Override
public boolean onContentLongClick(int position) {
return onRowLongClick(position);
}
@Override
public void onAvatarClick(String userId) {
Intent roomDetailsIntent = new Intent(getActivity(), VectorMemberDetailsActivity.class);
// in preview mode
// the room is stored in a temporary store
// so provide an handle to retrieve it
if (null != getRoomPreviewData()) {
roomDetailsIntent.putExtra(VectorMemberDetailsActivity.EXTRA_STORE_ID, new Integer(Matrix.getInstance(getActivity()).addTmpStore(mEventTimeLine.getStore())));
}
roomDetailsIntent.putExtra(VectorMemberDetailsActivity.EXTRA_ROOM_ID, mRoom.getRoomId());
roomDetailsIntent.putExtra(VectorMemberDetailsActivity.EXTRA_MEMBER_ID, userId);
roomDetailsIntent.putExtra(VectorMemberDetailsActivity.EXTRA_MATRIX_ID, mSession.getCredentials().userId);
getActivity().startActivityForResult(roomDetailsIntent, VectorRoomActivity.GET_MENTION_REQUEST_CODE);
}
@Override
public boolean onAvatarLongClick(String userId) {
if (getActivity() instanceof VectorRoomActivity) {
RoomState state = mRoom.getLiveState();
if (null != state) {
String displayName = state.getMemberName(userId);
if (!TextUtils.isEmpty(displayName)) {
((VectorRoomActivity)getActivity()).insertUserDisplayNameInTextEditor(displayName);
}
}
}
return true;
}
@Override
public void onSenderNameClick(String userId, String displayName) {
if (getActivity() instanceof VectorRoomActivity) {
((VectorRoomActivity)getActivity()).insertUserDisplayNameInTextEditor(displayName);
}
}
@Override
public void onMediaDownloaded(int position) {
}
@Override
public void onMoreReadReceiptClick(String eventId) {
FragmentManager fm = getActivity().getSupportFragmentManager();
VectorReadReceiptsDialogFragment fragment = (VectorReadReceiptsDialogFragment) fm.findFragmentByTag(TAG_FRAGMENT_RECEIPTS_DIALOG);
if (fragment != null) {
fragment.dismissAllowingStateLoss();
}
fragment = VectorReadReceiptsDialogFragment.newInstance(mSession, mRoom.getRoomId(), eventId);
fragment.show(fm, TAG_FRAGMENT_RECEIPTS_DIALOG);
}
@Override
public void onURLClick(Uri uri) {
if (null != uri) {
if (null != VectorUniversalLinkReceiver.parseUniversalLink(uri)) {
// pop to the home activity
Intent intent = new Intent(getActivity(), VectorHomeActivity.class);
intent.setFlags(android.content.Intent.FLAG_ACTIVITY_CLEAR_TOP | android.content.Intent.FLAG_ACTIVITY_SINGLE_TOP);
intent.putExtra(VectorHomeActivity.EXTRA_JUMP_TO_UNIVERSAL_LINK, uri);
getActivity().startActivity(intent);
} else {
try {
Intent intent = new Intent(Intent.ACTION_VIEW, uri);
intent.putExtra(Browser.EXTRA_APPLICATION_ID, getActivity().getPackageName());
getActivity().startActivity(intent);
} catch (Exception e) {
Log.e(LOG_TAG, "## onURLClick() : has to viewser to open " + uri +" with error" + e.getMessage());
}
}
}
}
@Override
public void onMatrixUserIdClick(final String userId) {
showInitLoading();
getActivity().runOnUiThread(new Runnable() {
@Override
public void run() {
CommonActivityUtils.goToOneToOneRoom(mSession, userId, getActivity(), new ApiCallback<Void>() {
@Override
public void onSuccess(Void info) {
// nothing to do here
}
private void onError(String errorMessage) {
hideInitLoading();
CommonActivityUtils.displayToast(getActivity(), errorMessage);
}
@Override
public void onNetworkError(Exception e) {
onError(e.getLocalizedMessage());
}
@Override
public void onMatrixError(MatrixError e) {
onError(e.getLocalizedMessage());
}
@Override
public void onUnexpectedError(Exception e) {
onError(e.getLocalizedMessage());
}
});
}
});
}
@Override
public void onRoomAliasClick(String roomAlias) {
try {
onURLClick(Uri.parse(VectorUtils.getPermalink(roomAlias, null)));
} catch (Exception e) {
Log.e(LOG_TAG, "onRoomAliasClick failed " + e.getLocalizedMessage());
}
}
@Override
public void onRoomIdClick(String roomId) {
try {
onURLClick(Uri.parse(VectorUtils.getPermalink(roomId, null)));
} catch (Exception e) {
Log.e(LOG_TAG, "onRoomIdClick failed " + e.getLocalizedMessage());
}
}
@Override
public void onMessageIdClick(String messageId) {
try {
onURLClick(Uri.parse(VectorUtils.getPermalink(mRoom.getRoomId(), messageId)));
} catch (Exception e) {
Log.e(LOG_TAG, "onRoomIdClick failed " + e.getLocalizedMessage());
}
}
}
| apache-2.0 |
samueltardieu/cgeo | main/src/cgeo/geocaching/connector/gc/IconDecoder.java | 18560 | package cgeo.geocaching.connector.gc;
import cgeo.geocaching.models.Geocache;
import cgeo.geocaching.enumerations.CacheType;
import cgeo.geocaching.settings.Settings;
import android.graphics.Bitmap;
/**
* icon decoder for cache icons
*
*/
final class IconDecoder {
private static final int CT_TRADITIONAL = 0;
private static final int CT_MULTI = 1;
private static final int CT_MYSTERY = 2;
private static final int CT_EVENT = 3;
private static final int CT_EARTH = 4;
private static final int CT_FOUND = 5;
private static final int CT_OWN = 6;
private static final int CT_MEGAEVENT = 7;
private static final int CT_CITO = 8;
private static final int CT_WEBCAM = 9;
private static final int CT_WHERIGO = 10;
private static final int CT_VIRTUAL = 11;
private static final int CT_LETTERBOX = 12;
private IconDecoder() {
throw new IllegalStateException("utility class");
}
static boolean parseMapPNG(final Geocache cache, final Bitmap bitmap, final UTFGridPosition xy, final int zoomlevel) {
final int topX = xy.getX() * 4;
final int topY = xy.getY() * 4;
final int bitmapWidth = bitmap.getWidth();
final int bitmapHeight = bitmap.getHeight();
if ((topX < 0) || (topY < 0) || (topX + 4 > bitmapWidth) || (topY + 4 > bitmapHeight)) {
return false; //out of image position
}
int numberOfDetections = 7; //for level 12 and 13
if (zoomlevel < 12) {
numberOfDetections = 5;
}
if (zoomlevel > 13) {
numberOfDetections = 13;
}
final int[] pngType = new int[numberOfDetections];
for (int x = topX; x < topX + 4; x++) {
for (int y = topY; y < topY + 4; y++) {
final int color = bitmap.getPixel(x, y);
if ((color >>> 24) != 255) {
continue; //transparent pixels (or semi_transparent) are only shadows of border
}
final int r = (color & 0xFF0000) >> 16;
final int g = (color & 0xFF00) >> 8;
final int b = color & 0xFF;
if (isPixelDuplicated(r, g, b, zoomlevel)) {
continue;
}
final int type;
if (zoomlevel < 12) {
type = getCacheTypeFromPixel11(r, g, b);
} else if (zoomlevel > 13) {
type = getCacheTypeFromPixel14(r, g, b);
} else {
type = getCacheTypeFromPixel13(r, g, b);
}
pngType[type]++;
}
}
int type = -1;
int count = 0;
for (int x = 0; x < pngType.length; x++) {
if (pngType[x] > count) {
count = pngType[x];
type = x;
}
}
if (count > 1) { // 2 pixels need to detect same type and we say good to go
switch (type) {
case CT_TRADITIONAL:
cache.setType(CacheType.TRADITIONAL, zoomlevel);
return true;
case CT_MULTI:
cache.setType(CacheType.MULTI, zoomlevel);
return true;
case CT_MYSTERY:
cache.setType(CacheType.MYSTERY, zoomlevel);
return true;
case CT_EVENT:
cache.setType(CacheType.EVENT, zoomlevel);
return true;
case CT_EARTH:
cache.setType(CacheType.EARTH, zoomlevel);
return true;
case CT_FOUND:
cache.setFound(true);
return true;
case CT_OWN:
cache.setOwnerUserId(Settings.getUserName());
return true;
case CT_MEGAEVENT:
cache.setType(CacheType.MEGA_EVENT, zoomlevel);
return true;
case CT_CITO:
cache.setType(CacheType.CITO, zoomlevel);
return true;
case CT_WEBCAM:
cache.setType(CacheType.WEBCAM, zoomlevel);
return true;
case CT_WHERIGO:
cache.setType(CacheType.WHERIGO, zoomlevel);
return true;
case CT_VIRTUAL:
cache.setType(CacheType.VIRTUAL, zoomlevel);
return true;
case CT_LETTERBOX:
cache.setType(CacheType.LETTERBOX, zoomlevel);
return true;
}
}
return false;
}
/**
* A method that returns true if pixel color appears on more than one cache type and shall be excluded from parsing
*
* @param r
* red value
* @param g
* green value
* @param b
* blue value
* @param zoomlevel
* zoom level of map
* @return true if parsing should not be performed
*/
private static boolean isPixelDuplicated(final int r, final int g, final int b, final int zoomlevel) {
if (zoomlevel < 12) {
if (((r == g) && (g == b)) || ((r == 233) && (g == 233) && (b == 234))) {
return true;
}
return false;
}
if (zoomlevel > 13) {
if ((r == g) && (g == b)) {
if ((r == 119) || (r == 231) || (r == 5) || (r == 230) || (r == 244) || (r == 93) || (r == 238) || (r == 73) || (r == 9) || (r == 225) || (r == 162) || (r == 153) || (r == 32) ||
(r == 50) || (r == 20) || (r == 232) || (r == 224) || (r == 192) || (r == 248) || (r == 152) || (r == 128) || (r == 176) || (r == 184) || (r == 200)) {
return false;
}
return true;
}
if ((r == 44) && (b == 44) && (g == 17) ||
(r == 228) && (b == 228) && (g == 255) ||
(r == 236) && (b == 236) && (g == 255) ||
(r == 252) && (b == 225) && (g == 83) ||
(r == 252) && (b == 221) && (g == 81) ||
(r == 252) && (b == 216) && (g == 79) ||
(r == 252) && (b == 211) && (g == 77) ||
(r == 251) && (b == 206) && (g == 75) ||
(r == 251) && (b == 201) && (g == 73) ||
(r == 251) && (b == 196) && (g == 71) ||
(r == 251) && (b == 191) && (g == 69) ||
(r == 243) && (b == 153) && (g == 36)) {
return true;
}
return false;
}
//zoom level 12, 13
if ((r == 95) && (g == 95) && (b == 95)) {
return true;
}
return false;
}
/**
* This method returns detected type from specific pixel from geocaching.com live map.
* It was constructed based on classification tree made by Orange (http://orange.biolab.si/)
* Input file was made from every non-transparent pixel of every possible "middle" cache icon from GC map
*
* @param r
* Red component of pixel (from 0 - 255)
* @param g
* Green component of pixel (from 0 - 255)
* @param b
* Blue component of pixel (from 0 - 255)
* @return Value from 0 to 6 representing detected type or state of the cache.
*/
private static int getCacheTypeFromPixel13(final int r, final int g, final int b) {
if (b < 130) {
if (r < 41) {
return CT_MYSTERY;
}
if (g < 74) {
return CT_EVENT;
}
if (r < 130) {
return CT_TRADITIONAL;
}
if (b < 31) {
return CT_MULTI;
}
if (b < 101) {
if (g < 99) {
return r < 178 ? CT_FOUND : CT_EVENT;
}
if (b < 58) {
if (g < 174) {
return CT_FOUND;
}
if (r < 224) {
return CT_OWN;
}
if (b < 49) {
return g < 210 ? CT_FOUND : CT_OWN;
}
if (g < 205) {
return g < 202 ? CT_FOUND : CT_OWN;
}
return CT_FOUND;
}
if (r < 255) {
return CT_FOUND;
}
return g < 236 ? CT_MULTI : CT_FOUND;
}
return g < 182 ? CT_EVENT : CT_MULTI;
}
if (r < 136) {
return CT_MYSTERY;
}
if (b < 168) {
return g < 174 ? CT_EARTH : CT_TRADITIONAL;
}
return CT_EARTH;
}
/**
* This method returns detected type from specific pixel from geocaching.com live map level 14 or higher.
* It was constructed based on classification tree made by Orange (http://orange.biolab.si/)
* Input file was made from every non-transparent pixel of every possible "full" cache icon from GC map
*
* @param r
* Red component of pixel (from 0 - 255)
* @param g
* Green component of pixel (from 0 - 255)
* @param b
* Blue component of pixel (from 0 - 255)
* @return Value from 0 to 6 representing detected type or state of the cache.
*/
private static int getCacheTypeFromPixel14(final int r, final int g, final int b) {
if (b < 128) {
if (r < 214) {
if (b < 37) {
if (g < 50) {
if (b < 19) {
if (g < 16) {
if (b < 4) {
return CT_FOUND;
}
return r < 8 ? CT_VIRTUAL : CT_WEBCAM;
}
return CT_FOUND;
}
return CT_WEBCAM;
}
if (b < 24) {
if (b < 18) {
return CT_EARTH;
}
return r < 127 ? CT_TRADITIONAL : CT_EARTH;
}
return CT_FOUND;
}
if (r < 142) {
if (r < 63) {
if (r < 26) {
return CT_CITO;
}
return r < 51 ? CT_WEBCAM : CT_CITO;
}
return g < 107 ? CT_WEBCAM : CT_MULTI;
}
if (g < 138) {
return r < 178 ? CT_MEGAEVENT : CT_EVENT;
}
return b < 71 ? CT_FOUND : CT_EARTH;
}
if (b < 77) {
if (g < 166) {
if (r < 238) {
return g < 120 ? CT_MULTI : CT_OWN;
}
if (b < 57) {
if (r < 254) {
if (b < 39) {
if (r < 239) {
return CT_OWN;
}
if (b < 36) {
if (g < 150) {
if (b < 24) {
return b < 22 ? CT_FOUND : CT_OWN;
}
if (g < 138) {
return b < 25 ? CT_FOUND : CT_OWN;
}
return CT_FOUND;
}
return CT_OWN;
}
if (b < 38) {
if (b < 37) {
if (g < 153) {
return r < 242 ? CT_OWN : CT_FOUND;
}
return CT_OWN;
}
return CT_FOUND;
}
return CT_OWN;
}
if (g < 148) {
return CT_OWN;
}
if (r < 244) {
return CT_FOUND;
}
if (b < 45) {
if (b < 42) {
return CT_FOUND;
}
if (g < 162) {
return r < 245 ? CT_OWN : CT_FOUND;
}
return CT_OWN;
}
return CT_FOUND;
}
return g < 3 ? CT_FOUND : CT_VIRTUAL;
}
return CT_OWN;
}
if (b < 51) {
if (r < 251) {
return CT_OWN;
}
return g < 208 ? CT_EARTH : CT_MULTI;
}
if (b < 63) {
if (r < 247) {
return CT_FOUND;
}
if (r < 250) {
if (g < 169) {
return CT_FOUND;
}
if (g < 192) {
if (b < 54) {
return CT_OWN;
}
if (r < 248) {
return g < 180 ? CT_FOUND : CT_OWN;
}
return CT_OWN;
}
return g < 193 ? CT_FOUND : CT_OWN;
}
return CT_FOUND;
}
return CT_FOUND;
}
if (g < 177) {
return CT_OWN;
}
if (r < 239) {
return CT_FOUND;
}
if (g < 207) {
return CT_OWN;
}
return r < 254 ? CT_FOUND : CT_EARTH;
}
if (r < 203) {
if (b < 218) {
if (g < 158) {
if (g < 71) {
return CT_MYSTERY;
}
return r < 153 ? CT_WHERIGO : CT_WEBCAM;
}
if (b < 167) {
return r < 157 ? CT_TRADITIONAL : CT_WEBCAM;
}
return CT_WHERIGO;
}
if (g < 199) {
if (r < 142) {
return CT_LETTERBOX;
}
return r < 175 ? CT_CITO : CT_LETTERBOX;
}
if (g < 207) {
return r < 167 ? CT_MEGAEVENT : CT_CITO;
}
return CT_EARTH;
}
if (b < 224) {
if (g < 235) {
if (b < 163) {
if (r < 249) {
return b < 133 ? CT_FOUND : CT_OWN;
}
return CT_FOUND;
}
if (r < 235) {
if (r < 213) {
if (r < 207) {
return CT_FOUND;
}
if (g < 206) {
return CT_OWN;
}
return g < 207 ? CT_FOUND : CT_OWN;
}
return g < 194 ? CT_OWN : CT_FOUND;
}
if (g < 230) {
return CT_OWN;
}
return b < 205 ? CT_FOUND : CT_OWN;
}
if (r < 238) {
return CT_CITO;
}
return b < 170 ? CT_EVENT : CT_FOUND;
}
if (r < 251) {
if (r < 210) {
return CT_MYSTERY;
}
if (b < 252) {
if (r < 243) {
if (r < 225) {
return CT_WHERIGO;
}
if (b < 232) {
if (g < 228) {
return CT_WEBCAM;
}
return r < 231 ? CT_VIRTUAL : CT_TRADITIONAL;
}
if (r < 236) {
return CT_WHERIGO;
}
return r < 240 ? CT_WEBCAM : CT_WHERIGO;
}
if (g < 247) {
return r < 245 ? CT_WEBCAM : CT_FOUND;
}
return CT_WHERIGO;
}
return CT_LETTERBOX;
}
if (r < 255) {
return CT_OWN;
}
return g < 254 ? CT_FOUND : CT_OWN;
}
/**
* This method returns detected type from specific pixel from geocaching.com live map level 11 or lower.
* It was constructed based on classification tree made by Orange (http://orange.biolab.si/)
* Input file was made from every non-transparent pixel of every possible "full" cache icon from GC map
*
* @param r
* Red component of pixel (from 0 - 255)
* @param g
* Green component of pixel (from 0 - 255)
* @param b
* Blue component of pixel (from 0 - 255)
* @return Value from 0 to 4 representing detected type or state of the cache.
*/
private static int getCacheTypeFromPixel11(final int r, final int g, final int b) {
if (g < 136) {
if (r < 90) {
return g < 111 ? CT_MYSTERY : CT_TRADITIONAL;
}
return b < 176 ? CT_EVENT : CT_MYSTERY;
}
if (r < 197) {
return CT_TRADITIONAL;
}
return b < 155 ? CT_MULTI : CT_EARTH;
}
}
| apache-2.0 |
spsnk/sky | sky/admin/ui/client-add - Copy.php | 705 | <script type="text/javascript">
clientAdd();
</script>
<form id="client" action="../core/query.php" method="post">
<input type="hidden" name="nya" value="client" />
<input type="hidden" name="act" value="add" />
<input type="text" name="name" value="Nombre" id="name" minlength="3" maxlength="40" class="required" /> <br />
<input type="text" name="address" value="Dirección" maxlength="40" id="addr" /> <br />
<input type="text" name="phone" value="Teléfono" id="phone" minlength="9" maxlength="18" />
<input type="checkbox" id="cel" />
<label for="cel">¿Celular?</label> <br />
<input type="submit" class="boton" value="Agregar Cliente" id="submit" />
</form> | apache-2.0 |
enaml-ops/omg-product-bundle | products/p-rabbitmq/enaml-gen/rabbitmq-haproxy/syslogaggregator.go | 345 | package rabbitmq_haproxy
/*
* File Generated by enaml generator
* !!! Please do not edit this file !!!
*/
type SyslogAggregator struct {
/*Address - Descr: Syslog drain hostname Default: <nil>
*/
Address interface{} `yaml:"address,omitempty"`
/*Port - Descr: Syslog drain port Default: <nil>
*/
Port interface{} `yaml:"port,omitempty"`
} | apache-2.0 |
batmancn/TinySDNController | ACE_wrappers/examples/Logger/simple-server/Logging_Acceptor.cpp | 2066 | // $Id: Logging_Acceptor.cpp 91671 2010-09-08 18:39:23Z johnnyw $
#include "ace/WFMO_Reactor.h"
#include "ace/Log_Msg.h"
#include "Logging_Acceptor.h"
#include "Logging_Handler.h"
#include "Reactor_Singleton.h"
// Initialize peer_acceptor object.
int
Logging_Acceptor::open (const ACE_INET_Addr &addr)
{
// Reuse addr if already in use.
if (this->peer_acceptor_.open (addr, 1) == -1)
return -1;
else
return 0;
}
// Default constructor.
Logging_Acceptor::Logging_Acceptor (void)
{
}
// Performs termination activities.
int
Logging_Acceptor::handle_close (ACE_HANDLE, ACE_Reactor_Mask)
{
this->peer_acceptor_.close ();
// Note, this object MUST be allocated dynamically!
delete this;
return 0;
}
Logging_Acceptor::~Logging_Acceptor (void)
{
}
// Returns underlying device descriptor.
ACE_HANDLE
Logging_Acceptor::get_handle (void) const
{
return this->peer_acceptor_.get_handle ();
}
// Accepts connections from client and registers new object with the
// ACE_Reactor.
int
Logging_Acceptor::handle_input (ACE_HANDLE)
{
Logging_Handler *svc_handler;
ACE_NEW_RETURN (svc_handler, Logging_Handler, -1);
// Accept the connection from a client client daemon.
// Try to find out if the implementation of the reactor that we are
// using requires us to reset the event association for the newly
// created handle. This is because the newly created handle will
// inherit the properties of the listen handle, including its event
// associations.
int reset_new_handle = this->reactor ()->uses_event_associations ();
if (this->peer_acceptor_.accept (svc_handler->peer (), // stream
0, // remote address
0, // timeout
1, // restart
reset_new_handle // reset new handler
) == -1
|| svc_handler->open () == -1)
{
svc_handler->close ();
ACE_ERROR_RETURN ((LM_ERROR, "%p", "accept/open failed"), -1);
}
return 0;
}
| apache-2.0 |
spring-projects/spring-framework | spring-test/src/test/java/org/springframework/test/context/configuration/interfaces/SqlConfigInterfaceTests.java | 2029 | /*
* Copyright 2002-2019 the original author or 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
*
* 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 org.springframework.test.context.configuration.interfaces;
import javax.sql.DataSource;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.test.context.jdbc.Sql;
import org.springframework.test.context.jdbc.SqlConfig;
import org.springframework.test.context.junit.jupiter.SpringExtension;
import org.springframework.test.jdbc.JdbcTestUtils;
import static org.assertj.core.api.Assertions.assertThat;
/**
* @author Sam Brannen
* @since 4.3
*/
@ExtendWith(SpringExtension.class)
class SqlConfigInterfaceTests implements SqlConfigTestInterface {
JdbcTemplate jdbcTemplate;
@Autowired
void setDataSource(DataSource dataSource) {
this.jdbcTemplate = new JdbcTemplate(dataSource);
}
@Test
@Sql(scripts = "/org/springframework/test/context/jdbc/schema.sql", //
config = @SqlConfig(separator = ";"))
@Sql("/org/springframework/test/context/jdbc/data-add-users-with-custom-script-syntax.sql")
void methodLevelScripts() {
assertNumUsers(3);
}
void assertNumUsers(int expected) {
assertThat(countRowsInTable("user")).as("Number of rows in the 'user' table.").isEqualTo(expected);
}
int countRowsInTable(String tableName) {
return JdbcTestUtils.countRowsInTable(this.jdbcTemplate, tableName);
}
}
| apache-2.0 |
imasahiro/armeria | core/src/test/java/com/linecorp/armeria/client/EndpointTest.java | 12327 | /*
* Copyright 2018 LINE Corporation
*
* LINE Corporation 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:
*
* 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.linecorp.armeria.client;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import org.junit.Test;
public class EndpointTest {
@Test
public void parse() {
final Endpoint foo = Endpoint.parse("foo");
assertThat(foo).isEqualTo(Endpoint.of("foo"));
assertThatThrownBy(foo::port).isInstanceOf(IllegalStateException.class);
assertThat(foo.weight()).isEqualTo(1000);
assertThat(foo.ipAddr()).isNull();
final Endpoint bar = Endpoint.parse("bar:80");
assertThat(bar).isEqualTo(Endpoint.of("bar", 80));
assertThat(bar.port()).isEqualTo(80);
assertThat(foo.weight()).isEqualTo(1000);
assertThat(foo.ipAddr()).isNull();
assertThat(Endpoint.parse("group:foo")).isEqualTo(Endpoint.ofGroup("foo"));
}
@Test
public void group() {
final Endpoint foo = Endpoint.ofGroup("foo");
assertThat(foo.isGroup()).isTrue();
assertThat(foo.groupName()).isEqualTo("foo");
assertThat(foo.authority()).isEqualTo("group:foo");
assertThatThrownBy(foo::host).isInstanceOf(IllegalStateException.class);
assertThatThrownBy(foo::ipAddr).isInstanceOf(IllegalStateException.class);
assertThatThrownBy(foo::port).isInstanceOf(IllegalStateException.class);
}
@Test
public void hostWithoutPort() {
final Endpoint foo = Endpoint.of("foo.com");
assertThat(foo.isGroup()).isFalse();
assertThat(foo.host()).isEqualTo("foo.com");
assertThat(foo.ipAddr()).isNull();
assertThat(foo.port(42)).isEqualTo(42);
assertThat(foo.withDefaultPort(42).port()).isEqualTo(42);
assertThat(foo.weight()).isEqualTo(1000);
assertThat(foo.authority()).isEqualTo("foo.com");
assertThat(foo.withIpAddr(null)).isSameAs(foo);
assertThatThrownBy(foo::port).isInstanceOf(IllegalStateException.class);
assertThatThrownBy(foo::groupName).isInstanceOf(IllegalStateException.class);
assertThatThrownBy(() -> foo.withDefaultPort(-1)).isInstanceOf(IllegalArgumentException.class);
}
@Test
public void hostWithPort() {
final Endpoint foo = Endpoint.of("foo.com", 80);
assertThat(foo.isGroup()).isFalse();
assertThat(foo.host()).isEqualTo("foo.com");
assertThat(foo.ipAddr()).isNull();
assertThat(foo.port()).isEqualTo(80);
assertThat(foo.port(42)).isEqualTo(80);
assertThat(foo.withDefaultPort(42)).isSameAs(foo);
assertThat(foo.weight()).isEqualTo(1000);
assertThat(foo.authority()).isEqualTo("foo.com:80");
assertThatThrownBy(foo::groupName).isInstanceOf(IllegalStateException.class);
}
@Test
public void hostWithWeight() {
final Endpoint foo = Endpoint.of("foo.com", 80).withWeight(500);
assertThat(foo.weight()).isEqualTo(500);
assertThat(foo.withWeight(750).weight()).isEqualTo(750);
assertThat(foo.withWeight(500)).isSameAs(foo);
foo.withWeight(0);
assertThatThrownBy(() -> foo.withWeight(-1)).isInstanceOf(IllegalArgumentException.class);
}
@Test
public void hostWithIpAddr() {
final Endpoint foo = Endpoint.of("foo.com").withIpAddr("192.168.0.1");
assertThat(foo.authority()).isEqualTo("foo.com");
assertThat(foo.ipAddr()).isEqualTo("192.168.0.1");
assertThat(foo.withIpAddr(null).ipAddr()).isNull();
assertThat(foo.withIpAddr("::1").authority()).isEqualTo("foo.com");
assertThat(foo.withIpAddr("::1").ipAddr()).isEqualTo("::1");
assertThat(foo.withIpAddr("192.168.0.1")).isSameAs(foo);
assertThat(foo.withIpAddr("192.168.0.2").authority()).isEqualTo("foo.com");
assertThat(foo.withIpAddr("192.168.0.2").ipAddr()).isEqualTo("192.168.0.2");
assertThatThrownBy(() -> foo.withIpAddr("no-ip")).isInstanceOf(IllegalArgumentException.class);
}
@Test
public void badHost() {
// Should not accept the host name followed by a port.
assertThatThrownBy(() -> Endpoint.of("foo:80")).isInstanceOf(IllegalArgumentException.class);
assertThatThrownBy(() -> Endpoint.of("127.0.0.1:80")).isInstanceOf(IllegalArgumentException.class);
assertThatThrownBy(() -> Endpoint.of("[::1]:80")).isInstanceOf(IllegalArgumentException.class);
}
@Test
public void ipV4() {
final Endpoint a = Endpoint.of("192.168.0.1");
assertThat(a.host()).isEqualTo("192.168.0.1");
assertThat(a.ipAddr()).isEqualTo("192.168.0.1");
assertThat(a.authority()).isEqualTo("192.168.0.1");
assertThatThrownBy(() -> a.withIpAddr(null)).isInstanceOf(IllegalStateException.class);
assertThat(a.withIpAddr("192.168.0.1")).isSameAs(a);
assertThat(a.withIpAddr("192.168.0.2")).isEqualTo(Endpoint.of("192.168.0.2"));
assertThat(Endpoint.of("192.168.0.1", 80).authority()).isEqualTo("192.168.0.1:80");
}
@Test
public void ipV4Parse() {
final Endpoint a = Endpoint.parse("192.168.0.1:80");
assertThat(a.host()).isEqualTo("192.168.0.1");
assertThat(a.ipAddr()).isEqualTo("192.168.0.1");
assertThat(a.port()).isEqualTo(80);
assertThat(a.authority()).isEqualTo("192.168.0.1:80");
}
@Test
public void ipV6() {
final Endpoint a = Endpoint.of("::1");
assertThat(a.host()).isEqualTo("::1");
assertThat(a.ipAddr()).isEqualTo("::1");
assertThat(a.authority()).isEqualTo("[::1]");
assertThatThrownBy(() -> a.withIpAddr(null)).isInstanceOf(IllegalStateException.class);
assertThat(a.withIpAddr("::1")).isSameAs(a);
assertThat(a.withIpAddr("::2")).isEqualTo(Endpoint.of("::2"));
assertThat(a.withIpAddr("[::1]")).isSameAs(a);
assertThat(a.withIpAddr("[::2]")).isEqualTo(Endpoint.of("::2"));
final Endpoint b = Endpoint.of("::1", 80);
assertThat(b.host()).isEqualTo("::1");
assertThat(b.ipAddr()).isEqualTo("::1");
assertThat(b.authority()).isEqualTo("[::1]:80");
// Surrounding '[' and ']' should be handled correctly.
final Endpoint c = Endpoint.of("[::1]");
assertThat(c.host()).isEqualTo("::1");
assertThat(c.ipAddr()).isEqualTo("::1");
assertThat(c.authority()).isEqualTo("[::1]");
final Endpoint d = Endpoint.of("[::1]", 80);
assertThat(d.host()).isEqualTo("::1");
assertThat(d.ipAddr()).isEqualTo("::1");
assertThat(d.authority()).isEqualTo("[::1]:80");
// withIpAddr() should handle surrounding '[' and ']' correctly.
final Endpoint e = Endpoint.of("foo").withIpAddr("[::1]");
assertThat(e.host()).isEqualTo("foo");
assertThat(e.ipAddr()).isEqualTo("::1");
}
@Test
public void ipV6Parse() {
final Endpoint a = Endpoint.parse("[::1]:80");
assertThat(a.host()).isEqualTo("::1");
assertThat(a.ipAddr()).isEqualTo("::1");
assertThat(a.port()).isEqualTo(80);
assertThat(a.authority()).isEqualTo("[::1]:80");
}
@Test
public void authorityCache() {
final Endpoint foo = Endpoint.of("foo.com", 80);
final String authority1 = foo.authority();
final String authority2 = foo.authority();
assertThat(authority1).isSameAs(authority2);
}
@Test
public void equals() {
final Endpoint a1 = Endpoint.of("a");
final Endpoint a2 = Endpoint.of("a");
final Endpoint groupA1 = Endpoint.ofGroup("a");
final Endpoint groupA2 = Endpoint.ofGroup("a");
assertThat(a1).isNotEqualTo(new Object());
assertThat(a1).isNotEqualTo(groupA1);
assertThat(groupA1).isNotEqualTo(a1);
assertThat(a1).isEqualTo(a1);
assertThat(a1).isEqualTo(a2);
assertThat(groupA1).isEqualTo(groupA1);
assertThat(groupA1).isEqualTo(groupA2);
}
@Test
public void portEquals() {
final Endpoint a = Endpoint.of("a");
final Endpoint b = Endpoint.of("a", 80);
final Endpoint c = Endpoint.of("a", 80);
final Endpoint d = Endpoint.of("a", 81);
final Endpoint e = Endpoint.of("a", 80).withIpAddr("::1");
final Endpoint f = Endpoint.of("a", 80).withWeight(500); // Weight not part of comparison
final Endpoint g = Endpoint.of("g", 80);
assertThat(a).isNotEqualTo(b);
assertThat(b).isEqualTo(c);
assertThat(b).isNotEqualTo(d);
assertThat(b).isNotEqualTo(e);
assertThat(b).isEqualTo(f);
assertThat(b).isNotEqualTo(g);
}
@Test
public void ipAddrEquals() {
final Endpoint a = Endpoint.of("a");
final Endpoint b = Endpoint.of("a").withIpAddr("::1");
final Endpoint c = Endpoint.of("a").withIpAddr("::1");
final Endpoint d = Endpoint.of("a").withIpAddr("::2");
final Endpoint e = Endpoint.of("a", 80).withIpAddr("::1");
final Endpoint f = Endpoint.of("a").withIpAddr("::1").withWeight(500); // Weight not part of comparison
final Endpoint g = Endpoint.of("g").withIpAddr("::1");
assertThat(a).isNotEqualTo(b);
assertThat(b).isEqualTo(c);
assertThat(b).isNotEqualTo(d);
assertThat(b).isNotEqualTo(e);
assertThat(b).isEqualTo(f);
assertThat(b).isNotEqualTo(g);
}
@Test
public void testHashCode() {
assertThat(Endpoint.of("a").hashCode()).isNotZero();
assertThat(Endpoint.of("a", 80).hashCode()).isNotZero();
assertThat(Endpoint.of("a").withIpAddr("::1").hashCode()).isNotZero();
assertThat(Endpoint.of("a", 80).withIpAddr("::1").hashCode()).isNotZero();
assertThat(Endpoint.ofGroup("a").hashCode()).isNotZero();
// Weight is not part of comparison.
final int hash = Endpoint.of("a", 80).withWeight(500).hashCode();
assertThat(Endpoint.of("a", 80).withWeight(750).hashCode()).isEqualTo(hash);
}
@Test
public void testToString() {
assertThat(Endpoint.of("a").toString()).isNotNull();
assertThat(Endpoint.of("a", 80).toString()).isNotNull();
assertThat(Endpoint.of("a").withIpAddr("::1").toString()).isNotNull();
}
@Test
public void comparison() {
assertThat(Endpoint.ofGroup("a")).isEqualByComparingTo(Endpoint.ofGroup("a"));
assertThat(Endpoint.ofGroup("a")).isLessThan(Endpoint.ofGroup("b"));
assertThat(Endpoint.ofGroup("a")).isLessThan(Endpoint.of("a"));
assertThat(Endpoint.of("a")).isEqualByComparingTo(Endpoint.of("a"));
assertThat(Endpoint.of("a")).isLessThan(Endpoint.of("b"));
assertThat(Endpoint.of("a")).isLessThan(Endpoint.of("a", 8080));
assertThat(Endpoint.of("a")).isLessThan(Endpoint.of("a").withIpAddr("1.1.1.1"));
assertThat(Endpoint.of("a")).isGreaterThan(Endpoint.ofGroup("a"));
assertThat(Endpoint.of("a", 8080)).isEqualByComparingTo(Endpoint.of("a", 8080));
assertThat(Endpoint.of("a", 8080)).isGreaterThan(Endpoint.of("a"));
assertThat(Endpoint.of("a", 8080)).isLessThan(Endpoint.of("a", 8081));
assertThat(Endpoint.of("a").withIpAddr("1.1.1.1"))
.isEqualByComparingTo(Endpoint.of("a").withIpAddr("1.1.1.1"));
assertThat(Endpoint.of("a").withIpAddr("1.1.1.1")).isGreaterThan(Endpoint.of("a"));
assertThat(Endpoint.of("a").withIpAddr("1.1.1.1"))
.isLessThan(Endpoint.of("a").withIpAddr("1.1.1.2"));
// Weight is not part of comparison.
assertThat(Endpoint.of("a").withWeight(1)).isEqualByComparingTo(Endpoint.of("a").withWeight(2));
}
}
| apache-2.0 |
racker/cassandra-syncer | node_modules/nodelint/lib/reporters/textmate_full.js | 2694 | /*
* Nodelint Textmate full HTML reporter
*
* Outputs to a TextMate HTML window printing JSLint results.
*
* The Command:
* . "$TM_SUPPORT_PATH/lib/webpreview.sh"
* html_header "JSLint Results"
* node "/path/to/nodelint/nodelint" "$TM_FILEPATH" \
* --config "$TM_BUNDLE_SUPPORT/bin/path/to/config.js" \
* --reporter "$TM_BUNDLE_SUPPORT/bin/path/to/full_reporter.js"
*
* Invoked by "⌃⇧V"
* @author Matthew Kitt
*
* For setup instructions see: https://github.com/tav/nodelint/wiki/Editor-and-IDE-integration
*
* Released into the Public Domain by tav <tav@espians.com>
* See the README.md for full credits of the awesome contributors!
*/
/**
* Module dependencies
*/
var util = require('util');
/**
* Reporter info string
*/
exports.info = "Textmate full HTML reporter";
/**
* Report linting results to the command-line.
*
* @api public
*
* @param {Array} results
*/
exports.report = function report(results) {
var error_regexp = /^\s*(\S*(\s+\S+)*)\s*$/,
i,
len = results.length,
output = '',
html = '',
file,
error,
reason,
line,
character;
for (i = 0; i < len; i += 1) {
file = results[i].file;
error = results[i].error;
reason = error.reason;
line = error.line;
character = error.character;
output += '<li>' +
'<a href="txmt://open?url=file://' + file + '&line=' +
line + '&column=' + character + '">' +
'<strong>' + reason + '</strong>' +
' <em>line ' + line +
', character ' + character + '</em>' +
'</a>' +
'<pre><code>' +
(error.evidence || '').replace(error_regexp, "$1") +
'</pre></code>' +
'</li>';
}
html += '<html>' +
'<head>' +
'<style type="text/css">' +
'body {font-size: 14px;}' +
'pre { background-color: #eee; color: #400; margin: 3px 0;}' +
'h1, h2 { font-family:"Arial, Helvetica"; margin: 0 0 5px; }' +
'h1 { font-size: 20px; }' +
'h2 { font-size: 16px;}' +
'a { font-family:"Arial, Helvetica";}' +
'ul { margin: 10px 0 0 20px; padding: 0; list-style: none;}' +
'li { margin: 0 0 10px; }' +
'</style>' +
'</head>' +
'<body>' +
'<h1>' + len + ' Error' + ((len === 1) ? '' : 's') + '</h1>' +
'<hr/>' +
'<ul>' +
output +
'</ul>' +
'</body>' +
'</html>';
util.puts(html);
};
| apache-2.0 |
JDoIt/jreaper | jreaper-view/src/main/webapp/resources/js/app/custom.js | 3478 |
// niceScroll
jQuery("html").niceScroll({
scrollspeed: 50,
mousescrollstep: 38,
cursorwidth: 7,
cursorborder: 0,
cursorcolor: '#f99200',
autohidemode: false,
zindex: 9999999,
horizrailenabled: false,
cursorborderradius: 0
});
//sticky header on scroll
$(window).load(function() {
$(".sticky").sticky({topSpacing: 0});
$(".sticky100").sticky({topSpacing: 100});
});
/*========tooltip and popovers====*/
/*==========================*/
$("[data-toggle=popover]").popover();
$("[data-toggle=tooltip]").tooltip();
/*==========search=============*/
//var searchForm = document.getElementById("search-form");
//document.getElementById("search-link").addEventListener("click", function () {
// searchForm.submit();
//});
//$(".search-ajax").keypress(function(event) {
//
// if (event.keyCode == 13) {
//
// doSearch();
// }
//});
//
//function doSearch(){
//
// var searchQ = $("#search").val();
// alert('Entered ' + searchQ);
//
//}
/*=========================*/
//parallax
//$(window).stellar({
// horizontalScrolling: false,
// responsive: true/*,
// scrollProperty: 'scroll',
// parallaxElements: false,
// horizontalScrolling: false,
// horizontalOffset: 0,
// verticalOffset: 0*/
//});
/*====flex slider for main slider on header2====*/
//$('.main-slider').flexslider({
// slideshowSpeed: 5000,
// directionNav: false,
// controlNav: true,
// animation: "fade"
//});
//owl carousel for work
//$(document).ready(function() {
// $("#work-carousel").owlCarousel({
// // Most important owl features
// items: 4,
// itemsCustom: false,
// itemsDesktop: [1199, 4],
// itemsDesktopSmall: [980, 3],
// itemsTablet: [768, 3],
// itemsTabletSmall: false,
// itemsMobile: [479, 1],
// singleItem: false,
// startDragging: true
// });
//
//});
//owl carousel for testimonials
//$(document).ready(function() {
//
// $("#testi-carousel").owlCarousel({
// // Most important owl features
// items: 1,
// itemsCustom: false,
// itemsDesktop: [1199, 1],
// itemsDesktopSmall: [980, 1],
// itemsTablet: [768, 1],
// itemsTabletSmall: false,
// itemsMobile: [479, 1],
// singleItem: false,
// startDragging: true
// });
//
//});
//owl carousel for full width image slider
//$(document).ready(function() {
//
// $("#full-img-slide").owlCarousel({
// // Most important owl features
// items: 1,
// itemsCustom: false,
// itemsDesktop: [1199, 1],
// itemsDesktopSmall: [980, 1],
// itemsTablet: [768, 1],
// itemsTabletSmall: false,
// itemsMobile: [479, 1],
// singleItem: false,
// startDragging: true
// });
//
//});
/* ==============================================
Counter Up
=============================================== */
//jQuery(document).ready(function($) {
// $('.counter').counterUp({
// delay: 100,
// time: 900
// });
//});
/* ==============================================
WOW plugin triggers animate.css on scroll
=============================================== */
//
//var wow = new WOW(
// {
// boxClass: 'wow', // animated element css class (default is wow)
// animateClass: 'animated', // animation css class (default is animated)
// offset: 100, // distance to the element when triggering the animation (default is 0)
// mobile: false // trigger animations on mobile devices (true is default)
// }
//);
//wow.init();
//portfolio mix
//$('#grid').mixitup(); | apache-2.0 |
rbattenfeld/dmr-statistics | src/main/java/org/jrbsoft/statistic/protocol/jmx/model/MBeanModelUpdater.java | 5698 | package org.jrbsoft.statistic.protocol.jmx.model;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import javax.management.Attribute;
import javax.management.AttributeChangeNotification;
import javax.management.AttributeList;
import javax.management.AttributeNotFoundException;
import javax.management.InstanceNotFoundException;
import javax.management.MBeanException;
import javax.management.MBeanServer;
import javax.management.MalformedObjectNameException;
import javax.management.Notification;
import javax.management.NotificationBroadcaster;
import javax.management.NotificationFilter;
import javax.management.NotificationListener;
import javax.management.ObjectName;
import javax.management.ReflectionException;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.jrbsoft.statistic.model.AbstractElement;
import org.jrbsoft.statistic.model.IModelUpdater;
import org.jrbsoft.statistic.model.IProtocolModel;
import org.jrbsoft.statistic.model.IRootModel;
public class MBeanModelUpdater implements IModelUpdater {
private static final Log _Logger = LogFactory.getLog(MBeanModelUpdater.class);
private final MBeanServer _mbeanServer;
private final List<MBeanModel> _models = new ArrayList<MBeanModel>();
private final AttributeChangeListener _attrChangeListener = new AttributeChangeListener();
private final AttributeChangeFilter _attrChangeFilter = new AttributeChangeFilter();
public MBeanModelUpdater(final MBeanServer mbeanServer) {
_mbeanServer = mbeanServer;
}
@Override
public void updateModel(final IRootModel model) throws IOException {
updateModels(model.getModels());
}
public void updateModels(final List<IProtocolModel> models) throws IOException {
if (models != null) {
for (final IProtocolModel protocolModel : models) {
if (protocolModel instanceof MBeanModel) {
update((MBeanModel)protocolModel);
}
}
}
}
public void updateMBeanModels(final List<MBeanModel> models) throws IOException {
if (models != null) {
for (final MBeanModel model : models) {
update(model);
}
}
}
//-----------------------------------------------------------------------||
//-- Private Methods ----------------------------------------------------||
//-----------------------------------------------------------------------||
private void update(final MBeanModel model) {
try {
if (!_models.contains(model)) {
final ObjectName mbean = getObjectName(model);
if (_mbeanServer.isRegistered(mbean)) {
for (final MBeanElement element : model.getMBeanElements()) {
updateStatistics(mbean, element.getKeys(), element);
}
// if (mbean instanceof NotificationBroadcaster) { TODO not notification at the moment, the model is not thread safe designed by purpose
// _models.add(model);
// register(mbean);
// }
} else {
_Logger.warn("Not registered: " + model.getObjectName());
}
}
} catch (MalformedObjectNameException | AttributeNotFoundException | InstanceNotFoundException | MBeanException | ReflectionException ex) {
_Logger.debug("Error by extracting mbean value. Reason: " + ex.getMessage());
}
}
private void updateStatistics(final ObjectName mbean, final String[] keys, final AbstractElement element) throws AttributeNotFoundException, InstanceNotFoundException, MBeanException, ReflectionException {
if (keys != null) {
final AttributeList values = _mbeanServer.getAttributes(mbean, keys);
for (Attribute attr : values.asList()) {
element.addStatistics(attr.getName(), attr.getValue());
}
}
}
private ObjectName getObjectName(final MBeanModel model) throws MalformedObjectNameException {
if (model.getMBeanObjectName() == null) {
model.setMBeanObjectName(new ObjectName(model.getObjectName()));
}
return model.getMBeanObjectName();
}
private void register(final ObjectName mbean) throws InstanceNotFoundException {
_mbeanServer.addNotificationListener(mbean, _attrChangeListener, _attrChangeFilter, null);
}
//-----------------------------------------------------------------------||
//--Private Classes -----------------------------------------------------||
//-----------------------------------------------------------------------||
private class AttributeChangeFilter implements NotificationFilter {
private static final long serialVersionUID = 1L;
public boolean isNotificationEnabled(final Notification notification) {
if (notification instanceof AttributeChangeNotification) {
return true;
} else {
return false;
}
}
}
private class AttributeChangeListener implements NotificationListener {
public void handleNotification(final Notification notification, final Object handback) {
if (notification instanceof AttributeChangeNotification) {
final AttributeChangeNotification changeNotification = (AttributeChangeNotification) notification;
for (final MBeanModel model : _models) {
model.updateNotification(changeNotification.getAttributeName(), changeNotification.getNewValue());
}
}
}
}
}
| apache-2.0 |
rabidgremlin/legal-beagle | src/main/java/com/rabidgremlin/legalbeagle/maven/MavenJarIdentifier.java | 3299 | /*
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.rabidgremlin.legalbeagle.maven;
import java.io.File;
import java.io.FileInputStream;
import java.util.List;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.rabidgremlin.legalbeagle.report.Report;
import com.rabidgremlin.legalbeagle.report.ReportItem;
import com.rabidgremlin.legalbeagle.report.ReportItemStatus;
import com.rabidgremlin.legalbeagle.util.HttpHelper;
import com.rabidgremlin.legalbeagle.xmlbindings.License;
import com.rabidgremlin.legalbeagle.xmlbindings.Model;
import com.rabidgremlin.legalbeagle.xmlbindings.Model.Licenses;
public class MavenJarIdentifier
{
private final Logger log = LoggerFactory.getLogger(MavenJarIdentifier.class);
private HttpHelper httpHelper;
public MavenJarIdentifier(HttpHelper httpHelper)
{
this.httpHelper = httpHelper;
}
private List<License> getLicense(HttpHelper httpHelper, Model pom) throws Exception
{
if (pom == null)
{
return null;
}
Licenses licenses = pom.getLicenses();
if (licenses != null)
{
return licenses.getLicense();
}
if (pom.getParent() != null)
{
return getLicense(httpHelper, httpHelper.getPom(new MavenArtifact(pom.getParent().getGroupId(), pom.getParent()
.getArtifactId(), pom.getParent().getVersion())));
}
return null;
}
public void identifyFiles(Report report) throws Exception
{
for (ReportItem reportItem : report.getReportItems())
{
File f = reportItem.getFile();
String fileHash = DigestUtils.sha1Hex(new FileInputStream(f));
try
{
log.info("Processing {}...", f.getAbsoluteFile());
Model mod = httpHelper.getPom(fileHash);
if (mod != null)
{
reportItem.setReportItemStatus(ReportItemStatus.IDENTIFIED);
reportItem.setDescription(mod.getName());
List<License> licenses = getLicense(httpHelper, mod);
if (licenses != null)
{
for (License license : licenses)
{
// some names have spaces and CR or LF in them
String licenseStr = license.getName().trim();
licenseStr = StringUtils.strip(licenseStr, "\n\r");
reportItem.addLicense(licenseStr);
}
}
else
{
reportItem.setReportItemStatus(ReportItemStatus.NO_LICENSE_FOUND);
}
}
else
{
reportItem.setReportItemStatus(ReportItemStatus.NOT_IDENTIFIED);
}
}
catch (Exception e)
{
reportItem.setReportItemStatus(ReportItemStatus.ERR);
reportItem.setError(e.getMessage());
}
}
}
}
| apache-2.0 |
ConsecroMUD/ConsecroMUD | com/suscipio_solutions/consecro_mud/Abilities/Prayers/Prayer_Monolith.java | 11008 | package com.suscipio_solutions.consecro_mud.Abilities.Prayers;
import java.util.Vector;
import com.suscipio_solutions.consecro_mud.Abilities.interfaces.Ability;
import com.suscipio_solutions.consecro_mud.Common.interfaces.CMMsg;
import com.suscipio_solutions.consecro_mud.Common.interfaces.PhyStats;
import com.suscipio_solutions.consecro_mud.Items.interfaces.Item;
import com.suscipio_solutions.consecro_mud.Items.interfaces.RawMaterial;
import com.suscipio_solutions.consecro_mud.Items.interfaces.Weapon;
import com.suscipio_solutions.consecro_mud.Items.interfaces.Wearable;
import com.suscipio_solutions.consecro_mud.Locales.interfaces.Room;
import com.suscipio_solutions.consecro_mud.MOBS.interfaces.MOB;
import com.suscipio_solutions.consecro_mud.core.CMClass;
import com.suscipio_solutions.consecro_mud.core.CMLib;
import com.suscipio_solutions.consecro_mud.core.interfaces.Environmental;
import com.suscipio_solutions.consecro_mud.core.interfaces.Physical;
import com.suscipio_solutions.consecro_mud.core.interfaces.Tickable;
@SuppressWarnings("rawtypes")
public class Prayer_Monolith extends Prayer
{
@Override public String ID() { return "Prayer_Monolith"; }
private final static String localizedName = CMLib.lang().L("Monolith");
@Override public String name() { return localizedName; }
private final static String localizedStaticDisplay = CMLib.lang().L("(Monolith)");
@Override public String displayText() { return localizedStaticDisplay; }
@Override public int maxRange(){return adjustedMaxInvokerRange(10);}
@Override public int minRange(){return 1;}
@Override public int classificationCode(){return Ability.ACODE_PRAYER|Ability.DOMAIN_CREATION;}
@Override public int abstractQuality(){ return Ability.QUALITY_OK_SELF;}
@Override protected int canAffectCode(){return CAN_ITEMS;}
@Override protected int canTargetCode(){return 0;}
@Override public long flags(){return Ability.FLAG_HOLY|Ability.FLAG_UNHOLY;}
private final static int TYP_ICE=0;
private final static int TYP_FIRE=1;
private final static int TYP_EARTH=2;
private final static int TYP_AIR=3;
protected int wallType=0;
protected int amountRemaining=0;
protected Item theWall=null;
@Override
public boolean okMessage(final Environmental myHost, final CMMsg msg)
{
if((affected==null)||(!(affected instanceof Item)))
return true;
final MOB mob=msg.source();
switch(wallType)
{
case TYP_ICE:
if((invoker!=null)
&&(mob.isInCombat())
&&(mob.getVictim()==invoker)
&&(mob.rangeToTarget()==1))
{
if(msg.sourceMinor()==CMMsg.TYP_ADVANCE)
{
Item w=mob.fetchWieldedItem();
if(w==null) w=mob.myNaturalWeapon();
if(w==null) return false;
final Room room=mob.location();
final CMMsg msg2=CMClass.getMsg(mob,null,CMMsg.MSG_WEAPONATTACK,L("^F^<FIGHT^><S-NAME> hack(s) at the monolith of ice with @x1.^</FIGHT^>^?",w.name()));
CMLib.color().fixSourceFightColor(msg2);
if(room.okMessage(mob,msg2))
{
room.send(mob,msg2);
amountRemaining-=mob.phyStats().damage();
if(amountRemaining<0)
{
for(int i=0;i<room.numInhabitants();i++)
{
final MOB M=room.fetchInhabitant(i);
if((M.isInCombat())
&&(M.getVictim()==invoker)
&&(M.rangeToTarget()>0)
&&(M.rangeToTarget()<3)
&&(!M.amDead()))
CMLib.combat().postDamage(invoker,M,this,CMLib.dice().roll(M.phyStats().level()/2,4,0),CMMsg.MASK_ALWAYS|CMMsg.MASK_MALICIOUS|CMMsg.TYP_COLD,Weapon.TYPE_PIERCING,"A shard of ice <DAMAGE> <T-NAME>!");
}
mob.location().showHappens(CMMsg.MSG_OK_ACTION,L("The monolith of ice shatters!!!"));
((Item)affected).destroy();
}
}
return false;
}
}
break;
case TYP_FIRE:
break;
case TYP_AIR:
if((invoker!=null)
&&(mob.isInCombat())
&&(mob.getVictim()==invoker)
&&(mob.rangeToTarget()>=1)
&&(msg.amITarget(invoker))
&&(msg.targetMinor()==CMMsg.TYP_WEAPONATTACK)
&&(msg.tool()!=null)
&&(msg.tool() instanceof Weapon)
&&(!((Weapon)msg.tool()).amWearingAt(Wearable.IN_INVENTORY))
&&(((Weapon)msg.tool()).weaponClassification()==Weapon.CLASS_RANGED))
{
mob.location().show(mob,invoker,CMMsg.MSG_OK_VISUAL,L("<S-NAME> fire(s) @x1 at <T-NAME>. The missile enters the monolith of air.",msg.tool().name()));
final MOB M=CMClass.getFactoryMOB();
M.setLocation(mob.location());
M.setName(L("The monolith of air"));
M.setVictim(mob);
M.setAtRange(mob.rangeToTarget());
CMLib.combat().postWeaponDamage(M,mob,(Weapon)msg.tool(),true);
M.setLocation(null);
M.setVictim(null);
if(mob.isMonster())
CMLib.commands().postRemove(mob,(Weapon)msg.tool(),true);
M.destroy();
return false;
}
break;
case TYP_EARTH:
if((invoker!=null)
&&(mob.isInCombat())
&&(mob.getVictim()==invoker)
&&(mob.rangeToTarget()==1))
{
if(msg.sourceMinor()==CMMsg.TYP_ADVANCE)
{
Item w=mob.fetchWieldedItem();
if(w==null) w=mob.myNaturalWeapon();
if(w==null) return false;
if(mob.location().show(mob,null,w,CMMsg.MSG_WEAPONATTACK,L("^F^<FIGHT^><S-NAME> hack(s) at the monolith of stone with <O-NAME>.^</FIGHT^>^?")))
{
amountRemaining-=mob.phyStats().damage();
if(amountRemaining<0)
{
mob.location().showHappens(CMMsg.MSG_OK_ACTION,L("The monolith of stone is destroyed!"));
((Item)affected).destroy();
}
}
return false;
}
}
break;
}
return super.okMessage(myHost,msg);
}
@Override
public void unInvoke()
{
super.unInvoke();
if(canBeUninvoked())
{
if((theWall!=null)
&&(invoker!=null)
&&(theWall.owner()!=null)
&&(theWall.owner() instanceof Room)
&&(((Room)theWall.owner()).isContent(theWall)))
{
MOB actorM=invoker; if(actorM==null) actorM=CMLib.map().deity();
switch(wallType)
{
case TYP_FIRE:
((Room)theWall.owner()).show(actorM,null,CMMsg.MSG_OK_VISUAL,L("The monolith of fire fades."));
break;
case TYP_AIR:
((Room)theWall.owner()).show(actorM,null,CMMsg.MSG_OK_VISUAL,L("The monolith of air dissipates."));
break;
case TYP_ICE:
((Room)theWall.owner()).show(actorM,null,CMMsg.MSG_OK_VISUAL,L("The monolith of ice melts."));
break;
case TYP_EARTH:
((Room)theWall.owner()).show(actorM,null,CMMsg.MSG_OK_VISUAL,L("The monolith of stone crumbles."));
break;
}
final Item wall=theWall;
theWall=null;
wall.destroy();
}
}
}
@Override
public boolean tick(Tickable ticking, int tickID)
{
if(tickID==Tickable.TICKID_MOB)
{
switch(wallType)
{
case TYP_ICE:
case TYP_EARTH:
case TYP_AIR:
if((invoker!=null)
&&(theWall!=null)
&&(invoker.location()!=null)
&&(!invoker.location().isContent(theWall)))
unInvoke();
break;
case TYP_FIRE:
if((invoker!=null)
&&(theWall!=null)
&&(invoker.location()!=null))
{
final Room room=invoker.location();
if(!invoker.location().isContent(theWall))
unInvoke();
else
for(int m=0;m<room.numInhabitants();m++)
{
final MOB mob=room.fetchInhabitant(m);
if((mob!=null)
&&(mob!=invoker)
&&(mob.isInCombat())
&&(mob.getVictim()==invoker)
&&(mob.rangeToTarget()==1))
{
final int damage = CMLib.dice().roll((int)Math.round((adjustedLevel(invoker,0)+(2.0*super.getX1Level(invoker())))/4.0),6,1);
CMLib.combat().postDamage(invoker,mob,this,damage,CMMsg.MASK_MALICIOUS|CMMsg.MASK_ALWAYS|CMMsg.TYP_FIRE,Weapon.TYPE_BURNING,"The monolith of fire flares and <DAMAGE> <T-NAME>!");
}
}
}
break;
}
}
return super.tick(ticking,tickID);
}
@Override
public boolean invoke(MOB mob, Vector commands, Physical givenTarget, boolean auto, int asLevel)
{
if((!mob.isInCombat())||(mob.rangeToTarget()<1))
{
mob.tell(L("You really should be in ranged combat to cast this."));
return false;
}
for(int i=0;i<mob.location().numItems();i++)
{
final Item I=mob.location().getItem(i);
if((I!=null)&&(I.fetchEffect(ID())!=null))
{
mob.tell(L("There is already a monolith here."));
return false;
}
}
// the invoke method for spells receives as
// parameters the invoker, and the REMAINING
// command line parameters, divided into words,
// and added as String objects to a vector.
if(!super.invoke(mob,commands,givenTarget,auto,asLevel))
return false;
final Physical target = mob.location();
final boolean success=proficiencyCheck(mob,0,auto);
if(success)
{
// it worked, so build a copy of this ability,
// and add it to the affects list of the
// affected MOB. Then tell everyone else
// what happened.
wallType=CMLib.dice().roll(1,4,-1);
final String text=text().toUpperCase().trim();
if((text.indexOf("STONE")>=0)||(text.indexOf("EARTH")>=0))
wallType=TYP_EARTH;
else
if((text.indexOf("ICE")>=0)||(text.indexOf("WATER")>=0))
wallType=TYP_ICE;
else
if(text.indexOf("AIR")>=0)
wallType=TYP_AIR;
else
if(text.indexOf("FIRE")>=0)
wallType=TYP_FIRE;
Item I=null;
switch(wallType)
{
case TYP_EARTH:
amountRemaining=mob.baseState().getHitPoints()/6;
I=CMClass.getItem("GenItem");
I.setName(L("a monolith of stone"));
I.setDisplayText(L("a monolith of stone has been erected here"));
I.setDescription(L("The bricks are sold and sturdy."));
I.setMaterial(RawMaterial.RESOURCE_STONE);
break;
case TYP_ICE:
amountRemaining=20;
I=CMClass.getItem("GenItem");
I.setName(L("a monolith of ice"));
I.setDisplayText(L("a monolith of ice has been erected here"));
I.setDescription(L("The ice is crystal clear."));
I.setMaterial(RawMaterial.RESOURCE_GLASS);
break;
case TYP_AIR:
I=CMClass.getItem("GenItem");
I.setName(L("a monolith of air"));
I.setDisplayText("");
I.setDescription(L("The air is swirling dangerously."));
I.setMaterial(RawMaterial.RESOURCE_NOTHING);
break;
case TYP_FIRE:
I=CMClass.getItem("GenItem");
I.setName(L("a monolith of fire"));
I.setDisplayText(L("a monolith of fire is burning here"));
I.setDescription(L("The flames are high and hot."));
I.setMaterial(RawMaterial.RESOURCE_NOTHING);
I.basePhyStats().setDisposition(I.basePhyStats().disposition()|PhyStats.IS_LIGHTSOURCE);
break;
}
if(I!=null)
{
final CMMsg msg = CMClass.getMsg(mob,target,this,verbalCastCode(mob,target,auto),auto?L("@x1 appears!",I.name()):L("^S<S-NAME> @x1 to construct @x2!^?",prayForWord(mob),I.name()));
if(mob.location().okMessage(mob,msg))
{
mob.location().send(mob,msg);
CMLib.flags().setGettable(I,false);
I.recoverPhyStats();
mob.location().addItem(I);
theWall=I;
beneficialAffect(mob,I,asLevel,0);
}
}
}
else
return beneficialWordsFizzle(mob,null,L("<S-NAME> @x1, but nothing happens.",prayWord(mob)));
// return whether it worked
return success;
}
}
| apache-2.0 |
blazsolar/rondel | api/src/main/java/solar/blaz/rondel/ServiceScope.java | 846 | /*
* Copyright 2016 Blaž Šolar
*
* 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 solar.blaz.rondel;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import javax.inject.Scope;
@Scope @Retention(RetentionPolicy.RUNTIME)
public @interface ServiceScope {
}
| apache-2.0 |
mkurdziel/BitHome-Hub-CSharp-V1 | SyNet Controller/GuiControls/ResizingCanvas.cs | 6108 | using System;
using System.Collections.Generic;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Media;
using SyNet.GuiHelpers;
namespace SyNet.GuiControls
{
/// <summary>
/// Derives from Canvas and provides designing functionality
/// </summary>
public partial class ResizingCanvas : Canvas
{
//private IGuiMovable m_movableParent;
private List<double> m_horizontalGuides = new List<double>();
private List<double> m_verticalGuides = new List<double>();
#region Public Properties
public List<double> HorizontalGuides
{
get
{
return m_horizontalGuides;
}
set
{
m_horizontalGuides = value;
}
}
public List<double> VerticalGuides
{
get
{
return m_verticalGuides;
}
set
{
m_verticalGuides = value;
}
}
/// <summary>
/// Gets the maximum movement space that can occur on the left
/// </summary>
public double SpaceOnLeft
{
get
{
//if (m_movableParent != null)
//{
// return m_movableParent.PositionLeft;
//}
return 0;
}
}
/// <summary>
/// Gets the maximum movement space that can occur on the right
/// </summary>
public double SpaceOnTop
{
get
{
//if (m_movableParent != null)
//{
// return m_movableParent.PositionTop;
//}
return 0;
}
}
#endregion
#region Constructors
/// <summary>
/// Default constructor
/// </summary>
public ResizingCanvas()
{
this.Loaded += ResizingCanvas_Loaded;
}
/// <summary>
/// Loaded event handler
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void ResizingCanvas_Loaded( object sender, RoutedEventArgs e )
{
//m_movableParent = Utilities.FindAncestor(typeof(IGuiMovable), this) as IGuiMovable;
}
#endregion
#region Overrides
/// <summary>
/// MeasureOverride override. Used to grow canvas when child objects
/// get too close to the edges
/// </summary>
/// <param name="constraint"></param>
/// <returns></returns>
protected override Size MeasureOverride( Size constraint )
{
Size size = new Size();
double leftMost = double.NaN;
double topMost = double.NaN;
double rightMost = double.NaN;
double bottomMost = double.NaN;
foreach (UIElement element in this.InternalChildren)
{
double left = Canvas.GetLeft(element);
double top = Canvas.GetTop(element);
left = double.IsNaN(left) ? 0 : left;
top = double.IsNaN(top) ? 0 : top;
if (leftMost > left || double.IsNaN(leftMost))
{
leftMost = left;
}
if (topMost > top || double.IsNaN(topMost))
{
topMost = top;
}
//measure desired size for each child
element.Measure(constraint);
Size desiredSize = element.DesiredSize;
if (!double.IsNaN(desiredSize.Width) && !double.IsNaN(desiredSize.Height))
{
size.Width = Math.Max(size.Width, left + desiredSize.Width);
size.Height = Math.Max(size.Height, top + desiredSize.Height);
}
}
//
// If the leftmost or topmost is off the left or topside of the canvas,
// then adjust appropriatly
//
//if ((leftMost < 0 || topMost < 0) && m_movableParent != null)
//{
// double left = (leftMost < 0) ? (0 - leftMost) : 0;
// double top = (topMost < 0) ? (0 - topMost) : 0;
// //
// // Make sure that the parent doesn't go out of bounds of its own parent
// //
// //if (movableParent.PositionLeft < left)
// //{
// // left = movableParent.PositionLeft;
// //}
// //if (movableParent.PositionTop < top)
// //{
// // top = movableParent.PositionTop;
// //}
// //
// // Move the parent left and up by the difference
// //
// m_movableParent.PositionLeft -= left;
// m_movableParent.PositionTop -= top;
// //
// // Move each item left by the difference
// //
// foreach (UIElement element in this.InternalChildren)
// {
// Canvas.SetLeft(element, Canvas.GetLeft(element) + left);
// Canvas.SetTop(element, Canvas.GetTop(element) + top);
// }
// //
// // Expand the parent by the difference
// size.Width += left;
// size.Height += top;
//}
//if ((leftMost > 0 || topMost > 0) && m_movableParent != null)
//{
// double left = leftMost - 0;
// double top = topMost - 0;
// //
// // Move each item left by the difference
// //
// foreach (UIElement element in this.InternalChildren)
// {
// Canvas.SetLeft(element, Canvas.GetLeft(element) - left);
// Canvas.SetTop(element, Canvas.GetTop(element) - top);
// }
// //
// // Move the parent right by the difference
// //
// m_movableParent.PositionLeft += left;
// m_movableParent.PositionTop += top;
//}
return size;
}
protected override void OnRender( System.Windows.Media.DrawingContext dc )
{
base.OnRender(dc);
foreach (double y in m_horizontalGuides)
{
Pen guide = new Pen(new SolidColorBrush(Colors.Blue), 1);
dc.DrawLine(guide, new Point(0, y), new Point(this.ActualWidth, y));
}
foreach (double x in m_verticalGuides)
{
Pen guide = new Pen(new SolidColorBrush(Colors.Green), 1);
dc.DrawLine(guide, new Point(x, 0), new Point(x, this.ActualHeight));
}
}
#endregion
}
} | apache-2.0 |
jyonger/Job | app/src/main/java/com/yong/job/three/MyProvider.java | 3626 | package com.yong.job.three;
import android.content.ContentProvider;
import android.content.ContentValues;
import android.content.UriMatcher;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.net.Uri;
/**
* Created by jyong on 2016/3/29.
*/
public class MyProvider extends ContentProvider {
private static final int BOOK_DIR = 0;
private static final int BOOK_ITEM = 1;
private static UriMatcher uriMatcher;
private MyHelper helper;
static {
uriMatcher = new UriMatcher(UriMatcher.NO_MATCH);
uriMatcher.addURI("com.yong.job.provider", "book", BOOK_DIR);
uriMatcher.addURI("com.yong.job.provider", "book/#", BOOK_ITEM);
}
@Override
public String getType(Uri uri) {
switch (uriMatcher.match(uri)) {
case BOOK_DIR:
return "vnd.android.cursor.dir/vnd.com.yong.job.provider.book";
case BOOK_ITEM:
return "vnd.android.cursor.item/vnd.com.yong.job.provider.book";
default:
break;
}
return null;
}
@Override
public boolean onCreate() {
helper = new MyHelper(getContext(), "job.db", null, 1);
return false;
}
@Override
public Cursor query(Uri uri, String[] projection, String selection, String[] selectionArgs, String sortOrder) {
SQLiteDatabase db = helper.getReadableDatabase();
Cursor cursor = null;
switch (uriMatcher.match(uri)) {
case BOOK_DIR:
cursor = db.query("book", projection, selection, selectionArgs, null, null, sortOrder);
break;
case BOOK_ITEM:
String bookId = uri.getPathSegments().get(1);
cursor = db.query("book", projection, "id=?", new String[]{bookId}, null, null, sortOrder);
break;
}
return cursor;
}
@Override
public Uri insert(Uri uri, ContentValues values) {
SQLiteDatabase db = helper.getWritableDatabase();
Uri uriReturn = null;
switch (uriMatcher.match(uri)) {
case BOOK_ITEM:
case BOOK_DIR:
long newBookId = db.insert("book", null, values);
uriReturn = Uri.parse("content://com.yong.job.provider/book/" + newBookId);
break;
}
return uriReturn;
}
@Override
public int delete(Uri uri, String selection, String[] selectionArgs) {
SQLiteDatabase db = helper.getWritableDatabase();
int row = 0;
switch (uriMatcher.match(uri)) {
case BOOK_DIR:
row = db.delete("book", selection, selectionArgs);
break;
case BOOK_ITEM:
String bookId = uri.getPathSegments().get(1);
row = db.delete("book", "id=?", new String[]{bookId});
break;
default:
break;
}
return row;
}
@Override
public int update(Uri uri, ContentValues values, String selection, String[] selectionArgs) {
SQLiteDatabase db = helper.getWritableDatabase();
int row = 0;
switch (uriMatcher.match(uri)) {
case BOOK_DIR:
row = db.update("book", values, selection, selectionArgs);
break;
case BOOK_ITEM:
String bookId = uri.getPathSegments().get(1);
row = db.update("book", values, "id = ?", new String[]{bookId});
break;
default:
break;
}
return row;
}
}
| apache-2.0 |
cncduLee/bbks-crawer | extract/bimoku/extract/main/MainChinapub.java | 1546 | package bimoku.extract.main;
import java.io.File;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import bimoku.extract.common.PropertyUtil;
import bimoku.extract.parser.Parser;
import bimoku.extract.parser.ParserChinapub;
public class MainChinapub {
private static ApplicationContext ctx = null;
private static Parser parser = null;
public static ApplicationContext getContext(){
if(ctx == null){
ctx = new ClassPathXmlApplicationContext("classpath:/beans.xml");
}
return ctx;
}
public static void extract(String configPath,Parser parser){
File file = new File(PropertyUtil.getProperty(configPath).getProperty("directory"));
File[] files = file.listFiles();
//创建一个固定大小[10]的线程池
ExecutorService pool = Executors.newFixedThreadPool(47);
for (int i = 0; i < files.length; i++) {
if (files[i].isDirectory()) {
String directoryitem = PropertyUtil.getProperty(configPath).getProperty("directory") + File.separator + files[i].getName();
Extract extract = new Extract(directoryitem,parser,configPath);
//把任务放到线程池的处理队列里面,等待处理
pool.execute(extract);
}
}
//处理完成后,关闭线程池
pool.shutdown();
}
public static void main(String[] args) {
extract("PubConfig.properties", (ParserChinapub)getContext().getBean("parserChinapub"));
}
}
| apache-2.0 |
radicalbit/ambari | ambari-web/app/controllers/wizard/step3_controller.js | 29808 | /**
* 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.
*/
var App = require('app');
var lazyloading = require('utils/lazy_loading');
var numberUtils = require('utils/number_utils');
App.WizardStep3Controller = Em.Controller.extend(App.ReloadPopupMixin, App.CheckHostMixin, {
name: 'wizardStep3Controller',
hosts: [],
content: [],
registeredHosts: [],
jdkRequestIndex: null,
registrationStartedAt: null,
/**
* Timeout for registration
* Based on <code>installOptions.manualInstall</code>
* @type {number}
*/
registrationTimeoutSecs: Em.computed.ifThenElse('content.installOptions.manualInstall', 15, 120),
/**
* Bootstrap calls are stopped
* @type {bool}
*/
stopBootstrap: false,
/**
* is Submit button disabled
* @type {bool}
*/
isSubmitDisabled: true,
/**
* True if bootstrap POST request failed
* @type {bool}
*/
isBootstrapFailed: false,
/**
* is Retry button disabled
* @type {bool}
*/
isRetryDisabled: function() {
return this.get('isBackDisabled') ? this.get('isBackDisabled') : !this.get('bootHosts').filterProperty('bootStatus', 'FAILED').length;
}.property('bootHosts.@each.bootStatus', 'isBackDisabled'),
/**
* Is Back button disabled
* @return {bool}
*/
isBackDisabled: function () {
return (this.get('isRegistrationInProgress') || !this.get('isWarningsLoaded')) && !this.get('isBootstrapFailed') || App.get('router.btnClickInProgress');
}.property('isRegistrationInProgress', 'isWarningsLoaded', 'isBootstrapFailed'),
/**
* Controller is using in Add Host Wizard
* @return {bool}
*/
isAddHostWizard: Em.computed.equal('content.controllerName', 'addHostController'),
/**
* @type {bool}
*/
isLoaded: false,
/**
* Polls count
* @type {number}
*/
numPolls: 0,
/**
* Is hosts registration in progress
* @type {bool}
*/
isRegistrationInProgress: true,
/**
* Are some registered hosts which are not added by user
* @type {bool}
*/
hasMoreRegisteredHosts: false,
/**
* List of installed hostnames
* @type {string[]}
*/
hostsInCluster: function () {
var installedHostsName = [];
var hosts = this.get('content.hosts');
for (var hostName in hosts) {
if (hosts[hostName].isInstalled) {
installedHostsName.push(hostName);
}
}
return installedHostsName;
}.property('content.hosts'),
/**
* Are hosts warnings loaded
* @type {bool}
*/
isWarningsLoaded: Em.computed.and('isJDKWarningsLoaded', 'isHostsWarningsLoaded'),
/**
* Check are hosts have any warnings
* @type {bool}
*/
isHostHaveWarnings: Em.computed.gt('warnings.length', 0),
/**
* Should warnings-box be visible
* @type {bool}
*/
isWarningsBoxVisible: function () {
return (App.get('testMode')) ? true : !this.get('isRegistrationInProgress');
}.property('isRegistrationInProgress'),
isNextButtonDisabled: Em.computed.or('App.router.btnClickInProgress', 'isSubmitDisabled'),
isBackButtonDisabled: Em.computed.or('App.router.btnClickInProgress', 'isBackDisabled'),
/**
*
* @method navigateStep
*/
navigateStep: function () {
if (this.get('isLoaded')) {
if (!this.get('content.installOptions.manualInstall')) {
if (!this.get('wizardController').getDBProperty('bootStatus')) {
this.setupBootStrap();
}
} else {
this.set('bootHosts', this.get('hosts'));
if (App.get('testMode')) {
this.startHostcheck(this.get('hosts'));
this.get('bootHosts').setEach('cpu', '2');
this.get('bootHosts').setEach('memory', '2000000');
this.set('isSubmitDisabled', false);
} else {
this.set('registrationStartedAt', null);
this.startRegistration();
}
}
}
}.observes('isLoaded'),
/**
* Clear controller data
* @method clearStep
*/
clearStep: function () {
this.set('stopBootstrap', false);
this.set('hosts', []);
this.get('bootHosts').clear();
this.get('wizardController').setDBProperty('bootStatus', false);
this.set('isHostsWarningsLoaded', false);
this.set('isJDKWarningsLoaded', false);
this.set('registrationStartedAt', null);
this.set('isLoaded', false);
this.set('isSubmitDisabled', true);
this.set('stopChecking', false);
},
/**
* setup bootstrap data and completion callback for bootstrap call
* @method setupBootStrap
*/
setupBootStrap: function () {
var self = this;
var bootStrapData = JSON.stringify({
'verbose': true,
'sshKey': this.get('content.installOptions.sshKey'),
'hosts': this.getBootstrapHosts(),
'user': this.get('content.installOptions.sshUser'),
'sshPort': this.get('content.installOptions.sshPort'),
'userRunAs': App.get('supports.customizeAgentUserAccount') ? this.get('content.installOptions.agentUser') : 'root'
});
App.router.get(this.get('content.controllerName')).launchBootstrap(bootStrapData, function (requestId) {
if (requestId == '0') {
self.startBootstrap();
} else if (requestId) {
self.set('content.installOptions.bootRequestId', requestId);
App.router.get(self.get('content.controllerName')).save('installOptions');
self.startBootstrap();
}
});
},
getBootstrapHosts: function () {
var hosts = this.get('content.hosts');
var bootstrapHosts = [];
for (var host in hosts) {
if (hosts.hasOwnProperty(host)) {
if (!hosts[host].isInstalled) {
bootstrapHosts.push(host);
}
}
}
return bootstrapHosts;
},
/**
* Make basic init steps
* @method loadStep
*/
loadStep: function () {
var wizardController = this.get('wizardController');
var previousStep = wizardController && wizardController.get('previousStep');
var currentStep = wizardController && wizardController.get('currentStep');
var isHostsLoaded = this.get('hosts').length !== 0;
var isPrevAndCurrStepsSetted = previousStep && currentStep;
var isPrevStepSmallerThenCurrent = previousStep < currentStep;
if (!isHostsLoaded || isPrevStepSmallerThenCurrent ||
!wizardController || !isPrevAndCurrStepsSetted) {
this.disablePreviousSteps();
this.clearStep();
App.router.get('clusterController').loadAmbariProperties();
this.loadHosts();
}
},
/**
* Loads the hostinfo from localStorage on the insertion of view. It's being called from view
* @method loadHosts
*/
loadHosts: function () {
var hostsInfo = this.get('content.hosts');
var hosts = [];
var bootStatus = (this.get('content.installOptions.manualInstall')) ? 'DONE' : 'PENDING';
if (App.get('testMode')) {
bootStatus = 'REGISTERED';
}
for (var index in hostsInfo) {
if (hostsInfo.hasOwnProperty(index) && !hostsInfo[index].isInstalled) {
hosts.pushObject(App.HostInfo.create({
name: hostsInfo[index].name,
bootStatus: bootStatus,
isChecked: false
}));
}
}
this.set('hosts', hosts);
this.set('isLoaded', true);
},
/**
* Parses and updates the content based on bootstrap API response.
* @return {bool} true if polling should continue (some hosts are in "RUNNING" state); false otherwise
* @method parseHostInfo
*/
parseHostInfo: function (hostsStatusFromServer) {
hostsStatusFromServer.forEach(function (_hostStatus) {
var host = this.get('bootHosts').findProperty('name', _hostStatus.hostName);
// check if hostname extracted from REST API data matches any hostname in content
// also, make sure that bootStatus modified by isHostsRegistered call does not get overwritten
// since these calls are being made in parallel
if (host && !['REGISTERED', 'REGISTERING'].contains(host.get('bootStatus'))) {
host.set('bootStatus', _hostStatus.status);
host.set('bootLog', _hostStatus.log);
}
}, this);
// if the data rendered by REST API has hosts in "RUNNING" state, polling will continue
return this.get('bootHosts').length != 0 && this.get('bootHosts').someProperty('bootStatus', 'RUNNING');
},
/**
* Remove list of hosts
* @param {Ember.Enumerable} hosts
* @return {App.ModalPopup}
* @method removeHosts
*/
removeHosts: function (hosts) {
var self = this;
return App.showConfirmationPopup(function () {
App.router.send('removeHosts', hosts);
self.hosts.removeObjects(hosts);
self.stopRegistration();
if (!self.hosts.length) {
self.set('isSubmitDisabled', true);
}
}, Em.I18n.t('installer.step3.hosts.remove.popup.body'));
},
/**
* Removes a single element on the trash icon click. Called from View
* @param {object} hostInfo
* @method removeHost
*/
removeHost: function (hostInfo) {
if (!this.get('isBackDisabled'))
this.removeHosts([hostInfo]);
},
/**
* Remove selected hosts (click-handler)
* @return App.ModalPopup
* @method removeSelectedHosts
*/
removeSelectedHosts: function () {
var selectedHosts = this.get('hosts').filterProperty('isChecked', true);
return this.removeHosts(selectedHosts);
},
/**
* Show popup with the list of hosts which are selected
* @return App.ModalPopup
* @method selectedHostsPopup
*/
selectedHostsPopup: function () {
var selectedHosts = this.get('hosts').filterProperty('isChecked').mapProperty('name');
return App.ModalPopup.show({
header: Em.I18n.t('installer.step3.selectedHosts.popup.header'),
secondary: null,
bodyClass: Em.View.extend({
templateName: require('templates/common/items_list_popup'),
items: selectedHosts,
insertedItems: [],
didInsertElement: function () {
lazyloading.run({
destination: this.get('insertedItems'),
source: this.get('items'),
context: this,
initSize: 100,
chunkSize: 500,
delay: 100
});
}
})
});
},
/**
* Retry one host {click-handler}
* @param {object} hostInfo
* @method retryHost
*/
retryHost: function (hostInfo) {
this.retryHosts([hostInfo]);
},
/**
* Retry list of hosts
* @param {object[]} hosts
* @method retryHosts
*/
retryHosts: function (hosts) {
var self = this;
var bootStrapData = JSON.stringify({
'verbose': true,
'sshKey': this.get('content.installOptions.sshKey'),
'hosts': hosts.mapProperty('name'),
'user': this.get('content.installOptions.sshUser'),
'sshPort': this.get('content.installOptions.sshPort'),
'userRunAs': App.get('supports.customizeAgentUserAccount') ? this.get('content.installOptions.agentUser') : 'root'
});
this.set('numPolls', 0);
this.set('registrationStartedAt', null);
this.set('isHostsWarningsLoaded', false);
this.set('stopChecking', false);
this.set('isSubmitDisabled', true);
if (this.get('content.installOptions.manualInstall')) {
this.startRegistration();
} else {
App.router.get(this.get('content.controllerName')).launchBootstrap(bootStrapData, function (requestId) {
self.set('content.installOptions.bootRequestId', requestId);
self.doBootstrap();
});
}
},
/**
* Retry selected hosts (click-handler)
* @method retrySelectedHosts
*/
retrySelectedHosts: function () {
if (!this.get('isRetryDisabled')) {
var selectedHosts = this.get('bootHosts').filterProperty('bootStatus', 'FAILED');
selectedHosts.forEach(function (_host) {
_host.set('bootStatus', 'DONE');
_host.set('bootLog', 'Retrying ...');
}, this);
this.retryHosts(selectedHosts);
}
},
/**
* Init bootstrap settings and start it
* @method startBootstrap
*/
startBootstrap: function () {
//this.set('isSubmitDisabled', true); //TODO: uncomment after actual hookup
this.set('numPolls', 0);
this.set('registrationStartedAt', null);
this.set('bootHosts', this.get('hosts'));
this.doBootstrap();
},
/**
* Update <code>isRegistrationInProgress</code> once
* @method setRegistrationInProgressOnce
*/
setRegistrationInProgressOnce: function () {
Em.run.once(this, 'setRegistrationInProgress');
}.observes('bootHosts.@each.bootStatus'),
/**
* Set <code>isRegistrationInProgress</code> value based on each host boot status
* @method setRegistrationInProgress
*/
setRegistrationInProgress: function () {
var bootHosts = this.get('bootHosts');
//if hosts aren't loaded yet then registration should be in progress
var result = (bootHosts.length === 0 && !this.get('isLoaded'));
for (var i = 0, l = bootHosts.length; i < l; i++) {
if (bootHosts[i].get('bootStatus') !== 'REGISTERED' && bootHosts[i].get('bootStatus') !== 'FAILED') {
result = true;
break;
}
}
this.set('isRegistrationInProgress', result);
},
/**
* Disable wizard's previous steps (while registering)
* @method disablePreviousSteps
*/
disablePreviousSteps: function () {
App.router.get('installerController.isStepDisabled').filter(function (step) {
return step.step >= 0 && step.step <= 2;
}).setEach('value', this.get('isBackDisabled'));
App.router.get('addHostController.isStepDisabled').filter(function (step) {
return step.step >= 0 && step.step <= 1;
}).setEach('value', this.get('isBackDisabled'));
}.observes('isBackDisabled'),
/**
* Close reload popup on exit from Confirm Hosts step
* @method closeReloadPopupOnExit
*/
closeReloadPopupOnExit: function () {
if (this.get('stopBootstrap')) {
this.closeReloadPopup();
}
}.observes('stopBootstrap'),
/**
* Do bootstrap calls
* @method doBootstrap
* @return {$.ajax|null}
*/
doBootstrap: function () {
if (this.get('stopBootstrap')) {
return null;
}
this.incrementProperty('numPolls');
return App.ajax.send({
name: 'wizard.step3.bootstrap',
sender: this,
data: {
bootRequestId: this.get('content.installOptions.bootRequestId'),
numPolls: this.get('numPolls'),
callback: this.doBootstrap,
timeout: 3000,
shouldUseDefaultHandler: true
},
success: 'doBootstrapSuccessCallback',
error: 'reloadErrorCallback'
});
},
/**
* Success-callback for each boostrap request
* @param {object} data
* @method doBootstrapSuccessCallback
*/
doBootstrapSuccessCallback: function (data) {
var self = this;
var pollingInterval = 3000;
this.reloadSuccessCallback();
if (Em.isNone(data.hostsStatus)) {
window.setTimeout(function () {
self.doBootstrap()
}, pollingInterval);
} else {
// in case of bootstrapping just one host, the server returns an object rather than an array, so
// force into an array
if (!(data.hostsStatus instanceof Array)) {
data.hostsStatus = [ data.hostsStatus ];
}
var keepPolling = this.parseHostInfo(data.hostsStatus);
// Single host : if the only hostname is invalid (data.status == 'ERROR')
// Multiple hosts : if one or more hostnames are invalid
// following check will mark the bootStatus as 'FAILED' for the invalid hostname
var installedHosts = App.Host.find().mapProperty('hostName');
var isErrorStatus = data.status == 'ERROR';
this.set('isBootstrapFailed', isErrorStatus);
if (isErrorStatus || data.hostsStatus.mapProperty('hostName').removeObjects(installedHosts).length != this.get('bootHosts').length) {
var hosts = this.get('bootHosts');
for (var i = 0; i < hosts.length; i++) {
var isValidHost = data.hostsStatus.someProperty('hostName', hosts[i].get('name'));
if (hosts[i].get('bootStatus') !== 'REGISTERED') {
if (!isValidHost) {
hosts[i].set('bootStatus', 'FAILED');
hosts[i].set('bootLog', Em.I18n.t('installer.step3.hosts.bootLog.failed'));
}
}
}
}
if (isErrorStatus || data.hostsStatus.someProperty('status', 'DONE') || data.hostsStatus.someProperty('status', 'FAILED')) {
// kicking off registration polls after at least one host has succeeded
this.startRegistration();
}
if (keepPolling) {
window.setTimeout(function () {
self.doBootstrap()
}, pollingInterval);
}
}
},
/**
* Start hosts registration
* @method startRegistration
*/
startRegistration: function () {
if (Em.isNone(this.get('registrationStartedAt'))) {
this.set('registrationStartedAt', App.dateTime());
this.isHostsRegistered();
}
},
/**
* Do requests to check if hosts are already registered
* @return {$.ajax|null}
* @method isHostsRegistered
*/
isHostsRegistered: function () {
if (this.get('stopBootstrap')) {
return null;
}
return App.ajax.send({
name: 'wizard.step3.is_hosts_registered',
sender: this,
success: 'isHostsRegisteredSuccessCallback',
error: 'reloadErrorCallback',
data: {
callback: this.isHostsRegistered,
timeout: 3000,
shouldUseDefaultHandler: true
}
});
},
/**
* Success-callback for registered hosts request
* @param {object} data
* @method isHostsRegisteredSuccessCallback
*/
isHostsRegisteredSuccessCallback: function (data) {
var hosts = this.get('bootHosts');
var jsonData = data;
this.reloadSuccessCallback();
if (!jsonData) {
return;
}
// keep polling until all hosts have registered/failed, or registrationTimeout seconds after the last host finished bootstrapping
var stopPolling = true;
hosts.forEach(function (_host, index) {
// Change name of first host for test mode.
if (App.get('testMode')) {
if (index == 0) {
_host.set('name', 'localhost.localdomain');
}
}
// actions to take depending on the host's current bootStatus
// RUNNING - bootstrap is running; leave it alone
// DONE - bootstrap is done; transition to REGISTERING
// REGISTERING - bootstrap is done but has not registered; transition to REGISTERED if host found in polling API result
// REGISTERED - bootstrap and registration is done; leave it alone
// FAILED - either bootstrap or registration failed; leave it alone
switch (_host.get('bootStatus')) {
case 'DONE':
_host.set('bootStatus', 'REGISTERING');
_host.set('bootLog', (_host.get('bootLog') != null ? _host.get('bootLog') : '') + Em.I18n.t('installer.step3.hosts.bootLog.registering'));
// update registration timestamp so that the timeout is computed from the last host that finished bootstrapping
this.set('registrationStartedAt', App.dateTime());
stopPolling = false;
break;
case 'REGISTERING':
if (jsonData.items.someProperty('Hosts.host_name', _host.name) && !jsonData.items.filterProperty('Hosts.host_name', _host.name).someProperty('Hosts.host_status', 'UNKNOWN')) {
_host.set('bootStatus', 'REGISTERED');
_host.set('bootLog', (_host.get('bootLog') != null ? _host.get('bootLog') : '') + Em.I18n.t('installer.step3.hosts.bootLog.registering'));
} else {
stopPolling = false;
}
break;
case 'RUNNING':
stopPolling = false;
break;
case 'REGISTERED':
case 'FAILED':
default:
break;
}
}, this);
if (stopPolling) {
this.startHostcheck(hosts);
}
else {
if (hosts.someProperty('bootStatus', 'RUNNING') || App.dateTime() - this.get('registrationStartedAt') < this.get('registrationTimeoutSecs') * 1000) {
// we want to keep polling for registration status if any of the hosts are still bootstrapping (so we check for RUNNING).
var self = this;
window.setTimeout(function () {
self.isHostsRegistered();
}, 3000);
}
else {
// registration timed out. mark all REGISTERING hosts to FAILED
hosts.filterProperty('bootStatus', 'REGISTERING').forEach(function (_host) {
_host.set('bootStatus', 'FAILED');
_host.set('bootLog', (_host.get('bootLog') != null ? _host.get('bootLog') : '') + Em.I18n.t('installer.step3.hosts.bootLog.failed'));
});
this.startHostcheck(hosts);
}
}
},
/**
* Do request for all registered hosts
* @return {$.ajax}
* @method getAllRegisteredHosts
*/
getAllRegisteredHosts: function () {
return App.ajax.send({
name: 'wizard.step3.is_hosts_registered',
sender: this,
success: 'getAllRegisteredHostsCallback'
});
}.observes('bootHosts'),
/**
* Success-callback for all registered hosts request
* @param {object} hosts
* @method getAllRegisteredHostsCallback
*/
getAllRegisteredHostsCallback: function (hosts) {
var registeredHosts = [];
var hostsInCluster = this.get('hostsInCluster');
var addedHosts = this.get('bootHosts').getEach('name');
hosts.items.forEach(function (host) {
if (!hostsInCluster.contains(host.Hosts.host_name) && !addedHosts.contains(host.Hosts.host_name)) {
registeredHosts.push(host.Hosts.host_name);
}
});
if (registeredHosts.length) {
this.set('hasMoreRegisteredHosts', true);
this.set('registeredHosts', registeredHosts);
} else {
this.set('hasMoreRegisteredHosts', false);
this.set('registeredHosts', '');
}
},
/**
* Get JDK name from server to determine if user had setup a customized JDK path when doing 'ambari-server setup'.
* The Ambari properties are different from default ambari-server setup, property 'jdk.name' will be missing if a customized jdk path is applied.
* @return {$.ajax}
* @method getJDKName
*/
getJDKName: function () {
return App.ajax.send({
name: 'ambari.service',
sender: this,
data: {
fields : '?fields=RootServiceComponents/properties/jdk.name,RootServiceComponents/properties/java.home,RootServiceComponents/properties/jdk_location'
},
success: 'getJDKNameSuccessCallback'
});
},
/**
* Success callback for JDK name, property 'jdk.name' will be missing if a customized jdk path is applied
* @param {object} data
* @method getJDKNameSuccessCallback
*/
getJDKNameSuccessCallback: function (data) {
this.set('needJDKCheckOnHosts', !data.RootServiceComponents.properties["jdk.name"]);
this.set('jdkLocation', Em.get(data, "RootServiceComponents.properties.jdk_location"));
this.set('javaHome', data.RootServiceComponents.properties["java.home"]);
},
doCheckJDK: function () {
var hostsNames = (!this.get('content.installOptions.manualInstall')) ? this.get('bootHosts').filterProperty('bootStatus', 'REGISTERED').getEach('name').join(",") : this.get('bootHosts').getEach('name').join(",");
var javaHome = this.get('javaHome');
var jdkLocation = this.get('jdkLocation');
App.ajax.send({
name: 'wizard.step3.jdk_check',
sender: this,
data: {
host_names: hostsNames,
java_home: javaHome,
jdk_location: jdkLocation
},
success: 'doCheckJDKsuccessCallback',
error: 'doCheckJDKerrorCallback'
});
},
doCheckJDKsuccessCallback: function (data) {
if(data){
this.set('jdkRequestIndex', data.href.split('/')[data.href.split('/').length - 1]);
}
if (this.get('jdkCategoryWarnings') == null) {
// get jdk check results for all hosts
App.ajax.send({
name: 'wizard.step3.jdk_check.get_results',
sender: this,
data: {
requestIndex: this.get('jdkRequestIndex')
},
success: 'parseJDKCheckResults'
})
} else {
this.set('isJDKWarningsLoaded', true);
}
},
doCheckJDKerrorCallback: function () {
this.set('isJDKWarningsLoaded', true);
},
parseJDKCheckResults: function (data) {
var jdkWarnings = [], hostsJDKContext = [], hostsJDKNames = [];
// check if the request ended
if (data.Requests.end_time > 0 && data.tasks) {
data.tasks.forEach( function(task) {
// generate warning context
if (Em.get(task, "Tasks.structured_out.java_home_check.exit_code") == 1){
var jdkContext = Em.I18n.t('installer.step3.hostWarningsPopup.jdk.context').format(task.Tasks.host_name);
hostsJDKContext.push(jdkContext);
hostsJDKNames.push(task.Tasks.host_name);
}
});
if (hostsJDKContext.length > 0) { // java jdk warning exist
var invalidJavaHome = this.get('javaHome');
jdkWarnings.push({
name: Em.I18n.t('installer.step3.hostWarningsPopup.jdk.name').format(invalidJavaHome),
hosts: hostsJDKContext,
hostsLong: hostsJDKContext,
hostsNames: hostsJDKNames,
category: 'jdk'
});
}
this.set('jdkCategoryWarnings', jdkWarnings);
} else {
// still doing JDK check, data not ready to be parsed
this.set('jdkCategoryWarnings', null);
}
this.doCheckJDKsuccessCallback();
},
/**
* Check JDK issues on registered hosts.
*/
checkHostJDK: function () {
this.set('isJDKWarningsLoaded', false);
this.set('jdkCategoryWarnings', null);
var self = this;
this.getJDKName().done( function() {
if (self.get('needJDKCheckOnHosts')) {
// need to do JDK check on each host
self.doCheckJDK();
} else {
// no customized JDK path, so no need to check jdk
self.set('jdkCategoryWarnings', []);
self.set('isJDKWarningsLoaded', true);
}
});
},
startHostcheck: function(hosts) {
if (!hosts.everyProperty('bootStatus', 'FAILED')) {
this.set('isWarningsLoaded', false);
this.getHostNameResolution();
this.checkHostJDK();
} else {
this.stopHostCheck();
}
},
_submitProceed: function () {
this.set('confirmedHosts', this.get('bootHosts'));
App.get('router').send('next');
},
/**
* Submit-click handler
* Disable 'Next' button while it is already under process. (using Router's property 'nextBtnClickInProgress')
* @return {App.ModalPopup?}
* @method submit
*/
submit: function () {
var self = this;
if(App.get('router.nextBtnClickInProgress')) {
return;
}
if (this.get('isHostHaveWarnings')) {
return App.showConfirmationPopup(
function () {
self._submitProceed();
},
Em.I18n.t('installer.step3.hostWarningsPopup.hostHasWarnings'));
}
this._submitProceed();
},
/**
* Show popup with host log
* @param {object} event
* @return {App.ModalPopup}
*/
hostLogPopup: function (event) {
var host = event.context;
return App.ModalPopup.show({
header: Em.I18n.t('installer.step3.hostLog.popup.header').format(host.get('name')),
secondary: null,
host: host,
bodyClass: App.WizardStep3HostLogPopupBody
});
},
/**
* Open popup that contain hosts' warnings
* @return {App.ModalPopup}
* @method hostWarningsPopup
*/
hostWarningsPopup: function () {
var self = this;
return App.ModalPopup.show({
header: Em.I18n.t('installer.step3.warnings.popup.header'),
secondary: Em.I18n.t('installer.step3.hostWarningsPopup.rerunChecks'),
primary: Em.I18n.t('common.close'),
autoHeight: false,
'data-qa': 'host-checks-modal',
onPrimary: function () {
self.set('checksUpdateStatus', null);
this.hide();
},
onClose: function () {
self.set('checksUpdateStatus', null);
this.hide();
},
onSecondary: function () {
self.rerunChecks();
},
didInsertElement: function () {
this._super();
this.fitHeight();
},
footerClass: App.WizardStep3HostWarningPopupFooter.reopen({
checkHostFinished: true
}),
bodyClass: App.WizardStep3HostWarningPopupBody.reopen({
checkHostFinished: true
})
});
},
/**
* Show popup with registered hosts
* @return {App.ModalPopup}
* @method registeredHostsPopup
*/
registeredHostsPopup: function () {
var self = this;
return App.ModalPopup.show({
header: Em.I18n.t('installer.step3.warning.registeredHosts').format(this.get('registeredHosts').length),
secondary: null,
bodyClass: Em.View.extend({
templateName: require('templates/wizard/step3/step3_registered_hosts_popup'),
message: Em.I18n.t('installer.step3.registeredHostsPopup'),
registeredHosts: self.get('registeredHosts'),
checkHostsFinished: true
})
})
}
});
| apache-2.0 |
mhansonp/geode-native | examples/dotnet/Apache.Geode.Examples.Cache/Program.cs | 1617 | /*
* 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.
*/
using System;
using Apache.Geode.Client;
namespace Apache.Geode.Examples.Cache
{
class Program
{
static void Main(string[] args)
{
var cacheFactory = CacheFactory.CreateCacheFactory()
.Set("log-level", "none");
var cache = cacheFactory.Create();
var poolFactory = cache.GetPoolFactory()
.AddLocator("localhost", 10334);
poolFactory.Create("pool", cache);
var regionFactory = cache.CreateRegionFactory(RegionShortcut.PROXY)
.SetPoolName("pool");
var region = regionFactory.Create<string, string>("region");
region["a"] = "1";
region["b"] = "2";
var a = region["a"];
var b = region["b"];
Console.Out.WriteLine("a = " + a);
Console.Out.WriteLine("b = " + b);
cache.Close();
}
}
}
| apache-2.0 |
gleb619/hotel_shop | src/main/java/org/test/shop/model/service/view/DocDocumentsViewService.java | 3026 | package org.test.shop.model.service.view;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.test.shop.controller.data.types.ScrollableSettings;
import org.test.shop.model.dao.view.DocDocumentsViewDao;
import org.test.shop.model.domain.entity.view.DocDocumentsView;
import org.test.shop.util.data.types.DateCompare;
@Service
@Transactional
public class DocDocumentsViewService {
@Autowired
private DocDocumentsViewDao docdocumentsviewDao;
@Transactional
public DocDocumentsView create(DocDocumentsView data) {
return docdocumentsviewDao.create(data);
}
@Transactional
public DocDocumentsView update(DocDocumentsView data) {
return docdocumentsviewDao.update(data);
}
@Transactional
public Boolean delete(Object id) {
return docdocumentsviewDao.delete(id);
}
@Transactional
public void popularity(DocDocumentsView data) {
docdocumentsviewDao.popularity(data);
}
@Transactional
public void popularityByKey(Object data) {
docdocumentsviewDao.popularityByKey(data);
}
@Transactional(readOnly = true)
public Integer todayNumber(ScrollableSettings settings) throws Exception {
return docdocumentsviewDao.todayNumber(settings);
}
@Transactional(readOnly = true)
public Integer total(ScrollableSettings settings) throws Exception {
return docdocumentsviewDao.total(settings);
}
@Transactional(readOnly = true)
public List<DocDocumentsView> namedFilter(ScrollableSettings settings) {
return docdocumentsviewDao.namedFilter(settings);
}
@Transactional(readOnly = true)
public List<DocDocumentsView> search(ScrollableSettings settings){
return docdocumentsviewDao.search(settings);
}
@Transactional(readOnly = true)
public List<DocDocumentsView> findByExample(DocDocumentsView example, String delimitter, ScrollableSettings settings) {
return docdocumentsviewDao.findByExample(example, delimitter, settings);
}
@Transactional(readOnly = true)
public List<DocDocumentsView> findByExample2(DocDocumentsView example, DateCompare type) {
return docdocumentsviewDao.findByExample2(example, type);
}
@Transactional(readOnly = true)
public List<DocDocumentsView> findAll() {
return docdocumentsviewDao.findAll(new ScrollableSettings());
}
@Transactional(readOnly = true)
public List<DocDocumentsView> findAll(ScrollableSettings settings) {
return docdocumentsviewDao.findAll(settings);
}
@Transactional(readOnly = true)
public List<DocDocumentsView> findAllScrollable(ScrollableSettings settings) {
return docdocumentsviewDao.findAllScrollable(settings);
}
@Transactional(readOnly = true)
public DocDocumentsView findById(ScrollableSettings scrollableSettings) {
return docdocumentsviewDao.findById(scrollableSettings);
}
@Transactional(readOnly = true)
public DocDocumentsView findById(Object key, Boolean initAll) {
return docdocumentsviewDao.findById(key, initAll);
}
}
| apache-2.0 |
etechi/ServiceFramework | Projects/Server/Test/DBSetup/Migrations/AppContextModelSnapshot.cs | 4457 | using System;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Metadata;
using Microsoft.EntityFrameworkCore.Migrations;
using DBSetup;
using SF;
using SF.Data;
using SF.Auth.Users;
namespace DBSetup.Migrations
{
[DbContext(typeof(AppContext))]
partial class AppContextModelSnapshot : ModelSnapshot
{
protected override void BuildModel(ModelBuilder modelBuilder)
{
modelBuilder
.HasAnnotation("ProductVersion", "1.1.0-rtm-22752")
.HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn);
modelBuilder.Entity("SF.Auth.Users.EFCore.DataModels.User", b =>
{
b.Property<long>("Id");
b.Property<int>("AccessFailedCount");
b.Property<DateTime>("CreatedTime");
b.Property<string>("Email")
.HasMaxLength(200);
b.Property<string>("Icon")
.HasMaxLength(200);
b.Property<string>("Image")
.HasMaxLength(200);
b.Property<long?>("InviterId");
b.Property<string>("LastAddress")
.HasMaxLength(100);
b.Property<int>("LastDeviceType");
b.Property<DateTime?>("LastSigninTime");
b.Property<DateTime?>("LockoutEndDateUtc");
b.Property<string>("NickName")
.HasMaxLength(100);
b.Property<bool>("NoIdents");
b.Property<byte>("ObjectState");
b.Property<string>("PasswordHash")
.HasMaxLength(100);
b.Property<string>("PhoneNumber")
.HasMaxLength(50);
b.Property<string>("SecurityStamp")
.IsRequired()
.HasMaxLength(100);
b.Property<int>("Sex");
b.Property<int>("SigninCount");
b.Property<string>("SignupAddress")
.HasMaxLength(100);
b.Property<int>("SignupDeviceType");
b.Property<string>("SignupIdentProvider")
.HasMaxLength(50);
b.Property<string>("SignupIdentValue")
.HasMaxLength(200);
b.Property<byte[]>("TimeStamp")
.IsConcurrencyToken()
.ValueGeneratedOnAddOrUpdate();
b.Property<DateTime>("UpdatedTime");
b.Property<string>("UserName")
.HasMaxLength(100);
b.Property<int>("UserType");
b.HasKey("Id");
b.HasIndex("CreatedTime");
b.HasIndex("LastSigninTime");
b.HasIndex("NoIdents");
b.HasIndex("SignupIdentProvider");
b.HasIndex("SignupIdentValue");
b.HasIndex("UserType");
b.ToTable("AppAuthUser");
});
modelBuilder.Entity("SF.Auth.Users.EFCore.DataModels.UserPhoneNumberIdent", b =>
{
b.Property<string>("Ident")
.HasMaxLength(100);
b.Property<long>("UserId");
b.Property<DateTime?>("ConfirmedTime");
b.Property<DateTime>("CreatedTime");
b.HasKey("Ident", "UserId");
b.HasAlternateKey("Ident");
b.HasIndex("UserId");
b.ToTable("AppAuthUserPhoneNumberIdent");
});
modelBuilder.Entity("SF.Data.IdentGenerator.EFCore.DataModels.IdentSeed", b =>
{
b.Property<string>("Type")
.ValueGeneratedOnAdd();
b.Property<long>("NextValue");
b.Property<byte[]>("TimeStamp")
.IsConcurrencyToken()
.ValueGeneratedOnAddOrUpdate();
b.HasKey("Type");
b.ToTable("AppSysIdentSeed");
});
}
}
}
| apache-2.0 |
springfox/springfox | springfox-core/src/main/java/springfox/documentation/service/ResolvedMethodParameter.java | 3023 | /*
*
* Copyright 2015-2019 the original author or 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 springfox.documentation.service;
import com.fasterxml.classmate.ResolvedType;
import org.springframework.core.MethodParameter;
import java.lang.annotation.Annotation;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import static java.util.Optional.*;
import static java.util.stream.Collectors.*;
import static java.util.stream.Stream.of;
public class ResolvedMethodParameter {
private final int parameterIndex;
private final List<Annotation> annotations;
private final String defaultName;
private final ResolvedType parameterType;
public ResolvedMethodParameter(String paramName, MethodParameter methodParameter, ResolvedType parameterType) {
this(methodParameter.getParameterIndex(),
paramName,
of(methodParameter.getParameterAnnotations()).collect(toList()),
parameterType);
}
public ResolvedMethodParameter(int parameterIndex, String defaultName, List<Annotation> annotations, ResolvedType
parameterType) {
this.parameterIndex = parameterIndex;
this.defaultName = defaultName;
this.parameterType = parameterType;
this.annotations = annotations;
}
public ResolvedType getParameterType() {
return parameterType;
}
public boolean hasParameterAnnotations() {
return !annotations.isEmpty();
}
public boolean hasParameterAnnotation(Class<? extends Annotation> annotation) {
return annotations.stream().anyMatch(annotation::isInstance);
}
@SuppressWarnings("unchecked")
public <T extends Annotation> Optional<T> findAnnotation(final Class<T> annotation) {
return (Optional<T>) annotations.stream().filter(annotation::isInstance).findFirst();
}
public int getParameterIndex() {
return parameterIndex;
}
public Optional<String> defaultName() {
return ofNullable(defaultName);
}
public ResolvedMethodParameter replaceResolvedParameterType(ResolvedType parameterType) {
return new ResolvedMethodParameter(parameterIndex, defaultName, annotations, parameterType);
}
public List<Annotation> getAnnotations() {
return annotations;
}
public ResolvedMethodParameter annotate(Annotation annotation) {
List<Annotation> annotations = new ArrayList<>(this.annotations);
annotations.add(annotation);
return new ResolvedMethodParameter(parameterIndex, defaultName, annotations, parameterType);
}
}
| apache-2.0 |
helloavery/hello-itavery | js/popup.js | 1082 | $('#open-popup').magnificPopup({
items: [
{
src: 'videos/Pulling-the-Plug.mp4',
type: 'iframe' // this overrides default type
},
],
gallery: {
enabled: true
},
type: 'image' // this is a default type
});
$('#open-popup2').magnificPopup({
items: [
{
src: 'videos/Experimental-Il Monstro Giallo.mp4',
type: 'iframe' // this overrides default type
},
],
gallery: {
enabled: true
},
type: 'image' // this is a default type
});
$('#open-popup3').magnificPopup({
items: [
{
src: 'videos/Documentary-Fruitless.mp4',
type: 'iframe' // this overrides default type
},
],
gallery: {
enabled: true
},
type: 'image' // this is a default type
});
$('#open-popup4').magnificPopup({
items: [
{
src: 'videos/Summers_Heart.mp4',
type: 'iframe' // this overrides default type
},
],
gallery: {
enabled: true
},
type: 'image' // this is a default type
});
| apache-2.0 |
dubenju/javay | src/java/org/xiph/libvorbis/alloc_chain.java | 506 | /*
* THIS FILE IS PART OF THE OggVorbis SOFTWARE CODEC SOURCE CODE.
* USE, DISTRIBUTION AND REPRODUCTION OF THIS LIBRARY SOURCE IS
* GOVERNED BY A BSD-STYLE SOURCE LICENSE INCLUDED WITH THIS SOURCE
* IN 'COPYING'. PLEASE READ THESE TERMS BEFORE DISTRIBUTING.
*
* THE OggVorbis SOURCE CODE IS (C) COPYRIGHT 1994-2002
* by the Xiph.Org Foundation http://www.xiph.org/
*/
package org.xiph.libvorbis;
class alloc_chain {
Object[] ptr;
alloc_chain next;
public alloc_chain() {
}
}
| apache-2.0 |
greycat-incubator/Paw | src/main/java/paw/graph/customTypes/tokenizedContent/Word.java | 1236 | /**
* Copyright 2017 Matthieu Jimenez. All rights reserved.
* <p>
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* <p>
* http://www.apache.org/licenses/LICENSE-2.0
* <p>
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package paw.graph.customTypes.tokenizedContent;
public class Word {
protected final byte type;
protected final int wordID;
protected int firstChar;
public Word(byte type, int wordID) {
this.type = type;
this.wordID = wordID;
}
public Word(byte type, int wordID, int firstChar) {
this.type = type;
this.wordID = wordID;
this.firstChar = firstChar;
}
public byte getType() {
return type;
}
public int getWordID() {
return wordID;
}
public int getFirstChar() {
return firstChar;
}
}
| apache-2.0 |
EuregJUG-Maas-Rhine/site | src/main/java/eu/euregjug/site/posts/PostRepository.java | 2364 | /*
* Copyright 2015-2016 EuregJUG.
*
* 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 eu.euregjug.site.posts;
import eu.euregjug.site.posts.PostEntity.Status;
import java.util.Date;
import java.util.List;
import java.util.Optional;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.repository.Repository;
import org.springframework.transaction.annotation.Transactional;
/**
* @author Michael J. Simons, 2015-12-28
*/
public interface PostRepository extends Repository<PostEntity, Integer>, PostRepositoryExt {
/**
* Saves the given post.
*
* @param entity
* @return Persisted post
*/
PostEntity save(PostEntity entity);
/**
* @param id
* @return Post with the given Id or an empty optional
*/
@Transactional(readOnly = true)
Optional<PostEntity> findOne(Integer id);
/**
* Selects a post by date and slug.
*
* @param publishedOn
* @param slug
* @return
*/
@Transactional(readOnly = true)
Optional<PostEntity> findByPublishedOnAndSlug(Date publishedOn, String slug);
/**
* Selects a "page" of posts with a given status.
*
* @param status status as selection criteria
* @param pageable
* @return
*/
@Transactional(readOnly = true)
Page<PostEntity> findAllByStatus(Status status, Pageable pageable);
/**
* Selects a "page" of posts.
*
* @param pageable
* @return
*/
@Transactional(readOnly = true)
Page<PostEntity> findAll(Pageable pageable);
/**
* Selects all posts sorted by the specified sort.
*
* @param sort
* @return
*/
@Transactional(readOnly = true)
List<PostEntity> findAll(Sort sort);
}
| apache-2.0 |
cloudfoundry/php-buildpack | fixtures/symfony_5_local_deps/vendor/symfony/console/Helper/QuestionHelper.php | 16379 | <?php
/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Symfony\Component\Console\Helper;
use Symfony\Component\Console\Cursor;
use Symfony\Component\Console\Exception\MissingInputException;
use Symfony\Component\Console\Exception\RuntimeException;
use Symfony\Component\Console\Formatter\OutputFormatter;
use Symfony\Component\Console\Formatter\OutputFormatterStyle;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Input\StreamableInputInterface;
use Symfony\Component\Console\Output\ConsoleOutputInterface;
use Symfony\Component\Console\Output\ConsoleSectionOutput;
use Symfony\Component\Console\Output\OutputInterface;
use Symfony\Component\Console\Question\ChoiceQuestion;
use Symfony\Component\Console\Question\Question;
use Symfony\Component\Console\Terminal;
use function Symfony\Component\String\s;
/**
* The QuestionHelper class provides helpers to interact with the user.
*
* @author Fabien Potencier <fabien@symfony.com>
*/
class QuestionHelper extends Helper
{
private $inputStream;
private static $shell;
private static $stty = true;
private static $stdinIsInteractive;
/**
* Asks a question to the user.
*
* @return mixed The user answer
*
* @throws RuntimeException If there is no data to read in the input stream
*/
public function ask(InputInterface $input, OutputInterface $output, Question $question)
{
if ($output instanceof ConsoleOutputInterface) {
$output = $output->getErrorOutput();
}
if (!$input->isInteractive()) {
return $this->getDefaultAnswer($question);
}
if ($input instanceof StreamableInputInterface && $stream = $input->getStream()) {
$this->inputStream = $stream;
}
try {
if (!$question->getValidator()) {
return $this->doAsk($output, $question);
}
$interviewer = function () use ($output, $question) {
return $this->doAsk($output, $question);
};
return $this->validateAttempts($interviewer, $output, $question);
} catch (MissingInputException $exception) {
$input->setInteractive(false);
if (null === $fallbackOutput = $this->getDefaultAnswer($question)) {
throw $exception;
}
return $fallbackOutput;
}
}
/**
* {@inheritdoc}
*/
public function getName()
{
return 'question';
}
/**
* Prevents usage of stty.
*/
public static function disableStty()
{
self::$stty = false;
}
/**
* Asks the question to the user.
*
* @return bool|mixed|string|null
*
* @throws RuntimeException In case the fallback is deactivated and the response cannot be hidden
*/
private function doAsk(OutputInterface $output, Question $question)
{
$this->writePrompt($output, $question);
$inputStream = $this->inputStream ?: \STDIN;
$autocomplete = $question->getAutocompleterCallback();
if (\function_exists('sapi_windows_cp_set')) {
// Codepage used by cmd.exe on Windows to allow special characters (éàüñ).
@sapi_windows_cp_set(1252);
}
if (null === $autocomplete || !self::$stty || !Terminal::hasSttyAvailable()) {
$ret = false;
if ($question->isHidden()) {
try {
$hiddenResponse = $this->getHiddenResponse($output, $inputStream, $question->isTrimmable());
$ret = $question->isTrimmable() ? trim($hiddenResponse) : $hiddenResponse;
} catch (RuntimeException $e) {
if (!$question->isHiddenFallback()) {
throw $e;
}
}
}
if (false === $ret) {
$ret = fgets($inputStream, 4096);
if (false === $ret) {
throw new MissingInputException('Aborted.');
}
if ($question->isTrimmable()) {
$ret = trim($ret);
}
}
} else {
$autocomplete = $this->autocomplete($output, $question, $inputStream, $autocomplete);
$ret = $question->isTrimmable() ? trim($autocomplete) : $autocomplete;
}
if ($output instanceof ConsoleSectionOutput) {
$output->addContent($ret);
}
$ret = \strlen($ret) > 0 ? $ret : $question->getDefault();
if ($normalizer = $question->getNormalizer()) {
return $normalizer($ret);
}
return $ret;
}
/**
* @return mixed
*/
private function getDefaultAnswer(Question $question)
{
$default = $question->getDefault();
if (null === $default) {
return $default;
}
if ($validator = $question->getValidator()) {
return \call_user_func($question->getValidator(), $default);
} elseif ($question instanceof ChoiceQuestion) {
$choices = $question->getChoices();
if (!$question->isMultiselect()) {
return isset($choices[$default]) ? $choices[$default] : $default;
}
$default = explode(',', $default);
foreach ($default as $k => $v) {
$v = $question->isTrimmable() ? trim($v) : $v;
$default[$k] = isset($choices[$v]) ? $choices[$v] : $v;
}
}
return $default;
}
/**
* Outputs the question prompt.
*/
protected function writePrompt(OutputInterface $output, Question $question)
{
$message = $question->getQuestion();
if ($question instanceof ChoiceQuestion) {
$output->writeln(array_merge([
$question->getQuestion(),
], $this->formatChoiceQuestionChoices($question, 'info')));
$message = $question->getPrompt();
}
$output->write($message);
}
/**
* @return string[]
*/
protected function formatChoiceQuestionChoices(ChoiceQuestion $question, string $tag)
{
$messages = [];
$maxWidth = max(array_map('self::strlen', array_keys($choices = $question->getChoices())));
foreach ($choices as $key => $value) {
$padding = str_repeat(' ', $maxWidth - self::strlen($key));
$messages[] = sprintf(" [<$tag>%s$padding</$tag>] %s", $key, $value);
}
return $messages;
}
/**
* Outputs an error message.
*/
protected function writeError(OutputInterface $output, \Exception $error)
{
if (null !== $this->getHelperSet() && $this->getHelperSet()->has('formatter')) {
$message = $this->getHelperSet()->get('formatter')->formatBlock($error->getMessage(), 'error');
} else {
$message = '<error>'.$error->getMessage().'</error>';
}
$output->writeln($message);
}
/**
* Autocompletes a question.
*
* @param resource $inputStream
*/
private function autocomplete(OutputInterface $output, Question $question, $inputStream, callable $autocomplete): string
{
$cursor = new Cursor($output, $inputStream);
$fullChoice = '';
$ret = '';
$i = 0;
$ofs = -1;
$matches = $autocomplete($ret);
$numMatches = \count($matches);
$sttyMode = shell_exec('stty -g');
// Disable icanon (so we can fread each keypress) and echo (we'll do echoing here instead)
shell_exec('stty -icanon -echo');
// Add highlighted text style
$output->getFormatter()->setStyle('hl', new OutputFormatterStyle('black', 'white'));
// Read a keypress
while (!feof($inputStream)) {
$c = fread($inputStream, 1);
// as opposed to fgets(), fread() returns an empty string when the stream content is empty, not false.
if (false === $c || ('' === $ret && '' === $c && null === $question->getDefault())) {
shell_exec(sprintf('stty %s', $sttyMode));
throw new MissingInputException('Aborted.');
} elseif ("\177" === $c) { // Backspace Character
if (0 === $numMatches && 0 !== $i) {
--$i;
$cursor->moveLeft(s($fullChoice)->slice(-1)->width(false));
$fullChoice = self::substr($fullChoice, 0, $i);
}
if (0 === $i) {
$ofs = -1;
$matches = $autocomplete($ret);
$numMatches = \count($matches);
} else {
$numMatches = 0;
}
// Pop the last character off the end of our string
$ret = self::substr($ret, 0, $i);
} elseif ("\033" === $c) {
// Did we read an escape sequence?
$c .= fread($inputStream, 2);
// A = Up Arrow. B = Down Arrow
if (isset($c[2]) && ('A' === $c[2] || 'B' === $c[2])) {
if ('A' === $c[2] && -1 === $ofs) {
$ofs = 0;
}
if (0 === $numMatches) {
continue;
}
$ofs += ('A' === $c[2]) ? -1 : 1;
$ofs = ($numMatches + $ofs) % $numMatches;
}
} elseif (\ord($c) < 32) {
if ("\t" === $c || "\n" === $c) {
if ($numMatches > 0 && -1 !== $ofs) {
$ret = (string) $matches[$ofs];
// Echo out remaining chars for current match
$remainingCharacters = substr($ret, \strlen(trim($this->mostRecentlyEnteredValue($fullChoice))));
$output->write($remainingCharacters);
$fullChoice .= $remainingCharacters;
$i = self::strlen($fullChoice);
$matches = array_filter(
$autocomplete($ret),
function ($match) use ($ret) {
return '' === $ret || 0 === strpos($match, $ret);
}
);
$numMatches = \count($matches);
$ofs = -1;
}
if ("\n" === $c) {
$output->write($c);
break;
}
$numMatches = 0;
}
continue;
} else {
if ("\x80" <= $c) {
$c .= fread($inputStream, ["\xC0" => 1, "\xD0" => 1, "\xE0" => 2, "\xF0" => 3][$c & "\xF0"]);
}
$output->write($c);
$ret .= $c;
$fullChoice .= $c;
++$i;
$tempRet = $ret;
if ($question instanceof ChoiceQuestion && $question->isMultiselect()) {
$tempRet = $this->mostRecentlyEnteredValue($fullChoice);
}
$numMatches = 0;
$ofs = 0;
foreach ($autocomplete($ret) as $value) {
// If typed characters match the beginning chunk of value (e.g. [AcmeDe]moBundle)
if (0 === strpos($value, $tempRet)) {
$matches[$numMatches++] = $value;
}
}
}
$cursor->clearLineAfter();
if ($numMatches > 0 && -1 !== $ofs) {
$cursor->savePosition();
// Write highlighted text, complete the partially entered response
$charactersEntered = \strlen(trim($this->mostRecentlyEnteredValue($fullChoice)));
$output->write('<hl>'.OutputFormatter::escapeTrailingBackslash(substr($matches[$ofs], $charactersEntered)).'</hl>');
$cursor->restorePosition();
}
}
// Reset stty so it behaves normally again
shell_exec(sprintf('stty %s', $sttyMode));
return $fullChoice;
}
private function mostRecentlyEnteredValue(string $entered): string
{
// Determine the most recent value that the user entered
if (false === strpos($entered, ',')) {
return $entered;
}
$choices = explode(',', $entered);
if (\strlen($lastChoice = trim($choices[\count($choices) - 1])) > 0) {
return $lastChoice;
}
return $entered;
}
/**
* Gets a hidden response from user.
*
* @param resource $inputStream The handler resource
* @param bool $trimmable Is the answer trimmable
*
* @throws RuntimeException In case the fallback is deactivated and the response cannot be hidden
*/
private function getHiddenResponse(OutputInterface $output, $inputStream, bool $trimmable = true): string
{
if ('\\' === \DIRECTORY_SEPARATOR) {
$exe = __DIR__.'/../Resources/bin/hiddeninput.exe';
// handle code running from a phar
if ('phar:' === substr(__FILE__, 0, 5)) {
$tmpExe = sys_get_temp_dir().'/hiddeninput.exe';
copy($exe, $tmpExe);
$exe = $tmpExe;
}
$sExec = shell_exec($exe);
$value = $trimmable ? rtrim($sExec) : $sExec;
$output->writeln('');
if (isset($tmpExe)) {
unlink($tmpExe);
}
return $value;
}
if (self::$stty && Terminal::hasSttyAvailable()) {
$sttyMode = shell_exec('stty -g');
shell_exec('stty -echo');
} elseif ($this->isInteractiveInput($inputStream)) {
throw new RuntimeException('Unable to hide the response.');
}
$value = fgets($inputStream, 4096);
if (self::$stty && Terminal::hasSttyAvailable()) {
shell_exec(sprintf('stty %s', $sttyMode));
}
if (false === $value) {
throw new MissingInputException('Aborted.');
}
if ($trimmable) {
$value = trim($value);
}
$output->writeln('');
return $value;
}
/**
* Validates an attempt.
*
* @param callable $interviewer A callable that will ask for a question and return the result
*
* @return mixed The validated response
*
* @throws \Exception In case the max number of attempts has been reached and no valid response has been given
*/
private function validateAttempts(callable $interviewer, OutputInterface $output, Question $question)
{
$error = null;
$attempts = $question->getMaxAttempts();
while (null === $attempts || $attempts--) {
if (null !== $error) {
$this->writeError($output, $error);
}
try {
return $question->getValidator()($interviewer());
} catch (RuntimeException $e) {
throw $e;
} catch (\Exception $error) {
}
}
throw $error;
}
private function isInteractiveInput($inputStream): bool
{
if ('php://stdin' !== (stream_get_meta_data($inputStream)['uri'] ?? null)) {
return false;
}
if (null !== self::$stdinIsInteractive) {
return self::$stdinIsInteractive;
}
if (\function_exists('stream_isatty')) {
return self::$stdinIsInteractive = stream_isatty(fopen('php://stdin', 'r'));
}
if (\function_exists('posix_isatty')) {
return self::$stdinIsInteractive = posix_isatty(fopen('php://stdin', 'r'));
}
if (!\function_exists('exec')) {
return self::$stdinIsInteractive = true;
}
exec('stty 2> /dev/null', $output, $status);
return self::$stdinIsInteractive = 1 !== $status;
}
}
| apache-2.0 |
mariaig/intellij-code-analysis-plugin | src/thesis/plugin/impl/RedundantChainExpressionGraph.java | 3955 | package thesis.plugin.impl;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;
/**
* Copyright Maria Igescu
* <p>
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* <p>
* http://www.apache.org/licenses/LICENSE-2.0
* <p>
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
public class RedundantChainExpressionGraph extends ExpressionGraph {
public RedundantChainExpressionGraph(String expression) {
super(expression);
}
public RedundantChainDetails getDetails(String node) {
if (!containsDirectChain(node, node)) {
return null;
}
RedundantChainDetails data = new RedundantChainDetails();
visitRedundantChain(rootId, edges.get(rootId), data, node);
return data;
}
public String getFinalExpression(String node, RedundantChainDetails details, String reducedExpression) {
// need to remove all the nodes that have filter
List<String> chainIds = new ArrayList<>();
getIdsFromTheRedundantChain(details.getParentId(), edges.get(details.getParentId()), details.getLastIdInChain(), chainIds);
for (String id : chainIds) {
methodParametersMap.remove(id);
aliases.remove(id);
edges.remove(id);
}
String newNodeId = UUID.randomUUID().toString() + "_" + node;
aliases.put(newNodeId, node);
methodParametersMap.put(newNodeId, reducedExpression);
edges.put(details.getParentId(), newNodeId);
if (!details.getLastChildId().isEmpty()) {
edges.put(newNodeId, details.getLastChildId());
}
return getFinalExpression();
}
private void visitRedundantChain(String parentId, String childId, RedundantChainDetails data, String node) {
if (childId == null || childId.isEmpty()) {
// not found
return;
}
String nextChildId = edges.get(childId);
String parentNode = aliases.get(parentId);
String childNode = aliases.get(childId);
String nextChildNode = nextChildId != null ? aliases.get(nextChildId) : "";
String value = methodParametersMap.get(childId);
int firstOpenBraceIndex = value.indexOf("(");
int lastClosedBraceIndex = value.lastIndexOf(")");
String exactValueWithoutBraces = value.substring(firstOpenBraceIndex + 1, lastClosedBraceIndex);
if (!parentNode.equals(node) &&
childNode.equals(node) && nextChildNode.equals(node)) {
// found the first direct chain - start saving data from here
data.setParentId(parentId);
data.setFirstIdInChain(childId);
data.addArgument(exactValueWithoutBraces);
} else if (parentNode.equals(node) && childNode.equals(node)) {
data.addArgument(exactValueWithoutBraces);
if(!nextChildNode.equals(node)) {
// at the end of the chain
data.setLastIdInChain(childId);
if(!nextChildNode.isEmpty()) {
data.setLastChildId(nextChildId);
}
return;
}
}
visitRedundantChain(childId, nextChildId, data, node);
}
private void getIdsFromTheRedundantChain(String parentId, String childId, String lastChildId, List<String> chainIds) {
if (childId.equals(lastChildId)) {
return;
}
chainIds.add(childId);
getIdsFromTheRedundantChain(childId, edges.get(childId), lastChildId, chainIds);
}
}
| apache-2.0 |
NakedObjectsGroup/NakedObjectsFramework | NakedFramework/NakedFramework.Persistor.Entity.Test.AdventureWorksCodeOnly/ProductCostHistory.cs | 1323 | // Copyright Naked Objects Group Ltd, 45 Station Road, Henley on Thames, UK, RG9 1AT
// 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.
using System;
using System.ComponentModel.DataAnnotations.Schema;
// ReSharper disable UnusedMember.Global
// ReSharper disable UnusedMember.Local
namespace NakedObjects.Persistor.Entity.Test.AdventureWorksCodeOnly;
[Table("Production.ProductCostHistory")]
public class ProductCostHistory {
[Column(Order = 0)]
[DatabaseGenerated(DatabaseGeneratedOption.None)]
public int ProductID { get; set; }
[Column(Order = 1)]
public DateTime StartDate { get; set; }
public DateTime? EndDate { get; set; }
[Column(TypeName = "money")]
public decimal StandardCost { get; set; }
public DateTime ModifiedDate { get; set; }
public virtual Product Product { get; set; }
} | apache-2.0 |
JesusM/SmartLock-Sample | app/src/androidTest/java/com/jesusm/smartlocksample/MainMenuNavigationTest.java | 2224 | package com.jesusm.smartlocksample;
import android.support.test.rule.ActivityTestRule;
import android.support.test.runner.AndroidJUnit4;
import android.test.suitebuilder.annotation.SmallTest;
import com.jesusm.smartlocksample.ui.MainActivity;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;
import static android.support.test.espresso.Espresso.onView;
import static android.support.test.espresso.action.ViewActions.click;
import static android.support.test.espresso.assertion.ViewAssertions.matches;
import static android.support.test.espresso.matcher.ViewMatchers.isDisplayed;
import static android.support.test.espresso.matcher.ViewMatchers.withId;
@RunWith(AndroidJUnit4.class)
@SmallTest
public class MainMenuNavigationTest {
/**
* A JUnit {@link Rule @Rule} to launch your activity under test. This is a replacement
* for {@link ActivityInstrumentationTestCase2}.
* <p/>
* Rules are interceptors which are executed for each test method and will run before
* any of your setup code in the {@link Before @Before} method.
* <p/>
* {@link ActivityTestRule} will create and launch of the activity for you and also expose
* the activity under test. To get a reference to the activity you can use
* the {@link ActivityTestRule#getActivity()} method.
*/
@Rule
public ActivityTestRule<MainActivity> activityTestRule = new ActivityTestRule<>(
MainActivity.class);
@Test
public void main_menu_open_google_signin_sample() {
navigateToGoogleSample();
// Check that the fragment has been inflated was changed.
onView(withId(R.id.statusText)).check(matches(isDisplayed()));
}
private void navigateToGoogleSample() {
onView(withId(R.id.googleSignInButton)).perform(click());
}
@Test
public void main_menu_open_common_sample() {
navigateToOrdinarySample();
// Check that the fragment has been inflated was changed.
onView(withId(R.id.email_login_form)).check(matches(isDisplayed()));
}
private void navigateToOrdinarySample() {
onView(withId(R.id.ordinarySampleButton)).perform(click());
}
}
| apache-2.0 |
InspectorConstructor/lemon-webgl | a6.php | 4385 | <!DOCTYPE html>
<!--
Nicholas St.Pierre
Student of UML CS course 91.461, GUI Programming
nstpierr@cs.uml.edu
10.22.2013
Assignment number six
This file was adapted from Jesse Heines' HTML template. Original header block follows:
Copied File: /~heines/91.461/91.461-2012-13f/461-lecs/code/j1.html
Jesse M. Heines, UMass Lowell Computer Science, heines@cs.uml.edu
Copyright (c) 2012 by Jesse M. Heines. All rights reserved. May be freely
copied or excerpted for educational purposes with credit to the author.
-->
<html>
<head>
<title>Assignment Six</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<!-- css reset file. credit link contained within the file. -->
<link rel="stylesheet" type="text/css" href="css/RESET.css" />
<!-- get jQuery -->
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<!-- get jQuery validation plugin -->
<script src="http://ajax.aspnetcdn.com/ajax/jquery.validate/1.11.1/jquery.validate.min.js"></script>
<!-- from Google: NOTO SANS and Lusitana web fonts. -->
<link href='http://fonts.googleapis.com/css?family=Noto+Sans|Lusitana:700|Titillium+Web:400,200' rel='stylesheet' type='text/css'>
<!-- My common style sheet. -->
<link rel="stylesheet" type="text/css" href="css/common.css" />
<!-- CSS specific to this assignment. -->
<link rel="stylesheet" type="text/css" href="css/a5.css" />
<!-- professor heines' form utilities code. credit within. -->
<script type="text/javascript" src="script/formUtilities.js"></script>
<!-- Contains the main javascript for this assignment. -->
<script type="text/javascript" src="script/a6.js"></script>
</head>
<body onload="makeTableIfPossible();">
<!-- this onLoad function fires after the page is loaded. it creates the table if possible. -->
<?php include 'navbar.inc.html'; // include the navbar from a file! ?>
<!-- instructions box -->
<div class="backgroundBox" >
<!-- casual introduction -->
<h1>Assignment 6</h1>
<h2>Using the jQuery Validation Plugin with Your Dynamic Table</h2>
<br>
<p>
Welcome to my sixth assignment for GUI Programming 1!
This assignment is all about form validation. The following form will create a multiplication table from the input data.
Enter numbers between one and forty two into the column and row boxes, and any number into the row and column start boxes.
Then click the submit button to generate a multiplication table.
</p>
</div>
<br>
<!-- the form and output -->
<div class="cleanBox"> <!-- a div for style -->
<div id="input" class="backgroundBox" >
<!-- error summary will appear here if needed. -->
<p id='summary'></p>
<!-- our input form! -->
<form id="inputForm" action="a6.php" > <!-- onsubmit="return validateInput();"-->
<!-- a simple table to align our input controls. please don't hate me. -->
<table>
<tr><td><label for="inputCols">columns</label></td><td><input type="number" name="inputCols" id="inputCols" class="input-positiveInt" /></td></tr>
<tr><td><label for="inputRows">rows</label></td><td> <input type="number" name="inputRows" id="inputRows" class="input-positiveInt" /></td></tr>
<tr><td><label for="inputStartCols">column start</label></td><td><input type="number" name="inputStartCols" id="inputStartCols" class="input-Int" /></td></tr>
<tr><td><label for="inputStartRows">row start</label></td><td><input type="number" name="inputStartRows" id="inputStartRows" class="input-Int" /></td></tr>
</table>
<br>
<input type="submit" name="Submit!" value="go" />
</form>
</div>
<!-- semi empty div for the result -->
<div id="output" class="backgroundBox loose">
<p>The table will appear here after you submit the form!</p>
</div>
</div>
<!-- the css icon -->
<p id="css-icon">
<a href="http://jigsaw.w3.org/css-validator/check/referer">
<img style="border:0;width:88px;height:31px"
src="http://jigsaw.w3.org/css-validator/images/vcss"
alt="Valid CSS!" />
</a>
</p>
</body>
</html>
| apache-2.0 |
technige/py2neo | test/unit/cypher/test_queries.py | 14947 | #!/usr/bin/env python
# -*- encoding: utf-8 -*-
# Copyright 2011-2021, Nigel Small
#
# 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.
from collections import OrderedDict
from pytest import mark, fixture
from py2neo.cypher.queries import (
unwind_create_nodes_query,
unwind_merge_nodes_query,
unwind_create_relationships_query,
unwind_merge_relationships_query,
)
@fixture
def node_keys():
return ["name", "family name", "age"]
@fixture
def node_data_lists():
return [
["Alice", "Allison", 33],
["Bob", "Robertson", 44],
["Carol", "Carlson", 55],
["Alice", "Smith", 66],
]
@fixture
def node_data_dicts(node_data_lists, node_keys):
data = [OrderedDict(zip(node_keys, a)) for a in node_data_lists]
data[1]["nickname"] = "Bobby"
del data[2]["age"]
return data
@fixture
def rel_type():
return "WORKS_FOR"
@fixture
def rel_keys():
return ["employee id", "job title", "since"]
@fixture
def rel_data_lists():
return [
("Alice", [1, "CEO", 1990], "ACME"),
("Bob", [123, "PA", 1999], "ACME"),
("Carol", [555, "Programmer", 2010], "Foo Corp"),
]
@fixture
def rel_data_lists_double_key():
return [
(("Alice", "Smith"), [1, "CEO", 1990], "ACME"),
(("Bob", "Jones"), [123, "PA", 1999], "ACME"),
(("Carol", "Brown"), [555, "Programmer", 2010], "Foo Corp"),
]
@fixture
def rel_data_lists_no_key():
return [
("Alice", [1, "CEO", 1990], None),
("Bob", [123, "PA", 1999], None),
("Carol", [555, "Programmer", 2010], None),
]
@fixture
def rel_data_dicts(rel_data_lists, rel_keys):
data = [(a, OrderedDict(zip(rel_keys, r)), b) for a, r, b in rel_data_lists]
return data
@fixture
def rel_data_dicts_with_mono_tuples(rel_data_lists, rel_keys):
data = [((a,), OrderedDict(zip(rel_keys, r)), (b,)) for a, r, b in rel_data_lists]
return data
@fixture
def start_node_key():
return "Person", "name"
@fixture
def start_node_double_key():
return "Person", "name", "family name"
@fixture
def end_node_key():
return "Company", "name"
class TestUnwindCreateNodesQuery(object):
def test_dict_data(self, node_data_dicts):
q, p = unwind_create_nodes_query(node_data_dicts)
assert q == ("UNWIND $data AS r\n"
"CREATE (_)\n"
"SET _ += r")
assert p == {"data": node_data_dicts}
def test_list_data(self, node_data_lists, node_keys):
q, p = unwind_create_nodes_query(node_data_lists, keys=node_keys)
assert q == ("UNWIND $data AS r\n"
"CREATE (_)\n"
"SET _ += {name: r[0], `family name`: r[1], age: r[2]}")
assert p == {"data": node_data_lists}
def test_with_one_label(self, node_data_dicts):
q, p = unwind_create_nodes_query(node_data_dicts, labels=["Person"])
assert q == ("UNWIND $data AS r\n"
"CREATE (_:Person)\n"
"SET _ += r")
assert p == {"data": node_data_dicts}
def test_with_two_labels(self, node_data_dicts):
q, p = unwind_create_nodes_query(node_data_dicts, labels=["Person", "Employee"])
assert q == ("UNWIND $data AS r\n"
"CREATE (_:Employee:Person)\n"
"SET _ += r")
assert p == {"data": node_data_dicts}
class TestUnwindMergeNodesQuery(object):
def test_dict_data(self, node_data_dicts):
q, p = unwind_merge_nodes_query(node_data_dicts, ("Person", "name"))
assert q == ("UNWIND $data AS r\n"
"MERGE (_:Person {name:r['name']})\n"
"SET _ += r")
assert p == {"data": node_data_dicts}
def test_list_data(self, node_data_lists, node_keys):
q, p = unwind_merge_nodes_query(node_data_lists, ("Person", "name"), keys=node_keys)
assert q == ("UNWIND $data AS r\n"
"MERGE (_:Person {name:r[0]})\n"
"SET _ += {name: r[0], `family name`: r[1], age: r[2]}")
assert p == {"data": node_data_lists}
def test_with_extra_labels(self, node_data_dicts):
q, p = unwind_merge_nodes_query(node_data_dicts, ("Person", "name"),
labels=["Human", "Employee"])
assert q == ("UNWIND $data AS r\n"
"MERGE (_:Person {name:r['name']})\n"
"SET _ += r\n"
"SET _:Employee:Human")
assert p == {"data": node_data_dicts}
@mark.parametrize("merge_key", ["Person", ("Person",)])
def test_with_no_merge_keys(self, node_data_dicts, merge_key):
q, p = unwind_merge_nodes_query(node_data_dicts, "Person")
assert q == ("UNWIND $data AS r\n"
"MERGE (_:Person)\n"
"SET _ += r")
assert p == {"data": node_data_dicts}
def test_with_one_merge_key(self, node_data_dicts):
q, p = unwind_merge_nodes_query(node_data_dicts, ("Person", "name"))
assert q == ("UNWIND $data AS r\n"
"MERGE (_:Person {name:r['name']})\n"
"SET _ += r")
assert p == {"data": node_data_dicts}
def test_with_two_merge_keys(self, node_data_dicts):
q, p = unwind_merge_nodes_query(node_data_dicts, ("Person", "name", "family name"))
assert q == ("UNWIND $data AS r\n"
"MERGE (_:Person {name:r['name'], `family name`:r['family name']})\n"
"SET _ += r")
assert p == {"data": node_data_dicts}
def test_list_data_with_preservation(self, node_data_lists, node_keys):
q, p = unwind_merge_nodes_query(node_data_lists, ("Person", "name"), keys=node_keys,
preserve=["age"])
assert q == ("UNWIND $data AS r\n"
"MERGE (_:Person {name:r[0]})\n"
"ON CREATE SET _ += {age: r[2]}\n"
"SET _ += {name: r[0], `family name`: r[1]}")
assert p == {"data": node_data_lists}
class TestUnwindCreateRelationshipsQuery(object):
def test_dict_data(self, rel_data_dicts, rel_type):
q, p = unwind_create_relationships_query(rel_data_dicts, rel_type)
assert q == ("UNWIND $data AS r\n"
"MATCH (a) WHERE id(a) = r[0]\n"
"MATCH (b) WHERE id(b) = r[2]\n"
"CREATE (a)-[_:WORKS_FOR]->(b)\n"
"SET _ += r[1]")
assert p == {"data": rel_data_dicts}
def test_list_data(self, rel_data_lists, rel_type, rel_keys):
q, p = unwind_create_relationships_query(rel_data_lists, rel_type, keys=rel_keys)
assert q == ("UNWIND $data AS r\n"
"MATCH (a) WHERE id(a) = r[0]\n"
"MATCH (b) WHERE id(b) = r[2]\n"
"CREATE (a)-[_:WORKS_FOR]->(b)\n"
"SET _ += {`employee id`: r[1][0], `job title`: r[1][1], since: r[1][2]}")
assert p == {"data": rel_data_lists}
def test_with_start_node_key(self, rel_data_dicts, rel_type, start_node_key):
q, p = unwind_create_relationships_query(rel_data_dicts, rel_type,
start_node_key=start_node_key)
assert q == ("UNWIND $data AS r\n"
"MATCH (a:Person {name:r[0]})\n"
"MATCH (b) WHERE id(b) = r[2]\n"
"CREATE (a)-[_:WORKS_FOR]->(b)\n"
"SET _ += r[1]")
assert p == {"data": rel_data_dicts}
def test_with_end_node_key(self, rel_data_dicts, rel_type, end_node_key):
q, p = unwind_create_relationships_query(rel_data_dicts, rel_type,
end_node_key=end_node_key)
assert q == ("UNWIND $data AS r\n"
"MATCH (a) WHERE id(a) = r[0]\n"
"MATCH (b:Company {name:r[2]})\n"
"CREATE (a)-[_:WORKS_FOR]->(b)\n"
"SET _ += r[1]")
assert p == {"data": rel_data_dicts}
def test_with_start_and_end_node_keys(self, rel_data_dicts, rel_type,
start_node_key, end_node_key):
q, p = unwind_create_relationships_query(rel_data_dicts, rel_type,
start_node_key=start_node_key,
end_node_key=end_node_key)
assert q == ("UNWIND $data AS r\n"
"MATCH (a:Person {name:r[0]})\n"
"MATCH (b:Company {name:r[2]})\n"
"CREATE (a)-[_:WORKS_FOR]->(b)\n"
"SET _ += r[1]")
assert p == {"data": rel_data_dicts}
def test_with_start_node_double_key(self, rel_data_lists_double_key, rel_keys,
rel_type, start_node_double_key):
q, p = unwind_create_relationships_query(rel_data_lists_double_key, rel_type,
start_node_key=start_node_double_key,
keys=rel_keys)
assert q == ("UNWIND $data AS r\n"
"MATCH (a:Person {name:r[0][0], `family name`:r[0][1]})\n"
"MATCH (b) WHERE id(b) = r[2]\n"
"CREATE (a)-[_:WORKS_FOR]->(b)\n"
"SET _ += {`employee id`: r[1][0], `job title`: r[1][1], since: r[1][2]}")
assert p == {"data": rel_data_lists_double_key}
def test_with_start_node_no_keys(self, rel_data_lists_no_key, rel_type, rel_keys,
start_node_key):
q, p = unwind_create_relationships_query(rel_data_lists_no_key, rel_type,
start_node_key=start_node_key,
end_node_key="Company", keys=rel_keys)
assert q == ("UNWIND $data AS r\n"
"MATCH (a:Person {name:r[0]})\n"
"MATCH (b:Company)\n"
"CREATE (a)-[_:WORKS_FOR]->(b)\n"
"SET _ += {`employee id`: r[1][0], `job title`: r[1][1], since: r[1][2]}")
assert p == {"data": rel_data_lists_no_key}
def test_with_mono_tuples(self, rel_data_dicts, rel_data_dicts_with_mono_tuples, rel_type):
q, p = unwind_create_relationships_query(rel_data_dicts_with_mono_tuples, rel_type)
assert q == ("UNWIND $data AS r\n"
"MATCH (a) WHERE id(a) = r[0]\n"
"MATCH (b) WHERE id(b) = r[2]\n"
"CREATE (a)-[_:WORKS_FOR]->(b)\n"
"SET _ += r[1]")
assert p == {"data": rel_data_dicts}
class TestUnwindMergeRelationshipsQuery(object):
def test_dict_data(self, rel_data_dicts, rel_type):
q, p = unwind_merge_relationships_query(rel_data_dicts, ("WORKS_FOR", "employee id"))
assert q == ("UNWIND $data AS r\n"
"MATCH (a) WHERE id(a) = r[0]\n"
"MATCH (b) WHERE id(b) = r[2]\n"
"MERGE (a)-[_:WORKS_FOR {`employee id`:r[1]['employee id']}]->(b)\n"
"SET _ += r[1]")
assert p == {"data": rel_data_dicts}
def test_list_data(self, rel_data_lists, rel_type, rel_keys):
q, p = unwind_merge_relationships_query(rel_data_lists, ("WORKS_FOR", "employee id"),
keys=rel_keys)
assert q == ("UNWIND $data AS r\n"
"MATCH (a) WHERE id(a) = r[0]\n"
"MATCH (b) WHERE id(b) = r[2]\n"
"MERGE (a)-[_:WORKS_FOR {`employee id`:r[1][0]}]->(b)\n"
"SET _ += {`employee id`: r[1][0], `job title`: r[1][1], since: r[1][2]}")
assert p == {"data": rel_data_lists}
def test_with_start_node_key(self, rel_data_dicts, rel_type, start_node_key):
q, p = unwind_merge_relationships_query(rel_data_dicts, ("WORKS_FOR", "employee id"),
start_node_key=start_node_key)
assert q == ("UNWIND $data AS r\n"
"MATCH (a:Person {name:r[0]})\n"
"MATCH (b) WHERE id(b) = r[2]\n"
"MERGE (a)-[_:WORKS_FOR {`employee id`:r[1]['employee id']}]->(b)\n"
"SET _ += r[1]")
assert p == {"data": rel_data_dicts}
def test_with_end_node_key(self, rel_data_dicts, rel_type, end_node_key):
q, p = unwind_merge_relationships_query(rel_data_dicts, ("WORKS_FOR", "employee id"),
end_node_key=end_node_key)
assert q == ("UNWIND $data AS r\n"
"MATCH (a) WHERE id(a) = r[0]\n"
"MATCH (b:Company {name:r[2]})\n"
"MERGE (a)-[_:WORKS_FOR {`employee id`:r[1]['employee id']}]->(b)\n"
"SET _ += r[1]")
assert p == {"data": rel_data_dicts}
def test_with_start_and_end_node_keys(self, rel_data_dicts, rel_type,
start_node_key, end_node_key):
q, p = unwind_merge_relationships_query(rel_data_dicts, ("WORKS_FOR", "employee id"),
start_node_key=start_node_key,
end_node_key=end_node_key)
assert q == ("UNWIND $data AS r\n"
"MATCH (a:Person {name:r[0]})\n"
"MATCH (b:Company {name:r[2]})\n"
"MERGE (a)-[_:WORKS_FOR {`employee id`:r[1]['employee id']}]->(b)\n"
"SET _ += r[1]")
assert p == {"data": rel_data_dicts}
def test_list_data_with_preservation(self, rel_data_lists, rel_type, rel_keys):
q, p = unwind_merge_relationships_query(rel_data_lists, ("WORKS_FOR", "employee id"),
keys=rel_keys, preserve=["since"])
assert q == ("UNWIND $data AS r\n"
"MATCH (a) WHERE id(a) = r[0]\n"
"MATCH (b) WHERE id(b) = r[2]\n"
"MERGE (a)-[_:WORKS_FOR {`employee id`:r[1][0]}]->(b)\n"
"ON CREATE SET _ += {since: r[1][2]}\n"
"SET _ += {`employee id`: r[1][0], `job title`: r[1][1]}")
assert p == {"data": rel_data_lists}
| apache-2.0 |
NAUMEN-GP/saiku | saiku-core/saiku-web/src/main/java/org/saiku/web/rest/resources/ExporterResource.java | 11999 | /*
* Copyright 2012 OSBI 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 org.saiku.web.rest.resources;
import org.saiku.olap.query2.ThinQuery;
import org.saiku.web.rest.objects.resultset.QueryResult;
import org.saiku.web.rest.util.ServletUtil;
import org.saiku.web.svg.Converter;
import com.lowagie.text.Image;
import com.lowagie.text.pdf.PdfContentByte;
import com.lowagie.text.pdf.PdfReader;
import com.lowagie.text.pdf.PdfStamper;
import org.apache.commons.lang.StringUtils;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.pdmodel.PDPage;
import org.apache.pdfbox.pdmodel.PDPageTree;
import org.apache.pdfbox.rendering.PDFRenderer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;
import java.util.UUID;
import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import javax.ws.rs.*;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.Response.Status;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
/**
* QueryServlet contains all the methods required when manipulating an OLAP Query.
* @author Paul Stoellberger
*
*/
@Component
@Path("/saiku/{username}/export")
@XmlAccessorType(XmlAccessType.NONE)
public class ExporterResource {
private static final Logger log = LoggerFactory.getLogger(ExporterResource.class);
private ISaikuRepository repository;
private Query2Resource query2Resource;
public void setQuery2Resource(Query2Resource qr){
this.query2Resource = qr;
}
public void setRepository(ISaikuRepository repository){
this.repository = repository;
}
@GET
@Produces({"application/json" })
@Path("/saiku/xls")
public Response exportExcel(@QueryParam("file") String file,
@QueryParam("formatter") String formatter,@QueryParam("name") String name,
@Context HttpServletRequest servletRequest)
{
try {
Response f = repository.getResource(file);
String fileContent = new String( (byte[]) f.getEntity());
String queryName = UUID.randomUUID().toString();
//fileContent = ServletUtil.replaceParameters(servletRequest, fileContent);
// queryResource.createQuery(queryName, null, null, null, fileContent, queryName, null);
// queryResource.execute(queryName, formatter, 0);
Map<String, String> parameters = ServletUtil.getParameters(servletRequest);
ThinQuery tq = query2Resource.createQuery(queryName, fileContent, null, null);
if (parameters != null) {
tq.getParameters().putAll(parameters);
}
if (StringUtils.isNotBlank(formatter)) {
HashMap<String, Object> p = new HashMap<String, Object>();
p.put("saiku.olap.result.formatter", formatter);
if (tq.getProperties() == null) {
tq.setProperties(p);
} else {
tq.getProperties().putAll(p);
}
}
query2Resource.execute(tq);
return query2Resource.getQueryExcelExport(queryName, formatter, name);
} catch (Exception e) {
log.error("Error exporting XLS for file: " + file, e);
return Response.serverError().entity(e.getMessage()).status(Status.INTERNAL_SERVER_ERROR).build();
}
}
@GET
@Produces({"application/json" })
@Path("/saiku/csv")
public Response exportCsv(@QueryParam("file") String file,
@QueryParam("formatter") String formatter,
@Context HttpServletRequest servletRequest)
{
try {
Response f = repository.getResource(file);
String fileContent = new String( (byte[]) f.getEntity());
//fileContent = ServletUtil.replaceParameters(servletRequest, fileContent);
String queryName = UUID.randomUUID().toString();
// query2Resource.createQuery(null, null, null, null, fileContent, queryName, null);
// query2Resource.execute(queryName,formatter, 0);
Map<String, String> parameters = ServletUtil.getParameters(servletRequest);
ThinQuery tq = query2Resource.createQuery(queryName, fileContent, null, null);
if (parameters != null) {
tq.getParameters().putAll(parameters);
}
if (StringUtils.isNotBlank(formatter)) {
HashMap<String, Object> p = new HashMap<String, Object>();
p.put("saiku.olap.result.formatter", formatter);
if (tq.getProperties() == null) {
tq.setProperties(p);
} else {
tq.getProperties().putAll(p);
}
}
query2Resource.execute(tq);
return query2Resource.getQueryCsvExport(queryName);
} catch (Exception e) {
log.error("Error exporting CSV for file: " + file, e);
return Response.serverError().entity(e.getMessage()).status(Status.INTERNAL_SERVER_ERROR).build();
}
}
@GET
@Produces({"application/json" })
@Path("/saiku/json")
public Response exportJson(@QueryParam("file") String file,
@QueryParam("formatter") String formatter,
@Context HttpServletRequest servletRequest)
{
try {
Response f = repository.getResource(file);
String fileContent = new String( (byte[]) f.getEntity());
fileContent = ServletUtil.replaceParameters(servletRequest, fileContent);
String queryName = UUID.randomUUID().toString();
// query2Resource.createQuery(null, null, null, null, fileContent, queryName, null);
// QueryResult qr = query2Resource.execute(queryName, formatter, 0);
Map<String, String> parameters = ServletUtil.getParameters(servletRequest);
ThinQuery tq = query2Resource.createQuery(queryName, fileContent, null, null);
if (parameters != null) {
tq.getParameters().putAll(parameters);
}
if (StringUtils.isNotBlank(formatter)) {
HashMap<String, Object> p = new HashMap<String, Object>();
p.put("saiku.olap.result.formatter", formatter);
if (tq.getProperties() == null) {
tq.setProperties(p);
} else {
tq.getProperties().putAll(p);
}
}
QueryResult qr = query2Resource.execute(tq);
return Response.ok().entity(qr).build();
} catch (Exception e) {
log.error("Error exporting JSON for file: " + file, e);
return Response.serverError().entity(e.getMessage()).status(Status.INTERNAL_SERVER_ERROR).build();
}
}
@GET
@Produces({"text/html" })
@Path("/saiku/html")
public Response exportHtml(@QueryParam("file") String file,
@QueryParam("formatter") String formatter,
@QueryParam("css") @DefaultValue("false") Boolean css,
@QueryParam("tableonly") @DefaultValue("false") Boolean tableonly,
@QueryParam("wrapcontent") @DefaultValue("true") Boolean wrapcontent,
@Context HttpServletRequest servletRequest)
{
try {
Response f = repository.getResource(file);
String fileContent = new String( (byte[]) f.getEntity());
fileContent = ServletUtil.replaceParameters(servletRequest, fileContent);
String queryName = UUID.randomUUID().toString();
query2Resource.createQuery(queryName, fileContent, null, null);
return query2Resource.exportHtml(queryName, formatter, css, tableonly, wrapcontent);
} catch (Exception e) {
log.error("Error exporting JSON for file: " + file, e);
return Response.serverError().entity(e.getMessage()).status(Status.INTERNAL_SERVER_ERROR).build();
}
}
@POST
@Produces({"image/*" })
@Path("/saiku/chart")
public Response exportChart(
@FormParam("type") @DefaultValue("png") String type,
@FormParam("svg") String svg,
@FormParam("size") Integer size,
@FormParam("name") String name)
{
try {
final String imageType = type.toUpperCase();
Converter converter = Converter.byType("PDF");
if (converter == null)
{
throw new Exception("Image convert is null");
}
// resp.setContentType(converter.getContentType());
// resp.setHeader("Content-disposition", "attachment; filename=chart." + converter.getExtension());
// final Integer size = req.getParameter("size") != null? Integer.parseInt(req.getParameter("size")) : null;
// final String svgDocument = req.getParameter("svg");
// if (svgDocument == null)
// {
// resp.sendError(HttpServletResponse.SC_BAD_REQUEST, "Missing 'svg' parameter");
// return;
// }
if (StringUtils.isBlank(svg)) {
throw new Exception("Missing 'svg' parameter");
}
final InputStream in = new ByteArrayInputStream(svg.getBytes("UTF-8"));
final ByteArrayOutputStream out = new ByteArrayOutputStream();
converter.convert(in, out, size);
out.flush();
byte[] doc = out.toByteArray();
byte[] b = null;
if(getVersion()!=null && !getVersion().contains("EE")) {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
PdfReader reader = new PdfReader(doc);
PdfStamper pdfStamper = new PdfStamper(reader,
baos);
URL dir_url = ExporterResource.class.getResource("/org/saiku/web/svg/watermark.png");
Image image = Image.getInstance(dir_url);
for (int i = 1; i <= reader.getNumberOfPages(); i++) {
PdfContentByte content = pdfStamper.getOverContent(i);
image.setAbsolutePosition(450f, 280f);
/*image.setAbsolutePosition(reader.getPageSize(1).getWidth() - image.getScaledWidth(), reader.getPageSize
(1).getHeight() - image.getScaledHeight());*/
//image.setAlignment(Image.MIDDLE);
content.addImage(image);
}
pdfStamper.close();
b = baos.toByteArray();
}
else{
b = doc;
}
if(!type.equals("pdf")) {
PDDocument document = PDDocument.load(new ByteArrayInputStream(b), null);
PDPageTree pdPages = document.getDocumentCatalog().getPages();
PDPage page = pdPages.get(0);
BufferedImage o = new PDFRenderer(document).renderImage(0);
ByteArrayOutputStream imgb = new ByteArrayOutputStream();
String ct = "";
String ext = "";
if(type.equals("png")){
ct = "image/png";
ext = "png";
}
else if(type.equals("jpg")){
ct = "image/jpg";
ext = "jpg";
}
ImageIO.write(o, type, imgb);
byte[] outfile = imgb.toByteArray();
if(name == null || name.equals("")){
name = "chart";
}
return Response.ok(outfile).type(ct).header(
"content-disposition",
"attachment; filename = "+name+"." + ext).header(
"content-length", outfile.length).build();
}
else{
if(name == null || name.equals("")){
name = "chart";
}
return Response.ok(b).type(converter.getContentType()).header(
"content-disposition",
"attachment; filename = "+name+"." + converter.getExtension()).header(
"content-length", b.length).build();
}
} catch (Exception e) {
log.error("Error exporting Chart to " + type, e);
return Response.serverError().entity(e.getMessage()).status(Status.INTERNAL_SERVER_ERROR).build();
}
}
public static String getVersion() {
Properties prop = new Properties();
InputStream input = null;
String version = "";
ClassLoader classloader = Thread.currentThread().getContextClassLoader();
InputStream is = classloader.getResourceAsStream("org/saiku/web/rest/resources/version.properties");
try {
//input = new FileInputStream("version.properties");
// load a properties file
prop.load(is);
// get the property value and print it out
System.out.println(prop.getProperty("VERSION"));
version = prop.getProperty("VERSION");
} catch (IOException e) {
e.printStackTrace();
}
return version;
}
}
| apache-2.0 |
hanguokai/youku | test/config.py | 368 | # -*- coding: utf-8 -*-
import json
# data for test, please replace it to yours
CLIENT_ID = 'your client id'
CLIENT_SECRET = 'your client secret'
REDIRECT_URI = 'http://127.0.0.1:5000/youku/authorize'
ACCESS_TOKEN = 'your access token'
USER_ID = '419384312'
USER_NAME = u'\u97e9\u56fd\u607a'
def print_json(obj):
print json.dumps(obj, indent=4, sort_keys=True)
| apache-2.0 |
cc387885389/Test | codegeneration/src/main/java/code/TempFactory.java | 929 | package code;
import java.util.List;
public class TempFactory {
public void createTemp(String name){
TempInfoManager tif = new TempInfoManager();
List<Info> listInfo = tif.analysis(name);
for(Info info : listInfo){
String outPutPath = info.getOutPutfilePath()+info.getPath();
String outPutFileName = info.getClassName()+"."+info.getType();
String templatePath = getClass().getResource("/").getFile().toString();
String templateName = info.getTempName();
Object modelValue = info;
if(info.getTableName() != null && !info.getTableName().equals("")){
modelValue = MapperManager.createDate(info);
}
FreeMarkerUtil.createTemplate(modelValue, outPutPath, outPutFileName, templatePath, templateName);
System.out.println(outPutFileName+" 创建成功!");
}
}
public static void main(String[] args) {
TempFactory factory = new TempFactory();
factory.createTemp("Student");
}
}
| apache-2.0 |
mengxr/spark-pr-dashboard | static/js/views/TableView.js | 4073 | define([
'react',
'jquery',
'underscore'
],
function(React, $, _) {
"use strict";
var ColumnHeader = React.createClass({displayName: 'ColumnHeader',
propTypes: {
name: React.PropTypes.string.isRequired,
sortable: React.PropTypes.bool.isRequired,
onSort: React.PropTypes.func.isRequired,
sortDirection: React.PropTypes.oneOf(['asc', 'desc', 'unsorted'])
},
getDefaultProps: function() {
return {
sortable: true,
sortDirection: 'unsorted'
};
},
sortDirectionIndicator: function() {
if (this.props.sortDirection === 'asc') {
return (React.createElement("span", null, " ▾"));
} else if (this.props.sortDirection === 'desc') {
return (React.createElement("span", null, " ▴"));
} else {
return '';
}
},
onSort: function() {
this.props.onSort(this.props.name);
},
render: function() {
return (
React.createElement("th", {onClick: this.onSort},
this.props.name, this.sortDirectionIndicator()
)
);
}
});
/**
* A table view that supports customizable per-column sorting.
*/
var TableView = React.createClass({displayName: 'TableView',
propTypes: {
rows: React.PropTypes.arrayOf(React.PropTypes.element).isRequired,
columnNames: React.PropTypes.arrayOf(React.PropTypes.string).isRequired,
sortFunctions: React.PropTypes.objectOf(React.PropTypes.func).isRequired,
initialSortCol: React.PropTypes.string,
initialSortDirection: React.PropTypes.string,
},
getInitialState: function() {
return {
sortCol: this.props.initialSortCol || '',
sortDirection: this.props.initialSortDirection || 'unsorted'
};
},
componentWillMount: function() {
this.doSort(this.state.sortCol, this.state.sortDirection, this.props.rows);
},
componentWillReceiveProps: function(newProps) {
this.doSort(this.state.sortCol, this.state.sortDirection, newProps.rows);
},
doSort: function(sortCol, sortDirection, sortedRows) {
// Sort the rows in this table and update its state
var newSortedRows = _.sortBy(sortedRows, this.props.sortFunctions[sortCol]);
if (sortDirection === 'desc') {
newSortedRows.reverse();
}
this.setState({sortCol: sortCol, sortDirection: sortDirection, sortedRows: newSortedRows});
},
onSort: function(sortCol) {
// Callback when a user clicks on a column header to perform a sort.
// Handles the logic of toggling sort directions
var sortDirection;
if (sortCol === this.state.sortCol) {
if (this.state.sortDirection === 'unsorted' || this.state.sortDirection === 'asc') {
sortDirection = 'desc';
} else if (this.state.sortDirection === 'desc') {
sortDirection = 'asc';
}
} else {
sortDirection = 'desc';
}
this.doSort(sortCol, sortDirection, this.state.sortedRows);
},
render: function() {
var _this = this;
var tableHeaders = _.map(this.props.columnNames, function(colName) {
var sortDirection = (colName === _this.state.sortCol ?
_this.state.sortDirection :
'unsorted');
return (
React.createElement(ColumnHeader, {
key: colName,
name: colName,
onSort: _this.onSort,
sortDirection: sortDirection}));
});
return (
React.createElement("table", {className: "table table-condensed table-hover"},
React.createElement("thead", null,
React.createElement("tr", null, tableHeaders)
),
React.createElement("tbody", null,
this.state.sortedRows
)
)
);
}
});
return TableView;
}
);
| apache-2.0 |
google/vr180 | java/com/google/vr180/api/internal/CameraInternalApiHandler.java | 3918 | // Copyright 2018 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.vr180.api.internal;
import android.support.annotation.Nullable;
import com.google.vr180.CameraInternalApi.CameraInternalApiRequest;
import com.google.vr180.CameraInternalApi.CameraInternalApiResponse;
import com.google.vr180.CameraInternalApi.CameraInternalApiResponse.ResponseStatus;
import com.google.vr180.CameraInternalApi.CameraInternalApiResponse.ResponseStatus.StatusCode;
import com.google.vr180.api.camerainterfaces.PairingManager;
/** Handler of camera internal API requests. */
public class CameraInternalApiHandler {
private final PairingManager pairingManager;
private final CameraInternalStatusManager cameraInternalStatusManager;
public CameraInternalApiHandler(
@Nullable PairingManager pairingManager,
CameraInternalStatusManager cameraInternalStatusManager) {
this.pairingManager = pairingManager;
this.cameraInternalStatusManager = cameraInternalStatusManager;
}
/** Handles camera internal API requests. */
public CameraInternalApiResponse handleInternalRequest(
CameraInternalApiRequest request) {
switch (request.getRequestType()) {
case UNKNOWN:
return getInvalidResponse();
case INTERNAL_STATUS:
return CameraInternalApiResponse.newBuilder()
.setResponseStatus(ResponseStatus.newBuilder().setStatusCode(StatusCode.OK).build())
.setInternalStatus(cameraInternalStatusManager.getCameraInternalStatus())
.build();
case START_PAIRING:
if (pairingManager != null) {
pairingManager.startPairing();
return getOkResponse();
} else {
return getNotSupportedResponse();
}
case CONFIRM_PAIRING:
if (pairingManager != null) {
pairingManager.confirmPairing();
return getOkResponse();
} else {
return getNotSupportedResponse();
}
case CANCEL_PAIRING:
if (pairingManager != null) {
pairingManager.stopPairing();
return getOkResponse();
} else {
return getNotSupportedResponse();
}
case CONFIGURE:
if (!request.hasConfigurationRequest()) {
return getInvalidResponse();
}
CameraInternalApiRequest.ConfigurationRequest configurationRequest =
request.getConfigurationRequest();
if (configurationRequest.hasCameraState()) {
cameraInternalStatusManager.onCameraStateChanged(configurationRequest.getCameraState());
}
return getOkResponse();
}
return getInvalidResponse();
}
private static CameraInternalApiResponse getOkResponse() {
return CameraInternalApiResponse.newBuilder()
.setResponseStatus(ResponseStatus.newBuilder().setStatusCode(StatusCode.OK).build())
.build();
}
private static CameraInternalApiResponse getInvalidResponse() {
return CameraInternalApiResponse.newBuilder()
.setResponseStatus(
ResponseStatus.newBuilder().setStatusCode(StatusCode.INVALID_REQUEST).build())
.build();
}
private static CameraInternalApiResponse getNotSupportedResponse() {
return CameraInternalApiResponse.newBuilder()
.setResponseStatus(
ResponseStatus.newBuilder().setStatusCode(StatusCode.NOT_SUPPORTED).build())
.build();
}
}
| apache-2.0 |
JasonJunjian/FishWeather | app/src/main/java/com/fishweather/android/gson/Weather.java | 423 | package com.fishweather.android.gson;
import com.google.gson.annotations.SerializedName;
import java.util.List;
/**
* Created by jason on 2017/8/22.
*/
public class Weather {
public AQI aqi;
public Basic basic;
@SerializedName("daily_forecast")
public List<Forecast> forecastList;
public Now now;
public String status;
public Suggestion suggestion;
public String weatherImage;
}
| apache-2.0 |
grbd/GBD.Build.BlackJack | docs/doxygen/html/classblackjack_1_1cmake_1_1target_1_1_lib_target___imported_1_1_lib_target___imported.js | 1177 | var classblackjack_1_1cmake_1_1target_1_1_lib_target___imported_1_1_lib_target___imported =
[
[ "__init__", "classblackjack_1_1cmake_1_1target_1_1_lib_target___imported_1_1_lib_target___imported.html#a12189d2083c5ceeabac4722c5d765b0f", null ],
[ "LibType", "classblackjack_1_1cmake_1_1target_1_1_lib_target___imported_1_1_lib_target___imported.html#a15420f6ec897d37ecade573820934080", null ],
[ "LibType", "classblackjack_1_1cmake_1_1target_1_1_lib_target___imported_1_1_lib_target___imported.html#a6d7be522d9144c9baeff264851cca406", null ],
[ "render_body", "classblackjack_1_1cmake_1_1target_1_1_lib_target___imported_1_1_lib_target___imported.html#ab5c4e1b6da3928739177ca403656adb8", null ],
[ "_LibType", "classblackjack_1_1cmake_1_1target_1_1_lib_target___imported_1_1_lib_target___imported.html#a0d3f9d25782475f8aa4feee6ed3e9efc", null ],
[ "GlobalImport", "classblackjack_1_1cmake_1_1target_1_1_lib_target___imported_1_1_lib_target___imported.html#ae29c2b6400b3bae398cd8e79efff0a77", null ],
[ "LibType", "classblackjack_1_1cmake_1_1target_1_1_lib_target___imported_1_1_lib_target___imported.html#a0feebdcd8fbd74d26deb78fcd087b354", null ]
]; | apache-2.0 |
webhost/mod_pagespeed | net/instaweb/rewriter/mobilize_rewrite_filter_test.cc | 20787 | /*
* Copyright 2014 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.
*/
// Author: stevensr@google.com (Ryan Stevens)
#include "net/instaweb/rewriter/public/mobilize_rewrite_filter.h"
#include "base/logging.h"
#include "net/instaweb/rewriter/public/rewrite_driver.h"
#include "net/instaweb/rewriter/public/rewrite_options.h"
#include "net/instaweb/rewriter/public/rewrite_test_base.h"
#include "pagespeed/kernel/base/gtest.h"
#include "pagespeed/kernel/base/mock_message_handler.h"
#include "pagespeed/kernel/base/scoped_ptr.h"
#include "pagespeed/kernel/base/statistics.h"
#include "pagespeed/kernel/base/stdio_file_system.h"
#include "pagespeed/kernel/base/string.h"
#include "pagespeed/kernel/base/string_util.h"
#include "pagespeed/kernel/html/html_element.h"
#include "pagespeed/kernel/html/html_node.h"
#include "pagespeed/kernel/html/html_writer_filter.h"
namespace net_instaweb {
namespace {
const char kAddedStyle[] = "stylestring";
const char kTestDataDir[] = "/net/instaweb/rewriter/testdata/";
const char kOriginal[] = "mobilize_test.html";
const char kRewritten[] = "mobilize_test_output.html";
} // namespace
// Base class for doing our tests. Can access MobilizeRewriteFilter's private
// API. Sets the content of the stylesheet added by the filter to be kAddedStyle
// instead of the default (which is large and will likely change).
class MobilizeRewriteFilterTest : public RewriteTestBase {
protected:
MobilizeRewriteFilterTest() {}
void CheckExpected(const GoogleString& expected) {
PrepareWrite();
EXPECT_STREQ(expected, output_buffer_);
}
virtual void SetUp() {
RewriteTestBase::SetUp();
filter_.reset(new MobilizeRewriteFilter(rewrite_driver()));
filter_->style_css_ = kAddedStyle;
}
virtual void TearDown() {
RewriteTestBase::TearDown();
}
virtual bool AddBody() const { return false; }
virtual bool AddHtmlTags() const { return false; }
void CheckVariable(const char* name, int value) {
Variable* var = rewrite_driver()->statistics()->FindVariable(name);
if (var == NULL) {
CHECK(false) << "Checked for a variable that doesn't exit.";
} else {
EXPECT_EQ(var->Get(), value) << name;
}
}
// Wrappers for MobilizeRewriteFilter private API.
void FilterAddStyleAndViewport(HtmlElement* element) {
filter_->AddStyleAndViewport(element);
}
void FilterAddReorderContainers(HtmlElement* element) {
filter_->AddReorderContainers(element);
}
void FilterRemoveReorderContainers() {
filter_->RemoveReorderContainers();
}
bool FilterIsReorderContainer(HtmlElement* element) {
return filter_->IsReorderContainer(element);
}
HtmlElement* FilterMobileRoleToContainer(MobileRole::Level mobile_role) {
return filter_->MobileRoleToContainer(mobile_role);
}
MobileRole::Level FilterGetMobileRole(HtmlElement* element) {
return filter_->GetMobileRole(element);
}
scoped_ptr<MobilizeRewriteFilter> filter_;
private:
void PrepareWrite() {
SetupWriter();
html_parse()->ApplyFilter(html_writer_filter_.get());
}
DISALLOW_COPY_AND_ASSIGN(MobilizeRewriteFilterTest);
};
// For testing private functions in isolation.
class MobilizeRewriteUnitTest : public MobilizeRewriteFilterTest {
protected:
MobilizeRewriteUnitTest() {}
virtual void SetUp() {
MobilizeRewriteFilterTest::SetUp();
static const char kUrl[] = "http://mob.rewrite.test/test.html";
ASSERT_TRUE(html_parse()->StartParse(kUrl));
}
virtual void TearDown() {
html_parse()->FinishParse();
MobilizeRewriteFilterTest::TearDown();
}
private:
DISALLOW_COPY_AND_ASSIGN(MobilizeRewriteUnitTest);
};
TEST_F(MobilizeRewriteUnitTest, AddStyles) {
HtmlElement* head = html_parse()->NewElement(NULL, HtmlName::kHead);
html_parse()->InsertNodeBeforeCurrent(head);
HtmlCharactersNode* content = html_parse()->NewCharactersNode(head, "123");
html_parse()->AppendChild(head, content);
CheckExpected("<head>123</head>");
FilterAddStyleAndViewport(head);
CheckExpected("<head>123<style>stylestring</style><meta name='viewport'"
" content='width=device-width,user-scalable=no'/></head>");
}
TEST_F(MobilizeRewriteUnitTest, HandleContainers) {
HtmlElement* body = html_parse()->NewElement(NULL, HtmlName::kBody);
html_parse()->InsertNodeBeforeCurrent(body);
HtmlCharactersNode* content = html_parse()->NewCharactersNode(body, "123");
html_parse()->AppendChild(body, content);
CheckExpected("<body>123</body>");
FilterAddReorderContainers(body);
CheckExpected("<body>123<div name='keeper'></div>"
"<div name='header'></div>"
"<div name='navigational'></div>"
"<div name='content'></div>"
"<div name='marginal'></div></body>");
FilterRemoveReorderContainers();
CheckExpected("<body>123</body>");
}
TEST_F(MobilizeRewriteUnitTest, CheckGetContainers) {
HtmlElement* body = html_parse()->NewElement(NULL, HtmlName::kBody);
html_parse()->InsertNodeBeforeCurrent(body);
FilterAddReorderContainers(body);
CheckExpected("<body><div name='keeper'></div>"
"<div name='header'></div>"
"<div name='navigational'></div>"
"<div name='content'></div>"
"<div name='marginal'></div></body>");
for (int i = 0; i < MobileRole::kInvalid; i++) {
MobileRole::Level expected = static_cast<MobileRole::Level>(i);
const MobileRole* role = &MobileRole::kMobileRoles[i];
EXPECT_EQ(expected, role->level);
const char* string = MobileRole::StringFromLevel(expected);
EXPECT_EQ(string, role->value);
EXPECT_EQ(expected, MobileRole::LevelFromString(string));
HtmlElement* container = FilterMobileRoleToContainer(expected);
EXPECT_FALSE(container == NULL);
EXPECT_TRUE(FilterIsReorderContainer(container));
}
}
TEST_F(MobilizeRewriteUnitTest, MobileRoleAttribute) {
HtmlElement* div = html_parse()->NewElement(NULL, HtmlName::kDiv);
html_parse()->AddAttribute(div, "data-mobile-role", "navigational");
// Add the new node to the parse tree so it will be deleted.
html_parse()->InsertNodeBeforeCurrent(div);
EXPECT_EQ(MobileRole::kNavigational,
FilterGetMobileRole(div));
}
TEST_F(MobilizeRewriteUnitTest, InvalidMobileRoleAttribute) {
HtmlElement* div = html_parse()->NewElement(NULL, HtmlName::kDiv);
html_parse()->AddAttribute(div, "data-mobile-role", "garbage");
// Add the new node to the parse tree so it will be deleted.
html_parse()->InsertNodeBeforeCurrent(div);
EXPECT_EQ(MobileRole::kInvalid,
FilterGetMobileRole(div));
}
TEST_F(MobilizeRewriteUnitTest, KeeperMobileRoleAttribute) {
HtmlElement* script = html_parse()->NewElement(NULL, HtmlName::kScript);
// Add the new node to the parse tree so it will be deleted.
html_parse()->InsertNodeBeforeCurrent(script);
EXPECT_EQ(MobileRole::kKeeper,
FilterGetMobileRole(script));
}
class MobilizeRewriteFunctionalTest : public MobilizeRewriteFilterTest {
protected:
MobilizeRewriteFunctionalTest() {}
virtual void SetUp() {
MobilizeRewriteFilterTest::SetUp();
html_parse()->AddFilter(filter_.get());
}
private:
DISALLOW_COPY_AND_ASSIGN(MobilizeRewriteFunctionalTest);
};
TEST_F(MobilizeRewriteFunctionalTest, AddStyleAndViewport) {
ValidateExpected("add_style_and_viewport",
"<head></head>",
"<head><style>stylestring</style><meta name='viewport'"
" content='width=device-width,user-scalable=no'/></head>");
CheckVariable(MobilizeRewriteFilter::kPagesMobilized, 1);
CheckVariable(MobilizeRewriteFilter::kKeeperBlocks, 0);
CheckVariable(MobilizeRewriteFilter::kHeaderBlocks, 0);
CheckVariable(MobilizeRewriteFilter::kNavigationalBlocks, 0);
CheckVariable(MobilizeRewriteFilter::kContentBlocks, 0);
CheckVariable(MobilizeRewriteFilter::kMarginalBlocks, 0);
CheckVariable(MobilizeRewriteFilter::kDeletedElements, 0);
}
TEST_F(MobilizeRewriteFunctionalTest, RemoveExistingViewport) {
ValidateExpected("remove_existing_viewport",
"<head><meta name='viewport' content='value' /></head>",
"<head><style>stylestring</style><meta name='viewport'"
" content='width=device-width,user-scalable=no'/></head>");
CheckVariable(MobilizeRewriteFilter::kPagesMobilized, 1);
CheckVariable(MobilizeRewriteFilter::kKeeperBlocks, 0);
CheckVariable(MobilizeRewriteFilter::kHeaderBlocks, 0);
CheckVariable(MobilizeRewriteFilter::kNavigationalBlocks, 0);
CheckVariable(MobilizeRewriteFilter::kContentBlocks, 0);
CheckVariable(MobilizeRewriteFilter::kMarginalBlocks, 0);
CheckVariable(MobilizeRewriteFilter::kDeletedElements, 1);
}
TEST_F(MobilizeRewriteFunctionalTest, HeadUnmodified) {
ValidateExpected("head_unmodified",
"<head><meta name='keywords' content='cool,stuff'/>"
"<style>abcd</style></head>",
"<head><meta name='keywords' content='cool,stuff'/>"
"<style>abcd</style><style>stylestring</style><meta"
" name='viewport' content='width=device-width,"
"user-scalable=no'/></head>");
CheckVariable(MobilizeRewriteFilter::kPagesMobilized, 1);
CheckVariable(MobilizeRewriteFilter::kKeeperBlocks, 0);
CheckVariable(MobilizeRewriteFilter::kHeaderBlocks, 0);
CheckVariable(MobilizeRewriteFilter::kNavigationalBlocks, 0);
CheckVariable(MobilizeRewriteFilter::kContentBlocks, 0);
CheckVariable(MobilizeRewriteFilter::kMarginalBlocks, 0);
CheckVariable(MobilizeRewriteFilter::kDeletedElements, 0);
}
TEST_F(MobilizeRewriteFunctionalTest, HeadLinksUnmodified) {
ValidateExpected("head_unmodified",
"<head><link rel='stylesheet' type='text/css'"
" href='theme.css'></head>",
"<head><link rel='stylesheet' type='text/css'"
" href='theme.css'><style>stylestring</style>"
"<meta name='viewport' content='width=device-width,"
"user-scalable=no'/></head>");
CheckVariable(MobilizeRewriteFilter::kPagesMobilized, 1);
CheckVariable(MobilizeRewriteFilter::kKeeperBlocks, 0);
CheckVariable(MobilizeRewriteFilter::kHeaderBlocks, 0);
CheckVariable(MobilizeRewriteFilter::kNavigationalBlocks, 0);
CheckVariable(MobilizeRewriteFilter::kContentBlocks, 0);
CheckVariable(MobilizeRewriteFilter::kMarginalBlocks, 0);
CheckVariable(MobilizeRewriteFilter::kDeletedElements, 0);
}
TEST_F(MobilizeRewriteFunctionalTest, EmptyBody) {
ValidateNoChanges("empty_body",
"<body></body>");
CheckVariable(MobilizeRewriteFilter::kPagesMobilized, 1);
CheckVariable(MobilizeRewriteFilter::kKeeperBlocks, 0);
CheckVariable(MobilizeRewriteFilter::kHeaderBlocks, 0);
CheckVariable(MobilizeRewriteFilter::kNavigationalBlocks, 0);
CheckVariable(MobilizeRewriteFilter::kContentBlocks, 0);
CheckVariable(MobilizeRewriteFilter::kMarginalBlocks, 0);
CheckVariable(MobilizeRewriteFilter::kDeletedElements, 0);
}
TEST_F(MobilizeRewriteFunctionalTest, KeeperTagsUnmodified) {
ValidateNoChanges("map_tags_unmodified",
"<body><map name='planetmap'><area shape='rect'"
" coords='0,0,82,126' alt='Sun'></map></body>");
ValidateNoChanges("script_tags_unmodified",
"<body><script>document.getElementById('demo')."
"innerHTML = 'Hello JavaScript!';</script></body>");
ValidateNoChanges("style_tags_unmodified",
"<body><style>* { foo: bar; }</style></body>");
CheckVariable(MobilizeRewriteFilter::kPagesMobilized, 3);
CheckVariable(MobilizeRewriteFilter::kKeeperBlocks, 3);
CheckVariable(MobilizeRewriteFilter::kHeaderBlocks, 0);
CheckVariable(MobilizeRewriteFilter::kNavigationalBlocks, 0);
CheckVariable(MobilizeRewriteFilter::kContentBlocks, 0);
CheckVariable(MobilizeRewriteFilter::kMarginalBlocks, 0);
CheckVariable(MobilizeRewriteFilter::kDeletedElements, 0);
}
TEST_F(MobilizeRewriteFunctionalTest, ReorderElements) {
ValidateExpected(
"reorder_elements", "<body><div data-mobile-role='marginal'>"
"<span>123</span></div><div data-mobile-role='header'>"
"<h1>foo</h1><p>bar</p></div></body>",
"<body><div data-mobile-role='header'><h1>foo</h1><p>bar</p>"
"</div><div data-mobile-role='marginal'><span>123</span></div>"
"</body>");
CheckVariable(MobilizeRewriteFilter::kPagesMobilized, 1);
CheckVariable(MobilizeRewriteFilter::kKeeperBlocks, 0);
CheckVariable(MobilizeRewriteFilter::kHeaderBlocks, 1);
CheckVariable(MobilizeRewriteFilter::kNavigationalBlocks, 0);
CheckVariable(MobilizeRewriteFilter::kContentBlocks, 0);
CheckVariable(MobilizeRewriteFilter::kMarginalBlocks, 1);
CheckVariable(MobilizeRewriteFilter::kDeletedElements, 0);
}
TEST_F(MobilizeRewriteFunctionalTest, ReorderElements2) {
ValidateExpected("reorder_elements_2",
"<body>123<div data-mobile-role='content'>890</div>456"
"<div data-mobile-role='header'>abc</div>def</body>",
"<body><div data-mobile-role='header'>abc</div>"
"<div data-mobile-role='content'>890</div></body>");
CheckVariable(MobilizeRewriteFilter::kPagesMobilized, 1);
CheckVariable(MobilizeRewriteFilter::kKeeperBlocks, 0);
CheckVariable(MobilizeRewriteFilter::kHeaderBlocks, 1);
CheckVariable(MobilizeRewriteFilter::kNavigationalBlocks, 0);
CheckVariable(MobilizeRewriteFilter::kContentBlocks, 1);
CheckVariable(MobilizeRewriteFilter::kMarginalBlocks, 0);
CheckVariable(MobilizeRewriteFilter::kDeletedElements, 3);
}
TEST_F(MobilizeRewriteFunctionalTest, RemoveTables) {
ValidateExpected(
"remove_tables",
"<body><div data-mobile-role='content'><table><tr><td>1</td>"
"<td>2</td></tr></table></div></body>",
"<body><div data-mobile-role='content'>12<br><br></div></body>");
CheckVariable(MobilizeRewriteFilter::kPagesMobilized, 1);
CheckVariable(MobilizeRewriteFilter::kKeeperBlocks, 0);
CheckVariable(MobilizeRewriteFilter::kHeaderBlocks, 0);
CheckVariable(MobilizeRewriteFilter::kNavigationalBlocks, 0);
CheckVariable(MobilizeRewriteFilter::kContentBlocks, 1);
CheckVariable(MobilizeRewriteFilter::kMarginalBlocks, 0);
CheckVariable(MobilizeRewriteFilter::kDeletedElements, 4);
}
TEST_F(MobilizeRewriteFunctionalTest, StripNav) {
ValidateExpected("strip_nav",
"<body><div data-mobile-role='navigational'><div>"
"<a href='foo.com'>123</a></div></div></body>",
"<body><div data-mobile-role='navigational'>"
"<a href='foo.com'>123</a></div></body>");
CheckVariable(MobilizeRewriteFilter::kPagesMobilized, 1);
CheckVariable(MobilizeRewriteFilter::kKeeperBlocks, 0);
CheckVariable(MobilizeRewriteFilter::kHeaderBlocks, 0);
CheckVariable(MobilizeRewriteFilter::kNavigationalBlocks, 1);
CheckVariable(MobilizeRewriteFilter::kContentBlocks, 0);
CheckVariable(MobilizeRewriteFilter::kMarginalBlocks, 0);
CheckVariable(MobilizeRewriteFilter::kDeletedElements, 1);
}
TEST_F(MobilizeRewriteFunctionalTest, StripOnlyNav) {
ValidateExpected(
"strip_only_nav",
"<body><div data-mobile-role='navigational'><div>"
"<a href='foo.com'>123</a></div></div>"
"<div data-mobile-role='header'><h1>foobar</h1></div></body>",
"<body><div data-mobile-role='header'><h1>foobar</h1></div>"
"<div data-mobile-role='navigational'><a href='foo.com'>123"
"</a></div></body>");
CheckVariable(MobilizeRewriteFilter::kPagesMobilized, 1);
CheckVariable(MobilizeRewriteFilter::kKeeperBlocks, 0);
CheckVariable(MobilizeRewriteFilter::kHeaderBlocks, 1);
CheckVariable(MobilizeRewriteFilter::kNavigationalBlocks, 1);
CheckVariable(MobilizeRewriteFilter::kContentBlocks, 0);
CheckVariable(MobilizeRewriteFilter::kMarginalBlocks, 0);
CheckVariable(MobilizeRewriteFilter::kDeletedElements, 1);
}
TEST_F(MobilizeRewriteFunctionalTest, UnknownMobileRole) {
// Its probably OK if the behavior resulting from having a weird
// data-mobile-role value is unexpected, as long as it doesn't crash.
ValidateExpected(
"unknown_mobile_role",
"<body><div data-mobile-role='garbage'><a>123</a></div></body>",
"<body></body>");
CheckVariable(MobilizeRewriteFilter::kPagesMobilized, 1);
CheckVariable(MobilizeRewriteFilter::kKeeperBlocks, 0);
CheckVariable(MobilizeRewriteFilter::kHeaderBlocks, 0);
CheckVariable(MobilizeRewriteFilter::kNavigationalBlocks, 0);
CheckVariable(MobilizeRewriteFilter::kContentBlocks, 0);
CheckVariable(MobilizeRewriteFilter::kMarginalBlocks, 0);
CheckVariable(MobilizeRewriteFilter::kDeletedElements, 3);
}
TEST_F(MobilizeRewriteFunctionalTest, MultipleHeads) {
// Check we only add the style and viewport tag once.
ValidateExpected("multiple_heads",
"<head></head><head></head>",
"<head><style>stylestring</style><meta name='viewport'"
" content='width=device-width,user-scalable=no'/></head>"
"<head></head>");
CheckVariable(MobilizeRewriteFilter::kPagesMobilized, 1);
CheckVariable(MobilizeRewriteFilter::kKeeperBlocks, 0);
CheckVariable(MobilizeRewriteFilter::kHeaderBlocks, 0);
CheckVariable(MobilizeRewriteFilter::kNavigationalBlocks, 0);
CheckVariable(MobilizeRewriteFilter::kContentBlocks, 0);
CheckVariable(MobilizeRewriteFilter::kMarginalBlocks, 0);
CheckVariable(MobilizeRewriteFilter::kDeletedElements, 0);
}
TEST_F(MobilizeRewriteFunctionalTest, MultipleBodys) {
// Each body should be handled as its own unit.
ValidateNoChanges("multiple_bodys",
"<body></body><body></body>");
CheckVariable(MobilizeRewriteFilter::kPagesMobilized, 1);
CheckVariable(MobilizeRewriteFilter::kKeeperBlocks, 0);
CheckVariable(MobilizeRewriteFilter::kHeaderBlocks, 0);
CheckVariable(MobilizeRewriteFilter::kNavigationalBlocks, 0);
CheckVariable(MobilizeRewriteFilter::kContentBlocks, 0);
CheckVariable(MobilizeRewriteFilter::kMarginalBlocks, 0);
CheckVariable(MobilizeRewriteFilter::kDeletedElements, 0);
}
TEST_F(MobilizeRewriteFunctionalTest, MultipleBodysWithContent) {
ValidateExpected(
"multiple_bodys_with_content",
"<body>123<div data-mobile-role='marginal'>567</div></body>"
"<body><div data-mobile-role='content'>890</div>"
"<div data-mobile-role='header'>abc</div></body>",
"<body><div data-mobile-role='marginal'>567</div></body><body>"
"<div data-mobile-role='header'>abc</div>"
"<div data-mobile-role='content'>890</div></body>");
CheckVariable(MobilizeRewriteFilter::kPagesMobilized, 1);
CheckVariable(MobilizeRewriteFilter::kKeeperBlocks, 0);
CheckVariable(MobilizeRewriteFilter::kHeaderBlocks, 1);
CheckVariable(MobilizeRewriteFilter::kNavigationalBlocks, 0);
CheckVariable(MobilizeRewriteFilter::kContentBlocks, 1);
CheckVariable(MobilizeRewriteFilter::kMarginalBlocks, 1);
CheckVariable(MobilizeRewriteFilter::kDeletedElements, 1);
}
// Check we are called correctly from the driver.
class MobilizeRewriteEndToEndTest : public RewriteTestBase {
protected:
MobilizeRewriteEndToEndTest() {}
virtual bool AddBody() const { return false; }
virtual bool AddHtmlTags() const { return false; }
StdioFileSystem filesystem_;
private:
DISALLOW_COPY_AND_ASSIGN(MobilizeRewriteEndToEndTest);
};
TEST_F(MobilizeRewriteEndToEndTest, FullPage) {
// This test will break when the CSS is changed. Update the expected output
// accordingly.
GoogleString original_buffer;
GoogleString original_filename =
StrCat(GTestSrcDir(), kTestDataDir, kOriginal);
ASSERT_TRUE(filesystem_.ReadFile(original_filename.c_str(), &original_buffer,
message_handler()));
GoogleString rewritten_buffer;
GoogleString rewritten_filename =
StrCat(GTestSrcDir(), kTestDataDir, kRewritten);
ASSERT_TRUE(filesystem_.ReadFile(rewritten_filename.c_str(),
&rewritten_buffer, message_handler()));
AddFilter(RewriteOptions::kMobilize);
ValidateExpected("full_page", original_buffer, rewritten_buffer);
}
} // namespace net_instaweb
| apache-2.0 |
midoks/WordPressPlugins | wp-spider/wp-spider-option.php | 6117 | <?php
class wp_spider_option{
//架构函数
public function __construct(){
if(is_admin()){
add_action('admin_menu', array(&$this, 'spider_menu'));
}
}
//设置面板
public function spider_menu(){
define('SPIDER_URL', plugins_url('', __FILE__));
//添加主目录
add_menu_page('蜘蛛记录',
'蜘蛛记录',
'manage_options',
'wp-spider',
array(&$this, 'spider_basic_intro'),
SPIDER_URL.'/zz.jpg');
//添加子目录
add_submenu_page('wp-spider',
'蜘蛛记录显示',
'蜘蛛记录显示',
'manage_options',
'wp-show-records',
array($this, 'spider_show_record'));
}
//插件介绍
public function spider_basic_intro(){
echo file_get_contents(SPIDER_ROOT.'/spiderIntroduction.txt');
echo '<hr />';
echo '<form method="post">';
echo '<input style="margin-left:10px;" name="submit" type="submit" class="button-primary" value="清空记录" /></p>';
echo '</form>';
}
//显示抓取记录
public function spider_show_record(){
if(isset($_GET['del_id'])){
$this->del_func($_GET['del_id']);
}
global $wpdb, $spider;
$table = $spider->tname;//表名
$p = isset($_GET['p'])?$_GET['p']:'1';//当前页
if((!is_numeric($p)) || ($p<=0)){$p = 1;}//页数的正确修改
//总页数
$sql = "select count(id) as count from {$table}";
//echo $sql;
$data = $wpdb->get_results($sql);
$countNum = $data[0]->count;
$pageNum = ceil($countNum/20);
//总页数判断
if($p>=$pageNum){$p=$pageNum;}
$trTpl = "<tr><td width='60px' style='text-align:center;'>%s</td>".
"<td width='60px' style='text-align:center;'>%s</td>".
"<td width='118px'>%s</td><td width='90px'>%s</td><td>%s</td>".
"<td width='40px' style='text-align:center;'>%s</td>".
"</tr>";
$tableHeadTpl = sprintf($trTpl, '序号', '蜘蛛名', '时间', 'IP地址', '收录页', '操作');
$tableBodyTpl = '';
$data = $this->spider_data($p, $table);
if(empty($data)){
$tableHeadTpl .= '<tr><td style="text-align:center;" colspan="6">无记录</td></tr>';
}
foreach($data as $k=>$v){
$tableHeadTpl .= sprintf($trTpl, $v['id'], $v['name'], $v['time'], $v['ip'], htmlentities($v['url'], ENT_QUOTES), $this->del_page($v['id']));
}
//var_dump($data);
//echo($tableTpl);
echo '<table class="wp-list-table widefat fixed posts">';
echo '<thead>';
echo($tableHeadTpl);
echo '</thead>';
echo '<tbody>';
echo($tableBodyTpl);
echo '</tbody>';
echo($this->Pagination($countNum, $p, 20, 7, 'p'));
echo '</table>';
//echo $this->Pagination($p);
}
//蜘蛛抓取记录数据获取
public function spider_data($page=1, $table='midoks_spider'){
global $wpdb, $spider;
if($page<1){
$page = 1;
}
$start = ($page-1)*20;//开始数据
//var_dump($start);
$sql = "select * from {$table} order by id desc limit {$start},20";
$data = $wpdb->get_results($sql);
$newData = array();
//echo '<pre>';
foreach($data as $k=>$v){
$arr = array();
$arr['id'] = $v->id;
$arr['name'] = $v->name;
$arr['time'] = date('Y-m-d H:i:s', $v->time);
$arr['ip'] = $v->ip;
$arr['url'] = urldecode($v->url);
$newData[] = $arr;
}
//var_dump($newData);
return $newData;
}
public function spider_del_id($id, $table='midoks_spider'){
global $wpdb, $spider;
$sql = "delete from {$table} where id='{$id}'";
$data = $wpdb->query($sql);
if($data){
echo '删除成功!!!';
}else{
echo '删除失败@!!';
}
}
public function del_page($id){
$url = $_SERVER['REQUEST_URI'];
$r_url = str_replace(strstr($url, '&'), '', $url);
$thisPageUrl = 'http://'.$_SERVER['HTTP_HOST'].$r_url.'&'.'del_id='.$id;
//echo '<pre>';echo $thisPageUrl; echo '<pre>';
$h = '<span><a href="'.$thisPageUrl.'">删除</a></span>';
return $h;
}
public function del_func($id){
$prev = $_SERVER['HTTP_REFERER'];
$this->spider_del_id($id);
//header('location: '.$prev);
echo "<script>window.location.href='{$prev}';</script>";
exit;
}
public function Pagination($total, $position, $page=5, $show=7, $pn = 'nav'){
//当前页
$url = $_SERVER['REQUEST_URI'];
$r_url = str_replace(strstr($url, '&'), '', $url);
$thisPageUrl = 'http://'.$_SERVER['HTTP_HOST'].$r_url.'&'.$pn.'=';
echo('<tr><td colspan="6">');
$prev = $position-1;//前页
$next = $position+1;//下页
//$showitems = 3;//显示多少li
$big = ceil($show/2);
$small = floor($show/2);//$show最好为奇数
$total_page = ceil($total/$page);//总页数
//if($prev < 1){$prev = 1;}
if($next > $total_page){$next = $total;}
if($position > $total_page){$position = $total_page;}
if(0 != $total_page){
//echo "<div id='page'><div class='center'><ul>";
/////////////////////////////////////////////
echo("<span><a href='".$thisPageUrl."1#' class='fixed'>首页</a></span>");
echo("<span style='margin-left:5px;'><a href='".$thisPageUrl.$prev."#'><<</a></span>");
$j=0;
for($i=1;$i<=$total_page;$i++){
$url = $thisPageUrl.$i;
if($position==$i)
$strli = "<span style='margin-left:5px;'><a href='".$url."#' class='current' >".$i.'</a></span>';
else
$strli = "<span style='margin-left:5px;'><a href='".$url."#' class='inactive' >".$i.'</a></span>';
if($total_page<=$show){echo $strli;}
if(($position+$small)>=$total_page){
if(($j<$show) && ($total_page>$show) && ($i>=($total_page-(2*$small)))){echo($strli);++$j;}
}else{if(($j<$show) && ($total_page>$show) && ($i>=($position-$small))){echo($strli);++$j;}}
}
echo("<span style='margin-left:5px;'><a href='".$thisPageUrl.$next."#'>>></a></span>");
echo("<span style='margin-left:5px;'><a href='".$thisPageUrl.$total_page."#' class='fixed'>尾页</a></span>");
echo("<span style='margin-left:30px;'>共{$total}条数据|</span>");
echo("<span>当前第{$position}页</span>");
//////////////////////////////////////////////
//echo '</ul></div></div>';
}
echo('</td></tr>');
}
}
if((isset($_POST['submit'])) && ($_POST['submit']=='清空记录') && isset($_GET['page']) && ('wp-spider' == $_GET['page'])){
global $spider;
$spider->clear();
}
?>
| apache-2.0 |
gquintana/metrics-sql | src/test/java/com/github/gquintana/metrics/sql/ResultSetTest.java | 4151 | package com.github.gquintana.metrics.sql;
/*
* #%L
* Metrics SQL
* %%
* Copyright (C) 2014 Open-Source
* %%
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* #L%
*/
import com.codahale.metrics.Meter;
import com.codahale.metrics.MetricRegistry;
import com.codahale.metrics.Timer;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import javax.sql.DataSource;
import java.lang.reflect.Proxy;
import java.sql.*;
import static org.junit.Assert.*;
/**
* Test Statement wrapper
*/
public class ResultSetTest {
private MetricRegistry metricRegistry;
private JdbcProxyFactory proxyFactory;
private DataSource rawDataSource;
private DataSource dataSource;
@Before
public void setUp() throws SQLException {
metricRegistry = new MetricRegistry();
proxyFactory = new JdbcProxyFactory(metricRegistry);
rawDataSource = H2DbUtil.createDataSource();
try(Connection connection = rawDataSource.getConnection()) {
H2DbUtil.initTable(connection);
}
dataSource = proxyFactory.wrapDataSource(rawDataSource);
}
@After
public void tearDown() throws SQLException {
try(Connection connection = rawDataSource.getConnection()) {
H2DbUtil.dropTable(connection);
}
H2DbUtil.close(dataSource);
}
@Test
public void testResultSetLife() throws SQLException {
// Act
Connection connection = dataSource.getConnection();
Statement statement = connection.createStatement();
ResultSet resultSet = statement.executeQuery("select * from METRICS_TEST");
while(resultSet.next()) {
int id = resultSet.getInt("ID");
String text = resultSet.getString("TEXT");
Timestamp timestamp = resultSet.getTimestamp("CREATED");
}
H2DbUtil.close(resultSet, statement, connection);
// Assert
assertNotNull(connection);
assertTrue(Proxy.isProxyClass(resultSet.getClass()));
Timer timer = metricRegistry.getTimers().get("java.sql.ResultSet.[select * from metrics_test]");
assertNotNull(timer);
assertEquals(1L, timer.getCount());
Meter meter = metricRegistry.meter("java.sql.ResultSet.[select * from metrics_test].rows");
assertNotNull(meter);
assertEquals(11L, meter.getCount());
}
@Test
public void testResultSetUnwrap() throws SQLException {
// Act
Connection connection = dataSource.getConnection();
Statement statement = connection.createStatement();
ResultSet resultSet = statement.executeQuery("select * from METRICS_TEST");
// Assert
assertTrue(resultSet.isWrapperFor(org.h2.jdbc.JdbcResultSet.class));
assertTrue(resultSet.unwrap(org.h2.jdbc.JdbcResultSet.class) instanceof org.h2.jdbc.JdbcResultSet);
H2DbUtil.close(resultSet, statement, connection);
}
@Test
public void testResultSet_Direct() throws SQLException {
// Act
Connection connection = rawDataSource.getConnection();
Statement statement = connection.createStatement();
String sql = "select * from METRICS_TEST order by ID";
ResultSet resultSet = MetricsSql.forRegistry(metricRegistry).wrap(statement.executeQuery(sql), sql);
H2DbUtil.close(resultSet, statement, connection);
// Assert
assertNotNull(connection);
assertTrue(Proxy.isProxyClass(resultSet.getClass()));
assertEquals(1, metricRegistry.getTimers().get("java.sql.ResultSet.[select * from metrics_test order by id]").getCount());
}
}
| apache-2.0 |
dangdangdotcom/sharding-jdbc | sharding-core/src/main/java/io/shardingsphere/core/parsing/parser/dialect/oracle/sql/OracleInsertParser.java | 1488 | /*
* Copyright 2016-2018 shardingsphere.io.
* <p>
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* 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.
* </p>
*/
package io.shardingsphere.core.parsing.parser.dialect.oracle.sql;
import io.shardingsphere.core.metadata.table.ShardingTableMetaData;
import io.shardingsphere.core.parsing.lexer.LexerEngine;
import io.shardingsphere.core.parsing.parser.dialect.oracle.clause.facade.OracleInsertClauseParserFacade;
import io.shardingsphere.core.parsing.parser.sql.dml.insert.AbstractInsertParser;
import io.shardingsphere.core.rule.ShardingRule;
/**
* Insert parser for Oracle.
*
* @author zhangliang
* @author panjuan
*/
public final class OracleInsertParser extends AbstractInsertParser {
public OracleInsertParser(final ShardingRule shardingRule, final LexerEngine lexerEngine, final ShardingTableMetaData shardingTableMetaData) {
super(shardingRule, shardingTableMetaData, lexerEngine, new OracleInsertClauseParserFacade(shardingRule, lexerEngine));
}
}
| apache-2.0 |
durban/exp-reagents | bench/src/main/scala/dev/tauri/choam/kcas/bench/GlobalCompareBench.scala | 2539 | /*
* SPDX-License-Identifier: Apache-2.0
* Copyright 2016-2020 Daniel Urban and contributors listed in NOTICE.txt
*
* 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 dev.tauri.choam
package kcas
package bench
import java.util.concurrent.ThreadLocalRandom
import org.openjdk.jmh.annotations._
import org.openjdk.jmh.infra.Blackhole
@Fork(6)
class GlobalCompareBench {
@Benchmark
def baseline(bh: Blackhole): Unit = {
val r1 = Ref.mk("a")
val r2 = Ref.mk("a")
bh.consume(r1)
bh.consume(r2)
}
@Benchmark
def bench0(bh: Blackhole): Unit = {
val r1 = Ref.mk("a")
val r2 = Ref.mk("a")
bh.consume(r1)
bh.consume(r2)
bh.consume(Ref.globalCompare(r1, r2))
}
@Benchmark
def bench1(bh: Blackhole): Unit = {
val tlr = ThreadLocalRandom.current()
val i0 = tlr.nextLong()
bh.consume(tlr.nextLong())
val r1 = Ref.mkWithId("a")(i0, tlr.nextLong(), tlr.nextLong(), tlr.nextLong())
val r2 = Ref.mkWithId("a")(i0, tlr.nextLong(), tlr.nextLong(), tlr.nextLong())
bh.consume(r1)
bh.consume(r2)
bh.consume(Ref.globalCompare(r1, r2))
}
@Benchmark
def bench2(bh: Blackhole): Unit = {
val tlr = ThreadLocalRandom.current()
val i0 = tlr.nextLong()
bh.consume(tlr.nextLong())
val i1 = tlr.nextLong()
bh.consume(tlr.nextLong())
val r1 = Ref.mkWithId("a")(i0, i1, tlr.nextLong(), tlr.nextLong())
val r2 = Ref.mkWithId("a")(i0, i1, tlr.nextLong(), tlr.nextLong())
bh.consume(r1)
bh.consume(r2)
bh.consume(Ref.globalCompare(r1, r2))
}
@Benchmark
def bench3(bh: Blackhole): Unit = {
val tlr = ThreadLocalRandom.current()
val i0 = tlr.nextLong()
bh.consume(tlr.nextLong())
val i1 = tlr.nextLong()
bh.consume(tlr.nextLong())
val i2 = tlr.nextLong()
bh.consume(tlr.nextLong())
val r1 = Ref.mkWithId("a")(i0, i1, i2, tlr.nextLong())
val r2 = Ref.mkWithId("a")(i0, i1, i2, tlr.nextLong())
bh.consume(r1)
bh.consume(r2)
bh.consume(Ref.globalCompare(r1, r2))
}
}
| apache-2.0 |
spinnaker/clouddriver | clouddriver-cloudfoundry/src/main/java/com/netflix/spinnaker/clouddriver/cloudfoundry/deploy/converters/CloneCloudFoundryServerGroupAtomicOperationConverter.java | 1868 | /*
* Copyright 2018 Pivotal, 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.spinnaker.clouddriver.cloudfoundry.deploy.converters;
import com.netflix.spinnaker.clouddriver.artifacts.ArtifactCredentialsRepository;
import com.netflix.spinnaker.clouddriver.cloudfoundry.CloudFoundryOperation;
import com.netflix.spinnaker.clouddriver.docker.registry.security.DockerRegistryNamedAccountCredentials;
import com.netflix.spinnaker.clouddriver.helpers.OperationPoller;
import com.netflix.spinnaker.clouddriver.orchestration.AtomicOperations;
import com.netflix.spinnaker.credentials.CredentialsRepository;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Component;
@CloudFoundryOperation(AtomicOperations.CLONE_SERVER_GROUP)
@Component
public class CloneCloudFoundryServerGroupAtomicOperationConverter
extends DeployCloudFoundryServerGroupAtomicOperationConverter {
public CloneCloudFoundryServerGroupAtomicOperationConverter(
@Qualifier("cloudFoundryOperationPoller") OperationPoller operationPoller,
ArtifactCredentialsRepository credentialsRepository,
CredentialsRepository<DockerRegistryNamedAccountCredentials>
dockerRegistryCredentialsRepository) {
super(operationPoller, credentialsRepository, dockerRegistryCredentialsRepository);
}
}
| apache-2.0 |
eugene-chow/keycloak | integration/adapter-spi/src/main/java/org/keycloak/adapters/HttpFacade.java | 2446 | package org.keycloak.adapters;
import javax.security.cert.X509Certificate;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.List;
/**
* @author <a href="mailto:bill@burkecentral.com">Bill Burke</a>
* @version $Revision: 1 $
*/
public interface HttpFacade {
Request getRequest();
Response getResponse();
X509Certificate[] getCertificateChain();
interface Request {
String getMethod();
/**
* Full request URI with query params
*
* @return
*/
String getURI();
/**
* HTTPS?
*
* @return
*/
boolean isSecure();
/**
* Get first query or form param
*
* @param param
* @return
*/
String getFirstParam(String param);
String getQueryParamValue(String param);
Cookie getCookie(String cookieName);
String getHeader(String name);
List<String> getHeaders(String name);
InputStream getInputStream();
String getRemoteAddr();
}
interface Response {
void setStatus(int status);
void addHeader(String name, String value);
void setHeader(String name, String value);
void resetCookie(String name, String path);
void setCookie(String name, String value, String path, String domain, int maxAge, boolean secure, boolean httpOnly);
OutputStream getOutputStream();
void sendError(int code, String message);
/**
* If the response is finished, end it.
*
*/
void end();
}
public class Cookie {
protected String name;
protected String value;
protected int version;
protected String domain;
protected String path;
public Cookie(String name, String value, int version, String domain, String path) {
this.name = name;
this.value = value;
this.version = version;
this.domain = domain;
this.path = path;
}
public String getName() {
return name;
}
public String getValue() {
return value;
}
public int getVersion() {
return version;
}
public String getDomain() {
return domain;
}
public String getPath() {
return path;
}
}
}
| apache-2.0 |
pollitosabroson/pycarribean | fabfile.py | 6624 | # -*- coding: utf-8 -*-
from fabric.api import cd, env, require, run, task
from fabric.colors import green, white
from fabric.context_managers import contextmanager, shell_env
from fabric.utils import puts
from fabutils import arguments, join, options
from fabutils.env import set_env_from_json_file
from fabutils.context import cmd_msg
from fabutils.tasks import ulocal, urun, ursync_project
from fabutils.text import SUCCESS_ART
@contextmanager
def virtualenv():
"""
Activates the virtualenv in which the commands shall be run.
"""
require('site_dir', 'django_settings')
with cd(env.site_dir):
with shell_env(DJANGO_SETTINGS_MODULE=env.django_settings):
yield
@task
def environment(env_name):
"""
Creates a dynamic environment based on the contents of the given
environments_file.
"""
if env_name == 'vagrant':
result = ulocal('vagrant ssh-config | grep IdentityFile', capture=True)
env.key_filename = result.split()[1].replace('"', '')
set_env_from_json_file('environments.json', env_name)
@task
def createdb():
"""
Creates a new database instance with utf-8 encoding for the project.
"""
urun('createdb pycaribbean -l en_US.UTF-8 -E UTF8 -T template0')
@task
def resetdb():
"""
Reset the project's database by dropping an creating it again.
"""
urun('dropdb pycaribbean')
createdb()
migrate()
@task
def bootstrap():
"""
Builds the environment to start the project.
"""
# Build the DB schema and collect the static files.
createdb()
migrate()
collectstatic()
@task
def loaddata(*args):
"""
Loads the given data fixtures into the project's database.
"""
with virtualenv():
run(join('python manage.py loaddata', arguments(*args)))
@task
def makemigrations(*args, **kwargs):
"""
Creates the new migrations based on the project's models changes.
"""
with virtualenv():
run(join('python manage.py makemigrations',
options(**kwargs), arguments(*args)))
@task
def migrate(*args, **kwargs):
"""
Syncs the DB and applies the available migrations.
"""
with virtualenv():
run(join('python manage.py migrate',
options(**kwargs), arguments(*args)))
@task
def collectstatic():
"""
Collects the static files.
"""
with virtualenv():
run('python manage.py collectstatic --noinput')
@task
def runserver():
"""
Starts the development server inside the Vagrant VM.
"""
with virtualenv():
run('python manage.py runserver_plus 0.0.0.0:8000')
@task
def deploy(git_ref, upgrade=False):
"""
Deploy the code of the given git reference to the previously selected
environment.
Pass ``upgrade=True`` to upgrade the versions of the already installed
project requirements (with pip).
"""
require('hosts', 'user', 'group', 'site_dir', 'django_settings')
# Retrives git reference metadata and creates a temp directory with the
# contents resulting of applying a ``git archive`` command.
message = white('Creating git archive from {0}'.format(git_ref), bold=True)
with cmd_msg(message):
repo = ulocal(
'basename `git rev-parse --show-toplevel`', capture=True)
commit = ulocal(
'git rev-parse --short {0}'.format(git_ref), capture=True)
branch = ulocal(
'git rev-parse --abbrev-ref HEAD', capture=True)
tmp_dir = '/tmp/blob-{0}-{1}/'.format(repo, commit)
ulocal('rm -fr {0}'.format(tmp_dir))
ulocal('mkdir {0}'.format(tmp_dir))
ulocal('git archive {0} ./src | tar -xC {1} --strip 1'.format(
commit, tmp_dir))
# Uploads the code of the temp directory to the host with rsync telling
# that it must delete old files in the server, upload deltas by checking
# file checksums recursivelly in a zipped way; changing the file
# permissions to allow read, write and execution to the owner, read and
# execution to the group and no permissions for any other user.
with cmd_msg(white('Uploading code to server...', bold=True)):
ursync_project(
local_dir=tmp_dir,
remote_dir=env.site_dir,
delete=True,
default_opts='-chrtvzP',
extra_opts='--chmod=750',
exclude=["*.pyc", "env/", "cover/"]
)
# Performs the deployment task, i.e. Install/upgrade project
# requirements, syncronize and migrate the database changes, collect
# static files, reload the webserver, etc.
message = white('Running deployment tasks', bold=True)
with cmd_msg(message, grouped=True):
with virtualenv():
message = white('Installing Python requirements with pip')
with cmd_msg(message, spaces=2):
run('pip install -{0}r ./requirements/production.txt'.format(
'U' if upgrade else ''))
message = white('Migrating database')
with cmd_msg(message, spaces=2):
run('python manage.py migrate --noinput')
message = white('Collecting static files')
with cmd_msg(message, spaces=2):
run('python manage.py collectstatic --noinput')
message = white('Setting file permissions')
with cmd_msg(message, spaces=2):
run('chgrp -R {0} .'.format(env.group))
run('chgrp -R {0} ../media'.format(env.group))
message = white('Restarting webserver')
with cmd_msg(message, spaces=2):
run('touch ../reload')
message = white('Registering deployment')
with cmd_msg(message, spaces=2):
register_deployment(commit, branch)
# Clean the temporary snapshot files that was just deployed to the host
message = white('Cleaning up...', bold=True)
with cmd_msg(message):
ulocal('rm -fr {0}'.format(tmp_dir))
puts(green(SUCCESS_ART), show_prefix=False)
puts(white('Code from {0} was succesfully deployed to host {1}'.format(
git_ref, ', '.join(env.hosts)), bold=True), show_prefix=False)
@task
def register_deployment(commit, branch):
"""
Register the current deployment at Opbeat with given commit and branch.
"""
with virtualenv():
run(
'opbeat -o $OPBEAT_ORGANIZATION_ID '
'-a $OPBEAT_APP_ID '
'-t $OPBEAT_SECRET_TOKEN deployment '
'--component path:. vcs:git rev:%s branch:%s '
% (commit, branch)
)
| apache-2.0 |
kapilt/cloud-custodian | c7n/actions/autotag.py | 6092 | # Copyright 2017-2018 Capital One Services, 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.
import six
from .core import EventAction
from c7n.exceptions import PolicyValidationError
from c7n.manager import resources
from c7n import utils
class AutoTagUser(EventAction):
"""Tag a resource with the user who created/modified it.
.. code-block:: yaml
policies:
- name: ec2-auto-tag-ownercontact
resource: ec2
description: |
Triggered when a new EC2 Instance is launched. Checks to see if
it's missing the OwnerContact tag. If missing it gets created
with the value of the ID of whomever called the RunInstances API
mode:
type: cloudtrail
role: arn:aws:iam::123456789000:role/custodian-auto-tagger
events:
- RunInstances
filters:
- tag:OwnerContact: absent
actions:
- type: auto-tag-user
tag: OwnerContact
There's a number of caveats to usage. Resources which don't
include tagging as part of their api may have some delay before
automation kicks in to create a tag. Real world delay may be several
minutes, with worst case into hours[0]. This creates a race condition
between auto tagging and automation.
In practice this window is on the order of a fraction of a second, as
we fetch the resource and evaluate the presence of the tag before
attempting to tag it.
References
CloudTrail User
https://docs.aws.amazon.com/awscloudtrail/latest/userguide/cloudtrail-event-reference-user-identity.html
""" # NOQA
schema_alias = True
schema = utils.type_schema(
'auto-tag-user',
required=['tag'],
**{'user-type': {
'type': 'array',
'items': {'type': 'string',
'enum': [
'IAMUser',
'AssumedRole',
'FederatedUser'
]}},
'update': {'type': 'boolean'},
'tag': {'type': 'string'},
'principal_id_tag': {'type': 'string'}
}
)
def get_permissions(self):
return self.manager.action_registry.get(
'tag')({}, self.manager).get_permissions()
def validate(self):
if self.manager.data.get('mode', {}).get('type') != 'cloudtrail':
raise PolicyValidationError(
"Auto tag owner requires an event %s" % (self.manager.data,))
if self.manager.action_registry.get('tag') is None:
raise PolicyValidationError(
"Resource does not support tagging %s" % (self.manager.data,))
if 'tag' not in self.data:
raise PolicyValidationError(
"auto-tag action requires 'tag'")
return self
def process(self, resources, event):
if event is None:
return
event = event['detail']
utype = event['userIdentity']['type']
if utype not in self.data.get('user-type', ['AssumedRole', 'IAMUser', 'FederatedUser']):
return
user = None
if utype == "IAMUser":
user = event['userIdentity']['userName']
principal_id_value = event['userIdentity'].get('principalId', '')
elif utype == "AssumedRole" or utype == "FederatedUser":
user = event['userIdentity']['arn']
prefix, user = user.rsplit('/', 1)
principal_id_value = event['userIdentity'].get('principalId', '').split(':')[0]
# instance role
if user.startswith('i-'):
return
# lambda function (old style)
elif user.startswith('awslambda'):
return
if user is None:
return
# if the auto-tag-user policy set update to False (or it's unset) then we
# will skip writing their UserName tag and not overwrite pre-existing values
if not self.data.get('update', False):
untagged_resources = []
# iterating over all the resources the user spun up in this event
for resource in resources:
tag_already_set = False
for tag in resource.get('Tags', ()):
if tag['Key'] == self.data['tag']:
tag_already_set = True
break
if not tag_already_set:
untagged_resources.append(resource)
# if update is set to True, we will overwrite the userName tag even if
# the user already set a value
else:
untagged_resources = resources
tag_action = self.manager.action_registry.get('tag')
new_tags = {
self.data['tag']: user
}
# if principal_id_key is set (and value), we'll set the principalId tag.
principal_id_key = self.data.get('principal_id_tag', None)
if principal_id_key and principal_id_value:
new_tags[principal_id_key] = principal_id_value
for key, value in six.iteritems(new_tags):
tag_action({'key': key, 'value': value}, self.manager).process(untagged_resources)
return new_tags
@classmethod
def register_resource(cls, registry, resource_class):
if 'auto-tag-user' in resource_class.action_registry:
return
if resource_class.action_registry.get('tag'):
resource_class.action_registry.register('auto-tag-user', AutoTagUser)
resources.subscribe(AutoTagUser.register_resource)
| apache-2.0 |
SnappyDataInc/snappy-store | gemfire-core/src/main/java/com/gemstone/gemfire/HeapDumper.java | 3357 | /*
* Copyright (c) 2010-2015 Pivotal Software, 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. See accompanying
* LICENSE file.
*/
package com.gemstone.gemfire;
import com.gemstone.gemfire.internal.shared.SystemProperties;
import com.sun.management.HotSpotDiagnosticMXBean;
import javax.management.MBeanServer;
import java.lang.management.ManagementFactory;
/**
* This class has been picked up from the following Oracle blog
* https://blogs.oracle.com/sundararajan/programmatically-dumping-heap-from-java-applications
*/
public class HeapDumper {
// This is the name of the HotSpot Diagnostic MBean
private static final String HOTSPOT_BEAN_NAME =
"com.sun.management:type=HotSpotDiagnostic";
// field to store the hotspot diagnostic MBean
private static volatile HotSpotDiagnosticMXBean hotspotMBean;
private static long lastHeapDumpTime = -1;
private static synchronized boolean takeDump() {
long currentTime = System.currentTimeMillis();
if ((currentTime- lastHeapDumpTime) > 3000) {
lastHeapDumpTime = currentTime;
return true;
} else {
return false;
}
}
static void dumpHeap(boolean live) {
boolean dumpProperty = SystemProperties.getServerInstance().getBoolean("dumpheap", false);
// return if dump property is not set or lastheapdumptime is less than 3 seconds
if (!dumpProperty || !takeDump()) {
return;
}
lastHeapDumpTime = System.currentTimeMillis();
String fileName = "heap" + lastHeapDumpTime + ".bin";
// initialize hotspot diagnostic MBean
initHotspotMBean();
try {
hotspotMBean.dumpHeap(fileName, live);
} catch (RuntimeException re) {
throw re;
} catch (Exception exp) {
throw new RuntimeException(exp);
}
}
// initialize the hotspot diagnostic MBean field
private static void initHotspotMBean() {
if (hotspotMBean == null) {
synchronized (HeapDumper.class) {
if (hotspotMBean == null) {
hotspotMBean = getHotspotMBean();
}
}
}
}
// get the hotspot diagnostic MBean from the
// platform MBean server
private static HotSpotDiagnosticMXBean getHotspotMBean() {
try {
MBeanServer server = ManagementFactory.getPlatformMBeanServer();
HotSpotDiagnosticMXBean bean =
ManagementFactory.newPlatformMXBeanProxy(server,
HOTSPOT_BEAN_NAME, HotSpotDiagnosticMXBean.class);
return bean;
} catch (RuntimeException re) {
throw re;
} catch (Exception exp) {
throw new RuntimeException(exp);
}
}
} | apache-2.0 |
consulo/consulo-python | python-impl/src/main/java/com/jetbrains/python/psi/impl/PyExecStatementImpl.java | 908 | /*
* Copyright 2000-2013 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.psi.impl;
import com.intellij.lang.ASTNode;
import com.jetbrains.python.psi.PyExecStatement;
/**
* @author yole
*/
public class PyExecStatementImpl extends PyElementImpl implements PyExecStatement {
public PyExecStatementImpl(ASTNode astNode) {
super(astNode);
}
}
| apache-2.0 |
aquarius520/effective-java-practices | src/com/aquarius/effectivejava/practices/chapter04/item19/PhysicalConstants.java | 678 | package com.aquarius.effectivejava.practices.chapter04.item19;
/**
* Created by aquarius on 2017/5/8.
*/
//在类中定义常量,接口只应该被用于定义类型,而不应用被用于定义常量
public class PhysicalConstants {
private PhysicalConstants() {
throw new RuntimeException("not allow instantiation, even through the reflection call!");
}
// Avogadro's number (1/mol)
public static final double AVOGADROS_NUMBER = 6.02214199e23;
// Boltzmann constant (J/K)
public static final double BOLTZMANN_CONSTANT = 1.3806503e-23;
// Mass of the electron (kg)
public static final double ELECTRON_MASS = 9.10938188e-31;
}
| apache-2.0 |
ymex/cocc.cute | kits/src/test/java/cn/ymex/kits/ExampleUnitTest.java | 305 | package cn.ymex.kits;
import org.junit.Test;
import static org.junit.Assert.*;
/**
* To work on unit tests, switch the Test Artifact in the Build Variants view.
*/
public class ExampleUnitTest {
@Test
public void addition_isCorrect() throws Exception {
assertEquals(4, 2 + 2);
}
} | apache-2.0 |
leapframework/framework | base/core/src/main/java/leap/core/security/UserPrincipal.java | 1031 | /*
* Copyright 2013 the original author or 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 leap.core.security;
import java.util.Collections;
import java.util.Map;
public interface UserPrincipal extends Principal {
/**
* Returns the user's display name.
*/
String getName();
/**
* Returns the user's login name.
*/
String getLoginName();
/**
* Returns the details property.
*/
default Map<String, Object> getProperties() {
return Collections.emptyMap();
}
} | apache-2.0 |
fusepoolP3/p3-silk | silk-core/src/main/scala/de/fuberlin/wiwiss/silk/runtime/task/TaskStatus.scala | 3076 | /*
* 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 de.fuberlin.wiwiss.silk.runtime.task
/**
* A status message
*/
sealed trait TaskStatus {
/**
* The current status message.
*/
def message: String
/**
* The progress of the computation.
* Will be 0.0 when the task has been started and 1.0 when it has finished execution.
*/
def progress: Double = 0.0
/**
* True, if the task is running at the moment; False, otherwise.
*/
def isRunning: Boolean = false
/**
* True, if the task has failed.
*/
def failed: Boolean = false
/**
* The complete status message including the progress.
*/
override def toString = message + " (" + "%3.1f".format(progress * 100.0) + "%)"
}
/**
* Status which indicates that the task has not been started yet.
*/
case class TaskIdle() extends TaskStatus {
def message = "Idle"
}
/**
* Status which indicates that the task has been started.
*/
case class TaskStarted(name: String) extends TaskStatus {
override def message = name + " started"
override def isRunning = true
}
/**
* Running status
*
* @param message The status message
* @param progress The progress of the computation (A value between 0.0 and 1.0 inclusive).
*/
case class TaskRunning(message: String, override val progress: Double) extends TaskStatus {
override def isRunning = true
}
/**
* Indicating that the task has been requested to stop but has not stopped yet.
*
* @param name The name of the task.
* @param progress The progress of the computation (A value between 0.0 and 1.0 inclusive).
*/
case class TaskCanceling(name: String, override val progress: Double) extends TaskStatus {
override def message = "Stopping " + name
override def isRunning = true
}
/**
* Status which indicates that the task has finished execution.
*
* @param name The name of the task.
* @param success True, if the computation finished successfully. False, otherwise.
* @param time The time in milliseconds needed to execute the task.
* @param exception The exception, if the task failed.
*/
case class TaskFinished(name: String, success: Boolean, time: Long, exception: Option[Throwable] = None) extends TaskStatus {
override def message = exception match {
case None => name + " finished in " + formattedTime
case Some(ex) => name + " failed after " + formattedTime + ": " + ex.getMessage
}
private def formattedTime = {
if (time < 1000)
time + "ms"
else
(time / 1000) + "s"
}
override def progress = 1.0
override def failed = !success
} | apache-2.0 |
opetrovski/development | oscm-apiversioning-soapmgmt-unittests/javasrc/org/oscm/apiversioning/adapter/AdapterFactoryTest.java | 2900 | /*******************************************************************************
*
* Copyright FUJITSU LIMITED 2017
*
* Creation Date: Feb 9, 2015
*
*******************************************************************************/
package org.oscm.apiversioning.adapter;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import org.junit.Before;
import org.junit.Test;
import org.oscm.apiversioning.enums.ModificationType;
/**
* @author zhaoh.fnst
*
*/
public class AdapterFactoryTest {
@SuppressWarnings("unused")
private AdapterFactory adapter;
@Before
public void setUp() throws Exception {
adapter = new AdapterFactory();
}
@Test
public void getAdapter_Add() throws Exception {
// given
ModificationType type = ModificationType.ADD;
// when
IAdapter result = AdapterFactory.getAdapter(type);
// then
assertTrue(result instanceof AddAdapter);
}
@Test
public void getAdapter_Remove() throws Exception {
// given
ModificationType type = ModificationType.ADD;
// when
IAdapter result = AdapterFactory.getAdapter(type);
// then
assertTrue(result instanceof AddAdapter);
}
@Test
public void getAdapter_AddException() throws Exception {
// given
ModificationType type = ModificationType.ADDEXCEPTION;
// when
IAdapter result = AdapterFactory.getAdapter(type);
// then
assertTrue(result instanceof ExceptionAdapter);
}
@Test
public void getAdapter_Update() throws Exception {
// given
ModificationType type = ModificationType.UPDATE;
// when
IAdapter result = AdapterFactory.getAdapter(type);
// then
assertTrue(result instanceof UpdateAdapter);
}
@Test
public void getAdapter_UpdateField() throws Exception {
// given
ModificationType type = ModificationType.UPDATEFIELD;
// when
IAdapter result = AdapterFactory.getAdapter(type);
// then
assertTrue(result instanceof UpdateFieldAdapter);
}
@Test
public void getAdapter_Exception() throws Exception {
// given
ModificationType type = ModificationType.REMOVEFIELD;
// when
try {
AdapterFactory.getAdapter(type);
} catch (RuntimeException ex) {
// then
assertEquals("No adapter is found", ex.getMessage());
}
}
}
| apache-2.0 |
zkzxc/MovieMemos | app/src/main/java/com/zk/moviememos/contract/TopContract.java | 320 | package com.zk.moviememos.contract;
import com.zk.moviememos.presenter.BasePresenter;
import com.zk.moviememos.view.BaseView;
/**
* Created by zk <zkzxc1988@163.com>.
*/
public interface TopContract {
interface View extends BaseView<Presenter> {
}
interface Presenter extends BasePresenter {
}
}
| apache-2.0 |
verma7/dcos-cassandra-service | cassandra-scheduler/src/test/java/com/mesosphere/dcos/cassandra/scheduler/CassandraSchedulerTest.java | 20157 | package com.mesosphere.dcos.cassandra.scheduler;
import com.fasterxml.jackson.datatype.guava.GuavaModule;
import com.fasterxml.jackson.datatype.jdk8.Jdk8Module;
import com.google.common.eventbus.EventBus;
import com.google.common.io.Resources;
import com.mesosphere.dcos.cassandra.common.config.*;
import com.mesosphere.dcos.cassandra.common.offer.PersistentOfferRequirementProvider;
import com.mesosphere.dcos.cassandra.common.tasks.*;
import com.mesosphere.dcos.cassandra.scheduler.client.SchedulerClient;
import com.mesosphere.dcos.cassandra.scheduler.plan.CassandraPhaseStrategies;
import com.mesosphere.dcos.cassandra.scheduler.plan.CassandraPlanManager;
import com.mesosphere.dcos.cassandra.scheduler.plan.backup.BackupManager;
import com.mesosphere.dcos.cassandra.scheduler.plan.backup.RestoreManager;
import com.mesosphere.dcos.cassandra.scheduler.plan.cleanup.CleanupManager;
import com.mesosphere.dcos.cassandra.scheduler.plan.repair.RepairManager;
import com.mesosphere.dcos.cassandra.scheduler.seeds.SeedsManager;
import com.mesosphere.dcos.cassandra.common.tasks.CassandraState;
import io.dropwizard.configuration.ConfigurationFactory;
import io.dropwizard.configuration.EnvironmentVariableSubstitutor;
import io.dropwizard.configuration.FileConfigurationSourceProvider;
import io.dropwizard.configuration.SubstitutingSourceProvider;
import io.dropwizard.jackson.Jackson;
import io.dropwizard.validation.BaseValidator;
import org.apache.curator.test.TestingServer;
import org.apache.mesos.Protos;
import org.apache.mesos.Scheduler;
import org.apache.mesos.SchedulerDriver;
import org.apache.mesos.curator.CuratorStateStore;
import org.apache.mesos.dcos.Capabilities;
import org.apache.mesos.reconciliation.DefaultReconciler;
import org.apache.mesos.reconciliation.Reconciler;
import org.apache.mesos.scheduler.plan.Block;
import org.apache.mesos.scheduler.plan.Phase;
import org.apache.mesos.scheduler.plan.PlanManager;
import org.apache.mesos.scheduler.plan.ReconciliationPhase;
import org.apache.mesos.state.StateStore;
import org.apache.mesos.testing.QueuedSchedulerDriver;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.mockito.Mock;
import org.mockito.Mockito;
import org.mockito.MockitoAnnotations;
import java.util.*;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.CompletionStage;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.stream.Collectors;
import static org.junit.Assert.*;
import static org.mockito.Mockito.when;
public class CassandraSchedulerTest {
@Mock private CompletionStage<Boolean> mockStage;
@Mock private CompletableFuture<Boolean> mockFuture;
private CassandraScheduler scheduler;
private ConfigurationManager configurationManager;
private PlanManager planManager;
private PersistentOfferRequirementProvider offerRequirementProvider;
private CassandraState cassandraState;
private Reconciler reconciler;
private EventBus eventBus;
private SchedulerClient client;
private BackupManager backup;
private RestoreManager restore;
private CleanupManager cleanup;
private RepairManager repair;
private SeedsManager seeds;
private ExecutorService executorService;
private MesosConfig mesosConfig;
private Protos.FrameworkID frameworkId;
private Protos.MasterInfo masterInfo;
private StateStore stateStore;
private static MutableSchedulerConfiguration config;
private static TestingServer server;
private QueuedSchedulerDriver driver;
private ConfigurationFactory<MutableSchedulerConfiguration> factory;
@Before
public void beforeEach() throws Exception {
server = new TestingServer();
server.start();
beforeHelper("scheduler.yml");
}
public void beforeHelper(String configName) throws Exception {
MockitoAnnotations.initMocks(this);
mesosConfig = Mockito.mock(MesosConfig.class);
client = Mockito.mock(SchedulerClient.class);
Mockito.when(mockFuture.get()).thenReturn(true);
Mockito.when(mockStage.toCompletableFuture()).thenReturn(mockFuture);
backup = Mockito.mock(BackupManager.class);
restore = Mockito.mock(RestoreManager.class);
cleanup = Mockito.mock(CleanupManager.class);
repair = Mockito.mock(RepairManager.class);
seeds = Mockito.mock(SeedsManager.class);
executorService = Executors.newCachedThreadPool();
frameworkId = TestUtils.generateFrameworkId();
eventBus = new EventBus();
planManager = new CassandraPlanManager(
new CassandraPhaseStrategies("org.apache.mesos.scheduler.plan.DefaultInstallStrategy"));
factory = new ConfigurationFactory<>(
MutableSchedulerConfiguration.class,
BaseValidator.newValidator(),
Jackson.newObjectMapper().registerModule(
new GuavaModule())
.registerModule(new Jdk8Module()),
"dw");
config = factory.build(
new SubstitutingSourceProvider(
new FileConfigurationSourceProvider(),
new EnvironmentVariableSubstitutor(false, true)),
Resources.getResource(configName).getFile());
final CuratorFrameworkConfig curatorConfig = config.getCuratorConfig();
stateStore = new CuratorStateStore(
"/" + config.getServiceConfig().getName(),
server.getConnectString());
DefaultConfigurationManager defaultConfigurationManager
= new DefaultConfigurationManager(CassandraSchedulerConfiguration.class,
"/" + config.createConfig().getServiceConfig().getName(),
server.getConnectString(),
config.createConfig(),
new ConfigValidator(),
stateStore);
Capabilities mockCapabilities = Mockito.mock(Capabilities.class);
when(mockCapabilities.supportsNamedVips()).thenReturn(true);
configurationManager = new ConfigurationManager(
new CassandraDaemonTask.Factory(mockCapabilities),
defaultConfigurationManager);
final ClusterTaskConfig clusterTaskConfig = configurationManager.getTargetConfig().getClusterTaskConfig();
cassandraState = new CassandraState(
configurationManager,
clusterTaskConfig,
stateStore);
reconciler = new DefaultReconciler(cassandraState.getStateStore());
offerRequirementProvider = new PersistentOfferRequirementProvider(defaultConfigurationManager, cassandraState);
scheduler = new CassandraScheduler(
configurationManager,
mesosConfig,
offerRequirementProvider,
planManager,
cassandraState,
client,
eventBus,
backup,
restore,
cleanup,
repair,
seeds,
executorService,
stateStore,
defaultConfigurationManager);
masterInfo = TestUtils.generateMasterInfo();
driver = new QueuedSchedulerDriver();
scheduler.setSchedulerDriver(driver);
scheduler.registered(driver, frameworkId, masterInfo);
}
@Test
public void testRegistered() throws Exception {
scheduler.registered(driver, frameworkId, masterInfo);
final Protos.FrameworkID frameworkID = stateStore.fetchFrameworkId().get();
assertEquals(frameworkID, this.frameworkId);
final Phase currentPhase = planManager.getCurrentPhase().get();
assertTrue(currentPhase instanceof ReconciliationPhase);
assertEquals(1, currentPhase.getBlocks().size());
}
@Test
public void install() {
scheduler.registered(driver, frameworkId, Protos.MasterInfo.getDefaultInstance());
runReconcile(driver);
final Phase currentPhase = planManager.getCurrentPhase().get();
assertEquals("Deploy", currentPhase.getName());
assertEquals(3, currentPhase.getBlocks().size());
// node-0
final Protos.Offer offer1 = TestUtils.generateOffer(frameworkId.getValue(), 4, 10240, 10240);
scheduler.resourceOffers(driver, Arrays.asList(offer1));
Block currentBlock = planManager.getCurrentBlock().get();
assertEquals("node-0", currentBlock.getName());
assertTrue(currentBlock.isInProgress());
Collection<QueuedSchedulerDriver.OfferOperations> offerOps = driver.drainAccepted();
assertEquals("expected accepted offer carried over from reconcile stage",
1, offerOps.size());
Collection<Protos.Offer.Operation> ops = offerOps.iterator().next().getOperations();
launchAll(ops, scheduler, driver);
assertTrue(currentBlock.isComplete());
// node-1
final Protos.Offer offer2 = TestUtils.generateOffer(frameworkId.getValue(), 4, 10240, 10240);
scheduler.resourceOffers(driver, Arrays.asList(offer2));
currentBlock = planManager.getCurrentBlock().get();
assertEquals("node-1", currentBlock.getName());
assertTrue(currentBlock.isInProgress());
offerOps = driver.drainAccepted();
assertEquals("expected accepted offer carried over from reconcile stage",
1, offerOps.size());
ops = offerOps.iterator().next().getOperations();
launchAll(ops, scheduler, driver);
assertTrue(currentBlock.isComplete());
// node-2
final Protos.Offer offer3 = TestUtils.generateOffer(frameworkId.getValue(), 4, 10240, 10240);
scheduler.resourceOffers(driver, Arrays.asList(offer3));
currentBlock = planManager.getCurrentBlock().get();
assertEquals("node-2", currentBlock.getName());
assertTrue(currentBlock.isInProgress());
offerOps = driver.drainAccepted();
assertEquals("expected accepted offer carried over from reconcile stage",
1, offerOps.size());
ops = offerOps.iterator().next().getOperations();
launchAll(ops, scheduler, driver);
assertTrue(currentBlock.isComplete());
}
@Test
public void installAndRecover() throws Exception {
install();
final Optional<Phase> currentPhase = planManager.getCurrentPhase();
final Optional<Block> currentBlock = planManager.getCurrentBlock();
assertTrue(!currentPhase.isPresent());
assertTrue(!currentBlock.isPresent());
final CassandraDaemonTask task = cassandraState.getDaemons().get("node-0");
scheduler.statusUpdate(driver,
TestUtils.generateStatus(task.getTaskInfo().getTaskId(), Protos.TaskState.TASK_KILLED));
Set<Protos.TaskStatus> taskStatuses = cassandraState.getTaskStatuses();
final Optional<Protos.TaskStatus> first = taskStatuses.stream().filter(status -> status.getTaskId().equals(task.getTaskInfo().getTaskId())).findFirst();
assertEquals(Protos.TaskState.TASK_KILLED, first.get().getState());
final CassandraTask templateTask = cassandraState.get("node-0-task-template").get();
final Protos.Offer offer = TestUtils.generateReplacementOffer(frameworkId.getValue(),
task.getTaskInfo(), templateTask.getTaskInfo());
scheduler.resourceOffers(driver, Arrays.asList(offer));
Collection<QueuedSchedulerDriver.OfferOperations> offerOps = driver.drainAccepted();
assertEquals(String.format("expected accepted offer: %s", offer), 1, offerOps.size());
Collection<Protos.Offer.Operation> ops = offerOps.iterator().next().getOperations();
launchAll(ops, scheduler, driver);
taskStatuses = cassandraState.getTaskStatuses();
final Optional<Protos.TaskStatus> node0Status = taskStatuses.stream().filter(status -> {
try {
return org.apache.mesos.offer.TaskUtils.toTaskName(status.getTaskId()).equals(task.getTaskInfo().getName());
} catch (Exception e) {
throw new RuntimeException(e);
}
}).findFirst();
assertEquals(Protos.TaskState.TASK_RUNNING, node0Status.get().getState());
}
@Test
public void installAndUpdate() throws Exception {
install();
Optional<Phase> currentPhase = planManager.getCurrentPhase();
Optional<Block> currentBlock = planManager.getCurrentBlock();
assertTrue(!currentPhase.isPresent());
assertTrue(!currentBlock.isPresent());
beforeHelper("update-scheduler.yml");
update();
currentPhase = planManager.getCurrentPhase();
currentBlock = planManager.getCurrentBlock();
assertTrue(!currentPhase.isPresent());
assertTrue(!currentBlock.isPresent());
}
@Test
public void testSuppress() throws Exception {
assertTrue(!driver.isSuppressed());
install();
assertTrue(driver.isSuppressed());
}
@Test
public void testRevive() throws Exception {
install();
assertTrue(driver.isSuppressed());
final CassandraDaemonTask task = cassandraState.getDaemons().get("node-0");
scheduler.statusUpdate(
driver,
TestUtils.generateStatus(task.getTaskInfo().getTaskId(), Protos.TaskState.TASK_KILLED));
assertTrue(!driver.isSuppressed());
}
public void update() {
scheduler.registered(driver, frameworkId, Protos.MasterInfo.getDefaultInstance());
runReconcile(driver);
final Phase currentPhase = planManager.getCurrentPhase().get();
assertEquals("Deploy", currentPhase.getName());
assertEquals(3, currentPhase.getBlocks().size());
Block currentBlock = planManager.getCurrentBlock().get();
assertEquals("node-0", currentBlock.getName());
assertTrue("expected current block to be in Pending due to offer carried over in reconcile stage",
currentBlock.isPending());
Collection<QueuedSchedulerDriver.OfferOperations> offerOps = driver.drainAccepted();
assertEquals("expected accepted offer carried over from reconcile stage",
0, offerOps.size());
Collection<Protos.Offer.Operation> ops = null;
// Roll out node-0
final CassandraTask node0 = cassandraState.get("node-0").get();
final CassandraTask node0Template = cassandraState.get(CassandraTemplateTask.toTemplateTaskName("node-0")).get();
final Protos.Offer offer1 = TestUtils.generateUpdateOffer(frameworkId.getValue(), node0.getTaskInfo(),
node0Template.getTaskInfo(), 3, 1024, 1024);
// Send TASK_KILL
scheduler.statusUpdate(
driver,
TestUtils.generateStatus(
node0.getTaskInfo().getTaskId(),
Protos.TaskState.TASK_KILLED));
scheduler.resourceOffers(driver, Arrays.asList(offer1));
currentBlock = planManager.getCurrentBlock().get();
assertEquals("node-0", currentBlock.getName());
assertTrue("expected current block to be in progress", currentBlock.isInProgress());
offerOps = driver.drainAccepted();
assertEquals("expected accepted offer carried over from reconcile stage",
1, offerOps.size());
ops = offerOps.iterator().next().getOperations();
launchAll(ops, scheduler, driver);
assertTrue(currentBlock.isComplete());
// Roll out node-1
final CassandraTask node1 = cassandraState.get("node-1").get();
final CassandraTask node1Template = cassandraState.get(CassandraTemplateTask.toTemplateTaskName("node-1")).get();
final Protos.Offer offer2 = TestUtils.generateUpdateOffer(frameworkId.getValue(), node1.getTaskInfo(),
node1Template.getTaskInfo(), 3, 1024, 1024);
Mockito.reset(client);
// Send TASK_KILL
scheduler.statusUpdate(driver, TestUtils.generateStatus(node1.getTaskInfo().getTaskId(),
Protos.TaskState.TASK_KILLED));
scheduler.resourceOffers(driver, Arrays.asList(offer2));
currentBlock = planManager.getCurrentBlock().get();
assertEquals("node-1", currentBlock.getName());
assertTrue("expected current block to be in progress",
currentBlock.isInProgress());
offerOps = driver.drainAccepted();
assertEquals("expected accepted offer carried over from reconcile stage",
1, offerOps.size());
ops = offerOps.iterator().next().getOperations();
launchAll(ops, scheduler, driver);
assertTrue(currentBlock.isComplete());
// Roll out node-2
final CassandraTask node2 = cassandraState.get("node-2").get();
final CassandraTask node2Template = cassandraState.get(CassandraTemplateTask.toTemplateTaskName("node-2")).get();
final Protos.Offer offer3 = TestUtils.generateUpdateOffer(frameworkId.getValue(), node2.getTaskInfo(),
node2Template.getTaskInfo(), 3, 1024, 1024);
Mockito.reset(client);
// Send TASK_KILL
scheduler.statusUpdate(driver, TestUtils.generateStatus(node2.getTaskInfo().getTaskId(),
Protos.TaskState.TASK_KILLED));
scheduler.resourceOffers(driver, Arrays.asList(offer3));
currentBlock = planManager.getCurrentBlock().get();
assertEquals("node-2", currentBlock.getName());
assertTrue("expected current block to be in progress",
currentBlock.isInProgress());
offerOps = driver.drainAccepted();
assertEquals("expected accepted offer carried over from reconcile stage",
1, offerOps.size());
ops = offerOps.iterator().next().getOperations();
launchAll(ops, scheduler, driver);
assertTrue(currentBlock.isComplete());
}
public static void launchAll(
final Collection<Protos.Offer.Operation> operations,
final Scheduler scheduler,
final SchedulerDriver driver) {
operations.stream()
.filter(op -> op.getType() == Protos.Offer.Operation.Type.LAUNCH)
.flatMap(op -> op.getLaunch().getTaskInfosList().stream())
.collect(Collectors.toList()).stream()
.map(info -> CassandraDaemonTask.parse(info))
.forEach(task -> scheduler.statusUpdate(driver, TestUtils.generateStatus(task.getTaskInfo().getTaskId(),
Protos.TaskState.TASK_RUNNING, CassandraMode.NORMAL)));
}
public void runReconcile(QueuedSchedulerDriver driver) {
Phase currentPhase = planManager.getCurrentPhase().get();
assertTrue(currentPhase instanceof ReconciliationPhase);
assertEquals(1, currentPhase.getBlocks().size());
while (currentPhase.getName().equals("Reconciliation") && !currentPhase.isComplete()) {
final Protos.Offer offer = TestUtils.generateOffer(frameworkId.getValue(), 4, 10240, 10240);
scheduler.resourceOffers(driver, Arrays.asList(offer));
final Collection<Protos.TaskStatus> taskStatuses = driver.drainReconciling();
if (taskStatuses.isEmpty()) {
// All reconciled
cassandraState.getTaskStatuses().forEach(status -> scheduler.statusUpdate(driver, status));
} else {
taskStatuses.forEach(status -> scheduler.statusUpdate(driver, status));
}
currentPhase = planManager.getCurrentPhase().get();
if (currentPhase.getName().equals("Reconciliation") && !currentPhase.isComplete()) {
final Collection<Protos.OfferID> declined = driver.drainDeclined();
assertEquals(1, declined.size());
assertEquals(declined.iterator().next(), offer.getId());
}
}
}
@After
public void afterEach() throws Exception {
server.close();
server.stop();
}
}
| apache-2.0 |
Hitooooo/RVPractice | app/src/main/java/com/hito/rvpractice/factory/ListTypeFactory.java | 968 | package com.hito.rvpractice.factory;
import android.view.View;
import com.hito.rvpractice.R;
import com.hito.rvpractice.adapter.holder.BasicHolder;
import com.hito.rvpractice.adapter.holder.DogHolder;
import com.hito.rvpractice.adapter.holder.PigHolder;
import com.hito.rvpractice.model.Dog;
import com.hito.rvpractice.model.Pig;
/**
* Created by dream on 2016/12/28.
*/
public class ListTypeFactory implements TypeFactory {
@Override
public int type(Pig pig) {
return R.layout.item_rv_pig;
}
@Override
public int type(Dog dog) {
return R.layout.item_rv_dog;
}
@Override
public BasicHolder onCreateViewHolder(View itemView, int viewType) {
switch (viewType) {
case R.layout.item_rv_pig:
return new PigHolder(itemView);
case R.layout.item_rv_dog:
return new DogHolder(itemView);
default:
return null;
}
}
}
| apache-2.0 |
caskdata/cdap | cdap-app-fabric/src/test/java/co/cask/cdap/internal/app/runtime/batch/dataset/output/AppWithMapReduceUsingMultipleOutputs.java | 4821 | /*
* Copyright © 2016 Cask Data, 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 co.cask.cdap.internal.app.runtime.batch.dataset.output;
import co.cask.cdap.api.ProgramLifecycle;
import co.cask.cdap.api.app.AbstractApplication;
import co.cask.cdap.api.data.batch.Input;
import co.cask.cdap.api.data.batch.Output;
import co.cask.cdap.api.dataset.lib.FileSetArguments;
import co.cask.cdap.api.dataset.lib.FileSetProperties;
import co.cask.cdap.api.mapreduce.AbstractMapReduce;
import co.cask.cdap.api.mapreduce.MapReduceContext;
import co.cask.cdap.api.mapreduce.MapReduceTaskContext;
import org.apache.hadoop.io.LongWritable;
import org.apache.hadoop.io.NullWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Job;
import org.apache.hadoop.mapreduce.Mapper;
import org.apache.hadoop.mapreduce.lib.input.TextInputFormat;
import org.apache.hadoop.mapreduce.lib.output.TextOutputFormat;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
/**
* App used to test whether M/R can write to multiple outputs. Tests writing to the same dataset, with different runtime
* arguments, as two different outputs.
*/
public class AppWithMapReduceUsingMultipleOutputs extends AbstractApplication {
public static final String PURCHASES = "purchases";
public static final String SEPARATED_PURCHASES = "smallPurchases";
@Override
public void configure() {
setName("AppWithMapReduceUsingMultipleOutputs");
setDescription("Application with MapReduce job using multiple outputs");
createDataset(PURCHASES, "fileSet", FileSetProperties.builder()
.setInputFormat(TextInputFormat.class)
.build());
createDataset(SEPARATED_PURCHASES, "fileSet", FileSetProperties.builder()
.setOutputFormat(TextOutputFormat.class)
.setOutputProperty(TextOutputFormat.SEPERATOR, " ")
.build());
addMapReduce(new SeparatePurchases());
addMapReduce(new InvalidMapReduce());
}
/**
* Simple map-only MR that simply writes to a different output, depending on the spend amount.
*/
public static class SeparatePurchases extends AbstractMapReduce {
@Override
public void initialize() throws Exception {
MapReduceContext context = getContext();
Map<String, String> inputArgs = new HashMap<>();
FileSetArguments.setInputPath(inputArgs, "inputFile");
// test using a stream with the same name, but aliasing it differently (so mapper gets the alias'd name)
context.addInput(Input.ofDataset(PURCHASES, inputArgs), FileMapper.class);
Map<String, String> output1Args = new HashMap<>();
FileSetArguments.setOutputPath(output1Args, "small_purchases");
context.addOutput(Output.ofDataset(SEPARATED_PURCHASES, output1Args).alias("small_purchases"));
Map<String, String> output2Args = new HashMap<>();
FileSetArguments.setOutputPath(output2Args, "large_purchases");
context.addOutput(Output.ofDataset(SEPARATED_PURCHASES, output2Args).alias("large_purchases"));
Job job = context.getHadoopJob();
job.setMapperClass(FileMapper.class);
job.setNumReduceTasks(0);
}
}
/**
* This is an invalid MR because it adds an output a second time, with the same alias.
*/
public static class InvalidMapReduce extends SeparatePurchases {
@Override
public void initialize() throws Exception {
super.initialize();
getContext().addOutput(Output.ofDataset(SEPARATED_PURCHASES).alias("small_purchases"));
}
}
public static class FileMapper extends Mapper<LongWritable, Text, LongWritable, Text>
implements ProgramLifecycle<MapReduceTaskContext<NullWritable, Text>> {
private MapReduceTaskContext<NullWritable, Text> mapReduceTaskContext;
@Override
public void initialize(MapReduceTaskContext<NullWritable, Text> context) throws Exception {
this.mapReduceTaskContext = context;
}
@Override
public void map(LongWritable key, Text data, Context context) throws IOException, InterruptedException {
String spend = data.toString().split(" ")[1];
String output = Integer.valueOf(spend) > 50 ? "large_purchases" : "small_purchases";
mapReduceTaskContext.write(output, NullWritable.get(), data);
}
@Override
public void destroy() {
}
}
}
| apache-2.0 |
bakenezumi/domala | meta/src/main/scala/domala/internal/macros/meta/generator/DeleteGenerator.scala | 2448 | package domala.internal.macros.meta.generator
import domala.Delete
import domala.internal.macros.meta.QueryDefDecl
import domala.internal.macros.meta.args.DaoMethodCommonArgs
import scala.collection.immutable.Seq
import scala.meta._
object DeleteGenerator extends DaoMethodGenerator {
override def annotationClass: Class[Delete] = classOf[Delete]
override def generate(
trtName: Type.Name,
_def: Decl.Def,
internalMethodName: Term.Name,
args: Seq[Term.Arg]): Defn.Def = {
val defDecl = QueryDefDecl.of(trtName, _def)
val commonArgs =
DaoMethodCommonArgs.of(args, trtName.syntax, _def.name.syntax)
val ignoreVersion = args
.collectFirst { case arg"ignoreVersion = $x" => x }
.getOrElse(q"false")
val suppressOptimisticLockException = args
.collectFirst { case arg"suppressOptimisticLockException = $x" => x }
.getOrElse(q"false")
if (commonArgs.hasSqlAnnotation || commonArgs.sqlFile) {
val query: (Term, Option[Term]) => Term.New =
if(commonArgs.hasSqlAnnotation) (entityAndEntityDesc, _) =>
q"new domala.jdbc.query.SqlAnnotationDeleteQuery(${commonArgs.sql}, $ignoreVersion, $suppressOptimisticLockException)($entityAndEntityDesc)"
else (entityAndEntityDesc, path) =>
q"new domala.jdbc.query.SqlFileDeleteQuery(${path.get}, $ignoreVersion, $suppressOptimisticLockException)($entityAndEntityDesc)"
val otherQueryArgs = Seq[Stat]()
val command =
q"getCommandImplementors.createDeleteCommand($internalMethodName, __query)"
SqlModifyQueryGenerator.generate(
defDecl,
commonArgs,
internalMethodName,
query,
otherQueryArgs,
command,
q"false")
} else {
val (paramName, paramTpe) =
AutoModifyQueryGenerator.extractParameter(defDecl)
val query =
q"getQueryImplementors.createAutoDeleteQuery($internalMethodName, __desc)"
val command =
q"getCommandImplementors.createDeleteCommand($internalMethodName, __query)"
val otherQueryArgs = Seq[Stat](
q"__query.setVersionIgnored($ignoreVersion)",
q"__query.setOptimisticLockExceptionSuppressed($suppressOptimisticLockException)"
)
AutoModifyQueryGenerator.generate(
defDecl,
commonArgs,
paramName,
paramTpe,
internalMethodName,
query,
otherQueryArgs,
command)
}
}
}
| apache-2.0 |
vivitc/publication-manager | publications/apps.py | 140 | from __future__ import unicode_literals
from django.apps import AppConfig
class PublicationsConfig(AppConfig):
name = 'publications'
| apache-2.0 |
spring-projects/spring-data-solr | src/test/java/org/springframework/data/solr/repository/ITestSimpleSolrRepository.java | 3858 | /*
* Copyright 2012-2020 the original author or 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
*
* 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 org.springframework.data.solr.repository;
import static org.assertj.core.api.Assertions.*;
import java.time.Duration;
import java.util.ArrayList;
import java.util.List;
import org.apache.commons.lang3.builder.EqualsBuilder;
import org.junit.Before;
import org.junit.Test;
import org.springframework.data.solr.AbstractITestWithEmbeddedSolrServer;
import org.springframework.data.solr.ExampleSolrBean;
import org.springframework.data.solr.core.SolrTemplate;
/**
* @author Christoph Strobl
* @author Mayank Kumar
*/
public class ITestSimpleSolrRepository extends AbstractITestWithEmbeddedSolrServer {
private ExampleSolrBeanRepository repository;
@Before
public void setUp() {
SolrTemplate template = new SolrTemplate(server);
template.afterPropertiesSet();
repository = new ExampleSolrBeanRepository(template, ExampleSolrBean.class);
}
@Test
public void testBeanLifecyle() {
ExampleSolrBean toInsert = createDefaultExampleBean();
ExampleSolrBean savedBean = repository.save(toInsert);
assertThat(savedBean).isSameAs(toInsert);
assertThat(repository.existsById(savedBean.getId())).isTrue();
ExampleSolrBean retrieved = repository.findById(savedBean.getId()).get();
assertThat(retrieved).isNotNull();
assertThat(EqualsBuilder.reflectionEquals(savedBean, retrieved, new String[] { "version" })).isTrue();
assertThat(repository.count()).isEqualTo(1);
assertThat(repository.existsById(savedBean.getId())).isTrue();
repository.delete(savedBean);
assertThat(repository.count()).isEqualTo(0);
assertThat(repository.findById(savedBean.getId()).isPresent()).isFalse();
}
@Test
public void testListFunctions() {
int objectCount = 100;
List<ExampleSolrBean> toInsert = new ArrayList<>(objectCount);
for (int i = 0; i < 100; i++) {
toInsert.add(createExampleBeanWithId(Integer.toString(i)));
}
repository.saveAll(toInsert);
assertThat(repository.count()).isEqualTo(objectCount);
int counter = 0;
for (ExampleSolrBean retrievedBean : repository.findAll()) {
assertThat(EqualsBuilder.reflectionEquals(toInsert.get(counter), retrievedBean, new String[] { "version" }))
.isTrue();
counter++;
if (counter > objectCount) {
fail("More beans return than added!");
}
}
repository.delete(toInsert.get(0));
assertThat(repository.count()).isEqualTo(99);
repository.deleteAll();
assertThat(repository.count()).isEqualTo(0);
}
@Test // DATASOLR-332
public void testBeanLifecyleWithCommitWithin() {
ExampleSolrBean toInsert = createDefaultExampleBean();
ExampleSolrBean savedBean = repository.save(toInsert, Duration.ofSeconds(10));
assertThat(savedBean).isSameAs(toInsert);
assertThat(repository.existsById(savedBean.getId())).isTrue();
ExampleSolrBean retrieved = repository.findById(savedBean.getId()).get();
assertThat(retrieved).isNotNull();
assertThat(EqualsBuilder.reflectionEquals(savedBean, retrieved, new String[] { "version" })).isTrue();
assertThat(repository.count()).isEqualTo(1);
assertThat(repository.existsById(savedBean.getId())).isTrue();
repository.delete(savedBean);
assertThat(repository.count()).isEqualTo(0);
assertThat(repository.findById(savedBean.getId()).isPresent()).isFalse();
}
}
| apache-2.0 |
leppa/home-assistant | homeassistant/components/automation/litejet.py | 3463 | """Trigger an automation when a LiteJet switch is released."""
import logging
import voluptuous as vol
from homeassistant.const import CONF_PLATFORM
from homeassistant.core import callback
import homeassistant.helpers.config_validation as cv
from homeassistant.helpers.event import track_point_in_utc_time
import homeassistant.util.dt as dt_util
# mypy: allow-untyped-defs, no-check-untyped-defs
_LOGGER = logging.getLogger(__name__)
CONF_NUMBER = "number"
CONF_HELD_MORE_THAN = "held_more_than"
CONF_HELD_LESS_THAN = "held_less_than"
TRIGGER_SCHEMA = vol.Schema(
{
vol.Required(CONF_PLATFORM): "litejet",
vol.Required(CONF_NUMBER): cv.positive_int,
vol.Optional(CONF_HELD_MORE_THAN): vol.All(
cv.time_period, cv.positive_timedelta
),
vol.Optional(CONF_HELD_LESS_THAN): vol.All(
cv.time_period, cv.positive_timedelta
),
}
)
async def async_attach_trigger(hass, config, action, automation_info):
"""Listen for events based on configuration."""
number = config.get(CONF_NUMBER)
held_more_than = config.get(CONF_HELD_MORE_THAN)
held_less_than = config.get(CONF_HELD_LESS_THAN)
pressed_time = None
cancel_pressed_more_than = None
@callback
def call_action():
"""Call action with right context."""
hass.async_run_job(
action,
{
"trigger": {
CONF_PLATFORM: "litejet",
CONF_NUMBER: number,
CONF_HELD_MORE_THAN: held_more_than,
CONF_HELD_LESS_THAN: held_less_than,
}
},
)
# held_more_than and held_less_than: trigger on released (if in time range)
# held_more_than: trigger after pressed with calculation
# held_less_than: trigger on released with calculation
# neither: trigger on pressed
@callback
def pressed_more_than_satisfied(now):
"""Handle the LiteJet's switch's button pressed >= held_more_than."""
call_action()
def pressed():
"""Handle the press of the LiteJet switch's button."""
nonlocal cancel_pressed_more_than, pressed_time
nonlocal held_less_than, held_more_than
pressed_time = dt_util.utcnow()
if held_more_than is None and held_less_than is None:
hass.add_job(call_action)
if held_more_than is not None and held_less_than is None:
cancel_pressed_more_than = track_point_in_utc_time(
hass, pressed_more_than_satisfied, dt_util.utcnow() + held_more_than
)
def released():
"""Handle the release of the LiteJet switch's button."""
nonlocal cancel_pressed_more_than, pressed_time
nonlocal held_less_than, held_more_than
# pylint: disable=not-callable
if cancel_pressed_more_than is not None:
cancel_pressed_more_than()
cancel_pressed_more_than = None
held_time = dt_util.utcnow() - pressed_time
if held_less_than is not None and held_time < held_less_than:
if held_more_than is None or held_time > held_more_than:
hass.add_job(call_action)
hass.data["litejet_system"].on_switch_pressed(number, pressed)
hass.data["litejet_system"].on_switch_released(number, released)
def async_remove():
"""Remove all subscriptions used for this trigger."""
return
return async_remove
| apache-2.0 |
blackcathacker/kc.preclean | coeus-code/src/main/java/org/kuali/kra/coi/disclosure/CoiDisclosureAction.java | 65675 | /*
* Copyright 2005-2014 The Kuali Foundation
*
* Licensed under the Educational Community 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.opensource.org/licenses/ecl1.php
*
* 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.kuali.kra.coi.disclosure;
import org.apache.commons.beanutils.BeanUtilsBean;
import org.apache.commons.beanutils.PropertyUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.codehaus.jackson.map.ObjectMapper;
import org.kuali.coeus.common.framework.attachment.AttachmentFile;
import org.kuali.coeus.common.framework.print.AbstractPrint;
import org.kuali.coeus.common.framework.print.Printable;
import org.kuali.coeus.common.framework.print.watermark.WatermarkService;
import org.kuali.coeus.sys.framework.controller.AuditActionHelper;
import org.kuali.coeus.sys.framework.controller.StrutsConfirmation;
import org.kuali.coeus.sys.framework.controller.SysFrameworkControllerConstants;
import org.kuali.coeus.sys.framework.service.KcServiceLocator;
import org.kuali.kra.coi.*;
import org.kuali.kra.coi.actions.CoiDisclosureActionService;
import org.kuali.kra.coi.certification.CertifyDisclosureEvent;
import org.kuali.kra.coi.certification.SubmitDisclosureAction;
import org.kuali.kra.coi.notesandattachments.CoiNotesAndAttachmentsHelper;
import org.kuali.kra.coi.notesandattachments.attachments.CoiDisclosureAttachment;
import org.kuali.kra.coi.notification.CoiNotification;
import org.kuali.kra.coi.print.CoiReportType;
import org.kuali.kra.coi.questionnaire.DisclosureModuleQuestionnaireBean;
import org.kuali.kra.coi.questionnaire.DisclosureQuestionnaireHelper;
import org.kuali.kra.coi.service.CoiPrintingService;
import org.kuali.kra.infrastructure.Constants;
import org.kuali.kra.infrastructure.KeyConstants;
import org.kuali.coeus.common.framework.print.AttachmentDataSource;
import org.kuali.coeus.common.questionnaire.framework.core.QuestionnaireHelperBase;
import org.kuali.coeus.common.questionnaire.framework.answer.AnswerHeader;
import org.kuali.coeus.common.questionnaire.framework.answer.QuestionnaireAnswerService;
import org.kuali.coeus.common.questionnaire.framework.answer.SaveQuestionnaireAnswerEvent;
import org.kuali.coeus.common.questionnaire.framework.print.QuestionnairePrintingService;
import org.kuali.rice.core.api.CoreApiServiceLocator;
import org.kuali.rice.core.api.util.KeyValue;
import org.kuali.rice.kew.api.KewApiConstants;
import org.kuali.rice.kew.api.exception.WorkflowException;
import org.kuali.rice.kns.question.ConfirmationQuestion;
import org.kuali.rice.kns.service.DictionaryValidationService;
import org.kuali.rice.kns.service.KNSServiceLocator;
import org.kuali.rice.kns.web.struts.form.KualiDocumentFormBase;
import org.kuali.rice.kns.web.struts.form.KualiForm;
import org.kuali.rice.krad.document.Document;
import org.kuali.rice.krad.keyvalues.KeyValuesFinder;
import org.kuali.rice.krad.util.GlobalVariables;
import org.kuali.rice.krad.util.KRADConstants;
import org.kuali.rice.krad.util.MessageMap;
import org.springframework.util.CollectionUtils;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class CoiDisclosureAction extends CoiAction {
private static final ActionForward RESPONSE_ALREADY_HANDLED = null;
private static final String ATTACHMENT_PATH = "document.coiDisclosureList[0].attachmentCoiDisclosures[";
private static final String CONFIRM_NO_DELETE = "";
private static final String DEFAULT_EVENT_ID_STRING = "label.coi.disclosure.type.id";
private static final String DEFAULT_EVENT_TITLE_STRING = "label.coi.disclosure.type.title";
protected static final String SCREENING_QUESTIONNAIRE_FAILURE_QUESTION = "CoiDisclosureScreeningQuestionnaireFailureQuestion";
public ActionForward addDisclosurePersonUnit(ActionMapping mapping, ActionForm form, HttpServletRequest request,
HttpServletResponse response) throws Exception {
CoiDisclosureForm coiDisclosureForm = (CoiDisclosureForm) form;
DisclosureHelper disclosureHelper = coiDisclosureForm.getDisclosureHelper();
if (checkRule(new AddDisclosureReporterUnitEvent("disclosureHelper.newDisclosurePersonUnit",
disclosureHelper.getNewDisclosurePersonUnit(), ((CoiDisclosureDocument) coiDisclosureForm.getDocument())
.getCoiDisclosure().getDisclosureReporter().getDisclosurePersonUnits()))) {
getCoiDisclosureService().addDisclosureReporterUnit(
((CoiDisclosureDocument)coiDisclosureForm.getDocument()).getCoiDisclosure().getDisclosureReporter(),
disclosureHelper.getNewDisclosurePersonUnit());
disclosureHelper.setNewDisclosurePersonUnit(new DisclosurePersonUnit());
}
return mapping.findForward(Constants.MAPPING_BASIC);
}
public ActionForward deleteDisclosurePersonUnit(ActionMapping mapping, ActionForm form, HttpServletRequest request,
HttpServletResponse response) throws Exception {
CoiDisclosureForm coiDisclosureForm = (CoiDisclosureForm) form;
DisclosureHelper disclosureHelper = coiDisclosureForm.getDisclosureHelper();
getCoiDisclosureService().deleteDisclosureReporterUnit(
((CoiDisclosureDocument) coiDisclosureForm.getDocument()).getCoiDisclosure().getDisclosureReporter(),
disclosureHelper.getDeletedUnits(), getSelectedLine(request));
return mapping.findForward(Constants.MAPPING_BASIC);
}
@Override
public final ActionForward save(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response)
throws Exception {
CoiDisclosureForm coiDisclosureForm = (CoiDisclosureForm) form;
CoiDisclosureDocument coiDisclosureDocument = (CoiDisclosureDocument)coiDisclosureForm.getDocument();
boolean isValid = true;
ActionForward actionForward = mapping.findForward(Constants.MAPPING_BASIC);
// notes and attachments
CoiNotesAndAttachmentsHelper helper = ((CoiDisclosureForm) form).getCoiNotesAndAttachmentsHelper();
CoiDisclosure coiDisclosure = coiDisclosureDocument.getCoiDisclosure();
helper.setOriginalDisclosureIdsIfNecessary(coiDisclosure);
if (coiDisclosure.getCoiDisclosureId() == null) {
coiDisclosure.initRequiredFields();
}
else {
getCoiDisclosureService().resetLeadUnit(coiDisclosure.getDisclosureReporter());
}
if (coiDisclosure.isUpdateEvent() ||(coiDisclosure.isAnnualEvent() && coiDisclosure.isAnnualUpdate())) {
isValid &= getCoiDisclosureService().setDisclProjectForSave(coiDisclosure, coiDisclosureForm.getDisclosureHelper().getMasterDisclosureBean());
}
getCoiDisclosureService().updateDisclosureAndProjectDisposition(coiDisclosure);
/************ Begin --- Save (if valid) document and questionnaire data ************/
// First validate the questionnaire data
if (coiDisclosure.getCoiDisclProjects() != null || !coiDisclosure.getCoiDisclProjects().isEmpty()) {
for (CoiDisclProject coiDisclProject : coiDisclosure.getCoiDisclProjects()) {
if (!new CoiDisclosureAdministratorActionRule().isValidDispositionStatus(coiDisclProject.getDisclosureDispositionCode())) {
isValid = false;
}
}
}
if (validateQuestionnaires(coiDisclosureForm)) {
// since Questionnaire data is OK we try to save doc
if (isValid) {
actionForward = super.save(mapping, form, request, response);
saveQuestionnaires(coiDisclosureForm);
}
helper.fixReloadedAttachments(request.getParameterMap());
}
/************ End --- Save (if valid) document and questionnaire data ************/
if (KRADConstants.SAVE_METHOD.equals(coiDisclosureForm.getMethodToCall()) && coiDisclosureForm.isAuditActivated()
&& GlobalVariables.getMessageMap().hasNoErrors()) {
actionForward = mapping.findForward("disclosureActions");
}
else if (coiDisclosure.isUpdateEvent() || (coiDisclosure.isAnnualEvent() && coiDisclosure.isAnnualUpdate())) {
actionForward = mapping.findForward(UPDATE_DISCLOSURE);
}
return actionForward;
}
protected boolean validateQuestionnaires(CoiDisclosureForm coiDisclosureForm) {
List<AnswerHeader> answerHeaders = generateListOfQuestionnaires(coiDisclosureForm);
return applyRules(new SaveQuestionnaireAnswerEvent(coiDisclosureForm.getCoiDisclosureDocument(), answerHeaders));
}
protected List<AnswerHeader> generateListOfQuestionnaires(CoiDisclosureForm coiDisclosureForm) {
List<AnswerHeader> answerHeaders = new ArrayList<AnswerHeader>();
answerHeaders.addAll(coiDisclosureForm.getDisclosureQuestionnaireHelper().getAnswerHeaders());
answerHeaders.addAll(coiDisclosureForm.getScreeningQuestionnaireHelper().getAnswerHeaders());
if (coiDisclosureForm.getDisclosureHelper().getMasterDisclosureBean() != null) {
List<List<CoiDisclosureProjectBean>> allProjects = coiDisclosureForm.getDisclosureHelper().getMasterDisclosureBean().getProjectLists();
for (List<CoiDisclosureProjectBean> projectList : allProjects) {
for (CoiDisclosureProjectBean bean : projectList) {
answerHeaders.addAll(bean.getAnswerHeaders());
}
}
}
return answerHeaders;
}
protected void saveQuestionnaires(CoiDisclosureForm coiDisclosureForm) {
List<AnswerHeader> answerHeaders = generateListOfQuestionnaires(coiDisclosureForm);
coiDisclosureForm.getDisclosureQuestionnaireHelper().preSave();
coiDisclosureForm.getScreeningQuestionnaireHelper().preSave();
if (coiDisclosureForm.getDisclosureHelper().getMasterDisclosureBean() != null) {
List<List<CoiDisclosureProjectBean>> allProjects = coiDisclosureForm.getDisclosureHelper().getMasterDisclosureBean().getProjectLists();
for (List<CoiDisclosureProjectBean> projectList : allProjects) {
for (CoiDisclosureProjectBean bean : projectList) {
bean.getProjectQuestionnaireHelper().preSave(coiDisclosureForm.getCoiDisclosureDocument().getCoiDisclosure());
}
}
}
getBusinessObjectService().save(answerHeaders);
}
@Override
public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response)
throws Exception {
String command = request.getParameter("command");
//KCCOI-278 added the load line above to fix master disclosure issues but this should really be done
// in all cases.
if (StringUtils.isNotBlank(command) && !StringUtils.containsIgnoreCase(command, KewApiConstants.INITIATE_COMMAND)) {
// 'view' in master disclosure's 'Disclosures' list
super.loadDocument((KualiDocumentFormBase) form);
}
CoiDisclosureForm coiDisclosureForm = (CoiDisclosureForm) form;
ActionForward actionForward = super.execute(mapping, form, request, response);
// we will populate questionnaire data after the execution of any dispatched ("methodTocall") methods. This point, right
// after the
// above super.execute() call works well for that because any such dispatched method has finished executing at the end of
// the call.
// we will populate questionnaire data after the execution of any dispatched "methodTocall" methods. This point, right
// after the above super.execute() call works well for that.
CoiDisclosureDocument coiDisclosureDocument = (CoiDisclosureDocument)coiDisclosureForm.getDocument();
CoiDisclosure coiDisclosure = coiDisclosureDocument.getCoiDisclosure();
// specify conditions to narrow down the range of the execution paths in which questionnaire data is populated
if ((coiDisclosureDocument.getDocumentHeader().hasWorkflowDocument())
&& !(coiDisclosure.isManualEvent() && CollectionUtils.isEmpty(coiDisclosure.getCoiDisclProjects()))) {
boolean forceQnnrReload = false;
// TODO : this is pretty hacky to refresh qn
if ((StringUtils.equals("reload", coiDisclosureForm.getMethodToCall()) && !coiDisclosure.isApprovedDisclosure() && !coiDisclosure.isAnnualUpdate() && !coiDisclosure.isUpdateEvent())
|| (StringUtils.equals("addManualProject", coiDisclosureForm.getMethodToCall()))) {
forceQnnrReload = true;
}
coiDisclosureForm.getDisclosureQuestionnaireHelper().prepareView(forceQnnrReload);
coiDisclosureForm.getScreeningQuestionnaireHelper().prepareView(forceQnnrReload);
}
// now the rest of subclass-specific custom logic for execute()
coiDisclosureDocument.getCoiDisclosure().initSelectedUnit();
if ((StringUtils.equals("reload", coiDisclosureForm.getMethodToCall())
|| StringUtils.equals("updateAttachmentFilter", coiDisclosureForm.getMethodToCall())
|| StringUtils.equals("headerTab", coiDisclosureForm.getMethodToCall()) || StringUtils.equals("docHandler",
coiDisclosureForm.getMethodToCall())) && coiDisclosureDocument.getCoiDisclosure().isApprovedDisclosure()) {
coiDisclosureForm.getDisclosureHelper().setMasterDisclosureBean(getCoiDisclosureService().getMasterDisclosureDetail(coiDisclosureDocument.getCoiDisclosure()));
setQuestionnaireStatuses(coiDisclosureForm);
actionForward = mapping.findForward(MASTER_DISCLOSURE);
}
else {
if (StringUtils.isNotBlank(command) && MASTER_DISCLOSURE.equals(command)) {
coiDisclosureDocument = (CoiDisclosureDocument) coiDisclosureForm.getDocument();
coiDisclosureDocument.getCoiDisclosure().initSelectedUnit();
coiDisclosureForm.getDisclosureHelper().setMasterDisclosureBean(getCoiDisclosureService().getMasterDisclosureDetail(coiDisclosureDocument.getCoiDisclosure()));
setQuestionnaireStatuses(coiDisclosureForm);
actionForward = mapping.findForward(MASTER_DISCLOSURE);
}
}
if (coiDisclosure.isManualEvent() && !CollectionUtils.isEmpty(coiDisclosure.getCoiDisclProjects())) {
coiDisclosure.getCoiDisclProjects().get(0).initHeaderItems();
}
// initialize the permissions for notes and attachments helper
//coiDisclosure was becoming null here, so loading the document above.
//KCCOI-278 added the line above to fix master disclosure issues but this should really be done
// in all cases.
coiDisclosureForm.getCoiNotesAndAttachmentsHelper().prepareView();
return actionForward;
}
@Override
public ActionForward docHandler(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response)
throws Exception {
CoiDisclosureForm coiDisclosureForm = (CoiDisclosureForm) form;
String command = coiDisclosureForm.getCommand();
ActionForward forward = mapping.findForward(Constants.MAPPING_BASIC);
String eventTypeCode = CoiDisclosureEventType.ANNUAL;
if (command.startsWith(KewApiConstants.INITIATE_COMMAND)) {
String[] parts = command.split("_");
if (parts.length > 1) {
eventTypeCode = parts[1];
}
// check to see if there's an existing update master or annual that is not approved/disapproved
CoiDisclosure coiDisclosure = null;
if (StringUtils.equals(eventTypeCode, CoiDisclosureEventType.UPDATE)
|| StringUtils.equals(eventTypeCode, CoiDisclosureEventType.ANNUAL)) {
coiDisclosure = getExistingDisclosure(eventTypeCode);
}
// if an existing update master exists, let's load it, otherwise initiate
if (coiDisclosure != null) {
coiDisclosureForm.setCommand(KewApiConstants.DOCSEARCH_COMMAND);
coiDisclosureForm.setDocId(coiDisclosure.getCoiDisclosureDocument().getDocumentNumber());
} else {
coiDisclosureForm.setCommand(KewApiConstants.INITIATE_COMMAND);
coiDisclosure = getCoiDisclosureService().versionCoiDisclosure();
// quick-fix: resetting the annual update flag value inherited via above versioning
if(coiDisclosure != null) {
coiDisclosure.setAnnualUpdate(false);
}
}
forward = super.docHandler(mapping, form, request, response);
if (CoiDisclosureEventType.UPDATE.equals(eventTypeCode) || (KewApiConstants.INITIATE_COMMAND.startsWith(command)
&& KRADConstants.DOC_HANDLER_METHOD.equals(coiDisclosureForm.getMethodToCall()) && isMasterDisclosureExist())) {
// update master disclosure or annual event with master disclosure exist
if (!isMasterDisclosureExist()) {
// minor hack to force CoiDisclosureForm to hide Actions tab
coiDisclosureForm.setMethodToCall("viewMasterDisclosure");
forward = mapping.findForward("masterDisclosureNotAvailable");
}
else {
if (StringUtils.equals(coiDisclosureForm.getCommand(), KewApiConstants.INITIATE_COMMAND)) {
getCoiDisclosureService().initDisclosureFromMasterDisclosure(coiDisclosure);
if (StringUtils.equals(eventTypeCode, CoiDisclosureEventType.ANNUAL)) {
coiDisclosure.setAnnualUpdate(true);
}
coiDisclosure.setEventTypeCode(eventTypeCode);
coiDisclosureForm.getDisclosureHelper().setMasterDisclosureBean(getCoiDisclosureService().getMasterDisclosureDetail(coiDisclosure));
if (coiDisclosure != null) {
coiDisclosureForm.getCoiDisclosureDocument().setCoiDisclosure(coiDisclosure);
coiDisclosure.setCoiDisclosureDocument(coiDisclosureForm.getCoiDisclosureDocument());
}
setQuestionnaireStatuses(coiDisclosureForm, coiDisclosure);
}else {
coiDisclosureForm.getDisclosureHelper().setMasterDisclosureBean(getCoiDisclosureService().getMasterDisclosureDetail(coiDisclosure));
}
forward = mapping.findForward(UPDATE_DISCLOSURE);
}
}
if (coiDisclosure != null) {
coiDisclosureForm.getCoiDisclosureDocument().setCoiDisclosure(coiDisclosure);
coiDisclosure.setCoiDisclosureDocument(coiDisclosureForm.getCoiDisclosureDocument());
}
coiDisclosureForm.getCoiDisclosureDocument().getCoiDisclosure().setEventTypeCode(eventTypeCode);
if (coiDisclosureForm.getCoiDisclosureDocument().getCoiDisclosure().getCoiDisclosureId() == null) {
coiDisclosureForm.getCoiDisclosureDocument().getCoiDisclosure().initRequiredFields();
}
else {
getCoiDisclosureService().resetLeadUnit(coiDisclosure.getDisclosureReporter());
}
}
else {
coiDisclosureForm.setCommand(KewApiConstants.DOCSEARCH_COMMAND);
super.docHandler(mapping, form, request, response);
CoiDisclosure coiDisclosure = coiDisclosureForm.getCoiDisclosureDocument().getCoiDisclosure();
if (coiDisclosure.isUpdateEvent() || (coiDisclosure.isAnnualEvent() && coiDisclosure.isAnnualUpdate())) {
coiDisclosureForm.getDisclosureHelper().setMasterDisclosureBean(getCoiDisclosureService().getMasterDisclosureDetail(coiDisclosureForm.getCoiDisclosureDocument().getCoiDisclosure()));
setQuestionnaireStatuses(coiDisclosureForm);
forward = mapping.findForward("updateDisclosure");
}
}
((CoiDisclosureForm)form).getDisclosureHelper().prepareView();
((CoiDisclosureForm)form).getCoiNotesAndAttachmentsHelper().prepareView();
if (!coiDisclosureForm.getCoiDisclosureDocument().getCoiDisclosure().isUpdateEvent()
&& (coiDisclosureForm.getCoiDisclosureDocument().getDocumentHeader().getWorkflowDocument().isInitiated() || coiDisclosureForm.getCoiDisclosureDocument().getDocumentHeader().getWorkflowDocument().isSaved())) {
checkToLoadDisclosureDetails(coiDisclosureForm.getCoiDisclosureDocument().getCoiDisclosure(),
((CoiDisclosureForm) form).getMethodToCall(), coiDisclosureForm.getDisclosureHelper().getNewProjectId(),
coiDisclosureForm.getDisclosureHelper().getNewModuleItemKey());
}
coiDisclosureForm.getCoiDisclosureDocument().getCoiDisclosure().refreshReferenceObject("coiDispositionStatus");
coiDisclosureForm.getCoiDisclosureDocument().getCoiDisclosure().setCoiDisclosureAttachmentFilter(coiDisclosureForm.getCoiNotesAndAttachmentsHelper().getNewAttachmentFilter());
return forward;
}
private void setQuestionnaireStatuses(CoiDisclosureForm coiDisclosureForm) {
coiDisclosureForm.getDisclosureQuestionnaireHelper().setAnswerHeaders(
coiDisclosureForm.getDisclosureHelper().getMasterDisclosureBean().getAnswerHeaders());
coiDisclosureForm.getDisclosureQuestionnaireHelper().resetHeaderLabels();
coiDisclosureForm.getDisclosureQuestionnaireHelper().setAnswerQuestionnaire(false);
coiDisclosureForm.getDisclosureQuestionnaireHelper().setQuestionnaireActiveStatuses();
for (AnswerHeader answerHeader : coiDisclosureForm.getDisclosureQuestionnaireHelper().getAnswerHeaders()) {
getQuestionnaireAnswerService().setupChildAnswerIndicator(answerHeader);
}
}
private void setQuestionnaireStatuses(CoiDisclosureForm coiDisclosureForm, CoiDisclosure coiDisclosure) {
coiDisclosureForm.getDisclosureQuestionnaireHelper().setAnswerHeaders(
coiDisclosureForm.getDisclosureHelper().getMasterDisclosureBean().getAnswerHeaders());
List<AnswerHeader> answerHeaders = getQuestionnaireAnswerService().getQuestionnaireAnswer(
new DisclosureModuleQuestionnaireBean(coiDisclosure));
if (CollectionUtils.isEmpty(coiDisclosureForm.getDisclosureQuestionnaireHelper().getAnswerHeaders())) {
coiDisclosureForm.getDisclosureHelper().getMasterDisclosureBean().getAnswerHeaders().addAll(answerHeaders);
} else {
for (AnswerHeader answerHeader : answerHeaders) {
boolean exists = false;
for (AnswerHeader existingHeader : coiDisclosureForm.getDisclosureQuestionnaireHelper().getAnswerHeaders()) {
if (StringUtils.equals(existingHeader.getModuleSubItemCode(), answerHeader.getModuleSubItemCode())
&& existingHeader.getQuestionnaireId().equals(answerHeader.getQuestionnaireId())) {
exists = true;
break;
}
}
if (!exists) {
coiDisclosureForm.getDisclosureHelper().getMasterDisclosureBean().getAnswerHeaders().add(answerHeader);
}
}
}
coiDisclosureForm.getDisclosureQuestionnaireHelper().resetHeaderLabels();
coiDisclosureForm.getDisclosureQuestionnaireHelper().setAnswerQuestionnaire(false);
coiDisclosureForm.getDisclosureQuestionnaireHelper().setQuestionnaireActiveStatuses();
}
private QuestionnaireAnswerService getQuestionnaireAnswerService() {
return KcServiceLocator.getService(QuestionnaireAnswerService.class);
}
private void checkToLoadDisclosureDetails(CoiDisclosure coiDisclosure, String methodToCall, String projectId,
String moduleItemKey) {
// TODO : load FE disclosure when creating coi disc
// still need more clarification on whether there is any other occasion this need to be loaded
if (coiDisclosure.getCoiDisclosureId() == null && !hasDisclosureDetails(coiDisclosure)) {
if (StringUtils.equals("newProjectDisclosure", methodToCall) && projectId != null) {
getCoiDisclosureService().initializeDisclosureProject(coiDisclosure, projectId);
coiDisclosure.setModuleItemKey(moduleItemKey);
}
else {
getCoiDisclosureService().initializeDisclosureDetails(coiDisclosure);
coiDisclosure.setModuleItemKey(projectId);
}
}
else {
if (!StringUtils.equals("addProposal", methodToCall) && !StringUtils.equals("save", methodToCall) && !CollectionUtils.isEmpty(coiDisclosure.getCoiDisclProjects())) {
for (CoiDisclProject coiDisclProject : coiDisclosure.getCoiDisclProjects()) {
// TODO : need to look into this condition further
if (!StringUtils.equals("addProposal", methodToCall) && !StringUtils.equals("save", methodToCall) && coiDisclProject.getCoiDisclProjectsId() != null) {
getCoiDisclosureService().updateDisclosureDetails(coiDisclProject);
}
}
}
}
// TODO : for manual proposal project
if (coiDisclosure.isManualEvent() && !CollectionUtils.isEmpty(coiDisclosure.getCoiDisclProjects())) {
for (CoiDisclProject coiDisclProject : coiDisclosure.getCoiDisclProjects()) {
// TODO : need to look into this condition further
if (!StringUtils.equals("addProposal", methodToCall) && !StringUtils.equals("save", methodToCall)
&& coiDisclProject.getCoiDisclProjectsId() != null) {
getCoiDisclosureService().updateDisclosureDetails(coiDisclProject);
}
}
}
}
public ActionForward newFinancialEntity(ActionMapping mapping, ActionForm form, HttpServletRequest request,
HttpServletResponse response) throws Exception {
ActionForward actionForward = save(mapping, form, request, response);
if (GlobalVariables.getMessageMap().hasNoErrors()) {
CoiDisclosureForm coiDisclosureForm = (CoiDisclosureForm) form;
CoiDisclosure coiDisclosure = ((CoiDisclosureDocument)coiDisclosureForm.getDocument()).getCoiDisclosure();
String forward = CoreApiServiceLocator.getKualiConfigurationService().getPropertyValueAsString(SysFrameworkControllerConstants.CONFIG_KUALI_DOCHANDLER_URL_PREFIX)
+ "/financialEntityEditNew.do?methodToCall=addNewCoiDiscFinancialEntity&coiDocId="
+ ((CoiDisclosureForm) form).getDocument().getDocumentNumber() + "&financialEntityHelper.reporterId="
+ coiDisclosure.getPersonId();
return new ActionForward(forward, true);
}
return actionForward;
}
public ActionForward editFinancialEntity(ActionMapping mapping, ActionForm form, HttpServletRequest request,
HttpServletResponse response) throws Exception {
ActionForward actionForward = save(mapping, form, request, response);
if (GlobalVariables.getMessageMap().hasNoErrors()) {
CoiDisclosureForm coiDisclosureForm = (CoiDisclosureForm) form;
CoiDisclosure coiDisclosure = ((CoiDisclosureDocument)coiDisclosureForm.getDocument()).getCoiDisclosure();
String forward = CoreApiServiceLocator.getKualiConfigurationService().getPropertyValueAsString(SysFrameworkControllerConstants.CONFIG_KUALI_DOCHANDLER_URL_PREFIX)
+ "/financialEntityEditList.do?methodToCall=editActiveFinancialEntity&coiDocId="
+ ((CoiDisclosureForm) form).getDocument().getDocumentNumber() + "&financialEntityHelper.editCoiEntityId="
+ coiDisclosure.getCoiDisclProjects().get(0).getCoiDiscDetails().get(getSelectedLine(request)).getPersonFinIntDisclosureId();
return new ActionForward(forward, true);
}
return actionForward;
}
public ActionForward addManualProject(ActionMapping mapping, ActionForm form, HttpServletRequest request,
HttpServletResponse response) throws Exception {
CoiDisclosureForm coiDisclosureForm = (CoiDisclosureForm) form;
DisclosureHelper disclosureHelper = coiDisclosureForm.getDisclosureHelper();
CoiDisclosure coiDisclosure = coiDisclosureForm.getCoiDisclosureDocument().getCoiDisclosure();
disclosureHelper.getNewCoiDisclProject().setCoiDisclosure(coiDisclosure);
disclosureHelper.getNewCoiDisclProject().setCoiDisclosureNumber(coiDisclosure.getCoiDisclosureNumber());
disclosureHelper.getNewCoiDisclProject().setModuleItemKey(disclosureHelper.getNewCoiDisclProject().getCoiProjectId());
disclosureHelper.getNewCoiDisclProject().setDisclosureStatusCode(CoiDisclosureStatus.IN_PROGRESS);
disclosureHelper.getNewCoiDisclProject().setDisclosureDispositionCode(CoiDispositionStatus.IN_PROGRESS);
disclosureHelper.getNewCoiDisclProject().refreshReferenceObject("coiDispositionStatus");
if (checkRule(new AddManualProjectEvent("disclosureHelper.newCoiDisclProject", disclosureHelper.getNewCoiDisclProject()))) {
getCoiDisclosureService().initializeDisclosureDetails(disclosureHelper.getNewCoiDisclProject());
disclosureHelper.getNewCoiDisclProject().setSequenceNumber(coiDisclosure.getSequenceNumber());
disclosureHelper.getNewCoiDisclProject().initHeaderItems();
coiDisclosure.getCoiDisclProjects().add(disclosureHelper.getNewCoiDisclProject());
coiDisclosure.setModuleItemKey(disclosureHelper.getNewCoiDisclProject().getProjectId());
coiDisclosure.setEventTypeCode(disclosureHelper.getNewCoiDisclProject().getDisclosureEventType());
disclosureHelper.setNewCoiDisclProject(new CoiDisclProject(coiDisclosure.getCoiDisclosureNumber(), coiDisclosure
.getSequenceNumber()));
}
return mapping.findForward(Constants.MAPPING_BASIC);
}
public ActionForward getDisclosuresToComplete(ActionMapping mapping, ActionForm form, HttpServletRequest request,
HttpServletResponse response) throws Exception {
String userId = getUserId();
DisclosureHelper disclosureHelper = ((CoiDisclosureForm) form).getDisclosureHelper();
getCoiDisclosureService().populateProposalsAndAwardToCompleteDisclosure(userId, disclosureHelper);
disclosureHelper.setNewProtocols(getCoiDisclosureService().getProtocols(userId));
disclosureHelper.setNewIacucProtocols(getCoiDisclosureService().getIacucProtocols(userId));
return mapping.findForward(Constants.MAPPING_BASIC);
}
public ActionForward newProjectDisclosure(ActionMapping mapping, ActionForm form, HttpServletRequest request,
HttpServletResponse response) throws Exception {
CoiDisclosureForm coiDisclosureForm = (CoiDisclosureForm) form;
coiDisclosureForm.setCommand(KewApiConstants.INITIATE_COMMAND + "_" + coiDisclosureForm.getDisclosureHelper().getEventTypeCode());
ActionForward forward = docHandler(mapping, form, request, response);
// Currently the way docHandler() is implemented in this class guarantees that setting the form command to 'initiate' will
// result in a disclosure
// version being created and set on the document in the form. This means the following code for versioning the disclosure
// and setting it on the
// form is redundant as it has already happened in the doc handler invocation above, hence its being commented out.
coiDisclosureForm.getCoiDisclosureDocument().getCoiDisclosure()
.setEventTypeCode(coiDisclosureForm.getDisclosureHelper().getEventTypeCode());
// dochandler may populate discdetails for new doc. here is just to reset to reload it again.
coiDisclosureForm.getCoiDisclosureDocument().getCoiDisclosure().setCoiDisclProjects(null);
checkToLoadDisclosureDetails(coiDisclosureForm.getCoiDisclosureDocument().getCoiDisclosure(),
((CoiDisclosureForm) form).getMethodToCall(), coiDisclosureForm.getDisclosureHelper().getNewProjectId(),
coiDisclosureForm.getDisclosureHelper().getNewModuleItemKey());
return forward;
}
public ActionForward submitDisclosureCertification(ActionMapping mapping, ActionForm form, HttpServletRequest request,
HttpServletResponse response) throws Exception {
ActionForward forward = mapping.findForward(Constants.MAPPING_BASIC);
CoiDisclosureForm coiDisclosureForm = (CoiDisclosureForm) form;
save(mapping, coiDisclosureForm, request, response);
CoiDisclosureDocument coiDisclosureDocument = (CoiDisclosureDocument)coiDisclosureForm.getDocument();
CoiDisclosure coiDisclosure = coiDisclosureDocument.getCoiDisclosure();
if (checkRule(new CertifyDisclosureEvent("disclosureHelper.certifyDisclosure", coiDisclosure))) {
coiDisclosureForm.setAuditActivated(true);
coiDisclosureForm.setUnitRulesMessages(getUnitRulesMessages(coiDisclosureForm.getCoiDisclosureDocument()));
AuditActionHelper auditActionHelper = new AuditActionHelper();
if (auditActionHelper.auditUnconditionally(coiDisclosureDocument) && !coiDisclosureForm.isUnitRulesErrorsExist()) {
// Certification occurs after the audit rules pass.
if (coiDisclosure.getCoiDisclosureId() == null) {
coiDisclosure.initRequiredFields();
}
else {
getCoiDisclosureService().resetLeadUnit(coiDisclosure.getDisclosureReporter());
}
/************ Begin --- Save (if valid) document and questionnaire data ************/
// TODO factor out the different versions of this doc and questionnaire data save block from various actions in this
// class and centralize it in a helper method
// First validate the questionnaire data
// TODO maybe add a COI questionnaire specific rule event to the condition below
if (validateQuestionnaires(coiDisclosureForm)) {
if (!getCoiDisclosureService().checkScreeningQuestionnaireRule(coiDisclosureDocument)) {
return promptForScreeningQuestionnaireFailure(mapping, form, request, response);
}
// since Questionnaire data is OK we try to save doc
getDocumentService().saveDocument(coiDisclosureDocument);
saveQuestionnaires(coiDisclosureForm);
// set the disclosure codes
coiDisclosure.setDisclosureDispositionCode(CoiDispositionStatus.SUBMITTED_FOR_REVIEW);
coiDisclosure.setDisclosureStatusCode(CoiDisclosureStatus.ROUTED_FOR_REVIEW);
// Update the corresponding discl project
getCoiDisclosureActionService().updateCoiDisclProjectStatus(coiDisclosure, CoiDisclosureStatus.ROUTED_FOR_REVIEW);
getCoiDisclosureActionService().updateCoiDisclProjectDisposition(coiDisclosure, CoiDispositionStatus.NO_CONFLICT_EXISTS);
// Certification occurs after the audit rules pass, and the document and the questionnaire data have been
// saved successfully
coiDisclosure.certifyDisclosure();
GlobalVariables.getMessageMap().putInfo("datavalidation", KeyConstants.MESSAGE_COI_CERT_SUBMITTED, new String[] {});
forward = submitForReviewAndRedirect(mapping, form, request, response, coiDisclosureForm, coiDisclosure,
coiDisclosureDocument);
}
/************ End --- Save (if valid) document and questionnaire data ************/
}
else {
GlobalVariables.getMessageMap().clearErrorMessages();
GlobalVariables.getMessageMap().putError("datavalidation", KeyConstants.ERROR_WORKFLOW_SUBMISSION, new String[] {});
}
}
return forward;
}
protected ActionForward promptForScreeningQuestionnaireFailure(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception {
Object question = request.getParameter(KRADConstants.QUESTION_INST_ATTRIBUTE_NAME);
Object buttonClicked = request.getParameter(KRADConstants.QUESTION_CLICKED_BUTTON);
String methodToCall = ((KualiForm) form).getMethodToCall();
if(question == null){
return this.performQuestionWithoutInput(mapping, form, request, response, SCREENING_QUESTIONNAIRE_FAILURE_QUESTION, "Based on answers to the screening questionnaire you are required to have at least one active financial entity to submit this disclosure. Would you like add a financial entity at this time?", KRADConstants.CONFIRMATION_QUESTION, methodToCall, "");
} else if(SCREENING_QUESTIONNAIRE_FAILURE_QUESTION.equals(question) && ConfirmationQuestion.YES.equals(buttonClicked)) {
return newFinancialEntity(mapping, form, request, response);
} else {
return mapping.findForward(Constants.MAPPING_BASIC);
}
}
public ActionForward printDisclosureCertification(ActionMapping mapping, ActionForm form, HttpServletRequest request,
HttpServletResponse response) throws Exception {
ActionForward actionForward = mapping.findForward(Constants.MAPPING_BASIC);
CoiDisclosure coiDisclosure = ((CoiDisclosureForm)form).getCoiDisclosureDocument().getCoiDisclosure();
coiDisclosure.setCertificationText(new String(coiDisclosure.getAcknowledgementStatement()));
List<Printable> printableArtifactList = new ArrayList<Printable>();
AbstractPrint printable;
printable = getCoiPrintingService().getCoiPrintable(CoiReportType.COI_APPROVED_DISCLOSURE);
printable.setPrintableBusinessObject(coiDisclosure);
printableArtifactList.add(printable);
AttachmentDataSource dataStream = getCoiPrintingService().print(printableArtifactList);
streamToResponse(dataStream, response);
actionForward = RESPONSE_ALREADY_HANDLED;
return actionForward;
}
private String getUserId() {
return GlobalVariables.getUserSession().getPrincipalId();
}
/****
* COI NOTES AND ATTACHMENTS
* **/
public ActionForward replaceAttachmentCoi(ActionMapping mapping, ActionForm form, HttpServletRequest request,
HttpServletResponse response) throws Exception {
int selection = this.getSelectedLine(request);
CoiNotesAndAttachmentsHelper helper = ((CoiDisclosureForm) form).getCoiNotesAndAttachmentsHelper();
CoiDisclosureAttachment attachment = helper.retrieveExistingAttachmentByType(selection);
return mapping.findForward(Constants.MAPPING_BASIC);
}
public ActionForward addAttachmentCoi(ActionMapping mapping, ActionForm form, HttpServletRequest request,
HttpServletResponse response) throws Exception {
save(mapping, form, request, response);
CoiNotesAndAttachmentsHelper helper = ((CoiDisclosureForm) form).getCoiNotesAndAttachmentsHelper();
helper.addNewCoiDisclosureAttachment();
return mapping.findForward(Constants.MAPPING_BASIC);
}
public ActionForward deleteCoiDisclosureAttachment(ActionMapping mapping, ActionForm form, HttpServletRequest request,
HttpServletResponse response) throws Exception {
int selection = this.getSelectedLine(request);
CoiNotesAndAttachmentsHelper helper = ((CoiDisclosureForm) form).getCoiNotesAndAttachmentsHelper();
final CoiDisclosureAttachment attachment = helper.retrieveExistingAttachmentByType(selection);
if (isValidContactData(attachment, ATTACHMENT_PATH + selection + "]")) {
return confirmDeleteAttachment(mapping, (CoiDisclosureForm) form, request, response);
}
else {
return mapping.findForward(Constants.MAPPING_BASIC);
}
}
protected boolean isValidContactData(CoiDisclosureAttachment attachment, String errorPath) {
MessageMap errorMap = GlobalVariables.getMessageMap();
errorMap.addToErrorPath(errorPath);
getDictionaryValidationService().validateBusinessObject(attachment);
errorMap.removeFromErrorPath(errorPath);
return errorMap.hasNoErrors();
}
protected DictionaryValidationService getDictionaryValidationService() {
return KNSServiceLocator.getKNSDictionaryValidationService();
}
protected ActionForward confirmDeleteAttachment(ActionMapping mapping, CoiDisclosureForm form, HttpServletRequest request,
HttpServletResponse response) throws Exception {
final int selection = this.getSelectedLine(request);
CoiNotesAndAttachmentsHelper helper = ((CoiDisclosureForm) form).getCoiNotesAndAttachmentsHelper();
final CoiDisclosureAttachment attachment = helper.retrieveExistingAttachmentByType(selection);
if (attachment == null) {
//may want to tell the user the selection was invalid.
return mapping.findForward(Constants.MAPPING_BASIC);
}
final String confirmMethod = helper.retrieveConfirmMethodByType();
final StrutsConfirmation confirm = buildParameterizedConfirmationQuestion(mapping, form, request, response, confirmMethod,
KeyConstants.QUESTION_DELETE_ATTACHMENT_CONFIRMATION, attachment.getDescription(), attachment.getFile().getName());
return confirm(confirm, confirmMethod, CONFIRM_NO_DELETE);
}
public ActionForward confirmDeleteCoiDisclosureAttachment(ActionMapping mapping, ActionForm form, HttpServletRequest request,
HttpServletResponse response) throws Exception {
return this.deleteAttachment(mapping, (CoiDisclosureForm) form, request, response, CoiDisclosureAttachment.class);
}
private ActionForward deleteAttachment(ActionMapping mapping, CoiDisclosureForm form, HttpServletRequest request,
HttpServletResponse response, Class<CoiDisclosureAttachment> attachmentType) throws Exception {
final int selection = this.getSelectedLine(request);
CoiNotesAndAttachmentsHelper helper = ((CoiDisclosureForm) form).getCoiNotesAndAttachmentsHelper();
if (!helper.deleteExistingAttachmentByType(selection)) {
//may want to tell the user the selection was invalid.
}
return mapping.findForward(Constants.MAPPING_BASIC);
}
public ActionForward viewAttachmentCoi(ActionMapping mapping, ActionForm form, HttpServletRequest request,
HttpServletResponse response) throws Exception {
final int selection = this.getSelectedLine(request);
CoiNotesAndAttachmentsHelper helper = ((CoiDisclosureForm) form).getCoiNotesAndAttachmentsHelper();
final CoiDisclosureAttachment attachment = helper.retrieveExistingAttachmentByType(selection);
if (attachment == null) {
//may want to tell the user the selection was invalid.
return mapping.findForward(Constants.MAPPING_BASIC);
}
final AttachmentFile file = attachment.getFile();
byte[] attachmentFile = null;
String attachmentFileType = file.getType().replace("\"", "");
this.streamToResponse(file.getData(), getValidHeaderString(file.getName()), getValidHeaderString(file.getType()), response);
return RESPONSE_ALREADY_HANDLED;
}
public ActionForward updateAttachmentFilter(ActionMapping mapping, ActionForm form, HttpServletRequest request,
HttpServletResponse response) throws Exception {
CoiNotesAndAttachmentsHelper helper = ((CoiDisclosureForm) form).getCoiNotesAndAttachmentsHelper();
helper.addNewCoiDisclosureAttachmentFilter();
return mapping.findForward(Constants.MAPPING_BASIC);
}
@Override
public void postSave(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response)
throws Exception {
super.postSave(mapping, form, request, response);
CoiNotesAndAttachmentsHelper helper = ((CoiDisclosureForm) form).getCoiNotesAndAttachmentsHelper();
if (!(helper.getFilesToDelete().isEmpty())) {
getBusinessObjectService().delete((helper.getFilesToDelete()));
helper.getFilesToDelete().clear();
}
for (CoiDisclosureAttachment attachment : ((CoiDisclosureForm) form).getCoiDisclosureDocument().getCoiDisclosure()
.getCoiDisclosureAttachments()) {
// for some reason, change and save, this list is not updated
attachment.getCoiDisclosure().refreshReferenceObject("coiDisclosureAttachments");
}
}
public ActionForward addNote(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response)
throws Exception {
CoiNotesAndAttachmentsHelper helper = ((CoiDisclosureForm) form).getCoiNotesAndAttachmentsHelper();
helper.addNewNote();
save(mapping, form, request, response);
helper.setManageNotesOpen();
return mapping.findForward(Constants.MAPPING_BASIC);
}
public ActionForward editNote(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response)
throws Exception {
final int selection = this.getSelectedLine(request);
CoiDisclosureForm disclosureForm = (CoiDisclosureForm) form;
CoiNotesAndAttachmentsHelper helper = disclosureForm.getCoiNotesAndAttachmentsHelper();
// add authorization here
helper.editNote(selection);
return mapping.findForward(Constants.MAPPING_BASIC);
}
public ActionForward deleteNote(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response)
throws Exception {
CoiNotesAndAttachmentsHelper helper = ((CoiDisclosureForm) form).getCoiNotesAndAttachmentsHelper();
// add authorization here
return confirmDeleteNote(mapping, (CoiDisclosureForm) form, request, response);
}
protected ActionForward confirmDeleteNote(ActionMapping mapping, CoiDisclosureForm form, HttpServletRequest request,
HttpServletResponse response) throws Exception {
final int selection = this.getSelectedLine(request);
final String confirmMethod = "deleteNoteConfirmed";
final StrutsConfirmation confirm = buildParameterizedConfirmationQuestion(mapping, form, request, response, confirmMethod,
KeyConstants.QUESTION_DELETE_NOTE_CONFIRMATION);
return confirm(confirm, confirmMethod, CONFIRM_NO_DELETE);
}
public ActionForward deleteNoteConfirmed(ActionMapping mapping, ActionForm form, HttpServletRequest request,
HttpServletResponse response) throws Exception {
final int selection = this.getSelectedLine(request);
if (!((CoiDisclosureForm)form).getCoiNotesAndAttachmentsHelper().deleteNote(selection)) {
//may want to tell the user the selection was invalid.
}
return mapping.findForward(Constants.MAPPING_BASIC);
}
protected CoiPrintingService getCoiPrintingService() {
return KcServiceLocator.getService(CoiPrintingService.class);
}
protected WatermarkService getWatermarkService() {
return KcServiceLocator.getService(WatermarkService.class);
}
protected CoiDisclosureActionService getDisclosureActionService() {
return KcServiceLocator.getService(CoiDisclosureActionService.class);
}
@SuppressWarnings({ "rawtypes", "unchecked" })
public ActionForward viewMasterDisclosure(ActionMapping mapping, ActionForm form, HttpServletRequest request,
HttpServletResponse response) throws Exception {
CoiDisclosureForm coiDisclosureForm = (CoiDisclosureForm) form;
return viewMasterDisclosure(GlobalVariables.getUserSession().getPrincipalId(), coiDisclosureForm, mapping);
}
public ActionForward viewMasterDisclosure(String personId, CoiDisclosureForm coiDisclosureForm, ActionMapping mapping) throws WorkflowException {
DisclosureHelper disclosureHelper = coiDisclosureForm.getDisclosureHelper();
Map fieldValues = new HashMap();
fieldValues.put("personId", personId);
fieldValues.put("currentDisclosure", "Y");
List<CoiDisclosure> disclosures = (List<CoiDisclosure>) getBusinessObjectService().findMatching(CoiDisclosure.class, fieldValues);
disclosureHelper.prepareView();
if (CollectionUtils.isEmpty(disclosures)) {
return mapping.findForward("masterDisclosureNotAvailable");
}
else {
coiDisclosureForm.setDocId(disclosures.get(0).getCoiDisclosureDocument().getDocumentNumber());
loadDocument(coiDisclosureForm);
disclosureHelper.setMasterDisclosureBean(getCoiDisclosureService().getMasterDisclosureDetail(coiDisclosureForm.getCoiDisclosureDocument().getCoiDisclosure()));
setQuestionnaireStatuses(coiDisclosureForm);
return mapping.findForward("masterDisclosure");
}
}
private ActionForward submitForReviewAndRedirect(ActionMapping mapping, ActionForm form, HttpServletRequest request,
HttpServletResponse response, CoiDisclosureForm coiDisclosureForm, CoiDisclosure coiDisclosure,
CoiDisclosureDocument coiDisclosureDocument) throws Exception {
SubmitDisclosureAction submitAction = coiDisclosureForm.getDisclosureActionHelper().getSubmitDisclosureAction();
ActionForward action = getDisclosureActionService().sendCertificationNotifications(coiDisclosureDocument,
coiDisclosureForm, submitAction, mapping);
if (action != null) {
return action;
}
getDisclosureActionService().submitToWorkflow(coiDisclosureDocument, coiDisclosureForm, submitAction);
//Since we are exiting the disclosure through a non-standard method, lets release
//any pessimistic locks
this.attemptLockRelease(coiDisclosureDocument, KRADConstants.CLOSE_METHOD);
return routeDisclosureToHoldingPage(mapping, coiDisclosureForm);
}
private ActionForward routeDisclosureToHoldingPage(ActionMapping mapping, CoiDisclosureForm coiDisclosureForm) {
String routeHeaderId = coiDisclosureForm.getDocument().getDocumentNumber();
String returnLocation = buildActionUrl(routeHeaderId, Constants.MAPPING_BASIC, "CoiDisclosureDocument");
ActionForward basicForward = mapping.findForward(KRADConstants.MAPPING_PORTAL);
ActionForward holdingPageForward = mapping.findForward(Constants.MAPPING_HOLDING_PAGE);
return routeToHoldingPage(basicForward, basicForward, holdingPageForward, returnLocation);
}
/**
*
* This method is for use with a JSON/AJAX call and should not be used as a post method
*
*/
public ActionForward getDisclosureEventTypeInfo(ActionMapping mapping, ActionForm form, HttpServletRequest request,
HttpServletResponse response) throws Exception {
String eventType = request.getParameter("eventType");
Map<String, Object> fieldValues = new HashMap<String, Object>();
fieldValues.put("eventTypeCode", eventType);
List<CoiDisclosureEventType> disclosureEventTypes = (List<CoiDisclosureEventType>) getBusinessObjectService().findMatching(
CoiDisclosureEventType.class, fieldValues);
StringWriter writer = new StringWriter();
if (!CollectionUtils.isEmpty(disclosureEventTypes)) {
CoiDisclosureEventType disclosureEventType = disclosureEventTypes.get(0);
CoiDisclosureEventTypeAjaxBean disclosureEventTypeAjaxBean = new CoiDisclosureEventTypeAjaxBean();
disclosureEventTypeAjaxBean.setDisclosureEventType(disclosureEventType);
//Special code to handle select box
if (disclosureEventType.isUseSelectBox1()) {
try {
String valuesFinder = disclosureEventType.getSelectBox1ValuesFinder();
if (StringUtils.isNotBlank(valuesFinder)) {
Class valuesFinderClass = Class.forName(valuesFinder);
KeyValuesFinder keyValuesFinder = (KeyValuesFinder)valuesFinderClass.newInstance();
List<KeyValue> keyValues = keyValuesFinder.getKeyValues();
if (!CollectionUtils.isEmpty(keyValues)) {
disclosureEventTypeAjaxBean.setKeyValues(keyValues);
}
}
}
catch (Exception e) {
//Failed to load select box
}
}
// disclosure ID and label are always required, so put in a default
if (StringUtils.isEmpty(disclosureEventType.getProjectIdLabel())) {
disclosureEventType.setProjectIdLabel(CoreApiServiceLocator.getKualiConfigurationService().getPropertyValueAsString(DEFAULT_EVENT_ID_STRING));
}
if (StringUtils.isEmpty(disclosureEventType.getProjectTitleLabel())) {
disclosureEventType.setProjectTitleLabel(CoreApiServiceLocator.getKualiConfigurationService().getPropertyValueAsString(DEFAULT_EVENT_TITLE_STRING));
}
ObjectMapper mapper = new ObjectMapper();
mapper.writeValue(writer, disclosureEventTypeAjaxBean);
response.setContentType("application/json");
ServletOutputStream out = response.getOutputStream();
try {
out.write(writer.getBuffer().toString().getBytes());
out.flush();
out.close();
}
catch (Exception e) {
e.printStackTrace(new PrintWriter(out));
}
}
return null;
}
private boolean hasDisclosureDetails(CoiDisclosure coiDisclosure) {
boolean result = false;
if (!CollectionUtils.isEmpty(coiDisclosure.getCoiDisclProjects())) {
for (CoiDisclProject project : coiDisclosure.getCoiDisclProjects()) {
if (!CollectionUtils.isEmpty(project.getCoiDiscDetails())) {
result = true;
break;
}
}
}
return result;
}
@Override
protected ActionForward saveOnClose(ActionMapping mapping, ActionForm form, HttpServletRequest request,
HttpServletResponse response) throws Exception {
ActionForward actionForward = mapping.findForward(Constants.MAPPING_BASIC);
CoiDisclosureForm coiDisclosureForm = (CoiDisclosureForm) form;
Document document = coiDisclosureForm.getDocument();
CoiDisclosure coiDisclosure = ((CoiDisclosureDocument) document).getCoiDisclosure();
boolean isValid = true;
if (coiDisclosure.getCoiDisclProjects() != null || !coiDisclosure.getCoiDisclProjects().isEmpty()) {
for (CoiDisclProject coiDisclProject : coiDisclosure.getCoiDisclProjects()) {
if (!new CoiDisclosureAdministratorActionRule().isValidStatus(
coiDisclosure.getCoiDisclosureStatus().getCoiDisclosureStatusCode(), coiDisclProject.getDisclosureDispositionCode())) {
isValid = false;
}
}
}
/************ Begin --- Save (if valid) document and questionnaire data ************/
// TODO factor out the different versions of this doc and questionnaire data save block from various actions in this class
// and centralize it in a helper method
// First validate the questionnaire data
// TODO maybe add a COI questionnaire specific rule event to the condition below
if (validateQuestionnaires(coiDisclosureForm)) {
// since Questionnaire data is OK we try to save doc
if (isValid) {
actionForward = super.saveOnClose(mapping, form, request, response);
saveQuestionnaires(coiDisclosureForm);
}
}
/************ End --- Save (if valid) document and questionnaire data ************/
return actionForward;
}
/**
* Questionnaire related actions below, should perhaps eventually be moved to a separate class for the sake of coherence of this
* action class
**/
public ActionForward printQuestionnaireAnswer(ActionMapping mapping, ActionForm form, HttpServletRequest request,
HttpServletResponse response) throws Exception {
// TODO : this is only available after questionnaire is saved ?
ActionForward forward = mapping.findForward(Constants.MAPPING_BASIC);
Map<String, Object> reportParameters = new HashMap<String, Object>();
CoiDisclosureForm coiDisclosureForm = (CoiDisclosureForm) form;
CoiDisclosure disclosure = coiDisclosureForm.getCoiDisclosureDocument().getCoiDisclosure();
final int answerHeaderIndex = this.getSelectedLine(request);
String methodToCall = (String) request.getAttribute(KRADConstants.METHOD_TO_CALL_ATTRIBUTE);
String formProperty = StringUtils.substringBetween(methodToCall, ".printQuestionnaireAnswer.", ".line");
DisclosureQuestionnaireHelper helper = (DisclosureQuestionnaireHelper) BeanUtilsBean.getInstance().getPropertyUtils().getProperty(form, formProperty);
AnswerHeader answerHeader = helper.getAnswerHeaders().get(answerHeaderIndex);
// TODO : a flag to check whether to print answer or not
// for release 3 : if questionnaire questions has answer, then print answer.
reportParameters.put("questionnaireId",
answerHeader.getQuestionnaire()
.getQuestionnaireSeqIdAsInteger());
reportParameters.put("template",
answerHeader.getQuestionnaire()
.getTemplate());
reportParameters.put("coeusModuleSubItemCode", answerHeader.getModuleSubItemCode());
AttachmentDataSource dataStream = getQuestionnairePrintingService().printQuestionnaireAnswer(disclosure, reportParameters);
if (dataStream.getData() != null) {
streamToResponse(dataStream, response);
forward = null;
}
return forward;
}
protected QuestionnairePrintingService getQuestionnairePrintingService() {
return KcServiceLocator.getService(QuestionnairePrintingService.class);
}
/**
*
* This method is for the 'update' button to update questionnaire answer to new version
*
* @param mapping
* @param form
* @param request
* @param response
* @return
* @throws Exception
*/
public ActionForward updateAnswerToNewVersion(ActionMapping mapping, ActionForm form, HttpServletRequest request,
HttpServletResponse response) throws Exception {
String methodToCallStart = "methodToCall.updateAnswerToNewVersion.";
String methodToCallEnd = ".line";
String methodToCall = ((String) request.getAttribute(KRADConstants.METHOD_TO_CALL_ATTRIBUTE));
String questionnaireHelperPath = methodToCall.substring(methodToCallStart.length(), methodToCall.indexOf(methodToCallEnd));
QuestionnaireHelperBase helper = (QuestionnaireHelperBase) PropertyUtils.getNestedProperty(form, questionnaireHelperPath);
helper.updateQuestionnaireAnswer(getLineToDelete(request));
return mapping.findForward(Constants.MAPPING_BASIC);
}
/**
* @see org.kuali.rice.kns.web.struts.action.KualiDocumentActionBase#refresh(org.apache.struts.action.ActionMapping,
* org.apache.struts.action.ActionForm, javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse)
*/
@Override
public ActionForward refresh(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response)
throws Exception {
ActionForward forward = super.refresh(mapping, form, request, response);
if (request.getParameter("refreshCaller") != null
&& request.getParameter("refreshCaller").toString().equals("kualiLookupable")) {
// Lookup field 'onchange' is not working if it is return a value from 'lookup', so do it on server side
for (Object obj : request.getParameterMap().keySet()) {
if (StringUtils.indexOf((String) obj, ((CoiDisclosureForm) form).getQuestionnaireFieldStarter()) == 0) {
((CoiDisclosureForm) form).getDisclosureQuestionnaireHelper().updateChildIndicator(
Integer.parseInt(StringUtils.substringBetween((String) obj,
((CoiDisclosureForm) form).getQuestionnaireFieldStarter(), "].answers[")));
}
}
}
return forward;
}
private boolean isMasterDisclosureExist() {
Map fieldValues = new HashMap();
fieldValues.put("personId", GlobalVariables.getUserSession().getPrincipalId());
fieldValues.put("currentDisclosure", "Y");
List<CoiDisclosure> disclosures = (List<CoiDisclosure>) getBusinessObjectService().findMatching(CoiDisclosure.class,
fieldValues);
return !CollectionUtils.isEmpty(disclosures);
}
private CoiDisclosure getExistingDisclosure(String eventTypeCode) {
CoiDisclosure updateMaster = null;
Map fieldValues = new HashMap();
fieldValues.put("personId", GlobalVariables.getUserSession().getPrincipalId());
fieldValues.put("eventTypeCode", eventTypeCode);
List<CoiDisclosure> disclosures = (List<CoiDisclosure>) getBusinessObjectService().findMatchingOrderBy(CoiDisclosure.class,
fieldValues, "sequenceNumber", false);
if (!CollectionUtils.isEmpty(disclosures)) {
for (CoiDisclosure disc : disclosures) {
if (!StringUtils.equals(disc.getDisclosureStatusCode(), CoiDisclosureStatus.APPROVED) &&
!StringUtils.equals(disc.getDisclosureStatusCode(), CoiDisclosureStatus.DISAPPROVED)) {
updateMaster = disc;
break;
}
}
}
return updateMaster;
}
public ActionForward viewDisclosureNotification(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) {
CoiDisclosureForm coiDisclosureForm = (CoiDisclosureForm) form;
String notificationId = request.getParameter("notificationId");
Map<String, String> fieldValues = new HashMap<String, String>();
fieldValues.put("notificationId", notificationId);
List<CoiNotification> notifications = (List<CoiNotification>) getBusinessObjectService().findMatching(CoiNotification.class, fieldValues);
coiDisclosureForm.getDisclosureHelper().setViewNotification(notifications.get(0));
return mapping.findForward("viewNotification");
}
}
| apache-2.0 |
aws/aws-sdk-java | aws-java-sdk-opsworks/src/main/java/com/amazonaws/services/opsworks/waiters/DescribeInstancesFunction.java | 1968 | /*
* Copyright 2017-2022 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with
* the License. A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
* CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions
* and limitations under the License.
*/
package com.amazonaws.services.opsworks.waiters;
import javax.annotation.Generated;
import com.amazonaws.annotation.SdkInternalApi;
import com.amazonaws.waiters.SdkFunction;
import com.amazonaws.services.opsworks.model.DescribeInstancesRequest;
import com.amazonaws.services.opsworks.model.DescribeInstancesResult;
import com.amazonaws.services.opsworks.AWSOpsWorks;
@SdkInternalApi
@Generated("com.amazonaws:aws-java-sdk-code-generator")
public class DescribeInstancesFunction implements SdkFunction<DescribeInstancesRequest, DescribeInstancesResult> {
/**
* Represents the service client
*/
private final AWSOpsWorks client;
/**
* Constructs a new DescribeInstancesFunction with the given client
*
* @param client
* Service client
*/
public DescribeInstancesFunction(AWSOpsWorks client) {
this.client = client;
}
/**
* Makes a call to the operation specified by the waiter by taking the corresponding request and returns the
* corresponding result
*
* @param describeInstancesRequest
* Corresponding request for the operation
* @return Corresponding result of the operation
*/
@Override
public DescribeInstancesResult apply(DescribeInstancesRequest describeInstancesRequest) {
return client.describeInstances(describeInstancesRequest);
}
}
| apache-2.0 |
LearnLib/automatalib | api/src/main/java/net/automatalib/automata/transducers/StateOutputAutomaton.java | 1609 | /* Copyright (C) 2013-2022 TU Dortmund
* This file is part of AutomataLib, http://www.automatalib.net/.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package net.automatalib.automata.transducers;
import java.util.Collection;
import net.automatalib.automata.concepts.DetSuffixOutputAutomaton;
import net.automatalib.ts.output.DeterministicStateOutputTS;
import net.automatalib.words.Word;
import net.automatalib.words.WordBuilder;
public interface StateOutputAutomaton<S, I, T, O>
extends DetSuffixOutputAutomaton<S, I, T, Word<O>>, DeterministicStateOutputTS<S, I, T, O> {
@Override
default Word<O> computeStateOutput(S state, Iterable<? extends I> input) {
WordBuilder<O> result;
if (input instanceof Word) {
result = new WordBuilder<>(((Word<?>) input).length() + 1);
} else if (input instanceof Collection) {
result = new WordBuilder<>(((Collection<?>) input).size() + 1);
} else {
result = new WordBuilder<>();
}
trace(state, input, result);
return result.toWord();
}
}
| apache-2.0 |
MehdiSfr/tensor-flow | tensorflow/g3doc/tutorials/mnist/input_data.py | 6582 | # Copyright 2015 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ==============================================================================
"""Functions for downloading and reading MNIST data."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import gzip
import os
import numpy
from six.moves import urllib
from six.moves import xrange # pylint: disable=redefined-builtin
SOURCE_URL = 'http://yann.lecun.com/exdb/mnist/'
def maybe_download(filename, work_directory):
"""Download the data from Yann's website, unless it's already here."""
if not os.path.exists(work_directory):
os.mkdir(work_directory)
filepath = os.path.join(work_directory, filename)
if not os.path.exists(filepath):
filepath, _ = urllib.request.urlretrieve(SOURCE_URL + filename, filepath)
statinfo = os.stat(filepath)
print('Successfully downloaded', filename, statinfo.st_size, 'bytes.')
return filepath
def _read32(bytestream):
dt = numpy.dtype(numpy.uint32).newbyteorder('>')
return numpy.frombuffer(bytestream.read(4), dtype=dt)
def extract_images(filename):
"""Extract the images into a 4D uint8 numpy array [index, y, x, depth]."""
print('Extracting', filename)
with gzip.open(filename) as bytestream:
magic = _read32(bytestream)
if magic != 2051:
raise ValueError(
'Invalid magic number %d in MNIST image file: %s' %
(magic, filename))
num_images = _read32(bytestream)
rows = _read32(bytestream)
cols = _read32(bytestream)
buf = bytestream.read(rows * cols * num_images)
data = numpy.frombuffer(buf, dtype=numpy.uint8)
data = data.reshape(num_images, rows, cols, 1)
return data
def dense_to_one_hot(labels_dense, num_classes=10):
"""Convert class labels from scalars to one-hot vectors."""
num_labels = labels_dense.shape[0]
index_offset = numpy.arange(num_labels) * num_classes
labels_one_hot = numpy.zeros((num_labels, num_classes))
labels_one_hot.flat[index_offset + labels_dense.ravel()] = 1
return labels_one_hot
def extract_labels(filename, one_hot=False):
"""Extract the labels into a 1D uint8 numpy array [index]."""
print('Extracting', filename)
with gzip.open(filename) as bytestream:
magic = _read32(bytestream)
if magic != 2049:
raise ValueError(
'Invalid magic number %d in MNIST label file: %s' %
(magic, filename))
num_items = _read32(bytestream)
buf = bytestream.read(num_items)
labels = numpy.frombuffer(buf, dtype=numpy.uint8)
if one_hot:
return dense_to_one_hot(labels)
return labels
class DataSet(object):
def __init__(self, images, labels, fake_data=False):
if fake_data:
self._num_examples = 10000
else:
assert images.shape[0] == labels.shape[0], (
"images.shape: %s labels.shape: %s" % (images.shape,
labels.shape))
self._num_examples = images.shape[0]
# Convert shape from [num examples, rows, columns, depth]
# to [num examples, rows*columns] (assuming depth == 1)
assert images.shape[3] == 1
images = images.reshape(images.shape[0],
images.shape[1] * images.shape[2])
# Convert from [0, 255] -> [0.0, 1.0].
images = images.astype(numpy.float32)
images = numpy.multiply(images, 1.0 / 255.0)
self._images = images
self._labels = labels
self._epochs_completed = 0
self._index_in_epoch = 0
@property
def images(self):
return self._images
@property
def labels(self):
return self._labels
@property
def num_examples(self):
return self._num_examples
@property
def epochs_completed(self):
return self._epochs_completed
def next_batch(self, batch_size, fake_data=False):
"""Return the next `batch_size` examples from this data set."""
if fake_data:
fake_image = [1.0 for _ in xrange(784)]
fake_label = 0
return [fake_image for _ in xrange(batch_size)], [
fake_label for _ in xrange(batch_size)]
start = self._index_in_epoch
self._index_in_epoch += batch_size
if self._index_in_epoch > self._num_examples:
# Finished epoch
self._epochs_completed += 1
# Shuffle the data
perm = numpy.arange(self._num_examples)
numpy.random.shuffle(perm)
self._images = self._images[perm]
self._labels = self._labels[perm]
# Start next epoch
start = 0
self._index_in_epoch = batch_size
assert batch_size <= self._num_examples
end = self._index_in_epoch
return self._images[start:end], self._labels[start:end]
def read_data_sets(train_dir, fake_data=False, one_hot=False):
class DataSets(object):
pass
data_sets = DataSets()
if fake_data:
data_sets.train = DataSet([], [], fake_data=True)
data_sets.validation = DataSet([], [], fake_data=True)
data_sets.test = DataSet([], [], fake_data=True)
return data_sets
TRAIN_IMAGES = 'train-images-idx3-ubyte.gz'
TRAIN_LABELS = 'train-labels-idx1-ubyte.gz'
TEST_IMAGES = 't10k-images-idx3-ubyte.gz'
TEST_LABELS = 't10k-labels-idx1-ubyte.gz'
VALIDATION_SIZE = 5000
local_file = maybe_download(TRAIN_IMAGES, train_dir)
train_images = extract_images(local_file)
local_file = maybe_download(TRAIN_LABELS, train_dir)
train_labels = extract_labels(local_file, one_hot=one_hot)
local_file = maybe_download(TEST_IMAGES, train_dir)
test_images = extract_images(local_file)
local_file = maybe_download(TEST_LABELS, train_dir)
test_labels = extract_labels(local_file, one_hot=one_hot)
validation_images = train_images[:VALIDATION_SIZE]
validation_labels = train_labels[:VALIDATION_SIZE]
train_images = train_images[VALIDATION_SIZE:]
train_labels = train_labels[VALIDATION_SIZE:]
data_sets.train = DataSet(train_images, train_labels)
data_sets.validation = DataSet(validation_images, validation_labels)
data_sets.test = DataSet(test_images, test_labels)
return data_sets
| apache-2.0 |
opensim-org/opensim-gui | Gui/opensim/K12Utils/src/org/opensim/k12utils/CreateLabDialog.java | 36703 | /* -------------------------------------------------------------------------- *
* OpenSim: CreateLabDialog.java *
* -------------------------------------------------------------------------- *
* OpenSim is a toolkit for musculoskeletal modeling and simulation, *
* developed as an open source project by a worldwide community. Development *
* and support is coordinated from Stanford University, with funding from the *
* U.S. NIH and DARPA. See http://opensim.stanford.edu and the README file *
* for more information including specific grant numbers. *
* *
* Copyright (c) 2005-2017 Stanford University and the Authors *
* Author(s): Ayman Habib *
* *
* 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. *
* -------------------------------------------------------------------------- */
/*
* CreateLabDialog.java
*
* Created on August 10, 2010, 7:21 PM
*/
package org.opensim.k12utils;
import java.beans.XMLEncoder;
import java.io.BufferedOutputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Hashtable;
import javax.swing.DefaultListModel;
import org.openide.DialogDescriptor;
import org.openide.DialogDisplayer;
import org.openide.NotifyDescriptor;
import org.opensim.k12.Lab;
import org.opensim.k12.LabOutput;
import org.opensim.k12.LabOutputsNode;
import org.opensim.k12.LabParameter;
import org.opensim.k12.LabParametersNode;
import org.opensim.modeling.Model;
import org.opensim.tools.serializers.ToolSerializer;
import org.opensim.utils.FileUtils;
import org.opensim.view.pub.OpenSimDB;
import org.opensim.view.pub.OpenSimDBDescriptor;
/**
*
* @author ayman
*/
public class CreateLabDialog extends javax.swing.JDialog {
Lab lab = new Lab();
DefaultListModel inputListModel;
DefaultListModel outputListModel;
/** Creates new form CreateLabDialog */
public CreateLabDialog(java.awt.Frame parent, boolean modal) {
super(parent, modal);
initComponents();
setTitle("Create Custom Tool...");
populateListModels();
}
/** 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.
*/
// <editor-fold defaultstate="collapsed" desc=" Generated Code ">//GEN-BEGIN:initComponents
private void initComponents() {
ModelSelectionbuttonGroup = new javax.swing.ButtonGroup();
MotionSelectionbuttonGroup = new javax.swing.ButtonGroup();
jLabel5 = new javax.swing.JLabel();
addOutputPanel = new javax.swing.JPanel();
labParameter1 = new org.opensim.k12.LabParameter();
fileTextFieldAndChooser3 = new org.opensim.swingui.FileTextFieldAndChooser();
motionSpecPanel = new javax.swing.JPanel();
useCurrentMotionRadioButton = new javax.swing.JRadioButton();
browseForMotionRadioButton = new javax.swing.JRadioButton();
fileTextFieldAndChooser2 = new org.opensim.swingui.FileTextFieldAndChooser();
noMotionRadioButton = new javax.swing.JRadioButton();
jLabel2 = new javax.swing.JLabel();
labNameLabel = new javax.swing.JLabel();
toolSpecPanel = new javax.swing.JPanel();
toolSetupTextFieldAndChooser = new org.opensim.swingui.FileTextFieldAndChooser();
jLabel3 = new javax.swing.JLabel();
labNameTextField = new javax.swing.JTextField();
modelSpecPanel = new javax.swing.JPanel();
modelFileTextFieldAndChooser = new org.opensim.swingui.FileTextFieldAndChooser();
useCurrentModelRadioButton = new javax.swing.JRadioButton();
jLabel1 = new javax.swing.JLabel();
browseForModelRadioButton = new javax.swing.JRadioButton();
inputsPanel = new javax.swing.JPanel();
jLabel4 = new javax.swing.JLabel();
inputsScrollPane = new javax.swing.JScrollPane();
inputsList = new javax.swing.JList();
addButton = new javax.swing.JButton();
delButton = new javax.swing.JButton();
saveLabButton = new javax.swing.JButton();
onputsPanel = new javax.swing.JPanel();
jLabel6 = new javax.swing.JLabel();
onputsScrollPane = new javax.swing.JScrollPane();
outputsList = new javax.swing.JList();
addButton1 = new javax.swing.JButton();
delButton1 = new javax.swing.JButton();
instructionsPanel = new javax.swing.JPanel();
instructionsTextFieldAndChooser = new org.opensim.swingui.FileTextFieldAndChooser();
jLabel7 = new javax.swing.JLabel();
jPanel1 = new javax.swing.JPanel();
jLabel8 = new javax.swing.JLabel();
jRunButtonTextField = new javax.swing.JTextField();
jLabel5.setText("Instructions file");
org.jdesktop.layout.GroupLayout addOutputPanelLayout = new org.jdesktop.layout.GroupLayout(addOutputPanel);
addOutputPanel.setLayout(addOutputPanelLayout);
addOutputPanelLayout.setHorizontalGroup(
addOutputPanelLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
.add(0, 100, Short.MAX_VALUE)
);
addOutputPanelLayout.setVerticalGroup(
addOutputPanelLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
.add(0, 100, Short.MAX_VALUE)
);
setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
motionSpecPanel.setBorder(javax.swing.BorderFactory.createEtchedBorder());
MotionSelectionbuttonGroup.add(useCurrentMotionRadioButton);
useCurrentMotionRadioButton.setText("Use Current");
useCurrentMotionRadioButton.setBorder(javax.swing.BorderFactory.createEmptyBorder(0, 0, 0, 0));
useCurrentMotionRadioButton.setMargin(new java.awt.Insets(0, 0, 0, 0));
MotionSelectionbuttonGroup.add(browseForMotionRadioButton);
browseForMotionRadioButton.setText("Browse");
browseForMotionRadioButton.setBorder(javax.swing.BorderFactory.createEmptyBorder(0, 0, 0, 0));
browseForMotionRadioButton.setMargin(new java.awt.Insets(0, 0, 0, 0));
fileTextFieldAndChooser2.setFileFilter(FileUtils.getFileFilter(".mot", "Motion file to load"));
MotionSelectionbuttonGroup.add(noMotionRadioButton);
noMotionRadioButton.setSelected(true);
noMotionRadioButton.setText("No Motion Needed");
noMotionRadioButton.setBorder(javax.swing.BorderFactory.createEmptyBorder(0, 0, 0, 0));
noMotionRadioButton.setMargin(new java.awt.Insets(0, 0, 0, 0));
jLabel2.setText("Motion:");
org.jdesktop.layout.GroupLayout motionSpecPanelLayout = new org.jdesktop.layout.GroupLayout(motionSpecPanel);
motionSpecPanel.setLayout(motionSpecPanelLayout);
motionSpecPanelLayout.setHorizontalGroup(
motionSpecPanelLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
.add(motionSpecPanelLayout.createSequentialGroup()
.add(motionSpecPanelLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
.add(motionSpecPanelLayout.createSequentialGroup()
.addContainerGap()
.add(browseForMotionRadioButton)
.addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
.add(fileTextFieldAndChooser2, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 315, Short.MAX_VALUE))
.add(jLabel2)
.add(motionSpecPanelLayout.createSequentialGroup()
.addContainerGap()
.add(noMotionRadioButton))
.add(motionSpecPanelLayout.createSequentialGroup()
.addContainerGap()
.add(useCurrentMotionRadioButton)))
.addContainerGap())
);
motionSpecPanelLayout.setVerticalGroup(
motionSpecPanelLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
.add(org.jdesktop.layout.GroupLayout.TRAILING, motionSpecPanelLayout.createSequentialGroup()
.add(jLabel2)
.addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
.add(noMotionRadioButton)
.addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
.add(useCurrentMotionRadioButton)
.addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.add(motionSpecPanelLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
.add(fileTextFieldAndChooser2, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
.add(browseForMotionRadioButton))
.add(62, 62, 62))
);
labNameLabel.setText("Lab Name:");
toolSpecPanel.setBorder(javax.swing.BorderFactory.createEtchedBorder());
toolSetupTextFieldAndChooser.setFileFilter(FileUtils.getFileFilter(".xml", "Setup file to run tool"));
jLabel3.setText("Tool setup file");
org.jdesktop.layout.GroupLayout toolSpecPanelLayout = new org.jdesktop.layout.GroupLayout(toolSpecPanel);
toolSpecPanel.setLayout(toolSpecPanelLayout);
toolSpecPanelLayout.setHorizontalGroup(
toolSpecPanelLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
.add(toolSpecPanelLayout.createSequentialGroup()
.addContainerGap()
.add(jLabel3)
.add(12, 12, 12)
.add(toolSetupTextFieldAndChooser, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 295, Short.MAX_VALUE)
.addContainerGap())
);
toolSpecPanelLayout.setVerticalGroup(
toolSpecPanelLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
.add(org.jdesktop.layout.GroupLayout.TRAILING, toolSpecPanelLayout.createSequentialGroup()
.addContainerGap(org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.add(toolSpecPanelLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
.add(toolSetupTextFieldAndChooser, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
.add(jLabel3))
.addContainerGap())
);
labNameTextField.setToolTipText("labName: Shows as wdinow title");
modelSpecPanel.setBorder(javax.swing.BorderFactory.createEtchedBorder());
modelFileTextFieldAndChooser.setCheckIfFileExists(true);
modelFileTextFieldAndChooser.setFileFilter(FileUtils.getFileFilter(".osim", "Model file to load"));
ModelSelectionbuttonGroup.add(useCurrentModelRadioButton);
useCurrentModelRadioButton.setSelected(true);
useCurrentModelRadioButton.setText("Use Current");
useCurrentModelRadioButton.setBorder(javax.swing.BorderFactory.createEmptyBorder(0, 0, 0, 0));
useCurrentModelRadioButton.setMargin(new java.awt.Insets(0, 0, 0, 0));
jLabel1.setText("Model File:");
ModelSelectionbuttonGroup.add(browseForModelRadioButton);
browseForModelRadioButton.setText("Browse");
browseForModelRadioButton.setBorder(javax.swing.BorderFactory.createEmptyBorder(0, 0, 0, 0));
browseForModelRadioButton.setMargin(new java.awt.Insets(0, 0, 0, 0));
org.jdesktop.layout.GroupLayout modelSpecPanelLayout = new org.jdesktop.layout.GroupLayout(modelSpecPanel);
modelSpecPanel.setLayout(modelSpecPanelLayout);
modelSpecPanelLayout.setHorizontalGroup(
modelSpecPanelLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
.add(modelSpecPanelLayout.createSequentialGroup()
.add(modelSpecPanelLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
.add(jLabel1)
.add(modelSpecPanelLayout.createSequentialGroup()
.addContainerGap()
.add(browseForModelRadioButton)
.addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
.add(modelFileTextFieldAndChooser, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 315, Short.MAX_VALUE))
.add(modelSpecPanelLayout.createSequentialGroup()
.addContainerGap()
.add(useCurrentModelRadioButton)))
.addContainerGap())
);
modelSpecPanelLayout.setVerticalGroup(
modelSpecPanelLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
.add(modelSpecPanelLayout.createSequentialGroup()
.add(jLabel1)
.add(7, 7, 7)
.add(useCurrentModelRadioButton)
.addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
.add(modelSpecPanelLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
.add(modelFileTextFieldAndChooser, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
.add(browseForModelRadioButton))
.addContainerGap())
);
inputsPanel.setBorder(javax.swing.BorderFactory.createEtchedBorder());
jLabel4.setText("Inputs");
inputsScrollPane.setViewportView(inputsList);
addButton.setText("Add");
addButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
addButtonActionPerformed(evt);
}
});
delButton.setText("Del");
delButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
delButtonActionPerformed(evt);
}
});
org.jdesktop.layout.GroupLayout inputsPanelLayout = new org.jdesktop.layout.GroupLayout(inputsPanel);
inputsPanel.setLayout(inputsPanelLayout);
inputsPanelLayout.setHorizontalGroup(
inputsPanelLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
.add(inputsPanelLayout.createSequentialGroup()
.add(jLabel4)
.add(18, 18, 18)
.add(inputsScrollPane, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 278, Short.MAX_VALUE)
.addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
.add(inputsPanelLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.TRAILING, false)
.add(delButton, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.add(addButton, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
.addContainerGap())
);
inputsPanelLayout.setVerticalGroup(
inputsPanelLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
.add(inputsPanelLayout.createSequentialGroup()
.add(37, 37, 37)
.add(jLabel4)
.addContainerGap(49, Short.MAX_VALUE))
.add(org.jdesktop.layout.GroupLayout.TRAILING, inputsScrollPane, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 100, Short.MAX_VALUE)
.add(inputsPanelLayout.createSequentialGroup()
.add(19, 19, 19)
.add(addButton)
.addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
.add(delButton)
.addContainerGap(29, Short.MAX_VALUE))
);
saveLabButton.setText("Save...");
saveLabButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
saveLabButtonActionPerformed(evt);
}
});
onputsPanel.setBorder(javax.swing.BorderFactory.createEtchedBorder());
jLabel6.setText("Outputs ");
onputsScrollPane.setViewportView(outputsList);
addButton1.setText("Add");
addButton1.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
addButton1ActionPerformed(evt);
}
});
delButton1.setText("Del");
org.jdesktop.layout.GroupLayout onputsPanelLayout = new org.jdesktop.layout.GroupLayout(onputsPanel);
onputsPanel.setLayout(onputsPanelLayout);
onputsPanelLayout.setHorizontalGroup(
onputsPanelLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
.add(onputsPanelLayout.createSequentialGroup()
.add(jLabel6)
.addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
.add(onputsScrollPane, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 275, Short.MAX_VALUE)
.addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
.add(onputsPanelLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.TRAILING, false)
.add(delButton1, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.add(addButton1, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
.addContainerGap())
);
onputsPanelLayout.setVerticalGroup(
onputsPanelLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
.add(onputsPanelLayout.createSequentialGroup()
.add(37, 37, 37)
.add(jLabel6)
.addContainerGap(50, Short.MAX_VALUE))
.add(onputsPanelLayout.createSequentialGroup()
.add(19, 19, 19)
.add(addButton1)
.addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
.add(delButton1)
.addContainerGap(30, Short.MAX_VALUE))
.add(org.jdesktop.layout.GroupLayout.TRAILING, onputsScrollPane, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 101, Short.MAX_VALUE)
);
instructionsPanel.setBorder(javax.swing.BorderFactory.createEtchedBorder());
instructionsTextFieldAndChooser.setFileFilter(FileUtils.getFileFilter(".html", "Html file with instructions. Will show in a separate window"));
jLabel7.setText("Instructions file");
org.jdesktop.layout.GroupLayout instructionsPanelLayout = new org.jdesktop.layout.GroupLayout(instructionsPanel);
instructionsPanel.setLayout(instructionsPanelLayout);
instructionsPanelLayout.setHorizontalGroup(
instructionsPanelLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
.add(instructionsPanelLayout.createSequentialGroup()
.addContainerGap()
.add(jLabel7)
.addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
.add(instructionsTextFieldAndChooser, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 296, Short.MAX_VALUE)
.addContainerGap())
);
instructionsPanelLayout.setVerticalGroup(
instructionsPanelLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
.add(org.jdesktop.layout.GroupLayout.TRAILING, instructionsPanelLayout.createSequentialGroup()
.addContainerGap(org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.add(instructionsPanelLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
.add(jLabel7)
.add(instructionsTextFieldAndChooser, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))
.addContainerGap())
);
jPanel1.setBorder(javax.swing.BorderFactory.createEtchedBorder());
jLabel8.setText("Run button label");
jRunButtonTextField.setText(" ");
org.jdesktop.layout.GroupLayout jPanel1Layout = new org.jdesktop.layout.GroupLayout(jPanel1);
jPanel1.setLayout(jPanel1Layout);
jPanel1Layout.setHorizontalGroup(
jPanel1Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
.add(jPanel1Layout.createSequentialGroup()
.addContainerGap()
.add(jLabel8)
.add(5, 5, 5)
.add(jRunButtonTextField, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 203, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
.addContainerGap(97, Short.MAX_VALUE))
);
jPanel1Layout.setVerticalGroup(
jPanel1Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
.add(jPanel1Layout.createSequentialGroup()
.add(23, 23, 23)
.add(jPanel1Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE)
.add(jRunButtonTextField, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
.add(jLabel8))
.addContainerGap(org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
org.jdesktop.layout.GroupLayout layout = new org.jdesktop.layout.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
.add(layout.createSequentialGroup()
.add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
.add(org.jdesktop.layout.GroupLayout.TRAILING, layout.createParallelGroup(org.jdesktop.layout.GroupLayout.TRAILING)
.add(org.jdesktop.layout.GroupLayout.LEADING, jPanel1, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.add(onputsPanel, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.add(inputsPanel, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.add(org.jdesktop.layout.GroupLayout.LEADING, motionSpecPanel, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.add(org.jdesktop.layout.GroupLayout.LEADING, modelSpecPanel, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.add(org.jdesktop.layout.GroupLayout.LEADING, layout.createSequentialGroup()
.addContainerGap()
.add(labNameLabel)
.addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
.add(labNameTextField, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 199, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))
.add(instructionsPanel, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.add(toolSpecPanel, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
.add(layout.createSequentialGroup()
.add(161, 161, 161)
.add(saveLabButton)))
.addContainerGap())
);
layout.setVerticalGroup(
layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
.add(layout.createSequentialGroup()
.addContainerGap()
.add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE)
.add(labNameLabel)
.add(labNameTextField, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
.add(modelSpecPanel, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
.add(motionSpecPanel, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 93, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
.add(instructionsPanel, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
.add(toolSpecPanel, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
.add(inputsPanel, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
.add(onputsPanel, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.add(jPanel1, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
.add(saveLabButton)
.addContainerGap())
);
pack();
}// </editor-fold>//GEN-END:initComponents
private void addButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_addButton1ActionPerformed
AddOutputTextPanel createOutputPanel = new AddOutputTextPanel();
DialogDescriptor dlg = new DialogDescriptor(createOutputPanel,"Add Output");
dlg.setClosingOptions(null);
dlg.setModal(true);
DialogDisplayer.getDefault().createDialog(dlg).setVisible(true);
Object userInput = dlg.getValue();
if (((Integer)userInput).compareTo((Integer)DialogDescriptor.OK_OPTION)==0){
((LabOutputsNode)lab.getObject(Lab.OUTPUTS)).addOutput(createOutputPanel.getOutputDescription());
outputListModel.addElement(createOutputPanel.getOutputDescription());
}
// TODO add your handling code here:
}//GEN-LAST:event_addButton1ActionPerformed
private void delButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_delButtonActionPerformed
// TODO add your handling code here:
Object obj=inputsList.getSelectedValue();
LabParameter p = (LabParameter)obj;
((LabParametersNode)lab.getObject(Lab.INPUTS)).removeParameter(p);
inputListModel.removeElement(p);
}//GEN-LAST:event_delButtonActionPerformed
private void addButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_addButtonActionPerformed
// TODO add your handling code here:
AddInputPanel createInputPanel = new AddInputPanel();
DialogDescriptor dlg = new DialogDescriptor(createInputPanel,"Add Input");
dlg.setClosingOptions(null);
dlg.setModal(true);
DialogDisplayer.getDefault().createDialog(dlg).setVisible(true);
Object userInput = dlg.getValue();
if (((Integer)userInput).compareTo((Integer)DialogDescriptor.OK_OPTION)==0){
((LabParametersNode)lab.getObject(Lab.INPUTS)).addParameter(createInputPanel.getParm());
inputListModel.addElement(createInputPanel.getParm());
}
}//GEN-LAST:event_addButtonActionPerformed
private void saveLabButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_saveLabButtonActionPerformed
// TODO add your handling code here:
// Create a Lab object and write it to the specified file
String fileName = FileUtils.getInstance().browseForFilenameToSave(
FileUtils.getFileFilter(".oscript", "Script file"),
true,
"lab.oscript");
if (fileName!= null)
try {saveLabToFile(fileName);
} catch (FileNotFoundException ex) {
NotifyDescriptor.Message dlg =
new NotifyDescriptor.Message("Failed to save lab to file.. Existing.");
DialogDisplayer.getDefault().notify(dlg);
ex.printStackTrace();
} catch (IOException ex) {
NotifyDescriptor.Message dlg =
new NotifyDescriptor.Message("Missing file specified, please fix before saving Lab to file.. Existing.");
DialogDisplayer.getDefault().notify(dlg);
ex.printStackTrace();
}
}//GEN-LAST:event_saveLabButtonActionPerformed
/**
* @param args the command line arguments
*/
public static void main(String args[]) {
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new CreateLabDialog(new javax.swing.JFrame(), true).setVisible(true);
}
});
}
private void saveLabToFile(String fileName) throws FileNotFoundException, IOException {
XMLEncoder encoder = new XMLEncoder(new BufferedOutputStream(
new FileOutputStream(fileName)));
Hashtable<String, Object> objects = lab.getStateObjects();
objects.put(lab.LAB_NAME, labNameTextField.getText());
if (useCurrentModelRadioButton.isSelected())
objects.put(lab.DB, new OpenSimDBDescriptor(OpenSimDB.getInstance()));
else if (browseForModelRadioButton.isSelected()){
Object[] allModels=OpenSimDB.getInstance().getAllModels();
boolean found = false;
for(int i=0; i<allModels.length && !found; i++){
Model nextModel = (Model)allModels[i];
found= (nextModel.getInputFileName().equals(modelFileTextFieldAndChooser.getFileName()));
}
if (!found){
Model loadModel = new Model(modelFileTextFieldAndChooser.getFileName());
OpenSimDB.getInstance().addModel(loadModel);
objects.put(lab.DB, new OpenSimDBDescriptor(OpenSimDB.getInstance()));
OpenSimDB.getInstance().removeModel(loadModel);
}
else
objects.put(lab.DB, new OpenSimDBDescriptor(OpenSimDB.getInstance()));
}
String label =jRunButtonTextField.getText();
objects.put(lab.RUN_LABEL, (label.length()==0?"Run...":label));
ToolSerializer ts = new ToolSerializer();
ts.setSetupFile(toolSetupTextFieldAndChooser.getFileName());
objects.put(lab.TOOL, ts);
/*
LabOutputsNode outs = new LabOutputsNode();
LabOutputTextToPanel lot = new LabOutputTextToPanel();
lot.setHtmlTemplate("HTMLString");
lot.setQuantitySpecfication("Analysis.StorageName.columnName");
outs.addOutput(lot);
LabOutputPlot lop = new LabOutputPlot();
lop.setPlotTitle("dTitle");
lop.setXAxisTitle("dXTitle");
lop.setYAxisTitle("dYTitle");
outs.addOutput(lop);
**/
encoder.writeObject(lab); // This method serializes an object graph
encoder.close();
}
private void populateListModels() {
LabParametersNode params = (LabParametersNode)lab.getObject(Lab.INPUTS);
if (params==null){
params = new LabParametersNode();
lab.addObject(Lab.INPUTS, params);
}
ArrayList<LabParameter> parms=params.getParameters();
inputListModel = new DefaultListModel();
for (int i=0; i<parms.size(); i++)
inputListModel.addElement(parms.get(i));
inputsList.setModel(inputListModel);
LabOutputsNode outs = (LabOutputsNode)lab.getObject(Lab.OUTPUTS);
if (outs==null){
outs = new LabOutputsNode();
lab.addObject(Lab.OUTPUTS, outs);
}
ArrayList<LabOutput> outputs=outs.getOutputs();
outputListModel = new DefaultListModel();
for (int i=0; i<outputs.size(); i++)
outputListModel.addElement(outputs.get(i));
outputsList.setModel(outputListModel);
}
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.ButtonGroup ModelSelectionbuttonGroup;
private javax.swing.ButtonGroup MotionSelectionbuttonGroup;
private javax.swing.JButton addButton;
private javax.swing.JButton addButton1;
private javax.swing.JPanel addOutputPanel;
private javax.swing.JRadioButton browseForModelRadioButton;
private javax.swing.JRadioButton browseForMotionRadioButton;
private javax.swing.JButton delButton;
private javax.swing.JButton delButton1;
private org.opensim.swingui.FileTextFieldAndChooser fileTextFieldAndChooser2;
private org.opensim.swingui.FileTextFieldAndChooser fileTextFieldAndChooser3;
private javax.swing.JList inputsList;
private javax.swing.JPanel inputsPanel;
private javax.swing.JScrollPane inputsScrollPane;
private javax.swing.JPanel instructionsPanel;
private org.opensim.swingui.FileTextFieldAndChooser instructionsTextFieldAndChooser;
private javax.swing.JLabel jLabel1;
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.JPanel jPanel1;
private javax.swing.JTextField jRunButtonTextField;
private javax.swing.JLabel labNameLabel;
private javax.swing.JTextField labNameTextField;
private org.opensim.k12.LabParameter labParameter1;
private org.opensim.swingui.FileTextFieldAndChooser modelFileTextFieldAndChooser;
private javax.swing.JPanel modelSpecPanel;
private javax.swing.JPanel motionSpecPanel;
private javax.swing.JRadioButton noMotionRadioButton;
private javax.swing.JPanel onputsPanel;
private javax.swing.JScrollPane onputsScrollPane;
private javax.swing.JList outputsList;
private javax.swing.JButton saveLabButton;
private org.opensim.swingui.FileTextFieldAndChooser toolSetupTextFieldAndChooser;
private javax.swing.JPanel toolSpecPanel;
private javax.swing.JRadioButton useCurrentModelRadioButton;
private javax.swing.JRadioButton useCurrentMotionRadioButton;
// End of variables declaration//GEN-END:variables
}
| apache-2.0 |
diabolicallabs/vertx-kieserver-client | src/main/java/com/diabolicallabs/kie/server/model/KieWorkItemInstance.java | 2302 | package com.diabolicallabs.kie.server.model;
import io.vertx.codegen.annotations.DataObject;
import io.vertx.core.json.JsonObject;
@DataObject
public class KieWorkItemInstance {
public Long id;
public String name;
public Integer state;
public JsonObject parameters = new JsonObject();
public Long processInstanceId;
public String containerId;
public Long nodeInstanceId;
public Long nodeId;
public KieWorkItemInstance() {
}
public KieWorkItemInstance(KieWorkItemInstance other) {
this();
this.id = other.id;
this.name = other.name;
this.state = other.state;
this.parameters = other.parameters;
this.processInstanceId = other.processInstanceId;
this.containerId = other.containerId;
this.nodeInstanceId = other.nodeInstanceId;
this.nodeId = other.nodeId;
}
public KieWorkItemInstance(String jsonString) {
this(new JsonObject(jsonString));
}
public KieWorkItemInstance(JsonObject json) {
if (json.containsKey("work-item-id")) id = json.getLong("work-item-id");
if (json.containsKey("work-item-name")) name = json.getString("work-item-name");
if (json.containsKey("work-item-state")) state = json.getInteger("work-item-state");
if (json.containsKey("work-item-params")) parameters = json.getJsonObject("work-item-params");
if (json.containsKey("process-instance-id")) processInstanceId = json.getLong("process-instance-id");
if (json.containsKey("container-id")) containerId = json.getString("container-id");
if (json.containsKey("node-instance-id")) nodeInstanceId = json.getLong("node-instance-id");
if (json.containsKey("node-id")) nodeId = json.getLong("node-id");
}
public JsonObject toJson() {
JsonObject json = new JsonObject();
if (id != null) json.put("work-item-id", id);
if (name != null) json.put("work-item-name", name);
if (state != null) json.put("work-item-state", state);
if (parameters != null) json.put("work-item-params", parameters);
if (processInstanceId != null) json.put("process-instance-id", processInstanceId);
if (containerId != null) json.put("container-id", containerId);
if (nodeInstanceId != null) json.put("node-instance-id", nodeInstanceId);
if (nodeId != null) json.put("node-id", nodeId);
return json;
}
}
| apache-2.0 |
kennknowles/go-yid | src/yid/nullable_test.go | 740 |
package yid
import "testing"
var nullable_tests = []struct {
grammar *Grammar
nullable bool
}{
{ Empty, false },
{ Eps, true },
{ Token("foo"), false },
{ Cat(Empty, Eps), false },
{ Cat(Eps, Empty), false },
{ Cat(Eps, Eps), true },
{ Cat(Eps, Token("baz")), false },
{ Alt(Eps, Empty), true },
{ Alt(Empty, Eps), true },
{ Alt(Empty, Empty), false },
{ Alt(Eps, Token("foo")), true },
{ rec_alt1, true },
{ As_then_bs, false },
{ Russ_cox_exponential, false },
}
func TestNullable(t *testing.T) {
for _, test_case := range nullable_tests {
if (test_case.grammar.Nullable() != test_case.nullable) {
t.Errorf("Nullable test failed (should be %t): %s", test_case.nullable, test_case.grammar.Pretty())
}
}
}
| apache-2.0 |
lsinfo3/onos | web/gui/src/main/webapp/tests/app/view/topo/topoPanel-spec.js | 4885 | /*
* Copyright 2015-present Open Networking Laboratory
*
* 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.
*/
/*
ONOS GUI -- Topo View -- Topo Panel Service - Unit Tests
*/
describe('factory: view/topo/topoPanel.js', function() {
var $log, fs, tps, bns, ps, panelLayer;
var mockWindow = {
innerWidth: 300,
innerHeight: 100,
navigator: {
userAgent: 'defaultUA'
},
on: function () {},
addEventListener: function () {}
};
beforeEach(module('ovTopo', 'onosUtil', 'onosLayer', 'ngRoute', 'onosNav',
'onosWidget', 'onosMast'));
beforeEach(function () {
module(function ($provide) {
$provide.value('$window', mockWindow);
});
});
beforeEach(inject(function (_$log_, FnService,
TopoPanelService, ButtonService, PanelService) {
$log = _$log_;
fs = FnService;
tps = TopoPanelService;
bns = ButtonService;
ps = PanelService;
panelLayer = d3.select('body').append('div').attr('id', 'floatpanels');
}));
afterEach(function () {
panelLayer.remove();
});
it('should define TopoPanelService', function () {
expect(tps).toBeDefined();
});
xit('should define api functions', function () {
expect(fs.areFunctions(tps, [
'initPanels',
'destroyPanels',
'createTopoPanel',
'showSummary',
'toggleSummary',
'toggleUseDetailsFlag',
'displaySingle',
'displayMulti',
'displayLink',
'displayNothing',
'displaySomething',
'addAction',
'hideSummaryPanel',
'detailVisible',
'summaryVisible'
])).toBeTruthy();
});
// === topoPanel api ------------------
it('should define topoPanel api functions', function () {
var panel = tps.createTopoPanel('foo');
expect(fs.areFunctions(panel, [
'panel', 'setup', 'destroy',
'appendHeader', 'appendBody', 'appendFooter',
'adjustHeight'
])).toBeTruthy();
panel.destroy();
});
it('should allow you to get panel', function () {
var panel = tps.createTopoPanel('foo');
expect(panel.panel()).toBeTruthy();
panel.destroy();
});
it('should set up panel', function () {
var p = tps.createTopoPanel('foo'),
h, b, f;
p.setup();
expect(p.panel().el().selectAll('div').size()).toBe(3);
h = p.panel().el().select('.header');
expect(h.empty()).toBe(false);
b = p.panel().el().select('.body');
expect(b.empty()).toBe(false);
f = p.panel().el().select('.footer');
expect(f.empty()).toBe(false);
p.destroy();
});
it('should destroy panel', function () {
spyOn(ps, 'destroyPanel').and.callThrough();
var p = tps.createTopoPanel('foo');
p.destroy();
expect(ps.destroyPanel).toHaveBeenCalledWith('foo');
});
it('should append to panel', function () {
var p = tps.createTopoPanel('foo');
p.setup();
p.appendHeader('div').attr('id', 'header-div');
expect(p.panel().el().select('#header-div').empty()).toBe(false);
p.appendBody('p').attr('id', 'body-paragraph');
expect(p.panel().el().select('#body-paragraph').empty()).toBe(false);
p.appendFooter('svg').attr('id', 'footer-svg');
expect(p.panel().el().select('#footer-svg').empty()).toBe(false);
p.destroy();
});
it('should warn if fromTop not given, adjustHeight', function () {
spyOn($log, 'warn');
var p = tps.createTopoPanel('foo');
p.adjustHeight();
expect($log.warn).toHaveBeenCalledWith(
'adjustHeight: height from top of page not given'
);
p.destroy();
});
xit('should warn if panel is not setup/defined, adjustHeight', function () {
spyOn($log, 'warn');
var p = tps.createTopoPanel('foo');
p.adjustHeight(50);
expect($log.warn).toHaveBeenCalledWith(
'adjustHeight: panel contents are not defined'
);
p.destroy();
});
// TODO: test adjustHeight height adjustment
// TODO: more tests...
});
| apache-2.0 |
loresoft/FluentHtml | Source/FluentHtml.Web/App_Start/FilterConfig.cs | 269 | using System.Web;
using System.Web.Mvc;
namespace FluentHtml.Web
{
public class FilterConfig
{
public static void RegisterGlobalFilters(GlobalFilterCollection filters)
{
filters.Add(new HandleErrorAttribute());
}
}
}
| apache-2.0 |
Neft-io/neft | packages/neft-runtime-android/app/src/main/jni/timers.cpp | 2343 | #include <jni.h>
#include "include/v8.h"
#include "js.cpp"
#include "java.cpp"
using namespace v8;
namespace timers {
static jobject jniObject;
static jmethodID jniShotMethod;
Persistent<Function, CopyablePersistentTraits<Function>> callback;
void registerCallback(const FunctionCallbackInfo<Value>& args){
Isolate *isolate = JS::GetIsolate();
Isolate::Scope isolate_scope(isolate);
Local<Function> callback = Local<Function>::Cast(args[0]);
Persistent<Function, CopyablePersistentTraits<Function>> value(isolate, callback);
timers::callback = value;
}
void shot(const FunctionCallbackInfo<Value>& args) {
Isolate *isolate = JS::GetIsolate();
Isolate::Scope isolate_scope(isolate);
jint delay = args[0]->Int32Value();
int id = Java::GetEnv()->CallIntMethod(jniObject, jniShotMethod, delay);
args.GetReturnValue().Set(Integer::New(isolate, id));
}
void immediate(const FunctionCallbackInfo<Value>& args) {
Isolate *isolate = JS::GetIsolate();
Isolate::Scope isolate_scope(isolate);
Local<Function> callback = Local<Function>::New(isolate, args[0].As<Function>());
isolate->EnqueueMicrotask(callback);
}
int main() {
Persistent<Object, CopyablePersistentTraits<Object>> jsObject;
jsObject = JS::CreateObject(JS::GetGlobalNeftObject(), "timers");
JS::LinkFunction(jsObject, "registerCallback", timers::registerCallback);
JS::LinkFunction(jsObject, "shot", timers::shot);
JS::LinkFunction(jsObject, "immediate", timers::immediate);
return 0;
}
}
extern "C" void Java_io_neft_Native_timers_1init(JNIEnv * env, jobject object, jobject timersObject) {
jclass jniClass = (jclass) env->GetObjectClass(timersObject);
timers::jniObject = env->NewGlobalRef(timersObject);
timers::jniShotMethod = env->GetMethodID(jniClass, "shot", "(I)I");
}
extern "C" void Java_io_neft_Native_timers_1callback(JNIEnv * env, jobject obj, jint id) {
Isolate *isolate = JS::GetIsolate();
Locker locker(isolate);
Isolate::Scope isolate_scope(isolate);
HandleScope handle_scope(isolate);
const unsigned argc = 1;
Local<Value> argv[argc] = { Int32::New(isolate, id) };
JS::CallFunction(timers::callback, argc, argv);
} | apache-2.0 |
corestoreio/csfw | net/jwt/doc.go | 1190 | // Copyright 2015-present, Cyrill @ Schumacher.fm and the CoreStore contributors
//
// 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 jwt provides a middleware for JSON web token authentication and
// runMode initialization.
//
// Further reading: https://float-middle.com/json-web-tokens-jwt-vs-sessions/
// and http://cryto.net/~joepie91/blog/2016/06/13/stop-using-jwt-for-sessions/
//
// https://news.ycombinator.com/item?id=11929267 => For people using JWT as a
// substitute for stateful sessions, how do you handle renewal (or revocation)?
//
// http://cryto.net/~joepie91/blog/2016/06/19/stop-using-jwt-for-sessions-part-2-why-your-solution-doesnt-work/
package jwt
| apache-2.0 |
suwa-sh/swagger-spec-mgr | src/main/java/me/suwash/swagger/spec/manager/sv/domain/gen/UserGen.java | 993 | package me.suwash.swagger.spec.manager.sv.domain.gen;
import org.hibernate.validator.constraints.NotEmpty;
import com.fasterxml.jackson.annotation.JsonProperty;
import lombok.AccessLevel;
import lombok.AllArgsConstructor;
import lombok.Getter;
import me.suwash.swagger.spec.manager.infra.validation.group.Create;
import me.suwash.swagger.spec.manager.infra.validation.group.Delete;
import me.suwash.swagger.spec.manager.infra.validation.group.Read;
import me.suwash.swagger.spec.manager.infra.validation.group.Update;
/**
* UserGen。
*/
@javax.annotation.Generated(value = "io.swagger.codegen.languages.SpringCodegen",
date = "2017-08-08T21:14:16.911+09:00")
@AllArgsConstructor(access = AccessLevel.PROTECTED)
@Getter
public class UserGen {
@JsonProperty("id")
@NotEmpty(groups = {Read.class, Create.class, Update.class, Delete.class})
protected String id = null;
@JsonProperty("email")
@NotEmpty(groups = {Create.class, Update.class})
protected String email = null;
}
| apache-2.0 |
MiguelCatalan/head-first-design-patterns | src/main/java/info/miguelcatalan/headfirst/designpatterns/facade/DVDPlayer.java | 499 | package info.miguelcatalan.headfirst.designpatterns.facade;
class DVDPlayer implements Playable {
private boolean isOn;
private String film;
DVDPlayer() {
this.isOn = false;
}
public void on() {
isOn = true;
}
public void off() {
isOn = false;
}
public boolean isOn() {
return isOn;
}
public void play(String filmName) {
this.film = filmName;
}
public String getFilm() {
return film;
}
}
| apache-2.0 |
phogue/Potato | src/Potato.Database.Shared.Test/MongoDb/TestSerializerMongoDbSaveExplicit.cs | 2465 | #region Copyright
// Copyright 2014 Myrcon Pty. 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.
#endregion
using System.Linq;
using NUnit.Framework;
using Potato.Database.Shared;
using Potato.Database.Shared.Serializers.NoSql;
namespace Potato.Database.Shared.Test.MongoDb {
[TestFixture]
public class TestSerializerMongoDbSaveExplicit : TestSerializerSave {
[Test]
public override void TestSaveIntoPlayerSetName() {
ISerializer serializer = new SerializerMongoDb();
ICompiledQuery serialized = serializer.Parse(this.TestSaveIntoPlayerSetNameExplicit).Compile();
Assert.AreEqual(@"save", serialized.Methods.First());
Assert.AreEqual(@"Player", serialized.Collections.First());
Assert.AreEqual(@"[{""$set"":{""Name"":""Phogue""}}]", serialized.Assignments.First());
}
[Test]
public override void TestSaveIntoPlayerSetNameScore() {
ISerializer serializer = new SerializerMongoDb();
ICompiledQuery serialized = serializer.Parse(this.TestSaveIntoPlayerSetNameScoreExplicit).Compile();
Assert.AreEqual(@"save", serialized.Methods.First());
Assert.AreEqual(@"Player", serialized.Collections.First());
Assert.AreEqual(@"[{""$set"":{""Name"":""Phogue"",""Score"":50.0}}]", serialized.Assignments.First());
}
[Test]
public override void TestSaveIntoPlayerSetNameAndStamp() {
ISerializer serializer = new SerializerMongoDb();
ICompiledQuery serialized = serializer.Parse(this.TestSaveIntoPlayerSetNameAndStampExplicit).Compile();
Assert.AreEqual(@"save", serialized.Methods.First());
Assert.AreEqual(@"Player", serialized.Collections.First());
Assert.AreEqual(@"[{""$set"":{""Name"":""Phogue"",""Stamp"":""2013-12-19T01:08:00.055""}}]", serialized.Assignments.First());
}
}
}
| apache-2.0 |
KarloKnezevic/Ferko | src/java/hr/fer/zemris/jcms/web/navig/builders/course/applications/ApplicationMainBuilder.java | 1457 | package hr.fer.zemris.jcms.web.navig.builders.course.applications;
import hr.fer.zemris.jcms.service.has.HasCourseInstance;
import hr.fer.zemris.jcms.web.actions.data.support.AbstractActionData;
import hr.fer.zemris.jcms.web.navig.ActionNavigationItem;
import hr.fer.zemris.jcms.web.navig.Navigation;
import hr.fer.zemris.jcms.web.navig.NavigationBuilder;
import hr.fer.zemris.jcms.web.navig.TextNavigationItem;
import hr.fer.zemris.jcms.web.navig.builders.course.CourseBuilderPart;
public class ApplicationMainBuilder extends NavigationBuilder {
public static void build(Navigation navig, AbstractActionData actionData, boolean root) {
HasCourseInstance d = (HasCourseInstance)actionData;
navig.suggestPageTitle(actionData.getMessageLogger().getText("Navigation.courseHome") + " " +d.getCourseInstance().getCourse().getName());
CourseBuilderPart.build(navig, actionData, false);
navig.getNavigationBar("m2")
.addItem(
new ActionNavigationItem(d.getCourseInstance().getCourse().getName(), false, "ShowCourse")
.addParameter("courseInstanceID", d.getCourseInstance().getId())
);
if(root) {
navig.getNavigationBar("m2")
.addItem(
new TextNavigationItem("Navigation.applicationsList")
);
} else {
navig.getNavigationBar("m2")
.addItem(
new ActionNavigationItem("Navigation.applicationsList", true, "ApplicationMain")
.addParameter("courseInstanceID", d.getCourseInstance().getId())
);
}
}
}
| apache-2.0 |
gustavoanatoly/hbase | hbase-shell/src/test/ruby/hbase/table_test.rb | 22751 | #
#
# 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.
#
require 'hbase_constants'
include HBaseConstants
module Hbase
# Constructor tests
class TableConstructorTest < Test::Unit::TestCase
include TestHelpers
def setup
setup_hbase
end
def teardown
shutdown
end
define_test "Hbase::Table constructor should not fail for existent tables" do
assert_nothing_raised do
table('hbase:meta').close()
end
end
end
# Helper methods tests
class TableHelpersTest < Test::Unit::TestCase
include TestHelpers
def setup
setup_hbase
# Create test table if it does not exist
@test_name = "hbase_shell_tests_table"
create_test_table(@test_name)
@test_table = table(@test_name)
end
def tearDown
@test_table.close()
shutdown
end
define_test "is_meta_table? method should return true for the meta table" do
assert(table('hbase:meta').is_meta_table?)
end
define_test "is_meta_table? method should return false for a normal table" do
assert(!@test_table.is_meta_table?)
end
#-------------------------------------------------------------------------------
define_test "get_all_columns should return columns list" do
cols = table('hbase:meta').get_all_columns
assert_kind_of(Array, cols)
assert(cols.length > 0)
end
#-------------------------------------------------------------------------------
define_test "parse_column_name should not return a qualifier for name-only column specifiers" do
col, qual = table('hbase:meta').parse_column_name('foo')
assert_not_nil(col)
assert_nil(qual)
end
define_test "parse_column_name should support and empty column qualifier" do
col, qual = table('hbase:meta').parse_column_name('foo:')
assert_not_nil(col)
assert_not_nil(qual)
end
define_test "parse_column_name should return a qualifier for family:qualifier column specifiers" do
col, qual = table('hbase:meta').parse_column_name('foo:bar')
assert_not_nil(col)
assert_not_nil(qual)
end
end
# Simple data management methods tests
class TableSimpleMethodsTest < Test::Unit::TestCase
include TestHelpers
def setup
setup_hbase
# Create test table if it does not exist
@test_name = "hbase_shell_tests_table"
create_test_table(@test_name)
@test_table = table(@test_name)
# Insert data to perform delete operations
@test_table.put("101", "x:a", "1")
@test_table.put("101", "x:a", "2", Time.now.to_i)
@test_table.put("102", "x:a", "1", 1212)
@test_table.put("102", "x:a", "2", 1213)
@test_table.put(103, "x:a", "3")
@test_table.put(103, "x:a", "4")
@test_table.put("104", "x:a", 5)
@test_table.put("104", "x:b", 6)
@test_table.put(105, "x:a", "3")
@test_table.put(105, "x:a", "4")
@test_table.put("111", "x:a", "5")
@test_table.put("111", "x:b", "6")
@test_table.put("112", "x:a", "5")
end
def teardown
@test_table.close
shutdown
end
define_test "put should work without timestamp" do
@test_table.put("123", "x:a", "1")
end
define_test "put should work with timestamp" do
@test_table.put("123", "x:a", "2", Time.now.to_i)
end
define_test "put should work with integer keys" do
@test_table.put(123, "x:a", "3")
end
define_test "put should work with integer values" do
@test_table.put("123", "x:a", 4)
end
define_test "put should work with attributes" do
@test_table.put("123", "x:a", 4, {ATTRIBUTES=>{'mykey'=>'myvalue'}})
end
#-------------------------------------------------------------------------------
define_test "delete should work without timestamp" do
@test_table.delete("101", "x:a")
res = @test_table._get_internal('101', 'x:a')
assert_nil(res)
end
define_test "delete should work with timestamp" do
@test_table.delete("102", "x:a", 1214)
res = @test_table._get_internal('102', 'x:a')
assert_nil(res)
end
define_test "delete should work with integer keys" do
@test_table.delete(103, "x:a")
res = @test_table._get_internal('103', 'x:a')
assert_nil(res)
end
#-------------------------------------------------------------------------------
define_test "deleteall should work w/o columns and timestamps" do
@test_table.deleteall("104")
res = @test_table._get_internal('104', 'x:a', 'x:b')
assert_nil(res)
end
define_test "deleteall should work with integer keys" do
@test_table.deleteall(105)
res = @test_table._get_internal('105', 'x:a')
assert_nil(res)
end
define_test "deletall should work with row prefix" do
@test_table.deleteall({ROWPREFIXFILTER => '11'})
res1 = @test_table._get_internal('111')
assert_nil(res1)
res2 = @test_table._get_internal('112')
assert_nil(res2)
end
define_test "append should work with value" do
@test_table.append("123", 'x:cnt2', '123')
assert_equal("123123", @test_table._append_internal("123", 'x:cnt2', '123'))
end
#-------------------------------------------------------------------------------
define_test "get_counter should work with integer keys" do
@test_table.incr(12345, 'x:cnt')
assert_kind_of(Fixnum, @test_table._get_counter_internal(12345, 'x:cnt'))
end
define_test "get_counter should return nil for non-existent counters" do
assert_nil(@test_table._get_counter_internal(12345, 'x:qqqq'))
end
end
# Complex data management methods tests
class TableComplexMethodsTest < Test::Unit::TestCase
include TestHelpers
def setup
setup_hbase
# Create test table if it does not exist
@test_name = "hbase_shell_tests_table"
create_test_table(@test_name)
@test_table = table(@test_name)
# Instert test data
@test_ts = 12345678
@test_table.put(1, "x:a", 1)
@test_table.put(1, "x:b", 2, @test_ts)
@test_table.put(2, "x:a", 11)
@test_table.put(2, "x:b", 12, @test_ts)
@test_table.put(3, "x:a", 21, {ATTRIBUTES=>{'mykey'=>'myvalue'}})
@test_table.put(3, "x:b", 22, @test_ts, {ATTRIBUTES=>{'mykey'=>'myvalue'}})
end
def teardown
@test_table.close
shutdown
end
define_test "count should work w/o a block passed" do
assert(@test_table._count_internal > 0)
end
define_test "count should work with a block passed (and yield)" do
rows = []
cnt = @test_table._count_internal(1) do |cnt, row|
rows << row
end
assert(cnt > 0)
assert(!rows.empty?)
end
define_test "count should support STARTROW parameter" do
count = @test_table.count STARTROW => '4'
assert(count == 0)
end
define_test "count should support STOPROW parameter" do
count = @test_table.count STOPROW => '0'
assert(count == 0)
end
define_test "count should support COLUMNS parameter" do
@test_table.put(4, "x:c", "31")
begin
count = @test_table.count COLUMNS => [ 'x:c']
assert(count == 1)
ensure
@test_table.delete(4, "x:c")
end
end
define_test "count should support FILTER parameter" do
count = @test_table.count FILTER => "ValueFilter(=, 'binary:11')"
assert(count == 1)
end
#-------------------------------------------------------------------------------
define_test "get should work w/o columns specification" do
res = @test_table._get_internal('1')
assert_not_nil(res)
assert_kind_of(Hash, res)
assert_not_nil(res['x:a'])
assert_not_nil(res['x:b'])
end
define_test "get should work for data written with Attributes" do
res = @test_table._get_internal('3')
assert_not_nil(res)
assert_kind_of(Hash, res)
assert_not_nil(res['x:a'])
assert_not_nil(res['x:b'])
end
define_test "get should work with integer keys" do
res = @test_table._get_internal(1)
assert_not_nil(res)
assert_kind_of(Hash, res)
assert_not_nil(res['x:a'])
assert_not_nil(res['x:b'])
end
define_test "get should work with hash columns spec and a single string COLUMN parameter" do
res = @test_table._get_internal('1', COLUMN => 'x:a')
assert_not_nil(res)
assert_kind_of(Hash, res)
assert_not_nil(res['x:a'])
assert_nil(res['x:b'])
end
define_test "get should work with hash columns spec and a single string COLUMNS parameter" do
res = @test_table._get_internal('1', COLUMNS => 'x:a')
assert_not_nil(res)
assert_kind_of(Hash, res)
assert_not_nil(res['x:a'])
assert_nil(res['x:b'])
end
define_test "get should work with hash columns spec and an array of strings COLUMN parameter" do
res = @test_table._get_internal('1', COLUMN => [ 'x:a', 'x:b' ])
assert_not_nil(res)
assert_kind_of(Hash, res)
assert_not_nil(res['x:a'])
assert_not_nil(res['x:b'])
end
define_test "get should work with hash columns spec and an array of strings COLUMNS parameter" do
res = @test_table._get_internal('1', COLUMNS => [ 'x:a', 'x:b' ])
assert_not_nil(res)
assert_kind_of(Hash, res)
assert_not_nil(res['x:a'])
assert_not_nil(res['x:b'])
end
define_test "get should work with hash columns spec and an array of strings COLUMNS parameter with AUTHORIZATIONS" do
res = @test_table._get_internal('1', COLUMNS => [ 'x:a', 'x:b' ], AUTHORIZATIONS=>['PRIVATE'])
assert_not_nil(res)
assert_kind_of(Hash, res)
assert_not_nil(res['x:a'])
assert_not_nil(res['x:b'])
end
define_test "get should work with hash columns spec and TIMESTAMP only" do
res = @test_table._get_internal('1', TIMESTAMP => @test_ts)
assert_not_nil(res)
assert_kind_of(Hash, res)
assert_nil(res['x:a'])
assert_not_nil(res['x:b'])
end
define_test "get should work with hash columns spec and TIMESTAMP and AUTHORIZATIONS" do
res = @test_table._get_internal('1', TIMESTAMP => 1234, AUTHORIZATIONS=>['PRIVATE'])
assert_nil(res)
end
define_test "get should fail with hash columns spec and strange COLUMN value" do
assert_raise(ArgumentError) do
@test_table._get_internal('1', COLUMN => {})
end
end
define_test "get should fail with hash columns spec and strange COLUMNS value" do
assert_raise(ArgumentError) do
@test_table._get_internal('1', COLUMN => {})
end
end
define_test "get should fail with hash columns spec and no TIMESTAMP or COLUMN[S]" do
assert_raise(ArgumentError) do
@test_table._get_internal('1', { :foo => :bar })
end
end
define_test "get should work with a string column spec" do
res = @test_table._get_internal('1', 'x:b')
assert_not_nil(res)
assert_kind_of(Hash, res)
assert_nil(res['x:a'])
assert_not_nil(res['x:b'])
end
define_test "get should work with an array columns spec" do
res = @test_table._get_internal('1', 'x:a', 'x:b')
assert_not_nil(res)
assert_kind_of(Hash, res)
assert_not_nil(res['x:a'])
assert_not_nil(res['x:b'])
end
define_test "get should work with an array or arrays columns spec (yeah, crazy)" do
res = @test_table._get_internal('1', ['x:a'], ['x:b'])
assert_not_nil(res)
assert_kind_of(Hash, res)
assert_not_nil(res['x:a'])
assert_not_nil(res['x:b'])
end
define_test "get with a block should yield (column, value) pairs" do
res = {}
@test_table._get_internal('1') { |col, val| res[col] = val }
assert_equal(res.keys.sort, [ 'x:a', 'x:b' ])
end
define_test "get should support COLUMNS with value CONVERTER information" do
@test_table.put(1, "x:c", [1024].pack('N'))
@test_table.put(1, "x:d", [98].pack('N'))
begin
res = @test_table._get_internal('1', ['x:c:toInt'], ['x:d:c(org.apache.hadoop.hbase.util.Bytes).toInt'])
assert_not_nil(res)
assert_kind_of(Hash, res)
assert_not_nil(/value=1024/.match(res['x:c']))
assert_not_nil(/value=98/.match(res['x:d']))
ensure
# clean up newly added columns for this test only.
@test_table.delete(1, "x:c")
@test_table.delete(1, "x:d")
end
end
define_test "get should support FILTER" do
@test_table.put(1, "x:v", "thisvalue")
begin
res = @test_table._get_internal('1', FILTER => "ValueFilter(=, 'binary:thisvalue')")
assert_not_nil(res)
assert_kind_of(Hash, res)
assert_not_nil(res['x:v'])
assert_nil(res['x:a'])
res = @test_table._get_internal('1', FILTER => "ValueFilter(=, 'binary:thatvalue')")
assert_nil(res)
ensure
# clean up newly added columns for this test only.
@test_table.delete(1, "x:v")
end
end
#-------------------------------------------------------------------------------
define_test "scan should work w/o any params" do
res = @test_table._scan_internal
assert_not_nil(res)
assert_kind_of(Hash, res)
assert_not_nil(res['1'])
assert_not_nil(res['1']['x:a'])
assert_not_nil(res['1']['x:b'])
assert_not_nil(res['2'])
assert_not_nil(res['2']['x:a'])
assert_not_nil(res['2']['x:b'])
end
define_test "scan should support STARTROW parameter" do
res = @test_table._scan_internal STARTROW => '2'
assert_not_nil(res)
assert_kind_of(Hash, res)
assert_nil(res['1'])
assert_not_nil(res['2'])
assert_not_nil(res['2']['x:a'])
assert_not_nil(res['2']['x:b'])
end
define_test "scan should support STOPROW parameter" do
res = @test_table._scan_internal STOPROW => '2'
assert_not_nil(res)
assert_kind_of(Hash, res)
assert_not_nil(res['1'])
assert_not_nil(res['1']['x:a'])
assert_not_nil(res['1']['x:b'])
assert_nil(res['2'])
end
define_test "scan should support ROWPREFIXFILTER parameter (test 1)" do
res = @test_table._scan_internal ROWPREFIXFILTER => '1'
assert_not_nil(res)
assert_kind_of(Hash, res)
assert_not_nil(res['1'])
assert_not_nil(res['1']['x:a'])
assert_not_nil(res['1']['x:b'])
assert_nil(res['2'])
end
define_test "scan should support ROWPREFIXFILTER parameter (test 2)" do
res = @test_table._scan_internal ROWPREFIXFILTER => '2'
assert_not_nil(res)
assert_kind_of(Hash, res)
assert_nil(res['1'])
assert_not_nil(res['2'])
assert_not_nil(res['2']['x:a'])
assert_not_nil(res['2']['x:b'])
end
define_test "scan should support LIMIT parameter" do
res = @test_table._scan_internal LIMIT => 1
assert_not_nil(res)
assert_kind_of(Hash, res)
assert_not_nil(res['1'])
assert_not_nil(res['1']['x:a'])
assert_not_nil(res['1']['x:b'])
assert_nil(res['2'])
end
define_test "scan should support REVERSED parameter" do
res = @test_table._scan_internal REVERSED => true
assert_not_nil(res)
assert_kind_of(Hash, res)
assert_not_nil(res['1'])
assert_not_nil(res['1']['x:a'])
assert_not_nil(res['1']['x:b'])
assert_not_nil(res['2'])
assert_not_nil(res['2']['x:a'])
assert_not_nil(res['2']['x:b'])
end
define_test "scan should support TIMESTAMP parameter" do
res = @test_table._scan_internal TIMESTAMP => @test_ts
assert_not_nil(res)
assert_kind_of(Hash, res)
assert_not_nil(res['1'])
assert_nil(res['1']['x:a'])
assert_not_nil(res['1']['x:b'])
assert_not_nil(res['2'])
assert_nil(res['2']['x:a'])
assert_not_nil(res['2']['x:b'])
end
define_test "scan should support TIMERANGE parameter" do
res = @test_table._scan_internal TIMERANGE => [0, 1]
assert_not_nil(res)
assert_kind_of(Hash, res)
assert_nil(res['1'])
assert_nil(res['2'])
end
define_test "scan should support COLUMNS parameter with an array of columns" do
res = @test_table._scan_internal COLUMNS => [ 'x:a', 'x:b' ]
assert_not_nil(res)
assert_kind_of(Hash, res)
assert_not_nil(res['1'])
assert_not_nil(res['1']['x:a'])
assert_not_nil(res['1']['x:b'])
assert_not_nil(res['2'])
assert_not_nil(res['2']['x:a'])
assert_not_nil(res['2']['x:b'])
end
define_test "scan should support COLUMNS parameter with a single column name" do
res = @test_table._scan_internal COLUMNS => 'x:a'
assert_not_nil(res)
assert_kind_of(Hash, res)
assert_not_nil(res['1'])
assert_not_nil(res['1']['x:a'])
assert_nil(res['1']['x:b'])
assert_not_nil(res['2'])
assert_not_nil(res['2']['x:a'])
assert_nil(res['2']['x:b'])
end
define_test "scan should work with raw and version parameter" do
# Create test table if it does not exist
@test_name_raw = "hbase_shell_tests_raw_scan"
create_test_table(@test_name_raw)
@test_table = table(@test_name_raw)
# Instert test data
@test_table.put(1, "x:a", 1)
@test_table.put(2, "x:raw1", 11)
@test_table.put(2, "x:raw1", 11)
@test_table.put(2, "x:raw1", 11)
@test_table.put(2, "x:raw1", 11)
args = {}
numRows = 0
count = @test_table._scan_internal(args) do |row, cells| # Normal Scan
numRows += 1
end
assert_equal(numRows, 2, "Num rows scanned without RAW/VERSIONS are not 2")
args = {VERSIONS=>10,RAW=>true} # Since 4 versions of row with rowkey 2 is been added, we can use any number >= 4 for VERSIONS to scan all 4 versions.
numRows = 0
count = @test_table._scan_internal(args) do |row, cells| # Raw Scan
numRows += 1
end
assert_equal(numRows, 5, "Num rows scanned without RAW/VERSIONS are not 5") # 5 since , 1 from row key '1' and other 4 from row key '4'
end
define_test "scan should fail on invalid COLUMNS parameter types" do
assert_raise(ArgumentError) do
@test_table._scan_internal COLUMNS => {}
end
end
define_test "scan should fail on non-hash params" do
assert_raise(ArgumentError) do
@test_table._scan_internal 123
end
end
define_test "scan with a block should yield rows and return rows counter" do
rows = {}
res = @test_table._scan_internal { |row, cells| rows[row] = cells }
assert_equal([rows.keys.size,false], res)
end
define_test "scan should support COLUMNS with value CONVERTER information" do
@test_table.put(1, "x:c", [1024].pack('N'))
@test_table.put(1, "x:d", [98].pack('N'))
begin
res = @test_table._scan_internal COLUMNS => ['x:c:toInt', 'x:d:c(org.apache.hadoop.hbase.util.Bytes).toInt']
assert_not_nil(res)
assert_kind_of(Hash, res)
assert_not_nil(/value=1024/.match(res['1']['x:c']))
assert_not_nil(/value=98/.match(res['1']['x:d']))
ensure
# clean up newly added columns for this test only.
@test_table.delete(1, "x:c")
@test_table.delete(1, "x:d")
end
end
define_test "scan should support FILTER" do
@test_table.put(1, "x:v", "thisvalue")
begin
res = @test_table._scan_internal FILTER => "ValueFilter(=, 'binary:thisvalue')"
assert_not_equal(res, {}, "Result is empty")
assert_kind_of(Hash, res)
assert_not_nil(res['1'])
assert_not_nil(res['1']['x:v'])
assert_nil(res['1']['x:a'])
assert_nil(res['2'])
res = @test_table._scan_internal FILTER => "ValueFilter(=, 'binary:thatvalue')"
assert_equal(res, {}, "Result is not empty")
ensure
# clean up newly added columns for this test only.
@test_table.delete(1, "x:v")
end
end
define_test "scan should support FILTER with non-ASCII bytes" do
@test_table.put(4, "x:a", "\x82")
begin
res = @test_table._scan_internal FILTER => "SingleColumnValueFilter('x', 'a', >=, 'binary:\x82', true, true)"
assert_not_equal(res, {}, "Result is empty")
assert_kind_of(Hash, res)
assert_not_nil(res['4'])
assert_not_nil(res['4']['x:a'])
assert_nil(res['1'])
assert_nil(res['2'])
ensure
# clean up newly added columns for this test only.
@test_table.delete(4, "x:a")
end
end
define_test "scan hbase meta table" do
res = table("hbase:meta")._scan_internal
assert_not_nil(res)
end
define_test "mutation with TTL should expire" do
@test_table.put('ttlTest', 'x:a', 'foo', { TTL => 1000 } )
begin
res = @test_table._get_internal('ttlTest', 'x:a')
assert_not_nil(res)
sleep 2
res = @test_table._get_internal('ttlTest', 'x:a')
assert_nil(res)
ensure
@test_table.delete('ttlTest', 'x:a')
end
end
define_test "Split count for a table" do
@testTableName = "tableWithSplits"
create_test_table_with_splits(@testTableName, SPLITS => ['10', '20', '30', '40'])
@table = table(@testTableName)
splits = @table._get_splits_internal()
#Total splits is 5 but here count is 4 as we ignore implicit empty split.
assert_equal(4, splits.size)
assert_equal(["10", "20", "30", "40"], splits)
drop_test_table(@testTableName)
end
define_test "Split count for a empty table" do
splits = @test_table._get_splits_internal()
#Empty split should not be part of this array.
assert_equal(0, splits.size)
assert_equal([], splits)
end
end
end
| apache-2.0 |
NJUJYB/disYarn | hadoop-yarn-project/hadoop-yarn/hadoop-yarn-registry/src/main/java/org/apache/hadoop/registry/client/impl/zk/RegistrySecurity.java | 30406 | /*
* 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.registry.client.impl.zk;
import com.google.common.base.Preconditions;
import com.google.common.base.Splitter;
import com.google.common.collect.Lists;
import org.apache.commons.lang.StringUtils;
import org.apache.curator.framework.CuratorFrameworkFactory;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.security.UserGroupInformation;
import org.apache.hadoop.security.authentication.util.KerberosUtil;
import org.apache.hadoop.service.AbstractService;
import org.apache.hadoop.service.ServiceStateException;
import org.apache.hadoop.util.ZKUtil;
import org.apache.zookeeper.Environment;
import org.apache.zookeeper.ZooDefs;
import org.apache.zookeeper.data.ACL;
import org.apache.zookeeper.data.Id;
import org.apache.zookeeper.server.auth.DigestAuthenticationProvider;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.security.auth.login.AppConfigurationEntry;
import java.io.File;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.ListIterator;
import java.util.Locale;
import java.util.concurrent.CopyOnWriteArrayList;
import static org.apache.hadoop.registry.client.impl.zk.ZookeeperConfigOptions.*;
import static org.apache.hadoop.registry.client.api.RegistryConstants.*;
/**
* Implement the registry security ... a self contained service for
* testability.
* <p>
* This class contains:
* <ol>
* <li>
* The registry security policy implementation, configuration reading, ACL
* setup and management
* </li>
* <li>Lots of static helper methods to aid security setup and debugging</li>
* </ol>
*/
public class RegistrySecurity extends AbstractService {
private static final Logger LOG =
LoggerFactory.getLogger(RegistrySecurity.class);
public static final String E_UNKNOWN_AUTHENTICATION_MECHANISM =
"Unknown/unsupported authentication mechanism; ";
/**
* there's no default user to add with permissions, so it would be
* impossible to create nodes with unrestricted user access
*/
public static final String E_NO_USER_DETERMINED_FOR_ACLS =
"No user for ACLs determinable from current user or registry option "
+ KEY_REGISTRY_USER_ACCOUNTS;
/**
* Error raised when the registry is tagged as secure but this
* process doesn't have hadoop security enabled.
*/
public static final String E_NO_KERBEROS =
"Registry security is enabled -but Hadoop security is not enabled";
/**
* Access policy options
*/
private enum AccessPolicy {
anon, sasl, digest
}
/**
* Access mechanism
*/
private AccessPolicy access;
/**
* User used for digest auth
*/
private String digestAuthUser;
/**
* Password used for digest auth
*/
private String digestAuthPassword;
/**
* Auth data used for digest auth
*/
private byte[] digestAuthData;
/**
* flag set to true if the registry has security enabled.
*/
private boolean secureRegistry;
/**
* An ACL with read-write access for anyone
*/
public static final ACL ALL_READWRITE_ACCESS =
new ACL(ZooDefs.Perms.ALL, ZooDefs.Ids.ANYONE_ID_UNSAFE);
/**
* An ACL with read access for anyone
*/
public static final ACL ALL_READ_ACCESS =
new ACL(ZooDefs.Perms.READ, ZooDefs.Ids.ANYONE_ID_UNSAFE);
/**
* An ACL list containing the {@link #ALL_READWRITE_ACCESS} entry.
* It is copy on write so can be shared without worry
*/
public static final List<ACL> WorldReadWriteACL;
static {
List<ACL> acls = new ArrayList<ACL>();
acls.add(ALL_READWRITE_ACCESS);
WorldReadWriteACL = new CopyOnWriteArrayList<ACL>(acls);
}
/**
* the list of system ACLs
*/
private final List<ACL> systemACLs = new ArrayList<ACL>();
/**
* A list of digest ACLs which can be added to permissions
* —and cleared later.
*/
private final List<ACL> digestACLs = new ArrayList<ACL>();
/**
* the default kerberos realm
*/
private String kerberosRealm;
/**
* Client context
*/
private String jaasClientContext;
/**
* Client identity
*/
private String jaasClientIdentity;
/**
* Create an instance
* @param name service name
*/
public RegistrySecurity(String name) {
super(name);
}
/**
* Init the service: this sets up security based on the configuration
* @param conf configuration
* @throws Exception
*/
@Override
protected void serviceInit(Configuration conf) throws Exception {
super.serviceInit(conf);
String auth = conf.getTrimmed(KEY_REGISTRY_CLIENT_AUTH,
REGISTRY_CLIENT_AUTH_ANONYMOUS);
switch (auth) {
case REGISTRY_CLIENT_AUTH_KERBEROS:
access = AccessPolicy.sasl;
break;
case REGISTRY_CLIENT_AUTH_DIGEST:
access = AccessPolicy.digest;
break;
case REGISTRY_CLIENT_AUTH_ANONYMOUS:
access = AccessPolicy.anon;
break;
default:
throw new ServiceStateException(E_UNKNOWN_AUTHENTICATION_MECHANISM
+ "\"" + auth + "\"");
}
initSecurity();
}
/**
* Init security.
*
* After this operation, the {@link #systemACLs} list is valid.
* @throws IOException
*/
private void initSecurity() throws IOException {
secureRegistry =
getConfig().getBoolean(KEY_REGISTRY_SECURE, DEFAULT_REGISTRY_SECURE);
systemACLs.clear();
if (secureRegistry) {
addSystemACL(ALL_READ_ACCESS);
// determine the kerberos realm from JVM and settings
kerberosRealm = getConfig().get(KEY_REGISTRY_KERBEROS_REALM,
getDefaultRealmInJVM());
// System Accounts
String system = getOrFail(KEY_REGISTRY_SYSTEM_ACCOUNTS,
DEFAULT_REGISTRY_SYSTEM_ACCOUNTS);
systemACLs.addAll(buildACLs(system, kerberosRealm, ZooDefs.Perms.ALL));
// user accounts (may be empty, but for digest one user AC must
// be built up
String user = getConfig().get(KEY_REGISTRY_USER_ACCOUNTS,
DEFAULT_REGISTRY_USER_ACCOUNTS);
List<ACL> userACLs = buildACLs(user, kerberosRealm, ZooDefs.Perms.ALL);
// add self if the current user can be determined
ACL self;
if (UserGroupInformation.isSecurityEnabled()) {
self = createSaslACLFromCurrentUser(ZooDefs.Perms.ALL);
if (self != null) {
userACLs.add(self);
}
}
// here check for UGI having secure on or digest + ID
switch (access) {
case sasl:
// secure + SASL => has to be authenticated
if (!UserGroupInformation.isSecurityEnabled()) {
throw new IOException("Kerberos required for secure registry access");
}
UserGroupInformation currentUser =
UserGroupInformation.getCurrentUser();
jaasClientContext = getOrFail(KEY_REGISTRY_CLIENT_JAAS_CONTEXT,
DEFAULT_REGISTRY_CLIENT_JAAS_CONTEXT);
jaasClientIdentity = currentUser.getShortUserName();
if (LOG.isDebugEnabled()) {
LOG.debug("Auth is SASL user=\"{}\" JAAS context=\"{}\"",
jaasClientIdentity,
jaasClientContext);
}
break;
case digest:
String id = getOrFail(KEY_REGISTRY_CLIENT_AUTHENTICATION_ID, "");
String pass = getOrFail(KEY_REGISTRY_CLIENT_AUTHENTICATION_PASSWORD, "");
if (userACLs.isEmpty()) {
//
throw new ServiceStateException(E_NO_USER_DETERMINED_FOR_ACLS);
}
digest(id, pass);
ACL acl = new ACL(ZooDefs.Perms.ALL, toDigestId(id, pass));
userACLs.add(acl);
digestAuthUser = id;
digestAuthPassword = pass;
String authPair = id + ":" + pass;
digestAuthData = authPair.getBytes("UTF-8");
if (LOG.isDebugEnabled()) {
LOG.debug("Auth is Digest ACL: {}", aclToString(acl));
}
break;
case anon:
// nothing is needed; account is read only.
if (LOG.isDebugEnabled()) {
LOG.debug("Auth is anonymous");
}
userACLs = new ArrayList<ACL>(0);
break;
}
systemACLs.addAll(userACLs);
} else {
if (LOG.isDebugEnabled()) {
LOG.debug("Registry has no security");
}
// wide open cluster, adding system acls
systemACLs.addAll(WorldReadWriteACL);
}
}
/**
* Add another system ACL
* @param acl add ACL
*/
public void addSystemACL(ACL acl) {
systemACLs.add(acl);
}
/**
* Add a digest ACL
* @param acl add ACL
*/
public boolean addDigestACL(ACL acl) {
if (secureRegistry) {
if (LOG.isDebugEnabled()) {
LOG.debug("Added ACL {}", aclToString(acl));
}
digestACLs.add(acl);
return true;
} else {
if (LOG.isDebugEnabled()) {
LOG.debug("Ignoring added ACL - registry is insecure{}",
aclToString(acl));
}
return false;
}
}
/**
* Reset the digest ACL list
*/
public void resetDigestACLs() {
if (LOG.isDebugEnabled()) {
LOG.debug("Cleared digest ACLs");
}
digestACLs.clear();
}
/**
* Flag to indicate the cluster is secure
* @return true if the config enabled security
*/
public boolean isSecureRegistry() {
return secureRegistry;
}
/**
* Get the system principals
* @return the system principals
*/
public List<ACL> getSystemACLs() {
Preconditions.checkNotNull(systemACLs, "registry security is unitialized");
return Collections.unmodifiableList(systemACLs);
}
/**
* Get all ACLs needed for a client to use when writing to the repo.
* That is: system ACLs, its own ACL, any digest ACLs
* @return the client ACLs
*/
public List<ACL> getClientACLs() {
List<ACL> clientACLs = new ArrayList<ACL>(systemACLs);
clientACLs.addAll(digestACLs);
return clientACLs;
}
/**
* Create a SASL ACL for the user
* @param perms permissions
* @return an ACL for the current user or null if they aren't a kerberos user
* @throws IOException
*/
public ACL createSaslACLFromCurrentUser(int perms) throws IOException {
UserGroupInformation currentUser = UserGroupInformation.getCurrentUser();
if (currentUser.hasKerberosCredentials()) {
return createSaslACL(currentUser, perms);
} else {
return null;
}
}
/**
* Given a UGI, create a SASL ACL from it
* @param ugi UGI
* @param perms permissions
* @return a new ACL
*/
public ACL createSaslACL(UserGroupInformation ugi, int perms) {
String userName = ugi.getUserName();
return new ACL(perms, new Id(SCHEME_SASL, userName));
}
/**
* Get a conf option, throw an exception if it is null/empty
* @param key key
* @param defval default value
* @return the value
* @throws IOException if missing
*/
private String getOrFail(String key, String defval) throws IOException {
String val = getConfig().get(key, defval);
if (StringUtils.isEmpty(val)) {
throw new IOException("Missing value for configuration option " + key);
}
return val;
}
/**
* Check for an id:password tuple being valid.
* This test is stricter than that in {@link DigestAuthenticationProvider},
* which splits the string, but doesn't check the contents of each
* half for being non-"".
* @param idPasswordPair id:pass pair
* @return true if the pass is considered valid.
*/
public boolean isValid(String idPasswordPair) {
String[] parts = idPasswordPair.split(":");
return parts.length == 2
&& !StringUtils.isEmpty(parts[0])
&& !StringUtils.isEmpty(parts[1]);
}
/**
* Get the derived kerberos realm.
* @return this is built from the JVM realm, or the configuration if it
* overrides it. If "", it means "don't know".
*/
public String getKerberosRealm() {
return kerberosRealm;
}
/**
* Generate a base-64 encoded digest of the idPasswordPair pair
* @param idPasswordPair id:password
* @return a string that can be used for authentication
*/
public String digest(String idPasswordPair) throws IOException {
if (StringUtils.isEmpty(idPasswordPair) || !isValid(idPasswordPair)) {
throw new IOException("Invalid id:password: " + idPasswordPair);
}
try {
return DigestAuthenticationProvider.generateDigest(idPasswordPair);
} catch (NoSuchAlgorithmException e) {
// unlikely since it is standard to the JVM, but maybe JCE restrictions
// could trigger it
throw new IOException(e.toString(), e);
}
}
/**
* Generate a base-64 encoded digest of the idPasswordPair pair
* @param id ID
* @param password pass
* @return a string that can be used for authentication
* @throws IOException
*/
public String digest(String id, String password) throws IOException {
return digest(id + ":" + password);
}
/**
* Given a digest, create an ID from it
* @param digest digest
* @return ID
*/
public Id toDigestId(String digest) {
return new Id(SCHEME_DIGEST, digest);
}
/**
* Create a Digest ID from an id:pass pair
* @param id ID
* @param password password
* @return an ID
* @throws IOException
*/
public Id toDigestId(String id, String password) throws IOException {
return toDigestId(digest(id, password));
}
/**
* Split up a list of the form
* <code>sasl:mapred@,digest:5f55d66, sasl@yarn@EXAMPLE.COM</code>
* into a list of possible ACL values, trimming as needed
*
* The supplied realm is added to entries where
* <ol>
* <li>the string begins "sasl:"</li>
* <li>the string ends with "@"</li>
* </ol>
* No attempt is made to validate any of the acl patterns.
*
* @param aclString list of 0 or more ACLs
* @param realm realm to add
* @return a list of split and potentially patched ACL pairs.
*
*/
public List<String> splitAclPairs(String aclString, String realm) {
List<String> list = Lists.newArrayList(
Splitter.on(',').omitEmptyStrings().trimResults()
.split(aclString));
ListIterator<String> listIterator = list.listIterator();
while (listIterator.hasNext()) {
String next = listIterator.next();
if (next.startsWith(SCHEME_SASL +":") && next.endsWith("@")) {
listIterator.set(next + realm);
}
}
return list;
}
/**
* Parse a string down to an ID, adding a realm if needed
* @param idPair id:data tuple
* @param realm realm to add
* @return the ID.
* @throws IllegalArgumentException if the idPair is invalid
*/
public Id parse(String idPair, String realm) {
int firstColon = idPair.indexOf(':');
int lastColon = idPair.lastIndexOf(':');
if (firstColon == -1 || lastColon == -1 || firstColon != lastColon) {
throw new IllegalArgumentException(
"ACL '" + idPair + "' not of expected form scheme:id");
}
String scheme = idPair.substring(0, firstColon);
String id = idPair.substring(firstColon + 1);
if (id.endsWith("@")) {
Preconditions.checkArgument(
StringUtils.isNotEmpty(realm),
"@ suffixed account but no realm %s", id);
id = id + realm;
}
return new Id(scheme, id);
}
/**
* Parse the IDs, adding a realm if needed, setting the permissions
* @param principalList id string
* @param realm realm to add
* @param perms permissions
* @return the relevant ACLs
* @throws IOException
*/
public List<ACL> buildACLs(String principalList, String realm, int perms)
throws IOException {
List<String> aclPairs = splitAclPairs(principalList, realm);
List<ACL> ids = new ArrayList<ACL>(aclPairs.size());
for (String aclPair : aclPairs) {
ACL newAcl = new ACL();
newAcl.setId(parse(aclPair, realm));
newAcl.setPerms(perms);
ids.add(newAcl);
}
return ids;
}
/**
* Parse an ACL list. This includes configuration indirection
* {@link ZKUtil#resolveConfIndirection(String)}
* @param zkAclConf configuration string
* @return an ACL list
* @throws IOException on a bad ACL parse
*/
public List<ACL> parseACLs(String zkAclConf) throws IOException {
try {
return ZKUtil.parseACLs(ZKUtil.resolveConfIndirection(zkAclConf));
} catch (ZKUtil.BadAclFormatException e) {
throw new IOException("Parsing " + zkAclConf + " :" + e, e);
}
}
/**
* Get the appropriate Kerberos Auth module for JAAS entries
* for this JVM.
* @return a JVM-specific kerberos login module classname.
*/
public static String getKerberosAuthModuleForJVM() {
if (System.getProperty("java.vendor").contains("IBM")) {
return "com.ibm.security.auth.module.Krb5LoginModule";
} else {
return "com.sun.security.auth.module.Krb5LoginModule";
}
}
/**
* JAAS template: {@value}
* Note the semicolon on the last entry
*/
private static final String JAAS_ENTRY =
"%s { %n"
+ " %s required%n"
// kerberos module
+ " keyTab=\"%s\"%n"
+ " debug=true%n"
+ " principal=\"%s\"%n"
+ " useKeyTab=true%n"
+ " useTicketCache=false%n"
+ " doNotPrompt=true%n"
+ " storeKey=true;%n"
+ "}; %n"
;
/**
* Create a JAAS entry for insertion
* @param context context of the entry
* @param principal kerberos principal
* @param keytab keytab
* @return a context
*/
public String createJAASEntry(
String context,
String principal,
File keytab) {
Preconditions.checkArgument(StringUtils.isNotEmpty(principal),
"invalid principal");
Preconditions.checkArgument(StringUtils.isNotEmpty(context),
"invalid context");
Preconditions.checkArgument(keytab != null && keytab.isFile(),
"Keytab null or missing: ");
String keytabpath = keytab.getAbsolutePath();
// fix up for windows; no-op on unix
keytabpath = keytabpath.replace('\\', '/');
return String.format(
Locale.ENGLISH,
JAAS_ENTRY,
context,
getKerberosAuthModuleForJVM(),
keytabpath,
principal);
}
/**
* Bind the JVM JAS setting to the specified JAAS file.
*
* <b>Important:</b> once a file has been loaded the JVM doesn't pick up
* changes
* @param jaasFile the JAAS file
*/
public static void bindJVMtoJAASFile(File jaasFile) {
String path = jaasFile.getAbsolutePath();
if (LOG.isDebugEnabled()) {
LOG.debug("Binding {} to {}", Environment.JAAS_CONF_KEY, path);
}
System.setProperty(Environment.JAAS_CONF_KEY, path);
}
/**
* Set the Zookeeper server property
* {@link ZookeeperConfigOptions#PROP_ZK_SERVER_SASL_CONTEXT}
* to the SASL context. When the ZK server starts, this is the context
* which it will read in
* @param contextName the name of the context
*/
public static void bindZKToServerJAASContext(String contextName) {
System.setProperty(PROP_ZK_SERVER_SASL_CONTEXT, contextName);
}
/**
* Reset any system properties related to JAAS
*/
public static void clearJaasSystemProperties() {
System.clearProperty(Environment.JAAS_CONF_KEY);
}
/**
* Resolve the context of an entry. This is an effective test of
* JAAS setup, because it will relay detected problems up
* @param context context name
* @return the entry
* @throws RuntimeException if there is no context entry found
*/
public static AppConfigurationEntry[] validateContext(String context) {
if (context == null) {
throw new RuntimeException("Null context argument");
}
if (context.isEmpty()) {
throw new RuntimeException("Empty context argument");
}
javax.security.auth.login.Configuration configuration =
javax.security.auth.login.Configuration.getConfiguration();
AppConfigurationEntry[] entries =
configuration.getAppConfigurationEntry(context);
if (entries == null) {
throw new RuntimeException(
String.format("Entry \"%s\" not found; " +
"JAAS config = %s",
context,
describeProperty(Environment.JAAS_CONF_KEY) ));
}
return entries;
}
/**
* Apply the security environment to this curator instance. This
* may include setting up the ZK system properties for SASL
* @param builder curator builder
*/
public void applySecurityEnvironment(CuratorFrameworkFactory.Builder builder) {
if (isSecureRegistry()) {
switch (access) {
case anon:
clearZKSaslClientProperties();
break;
case digest:
// no SASL
clearZKSaslClientProperties();
builder.authorization(SCHEME_DIGEST, digestAuthData);
break;
case sasl:
// bind to the current identity and context within the JAAS file
setZKSaslClientProperties(jaasClientIdentity, jaasClientContext);
}
}
}
/**
* Set the client properties. This forces the ZK client into
* failing if it can't auth.
* <b>Important:</b>This is JVM-wide.
* @param username username
* @param context login context
* @throws RuntimeException if the context cannot be found in the current
* JAAS context
*/
public static void setZKSaslClientProperties(String username,
String context) {
RegistrySecurity.validateContext(context);
enableZookeeperClientSASL();
System.setProperty(PROP_ZK_SASL_CLIENT_USERNAME, username);
System.setProperty(PROP_ZK_SASL_CLIENT_CONTEXT, context);
}
/**
* Clear all the ZK SASL Client properties
* <b>Important:</b>This is JVM-wide
*/
public static void clearZKSaslClientProperties() {
disableZookeeperClientSASL();
System.clearProperty(PROP_ZK_SASL_CLIENT_CONTEXT);
System.clearProperty(PROP_ZK_SASL_CLIENT_USERNAME);
}
/**
* Turn ZK SASL on
* <b>Important:</b>This is JVM-wide
*/
protected static void enableZookeeperClientSASL() {
System.setProperty(PROP_ZK_ENABLE_SASL_CLIENT, "true");
}
/**
* Force disable ZK SASL bindings.
* <b>Important:</b>This is JVM-wide
*/
public static void disableZookeeperClientSASL() {
System.setProperty(ZookeeperConfigOptions.PROP_ZK_ENABLE_SASL_CLIENT, "false");
}
/**
* Is the system property enabling the SASL client set?
* @return true if the SASL client system property is set.
*/
public static boolean isClientSASLEnabled() {
return Boolean.parseBoolean(System.getProperty(
ZookeeperConfigOptions.PROP_ZK_ENABLE_SASL_CLIENT, "true"));
}
/**
* Log details about the current Hadoop user at INFO.
* Robust against IOEs when trying to get the current user
*/
public void logCurrentHadoopUser() {
try {
UserGroupInformation currentUser = UserGroupInformation.getCurrentUser();
LOG.info("Current user = {}",currentUser);
UserGroupInformation realUser = currentUser.getRealUser();
LOG.info("Real User = {}" , realUser);
} catch (IOException e) {
LOG.warn("Failed to get current user {}, {}", e);
}
}
/**
* Stringify a list of ACLs for logging. Digest ACLs have their
* digest values stripped for security.
* @param acls ACL list
* @return a string for logs, exceptions, ...
*/
public static String aclsToString(List<ACL> acls) {
StringBuilder builder = new StringBuilder();
if (acls == null) {
builder.append("null ACL");
} else {
builder.append('\n');
for (ACL acl : acls) {
builder.append(aclToString(acl))
.append(" ");
}
}
return builder.toString();
}
/**
* Convert an ACL to a string, with any obfuscation needed
* @param acl ACL
* @return ACL string value
*/
public static String aclToString(ACL acl) {
return String.format(Locale.ENGLISH,
"0x%02x: %s",
acl.getPerms(),
idToString(acl.getId())
);
}
/**
* Convert an ID to a string, stripping out all but the first few characters
* of any digest auth hash for security reasons
* @param id ID
* @return a string description of a Zookeeper ID
*/
public static String idToString(Id id) {
String s;
if (id.getScheme().equals(SCHEME_DIGEST)) {
String ids = id.getId();
int colon = ids.indexOf(':');
if (colon > 0) {
ids = ids.substring(colon + 3);
}
s = SCHEME_DIGEST + ": " + ids;
} else {
s = id.toString();
}
return s;
}
/**
* Build up low-level security diagnostics to aid debugging
* @return a string to use in diagnostics
*/
public String buildSecurityDiagnostics() {
StringBuilder builder = new StringBuilder();
builder.append(secureRegistry ? "secure registry; "
: "insecure registry; ");
builder.append("Curator service access policy: ").append(access);
builder.append("; System ACLs: ").append(aclsToString(systemACLs));
builder.append("User: ").append(UgiInfo.fromCurrentUser());
builder.append("; Kerberos Realm: ").append(kerberosRealm);
builder.append(describeProperty(Environment.JAAS_CONF_KEY));
String sasl =
System.getProperty(PROP_ZK_ENABLE_SASL_CLIENT,
DEFAULT_ZK_ENABLE_SASL_CLIENT);
boolean saslEnabled = Boolean.parseBoolean(sasl);
builder.append(describeProperty(PROP_ZK_ENABLE_SASL_CLIENT,
DEFAULT_ZK_ENABLE_SASL_CLIENT));
if (saslEnabled) {
builder.append("; JAAS Client Identity")
.append("=")
.append(jaasClientIdentity)
.append("; ");
builder.append(KEY_REGISTRY_CLIENT_JAAS_CONTEXT)
.append("=")
.append(jaasClientContext)
.append("; ");
builder.append(describeProperty(PROP_ZK_SASL_CLIENT_USERNAME));
builder.append(describeProperty(PROP_ZK_SASL_CLIENT_CONTEXT));
}
builder.append(describeProperty(PROP_ZK_ALLOW_FAILED_SASL_CLIENTS,
"(undefined but defaults to true)"));
builder.append(describeProperty(
PROP_ZK_SERVER_MAINTAIN_CONNECTION_DESPITE_SASL_FAILURE));
return builder.toString();
}
private static String describeProperty(String name) {
return describeProperty(name, "(undefined)");
}
private static String describeProperty(String name, String def) {
return "; " + name + "=" + System.getProperty(name, def);
}
/**
* Get the default kerberos realm —returning "" if there
* is no realm or other problem
* @return the default realm of the system if it
* could be determined
*/
public static String getDefaultRealmInJVM() {
try {
return KerberosUtil.getDefaultRealm();
// JDK7
} catch (ClassNotFoundException ignored) {
// ignored
} catch (NoSuchMethodException ignored) {
// ignored
} catch (IllegalAccessException ignored) {
// ignored
} catch (InvocationTargetException ignored) {
// ignored
}
return "";
}
/**
* Create an ACL For a user.
* @param ugi User identity
* @return the ACL For the specified user. Ifthe username doesn't end
* in "@" then the realm is added
*/
public ACL createACLForUser(UserGroupInformation ugi, int perms) {
if (LOG.isDebugEnabled()) {
LOG.debug("Creating ACL For ", new UgiInfo(ugi));
}
if (!secureRegistry) {
return ALL_READWRITE_ACCESS;
} else {
return createACLfromUsername(ugi.getUserName(), perms);
}
}
/**
* Given a user name (short or long), create a SASL ACL
* @param username user name; if it doesn't contain an "@" symbol, the
* service's kerberos realm is added
* @param perms permissions
* @return an ACL for the user
*/
public ACL createACLfromUsername(String username, int perms) {
if (!username.contains("@")) {
username = username + "@" + kerberosRealm;
if (LOG.isDebugEnabled()) {
LOG.debug("Appending kerberos realm to make {}", username);
}
}
return new ACL(perms, new Id(SCHEME_SASL, username));
}
/**
* On demand string-ifier for UGI with extra details
*/
public static class UgiInfo {
public static UgiInfo fromCurrentUser() {
try {
return new UgiInfo(UserGroupInformation.getCurrentUser());
} catch (IOException e) {
LOG.info("Failed to get current user {}", e, e);
return new UgiInfo(null);
}
}
private final UserGroupInformation ugi;
public UgiInfo(UserGroupInformation ugi) {
this.ugi = ugi;
}
@Override
public String toString() {
if (ugi==null) {
return "(null ugi)";
}
StringBuilder builder = new StringBuilder();
builder.append(ugi.getUserName()).append(": ");
builder.append(ugi.toString());
builder.append(" hasKerberosCredentials=").append(
ugi.hasKerberosCredentials());
builder.append(" isFromKeytab=").append(ugi.isFromKeytab());
builder.append(" kerberos is enabled in Hadoop =").append(UserGroupInformation.isSecurityEnabled());
return builder.toString();
}
}
/**
* on-demand stringifier for a list of ACLs
*/
public static class AclListInfo {
public final List<ACL> acls;
public AclListInfo(List<ACL> acls) {
this.acls = acls;
}
@Override
public String toString() {
return aclsToString(acls);
}
}
}
| apache-2.0 |
comdexxsolutionsllc/dcas-laravel55 | config/sitemap.php | 1547 | <?php
use GuzzleHttp\RequestOptions;
use Spatie\Sitemap\Crawler\Profile;
return [
/*
* These options will be passed to GuzzleHttp\Client when it is created.
* For in-depth information on all options see the Guzzle docs:
*
* http://docs.guzzlephp.org/en/stable/request-options.html
*/
'guzzle_options' => [
/*
* Whether or not cookies are used in a request.
*/
RequestOptions::COOKIES => true,
/*
* The number of seconds to wait while trying to connect to a server.
* Use 0 to wait indefinitely.
*/
RequestOptions::CONNECT_TIMEOUT => 10,
/*
* The timeout of the request in seconds. Use 0 to wait indefinitely.
*/
RequestOptions::TIMEOUT => 10,
/*
* Describes the redirect behavior of a request.
*/
RequestOptions::ALLOW_REDIRECTS => false,
],
/*
* The sitemap generator can execute JavaScript on each page so it will
* discover links that are generated by your JS scripts. This feature
* is powered by headless Chrome.
*/
'execute_javascript' => false,
/*
* The package will make an educated guess as to where Google Chrome is installed.
* You can also manually pass it's location here.
*/
'chrome_binary_path' => null,
/*
* The sitemap generator uses a CrawlProfile implementation to determine
* which urls should be crawled for the sitemap.
*/
'crawl_profile' => Profile::class,
];
| apache-2.0 |
ufcpp/UfcppSample | Demo/2017/Ạṇạḷỵẓẹṛ/Ạṇạḷỵẓẹṛ/Ạṇạḷỵẓẹṛ.Test/ẠṇạḷỵẓẹṛUnitTests.cs | 735 | using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CodeFixes;
using Microsoft.CodeAnalysis.Diagnostics;
using System;
using TestHelper;
using Xunit;
using Ạṇạḷỵẓẹṛ;
namespace Ạṇạḷỵẓẹṛ.Test
{
public class ẠṇạḷỵẓẹṛUnitTests : ConventionCodeFixVerifier
{
[Fact]
public void EmptySource() => VerifyCSharpByConvention();
[Fact]
public void LowercaseLetters() => VerifyCSharpByConvention();
protected override CodeFixProvider GetCSharpCodeFixProvider() => new ẠṇạḷỵẓẹṛCodeFixProvider();
protected override DiagnosticAnalyzer GetCSharpDiagnosticAnalyzer() => new ẠṇạḷỵẓẹṛAnalyzer();
}
}
| apache-2.0 |