repo_name stringlengths 5 108 | path stringlengths 6 333 | size stringlengths 1 6 | content stringlengths 4 977k | license stringclasses 15
values |
|---|---|---|---|---|
lessthanoptimal/BoofCV | main/boofcv-sfm/src/test/java/boofcv/abst/sfm/d3/TestPyramidDirectColorDepth_to_DepthVisualOdometry.java | 2124 | /*
* Copyright (c) 2011-2020, Peter Abeles. All Rights Reserved.
*
* This file is part of BoofCV (http://boofcv.org).
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package boofcv.abst.sfm.d3;
import boofcv.alg.sfm.DepthSparse3D;
import boofcv.alg.sfm.d3.direct.PyramidDirectColorDepth;
import boofcv.core.image.ConvertImageFilter;
import boofcv.factory.transform.pyramid.FactoryPyramid;
import boofcv.struct.image.GrayU16;
import boofcv.struct.image.GrayU8;
import boofcv.struct.image.ImageType;
import boofcv.struct.image.Planar;
import boofcv.struct.pyramid.ConfigDiscreteLevels;
import boofcv.struct.pyramid.ImagePyramid;
/**
* @author Peter Abeles
*/
public class TestPyramidDirectColorDepth_to_DepthVisualOdometry extends CheckVisualOdometryDepthSim<GrayU8, GrayU16> {
public TestPyramidDirectColorDepth_to_DepthVisualOdometry() {
super(GrayU8.class, GrayU16.class);
setAlgorithm(createAlgorithm());
}
protected DepthVisualOdometry<GrayU8, GrayU16> createAlgorithm() {
ConfigDiscreteLevels config = ConfigDiscreteLevels.levels(3);
ImagePyramid<Planar<GrayU8>> pyramid = FactoryPyramid.discreteGaussian(config,
-1, 2, false, ImageType.pl(1, GrayU8.class));
PyramidDirectColorDepth<GrayU8> alg = new PyramidDirectColorDepth<>(pyramid);
ConvertImageFilter<GrayU8, Planar<GrayU8>> convertInput = new ConvertImageFilter<>(
ImageType.single(GrayU8.class), ImageType.pl(1, GrayU8.class));
DepthSparse3D<GrayU16> sparse3D = new DepthSparse3D.I<>(depthUnits);
return new PyramidDirectColorDepth_to_DepthVisualOdometry<>(sparse3D, convertInput, alg, GrayU16.class);
}
}
| apache-2.0 |
dieselpoint/diesel.cluster | diesel.cluster.transport.simulator/src/main/java/com/dieselpoint/cluster/transport/simulator/SimulatorTransportServer.java | 539 | package com.dieselpoint.cluster.transport.simulator;
import java.util.concurrent.CompletableFuture;
import java.util.function.Function;
import com.dieselpoint.cluster.common.Message;
import com.dieselpoint.cluster.common.TransportServer;
public class SimulatorTransportServer implements TransportServer {
Function<Message, CompletableFuture<Message>> listener;
@Override
public void close() {
}
@Override
public void setListener(Function<Message, CompletableFuture<Message>> listener) {
this.listener = listener;
}
}
| apache-2.0 |
schorndorfer/uima-components | annotator-parent/type-system/src/main/java/org/apache/ctakes/typesystem/type/textsem/MedicationDurationModifier.java | 1858 |
/* First created by JCasGen Fri Jan 03 13:40:16 CST 2014 */
package org.apache.ctakes.typesystem.type.textsem;
import org.apache.uima.jcas.JCas;
import org.apache.uima.jcas.JCasRegistry;
import org.apache.uima.jcas.cas.TOP_Type;
/** The amount of time after which a medication should stop
being used, e.g., "2 weeks" in "one 5 mg tablet twice-a-day for 2
weeks"
* Updated by JCasGen Fri Jan 03 13:40:16 CST 2014
* XML source: C:/WKT/git/schorndorfer/uima-components/annotator-parent/type-system/src/main/resources/org/apache/ctakes/typesystem/types/TypeSystem.xml
* @generated */
public class MedicationDurationModifier extends Modifier {
/** @generated
* @ordered
*/
@SuppressWarnings ("hiding")
public final static int typeIndexID = JCasRegistry.register(MedicationDurationModifier.class);
/** @generated
* @ordered
*/
@SuppressWarnings ("hiding")
public final static int type = typeIndexID;
/** @generated */
@Override
public int getTypeIndexID() {return typeIndexID;}
/** Never called. Disable default constructor
* @generated */
protected MedicationDurationModifier() {/* intentionally empty block */}
/** Internal - constructor used by generator
* @generated */
public MedicationDurationModifier(int addr, TOP_Type type) {
super(addr, type);
readObject();
}
/** @generated */
public MedicationDurationModifier(JCas jcas) {
super(jcas);
readObject();
}
/** @generated */
public MedicationDurationModifier(JCas jcas, int begin, int end) {
super(jcas);
setBegin(begin);
setEnd(end);
readObject();
}
/** <!-- begin-user-doc -->
* Write your own initialization here
* <!-- end-user-doc -->
@generated modifiable */
private void readObject() {/*default - does nothing empty block */}
}
| apache-2.0 |
tanhaichao/leopard | myjetty/myjetty-workbench/src/main/java/io/leopard/myjetty/workbench/WebappServlet.java | 5277 | package io.leopard.myjetty.workbench;
import java.io.IOException;
import java.io.OutputStream;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.util.StringUtils;
import io.leopard.myjetty.web.freemarker.JsonView;
import io.leopard.myjetty.web.freemarker.MyJettyView;
import io.leopard.myjetty.webapp.WebappServiceImpl;
public class WebappServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
private WebappController webappController = WebappController.getInstance();
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String uri = request.getRequestURI();
System.out.println("doGet uri:" + uri);
if ("/workbench/webapp".equals(uri)) {
this.index(request, response);
}
else if ("/workbench/webapp/".equals(uri)) {
this.index(request, response);
}
else if ("/workbench/webapp/index".equals(uri)) {
this.index(request, response);
}
else if ("/workbench/webapp/start".equals(uri)) {
this.start(request, response);
}
else if ("/workbench/webapp/stop".equals(uri)) {
this.stop(request, response);
}
else if ("/workbench/webapp/restart".equals(uri)) {
this.restart(request, response);
}
else if ("/workbench/webapp/update".equals(uri)) {
this.update(request, response);
}
else if ("/workbench/webapp/compile".equals(uri)) {
this.compile(request, response);
}
else if ("/workbench/webapp/deploy".equals(uri)) {
this.deploy(request, response);
}
else if ("/workbench/webapp/packaging".equals(uri)) {
this.packaging(request, response);
}
else {
throw new ServletException("未知地址[" + uri + "].");
}
}
protected void index(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String projectId = this.getProjectId(request);
MyJettyView view = new MyJettyView("webapp");
view.addObject("projectId", projectId);
view.render(request, response);
}
protected String getProjectId(HttpServletRequest request) {
String projectId = request.getParameter("projectId");
if (StringUtils.isEmpty(projectId)) {
// TODO ahai
// projectId = WebappServiceImpl.getInstance().getDefaultProjectId();
// if (projectId == null) {
// projectId = "";
// }
}
return projectId;
}
protected void start(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/plain; charset=UTF-8");
String projectId = this.getProjectId(request);
this.webappController.start(projectId);
JsonView view = new JsonView("starting");
view.render(request, response);
}
protected void stop(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/plain; charset=UTF-8");
String projectId = this.getProjectId(request);
this.webappController.stop(projectId);
JsonView view = new JsonView("stop");
view.render(request, response);
}
protected void restart(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/plain; charset=UTF-8");
String projectId = this.getProjectId(request);
webappController.restart(projectId);
JsonView view = new JsonView("restart");
view.render(request, response);
}
protected void deploy(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/plain; charset=UTF-8");
String projectId = this.getProjectId(request);
OutputStream output = response.getOutputStream();
webappController.svnupdate(projectId, output);
webappController.packaging(projectId, output);
webappController.restart(projectId);
// JsonView view = new JsonView("deploy");
// view.render(request, response);
}
protected void packaging(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/plain; charset=UTF-8");
String projectId = this.getProjectId(request);
this.webappController.packaging(projectId, response.getOutputStream());
response.flushBuffer();
// JsonView view = new JsonView("packaging");
// view.render(request, response);
}
protected void compile(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/plain; charset=UTF-8");
String projectId = this.getProjectId(request);
this.webappController.compile(projectId, response.getOutputStream());
// JsonView view = new JsonView("compile");
// view.render(request, response);
}
protected void update(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/plain; charset=UTF-8");
String projectId = this.getProjectId(request);
this.webappController.svnupdate(projectId, response.getOutputStream());
}
}
| apache-2.0 |
Top-Q/jsystem | jsystem-core-projects/jsystemCore/src/main/java/jsystem/framework/scenario/ScenarioAsTest.java | 667 | /*
* Copyright 2005-2010 Ignis Software Tools Ltd. All rights reserved.
*/
package jsystem.framework.scenario;
import junit.framework.SystemTestCase;
import junit.framework.Test;
/**
* A wrapper to signal that a Scenario is ran as a Test<br>
* will hold the current running test inside the ScenarioTest
*
* @author Nizan Freedman
*
*/
public class ScenarioAsTest extends SystemTestCase {
private RunnerTest currentRunnerTest;
public RunnerTest getCurrentRunnerTest() {
return currentRunnerTest;
}
public void setCurrentRunnerTest(Test test) {
currentRunnerTest = ScenariosManager.getInstance().getCurrentScenario().findRunnerTest(test);
}
}
| apache-2.0 |
xiaguangme/struts2-src-study | src/org/apache/struts2/interceptor/ApplicationAware.java | 1549 | /*
* $Id: ApplicationAware.java 651946 2008-04-27 13:41:38Z apetrelli $
*
* 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.struts2.interceptor;
import java.util.Map;
/**
* Actions that want to be aware of the application Map object should implement this interface.
* This will give them access to a Map where they can put objects that should be available
* to other parts of the application. <p>
* <p/>
* Typical uses are configuration objects and caches.
*
*/
public interface ApplicationAware {
/**
* Sets the map of application properties in the implementing class.
*
* @param application a Map of application properties.
*/
public void setApplication(Map<String,Object> application);
}
| apache-2.0 |
matobet/mustech | server/src/main/java/cz/muni/fi/pv243/mustech/service/PermissionService.java | 695 | package cz.muni.fi.pv243.mustech.service;
import cz.muni.fi.pv243.mustech.model.BaseModel;
import javax.annotation.Resource;
import javax.ejb.EJBContext;
import javax.ejb.Stateless;
import javax.enterprise.inject.Default;
/**
* Simple EJB helper to access the Security Context from CDI service beans
*/
@Stateless
@Default
public class PermissionService implements IPermissionService{
@Resource
private EJBContext context;
public <T extends BaseModel> boolean checkAccess(PrincipalChecker<T> checker, T entity) {
String principal = context.getCallerPrincipal().getName();
return context.isCallerInRole("ADMIN") || checker.canAccess(principal, entity);
}
}
| apache-2.0 |
shliama/AutoRotateExtension | src/main/java/ua/orangelamp/dashclockrotateextension/AutoRotateExtension.java | 1486 | package ua.orangelamp.dashclockrotateextension;
import android.content.ContentResolver;
import android.provider.Settings;
import com.google.android.apps.dashclock.api.DashClockExtension;
import com.google.android.apps.dashclock.api.ExtensionData;
public class AutoRotateExtension extends DashClockExtension {
@Override
protected void onUpdateData(int reason) {
ContentResolver resolver = getContentResolver();
boolean autoOrientationEnabled = getAutoOrientationEnabled(resolver);
if (reason == UPDATE_REASON_MANUAL) {
setAutoOrientationEnabled(resolver, !autoOrientationEnabled);
autoOrientationEnabled = getAutoOrientationEnabled(resolver);
}
publishUpdate(new ExtensionData()
.visible(true)
.icon(autoOrientationEnabled ? R.drawable.ic_auto_rotate_on : R.drawable.ic_auto_rotate_off)
.status(autoOrientationEnabled ? "ON" : "OFF")
.expandedTitle("Auto-rotate screen - " + (autoOrientationEnabled ? "On" : "Off")));
}
public boolean getAutoOrientationEnabled(ContentResolver resolver) {
return android.provider.Settings.System.getInt(resolver,
Settings.System.ACCELEROMETER_ROTATION, 0) == 1;
}
public void setAutoOrientationEnabled(ContentResolver resolver, boolean enabled) {
Settings.System.putInt(resolver,
Settings.System.ACCELEROMETER_ROTATION, enabled ? 1 : 0);
}
}
| apache-2.0 |
pepstock-org/Charba | src/org/pepstock/charba/client/defaults/IsDefaultBoxHandler.java | 1024 | /**
Copyright 2017 Andrea "Stock" Stocchero
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.pepstock.charba.client.defaults;
/**
* Interface to define box dimension of options elements.
*
* @author Andrea "Stock" Stocchero
*
*/
public interface IsDefaultBoxHandler {
/**
* Returns the width of colored box.
*
* @return width of colored box.
*/
int getBoxWidth();
/**
* Returns the height of colored box.
*
* @return height of colored box.
*/
int getBoxHeight();
} | apache-2.0 |
consulo/consulo | modules/base/lang-api/src/main/java/com/intellij/psi/codeStyle/autodetect/IndentOptionsAdjuster.java | 862 | /*
* Copyright 2000-2016 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.intellij.psi.codeStyle.autodetect;
import com.intellij.psi.codeStyle.CommonCodeStyleSettings;
import javax.annotation.Nonnull;
public interface IndentOptionsAdjuster {
void adjust(@Nonnull CommonCodeStyleSettings.IndentOptions indentOptions);
}
| apache-2.0 |
EXEM-OSS/flamingo | flamingo-web/src/main/java/org/exem/flamingo/web/model/rest/NodeType.java | 1043 | /*
* Copyright 2012-2016 the Flamingo Community.
*
* 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.exem.flamingo.web.model.rest;
import java.io.Serializable;
/**
* Created by sanghyunbak on 2016. 12. 6..
*/
public enum NodeType implements Serializable {
FOLDER("folder"), ITEM("item");
/**
* 노드 유형의 문자열 값
*/
public final String value;
/**
* 기본 생성자.
*
* @param value 노드 유형의 문자열 값
*/
NodeType(String value) {
this.value = value;
}
} | apache-2.0 |
opencb/hpg-bigdata | hpg-bigdata-core/src/main/java/org/opencb/hpg/bigdata/core/config/StorageEtlConfiguration.java | 2266 | /*
* Copyright 2015 OpenCB
*
* 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.opencb.hpg.bigdata.core.config;
import org.opencb.commons.datastore.core.ObjectMap;
/**
* Created by imedina on 09/05/15.
*/
public class StorageEtlConfiguration {
private String manager;
/**
* options parameter defines database-specific parameters.
*/
private ObjectMap options;
private DatabaseCredentials database;
public StorageEtlConfiguration() {
}
// public StorageEtlConfiguration(String manager, Map<String, String> options, DatabaseCredentials database) {
// this.manager = manager;
// this.options = options;
// this.database = database;
// }
public StorageEtlConfiguration(String manager, ObjectMap options, DatabaseCredentials database) {
this.manager = manager;
this.options = options;
this.database = database;
}
@Override
public String toString() {
final StringBuilder sb = new StringBuilder("StorageEtlConfiguration{");
sb.append("manager='").append(manager).append('\'');
sb.append(", options=").append(options);
sb.append(", database=").append(database);
sb.append('}');
return sb.toString();
}
public String getManager() {
return manager;
}
public void setManager(String manager) {
this.manager = manager;
}
public ObjectMap getOptions() {
return options;
}
public void setOptions(ObjectMap options) {
this.options = options;
}
public DatabaseCredentials getDatabase() {
return database;
}
public void setDatabase(DatabaseCredentials database) {
this.database = database;
}
}
| apache-2.0 |
SpannaProject/SpannaAPI | src/main/java/org/spanna/material/Stairs.java | 2782 | package org.spanna.material;
import org.spanna.Material;
import org.spanna.block.BlockFace;
/**
* Represents stairs.
*/
public class Stairs extends MaterialData implements Directional {
/**
*
* @deprecated Magic value
*/
@Deprecated
public Stairs(final int type) {
super(type);
}
public Stairs(final Material type) {
super(type);
}
/**
*
* @deprecated Magic value
*/
@Deprecated
public Stairs(final int type, final byte data) {
super(type, data);
}
/**
*
* @deprecated Magic value
*/
@Deprecated
public Stairs(final Material type, final byte data) {
super(type, data);
}
/**
* @return the direction the stairs ascend towards
*/
public BlockFace getAscendingDirection() {
byte data = getData();
switch (data & 0x3) {
case 0x0:
default:
return BlockFace.EAST;
case 0x1:
return BlockFace.WEST;
case 0x2:
return BlockFace.SOUTH;
case 0x3:
return BlockFace.NORTH;
}
}
/**
* @return the direction the stairs descend towards
*/
public BlockFace getDescendingDirection() {
return getAscendingDirection().getOppositeFace();
}
/**
* Set the direction the stair part of the block is facing
*/
public void setFacingDirection(BlockFace face) {
byte data;
switch (face) {
case NORTH:
data = 0x3;
break;
case SOUTH:
data = 0x2;
break;
case EAST:
default:
data = 0x0;
break;
case WEST:
data = 0x1;
break;
}
setData((byte) ((getData() & 0xC) | data));
}
/**
* @return the direction the stair part of the block is facing
*/
public BlockFace getFacing() {
return getDescendingDirection();
}
/**
* Test if step is inverted
*
* @return true if inverted (top half), false if normal (bottom half)
*/
public boolean isInverted() {
return ((getData() & 0x4) != 0);
}
/**
* Set step inverted state
*
* @param inv - true if step is inverted (top half), false if step is
* normal (bottom half)
*/
public void setInverted(boolean inv) {
int dat = getData() & 0x3;
if (inv) {
dat |= 0x4;
}
setData((byte) dat);
}
@Override
public String toString() {
return super.toString() + " facing " + getFacing() + (isInverted()?" inverted":"");
}
@Override
public Stairs clone() {
return (Stairs) super.clone();
}
}
| apache-2.0 |
SVADemoAPP/webServer | src/main/java/web/com/sva/web/controllers/RangemapController.java | 3109 | package com.sva.web.controllers;
import java.util.Collection;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import com.sva.common.ConvertUtil;
import com.sva.dao.CommonDao;
import com.sva.dao.RangemapDao;
import com.sva.model.LinemapModel;
@Controller
@RequestMapping(value = "/rangemap")
public class RangemapController
{
@Autowired
private RangemapDao dao;
@Autowired
private CommonDao daoCom;
@Value("${mysql.db}")
private String db;
@RequestMapping(value = "/api/getChartData", method = {RequestMethod.POST})
@ResponseBody
public Map<String, Object> getChartData(
@RequestParam("placeId") String placeId,
@RequestParam("floorNo") String floorNo,
@RequestParam("time") String time, @RequestParam("x1") String x1,
@RequestParam("y1") String y1, @RequestParam("x2") String x2,
@RequestParam("y2") String y2)
{
Collection<LinemapModel> res = null;
Date d = ConvertUtil.dateStringFormat(time, "yyyy-MM-dd");
String dStr = ConvertUtil.dateFormat(d, "yyyyMMdd");
String table = "location" + dStr;
Map<String, Object> modelMap = new HashMap<String, Object>(2);
if (daoCom.isTableExist(table, db) > 0)
{
res = dao.getData(placeId, floorNo, x1, y1, x2, y2, table);
modelMap.put("error", false);
modelMap.put("data", res);
}
else
{
modelMap.put("error", false);
modelMap.put("data", res);
}
return modelMap;
}
@RequestMapping(value = "/api/getInfoData", method = {RequestMethod.POST})
@ResponseBody
public Map<String, Object> getInfoData(
@RequestParam("placeId") String placeId,
@RequestParam("floorNo") String floorNo,
@RequestParam("time") String time, @RequestParam("x1") String x1,
@RequestParam("y1") String y1, @RequestParam("x2") String x2,
@RequestParam("y2") String y2)
{
int count = 0;
Date d = ConvertUtil.dateStringFormat(time, "yyyy-MM-dd");
String dStr = ConvertUtil.dateFormat(d, "yyyyMMdd");
String table = "location" + dStr;
Map<String, Object> modelMap = new HashMap<String, Object>(2);
if (daoCom.isTableExist(table, db) > 0)
{
count = dao.getTotalCount(placeId, floorNo, x1, y1, x2, y2, table);
modelMap.put("error", false);
modelMap.put("total", count);
}
else
{
modelMap.put("error", true);
modelMap.put("total", count);
}
return modelMap;
}
}
| apache-2.0 |
stevem999/gocd | plugin-infra/go-plugin-infra/src/main/java/com/thoughtworks/go/plugin/infra/DefaultPluginManager.java | 9092 | /*
* Copyright 2018 ThoughtWorks, 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.thoughtworks.go.plugin.infra;
import com.thoughtworks.go.plugin.api.GoPlugin;
import com.thoughtworks.go.plugin.api.exceptions.UnhandledRequestTypeException;
import com.thoughtworks.go.plugin.api.info.PluginDescriptor;
import com.thoughtworks.go.plugin.api.request.GoPluginApiRequest;
import com.thoughtworks.go.plugin.api.response.GoPluginApiResponse;
import com.thoughtworks.go.plugin.infra.commons.PluginUploadResponse;
import com.thoughtworks.go.plugin.infra.listeners.DefaultPluginJarChangeListener;
import com.thoughtworks.go.plugin.infra.monitor.DefaultPluginJarLocationMonitor;
import com.thoughtworks.go.plugin.infra.plugininfo.DefaultPluginRegistry;
import com.thoughtworks.go.plugin.infra.plugininfo.GoPluginDescriptor;
import com.thoughtworks.go.util.FileUtil;
import com.thoughtworks.go.util.SystemEnvironment;
import org.apache.commons.io.FileUtils;
import org.apache.http.HttpStatus;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.io.File;
import java.io.IOException;
import java.util.*;
import static com.thoughtworks.go.util.SystemEnvironment.PLUGIN_BUNDLE_PATH;
import static java.lang.Double.parseDouble;
@Service
public class DefaultPluginManager implements PluginManager {
private static final Logger LOGGER = LoggerFactory.getLogger(DefaultPluginManager.class);
private final DefaultPluginJarLocationMonitor monitor;
private DefaultPluginRegistry registry;
private final DefaultPluginJarChangeListener defaultPluginJarChangeListener;
private SystemEnvironment systemEnvironment;
private File bundleLocation;
private GoPluginOSGiFramework goPluginOSGiFramework;
private PluginWriter pluginWriter;
private PluginValidator pluginValidator;
private final Map<PluginDescriptor, Set<String>> initializedPluginsWithTheirExtensionTypes = new HashMap<>();
private PluginRequestProcessorRegistry requestProcesRegistry;
@Autowired
public DefaultPluginManager(DefaultPluginJarLocationMonitor monitor, DefaultPluginRegistry registry, GoPluginOSGiFramework goPluginOSGiFramework,
DefaultPluginJarChangeListener defaultPluginJarChangeListener, PluginRequestProcessorRegistry requestProcesRegistry, PluginWriter pluginWriter,
PluginValidator pluginValidator, SystemEnvironment systemEnvironment) {
this.monitor = monitor;
this.registry = registry;
this.defaultPluginJarChangeListener = defaultPluginJarChangeListener;
this.requestProcesRegistry = requestProcesRegistry;
this.systemEnvironment = systemEnvironment;
bundleLocation = bundlePath();
this.goPluginOSGiFramework = goPluginOSGiFramework;
this.pluginWriter = pluginWriter;
this.pluginValidator = pluginValidator;
}
@Override
public List<GoPluginDescriptor> plugins() {
return registry.plugins();
}
public PluginUploadResponse addPlugin(File uploadedPlugin, String filename) {
if (!pluginValidator.namecheckForJar(filename)) {
Map<Integer, String> errors = new HashMap<>();
errors.put(HttpStatus.SC_UNSUPPORTED_MEDIA_TYPE, "Please upload a jar.");
return PluginUploadResponse.create(false, null, errors);
}
return pluginWriter.addPlugin(uploadedPlugin, filename);
}
@Override
public GoPluginDescriptor getPluginDescriptorFor(String pluginId) {
return registry.getPlugin(pluginId);
}
@Override
public void startInfrastructure(boolean shouldPoll) {
removeBundleDirectory();
goPluginOSGiFramework.start();
addPluginChangeListener(new PluginChangeListener() {
@Override
public void pluginLoaded(GoPluginDescriptor pluginDescriptor) {
}
@Override
public void pluginUnLoaded(GoPluginDescriptor pluginDescriptor) {
synchronized (initializedPluginsWithTheirExtensionTypes) {
initializedPluginsWithTheirExtensionTypes.remove(pluginDescriptor);
}
}
});
monitor.addPluginJarChangeListener(defaultPluginJarChangeListener);
if (shouldPoll) {
monitor.start();
} else {
monitor.oneShot();
}
}
@Override
public void stopInfrastructure() {
goPluginOSGiFramework.stop();
monitor.stop();
initializedPluginsWithTheirExtensionTypes.clear();
}
@Override
public void addPluginChangeListener(PluginChangeListener pluginChangeListener) {
goPluginOSGiFramework.addPluginChangeListener(pluginChangeListener);
}
@Override
public GoPluginApiResponse submitTo(final String pluginId, String extensionType, final GoPluginApiRequest apiRequest) {
return goPluginOSGiFramework.doOn(GoPlugin.class, pluginId, extensionType, new ActionWithReturn<GoPlugin, GoPluginApiResponse>() {
@Override
public GoPluginApiResponse execute(GoPlugin plugin, GoPluginDescriptor pluginDescriptor) {
ensureInitializerInvoked(pluginDescriptor, plugin, extensionType);
try {
return plugin.handle(apiRequest);
} catch (UnhandledRequestTypeException e) {
LOGGER.error(e.getMessage());
LOGGER.debug(e.getMessage(), e);
throw new RuntimeException(e);
}
}
});
}
private void ensureInitializerInvoked(GoPluginDescriptor pluginDescriptor, GoPlugin plugin, String extensionType) {
synchronized (initializedPluginsWithTheirExtensionTypes) {
if (initializedPluginsWithTheirExtensionTypes.get(pluginDescriptor) == null) {
initializedPluginsWithTheirExtensionTypes.put(pluginDescriptor, new HashSet<>());
}
Set<String> initializedExtensions = initializedPluginsWithTheirExtensionTypes.get(pluginDescriptor);
if (initializedExtensions == null || initializedExtensions.contains(extensionType)) {
return;
}
initializedPluginsWithTheirExtensionTypes.get(pluginDescriptor).add(extensionType);
PluginAwareDefaultGoApplicationAccessor accessor = new PluginAwareDefaultGoApplicationAccessor(pluginDescriptor, requestProcesRegistry);
plugin.initializeGoApplicationAccessor(accessor);
}
}
@Override
public boolean isPluginOfType(final String extension, String pluginId) {
return goPluginOSGiFramework.hasReferenceFor(GoPlugin.class, pluginId, extension);
}
@Override
public String resolveExtensionVersion(String pluginId, String extensionType, final List<String> goSupportedExtensionVersions) {
String resolvedExtensionVersion = goPluginOSGiFramework.doOn(GoPlugin.class, pluginId, extensionType, new ActionWithReturn<GoPlugin, String>() {
@Override
public String execute(GoPlugin goPlugin, GoPluginDescriptor pluginDescriptor) {
List<String> pluginSupportedVersions = goPlugin.pluginIdentifier().getSupportedExtensionVersions();
String currentMaxVersion = "0";
for (String pluginSupportedVersion : pluginSupportedVersions) {
if (goSupportedExtensionVersions.contains(pluginSupportedVersion) && parseDouble(currentMaxVersion) < parseDouble(pluginSupportedVersion)) {
currentMaxVersion = pluginSupportedVersion;
}
}
return currentMaxVersion;
}
});
if ("0".equals(resolvedExtensionVersion)) {
throw new RuntimeException(String.format("Could not find matching extension version between Plugin[%s] and Go", pluginId));
}
return resolvedExtensionVersion;
}
private void removeBundleDirectory() {
try {
FileUtils.deleteDirectory(bundleLocation);
} catch (IOException e) {
throw new RuntimeException(String.format("Failed to copy delete bundle directory %s", bundleLocation), e);
}
}
private File bundlePath() {
File bundleDir = new File(systemEnvironment.get(PLUGIN_BUNDLE_PATH));
FileUtil.validateAndCreateDirectory(bundleDir);
return bundleDir;
}
}
| apache-2.0 |
dagnir/aws-sdk-java | aws-java-sdk-lightsail/src/main/java/com/amazonaws/services/lightsail/model/transform/CreateInstancesRequestProtocolMarshaller.java | 2664 | /*
* 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.lightsail.model.transform;
import javax.annotation.Generated;
import com.amazonaws.SdkClientException;
import com.amazonaws.Request;
import com.amazonaws.http.HttpMethodName;
import com.amazonaws.services.lightsail.model.*;
import com.amazonaws.transform.Marshaller;
import com.amazonaws.protocol.*;
import com.amazonaws.annotation.SdkInternalApi;
/**
* CreateInstancesRequest Marshaller
*/
@Generated("com.amazonaws:aws-java-sdk-code-generator")
@SdkInternalApi
public class CreateInstancesRequestProtocolMarshaller implements Marshaller<Request<CreateInstancesRequest>, CreateInstancesRequest> {
private static final OperationInfo SDK_OPERATION_BINDING = OperationInfo.builder().protocol(Protocol.AWS_JSON).requestUri("/")
.httpMethodName(HttpMethodName.POST).hasExplicitPayloadMember(false).hasPayloadMembers(true)
.operationIdentifier("Lightsail_20161128.CreateInstances").serviceName("AmazonLightsail").build();
private final com.amazonaws.protocol.json.SdkJsonProtocolFactory protocolFactory;
public CreateInstancesRequestProtocolMarshaller(com.amazonaws.protocol.json.SdkJsonProtocolFactory protocolFactory) {
this.protocolFactory = protocolFactory;
}
public Request<CreateInstancesRequest> marshall(CreateInstancesRequest createInstancesRequest) {
if (createInstancesRequest == null) {
throw new SdkClientException("Invalid argument passed to marshall(...)");
}
try {
final ProtocolRequestMarshaller<CreateInstancesRequest> protocolMarshaller = protocolFactory.createProtocolMarshaller(SDK_OPERATION_BINDING,
createInstancesRequest);
protocolMarshaller.startMarshalling();
CreateInstancesRequestMarshaller.getInstance().marshall(createInstancesRequest, protocolMarshaller);
return protocolMarshaller.finishMarshalling();
} catch (Exception e) {
throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e);
}
}
}
| apache-2.0 |
lburgazzoli/apache-activemq-artemis | tests/activemq5-unit-tests/src/test/java/org/apache/activemq/ExclusiveConsumerStartupDestinationTest.java | 7714 | /**
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.activemq;
import javax.jms.Connection;
import javax.jms.ConnectionFactory;
import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.MessageConsumer;
import javax.jms.MessageProducer;
import javax.jms.Session;
import org.apache.activemq.broker.BrokerService;
import org.apache.activemq.broker.region.policy.PolicyEntry;
import org.apache.activemq.broker.region.policy.PolicyMap;
import org.apache.activemq.command.ActiveMQQueue;
public class ExclusiveConsumerStartupDestinationTest extends EmbeddedBrokerTestSupport {
private static final String VM_BROKER_URL = "vm://localhost";
@Override
protected BrokerService createBroker() throws Exception {
BrokerService answer = new BrokerService();
answer.setPersistent(false);
PolicyMap map = new PolicyMap();
PolicyEntry entry = new PolicyEntry();
entry.setAllConsumersExclusiveByDefault(true);
map.setDefaultEntry(entry);
answer.setDestinationPolicy(map);
return answer;
}
protected String getBrokerConfigUri() {
return "org/apache/activemq/broker/exclusive-consumer-startup-destination.xml";
}
private Connection createConnection(final boolean start) throws JMSException {
ConnectionFactory cf = new ActiveMQConnectionFactory(VM_BROKER_URL);
Connection conn = cf.createConnection();
if (start) {
conn.start();
}
return conn;
}
public void testExclusiveConsumerSelectedCreatedFirst() throws JMSException, InterruptedException {
Connection conn = createConnection(true);
Session exclusiveSession = null;
Session fallbackSession = null;
Session senderSession = null;
try {
exclusiveSession = conn.createSession(false, Session.AUTO_ACKNOWLEDGE);
fallbackSession = conn.createSession(false, Session.AUTO_ACKNOWLEDGE);
senderSession = conn.createSession(false, Session.AUTO_ACKNOWLEDGE);
ActiveMQQueue exclusiveQueue = new ActiveMQQueue("TEST.QUEUE1");
MessageConsumer exclusiveConsumer = exclusiveSession.createConsumer(exclusiveQueue);
ActiveMQQueue fallbackQueue = new ActiveMQQueue("TEST.QUEUE1");
MessageConsumer fallbackConsumer = fallbackSession.createConsumer(fallbackQueue);
ActiveMQQueue senderQueue = new ActiveMQQueue("TEST.QUEUE1");
MessageProducer producer = senderSession.createProducer(senderQueue);
Message msg = senderSession.createTextMessage("test");
producer.send(msg);
// TODO need two send a 2nd message - bug AMQ-1024
// producer.send(msg);
Thread.sleep(100);
// Verify exclusive consumer receives the message.
assertNotNull(exclusiveConsumer.receive(100));
assertNull(fallbackConsumer.receive(100));
}
finally {
fallbackSession.close();
senderSession.close();
conn.close();
}
}
//Exclusive consumer not implemented yet.
public void testFailoverToAnotherExclusiveConsumerCreatedFirst() throws JMSException, InterruptedException {
Connection conn = createConnection(true);
Session exclusiveSession1 = null;
Session exclusiveSession2 = null;
Session fallbackSession = null;
Session senderSession = null;
try {
exclusiveSession1 = conn.createSession(false, Session.AUTO_ACKNOWLEDGE);
exclusiveSession2 = conn.createSession(false, Session.AUTO_ACKNOWLEDGE);
fallbackSession = conn.createSession(false, Session.AUTO_ACKNOWLEDGE);
senderSession = conn.createSession(false, Session.AUTO_ACKNOWLEDGE);
// This creates the exclusive consumer first which avoids AMQ-1024
// bug.
ActiveMQQueue exclusiveQueue = new ActiveMQQueue("TEST.QUEUE2");
MessageConsumer exclusiveConsumer1 = exclusiveSession1.createConsumer(exclusiveQueue);
MessageConsumer exclusiveConsumer2 = exclusiveSession2.createConsumer(exclusiveQueue);
ActiveMQQueue fallbackQueue = new ActiveMQQueue("TEST.QUEUE2");
MessageConsumer fallbackConsumer = fallbackSession.createConsumer(fallbackQueue);
ActiveMQQueue senderQueue = new ActiveMQQueue("TEST.QUEUE2");
MessageProducer producer = senderSession.createProducer(senderQueue);
Message msg = senderSession.createTextMessage("test");
producer.send(msg);
Thread.sleep(100);
// Verify exclusive consumer receives the message.
assertNotNull(exclusiveConsumer1.receive(100));
assertNull(exclusiveConsumer2.receive(100));
assertNull(fallbackConsumer.receive(100));
// Close the exclusive consumer to verify the non-exclusive consumer
// takes over
exclusiveConsumer1.close();
producer.send(msg);
producer.send(msg);
assertNotNull("Should have received a message", exclusiveConsumer2.receive(100));
assertNull("Should not have received a message", fallbackConsumer.receive(100));
}
finally {
fallbackSession.close();
senderSession.close();
conn.close();
}
}
public void testFailoverToNonExclusiveConsumer() throws JMSException, InterruptedException {
Connection conn = createConnection(true);
Session exclusiveSession = null;
Session fallbackSession = null;
Session senderSession = null;
try {
exclusiveSession = conn.createSession(false, Session.AUTO_ACKNOWLEDGE);
fallbackSession = conn.createSession(false, Session.AUTO_ACKNOWLEDGE);
senderSession = conn.createSession(false, Session.AUTO_ACKNOWLEDGE);
// This creates the exclusive consumer first which avoids AMQ-1024
// bug.
ActiveMQQueue exclusiveQueue = new ActiveMQQueue("TEST.QUEUE3");
MessageConsumer exclusiveConsumer = exclusiveSession.createConsumer(exclusiveQueue);
ActiveMQQueue fallbackQueue = new ActiveMQQueue("TEST.QUEUE3");
MessageConsumer fallbackConsumer = fallbackSession.createConsumer(fallbackQueue);
ActiveMQQueue senderQueue = new ActiveMQQueue("TEST.QUEUE3");
MessageProducer producer = senderSession.createProducer(senderQueue);
Message msg = senderSession.createTextMessage("test");
producer.send(msg);
Thread.sleep(100);
// Verify exclusive consumer receives the message.
assertNotNull(exclusiveConsumer.receive(100));
assertNull(fallbackConsumer.receive(100));
// Close the exclusive consumer to verify the non-exclusive consumer
// takes over
exclusiveConsumer.close();
producer.send(msg);
assertNotNull(fallbackConsumer.receive(100));
}
finally {
fallbackSession.close();
senderSession.close();
conn.close();
}
}
}
| apache-2.0 |
KimShen/sissi | src/main/java/com/sissi/pipeline/in/iq/register/store/RegisterStoreMultiProcessor.java | 917 | package com.sissi.pipeline.in.iq.register.store;
import com.sissi.field.Fields;
import com.sissi.field.impl.BeanFields;
import com.sissi.pipeline.Input;
import com.sissi.protocol.iq.data.XData;
import com.sissi.protocol.iq.data.XField;
import com.sissi.protocol.iq.register.simple.Username;
import com.sissi.ucenter.register.RegisterContext;
/**
* 复杂表单
*
* @author kim 2013年12月5日
*/
public class RegisterStoreMultiProcessor extends RegisterStoreProcessor {
public RegisterStoreMultiProcessor(RegisterContext registerContext, Input input) {
super(registerContext, input);
}
@Override
protected Fields process(Fields fields) {
return new BeanFields(false, fields.findField(XData.NAME, XData.class).getFields());
}
@Override
protected String username(Fields fields) {
return fields.findField(XData.NAME, XData.class).findField(Username.NAME, XField.class).getValue().toString();
}
} | apache-2.0 |
apache/velocity-engine | velocity-engine-core/src/main/java/org/apache/velocity/runtime/parser/node/ASTLENode.java | 1325 | package org.apache.velocity.runtime.parser.node;
/*
* 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.
*/
import org.apache.velocity.runtime.parser.Parser;
/**
* Handles arg1 <= arg2<br><br>
*/
public class ASTLENode extends ASTComparisonNode
{
public ASTLENode(int id)
{
super(id);
}
public ASTLENode(Parser p, int id)
{
super(p, id);
}
@Override
public String getLiteralOperator()
{
return "<=";
}
public boolean numberTest(int compareResult)
{
return compareResult <= 0;
}
}
| apache-2.0 |
OpenGamma/Strata | modules/measure/src/test/java/com/opengamma/strata/measure/calc/TargetTypeCalculationParameterTest.java | 3428 | /*
* Copyright (C) 2016 - present by OpenGamma Inc. and the OpenGamma group of companies
*
* Please see distribution for license.
*/
package com.opengamma.strata.measure.calc;
import static com.opengamma.strata.collect.TestHelper.coverBeanEquals;
import static com.opengamma.strata.collect.TestHelper.coverImmutableBean;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException;
import java.util.Optional;
import org.junit.jupiter.api.Test;
import com.google.common.collect.ImmutableMap;
import com.opengamma.strata.basics.CalculationTarget;
import com.opengamma.strata.calc.TestingMeasures;
import com.opengamma.strata.calc.runner.CalculationParameter;
import com.opengamma.strata.calc.runner.TestParameter;
import com.opengamma.strata.calc.runner.TestParameter2;
/**
* Test {@link TargetTypeCalculationParameter}.
*/
public class TargetTypeCalculationParameterTest {
private static final CalculationParameter PARAM1 = new TestParameter();
private static final CalculationParameter PARAM2 = new TestParameter();
private static final CalculationParameter PARAM3 = new TestParameter();
private static final CalculationParameter PARAM_OTHER = new TestParameter2();
private static final TestTarget TARGET1 = new TestTarget();
private static final TestTarget2 TARGET2 = new TestTarget2();
private static final TestTarget3 TARGET3 = new TestTarget3();
//-------------------------------------------------------------------------
@Test
public void test_of() {
TargetTypeCalculationParameter test = TargetTypeCalculationParameter.of(
ImmutableMap.of(TestTarget.class, PARAM1, TestTarget2.class, PARAM2), PARAM3);
assertThat(test.getQueryType()).isEqualTo(TestParameter.class);
assertThat(test.getParameters()).hasSize(2);
assertThat(test.getDefaultParameter()).isEqualTo(PARAM3);
assertThat(test.queryType()).isEqualTo(TestParameter.class);
assertThat(test.filter(TARGET1, TestingMeasures.PRESENT_VALUE)).isEqualTo(Optional.of(PARAM1));
assertThat(test.filter(TARGET2, TestingMeasures.PRESENT_VALUE)).isEqualTo(Optional.of(PARAM2));
assertThat(test.filter(TARGET3, TestingMeasures.PRESENT_VALUE)).isEqualTo(Optional.of(PARAM3));
}
@Test
public void of_empty() {
assertThatIllegalArgumentException()
.isThrownBy(() -> TargetTypeCalculationParameter.of(ImmutableMap.of(), PARAM3));
}
@Test
public void of_badType() {
assertThatIllegalArgumentException()
.isThrownBy(() -> TargetTypeCalculationParameter.of(ImmutableMap.of(TestTarget.class, PARAM_OTHER), PARAM3));
}
//-------------------------------------------------------------------------
@Test
public void coverage() {
TargetTypeCalculationParameter test = TargetTypeCalculationParameter.of(
ImmutableMap.of(TestTarget.class, PARAM1, TestTarget2.class, PARAM2), PARAM3);
coverImmutableBean(test);
TargetTypeCalculationParameter test2 = TargetTypeCalculationParameter.of(
ImmutableMap.of(TestTarget.class, PARAM1), PARAM2);
coverBeanEquals(test, test2);
}
//-------------------------------------------------------------------------
private static class TestTarget implements CalculationTarget {
}
private static class TestTarget2 implements CalculationTarget {
}
private static class TestTarget3 implements CalculationTarget {
}
}
| apache-2.0 |
MinghuiGao/forum_ssh | src/action/LoginAction.java | 1266 | package action;
import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ModelDriven;
import javax.servlet.http.*;
import service.interfaces.*;
import entity.*;
public class LoginAction extends BaseAction implements ModelDriven<User>
{
private User user = new User();
public User getModel()
{
return user;
}
@Override
public void validate()
{
if("".equals(user.getValidationCode())) return;
Object obj = ActionContext.getContext().getSession().get(
"validation_code");
String validationCode = (obj != null) ? obj.toString() : "";
if (!validationCode.equalsIgnoreCase(user.getValidationCode()))
{
if (user.getValidationCode() != null)
{
this.addFieldError("validationCode", "ÑéÖ¤ÂëÊäÈë´íÎó!");
}
}
}
public String execute() throws Exception
{
try
{
UserService userService = serviceManager.getUserService();
if(userService.verifyUser(user))
{
saveCookie("user", user.getName(), 24 * 60 * 60);
HttpSession session = request.getSession();
session.setAttribute("username", user.getName());
session.setMaxInactiveInterval(60 * 60 * 3);
return SUCCESS;
}
}
catch (Exception e)
{
System.out.println(e.getMessage());
}
return ERROR;
}
} | apache-2.0 |
lafaspot/JsonPath | json-path/src/main/java/com/jayway/jsonpath/spi/json/JsonOrgJsonProvider.java | 6389 | package com.jayway.jsonpath.spi.json;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.json.JSONTokener;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.jayway.jsonpath.InvalidJsonException;
import com.jayway.jsonpath.JsonPathException;
public class JsonOrgJsonProvider extends AbstractJsonProvider {
private static final Logger logger = LoggerFactory.getLogger(GsonJsonProvider.class);
@Override
public Object parse(String json) throws InvalidJsonException {
try {
return new JSONTokener(json).nextValue();
} catch (JSONException e) {
throw new InvalidJsonException(e);
}
}
@Override
public Object parse(InputStream jsonStream, String charset) throws InvalidJsonException {
try {
return new JSONTokener(new InputStreamReader(jsonStream, charset)).nextValue();
} catch (UnsupportedEncodingException e) {
throw new JsonPathException(e);
} catch (JSONException e) {
throw new InvalidJsonException(e);
}
}
@Override
public Object unwrap(Object obj) {
if(obj == JSONObject.NULL){
return null;
}
return obj;
}
@Override
public String toJson(Object obj) {
return obj.toString();
}
@Override
public Object createArray() {
return new JSONArray();
}
@Override
public Object createMap() {
return new JSONObject();
}
@Override
public boolean isArray(Object obj) {
return (obj instanceof JSONArray || obj instanceof List);
}
@Override
public Object getArrayIndex(Object obj, int idx) {
try {
return toJsonArray(obj).get(idx);
} catch (JSONException e) {
throw new JsonPathException(e);
}
}
@Override
public void setArrayIndex(Object array, int index, Object newValue) {
try {
if (!isArray(array)) {
throw new UnsupportedOperationException();
} else {
toJsonArray(array).put(index, createJsonElement(newValue));
}
} catch (JSONException e) {
throw new JsonPathException(e);
}
}
@Override
public Object getMapValue(Object obj, String key) {
try {
JSONObject jsonObject = toJsonObject(obj);
Object o = jsonObject.opt(key);
if (o == null) {
return UNDEFINED;
} else {
return unwrap(o);
}
} catch (JSONException e) {
throw new JsonPathException(e);
}
}
@Override
public void setProperty(Object obj, Object key, Object value) {
try {
if (isMap(obj))
toJsonObject(obj).put(key.toString(), createJsonElement(value));
else {
JSONArray array = toJsonArray(obj);
int index;
if (key != null) {
index = key instanceof Integer ? (Integer) key : Integer.parseInt(key.toString());
} else {
index = array.length();
}
if (index == array.length()) {
array.put(createJsonElement(value));
} else {
array.put(index, createJsonElement(value));
}
}
} catch (JSONException e) {
throw new JsonPathException(e);
}
}
@Override
@SuppressWarnings("unchecked")
public void removeProperty(Object obj, Object key) {
if (isMap(obj))
toJsonObject(obj).remove(key.toString());
else {
JSONArray array = toJsonArray(obj);
int index = key instanceof Integer ? (Integer) key : Integer.parseInt(key.toString());
array.remove(index);
}
}
@Override
public boolean isMap(Object obj) {
return (obj instanceof JSONObject);
}
@Override
public Collection<String> getPropertyKeys(Object obj) {
JSONObject jsonObject = toJsonObject(obj);
List<String> keys = new ArrayList<String>();
try {
for (int i = 0; i < jsonObject.names().length(); i++) {
String key = (String) jsonObject.names().get(i);
keys.add(key);
}
return keys;
} catch (JSONException e) {
throw new JsonPathException(e);
}
}
@Override
public int length(Object obj) {
if (isArray(obj)) {
return toJsonArray(obj).length();
} else if (isMap(obj)) {
return toJsonObject(obj).length();
} else {
if (obj instanceof String) {
return ((String) obj).length();
}
}
throw new JsonPathException("length operation can not applied to " + obj != null ? obj.getClass().getName() : "null");
}
@Override
public Iterable<?> toIterable(Object obj) {
try {
if (isArray(obj)) {
JSONArray arr = toJsonArray(obj);
List<Object> values = new ArrayList<Object>(arr.length());
for (int i = 0; i < arr.length(); i++) {
values.add(unwrap(arr.get(i)));
}
return values;
} else {
JSONObject jsonObject = toJsonObject(obj);
List<Object> values = new ArrayList<Object>();
for (int i = 0; i < jsonObject.names().length(); i++) {
String key = (String) jsonObject.names().get(i);
Object val = jsonObject.get(key);
values.add(unwrap(val));
}
return values;
}
} catch (JSONException e) {
throw new JsonPathException(e);
}
}
private Object createJsonElement(Object o) {
return o;
}
private JSONArray toJsonArray(Object o) {
return (JSONArray) o;
}
private JSONObject toJsonObject(Object o) {
return (JSONObject) o;
}
}
| apache-2.0 |
ulfjack/bazel | src/main/java/net/starlark/java/cmd/Starlark.java | 6726 | // Copyright 2016 The Bazel Authors. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package net.starlark.java.cmd;
import com.google.devtools.build.lib.syntax.EvalException;
import com.google.devtools.build.lib.syntax.EvalUtils;
import com.google.devtools.build.lib.syntax.FileOptions;
import com.google.devtools.build.lib.syntax.Module;
import com.google.devtools.build.lib.syntax.Mutability;
import com.google.devtools.build.lib.syntax.ParserInput;
import com.google.devtools.build.lib.syntax.StarlarkSemantics;
import com.google.devtools.build.lib.syntax.StarlarkThread;
import com.google.devtools.build.lib.syntax.SyntaxError;
import java.io.BufferedReader;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.time.Duration;
/**
* Starlark is a standalone starlark intepreter. The environment doesn't
* contain Bazel-specific functions and variables. Load statements are
* forbidden for the moment.
*/
class Starlark {
private static final String START_PROMPT = ">> ";
private static final String CONTINUATION_PROMPT = ".. ";
private static final Charset CHARSET = StandardCharsets.ISO_8859_1;
private final BufferedReader reader =
new BufferedReader(new InputStreamReader(System.in, CHARSET));
private final StarlarkThread thread;
private final Module module = Module.create();
// TODO(adonovan): set load-binds-globally option when we support load,
// so that loads bound in one REPL chunk are visible in the next.
private final FileOptions options = FileOptions.DEFAULT;
{
Mutability mu = Mutability.create("interpreter");
thread = new StarlarkThread(mu, StarlarkSemantics.DEFAULT);
thread.setPrintHandler((th, msg) -> System.out.println(msg));
}
private String prompt() {
StringBuilder input = new StringBuilder();
System.out.print(START_PROMPT);
try {
String lineSeparator = "";
while (true) {
String line = reader.readLine();
if (line == null) {
return null;
}
if (line.isEmpty()) {
return input.toString();
}
input.append(lineSeparator).append(line);
lineSeparator = "\n";
System.out.print(CONTINUATION_PROMPT);
}
} catch (IOException io) {
io.printStackTrace();
return null;
}
}
/** Provide a REPL evaluating Starlark code. */
@SuppressWarnings("CatchAndPrintStackTrace")
private void readEvalPrintLoop() {
System.err.println("Welcome to Starlark (java.starlark.net)");
String line;
// TODO(adonovan): parse a compound statement, like the Python and
// go.starlark.net REPLs. This requires a new grammar production, and
// integration with the lexer so that it consumes new
// lines only until the parse is complete.
while ((line = prompt()) != null) {
ParserInput input = ParserInput.fromString(line, "<stdin>");
try {
Object result = EvalUtils.exec(input, options, module, thread);
if (result != com.google.devtools.build.lib.syntax.Starlark.NONE) {
System.out.println(com.google.devtools.build.lib.syntax.Starlark.repr(result));
}
} catch (SyntaxError.Exception ex) {
for (SyntaxError error : ex.errors()) {
System.err.println(error);
}
} catch (EvalException ex) {
System.err.println(ex.print());
} catch (InterruptedException ex) {
System.err.println("Interrupted");
}
}
}
/** Execute a Starlark file. */
private int executeFile(String filename) {
String content;
try {
content = new String(Files.readAllBytes(Paths.get(filename)), CHARSET);
return execute(filename, content);
} catch (Exception e) {
e.printStackTrace();
return 1;
}
}
/** Execute a Starlark file. */
private int execute(String filename, String content) {
try {
EvalUtils.exec(ParserInput.fromString(content, filename), options, module, thread);
return 0;
} catch (SyntaxError.Exception ex) {
for (SyntaxError error : ex.errors()) {
System.err.println(error);
}
return 1;
} catch (EvalException ex) {
System.err.println(ex.print());
return 1;
} catch (Exception e) {
e.printStackTrace(System.err);
return 1;
}
}
public static void main(String[] args) throws IOException {
String file = null;
String cmd = null;
String cpuprofile = null;
// parse flags
int i;
for (i = 0; i < args.length; i++) {
if (!args[i].startsWith("-")) {
break;
}
if (args[i].equals("--")) {
i++;
break;
}
if (args[i].equals("-c")) {
if (i + 1 == args.length) {
throw new IOException("-c <cmd> flag needs an argument");
}
cmd = args[++i];
} else if (args[i].equals("-cpuprofile")) {
if (i + 1 == args.length) {
throw new IOException("-cpuprofile <file> flag needs an argument");
}
cpuprofile = args[++i];
} else {
throw new IOException("unknown flag: " + args[i]);
}
}
// positional arguments
if (i < args.length) {
if (i + 1 < args.length) {
throw new IOException("too many positional arguments");
}
file = args[i];
}
if (cpuprofile != null) {
FileOutputStream out = new FileOutputStream(cpuprofile);
com.google.devtools.build.lib.syntax.Starlark.startCpuProfile(out, Duration.ofMillis(10));
}
int exit;
if (file == null) {
if (cmd != null) {
exit = new Starlark().execute("<command-line>", cmd);
} else {
new Starlark().readEvalPrintLoop();
exit = 0;
}
} else if (cmd == null) {
exit = new Starlark().executeFile(file);
} else {
System.err.println("usage: Starlark [-cpuprofile file] [-c cmd | file]");
exit = 1;
}
if (cpuprofile != null) {
com.google.devtools.build.lib.syntax.Starlark.stopCpuProfile();
}
System.exit(exit);
}
}
| apache-2.0 |
PetrGasparik/midpoint | gui/admin-gui/src/main/java/com/evolveum/midpoint/web/component/input/QNameEditorPanel.java | 7773 | /*
* Copyright (c) 2010-2016 Evolveum
*
* 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.evolveum.midpoint.web.component.input;
import com.evolveum.midpoint.gui.api.component.BasePanel;
import com.evolveum.midpoint.prism.path.ItemPath;
import com.evolveum.midpoint.prism.path.NameItemPathSegment;
import com.evolveum.midpoint.schema.constants.MidPointConstants;
import com.evolveum.midpoint.schema.constants.SchemaConstants;
import com.evolveum.midpoint.web.page.admin.configuration.component.EmptyOnChangeAjaxFormUpdatingBehavior;
import com.evolveum.midpoint.web.util.InfoTooltipBehavior;
import com.evolveum.prism.xml.ns._public.types_3.ItemPathType;
import org.apache.commons.lang.StringUtils;
import org.apache.wicket.ajax.AjaxRequestTarget;
import org.apache.wicket.behavior.AttributeAppender;
import org.apache.wicket.markup.html.WebMarkupContainer;
import org.apache.wicket.markup.html.basic.Label;
import org.apache.wicket.markup.html.form.DropDownChoice;
import org.apache.wicket.markup.html.form.TextField;
import org.apache.wicket.model.IModel;
import javax.xml.namespace.QName;
import java.util.Arrays;
import java.util.List;
/**
* @author shood
*
* Item paths edited by this component are limited to single segment.
* TODO - this component should probably be renamed to ItemPathType editor
* */
public class QNameEditorPanel extends BasePanel<ItemPathType>{
private static final String ID_LOCAL_PART = "localPart";
private static final String ID_NAMESPACE = "namespace";
private static final String ID_LOCAL_PART_LABEL = "localPartLabel";
private static final String ID_LOCAL_PART_REQUIRED = "localPartRequired";
private static final String ID_NAMESPACE_LABEL = "namespaceLabel";
private static final String ID_NAMESPACE_REQUIRED = "namespaceRequired";
private static final String ID_T_LOCAL_PART = "localPartTooltip";
private static final String ID_T_NAMESPACE = "namespaceTooltip";
private IModel<ItemPathType> itemPathModel;
private IModel<String> localpartModel;
private IModel<String> namespaceModel;
public QNameEditorPanel(String id, IModel<ItemPathType> model, String localPartLabelKey, String localPartTooltipKey,
String namespaceLabelKey, String namespaceTooltipKey, boolean markLocalPartAsRequired, boolean markNamespaceAsRequired) {
super(id, model);
this.itemPathModel = model;
localpartModel = new IModel<String>() {
@Override
public String getObject() {
QName qName = itemPathToQName();
return qName != null ? qName.getLocalPart() : null;
}
@Override
public void setObject(String object) {
if (object == null) {
itemPathModel.setObject(null);
} else {
itemPathModel.setObject(new ItemPathType(new ItemPath(new QName(namespaceModel.getObject(), object))));
}
}
@Override
public void detach() {
}
};
namespaceModel = new IModel<String>() {
@Override
public String getObject() {
QName qName = itemPathToQName();
return qName != null ? qName.getNamespaceURI() : null;
}
@Override
public void setObject(String object) {
if (StringUtils.isBlank(localpartModel.getObject())) {
itemPathModel.setObject(null);
} else {
itemPathModel.setObject(new ItemPathType(new ItemPath(new QName(object, localpartModel.getObject()))));
}
}
@Override
public void detach() {
}
};
initLayout(localPartLabelKey, localPartTooltipKey, namespaceLabelKey, namespaceTooltipKey, markLocalPartAsRequired, markNamespaceAsRequired);
}
private QName itemPathToQName() {
if (itemPathModel.getObject() == null) {
return null;
}
ItemPath path = itemPathModel.getObject().getItemPath();
if (path.size() == 0) {
return null;
} else if (path.size() == 1 && path.first() instanceof NameItemPathSegment) {
return ((NameItemPathSegment) path.first()).getName();
} else {
throw new IllegalStateException("Malformed ItemPath: " + path);
}
}
@Override
public IModel<ItemPathType> getModel() {
IModel<ItemPathType> model = super.getModel();
ItemPathType modelObject = model.getObject();
// TODO consider removing this
if (modelObject == null){
model.setObject(new ItemPathType());
}
return model;
}
private void initLayout(String localPartLabelKey, String localPartTooltipKey,
String namespaceLabelKey, String namespaceTooltipKey, boolean markLocalPartAsRequired, boolean markNamespaceAsRequired){
Label localPartLabel = new Label(ID_LOCAL_PART_LABEL, getString(localPartLabelKey));
localPartLabel.setOutputMarkupId(true);
localPartLabel.setOutputMarkupPlaceholderTag(true);
add(localPartLabel);
WebMarkupContainer localPartRequired = new WebMarkupContainer(ID_LOCAL_PART_REQUIRED);
localPartRequired.setVisible(markLocalPartAsRequired);
add(localPartRequired);
Label namespaceLabel = new Label(ID_NAMESPACE_LABEL, getString(namespaceLabelKey));
namespaceLabel.setOutputMarkupId(true);
namespaceLabel.setOutputMarkupPlaceholderTag(true);
add(namespaceLabel);
WebMarkupContainer namespaceRequired = new WebMarkupContainer(ID_NAMESPACE_REQUIRED);
namespaceRequired.setVisible(markNamespaceAsRequired);
add(namespaceRequired);
TextField localPart = new TextField<>(ID_LOCAL_PART, localpartModel);
localPart.setOutputMarkupId(true);
localPart.setOutputMarkupPlaceholderTag(true);
localPart.setRequired(isLocalPartRequired());
localPart.add(new UpdateBehavior());
add(localPart);
DropDownChoice namespace = new DropDownChoice<>(ID_NAMESPACE, namespaceModel, prepareNamespaceList());
namespace.setOutputMarkupId(true);
namespace.setOutputMarkupPlaceholderTag(true);
namespace.setNullValid(false);
namespace.setRequired(isNamespaceRequired());
namespace.add(new UpdateBehavior());
add(namespace);
Label localPartTooltip = new Label(ID_T_LOCAL_PART);
localPartTooltip.add(new AttributeAppender("data-original-title", getString(localPartTooltipKey)));
localPartTooltip.add(new InfoTooltipBehavior());
localPartTooltip.setOutputMarkupPlaceholderTag(true);
add(localPartTooltip);
Label namespaceTooltip = new Label(ID_T_NAMESPACE);
namespaceTooltip.add(new AttributeAppender("data-original-title", getString(namespaceTooltipKey)));
namespaceTooltip.add(new InfoTooltipBehavior());
namespaceTooltip.setOutputMarkupPlaceholderTag(true);
add(namespaceTooltip);
}
/**
* Override to provide custom list of namespaces
* for QName editor
* */
protected List<String> prepareNamespaceList(){
return Arrays.asList(SchemaConstants.NS_ICF_SCHEMA, MidPointConstants.NS_RI);
}
public boolean isLocalPartRequired(){
return false;
}
public boolean isNamespaceRequired() {
return false;
}
private class UpdateBehavior extends EmptyOnChangeAjaxFormUpdatingBehavior {
@Override
protected void onUpdate(AjaxRequestTarget target) {
QNameEditorPanel.this.onUpdate(target);
}
}
protected void onUpdate(AjaxRequestTarget target) {
}
}
| apache-2.0 |
oldinaction/smjava | javase/msb_base/src/theThirdChapter/TestOverLoad.java | 292 | package theThirdChapter;
public class TestOverLoad {
//���ݴ��IJ�����ȷ��Ҫ���õķ���
void max(int a, int b) {
System.out.println(a > b ? a : b);
}
void max(float a, float b) {
System.out.println(a > b ? a : b);
}
}
| apache-2.0 |
StyleTang/incubator-rocketmq-externals | rocketmq-console/src/main/java/org/apache/rocketmq/console/util/MsgTraceDecodeUtil.java | 8548 | /*
* 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.rocketmq.console.util;
import java.util.ArrayList;
import java.util.List;
import org.apache.rocketmq.client.producer.LocalTransactionState;
import org.apache.rocketmq.client.trace.TraceBean;
import org.apache.rocketmq.client.trace.TraceConstants;
import org.apache.rocketmq.client.trace.TraceContext;
import org.apache.rocketmq.client.trace.TraceType;
import org.apache.rocketmq.common.message.MessageType;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import static org.apache.rocketmq.client.trace.TraceType.Pub;
public class MsgTraceDecodeUtil {
private final static Logger log = LoggerFactory.getLogger(MsgTraceDecodeUtil.class);
private static final int TRACE_MSG_PUB_V1_LEN = 12;
private static final int TRACE_MSG_PUB_V2_LEN = 13;
private static final int TRACE_MSG_PUB_V3_LEN = 14;
private static final int TRACE_MSG_PUB_V4_LEN = 15;
private static final int TRACE_MSG_SUBAFTER_V1_LEN = 6;
private static final int TRACE_MSG_SUBAFTER_V2_LEN = 7;
private static final int TRACE_MSG_SUBAFTER_V3_LEN = 9;
public static List<TraceContext> decoderFromTraceDataString(String traceData) {
List<TraceContext> resList = new ArrayList<TraceContext>();
if (traceData == null || traceData.length() <= 0) {
return resList;
}
String[] contextList = traceData.split(String.valueOf(TraceConstants.FIELD_SPLITOR));
for (String context : contextList) {
String[] line = context.split(String.valueOf(TraceConstants.CONTENT_SPLITOR));
if (line[0].equals(Pub.name())) {
TraceContext pubContext = initTraceContext();
pubContext.setTraceType(Pub);
pubContext.setTimeStamp(Long.parseLong(line[1]));
pubContext.setRegionId(line[2]);
pubContext.setGroupName(line[3]);
TraceBean bean = new TraceBean();
bean.setTopic(line[4]);
bean.setMsgId(line[5]);
bean.setTags(line[6]);
bean.setKeys(line[7]);
bean.setStoreHost(line[8]);
bean.setBodyLength(Integer.parseInt(line[9]));
pubContext.setCostTime(Integer.parseInt(line[10]));
bean.setMsgType(MessageType.values()[Integer.parseInt(line[11])]);
// compatible with different version
switch (line.length) {
case TRACE_MSG_PUB_V1_LEN:
break;
case TRACE_MSG_PUB_V2_LEN:
pubContext.setSuccess(Boolean.parseBoolean(line[12]));
break;
case TRACE_MSG_PUB_V3_LEN:
bean.setOffsetMsgId(line[12]);
pubContext.setSuccess(Boolean.parseBoolean(line[13]));
break;
case TRACE_MSG_PUB_V4_LEN:
bean.setOffsetMsgId(line[12]);
pubContext.setSuccess(Boolean.parseBoolean(line[13]));
bean.setClientHost(line[14]);
break;
default:
bean.setOffsetMsgId(line[12]);
pubContext.setSuccess(Boolean.parseBoolean(line[13]));
bean.setClientHost(line[14]);
log.warn("Detect new version trace msg of {} type", Pub.name());
break;
}
pubContext.setTraceBeans(new ArrayList<TraceBean>(1));
pubContext.getTraceBeans().add(bean);
resList.add(pubContext);
} else if (line[0].equals(TraceType.SubBefore.name())) {
TraceContext subBeforeContext = initTraceContext();
subBeforeContext.setTraceType(TraceType.SubBefore);
subBeforeContext.setTimeStamp(Long.parseLong(line[1]));
subBeforeContext.setRegionId(line[2]);
subBeforeContext.setGroupName(line[3]);
subBeforeContext.setRequestId(line[4]);
TraceBean bean = new TraceBean();
bean.setMsgId(line[5]);
bean.setRetryTimes(Integer.parseInt(line[6]));
bean.setKeys(line[7]);
subBeforeContext.setTraceBeans(new ArrayList<TraceBean>(1));
subBeforeContext.getTraceBeans().add(bean);
resList.add(subBeforeContext);
} else if (line[0].equals(TraceType.SubAfter.name())) {
TraceContext subAfterContext = initTraceContext();
subAfterContext.setTraceType(TraceType.SubAfter);
subAfterContext.setRequestId(line[1]);
TraceBean bean = new TraceBean();
bean.setMsgId(line[2]);
bean.setKeys(line[5]);
subAfterContext.setTraceBeans(new ArrayList<TraceBean>(1));
subAfterContext.getTraceBeans().add(bean);
subAfterContext.setCostTime(Integer.parseInt(line[3]));
subAfterContext.setSuccess(Boolean.parseBoolean(line[4]));
// compatible with different version
switch (line.length) {
case TRACE_MSG_SUBAFTER_V1_LEN:
break;
case TRACE_MSG_SUBAFTER_V2_LEN:
subAfterContext.setContextCode(Integer.parseInt(line[6]));
break;
case TRACE_MSG_SUBAFTER_V3_LEN:
subAfterContext.setContextCode(Integer.parseInt(line[6]));
subAfterContext.setTimeStamp(Long.parseLong(line[7]));
subAfterContext.setGroupName(line[8]);
break;
default:
subAfterContext.setContextCode(Integer.parseInt(line[6]));
subAfterContext.setTimeStamp(Long.parseLong(line[7]));
subAfterContext.setGroupName(line[8]);
log.warn("Detect new version trace msg of {} type", TraceType.SubAfter.name());
break;
}
resList.add(subAfterContext);
} else if (line[0].equals(TraceType.EndTransaction.name())) {
TraceContext endTransactionContext = initTraceContext();
endTransactionContext.setTraceType(TraceType.EndTransaction);
endTransactionContext.setTimeStamp(Long.parseLong(line[1]));
endTransactionContext.setRegionId(line[2]);
endTransactionContext.setGroupName(line[3]);
TraceBean bean = new TraceBean();
bean.setTopic(line[4]);
bean.setMsgId(line[5]);
bean.setTags(line[6]);
bean.setKeys(line[7]);
bean.setStoreHost(line[8]);
bean.setMsgType(MessageType.values()[Integer.parseInt(line[9])]);
bean.setTransactionId(line[10]);
bean.setTransactionState(LocalTransactionState.valueOf(line[11]));
bean.setFromTransactionCheck(Boolean.parseBoolean(line[12]));
endTransactionContext.setTraceBeans(new ArrayList<TraceBean>(1));
endTransactionContext.getTraceBeans().add(bean);
resList.add(endTransactionContext);
}
}
return resList;
}
private static TraceContext initTraceContext() {
TraceContext traceContext = new TraceContext();
traceContext.setTimeStamp(0L);
traceContext.setCostTime(-1);
traceContext.setRequestId(null);
return traceContext;
}
}
| apache-2.0 |
dropbox/bazel | src/main/java/com/google/devtools/build/lib/query2/ConfiguredTargetAccessor.java | 5188 | // Copyright 2017 The Bazel Authors. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package com.google.devtools.build.lib.query2;
import com.google.devtools.build.lib.analysis.ConfiguredTarget;
import com.google.devtools.build.lib.cmdline.Label;
import com.google.devtools.build.lib.packages.NoSuchTargetException;
import com.google.devtools.build.lib.packages.Rule;
import com.google.devtools.build.lib.packages.Target;
import com.google.devtools.build.lib.packages.TargetUtils;
import com.google.devtools.build.lib.query2.engine.QueryEnvironment.TargetAccessor;
import com.google.devtools.build.lib.query2.engine.QueryException;
import com.google.devtools.build.lib.query2.engine.QueryExpression;
import com.google.devtools.build.lib.query2.engine.QueryVisibility;
import com.google.devtools.build.lib.rules.AliasConfiguredTarget;
import com.google.devtools.build.lib.skyframe.PackageValue;
import com.google.devtools.build.skyframe.WalkableGraph;
import java.util.List;
import java.util.Set;
/** A {@link TargetAccessor} for {@link ConfiguredTarget} objects.
*
* Incomplete; we'll implement getLabelListAttr and getVisibility when needed.
*/
class ConfiguredTargetAccessor implements TargetAccessor<ConfiguredTarget> {
private final WalkableGraph walkableGraph;
ConfiguredTargetAccessor(WalkableGraph walkableGraph) {
this.walkableGraph = walkableGraph;
}
@Override
public String getTargetKind(ConfiguredTarget target) {
Target actualTarget = getTargetFromConfiguredTarget(target);
return actualTarget.getTargetKind();
}
@Override
public String getLabel(ConfiguredTarget target) {
return target.getLabel().toString();
}
@Override
public String getPackage(ConfiguredTarget target) {
return target.getLabel().getPackageIdentifier().getPackageFragment().toString();
}
@Override
public boolean isRule(ConfiguredTarget target) {
Target actualTarget = getTargetFromConfiguredTarget(target);
return actualTarget instanceof Rule;
}
@Override
public boolean isTestRule(ConfiguredTarget target) {
Target actualTarget = getTargetFromConfiguredTarget(target);
return TargetUtils.isTestRule(actualTarget);
}
@Override
public boolean isTestSuite(ConfiguredTarget target) {
Target actualTarget = getTargetFromConfiguredTarget(target);
return TargetUtils.isTestSuiteRule(actualTarget);
}
@Override
public List<ConfiguredTarget> getLabelListAttr(
QueryExpression caller,
ConfiguredTarget configuredTarget,
String attrName,
String errorMsgPrefix)
throws QueryException, InterruptedException {
// TODO(bazel-team): implement this if needed.
throw new UnsupportedOperationException();
}
@Override
public List<String> getStringListAttr(ConfiguredTarget target, String attrName) {
Target actualTarget = getTargetFromConfiguredTarget(target);
return TargetUtils.getStringListAttr(actualTarget, attrName);
}
@Override
public String getStringAttr(ConfiguredTarget target, String attrName) {
Target actualTarget = getTargetFromConfiguredTarget(target);
return TargetUtils.getStringAttr(actualTarget, attrName);
}
@Override
public Iterable<String> getAttrAsString(ConfiguredTarget target, String attrName) {
Target actualTarget = getTargetFromConfiguredTarget(target);
return TargetUtils.getAttrAsString(actualTarget, attrName);
}
@Override
public Set<QueryVisibility<ConfiguredTarget>> getVisibility(ConfiguredTarget from)
throws QueryException, InterruptedException {
// TODO(bazel-team): implement this if needed.
throw new UnsupportedOperationException();
}
public Target getTargetFromConfiguredTarget(ConfiguredTarget configuredTarget) {
return getTargetFromConfiguredTarget(configuredTarget, walkableGraph);
}
public static Target getTargetFromConfiguredTarget(
ConfiguredTarget configuredTarget, WalkableGraph walkableGraph) {
Target target = null;
try {
Label label =
configuredTarget instanceof AliasConfiguredTarget
? ((AliasConfiguredTarget) configuredTarget).getOriginalLabel()
: configuredTarget.getLabel();
target =
((PackageValue) walkableGraph.getValue(PackageValue.key(label.getPackageIdentifier())))
.getPackage()
.getTarget(label.getName());
} catch (NoSuchTargetException e) {
throw new IllegalStateException("Unable to get target from package in accessor.");
} catch (InterruptedException e2) {
throw new IllegalStateException("Thread interrupted in the middle of getting a Target.");
}
return target;
}
}
| apache-2.0 |
semonte/intellij-community | platform/lang-impl/src/com/intellij/codeInsight/hints/ParameterHintsPassFactory.java | 2723 | /*
* Copyright 2000-2017 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.intellij.codeInsight.hints;
import com.intellij.codeHighlighting.TextEditorHighlightingPass;
import com.intellij.codeHighlighting.TextEditorHighlightingPassFactory;
import com.intellij.codeHighlighting.TextEditorHighlightingPassRegistrar;
import com.intellij.openapi.components.AbstractProjectComponent;
import com.intellij.openapi.editor.Editor;
import com.intellij.openapi.editor.EditorFactory;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.util.Key;
import com.intellij.psi.PsiFile;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
public class ParameterHintsPassFactory extends AbstractProjectComponent implements TextEditorHighlightingPassFactory {
protected static final Key<Long> PSI_MODIFICATION_STAMP = Key.create("psi.modification.stamp");
public ParameterHintsPassFactory(Project project, TextEditorHighlightingPassRegistrar registrar) {
super(project);
registrar.registerTextEditorHighlightingPass(this, null, null, false, -1);
}
@Nullable
@Override
public TextEditorHighlightingPass createHighlightingPass(@NotNull PsiFile file, @NotNull Editor editor) {
if (editor.isOneLineMode()) return null;
long currentStamp = getCurrentModificationStamp(file);
Long savedStamp = editor.getUserData(PSI_MODIFICATION_STAMP);
if (savedStamp != null && savedStamp == currentStamp) return null;
return new ParameterHintsPass(file, editor);
}
public static long getCurrentModificationStamp(@NotNull PsiFile file) {
return file.getManager().getModificationTracker().getModificationCount();
}
public static void forceHintsUpdateOnNextPass() {
for (Editor editor : EditorFactory.getInstance().getAllEditors()) {
forceHintsUpdateOnNextPass(editor);
}
}
public static void forceHintsUpdateOnNextPass(@NotNull Editor editor) {
editor.putUserData(PSI_MODIFICATION_STAMP, null);
}
protected static void putCurrentPsiModificationStamp(@NotNull Editor editor, @NotNull PsiFile file) {
editor.putUserData(PSI_MODIFICATION_STAMP, getCurrentModificationStamp(file));
}
} | apache-2.0 |
GerritCodeReview/plugins_importer | src/main/java/com/googlesource/gerrit/plugins/importer/ResumeImportStatistic.java | 741 | // Copyright (C) 2015 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.googlesource.gerrit.plugins.importer;
class ResumeImportStatistic extends ImportStatistic {
int numChangesUpdated;
}
| apache-2.0 |
ReactiveX/RxJava | src/main/java/io/reactivex/rxjava3/observers/DisposableObserver.java | 3372 | /*
* Copyright (c) 2016-present, RxJava 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 io.reactivex.rxjava3.observers;
import java.util.concurrent.atomic.AtomicReference;
import io.reactivex.rxjava3.annotations.NonNull;
import io.reactivex.rxjava3.core.Observer;
import io.reactivex.rxjava3.disposables.Disposable;
import io.reactivex.rxjava3.internal.disposables.DisposableHelper;
import io.reactivex.rxjava3.internal.util.EndConsumerHelper;
/**
* An abstract {@link Observer} that allows asynchronous cancellation by implementing {@link Disposable}.
*
* <p>All pre-implemented final methods are thread-safe.
*
* <p>Use the public {@link #dispose()} method to dispose the sequence from within an
* {@code onNext} implementation.
*
* <p>Like all other consumers, {@code DisposableObserver} can be subscribed only once.
* Any subsequent attempt to subscribe it to a new source will yield an
* {@link IllegalStateException} with message {@code "It is not allowed to subscribe with a(n) <class name> multiple times."}.
*
* <p>Implementation of {@link #onStart()}, {@link #onNext(Object)}, {@link #onError(Throwable)}
* and {@link #onComplete()} are not allowed to throw any unchecked exceptions.
* If for some reason this can't be avoided, use {@link io.reactivex.rxjava3.core.Observable#safeSubscribe(io.reactivex.rxjava3.core.Observer)}
* instead of the standard {@code subscribe()} method.
*
* <p>Example<pre><code>
* Disposable d =
* Observable.range(1, 5)
* .subscribeWith(new DisposableObserver<Integer>() {
* @Override public void onStart() {
* System.out.println("Start!");
* }
* @Override public void onNext(Integer t) {
* if (t == 3) {
* dispose();
* }
* System.out.println(t);
* }
* @Override public void onError(Throwable t) {
* t.printStackTrace();
* }
* @Override public void onComplete() {
* System.out.println("Done!");
* }
* });
* // ...
* d.dispose();
* </code></pre>
*
* @param <T> the received value type
*/
public abstract class DisposableObserver<T> implements Observer<T>, Disposable {
final AtomicReference<Disposable> upstream = new AtomicReference<>();
@Override
public final void onSubscribe(@NonNull Disposable d) {
if (EndConsumerHelper.setOnce(this.upstream, d, getClass())) {
onStart();
}
}
/**
* Called once the single upstream Disposable is set via onSubscribe.
*/
protected void onStart() {
}
@Override
public final boolean isDisposed() {
return upstream.get() == DisposableHelper.DISPOSED;
}
@Override
public final void dispose() {
DisposableHelper.dispose(upstream);
}
}
| apache-2.0 |
liu-a-wei/LearnSpringMVC | LearnSpringMVC/src/main/java/com/liuawei/model/WorkInfoModel.java | 667 | package com.liuawei.model;
public class WorkInfoModel {
//所在城市
private String city;
//职位
private String job;
//工作年限
private String year;
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
public String getJob() {
return job;
}
public void setJob(String job) {
this.job = job;
}
public String getYear() {
return year;
}
public void setYear(String year) {
this.year = year;
}
@Override
public String toString() {
return "WorkInfoModel [city=" + city + ", job=" + job + ", year="
+ year + "]";
}
}
| apache-2.0 |
xfumihiro/ViewInspector | view-inspector-runtime/src/main/java/view_inspector/ViewInspector.java | 3568 | package view_inspector;
import android.app.Activity;
import android.app.Application;
import android.content.Context;
import android.util.Log;
import android.view.View;
import android.view.WindowManager;
import com.f2prateek.rx.preferences.Preference;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import javax.inject.Inject;
import view_inspector.dagger.ActivityComponent;
import view_inspector.dagger.ActivityModule;
import view_inspector.dagger.ApplicationComponent;
import view_inspector.dagger.ApplicationModule;
import view_inspector.dagger.DaggerActivityComponent;
import view_inspector.dagger.DaggerApplicationComponent;
import view_inspector.dagger.qualifier.BypassInterceptor;
import view_inspector.dagger.qualifier.ProbeMeasures;
import view_inspector.dagger.qualifier.Scalpel3D;
import view_inspector.dagger.qualifier.ShowOutline;
import view_inspector.probe.Probe;
import view_inspector.probe.ViewInspectorInterceptor;
import view_inspector.ui.ViewInspectorToolbar;
public final class ViewInspector {
public static final String TAG = "ViewInspector";
public static ApplicationComponent applicationComponent;
public static Set<Context> contextSet = new HashSet<>();
public static Map<Context, ActivityComponent> runtimeComponentMap = new HashMap<>();
public static Map<Context, ViewInspectorToolbar> toolbarMap = new HashMap<>();
public static View viewRoot;
@Inject WindowManager windowManager;
@Inject @ShowOutline Preference<Boolean> showOutline;
@Inject @ProbeMeasures Preference<Boolean> probeMeasures;
@Inject @BypassInterceptor Preference<Boolean> bypassInterceptor;
@Inject @Scalpel3D Preference<Boolean> scalpelEnabled;
@Inject ViewInspectorInterceptor interceptor;
@Inject ViewInspectorToolbar toolbar;
public static ViewInspector create() {
return new ViewInspector();
}
public void onCreate(Context context) {
if (!contextSet.contains(context)) {
contextSet.add(context);
if (applicationComponent == null) {
// create dagger component for the application
Application application = (Application) context.getApplicationContext();
applicationComponent = DaggerApplicationComponent.builder()
.applicationModule(new ApplicationModule(application))
.build();
}
if (!runtimeComponentMap.containsKey(context)) {
// create dagger components per activity
ActivityComponent activityComponent = DaggerActivityComponent.builder()
.applicationComponent(applicationComponent)
.activityModule(new ActivityModule((Activity) context))
.build();
runtimeComponentMap.put(context, activityComponent);
activityComponent.inject(this);
}
// Reset preferences
showOutline.set(false);
probeMeasures.set(false);
bypassInterceptor.set(false);
scalpelEnabled.set(false);
Probe.deploy(context, interceptor);
windowManager.addView(toolbar, ViewInspectorToolbar.createLayoutParams(context));
toolbarMap.put(context, toolbar);
}
}
public void onResume() {
toolbar.setVisibility(View.VISIBLE);
}
public void onPause() {
toolbar.closeMenu();
toolbar.setVisibility(View.GONE);
}
public void onDestroy(Context context) {
// remove dagger component map
runtimeComponentMap.remove(context);
ViewInspectorToolbar toolbarInstance = toolbarMap.get(context);
if (toolbarInstance != null) windowManager.removeViewImmediate(toolbarInstance);
}
}
| apache-2.0 |
JadiraOrg/jadira | scanner/src/main/java/org/jadira/scanner/ConfigurationBuilder.java | 7253 | /*
* Copyright 2013 Chris Pheby
*
* 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.jadira.scanner;
import java.net.URL;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import org.jadira.scanner.classpath.filter.NameFilter;
import org.jadira.scanner.core.api.Filter;
import org.jadira.scanner.core.api.Locator;
import org.jadira.scanner.core.exception.ClasspathAccessException;
import org.jadira.scanner.core.utils.reflection.ClassLoaderUtils;
public class ConfigurationBuilder implements Configuration {
private List<URL> urls = new ArrayList<URL>();
private List<Locator<URL>> locators = new ArrayList<Locator<URL>>();
private List<ClassLoader> classLoaders = new ArrayList<ClassLoader>();
private List<Filter<?>> filters = new ArrayList<Filter<?>>();
public ConfigurationBuilder() {
ClassLoader[] cls = ClassLoaderUtils.getClassLoaders();
for (ClassLoader next : cls) {
classLoaders.add(next);
}
}
public static ConfigurationBuilder build(final Object... params) {
ConfigurationBuilder builder = new ConfigurationBuilder();
List<Object> paramsList = flattenParams(params);
List<ClassLoader> cLoaders = new ArrayList<ClassLoader>();
for (Object param : paramsList) {
if (param instanceof ClassLoader) {
cLoaders.add((ClassLoader) param);
} else if (param instanceof URL) {
builder.addUrls((URL) param);
} else if (param instanceof Locator) {
@SuppressWarnings("unchecked") final Locator<URL>[] myParams = new Locator[] {(Locator<URL>)param};
builder.addLocators(myParams);
} else if (param instanceof Filter) {
builder.addFilters((Filter<?>) param);
} else if (param instanceof String) {
builder.addFilters(new NameFilter((String)param));
} else {
throw new ClasspathAccessException("Could not handle builder parameter " + param.toString());
}
}
builder.setClassLoaders(cLoaders);
return builder;
}
private static List<Object> flattenParams(final Object... params) {
List<Object> paramsList = new ArrayList<Object>(params.length);
if (params != null) {
for (Object param : params) {
if (param != null) {
if (param.getClass().isArray()) {
for (Object nextEntry : (Object[]) param) {
if (nextEntry != null) {
paramsList.add(nextEntry);
}
}
}
else if (param instanceof Iterable) {
for (Object nextEntry : (Iterable<?>) param) {
if (nextEntry != null) {
paramsList.add(nextEntry); }
}
}
else {
paramsList.add(param);
}
}
}
}
return paramsList;
}
public Scanner build() {
return new Scanner(this);
}
@Override
public List<URL> getUrls() {
return urls;
}
ConfigurationBuilder setUrls(final Collection<URL> urls) {
this.urls = new ArrayList<URL>(urls);
return this;
}
ConfigurationBuilder setUrls(final URL... urls) {
this.urls = new ArrayList<URL>(urls.length);
for(URL next : urls) {
this.urls.add(next);
}
return this;
}
ConfigurationBuilder addUrls(final Collection<URL> urls) {
this.urls.addAll(urls);
return this;
}
ConfigurationBuilder addUrls(final URL... urls) {
for(URL next : urls) {
this.urls.add(next);
}
return this;
}
@Override
public List<Locator<URL>> getLocators() {
return locators;
}
ConfigurationBuilder setLocators(final Collection<Locator<URL>> locators) {
this.locators = new ArrayList<Locator<URL>>(locators);
return this;
}
@SafeVarargs
final ConfigurationBuilder setLocators(final Locator<URL>... locators) {
this.locators = new ArrayList<Locator<URL>>(locators.length);
for (Locator<URL> next : locators) {
this.locators.add(next);
}
return this;
}
ConfigurationBuilder addLocators(final Collection<Locator<URL>> locators) {
this.locators.addAll(locators);
return this;
}
@SafeVarargs
final ConfigurationBuilder addLocators(final Locator<URL>... locators) {
for (Locator<URL> next : locators) {
this.locators.add(next);
}
return this;
}
@Override
public List<ClassLoader> getClassLoaders() {
return classLoaders;
}
ConfigurationBuilder setClassLoaders(final Collection<ClassLoader> classLoaders) {
this.classLoaders = new ArrayList<ClassLoader>(classLoaders);
return this;
}
ConfigurationBuilder setClassLoaders(final ClassLoader... classLoaders) {
this.classLoaders = new ArrayList<ClassLoader>(classLoaders.length);
for (ClassLoader next : classLoaders) {
this.classLoaders.add(next);
}
return this;
}
ConfigurationBuilder addClassLoaders(final Collection<ClassLoader> classLoaders) {
this.classLoaders.addAll(classLoaders);
return this;
}
ConfigurationBuilder addClassLoaders(final ClassLoader... classLoaders) {
for (ClassLoader next : classLoaders) {
this.classLoaders.add(next);
}
return this;
}
@Override
public List<Filter<?>> getFilters() {
return filters;
}
ConfigurationBuilder setFilters(final List<Filter<?>> filters) {
this.filters = new ArrayList<Filter<?>>(filters);
return this;
}
ConfigurationBuilder setFilters(final Filter<?>... filters) {
this.filters = new ArrayList<Filter<?>>(filters.length);
for (Filter<?> next : filters) {
this.filters.add(next);
}
return this;
}
ConfigurationBuilder addFilters(final List<Filter<?>> filters) {
this.filters.addAll(filters);
return this;
}
ConfigurationBuilder addFilters(final Filter<?>... filters) {
for (Filter<?> next : filters) {
this.filters.add(next);
}
return this;
}
}
| apache-2.0 |
daedric/buck | src/com/facebook/buck/jvm/java/PrebuiltJarDescription.java | 5927 | /*
* Copyright 2014-present Facebook, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may
* not use this file except in compliance with the License. You may obtain
* a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*/
package com.facebook.buck.jvm.java;
import com.facebook.buck.model.BuildTarget;
import com.facebook.buck.model.BuildTargets;
import com.facebook.buck.model.UnflavoredBuildTarget;
import com.facebook.buck.parser.NoSuchBuildTargetException;
import com.facebook.buck.rules.AbstractBuildRule;
import com.facebook.buck.rules.AbstractDescriptionArg;
import com.facebook.buck.rules.AddToRuleKey;
import com.facebook.buck.rules.BuildContext;
import com.facebook.buck.rules.BuildRule;
import com.facebook.buck.rules.BuildRuleParams;
import com.facebook.buck.rules.BuildRuleResolver;
import com.facebook.buck.rules.BuildableContext;
import com.facebook.buck.rules.Description;
import com.facebook.buck.rules.SourcePath;
import com.facebook.buck.rules.SourcePathResolver;
import com.facebook.buck.rules.SourcePathRuleFinder;
import com.facebook.buck.rules.TargetGraph;
import com.facebook.buck.step.Step;
import com.facebook.buck.step.fs.CopyStep;
import com.facebook.buck.step.fs.MakeCleanDirectoryStep;
import com.facebook.infer.annotation.SuppressFieldNotInitialized;
import com.google.common.annotations.VisibleForTesting;
import com.google.common.base.Suppliers;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableSortedSet;
import java.nio.file.Path;
import java.util.Optional;
public class PrebuiltJarDescription implements Description<PrebuiltJarDescription.Arg> {
@Override
public Arg createUnpopulatedConstructorArg() {
return new Arg();
}
@Override
public <A extends Arg> BuildRule createBuildRule(
TargetGraph targetGraph,
BuildRuleParams params,
BuildRuleResolver resolver,
A args) throws NoSuchBuildTargetException {
SourcePathRuleFinder ruleFinder = new SourcePathRuleFinder(resolver);
if (params.getBuildTarget().getFlavors().contains(CalculateAbi.FLAVOR)) {
return CalculateAbi.of(
params.getBuildTarget(),
ruleFinder,
params,
args.binaryJar);
}
SourcePathResolver pathResolver = new SourcePathResolver(ruleFinder);
BuildTarget abiJarTarget = params.getBuildTarget().withAppendedFlavors(CalculateAbi.FLAVOR);
BuildRule prebuilt = new PrebuiltJar(
params,
pathResolver,
args.binaryJar,
abiJarTarget,
args.sourceJar,
args.gwtJar,
args.javadocUrl,
args.mavenCoords,
args.provided.orElse(false));
UnflavoredBuildTarget prebuiltJarBuildTarget = params.getBuildTarget().checkUnflavored();
BuildTarget flavoredBuildTarget = BuildTargets.createFlavoredBuildTarget(
prebuiltJarBuildTarget, JavaLibrary.GWT_MODULE_FLAVOR);
BuildRuleParams gwtParams = params.copyWithChanges(
flavoredBuildTarget,
/* declaredDeps */ Suppliers.ofInstance(ImmutableSortedSet.of(prebuilt)),
/* inferredDeps */ Suppliers.ofInstance(ImmutableSortedSet.of()));
BuildRule gwtModule = createGwtModule(gwtParams, args);
resolver.addToIndex(gwtModule);
return prebuilt;
}
@VisibleForTesting
static BuildRule createGwtModule(BuildRuleParams params, Arg arg) {
// Because a PrebuiltJar rarely requires any building whatsoever (it could if the source_jar
// is a BuildTargetSourcePath), we make the PrebuiltJar a dependency of the GWT module. If this
// becomes a performance issue in practice, then we will explore reducing the dependencies of
// the GWT module.
final SourcePath input;
if (arg.gwtJar.isPresent()) {
input = arg.gwtJar.get();
} else if (arg.sourceJar.isPresent()) {
input = arg.sourceJar.get();
} else {
input = arg.binaryJar;
}
class ExistingOuputs extends AbstractBuildRule {
@AddToRuleKey
private final SourcePath source;
private final Path output;
protected ExistingOuputs(
BuildRuleParams params,
SourcePath source) {
super(params);
this.source = source;
BuildTarget target = params.getBuildTarget();
this.output = BuildTargets.getGenPath(
getProjectFilesystem(),
target,
String.format("%s/%%s-gwt.jar", target.getShortName()));
}
@Override
public ImmutableList<Step> getBuildSteps(
BuildContext context,
BuildableContext buildableContext) {
buildableContext.recordArtifact(getPathToOutput());
ImmutableList.Builder<Step> steps = ImmutableList.builder();
steps.add(new MakeCleanDirectoryStep(getProjectFilesystem(), output.getParent()));
steps.add(CopyStep.forFile(
getProjectFilesystem(),
context.getSourcePathResolver().getAbsolutePath(source),
output));
return steps.build();
}
@Override
public Path getPathToOutput() {
return output;
}
}
return new ExistingOuputs(params, input);
}
@SuppressFieldNotInitialized
public static class Arg extends AbstractDescriptionArg {
public SourcePath binaryJar;
public Optional<SourcePath> sourceJar;
public Optional<SourcePath> gwtJar;
public Optional<String> javadocUrl;
public Optional<String> mavenCoords;
public Optional<Boolean> provided;
public ImmutableSortedSet<BuildTarget> deps = ImmutableSortedSet.of();
}
}
| apache-2.0 |
consulo/consulo-xml | xml-dom-api/src/main/java/com/intellij/util/xml/DomReferenceInjector.java | 1052 | /*
* Copyright 2000-2009 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.intellij.util.xml;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import com.intellij.psi.PsiElement;
import com.intellij.psi.PsiReference;
public interface DomReferenceInjector {
@Nullable
String resolveString(@Nullable String unresolvedText, @Nonnull ConvertContext context);
@Nonnull
PsiReference[] inject(@Nullable String unresolvedText, @Nonnull PsiElement element, @Nonnull ConvertContext context);
}
| apache-2.0 |
echalkpad/t4f-data | search/elasticsearch/src/test/java/io/datalayer/elasticsearch/ElasticSearchQueryFacetTest.java | 11726 | package io.datalayer.elasticsearch;
import static io.datalayer.elasticsearch.fixture.AosElasticSearchFacets.dateHistogramFacetBuilder;
import static io.datalayer.elasticsearch.fixture.AosElasticSearchFacets.filterFacetBuilder;
import static io.datalayer.elasticsearch.fixture.AosElasticSearchFacets.filteredTermsFacetBuilder;
import static io.datalayer.elasticsearch.fixture.AosElasticSearchFacets.geoDistanceFacetBuilder;
import static io.datalayer.elasticsearch.fixture.AosElasticSearchFacets.histogramFacetBuilder;
import static io.datalayer.elasticsearch.fixture.AosElasticSearchFacets.queryFacetBuilder;
import static io.datalayer.elasticsearch.fixture.AosElasticSearchFacets.rangeFacetBuilder;
import static io.datalayer.elasticsearch.fixture.AosElasticSearchFacets.statisticalFacetBuilder;
import static io.datalayer.elasticsearch.fixture.AosElasticSearchFacets.termFacetBuilder;
import static io.datalayer.elasticsearch.fixture.AosElasticSearchFacets.termsFacetBuilder;
import static io.datalayer.elasticsearch.fixture.AosElasticSearchFacets.termsStatsFacetBuilder;
import static org.junit.Assert.assertTrue;
import io.datalayer.elasticsearch._base.ElasticSearchBaseTest;
import java.io.IOException;
import java.util.Date;
import org.elasticsearch.action.admin.indices.create.CreateIndexResponse;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.common.xcontent.XContentFactory;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.facet.datehistogram.DateHistogramFacet;
import org.elasticsearch.search.facet.filter.FilterFacet;
import org.elasticsearch.search.facet.geodistance.GeoDistanceFacet;
import org.elasticsearch.search.facet.histogram.HistogramFacet;
import org.elasticsearch.search.facet.query.QueryFacet;
import org.elasticsearch.search.facet.range.RangeFacet;
import org.elasticsearch.search.facet.statistical.StatisticalFacet;
import org.elasticsearch.search.facet.terms.TermsFacet;
import org.elasticsearch.search.facet.termsstats.TermsStatsFacet;
import org.junit.BeforeClass;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* <p>
* This test class gathers the ElasticSearch common methods and executes them in order.
* It will search with faceted queries an index.
* </p>
* <p>
* You can override the #useRemoteServer method (default is false):
* <ul>
* <li>If false, this test will kick-off an ElasticSearch Embedded Cluster (easy!).</li>
* <li>If true, ensure you have an ElasticSearch server running on ES_CLUSTER_HOST:ES_CLUSTER_PORT with name ES_CLUSTER_NAME.</li>
* </ul>
* </p>
*/
public class ElasticSearchQueryFacetTest extends ElasticSearchBaseTest {
private static final Logger LOGGER = LoggerFactory.getLogger(ElasticSearchQueryFacetTest.class);
private static SearchResponse searchResponse;
@BeforeClass
public static void beforeClass() throws IOException {
ElasticSearchBaseTest.beforeClass();
indexName("facets");
typeName("facets");
ElasticSearchBaseTest.beforeClass();
String mapping = XContentFactory.jsonBuilder() //
.startObject() //
.startObject(typeName()) //
.startObject("properties") //
.startObject("location") //
.field("type", "geo_point") //
.field("lat_lon", true) //
.endObject() //
.endObject() //
.endObject() //
.endObject() //
.string();
LOGGER.info("Mapping=" + mapping);
CreateIndexResponse createIndexResponse = client().admin() //
.indices() //
.prepareCreate(indexName()) //
.addMapping(typeName(), mapping) //
.execute() //
.actionGet();
assertTrue(createIndexResponse.isAcknowledged());
int numDocs = 100;
index(numDocs);
searchResponse = client().prepareSearch(indexName()) //
.setTypes(typeName()) //
.setSize(100) //
.setQuery(QueryBuilders.matchAllQuery()) //
.addFacet(queryFacetBuilder) //
.addFacet(filterFacetBuilder) //
.addFacet(filteredTermsFacetBuilder) //
.addFacet(rangeFacetBuilder) //
.addFacet(termFacetBuilder) //
.addFacet(termsFacetBuilder) //
.addFacet(histogramFacetBuilder) //
.addFacet(dateHistogramFacetBuilder) //
.addFacet(statisticalFacetBuilder) //
.addFacet(termsStatsFacetBuilder) //
.addFacet(geoDistanceFacetBuilder) //
.execute() //
.actionGet();
}
@Test
public void testQueryFacet() throws IOException {
QueryFacet queryFacet = (QueryFacet) searchResponse.getFacets() //
.facetsAsMap() //
.get("query_facet");
LOGGER.info("Count: " + queryFacet.getCount()); // Number of docs that matched.
assertTrue(queryFacet.getCount() > 0);
}
@Test
public void testFilterFacet() throws IOException {
FilterFacet filterFacet = (FilterFacet) searchResponse.getFacets() //
.facetsAsMap() //
.get("filter_facet");
LOGGER.info("Count: " + filterFacet.getCount()); // Number of docs that matched.
assertTrue(filterFacet.getCount() > 0);
}
@Test
public void testRangeFacet() throws IOException {
RangeFacet rangeFacet = (RangeFacet) searchResponse.getFacets() //
.facetsAsMap() //
.get("range_facet");
for (RangeFacet.Entry entry : rangeFacet) {
LOGGER.info("From: " + entry.getFrom()); // Range from requested.
LOGGER.info("To: " + entry.getTo()); // Range to requested.
LOGGER.info("Count: " + entry.getCount()); // Doc count.
LOGGER.info("Min: " + entry.getMin()); // Min value.
LOGGER.info("Max: " + entry.getMax()); // Max value.
LOGGER.info("Mean: " + entry.getMean()); // Mean.
LOGGER.info("Total: " + entry.getTotal()); // Sum of values.
}
}
@Test
public void testTermFacet() throws IOException {
TermsFacet termFacet = (TermsFacet) searchResponse.getFacets() //
.facetsAsMap() //
.get("term_facet");
for (TermsFacet.Entry entry : termFacet) {
LOGGER.info("Term: " + entry.getTerm()); // Term.
LOGGER.info("Count: " + entry.getCount()); // Doc count.
}
}
@Test
public void testTermsFacet() throws IOException {
TermsFacet termsFacet = (TermsFacet) searchResponse.getFacets() //
.facetsAsMap() //
.get("terms_facet");
LOGGER.info("Total Count: " + termsFacet.getTotalCount()); // Total terms doc count.
LOGGER.info("Other Count: " + termsFacet.getOtherCount()); // Not shown terms doc count.
LOGGER.info("Missing Count: " + termsFacet.getMissingCount()); // Without term doc count.
for (TermsFacet.Entry entry : termsFacet) {
LOGGER.info("Term: " + entry.getTerm() + " - Count: " + entry.getCount()); // Term and Doc count.
}
}
@Test
public void testHistogramFacet() throws IOException {
HistogramFacet histogramFacet = (HistogramFacet) searchResponse.getFacets() //
.facetsAsMap() //
.get("histogram_facet");
for (HistogramFacet.Entry entry : histogramFacet) {
LOGGER.info("Key: " + entry.getKey()); // Key (X-Axis)
LOGGER.info("Max: " + entry.getMax()); // Max.
LOGGER.info("Mean: " + entry.getMean()); // Mean.
LOGGER.info("Min: " + entry.getMin()); // Min.
LOGGER.info("Count: " + entry.getCount()); // Doc count (Y-Axis)
LOGGER.info("Total: " + entry.getTotal());
LOGGER.info("Total Count: " + entry.getTotalCount());
LOGGER.info("---");
}
}
@Test
public void testDateHistogramFacet() throws IOException {
DateHistogramFacet dateHistogramFacet = (DateHistogramFacet) searchResponse.getFacets() //
.facetsAsMap() //
.get("date_histogram_facet");
for (DateHistogramFacet.Entry entry : dateHistogramFacet) {
LOGGER.info("Date: " + new Date(entry.getTime())); // Date in ms since epoch (X-Axis).
LOGGER.info("Max: " + entry.getMax()); // Max.
LOGGER.info("Mean: " + entry.getMean()); // Mean.
LOGGER.info("Min: " + entry.getMin()); // Min.
LOGGER.info("Count: " + entry.getCount()); // Doc count (Y-Axis)
LOGGER.info("Total: " + entry.getTotal());
LOGGER.info("Total Count: " + entry.getTotalCount());
LOGGER.info("---");
}
}
@Test
public void testStatisticalFacet() throws IOException {
StatisticalFacet statisticalFacet = (StatisticalFacet) searchResponse.getFacets() //
.facetsAsMap() //
.get("statistical_facet");
LOGGER.info("Count: " + statisticalFacet.getCount()); // Doc count
LOGGER.info("Min: " + statisticalFacet.getMin()); // Min value
LOGGER.info("Max: " + statisticalFacet.getMax()); // Max value
LOGGER.info("Mean: " + statisticalFacet.getMean()); // Mean
LOGGER.info("Total: " + statisticalFacet.getTotal()); // Sum of values
LOGGER.info("Std Deviation: " + statisticalFacet.getStdDeviation()); // Standard Deviation
LOGGER.info("Sum of Squares: " + statisticalFacet.getSumOfSquares()); // Sum of Squares
LOGGER.info("Variance: " + statisticalFacet.getVariance()); // Variance
}
@Test
public void testTermsStatsFacet() throws IOException {
TermsStatsFacet termsStatsFacet = (TermsStatsFacet) searchResponse.getFacets() //
.facetsAsMap() //
.get("terms_stats_facet");
termsStatsFacet.getMissingCount(); // Without term doc count
for (TermsStatsFacet.Entry entry : termsStatsFacet) {
LOGGER.info("Term: " + entry.getTerm()); // Term
LOGGER.info("Count: " + entry.getCount()); // Doc count
LOGGER.info("Min: " + entry.getMin()); // Min value
LOGGER.info("Max: " + entry.getMax()); // Max value
LOGGER.info("Mean: " + entry.getMean()); // Mean
LOGGER.info("Total: " + entry.getTotal()); // Sum of values
}
}
@Test
public void testGeoDistanceFacet() throws IOException {
GeoDistanceFacet geoDistanceFacet = (GeoDistanceFacet) searchResponse.getFacets() //
.facetsAsMap() //
.get("geo_distance_facet");
for (GeoDistanceFacet.Entry entry : geoDistanceFacet) {
LOGGER.info("From: " + entry.getFrom()); // Distance from requested
LOGGER.info("To: " + entry.getTo()); // Distance to requested
LOGGER.info("Count: " + entry.getCount()); // Doc count
LOGGER.info("Min: " + entry.getMin()); // Min value
LOGGER.info("Max: " + entry.getMax()); // Max value
LOGGER.info("Total: " + entry.getTotal()); // Sum of values
LOGGER.info("Mean: " + entry.getMean()); // Mean
}
}
}
| apache-2.0 |
fSergio101/orchextra-android-sdk | orchextrasdk-domain/src/main/java/com/gigigo/orchextra/domain/abstractions/geofences/GeofenceRegister.java | 982 | /*
* Created by Orchextra
*
* Copyright (C) 2016 Gigigo Mobile Services SL
*
* 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.gigigo.orchextra.domain.abstractions.geofences;
import com.gigigo.orchextra.domain.model.entities.proximity.OrchextraGeofenceUpdates;
public interface GeofenceRegister {
void registerGeofences(OrchextraGeofenceUpdates geofenceUpdates);
void clearGeofences();
void startGeofenceRegister();
void stopGeofenceRegister();
}
| apache-2.0 |
imie-source/Ekologia | EkologiaService/ejbModule/coop/ekologia/service/mapper/Mapper.java | 906 | package coop.ekologia.service.mapper;
import java.util.ArrayList;
import java.util.Collection;
import coop.ekologia.DTO.user.UserDTO;
import coop.ekologia.entity.user.User;
public abstract class Mapper<DTO, Entity> {
public abstract DTO mapFromEntity(Entity entity);
public abstract Entity mapToEntity(DTO entity);
public Collection<DTO> mapFromEntity(Collection<Entity> entities) {
if (entities == null) {
return new ArrayList<DTO>();
}
Collection<DTO> result = new ArrayList<DTO>();
for (Entity entity: entities) {
result.add(mapFromEntity(entity));
}
return result;
}
public Collection<Entity> mapToEntity(Collection<DTO> entities) {
if (entities == null) {
return new ArrayList<Entity>();
}
Collection<Entity> result = new ArrayList<Entity>();
for (DTO entity: entities) {
result.add(mapToEntity(entity));
}
return result;
}
}
| apache-2.0 |
lioutasb/CSCartApp | app/src/main/java/gr/plushost/prototypeapp/parsers/LanguagesParser.java | 1064 | package gr.plushost.prototypeapp.parsers;
import org.json.JSONArray;
import java.util.ArrayList;
import java.util.List;
import gr.plushost.prototypeapp.items.StoreLanguageItem;
/**
* Created by billiout on 11/3/2015.
*/
public class LanguagesParser {
public List<StoreLanguageItem> parse(JSONArray response){
List<StoreLanguageItem> list = new ArrayList<>();
try {
for(int i = 0; i < response.length(); i++){
StoreLanguageItem item = new StoreLanguageItem();
item.setLanguage_code(response.getJSONObject(i).getString("language_code"));
item.setLanguage_id(response.getJSONObject(i).getString("language_id"));
item.setLanguage_name(response.getJSONObject(i).getString("language_name"));
item.setPosition(response.getJSONObject(i).getInt("position"));
list.add(item);
}
}
catch (Exception e){
e.printStackTrace();
}
return list;
}
}
| apache-2.0 |
Intuso/housemate | client/real/impl/src/main/java/com/intuso/housemate/client/real/impl/internal/CombinationList.java | 5849 | package com.intuso.housemate.client.real.impl.internal;
import com.intuso.housemate.client.api.internal.object.List;
import com.intuso.housemate.client.api.internal.object.Object;
import com.intuso.housemate.client.api.internal.object.Tree;
import com.intuso.housemate.client.api.internal.object.view.ListView;
import com.intuso.housemate.client.api.internal.object.view.View;
import com.intuso.utilities.collection.ManagedCollection;
import com.intuso.utilities.collection.ManagedCollectionFactory;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.NoSuchElementException;
/**
* Created by tomc on 02/05/17.
*/
public class CombinationList<T extends Object<?, ?, ?>>
implements List<T, CombinationList<T>>, List.Listener<T, List<T, ?>> {
private final List.Data data;
private final ManagedCollection<List.Listener<? super T, ? super CombinationList<T>>> listeners;
private final java.util.List<List<? extends T, ?>> lists = new ArrayList<>();
public CombinationList(List.Data data, ManagedCollectionFactory managedCollectionFactory) {
this.data = data;
this.listeners = managedCollectionFactory.createSet();
}
public void addList(List<? extends T, ?> list) {
lists.add(list);
((List<T, ?>)list).addObjectListener(this, true);
}
@Override
public Data getData() {
return data;
}
@Override
public String getObjectClass() {
return Data.OBJECT_CLASS;
}
@Override
public String getId() {
return data.getId();
}
@Override
public String getName() {
return data.getName();
}
@Override
public String getDescription() {
return data.getDescription();
}
@Override
public ManagedCollection.Registration addObjectListener(Listener<? super T, ? super CombinationList<T>> listener) {
return listeners.add(listener);
}
@Override
public ManagedCollection.Registration addObjectListener(Listener<? super T, ? super CombinationList<T>> listener, boolean callForExistingElements) {
ManagedCollection.Registration result = listeners.add(listener);
if(callForExistingElements)
for(List<? extends T, ?> list : lists)
for(T element : list)
listener.elementAdded(this, element);
return result;
}
@Override
public T get(String id) {
for(List<? extends T, ?> list : lists) {
T element = list.get(id);
if(element != null)
return element;
}
return null;
}
@Override
public T getByName(String name) {
for(List<? extends T, ?> list : lists) {
T element = list.getByName(name);
if(element != null)
return element;
}
return null;
}
@Override
public Object<?, ?, ?> getChild(String id) {
return get(id);
}
@Override
public ListView<?> createView(View.Mode mode) {
return new ListView<>(mode);
}
@Override
public Tree getTree(ListView<?> view, Tree.ReferenceHandler referenceHandler, Tree.Listener listener, java.util.List<ManagedCollection.Registration> listenerRegistrations) {
Tree result = new Tree(getData());
switch (view.getMode()) {
case ANCESTORS:
for(T t : this)
result.getChildren().put(t.getId(), ((Object) t).getTree(t.createView(View.Mode.ANCESTORS), referenceHandler, listener, listenerRegistrations));
break;
case CHILDREN:
for(T t : this)
result.getChildren().put(t.getId(), ((Object) t).getTree(view.getView(), referenceHandler, listener, listenerRegistrations));
break;
case SELECTION:
if (view.getElements() != null) {
for (String id : view.getElements()) {
T t = get(id);
if (t != null)
result.getChildren().put(id, ((Object) t).getTree(view.getView(), referenceHandler, listener, listenerRegistrations));
}
}
break;
}
return result;
}
@Override
public int size() {
int totalSize = 0;
for(List<? extends T, ?> list : lists)
totalSize += list.size();
return totalSize;
}
@Override
public Iterator<T> iterator() {
return new IteratorImpl();
}
@Override
public void elementAdded(List<T, ?> list, T element) {
for(List.Listener<? super T, ? super CombinationList<T>> listener : listeners)
listener.elementAdded(this, element);
}
@Override
public void elementRemoved(List<T, ?> list, T element) {
for(List.Listener<? super T, ? super CombinationList<T>> listener : listeners)
listener.elementRemoved(this, element);
}
public class IteratorImpl implements Iterator<T> {
private final Iterator<List<? extends T, ?>> listsIter = lists.iterator();
private Iterator<? extends T> current = listsIter.hasNext() ? listsIter.next().iterator() : null;
@Override
public boolean hasNext() {
if(current != null && !current.hasNext())
current = listsIter.hasNext() ? listsIter.next().iterator() : null;
return current != null && current.hasNext();
}
@Override
public T next() {
if(current == null)
throw new NoSuchElementException();
return current.next();
}
@Override
public void remove() {
if(current == null)
throw new NoSuchElementException();
current.remove();
}
}
}
| apache-2.0 |
NationalSecurityAgency/ghidra | Ghidra/Features/Base/src/test.slow/java/ghidra/app/merge/listing/AbstractExternalMergerTest.java | 31260 | /* ###
* IP: GHIDRA
*
* 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 ghidra.app.merge.listing;
import static org.junit.Assert.*;
import java.awt.Component;
import java.awt.Window;
import java.util.List;
import javax.swing.JComponent;
import javax.swing.border.Border;
import javax.swing.border.TitledBorder;
import org.junit.Assert;
import generic.test.TestUtils;
import ghidra.app.cmd.function.AddRegisterParameterCommand;
import ghidra.app.cmd.function.AddStackParameterCommand;
import ghidra.program.database.ProgramDB;
import ghidra.program.database.symbol.LibrarySymbol;
import ghidra.program.model.address.Address;
import ghidra.program.model.data.DataType;
import ghidra.program.model.lang.Register;
import ghidra.program.model.listing.*;
import ghidra.program.model.symbol.*;
import ghidra.util.exception.DuplicateNameException;
import ghidra.util.exception.InvalidInputException;
public abstract class AbstractExternalMergerTest extends AbstractListingMergeManagerTest {
static final String KEEP_BOTH_BUTTON = ExternalFunctionMerger.KEEP_BOTH_BUTTON_NAME;
static final String MERGE_BOTH_BUTTON = ExternalFunctionMerger.MERGE_BOTH_BUTTON_NAME;
public AbstractExternalMergerTest() {
super();
}
ExternalLocation createExternalLabel(ProgramDB program, String transactionDescription,
String library, String label, String addressAsString, DataType dataType,
SourceType sourceType) {
Address address = (addressAsString != null) ? addr(program, addressAsString) : null;
int txId = program.startTransaction(transactionDescription);
boolean commit = false;
ExternalManager externalManager = program.getExternalManager();
try {
SymbolTable symbolTable = program.getSymbolTable();
Library externalLibrary = symbolTable.createExternalLibrary(library, sourceType);
ExternalLocation externalLocation =
externalManager.addExtLocation(externalLibrary, label, address, sourceType);
if (dataType != null) {
externalLocation.setDataType(dataType);
}
commit = true;
}
catch (Exception e) {
Assert.fail(e.getMessage());
}
finally {
program.endTransaction(txId, commit);
}
assertTrue(externalManager.contains(library));
ExternalLocation externalLocation =
externalManager.getUniqueExternalLocation(library, label);
assertNotNull(externalLocation);
assertEquals(false, externalLocation.isFunction());
assertEquals(library + "::" + label, externalLocation.toString());
assertEquals(address, externalLocation.getAddress());
assertTrue(externalLocation.getSource() == sourceType);
DataType extDataType = externalLocation.getDataType();
if (dataType == null) {
assertNull(extDataType);
}
else {
assertNotNull(extDataType);
assertTrue(extDataType.isEquivalent(dataType));
}
return externalLocation;
}
/**
*
* @param program
* @param transactionDescription
* @param library
* @param label
*/
void removeExternalLabel(ProgramDB program, String transactionDescription, String library,
String label) {
int txId = program.startTransaction(transactionDescription);
boolean commit = false;
ExternalManager externalManager = program.getExternalManager();
try {
ExternalLocation externalLocation =
externalManager.getUniqueExternalLocation(library, label);
assertNotNull(externalLocation);
program.getSymbolTable().removeSymbolSpecial(externalLocation.getSymbol());
commit = true;
}
catch (Exception e) {
Assert.fail(e.getMessage());
}
finally {
program.endTransaction(txId, commit);
}
assertTrue(externalManager.contains(library));
ExternalLocation externalLocation =
externalManager.getUniqueExternalLocation(library, label);
assertNull(externalLocation);
}
/**
*
* @param program
* @param transactionDescription
* @param library
* @param label
* @param addressAsString
* @param sourceType
* @return
*/
ExternalLocation createExternalFunction(ProgramDB program, String transactionDescription,
String library, String label, String addressAsString, SourceType sourceType) {
Address address = (addressAsString != null) ? addr(program, addressAsString) : null;
int txId = program.startTransaction(transactionDescription);
boolean commit = false;
ExternalManager externalManager = program.getExternalManager();
try {
SymbolTable symbolTable = program.getSymbolTable();
Library externalLibrary = symbolTable.createExternalLibrary(library, sourceType);
ExternalLocation externalLocation =
externalManager.addExtFunction(externalLibrary, label, address, sourceType);
assertNotNull(externalLocation);
commit = true;
}
catch (Exception e) {
Assert.fail(e.getMessage());
}
finally {
program.endTransaction(txId, commit);
}
assertTrue(externalManager.contains(library));
ExternalLocation externalLocation =
externalManager.getUniqueExternalLocation(library, label);
assertNotNull(externalLocation);
assertEquals(true, externalLocation.isFunction());
assertEquals(library + "::" + label, externalLocation.toString());
assertEquals(address, externalLocation.getAddress());
assertTrue(externalLocation.getSource() == sourceType);
DataType extDataType = externalLocation.getDataType();
assertNull(extDataType);
Function function = externalLocation.getFunction();
assertNotNull(function);
assertEquals(0, function.getParameterCount());
return externalLocation;
}
/**
*
* @param program
* @param transactionDescription
* @param library
* @param label
* @param addressAsString
*/
void removeExternalFunctionLocation(ProgramDB program, String transactionDescription,
String library, String label, String addressAsString) {
int txId = program.startTransaction(transactionDescription);
boolean commit = false;
ExternalManager externalManager = program.getExternalManager();
try {
ExternalLocation externalLocation =
externalManager.getUniqueExternalLocation(library, label);
assertNotNull(externalLocation);
if (!externalLocation.isFunction()) {
Assert.fail(externalLocation.getLabel() + " is not a function.");
}
Symbol externalSymbol = externalLocation.getSymbol();
boolean delete = externalSymbol.delete();
assertTrue(delete);
commit = true;
Symbol s = getUniqueSymbol(program, library, program.getGlobalNamespace());
if (s instanceof LibrarySymbol) {
Symbol symbol = getUniqueSymbol(program, label, (Namespace) s.getObject());
symbol.delete();
}
commit = true;
}
catch (Exception e) {
Assert.fail(e.getMessage());
}
finally {
program.endTransaction(txId, commit);
}
SymbolTable symbolTable = program.getSymbolTable();
Symbol s = symbolTable.getLibrarySymbol(library);
if (s instanceof LibrarySymbol) {
Symbol symbol = getUniqueSymbol(program, label, (Namespace) s.getObject());
assertNull(symbol);
}
assertTrue(externalManager.contains(library));
ExternalLocation externalLocation =
externalManager.getUniqueExternalLocation(library, label);
assertNull(externalLocation);
FunctionIterator externalFunctions = program.getFunctionManager().getExternalFunctions();
assertEquals(false, externalFunctions.hasNext());
}
/**
*
* @param program
* @param transactionDescription
* @param library
* @param label
* @param addressAsString
*/
void changeExternalFunctionIntoExternalLabel(Program program, String[] path) {
Function externalFunction = getExternalFunction(program, path);
int txId = program.startTransaction("Changing external function into an external label.");
boolean commit = false;
try {
Symbol externalSymbol = externalFunction.getSymbol();
boolean delete = externalSymbol.delete();
assertTrue(delete);
commit = true;
}
catch (Exception e) {
Assert.fail(e.getMessage());
}
finally {
program.endTransaction(txId, commit);
}
ExternalLocation externalLocation = getExternalLocation(program, path);
assertNotNull(externalLocation);
assertFalse(externalLocation.isFunction());
}
/**
*
* @param program
* @param transactionDescription
* @param library
* @param label
* @param addressAsString
*/
void setAddressForExternalLabel(ProgramDB program, String transactionDescription,
String library, String label, String addressAsString) {
int txId = program.startTransaction(transactionDescription);
boolean commit = false;
ExternalManager externalManager = program.getExternalManager();
try {
ExternalLocation externalLocation =
externalManager.getUniqueExternalLocation(library, label);
assertNotNull(externalLocation);
Address address = (addressAsString != null) ? addr(program, addressAsString) : null;
externalLocation.setLocation(externalLocation.getLabel(), address,
externalLocation.getSource());
commit = true;
}
catch (Exception e) {
Assert.fail(e.getMessage());
}
finally {
program.endTransaction(txId, commit);
}
assertTrue(externalManager.contains(library));
ExternalLocation externalLocation =
externalManager.getUniqueExternalLocation(library, label);
assertNotNull(externalLocation);
assertEquals(library + "::" + label, externalLocation.toString());
Address address = externalLocation.getAddress();
assertEquals(addressAsString, (address != null) ? address.toString() : null);
}
/**
*
* @param program
* @param transactionDescription
* @param library
* @param label
*/
void removeAddressFromExternalLabel(ProgramDB program, String transactionDescription,
String library, String label) {
int txId = program.startTransaction(transactionDescription);
boolean commit = false;
ExternalManager externalManager = program.getExternalManager();
try {
ExternalLocation externalLocation =
externalManager.getUniqueExternalLocation(library, label);
assertNotNull(externalLocation);
externalLocation.setLocation(externalLocation.getLabel(), null,
externalLocation.getSource());
commit = true;
}
catch (Exception e) {
Assert.fail(e.getMessage());
}
finally {
program.endTransaction(txId, commit);
}
assertTrue(externalManager.contains(library));
ExternalLocation externalLocation =
externalManager.getUniqueExternalLocation(library, label);
assertNotNull(externalLocation);
assertEquals(library + "::" + label, externalLocation.toString());
assertNull(externalLocation.getAddress());
}
/**
*
* @param program
* @param transactionDescription
* @param library
* @param label
*/
void changeMemAddressForExternalLabel(ProgramDB program, String transactionDescription,
String library, String label, String changeAddressAsString) {
Address changeAddress =
(changeAddressAsString != null) ? addr(program, changeAddressAsString) : null;
int txId = program.startTransaction(transactionDescription);
boolean commit = false;
ExternalManager externalManager = program.getExternalManager();
try {
ExternalLocation externalLocation =
externalManager.getUniqueExternalLocation(library, label);
assertNotNull(externalLocation);
externalLocation.setLocation(externalLocation.getLabel(), changeAddress,
externalLocation.getSource());
commit = true;
}
catch (Exception e) {
Assert.fail(e.getMessage());
}
finally {
program.endTransaction(txId, commit);
}
assertTrue(externalManager.contains(library));
ExternalLocation externalLocation =
externalManager.getUniqueExternalLocation(library, label);
assertNotNull(externalLocation);
assertEquals(library + "::" + label, externalLocation.toString());
assertEquals(changeAddress, externalLocation.getAddress());
}
/**
*
* @param program
* @param transactionDescription
* @param library
* @param label
* @param addressAsString
* @param externalDataType
*/
void setDataTypeForExternalLabel(ProgramDB program, String transactionDescription,
String library, String label, String addressAsString, DataType externalDataType) {
Address address = (addressAsString != null) ? addr(program, addressAsString) : null;
int txId = program.startTransaction(transactionDescription);
boolean commit = false;
ExternalManager externalManager = program.getExternalManager();
try {
ExternalLocation externalLocation =
externalManager.getUniqueExternalLocation(library, label);
assertNotNull(externalLocation);
externalLocation.setDataType(externalDataType);
commit = true;
}
catch (Exception e) {
Assert.fail(e.getMessage());
}
finally {
program.endTransaction(txId, commit);
}
assertTrue(externalManager.contains(library));
ExternalLocation externalLocation =
externalManager.getUniqueExternalLocation(library, label);
assertNotNull(externalLocation);
assertEquals(library + "::" + label, externalLocation.toString());
assertEquals(address, externalLocation.getAddress());
DataType dataType = externalLocation.getDataType();
assertTrue(dataType.isEquivalent(externalDataType));
}
/**
*
* @param program
* @param transactionDescription
* @param library
* @param label
* @param addressAsString
*/
void removeDataTypeFromExternalLabel(ProgramDB program, String transactionDescription,
String library, String label, String addressAsString) {
Address address = (addressAsString != null) ? addr(program, addressAsString) : null;
int txId = program.startTransaction(transactionDescription);
boolean commit = false;
ExternalManager externalManager = program.getExternalManager();
try {
ExternalLocation externalLocation =
externalManager.getUniqueExternalLocation(library, label);
assertNotNull(externalLocation);
externalLocation.setDataType(null);
commit = true;
}
catch (Exception e) {
Assert.fail(e.getMessage());
}
finally {
program.endTransaction(txId, commit);
}
assertTrue(externalManager.contains(library));
ExternalLocation externalLocation =
externalManager.getUniqueExternalLocation(library, label);
assertNotNull(externalLocation);
assertEquals(library + "::" + label, externalLocation.toString());
assertEquals(address, externalLocation.getAddress());
DataType dataType = externalLocation.getDataType();
assertNull(dataType);
}
/**
*
* @param program
* @param transactionDescription
* @param library
* @param label
* @param externalSourceType
*/
void setSourceTypeForExternalLabel(ProgramDB program, String transactionDescription,
String library, String label, SourceType externalSourceType) {
int txId = program.startTransaction(transactionDescription);
boolean commit = false;
ExternalManager externalManager = program.getExternalManager();
try {
ExternalLocation externalLocation =
externalManager.getUniqueExternalLocation(library, label);
assertNotNull(externalLocation);
externalLocation.setLocation(externalLocation.getLabel(), externalLocation.getAddress(),
externalSourceType);
commit = true;
}
catch (Exception e) {
Assert.fail(e.getMessage());
}
finally {
program.endTransaction(txId, commit);
}
assertTrue(externalManager.contains(library));
ExternalLocation externalLocation =
externalManager.getUniqueExternalLocation(library, label);
assertNotNull(externalLocation);
assertEquals(library + "::" + label, externalLocation.toString());
SourceType sourceType = externalLocation.getSource();
assertTrue(sourceType == externalSourceType);
}
/**
*
* @param program
* @param transactionDescription
* @param library
* @param label
*/
void changeExternalLabelIntoFunction(ProgramDB program, String transactionDescription,
String library, String label) {
int txId = program.startTransaction(transactionDescription);
boolean commit = false;
ExternalManager externalManager = program.getExternalManager();
try {
ExternalLocation externalLocation =
externalManager.getUniqueExternalLocation(library, label);
assertNotNull(externalLocation);
externalLocation.createFunction();
commit = true;
}
catch (Exception e) {
Assert.fail(e.getMessage());
}
finally {
program.endTransaction(txId, commit);
}
assertTrue(externalManager.contains(library));
ExternalLocation externalLocation =
externalManager.getUniqueExternalLocation(library, label);
assertNotNull(externalLocation);
assertEquals(library + "::" + label, externalLocation.toString());
DataType dataType = externalLocation.getDataType();
assertNull(dataType);
Function function = externalLocation.getFunction();
assertNotNull(function);
}
/**
*
* @param externalLocation
* @param expectedAddress
*/
void checkExternalAddress(ExternalLocation externalLocation, String expectedAddress) {
Address address = externalLocation.getAddress();
String addressString = (address != null) ? address.toString() : null;
String failureMessage =
"Expected external address '" + expectedAddress + "' but was '" + addressString + "'";
assertEquals(failureMessage, expectedAddress, addressString);
}
/**
*
* @param externalLocation
* @param expectedSourceType
*/
void checkExternalSourceType(ExternalLocation externalLocation, SourceType expectedSourceType) {
SourceType sourceType = externalLocation.getSource();
String failureMessage =
"Expected external source type '" + expectedSourceType.getDisplayString() +
"' but was '" + sourceType.getDisplayString() + "'";
assertEquals(failureMessage, expectedSourceType, sourceType);
}
/**
*
* @param externalLocation
* @param expectedDataType
*/
void checkExternalDataType(ExternalLocation externalLocation, DataType expectedDataType) {
DataType dataType = externalLocation.getDataType();
String failureMessage = "Expected external data type '" + expectedDataType.getName() +
"' but was '" + ((dataType != null) ? dataType.getName() : null) + "'";
assertTrue(failureMessage, expectedDataType.isEquivalent(dataType));
}
void checkDataType(DataType expectedDataType, DataType actualDataType) {
String failureMessage = "Expected external data type '" + expectedDataType.getName() +
"' but was '" + ((actualDataType != null) ? actualDataType.getName() : null) + "'";
assertTrue(failureMessage, expectedDataType.isEquivalent(actualDataType));
}
/**
*
* @param function
* @param expectedDataType
*/
void checkFunctionReturnType(Function function, DataType expectedDataType) {
DataType functionReturnType = function.getReturnType();
String failureMessage = "Expected return type '" + expectedDataType.getName() +
"' but was '" + functionReturnType.getName() + "'";
assertTrue(failureMessage, expectedDataType.isEquivalent(functionReturnType));
}
/**
*
* @param parameter
* @param expectedDataType
*/
void checkParameterDataType(Parameter parameter, DataType expectedDataType) {
DataType parameterDataType = parameter.getDataType();
String failureMessage =
"Expected data type '" + expectedDataType.getName() + "' for parameter " +
(parameter.getOrdinal() + 1) + " but was '" + parameterDataType.getName() + "'";
assertTrue(failureMessage, expectedDataType.isEquivalent(parameterDataType));
}
/**
*
* @param programVersion
* @param externalLocationPathName
* @param conflictNumber
* @param totalNumberOfConflicts
* @throws Exception
*/
void checkExternalPanelInfo(final String programVersion, final String externalLocationPathName,
final int conflictNumber, final int totalNumberOfConflicts) throws Exception {
waitForPrompting();
Component mergePanel = getMergePanel(ExternalConflictInfoPanel.class);
Window window = windowForComponent(mergePanel);
JComponent comp = findComponent(window, ExternalConflictInfoPanel.class);
assertNotNull(comp);
Border border = comp.getBorder();
String title = ((TitledBorder) border).getTitle();
assertEquals("Resolve External Location Conflict", title);
ExternalConflictInfoPanel panel = (ExternalConflictInfoPanel) comp;
String versionTitle = (String) TestUtils.getInstanceField("versionTitle", panel);
assertEquals(programVersion, versionTitle);
String labelPathName = (String) TestUtils.getInstanceField("labelPathName", panel);
assertEquals(externalLocationPathName, labelPathName);
int conflictNum = (Integer) TestUtils.getInstanceField("conflictNum", panel);
assertEquals(conflictNumber, conflictNum);
int totalConflicts = (Integer) TestUtils.getInstanceField("totalConflicts", panel);
assertEquals(totalNumberOfConflicts, totalConflicts);
}
/**
* Changes the function's parameter indicated by index to be a register
* parameter with the indicated register.
* @param func the function
* @param index the index of an existing parameter
* @param reg the new register for this parameter
*/
void changeToRegisterParameter(Function func, int index, Register reg) {
Parameter p = func.getParameter(index);
String name = p.getName();
DataType dt = p.getDataType();
String comment = p.getComment();
func.removeParameter(index);
func.setCustomVariableStorage(true);
AddRegisterParameterCommand cmd =
new AddRegisterParameterCommand(func, reg, null, dt, index, SourceType.USER_DEFINED);
cmd.applyTo(func.getProgram());
p = func.getParameter(index);
if (!isDefaultParamName(name)) {
try {
p.setName(name, SourceType.USER_DEFINED);
}
catch (DuplicateNameException e) {
Assert.fail(e.getMessage());
}
catch (InvalidInputException e) {
Assert.fail(e.getMessage());
}
}
if (comment != null) {
p.setComment(comment);
}
}
/**
* @param name the parameter name
* @return true if name is null or a default parameter name.
*/
boolean isDefaultParamName(String name) {
if (name == null) {
return true;
}
if (name.startsWith(Function.DEFAULT_PARAM_PREFIX)) {
String num = name.substring(Function.DEFAULT_PARAM_PREFIX.length());
try {
Integer.parseInt(num);
return true;
}
catch (NumberFormatException e1) {
// Do nothing so returns false;
}
}
return false;
}
/**
* Changes the function's parameter indicated by index to be a stack
* parameter with the indicated stack offset.
* @param func the function
* @param index the index of an existing parameter
* @param stackOffset the stack offset for this parameter
*/
void changeToStackParameter(Function func, int index, int stackOffset) {
Parameter p = func.getParameter(index);
String name = p.getName();
DataType dt = p.getDataType();
String comment = p.getComment();
func.removeParameter(index);
AddStackParameterCommand cmd = new AddStackParameterCommand(func, stackOffset, null, dt,
index, SourceType.USER_DEFINED);
cmd.applyTo(func.getProgram());
p = func.getParameter(index);
if (!isDefaultParamName(name)) {
try {
p.setName(name, SourceType.USER_DEFINED);
}
catch (DuplicateNameException e) {
Assert.fail(e.getMessage());
}
catch (InvalidInputException e) {
Assert.fail(e.getMessage());
}
}
if (comment != null) {
p.setComment(comment);
}
}
Function createExternalFunction(final Program program, final String[] path)
throws DuplicateNameException, InvalidInputException {
return createExternalFunction(program, path, null, null, SourceType.USER_DEFINED);
}
Function createExternalFunction(final Program program, final String[] path,
final Address address) throws DuplicateNameException, InvalidInputException {
return createExternalFunction(program, path, address, null, SourceType.USER_DEFINED);
}
Function createExternalFunction(final Program program, final String[] path,
final DataType returnType) throws DuplicateNameException, InvalidInputException {
return createExternalFunction(program, path, null, returnType, SourceType.USER_DEFINED);
}
Function createExternalFunction(final Program program, final String[] path,
final Address memoryAddress, final DataType returnType, final SourceType sourceType)
throws DuplicateNameException, InvalidInputException {
SymbolTable symbolTable = program.getSymbolTable();
ExternalManager externalManager = program.getExternalManager();
int nameIndex = path.length - 1;
Library externalLibrary;
Symbol librarySymbol = symbolTable.getLibrarySymbol(path[0]);
if (librarySymbol != null) {
externalLibrary = (Library) librarySymbol.getObject();
}
else {
externalLibrary = symbolTable.createExternalLibrary(path[0], sourceType);
}
Namespace currentNamespace = externalLibrary;
for (int i = 1; i < nameIndex; i++) {
Symbol nextNamespaceSymbol = getUniqueSymbol(program, path[i], currentNamespace);
if (nextNamespaceSymbol != null) {
currentNamespace = (Namespace) nextNamespaceSymbol.getObject();
}
else {
currentNamespace =
symbolTable.createNameSpace(currentNamespace, path[i], sourceType);
}
}
ExternalLocation externalLocation = externalManager.addExtFunction(currentNamespace,
path[nameIndex], memoryAddress, sourceType);
Function function = externalLocation.getFunction();
assertNotNull(function);
if (returnType != null) {
function.setReturnType(returnType, sourceType);
}
return function;
}
ExternalLocation createExternalLabel(final Program program, final String[] path,
final Address memoryAddress, final SourceType sourceType)
throws DuplicateNameException, InvalidInputException {
SymbolTable symbolTable = program.getSymbolTable();
ExternalManager externalManager = program.getExternalManager();
int nameIndex = path.length - 1;
Library externalLibrary;
Symbol librarySymbol = getUniqueSymbol(program, path[0], program.getGlobalNamespace());
if (librarySymbol != null) {
externalLibrary = (Library) librarySymbol.getObject();
}
else {
externalLibrary = symbolTable.createExternalLibrary(path[0], sourceType);
}
Namespace currentNamespace = externalLibrary;
for (int i = 1; i < nameIndex; i++) {
Symbol nextNamespaceSymbol = getUniqueSymbol(program, path[i], currentNamespace);
if (nextNamespaceSymbol != null) {
currentNamespace = (Namespace) nextNamespaceSymbol.getObject();
}
else {
currentNamespace =
symbolTable.createNameSpace(currentNamespace, path[i], sourceType);
}
}
ExternalLocation externalLocation = externalManager.addExtLocation(currentNamespace,
path[nameIndex], memoryAddress, sourceType);
return externalLocation;
}
Namespace createExternalNamespace(final Program program, final String[] path,
final SourceType sourceType) throws DuplicateNameException, InvalidInputException {
SymbolTable symbolTable = program.getSymbolTable();
int namespaceIndex = path.length;
Library externalLibrary;
Symbol librarySymbol = getUniqueSymbol(program, path[0], program.getGlobalNamespace());
if (librarySymbol != null) {
externalLibrary = (Library) librarySymbol.getObject();
}
else {
externalLibrary = symbolTable.createExternalLibrary(path[0], sourceType);
}
Namespace currentNamespace = externalLibrary;
for (int i = 1; i < namespaceIndex; i++) {
Symbol nextNamespaceSymbol = getUniqueSymbol(program, path[i], currentNamespace);
if (nextNamespaceSymbol != null) {
currentNamespace = (Namespace) nextNamespaceSymbol.getObject();
}
else {
currentNamespace =
symbolTable.createNameSpace(currentNamespace, path[i], sourceType);
}
}
return currentNamespace;
}
Parameter addStackParameter(Function function, String name, SourceType sourceType,
DataType dataType, int stackOffset, String comment)
throws InvalidInputException, DuplicateNameException {
Parameter parameter1 =
new ParameterImpl(name, dataType, stackOffset, function.getProgram());
parameter1.setComment(comment);
return function.addParameter(parameter1, sourceType);
}
Parameter addParameter(Function function, String name, SourceType sourceType, DataType dataType,
String comment) throws InvalidInputException, DuplicateNameException {
Parameter parameter1 = new ParameterImpl(name, dataType, function.getProgram());
parameter1.setComment(comment);
return function.addParameter(parameter1, sourceType);
}
Function getExternalFunction(Program program, String[] path) {
SymbolTable symbolTable = program.getSymbolTable();
int nameIndex = path.length - 1;
Symbol librarySymbol = symbolTable.getLibrarySymbol(path[0]);
SymbolType librarySymbolType = librarySymbol.getSymbolType();
assertEquals(SymbolType.LIBRARY, librarySymbolType);
Library externalLibrary = (Library) librarySymbol.getObject();
Namespace currentNamespace = externalLibrary;
for (int i = 1; i < nameIndex; i++) {
Symbol nextNamespaceSymbol = getUniqueSymbol(program, path[i], currentNamespace);
currentNamespace = (Namespace) nextNamespaceSymbol.getObject();
}
Symbol functionSymbol = getUniqueSymbol(program, path[nameIndex], currentNamespace);
if (functionSymbol == null) {
return null;
}
SymbolType functionSymbolType = functionSymbol.getSymbolType();
assertEquals(SymbolType.FUNCTION, functionSymbolType);
Function function = (Function) functionSymbol.getObject();
return function;
}
ExternalLocation getExternalLocation(Program program, String[] path) {
int nameIndex = path.length - 1;
Namespace namespace = getExternalNamespace(program, path, path.length - 1);
List<Symbol> symbols = program.getSymbolTable().getSymbols(path[nameIndex], namespace);
if (symbols.size() != 1) {
return null;
}
ExternalManager externalManager = program.getExternalManager();
return externalManager.getExternalLocation(symbols.get(0));
}
Namespace getExternalNamespace(Program program, String[] path) {
return getExternalNamespace(program, path, path.length);
}
Namespace getExternalNamespace(Program program, String[] path, int pathLength) {
SymbolTable symbolTable = program.getSymbolTable();
Symbol librarySymbol = symbolTable.getLibrarySymbol(path[0]);
SymbolType librarySymbolType = librarySymbol.getSymbolType();
assertEquals(SymbolType.LIBRARY, librarySymbolType);
Library externalLibrary = (Library) librarySymbol.getObject();
Namespace currentNamespace = externalLibrary;
for (int i = 1; i < pathLength; i++) {
currentNamespace = findExternalNamespaceSymbol(symbolTable, path[i], currentNamespace);
if (currentNamespace == null) {
return null;
}
}
return currentNamespace;
}
private Namespace findExternalNamespaceSymbol(SymbolTable symbolTable, String name,
Namespace currentNamespace) {
List<Symbol> symbols = symbolTable.getSymbols(name, currentNamespace);
for (Symbol symbol : symbols) {
Object object = symbol.getObject();
if (object instanceof Namespace) {
Namespace namespace = (Namespace) object;
if (namespace.isExternal()) {
return namespace;
}
}
}
return null;
}
}
| apache-2.0 |
cloudfoundry/cf-java-client | cloudfoundry-util/src/main/java/org/cloudfoundry/util/tuple/Consumer8.java | 1806 | /*
* Copyright 2013-2021 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.cloudfoundry.util.tuple;
/**
* An operation that accepts eight input arguments and returns no result
*
* @param <T1> The type of the first input to the operation
* @param <T2> The type of the second input to the operation
* @param <T3> The type of the third input to the operation
* @param <T4> The type of the fourth input to the operation
* @param <T5> The type of the fifth input to the operation
* @param <T6> The type of the sixth input to the operation
* @param <T7> The type of the seventh input to the operation
* @param <T8> The type of the eighth input to the operation
*/
@FunctionalInterface
public interface Consumer8<T1, T2, T3, T4, T5, T6, T7, T8> {
/**
* Performs this operation on the given arguments
*
* @param t1 the first input argument
* @param t2 the second input argument
* @param t3 the third input argument
* @param t4 the fourth input argument
* @param t5 the fifth input argument
* @param t6 the sixth input argument
* @param t7 the seventh input argument
* @param t8 the eighth input argument
*/
void accept(T1 t1, T2 t2, T3 t3, T4 t4, T5 t5, T6 t6, T7 t7, T8 t8);
}
| apache-2.0 |
googleinterns/noms | src/main/java/com/google/sps/servlets/PostDataServlet.java | 3724 | // Copyright 2019 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package com.google.sps.servlets;
import com.google.appengine.api.datastore.DatastoreService;
import com.google.appengine.api.datastore.DatastoreServiceFactory;
import com.google.appengine.api.datastore.Entity;
import com.google.appengine.api.datastore.EntityNotFoundException;
import com.google.appengine.api.datastore.Key;
import com.google.appengine.api.datastore.KeyFactory;
import com.google.appengine.api.datastore.PreparedQuery;
import com.google.appengine.api.datastore.Query;
import com.google.appengine.api.datastore.Query.Filter;
import com.google.appengine.api.datastore.Query.FilterPredicate;
import com.google.appengine.api.datastore.Query.FilterOperator;
import com.google.appengine.api.datastore.Query.SortDirection;
import com.google.sps.api.GmailConfiguration;
import com.google.sps.data.Post;
import com.google.gson.Gson;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/* Servlet that stores and retrieves posts. */
@WebServlet("/postData")
public class PostDataServlet extends HttpServlet {
public static final DatastoreService datastore = DatastoreServiceFactory.getDatastoreService();
public static final String ENTITY_KIND = "Post";
/* Convert an ArrayList of Post objects to JSON. */
private String listToJson(ArrayList<Post> alist) {
Gson gson = new Gson();
String json = gson.toJson(alist);
return json;
}
@Override
public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException {
String collegeId = request.getParameter("collegeId");
// Queries Datastore with the college ID and receives posts such that the soonest events are shown first.
Filter collegeIdFilter = new FilterPredicate("collegeId", FilterOperator.EQUAL, collegeId);
Query query = new Query(ENTITY_KIND).setFilter(collegeIdFilter).addSort("timeSort", SortDirection.ASCENDING);
PreparedQuery results = datastore.prepare(query);
ArrayList<Post> posts = Post.queryToPosts(results, datastore);
// Prepares the relevant posts in JSON.
String json = listToJson(posts);
response.setContentType("application/json");
response.getWriter().println(json);
}
/* On the POST command, serializes the request information into Post objects,
* stores the post as entity in Datastore.
*/
@Override
public void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException {
String collegeId = request.getParameter("collegeId");
Post newPost = new Post();
newPost.requestToPost(request);
if (newPost.valid) {
Entity collegeEntity = new Entity("College", collegeId);
datastore.put(collegeEntity);
Entity newPostEntity = newPost.postToEntity(ENTITY_KIND);
datastore.put(newPostEntity);
GmailConfiguration.notifyUsers(collegeId, newPost);
}
String redirectURL ="/find-events.html?" + "collegeid=" + collegeId;
response.sendRedirect(redirectURL);
}
}
| apache-2.0 |
dbolser-ebi/ensj-healthcheck | test/src/org/ensembl/healthcheck/test/LogFormatterTest.java | 1266 | /*
* Copyright [1999-2014] Wellcome Trust Sanger Institute and the EMBL-European Bioinformatics Institute
*
* 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.ensembl.healthcheck.test;
import java.util.logging.Level;
import java.util.logging.LogRecord;
import org.ensembl.healthcheck.util.LogFormatter;
import org.testng.Assert;
import org.testng.annotations.Test;
public class LogFormatterTest {
/** Test of format method, of class org.ensembl.healthcheck.util.LogFormatter. */
@Test
public void testFormat() {
LogFormatter lf = new LogFormatter();
LogRecord lr = new LogRecord(Level.INFO, "a test message");
String msg = lf.format(lr);
Assert.assertEquals(msg, "a test message\n", "Checking formatting");
}
}
| apache-2.0 |
googleads/authorized-buyers-marketplace-api-samples | java/src/main/java/com/google/api/services/samples/authorizedbuyers/marketplace/Utils.java | 34419 | /*
* Copyright (c) 2021 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.api.services.samples.authorizedbuyers.marketplace;
import com.google.api.client.googleapis.javanet.GoogleNetHttpTransport;
import com.google.api.client.http.HttpRequestInitializer;
import com.google.api.client.http.HttpTransport;
import com.google.api.client.json.JsonFactory;
import com.google.api.client.json.gson.GsonFactory;
import com.google.api.services.authorizedbuyersmarketplace.v1.AuthorizedBuyersMarketplace;
import com.google.api.services.authorizedbuyersmarketplace.v1.AuthorizedBuyersMarketplaceScopes;
import com.google.api.services.authorizedbuyersmarketplace.v1.model.*;
import com.google.auth.http.HttpCredentialsAdapter;
import com.google.auth.oauth2.GoogleCredentials;
import com.google.auth.oauth2.ServiceAccountCredentials;
import java.io.FileInputStream;
import java.io.IOException;
import java.security.GeneralSecurityException;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import org.joda.time.format.DateTimeFormat;
import org.joda.time.format.DateTimeFormatter;
/** Utilities used by the Authorized Buyers Marketplace API samples. */
public class Utils {
/**
* Specify the name of your application. If the application name is {@code null} or blank, the
* application will log a warning. Suggested format is "MyCompany-ProductName/1.0".
*/
private static final String APPLICATION_NAME = "";
/** Full path to JSON Key file - include file name */
private static final java.io.File JSON_FILE = new java.io.File("INSERT_PATH_TO_JSON_FILE");
/**
* Global instance of a DateTimeFormatter used to parse LocalDate instances and convert them to
* String.
*/
private static final DateTimeFormatter dateFormatter = DateTimeFormat.forPattern("Y-M-d");
/** Global instance of the JSON factory. */
private static final JsonFactory JSON_FACTORY = GsonFactory.getDefaultInstance();
/**
* Global instance of the maximum page size, which will be the default page size for samples with
* pagination.
*/
private static final Integer MAXIMUM_PAGE_SIZE = 50;
/**
* Authorizes the application to access the user's protected data.
*
* @throws IOException if the {@code JSON_FILE} can not be read.
* @return An instantiated GoogleCredentials instance.
*/
private static GoogleCredentials authorize() throws IOException {
GoogleCredentials credentials;
try (FileInputStream serviceAccountStream = new FileInputStream((JSON_FILE))) {
Set<String> scopes = new HashSet<>(AuthorizedBuyersMarketplaceScopes.all());
credentials = ServiceAccountCredentials.fromStream(serviceAccountStream).createScoped(scopes);
}
return credentials;
}
/** Helper method to produce an appropriate indent for the given indentLevel. */
private static String getIndent(int indentLevel) {
StringBuilder builder = new StringBuilder();
for (int i = 0; i < indentLevel; i++) {
builder.append('\t');
}
return builder.toString();
}
/** Helper method to produce a prefix for a printed field. */
private static String getPrefix(int indentLevel) {
StringBuilder builder = new StringBuilder();
builder.append(getIndent(indentLevel));
// Root-level messages will be denoted with an asterisk. Otherwise, fields will be denoted with
// a hyphen.
char bullet = (indentLevel == 0) ? '*' : '-';
return builder.append(bullet).toString();
}
/** Helper method to print a {@code String} field. */
private static void printField(String fieldDesc, String field, int indentLevel) {
if (field == null) {
return;
}
String prefix = getPrefix(indentLevel);
System.out.printf("%s%s: %s%n", prefix, fieldDesc, field);
}
/** Helper method to print a {@code String} field. */
private static void printField(
String fieldDesc, String field, String defaultValue, int indentLevel) {
field = (field != null) ? field : defaultValue;
String prefix = getPrefix(indentLevel);
System.out.printf("%s%s: %s%n", prefix, fieldDesc, field);
}
/** Helper method to print an {@code Integer} field. */
private static void printField(String fieldDesc, Integer field, int indentLevel) {
if (field == null) {
return;
}
String prefix = getPrefix(indentLevel);
System.out.printf("%s%s: %d%n", prefix, fieldDesc, field);
}
/** Helper method to print an {@code Integer} field. */
private static void printField(
String fieldDesc, Integer field, Integer defaultValue, int indentLevel) {
field = (field != null) ? field : defaultValue;
String prefix = getPrefix(indentLevel);
System.out.printf("%s%s: %d%n", prefix, fieldDesc, field);
}
/** Helper method to print a {@code Long} field. */
private static void printField(String fieldDesc, Long field, int indentLevel) {
if (field == null) {
return;
}
String prefix = getPrefix(indentLevel);
System.out.printf("%s%s: %d%n", prefix, fieldDesc, field);
}
/** Helper method to print a {@code Long} field. */
private static void printField(String fieldDesc, Long field, Long defaultValue, int indentLevel) {
field = (field != null) ? field : defaultValue;
String prefix = getPrefix(indentLevel);
System.out.printf("%s%s: %d%n", prefix, fieldDesc, field);
}
/** Helper method to print a {@code Double} field. */
private static void printField(String fieldDesc, Double field, int indentLevel) {
if (field == null) {
return;
}
String prefix = getPrefix(indentLevel);
System.out.printf("%s%s: %f%n", prefix, fieldDesc, field);
}
/** Helper method to print a {@code Double} field. */
private static void printField(
String fieldDesc, Double field, Double defaultValue, int indentLevel) {
field = (field != null) ? field : defaultValue;
String prefix = getPrefix(indentLevel);
System.out.printf("%s%s: %f%n", prefix, fieldDesc, field);
}
/** Helper method to print a {@code Boolean} field. */
private static void printField(String fieldDesc, Boolean field, int indentLevel) {
if (field == null) {
return;
}
String prefix = getPrefix(indentLevel);
System.out.printf("%s%s: %b%n", prefix, fieldDesc, field);
}
/** Helper method to print a {@code Boolean} field. */
private static void printField(
String fieldDesc, Boolean field, Boolean defaultValue, int indentLevel) {
field = (field != null) ? field : defaultValue;
String prefix = getPrefix(indentLevel);
System.out.printf("%s%s: %b%n", prefix, fieldDesc, field);
}
private static void printField(String fieldDesc, DealPausingInfo field, int indentLevel) {
if (field == null) {
return;
}
System.out.printf("%s%s:%n", getPrefix(indentLevel), fieldDesc);
indentLevel++;
printField("Pausing consented", field.getPausingConsented(), indentLevel);
printField("Pause role", field.getPauseRole(), indentLevel);
printField("Pause reason", field.getPauseReason(), indentLevel);
}
private static void printField(String fieldDesc, RtbMetrics field, int indentLevel) {
if (field == null) {
return;
}
System.out.printf("%s%s:%n", getPrefix(indentLevel), fieldDesc);
indentLevel++;
printField("Bid requests over last 7 days", field.getBidRequests7Days(), 0L, indentLevel);
printField("Bids over last 7 days", field.getBids7Days(), 0L, indentLevel);
printField("Ad impressions over last 7 days", field.getAdImpressions7Days(), 0L, indentLevel);
printField("Bid rate over last 7 days", field.getBidRate7Days(), 0.0, indentLevel);
printField(
"Filtered bid rate over last 7 days", field.getFilteredBidRate7Days(), 0.0, indentLevel);
printField(
"Must bid rate for current month", field.getMustBidRateCurrentMonth(), 0.0, indentLevel);
}
private static void printField(String fieldDesc, Money field, int indentLevel) {
if (field == null) {
return;
}
System.out.printf("%s%s:%n", getPrefix(indentLevel), fieldDesc);
indentLevel++;
printField("Currency code", field.getCurrencyCode(), indentLevel);
printField("Units", field.getUnits(), 0L, indentLevel);
printField("Nanos", field.getNanos(), 0, indentLevel);
}
private static void printField(String fieldDesc, TimeZone field, int indentLevel) {
if (field == null) {
return;
}
System.out.printf("%s%s:%n", getPrefix(indentLevel), fieldDesc);
indentLevel++;
printField("ID", field.getId(), indentLevel);
printField("Version", field.getVersion(), indentLevel);
}
private static void printField(String fieldDesc, CriteriaTargeting field, int indentLevel) {
if (field == null) {
return;
}
System.out.printf("%s%s:%n", getPrefix(indentLevel), fieldDesc);
indentLevel++;
printLongList("Targeted Criteria IDs", field.getTargetedCriteriaIds(), indentLevel);
printLongList("Excluded Criteria IDs", field.getTargetedCriteriaIds(), indentLevel);
}
private static void printField(String fieldDesc, AdSize field, int indentLevel) {
if (field == null) {
return;
}
System.out.printf("%s%s:%n", getPrefix(indentLevel), fieldDesc);
indentLevel++;
printField("Width", field.getWidth(), indentLevel);
printField("Height", field.getHeight(), indentLevel);
}
private static void printField(String fieldDesc, InventorySizeTargeting field, int indentLevel) {
if (field == null) {
return;
}
System.out.printf("%s%s:%n", getPrefix(indentLevel), fieldDesc);
indentLevel++;
printAdSizeList("Targeted inventory sizes", field.getTargetedInventorySizes(), indentLevel);
printAdSizeList("Excluded inventory sizes", field.getExcludedInventorySizes(), indentLevel);
}
private static void printField(
String fieldDesc, OperatingSystemTargeting field, int indentLevel) {
if (field == null) {
return;
}
System.out.printf("%s%s:%n", getPrefix(indentLevel), fieldDesc);
indentLevel++;
printField("Operating system criteria", field.getOperatingSystemCriteria(), indentLevel);
printField(
"Operating system version criteria",
field.getOperatingSystemVersionCriteria(),
indentLevel);
}
private static void printField(String fieldDesc, TechnologyTargeting field, int indentLevel) {
if (field == null) {
return;
}
System.out.printf("%s%s:%n", getPrefix(indentLevel), fieldDesc);
indentLevel++;
printField("Device category targeting", field.getDeviceCategoryTargeting(), indentLevel);
printField("Device capability targeting", field.getDeviceCapabilityTargeting(), indentLevel);
printField("Operating system targeting", field.getOperatingSystemTargeting(), indentLevel);
}
private static void printField(String fieldDesc, UriTargeting field, int indentLevel) {
if (field == null) {
return;
}
System.out.printf("%s%s:%n", getPrefix(indentLevel), fieldDesc);
indentLevel++;
printStringList("Targeted URIs", field.getTargetedUris(), indentLevel);
printStringList("Excluded URIs", field.getExcludedUris(), indentLevel);
}
private static void printField(
String fieldDesc, FirstPartyMobileApplicationTargeting field, int indentLevel) {
if (field == null) {
return;
}
System.out.printf("%s%s:%n", getPrefix(indentLevel), fieldDesc);
indentLevel++;
printStringList("Targeted App IDs", field.getTargetedAppIds(), indentLevel);
printStringList("Excluded App IDs", field.getExcludedAppIds(), indentLevel);
}
private static void printField(
String fieldDesc, MobileApplicationTargeting field, int indentLevel) {
if (field == null) {
return;
}
System.out.printf("%s%s:%n", getPrefix(indentLevel), fieldDesc);
indentLevel++;
printField(
"First-party mobile application targeting", field.getFirstPartyTargeting(), indentLevel);
}
private static void printField(String fieldDesc, PlacementTargeting field, int indentLevel) {
if (field == null) {
return;
}
System.out.printf("%s%s:%n", getPrefix(indentLevel), fieldDesc);
indentLevel++;
printField("URI targeting", field.getUriTargeting(), indentLevel);
printField("Mobile application targeting", field.getMobileApplicationTargeting(), indentLevel);
}
private static void printField(String fieldDesc, TimeOfDay field, int indentLevel) {
if (field == null) {
return;
}
System.out.printf("%s%s:%n", getPrefix(indentLevel), fieldDesc);
indentLevel++;
printField("Hours", field.getHours(), indentLevel);
printField("Minutes", field.getMinutes(), indentLevel);
printField("Seconds", field.getSeconds(), indentLevel);
printField("Nanos", field.getNanos(), indentLevel);
}
private static void printField(String fieldDesc, DayPart field, int indentLevel) {
if (field == null) {
return;
}
System.out.printf("%s%s:%n", getPrefix(indentLevel), fieldDesc);
indentLevel++;
printField("Day of week", field.getDayOfWeek(), indentLevel);
printField("Start time", field.getStartTime(), indentLevel);
printField("End time", field.getEndTime(), indentLevel);
}
private static void printField(String fieldDesc, DayPartTargeting field, int indentLevel) {
if (field == null) {
return;
}
System.out.printf("%s%s:%n", getPrefix(indentLevel), fieldDesc);
indentLevel++;
printDayPartList("Day parts", field.getDayParts(), indentLevel);
printField("Time zone type", field.getTimeZoneType(), indentLevel);
}
private static void printField(String fieldDesc, VideoTargeting field, int indentLevel) {
if (field == null) {
return;
}
System.out.printf("%s%s:%n", getPrefix(indentLevel), fieldDesc);
indentLevel++;
printStringList("Targeted position types", field.getTargetedPositionTypes(), indentLevel);
printStringList("Excluded position types", field.getExcludedPositionTypes(), indentLevel);
}
private static void printField(String fieldDesc, MarketplaceTargeting field, int indentLevel) {
if (field == null) {
return;
}
System.out.printf("%s%s:%n", getPrefix(indentLevel), fieldDesc);
indentLevel++;
printField("Geo targeting", field.getGeoTargeting(), indentLevel);
printField("Inventory size targeting", field.getInventorySizeTargeting(), indentLevel);
printField("Technology targeting", field.getTechnologyTargeting(), indentLevel);
printField("Placement targeting", field.getPlacementTargeting(), indentLevel);
printField("Video targeting", field.getVideoTargeting(), indentLevel);
printField("User list targeting", field.getUserListTargeting(), indentLevel);
printField("Day part targeting", field.getDaypartTargeting(), indentLevel);
}
private static void printField(String fieldDesc, CreativeRequirements field, int indentLevel) {
if (field == null) {
return;
}
System.out.printf("%s%s:%n", getPrefix(indentLevel), fieldDesc);
indentLevel++;
printField("Creative preapproval policy", field.getCreativePreApprovalPolicy(), indentLevel);
printField(
"Creative safeframe compatibility", field.getCreativeSafeFrameCompatibility(), indentLevel);
printField("Programmatic creative source", field.getProgrammaticCreativeSource(), indentLevel);
}
private static void printField(String fieldDesc, FrequencyCap field, int indentLevel) {
if (field == null) {
return;
}
System.out.printf("%s%s:%n", getPrefix(indentLevel), fieldDesc);
indentLevel++;
printField("Max impressions", field.getMaxImpressions(), indentLevel);
printField("Time units count", field.getTimeUnitsCount(), indentLevel);
printField("Time unit type", field.getTimeUnitType(), indentLevel);
}
private static void printField(String fieldDesc, DeliveryControl field, int indentLevel) {
if (field == null) {
return;
}
System.out.printf("%s%s:%n", getPrefix(indentLevel), fieldDesc);
indentLevel++;
printField("Delivery rate type", field.getDeliveryRateType(), indentLevel);
printFrequencyCapList("Frequency caps", field.getFrequencyCap(), indentLevel);
printField("Road blocking type", field.getRoadblockingType(), indentLevel);
printField("Companion delivery type", field.getCompanionDeliveryType(), indentLevel);
printField("Creative rotation type", field.getCreativeRotationType(), indentLevel);
}
private static void printField(String fieldDesc, Price field, int indentLevel) {
if (field == null) {
return;
}
System.out.printf("%s%s:%n", getPrefix(indentLevel), fieldDesc);
indentLevel++;
printField("Type", field.getType(), indentLevel);
printField("Amount", field.getAmount(), indentLevel);
}
private static void printField(
String fieldDesc, ProgrammaticGuaranteedTerms field, int indentLevel) {
if (field == null) {
return;
}
System.out.printf("%s%s:%n", getPrefix(indentLevel), fieldDesc);
indentLevel++;
printField("Guaranteed looks", field.getGuaranteedLooks(), indentLevel);
printField("Fixed price", field.getFixedPrice(), indentLevel);
printField("Minimum daily looks", field.getMinimumDailyLooks(), indentLevel);
printField("Reservation type", field.getReservationType(), indentLevel);
printField("Impression cap", field.getImpressionCap(), indentLevel);
printField("Percent share of voice", field.getPercentShareOfVoice(), indentLevel);
}
private static void printField(String fieldDesc, PreferredDealTerms field, int indentLevel) {
if (field == null) {
return;
}
System.out.printf("%s%s:%n", getPrefix(indentLevel), fieldDesc);
indentLevel++;
printField("Fixed price", field.getFixedPrice(), indentLevel);
}
private static void printField(String fieldDesc, PrivateAuctionTerms field, int indentLevel) {
if (field == null) {
return;
}
System.out.printf("%s%s:%n", getPrefix(indentLevel), fieldDesc);
indentLevel++;
printField("Floor price", field.getFloorPrice(), indentLevel);
printField("Open auction allowed", field.getOpenAuctionAllowed(), indentLevel);
}
private static void printField(String fieldDesc, PrivateData field, int indentLevel) {
if (field == null) {
return;
}
System.out.printf("%s%s:%n", getPrefix(indentLevel), fieldDesc);
indentLevel++;
printField("Reference ID", field.getReferenceId(), indentLevel);
}
private static void printField(String fieldDesc, Deal field, int indentLevel) {
if (field == null) {
return;
}
System.out.printf("%s%s:%n", getPrefix(indentLevel), fieldDesc);
indentLevel++;
printField("Deal name", field.getName(), indentLevel);
printField("Create time", field.getCreateTime(), indentLevel);
printField("Update time", field.getUpdateTime(), indentLevel);
printField("Proposal revision", field.getProposalRevision(), indentLevel);
printField("Display name", field.getDisplayName(), indentLevel);
printField("Billed buyer", field.getBilledBuyer(), indentLevel);
printField("Proposal revision", field.getProposalRevision(), indentLevel);
printField("Publisher profile", field.getPublisherProfile(), indentLevel);
printField("Deal type", field.getDealType(), indentLevel);
printField("Estimated gross spend", field.getEstimatedGrossSpend(), indentLevel);
printField("Seller time zone", field.getSellerTimeZone(), indentLevel);
printField("Description", field.getDescription(), indentLevel);
printField("Flight start time", field.getFlightStartTime(), indentLevel);
printField("Flight end time", field.getFlightEndTime(), indentLevel);
printField("Marketplace targeting", field.getTargeting(), indentLevel);
printField("Creative requirements", field.getCreativeRequirements(), indentLevel);
printField("Delivery control", field.getDeliveryControl(), indentLevel);
printField("Buyer", field.getBuyer(), indentLevel);
printField("Client", field.getClient(), indentLevel);
printField(
"Programmatic guaranteed terms", field.getProgrammaticGuaranteedTerms(), indentLevel);
printField("Preferred deal terms", field.getPreferredDealTerms(), indentLevel);
printField("Private auction terms", field.getPrivateAuctionTerms(), indentLevel);
}
private static void printField(String fieldDesc, Contact field, int indentLevel) {
if (field == null) {
return;
}
System.out.printf("%s%s:%n", getPrefix(indentLevel), fieldDesc);
indentLevel++;
printField("Email", field.getEmail(), indentLevel);
printField("Display name", field.getDisplayName(), indentLevel);
}
private static void printField(String fieldDesc, Note field, int indentLevel) {
if (field == null) {
return;
}
System.out.printf("%s%s:%n", getPrefix(indentLevel), fieldDesc);
indentLevel++;
printField("Create time", field.getCreateTime(), indentLevel);
printField("Creator role", field.getCreatorRole(), indentLevel);
printField("Note value", field.getNote(), indentLevel);
}
private static void printField(
String fieldDesc, PublisherProfileMobileApplication field, int indentLevel) {
if (field == null) {
return;
}
System.out.printf("%s%s:%n", getPrefix(indentLevel), fieldDesc);
indentLevel++;
printField("Name", field.getName(), indentLevel);
printField("App Store", field.getAppStore(), indentLevel);
printField("External App ID", field.getExternalAppId(), indentLevel);
}
/** Helper method to print a {@code List} of {@code String} values. */
private static void printStringList(String fieldDesc, List<String> values, int indentLevel) {
if (values == null) {
return;
}
System.out.printf("%s%s:%n", getPrefix(indentLevel), fieldDesc);
indentLevel++;
for (String item : values) {
System.out.printf("%s%s%n", getPrefix(indentLevel), item);
}
}
/** Helper method to print a {@code List} of {@code Integer} values. */
private static void printIntegerList(String fieldDesc, List<Integer> values, int indentLevel) {
if (values == null) {
return;
}
System.out.printf("%s%s:%n", getPrefix(indentLevel), fieldDesc);
indentLevel++;
for (Integer item : values) {
System.out.printf("%s%d%n", getPrefix(indentLevel), item);
}
}
/** Helper method to print a {@code List} of {@code Long} values. */
private static void printLongList(String fieldDesc, List<Long> values, int indentLevel) {
if (values == null) {
return;
}
System.out.printf("%s%s:%n", getPrefix(indentLevel), fieldDesc);
indentLevel++;
for (Long item : values) {
System.out.printf("%s%d%n", getPrefix(indentLevel), item);
}
}
/** Helper method to print a {@code List} of {@code AdSize} values. */
private static void printAdSizeList(String fieldDesc, List<AdSize> values, int indentLevel) {
if (values == null) {
return;
}
System.out.printf("%s%s:%n", getPrefix(indentLevel), fieldDesc);
indentLevel++;
for (AdSize adSize : values) {
printField("AdSize", adSize, indentLevel);
}
}
/** Helper method to print a {@code List} of {@code Contact} values. */
private static void printContactList(String fieldDesc, List<Contact> values, int indentLevel) {
if (values == null) {
return;
}
System.out.printf("%s%s:%n", getPrefix(indentLevel), fieldDesc);
indentLevel++;
for (Contact contact : values) {
printField("Contact", contact, indentLevel);
}
}
/** Helper method to print a {@code List} of {@code DayPart} values. */
private static void printDayPartList(String fieldDesc, List<DayPart> values, int indentLevel) {
if (values == null) {
return;
}
System.out.printf("%s%s:%n", getPrefix(indentLevel), fieldDesc);
indentLevel++;
for (DayPart dayPart : values) {
printField("Day part", dayPart, indentLevel);
}
}
/** Helper method to print a {@code List} of {@code FrequencyCap} values. */
private static void printFrequencyCapList(
String fieldDesc, List<FrequencyCap> values, int indentLevel) {
if (values == null) {
return;
}
System.out.printf("%s%s:%n", getPrefix(indentLevel), fieldDesc);
indentLevel++;
for (FrequencyCap frequencyCap : values) {
printField("Frequency cap", frequencyCap, indentLevel);
}
}
/** Helper method to print a {@code List} of {@code Note} values. */
private static void printNoteList(String fieldDesc, List<Note> values, int indentLevel) {
if (values == null) {
return;
}
System.out.printf("%s%s:%n", getPrefix(indentLevel), fieldDesc);
indentLevel++;
for (Note note : values) {
printField("Note", note, indentLevel);
}
}
/** Helper method to print a {@code List} of {@code PublisherProfileMobileApplication} values. */
private static void printListOfPubProfileMobileApps(
String fieldDesc, List<PublisherProfileMobileApplication> apps, int indentLevel) {
if (apps == null) {
return;
}
System.out.printf("%s%s:%n", getPrefix(indentLevel), fieldDesc);
indentLevel++;
for (PublisherProfileMobileApplication app : apps) {
printField("Publisher profile mobile application", app, indentLevel);
}
}
/**
* Retrieve a {@code DateTimeFormatter} instance used to parse and serialize {@code LocalDate}.
*
* @return An initialized {@code DateTimeFormatter} instance.
*/
public static DateTimeFormatter getDateTimeFormatterForLocalDate() {
return dateFormatter;
}
/**
* Retrieve the default maximum page size.
*
* @return An Integer representing the default maximum page size for samples with pagination.
*/
public static Integer getMaximumPageSize() {
return MAXIMUM_PAGE_SIZE;
}
/**
* Performs all necessary setup steps for running requests against the Marketplace API.
*
* @return An initialized AuthorizedBuyersMarketplace service object.
*/
public static AuthorizedBuyersMarketplace getMarketplaceClient()
throws IOException, GeneralSecurityException {
GoogleCredentials credentials = authorize();
HttpRequestInitializer requestInitializer = new HttpCredentialsAdapter(credentials);
HttpTransport httpTransport = GoogleNetHttpTransport.newTrustedTransport();
return new AuthorizedBuyersMarketplace.Builder(httpTransport, JSON_FACTORY, requestInitializer)
.setApplicationName(APPLICATION_NAME)
.build();
}
/** Prints a {@code AuctionPackage} instance in a human-readable format. */
public static void printAuctionPackage(AuctionPackage auctionPackage) {
int indentLevel = 0;
printField("Auction package name", auctionPackage.getName(), indentLevel);
indentLevel++;
printField("Creator", auctionPackage.getCreator(), indentLevel);
printField("Display name", auctionPackage.getDisplayName(), indentLevel);
printField("Description", auctionPackage.getDescription(), indentLevel);
printField("Create time", auctionPackage.getCreateTime(), indentLevel);
printField("Update time", auctionPackage.getUpdateTime(), indentLevel);
printStringList("Subscribed clients", auctionPackage.getSubscribedClients(), indentLevel);
}
/** Prints a {@code Client} instance in a human-readable format. */
public static void printClient(Client client) {
int indentLevel = 0;
printField("Client name", client.getName(), indentLevel);
indentLevel++;
printField("Display name", client.getDisplayName(), indentLevel);
printField("Partner client ID", client.getPartnerClientId(), indentLevel);
printField("Role", client.getRole(), indentLevel);
printField("State", client.getState(), indentLevel);
printField("Seller visible", client.getSellerVisible(), indentLevel);
}
/** Prints a {@code ClientUser} instance in a human-readable format. */
public static void printClientUser(ClientUser clientUser) {
int indentLevel = 0;
printField("Client user name", clientUser.getName(), indentLevel);
indentLevel++;
printField("State", clientUser.getState(), indentLevel);
printField("Email", clientUser.getEmail(), indentLevel);
}
/** Prints a {@code Deal} instance in a human-readable format. */
public static void printDeal(Deal deal) {
int indentLevel = 0;
printField("Deal name", deal.getName(), indentLevel);
indentLevel++;
printField("Create time", deal.getCreateTime(), indentLevel);
printField("Update time", deal.getUpdateTime(), indentLevel);
printField("Proposal revision", deal.getProposalRevision(), indentLevel);
printField("Display name", deal.getDisplayName(), indentLevel);
printField("Billed buyer", deal.getBilledBuyer(), indentLevel);
printField("Proposal revision", deal.getProposalRevision(), indentLevel);
printField("Publisher profile", deal.getPublisherProfile(), indentLevel);
printField("Deal type", deal.getDealType(), indentLevel);
printField("Estimated gross spend", deal.getEstimatedGrossSpend(), indentLevel);
printField("Seller time zone", deal.getSellerTimeZone(), indentLevel);
printField("Description", deal.getDescription(), indentLevel);
printField("Flight start time", deal.getFlightStartTime(), indentLevel);
printField("Flight end time", deal.getFlightEndTime(), indentLevel);
printField("Marketplace targeting", deal.getTargeting(), indentLevel);
printField("Creative requirements", deal.getCreativeRequirements(), indentLevel);
printField("Delivery control", deal.getDeliveryControl(), indentLevel);
printField("Buyer", deal.getBuyer(), indentLevel);
printField("Client", deal.getClient(), indentLevel);
printField("Programmatic guaranteed terms", deal.getProgrammaticGuaranteedTerms(), indentLevel);
printField("Preferred deal terms", deal.getPreferredDealTerms(), indentLevel);
printField("Private auction terms", deal.getPrivateAuctionTerms(), indentLevel);
}
/** Prints a {@code Proposal} instance in a human-readable format. */
public static void printProposal(Proposal proposal) {
int indentLevel = 0;
printField("Proposal name", proposal.getName(), indentLevel);
indentLevel++;
printField("Display name", proposal.getDisplayName(), indentLevel);
printField("Update time", proposal.getUpdateTime(), indentLevel);
printField("Proposal revision", proposal.getProposalRevision(), indentLevel);
printField("Deal type", proposal.getDealType(), indentLevel);
printField("Is renegotiating", proposal.getIsRenegotiating(), indentLevel);
printField("Originator role", proposal.getOriginatorRole(), indentLevel);
printField("Publisher profile", proposal.getPublisherProfile(), indentLevel);
printField("Buyer private data", proposal.getBuyerPrivateData(), indentLevel);
printField("Billed buyer", proposal.getBilledBuyer(), indentLevel);
printContactList("Seller contacts", proposal.getSellerContacts(), indentLevel);
printContactList("Buyer contacts", proposal.getBuyerContacts(), indentLevel);
printField(
"Last updater or commenter role", proposal.getLastUpdaterOrCommentorRole(), indentLevel);
printField("Terms and conditions", proposal.getTermsAndConditions(), indentLevel);
printField("Pausing consented", proposal.getPausingConsented(), indentLevel);
printNoteList("Notes", proposal.getNotes(), indentLevel);
printField("Buyer", proposal.getBuyer(), indentLevel);
printField("Client", proposal.getClient(), indentLevel);
}
/** Prints a {@code PublisherProfile} instance in a human-readable format. */
public static void printPublisherProfile(PublisherProfile publisherProfile) {
int indentLevel = 0;
printField("Publisher profile name", publisherProfile.getName(), indentLevel);
indentLevel++;
printField("Display name", publisherProfile.getDisplayName(), indentLevel);
printStringList("Domains", publisherProfile.getDomains(), indentLevel);
printListOfPubProfileMobileApps("Mobile apps", publisherProfile.getMobileApps(), indentLevel);
printField("Logo URL", publisherProfile.getLogoUrl(), indentLevel);
printField("Direct deals contact", publisherProfile.getDirectDealsContact(), indentLevel);
printField(
"Programmatic deals contact", publisherProfile.getProgrammaticDealsContact(), indentLevel);
printField("Media kit URL", publisherProfile.getMediaKitUrl(), indentLevel);
printField("Sample page URL", publisherProfile.getSamplePageUrl(), indentLevel);
printField("Overview", publisherProfile.getOverview(), indentLevel);
printField("Pitch statement", publisherProfile.getPitchStatement(), indentLevel);
printStringList("Top headlines", publisherProfile.getTopHeadlines(), indentLevel);
printField("Audience description", publisherProfile.getAudienceDescription(), indentLevel);
printField("Is parent", publisherProfile.getIsParent(), indentLevel);
printField("Publisher code", publisherProfile.getPublisherCode(), indentLevel);
}
/** Prints a {@code FinalizedDeal} instance in a human-readable format. */
public static void printFinalizedDeal(FinalizedDeal finalizedDeal) {
int indentLevel = 0;
printField("Finalized deal name", finalizedDeal.getName(), indentLevel);
indentLevel++;
printField("Deal serving status", finalizedDeal.getDealServingStatus(), indentLevel);
printField("Deal pausing info", finalizedDeal.getDealPausingInfo(), indentLevel);
printField("RTB metrics", finalizedDeal.getRtbMetrics(), indentLevel);
printField("Ready to serve", finalizedDeal.getReadyToServe(), indentLevel);
printField("Deal", finalizedDeal.getDeal(), indentLevel);
}
}
| apache-2.0 |
yangcy2016/saasovation-all | identityacess/src/main/java/com/saasovation/identityaccess/domain/model/IdentifiedValueObject.java | 183 | package com.saasovation.identityaccess.domain.model;
public abstract class IdentifiedValueObject extends IdentifiedDomainObject{
public IdentifiedValueObject() {
super();
}
}
| apache-2.0 |
tuwiendsg/MELA | MELA-Core/MELA-DataService/src/main/java/at/ac/tuwien/dsg/mela/dataservice/api/DataService.java | 13270 | /**
* Copyright 2013 Technische Universitat Wien (TUW), Distributed Systems Group
* E184
*
* This work was partially supported by the European Commission in terms of the
* CELAR FP7 project (FP7-ICT-2011-8 \#317790)
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package at.ac.tuwien.dsg.mela.dataservice.api;
import at.ac.tuwien.dsg.mela.common.configuration.metricComposition.CompositionRulesConfiguration;
import at.ac.tuwien.dsg.mela.common.monitoringConcepts.Action;
import at.ac.tuwien.dsg.mela.common.monitoringConcepts.Metric;
import at.ac.tuwien.dsg.mela.common.monitoringConcepts.MonitoredElement;
import at.ac.tuwien.dsg.mela.common.monitoringConcepts.MonitoredElementMonitoringSnapshot;
import at.ac.tuwien.dsg.mela.common.requirements.Requirements;
import com.wordnik.swagger.annotations.Api;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import javax.ws.rs.*;
import javax.ws.rs.ext.Provider;
import javax.xml.bind.JAXBContext;
import at.ac.tuwien.dsg.mela.common.monitoringConcepts.MonitoredElementMonitoringSnapshots;
import at.ac.tuwien.dsg.mela.dataservice.DataCollectionService;
import java.io.StringReader;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import javax.ws.rs.core.Response;
import org.slf4j.LoggerFactory;
/**
* Author: Daniel Moldovan E-Mail: d.moldovan@dsg.tuwien.ac.at *
*/
@Service
@Provider
@Path("/")
@Api(value = "/", description = "The ElasticityAnalysisService is the entry point for all elasticity related monitoring data")
public class DataService {
static final org.slf4j.Logger log = LoggerFactory.getLogger(DataService.class);
@Autowired
private DataCollectionService collectionService;
public DataService() {
}
/**
* @param compositionRulesConfiguration the metric composition rules, both
* the HISTORICAL and MULTI_LEVEL rules
*/
@PUT
@Path("/{serviceID}/metricscompositionrules")
@Consumes("application/xml")
public void putCompositionRules(CompositionRulesConfiguration compositionRulesConfiguration, @PathParam("serviceID") String serviceID) {
if (compositionRulesConfiguration != null) {
compositionRulesConfiguration.setTargetServiceID(serviceID);
collectionService.setCompositionRulesConfiguration(serviceID, compositionRulesConfiguration);
} else {
log.warn("supplied compositionRulesConfiguration is null");
}
}
/**
* @param element the service topology to be monitored
*/
@PUT
@Path("/service")
@Consumes("application/xml")
public void putServiceDescription(MonitoredElement element) {
if (element != null) {
collectionService.addService(element);
} else {
log.warn("supplied service description is null");
}
}
/**
* @param serviceID the service to be removed
*/
@DELETE
@Path("/{serviceID}")
@Consumes("application/xml")
public void removeServiceDescription(@PathParam("serviceID") String serviceID) {
collectionService.removeService(serviceID);
}
/**
* @param element refreshes the VM's attached to each Service Unit. For a
* structural update, use "PUT servicedescription", as in such a case the
* elasticity signature needs to be recomputed
*/
@POST
@Path("/{serviceID}/structure")
@Consumes("application/xml")
public void updateServiceDescription(MonitoredElement element) {
if (element != null) {
collectionService.updateServiceConfiguration(element);
} else {
log.warn("supplied service description is null");
}
}
/**
* @param requirements service behavior limits on metrics directly measured
* or obtained from metric composition
*/
@PUT
@Path("/{serviceID}/requirements")
@Consumes("application/xml")
public void putServiceRequirements(Requirements requirements, @PathParam("serviceID") String serviceID) {
if (requirements != null) {
requirements.setTargetServiceID(serviceID);
collectionService.addRequirements(serviceID, requirements);
} else {
log.warn("supplied service requirements are null");
}
}
/**
* Method used to list for a particular service unit ID what are the
* available metrics that can be monitored directly
*
* @param monitoredElementID ID of the service UNIT from which to return the
* available monitored data (before composition) for the VMS belonging to
* the SERVICE UNIT example: http://localhost:8080/MELA/REST_WS/metrics
* ?serviceID=CassandraController
* @return
*/
@GET
@Path("/{serviceID}/metrics")
@Produces("application/xml")
public Collection<Metric> getAvailableMetrics(@PathParam("serviceID") String serviceID, @QueryParam("monitoredElementID") String monitoredElementID,
@QueryParam("monitoredElementLevel") String monitoredElementLevel) {
try {
JAXBContext context = JAXBContext.newInstance(MonitoredElement.class);
String monElementRepr = "<MonitoredElement id=\"" + monitoredElementID + "\" level=\"" + monitoredElementLevel + "\"/>";
MonitoredElement monitoredElement = (MonitoredElement) context.createUnmarshaller().unmarshal(new StringReader(monElementRepr));
return collectionService.getAvailableMetricsForMonitoredElement(serviceID, monitoredElement);
} catch (Exception ex) {
log.error(ex.getMessage(), ex);
return new ArrayList<Metric>();
}
}
/**
* Method for retrieving an easy to display JSON string of the latest
* monitored Data complete with composed metrics
*
* @return JSON representation of the monitored data. JSON Format:
* {"name":"ServiceEntityName"
* ,"type":"MonitoredElementType","children":[{"name":"metric value
* [metricName]","type":"metric"}]} JSON Example:
* {"name":"LoadBalancer","children":[{"name":"1
* [vmCount]","type":"metric"},{"name":"51 [clients]","type":"metric"},{"
* name":"10.99.0.62","children":[{"name":"51
* [activeConnections]","type":"metric"},{"name":"1
* [vmCount]","type":"metric"}],"type":"VM"}],"type":"SERVICE_UNIT"}
*/
@GET
@Path("/{serviceID}/monitoringdata/json")
@Produces("application/json")
public String getLatestMonitoringDataInJSON(@PathParam("serviceID") String serviceID) {
return collectionService.getLatestMonitoringDataINJSON(serviceID);
}
@GET
@Path("/{serviceID}/monitoringdata/{monitoredElementID}/{monitoredElementLevel}/{metricName}/{metricUnit}")
@Produces("text/plain")
public String getValueForParticularMetric(@PathParam("serviceID") String serviceID,
@PathParam("monitoredElementID") String monitoredElementID,
@PathParam("monitoredElementLevel") String monitoredElementlevel,
@PathParam("metricName") String metricName,
@PathParam("metricUnit") String metricUnit
) {
return collectionService.getLatestValueForParticularMetric(serviceID, monitoredElementID, monitoredElementlevel, metricName, metricUnit);
}
/**
* @return the service structure containing all virtual machines currently
* running service units
*/
@GET
@Path("/{serviceID}/structure")
@Produces("application/xml")
public MonitoredElement getLatestServiceStructure(@PathParam("serviceID") String serviceID) {
return collectionService.getLatestServiceStructure(serviceID);
}
@GET
@Path("/{serviceID}/monitoringdata/xml")
@Produces("application/xml")
public MonitoredElementMonitoringSnapshot getLatestMonitoringDataInXML(@PathParam("serviceID") String serviceID) {
return collectionService.getLatestMonitoringDataInXML(serviceID);
}
@POST
@Path("/{serviceID}/monitoringdata/xml")
@Consumes("application/xml")
@Produces("application/xml")
public MonitoredElementMonitoringSnapshot getLatestMonitoringDataInXML(@PathParam("serviceID") String serviceID, MonitoredElement element) {
return collectionService.getLatestMonitoringData(serviceID, element);
}
@GET
@Path("/{serviceID}/historicalmonitoringdata/all/xml")
@Produces("application/xml")
public MonitoredElementMonitoringSnapshots getAllAggregatedMonitoringData(@PathParam("serviceID") String serviceID) {
return collectionService.getAllAggregatedMonitoringData(serviceID);
}
@GET
@Path("/{serviceID}/historicalmonitoringdata/ininterval/xml")
@Produces("application/xml")
public MonitoredElementMonitoringSnapshots getAllAggregatedMonitoringDataInTimeInterval(@PathParam("serviceID") String serviceID, @QueryParam("startTimestamp") long startTimestamp,
@QueryParam("endTimestamp") long endTimestamp) {
return collectionService.getAggregatedMonitoringDataInTimeInterval(serviceID, startTimestamp, endTimestamp);
}
@GET
@Path("/{serviceID}/historicalmonitoringdata/fromtimestamp/xml")
@Produces("application/xml")
public MonitoredElementMonitoringSnapshots getAllAggregatedMonitoringDataFromTimestamp(@PathParam("serviceID") String serviceID, @QueryParam("timestamp") long timestamp) {
return collectionService.getAllAggregatedMonitoringDataFromTimestamp(serviceID, timestamp);
}
@GET
@Path("/{serviceID}/historicalmonitoringdata/lastX/xml")
@Produces("application/xml")
public MonitoredElementMonitoringSnapshots getLastXAggregatedMonitoringData(@PathParam("serviceID") String serviceID, @QueryParam("count") int count) {
return collectionService.getLastXAggregatedMonitoringData(serviceID, count);
}
@GET
@Path("/{serviceID}/metriccompositionrules/json")
@Produces("application/json")
public String getMetricCompositionRules(@PathParam("serviceID") String serviceID) {
return collectionService.getMetricCompositionRules(serviceID);
}
@GET
@Path("/{serviceID}/metriccompositionrules/xml")
@Produces("application/xml")
public CompositionRulesConfiguration getMetricCompositionRulesXML(@PathParam("serviceID") String serviceID) {
return collectionService.getMetricCompositionRulesXML(serviceID);
}
@PUT
@Path("/{serviceID}/{targetEntityID}/executingaction/{action}")
public void addExecutingAction(@PathParam("serviceID") String serviceID, @PathParam("targetEntityID") String targetEntityID, @PathParam("action") String action
) {
List<Action> actions = new ArrayList<Action>();
actions.add(new Action(targetEntityID, action));
collectionService.addExecutingActions(serviceID, actions);
}
@DELETE
@Path("/{serviceID}/{targetEntityID}/executingaction/{action}")
public void removeExecutingAction(@PathParam("serviceID") String serviceID, @PathParam("targetEntityID") String targetEntityID, @PathParam("action") String action
) {
List<Action> actions = new ArrayList<Action>();
actions.add(new Action(targetEntityID, action));
collectionService.removeExecutingActions(serviceID, actions);
}
@GET
@Path("/{serviceID}/healthy")
public String testIfAllVMsReportMEtricsGreaterThanZero(@PathParam("serviceID") String serviceID) {
return "" + collectionService.testIfServiceIsHealthy(serviceID);
}
@GET
@Path("/elasticservices")
@Produces("application/json")
public String getServices() {
return collectionService.getAllManagedServicesIDs();
}
@GET
@Path("/{serviceID}/events/json")
@Produces("application/json")
public String getEvents(@PathParam("serviceID") String serviceID) {
return collectionService.getEvents(serviceID);
}
/**
* Currently for ease of specification, events are send as one string
* separated by ","
*
* @param serviceID
* @param events
*/
@POST
@Path("/{serviceID}/events")
@Consumes("text/plain")
public void writeEvents(@PathParam("serviceID") String serviceID, String event) {
collectionService.writeEvents(serviceID, event);
}
@GET
@Path("/{serviceID}/data/csv")
@Produces("text/csv")
public Response getCompleteMonitoringtHistoryAsCSV(@PathParam("serviceID") String serviceID) {
String csvString = collectionService.getCompleteMonitoringHistoryAsCSV(serviceID);
Response response = Response.status(200).header("Content-Disposition", "attachment; filename=" + serviceID + "_monitoring_data.csv").entity(csvString).build();
return response;
}
}
| apache-2.0 |
devesion/java-obd-adapter | adapter/src/main/java/com/devesion/commons/obd/adapter/shared/ObdCommandResponseException.java | 756 | package com.devesion.commons.obd.adapter.shared;
import com.devesion.commons.obd.adapter.command.ObdCommand;
import lombok.Getter;
/**
* Represents invalid OBD command.
*/
public class ObdCommandResponseException extends ObdCommunicationException {
@Getter
private ObdCommand command;
private String responseData;
public ObdCommandResponseException(ObdCommand command) {
this.command = command;
}
public ObdCommandResponseException(ObdCommand command, String responseData) {
this.command = command;
this.responseData = responseData;
}
@Override
public String getMessage() {
String message = "command '" + command + "";
if (responseData != null) {
message += "', response '" + responseData + "'";
}
return message;
}
}
| apache-2.0 |
consulo/consulo-python | python-impl/src/main/java/com/jetbrains/python/editor/PythonEnterHandler.java | 18299 | /*
* Copyright 2000-2014 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.jetbrains.python.editor;
import java.util.regex.Matcher;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import com.intellij.codeInsight.CodeInsightSettings;
import com.intellij.codeInsight.editorActions.AutoHardWrapHandler;
import com.intellij.codeInsight.editorActions.enter.EnterHandlerDelegateAdapter;
import com.intellij.ide.DataManager;
import com.intellij.injected.editor.EditorWindow;
import com.intellij.lang.ASTNode;
import com.intellij.lang.injection.InjectedLanguageManager;
import com.intellij.openapi.actionSystem.DataContext;
import com.intellij.openapi.editor.Document;
import com.intellij.openapi.editor.Editor;
import com.intellij.openapi.editor.actionSystem.EditorActionHandler;
import com.intellij.openapi.editor.actions.SplitLineAction;
import com.intellij.openapi.util.Ref;
import com.intellij.openapi.util.TextRange;
import com.intellij.openapi.util.text.LineTokenizer;
import com.intellij.psi.PsiComment;
import com.intellij.psi.PsiDocumentManager;
import com.intellij.psi.PsiElement;
import com.intellij.psi.PsiErrorElement;
import com.intellij.psi.PsiFile;
import com.intellij.psi.PsiWhiteSpace;
import com.intellij.psi.TokenType;
import com.intellij.psi.impl.source.tree.TreeUtil;
import com.intellij.psi.impl.source.tree.injected.InjectedLanguageUtil;
import com.intellij.psi.util.PsiTreeUtil;
import com.jetbrains.python.PyTokenTypes;
import com.jetbrains.python.codeInsight.PyCodeInsightSettings;
import com.jetbrains.python.documentation.docstrings.DocStringFormat;
import com.jetbrains.python.documentation.docstrings.DocStringUtil;
import com.jetbrains.python.documentation.docstrings.GoogleCodeStyleDocString;
import com.jetbrains.python.documentation.docstrings.GoogleCodeStyleDocStringBuilder;
import com.jetbrains.python.documentation.docstrings.PyDocstringGenerator;
import com.jetbrains.python.documentation.docstrings.SectionBasedDocString;
import com.jetbrains.python.psi.*;
import com.jetbrains.python.psi.impl.PyStringLiteralExpressionImpl;
/**
* @author yole
*/
public class PythonEnterHandler extends EnterHandlerDelegateAdapter
{
private int myPostprocessShift = 0;
public static final Class[] IMPLICIT_WRAP_CLASSES = new Class[]{
PyListLiteralExpression.class,
PySetLiteralExpression.class,
PyDictLiteralExpression.class,
PyDictLiteralExpression.class,
PyParenthesizedExpression.class,
PyArgumentList.class,
PyParameterList.class
};
private static final Class[] WRAPPABLE_CLASSES = new Class[]{
PsiComment.class,
PyParenthesizedExpression.class,
PyListCompExpression.class,
PyDictCompExpression.class,
PySetCompExpression.class,
PyDictLiteralExpression.class,
PySetLiteralExpression.class,
PyListLiteralExpression.class,
PyArgumentList.class,
PyParameterList.class,
PyDecoratorList.class,
PySliceExpression.class,
PySubscriptionExpression.class,
PyGeneratorExpression.class
};
@Override
public Result preprocessEnter(@Nonnull PsiFile file,
@Nonnull Editor editor,
@Nonnull Ref<Integer> caretOffset,
@Nonnull Ref<Integer> caretAdvance,
@Nonnull DataContext dataContext,
EditorActionHandler originalHandler)
{
int offset = caretOffset.get();
if(editor instanceof EditorWindow)
{
file = InjectedLanguageManager.getInstance(file.getProject()).getTopLevelFile(file);
editor = InjectedLanguageUtil.getTopLevelEditor(editor);
offset = editor.getCaretModel().getOffset();
}
if(!(file instanceof PyFile))
{
return Result.Continue;
}
final Boolean isSplitLine = DataManager.getInstance().loadFromDataContext(dataContext, SplitLineAction.SPLIT_LINE_KEY);
if(isSplitLine != null)
{
return Result.Continue;
}
final Document doc = editor.getDocument();
PsiDocumentManager.getInstance(file.getProject()).commitDocument(doc);
final PsiElement element = file.findElementAt(offset);
CodeInsightSettings codeInsightSettings = CodeInsightSettings.getInstance();
if(codeInsightSettings.JAVADOC_STUB_ON_ENTER)
{
PsiElement comment = element;
if(comment == null && offset != 0)
{
comment = file.findElementAt(offset - 1);
}
int expectedStringStart = editor.getCaretModel().getOffset() - 3; // """ or '''
if(comment != null)
{
final DocstringState state = canGenerateDocstring(comment, expectedStringStart, doc);
if(state != DocstringState.NONE)
{
insertDocStringStub(editor, comment, state);
return Result.Continue;
}
}
}
if(element == null)
{
return Result.Continue;
}
PsiElement elementParent = element.getParent();
if(element.getNode().getElementType() == PyTokenTypes.LPAR)
{
elementParent = elementParent.getParent();
}
if(elementParent instanceof PyParenthesizedExpression || elementParent instanceof PyGeneratorExpression)
{
return Result.Continue;
}
if(offset > 0 && !(PyTokenTypes.STRING_NODES.contains(element.getNode().getElementType())))
{
final PsiElement prevElement = file.findElementAt(offset - 1);
if(prevElement == element)
{
return Result.Continue;
}
}
if(PyTokenTypes.TRIPLE_NODES.contains(element.getNode().getElementType()) || element.getNode().getElementType() == PyTokenTypes.DOCSTRING)
{
return Result.Continue;
}
final PsiElement prevElement = file.findElementAt(offset - 1);
PyStringLiteralExpression string = PsiTreeUtil.findElementOfClassAtOffset(file, offset, PyStringLiteralExpression.class, false);
if(string != null && prevElement != null && PyTokenTypes.STRING_NODES.contains(prevElement.getNode().getElementType()) && string.getTextOffset() < offset && !(element.getNode() instanceof
PsiWhiteSpace))
{
final String stringText = element.getText();
final int prefixLength = PyStringLiteralExpressionImpl.getPrefixLength(stringText);
if(string.getTextOffset() + prefixLength >= offset)
{
return Result.Continue;
}
final String pref = element.getText().substring(0, prefixLength);
final String quote = element.getText().substring(prefixLength, prefixLength + 1);
final boolean nextIsBackslash = "\\".equals(doc.getText(TextRange.create(offset - 1, offset)));
final boolean isEscapedQuote = quote.equals(doc.getText(TextRange.create(offset, offset + 1))) && nextIsBackslash;
final boolean isEscapedBackslash = "\\".equals(doc.getText(TextRange.create(offset - 2, offset - 1))) && nextIsBackslash;
if(nextIsBackslash && !isEscapedQuote && !isEscapedBackslash)
{
return Result.Continue;
}
final StringBuilder replacementString = new StringBuilder();
myPostprocessShift = prefixLength + quote.length();
if(PsiTreeUtil.getParentOfType(string, IMPLICIT_WRAP_CLASSES) != null)
{
replacementString.append(quote).append(pref).append(quote);
doc.insertString(offset, replacementString);
caretOffset.set(caretOffset.get() + 1);
return Result.Continue;
}
else
{
if(isEscapedQuote)
{
replacementString.append(quote);
caretOffset.set(caretOffset.get() + 1);
}
replacementString.append(quote).append(" \\").append(pref);
if(!isEscapedQuote)
{
replacementString.append(quote);
}
doc.insertString(offset, replacementString.toString());
caretOffset.set(caretOffset.get() + 3);
return Result.Continue;
}
}
if(!PyCodeInsightSettings.getInstance().INSERT_BACKSLASH_ON_WRAP)
{
return Result.Continue;
}
return checkInsertBackslash(file, caretOffset, dataContext, offset, doc);
}
private static Result checkInsertBackslash(PsiFile file, Ref<Integer> caretOffset, DataContext dataContext, int offset, Document doc)
{
boolean autoWrapInProgress = DataManager.getInstance().loadFromDataContext(dataContext, AutoHardWrapHandler.AUTO_WRAP_LINE_IN_PROGRESS_KEY) != null;
if(needInsertBackslash(file, offset, autoWrapInProgress))
{
doc.insertString(offset, "\\");
caretOffset.set(caretOffset.get() + 1);
}
return Result.Continue;
}
public static boolean needInsertBackslash(PsiFile file, int offset, boolean autoWrapInProgress)
{
if(offset > 0)
{
final PsiElement beforeCaret = file.findElementAt(offset - 1);
if(beforeCaret instanceof PsiWhiteSpace && beforeCaret.getText().indexOf('\\') >= 0)
{
// we've got a backslash at EOL already, don't need another one
return false;
}
}
PsiElement atCaret = file.findElementAt(offset);
if(atCaret == null)
{
return false;
}
ASTNode nodeAtCaret = atCaret.getNode();
return needInsertBackslash(nodeAtCaret, autoWrapInProgress);
}
public static boolean needInsertBackslash(ASTNode nodeAtCaret, boolean autoWrapInProgress)
{
PsiElement statementBefore = findStatementBeforeCaret(nodeAtCaret);
PsiElement statementAfter = findStatementAfterCaret(nodeAtCaret);
if(statementBefore != statementAfter)
{ // Enter pressed at statement break
return false;
}
if(statementBefore == null)
{ // empty file
return false;
}
if(PsiTreeUtil.hasErrorElements(statementBefore))
{
if(!autoWrapInProgress)
{
// code is already bad, don't mess it up even further
return false;
}
// if we're in middle of typing, it's expected that we will have error elements
}
if(inFromImportParentheses(statementBefore, nodeAtCaret.getTextRange().getStartOffset()))
{
return false;
}
PsiElement wrappableBefore = findWrappable(nodeAtCaret, true);
PsiElement wrappableAfter = findWrappable(nodeAtCaret, false);
if(!(wrappableBefore instanceof PsiComment))
{
while(wrappableBefore != null)
{
PsiElement next = PsiTreeUtil.getParentOfType(wrappableBefore, WRAPPABLE_CLASSES);
if(next == null)
{
break;
}
wrappableBefore = next;
}
}
if(!(wrappableAfter instanceof PsiComment))
{
while(wrappableAfter != null)
{
PsiElement next = PsiTreeUtil.getParentOfType(wrappableAfter, WRAPPABLE_CLASSES);
if(next == null)
{
break;
}
wrappableAfter = next;
}
}
if(wrappableBefore instanceof PsiComment || wrappableAfter instanceof PsiComment)
{
return false;
}
if(wrappableAfter == null)
{
return !(wrappableBefore instanceof PyDecoratorList);
}
return wrappableBefore != wrappableAfter;
}
private static void insertDocStringStub(Editor editor, PsiElement element, DocstringState state)
{
PyDocStringOwner docOwner = PsiTreeUtil.getParentOfType(element, PyDocStringOwner.class);
if(docOwner != null)
{
final int caretOffset = editor.getCaretModel().getOffset();
final Document document = editor.getDocument();
final String quotes = document.getText(TextRange.from(caretOffset - 3, 3));
final String docString = PyDocstringGenerator.forDocStringOwner(docOwner).withInferredParameters(true).withQuotes(quotes).forceNewMode().buildDocString();
if(state == DocstringState.INCOMPLETE)
{
document.insertString(caretOffset, docString.substring(3));
}
else if(state == DocstringState.EMPTY)
{
document.replaceString(caretOffset, caretOffset + 3, docString.substring(3));
}
}
}
@Nullable
private static PsiElement findWrappable(ASTNode nodeAtCaret, boolean before)
{
PsiElement wrappable = before ? findBeforeCaret(nodeAtCaret, WRAPPABLE_CLASSES) : findAfterCaret(nodeAtCaret, WRAPPABLE_CLASSES);
if(wrappable == null)
{
PsiElement emptyTuple = before ? findBeforeCaret(nodeAtCaret, PyTupleExpression.class) : findAfterCaret(nodeAtCaret, PyTupleExpression.class);
if(emptyTuple != null && emptyTuple.getNode().getFirstChildNode().getElementType() == PyTokenTypes.LPAR)
{
wrappable = emptyTuple;
}
}
return wrappable;
}
@Nullable
private static PsiElement findStatementBeforeCaret(ASTNode node)
{
return findBeforeCaret(node, PyStatement.class);
}
@Nullable
private static PsiElement findStatementAfterCaret(ASTNode node)
{
return findAfterCaret(node, PyStatement.class);
}
private static PsiElement findBeforeCaret(ASTNode atCaret, Class<? extends PsiElement>... classes)
{
while(atCaret != null)
{
atCaret = TreeUtil.prevLeaf(atCaret);
if(atCaret != null && atCaret.getElementType() != TokenType.WHITE_SPACE)
{
return getNonStrictParentOfType(atCaret.getPsi(), classes);
}
}
return null;
}
private static PsiElement findAfterCaret(ASTNode atCaret, Class<? extends PsiElement>... classes)
{
while(atCaret != null)
{
if(atCaret.getElementType() != TokenType.WHITE_SPACE)
{
return getNonStrictParentOfType(atCaret.getPsi(), classes);
}
atCaret = TreeUtil.nextLeaf(atCaret);
}
return null;
}
@Nullable
private static <T extends PsiElement> T getNonStrictParentOfType(@Nonnull PsiElement element, @Nonnull Class<? extends T>... classes)
{
PsiElement run = element;
while(run != null)
{
for(Class<? extends T> aClass : classes)
{
if(aClass.isInstance(run))
{
return (T) run;
}
}
if(run instanceof PsiFile || run instanceof PyStatementList)
{
break;
}
run = run.getParent();
}
return null;
}
private static boolean inFromImportParentheses(PsiElement statement, int offset)
{
if(!(statement instanceof PyFromImportStatement))
{
return false;
}
PyFromImportStatement fromImportStatement = (PyFromImportStatement) statement;
PsiElement leftParen = fromImportStatement.getLeftParen();
if(leftParen != null && offset >= leftParen.getTextRange().getEndOffset())
{
return true;
}
return false;
}
@Override
public Result postProcessEnter(@Nonnull PsiFile file, @Nonnull Editor editor, @Nonnull DataContext dataContext)
{
if(!(file instanceof PyFile))
{
return Result.Continue;
}
if(myPostprocessShift > 0)
{
editor.getCaretModel().moveCaretRelatively(myPostprocessShift, 0, false, false, false);
myPostprocessShift = 0;
return Result.Continue;
}
addGoogleDocStringSectionIndent(file, editor, editor.getCaretModel().getOffset());
return super.postProcessEnter(file, editor, dataContext);
}
private static void addGoogleDocStringSectionIndent(@Nonnull PsiFile file, @Nonnull Editor editor, int offset)
{
final Document document = editor.getDocument();
PsiDocumentManager.getInstance(file.getProject()).commitDocument(document);
final PsiElement element = file.findElementAt(offset);
if(element != null)
{
// Insert additional indentation after section header in Google code style docstrings
final PyStringLiteralExpression pyString = DocStringUtil.getParentDefinitionDocString(element);
if(pyString != null)
{
final String docStringText = pyString.getText();
final DocStringFormat format = DocStringUtil.guessDocStringFormat(docStringText, pyString);
if(format == DocStringFormat.GOOGLE && offset + 1 < document.getTextLength())
{
final int lineNum = document.getLineNumber(offset);
final TextRange lineRange = TextRange.create(document.getLineStartOffset(lineNum - 1), document.getLineEndOffset(lineNum - 1));
final Matcher matcher = GoogleCodeStyleDocString.SECTION_HEADER.matcher(document.getText(lineRange));
if(matcher.matches() && SectionBasedDocString.isValidSectionTitle(matcher.group(1)))
{
document.insertString(offset, GoogleCodeStyleDocStringBuilder.getDefaultSectionIndent(file.getProject()));
editor.getCaretModel().moveCaretRelatively(2, 0, false, false, false);
}
}
}
}
}
enum DocstringState
{
NONE,
INCOMPLETE,
EMPTY
}
@Nonnull
public static DocstringState canGenerateDocstring(@Nonnull PsiElement element, int firstQuoteOffset, @Nonnull Document document)
{
if(firstQuoteOffset < 0 || firstQuoteOffset > document.getTextLength() - 3)
{
return DocstringState.NONE;
}
final String quotes = document.getText(TextRange.from(firstQuoteOffset, 3));
if(!quotes.equals("\"\"\"") && !quotes.equals("'''"))
{
return DocstringState.NONE;
}
final PyStringLiteralExpression pyString = DocStringUtil.getParentDefinitionDocString(element);
if(pyString != null)
{
String nodeText = element.getText();
final int prefixLength = PyStringLiteralExpressionImpl.getPrefixLength(nodeText);
nodeText = nodeText.substring(prefixLength);
final String literalText = pyString.getText();
if(literalText.endsWith(nodeText) && nodeText.startsWith(quotes))
{
if(firstQuoteOffset == pyString.getTextOffset() + prefixLength)
{
PsiErrorElement error = PsiTreeUtil.getNextSiblingOfType(pyString, PsiErrorElement.class);
if(error == null)
{
error = PsiTreeUtil.getNextSiblingOfType(pyString.getParent(), PsiErrorElement.class);
}
if(error != null)
{
return DocstringState.INCOMPLETE;
}
if(nodeText.equals(quotes + quotes))
{
return DocstringState.EMPTY;
}
if(nodeText.length() < 6 || !nodeText.endsWith(quotes))
{
return DocstringState.INCOMPLETE;
}
// Sometimes if incomplete docstring is followed by another declaration with a docstring, it might be treated
// as complete docstring, because we can't understand that closing quotes actually belong to another docstring.
final String docstringIndent = PyIndentUtil.getLineIndent(document, document.getLineNumber(firstQuoteOffset));
for(String line : LineTokenizer.tokenizeIntoList(nodeText, false))
{
final String lineIndent = PyIndentUtil.getLineIndent(line);
final String lineContent = line.substring(lineIndent.length());
if((lineContent.startsWith("def ") || lineContent.startsWith("class ")) &&
docstringIndent.length() > lineIndent.length() && docstringIndent.startsWith(lineIndent))
{
return DocstringState.INCOMPLETE;
}
}
}
}
}
return DocstringState.NONE;
}
}
| apache-2.0 |
OpenHFT/Chronicle-Common | src/main/java/net/openhft/chronicle/common/nio/VanillaSelectionKeyHandler.java | 882 | /*
* Copyright 2014 Higher Frequency Trading
*
* http://www.higherfrequencytrading.com
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package net.openhft.chronicle.common.nio;
import java.io.IOException;
import java.nio.channels.SelectionKey;
public interface VanillaSelectionKeyHandler {
public void onKey(final SelectionKey key)
throws IOException;
}
| apache-2.0 |
tetriscode/spatialconnect-android-sdk | spatialconnect/src/main/java/com/boundlessgeo/spatialconnect/stores/SCDataStore.java | 3591 | /*
*
* * ****************************************************************************
* * Licensed to the Apache Software Foundation (ASF) under one
* * or more contributor license agreements. See the NOTICE file
* * distributed with this work for additional information
* * regarding copyright ownership. The ASF licenses this file
* * to you under the Apache License, Version 2.0 (the
* * "License"); you may not use this file except in compliance
* * with the License. You may obtain a copy of the License at
* *
* * http://www.apache.org/licenses/LICENSE-2.0
* *
* * Unless required by applicable law or agreed to in writing,
* * software distributed under the License is distributed on an
* * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* * KIND, either express or implied. See the License for the
* * specific language governing permissions and limitations
* * under the License.
* * ****************************************************************************
*
*/
package com.boundlessgeo.spatialconnect.stores;
import android.content.Context;
import com.boundlessgeo.spatialconnect.config.SCStoreConfig;
import com.boundlessgeo.spatialconnect.dataAdapter.SCDataAdapter;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
public abstract class SCDataStore implements SCSpatialStore
{
private SCDataAdapter adapter;
// TODO: should we use the SCStoreConfig object instead of the store id?
private String storeId;
private String name;
private int version = 0;
private String type;
private Context context;
private SCDataStoreStatus status = SCDataStoreStatus.DATA_STORE_STOPPED;
public SCDataStore(Context context, SCStoreConfig scStoreConfig)
{
this.context = context;
if (scStoreConfig.getUniqueID() != null) {
this.storeId = scStoreConfig.getUniqueID();
} else {
this.storeId = UUID.randomUUID().toString();
}
}
public SCDataAdapter getAdapter()
{
return this.adapter;
}
public void setAdapter(SCDataAdapter adapter)
{
this.adapter = adapter;
}
public String getStoreId()
{
return this.storeId;
}
public String getName()
{
return this.name;
}
public void setName(String name)
{
this.name = name;
}
public int getVersion()
{
return this.version;
}
public void setVersion(int version)
{
this.version = version;
}
public String getType()
{
return this.type;
}
public void setType(String type)
{
this.type = type;
}
public String getKey()
{
return this.type + "." + this.version;
}
public Context getContext()
{
return this.context;
}
public void setContext(Context context)
{
this.context = context;
}
public SCDataStoreStatus getStatus()
{
return this.status;
}
public void setStatus(SCDataStoreStatus status)
{
this.status = status;
}
public Map<String, String> toMap()
{
Map<String, String> storeMap = new HashMap<>();
storeMap.put("storeId", this.storeId);
storeMap.put("name", this.name);
storeMap.put("type", this.type);
storeMap.put("version", Integer.toString(this.version));
storeMap.put("key", getKey());
return storeMap;
}
@Override
public String toString() {
return storeId + "." + name;
}
}
| apache-2.0 |
jentfoo/aws-sdk-java | aws-java-sdk-personalize/src/main/java/com/amazonaws/services/personalize/model/DeleteSchemaResult.java | 2323 | /*
* Copyright 2014-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with
* the License. A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
* CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions
* and limitations under the License.
*/
package com.amazonaws.services.personalize.model;
import java.io.Serializable;
import javax.annotation.Generated;
/**
*
* @see <a href="http://docs.aws.amazon.com/goto/WebAPI/personalize-2018-05-22/DeleteSchema" target="_top">AWS API
* Documentation</a>
*/
@Generated("com.amazonaws:aws-java-sdk-code-generator")
public class DeleteSchemaResult extends com.amazonaws.AmazonWebServiceResult<com.amazonaws.ResponseMetadata> implements Serializable, Cloneable {
/**
* Returns a string representation of this object. This is useful for testing and debugging. Sensitive data will be
* redacted from this string using a placeholder value.
*
* @return A string representation of this object.
*
* @see java.lang.Object#toString()
*/
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("{");
sb.append("}");
return sb.toString();
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (obj instanceof DeleteSchemaResult == false)
return false;
DeleteSchemaResult other = (DeleteSchemaResult) obj;
return true;
}
@Override
public int hashCode() {
final int prime = 31;
int hashCode = 1;
return hashCode;
}
@Override
public DeleteSchemaResult clone() {
try {
return (DeleteSchemaResult) super.clone();
} catch (CloneNotSupportedException e) {
throw new IllegalStateException("Got a CloneNotSupportedException from Object.clone() " + "even though we're Cloneable!", e);
}
}
}
| apache-2.0 |
pafnat/WebServiceTraining | 00_Demo/src/com/javaws/countryInfo/consumer/CountryInfoConsumer.java | 987 | package com.javaws.countryInfo.consumer;
import org.oorsprong.websamples.CountryInfoService;
import org.oorsprong.websamples.CountryInfoServiceSoapType;
public class CountryInfoConsumer {
public static void main(String[] args) {
CountryInfoService countryInfoService = new CountryInfoService();
CountryInfoServiceSoapType countryInfoServiceSoapType = countryInfoService.getCountryInfoServiceSoap();
System.out.println("Country name is " + countryInfoServiceSoapType.countryName("AU") + " Capital is " + countryInfoServiceSoapType.capitalCity("AU"));
System.out.println("Country name is " + countryInfoServiceSoapType.countryName("CN") + " Capital is " + countryInfoServiceSoapType.capitalCity("CN"));
System.out.println("Country name is " + countryInfoServiceSoapType.countryName("DN") + " Capital is " + countryInfoServiceSoapType.capitalCity("CN") + " Currency code is " + countryInfoServiceSoapType.currencyName("DKK"));
}
}
| apache-2.0 |
zpao/buck | src/com/facebook/buck/swift/SwiftDescriptionsProvider.java | 1659 | /*
* Copyright (c) Facebook, Inc. and 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 com.facebook.buck.swift;
import com.facebook.buck.core.config.BuckConfig;
import com.facebook.buck.core.description.Description;
import com.facebook.buck.core.description.DescriptionCreationContext;
import com.facebook.buck.core.model.targetgraph.DescriptionProvider;
import com.facebook.buck.core.toolchain.ToolchainProvider;
import com.facebook.buck.cxx.config.CxxBuckConfig;
import java.util.Collection;
import java.util.Collections;
import org.pf4j.Extension;
@Extension
public class SwiftDescriptionsProvider implements DescriptionProvider {
@Override
public Collection<Description<?>> getDescriptions(DescriptionCreationContext context) {
ToolchainProvider toolchainProvider = context.getToolchainProvider();
BuckConfig config = context.getBuckConfig();
SwiftBuckConfig swiftBuckConfig = new SwiftBuckConfig(config);
CxxBuckConfig cxxBuckConfig = new CxxBuckConfig(config);
return Collections.singleton(
new SwiftLibraryDescription(toolchainProvider, cxxBuckConfig, swiftBuckConfig));
}
}
| apache-2.0 |
aws/aws-sdk-java | aws-java-sdk-devicefarm/src/main/java/com/amazonaws/services/devicefarm/model/transform/DeleteNetworkProfileRequestMarshaller.java | 2046 | /*
* Copyright 2017-2022 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with
* the License. A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
* CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions
* and limitations under the License.
*/
package com.amazonaws.services.devicefarm.model.transform;
import javax.annotation.Generated;
import com.amazonaws.SdkClientException;
import com.amazonaws.services.devicefarm.model.*;
import com.amazonaws.protocol.*;
import com.amazonaws.annotation.SdkInternalApi;
/**
* DeleteNetworkProfileRequestMarshaller
*/
@Generated("com.amazonaws:aws-java-sdk-code-generator")
@SdkInternalApi
public class DeleteNetworkProfileRequestMarshaller {
private static final MarshallingInfo<String> ARN_BINDING = MarshallingInfo.builder(MarshallingType.STRING).marshallLocation(MarshallLocation.PAYLOAD)
.marshallLocationName("arn").build();
private static final DeleteNetworkProfileRequestMarshaller instance = new DeleteNetworkProfileRequestMarshaller();
public static DeleteNetworkProfileRequestMarshaller getInstance() {
return instance;
}
/**
* Marshall the given parameter object.
*/
public void marshall(DeleteNetworkProfileRequest deleteNetworkProfileRequest, ProtocolMarshaller protocolMarshaller) {
if (deleteNetworkProfileRequest == null) {
throw new SdkClientException("Invalid argument passed to marshall(...)");
}
try {
protocolMarshaller.marshall(deleteNetworkProfileRequest.getArn(), ARN_BINDING);
} catch (Exception e) {
throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e);
}
}
}
| apache-2.0 |
rjeschke/neetlisp | src/neetlisp/fns/core/FnNumGe.java | 1750 | /*
* Copyright (C) 2012 René Jeschke <rene_jeschke@yahoo.de>
*
* 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 neetlisp.fns.core;
import neetlisp.Context;
import neetlisp.Fn;
import neetlisp.FnMeta;
import neetlisp.NIterator;
import neetlisp.NSeq;
import neetlisp.Number;
import neetlisp.seq.NArray;
public class FnNumGe extends Fn
{
public FnNumGe(final Context context)
{
super(context, new FnMeta("core/>=",
"(num & nums)\n" +
" Returns true if num & nums are in monotonically non-increasing order",
1, true, 0));
}
public Object eval(Object first, Object others)
{
boolean ok = true;
Number num = (Number)first;
for(final NIterator it = ((NSeq)others).getIterator(); it.hasNext();)
{
final Number next = (Number)it.next();
if(num.compareTo(next) < 0)
{
ok = false;
break;
}
num = next;
}
return ok;
}
@Override
public Object invoke(Object ... objects)
{
this.assureArguments(objects.length);
return this.eval(objects[0], NArray.hardTailseq(objects, 1));
}
}
| apache-2.0 |
x-meta/xworker | xworker_javafx/src/main/java/xworker/javafx/beans/property/MapAdapter.java | 3566 | package xworker.javafx.beans.property;
import javafx.beans.property.*;
import javafx.collections.FXCollections;
import javafx.collections.ObservableMap;
import org.xmeta.ActionContext;
import org.xmeta.Thing;
import java.util.*;
public class MapAdapter<K, V> implements Map<K, V> {
private ObservableMap<K, Property> valueMap = FXCollections.observableMap(new HashMap<>());
Thing thing;
ActionContext actionContext;
public MapAdapter(Thing thing, ActionContext actionContext){
this.thing = thing;
this.actionContext = actionContext;
}
public MapAdapter(){
}
public ObservableMap<K, Property> getValueMap(){
return valueMap;
}
@Override
public int size() {
return valueMap.size();
}
@Override
public boolean isEmpty() {
return valueMap.isEmpty();
}
@Override
public boolean containsKey(Object key) {
return valueMap.containsKey(key);
}
@Override
public boolean containsValue(Object value) {
return valueMap.containsValue(value);
}
public void setProperty(K key, Property<Object> property){
valueMap.put(key, property);
}
public Property<Object> getProperty(K key){
return valueMap.get(key);
}
@Override
public V get(Object key) {
Property<?> p = valueMap.get(key);
if(p != null){
return (V) p.getValue();
}
return null;
}
@Override
public V put(K key, V value) {
Property p = valueMap.get(key);
if(p != null){
p.setValue(value);
}else{
for(Thing child : thing.getChilds()){
if(child.getMetadata().getName().equals(key)){
String thingName = child.getThingName();
if("BooleanProperty".equals(thingName)){
p = new SimpleBooleanProperty();
}else if("DoubleProperty".equals(thingName)){
p = new SimpleDoubleProperty();
}else if("FloatProperty".equals(thingName)){
p = new SimpleFloatProperty();
}else if("IntegerProperty".equals(thingName)){
p = new SimpleIntegerProperty();
}else if("LongProperty".equals(thingName)){
p = new SimpleLongProperty();
}else{
p = new SimpleObjectProperty();
}
if(p != null){
break;
}
}
}
if(p == null){
p = new SimpleObjectProperty();
}
valueMap.put(key, p);
p.setValue(value);
}
return value;
}
@Override
public V remove(Object key) {
return (V) valueMap.remove(key);
}
@Override
public void putAll(Map<? extends K, ? extends V> m) {
for(K key : m.keySet()){
put(key, m.get(key));
}
}
@Override
public void clear() {
valueMap.clear();
}
@Override
public Set<K> keySet() {
return valueMap.keySet();
}
@Override
public Collection<V> values() {
List<V> values = new ArrayList<>();
for(Property p : valueMap.values()){
values.add((V) p.getValue());
}
return values;
}
@Override
public Set<Entry<K, V>> entrySet() {
throw new UnsupportedOperationException();
}
}
| apache-2.0 |
guoxiaoxing/material-design-music-player | music/src/main/java/com/guoxiaoxing/music/ui/activity/SettingsActivity.java | 3572 | package com.guoxiaoxing.music.ui.activity;
import android.os.Bundle;
import android.preference.PreferenceFragment;
import android.preference.PreferenceManager;
import android.support.annotation.ColorInt;
import android.support.annotation.NonNull;
import android.support.annotation.StyleRes;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.view.MenuItem;
import com.afollestad.appthemeengine.ATE;
import com.afollestad.appthemeengine.Config;
import com.afollestad.appthemeengine.customizers.ATEActivityThemeCustomizer;
import com.afollestad.materialdialogs.color.ColorChooserDialog;
import com.guoxiaoxing.music.R;
import com.guoxiaoxing.music.ui.base.BaseActivity;
import com.guoxiaoxing.music.ui.fragment.SettingsFragment;
import com.guoxiaoxing.music.ui.subfragment.StyleSelectorFragment;
import com.guoxiaoxing.music.util.Constants;
import com.guoxiaoxing.music.util.PreferencesUtility;
public class SettingsActivity extends BaseActivity implements ColorChooserDialog.ColorCallback, ATEActivityThemeCustomizer {
String action;
@Override
public void onCreate(Bundle savedInstanceState) {
if (PreferencesUtility.getInstance(this).getTheme().equals("dark"))
setTheme(R.style.AppThemeDark);
else if (PreferencesUtility.getInstance(this).getTheme().equals("black"))
setTheme(R.style.AppThemeNormalBlack);
super.onCreate(savedInstanceState);
enableNormalTitle();
setContentView(R.layout.activity_settings);
action = getIntent().getAction();
if (action.equals(Constants.SETTINGS_STYLE_SELECTOR)) {
getSupportActionBar().setTitle(R.string.now_playing);
String what = getIntent().getExtras().getString(Constants.SETTINGS_STYLE_SELECTOR_WHAT);
Fragment fragment = StyleSelectorFragment.newInstance(what);
FragmentManager fragmentManager = getSupportFragmentManager();
fragmentManager.beginTransaction()
.add(R.id.fragment_container, fragment).commit();
} else {
getSupportActionBar().setTitle(R.string.settings);
PreferenceFragment fragment = new SettingsFragment();
android.app.FragmentManager fragmentManager = getFragmentManager();
fragmentManager.beginTransaction()
.replace(R.id.fragment_container, fragment).commit();
}
}
@Override
public boolean onOptionsItemSelected(final MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
finish();
return true;
default:
break;
}
return super.onOptionsItemSelected(item);
}
@StyleRes
@Override
public int getActivityTheme() {
return PreferenceManager.getDefaultSharedPreferences(this).getBoolean("dark_theme", false) ?
R.style.AppThemeDark : R.style.AppThemeLight;
}
@Override
public void onColorSelection(@NonNull ColorChooserDialog dialog, @ColorInt int selectedColor) {
final Config config = ATE.config(this, getATEKey());
switch (dialog.getTitle()) {
case R.string.primary_color:
config.primaryColor(selectedColor);
break;
case R.string.accent_color:
config.accentColor(selectedColor);
break;
}
config.commit();
recreate(); // recreation needed to reach the checkboxes in the preferences layout
}
}
| apache-2.0 |
cjstehno/ersatz | ersatz/src/test/java/io/github/cjstehno/ersatz/ErsatzServerTest.java | 2310 | /**
* Copyright (C) 2022 Christopher J. Stehno
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.github.cjstehno.ersatz;
import io.github.cjstehno.ersatz.ErsatzServer;
import lombok.val;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.*;
class ErsatzServerTest {
@Test @DisplayName("not started should give useful error")
void not_started() {
val server = new ErsatzServer();
try {
final var thrown = assertThrows(IllegalStateException.class, () -> server.httpUrl("/nothing"));
assertEquals("The port (-1) is invalid: Has the server been started?", thrown.getMessage());
} finally {
server.close();
}
}
@Test @DisplayName("auto-start disabled")
void autoStartDisabled() {
val server = new ErsatzServer(cfg -> cfg.autoStart(false));
try {
server.expectations(expect -> {
expect.GET("/foo").responds().code(200);
});
val thrown = assertThrows(Exception.class, server::getHttpUrl);
assertEquals("The port (-1) is invalid: Has the server been started?", thrown.getMessage());
} finally {
server.close();
}
}
@Test @DisplayName("auto-start enabled")
void autoStartEnabled() {
val server = new ErsatzServer(cfg -> cfg.autoStart(true));
try {
server.expectations(expect -> {
expect.GET("/foo").responds().code(200);
});
assertTrue(server.getHttpUrl().startsWith("http://localhost:"));
} finally {
server.close();
}
}
}
| apache-2.0 |
jdcasey/pnc | bpm/src/main/java/org/jboss/pnc/bpm/BpmEventType.java | 3104 | /**
* JBoss, Home of Professional Open Source.
* Copyright 2014-2018 Red Hat, Inc., and individual contributors
* as indicated by the @author tags.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jboss.pnc.bpm;
import lombok.ToString;
import org.jboss.pnc.rest.restmodel.bpm.BpmNotificationRest;
import org.jboss.pnc.rest.restmodel.bpm.BpmStringMapNotificationRest;
import org.jboss.pnc.rest.restmodel.bpm.BuildResultRest;
import org.jboss.pnc.rest.restmodel.bpm.ProcessProgressUpdate;
import org.jboss.pnc.rest.restmodel.causeway.MilestoneReleaseResultRest;
import static java.util.Objects.requireNonNull;
/**
* Types of events that BPM process can send notifications about to PNC.
* Each type contains two pieces of data - string identifier
* and type of the received notification. This data is used
* in deserialization inside BPM REST endpoint, for example.
*
* @author Jakub Senko
*/
@ToString
public enum BpmEventType { //TODO merge with org.jboss.pnc.spi.notifications.model.EventType ?
// <T extends BpmNotificationRest>
PROCESS_PROGRESS_UPDATE(ProcessProgressUpdate.class),
DEBUG(BpmStringMapNotificationRest.class),
BREW_IMPORT_SUCCESS(MilestoneReleaseResultRest.class), //TODO remove SUCCESS|ERROR from the event types ?
BREW_IMPORT_ERROR(BpmStringMapNotificationRest.class),
BUILD_COMPLETE(BuildResultRest.class),
RC_REPO_CREATION_SUCCESS(BpmStringMapNotificationRest.class),
RC_REPO_CREATION_ERROR(BpmStringMapNotificationRest.class),
RC_REPO_CLONE_SUCCESS(BpmStringMapNotificationRest.class),
RC_REPO_CLONE_ERROR(BpmStringMapNotificationRest.class),
//notification for bpm task completion
RC_CREATION_SUCCESS(BpmStringMapNotificationRest.class),
RC_CREATION_ERROR(BpmStringMapNotificationRest.class),
BCC_CONFIG_SET_ADDITION_SUCCESS(BpmStringMapNotificationRest.class),
BCC_CONFIG_SET_ADDITION_ERROR(BpmStringMapNotificationRest.class);
private final Class<? extends BpmNotificationRest> type;
/**
* @param type Type of the class containing event data received from the process.
* Usually named *Rest.
*/
BpmEventType(Class<? extends BpmNotificationRest> type) {
requireNonNull(type);
this.type = type;
}
public <T extends BpmNotificationRest> Class<T> getType() {
return (Class<T>) type;
}
public static BpmEventType nullableValueOf(String name) {
try {
return valueOf(name);
} catch (IllegalArgumentException | NullPointerException e) {
return null;
}
}
}
| apache-2.0 |
GitHubJiang/JpushJiang | src/main/java/cn/study/innerclass/Exsample.java | 2371 | /**
* Copyright (c) 2015 Jumbomart All Rights Reserved.
*
* This software is the confidential and proprietary information of Jumbomart. You shall not
* disclose such Confidential Information and shall use it only in accordance with the terms of the
* license agreement you entered into with Jumbo.
*
* JUMBOMART MAKES NO REPRESENTATIONS OR WARRANTIES ABOUT THE SUITABILITY OF THE SOFTWARE, EITHER
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE IMPLIED WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE, OR NON-INFRINGEMENT. JUMBOMART SHALL NOT BE LIABLE FOR ANY
* DAMAGES SUFFERED BY LICENSEE AS A RESULT OF USING, MODIFYING OR DISTRIBUTING THIS SOFTWARE OR ITS
* DERIVATIVES.
*
*/
package cn.study.innerclass;
public class Exsample {
private static String str = "我只是一个字符串";
private String name;
private int age;
static {
System.out.println("我是Exsample的静态块!!!!");
}
{
System.out.println("我是Exsample的初始化模块!!!!");
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
//静态内部类
public static class StaticInnerClass {
{
System.out.println("我是Exsample.StaticInnerClass的初始化模块!!!!");
}
private String prName;
public String getPrName() {
return prName;
}
public void setPrName(String prName) {
this.prName = prName;
}
public void test() {
System.out.println(Exsample.class.getName());
}
}
//成员内部类
public class PublicInnerClass {
{
System.out.println("我是Exsample.PublicInnerClass的初始化模块!!!!");
}
private int puAge;
public int getPuAge() {
return puAge;
}
public void setPuAge(int puAge) {
this.puAge = puAge;
}
public void test() {
System.out.println(Exsample.class.getName());
}
}
}
| apache-2.0 |
AndrewHancock/MiniJava-compiler | src/main/java/ir/regalloc/Register.java | 206 | package ir.regalloc;
public class Register extends Value
{
public Register(int registerIndex)
{
super(registerIndex);
}
public int getRegisterIndex()
{
return getValue();
}
}
| apache-2.0 |
fengshao0907/bookkeeper | bookkeeper-server/src/main/java/org/apache/bookkeeper/bookie/EntryMemTable.java | 14177 | /**
*
* 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.bookkeeper.bookie;
import org.apache.bookkeeper.bookie.Bookie.NoLedgerException;
import org.apache.bookkeeper.stats.BookkeeperServerStatsLogger;
import org.apache.bookkeeper.util.MathUtils;
import org.apache.bookkeeper.stats.ServerStatsProvider;
import org.apache.bookkeeper.stats.BookkeeperServerStatsLogger.BookkeeperServerOp;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicLong;
import java.util.concurrent.locks.ReentrantReadWriteLock;
import java.util.concurrent.ConcurrentSkipListMap;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.apache.bookkeeper.bookie.CheckpointProgress.CheckPoint;
import org.apache.bookkeeper.conf.ServerConfiguration;
/**
* The EntryMemTable holds in-memory representation to the entries not-yet flushed.
* When asked to flush, current EntrySkipList is moved to snapshot and is cleared.
* We continue to serve edits out of new EntrySkipList and backing snapshot until
* flusher reports in that the flush succeeded. At that point we let the snapshot go.
*/
public class EntryMemTable {
private static Logger Logger = LoggerFactory.getLogger(Journal.class);
/**
* Entry skip list
*/
static class EntrySkipList extends ConcurrentSkipListMap<EntryKey, EntryKeyValue> {
final CheckPoint cp;
static final EntrySkipList EMPTY_VALUE = new EntrySkipList(CheckPoint.MAX) {
@Override
public boolean isEmpty() {
return true;
}
};
EntrySkipList(final CheckPoint cp) {
super(EntryKey.COMPARATOR);
this.cp = cp;
}
int compareTo(final CheckPoint cp) {
return this.cp.compareTo(cp);
}
@Override
public EntryKeyValue put(EntryKey k, EntryKeyValue v) {
return putIfAbsent(k, v);
}
@Override
public EntryKeyValue putIfAbsent(EntryKey k, EntryKeyValue v) {
assert k.equals(v);
return super.putIfAbsent(v, v);
}
@Override
public boolean equals(Object o) {
return this == o;
}
}
volatile EntrySkipList kvmap;
// Snapshot of EntryMemTable. Made for flusher.
volatile EntrySkipList snapshot;
final ServerConfiguration conf;
final CheckpointProgress progress;
final ReentrantReadWriteLock lock = new ReentrantReadWriteLock();
// Used to track own data size
final AtomicLong size;
final long skipListSizeLimit;
SkipListArena allocator;
private EntrySkipList newSkipList() {
return new EntrySkipList(progress.requestCheckpoint());
}
/**
* Constructor.
* @param conf Server configuration
*/
public EntryMemTable(final ServerConfiguration conf, final CheckpointProgress progress) {
this.progress = progress;
this.kvmap = newSkipList();
this.snapshot = EntrySkipList.EMPTY_VALUE;
this.conf = conf;
this.size = new AtomicLong(0);
this.allocator = new SkipListArena(conf);
// skip list size limit
this.skipListSizeLimit = conf.getSkipListSizeLimit();
}
void dump() {
for (EntryKey key: this.kvmap.keySet()) {
Logger.info(key.toString());
}
for (EntryKey key: this.snapshot.keySet()) {
Logger.info(key.toString());
}
}
CheckPoint snapshot() throws IOException {
return snapshot(CheckPoint.MAX);
}
/**
* Snapshot current EntryMemTable. if given <i>oldCp</i> is older than current checkpoint,
* we don't do any snapshot. If snapshot happened, we return the checkpoint of the snapshot.
*
* @param oldCp
* checkpoint
* @return checkpoint of the snapshot, null means no snapshot
* @throws IOException
*/
CheckPoint snapshot(CheckPoint oldCp) throws IOException {
CheckPoint cp = null;
// No-op if snapshot currently has entries
if (this.snapshot.isEmpty() &&
this.kvmap.compareTo(oldCp) < 0) {
final long startTimeNanos = MathUtils.nowInNano();
this.lock.writeLock().lock();
try {
if (this.snapshot.isEmpty() && !this.kvmap.isEmpty()
&& this.kvmap.compareTo(oldCp) < 0) {
this.snapshot = this.kvmap;
this.kvmap = newSkipList();
// get the checkpoint of the memtable.
cp = this.kvmap.cp;
// Reset heap to not include any keys
this.size.set(0);
// Reset allocator so we get a fresh buffer for the new EntryMemTable
this.allocator = new SkipListArena(conf);
}
} finally {
this.lock.writeLock().unlock();
}
if (null != cp) {
ServerStatsProvider.getStatsLoggerInstance().getOpStatsLogger(BookkeeperServerOp
.SKIP_LIST_SNAPSHOT).registerSuccessfulEvent(MathUtils.elapsedMicroSec(startTimeNanos));
} else {
ServerStatsProvider.getStatsLoggerInstance().getOpStatsLogger(BookkeeperServerOp
.SKIP_LIST_SNAPSHOT).registerFailedEvent(MathUtils.elapsedMicroSec(startTimeNanos));
}
}
return cp;
}
/**
* Flush snapshot and clear it.
*/
long flush(final SkipListFlusher flusher) throws IOException {
return flushSnapshot(flusher, CheckPoint.MAX);
}
/**
* Flush memtable until checkpoint.
*
* @param checkpoint
* all data before this checkpoint need to be flushed.
*/
public long flush(SkipListFlusher flusher, CheckPoint checkpoint) throws IOException {
long size = flushSnapshot(flusher, checkpoint);
if (null != snapshot(checkpoint)) {
size += flushSnapshot(flusher, checkpoint);
}
return size;
}
/**
* Flush snapshot and clear it iff its data is before checkpoint.
* Only this function change non-empty this.snapshot.
*/
private long flushSnapshot(final SkipListFlusher flusher, CheckPoint checkpoint) throws IOException {
long size = 0;
if (this.snapshot.compareTo(checkpoint) < 0) {
long ledger, ledgerGC = -1;
synchronized (this) {
EntrySkipList keyValues = this.snapshot;
if (keyValues.compareTo(checkpoint) < 0) {
for (EntryKey key : keyValues.keySet()) {
EntryKeyValue kv = (EntryKeyValue)key;
size += kv.getLength();
ledger = kv.getLedgerId();
if (ledgerGC != ledger) {
try {
flusher.process(ledger, kv.getEntryId(), kv.getValueAsByteBuffer());
} catch (NoLedgerException exception) {
ledgerGC = ledger;
}
}
}
ServerStatsProvider.getStatsLoggerInstance().getCounter(
BookkeeperServerStatsLogger.BookkeeperServerCounter.SKIP_LIST_FLUSH_BYTES).add(size);
clearSnapshot(keyValues);
}
}
}
return size;
}
/**
* The passed snapshot was successfully persisted; it can be let go.
* @param keyValues The snapshot to clean out.
* @see {@link #snapshot()}
*/
private void clearSnapshot(final EntrySkipList keyValues) {
// Caller makes sure that keyValues not empty
assert !keyValues.isEmpty();
this.lock.writeLock().lock();
try {
// create a new snapshot and let the old one go.
assert this.snapshot == keyValues;
this.snapshot = EntrySkipList.EMPTY_VALUE;
} finally {
this.lock.writeLock().unlock();
}
}
/**
* Throttling writer w/ 1 ms delay
*/
private void throttleWriters() {
try {
Thread.sleep(1);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
ServerStatsProvider.getStatsLoggerInstance().getCounter(BookkeeperServerStatsLogger.BookkeeperServerCounter
.SKIP_LIST_THROTTLING).inc();
}
/**
* Write an update
* @param entry
* @return approximate size of the passed key and value.
*/
public long addEntry(long ledgerId, long entryId, final ByteBuffer entry, final CacheCallback cb)
throws IOException {
long size = 0;
final long startTimeNanos = MathUtils.nowInNano();
if (isSizeLimitReached()) {
CheckPoint cp = snapshot();
if (null != cp) {
cb.onSizeLimitReached(cp);
} else {
throttleWriters();
}
}
this.lock.readLock().lock();
try {
EntryKeyValue toAdd = cloneWithAllocator(ledgerId, entryId, entry);
size = internalAdd(toAdd);
} finally {
this.lock.readLock().unlock();
}
ServerStatsProvider.getStatsLoggerInstance().getOpStatsLogger(BookkeeperServerOp
.SKIP_LIST_PUT_ENTRY).registerSuccessfulEvent(MathUtils.elapsedMicroSec(startTimeNanos));
return size;
}
/**
* Internal version of add() that doesn't clone KVs with the
* allocator, and doesn't take the lock.
*
* Callers should ensure they already have the read lock taken
*/
private long internalAdd(final EntryKeyValue toAdd) throws IOException {
long sizeChange = 0;
if (kvmap.putIfAbsent(toAdd, toAdd) == null) {
sizeChange = toAdd.getLength();
size.addAndGet(sizeChange);
}
return sizeChange;
}
private EntryKeyValue newEntry(long ledgerId, long entryId, final ByteBuffer entry) {
byte[] buf;
int offset = 0;
int length = entry.remaining();
if (entry.hasArray()) {
buf = entry.array();
offset = entry.arrayOffset();
}
else {
buf = new byte[length];
entry.get(buf);
}
return new EntryKeyValue(ledgerId, entryId, buf, offset, length);
}
private EntryKeyValue cloneWithAllocator(long ledgerId, long entryId, final ByteBuffer entry) {
int len = entry.remaining();
SkipListArena.MemorySlice alloc = allocator.allocateBytes(len);
if (alloc == null) {
// The allocation was too large, allocator decided
// not to do anything with it.
return newEntry(ledgerId, entryId, entry);
}
assert alloc.getData() != null;
entry.get(alloc.getData(), alloc.getOffset(), len);
return new EntryKeyValue(ledgerId, entryId, alloc.getData(), alloc.getOffset(), len);
}
/**
* Find the entry with given key
* @param ledgerId
* @param entryId
* @return the entry kv or null if none found.
*/
public EntryKeyValue getEntry(long ledgerId, long entryId) throws IOException {
EntryKey key = new EntryKey(ledgerId, entryId);
EntryKeyValue value = null;
long startTimeNanos = MathUtils.nowInNano();
this.lock.readLock().lock();
try {
value = this.kvmap.get(key);
if (value == null) {
value = this.snapshot.get(key);
}
} finally {
this.lock.readLock().unlock();
}
ServerStatsProvider.getStatsLoggerInstance().getOpStatsLogger(BookkeeperServerOp
.SKIP_LIST_GET_ENTRY).registerSuccessfulEvent(MathUtils.elapsedMicroSec(startTimeNanos));
return value;
}
/**
* Find the last entry with the given ledger key
* @param ledgerId
* @return the entry kv or null if none found.
*/
public EntryKeyValue getLastEntry(long ledgerId) throws IOException {
EntryKey result = null;
EntryKey key = new EntryKey(ledgerId, Long.MAX_VALUE);
long startTimeNanos = MathUtils.nowInNano();
this.lock.readLock().lock();
try {
result = this.kvmap.floorKey(key);
if (result == null || result.getLedgerId() != ledgerId) {
result = this.snapshot.floorKey(key);
}
} finally {
this.lock.readLock().unlock();
}
ServerStatsProvider.getStatsLoggerInstance().getOpStatsLogger(BookkeeperServerOp
.SKIP_LIST_GET_ENTRY).registerSuccessfulEvent(MathUtils.elapsedMicroSec(startTimeNanos));
if (result == null || result.getLedgerId() != ledgerId) {
return null;
}
return (EntryKeyValue)result;
}
/**
* Check if the entire heap usage for this EntryMemTable exceeds limit
*/
boolean isSizeLimitReached() {
return size.get() >= skipListSizeLimit;
}
/**
* Check if there is data in the mem-table
* @return
*/
boolean isEmpty() {
return size.get() == 0 && snapshot.isEmpty();
}
}
| apache-2.0 |
oriontribunal/CoffeeMud | com/planet_ink/coffee_mud/Items/Basic/LargeSack.java | 1898 | package com.planet_ink.coffee_mud.Items.Basic;
import com.planet_ink.coffee_mud.core.interfaces.*;
import com.planet_ink.coffee_mud.core.*;
import com.planet_ink.coffee_mud.core.collections.*;
import com.planet_ink.coffee_mud.Abilities.interfaces.*;
import com.planet_ink.coffee_mud.Areas.interfaces.*;
import com.planet_ink.coffee_mud.Behaviors.interfaces.*;
import com.planet_ink.coffee_mud.CharClasses.interfaces.*;
import com.planet_ink.coffee_mud.Commands.interfaces.*;
import com.planet_ink.coffee_mud.Common.interfaces.*;
import com.planet_ink.coffee_mud.Exits.interfaces.*;
import com.planet_ink.coffee_mud.Items.interfaces.*;
import com.planet_ink.coffee_mud.Libraries.interfaces.*;
import com.planet_ink.coffee_mud.Locales.interfaces.*;
import com.planet_ink.coffee_mud.MOBS.interfaces.*;
import com.planet_ink.coffee_mud.Races.interfaces.*;
/*
Copyright 2001-2016 Bo Zimmerman
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
public class LargeSack extends StdContainer
{
@Override
public String ID()
{
return "LargeSack";
}
public LargeSack()
{
super();
setName("a large sack");
setDisplayText("a large sack is crumpled up here.");
setDescription("A nice big berlap sack to put your things in.");
capacity=100;
baseGoldValue=5;
setMaterial(RawMaterial.RESOURCE_COTTON);
recoverPhyStats();
}
}
| apache-2.0 |
snyholm/indeterminatecheckbox | indeterminatecheckbox-addon/src/main/java/org/vaadin/sebastian/indeterminatecheckbox/testcomponents/TestBean.java | 261 | package org.vaadin.sebastian.indeterminatecheckbox.testcomponents;
public class TestBean {
private Boolean value;
public Boolean getValue() {
return value;
}
public void setValue(Boolean value) {
this.value = value;
}
}
| apache-2.0 |
dmarko484/mangooio | mangooio-core/src/main/java/io/mangoo/i18n/Messages.java | 3257 | package io.mangoo.i18n;
import java.text.MessageFormat;
import java.util.HashMap;
import java.util.Locale;
import java.util.Map;
import java.util.ResourceBundle;
import com.google.inject.Singleton;
import io.mangoo.enums.Default;
import io.mangoo.enums.Key;
import io.mangoo.enums.Validation;
/**
*
* @author skubiak
*
*/
@Singleton
public class Messages {
private Map<String, String> defaults = new HashMap<String, String>();
private ResourceBundle bundle;
private Locale locale;
public Messages() {
this.bundle = ResourceBundle.getBundle(Default.BUNDLE_NAME.toString(), Locale.getDefault());
defaults.put(Key.FORM_REQUIRED.toString(), Validation.REQUIRED.toString());
defaults.put(Key.FORM_MIN.toString(), Validation.MIN.toString());
defaults.put(Key.FORM_MAX.toString(), Validation.MAX.toString());
defaults.put(Key.FORM_EXACT_MATCH.toString(), Validation.EXACT_MATCH.toString());
defaults.put(Key.FORM_MATCH.toString(), Validation.MATCH.toString());
defaults.put(Key.FORM_EMAIL.toString(), Validation.EMAIL.toString());
defaults.put(Key.FORM_IPV4.toString(), Validation.IPV4.toString());
defaults.put(Key.FORM_IPV6.toString(), Validation.IPV6.toString());
defaults.put(Key.FORM_RANGE.toString(), Validation.RANGE.toString());
defaults.put(Key.FORM_URL.toString(), Validation.URL.toString());
}
/**
* Refreshes the resource bundle by reloading the bundle with the default locale
*/
public void reload() {
if (!Locale.getDefault().equals(this.locale)) {
this.locale = Locale.getDefault();
this.bundle = ResourceBundle.getBundle(Default.BUNDLE_NAME.toString(), Locale.getDefault());
}
}
/**
* Returns a localized value for a given key stored in messages_xx.properties
*
* @param key The key to look up the localized value
* @return The localized value or an empty value if the given key is not configured
*/
public String get(String key) {
return this.bundle.getString(key);
}
/**
* Returns a localized value for a given key stored in messages_xx.properties and passing the
* given arguments
*
* @param key The key to look up the localized value
* @param arguments The arguments to use
* @return The localized value or null value if the given key is not configured
*/
@SuppressWarnings("all")
public String get(String key, Object... arguments) {
if (this.bundle.containsKey(key)) {
return MessageFormat.format(this.bundle.getString(key), arguments);
} else if (this.defaults.containsKey(key)) {
return MessageFormat.format(this.defaults.get(key), arguments);
}
return "";
}
/**
* Returns a localized value for a given key stored in messages_xx.properties and passing the
* given arguments
*
* @param key The key enum to lookup up the localized value
* @param arguments The arguments to use
* @return The localized value or null value if the given key is not configured
*/
public String get(Key key, Object... arguments) {
return get(key.toString(), arguments);
}
} | apache-2.0 |
edgar615/direwolves | core/src/main/java/com/github/edgar615/gateway/core/definition/EventbusEndpointCodec.java | 2986 | package com.github.edgar615.gateway.core.definition;
import com.google.common.base.Preconditions;
import com.google.common.base.Strings;
import com.google.common.collect.ArrayListMultimap;
import com.google.common.collect.Multimap;
import io.vertx.core.json.JsonArray;
import io.vertx.core.json.JsonObject;
import java.util.ArrayList;
import java.util.List;
/**
* Created by Edgar on 2017/3/8.
*
* @author Edgar Date 2017/3/8
*/
public class EventbusEndpointCodec implements EndpointCodec {
@Override
public Endpoint fromJson(JsonObject jsonObject) {
String type = jsonObject.getString("type");
Preconditions.checkNotNull(type, "endpoint type cannot be null");
Preconditions.checkArgument(type.equalsIgnoreCase("eventbus"),
"endpoint name must be eventbus");
String address = jsonObject.getString("address");
Preconditions.checkNotNull(address, "endpoint address cannot be null");
String name = jsonObject.getString("name", "default");
Preconditions.checkNotNull(name, "endpoint name cannot be null");
String policy = jsonObject.getString("policy");
Preconditions.checkNotNull(policy, "endpoint policy cannot be null");
JsonObject header = jsonObject.getJsonObject("header", new JsonObject());
Multimap<String, String> headers = ArrayListMultimap.create();
for (String key : header.fieldNames()) {
Object value = header.getValue(key);
if (value instanceof JsonArray) {
JsonArray jsonArray = (JsonArray) value;
for (int i = 0; i < jsonArray.size(); i++) {
headers.put(key, jsonArray.getValue(i).toString());
}
} else {
headers.put(key, value.toString());
}
}
return new EventbusEndpointImpl(name, address, policy, jsonObject.getString("action"),
headers);
}
@Override
public JsonObject toJson(Endpoint endpoint) {
EventbusEndpoint eventbusEndpoint = (EventbusEndpoint) endpoint;
JsonObject header = new JsonObject();
for (String key : eventbusEndpoint.headers().keySet()) {
List<String> values = new ArrayList<>(eventbusEndpoint.headers().get(key));
header.put(key, values);
}
JsonObject jsonObject = new JsonObject()
.put("type", eventbusEndpoint.type())
.put("name", eventbusEndpoint.name())
.put("address", eventbusEndpoint.address())
.put("policy", eventbusEndpoint.policy())
.put("header", header);
if (!Strings.isNullOrEmpty(((EventbusEndpoint) endpoint).action())) {
jsonObject.put("action", ((EventbusEndpoint) endpoint).action());
}
return jsonObject;
}
@Override
public String type() {
return EventbusEndpoint.TYPE;
}
}
| apache-2.0 |
mmmsplay10/QuizUpWinner | quizup/com/fasterxml/jackson/databind/type/TypeBindings.java | 7972 | package com.fasterxml.jackson.databind.type;
import com.fasterxml.jackson.databind.JavaType;
import java.lang.reflect.Modifier;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.lang.reflect.TypeVariable;
import java.util.Collection;
import java.util.Collections;
import java.util.HashSet;
import java.util.LinkedHashMap;
import java.util.Map;
public class TypeBindings
{
private static final JavaType[] NO_TYPES = new JavaType[0];
public static final JavaType UNBOUND = new SimpleType(Object.class);
protected Map<String, JavaType> _bindings;
protected final Class<?> _contextClass;
protected final JavaType _contextType;
private final TypeBindings _parentBindings;
protected HashSet<String> _placeholders;
protected final TypeFactory _typeFactory;
public TypeBindings(TypeFactory paramTypeFactory, JavaType paramJavaType)
{
this(paramTypeFactory, null, paramJavaType.getRawClass(), paramJavaType);
}
private TypeBindings(TypeFactory paramTypeFactory, TypeBindings paramTypeBindings, Class<?> paramClass, JavaType paramJavaType)
{
this._typeFactory = paramTypeFactory;
this._parentBindings = paramTypeBindings;
this._contextClass = paramClass;
this._contextType = paramJavaType;
}
public TypeBindings(TypeFactory paramTypeFactory, Class<?> paramClass)
{
this(paramTypeFactory, null, paramClass, null);
}
public void _addPlaceholder(String paramString)
{
if (this._placeholders == null)
this._placeholders = new HashSet();
this._placeholders.add(paramString);
}
protected void _resolve()
{
_resolveBindings(this._contextClass);
if (this._contextType != null)
{
int i = this._contextType.containedTypeCount();
if (i > 0)
for (int j = 0; j < i; j++)
addBinding(this._contextType.containedTypeName(j), this._contextType.containedType(j));
}
if (this._bindings == null)
this._bindings = Collections.emptyMap();
}
protected void _resolveBindings(Type paramType)
{
if (paramType == null)
return;
label214: Object localObject;
if ((paramType instanceof ParameterizedType))
{
ParameterizedType localParameterizedType = (ParameterizedType)paramType;
Type[] arrayOfType2 = localParameterizedType.getActualTypeArguments();
if ((arrayOfType2 != null) && (arrayOfType2.length > 0))
{
Class localClass3 = (Class)localParameterizedType.getRawType();
TypeVariable[] arrayOfTypeVariable2 = localClass3.getTypeParameters();
if (arrayOfTypeVariable2.length != arrayOfType2.length)
throw new IllegalArgumentException("Strange parametrized type (in class " + localClass3.getName() + "): number of type arguments != number of type parameters (" + arrayOfType2.length + " vs " + arrayOfTypeVariable2.length + ")");
int m = 0;
int n = arrayOfType2.length;
while (m < n)
{
String str2 = arrayOfTypeVariable2[m].getName();
if (this._bindings == null)
this._bindings = new LinkedHashMap();
else
if (this._bindings.containsKey(str2))
break label214;
_addPlaceholder(str2);
this._bindings.put(str2, this._typeFactory._constructType(arrayOfType2[m], this));
m++;
}
}
localObject = (Class)localParameterizedType.getRawType();
}
else if ((paramType instanceof Class))
{
Class localClass1 = (Class)paramType;
localObject = localClass1;
Class localClass2 = localClass1.getDeclaringClass();
if ((localClass2 != null) && (!localClass2.isAssignableFrom((Class)localObject)))
_resolveBindings(((Class)localObject).getDeclaringClass());
TypeVariable[] arrayOfTypeVariable1 = ((Class)localObject).getTypeParameters();
if ((arrayOfTypeVariable1 != null) && (arrayOfTypeVariable1.length > 0))
{
JavaType localJavaType = this._contextType;
JavaType[] arrayOfJavaType = null;
if (localJavaType != null)
{
boolean bool = ((Class)localObject).isAssignableFrom(this._contextType.getRawClass());
arrayOfJavaType = null;
if (bool)
arrayOfJavaType = this._typeFactory.findTypeParameters(this._contextType, (Class)localObject);
}
for (int k = 0; k < arrayOfTypeVariable1.length; k++)
{
TypeVariable localTypeVariable = arrayOfTypeVariable1[k];
String str1 = localTypeVariable.getName();
Type localType = localTypeVariable.getBounds()[0];
if (localType != null)
{
if (this._bindings == null)
this._bindings = new LinkedHashMap();
else
if (this._bindings.containsKey(str1))
continue;
_addPlaceholder(str1);
if (arrayOfJavaType != null)
this._bindings.put(str1, arrayOfJavaType[k]);
else
this._bindings.put(str1, this._typeFactory._constructType(localType, this));
}
}
}
}
else
{
return;
}
_resolveBindings(((Class)localObject).getGenericSuperclass());
Type[] arrayOfType1 = ((Class)localObject).getGenericInterfaces();
int i = arrayOfType1.length;
for (int j = 0; j < i; j++)
_resolveBindings(arrayOfType1[j]);
}
public void addBinding(String paramString, JavaType paramJavaType)
{
if ((this._bindings == null) || (this._bindings.size() == 0))
this._bindings = new LinkedHashMap();
this._bindings.put(paramString, paramJavaType);
}
public TypeBindings childInstance()
{
return new TypeBindings(this._typeFactory, this, this._contextClass, this._contextType);
}
public JavaType findType(String paramString)
{
if (this._bindings == null)
_resolve();
JavaType localJavaType = (JavaType)this._bindings.get(paramString);
if (localJavaType != null)
return localJavaType;
if ((this._placeholders != null) && (this._placeholders.contains(paramString)))
return UNBOUND;
if (this._parentBindings != null)
return this._parentBindings.findType(paramString);
if ((this._contextClass != null) && (this._contextClass.getEnclosingClass() != null) && (!Modifier.isStatic(this._contextClass.getModifiers())))
return UNBOUND;
String str;
if (this._contextClass != null)
str = this._contextClass.getName();
else if (this._contextType != null)
str = this._contextType.toString();
else
str = "UNKNOWN";
throw new IllegalArgumentException("Type variable '" + paramString + "' can not be resolved (with context of class " + str + ")");
}
public int getBindingCount()
{
if (this._bindings == null)
_resolve();
return this._bindings.size();
}
public JavaType resolveType(Class<?> paramClass)
{
return this._typeFactory._constructType(paramClass, this);
}
public JavaType resolveType(Type paramType)
{
return this._typeFactory._constructType(paramType, this);
}
public String toString()
{
if (this._bindings == null)
_resolve();
StringBuilder localStringBuilder = new StringBuilder("[TypeBindings for ");
if (this._contextType != null)
localStringBuilder.append(this._contextType.toString());
else
localStringBuilder.append(this._contextClass.getName());
localStringBuilder.append(": ").append(this._bindings).append("]");
return localStringBuilder.toString();
}
public JavaType[] typesAsArray()
{
if (this._bindings == null)
_resolve();
if (this._bindings.size() == 0)
return NO_TYPES;
return (JavaType[])this._bindings.values().toArray(new JavaType[this._bindings.size()]);
}
}
/* Location: /Users/vikas/Documents/Mhacks_Real_app/classes-dex2jar.jar
* Qualified Name: com.fasterxml.jackson.databind.type.TypeBindings
* JD-Core Version: 0.6.2
*/ | apache-2.0 |
wang88/jetty | jetty-webapp/src/main/java/org/eclipse/jetty/webapp/CloneConfiguration.java | 706 | package org.eclipse.jetty.webapp;
public class CloneConfiguration extends AbstractConfiguration
{
final WebAppContext _template;
CloneConfiguration(WebAppContext template)
{
_template=template;
}
@Override
public void configure(WebAppContext context) throws Exception
{
for (Configuration configuration : _template.getConfigurations())
configuration.cloneConfigure(_template,context);
}
@Override
public void deconfigure(WebAppContext context) throws Exception
{
for (Configuration configuration : _template.getConfigurations())
configuration.deconfigure(context);
}
}
| apache-2.0 |
xinfan123/blue-server | bulu-service/src/main/java/ruc/irm/similarity/word/hownet2/concept/Concept.java | 6430 | package ruc.irm.similarity.word.hownet2.concept;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.StringTokenizer;
import ruc.irm.similarity.word.hownet.HownetMeta;
/**
* 知网的概念表示类 <br/>example和英文部分对于相似度的计算不起作用,考虑到内存开销, 在概念的表示中去掉了这部分数据的对应定义
*
* @author <a href="mailto:iamxiatian@gmail.com">夏天</a>
* @organization 中国人民大学信息资源管理学院 知识工程实验室
*/
public class Concept implements HownetMeta {
/** 中文概念名称 */
protected String word;
/** 词性: Part of Speech */
protected String pos;
/** 定义 */
protected String define;
/** 是否是实词,false表示为虚词, 一般为实词 */
protected boolean bSubstantive;
/** 第一基本义原 */
protected String mainSememe;
/** 其他基本义原 */
protected String[] secondSememes;
/** 关系义元原 */
protected String[] relationSememes;
/** 关系符号描述 */
protected String[] symbolSememes;
static String[][] Concept_Type = { { "=", "事件" },
{ "aValue|属性值", "属性值" }, { "qValue|数量值", "数量值" },
{ "attribute|属性", "属性" }, { "quantity|数量", "数量" },
{ "unit|", "单位" }, { "%", "部件" } };
public Concept(String word, String pos, String def) {
this.word = word;
this.pos = pos;
this.define = (def == null) ? "" : def.trim();
// 虚词用{***}表示
if (define.length() > 0
&& define.charAt(0) == '{'
&& define.charAt(define.length() - 1) == '}'){
this.bSubstantive = false;
} else {
this.bSubstantive = true;
}
parseDefine();
}
/**
* 处理定义,把定义分为第一基本义元、其他基本义元、关系义元和符号义元四类
*/
private void parseDefine() {
List<String> secondList = new ArrayList<String>(); //其他基本义原
List<String> relationList = new ArrayList<String>(); //关系义原
List<String> symbolList = new ArrayList<String>(); //符号义原
String tokenString = this.define;
//如果不是实词,则处理“{}”中的内容
if (!this.bSubstantive) {
tokenString = define.substring(1, define.length() - 1);
}
StringTokenizer token = new StringTokenizer(tokenString, ",", false);
// 第一个为第一基本义元
if (token.hasMoreTokens()) {
this.mainSememe = token.nextToken();
}
main_loop: while (token.hasMoreTokens()) {
String item = token.nextToken();
if (item.equals("")) continue;
// 先判断是否为符号义元
String symbol = item.substring(0, 1);
for(int i=0;i< Symbol_Descriptions.length;i++){
if(symbol.equals( Symbol_Descriptions[i][0])){
symbolList.add(item);
continue main_loop;
}
}
//如果不是符号义元,则进一步判断是关系义元还是第二基本义元, 带有“=”表示关系义原
if (item.indexOf('=') > 0){
relationList.add(item);
} else {
secondList.add(item);
}
}
this.secondSememes = secondList.toArray(new String[secondList.size()]);
this.relationSememes = relationList.toArray(new String[relationList.size()]);
this.symbolSememes = symbolList.toArray(new String[symbolList.size()]);
}
/**
* 获取第一义元
*
* @return
*/
public String getMainSememe() {
return mainSememe;
}
/**
* 获取其他基本义元描述
*
* @return
*/
public String[] getSecondSememes() {
return secondSememes;
}
/**
* 获取关系义元描述
*
* @return
*/
public String[] getRelationSememes() {
return relationSememes;
}
/**
* 获取符号义元描述
*
* @return
*/
public String[] getSymbolSememes() {
return symbolSememes;
}
public Set<String> getAllSememeNames(){
Set<String> names = new HashSet<String>();
//加入主义原
names.add(getMainSememe());
//加入关系义原
for(String item:getRelationSememes()){
names.add(item.substring(item.indexOf("=") + 1));
}
//加入符号义原
for(String item:getSymbolSememes()){
names.add(item.substring(1));
}
//加入其他义原集合
for(String item:getSecondSememes()){
names.add(item);
}
return names;
}
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("name=");
sb.append(this.word);
sb.append("; pos=");
sb.append(this.pos);
sb.append("; define=");
sb.append(this.define);
sb.append("; 第一基本义元:[" + mainSememe);
sb.append("]; 其他基本义元描述:[");
for(String sem: secondSememes){
sb.append(sem);
sb.append(";");
}
sb.append("]; [关系义元描述:");
for(String sem: relationSememes){
sb.append(sem);
sb.append(";");
}
sb.append("]; [关系符号描述:");
for(String sem: symbolSememes){
sb.append(sem);
sb.append(";");
}
sb.append("]");
return sb.toString();
}
/**
* 是实词还是虚词
*
* @return true:实词;false:虚词
*/
public boolean isSubstantive() {
return this.bSubstantive;
}
public String getWord() {
return word;
}
public void setWord(String word) {
this.word = word;
}
public String getPos() {
return pos;
}
public void setPos(String pos) {
this.pos = pos;
}
public String getDefine() {
return define;
}
public void setDefine(String define) {
this.define = define;
}
/**
* 获取该概念的类型
*
* @return
*/
public String getType() {
for (int i = 0; i < Concept_Type.length; i++) {
if (define.toUpperCase().indexOf(Concept_Type[i][0].toUpperCase()) >= 0) {
return Concept_Type[i][1];
}
}
return "普通概念";
}
public int hashCode(){
return define==null?word.hashCode():define.hashCode();
}
public boolean equals(Object anObject){
if(anObject instanceof Concept){
Concept c = (Concept)anObject;
return word.equals(c.word) && define.equals(c.define);
}else{
return false;
}
}
} | apache-2.0 |
misberner/automatalib | serialization/core/src/main/java/net/automatalib/serialization/automaton/SimpleAutomatonSerializer.java | 3726 | /* Copyright (C) 2013-2020 TU Dortmund
* This file is part of AutomataLib, http://www.automatalib.net/.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package net.automatalib.serialization.automaton;
import java.io.File;
import java.io.IOException;
import java.io.OutputStream;
import java.util.function.Function;
import net.automatalib.automata.simple.SimpleAutomaton;
import net.automatalib.commons.util.IOUtil;
import net.automatalib.serialization.InputModelSerializer;
import net.automatalib.words.Alphabet;
/**
* A refining interface of {@link InputModelSerializer} that binds the model to {@link SimpleAutomaton}s. It also adds
* new functionality to dynamically serialize systems of arbitrary input type if a transformer to the default input type
* (specified by implementing class) is given.
* <p>
* <b>Note:</b> These model-specific interfaces may be omitted if Java starts supporting higher-kinded generics (or we
* switch to a language that supports these).
*
* @param <I>
* The default input symbol type
*
* @author frohme
*/
public interface SimpleAutomatonSerializer<I> extends InputModelSerializer<I, SimpleAutomaton<?, I>> {
/**
* Writes the model to the given output stream.
* <p>
* Note: the output stream will <b>not</b> be closed.
*
* @param os
* the output stream to write to
* @param model
* the model to write
* @param alphabet
* the inputs of the model to which serialization should be limit
* @param inputTransformer
* a function to transform the inputs of the model to the inputs of {@code this} serializer.
* @param <I2>
* the input symbol type of the model
*
* @throws IOException
* when writing to the output stream fails.
*/
<I2> void writeModel(OutputStream os,
SimpleAutomaton<?, I2> model,
Alphabet<I2> alphabet,
Function<I2, I> inputTransformer) throws IOException;
/**
* Writes the model to the given file.
*
* @param f
* the file to write to
* @param model
* the model to write
* @param alphabet
* the inputs of the model to which serialization should be limit
* @param inputTransformer
* a function to transform the inputs of the model to the inputs of {@code this} serializer.
* @param <I2>
* the input symbol type of the model
*
* @throws IOException
* when writing to the output stream fails.
*/
default <I2> void writeModel(File f,
SimpleAutomaton<?, I2> model,
Alphabet<I2> alphabet,
Function<I2, I> inputTransformer) throws IOException {
try (OutputStream os = IOUtil.asBufferedOutputStream(f)) {
writeModel(os, model, alphabet, inputTransformer);
}
}
@Override
default void writeModel(OutputStream os, SimpleAutomaton<?, I> model, Alphabet<I> alphabet) throws IOException {
writeModel(os, model, alphabet, Function.identity());
}
}
| apache-2.0 |
hortonworks/cloudbreak | core/src/main/java/com/sequenceiq/cloudbreak/service/rdsconfig/KnoxGatewayServiceRdsConfigProvider.java | 1253 | package com.sequenceiq.cloudbreak.service.rdsconfig;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import com.sequenceiq.cloudbreak.api.endpoint.v4.database.base.DatabaseType;
import com.sequenceiq.cloudbreak.domain.Blueprint;
@Component
public class KnoxGatewayServiceRdsConfigProvider extends AbstractRdsConfigProvider {
private static final String PILLAR_KEY = "knox_gateway";
@Value("${cb.knox_gateway.database.port:5432}")
private String port;
@Value("${cb.knox_gateway.database.user:knox_gateway}")
private String userName;
@Value("${cb.knox_gateway.database.db:knox_gateway}")
private String db;
@Override
protected String getDbUser() {
return userName;
}
@Override
protected String getDb() {
return db;
}
@Override
protected String getDbPort() {
return port;
}
@Override
protected String getPillarKey() {
return PILLAR_KEY;
}
@Override
protected DatabaseType getRdsType() {
return DatabaseType.KNOX_GATEWAY;
}
@Override
protected boolean isRdsConfigNeeded(Blueprint blueprint, boolean hasGateway) {
return hasGateway;
}
}
| apache-2.0 |
jmapper-framework/jmapper-test | JMapper Test/src/test/java/com/googlecode/jmapper/integrationtest/configurations/bean/JGlobalMapDInheritance.java | 135 | package com.googlecode.jmapper.integrationtest.configurations.bean;
public class JGlobalMapDInheritance extends JGlobalMapD {
}
| apache-2.0 |
takezoe/xlsbeans | src/main/java/com/github/takezoe/xlsbeans/xssfconverter/impl/xssf/XssfWWorkbookImpl.java | 1227 | package com.github.takezoe.xlsbeans.xssfconverter.impl.xssf;
import com.github.takezoe.xlsbeans.xssfconverter.NullWSheetImpl;
import com.github.takezoe.xlsbeans.xssfconverter.WSheet;
import com.github.takezoe.xlsbeans.xssfconverter.WWorkbook;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
/**
* Workbook wrapper for HSSF/XSSF.
*
* @author Mitsuyoshi Hasegawa
*/
public class XssfWWorkbookImpl implements WWorkbook {
private Workbook workbook = null;
public XssfWWorkbookImpl(Workbook workbook) {
this.workbook = workbook;
}
public WSheet getSheet(int i) {
Sheet sheet = workbook.getSheetAt(i);
return (sheet != null) ? new XssfWSheetImpl(sheet) : NullWSheetImpl.INSTANCE;
}
public WSheet getSheet(String name) {
Sheet sheet = workbook.getSheet(name);
return (sheet != null) ? new XssfWSheetImpl(sheet) : NullWSheetImpl.INSTANCE;
}
public WSheet[] getSheets() {
int sheetNum = workbook.getNumberOfSheets();
WSheet[] retSheets = new WSheet[sheetNum];
for (int i = 0; i < sheetNum; i++) {
retSheets[i] = new XssfWSheetImpl(workbook.getSheetAt(i));
}
return retSheets;
}
}
| apache-2.0 |
johandoornenbal/estatio | estatioapp/dom/src/test/java/org/estatio/dom/lease/LeaseItemsTest.java | 2088 | /*
*
* Copyright 2012-2014 Eurocommercial Properties NV
*
*
* 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.estatio.dom.lease;
import java.util.List;
import org.junit.Before;
import org.junit.Test;
import org.apache.isis.applib.query.Query;
import org.estatio.dom.FinderInteraction;
import org.estatio.dom.FinderInteraction.FinderMethod;
import static org.hamcrest.CoreMatchers.is;
import static org.junit.Assert.assertThat;
public class LeaseItemsTest {
FinderInteraction finderInteraction;
LeaseItems leaseItems;
@Before
public void setup() {
leaseItems = new LeaseItems() {
@Override
protected <T> T firstMatch(Query<T> query) {
finderInteraction = new FinderInteraction(query, FinderMethod.FIRST_MATCH);
return null;
}
@Override
protected List<LeaseItem> allInstances() {
finderInteraction = new FinderInteraction(null, FinderMethod.ALL_INSTANCES);
return null;
}
@Override
protected <T> List<T> allMatches(Query<T> query) {
finderInteraction = new FinderInteraction(query, FinderMethod.ALL_MATCHES);
return null;
}
};
}
public static class AllLeaseItems extends LeaseItemsTest {
@Test
public void happyCase() {
leaseItems.allLeaseItems();
assertThat(finderInteraction.getFinderMethod(), is(FinderMethod.ALL_INSTANCES));
}
}
} | apache-2.0 |
opetrovski/development | oscm-file-billing-adapter/javasrc/org/oscm/billing/external/adapter/bean/ConfigProperties.java | 2490 | /*******************************************************************************
*
* Copyright FUJITSU LIMITED 2017
*
* Creation Date: 12.01.2015
*
*******************************************************************************/
package org.oscm.billing.external.adapter.bean;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;
import org.oscm.billing.external.exception.BillingException;
/**
* Configuration properties of FileBillingAdapter
*/
public class ConfigProperties {
Properties configProperties = null;
String adapterId = null;
private final static String PROPERTY_FILE = "billingApplication.properties";
public ConfigProperties(String adapterId) {
this.adapterId = adapterId;
}
/**
* Get the config property specified by key
*/
public String getConfigProperty(String key) throws BillingException {
String value = (String) getConfigProperties().get(key);
if (value == null || value.trim().length() == 0) {
throw new BillingException("Configsetting: " + key + " is missing");
}
return value;
}
/**
* Get the config properties
*/
Properties getConfigProperties() throws BillingException {
if (configProperties == null) {
loadProperties();
}
return configProperties;
}
/**
* Set the config properties
*/
void setConfigProperties(Properties configProperties) {
this.configProperties = configProperties;
}
/**
* Load the config properties from PROPERTY_FILE
*/
void loadProperties() throws BillingException {
ClassLoader classLoader = this.getClass().getClassLoader();
try (InputStream in = classLoader.getResourceAsStream(PROPERTY_FILE);) {
if (in != null) {
Properties props = new Properties();
props.load(in);
setConfigProperties(props);
}
} catch (IOException e) {
setConfigProperties(null);
throw new BillingException("Configsettings are missing");
}
}
}
| apache-2.0 |
statsbiblioteket/doms-ecm | ecm-repository/src/main/java/dk/statsbiblioteket/doms/ecm/repository/exceptions/NotImplementedYetException.java | 525 | package dk.statsbiblioteket.doms.ecm.repository.exceptions;
/**
* A development class. Methods not implemented should throw this exception. As
* such, they will be easy to find via a global search.
*
*<br/>
* This class should not be used in a released version
*/
public class NotImplementedYetException extends RuntimeException {
public NotImplementedYetException(String s) {
super(s);
}
public NotImplementedYetException(String s, Throwable throwable) {
super(s, throwable);
}
}
| apache-2.0 |
babymm/mumu | mumu-common/mumu-common-core/src/main/java/com/lovecws/mumu/common/core/utils/BankCardUtil.java | 70210 | package com.lovecws.mumu.common.core.utils;
public class BankCardUtil {
// BIN号
private final static String[] bankBin = { "621098", "622150", "622151", "622181", "622188", "955100", "621095",
"620062", "621285", "621798", "621799", "621797", "620529", "622199", "621096", "621622", "623219",
"621674", "623218", "621599", "370246", "370248", "370249", "427010", "427018", "427019", "427020",
"427029", "427030", "427039", "370247", "438125", "438126", "451804", "451810", "451811", "458071",
"489734", "489735", "489736", "510529", "427062", "524091", "427064", "530970", "530990", "558360",
"620200", "620302", "620402", "620403", "620404", "524047", "620406", "620407", "525498", "620409",
"620410", "620411", "620412", "620502", "620503", "620405", "620408", "620512", "620602", "620604",
"620607", "620611", "620612", "620704", "620706", "620707", "620708", "620709", "620710", "620609",
"620712", "620713", "620714", "620802", "620711", "620904", "620905", "621001", "620902", "621103",
"621105", "621106", "621107", "621102", "621203", "621204", "621205", "621206", "621207", "621208",
"621209", "621210", "621302", "621303", "621202", "621305", "621306", "621307", "621309", "621311",
"621313", "621211", "621315", "621304", "621402", "621404", "621405", "621406", "621407", "621408",
"621409", "621410", "621502", "621317", "621511", "621602", "621603", "621604", "621605", "621608",
"621609", "621610", "621611", "621612", "621613", "621614", "621615", "621616", "621617", "621607",
"621606", "621804", "621807", "621813", "621814", "621817", "621901", "621904", "621905", "621906",
"621907", "621908", "621909", "621910", "621911", "621912", "621913", "621915", "622002", "621903",
"622004", "622005", "622006", "622007", "622008", "622010", "622011", "622012", "621914", "622015",
"622016", "622003", "622018", "622019", "622020", "622102", "622103", "622104", "622105", "622013",
"622111", "622114", "622200", "622017", "622202", "622203", "622208", "622210", "622211", "622212",
"622213", "622214", "622110", "622220", "622223", "622225", "622229", "622230", "622231", "622232",
"622233", "622234", "622235", "622237", "622215", "622239", "622240", "622245", "622224", "622303",
"622304", "622305", "622306", "622307", "622308", "622309", "622238", "622314", "622315", "622317",
"622302", "622402", "622403", "622404", "622313", "622504", "622505", "622509", "622513", "622517",
"622502", "622604", "622605", "622606", "622510", "622703", "622715", "622806", "622902", "622903",
"622706", "623002", "623006", "623008", "623011", "623012", "622904", "623015", "623100", "623202",
"623301", "623400", "623500", "623602", "623803", "623901", "623014", "624100", "624200", "624301",
"624402", "62451804", "62451810", "62451811", "62458071", "623700", "628288", "624000", "628286", "622206",
"621225", "526836", "513685", "543098", "458441", "620058", "621281", "622246", "900000", "544210",
"548943", "370267", "621558", "621559", "621722", "621723", "620086", "621226", "402791", "427028",
"427038", "548259", "356879", "356880", "356881", "356882", "528856", "621618", "620516", "621227",
"621721", "900010", "625330", "625331", "625332", "623062", "622236", "621670", "524374", "550213",
"374738", "374739", "621288", "625708", "625709", "622597", "622599", "360883", "360884", "625865",
"625866", "625899", "621376", "620054", "620142", "621428", "625939", "621434", "625987", "621761",
"621749", "620184", "621300", "621378", "625114", "622159", "621720", "625021", "625022", "621379",
"620114", "620146", "621724", "625918", "621371", "620143", "620149", "621414", "625914", "621375",
"620187", "621433", "625986", "621370", "625925", "622926", "622927", "622928", "622929", "622930",
"622931", "620124", "620183", "620561", "625116", "622227", "621372", "621464", "625942", "622158",
"625917", "621765", "620094", "620186", "621719", "621719", "621750", "621377", "620148", "620185",
"621374", "621731", "621781", "552599", "623206", "621671", "620059", "403361", "404117", "404118",
"404119", "404120", "404121", "463758", "514027", "519412", "519413", "520082", "520083", "558730",
"621282", "621336", "621619", "622821", "622822", "622823", "622824", "622825", "622826", "622827",
"622828", "622836", "622837", "622840", "622841", "622843", "622844", "622845", "622846", "622847",
"622848", "622849", "623018", "625996", "625997", "625998", "628268", "625826", "625827", "548478",
"544243", "622820", "622830", "622838", "625336", "628269", "620501", "621660", "621661", "621662",
"621663", "621665", "621667", "621668", "621669", "621666", "625908", "625910", "625909", "356833",
"356835", "409665", "409666", "409668", "409669", "409670", "409671", "409672", "456351", "512315",
"512316", "512411", "512412", "514957", "409667", "518378", "518379", "518474", "518475", "518476",
"438088", "524865", "525745", "525746", "547766", "552742", "553131", "558868", "514958", "622752",
"622753", "622755", "524864", "622757", "622758", "622759", "622760", "622761", "622762", "622763",
"601382", "622756", "628388", "621256", "621212", "620514", "622754", "622764", "518377", "622765",
"622788", "621283", "620061", "621725", "620040", "558869", "621330", "621331", "621332", "621333",
"621297", "377677", "621568", "621569", "625905", "625906", "625907", "628313", "625333", "628312",
"623208", "621620", "621756", "621757", "621758", "621759", "621785", "621786", "621787", "621788",
"621789", "621790", "621672", "625337", "625338", "625568", "621648", "621248", "621249", "622750",
"622751", "622771", "622772", "622770", "625145", "620531", "620210", "620211", "622479", "622480",
"622273", "622274", "621231", "621638", "621334", "625140", "621395", "622725", "622728", "621284",
"421349", "434061", "434062", "436728", "436742", "453242", "491031", "524094", "526410", "544033",
"552245", "589970", "620060", "621080", "621081", "621466", "621467", "621488", "621499", "621598",
"621621", "621700", "622280", "622700", "622707", "622966", "622988", "625955", "625956", "553242",
"621082", "621673", "623211", "356896", "356899", "356895", "436718", "436738", "436745", "436748",
"489592", "531693", "532450", "532458", "544887", "552801", "557080", "558895", "559051", "622166",
"622168", "622708", "625964", "625965", "625966", "628266", "628366", "625362", "625363", "628316",
"628317", "620021", "620521", "405512", "601428", "405512", "434910", "458123", "458124", "520169",
"522964", "552853", "601428", "622250", "622251", "521899", "622254", "622255", "622256", "622257",
"622258", "622259", "622253", "622261", "622284", "622656", "628216", "622252", "66405512", "622260",
"66601428", "955590", "955591", "955592", "955593", "628218", "622262", "621069", "620013", "625028",
"625029", "621436", "621002", "621335", "433670", "433680", "442729", "442730", "620082", "622690",
"622691", "622692", "622696", "622698", "622998", "622999", "433671", "968807", "968808", "968809",
"621771", "621767", "621768", "621770", "621772", "621773", "620527", "356837", "356838", "486497",
"622660", "622662", "622663", "622664", "622665", "622666", "622667", "622669", "622670", "622671",
"622672", "622668", "622661", "622674", "622673", "620518", "621489", "621492", "620535", "623156",
"621490", "621491", "620085", "623155", "623157", "623158", "623159", "999999", "621222", "623020",
"623021", "623022", "623023", "622630", "622631", "622632", "622633", "622615", "622616", "622618",
"622622", "622617", "622619", "415599", "421393", "421865", "427570", "427571", "472067", "472068",
"622620", "621691", "545392", "545393", "545431", "545447", "356859", "356857", "407405", "421869",
"421870", "421871", "512466", "356856", "528948", "552288", "622600", "622601", "622602", "517636",
"622621", "628258", "556610", "622603", "464580", "464581", "523952", "545217", "553161", "356858",
"622623", "625911", "377152", "377153", "377158", "377155", "625912", "625913", "356885", "356886",
"356887", "356888", "356890", "402658", "410062", "439188", "439227", "468203", "479228", "479229",
"512425", "521302", "524011", "356889", "545620", "545621", "545947", "545948", "552534", "552587",
"622575", "622576", "622577", "622579", "622580", "545619", "622581", "622582", "622588", "622598",
"622609", "690755", "690755", "545623", "621286", "620520", "621483", "621485", "621486", "628290",
"622578", "370285", "370286", "370287", "370289", "439225", "518710", "518718", "628362", "439226",
"628262", "625802", "625803", "621299", "966666", "622909", "622908", "438588", "438589", "461982",
"486493", "486494", "486861", "523036", "451289", "527414", "528057", "622901", "622902", "622922",
"628212", "451290", "524070", "625084", "625085", "625086", "625087", "548738", "549633", "552398",
"625082", "625083", "625960", "625961", "625962", "625963", "356851", "356852", "404738", "404739",
"456418", "498451", "515672", "356850", "517650", "525998", "622177", "622277", "622516", "622517",
"622518", "622520", "622521", "622522", "622523", "628222", "628221", "984301", "984303", "622176",
"622276", "622228", "621352", "621351", "621390", "621792", "625957", "625958", "621791", "620530",
"625993", "622519", "621793", "621795", "621796", "622500", "623078", "622384", "940034", "940015",
"622886", "622391", "940072", "622359", "940066", "622857", "940065", "621019", "622309", "621268",
"622884", "621453", "622684", "621016", "621015", "622950", "622951", "621072", "623183", "623185",
"621005", "622172", "622985", "622987", "622267", "622278", "622279", "622468", "622892", "940021",
"621050", "620522", "356827", "356828", "356830", "402673", "402674", "438600", "486466", "519498",
"520131", "524031", "548838", "622148", "622149", "622268", "356829", "622300", "628230", "622269",
"625099", "625953", "625350", "625351", "625352", "519961", "625839", "421317", "602969", "621030",
"621420", "621468", "623111", "422160", "422161", "622865", "940012", "623131", "622178", "622179",
"628358", "622394", "940025", "621279", "622281", "622316", "940022", "621418", "512431", "520194",
"621626", "623058", "602907", "622986", "622989", "622298", "622338", "940032", "623205", "621977",
"990027", "622325", "623029", "623105", "621244", "623081", "623108", "566666", "622455", "940039",
"622466", "628285", "622420", "940041", "623118", "603708", "622993", "623070", "623069", "623172",
"623173", "622383", "622385", "628299", "603506", "603367", "622878", "623061", "623209", "628242",
"622595", "622303", "622305", "621259", "622596", "622333", "940050", "621439", "623010", "621751",
"628278", "625502", "625503", "625135", "622476", "621754", "622143", "940001", "623026", "623086",
"628291", "621532", "621482", "622135", "622152", "622153", "622154", "622996", "622997", "940027",
"623099", "623007", "940055", "622397", "622398", "940054", "622331", "622426", "625995", "621452",
"628205", "628214", "625529", "622428", "621529", "622429", "621417", "623089", "623200", "940057",
"622311", "623119", "622877", "622879", "621775", "623203", "603601", "622137", "622327", "622340",
"622366", "622134", "940018", "623016", "623096", "940049", "622425", "622425", "621577", "622485",
"623098", "628329", "621538", "940006", "621269", "622275", "621216", "622465", "940031", "621252",
"622146", "940061", "621419", "623170", "622440", "940047", "940017", "622418", "623077", "622413",
"940002", "623188", "622310", "940068", "622321", "625001", "622427", "940069", "623039", "628273",
"622370", "683970", "940074", "621437", "628319", "990871", "622308", "621415", "623166", "622132",
"621340", "621341", "622140", "623073", "622147", "621633", "622301", "623171", "621422", "622335",
"622336", "622165", "622315", "628295", "625950", "621760", "622337", "622411", "623102", "622342",
"623048", "622367", "622392", "623085", "622395", "622441", "622448", "621413", "622856", "621037",
"621097", "621588", "623032", "622644", "623518", "622870", "622866", "623072", "622897", "628279",
"622864", "621403", "622561", "622562", "622563", "622167", "622777", "621497", "622868", "622899",
"628255", "625988", "622566", "622567", "622625", "622626", "625946", "628200", "621076", "504923",
"622173", "622422", "622447", "622131", "940076", "621579", "622876", "622873", "622962", "622936",
"623060", "622937", "623101", "621460", "622939", "622960", "623523", "621591", "622961", "628210",
"622283", "625902", "621010", "622980", "623135", "621726", "621088", "620517", "622740", "625036",
"621014", "621004", "622972", "623196", "621028", "623083", "628250", "623121", "621070", "628253",
"622979", "621035", "621038", "621086", "621498", "621296", "621448", "622945", "621755", "622940",
"623120", "628355", "621089", "623161", "628339", "621074", "621515", "623030", "621345", "621090",
"623178", "621091", "623168", "621057", "623199", "621075", "623037", "628303", "621233", "621235",
"621223", "621780", "621221", "623138", "628389", "621239", "623068", "621271", "628315", "621272",
"621738", "621273", "623079", "621263", "621325", "623084", "621327", "621753", "628331", "623160",
"621366", "621388", "621348", "621359", "621360", "621217", "622959", "621270", "622396", "622511",
"623076", "621391", "621339", "621469", "621625", "623688", "623113", "621601", "621655", "621636",
"623182", "623087", "621696", "622955", "622478", "940013", "621495", "621688", "623162", "622462",
"628272", "625101", "622323", "623071", "603694", "622128", "622129", "623035", "623186", "621522",
"622271", "940037", "940038", "985262", "622322", "628381", "622481", "622341", "940058", "623115",
"621258", "621465", "621528", "622328", "940062", "625288", "623038", "625888", "622332", "940063",
"623123", "622138", "621066", "621560", "621068", "620088", "621067", "622531", "622329", "623103",
"622339", "620500", "621024", "622289", "622389", "628300", "625516", "621516", "622859", "622869",
"623075", "622895", "623125", "622947", "621561", "623095", "621073", "623109", "621361", "623033",
"623207", "622891", "621363", "623189", "623510", "622995", "621053", "621230", "621229", "622218",
"628267", "621392", "621481", "621310", "621396", "623251", "628351" };
// "发卡行.卡种名称",
private static final String[] bankName = { "邮储银行·绿卡通", "邮储银行·绿卡银联标准卡", "邮储银行·绿卡银联标准卡", "邮储银行·绿卡专用卡", "邮储银行·绿卡银联标准卡",
"邮储银行·绿卡(银联卡)", "邮储银行·绿卡VIP卡", "邮储银行·银联标准卡", "邮储银行·中职学生资助卡", "邮政储蓄银行·IC绿卡通VIP卡", "邮政储蓄银行·IC绿卡通",
"邮政储蓄银行·IC联名卡", "邮政储蓄银行·IC预付费卡", "邮储银行·绿卡银联标准卡", "邮储银行·绿卡通", "邮政储蓄银行·武警军人保障卡", "邮政储蓄银行·中国旅游卡(金卡)",
"邮政储蓄银行·普通高中学生资助卡", "邮政储蓄银行·中国旅游卡(普卡)", "邮政储蓄银行·福农卡", "工商银行·牡丹运通卡金卡", "工商银行·牡丹运通卡金卡", "工商银行·牡丹运通卡金卡",
"工商银行·牡丹VISA卡(单位卡)", "工商银行·牡丹VISA信用卡", "工商银行·牡丹VISA卡(单位卡)", "工商银行·牡丹VISA信用卡", "工商银行·牡丹VISA信用卡",
"工商银行·牡丹VISA信用卡", "工商银行·牡丹VISA信用卡", "工商银行·牡丹运通卡普通卡", "工商银行·牡丹VISA信用卡", "工商银行·牡丹VISA白金卡", "工商银行·牡丹贷记卡(银联卡)",
"工商银行·牡丹贷记卡(银联卡)", "工商银行·牡丹贷记卡(银联卡)", "工商银行·牡丹贷记卡(银联卡)", "工商银行·牡丹欧元卡", "工商银行·牡丹欧元卡", "工商银行·牡丹欧元卡",
"工商银行·牡丹万事达国际借记卡", "工商银行·牡丹VISA信用卡", "工商银行·海航信用卡", "工商银行·牡丹VISA信用卡", "工商银行·牡丹万事达信用卡", "工商银行·牡丹万事达信用卡",
"工商银行·牡丹万事达信用卡", "工商银行·牡丹灵通卡", "工商银行·牡丹灵通卡", "工商银行·牡丹灵通卡", "工商银行·牡丹灵通卡", "工商银行·牡丹灵通卡", "工商银行·牡丹万事达白金卡",
"工商银行·牡丹灵通卡", "工商银行·牡丹灵通卡", "工商银行·海航信用卡个人普卡", "工商银行·牡丹灵通卡", "工商银行·牡丹灵通卡", "工商银行·牡丹灵通卡", "工商银行·牡丹灵通卡",
"工商银行·牡丹灵通卡", "工商银行·牡丹灵通卡", "工商银行·牡丹灵通卡", "工商银行·牡丹灵通卡", "工商银行·牡丹灵通卡", "工商银行·牡丹灵通卡", "工商银行·牡丹灵通卡",
"工商银行·牡丹灵通卡", "工商银行·牡丹灵通卡", "工商银行·牡丹灵通卡", "工商银行·牡丹灵通卡", "工商银行·牡丹灵通卡", "工商银行·牡丹灵通卡", "工商银行·牡丹灵通卡",
"工商银行·牡丹灵通卡", "工商银行·牡丹灵通卡", "工商银行·牡丹灵通卡", "工商银行·牡丹灵通卡", "工商银行·牡丹灵通卡", "工商银行·牡丹灵通卡", "工商银行·牡丹灵通卡",
"工商银行·牡丹灵通卡", "工商银行·牡丹灵通卡", "工商银行·牡丹灵通卡", "工商银行·牡丹灵通卡", "工商银行·牡丹灵通卡", "工商银行·牡丹灵通卡", "工商银行·牡丹灵通卡",
"工商银行·牡丹灵通卡", "工商银行·牡丹灵通卡", "工商银行·牡丹灵通卡", "工商银行·牡丹灵通卡", "工商银行·牡丹灵通卡", "工商银行·牡丹灵通卡", "工商银行·牡丹灵通卡",
"工商银行·牡丹灵通卡", "工商银行·牡丹灵通卡", "工商银行·牡丹灵通卡", "工商银行·牡丹灵通卡", "工商银行·牡丹灵通卡", "工商银行·牡丹灵通卡", "工商银行·牡丹灵通卡",
"工商银行·牡丹灵通卡", "工商银行·牡丹灵通卡", "工商银行·牡丹灵通卡", "工商银行·牡丹灵通卡", "工商银行·牡丹灵通卡", "工商银行·牡丹灵通卡", "工商银行·牡丹灵通卡",
"工商银行·牡丹灵通卡", "工商银行·牡丹灵通卡", "工商银行·牡丹灵通卡", "工商银行·牡丹灵通卡", "工商银行·牡丹灵通卡", "工商银行·牡丹灵通卡", "工商银行·牡丹灵通卡",
"工商银行·牡丹灵通卡", "工商银行·牡丹灵通卡", "工商银行·牡丹灵通卡", "工商银行·牡丹灵通卡", "工商银行·牡丹灵通卡", "工商银行·牡丹灵通卡", "工商银行·牡丹灵通卡",
"工商银行·牡丹灵通卡", "工商银行·牡丹灵通卡", "工商银行·牡丹灵通卡", "工商银行·牡丹灵通卡", "工商银行·牡丹灵通卡", "工商银行·牡丹灵通卡", "工商银行·牡丹灵通卡",
"工商银行·牡丹灵通卡", "工商银行·牡丹灵通卡", "工商银行·牡丹灵通卡", "工商银行·牡丹灵通卡", "工商银行·牡丹灵通卡", "工商银行·牡丹灵通卡", "工商银行·牡丹灵通卡",
"工商银行·牡丹灵通卡", "工商银行·牡丹灵通卡", "工商银行·牡丹灵通卡", "工商银行·牡丹灵通卡", "工商银行·牡丹灵通卡", "工商银行·牡丹灵通卡", "工商银行·牡丹灵通卡",
"工商银行·牡丹灵通卡", "工商银行·牡丹灵通卡", "工商银行·牡丹灵通卡", "工商银行·牡丹灵通卡", "工商银行·牡丹灵通卡", "工商银行·牡丹灵通卡", "工商银行·牡丹灵通卡",
"工商银行·牡丹灵通卡", "工商银行·牡丹灵通卡", "工商银行·牡丹灵通卡", "工商银行·牡丹灵通卡", "工商银行·牡丹灵通卡", "工商银行·牡丹灵通卡", "工商银行·牡丹灵通卡",
"工商银行·牡丹灵通卡", "工商银行·牡丹灵通卡", "工商银行·牡丹灵通卡", "工商银行·牡丹灵通卡", "工商银行·牡丹灵通卡", "工商银行·牡丹灵通卡", "工商银行·牡丹灵通卡",
"工商银行·牡丹灵通卡", "工商银行·牡丹灵通卡", "工商银行·牡丹灵通卡", "工商银行·牡丹灵通卡", "工商银行·牡丹灵通卡", "工商银行·牡丹灵通卡", "工商银行·牡丹灵通卡",
"工商银行·牡丹灵通卡", "工商银行·牡丹灵通卡", "工商银行·牡丹灵通卡", "工商银行·牡丹灵通卡", "工商银行·牡丹灵通卡", "工商银行·牡丹灵通卡", "工商银行·牡丹灵通卡",
"工商银行·灵通卡", "工商银行·牡丹灵通卡", "工商银行·E时代卡", "工商银行·E时代卡", "工商银行·理财金卡", "工商银行·准贷记卡(个普)", "工商银行·准贷记卡(个普)",
"工商银行·准贷记卡(个普)", "工商银行·准贷记卡(个普)", "工商银行·准贷记卡(个普)", "工商银行·牡丹灵通卡", "工商银行·准贷记卡(商普)", "工商银行·牡丹卡(商务卡)",
"工商银行·准贷记卡(商金)", "工商银行·牡丹卡(商务卡)", "工商银行·贷记卡(个普)", "工商银行·牡丹卡(个人卡)", "工商银行·牡丹卡(个人卡)", "工商银行·牡丹卡(个人卡)",
"工商银行·牡丹卡(个人卡)", "工商银行·贷记卡(个金)", "工商银行·牡丹交通卡", "工商银行·准贷记卡(个金)", "工商银行·牡丹交通卡", "工商银行·贷记卡(商普)",
"工商银行·贷记卡(商金)", "工商银行·牡丹卡(商务卡)", "工商银行·牡丹灵通卡", "工商银行·牡丹灵通卡", "工商银行·牡丹灵通卡", "工商银行·牡丹灵通卡", "工商银行·牡丹灵通卡",
"工商银行·牡丹灵通卡", "工商银行·牡丹灵通卡", "工商银行·牡丹交通卡", "工商银行·牡丹灵通卡", "工商银行·牡丹灵通卡", "工商银行·牡丹灵通卡", "工商银行·牡丹灵通卡",
"工商银行·牡丹灵通卡", "工商银行·牡丹灵通卡", "工商银行·牡丹灵通卡", "工商银行·牡丹灵通卡", "工商银行·牡丹灵通卡", "工商银行·牡丹灵通卡", "工商银行·牡丹灵通卡",
"工商银行·牡丹灵通卡", "工商银行·牡丹灵通卡", "工商银行·牡丹灵通卡", "工商银行·牡丹灵通卡", "工商银行·牡丹灵通卡", "工商银行·牡丹灵通卡", "工商银行·牡丹灵通卡",
"工商银行·牡丹灵通卡", "工商银行·牡丹灵通卡", "工商银行·牡丹灵通卡", "工商银行·牡丹灵通卡", "工商银行·牡丹灵通卡", "工商银行·牡丹灵通卡", "工商银行·牡丹灵通卡",
"工商银行·牡丹灵通卡", "工商银行·牡丹灵通卡", "工商银行·牡丹灵通卡", "工商银行·牡丹灵通卡", "工商银行·牡丹灵通卡", "工商银行·牡丹灵通卡", "工商银行·牡丹灵通卡",
"工商银行·牡丹灵通卡", "工商银行·牡丹灵通卡", "工商银行·牡丹灵通卡", "工商银行·牡丹灵通卡", "工商银行·牡丹灵通卡", "工商银行·牡丹灵通卡", "工商银行·牡丹灵通卡",
"工商银行·牡丹灵通卡", "工商银行·牡丹灵通卡", "工商银行·牡丹灵通卡", "工商银行·牡丹灵通卡", "工商银行·牡丹灵通卡", "工商银行·牡丹贷记卡", "工商银行·牡丹贷记卡",
"工商银行·牡丹贷记卡", "工商银行·牡丹贷记卡", "工商银行·牡丹灵通卡", "工商银行·中央预算单位公务卡", "工商银行·牡丹灵通卡", "工商银行·财政预算单位公务卡", "工商银行·牡丹卡白金卡",
"工商银行·牡丹卡普卡", "工商银行·国航知音牡丹信用卡", "工商银行·国航知音牡丹信用卡", "工商银行·国航知音牡丹信用卡", "工商银行·国航知音牡丹信用卡", "工商银行·银联标准卡",
"工商银行·中职学生资助卡", "工商银行·专用信用消费卡", "工商银行·牡丹社会保障卡", "中国工商银行·牡丹东航联名卡", "中国工商银行·牡丹东航联名卡", "中国工商银行·牡丹运通白金卡",
"中国工商银行·福农灵通卡", "中国工商银行·福农灵通卡", "工商银行·灵通卡", "工商银行·灵通卡", "中国工商银行·中国旅行卡", "工商银行·牡丹卡普卡", "工商银行·国际借记卡",
"工商银行·国际借记卡", "工商银行·国际借记卡", "工商银行·国际借记卡", "中国工商银行·牡丹JCB信用卡", "中国工商银行·牡丹JCB信用卡", "中国工商银行·牡丹JCB信用卡",
"中国工商银行·牡丹JCB信用卡", "中国工商银行·牡丹多币种卡", "中国工商银行·武警军人保障卡", "工商银行·预付芯片卡", "工商银行·理财金账户金卡", "工商银行·灵通卡",
"工商银行·牡丹宁波市民卡", "中国工商银行·中国旅游卡", "中国工商银行·中国旅游卡", "中国工商银行·中国旅游卡", "中国工商银行·借记卡", "中国工商银行·借贷合一卡",
"中国工商银行·普通高中学生资助卡", "中国工商银行·牡丹多币种卡", "中国工商银行·牡丹多币种卡", "中国工商银行·牡丹百夫长信用卡", "中国工商银行·牡丹百夫长信用卡", "工商银行·工银财富卡",
"中国工商银行·中小商户采购卡", "中国工商银行·中小商户采购卡", "中国工商银行·环球旅行金卡", "中国工商银行·环球旅行白金卡", "中国工商银行·牡丹工银大来卡", "中国工商银行·牡丹工银大莱卡",
"中国工商银行·IC金卡", "中国工商银行·IC白金卡", "中国工商银行·工行IC卡(红卡)", "中国工商银行布鲁塞尔分行·借记卡", "中国工商银行布鲁塞尔分行·预付卡",
"中国工商银行布鲁塞尔分行·预付卡", "中国工商银行金边分行·借记卡", "中国工商银行金边分行·信用卡", "中国工商银行金边分行·借记卡", "中国工商银行金边分行·信用卡",
"中国工商银行加拿大分行·借记卡", "中国工商银行加拿大分行·借记卡", "中国工商银行加拿大分行·预付卡", "中国工商银行巴黎分行·借记卡", "中国工商银行巴黎分行·借记卡",
"中国工商银行巴黎分行·贷记卡", "中国工商银行法兰克福分行·贷记卡", "中国工商银行法兰克福分行·借记卡", "中国工商银行法兰克福分行·贷记卡", "中国工商银行法兰克福分行·贷记卡",
"中国工商银行法兰克福分行·借记卡", "中国工商银行法兰克福分行·预付卡", "中国工商银行法兰克福分行·预付卡", "中国工商银行印尼分行·借记卡", "中国工商银行印尼分行·信用卡",
"中国工商银行米兰分行·借记卡", "中国工商银行米兰分行·预付卡", "中国工商银行米兰分行·预付卡", "中国工商银行阿拉木图子行·借记卡", "中国工商银行阿拉木图子行·贷记卡",
"中国工商银行阿拉木图子行·借记卡", "中国工商银行阿拉木图子行·预付卡", "中国工商银行万象分行·借记卡", "中国工商银行万象分行·贷记卡", "中国工商银行卢森堡分行·借记卡",
"中国工商银行卢森堡分行·贷记卡", "中国工商银行澳门分行·E时代卡", "中国工商银行澳门分行·E时代卡", "中国工商银行澳门分行·E时代卡", "中国工商银行澳门分行·理财金账户",
"中国工商银行澳门分行·理财金账户", "中国工商银行澳门分行·理财金账户", "中国工商银行澳门分行·预付卡", "中国工商银行澳门分行·预付卡", "中国工商银行澳门分行·工银闪付预付卡",
"中国工商银行澳门分行·工银银联公司卡", "中国工商银行澳门分行·Diamond", "中国工商银行阿姆斯特丹·借记卡", "中国工商银行卡拉奇分行·借记卡", "中国工商银行卡拉奇分行·贷记卡",
"中国工商银行新加坡分行·贷记卡", "中国工商银行新加坡分行·贷记卡", "中国工商银行新加坡分行·借记卡", "中国工商银行新加坡分行·预付卡", "中国工商银行新加坡分行·预付卡",
"中国工商银行新加坡分行·借记卡", "中国工商银行新加坡分行·借记卡", "中国工商银行马德里分行·借记卡", "中国工商银行马德里分行·借记卡", "中国工商银行马德里分行·预付卡",
"中国工商银行马德里分行·预付卡", "中国工商银行伦敦子行·借记卡", "中国工商银行伦敦子行·工银伦敦借记卡", "中国工商银行伦敦子行·借记卡", "农业银行·金穗贷记卡", "农业银行·中国旅游卡",
"农业银行·普通高中学生资助卡", "农业银行·银联标准卡", "农业银行·金穗贷记卡(银联卡)", "农业银行·金穗贷记卡(银联卡)", "农业银行·金穗贷记卡(银联卡)", "农业银行·金穗贷记卡(银联卡)",
"农业银行·金穗贷记卡(银联卡)", "农业银行·金穗贷记卡(银联卡)", "农业银行·VISA白金卡", "农业银行·万事达白金卡", "农业银行·金穗贷记卡(银联卡)", "农业银行·金穗贷记卡(银联卡)",
"农业银行·金穗贷记卡(银联卡)", "农业银行·金穗贷记卡(银联卡)", "农业银行·金穗贷记卡", "农业银行·中职学生资助卡", "农业银行·专用惠农卡", "农业银行·武警军人保障卡",
"农业银行·金穗校园卡(银联卡)", "农业银行·金穗星座卡(银联卡)", "农业银行·金穗社保卡(银联卡)", "农业银行·金穗旅游卡(银联卡)", "农业银行·金穗青年卡(银联卡)",
"农业银行·复合介质金穗通宝卡", "农业银行·金穗海通卡", "农业银行·退役金卡", "农业银行·金穗贷记卡", "农业银行·金穗贷记卡", "农业银行·金穗通宝卡(银联卡)", "农业银行·金穗惠农卡",
"农业银行·金穗通宝银卡", "农业银行·金穗通宝卡(银联卡)", "农业银行·金穗通宝卡(银联卡)", "农业银行·金穗通宝卡", "农业银行·金穗通宝卡(银联卡)", "农业银行·金穗通宝卡(银联卡)",
"农业银行·金穗通宝钻石卡", "农业银行·掌尚钱包", "农业银行·银联IC卡金卡", "农业银行·银联预算单位公务卡金卡", "农业银行·银联IC卡白金卡", "农业银行·金穗公务卡",
"中国农业银行贷记卡·IC普卡", "中国农业银行贷记卡·IC金卡", "中国农业银行贷记卡·澳元卡", "中国农业银行贷记卡·欧元卡", "中国农业银行贷记卡·金穗通商卡", "中国农业银行贷记卡·金穗通商卡",
"中国农业银行贷记卡·银联白金卡", "中国农业银行贷记卡·中国旅游卡", "中国农业银行贷记卡·银联IC公务卡", "宁波市农业银行·市民卡B卡", "中国银行·联名卡", "中国银行·个人普卡",
"中国银行·个人金卡", "中国银行·员工普卡", "中国银行·员工金卡", "中国银行·理财普卡", "中国银行·理财金卡", "中国银行·理财银卡", "中国银行·理财白金卡",
"中国银行·中行金融IC卡白金卡", "中国银行·中行金融IC卡普卡", "中国银行·中行金融IC卡金卡", "中国银行·中银JCB卡金卡", "中国银行·中银JCB卡普卡", "中国银行·员工普卡",
"中国银行·个人普卡", "中国银行·中银威士信用卡员", "中国银行·中银威士信用卡员", "中国银行·个人白金卡", "中国银行·中银威士信用卡", "中国银行·长城公务卡", "中国银行·长城电子借记卡",
"中国银行·中银万事达信用卡", "中国银行·中银万事达信用卡", "中国银行·中银万事达信用卡", "中国银行·中银万事达信用卡", "中国银行·中银万事达信用卡", "中国银行·中银威士信用卡员",
"中国银行·长城万事达信用卡", "中国银行·长城万事达信用卡", "中国银行·长城万事达信用卡", "中国银行·长城万事达信用卡", "中国银行·长城万事达信用卡", "中国银行·中银奥运信用卡",
"中国银行·长城信用卡", "中国银行·长城信用卡", "中国银行·长城信用卡", "中国银行·长城万事达信用卡", "中国银行·长城公务卡", "中国银行·长城公务卡", "中国银行·中银万事达信用卡",
"中国银行·中银万事达信用卡", "中国银行·长城人民币信用卡", "中国银行·长城人民币信用卡", "中国银行·长城人民币信用卡", "中国银行·长城信用卡", "中国银行·长城人民币信用卡",
"中国银行·长城人民币信用卡", "中国银行·长城信用卡", "中国银行·银联单币贷记卡", "中国银行·长城信用卡", "中国银行·长城信用卡", "中国银行·长城信用卡", "中国银行·长城电子借记卡",
"中国银行·长城人民币信用卡", "中国银行·银联标准公务卡", "中国银行·一卡双账户普卡", "中国银行·财互通卡", "中国银行·电子现金卡", "中国银行·长城人民币信用卡",
"中国银行·长城单位信用卡普卡", "中国银行·中银女性主题信用卡", "中国银行·长城单位信用卡金卡", "中国银行·白金卡", "中国银行·中职学生资助卡", "中国银行·银联标准卡",
"中国银行·金融IC卡", "中国银行·长城社会保障卡", "中国银行·世界卡", "中国银行·社保联名卡", "中国银行·社保联名卡", "中国银行·医保联名卡", "中国银行·医保联名卡",
"中国银行·公司借记卡", "中国银行·银联美运顶级卡", "中国银行·长城福农借记卡金卡", "中国银行·长城福农借记卡普卡", "中国银行·中行金融IC卡普卡", "中国银行·中行金融IC卡金卡",
"中国银行·中行金融IC卡白金卡", "中国银行·长城银联公务IC卡白金卡", "中国银行·中银旅游信用卡", "中国银行·长城银联公务IC卡金卡", "中国银行·中国旅游卡", "中国银行·武警军人保障卡",
"中国银行·社保联名借记IC卡", "中国银行·社保联名借记IC卡", "中国银行·医保联名借记IC卡", "中国银行·医保联名借记IC卡", "中国银行·借记IC个人普卡", "中国银行·借记IC个人金卡",
"中国银行·借记IC个人普卡", "中国银行·借记IC白金卡", "中国银行·借记IC钻石卡", "中国银行·借记IC联名卡", "中国银行·普通高中学生资助卡", "中国银行·长城环球通港澳台旅游金卡",
"中国银行·长城环球通港澳台旅游白金卡", "中国银行·中银福农信用卡", "中国银行金边分行·借记卡", "中国银行雅加达分行·借记卡", "中国银行首尔分行·借记卡", "中国银行澳门分行·人民币信用卡",
"中国银行澳门分行·人民币信用卡", "中国银行澳门分行·中银卡", "中国银行澳门分行·中银卡", "中国银行澳门分行·中银卡", "中国银行澳门分行·中银银联双币商务卡", "中国银行澳门分行·预付卡",
"中国银行澳门分行·澳门中国银行银联预付卡", "中国银行澳门分行·澳门中国银行银联预付卡", "中国银行澳门分行·熊猫卡", "中国银行澳门分行·财富卡", "中国银行澳门分行·银联港币卡",
"中国银行澳门分行·银联澳门币卡", "中国银行马尼拉分行·双币种借记卡", "中国银行胡志明分行·借记卡", "中国银行曼谷分行·借记卡", "中国银行曼谷分行·长城信用卡环球通", "中国银行曼谷分行·借记卡",
"建设银行·龙卡准贷记卡", "建设银行·龙卡准贷记卡金卡", "建设银行·中职学生资助卡", "建设银行·乐当家银卡VISA", "建设银行·乐当家金卡VISA", "建设银行·乐当家白金卡",
"建设银行·龙卡普通卡VISA", "建设银行·龙卡储蓄卡", "建设银行·VISA准贷记卡(银联卡)", "建设银行·VISA准贷记金卡", "建设银行·乐当家", "建设银行·乐当家",
"建设银行·准贷记金卡", "建设银行·乐当家白金卡", "建设银行·金融复合IC卡", "建设银行·银联标准卡", "建设银行·银联理财钻石卡", "建设银行·金融IC卡", "建设银行·理财白金卡",
"建设银行·社保IC卡", "建设银行·财富卡私人银行卡", "建设银行·理财金卡", "建设银行·福农卡", "建设银行·武警军人保障卡", "建设银行·龙卡通", "建设银行·银联储蓄卡",
"建设银行·龙卡储蓄卡(银联卡)", "建设银行·准贷记卡", "建设银行·理财白金卡", "建设银行·理财金卡", "建设银行·准贷记卡普卡", "建设银行·准贷记卡金卡", "建设银行·龙卡信用卡",
"建设银行·建行陆港通龙卡", "中国建设银行·普通高中学生资助卡", "中国建设银行·中国旅游卡", "中国建设银行·龙卡JCB金卡", "中国建设银行·龙卡JCB白金卡", "中国建设银行·龙卡JCB普卡",
"中国建设银行·龙卡贷记卡公司卡", "中国建设银行·龙卡贷记卡", "中国建设银行·龙卡国际普通卡VISA", "中国建设银行·龙卡国际金卡VISA", "中国建设银行·VISA白金信用卡",
"中国建设银行·龙卡国际白金卡", "中国建设银行·龙卡国际普通卡MASTER", "中国建设银行·龙卡国际金卡MASTER", "中国建设银行·龙卡万事达金卡", "中国建设银行·龙卡贷记卡",
"中国建设银行·龙卡万事达白金卡", "中国建设银行·龙卡贷记卡", "中国建设银行·龙卡万事达信用卡", "中国建设银行·龙卡人民币信用卡", "中国建设银行·龙卡人民币信用金卡",
"中国建设银行·龙卡人民币白金卡", "中国建设银行·龙卡IC信用卡普卡", "中国建设银行·龙卡IC信用卡金卡", "中国建设银行·龙卡IC信用卡白金卡", "中国建设银行·龙卡银联公务卡普卡",
"中国建设银行·龙卡银联公务卡金卡", "中国建设银行·中国旅游卡", "中国建设银行·中国旅游卡", "中国建设银行·龙卡IC公务卡", "中国建设银行·龙卡IC公务卡", "交通银行·交行预付卡",
"交通银行·世博预付IC卡", "交通银行·太平洋互连卡", "交通银行·太平洋万事顺卡", "交通银行·太平洋互连卡(银联卡)", "交通银行·太平洋白金信用卡", "交通银行·太平洋双币贷记卡",
"交通银行·太平洋双币贷记卡", "交通银行·太平洋双币贷记卡", "交通银行·太平洋白金信用卡", "交通银行·太平洋双币贷记卡", "交通银行·太平洋万事顺卡", "交通银行·太平洋人民币贷记卡",
"交通银行·太平洋人民币贷记卡", "交通银行·太平洋双币贷记卡", "交通银行·太平洋准贷记卡", "交通银行·太平洋准贷记卡", "交通银行·太平洋准贷记卡", "交通银行·太平洋准贷记卡",
"交通银行·太平洋借记卡", "交通银行·太平洋借记卡", "交通银行·太平洋人民币贷记卡", "交通银行·太平洋借记卡", "交通银行·太平洋MORE卡", "交通银行·白金卡",
"交通银行·交通银行公务卡普卡", "交通银行·太平洋人民币贷记卡", "交通银行·太平洋互连卡", "交通银行·太平洋借记卡", "交通银行·太平洋万事顺卡", "交通银行·太平洋贷记卡(银联卡)",
"交通银行·太平洋贷记卡(银联卡)", "交通银行·太平洋贷记卡(银联卡)", "交通银行·太平洋贷记卡(银联卡)", "交通银行·交通银行公务卡金卡", "交通银行·交银IC卡",
"交通银行香港分行·交通银行港币借记卡", "交通银行香港分行·港币礼物卡", "交通银行香港分行·双币种信用卡", "交通银行香港分行·双币种信用卡", "交通银行香港分行·双币卡",
"交通银行香港分行·银联人民币卡", "交通银行澳门分行·银联借记卡", "中信银行·中信借记卡", "中信银行·中信借记卡", "中信银行·中信国际借记卡", "中信银行·中信国际借记卡",
"中信银行·中国旅行卡", "中信银行·中信借记卡(银联卡)", "中信银行·中信借记卡(银联卡)", "中信银行·中信贵宾卡(银联卡)", "中信银行·中信理财宝金卡", "中信银行·中信理财宝白金卡",
"中信银行·中信钻石卡", "中信银行·中信钻石卡", "中信银行·中信借记卡", "中信银行·中信理财宝(银联卡)", "中信银行·中信理财宝(银联卡)", "中信银行·中信理财宝(银联卡)",
"中信银行·借记卡", "中信银行·理财宝IC卡", "中信银行·理财宝IC卡", "中信银行·理财宝IC卡", "中信银行·理财宝IC卡", "中信银行·理财宝IC卡", "中信银行·主账户复合电子现金卡",
"光大银行·阳光商旅信用卡", "光大银行·阳光商旅信用卡", "光大银行·阳光商旅信用卡", "光大银行·阳光卡(银联卡)", "光大银行·阳光卡(银联卡)", "光大银行·阳光卡(银联卡)",
"光大银行·阳光卡(银联卡)", "光大银行·阳光卡(银联卡)", "光大银行·阳光卡(银联卡)", "光大银行·阳光卡(银联卡)", "光大银行·阳光卡(银联卡)", "光大银行·阳光卡(银联卡)",
"光大银行·阳光卡(银联卡)", "光大银行·阳光卡(银联卡)", "光大银行·阳光卡(银联卡)", "光大银行·阳光卡(银联卡)", "光大银行·阳光卡(银联卡)", "光大银行·阳光卡(银联卡)",
"光大银行·借记卡普卡", "光大银行·社会保障IC卡", "光大银行·IC借记卡普卡", "光大银行·手机支付卡", "光大银行·联名IC卡普卡", "光大银行·借记IC卡白金卡", "光大银行·借记IC卡金卡",
"光大银行·阳光旅行卡", "光大银行·借记IC卡钻石卡", "光大银行·联名IC卡金卡", "光大银行·联名IC卡白金卡", "光大银行·联名IC卡钻石卡", "华夏银行·华夏卡(银联卡)",
"华夏银行·华夏白金卡", "华夏银行·华夏普卡", "华夏银行·华夏金卡", "华夏银行·华夏白金卡", "华夏银行·华夏钻石卡", "华夏银行·华夏卡(银联卡)", "华夏银行·华夏至尊金卡(银联卡)",
"华夏银行·华夏丽人卡(银联卡)", "华夏银行·华夏万通卡", "民生银行·民生借记卡(银联卡)", "民生银行·民生银联借记卡-金卡", "民生银行·钻石卡", "民生银行·民生借记卡(银联卡)",
"民生银行·民生借记卡(银联卡)", "民生银行·民生借记卡(银联卡)", "民生银行·民生借记卡", "民生银行·民生国际卡", "民生银行·民生国际卡(银卡)", "民生银行·民生国际卡(欧元卡)",
"民生银行·民生国际卡(澳元卡)", "民生银行·民生国际卡", "民生银行·民生国际卡", "民生银行·薪资理财卡", "民生银行·借记卡普卡", "民生银行·民生MasterCard",
"民生银行·民生MasterCard", "民生银行·民生MasterCard", "民生银行·民生MasterCard", "民生银行·民生JCB信用卡", "民生银行·民生JCB金卡",
"民生银行·民生贷记卡(银联卡)", "民生银行·民生贷记卡(银联卡)", "民生银行·民生贷记卡(银联卡)", "民生银行·民生贷记卡(银联卡)", "民生银行·民生贷记卡(银联卡)",
"民生银行·民生JCB普卡", "民生银行·民生贷记卡(银联卡)", "民生银行·民生贷记卡(银联卡)", "民生银行·民生信用卡(银联卡)", "民生银行·民生信用卡(银联卡)",
"民生银行·民生银联白金信用卡", "民生银行·民生贷记卡(银联卡)", "民生银行·民生银联个人白金卡", "民生银行·公务卡金卡", "民生银行·民生贷记卡(银联卡)", "民生银行·民生银联商务信用卡",
"民生银行·民VISA无限卡", "民生银行·民生VISA商务白金卡", "民生银行·民生万事达钛金卡", "民生银行·民生万事达世界卡", "民生银行·民生万事达白金公务卡", "民生银行·民生JCB白金卡",
"民生银行·银联标准金卡", "民生银行·银联芯片普卡", "民生银行·民生运通双币信用卡普卡", "民生银行·民生运通双币信用卡金卡", "民生银行·民生运通双币信用卡钻石卡",
"民生银行·民生运通双币标准信用卡白金卡", "民生银行·银联芯片金卡", "民生银行·银联芯片白金卡", "招商银行·招商银行信用卡", "招商银行·招商银行信用卡", "招商银行·招商银行信用卡",
"招商银行·招商银行信用卡", "招商银行·招商银行信用卡", "招商银行·两地一卡通", "招商银行·招行国际卡(银联卡)", "招商银行·招商银行信用卡", "招商银行·VISA商务信用卡",
"招商银行·招行国际卡(银联卡)", "招商银行·招商银行信用卡", "招商银行·招商银行信用卡", "招商银行·招行国际卡(银联卡)", "招商银行·世纪金花联名信用卡", "招商银行·招行国际卡(银联卡)",
"招商银行·招商银行信用卡", "招商银行·万事达信用卡", "招商银行·万事达信用卡", "招商银行·万事达信用卡", "招商银行·万事达信用卡", "招商银行·招商银行信用卡", "招商银行·招商银行信用卡",
"招商银行·招商银行信用卡", "招商银行·招商银行信用卡", "招商银行·招商银行信用卡", "招商银行·招商银行信用卡", "招商银行·一卡通(银联卡)", "招商银行·万事达信用卡",
"招商银行·招商银行信用卡", "招商银行·招商银行信用卡", "招商银行·一卡通(银联卡)", "招商银行·公司卡(银联卡)", "招商银行·金卡", "招商银行·招行一卡通", "招商银行·招行一卡通",
"招商银行·万事达信用卡", "招商银行·金葵花卡", "招商银行·电子现金卡", "招商银行·银联IC普卡", "招商银行·银联IC金卡", "招商银行·银联金葵花IC卡", "招商银行·IC公务卡",
"招商银行·招商银行信用卡", "招商银行信用卡中心·美国运通绿卡", "招商银行信用卡中心·美国运通金卡", "招商银行信用卡中心·美国运通商务绿卡", "招商银行信用卡中心·美国运通商务金卡",
"招商银行信用卡中心·VISA信用卡", "招商银行信用卡中心·MASTER信用卡", "招商银行信用卡中心·MASTER信用金卡", "招商银行信用卡中心·银联标准公务卡(金卡)",
"招商银行信用卡中心·VISA信用卡", "招商银行信用卡中心·银联标准财政公务卡", "招商银行信用卡中心·芯片IC信用卡", "招商银行信用卡中心·芯片IC信用卡", "招商银行香港分行·香港一卡通",
"兴业银行·兴业卡(银联卡)", "兴业银行·兴业卡(银联标准卡)", "兴业银行·兴业自然人生理财卡", "兴业银行·兴业智能卡(银联卡)", "兴业银行·兴业智能卡", "兴业银行·visa标准双币个人普卡",
"兴业银行·VISA商务普卡", "兴业银行·VISA商务金卡", "兴业银行·VISA运动白金信用卡", "兴业银行·万事达信用卡(银联卡)", "兴业银行·VISA信用卡(银联卡)",
"兴业银行·加菲猫信用卡", "兴业银行·个人白金卡", "兴业银行·银联信用卡(银联卡)", "兴业银行·银联信用卡(银联卡)", "兴业银行·银联白金信用卡", "兴业银行·银联标准公务卡",
"兴业银行·VISA信用卡(银联卡)", "兴业银行·万事达信用卡(银联卡)", "兴业银行·银联标准贷记普卡", "兴业银行·银联标准贷记金卡", "兴业银行·银联标准贷记金卡", "兴业银行·银联标准贷记金卡",
"兴业银行·兴业信用卡", "兴业银行·兴业信用卡", "兴业银行·兴业信用卡", "兴业银行·银联标准贷记普卡", "兴业银行·银联标准贷记普卡", "兴业银行·兴业芯片普卡", "兴业银行·兴业芯片金卡",
"兴业银行·兴业芯片白金卡", "兴业银行·兴业芯片钻石卡", "浦东发展银行·浦发JCB金卡", "浦东发展银行·浦发JCB白金卡", "浦东发展银行·信用卡VISA普通", "浦东发展银行·信用卡VISA金卡",
"浦东发展银行·浦发银行VISA年青卡", "浦东发展银行·VISA白金信用卡", "浦东发展银行·浦发万事达白金卡", "浦东发展银行·浦发JCB普卡", "浦东发展银行·浦发万事达金卡",
"浦东发展银行·浦发万事达普卡", "浦东发展银行·浦发单币卡", "浦东发展银行·浦发银联单币麦兜普卡", "浦东发展银行·东方轻松理财卡", "浦东发展银行·东方-轻松理财卡普卡",
"浦东发展银行·东方轻松理财卡", "浦东发展银行·东方轻松理财智业金卡", "浦东发展银行·东方卡(银联卡)", "浦东发展银行·东方卡(银联卡)", "浦东发展银行·东方卡(银联卡)",
"浦东发展银行·公务卡金卡", "浦东发展银行·公务卡普卡", "浦东发展银行·东方卡", "浦东发展银行·东方卡", "浦东发展银行·浦发单币卡", "浦东发展银行·浦发联名信用卡",
"浦东发展银行·浦发银联白金卡", "浦东发展银行·轻松理财普卡", "浦东发展银行·移动联名卡", "浦东发展银行·轻松理财消贷易卡", "浦东发展银行·轻松理财普卡(复合卡)", "浦东发展银行·贷记卡",
"浦东发展银行·贷记卡", "浦东发展银行·东方借记卡(复合卡)", "浦东发展银行·电子现金卡(IC卡)", "浦东发展银行·移动浦发联名卡", "浦东发展银行·东方-标准准贷记卡",
"浦东发展银行·轻松理财金卡(复合卡)", "浦东发展银行·轻松理财白金卡(复合卡)", "浦东发展银行·轻松理财钻石卡(复合卡)", "浦东发展银行·东方卡", "恒丰银行·九州IC卡",
"恒丰银行·九州借记卡(银联卡)", "恒丰银行·九州借记卡(银联卡)", "天津市商业银行·银联卡(银联卡)", "烟台商业银行·金通卡", "潍坊银行·鸢都卡(银联卡)", "潍坊银行·鸳都卡(银联卡)",
"临沂商业银行·沂蒙卡(银联卡)", "临沂商业银行·沂蒙卡(银联卡)", "日照市商业银行·黄海卡", "日照市商业银行·黄海卡(银联卡)", "浙商银行·商卡", "浙商银行·商卡", "渤海银行·浩瀚金卡",
"渤海银行·渤海银行借记卡", "渤海银行·金融IC卡", "渤海银行·渤海银行公司借记卡", "星展银行·星展银行借记卡", "星展银行·星展银行借记卡", "恒生银行·恒生通财卡",
"恒生银行·恒生优越通财卡", "新韩银行·新韩卡", "上海银行·慧通钻石卡", "上海银行·慧通金卡", "上海银行·私人银行卡", "上海银行·综合保险卡", "上海银行·申卡社保副卡(有折)",
"上海银行·申卡社保副卡(无折)", "上海银行·白金IC借记卡", "上海银行·慧通白金卡(配折)", "上海银行·慧通白金卡(不配折)", "上海银行·申卡(银联卡)", "上海银行·申卡借记卡",
"上海银行·银联申卡(银联卡)", "上海银行·单位借记卡", "上海银行·首发纪念版IC卡", "上海银行·申卡贷记卡", "上海银行·申卡贷记卡", "上海银行·J分期付款信用卡", "上海银行·申卡贷记卡",
"上海银行·申卡贷记卡", "上海银行·上海申卡IC", "上海银行·申卡贷记卡", "上海银行·申卡贷记卡普通卡", "上海银行·申卡贷记卡金卡", "上海银行·万事达白金卡", "上海银行·万事达星运卡",
"上海银行·申卡贷记卡金卡", "上海银行·申卡贷记卡普通卡", "上海银行·安融卡", "上海银行·分期付款信用卡", "上海银行·信用卡", "上海银行·个人公务卡", "上海银行·安融卡",
"上海银行·上海银行银联白金卡", "上海银行·贷记IC卡", "上海银行·中国旅游卡(IC普卡)", "上海银行·中国旅游卡(IC金卡)", "上海银行·中国旅游卡(IC白金卡)", "上海银行·万事达钻石卡",
"上海银行·淘宝IC普卡", "北京银行·京卡借记卡", "北京银行·京卡(银联卡)", "北京银行·京卡借记卡", "北京银行·京卡", "北京银行·京卡", "北京银行·借记IC卡",
"北京银行·京卡贵宾金卡", "北京银行·京卡贵宾白金卡", "吉林银行·君子兰一卡通(银联卡)", "吉林银行·君子兰卡(银联卡)", "吉林银行·长白山金融IC卡", "吉林银行·信用卡",
"吉林银行·信用卡", "吉林银行·公务卡", "镇江市商业银行·金山灵通卡(银联卡)", "镇江市商业银行·金山灵通卡(银联卡)", "宁波银行·银联标准卡", "宁波银行·汇通借记卡",
"宁波银行·汇通卡(银联卡)", "宁波银行·明州卡", "宁波银行·汇通借记卡", "宁波银行·汇通国际卡银联双币卡", "宁波银行·汇通国际卡银联双币卡", "平安银行·新磁条借记卡",
"平安银行·平安银行IC借记卡", "平安银行·万事顺卡", "平安银行·平安银行借记卡", "平安银行·平安银行借记卡", "平安银行·万事顺借记卡", "焦作市商业银行·月季借记卡(银联卡)",
"焦作市商业银行·月季城市通(银联卡)", "焦作市商业银行·中国旅游卡", "温州银行·金鹿卡", "汉口银行·九通卡(银联卡)", "汉口银行·九通卡", "汉口银行·借记卡", "汉口银行·借记卡",
"盛京银行·玫瑰卡", "盛京银行·玫瑰IC卡", "盛京银行·玫瑰IC卡", "盛京银行·玫瑰卡", "盛京银行·玫瑰卡", "盛京银行·玫瑰卡(银联卡)", "盛京银行·玫瑰卡(银联卡)",
"盛京银行·盛京银行公务卡", "洛阳银行·都市一卡通(银联卡)", "洛阳银行·都市一卡通(银联卡)", "洛阳银行·--", "大连银行·北方明珠卡", "大连银行·人民币借记卡",
"大连银行·金融IC借记卡", "大连银行·大连市社会保障卡", "大连银行·借记IC卡", "大连银行·借记IC卡", "大连银行·大连市商业银行贷记卡", "大连银行·大连市商业银行贷记卡",
"大连银行·银联标准公务卡", "苏州市商业银行·姑苏卡", "杭州商业银行·西湖卡", "杭州商业银行·西湖卡", "杭州商业银行·借记IC卡", "杭州商业银行·", "南京银行·梅花信用卡公务卡",
"南京银行·梅花信用卡商务卡", "南京银行·梅花贷记卡(银联卡)", "南京银行·梅花借记卡(银联卡)", "南京银行·白金卡", "南京银行·商务卡", "东莞市商业银行·万顺通卡(银联卡)",
"东莞市商业银行·万顺通卡(银联卡)", "东莞市商业银行·万顺通借记卡", "东莞市商业银行·社会保障卡", "乌鲁木齐市商业银行·雪莲借记IC卡", "乌鲁木齐市商业银行·乌鲁木齐市公务卡",
"乌鲁木齐市商业银行·福农卡贷记卡", "乌鲁木齐市商业银行·福农卡准贷记卡", "乌鲁木齐市商业银行·雪莲准贷记卡", "乌鲁木齐市商业银行·雪莲贷记卡(银联卡)", "乌鲁木齐市商业银行·雪莲借记IC卡",
"乌鲁木齐市商业银行·雪莲借记卡(银联卡)", "乌鲁木齐市商业银行·雪莲卡(银联卡)", "绍兴银行·兰花IC借记卡", "绍兴银行·社保IC借记卡", "绍兴银行·兰花公务卡",
"成都商业银行·芙蓉锦程福农卡", "成都商业银行·芙蓉锦程天府通卡", "成都商业银行·锦程卡(银联卡)", "成都商业银行·锦程卡金卡", "成都商业银行·锦程卡定活一卡通金卡",
"成都商业银行·锦程卡定活一卡通", "成都商业银行·锦程力诚联名卡", "成都商业银行·锦程力诚联名卡", "成都商业银行·锦程卡(银联卡)", "抚顺银行·借记IC卡", "临商银行·借记卡",
"宜昌市商业银行·三峡卡(银联卡)", "宜昌市商业银行·信用卡(银联卡)", "葫芦岛市商业银行·一通卡", "葫芦岛市商业银行·一卡通(银联卡)", "天津市商业银行·津卡",
"天津市商业银行·津卡贷记卡(银联卡)", "天津市商业银行·贷记IC卡", "天津市商业银行·--", "天津银行·商务卡", "宁夏银行·宁夏银行公务卡", "宁夏银行·宁夏银行福农贷记卡",
"宁夏银行·如意卡(银联卡)", "宁夏银行·宁夏银行福农借记卡", "宁夏银行·如意借记卡", "宁夏银行·如意IC卡", "宁夏银行·宁夏银行如意借记卡", "宁夏银行·中国旅游卡",
"齐商银行·金达卡(银联卡)", "齐商银行·金达借记卡(银联卡)", "齐商银行·金达IC卡", "徽商银行·黄山卡", "徽商银行·黄山卡", "徽商银行·借记卡", "徽商银行·徽商银行中国旅游卡(安徽)",
"徽商银行合肥分行·黄山卡", "徽商银行芜湖分行·黄山卡(银联卡)", "徽商银行马鞍山分行·黄山卡(银联卡)", "徽商银行淮北分行·黄山卡(银联卡)", "徽商银行安庆分行·黄山卡(银联卡)",
"重庆银行·长江卡(银联卡)", "重庆银行·长江卡(银联卡)", "重庆银行·长江卡", "重庆银行·借记IC卡", "哈尔滨银行·丁香一卡通(银联卡)", "哈尔滨银行·丁香借记卡(银联卡)",
"哈尔滨银行·丁香卡", "哈尔滨银行·福农借记卡", "无锡市商业银行·太湖金保卡(银联卡)", "丹东银行·借记IC卡", "丹东银行·丹东银行公务卡", "兰州银行·敦煌卡", "南昌银行·金瑞卡(银联卡)",
"南昌银行·南昌银行借记卡", "南昌银行·金瑞卡", "晋商银行·晋龙一卡通", "晋商银行·晋龙一卡通", "晋商银行·晋龙卡(银联卡)", "青岛银行·金桥通卡", "青岛银行·金桥卡(银联卡)",
"青岛银行·金桥卡(银联卡)", "青岛银行·金桥卡", "青岛银行·借记IC卡", "吉林银行·雾凇卡(银联卡)", "吉林银行·雾凇卡(银联卡)", "南通商业银行·金桥卡(银联卡)",
"南通商业银行·金桥卡(银联卡)", "日照银行·黄海卡、财富卡借记卡", "鞍山银行·千山卡(银联卡)", "鞍山银行·千山卡(银联卡)", "鞍山银行·千山卡", "青海银行·三江银行卡(银联卡)",
"青海银行·三江卡", "台州银行·大唐贷记卡", "台州银行·大唐准贷记卡", "台州银行·大唐卡(银联卡)", "台州银行·大唐卡", "台州银行·借记卡", "台州银行·公务卡",
"泉州银行·海峡银联卡(银联卡)", "泉州银行·海峡储蓄卡", "泉州银行·海峡银联卡(银联卡)", "泉州银行·海峡卡", "泉州银行·公务卡", "昆明商业银行·春城卡(银联卡)",
"昆明商业银行·春城卡(银联卡)", "昆明商业银行·富滇IC卡(复合卡)", "阜新银行·借记IC卡", "嘉兴银行·南湖借记卡(银联卡)", "廊坊银行·白金卡", "廊坊银行·金卡",
"廊坊银行·银星卡(银联卡)", "廊坊银行·龙凤呈祥卡", "内蒙古银行·百灵卡(银联卡)", "内蒙古银行·成吉思汗卡", "湖州市商业银行·百合卡", "湖州市商业银行·", "沧州银行·狮城卡",
"南宁市商业银行·桂花卡(银联卡)", "包商银行·雄鹰卡(银联卡)", "包商银行·包头市商业银行借记卡", "包商银行·雄鹰贷记卡", "包商银行·包商银行内蒙古自治区公务卡", "包商银行·贷记卡",
"包商银行·借记卡", "连云港市商业银行·金猴神通借记卡", "威海商业银行·通达卡(银联卡)", "威海市商业银行·通达借记IC卡", "攀枝花市商业银行·攀枝花卡(银联卡)", "攀枝花市商业银行·攀枝花卡",
"绵阳市商业银行·科技城卡(银联卡)", "泸州市商业银行·酒城卡(银联卡)", "泸州市商业银行·酒城IC卡", "大同市商业银行·云冈卡(银联卡)", "三门峡银行·天鹅卡(银联卡)",
"广东南粤银行·南珠卡(银联卡)", "张家口市商业银行·好运IC借记卡", "桂林市商业银行·漓江卡(银联卡)", "龙江银行·福农借记卡", "龙江银行·联名借记卡", "龙江银行·福农借记卡",
"龙江银行·龙江IC卡", "龙江银行·社会保障卡", "龙江银行·--", "江苏长江商业银行·长江卡", "徐州市商业银行·彭城借记卡(银联卡)", "南充市商业银行·借记IC卡",
"南充市商业银行·熊猫团团卡", "莱商银行·银联标准卡", "莱芜银行·金凤卡", "莱商银行·借记IC卡", "德阳银行·锦程卡定活一卡通", "德阳银行·锦程卡定活一卡通金卡",
"德阳银行·锦程卡定活一卡通", "唐山市商业银行·唐山市城通卡", "曲靖市商业银行·珠江源卡", "曲靖市商业银行·珠江源IC卡", "温州银行·金鹿信用卡", "温州银行·金鹿信用卡",
"温州银行·金鹿公务卡", "温州银行·贷记IC卡", "汉口银行·汉口银行贷记卡", "汉口银行·汉口银行贷记卡", "汉口银行·九通香港旅游贷记普卡", "汉口银行·九通香港旅游贷记金卡",
"汉口银行·贷记卡", "汉口银行·九通公务卡", "江苏银行·聚宝借记卡", "江苏银行·月季卡", "江苏银行·紫金卡", "江苏银行·绿扬卡(银联卡)", "江苏银行·月季卡(银联卡)",
"江苏银行·九州借记卡(银联卡)", "江苏银行·月季卡(银联卡)", "江苏银行·聚宝惠民福农卡", "江苏银行·江苏银行聚宝IC借记卡", "江苏银行·聚宝IC借记卡VIP卡",
"长治市商业银行·长治商行银联晋龙卡", "承德市商业银行·热河卡", "承德银行·借记IC卡", "德州银行·长河借记卡", "德州银行·--", "遵义市商业银行·社保卡", "遵义市商业银行·尊卡",
"邯郸市商业银行·邯银卡", "邯郸市商业银行·邯郸银行贵宾IC借记卡", "安顺市商业银行·黄果树福农卡", "安顺市商业银行·黄果树借记卡", "江苏银行·紫金信用卡(公务卡)", "江苏银行·紫金信用卡",
"江苏银行·天翼联名信用卡", "平凉市商业银行·广成卡", "玉溪市商业银行·红塔卡", "玉溪市商业银行·红塔卡", "浙江民泰商业银行·金融IC卡", "浙江民泰商业银行·民泰借记卡",
"浙江民泰商业银行·金融IC卡C卡", "浙江民泰商业银行·银联标准普卡金卡", "浙江民泰商业银行·商惠通", "上饶市商业银行·三清山卡", "东营银行·胜利卡", "泰安市商业银行·岱宗卡",
"泰安市商业银行·市民一卡通", "浙江稠州商业银行·义卡", "浙江稠州商业银行·义卡借记IC卡", "浙江稠州商业银行·公务卡", "自贡市商业银行·借记IC卡", "自贡市商业银行·锦程卡",
"鄂尔多斯银行·天骄公务卡", "鹤壁银行·鹤卡", "许昌银行·连城卡", "铁岭银行·龙凤卡", "乐山市商业银行·大福卡", "乐山市商业银行·--", "长安银行·长长卡", "长安银行·借记IC卡",
"重庆三峡银行·财富人生卡", "重庆三峡银行·借记卡", "石嘴山银行·麒麟借记卡", "石嘴山银行·麒麟借记卡", "石嘴山银行·麒麟公务卡", "盘锦市商业银行·鹤卡",
"盘锦市商业银行·盘锦市商业银行鹤卡", "平顶山银行·平顶山银行公务卡", "朝阳银行·鑫鑫通卡", "朝阳银行·朝阳银行福农卡", "朝阳银行·红山卡", "宁波东海银行·绿叶卡", "遂宁市商业银行·锦程卡",
"遂宁是商业银行·金荷卡", "保定银行·直隶卡", "保定银行·直隶卡", "凉山州商业银行·锦程卡", "凉山州商业银行·金凉山卡", "漯河银行·福卡", "漯河银行·福源卡", "漯河银行·福源公务卡",
"达州市商业银行·锦程卡", "新乡市商业银行·新卡", "晋中银行·九州方圆借记卡", "晋中银行·九州方圆卡", "驻马店银行·驿站卡", "驻马店银行·驿站卡", "驻马店银行·公务卡",
"衡水银行·金鼎卡", "衡水银行·借记IC卡", "周口银行·如愿卡", "周口银行·公务卡", "阳泉市商业银行·金鼎卡", "阳泉市商业银行·金鼎卡", "宜宾市商业银行·锦程卡",
"宜宾市商业银行·借记IC卡", "库尔勒市商业银行·孔雀胡杨卡", "雅安市商业银行·锦城卡", "雅安市商业银行·--", "安阳银行·安鼎卡", "信阳银行·信阳卡", "信阳银行·公务卡",
"信阳银行·信阳卡", "华融湘江银行·华融卡", "华融湘江银行·华融卡", "营口沿海银行·祥云借记卡", "景德镇商业银行·瓷都卡", "哈密市商业银行·瓜香借记卡", "湖北银行·金牛卡",
"湖北银行·汉江卡", "湖北银行·借记卡", "湖北银行·三峡卡", "湖北银行·至尊卡", "湖北银行·金融IC卡", "西藏银行·借记IC卡", "新疆汇和银行·汇和卡", "广东华兴银行·借记卡",
"广东华兴银行·华兴银联公司卡", "广东华兴银行·华兴联名IC卡", "广东华兴银行·华兴金融IC借记卡", "濮阳银行·龙翔卡", "宁波通商银行·借记卡", "甘肃银行·神舟兴陇借记卡",
"甘肃银行·甘肃银行神州兴陇IC卡", "枣庄银行·借记IC卡", "本溪市商业银行·借记卡", "盛京银行·医保卡", "上海农商银行·如意卡(银联卡)", "上海农商银行·如意卡(银联卡)",
"上海农商银行·鑫通卡", "上海农商银行·国际如意卡", "上海农商银行·借记IC卡", "常熟市农村商业银行·粒金贷记卡(银联卡)", "常熟市农村商业银行·公务卡", "常熟市农村商业银行·粒金准贷卡",
"常熟农村商业银行·粒金借记卡(银联卡)", "常熟农村商业银行·粒金IC卡", "常熟农村商业银行·粒金卡", "深圳农村商业银行·信通卡(银联卡)", "深圳农村商业银行·信通商务卡(银联卡)",
"深圳农村商业银行·信通卡", "深圳农村商业银行·信通商务卡", "广州农村商业银行·福农太阳卡", "广东南海农村商业银行·盛通卡", "广东南海农村商业银行·盛通卡(银联卡)",
"佛山顺德农村商业银行·恒通卡(银联卡)", "佛山顺德农村商业银行·恒通卡", "佛山顺德农村商业银行·恒通卡(银联卡)", "江阴农村商业银行·暨阳公务卡", "江阴市农村商业银行·合作贷记卡(银联卡)",
"江阴农村商业银行·合作借记卡", "江阴农村商业银行·合作卡(银联卡)", "江阴农村商业银行·暨阳卡", "重庆农村商业银行·江渝借记卡VIP卡", "重庆农村商业银行·江渝IC借记卡",
"重庆农村商业银行·江渝乡情福农卡", "东莞农村商业银行·信通卡(银联卡)", "东莞农村商业银行·信通卡(银联卡)", "东莞农村商业银行·信通信用卡", "东莞农村商业银行·信通借记卡",
"东莞农村商业银行·贷记IC卡", "张家港农村商业银行·一卡通(银联卡)", "张家港农村商业银行·一卡通(银联卡)", "张家港农村商业银行·", "北京农村商业银行·信通卡", "北京农村商业银行·惠通卡",
"北京农村商业银行·凤凰福农卡", "北京农村商业银行·惠通卡", "北京农村商业银行·中国旅行卡", "北京农村商业银行·凤凰卡", "天津农村商业银行·吉祥商联IC卡",
"天津农村商业银行·信通借记卡(银联卡)", "天津农村商业银行·借记IC卡", "鄞州农村合作银行·蜜蜂借记卡(银联卡)", "宁波鄞州农村合作银行·蜜蜂电子钱包(IC)",
"宁波鄞州农村合作银行·蜜蜂IC借记卡", "宁波鄞州农村合作银行·蜜蜂贷记IC卡", "宁波鄞州农村合作银行·蜜蜂贷记卡", "宁波鄞州农村合作银行·公务卡", "成都农村商业银行·福农卡",
"成都农村商业银行·福农卡", "珠海农村商业银行·信通卡(银联卡)", "太仓农村商业银行·郑和卡(银联卡)", "太仓农村商业银行·郑和IC借记卡", "无锡农村商业银行·金阿福",
"无锡农村商业银行·借记IC卡", "黄河农村商业银行·黄河卡", "黄河农村商业银行·黄河富农卡福农卡", "黄河农村商业银行·借记IC卡", "天津滨海农村商业银行·四海通卡",
"天津滨海农村商业银行·四海通e芯卡", "武汉农村商业银行·汉卡", "武汉农村商业银行·汉卡", "武汉农村商业银行·中国旅游卡", "江南农村商业银行·阳湖卡(银联卡)", "江南农村商业银行·天天红火卡",
"江南农村商业银行·借记IC卡", "海口联合农村商业银行·海口联合农村商业银行合卡", "湖北嘉鱼吴江村镇银行·垂虹卡", "福建建瓯石狮村镇银行·玉竹卡", "浙江平湖工银村镇银行·金平卡",
"重庆璧山工银村镇银行·翡翠卡", "重庆农村商业银行·银联标准贷记卡", "重庆农村商业银行·公务卡", "南阳村镇银行·玉都卡", "晋中市榆次融信村镇银行·魏榆卡", "三水珠江村镇银行·珠江太阳卡",
"东营莱商村镇银行·绿洲卡", "建设银行·单位结算卡", "玉溪市商业银行·红塔卡" };
/**
* 根据银行卡号获取银行信息
* @param bankCard 银行卡号
* @return
*/
public static final String getBankCard(String bankCard){
//检测是否为空
if(bankCard==null||"".equals(bankCard)){
throw null;
}
//检测是否是银行卡
boolean isBankCard = ValidateUtils.isBankCard(bankCard);
if(!isBankCard){
return null;
}
//获取前六位
String preCode = bankCard.substring(0, 6);
System.out.println("银行卡号前六位: "+preCode);
int index = 0;
for (int i = 0; i < bankBin.length; i++) {
if (preCode.equals(bankBin[i])) {
index = i;
break;
}
}
if (index == 0) {
System.out.println("NOT FOUND");
return null;
}
return bankName[index];
}
public static void main(String[] args) {
String bankCard = getBankCard("4581240916299457");
System.out.println(bankCard);
}
}
| apache-2.0 |
geraldox100/gerador_de_vo | src/test/java/br/com/geraldoferraz/geradordevo/entidades/HierarquiaVO.java | 84 | package br.com.geraldoferraz.geradordevo.entidades;
public class HierarquiaVO {
}
| apache-2.0 |
FantasyLWX/LuLuTong | app/src/main/java/com/fantasy/lulutong/activity/me/InformActivity.java | 1158 | package com.fantasy.lulutong.activity.me;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.RelativeLayout;
import com.fantasy.lulutong.R;
import com.fantasy.lulutong.activity.BaseActivity;
import com.fantasy.lulutong.util.ActivityCollector;
/**
* “通知”的页面
* @author Fantasy
* @version 1.0, 2017-02-
*/
public class InformActivity extends BaseActivity implements View.OnClickListener {
private RelativeLayout relativeBack;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.layout_inform);
relativeBack = (RelativeLayout) findViewById(R.id.relative_inform_back);
relativeBack.setOnClickListener(this);
}
@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.relative_inform_back:
finish();
break;
/*case :
break;*/
default:
break;
}
}
}
| apache-2.0 |
Esri/vehicle-commander-java | source/VehicleCommander/src/com/esri/vehiclecommander/controller/AppConfigController.java | 31197 | /*******************************************************************************
* Copyright 2012-2015 Esri
*
* 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.esri.vehiclecommander.controller;
import com.esri.core.geometry.AngularUnit;
import com.esri.militaryapps.controller.LocationController.LocationMode;
import com.esri.militaryapps.controller.MessageController;
import java.io.File;
import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.HashSet;
import java.util.Set;
import java.util.UUID;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.prefs.Preferences;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;
/**
* A controller for application configuration settings. For example, this class
* manages settings used for sending position reports to other users.
*/
public class AppConfigController {
private static final String KEY_USERNAME = AppConfigController.class.getSimpleName() + "username";
private static final String KEY_VEHICLE_TYPE = AppConfigController.class.getSimpleName() + "vehicleType";
private static final String KEY_UNIQUE_ID = AppConfigController.class.getSimpleName() + "uniqueId";
private static final String KEY_SIC = AppConfigController.class.getSimpleName() + "sic";
private static final String KEY_PORT = AppConfigController.class.getSimpleName() + "port";
private static final String KEY_POSITION_MESSAGE_INTERVAL = AppConfigController.class.getSimpleName() + "positionMessageInterval";
private static final String KEY_VEHICLE_STATUS_MESSAGE_INTERVAL = AppConfigController.class.getSimpleName() + "vehicleStatusMessageInterval";
private static final String KEY_GPS_TYPE = AppConfigController.class.getSimpleName() + "gpsType";
private static final String KEY_GPX = AppConfigController.class.getSimpleName() + "gpx";
private static final String KEY_SPEED_MULTIPLIER = AppConfigController.class.getSimpleName() + "speedMultiplier";
private static final String KEY_MPK_CHOOSER_DIR = AppConfigController.class.getSimpleName() + "mpkFileChooserDirectory";
private static final String KEY_GPX_CHOOSER_DIR = AppConfigController.class.getSimpleName() + "gpxFileChooserDirectory";
private static final String KEY_SHOW_MESSAGE_LABELS = AppConfigController.class.getSimpleName() + "showMessageLabels";
private static final String KEY_DECORATED = AppConfigController.class.getSimpleName() + "decorated";
private static final String KEY_SHOW_MGRS_GRID = AppConfigController.class.getSimpleName() + "showMgrsGrid";
private static final String KEY_SHOW_LOCAL_TIME_ZONE = AppConfigController.class.getSimpleName() + "showLocalTimeZone";
private static final String KEY_MGRS_COORDINATE_NOTATION = AppConfigController.class.getSimpleName() + "useMgrs";
private static final String KEY_HEADING_UNITS = AppConfigController.class.getSimpleName() + "headingUnits";
private static final String KEY_GEOMESSAGE_VERSION = AppConfigController.class.getSimpleName() + "geomessageVersion";
private boolean gpsTypeDirty = false;
/**
* @param messageController the messageController to set
*/
public void setMessageController(MessageController messageController) {
this.messageController = messageController;
if (null != messageController && -1 != getPort()) {
messageController.setPort(getPort());
}
}
public MessageController getMessageController() {
return messageController;
}
private class AppConfigHandler extends DefaultHandler {
private String username = null;
private String vehicleType = null;
private String uniqueId = null;
private String sic = null;
private int port = -1;
private int positionMessageInterval = -1;
private int vehicleStatusMessageInterval = -1;
private LocationMode gpsType = LocationMode.SIMULATOR;
private String gpx = null;
private double speedMultiplier = -1;
private int headingUnits = AngularUnit.Code.DEGREE;
private String geomessageVersion = "1.1";
private boolean readingUser = false;
private boolean readingCode = false;
private boolean readingMessaging = false;
private boolean readingPort = false;
private boolean readingPositionMessageInterval = false;
private boolean readingVehicleStatusMessageInterval = false;
private boolean readingGps = false;
@Override
public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException {
if ("user".equalsIgnoreCase(qName)) {
readingUser = true;
username = attributes.getValue("name");
vehicleType = attributes.getValue("type");
uniqueId = attributes.getValue("id");
} else if (readingUser) {
if ("code".equalsIgnoreCase(qName)) {
readingCode = true;
}
} else if ("messaging".equalsIgnoreCase(qName)) {
readingMessaging = true;
} else if (readingMessaging) {
if ("port".equalsIgnoreCase(qName)) {
readingPort = true;
} else if ("interval".equalsIgnoreCase(qName) || "positionmessageinterval".equalsIgnoreCase(qName)) {
//Vehicle Commander 1.0 used "interval" instead of "positionmessageinterval"; accept either one
readingPositionMessageInterval = true;
} else if ("vehiclestatusmessageinterval".equalsIgnoreCase(qName)) {
readingVehicleStatusMessageInterval = true;
}
} else if ("gps".equalsIgnoreCase(qName)) {
readingGps = true;
gpsType = "onboard".equalsIgnoreCase(attributes.getValue("type"))
? LocationMode.LOCATION_SERVICE : LocationMode.SIMULATOR;
gpx = attributes.getValue("gpx");
String speedMultiplierString = attributes.getValue("speedMultiplier");
if (null != speedMultiplierString) {
try {
speedMultiplier = Double.parseDouble(speedMultiplierString);
} catch (Throwable t) {}
}
}
}
@Override
public void characters(char[] ch, int start, int length) throws SAXException {
String value = new String(ch, start, length);
if (readingCode) {
sic = value;
} else {
try {
int intValue = Integer.parseInt(value);
if (readingPort) {
port = intValue;
} else if (readingPositionMessageInterval) {
positionMessageInterval = intValue;
} else if (readingVehicleStatusMessageInterval) {
vehicleStatusMessageInterval = intValue;
}
} catch (NumberFormatException nfe) {
}
}
}
@Override
public void endElement(String uri, String localName, String qName) throws SAXException {
if ("user".equalsIgnoreCase(qName)) {
readingUser = false;
} else if ("code".equalsIgnoreCase(qName)) {
readingCode = false;
} else if ("messaging".equalsIgnoreCase(qName)) {
readingMessaging = false;
} else if ("port".equalsIgnoreCase(qName)) {
readingPort = false;
} else if ("interval".equalsIgnoreCase(qName) || "positionmessageinterval".equalsIgnoreCase(qName)) {
//Vehicle Commander 1.0 used "interval" instead of "positionmessageinterval"; accept either one
readingPositionMessageInterval = false;
} else if ("vehiclestatusmessageinterval".equalsIgnoreCase(qName)) {
readingVehicleStatusMessageInterval = false;
} else if ("gps".equalsIgnoreCase(qName)) {
readingGps = false;
}
}
}
private final Preferences preferences;
private final Set<AppConfigListener> listeners = new HashSet<AppConfigListener>();
private LocationController locationController;
private MessageController messageController;
/**
* Creates a new AppConfigController. This constructor first reads the user's
* settings from the system. Then, if appconfig.xml is present in the working
* directory, any settings not present in the user profile will be read from
* appconfig.xml.
*/
public AppConfigController() {
preferences = Preferences.userNodeForPackage(getClass());
try {
resetFromAppConfigFile(false);
} catch (ParserConfigurationException ex) {
Logger.getLogger(AppConfigController.class.getName()).log(Level.SEVERE, null, ex);
} catch (SAXException ex) {
Logger.getLogger(AppConfigController.class.getName()).log(Level.SEVERE, null, ex);
} catch (IOException ex) {
Logger.getLogger(AppConfigController.class.getName()).log(Level.SEVERE, null, ex);
} catch (URISyntaxException ex) {
Logger.getLogger(AppConfigController.class.getName()).log(Level.SEVERE, null, ex);
}
}
public void addListener(AppConfigListener listener) {
listeners.add(listener);
}
/**
* Returns the file that will be read when resetting application configuration
* settings. This file may or may not actually exist.
* @return the file that will be read when resetting application configuration
* settings.
*/
private URI getAppConfigFileUri() throws URISyntaxException {
File configFile = new File("./appconfig.xml");
if (configFile.exists()) {
return configFile.toURI();
} else {
return getClass().getResource("/com/esri/vehiclecommander/resources/appconfig.xml").toURI();
}
}
/**
* Resets application configuration settings by reading appconfig.xml found
* in the working directory.
* @param overwriteExistingSettings true if settings that are present should
* be overwritten; false if settings that
* are present should not be overwritten
*/
public final void resetFromAppConfigFile(boolean overwriteExistingSettings) throws ParserConfigurationException, SAXException, IOException, URISyntaxException {
if (overwriteExistingSettings || null == getUsername() || null == getUniqueId()
|| null == getVehicleType()
|| null == getGpsType() || null == getGpx() || 0 >= getSpeedMultiplier()
|| null == getSic() || -1 == getPort() || -1 == getPositionMessageInterval()
|| -1 == getVehicleStatusMessageInterval()) {
AppConfigHandler handler = new AppConfigHandler();
SAXParser parser = SAXParserFactory.newInstance().newSAXParser();
parser.parse(getAppConfigFileUri().toString(), handler);
if (overwriteExistingSettings || null == getUsername()) {
setUsername(handler.username);
}
if (overwriteExistingSettings || null == getVehicleType()) {
setVehicleType(handler.vehicleType);
}
if (overwriteExistingSettings || null == getUniqueId()) {
setUniqueId(handler.uniqueId);
}
if (overwriteExistingSettings || null == getSic()) {
setSic(handler.sic);
}
if (overwriteExistingSettings || -1 == getPort()) {
setPort(handler.port);
}
if (overwriteExistingSettings || -1 == getPositionMessageInterval()) {
setPositionMessageInterval(handler.positionMessageInterval);
}
if (overwriteExistingSettings || -1 == getVehicleStatusMessageInterval()) {
setVehicleStatusMessageInterval(handler.vehicleStatusMessageInterval);
}
if (overwriteExistingSettings || null == getGpsType()) {
setLocationMode(handler.gpsType, false);
}
if (overwriteExistingSettings || null == getGpx()) {
setGpx(handler.gpx, false);
}
if (overwriteExistingSettings || -1 == getSpeedMultiplier()) {
setSpeedMultiplier(handler.speedMultiplier);
}
if (overwriteExistingSettings || null == getGeomessageVersion()) {
setGeomessageVersion(handler.geomessageVersion);
}
resetLocationController();
}
}
private void setPreference(String key, String value) {
if (null != key) {
if (null == value) {
preferences.remove(key);
} else {
preferences.put(key, value);
}
}
}
private void setPreference(String key, int value) {
preferences.putInt(key, value);
}
private void setPreference(String key, double value) {
preferences.putDouble(key, value);
}
private void setPreference(String key, boolean value) {
preferences.putBoolean(key, value);
}
/**
* Saves the specified username to the application configuration settings.
* @param username the username, or null to erase the setting.
*/
public void setUsername(String username) {
setPreference(KEY_USERNAME, username);
}
/**
* Returns the stored username, or null if no username has been set.
* @return the stored username, or null if no username has been set.
*/
public final String getUsername() {
return preferences.get(KEY_USERNAME, null);
}
/**
* Saves the specified vehicle type to the application configuration settings.
* @param vehicleType the vehicle type, or null to erase the setting.
*/
public void setVehicleType(String vehicleType) {
setPreference(KEY_VEHICLE_TYPE, vehicleType);
}
/**
* Returns the stored vehicle type, or null if no vehicle type has been set.
* @return the stored vehicle type, or null if no vehicle type has been set.
*/
public final String getVehicleType() {
return preferences.get(KEY_VEHICLE_TYPE, null);
}
/**
* Saves the specified unique ID to the application configuration settings.
* Normally this is a UUID/GUID.
* @param uniqueId the unique ID. Unique ID cannot be null, so if uniqueId parameter
* is null, the unique ID will be set to a new random GUID.
*/
public void setUniqueId(String uniqueId) {
if (null == uniqueId) {
uniqueId = UUID.randomUUID().toString();
}
setPreference(KEY_UNIQUE_ID, uniqueId);
}
/**
* Returns the stored unique ID. If no ID has been set, a new ID will be generated.
* @return the stored unique ID. If no ID has been set, a new ID will be generated.
*/
public final String getUniqueId() {
String uniqueId = preferences.get(KEY_UNIQUE_ID, null);
if (null == uniqueId) {
uniqueId = UUID.randomUUID().toString();
setUniqueId(uniqueId);
}
return uniqueId;
}
/**
* Saves the specified symbol ID code to the application configuration settings.
* @param sic the symbol ID code, or null to erase the setting.
*/
public void setSic(String sic) {
setPreference(KEY_SIC, sic);
}
/**
* Returns the stored symbol ID code, or null if no symbol ID code has been set.
* @return the stored symbol ID code, or null if no symbol ID code has been set.
*/
public final String getSic() {
return preferences.get(KEY_SIC, null);
}
/**
* Saves the specified UDP port number for messaging to the application configuration settings.
* @param port the messaging port number.
* @throws IllegalArgumentException if port is less than 0 or more than 0xFFFF.
*/
public void setPort(int port) throws IllegalArgumentException {
if (port < 0 || port > 0xFFFF) {
//Invalid port number; do nothing
Logger.getLogger(AppConfigController.class.getName()).log(Level.WARNING, "Invalid port number: {0}", port);
} else {
setPreference(KEY_PORT, port);
if (null != messageController) {
messageController.setPort(port);
}
}
}
/**
* Returns the stored UDP port number for messaging, or -1 if no port number has been set.
* @return the stored UDP port number for messaging, or -1 if no port number has been set.
*/
public final int getPort() {
return preferences.getInt(KEY_PORT, -1);
}
/**
* Saves the specified position message interval, in milliseconds, to the application configuration settings.
* @param positionMessageInterval the position message interval, in milliseconds.
*/
public void setPositionMessageInterval(int positionMessageInterval) {
setPreference(KEY_POSITION_MESSAGE_INTERVAL, positionMessageInterval);
}
/**
* Returns the stored position message interval, in milliseconds, or -1 if no messaging interval has been set.
* @return the stored position message interval, in milliseconds, or -1 if no messaging interval has been set.
*/
public final int getPositionMessageInterval() {
return preferences.getInt(KEY_POSITION_MESSAGE_INTERVAL, -1);
}
/**
* Saves the specified vehicle status message interval, in milliseconds, to the application configuration settings.
* @param vehicleStatusMessageInterval the vehicle status message interval, in milliseconds.
*/
public void setVehicleStatusMessageInterval(int vehicleStatusMessageInterval) {
setPreference(KEY_VEHICLE_STATUS_MESSAGE_INTERVAL, vehicleStatusMessageInterval);
}
/**
* Returns the stored vehicle status message interval, in milliseconds, or -1 if no messaging interval has been set.
* @return the stored vehicle status message interval, in milliseconds, or -1 if no messaging interval has been set.
*/
public final int getVehicleStatusMessageInterval() {
return preferences.getInt(KEY_VEHICLE_STATUS_MESSAGE_INTERVAL, -1);
}
/**
* Saves the GPS type to the application configuration settings.
* @deprecated use setLocationMode instead.
* @param locationMode the location mode.
*/
public void setGpsType(LocationMode locationMode) throws ParserConfigurationException, SAXException, IOException {
setLocationMode(locationMode);
}
/**
* Saves the location mode to the application configuration settings.
* @param locationMode the location mode.
*/
public void setLocationMode(LocationMode locationMode) throws ParserConfigurationException, SAXException, IOException {
setLocationMode(locationMode, true);
}
private void setLocationMode(LocationMode locationMode, boolean resetNow) throws ParserConfigurationException, SAXException, IOException {
LocationMode oldMode = getLocationMode();
setPreference(KEY_GPS_TYPE, locationMode.toString());
if (null == oldMode || !oldMode.equals(locationMode)) {
gpsTypeDirty = true;
if (resetNow) {
resetLocationController();
}
}
}
private void resetLocationController() throws ParserConfigurationException, SAXException, IOException {
if (null != locationController) {
locationController.pause();
locationController.reset();
if (getLocationMode().equals(LocationMode.SIMULATOR)) {
locationController.setGpxFile(null == getGpx() ? null : new File(getGpx()));
}
locationController.setMode(getLocationMode(), false);
gpsTypeDirty = false;
locationController.start();
}
}
/**
* Returns the GPS type.
* @return the GPS type.
* @deprecated use getLocationMode() instead.
*/
public LocationMode getGpsType() {
return getLocationMode();
}
public LocationMode getLocationMode() {
String name = preferences.get(KEY_GPS_TYPE, null);
if (null == name) {
return null;
} else {
try {
return LocationMode.valueOf(name);
} catch (Throwable t) {
return null;
}
}
}
/**
* Saves the GPX file to be used for simulated GPS to the application configuration settings.
* @param gpx the GPX file to be used for simulated GPS.
*/
public void setGpx(String gpx) throws ParserConfigurationException, SAXException, IOException {
setGpx(gpx, true);
}
private void setGpx(String gpx, boolean resetNow) throws ParserConfigurationException, SAXException, IOException {
String oldGpx = getGpx();
setPreference(KEY_GPX, gpx);
if (resetNow) {
if (gpsTypeDirty) {
resetLocationController();
} else if (null == oldGpx) {
if (null != gpx) {
resetLocationController();
}
} else if (!oldGpx.equals(gpx)) {
resetLocationController();
}
}
}
/**
* Returns the GPX file to be used for simulated GPS.
* @return the GPX file to be used for simulated GPS.
*/
public String getGpx() {
return preferences.get(KEY_GPX, null);
}
/**
* Saves the simulated GPS speed multiplier to the application configuration settings.
* @param multiplier the simulated GPS speed multiplier.
*/
public void setSpeedMultiplier(double multiplier) {
setPreference(KEY_SPEED_MULTIPLIER, multiplier);
if (null != locationController) {
locationController.setSpeedMultiplier(multiplier);
}
}
/**
* Returns the simulated GPS speed multiplier, or -1 if no speed multiplier has been set.
* @return the simulated GPS speed multiplier, or -1 if no speed multiplier has been set.
*/
public final double getSpeedMultiplier() {
return preferences.getDouble(KEY_SPEED_MULTIPLIER, -1);
}
/**
* Saves the current directory for the map package file chooser to the application
* configuration settings.
* @param the current directory for the map package file chooser.
*/
public void setMPKFileChooserCurrentDirectory(String dir) {
setPreference(KEY_MPK_CHOOSER_DIR, dir);
}
/**
* Returns the stored current directory for the map package file chooser, or
* null if no directory has been set.
* @return the stored current directory for the map package file chooser, or
* null if no directory has been set.
*/
public String getMPKFileChooserCurrentDirectory() {
return preferences.get(KEY_MPK_CHOOSER_DIR, null);
}
/**
* Saves the current directory for the GPX file chooser to the application
* configuration settings.
* @param the current directory for the GPX file chooser.
*/
public void setGPXFileChooserCurrentDirectory(String dir) {
setPreference(KEY_GPX_CHOOSER_DIR, dir);
}
/**
* Returns the stored current directory for the GPX file chooser, or
* null if no directory has been set.
* @return the stored current directory for the GPX file chooser, or
* null if no directory has been set.
*/
public String getGPXFileChooserCurrentDirectory() {
return preferences.get(KEY_GPX_CHOOSER_DIR, null);
}
/**
* Gets the application's GPSController.
* @return the gpsController
* @deprecated use getLocationController() instead.
*/
public LocationController getGpsController() {
return getLocationController();
}
public LocationController getLocationController() {
return locationController;
}
/**
* Gives this AppConfigController a reference to the application's GPSController.
* @param gpsController the gpsController to set
* @deprecated use setLocationController(LocationController) instead.
*/
public void setGpsController(LocationController locationController) {
setLocationController(locationController);
}
public void setLocationController(LocationController locationController) {
this.locationController = locationController;
}
/**
* Returns true if the application should show labels for new message features.
* @return true if the application should show labels for new message features.
*/
public boolean isShowMessageLabels() {
return preferences.getBoolean(KEY_SHOW_MESSAGE_LABELS, true);
}
/**
* Tells the application whether it should show labels for new message features.
* @param showMessageLabels true if the application should show labels for new message features.
*/
public void setShowMessageLabels(final boolean showMessageLabels) {
final boolean oldValue = isShowMessageLabels();
setPreference(KEY_SHOW_MESSAGE_LABELS, showMessageLabels);
if (oldValue != showMessageLabels) {
synchronized (listeners) {
for (final AppConfigListener listener : listeners) {
new Thread() {
@Override
public void run() {
listener.showMessageLabelsChanged(showMessageLabels);
}
}.start();
}
}
}
}
/**
* Returns true if the application should be decorated (title bar, resizable, etc.).
* @return true if the application should be decorated (title bar, resizable, etc.).
*/
public boolean isDecorated() {
return preferences.getBoolean(KEY_DECORATED, true);
}
/**
* Tells the application whether it should be decorated (title bar, resizable, etc.).
* @param decorated true if the application should be decorated (title bar, resizable, etc.).
*/
public void setDecorated(final boolean decorated) {
boolean oldDecorated = isDecorated();
setPreference(KEY_DECORATED, decorated);
if (decorated != oldDecorated) {
for (final AppConfigListener listener : listeners) {
listener.decoratedChanged(decorated);
}
}
}
/**
* Returns true if the application should show an MGRS grid on the map.
* @return true if the application should show an MGRS grid on the map.
*/
public boolean isShowMgrsGrid() {
return preferences.getBoolean(KEY_SHOW_MGRS_GRID, false);
}
/**
* Tells the application whether it should show an MGRS grid on the map.
* @param showMessageLabels true if the application should show an MGRS grid on the map.
*/
public void setShowMgrsGrid(final boolean showMgrsGrid) {
setPreference(KEY_SHOW_MGRS_GRID, showMgrsGrid);
}
/**
* Returns true if the application should display the time in the machine's
* time zone.
* @return true if the application should display the time in the machine's
* time zone.
*/
public boolean isShowLocalTimeZone() {
return preferences.getBoolean(KEY_SHOW_LOCAL_TIME_ZONE, false);
}
/**
* Tells the application whether it should display the time in the machine's
* time zone.
* @param showLocalTimeZone true if the application should display the time
* in the machine's time zone.
*/
public void setShowLocalTimeZone(boolean showLocalTimeZone) {
setPreference(KEY_SHOW_LOCAL_TIME_ZONE, showLocalTimeZone);
}
/**
* Returns true if the application should display the current GPS location in
* MGRS coordinates.
* @return true if the application should display the current GPS location in
* MGRS coordinates and false if the application should display the current
* GPS location in longitude/latitude.
*/
public boolean isShowMgrs() {
return preferences.getBoolean(KEY_MGRS_COORDINATE_NOTATION, true);
}
/**
* Tells the application whether to use MGRS or longitude/latitude coordinate
* notation for coordinate display.
* @param useMgrs true for MGRS and false for longitude/latitude.
*/
public void setShowMgrs(boolean showMgrs) {
setPreference(KEY_MGRS_COORDINATE_NOTATION, showMgrs);
}
/**
* Tells the application the units in which to display the GPS heading.
* @param an AngularUnit.Code constant representing the units in which to display
* the GPS heading.
* @see AngularUnit.Code
*/
public void setHeadingUnits(int headingUnits) {
setPreference(KEY_HEADING_UNITS, headingUnits);
}
/**
* Returns the units in which to display the GPS heading.
* @return an AngularUnit.Code constant representing the units in which to display
* the GPS heading. The default is degrees.
*/
public int getHeadingUnits() {
return preferences.getInt(KEY_HEADING_UNITS, AngularUnit.Code.DEGREE);
}
/**
* Tells the application the Geomessage version to use for outgoing messages.
* @param geomessageVersion the Geomessage version.
*/
public void setGeomessageVersion(String geomessageVersion) {
setPreference(KEY_GEOMESSAGE_VERSION, geomessageVersion);
}
/**
* Returns the Geomessage version that the application is using for outgoing messages.
* @return the Geomessage version that the application is using for outgoing messages.
*/
public String getGeomessageVersion() {
return preferences.get(KEY_GEOMESSAGE_VERSION, "1.1");
}
}
| apache-2.0 |
signed/intellij-community | platform/lang-impl/src/com/intellij/profile/codeInspection/ui/inspectionsTree/InspectionsConfigTreeTable.java | 22103 | /*
* Copyright 2000-2016 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.intellij.profile.codeInspection.ui.inspectionsTree;
import com.intellij.codeHighlighting.HighlightDisplayLevel;
import com.intellij.codeInsight.daemon.HighlightDisplayKey;
import com.intellij.codeInspection.ex.InspectionProfileImpl;
import com.intellij.codeInspection.ex.ScopeToolState;
import com.intellij.ide.IdeTooltip;
import com.intellij.ide.IdeTooltipManager;
import com.intellij.lang.annotation.HighlightSeverity;
import com.intellij.openapi.Disposable;
import com.intellij.openapi.application.ModalityState;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.util.Comparing;
import com.intellij.openapi.util.SystemInfo;
import com.intellij.openapi.util.registry.Registry;
import com.intellij.openapi.util.text.StringUtil;
import com.intellij.profile.codeInspection.ui.InspectionsAggregationUtil;
import com.intellij.profile.codeInspection.ui.SingleInspectionProfilePanel;
import com.intellij.profile.codeInspection.ui.ToolDescriptors;
import com.intellij.profile.codeInspection.ui.table.ScopesAndSeveritiesTable;
import com.intellij.profile.codeInspection.ui.table.ThreeStateCheckBoxRenderer;
import com.intellij.ui.DoubleClickListener;
import com.intellij.ui.treeStructure.treetable.TreeTable;
import com.intellij.ui.treeStructure.treetable.TreeTableModel;
import com.intellij.ui.treeStructure.treetable.TreeTableTree;
import com.intellij.util.Alarm;
import com.intellij.util.NullableFunction;
import com.intellij.util.containers.ContainerUtil;
import com.intellij.util.containers.HashSet;
import com.intellij.util.ui.JBUI;
import com.intellij.util.ui.TextTransferable;
import com.intellij.util.ui.UIUtil;
import com.intellij.util.ui.table.IconTableCellRenderer;
import one.util.streamex.MoreCollectors;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import javax.swing.*;
import javax.swing.table.AbstractTableModel;
import javax.swing.table.TableColumn;
import javax.swing.tree.DefaultTreeModel;
import javax.swing.tree.TreeNode;
import javax.swing.tree.TreePath;
import java.awt.*;
import java.awt.datatransfer.Transferable;
import java.awt.event.*;
import java.util.*;
import java.util.List;
import java.util.stream.Stream;
/**
* @author Dmitry Batkovich
*/
public class InspectionsConfigTreeTable extends TreeTable {
private final static Logger LOG = Logger.getInstance(InspectionsConfigTreeTable.class);
private final static int TREE_COLUMN = 0;
private final static int SEVERITIES_COLUMN = 1;
private final static int IS_ENABLED_COLUMN = 2;
public static int getAdditionalPadding() {
return SystemInfo.isMac ? 10 : 0;
}
public static InspectionsConfigTreeTable create(final InspectionsConfigTreeTableSettings settings, @NotNull Disposable parentDisposable) {
return new InspectionsConfigTreeTable(new InspectionsConfigTreeTableModel(settings, parentDisposable));
}
public InspectionsConfigTreeTable(final InspectionsConfigTreeTableModel model) {
super(model);
TableColumn severitiesColumn = getColumnModel().getColumn(SEVERITIES_COLUMN);
severitiesColumn.setCellRenderer(new IconTableCellRenderer<Icon>() {
@Override
public Component getTableCellRendererComponent(JTable table, Object value, boolean selected, boolean focus, int row, int column) {
Component component = super.getTableCellRendererComponent(table, value, false, focus, row, column);
Color bg = selected ? table.getSelectionBackground() : table.getBackground();
component.setBackground(bg);
((JLabel) component).setText("");
return component;
}
@Nullable
@Override
protected Icon getIcon(@NotNull Icon value, JTable table, int row) {
return value;
}
});
severitiesColumn.setMaxWidth(JBUI.scale(20));
TableColumn isEnabledColumn = getColumnModel().getColumn(IS_ENABLED_COLUMN);
isEnabledColumn.setMaxWidth(JBUI.scale(20 + getAdditionalPadding()));
ThreeStateCheckBoxRenderer boxRenderer = new ThreeStateCheckBoxRenderer();
boxRenderer.setOpaque(true);
isEnabledColumn.setCellRenderer(boxRenderer);
isEnabledColumn.setCellEditor(new ThreeStateCheckBoxRenderer());
addMouseMotionListener(new MouseAdapter() {
@Override
public void mouseMoved(final MouseEvent e) {
Point point = e.getPoint();
int column = columnAtPoint(point);
int row = rowAtPoint(point);
UIUtil.resetEnabledRollOver(InspectionsConfigTreeTable.this, IS_ENABLED_COLUMN);
switch (column) {
case SEVERITIES_COLUMN:
Object maybeIcon = getModel().getValueAt(row, column);
if (maybeIcon instanceof MultiScopeSeverityIcon) {
MultiScopeSeverityIcon icon = (MultiScopeSeverityIcon)maybeIcon;
LinkedHashMap<String, HighlightDisplayLevel> scopeToAverageSeverityMap =
icon.getScopeToAverageSeverityMap();
JComponent component;
if (scopeToAverageSeverityMap.size() == 1 &&
icon.getDefaultScopeName().equals(ContainerUtil.getFirstItem(scopeToAverageSeverityMap.keySet()))) {
HighlightDisplayLevel level = ContainerUtil.getFirstItem(scopeToAverageSeverityMap.values());
JLabel label = new JLabel();
label.setIcon(level.getIcon());
label.setText(SingleInspectionProfilePanel.renderSeverity(level.getSeverity()));
component = label;
} else {
component = new ScopesAndSeveritiesHintTable(scopeToAverageSeverityMap, icon.getDefaultScopeName());
}
IdeTooltipManager.getInstance().show(
new IdeTooltip(InspectionsConfigTreeTable.this, point, component), false);
}
break;
case IS_ENABLED_COLUMN:
if (Registry.is("ide.intellij.laf.win10.ui")) {
JComponent rc = (JComponent)getColumnModel().getColumn(column).getCellRenderer();
rc.putClientProperty("ThreeStateCheckBoxRenderer.rolloverRow", row);
((AbstractTableModel)getModel()).fireTableCellUpdated(row, column);
}
break;
default: break;
}
}
});
addMouseListener(new MouseAdapter() {
@Override public void mouseExited(MouseEvent e) {
UIUtil.resetEnabledRollOver(InspectionsConfigTreeTable.this, IS_ENABLED_COLUMN);
}
});
new DoubleClickListener() {
@Override
protected boolean onDoubleClick(MouseEvent event) {
final TreePath path = getTree().getPathForRow(getTree().getLeadSelectionRow());
if (path != null) {
final InspectionConfigTreeNode node = (InspectionConfigTreeNode)path.getLastPathComponent();
if (node.isLeaf()) {
model.swapInspectionEnableState();
}
}
return true;
}
}.installOn(this);
setTransferHandler(new TransferHandler() {
@Nullable
@Override
protected Transferable createTransferable(JComponent c) {
final TreePath path = getTree().getPathForRow(getTree().getLeadSelectionRow());
if (path != null) {
return new TextTransferable(StringUtil.join(ContainerUtil.mapNotNull(path.getPath(),
(NullableFunction<Object, String>)o -> o == path.getPath()[0] ? null : o.toString()), " | "));
}
return null;
}
@Override
public int getSourceActions(JComponent c) {
return COPY;
}
});
getTableHeader().setReorderingAllowed(false);
registerKeyboardAction(new ActionListener() {
public void actionPerformed(ActionEvent e) {
model.swapInspectionEnableState();
updateUI();
}
}, KeyStroke.getKeyStroke(KeyEvent.VK_SPACE, 0), JComponent.WHEN_FOCUSED);
getEmptyText().setText("No enabled inspections available");
}
@Override
public void paint(@NotNull Graphics g) {
super.paint(g);
UIUtil.fixOSXEditorBackground(this);
}
public abstract static class InspectionsConfigTreeTableSettings {
private final TreeNode myRoot;
private final Project myProject;
public InspectionsConfigTreeTableSettings(final TreeNode root, final Project project) {
myRoot = root;
myProject = project;
}
public TreeNode getRoot() {
return myRoot;
}
public Project getProject() {
return myProject;
}
protected abstract InspectionProfileImpl getInspectionProfile();
protected abstract void onChanged(InspectionConfigTreeNode node);
public abstract void updateRightPanel();
}
public static void setToolEnabled(boolean newState,
@NotNull InspectionProfileImpl profile,
@NotNull String toolId,
@NotNull Project project) {
if (newState) {
profile.enableTool(toolId, project);
}
else {
profile.disableTool(toolId, project);
}
for (ScopeToolState scopeToolState : profile.getTools(toolId, project).getTools()) {
scopeToolState.setEnabled(newState);
}
}
private static class InspectionsConfigTreeTableModel extends DefaultTreeModel implements TreeTableModel {
private final InspectionsConfigTreeTableSettings mySettings;
private final Runnable myUpdateRunnable;
private TreeTable myTreeTable;
private Alarm myUpdateAlarm;
public InspectionsConfigTreeTableModel(final InspectionsConfigTreeTableSettings settings, @NotNull Disposable parentDisposable) {
super(settings.getRoot());
mySettings = settings;
myUpdateRunnable = () -> {
settings.updateRightPanel();
((AbstractTableModel)myTreeTable.getModel()).fireTableDataChanged();
};
myUpdateAlarm = new Alarm(Alarm.ThreadToUse.SWING_THREAD, parentDisposable);
}
@Override
public int getColumnCount() {
return 3;
}
@Nullable
@Override
public String getColumnName(final int column) {
return null;
}
@Override
public Class getColumnClass(final int column) {
switch (column) {
case TREE_COLUMN:
return TreeTableModel.class;
case SEVERITIES_COLUMN:
return Icon.class;
case IS_ENABLED_COLUMN:
return Boolean.class;
}
throw new IllegalArgumentException();
}
@Nullable
@Override
public Object getValueAt(final Object node, final int column) {
if (column == TREE_COLUMN) {
return null;
}
final InspectionConfigTreeNode treeNode = (InspectionConfigTreeNode)node;
final List<HighlightDisplayKey> inspectionsKeys = InspectionsAggregationUtil.getInspectionsKeys(treeNode);
if (column == SEVERITIES_COLUMN) {
final MultiColoredHighlightSeverityIconSink sink = new MultiColoredHighlightSeverityIconSink();
for (final HighlightDisplayKey selectedInspectionsNode : inspectionsKeys) {
final String toolId = selectedInspectionsNode.toString();
if (mySettings.getInspectionProfile().getTools(toolId, mySettings.getProject()).isEnabled()) {
sink.put(mySettings.getInspectionProfile().getToolDefaultState(toolId, mySettings.getProject()),
mySettings.getInspectionProfile().getNonDefaultTools(toolId, mySettings.getProject()));
}
}
return sink.constructIcon(mySettings.getInspectionProfile());
} else if (column == IS_ENABLED_COLUMN) {
return isEnabled(inspectionsKeys);
}
throw new IllegalArgumentException();
}
@Nullable
private Boolean isEnabled(final List<HighlightDisplayKey> selectedInspectionsNodes) {
return selectedInspectionsNodes
.stream()
.map(key -> mySettings.getInspectionProfile().getTools(key.toString(), mySettings.getProject()))
.flatMap(tools -> tools.isEnabled() ? tools.getTools().stream().map(ScopeToolState::isEnabled) : Stream.of(false))
.distinct()
.collect(MoreCollectors.onlyOne()).orElse(null);
}
@Override
public boolean isCellEditable(final Object node, final int column) {
return column == IS_ENABLED_COLUMN;
}
@Override
public void setValueAt(final Object aValue, final Object node, final int column) {
LOG.assertTrue(column == IS_ENABLED_COLUMN);
if (aValue == null) {
return;
}
final boolean doEnable = (Boolean) aValue;
final InspectionProfileImpl profile = mySettings.getInspectionProfile();
for (final InspectionConfigTreeNode aNode : InspectionsAggregationUtil.getInspectionsNodes((InspectionConfigTreeNode)node)) {
setToolEnabled(doEnable, profile, aNode.getKey().toString(), mySettings.getProject());
aNode.dropCache();
mySettings.onChanged(aNode);
}
updateRightPanel();
}
public void swapInspectionEnableState() {
LOG.assertTrue(myTreeTable != null);
Boolean state = null;
final HashSet<HighlightDisplayKey> tools = new HashSet<>();
final List<InspectionConfigTreeNode> nodes = new ArrayList<>();
for (TreePath selectionPath : myTreeTable.getTree().getSelectionPaths()) {
final InspectionConfigTreeNode node = (InspectionConfigTreeNode)selectionPath.getLastPathComponent();
collectInspectionFromNodes(node, tools, nodes);
}
final int[] selectedRows = myTreeTable.getSelectedRows();
for (int selectedRow : selectedRows) {
final Boolean value = (Boolean)myTreeTable.getValueAt(selectedRow, IS_ENABLED_COLUMN);
if (state == null) {
state = value;
}
else if (!state.equals(value)) {
state = null;
break;
}
}
final boolean newState = !Boolean.TRUE.equals(state);
final InspectionProfileImpl profile = mySettings.getInspectionProfile();
for (HighlightDisplayKey tool : tools) {
setToolEnabled(newState, profile, tool.toString(), mySettings.getProject());
}
for (InspectionConfigTreeNode node : nodes) {
node.dropCache();
mySettings.onChanged(node);
}
updateRightPanel();
}
private void updateRightPanel() {
if (myTreeTable != null) {
if (!myUpdateAlarm.isDisposed()) {
myUpdateAlarm.cancelAllRequests();
myUpdateAlarm.addRequest(myUpdateRunnable, 10, ModalityState.stateForComponent(myTreeTable));
}
}
}
private static void collectInspectionFromNodes(final InspectionConfigTreeNode node,
final Set<HighlightDisplayKey> tools,
final List<InspectionConfigTreeNode> nodes) {
if (node == null) {
return;
}
nodes.add(node);
final ToolDescriptors descriptors = node.getDescriptors();
if (descriptors == null) {
for (int i = 0; i < node.getChildCount(); i++) {
collectInspectionFromNodes((InspectionConfigTreeNode)node.getChildAt(i), tools, nodes);
}
} else {
final HighlightDisplayKey key = descriptors.getDefaultDescriptor().getKey();
tools.add(key);
}
}
@Override
public void setTree(final JTree tree) {
myTreeTable = ((TreeTableTree)tree).getTreeTable();
}
}
private static class SeverityAndOccurrences {
private HighlightSeverity myPrimarySeverity;
private final Map<String, HighlightSeverity> myOccurrences = new HashMap<>();
public void setSeverityToMixed() {
myPrimarySeverity = ScopesAndSeveritiesTable.MIXED_FAKE_SEVERITY;
}
public SeverityAndOccurrences incOccurrences(final String toolName, final HighlightSeverity severity) {
if (myPrimarySeverity == null) {
myPrimarySeverity = severity;
} else if (!Comparing.equal(severity, myPrimarySeverity)) {
myPrimarySeverity = ScopesAndSeveritiesTable.MIXED_FAKE_SEVERITY;
}
myOccurrences.put(toolName, severity);
return this;
}
public HighlightSeverity getPrimarySeverity() {
return myPrimarySeverity;
}
public int getOccurrencesSize() {
return myOccurrences.size();
}
public Map<String, HighlightSeverity> getOccurrences() {
return myOccurrences;
}
}
private static class MultiColoredHighlightSeverityIconSink {
private final Map<String, SeverityAndOccurrences> myScopeToAverageSeverityMap = new HashMap<>();
private String myDefaultScopeName;
public Icon constructIcon(final InspectionProfileImpl inspectionProfile) {
final Map<String, HighlightSeverity> computedSeverities = computeSeverities(inspectionProfile);
if (computedSeverities == null) {
return null;
}
boolean allScopesHasMixedSeverity = true;
for (HighlightSeverity severity : computedSeverities.values()) {
if (!severity.equals(ScopesAndSeveritiesTable.MIXED_FAKE_SEVERITY)) {
allScopesHasMixedSeverity = false;
break;
}
}
return allScopesHasMixedSeverity
? ScopesAndSeveritiesTable.MIXED_FAKE_LEVEL.getIcon()
: new MultiScopeSeverityIcon(computedSeverities, myDefaultScopeName, inspectionProfile);
}
@Nullable
private Map<String, HighlightSeverity> computeSeverities(final InspectionProfileImpl inspectionProfile) {
if (myScopeToAverageSeverityMap.isEmpty()) {
return null;
}
final Map<String, HighlightSeverity> result = new HashMap<>();
final Map.Entry<String, SeverityAndOccurrences> entry = ContainerUtil.getFirstItem(myScopeToAverageSeverityMap.entrySet());
result.put(entry.getKey(), entry.getValue().getPrimarySeverity());
if (myScopeToAverageSeverityMap.size() == 1) {
return result;
}
final SeverityAndOccurrences defaultSeveritiesAndOccurrences = myScopeToAverageSeverityMap.get(myDefaultScopeName);
if (defaultSeveritiesAndOccurrences == null) {
for (Map.Entry<String, SeverityAndOccurrences> e: myScopeToAverageSeverityMap.entrySet()) {
final HighlightSeverity primarySeverity = e.getValue().getPrimarySeverity();
if (primarySeverity != null) {
result.put(e.getKey(), primarySeverity);
}
}
return result;
}
final int allInspectionsCount = defaultSeveritiesAndOccurrences.getOccurrencesSize();
final Map<String, HighlightSeverity> allScopes = defaultSeveritiesAndOccurrences.getOccurrences();
for (String currentScope : myScopeToAverageSeverityMap.keySet()) {
final SeverityAndOccurrences currentSeverityAndOccurrences = myScopeToAverageSeverityMap.get(currentScope);
if (currentSeverityAndOccurrences == null) {
continue;
}
final HighlightSeverity currentSeverity = currentSeverityAndOccurrences.getPrimarySeverity();
if (currentSeverity == ScopesAndSeveritiesTable.MIXED_FAKE_SEVERITY ||
currentSeverityAndOccurrences.getOccurrencesSize() == allInspectionsCount ||
myDefaultScopeName.equals(currentScope)) {
result.put(currentScope, currentSeverity);
}
else {
Set<String> toolsToCheck = ContainerUtil.newHashSet(allScopes.keySet());
toolsToCheck.removeAll(currentSeverityAndOccurrences.getOccurrences().keySet());
boolean doContinue = false;
final Map<String, HighlightSeverity> lowerScopeOccurrences = myScopeToAverageSeverityMap.get(myDefaultScopeName).getOccurrences();
for (String toolName : toolsToCheck) {
final HighlightSeverity currentToolSeverity = lowerScopeOccurrences.get(toolName);
if (currentToolSeverity != null) {
if (!currentSeverity.equals(currentToolSeverity)) {
result.put(currentScope, ScopesAndSeveritiesTable.MIXED_FAKE_SEVERITY);
doContinue = true;
break;
}
}
}
if (doContinue) {
continue;
}
result.put(currentScope, currentSeverity);
}
}
return result;
}
public void put(@NotNull final ScopeToolState defaultState, @NotNull final List<ScopeToolState> nonDefault) {
putOne(defaultState);
if (myDefaultScopeName == null) {
myDefaultScopeName = defaultState.getScopeName();
}
for (final ScopeToolState scopeToolState : nonDefault) {
putOne(scopeToolState);
}
}
private void putOne(final ScopeToolState state) {
if (!state.isEnabled()) {
return;
}
final Icon icon = state.getLevel().getIcon();
final String scopeName = state.getScopeName();
if (icon instanceof HighlightDisplayLevel.ColoredIcon) {
final SeverityAndOccurrences severityAndOccurrences = myScopeToAverageSeverityMap.get(scopeName);
final String inspectionName = state.getTool().getShortName();
if (severityAndOccurrences == null) {
myScopeToAverageSeverityMap.put(scopeName, new SeverityAndOccurrences().incOccurrences(inspectionName, state.getLevel().getSeverity()));
} else {
severityAndOccurrences.incOccurrences(inspectionName, state.getLevel().getSeverity());
}
}
}
}
}
| apache-2.0 |
SergiusIW/ton | src/main/java/com/matthewmichelotti/ton/TonParserException.java | 1283 | /*
* Copyright 2015-2016 Matthew D. Michelotti
*
* 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.matthewmichelotti.ton;
import java.io.IOException;
/**
* An exception thrown when unexpected data appears while parsing TON data.
* Such exceptions will include a file location, which includes line and column numbers
* if parsing plain text.
*/
@SuppressWarnings("serial")
public abstract class TonParserException extends IOException {
private FileLoc fileLoc;
TonParserException(String message, FileLoc fileLoc) {
super(message + " (file location: " + fileLoc + ")");
this.fileLoc = fileLoc;
}
/**
* Gets the file location corresponding to the error.
*
* @return file location
*/
public FileLoc getFileLoc() {
return fileLoc;
}
}
| apache-2.0 |
Banno/sbt-plantuml-plugin | src/main/java/net/sourceforge/plantuml/project2/RowOverwrite.java | 2743 | /* ========================================================================
* PlantUML : a free UML diagram generator
* ========================================================================
*
* (C) Copyright 2009-2017, Arnaud Roques
*
* Project Info: http://plantuml.com
*
* This file is part of PlantUML.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*
* Original Author: Arnaud Roques
*/
package net.sourceforge.plantuml.project2;
import java.awt.geom.Dimension2D;
import net.sourceforge.plantuml.Dimension2DDouble;
import net.sourceforge.plantuml.graphic.AbstractTextBlock;
import net.sourceforge.plantuml.graphic.StringBounder;
import net.sourceforge.plantuml.graphic.TextBlock;
import net.sourceforge.plantuml.ugraphic.UGraphic;
import net.sourceforge.plantuml.ugraphic.UTranslate;
class RowOverwrite implements Row {
private final Row r1;
private final Row r2;
public RowOverwrite(Row r1, Row r2) {
this.r1 = r1;
this.r2 = r2;
}
public TextBlock asTextBloc(final TimeConverter timeConverter) {
return new AbstractTextBlock() {
public void drawU(UGraphic ug) {
final double minX = getMinXwithoutHeader(timeConverter);
final double minXr1 = r1.getMinXwithoutHeader(timeConverter);
final double minXr2 = r2.getMinXwithoutHeader(timeConverter);
r1.asTextBloc(timeConverter).drawU(ug.apply(new UTranslate((minXr1 - minX), 0)));
r2.asTextBloc(timeConverter).drawU(ug.apply(new UTranslate((minXr2 - minX), 0)));
}
public Dimension2D calculateDimension(StringBounder stringBounder) {
final double width = getMaxXwithoutHeader(timeConverter) - getMinXwithoutHeader(timeConverter);
final double height = getHeight();
return new Dimension2DDouble(width, height);
}
};
}
public double getMinXwithoutHeader(TimeConverter timeConverter) {
return Math.min(r1.getMinXwithoutHeader(timeConverter), r2.getMinXwithoutHeader(timeConverter));
}
public double getMaxXwithoutHeader(TimeConverter timeConverter) {
return Math.max(r1.getMaxXwithoutHeader(timeConverter), r2.getMaxXwithoutHeader(timeConverter));
}
public double getHeight() {
return Math.max(r1.getHeight(), r2.getHeight());
}
public TextBlock header() {
return r1.header();
}
}
| apache-2.0 |
BonDyka/abondarev | jun/chapter_007/src/main/java/ru/job4j/nbalgo/ConcurrentCash.java | 1851 | package ru.job4j.nbalgo;
import java.util.concurrent.ConcurrentHashMap;
/**
* Represent concurrent storage for models of type {@link User} associated
* with some key.
*
* @author Alexander Bondarev(mailto:bondarew2507@gmail.com).
* @since 21.11.2017.
*/
public class ConcurrentCash<K, V extends User> {
private ConcurrentHashMap<K, V> container = new ConcurrentHashMap<>();
/**
* Adds new element of type {@link User} if its associated key doesn't
* exist.
*
* @param key associated key.
* @param value element for adding.
*/
public void add(K key, V value) {
if (!container.containsKey(key)) {
container.put(key, value);
}
}
/**
* Returns element associated with specified key.
*
* @param key it's key for access to element.
* @return element associated with key.
*/
public V get(K key) {
return container.get(key);
}
/**
* Update value of type {@link User} associated with specified key if it
* exist. If any other thread try update the value at the same time throws
* @link OptimisticException}.
*
* @param key it's key of updating value.
* @param value new value.
* @throws OptimisticException throws if more than one thread try update
* value at the same time.
*/
public void update(K key, V value) throws OptimisticException {
container.computeIfPresent(key, (k, v) -> {
if (v.getVersion() != value.getVersion() - 1) {
throw new OptimisticException("Attempt change updated");
}
return value;
});
}
/**
* Delete element associated with specified key.
*
* @param key of element for deletion.
*/
public void delete(K key) {
container.remove(key);
}
}
| apache-2.0 |
medicayun/medicayundicom | dcm4jboss-all/tags/DCM4JBOSS_2_5_4/dcm4jboss-sar/src/java/org/dcm4chex/archive/dcm/mwlscu/MWLScuService.java | 11722 | /* ***** BEGIN LICENSE BLOCK *****
* Version: MPL 1.1/GPL 2.0/LGPL 2.1
*
* The contents of this file are subject to the Mozilla Public License Version
* 1.1 (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.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
* for the specific language governing rights and limitations under the
* License.
*
* The Original Code is part of dcm4che, an implementation of DICOM(TM) in
* Java(TM), available at http://sourceforge.net/projects/dcm4che.
*
* The Initial Developer of the Original Code is
* TIANI Medgraph AG.
* Portions created by the Initial Developer are Copyright (C) 2003-2005
* the Initial Developer. All Rights Reserved.
*
* Contributor(s):
* Gunter Zeilinger <gunter.zeilinger@tiani.com>
* Franz Willer <franz.willer@gwi-ag.com>
*
* Alternatively, the contents of this file may be used under the terms of
* either the GNU General Public License Version 2 or later (the "GPL"), or
* the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
* in which case the provisions of the GPL or the LGPL are applicable instead
* of those above. If you wish to allow use of your version of this file only
* under the terms of either the GPL or the LGPL, and not to allow others to
* use your version of this file under the terms of the MPL, indicate your
* decision by deleting the provisions above and replace them with the notice
* and other provisions required by the GPL or the LGPL. If you do not delete
* the provisions above, a recipient may use your version of this file under
* the terms of any one of the MPL, the GPL or the LGPL.
*
* ***** END LICENSE BLOCK ***** */
package org.dcm4chex.archive.dcm.mwlscu;
import java.io.IOException;
import java.net.Socket;
import java.rmi.RemoteException;
import java.security.GeneralSecurityException;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import javax.ejb.CreateException;
import org.dcm4che.data.Command;
import org.dcm4che.data.Dataset;
import org.dcm4che.data.DcmObjectFactory;
import org.dcm4che.dict.UIDs;
import org.dcm4che.net.AAssociateAC;
import org.dcm4che.net.AAssociateRQ;
import org.dcm4che.net.ActiveAssociation;
import org.dcm4che.net.Association;
import org.dcm4che.net.AssociationFactory;
import org.dcm4che.net.Dimse;
import org.dcm4che.net.FutureRSP;
import org.dcm4che.net.PDU;
import org.dcm4chex.archive.config.DicomPriority;
import org.dcm4chex.archive.ejb.interfaces.MWLManager;
import org.dcm4chex.archive.ejb.interfaces.MWLManagerHome;
import org.dcm4chex.archive.ejb.jdbc.AECmd;
import org.dcm4chex.archive.ejb.jdbc.AEData;
import org.dcm4chex.archive.ejb.jdbc.MWLQueryCmd;
import org.dcm4chex.archive.util.EJBHomeFactory;
import org.dcm4chex.archive.util.HomeFactoryException;
import org.jboss.system.ServiceMBeanSupport;
/**
* @author franz.willer
* @version $Revision: 2010 $ $Date: 2005-10-07 03:55:27 +0800 (周五, 07 10月 2005) $
* MBean to configure and service modality worklist managment issues.
* <p>
*
*/
public class MWLScuService extends ServiceMBeanSupport {
/** Holds the calling AET. */
private String callingAET;
/** Holds the AET of modality worklist service. */
private String calledAET;
/** Holds Association timeout in ms. */
private int acTimeout;
/** Holds DICOM message timeout in ms. */
private int dimseTimeout;
/** Holds max PDU length in bytes. */
private int maxPDUlen = 16352;
/** Holds socket close delay in ms. */
private int soCloseDelay;
/** DICOM priority. Used for move and media creation action. */
private int priority = 0;
private static final String[] NATIVE_TS = { UIDs.ExplicitVRLittleEndian,
UIDs.ImplicitVRLittleEndian};
private MWLManager mwlManager;
/**
* Returns the calling AET defined in this MBean.
*
* @return The calling AET.
*/
public final String getCallingAET() {
return callingAET;
}
/**
* Set the calling AET.
*
* @param aet The calling AET to set.
*/
public final void setCallingAET( String aet ) {
callingAET = aet;
}
/**
* Returns the AET that holds the work list (Modality Work List SCP).
*
* @return The retrieve AET.
*/
public final String getCalledAET() {
return calledAET;
}
/**
* Set the retrieve AET.
*
* @param aet The retrieve AET to set.
*/
public final void setCalledAET( String aet ) {
calledAET = aet;
}
public final boolean isLocal() {
return "LOCAL".equalsIgnoreCase(calledAET);
}
/**
* Returns the Association timeout in ms.
*
* @return Returns the acTimeout.
*/
public final int getAcTimeout() {
return acTimeout;
}
/**
* Set the association timeout.
*
* @param acTimeout The acTimeout in ms.
*/
public final void setAcTimeout(int acTimeout) {
this.acTimeout = acTimeout;
}
/**
* Returns the DICOM message timeout in ms.
*
* @return Returns the dimseTimeout.
*/
public final int getDimseTimeout() {
return dimseTimeout;
}
/**
* Set the DICOM message timeout.
*
* @param dimseTimeout The dimseTimeout in ms.
*/
public final void setDimseTimeout(int dimseTimeout) {
this.dimseTimeout = dimseTimeout;
}
/**
* Returns the socket close delay in ms.
*
* @return Returns the soCloseDelay.
*/
public final int getSoCloseDelay() {
return soCloseDelay;
}
/**
* Set the socket close delay.
*
* @param delay Socket close delay in ms.
*/
public final void setSoCloseDelay( int delay ) {
soCloseDelay = delay;
}
/**
* returns the max PDU length in bytes.
*
* @return Returns the maxPDUlen.
*/
public final int getMaxPDUlen() {
return maxPDUlen;
}
/**
* Set the max PDU length.
*
* @param maxPDUlen The maxPDUlen in bytes.
*/
public final void setMaxPDUlen(int maxPDUlen) {
this.maxPDUlen = maxPDUlen;
}
/**
* Returns the DICOM priority as int value.
* <p>
* This value is used for CFIND.
* 0..MED, 1..HIGH, 2..LOW
*
* @return Returns the priority.
*/
public final String getPriority() {
return DicomPriority.toString(priority);
}
/**
* Set the DICOM priority.
*
* @param priority The priority to set.
*/
public final void setPriority(String priority) {
this.priority = DicomPriority.toCode(priority);
}
/**
*
*/
protected void startService() throws Exception {
super.startService();
}
/**
*
*/
protected void stopService() throws Exception {
super.stopService();
}
public boolean deleteMWLEntry( String spsID ) {
try {
lookupMWLManager().removeWorklistItem( spsID );
log.info("MWL entry with id "+spsID+" removed!");
return true;
} catch (Exception x) {
log.error("Can't delete MWLEntry with id:"+spsID, x );
return false;
}
}
/**
* Get a list of work list entries.
*/
public List findMWLEntries( Dataset searchDS ) {
if ( isLocal() ) {
return findMWLEntriesLocal( searchDS );
} else {
return findMWLEntriesFromAET( searchDS );
}
}
/**
* @param searchDS
* @return
*/
private List findMWLEntriesLocal(Dataset searchDS) {
List l = new ArrayList();
MWLQueryCmd queryCmd = null;
try {
queryCmd = new MWLQueryCmd(searchDS);
queryCmd.execute();
while ( queryCmd.next() ) {
l.add( queryCmd.getDataset() );
}
} catch (SQLException x) {
log.error( "Exception in findMWLEntriesLocal! ", x);
}
if ( queryCmd != null ) queryCmd.close();
return l;
}
private List findMWLEntriesFromAET( Dataset searchDS ) {
ActiveAssociation assoc = null;
String iuid = null;
List list = new ArrayList();
try {
//get association for mwl find.
AEData aeData = new AECmd( calledAET ).getAEData();
assoc = openAssoc( aeData.getHostName(), aeData.getPort(), getCFINDAssocReq() );
if ( assoc == null ) {
log.error( "Couldnt open association to " + aeData );
return list;
}
Association as = assoc.getAssociation();
if (as.getAcceptedTransferSyntaxUID(1) == null) {
log.error(calledAET +" doesnt support CFIND request!", null );
return list;
}
//send mwl cfind request.
Command cmd = DcmObjectFactory.getInstance().newCommand();
cmd.initCFindRQ(1, UIDs.ModalityWorklistInformationModelFIND, priority );
Dimse mcRQ = AssociationFactory.getInstance().newDimse(1, cmd, searchDS);
if ( log.isDebugEnabled() ) log.debug("make CFIND req:"+mcRQ);
FutureRSP rsp = assoc.invoke(mcRQ);
Dimse dimse = rsp.get();
if ( log.isDebugEnabled() ) log.debug("CFIND resp:"+dimse);
List pending = rsp.listPending();
if ( log.isDebugEnabled() ) log.debug("CFIND pending:"+pending);
Iterator iter = pending.iterator();
while ( iter.hasNext() ) {
list.add( ( (Dimse) iter.next()).getDataset() );
}
list.add( dimse.getDataset() );
} catch (Exception e) {
log.error( "Cant get working list! Reason: unexpected error", e);
return list;
} finally {
if ( assoc != null )
try {
assoc.release( true );
} catch (Exception e1) {
log.error( "Cant release association for CFIND modality working list"+assoc.getAssociation(),e1);
}
}
return list;
}
/**
* Open a DICOM association for given host, port and assocition request.
*
* @param host Host to create the association.
* @param port Port number to create the association.
* @param assocRQ The association request object.
*
* @return The Active association object.
*
* @throws IOException
* @throws GeneralSecurityException
*/
private ActiveAssociation openAssoc( String host, int port, AAssociateRQ assocRQ ) throws IOException, GeneralSecurityException {
AssociationFactory aFact = AssociationFactory.getInstance();
Association assoc = aFact.newRequestor( new Socket( host, port ) );
assoc.setAcTimeout(acTimeout);
assoc.setDimseTimeout(dimseTimeout);
assoc.setSoCloseDelay(soCloseDelay);
PDU assocAC = assoc.connect(assocRQ);
if (!(assocAC instanceof AAssociateAC)) { return null; }
ActiveAssociation retval = aFact.newActiveAssociation(assoc, null);
retval.start();
return retval;
}
/**
* Return the association request for media creation.
* <p>
* This association is used for sending media creation request and action command.
*
* @return Association for media creation.
*/
private AAssociateRQ getCFINDAssocReq() {
AssociationFactory aFact = AssociationFactory.getInstance();
AAssociateRQ assocRQ = aFact.newAAssociateRQ();
assocRQ.setCalledAET( calledAET );
assocRQ.setCallingAET( callingAET );
assocRQ.setMaxPDULength( maxPDUlen );
assocRQ.addPresContext(aFact.newPresContext(1,
UIDs.ModalityWorklistInformationModelFIND,
NATIVE_TS ));
return assocRQ;
}
/**
* Returns the MWLManager session bean.
*
* @return The MWLManager.
*
* @throws HomeFactoryException
* @throws RemoteException
* @throws CreateException
*/
private MWLManager lookupMWLManager() throws HomeFactoryException, RemoteException, CreateException {
if ( mwlManager == null ) {
MWLManagerHome home = (MWLManagerHome) EJBHomeFactory
.getFactory().lookup(MWLManagerHome.class,
MWLManagerHome.JNDI_NAME);
mwlManager = home.create();
}
return mwlManager;
}
}
| apache-2.0 |
bingoohuang/spring-boot-blank | src/main/java/com/github/bingoohuang/springbootbank/demo/MessageRepository.java | 196 | package com.github.bingoohuang.springbootbank.demo;
public interface MessageRepository {
Iterable<Message> findAll();
Message save(Message message);
Message findMessage(Long id);
}
| apache-2.0 |
vam-google/google-cloud-java | google-api-grpc/proto-google-cloud-video-intelligence-v1beta1/src/main/java/com/google/cloud/videointelligence/v1beta1/VideoAnnotationResultsOrBuilder.java | 8178 | // Generated by the protocol buffer compiler. DO NOT EDIT!
// source: google/cloud/videointelligence/v1beta1/video_intelligence.proto
package com.google.cloud.videointelligence.v1beta1;
public interface VideoAnnotationResultsOrBuilder
extends
// @@protoc_insertion_point(interface_extends:google.cloud.videointelligence.v1beta1.VideoAnnotationResults)
com.google.protobuf.MessageOrBuilder {
/**
*
*
* <pre>
* Video file location in
* [Google Cloud Storage](https://cloud.google.com/storage/).
* </pre>
*
* <code>string input_uri = 1;</code>
*/
java.lang.String getInputUri();
/**
*
*
* <pre>
* Video file location in
* [Google Cloud Storage](https://cloud.google.com/storage/).
* </pre>
*
* <code>string input_uri = 1;</code>
*/
com.google.protobuf.ByteString getInputUriBytes();
/**
*
*
* <pre>
* Label annotations. There is exactly one element for each unique label.
* </pre>
*
* <code>repeated .google.cloud.videointelligence.v1beta1.LabelAnnotation label_annotations = 2;
* </code>
*/
java.util.List<com.google.cloud.videointelligence.v1beta1.LabelAnnotation>
getLabelAnnotationsList();
/**
*
*
* <pre>
* Label annotations. There is exactly one element for each unique label.
* </pre>
*
* <code>repeated .google.cloud.videointelligence.v1beta1.LabelAnnotation label_annotations = 2;
* </code>
*/
com.google.cloud.videointelligence.v1beta1.LabelAnnotation getLabelAnnotations(int index);
/**
*
*
* <pre>
* Label annotations. There is exactly one element for each unique label.
* </pre>
*
* <code>repeated .google.cloud.videointelligence.v1beta1.LabelAnnotation label_annotations = 2;
* </code>
*/
int getLabelAnnotationsCount();
/**
*
*
* <pre>
* Label annotations. There is exactly one element for each unique label.
* </pre>
*
* <code>repeated .google.cloud.videointelligence.v1beta1.LabelAnnotation label_annotations = 2;
* </code>
*/
java.util.List<? extends com.google.cloud.videointelligence.v1beta1.LabelAnnotationOrBuilder>
getLabelAnnotationsOrBuilderList();
/**
*
*
* <pre>
* Label annotations. There is exactly one element for each unique label.
* </pre>
*
* <code>repeated .google.cloud.videointelligence.v1beta1.LabelAnnotation label_annotations = 2;
* </code>
*/
com.google.cloud.videointelligence.v1beta1.LabelAnnotationOrBuilder getLabelAnnotationsOrBuilder(
int index);
/**
*
*
* <pre>
* Face annotations. There is exactly one element for each unique face.
* </pre>
*
* <code>repeated .google.cloud.videointelligence.v1beta1.FaceAnnotation face_annotations = 3;
* </code>
*/
java.util.List<com.google.cloud.videointelligence.v1beta1.FaceAnnotation>
getFaceAnnotationsList();
/**
*
*
* <pre>
* Face annotations. There is exactly one element for each unique face.
* </pre>
*
* <code>repeated .google.cloud.videointelligence.v1beta1.FaceAnnotation face_annotations = 3;
* </code>
*/
com.google.cloud.videointelligence.v1beta1.FaceAnnotation getFaceAnnotations(int index);
/**
*
*
* <pre>
* Face annotations. There is exactly one element for each unique face.
* </pre>
*
* <code>repeated .google.cloud.videointelligence.v1beta1.FaceAnnotation face_annotations = 3;
* </code>
*/
int getFaceAnnotationsCount();
/**
*
*
* <pre>
* Face annotations. There is exactly one element for each unique face.
* </pre>
*
* <code>repeated .google.cloud.videointelligence.v1beta1.FaceAnnotation face_annotations = 3;
* </code>
*/
java.util.List<? extends com.google.cloud.videointelligence.v1beta1.FaceAnnotationOrBuilder>
getFaceAnnotationsOrBuilderList();
/**
*
*
* <pre>
* Face annotations. There is exactly one element for each unique face.
* </pre>
*
* <code>repeated .google.cloud.videointelligence.v1beta1.FaceAnnotation face_annotations = 3;
* </code>
*/
com.google.cloud.videointelligence.v1beta1.FaceAnnotationOrBuilder getFaceAnnotationsOrBuilder(
int index);
/**
*
*
* <pre>
* Shot annotations. Each shot is represented as a video segment.
* </pre>
*
* <code>repeated .google.cloud.videointelligence.v1beta1.VideoSegment shot_annotations = 4;
* </code>
*/
java.util.List<com.google.cloud.videointelligence.v1beta1.VideoSegment> getShotAnnotationsList();
/**
*
*
* <pre>
* Shot annotations. Each shot is represented as a video segment.
* </pre>
*
* <code>repeated .google.cloud.videointelligence.v1beta1.VideoSegment shot_annotations = 4;
* </code>
*/
com.google.cloud.videointelligence.v1beta1.VideoSegment getShotAnnotations(int index);
/**
*
*
* <pre>
* Shot annotations. Each shot is represented as a video segment.
* </pre>
*
* <code>repeated .google.cloud.videointelligence.v1beta1.VideoSegment shot_annotations = 4;
* </code>
*/
int getShotAnnotationsCount();
/**
*
*
* <pre>
* Shot annotations. Each shot is represented as a video segment.
* </pre>
*
* <code>repeated .google.cloud.videointelligence.v1beta1.VideoSegment shot_annotations = 4;
* </code>
*/
java.util.List<? extends com.google.cloud.videointelligence.v1beta1.VideoSegmentOrBuilder>
getShotAnnotationsOrBuilderList();
/**
*
*
* <pre>
* Shot annotations. Each shot is represented as a video segment.
* </pre>
*
* <code>repeated .google.cloud.videointelligence.v1beta1.VideoSegment shot_annotations = 4;
* </code>
*/
com.google.cloud.videointelligence.v1beta1.VideoSegmentOrBuilder getShotAnnotationsOrBuilder(
int index);
/**
*
*
* <pre>
* Safe search annotations.
* </pre>
*
* <code>
* repeated .google.cloud.videointelligence.v1beta1.SafeSearchAnnotation safe_search_annotations = 6;
* </code>
*/
java.util.List<com.google.cloud.videointelligence.v1beta1.SafeSearchAnnotation>
getSafeSearchAnnotationsList();
/**
*
*
* <pre>
* Safe search annotations.
* </pre>
*
* <code>
* repeated .google.cloud.videointelligence.v1beta1.SafeSearchAnnotation safe_search_annotations = 6;
* </code>
*/
com.google.cloud.videointelligence.v1beta1.SafeSearchAnnotation getSafeSearchAnnotations(
int index);
/**
*
*
* <pre>
* Safe search annotations.
* </pre>
*
* <code>
* repeated .google.cloud.videointelligence.v1beta1.SafeSearchAnnotation safe_search_annotations = 6;
* </code>
*/
int getSafeSearchAnnotationsCount();
/**
*
*
* <pre>
* Safe search annotations.
* </pre>
*
* <code>
* repeated .google.cloud.videointelligence.v1beta1.SafeSearchAnnotation safe_search_annotations = 6;
* </code>
*/
java.util.List<? extends com.google.cloud.videointelligence.v1beta1.SafeSearchAnnotationOrBuilder>
getSafeSearchAnnotationsOrBuilderList();
/**
*
*
* <pre>
* Safe search annotations.
* </pre>
*
* <code>
* repeated .google.cloud.videointelligence.v1beta1.SafeSearchAnnotation safe_search_annotations = 6;
* </code>
*/
com.google.cloud.videointelligence.v1beta1.SafeSearchAnnotationOrBuilder
getSafeSearchAnnotationsOrBuilder(int index);
/**
*
*
* <pre>
* If set, indicates an error. Note that for a single `AnnotateVideoRequest`
* some videos may succeed and some may fail.
* </pre>
*
* <code>.google.rpc.Status error = 5;</code>
*/
boolean hasError();
/**
*
*
* <pre>
* If set, indicates an error. Note that for a single `AnnotateVideoRequest`
* some videos may succeed and some may fail.
* </pre>
*
* <code>.google.rpc.Status error = 5;</code>
*/
com.google.rpc.Status getError();
/**
*
*
* <pre>
* If set, indicates an error. Note that for a single `AnnotateVideoRequest`
* some videos may succeed and some may fail.
* </pre>
*
* <code>.google.rpc.Status error = 5;</code>
*/
com.google.rpc.StatusOrBuilder getErrorOrBuilder();
}
| apache-2.0 |
henrichg/PhoneProfilesPlus | phoneProfilesPlus/src/main/java/sk/henrichg/phoneprofilesplus/PPIntent.java | 9837 | package sk.henrichg.phoneprofilesplus;
import android.os.Parcel;
import android.os.Parcelable;
class PPIntent implements Parcelable {
long _id;
String _name;
String _packageName;
String _className;
String _action;
String _data;
String _mimeType;
String _extraKey1;
String _extraValue1;
int _extraType1;
String _extraKey2;
String _extraValue2;
int _extraType2;
String _extraKey3;
String _extraValue3;
int _extraType3;
String _extraKey4;
String _extraValue4;
int _extraType4;
String _extraKey5;
String _extraValue5;
int _extraType5;
String _extraKey6;
String _extraValue6;
int _extraType6;
String _extraKey7;
String _extraValue7;
int _extraType7;
String _extraKey8;
String _extraValue8;
int _extraType8;
String _extraKey9;
String _extraValue9;
int _extraType9;
String _extraKey10;
String _extraValue10;
int _extraType10;
String _categories;
String _flags;
int _intentType;
//int _usedCount;
boolean _doNotDelete;
PPIntent() {}
PPIntent(
long id,
String name,
String packageName,
String className,
String action,
String data,
String mimeType,
String extraKey1,
String extraValue1,
int extraType1,
String extraKey2,
String extraValue2,
int extraType2,
String extraKey3,
String extraValue3,
int extraType3,
String extraKey4,
String extraValue4,
int extraType4,
String extraKey5,
String extraValue5,
int extraType5,
String extraKey6,
String extraValue6,
int extraType6,
String extraKey7,
String extraValue7,
int extraType7,
String extraKey8,
String extraValue8,
int extraType8,
String extraKey9,
String extraValue9,
int extraType9,
String extraKey10,
String extraValue10,
int extraType10,
String categories,
String flags,
//int usedCount,
int intentType,
boolean doNotDelete
)
{
this._id = id;
this._name = name;
this._packageName = packageName;
this._className = className;
this._action = action;
this._data = data;
this._mimeType = mimeType;
this._extraKey1 = extraKey1;
this._extraValue1 = extraValue1;
this._extraType1 = extraType1;
this._extraKey2 = extraKey2;
this._extraValue2 = extraValue2;
this._extraType2 = extraType2;
this._extraKey3 = extraKey3;
this._extraValue3 = extraValue3;
this._extraType3 = extraType3;
this._extraKey4 = extraKey4;
this._extraValue4 = extraValue4;
this._extraType4 = extraType4;
this._extraKey5 = extraKey5;
this._extraValue5 = extraValue5;
this._extraType5 = extraType5;
this._extraKey6 = extraKey6;
this._extraValue6 = extraValue6;
this._extraType6 = extraType6;
this._extraKey7 = extraKey7;
this._extraValue7 = extraValue7;
this._extraType7 = extraType7;
this._extraKey8 = extraKey8;
this._extraValue8 = extraValue8;
this._extraType8 = extraType8;
this._extraKey9 = extraKey9;
this._extraValue9 = extraValue9;
this._extraType9 = extraType9;
this._extraKey10 = extraKey10;
this._extraValue10 = extraValue10;
this._extraType10 = extraType10;
this._categories = categories;
this._flags = flags;
this._intentType = intentType;
//this._usedCount = usedCount;
this._doNotDelete = doNotDelete;
}
private PPIntent(Parcel in) {
this._id = in.readLong();
this._name = in.readString();
this._packageName = in.readString();
this._className = in.readString();
this._action = in.readString();
this._data = in.readString();
this._mimeType = in.readString();
this._extraKey1 = in.readString();
this._extraValue1 = in.readString();
this._extraType1 = in.readInt();
this._extraKey2 = in.readString();
this._extraValue2 = in.readString();
this._extraType2 = in.readInt();
this._extraKey3 = in.readString();
this._extraValue3 = in.readString();
this._extraType3 = in.readInt();
this._extraKey4 = in.readString();
this._extraValue4 = in.readString();
this._extraType4 = in.readInt();
this._extraKey5 = in.readString();
this._extraValue5 = in.readString();
this._extraType5 = in.readInt();
this._extraKey6 = in.readString();
this._extraValue6 = in.readString();
this._extraType6 = in.readInt();
this._extraKey7 = in.readString();
this._extraValue7 = in.readString();
this._extraType7 = in.readInt();
this._extraKey8 = in.readString();
this._extraValue8 = in.readString();
this._extraType8 = in.readInt();
this._extraKey9 = in.readString();
this._extraValue9 = in.readString();
this._extraType9 = in.readInt();
this._extraKey10 = in.readString();
this._extraValue10 = in.readString();
this._extraType10 = in.readInt();
this._categories = in.readString();
this._flags = in.readString();
this._intentType = in.readInt();
//this._usedCount = in.readInt();
this._doNotDelete = in.readInt() == 1;
}
@Override
public int describeContents() {
return 0;
}
@Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeLong(this._id);
dest.writeString(this._name);
dest.writeString(this._packageName);
dest.writeString(this._className);
dest.writeString(this._action);
dest.writeString(this._data);
dest.writeString(this._mimeType);
dest.writeString(this._extraKey1);
dest.writeString(this._extraValue1);
dest.writeInt(this._extraType1);
dest.writeString(this._extraKey2);
dest.writeString(this._extraValue2);
dest.writeInt(this._extraType2);
dest.writeString(this._extraKey3);
dest.writeString(this._extraValue3);
dest.writeInt(this._extraType3);
dest.writeString(this._extraKey4);
dest.writeString(this._extraValue4);
dest.writeInt(this._extraType4);
dest.writeString(this._extraKey5);
dest.writeString(this._extraValue5);
dest.writeInt(this._extraType5);
dest.writeString(this._extraKey6);
dest.writeString(this._extraValue6);
dest.writeInt(this._extraType6);
dest.writeString(this._extraKey7);
dest.writeString(this._extraValue7);
dest.writeInt(this._extraType7);
dest.writeString(this._extraKey8);
dest.writeString(this._extraValue8);
dest.writeInt(this._extraType8);
dest.writeString(this._extraKey9);
dest.writeString(this._extraValue9);
dest.writeInt(this._extraType9);
dest.writeString(this._extraKey10);
dest.writeString(this._extraValue10);
dest.writeInt(this._extraType10);
dest.writeString(this._categories);
dest.writeString(this._flags);
dest.writeInt(this._intentType);
//dest.writeInt(this._usedCount);
dest.writeInt(this._doNotDelete ? 1 : 0);
}
PPIntent duplicate() {
PPIntent newPPIntent = new PPIntent();
newPPIntent._name = _name + "_d";
newPPIntent._packageName = _packageName;
newPPIntent._className = _className;
newPPIntent._action = _action;
newPPIntent._data = _data;
newPPIntent._mimeType = _mimeType;
newPPIntent._extraKey1 = _extraKey1;
newPPIntent._extraValue1 = _extraValue1;
newPPIntent._extraType1 = _extraType1;
newPPIntent._extraKey2 = _extraKey2;
newPPIntent._extraValue2 = _extraValue2;
newPPIntent._extraType2 = _extraType2;
newPPIntent._extraKey3 = _extraKey3;
newPPIntent._extraValue3 = _extraValue3;
newPPIntent._extraType3 = _extraType3;
newPPIntent._extraKey4 = _extraKey4;
newPPIntent._extraValue4 = _extraValue4;
newPPIntent._extraType4 = _extraType4;
newPPIntent._extraKey5 = _extraKey5;
newPPIntent._extraValue5 = _extraValue5;
newPPIntent._extraType5 = _extraType5;
newPPIntent._extraKey6 = _extraKey6;
newPPIntent._extraValue6 = _extraValue6;
newPPIntent._extraType6 = _extraType6;
newPPIntent._extraKey7 = _extraKey7;
newPPIntent._extraValue7 = _extraValue7;
newPPIntent._extraType7 = _extraType7;
newPPIntent._extraKey8 = _extraKey8;
newPPIntent._extraValue8 = _extraValue8;
newPPIntent._extraType8 = _extraType8;
newPPIntent._extraKey9 = _extraKey9;
newPPIntent._extraValue9 = _extraValue9;
newPPIntent._extraType9 = _extraType9;
newPPIntent._extraKey10 = _extraKey10;
newPPIntent._extraValue10 = _extraValue10;
newPPIntent._extraType10 = _extraType10;
newPPIntent._categories = _categories;
newPPIntent._flags = _flags;
newPPIntent._intentType = _intentType;
newPPIntent._doNotDelete = _doNotDelete;
return newPPIntent;
}
public static final Parcelable.Creator<PPIntent> CREATOR = new Parcelable.Creator<PPIntent>() {
public PPIntent createFromParcel(Parcel source) {
return new PPIntent(source);
}
public PPIntent[] newArray(int size) {
return new PPIntent[size];
}
};
}
| apache-2.0 |
kris-davison/capricoinj | core/src/main/java/com/capricoinj/kits/WalletAppKit.java | 20509 | /*
* Copyright 2013 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.capricoinj.kits;
import com.capricoinj.core.*;
import com.capricoinj.net.discovery.DnsDiscovery;
import com.capricoinj.protocols.channels.StoredPaymentChannelClientStates;
import com.capricoinj.protocols.channels.StoredPaymentChannelServerStates;
import com.capricoinj.store.BlockStoreException;
import com.capricoinj.store.SPVBlockStore;
import com.capricoinj.store.ValidHashStore;
import com.capricoinj.store.WalletProtobufSerializer;
import com.capricoinj.wallet.DeterministicSeed;
import com.capricoinj.wallet.KeyChainGroup;
import com.capricoinj.wallet.Protos;
import com.google.common.collect.ImmutableList;
import com.google.common.util.concurrent.AbstractIdleService;
import com.google.common.util.concurrent.MoreExecutors;
import com.google.common.util.concurrent.Service;
import com.subgraph.orchid.TorClient;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.annotation.Nullable;
import java.io.*;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.nio.channels.FileLock;
import java.util.List;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import static com.google.common.base.Preconditions.checkNotNull;
import static com.google.common.base.Preconditions.checkState;
/**
* <p>Utility class that wraps the boilerplate needed to set up a new SPV peercoinj app. Instantiate it with a directory
* and file prefix, optionally configure a few things, then use startAsync and optionally awaitRunning. The object will
* construct and configure a {@link BlockChain}, {@link SPVBlockStore}, {@link Wallet} and {@link PeerGroup}. Depending
* on the value of the blockingStartup property, startup will be considered complete once the block chain has fully
* synchronized, so it can take a while.</p>
*
* <p>To add listeners and modify the objects that are constructed, you can either do that by overriding the
* {@link #onSetupCompleted()} method (which will run on a background thread) and make your changes there,
* or by waiting for the service to start and then accessing the objects from wherever you want. However, you cannot
* access the objects this class creates until startup is complete.</p>
*
* <p>The asynchronous design of this class may seem puzzling (just use {@link #awaitRunning()} if you don't want that).
* It is to make it easier to fit peercoinj into GUI apps, which require a high degree of responsiveness on their main
* thread which handles all the animation and user interaction. Even when blockingStart is false, initializing peercoinj
* means doing potentially blocking file IO, generating keys and other potentially intensive operations. By running it
* on a background thread, there's no risk of accidentally causing UI lag.</p>
*
* <p>Note that {@link #awaitRunning()} can throw an unchecked {@link java.lang.IllegalStateException}
* if anything goes wrong during startup - you should probably handle it and use {@link Exception#getCause()} to figure
* out what went wrong more precisely. Same thing if you just use the {@link #startAsync()} method.</p>
*/
public class WalletAppKit extends AbstractIdleService {
protected static final Logger log = LoggerFactory.getLogger(WalletAppKit.class);
protected final String filePrefix;
protected final NetworkParameters params;
protected volatile BlockChain vChain;
protected volatile SPVBlockStore vStore;
protected ValidHashStore validHashStore;
protected volatile Wallet vWallet;
protected volatile PeerGroup vPeerGroup;
protected final File directory;
protected volatile File vWalletFile;
protected boolean useAutoSave = true;
protected PeerAddress[] peerAddresses;
protected PeerEventListener downloadListener;
protected boolean autoStop = true;
protected InputStream checkpoints;
protected boolean blockingStartup = true;
protected boolean useTor = false; // Perhaps in future we can change this to true.
protected String userAgent, version;
protected WalletProtobufSerializer.WalletFactory walletFactory;
@Nullable protected DeterministicSeed restoreFromSeed;
public WalletAppKit(NetworkParameters params, File directory, String filePrefix) {
this.params = checkNotNull(params);
this.directory = checkNotNull(directory);
this.filePrefix = checkNotNull(filePrefix);
}
/** Will only connect to the given addresses. Cannot be called after startup. */
public WalletAppKit setPeerNodes(PeerAddress... addresses) {
checkState(state() == State.NEW, "Cannot call after startup");
this.peerAddresses = addresses;
return this;
}
/** Will only connect to localhost. Cannot be called after startup. */
public WalletAppKit connectToLocalHost() {
try {
final InetAddress localHost = InetAddress.getLocalHost();
return setPeerNodes(new PeerAddress(localHost, params.getPort()));
} catch (UnknownHostException e) {
// Borked machine with no loopback adapter configured properly.
throw new RuntimeException(e);
}
}
/** If true, the wallet will save itself to disk automatically whenever it changes. */
public WalletAppKit setAutoSave(boolean value) {
checkState(state() == State.NEW, "Cannot call after startup");
useAutoSave = value;
return this;
}
/**
* If you want to learn about the sync process, you can provide a listener here. For instance, a
* {@link DownloadListener} is a good choice.
*/
public WalletAppKit setDownloadListener(PeerEventListener listener) {
this.downloadListener = listener;
return this;
}
/** If true, will register a shutdown hook to stop the library. Defaults to true. */
public WalletAppKit setAutoStop(boolean autoStop) {
this.autoStop = autoStop;
return this;
}
/**
* If set, the file is expected to contain a checkpoints file calculated with BuildCheckpoints. It makes initial
* block sync faster for new users - please refer to the documentation on the peercoinj website for further details.
*/
public WalletAppKit setCheckpoints(InputStream checkpoints) {
this.checkpoints = checkNotNull(checkpoints);
return this;
}
/**
* If true (the default) then the startup of this service won't be considered complete until the network has been
* brought up, peer connections established and the block chain synchronised. Therefore {@link #startAndWait()} can
* potentially take a very long time. If false, then startup is considered complete once the network activity
* begins and peer connections/block chain sync will continue in the background.
*/
public WalletAppKit setBlockingStartup(boolean blockingStartup) {
this.blockingStartup = blockingStartup;
return this;
}
/**
* Sets the string that will appear in the subver field of the version message.
* @param userAgent A short string that should be the name of your app, e.g. "My Wallet"
* @param version A short string that contains the version number, e.g. "1.0-BETA"
*/
public WalletAppKit setUserAgent(String userAgent, String version) {
this.userAgent = checkNotNull(userAgent);
this.version = checkNotNull(version);
return this;
}
/**
* If called, then an embedded Tor client library will be used to connect to the P2P network. The user does not need
* any additional software for this: it's all pure Java. As of April 2014 <b>this mode is experimental</b>.
*/
public WalletAppKit useTor() {
this.useTor = true;
return this;
}
/**
* If a seed is set here then any existing wallet that matches the file name will be renamed to a backup name,
* the chain file will be deleted, and the wallet object will be instantiated with the given seed instead of
* a fresh one being created. This is intended for restoring a wallet from the original seed. To implement restore
* you would shut down the existing appkit, if any, then recreate it with the seed given by the user, then start
* up the new kit. The next time your app starts it should work as normal (that is, don't keep calling this each
* time).
*/
public WalletAppKit restoreWalletFromSeed(DeterministicSeed seed) {
this.restoreFromSeed = seed;
return this;
}
/**
* <p>Override this to return wallet extensions if any are necessary.</p>
*
* <p>When this is called, chain(), store(), and peerGroup() will return the created objects, however they are not
* initialized/started.</p>
*/
protected List<WalletExtension> provideWalletExtensions() throws Exception {
return ImmutableList.of();
}
/**
* This method is invoked on a background thread after all objects are initialised, but before the peer group
* or block chain download is started. You can tweak the objects configuration here.
*/
protected void onSetupCompleted() { }
/**
* Tests to see if the spvchain file has an operating system file lock on it. Useful for checking if your app
* is already running. If another copy of your app is running and you start the appkit anyway, an exception will
* be thrown during the startup process. Returns false if the chain file does not exist.
*/
public boolean isChainFileLocked() throws IOException {
RandomAccessFile file2 = null;
try {
File file = new File(directory, filePrefix + ".spvchain");
if (!file.exists())
return false;
file2 = new RandomAccessFile(file, "rw");
FileLock lock = file2.getChannel().tryLock();
if (lock == null)
return true;
lock.release();
return false;
} finally {
if (file2 != null)
file2.close();
}
}
@Override
protected void startUp() throws Exception {
// Runs in a separate thread.
if (!directory.exists()) {
if (!directory.mkdirs()) {
throw new IOException("Could not create directory " + directory.getAbsolutePath());
}
}
log.info("Starting up with directory = {}", directory);
try {
File chainFile = new File(directory, filePrefix + ".spvchain");
File validHashFile = new File(directory, filePrefix + ".hashes");
boolean chainFileExists = chainFile.exists();
vWalletFile = new File(directory, filePrefix + ".wallet");
boolean shouldReplayWallet = (vWalletFile.exists() && !chainFileExists) || restoreFromSeed != null;
vWallet = createOrLoadWallet(shouldReplayWallet);
validHashStore = new ValidHashStore(validHashFile);
vStore = new SPVBlockStore(params, chainFile);
if ((!chainFileExists || restoreFromSeed != null) && checkpoints != null) {
// Initialize the chain file with a checkpoint to speed up first-run sync.
long time;
if (restoreFromSeed != null) {
time = restoreFromSeed.getCreationTimeSeconds();
if (chainFileExists) {
log.info("Deleting the chain file in preparation from restore.");
vStore.close();
if (!chainFile.delete())
throw new Exception("Failed to delete chain file in preparation for restore.");
vStore = new SPVBlockStore(params, chainFile);
}
} else {
time = vWallet.getEarliestKeyCreationTime();
}
CheckpointManager.checkpoint(params, checkpoints, vStore, time);
}
vChain = new BlockChain(params, vStore, validHashStore);
vPeerGroup = createPeerGroup();
if (this.userAgent != null)
vPeerGroup.setUserAgent(userAgent, version);
// Set up peer addresses or discovery first, so if wallet extensions try to broadcast a transaction
// before we're actually connected the broadcast waits for an appropriate number of connections.
if (peerAddresses != null) {
for (PeerAddress addr : peerAddresses) vPeerGroup.addAddress(addr);
vPeerGroup.setMaxConnections(peerAddresses.length);
peerAddresses = null;
} else {
vPeerGroup.addPeerDiscovery(new DnsDiscovery(params));
}
vChain.addWallet(vWallet);
vPeerGroup.addWallet(vWallet);
onSetupCompleted();
if (blockingStartup) {
vPeerGroup.startAsync();
vPeerGroup.awaitRunning();
// Make sure we shut down cleanly.
installShutdownHook();
completeExtensionInitiations(vPeerGroup);
// TODO: Be able to use the provided download listener when doing a blocking startup.
final DownloadListener listener = new DownloadListener();
vPeerGroup.startBlockChainDownload(listener);
listener.await();
} else {
vPeerGroup.startAsync();
vPeerGroup.addListener(new Service.Listener() {
@Override
public void running() {
completeExtensionInitiations(vPeerGroup);
final PeerEventListener l = downloadListener == null ? new DownloadListener() : downloadListener;
vPeerGroup.startBlockChainDownload(l);
}
@Override
public void failed(State from, Throwable failure) {
throw new RuntimeException(failure);
}
}, MoreExecutors.sameThreadExecutor());
}
} catch (BlockStoreException e) {
throw new IOException(e);
}
}
private Wallet createOrLoadWallet(boolean shouldReplayWallet) throws Exception {
Wallet wallet;
maybeMoveOldWalletOutOfTheWay();
if (vWalletFile.exists()) {
wallet = loadWallet(shouldReplayWallet);
} else {
wallet = createWallet();
wallet.freshReceiveKey();
for (WalletExtension e : provideWalletExtensions()) {
wallet.addExtension(e);
}
wallet.saveToFile(vWalletFile);
}
if (useAutoSave) wallet.autosaveToFile(vWalletFile, 200, TimeUnit.MILLISECONDS, null);
return wallet;
}
private Wallet loadWallet(boolean shouldReplayWallet) throws Exception {
Wallet wallet;
FileInputStream walletStream = new FileInputStream(vWalletFile);
try {
List<WalletExtension> extensions = provideWalletExtensions();
wallet = new Wallet(params);
WalletExtension[] extArray = extensions.toArray(new WalletExtension[extensions.size()]);
Protos.Wallet proto = WalletProtobufSerializer.parseToProto(walletStream);
final WalletProtobufSerializer serializer;
if (walletFactory != null)
serializer = new WalletProtobufSerializer(walletFactory);
else
serializer = new WalletProtobufSerializer();
wallet = serializer.readWallet(params, extArray, proto);
if (shouldReplayWallet)
wallet.clearTransactions(0);
} finally {
walletStream.close();
}
return wallet;
}
protected Wallet createWallet() {
KeyChainGroup kcg;
if (restoreFromSeed != null)
kcg = new KeyChainGroup(params, restoreFromSeed);
else
kcg = new KeyChainGroup(params);
if (walletFactory != null) {
return walletFactory.create(params, kcg);
} else {
return new Wallet(params, kcg); // default
}
}
private void maybeMoveOldWalletOutOfTheWay() {
if (restoreFromSeed == null) return;
if (!vWalletFile.exists()) return;
int counter = 1;
File newName;
do {
newName = new File(vWalletFile.getParent(), "Backup " + counter + " for " + vWalletFile.getName());
counter++;
} while (newName.exists());
log.info("Renaming old wallet file {} to {}", vWalletFile, newName);
if (!vWalletFile.renameTo(newName)) {
// This should not happen unless something is really messed up.
throw new RuntimeException("Failed to rename wallet for restore");
}
}
/*
* As soon as the transaction broadcaster han been created we will pass it to the
* payment channel extensions
*/
private void completeExtensionInitiations(TransactionBroadcaster transactionBroadcaster) {
StoredPaymentChannelClientStates clientStoredChannels = (StoredPaymentChannelClientStates)
vWallet.getExtensions().get(StoredPaymentChannelClientStates.class.getName());
if(clientStoredChannels != null) {
clientStoredChannels.setTransactionBroadcaster(transactionBroadcaster);
}
StoredPaymentChannelServerStates serverStoredChannels = (StoredPaymentChannelServerStates)
vWallet.getExtensions().get(StoredPaymentChannelServerStates.class.getName());
if(serverStoredChannels != null) {
serverStoredChannels.setTransactionBroadcaster(transactionBroadcaster);
}
}
protected PeerGroup createPeerGroup() throws TimeoutException {
if (useTor) {
TorClient torClient = new TorClient();
torClient.getConfig().setDataDirectory(directory);
return PeerGroup.newWithTor(params, vChain, torClient);
}
else
return new PeerGroup(params, vChain);
}
private void installShutdownHook() {
if (autoStop) Runtime.getRuntime().addShutdownHook(new Thread() {
@Override public void run() {
try {
WalletAppKit.this.stopAsync();
WalletAppKit.this.awaitTerminated();
} catch (Exception e) {
throw new RuntimeException(e);
}
}
});
}
@Override
protected void shutDown() throws Exception {
// Runs in a separate thread.
try {
vPeerGroup.stopAsync();
vPeerGroup.awaitTerminated();
vWallet.saveToFile(vWalletFile);
vStore.close();
vPeerGroup = null;
vWallet = null;
vStore = null;
vChain = null;
} catch (BlockStoreException e) {
throw new IOException(e);
}
}
public NetworkParameters params() {
return params;
}
public BlockChain chain() {
checkState(state() == State.STARTING || state() == State.RUNNING, "Cannot call until startup is complete");
return vChain;
}
public SPVBlockStore store() {
checkState(state() == State.STARTING || state() == State.RUNNING, "Cannot call until startup is complete");
return vStore;
}
public Wallet wallet() {
checkState(state() == State.STARTING || state() == State.RUNNING, "Cannot call until startup is complete");
return vWallet;
}
public PeerGroup peerGroup() {
checkState(state() == State.STARTING || state() == State.RUNNING, "Cannot call until startup is complete");
return vPeerGroup;
}
public File directory() {
return directory;
}
}
| apache-2.0 |
google-code-export/google-api-dfp-java | examples/v201211/suggestedadunitservice/GetSuggestedAdUnitsByStatementExample.java | 2843 | // Copyright 2012 Google Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package v201211.suggestedadunitservice;
import com.google.api.ads.dfp.lib.DfpService;
import com.google.api.ads.dfp.lib.DfpServiceLogger;
import com.google.api.ads.dfp.lib.DfpUser;
import com.google.api.ads.dfp.lib.utils.v201211.StatementBuilder;
import com.google.api.ads.dfp.v201211.Statement;
import com.google.api.ads.dfp.v201211.SuggestedAdUnit;
import com.google.api.ads.dfp.v201211.SuggestedAdUnitPage;
import com.google.api.ads.dfp.v201211.SuggestedAdUnitServiceInterface;
/**
* This example gets suggested ad units that have more than 50 requests. The
* statement retrieves up to the maximum page size limit of 500. This feature is
* only available to DFP premium solution networks.
*
* Tags: SuggestedAdUnitService.getSuggestedAdUnitsByStatement
*
* @author api.arogal@gmail.com (Adam Rogal)
*/
public class GetSuggestedAdUnitsByStatementExample {
public static void main(String[] args) {
try {
// Log SOAP XML request and response.
DfpServiceLogger.log();
// Get DfpUser from "~/dfp.properties".
DfpUser user = new DfpUser();
// Get the SuggestedAdUnitService.
SuggestedAdUnitServiceInterface suggestedAdUnitService =
user.getService(DfpService.V201211.SUGGESTED_AD_UNIT_SERVICE);
// Create a statement to only select suggested ad units that have more
// than 50 requests.
Statement filterStatement =
new StatementBuilder("WHERE numRequests > :numRequests LIMIT 500")
.putValue("numRequests", 50).toStatement();
// Get suggested ad units by statement.
SuggestedAdUnitPage page =
suggestedAdUnitService.getSuggestedAdUnitsByStatement(filterStatement);
if (page.getResults() != null) {
int i = page.getStartIndex();
for (SuggestedAdUnit suggestedAdUnit : page.getResults()) {
System.out.println(i + ") Suggested ad unit with ID \"" + suggestedAdUnit.getId()
+ "\" and number of requests \"" + suggestedAdUnit.getNumRequests()
+ "\" was found.");
i++;
}
}
System.out.println("Number of results found: " + page.getTotalResultSetSize());
} catch (Exception e) {
e.printStackTrace();
}
}
}
| apache-2.0 |
milinda/play-samlsso | play-samlsso-lib/src/main/java/org/pathirage/play/samlsso/SAMLResponseValidator.java | 18692 | /**
* Copyright 2014 Milinda Pathirage
*
* 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.pathirage.play.samlsso;
import org.joda.time.DateTime;
import org.opensaml.common.SAMLObject;
import org.opensaml.common.binding.SAMLMessageContext;
import org.opensaml.common.xml.SAMLConstants;
import org.opensaml.saml2.core.*;
import org.opensaml.saml2.encryption.Decrypter;
import org.opensaml.saml2.metadata.IDPSSODescriptor;
import org.opensaml.saml2.metadata.SPSSODescriptor;
import org.opensaml.security.MetadataCriteria;
import org.opensaml.security.SAMLSignatureProfileValidator;
import org.opensaml.xml.encryption.DecryptionException;
import org.opensaml.xml.security.*;
import org.opensaml.xml.security.credential.UsageType;
import org.opensaml.xml.security.criteria.EntityIDCriteria;
import org.opensaml.xml.security.criteria.UsageCriteria;
import org.opensaml.xml.signature.Signature;
import org.opensaml.xml.signature.SignatureTrustEngine;
import org.opensaml.xml.validation.ValidationException;
import org.opensaml.xml.validation.ValidatorSuite;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.List;
/**
* Based on pac4j org.pac4j.saml.sso.Saml2ResponseValidator and CXF SAMLProtocolResponseValidator
*/
public class SAMLResponseValidator {
private static final Logger log = LoggerFactory.getLogger(SAMLResponseValidator.class);
public static final String SAML2_STATUSCODE_SUCCESS =
"urn:oasis:names:tc:SAML:2.0:status:Success";
/* maximum skew in seconds between SP and IDP clocks */
private int acceptedSkew = 120;
/* maximum lifetime after a successfull authentication on an IDP */
private int maximumAuthenticationLifetime = 3600;
private SignatureTrustEngine trustEngine;
private Decrypter decrypter;
private String callbackUrl;
public SAMLResponseValidator(SignatureTrustEngine trustEngine, Decrypter decrypter, String callbackUrl) {
this.trustEngine = trustEngine;
this.decrypter = decrypter;
this.callbackUrl = callbackUrl;
}
public void isValidResponse(SAMLMessageContext messageContext) throws Exception {
SAMLObject responseObject = messageContext.getInboundSAMLMessage();
if (!(responseObject instanceof Response)) {
throw new Exception("Unknown SAML2 response type.");
}
Response response = (Response) responseObject;
if (response.getStatus() == null ||
response.getStatus().getStatusCode() == null) {
log.error("Either SAML response status or status code is null.");
throw new Exception("Invalid SAML response.");
}
if (!SAML2_STATUSCODE_SUCCESS.equals(response.getStatus().getStatusCode().getValue())) {
log.error("SAML response status code " + response.getStatus().getStatusCode().getValue() + " doesn't" +
"equal to expected status code " + SAML2_STATUSCODE_SUCCESS);
throw new Exception("Invalid SAML response.");
}
validateResponseAgainstSchema(response);
validateResponseSignature(response, messageContext);
for (EncryptedAssertion encryptedAssertion : response.getEncryptedAssertions()) {
try {
response.getAssertions().add(decrypter.decrypt(encryptedAssertion));
} catch (Exception e) {
log.error("Decryption failed for a assertion.", e);
}
}
Assertion subjectAssertion = validateSAMLSSOResponse(response, messageContext);
if(subjectAssertion == null){
throw new Exception("No valid subject assestion found in response.");
}
}
private Assertion validateSAMLSSOResponse(Response samlResponse, SAMLMessageContext messageContext) throws Exception {
for(Assertion assertion : samlResponse.getAssertions()){
if(assertion.getAuthnStatements().size() > 0){
try{
validateAssertion(assertion, messageContext);
} catch (Exception e){
log.error("Current assertion validation failed, continue with the next one", e);
continue;
}
return assertion;
}
}
return null;
}
/**
* 09-03-2014(Milinda) - Copied from pac4j and modify to make it work in this code.
* Validate the given assertion:
* - issueInstant
* - issuer
* - subject
* - conditions
* - authnStatements
* - signature
*
* @param assertion
* @param messageContext
*/
protected void validateAssertion(final Assertion assertion, final SAMLMessageContext messageContext) {
if (!isIssueInstantValid(assertion.getIssueInstant())) {
throw new RuntimeException("Assertion issue instant is too old or in the future");
}
validateIssuer(assertion.getIssuer(), messageContext);
if (assertion.getSubject() != null) {
validateSubject(assertion.getSubject(), messageContext, decrypter);
} else {
throw new RuntimeException("Assertion subject cannot be null");
}
validateAssertionConditions(assertion.getConditions(), messageContext);
validateAuthenticationStatements(assertion.getAuthnStatements(), messageContext);
validateAssertionSignature(assertion.getSignature(), messageContext);
}
/**
* 09-03-2014(Milinda) - Copied from pac4j and modify to make it work in this code.
* Validate assertionConditions
* - notBefore
* - notOnOrAfter
*
* @param conditions
* @param context
*/
protected void validateAssertionConditions(final Conditions conditions, final SAMLMessageContext context) {
if (conditions == null) {
throw new RuntimeException("Assertion conditions cannot be null");
}
if (conditions.getNotBefore() != null) {
if (conditions.getNotBefore().minusSeconds(acceptedSkew).isAfterNow()) {
throw new RuntimeException("Assertion condition notBefore is not valid");
}
}
if (conditions.getNotOnOrAfter() != null) {
if (conditions.getNotOnOrAfter().plusSeconds(acceptedSkew).isBeforeNow()) {
throw new RuntimeException("Assertion condition notOnOrAfter is not valid");
}
}
validateAudienceRestrictions(conditions.getAudienceRestrictions(), context.getLocalEntityId());
}
/**
* 09-03-2014(Milinda) - Copied from pac4j and modify to make it work in this code.
* Validate audience by matching the SP entityId.
*
* @param audienceRestrictions
* @param spEntityId
*/
protected void validateAudienceRestrictions(final List<AudienceRestriction> audienceRestrictions,
final String spEntityId) {
if (audienceRestrictions == null || audienceRestrictions.size() == 0) {
throw new RuntimeException("Audience restrictions cannot be null or empty");
}
if (!matchAudienceRestriction(audienceRestrictions, spEntityId)) {
throw new RuntimeException("Assertion audience does not match SP configuration");
}
}
private boolean matchAudienceRestriction(final List<AudienceRestriction> audienceRestrictions,
final String spEntityId) {
for (AudienceRestriction audienceRestriction : audienceRestrictions) {
if (audienceRestriction.getAudiences() != null) {
for (Audience audience : audienceRestriction.getAudiences()) {
if (spEntityId.equals(audience.getAudienceURI())) {
return true;
}
}
}
}
return false;
}
/**
* 09-03-2014(Milinda) - Copied from pac4j and modify to make it work in this code.
* Validate assertion signature. If none is found and the SAML response did not have one and the SP requires
* the assertions to be signed, the validation fails.
*
* @param signature
* @param context
*/
protected void validateAssertionSignature(final Signature signature, final SAMLMessageContext context) {
if (signature != null) {
validateSignature(signature, context.getPeerEntityMetadata().getEntityID());
} else if (((SPSSODescriptor) context.getLocalEntityRoleMetadata()).getWantAssertionsSigned()
&& !context.isInboundSAMLMessageAuthenticated()) {
throw new RuntimeException("Assertion or response must be signed");
}
}
/**
* 09-03-2014(Milinda) - Copied from pac4j and modify to make it work in this code.
* Validate the given digital signature by checking its profile and value.
*
* @param signature
* @param idpEntityId
*/
protected void validateSignature(final Signature signature, final String idpEntityId) {
SAMLSignatureProfileValidator validator = new SAMLSignatureProfileValidator();
try {
validator.validate(signature);
} catch (ValidationException e) {
throw new RuntimeException("SAMLSignatureProfileValidator failed to validate signature", e);
}
CriteriaSet criteriaSet = new CriteriaSet();
criteriaSet.add(new UsageCriteria(UsageType.SIGNING));
criteriaSet.add(new MetadataCriteria(IDPSSODescriptor.DEFAULT_ELEMENT_NAME, SAMLConstants.SAML20P_NS));
criteriaSet.add(new EntityIDCriteria(idpEntityId));
boolean valid;
try {
valid = trustEngine.validate(signature, criteriaSet);
} catch (org.opensaml.xml.security.SecurityException e) {
throw new RuntimeException("An error occured during signature validation", e);
}
if (!valid) {
throw new RuntimeException("Signature is not trusted");
}
}
/**
* 09-03-2014(Milinda) - Copied from pac4j and modify to make it work in this code.
* Validate the given authnStatements:
* - authnInstant
* - sessionNotOnOrAfter
*
* @param authnStatements
* @param messageContext
*/
protected void validateAuthenticationStatements(final List<AuthnStatement> authnStatements,
final SAMLMessageContext messageContext) {
for (AuthnStatement statement : authnStatements) {
if (!isAuthnInstantValid(statement.getAuthnInstant())) {
throw new RuntimeException("Authentication issue instant is too old or in the future");
}
if (statement.getSessionNotOnOrAfter() != null && statement.getSessionNotOnOrAfter().isBeforeNow()) {
throw new RuntimeException("Authentication session between IDP and subject has ended");
}
// TODO implement authnContext validation
}
}
private boolean isAuthnInstantValid(DateTime authnInstant) {
return isDateValid(authnInstant, maximumAuthenticationLifetime);
}
/**
* 09-03-2014(Milinda) - Copied from pac4j and modify to make it work in this code.
* Validate issuer format and value.
*
* @param issuer
* @param messageContext
*/
protected void validateIssuer(final Issuer issuer, final SAMLMessageContext messageContext) {
if (issuer.getFormat() != null && !issuer.getFormat().equals(NameIDType.ENTITY)) {
throw new RuntimeException("Issuer type is not entity but " + issuer.getFormat());
}
if (!messageContext.getPeerEntityMetadata().getEntityID().equals(issuer.getValue())) {
throw new RuntimeException("Issuer " + issuer.getValue() + " does not match idp entityId "
+ messageContext.getPeerEntityMetadata().getEntityID());
}
}
/**
* 09-03-2014(Milinda) - Copied from pac4j and modify to make it work in this code.
* Validate the given subject by finding a valid Bearer confirmation. If the subject is valid,
* put its nameID in the context.
*
* @param subject
* @param messageContext
* @param decrypter
*/
@SuppressWarnings("unchecked")
protected void validateSubject(final Subject subject, final SAMLMessageContext messageContext,
final Decrypter decrypter) {
for (SubjectConfirmation confirmation : subject.getSubjectConfirmations()) {
if (SubjectConfirmation.METHOD_BEARER.equals(confirmation.getMethod())) {
if (isValidBearerSubjectConfirmationData(confirmation.getSubjectConfirmationData(), messageContext)) {
NameID nameID = null;
if (subject.getEncryptedID() != null) {
try {
nameID = (NameID) decrypter.decrypt(subject.getEncryptedID());
} catch (DecryptionException e) {
throw new RuntimeException("Decryption of nameID's subject failed", e);
}
} else {
nameID = subject.getNameID();
}
messageContext.setSubjectNameIdentifier(nameID);
return;
}
}
}
throw new RuntimeException("Subject confirmation validation failed");
}
/**
* 09-03-2014(Milinda) - Copied from pac4j and modify to make it work in this code.
* Validate Bearer subject confirmation data
* - notBefore
* - NotOnOrAfter
* - recipient
*
* @param data
* @param context
* @return true if all Bearer subject checks are passing
*/
protected boolean isValidBearerSubjectConfirmationData(final SubjectConfirmationData data,
final SAMLMessageContext context) {
if (data == null) {
log.debug("SubjectConfirmationData cannot be null for Bearer confirmation");
return false;
}
// TODO Validate inResponseTo
if (data.getNotBefore() != null) {
log.debug("SubjectConfirmationData notBefore must be null for Bearer confirmation");
return false;
}
if (data.getNotOnOrAfter() == null) {
log.debug("SubjectConfirmationData notOnOrAfter cannot be null for Bearer confirmation");
return false;
}
if (data.getNotOnOrAfter().plusSeconds(acceptedSkew).isBeforeNow()) {
log.debug("SubjectConfirmationData notOnOrAfter is too old");
return false;
}
if (data.getRecipient() == null) {
log.debug("SubjectConfirmationData recipient cannot be null for Bearer confirmation");
return false;
} else {
if (!data.getRecipient().equals(callbackUrl)) {
log.debug("SubjectConfirmationData recipient {} does not match SP assertion consumer URL, found",
data.getRecipient());
return false;
}
}
return true;
}
/**
* 09-03-2014(Milinda) - Copied from pac4j and modify to make it work in this code.
* @param issueInstant
* @param interval
* @return
*/
private boolean isDateValid(final DateTime issueInstant, int interval) {
long now = System.currentTimeMillis();
return issueInstant.isBefore(now + acceptedSkew * 1000)
&& issueInstant.isAfter(now - (acceptedSkew + interval) * 1000);
}
/**
* 09-03-2014(Milinda) - Copied from pac4j and modify to make it work in this code.
* @param issueInstant
* @return
*/
private boolean isIssueInstantValid(final DateTime issueInstant) {
return isDateValid(issueInstant, 0);
}
/**
* 09-03-2014(Milinda) - Copied from pac4j and modify to make it work in this code.
* @param samlResponse
* @throws Exception
*/
private void validateResponseAgainstSchema(Response samlResponse) throws Exception {
ValidatorSuite schemaValidators =
org.opensaml.Configuration.getValidatorSuite("saml2-core-schema-validator");
try {
schemaValidators.validate(samlResponse);
} catch (ValidationException e) {
log.error("SAML response schema validation error.", e);
throw new Exception("Invalid SAML response.", e);
}
}
/**
* 09-03-2014(Milinda) - Copied from pac4j and modify to make it work in this code.
* @param samlResponse
* @param messageContext
* @throws Exception
*/
private void validateResponseSignature(Response samlResponse, SAMLMessageContext messageContext) throws Exception {
if (!samlResponse.isSigned()) {
return;
}
SAMLSignatureProfileValidator signatureProfileValidator = new SAMLSignatureProfileValidator();
try {
signatureProfileValidator.validate(samlResponse.getSignature());
} catch (ValidationException ve) {
log.error("SAML response contains invalid signature profile.");
throw new Exception("Invalid SAML response.", ve);
}
CriteriaSet criteriaSet = new CriteriaSet();
criteriaSet.add(new UsageCriteria(UsageType.SIGNING));
criteriaSet.add(new MetadataCriteria(IDPSSODescriptor.DEFAULT_ELEMENT_NAME, SAMLConstants.SAML20P_NS));
criteriaSet.add(new EntityIDCriteria(messageContext.getPeerEntityId()));
boolean valid;
try {
valid = trustEngine.validate(samlResponse.getSignature(), criteriaSet);
} catch (Exception e) {
throw new Exception("SAML response signature validation failed.", e);
}
if (!valid) {
log.error("Invalid signature in SAML response.");
throw new Exception("Invalid SAML response.");
}
messageContext.setInboundSAMLMessageAuthenticated(true);
}
}
| apache-2.0 |
ggomez1973/motherhacker | campsite/src/main/java/com/challenge/campsite/services/IAdminService.java | 257 | package com.challenge.campsite.services;
import com.challenge.campsite.domain.Reservation;
import java.util.List;
import java.util.UUID;
public interface IAdminService {
List<Reservation> getReservations();
Reservation getReservation(UUID id);
}
| apache-2.0 |
ecki/commons-vfs | commons-vfs2/src/test/java/org/apache/commons/vfs2/provider/ftps/MultipleConnectionTestCase.java | 2687 | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.commons.vfs2.provider.ftps;
import java.io.IOException;
import java.net.SocketException;
import org.apache.commons.net.ftp.FTPSClient;
import org.apache.commons.vfs2.FileObject;
import org.apache.commons.vfs2.FileSystemException;
import org.apache.commons.vfs2.VFS;
import org.apache.ftpserver.ftplet.FtpException;
import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.Test;
public class MultipleConnectionTestCase {
@BeforeClass
public static void setUpClass() throws FtpException, IOException {
AbstractFtpsProviderTestCase.setUpClass(true);
}
@AfterClass
public static void tearDownClass() {
AbstractFtpsProviderTestCase.tearDownClass();
}
private FTPSClient init(final FTPSClient client) {
client.enterLocalPassiveMode();
return client;
}
private FileObject resolveRoot() throws FileSystemException {
return VFS.getManager().resolveFile(AbstractFtpsProviderTestCase.getConnectionUri(),
new FtpsProviderImplicitTestCase().getFileSystemOptions());
}
@Test
public void testConnectRoot() throws IOException {
resolveRoot();
resolveRoot();
}
@Test
public void testUnderlyingConnect() throws SocketException, IOException {
final FTPSClient client1 = this.init(new FTPSClient(true));
final FTPSClient client2 = this.init(new FTPSClient(true));
try {
final String hostname = "localhost";
client1.connect(hostname, AbstractFtpsProviderTestCase.getSocketPort());
client2.connect(hostname, AbstractFtpsProviderTestCase.getSocketPort());
} finally {
if (client1 != null) {
client1.disconnect();
}
if (client2 != null) {
client2.disconnect();
}
}
}
}
| apache-2.0 |
h/paco | Paco-Server/src/com/google/sampling/experiential/server/DefaultExperimentService.java | 24159 | package com.google.sampling.experiential.server;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.logging.Logger;
import org.joda.time.DateMidnight;
import org.joda.time.DateTime;
import org.joda.time.DateTimeZone;
import com.google.appengine.api.datastore.DatastoreService;
import com.google.appengine.api.datastore.DatastoreServiceFactory;
import com.google.appengine.api.datastore.Key;
import com.google.appengine.api.datastore.Transaction;
import com.google.appengine.api.datastore.TransactionOptions;
import com.google.common.base.Joiner;
import com.google.common.base.Strings;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.google.common.collect.Sets;
import com.google.sampling.experiential.datastore.ExperimentJsonEntityManager;
import com.google.sampling.experiential.datastore.PublicExperimentList;
import com.google.sampling.experiential.datastore.PublicExperimentList.CursorExerimentIdListPair;
import com.google.sampling.experiential.model.Event;
import com.pacoapp.paco.shared.model.SignalTimeDAO;
import com.pacoapp.paco.shared.model2.ActionTrigger;
import com.pacoapp.paco.shared.model2.ExperimentDAO;
import com.pacoapp.paco.shared.model2.ExperimentGroup;
import com.pacoapp.paco.shared.model2.ExperimentIdQueryResult;
import com.pacoapp.paco.shared.model2.ExperimentJoinQueryResult;
import com.pacoapp.paco.shared.model2.ExperimentQueryResult;
import com.pacoapp.paco.shared.model2.ExperimentValidator;
import com.pacoapp.paco.shared.model2.InterruptCue;
import com.pacoapp.paco.shared.model2.InterruptTrigger;
import com.pacoapp.paco.shared.model2.JsonConverter;
import com.pacoapp.paco.shared.model2.PacoAction;
import com.pacoapp.paco.shared.model2.Pair;
import com.pacoapp.paco.shared.model2.Schedule;
import com.pacoapp.paco.shared.model2.ScheduleTrigger;
import com.pacoapp.paco.shared.model2.SignalTime;
import com.pacoapp.paco.shared.model2.ValidationMessage;
import com.pacoapp.paco.shared.scheduling.ActionScheduleGenerator;
import com.pacoapp.paco.shared.util.ExperimentHelper;
class DefaultExperimentService implements ExperimentService {
private static final Logger log = Logger.getLogger(DefaultExperimentService.class.getName());
private String getExperimentAsJson(Long id) {
return ExperimentJsonEntityManager.getExperiment(id);
}
@Override
/**
* This is to be used server side only because it does not scrub out participant id information.
*/
public ExperimentDAO getExperiment(Long id) {
String experimentJson = getExperimentAsJson(id);
if (experimentJson != null) {
return JsonConverter.fromSingleEntityJson(experimentJson);
}
return null;
}
@Override
public List<ExperimentDAO> getExperimentsById(List<Long> experimentIds, String email, DateTimeZone timezone) {
List<Long> allowedExperimentIds = Lists.newArrayList();
for (Long experimentId : experimentIds) {
if (ExperimentAccessManager.isUserAllowedToGetExperiments(experimentId, email)) {
allowedExperimentIds.add(experimentId);
}
}
List<String> experimentJsons = getExperimentsByIdAsJson(allowedExperimentIds, email, timezone);
List<ExperimentDAO> experiments = Lists.newArrayList();
for (String experimentJson : experimentJsons) {
if (experimentJson != null) {
experiments .add(JsonConverter.fromSingleEntityJson(experimentJson));
}
}
removeNonAdminData(email, experiments);
return experiments;
}
protected List<ExperimentDAO> getExperimentsByIdInternal(List<Long> experimentIds, String email, DateTimeZone timezone) {
List<String> experimentJsons = getExperimentsByIdAsJson(experimentIds, email, timezone);
log.info("Got back " + experimentJsons.size() +" jsons for " + experimentIds.size() + " ids ( " + Joiner.on(",").join(experimentIds) + ")");
List<ExperimentDAO> experiments = Lists.newArrayList();
for (String experimentJson : experimentJsons) {
if (experimentJson != null) {
final ExperimentDAO fromSingleEntityJson = JsonConverter.fromSingleEntityJson(experimentJson);
if (fromSingleEntityJson != null) {
experiments.add(fromSingleEntityJson);
log.info("Retrieved experimentDAO from json for experiment: " + fromSingleEntityJson.getTitle());
} else {
log.severe("could not recreate experiment for experiment data: " + experimentJson);
}
}
}
return experiments;
}
protected List<String> getExperimentsByIdAsJson(List<Long> experimentIds, String email, DateTimeZone timezone) {
// TODO who can access this call and in what role?
// is email a participant or an admin?
return ExperimentJsonEntityManager.getExperimentsById(experimentIds);
}
// save experiments
@Override
public List<ValidationMessage> saveExperiment(ExperimentDAO experiment,
String loggedInUserEmail,
DateTimeZone timezone) {
if (ExperimentAccessManager.isUserAllowedToSaveExperiment(experiment.getId(), loggedInUserEmail)) {
ensureIdsOnActionTriggerObjects(experiment);
lowercaseAllEmailAddresses(experiment);
ExperimentValidator validator = new ExperimentValidator();
experiment.validateWith(validator);
List<ValidationMessage> results = validator.getResults();
if (!results.isEmpty()) {
return results;
}
DatastoreService ds = DatastoreServiceFactory.getDatastoreService();
TransactionOptions options = TransactionOptions.Builder.withXG(true);
Transaction tx = ds.beginTransaction(options);
try {
if (experiment.getId() == null) {
experiment.setCreator(loggedInUserEmail);
}
if (!experiment.getAdmins().contains(loggedInUserEmail)) {
experiment.getAdmins().add(loggedInUserEmail);
}
if (Strings.isNullOrEmpty(experiment.getContactEmail())) {
experiment.setContactEmail(experiment.getCreator());
}
Integer version = experiment.getVersion();
if (version == null || version == 0) {
version = 1;
} else {
version++;
}
experiment.setVersion(version);
experiment.setModifyDate(com.pacoapp.paco.shared.util.TimeUtil.formatDate(new Date().getTime()));
Key experimentKey = ExperimentJsonEntityManager.saveExperiment(ds, tx, JsonConverter.jsonify(experiment),
experiment.getId(),
experiment.getTitle(),
experiment.getVersion());
experiment.setId(experimentKey.getId());
ExperimentAccessManager.updateAccessControlEntities(ds, tx, experiment, experimentKey, timezone);
tx.commit();
return null;
} catch (Exception e) {
e.printStackTrace();
throw new IllegalStateException(e);
} finally {
if (tx.isActive()) {
tx.rollback();
}
}
}
throw new IllegalStateException(loggedInUserEmail + " does not have permission to edit " + experiment.getTitle());
}
private void lowercaseAllEmailAddresses(ExperimentDAO experiment) {
experiment.setAdmins(ExperimentAccessManager.lowerCaseEmails(experiment.getAdmins()));
if (experiment.getPublishedUsers() != null && !experiment.getPublishedUsers().isEmpty()) {
experiment.setPublishedUsers(ExperimentAccessManager.lowerCaseEmails(experiment.getPublishedUsers()));
}
experiment.setCreator(experiment.getCreator().toLowerCase());
}
private void ensureIdsOnActionTriggerObjects(ExperimentDAO experiment) {
// ill-formed experiments will be handled next in the validation phase before saving.
long id = new Date().getTime();
List<ExperimentGroup> groups = experiment.getGroups();
if (groups == null) {
return;
}
for (ExperimentGroup experimentGroup : groups) {
List<ActionTrigger> actionTriggers = experimentGroup.getActionTriggers();
if (actionTriggers != null) {
for (ActionTrigger actionTrigger : actionTriggers) {
if (actionTrigger.getId() == null) {
actionTrigger.setId(id++);
}
List<PacoAction> actions = actionTrigger.getActions();
if (actions != null) {
for (PacoAction pacoAction : actions) {
if (pacoAction.getId() == null) {
pacoAction.setId(id++);
}
}
}
if (actionTrigger instanceof ScheduleTrigger) {
ScheduleTrigger scheduleTrigger = (ScheduleTrigger)actionTrigger;
List<Schedule> schedules = scheduleTrigger.getSchedules();
if (schedules != null) {
for (Schedule schedule : schedules) {
if (schedule.getId() == null) {
schedule.setId(id++);
}
}
}
} else if (actionTrigger instanceof InterruptTrigger) {
InterruptTrigger interruptTrigger = (InterruptTrigger)actionTrigger;
List<InterruptCue> cues = interruptTrigger.getCues();
for (InterruptCue interruptCue : cues) {
if (interruptCue.getId() == null) {
interruptCue.setId(id++);
}
}
}
}
}
}
}
// delete experiments
@Override
public Boolean deleteExperiment(Long experimentId, String loggedInUserEmail) {
if (experimentId == null) {
throw new IllegalArgumentException("Cannot delete experiment: " + experimentId + " because it does not exist");
}
if (ExperimentAccessManager.isUserAllowedToDeleteExperiment(experimentId, loggedInUserEmail)) {
DatastoreService ds = DatastoreServiceFactory.getDatastoreService();
TransactionOptions options = TransactionOptions.Builder.withXG(true);
Transaction tx = ds.beginTransaction(options);
try {
ExperimentJsonEntityManager.delete(ds, tx, experimentId);
ExperimentAccessManager.deleteAccessControlEntitiesFor(ds, tx, experimentId);
tx.commit();
return true;
} catch (Exception e) {
e.printStackTrace();
} finally {
if (tx.isActive()) {
tx.rollback();
}
}
return false;
}
throw new IllegalStateException(loggedInUserEmail + " does not have permission to delete " + experimentId);
}
@Override
public Boolean deleteExperiment(ExperimentDAO experimentDAO, String loggedInUserEmail) {
return deleteExperiment(experimentDAO.getId(), loggedInUserEmail);
}
@Override
public Boolean deleteExperiments(List<Long> experimentIds, String email) {
if (experimentIds == null || experimentIds.isEmpty()) {
throw new IllegalArgumentException("No ids specified for deletion");
}
if (ExperimentAccessManager.isUserAllowedToDeleteExperiments(experimentIds, email)) {
DatastoreService ds = DatastoreServiceFactory.getDatastoreService();
TransactionOptions options = TransactionOptions.Builder.withXG(true);
Transaction tx = ds.beginTransaction(options);
try {
ExperimentJsonEntityManager.delete(ds, tx, experimentIds);
ExperimentAccessManager.deleteAccessControlEntitiesFor(ds, tx, experimentIds);
tx.commit();
return true;
} catch (Exception e) {
e.printStackTrace();
} finally {
if (tx.isActive()) {
tx.rollback();
}
}
return false;
}
throw new IllegalStateException(email + " does not have permission to delete one or more of the experiments: " + Joiner.on(",").join(experimentIds));
}
@Override
public ExperimentQueryResult getMyJoinableExperiments(String email, DateTimeZone timeZoneForClient,
Integer limit, String cursor) {
// TODO figure out what to do about getting a paginated result over two tables. Right now, return everything.
// Actually, the experiment hub will get rid of this broad query
ExperimentIdQueryResult adminExperimentIdQueryResult = ExperimentAccessManager.getExistingExperimentIdsForAdmin(email, 0, null);
List<Long> experimentIds = Lists.newArrayList();
experimentIds.addAll(adminExperimentIdQueryResult.getExperiments());
ExperimentIdQueryResult existingPublishedExperimentIdsForUser = ExperimentAccessManager.getExistingPublishedExperimentIdsForUser(email, 0, null);
experimentIds.addAll(existingPublishedExperimentIdsForUser.getExperiments());
List<ExperimentDAO> experiments = getExperimentsByIdInternal(experimentIds, email, timeZoneForClient);
experiments = removeEnded(experiments, timeZoneForClient);
removeNonAdminData(email, experiments);
// for now, use the cursor as an offset to return the requested subset.
int offset = 0;
if (!Strings.isNullOrEmpty(cursor)) {
try {
offset = Integer.parseInt(cursor);
} catch (NumberFormatException e) {
offset = 0;
}
}
if (limit != null && limit > 0) {
int end = Math.min(offset + limit, experiments.size());
List<ExperimentDAO> experimentSubset = experiments.subList(offset, end);
if (end < experiments.size()) {
cursor = Integer.toString(end);
} else {
cursor = null;
}
return new ExperimentQueryResult(cursor, experimentSubset);
} else {
return new ExperimentQueryResult(null, experiments);
}
}
private List<ExperimentDAO> removeEnded(List<ExperimentDAO> experiments, DateTimeZone timeZoneForClient) {
List<ExperimentDAO> keepers = Lists.newArrayList();
DateMidnight now = DateTime.now().withZone(timeZoneForClient).toDateMidnight();
for (ExperimentDAO experimentDAO : experiments) {
final DateTime latestEndDate = getLatestEndDate(experimentDAO);
if (latestEndDate == null || !now.isAfter(latestEndDate)) {
keepers.add(experimentDAO);
}
}
return keepers;
}
private DateTime getLatestEndDate(ExperimentDAO experimentDAO) {
return ActionScheduleGenerator.getLastEndTime(experimentDAO);
}
@Override
public ExperimentQueryResult getMyJoinedExperiments(String email, DateTimeZone timeZoneForClient,
Integer limit, String cursor) {
ExperimentJoinQueryResult experimentIdJoinDatePairs = ExperimentAccessManager.getJoinedExperimentsFor(email, limit == null ? 1000 : limit, cursor);
if (experimentIdJoinDatePairs.getExperiments() == null ||
// we got zero back, so we haven't updated yet. This is true if there is no cursor. If there is a cursor, we have just exhausted the list.
(experimentIdJoinDatePairs.getExperiments().size() == 0 && cursor == null)) {
List<Event> events = getJoinEventsForLoggedInUser(email, timeZoneForClient);
List<Pair<Long, Date>> uniqueExperimentIdJoinDatePairs = getUniqueExperimentIdAndJoinDates(events);
if (uniqueExperimentIdJoinDatePairs.size() > 0) {
ExperimentAccessManager.addJoinedExperimentsFor(email, uniqueExperimentIdJoinDatePairs);
}
experimentIdJoinDatePairs.setExperiments(uniqueExperimentIdJoinDatePairs);
}
List<ExperimentDAO> experimentDAOs = Lists.newArrayList();
if (experimentIdJoinDatePairs.getExperiments().size() == 0) {
return new ExperimentQueryResult(null, experimentDAOs);
}
Map<Long, Date> experimentIds = Maps.newHashMap();
for (Pair<Long,Date> pair: experimentIdJoinDatePairs.getExperiments()) {
experimentIds.put(pair.first, pair.second);
}
List<ExperimentDAO> experiments = getExperimentsByIdInternal(Lists.newArrayList(experimentIds.keySet()), email, timeZoneForClient);
removeNonAdminData(email, experiments);
addJoinDate(experiments, experimentIds);
return new ExperimentQueryResult(experimentIdJoinDatePairs.getCursor(), experiments); // TODO honor the limit and cursor
}
private void addJoinDate(List<ExperimentDAO> experiments, Map<Long, Date> experimentIds) {
// Are the experiments returned in the order the ids were sent?
// Can't say for sure so n^2 it is
for (ExperimentDAO experiment : experiments) {
Date date = experimentIds.get(experiment.getId());
experiment.setJoinDate(com.pacoapp.paco.shared.util.TimeUtil.formatDate(date.getTime()));
}
}
public static List<Pair<Long, Date>> getUniqueExperimentIdAndJoinDates(List<Event> events) {
Set<Pair<Long, Date>> experimentIds = Sets.newHashSet();
for(Event event : events) {
if (event.getExperimentId() == null) {
continue; // legacy check
}
long experimentId = Long.parseLong(event.getExperimentId());
Date joinDate = event.getResponseTime();
Pair<Long, Date> pair = new Pair<Long, Date>(experimentId, joinDate);
experimentIds.add(pair);
}
return Lists.newArrayList(experimentIds);
}
public static List<Event> getJoinEventsForLoggedInUser(String loggedInUserEmail, DateTimeZone timeZoneOnClient) {
List<com.google.sampling.experiential.server.Query> queries = new QueryParser().parse("who=" + loggedInUserEmail);
List<Event> events = EventRetriever.getInstance().getEvents(queries, loggedInUserEmail, timeZoneOnClient, 0, 20000);
System.out.println("DEFAULT EVENT SIZE: " + events.size());
Map<String, Event> eventsByExperimentId = Maps.newHashMap();
for (Event event : events) {
if (event.isJoined()) {
String experimentId = event.getExperimentId();
if (experimentId == null) {
continue;
}
final Event eventWithSameId = eventsByExperimentId.get(experimentId);
if (eventWithSameId != null) {
if (eventWithSameId.getResponseTime().before(event.getResponseTime())) {
eventsByExperimentId.put(event.getExperimentId(), event);
}
} else {
eventsByExperimentId.put(event.getExperimentId(), event);
}
}
}
return Lists.newArrayList(eventsByExperimentId.values());
}
@Override
public ExperimentQueryResult getUsersAdministeredExperiments(String email, DateTimeZone timezone, Integer limit,
String cursor) {
ExperimentIdQueryResult experimentIdsQueryResult = ExperimentAccessManager.getExistingExperimentIdsForAdmin(email, limit == null ? 0 : limit, cursor);
//log.info("Administered experiments for: " + email + ". Count: " + experimentIds.size() + ". ids = " + Joiner.on(",").join(experimentIds));
List<ExperimentDAO> experiments = getExperimentsByIdInternal(experimentIdsQueryResult.getExperiments(), email, timezone);
return new ExperimentQueryResult(experimentIdsQueryResult.getCursor(), experiments);
}
@Override
public ExperimentQueryResult getExperimentsPublishedPublicly(DateTimeZone timezone, Integer limit, String cursor, String email) {
CursorExerimentIdListPair cursorIdPair = PublicExperimentList.getPublicExperiments(timezone.getID(), limit, cursor);
List<ExperimentDAO> experiments = getExperimentsByIdInternal(cursorIdPair.ids, null, timezone);
removeNonAdminData(email, experiments);
return new ExperimentQueryResult(cursorIdPair.cursor, experiments);
}
public void removeNonAdminData(String email, List<ExperimentDAO> experiments) {
removeOtherPublished(experiments, email);
removeAdmins(experiments, email);
removeCreator(experiments, email);
}
private void removeOtherPublished(List<ExperimentDAO> experiments, String email) {
for (ExperimentDAO experimentDAO : experiments) {
if (!experimentDAO.getAdmins().contains(email)) {
List<String> empty = Lists.newArrayList();
experimentDAO.setPublishedUsers(empty);
}
}
}
private void removeCreator(List<ExperimentDAO> experiments, String email) {
for (ExperimentDAO experimentDAO : experiments) {
if (!experimentDAO.getAdmins().contains(email)) {
String contact = experimentDAO.getContactEmail();
if (Strings.isNullOrEmpty(contact)) {
experimentDAO.setContactEmail(experimentDAO.getCreator());
} else {
experimentDAO.setCreator(null);
}
}
}
}
private void removeAdmins(List<ExperimentDAO> experiments ,String email) {
for (ExperimentDAO experimentDAO : experiments) {
if (!experimentDAO.getAdmins().contains(email)) {
List<String> empty = Lists.newArrayList();
experimentDAO.setAdmins(empty);
}
}
}
// referred experiments
@Override
public ExperimentDAO getReferredExperiment(long referredId) {
// TODO Auto-generated method stub
return null;
}
@Override
public void setReferredExperiment(Long referringExperimentId, Long referencedExperimentId) {
// TODO Auto-generated method stub
}
//utility apis that probably belong somewhere else
@Override
public boolean isOver(ExperimentDAO experiment, DateTime nowInUserTimezone) {
for (ExperimentGroup group : experiment.getGroups()) {
boolean groupIsOver = group.getFixedDuration() != null && group.getFixedDuration()
&& getEndDateTime(group).isBefore(nowInUserTimezone);
if (!groupIsOver) {
return false;
}
}
return true;
}
private DateTime getEndDateTime(ExperimentGroup group) {
DateTime lastEndDate = null;
List<ActionTrigger> activeTriggers = group.getActionTriggers();
for (ActionTrigger actionTrigger : activeTriggers) {
if (actionTrigger instanceof InterruptTrigger) {
DateTime thisActionTriggerEndDate = TimeUtil.getDateMidnightForDateString(group.getEndDate()).plusDays(1).toDateTime();
lastEndDate = latestOf(lastEndDate, thisActionTriggerEndDate);
} else {
ScheduleTrigger scheduleTrigger = (ScheduleTrigger) actionTrigger;
for (Schedule schedule : scheduleTrigger.getSchedules()) {
if (schedule.getScheduleType().equals(Schedule.WEEKDAY)) {
List<SignalTime> signalTimes = schedule.getSignalTimes();
SignalTime lastSignalTime = signalTimes.get(signalTimes.size() - 1);
if (lastSignalTime.getType() == SignalTimeDAO.FIXED_TIME) {
DateTime thisScheduleEndDate = TimeUtil.getDateMidnightForDateString(group.getEndDate()).toDateTime().withMillisOfDay(lastSignalTime.getFixedTimeMillisFromMidnight());
lastEndDate = latestOf(lastEndDate, thisScheduleEndDate);
} else {
DateTime thisScheduleEndDate = TimeUtil.getDateMidnightForDateString(group.getEndDate()).plusDays(1).toDateTime();
lastEndDate = latestOf(lastEndDate, thisScheduleEndDate);
}
} else /* if (schedule.getScheduleType().equals(SCHEDULE_TYPE_ESM)) */{
DateTime thisActionTriggerEndDate = TimeUtil.getDateMidnightForDateString(group.getEndDate()).plusDays(1).toDateTime();
lastEndDate = latestOf(lastEndDate, thisActionTriggerEndDate);
}
}
}
}
return lastEndDate;
}
private DateTime latestOf(DateTime lastEndDate, DateTime thisActionTriggerEndDate) {
if (lastEndDate == null || thisActionTriggerEndDate.isAfter(lastEndDate)) {
return thisActionTriggerEndDate;
} else {
return lastEndDate;
}
}
@Override
public ExperimentQueryResult getAllExperiments(String cursor) {
ExperimentQueryResult result = new ExperimentQueryResult();
ExperimentHelper.Pair<String, List<String>> jsonResults = ExperimentJsonEntityManager.getAllExperiments(cursor);
List<ExperimentDAO> experiments = Lists.newArrayList();
List<String> experimentEntities = jsonResults.second;
for (String experimentJson : experimentEntities) {
experiments.add(JsonConverter.fromSingleEntityJson(experimentJson));
}
result.setExperiments(experiments);
result.setCursor(jsonResults.first);
return result;
}
} | apache-2.0 |
Arcnor/bladecoder-adventure-engine | adventure-composer/src/main/java/com/bladecoder/engineeditor/model/BaseDocument.java | 11185 | /*******************************************************************************
* Copyright 2014 Rafael Garcia Moreno.
*
* 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.bladecoder.engineeditor.model;
import java.beans.PropertyChangeEvent;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.util.Collections;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Properties;
import java.util.TreeSet;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathExpressionException;
import javax.xml.xpath.XPathFactory;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;
import com.bladecoder.engine.loader.XMLConstants;
import com.bladecoder.engine.util.EngineLogger;
import com.bladecoder.engineeditor.utils.I18NUtils;
public abstract class BaseDocument extends PropertyChange {
public static final String NOTIFY_ELEMENT_DELETED = "ELEMENT_DELETED";
public static final String NOTIFY_ELEMENT_CREATED = "ELEMENT_CREATED";
public static final String NOTIFY_DOCUMENT_SAVED = "DOCUMENT_SAVED";
public static final char I18NPREFIX = '@';
Document doc;
private String filename;
protected String modelPath;
protected Properties i18n;
protected boolean modified = false;
public abstract String getRootTag();
@SuppressWarnings("serial")
public void create() throws ParserConfigurationException {
DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
doc = dBuilder.newDocument();
Element rootElement = doc.createElement(getRootTag());
doc.appendChild(rootElement);
// To save in alphabetical order we override the keys method
i18n = new Properties() {
@Override
public synchronized Enumeration<Object> keys() {
return Collections.enumeration(new TreeSet<Object>(keySet()));
}
};
modified = true;
firePropertyChange();
}
protected String getI18NFilename() {
String name = getAbsoluteName();
return name.substring(0, name.lastIndexOf('.')) + ".properties";
}
@SuppressWarnings("serial")
protected void loadI18N() {
String i18nFilename = getI18NFilename();
// To save in alphabetical order we override the keys method
i18n = new Properties() {
@Override
public synchronized Enumeration<Object> keys() {
return Collections.enumeration(new TreeSet<Object>(keySet()));
}
};
try {
i18n.load(new FileInputStream(i18nFilename));
} catch (IOException e) {
EngineLogger.error("ERROR LOADING BUNDLE: " + i18nFilename);
}
}
public String getTranslation(String key) {
if (key.isEmpty() || key.charAt(0) != I18NPREFIX || i18n == null)
return key;
return i18n.getProperty(key.substring(1), key);
}
public void setTranslation(String key, String value) {
if (key.charAt(0) != I18NPREFIX)
i18n.setProperty(key, value);
else
i18n.setProperty(key.substring(1), value);
}
public Properties getI18N() {
return i18n;
}
protected void saveI18N() {
String i18nFilename = getI18NFilename();
I18NUtils.deleteUnusedKeys(this);
try {
FileOutputStream os = new FileOutputStream(i18nFilename);
Writer out = new OutputStreamWriter(os, "ISO-8859-1");
i18n.store(out, filename);
} catch (IOException e) {
EngineLogger.error("ERROR WRITING BUNDLE: " + i18nFilename);
}
}
public void load() throws ParserConfigurationException, SAXException, IOException {
File fXmlFile = new File(getAbsoluteName());
DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
doc = dBuilder.parse(fXmlFile);
loadI18N();
modified = false;
}
public void save() throws TransformerException, IOException {
if (!modified)
return;
TransformerFactory transformerFactory = TransformerFactory.newInstance();
Transformer transformer = transformerFactory.newTransformer();
transformer.setOutputProperty(OutputKeys.INDENT, "yes");
DOMSource source = new DOMSource(doc);
StreamResult result = new StreamResult(new FileOutputStream(getAbsoluteName()));
transformer.transform(source, result);
saveI18N();
modified = false;
firePropertyChange(NOTIFY_DOCUMENT_SAVED);
}
public boolean isModified() {
return modified;
}
public String getFilename() {
return filename;
}
public void setFilename(String filename) {
this.filename = filename;
}
public String getAbsoluteName() {
return modelPath + "/" + filename;
}
public void setModelPath(String p) {
modelPath = p;
}
public String getRootAttr(String attr) {
return doc.getDocumentElement().getAttribute(attr);
}
public String getElementAttr(String tag, String attr) {
NodeList nl = doc.getDocumentElement().getElementsByTagName(tag);
if (nl.getLength() == 0)
return "";
else
return ((Element) nl.item(0)).getAttribute(attr);
}
public void setElementAttr(String tag, String attr, String value) {
NodeList nl = doc.getDocumentElement().getElementsByTagName(tag);
Element e = null;
if (nl.getLength() == 0) {
e = doc.createElement(tag);
doc.getDocumentElement().appendChild(e);
} else {
e = (Element) nl.item(0);
}
e.setAttribute(attr, value);
modified = true;
}
public void setModified() {
modified = true;
firePropertyChange(DOCUMENT_CHANGED, null, doc.getDocumentElement());
}
public Element getRootElement() {
return doc.getDocumentElement();
}
public Document getDocument() {
return doc;
}
public Element cloneNode(Element parent, Element e) {
Element cloned;
if (e.getOwnerDocument() != doc) {
cloned = (Element) doc.importNode(e, true);
} else {
cloned = (Element) e.cloneNode(true);
}
parent.appendChild(cloned);
if (cloned.getAttribute("id") != null && !cloned.getAttribute("id").isEmpty()) {
cloned.setAttribute("id", getCheckedId(cloned, cloned.getAttribute("id")));
}
setModified(cloned);
return cloned;
}
public void setModified(Element e) {
setModified(e.getTagName(), e);
}
public void setModified(Element e, Object source) {
modified = true;
PropertyChangeEvent evt = new PropertyChangeEvent(source, e.getTagName(), null, e);
firePropertyChange(evt);
}
public void setModified(String property, Element e) {
modified = true;
firePropertyChange(property, null, e);
}
public String getRootAttr(Element e, String a) {
return e.getAttribute(a);
}
public void setRootAttr(Element e, String attr, String value) {
String old = e.getAttribute(attr);
if (value != null && !value.isEmpty())
e.setAttribute(attr, value);
else
e.removeAttribute(attr);
modified = true;
firePropertyChange(attr, old, e);
}
public void setRootAttr(String attr, String value) {
String old = getRootAttr(getRootElement(), attr);
if (value != null && !value.isEmpty())
getRootElement().setAttribute(attr, value);
else
getRootElement().removeAttribute(attr);
modified = true;
firePropertyChange(attr, old, getRootElement());
}
public void deleteElement(Element e) {
e.getParentNode().removeChild(e);
modified = true;
firePropertyChange(NOTIFY_ELEMENT_DELETED, e);
}
public Element createVerb(Element e, String id, String state, String target) {
Element ev = doc.createElement("verb");
ev.setAttribute("id", id);
if (state != null && !state.isEmpty())
ev.setAttribute("state", state);
if (target != null && !target.isEmpty())
ev.setAttribute("target", target);
e.appendChild(ev);
modified = true;
firePropertyChange("verb", null, e);
return ev;
}
public Element createAction(Element verb, String action, String actor, HashMap<String, String> params) {
Element e = doc.createElement(action);
if (actor != null && !actor.isEmpty())
e.setAttribute("actor", actor);
if (params != null) {
for (String k : params.keySet()) {
String v = params.get(k);
e.setAttribute(k, v);
}
}
verb.appendChild(e);
modified = true;
firePropertyChange("action", null, e);
return e;
}
public String getType(Element e) {
return e.getAttribute(XMLConstants.TYPE_ATTR);
}
public String getRenderer(Element e) {
return e.getAttribute(XMLConstants.RENDERER_ATTR);
}
public NodeList getChildrenByTag(Element e, String tag) {
XPathFactory xpathFactory = XPathFactory.newInstance();
XPath xpath = xpathFactory.newXPath();
try {
return (NodeList) xpath.evaluate("./" + tag, e, XPathConstants.NODESET);
} catch (XPathExpressionException ex) {
// TODO Auto-generated catch block
ex.printStackTrace();
}
return null;
}
public Element getElement() {
return doc.getDocumentElement();
}
/**
* Sets the element id avoiding duplicated ids
*
* @param e
* @param id
*/
public void setId(Element e, String id) {
String idChecked = getCheckedId(e, id);
setRootAttr(e, "id", idChecked);
}
public String getCheckedId(Element e, String id) {
String idChecked = id;
if (e.getParentNode() instanceof Element) {
NodeList nl = ((Element) e.getParentNode()).getElementsByTagName(e.getTagName());
boolean checked = false;
int i = 1;
while (!checked) {
checked = true;
for (int j = 0; j < nl.getLength(); j++) {
Element e2 = (Element) nl.item(j);
if (e2.getAttribute("id").equals(idChecked) && e != e2) {
i++;
idChecked = id + i;
checked = false;
break;
}
}
}
}
return idChecked;
}
public String getId(Element e) {
return e.getAttribute("id");
}
public Element createElement(Element parent, String type) {
Element es = doc.createElement(type);
parent.appendChild(es);
return es;
}
public int indexOf(Element parent, Element e) {
int idx = -1;
NodeList childNodes = parent.getChildNodes();
for (int i = 0; i < childNodes.getLength(); i++) {
if (childNodes.item(i) instanceof Element)
idx++;
if (e == childNodes.item(i)) {
break;
}
}
return idx;
}
}
| apache-2.0 |
liefke/org.fastnate | fastnate-data/src/main/java/org/fastnate/data/properties/UniquePropertyEntityConverter.java | 991 | package org.fastnate.data.properties;
import org.fastnate.data.EntityRegistration;
import lombok.RequiredArgsConstructor;
/**
* Uses the {@link EntityRegistration} to resolve entities by a specific unique property.
*
* If an entity has exactly one unique property, one can use {@link DefaultEntityConverter} instead.
*
* If an entity has no unique property or some other kind of key is used as reference in the CSV files, one can use
* {@link MapConverter}.
*
* @author Tobias Liefke
*/
@RequiredArgsConstructor
public class UniquePropertyEntityConverter implements PropertyConverter<Object> {
/** Used to find the entities. */
private final EntityRegistration entityRegistration;
/** The name of the unique properties. */
private final String uniqueProperty;
@Override
public Object convert(final Class<? extends Object> targetType, final String value) {
return value == null ? null : this.entityRegistration.findEntity(targetType, this.uniqueProperty, value);
}
}
| apache-2.0 |
jhrcek/kie-wb-common | kie-wb-common-stunner/kie-wb-common-stunner-sets/kie-wb-common-stunner-case-mgmt/kie-wb-common-stunner-case-mgmt-client/src/main/java/org/kie/workbench/common/stunner/cm/client/command/CaseManagementRemoveChildCommand.java | 2165 | /*
* Copyright 2017 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.kie.workbench.common.stunner.cm.client.command;
import org.kie.workbench.common.stunner.core.client.canvas.AbstractCanvasHandler;
import org.kie.workbench.common.stunner.core.client.canvas.command.AbstractCanvasCommand;
import org.kie.workbench.common.stunner.core.client.canvas.command.RemoveCanvasChildCommand;
import org.kie.workbench.common.stunner.core.command.Command;
import org.kie.workbench.common.stunner.core.graph.Node;
import org.kie.workbench.common.stunner.core.graph.command.GraphCommandExecutionContext;
import org.kie.workbench.common.stunner.core.rule.RuleViolation;
public class CaseManagementRemoveChildCommand extends org.kie.workbench.common.stunner.core.client.canvas.command.RemoveChildCommand {
public CaseManagementRemoveChildCommand(final Node parent,
final Node child) {
super(parent,
child);
}
@Override
@SuppressWarnings("unchecked")
protected Command<GraphCommandExecutionContext, RuleViolation> newGraphCommand(final AbstractCanvasHandler context) {
return new org.kie.workbench.common.stunner.cm.client.command.graph.CaseManagementRemoveChildCommand(parent,
child);
}
@Override
protected AbstractCanvasCommand newCanvasCommand(final AbstractCanvasHandler context) {
return new RemoveCanvasChildCommand(parent,
child);
}
}
| apache-2.0 |
DesignAndDeploy/dnd | DND/src/edu/teco/dnd/module/config/BlockTypeHolder.java | 9993 | package edu.teco.dnd.module.config;
import java.util.Collections;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import com.google.gson.annotations.SerializedName;
import edu.teco.dnd.blocks.FunctionBlock;
import edu.teco.dnd.module.Module;
/**
* BlockTypeHolders are used to specify what kind of {@link FunctionBlock}s a {@link Module} can run. The
* BlockTypeHolders of a Module are a tree. The leaves have a {@link #getType() type} and an {@link #getAmountAllowed()
* amount} set. Those can be used to store the given amount of FunctionBlocks of the given type.
*
* Non-leaf nodes have a variable number of children. They can also have an amount set. This is a total amount that may
* not be exceeded by all children. For example, if root has an amount of 2 and two children. One which can hold two
* FunctionBlocks of type <code>foo</code> and one that can hold one of type <code>bar</code>, then the Module could run
* one FunctionBlocks of type <code>foo</code> or one or two of type <code>bar</code> (but not three as that would
* exceed the root) or one of type <code>foo</code> and one of type <code>bar</code> (not more as the root will be
* full).
*/
public class BlockTypeHolder implements Iterable<BlockTypeHolder> {
private static final Logger LOGGER = LogManager.getLogger(BlockTypeHolder.class);
/**
* The types of FunctionBlocks controlled by this BlockTypeHolder. This is used as a
*/
private final String type;
/**
* Number of FunctionBlocks that can be stored in this BlockTypeHolder. Negative values mean unrestricted.
*/
@SerializedName("amount")
private int amountAllowed = -1;
/**
* Number of slots that are left. Negative means unrestricted.
*/
private int amountLeft = -1;
/**
* An identifier that will be unique on a Module.
*/
private int id = -1;
/**
* Children of this BlockTypeHolder. May be empty.
*/
private final Set<BlockTypeHolder> children = new HashSet<BlockTypeHolder>();
/**
* Parent of this BlockTypeHolder. Will be <code>null</code> for the root.
*/
private transient BlockTypeHolder parent = null;
/**
* Constructor without arguments for Gson.
*/
@SuppressWarnings("unused")
private BlockTypeHolder() {
this((String) null, -1);
}
/**
* Initializes a new leaf node.
*
* @param type
* the type this leaf node is used for
* @param amount
* the amount of FunctionBlocks this BlockTypeHolder can hold. Negative values mean unrestricted.
*/
public BlockTypeHolder(String type, int amount) {
// leave node
this.type = type;
this.amountAllowed = amount;
this.amountLeft = amount;
}
/**
* Initializes a new non-leaf node.
*
* @param children
* initial children of the BlockTypeHolder
* @param amount
* the amount of FunctionBlocks this BlockTypeHolder can hold. Negative values mean unrestricted. This is
* a total maximum for all children.
*/
public BlockTypeHolder(Set<BlockTypeHolder> children, int amount) {
// non leave node
this.type = null;
if (children != null) {
this.children.addAll(children);
}
this.amountAllowed = amount;
this.amountLeft = amount;
}
/**
* Initializes a new non-leaf node without any children.
*
* @param amount
* the amount of FunctionBlocks this BlockTypeHolder can hold. Negative values mean unrestricted. This is
* a total maximum for all children.
*/
public BlockTypeHolder(final int amount) {
this(Collections.<BlockTypeHolder> emptySet(), amount);
}
/**
* Returns the children of this BlockTypeHolder. Will be empty for leaf nodes.
*
* @return the children of this BlockTypeHolder. Non-<code>null</code>, but possibly empty.
*/
public Set<BlockTypeHolder> getChildren() {
return children;
}
/**
* Returns the parent of this BlockTypeHolder.
*
* @return the parent of this BlockTypeHolder. May be <code>null</code>.
*/
public BlockTypeHolder getParent() {
return parent;
}
/**
* Sets the parent of this BlockTypeHolder. This does not change the children of <code>parent</code>.
*
* @param parent
* the new parent of this BlockTypeHolder. May be <code>null</code>.
*/
public void setParent(BlockTypeHolder parent) {
this.parent = parent;
}
/**
* Returns the number of {@link FunctionBlock}s that can be hold by this BlockTypeHolder. This is the total amount.
*
* @return the number of FunctionBlocks that can be hold by this BlockTypeHolder. A negative number means that there
* is no limit.
* @see #getAmountLeft()
*/
public int getAmountAllowed() {
return amountAllowed;
}
/**
* Returns the number of {@link FunctionBlock}s that can still be added to this BlockTypeHolder before it is full.
*
* @return the number of FunctionBlocks that can be added to this BlockTypeHolder before it is full. A negative
* number means that there is no limit.
* @see #getAmountAllowed()
*/
public int getAmountLeft() {
return amountLeft;
}
/**
* Sets the number of {@link FunctionBlock}s that can be added to this BlockTypeHolder before it is full.
*
* @param amountLeft
* the number of FunctionBlocks that can be added to this {@link BlockTypeHolder} before it is full. A
* negative number means that there is no limit.
* @see #getAmountLeft()
*/
public void setAmountLeft(int amountLeft) {
LOGGER.trace("setting amountLeft to {}", amountLeft);
this.amountLeft = amountLeft;
}
/**
* Returns the type of {@link FunctionBlock}s this BlockTypeHolder is used for. This is used as a RegEx.
*
* @return a RegEx describing the types of {@link FunctionBlock}s this BlockTypeHolder is used for.
* <code>null</code> for non-leaf nodes
*/
public String getType() {
return this.type;
}
/**
* Returns the ID of this BlockTypeHolder. This should be unique per {@link Module}, however this class has no
* directly control over the IDs.
*
* @return the ID of this BlockTypeHolder
*/
public int getID() {
return id;
}
/**
* Sets the ID of this BlockTypeHolder. Must be positive. This should be unique per {@link Module}, however no
* checks for uniqueness are made in this method.
*
* @param id
* the new ID of this BlockTypeHolder
*/
public void setID(int id) {
if (id < 0) {
throw new IllegalArgumentException();
}
this.id = id;
}
/**
* Tries to add a {@link FunctionBlock} of the given type to this BlockTypeHolder. This only works for leaf nodes.
*
* This will fail if the given type does not match the {@link #getType()} RegEx. Also this BlockTypeHolder as well
* as all its {@link #getParent() parents} have to have at least one {@link #getAmountLeft() free slot}.
*
* This method can be called concurrently with itself and/or {@link #increase()}.
*
* @param blockType
* the type of FunctionBlock to add
* @return true if the block was successfully added, false otherwise
*/
public synchronized boolean tryAdd(final String blockType) {
String normalizedBlockType = blockType;
if (normalizedBlockType == null) {
normalizedBlockType = "";
}
if (!normalizedBlockType.matches(type)) {
return false;
}
return tryDecrease();
}
/**
* Tries to decrease this BlockTypeHolder’s {@link #getAmountLeft()} and that of all its parents. Fails if any
* BlockTypeHolder involved has no free slots. In that case no amount is changed.
*
* If a {@link #getAmountLeft()} is negative it is not changed and interpreted as having free slots.
*
* @return <code>true</code> if this BlockTypeHolder and all its parents had at least one free slot and those have
* be decreased by one.
*/
private synchronized boolean tryDecrease() {
LOGGER.entry();
if (amountLeft != 0 && (parent == null || parent.tryDecrease())) {
if (amountLeft > 0) {
amountLeft--;
}
LOGGER.exit(true);
return true;
} else {
LOGGER.exit(false);
return false;
}
}
/**
* Adds a free slot to this {@link BlockTypeHolder} and all its parents. Will not increase past
* {@link #getAmountAllowed()}.
*
* @see #getAmountLeft()
*/
public synchronized void increase() {
if (amountLeft < 0) {
if (parent != null) {
parent.increase();
}
} else {
if (amountLeft < amountAllowed) {
if (parent != null) {
parent.increase();
}
amountLeft++;
} else {
LOGGER.warn("more block=>{} freed than marked as in use.", type);
}
}
}
/**
* Returns <code>true</code> if this is a leaf node.
*
* @return <code>true</code> if this is a leaf node
*/
public boolean isLeaf() {
return !children.isEmpty();
}
/*
* (non-Javadoc)
*
* @see java.lang.Object#hashCode()
*/
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + amountAllowed;
result = prime * result + ((children == null) ? 0 : children.hashCode());
result = prime * result + ((type == null) ? 0 : type.hashCode());
return result;
}
/*
* (non-Javadoc)
*
* @see java.lang.Object#equals(java.lang.Object)
*/
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
BlockTypeHolder other = (BlockTypeHolder) obj;
if (amountAllowed != other.amountAllowed) {
return false;
}
if (children == null) {
if (other.children != null) {
return false;
}
} else if (!children.equals(other.children)) {
return false;
}
if (type == null) {
if (other.type != null) {
return false;
}
} else if (!type.equals(other.type)) {
return false;
}
return true;
}
@Override
public Iterator<BlockTypeHolder> iterator() {
return new BlockTypeHolderIterator(this);
}
}
| apache-2.0 |
andifalk/spring-core-workshop | spring-java-configuration/src/main/java/info/novatec/xml/service/MyService2.java | 101 | package info.novatec.xml.service;
public interface MyService2 {
String sayHello(String message);
}
| apache-2.0 |