hexsha
stringlengths 40
40
| size
int64 8
1.04M
| content
stringlengths 8
1.04M
| avg_line_length
float64 2.24
100
| max_line_length
int64 4
1k
| alphanum_fraction
float64 0.25
0.97
|
|---|---|---|---|---|---|
4ee1f6c74710570544d6f49fcecb908376b746c3
| 5,929
|
// Copyright (C) 2007 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.caja.parser.html;
import com.google.caja.lexer.FilePosition;
import com.google.caja.reporting.MessagePart;
import com.google.caja.reporting.MessageQueue;
import com.google.caja.reporting.MessageType;
import com.google.common.collect.Lists;
import java.util.List;
import org.w3c.dom.Document;
import org.w3c.dom.DocumentFragment;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
/**
* Abstract base class for OpenElementStack implementations that maintains the
* open element stack as the tree is built around it.
*
* @author mikesamuel@gmail.com
*/
abstract class AbstractElementStack implements OpenElementStack {
protected static final boolean DEBUG = false;
protected final Document doc;
protected final boolean needsDebugData;
private final DocumentFragment rootElement;
/** A list of open nodes. */
private final List<OpenNode> openNodes = Lists.newArrayList();
/**
* @param needsDebugData see {@link DomParser#setNeedsDebugData(boolean)}
*/
AbstractElementStack(Document doc, Namespaces ns, boolean needsDebugData) {
this.doc = doc;
this.needsDebugData = needsDebugData;
this.rootElement = doc.createDocumentFragment();
this.openNodes.add(new OpenNode(rootElement, ns, null));
}
public final Document getDocument() { return doc; }
/** {@inheritDoc} */
public final DocumentFragment getRootElement() {
return rootElement;
}
/** {@inheritDoc} */
public void open(boolean fragment) { /* noop */ }
/** The current element — according to HTML5 the stack grows down. */
protected final OpenNode getBottom() {
return openNodes.get(openNodes.size() - 1);
}
/** The count of open elements. */
protected final int getNOpenElements() {
return openNodes.size();
}
/** The index-th open element counting from 0 at the root. */
protected final Element getElement(int index) {
assert index > 0 : "" + index;
return (Element) openNodes.get(index).n;
}
/**
* Adds an element to the element stack, puts it on the previous head's
* child list, and updates file positions.
*/
protected final void push(Element el, Namespaces ns, String qname) {
if (DEBUG) System.err.println("push(" + el + ")");
Node parent = getBottom().n;
openNodes.add(new OpenNode(el, ns, qname));
doAppend(el, parent);
}
/**
* Append a node to the DOM tree as the child of the bottom.
* This may be overridden by subclasses if they wish to add at a different
* location.
*/
@SuppressWarnings("static-method")
protected void doAppend(Node el, Node parent) {
parent.appendChild(el);
}
/**
* Pop the N bottom levels of the open element stack.
* @param endPos the position at which the popped elements should be
* considered to end.
*/
protected final void popN(int n, FilePosition endPos) {
if (DEBUG) System.err.println("popN(" + n + ", " + endPos + ")");
n = Math.min(n, openNodes.size() - 1);
while (--n >= 0) {
Node node = openNodes.remove(openNodes.size() - 1).n;
if (needsDebugData) {
Nodes.setFilePositionFor(
node, FilePosition.span(Nodes.getFilePositionFor(node), endPos));
if (openNodes.size() == 1) {
FilePosition rootPos = Nodes.getFilePositionFor(rootElement);
if (rootPos.endCharInFile() <= 1) {
rootPos = Nodes.getFilePositionFor(rootElement.getFirstChild());
}
if (rootPos.startCharInFile() <= endPos.startCharInFile()) {
Nodes.setFilePositionFor(
rootElement, FilePosition.span(rootPos, endPos));
}
}
}
}
}
/** Strip ignorable whitespace nodes from the root. */
protected void stripIgnorableText() {
if (rootElement.getFirstChild() == null) { return; }
// No need to loop because processText normalizes.
Node firstChild = rootElement.getFirstChild();
if (isIgnorableTextNode(firstChild)) {
rootElement.removeChild(firstChild);
if (rootElement.getFirstChild() == null) { return; }
}
// No need to loop because processText normalizes.
Node lastChild = rootElement.getLastChild();
if (isIgnorableTextNode(lastChild)) {
rootElement.removeChild(lastChild);
}
}
/**
* @see <a href="http://www.w3.org/TR/REC-xml/#sec-white-space">ignorable
* white space</a>
*/
private static boolean isIgnorableTextNode(Node t) {
// TODO(mikesamuel): check against XML&HTML definitions of whitespace.
// Note: CDATA and ESCAPED text purposefully not treated as whitespace.
return t.getNodeType() == Node.TEXT_NODE
&& "".equals(t.getNodeValue().trim());
}
static Namespaces unknownNamespace(
FilePosition pos, Namespaces ns, String qname, MessageQueue mq) {
int colon = qname.indexOf(':');
String prefix = colon >= 0 ? qname.substring(0, colon) : "";
mq.addMessage(
MessageType.NO_SUCH_NAMESPACE, pos, MessagePart.Factory.valueOf(prefix),
MessagePart.Factory.valueOf(qname));
return new Namespaces(
ns, prefix, "unknown:///" + prefix);
}
static class OpenNode {
final Node n;
final Namespaces ns;
final String qname;
OpenNode(Node n, Namespaces ns, String qname) {
this.n = n;
this.ns = ns;
this.qname = qname;
}
}
}
| 32.938889
| 80
| 0.677855
|
3651f8c0cd1d8f9242d431cb4d2b270304b4fe70
| 1,763
|
package com.javayh.mybatis.controller;
import com.javayh.mybatis.dao.MybatisDao;
import com.javayh.mybatis.vo.LogisticsVO;
import com.zaxxer.hikari.HikariDataSource;
import lombok.SneakyThrows;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.mapping.Environment;
import org.apache.ibatis.session.Configuration;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.apache.ibatis.transaction.TransactionFactory;
import org.apache.ibatis.transaction.jdbc.JdbcTransactionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import javax.sql.DataSource;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
/**
* <p>
*
* </p>
*
* @author Dylan
* @version 1.0.0
* @since 2021-03-08
*/
@RestController
@RequestMapping(value = "/mybatis/")
public class MybatisController {
@Autowired
private MybatisDao dao;
@SneakyThrows
@GetMapping(value = "name")
public List<?> findAllName(){
/* String resource = "mybatis-config.xml";
InputStream inputStream = Resources.getResourceAsStream(resource);
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
SqlSession sqlSession = sqlSessionFactory.openSession();
Object o = sqlSession.selectOne("");*/
return dao.findAllName();
}
@GetMapping(value = "all")
public List<?> findAll(){
return dao.findListAndIf(new ArrayList<>());
}
}
| 30.396552
| 96
| 0.757799
|
284928fc57c096e2ed8444f4eb07cddce12a91f2
| 591
|
package org.mintleaf.modules.video.dao;
import org.beetl.sql.core.annotatoin.Param;
import org.beetl.sql.core.annotatoin.SqlResource;
import org.beetl.sql.core.mapper.BaseMapper;
import org.mintleaf.modules.video.entity.Comment;
import org.springframework.stereotype.Component;
import java.util.List;
@Component
@SqlResource("comment")
public interface CommentDao extends BaseMapper<Comment> {
/**
* 获得评论
* @return
*/
List<Comment> getComment();
/**
* 根据ID批量删除评论
* @param ids
* @return
*/
int deleteByIds(@Param("ids") String[] ids);
}
| 21.888889
| 57
| 0.698816
|
4c94394a9803adea880e6bb1d267275cf30688cf
| 2,655
|
/*
* Project Scelight
*
* Copyright (c) 2013 Andras Belicza <iczaaa@gmail.com>
*
* This software is the property of Andras Belicza.
* Copying, modifying, distributing, refactoring without the author's permission
* is prohibited and protected by Law.
*/
package hu.sltool.release;
import hu.scelightapi.XConsts;
import hu.scelightapi.r.XR;
import hu.sllauncher.bean.BuildInfoBean;
import java.io.BufferedWriter;
import java.io.FileOutputStream;
import java.nio.charset.Charset;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;
import java.util.Date;
import java.util.Properties;
import javax.xml.bind.JAXB;
/**
* Application which prepares building the next External Module API release.
*
* <p>
* Tasks it does:
* </p>
* <ul>
* <li>Increments the ext mod API build number.</li>
* <li>Creates the properties file used by the Ant build script.</li>
* </ul>
*
* @author Andras Belicza
*/
public class PrepNextExtModApiRelease {
/**
* @param args used to take arguments from the running environment; args[0] is the name of the ext-mod-api-build.properties file to generate for Ant
* @throws Exception if any error occurs
*/
public static void main( final String[] args ) throws Exception {
final String BUILD_INFO_FILE = "/hu/scelightapi/r/bean/build-info.xml";
// Read current app-libs build info
final BuildInfoBean b = JAXB.unmarshal( XR.class.getResource( BUILD_INFO_FILE ), BuildInfoBean.class );
System.out.println( "Current: " + b );
// Increment build
b.setBuild( b.getBuildNumber() + 1 );
b.setDate( new Date() );
System.out.println( "New: " + b );
// Archive to ext-mod-api-build-history.txt and save new build info
// to both src-app and bin-app folders (so no refresh is required in Eclipse)
try ( final BufferedWriter out = Files.newBufferedWriter( Paths.get( "dev-data", "ext-mod-api-build-history.txt" ), Charset.forName( "UTF-8" ),
StandardOpenOption.APPEND ) ) {
out.write( b.getBuildNumber() + " " + b.getDate() );
out.newLine();
}
JAXB.marshal( b, Paths.get( "src-ext-mod-api", BUILD_INFO_FILE ).toFile() );
JAXB.marshal( b, Paths.get( "bin-ext-mod-api", BUILD_INFO_FILE ).toFile() );
// Create properties file for Ant
final Properties p = new Properties();
p.setProperty( "extModApiVer", XConsts.EXT_MOD_API_VERSION.toString() );
p.setProperty( "extModApiBuildNumber", b.getBuildNumber().toString() );
try ( final FileOutputStream out = new FileOutputStream( args[ 0 ] ) ) {
p.store( out, null );
}
}
}
| 34.038462
| 150
| 0.685499
|
459c416462020655fc91d5456ac8229d2d5d0442
| 12,334
|
/**
* Copyright (C) 2016-2017 Salvatore Virga - salvo.virga@tum.de, Marco Esposito - marco.esposito@tum.de
* Technische Universität München
* Chair for Computer Aided Medical Procedures and Augmented Reality
* Fakultät für Informatik / I16, Boltzmannstraße 3, 85748 Garching bei München, Germany
* http://campar.in.tum.de
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
* INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
* IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY,
* OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA,
* OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
* THE POSSIBILITY OF SUCH DAMAGE.
*/
package de.tum.in.camp.kuka.ros.app;
import java.net.URI;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import org.ros.address.BindAddress;
import org.ros.node.DefaultNodeMainExecutor;
import org.ros.node.NodeConfiguration;
import org.ros.node.NodeMainExecutor;
import org.ros.time.NtpTimeProvider;
import com.kuka.connectivity.fastRobotInterface.FRIConfiguration;
import com.kuka.connectivity.fastRobotInterface.FRIJointOverlay;
import com.kuka.connectivity.fastRobotInterface.FRISession;
import com.kuka.common.ThreadUtil;
import com.kuka.connectivity.motionModel.smartServo.SmartServo;
import com.kuka.connectivity.motionModel.smartServoLIN.SmartServoLIN;
import com.kuka.roboticsAPI.applicationModel.RoboticsAPIApplication;
import com.kuka.roboticsAPI.applicationModel.RoboticsAPIApplicationState;
import com.kuka.roboticsAPI.deviceModel.LBR;
import com.kuka.roboticsAPI.geometricModel.ObjectFrame;
import com.kuka.roboticsAPI.geometricModel.Tool;
import com.kuka.roboticsAPI.uiModel.userKeys.IUserKey;
import com.kuka.roboticsAPI.uiModel.userKeys.IUserKeyBar;
import com.kuka.roboticsAPI.uiModel.userKeys.IUserKeyListener;
import de.tum.in.camp.kuka.ros.ControlModeHandler;
import de.tum.in.camp.kuka.ros.GoalReachedEventListener;
import de.tum.in.camp.kuka.ros.Configuration;
import de.tum.in.camp.kuka.ros.iiwaPublisher;
import de.tum.in.camp.kuka.ros.Logger;
/*
* Base application for all ROS-Sunrise applications.
* Manages lifetime of ROS Nodes, NTP synchronization, loading the configuration from the ROS parameter server,
* attaching the Sunrise tool specified in the configuration, and publishing the current state of the robot.
*/
public abstract class ROSBaseApplication extends RoboticsAPIApplication {
protected LBR robot;
protected Tool tool;
private String _clientName;
protected String toolFrameID;
protected static final String toolFrameIDSuffix = "_link_ee";
protected ObjectFrame toolFrame;
protected SmartServo motion;
protected SmartServoLIN linearMotion;
protected ControlModeHandler controlModeHandler;
protected GoalReachedEventListener handler;
protected boolean initSuccessful;
protected boolean debug;
protected boolean running;
protected boolean cleanedup = false;
protected iiwaPublisher publisher;
protected Configuration configuration;
// ROS Configuration and Node execution objects.
protected NodeConfiguration nodeConfPublisher;
protected NodeConfiguration nodeConfConfiguration;
protected NodeMainExecutor nodeMainExecutor;
// Configurable Toolbars.
protected List<IUserKeyBar> generalKeyBars = new ArrayList<IUserKeyBar>();
protected List<IUserKey> generalKeys = new ArrayList<IUserKey>();
protected List<IUserKeyListener> generalKeyLists = new ArrayList<IUserKeyListener>();
protected abstract void configureNodes(URI uri);
protected abstract void addNodesToExecutor(NodeMainExecutor nodeExecutor);
protected abstract void initializeApp();
protected abstract void beforeControlLoop();
protected abstract void controlLoop();
/*
* SmartServo control makes the control loop very slow
* These variables are used to run them every *decimation* times,
* In order to balance the load, they alternate at *decimationCounter* % *decimation* == 0 and
* *decimationCounter* % *decimation* == *decimation* / 2
*/
// TODO : in config.txt or processData
protected int decimationCounter = 0;
protected int controlDecimation = 1;
public void initialize() {
Logger.setSunriseLogger(getLogger());
robot = getContext().getDeviceFromType(LBR.class);
// Standard configuration.
configuration = new Configuration();
publisher = new iiwaPublisher(configuration.getRobotName(), configuration);
// ROS initialization.
try {
URI uri = new URI(configuration.getMasterURI());
nodeConfConfiguration = NodeConfiguration.newPublic(configuration.getRobotIp());
nodeConfConfiguration.setTimeProvider(configuration.getTimeProvider());
nodeConfConfiguration.setNodeName(configuration.getRobotName() + "/iiwa_configuration");
nodeConfConfiguration.setMasterUri(uri);
nodeConfConfiguration.setTcpRosBindAddress(BindAddress.newPublic(30000));
nodeConfConfiguration.setXmlRpcBindAddress(BindAddress.newPublic(30001));
nodeConfPublisher = NodeConfiguration.newPublic(configuration.getRobotIp());
nodeConfPublisher.setTimeProvider(configuration.getTimeProvider());
nodeConfPublisher.setNodeName(configuration.getRobotName() + "/iiwa_publisher");
nodeConfPublisher.setMasterUri(uri);
nodeConfPublisher.setTcpRosBindAddress(BindAddress.newPublic(30002));
nodeConfPublisher.setXmlRpcBindAddress(BindAddress.newPublic(30003));
// Additional configuration needed in subclasses.
configureNodes(uri);
}
catch (Exception e) {
if (debug)
Logger.info("Node Configuration failed. " + "Please check the ROS master IP in the Sunrise configuration.");
Logger.info(e.toString());
return;
}
try {
// Start the Publisher node with the set up configuration.
nodeMainExecutor = DefaultNodeMainExecutor.newDefault();
nodeMainExecutor.execute(publisher, nodeConfPublisher);
nodeMainExecutor.execute(configuration, nodeConfConfiguration);
// Additional Nodes from subclasses.
addNodesToExecutor(nodeMainExecutor);
if (debug)
Logger.info("ROS Node Executor initialized.");
}
catch(Exception e) {
if (debug)
Logger.info("ROS Node Executor initialization failed.");
Logger.info(e.toString());
return;
}
// END of ROS initialization.
// Additional initialization from subclasses.
initializeApp();
initSuccessful = true; // We cannot throw here.
}
public void run() {
if (!initSuccessful) {
throw new RuntimeException("Could not init the RoboticApplication successfully");
}
try {
Logger.info("Waiting for ROS Master to connect... ");
configuration.waitForInitialization();
Logger.info("ROS Master is connected!");
} catch (InterruptedException e1) {
e1.printStackTrace();
return;
}
Logger.info("Using time provider: " + configuration.getTimeProvider().getClass().getSimpleName());
// Configurable toolbars to publish events on topics.
configuration.setupToolbars(getApplicationUI(), publisher, generalKeys, generalKeyLists, generalKeyBars);
// Tool to attach, robot's flange will be used if no tool has been defined.
String toolFromConfig = configuration.getToolName();
if (toolFromConfig != "") {
Logger.info("Attaching tool " + toolFromConfig);
tool = (Tool)getApplicationData().createFromTemplate(toolFromConfig);
tool.attachTo(robot.getFlange());
toolFrameID = toolFromConfig + toolFrameIDSuffix;
toolFrame = tool.getFrame("/" + toolFrameID);
} else {
Logger.info("No tool attached. Using flange.");
toolFrameID = configuration.getRobotName() + toolFrameIDSuffix;
toolFrame = robot.getFlange();
}
controlModeHandler = new ControlModeHandler(robot, tool, toolFrame, publisher, configuration);
motion = controlModeHandler.createSmartServoMotion();
// Publish joint state?
publisher.setPublishJointStates(configuration.getPublishJointStates());
// Initialize motion.
toolFrame.moveAsync(motion);
// Hook the GoalReachedEventHandler
motion.getRuntime().setGoalReachedEventHandler(handler);
if (configuration.getTimeProvider() instanceof org.ros.time.NtpTimeProvider) {
((NtpTimeProvider) configuration.getTimeProvider()).startPeriodicUpdates(100, TimeUnit.MILLISECONDS); // TODO: update time as param
}
// Run what is needed before the control loop in the subclasses.
beforeControlLoop();
running = true;
// configure and start FRI session
FRIConfiguration friConfiguration = FRIConfiguration.createRemoteConfiguration(robot, _clientName);
friConfiguration.setSendPeriodMilliSec(5);
friConfiguration.setReceiveMultiplier(1);
getLogger().info("Creating FRI connection to " + friConfiguration.getHostName());
getLogger().info("SendPeriod: " + friConfiguration.getSendPeriodMilliSec() + "ms |"
+ " ReceiveMultiplier: " + friConfiguration.getReceiveMultiplier());
FRISession friSession = new FRISession(friConfiguration);
FRIJointOverlay jointOverlay = new FRIJointOverlay(friSession);
// wait until FRI session is ready to switch to command mode
try
{
friSession.await(10, TimeUnit.SECONDS);
}
catch (final TimeoutException e)
{
getLogger().error(e.getLocalizedMessage());
friSession.close();
return;
}
getLogger().info("FRI connection established.");
// The run loop
Logger.info("Starting the ROS control loop...");
try {
while(running) {
decimationCounter++;
// This will publish the current robot state on the various ROS topics.
publisher.publishCurrentState(robot, motion, toolFrame);
if ((decimationCounter % controlDecimation) == 0)
controlLoop(); // Perform control loop specified by subclass
}
}
catch (Exception e) {
Logger.info("ROS control loop aborted. " + e.toString());
} finally {
// done
friSession.close();
Logger.info("ROS control Ending Procedures.");
cleanedup = cleanup();
Logger.info("ROS control loop has ended. Application terminated.");
}
}
@Override
public void dispose() {
Logger.info("Dispose Application");
configuration.cleanup();
running = false;
int cnt = 100;
while( !cleanedup ){
ThreadUtil.milliSleep(100);
cnt = cnt -1;
if( cnt < 0 )
{
Logger.error("Dispose failed due the impossibility to stop the control loop");
Logger.error("Try to force cleanup");
cleanedup = cleanup();
}
}
super.dispose();
}
@Override
public void onApplicationStateChanged(RoboticsAPIApplicationState state) {
if (state == RoboticsAPIApplicationState.STOPPING) {
running = false;
}
super.onApplicationStateChanged(state);
};
boolean cleanup() {
running = false;
if (nodeMainExecutor != null) {
Logger.info("Stopping ROS nodes");
nodeMainExecutor.shutdown();
Logger.info("Shutdown Scheduler");
nodeMainExecutor.getScheduledExecutorService().shutdownNow();
}
Logger.info("Stopped ROS nodes");
return true;
}
}
| 38.786164
| 209
| 0.736176
|
9f6d6f2c17238b27b6dbd3764de29ed437ee7f69
| 6,125
|
package de.marcermarc.farmworld.controller;
import de.marcermarc.farmworld.Messages;
import de.marcermarc.farmworld.Util;
import de.marcermarc.farmworld.models.WorldSettings;
import org.bukkit.*;
import org.bukkit.block.Block;
import org.bukkit.block.CommandBlock;
import org.bukkit.block.data.FaceAttachable;
import org.bukkit.block.data.type.Switch;
import org.bukkit.entity.Player;
import org.jetbrains.annotations.Nullable;
import java.io.File;
import java.io.IOException;
import java.time.ZonedDateTime;
import java.util.Map;
import java.util.Optional;
import java.util.logging.Level;
public class WorldController {
private final PluginController controller;
public WorldController(PluginController controller) {
this.controller = controller;
}
public void loadOrCreateFromConfig() {
for (Map.Entry<String, WorldSettings> entry : controller.getConfig().getWorldSettings().entrySet()) {
String worldName = entry.getKey();
WorldSettings settings = entry.getValue();
Optional<World> world = getFarmworld(worldName);
if (!world.isPresent()) {
create(worldName, controller.getConfig().getWorldSettings().get(worldName), null);
} else if (world.get().canGenerateStructures() != settings.isStructures()
|| world.get().getEnvironment() != settings.getEnvironment()) {
controller.getMain().getLogger().log(Level.WARNING, Messages.getWorldSettingsChanged(worldName));
}
}
// ToDo Delete unused worlds if possible
}
public boolean recreate(String name, @Nullable Player player) {
WorldSettings worldSettings = controller.getConfig().getWorldSettings().get(name);
worldSettings.setLastRecreation(ZonedDateTime.now());
controller.getConfig().addOrUpdateWorld(name, worldSettings);
return delete(name, worldSettings)
&& create(name, worldSettings, player);
}
public boolean deleteAndRemoveFromConfig(String name) {
WorldSettings worldSettings = controller.getConfig().getWorldSettings().get(name);
boolean success = delete(name, worldSettings);
controller.getConfig().removeWorld(name);
return success;
}
public boolean delete(String name, WorldSettings settings) {
Optional<World> world = getFarmworld(name);
if (!world.isPresent()) {
return false;
}
File worldFolder = world.get().getWorldFolder();
for (Player player : world.get().getPlayers()) {
controller.getPlayerController().returnPlayer(player);
player.sendMessage(Messages.getWorldDelete());
}
controller.getPlayerData().getAll().stream()
.filter(x -> x.getWorld().equals(name))
.forEach(x -> {
x.setHasToReturn(true);
controller.getPlayerData().setData(x);
});
Bukkit.unloadWorld(world.get(), false);
try {
Util.deleteRecursively(worldFolder.toPath());
return true;
} catch (IOException e) {
controller.getMain().getLogger().log(Level.SEVERE, Messages.getWorldDeleteFailed(name), e);
return false;
}
}
public boolean createAndSaveConfig(String name, WorldSettings settings, @Nullable Player player) {
boolean success = create(name, settings, player);
if (success) {
controller.getConfig().addOrUpdateWorld(name, settings);
}
return success;
}
public boolean create(String name, WorldSettings settings, @Nullable Player player) {
if (Bukkit.getWorld(name) != null) {
// world already exists
return true;
}
WorldCreator creator = new WorldCreator(name);
creator.environment(settings.getEnvironment());
creator.generateStructures(settings.isStructures());
creator.type(settings.getType());
World world = Bukkit.createWorld(creator);
if (world == null) {
controller.getMain().getLogger().log(Level.SEVERE, Messages.getWorldCreationFailedConsole(name));
if (player != null) {
player.sendMessage(Messages.getWorldCreationFailedPlayer(name));
}
return false;
}
createReturnPossibility(world);
Location spawnLoc = Util.getFarmWorldSpawnLocation(world);
world.setSpawnLocation(spawnLoc);
if (settings.getEnvironment().equals(World.Environment.NETHER) && spawnLoc.getY() >= 128) {
String warnString = String.format("The spawnloaction of %s is invalid.", world.getName());
Bukkit.getLogger().log(Level.WARNING, warnString);
if (player != null) player.sendMessage(Messages.getMessagePrefix() + warnString);
}
world.getWorldBorder().setSize(settings.getWorldsize());
world.setPVP(false); // ToDo configurable
return true;
}
private void createReturnPossibility(World world) {
world.loadChunk(0, 0, true);
int y = Util.getSpawnY(world, 0, 0);
Block spawnBlock = world.getBlockAt(0, y, 0);
spawnBlock.setType(Material.COMMAND_BLOCK, false);
CommandBlock spawnBlockState = (CommandBlock) spawnBlock.getState();
spawnBlockState.setCommand("marcerfarmworld return");
spawnBlockState.update(false, false);
Block button = world.getBlockAt(0, y + 1, 0);
button.setType(Material.STONE_BUTTON, false);
Switch buttonFace = (Switch) button.getBlockData();
buttonFace.setAttachedFace(FaceAttachable.AttachedFace.FLOOR);
button.setBlockData(buttonFace, false);
world.unloadChunkRequest(0,0);
}
private Optional<World> getFarmworld(String name) {
return Bukkit.getWorlds().stream()
.filter(x -> x.getName().equals(name))
.findAny();
}
private boolean isWorldNew(World world) {
return !world.isChunkGenerated(0, 0);
}
}
| 33.839779
| 113
| 0.645551
|
ee92dd5dc879f93df9c76a30f5ba11d2ab1de819
| 2,149
|
package com.pact.healthapp.components.healthreport;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import com.pact.healthapp.R;
import com.pact.healthapp.components.login.LoginActivity;
import com.pact.healthapp.http.ServiceEngin;
import com.pact.healthapp.universal.BaseFragmentActivity;
import com.pact.healthapp.utils.SharedPreferenceUtils;
/**
* 体检报告、健康报告
*
* @author Administrator
*/
public class HealthReportActivity extends BaseFragmentActivity {
private SharedPreferenceUtils sp = new SharedPreferenceUtils();
private String TYPE;
@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContenierView(1);
myApplication.addActivity(this);
btn_right.setVisibility(View.GONE);
TYPE = getIntent().getStringExtra("TYPE");
if (TYPE.equals("0")) {
setTitle("体检报告");
} else if (TYPE.equals("1")) {
setTitle("评估报告");
}
setBackType(0);
if (!sp.getLoginState(context)) {
Intent intent = new Intent(context, LoginActivity.class);
startActivityForResult(intent, ServiceEngin.REQUEST_LOGIN);
return;
}
mFragmentManager
.beginTransaction()
.replace(R.id.login_fl_continer,
new HealthReportListFragment(TYPE))
.addToBackStack("HealthReportListFragment").commit();
}
@Override
protected void onActivityResult(int arg0, int arg1, Intent arg2) {
// TODO Auto-generated method stub
super.onActivityResult(arg0, arg1, arg2);
if (arg0 == ServiceEngin.REQUEST_LOGIN &&arg1 == Activity.RESULT_CANCELED) {
finish();
} else {
mFragmentManager
.beginTransaction()
.replace(R.id.login_fl_continer,
new HealthReportListFragment(TYPE))
.addToBackStack("HealthReportListFragment").commit();
}
}
}
| 33.578125
| 84
| 0.638436
|
08a6c817fa93cbe879aa8c6746fdae64d546d2c1
| 1,994
|
/*
* Copyright 2009-2014 PrimeTek.
*
* 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.primefaces.barcelona.view.misc;
import javax.annotation.PostConstruct;
import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.context.FacesContext;
import org.primefaces.context.RequestContext;
import org.primefaces.barcelona.domain.User;
@ManagedBean
public class RequestContextView {
private User user;
@PostConstruct
public void init() {
user = new User();
if(!FacesContext.getCurrentInstance().isPostback()) {
RequestContext.getCurrentInstance().execute("alert('This onload script is added from backing bean.')");
}
}
public User getUser() {
return user;
}
public void setUser(User user) {
this.user = user;
}
public void save() {
RequestContext context = RequestContext.getCurrentInstance();
context.addCallbackParam("saved", true); //basic parameter
context.addCallbackParam("user", user); //pojo as json
//execute javascript oncomplete
context.execute("PrimeFaces.info('Hello from the Backing Bean');");
//update panel
context.update("form:panel");
//scroll to panel
context.scrollTo("form:panel");
//add facesmessage
FacesContext.getCurrentInstance().addMessage(null, new FacesMessage("Success", "Success"));
}
}
| 30.676923
| 115
| 0.685055
|
be28310248bb8fe1c229548b88f9b2e855ad0658
| 673
|
package ru.otus.atm.model;
public class Nominal implements Bill {
private final long nominal;
public Nominal(long nominal) {
this.nominal = nominal;
}
@Override
public long getOrdinal() {
return nominal;
}
@Override
public long calculate(long amount) {
return amount * getOrdinal();
}
@Override
public int hashCode() {
return (int) getOrdinal();
}
@Override
public boolean equals(Object obj) {
return nominal == ((Nominal) obj).getOrdinal();
}
@Override
public int compareTo(Object o) {
return (int) (getOrdinal() - ((Bill) o).getOrdinal());
}
}
| 19.228571
| 62
| 0.591382
|
a60eb5d47b6588a9584fbee263060809f7e86e84
| 2,406
|
/*
* Copyright (C) 2020 Peter Paul Bakker, Stokpop Software Solutions
*
* 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 nl.stokpop.lograter.counter;
import nl.stokpop.lograter.store.TimeMeasurementStore;
import nl.stokpop.lograter.util.time.TimePeriod;
/**
* A request counter that cannot be changed.
*/
public class RequestCounterReadOnly extends RequestCounter {
/**
* Create new (in memory!) counter based on two request counters for the given time period.
* The returned RequestCounter is read only.
*/
public RequestCounterReadOnly(
final RequestCounter requestCounterOne,
final RequestCounter requestCounterTwo,
final TimePeriod timePeriod) {
super(requestCounterOne, requestCounterTwo, timePeriod);
}
/**
* Create new (in memory!) counter based on two request counters for the given time period.
* The returned RequestCounter is read only.
*/
public RequestCounterReadOnly(
final String counterKey,
final RequestCounter requestCounterOne,
final RequestCounter requestCounterTwo,
final TimePeriod timePeriod) {
super(counterKey, requestCounterOne, requestCounterTwo, timePeriod);
}
public RequestCounterReadOnly(final String counterKey, final TimeMeasurementStore timeMeasurementStore) {
super(counterKey, timeMeasurementStore);
}
protected RequestCounterReadOnly(final String counterKey, final TimeMeasurementStore timeSlicedTimeMeasurements, final TimePeriod timePeriod) {
super(counterKey, timeSlicedTimeMeasurements, timePeriod);
}
public RequestCounterReadOnly(final String uniqueCounterKey, final RequestCounter successCounter, final RequestCounter failureCounter) {
super(uniqueCounterKey, successCounter, failureCounter);
}
@Override
public void incRequests(final long timestamp, final int durationInMilliseconds) {
throw new UnsupportedOperationException("This request counter is read only.");
}
}
| 35.910448
| 144
| 0.783874
|
511829dba98af947cf829c935786cce5124e5746
| 2,026
|
package io.kokuwa.micronaut.logging.http.level;
import java.util.Optional;
import org.reactivestreams.Publisher;
import io.micronaut.context.annotation.Requires;
import io.micronaut.context.annotation.Value;
import io.micronaut.core.util.StringUtils;
import io.micronaut.http.HttpResponse;
import io.micronaut.http.MutableHttpRequest;
import io.micronaut.http.annotation.Filter;
import io.micronaut.http.context.ServerRequestContext;
import io.micronaut.http.filter.ClientFilterChain;
import io.micronaut.http.filter.HttpClientFilter;
/**
* Propagates log-level from server request to client.
*
* @author Stephan Schnabel
*/
@Requires(beans = LogLevelServerFilter.class)
@Requires(property = LogLevelClientFilter.PREFIX + ".enabled", notEquals = StringUtils.FALSE)
@Filter("${" + LogLevelClientFilter.PREFIX + ".path:/**}")
public class LogLevelClientFilter implements HttpClientFilter {
public static final String PREFIX = "logger.http.level.propagation";
public static final int DEFAULT_ORDER = HIGHEST_PRECEDENCE;
private final String serverHeader;
private final String propagationHeader;
private final int order;
public LogLevelClientFilter(
@Value("${" + LogLevelServerFilter.PREFIX + ".header}") Optional<String> serverHeader,
@Value("${" + PREFIX + ".header}") Optional<String> propagationHeader,
@Value("${" + PREFIX + ".order}") Optional<Integer> order) {
this.serverHeader = serverHeader.orElse(LogLevelServerFilter.DEFAULT_HEADER);
this.propagationHeader = propagationHeader.orElse(this.serverHeader);
this.order = order.orElse(DEFAULT_ORDER);
}
@Override
public int getOrder() {
return order;
}
@Override
public Publisher<? extends HttpResponse<?>> doFilter(MutableHttpRequest<?> targetRequest, ClientFilterChain chain) {
ServerRequestContext.currentRequest()
.flatMap(currentRequest -> currentRequest.getHeaders().getFirst(serverHeader))
.ifPresent(level -> targetRequest.getHeaders().add(propagationHeader, level));
return chain.proceed(targetRequest);
}
}
| 36.178571
| 117
| 0.780355
|
a6b1b61dea081c36908c24df60f60dbe4590d573
| 1,509
|
package de.uhd.ifi.se.decision.management.jira.git.gitclient;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import java.util.List;
import org.eclipse.jgit.lib.Ref;
import org.eclipse.jgit.revwalk.RevCommit;
import org.junit.Test;
import com.atlassian.jira.component.ComponentAccessor;
import com.atlassian.jira.issue.Issue;
public class TestGetFeatureBranchCommits extends TestSetUpGit {
@Test
public void testGetFeatureBranchCommitsByRef() {
Ref featureBranch = gitClient.getBranches("TEST-4.feature.branch").get(0);
List<RevCommit> commits = gitClient.getFeatureBranchCommits(featureBranch);
assertEquals(5, commits.size());
// oldest commits come first
assertTrue(commits.get(0).getCommitTime() < commits.get(1).getCommitTime());
}
@Test
public void testGetFeatureBranchCommitsByRefNull() {
List<RevCommit> commits = gitClient.getFeatureBranchCommits((Ref) null);
assertEquals(0, commits.size());
}
@Test
// TODO Only use one feature branch for unit testing
public void testGetFeatureBranchCommitsByJiraIssue() {
Issue issue = ComponentAccessor.getIssueManager().getIssueByCurrentKey("TEST-4");
assertEquals("TEST-4", issue.getKey());
List<RevCommit> commits = gitClient.getFeatureBranchCommits(issue);
assertEquals(5, commits.size());
}
@Test
public void testGetFeatureBranchCommitsByJiraIssueNull() {
List<RevCommit> commits = gitClient.getFeatureBranchCommits((Issue) null);
assertEquals(0, commits.size());
}
}
| 31.4375
| 83
| 0.779324
|
95ebf91de2984ac840c76660524ccaa6081994ca
| 2,069
|
/**
* Copyright © 2012-2016 <a href="https://github.com/thinkgem/jeesite">JeeSite</a> All rights reserved.
*/
package com.thinkgem.jeesite.modules.sys.entity;
import org.hibernate.validator.constraints.Length;
import java.util.Date;
import com.fasterxml.jackson.annotation.JsonFormat;
import com.thinkgem.jeesite.common.persistence.DataEntity;
/**
* 用户在线记录Entity
* @author ljk
* @version 2019-04-08
*/
public class SysUserOnlineLog extends DataEntity<SysUserOnlineLog> {
private static final long serialVersionUID = 1L;
private String loginName; // login_name
private long loginTime; // login_time
private long logoutTime; // logout_time
private Date upadteDate; // upadte_date
private Double onlineHours; // online_hours
private Date beginDate; // 开始日期
private Date endDate; // 结束日期
public SysUserOnlineLog() {
super();
}
public SysUserOnlineLog(String id){
super(id);
}
@Length(min=1, max=100, message="login_name长度必须介于 1 和 100 之间")
public String getLoginName() {
return loginName;
}
public void setLoginName(String loginName) {
this.loginName = loginName;
}
@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss")
public long getLoginTime() {
return loginTime;
}
public void setLoginTime(long loginTime) {
this.loginTime = loginTime;
}
@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss")
public long getLogoutTime() {
return logoutTime;
}
public void setLogoutTime(long logoutTime) {
this.logoutTime = logoutTime;
}
@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss")
public Date getUpadteDate() {
return upadteDate;
}
public void setUpadteDate(Date upadteDate) {
this.upadteDate = upadteDate;
}
public Double getOnlineHours() {
return onlineHours;
}
public void setOnlineHours(Double onlineHours) {
this.onlineHours = onlineHours;
}
public Date getBeginDate() {
return beginDate;
}
public void setBeginDate(Date beginDate) {
this.beginDate = beginDate;
}
public Date getEndDate() {
return endDate;
}
public void setEndDate(Date endDate) {
this.endDate = endDate;
}
}
| 21.329897
| 108
| 0.726921
|
d437c9f2397d50d271a20625d3626ed82f2777f6
| 1,137
|
package org.yggdrasil.node.network.messages.payloads;
import org.apache.commons.lang3.SerializationUtils;
import org.yggdrasil.node.network.messages.MessagePayload;
import javax.validation.constraints.NotNull;
/**
* The Ping Pong Message is used to communicate back and forth to see if a conneciton
* is alive between nodes.
*
* @since 0.0.10
* @author nathanielbunch
*/
public class PingPongMessage implements MessagePayload {
@NotNull
private final int nonce;
private PingPongMessage(Builder builder) {
this.nonce = builder.nonce;
}
public int getNonce() {
return nonce;
}
@Override
public byte[] getDataBytes() {
return SerializationUtils.serialize(nonce);
}
public static class Builder {
private int nonce;
private Builder(){}
public static Builder newBuilder() {
return new Builder();
}
public Builder setNonce(int nonce) {
this.nonce = nonce;
return this;
}
public PingPongMessage build() {
return new PingPongMessage(this);
}
}
}
| 21.055556
| 85
| 0.64292
|
d09a946906e73ff815af27739356af61c24411f9
| 228
|
package org.pricelessfestival.crossoff.server.service;
import org.hibernate.Session;
import java.util.function.Function;
/**
* Created by ivan on 5/12/18.
*/
public interface Transaction<R> extends Function<Session, R> {
}
| 19
| 62
| 0.758772
|
1aa79d4c260269dbc6dcd37276c5817e9e0400fb
| 2,106
|
/* Class11_Sub2_Sub37 - Decompiled by JODE
* Visit http://jode.sourceforge.net/
*/
final class Class11_Sub2_Sub37 extends Class11_Sub2 {
static int anInt9757 = -2;
static int anInt9758;
static int anInt9759;
static int anInt9760;
static int anInt9761;
static final void method3840(int i, boolean bool, int i_0_) {
try {
Class127.anInt1720 = -Class32.anInt441 + i_0_;
anInt9758++;
if (bool != true)
method3841(null, false, 61, 74);
Class11_Sub12.anInt5446 = i - Class32.anInt451;
} catch (RuntimeException runtimeexception) {
throw Class205.method1298(runtimeexception, ("gea.C(" + i + ','
+ bool + ',' + i_0_ + ')'));
}
}
static final int method3841(byte[] is, boolean bool, int i, int i_1_) {
try {
anInt9761++;
int i_2_ = -1;
if (bool != true)
anInt9757 = -63;
for (int i_3_ = i_1_; i > i_3_; i_3_++)
i_2_ = i_2_ >>> 8
^ (Class11_Sub30_Sub1.anIntArray8977[(is[i_3_] ^ i_2_) & 0xff]);
i_2_ ^= 0xffffffff;
return i_2_;
} catch (RuntimeException runtimeexception) {
throw Class205.method1298(runtimeexception, ("gea.E("
+ (is != null ? "{...}" : "null") + ',' + bool + ',' + i
+ ',' + i_1_ + ')'));
}
}
public Class11_Sub2_Sub37() {
super(0, true);
}
static final Class307[] method3842(int i) {
try {
anInt9760++;
if (i != 12686)
anInt9757 = -15;
return (new Class307[] { Class350.aClass307_4608,
Class376_Sub7.aClass307_7038, Class316.aClass307_4181 });
} catch (RuntimeException runtimeexception) {
throw Class205.method1298(runtimeexception, "gea.F(" + i + ')');
}
}
final int[] method2254(int i, boolean bool) {
try {
anInt9759++;
if (bool != true)
return null;
int[] is = ((Class11_Sub2) this).aClass105_5043.method693(i,
(byte) -42);
if (((Class105) ((Class11_Sub2) this).aClass105_5043).aBool1421)
Class311.method1899(is, 0, Class33_Sub2.anInt6696,
Class171.anIntArray2199[i]);
return is;
} catch (RuntimeException runtimeexception) {
throw Class205.method1298(runtimeexception, "gea.A(" + i + ','
+ bool + ')');
}
}
}
| 27.710526
| 72
| 0.635328
|
2f261dc37d90c5d89a7d2d0687a736483cc43090
| 1,511
|
/**
* Copyright (C) 2012 Red Hat, Inc. and/or its affiliates.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* 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.jbpm.formModeler.service.bb.mvc.taglib.factory;
import org.jbpm.formModeler.service.bb.mvc.components.HandlerMarkupGenerator;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.servlet.jsp.JspTagException;
public class HandlerTag extends GenericFactoryTag {
private static transient Logger log = LoggerFactory.getLogger(HandlerTag.class);
public int doEndTag() throws JspTagException {
HandlerMarkupGenerator markupGenerator = HandlerMarkupGenerator.lookup();
String textToWrite = markupGenerator.getMarkup(getBean(), getAction());
try {
pageContext.getOut().print(textToWrite);
} catch (java.io.IOException ex) {
log.error("Error rendering tag: ", ex);
}
return EVAL_PAGE;
}
public int doStartTag() throws JspTagException {
return SKIP_BODY;
}
}
| 35.139535
| 84
| 0.720053
|
98546513c728df57ac4425cb8444436915f8f1e4
| 1,946
|
package com.thinkerwolf.hantis.cache;
/**
* 缓存键值
*
* @author wukai
*
*/
public class CacheKey {
private static final int PRIME = 37;
private static final int INITIAL_VALUE = 17;
private int iPrime;
private int hashCode;
public CacheKey() {
this.iPrime = PRIME;
this.hashCode = INITIAL_VALUE;
}
public CacheKey append(Object obj) {
if (obj == null) {
hashCode *= iPrime;
} else {
hashCode = hashCode * iPrime + obj.hashCode();
}
return this;
}
public CacheKey append(byte[] arrays) {
for (byte array : arrays) {
append(array);
}
return this;
}
public CacheKey append(short[] arrays) {
for (short array : arrays) {
append(array);
}
return this;
}
public CacheKey append(int[] arrays) {
for (int array : arrays) {
append(array);
}
return this;
}
public CacheKey append(long[] arrays) {
for (long array : arrays) {
append(array);
}
return this;
}
public CacheKey append(float[] arrays) {
for (float array : arrays) {
append(array);
}
return this;
}
public CacheKey append(double[] arrays) {
for (double array : arrays) {
append(array);
}
return this;
}
public CacheKey append(boolean[] arrays) {
for (boolean array : arrays) {
append(array);
}
return this;
}
public CacheKey append(Object[] objs) {
if (objs == null) {
hashCode *= iPrime;
} else {
for (Object obj : objs) {
append(obj);
}
}
return this;
}
@Override
public int hashCode() {
return hashCode;
}
@Override
public String toString() {
return "CacheKey [hashCode:" + hashCode + "]";
}
@Override
public boolean equals(Object obj) {
if (obj == null) {
return false;
} else if (this.getClass() != obj.getClass()) {
return false;
}
CacheKey ck = (CacheKey) obj;
if (hashCode == ck.hashCode) {
return true;
}
return false;
}
// public static void main(String[] args) {
// CacheKey k = new CacheKey();
// }
}
| 16.491525
| 49
| 0.621788
|
2041e7ffddd4d145f8ba84aedc4ef00c38e12a15
| 4,868
|
// ***********************************************************************
// SwerveTeleOp
// ***********************************************************************
// The tele-op mode for swerve robot operations
package org.firstinspires.ftc.teamcode;
import com.qualcomm.robotcore.eventloop.opmode.TeleOp;
import com.qualcomm.robotcore.hardware.DcMotor;
import org.firstinspires.ftc.robotcore.external.navigation.DistanceUnit;
// ***********************************************************************
// Definitions from Qualcomm code for OpMode recognition
// ***********************************************************************
@TeleOp(name="Swerve: 2-TeleOp 1.1", group="Swerve")
public class SwerveTeleOp extends SwerveCore {
// Note when we are approaching the end of the game
int posorneg = 1;
// ***********************************************************************
// SwerveTeleOp
// ***********************************************************************
// Constructs the class.
// The system calls this member when the class is instantiated.
public SwerveTeleOp() {
}
// ***********************************************************************
// Init
// ***********************************************************************
// Performs any actions that are necessary when the OpMode is enabled.
// The system calls this member once when the OpMode is enabled.
@Override
public void init() {
swerveDebug(500, "SwerveTeleOp::init", "START");
// Run initialization of other parts of the class
// Note that the class will connect to all of our motors and servos
super.init();
// We are just starting, so not in the end game yet...
swerveDebug(500, "SwerveTeleOp::init", "DONE");
}
// ***********************************************************************
// start
// ***********************************************************************
// Do first actions when the start command is given.
// Called once when the OpMode is started.
@Override
public void start() {
swerveDebug(500, "SwerveTeleOp::start", "START");
// Call the super/base class start method.
super.start();
ourSwerve.curSwerveMode = SwerveDrive.swerveModes.SWERVE_DRIVER;
swerveDebug(500, "SwerveTeleOp::start", "DONE");
}
// ***********************************************************************
// loop
// ***********************************************************************
// State machine for autonomous robot control
// Called continuously while OpMode is running
@Override
public void loop() {
// double totalPower;
// int endGameTime;
swerveDebug(2000, "SwerveTeleOp::loop", "START");
// set swerve drive orientation automation level based on driver request
if (gamepad1.b) {
ourSwerve.setSwerveMode(SwerveDrive.swerveModes.SWERVE_AUTO);
}
if (gamepad1.a) {
ourSwerve.setSwerveMode(SwerveDrive.swerveModes.SWERVE_DRIVER);
}
if (gamepad1.x) {
ourSwerve.setSwerveMode(SwerveDrive.swerveModes.SWERVE_DRIVE_ORIENT);
}
if (gamepad1.y) {
ourSwerve.setSwerveMode(SwerveDrive.swerveModes.SWERVE_DRIVE_TURN);
}
// Move the robot, flipping y since the joysticks are upside down
ourSwerve.driveRobot(gamepad1.left_stick_x, -gamepad1.left_stick_y, -gamepad1.right_stick_x, gamepad1.right_stick_y);
// *** use buttons to trigger other actions ***
strafe();
// Any loop background updates happen now....
loopEndReporting();
swerveDebug(500, "SwerveTeleOp::loop", "DONE");
}
// ***********************************************************************
// stop
// ***********************************************************************
// Performs any actions that are necessary when the OpMode is disabled.
// The system calls this member once when the OpMode is disabled.
@Override
public void stop() {
swerveDebug(500, "SwerveTeleOp::stop", "START");
// Call the super/base class stop method
super.stop();
swerveDebug(500, "SwerveTeleOp::stop", "DONE");
}
private void strafe() {
if (gamepad1.dpad_left) {
swerveLeftFront.updateWheel(1, -0.50);
swerveRightFront.updateWheel(1, -0.50);
swerveLeftRear.updateWheel(1, -0.50);
swerveRightRear.updateWheel(1, -0.50);
} else if (gamepad1.dpad_right) {
swerveLeftFront.updateWheel(1, 0.50);
swerveRightFront.updateWheel(1, 0.50);
swerveLeftRear.updateWheel(1, 0.50);
swerveRightRear.updateWheel(1, 0.50);
}
}
}
| 38.330709
| 125
| 0.500616
|
84770ad1ac622b9eefc39e185be549efd78700ad
| 74,998
|
package com.ruitukeji.zwbh.retrofit;
import android.content.Context;
import com.kymjs.common.FileUtils;
import com.kymjs.common.Log;
import com.kymjs.common.NetworkUtils;
import com.kymjs.common.PreferenceHelper;
import com.kymjs.common.StringUtils;
import com.kymjs.rxvolley.RxVolley;
import com.kymjs.rxvolley.client.HttpCallback;
import com.kymjs.rxvolley.client.HttpParams;
import com.kymjs.rxvolley.client.ProgressListener;
import com.kymjs.rxvolley.http.VolleyError;
import com.ruitukeji.zwbh.application.MyApplication;
import com.ruitukeji.zwbh.common.KJActivityStack;
import com.ruitukeji.zwbh.constant.NumericConstants;
import com.ruitukeji.zwbh.constant.StringConstants;
import com.ruitukeji.zwbh.constant.URLConstants;
import com.ruitukeji.zwbh.entity.BaseResult;
import com.ruitukeji.zwbh.entity.loginregister.LoginBean;
import com.ruitukeji.zwbh.utils.JsonUtil;
import com.ruitukeji.zwbh.utils.httputil.HttpRequest;
import com.ruitukeji.zwbh.utils.httputil.HttpUtilParams;
import com.ruitukeji.zwbh.utils.httputil.ResponseListener;
import java.io.File;
import java.util.ArrayList;
import java.util.List;
import static com.ruitukeji.zwbh.utils.httputil.HttpRequest.doFailure;
import static com.ruitukeji.zwbh.utils.httputil.HttpRequest.doSuccess;
/**
* Created by ruitu on 2016/9/17.
*/
public class RequestClient {
/**
* @param httpParams 上传头像图片
*/
public static void upLoadImg(HttpParams httpParams, int type, final ResponseListener<String> listener) {
// for (int i = 0; i < files.size(); i++) {
// File file = new File(files.get(i));
// params.put("file" + i, file);
// }
// httpParams.putHeaders("Content-Type", "application/x-www-form-urlencoded");
doServer(new TokenCallback() {
@Override
public void execute() {
String accessToken = PreferenceHelper.readString(MyApplication.getContext(), StringConstants.FILENAME, "accessToken");
if (StringUtils.isEmpty(accessToken)) {
// PreferenceHelper.write(KJActivityStack.create().topActivity(), StringConstants.FILENAME, "isGoneBanner", false);
listener.onFailure(NumericConstants.TOLINGIN + "");
return;
}
httpParams.putHeaders("authorization-token", accessToken);
if (type == 0) {
HttpRequest.requestPostFORMHttp(URLConstants.UPLOADAVATAR, httpParams, listener);
} else {
HttpRequest.requestPostFORMHttp(URLConstants.UPLOADQFCTIMG, httpParams, listener);
}
}
}, listener);
}
/**
* 上传图片
*/
public static void upLoadImg(File file, String key, final ResponseListener<String> listener) {
// String key = "<指定七牛服务上的文件名,或 null>";
String token = " <从服务端SDK获取>";
//new一个uploadManager类
// UploadManager uploadManager = new UploadManager();
// uploadManager.put(file, key, token,
// new UpCompletionHandler() {
// @Override
// public void complete(String key, ResponseInfo info, JSONObject res) {
// //res包含hash、key等信息,具体字段取决于上传策略的设置
// if (info.isOK()) {
// Log.i("qiniu", "Upload Success");
// } else {
// Log.i("qiniu", "Upload Fail");
// //如果失败,这里可以把info信息上报自己的服务器,便于后面分析上传错误原因
// }
// Log.i("qiniu", key + ",\r\n " + info + ",\r\n " + res);
// }
// }, null);
}
/**
* 刷新Token
*/
public static void doRefreshToken(String refreshToken, TokenCallback callback, ResponseListener listener) {
Log.d("tag", "doRefreshToken");
Context context = KJActivityStack.create().topActivity();
HttpParams params = HttpUtilParams.getInstance().getHttpParams();
params.put("refreshToken", refreshToken);
RxVolley.get(URLConstants.REFRESHTOKEN, params, new HttpCallback() {
@Override
public void onSuccess(String t) {
super.onSuccess(t);
BaseResult baseResult = (BaseResult) JsonUtil.getInstance().json2Obj(t, BaseResult.class);
if (baseResult.getCode() != NumericConstants.SUCCESS) {
unDoList.clear();
isRefresh = false;
// PreferenceHelper.write(KJActivityStack.create().topActivity(), StringConstants.FILENAME, "isGoneBanner", false);
PreferenceHelper.write(context, StringConstants.FILENAME, "userId", 0);
PreferenceHelper.write(context, StringConstants.FILENAME, "accessToken", "");
PreferenceHelper.write(context, StringConstants.FILENAME, "refreshToken", "");
PreferenceHelper.write(context, StringConstants.FILENAME, "expireTime", "0");
PreferenceHelper.write(context, StringConstants.FILENAME, "timeBefore", "0");
listener.onFailure(NumericConstants.TOLINGIN + "");
return;
}
LoginBean response1 = (LoginBean) JsonUtil.getInstance().json2Obj(t, LoginBean.class);
// PreferenceHelper.write(context, StringConstants.FILENAME, "userId", response1.getResult().getUserId());
PreferenceHelper.write(context, StringConstants.FILENAME, "accessToken", response1.getResult().getAccessToken());
PreferenceHelper.write(context, StringConstants.FILENAME, "refreshToken", response1.getResult().getRefreshToken());
PreferenceHelper.write(context, StringConstants.FILENAME, "expireTime", response1.getResult().getExpireTime() + "");
PreferenceHelper.write(context, StringConstants.FILENAME, "timeBefore", System.currentTimeMillis() + "");
for (int i = 0; i < unDoList.size(); i++) {
unDoList.get(i).execute();
}
unDoList.clear();
isRefresh = false;
callback.execute();
}
@Override
public void onFailure(VolleyError error) {
super.onFailure(error);
Log.d("tag", "onSuccess");
unDoList.clear();
isRefresh = false;
// PreferenceHelper.write(KJActivityStack.create().topActivity(), StringConstants.FILENAME, "isGoneBanner", false);
PreferenceHelper.write(context, StringConstants.FILENAME, "userId", 0);
PreferenceHelper.write(context, StringConstants.FILENAME, "accessToken", "");
PreferenceHelper.write(context, StringConstants.FILENAME, "refreshToken", "");
PreferenceHelper.write(context, StringConstants.FILENAME, "expireTime", "0");
PreferenceHelper.write(context, StringConstants.FILENAME, "timeBefore", "0");
listener.onFailure(NumericConstants.TOLINGIN + "");
}
});
}
/**
* 应用配置参数
*/
public static void getAppConfig(HttpParams httpParams, final ResponseListener<String> listener) {
HttpRequest.requestGetHttp(URLConstants.APPCONFIG, httpParams, listener);
}
/**
* 获取文章内容
*/
public static void getArticle(HttpParams httpParams, String type, final ResponseListener<String> listener) {
HttpRequest.requestGetHttp(URLConstants.GETARTICLE + "/" + type, httpParams, listener);
}
/**
* 登录
*/
public static void postLogin(HttpParams httpParams, final ResponseListener<String> listener) {
HttpRequest.requestPostHttp(URLConstants.USERLOGIN, httpParams, listener);
}
/**
* 第三方登录
*/
public static void postThirdLogin(HttpParams httpParams, final ResponseListener<String> listener) {
HttpRequest.requestPostHttp(URLConstants.THIRDLOGIN, httpParams, listener);
}
/**
* 第三方登录绑定手机号
*/
public static void postThirdLoginAdd(HttpParams httpParams, final ResponseListener<String> listener) {
HttpRequest.requestPostHttp(URLConstants.THIRDLOGINADD, httpParams, listener);
}
/**
* 发送验证码
*/
public static void postCaptcha(HttpParams httpParams, final ResponseListener<String> listener) {
HttpRequest.requestPostHttp(URLConstants.SENDCAPTCHA, httpParams, listener);
}
/**
* 注册
*/
public static void postRegister(HttpParams httpParams, final ResponseListener<String> listener) {
HttpRequest.requestPostHttp(URLConstants.USERREG, httpParams, listener);
}
/**
* 得到全部城市
*/
public static void getAllCity(HttpParams httpParams, final ResponseListener<String> listener) {
HttpRequest.requestGetHttp(URLConstants.ALLCITY, httpParams, listener);
}
/**
* 得到热门城市
*/
public static void getHotCity(HttpParams httpParams, final ResponseListener<String> listener) {
HttpRequest.requestGetHttp(URLConstants.ALLHOTCITY, httpParams, listener);
}
/**
* 个人认证----基本信息
*
* @param httpParams
* @param listener
*/
public static void postPersonalInformation(HttpParams httpParams, ResponseListener<String> listener) {
Log.d("tag", "postPersonalInformation");
doServer(new TokenCallback() {
@Override
public void execute() {
String accessToken = PreferenceHelper.readString(MyApplication.getContext(), StringConstants.FILENAME, "accessToken");
if (StringUtils.isEmpty(accessToken)) {
// PreferenceHelper.write(KJActivityStack.create().topActivity(), StringConstants.FILENAME, "isGoneBanner", false);
listener.onFailure(NumericConstants.TOLINGIN + "");
return;
}
httpParams.putHeaders("authorization-token", accessToken);
HttpRequest.requestPostHttp(URLConstants.PERSONAUTH, httpParams, listener);
}
}, listener);
}
/**
* 企业认证----企业信息
*
* @param httpParams
* @param listener
*/
public static void postEnterpriseInformation(HttpParams httpParams, ResponseListener<String> listener) {
Log.d("tag", "postEnterpriseInformation");
doServer(new TokenCallback() {
@Override
public void execute() {
String accessToken = PreferenceHelper.readString(MyApplication.getContext(), StringConstants.FILENAME, "accessToken");
if (StringUtils.isEmpty(accessToken)) {
// PreferenceHelper.write(KJActivityStack.create().topActivity(), StringConstants.FILENAME, "isGoneBanner", false);
listener.onFailure(NumericConstants.TOLINGIN + "");
return;
}
httpParams.putHeaders("authorization-token", accessToken);
HttpRequest.requestPostHttp(URLConstants.BUSINESSAUTH, httpParams, listener);
}
}, listener);
}
/**
* 重置密码
*/
public static void postResetpwd(HttpParams httpParams, final ResponseListener<String> listener) {
HttpRequest.requestPostHttp(URLConstants.USERRESTPWD, httpParams, listener);
}
/**
* 首页
*/
public static void getHome(HttpParams httpParams, final ResponseListener<String> listener) {
Log.d("tag", "getHome");
String accessToken = PreferenceHelper.readString(MyApplication.getContext(), StringConstants.FILENAME, "accessToken");
if (!StringUtils.isEmpty(accessToken)) {
httpParams.putHeaders("authorization-token", accessToken);
}
HttpRequest.requestGetHttp(URLConstants.HOME, httpParams, listener);
}
/**
* 公告详情
*/
public static void getAnnouncement(HttpParams httpParams, int id, final ResponseListener<String> listener) {
Log.d("tag", "getAnnouncement");
HttpRequest.requestGetHttp(URLConstants.ANNOUNCEMENT + "/" + id, httpParams, listener);
}
/**
* 查询始发地目的地
*/
public static void getAddress(HttpParams httpParams, final ResponseListener<String> listener) {
Log.d("tag", "getAddress");
doServer(new TokenCallback() {
@Override
public void execute() {
String accessToken = PreferenceHelper.readString(MyApplication.getContext(), StringConstants.FILENAME, "accessToken");
if (StringUtils.isEmpty(accessToken)) {
//PreferenceHelper.write(KJActivityStack.create().topActivity(), StringConstants.FILENAME, "isGoneBanner", false);
listener.onFailure(NumericConstants.TOLINGIN + "");
return;
}
httpParams.putHeaders("authorization-token", accessToken);
HttpRequest.requestGetHttp(URLConstants.INFOADDRESS, httpParams, listener);
}
}, listener);
}
/**
* 始发地目的地--弹框
*/
public static void getAddressBounced(HttpParams httpParams, ResponseListener<String> listener) {
HttpRequest.requestGetHttp(URLConstants.ADDRESSBOUNCED, httpParams, listener);
}
/**
* 查询始发地目的地
*/
public static void getDelAddress(HttpParams httpParams, final ResponseListener<String> listener) {
Log.d("tag", "getDelAddress");
doServer(new TokenCallback() {
@Override
public void execute() {
String accessToken = PreferenceHelper.readString(MyApplication.getContext(), StringConstants.FILENAME, "accessToken");
if (StringUtils.isEmpty(accessToken)) {
//PreferenceHelper.write(KJActivityStack.create().topActivity(), StringConstants.FILENAME, "isGoneBanner", false);
listener.onFailure(NumericConstants.TOLINGIN + "");
return;
}
httpParams.putHeaders("authorization-token", accessToken);
HttpRequest.requestPostHttp(URLConstants.DELADDRESS, httpParams, listener);
}
}, listener);
}
/**
* 是否默认地址
*/
public static void getUpdateDefault(HttpParams httpParams, final ResponseListener<String> listener) {
Log.d("tag", "getUpdateDefault");
doServer(new TokenCallback() {
@Override
public void execute() {
String accessToken = PreferenceHelper.readString(MyApplication.getContext(), StringConstants.FILENAME, "accessToken");
if (StringUtils.isEmpty(accessToken)) {
//PreferenceHelper.write(KJActivityStack.create().topActivity(), StringConstants.FILENAME, "isGoneBanner", false);
listener.onFailure(NumericConstants.TOLINGIN + "");
return;
}
httpParams.putHeaders("authorization-token", accessToken);
HttpRequest.requestPostHttp(URLConstants.UPDATEDEFAULT, httpParams, listener);
}
}, listener);
}
/**
* 始发地目的地信息管理
*/
public static void postAddress(HttpParams httpParams, final ResponseListener<String> listener) {
doServer(new TokenCallback() {
@Override
public void execute() {
String accessToken = PreferenceHelper.readString(MyApplication.getContext(), StringConstants.FILENAME, "accessToken");
if (StringUtils.isEmpty(accessToken)) {
// PreferenceHelper.write(KJActivityStack.create().topActivity(), StringConstants.FILENAME, "isGoneBanner", false);
listener.onFailure(NumericConstants.TOLINGIN + "");
return;
}
httpParams.putHeaders("authorization-token", accessToken);
HttpRequest.requestPostHttp(URLConstants.ADDRESS, httpParams, listener);
}
}, listener);
}
/**
* 获取单条信息
*/
public static void getOneInfoAddress(HttpParams httpParams, final ResponseListener<String> listener) {
doServer(new TokenCallback() {
@Override
public void execute() {
String accessToken = PreferenceHelper.readString(MyApplication.getContext(), StringConstants.FILENAME, "accessToken");
if (StringUtils.isEmpty(accessToken)) {
// PreferenceHelper.write(KJActivityStack.create().topActivity(), StringConstants.FILENAME, "isGoneBanner", false);
listener.onFailure(NumericConstants.TOLINGIN + "");
return;
}
httpParams.putHeaders("authorization-token", accessToken);
HttpRequest.requestGetHttp(URLConstants.GETONEINFOADDRESS, httpParams, listener);
}
}, listener);
}
/**
* 修改始发地 目的地信息
*/
public static void postUpdateAddress(HttpParams httpParams, final ResponseListener<String> listener) {
doServer(new TokenCallback() {
@Override
public void execute() {
String accessToken = PreferenceHelper.readString(MyApplication.getContext(), StringConstants.FILENAME, "accessToken");
if (StringUtils.isEmpty(accessToken)) {
// PreferenceHelper.write(KJActivityStack.create().topActivity(), StringConstants.FILENAME, "isGoneBanner", false);
listener.onFailure(NumericConstants.TOLINGIN + "");
return;
}
httpParams.putHeaders("authorization-token", accessToken);
HttpRequest.requestPostHttp(URLConstants.UPDATEADDRESS, httpParams, listener);
}
}, listener);
}
/**
* 获取常用司机信息
*/
public static void getDriverList(HttpParams httpParams, ResponseListener<String> listener) {
doServer(new TokenCallback() {
@Override
public void execute() {
String accessToken = PreferenceHelper.readString(MyApplication.getContext(), StringConstants.FILENAME, "accessToken");
if (StringUtils.isEmpty(accessToken)) {
// PreferenceHelper.write(KJActivityStack.create().topActivity(), StringConstants.FILENAME, "isGoneBanner", false);
listener.onFailure(NumericConstants.TOLINGIN + "");
return;
}
httpParams.putHeaders("authorization-token", accessToken);
HttpRequest.requestGetHttp(URLConstants.GETDRIVERINFO, httpParams, listener);
}
}, listener);
}
/**
* 加入黑名单/移除黑名单
*/
public static void postDriverBack(HttpParams httpParams, ResponseListener<String> listener) {
doServer(new TokenCallback() {
@Override
public void execute() {
String accessToken = PreferenceHelper.readString(MyApplication.getContext(), StringConstants.FILENAME, "accessToken");
if (StringUtils.isEmpty(accessToken)) {
// PreferenceHelper.write(KJActivityStack.create().topActivity(), StringConstants.FILENAME, "isGoneBanner", false);
listener.onFailure(NumericConstants.TOLINGIN + "");
return;
}
httpParams.putHeaders("authorization-token", accessToken);
HttpRequest.requestPostHttp(URLConstants.DRIVERBACK, httpParams, listener);
}
}, listener);
}
/**
* 删除司机
*/
public static void postDeleteDriver(HttpParams httpParams, ResponseListener<String> listener) {
doServer(new TokenCallback() {
@Override
public void execute() {
String accessToken = PreferenceHelper.readString(MyApplication.getContext(), StringConstants.FILENAME, "accessToken");
if (StringUtils.isEmpty(accessToken)) {
// PreferenceHelper.write(KJActivityStack.create().topActivity(), StringConstants.FILENAME, "isGoneBanner", false);
listener.onFailure(NumericConstants.TOLINGIN + "");
return;
}
httpParams.putHeaders("authorization-token", accessToken);
HttpRequest.requestPostHttp(URLConstants.DELCOLLECTDRIVER, httpParams, listener);
}
}, listener);
}
/**
* 获取个人订单信息 发票
*/
public static void getApplicationInvoiceList(HttpParams httpParams, ResponseListener<String> listener) {
doServer(new TokenCallback() {
@Override
public void execute() {
String accessToken = PreferenceHelper.readString(MyApplication.getContext(), StringConstants.FILENAME, "accessToken");
if (StringUtils.isEmpty(accessToken)) {
// PreferenceHelper.write(KJActivityStack.create().topActivity(), StringConstants.FILENAME, "isGoneBanner", false);
listener.onFailure(NumericConstants.TOLINGIN + "");
return;
}
httpParams.putHeaders("authorization-token", accessToken);
HttpRequest.requestGetHttp(URLConstants.INVOICEGETGOODSINFO, httpParams, listener);
}
}, listener);
}
/**
* 申请个人和公司发票
*/
public static void postApplicationInvoice(HttpParams httpParams, ResponseListener<String> listener) {
doServer(new TokenCallback() {
@Override
public void execute() {
String accessToken = PreferenceHelper.readString(MyApplication.getContext(), StringConstants.FILENAME, "accessToken");
if (StringUtils.isEmpty(accessToken)) {
// PreferenceHelper.write(KJActivityStack.create().topActivity(), StringConstants.FILENAME, "isGoneBanner", false);
listener.onFailure(NumericConstants.TOLINGIN + "");
return;
}
httpParams.putHeaders("authorization-token", accessToken);
HttpRequest.requestPostHttp(URLConstants.INVOICEAPPLYINVOICE, httpParams, listener);
}
}, listener);
}
/**
* 开票记录
*/
public static void getBillingRecordsList(HttpParams httpParams, ResponseListener<String> listener) {
doServer(new TokenCallback() {
@Override
public void execute() {
String accessToken = PreferenceHelper.readString(MyApplication.getContext(), StringConstants.FILENAME, "accessToken");
if (StringUtils.isEmpty(accessToken)) {
// PreferenceHelper.write(KJActivityStack.create().topActivity(), StringConstants.FILENAME, "isGoneBanner", false);
listener.onFailure(NumericConstants.TOLINGIN + "");
return;
}
httpParams.putHeaders("authorization-token", accessToken);
HttpRequest.requestGetHttp(URLConstants.INVOICERECORD, httpParams, listener);
}
}, listener);
}
/**
* 开票详情
*/
public static void getBillingDetails(HttpParams httpParams, ResponseListener<String> listener) {
doServer(new TokenCallback() {
@Override
public void execute() {
String accessToken = PreferenceHelper.readString(MyApplication.getContext(), StringConstants.FILENAME, "accessToken");
if (StringUtils.isEmpty(accessToken)) {
listener.onFailure(NumericConstants.TOLINGIN + "");
return;
}
httpParams.putHeaders("authorization-token", accessToken);
HttpRequest.requestGetHttp(URLConstants.INVOICEREINFO, httpParams, listener);
}
}, listener);
}
/**
* 所含订单
*/
public static void getContainsOrder(HttpParams httpParams, ResponseListener<String> listener) {
doServer(new TokenCallback() {
@Override
public void execute() {
String accessToken = PreferenceHelper.readString(MyApplication.getContext(), StringConstants.FILENAME, "accessToken");
if (StringUtils.isEmpty(accessToken)) {
listener.onFailure(NumericConstants.TOLINGIN + "");
return;
}
httpParams.putHeaders("authorization-token", accessToken);
HttpRequest.requestGetHttp(URLConstants.CONTAINSORDER, httpParams, listener);
}
}, listener);
}
/**
* 获取异常信息
*/
public static void getAbnormalRecords(HttpParams httpParams, ResponseListener<String> listener) {
doServer(new TokenCallback() {
@Override
public void execute() {
String accessToken = PreferenceHelper.readString(MyApplication.getContext(), StringConstants.FILENAME, "accessToken");
if (StringUtils.isEmpty(accessToken)) {
listener.onFailure(NumericConstants.TOLINGIN + "");
return;
}
httpParams.putHeaders("authorization-token", accessToken);
HttpRequest.requestGetHttp(URLConstants.GETABNORMAL, httpParams, listener);
}
}, listener);
}
/**
* 获取异常信息详情
*/
public static void getAbnormalSituation(HttpParams httpParams, ResponseListener<String> listener) {
doServer(new TokenCallback() {
@Override
public void execute() {
String accessToken = PreferenceHelper.readString(MyApplication.getContext(), StringConstants.FILENAME, "accessToken");
if (StringUtils.isEmpty(accessToken)) {
listener.onFailure(NumericConstants.TOLINGIN + "");
return;
}
httpParams.putHeaders("authorization-token", accessToken);
HttpRequest.requestGetHttp(URLConstants.GETONEABNORMAL, httpParams, listener);
}
}, listener);
}
/**
* 获取周边司机
* 经度
* 纬度
*/
public static void getNearbySearch(HttpParams httpParams, ResponseListener<String> listener) {
RxVolley.get(URLConstants.MAINNEARBYSEARCH, httpParams, new HttpCallback() {
@Override
public void onSuccess(String t) {
super.onSuccess(t);
listener.onSuccess(t);
}
@Override
public void onFailure(int errorNo, String strMsg) {
super.onFailure(errorNo, strMsg);
doFailure(errorNo, strMsg, listener);
}
});
}
/**
* 获取驾车距离
*/
public static void getDistance(HttpParams httpParams, final ResponseListener<String> listener) {
RxVolley.get(URLConstants.DISTANCE, httpParams, new HttpCallback() {
@Override
public void onSuccess(String t) {
super.onSuccess(t);
listener.onSuccess(t);
}
@Override
public void onFailure(int errorNo, String strMsg) {
super.onFailure(errorNo, strMsg);
doFailure(errorNo, strMsg, listener);
}
});
}
/**
* 获取消息列表
*/
public static void getMessage(HttpParams httpParams, final ResponseListener<String> listener) {
String accessToken = PreferenceHelper.readString(KJActivityStack.create().topActivity(), StringConstants.FILENAME, "accessToken");
if (!StringUtils.isEmpty(accessToken)) {
httpParams.putHeaders("authorization-token", accessToken);
}
HttpRequest.requestGetHttp(URLConstants.MESSAGE, httpParams, listener);
}
/**
* 删除消息
*/
public static void postDeleteMessage(HttpParams httpParams, final ResponseListener<String> listener) {
doServer(new TokenCallback() {
@Override
public void execute() {
String accessToken = PreferenceHelper.readString(MyApplication.getContext(), StringConstants.FILENAME, "accessToken");
if (StringUtils.isEmpty(accessToken)) {
// PreferenceHelper.write(KJActivityStack.create().topActivity(), StringConstants.FILENAME, "isGoneBanner", false);
listener.onFailure(NumericConstants.TOLINGIN + "");
return;
}
httpParams.putHeaders("authorization-token", accessToken);
HttpRequest.requestPostHttp(URLConstants.DELMESSAGE, httpParams, listener);
}
}, listener);
}
/**
* 标记已读消息
*/
public static void postReadMessage(HttpParams httpParams, final ResponseListener<String> listener) {
doServer(new TokenCallback() {
@Override
public void execute() {
String accessToken = PreferenceHelper.readString(MyApplication.getContext(), StringConstants.FILENAME, "accessToken");
if (StringUtils.isEmpty(accessToken)) {
// PreferenceHelper.write(KJActivityStack.create().topActivity(), StringConstants.FILENAME, "isGoneBanner", false);
listener.onFailure(NumericConstants.TOLINGIN + "");
return;
}
httpParams.putHeaders("authorization-token", accessToken);
HttpRequest.requestPostHttp(URLConstants.READMESSAGE, httpParams, listener);
}
}, listener);
}
/**
* 获取未读消息数量
*/
public static void getUnRead(HttpParams httpParams, final ResponseListener<String> listener) {
String accessToken = PreferenceHelper.readString(KJActivityStack.create().topActivity(), StringConstants.FILENAME, "accessToken");
if (!StringUtils.isEmpty(accessToken)) {
httpParams.putHeaders("authorization-token", accessToken);
}
HttpRequest.requestGetHttp(URLConstants.GETUNREAD, httpParams, listener);
}
/**
* 获取消息详情
*/
public static void getMessageDetails(HttpParams httpParams, ResponseListener<String> listener) {
String accessToken = PreferenceHelper.readString(KJActivityStack.create().topActivity(), StringConstants.FILENAME, "accessToken");
if (!StringUtils.isEmpty(accessToken)) {
httpParams.putHeaders("authorization-token", accessToken);
}
HttpRequest.requestGetHttp(URLConstants.MESSAGEDETAIL, httpParams, listener);
}
/**
* 获取车长车型
*/
public static void getConductorModels(HttpParams httpParams, final ResponseListener<String> listener) {
HttpRequest.requestGetHttp(URLConstants.GETALLCARSTYLE, httpParams, listener);
}
/**
* 同城 长途 提交订单
*/
public static void postLogistics(HttpParams httpParams, final ResponseListener<String> listener) {
Log.d("tag", "postLogistics");
doServer(new TokenCallback() {
@Override
public void execute() {
String accessToken = PreferenceHelper.readString(MyApplication.getContext(), StringConstants.FILENAME, "accessToken");
if (StringUtils.isEmpty(accessToken)) {
PreferenceHelper.write(KJActivityStack.create().topActivity(), StringConstants.FILENAME, "isGoneBanner", false);
listener.onFailure(NumericConstants.TOLINGIN + "");
return;
}
httpParams.putHeaders("authorization-token", accessToken);
HttpRequest.requestPostHttp(URLConstants.ORDERADD, httpParams, listener);
}
}, listener);
}
/**
* 派单给司机
*/
public static void postSendOrder(HttpParams httpParams, final ResponseListener<String> listener) {
Log.d("tag", "postSendOrder");
doServer(new TokenCallback() {
@Override
public void execute() {
String accessToken = PreferenceHelper.readString(MyApplication.getContext(), StringConstants.FILENAME, "accessToken");
if (StringUtils.isEmpty(accessToken)) {
PreferenceHelper.write(KJActivityStack.create().topActivity(), StringConstants.FILENAME, "isGoneBanner", false);
listener.onFailure(NumericConstants.TOLINGIN + "");
return;
}
httpParams.putHeaders("authorization-token", accessToken);
HttpRequest.requestPostHttp(URLConstants.SENDORDER, httpParams, listener);
}
}, listener);
}
/**
* 获取用户信息
*/
public static void getInfo(HttpParams httpParams, ResponseListener<String> listener) {
Log.d("tag", "getInfo");
doServer(new TokenCallback() {
@Override
public void execute() {
String accessToken = PreferenceHelper.readString(MyApplication.getContext(), StringConstants.FILENAME, "accessToken");
if (StringUtils.isEmpty(accessToken)) {
listener.onFailure(NumericConstants.TOLINGIN + "");
return;
}
httpParams.putHeaders("authorization-token", accessToken);
HttpRequest.requestGetHttp(URLConstants.USERINFO, httpParams, listener);
}
}, listener);
}
/**
* 显示货源列表
*/
public static void getGoodsList(HttpParams httpParams, final ResponseListener<String> listener) {
Log.d("tag", "getGoodsList");
doServer(new TokenCallback() {
@Override
public void execute() {
String accessToken = PreferenceHelper.readString(MyApplication.getContext(), StringConstants.FILENAME, "accessToken");
if (StringUtils.isEmpty(accessToken)) {
PreferenceHelper.write(KJActivityStack.create().topActivity(), StringConstants.FILENAME, "isGoneBanner", false);
listener.onFailure(NumericConstants.TOLINGIN + "");
return;
}
httpParams.putHeaders("authorization-token", accessToken);
HttpRequest.requestGetHttp(URLConstants.GOODSLIST, httpParams, listener);
}
}, listener);
}
/**
* 货源详情功能
*/
public static void getGoodDetail(HttpParams httpParams, final ResponseListener<String> listener) {
Log.d("tag", "getGoodDetail");
doServer(new TokenCallback() {
@Override
public void execute() {
String accessToken = PreferenceHelper.readString(MyApplication.getContext(), StringConstants.FILENAME, "accessToken");
if (StringUtils.isEmpty(accessToken)) {
PreferenceHelper.write(KJActivityStack.create().topActivity(), StringConstants.FILENAME, "isGoneBanner", false);
listener.onFailure(NumericConstants.TOLINGIN + "");
return;
}
httpParams.putHeaders("authorization-token", accessToken);
HttpRequest.requestPostFORMHttp(URLConstants.GOODDETAIL, httpParams, listener);
}
}, listener);
}
/**
* 取消订单功能
*/
public static void postCancelOrder(HttpParams httpParams, final ResponseListener<String> listener) {
Log.d("tag", "postCancelGoods");
doServer(new TokenCallback() {
@Override
public void execute() {
String accessToken = PreferenceHelper.readString(MyApplication.getContext(), StringConstants.FILENAME, "accessToken");
if (StringUtils.isEmpty(accessToken)) {
PreferenceHelper.write(KJActivityStack.create().topActivity(), StringConstants.FILENAME, "isGoneBanner", false);
listener.onFailure(NumericConstants.TOLINGIN + "");
return;
}
httpParams.putHeaders("authorization-token", accessToken);
HttpRequest.requestPostHttp(URLConstants.CANCELGOODS, httpParams, listener);
}
}, listener);
}
/**
* 再次发布弹框
*/
public static void postReleaseAgain(HttpParams httpParams, ResponseListener<String> listener) {
Log.d("tag", "postReleaseAgain");
doServer(new TokenCallback() {
@Override
public void execute() {
String accessToken = PreferenceHelper.readString(MyApplication.getContext(), StringConstants.FILENAME, "accessToken");
if (StringUtils.isEmpty(accessToken)) {
PreferenceHelper.write(KJActivityStack.create().topActivity(), StringConstants.FILENAME, "isGoneBanner", false);
listener.onFailure(NumericConstants.TOLINGIN + "");
return;
}
httpParams.putHeaders("authorization-token", accessToken);
HttpRequest.requestPostHttp(URLConstants.RELEASEAGAIN, httpParams, listener);
}
}, listener);
}
/**
* 任务---确认取消订单
*/
public static void postConfirmCancelOrder(HttpParams httpParams, ResponseListener<String> listener) {
Log.d("tag", "postConfirmCancelOrder");
doServer(new TokenCallback() {
@Override
public void execute() {
String accessToken = PreferenceHelper.readString(KJActivityStack.create().topActivity(), StringConstants.FILENAME, "accessToken");
if (StringUtils.isEmpty(accessToken)) {
listener.onFailure(NumericConstants.TOLINGIN + "");
return;
}
httpParams.putHeaders("authorization-token", accessToken);
HttpRequest.requestPostHttp(URLConstants.CANCELGOODSCOMPLETE, httpParams, listener);
}
}, listener);
}
/**
* 更新用户信息
*/
public static void putInfo(HttpParams httpParams, final ResponseListener<String> listener) {
Log.d("tag", "getInfo");
doServer(new TokenCallback() {
@Override
public void execute() {
String accessToken = PreferenceHelper.readString(MyApplication.getContext(), StringConstants.FILENAME, "accessToken");
if (StringUtils.isEmpty(accessToken)) {
// PreferenceHelper.write(KJActivityStack.create().topActivity(), StringConstants.FILENAME, "isGoneBanner", false);
listener.onFailure(NumericConstants.TOLINGIN + "");
return;
}
httpParams.putHeaders("authorization-token", accessToken);
HttpRequest.requestGetHttp(URLConstants.UPDATEINFO, httpParams, listener);
}
}, listener);
}
/**
* 改变广告状态
*/
public static void postChangeAd(HttpParams httpParams, final ResponseListener<String> listener) {
Log.d("tag", "postChangeAd");
doServer(new TokenCallback() {
@Override
public void execute() {
String accessToken = PreferenceHelper.readString(MyApplication.getContext(), StringConstants.FILENAME, "accessToken");
if (StringUtils.isEmpty(accessToken)) {
// PreferenceHelper.write(KJActivityStack.create().topActivity(), StringConstants.FILENAME, "isGoneBanner", false);
listener.onFailure(NumericConstants.TOLINGIN + "");
return;
}
httpParams.putHeaders("authorization-token", accessToken);
HttpRequest.requestPostHttp(URLConstants.CHANGEAD, httpParams, listener);
}
}, listener);
}
/**
* 获取广告状态
*/
public static void getIsAd(HttpParams httpParams, final ResponseListener<String> listener) {
Log.d("tag", "getIsAd");
doServer(new TokenCallback() {
@Override
public void execute() {
String accessToken = PreferenceHelper.readString(MyApplication.getContext(), StringConstants.FILENAME, "accessToken");
if (StringUtils.isEmpty(accessToken)) {
// PreferenceHelper.write(KJActivityStack.create().topActivity(), StringConstants.FILENAME, "isGoneBanner", false);
listener.onFailure(NumericConstants.TOLINGIN + "");
return;
}
httpParams.putHeaders("authorization-token", accessToken);
HttpRequest.requestGetHttp(URLConstants.ISAD, httpParams, listener);
}
}, listener);
}
/**
* 获取个人认证
*/
public static void getPersonalCertificate(HttpParams httpParams, final ResponseListener<String> listener) {
Log.d("tag", "getPersonalCertificate");
doServer(new TokenCallback() {
@Override
public void execute() {
String accessToken = PreferenceHelper.readString(MyApplication.getContext(), StringConstants.FILENAME, "accessToken");
if (StringUtils.isEmpty(accessToken)) {
// PreferenceHelper.write(KJActivityStack.create().topActivity(), StringConstants.FILENAME, "isGoneBanner", false);
listener.onFailure(NumericConstants.TOLINGIN + "");
return;
}
httpParams.putHeaders("authorization-token", accessToken);
HttpRequest.requestGetHttp(URLConstants.GETPERSONAUTHINFO, httpParams, listener);
}
}, listener);
}
/**
* 获取企业公司认证信息
*/
public static void getCompanyAuthInfo(HttpParams httpParams, final ResponseListener<String> listener) {
Log.d("tag", "getPersonalCertificate");
doServer(new TokenCallback() {
@Override
public void execute() {
String accessToken = PreferenceHelper.readString(MyApplication.getContext(), StringConstants.FILENAME, "accessToken");
if (StringUtils.isEmpty(accessToken)) {
// PreferenceHelper.write(KJActivityStack.create().topActivity(), StringConstants.FILENAME, "isGoneBanner", false);
listener.onFailure(NumericConstants.TOLINGIN + "");
return;
}
httpParams.putHeaders("authorization-token", accessToken);
HttpRequest.requestGetHttp(URLConstants.GETCOMPANYAUTHINFO, httpParams, listener);
}
}, listener);
}
/**
* 显示订单列表
*/
public static void getOrderList(HttpParams httpParams, final ResponseListener<String> listener) {
Log.d("tag", "getOnlineService");
doServer(new TokenCallback() {
@Override
public void execute() {
String accessToken = PreferenceHelper.readString(MyApplication.getContext(), StringConstants.FILENAME, "accessToken");
if (StringUtils.isEmpty(accessToken)) {
// PreferenceHelper.write(KJActivityStack.create().topActivity(), StringConstants.FILENAME, "isGoneBanner", false);
listener.onFailure(NumericConstants.TOLINGIN + "");
return;
}
httpParams.putHeaders("authorization-token", accessToken);
HttpRequest.requestGetHttp(URLConstants.SHOWORDERLIST, httpParams, listener);
}
}, listener);
}
/**
* 显示订单详情
*/
public static void getOrderDetails(HttpParams httpParams, final ResponseListener<String> listener) {
Log.d("tag", "getOrderInfo");
doServer(new TokenCallback() {
@Override
public void execute() {
String accessToken = PreferenceHelper.readString(MyApplication.getContext(), StringConstants.FILENAME, "accessToken");
if (StringUtils.isEmpty(accessToken)) {
// PreferenceHelper.write(KJActivityStack.create().topActivity(), StringConstants.FILENAME, "isGoneBanner", false);
listener.onFailure(NumericConstants.TOLINGIN + "");
return;
}
httpParams.putHeaders("authorization-token", accessToken);
HttpRequest.requestGetHttp(URLConstants.ORDERDETAIL, httpParams, listener);
}
}, listener);
}
/**
* 获取货物签收单信息
*/
public static void getCarGoInfo(HttpParams httpParams, final ResponseListener<String> listener) {
Log.d("tag", "getCarGoInfo");
doServer(new TokenCallback() {
@Override
public void execute() {
String accessToken = PreferenceHelper.readString(MyApplication.getContext(), StringConstants.FILENAME, "accessToken");
if (StringUtils.isEmpty(accessToken)) {
// PreferenceHelper.write(KJActivityStack.create().topActivity(), StringConstants.FILENAME, "isGoneBanner", false);
listener.onFailure(NumericConstants.TOLINGIN + "");
return;
}
httpParams.putHeaders("authorization-token", accessToken);
HttpRequest.requestGetHttp(URLConstants.CARGOINFO, httpParams, listener);
}
}, listener);
}
/**
* 收藏司机
*/
public static void postCollectDriver(HttpParams httpParams, final ResponseListener<String> listener) {
Log.d("tag", "postCollectDriver");
doServer(new TokenCallback() {
@Override
public void execute() {
String accessToken = PreferenceHelper.readString(MyApplication.getContext(), StringConstants.FILENAME, "accessToken");
if (StringUtils.isEmpty(accessToken)) {
// PreferenceHelper.write(KJActivityStack.create().topActivity(), StringConstants.FILENAME, "isGoneBanner", false);
listener.onFailure(NumericConstants.TOLINGIN + "");
return;
}
httpParams.putHeaders("authorization-token", accessToken);
HttpRequest.requestPostHttp(URLConstants.COLLECTDRIVER, httpParams, listener);
}
}, listener);
}
/**
* 收藏司机
*/
public static void postComplaintDriver(HttpParams httpParams, final ResponseListener<String> listener) {
Log.d("tag", "postComplaintDriver");
doServer(new TokenCallback() {
@Override
public void execute() {
String accessToken = PreferenceHelper.readString(MyApplication.getContext(), StringConstants.FILENAME, "accessToken");
if (StringUtils.isEmpty(accessToken)) {
listener.onFailure(NumericConstants.TOLINGIN + "");
return;
}
httpParams.putHeaders("authorization-token", accessToken);
HttpRequest.requestPostHttp(URLConstants.COMPLAINTDRIVER, httpParams, listener);
}
}, listener);
}
/**
* 查看凭证
*/
public static void getShowCerPic(HttpParams httpParams, final ResponseListener<String> listener) {
Log.d("tag", "getShowCerPic");
doServer(new TokenCallback() {
@Override
public void execute() {
String accessToken = PreferenceHelper.readString(MyApplication.getContext(), StringConstants.FILENAME, "accessToken");
if (StringUtils.isEmpty(accessToken)) {
// PreferenceHelper.write(KJActivityStack.create().topActivity(), StringConstants.FILENAME, "isGoneBanner", false);
listener.onFailure(NumericConstants.TOLINGIN + "");
return;
}
httpParams.putHeaders("authorization-token", accessToken);
HttpRequest.requestGetHttp(URLConstants.SHOWCERPIC, httpParams, listener);
}
}, listener);
}
/**
* 获取微信支付参数
*/
public static void getWxPay(HttpParams httpParams, final ResponseListener<String> listener) {
Log.d("tag", "getWxPay");
doServer(new TokenCallback() {
@Override
public void execute() {
String accessToken = PreferenceHelper.readString(MyApplication.getContext(), StringConstants.FILENAME, "accessToken");
if (StringUtils.isEmpty(accessToken)) {
// PreferenceHelper.write(KJActivityStack.create().topActivity(), StringConstants.FILENAME, "isGoneBanner", false);
listener.onFailure(NumericConstants.TOLINGIN + "");
return;
}
httpParams.putHeaders("authorization-token", accessToken);
HttpRequest.requestGetHttp(URLConstants.WXPAY, httpParams, listener);
}
}, listener);
}
/**
* 通过余额支付
*/
public static void postScorePay(HttpParams httpParams, final ResponseListener<String> listener) {
Log.d("tag", "postScorePay");
doServer(new TokenCallback() {
@Override
public void execute() {
String accessToken = PreferenceHelper.readString(MyApplication.getContext(), StringConstants.FILENAME, "accessToken");
if (StringUtils.isEmpty(accessToken)) {
// PreferenceHelper.write(KJActivityStack.create().topActivity(), StringConstants.FILENAME, "isGoneBanner", false);
listener.onFailure(NumericConstants.TOLINGIN + "");
return;
}
httpParams.putHeaders("authorization-token", accessToken);
HttpRequest.requestPostHttp(URLConstants.SCOREPAY, httpParams, listener);
}
}, listener);
}
/**
* 获取支付宝支付参数
*/
public static void getAlipay(HttpParams httpParams, final ResponseListener<String> listener) {
Log.d("tag", "getAlipay");
doServer(new TokenCallback() {
@Override
public void execute() {
String accessToken = PreferenceHelper.readString(MyApplication.getContext(), StringConstants.FILENAME, "accessToken");
if (StringUtils.isEmpty(accessToken)) {
// PreferenceHelper.write(KJActivityStack.create().topActivity(), StringConstants.FILENAME, "isGoneBanner", false);
listener.onFailure(NumericConstants.TOLINGIN + "");
return;
}
httpParams.putHeaders("authorization-token", accessToken);
HttpRequest.requestGetHttp(URLConstants.ALIPAY, httpParams, listener);
}
}, listener);
}
/**
* 上传支付凭证
*/
public static void uploadCerPic(HttpParams httpParams, final ResponseListener<String> listener) {
Log.d("tag", "uploadCerPic");
doServer(new TokenCallback() {
@Override
public void execute() {
String accessToken = PreferenceHelper.readString(MyApplication.getContext(), StringConstants.FILENAME, "accessToken");
if (StringUtils.isEmpty(accessToken)) {
// PreferenceHelper.write(KJActivityStack.create().topActivity(), StringConstants.FILENAME, "isGoneBanner", false);
listener.onFailure(NumericConstants.TOLINGIN + "");
return;
}
httpParams.putHeaders("authorization-token", accessToken);
HttpRequest.requestPostHttp(URLConstants.UPLOADCERPIC, httpParams, listener);
}
}, listener);
}
/**
* 显示司机报价列表
*/
public static void getShowDriverQuoteList(HttpParams httpParams, final ResponseListener<String> listener) {
Log.d("tag", "getShowDriverQuoteList");
doServer(new TokenCallback() {
@Override
public void execute() {
String accessToken = PreferenceHelper.readString(MyApplication.getContext(), StringConstants.FILENAME, "accessToken");
if (StringUtils.isEmpty(accessToken)) {
// PreferenceHelper.write(KJActivityStack.create().topActivity(), StringConstants.FILENAME, "isGoneBanner", false);
listener.onFailure(NumericConstants.TOLINGIN + "");
return;
}
httpParams.putHeaders("authorization-token", accessToken);
HttpRequest.requestGetHttp(URLConstants.SHOWDRIVERQUOTELIST, httpParams, listener);
}
}, listener);
}
/**
* 提交司机报价
*/
public static void sendDriverPrice(HttpParams httpParams, final ResponseListener<String> listener) {
Log.d("tag", "sendDriverPrice");
doServer(new TokenCallback() {
@Override
public void execute() {
String accessToken = PreferenceHelper.readString(MyApplication.getContext(), StringConstants.FILENAME, "accessToken");
if (StringUtils.isEmpty(accessToken)) {
// PreferenceHelper.write(KJActivityStack.create().topActivity(), StringConstants.FILENAME, "isGoneBanner", false);
listener.onFailure(NumericConstants.TOLINGIN + "");
return;
}
httpParams.putHeaders("authorization-token", accessToken);
HttpRequest.requestPostHttp(URLConstants.SENDDRIVERPRICE, httpParams, listener);
}
}, listener);
}
/**
* 我的钱包
*/
public static void getPay(HttpParams httpParams, final ResponseListener<String> listener) {
Log.d("tag", "getPay");
doServer(new TokenCallback() {
@Override
public void execute() {
String accessToken = PreferenceHelper.readString(MyApplication.getContext(), StringConstants.FILENAME, "accessToken");
if (StringUtils.isEmpty(accessToken)) {
// PreferenceHelper.write(KJActivityStack.create().topActivity(), StringConstants.FILENAME, "isGoneBanner", false);
listener.onFailure(NumericConstants.TOLINGIN + "");
return;
}
httpParams.putHeaders("authorization-token", accessToken);
HttpRequest.requestGetHttp(URLConstants.PAY, httpParams, listener);
}
}, listener);
}
/**
* 账户明细
*/
public static void getTimeName(HttpParams httpParams, ResponseListener<String> listener) {
Log.d("tag", "getTimeName");
HttpRequest.requestGetHttp(URLConstants.GRTTIMENAME, httpParams, listener);
}
/**
* 账户明细
*/
public static void getIncomeDetails(HttpParams httpParams, final ResponseListener<String> listener) {
Log.d("tag", "getIncomeDetails");
doServer(new TokenCallback() {
@Override
public void execute() {
String accessToken = PreferenceHelper.readString(MyApplication.getContext(), StringConstants.FILENAME, "accessToken");
if (StringUtils.isEmpty(accessToken)) {
// PreferenceHelper.write(KJActivityStack.create().topActivity(), StringConstants.FILENAME, "isGoneBanner", false);
listener.onFailure(NumericConstants.TOLINGIN + "");
return;
}
httpParams.putHeaders("authorization-token", accessToken);
HttpRequest.requestGetHttp(URLConstants.INCOMEDETAILS, httpParams, listener);
}
}, listener);
}
/**
* 提现记录
*/
public static void showCashRecord(HttpParams httpParams, ResponseListener<String> listener) {
doServer(new TokenCallback() {
@Override
public void execute() {
String accessToken = PreferenceHelper.readString(MyApplication.getContext(), StringConstants.FILENAME, "accessToken");
if (StringUtils.isEmpty(accessToken)) {
listener.onFailure(NumericConstants.TOLINGIN + "");
return;
}
httpParams.putHeaders("authorization-token", accessToken);
HttpRequest.requestGetHttp(URLConstants.SHOWCASHRECORD, httpParams, listener);
}
}, listener);
}
/**
* 获取个人银行卡信息
*/
public static void getMyBankCard(HttpParams httpParams, final ResponseListener<String> listener) {
doServer(new TokenCallback() {
@Override
public void execute() {
String accessToken = PreferenceHelper.readString(MyApplication.getContext(), StringConstants.FILENAME, "accessToken");
if (StringUtils.isEmpty(accessToken)) {
listener.onFailure(NumericConstants.TOLINGIN + "");
return;
}
httpParams.putHeaders("authorization-token", accessToken);
HttpRequest.requestGetHttp(URLConstants.MYBANKCARD, httpParams, listener);
}
}, listener);
}
/**
* 添加银行卡
*/
public static void postAddBankCard(HttpParams httpParams, final ResponseListener<String> listener) {
doServer(new TokenCallback() {
@Override
public void execute() {
String accessToken = PreferenceHelper.readString(MyApplication.getContext(), StringConstants.FILENAME, "accessToken");
if (StringUtils.isEmpty(accessToken)) {
listener.onFailure(NumericConstants.TOLINGIN + "");
return;
}
httpParams.putHeaders("authorization-token", accessToken);
HttpRequest.requestPostHttp(URLConstants.ADDBANKCARD, httpParams, listener);
}
}, listener);
}
/**
* 设置支付密码
*/
public static void postSetPayPassword(HttpParams httpParams, ResponseListener<String> listener) {
doServer(new TokenCallback() {
@Override
public void execute() {
String accessToken = PreferenceHelper.readString(MyApplication.getContext(), StringConstants.FILENAME, "accessToken");
if (StringUtils.isEmpty(accessToken)) {
listener.onFailure(NumericConstants.TOLINGIN + "");
return;
}
httpParams.putHeaders("authorization-token", accessToken);
HttpRequest.requestPostHttp(URLConstants.SETPAYPASSEORD, httpParams, listener);
}
}, listener);
}
/**
* 修改密码校验
*/
public static void getCheckPayPassword(HttpParams httpParams, ResponseListener<String> listener) {
doServer(new TokenCallback() {
@Override
public void execute() {
String accessToken = PreferenceHelper.readString(MyApplication.getContext(), StringConstants.FILENAME, "accessToken");
if (StringUtils.isEmpty(accessToken)) {
listener.onFailure(NumericConstants.TOLINGIN + "");
return;
}
httpParams.putHeaders("authorization-token", accessToken);
HttpRequest.requestPostHttp(URLConstants.CHECKPAYPASSEORD, httpParams, listener);
}
}, listener);
}
/**
* 获得银行
*/
public static void getBank(HttpParams httpParams, final ResponseListener<String> listener) {
HttpRequest.requestGetHttp(URLConstants.GETBANK, httpParams, listener);
}
/**
* 显示我的推荐列表
*/
public static void showMyRecommList(HttpParams httpParams, final ResponseListener<String> listener) {
doServer(new TokenCallback() {
@Override
public void execute() {
String accessToken = PreferenceHelper.readString(MyApplication.getContext(), StringConstants.FILENAME, "accessToken");
if (StringUtils.isEmpty(accessToken)) {
// PreferenceHelper.write(KJActivityStack.create().topActivity(), StringConstants.FILENAME, "isGoneBanner", false);
listener.onFailure(NumericConstants.TOLINGIN + "");
return;
}
httpParams.putHeaders("authorization-token", accessToken);
HttpRequest.requestGetHttp(URLConstants.SHOWMYRECOMMLIST, httpParams, listener);
}
}, listener);
}
/**
* 余额提现
*/
public static void postWithdrawal(HttpParams httpParams, final ResponseListener<String> listener) {
doServer(new TokenCallback() {
@Override
public void execute() {
String accessToken = PreferenceHelper.readString(MyApplication.getContext(), StringConstants.FILENAME, "accessToken");
if (StringUtils.isEmpty(accessToken)) {
listener.onFailure(NumericConstants.TOLINGIN + "");
return;
}
httpParams.putHeaders("authorization-token", accessToken);
HttpRequest.requestPostHttp(URLConstants.WITHDRAWAL, httpParams, listener);
}
}, listener);
}
/**
* 充值
*/
public static void postRecharge(HttpParams httpParams, int type, final ResponseListener<String> listener) {
doServer(new TokenCallback() {
@Override
public void execute() {
String accessToken = PreferenceHelper.readString(MyApplication.getContext(), StringConstants.FILENAME, "accessToken");
if (StringUtils.isEmpty(accessToken)) {
// PreferenceHelper.write(KJActivityStack.create().topActivity(), StringConstants.FILENAME, "isGoneBanner", false);
listener.onFailure(NumericConstants.TOLINGIN + "");
return;
}
httpParams.putHeaders("authorization-token", accessToken);
if (type == 1) {
HttpRequest.requestPostHttp(URLConstants.RECHARGEBYALIPAY, httpParams, listener);
} else if (type == 2) {
HttpRequest.requestPostHttp(URLConstants.RECHARGEBYWEXIN, httpParams, listener);
}
}
}, listener);
}
/**
* 查看账单
*/
public static void getPayRecord(HttpParams httpParams, final ResponseListener<String> listener) {
doServer(new TokenCallback() {
@Override
public void execute() {
String accessToken = PreferenceHelper.readString(MyApplication.getContext(), StringConstants.FILENAME, "accessToken");
if (StringUtils.isEmpty(accessToken)) {
// PreferenceHelper.write(KJActivityStack.create().topActivity(), StringConstants.FILENAME, "isGoneBanner", false);
listener.onFailure(NumericConstants.TOLINGIN + "");
return;
}
httpParams.putHeaders("authorization-token", accessToken);
HttpRequest.requestGetHttp(URLConstants.SHOWPAYRECORD, httpParams, listener);
}
}, listener);
}
/**
* 缴纳保证金
*/
public static void getPayBond(HttpParams httpParams, int way, final ResponseListener<String> listener) {
doServer(new TokenCallback() {
@Override
public void execute() {
String accessToken = PreferenceHelper.readString(MyApplication.getContext(), StringConstants.FILENAME, "accessToken");
if (StringUtils.isEmpty(accessToken)) {
// PreferenceHelper.write(KJActivityStack.create().topActivity(), StringConstants.FILENAME, "isGoneBanner", false);
listener.onFailure(NumericConstants.TOLINGIN + "");
return;
}
httpParams.putHeaders("authorization-token", accessToken);
if (way == 1) {//支付宝
HttpRequest.requestGetHttp(URLConstants.ALIPAYCASH, httpParams, listener);
} else if (way == 2) {//微信
HttpRequest.requestGetHttp(URLConstants.PAYBOND1, httpParams, listener);
}
}
}, listener);
}
/**
* 充值记录
*/
public static void getRechargeRecord(HttpParams httpParams, final ResponseListener<String> listener) {
doServer(new TokenCallback() {
@Override
public void execute() {
String accessToken = PreferenceHelper.readString(MyApplication.getContext(), StringConstants.FILENAME, "accessToken");
if (StringUtils.isEmpty(accessToken)) {
// PreferenceHelper.write(KJActivityStack.create().topActivity(), StringConstants.FILENAME, "isGoneBanner", false);
listener.onFailure(NumericConstants.TOLINGIN + "");
return;
}
httpParams.putHeaders("authorization-token", accessToken);
HttpRequest.requestGetHttp(URLConstants.RECHARGERECORD, httpParams, listener);
}
}, listener);
}
/**
* 获取评价详情
*/
public static void getEvaluationShare(HttpParams httpParams, final ResponseListener<String> listener) {
doServer(new TokenCallback() {
@Override
public void execute() {
String accessToken = PreferenceHelper.readString(MyApplication.getContext(), StringConstants.FILENAME, "accessToken");
if (StringUtils.isEmpty(accessToken)) {
// PreferenceHelper.write(KJActivityStack.create().topActivity(), StringConstants.FILENAME, "isGoneBanner", false);
listener.onFailure(NumericConstants.TOLINGIN + "");
return;
}
httpParams.putHeaders("authorization-token", accessToken);
HttpRequest.requestGetHttp(URLConstants.COMMENTINFO, httpParams, listener);
}
}, listener);
}
/**
* 发送评价详情
*/
public static void postEvaluationShare(HttpParams httpParams, final ResponseListener<String> listener) {
doServer(new TokenCallback() {
@Override
public void execute() {
String accessToken = PreferenceHelper.readString(MyApplication.getContext(), StringConstants.FILENAME, "accessToken");
if (StringUtils.isEmpty(accessToken)) {
// PreferenceHelper.write(KJActivityStack.create().topActivity(), StringConstants.FILENAME, "isGoneBanner", false);
listener.onFailure(NumericConstants.TOLINGIN + "");
return;
}
httpParams.putHeaders("authorization-token", accessToken);
HttpRequest.requestPostHttp(URLConstants.SENDCOMMENTINFO, httpParams, listener);
}
}, listener);
}
/**
* 获取订单轨迹信息
*
* @param httpParams 提交参数
* @param listener 回调
*/
public static void getTrajectory(HttpParams httpParams, final ResponseListener<String> listener) {
RxVolley.get(URLConstants.LOGISTICSPOSITIONING, httpParams, new HttpCallback() {
@Override
public void onSuccess(String t) {
super.onSuccess(t);
listener.onSuccess(t);
}
@Override
public void onFailure(int errorNo, String strMsg) {
super.onFailure(errorNo, strMsg);
doFailure(errorNo, strMsg, listener);
}
});
}
/**
* 投诉中心
*/
public static void getComplaintCenter(HttpParams httpParams, final ResponseListener<String> listener) {
doServer(new TokenCallback() {
@Override
public void execute() {
String accessToken = PreferenceHelper.readString(MyApplication.getContext(), StringConstants.FILENAME, "accessToken");
if (StringUtils.isEmpty(accessToken)) {
// PreferenceHelper.write(KJActivityStack.create().topActivity(), StringConstants.FILENAME, "isGoneBanner", false);
listener.onFailure(NumericConstants.TOLINGIN + "");
return;
}
httpParams.putHeaders("authorization-token", accessToken);
HttpRequest.requestGetHttp(URLConstants.COMPLAINTCENTER, httpParams, listener);
}
}, listener);
}
/**
* 帮助中心
*/
public static void getHelpCenter(HttpParams httpParams, final ResponseListener<String> listener) {
HttpRequest.requestGetHttp(URLConstants.HELPCENTER, httpParams, listener);
}
/**
* 帮助中心详情
*/
public static void getHelpCenterDetails(HttpParams httpParams, final ResponseListener<String> listener) {
HttpRequest.requestGetHttp(URLConstants.HELPCENTERDETAIL, httpParams, listener);
}
/**
* 用户反馈
*/
public static void postUserFeedback(HttpParams httpParams, ResponseListener<String> listener) {
String accessToken = PreferenceHelper.readString(MyApplication.getContext(), StringConstants.FILENAME, "accessToken");
if (!StringUtils.isEmpty(accessToken)) {
httpParams.putHeaders("authorization-token", accessToken);
}
HttpRequest.requestPostHttp(URLConstants.USERFEEDBACK, httpParams, listener);
}
/**
* 修改密码
*/
public static void postChangePassword(HttpParams httpParams, final ResponseListener<String> listener) {
doServer(new TokenCallback() {
@Override
public void execute() {
String accessToken = PreferenceHelper.readString(MyApplication.getContext(), StringConstants.FILENAME, "accessToken");
if (StringUtils.isEmpty(accessToken)) {
// PreferenceHelper.write(KJActivityStack.create().topActivity(), StringConstants.FILENAME, "isGoneBanner", false);
listener.onFailure(NumericConstants.TOLINGIN + "");
return;
}
httpParams.putHeaders("authorization-token", accessToken);
HttpRequest.requestPostHttp(URLConstants.UPDATEPWD, httpParams, listener);
}
}, listener);
}
/**
* 下载App
*/
@SuppressWarnings("unchecked")
public static void downloadApp(String updateAppUrl, ProgressListener progressListener, final ResponseListener<String> listener) {
RxVolley.download(FileUtils.getSaveFolder(StringConstants.DOWNLOADPATH).getAbsolutePath() + "/WZTXH.apk", updateAppUrl, progressListener, new HttpCallback() {
@Override
public void onSuccess(String t) {
BaseResult result = new BaseResult();
result.setResult(FileUtils.getSaveFolder(StringConstants.DOWNLOADPATH).getAbsolutePath() + "/WZTXH.apk");
result.setMsg("SUCCESS");
result.setCode(NumericConstants.SUCCESS);
doSuccess(JsonUtil.getInstance().obj2JsonString(result), listener);
}
@Override
public void onFailure(int errorNo, String strMsg) {
Log.d(errorNo + "====failure" + strMsg);
doFailure(errorNo, strMsg, listener);
}
});
}
/**
* 是否登录
*/
public static void isLogin(final ResponseListener<String> listener) {
doServer(new TokenCallback() {
@Override
public void execute() {
String accessToken = PreferenceHelper.readString(MyApplication.getContext(), StringConstants.FILENAME, "accessToken");
if (StringUtils.isEmpty(accessToken)) {
// PreferenceHelper.write(KJActivityStack.create().topActivity(), StringConstants.FILENAME, "isGoneBanner", false);
listener.onFailure(NumericConstants.TOLINGIN + "");
return;
}
listener.onSuccess("");
}
}, listener);
}
/**
* 刷新token回调
*/
public static boolean isRefresh = false;
public static void doServer(final TokenCallback callback, ResponseListener listener) {
final Context context = KJActivityStack.create().topActivity();
if (!NetworkUtils.isNetWorkAvailable(context)) {
doFailure(-1, "NetWork err", listener);
return;
}
Log.d("tag", "isNetWorkAvailable" + true);
String accessToken = PreferenceHelper.readString(context, StringConstants.FILENAME, "accessToken", "");
if (StringUtils.isEmpty(accessToken)) {
Log.d("tag", "onFailure");
// PreferenceHelper.write(KJActivityStack.create().topActivity(), StringConstants.FILENAME, "isGoneBanner", false);
PreferenceHelper.write(context, StringConstants.FILENAME, "userId", 0);
PreferenceHelper.write(context, StringConstants.FILENAME, "accessToken", "");
PreferenceHelper.write(context, StringConstants.FILENAME, "refreshToken", "");
PreferenceHelper.write(context, StringConstants.FILENAME, "expireTime", "0");
PreferenceHelper.write(context, StringConstants.FILENAME, "timeBefore", "0");
listener.onFailure(NumericConstants.TOLINGIN + "");
return;
}
long nowTime = System.currentTimeMillis();
// String timebefore = PreferenceHelper.readString(context, StringConstants.FILENAME, "timebefore", "0");
// long timebefore1 = 0;
// if (StringUtils.isEmpty(timebefore)) {
// timebefore1 = 0;
// } else {
// timebefore1 = Long.decode(timebefore);
// }
String expireTime = PreferenceHelper.readString(context, StringConstants.FILENAME, "expireTime");
long expireTime1 = 0;
if (StringUtils.isEmpty(expireTime)) {
expireTime1 = 0;
} else {
expireTime1 = Long.decode(expireTime);
}
long refreshTime = nowTime - expireTime1 * 1000 - 2000;
if (refreshTime >= 0) {
if (isRefresh) {
unDoList.add(callback);
return;
}
isRefresh = true;
String refreshToken = PreferenceHelper.readString(context, StringConstants.FILENAME, "refreshToken");
doRefreshToken(refreshToken, callback, listener);
} else {
Log.d("tag", "onSuccess");
callback.execute();
}
}
public interface TokenCallback {
void execute();
}
private static List<TokenCallback> unDoList = new ArrayList<>();
}
| 43.176742
| 166
| 0.604949
|
f3231af89d391c9745e7f4c207ecda6da8c4067a
| 226
|
package info.izumin.android.bletia.core;
/**
* Created by izumin on 11/11/15.
*/
public interface ResolveStrategy<T, E extends Throwable, R> {
void resolve(T value);
void reject(E throwable);
R getResolver();
}
| 20.545455
| 61
| 0.685841
|
297f8c9c205537c100fb53e1b2f238bb3c51499c
| 9,794
|
package org.sagebionetworks.bridge.dynamodb;
import static com.google.common.base.Preconditions.checkNotNull;
import java.util.List;
import javax.annotation.Resource;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.sagebionetworks.bridge.BridgeUtils;
import org.sagebionetworks.bridge.config.BridgeConfig;
import org.sagebionetworks.bridge.dao.CriteriaDao;
import org.sagebionetworks.bridge.dao.NotificationTopicDao;
import org.sagebionetworks.bridge.exceptions.EntityNotFoundException;
import org.sagebionetworks.bridge.models.Criteria;
import org.sagebionetworks.bridge.time.DateUtils;
import org.sagebionetworks.bridge.models.notifications.NotificationTopic;
import com.amazonaws.AmazonServiceException;
import com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBMapper;
import com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBQueryExpression;
import com.amazonaws.services.dynamodbv2.datamodeling.QueryResultPage;
import com.amazonaws.services.dynamodbv2.model.AttributeValue;
import com.amazonaws.services.dynamodbv2.model.ComparisonOperator;
import com.amazonaws.services.dynamodbv2.model.Condition;
import com.amazonaws.services.sns.AmazonSNSClient;
import com.amazonaws.services.sns.model.CreateTopicResult;
import com.amazonaws.services.sns.model.DeleteTopicRequest;
import com.google.common.collect.ImmutableList;
@Component
public class DynamoNotificationTopicDao implements NotificationTopicDao {
private static final Logger LOG = LoggerFactory.getLogger(DynamoNotificationTopicDao.class);
static final String ATTR_DISPLAY_NAME = "DisplayName";
static final String CRITERIA_KEY_PREFIX = "notificationtopic:";
private DynamoDBMapper mapper;
private AmazonSNSClient snsClient;
private BridgeConfig config;
private CriteriaDao criteriaDao;
@Resource(name = "notificationTopicMapper")
final void setNotificationTopicMapper(DynamoDBMapper mapper) {
this.mapper = mapper;
}
@Resource(name = "snsClient")
final void setSnsClient(AmazonSNSClient snsClient) {
this.snsClient = snsClient;
}
@Resource(name = "bridgeConfig")
public final void setBridgeConfig(BridgeConfig bridgeConfig) {
this.config = bridgeConfig;
}
/** Criteria DAO, because Criteria goes in a separate table. */
@Autowired
public final void setCriteriaDao(CriteriaDao criteriaDao) {
this.criteriaDao = criteriaDao;
}
@Override
public List<NotificationTopic> listTopics(String appId, boolean includeDeleted) {
checkNotNull(appId);
// Consistent reads is set to true, because this is the table's primary key, and having reliable tests is more
// important than saving a small amount of DDB capacity.
DynamoNotificationTopic hashKey = new DynamoNotificationTopic();
hashKey.setAppId(appId);
DynamoDBQueryExpression<DynamoNotificationTopic> query = new DynamoDBQueryExpression<DynamoNotificationTopic>();
query.withConsistentRead(true);
query.withHashKeyValues(hashKey);
if (!includeDeleted) {
query.withQueryFilterEntry("deleted", new Condition()
.withComparisonOperator(ComparisonOperator.NE)
.withAttributeValueList(new AttributeValue().withN("1")));
}
QueryResultPage<DynamoNotificationTopic> resultPage = mapper.queryPage(DynamoNotificationTopic.class, query);
List<DynamoNotificationTopic> topicList = resultPage.getResults();
// Load criteria.
topicList.forEach(this::loadCriteria);
return ImmutableList.copyOf(topicList);
}
@Override
public NotificationTopic getTopic(String appId, String guid) {
checkNotNull(appId);
checkNotNull(guid);
return getTopicInternal(appId, guid);
}
private NotificationTopic getTopicInternal(String appId, String guid) {
DynamoNotificationTopic hashKey = new DynamoNotificationTopic();
hashKey.setAppId(appId);
hashKey.setGuid(guid);
DynamoNotificationTopic topic = mapper.load(hashKey);
if (topic == null) {
throw new EntityNotFoundException(NotificationTopic.class);
}
loadCriteria(topic);
return topic;
}
@Override
public NotificationTopic createTopic(NotificationTopic topic) {
checkNotNull(topic);
// Create SNS topic first. If SNS fails, an exception is thrown. If DDB call fails, the SNS topic is orphaned
// but that will not break the data integrity of Bridge data.
topic.setGuid(BridgeUtils.generateGuid());
String snsTopicName = createSnsTopicName(topic);
CreateTopicResult result = snsClient.createTopic(snsTopicName);
// Display name is required for SMS notifications. Strangely, there's no way to set display name in the
// create API, only the set attribute API.
snsClient.setTopicAttributes(result.getTopicArn(), ATTR_DISPLAY_NAME, topic.getShortName());
topic.setTopicARN(result.getTopicArn());
long timestamp = DateUtils.getCurrentMillisFromEpoch();
topic.setCreatedOn(timestamp);
topic.setModifiedOn(timestamp);
persistCriteria(topic);
mapper.save(topic);
return topic;
}
@Override
public NotificationTopic updateTopic(NotificationTopic topic) {
checkNotNull(topic);
checkNotNull(topic.getGuid());
NotificationTopic existing = getTopicInternal(topic.getAppId(), topic.getGuid());
existing.setName(topic.getName());
existing.setDescription(topic.getDescription());
existing.setModifiedOn(DateUtils.getCurrentMillisFromEpoch() );
existing.setCriteria(topic.getCriteria());
persistCriteria(topic);
mapper.save(existing);
return existing;
}
@Override
public void deleteTopic(String appId, String guid) {
checkNotNull(appId);
checkNotNull(guid);
NotificationTopic existing = getTopicInternal(appId, guid);
if (existing.isDeleted()) {
throw new EntityNotFoundException(NotificationTopic.class);
}
existing.setDeleted(true);
mapper.save(existing);
}
@Override
public void deleteTopicPermanently(String appId, String guid) {
checkNotNull(appId);
checkNotNull(guid);
NotificationTopic existing = getTopicInternal(appId, guid);
// Delete the DDB record first. If it fails an exception is thrown. If SNS fails, the SNS topic
// is not deleted, but the DDB record has successfully deleted, so suppress the exception (just
// log it) because the topic has been deleted from Bridge without a referential integrity problem.
DynamoNotificationTopic hashKey = new DynamoNotificationTopic();
hashKey.setAppId(appId);
hashKey.setGuid(guid);
mapper.delete(hashKey);
// Delete criteria, if it exists.
if (existing.getCriteria() != null) {
criteriaDao.deleteCriteria(getCriteriaKey(guid));
}
// Delete from SNS.
try {
DeleteTopicRequest request = new DeleteTopicRequest().withTopicArn(existing.getTopicARN());
snsClient.deleteTopic(request);
} catch(AmazonServiceException e) {
LOG.warn("Bridge topic '" + existing.getName() + "' in app '" + existing.getAppId()
+ "' deleted, but SNS topic deletion threw exception", e);
}
}
@Override
public void deleteAllTopics(String appId) {
checkNotNull(appId);
List<NotificationTopic> topics = listTopics(appId, true);
// Delete them individually.
for (NotificationTopic topic : topics) {
deleteTopicPermanently(appId, topic.getGuid());
}
}
/**
* So we can find these in the AWS console, we give these a specifically formatted name.
*/
private String createSnsTopicName(NotificationTopic topic) {
return topic.getAppId() + "-" + config.getEnvironment().name().toLowerCase() + "-" + topic.getGuid();
}
// Generates the criteria key for the given topic guid.
private String getCriteriaKey(String topicGuid) {
return CRITERIA_KEY_PREFIX + topicGuid;
}
// Helper method to get the criteria key for a topic.
private String getCriteriaKey(NotificationTopic topic) {
return getCriteriaKey(topic.getGuid());
}
// Helper method to load criteria, which comes from another table.
private void loadCriteria(NotificationTopic topic) {
Criteria criteria = criteriaDao.getCriteria(getCriteriaKey(topic));
// There are two kinds notification topics: topics with criteria, and topics without. Topics with criteria
// have their subscribers auto-managed by Bridge server. Topics without need to be subscribed to manually.
// To ensure we keep this separation clear, only set a criteria into the topic if it exists.
if (criteria != null) {
topic.setCriteria(criteria);
}
}
// Helper method which saves the criteria, if it exists. Called by create and update.
private void persistCriteria(NotificationTopic topic) {
Criteria criteria = topic.getCriteria();
// Similarly, only save the criteria if one was provided.
if (criteria != null) {
topic.setCriteria(criteria);
criteria.setKey(getCriteriaKey(topic));
criteriaDao.createOrUpdateCriteria(criteria);
}
}
}
| 38.108949
| 120
| 0.697978
|
2f4972c504ac788872e70cf30c50a809a5af9590
| 5,981
|
package com.yan.web.controller.index;
import com.yan.api.persistence.DelegateService;
import com.yan.core.annotation.LogInject;
import com.yan.core.controller.BaseController;
import com.yan.dao.model.index.MenuModel;
import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
import org.slf4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* 名称:MainController<br>
* <p>
* 描述:首页主控制器,包含一些通用的方法(模板查看、菜单加载、文件下载...)<br>
*
* @author Yanzheng 严正<br>
* 时间:<br>
* 2017-09-11 09:10:21<br>
* 版权:<br>
* Copyright 2017 <a href="https://github.com/micyo202" target="_blank">https://github.com/micyo202</a>. All rights reserved.
*/
@Controller
public class IndexController extends BaseController {
/**
* 日志记录<br>
*/
@LogInject
private static Logger log;
/**
* 生成delegateMapper<br>
*/
@Autowired
private DelegateService delegateService;
/**
* 跳转到登录页<br>
*
* @return String 登录页路径
*/
@RequestMapping("/login")
public String login() {
if (this.isNull(this.getSessionUser())) {
return "login";
} else {
return "redirect:/";
}
}
/**
* 跳转错误页(包含404、500等一系列错误页)<br>
*
* @return String 错误页路径
*/
@RequestMapping("/{errorCode}/error")
public String error(@PathVariable String errorCode) {
System.out.println(errorCode);
return "error";
}
/**
* UI模板查看<br>
*
* @return String 模板页面地址
*/
@RequestMapping("/template")
public String template() {
return "template";
}
/**
* 通用文件下载<br>
*
* @param fileName 文件名称(数据库中保存的名称)
* @return ResponseEntity<byte[]> 下载的文件
*/
@RequestMapping("/{fileName}/download")
public ResponseEntity<byte[]> download(@PathVariable String fileName) {
return this.fileDownLoad(fileName);
}
/**
* 获取系统菜单<br>
*
* @return List<MenuModel> 菜单列表集合
*/
@RequestMapping("/{roleId}/menu")
@ResponseBody
public List<MenuModel> menu(@PathVariable String roleId) {
if ("admin".equals(this.getSessionUser().getUserType())) {
// 管理员菜单(在系统 xml 中配置)
return getMenuForXml();
} else {
// 一般用户菜单 general(根据角色获取对应菜单列表)
Map<String, Object> paramMap = new HashMap<>();
paramMap.put("menuId", "00000000000000000000000000000001");
paramMap.put("roleId", roleId);
paramMap.put("userId", this.getSessionUser().getUserId());
List<MenuModel> list = new ArrayList<>();
List<MenuModel> rootList = delegateService.selectList("com.yan.dao.mapper.index.IndexCustomMapper.getMenu", paramMap);
for (MenuModel menuModel : rootList) {
menuModel.setChildren(getMenu(menuModel.getId(), roleId));
list.add(menuModel);
}
return list;
}
}
/**
* 递归获取所有菜单信息<br>
*
* @param pid 菜单父ID
* @return List<MenuModel> 菜单列表集合
*/
private List<MenuModel> getMenu(String pid, String roleId) {
Map<String, Object> paramMap = new HashMap<>();
paramMap.put("menuId", pid);
paramMap.put("roleId", roleId);
paramMap.put("userId", this.getSessionUser().getUserId());
List<MenuModel> list = new ArrayList<>();
List<MenuModel> menuList = delegateService.selectList("com.yan.dao.mapper.index.IndexCustomMapper.getMenu", paramMap);
for (MenuModel menuModel : menuList) {
if (!this.isNull(menuModel.getId())) {
menuModel.setChildren(getMenu(menuModel.getId(), roleId));
}
list.add(menuModel);
}
return list;
}
/**
* 从 xml 中读取管理员菜单(adminMenu.xml)<br>
*
* @return List<MenuModel> 菜单列表集合
*/
@SuppressWarnings("unchecked")
private List<MenuModel> getMenuForXml() {
List<MenuModel> list = new ArrayList<>();
try {
// 获取需要读取的xml文件路径
InputStream inputStream = this.getClass().getResourceAsStream("/adminMenu.xml");
// 创建SAXReader的对象reader
SAXReader reader = new SAXReader();
// 通过reader对象的read方法加载adminMenu.xml文件,获取docuemnt对象。
Document document = reader.read(inputStream);
// 通过document对象获取根节点element
Element element = document.getRootElement();
List<Element> menus = element.elements();
for (Element menu : menus) {
MenuModel menuModelParent = new MenuModel();
List<MenuModel> childList = new ArrayList<>();
menuModelParent.setName(menu.attributeValue("name"));
menuModelParent.setIcon(this.isNull(menu.attributeValue("icon")) ? "zmdi zmdi-apps" : menu.attributeValue("icon"));
List<Element> menuItems = menu.elements();
for (Element menuItem : menuItems) {
MenuModel menuModelChild = new MenuModel();
menuModelChild.setName(menuItem.elementText("name"));
menuModelChild.setUrl(menuItem.elementText("url"));
childList.add(menuModelChild);
}
menuModelParent.setChildren(childList);
list.add(menuModelParent);
}
} catch (Exception e) {
log.error("读取 xml 菜单信息失败");
e.printStackTrace();
}
return list;
}
}
| 31.645503
| 131
| 0.608761
|
fd80af6349d941b992f7242e4daefee8625ebf07
| 1,143
|
/*
* Janssen Project software is available under the Apache License (2004). See http://www.apache.org/licenses/ for full text.
*
* Copyright (c) 2020, Janssen Project
*/
package io.jans.config.oxtrust;
import com.fasterxml.jackson.annotation.JsonPropertyOrder;
import java.io.Serializable;
/**
* Attribute mapping
*
* @author Yuriy Movchan Date: 10/23/2015
*/
@JsonPropertyOrder({ "source", "destination" })
public class CacheRefreshAttributeMapping implements Serializable {
private static final long serialVersionUID = 8040484460012448855L;
private String source;
private String destination;
public CacheRefreshAttributeMapping() {
}
public CacheRefreshAttributeMapping(String source, String destination) {
this.source = source;
this.destination = destination;
}
public String getSource() {
return source;
}
public void setSource(String source) {
this.source = source;
}
public String getDestination() {
return destination;
}
public void setDestination(String destination) {
this.destination = destination;
}
}
| 21.980769
| 124
| 0.697288
|
528293a6f2a45a7527046f20f685011aeef81180
| 2,003
|
/*
* JBoss, Home of Professional Open Source
* Copyright 2012, Red Hat Middleware LLC, and individual contributors
* by the @authors tag. See the copyright.txt in the distribution for a
* full listing of individual 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 org.jboss.shrinkwrap.resolver.api.maven.strategy;
import org.jboss.shrinkwrap.resolver.api.maven.coordinate.MavenDependency;
import org.jboss.shrinkwrap.resolver.api.maven.filter.MavenResolutionFilter;
/**
* {@link MavenResolutionStrategy} implementation where all {@link MavenDependency}s are accepted
*
* @author <a href="mailto:kpiwko@redhat.com">Karel Piwko</a>
* @author <a href="mailto:alr@jboss.org">Andrew Lee Rubinger</a>
*/
public enum AcceptAllStrategy implements MavenResolutionStrategy {
INSTANCE;
/**
* Returns a {@link MavenResolutionFilter} chain allowing all {@link MavenDependency}s to pass-through.
*
* @see org.jboss.shrinkwrap.resolver.api.maven.strategy.MavenResolutionStrategy#getResolutionFilters()
*/
@Override
public MavenResolutionFilter[] getResolutionFilters() {
return MavenResolutionFilterUtil.getEmptyChain();
}
/**
* {@inheritDoc}
*
* @see org.jboss.shrinkwrap.resolver.api.maven.strategy.MavenResolutionStrategy#getTransitiveExclusionPolicy()
*/
@Override
public TransitiveExclusionPolicy getTransitiveExclusionPolicy() {
return DefaultTransitiveExclusionPolicy.INSTANCE;
}
}
| 40.06
| 115
| 0.749376
|
6b5da7c0cdcf4bdc431a7ee789ecaa640fd4c1e9
| 1,267
|
// Copyright (C) 2014 The Android Open Source Project
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package com.google.gerrit.extensions.restapi;
/**
* Optional interface for {@link RestCollection}.
*
* <p>Collections that implement this interface can accept a {@code DELETE} directly on the
* collection itself.
*/
public interface AcceptsDelete<P extends RestResource> {
/**
* Handle deletion of a child resource by DELETE on the collection.
*
* @param parent parent collection handle.
* @param id id of the resource being created (optional).
* @return a view to perform the deletion.
* @throws RestApiException the view cannot be constructed.
*/
RestModifyView<P, ?> delete(P parent, IdString id) throws RestApiException;
}
| 37.264706
| 91
| 0.738753
|
a9b1cb334d9d11123c04b7368c303d0f17b65d42
| 954
|
package beerme;
import java.util.Date;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Table;
@Entity
@Table(name="event")
public class Event {
@Id
@Column(name="id")
@GeneratedValue
private long id;
@Column(name="datetime")
private Date datetime;
@Column(name="entrytype")
private String eventType;
@Column(name="comments")
private String comments;
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public Date getDatetime() {
return datetime;
}
public void setDatetime(Date datetime) {
this.datetime = datetime;
}
public String getEventType() {
return eventType;
}
public void setEventType(String eventType) {
this.eventType = eventType;
}
public String getComments() {
return comments;
}
public void setComments(String comments) {
this.comments = comments;
}
}
| 19.469388
| 45
| 0.731656
|
6e9bbeffe8cc9904e3af3cc465bcd0b74efb8d05
| 537
|
package org.goskyer.microserver.bio.listener;
import org.goskyer.microserver.bio.MicroConnection;
import org.goskyer.microserver.bio.ServerConfig;
import org.goskyer.microserver.bio.ServerState;
public abstract class ServerListener {
public abstract void onCreate(ServerConfig config, ServerState state);
public abstract void onStart(ServerConfig config, ServerState state);
public abstract void onAccept(final MicroConnection connection);
public abstract void onClose(ServerConfig config, ServerState state);
}
| 26.85
| 74
| 0.808194
|
680dceaa2f8aee27fc227c3eab19c0796038bcb2
| 5,317
|
package tests.restapi.airlockkey;
import java.io.IOException;
import org.apache.commons.lang3.RandomStringUtils;
import org.apache.wink.json4j.JSONArray;
import org.apache.wink.json4j.JSONException;
import org.apache.wink.json4j.JSONObject;
import org.testng.Assert;
import org.testng.annotations.AfterTest;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Parameters;
import org.testng.annotations.Test;
import tests.com.ibm.qautils.FileUtils;
import tests.restapi.AirlockUtils;
import tests.restapi.FeaturesRestApi;
import tests.restapi.OperationRestApi;
public class UpdateKeyPermissions {
protected String adminToken;
protected String m_url;
protected String operationsUrl;
protected String translationUrl;
protected String analyticsUrl;
protected String adminUser;
protected String adminPassword;
protected String m_appName;
protected String config;
protected AirlockUtils baseUtils;
protected String apikey;
protected OperationRestApi operApi;
private FeaturesRestApi f;
private String productLeadUser;
private String productLeadPassword;
private String editorUser;
private String editorPassword;
@BeforeClass
@Parameters({"url","translationsUrl","analyticsUrl","configPath", "operationsUrl","admin","adminPass","appName","editor","editorPass","productLead", "productLeadPass","productsToDeleteFile"})
public void init(String url,String t_url,String a_url, String configPath, String c_operationsUrl,String admin,String adminPass, String appName, String editor, String editorPass, String productLead, String productLeadPass, String productsToDeleteFile) throws IOException{
m_url = url;
operationsUrl = c_operationsUrl;
translationUrl = t_url;
analyticsUrl = a_url;
config = configPath;
adminUser = admin;
adminPassword = adminPass;
productLeadUser = productLead;
productLeadPassword = productLeadPass;
editorUser = editor;
editorPassword = editorPass;
operApi = new OperationRestApi();
operApi.setURL(c_operationsUrl);
f = new FeaturesRestApi();
f.setURL(m_url);
baseUtils = new AirlockUtils(m_url, a_url, t_url, configPath, "", adminUser, adminPassword, m_appName, productsToDeleteFile);
if(appName != null) {
m_appName = appName;
}
adminToken = baseUtils.setNewJWTToken(adminUser, adminPassword, m_appName);
if (adminToken == null){
Assert.fail("Can't set adminToken");
}
apikey = FileUtils.fileToString(config + "airlockkey/key_template1.txt", "UTF-8", false);
try {
operApi.resetUsersFromList(config + "airlockkey/original_users.txt", adminToken);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
/*
* Only owner or admin can update key
*/
@Test (description="create and update key using different permissions")
public void updateKey() throws Exception{
JSONObject json = populateKeyName();
JSONArray roles = new JSONArray();
roles.add("ProductLead");
roles.add("Editor");
json.put("roles", roles);
//update using owner token
String prodLeadsessionToken = baseUtils.setNewJWTToken(productLeadUser, productLeadPassword, m_appName);
String keyID = operApi.generateAirlockKey(json.toString(), prodLeadsessionToken);
Assert.assertFalse(keyID.contains("error"), "Can't create api key: " + keyID);
String response = operApi.getKey(keyID, prodLeadsessionToken);
Assert.assertFalse(response.contains("error"), "Can't get api key: " + response);
JSONObject jsonKey = new JSONObject(response);
roles = new JSONArray();
roles.add("ProductLead");
jsonKey.put("roles", roles);
response = operApi.updateKey(keyID, jsonKey.toString(), prodLeadsessionToken);
Assert.assertFalse(response.contains("error"), "Can't update api key: " + response);
//update using admin token
response = operApi.getKey(keyID, adminToken);
Assert.assertFalse(response.contains("error"), "Can't get api key: " + response);
jsonKey = new JSONObject(response);
roles = new JSONArray();
roles.add("ProductLead");
roles.add("Editor");
jsonKey.put("roles", roles);
response = operApi.updateKey(keyID, jsonKey.toString(), adminToken);
Assert.assertFalse(response.contains("error"), "Can't update api key: " + response);
//update using editor token
String editorToken = baseUtils.setNewJWTToken(editorUser, editorPassword, m_appName);
response = operApi.getKey(keyID, editorToken);
Assert.assertFalse(response.contains("error"), "Can't get api key: " + response);
jsonKey = new JSONObject(response);
roles = new JSONArray();
roles.add("Editor");
jsonKey.put("roles", roles);
response = operApi.updateKey(keyID, jsonKey.toString(), editorToken);
Assert.assertTrue(response.contains("error"), "Can't update api key: " + response);
}
@AfterTest (alwaysRun=true)
private void reset() throws Exception{
operApi.resetUsersFromList(config + "airlockkey/original_users.txt", adminToken);
baseUtils.deleteKeys(productLeadUser);
}
private JSONObject populateKeyName() throws JSONException{
JSONObject json = new JSONObject(apikey);
json.put("key", RandomStringUtils.randomAlphabetic(3));
return json;
}
}
| 34.751634
| 272
| 0.732744
|
1d4644b5b237d2ba1b08b572a9f047656a92eb8f
| 313
|
package com.darian.spring.demo.service.impl;
import com.darian.spring.demo.service.DemoService;
import com.darian.spring.framework.annotation.DarianService;
@DarianService
public class DemoServiceImpl implements DemoService {
public String get(String name) {
return "My name is " + name;
}
}
| 20.866667
| 60
| 0.753994
|
5448407d7a8170e6031d48606d0ff8d9b427cf44
| 2,283
|
package com.gempukku.swccgo.cards.set1.light;
import com.gempukku.swccgo.cards.AbstractCharacterDevice;
import com.gempukku.swccgo.common.*;
import com.gempukku.swccgo.filters.Filter;
import com.gempukku.swccgo.filters.Filters;
import com.gempukku.swccgo.game.PhysicalCard;
import com.gempukku.swccgo.game.SwccgGame;
import com.gempukku.swccgo.logic.modifiers.CancelsGameTextModifier;
import com.gempukku.swccgo.logic.modifiers.MayNotMoveModifier;
import com.gempukku.swccgo.logic.modifiers.Modifier;
import java.util.LinkedList;
import java.util.List;
/**
* Set: Premiere
* Type: Device
* Title: Restraining Bolt
*/
public class Card1_038 extends AbstractCharacterDevice {
public Card1_038() {
super(Side.LIGHT, 6, Title.Restraining_Bolt);
setLore("Fits in a special socket on a droid's body. When installed, restricts actions of droids, forcing them to follow orders. Can be operated remotely by a 'caller.'");
setGameText("Deploy on any droid at any site. Droid cannot move and cannot utilize its 'game text.' During your deploy phase, Restraining Bolt may be transferred (for free) to another droid at same site.");
addKeywords(Keyword.DEVICE_THAT_DEPLOYS_ON_DROIDS);
}
@Override
public boolean canBeDeployedOnOpponentsCharacter() {
return true;
}
@Override
protected Filter getGameTextValidDeployTargetFilter(SwccgGame game, PhysicalCard self, PlayCardOptionId playCardOptionId, boolean asReact) {
return Filters.and(Filters.droid, Filters.not(Icon.PRESENCE), Filters.at(Filters.site));
}
@Override
protected Filter getGameTextValidToUseDeviceFilter(final SwccgGame game, final PhysicalCard self) {
return Filters.and(Filters.droid, Filters.not(Icon.PRESENCE));
}
// TODO: Device transfer: Can transfer to any droid at same site, getTopLevelAction
@Override
protected List<Modifier> getGameTextWhileActiveInPlayModifiers(SwccgGame game, final PhysicalCard self) {
Filter hasAttached = Filters.hasAttached(self);
List<Modifier> modifiers = new LinkedList<Modifier>();
modifiers.add(new MayNotMoveModifier(self, hasAttached));
modifiers.add(new CancelsGameTextModifier(self, hasAttached));
return modifiers;
}
}
| 41.509091
| 214
| 0.755147
|
3f44c2ea6aafbffdc8c4a7aadc988fa49127b64b
| 418
|
// Generated by the protocol buffer compiler. DO NOT EDIT!
// source: tribuo-core-impl.proto
package org.tribuo.protos.core;
public interface ModHashCodeHasherProtoOrBuilder extends
// @@protoc_insertion_point(interface_extends:tribuo.core.ModHashCodeHasherProto)
com.google.protobuf.MessageOrBuilder {
/**
* <code>int32 dimension = 1;</code>
* @return The dimension.
*/
int getDimension();
}
| 26.125
| 85
| 0.739234
|
c828f2ee1c121ba237e75ed407ae7de4e0c7d23f
| 6,518
|
/*
* GridGain Community Edition Licensing
* Copyright 2019 GridGain Systems, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License") modified with Commons Clause
* Restriction; 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.
*
* Commons Clause Restriction
*
* The Software is provided to you by the Licensor under the License, as defined below, subject to
* the following condition.
*
* Without limiting other conditions in the License, the grant of rights under the License will not
* include, and the License does not grant to you, the right to Sell the Software.
* For purposes of the foregoing, “Sell” means practicing any or all of the rights granted to you
* under the License to provide to third parties, for a fee or other consideration (including without
* limitation fees for hosting or consulting/ support services related to the Software), a product or
* service whose value derives, entirely or substantially, from the functionality of the Software.
* Any license notice or attribution required by the License must also include this Commons Clause
* License Condition notice.
*
* For purposes of the clause above, the “Licensor” is Copyright 2019 GridGain Systems, Inc.,
* the “License” is the Apache License, Version 2.0, and the Software is the GridGain Community
* Edition software provided with this notice.
*/
package org.apache.ignite.internal;
import java.util.Collection;
import java.util.UUID;
import java.util.concurrent.atomic.AtomicInteger;
import org.apache.ignite.Ignite;
import org.apache.ignite.cluster.ClusterGroup;
import org.apache.ignite.cluster.ClusterNode;
import org.apache.ignite.internal.util.lang.GridAbsPredicate;
import org.apache.ignite.internal.util.typedef.F;
import org.apache.ignite.internal.util.typedef.P2;
import org.apache.ignite.messaging.MessagingListenActor;
import org.apache.ignite.testframework.GridTestUtils;
import org.apache.ignite.testframework.junits.common.GridCommonTest;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
/**
* Test for {@link org.apache.ignite.IgniteCluster}.
*/
@GridCommonTest(group = "Kernal Self")
@RunWith(JUnit4.class)
public class GridSelfTest extends ClusterGroupAbstractTest {
/** Nodes count. */
private static final int NODES_CNT = 4;
/** {@inheritDoc} */
@SuppressWarnings({"ConstantConditions"})
@Override protected void beforeTestsStarted() throws Exception {
assert NODES_CNT > 2;
for (int i = 0; i < NODES_CNT; i++)
startGrid(i);
waitForTopology(NODES_CNT);
}
/** {@inheritDoc} */
@Override protected ClusterGroup projection() {
return grid(0).cluster();
}
/** {@inheritDoc} */
@Override protected UUID localNodeId() {
return grid(0).localNode().id();
}
/** {@inheritDoc} */
@Override protected Collection<UUID> remoteNodeIds() {
return F.nodeIds(grid(0).cluster().forRemotes().nodes());
}
/** {@inheritDoc} */
@Test
@Override public void testRemoteNodes() throws Exception {
int size = remoteNodeIds().size();
String name = "oneMoreGrid";
try {
Ignite g = startGrid(name);
UUID joinedId = g.cluster().localNode().id();
assert projection().forRemotes().nodes().size() == size + 1;
assert F.nodeIds(projection().forRemotes().nodes()).contains(joinedId);
}
finally {
stopGrid(name);
}
}
/** {@inheritDoc} */
@Test
@Override public void testRemoteProjection() throws Exception {
ClusterGroup remotePrj = projection().forRemotes();
int size = remotePrj.nodes().size();
String name = "oneMoreGrid";
try {
Ignite g = startGrid(name);
UUID joinedId = g.cluster().localNode().id();
assert remotePrj.nodes().size() == size + 1;
assert F.nodeIds(remotePrj.nodes()).contains(joinedId);
}
finally {
stopGrid(name);
}
}
/**
* @throws Exception If failed.
*/
@Test
public void testAsyncListen() throws Exception {
final String hello = "HELLO!";
final String bye = "BYE!";
final Ignite g = grid(0);
final UUID locNodeId = g.cluster().localNode().id();
g.message().remoteListen(null, new MessagingListenActor<String>() {
@Override protected void receive(UUID nodeId, String rcvMsg) throws Throwable {
if (hello.equals(rcvMsg)) {
assertEquals(locNodeId, nodeId);
assertEquals(hello, rcvMsg);
stop(bye);
}
}
});
final AtomicInteger cnt = new AtomicInteger();
g.message().localListen(null, new P2<UUID, String>() {
@Override public boolean apply(UUID nodeId, String msg) {
if (msg.equals(bye))
cnt.incrementAndGet();
return true;
}
});
g.message().send(null, hello);
GridTestUtils.waitForCondition(new GridAbsPredicate() {
@Override public boolean apply() {
return cnt.get() == g.cluster().nodes().size();
}
}, 5000);
assertEquals(cnt.get(), g.cluster().nodes().size());
}
/**
* @throws Exception If failed.
*/
@Test
public void testForOthers() throws Exception {
ClusterNode node0 = grid(0).localNode();
ClusterNode node1 = grid(1).localNode();
ClusterNode node2 = grid(2).localNode();
ClusterNode node3 = grid(3).localNode();
ClusterGroup p1 = grid(0).cluster().forOthers(node0);
assertEquals(3, p1.nodes().size());
assertEquals(2, p1.forOthers(node1).nodes().size());
assertEquals(1, p1.forOthers(node1, node2).nodes().size());
assertEquals(1, grid(0).cluster().forOthers(node1, node2, node3).nodes().size());
}
}
| 32.753769
| 101
| 0.641608
|
6d726084d61879d1f6347531b5e7cf6d02f3b5f3
| 1,357
|
package com.example.jimssgym;
import android.content.ClipData;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
public class QuickScanCardViewHolder extends RecyclerView.ViewHolder {
public View view;
public ClipData.Item currentItem;
private Context context;
ImageView exerciseImage;
TextView exerciseTitle, exerciseArea;
public QuickScanCardViewHolder(@NonNull final View itemView) {
super(itemView);
this.exerciseImage = itemView.findViewById(R.id.exerciseImage);
this.exerciseTitle = itemView.findViewById(R.id.FName);
this.exerciseArea = itemView.findViewById(R.id.LName);
view = itemView;
context = view.getContext();
view.setOnClickListener(new View.OnClickListener() {
@Override public void onClick(View v) {
Bundle extras = new Bundle();
extras.putCharSequence("QR_RESULT", exerciseTitle.getText());
Intent intent = new Intent(context, QuickScanActivity.class);
intent.putExtras(extras);
context.startActivity(intent);
}
});
}
}
| 33.097561
| 77
| 0.694915
|
e213ee16c1da751deda928c3517486f2c9c0b276
| 6,548
|
/*
* 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.camel.quarkus.component.jslt.it;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;
import javax.enterprise.context.ApplicationScoped;
import javax.inject.Inject;
import javax.ws.rs.Consumes;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import org.apache.camel.CamelExecutionException;
import org.apache.camel.Exchange;
import org.apache.camel.ProducerTemplate;
import org.apache.camel.component.jslt.JsltConstants;
import org.jboss.logging.Logger;
import static java.util.Collections.singletonMap;
@Path("/jslt")
@ApplicationScoped
public class JsltResource {
private static final Logger LOG = Logger.getLogger(JsltResource.class);
@Inject
ProducerTemplate template;
@Path("/transformInputStream")
@GET
@Consumes(MediaType.TEXT_PLAIN)
@Produces(MediaType.TEXT_PLAIN)
public String transformInputStream(String input) throws IOException {
LOG.debugf("Invoking transformInputStream(%s)", input);
try (InputStream is = new ByteArrayInputStream(input.getBytes(StandardCharsets.UTF_8))) {
return template.requestBody("jslt:demoPlayground/transformation.json", is, String.class);
}
}
@Path("/transformInvalidBody")
@GET
@Produces(MediaType.TEXT_PLAIN)
public String transformInvalidBody() {
LOG.debugf("Invoking transformInvalidBody()");
try {
template.requestBody("jslt:demoPlayground/transformation.json", 4, String.class);
} catch (CamelExecutionException vex) {
return vex.getCause().getMessage();
}
return null;
}
@Path("/transformString")
@GET
@Consumes(MediaType.TEXT_PLAIN)
@Produces(MediaType.TEXT_PLAIN)
public String transformString(String input) {
LOG.debugf("Invoking transformString(%s)", input);
return template.requestBody("jslt:demoPlayground/transformation.json", input, String.class);
}
@Path("/transformFromHeaderWithPrettyPrint")
@GET
@Consumes(MediaType.TEXT_PLAIN)
@Produces(MediaType.TEXT_PLAIN)
public String transformFromHeaderWithPrettyPrint(String input) throws IOException {
LOG.debugf("Invoking transformFromHeaderWithPrettyPrint(%s)", input);
Map<String, Object> headers = singletonMap(JsltConstants.HEADER_JSLT_RESOURCE_URI,
"demoPlayground/transformation.json");
try (InputStream is = new ByteArrayInputStream(input.getBytes(StandardCharsets.UTF_8))) {
String uri = "jslt:demoPlayground/transformation.json?prettyPrint=true&allowTemplateFromHeader=true";
return template.requestBodyAndHeaders(uri, is, headers, String.class);
}
}
@Path("/transformInputStreamWithFilter")
@GET
@Consumes(MediaType.TEXT_PLAIN)
@Produces(MediaType.TEXT_PLAIN)
public String transformInputStreamWithFilter(String input) throws IOException {
LOG.debugf("Invoking transformInputStreamWithFilter(%s)", input);
try (InputStream is = new ByteArrayInputStream(input.getBytes(StandardCharsets.UTF_8))) {
String uri = "jsltWithFilter:objectFilter/transformation.json";
return template.requestBody(uri, is, String.class);
}
}
@Path("/transformInputStreamWithVariables")
@GET
@Consumes(MediaType.TEXT_PLAIN)
@Produces(MediaType.TEXT_PLAIN)
public String transformInputStreamWithVariables(String input) throws IOException {
LOG.debugf("Invoking transformInputStreamWithVariables(%s)", input);
Map<String, Object> headers = new HashMap<>();
headers.put("published", "2020-05-26T16:00:00+02:00");
headers.put("type", "Controller");
// infinite recursion value that cannot be serialized by camel-jslt
headers.put("infinite", JsltConfiguration.createInfiniteRecursionObject());
try (InputStream is = new ByteArrayInputStream(input.getBytes(StandardCharsets.UTF_8))) {
String uri = "jslt:withVariables/transformation.json";
return template.requestBodyAndHeaders(uri, is, headers, String.class);
}
}
@Path("/transformInputStreamWithVariablesAndProperties")
@GET
@Consumes(MediaType.TEXT_PLAIN)
@Produces(MediaType.TEXT_PLAIN)
public String transformInputStreamWithVariablesAndProperties(String input) throws IOException {
LOG.debugf("Invoking transformInputStreamWithVariablesAndProperties(%s)", input);
try (InputStream is = new ByteArrayInputStream(input.getBytes(StandardCharsets.UTF_8))) {
String uri = "jslt:withVariables/transformationWithProperties.json?allowContextMapAll=true";
Exchange ex = template.request(uri, e -> {
e.getMessage().setBody(is);
e.getMessage().setHeader("published", "2020-05-26T16:00:00+02:00");
e.getMessage().setHeader("type", "Controller");
e.setProperty("infinite", JsltConfiguration.createInfiniteRecursionObject());
e.setProperty("instance", "559e934f-b32b-47ab-8327-bd50e2bdc029");
});
return ex.getMessage().getBody(String.class);
}
}
@Path("/transformWithFunction")
@GET
@Produces(MediaType.TEXT_PLAIN)
public String transformWithFunction() {
LOG.debugf("Invoking transformWithFunction()");
Map<String, Object> headers = singletonMap(JsltConstants.HEADER_JSLT_STRING, "power(2, 10)");
return template.requestBodyAndHeaders("jsltWithFunction:dummy", "{}", headers, String.class);
}
}
| 41.18239
| 113
| 0.713806
|
f6a435b679ea5218fecbbd29e8da88020a0a0d29
| 1,000
|
package com.cannizarro.securitycamera.webRTC;
import android.util.Log;
import org.webrtc.SdpObserver;
import org.webrtc.SessionDescription;
/**
* Webrtc_Step2
* Created by vivek-3102 on 11/03/17.
*/
public class CustomSdpObserver implements SdpObserver {
private String tag;
public CustomSdpObserver(String logTag) {
tag = this.getClass().getCanonicalName();
this.tag = this.tag + " " + logTag;
}
@Override
public void onCreateSuccess(SessionDescription sessionDescription) {
Log.d(tag, "onCreateSuccess() called with: sessionDescription = [" + sessionDescription + "]");
}
@Override
public void onSetSuccess() {
Log.d(tag, "onSetSuccess() called");
}
@Override
public void onCreateFailure(String s) {
Log.d(tag, "onCreateFailure() called with: s = [" + s + "]");
}
@Override
public void onSetFailure(String s) {
Log.d(tag, "onSetFailure() called with: s = [" + s + "]");
}
}
| 22.222222
| 103
| 0.642
|
295d36da2bc8cd848d5a7e7d21668cb029761d38
| 149
|
package prosayj.thinking.spring4.assemblybeanhighlevel.conditional.restfun;
/**
* MagicBean
*
* @author yangjian
*/
public class MagicBean {
}
| 13.545455
| 75
| 0.744966
|
becd8dd8eb8fd53ec59371e96f9199472179ade8
| 6,972
|
package Compilador.Lexical;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.PushbackInputStream;
/**
*
* @author pedro
*/
public class LexicalAnalysis {
private int line;
private PushbackInputStream input;
private SymbolTable st = new SymbolTable();
private TokenType lastType;
private int identLevel = 0;
public LexicalAnalysis(String filename) throws LexicalException {
try {
input = new PushbackInputStream(new FileInputStream(filename));
} catch (Exception e) {
throw new LexicalException("Unable to open file");
}
line = 1;
}
public void close() throws Exception {
input.close();
}
public int line() {
return this.line;
}
public Lexeme nextToken() throws IOException {
Lexeme lex = new Lexeme("", TokenType.END_OF_FILE);
int c, e = 1;
while (e != 9 && e != 10){
c = input.read();
//System.out.printf("[LOG] - %d\n", (int)c);
switch (e){
case 1:
if (c == -1)
e = 10;
else if (c == ' ' || c == '\t' || c == '\n' || c == '\r'){
e = 1;
if (c == '\n')
this.line++;
}
else if (c == '{')
e = 2;
else if (Character.isDigit(c)){
lex.token += (char) c;
e = 3;
}
else if (c == '!' || c == '='){
lex.token += (char) c;
e = 4;
}
else if(c == '<' || c == '>'){
lex.token += (char) c;
e = 5;
}
else if(Character.isLetter(c)){
lex.token += (char) c;
e = 7;
}
else if (c == '\"'){
e = 8;
}
else if(c == ';' || c == ',' || c == '(' || c == ')' || c == '+' || c == '*' || c == '/' || c =='-'){
lex.token += (char)c;
e = 9;
}
else {
lex.token += (char) c;
lex.type = TokenType.INVALID_TOKEN;
e = 10;
}
break;
case 2:
if (c == '}'){
e = 1;
this.line++;
}
if(c == -1){
e = 10;
}
break;
case 3:
if (Character.isDigit(c)){
lex.token += (char) c;
} else {
if (c != -1 && c != '.')
input.unread(c);
if(c == '.'){
lex.token += (char) c;
e = 6;
}
else {
lex.type = TokenType.CONST_INT;
e = 10;
}
}
break;
case 4:
if (c == '='){
lex.token += (char) c;
e = 9;
} else {
if (c == -1)
lex.type = TokenType.UNEXPECTED_EOF;
else
e = 9;
}
break;
case 5: //eu que fiz
if(c == '='){
lex.token += (char) c;
}
else{
if(c == -1){
lex.type = TokenType.UNEXPECTED_EOF;
}
else{
input.unread(c);
}
}
e = 9;
break;
case 6://eu que fiz
if (Character.isDigit(c)){
lex.token += (char) c;
}
else {
if (c != -1){
input.unread(c);
}
lex.type = TokenType.CONST_FLOAT;
e = 10;
}
break;
case 7:
if (Character.isDigit(c) || Character.isLetter(c)){
lex.token += (char) c;
} else {
if (c != -1)
input.unread(c);
e = 9;
}
break;
case 8:
if (c == '\"'){
e = 10;
lex.type = TokenType.LITERAL;
} else {
if (c == -1){
e = 10;
lex.type = TokenType.UNEXPECTED_EOF;
} else
lex.token += (char) c;
}
break;
}
}
if (e == 9){
if (st.contains(lex.token)){
lex.type = st.find(lex.token).getTokenType();
if(lex.type != TokenType.VAR_FLT ||lex.type != TokenType.VAR_INT ||lex.type != TokenType.VAR_STR){
if(lex.type == TokenType.THEN || lex.type == TokenType.DO){
this.identLevel++;
}
else if(lex.type == TokenType.END){
this.identLevel--;
}
else if(lex.type == TokenType.INT || lex.type == TokenType.FLOAT || lex.type == TokenType.STRING ){
this.lastType = lex.type;
} else if(lex.type == TokenType.DOT_COMMA){
this.lastType = null;
}
}
/*EXPLODE ERRO DE VARIAVEL JA DECLARADA*/
if(lex.type == TokenType.VAR_FLT ||lex.type == TokenType.VAR_INT ||lex.type == TokenType.VAR_STR) {
if(this.lastType != null){
System.err.printf ("[PREVIUS DECLARATION ERROR] LINE - %d: %s\n", this.line, lex.token);
System.exit(0);
}
}
}
else{
lex.type = st.createVar(lex.token, this.identLevel, this.lastType);
}
}
return lex;
}
}
| 35.035176
| 121
| 0.301061
|
8eccefaf268ade927a2bcdf899356802269c7ba2
| 7,957
|
package com.dldhk97.kumohcafeteriaviewer.receiver;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.util.Log;
import androidx.core.app.NotificationCompat;
import androidx.preference.PreferenceManager;
import com.dldhk97.kumohcafeteriaviewer.MainActivity;
import com.dldhk97.kumohcafeteriaviewer.R;
import com.dldhk97.kumohcafeteriaviewer.data.DatabaseManager;
import com.dldhk97.kumohcafeteriaviewer.data.FavoriteManager;
import com.dldhk97.kumohcafeteriaviewer.data.MenuManager;
import com.dldhk97.kumohcafeteriaviewer.data.NotificationItemManager;
import com.dldhk97.kumohcafeteriaviewer.model.Item;
import com.dldhk97.kumohcafeteriaviewer.model.Menu;
import com.dldhk97.kumohcafeteriaviewer.model.NotificationItem;
import com.dldhk97.kumohcafeteriaviewer.model.WeekMenus;
import com.dldhk97.kumohcafeteriaviewer.utility.DateUtility;
import java.util.Calendar;
public class BroadcastReceiver extends android.content.BroadcastReceiver {
public static String ACTION_USER_NOTIFICATION = "com.dldhk97.kumohacfeteriaviewer.receiver.BroadcastReceiver";
@Override
public void onReceive(Context context, Intent intent) {
if(intent.getAction().equals(ACTION_USER_NOTIFICATION)){
NotificationManager notificationmanager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
// 알림 ID 가져오기
String notificationItemID = intent.getStringExtra("notificationItemID");
if(notificationItemID == null){
Log.d("aaaaa", "notificationItemID is null");
return;
}
DatabaseManager.getInstance().setContextIfNotExist(context); // DB매니저가 인스턴스화되지 않으면 초기화. 이거안하면 어플 실행안됬을때 터짐.
// 알림 객체 가져오기
NotificationItem notificationItem = NotificationItemManager.getInstance().findItem(notificationItemID);
if(notificationItem == null){
Log.d("aaaaa", "notificationItem is null");
return;
}
// 설정 정보 가져오기
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);
// 알림 객체가 유효한지(deactivated 된지, 너무 늦게 알림발생했는지) 체크
if(!isNotificationItemValid(notificationItem, prefs)){
Log.d("aaaaa", "notificationItem is invalid");
return;
}
// 푸시 타이틀 및 내용 설정
String pushTitle = notificationItem.getCafeteriaType().toString() + " - " + notificationItem.getMealTimeType() + " [" + notificationItem.getHour() + ":" + notificationItem.getMin() + "]";
// 푸시컨텐츠가 없으면 알릴 필요 없다.
Menu menu = getMenuFromMenuManager(notificationItem);
if(menu == null) {
Log.d("aaaaa", "Menu is null");
return;
}
// 찜목록 체크. "찜목록만 알림 설정"이 꺼져있는 경우 그냥 true 반환함.
if(!isFavoriteIncluded(menu, prefs)){
Log.d("aaaaa", "notificationItem is invalid");
return;
}
// 알림 빌더 생성
boolean ring = prefs.getBoolean("ring", true);
boolean vibrate = prefs.getBoolean("vibrate", true);
String menuText = menu.toString();
String menuSummary = menuText.replace("\n",", ");;
NotificationCompat.Builder builder = buildNotification(context, pushTitle, menuSummary, menuText, ring, vibrate);
// 알림
notificationmanager.notify(1, builder.build());
}
}
private static int validTimeMil = 600000; // 10분
private boolean isNotificationItemValid(NotificationItem notificationItem, SharedPreferences prefs){
// 알림 아이템이 deactivated 인 경우
if(!notificationItem.isActivated()){
Log.d("aaaaa", "notificationItem is deactivated");
return false;
}
// 알림이 10분 지나서 동작하면 유효하지 않은 알림으로 처리.
Calendar targetTime = Calendar.getInstance();
targetTime.set(Calendar.HOUR_OF_DAY, notificationItem.getHour());
targetTime.set(Calendar.MINUTE, notificationItem.getMin());
targetTime.set(Calendar.SECOND, 0);
targetTime.set(Calendar.MILLISECOND, 0);
Calendar now = Calendar.getInstance();
long diffMil = Calendar.getInstance().getTimeInMillis() - targetTime.getTimeInMillis();
if(diffMil >= validTimeMil){
Log.d("aaaaa", "notificationItem time over : " + diffMil);
return false;
}
// 주말이면 알리지 않음 체크되있으면, 주말인지 검사함.
boolean no_notify_holiday = prefs.getBoolean("no_notify_holiday", false);
if(no_notify_holiday){
int dayOfWeek = Calendar.getInstance().get(Calendar.DAY_OF_WEEK);
if(dayOfWeek == 1 || dayOfWeek == 7){
Log.d("aaaaa", "today is not holiday. dayofWeek : " + dayOfWeek);
return false;
}
}
return true;
}
// 메뉴 매니저에서 메뉴 객체 가져오기
private Menu getMenuFromMenuManager(NotificationItem notificationItem){
Menu menu = null;
try {
Calendar today = DateUtility.remainOnlyDate(Calendar.getInstance());
WeekMenus weekMenus = MenuManager.getInstance().getWeekMenus(notificationItem.getCafeteriaType(), today, false);
for(Menu m : weekMenus.get(today).getMenus()){
if(m.getCafeteriaType() == notificationItem.getCafeteriaType()){
menu = m;
break;
}
}
} catch (Exception e) {
e.printStackTrace();
}
return menu;
}
// 찜목록 체크
private boolean isFavoriteIncluded(Menu menu, SharedPreferences prefs){
// 찜목록만 알리는 경우 체크
boolean favorite_only = prefs.getBoolean("favorite_only", false);
if(favorite_only){
try{
boolean isFavoriteContains = false;
for(Item i : FavoriteManager.getInstance().getCurrentItems()){
if(menu.toString().contains(i.getItemName())){
isFavoriteContains = true;
break;
}
}
if(!isFavoriteContains){
Log.d("aaaaa", "Favorite is not contained.");
return false;
}
}
catch (Exception e){
e.printStackTrace();
}
}
return true;
}
// 알림 생성
private NotificationCompat.Builder buildNotification(Context context, String contentTitle, String contentTextSummary, String contentText, boolean ring, boolean vibrate){
PendingIntent pendingIntent = PendingIntent.getActivity(context, 0, new Intent(context, MainActivity.class), PendingIntent.FLAG_UPDATE_CURRENT);
NotificationCompat.Builder builder = new NotificationCompat.Builder(context);
builder.setSmallIcon(R.drawable.ic_menu_main).setTicker("HETT").setWhen(System.currentTimeMillis())
.setNumber(1).setContentTitle(contentTitle).setContentText(contentTextSummary)
.setContentIntent(pendingIntent).setAutoCancel(true)
.setStyle(new NotificationCompat.BigTextStyle().bigText(contentText));
if(ring && vibrate){
builder.setDefaults(Notification.DEFAULT_SOUND | Notification.DEFAULT_VIBRATE | Notification.DEFAULT_LIGHTS);
Log.d("aaaaa", "Notification ALL");
}
else if(ring){
builder.setDefaults(Notification.DEFAULT_SOUND);
Log.d("aaaaa", "Notification SOUND ONLY");
}
else if(vibrate){
builder.setDefaults(Notification.DEFAULT_VIBRATE);
Log.d("aaaaa", "Notification VIBRATION ONLY");
}
return builder;
}
}
| 41.227979
| 199
| 0.631896
|
fe8a388b50698cc46afa0485b203d3ca656760db
| 5,177
|
/*
* Copyright (c) 2018, Lawrence Livermore National Security, LLC. Produced at the Lawrence Livermore National Laboratory
* CODE-743439.
* All rights reserved.
* This file is part of CCT. For details, see https://github.com/LLNL/coda-calibration-tool.
*
* Licensed under the Apache License, Version 2.0 (the “Licensee”); you may not use this file except in compliance with the License. You may obtain a copy of the License at:
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an “AS IS” BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and limitations under the license.
*
* This work was performed under the auspices of the U.S. Department of Energy
* by Lawrence Livermore National Laboratory under Contract DE-AC52-07NA27344.
*/
package llnl.gnem.core.gui.plotting.plotobject;
import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Shape;
import java.awt.font.FontRenderContext;
import java.awt.font.TextLayout;
import java.awt.geom.AffineTransform;
import llnl.gnem.core.gui.plotting.HorizAlignment;
import llnl.gnem.core.gui.plotting.JBasicPlot;
import llnl.gnem.core.gui.plotting.VertAlignment;
import llnl.gnem.core.gui.plotting.VertPinEdge;
import llnl.gnem.core.gui.plotting.transforms.Coordinate;
import llnl.gnem.core.gui.plotting.transforms.CoordinateTransform;
/**
* Text that is pinned in the vertical direction a fixed amount from one of the
* plot's edges. In the horizontal direction, the text is fixed to a data value.
* The effect is that upon zooming, the text stays the same distance from the
* edge (vertically) but floats to the new position of the X-value.
*
* @author Doug Dodge
*/
public class YPinnedText extends BasicText {
/**
* Constructor for the YPinnedText object
*
* @param x
* The X-data value (real-world) of the text
* @param y
* The vertical offset in mm from the plot edge
* @param text
* The text string
* @param vp
* The plot edge to pin to ( TOP, BOTTOM )
* @param fontName
* The name of the font used to render the text
* @param fontSize
* The size of the font used to render the text
* @param textC
* The color of the text
* @param hAlign
* The horizontal alignment of the text relative to the pin
* point.
* @param vAlign
* The vertical alignment of the text relative to the pin point.
*/
public YPinnedText(double x, double y, String text, VertPinEdge vp, String fontName, double fontSize, Color textC, HorizAlignment hAlign, VertAlignment vAlign) {
super(text, fontName, fontSize, textC, hAlign, vAlign);
_X = x;
_Y = y;
V_Pin = vp;
}
/**
* Constructor for the YPinnedText object
*
* @param x
* The X-data value (real-world) of the text
* @param y
* The vertical offset in mm from the plot edge
* @param text
* The text string
*/
public YPinnedText(double x, double y, String text) {
super(text);
_X = x;
_Y = y;
V_Pin = VertPinEdge.TOP;
}
/**
* render this text string
*
* @param g
* The graphics context on which to render the text
* @param owner
* The JBasicPlot that owns this text
*/
public void render(Graphics g, JBasicPlot owner) {
if (!visible || _Text.length() < 1 || !owner.getCanDisplay())
return;
// Remove any pre-existing regions before creating new...
region.clear();
int yOffset = owner.getUnitsMgr().getVertUnitsToPixels(_Y);
CoordinateTransform ct = owner.getCoordinateTransform();
Coordinate coord = new Coordinate(0.0, 0.0, _X, 0.0);
ct.WorldToPlot(coord);
int xval = (int) coord.getX();
int yval = V_Pin == VertPinEdge.TOP ? owner.getPlotTop() + yOffset : owner.getPlotTop() + owner.getPlotHeight() - yOffset;
Graphics2D g2d = (Graphics2D) g;
// Save old color
Color oldColor = g2d.getColor();
// Create new font and color
g2d.setColor(_Color);
// Layout and render text
TextLayout textTl = new TextLayout(_Text, new Font(_FontName, Font.PLAIN, (int) _FontSize), new FontRenderContext(null, false, false));
float xshift = getHorizontalAlignmentOffset(textTl);
float yshift = getVerticalAlignmentOffset(textTl);
textTl.draw(g2d, xval + xshift, yval + yshift);
AffineTransform textAt = new AffineTransform();
textAt.translate(xval + xshift, yval + yshift);
Shape s = textTl.getOutline(textAt);
addToRegion(s.getBounds2D());
// restore old color
g2d.setColor(oldColor);
}
private double _X;
private double _Y;
private VertPinEdge V_Pin;
}
| 38.634328
| 209
| 0.655206
|
1e6a8384fdb65ef93b4e6f7d0f391133de2bc386
| 513
|
package js.format;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Locale;
/**
* Standard date format - 1964-03-15
*
* @author Iulian Rotaru
* @version final
*/
public final class StandardDate extends DateTimeFormat {
/** Constant for standard date format. */
private static final String STANDARD_FORMAT = "yyyy-MM-dd";
@Override
protected DateFormat createDateFormat(Locale locale) {
return new SimpleDateFormat(STANDARD_FORMAT, locale);
}
}
| 23.318182
| 61
| 0.723197
|
9e432ef77f68bd118892b9fd41c528fdabaec07b
| 538
|
package com.tiknil.boilerplate.fragments;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.View;
/**
* Classe Fragment di base da cui tutti gli altri fragment derivano
*
* @TiKnil
*/
public class BaseFragment extends Fragment {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
@Override
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
}
}
| 22.416667
| 69
| 0.730483
|
72ee072ebd6853474878cd365985ebe7953612f8
| 15,369
|
/*
* Copyright 2018 Red Hat, Inc. and/or its affiliates.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* 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.jbpm.process.workitem.jira;
import java.net.URI;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import com.atlassian.jira.rest.client.IssueRestClient;
import com.atlassian.jira.rest.client.JiraRestClient;
import com.atlassian.jira.rest.client.MetadataRestClient;
import com.atlassian.jira.rest.client.ProgressMonitor;
import com.atlassian.jira.rest.client.ProjectRestClient;
import com.atlassian.jira.rest.client.SearchRestClient;
import com.atlassian.jira.rest.client.UserRestClient;
import com.atlassian.jira.rest.client.domain.BasicIssue;
import com.atlassian.jira.rest.client.domain.Comment;
import com.atlassian.jira.rest.client.domain.Issue;
import com.atlassian.jira.rest.client.domain.IssueType;
import com.atlassian.jira.rest.client.domain.SearchResult;
import com.atlassian.jira.rest.client.domain.Transition;
import com.atlassian.jira.rest.client.domain.User;
import com.atlassian.jira.rest.client.domain.input.IssueInput;
import com.atlassian.jira.rest.client.domain.input.TransitionInput;
import org.drools.core.process.instance.impl.WorkItemImpl;
import org.jbpm.bpmn2.handler.WorkItemHandlerRuntimeException;
import org.jbpm.process.workitem.core.TestWorkItemManager;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.runners.MockitoJUnitRunner;
import static org.junit.Assert.*;
import static org.mockito.Matchers.anyString;
import static org.mockito.Mockito.*;
@RunWith(MockitoJUnitRunner.class)
public class JiraWorkitemHandlerTest {
@Mock
JiraAuth auth;
@Mock
IssueRestClient issueRestClient;
@Mock
JiraRestClient jiraRestClient;
@Mock
MetadataRestClient metadataRestClient;
@Mock
ProjectRestClient projectRestClient;
@Mock
SearchRestClient searchRestClient;
@Mock
UserRestClient userRestClient;
@Mock
SearchResult searchResults;
@Mock
User user;
private URI testURI = URI.create("http://testURI.com/test");
@Before
public void setUp() {
try {
when(auth.getIssueRestClient()).thenReturn(issueRestClient);
when(auth.getMetaDataRestClient()).thenReturn(metadataRestClient);
when(auth.getProjectRestClient()).thenReturn(projectRestClient);
when(auth.getSearchRestClient()).thenReturn(searchRestClient);
when(auth.getUserRestClient()).thenReturn(userRestClient);
// metadataclient
IssueType testIssueType = new IssueType(testURI,
1L,
"testIssueType",
false,
"test descriptoin",
testURI);
List<IssueType> testIssueTypes = new ArrayList<>();
testIssueTypes.add(testIssueType);
when(metadataRestClient.getIssueTypes(any(ProgressMonitor.class))).thenReturn(testIssueTypes);
// issuerestclient
BasicIssue basicIssue = new BasicIssue(testURI,
"testIssueKey");
when(issueRestClient.createIssue(any(IssueInput.class),
any(ProgressMonitor.class))).thenReturn(basicIssue);
Issue issue = new Issue("",
null,
"testIssueKey",
null,
null,
null,
"",
null,
null,
null,
null,
null,
null,
null,
null,
null,
null,
null,
null,
null,
null,
null,
null,
null,
null,
null,
null,
null,
null,
null);
when(issueRestClient.getIssue(anyString(),
any(ProgressMonitor.class))).thenReturn(issue);
doNothing().when(issueRestClient).addComment(any(ProgressMonitor.class),
any(URI.class),
any(Comment.class));
Transition testTransition = new Transition("Resolve Issue",
1,
null);
List<Transition> testAllTransitions = new ArrayList<>();
testAllTransitions.add(testTransition);
when(issueRestClient.getTransitions(any(URI.class),
any(ProgressMonitor.class))).thenReturn(testAllTransitions);
doNothing().when(issueRestClient).transition(any(URI.class),
any(TransitionInput.class),
any(ProgressMonitor.class));
// searchrestclient
List<BasicIssue> testSearchResults = new ArrayList<>();
testSearchResults.add(basicIssue);
when(searchRestClient.searchJql(anyString(),
any(ProgressMonitor.class))).thenReturn(searchResults);
when(searchResults.getIssues()).thenReturn(testSearchResults);
// userrestclient
when(userRestClient.getUser(anyString(),
any(ProgressMonitor.class))).thenReturn(user);
} catch (Exception e) {
fail(e.getMessage());
}
}
@Test
public void testCreateIssue() throws Exception {
TestWorkItemManager manager = new TestWorkItemManager();
WorkItemImpl workItem = new WorkItemImpl();
workItem.setParameter("ProjectKey",
"testJiraProject");
workItem.setParameter("IssueSummary",
"test issue summary");
workItem.setParameter("IssueDescription",
"this is test issue description");
workItem.setParameter("IssueType",
"testIssueType");
workItem.setParameter("AssigneeName",
"testAssigneeName");
workItem.setParameter("ReporterName",
"testReporterName");
workItem.setParameter("ComponentName",
"testComponentName");
CreateIssueWorkitemHandler handler = new CreateIssueWorkitemHandler("testusername",
"testpassword",
"testjiraurl");
handler.setAuth(auth);
handler.executeWorkItem(workItem,
manager);
assertNotNull(manager.getResults());
assertEquals(1,
manager.getResults().size());
assertTrue(manager.getResults().containsKey(workItem.getId()));
assertTrue((manager.getResults().get(workItem.getId())).get("CreatedIssueKey") instanceof String);
String cretedJiraKey = (String) manager.getResults().get(workItem.getId()).get("CreatedIssueKey");
assertNotNull(cretedJiraKey);
assertEquals("testIssueKey",
cretedJiraKey);
}
@Test(expected = WorkItemHandlerRuntimeException.class)
public void testCreateIssueInvalidParams() throws Exception {
TestWorkItemManager manager = new TestWorkItemManager();
WorkItemImpl workItem = new WorkItemImpl();
CreateIssueWorkitemHandler handler = new CreateIssueWorkitemHandler("testusername",
"testpassword",
"testjiraurl");
handler.setAuth(auth);
handler.executeWorkItem(workItem,
manager);
assertNotNull(manager.getResults());
assertEquals(0,
manager.getResults().size());
}
@Test
public void testJqlSearch() throws Exception {
TestWorkItemManager manager = new TestWorkItemManager();
WorkItemImpl workItem = new WorkItemImpl();
workItem.setParameter("SearchQuery",
"test jql query");
JqlSearchWorkitemHandler handler = new JqlSearchWorkitemHandler("testusername",
"testpassword",
"testjiraurl");
handler.setAuth(auth);
handler.executeWorkItem(workItem,
manager);
assertNotNull(manager.getResults());
assertEquals(1,
manager.getResults().size());
assertTrue(manager.getResults().containsKey(workItem.getId()));
assertTrue((manager.getResults().get(workItem.getId())).get("SearchResults") instanceof Map);
Map<String, String> searchResults = (Map<String, String>) manager.getResults().get(workItem.getId()).get("SearchResults");
assertNotNull(searchResults);
assertEquals(1,
searchResults.size());
}
@Test(expected = WorkItemHandlerRuntimeException.class)
public void testJqlSearchInvalidParams() throws Exception {
TestWorkItemManager manager = new TestWorkItemManager();
WorkItemImpl workItem = new WorkItemImpl();
JqlSearchWorkitemHandler handler = new JqlSearchWorkitemHandler("testusername",
"testpassword",
"testjiraurl");
handler.setAuth(auth);
handler.executeWorkItem(workItem,
manager);
assertNotNull(manager.getResults());
assertEquals(0,
manager.getResults().size());
}
@Test
public void testAddComment() throws Exception {
TestWorkItemManager manager = new TestWorkItemManager();
WorkItemImpl workItem = new WorkItemImpl();
workItem.setParameter("IssueKey",
"testIssueKey");
workItem.setParameter("Comment",
"testComment");
workItem.setParameter("Commenter",
"testCommenter");
workItem.setParameter("CommentVisibleTo",
"testVisibilityGroup");
AddCommentOnIssueWorkitemHandler handler = new AddCommentOnIssueWorkitemHandler("testusername",
"testpassword",
"testjiraurl");
handler.setAuth(auth);
handler.executeWorkItem(workItem,
manager);
assertNotNull(manager.getResults());
assertEquals(1,
manager.getResults().size());
assertTrue(manager.getResults().containsKey(workItem.getId()));
}
@Test(expected = WorkItemHandlerRuntimeException.class)
public void testAddCommentInvalidParams() throws Exception {
TestWorkItemManager manager = new TestWorkItemManager();
WorkItemImpl workItem = new WorkItemImpl();
AddCommentOnIssueWorkitemHandler handler = new AddCommentOnIssueWorkitemHandler("testusername",
"testpassword",
"testjiraurl");
handler.setAuth(auth);
handler.executeWorkItem(workItem,
manager);
assertNotNull(manager.getResults());
assertEquals(0,
manager.getResults().size());
}
@Test
public void testResolveIssue() throws Exception {
TestWorkItemManager manager = new TestWorkItemManager();
WorkItemImpl workItem = new WorkItemImpl();
workItem.setParameter("IssueKey",
"testIssueKey");
workItem.setParameter("Resolution",
"testResolved");
workItem.setParameter("ResolutionComment",
"testResolutionComment");
ResolveIssueWorkitemHandler handler = new ResolveIssueWorkitemHandler("testusername",
"testpassword",
"testjiraurl");
handler.setAuth(auth);
handler.executeWorkItem(workItem,
manager);
assertNotNull(manager.getResults());
assertEquals(1,
manager.getResults().size());
assertTrue(manager.getResults().containsKey(workItem.getId()));
}
@Test(expected = WorkItemHandlerRuntimeException.class)
public void testResolveIssueInvalidParams() throws Exception {
TestWorkItemManager manager = new TestWorkItemManager();
WorkItemImpl workItem = new WorkItemImpl();
ResolveIssueWorkitemHandler handler = new ResolveIssueWorkitemHandler("testusername",
"testpassword",
"testjiraurl");
handler.setAuth(auth);
handler.executeWorkItem(workItem,
manager);
assertNotNull(manager.getResults());
assertEquals(0,
manager.getResults().size());
}
}
| 41.650407
| 130
| 0.525148
|
109855afc0bbbc2778a2e8aa87064337527fe05e
| 5,793
|
package hr.fer.zemris.jcms.service.assessments.defimpl.comp;
import java.io.IOException;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import javax.tools.FileObject;
import javax.tools.JavaFileManager;
import javax.tools.JavaFileObject;
import javax.tools.JavaFileObject.Kind;
import org.apache.log4j.Logger;
public class MyJavaFileManager implements JavaFileManager {
public static final Logger logger = Logger.getLogger(MyJavaFileManager.class.getCanonicalName());
JavaFileManager delegate = null;
Map<String,MemoryJavaFileObject> map = new HashMap<String, MemoryJavaFileObject>();
String packagePrefix;
public void releaseDelegateFileManager() {
delegate = null;
}
public Map<String, MemoryJavaFileObject> getMap() {
return map;
}
public MyJavaFileManager(JavaFileManager delegate, String packagePrefix) {
super();
this.delegate = delegate;
this.packagePrefix = packagePrefix;
}
@Override
public void close() throws IOException {
//System.out.println("****[Delegate]: close();");
if(delegate==null) throw new IOException("Delegate File Manager was closed!");
delegate.close();
}
@Override
public void flush() throws IOException {
//System.out.println("****[Delegate]: flush();");
if(delegate==null) throw new IOException("Delegate File Manager was closed!");
delegate.flush();
}
@Override
public ClassLoader getClassLoader(Location location) {
//System.out.println("****[Delegate]: getClassLoader(location={name="+location.getName()+", isOutputLocation="+location.isOutputLocation()+"});");
if(delegate==null) return null;
return delegate.getClassLoader(location);
}
@Override
public FileObject getFileForInput(Location location, String packageName,
String relativeName) throws IOException {
//System.out.println("****[Delegate]: getFileForInput(location={name="+location.getName()+", isOutputLocation="+location.isOutputLocation()+"},package="+packageName+", relativaName="+relativeName+");");
if(delegate==null) throw new IOException("Delegate File Manager was closed!");
return delegate.getFileForInput(location, packageName, relativeName);
}
@Override
public FileObject getFileForOutput(Location location, String packageName,
String relativeName, FileObject sibling) throws IOException {
//System.out.println("****[Delegate]: getFileForOutput(location={name="+location.getName()+", isOutputLocation="+location.isOutputLocation()+"},package="+packageName+", relativaName="+relativeName+", sibling="+sibling+");");
if(delegate==null) throw new IOException("Delegate File Manager was closed!");
return delegate.getFileForOutput(location, packageName, relativeName, sibling);
}
@Override
public JavaFileObject getJavaFileForInput(Location location,
String className, Kind kind) throws IOException {
//System.out.println("****[Delegate]: getJavaFileForInput(location={name="+location.getName()+", isOutputLocation="+location.isOutputLocation()+"},className="+className+", kind="+kind+");");
if(delegate==null) throw new IOException("Delegate File Manager was closed!");
return delegate.getJavaFileForInput(location, className, kind);
}
@Override
public JavaFileObject getJavaFileForOutput(Location location,
String className, Kind kind, FileObject sibling) throws IOException {
//System.out.println("****[Delegate]: getJavaFileForOutput(location={name="+location.getName()+", isOutputLocation="+location.isOutputLocation()+"},className="+className+", kind="+kind+", sibling="+sibling+");");
if(className.startsWith(packagePrefix)) {
MemoryJavaFileObject m = map.get(className);
if(m==null) {
m = new MemoryJavaFileObject(className);
map.put(m.getName(), m);
}
return m;
}
if(delegate==null) throw new IOException("Delegate File Manager was closed!");
return delegate.getJavaFileForOutput(location, className, kind, sibling);
}
@Override
public boolean handleOption(String current, Iterator<String> remaining) {
//System.out.println("****[Delegate]: handleOption(current="+current+",...);");
if(delegate==null) return false;
return delegate.handleOption(current, remaining);
}
@Override
public boolean hasLocation(Location location) {
//System.out.println("****[Delegate]: hasLocation(location={name="+location.getName()+", isOutputLocation="+location.isOutputLocation()+"});");
if(delegate==null) return false;
return delegate.hasLocation(location);
}
@Override
public String inferBinaryName(Location location, JavaFileObject file) {
//System.out.println("****[Delegate]: inferBinaryName(location={name="+location.getName()+", isOutputLocation="+location.isOutputLocation()+"}, file="+file+");");
if(delegate==null) return null;
return delegate.inferBinaryName(location, file);
}
@Override
public boolean isSameFile(FileObject a, FileObject b) {
//System.out.println("****[Delegate]: isSameFile(a="+a+", b="+b+");");
if(delegate==null) throw new IllegalArgumentException("Delegate File Manager was closed!");
return delegate.isSameFile(a, b);
}
@Override
public Iterable<JavaFileObject> list(Location location, String packageName,
Set<Kind> kinds, boolean recurse) throws IOException {
//System.out.println("****[Delegate]: list(location={name="+location.getName()+", isOutputLocation="+location.isOutputLocation()+"},package="+packageName+", kinds="+kinds+", recurse="+recurse+");");
if(delegate==null) throw new IOException("Delegate File Manager was closed!");
return delegate.list(location, packageName, kinds, recurse);
}
@Override
public int isSupportedOption(String option) {
//System.out.println("****[Delegate]: isSupportedOption(option="+option+");");
if(delegate==null) return -1;
return delegate.isSupportedOption(option);
}
}
| 40.795775
| 226
| 0.74193
|
57d5aeb9e273ab3118b784ee147f8fd87c38887b
| 2,435
|
/* ----------------------------------------------------------------------------
* This file was automatically generated by SWIG (http://www.swig.org).
* Version 3.0.12
*
* Do not make changes to this file unless you know what you are doing--modify
* the SWIG interface file instead.
* ----------------------------------------------------------------------------- */
package org.quantlib;
public class ZeroCouponBond extends Bond {
private transient long swigCPtr;
protected ZeroCouponBond(long cPtr, boolean cMemoryOwn) {
super(QuantLibJNI.ZeroCouponBond_SWIGUpcast(cPtr), cMemoryOwn);
swigCPtr = cPtr;
}
protected static long getCPtr(ZeroCouponBond obj) {
return (obj == null) ? 0 : obj.swigCPtr;
}
protected void finalize() {
delete();
}
public synchronized void delete() {
if (swigCPtr != 0) {
if (swigCMemOwn) {
swigCMemOwn = false;
QuantLibJNI.delete_ZeroCouponBond(swigCPtr);
}
swigCPtr = 0;
}
super.delete();
}
public ZeroCouponBond(long settlementDays, Calendar calendar, double faceAmount, Date maturityDate, BusinessDayConvention paymentConvention, double redemption, Date issueDate) {
this(QuantLibJNI.new_ZeroCouponBond__SWIG_0(settlementDays, Calendar.getCPtr(calendar), calendar, faceAmount, Date.getCPtr(maturityDate), maturityDate, paymentConvention.swigValue(), redemption, Date.getCPtr(issueDate), issueDate), true);
}
public ZeroCouponBond(long settlementDays, Calendar calendar, double faceAmount, Date maturityDate, BusinessDayConvention paymentConvention, double redemption) {
this(QuantLibJNI.new_ZeroCouponBond__SWIG_1(settlementDays, Calendar.getCPtr(calendar), calendar, faceAmount, Date.getCPtr(maturityDate), maturityDate, paymentConvention.swigValue(), redemption), true);
}
public ZeroCouponBond(long settlementDays, Calendar calendar, double faceAmount, Date maturityDate, BusinessDayConvention paymentConvention) {
this(QuantLibJNI.new_ZeroCouponBond__SWIG_2(settlementDays, Calendar.getCPtr(calendar), calendar, faceAmount, Date.getCPtr(maturityDate), maturityDate, paymentConvention.swigValue()), true);
}
public ZeroCouponBond(long settlementDays, Calendar calendar, double faceAmount, Date maturityDate) {
this(QuantLibJNI.new_ZeroCouponBond__SWIG_3(settlementDays, Calendar.getCPtr(calendar), calendar, faceAmount, Date.getCPtr(maturityDate), maturityDate), true);
}
}
| 44.272727
| 242
| 0.71499
|
2cf6ef5e2904a1092516aee80f047c5866c50c05
| 437
|
package com.trio.breakFast.util.ips;
/**
* Created by weimao on 2016/3/26.
*/
/**
* @author //作者 weimao
* @ClassName: //类名/接口名/表名
* @Description: //一句话功能简述/表所属模块
* @Date //创建/生成日期 2016/03/26 21:41
* @History:// 历史修改记录
* <author> // 修改人1
* <time> // 修改时间
* <desc> // 描述修改内容
* <author> // 修改人2
* <time> // 修改时间
* <desc> // 描述修改内容
*/
public class MyXmlException extends Exception {//只实现Exception中的方法 TODO
}
| 19.863636
| 70
| 0.592677
|
0db78dc3c1df7bec5a888ceedaca0828f2ef490f
| 1,392
|
package com.yugabyte.yw.common.swagger;
import io.swagger.annotations.*;
import io.swagger.core.filter.AbstractSpecFilter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@SwaggerDefinition(
info =
@Info(
title = "Yugabyte Platform API",
description = "Yugabyte Platform API",
version = "v1",
contact = @Contact(name = "Yugabyte", url = "http://docs.yugabyte.com"),
license =
@License(
name = YWSwaggerSpecFilter.LICENSE_1_0_0_NAME,
url = YWSwaggerSpecFilter.POLYFORM_FREE_TRIAL_LICENSE_1_0_0_URL)),
consumes = {"application/json"},
produces = {"application/json"},
schemes = {SwaggerDefinition.Scheme.HTTP, SwaggerDefinition.Scheme.HTTPS},
externalDocs =
@ExternalDocs(value = "About Yugabyte Platform", url = "https://docs.yugabyte.com"))
public class YWSwaggerSpecFilter extends AbstractSpecFilter {
public static final Logger LOG = LoggerFactory.getLogger(YWSwaggerSpecFilter.class);
static final String LICENSE_1_0_0_NAME = "Polyform Free Trial License 1.0.0";
static final String POLYFORM_FREE_TRIAL_LICENSE_1_0_0_URL =
"https://github.com/yugabyte/yugabyte-db/blob/master/licenses/"
+ "POLYFORM-FREE-TRIAL-LICENSE-1.0.0.txt";
public YWSwaggerSpecFilter() {
YWModelConverter.register();
}
}
| 38.666667
| 92
| 0.683908
|
058224a07e5d67b26a60dc251dacb690fbf92089
| 2,320
|
/*
* Copyright (C) 2007-2014, GoodData(R) Corporation. All rights reserved.
*/
package com.gooddata.md.report;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.gooddata.md.AbstractObj;
import com.gooddata.md.Meta;
import com.gooddata.md.Queryable;
import com.gooddata.md.Updatable;
import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonTypeInfo;
import com.fasterxml.jackson.annotation.JsonTypeName;
import java.util.Collection;
import static java.util.Arrays.asList;
/**
* Report
*/
@JsonTypeName("report")
@JsonTypeInfo(include = JsonTypeInfo.As.WRAPPER_OBJECT, use = JsonTypeInfo.Id.NAME)
@JsonInclude(JsonInclude.Include.NON_NULL)
public class Report extends AbstractObj implements Queryable, Updatable {
@JsonProperty("content")
private final Content content;
@JsonCreator
private Report(@JsonProperty("meta") Meta meta, @JsonProperty("content") Content content) {
super(meta);
this.content = content;
}
/* Just for serialization test */
Report(String title, String domain, String... definitions) {
super(new Meta(title));
content = new Content(asList(definitions), asList(domain));
}
public Report(String title, ReportDefinition... definitions) {
this(title, null, uris(definitions));
}
@JsonIgnore
public Collection<String> getDefinitions() {
return content.getDefinitions();
}
@JsonIgnore
public Collection<String> getDomains() {
return content.getDomains();
}
@JsonInclude(JsonInclude.Include.NON_NULL)
private static class Content {
private final Collection<String> definitions;
private final Collection<String> domains;
@JsonCreator
public Content(@JsonProperty("definitions") Collection<String> definitions,
@JsonProperty("domains") Collection<String> domains) {
this.definitions = definitions;
this.domains = domains;
}
public Collection<String> getDefinitions() {
return definitions;
}
public Collection<String> getDomains() {
return domains;
}
}
}
| 29.367089
| 95
| 0.694828
|
cea13e418612414cb1d58a11320800343852bb99
| 761
|
package mainclient.methodRemovedInSuperclass;
import main.methodRemovedInSuperclass.MethodRemovedInSuperclass;
import main.methodRemovedInSuperclass.SMethodRemovedInSuperclass;
public class MethodRemovedInSuperclassFA {
public int accessSuperS() {
SMethodRemovedInSuperclass s = new MethodRemovedInSuperclassExt();
return s.methodRemovedSS();
}
public int accessSuperSAbs() {
SMethodRemovedInSuperclass s = new MethodRemovedInSuperclassExt();
return s.methodRemovedSSAbs();
}
public int accessSuper() {
MethodRemovedInSuperclass s = new MethodRemovedInSuperclassExt();
return s.methodRemovedS();
}
public int accessSuperAbs() {
MethodRemovedInSuperclass s = new MethodRemovedInSuperclassExt();
return s.methodRemovedSAbs();
}
}
| 27.178571
| 68
| 0.802891
|
98f0e143689cd73157c7080e7105ea4d46df6c0d
| 1,075
|
/*
* Copyright 2016, Yahoo Inc.
* Licensed under the Apache License, Version 2.0
* See LICENSE file in project root for terms.
*/
package example;
import com.yahoo.elide.annotation.Include;
import java.util.Set;
import javax.persistence.CascadeType;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.OneToMany;
@Entity(name = "invoice")
@Include
public class Invoice {
private long id;
private Set<LineItem> items;
@Id
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
@OneToMany(cascade = { CascadeType.DETACH, CascadeType.REMOVE } , mappedBy = "invoice", targetEntity = LineItem.class)
public Set<LineItem> getItems() {
return items;
}
public void setItems(Set<LineItem> items) {
this.items = items;
}
@Override
public int hashCode() {
return Long.hashCode(id);
}
@Override
public boolean equals(Object obj) {
return obj instanceof Invoice && id == ((Invoice) obj).id;
}
}
| 21.5
| 122
| 0.654884
|
03ce8bf291b79b695e4d47f64e8d28dba75e83cf
| 1,173
|
package com.texastoc.module.quarterly;
import com.texastoc.common.GameFinalizedEvent;
import com.texastoc.module.quarterly.model.QuarterlySeason;
import com.texastoc.module.quarterly.service.QuarterlySeasonService;
import java.time.LocalDate;
import java.util.List;
import org.springframework.stereotype.Service;
@Service
public class QuarterlySeasonModuleImpl implements QuarterlySeasonModule {
private final QuarterlySeasonService quarterlySeasonService;
public QuarterlySeasonModuleImpl(
QuarterlySeasonService quarterlySeasonService) {
this.quarterlySeasonService = quarterlySeasonService;
}
@Override
public List<QuarterlySeason> create(int seasonId, int startYear) {
return quarterlySeasonService.create(seasonId, startYear);
}
@Override
public List<QuarterlySeason> getBySeasonId(int seasonId) {
return quarterlySeasonService.getBySeasonId(seasonId);
}
@Override
public QuarterlySeason getByDate(LocalDate date) {
return quarterlySeasonService.getByDate(date);
}
@Override
public void gameFinalized(GameFinalizedEvent gameFinalizedEvent) {
quarterlySeasonService.gameFinalized(gameFinalizedEvent);
}
}
| 29.325
| 73
| 0.812447
|
6da5c360aafc22f56a8be070c84c8f3f35ee5488
| 4,195
|
/*
* Copyright (c) 2007-2011 by The Broad Institute of MIT and Harvard. All Rights Reserved.
*
* This software is licensed under the terms of the GNU Lesser General Public License (LGPL),
* Version 2.1 which is available at http://www.opensource.org/licenses/lgpl-2.1.php.
*
* THE SOFTWARE IS PROVIDED "AS IS." THE BROAD AND MIT MAKE NO REPRESENTATIONS OR
* WARRANTES OF ANY KIND CONCERNING THE SOFTWARE, EXPRESS OR IMPLIED, INCLUDING,
* WITHOUT LIMITATION, WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
* PURPOSE, NONINFRINGEMENT, OR THE ABSENCE OF LATENT OR OTHER DEFECTS, WHETHER
* OR NOT DISCOVERABLE. IN NO EVENT SHALL THE BROAD OR MIT, OR THEIR RESPECTIVE
* TRUSTEES, DIRECTORS, OFFICERS, EMPLOYEES, AND AFFILIATES BE LIABLE FOR ANY DAMAGES
* OF ANY KIND, INCLUDING, WITHOUT LIMITATION, INCIDENTAL OR CONSEQUENTIAL DAMAGES,
* ECONOMIC DAMAGES OR INJURY TO PROPERTY AND LOST PROFITS, REGARDLESS OF WHETHER
* THE BROAD OR MIT SHALL BE ADVISED, SHALL HAVE OTHER REASON TO KNOW, OR IN FACT
* SHALL KNOW OF THE POSSIBILITY OF THE FOREGOING.
*/
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package org.broad.igv.ui.panel;
import java.awt.Cursor;
import java.awt.event.MouseEvent;
import javax.swing.JButton;
import org.broad.igv.feature.RegionOfInterest;
import org.broad.igv.ui.AbstractDataPanelTool;
import org.broad.igv.ui.IGV;
/**
* @author eflakes
*/
public class RegionOfInterestTool extends AbstractDataPanelTool {
Integer roiStart = null;
JButton roiButton;
public RegionOfInterestTool(DataPanel owner, JButton roiButton) {
super(owner, Cursor.getPredefinedCursor(Cursor.CROSSHAIR_CURSOR));
this.roiButton = roiButton;
setName("Region of Interest");
}
public int getRoiStart() {
return (roiStart == null ? 0 : roiStart.intValue());
}
/**
* The mouse has been clicked. Define one edge of the region of interest.
*/
@Override
public void mouseClicked(final MouseEvent e) {
if (e.isPopupTrigger()) {
return;
}
if(e.getClickCount() > 1) {
return;
}
ReferenceFrame referenceFrame = this.getReferenceFame();
if (e.getButton() == MouseEvent.BUTTON1 &&
e.getClickCount() == 1) {
Object chromosome = referenceFrame.getChromosome();
// Allow Regions of Interest edits if ROI is enabled
// and we have a valid Chromosome
if (chromosome != null) {
String chromosomeName = referenceFrame.getChrName();
if (chromosomeName != null) {
int x = e.getX();
// Create a user Region of Interest
if (roiStart == null) {
roiStart = (int) referenceFrame.getChromosomePosition(x);
getOwner().repaint();
} else {
try {
int roiEnd = (int) referenceFrame.getChromosomePosition(x);
int start = Math.min(roiStart, roiEnd);
int end = Math.max(roiStart, roiEnd);
if (start == end) {
++end;
}
// Create a Region of Interest
RegionOfInterest regionOfInterest =
new RegionOfInterest(
chromosomeName,
start,
end,
null);
// TODO -- get this ugly reference out of here
IGV.getInstance().endROI();
IGV.getInstance().addRegionOfInterest(regionOfInterest);
} finally {
roiButton.setSelected(false);
}
}
}
IGV.getInstance().doRefresh();
}
}
}
}
| 34.669421
| 93
| 0.555423
|
b0286e27f172610f67aaa94ad9788f77d536ff0d
| 5,255
|
/*
* This file is generated by jOOQ.
*/
package com.leryn.auth.data.tables;
import com.leryn.auth.data.Idaas;
import com.leryn.auth.data.Keys;
import com.leryn.auth.data.tables.records.AuthorityPageElementRelationRecord;
import java.time.LocalDateTime;
import java.util.Arrays;
import java.util.List;
import org.jooq.Field;
import org.jooq.ForeignKey;
import org.jooq.Identity;
import org.jooq.Name;
import org.jooq.Record;
import org.jooq.Row3;
import org.jooq.Schema;
import org.jooq.Table;
import org.jooq.TableField;
import org.jooq.TableOptions;
import org.jooq.UniqueKey;
import org.jooq.impl.DSL;
import org.jooq.impl.SQLDataType;
import org.jooq.impl.TableImpl;
/**
* 权限-页面元素关系表
*/
@SuppressWarnings({ "all", "unchecked", "rawtypes" })
public class AuthorityPageElementRelation extends TableImpl<AuthorityPageElementRelationRecord> {
private static final long serialVersionUID = 1L;
/**
* The reference instance of <code>idaas.authority_page_element_relation</code>
*/
public static final AuthorityPageElementRelation AUTHORITY_PAGE_ELEMENT_RELATION = new AuthorityPageElementRelation();
/**
* The class holding records for this type
*/
@Override
public Class<AuthorityPageElementRelationRecord> getRecordType() {
return AuthorityPageElementRelationRecord.class;
}
/**
* The column <code>idaas.authority_page_element_relation.id</code>. 代理主键
*/
public final TableField<AuthorityPageElementRelationRecord, Integer> ID = createField(DSL.name("id"), SQLDataType.INTEGER.nullable(false).identity(true), this, "代理主键");
/**
* The column <code>idaas.authority_page_element_relation.create_time</code>. 创建时间
*/
public final TableField<AuthorityPageElementRelationRecord, LocalDateTime> CREATE_TIME = createField(DSL.name("create_time"), SQLDataType.LOCALDATETIME(0).nullable(false).defaultValue(DSL.field("CURRENT_TIMESTAMP", SQLDataType.LOCALDATETIME)), this, "创建时间");
/**
* The column <code>idaas.authority_page_element_relation.modified_time</code>. 修改时间
*/
public final TableField<AuthorityPageElementRelationRecord, LocalDateTime> MODIFIED_TIME = createField(DSL.name("modified_time"), SQLDataType.LOCALDATETIME(0).nullable(false).defaultValue(DSL.field("CURRENT_TIMESTAMP", SQLDataType.LOCALDATETIME)), this, "修改时间");
private AuthorityPageElementRelation(Name alias, Table<AuthorityPageElementRelationRecord> aliased) {
this(alias, aliased, null);
}
private AuthorityPageElementRelation(Name alias, Table<AuthorityPageElementRelationRecord> aliased, Field<?>[] parameters) {
super(alias, null, aliased, parameters, DSL.comment("权限-页面元素关系表"), TableOptions.table());
}
/**
* Create an aliased <code>idaas.authority_page_element_relation</code> table reference
*/
public AuthorityPageElementRelation(String alias) {
this(DSL.name(alias), AUTHORITY_PAGE_ELEMENT_RELATION);
}
/**
* Create an aliased <code>idaas.authority_page_element_relation</code> table reference
*/
public AuthorityPageElementRelation(Name alias) {
this(alias, AUTHORITY_PAGE_ELEMENT_RELATION);
}
/**
* Create a <code>idaas.authority_page_element_relation</code> table reference
*/
public AuthorityPageElementRelation() {
this(DSL.name("authority_page_element_relation"), null);
}
public <O extends Record> AuthorityPageElementRelation(Table<O> child, ForeignKey<O, AuthorityPageElementRelationRecord> key) {
super(child, key, AUTHORITY_PAGE_ELEMENT_RELATION);
}
@Override
public Schema getSchema() {
return Idaas.IDAAS;
}
@Override
public Identity<AuthorityPageElementRelationRecord, Integer> getIdentity() {
return (Identity<AuthorityPageElementRelationRecord, Integer>) super.getIdentity();
}
@Override
public UniqueKey<AuthorityPageElementRelationRecord> getPrimaryKey() {
return Keys.KEY_AUTHORITY_PAGE_ELEMENT_RELATION_PRIMARY;
}
@Override
public List<UniqueKey<AuthorityPageElementRelationRecord>> getKeys() {
return Arrays.<UniqueKey<AuthorityPageElementRelationRecord>>asList(Keys.KEY_AUTHORITY_PAGE_ELEMENT_RELATION_PRIMARY);
}
@Override
public AuthorityPageElementRelation as(String alias) {
return new AuthorityPageElementRelation(DSL.name(alias), this);
}
@Override
public AuthorityPageElementRelation as(Name alias) {
return new AuthorityPageElementRelation(alias, this);
}
/**
* Rename this table
*/
@Override
public AuthorityPageElementRelation rename(String name) {
return new AuthorityPageElementRelation(DSL.name(name), null);
}
/**
* Rename this table
*/
@Override
public AuthorityPageElementRelation rename(Name name) {
return new AuthorityPageElementRelation(name, null);
}
// -------------------------------------------------------------------------
// Row3 type methods
// -------------------------------------------------------------------------
@Override
public Row3<Integer, LocalDateTime, LocalDateTime> fieldsRow() {
return (Row3) super.fieldsRow();
}
}
| 33.903226
| 266
| 0.70961
|
2d9ebd8deec8eee8d8844a5d1579bfe3529f9835
| 1,592
|
package es.drodriguez.com;
public class CreatorRandom {
public static int edadAleatorio(){
int probabilidad = (int)(Math.random()*100);
if (probabilidad <= 50){
//25-18 = 7 intervalo de edades aleatorias a asignar
return 18 + (int)(Math.random()*7);
}else if (probabilidad <= 80){
return 25 + (int)(Math.random()*7);
} else {
return 32 + (int)(Math.random()*7);
}
}
private static String[] nameBoysAleatorios={"Daniel", "José Luis", "José Manuel",
"Juan", "Miguel", "Manuel", "Javier", "Carlos", "Jesus"};
private static String[] nameGirlsAleatorios={"Mamen", "Isabel", "Pilar",
"Raquel", "Mari Mar", "Mercedes", "Maria Dolores", "Dolores"};
private static String[] personasApellidos={"Rodríguez","Fernández", "García", "López", "Ortiz",
"González", "Sánchez", "Muñoz", "Heredia", "Alvarez", "Torres", "Molina", "Serrano", "Marin", "Ramos", "Gil",
"Vázquez", "Diaz", "Romero"};
public static String nameGrilsAleatorios(){
int probabilidad = (int) (Math.random()* nameGirlsAleatorios.length);
return nameGirlsAleatorios[probabilidad];
}
public static String nameBoysAleatorios(){
int probabilidad = (int) (Math.random()* nameBoysAleatorios.length);
return nameBoysAleatorios[probabilidad];
}
public static String personasApellidos(){
int probabilidad = (int) (Math.random()*personasApellidos.length);
return personasApellidos[probabilidad];
}
}
| 35.377778
| 126
| 0.605528
|
020f39130cee607798a2e9eb38838fd0dc48346f
| 1,430
|
package com.github.dynamicextensionsalfresco.behaviours.annotations;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* Indicates a method is a Class-level Policy.
* <p>
* This annotation should only be applied to {@link org.alfresco.repo.policy.ClassPolicy} interface methods.
*
* @author Laurens Fridael
*
*/
@Target({ ElementType.METHOD })
@Retention(RetentionPolicy.RUNTIME)
public @interface AssociationPolicy {
/**
* The QNames of the types or aspects to apply the Policy to. Can be specified in prefix format (
* <code>cm:content</code>) or fully-qualified format (
* <code>{http://www.alfresco.org/model/content/1.0}content</code>).
* <p>
* If no value is specified, the Policy is applied to all types and aspects.
*
* @return
*/
String[] value() default {};
/**
* The QName of the association to apply the Policy to. Can be specified in prefix format ( or fully-qualified
* format.
* <p>
* If no value is specified, the Policy is applied to all associations. If an association has been specified, the
* class name must also be specified. It is invalid to specify only an assocation.
*
* @return
*/
String association() default "";
/**
* Indicates when to trigger the Behaviour.
*
* @return
*/
Event event() default Event.INHERITED_OR_ALL;
}
| 28.6
| 114
| 0.716783
|
c59fa3a68a5dbfd05628ea1270e29cd3f93adbe9
| 1,015
|
public void solve() {
int n = sc.ni();
int m = sc.ni();
visit = new int[n];
adj = new HashSet[n];
adj1 = new ArrayList[n];
for (int i = 0; i < n; i++) {
adj[i] = new HashSet();
adj1[i] = new ArrayList();
}
for (int i = 0; i < m; i++) {
int x = sc.ni() - 1;
int y = sc.ni() - 1;
adj[x].add(y);
adj1[y].add(x);
}
cost = new int[n];
int p = sc.ni();
int[] path = new int[p];
for (int i = 0; i < p; i++) path[i] = sc.ni() - 1;
bfs(path[p - 1]);
int min = 0, max = 0;
for (int i = 0; i < p - 2; i++) {
HashSet<Integer> set = new HashSet();
int tmp = Integer.MAX_VALUE;
for (int x : adj[path[i]]) tmp = Math.min(tmp, cost[x]);
for (int x : adj[path[i]]) if (cost[x] == tmp)
set.add(x);
if (!(set.size() == 1 && set.contains(path[i + 1])))
max++;
if (!set.contains(path[i + 1]))
min++;
}
pw.println(min + " " + max);
}
| 29
| 64
| 0.42266
|
6db554e494f185f33f131710675acb9f5f1d28d8
| 2,156
|
package org.wang.chuangen.webvs.vo;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.alibaba.fastjson.serializer.SimplePropertyPreFilter;
/**
* 通用结果对象
* @author 王传根
* @date 2016-1-25 上午10:54:28
*/
public class Result{
/**
* 状态
*/
private int status=0;
/**
* 信息
*/
private String message="";
/**
* 总数
*/
private int total=0;
/**
* 数据集合
*/
private Object data;
public Result(){}
public Result(Object data){
this.status=Code.VALID;
this.data=data;
}
public Result(int total){
this.status=Code.VALID;
this.total=total;
}
public Result(int status,Object data) {
this.status = status;
this.data = data;
}
public Result(Object data,int total) {
this.status = Code.VALID;
this.total = total;
this.data = data;
}
public Result(Object data,String message){
status=Code.VALID;
this.data=data;
this.message=message;
}
public Result(int status,String message){
this.status=status;
this.message=message;
}
public int getStatus() {
return status;
}
public void setStatus(int status) {
this.status = status;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
public int getTotal() {
return total;
}
public void setTotal(int total) {
this.total = total;
}
public Object getData() {
return data;
}
public void setData(Object data) {
this.data = data;
}
@Override
public String toString() {
return "Result [status=" + status + ", message=" + message + ", total=" + total + ", data=" + data + "]";
}
public String toJSON(){
return JSON.toJSONString(this,SerializerFeature.DisableCircularReferenceDetect);
}
public String toJSON(String callback,String... filterText){
SimplePropertyPreFilter filter=new SimplePropertyPreFilter(filterText);
String jsonText=JSON.toJSONString(this,filter,SerializerFeature.DisableCircularReferenceDetect);
if(callback==null||"".equals(callback))return jsonText;
return callback+"("+jsonText+")";
}
}
| 22
| 108
| 0.663729
|
77fafa026a8ea86d755e436223dda3c78dd12bde
| 295
|
package com.company;
public class LeetCode_191_540 {
// you need to treat n as an unsigned value
public int hammingWeight(int n) {
int counter = 0;
while (n != 0) {
counter++;
n = n&(n-1);
}
return counter;
}
}
| 19.666667
| 48
| 0.488136
|
8dd360a9e9987ad6c874b0d647ecd5eaf29cff62
| 415
|
package xoxo.exceptions;
/**
* An exception that is thrown if the Kiss Key that
* is used to encrypt a message exceeding 28 characters
* in length.
*
* @author M. Ghautsul Azham
* @author Mgs. Muhammad Thoyib Antarnusa
*/
public class KeyTooLongException extends RuntimeException {
/**
* Class constructor.
*/
public KeyTooLongException(String message) {
super(message);
}
}
| 20.75
| 59
| 0.681928
|
d8301640446675e7e0b5b0c6b9b0c9da2b82e876
| 3,398
|
package org.ohdsi.drugmapping.gui.files;
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.util.ArrayList;
import java.util.List;
import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JFileChooser;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
import org.ohdsi.drugmapping.DrugMappingPreprocessor;
public class FolderGUI extends JPanel {
private static final long serialVersionUID = -23890588306917810L;
private final int FOLDER_LABEL_SIZE = 260;
private String name = "";
private String folderName = ".";
private JPanel folderLabelPanel;
private JLabel folderLabel;
private JTextField folderNameField;
private JButton folderSelectButton;
public FolderGUI(String name, String labelText, String defaultFolderName) {
this.name = name;
this.folderName = defaultFolderName;
setLayout(new BoxLayout(this, BoxLayout.X_AXIS));
folderLabelPanel = new JPanel(new BorderLayout());
folderLabelPanel.setMinimumSize(new Dimension(FOLDER_LABEL_SIZE, folderLabelPanel.getHeight()));
folderLabelPanel.setPreferredSize(new Dimension(FOLDER_LABEL_SIZE, folderLabelPanel.getHeight()));
folderLabel = new JLabel(labelText + ":");
folderLabelPanel.add(folderLabel, BorderLayout.WEST);
folderNameField = new JTextField();
folderNameField.setText(defaultFolderName);
folderNameField.setPreferredSize(new Dimension(10000, folderNameField.getHeight()));
folderNameField.setEditable(false);
folderSelectButton = new JButton("Select");
add(folderLabelPanel);
add(folderNameField);
add(new JLabel(" "));
add(folderSelectButton);
folderSelectButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
JFileChooser folderChooser = new JFileChooser();
folderChooser.setCurrentDirectory(new File(folderName)); // start at application current directory
folderChooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
int returnVal = folderChooser.showOpenDialog(null);
if(returnVal == JFileChooser.APPROVE_OPTION) {
folderName = folderChooser.getSelectedFile().getAbsolutePath();
folderNameField.setText(folderName);
}
}
});
DrugMappingPreprocessor.disableWhenRunning(folderSelectButton);
}
public String getName() {
return name;
}
public String getFolderName() {
return folderName;
}
public List<String> getSettings() {
List<String> settings = new ArrayList<String>();
settings.add("#");
settings.add("# " + name);
settings.add("#");
settings.add("");
settings.add(name + ".folderName=" + folderName);
return settings;
}
public void putSettings(List<String> settings) {
for (String setting : settings) {
if ((!setting.trim().equals("")) && (!setting.substring(0, 1).equals("#"))) {
int equalSignIndex = setting.indexOf("=");
String settingPath = setting.substring(0, equalSignIndex);
String value = setting.substring(equalSignIndex + 1).trim();
if (settingPath.equals(name + ".folderName")) {
folderName = value;
folderNameField.setText(folderName);
break;
}
}
}
}
}
| 29.293103
| 103
| 0.715127
|
edbcfa56c412d42f0217172ace43c3151a245d16
| 1,970
|
/**
* Copyright 2014 Thomas Naeff (github.com/thnaeff)
*
* 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 ch.thn.guiutil.input.filechooser;
import java.io.File;
import javax.swing.JFileChooser;
import javax.swing.filechooser.FileSystemView;
/**
* <b>Important:</b> Only works if given in the constructor of {@link JFileChooser}!
*
* @author Thomas Naeff (github.com/thnaeff)
*
*/
public class DirectoryRestrictionFileSystemView extends FileSystemView {
private File[] rootDirectories = null;
public DirectoryRestrictionFileSystemView(File rootDirectory) {
super();
setRootDirectory(rootDirectory);
}
public DirectoryRestrictionFileSystemView(File[] rootDirectories) {
super();
this.rootDirectories = rootDirectories;
}
public void setRootDirectory(File rootDirectory) {
this.rootDirectories = new File[] {rootDirectory};
}
public void setRootDirectories(File[] rootDirectories) {
this.rootDirectories = rootDirectories;
}
@Override
public File createNewFolder(File containingDir) {
File folder = new File(containingDir, "New Folder");
folder.mkdir();
return folder;
}
@Override
public File[] getRoots() {
return rootDirectories;
}
@Override
public File getDefaultDirectory() {
return rootDirectories[0];
}
@Override
public File getHomeDirectory() {
return rootDirectories[0];
}
}
| 26.266667
| 84
| 0.706599
|
8be6d76f5712aec34800ca1b41ab71d835aff130
| 465
|
package com.nordstrom.remote;
import com.jcraft.jsch.JSchException;
public class RemoteSessionInstantiationException extends RuntimeException {
private static final long serialVersionUID = 1338642330237654343L;
public RemoteSessionInstantiationException(JSchException cause) {
super(cause);
}
public RemoteSessionInstantiationException(String message, JSchException cause) {
super(message, cause);
}
}
| 25.833333
| 86
| 0.735484
|
ebc1d04be5cec28089aa06df8c108015f91230a3
| 2,085
|
package com.djk.auth.manager;
import com.djk.utils.CustomLocalDateTimeDeserializer;
import com.djk.utils.CustomLocalDateTimeSerializer;
import com.fasterxml.jackson.databind.annotation.JsonDeserialize;
import com.fasterxml.jackson.databind.annotation.JsonSerialize;
import lombok.Data;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;
/**
* Created by dujinkai on 2018/6/30.
* 管理员实体类
*/
@Data
public class Manager {
/**
* 主键id
*/
private long id;
/**
* 用户名
*/
private String userName;
/**
* 密码
*/
private String password;
/**
* 删除标记 0 未删除 1 已删除
*/
private String delFlag;
/**
* 创建人
*/
private long creator;
/**
* 创建时间
*/
@JsonSerialize(using = CustomLocalDateTimeSerializer.class)
@JsonDeserialize(using = CustomLocalDateTimeDeserializer.class)
private LocalDateTime createTime;
/**
* 管理员的权限
*/
private List<Authority> authorities;
/**
* 转化成用户对象
*
* @return 返回用户对象
*/
public UserDetails convertToUserDetails() {
// 用户的权限信息
List<GrantedAuthority> grantedAuthorities = new ArrayList<>();
// 过滤出有权限的权限信息
authorities = authorities.stream().filter(authority1 -> !StringUtils.isEmpty(authority1.getAuthority())).collect(Collectors.toList());
if (!CollectionUtils.isEmpty(authorities)) {
grantedAuthorities = authorities.stream().map(authority -> new SimpleGrantedAuthority(authority.getAuthority())).collect(Collectors.toList());
}
return new User(this.getUserName(), this.getPassword(), grantedAuthorities);
}
}
| 23.965517
| 154
| 0.694964
|
e35d619ff33f37b0b6bc0e87ce88f2eec190592c
| 4,043
|
package com.example.foodradar;
import android.os.Bundle;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentPagerAdapter;
import androidx.viewpager.widget.ViewPager;
import com.example.foodradar.adapter.SectionsPageAdapter;
import com.example.foodradar.fragment.HomeFragment;
import com.example.foodradar.fragment.LoadingFragment;
import com.example.foodradar.fragment.RecommendedFragment;
import com.example.foodradar.fragment.SettingsFragment;
import com.google.android.material.bottomnavigation.BottomNavigationView;
public class MainActivity extends AppCompatActivity implements BottomNavigationView.OnNavigationItemSelectedListener {
// for debugging purposes
private static final String TAG = "My_message";
/**
* Keeping track of fragment positions
*/
private static final int HOME_POSITION = 0;
private static final int SETTINGS_POSITION = 1;
/**
* The {@link androidx.viewpager.widget.PagerAdapter} that will provide
* fragments for each of the sections. We use a
* {@link FragmentPagerAdapter} derivative, which will keep every
* loaded fragment in memory. If this becomes too memory intensive, it
* may be best to switch to a
* androidx.fragment.app.FragmentStatePagerAdapter.
*/
private SectionsPageAdapter mSectionsPageAdapter;
/**
* The {@link ViewPager} that will host the section contents.
*/
private ViewPager mViewPager;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//loading the default fragment
loadFragment(new HomeFragment());
//getting bottom navigation view and attaching the listener
BottomNavigationView navigation = findViewById(R.id.navigation);
navigation.setOnNavigationItemSelectedListener(this);
// Create the adapter that will return a fragment for each of the three
// primary sections of the activity.
FragmentManager fragmentManager = getSupportFragmentManager();
mSectionsPageAdapter = new SectionsPageAdapter(fragmentManager);
}
/**
* On return from MapActivity, reset MainActivity to default
*/
@Override
protected void onResume() {
super.onResume();
BottomNavigationView navigation = findViewById(R.id.navigation);
navigation.setVisibility(View.VISIBLE);
Button searchButton = (Button) findViewById(R.id.search_button);
searchButton.setEnabled(true);
}
private void setupViewPager(ViewPager viewPager) {
// TODO: see if we can replace the words with icons in the future
mSectionsPageAdapter.addFragment(new HomeFragment(), "Home");
mSectionsPageAdapter.addFragment(new SettingsFragment(), "Settings");
viewPager.setAdapter(mSectionsPageAdapter);
}
private boolean loadFragment(Fragment fragment) {
//switching fragment
if (fragment != null) {
getSupportFragmentManager()
.beginTransaction()
.replace(R.id.fragment_container, fragment)
.commit();
return true;
}
return false;
}
@Override
public boolean onNavigationItemSelected(@NonNull MenuItem item) {
Fragment fragment = null;
switch (item.getItemId()) {
case R.id.action_home:
fragment = new HomeFragment();
break;
case R.id.action_recommended:
fragment = new RecommendedFragment();
break;
case R.id.action_settings:
fragment = new SettingsFragment();
break;
}
return loadFragment(fragment);
}
}
| 33.691667
| 118
| 0.691071
|
089d2f815fed8d7f953f7c1a4515934ae6e875d3
| 1,715
|
package com.codeborne.selenide.commands;
import com.codeborne.selenide.Condition;
import com.codeborne.selenide.SelenideElement;
import com.codeborne.selenide.impl.WebElementSource;
import org.junit.Before;
import org.junit.Test;
import org.openqa.selenium.WebElement;
import java.lang.reflect.Field;
import static org.junit.Assert.assertEquals;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
public class ShouldNotBeCommandTest {
private SelenideElement proxy;
private WebElementSource locator;
private ShouldNotBe shouldNotBeCommand;
private WebElement mockedFoundElement;
@Before
public void setup() {
shouldNotBeCommand = new ShouldNotBe();
proxy = mock(SelenideElement.class);
locator = mock(WebElementSource.class);
mockedFoundElement = mock(WebElement.class);
when(locator.getWebElement()).thenReturn(mockedFoundElement);
}
@Test
public void testDefaultConstructor() throws NoSuchFieldException, IllegalAccessException {
ShouldNotBe shouldNotBe = new ShouldNotBe();
Field prefixField = shouldNotBe.getClass().getSuperclass().getDeclaredField("prefix");
prefixField.setAccessible(true);
String prefix = (String) prefixField.get(shouldNotBe);
assertEquals("be ", prefix);
}
@Test
public void testExecuteMethodWithNonStringArgs() {
SelenideElement returnedElement = shouldNotBeCommand.execute(proxy, locator, new Object[]{Condition.disabled});
assertEquals(proxy, returnedElement);
}
@Test
public void testExecuteMethodWithStringArgs() {
SelenideElement returnedElement = shouldNotBeCommand.execute(proxy, locator, new Object[]{"hello"});
assertEquals(proxy, returnedElement);
}
}
| 32.358491
| 115
| 0.777843
|
96f500ca62b50c6ce850c91343ad26365568bb2f
| 10,596
|
package ru.fizteh.fivt.students.LevkovMiron.shell;
import java.io.*;
import java.nio.file.*;
import java.util.HashMap;
import java.util.Scanner;
/**
* Created by Мирон on 19.09.2014 ${PACKAGE_NAME}.
*/
class Shell {
private String curDir;
Shell() {
curDir = System.getProperty("user.dir");
curDir = replaceSlash(curDir);
}
String replaceSlash(String s) {
char[] charArray = s.toCharArray();
for (int i = 0; i < charArray.length; i++) {
if (charArray[i] == '\\') {
charArray[i] = '/';
}
}
return new String(charArray);
}
String root() {
String s = File.listRoots()[0].toString();
return s.substring(0, s.length() - 1);
}
String absPath(String path) {
while (path.charAt(0) == '/') {
path = path.substring(1);
}
if (!path.contains(":")) {
path = curDir + "/" + path;
}
return path;
}
void cd(final String path) throws NoSuchFileException {
if (".".equals(path)) {
return;
}
String previousDir = curDir;
if ("..".equals(path)) {
String[] dirs = curDir.split("/");
curDir = root();
for (int i = 1; i < dirs.length - 1; i++) {
curDir += "/" + dirs[i];
}
return;
}
curDir = absPath(path);
curDir = replaceSlash(curDir);
File f = new File(curDir);
if (!f.exists()) {
curDir = previousDir;
throw new NoSuchFileException("cd: " + path + ": No such file or directory");
}
}
void mkdir(final String name) {
File curDirFile = new File(curDir + "/" + name);
curDirFile.mkdir();
}
void pwd() {
System.out.println(curDir);
}
void ls() {
String[] list = new File(curDir).list();
for (String file : list) {
System.out.println(file);
}
}
void exit() {
System.exit(1);
}
void cat(final String name) throws IOException {
File file = new File(absPath(name));
if (file.isDirectory()) {
throw new NoSuchFileException("cat: " + name + ": is a directory");
}
if (!file.exists()) {
throw new NoSuchFileException("cat: " + name + ": No such file or directory");
}
try (FileInputStream stream = new FileInputStream(file);
Scanner scanner = new Scanner(stream)) {
while (scanner.hasNext()) {
System.out.println(scanner.nextLine());
}
} catch (IOException e) {
throw new IOException("cat: " + name + ": IOException");
}
}
void mv(String sourcePath, String destinationPath) throws IOException {
destinationPath = absPath(destinationPath);
sourcePath = absPath(sourcePath);
try {
File file = new File(sourcePath);
File destinationFile = new File(destinationPath);
String fileName = file.getName();
Path source = Paths.get(sourcePath);
Path destination = Paths.get(destinationPath + "/" + fileName);
if (!destinationFile.exists() && destinationFile.getParent().equals(file.getParent())) {
destination = Paths.get(destinationPath);
}
Files.move(source, destination);
if (file.isDirectory()) {
for (File f : file.listFiles()) {
mv(f.getAbsolutePath(), destinationPath + "/" + fileName);
}
}
} catch (NoSuchFileException e) {
throw new IOException("mv: " + sourcePath + " " + destinationPath + ": No such file or directory");
} catch (IOException e) {
throw new IOException("mv: " + sourcePath + " " + destinationPath + ": IOException");
}
}
void rm(String path) throws IOException {
path = absPath(path);
File file = new File(path);
try {
if (file.isDirectory()) {
throw new NoSuchFileException("rm: " + file.getName() + ": is a directory");
}
Files.delete(Paths.get(path));
} catch (NoSuchFileException e) {
throw new IOException("rm: " + path + ": No such file or directory");
} catch (IOException e) {
throw new IOException("rm: " + path + ": IOException");
}
}
void rmR(String path) throws IOException {
path = absPath(path);
File file = new File(path);
try {
if (file.isDirectory()) {
for (File f : file.listFiles()) {
rmR(path + "/" + f.getName());
}
}
Files.delete(Paths.get(path));
} catch (NoSuchFileException e) {
throw new IOException("rm [-r]: " + path + ": No such file or directory");
} catch (IOException e) {
throw new IOException("rm [-r]: " + path + ": IOException");
}
}
void cp(String sourcePath, String destinationPath) throws IOException {
destinationPath = absPath(destinationPath);
sourcePath = absPath(sourcePath);
try {
File file = new File(sourcePath);
Path source = Paths.get(sourcePath);
if (file.isDirectory()) {
throw new IllegalArgumentException(("cp: " + sourcePath + ": is a directory (not copied)"));
}
String fileName = file.getName();
File destinationFile = new File(destinationPath);
if (!destinationFile.exists()) {
destinationFile.mkdir();
}
Path destination = Paths.get(destinationPath + "/" + fileName);
Files.copy(source, destination);
} catch (NoSuchFileException e) {
throw new IOException("cp: " + sourcePath + " " + destinationPath + ": No such file or directory");
} catch (IOException e) {
throw new IOException("cp: " + sourcePath + " " + destinationPath + ": IOException");
}
}
void cpR(String sourcePath, String destinationPath) throws IOException {
destinationPath = absPath(destinationPath);
sourcePath = absPath(sourcePath);
try {
File file = new File(sourcePath);
File destinationFile = new File(destinationPath);
String fileName = file.getName();
Path source = Paths.get(sourcePath);
Path destination = Paths.get(destinationPath + "/" + fileName);
if (!destinationFile.exists() && destinationFile.getParent().equals(file.getParent())) {
destination = Paths.get(destinationPath);
}
if (!destinationFile.exists()) {
destinationFile.mkdir();
}
if (file.isDirectory()) {
for (File f : file.listFiles()) {
cpR(f.getAbsolutePath(), destinationPath + "/" + fileName);
}
} else {
Files.copy(source, destination);
}
} catch (NoSuchFileException e) {
throw new IOException("cp [-r]:" + sourcePath + " " + destinationPath + ": No such file or directory");
} catch (IOException e) {
throw new IOException("cp [-r]: " + sourcePath + " " + destinationPath + ": IOException");
}
}
void runCommand(String inString, final PrintStream printStream) {
HashMap<String, Integer> cmdMap = new HashMap<>();
cmdMap.put("cd", 2);
cmdMap.put("mkdir", 2);
cmdMap.put("pwd", 1);
cmdMap.put("ls", 1);
cmdMap.put("exit", 1);
cmdMap.put("cat", 2);
cmdMap.put("mv", 3);
boolean flag = printStream.equals(System.err);
try {
inString = inString.trim();
String[] command = inString.split(" ");
if (cmdMap.containsKey(command[0]) && cmdMap.get(command[0]) != command.length) {
throw new ArrayIndexOutOfBoundsException();
}
if (command[0].equals("cd") && command.length == 2) {
cd(command[1]);
} else if (command[0].equals("mkdir")) {
mkdir(command[1]);
} else if (command[0].equals("pwd")) {
pwd();
} else if (command[0].equals("ls")) {
ls();
} else if (command[0].equals("exit")) {
exit();
} else if (command[0].equals("cat")) {
cat(command[1]);
} else if (command[0].equals("rm")) {
if (command[1].equals("-r")) {
if (command.length != 3) {
throw new ArrayIndexOutOfBoundsException();
}
rmR(command[2]);
} else {
if (command.length != 2) {
throw new ArrayIndexOutOfBoundsException();
}
rm(command[1]);
}
} else if (command[0].equals("cp")) {
if (command[1].equals("-r")) {
if (command.length != 4) {
throw new ArrayIndexOutOfBoundsException();
}
cpR(command[2], command[3]);
} else {
if (command.length != 3) {
throw new ArrayIndexOutOfBoundsException();
}
cp(command[1], command[2]);
}
} else if (command[0].equals("mv")) {
mv(command[1], command[2]);
} else {
printStream.println(command[0] + ": Unknown command");
if (flag) {
System.exit(-3);
}
}
} catch (ArrayIndexOutOfBoundsException e) {
printStream.println("Wrong command format " + "\"" + inString + "\": to few arguments\n");
if (flag) {
System.exit(-4);
}
} catch (NoSuchFileException e) {
printStream.println(e.getMessage());
if (flag) {
System.exit(-1);
}
} catch (IOException e) {
printStream.println(e.getMessage());
if (flag) {
System.exit(-2);
}
}
}
}
| 35.797297
| 115
| 0.490279
|
c58f7a84e30cc54218ef0c9a7a7b84690ed3cf88
| 3,338
|
package no.unit.nva.customer.get;
import com.amazonaws.services.dynamodbv2.AmazonDynamoDBClientBuilder;
import com.amazonaws.services.lambda.runtime.Context;
import no.unit.nva.customer.ObjectMapperConfig;
import no.unit.nva.customer.exception.InputException;
import no.unit.nva.customer.model.CustomerDb;
import no.unit.nva.customer.model.CustomerDto;
import no.unit.nva.customer.model.CustomerMapper;
import no.unit.nva.customer.service.CustomerService;
import no.unit.nva.customer.service.impl.DynamoDBCustomerService;
import nva.commons.exceptions.ApiGatewayException;
import nva.commons.handlers.ApiGatewayHandler;
import nva.commons.handlers.RequestInfo;
import nva.commons.utils.Environment;
import nva.commons.utils.JacocoGenerated;
import java.util.UUID;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import static org.apache.http.HttpStatus.SC_OK;
public class GetCustomerHandler extends ApiGatewayHandler<Void, CustomerDto> {
public static final String ID_NAMESPACE_ENV = "ID_NAMESPACE";
public static final String IDENTIFIER = "identifier";
public static final String IDENTIFIER_IS_NOT_A_VALID_UUID = "Identifier is not a valid UUID: ";
private final CustomerService customerService;
private final CustomerMapper customerMapper;
private static final Logger logger = LoggerFactory.getLogger(GetCustomerHandler.class);
/**
* Default Constructor for GetCustomerHandler.
*/
@JacocoGenerated
public GetCustomerHandler() {
this(defaultCustomerService(),
defaultCustomerMapper(),
new Environment()
);
}
@JacocoGenerated
private static DynamoDBCustomerService defaultCustomerService() {
return new DynamoDBCustomerService(
AmazonDynamoDBClientBuilder.defaultClient(),
ObjectMapperConfig.objectMapper,
new Environment());
}
@JacocoGenerated
private static CustomerMapper defaultCustomerMapper() {
String namespace = new Environment().readEnv(ID_NAMESPACE_ENV);
return new CustomerMapper(namespace);
}
/**
* Constructor for CreateCustomerHandler.
*
* @param customerService customerService
* @param environment environment
*/
public GetCustomerHandler(CustomerService customerService, CustomerMapper customerMapper, Environment environment) {
super(Void.class, environment, logger);
this.customerService = customerService;
this.customerMapper = customerMapper;
}
@Override
protected CustomerDto processInput(Void input, RequestInfo requestInfo, Context context)
throws ApiGatewayException {
CustomerDb customerDb = customerService.getCustomer(getIdentifier(requestInfo));
return customerMapper.toCustomerDto(customerDb);
}
protected UUID getIdentifier(RequestInfo requestInfo) throws ApiGatewayException {
String identifier = null;
try {
identifier = requestInfo.getPathParameters().get(IDENTIFIER);
return UUID.fromString(identifier);
} catch (Exception e) {
throw new InputException(IDENTIFIER_IS_NOT_A_VALID_UUID + identifier, e);
}
}
@Override
protected Integer getSuccessStatusCode(Void input, CustomerDto output) {
return SC_OK;
}
}
| 35.892473
| 120
| 0.739065
|
74bf2b720e27d6de08cc78bfc306fb11e9610ede
| 989
|
package com.mycompany.nncloudrestservice.serverservice;
import java.rmi.RemoteException;
import com.mycompany.nncloudrestservice.pojo.RMIServer;
import com.mycompany.nncloudrestservice.utils.ServerListContainer;
import java.util.Timer;
public class CalculationServerRegistrationService implements ICalculationServerRegistrationService{
@Override
public void register(RMIServer server) throws RemoteException {
server.setId(ServerListContainer.getInstance().size());
ServerListContainer.addServer(server);
}
@Override
public String sayHello() throws RemoteException {
return "Hello world, 2+2="+String.valueOf(2+2);
}
@Override
public void unRegister(RMIServer server) throws RemoteException {
ServerListContainer.deleteAt(server.getId());
}
@Override
public void report(RMIServer server) throws RemoteException {
ServerListContainer.getAt(server.getId()).setLast_report_timer(System.currentTimeMillis());
}
}
| 31.903226
| 103
| 0.771486
|
6a869c48016e424f2fc34af418f8ede09503520b
| 1,402
|
package no.cantara.cs.persistence;
import no.cantara.cs.dto.Application;
import no.cantara.cs.dto.ApplicationConfig;
import java.util.List;
import java.util.Map;
/**
* @author <a href="mailto:erik-dev@fjas.no">Erik Drolshammer</a> 2015-07-09.
*/
public interface ApplicationConfigDao {
Application getApplication(String artifact);
Application createApplication(Application newApplication);
ApplicationConfig createApplicationConfig(String applicationId, ApplicationConfig newConfig);
List<ApplicationConfig> findAllApplicationConfigsByArtifactId(String artifactId);
ApplicationConfig findTheLatestApplicationConfigByArtifactId(String artifactId);
List<ApplicationConfig> findAllApplicationConfigsByApplicationId(String applicationId);
ApplicationConfig findTheLatestApplicationConfigByApplicationId(String applicationId);
ApplicationConfig getApplicationConfig(String configId);
ApplicationConfig deleteApplicationConfig(String configId);
ApplicationConfig updateApplicationConfig(String configId, ApplicationConfig updatedConfig);
String getArtifactId(ApplicationConfig config);
List< ApplicationConfig> getAllConfigs();
List<Application> getApplications();
Application deleteApplication(String applicationId);
boolean canDeleteApplicationConfig(String configId);
boolean canDeleteApplication(String applicationId);
}
| 30.478261
| 97
| 0.815264
|
75a461cb85a158e1b85281c1681990c4866ceb6c
| 3,580
|
/*
* MIT License
*
* Copyright (c) 2019. Austin Thompson
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package animtool.settings;
import javafx.beans.property.BooleanProperty;
import javafx.beans.property.SimpleBooleanProperty;
import javafx.scene.Node;
import javafx.scene.control.CheckBox;
import javafx.scene.control.Tooltip;
import org.json.JSONObject;
public class BooleanSetting extends Setting {
private static final String VALUE_KEY = "value";
private final BooleanProperty value = new SimpleBooleanProperty();
public BooleanSetting(String identifier, String label, String tip, boolean hidden, boolean value) {
super(identifier, label, tip, hidden);
this.value.set(value);
}
public BooleanSetting(String identifier, boolean value) {
super(identifier);
this.value.set(value);
}
public BooleanSetting(String identifier) {
super(identifier);
}
public BooleanSetting hide() {
setHidden(true);
return this;
}
public BooleanSetting tip(String tip) {
setTip(tip);
return this;
}
public BooleanSetting label(String label) {
setLabel(label);
return this;
}
public boolean getValue() {
return value.get();
}
public void setValue(boolean value) {
this.value.set(value);
}
public BooleanProperty valueProperty() {
return value;
}
@Override
public SettingNode makeJFXNode() {
CheckBox checkBox = new CheckBox(getLabel());
checkBox.setSelected(getValue());
if (getTip() != null && !getTip().isEmpty()) {
checkBox.setTooltip(new Tooltip(getTip()));
}
return new SettingNode() {
@Override
public void applyToSetting() {
setValue(checkBox.isSelected());
}
@Override
public Node getNode() {
return checkBox;
}
};
}
@Override
JSONObject toJSON() {
return super.toJSON().put(VALUE_KEY, getValue());
}
@Override
void initFromJSON(JSONObject json) {
setValue(json.getBoolean(VALUE_KEY));
}
@Override
public String toString() {
return "Boolean(id:\"" + getID() + "\", label:\"" + getLabel() + "\", value:" + getValue() + ")";
}
@Override
public boolean equals(Object obj) {
return super.equals(obj) && obj instanceof BooleanSetting && ((BooleanSetting) obj).getValue() == getValue();
}
}
| 28.870968
| 117
| 0.656145
|
bf0a1b0dafe20a2c19c481cccbb6f7490d2ee862
| 803
|
package pw.dotdash.bending.api.effect;
import com.flowpowered.math.vector.Vector3d;
import org.spongepowered.api.Sponge;
import org.spongepowered.api.effect.particle.ParticleEffect;
import pw.dotdash.bending.api.element.Element;
/**
* Represents a service used for the creation of particle effects.
*/
public interface EffectService {
/**
* Gets the singleton instance of the {@link EffectService}.
*
* @return The singleton service instance
*/
static EffectService getInstance() {
return Sponge.getServiceManager().provideUnchecked(EffectService.class);
}
ParticleEffect getExtinguishEffect();
ParticleEffect createParticle(Element element, int quantity, Vector3d offset);
ParticleEffect createRandomParticle(Element element, int quantity);
}
| 29.740741
| 82
| 0.753425
|
5b1c3a69ae5e4bfd9818346c7c1ee1ccf813776d
| 1,033
|
// _ _ _ ___ _ _
// /_\ _ _ | |_ (_) / __| | |_ ___ __ _ | |_
// / _ \ | ' \ | _| | | | (__ | ' \ / -_) / _` | | _|
// /_/ \_\ |_||_| \__| |_| \___| |_||_| \___| \__,_| \__|
//
// Copyright (C) Filli-IT (Einzelunternehmen) & Ursin Filli - All Rights Reserverd
// Unauthorized copying of the this file, via any medium is strictly prohibited
// Proprietary and confidential
// Written by Ursin Filli <ursin.filli@Filli-IT.ch>
package de.superlandnetwork.anticheat.modules;
import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
import org.bukkit.event.Listener;
import org.bukkit.event.player.PlayerCommandPreprocessEvent;
public class CommandBlock implements Listener {
@EventHandler(priority=EventPriority.HIGHEST)
public void onCommand(PlayerCommandPreprocessEvent event) {
String command = event.getMessage();
command.replace("/", "");
if (command.split(" ")[0].contains(":")) {
event.setCancelled(true);
}
}
}
| 32.28125
| 82
| 0.626331
|
a05bdffd028c72a0acc148f34d6fb7d45bce32db
| 983
|
/*******************************************************************************
* Copyright (C) 2017 Create-Net / FBK.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License 2.0
* which accompanies this distribution, and is available at
* https://www.eclipse.org/legal/epl-2.0/
*
* SPDX-License-Identifier: EPL-2.0
*
* Contributors:
* Create-Net / FBK - initial API and implementation
******************************************************************************/
package org.eclipse.agail.device.base;
public class SensorUuid {
public String serviceUuid;
public String charValueUuid;
public String charConfigUuid;
public String charFreqUuid;
public SensorUuid(String service, String charValueUuid, String charConfig, String charFreq) {
this.serviceUuid = service;
this.charValueUuid = charValueUuid;
this.charConfigUuid = charConfig;
this.charFreqUuid = charFreq;
}
}
| 35.107143
| 94
| 0.633774
|
7b3500d29a0c6b916535e9a4b0d0e2af3ef65156
| 452
|
package me.activated.core.database.redis.payload.action;
public enum JedisAction {
SERVER_DATA, PLAYER_DATA, PLAYER_MESSAGE, RANKS_UPDATE, PERMISSIONS_UPDATE, REPORT_SAVE, STAFF_CONNECT, STAFF_SWITCH, STAFF_DISCONNECT,
EXECUTE_PUNISHMENT, EXECUTE_UNBLACKLIST, EXECUTE_UNMUTE, EXECUTE_UNBAN, EXECUTE_ALT_KICK,
TAGS_UPDATE, SERVER_COMMAND, LEFT_FROZEN, JOIN_ME, GRANTS_UPDATE, PLAYER_PERMISSIONS_UPDATE,
SERVER_ONLINE, SERVER_OFFLINE
}
| 45.2
| 139
| 0.829646
|
263f199092931b71065b51b62e36d5de83c84185
| 862
|
package pl.beriko.ioz.web.callback.security;
import javax.security.auth.callback.*;
/**
* @author octavian.rusu
* @version 1.0 Date: Mar 8, 2010
*/
public class HttpCallbackHandler implements CallbackHandler {
private String name;
private String password;
public HttpCallbackHandler() {
// TODO Auto-generated constructor stub
}
public HttpCallbackHandler(String name, String password) {
this.name = name;
this.password = password;
}
public void handle(Callback[] callbacks) {
// TODO: visitor
for (Callback callback : callbacks) {
if (callback instanceof NameCallback) {
NameCallback nameCB = (NameCallback) callback;
nameCB.setName(name);
} else if (callback instanceof PasswordCallback) {
PasswordCallback passwordCB = (PasswordCallback) callback;
passwordCB.setPassword(password.toCharArray());
}
}
}
}
| 23.297297
| 62
| 0.727378
|
e5ff3695c185e778ffe1dc928114ea8090cdcfbd
| 601
|
package ui.ssh;
import javax.swing.JComponent;
import gui.windowmanager.WindowDefinition;
import ssh.SSHConstants;
import state.provider.ApplicationProvider;
/**
* @author Daniel J. Rivers
* 2015
*
* Created: Oct 13, 2015, 7:29:08 AM
*/
public class SSHSessionDefinition implements WindowDefinition {
@Override
public JComponent getCenterComponent( Object state ) {
ApplicationProvider a = (ApplicationProvider)state;
return new AllSSHSessionsPanel( a.getSSHManager(), a );
}
@Override
public String getTitle() {
return SSHConstants.WD_SSH;
}
}
| 22.259259
| 64
| 0.715474
|
9df9903c0b402b22b2a087a6e8ec6cc97fd8d3b1
| 436
|
// Code generated by lark suite oapi sdk gen
package com.larksuite.oapi.service.bitable.v1.model;
import com.google.gson.annotations.SerializedName;
public class AppTableRecordBatchDeleteResult {
@SerializedName("records")
private DeleteRecord[] records;
public DeleteRecord[] getRecords() {
return this.records;
}
public void setRecords(DeleteRecord[] records) {
this.records = records;
}
}
| 24.222222
| 52
| 0.71789
|
ed359487a16f6336ecc321609018606e44e6df7e
| 3,481
|
package com.estafet.boostcd.jenkins.api.model;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.ForeignKey;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.SequenceGenerator;
import javax.persistence.Table;
import javax.persistence.UniqueConstraint;
@Entity
@Table(name = "MICROSERVICE", uniqueConstraints = {
@UniqueConstraint(columnNames = {"ENV_ID", "MICROSERVICE"}, name = "MICROSERVICE_KEY") })
public class Microservice {
@Id
@SequenceGenerator(name = "MICROSERVICE_ID_SEQ", sequenceName = "MICROSERVICE_ID_SEQ", allocationSize = 1)
@GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "MICROSERVICE_ID_SEQ")
@Column(name = "MICROSERVICE_ID")
private Long id;
@Column(name = "MICROSERVICE", nullable = false)
private String microservice;
@ManyToOne
@JoinColumn(name = "ENV_ID", nullable = false, referencedColumnName = "ENV_ID", foreignKey = @ForeignKey(name = "MICROSERVICE_TO_ENV_FK"))
private Env env;
public String getMicroservice() {
return microservice;
}
public void setMicroservice(String microservice) {
this.microservice = microservice;
}
public Env getEnv() {
return env;
}
public void setEnv(Env microserviceEnv) {
this.env = microserviceEnv;
}
public String buildBuildName() {
if (env.getName().equals("build")) {
return "build-" + microservice;
} else {
return null;
}
}
public String promoteBuildName() {
if (env.getNext() == null) {
return null;
} else if (env.getName().equals("build")) {
return "release-" + microservice;
} else if (env.getNext().equals("prod")) {
return "promote-to-prod-" + microservice;
} else {
return "promote-" + env.getName() + "-" + microservice;
}
}
public static MicroserviceBuilder builder() {
return new MicroserviceBuilder();
}
public static class MicroserviceBuilder {
private String microservice;
private Env env;
public MicroserviceBuilder setEnv(Env env) {
this.env = env;
return this;
}
public MicroserviceBuilder setMicroservice(String microservice) {
this.microservice = microservice;
return this;
}
public Microservice build() {
Microservice app = new Microservice();
app.setMicroservice(microservice);
app.setEnv(env);
return app;
}
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((env == null) ? 0 : env.hashCode());
result = prime * result + ((microservice == null) ? 0 : microservice.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Microservice other = (Microservice) obj;
if (env == null) {
if (other.env != null)
return false;
} else if (!env.equals(other.env))
return false;
if (microservice == null) {
if (other.microservice != null)
return false;
} else if (!microservice.equals(other.microservice))
return false;
return true;
}
@Override
public String toString() {
return "Microservice [id=" + id + ", microservice=" + microservice + ", env=" + env + "]";
}
}
| 25.977612
| 140
| 0.672508
|
8c588943e3bebd60bfa4d7bea58aa0e424176efb
| 543
|
package en.mikula.adventure.utils;
import java.util.Arrays;
public class CaseTransformer {
/**
* Transforms given text in camel case to snake case
*/
public static String camelToSnake(String text) {
// Split string by capital letters
String[] parts = text.split("(?=\\p{Upper})");
// Map strings to be lower case
parts = Arrays.stream(parts).map(String::toLowerCase).toArray(String[]::new);
// Join string array with an underscore
return String.join("_", parts);
}
}
| 24.681818
| 85
| 0.631676
|
54a18d818ad1c08c174f8fc4da39b648ff056b2c
| 218
|
package cartucho;
public class CantidadInsuficiente extends Exception {
private static final long serialVersionUID = 3953164442997740645L;
public CantidadInsuficiente(String mensaje) {
super(mensaje);
}
}
| 19.818182
| 68
| 0.784404
|
b38de14af9c0399c0bf2e36a5078479dc9afdd9a
| 6,508
|
/*
* Copyright (C) 2017, Google Inc.
* and other copyright owners as documented in the project's IP log.
*
* This program and the accompanying materials are made available
* under the terms of the Eclipse Distribution License v1.0 which
* accompanies this distribution, is reproduced below, and is
* available at http://www.eclipse.org/org/documents/edl-v10.php
*
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or
* without modification, are permitted provided that the following
* conditions are met:
*
* - Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* - Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following
* disclaimer in the documentation and/or other materials provided
* with the distribution.
*
* - Neither the name of the Eclipse Foundation, 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.eclipse.jgit.pgm.debug;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;
import org.eclipse.jgit.internal.storage.io.BlockSource;
import org.eclipse.jgit.internal.storage.reftable.RefCursor;
import org.eclipse.jgit.internal.storage.reftable.ReftableReader;
import org.eclipse.jgit.lib.AnyObjectId;
import org.eclipse.jgit.lib.ObjectId;
import org.eclipse.jgit.lib.Ref;
import org.eclipse.jgit.lib.RefComparator;
import org.eclipse.jgit.lib.TextProgressMonitor;
import org.eclipse.jgit.pgm.Command;
import org.eclipse.jgit.pgm.TextBuiltin;
import org.kohsuke.args4j.Argument;
@Command
class VerifyReftable extends TextBuiltin {
private static final long SEED1 = 0xaba8bb4de4caf86cL;
private static final long SEED2 = 0x28bb5c25ad43ecb5L;
@Argument(index = 0)
private String lsRemotePath;
@Argument(index = 1)
private String reftablePath;
/** {@inheritDoc} */
@Override
protected void run() throws Exception {
List<Ref> refs = WriteReftable.readRefs(lsRemotePath);
try (FileInputStream in = new FileInputStream(reftablePath);
BlockSource src = BlockSource.from(in);
ReftableReader reader = new ReftableReader(src)) {
scan(refs, reader);
seek(refs, reader);
byId(refs, reader);
}
}
@SuppressWarnings("nls")
private void scan(List<Ref> refs, ReftableReader reader)
throws IOException {
errw.print(String.format("%-20s", "sequential scan..."));
errw.flush();
try (RefCursor rc = reader.allRefs()) {
for (Ref exp : refs) {
verify(exp, rc);
}
if (rc.next()) {
throw die("expected end of table");
}
}
errw.println(" OK");
}
@SuppressWarnings("nls")
private void seek(List<Ref> refs, ReftableReader reader)
throws IOException {
List<Ref> rnd = new ArrayList<>(refs);
Collections.shuffle(rnd, new Random(SEED1));
TextProgressMonitor pm = new TextProgressMonitor(errw);
pm.beginTask("random seek", rnd.size());
for (Ref exp : rnd) {
try (RefCursor rc = reader.seekRef(exp.getName())) {
verify(exp, rc);
if (rc.next()) {
throw die("should not have ref after " + exp.getName());
}
}
pm.update(1);
}
pm.endTask();
}
@SuppressWarnings("nls")
private void byId(List<Ref> refs, ReftableReader reader)
throws IOException {
Map<ObjectId, List<Ref>> want = groupById(refs);
List<List<Ref>> rnd = new ArrayList<>(want.values());
Collections.shuffle(rnd, new Random(SEED2));
TextProgressMonitor pm = new TextProgressMonitor(errw);
pm.beginTask("byObjectId", rnd.size());
for (List<Ref> exp : rnd) {
Collections.sort(exp, RefComparator.INSTANCE);
ObjectId id = exp.get(0).getObjectId();
try (RefCursor rc = reader.byObjectId(id)) {
for (Ref r : exp) {
verify(r, rc);
}
}
pm.update(1);
}
pm.endTask();
}
private static Map<ObjectId, List<Ref>> groupById(List<Ref> refs) {
Map<ObjectId, List<Ref>> m = new HashMap<>();
for (Ref r : refs) {
ObjectId id = r.getObjectId();
if (id != null) {
List<Ref> c = m.get(id);
if (c == null) {
c = new ArrayList<>(2);
m.put(id, c);
}
c.add(r);
}
}
return m;
}
@SuppressWarnings("nls")
private void verify(Ref exp, RefCursor rc) throws IOException {
if (!rc.next()) {
throw die("ended before " + exp.getName());
}
Ref act = rc.getRef();
if (!exp.getName().equals(act.getName())) {
throw die(String.format("expected %s, found %s",
exp.getName(),
act.getName()));
}
if (exp.isSymbolic()) {
if (!act.isSymbolic()) {
throw die("expected " + act.getName() + " to be symbolic");
}
if (!exp.getTarget().getName().equals(act.getTarget().getName())) {
throw die(String.format("expected %s to be %s, found %s",
exp.getName(),
exp.getLeaf().getName(),
act.getLeaf().getName()));
}
return;
}
if (!AnyObjectId.equals(exp.getObjectId(), act.getObjectId())) {
throw die(String.format("expected %s to be %s, found %s",
exp.getName(),
id(exp.getObjectId()),
id(act.getObjectId())));
}
if (exp.getPeeledObjectId() != null
&& !AnyObjectId.equals(exp.getPeeledObjectId(), act.getPeeledObjectId())) {
throw die(String.format("expected %s to be %s, found %s",
exp.getName(),
id(exp.getPeeledObjectId()),
id(act.getPeeledObjectId())));
}
}
@SuppressWarnings("nls")
private static String id(ObjectId id) {
return id != null ? id.name() : "<null>";
}
}
| 30.553991
| 79
| 0.692532
|
36a24c0999b6d4d9d306a2d4f4bb3d549481158d
| 3,198
|
/* LICENSE
Copyright (c) 2013-2016, Jesse Hostetler (jessehostetler@gmail.com)
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
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 edu.oregonstate.eecs.mcplan.domains.yahtzee2;
import java.util.Arrays;
import edu.oregonstate.eecs.mcplan.ActionGenerator;
import edu.oregonstate.eecs.mcplan.util.Fn;
/**
* Generates KeepAction if rerolls left > 0, otherwise generates ScoreAction.
*/
public class YahtzeePhasedActionGenerator extends ActionGenerator<YahtzeeState, YahtzeeAction>
{
private boolean rerolls = false;
private Hand h = null;
private Fn.MultisetPowerSetGenerator power_set = null;
private int cat_idx = 0;
private boolean[] filled = null;
private int Nunfilled = 0;
@Override
public ActionGenerator<YahtzeeState, YahtzeeAction> create()
{
return new YahtzeePhasedActionGenerator();
}
@Override
public void setState( final YahtzeeState s, final long t )
{
rerolls = s.rerolls > 0;
h = s.hand();
if( rerolls ) {
power_set = new Fn.MultisetPowerSetGenerator( Arrays.copyOf( h.dice, h.dice.length ) );
}
cat_idx = 0;
filled = Arrays.copyOf( s.filled, s.filled.length );
Nunfilled = filled.length - Fn.sum( filled );
}
@Override
public int size()
{
if( rerolls ) {
return Fn.multisetPowerSetCardinality( h.dice );
}
else {
return Nunfilled;
}
}
@Override
public boolean hasNext()
{
if( rerolls ) {
return power_set.hasNext();
}
else {
return (cat_idx < YahtzeeScores.values().length && Nunfilled > 0);
}
}
@Override
public YahtzeeAction next()
{
if( rerolls ) {
return new KeepAction( power_set.next() );
}
else {
while( cat_idx < YahtzeeScores.values().length ) {
final YahtzeeScores category = YahtzeeScores.values()[cat_idx++];
if( !filled[category.ordinal()] ) {
filled[category.ordinal()] = true;
Nunfilled -= 1;
return new ScoreAction( category );
}
}
}
throw new IllegalStateException( "hasNext() was false" );
}
}
| 29.072727
| 94
| 0.737023
|
ef2c55ea2bad7cfa79e50509811eb3fb511aee05
| 6,261
|
package tamaized.dalquor.client.entity.boss.render;
import net.minecraft.client.Minecraft;
import net.minecraft.client.model.ModelBase;
import net.minecraft.client.model.ModelBiped;
import net.minecraft.client.renderer.GlStateManager;
import net.minecraft.client.renderer.block.model.ItemCameraTransforms;
import net.minecraft.client.renderer.entity.RenderLiving;
import net.minecraft.client.renderer.entity.RenderManager;
import net.minecraft.client.renderer.entity.layers.LayerBipedArmor;
import net.minecraft.entity.EntityLivingBase;
import net.minecraft.item.ItemStack;
import net.minecraft.util.EnumHandSide;
import net.minecraft.util.EnumParticleTypes;
import net.minecraft.util.ResourceLocation;
import net.minecraft.util.math.Vec3d;
import net.minecraft.world.World;
import net.minecraftforge.fml.relauncher.Side;
import net.minecraftforge.fml.relauncher.SideOnly;
import tamaized.tammodized.client.particles.ParticleFluff;
import tamaized.dalquor.DalQuor;
import tamaized.dalquor.client.entity.boss.model.ModelXia2;
import tamaized.dalquor.common.entity.boss.xia.EntityBossXia2;
import java.util.Random;
@SideOnly(Side.CLIENT)
public class RenderXia2<T extends EntityBossXia2> extends RenderLiving<T> {
private static final ResourceLocation TEXTURE = new ResourceLocation(DalQuor.modid, "textures/entity/xiaform2.png");
public RenderXia2(RenderManager manager, ModelBase par1ModelBase, float par2) {
super(manager, par1ModelBase, par2);
addLayer(new LayerBipedArmor(this));
}
@Override
public void doRender(T entity, double x, double y, double z, float yaw, float ticks) {
GlStateManager.pushMatrix();
{
if (entity.getSphereState())
renderSphere(entity.world, entity, 1, 10);
// if (net.minecraftforge.common.MinecraftForge.EVENT_BUS.post(new net.minecraftforge.client.event.RenderLivingEvent.Pre(entity, this, x, y, z))) return;
ItemStack itemstack = entity.getHeldItemMainhand();
ItemStack itemstack1 = entity.getHeldItemOffhand();
ModelBiped.ArmPose modelbiped$armpose = ModelBiped.ArmPose.EMPTY;
ModelBiped.ArmPose modelbiped$armpose1 = ModelBiped.ArmPose.EMPTY;
if (!itemstack.isEmpty())
modelbiped$armpose = ModelBiped.ArmPose.ITEM;
if (!itemstack1.isEmpty())
modelbiped$armpose1 = ModelBiped.ArmPose.ITEM;
if (entity.getPrimaryHand() == EnumHandSide.RIGHT) {
getMainModel().rightArmPose = modelbiped$armpose;
getMainModel().leftArmPose = modelbiped$armpose1;
} else {
getMainModel().rightArmPose = modelbiped$armpose1;
getMainModel().leftArmPose = modelbiped$armpose;
}
super.doRender(entity, x, y, z, yaw, ticks);
boolean flag = entity.getPrimaryHand() == EnumHandSide.RIGHT;
if (!itemstack.isEmpty() || !itemstack1.isEmpty()) {
GlStateManager.pushMatrix();
if (getMainModel().isChild) {
float f = 0.5F;
GlStateManager.translate(0.0F, 0.625F, 0.0F);
GlStateManager.rotate(-20.0F, -1.0F, 0.0F, 0.0F);
GlStateManager.scale(0.5F, 0.5F, 0.5F);
}
// EntityPlayer client = Minecraft.getMinecraft().thePlayer;
// GlStateManager.translate(entity.posX-client.posX, entity.posY-client.posY, entity.posZ-client.posZ);
GlStateManager.translate(x, y + 1.5, z);
GlStateManager.rotate(-entity.renderYawOffset, 0, 1, 0);
GlStateManager.rotate(180, 1, 0, 0);
renderHeldItem(entity, itemstack, ItemCameraTransforms.TransformType.THIRD_PERSON_RIGHT_HAND, EnumHandSide.RIGHT);
renderHeldItem(entity, itemstack1, ItemCameraTransforms.TransformType.THIRD_PERSON_LEFT_HAND, EnumHandSide.LEFT);
GlStateManager.popMatrix();
}
renderLabel(entity, x, y, z);
}
// net.minecraftforge.common.MinecraftForge.EVENT_BUS.post(new net.minecraftforge.client.event.RenderLivingEvent.Post(entity, this, x, y, z));
Minecraft mc = Minecraft.getMinecraft();
World world = mc.world;
if (!mc.isGamePaused() && ticks != 1.0F) {
for (int i = 0; i < 10; i++) {
Double dX = (world.rand.nextDouble() * 1.0) - 0.5D;
Double dZ = (world.rand.nextDouble() * 1.0) - 0.5D;
// world.spawnParticle(EnumParticleTypes.PORTAL, entity.posX + dX, entity.posY, entity.posZ + dZ, 0, 0, 0);
world.spawnParticle(EnumParticleTypes.PORTAL, entity.posX, entity.posY + 0.25, entity.posZ, dX, 0, dZ);
}
}
GlStateManager.popMatrix();
}
private void renderHeldItem(EntityLivingBase entity, ItemStack stack, ItemCameraTransforms.TransformType transform, EnumHandSide hand) {
if (!stack.isEmpty()) {
GlStateManager.pushMatrix();
if (entity.isSneaking()) {
GlStateManager.translate(0.0F, 0.2F, 0.0F);
}
// Forge: moved this call down, fixes incorrect offset while sneaking.
getMainModel().postRenderArm(0.0625F, hand);
GlStateManager.rotate(-90.0F, 1.0F, 0.0F, 0.0F);
GlStateManager.rotate(180.0F, 0.0F, 1.0F, 0.0F);
boolean flag = hand == EnumHandSide.LEFT;
GlStateManager.translate((float) (flag ? -1 : 1) / 16.0F, 0.125F, -0.625F);
// GlStateManager.translate(entity.posX-Minecraft.getMinecraft().thePlayer.posX, entity.posY-Minecraft.getMinecraft().thePlayer.posY, entity.posZ-Minecraft.getMinecraft().thePlayer.posZ);
Minecraft.getMinecraft().getItemRenderer().renderItemSide(entity, stack, transform, flag);
GlStateManager.popMatrix();
}
}
private void renderSphere(World world, T entity, double radius, int amount) {
if (world == null || Minecraft.getMinecraft().isGamePaused())
return;
Random rand = world.rand;
for (int index = 0; index < amount; index++) {
float speed = 0.08F;
Vec3d vec = new Vec3d(0, radius, 0).rotatePitch(rand.nextInt(360)).rotateYaw(rand.nextInt(360));
Minecraft.getMinecraft().effectRenderer.addEffect(new ParticleFluff(world, entity.getPositionVector().add(0, entity.getEyeHeight(), 0).add(vec), Vec3d.ZERO, rand.nextInt(6) + 2, 0, rand.nextFloat() * 0.90F + 0.10F, 0x7700FFFF));
}
}
@Override
protected ResourceLocation getEntityTexture(T entity) {
return TEXTURE;
}
@Override
public ModelXia2 getMainModel() {
return (ModelXia2) super.getMainModel();
}
protected void renderLabel(T entity, double x, double y, double z) {
// y += (double)((float)getFontRendererFromRenderManager().FONT_HEIGHT * 1.15F * z);
renderLivingLabel(entity, entity.getDisplayName().getFormattedText(), x, y, z, 32);
}
}
| 44.404255
| 231
| 0.742853
|
c73193e9f150b811351a8ff64b16233ac96390d3
| 6,667
|
// Decompiled by Jad v1.5.8g. Copyright 2001 Pavel Kouznetsov.
// Jad home page: http://www.kpdus.com/jad.html
// Decompiler options: packimports(3) annotate safe
package com.irobot.home.fragments;
import android.animation.Animator;
import android.animation.AnimatorListenerAdapter;
import com.irobot.home.view.*;
// Referenced classes of package com.irobot.home.fragments:
// be
class be$11 extends AnimatorListenerAdapter
{
public void onAnimationEnd(Animator animator)
{
super.onAnimationEnd(animator);
// 0 0:aload_0
// 1 1:aload_1
// 2 2:invokespecial #22 <Method void AnimatorListenerAdapter.onAnimationEnd(Animator)>
a.l.setEnabled(true);
// 3 5:aload_0
// 4 6:getfield #15 <Field be a>
// 5 9:getfield #26 <Field CustomSquaredImageButton be.l>
// 6 12:iconst_1
// 7 13:invokevirtual #32 <Method void CustomSquaredImageButton.setEnabled(boolean)>
a.n.setEnabled(true);
// 8 16:aload_0
// 9 17:getfield #15 <Field be a>
// 10 20:getfield #36 <Field CircleRippleButton be.n>
// 11 23:iconst_1
// 12 24:invokevirtual #39 <Method void CircleRippleButton.setEnabled(boolean)>
a.n.setClickable(true);
// 13 27:aload_0
// 14 28:getfield #15 <Field be a>
// 15 31:getfield #36 <Field CircleRippleButton be.n>
// 16 34:iconst_1
// 17 35:invokevirtual #42 <Method void CircleRippleButton.setClickable(boolean)>
a.O.setVisibility(4);
// 18 38:aload_0
// 19 39:getfield #15 <Field be a>
// 20 42:getfield #46 <Field CircleButton be.O>
// 21 45:iconst_4
// 22 46:invokevirtual #52 <Method void CircleButton.setVisibility(int)>
a.Q.setVisibility(4);
// 23 49:aload_0
// 24 50:getfield #15 <Field be a>
// 25 53:getfield #55 <Field CircleButton be.Q>
// 26 56:iconst_4
// 27 57:invokevirtual #52 <Method void CircleButton.setVisibility(int)>
a.S.setVisibility(4);
// 28 60:aload_0
// 29 61:getfield #15 <Field be a>
// 30 64:getfield #58 <Field CircleButton be.S>
// 31 67:iconst_4
// 32 68:invokevirtual #52 <Method void CircleButton.setVisibility(int)>
a.T.setVisibility(4);
// 33 71:aload_0
// 34 72:getfield #15 <Field be a>
// 35 75:getfield #62 <Field PercentageRingView be.T>
// 36 78:iconst_4
// 37 79:invokevirtual #65 <Method void PercentageRingView.setVisibility(int)>
be.a(a, true ^ be.c(a));
// 38 82:aload_0
// 39 83:getfield #15 <Field be a>
// 40 86:iconst_1
// 41 87:aload_0
// 42 88:getfield #15 <Field be a>
// 43 91:invokestatic #69 <Method boolean be.c(be)>
// 44 94:ixor
// 45 95:invokestatic #72 <Method boolean be.a(be, boolean)>
// 46 98:pop
a.ad.setVisibility(0);
// 47 99:aload_0
// 48 100:getfield #15 <Field be a>
// 49 103:getfield #76 <Field BatteryGaugeView be.ad>
// 50 106:iconst_0
// 51 107:invokevirtual #79 <Method void BatteryGaugeView.setVisibility(int)>
// 52 110:return
}
public void onAnimationStart(Animator animator)
{
super.onAnimationStart(animator);
// 0 0:aload_0
// 1 1:aload_1
// 2 2:invokespecial #82 <Method void AnimatorListenerAdapter.onAnimationStart(Animator)>
a.l.setVisibility(0);
// 3 5:aload_0
// 4 6:getfield #15 <Field be a>
// 5 9:getfield #26 <Field CustomSquaredImageButton be.l>
// 6 12:iconst_0
// 7 13:invokevirtual #83 <Method void CustomSquaredImageButton.setVisibility(int)>
a.R.setVisibility(4);
// 8 16:aload_0
// 9 17:getfield #15 <Field be a>
// 10 20:getfield #87 <Field CustomTextView be.R>
// 11 23:iconst_4
// 12 24:invokevirtual #90 <Method void CustomTextView.setVisibility(int)>
a.N.setVisibility(4);
// 13 27:aload_0
// 14 28:getfield #15 <Field be a>
// 15 31:getfield #93 <Field CustomTextView be.N>
// 16 34:iconst_4
// 17 35:invokevirtual #90 <Method void CustomTextView.setVisibility(int)>
if(a.n.getAnimationProgress() > 0.0F)
//* 18 38:aload_0
//* 19 39:getfield #15 <Field be a>
//* 20 42:getfield #36 <Field CircleRippleButton be.n>
//* 21 45:invokevirtual #97 <Method float CircleRippleButton.getAnimationProgress()>
//* 22 48:fconst_0
//* 23 49:fcmpl
//* 24 50:ifle 64
a.n.setAnimationProgress(0.0F);
// 25 53:aload_0
// 26 54:getfield #15 <Field be a>
// 27 57:getfield #36 <Field CircleRippleButton be.n>
// 28 60:fconst_0
// 29 61:invokevirtual #101 <Method void CircleRippleButton.setAnimationProgress(float)>
a.O.setEnabled(false);
// 30 64:aload_0
// 31 65:getfield #15 <Field be a>
// 32 68:getfield #46 <Field CircleButton be.O>
// 33 71:iconst_0
// 34 72:invokevirtual #102 <Method void CircleButton.setEnabled(boolean)>
a.Q.setEnabled(false);
// 35 75:aload_0
// 36 76:getfield #15 <Field be a>
// 37 79:getfield #55 <Field CircleButton be.Q>
// 38 82:iconst_0
// 39 83:invokevirtual #102 <Method void CircleButton.setEnabled(boolean)>
a.S.setEnabled(false);
// 40 86:aload_0
// 41 87:getfield #15 <Field be a>
// 42 90:getfield #58 <Field CircleButton be.S>
// 43 93:iconst_0
// 44 94:invokevirtual #102 <Method void CircleButton.setEnabled(boolean)>
a.T.setClickable(false);
// 45 97:aload_0
// 46 98:getfield #15 <Field be a>
// 47 101:getfield #62 <Field PercentageRingView be.T>
// 48 104:iconst_0
// 49 105:invokevirtual #103 <Method void PercentageRingView.setClickable(boolean)>
// 50 108:return
}
final be a;
be$11(be be1)
{
a = be1;
// 0 0:aload_0
// 1 1:aload_1
// 2 2:putfield #15 <Field be a>
super();
// 3 5:aload_0
// 4 6:invokespecial #17 <Method void AnimatorListenerAdapter()>
// 5 9:return
}
}
| 40.90184
| 99
| 0.567122
|
71318aad4db0f06b9781e298029a8ddb275ec9ca
| 2,302
|
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
package com.azure.resourcemanager.appservice.models;
import com.azure.core.util.ExpandableStringEnum;
import com.fasterxml.jackson.annotation.JsonCreator;
import java.util.Collection;
/**
* OneDeploy type.
*/
public class DeployType extends ExpandableStringEnum<DeployType> {
/**
* Deploy the war file to {@code /home/site/wwwroot/app.war}.
*
* If {@code DeployOptions.path} is provided, {@code path=webapps/<appname>} will behave exactly like wardeploy by
* unzipping app to {@code /home/site/wwwroot/webapps/<appname>}.
*/
public static final DeployType WAR = fromString("war");
/**
* Deploy the jar file to {@code /home/site/wwwroot/app.jar}.
*/
public static final DeployType JAR = fromString("jar");
/**
* Deploy the ear file to {@code /home/site/wwwroot/app.ear}.
*/
public static final DeployType EAR = fromString("ear");
/**
* Deploy the jar to {@code /home/site/libs}. {@code DeployOptions.path} parameter needs to be specified.
*/
public static final DeployType JAR_LIB = fromString("lib");
/**
* Deploy the static file to {@code /home/site/wwwroot/}.
* {@code DeployOptions.path} parameter needs to be specified.
*/
public static final DeployType STATIC = fromString("static");
/**
* Deploy the script as startup.sh (Linux) or startup.cmd (Windows) to {@code /home/site/scripts/}.
* {@code DeployOptions.path} parameter is not supported.
*/
public static final DeployType SCRIPT_STARTUP = fromString("startup");
/**
* unzip the zip to {@code /home/site/wwwroot}. {@code DeployOptions.path} parameter is optional.
*/
public static final DeployType ZIP = fromString("zip");
/**
* Creates or finds a DeployType from its string representation.
* @param name a name to look for
* @return the corresponding DeployType
*/
@JsonCreator
public static DeployType fromString(String name) {
return fromString(name, DeployType.class);
}
/**
* @return known DeployType type values
*/
public static Collection<DeployType> values() {
return values(DeployType.class);
}
}
| 31.534247
| 118
| 0.666811
|
01313ea322030aeaeb24509a00aac911501199cb
| 3,352
|
package com.bazl.dna.database.core.response.datamodel;
import com.bazl.dna.database.service.model.po.CaseImage;
import com.bazl.dna.database.service.model.po.CaseInfo;
import com.bazl.dna.database.service.model.po.ConsignmentInfo;
import com.bazl.dna.database.service.model.vo.CaseInfoVo;
import com.bazl.dna.database.service.model.vo.CasePersonInfoVo;
import com.bazl.dna.database.service.model.vo.ConsignmentInfoVo;
import com.bazl.dna.database.service.model.vo.DnaSampleInfoVo;
import java.io.Serializable;
import java.util.List;
/**
* 案件详情对象
* Created by lizhihua on 2020-04-10.
*/
public class CaseInfoDetailDataModel implements Serializable {
/**
*
*/
private static final long serialVersionUID = 1L;
private CaseInfo caseInfo;
CaseInfoVo caseInfoVo = new CaseInfoVo();
private ConsignmentInfo consignmentInfo;
private ConsignmentInfoVo consignmentInfoVo;
private List<CasePersonInfoVo> casePersonInfoList;
private List<DnaSampleInfoVo> personDnaSampleInfoList;
private List<DnaSampleInfoVo> evidenceDnaSampleInfoList;
private List<CaseImage> caseImageList;
/**
* 委托单位集合
*/
private List<String> clientOrgList;
public CaseInfo getCaseInfo() {
return caseInfo;
}
public ConsignmentInfoVo getConsignmentInfoVo() {
return consignmentInfoVo;
}
public void setConsignmentInfoVo(ConsignmentInfoVo consignmentInfoVo) {
this.consignmentInfoVo = consignmentInfoVo;
}
public void setCaseInfo(CaseInfo caseInfo) {
this.caseInfo = caseInfo;
}
public void setCaseInfo(CaseInfoVo caseInfo) {
this.caseInfo = caseInfo;
}
public ConsignmentInfo getConsignmentInfo() {
return consignmentInfo;
}
public void setConsignmentInfo(ConsignmentInfo consignmentInfo) {
this.consignmentInfo = consignmentInfo;
}
public List<CasePersonInfoVo> getCasePersonInfoList() {
return casePersonInfoList;
}
public void setCasePersonInfoList(List<CasePersonInfoVo> casePersonInfoList) {
this.casePersonInfoList = casePersonInfoList;
}
public List<DnaSampleInfoVo> getPersonDnaSampleInfoList() {
return personDnaSampleInfoList;
}
public void setPersonDnaSampleInfoList(List<DnaSampleInfoVo> personDnaSampleInfoList) {
this.personDnaSampleInfoList = personDnaSampleInfoList;
}
public List<DnaSampleInfoVo> getEvidenceDnaSampleInfoList() {
return evidenceDnaSampleInfoList;
}
public void setEvidenceDnaSampleInfoList(List<DnaSampleInfoVo> evidenceDnaSampleInfoList) {
this.evidenceDnaSampleInfoList = evidenceDnaSampleInfoList;
}
public List<CaseImage> getCaseImageList() {
return caseImageList;
}
public void setCaseImageList(List<CaseImage> caseImageList) {
this.caseImageList = caseImageList;
}
public static long getSerialVersionUID() {
return serialVersionUID;
}
public CaseInfoVo getCaseInfoVo() {
return caseInfoVo;
}
public void setCaseInfoVo(CaseInfoVo caseInfoVo) {
this.caseInfoVo = caseInfoVo;
}
public List<String> getClientOrgList() {
return clientOrgList;
}
public void setClientOrgList(List<String> clientOrgList) {
this.clientOrgList = clientOrgList;
}
}
| 26.1875
| 95
| 0.727625
|
2721d0478dba7855d7e885799012079339546796
| 124
|
package com.Maven.java_bootcamp;
public class App
{
public String getMessage(){
return "Hello World";
}
}
| 13.777778
| 32
| 0.645161
|
5721985ab2fa4aa74b97a9e8672f1af613955e3f
| 2,993
|
package net.jarlehansen.proto2javame.io.protoinput.fields;
import net.jarlehansen.proto2javame.domain.proto.*;
import net.jarlehansen.proto2javame.io.exception.ProtoFileValidationException;
import net.jarlehansen.proto2javame.io.protoinput.AbstractProtoParser;
import net.jarlehansen.proto2javame.io.validator.ProtoFileValues;
import java.util.HashSet;
import java.util.Set;
/**
* @author hansjar@gmail.com Jarle Hansen
*/
public final class FieldParser extends AbstractProtoParser {
// Package protected for testing purposes
ProtoFileInput protoInput;
public FieldParser() {
protoInput = new ProtoFileInput();
protoInput.setProtoClassName("");
}
/**
* Valid input:
* repeated/optional/required string text = 1;
*/
public void parseAndAddProtoFile(final ProtoFileInput protoInput) {
this.protoInput = protoInput;
final FieldData fieldData = new FieldData();
fieldData.setScope(getScopeTag(strings[0]));
if (fieldData.getScope() == ValidScopes.REPEATED) {
fieldData.setListImpl(ListImplementation.VECTOR);
}
fieldData.setType(getTypeTag(strings[1]));
fieldData.setName(strings[2]);
fieldData.setId(getIdTag(strings[4]));
protoInput.addFieldData(fieldData);
}
ValidScopes getScopeTag(final String token) {
final ValidScopes scope;
if (ProtoFileValues.REQUIRED_TAG.getTag().equals(token)) {
scope = ValidScopes.REQUIRED;
} else if (ProtoFileValues.OPTIONAL_TAG.getTag().equals(token)) {
scope = ValidScopes.OPTIONAL;
} else if (ProtoFileValues.REPEATED_TAG.getTag().equals(token)) {
scope = ValidScopes.REPEATED;
} else {
throw new ProtoFileValidationException("The tag required, optional or repeated are mandatory for all variables, content: " + line);
}
return scope;
}
DataType getTypeTag(final String token) {
DataType type = null;
for (ValidTypes typeObj : ValidTypes.values()) {
if (typeObj.getProtoType().equals(token)) {
type = typeObj;
break;
}
}
// If its not a previously declared type and a current enum is active it must be an enum field
if (type == null) {
if(protoInput.getEnumData(token) != null) {
type = ValidTypes.ENUM_VALUE;
} else {
type = new CustomType(token);
}
}
return type;
}
int getIdTag(final String idString) {
// remove ;
final String tempId = idString.substring(0, idString.length() - 1);
final int id;
if (tempId.matches("[0-9]++")) {
id = Integer.parseInt(tempId);
} else {
throw new ProtoFileValidationException("The field id is not a valid number, id: " + idString + ", content: " + line);
}
return id;
}
}
| 30.85567
| 143
| 0.62713
|
1f0dff535cadfa0b402cf5d3a7028c516eb0ce0b
| 2,389
|
/*
* #%L
* %%
* Copyright (C) 2011 - 2017 BMW Car IT GmbH
* %%
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* #L%
*/
package joynr.system.RoutingTypes;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import java.util.UUID;
import org.junit.Test;
public class RoutingTypesUtilTest {
String mqttAddressString = "{\"_typeName\":\"joynr.system.RoutingTypes.MqttAddress\",\"brokerUri\":\"tcp://host:1234\",\"topic\":\"topic\"}";
static final String BROKERURI = "tcp://host:1234";
private static final String MESSAGINGENDPOINTURL = "http://server:8080/bounceproxy/";
static final String TOPIC = "topic";
static final String CHANNELID = UUID.randomUUID().toString();
@Test
public void toMqttAddressStringTest() {
MqttAddress mqttAddress = new MqttAddress(BROKERURI, TOPIC);
String addressString = RoutingTypesUtil.toAddressString(mqttAddress);
assertEquals(mqttAddressString, addressString);
}
@Test
public void fromMqttAddressString() {
Address address = RoutingTypesUtil.fromAddressString(mqttAddressString);
assertTrue(address instanceof MqttAddress);
MqttAddress mqttAddress = (MqttAddress) address;
assertEquals(BROKERURI, mqttAddress.getBrokerUri());
assertEquals(TOPIC, mqttAddress.getTopic());
}
@Test
public void fromChannelAddressString() {
ChannelAddress channelAddress = new ChannelAddress(MESSAGINGENDPOINTURL, CHANNELID);
String addressString = RoutingTypesUtil.toAddressString(channelAddress);
Address address = RoutingTypesUtil.fromAddressString(addressString);
assertTrue(address instanceof ChannelAddress);
assertEquals(MESSAGINGENDPOINTURL, channelAddress.getMessagingEndpointUrl());
assertEquals(CHANNELID, channelAddress.getChannelId());
}
}
| 38.532258
| 145
| 0.726664
|
020924b9b536ec45e30113398b62d5862f0996e8
| 228
|
package io.drogue.iot.rodney.rules;
import java.util.List;
import javax.validation.constraints.NotNull;
import io.drogue.iot.rodney.Command;
public interface RuleProvider {
@NotNull List<Command> check(String phrase);
}
| 19
| 48
| 0.780702
|
2ec4f473db12c9b8fde8ef6cdf8ed3b5100828ba
| 851
|
package com.armadialogcreator.canvas;
import javafx.scene.text.Font;
import javafx.scene.text.Text;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
/**
@author Kayler
@since 12/09/2017 */
public class FontMetrics {
private final Font font;
private final Text t = new Text("");
public FontMetrics(@NotNull Font font) {
this.font = font;
t.setFont(font);
}
/**
Computes the string width for the given text.
@param text the text. If this is null, the returned result will be equal to if text was an empty string
@return the string width
*/
public int computeStringWidth(@Nullable String text) {
this.t.setText(text);
return (int) t.getLayoutBounds().getWidth();
}
/** @return the font's line height */
public int getLineHeight() {
return (int) t.getLayoutBounds().getHeight();
}
}
| 23.638889
| 105
| 0.721504
|
9ba73abea08f81d6c52535d1571c860f73b8651c
| 1,608
|
package com.liquidlabs.vso.deployment.bundle;
import com.liquidlabs.common.net.URI;
import java.util.List;
import com.liquidlabs.common.LifeCycle;
import com.liquidlabs.transport.proxy.clientHandlers.Cacheable;
import com.liquidlabs.transport.proxy.ReplayOnAddressChange;
import com.liquidlabs.vso.work.WorkAssignment;
public interface BundleSpace extends LifeCycle {
public static String NAME = BundleSpace.class.getSimpleName();
void registerBundle(Bundle bundle) throws Exception;
void registerBundleServices(List<Service> services);
void registerBundleService(Service service);
@Cacheable
List<String> getBundleNames(String query);
List<Bundle> getBundles();
Bundle getBundle(String fullBundleName);
List<Service> getBundleServices(String bundleId);
List<Service> getBundleServicesForQuery(String query);
String[] getBundleServiceNames(String bundleId);
Service getBundleService(String serviceName);
/**
* @return TRUE when the request was satisfied or could be handled in BG, otherwise if the request is still pending return FALSE
*/
@ReplayOnAddressChange
boolean requestServiceStart(String requestId, WorkAssignment workInfo);
void updateBundle(Bundle bundle);
URI getEndPoint();
/**
* Returns True when > 1 allocation is outstanding
* @param workAssignmenet
* @return
*/
boolean isWorkAssignmentPending(WorkAssignment workAssignmenet);
boolean isServiceRunning(String serviceId) ;
void remove(String bundleId);
@Cacheable(ttl=10)
String getBundleXML(String bundleId);
String getBundleStatus(String bundleId);
void bounceSystem();
}
| 25.125
| 129
| 0.792289
|
f41604eff0225ca0ac66f9b2bb50deeb42a1cba4
| 817
|
package com.codenamerevy.additionalbars.api.block;
import net.minecraft.core.BlockPos;
import net.minecraft.world.entity.player.Player;
import net.minecraft.world.level.BlockGetter;
import net.minecraft.world.level.block.Block;
import net.minecraft.world.level.block.Blocks;
import net.minecraft.world.level.block.SimpleWaterloggedBlock;
import net.minecraft.world.level.block.state.BlockBehaviour;
public abstract class BasicBarsBlock extends Block implements CustomOxidizableBlock, SimpleWaterloggedBlock {
protected OxidizationState oxidizationState;
public BasicBarsBlock(Properties properties) {
super(properties);
}
public BasicBarsBlock(OxidizationState oxidizationState, Properties properties) {
super(properties);
this.oxidizationState = oxidizationState;
}
}
| 35.521739
| 109
| 0.801714
|
d19464aa3e2b062f95cc6b11083240054091c719
| 3,090
|
package rest.koios.client.backend.api.script;
import rest.koios.client.backend.api.base.Result;
import rest.koios.client.backend.api.base.exception.ApiException;
import rest.koios.client.backend.api.script.model.NativeScript;
import rest.koios.client.backend.api.script.model.PlutusScript;
import rest.koios.client.backend.api.script.model.ScriptRedeemer;
import rest.koios.client.backend.factory.options.Options;
import java.util.List;
/**
* Script Service
*/
public interface ScriptService {
/**
* Native Script List with Filtering, Pagination, Ordering Options
* List of all existing native script hashes along with their creation transaction hashes
* <p><b>200</b> - List of script and creation tx hash pairs
* <p><b>401</b> - The selected server has restricted the endpoint to be only usable via authentication. The authentication supplied was not authorized to access the endpoint
* <p><b>404</b> - The server does not recognise the combination of endpoint and parameters provided
*
* @param options Filtering and Pagination options (optional)
* @return Result of Type List of {@link PlutusScript}
* @throws ApiException if an error occurs while attempting to invoke the API
*/
Result<List<NativeScript>> getNativeScriptList(Options options) throws ApiException;
/**
* Plutus Script List with Filtering, Pagination, Ordering Options
* List of all existing Plutus script hashes along with their creation transaction hashes
* <p><b>200</b> - List of script and creation tx hash pairs
* <p><b>401</b> - The selected server has restricted the endpoint to be only usable via authentication. The authentication supplied was not authorized to access the endpoint
* <p><b>404</b> - The server does not recognise the combination of endpoint and parameters provided
*
* @param options Filtering and Pagination options (optional)
* @return Result of Type List of {@link PlutusScript}
* @throws ApiException if an error occurs while attempting to invoke the API
*/
Result<List<PlutusScript>> getPlutusScriptList(Options options) throws ApiException;
/**
* Script Redeemers with Filtering, Pagination, Ordering Options
* List of all redeemers for a given script hash
* <p><b>200</b> - List of all redeemers for a given script hash
* <p><b>401</b> - The selected server has restricted the endpoint to be only usable via authentication. The authentication supplied was not authorized to access the endpoint
* <p><b>404</b> - The server does not recognise the combination of endpoint and parameters provided
*
* @param scriptHash Script hash in hexadecimal format (hex) (required)
* @param options Filtering and Pagination options (optional)
* @return Result of Type List of all {@link ScriptRedeemer} for a given script hash
* @throws ApiException if an error occurs while attempting to invoke the API
*/
Result<List<ScriptRedeemer>> getScriptRedeemers(String scriptHash, Options options) throws ApiException;
}
| 54.210526
| 178
| 0.739806
|
31a5e2383ac20db0a6f39c5127f5ecfe9830ab00
| 3,021
|
package com.theplasmadonation.jeewan.menuIeams;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.RatingBar;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import com.theplasmadonation.jeewan.R;
import com.google.android.gms.tasks.OnFailureListener;
import com.google.android.gms.tasks.OnSuccessListener;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.firestore.FirebaseFirestore;
public class Send_Feedback extends AppCompatActivity {
RatingBar ratingBar;
EditText feedback;
Button submit;
Float ratedValue;
Feedbackform feedbackform;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.menu_send_feedback);
ratingBar = (RatingBar)findViewById(R.id.ratingBar);
ratingBar.setRating(1);
ratedValue=ratingBar.getRating();
feedback = (EditText)findViewById(R.id.feedback);
ratingBar.setOnRatingBarChangeListener(new RatingBar.OnRatingBarChangeListener() {
@Override
public void onRatingChanged(RatingBar ratingBar, float v, boolean b) {
ratedValue = ratingBar.getRating();
}
});
submit = (Button)findViewById(R.id.submitButton);
submit.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
submit.setEnabled(false);
if(feedback.getText().toString().isEmpty())
{
submit.setEnabled(true);
feedback.setError("Enter your feedback");
return;
}
//add feedback in in firestore
feedbackform=new Feedbackform(ratedValue.toString(),feedback.getText().toString().trim());
FirebaseFirestore.getInstance().collection("Feedback").
document(FirebaseAuth.getInstance().getCurrentUser().getUid()).set(feedbackform)
.addOnSuccessListener(new OnSuccessListener<Void>() {
@Override
public void onSuccess(Void aVoid) {
startActivity(new Intent(getApplicationContext(),FeedbackSubmitted.class));
}
})
.addOnFailureListener(new OnFailureListener() {
@Override
public void onFailure(@NonNull Exception e) {
submit.setEnabled(true);
Toast.makeText(getApplicationContext(),"Something went wrong,Please try again later!",Toast.LENGTH_LONG).show();
}
});
}
});
}
}
| 41.383562
| 144
| 0.606422
|
92d59153aa771e59006e2dbc4a1fb66874fb1f7f
| 26,980
|
/**
* Generated with Acceleo
*/
package org.wso2.integrationstudio.gmf.esb.components;
// Start of user code for imports
import java.util.Iterator;
import java.util.List;
import org.eclipse.emf.common.notify.Notification;
import org.eclipse.emf.common.util.BasicDiagnostic;
import org.eclipse.emf.common.util.BasicEList;
import org.eclipse.emf.common.util.Diagnostic;
import org.eclipse.emf.common.util.EList;
import org.eclipse.emf.common.util.WrappedException;
import org.eclipse.emf.ecore.EObject;
import org.eclipse.emf.ecore.EStructuralFeature;
import org.eclipse.emf.ecore.EcorePackage;
import org.eclipse.emf.ecore.resource.ResourceSet;
import org.eclipse.emf.ecore.util.Diagnostician;
import org.eclipse.emf.ecore.util.EcoreUtil;
import org.eclipse.emf.eef.runtime.api.notify.EStructuralFeatureNotificationFilter;
import org.eclipse.emf.eef.runtime.api.notify.IPropertiesEditionEvent;
import org.eclipse.emf.eef.runtime.api.notify.NotificationFilter;
import org.eclipse.emf.eef.runtime.context.PropertiesEditingContext;
import org.eclipse.emf.eef.runtime.context.impl.EObjectPropertiesEditionContext;
import org.eclipse.emf.eef.runtime.context.impl.EReferencePropertiesEditionContext;
import org.eclipse.emf.eef.runtime.impl.components.SinglePartPropertiesEditingComponent;
import org.eclipse.emf.eef.runtime.impl.notify.PropertiesEditionEvent;
import org.eclipse.emf.eef.runtime.impl.utils.EEFConverterUtil;
import org.eclipse.emf.eef.runtime.impl.utils.EEFUtils;
import org.eclipse.emf.eef.runtime.policies.PropertiesEditingPolicy;
import org.eclipse.emf.eef.runtime.policies.impl.CreateEditingPolicy;
import org.eclipse.emf.eef.runtime.providers.PropertiesEditingProvider;
import org.eclipse.emf.eef.runtime.ui.widgets.referencestable.ReferencesTableSettings;
import org.eclipse.jface.viewers.Viewer;
import org.eclipse.jface.viewers.ViewerFilter;
import org.wso2.integrationstudio.gmf.esb.EsbPackage;
import org.wso2.integrationstudio.gmf.esb.RegistryKeyProperty;
import org.wso2.integrationstudio.gmf.esb.ThrottleMediator;
import org.wso2.integrationstudio.gmf.esb.ThrottlePolicyEntry;
import org.wso2.integrationstudio.gmf.esb.ThrottlePolicyType;
import org.wso2.integrationstudio.gmf.esb.ThrottleSequenceType;
import org.wso2.integrationstudio.gmf.esb.impl.EsbFactoryImpl;
import org.wso2.integrationstudio.gmf.esb.parts.EsbViewsRepository;
import org.wso2.integrationstudio.gmf.esb.parts.ThrottleMediatorPropertiesEditionPart;
import org.wso2.integrationstudio.gmf.esb.presentation.EEFPropertyViewUtil;
// End of user code
/**
*
*
*/
public class ThrottleMediatorPropertiesEditionComponent extends SinglePartPropertiesEditingComponent {
public static String BASE_PART = "Base"; //$NON-NLS-1$
/**
* Settings for policyEntries ReferencesTable
*/
protected ReferencesTableSettings policyEntriesSettings;
/**
* Default constructor
*
*/
public ThrottleMediatorPropertiesEditionComponent(PropertiesEditingContext editingContext, EObject throttleMediator, String editing_mode) {
super(editingContext, throttleMediator, editing_mode);
parts = new String[] { BASE_PART };
repositoryKey = EsbViewsRepository.class;
partKey = EsbViewsRepository.ThrottleMediator.class;
}
/**
* {@inheritDoc}
*
* @see org.eclipse.emf.eef.runtime.api.component.IPropertiesEditionComponent#initPart(java.lang.Object, int, org.eclipse.emf.ecore.EObject,
* org.eclipse.emf.ecore.resource.ResourceSet)
*
*/
public void initPart(Object key, int kind, EObject elt, ResourceSet allResource) {
setInitializing(true);
if (editingPart != null && key == partKey) {
editingPart.setContext(elt, allResource);
final ThrottleMediator throttleMediator = (ThrottleMediator)elt;
final ThrottleMediatorPropertiesEditionPart basePart = (ThrottleMediatorPropertiesEditionPart)editingPart;
// init values
if (isAccessible(EsbViewsRepository.ThrottleMediator.Misc.description))
basePart.setDescription(EEFConverterUtil.convertToString(EcorePackage.Literals.ESTRING, throttleMediator.getDescription()));
if (isAccessible(EsbViewsRepository.ThrottleMediator.General.commentsList))
basePart.setCommentsList(throttleMediator.getCommentsList());
if (isAccessible(EsbViewsRepository.ThrottleMediator.General.reverse)) {
basePart.setReverse(throttleMediator.isReverse());
}
if (isAccessible(EsbViewsRepository.ThrottleMediator.General.groupId))
basePart.setGroupId(EEFConverterUtil.convertToString(EcorePackage.Literals.ESTRING, throttleMediator.getGroupId()));
if (isAccessible(EsbViewsRepository.ThrottleMediator.ThrottlePolicy.policyType)) {
basePart.initPolicyType(EEFUtils.choiceOfValues(throttleMediator, EsbPackage.eINSTANCE.getThrottleMediator_PolicyType()), throttleMediator.getPolicyType());
}
if (isAccessible(EsbViewsRepository.ThrottleMediator.ThrottlePolicy.maxConcurrentAccessCount)) {
basePart.setMaxConcurrentAccessCount(EEFConverterUtil.convertToString(EcorePackage.Literals.EINT, throttleMediator.getMaxConcurrentAccessCount()));
}
if (isAccessible(EsbViewsRepository.ThrottleMediator.ThrottlePolicy.policyEntries)) {
policyEntriesSettings = new ReferencesTableSettings(throttleMediator, EsbPackage.eINSTANCE.getThrottleMediator_PolicyEntries());
basePart.initPolicyEntries(policyEntriesSettings);
}
if (isAccessible(EsbViewsRepository.ThrottleMediator.OnAccept.onAcceptBranchsequenceType)) {
basePart.initOnAcceptBranchsequenceType(EEFUtils.choiceOfValues(throttleMediator, EsbPackage.eINSTANCE.getThrottleMediator_OnAcceptBranchsequenceType()), throttleMediator.getOnAcceptBranchsequenceType());
}
if (isAccessible(EsbViewsRepository.ThrottleMediator.OnReject.onRejectBranchsequenceType)) {
basePart.initOnRejectBranchsequenceType(EEFUtils.choiceOfValues(throttleMediator, EsbPackage.eINSTANCE.getThrottleMediator_OnRejectBranchsequenceType()), throttleMediator.getOnRejectBranchsequenceType());
}
// Start of user code for OnAcceptBranchSequenceKey command update
if (isAccessible(EsbViewsRepository.ThrottleMediator.OnAccept.onAcceptBranchSequenceKey)) {
basePart.setOnAcceptBranchSequenceKey(throttleMediator.getOnAcceptBranchsequenceKey());
}
// End of user code
// Start of user code for OnRejectBranchSequenceKey command update
if (isAccessible(EsbViewsRepository.ThrottleMediator.OnReject.onRejectBranchSequenceKey)) {
basePart.setOnAcceptBranchSequenceKey(throttleMediator.getOnRejectBranchsequenceKey());
}
// End of user code
// Start of user code for policyKey command update
if (isAccessible(EsbViewsRepository.ThrottleMediator.ThrottlePolicy.policyKey)) {
basePart.setPolicyKey(throttleMediator.getPolicyKey());
}
// End of user code
// init filters
if (isAccessible(EsbViewsRepository.ThrottleMediator.ThrottlePolicy.policyEntries)) {
basePart.addFilterToPolicyEntries(new ViewerFilter() {
/**
* {@inheritDoc}
*
* @see org.eclipse.jface.viewers.ViewerFilter#select(org.eclipse.jface.viewers.Viewer, java.lang.Object, java.lang.Object)
*/
public boolean select(Viewer viewer, Object parentElement, Object element) {
return (element instanceof String && element.equals("")) || (element instanceof ThrottlePolicyEntry); //$NON-NLS-1$
}
});
// Start of user code for additional businessfilters for policyEntries
// End of user code
}
// Start of user code for OnAcceptBranchSequenceKey filter update
// End of user code
// Start of user code for OnRejectBranchSequenceKey filter update
// End of user code
// Start of user code for policyKey filter update
// End of user code
// init values for referenced views
// init filters for referenced views
}
setInitializing(false);
}
/**
* {@inheritDoc}
* @see org.eclipse.emf.eef.runtime.impl.components.StandardPropertiesEditionComponent#associatedFeature(java.lang.Object)
*/
public EStructuralFeature associatedFeature(Object editorKey) {
if (editorKey == EsbViewsRepository.ThrottleMediator.Misc.description) {
return EsbPackage.eINSTANCE.getEsbElement_Description();
}
if (editorKey == EsbViewsRepository.ThrottleMediator.General.commentsList) {
return EsbPackage.eINSTANCE.getEsbElement_CommentsList();
}
if (editorKey == EsbViewsRepository.ThrottleMediator.General.reverse) {
return EsbPackage.eINSTANCE.getMediator_Reverse();
}
if (editorKey == EsbViewsRepository.ThrottleMediator.General.groupId) {
return EsbPackage.eINSTANCE.getThrottleMediator_GroupId();
}
if (editorKey == EsbViewsRepository.ThrottleMediator.ThrottlePolicy.policyType) {
return EsbPackage.eINSTANCE.getThrottleMediator_PolicyType();
}
if (editorKey == EsbViewsRepository.ThrottleMediator.ThrottlePolicy.maxConcurrentAccessCount) {
return EsbPackage.eINSTANCE.getThrottleMediator_MaxConcurrentAccessCount();
}
if (editorKey == EsbViewsRepository.ThrottleMediator.ThrottlePolicy.policyEntries) {
return EsbPackage.eINSTANCE.getThrottleMediator_PolicyEntries();
}
if (editorKey == EsbViewsRepository.ThrottleMediator.OnAccept.onAcceptBranchsequenceType) {
return EsbPackage.eINSTANCE.getThrottleMediator_OnAcceptBranchsequenceType();
}
if (editorKey == EsbViewsRepository.ThrottleMediator.OnReject.onRejectBranchsequenceType) {
return EsbPackage.eINSTANCE.getThrottleMediator_OnRejectBranchsequenceType();
}
if (editorKey == EsbViewsRepository.ThrottleMediator.OnAccept.onAcceptBranchSequenceKey) {
return EsbPackage.eINSTANCE.getThrottleMediator_OnAcceptBranchsequenceKey();
}
if (editorKey == EsbViewsRepository.ThrottleMediator.OnReject.onRejectBranchSequenceKey) {
return EsbPackage.eINSTANCE.getThrottleMediator_OnRejectBranchsequenceKey();
}
if (editorKey == EsbViewsRepository.ThrottleMediator.ThrottlePolicy.policyKey) {
return EsbPackage.eINSTANCE.getThrottleMediator_PolicyKey();
}
return super.associatedFeature(editorKey);
}
/**
* {@inheritDoc}
* @see org.eclipse.emf.eef.runtime.impl.components.StandardPropertiesEditionComponent#updateSemanticModel(org.eclipse.emf.eef.runtime.api.notify.IPropertiesEditionEvent)
*
*/
public void updateSemanticModel(final IPropertiesEditionEvent event) {
ThrottleMediator throttleMediator = (ThrottleMediator)semanticObject;
if (EsbViewsRepository.ThrottleMediator.Misc.description == event.getAffectedEditor()) {
throttleMediator.setDescription((java.lang.String)EEFConverterUtil.createFromString(EcorePackage.Literals.ESTRING, (String)event.getNewValue()));
}
if (EsbViewsRepository.ThrottleMediator.General.commentsList == event.getAffectedEditor()) {
if (event.getKind() == PropertiesEditionEvent.SET) {
throttleMediator.getCommentsList().clear();
throttleMediator.getCommentsList().addAll(((EList) event.getNewValue()));
}
}
if (EsbViewsRepository.ThrottleMediator.General.reverse == event.getAffectedEditor()) {
throttleMediator.setReverse((Boolean)event.getNewValue());
}
if (EsbViewsRepository.ThrottleMediator.General.groupId == event.getAffectedEditor()) {
throttleMediator.setGroupId((java.lang.String)EEFConverterUtil.createFromString(EcorePackage.Literals.ESTRING, (String)event.getNewValue()));
}
if (EsbViewsRepository.ThrottleMediator.ThrottlePolicy.policyType == event.getAffectedEditor()) {
throttleMediator.setPolicyType((ThrottlePolicyType)event.getNewValue());
}
if (EsbViewsRepository.ThrottleMediator.ThrottlePolicy.maxConcurrentAccessCount == event.getAffectedEditor()) {
throttleMediator.setMaxConcurrentAccessCount((EEFConverterUtil.createIntFromString(EcorePackage.Literals.EINT, (String)event.getNewValue())));
}
if (EsbViewsRepository.ThrottleMediator.ThrottlePolicy.policyEntries == event.getAffectedEditor()) {
if (event.getKind() == PropertiesEditionEvent.ADD) {
EReferencePropertiesEditionContext context = new EReferencePropertiesEditionContext(editingContext, this, policyEntriesSettings, editingContext.getAdapterFactory());
PropertiesEditingProvider provider = (PropertiesEditingProvider)editingContext.getAdapterFactory().adapt(semanticObject, PropertiesEditingProvider.class);
if (provider != null) {
PropertiesEditingPolicy policy = provider.getPolicy(context);
if (policy instanceof CreateEditingPolicy) {
policy.execute();
}
}
} else if (event.getKind() == PropertiesEditionEvent.EDIT) {
EObjectPropertiesEditionContext context = new EObjectPropertiesEditionContext(editingContext, this, (EObject) event.getNewValue(), editingContext.getAdapterFactory());
PropertiesEditingProvider provider = (PropertiesEditingProvider)editingContext.getAdapterFactory().adapt((EObject) event.getNewValue(), PropertiesEditingProvider.class);
if (provider != null) {
PropertiesEditingPolicy editionPolicy = provider.getPolicy(context);
if (editionPolicy != null) {
editionPolicy.execute();
}
}
} else if (event.getKind() == PropertiesEditionEvent.REMOVE) {
policyEntriesSettings.removeFromReference((EObject) event.getNewValue());
} else if (event.getKind() == PropertiesEditionEvent.MOVE) {
policyEntriesSettings.move(event.getNewIndex(), (ThrottlePolicyEntry) event.getNewValue());
}
}
if (EsbViewsRepository.ThrottleMediator.OnAccept.onAcceptBranchsequenceType == event.getAffectedEditor()) {
throttleMediator.setOnAcceptBranchsequenceType((ThrottleSequenceType)event.getNewValue());
}
if (EsbViewsRepository.ThrottleMediator.OnReject.onRejectBranchsequenceType == event.getAffectedEditor()) {
throttleMediator.setOnRejectBranchsequenceType((ThrottleSequenceType)event.getNewValue());
}
if (EsbViewsRepository.ThrottleMediator.OnAccept.onAcceptBranchSequenceKey == event.getAffectedEditor()) {
// Start of user code for updateOnAcceptBranchSequenceKey method body
if (event.getNewValue() != null) {
RegistryKeyProperty rkp = (RegistryKeyProperty) event.getNewValue();
throttleMediator.setOnAcceptBranchsequenceKey(rkp);
} else {
throttleMediator.setOnAcceptBranchsequenceKey(EsbFactoryImpl.eINSTANCE.createRegistryKeyProperty());
}
// End of user code
}
if (EsbViewsRepository.ThrottleMediator.OnReject.onRejectBranchSequenceKey == event.getAffectedEditor()) {
// Start of user code for updateOnRejectBranchSequenceKey method body
if (event.getNewValue() != null) {
RegistryKeyProperty rkp = (RegistryKeyProperty) event.getNewValue();
throttleMediator.setOnRejectBranchsequenceKey(rkp);
} else {
throttleMediator.setOnRejectBranchsequenceKey(EsbFactoryImpl.eINSTANCE.createRegistryKeyProperty());
}
// End of user code
}
if (EsbViewsRepository.ThrottleMediator.ThrottlePolicy.policyKey == event.getAffectedEditor()) {
// Start of user code for updatePolicyKey method body
if (event.getNewValue() != null) {
RegistryKeyProperty rkp = (RegistryKeyProperty) event.getNewValue();
throttleMediator.setPolicyKey(rkp);
} else {
throttleMediator.setPolicyKey(EsbFactoryImpl.eINSTANCE.createRegistryKeyProperty());
}
// End of user code
}
}
/**
* {@inheritDoc}
* @see org.eclipse.emf.eef.runtime.impl.components.StandardPropertiesEditionComponent#updatePart(org.eclipse.emf.common.notify.Notification)
*/
public void updatePart(Notification msg) {
super.updatePart(msg);
if (editingPart.isVisible()) {
ThrottleMediatorPropertiesEditionPart basePart = (ThrottleMediatorPropertiesEditionPart)editingPart;
if (EsbPackage.eINSTANCE.getEsbElement_Description().equals(msg.getFeature()) && msg.getNotifier().equals(semanticObject) && basePart != null && isAccessible(EsbViewsRepository.ThrottleMediator.Misc.description)) {
if (msg.getNewValue() != null) {
basePart.setDescription(EcoreUtil.convertToString(EcorePackage.Literals.ESTRING, msg.getNewValue()));
} else {
basePart.setDescription("");
}
}
if (EsbPackage.eINSTANCE.getEsbElement_CommentsList().equals(msg.getFeature()) && msg.getNotifier().equals(semanticObject) && basePart != null && isAccessible(EsbViewsRepository.ThrottleMediator.General.commentsList)) {
if (msg.getNewValue() instanceof EList<?>) {
basePart.setCommentsList((EList<?>)msg.getNewValue());
} else if (msg.getNewValue() == null) {
basePart.setCommentsList(new BasicEList<Object>());
} else {
BasicEList<Object> newValueAsList = new BasicEList<Object>();
newValueAsList.add(msg.getNewValue());
basePart.setCommentsList(newValueAsList);
}
}
if (EsbPackage.eINSTANCE.getMediator_Reverse().equals(msg.getFeature()) && msg.getNotifier().equals(semanticObject) && basePart != null && isAccessible(EsbViewsRepository.ThrottleMediator.General.reverse))
basePart.setReverse((Boolean)msg.getNewValue());
if (EsbPackage.eINSTANCE.getThrottleMediator_GroupId().equals(msg.getFeature()) && msg.getNotifier().equals(semanticObject) && basePart != null && isAccessible(EsbViewsRepository.ThrottleMediator.General.groupId)) {
if (msg.getNewValue() != null) {
basePart.setGroupId(EcoreUtil.convertToString(EcorePackage.Literals.ESTRING, msg.getNewValue()));
} else {
basePart.setGroupId("");
}
}
if (EsbPackage.eINSTANCE.getThrottleMediator_PolicyType().equals(msg.getFeature()) && msg.getNotifier().equals(semanticObject) && isAccessible(EsbViewsRepository.ThrottleMediator.ThrottlePolicy.policyType))
basePart.setPolicyType((ThrottlePolicyType)msg.getNewValue());
if (EsbPackage.eINSTANCE.getThrottleMediator_MaxConcurrentAccessCount().equals(msg.getFeature()) && msg.getNotifier().equals(semanticObject) && basePart != null && isAccessible(EsbViewsRepository.ThrottleMediator.ThrottlePolicy.maxConcurrentAccessCount)) {
if (msg.getNewValue() != null) {
basePart.setMaxConcurrentAccessCount(EcoreUtil.convertToString(EcorePackage.Literals.EINT, msg.getNewValue()));
} else {
basePart.setMaxConcurrentAccessCount("");
}
}
if (EsbPackage.eINSTANCE.getThrottleMediator_PolicyEntries().equals(msg.getFeature()) && isAccessible(EsbViewsRepository.ThrottleMediator.ThrottlePolicy.policyEntries))
basePart.updatePolicyEntries();
if (EsbPackage.eINSTANCE.getThrottleMediator_OnAcceptBranchsequenceType().equals(msg.getFeature()) && msg.getNotifier().equals(semanticObject) && isAccessible(EsbViewsRepository.ThrottleMediator.OnAccept.onAcceptBranchsequenceType))
basePart.setOnAcceptBranchsequenceType((ThrottleSequenceType)msg.getNewValue());
if (EsbPackage.eINSTANCE.getThrottleMediator_OnRejectBranchsequenceType().equals(msg.getFeature()) && msg.getNotifier().equals(semanticObject) && isAccessible(EsbViewsRepository.ThrottleMediator.OnReject.onRejectBranchsequenceType))
basePart.setOnRejectBranchsequenceType((ThrottleSequenceType)msg.getNewValue());
// Start of user code for OnAcceptBranchSequenceKey live update
if (EsbPackage.eINSTANCE.getThrottleMediator_OnAcceptBranchsequenceKey().equals(msg.getFeature()) && msg.getNotifier().equals(semanticObject) && basePart != null && isAccessible(EsbViewsRepository.ThrottleMediator.OnAccept.onAcceptBranchSequenceKey)) {
if (msg.getNewValue() != null) {
basePart.setOnAcceptBranchSequenceKey((RegistryKeyProperty)msg.getNewValue());
} else {
basePart.setOnAcceptBranchSequenceKey(EsbFactoryImpl.eINSTANCE.createRegistryKeyProperty());
}
}
// End of user code
// Start of user code for OnRejectBranchSequenceKey live update
if (EsbPackage.eINSTANCE.getThrottleMediator_OnRejectBranchsequenceKey().equals(msg.getFeature())
&& msg.getNotifier().equals(semanticObject) && basePart != null
&& isAccessible(EsbViewsRepository.ThrottleMediator.OnReject.onRejectBranchSequenceKey)) {
if (msg.getNewValue() != null) {
basePart.setOnRejectBranchSequenceKey((RegistryKeyProperty) msg.getNewValue());
} else {
basePart.setOnRejectBranchSequenceKey(EsbFactoryImpl.eINSTANCE.createRegistryKeyProperty());
}
}
// End of user code
// Start of user code for policyKey live update
if (EsbPackage.eINSTANCE.getThrottleMediator_PolicyKey().equals(msg.getFeature())
&& msg.getNotifier().equals(semanticObject) && basePart != null
&& isAccessible(EsbViewsRepository.ThrottleMediator.ThrottlePolicy.policyKey)) {
if (msg.getNewValue() != null) {
basePart.setPolicyKey((RegistryKeyProperty) msg.getNewValue());
} else {
basePart.setPolicyKey(EsbFactoryImpl.eINSTANCE.createRegistryKeyProperty());
}
}
// End of user code
}
}
/**
* {@inheritDoc}
*
* @see org.eclipse.emf.eef.runtime.impl.components.StandardPropertiesEditionComponent#getNotificationFilters()
*/
@Override
protected NotificationFilter[] getNotificationFilters() {
NotificationFilter filter = new EStructuralFeatureNotificationFilter(
EsbPackage.eINSTANCE.getEsbElement_Description(),
EsbPackage.eINSTANCE.getEsbElement_CommentsList(),
EsbPackage.eINSTANCE.getMediator_Reverse(),
EsbPackage.eINSTANCE.getThrottleMediator_GroupId(),
EsbPackage.eINSTANCE.getThrottleMediator_PolicyType(),
EsbPackage.eINSTANCE.getThrottleMediator_MaxConcurrentAccessCount(),
EsbPackage.eINSTANCE.getThrottleMediator_PolicyEntries(),
EsbPackage.eINSTANCE.getThrottleMediator_OnAcceptBranchsequenceType(),
EsbPackage.eINSTANCE.getThrottleMediator_OnRejectBranchsequenceType(),
EsbPackage.eINSTANCE.getThrottleMediator_OnAcceptBranchsequenceKey(),
EsbPackage.eINSTANCE.getThrottleMediator_OnRejectBranchsequenceKey(),
EsbPackage.eINSTANCE.getThrottleMediator_PolicyKey() );
return new NotificationFilter[] {filter,};
}
/**
* {@inheritDoc}
*
* @see org.eclipse.emf.eef.runtime.api.component.IPropertiesEditionComponent#validateValue(org.eclipse.emf.eef.runtime.api.notify.IPropertiesEditionEvent)
*
*/
public Diagnostic validateValue(IPropertiesEditionEvent event) {
Diagnostic ret = Diagnostic.OK_INSTANCE;
if (event.getNewValue() != null) {
try {
if (EsbViewsRepository.ThrottleMediator.Misc.description == event.getAffectedEditor()) {
Object newValue = event.getNewValue();
if (newValue instanceof String) {
newValue = EEFConverterUtil.createFromString(EsbPackage.eINSTANCE.getEsbElement_Description().getEAttributeType(), (String)newValue);
}
ret = Diagnostician.INSTANCE.validate(EsbPackage.eINSTANCE.getEsbElement_Description().getEAttributeType(), newValue);
}
if (EsbViewsRepository.ThrottleMediator.General.commentsList == event.getAffectedEditor()) {
BasicDiagnostic chain = new BasicDiagnostic();
for (Iterator iterator = ((List)event.getNewValue()).iterator(); iterator.hasNext();) {
chain.add(Diagnostician.INSTANCE.validate(EsbPackage.eINSTANCE.getEsbElement_CommentsList().getEAttributeType(), iterator.next()));
}
ret = chain;
}
if (EsbViewsRepository.ThrottleMediator.General.reverse == event.getAffectedEditor()) {
Object newValue = event.getNewValue();
if (newValue instanceof String) {
newValue = EEFConverterUtil.createFromString(EsbPackage.eINSTANCE.getMediator_Reverse().getEAttributeType(), (String)newValue);
}
ret = Diagnostician.INSTANCE.validate(EsbPackage.eINSTANCE.getMediator_Reverse().getEAttributeType(), newValue);
}
if (EsbViewsRepository.ThrottleMediator.General.groupId == event.getAffectedEditor()) {
Object newValue = event.getNewValue();
if (newValue instanceof String) {
newValue = EEFConverterUtil.createFromString(EsbPackage.eINSTANCE.getThrottleMediator_GroupId().getEAttributeType(), (String)newValue);
}
ret = Diagnostician.INSTANCE.validate(EsbPackage.eINSTANCE.getThrottleMediator_GroupId().getEAttributeType(), newValue);
}
if (EsbViewsRepository.ThrottleMediator.ThrottlePolicy.policyType == event.getAffectedEditor()) {
Object newValue = event.getNewValue();
if (newValue instanceof String) {
newValue = EEFConverterUtil.createFromString(EsbPackage.eINSTANCE.getThrottleMediator_PolicyType().getEAttributeType(), (String)newValue);
}
ret = Diagnostician.INSTANCE.validate(EsbPackage.eINSTANCE.getThrottleMediator_PolicyType().getEAttributeType(), newValue);
}
if (EsbViewsRepository.ThrottleMediator.ThrottlePolicy.maxConcurrentAccessCount == event.getAffectedEditor()) {
Object newValue = event.getNewValue();
if (newValue instanceof String) {
newValue = EEFConverterUtil.createFromString(EsbPackage.eINSTANCE.getThrottleMediator_MaxConcurrentAccessCount().getEAttributeType(), (String)newValue);
}
ret = Diagnostician.INSTANCE.validate(EsbPackage.eINSTANCE.getThrottleMediator_MaxConcurrentAccessCount().getEAttributeType(), newValue);
}
if (EsbViewsRepository.ThrottleMediator.OnAccept.onAcceptBranchsequenceType == event.getAffectedEditor()) {
Object newValue = event.getNewValue();
if (newValue instanceof String) {
newValue = EEFConverterUtil.createFromString(EsbPackage.eINSTANCE.getThrottleMediator_OnAcceptBranchsequenceType().getEAttributeType(), (String)newValue);
}
ret = Diagnostician.INSTANCE.validate(EsbPackage.eINSTANCE.getThrottleMediator_OnAcceptBranchsequenceType().getEAttributeType(), newValue);
}
if (EsbViewsRepository.ThrottleMediator.OnReject.onRejectBranchsequenceType == event.getAffectedEditor()) {
Object newValue = event.getNewValue();
if (newValue instanceof String) {
newValue = EEFConverterUtil.createFromString(EsbPackage.eINSTANCE.getThrottleMediator_OnRejectBranchsequenceType().getEAttributeType(), (String)newValue);
}
ret = Diagnostician.INSTANCE.validate(EsbPackage.eINSTANCE.getThrottleMediator_OnRejectBranchsequenceType().getEAttributeType(), newValue);
}
} catch (IllegalArgumentException iae) {
ret = BasicDiagnostic.toDiagnostic(iae);
} catch (WrappedException we) {
ret = BasicDiagnostic.toDiagnostic(we);
}
}
return ret;
}
// Start of user code for help compatibility
/**
* @generated NOT
*/
@Override
public String getHelpContent(Object key, int kind) {
return EEFPropertyViewUtil.getHelpContent(key);
}
// End of user code
}
| 48.700361
| 264
| 0.761861
|
29442d41934bffa2c991ba90fa0ef61e02f4027c
| 14,428
|
/*
* Copyright 2012-2017 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.simpleworkflow.model;
import java.io.Serializable;
import javax.annotation.Generated;
/**
* <p>
* Contains details about a workflow execution.
* </p>
*/
@Generated("com.amazonaws:aws-java-sdk-code-generator")
public class WorkflowExecutionDetail extends com.amazonaws.AmazonWebServiceResult<com.amazonaws.ResponseMetadata> implements Serializable, Cloneable {
/**
* <p>
* Information about the workflow execution.
* </p>
*/
private WorkflowExecutionInfo executionInfo;
/**
* <p>
* The configuration settings for this workflow execution including timeout values, tasklist etc.
* </p>
*/
private WorkflowExecutionConfiguration executionConfiguration;
/**
* <p>
* The number of tasks for this workflow execution. This includes open and closed tasks of all types.
* </p>
*/
private WorkflowExecutionOpenCounts openCounts;
/**
* <p>
* The time when the last activity task was scheduled for this workflow execution. You can use this information to
* determine if the workflow has not made progress for an unusually long period of time and might require a
* corrective action.
* </p>
*/
private java.util.Date latestActivityTaskTimestamp;
/**
* <p>
* The latest executionContext provided by the decider for this workflow execution. A decider can provide an
* executionContext (a free-form string) when closing a decision task using <a>RespondDecisionTaskCompleted</a>.
* </p>
*/
private String latestExecutionContext;
/**
* <p>
* Information about the workflow execution.
* </p>
*
* @param executionInfo
* Information about the workflow execution.
*/
public void setExecutionInfo(WorkflowExecutionInfo executionInfo) {
this.executionInfo = executionInfo;
}
/**
* <p>
* Information about the workflow execution.
* </p>
*
* @return Information about the workflow execution.
*/
public WorkflowExecutionInfo getExecutionInfo() {
return this.executionInfo;
}
/**
* <p>
* Information about the workflow execution.
* </p>
*
* @param executionInfo
* Information about the workflow execution.
* @return Returns a reference to this object so that method calls can be chained together.
*/
public WorkflowExecutionDetail withExecutionInfo(WorkflowExecutionInfo executionInfo) {
setExecutionInfo(executionInfo);
return this;
}
/**
* <p>
* The configuration settings for this workflow execution including timeout values, tasklist etc.
* </p>
*
* @param executionConfiguration
* The configuration settings for this workflow execution including timeout values, tasklist etc.
*/
public void setExecutionConfiguration(WorkflowExecutionConfiguration executionConfiguration) {
this.executionConfiguration = executionConfiguration;
}
/**
* <p>
* The configuration settings for this workflow execution including timeout values, tasklist etc.
* </p>
*
* @return The configuration settings for this workflow execution including timeout values, tasklist etc.
*/
public WorkflowExecutionConfiguration getExecutionConfiguration() {
return this.executionConfiguration;
}
/**
* <p>
* The configuration settings for this workflow execution including timeout values, tasklist etc.
* </p>
*
* @param executionConfiguration
* The configuration settings for this workflow execution including timeout values, tasklist etc.
* @return Returns a reference to this object so that method calls can be chained together.
*/
public WorkflowExecutionDetail withExecutionConfiguration(WorkflowExecutionConfiguration executionConfiguration) {
setExecutionConfiguration(executionConfiguration);
return this;
}
/**
* <p>
* The number of tasks for this workflow execution. This includes open and closed tasks of all types.
* </p>
*
* @param openCounts
* The number of tasks for this workflow execution. This includes open and closed tasks of all types.
*/
public void setOpenCounts(WorkflowExecutionOpenCounts openCounts) {
this.openCounts = openCounts;
}
/**
* <p>
* The number of tasks for this workflow execution. This includes open and closed tasks of all types.
* </p>
*
* @return The number of tasks for this workflow execution. This includes open and closed tasks of all types.
*/
public WorkflowExecutionOpenCounts getOpenCounts() {
return this.openCounts;
}
/**
* <p>
* The number of tasks for this workflow execution. This includes open and closed tasks of all types.
* </p>
*
* @param openCounts
* The number of tasks for this workflow execution. This includes open and closed tasks of all types.
* @return Returns a reference to this object so that method calls can be chained together.
*/
public WorkflowExecutionDetail withOpenCounts(WorkflowExecutionOpenCounts openCounts) {
setOpenCounts(openCounts);
return this;
}
/**
* <p>
* The time when the last activity task was scheduled for this workflow execution. You can use this information to
* determine if the workflow has not made progress for an unusually long period of time and might require a
* corrective action.
* </p>
*
* @param latestActivityTaskTimestamp
* The time when the last activity task was scheduled for this workflow execution. You can use this
* information to determine if the workflow has not made progress for an unusually long period of time and
* might require a corrective action.
*/
public void setLatestActivityTaskTimestamp(java.util.Date latestActivityTaskTimestamp) {
this.latestActivityTaskTimestamp = latestActivityTaskTimestamp;
}
/**
* <p>
* The time when the last activity task was scheduled for this workflow execution. You can use this information to
* determine if the workflow has not made progress for an unusually long period of time and might require a
* corrective action.
* </p>
*
* @return The time when the last activity task was scheduled for this workflow execution. You can use this
* information to determine if the workflow has not made progress for an unusually long period of time and
* might require a corrective action.
*/
public java.util.Date getLatestActivityTaskTimestamp() {
return this.latestActivityTaskTimestamp;
}
/**
* <p>
* The time when the last activity task was scheduled for this workflow execution. You can use this information to
* determine if the workflow has not made progress for an unusually long period of time and might require a
* corrective action.
* </p>
*
* @param latestActivityTaskTimestamp
* The time when the last activity task was scheduled for this workflow execution. You can use this
* information to determine if the workflow has not made progress for an unusually long period of time and
* might require a corrective action.
* @return Returns a reference to this object so that method calls can be chained together.
*/
public WorkflowExecutionDetail withLatestActivityTaskTimestamp(java.util.Date latestActivityTaskTimestamp) {
setLatestActivityTaskTimestamp(latestActivityTaskTimestamp);
return this;
}
/**
* <p>
* The latest executionContext provided by the decider for this workflow execution. A decider can provide an
* executionContext (a free-form string) when closing a decision task using <a>RespondDecisionTaskCompleted</a>.
* </p>
*
* @param latestExecutionContext
* The latest executionContext provided by the decider for this workflow execution. A decider can provide an
* executionContext (a free-form string) when closing a decision task using
* <a>RespondDecisionTaskCompleted</a>.
*/
public void setLatestExecutionContext(String latestExecutionContext) {
this.latestExecutionContext = latestExecutionContext;
}
/**
* <p>
* The latest executionContext provided by the decider for this workflow execution. A decider can provide an
* executionContext (a free-form string) when closing a decision task using <a>RespondDecisionTaskCompleted</a>.
* </p>
*
* @return The latest executionContext provided by the decider for this workflow execution. A decider can provide an
* executionContext (a free-form string) when closing a decision task using
* <a>RespondDecisionTaskCompleted</a>.
*/
public String getLatestExecutionContext() {
return this.latestExecutionContext;
}
/**
* <p>
* The latest executionContext provided by the decider for this workflow execution. A decider can provide an
* executionContext (a free-form string) when closing a decision task using <a>RespondDecisionTaskCompleted</a>.
* </p>
*
* @param latestExecutionContext
* The latest executionContext provided by the decider for this workflow execution. A decider can provide an
* executionContext (a free-form string) when closing a decision task using
* <a>RespondDecisionTaskCompleted</a>.
* @return Returns a reference to this object so that method calls can be chained together.
*/
public WorkflowExecutionDetail withLatestExecutionContext(String latestExecutionContext) {
setLatestExecutionContext(latestExecutionContext);
return this;
}
/**
* Returns a string representation of this object; useful for testing and debugging.
*
* @return A string representation of this object.
*
* @see java.lang.Object#toString()
*/
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("{");
if (getExecutionInfo() != null)
sb.append("ExecutionInfo: ").append(getExecutionInfo()).append(",");
if (getExecutionConfiguration() != null)
sb.append("ExecutionConfiguration: ").append(getExecutionConfiguration()).append(",");
if (getOpenCounts() != null)
sb.append("OpenCounts: ").append(getOpenCounts()).append(",");
if (getLatestActivityTaskTimestamp() != null)
sb.append("LatestActivityTaskTimestamp: ").append(getLatestActivityTaskTimestamp()).append(",");
if (getLatestExecutionContext() != null)
sb.append("LatestExecutionContext: ").append(getLatestExecutionContext());
sb.append("}");
return sb.toString();
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (obj instanceof WorkflowExecutionDetail == false)
return false;
WorkflowExecutionDetail other = (WorkflowExecutionDetail) obj;
if (other.getExecutionInfo() == null ^ this.getExecutionInfo() == null)
return false;
if (other.getExecutionInfo() != null && other.getExecutionInfo().equals(this.getExecutionInfo()) == false)
return false;
if (other.getExecutionConfiguration() == null ^ this.getExecutionConfiguration() == null)
return false;
if (other.getExecutionConfiguration() != null && other.getExecutionConfiguration().equals(this.getExecutionConfiguration()) == false)
return false;
if (other.getOpenCounts() == null ^ this.getOpenCounts() == null)
return false;
if (other.getOpenCounts() != null && other.getOpenCounts().equals(this.getOpenCounts()) == false)
return false;
if (other.getLatestActivityTaskTimestamp() == null ^ this.getLatestActivityTaskTimestamp() == null)
return false;
if (other.getLatestActivityTaskTimestamp() != null && other.getLatestActivityTaskTimestamp().equals(this.getLatestActivityTaskTimestamp()) == false)
return false;
if (other.getLatestExecutionContext() == null ^ this.getLatestExecutionContext() == null)
return false;
if (other.getLatestExecutionContext() != null && other.getLatestExecutionContext().equals(this.getLatestExecutionContext()) == false)
return false;
return true;
}
@Override
public int hashCode() {
final int prime = 31;
int hashCode = 1;
hashCode = prime * hashCode + ((getExecutionInfo() == null) ? 0 : getExecutionInfo().hashCode());
hashCode = prime * hashCode + ((getExecutionConfiguration() == null) ? 0 : getExecutionConfiguration().hashCode());
hashCode = prime * hashCode + ((getOpenCounts() == null) ? 0 : getOpenCounts().hashCode());
hashCode = prime * hashCode + ((getLatestActivityTaskTimestamp() == null) ? 0 : getLatestActivityTaskTimestamp().hashCode());
hashCode = prime * hashCode + ((getLatestExecutionContext() == null) ? 0 : getLatestExecutionContext().hashCode());
return hashCode;
}
@Override
public WorkflowExecutionDetail clone() {
try {
return (WorkflowExecutionDetail) super.clone();
} catch (CloneNotSupportedException e) {
throw new IllegalStateException("Got a CloneNotSupportedException from Object.clone() " + "even though we're Cloneable!", e);
}
}
}
| 39.856354
| 156
| 0.671819
|
ff39adfe0b942c281f50d84c6149dddbd4d26129
| 5,916
|
/**
*
* Copyright 2005 The Apache Software Foundation or its licensors, as applicable
*
* 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.daytrader;
import java.math.BigDecimal;
import java.util.Date;
import java.io.Serializable;
import org.daytrader.util.*;
public class OrderDataBean implements Serializable
{
private Integer orderID; /* orderID */
private String orderType; /* orderType (buy, sell, etc.) */
private String orderStatus; /* orderStatus (open, processing, completed, closed, cancelled) */
private Date openDate; /* openDate (when the order was entered) */
private Date completionDate; /* completionDate */
private double quantity; /* quantity */
private BigDecimal price; /* price */
private BigDecimal orderFee; /* price */
/* Fields for relationship fields are not kept in the Data Bean */
private String symbol;
public OrderDataBean() {}
/**
* OrderDataBean
* @construct an OrderDataBean
*/
public OrderDataBean(Integer orderID,
String orderType,
String orderStatus,
Date openDate,
Date completionDate,
double quantity,
BigDecimal price,
BigDecimal orderFee,
String symbol
)
{
setOrderID(orderID);
setOrderType(orderType);
setOrderStatus(orderStatus);
setOpenDate(openDate);
setCompletionDate(completionDate);
setQuantity(quantity);
setPrice(price);
setOrderFee(orderFee);
setSymbol(symbol);
}
public static OrderDataBean getRandomInstance() {
return new OrderDataBean(
new Integer(TradeConfig.rndInt(100000)),
TradeConfig.rndBoolean() ? "buy" : "sell",
"open",
new java.util.Date(TradeConfig.rndInt(Integer.MAX_VALUE)),
new java.util.Date(TradeConfig.rndInt(Integer.MAX_VALUE)),
TradeConfig.rndQuantity(),
TradeConfig.rndBigDecimal(1000.0f),
TradeConfig.rndBigDecimal(1000.0f),
TradeConfig.rndSymbol()
);
}
public String toString()
{
return "Order " + getOrderID()
+ "\n\t orderType: " + getOrderType()
+ "\n\t orderStatus: " + getOrderStatus()
+ "\n\t openDate: " + getOpenDate()
+ "\n\t completionDate: " + getCompletionDate()
+ "\n\t quantity: " + getQuantity()
+ "\n\t price: " + getPrice()
+ "\n\t orderFee: " + getOrderFee()
+ "\n\t symbol: " + getSymbol()
;
}
public String toHTML()
{
return "<BR>Order <B>" + getOrderID() + "</B>"
+ "<LI> orderType: " + getOrderType() + "</LI>"
+ "<LI> orderStatus: " + getOrderStatus() + "</LI>"
+ "<LI> openDate: " + getOpenDate() + "</LI>"
+ "<LI> completionDate: " + getCompletionDate() + "</LI>"
+ "<LI> quantity: " + getQuantity() + "</LI>"
+ "<LI> price: " + getPrice() + "</LI>"
+ "<LI> orderFee: " + getOrderFee() + "</LI>"
+ "<LI> symbol: " + getSymbol() + "</LI>"
;
}
public void print()
{
Log.log( this.toString() );
}
/**
* Gets the orderID
* @return Returns a Integer
*/
public Integer getOrderID() {
return orderID;
}
/**
* Sets the orderID
* @param orderID The orderID to set
*/
public void setOrderID(Integer orderID) {
this.orderID = orderID;
}
/**
* Gets the orderType
* @return Returns a String
*/
public String getOrderType() {
return orderType;
}
/**
* Sets the orderType
* @param orderType The orderType to set
*/
public void setOrderType(String orderType) {
this.orderType = orderType;
}
/**
* Gets the orderStatus
* @return Returns a String
*/
public String getOrderStatus() {
return orderStatus;
}
/**
* Sets the orderStatus
* @param orderStatus The orderStatus to set
*/
public void setOrderStatus(String orderStatus) {
this.orderStatus = orderStatus;
}
/**
* Gets the openDate
* @return Returns a Date
*/
public Date getOpenDate() {
return openDate;
}
/**
* Sets the openDate
* @param openDate The openDate to set
*/
public void setOpenDate(Date openDate) {
this.openDate = openDate;
}
/**
* Gets the completionDate
* @return Returns a Date
*/
public Date getCompletionDate() {
return completionDate;
}
/**
* Sets the completionDate
* @param completionDate The completionDate to set
*/
public void setCompletionDate(Date completionDate) {
this.completionDate = completionDate;
}
/**
* Gets the quantity
* @return Returns a BigDecimal
*/
public double getQuantity() {
return quantity;
}
/**
* Sets the quantity
* @param quantity The quantity to set
*/
public void setQuantity(double quantity) {
this.quantity = quantity;
}
/**
* Gets the price
* @return Returns a BigDecimal
*/
public BigDecimal getPrice() {
return price;
}
/**
* Sets the price
* @param price The price to set
*/
public void setPrice(BigDecimal price) {
this.price = price;
}
/**
* Gets the orderFee
* @return Returns a BigDecimal
*/
public BigDecimal getOrderFee() {
return orderFee;
}
/**
* Sets the orderFee
* @param orderFee The orderFee to set
*/
public void setOrderFee(BigDecimal orderFee) {
this.orderFee = orderFee;
}
/**
* Gets the symbol
* @return Returns a String
*/
public String getSymbol() {
return symbol;
}
/**
* Sets the symbol
* @param symbol The symbol to set
*/
public void setSymbol(String symbol) {
this.symbol = symbol;
}
}
| 22.494297
| 97
| 0.646214
|
bc30309cb67432403e3d5439815ab5a5012f6c6c
| 9,842
|
package com.openwebserver.core.handlers;
import FileManager.Folder;
import FileManager.Local;
import com.openwebserver.api.Hidden;
import com.openwebserver.core.WebException;
import com.openwebserver.core.WebServer;
import com.openwebserver.core.http.Header;
import com.openwebserver.core.http.Headers;
import com.openwebserver.core.http.content.Code;
import com.openwebserver.core.objects.Request;
import com.openwebserver.core.objects.Response;
import com.openwebserver.core.routing.Route;
import com.openwebserver.core.security.CORS.CORS;
import com.openwebserver.core.security.CORS.Policy;
import com.openwebserver.core.security.CORS.PolicyManager;
import com.openwebserver.core.security.authorization.Authorize;
import com.openwebserver.core.security.authorization.Authorizer;
import com.openwebserver.core.security.content.Accept;
import com.openwebserver.core.security.sessions.SessionManager;
import com.openwebserver.core.security.sessions.annotations.Session;
import com.openwebserver.services.objects.Service;
import org.json.JSONPropertyIgnore;
import java.lang.reflect.InvocationTargetException;
import java.util.function.Consumer;
public class RequestHandler extends Route implements RouteRegister{
private ContentHandler contentHandler;
private final Headers headers = new Headers();
private java.lang.reflect.Method reflection;
private Consumer<RequestHandler> registerListener;
public void setOnRegisterListener(Consumer<RequestHandler> listener){
this.registerListener = listener;
}
public RequestHandler(Route notation, ContentHandler contentHandler) {
this(notation,contentHandler,null);
}
public RequestHandler(Route notation, ContentHandler contentHandler, Session sessionSpecification) {
super(notation);
this.contentHandler = contentHandler;
this.sessionSpecification = sessionSpecification;
}
public void setContentHandler(ContentHandler contentHandler){
this.contentHandler = contentHandler;
}
public Response handle(Request request) throws WebException {
request.setHandler(this);
handleCORS(request);
if (!super.hasRequired(request)) {
throw new WebException(Code.Bad_Request, "method requires arguments").extra("required", getRequired()).addRequest(request);
}
if(acceptedContentType != null && headers.containsKey("Content-Type")){
Header header = headers.get("Content-Type");
System.out.println(header);
//TODO Filter Accepted content with requesthandler
}
if(needsAuthentication() && !getAuthorizer().authorize(request)){
throw new WebException(Code.Unauthorized,"Invalid Token").addRequest(request);
}
try {
SessionManager.bind(sessionSpecification, request);
}catch (com.openwebserver.core.security.sessions.Session.SessionException e){
if(sessionSpecification != null && !sessionSpecification.redirect().equals("")){
return Response.simple(Code.Temporary_Redirect).addHeader(new Header("Location", sessionSpecification.redirect())).addHeaders(this.headers);
}
throw e;
}
return contentHandler.respond(request);
}
public Headers getHeaders() {
return headers;
}
@Override
public void addPrefix(String prefix) {
super.addPrefix(prefix);
if(CORS_handler != null){
CORS_handler.addPrefix(prefix);
}
}
//region sessions
private SessionHandler sessionHandler = (annotation, session) -> session.hasRequired(annotation.require());
private Session sessionSpecification;
public void setSessionHandler(SessionHandler handler){
this.sessionHandler = handler;
}
public void setSessionSpecification(Session sessionSpecification) {
this.sessionSpecification = sessionSpecification;
}
@JSONPropertyIgnore
public SessionHandler getSessionHandler() {
return sessionHandler;
}
public Session getSessionSpecification() {
return sessionSpecification;
}
//endregion
//region CORS
public void handleCORS(Request request){
if(overrideOrigin){
request.headers.tryGet("Origin", header -> this.headers.replace("Access-Control-Allow-Origin", header.getValue()));
}
}
private Policy policy;
private boolean overrideOrigin = false;
private RequestHandler CORS_handler;
public void setCORSPolicy(CORS policy) {
if(policy != null) {
setCORSPolicy(policy.value(), policy.overrideOrigin());
}
}
public void setCORSPolicy(String policy) {
setCORSPolicy(policy, false);
}
public void setCORSPolicy(String policy, boolean overrideOrigin) {
if(policy == null){
return;
}
try {
this.policy = PolicyManager.getPolicy(policy);
this.headers.addAll(this.policy.pack());
CORS_handler = new RequestHandler(new Route(this.getPath(), Method.OPTIONS), request -> {
Headers headers = getPolicy().pack();
if(overrideOrigin){
request.headers.tryGet("Origin", header -> headers.replace("Access-Control-Allow-Origin", header.getValue()));
}
return Response.simple(Code.No_Content).addHeaders(headers);
});
this.overrideOrigin = overrideOrigin;
} catch (PolicyManager.PolicyException.NotFound notFound) {
notFound.printStackTrace();
} catch (PolicyManager.PolicyException e) {
if(!overrideOrigin){
e.printStackTrace();
}
}
}
public String getPolicyName() {
if(getPolicy() != null){
return getPolicy().getName();
}
return null;
}
public Policy getPolicy() {
return policy;
}
//endregion
//region Authentication
private Authorizer<?> authorizer;
public void setAuthorizer(Authorizer<?> authorizer){
if(needsAuthentication()) {
this.authorizer = authorizer;
}
}
protected Authorizer<?> getAuthorizer() {
return authorizer;
}
//endregion
//region method reflection
public void setReflection(java.lang.reflect.Method method){
setSessionSpecification(method.isAnnotationPresent(Session.class)? method.getAnnotation(Session.class): null);
setCORSPolicy(method.isAnnotationPresent(CORS.class)? method.getAnnotation(CORS.class): null);
setNeedsAuthentication(method.isAnnotationPresent(Authorize.class));
setAcceptContent(method.isAnnotationPresent(Accept.class)? method.getAnnotation(Accept.class): null);
setHidden(method.isAnnotationPresent(Hidden.class));
this.reflection = method;
}
@JSONPropertyIgnore
public java.lang.reflect.Method getReflection() {
return reflection;
}
//endregion
//region contenttype
private Accept acceptedContentType;
private void setAcceptContent(Accept accept) {
this.acceptedContentType = accept;
}
public void acceptsContent(){
}
//endregion
@Override
public void register(Consumer<RequestHandler> routeConsumer) {
routeConsumer.accept(this);
if(CORS_handler != null){
routeConsumer.accept(CORS_handler);
}
if(registerListener != null){
registerListener.accept(this);
}
}
public static RequestHandler inline(String path, Method method, ContentHandler handler){
return new RequestHandler(new Route(path, method), handler);
}
public static RequestHandler folder(String path){
return RequestHandler.folder(new Folder(path));
}
public static RequestHandler folder(Folder folder){
return folder("", folder);
}
public static RequestHandler folder(String pathPrefix, Folder f){
return new RequestHandler(new Route(pathPrefix + "/#", Method.GET), request -> {
String path = request.getPath(true);
if(path.endsWith("/") || !path.contains("."))
{
return Response.simple(new Local(f.getPath() + "/" + WebServer.rootFilename));
}
return Response.simple(new Local(f.getPath() + path));
});
}
public static void wrap(java.lang.reflect.Method method, Service service){
if(method.isAnnotationPresent(com.openwebserver.services.annotations.Route.class)) {
RequestHandler handler = new RequestHandler(new Route(method.getAnnotation(com.openwebserver.services.annotations.Route.class)), null);
method.setAccessible(true);
if (method.getReturnType().equals(Response.class)) {
handler.setContentHandler(request -> {
try {
return ((Response) method.invoke(service, request));
} catch (InvocationTargetException | IllegalAccessException e) {
throw new WebException(e).addRequest(request);
}
});
} else {
handler.setContentHandler(request -> {
try {
return Response.simple(method.invoke(service, request));
} catch (InvocationTargetException | IllegalAccessException e) {
throw new WebException(e).addRequest(request);
}
});
}
handler.setReflection(method);
handler.setOnRegisterListener(service);
handler.setSessionHandler(service.getSessionHandler());
service.add(handler);
}
}
}
| 36.587361
| 156
| 0.657793
|
d7b88d56d015ea7cf2e7832b00a392e8eabac336
| 3,745
|
package plp.functional3.expression;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import plp.expressions1.util.Tipo;
import plp.expressions2.expression.Expressao;
import plp.expressions2.expression.Id;
import plp.expressions2.expression.Valor;
import plp.expressions2.memory.AmbienteCompilacao;
import plp.expressions2.memory.AmbienteExecucao;
import plp.expressions2.memory.VariavelJaDeclaradaException;
import plp.expressions2.memory.VariavelNaoDeclaradaException;
import plp.functional3.util.TipoLista;
public class ExpCompreensaoLista implements Expressao {
private Expressao expressao;
private Expressao filtro;
private Gerador gerador;
public ExpCompreensaoLista(Expressao expressao) {
this.expressao = expressao;
}
public void setFiltro(Expressao filtro) {
this.filtro = filtro;
}
public void add(Gerador gerador) {
if (this.gerador == null) {
this.gerador = gerador;
} else {
this.gerador.addProximoGerador(gerador);
}
}
public void setGeradores(List<Gerador> geradores) {
for (Gerador geradorTemp : geradores) {
this.add(geradorTemp);
}
}
public Valor avaliar(AmbienteExecucao amb)
throws VariavelNaoDeclaradaException, VariavelJaDeclaradaException {
ValorLista result = ValorLista.getInstancia(null, null);
gerador.gerarValores(amb, result, expressao, filtro);
return result.inverter();
}
public boolean checaTipo(AmbienteCompilacao amb)
throws VariavelNaoDeclaradaException, VariavelJaDeclaradaException {
if (!temGerador())
return false;
boolean retorno = gerador.checaTipo(amb);
amb.incrementa();
mapTypeBindings(amb);
retorno &= expressao.checaTipo(amb);
retorno &= filtroChecaTipo(amb);
amb.restaura();
return retorno;
}
private void mapTypeBindings(AmbienteCompilacao amb) {
Map<Id, Tipo> typeBindings = gerador.checkTypeBindings(amb);
Set<Entry<Id, Tipo>> entrySet = typeBindings.entrySet();
for (Entry<Id, Tipo> entry : entrySet) {
amb.map(entry.getKey(), entry.getValue());
}
}
private boolean temGerador() {
return gerador != null;
}
private boolean filtroChecaTipo(AmbienteCompilacao amb) {
return filtro == null || filtro.checaTipo(amb)
&& filtro.getTipo(amb).eBooleano();
}
public Tipo getTipo(AmbienteCompilacao amb)
throws VariavelNaoDeclaradaException, VariavelJaDeclaradaException {
amb.incrementa();
mapTypeBindings(amb);
TipoLista retorno = new TipoLista(expressao.getTipo(amb));
amb.restaura();
return retorno;
}
public ExpCompreensaoLista clone() {
ExpCompreensaoLista retorno = new ExpCompreensaoLista(this.expressao.clone());
retorno.setFiltro(this.filtro.clone());
if (this.gerador != null) {
List<Gerador> listaGer = new ArrayList<Gerador>();
Gerador ger = this.gerador;
do {
listaGer.add(ger);
ger = ger.getProximoGerador();
} while(ger.temProximoGerador());
retorno.setGeradores(listaGer);
}
return retorno;
}
public Expressao reduzir(AmbienteExecucao ambiente) {
ambiente.incrementa();
Gerador ger = this.gerador;
while(ger.temProximoGerador()){
ger.reduzir(ambiente);
ger = ger.getProximoGerador();
}
this.expressao = this.expressao.reduzir(ambiente);
if (this.filtro != null) {
this.filtro = this.filtro.reduzir(ambiente);
}
ambiente.restaura();
return this;
}
public String toString() {
String aux = this.expressao.toString();
Gerador ger = this.gerador;
aux += ger.toString();
while(ger.temProximoGerador()){
ger = ger.getProximoGerador();
aux += "," + ger.toString();
}
if (this.filtro != null) {
aux += " if "+this.filtro;
}
return aux;
}
}
| 22.835366
| 80
| 0.723632
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.