repo_name stringlengths 5 108 | path stringlengths 6 333 | size stringlengths 1 6 | content stringlengths 4 977k | license stringclasses 15 values |
|---|---|---|---|---|
treeform/orekit | src/test/java/org/orekit/attitudes/YawCompensationTest.java | 14371 | /* Copyright 2002-2014 CS Systèmes d'Information
* Licensed to CS Systèmes d'Information (CS) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* CS 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.orekit.attitudes;
import org.apache.commons.math3.geometry.euclidean.threed.Line;
import org.apache.commons.math3.geometry.euclidean.threed.Plane;
import org.apache.commons.math3.geometry.euclidean.threed.Rotation;
import org.apache.commons.math3.geometry.euclidean.threed.Vector3D;
import org.apache.commons.math3.util.FastMath;
import org.junit.After;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.orekit.Utils;
import org.orekit.bodies.GeodeticPoint;
import org.orekit.bodies.OneAxisEllipsoid;
import org.orekit.errors.OrekitException;
import org.orekit.frames.Frame;
import org.orekit.frames.FramesFactory;
import org.orekit.frames.Transform;
import org.orekit.orbits.CircularOrbit;
import org.orekit.orbits.KeplerianOrbit;
import org.orekit.orbits.Orbit;
import org.orekit.orbits.PositionAngle;
import org.orekit.propagation.Propagator;
import org.orekit.propagation.SpacecraftState;
import org.orekit.propagation.analytical.KeplerianPropagator;
import org.orekit.time.AbsoluteDate;
import org.orekit.time.DateComponents;
import org.orekit.time.TimeComponents;
import org.orekit.time.TimeScalesFactory;
import org.orekit.utils.AngularCoordinates;
import org.orekit.utils.Constants;
import org.orekit.utils.IERSConventions;
import org.orekit.utils.PVCoordinates;
public class YawCompensationTest {
// Computation date
private AbsoluteDate date;
// Reference frame = ITRF 2005C
private Frame itrf;
// Satellite position
CircularOrbit circOrbit;
// Earth shape
OneAxisEllipsoid earthShape;
/** Test that pointed target remains the same with or without yaw compensation
*/
@Test
public void testTarget() throws OrekitException {
// Attitude laws
// **************
// Target pointing attitude provider without yaw compensation
NadirPointing nadirLaw = new NadirPointing(earthShape);
// Target pointing attitude provider with yaw compensation
YawCompensation yawCompensLaw = new YawCompensation(nadirLaw);
// Check target
// *************
// without yaw compensation
Vector3D noYawObserved = nadirLaw.getTargetPoint(circOrbit, date, itrf);
// with yaw compensation
Vector3D yawObserved = yawCompensLaw.getTargetPoint(circOrbit, date, itrf);
// Check difference
Vector3D observedDiff = noYawObserved.subtract(yawObserved);
Assert.assertEquals(0.0, observedDiff.getNorm(), Utils.epsilonTest);
}
/** Test that pointed target motion is along -X sat axis
*/
@Test
public void testAlignment() throws OrekitException {
Frame inertFrame = circOrbit.getFrame();
Frame earthFrame = earthShape.getBodyFrame();
AttitudeProvider law = new YawCompensation(new NadirPointing(earthShape));
Attitude att0 = law.getAttitude(circOrbit, date, circOrbit.getFrame());
// ground point in satellite Z direction
Vector3D satInert = circOrbit.getPVCoordinates().getPosition();
Vector3D zInert = att0.getRotation().applyInverseTo(Vector3D.PLUS_K);
GeodeticPoint gp = earthShape.getIntersectionPoint(new Line(satInert,
satInert.add(Constants.WGS84_EARTH_EQUATORIAL_RADIUS, zInert),
1.0e-10),
satInert,
inertFrame, circOrbit.getDate());
Vector3D pEarth = earthShape.transform(gp);
// velocity of ground point, in inertial frame
double h = 1.0;
double s2 = 1.0 / (12 * h);
double s1 = 8.0 * s2;
Transform tM2h = earthFrame.getTransformTo(inertFrame, circOrbit.getDate().shiftedBy(-2 * h));
Vector3D pM2h = tM2h.transformPosition(pEarth);
Transform tM1h = earthFrame.getTransformTo(inertFrame, circOrbit.getDate().shiftedBy(-h));
Vector3D pM1h = tM1h.transformPosition(pEarth);
Transform tP1h = earthFrame.getTransformTo(inertFrame, circOrbit.getDate().shiftedBy( h));
Vector3D pP1h = tP1h.transformPosition(pEarth);
Transform tP2h = earthFrame.getTransformTo(inertFrame, circOrbit.getDate().shiftedBy( 2 * h));
Vector3D pP2h = tP2h.transformPosition(pEarth);
Vector3D vSurfaceInertial = new Vector3D(s1, pP1h, -s1, pM1h, -s2, pP2h, s2, pM2h);
// relative velocity
Vector3D pSurfaceInertial = earthFrame.getTransformTo(inertFrame, circOrbit.getDate()).transformPosition(pEarth);
Vector3D vSatInertial = circOrbit.getPVCoordinates().getVelocity();
Plane sspPlane = new Plane(pSurfaceInertial, 1.0e-10);
Vector3D satVelocityHorizonal = sspPlane.toSpace(sspPlane.toSubSpace(vSatInertial));
Vector3D satVelocityAtSurface = satVelocityHorizonal.scalarMultiply(pSurfaceInertial.getNorm()/satInert.getNorm());
Vector3D relativeVelocity = vSurfaceInertial.subtract(satVelocityAtSurface);
// relative velocity in satellite frame, must be in (X, Z) plane
Vector3D relVelSat = att0.getRotation().applyTo(relativeVelocity);
Assert.assertEquals(0.0, relVelSat.getY(), 2.0e-5);
}
/** Test that maximum yaw compensation is at ascending/descending node,
* and minimum yaw compensation is at maximum latitude.
*/
@Test
public void testCompensMinMax() throws OrekitException {
// Attitude laws
// **************
// Target pointing attitude provider over satellite nadir at date, without yaw compensation
NadirPointing nadirLaw = new NadirPointing(earthShape);
// Target pointing attitude provider with yaw compensation
YawCompensation yawCompensLaw = new YawCompensation(nadirLaw);
// Extrapolation over one orbital period (sec)
double duration = circOrbit.getKeplerianPeriod();
KeplerianPropagator extrapolator = new KeplerianPropagator(circOrbit);
// Extrapolation initializations
double delta_t = 15.0; // extrapolation duration in seconds
AbsoluteDate extrapDate = date; // extrapolation start date
// Min initialization
double yawMin = 1.e+12;
double latMin = 0.;
while (extrapDate.durationFrom(date) < duration) {
extrapDate = extrapDate.shiftedBy(delta_t);
// Extrapolated orbit state at date
Orbit extrapOrbit = extrapolator.propagate(extrapDate).getOrbit();
PVCoordinates extrapPvSatEME2000 = extrapOrbit.getPVCoordinates();
// Satellite latitude at date
double extrapLat =
earthShape.transform(extrapPvSatEME2000.getPosition(), FramesFactory.getEME2000(), extrapDate).getLatitude();
// Compute yaw compensation angle -- rotations composition
double yawAngle = yawCompensLaw.getYawAngle(extrapOrbit, extrapDate, extrapOrbit.getFrame());
// Update minimum yaw compensation angle
if (FastMath.abs(yawAngle) <= yawMin) {
yawMin = FastMath.abs(yawAngle);
latMin = extrapLat;
}
// Checks
// ------------------
// 1/ Check yaw values around ascending node (max yaw)
if ((FastMath.abs(extrapLat) < FastMath.toRadians(2.)) &&
(extrapPvSatEME2000.getVelocity().getZ() >= 0. )) {
Assert.assertTrue((FastMath.abs(yawAngle) >= FastMath.toRadians(3.22)) &&
(FastMath.abs(yawAngle) <= FastMath.toRadians(3.23)));
}
// 2/ Check yaw values around maximum positive latitude (min yaw)
if ( extrapLat > FastMath.toRadians(50.) ) {
Assert.assertTrue(FastMath.abs(yawAngle) <= FastMath.toRadians(0.26));
}
// 3/ Check yaw values around descending node (max yaw)
if ( (FastMath.abs(extrapLat) < FastMath.toRadians(2.))
&& (extrapPvSatEME2000.getVelocity().getZ() <= 0. ) ) {
Assert.assertTrue((FastMath.abs(yawAngle) >= FastMath.toRadians(3.22)) &&
(FastMath.abs(yawAngle) <= FastMath.toRadians(3.23)));
}
// 4/ Check yaw values around maximum negative latitude (min yaw)
if ( extrapLat < FastMath.toRadians(-50.) ) {
Assert.assertTrue(FastMath.abs(yawAngle) <= FastMath.toRadians(0.26));
}
}
// 5/ Check that minimum yaw compensation value is around maximum latitude
Assert.assertEquals(0.0, FastMath.toDegrees(yawMin), 0.004);
Assert.assertEquals(50.0, FastMath.toDegrees(latMin), 0.22);
}
/** Test that compensation rotation axis is Zsat, yaw axis
*/
@Test
public void testCompensAxis() throws OrekitException {
// Attitude laws
// **************
// Target pointing attitude provider over satellite nadir at date, without yaw compensation
NadirPointing nadirLaw = new NadirPointing(earthShape);
// Target pointing attitude provider with yaw compensation
YawCompensation yawCompensLaw = new YawCompensation(nadirLaw);
// Get attitude rotations from non yaw compensated / yaw compensated laws
Rotation rotNoYaw = nadirLaw.getAttitude(circOrbit, date, circOrbit.getFrame()).getRotation();
Rotation rotYaw = yawCompensLaw.getAttitude(circOrbit, date, circOrbit.getFrame()).getRotation();
// Compose rotations composition
Rotation compoRot = rotYaw.applyTo(rotNoYaw.revert());
Vector3D yawAxis = compoRot.getAxis();
// Check axis
Assert.assertEquals(0., yawAxis.subtract(Vector3D.PLUS_K).getNorm(), Utils.epsilonTest);
}
@Test
public void testSpin() throws OrekitException {
NadirPointing nadirLaw = new NadirPointing(earthShape);
// Target pointing attitude provider with yaw compensation
AttitudeProvider law = new YawCompensation(nadirLaw);
KeplerianOrbit orbit =
new KeplerianOrbit(7178000.0, 1.e-4, FastMath.toRadians(50.),
FastMath.toRadians(10.), FastMath.toRadians(20.),
FastMath.toRadians(30.), PositionAngle.MEAN,
FramesFactory.getEME2000(),
date.shiftedBy(-300.0), 3.986004415e14);
Propagator propagator = new KeplerianPropagator(orbit, law);
double h = 0.01;
SpacecraftState sMinus = propagator.propagate(date.shiftedBy(-h));
SpacecraftState s0 = propagator.propagate(date);
SpacecraftState sPlus = propagator.propagate(date.shiftedBy(h));
// check spin is consistent with attitude evolution
double errorAngleMinus = Rotation.distance(sMinus.shiftedBy(h).getAttitude().getRotation(),
s0.getAttitude().getRotation());
double evolutionAngleMinus = Rotation.distance(sMinus.getAttitude().getRotation(),
s0.getAttitude().getRotation());
Assert.assertEquals(0.0, errorAngleMinus, 1.0e-6 * evolutionAngleMinus);
double errorAnglePlus = Rotation.distance(s0.getAttitude().getRotation(),
sPlus.shiftedBy(-h).getAttitude().getRotation());
double evolutionAnglePlus = Rotation.distance(s0.getAttitude().getRotation(),
sPlus.getAttitude().getRotation());
Assert.assertEquals(0.0, errorAnglePlus, 1.0e-6 * evolutionAnglePlus);
Vector3D spin0 = s0.getAttitude().getSpin();
Vector3D reference = AngularCoordinates.estimateRate(sMinus.getAttitude().getRotation(),
sPlus.getAttitude().getRotation(),
2 * h);
Assert.assertTrue(spin0.getNorm() > 1.0e-3);
Assert.assertEquals(0.0, spin0.subtract(reference).getNorm(), 1.0e-9);
}
@Before
public void setUp() {
try {
Utils.setDataRoot("regular-data");
// Computation date
date = new AbsoluteDate(new DateComponents(2008, 04, 07),
TimeComponents.H00,
TimeScalesFactory.getUTC());
// Body mu
final double mu = 3.9860047e14;
// Reference frame = ITRF 2005
itrf = FramesFactory.getITRF(IERSConventions.IERS_2010, true);
// Satellite position
circOrbit =
new CircularOrbit(7178000.0, 0.5e-4, -0.5e-4, FastMath.toRadians(50.), FastMath.toRadians(270.),
FastMath.toRadians(5.300), PositionAngle.MEAN,
FramesFactory.getEME2000(), date, mu);
// Elliptic earth shape */
earthShape =
new OneAxisEllipsoid(6378136.460, 1 / 298.257222101, itrf);
} catch (OrekitException oe) {
Assert.fail(oe.getMessage());
}
}
@After
public void tearDown() {
date = null;
itrf = null;
circOrbit = null;
earthShape = null;
}
}
| apache-2.0 |
GerritCodeReview/gerrit-attic | src/main/java/com/google/gerrit/client/changes/ChangeInfoBlock.java | 3819 | // Copyright (C) 2008 The Android Open Source Project
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package com.google.gerrit.client.changes;
import static com.google.gerrit.client.FormatUtil.mediumFormat;
import com.google.gerrit.client.data.AccountInfoCache;
import com.google.gerrit.client.reviewdb.Branch;
import com.google.gerrit.client.reviewdb.Change;
import com.google.gerrit.client.ui.AccountDashboardLink;
import com.google.gerrit.client.ui.ChangeLink;
import com.google.gerrit.client.ui.ProjectOpenLink;
import com.google.gwt.user.client.ui.Composite;
import com.google.gwt.user.client.ui.FlowPanel;
import com.google.gwt.user.client.ui.Grid;
import com.google.gwt.user.client.ui.HTMLTable.CellFormatter;
import com.google.gwtexpui.clippy.client.CopyableLabel;
public class ChangeInfoBlock extends Composite {
private static final int R_CHANGE_ID = 0;
private static final int R_OWNER = 1;
private static final int R_PROJECT = 2;
private static final int R_BRANCH = 3;
private static final int R_UPLOADED = 4;
private static final int R_UPDATED = 5;
private static final int R_STATUS = 6;
private static final int R_PERMALINK = 7;
private static final int R_CNT = 8;
private final Grid table;
public ChangeInfoBlock() {
table = new Grid(R_CNT, 2);
table.setStyleName("gerrit-InfoBlock");
table.addStyleName("gerrit-ChangeInfoBlock");
initRow(R_CHANGE_ID, "Change-Id: ");
initRow(R_OWNER, Util.C.changeInfoBlockOwner());
initRow(R_PROJECT, Util.C.changeInfoBlockProject());
initRow(R_BRANCH, Util.C.changeInfoBlockBranch());
initRow(R_UPLOADED, Util.C.changeInfoBlockUploaded());
initRow(R_UPDATED, Util.C.changeInfoBlockUpdated());
initRow(R_STATUS, Util.C.changeInfoBlockStatus());
final CellFormatter fmt = table.getCellFormatter();
fmt.addStyleName(0, 0, "topmost");
fmt.addStyleName(0, 1, "topmost");
fmt.addStyleName(R_CHANGE_ID, 1, "changeid");
fmt.addStyleName(R_CNT - 2, 0, "bottomheader");
fmt.addStyleName(R_PERMALINK, 0, "permalink");
fmt.addStyleName(R_PERMALINK, 1, "permalink");
initWidget(table);
}
private void initRow(final int row, final String name) {
table.setText(row, 0, name);
table.getCellFormatter().addStyleName(row, 0, "header");
}
public void display(final Change chg, final AccountInfoCache acc) {
final Branch.NameKey dst = chg.getDest();
table.setText(R_CHANGE_ID, 1, chg.getKey().get());
table.setWidget(R_OWNER, 1, AccountDashboardLink.link(acc, chg.getOwner()));
table.setWidget(R_PROJECT, 1, new ProjectOpenLink(chg.getProject()));
table.setText(R_BRANCH, 1, dst.getShortName());
table.setText(R_UPLOADED, 1, mediumFormat(chg.getCreatedOn()));
table.setText(R_UPDATED, 1, mediumFormat(chg.getLastUpdatedOn()));
table.setText(R_STATUS, 1, Util.toLongString(chg.getStatus()));
if (chg.getStatus().isClosed()) {
table.getCellFormatter().addStyleName(R_STATUS, 1, "closedstate");
} else {
table.getCellFormatter().removeStyleName(R_STATUS, 1, "closedstate");
}
final FlowPanel fp = new FlowPanel();
fp.add(new ChangeLink(Util.C.changePermalink(), chg.getId()));
fp.add(new CopyableLabel(ChangeLink.permalink(chg.getId()), false));
table.setWidget(R_PERMALINK, 1, fp);
}
}
| apache-2.0 |
jentfoo/aws-sdk-java | aws-java-sdk-opsworks/src/main/java/com/amazonaws/services/opsworks/model/transform/CommandJsonUnmarshaller.java | 4731 | /*
* 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.opsworks.model.transform;
import java.math.*;
import javax.annotation.Generated;
import com.amazonaws.services.opsworks.model.*;
import com.amazonaws.transform.SimpleTypeJsonUnmarshallers.*;
import com.amazonaws.transform.*;
import com.fasterxml.jackson.core.JsonToken;
import static com.fasterxml.jackson.core.JsonToken.*;
/**
* Command JSON Unmarshaller
*/
@Generated("com.amazonaws:aws-java-sdk-code-generator")
public class CommandJsonUnmarshaller implements Unmarshaller<Command, JsonUnmarshallerContext> {
public Command unmarshall(JsonUnmarshallerContext context) throws Exception {
Command command = new Command();
int originalDepth = context.getCurrentDepth();
String currentParentElement = context.getCurrentParentElement();
int targetDepth = originalDepth + 1;
JsonToken token = context.getCurrentToken();
if (token == null)
token = context.nextToken();
if (token == VALUE_NULL) {
return null;
}
while (true) {
if (token == null)
break;
if (token == FIELD_NAME || token == START_OBJECT) {
if (context.testExpression("CommandId", targetDepth)) {
context.nextToken();
command.setCommandId(context.getUnmarshaller(String.class).unmarshall(context));
}
if (context.testExpression("InstanceId", targetDepth)) {
context.nextToken();
command.setInstanceId(context.getUnmarshaller(String.class).unmarshall(context));
}
if (context.testExpression("DeploymentId", targetDepth)) {
context.nextToken();
command.setDeploymentId(context.getUnmarshaller(String.class).unmarshall(context));
}
if (context.testExpression("CreatedAt", targetDepth)) {
context.nextToken();
command.setCreatedAt(context.getUnmarshaller(String.class).unmarshall(context));
}
if (context.testExpression("AcknowledgedAt", targetDepth)) {
context.nextToken();
command.setAcknowledgedAt(context.getUnmarshaller(String.class).unmarshall(context));
}
if (context.testExpression("CompletedAt", targetDepth)) {
context.nextToken();
command.setCompletedAt(context.getUnmarshaller(String.class).unmarshall(context));
}
if (context.testExpression("Status", targetDepth)) {
context.nextToken();
command.setStatus(context.getUnmarshaller(String.class).unmarshall(context));
}
if (context.testExpression("ExitCode", targetDepth)) {
context.nextToken();
command.setExitCode(context.getUnmarshaller(Integer.class).unmarshall(context));
}
if (context.testExpression("LogUrl", targetDepth)) {
context.nextToken();
command.setLogUrl(context.getUnmarshaller(String.class).unmarshall(context));
}
if (context.testExpression("Type", targetDepth)) {
context.nextToken();
command.setType(context.getUnmarshaller(String.class).unmarshall(context));
}
} else if (token == END_ARRAY || token == END_OBJECT) {
if (context.getLastParsedParentElement() == null || context.getLastParsedParentElement().equals(currentParentElement)) {
if (context.getCurrentDepth() <= originalDepth)
break;
}
}
token = context.nextToken();
}
return command;
}
private static CommandJsonUnmarshaller instance;
public static CommandJsonUnmarshaller getInstance() {
if (instance == null)
instance = new CommandJsonUnmarshaller();
return instance;
}
}
| apache-2.0 |
autoschool/zlogger | src/main/java/zlogger/logic/models/Commentary.java | 795 | package zlogger.logic.models;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonPropertyOrder;
import javax.persistence.*;
@Entity
@Table(name = "commentaries", uniqueConstraints = {@UniqueConstraint(columnNames = "id")})
@JsonIgnoreProperties({"hibernateLazyInitializer", "handler"})
@JsonPropertyOrder({"id", "message", "creationDate", "creator", "post"})
public class Commentary extends AbstractPost {
@ManyToOne
@JoinColumn(name = "post_id", nullable = false)
private Post post;
public Commentary() {
}
public Commentary(String message) {
this.message = message;
}
public Post getPost() {
return post;
}
public void setPost(Post post) {
this.post = post;
}
}
| apache-2.0 |
rcarlosdasilva/weixin | src/main/java/io/github/rcarlosdasilva/weixin/model/request/base/BasicWeixinRequest.java | 433 | package io.github.rcarlosdasilva.weixin.model.request.base;
/**
* 基本公众号请求模型
*
* @author Dean Zhao (rcarlosdailva@qq.com)
*/
public class BasicWeixinRequest extends BasicRequest {
/**
* 重写生成URL策略,可根据不同策略重写.
*/
@Override
public String toString() {
return new StringBuilder(this.path).append("?access_token=").append(this.accessToken)
.toString();
}
}
| apache-2.0 |
dangdangdotcom/sharding-jdbc | sharding-core/src/main/java/io/shardingsphere/core/parsing/lexer/dialect/oracle/OracleLexer.java | 1578 | /*
* Copyright 2016-2018 shardingsphere.io.
* <p>
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* </p>
*/
package io.shardingsphere.core.parsing.lexer.dialect.oracle;
import io.shardingsphere.core.parsing.lexer.Lexer;
import io.shardingsphere.core.parsing.lexer.analyzer.CharType;
import io.shardingsphere.core.parsing.lexer.analyzer.Dictionary;
/**
* Oracle Lexical analysis.
*
* @author zhangliang
*/
public final class OracleLexer extends Lexer {
private static Dictionary dictionary = new Dictionary(OracleKeyword.values());
public OracleLexer(final String input) {
super(input, dictionary);
}
@Override
protected boolean isHintBegin() {
return '/' == getCurrentChar(0) && '*' == getCurrentChar(1) && '+' == getCurrentChar(2);
}
@Override
protected boolean isIdentifierBegin(final char ch) {
return CharType.isAlphabet(ch) || '\"' == ch || '_' == ch || '$' == ch;
}
@Override
protected boolean isCharsBegin() {
return '\'' == getCurrentChar(0);
}
}
| apache-2.0 |
yvoswillens/flowable-engine | modules/flowable-cmmn-json-converter/src/main/java/org/flowable/cmmn/editor/json/converter/StageJsonConverter.java | 6315 | /* 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.flowable.cmmn.editor.json.converter;
import java.util.Map;
import org.apache.commons.lang3.StringUtils;
import org.flowable.cmmn.editor.constants.CmmnStencilConstants;
import org.flowable.cmmn.editor.json.converter.CmmnJsonConverter.CmmnModelIdHelper;
import org.flowable.cmmn.editor.json.converter.util.ListenerConverterUtil;
import org.flowable.cmmn.editor.json.model.CmmnModelInfo;
import org.flowable.cmmn.model.BaseElement;
import org.flowable.cmmn.model.CaseElement;
import org.flowable.cmmn.model.CmmnModel;
import org.flowable.cmmn.model.GraphicInfo;
import org.flowable.cmmn.model.PlanItem;
import org.flowable.cmmn.model.Stage;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.node.ArrayNode;
import com.fasterxml.jackson.databind.node.ObjectNode;
/**
* @author Tijs Rademakers
* @author Joram Barrez
*/
public class StageJsonConverter extends BaseCmmnJsonConverter implements FormAwareConverter, FormKeyAwareConverter,
DecisionTableAwareConverter, DecisionTableKeyAwareConverter, CaseModelAwareConverter, ProcessModelAwareConverter {
protected Map<String, String> formMap;
protected Map<String, CmmnModelInfo> formKeyMap;
protected Map<String, String> decisionTableMap;
protected Map<String, CmmnModelInfo> decisionTableKeyMap;
protected Map<String, String> caseModelMap;
protected Map<String, String> processModelMap;
public static void fillTypes(Map<String, Class<? extends BaseCmmnJsonConverter>> convertersToCmmnMap,
Map<Class<? extends BaseElement>, Class<? extends BaseCmmnJsonConverter>> convertersToJsonMap) {
fillJsonTypes(convertersToCmmnMap);
fillCmmnTypes(convertersToJsonMap);
}
public static void fillJsonTypes(Map<String, Class<? extends BaseCmmnJsonConverter>> convertersToCmmnMap) {
convertersToCmmnMap.put(STENCIL_STAGE, StageJsonConverter.class);
}
public static void fillCmmnTypes(Map<Class<? extends BaseElement>, Class<? extends BaseCmmnJsonConverter>> convertersToJsonMap) {
convertersToJsonMap.put(Stage.class, StageJsonConverter.class);
}
@Override
protected String getStencilId(BaseElement baseElement) {
return STENCIL_STAGE;
}
@Override
protected void convertElementToJson(ObjectNode elementNode, ObjectNode propertiesNode, ActivityProcessor processor, BaseElement baseElement, CmmnModel cmmnModel) {
PlanItem planItem = (PlanItem) baseElement;
Stage stage = (Stage) planItem.getPlanItemDefinition();
if (stage.getDisplayOrder() != null) {
propertiesNode.put(PROPERTY_DISPLAY_ORDER, stage.getDisplayOrder());
}
if (stage.isIncludeInStageOverview()) {
propertiesNode.put(PROPERTY_INCLUDE_IN_STAGE_OVERVIEW, true);
}
GraphicInfo graphicInfo = cmmnModel.getGraphicInfo(planItem.getId());
ArrayNode subProcessShapesArrayNode = objectMapper.createArrayNode();
processor.processPlanItems(stage, cmmnModel, subProcessShapesArrayNode, formKeyMap, decisionTableKeyMap, graphicInfo.getX(), graphicInfo.getY());
elementNode.set("childShapes", subProcessShapesArrayNode);
ListenerConverterUtil.convertLifecycleListenersToJson(objectMapper, propertiesNode, stage);
}
@Override
protected CaseElement convertJsonToElement(JsonNode elementNode, JsonNode modelNode, ActivityProcessor processor,
BaseElement parentElement, Map<String, JsonNode> shapeMap, CmmnModel cmmnModel, CmmnModelIdHelper cmmnModelIdHelper) {
Stage stage = new Stage();
stage.setId(CmmnJsonConverterUtil.getElementId(elementNode));
stage.setAutoComplete(CmmnJsonConverterUtil.getPropertyValueAsBoolean(PROPERTY_IS_AUTOCOMPLETE, elementNode));
String autoCompleteCondition = CmmnJsonConverterUtil.getPropertyValueAsString(PROPERTY_AUTOCOMPLETE_CONDITION, elementNode);
if (StringUtils.isNotEmpty(autoCompleteCondition)) {
stage.setAutoCompleteCondition(autoCompleteCondition);
}
stage.setDisplayOrder(CmmnJsonConverterUtil
.getPropertyValueAsInteger(CmmnStencilConstants.PROPERTY_DISPLAY_ORDER, elementNode));
stage.setIncludeInStageOverview(CmmnJsonConverterUtil
.getPropertyValueAsBoolean(CmmnStencilConstants.PROPERTY_INCLUDE_IN_STAGE_OVERVIEW, elementNode, true));
JsonNode childShapesArray = elementNode.get(EDITOR_CHILD_SHAPES);
processor.processJsonElements(childShapesArray, modelNode, stage, shapeMap, formMap, decisionTableMap,
caseModelMap, processModelMap, cmmnModel, cmmnModelIdHelper);
Stage parentStage = (Stage) parentElement;
stage.setParent(parentStage);
ListenerConverterUtil.convertJsonToLifeCycleListeners(elementNode, stage);
return stage;
}
@Override
public void setFormMap(Map<String, String> formMap) {
this.formMap = formMap;
}
@Override
public void setFormKeyMap(Map<String, CmmnModelInfo> formKeyMap) {
this.formKeyMap = formKeyMap;
}
@Override
public void setDecisionTableMap(Map<String, String> decisionTableMap) {
this.decisionTableMap = decisionTableMap;
}
@Override
public void setDecisionTableKeyMap(Map<String, CmmnModelInfo> decisionTableKeyMap) {
this.decisionTableKeyMap = decisionTableKeyMap;
}
@Override
public void setCaseModelMap(Map<String, String> caseModelMap) {
this.caseModelMap = caseModelMap;
}
@Override
public void setProcessModelMap(Map<String, String> processModelMap) {
this.processModelMap = processModelMap;
}
}
| apache-2.0 |
kwin/jackrabbit-oak | oak-jcr/src/main/java/org/apache/jackrabbit/oak/jcr/observation/ChangeProcessor.java | 19262 | /*
* 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.jackrabbit.oak.jcr.observation;
import static com.google.common.base.Preconditions.checkState;
import static org.apache.jackrabbit.api.stats.RepositoryStatistics.Type.OBSERVATION_EVENT_COUNTER;
import static org.apache.jackrabbit.api.stats.RepositoryStatistics.Type.OBSERVATION_EVENT_DURATION;
import static org.apache.jackrabbit.oak.plugins.observation.filter.VisibleFilter.VISIBLE_FILTER;
import static org.apache.jackrabbit.oak.spi.whiteboard.WhiteboardUtils.registerMBean;
import static org.apache.jackrabbit.oak.spi.whiteboard.WhiteboardUtils.registerObserver;
import static org.apache.jackrabbit.oak.spi.whiteboard.WhiteboardUtils.scheduleWithFixedDelay;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicReference;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import javax.jcr.observation.Event;
import javax.jcr.observation.EventIterator;
import javax.jcr.observation.EventListener;
import com.google.common.collect.ImmutableMap;
import com.google.common.util.concurrent.Monitor;
import com.google.common.util.concurrent.Monitor.Guard;
import org.apache.jackrabbit.api.jmx.EventListenerMBean;
import org.apache.jackrabbit.commons.observation.ListenerTracker;
import org.apache.jackrabbit.oak.api.ContentSession;
import org.apache.jackrabbit.oak.namepath.NamePathMapper;
import org.apache.jackrabbit.oak.plugins.observation.CommitRateLimiter;
import org.apache.jackrabbit.oak.plugins.observation.filter.EventFilter;
import org.apache.jackrabbit.oak.plugins.observation.filter.FilterConfigMBean;
import org.apache.jackrabbit.oak.plugins.observation.filter.FilterProvider;
import org.apache.jackrabbit.oak.plugins.observation.filter.Filters;
import org.apache.jackrabbit.oak.spi.commit.BackgroundObserver;
import org.apache.jackrabbit.oak.spi.commit.BackgroundObserverMBean;
import org.apache.jackrabbit.oak.spi.commit.CommitInfo;
import org.apache.jackrabbit.oak.spi.commit.Observer;
import org.apache.jackrabbit.oak.spi.state.NodeState;
import org.apache.jackrabbit.oak.spi.whiteboard.CompositeRegistration;
import org.apache.jackrabbit.oak.spi.whiteboard.Registration;
import org.apache.jackrabbit.oak.spi.whiteboard.Whiteboard;
import org.apache.jackrabbit.oak.spi.whiteboard.WhiteboardExecutor;
import org.apache.jackrabbit.oak.stats.StatisticManager;
import org.apache.jackrabbit.oak.stats.MeterStats;
import org.apache.jackrabbit.oak.stats.TimerStats;
import org.apache.jackrabbit.oak.util.PerfLogger;
import org.apache.jackrabbit.stats.TimeSeriesMax;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* A {@code ChangeProcessor} generates observation {@link javax.jcr.observation.Event}s
* based on a {@link FilterProvider filter} and delivers them to an {@link EventListener}.
* <p>
* After instantiation a {@code ChangeProcessor} must be started in order to start
* delivering observation events and stopped to stop doing so.
*/
class ChangeProcessor implements Observer {
private static final Logger LOG = LoggerFactory.getLogger(ChangeProcessor.class);
private static final PerfLogger PERF_LOGGER = new PerfLogger(
LoggerFactory.getLogger(ChangeProcessor.class.getName() + ".perf"));
/**
* Fill ratio of the revision queue at which commits should be delayed
* (conditional of {@code commitRateLimiter} being non {@code null}).
*/
public static final double DELAY_THRESHOLD;
/**
* Maximal number of milli seconds a commit is delayed once {@code DELAY_THRESHOLD}
* kicks in.
*/
public static final int MAX_DELAY;
// OAK-4533: make DELAY_THRESHOLD and MAX_DELAY adjustable - using System.properties for now
static {
final String delayThresholdStr = System.getProperty("oak.commitRateLimiter.delayThreshold");
final String maxDelayStr = System.getProperty("oak.commitRateLimiter.maxDelay");
double delayThreshold = 0.8; /* default is 0.8 still */
int maxDelay = 10000; /* default is 10000 still */
try{
if (delayThresholdStr != null && delayThresholdStr.length() != 0) {
delayThreshold = Double.parseDouble(delayThresholdStr);
LOG.info("<clinit> using oak.commitRateLimiter.delayThreshold of " + delayThreshold);
}
} catch(RuntimeException e) {
LOG.warn("<clinit> could not parse oak.commitRateLimiter.delayThreshold, using default(" + delayThreshold + "): " + e, e);
}
try{
if (maxDelayStr != null && maxDelayStr.length() != 0) {
maxDelay = Integer.parseInt(maxDelayStr);
LOG.info("<clinit> using oak.commitRateLimiter.maxDelay of " + maxDelay + "ms");
}
} catch(RuntimeException e) {
LOG.warn("<clinit> could not parse oak.commitRateLimiter.maxDelay, using default(" + maxDelay + "): " + e, e);
}
DELAY_THRESHOLD = delayThreshold;
MAX_DELAY = maxDelay;
}
private static final AtomicInteger COUNTER = new AtomicInteger();
/**
* JMX ObjectName property storing the listenerId which allows
* to correlate various mbeans
*/
static final String LISTENER_ID = "listenerId";
private final ContentSession contentSession;
private final NamePathMapper namePathMapper;
private final ListenerTracker tracker;
private final EventListener eventListener;
private final AtomicReference<FilterProvider> filterProvider;
private final MeterStats eventCount;
private final TimerStats eventDuration;
private final TimeSeriesMax maxQueueLength;
private final int queueLength;
private final CommitRateLimiter commitRateLimiter;
/**
* Lazy initialization via the {@link #start(Whiteboard)} method
*/
private String listenerId;
/**
* Lazy initialization via the {@link #start(Whiteboard)} method
*/
private CompositeRegistration registration;
private volatile NodeState previousRoot;
public ChangeProcessor(
ContentSession contentSession,
NamePathMapper namePathMapper,
ListenerTracker tracker,
FilterProvider filter,
StatisticManager statisticManager,
int queueLength,
CommitRateLimiter commitRateLimiter) {
this.contentSession = contentSession;
this.namePathMapper = namePathMapper;
this.tracker = tracker;
eventListener = tracker.getTrackedListener();
filterProvider = new AtomicReference<FilterProvider>(filter);
this.eventCount = statisticManager.getMeter(OBSERVATION_EVENT_COUNTER);
this.eventDuration = statisticManager.getTimer(OBSERVATION_EVENT_DURATION);
this.maxQueueLength = statisticManager.maxQueLengthRecorder();
this.queueLength = queueLength;
this.commitRateLimiter = commitRateLimiter;
}
/**
* Set the filter for the events this change processor will generate.
* @param filter
*/
public void setFilterProvider(FilterProvider filter) {
filterProvider.set(filter);
}
/**
* Start this change processor
* @param whiteboard the whiteboard instance to used for scheduling individual
* runs of this change processor.
* @throws IllegalStateException if started already
*/
public synchronized void start(Whiteboard whiteboard) {
checkState(registration == null, "Change processor started already");
final WhiteboardExecutor executor = new WhiteboardExecutor();
executor.start(whiteboard);
final BackgroundObserver observer = createObserver(executor);
listenerId = COUNTER.incrementAndGet() + "";
Map<String, String> attrs = ImmutableMap.of(LISTENER_ID, listenerId);
String name = tracker.toString();
registration = new CompositeRegistration(
registerObserver(whiteboard, observer),
registerMBean(whiteboard, EventListenerMBean.class,
tracker.getListenerMBean(), "EventListener", name, attrs),
registerMBean(whiteboard, BackgroundObserverMBean.class,
observer.getMBean(), BackgroundObserverMBean.TYPE, name, attrs),
//TODO If FilterProvider gets changed later then MBean would need to be
// re-registered
registerMBean(whiteboard, FilterConfigMBean.class,
filterProvider.get().getConfigMBean(), FilterConfigMBean.TYPE, name, attrs),
new Registration() {
@Override
public void unregister() {
observer.close();
}
},
new Registration() {
@Override
public void unregister() {
executor.stop();
}
},
scheduleWithFixedDelay(whiteboard, new Runnable() {
@Override
public void run() {
tracker.recordOneSecond();
}
}, 1)
);
}
private BackgroundObserver createObserver(final WhiteboardExecutor executor) {
return new BackgroundObserver(this, executor, queueLength) {
private volatile long delay;
private volatile boolean blocking;
@Override
protected void added(int queueSize) {
maxQueueLength.recordValue(queueSize);
tracker.recordQueueLength(queueSize);
if (queueSize == queueLength) {
if (commitRateLimiter != null) {
if (!blocking) {
LOG.warn("Revision queue is full. Further commits will be blocked.");
}
commitRateLimiter.blockCommits();
} else if (!blocking) {
LOG.warn("Revision queue is full. Further revisions will be compacted.");
}
blocking = true;
} else {
double fillRatio = (double) queueSize / queueLength;
if (fillRatio > DELAY_THRESHOLD) {
if (commitRateLimiter != null) {
if (delay == 0) {
LOG.warn("Revision queue is becoming full. Further commits will be delayed.");
}
// Linear backoff proportional to the number of items exceeding
// DELAY_THRESHOLD. Offset by 1 to trigger the log message in the
// else branch once the queue falls below DELAY_THRESHOLD again.
int newDelay = 1 + (int) ((fillRatio - DELAY_THRESHOLD) / (1 - DELAY_THRESHOLD) * MAX_DELAY);
if (newDelay > delay) {
delay = newDelay;
commitRateLimiter.setDelay(delay);
}
}
} else {
if (commitRateLimiter != null) {
if (delay > 0) {
LOG.debug("Revision queue becoming empty. Unblocking commits");
commitRateLimiter.setDelay(0);
delay = 0;
}
if (blocking) {
LOG.debug("Revision queue becoming empty. Stop delaying commits.");
commitRateLimiter.unblockCommits();
blocking = false;
}
}
}
}
}
};
}
private final Monitor runningMonitor = new Monitor();
private final RunningGuard running = new RunningGuard(runningMonitor);
/**
* Try to stop this change processor if running. This method will wait
* the specified time for a pending event listener to complete. If
* no timeout occurred no further events will be delivered after this
* method returns.
* <p>
* Does nothing if stopped already.
*
* @param timeOut time this method will wait for an executing event
* listener to complete.
* @param unit time unit for {@code timeOut}
* @return {@code true} if no time out occurred and this change processor
* could be stopped, {@code false} otherwise.
* @throws IllegalStateException if not yet started
*/
public synchronized boolean stopAndWait(int timeOut, TimeUnit unit) {
checkState(registration != null, "Change processor not started");
if (running.stop()) {
if (runningMonitor.enter(timeOut, unit)) {
registration.unregister();
runningMonitor.leave();
return true;
} else {
// Timed out
return false;
}
} else {
// Stopped already
return true;
}
}
/**
* Stop this change processor after all pending events have been
* delivered. In contrast to {@link #stopAndWait(int, java.util.concurrent.TimeUnit)}
* this method returns immediately without waiting for pending listeners to
* complete.
*/
public synchronized void stop() {
checkState(registration != null, "Change processor not started");
if (running.stop()) {
registration.unregister();
runningMonitor.leave();
}
}
@Override
public void contentChanged(@Nonnull NodeState root, @Nullable CommitInfo info) {
if (previousRoot != null) {
try {
long start = PERF_LOGGER.start();
FilterProvider provider = filterProvider.get();
// FIXME don't rely on toString for session id
if (provider.includeCommit(contentSession.toString(), info)) {
EventFilter filter = provider.getFilter(previousRoot, root);
EventIterator events = new EventQueue(namePathMapper, info, previousRoot, root,
provider.getSubTrees(), Filters.all(filter, VISIBLE_FILTER));
if (events.hasNext() && runningMonitor.enterIf(running)) {
try {
CountingIterator countingEvents = new CountingIterator(events);
eventListener.onEvent(countingEvents);
countingEvents.updateCounters(eventCount, eventDuration);
} finally {
runningMonitor.leave();
}
}
}
PERF_LOGGER.end(start, 100,
"Generated events (before: {}, after: {})",
previousRoot, root);
} catch (Exception e) {
LOG.warn("Error while dispatching observation events for " + tracker, e);
}
}
previousRoot = root;
}
private static class CountingIterator implements EventIterator {
private final long t0 = System.nanoTime();
private final EventIterator events;
private long eventCount;
private long sysTime;
public CountingIterator(EventIterator events) {
this.events = events;
}
public void updateCounters(MeterStats eventCount, TimerStats eventDuration) {
checkState(this.eventCount >= 0);
eventCount.mark(this.eventCount);
eventDuration.update(System.nanoTime() - t0 - sysTime, TimeUnit.NANOSECONDS);
this.eventCount = -1;
}
@Override
public Event next() {
if (eventCount == -1) {
LOG.warn("Access to EventIterator outside the onEvent callback detected. This will " +
"cause observation related values in RepositoryStatistics to become unreliable.");
eventCount = -2;
}
long t0 = System.nanoTime();
try {
return events.nextEvent();
} finally {
eventCount++;
sysTime += System.nanoTime() - t0;
}
}
@Override
public boolean hasNext() {
long t0 = System.nanoTime();
try {
return events.hasNext();
} finally {
sysTime += System.nanoTime() - t0;
}
}
@Override
public Event nextEvent() {
return next();
}
@Override
public void skip(long skipNum) {
long t0 = System.nanoTime();
try {
events.skip(skipNum);
} finally {
sysTime += System.nanoTime() - t0;
}
}
@Override
public long getSize() {
return events.getSize();
}
@Override
public long getPosition() {
return events.getPosition();
}
@Override
public void remove() {
throw new UnsupportedOperationException();
}
}
private static class RunningGuard extends Guard {
private boolean stopped;
public RunningGuard(Monitor monitor) {
super(monitor);
}
@Override
public boolean isSatisfied() {
return !stopped;
}
/**
* @return {@code true} if this call set this guard to stopped,
* {@code false} if another call set this guard to stopped before.
*/
public boolean stop() {
boolean wasStopped = stopped;
stopped = true;
return !wasStopped;
}
}
@Override
public String toString() {
return "ChangeProcessor ["
+ "listenerId=" + listenerId
+ ", tracker=" + tracker
+ ", contentSession=" + contentSession
+ ", eventCount=" + eventCount
+ ", eventDuration=" + eventDuration
+ ", commitRateLimiter=" + commitRateLimiter
+ ", running=" + running.isSatisfied() + "]";
}
}
| apache-2.0 |
dolszews/appium-tigerspike | src/main/java/io/appium/java_client/pagefactory/utils/WebDriverUnpackUtility.java | 5504 | /*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* See the NOTICE file distributed with this work for additional
* information regarding copyright ownership.
* 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.appium.java_client.pagefactory.utils;
import static io.appium.java_client.pagefactory.bys.ContentType.HTML_OR_DEFAULT;
import static io.appium.java_client.pagefactory.bys.ContentType.NATIVE_MOBILE_SPECIFIC;
import static java.util.Optional.ofNullable;
import io.appium.java_client.HasSessionDetails;
import io.appium.java_client.pagefactory.bys.ContentType;
import org.openqa.selenium.ContextAware;
import org.openqa.selenium.SearchContext;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.internal.WrapsDriver;
import org.openqa.selenium.internal.WrapsElement;
public final class WebDriverUnpackUtility {
private static final String NATIVE_APP_PATTERN = "NATIVE_APP";
/**
* This method extract an instance of {@link org.openqa.selenium.WebDriver} from the given
* {@link org.openqa.selenium.SearchContext}.
* @param searchContext is an instance of {@link org.openqa.selenium.SearchContext}
* It may be the instance of {@link org.openqa.selenium.WebDriver}
* or {@link org.openqa.selenium.WebElement} or some other user's
* extension/implementation.
* Note: if you want to use your own implementation then it should implement
* {@link org.openqa.selenium.internal.WrapsDriver} or
* {@link org.openqa.selenium.internal.WrapsElement}
* @return the instance of {@link org.openqa.selenium.WebDriver}.
* Note: if the given {@link org.openqa.selenium.SearchContext} is not
* {@link org.openqa.selenium.WebDriver} and it doesn't implement
* {@link org.openqa.selenium.internal.WrapsDriver} or
* {@link org.openqa.selenium.internal.WrapsElement} then this method returns
* null.
*
*/
public static WebDriver unpackWebDriverFromSearchContext(SearchContext searchContext) {
if (searchContext instanceof WebDriver) {
return (WebDriver) searchContext;
}
if (searchContext instanceof WrapsDriver) {
return unpackWebDriverFromSearchContext(
((WrapsDriver) searchContext).getWrappedDriver());
}
// Search context it is not only Webdriver. Webelement is search context
// too.
// RemoteWebElement and MobileElement implement WrapsDriver
if (searchContext instanceof WrapsElement) {
return unpackWebDriverFromSearchContext(
((WrapsElement) searchContext).getWrappedElement());
}
return null;
}
/**
* @param context is an instance of {@link org.openqa.selenium.SearchContext}
* It may be the instance of {@link org.openqa.selenium.WebDriver}
* or {@link org.openqa.selenium.WebElement} or some other user's
* extension/implementation.
* Note: if you want to use your own implementation then it should
* implement {@link org.openqa.selenium.ContextAware} or
* {@link org.openqa.selenium.internal.WrapsDriver}
* @return current content type. It depends on current context. If current context is
* NATIVE_APP it will return
* {@link io.appium.java_client.pagefactory.bys.ContentType#NATIVE_MOBILE_SPECIFIC}.
* {@link io.appium.java_client.pagefactory.bys.ContentType#HTML_OR_DEFAULT} will be returned
* if the current context is WEB_VIEW.
* {@link io.appium.java_client.pagefactory.bys.ContentType#HTML_OR_DEFAULT} also will be
* returned if the given {@link org.openqa.selenium.SearchContext}
* instance doesn't implement
* {@link org.openqa.selenium.ContextAware} and {@link org.openqa.selenium.internal.WrapsDriver}
*/
public static ContentType getCurrentContentType(SearchContext context) {
return ofNullable(unpackWebDriverFromSearchContext(context)).map(driver -> {
if (HasSessionDetails.class.isAssignableFrom(driver.getClass())) {
HasSessionDetails hasSessionDetails = HasSessionDetails.class.cast(driver);
if (hasSessionDetails.isBrowser()) {
return HTML_OR_DEFAULT;
}
return NATIVE_MOBILE_SPECIFIC;
}
if (!ContextAware.class.isAssignableFrom(driver.getClass())) { //it is desktop browser
return HTML_OR_DEFAULT;
}
ContextAware contextAware = ContextAware.class.cast(driver);
String currentContext = contextAware.getContext();
if (currentContext.contains(NATIVE_APP_PATTERN)) {
return NATIVE_MOBILE_SPECIFIC;
}
return HTML_OR_DEFAULT;
}).orElse(HTML_OR_DEFAULT);
}
}
| apache-2.0 |
weiwenqiang/GitHub | Update/AndroidUtilCode-master/utilcode/src/main/java/com/blankj/utilcode/util/SnackbarUtils.java | 8905 | package com.blankj.utilcode.util;
import android.support.annotation.ColorInt;
import android.support.annotation.DrawableRes;
import android.support.annotation.IntDef;
import android.support.annotation.IntRange;
import android.support.annotation.LayoutRes;
import android.support.annotation.NonNull;
import android.support.design.widget.Snackbar;
import android.text.SpannableString;
import android.text.Spanned;
import android.text.style.ForegroundColorSpan;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.ref.WeakReference;
/**
* <pre>
* author: Blankj
* blog : http://blankj.com
* time : 2016/10/16
* desc : Snackbar相关工具类
* </pre>
*/
public final class SnackbarUtils {
public static final int LENGTH_INDEFINITE = -2;
public static final int LENGTH_SHORT = -1;
public static final int LENGTH_LONG = 0;
@IntDef({LENGTH_INDEFINITE, LENGTH_SHORT, LENGTH_LONG})
@Retention(RetentionPolicy.SOURCE)
public @interface Duration {
}
private static final int COLOR_DEFAULT = 0xFEFFFFFF;
private static final int COLOR_SUCCESS = 0xFF2BB600;
private static final int COLOR_WARNING = 0xFFFFC100;
private static final int COLOR_ERROR = 0xFFFF0000;
private static final int COLOR_MESSAGE = 0xFFFFFFFF;
private static WeakReference<Snackbar> snackbarWeakReference;
private View parent;
private CharSequence message;
private int messageColor;
private int bgColor;
private int bgResource;
private int duration;
private CharSequence actionText;
private int actionTextColor;
private View.OnClickListener actionListener;
private int bottomMargin;
private SnackbarUtils(final View parent) {
setDefault();
this.parent = parent;
}
private void setDefault() {
message = "";
messageColor = COLOR_DEFAULT;
bgColor = COLOR_DEFAULT;
bgResource = -1;
duration = LENGTH_SHORT;
actionText = "";
actionTextColor = COLOR_DEFAULT;
bottomMargin = 0;
}
/**
* 设置snackbar依赖view
*
* @param parent 依赖view
* @return {@link SnackbarUtils}
*/
public static SnackbarUtils with(@NonNull final View parent) {
return new SnackbarUtils(parent);
}
/**
* 设置消息
*
* @param msg 消息
* @return {@link SnackbarUtils}
*/
public SnackbarUtils setMessage(@NonNull final CharSequence msg) {
this.message = msg;
return this;
}
/**
* 设置消息颜色
*
* @param color 颜色
* @return {@link SnackbarUtils}
*/
public SnackbarUtils setMessageColor(@ColorInt final int color) {
this.messageColor = color;
return this;
}
/**
* 设置背景色
*
* @param color 背景色
* @return {@link SnackbarUtils}
*/
public SnackbarUtils setBgColor(@ColorInt final int color) {
this.bgColor = color;
return this;
}
/**
* 设置背景资源
*
* @param bgResource 背景资源
* @return {@link SnackbarUtils}
*/
public SnackbarUtils setBgResource(@DrawableRes final int bgResource) {
this.bgResource = bgResource;
return this;
}
/**
* 设置显示时长
*
* @param duration 时长
* <ul>
* <li>{@link Duration#LENGTH_INDEFINITE}永久</li>
* <li>{@link Duration#LENGTH_SHORT}短时</li>
* <li>{@link Duration#LENGTH_LONG}长时</li>
* </ul>
* @return {@link SnackbarUtils}
*/
public SnackbarUtils setDuration(@Duration final int duration) {
this.duration = duration;
return this;
}
/**
* 设置行为
*
* @param text 文本
* @param listener 事件
* @return {@link SnackbarUtils}
*/
public SnackbarUtils setAction(@NonNull final CharSequence text, @NonNull final View.OnClickListener listener) {
return setAction(text, COLOR_DEFAULT, listener);
}
/**
* 设置行为
*
* @param text 文本
* @param color 文本颜色
* @param listener 事件
* @return {@link SnackbarUtils}
*/
public SnackbarUtils setAction(@NonNull final CharSequence text, @ColorInt final int color, @NonNull final View.OnClickListener listener) {
this.actionText = text;
this.actionTextColor = color;
this.actionListener = listener;
return this;
}
/**
* 设置底边距
*
* @param bottomMargin 底边距
*/
public SnackbarUtils setBottomMargin(@IntRange(from = 1) final int bottomMargin) {
this.bottomMargin = bottomMargin;
return this;
}
/**
* 显示snackbar
*/
public void show() {
final View view = parent;
if (view == null) return;
if (messageColor != COLOR_DEFAULT) {
SpannableString spannableString = new SpannableString(message);
ForegroundColorSpan colorSpan = new ForegroundColorSpan(messageColor);
spannableString.setSpan(colorSpan, 0, spannableString.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
snackbarWeakReference = new WeakReference<>(Snackbar.make(view, spannableString, duration));
} else {
snackbarWeakReference = new WeakReference<>(Snackbar.make(view, message, duration));
}
final Snackbar snackbar = snackbarWeakReference.get();
final View snackbarView = snackbar.getView();
if (bgResource != -1) {
snackbarView.setBackgroundResource(bgResource);
} else if (bgColor != COLOR_DEFAULT) {
snackbarView.setBackgroundColor(bgColor);
}
if (bottomMargin != 0) {
ViewGroup.MarginLayoutParams params = (ViewGroup.MarginLayoutParams) snackbarView.getLayoutParams();
params.bottomMargin = bottomMargin;
}
if (actionText.length() > 0 && actionListener != null) {
if (actionTextColor != COLOR_DEFAULT) {
snackbar.setActionTextColor(actionTextColor);
}
snackbar.setAction(actionText, actionListener);
}
snackbar.show();
}
/**
* 显示预设成功的snackbar
*/
public void showSuccess() {
bgColor = COLOR_SUCCESS;
messageColor = COLOR_MESSAGE;
actionTextColor = COLOR_MESSAGE;
show();
}
/**
* 显示预设警告的snackbar
*/
public void showWarning() {
bgColor = COLOR_WARNING;
messageColor = COLOR_MESSAGE;
actionTextColor = COLOR_MESSAGE;
show();
}
/**
* 显示预设错误的snackbar
*/
public void showError() {
bgColor = COLOR_ERROR;
messageColor = COLOR_MESSAGE;
actionTextColor = COLOR_MESSAGE;
show();
}
/**
* 消失snackbar
*/
public static void dismiss() {
if (snackbarWeakReference != null && snackbarWeakReference.get() != null) {
snackbarWeakReference.get().dismiss();
snackbarWeakReference = null;
}
}
/**
* 获取snackbar视图
*
* @return snackbar视图
*/
public static View getView() {
Snackbar snackbar = snackbarWeakReference.get();
if (snackbar == null) return null;
return snackbar.getView();
}
/**
* 添加snackbar视图
* <p>在{@link #show()}之后调用</p>
*
* @param layoutId 布局文件
* @param params 布局参数
*/
public static void addView(@LayoutRes final int layoutId, @NonNull final ViewGroup.LayoutParams params) {
final View view = getView();
if (view != null) {
view.setPadding(0, 0, 0, 0);
Snackbar.SnackbarLayout layout = (Snackbar.SnackbarLayout) view;
View child = LayoutInflater.from(view.getContext()).inflate(layoutId, null);
layout.addView(child, -1, params);
}
}
/**
* 添加snackbar视图
* <p>在{@link #show()}之后调用</p>
*
* @param child 要添加的view
* @param params 布局参数
*/
public static void addView(@NonNull final View child, @NonNull final ViewGroup.LayoutParams params) {
final View view = getView();
if (view != null) {
view.setPadding(0, 0, 0, 0);
Snackbar.SnackbarLayout layout = (Snackbar.SnackbarLayout) view;
layout.addView(child, params);
}
}
}
| apache-2.0 |
googleads/google-ads-java | google-ads-stubs-v8/src/main/java/com/google/ads/googleads/v8/common/HotelCheckInDateRangeInfo.java | 24968 | // Generated by the protocol buffer compiler. DO NOT EDIT!
// source: google/ads/googleads/v8/common/criteria.proto
package com.google.ads.googleads.v8.common;
/**
* <pre>
* Criterion for a check-in date range.
* </pre>
*
* Protobuf type {@code google.ads.googleads.v8.common.HotelCheckInDateRangeInfo}
*/
public final class HotelCheckInDateRangeInfo extends
com.google.protobuf.GeneratedMessageV3 implements
// @@protoc_insertion_point(message_implements:google.ads.googleads.v8.common.HotelCheckInDateRangeInfo)
HotelCheckInDateRangeInfoOrBuilder {
private static final long serialVersionUID = 0L;
// Use HotelCheckInDateRangeInfo.newBuilder() to construct.
private HotelCheckInDateRangeInfo(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) {
super(builder);
}
private HotelCheckInDateRangeInfo() {
startDate_ = "";
endDate_ = "";
}
@java.lang.Override
@SuppressWarnings({"unused"})
protected java.lang.Object newInstance(
UnusedPrivateParameter unused) {
return new HotelCheckInDateRangeInfo();
}
@java.lang.Override
public final com.google.protobuf.UnknownFieldSet
getUnknownFields() {
return this.unknownFields;
}
private HotelCheckInDateRangeInfo(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
this();
if (extensionRegistry == null) {
throw new java.lang.NullPointerException();
}
com.google.protobuf.UnknownFieldSet.Builder unknownFields =
com.google.protobuf.UnknownFieldSet.newBuilder();
try {
boolean done = false;
while (!done) {
int tag = input.readTag();
switch (tag) {
case 0:
done = true;
break;
case 10: {
java.lang.String s = input.readStringRequireUtf8();
startDate_ = s;
break;
}
case 18: {
java.lang.String s = input.readStringRequireUtf8();
endDate_ = s;
break;
}
default: {
if (!parseUnknownField(
input, unknownFields, extensionRegistry, tag)) {
done = true;
}
break;
}
}
}
} catch (com.google.protobuf.InvalidProtocolBufferException e) {
throw e.setUnfinishedMessage(this);
} catch (java.io.IOException e) {
throw new com.google.protobuf.InvalidProtocolBufferException(
e).setUnfinishedMessage(this);
} finally {
this.unknownFields = unknownFields.build();
makeExtensionsImmutable();
}
}
public static final com.google.protobuf.Descriptors.Descriptor
getDescriptor() {
return com.google.ads.googleads.v8.common.CriteriaProto.internal_static_google_ads_googleads_v8_common_HotelCheckInDateRangeInfo_descriptor;
}
@java.lang.Override
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return com.google.ads.googleads.v8.common.CriteriaProto.internal_static_google_ads_googleads_v8_common_HotelCheckInDateRangeInfo_fieldAccessorTable
.ensureFieldAccessorsInitialized(
com.google.ads.googleads.v8.common.HotelCheckInDateRangeInfo.class, com.google.ads.googleads.v8.common.HotelCheckInDateRangeInfo.Builder.class);
}
public static final int START_DATE_FIELD_NUMBER = 1;
private volatile java.lang.Object startDate_;
/**
* <pre>
* Start date in the YYYY-MM-DD format.
* </pre>
*
* <code>string start_date = 1;</code>
* @return The startDate.
*/
@java.lang.Override
public java.lang.String getStartDate() {
java.lang.Object ref = startDate_;
if (ref instanceof java.lang.String) {
return (java.lang.String) ref;
} else {
com.google.protobuf.ByteString bs =
(com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
startDate_ = s;
return s;
}
}
/**
* <pre>
* Start date in the YYYY-MM-DD format.
* </pre>
*
* <code>string start_date = 1;</code>
* @return The bytes for startDate.
*/
@java.lang.Override
public com.google.protobuf.ByteString
getStartDateBytes() {
java.lang.Object ref = startDate_;
if (ref instanceof java.lang.String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8(
(java.lang.String) ref);
startDate_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
public static final int END_DATE_FIELD_NUMBER = 2;
private volatile java.lang.Object endDate_;
/**
* <pre>
* End date in the YYYY-MM-DD format.
* </pre>
*
* <code>string end_date = 2;</code>
* @return The endDate.
*/
@java.lang.Override
public java.lang.String getEndDate() {
java.lang.Object ref = endDate_;
if (ref instanceof java.lang.String) {
return (java.lang.String) ref;
} else {
com.google.protobuf.ByteString bs =
(com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
endDate_ = s;
return s;
}
}
/**
* <pre>
* End date in the YYYY-MM-DD format.
* </pre>
*
* <code>string end_date = 2;</code>
* @return The bytes for endDate.
*/
@java.lang.Override
public com.google.protobuf.ByteString
getEndDateBytes() {
java.lang.Object ref = endDate_;
if (ref instanceof java.lang.String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8(
(java.lang.String) ref);
endDate_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
private byte memoizedIsInitialized = -1;
@java.lang.Override
public final boolean isInitialized() {
byte isInitialized = memoizedIsInitialized;
if (isInitialized == 1) return true;
if (isInitialized == 0) return false;
memoizedIsInitialized = 1;
return true;
}
@java.lang.Override
public void writeTo(com.google.protobuf.CodedOutputStream output)
throws java.io.IOException {
if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(startDate_)) {
com.google.protobuf.GeneratedMessageV3.writeString(output, 1, startDate_);
}
if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(endDate_)) {
com.google.protobuf.GeneratedMessageV3.writeString(output, 2, endDate_);
}
unknownFields.writeTo(output);
}
@java.lang.Override
public int getSerializedSize() {
int size = memoizedSize;
if (size != -1) return size;
size = 0;
if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(startDate_)) {
size += com.google.protobuf.GeneratedMessageV3.computeStringSize(1, startDate_);
}
if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(endDate_)) {
size += com.google.protobuf.GeneratedMessageV3.computeStringSize(2, endDate_);
}
size += unknownFields.getSerializedSize();
memoizedSize = size;
return size;
}
@java.lang.Override
public boolean equals(final java.lang.Object obj) {
if (obj == this) {
return true;
}
if (!(obj instanceof com.google.ads.googleads.v8.common.HotelCheckInDateRangeInfo)) {
return super.equals(obj);
}
com.google.ads.googleads.v8.common.HotelCheckInDateRangeInfo other = (com.google.ads.googleads.v8.common.HotelCheckInDateRangeInfo) obj;
if (!getStartDate()
.equals(other.getStartDate())) return false;
if (!getEndDate()
.equals(other.getEndDate())) return false;
if (!unknownFields.equals(other.unknownFields)) return false;
return true;
}
@java.lang.Override
public int hashCode() {
if (memoizedHashCode != 0) {
return memoizedHashCode;
}
int hash = 41;
hash = (19 * hash) + getDescriptor().hashCode();
hash = (37 * hash) + START_DATE_FIELD_NUMBER;
hash = (53 * hash) + getStartDate().hashCode();
hash = (37 * hash) + END_DATE_FIELD_NUMBER;
hash = (53 * hash) + getEndDate().hashCode();
hash = (29 * hash) + unknownFields.hashCode();
memoizedHashCode = hash;
return hash;
}
public static com.google.ads.googleads.v8.common.HotelCheckInDateRangeInfo parseFrom(
java.nio.ByteBuffer data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.ads.googleads.v8.common.HotelCheckInDateRangeInfo parseFrom(
java.nio.ByteBuffer data,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static com.google.ads.googleads.v8.common.HotelCheckInDateRangeInfo parseFrom(
com.google.protobuf.ByteString data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.ads.googleads.v8.common.HotelCheckInDateRangeInfo parseFrom(
com.google.protobuf.ByteString data,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static com.google.ads.googleads.v8.common.HotelCheckInDateRangeInfo parseFrom(byte[] data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.ads.googleads.v8.common.HotelCheckInDateRangeInfo parseFrom(
byte[] data,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static com.google.ads.googleads.v8.common.HotelCheckInDateRangeInfo parseFrom(java.io.InputStream input)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3
.parseWithIOException(PARSER, input);
}
public static com.google.ads.googleads.v8.common.HotelCheckInDateRangeInfo parseFrom(
java.io.InputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3
.parseWithIOException(PARSER, input, extensionRegistry);
}
public static com.google.ads.googleads.v8.common.HotelCheckInDateRangeInfo parseDelimitedFrom(java.io.InputStream input)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3
.parseDelimitedWithIOException(PARSER, input);
}
public static com.google.ads.googleads.v8.common.HotelCheckInDateRangeInfo parseDelimitedFrom(
java.io.InputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3
.parseDelimitedWithIOException(PARSER, input, extensionRegistry);
}
public static com.google.ads.googleads.v8.common.HotelCheckInDateRangeInfo parseFrom(
com.google.protobuf.CodedInputStream input)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3
.parseWithIOException(PARSER, input);
}
public static com.google.ads.googleads.v8.common.HotelCheckInDateRangeInfo parseFrom(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3
.parseWithIOException(PARSER, input, extensionRegistry);
}
@java.lang.Override
public Builder newBuilderForType() { return newBuilder(); }
public static Builder newBuilder() {
return DEFAULT_INSTANCE.toBuilder();
}
public static Builder newBuilder(com.google.ads.googleads.v8.common.HotelCheckInDateRangeInfo prototype) {
return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype);
}
@java.lang.Override
public Builder toBuilder() {
return this == DEFAULT_INSTANCE
? new Builder() : new Builder().mergeFrom(this);
}
@java.lang.Override
protected Builder newBuilderForType(
com.google.protobuf.GeneratedMessageV3.BuilderParent parent) {
Builder builder = new Builder(parent);
return builder;
}
/**
* <pre>
* Criterion for a check-in date range.
* </pre>
*
* Protobuf type {@code google.ads.googleads.v8.common.HotelCheckInDateRangeInfo}
*/
public static final class Builder extends
com.google.protobuf.GeneratedMessageV3.Builder<Builder> implements
// @@protoc_insertion_point(builder_implements:google.ads.googleads.v8.common.HotelCheckInDateRangeInfo)
com.google.ads.googleads.v8.common.HotelCheckInDateRangeInfoOrBuilder {
public static final com.google.protobuf.Descriptors.Descriptor
getDescriptor() {
return com.google.ads.googleads.v8.common.CriteriaProto.internal_static_google_ads_googleads_v8_common_HotelCheckInDateRangeInfo_descriptor;
}
@java.lang.Override
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return com.google.ads.googleads.v8.common.CriteriaProto.internal_static_google_ads_googleads_v8_common_HotelCheckInDateRangeInfo_fieldAccessorTable
.ensureFieldAccessorsInitialized(
com.google.ads.googleads.v8.common.HotelCheckInDateRangeInfo.class, com.google.ads.googleads.v8.common.HotelCheckInDateRangeInfo.Builder.class);
}
// Construct using com.google.ads.googleads.v8.common.HotelCheckInDateRangeInfo.newBuilder()
private Builder() {
maybeForceBuilderInitialization();
}
private Builder(
com.google.protobuf.GeneratedMessageV3.BuilderParent parent) {
super(parent);
maybeForceBuilderInitialization();
}
private void maybeForceBuilderInitialization() {
if (com.google.protobuf.GeneratedMessageV3
.alwaysUseFieldBuilders) {
}
}
@java.lang.Override
public Builder clear() {
super.clear();
startDate_ = "";
endDate_ = "";
return this;
}
@java.lang.Override
public com.google.protobuf.Descriptors.Descriptor
getDescriptorForType() {
return com.google.ads.googleads.v8.common.CriteriaProto.internal_static_google_ads_googleads_v8_common_HotelCheckInDateRangeInfo_descriptor;
}
@java.lang.Override
public com.google.ads.googleads.v8.common.HotelCheckInDateRangeInfo getDefaultInstanceForType() {
return com.google.ads.googleads.v8.common.HotelCheckInDateRangeInfo.getDefaultInstance();
}
@java.lang.Override
public com.google.ads.googleads.v8.common.HotelCheckInDateRangeInfo build() {
com.google.ads.googleads.v8.common.HotelCheckInDateRangeInfo result = buildPartial();
if (!result.isInitialized()) {
throw newUninitializedMessageException(result);
}
return result;
}
@java.lang.Override
public com.google.ads.googleads.v8.common.HotelCheckInDateRangeInfo buildPartial() {
com.google.ads.googleads.v8.common.HotelCheckInDateRangeInfo result = new com.google.ads.googleads.v8.common.HotelCheckInDateRangeInfo(this);
result.startDate_ = startDate_;
result.endDate_ = endDate_;
onBuilt();
return result;
}
@java.lang.Override
public Builder clone() {
return super.clone();
}
@java.lang.Override
public Builder setField(
com.google.protobuf.Descriptors.FieldDescriptor field,
java.lang.Object value) {
return super.setField(field, value);
}
@java.lang.Override
public Builder clearField(
com.google.protobuf.Descriptors.FieldDescriptor field) {
return super.clearField(field);
}
@java.lang.Override
public Builder clearOneof(
com.google.protobuf.Descriptors.OneofDescriptor oneof) {
return super.clearOneof(oneof);
}
@java.lang.Override
public Builder setRepeatedField(
com.google.protobuf.Descriptors.FieldDescriptor field,
int index, java.lang.Object value) {
return super.setRepeatedField(field, index, value);
}
@java.lang.Override
public Builder addRepeatedField(
com.google.protobuf.Descriptors.FieldDescriptor field,
java.lang.Object value) {
return super.addRepeatedField(field, value);
}
@java.lang.Override
public Builder mergeFrom(com.google.protobuf.Message other) {
if (other instanceof com.google.ads.googleads.v8.common.HotelCheckInDateRangeInfo) {
return mergeFrom((com.google.ads.googleads.v8.common.HotelCheckInDateRangeInfo)other);
} else {
super.mergeFrom(other);
return this;
}
}
public Builder mergeFrom(com.google.ads.googleads.v8.common.HotelCheckInDateRangeInfo other) {
if (other == com.google.ads.googleads.v8.common.HotelCheckInDateRangeInfo.getDefaultInstance()) return this;
if (!other.getStartDate().isEmpty()) {
startDate_ = other.startDate_;
onChanged();
}
if (!other.getEndDate().isEmpty()) {
endDate_ = other.endDate_;
onChanged();
}
this.mergeUnknownFields(other.unknownFields);
onChanged();
return this;
}
@java.lang.Override
public final boolean isInitialized() {
return true;
}
@java.lang.Override
public Builder mergeFrom(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
com.google.ads.googleads.v8.common.HotelCheckInDateRangeInfo parsedMessage = null;
try {
parsedMessage = PARSER.parsePartialFrom(input, extensionRegistry);
} catch (com.google.protobuf.InvalidProtocolBufferException e) {
parsedMessage = (com.google.ads.googleads.v8.common.HotelCheckInDateRangeInfo) e.getUnfinishedMessage();
throw e.unwrapIOException();
} finally {
if (parsedMessage != null) {
mergeFrom(parsedMessage);
}
}
return this;
}
private java.lang.Object startDate_ = "";
/**
* <pre>
* Start date in the YYYY-MM-DD format.
* </pre>
*
* <code>string start_date = 1;</code>
* @return The startDate.
*/
public java.lang.String getStartDate() {
java.lang.Object ref = startDate_;
if (!(ref instanceof java.lang.String)) {
com.google.protobuf.ByteString bs =
(com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
startDate_ = s;
return s;
} else {
return (java.lang.String) ref;
}
}
/**
* <pre>
* Start date in the YYYY-MM-DD format.
* </pre>
*
* <code>string start_date = 1;</code>
* @return The bytes for startDate.
*/
public com.google.protobuf.ByteString
getStartDateBytes() {
java.lang.Object ref = startDate_;
if (ref instanceof String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8(
(java.lang.String) ref);
startDate_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
/**
* <pre>
* Start date in the YYYY-MM-DD format.
* </pre>
*
* <code>string start_date = 1;</code>
* @param value The startDate to set.
* @return This builder for chaining.
*/
public Builder setStartDate(
java.lang.String value) {
if (value == null) {
throw new NullPointerException();
}
startDate_ = value;
onChanged();
return this;
}
/**
* <pre>
* Start date in the YYYY-MM-DD format.
* </pre>
*
* <code>string start_date = 1;</code>
* @return This builder for chaining.
*/
public Builder clearStartDate() {
startDate_ = getDefaultInstance().getStartDate();
onChanged();
return this;
}
/**
* <pre>
* Start date in the YYYY-MM-DD format.
* </pre>
*
* <code>string start_date = 1;</code>
* @param value The bytes for startDate to set.
* @return This builder for chaining.
*/
public Builder setStartDateBytes(
com.google.protobuf.ByteString value) {
if (value == null) {
throw new NullPointerException();
}
checkByteStringIsUtf8(value);
startDate_ = value;
onChanged();
return this;
}
private java.lang.Object endDate_ = "";
/**
* <pre>
* End date in the YYYY-MM-DD format.
* </pre>
*
* <code>string end_date = 2;</code>
* @return The endDate.
*/
public java.lang.String getEndDate() {
java.lang.Object ref = endDate_;
if (!(ref instanceof java.lang.String)) {
com.google.protobuf.ByteString bs =
(com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
endDate_ = s;
return s;
} else {
return (java.lang.String) ref;
}
}
/**
* <pre>
* End date in the YYYY-MM-DD format.
* </pre>
*
* <code>string end_date = 2;</code>
* @return The bytes for endDate.
*/
public com.google.protobuf.ByteString
getEndDateBytes() {
java.lang.Object ref = endDate_;
if (ref instanceof String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8(
(java.lang.String) ref);
endDate_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
/**
* <pre>
* End date in the YYYY-MM-DD format.
* </pre>
*
* <code>string end_date = 2;</code>
* @param value The endDate to set.
* @return This builder for chaining.
*/
public Builder setEndDate(
java.lang.String value) {
if (value == null) {
throw new NullPointerException();
}
endDate_ = value;
onChanged();
return this;
}
/**
* <pre>
* End date in the YYYY-MM-DD format.
* </pre>
*
* <code>string end_date = 2;</code>
* @return This builder for chaining.
*/
public Builder clearEndDate() {
endDate_ = getDefaultInstance().getEndDate();
onChanged();
return this;
}
/**
* <pre>
* End date in the YYYY-MM-DD format.
* </pre>
*
* <code>string end_date = 2;</code>
* @param value The bytes for endDate to set.
* @return This builder for chaining.
*/
public Builder setEndDateBytes(
com.google.protobuf.ByteString value) {
if (value == null) {
throw new NullPointerException();
}
checkByteStringIsUtf8(value);
endDate_ = value;
onChanged();
return this;
}
@java.lang.Override
public final Builder setUnknownFields(
final com.google.protobuf.UnknownFieldSet unknownFields) {
return super.setUnknownFields(unknownFields);
}
@java.lang.Override
public final Builder mergeUnknownFields(
final com.google.protobuf.UnknownFieldSet unknownFields) {
return super.mergeUnknownFields(unknownFields);
}
// @@protoc_insertion_point(builder_scope:google.ads.googleads.v8.common.HotelCheckInDateRangeInfo)
}
// @@protoc_insertion_point(class_scope:google.ads.googleads.v8.common.HotelCheckInDateRangeInfo)
private static final com.google.ads.googleads.v8.common.HotelCheckInDateRangeInfo DEFAULT_INSTANCE;
static {
DEFAULT_INSTANCE = new com.google.ads.googleads.v8.common.HotelCheckInDateRangeInfo();
}
public static com.google.ads.googleads.v8.common.HotelCheckInDateRangeInfo getDefaultInstance() {
return DEFAULT_INSTANCE;
}
private static final com.google.protobuf.Parser<HotelCheckInDateRangeInfo>
PARSER = new com.google.protobuf.AbstractParser<HotelCheckInDateRangeInfo>() {
@java.lang.Override
public HotelCheckInDateRangeInfo parsePartialFrom(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return new HotelCheckInDateRangeInfo(input, extensionRegistry);
}
};
public static com.google.protobuf.Parser<HotelCheckInDateRangeInfo> parser() {
return PARSER;
}
@java.lang.Override
public com.google.protobuf.Parser<HotelCheckInDateRangeInfo> getParserForType() {
return PARSER;
}
@java.lang.Override
public com.google.ads.googleads.v8.common.HotelCheckInDateRangeInfo getDefaultInstanceForType() {
return DEFAULT_INSTANCE;
}
}
| apache-2.0 |
joaojunior10/StormIDS | StormEngine/src/main/java/util/storm/StormRunner.java | 854 | package util.storm;
import backtype.storm.Config;
import backtype.storm.LocalCluster;
import backtype.storm.generated.StormTopology;
public final class StormRunner {
private static final int MILLIS_IN_SEC = 1000;
private StormRunner() {
}
public static void runTopologyLocally(StormTopology topology,
String topologyName, Config conf, int runtimeInSeconds)
throws InterruptedException {
LocalCluster cluster = new LocalCluster();
cluster.submitTopology(topologyName, conf, topology);
System.out
.println("\n\n==================================\n STORM TOPOLOGY INITIALIZING \n==================================\n\n");
// If the runtime is 0, it will run indefinitely
if (runtimeInSeconds != 0) {
Thread.sleep((long) runtimeInSeconds * MILLIS_IN_SEC);
cluster.killTopology(topologyName);
cluster.shutdown();
}
}
}
| apache-2.0 |
alexruiz/fest-assert-1.x | src/main/java/org/fest/assertions/BigDecimalAssert.java | 2977 | /*
* Created on Dec 27, 2006
*
* 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.
*
* Copyright @2006-2013 the original author or authors.
*/
package org.fest.assertions;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.math.BigDecimal;
import static java.math.BigDecimal.ZERO;
/**
* Assertions for {@code BigDecimal}s.
* <p/>
* To create a new instance of this class invoke {@link Assertions#assertThat(BigDecimal)}.
*
* @author David DIDIER
* @author Ted M. Young
* @author Yvonne Wang
* @author Alex Ruiz
*/
public class BigDecimalAssert extends ComparableAssert<BigDecimalAssert, BigDecimal> implements NumberAssert {
/**
* Creates a new {@link BigDecimalAssert}.
*
* @param actual the target to verify.
*/
protected BigDecimalAssert(@Nullable BigDecimal actual) {
super(BigDecimalAssert.class, actual);
}
/**
* Verifies that the actual {@code BigDecimal} is positive.
*
* @return this assertion object.
* @throws AssertionError if the actual {@code BigDecimal} value is {@code null}.
* @throws AssertionError if the actual {@code BigDecimal} value is not positive.
*/
@Override
public @NotNull BigDecimalAssert isPositive() {
return isGreaterThan(ZERO);
}
/**
* Verifies that the actual {@code BigDecimal} is negative.
*
* @return this assertion object.
* @throws AssertionError if the actual {@code BigDecimal} value is {@code null}.
* @throws AssertionError if the actual {@code BigDecimal} value is not negative.
*/
@Override
public @NotNull BigDecimalAssert isNegative() {
return isLessThan(ZERO);
}
/**
* Verifies that the actual {@code BigDecimal} is equal to zero, regardless of precision.
*
* @return this assertion object.
* @throws AssertionError if the actual {@code BigDecimal} value is {@code null}.
* @throws AssertionError if the actual {@code BigDecimal} value is not equal to zero.
*/
@Override
public @NotNull BigDecimalAssert isZero() {
return isEqualByComparingTo(ZERO);
}
/**
* Verifies that the actual {@code BigDecimal} is not equal to zero, regardless of precision.
*
* @return this assertion object.
* @throws AssertionError if the actual {@code BigDecimal} is {@code null}.
* @throws AssertionError if the actual {@code BigDecimal} is equal to zero.
*/
public @NotNull BigDecimalAssert isNotZero() {
return isNotEqualByComparingTo(ZERO);
}
}
| apache-2.0 |
salesfront/commons | src/main/java/com/salesfront/commons/shared/exception/request/parameter/SfXmlParsingException.java | 1338 | /*
* Copyright (C) Alexandre Harvey-Tremblay - All Rights Reserved
* Unauthorized copying of this file, via any medium is strictly prohibited
* Proprietary and confidential
* Written by Alexandre Harvey-Tremblay <ahtremblay@gmail.com>, 2014
*/
package com.salesfront.commons.shared.exception.request.parameter;
import com.salesfront.commons.shared.XmlError;
import java.util.ArrayList;
import java.util.List;
/**
* Created by ahtremblay on 15-10-07.
*/
public class SfXmlParsingException extends SfXmlException {
private static final long serialVersionUID = -3883421884427610735L;
public SfXmlParsingException() {
}
public SfXmlParsingException(List<XmlError> xmlErrorList) {
super(xmlErrorList);
}
public SfXmlParsingException(String message, List<XmlError> xmlErrorList) {
super(message, xmlErrorList);
}
public SfXmlParsingException(String message) {
super(message);
}
public SfXmlParsingException(String message, Throwable cause) {
super(message, cause);
}
public SfXmlParsingException(Throwable cause) {
super(cause);
}
public SfXmlParsingException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) {
super(message, cause, enableSuppression, writableStackTrace);
}
}
| apache-2.0 |
jonsabados/virp | virp-core/src/test/java/com/jshnd/virp/config/dummyclasses/notmapped/UnmappedClass.java | 87 | package com.jshnd.virp.config.dummyclasses.notmapped;
public class UnmappedClass {
}
| apache-2.0 |
ox-it/cucm-http-api | src/main/java/com/cisco/axl/api/_8/ListDeviceMobilityGroupRes.java | 4036 |
package com.cisco.axl.api._8;
import java.util.ArrayList;
import java.util.List;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlType;
/**
* <p>Java class for ListDeviceMobilityGroupRes complex type.
*
* <p>The following schema fragment specifies the expected content contained within this class.
*
* <pre>
* <complexType name="ListDeviceMobilityGroupRes">
* <complexContent>
* <extension base="{http://www.cisco.com/AXL/API/8.0}APIResponse">
* <sequence>
* <element name="return">
* <complexType>
* <complexContent>
* <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
* <sequence>
* <element name="deviceMobilityGroup" type="{http://www.cisco.com/AXL/API/8.0}LDeviceMobilityGroup" maxOccurs="unbounded" minOccurs="0"/>
* </sequence>
* </restriction>
* </complexContent>
* </complexType>
* </element>
* </sequence>
* </extension>
* </complexContent>
* </complexType>
* </pre>
*
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "ListDeviceMobilityGroupRes", propOrder = {
"_return"
})
public class ListDeviceMobilityGroupRes
extends APIResponse
{
@XmlElement(name = "return", required = true)
protected ListDeviceMobilityGroupRes.Return _return;
/**
* Gets the value of the return property.
*
* @return
* possible object is
* {@link ListDeviceMobilityGroupRes.Return }
*
*/
public ListDeviceMobilityGroupRes.Return getReturn() {
return _return;
}
/**
* Sets the value of the return property.
*
* @param value
* allowed object is
* {@link ListDeviceMobilityGroupRes.Return }
*
*/
public void setReturn(ListDeviceMobilityGroupRes.Return value) {
this._return = value;
}
/**
* <p>Java class for anonymous complex type.
*
* <p>The following schema fragment specifies the expected content contained within this class.
*
* <pre>
* <complexType>
* <complexContent>
* <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
* <sequence>
* <element name="deviceMobilityGroup" type="{http://www.cisco.com/AXL/API/8.0}LDeviceMobilityGroup" maxOccurs="unbounded" minOccurs="0"/>
* </sequence>
* </restriction>
* </complexContent>
* </complexType>
* </pre>
*
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "", propOrder = {
"deviceMobilityGroup"
})
public static class Return {
protected List<LDeviceMobilityGroup> deviceMobilityGroup;
/**
* Gets the value of the deviceMobilityGroup property.
*
* <p>
* This accessor method returns a reference to the live list,
* not a snapshot. Therefore any modification you make to the
* returned list will be present inside the JAXB object.
* This is why there is not a <CODE>set</CODE> method for the deviceMobilityGroup property.
*
* <p>
* For example, to add a new item, do as follows:
* <pre>
* getDeviceMobilityGroup().add(newItem);
* </pre>
*
*
* <p>
* Objects of the following type(s) are allowed in the list
* {@link LDeviceMobilityGroup }
*
*
*/
public List<LDeviceMobilityGroup> getDeviceMobilityGroup() {
if (deviceMobilityGroup == null) {
deviceMobilityGroup = new ArrayList<LDeviceMobilityGroup>();
}
return this.deviceMobilityGroup;
}
}
}
| apache-2.0 |
Developmc/Demo_UI_ContextMenu | app/src/main/java/com/yalantis/contextmenu/sample/MainActivity.java | 6410 | package com.yalantis.contextmenu.sample;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.os.Bundle;
import android.support.v4.app.DialogFragment;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v7.app.ActionBarActivity;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;
import com.yalantis.contextmenu.R;
import com.yalantis.contextmenu.lib.ContextMenuDialogFragment;
import com.yalantis.contextmenu.lib.MenuObject;
import com.yalantis.contextmenu.lib.MenuParams;
import com.yalantis.contextmenu.lib.interfaces.OnMenuItemClickListener;
import com.yalantis.contextmenu.lib.interfaces.OnMenuItemLongClickListener;
import java.util.ArrayList;
import java.util.List;
public class MainActivity extends ActionBarActivity implements OnMenuItemClickListener,
OnMenuItemLongClickListener{
private FragmentManager fragmentManager;
private DialogFragment mMenuDialogFragment;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
fragmentManager = getSupportFragmentManager();
initToolbar();
initMenuFragment();
addFragment(new MainFragment(), true, R.id.container);
}
private void initMenuFragment() {
MenuParams menuParams = new MenuParams();
menuParams.setActionBarSize((int) getResources().getDimension(R.dimen.tool_bar_height));
menuParams.setMenuObjects(getMenuObjects());
menuParams.setClosableOutside(false);
//创建实例
mMenuDialogFragment = ContextMenuDialogFragment.newInstance(menuParams);
}
private List<MenuObject> getMenuObjects() {
// You can use any [resource, bitmap, drawable, color] as image:
// item.setResource(...)
// item.setBitmap(...)
// item.setDrawable(...)
// item.setColor(...)
// You can set image ScaleType:
// item.setScaleType(ScaleType.FIT_XY)
// You can use any [resource, drawable, color] as background:
// item.setBgResource(...)
// item.setBgDrawable(...)
// item.setBgColor(...)
// You can use any [color] as text color:
// item.setTextColor(...)
// You can set any [color] as divider color:
// item.setDividerColor(...)
List<MenuObject> menuObjects = new ArrayList<>();
MenuObject close = new MenuObject();
close.setResource(R.drawable.icn_close);
MenuObject send = new MenuObject("Send message");
send.setResource(R.drawable.icn_1);
MenuObject like = new MenuObject("Like profile");
Bitmap b = BitmapFactory.decodeResource(getResources(), R.drawable.icn_2);
like.setBitmap(b);
MenuObject addFr = new MenuObject("Add to friends");
BitmapDrawable bd = new BitmapDrawable(getResources(),
BitmapFactory.decodeResource(getResources(), R.drawable.icn_3));
addFr.setDrawable(bd);
MenuObject addFav = new MenuObject("Add to favorites");
addFav.setResource(R.drawable.icn_4);
MenuObject block = new MenuObject("Block user");
block.setResource(R.drawable.icn_5);
menuObjects.add(close);
menuObjects.add(send);
menuObjects.add(like);
menuObjects.add(addFr);
menuObjects.add(addFav);
menuObjects.add(block);
return menuObjects;
}
private void initToolbar() {
Toolbar mToolbar = (Toolbar) findViewById(R.id.toolbar);
TextView mToolBarTextView = (TextView) findViewById(R.id.text_view_toolbar_title);
setSupportActionBar(mToolbar);
getSupportActionBar().setHomeButtonEnabled(true);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setDisplayShowTitleEnabled(false);
mToolbar.setNavigationIcon(R.drawable.btn_back);
mToolbar.setNavigationOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
onBackPressed();
}
});
mToolBarTextView.setText("Samantha");
}
protected void addFragment(Fragment fragment, boolean addToBackStack, int containerId) {
invalidateOptionsMenu();
String backStackName = fragment.getClass().getName();
boolean fragmentPopped = fragmentManager.popBackStackImmediate(backStackName, 0);
if (!fragmentPopped) {
FragmentTransaction transaction = fragmentManager.beginTransaction();
transaction.add(containerId, fragment, backStackName)
.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE);
if (addToBackStack)
transaction.addToBackStack(backStackName);
transaction.commit();
}
}
@Override
public boolean onCreateOptionsMenu(final Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.menu_main, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.context_menu:
if (fragmentManager.findFragmentByTag(ContextMenuDialogFragment.TAG) == null) {
mMenuDialogFragment.show(fragmentManager, ContextMenuDialogFragment.TAG);
}
break;
}
return super.onOptionsItemSelected(item);
}
@Override
public void onBackPressed() {
if (mMenuDialogFragment != null && mMenuDialogFragment.isAdded()) {
mMenuDialogFragment.dismiss();
} else{
finish();
}
}
@Override
public void onMenuItemClick(View clickedView, int position) {
Toast.makeText(this, "Clicked on position: " + position, Toast.LENGTH_SHORT).show();
}
@Override
public void onMenuItemLongClick(View clickedView, int position) {
Toast.makeText(this, "Long clicked on position: " + position, Toast.LENGTH_SHORT).show();
}
}
| apache-2.0 |
chutipon29301/MonkeyQRGenerator | src/Summary.java | 2801 | /*
* Copyright [2017] [Chutipon]
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
import java.awt.EventQueue;
import javax.swing.*;
import javax.swing.border.EmptyBorder;
import java.awt.Font;
import java.util.ArrayList;
@SuppressWarnings("SpellCheckingInspection")
class Summary extends JFrame {
private static String levelName;
private static String levelCode;
private static String levelRev;
/**
* Create the frame.
*/
private Summary() {
setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
setBounds(100, 100, 450, 300);
JPanel contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);
setLevelCode();
setLevelRev();
JLabel lblTheFollowingFile = new JLabel("The following file has been created.");
lblTheFollowingFile.setFont(new Font("Cordia New", Font.PLAIN, 18));
lblTheFollowingFile.setBounds(10, 11, 245, 26);
contentPane.add(lblTheFollowingFile);
ArrayList<JLabel> label = new ArrayList<>();
label.add(new JLabel("- " + levelCode + "SKILLKEY" + levelRev + ".pdf"));
label.add(new JLabel("- " + levelCode + "HWKEY" + levelRev + ".pdf"));
label.add(new JLabel("- " + levelCode + "TESTKEY" + levelRev + ".pdf"));
label.add(new JLabel("- " + levelCode + "HOTKEY" + levelRev + ".pdf"));
for (int i = 0; i < label.size(); i++) {
label.get(i).setVerticalAlignment(SwingConstants.TOP);
label.get(i).setFont(new Font("Cordia New", Font.PLAIN, 18));
label.get(i).setBounds(37, 48 + (i * 30), 361, 202);
contentPane.add(label.get(i));
}
}
static void run(String levelName) {
Summary.levelName = levelName;
EventQueue.invokeLater(() -> {
try {
Summary frame = new Summary();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
});
}
private void setLevelCode() {
levelCode = levelName.substring(0, levelName.indexOf('('));
}
private void setLevelRev() {
levelRev = levelName.substring(levelName.indexOf('('));
}
} | apache-2.0 |
MAMISHO/AppCostal-Beta | appCostal-beta/src/java/com/appcostal/struts/AddPasoAction.java | 2635 | /*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package com.appcostal.struts;
import appcostal.model.DAO;
import appcostal.model.Hermano;
import appcostal.model.Paso;
import appcostal.model.RelHermanoPaso;
import appcostal.model.RelHermanoPasoId;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
/**
*
* @author MAMISHO
*/
public class AddPasoAction extends org.apache.struts.action.Action {
/* forward name="success" path="" */
private static final String SUCCESS = "success";
/**
* This is the action called from the Struts framework.
*
* @param mapping The ActionMapping used to select this instance.
* @param form The optional ActionForm bean for this request.
* @param request The HTTP Request we are processing.
* @param response The HTTP Response we are processing.
* @throws java.lang.Exception
* @return
*/
@Override
public ActionForward execute(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response)
throws Exception {
String dni =((AddPasoActionForm)form).getDni();
//String nombre=((AddPasoActionForm)form).getNombre();
//String apellido1=((AddPasoActionForm)form).getApellido1();
//String apellido2=((AddPasoActionForm)form).getApellido2();
if(dni==null){
dni=(String) request.getAttribute("dni");
}
DAO dao=new DAO();
List<RelHermanoPaso> pasos_hermano=dao.pasosDeHermano(dni);
List<Paso> pasos=new ArrayList();
Iterator<RelHermanoPaso> it=pasos_hermano.iterator();
while(it.hasNext()){
Integer idPaso=it.next().getId().getIdpaso();
Paso paso=dao.obtenerPaso(idPaso.toString());
if(paso!=null){
pasos.add(paso);
}
}
List<Paso> pasosDisponibles=pasosDisponibles=dao.pasosDisponibles();
Hermano hermano=dao.obtenerHermano(dni);
pasosDisponibles.removeAll(pasos);
request.setAttribute("listaPasos", pasosDisponibles);
request.setAttribute("hermano", hermano);
request.setAttribute("pasosHermano", pasos);
return mapping.findForward(SUCCESS);
}
}
| apache-2.0 |
adammurdoch/native-platform | file-events/src/main/java/net/rubygrapefruit/platform/internal/jni/InotifyInstanceLimitTooLowException.java | 432 | package net.rubygrapefruit.platform.internal.jni;
/**
* A {@link InotifyInstanceLimitTooLowException} is thrown by {@link AbstractFileEventFunctions.AbstractWatcherBuilder#start()}
* when the inotify instance count is too low.
*/
public class InotifyInstanceLimitTooLowException extends InsufficientResourcesForWatchingException {
public InotifyInstanceLimitTooLowException(String message) {
super(message);
}
}
| apache-2.0 |
dorzey/assertj-core | src/test/java/org/assertj/core/util/BigDecimalComparatorTest.java | 2121 | /**
* 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.
*
* Copyright 2012-2016 the original author or authors.
*/
package org.assertj.core.util;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.util.BigDecimalComparator.BIG_DECIMAL_COMPARATOR;
import java.math.BigDecimal;
import org.junit.Test;
public class BigDecimalComparatorTest {
@Test
public void should_consider_null_to_be_less_than_non_bull() {
// GIVEN
BigDecimal bigDecimal1 = null;
BigDecimal bigDecimal2 = BigDecimal.ZERO;
// WHEN
int result = BIG_DECIMAL_COMPARATOR.compare(bigDecimal1, bigDecimal2);
// THEN
assertThat(result).isNegative();
}
@Test
public void should_consider_non_null_to_be_greater_than_null() {
// GIVEN
BigDecimal bigDecimal1 = BigDecimal.ZERO;
BigDecimal bigDecimal2 = null;
// WHEN
int result = BIG_DECIMAL_COMPARATOR.compare(bigDecimal1, bigDecimal2);
// THEN
assertThat(result).isPositive();
}
@Test
public void should_return_0_when_both_BigDecimal_are_null() {
// GIVEN
BigDecimal bigDecimal1 = null;
BigDecimal bigDecimal2 = null;
// WHEN
int result = BIG_DECIMAL_COMPARATOR.compare(bigDecimal1, bigDecimal2);
// THEN
assertThat(result).isZero();
}
@Test
public void should_compare_BigDecimal_with_natural_comparator() {
// GIVEN
BigDecimal bigDecimal1 = new BigDecimal("0.0");
BigDecimal bigDecimal2 = new BigDecimal("0.000000");
// WHEN
int result = BIG_DECIMAL_COMPARATOR.compare(bigDecimal1, bigDecimal2);
// THEN
assertThat(result).isZero();
}
}
| apache-2.0 |
opentracing-contrib/java-spring-cloud | instrument-starters/opentracing-spring-cloud-jdbc-starter/src/test/java/io/opentracing/contrib/spring/cloud/jdbc/MockTracingConfiguration.java | 1164 | /**
* Copyright 2017-2018 The OpenTracing 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 io.opentracing.contrib.spring.cloud.jdbc;
import io.opentracing.mock.MockTracer;
import io.opentracing.util.GlobalTracerTestUtil;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
/**
* @author Pavol Loffay
*/
@Configuration
@EnableAutoConfiguration
public class MockTracingConfiguration {
@Bean
public MockTracer mockTracer() {
GlobalTracerTestUtil.resetGlobalTracer();
return new MockTracer();
}
}
| apache-2.0 |
yareeh/l8er | src/test/java/l8er/Java8.java | 4293 | package l8er;
import static java.util.Arrays.asList;
import static java.util.stream.Collectors.joining;
import static java.util.stream.Collectors.toList;
import static java.util.stream.Collectors.toMap;
import static java.util.stream.Stream.concat;
import static java.util.stream.Stream.generate;
import static java.util.stream.Stream.iterate;
import static org.hamcrest.core.Is.is;
import static org.hamcrest.core.IsCollectionContaining.hasItems;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertThat;
import static org.junit.Assert.assertTrue;
import java.util.Map;
import java.util.function.BinaryOperator;
import java.util.function.Predicate;
import java.util.stream.Stream;
import org.junit.Test;
public class Java8 {
private static final Predicate<Integer> even = n -> (n & 1) != 1;
private static final Predicate<Integer> odd = n -> (n & 1) == 1;
private static final BinaryOperator<Integer> sum = (n, m) -> n + m;
@Test
public void examples() {
assertThat(Stream.of(1, 2, 3, 4).filter(even).collect(toList()), is(asList(2, 4)));
assertThat(Stream.of(1, 2).map(String::valueOf).collect(toList()), is(asList("1", "2")));
assertThat(asList(1, 2).parallelStream().map(String::valueOf).collect(toList()), is(asList("1", "2")));
assertThat(Stream.of(1, 2, 3).limit(2).collect(toList()), is(asList(1, 2)));
assertThat(Stream.of(1, 2, 3).skip(2).collect(toList()), is(asList(3)));
assertThat(Stream.of(1, 2, 3).skip(1).collect(toList()), is(asList(2, 3)));
assertThat(Stream.of(1, 2, 3).limit(1).collect(toList()), is(asList(1)));
assertThat(Stream.of(1, 2, 3).reduce(sum).get(), is(6));
assertThat(Stream.of(1, 3, 5).filter(even).collect(toList()), is(asList()));
assertTrue(Stream.of(1, 2, 3).anyMatch(n -> n == 2));
assertTrue(Stream.of(1, 2, 3).anyMatch(even));
assertFalse(Stream.of(1, 2, 3).allMatch(odd));
assertFalse(Stream.of(1, 2, 3).noneMatch(odd));
assertThat(Stream.of(1, 2, 3).reduce(0, sum), is(6));
assertThat(Stream.of(1, 2, 3).map(String::valueOf).collect(joining(",")), is("1,2,3"));
assertThat(Stream.of(1, 2, 3).map(String::valueOf).collect(joining(":")), is("1:2:3"));
final Map<Integer, Integer> map = Stream.of(asList(1, 2), asList(3, 4)).collect(toMap(a -> a.get(0), a -> a.get(1)));
assertThat(map.keySet(), hasItems(1, 3));
assertThat(map.values(), hasItems(2, 4));
assertThat(Stream.of(asList(1, 2), asList(3, 4)).flatMap(a -> a.stream()).collect(toList()), is(asList(1, 2, 3, 4)));
assertThat(Stream.of(1, 2, 2, 3).distinct().collect(toList()), is(asList(1, 2, 3)));
assertThat(iterate(1, n -> n + 1).limit(3).collect(toList()), is(asList(1, 2, 3)));
assertThat(generate(() -> "car").limit(3).collect(toList()), is(asList("car", "car", "car")));
assertThat(concat(Stream.of(1, 2), Stream.of(3, 4)).collect(toList()), is(asList(1, 2, 3, 4)));
}
@Test
public void blogExamples() {
Stream.of(1, 2, 3, 4).filter(even); // returns 2, 4
Stream.of(1, 2).map(String::valueOf); // returns "1", "2"
asList(1, 2).parallelStream().map(String::valueOf); // execute in parallel
Stream.of(1, 2, 3).limit(2); // returns 1, 2
Stream.of(1, 2, 3).skip(2); // returns 3
Stream.of(1, 2, 3).skip(1); // returns 2, 3
Stream.of(1, 2, 3).findFirst(); // returns 1
Stream.of(1, 2, 3).reduce(sum); // returns 6
Stream.of(1, 3, 5).filter(even).findFirst(); // returns Option.none()
Stream.of(1, 2, 3).anyMatch(n -> n == 2); // returns true
Stream.of(1, 2, 3).anyMatch(even); // returns true
Stream.of(1, 2, 3).allMatch(odd); // returns false
Stream.of(1, 2, 3).noneMatch(odd); // returns false
Stream.of(1, 2, 3).reduce(0, sum); // returns 6
Stream.of(1, 2, 3).map(String::valueOf).collect(joining(",")); // returns "1,2,3"
Stream.of(1, 2, 3).map(String::valueOf).collect(joining(":")); // returns "1:2:3"
Stream.of(asList(1, 2), asList(3, 4)).collect(toMap(a -> a.get(0), a -> a.get(1))); // returns map where 1 -> 2, 3 -> 4
Stream.of(asList(1, 2), asList(3, 4)).flatMap(a -> a.stream()); // returns 1, 2, 3, 4
Stream.of(1, 2, 2, 3).distinct(); // returns 1, 2, 3
iterate(1, n -> n + 1); // returns 1, 2, 3, ...
generate(() -> "car"); // lazily returns an infinite sequence of "car"s
concat(Stream.of(1, 2), Stream.of(3, 4)); // returns 1, 2, 3, 4
}
}
| apache-2.0 |
jjjaaajjj/ws-android-murach | ex_solutions/ch09_ex2_TipCalculator_sol/src/com/murach/tipcalculator/AboutFragment.java | 520 | package com.murach.tipcalculator;
import android.app.Fragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
public class AboutFragment extends Fragment {
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_about, container, false);
return view;
}
} | apache-2.0 |
Xevryll/JDA | src/main/java/net/dv8tion/jda/core/handle/VoiceServerUpdateHandler.java | 3726 | /*
* Copyright 2015-2017 Austin Keener & Michael Ritter
*
* 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.dv8tion.jda.core.handle;
import com.neovisionaries.ws.client.WebSocketException;
import net.dv8tion.jda.core.audio.AudioConnection;
import net.dv8tion.jda.core.audio.AudioWebSocket;
import net.dv8tion.jda.core.entities.Guild;
import net.dv8tion.jda.core.entities.impl.JDAImpl;
import net.dv8tion.jda.core.managers.impl.AudioManagerImpl;
import net.dv8tion.jda.core.requests.GuildLock;
import net.dv8tion.jda.core.requests.WebSocketClient;
import org.json.JSONObject;
import java.io.IOException;
public class VoiceServerUpdateHandler extends SocketHandler
{
public VoiceServerUpdateHandler(JDAImpl api)
{
super(api);
}
@Override
protected Long handleInternally(JSONObject content)
{
final long guildId = content.getLong("guild_id");
api.getClient().getQueuedAudioConnectionMap().remove(guildId);
if (api.getGuildLock().isLocked(guildId))
return guildId;
if (content.isNull("endpoint"))
{
//Discord did not provide an endpoint yet, we are to wait until discord has resources to provide
// an endpoint, which will result in them sending another VOICE_SERVER_UPDATE which we will handle
// to actually connect to the audio server.
return null;
}
String endpoint = content.getString("endpoint");
String token = content.getString("token");
Guild guild = api.getGuildMap().get(guildId);
if (guild == null)
throw new IllegalArgumentException("Attempted to start audio connection with Guild that doesn't exist! JSON: " + content);
String sessionId = guild.getSelfMember().getVoiceState().getSessionId();
if (sessionId == null)
throw new IllegalArgumentException("Attempted to create audio connection without having a session ID. Did VOICE_STATE_UPDATED fail?");
//Strip the port from the endpoint.
endpoint = endpoint.replace(":80", "");
AudioManagerImpl audioManager = (AudioManagerImpl) guild.getAudioManager();
synchronized (audioManager.CONNECTION_LOCK) //Synchronized to prevent attempts to close while setting up initial objects.
{
if (audioManager.isConnected())
audioManager.prepareForRegionChange();
if (!audioManager.isAttemptingToConnect())
{
WebSocketClient.LOG.debug("Received a VOICE_SERVER_UPDATE but JDA is not currently connected nor attempted to connect " +
"to a VoiceChannel. Assuming that this is caused by another client running on this account. Ignoring the event.");
return null;
}
AudioWebSocket socket = new AudioWebSocket(audioManager.getListenerProxy(), endpoint, api, guild, sessionId, token, audioManager.isAutoReconnect());
AudioConnection connection = new AudioConnection(socket, audioManager.getQueuedAudioConnection());
audioManager.setAudioConnection(connection);
socket.startConnection();
return null;
}
}
}
| apache-2.0 |
intellimate/Izou | src/main/java/org/intellimate/izou/system/context/ContextImplementation.java | 34156 | package org.intellimate.izou.system.context;
import org.intellimate.izou.activator.ActivatorModel;
import org.intellimate.izou.identification.AddOnInformation;
import org.intellimate.izou.addon.AddOnModel;
import org.intellimate.izou.events.*;
import org.intellimate.izou.identification.Identifiable;
import org.intellimate.izou.identification.Identification;
import org.intellimate.izou.identification.IdentificationManager;
import org.intellimate.izou.identification.IllegalIDException;
import org.intellimate.izou.main.Main;
import org.intellimate.izou.output.OutputControllerModel;
import org.intellimate.izou.output.OutputExtensionModel;
import org.intellimate.izou.output.OutputPluginModel;
import org.intellimate.izou.resource.ResourceModel;
import org.intellimate.izou.resource.ResourceBuilderModel;
import org.intellimate.izou.system.Context;
import org.intellimate.izou.system.file.FileSubscriber;
import org.intellimate.izou.system.file.ReloadableFile;
import org.intellimate.izou.system.logger.IzouLogger;
import org.intellimate.izou.threadpool.TrackingExecutorService;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.spi.ExtendedLogger;
import org.intellimate.izou.util.IdentifiableSet;
import java.io.File;
import java.io.IOException;
import java.nio.file.Path;
import java.util.List;
import java.util.Optional;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutorService;
import java.util.function.Consumer;
/**
* This class provides much of the general Communication with Izou.
*/
public class ContextImplementation implements Context {
private final AddOnModel addOn;
private final Main main;
private final Events events = new EventsImpl();
private final Resources resources = new ResourcesImpl();
private final Files files;
private final ExtendedLogger logger;
private final ThreadPool threadPool;
private final Activators activators = new ActivatorsImpl();
private final Output output = new OutputImpl();
private final System system = new SystemImpl();
private final AddOns addOns = new AddOnsImpl();
/**
* creates a new context for the addOn
*
* A context contains all the "global" or generally necessary information an addOn might need that it otherwise does
* not have access too
*
* @param addOn the addOn for which to create a new context
* @param main instance of main
* @param logLevel the logLevel to initialize the IzouLogger with
*/
public ContextImplementation(AddOnModel addOn, Main main, String logLevel) {
this.addOn = addOn;
this.main = main;
this.files = new FilesImpl();
this.threadPool = new ThreadPoolImpl();
IzouLogger izouLogger = main.getIzouLogger();
if (izouLogger != null)
this.logger = izouLogger.createFileLogger(addOn.getID(), logLevel);
else {
this.logger = null;
org.apache.logging.log4j.Logger fileLogger = LogManager.getLogger(this.getClass());
fileLogger.error("IzouLogger has not been initialized");
throw new NullPointerException("IzouLogger has not been initialized");
}
}
/**
* returns the API used for interaction with Events
* @return Events
*/
@Override
public Events getEvents() {
return events;
}
/**
* returns the API used for interaction with Resource
* @return Resource
*/
@Override
public Resources getResources() {
return resources;
}
/**
* returns the API used for interaction with Files
* @return Files
*/
@Override
public Files getFiles() {
return files;
}
/**
* gets logger for addOn
*
* @return the logger
*/
@Override
public ExtendedLogger getLogger() {
return logger;
}
/**
* returns the API used to manage the ThreadPool
* @return ThreadPool
*/
@Override
public ThreadPool getThreadPool() {
return threadPool;
}
/**
* returns the API to manage the Activators
* @return Activator
*/
@Override
public Activators getActivators() {
return activators;
}
/**
* Returns the API used to manage the OutputPlugins and OutputExtensions.
*
* @return Output
*/
@Override
public Output getOutput() {
return output;
}
/**
* Returns the API used to interact with Izou.
*
* @return System.
*/
@Override
public System getSystem() {
return system;
}
/**
* Gets the API to manage the addOns.
*
* @return AddOns.
*/
@Override
public AddOns getAddOns() {
return addOns;
}
private class FilesImpl implements Files {
/**
* Use this method to register a file with the watcherService
*
* @param dir directory of file
* @param fileType the name/extension of the file
* IMPORTANT: Please try to always enter the full name with extension of the file (Ex: "test.txt"),
* it would be best if the fileType is the full file name, and that the file name is clearly
* distinguishable from other files.
* For example, the property files are stored with the ID of the addon they belong too. That way
* every property file is easily distinguishable.
* @param reloadableFile object of interface that file belongs to
* @throws IOException exception thrown by watcher service
*/
@Override
public void registerFileDir(Path dir, String fileType, ReloadableFile reloadableFile) throws IOException {
main.getFileManager().registerFileDir(dir, fileType, reloadableFile);
}
/**
* Writes default file to real file
* The default file would be a file that can be packaged along with the code, from which a real file (say a
* properties file for example) can be loaded. This is useful because there are files (like property files0 that
* cannot be shipped with the package and have to be created at runtime. To still be able to fill these files, you
* can create a default file (usually txt) from which the content, as mentioned above, can then be loaded into the
* real file.
*
* @param defaultFilePath path to default file (or where it should be created)
* @param realFilePath path to real file (that should be filled with content of default file)
* @return true if operation has succeeded, else false
*/
@Override
public boolean writeToFile(String defaultFilePath, String realFilePath) {
return main.getFileManager().writeToFile(defaultFilePath, realFilePath);
}
/**
* Creates a default File in case it does not exist yet. Default files can be used to load other files that are
* created at runtime (like properties file)
*
* @param defaultFilePath path to default file.txt (or where it should be created)
* @param initMessage the string to write in default file
* @throws java.io.IOException is thrown by bufferedWriter
*/
@Override
public void createDefaultFile(String defaultFilePath, String initMessage) throws IOException {
main.getFileManager().createDefaultFile(defaultFilePath, initMessage);
}
/**
* Registers a {@link FileSubscriber} with a {@link ReloadableFile}. So when the {@code reloadableFile} is
* reloaded, the fileSubscriber will be notified. Multiple file subscribers can be registered with the same
* reloadable file.
*
* @param reloadableFile the reloadable file that should be observed
* @param fileSubscriber the fileSubscriber that should be notified when the reloadable file is reloaded
* @param identification the Identification of the requesting instance
* @throws IllegalIDException not yet implemented
*/
@Override
public void register(ReloadableFile reloadableFile, FileSubscriber fileSubscriber,
Identification identification) throws IllegalIDException {
main.getFilePublisher().register(reloadableFile, fileSubscriber, identification);
}
/**
* Registers a {@link FileSubscriber} so that whenever any file is reloaded, the fileSubscriber is notified.
*
* @param fileSubscriber the fileSubscriber that should be notified when the reloadable file is reloaded
* @param identification the Identification of the requesting instance
* @throws IllegalIDException not yet implemented
*/
@Override
public void register(FileSubscriber fileSubscriber, Identification identification) throws IllegalIDException {
main.getFilePublisher().register(fileSubscriber, identification);
}
/**
* Unregisters all instances of fileSubscriber found.
*
* @param fileSubscriber the fileSubscriber to unregister
*/
@Override
public void unregister(FileSubscriber fileSubscriber) {
main.getFilePublisher().unregister(fileSubscriber);
}
/**
* gets the File pointing towards the location of the lib-folder
*
* @return the File
*/
@Override
public File getLibLocation() {
return main.getFileSystemManager().getLibLocation();
}
/**
* gets the File pointing towards the location of the resource-folder
*
* @return the File
*/
@Override
public File getResourceLocation() {
return main.getFileSystemManager().getResourceLocation();
}
/**
* gets the File pointing towards the location of the properties-folder
*
* @return the File
*/
@Override
public File getPropertiesLocation() {
return main.getFileSystemManager().getPropertiesLocation();
}
/**
* gets the File pointing towards the location of the logs-folder
*
* @return the File
*/
@Override
public File getLogsLocation() {
return main.getFileSystemManager().getLogsLocation();
}
}
private class EventsImpl implements Events {
public EventsDistributor eventsDistributor = new DistributorImpl();
/**
* Adds an listener for events.
* <p>
* Be careful with this method, it will register the listener for ALL the informations found in the Event. If your
* event-type is a common event type, it will fire EACH time!.
* It will also register for all Descriptors individually!
* It will also ignore if this listener is already listening to an Event.
* Method is thread-safe.
* </p>
* @param event the Event to listen to (it will listen to all descriptors individually!)
* @param eventListener the ActivatorEventListener-interface for receiving activator events
* @throws IllegalIDException not yet implemented
*/
@SuppressWarnings("JavaDoc")
@Override
public void registerEventListener(EventModel event, EventListenerModel eventListener) throws IllegalIDException {
main.getEventDistributor().registerEventListener(event, eventListener);
}
/**
* Adds an listener for events.
* <p>
* It will register for all ids individually!
* This method will ignore if this listener is already listening to an Event.
* Method is thread-safe.
* </p>
* @param ids this can be type, or descriptors etc.
* @param eventListener the ActivatorEventListener-interface for receiving activator events
*/
@Override
public void registerEventListener(List<String> ids, EventListenerModel eventListener) {
main.getEventDistributor().registerEventListener(ids, eventListener);
}
/**
* unregister an EventListener
*<p>
* It will unregister for all Descriptors individually!
* It will also ignore if this listener is not listening to an Event.
* Method is thread-safe.
*
* @param event the Event to stop listen to
* @param eventListener the ActivatorEventListener used to listen for events
* @throws IllegalArgumentException if Listener is already listening to the Event or the id is not allowed
*/
@Override
public void unregisterEventListener(EventModel event, EventListenerModel eventListener) {
main.getEventDistributor().unregisterEventListener(event, eventListener);
}
/**
* unregister an EventListener that gets called before the generation of the resources and the outputPlugins.
* <p>
* It will unregister for all Descriptors individually!
* It will also ignore if this listener is not listening to an Event.
* Method is thread-safe.
*
* @param eventListener the ActivatorEventListener used to listen for events
* @throws IllegalArgumentException if Listener is already listening to the Event or the id is not allowed
*/
@Override
public void unregisterEventListener(EventListenerModel eventListener) {
main.getEventDistributor().unregisterEventListener(eventListener);
}
/**
* Adds an listener for events that gets called when the event finished processing.
* <p>
* Be careful with this method, it will register the listener for ALL the informations found in the Event. If your
* event-type is a common event type, it will fire EACH time!.
* It will also register for all Descriptors individually!
* It will also ignore if this listener is already listening to an Event.
* Method is thread-safe.
* </p>
*
* @param event the Event to listen to (it will listen to all descriptors individually!)
* @param eventListener the ActivatorEventListener-interface for receiving activator events
* @throws IllegalIDException not yet implemented
*/
@Override
public void registerEventFinishedListener(EventModel event, EventListenerModel eventListener) throws IllegalIDException {
main.getEventDistributor().registerEventFinishedListener(event, eventListener);
}
/**
* Adds an listener for events that gets called when the event finished processing.
* <p>
* It will register for all ids individually!
* This method will ignore if this listener is already listening to an Event.
* Method is thread-safe.
* </p>
*
* @param ids this can be type, or descriptors etc.
* @param eventListener the ActivatorEventListener-interface for receiving activator events
*/
@Override
public void registerEventFinishedListener(List<String> ids, EventListenerModel eventListener) {
main.getEventDistributor().registerEventFinishedListener(ids, eventListener);
}
/**
* unregister an EventListener that got called when the event finished processing.
* <p>
* It will unregister for all Descriptors individually!
* It will also ignore if this listener is not listening to an Event.
* Method is thread-safe.
*
* @param event the Event to stop listen to
* @param eventListener the ActivatorEventListener used to listen for events
* @throws IllegalArgumentException if Listener is already listening to the Event or the id is not allowed
*/
@Override
public void unregisterEventFinishedListener(EventModel event, EventListenerModel eventListener) {
main.getEventDistributor().unregisterEventFinishedListener(event, eventListener);
}
/**
* unregister an EventListener that got called when the event finished processing.
* <p>
* It will unregister for all Descriptors individually!
* It will also ignore if this listener is not listening to an Event.
* Method is thread-safe.
*
* @param eventListener the ActivatorEventListener used to listen for events
* @throws IllegalArgumentException if Listener is already listening to the Event or the id is not allowed
*/
@Override
public void unregisterEventFinishedListener(EventListenerModel eventListener) {
main.getEventDistributor().unregisterEventFinishedListener(eventListener);
}
/**
* Registers with the LocalEventManager to fire an event.
* <p>
* Note: the same Event can be fired from multiple sources.
* Method is thread-safe.
* @param identification the Identification of the the instance
* @return an Optional, empty if already registered
* @throws IllegalIDException not yet implemented
*/
@Override
public Optional<EventCallable> registerEventCaller(Identification identification) throws IllegalIDException {
return main.getLocalEventManager().registerCaller(identification);
}
/**
* Unregister with the LocalEventManager.
* <p>
* Method is thread-safe.
* @param identification the Identification of the the instance
*/
@Override
public void unregisterEventCaller(Identification identification) {
main.getLocalEventManager().unregisterCaller(identification);
}
/**
* This method fires an Event
*
* @param event the fired Event
* @throws IllegalIDException not yet implemented
*/
@Override
public void fireEvent(EventModel event) throws IllegalIDException, MultipleEventsException {
main.getLocalEventManager().fireEvent(event);
}
/**
* returns the API for the EventsDistributor
* @return Distributor
*/
@Override
public EventsDistributor distributor() {
return eventsDistributor;
}
/**
* returns the ID of the Manager (LocalEventManager)
*/
@Override
public Identification getManagerIdentification() {
Optional<Identification> identification = IdentificationManager.getInstance()
.getIdentification(main.getLocalEventManager());
if (!identification.isPresent()) {
//should not happen
throw new RuntimeException("unable to obtain ID for LocalEventManager");
}
return identification.get();
}
private class DistributorImpl implements EventsDistributor {
/**
* with this method you can register EventPublisher add a Source of Events to the System.
* <p>
* This method represents a higher level of abstraction! Use the EventManager to fire Events!
* This method is intended for use cases where you have an entire new source of events (e.g. network)
* @param identification the Identification of the Source
* @return An Optional Object which may or may not contains an EventPublisher
* @throws IllegalIDException not yet implemented
*/
@Override
public Optional<EventCallable> registerEventPublisher(Identification identification) throws IllegalIDException {
return main.getEventDistributor().registerEventPublisher(identification);
}
/**
* with this method you can unregister EventPublisher add a Source of Events to the System.
* <p>
* This method represents a higher level of abstraction! Use the EventManager to fire Events!
* This method is intended for use cases where you have an entire new source of events (e.g. network)
* @param identification the Identification of the Source
*/
@Override
public void unregisterEventPublisher(Identification identification) {
main.getEventDistributor().unregisterEventPublisher(identification);
}
/**
* Registers an EventController to control EventDispatching-Behaviour
* <p>
* Method is thread-safe.
* It is expected that this method executes quickly.
*
* @param eventsController the EventController Interface to control event-dispatching
* @throws IllegalIDException not yet implemented
*/
@Override
public void registerEventsController(EventsControllerModel eventsController) throws IllegalIDException {
main.getEventDistributor().registerEventsController(eventsController);
}
/**
* Unregisters an EventController
* <p>
* Method is thread-safe.
*
* @param eventsController the EventController Interface to remove
*/
@Override
public void unregisterEventsController(EventsControllerModel eventsController) {
main.getEventDistributor().unregisterEventsController(eventsController);
}
/**
* fires the event concurrently, this is generally discouraged.
* <p>
* This method should not be used for normal Events, for for events which obey the following laws:<br>
* 1. they are time critical.<br>
* 2. addons are not expected to react in any way beside a small update<br>
* 3. they are few.<br>
* if your event matches the above laws, you may consider firing it concurrently.
* </p>
*
* @param eventModel the EventModel
*/
@Override
public void fireEventConcurrently(EventModel<?> eventModel) {
main.getEventDistributor().fireEventConcurrently(eventModel);
}
/**
* returns the ID of the Manager (EventsDistributor)
*/
@Override
public Identification getManagerIdentification() {
Optional<Identification> identification = IdentificationManager.getInstance()
.getIdentification(main.getEventDistributor());
if (!identification.isPresent()) {
//should not happen
throw new RuntimeException("unable to obtain ID for EventsDistributor");
}
return identification.get();
}
}
}
private class ResourcesImpl implements Resources {
/**
* registers a ResourceBuilder.
* <p>
* this method registers all the events, resourcesID etc.
* </p>
* @param resourceBuilder an instance of the ResourceBuilder
* @throws IllegalIDException not yet implemented
*/
@Override
public void registerResourceBuilder(ResourceBuilderModel resourceBuilder) throws IllegalIDException {
main.getResourceManager().registerResourceBuilder(resourceBuilder);
}
/**
* unregister a ResourceBuilder.
* <p>
* this method unregisters all the events, resourcesID etc.
* @param resourceBuilder an instance of the ResourceBuilder
*/
@Override
public void unregisterResourceBuilder(ResourceBuilderModel resourceBuilder) {
main.getResourceManager().unregisterResourceBuilder(resourceBuilder);
}
/**
* generates a resources
* <p>
* @param resource the resource to request
* @param consumer the callback when the ResourceBuilder finishes
* @throws IllegalIDException not yet implemented
*/
@Override
@Deprecated
public void generateResource(ResourceModel resource, Consumer<List<ResourceModel>> consumer) throws IllegalIDException {
main.getResourceManager().generatedResource(resource, consumer);
}
/**
* generates a resources
* <p>
* It will use the first matching resource! So if you really want to be sure, set the provider
* Identification
* </p>
* @param resource the resource to request
* @return an optional of an CompletableFuture
* @throws IllegalIDException not yet implemented
*/
@Override
public Optional<CompletableFuture<List<ResourceModel>>> generateResource(ResourceModel resource) throws IllegalIDException {
return main.getResourceManager().generateResource(resource);
}
/**
* returns the ID of the Manager
*/
@Override
public Identification getManagerIdentification() {
Optional<Identification> identification = IdentificationManager.getInstance()
.getIdentification(main.getResourceManager());
if (!identification.isPresent()) {
//should not happen
throw new RuntimeException("unable to obtain ID for ResourceManager");
}
return identification.get();
}
}
private class ThreadPoolImpl implements ThreadPool {
/**
* returns an ThreadPool where all the IzouPlugins are running
* @param identifiable the Identifiable to set each created Task as the Source
* @return an instance of ExecutorService
* @throws IllegalIDException not implemented yet
*/
@Override
public ExecutorService getThreadPool(Identifiable identifiable) throws IllegalIDException {
return TrackingExecutorService.createTrackingExecutorService(
main.getThreadPoolManager().getAddOnsThreadPool(), identifiable);
}
/**
* tries everything to log the exception
*
* @param throwable the Throwable
* @param target an instance of the thing which has thrown the Exception
*/
@Override
public void handleThrowable(Throwable throwable, Object target) {
main.getThreadPoolManager().handleThrowable(throwable, target);
}
/**
* returns the ID of the Manager
*/
@Override
public Identification getManagerIdentification() {
Optional<Identification> identification = IdentificationManager.getInstance()
.getIdentification(main.getEventDistributor());
if (!identification.isPresent()) {
//should not happen
throw new RuntimeException("unable to obtain ID for ThreadPoolManager");
}
return identification.get();
}
}
private class ActivatorsImpl implements Activators {
/**
* adds an activator and automatically submits it to the Thread-Pool
* @param activatorModel the activator to add
* @throws IllegalIDException not yet implemented
*/
@Override
public void addActivator(ActivatorModel activatorModel) throws IllegalIDException {
main.getActivatorManager().addActivator(activatorModel);
}
/**
* removes the activator and stops the Thread
* @param activatorModel the activator to remove
*/
@Override
public void removeActivator(ActivatorModel activatorModel) {
main.getActivatorManager().removeActivator(activatorModel);
}
/**
* returns the ID of the Manager
*/
@Override
public Identification getManagerIdentification() {
Optional<Identification> identification = IdentificationManager.getInstance()
.getIdentification(main.getActivatorManager());
if (!identification.isPresent()) {
//should not happen
throw new RuntimeException("unable to obtain ID for ActivatorManager");
}
return identification.get();
}
}
private class AddOnsImpl implements AddOns {
@Override
public AddOnModel getAddOn() {
return addOn;
}
@Override
public Optional<AddOnInformation> getAddOnInformation(String id) {
return main.getAddOnInformationManager().getAddOnInformation(id);
}
@Override
public Optional<AddOnInformation> getAddOnInformation(int serverID) {
return main.getAddOnInformationManager().getAddOnInformation(serverID);
}
@Override
public IdentifiableSet<AddOnInformation> getAllAddOnInformations() {
return main.getAddOnInformationManager().getAllAddOnInformations();
}
}
private class OutputImpl implements Output {
/**
* adds output extension to desired outputPlugin
*
* adds output extension to desired outputPlugin, so that the output-plugin can start and stop the outputExtension
* task as needed. The outputExtension is specific to the output-plugin
*
* @param outputExtension the outputExtension to be added
* @throws IllegalIDException not yet implemented
*/
@Override
public void addOutputExtension(OutputExtensionModel outputExtension) throws IllegalIDException {
main.getOutputManager().addOutputExtension(outputExtension);
}
/**
* removes the output-extension of id: extensionId from outputPluginList
*
* @param outputExtension the OutputExtension to remove
*/
@Override
public void removeOutputExtension(OutputExtensionModel outputExtension) {
main.getOutputManager().removeOutputExtension(outputExtension);
}
/**
* adds outputPlugin to outputPluginList, starts a new thread for the outputPlugin, and stores the future object in a HashMap
* @param outputPlugin OutputPlugin to add
* @throws IllegalIDException not yet implemented
*/
@Override
public void addOutputPlugin(OutputPluginModel outputPlugin) throws IllegalIDException {
main.getOutputManager().addOutputPlugin(outputPlugin);
}
/**
* removes the OutputPlugin and stops the thread
* @param outputPlugin the outputPlugin to remove
*/
@Override
public void removeOutputPlugin(OutputPluginModel outputPlugin) {
main.getOutputManager().removeOutputPlugin(outputPlugin);
}
@Override
public void addOutputController(OutputControllerModel outputController) {
main.getOutputControllerManager().addOutputController(outputController);
}
@Override
public void removeOutputController(OutputControllerModel outputController) {
main.getOutputControllerManager().removeOutputController(outputController);
}
@Override
public Optional<OutputControllerModel> getOutputController(Identifiable identifiable) {
return main.getOutputControllerManager().getOutputController(identifiable);
}
/**
* returns all the associated OutputExtensions
*
* @param outputPlugin the OutputPlugin to search for
* @return a List of Identifications
*/
@Override
public List<Identification> getAssociatedOutputExtension(OutputPluginModel<?, ?> outputPlugin) {
return main.getOutputManager().getAssociatedOutputExtension(outputPlugin);
}
/**
* starts every associated OutputExtension
*
* @param outputPlugin the OutputPlugin to generate the Data for
* @param t the argument or null
* @param event the Event to generate for @return a List of Future-Objects
* @param <T> the type of the argument
* @param <X> the return type
* @return a List of Future-Objects
*/
@Override
public <T, X> List<CompletableFuture<X>> generateAllOutputExtensions(OutputPluginModel<T, X> outputPlugin,
T t, EventModel event) {
return main.getOutputManager().generateAllOutputExtensions(outputPlugin, t, event);
}
/**
* returns the ID of the Manager
*/
@Override
public Identification getManagerIdentification() {
Optional<Identification> identification = IdentificationManager.getInstance()
.getIdentification(main.getOutputManager());
if (!identification.isPresent()) {
//should not happen
throw new RuntimeException("unable to obtain ID for OutputManager");
}
return identification.get();
}
}
private class SystemImpl implements System {
/**
* this method registers an listener which will be fired when all the addons finished registering.
*
* @param runnable the runnable to register.
*/
@Override
public void registerInitializedListener(Runnable runnable) {
main.getAddOnManager().addInitializedListener(runnable);
}
}
}
| apache-2.0 |
sdempsay/osgi-jaxrs-services | publisher/src/main/java/com/pavlovmedia/oss/jaxrs/publisher/impl/swagger/SwaggerConfiguration.java | 2414 | /*
* Copyright 2017 Pavlov Media
*
* 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.pavlovmedia.oss.jaxrs.publisher.impl.swagger;
import org.osgi.service.component.annotations.Activate;
import org.osgi.service.component.annotations.Component;
import org.osgi.service.component.annotations.Modified;
import org.osgi.service.metatype.annotations.Designate;
import com.pavlovmedia.oss.jaxrs.publisher.api.Publisher;
import com.pavlovmedia.oss.jaxrs.publisher.impl.config.SwaggerConfigurationConfig;
/**
* This class represents the meta-data that can be served by
* swagger.
*
* @author Shawn Dempsay {@literal <sdempsay@pavlovmedia.com>}
*
*/
@Component(immediate=true,
property= {
Publisher.SCAN_IGNORE + "=true",
"com.eclipsesource.jaxrs.publish=false"
},
service= {
SwaggerConfiguration.class
})
@Designate(ocd = SwaggerConfigurationConfig.class)
public class SwaggerConfiguration {
public String title;
public String description;
public String apiVersion;
public String contactName;
public String contactUrl;
public String contactEmail;
public String licenseName;
public String licenseUrl;
@Activate
protected void activate(final SwaggerConfigurationConfig properties) {
parse(properties);
}
@Modified
protected void modified(final SwaggerConfigurationConfig properties) {
parse(properties);
}
private void parse(final SwaggerConfigurationConfig properties) {
title = properties.title();
description = properties.description();
apiVersion = properties.apiVersion();
contactName = properties.contactName();
contactUrl = properties.contactUrl();
contactEmail = properties.contactEmail();
licenseName = properties.licenseName();
licenseUrl = properties.licenseUrl();
}
}
| apache-2.0 |
google/gke-auditor | src/main/java/com/google/gke/auditor/system/RunnerConfig.java | 7661 | // Copyright 2020 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package com.google.gke.auditor.system;
import com.google.gke.auditor.configs.DetectorConfig;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;
import java.util.stream.Stream;
/**
* A configuration class for running the tool.
* <p>
* Controls settings such as: which detectors will be run and in which way, output coloring, output
* verbosity, inclusion of default K8s assets into the auditing.
*/
public class RunnerConfig {
/**
* List of RBAC detectors needed to be run.
*/
private List<DetectorConfig> rbacDetectors;
/**
* List of node isolation detectors needed to be run.
*/
private List<DetectorConfig> isolationDetectors;
/**
* List of PSP detectors needed to be run.
*/
private List<DetectorConfig> pspDetectors;
/**
* If false, runs each detector on all assets. If true, runs all detectors on each asset.
*/
private Boolean runIndividualAssets;
/**
* If true, the tool output is non-verbose.
*/
private boolean quiet;
/**
* If true, the tool output is colored.
*/
private boolean color;
/**
* If true, K8s defaults will be included in the audit.
*/
private boolean includeDefaults;
private RunnerConfig() {
}
/**
* Returns true if the output is colored, false otherwise.
*/
public boolean isOutputColored() {
return color;
}
/**
* Returns true if the output is non-verbose, false otherwise.
*/
public boolean isQuiet() {
return quiet;
}
/**
* Returns true if the K8s defaults should be included in the audit, false otherwise.
*/
public boolean shouldIncludeDefaults() {
return includeDefaults;
}
/**
* Returns true if the detectors need to be run on individual assets, false otherwise.
*/
public boolean getRunIndividualAssets() {
return this.runIndividualAssets;
}
/**
* Returns all asset types used by the configured detectors.
*/
public ResourceType[] getAssetTypes() {
return getAllDetectors()
.stream()
.map(DetectorConfig::getAssetFilters)
.flatMap(Arrays::stream)
.distinct()
.toArray(ResourceType[]::new);
}
/**
* Returns a list of RBAC detectors needed to be run.
*/
public List<DetectorConfig> getRbacDetectors() {
return rbacDetectors;
}
/**
* Returns a list of node isolation detectors needed to be run.
*/
public List<DetectorConfig> getIsolationDetectors() {
return isolationDetectors;
}
/**
* Returns a list of psp detectors needed to be run.
*/
public List<DetectorConfig> getPspDetectors() {
return pspDetectors;
}
/**
* Gets a list of all detectors needed to be run.
* <p>
* Note: this does not return all supported detectors, rather returns a joined list of detectors
* requested to be run from each group.
*/
public List<DetectorConfig> getAllDetectors() {
return Stream.of(rbacDetectors, isolationDetectors, pspDetectors)
.flatMap(Collection::stream)
.collect(Collectors.toList());
}
/***
* Builder class for {@link RunnerConfig}.
*/
public static class Builder {
private Set<Integer> rbacIndices;
private Set<Integer> isolationIndices;
private Set<Integer> pspIndices;
private boolean runIndividualAssets;
private boolean quiet;
private boolean color;
private boolean includeDefaults;
/**
* Builds and returns a {@link RunnerConfig}.
*/
public RunnerConfig build() {
RunnerConfig config = new RunnerConfig();
config.rbacDetectors = filterDetectors(Detectors.RBAC_DETECTORS, rbacIndices);
config.isolationDetectors = filterDetectors(Detectors.ISOLATION_DETECTORS, isolationIndices);
config.pspDetectors = filterDetectors(Detectors.PSP_DETECTORS, pspIndices);
config.quiet = quiet;
config.color = color;
config.includeDefaults = includeDefaults;
config.runIndividualAssets = runIndividualAssets;
return config;
}
/**
* Set a list of 1-indexed indices of RBAC detectors to run.
* @param rbacIndices list of indices for RBAC detectors that need to be run
* @return this
*/
public Builder setRbacDetectorIndices(Set<Integer> rbacIndices) {
this.rbacIndices = rbacIndices;
return this;
}
/**
* Set a list of 1-indexed indices of isolation detectors to run.
* @param isolationIndices list of indices for isolation detectors that need to be run
* @return this
*/
public Builder setIsolationDetectorIndices(Set<Integer> isolationIndices) {
this.isolationIndices = isolationIndices;
return this;
}
/**
* Set a list of 1-indexed indices of PSP detectors to run
* @param pspIndices list of indices for PSP detectors that need to be run
* @return this
*/
public Builder setPspDetectorIndices(Set<Integer> pspIndices) {
this.pspIndices = pspIndices;
return this;
}
/**
* If set to false, runs each detector on all assets. If true, runs all detectors on each
* asset.
* @param runIndividualAssets if true, the tool will be run on each asset individually
* @return this
*/
public Builder setRunIndividualAssets(boolean runIndividualAssets) {
this.runIndividualAssets = runIndividualAssets;
return this;
}
/**
* If set to true, the auditor output is non-verbose.
* @param quiet if true, the output is non-verbose
* @return this
*/
public Builder setQuiet(boolean quiet) {
this.quiet = quiet;
return this;
}
/**
* If set to true, the auditor output is colored.
* @param color if true, the output is colored
* @return this
*/
public Builder setColor(boolean color) {
this.color = color;
return this;
}
/**
* If set to true, the tool includes default K8s assets into the audit.
* @param includeDefaults true if defaults need to be included, false otherwise
* @return this
*/
public Builder setIncludeDefaults(boolean includeDefaults) {
this.includeDefaults = includeDefaults;
return this;
}
/**
* Filters the list of detector according to the list of given indices (1-indexed). If indices
* are null, returns all detectors.
* @param detectors detectors that need to be filtered.
* @param indices list of 1-indexed indices of detectors that need to be filtered
* @return list of filtered detectors
*/
private List<DetectorConfig> filterDetectors(List<DetectorConfig> detectors,
Set<Integer> indices) {
if (indices == null) {
return detectors;
}
List<DetectorConfig> filteredDetectors = new ArrayList<>();
for (int i : indices) {
// Indices are 1-indexed.
if (i > 0 && i <= detectors.size()) {
filteredDetectors.add(detectors.get(i - 1));
}
}
return filteredDetectors;
}
}
}
| apache-2.0 |
gstevey/gradle | subprojects/core-api/src/main/java/org/gradle/plugin/management/package-info.java | 778 | /*
* Copyright 2017 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.
*/
/**
* APIs to influence how plugins are resolved.
* @since 3.5
*/
@org.gradle.api.Incubating
@org.gradle.api.NonNullApi
package org.gradle.plugin.management;
| apache-2.0 |
gavin2lee/generic-support | auth-admin-api/src/main/java/com/generic/support/admin/repository/UserRepository.java | 919 | package com.generic.support.admin.repository;
import java.util.List;
import org.apache.ibatis.annotations.Delete;
import org.apache.ibatis.annotations.Param;
import com.lachesis.support.objects.entity.auth.Role;
import com.lachesis.support.objects.entity.auth.User;
import com.lachesis.support.objects.entity.auth.UserRole;
public interface UserRepository {
User findOne(@Param("id") Long id);
User findOneByUsername(@Param("username") String username);
Long insertOne(User u);
Integer updateOne(User u);
Integer addRole(UserRole userRole);
Integer addRoles(List<UserRole> userRoles);
Integer deleteRoles(@Param("userId") Long userId, @Param("roles") List<Role> roles);
Integer deleteRole(@Param("userId") Long userId, @Param("role") Role role);
Integer deleteAllRoles(@Param("userId") Long userID);
@Delete("delete from T_USER where ID = #{id}")
Integer deleteOne(@Param("id") Long id);
}
| apache-2.0 |
taktos/ea2ddl | ea2ddl-dao/src/main/java/jp/sourceforge/ea2ddl/dao/cbean/nss/TPaletteitemNss.java | 970 | package jp.sourceforge.ea2ddl.dao.cbean.nss;
import jp.sourceforge.ea2ddl.dao.cbean.cq.TPaletteitemCQ;
/**
* The nest select set-upper of t_paletteitem.
* @author DBFlute(AutoGenerator)
*/
public class TPaletteitemNss {
protected TPaletteitemCQ _query;
public TPaletteitemNss(TPaletteitemCQ query) { _query = query; }
public boolean hasConditionQuery() { return _query != null; }
// ===================================================================================
// With Nested Foreign Table
// =========================
// ===================================================================================
// With Nested Referrer Table
// ==========================
}
| apache-2.0 |
evandor/skysail-webconsole | webconsole.osgi/src/io/skysail/webconsole/osgi/entities/PackageResolvingCandidate.java | 617 | package io.skysail.webconsole.osgi.entities;
import org.osgi.service.packageadmin.ExportedPackage;
import io.skysail.webconsole.osgi.entities.bundles.BundleDescriptor;
import lombok.Getter;
@Getter
public class PackageResolvingCandidate {
private BundleDescriptor exportingBundle;
private String name;
private String version;
@SuppressWarnings("deprecation")
public PackageResolvingCandidate(ExportedPackage export) {
exportingBundle = new BundleDescriptor(export.getExportingBundle(),null);
name = export.getName();
version = export.getVersion().toString();
}
}
| apache-2.0 |
simon-eastwood/DependencyCheckCM | dependency-check-core/src/main/java/org/owasp/dependencycheck/jaxb/pom/generated/Reporting.java | 7218 | //
// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, vJAXB 2.1.10 in JDK 6
// See <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a>
// Any modifications to this file will be lost upon recompilation of the source schema.
// Generated on: 2012.11.09 at 12:33:57 PM EST
//
package org.owasp.dependencycheck.jaxb.pom.generated;
import java.util.ArrayList;
import java.util.List;
import javax.annotation.Generated;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlType;
/**
* Section for management of reports and their configuration.
*
* <p>Java class for Reporting complex type.
*
* <p>The following schema fragment specifies the expected content contained within this class.
*
* <pre>
* <complexType name="Reporting">
* <complexContent>
* <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
* <all>
* <element name="excludeDefaults" type="{http://www.w3.org/2001/XMLSchema}boolean" minOccurs="0"/>
* <element name="outputDirectory" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
* <element name="plugins" minOccurs="0">
* <complexType>
* <complexContent>
* <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
* <sequence>
* <element name="plugin" type="{http://maven.apache.org/POM/4.0.0}ReportPlugin" maxOccurs="unbounded" minOccurs="0"/>
* </sequence>
* </restriction>
* </complexContent>
* </complexType>
* </element>
* </all>
* </restriction>
* </complexContent>
* </complexType>
* </pre>
*
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "Reporting", propOrder = {
})
@Generated(value = "com.sun.tools.internal.xjc.Driver", date = "2012-11-09T12:33:57-05:00", comments = "JAXB RI vJAXB 2.1.10 in JDK 6")
public class Reporting {
@XmlElement(defaultValue = "false")
@Generated(value = "com.sun.tools.internal.xjc.Driver", date = "2012-11-09T12:33:57-05:00", comments = "JAXB RI vJAXB 2.1.10 in JDK 6")
protected Boolean excludeDefaults;
@Generated(value = "com.sun.tools.internal.xjc.Driver", date = "2012-11-09T12:33:57-05:00", comments = "JAXB RI vJAXB 2.1.10 in JDK 6")
protected String outputDirectory;
@Generated(value = "com.sun.tools.internal.xjc.Driver", date = "2012-11-09T12:33:57-05:00", comments = "JAXB RI vJAXB 2.1.10 in JDK 6")
protected Reporting.Plugins plugins;
/**
* Gets the value of the excludeDefaults property.
*
* @return
* possible object is
* {@link Boolean }
*
*/
@Generated(value = "com.sun.tools.internal.xjc.Driver", date = "2012-11-09T12:33:57-05:00", comments = "JAXB RI vJAXB 2.1.10 in JDK 6")
public Boolean isExcludeDefaults() {
return excludeDefaults;
}
/**
* Sets the value of the excludeDefaults property.
*
* @param value
* allowed object is
* {@link Boolean }
*
*/
@Generated(value = "com.sun.tools.internal.xjc.Driver", date = "2012-11-09T12:33:57-05:00", comments = "JAXB RI vJAXB 2.1.10 in JDK 6")
public void setExcludeDefaults(Boolean value) {
this.excludeDefaults = value;
}
/**
* Gets the value of the outputDirectory property.
*
* @return
* possible object is
* {@link String }
*
*/
@Generated(value = "com.sun.tools.internal.xjc.Driver", date = "2012-11-09T12:33:57-05:00", comments = "JAXB RI vJAXB 2.1.10 in JDK 6")
public String getOutputDirectory() {
return outputDirectory;
}
/**
* Sets the value of the outputDirectory property.
*
* @param value
* allowed object is
* {@link String }
*
*/
@Generated(value = "com.sun.tools.internal.xjc.Driver", date = "2012-11-09T12:33:57-05:00", comments = "JAXB RI vJAXB 2.1.10 in JDK 6")
public void setOutputDirectory(String value) {
this.outputDirectory = value;
}
/**
* Gets the value of the plugins property.
*
* @return
* possible object is
* {@link Reporting.Plugins }
*
*/
@Generated(value = "com.sun.tools.internal.xjc.Driver", date = "2012-11-09T12:33:57-05:00", comments = "JAXB RI vJAXB 2.1.10 in JDK 6")
public Reporting.Plugins getPlugins() {
return plugins;
}
/**
* Sets the value of the plugins property.
*
* @param value
* allowed object is
* {@link Reporting.Plugins }
*
*/
@Generated(value = "com.sun.tools.internal.xjc.Driver", date = "2012-11-09T12:33:57-05:00", comments = "JAXB RI vJAXB 2.1.10 in JDK 6")
public void setPlugins(Reporting.Plugins value) {
this.plugins = value;
}
/**
* <p>Java class for anonymous complex type.
*
* <p>The following schema fragment specifies the expected content contained within this class.
*
* <pre>
* <complexType>
* <complexContent>
* <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
* <sequence>
* <element name="plugin" type="{http://maven.apache.org/POM/4.0.0}ReportPlugin" maxOccurs="unbounded" minOccurs="0"/>
* </sequence>
* </restriction>
* </complexContent>
* </complexType>
* </pre>
*
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "", propOrder = {
"plugin"
})
@Generated(value = "com.sun.tools.internal.xjc.Driver", date = "2012-11-09T12:33:57-05:00", comments = "JAXB RI vJAXB 2.1.10 in JDK 6")
public static class Plugins {
@Generated(value = "com.sun.tools.internal.xjc.Driver", date = "2012-11-09T12:33:57-05:00", comments = "JAXB RI vJAXB 2.1.10 in JDK 6")
protected List<ReportPlugin> plugin;
/**
* Gets the value of the plugin property.
*
* <p>
* This accessor method returns a reference to the live list,
* not a snapshot. Therefore any modification you make to the
* returned list will be present inside the JAXB object.
* This is why there is not a <CODE>set</CODE> method for the plugin property.
*
* <p>
* For example, to add a new item, do as follows:
* <pre>
* getPlugin().add(newItem);
* </pre>
*
*
* <p>
* Objects of the following type(s) are allowed in the list
* {@link ReportPlugin }
*
*
*/
@Generated(value = "com.sun.tools.internal.xjc.Driver", date = "2012-11-09T12:33:57-05:00", comments = "JAXB RI vJAXB 2.1.10 in JDK 6")
public List<ReportPlugin> getPlugin() {
if (plugin == null) {
plugin = new ArrayList<ReportPlugin>();
}
return this.plugin;
}
}
}
| apache-2.0 |
Deflaktor/Test | src/Foot.java | 617 | import java.awt.Graphics2D;
public class Foot extends Part {
private final int width = 48;
private final int height = 16;
public Foot() {
super();
this.originX = 24;
this.originY = 8;
}
@Override
public void paint(Graphics2D g) {
if (this.image != null) {
g.drawImage(this.image, this.x - this.originX, this.y - this.originY, this.width, this.height, null);
}
g.drawRoundRect(this.x - this.originX, this.y - this.originY, this.width, this.height, 5, 5);
}
@Override
public void update() {
// TODO Auto-generated method stub
}
}
| apache-2.0 |
adelapie/open-ecard-IRMA | common/src/main/java/org/openecard/common/ECardConstants.java | 10285 | /****************************************************************************
* Copyright (C) 2012 ecsec GmbH.
* All rights reserved.
* Contact: ecsec GmbH (info@ecsec.de)
*
* This file is part of the Open eCard App.
*
* GNU General Public License Usage
* This file may be used under the terms of the GNU General Public
* License version 3.0 as published by the Free Software Foundation
* and appearing in the file LICENSE.GPL included in the packaging of
* this file. Please review the following information to ensure the
* GNU General Public License version 3.0 requirements will be met:
* http://www.gnu.org/copyleft/gpl.html.
*
* Other Usage
* Alternatively, this file may be used in accordance with the terms
* and conditions contained in a signed written agreement between
* you and ecsec GmbH.
*
***************************************************************************/
package org.openecard.common;
import java.util.TreeMap;
/**
*
* @author Tobias Wich <tobias.wich@ecsec.de>
*/
public class ECardConstants {
private static final String ECARD_PREFIX = "http://www.bsi.bund.de/ecard/api/1.1/";
private static final String MAJOR_PREFIX = ECARD_PREFIX + "resultmajor#";
private static final String DSS_PREFIX = "urn:oasis:names:tc:dss:1.0:";
private static final String MINOR_PREFIX = ECARD_PREFIX + "resultminor/";
private static final String APP_PREFIX = MINOR_PREFIX + "al"; // Application Layer
private static final String DP_PREFIX = MINOR_PREFIX + "dp"; // Dispatcher
private static final String IL_PREFIX = MINOR_PREFIX + "il"; // Identity Layer
private static final String SAL_PREFIX = MINOR_PREFIX + "sal"; // Service Access Layer
private static final String IFD_PREFIX = MINOR_PREFIX + "ifdl"; // Interface Device Layer
//
// Inofficial Constants
//
public static final int CONTEXT_HANDLE_DEFAULT_SIZE = 16;
public static final int SLOT_HANDLE_DEFAULT_SIZE = 24;
public static final String UNKNOWN_CARD = "http://bsi.bund.de/cif/unknown";
public static final String PAOS_NEXT = ECARD_PREFIX + "PAOS/GetNextCommand";
public static final String ACTOR_NEXT = "http://schemas.xmlsoap.org/soap/actor/next";
public static final String SOAP_ENVELOPE = "http://schemas.xmlsoap.org/soap/envelope/";
public static final String PAOS_VERSION_11 = "urn:liberty:paos:2003-08";
public static final String PAOS_VERSION_20 = "urn:liberty:paos:2006-08";
public static final String WS_ADDRESSING = "http://www.w3.org/2005/03/addressing";
public static class CIF {
public static final String GET_SPECIFIED = ECARD_PREFIX + "cardinfo/action#getSpecifiedFile";
public static final String GET_RELATED = ECARD_PREFIX + "cardinfo/action#getRelatedFiles";
public static final String GET_OTHER = ECARD_PREFIX + "cardinfo/action#getOtherFiles";
};
public static class Profile {
public static final String ECSEC = "http://ws.ecsec.de";
public static final String ECARD_1_1 = "http://www.bsi.bund.de/ecard/api/1.1";
};
public static class Protocol {
public static final String PIN_COMPARE = "urn:oid:1.3.162.15480.3.0.9";
public static final String MUTUAL_AUTH = "urn:oid:1.3.162.15480.3.0.12";
public static final String EAC_GENERIC = "urn:oid:1.3.162.15480.3.0.14";
public static final String EAC2 = "urn:oid:1.3.162.15480.3.0.14.2";
public static final String RSA_AUTH = "urn:oid:1.3.162.15480.3.0.15";
public static final String GENERIC_CRYPTO = "urn:oid:1.3.162.15480.3.0.25";
public static final String TERMINAL_AUTH = "urn:oid:0.4.0.127.0.7.2.2.2";
public static final String CHIP_AUTH = "urn:oid:0.4.0.127.0.7.2.2.3";
public static final String PACE = "urn:oid:0.4.0.127.0.7.2.2.4";
public static final String RESTRICTED_ID = "urn:oid:0.4.0.127.0.7.2.2.5";
};
public static class IFD {
public static class Protocol {
public static final String T0 = "urn:iso:std:iso-iec:7816:-3:tech:protocols:T-equals-0";
public static final String T1 = "urn:iso:std:iso-iec:7816:-3:tech:protocols:T-equals-1";
public static final String T2 = "urn:iso:std:iso-iec:10536:tech:protocols:T-equals-2";
public static final String TYPE_A = "urn:iso:std:iso-iec:14443:-2:tech:protocols:Type-A";
public static final String TYPE_B = "urn:iso:std:iso-iec:14443:-2:tech:protocols:Type-B";
};
};
//
// Major values
//
public static class Major {
public static final String OK = MAJOR_PREFIX + "ok";
public static final String PENDING = DSS_PREFIX + "profiles:asynchronousprocessing:resultmajor:Pending";
public static final String WARN = MAJOR_PREFIX + "warning";
public static final String ERROR = MAJOR_PREFIX + "error";
public static final String NEXT = MAJOR_PREFIX + "nextRequest";
};
//
// Minor values
//
public static class Minor {
public static class App {
public static final String NO_PERM = APP_PREFIX + "/common#noPermission";
public static final String INT_ERROR = APP_PREFIX + "/common#internalError";
public static final String PARM_ERROR = APP_PREFIX + "/common#parameterError";
public static final String UNKNOWN_ERROR = APP_PREFIX + "/common#unknownError";
public static final String INCORRECT_PARM = APP_PREFIX + "/common#incorrectParameter";
};
public static class Disp {
public static final String INVALID_CHANNEL_HANDLE = DP_PREFIX + "#invalidChannelHandle";
};
public static class Ident {
private static final String IL_IS_PREFIX = IL_PREFIX + "il"; // Identity Layer - Identity Service
public static final String AUTH_FAIL = IL_IS_PREFIX + "#authenticationFailure";
public static final String UNKNOWN_POLICY = "unknownPolicyWarning";
public static final String UNKNOWN_ATTRIBUTE = "unknownAttributeWarning";
public static final String UNKNOWN_DEFAULT_URI = "unknownDefaultURIWarning";
public static class Sig {
};
public static class Enc {
};
};
public static class SAL {
public static final String UNKNOWN_HANDLE = SAL_PREFIX + "#unknownConnectionHandle";
public static final String UNKNOWN_CARDTYPE = SAL_PREFIX + "#unknownCardType";
public static final String PROTOCOL_NOT_RECOGNIZED = SAL_PREFIX + "#protocolNotRecognized";
public static final String INAPPROPRIATE_PROTOCOL_FOR_ACTION = SAL_PREFIX + "#inappropriateProtocolForAction";
public static final String REPO_UNREACHABLE = SAL_PREFIX + "/support#cardInfoRepositoryUnreachable";
public static final String SECURITY_CONDITINON_NOT_SATISFIED = SAL_PREFIX + "#securityConditionNotSatisfied";
public static final String NAMED_ENTITY_NOT_FOUND = SAL_PREFIX + "#namedEntityNotFound";
public static final String CANCELLATION_BY_USER = SAL_PREFIX + "#cancellationByUser";
public static final String INVALID_SIGNATURE = SAL_PREFIX + "#invalidSignature";
};
public static class IFD {
public static final String CANCELLATION_BY_USER = IFD_PREFIX + "#cancellationByUser";
public static final String INVALID_CONTEXT_HANDLE = IFD_PREFIX + "/common#invalidContextHandle";
public static final String INVALID_SLOT_HANDLE = IFD_PREFIX + "/common#invalidSlotHandle";
public static final String TIMEOUT_ERROR = IFD_PREFIX + "/common#timeoutError";
public static final String IFD_SHARING_VIOLATION = IFD_PREFIX + "/terminal#IFDSharingViolation";
public static final String NO_CARD = IFD_PREFIX + "/terminal#noCard";
public static final String UNKNOWN_ACTION = IFD_PREFIX + "/terminal#unknownAction";
public static final String UNKNOWN_IFD = IFD_PREFIX + "/terminal#unknownIFD";
public static final String UNKNOWN_SLOT = IFD_PREFIX + "/terminal#unknownSlot";
// Not yet specified by the BSI
public static final String PASSWORD_SUSPENDED = IFD_PREFIX + "/passwordSuspended";
public static final String PASSWORD_BLOCKED = IFD_PREFIX + "/passwordBlocked";
public static final String PASSWORD_ERROR = IFD_PREFIX + "/passwordError";
public static final String PASSWORD_DEACTIVATED = IFD_PREFIX + "/passwordDeactivated";
public static final String AUTHENTICATION_FAILED = IFD_PREFIX + "/authenticationFailed";
public static final String UNKNOWN_ERROR = IFD_PREFIX + "/unknownError";
public static class IO {
private static final String IO_PREFIX = IFD_PREFIX + "/IO";
public static final String NO_TRANSACTION_STARTED = IFD_PREFIX + "#noTransactionStarted";
public static final String UNKNOWN_DISPLAY_INDEX = IO_PREFIX + "#unknownDisplayIndex";
public static final String UNKNOWN_OUTPUT_DEVICE = IO_PREFIX + "#unknownOutputDevice";
public static final String UNKNOWN_INPUT_UNIT = IO_PREFIX + "#unknownInputUnit";
public static final String UNKNOWN_PIN_FORMAT = IO_PREFIX + "#unknownPINFormat";
public static final String CANCEL_NOT_POSSIBLE = IO_PREFIX + "#cancelNotPossible";
};
};
};
private static final TreeMap<String,String> msgMap = new TreeMap<String, String>();
static {
// major types
msgMap.put(Major.OK, "No error occurred during execution of the operation.");
msgMap.put(Major.WARN, "If the result of the operation is in principle OK, but there is a detail which may require closer investigation, a warning is given as a response.");
msgMap.put(Major.ERROR, "An error occurred during execution of the operation.");
msgMap.put(Major.NEXT, "This result appears if at least one more request is expected within a protocol.");
// minor App
// minor App common
msgMap.put(Minor.App.NO_PERM, "Use of the function by the client application is not permitted.");
msgMap.put(Minor.App.INT_ERROR, "Internal error.");
msgMap.put(Minor.App.PARM_ERROR, "There was some problem with a provided or omitted parameter.");
// minor SAL
msgMap.put(Minor.SAL.UNKNOWN_HANDLE, "Unknown connection handle specified.");
msgMap.put(Minor.SAL.UNKNOWN_CARDTYPE, "Unknown card type specified.");
// minor SAL support
msgMap.put(Minor.SAL.REPO_UNREACHABLE, "The CardInfo repository server is not accessible");
}
public static String URI2Msg(final String uri) {
String result = msgMap.get(uri);
return (result != null) ? result : "";
}
}
| apache-2.0 |
Reidddddd/mo-hadoop2.6.0 | hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/main/java/org/apache/hadoop/yarn/server/resourcemanager/scheduler/fair/FSAppAttempt.java | 29920 | /**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.hadoop.yarn.server.resourcemanager.scheduler.fair;
import java.io.Serializable;
import java.util.Arrays;
import java.util.Collection;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.hadoop.classification.InterfaceAudience.Private;
import org.apache.hadoop.classification.InterfaceStability.Unstable;
import org.apache.hadoop.yarn.api.records.ApplicationAttemptId;
import org.apache.hadoop.yarn.api.records.Container;
import org.apache.hadoop.yarn.api.records.ContainerId;
import org.apache.hadoop.yarn.api.records.ContainerStatus;
import org.apache.hadoop.yarn.api.records.NodeId;
import org.apache.hadoop.yarn.api.records.Priority;
import org.apache.hadoop.yarn.api.records.Resource;
import org.apache.hadoop.yarn.api.records.ResourceRequest;
import org.apache.hadoop.yarn.server.resourcemanager.RMAuditLogger;
import org.apache.hadoop.yarn.server.resourcemanager.RMAuditLogger.AuditConstants;
import org.apache.hadoop.yarn.server.resourcemanager.RMContext;
import org.apache.hadoop.yarn.server.resourcemanager.resource.ResourceWeights;
import org.apache.hadoop.yarn.server.resourcemanager.rmcontainer.RMContainer;
import org.apache.hadoop.yarn.server.resourcemanager.rmcontainer.RMContainerEvent;
import org.apache.hadoop.yarn.server.resourcemanager.rmcontainer.RMContainerEventType;
import org.apache.hadoop.yarn.server.resourcemanager.rmcontainer.RMContainerFinishedEvent;
import org.apache.hadoop.yarn.server.resourcemanager.rmcontainer.RMContainerImpl;
import org.apache.hadoop.yarn.server.resourcemanager.scheduler.ActiveUsersManager;
import org.apache.hadoop.yarn.server.resourcemanager.scheduler.NodeType;
import org.apache.hadoop.yarn.server.resourcemanager.scheduler.QueueMetrics;
import org.apache.hadoop.yarn.server.resourcemanager.scheduler.SchedulerApplicationAttempt;
import org.apache.hadoop.yarn.server.utils.BuilderUtils;
import org.apache.hadoop.yarn.util.resource.DefaultResourceCalculator;
import org.apache.hadoop.yarn.util.resource.Resources;
/**
* Represents an application attempt from the viewpoint of the Fair Scheduler.
*/
@Private
@Unstable
public class FSAppAttempt extends SchedulerApplicationAttempt
implements Schedulable {
private static final Log LOG = LogFactory.getLog(FSAppAttempt.class);
private static final DefaultResourceCalculator RESOURCE_CALCULATOR
= new DefaultResourceCalculator();
private long startTime;
private Priority priority;
private ResourceWeights resourceWeights;
private Resource demand = Resources.createResource(0);
private FairScheduler scheduler;
private Resource fairShare = Resources.createResource(0, 0);
private Resource preemptedResources = Resources.createResource(0);
private RMContainerComparator comparator = new RMContainerComparator();
private final Map<RMContainer, Long> preemptionMap = new HashMap<RMContainer, Long>();
/**
* Delay scheduling: We often want to prioritize scheduling of node-local
* containers over rack-local or off-switch containers. To acheive this
* we first only allow node-local assigments for a given prioirty level,
* then relax the locality threshold once we've had a long enough period
* without succesfully scheduling. We measure both the number of "missed"
* scheduling opportunities since the last container was scheduled
* at the current allowed level and the time since the last container
* was scheduled. Currently we use only the former.
*/
private final Map<Priority, NodeType> allowedLocalityLevel =
new HashMap<Priority, NodeType>();
public FSAppAttempt(FairScheduler scheduler,
ApplicationAttemptId applicationAttemptId, String user, FSLeafQueue queue,
ActiveUsersManager activeUsersManager, RMContext rmContext) {
super(applicationAttemptId, user, queue, activeUsersManager, rmContext);
this.scheduler = scheduler;
this.startTime = scheduler.getClock().getTime();
this.priority = Priority.newInstance(1);
this.resourceWeights = new ResourceWeights();
}
public ResourceWeights getResourceWeights() {
return resourceWeights;
}
/**
* Get metrics reference from containing queue.
*/
public QueueMetrics getMetrics() {
return queue.getMetrics();
}
synchronized public void containerCompleted(RMContainer rmContainer,
ContainerStatus containerStatus, RMContainerEventType event) {
Container container = rmContainer.getContainer();
ContainerId containerId = container.getId();
// Remove from the list of newly allocated containers if found
newlyAllocatedContainers.remove(rmContainer);
// Inform the container
rmContainer.handle(
new RMContainerFinishedEvent(
containerId,
containerStatus,
event)
);
LOG.info("Completed container: " + rmContainer.getContainerId() +
" in state: " + rmContainer.getState() + " event:" + event);
// Remove from the list of containers
if (liveContainers.remove(containerId) == null) {
LOG.info("Additional complete request on completed container " +
rmContainer.getContainerId());
return;
}
RMAuditLogger.logSuccess(getUser(),
AuditConstants.RELEASE_CONTAINER, "SchedulerApp",
getApplicationId(), containerId);
// Update usage metrics
Resource containerResource = rmContainer.getContainer().getResource();
queue.getMetrics().releaseResources(getUser(), 1, containerResource);
Resources.subtractFrom(currentConsumption, containerResource);
// remove from preemption map if it is completed
preemptionMap.remove(rmContainer);
// Clear resource utilization metrics cache.
lastMemoryAggregateAllocationUpdateTime = -1;
}
private synchronized void unreserveInternal(
Priority priority, FSSchedulerNode node) {
Map<NodeId, RMContainer> reservedContainers =
this.reservedContainers.get(priority);
RMContainer reservedContainer = reservedContainers.remove(node.getNodeID());
if (reservedContainers.isEmpty()) {
this.reservedContainers.remove(priority);
}
// Reset the re-reservation count
resetReReservations(priority);
Resource resource = reservedContainer.getContainer().getResource();
Resources.subtractFrom(currentReservation, resource);
LOG.info("Application " + getApplicationId() + " unreserved " + " on node "
+ node + ", currently has " + reservedContainers.size() + " at priority "
+ priority + "; currentReservation " + currentReservation);
}
@Override
public synchronized Resource getHeadroom() {
final FSQueue queue = (FSQueue) this.queue;
SchedulingPolicy policy = queue.getPolicy();
Resource queueFairShare = queue.getFairShare();
Resource queueUsage = queue.getResourceUsage();
Resource clusterResource = this.scheduler.getClusterResource();
Resource clusterUsage = this.scheduler.getRootQueueMetrics()
.getAllocatedResources();
Resource clusterAvailableResource = Resources.subtract(clusterResource,
clusterUsage);
Resource headroom = policy.getHeadroom(queueFairShare,
queueUsage, clusterAvailableResource);
if (LOG.isDebugEnabled()) {
LOG.debug("Headroom calculation for " + this.getName() + ":" +
"Min(" +
"(queueFairShare=" + queueFairShare +
" - queueUsage=" + queueUsage + ")," +
" clusterAvailableResource=" + clusterAvailableResource +
"(clusterResource=" + clusterResource +
" - clusterUsage=" + clusterUsage + ")" +
"Headroom=" + headroom);
}
return headroom;
}
public synchronized float getLocalityWaitFactor(
Priority priority, int clusterNodes) {
// Estimate: Required unique resources (i.e. hosts + racks)
int requiredResources =
Math.max(this.getResourceRequests(priority).size() - 1, 0);
// waitFactor can't be more than '1'
// i.e. no point skipping more than clustersize opportunities
return Math.min(((float)requiredResources / clusterNodes), 1.0f);
}
/**
* Return the level at which we are allowed to schedule containers, given the
* current size of the cluster and thresholds indicating how many nodes to
* fail at (as a fraction of cluster size) before relaxing scheduling
* constraints.
*/
public synchronized NodeType getAllowedLocalityLevel(Priority priority,
int numNodes, double nodeLocalityThreshold, double rackLocalityThreshold) {
// upper limit on threshold
if (nodeLocalityThreshold > 1.0) { nodeLocalityThreshold = 1.0; }
if (rackLocalityThreshold > 1.0) { rackLocalityThreshold = 1.0; }
// If delay scheduling is not being used, can schedule anywhere
if (nodeLocalityThreshold < 0.0 || rackLocalityThreshold < 0.0) {
return NodeType.OFF_SWITCH;
}
// Default level is NODE_LOCAL
if (!allowedLocalityLevel.containsKey(priority)) {
allowedLocalityLevel.put(priority, NodeType.NODE_LOCAL);
return NodeType.NODE_LOCAL;
}
NodeType allowed = allowedLocalityLevel.get(priority);
// If level is already most liberal, we're done
if (allowed.equals(NodeType.OFF_SWITCH)) return NodeType.OFF_SWITCH;
double threshold = allowed.equals(NodeType.NODE_LOCAL) ? nodeLocalityThreshold :
rackLocalityThreshold;
// Relax locality constraints once we've surpassed threshold.
if (getSchedulingOpportunities(priority) > (numNodes * threshold)) {
if (allowed.equals(NodeType.NODE_LOCAL)) {
allowedLocalityLevel.put(priority, NodeType.RACK_LOCAL);
resetSchedulingOpportunities(priority);
}
else if (allowed.equals(NodeType.RACK_LOCAL)) {
allowedLocalityLevel.put(priority, NodeType.OFF_SWITCH);
resetSchedulingOpportunities(priority);
}
}
return allowedLocalityLevel.get(priority);
}
/**
* Return the level at which we are allowed to schedule containers.
* Given the thresholds indicating how much time passed before relaxing
* scheduling constraints.
*/
public synchronized NodeType getAllowedLocalityLevelByTime(Priority priority,
long nodeLocalityDelayMs, long rackLocalityDelayMs,
long currentTimeMs) {
// if not being used, can schedule anywhere
if (nodeLocalityDelayMs < 0 || rackLocalityDelayMs < 0) {
return NodeType.OFF_SWITCH;
}
// default level is NODE_LOCAL
if (! allowedLocalityLevel.containsKey(priority)) {
allowedLocalityLevel.put(priority, NodeType.NODE_LOCAL);
return NodeType.NODE_LOCAL;
}
NodeType allowed = allowedLocalityLevel.get(priority);
// if level is already most liberal, we're done
if (allowed.equals(NodeType.OFF_SWITCH)) {
return NodeType.OFF_SWITCH;
}
// check waiting time
long waitTime = currentTimeMs;
if (lastScheduledContainer.containsKey(priority)) {
waitTime -= lastScheduledContainer.get(priority);
} else {
waitTime -= getStartTime();
}
long thresholdTime = allowed.equals(NodeType.NODE_LOCAL) ?
nodeLocalityDelayMs : rackLocalityDelayMs;
if (waitTime > thresholdTime) {
if (allowed.equals(NodeType.NODE_LOCAL)) {
allowedLocalityLevel.put(priority, NodeType.RACK_LOCAL);
resetSchedulingOpportunities(priority, currentTimeMs);
} else if (allowed.equals(NodeType.RACK_LOCAL)) {
allowedLocalityLevel.put(priority, NodeType.OFF_SWITCH);
resetSchedulingOpportunities(priority, currentTimeMs);
}
}
return allowedLocalityLevel.get(priority);
}
synchronized public RMContainer allocate(NodeType type, FSSchedulerNode node,
Priority priority, ResourceRequest request,
Container container) {
// Update allowed locality level
NodeType allowed = allowedLocalityLevel.get(priority);
if (allowed != null) {
if (allowed.equals(NodeType.OFF_SWITCH) &&
(type.equals(NodeType.NODE_LOCAL) ||
type.equals(NodeType.RACK_LOCAL))) {
this.resetAllowedLocalityLevel(priority, type);
}
else if (allowed.equals(NodeType.RACK_LOCAL) &&
type.equals(NodeType.NODE_LOCAL)) {
this.resetAllowedLocalityLevel(priority, type);
}
}
// Required sanity check - AM can call 'allocate' to update resource
// request without locking the scheduler, hence we need to check
if (getTotalRequiredResources(priority) <= 0) {
return null;
}
// Create RMContainer
RMContainer rmContainer = new RMContainerImpl(container,
getApplicationAttemptId(), node.getNodeID(),
appSchedulingInfo.getUser(), rmContext);
// Add it to allContainers list.
newlyAllocatedContainers.add(rmContainer);
liveContainers.put(container.getId(), rmContainer);
// Update consumption and track allocations
List<ResourceRequest> resourceRequestList = appSchedulingInfo.allocate(
type, node, priority, request, container);
Resources.addTo(currentConsumption, container.getResource());
// Update resource requests related to "request" and store in RMContainer
((RMContainerImpl) rmContainer).setResourceRequests(resourceRequestList);
// Inform the container
rmContainer.handle(
new RMContainerEvent(container.getId(), RMContainerEventType.START));
if (LOG.isDebugEnabled()) {
LOG.debug("allocate: applicationAttemptId="
+ container.getId().getApplicationAttemptId()
+ " container=" + container.getId() + " host="
+ container.getNodeId().getHost() + " type=" + type);
}
RMAuditLogger.logSuccess(getUser(),
AuditConstants.ALLOC_CONTAINER, "SchedulerApp",
getApplicationId(), container.getId());
return rmContainer;
}
/**
* Should be called when the scheduler assigns a container at a higher
* degree of locality than the current threshold. Reset the allowed locality
* level to a higher degree of locality.
*/
public synchronized void resetAllowedLocalityLevel(Priority priority,
NodeType level) {
NodeType old = allowedLocalityLevel.get(priority);
LOG.info("Raising locality level from " + old + " to " + level + " at " +
" priority " + priority);
allowedLocalityLevel.put(priority, level);
}
// related methods
public void addPreemption(RMContainer container, long time) {
assert preemptionMap.get(container) == null;
preemptionMap.put(container, time);
Resources.addTo(preemptedResources, container.getAllocatedResource());
}
public Long getContainerPreemptionTime(RMContainer container) {
return preemptionMap.get(container);
}
public Set<RMContainer> getPreemptionContainers() {
return preemptionMap.keySet();
}
@Override
public FSLeafQueue getQueue() {
return (FSLeafQueue)super.getQueue();
}
public Resource getPreemptedResources() {
return preemptedResources;
}
public void resetPreemptedResources() {
preemptedResources = Resources.createResource(0);
for (RMContainer container : getPreemptionContainers()) {
Resources.addTo(preemptedResources, container.getAllocatedResource());
}
}
public void clearPreemptedResources() {
preemptedResources.setMemory(0);
preemptedResources.setVirtualCores(0);
}
/**
* Create and return a container object reflecting an allocation for the
* given appliction on the given node with the given capability and
* priority.
*/
public Container createContainer(
FSSchedulerNode node, Resource capability, Priority priority) {
NodeId nodeId = node.getRMNode().getNodeID();
ContainerId containerId = BuilderUtils.newContainerId(
getApplicationAttemptId(), getNewContainerId());
// Create the container
Container container =
BuilderUtils.newContainer(containerId, nodeId, node.getRMNode()
.getHttpAddress(), capability, priority, null);
return container;
}
/**
* Reserve a spot for {@code container} on this {@code node}. If
* the container is {@code alreadyReserved} on the node, simply
* update relevant bookeeping. This dispatches ro relevant handlers
* in {@link FSSchedulerNode}..
*/
private void reserve(Priority priority, FSSchedulerNode node,
Container container, boolean alreadyReserved) {
LOG.info("Making reservation: node=" + node.getNodeName() +
" app_id=" + getApplicationId());
if (!alreadyReserved) {
getMetrics().reserveResource(getUser(), container.getResource());
RMContainer rmContainer =
super.reserve(node, priority, null, container);
node.reserveResource(this, priority, rmContainer);
} else {
RMContainer rmContainer = node.getReservedContainer();
super.reserve(node, priority, rmContainer, container);
node.reserveResource(this, priority, rmContainer);
}
}
/**
* Remove the reservation on {@code node} at the given {@link Priority}.
* This dispatches SchedulerNode handlers as well.
*/
public void unreserve(Priority priority, FSSchedulerNode node) {
RMContainer rmContainer = node.getReservedContainer();
unreserveInternal(priority, node);
node.unreserveResource(this);
getMetrics().unreserveResource(
getUser(), rmContainer.getContainer().getResource());
}
/**
* Assign a container to this node to facilitate {@code request}. If node does
* not have enough memory, create a reservation. This is called once we are
* sure the particular request should be facilitated by this node.
*
* @param node
* The node to try placing the container on.
* @param request
* The ResourceRequest we're trying to satisfy.
* @param type
* The locality of the assignment.
* @param reserved
* Whether there's already a container reserved for this app on the node.
* @return
* If an assignment was made, returns the resources allocated to the
* container. If a reservation was made, returns
* FairScheduler.CONTAINER_RESERVED. If no assignment or reservation was
* made, returns an empty resource.
*/
private Resource assignContainer(
FSSchedulerNode node, ResourceRequest request, NodeType type,
boolean reserved) {
// How much does this request need?
Resource capability = request.getCapability();
// How much does the node have?
Resource available = node.getAvailableResource();
Container container = null;
if (reserved) {
container = node.getReservedContainer().getContainer();
} else {
container = createContainer(node, capability, request.getPriority());
}
// Can we allocate a container on this node?
if (Resources.fitsIn(capability, available)) {
// Inform the application of the new container for this request
RMContainer allocatedContainer =
allocate(type, node, request.getPriority(), request, container);
if (allocatedContainer == null) {
// Did the application need this resource?
if (reserved) {
unreserve(request.getPriority(), node);
}
return Resources.none();
}
// If we had previously made a reservation, delete it
if (reserved) {
unreserve(request.getPriority(), node);
}
// Inform the node
node.allocateContainer(allocatedContainer);
// If not running unmanaged, the first container we allocate is
// always the AM. Set amResource for this app and
// Update the leaf queue's AM usage
if (!isAmRunning() && !getUnmanagedAM()) {
setAMResource(container.getResource());
getQueue().addAMResourceUsage(container.getResource());
setAmRunning(true);
}
return container.getResource();
} else {
// The desired container won't fit here, so reserve
reserve(request.getPriority(), node, container, reserved);
return FairScheduler.CONTAINER_RESERVED;
}
}
private Resource assignContainer(FSSchedulerNode node, boolean reserved) {
if (LOG.isDebugEnabled()) {
LOG.debug("Node offered to app: " + getName() + " reserved: " + reserved);
}
// Check the AM resource usage for the leaf queue
if (!isAmRunning() && !getUnmanagedAM()) {
List<ResourceRequest> ask = appSchedulingInfo.getAllResourceRequests();
if (ask.isEmpty() || !getQueue().canRunAppAM(
ask.get(0).getCapability())) {
if (LOG.isDebugEnabled()) {
LOG.debug("Skipping allocation because maxAMShare limit would " +
"be exceeded");
}
return Resources.none();
}
}
Collection<Priority> prioritiesToTry = (reserved) ?
Arrays.asList(node.getReservedContainer().getReservedPriority()) :
getPriorities();
// For each priority, see if we can schedule a node local, rack local
// or off-switch request. Rack of off-switch requests may be delayed
// (not scheduled) in order to promote better locality.
synchronized (this) {
for (Priority priority : prioritiesToTry) {
if (getTotalRequiredResources(priority) <= 0 ||
!hasContainerForNode(priority, node)) {
continue;
}
addSchedulingOpportunity(priority);
// Check the AM resource usage for the leaf queue
if (getLiveContainers().size() == 0 && !getUnmanagedAM()) {
if (!getQueue().canRunAppAM(getAMResource())) {
return Resources.none();
}
}
ResourceRequest rackLocalRequest = getResourceRequest(priority,
node.getRackName());
ResourceRequest localRequest = getResourceRequest(priority,
node.getNodeName());
if (localRequest != null && !localRequest.getRelaxLocality()) {
LOG.warn("Relax locality off is not supported on local request: "
+ localRequest);
}
NodeType allowedLocality;
if (scheduler.isContinuousSchedulingEnabled()) {
allowedLocality = getAllowedLocalityLevelByTime(priority,
scheduler.getNodeLocalityDelayMs(),
scheduler.getRackLocalityDelayMs(),
scheduler.getClock().getTime());
} else {
allowedLocality = getAllowedLocalityLevel(priority,
scheduler.getNumClusterNodes(),
scheduler.getNodeLocalityThreshold(),
scheduler.getRackLocalityThreshold());
}
if (rackLocalRequest != null && rackLocalRequest.getNumContainers() != 0
&& localRequest != null && localRequest.getNumContainers() != 0) {
return assignContainer(node, localRequest,
NodeType.NODE_LOCAL, reserved);
}
if (rackLocalRequest != null && !rackLocalRequest.getRelaxLocality()) {
continue;
}
if (rackLocalRequest != null && rackLocalRequest.getNumContainers() != 0
&& (allowedLocality.equals(NodeType.RACK_LOCAL) ||
allowedLocality.equals(NodeType.OFF_SWITCH))) {
return assignContainer(node, rackLocalRequest,
NodeType.RACK_LOCAL, reserved);
}
ResourceRequest offSwitchRequest =
getResourceRequest(priority, ResourceRequest.ANY);
if (offSwitchRequest != null && !offSwitchRequest.getRelaxLocality()) {
continue;
}
if (offSwitchRequest != null && offSwitchRequest.getNumContainers() != 0
&& allowedLocality.equals(NodeType.OFF_SWITCH)) {
return assignContainer(node, offSwitchRequest,
NodeType.OFF_SWITCH, reserved);
}
}
}
return Resources.none();
}
/**
* Called when this application already has an existing reservation on the
* given node. Sees whether we can turn the reservation into an allocation.
* Also checks whether the application needs the reservation anymore, and
* releases it if not.
*
* @param node
* Node that the application has an existing reservation on
*/
public Resource assignReservedContainer(FSSchedulerNode node) {
RMContainer rmContainer = node.getReservedContainer();
Priority priority = rmContainer.getReservedPriority();
// Make sure the application still needs requests at this priority
if (getTotalRequiredResources(priority) == 0) {
unreserve(priority, node);
return Resources.none();
}
// Fail early if the reserved container won't fit.
// Note that we have an assumption here that there's only one container size
// per priority.
if (!Resources.fitsIn(node.getReservedContainer().getReservedResource(),
node.getAvailableResource())) {
return Resources.none();
}
return assignContainer(node, true);
}
/**
* Whether this app has containers requests that could be satisfied on the
* given node, if the node had full space.
*/
public boolean hasContainerForNode(Priority prio, FSSchedulerNode node) {
ResourceRequest anyRequest = getResourceRequest(prio, ResourceRequest.ANY);
ResourceRequest rackRequest = getResourceRequest(prio, node.getRackName());
ResourceRequest nodeRequest = getResourceRequest(prio, node.getNodeName());
return
// There must be outstanding requests at the given priority:
anyRequest != null && anyRequest.getNumContainers() > 0 &&
// If locality relaxation is turned off at *-level, there must be a
// non-zero request for the node's rack:
(anyRequest.getRelaxLocality() ||
(rackRequest != null && rackRequest.getNumContainers() > 0)) &&
// If locality relaxation is turned off at rack-level, there must be a
// non-zero request at the node:
(rackRequest == null || rackRequest.getRelaxLocality() ||
(nodeRequest != null && nodeRequest.getNumContainers() > 0)) &&
// The requested container must be able to fit on the node:
Resources.lessThanOrEqual(RESOURCE_CALCULATOR, null,
anyRequest.getCapability(), node.getRMNode().getTotalCapability());
}
static class RMContainerComparator implements Comparator<RMContainer>,
Serializable {
@Override
public int compare(RMContainer c1, RMContainer c2) {
int ret = c1.getContainer().getPriority().compareTo(
c2.getContainer().getPriority());
if (ret == 0) {
return c2.getContainerId().compareTo(c1.getContainerId());
}
return ret;
}
}
/* Schedulable methods implementation */
@Override
public String getName() {
return getApplicationId().toString();
}
@Override
public Resource getDemand() {
return demand;
}
@Override
public long getStartTime() {
return startTime;
}
@Override
public Resource getMinShare() {
return Resources.none();
}
@Override
public Resource getMaxShare() {
return Resources.unbounded();
}
@Override
public Resource getResourceUsage() {
// Here the getPreemptedResources() always return zero, except in
// a preemption round
return Resources.subtract(getCurrentConsumption(), getPreemptedResources());
}
@Override
public ResourceWeights getWeights() {
return scheduler.getAppWeight(this);
}
@Override
public Priority getPriority() {
// Right now per-app priorities are not passed to scheduler,
// so everyone has the same priority.
return priority;
}
@Override
public Resource getFairShare() {
return this.fairShare;
}
@Override
public void setFairShare(Resource fairShare) {
this.fairShare = fairShare;
}
@Override
public void updateDemand() {
demand = Resources.createResource(0);
// Demand is current consumption plus outstanding requests
Resources.addTo(demand, getCurrentConsumption());
// Add up outstanding resource requests
synchronized (this) {
for (Priority p : getPriorities()) {
for (ResourceRequest r : getResourceRequests(p).values()) {
Resource total = Resources.multiply(r.getCapability(), r.getNumContainers());
Resources.addTo(demand, total);
}
}
}
}
@Override
public Resource assignContainer(FSSchedulerNode node) {
return assignContainer(node, false);
}
/**
* Preempt a running container according to the priority
*/
@Override
public RMContainer preemptContainer() {
if (LOG.isDebugEnabled()) {
LOG.debug("App " + getName() + " is going to preempt a running " +
"container");
}
RMContainer toBePreempted = null;
for (RMContainer container : getLiveContainers()) {
if (!getPreemptionContainers().contains(container) &&
(toBePreempted == null ||
comparator.compare(toBePreempted, container) > 0)) {
toBePreempted = container;
}
}
return toBePreempted;
}
}
| apache-2.0 |
Ravmouse/vvasilyev | chapter_001/src/test/java/ru/job4j/loop/package-info.java | 140 | /**
* Package for CounterTest Class.
* @author Vitaly Vasilyev (rav.energ@rambler.ru)
* @version $Id$
* @since 0.1
*/
package ru.job4j.loop; | apache-2.0 |
kireet/feedly-cassandra | src/main/java/com/feedly/cassandra/dao/EColumnFilterStrategy.java | 260 | package com.feedly.cassandra.dao;
enum EColumnFilterStrategy
{
/**
* retrieve all columns
*/
UNFILTERED,
/**
* retrieve a range of columns
*/
RANGE,
/**
* retrive a specific set of columns
*/
INCLUDES;
}
| apache-2.0 |
vincenzomazzeo/map-engine | src/main/java/it/alidays/mapengine/core/fetch/ForEachMethod.java | 1717 | /*
* Copyright 2015 Alidays S.p.A.
*
* 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 it.alidays.mapengine.core.fetch;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import org.dom4j.Element;
public class ForEachMethod implements ToEntityMethod {
private final String path;
private final Map<String, Binder> binderMap;
protected ForEachMethod(String path) {
this.path = path;
this.binderMap = new LinkedHashMap<>();
}
@Override
public List<Map<String, Object>> run(Element baseNode) {
List<Map<String, Object>> result = new ArrayList<>();
@SuppressWarnings("unchecked")
List<Element> nodes = baseNode.selectNodes(this.path);
for (Element node : nodes) {
Map<String, Object> tupla = new HashMap<>();
result.add(tupla);
for (String attribute : this.binderMap.keySet()) {
Binder binder = this.binderMap.get(attribute);
tupla.put(attribute, binder.bind(node));
}
}
return result;
}
protected void addBinder(String attribute, Binder binder) {
this.binderMap.put(attribute, binder);
}
}
| apache-2.0 |
sis-direct/spring-data-examples | mongodb/query-by-example/src/main/java/example/springdata/mongodb/querybyexample/package-info.java | 778 | /*
* Copyright 2016 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.
*/
/**
* Sample showing Query-by-Example related features of Spring Data MongoDB.
*
* @author Mark Paluch
*/
package example.springdata.mongodb.querybyexample;
| apache-2.0 |
saego/RepositBasic | Collections Pro/OrderBook/src/test/java/OrderTest.java | 995 | import org.hamcrest.core.Is;
import org.junit.Before;
import org.junit.Test;
import static org.hamcrest.core.Is.is;
import static org.junit.Assert.*;
/**
* Created by Saego on 03.10.2017.
*/
public class OrderTest {
private Order order;
@Before
public void setUp(){
this.order = new Order(new Book("Robinzon"), true, 12, 14);
}
@Test
public void getBook() throws Exception {
assertThat(this.order.getBook(), is(new Book("Robinzon")));
}
@Test
public void isOperation() throws Exception {
assertThat(this.order.isOperation(), is(true));
}
@Test
public void getPrice() throws Exception {
assertThat(this.order.getPrice(), is((float) 12));
}
@Test
public void getVolume() throws Exception {
assertThat(this.order.getVolume(), is(14));
}
@Test
public void setVolume() throws Exception {
order.setVolume(23);
assertThat(this.order.getVolume(), is(23));
}
} | apache-2.0 |
openwide-java/owsi-core-parent | owsi-core/owsi-core-components/owsi-core-component-wicket-more/src/main/java/fr/openwide/core/wicket/more/markup/repeater/table/builder/state/IAddedBootstrapBadgeColumnState.java | 2784 | package fr.openwide.core.wicket.more.markup.repeater.table.builder.state;
import org.apache.wicket.behavior.Behavior;
import org.apache.wicket.model.IModel;
import com.google.common.base.Function;
import fr.openwide.core.commons.util.binding.AbstractCoreBinding;
import fr.openwide.core.jpa.more.business.sort.ISort;
import fr.openwide.core.wicket.more.condition.Condition;
import fr.openwide.core.wicket.more.link.descriptor.generator.ILinkGenerator;
import fr.openwide.core.wicket.more.link.descriptor.mapper.ILinkDescriptorMapper;
import fr.openwide.core.wicket.more.markup.html.sort.ISortIconStyle;
import fr.openwide.core.wicket.more.markup.html.sort.TableSortLink.CycleMode;
public interface IAddedBootstrapBadgeColumnState<T, S extends ISort<?>, C> extends IAddedCoreColumnState<T, S> {
@Override
IAddedBootstrapBadgeColumnState<T, S, C> when(Condition condition);
@Override
IAddedBootstrapBadgeColumnState<T, S, C> withClass(String cssClass);
@Override
IAddedBootstrapBadgeColumnState<T, S, C> withSort(S sort);
@Override
IAddedBootstrapBadgeColumnState<T, S, C> withSort(S sort, ISortIconStyle sortIconStyle);
@Override
IAddedBootstrapBadgeColumnState<T, S, C> withSort(S sort, ISortIconStyle sortIconStyle, CycleMode cycleMode);
IAddedBootstrapBadgeColumnState<T, S, C> withLink(ILinkDescriptorMapper<? extends ILinkGenerator, ? super IModel<T>> linkGeneratorMapper);
<E> IAddedBootstrapBadgeColumnState<T, S, C> withLink(Function<? super T, E> binding, ILinkDescriptorMapper<? extends ILinkGenerator, ? super IModel<E>> linkGeneratorMapper);
<E> IAddedBootstrapBadgeColumnState<T, S, C> withLink(AbstractCoreBinding<? super T, E> binding, ILinkDescriptorMapper<? extends ILinkGenerator, ? super IModel<E>> linkGeneratorMapper);
IAddedBootstrapBadgeColumnState<T, S, C> withSideLink(ILinkDescriptorMapper<? extends ILinkGenerator, ? super IModel<T>> linkGeneratorMapper);
<E> IAddedBootstrapBadgeColumnState<T, S, C> withSideLink(Function<? super T, E> binding, ILinkDescriptorMapper<? extends ILinkGenerator, ? super IModel<E>> linkGeneratorMapper);
<E> IAddedBootstrapBadgeColumnState<T, S, C> withSideLink(AbstractCoreBinding<? super T, E> binding, ILinkDescriptorMapper<? extends ILinkGenerator, ? super IModel<E>> linkGeneratorMapper);
/**
* @deprecated This is the default behavior, so calling this method is generally useless. The method is here for
* compatibility reasons.
*/
@Deprecated
IAddedBootstrapBadgeColumnState<T, S, C> disableIfInvalid();
IAddedBootstrapBadgeColumnState<T, S, C> hideIfInvalid();
IAddedBootstrapBadgeColumnState<T, S, C> throwExceptionIfInvalid();
IAddedBootstrapBadgeColumnState<T, S, C> linkBehavior(Behavior linkBehavior);
IAddedBootstrapBadgeColumnState<T, S, C> targetBlank();
}
| apache-2.0 |
MER-GROUP/intellij-community | java/typeMigration/test/com/intellij/refactoring/ChangeTypeSignatureTest.java | 4329 | /*
* User: anna
* Date: 18-Mar-2008
*/
package com.intellij.refactoring;
import com.intellij.psi.*;
import com.intellij.psi.impl.source.PsiImmediateClassType;
import com.intellij.psi.search.GlobalSearchScope;
import com.intellij.psi.util.PsiTreeUtil;
import com.intellij.refactoring.typeMigration.TypeMigrationLabeler;
import com.intellij.refactoring.typeMigration.TypeMigrationProcessor;
import com.intellij.refactoring.typeMigration.TypeMigrationRules;
import com.intellij.testFramework.LightCodeInsightTestCase;
import com.intellij.testFramework.PlatformTestUtil;
import org.jetbrains.annotations.NotNull;
public class ChangeTypeSignatureTest extends LightCodeInsightTestCase {
@NotNull
@Override
protected String getTestDataPath() {
return PlatformTestUtil.getCommunityPath() + "/java/typeMigration/testData";
}
private void doTest(boolean success, String migrationTypeText) throws Exception {
String dataPath = "/refactoring/changeTypeSignature/";
configureByFile(dataPath + getTestName(false) + ".java");
final PsiFile file = getFile();
final PsiElement element = file.findElementAt(getEditor().getCaretModel().getOffset());
final PsiReferenceParameterList parameterList = PsiTreeUtil.getParentOfType(element, PsiReferenceParameterList.class);
assert parameterList != null;
final PsiClass superClass = (PsiClass)((PsiJavaCodeReferenceElement)parameterList.getParent()).resolve();
assert superClass != null;
PsiType migrationType = getJavaFacade().getElementFactory().createTypeFromText(migrationTypeText, null);
try {
final TypeMigrationRules rules = new TypeMigrationRules();
rules.setBoundScope(GlobalSearchScope.projectScope(getProject()));
new TypeMigrationProcessor(getProject(),
parameterList,
PsiSubstitutor.EMPTY.put(superClass.getTypeParameters()[0], migrationType).substitute(new PsiImmediateClassType(superClass, PsiSubstitutor.EMPTY)),
rules).run();
if (success) {
checkResultByFile(dataPath + getTestName(false) + ".java.after");
} else {
fail("Conflicts should be detected");
}
}
catch (RuntimeException e) {
if (success) {
e.printStackTrace();
fail("Conflicts should not appear");
}
}
}
private void doTest(boolean success) throws Exception {
doTest(success, CommonClassNames.JAVA_LANG_OBJECT);
}
public void testListTypeArguments() throws Exception {
doTest(true);
}
public void testFieldUsage() throws Exception {
doTest(true);
}
public void testFieldUsage1() throws Exception {
doTest(true);
}
public void testReturnType() throws Exception {
doTest(true);
}
public void testReturnType1() throws Exception {
doTest(true);
}
public void testReturnType2() throws Exception {
doTest(true);
}
public void testPassedParameter() throws Exception {
doTest(true);
}
public void testPassedParameter1() throws Exception {
doTest(true, "java.lang.Integer");
}
public void testPassedParameter2() throws Exception {
doTest(true);
}
public void testUsedInSuper() throws Exception {
doTest(true);
}
public void testCompositeReturnType() throws Exception {
doTest(true);
}
public void testTypeHierarchy() throws Exception {
doTest(true);
}
public void testTypeHierarchy1() throws Exception {
doTest(true);
}
public void testTypeHierarchy2() throws Exception {
doTest(true);
}
public void testTypeHierarchyFieldUsage() throws Exception {
doTest(true);
}
public void testTypeHierarchyFieldUsageConflict() throws Exception {
doTest(true);
}
public void testParameterMigration() throws Exception {
doTest(true);
}
public void testParameterMigration1() throws Exception {
doTest(true, "java.lang.Integer");
}
public void testParameterMigration2() throws Exception {
doTest(true, "java.lang.Integer");
}
public void testFieldTypeMigration() throws Exception {
doTest(true, "java.lang.String");
}
public void testMethodReturnTypeMigration() throws Exception {
doTest(true, "java.lang.Integer");
}
@Override
protected boolean isRunInWriteAction() {
return false;
}
} | apache-2.0 |
gianm/druid | extensions-core/druid-basic-security/src/main/java/org/apache/druid/security/basic/authorization/db/updater/CoordinatorBasicAuthorizerMetadataStorageUpdater.java | 46081 | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.druid.security.basic.authorization.db.updater;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.common.base.Preconditions;
import com.google.common.collect.Lists;
import com.google.inject.Inject;
import org.apache.druid.common.config.ConfigManager;
import org.apache.druid.concurrent.LifecycleLock;
import org.apache.druid.guice.ManageLifecycle;
import org.apache.druid.guice.annotations.Smile;
import org.apache.druid.java.util.common.ISE;
import org.apache.druid.java.util.common.StringUtils;
import org.apache.druid.java.util.common.concurrent.Execs;
import org.apache.druid.java.util.common.concurrent.ScheduledExecutors;
import org.apache.druid.java.util.common.lifecycle.LifecycleStart;
import org.apache.druid.java.util.common.lifecycle.LifecycleStop;
import org.apache.druid.java.util.emitter.EmittingLogger;
import org.apache.druid.metadata.MetadataCASUpdate;
import org.apache.druid.metadata.MetadataStorageConnector;
import org.apache.druid.metadata.MetadataStorageTablesConfig;
import org.apache.druid.security.basic.BasicAuthCommonCacheConfig;
import org.apache.druid.security.basic.BasicAuthDBConfig;
import org.apache.druid.security.basic.BasicAuthUtils;
import org.apache.druid.security.basic.BasicSecurityDBResourceException;
import org.apache.druid.security.basic.authorization.BasicRoleBasedAuthorizer;
import org.apache.druid.security.basic.authorization.db.cache.BasicAuthorizerCacheNotifier;
import org.apache.druid.security.basic.authorization.entity.BasicAuthorizerGroupMapping;
import org.apache.druid.security.basic.authorization.entity.BasicAuthorizerGroupMappingMapBundle;
import org.apache.druid.security.basic.authorization.entity.BasicAuthorizerPermission;
import org.apache.druid.security.basic.authorization.entity.BasicAuthorizerRole;
import org.apache.druid.security.basic.authorization.entity.BasicAuthorizerRoleMapBundle;
import org.apache.druid.security.basic.authorization.entity.BasicAuthorizerUser;
import org.apache.druid.security.basic.authorization.entity.BasicAuthorizerUserMapBundle;
import org.apache.druid.security.basic.authorization.entity.GroupMappingAndRoleMap;
import org.apache.druid.security.basic.authorization.entity.UserAndRoleMap;
import org.apache.druid.server.security.Action;
import org.apache.druid.server.security.Authorizer;
import org.apache.druid.server.security.AuthorizerMapper;
import org.apache.druid.server.security.Resource;
import org.apache.druid.server.security.ResourceAction;
import org.apache.druid.server.security.ResourceType;
import org.joda.time.Duration;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ThreadLocalRandom;
import java.util.concurrent.TimeUnit;
@ManageLifecycle
public class CoordinatorBasicAuthorizerMetadataStorageUpdater implements BasicAuthorizerMetadataStorageUpdater
{
private static final EmittingLogger LOG =
new EmittingLogger(CoordinatorBasicAuthorizerMetadataStorageUpdater.class);
private static final long UPDATE_RETRY_DELAY = 1000;
private static final String USERS = "users";
private static final String GROUP_MAPPINGS = "groupMappings";
private static final String ROLES = "roles";
public static final List<ResourceAction> SUPERUSER_PERMISSIONS = makeSuperUserPermissions();
private final AuthorizerMapper authorizerMapper;
private final MetadataStorageConnector connector;
private final MetadataStorageTablesConfig connectorConfig;
private final BasicAuthorizerCacheNotifier cacheNotifier;
private final BasicAuthCommonCacheConfig commonCacheConfig;
private final ObjectMapper objectMapper;
private final int numRetries = 5;
private final Map<String, BasicAuthorizerUserMapBundle> cachedUserMaps;
private final Map<String, BasicAuthorizerGroupMappingMapBundle> cachedGroupMappingMaps;
private final Map<String, BasicAuthorizerRoleMapBundle> cachedRoleMaps;
private final Set<String> authorizerNames;
private final LifecycleLock lifecycleLock = new LifecycleLock();
private final ScheduledExecutorService exec;
private volatile boolean stopped = false;
@Inject
public CoordinatorBasicAuthorizerMetadataStorageUpdater(
AuthorizerMapper authorizerMapper,
MetadataStorageConnector connector,
MetadataStorageTablesConfig connectorConfig,
BasicAuthCommonCacheConfig commonCacheConfig,
@Smile ObjectMapper objectMapper,
BasicAuthorizerCacheNotifier cacheNotifier,
ConfigManager configManager // -V6022: ConfigManager creates the db table we need, set a dependency here
)
{
this.exec = Execs.scheduledSingleThreaded("CoordinatorBasicAuthorizerMetadataStorageUpdater-Exec--%d");
this.authorizerMapper = authorizerMapper;
this.connector = connector;
this.connectorConfig = connectorConfig;
this.commonCacheConfig = commonCacheConfig;
this.objectMapper = objectMapper;
this.cacheNotifier = cacheNotifier;
this.cachedUserMaps = new ConcurrentHashMap<>();
this.cachedGroupMappingMaps = new ConcurrentHashMap<>();
this.cachedRoleMaps = new ConcurrentHashMap<>();
this.authorizerNames = new HashSet<>();
}
@LifecycleStart
public void start()
{
if (!lifecycleLock.canStart()) {
throw new ISE("can't start.");
}
if (authorizerMapper == null || authorizerMapper.getAuthorizerMap() == null) {
return;
}
try {
LOG.info("Starting CoordinatorBasicAuthorizerMetadataStorageUpdater");
BasicAuthUtils.maybeInitialize(
() -> {
for (Map.Entry<String, Authorizer> entry : authorizerMapper.getAuthorizerMap().entrySet()) {
Authorizer authorizer = entry.getValue();
if (authorizer instanceof BasicRoleBasedAuthorizer) {
BasicRoleBasedAuthorizer basicRoleBasedAuthorizer = (BasicRoleBasedAuthorizer) authorizer;
BasicAuthDBConfig dbConfig = basicRoleBasedAuthorizer.getDbConfig();
String authorizerName = entry.getKey();
authorizerNames.add(authorizerName);
byte[] userMapBytes = getCurrentUserMapBytes(authorizerName);
Map<String, BasicAuthorizerUser> userMap = BasicAuthUtils.deserializeAuthorizerUserMap(
objectMapper,
userMapBytes
);
cachedUserMaps.put(authorizerName, new BasicAuthorizerUserMapBundle(userMap, userMapBytes));
byte[] groupMappingMapBytes = getCurrentGroupMappingMapBytes(authorizerName);
Map<String, BasicAuthorizerGroupMapping> groupMappingMap = BasicAuthUtils.deserializeAuthorizerGroupMappingMap(
objectMapper,
groupMappingMapBytes
);
cachedGroupMappingMaps.put(
authorizerName,
new BasicAuthorizerGroupMappingMapBundle(
groupMappingMap,
groupMappingMapBytes
)
);
byte[] roleMapBytes = getCurrentRoleMapBytes(authorizerName);
Map<String, BasicAuthorizerRole> roleMap = BasicAuthUtils.deserializeAuthorizerRoleMap(
objectMapper,
roleMapBytes
);
cachedRoleMaps.put(authorizerName, new BasicAuthorizerRoleMapBundle(roleMap, roleMapBytes));
initSuperUsersAndGroupMapping(authorizerName, userMap, roleMap, groupMappingMap,
dbConfig.getInitialAdminUser(),
dbConfig.getInitialAdminRole(),
dbConfig.getInitialAdminGroupMapping()
);
}
}
return true;
});
ScheduledExecutors.scheduleWithFixedDelay(
exec,
new Duration(commonCacheConfig.getPollingPeriod()),
new Duration(commonCacheConfig.getPollingPeriod()),
() -> {
if (stopped) {
return ScheduledExecutors.Signal.STOP;
}
try {
LOG.debug("Scheduled db poll is running");
for (String authorizerName : authorizerNames) {
byte[] userMapBytes = getCurrentUserMapBytes(authorizerName);
Map<String, BasicAuthorizerUser> userMap = BasicAuthUtils.deserializeAuthorizerUserMap(
objectMapper,
userMapBytes
);
if (userMapBytes != null) {
synchronized (cachedUserMaps) {
cachedUserMaps.put(authorizerName, new BasicAuthorizerUserMapBundle(userMap, userMapBytes));
}
}
byte[] groupMappingMapBytes = getCurrentGroupMappingMapBytes(authorizerName);
Map<String, BasicAuthorizerGroupMapping> groupMappingMap = BasicAuthUtils.deserializeAuthorizerGroupMappingMap(
objectMapper,
groupMappingMapBytes
);
if (groupMappingMapBytes != null) {
synchronized (cachedGroupMappingMaps) {
cachedGroupMappingMaps.put(authorizerName, new BasicAuthorizerGroupMappingMapBundle(groupMappingMap, groupMappingMapBytes));
}
}
byte[] roleMapBytes = getCurrentRoleMapBytes(authorizerName);
Map<String, BasicAuthorizerRole> roleMap = BasicAuthUtils.deserializeAuthorizerRoleMap(
objectMapper,
roleMapBytes
);
if (roleMapBytes != null) {
synchronized (cachedRoleMaps) {
cachedRoleMaps.put(authorizerName, new BasicAuthorizerRoleMapBundle(roleMap, roleMapBytes));
}
}
}
LOG.debug("Scheduled db poll is done");
}
catch (Throwable t) {
LOG.makeAlert(t, "Error occured while polling for cachedUserMaps, cachedGroupMappingMaps, cachedRoleMaps.").emit();
}
return ScheduledExecutors.Signal.REPEAT;
}
);
lifecycleLock.started();
}
finally {
lifecycleLock.exitStart();
}
}
@LifecycleStop
public void stop()
{
if (!lifecycleLock.canStop()) {
throw new ISE("can't stop.");
}
LOG.info("CoordinatorBasicAuthorizerMetadataStorageUpdater is stopping.");
stopped = true;
LOG.info("CoordinatorBasicAuthorizerMetadataStorageUpdater is stopped.");
}
private static String getPrefixedKeyColumn(String keyPrefix, String keyName)
{
return StringUtils.format("basic_authorization_%s_%s", keyPrefix, keyName);
}
private boolean tryUpdateUserMap(
String prefix,
Map<String, BasicAuthorizerUser> userMap,
byte[] oldUserMapValue,
byte[] newUserMapValue
)
{
try {
List<MetadataCASUpdate> updates = new ArrayList<>();
if (userMap != null) {
updates.add(
createMetadataCASUpdate(prefix, oldUserMapValue, newUserMapValue, USERS)
);
boolean succeeded = connector.compareAndSwap(updates);
if (succeeded) {
cachedUserMaps.put(prefix, new BasicAuthorizerUserMapBundle(userMap, newUserMapValue));
byte[] serializedUserAndRoleMap = getCurrentUserAndRoleMapSerialized(prefix);
cacheNotifier.addUpdateUser(prefix, serializedUserAndRoleMap);
return true;
} else {
return false;
}
}
return false;
}
catch (Exception e) {
throw new RuntimeException(e);
}
}
private boolean tryUpdateGroupMappingMap(
String prefix,
Map<String, BasicAuthorizerGroupMapping> groupMappingMap,
byte[] oldGroupMappingMapValue,
byte[] newGroupMappingMapValue
)
{
try {
List<MetadataCASUpdate> updates = new ArrayList<>();
if (groupMappingMap != null) {
updates.add(
createMetadataCASUpdate(prefix, oldGroupMappingMapValue, newGroupMappingMapValue, GROUP_MAPPINGS)
);
boolean succeeded = connector.compareAndSwap(updates);
if (succeeded) {
cachedGroupMappingMaps.put(prefix,
new BasicAuthorizerGroupMappingMapBundle(
groupMappingMap,
newGroupMappingMapValue
)
);
byte[] serializedGroupMappingAndRoleMap = getCurrentGroupMappingAndRoleMapSerialized(prefix);
cacheNotifier.addUpdateGroupMapping(prefix, serializedGroupMappingAndRoleMap);
return true;
} else {
return false;
}
}
return false;
}
catch (Exception e) {
throw new RuntimeException(e);
}
}
private boolean tryUpdateRoleMap(
String prefix,
Map<String, BasicAuthorizerRole> roleMap,
byte[] oldRoleMapValue,
byte[] newRoleMapValue
)
{
try {
List<MetadataCASUpdate> updates = new ArrayList<>();
if (roleMap != null) {
updates.add(
createMetadataCASUpdate(prefix, oldRoleMapValue, newRoleMapValue, ROLES)
);
boolean succeeded = connector.compareAndSwap(updates);
if (succeeded) {
cachedRoleMaps.put(prefix, new BasicAuthorizerRoleMapBundle(roleMap, newRoleMapValue));
byte[] serializedUserAndRoleMap = getCurrentUserAndRoleMapSerialized(prefix);
cacheNotifier.addUpdateUser(prefix, serializedUserAndRoleMap);
byte[] serializedGroupMappingAndRoleMap = getCurrentGroupMappingAndRoleMapSerialized(prefix);
cacheNotifier.addUpdateGroupMapping(prefix, serializedGroupMappingAndRoleMap);
return true;
} else {
return false;
}
}
return false;
}
catch (Exception e) {
throw new RuntimeException(e);
}
}
private boolean tryUpdateUserAndRoleMap(
String prefix,
Map<String, BasicAuthorizerUser> userMap,
byte[] oldUserMapValue,
byte[] newUserMapValue,
Map<String, BasicAuthorizerRole> roleMap,
byte[] oldRoleMapValue,
byte[] newRoleMapValue
)
{
try {
List<MetadataCASUpdate> updates = new ArrayList<>();
if (userMap != null && roleMap != null) {
updates.add(
createMetadataCASUpdate(prefix, oldUserMapValue, newUserMapValue, USERS)
);
updates.add(
createMetadataCASUpdate(prefix, oldRoleMapValue, newRoleMapValue, ROLES)
);
boolean succeeded = connector.compareAndSwap(updates);
if (succeeded) {
cachedUserMaps.put(prefix, new BasicAuthorizerUserMapBundle(userMap, newUserMapValue));
cachedRoleMaps.put(prefix, new BasicAuthorizerRoleMapBundle(roleMap, newRoleMapValue));
byte[] serializedUserAndRoleMap = getCurrentUserAndRoleMapSerialized(prefix);
cacheNotifier.addUpdateUser(prefix, serializedUserAndRoleMap);
return true;
} else {
return false;
}
}
}
catch (Exception e) {
throw new RuntimeException(e);
}
return false;
}
private boolean tryUpdateGroupMappingAndRoleMap(
String prefix,
Map<String, BasicAuthorizerGroupMapping> groupMappingMap,
byte[] oldGroupMappingMapValue,
byte[] newGroupMappingMapValue,
Map<String, BasicAuthorizerRole> roleMap,
byte[] oldRoleMapValue,
byte[] newRoleMapValue
)
{
try {
List<MetadataCASUpdate> updates = new ArrayList<>();
if (groupMappingMap != null && roleMap != null) {
updates.add(
createMetadataCASUpdate(prefix, oldGroupMappingMapValue, newGroupMappingMapValue, GROUP_MAPPINGS)
);
updates.add(
createMetadataCASUpdate(prefix, oldRoleMapValue, newRoleMapValue, ROLES)
);
}
boolean succeeded = connector.compareAndSwap(updates);
if (succeeded) {
cachedGroupMappingMaps.put(prefix, new BasicAuthorizerGroupMappingMapBundle(groupMappingMap, newGroupMappingMapValue));
cachedRoleMaps.put(prefix, new BasicAuthorizerRoleMapBundle(roleMap, newRoleMapValue));
byte[] serializedGroupMappingAndRoleMap = getCurrentGroupMappingAndRoleMapSerialized(prefix);
cacheNotifier.addUpdateGroupMapping(prefix, serializedGroupMappingAndRoleMap);
return true;
} else {
return false;
}
}
catch (Exception e) {
throw new RuntimeException(e);
}
}
@Nonnull
private MetadataCASUpdate createMetadataCASUpdate(
String prefix,
byte[] oldValue,
byte[] newValue,
String columnName
)
{
return new MetadataCASUpdate(
connectorConfig.getConfigTable(),
MetadataStorageConnector.CONFIG_TABLE_KEY_COLUMN,
MetadataStorageConnector.CONFIG_TABLE_VALUE_COLUMN,
getPrefixedKeyColumn(prefix, columnName),
oldValue,
newValue
);
}
@Override
public void createUser(String prefix, String userName)
{
Preconditions.checkState(lifecycleLock.awaitStarted(1, TimeUnit.MILLISECONDS));
createUserInternal(prefix, userName);
}
@Override
public void deleteUser(String prefix, String userName)
{
Preconditions.checkState(lifecycleLock.awaitStarted(1, TimeUnit.MILLISECONDS));
deleteUserInternal(prefix, userName);
}
@Override
public void createGroupMapping(String prefix, BasicAuthorizerGroupMapping groupMapping)
{
Preconditions.checkState(lifecycleLock.awaitStarted(1, TimeUnit.MILLISECONDS));
createGroupMappingInternal(prefix, groupMapping);
}
@Override
public void deleteGroupMapping(String prefix, String groupMappingName)
{
Preconditions.checkState(lifecycleLock.awaitStarted(1, TimeUnit.MILLISECONDS));
deleteGroupMappingInternal(prefix, groupMappingName);
}
@Override
public void createRole(String prefix, String roleName)
{
Preconditions.checkState(lifecycleLock.awaitStarted(1, TimeUnit.MILLISECONDS));
createRoleInternal(prefix, roleName);
}
@Override
public void deleteRole(String prefix, String roleName)
{
Preconditions.checkState(lifecycleLock.awaitStarted(1, TimeUnit.MILLISECONDS));
deleteRoleInternal(prefix, roleName);
}
@Override
public void assignUserRole(String prefix, String userName, String roleName)
{
Preconditions.checkState(lifecycleLock.awaitStarted(1, TimeUnit.MILLISECONDS));
assignUserRoleInternal(prefix, userName, roleName);
}
@Override
public void unassignUserRole(String prefix, String userName, String roleName)
{
Preconditions.checkState(lifecycleLock.awaitStarted(1, TimeUnit.MILLISECONDS));
unassignUserRoleInternal(prefix, userName, roleName);
}
@Override
public void assignGroupMappingRole(String prefix, String groupMappingName, String roleName)
{
Preconditions.checkState(lifecycleLock.awaitStarted(1, TimeUnit.MILLISECONDS));
assignGroupMappingRoleInternal(prefix, groupMappingName, roleName);
}
@Override
public void unassignGroupMappingRole(String prefix, String groupMappingName, String roleName)
{
Preconditions.checkState(lifecycleLock.awaitStarted(1, TimeUnit.MILLISECONDS));
unassignGroupMappingRoleInternal(prefix, groupMappingName, roleName);
}
@Override
public void setPermissions(String prefix, String roleName, List<ResourceAction> permissions)
{
Preconditions.checkState(lifecycleLock.awaitStarted(1, TimeUnit.MILLISECONDS));
setPermissionsInternal(prefix, roleName, permissions);
}
@Override
@Nullable
public Map<String, BasicAuthorizerUser> getCachedUserMap(String prefix)
{
BasicAuthorizerUserMapBundle userMapBundle = cachedUserMaps.get(prefix);
return userMapBundle == null ? null : userMapBundle.getUserMap();
}
@Override
public Map<String, BasicAuthorizerGroupMapping> getCachedGroupMappingMap(String prefix)
{
BasicAuthorizerGroupMappingMapBundle groupMapBundle = cachedGroupMappingMaps.get(prefix);
return groupMapBundle == null ? null : groupMapBundle.getGroupMappingMap();
}
@Override
@Nullable
public Map<String, BasicAuthorizerRole> getCachedRoleMap(String prefix)
{
BasicAuthorizerRoleMapBundle roleMapBundle = cachedRoleMaps.get(prefix);
return roleMapBundle == null ? null : roleMapBundle.getRoleMap();
}
@Override
public byte[] getCurrentUserMapBytes(String prefix)
{
return connector.lookup(
connectorConfig.getConfigTable(),
MetadataStorageConnector.CONFIG_TABLE_KEY_COLUMN,
MetadataStorageConnector.CONFIG_TABLE_VALUE_COLUMN,
getPrefixedKeyColumn(prefix, USERS)
);
}
@Override
public byte[] getCurrentGroupMappingMapBytes(String prefix)
{
return connector.lookup(
connectorConfig.getConfigTable(),
MetadataStorageConnector.CONFIG_TABLE_KEY_COLUMN,
MetadataStorageConnector.CONFIG_TABLE_VALUE_COLUMN,
getPrefixedKeyColumn(prefix, GROUP_MAPPINGS)
);
}
@Override
public byte[] getCurrentRoleMapBytes(String prefix)
{
return connector.lookup(
connectorConfig.getConfigTable(),
MetadataStorageConnector.CONFIG_TABLE_KEY_COLUMN,
MetadataStorageConnector.CONFIG_TABLE_VALUE_COLUMN,
getPrefixedKeyColumn(prefix, ROLES)
);
}
@Override
public void refreshAllNotification()
{
authorizerNames.forEach(
(authorizerName) -> {
try {
byte[] serializedUserAndRoleMap = getCurrentUserAndRoleMapSerialized(authorizerName);
cacheNotifier.addUpdateUser(authorizerName, serializedUserAndRoleMap);
byte[] serializeGroupAndRoleMap = getCurrentGroupMappingAndRoleMapSerialized(authorizerName);
cacheNotifier.addUpdateGroupMapping(authorizerName, serializeGroupAndRoleMap);
}
catch (IOException ioe) {
throw new RuntimeException(ioe);
}
}
);
}
private byte[] getCurrentUserAndRoleMapSerialized(String prefix) throws IOException
{
BasicAuthorizerUserMapBundle userMapBundle = cachedUserMaps.get(prefix);
BasicAuthorizerRoleMapBundle roleMapBundle = cachedRoleMaps.get(prefix);
UserAndRoleMap userAndRoleMap = new UserAndRoleMap(
userMapBundle == null ? null : userMapBundle.getUserMap(),
roleMapBundle == null ? null : roleMapBundle.getRoleMap()
);
return objectMapper.writeValueAsBytes(userAndRoleMap);
}
private byte[] getCurrentGroupMappingAndRoleMapSerialized(String prefix) throws IOException
{
BasicAuthorizerGroupMappingMapBundle groupMappingMapBundle = cachedGroupMappingMaps.get(prefix);
BasicAuthorizerRoleMapBundle roleMapBundle = cachedRoleMaps.get(prefix);
GroupMappingAndRoleMap groupMappingAndRoleMap = new GroupMappingAndRoleMap(
groupMappingMapBundle == null ? null : groupMappingMapBundle.getGroupMappingMap(),
roleMapBundle == null ? null : roleMapBundle.getRoleMap()
);
return objectMapper.writeValueAsBytes(groupMappingAndRoleMap);
}
private void createUserInternal(String prefix, String userName)
{
int attempts = 0;
while (attempts < numRetries) {
if (createUserOnce(prefix, userName)) {
return;
} else {
attempts++;
}
try {
Thread.sleep(ThreadLocalRandom.current().nextLong(UPDATE_RETRY_DELAY));
}
catch (InterruptedException ie) {
throw new RuntimeException(ie);
}
}
throw new ISE("Could not create user [%s] due to concurrent update contention.", userName);
}
private void deleteUserInternal(String prefix, String userName)
{
int attempts = 0;
while (attempts < numRetries) {
if (deleteUserOnce(prefix, userName)) {
return;
} else {
attempts++;
}
try {
Thread.sleep(ThreadLocalRandom.current().nextLong(UPDATE_RETRY_DELAY));
}
catch (InterruptedException ie) {
throw new RuntimeException(ie);
}
}
throw new ISE("Could not delete user [%s] due to concurrent update contention.", userName);
}
private void createGroupMappingInternal(String prefix, BasicAuthorizerGroupMapping groupMapping)
{
int attempts = 0;
while (attempts < numRetries) {
if (createGroupMappingOnce(prefix, groupMapping)) {
return;
} else {
attempts++;
}
try {
Thread.sleep(ThreadLocalRandom.current().nextLong(UPDATE_RETRY_DELAY));
}
catch (InterruptedException ie) {
throw new RuntimeException(ie);
}
}
throw new ISE("Could not create group mapping [%s] due to concurrent update contention.", groupMapping);
}
private void deleteGroupMappingInternal(String prefix, String groupMappingName)
{
int attempts = 0;
while (attempts < numRetries) {
if (deleteGroupMappingOnce(prefix, groupMappingName)) {
return;
} else {
attempts++;
}
try {
Thread.sleep(ThreadLocalRandom.current().nextLong(UPDATE_RETRY_DELAY));
}
catch (InterruptedException ie) {
throw new RuntimeException(ie);
}
}
throw new ISE("Could not delete group mapping [%s] due to concurrent update contention.", groupMappingName);
}
private void createRoleInternal(String prefix, String roleName)
{
int attempts = 0;
while (attempts < numRetries) {
if (createRoleOnce(prefix, roleName)) {
return;
} else {
attempts++;
}
try {
Thread.sleep(ThreadLocalRandom.current().nextLong(UPDATE_RETRY_DELAY));
}
catch (InterruptedException ie) {
throw new RuntimeException(ie);
}
}
throw new ISE("Could not create role [%s] due to concurrent update contention.", roleName);
}
private void deleteRoleInternal(String prefix, String roleName)
{
int attempts = 0;
while (attempts < numRetries) {
if (deleteRoleOnce(prefix, roleName)) {
return;
} else {
attempts++;
}
try {
Thread.sleep(ThreadLocalRandom.current().nextLong(UPDATE_RETRY_DELAY));
}
catch (InterruptedException ie) {
throw new RuntimeException(ie);
}
}
throw new ISE("Could not delete role [%s] due to concurrent update contention.", roleName);
}
private void assignUserRoleInternal(String prefix, String userName, String roleName)
{
int attempts = 0;
while (attempts < numRetries) {
if (assignUserRoleOnce(prefix, userName, roleName)) {
return;
} else {
attempts++;
}
try {
Thread.sleep(ThreadLocalRandom.current().nextLong(UPDATE_RETRY_DELAY));
}
catch (InterruptedException ie) {
throw new RuntimeException(ie);
}
}
throw new ISE("Could not assign role [%s] to user [%s] due to concurrent update contention.", roleName, userName);
}
private void unassignUserRoleInternal(String prefix, String userName, String roleName)
{
int attempts = 0;
while (attempts < numRetries) {
if (unassignUserRoleOnce(prefix, userName, roleName)) {
return;
} else {
attempts++;
}
try {
Thread.sleep(ThreadLocalRandom.current().nextLong(UPDATE_RETRY_DELAY));
}
catch (InterruptedException ie) {
throw new RuntimeException(ie);
}
}
throw new ISE("Could not unassign role [%s] from user [%s] due to concurrent update contention.", roleName, userName);
}
private void assignGroupMappingRoleInternal(String prefix, String groupMappingName, String roleName)
{
int attempts = 0;
while (attempts < numRetries) {
if (assignGroupMappingRoleOnce(prefix, groupMappingName, roleName)) {
return;
} else {
attempts++;
}
try {
Thread.sleep(ThreadLocalRandom.current().nextLong(UPDATE_RETRY_DELAY));
}
catch (InterruptedException ie) {
throw new RuntimeException(ie);
}
}
throw new ISE("Could not assign role [%s] to group mapping [%s] due to concurrent update contention.",
roleName,
groupMappingName
);
}
private void unassignGroupMappingRoleInternal(String prefix, String groupMappingName, String roleName)
{
int attempts = 0;
while (attempts < numRetries) {
if (unassignGroupMappingRoleOnce(prefix, groupMappingName, roleName)) {
return;
} else {
attempts++;
}
try {
Thread.sleep(ThreadLocalRandom.current().nextLong(UPDATE_RETRY_DELAY));
}
catch (InterruptedException ie) {
throw new RuntimeException(ie);
}
}
throw new ISE("Could not unassign role [%s] from group mapping [%s] due to concurrent update contention.", roleName,
groupMappingName
);
}
private void setPermissionsInternal(String prefix, String roleName, List<ResourceAction> permissions)
{
int attempts = 0;
while (attempts < numRetries) {
if (setPermissionsOnce(prefix, roleName, permissions)) {
return;
} else {
attempts++;
}
try {
Thread.sleep(ThreadLocalRandom.current().nextLong(UPDATE_RETRY_DELAY));
}
catch (InterruptedException ie) {
throw new RuntimeException(ie);
}
}
throw new ISE("Could not set permissions for role [%s] due to concurrent update contention.", roleName);
}
private boolean deleteUserOnce(String prefix, String userName)
{
byte[] oldValue = getCurrentUserMapBytes(prefix);
Map<String, BasicAuthorizerUser> userMap = BasicAuthUtils.deserializeAuthorizerUserMap(objectMapper, oldValue);
if (userMap.get(userName) == null) {
throw new BasicSecurityDBResourceException("User [%s] does not exist.", userName);
} else {
userMap.remove(userName);
}
byte[] newValue = BasicAuthUtils.serializeAuthorizerUserMap(objectMapper, userMap);
return tryUpdateUserMap(prefix, userMap, oldValue, newValue);
}
private boolean createUserOnce(String prefix, String userName)
{
byte[] oldValue = getCurrentUserMapBytes(prefix);
Map<String, BasicAuthorizerUser> userMap = BasicAuthUtils.deserializeAuthorizerUserMap(objectMapper, oldValue);
if (userMap.get(userName) != null) {
throw new BasicSecurityDBResourceException("User [%s] already exists.", userName);
} else {
userMap.put(userName, new BasicAuthorizerUser(userName, null));
}
byte[] newValue = BasicAuthUtils.serializeAuthorizerUserMap(objectMapper, userMap);
return tryUpdateUserMap(prefix, userMap, oldValue, newValue);
}
private boolean deleteGroupMappingOnce(String prefix, String groupMappingName)
{
byte[] oldValue = getCurrentGroupMappingMapBytes(prefix);
Map<String, BasicAuthorizerGroupMapping> groupMappingMap = BasicAuthUtils.deserializeAuthorizerGroupMappingMap(objectMapper, oldValue);
if (groupMappingMap.get(groupMappingName) == null) {
throw new BasicSecurityDBResourceException("Group mapping [%s] does not exist.", groupMappingName);
} else {
groupMappingMap.remove(groupMappingName);
}
byte[] newValue = BasicAuthUtils.serializeAuthorizerGroupMappingMap(objectMapper, groupMappingMap);
return tryUpdateGroupMappingMap(prefix, groupMappingMap, oldValue, newValue);
}
private boolean createGroupMappingOnce(String prefix, BasicAuthorizerGroupMapping groupMapping)
{
byte[] oldValue = getCurrentGroupMappingMapBytes(prefix);
Map<String, BasicAuthorizerGroupMapping> groupMappingMap = BasicAuthUtils.deserializeAuthorizerGroupMappingMap(objectMapper, oldValue);
if (groupMappingMap.get(groupMapping.getName()) != null) {
throw new BasicSecurityDBResourceException("Group mapping [%s] already exists.", groupMapping.getName());
} else {
groupMappingMap.put(groupMapping.getName(), groupMapping);
}
byte[] newValue = BasicAuthUtils.serializeAuthorizerGroupMappingMap(objectMapper, groupMappingMap);
return tryUpdateGroupMappingMap(prefix, groupMappingMap, oldValue, newValue);
}
private boolean createRoleOnce(String prefix, String roleName)
{
byte[] oldValue = getCurrentRoleMapBytes(prefix);
Map<String, BasicAuthorizerRole> roleMap = BasicAuthUtils.deserializeAuthorizerRoleMap(objectMapper, oldValue);
if (roleMap.get(roleName) != null) {
throw new BasicSecurityDBResourceException("Role [%s] already exists.", roleName);
} else {
roleMap.put(roleName, new BasicAuthorizerRole(roleName, null));
}
byte[] newValue = BasicAuthUtils.serializeAuthorizerRoleMap(objectMapper, roleMap);
return tryUpdateRoleMap(prefix, roleMap, oldValue, newValue);
}
private boolean deleteRoleOnce(String prefix, String roleName)
{
byte[] oldRoleMapValue = getCurrentRoleMapBytes(prefix);
Map<String, BasicAuthorizerRole> roleMap = BasicAuthUtils.deserializeAuthorizerRoleMap(
objectMapper,
oldRoleMapValue
);
if (roleMap.get(roleName) == null) {
throw new BasicSecurityDBResourceException("Role [%s] does not exist.", roleName);
} else {
roleMap.remove(roleName);
}
byte[] oldUserMapValue = getCurrentUserMapBytes(prefix);
Map<String, BasicAuthorizerUser> userMap = BasicAuthUtils.deserializeAuthorizerUserMap(
objectMapper,
oldUserMapValue
);
for (BasicAuthorizerUser user : userMap.values()) {
user.getRoles().remove(roleName);
}
byte[] newUserMapValue = BasicAuthUtils.serializeAuthorizerUserMap(objectMapper, userMap);
byte[] oldGroupMapValue = getCurrentGroupMappingMapBytes(prefix);
Map<String, BasicAuthorizerGroupMapping> groupMap = BasicAuthUtils.deserializeAuthorizerGroupMappingMap(
objectMapper,
oldGroupMapValue
);
for (BasicAuthorizerGroupMapping group : groupMap.values()) {
group.getRoles().remove(roleName);
}
byte[] newGroupMapValue = BasicAuthUtils.serializeAuthorizerGroupMappingMap(objectMapper, groupMap);
byte[] newRoleMapValue = BasicAuthUtils.serializeAuthorizerRoleMap(objectMapper, roleMap);
return tryUpdateUserAndRoleMap(
prefix,
userMap, oldUserMapValue, newUserMapValue,
roleMap, oldRoleMapValue, newRoleMapValue
) && tryUpdateGroupMappingAndRoleMap(
prefix,
groupMap, oldGroupMapValue, newGroupMapValue,
roleMap, newRoleMapValue, newRoleMapValue
);
}
private boolean assignUserRoleOnce(String prefix, String userName, String roleName)
{
byte[] oldRoleMapValue = getCurrentRoleMapBytes(prefix);
Map<String, BasicAuthorizerRole> roleMap = BasicAuthUtils.deserializeAuthorizerRoleMap(
objectMapper,
oldRoleMapValue
);
if (roleMap.get(roleName) == null) {
throw new BasicSecurityDBResourceException("Role [%s] does not exist.", roleName);
}
byte[] oldUserMapValue = getCurrentUserMapBytes(prefix);
Map<String, BasicAuthorizerUser> userMap = BasicAuthUtils.deserializeAuthorizerUserMap(
objectMapper,
oldUserMapValue
);
BasicAuthorizerUser user = userMap.get(userName);
if (userMap.get(userName) == null) {
throw new BasicSecurityDBResourceException("User [%s] does not exist.", userName);
}
if (user.getRoles().contains(roleName)) {
throw new BasicSecurityDBResourceException("User [%s] already has role [%s].", userName, roleName);
}
user.getRoles().add(roleName);
byte[] newUserMapValue = BasicAuthUtils.serializeAuthorizerUserMap(objectMapper, userMap);
// Role map is unchanged, but submit as an update to ensure that the table didn't change (e.g., role deleted)
return tryUpdateUserAndRoleMap(
prefix,
userMap, oldUserMapValue, newUserMapValue,
roleMap, oldRoleMapValue, oldRoleMapValue
);
}
private boolean unassignUserRoleOnce(String prefix, String userName, String roleName)
{
byte[] oldRoleMapValue = getCurrentRoleMapBytes(prefix);
Map<String, BasicAuthorizerRole> roleMap = BasicAuthUtils.deserializeAuthorizerRoleMap(
objectMapper,
oldRoleMapValue
);
if (roleMap.get(roleName) == null) {
throw new BasicSecurityDBResourceException("Role [%s] does not exist.", roleName);
}
byte[] oldUserMapValue = getCurrentUserMapBytes(prefix);
Map<String, BasicAuthorizerUser> userMap = BasicAuthUtils.deserializeAuthorizerUserMap(
objectMapper,
oldUserMapValue
);
BasicAuthorizerUser user = userMap.get(userName);
if (userMap.get(userName) == null) {
throw new BasicSecurityDBResourceException("User [%s] does not exist.", userName);
}
if (!user.getRoles().contains(roleName)) {
throw new BasicSecurityDBResourceException("User [%s] does not have role [%s].", userName, roleName);
}
user.getRoles().remove(roleName);
byte[] newUserMapValue = BasicAuthUtils.serializeAuthorizerUserMap(objectMapper, userMap);
// Role map is unchanged, but submit as an update to ensure that the table didn't change (e.g., role deleted)
return tryUpdateUserAndRoleMap(
prefix,
userMap, oldUserMapValue, newUserMapValue,
roleMap, oldRoleMapValue, oldRoleMapValue
);
}
private boolean assignGroupMappingRoleOnce(String prefix, String groupMappingName, String roleName)
{
byte[] oldRoleMapValue = getCurrentRoleMapBytes(prefix);
Map<String, BasicAuthorizerRole> roleMap = BasicAuthUtils.deserializeAuthorizerRoleMap(
objectMapper,
oldRoleMapValue
);
if (roleMap.get(roleName) == null) {
throw new BasicSecurityDBResourceException("Role [%s] does not exist.", roleName);
}
byte[] oldGroupMappingMapValue = getCurrentGroupMappingMapBytes(prefix);
Map<String, BasicAuthorizerGroupMapping> groupMappingMap = BasicAuthUtils.deserializeAuthorizerGroupMappingMap(
objectMapper,
oldGroupMappingMapValue
);
BasicAuthorizerGroupMapping groupMapping = groupMappingMap.get(groupMappingName);
if (groupMappingMap.get(groupMappingName) == null) {
throw new BasicSecurityDBResourceException("Group mapping [%s] does not exist.", groupMappingName);
}
if (groupMapping.getRoles().contains(roleName)) {
throw new BasicSecurityDBResourceException("Group mapping [%s] already has role [%s].", groupMappingName, roleName);
}
groupMapping.getRoles().add(roleName);
byte[] newGroupMapValue = BasicAuthUtils.serializeAuthorizerGroupMappingMap(objectMapper, groupMappingMap);
// Role map is unchanged, but submit as an update to ensure that the table didn't change (e.g., role deleted)
return tryUpdateGroupMappingAndRoleMap(
prefix,
groupMappingMap, oldGroupMappingMapValue, newGroupMapValue,
roleMap, oldRoleMapValue, oldRoleMapValue
);
}
private boolean unassignGroupMappingRoleOnce(String prefix, String groupMappingName, String roleName)
{
byte[] oldRoleMapValue = getCurrentRoleMapBytes(prefix);
Map<String, BasicAuthorizerRole> roleMap = BasicAuthUtils.deserializeAuthorizerRoleMap(
objectMapper,
oldRoleMapValue
);
if (roleMap.get(roleName) == null) {
throw new BasicSecurityDBResourceException("Role [%s] does not exist.", roleName);
}
byte[] oldGroupMappingMapValue = getCurrentGroupMappingMapBytes(prefix);
Map<String, BasicAuthorizerGroupMapping> groupMappingMap = BasicAuthUtils.deserializeAuthorizerGroupMappingMap(
objectMapper,
oldGroupMappingMapValue
);
BasicAuthorizerGroupMapping groupMapping = groupMappingMap.get(groupMappingName);
if (groupMappingMap.get(groupMappingName) == null) {
throw new BasicSecurityDBResourceException("Group mapping [%s] does not exist.", groupMappingName);
}
if (!groupMapping.getRoles().contains(roleName)) {
throw new BasicSecurityDBResourceException("Group mapping [%s] does not have role [%s].", groupMappingName, roleName);
}
groupMapping.getRoles().remove(roleName);
byte[] newGroupMapValue = BasicAuthUtils.serializeAuthorizerGroupMappingMap(objectMapper, groupMappingMap);
// Role map is unchanged, but submit as an update to ensure that the table didn't change (e.g., role deleted)
return tryUpdateGroupMappingAndRoleMap(
prefix,
groupMappingMap, oldGroupMappingMapValue, newGroupMapValue,
roleMap, oldRoleMapValue, oldRoleMapValue
);
}
private boolean setPermissionsOnce(String prefix, String roleName, List<ResourceAction> permissions)
{
byte[] oldRoleMapValue = getCurrentRoleMapBytes(prefix);
Map<String, BasicAuthorizerRole> roleMap = BasicAuthUtils.deserializeAuthorizerRoleMap(
objectMapper,
oldRoleMapValue
);
if (roleMap.get(roleName) == null) {
throw new BasicSecurityDBResourceException("Role [%s] does not exist.", roleName);
}
roleMap.put(
roleName,
new BasicAuthorizerRole(roleName, BasicAuthorizerPermission.makePermissionList(permissions))
);
byte[] newRoleMapValue = BasicAuthUtils.serializeAuthorizerRoleMap(objectMapper, roleMap);
return tryUpdateRoleMap(prefix, roleMap, oldRoleMapValue, newRoleMapValue);
}
private void initSuperUsersAndGroupMapping(
String authorizerName,
Map<String, BasicAuthorizerUser> userMap,
Map<String, BasicAuthorizerRole> roleMap,
Map<String, BasicAuthorizerGroupMapping> groupMappingMap,
String initialAdminUser,
String initialAdminRole,
String initialAdminGroupMapping
)
{
if (!roleMap.containsKey(BasicAuthUtils.ADMIN_NAME)) {
createRoleInternal(authorizerName, BasicAuthUtils.ADMIN_NAME);
setPermissionsInternal(authorizerName, BasicAuthUtils.ADMIN_NAME, SUPERUSER_PERMISSIONS);
}
if (!roleMap.containsKey(BasicAuthUtils.INTERNAL_USER_NAME)) {
createRoleInternal(authorizerName, BasicAuthUtils.INTERNAL_USER_NAME);
setPermissionsInternal(authorizerName, BasicAuthUtils.INTERNAL_USER_NAME, SUPERUSER_PERMISSIONS);
}
if (!userMap.containsKey(BasicAuthUtils.ADMIN_NAME)) {
createUserInternal(authorizerName, BasicAuthUtils.ADMIN_NAME);
assignUserRoleInternal(authorizerName, BasicAuthUtils.ADMIN_NAME, BasicAuthUtils.ADMIN_NAME);
}
if (!userMap.containsKey(BasicAuthUtils.INTERNAL_USER_NAME)) {
createUserInternal(authorizerName, BasicAuthUtils.INTERNAL_USER_NAME);
assignUserRoleInternal(authorizerName, BasicAuthUtils.INTERNAL_USER_NAME, BasicAuthUtils.INTERNAL_USER_NAME);
}
if (initialAdminRole != null
&& !(initialAdminRole.equals(BasicAuthUtils.ADMIN_NAME) || initialAdminRole.equals(BasicAuthUtils.INTERNAL_USER_NAME))
&& !roleMap.containsKey(initialAdminRole)) {
createRoleInternal(authorizerName, initialAdminRole);
setPermissionsInternal(authorizerName, initialAdminRole, SUPERUSER_PERMISSIONS);
}
if (initialAdminUser != null
&& !(initialAdminUser.equals(BasicAuthUtils.ADMIN_NAME) || initialAdminUser.equals(BasicAuthUtils.INTERNAL_USER_NAME))
&& !userMap.containsKey(initialAdminUser)) {
createUserInternal(authorizerName, initialAdminUser);
assignUserRoleInternal(authorizerName, initialAdminUser, initialAdminRole == null ? BasicAuthUtils.ADMIN_NAME : initialAdminRole);
}
if (initialAdminGroupMapping != null && !groupMappingMap.containsKey(BasicAuthUtils.ADMIN_GROUP_MAPPING_NAME)) {
BasicAuthorizerGroupMapping groupMapping =
new BasicAuthorizerGroupMapping(
BasicAuthUtils.ADMIN_GROUP_MAPPING_NAME,
initialAdminGroupMapping,
new HashSet<>(Collections.singletonList(initialAdminRole == null ? BasicAuthUtils.ADMIN_NAME : initialAdminRole))
);
createGroupMappingInternal(authorizerName, groupMapping);
}
}
private static List<ResourceAction> makeSuperUserPermissions()
{
ResourceAction datasourceR = new ResourceAction(
new Resource(".*", ResourceType.DATASOURCE),
Action.READ
);
ResourceAction datasourceW = new ResourceAction(
new Resource(".*", ResourceType.DATASOURCE),
Action.WRITE
);
ResourceAction configR = new ResourceAction(
new Resource(".*", ResourceType.CONFIG),
Action.READ
);
ResourceAction configW = new ResourceAction(
new Resource(".*", ResourceType.CONFIG),
Action.WRITE
);
ResourceAction stateR = new ResourceAction(
new Resource(".*", ResourceType.STATE),
Action.READ
);
ResourceAction stateW = new ResourceAction(
new Resource(".*", ResourceType.STATE),
Action.WRITE
);
return Lists.newArrayList(datasourceR, datasourceW, configR, configW, stateR, stateW);
}
}
| apache-2.0 |
TKnudsen/timeSeries | src/main/java/com/github/TKnudsen/timeseries/operations/io/json/timeSeries/JSONIOTimeSeriesTester.java | 3865 | package com.github.TKnudsen.timeseries.operations.io.json.timeSeries;
import java.util.Date;
import com.github.TKnudsen.timeseries.data.ITimeSeries;
import com.github.TKnudsen.timeseries.data.dataGeneration.TimeSeriesGenerator;
import com.github.TKnudsen.timeseries.data.multivariate.ITimeSeriesMultivariate;
import com.github.TKnudsen.timeseries.data.multivariate.TimeSeriesMultivariateLabeledWithEventsIntervalsAndDurations;
import com.github.TKnudsen.timeseries.data.primitives.TimeDuration;
import com.github.TKnudsen.timeseries.data.primitives.TimeInterval;
import com.github.TKnudsen.timeseries.data.primitives.TimeQuantization;
import com.github.TKnudsen.timeseries.data.univariate.ITimeSeriesUnivariate;
import com.github.TKnudsen.timeseries.operations.tools.DateTools;
/**
* <p>
* Title: JSONIOTester
* </p>
*
* <p>
* Description: tests JSON output-inout.
* </p>
*
* <p>
* Copyright: Copyright (c) 2017
* </p>
*
* @author Juergen Bernard
* @version 1.0
*/
public class JSONIOTimeSeriesTester {
public static void main(String[] args) {
// create dummy time series
Date startDate = DateTools.createDate(2016, 4, 3, 2, 1, 0, 0);
Date endDate = DateTools.createDate(2016, 4, 3, 3, 1, 0, 0);
TimeDuration quantization = new TimeDuration(TimeQuantization.MINUTES, 10);
ITimeSeriesUnivariate timeSeries = TimeSeriesGenerator.generateSyntheticTimeSeriesUnivariate(startDate.getTime(), endDate.getTime(), quantization, true);
System.out.println(timeSeries);
// write
String file = "ts.json";
String create = JSONTimeSeriesWriter.writeToString(timeSeries);
JSONTimeSeriesWriter.writeToFile(timeSeries, file);
System.out.println(create);
// load
ITimeSeriesUnivariate loadConfigsFromString = JSONTimeSeriesLoader.loadFromString(create);
System.out.println(loadConfigsFromString);
ITimeSeriesUnivariate loadConfigsFromFile = JSONTimeSeriesLoader.loadConfigsFromFile(file);
System.out.println(loadConfigsFromFile);
Date startDateMV = DateTools.createDate(2016, 4, 3, 2, 1, 0, 0);
Date endDateMV = DateTools.createDate(2016, 4, 3, 3, 1, 0, 0);
TimeDuration quantizationMV = new TimeDuration(TimeQuantization.MINUTES, 10);
ITimeSeries timeSeriesMV = TimeSeriesGenerator.generateSyntheticTimeSeriesMultivariate(startDateMV.getTime(), endDateMV.getTime(), 10, quantizationMV, true);
TimeSeriesMultivariateLabeledWithEventsIntervalsAndDurations TSML = new TimeSeriesMultivariateLabeledWithEventsIntervalsAndDurations((ITimeSeriesMultivariate) timeSeriesMV);
TSML.addEventLabel(0, "TestEvent");
TSML.addTimeIntervalLabel(new TimeInterval(0, 5), "TestTimeInterval");
System.out.println(TSML);
System.out.println(TSML.getAttributeName(0));
System.out.println(TSML.getEventLabels());
System.out.println(TSML.getIntervalLabels());
// write
String fileMV = "ts.json";
String createMV = JSONTimeSeriesWriter.writeToString(TSML);
JSONTimeSeriesWriter.writeToFile(TSML, fileMV);
System.out.println(createMV);
// load
TimeSeriesMultivariateLabeledWithEventsIntervalsAndDurations loadConfigsFromStringMV = JSONTimeSeriesLoader.loadTSMVLabeledFromString(createMV);
System.out.println(loadConfigsFromStringMV);
TimeSeriesMultivariateLabeledWithEventsIntervalsAndDurations loadConfigsFromFileMV = JSONTimeSeriesLoader.loadTSMVLabeledFromFile(fileMV);
System.out.println(loadConfigsFromFileMV);
System.out.println(loadConfigsFromStringMV.getAttributeName(0));
System.out.println(loadConfigsFromStringMV.getEventLabels());
System.out.println(loadConfigsFromStringMV.getIntervalLabels());
System.out.println(loadConfigsFromFileMV.getAttributeName(0));
System.out.println(loadConfigsFromFileMV.getEventLabels());
System.out.println(loadConfigsFromFileMV.getIntervalLabels());
}
}
| apache-2.0 |
Top-Q/jsystem | jsystem-core-projects/jsystemApp/src/main/java/jsystem/treeui/RunnerCmd.java | 3887 | /*
* Copyright 2005-2010 Ignis Software Tools Ltd. All rights reserved.
*/
package jsystem.treeui;
import java.io.File;
import java.util.Date;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
/**
* @author Michael Oziransky
*/
public class RunnerCmd {
private String alias;
private String projectPath;
private String sutFile;
private String scenarioFile;
private boolean saveRunProperties;
private Date schedule;
private int repetition;
private boolean dependOnPrevious;
private boolean freezeOnFail;
private boolean stopSuiteExecution;
private boolean stopEntireExecution;
public RunnerCmd() {
repetition = 0;
dependOnPrevious = false;
saveRunProperties = false;
freezeOnFail = false;
schedule = null;
alias = "";
}
public String toString() {
return alias;
}
public String getProjectPath() {
return projectPath;
}
public void setProjectPath(String projectPath) {
this.projectPath = projectPath;
}
public String getSutFile() {
return sutFile;
}
public String getSutFullPath() {
File file = new File(projectPath + "/" + sutFile);
return file.getAbsolutePath();
}
public String getSutName() {
return (new File(sutFile).getName());
}
public void setSutFile(String sutFile) {
this.sutFile = sutFile;
}
public String getScenarioFile() {
return scenarioFile;
}
public String getScenarioName() {
return scenarioFile.split("\\.")[0];
}
public void setScenarioFile(String scenarioFile) {
this.scenarioFile = scenarioFile;
}
public boolean isSaveRunProperties() {
return saveRunProperties;
}
public void setSaveRunProperties(boolean saveRunProperties) {
this.saveRunProperties = saveRunProperties;
}
public Date getSchedule() {
return schedule;
}
public void setSchedule(Date schedule) {
this.schedule = schedule;
}
public int getRepetition() {
return repetition;
}
public void setRepetition(int repetition) {
this.repetition = repetition;
}
public boolean isDependOnPrevious() {
return dependOnPrevious;
}
public void setDependOnPrevious(boolean dependOnPrevious) {
this.dependOnPrevious = dependOnPrevious;
}
public boolean isFreezeOnFail() {
return freezeOnFail;
}
public void setFreezeOnFail(boolean freezeOnFail) {
this.freezeOnFail = freezeOnFail;
}
public boolean isStopSuiteExecution() {
return stopSuiteExecution;
}
public void setStopSuiteExecution(boolean stopExecution) {
this.stopSuiteExecution = stopExecution;
}
public boolean isStopEntireExecution() {
return stopEntireExecution;
}
public void setStopEntireExecution(boolean stopEntireExecution) {
this.stopEntireExecution = stopEntireExecution;
}
public String getAlias() {
return alias;
}
public void setAlias(String alias) {
this.alias = alias;
}
public void toElement(Element createElement, Document doc) {
createElement.setAttribute("repetitions", Integer.toString(repetition));
createElement.setAttribute("saveRunProperties", Boolean.toString(saveRunProperties));
createElement.setAttribute("dependOnPrevious", Boolean.toString(dependOnPrevious));
createElement.setAttribute("freezeOnFail", Boolean.toString(freezeOnFail));
createElement.setAttribute("stopSuiteExecution", Boolean.toString(stopSuiteExecution));
createElement.setAttribute("stopEntireExecution", Boolean.toString(stopEntireExecution));
createElement.setAttribute("alias", alias);
Element projPathElement = doc.createElement("projectPath");
projPathElement.setTextContent(projectPath);
createElement.appendChild(projPathElement);
Element sutFileElement = doc.createElement("sutFile");
sutFileElement.setTextContent(sutFile);
createElement.appendChild(sutFileElement);
Element scenarioNameElement = doc.createElement("scenarioName");
scenarioNameElement.setTextContent(scenarioFile);
createElement.appendChild(scenarioNameElement);
}
} | apache-2.0 |
martinstrejc/jgreen | jgreen-core/src/main/java/cz/wicketstuff/jgreen/core/JGreenSettings.java | 1271 | /*
* 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 cz.wicketstuff.jgreen.core;
import javax.validation.Valid;
import javax.validation.constraints.NotNull;
import org.springframework.boot.context.properties.ConfigurationProperties;
/**
* @author Martin Strejc
*
*/
@ConfigurationProperties(prefix="jgreen.core")
public class JGreenSettings {
@NotNull
@Valid
private String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
| apache-2.0 |
saichler/DataSand | yang/src/main/java/org/datasand/yang/parser/YangNodeAttributes.java | 3073 | /*
* Copyright (c) 2016 DataSand,Sharon Aicler and others. All rights reserved.
*
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License v1.0 which accompanies this distribution,
* and is available at http://www.eclipse.org/legal/epl-v10.html
*/
package org.datasand.yang.parser;
/**
* @author Sharon Aicler (saichler@gmail.com)
* Created by saichler on 5/19/16.
*/
public class YangNodeAttributes {
private final String name;
private final YangTagEnum type;
private String packageName = null;
private String filePath = null;
private String fileName;
public YangNodeAttributes(String name, YangTagEnum type){
this.name = name;
this.type = type;
this.fileName = YangParser.formatElementName(this.name)+".java";
}
public static final YangNodeAttributes getNameAndType(String data, int startPoint){
int index = data.indexOf("{",startPoint);
String prevData = data.substring(0,index);
int startIndex1 = prevData.lastIndexOf(";");
int startIndex2 = prevData.lastIndexOf("}");
int startIndex3 = prevData.lastIndexOf("{");
int startIndex = 0;
if(startIndex1!=-1){
startIndex = startIndex1;
}
if(startIndex2>startIndex) {
startIndex = startIndex2;
}
if(startIndex3>startIndex) {
startIndex = startIndex3;
}
String str = data.substring(startIndex,index);
index = -1;
YangTagEnum enums[] = YangTagEnum.values();
boolean found = false;
int x = -1;
int y = -1;
for(int i=0;i<enums.length;i++){
String enumName = enums[i].name();
if(enumName.startsWith("_")){
enumName = enumName.substring(1);
}
x = str.lastIndexOf(enumName);
if(x==-1){
continue;
}
y = str.indexOf(enumName);
if(y<x){
x = y;
}
if(x+startIndex>=startPoint){
found = true;
startPoint = x;
index = i;
break;
}
}
if(index==-1){
throw new IllegalArgumentException("Can't figure out node type from "+str);
}
return new YangNodeAttributes(str.substring(x+enums[index].name().length()).trim(),enums[index]);
}
public String getName() {
return name;
}
public YangTagEnum getType() {
return type;
}
public String getPackageName() {
return packageName;
}
public void setPackageName(String packageName) {
this.packageName = packageName;
}
public String getFilePath() {
return filePath;
}
public void setFilePath(String filePath) {
this.filePath = filePath;
}
public String getFileName() {
return fileName;
}
public void setFileName(String fileName) {
this.fileName = fileName;
}
}
| apache-2.0 |
infinitiessoft/nova2.0-api | src/main/java/com/infinities/nova/networks/views/ViewBuilder.java | 1611 | /*******************************************************************************
* Copyright 2015 InfinitiesSoft Solutions 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.infinities.nova.networks.views;
import java.util.List;
import javax.ws.rs.container.ContainerRequestContext;
import com.infinities.nova.networks.model.Network;
import com.infinities.nova.networks.model.NetworkTemplate;
import com.infinities.nova.networks.model.Networks;
/**
* @author pohsun
*
*/
public class ViewBuilder {
/**
* @param requestContext
* @param networks
* @return
*/
public Networks index(ContainerRequestContext requestContext, List<Network> networks) {
Networks ret = new Networks();
ret.setList(networks);
return ret;
}
/**
* @param requestContext
* @param network
* @return
*/
public NetworkTemplate show(ContainerRequestContext requestContext, Network network) {
NetworkTemplate template = new NetworkTemplate();
template.setNetwork(network);
return template;
}
}
| apache-2.0 |
ferfischer/Miwok | app/src/main/java/com/example/android/miwok/FamilyFragment.java | 7292 | package com.example.android.miwok;
import android.content.Context;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ListView;
import java.util.ArrayList;
/**
* A simple {@link Fragment} subclass.
*/
public class FamilyFragment extends Fragment {
MediaPlayer mMediaPlayer;
private AudioManager mAudioManager;
/**
* This listener gets triggered whenever the audio focus changes
* (i.e., we gain or lose audio focus because of another app or device).
*/
private AudioManager.OnAudioFocusChangeListener mOnAudioFocusChangeListener = new AudioManager.OnAudioFocusChangeListener() {
@Override
public void onAudioFocusChange(int focusChange) {
if (focusChange == AudioManager.AUDIOFOCUS_LOSS_TRANSIENT ||
focusChange == AudioManager.AUDIOFOCUS_LOSS_TRANSIENT_CAN_DUCK) {
// The AUDIOFOCUS_LOSS_TRANSIENT case means that we've lost audio focus for a
// short amount of time. The AUDIOFOCUS_LOSS_TRANSIENT_CAN_DUCK case means that
// our app is allowed to continue playing sound but at a lower volume. We'll treat
// both cases the same way because our app is playing short sound files.
// Pause playback and reset player to the start of the file. That way, we can
// play the word from the beginning when we resume playback.
mMediaPlayer.pause();
mMediaPlayer.seekTo(0);
} else if (focusChange == AudioManager.AUDIOFOCUS_GAIN) {
// The AUDIOFOCUS_GAIN case means we have regained focus and can resume playback.
mMediaPlayer.start();
} else if (focusChange == AudioManager.AUDIOFOCUS_LOSS) {
// The AUDIOFOCUS_LOSS case means we've lost audio focus and
// Stop playback and clean up resources
releaseMediaPlayer();
}
}
};
/**
* This listener gets triggered when the {@link MediaPlayer} has completed
* playing the audio file.
*/
private MediaPlayer.OnCompletionListener mCompletionListener = new MediaPlayer.OnCompletionListener() {
@Override
public void onCompletion(MediaPlayer mediaPlayer) {
// Now that the sound file has finished playing, release the media player resources.
releaseMediaPlayer();
}
};
public FamilyFragment() {
// Required empty public constructor
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.word_list, container, false);
/* Usando arraylist of Word */
final ArrayList<Word> words = new ArrayList<Word>();
words.add(new Word("father", "әpә", R.drawable.family_father, R.raw.family_father));
words.add(new Word("mother", "әṭa", R.drawable.family_mother, R.raw.family_mother));
words.add(new Word("son", "angsi", R.drawable.family_son, R.raw.family_son));
words.add(new Word("daughter", "tune", R.drawable.family_daughter, R.raw.family_daughter));
words.add(new Word("older brother", "taachi", R.drawable.family_older_brother, R.raw.family_older_brother));
words.add(new Word("younger brother", "chalitti", R.drawable.family_younger_brother, R.raw.family_younger_brother));
words.add(new Word("older sister", "teṭe", R.drawable.family_older_sister, R.raw.family_older_sister));
words.add(new Word("younger sister", "kolliti", R.drawable.family_younger_sister, R.raw.family_younger_sister));
words.add(new Word("grandmother", "ama", R.drawable.family_grandmother, R.raw.family_grandfather));
words.add(new Word("grandfather", "paapa", R.drawable.family_grandfather, R.raw.family_grandfather));
WordAdapter adapter = new WordAdapter(getActivity(), words, R.color.category_family);
ListView listView = (ListView) rootView.findViewById(R.id.list);
// Estabelecer um click listener para reproduzir o áudio quando o item da lista é clicado
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> adapterView, View view, int position, long l) {
// Obter {@link Word} objeto em uma posição dada em que o usuário clicou
Word word = words.get(position);
Log.v("FamilyFragment", "Current word: " + word);
// Antes de iniciar, libera os recursos usados pelo media player se estiverem em uso
releaseMediaPlayer();
mAudioManager = (AudioManager) getActivity().getSystemService(Context.AUDIO_SERVICE);
// Request audio focus for playback
int result = mAudioManager.requestAudioFocus(mOnAudioFocusChangeListener,
// Use the music stream.
AudioManager.STREAM_MUSIC,
// Request focus for a short time.
AudioManager.AUDIOFOCUS_GAIN_TRANSIENT);
if (result == AudioManager.AUDIOFOCUS_REQUEST_GRANTED) {
// Create and setup the {@link MediaPlayer} for the audio resource associated
// with the current word
mMediaPlayer = MediaPlayer.create(getActivity(), word.getAudioResouceId());
// Start the audio file
mMediaPlayer.start();
// Setup a listener on the media player, so that we can stop and release the
// media player once the sound has finished playing.
mMediaPlayer.setOnCompletionListener(mCompletionListener);
}
}
});
listView.setAdapter(adapter);
return rootView;
}
/**
* Clean up the media player by releasing its resources.
*/
private void releaseMediaPlayer() {
// If the media player is not null, then it may be currently playing a sound.
if (mMediaPlayer != null) {
// Regardless of the current state of the media player, release its resources
// because we no longer need it.
mMediaPlayer.release();
// Set the media player back to null. For our code, we've decided that
// setting the media player to null is an easy way to tell that the media player
// is not configured to play an audio file at the moment.
mMediaPlayer = null;
// Regardless of whether or not we were granted audio focus, abandon it. This also
// unregisters the AudioFocusChangeListener so we don't get anymore callbacks.
mAudioManager.abandonAudioFocus(mOnAudioFocusChangeListener);
}
}
@Override
public void onStop() {
super.onStop();
releaseMediaPlayer();
}
}
| apache-2.0 |
citygml4j/citygml4j | src-gen/main/java/net/opengis/gml/NodeType.java | 3569 | //
// Diese Datei wurde mit der JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.3.2 generiert
// Siehe <a href="https://javaee.github.io/jaxb-v2/">https://javaee.github.io/jaxb-v2/</a>
// Änderungen an dieser Datei gehen bei einer Neukompilierung des Quellschemas verloren.
// Generiert: 2019.02.03 um 11:14:53 PM CET
//
package net.opengis.gml;
import java.util.ArrayList;
import java.util.List;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlType;
/**
* Its optional co-boundary is a set of connected directedEdges. The orientation of one of these dirEdges is "+" if the Node is the "to" node of the Edge, and "-" if it is the "from" node.
*
* <p>Java-Klasse für NodeType complex type.
*
* <p>Das folgende Schemafragment gibt den erwarteten Content an, der in dieser Klasse enthalten ist.
*
* <pre>
* <complexType name="NodeType">
* <complexContent>
* <extension base="{http://www.opengis.net/gml}AbstractTopoPrimitiveType">
* <sequence>
* <element ref="{http://www.opengis.net/gml}directedEdge" maxOccurs="unbounded" minOccurs="0"/>
* <element ref="{http://www.opengis.net/gml}pointProperty" minOccurs="0"/>
* </sequence>
* </extension>
* </complexContent>
* </complexType>
* </pre>
*
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "NodeType", propOrder = {
"directedEdge",
"pointProperty"
})
public class NodeType
extends AbstractTopoPrimitiveType
{
protected List<DirectedEdgePropertyType> directedEdge;
protected PointPropertyType pointProperty;
/**
* Gets the value of the directedEdge property.
*
* <p>
* This accessor method returns a reference to the live list,
* not a snapshot. Therefore any modification you make to the
* returned list will be present inside the JAXB object.
* This is why there is not a <CODE>set</CODE> method for the directedEdge property.
*
* <p>
* For example, to add a new item, do as follows:
* <pre>
* getDirectedEdge().add(newItem);
* </pre>
*
*
* <p>
* Objects of the following type(s) are allowed in the list
* {@link DirectedEdgePropertyType }
*
*
*/
public List<DirectedEdgePropertyType> getDirectedEdge() {
if (directedEdge == null) {
directedEdge = new ArrayList<DirectedEdgePropertyType>();
}
return this.directedEdge;
}
public boolean isSetDirectedEdge() {
return ((this.directedEdge!= null)&&(!this.directedEdge.isEmpty()));
}
public void unsetDirectedEdge() {
this.directedEdge = null;
}
/**
* Ruft den Wert der pointProperty-Eigenschaft ab.
*
* @return
* possible object is
* {@link PointPropertyType }
*
*/
public PointPropertyType getPointProperty() {
return pointProperty;
}
/**
* Legt den Wert der pointProperty-Eigenschaft fest.
*
* @param value
* allowed object is
* {@link PointPropertyType }
*
*/
public void setPointProperty(PointPropertyType value) {
this.pointProperty = value;
}
public boolean isSetPointProperty() {
return (this.pointProperty!= null);
}
public void setDirectedEdge(List<DirectedEdgePropertyType> value) {
this.directedEdge = value;
}
}
| apache-2.0 |
qobel/esoguproject | spring-framework/spring-webmvc-portlet/src/test/java/org/springframework/web/portlet/mvc/PortletWrappingControllerTests.java | 7271 | /*
* Copyright 2002-2012 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.springframework.web.portlet.mvc;
import java.io.IOException;
import javax.portlet.ActionRequest;
import javax.portlet.ActionResponse;
import javax.portlet.Portlet;
import javax.portlet.PortletConfig;
import javax.portlet.PortletException;
import javax.portlet.RenderRequest;
import javax.portlet.RenderResponse;
import org.junit.Before;
import org.junit.Test;
import org.springframework.beans.BeansException;
import org.springframework.beans.MutablePropertyValues;
import org.springframework.mock.web.portlet.MockActionRequest;
import org.springframework.mock.web.portlet.MockActionResponse;
import org.springframework.mock.web.portlet.MockPortletConfig;
import org.springframework.mock.web.portlet.MockPortletContext;
import org.springframework.mock.web.portlet.MockRenderRequest;
import org.springframework.mock.web.portlet.MockRenderResponse;
import org.springframework.web.portlet.context.ConfigurablePortletApplicationContext;
import org.springframework.web.portlet.context.StaticPortletApplicationContext;
import static org.junit.Assert.*;
/**
* Unit tests for the {@link PortletWrappingController} class.
*
* @author Mark Fisher
* @author Rick Evans
* @author Chris Beams
*/
public final class PortletWrappingControllerTests {
private static final String RESULT_RENDER_PARAMETER_NAME = "result";
private static final String PORTLET_WRAPPING_CONTROLLER_BEAN_NAME = "controller";
private static final String RENDERED_RESPONSE_CONTENT = "myPortlet-view";
private static final String PORTLET_NAME_ACTION_REQUEST_PARAMETER_NAME = "portletName";
private PortletWrappingController controller;
@Before
public void setUp() {
ConfigurablePortletApplicationContext applicationContext = new MyApplicationContext();
MockPortletConfig config = new MockPortletConfig(new MockPortletContext(), "wrappedPortlet");
applicationContext.setPortletConfig(config);
applicationContext.refresh();
controller = (PortletWrappingController) applicationContext.getBean(PORTLET_WRAPPING_CONTROLLER_BEAN_NAME);
}
@Test
public void testActionRequest() throws Exception {
MockActionRequest request = new MockActionRequest();
MockActionResponse response = new MockActionResponse();
request.setParameter("test", "test");
controller.handleActionRequest(request, response);
String result = response.getRenderParameter(RESULT_RENDER_PARAMETER_NAME);
assertEquals("myPortlet-action", result);
}
@Test
public void testRenderRequest() throws Exception {
MockRenderRequest request = new MockRenderRequest();
MockRenderResponse response = new MockRenderResponse();
controller.handleRenderRequest(request, response);
String result = response.getContentAsString();
assertEquals(RENDERED_RESPONSE_CONTENT, result);
}
@Test(expected=IllegalArgumentException.class)
public void testActionRequestWithNoParameters() throws Exception {
MockActionRequest request = new MockActionRequest();
MockActionResponse response = new MockActionResponse();
controller.handleActionRequest(request, response);
}
@Test(expected=IllegalArgumentException.class)
public void testRejectsPortletClassThatDoesNotImplementPortletInterface() throws Exception {
PortletWrappingController controller = new PortletWrappingController();
controller.setPortletClass(String.class);
controller.afterPropertiesSet();
}
@Test(expected=IllegalArgumentException.class)
public void testRejectsIfPortletClassIsNotSupplied() throws Exception {
PortletWrappingController controller = new PortletWrappingController();
controller.setPortletClass(null);
controller.afterPropertiesSet();
}
@Test(expected=IllegalStateException.class)
public void testDestroyingTheControllerPropagatesDestroyToWrappedPortlet() throws Exception {
final PortletWrappingController controller = new PortletWrappingController();
controller.setPortletClass(MyPortlet.class);
controller.afterPropertiesSet();
// test for destroy() call being propagated via exception being thrown :(
controller.destroy();
}
@Test
public void testPortletName() throws Exception {
MockActionRequest request = new MockActionRequest();
MockActionResponse response = new MockActionResponse();
request.setParameter(PORTLET_NAME_ACTION_REQUEST_PARAMETER_NAME, "test");
controller.handleActionRequest(request, response);
String result = response.getRenderParameter(RESULT_RENDER_PARAMETER_NAME);
assertEquals("wrappedPortlet", result);
}
@Test
public void testDelegationToMockPortletConfigIfSoConfigured() throws Exception {
final String BEAN_NAME = "Sixpence None The Richer";
MockActionRequest request = new MockActionRequest();
MockActionResponse response = new MockActionResponse();
PortletWrappingController controller = new PortletWrappingController();
controller.setPortletClass(MyPortlet.class);
controller.setUseSharedPortletConfig(false);
controller.setBeanName(BEAN_NAME);
controller.afterPropertiesSet();
request.setParameter(PORTLET_NAME_ACTION_REQUEST_PARAMETER_NAME, "true");
controller.handleActionRequest(request, response);
String result = response.getRenderParameter(RESULT_RENDER_PARAMETER_NAME);
assertEquals(BEAN_NAME, result);
}
public static final class MyPortlet implements Portlet {
private PortletConfig portletConfig;
@Override
public void init(PortletConfig portletConfig) {
this.portletConfig = portletConfig;
}
@Override
public void processAction(ActionRequest request, ActionResponse response) throws PortletException {
if (request.getParameter("test") != null) {
response.setRenderParameter(RESULT_RENDER_PARAMETER_NAME, "myPortlet-action");
} else if (request.getParameter(PORTLET_NAME_ACTION_REQUEST_PARAMETER_NAME) != null) {
response.setRenderParameter(RESULT_RENDER_PARAMETER_NAME, getPortletConfig().getPortletName());
} else {
throw new IllegalArgumentException("no request parameters");
}
}
@Override
public void render(RenderRequest request, RenderResponse response) throws IOException {
response.getWriter().write(RENDERED_RESPONSE_CONTENT);
}
public PortletConfig getPortletConfig() {
return this.portletConfig;
}
@Override
public void destroy() {
throw new IllegalStateException("Being destroyed...");
}
}
private static final class MyApplicationContext extends StaticPortletApplicationContext {
@Override
public void refresh() throws BeansException {
MutablePropertyValues pvs = new MutablePropertyValues();
pvs.add("portletClass", MyPortlet.class);
registerSingleton(PORTLET_WRAPPING_CONTROLLER_BEAN_NAME, PortletWrappingController.class, pvs);
super.refresh();
}
}
}
| apache-2.0 |
jai1/pulsar | pulsar-testclient/src/main/java/org/apache/pulsar/testclient/PerformanceProducer.java | 18862 | /**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.pulsar.testclient;
import static java.util.concurrent.TimeUnit.NANOSECONDS;
import static org.apache.commons.lang3.StringUtils.isBlank;
import static org.apache.commons.lang3.StringUtils.isNotBlank;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.PrintStream;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.text.DecimalFormat;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.LongAdder;
import org.HdrHistogram.Histogram;
import org.HdrHistogram.HistogramLogWriter;
import org.HdrHistogram.Recorder;
import org.apache.pulsar.client.api.ClientBuilder;
import org.apache.pulsar.client.api.CompressionType;
import org.apache.pulsar.client.api.CryptoKeyReader;
import org.apache.pulsar.client.api.EncryptionKeyInfo;
import org.apache.pulsar.client.api.MessageRoutingMode;
import org.apache.pulsar.client.api.Producer;
import org.apache.pulsar.client.api.ProducerBuilder;
import org.apache.pulsar.client.api.PulsarClient;
import org.apache.pulsar.testclient.utils.PaddingDecimalFormat;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.beust.jcommander.JCommander;
import com.beust.jcommander.Parameter;
import com.beust.jcommander.ParameterException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.ObjectWriter;
import com.google.common.collect.Lists;
import com.google.common.util.concurrent.RateLimiter;
import io.netty.util.concurrent.DefaultThreadFactory;
public class PerformanceProducer {
private static final ExecutorService executor = Executors
.newCachedThreadPool(new DefaultThreadFactory("pulsar-perf-producer-exec"));
private static final LongAdder messagesSent = new LongAdder();
private static final LongAdder bytesSent = new LongAdder();
private static Recorder recorder = new Recorder(TimeUnit.SECONDS.toMillis(120000), 5);
private static Recorder cumulativeRecorder = new Recorder(TimeUnit.SECONDS.toMillis(120000), 5);
static class Arguments {
@Parameter(names = { "-h", "--help" }, description = "Help message", help = true)
boolean help;
@Parameter(names = { "--conf-file" }, description = "Configuration file")
public String confFile;
@Parameter(description = "persistent://prop/ns/my-topic", required = true)
public List<String> topics;
@Parameter(names = { "-r", "--rate" }, description = "Publish rate msg/s across topics")
public int msgRate = 100;
@Parameter(names = { "-s", "--size" }, description = "Message size")
public int msgSize = 1024;
@Parameter(names = { "-t", "--num-topic" }, description = "Number of topics")
public int numTopics = 1;
@Parameter(names = { "-n", "--num-producers" }, description = "Number of producers (per topic)")
public int numProducers = 1;
@Parameter(names = { "-u", "--service-url" }, description = "Pulsar Service URL")
public String serviceURL;
@Parameter(names = { "--auth_plugin" }, description = "Authentication plugin class name")
public String authPluginClassName;
@Parameter(names = {
"--auth_params" }, description = "Authentication parameters, e.g., \"key1:val1,key2:val2\"")
public String authParams;
@Parameter(names = { "-o", "--max-outstanding" }, description = "Max number of outstanding messages")
public int maxOutstanding = 1000;
@Parameter(names = { "-c",
"--max-connections" }, description = "Max number of TCP connections to a single broker")
public int maxConnections = 100;
@Parameter(names = { "-m",
"--num-messages" }, description = "Number of messages to publish in total. If 0, it will keep publishing")
public long numMessages = 0;
@Parameter(names = { "-i",
"--stats-interval-seconds" }, description = "Statistics Interval Seconds. If 0, statistics will be disabled")
public long statsIntervalSeconds = 0;
@Parameter(names = { "-z", "--compression" }, description = "Compress messages payload")
public CompressionType compression = CompressionType.NONE;
@Parameter(names = { "-f", "--payload-file" }, description = "Use payload from a file instead of empty buffer")
public String payloadFilename = null;
@Parameter(names = { "-b",
"--batch-time-window" }, description = "Batch messages in 'x' ms window (Default: 1ms)")
public double batchTimeMillis = 1.0;
@Parameter(names = { "-time",
"--test-duration" }, description = "Test duration in secs. If 0, it will keep publishing")
public long testTime = 0;
@Parameter(names = "--warmup-time", description = "Warm-up time in seconds (Default: 1 sec)")
public double warmupTimeSeconds = 1.0;
@Parameter(names = {
"--use-tls" }, description = "Use TLS encryption on the connection")
public boolean useTls;
@Parameter(names = {
"--trust-cert-file" }, description = "Path for the trusted TLS certificate file")
public String tlsTrustCertsFilePath = "";
@Parameter(names = { "-k", "--encryption-key-name" }, description = "The public key name to encrypt payload")
public String encKeyName = null;
@Parameter(names = { "-v",
"--encryption-key-value-file" }, description = "The file which contains the public key to encrypt payload")
public String encKeyFile = null;
}
public static void main(String[] args) throws Exception {
final Arguments arguments = new Arguments();
JCommander jc = new JCommander(arguments);
jc.setProgramName("pulsar-perf-producer");
try {
jc.parse(args);
} catch (ParameterException e) {
System.out.println(e.getMessage());
jc.usage();
System.exit(-1);
}
if (arguments.help) {
jc.usage();
System.exit(-1);
}
if (arguments.topics.size() != 1) {
System.out.println("Only one topic name is allowed");
jc.usage();
System.exit(-1);
}
if (arguments.confFile != null) {
Properties prop = new Properties(System.getProperties());
prop.load(new FileInputStream(arguments.confFile));
if (arguments.serviceURL == null) {
arguments.serviceURL = prop.getProperty("brokerServiceUrl");
}
if (arguments.serviceURL == null) {
arguments.serviceURL = prop.getProperty("webServiceUrl");
}
// fallback to previous-version serviceUrl property to maintain backward-compatibility
if (arguments.serviceURL == null) {
arguments.serviceURL = prop.getProperty("serviceUrl", "http://localhost:8080/");
}
if (arguments.authPluginClassName == null) {
arguments.authPluginClassName = prop.getProperty("authPlugin", null);
}
if (arguments.authParams == null) {
arguments.authParams = prop.getProperty("authParams", null);
}
if (arguments.useTls == false) {
arguments.useTls = Boolean.parseBoolean(prop.getProperty("useTls"));
}
if (isBlank(arguments.tlsTrustCertsFilePath)) {
arguments.tlsTrustCertsFilePath = prop.getProperty("tlsTrustCertsFilePath", "");
}
}
// Dump config variables
ObjectMapper m = new ObjectMapper();
ObjectWriter w = m.writerWithDefaultPrettyPrinter();
log.info("Starting Pulsar perf producer with config: {}", w.writeValueAsString(arguments));
// Read payload data from file if needed
byte payloadData[];
if (arguments.payloadFilename != null) {
payloadData = Files.readAllBytes(Paths.get(arguments.payloadFilename));
} else {
payloadData = new byte[arguments.msgSize];
}
// Now processing command line arguments
String prefixTopicName = arguments.topics.get(0);
List<Future<Producer<byte[]>>> futures = Lists.newArrayList();
ClientBuilder clientBuilder = PulsarClient.builder() //
.serviceUrl(arguments.serviceURL) //
.connectionsPerBroker(arguments.maxConnections) //
.ioThreads(Runtime.getRuntime().availableProcessors()) //
.statsInterval(arguments.statsIntervalSeconds, TimeUnit.SECONDS) //
.enableTls(arguments.useTls) //
.tlsTrustCertsFilePath(arguments.tlsTrustCertsFilePath);
if (isNotBlank(arguments.authPluginClassName)) {
clientBuilder.authentication(arguments.authPluginClassName, arguments.authParams);
}
class EncKeyReader implements CryptoKeyReader {
EncryptionKeyInfo keyInfo = new EncryptionKeyInfo();
EncKeyReader(byte[] value) {
keyInfo.setKey(value);
}
@Override
public EncryptionKeyInfo getPublicKey(String keyName, Map<String, String> keyMeta) {
if (keyName.equals(arguments.encKeyName)) {
return keyInfo;
}
return null;
}
@Override
public EncryptionKeyInfo getPrivateKey(String keyName, Map<String, String> keyMeta) {
return null;
}
}
PulsarClient client = clientBuilder.build();
ProducerBuilder<byte[]> producerBuilder = client.newProducer() //
.sendTimeout(0, TimeUnit.SECONDS) //
.compressionType(arguments.compression) //
.maxPendingMessages(arguments.maxOutstanding) //
// enable round robin message routing if it is a partitioned topic
.messageRoutingMode(MessageRoutingMode.RoundRobinPartition);
if (arguments.batchTimeMillis == 0.0) {
producerBuilder.enableBatching(false);
} else {
long batchTimeUsec = (long) (arguments.batchTimeMillis * 1000);
producerBuilder.batchingMaxPublishDelay(batchTimeUsec, TimeUnit.MICROSECONDS)
.enableBatching(true);
}
// Block if queue is full else we will start seeing errors in sendAsync
producerBuilder.blockIfQueueFull(true);
if (arguments.encKeyName != null) {
producerBuilder.addEncryptionKey(arguments.encKeyName);
byte[] pKey = Files.readAllBytes(Paths.get(arguments.encKeyFile));
EncKeyReader keyReader = new EncKeyReader(pKey);
producerBuilder.cryptoKeyReader(keyReader);
}
for (int i = 0; i < arguments.numTopics; i++) {
String topic = (arguments.numTopics == 1) ? prefixTopicName : String.format("%s-%d", prefixTopicName, i);
log.info("Adding {} publishers on topic {}", arguments.numProducers, topic);
for (int j = 0; j < arguments.numProducers; j++) {
futures.add(producerBuilder.clone().topic(topic).createAsync());
}
}
final List<Producer<byte[]>> producers = Lists.newArrayListWithCapacity(futures.size());
for (Future<Producer<byte[]>> future : futures) {
producers.add(future.get());
}
log.info("Created {} producers", producers.size());
Runtime.getRuntime().addShutdownHook(new Thread() {
public void run() {
printAggregatedStats();
}
});
Collections.shuffle(producers);
AtomicBoolean isDone = new AtomicBoolean();
executor.submit(() -> {
try {
RateLimiter rateLimiter = RateLimiter.create(arguments.msgRate);
long startTime = System.nanoTime();
long warmupEndTime = startTime + (long) (arguments.warmupTimeSeconds * 1e9);
long testEndTime = startTime + (long) (arguments.testTime * 1e9);
// Send messages on all topics/producers
long totalSent = 0;
while (true) {
for (Producer<byte[]> producer : producers) {
if (arguments.testTime > 0) {
if (System.nanoTime() > testEndTime) {
log.info("------------------- DONE -----------------------");
printAggregatedStats();
isDone.set(true);
Thread.sleep(5000);
System.exit(0);
}
}
if (arguments.numMessages > 0) {
if (totalSent++ >= arguments.numMessages) {
log.info("------------------- DONE -----------------------");
printAggregatedStats();
isDone.set(true);
Thread.sleep(5000);
System.exit(0);
}
}
rateLimiter.acquire();
final long sendTime = System.nanoTime();
producer.sendAsync(payloadData).thenRun(() -> {
messagesSent.increment();
bytesSent.add(payloadData.length);
long now = System.nanoTime();
if (now > warmupEndTime) {
long latencyMicros = NANOSECONDS.toMicros(now - sendTime);
recorder.recordValue(latencyMicros);
cumulativeRecorder.recordValue(latencyMicros);
}
}).exceptionally(ex -> {
log.warn("Write error on message", ex);
System.exit(-1);
return null;
});
}
}
} catch (Throwable t) {
log.error("Got error", t);
}
});
// Print report stats
long oldTime = System.nanoTime();
Histogram reportHistogram = null;
String statsFileName = "perf-producer-" + System.currentTimeMillis() + ".hgrm";
log.info("Dumping latency stats to {}", statsFileName);
PrintStream histogramLog = new PrintStream(new FileOutputStream(statsFileName), false);
HistogramLogWriter histogramLogWriter = new HistogramLogWriter(histogramLog);
// Some log header bits
histogramLogWriter.outputLogFormatVersion();
histogramLogWriter.outputLegend();
while (true) {
try {
Thread.sleep(10000);
} catch (InterruptedException e) {
break;
}
if (isDone.get()) {
break;
}
long now = System.nanoTime();
double elapsed = (now - oldTime) / 1e9;
double rate = messagesSent.sumThenReset() / elapsed;
double throughput = bytesSent.sumThenReset() / elapsed / 1024 / 1024 * 8;
reportHistogram = recorder.getIntervalHistogram(reportHistogram);
log.info(
"Throughput produced: {} msg/s --- {} Mbit/s --- Latency: mean: {} ms - med: {} - 95pct: {} - 99pct: {} - 99.9pct: {} - 99.99pct: {} - Max: {}",
throughputFormat.format(rate), throughputFormat.format(throughput),
dec.format(reportHistogram.getMean() / 1000.0),
dec.format(reportHistogram.getValueAtPercentile(50) / 1000.0),
dec.format(reportHistogram.getValueAtPercentile(95) / 1000.0),
dec.format(reportHistogram.getValueAtPercentile(99) / 1000.0),
dec.format(reportHistogram.getValueAtPercentile(99.9) / 1000.0),
dec.format(reportHistogram.getValueAtPercentile(99.99) / 1000.0),
dec.format(reportHistogram.getMaxValue() / 1000.0));
histogramLogWriter.outputIntervalHistogram(reportHistogram);
reportHistogram.reset();
oldTime = now;
}
client.close();
}
private static void printAggregatedStats() {
Histogram reportHistogram = cumulativeRecorder.getIntervalHistogram();
log.info(
"Aggregated latency stats --- Latency: mean: {} ms - med: {} - 95pct: {} - 99pct: {} - 99.9pct: {} - 99.99pct: {} - 99.999pct: {} - Max: {}",
dec.format(reportHistogram.getMean() / 1000.0),
dec.format(reportHistogram.getValueAtPercentile(50) / 1000.0),
dec.format(reportHistogram.getValueAtPercentile(95) / 1000.0),
dec.format(reportHistogram.getValueAtPercentile(99) / 1000.0),
dec.format(reportHistogram.getValueAtPercentile(99.9) / 1000.0),
dec.format(reportHistogram.getValueAtPercentile(99.99) / 1000.0),
dec.format(reportHistogram.getValueAtPercentile(99.999) / 1000.0),
dec.format(reportHistogram.getMaxValue() / 1000.0));
}
static final DecimalFormat throughputFormat = new PaddingDecimalFormat("0.0", 8);
static final DecimalFormat dec = new PaddingDecimalFormat("0.000", 7);
private static final Logger log = LoggerFactory.getLogger(PerformanceProducer.class);
}
| apache-2.0 |
lesaint/experimenting-annotation-processing | experimenting-rounds/massive-count-of-annotated-classes/src/main/java/fr/javatronic/blog/massive/annotation1/sub1/Class_5977.java | 151 | package fr.javatronic.blog.massive.annotation1.sub1;
import fr.javatronic.blog.processor.Annotation_001;
@Annotation_001
public class Class_5977 {
}
| apache-2.0 |
lesaint/experimenting-annotation-processing | experimenting-rounds/massive-count-of-annotated-classes/src/main/java/fr/javatronic/blog/massive/annotation1/sub1/Class_0924.java | 151 | package fr.javatronic.blog.massive.annotation1.sub1;
import fr.javatronic.blog.processor.Annotation_001;
@Annotation_001
public class Class_0924 {
}
| apache-2.0 |
googlearchive/leanback-showcase | app/src/main/java/android/support/v17/leanback/supportleanbackshowcase/app/room/di/scope/PerActivity.java | 946 | /*
* Copyright (C) 2017 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package android.support.v17.leanback.supportleanbackshowcase.app.room.di.scope;
import java.lang.annotation.Documented;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import javax.inject.Scope;
@Documented
@Retention(RetentionPolicy.RUNTIME)
@Scope
public @interface PerActivity {
}
| apache-2.0 |
maguero/emisi | src/main/java/com/emisi/presentation/ConsultaPage.java | 3448 | package com.emisi.presentation;
import java.util.ArrayList;
import java.util.List;
import org.apache.wicket.PageParameters;
import org.apache.wicket.markup.html.basic.Label;
import org.apache.wicket.markup.html.link.BookmarkablePageLink;
import org.apache.wicket.markup.html.navigation.paging.PagingNavigator;
import org.apache.wicket.markup.repeater.Item;
import org.apache.wicket.markup.repeater.data.DataView;
import org.apache.wicket.markup.repeater.data.ListDataProvider;
import org.apache.wicket.spring.injection.annot.SpringBean;
import org.dcm4che2.data.DicomObject;
import org.dcm4che2.io.DicomInputStream;
import com.emisi.dao.SerieDAOImpl;
import com.emisi.model.Imagen;
import com.emisi.model.Serie;
import com.emisi.service.GenericService;
import com.emisi.util.DicomUtils;
public class ConsultaPage extends TemplateIndex {
// private final Logger logger = LoggerFactory.getLogger(ConsultaPage.class);
private static final long serialVersionUID = 1L;
@SpringBean(name = "service.imagen")
private GenericService<Imagen> imagenService;
// @SpringBean(name = "dao.serie")
// private SerieDAOImpl daoSerie;
public ConsultaPage(final PageParameters parameters) {
super(parameters);
//add(new Label("version", getApplication().getFrameworkSettings().getVersion()));
List<Imagen> imagenes = imagenService.findAll();
// logger.info("result: " + list.size());
/*
List<Imagen> imagenes = new ArrayList<Imagen>();
List<Serie> series = daoSerie.findAll();
for (Serie serie : series) {
imagenes.addAll(serie.getImagenes());
}
*/
@SuppressWarnings("unchecked")
final DataView dataView = new DataView("tablaImagen", new ListDataProvider(
imagenes)) {
@Override
protected void populateItem(Item item) {
final Imagen imagen = (Imagen) item.getModelObject();
if (imagen == null) {
item.add(new Label("id", "-"));
item.add(new Label("modalidad", "N/A"));
item.add(new Label("diagnostico", "N/A"));
item.add(new Label("imagen", "Imagen no disponible."));
item.add(new Label("detalle", "-"));
return;
}
// id de la imagen
item.add(new Label("id", imagen.getIdImagen()));//.substring(0, 10)));
// id de la imagen
item.add(new Label("modalidad", imagen.getModalidad()));
// id de la imagen
item.add(new Label("diagnostico", imagen.getDiagnostico()));
// imagen
DicomInputStream din = null;
try {
DicomObject dcmObj = DicomUtils.getDicomObject(imagen.getDicom());
item.add(DicomUtils.getImageFromDicom(dcmObj));
} catch (Exception e1) {
item.add(new Label("imagen", "Imagen no disponible."));
e1.printStackTrace();
} finally {
try {
din.close();
} catch (Exception ignore) {
}
}
//link al detalle de la imagen
PageParameters pars = new PageParameters();
pars.add("id", imagen.getIdImagen());
BookmarkablePageLink linkDetalle = new BookmarkablePageLink("detalle", ImagenPage.class, pars);
item.add(linkDetalle);
}
};
dataView.setItemsPerPage(10);
add(dataView);
add(new PagingNavigator("navigator", dataView));
}
}
| apache-2.0 |
linkedin/pinot | pinot-core/src/main/java/org/apache/pinot/core/startree/v2/builder/StarTreeIndexCombiner.java | 4127 | /**
* 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.pinot.core.startree.v2.builder;
import com.google.common.base.Preconditions;
import java.io.Closeable;
import java.io.File;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.nio.channels.FileChannel;
import java.util.HashMap;
import java.util.Map;
import org.apache.commons.io.FileUtils;
import org.apache.pinot.core.startree.v2.AggregationFunctionColumnPair;
import static org.apache.pinot.core.segment.creator.impl.V1Constants.Indexes.RAW_SV_FORWARD_INDEX_FILE_EXTENSION;
import static org.apache.pinot.core.segment.creator.impl.V1Constants.Indexes.UNSORTED_SV_FORWARD_INDEX_FILE_EXTENSION;
import static org.apache.pinot.core.startree.v2.StarTreeV2Constants.STAR_TREE_INDEX_FILE_NAME;
import static org.apache.pinot.core.startree.v2.store.StarTreeIndexMapUtils.IndexKey;
import static org.apache.pinot.core.startree.v2.store.StarTreeIndexMapUtils.IndexType;
import static org.apache.pinot.core.startree.v2.store.StarTreeIndexMapUtils.IndexValue;
import static org.apache.pinot.core.startree.v2.store.StarTreeIndexMapUtils.STAR_TREE_INDEX_KEY;
/**
* The {@code StarTreeIndexCombiner} class combines multiple star-tree indexes into a single index file.
*/
public class StarTreeIndexCombiner implements Closeable {
private final FileChannel _fileChannel;
public StarTreeIndexCombiner(File indexFile)
throws IOException {
Preconditions.checkState(!indexFile.exists(), "Star-tree index file already exists");
_fileChannel = new RandomAccessFile(indexFile, "rw").getChannel();
}
/**
* Combines the index files inside the given directory into the single index file, then cleans the directory.
*/
public Map<IndexKey, IndexValue> combine(StarTreeV2BuilderConfig builderConfig, File starTreeIndexDir)
throws IOException {
Map<IndexKey, IndexValue> indexMap = new HashMap<>();
// Write star-tree index
File starTreeIndexFile = new File(starTreeIndexDir, STAR_TREE_INDEX_FILE_NAME);
indexMap.put(STAR_TREE_INDEX_KEY, writeFile(starTreeIndexFile));
// Write dimension indexes
for (String dimension : builderConfig.getDimensionsSplitOrder()) {
File dimensionIndexFile = new File(starTreeIndexDir, dimension + UNSORTED_SV_FORWARD_INDEX_FILE_EXTENSION);
indexMap.put(new IndexKey(IndexType.FORWARD_INDEX, dimension), writeFile(dimensionIndexFile));
}
// Write metric (function-column pair) indexes
for (AggregationFunctionColumnPair functionColumnPair : builderConfig.getFunctionColumnPairs()) {
String metric = functionColumnPair.toColumnName();
File metricIndexFile = new File(starTreeIndexDir, metric + RAW_SV_FORWARD_INDEX_FILE_EXTENSION);
indexMap.put(new IndexKey(IndexType.FORWARD_INDEX, metric), writeFile(metricIndexFile));
}
FileUtils.cleanDirectory(starTreeIndexDir);
return indexMap;
}
private IndexValue writeFile(File srcFile)
throws IOException {
try (FileChannel src = new RandomAccessFile(srcFile, "r").getChannel()) {
long offset = _fileChannel.position();
long size = src.size();
org.apache.pinot.common.utils.FileUtils.transferBytes(src, 0, size, _fileChannel);
return new IndexValue(offset, size);
}
}
@Override
public void close()
throws IOException {
_fileChannel.close();
}
}
| apache-2.0 |
factoryfx/factoryfx | factory/src/main/java/io/github/factoryfx/server/user/persistent/UserFactory.java | 1710 | package io.github.factoryfx.server.user.persistent;
import com.fasterxml.jackson.annotation.JsonAlias;
import io.github.factoryfx.factory.attribute.types.LocaleAttribute;
import io.github.factoryfx.factory.attribute.types.PasswordAttribute;
import io.github.factoryfx.factory.attribute.types.StringAttribute;
import io.github.factoryfx.factory.attribute.types.StringListAttribute;
import io.github.factoryfx.factory.FactoryBase;
import io.github.factoryfx.factory.SimpleFactoryBase;
import io.github.factoryfx.server.user.User;
public class UserFactory<R extends FactoryBase<?,R>> extends SimpleFactoryBase<User,R> {
/**key is static and not part of the factory to keep the key secret*/
public static String passwordKey;
public final StringAttribute name = new StringAttribute().en("name").de("Name");
public final PasswordAttribute password = new PasswordAttribute().en("password").de("Passwort").hash(s -> new PasswordHash().hash(s));
public final LocaleAttribute locale = new LocaleAttribute().en("locale").de("Sprache");
@JsonAlias({"permissions", "permissons"})//for compatibility
public final StringListAttribute permissions = new StringListAttribute().en("permissions").de("Rechte").nullable();
@Override
protected User createImpl() {
if (passwordKey==null){
throw new IllegalStateException("missing passwordKey (you could create one with EncryptedStringAttribute), should be constant therefore don't create the key dynamically");
}
return new User(name.get(),password.get().decrypt(passwordKey),locale.get(),permissions.get());
}
public UserFactory(){
config().setDisplayTextProvider(name::get,name);
}
}
| apache-2.0 |
leangen/geantyref | src/test/java/io/leangen/geantyref/AbstractGenericsReflectorTest.java | 28797 | /*
* License: Apache License, Version 2.0
* See the LICENSE file in the root directory or at <a href="http://www.apache.org/licenses/LICENSE-2">apache.org</a>.
*/
package io.leangen.geantyref;
import static org.junit.Assert.assertNotEquals;
import junit.framework.TestCase;
import java.io.Serializable;
import java.lang.reflect.Array;
import java.lang.reflect.Field;
import java.lang.reflect.GenericArrayType;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.RandomAccess;
public abstract class AbstractGenericsReflectorTest extends TestCase {
/**
* A constant that's false, to use in an if() block for code that's only there to show that it
* compiles. This code "proves" that the test is an actual valid test case, by showing the
* compiler agrees. But some of the code should not actually be executed, because it might throw
* exceptions (because we're too lazy to initialize everything).
*/
private static final boolean COMPILE_CHECK = false;
private static final TypeToken<ArrayList<String>> ARRAYLIST_OF_STRING = new TypeToken<ArrayList<String>>() {
};
private static final TypeToken<List<String>> LIST_OF_STRING = new TypeToken<List<String>>() {
};
private static final TypeToken<Collection<String>> COLLECTION_OF_STRING = new TypeToken<Collection<String>>() {
};
private static final TypeToken<ArrayList<List<String>>> ARRAYLIST_OF_LIST_OF_STRING = new TypeToken<ArrayList<List<String>>>() {
};
private static final TypeToken<List<List<String>>> LIST_OF_LIST_OF_STRING = new TypeToken<List<List<String>>>() {
};
private static final TypeToken<Collection<List<String>>> COLLECTION_OF_LIST_OF_STRING = new TypeToken<Collection<List<String>>>() {
};
private static final TypeToken<ArrayList<? extends String>> ARRAYLIST_OF_EXT_STRING = new TypeToken<ArrayList<? extends String>>() {
};
private static final TypeToken<Collection<? extends String>> COLLECTION_OF_EXT_STRING = new TypeToken<Collection<? extends String>>() {
};
private static final TypeToken<Collection<? super String>> COLLECTION_OF_SUPER_STRING = new TypeToken<Collection<? super String>>() {
};
private static final TypeToken<ArrayList<List<? extends String>>> ARRAYLIST_OF_LIST_OF_EXT_STRING = new TypeToken<ArrayList<List<? extends String>>>() {
};
private static final TypeToken<List<List<? extends String>>> LIST_OF_LIST_OF_EXT_STRING = new TypeToken<List<List<? extends String>>>() {
};
private static final TypeToken<Collection<List<? extends String>>> COLLECTION_OF_LIST_OF_EXT_STRING = new TypeToken<Collection<List<? extends String>>>() {
};
private final ReflectionStrategy strategy;
public AbstractGenericsReflectorTest(ReflectionStrategy strategy) {
this.strategy = strategy;
}
protected static Class<?> getClassType(Type type) {
if (type instanceof Class) {
return (Class<?>) type;
} else if (type instanceof ParameterizedType) {
ParameterizedType pType = (ParameterizedType) type;
return (Class<?>) pType.getRawType();
} else if (type instanceof GenericArrayType) {
GenericArrayType aType = (GenericArrayType) type;
Class<?> componentType = getClassType(aType.getGenericComponentType());
return Array.newInstance(componentType, 0).getClass();
} else {
throw new IllegalArgumentException("Only supports Class, ParameterizedType and GenericArrayType. Not " + type.getClass());
}
}
private boolean isSupertype(TypeToken<?> supertype, TypeToken<?> subtype) {
return strategy.isSupertype(supertype.getType(), subtype.getType());
}
/**
* Tests that the types given are not equal, but they are eachother's supertype.
*/
private void testMutualSupertypes(TypeToken<?>... types) {
for (int i = 0; i < types.length; i++) {
for (int j = i + 1; j < types.length; j++) {
assertFalse(types[i].equals(types[j]));
assertTrue(isSupertype(types[i], types[j]));
assertTrue(isSupertype(types[i], types[j]));
}
}
}
/**
* Tests that the types given are not equal, but they are eachother's supertype.
*/
private <T> void checkedTestMutualSupertypes(TypeToken<T> type1, TypeToken<T> type2) {
assertFalse(type1.equals(type2));
assertTrue(isSupertype(type1, type2));
assertTrue(isSupertype(type2, type1));
}
/**
* Test if superType is seen as a real (not equal) supertype of subType.
*/
private void testRealSupertype(TypeToken<?> superType, TypeToken<?> subType) {
// test if it's really seen as a supertype
assertTrue(isSupertype(superType, subType));
// check if they're not seen as supertypes the other way around
assertFalse(isSupertype(subType, superType));
}
private <T> void checkedTestInexactSupertype(TypeToken<T> expectedSuperclass, TypeToken<? extends T> type) {
testInexactSupertype(expectedSuperclass, type);
}
/**
* Checks if the supertype is seen as a supertype of subType.
* But, if superType is a Class or ParameterizedType, with different type parameters.
*/
private void testInexactSupertype(TypeToken<?> superType, TypeToken<?> subType) {
testRealSupertype(superType, subType);
strategy.testInexactSupertype(superType.getType(), subType.getType());
}
/**
* Like testExactSuperclass, but the types of the arguments are checked so only valid test cases
* can be applied
*/
private <T> void checkedTestExactSuperclass(TypeToken<T> expectedSuperclass, TypeToken<? extends T> type) {
testExactSuperclass(expectedSuperclass, type);
}
/**
* Checks if the given types are equal
*/
private <T> void assertCheckedTypeEquals(TypeToken<T> expected, TypeToken<T> type) {
assertEquals(expected, type);
}
/**
* Checks if the supertype is seen as a supertype of subType.
* SuperType must be a Class or ParameterizedType, with the right type parameters.
*/
private void testExactSuperclass(TypeToken<?> expectedSuperclass, TypeToken<?> type) {
testRealSupertype(expectedSuperclass, type);
strategy.testExactSuperclass(expectedSuperclass.getType(), type.getType());
}
private TypeToken<?> getFieldType(TypeToken<?> forType, String fieldName) {
return getFieldType(forType.getType(), fieldName);
}
/**
* Uses the reflector being tested to get the type of the field named "f" in the given type.
* The returned value is cased into a TypeToken assuming the WithF interface is used correctly,
* and the reflector returned the correct result.
*/
@SuppressWarnings("unchecked") // assuming the WithT interface is used correctly
private <T> TypeToken<? extends T> getF(TypeToken<? extends WithF<? extends T>> type) {
return (TypeToken<? extends T>) getFieldType(type, "f");
}
/**
* Variant of {@link #getF(TypeToken)} that's stricter in arguments and return type, for checked
* equals tests.
*
* @see #getF(TypeToken)
*/
@SuppressWarnings("unchecked") // assuming the WithT interface is used correctly
private <T> TypeToken<T> getStrictF(TypeToken<? extends WithF<T>> type) {
return (TypeToken<T>) getFieldType(type, "f");
}
@SuppressWarnings("unchecked")
private <T extends TypeToken<?>> T getFToken(TypeToken<? extends WithFToken<T>> type) {
return (T) getFieldType(type, "f");
}
private TypeToken<?> getFieldType(Type forType, String fieldName) {
try {
Class<?> clazz = getClassType(forType);
return getFieldType(forType, clazz.getField(fieldName));
} catch (NoSuchFieldException e) {
throw new RuntimeException("Error in test: can't find field " + fieldName, e);
}
}
private TypeToken<?> getFieldType(Type forType, Field field) {
return TypeToken.get(strategy.getFieldType(forType, field));
}
private <T, U extends T> void checkedTestExactSuperclassChain(TypeToken<T> type1, TypeToken<U> type2, TypeToken<? extends U> type3) {
testExactSuperclassChain(type1, type2, type3);
}
private void testExactSuperclassChain(TypeToken<?>... types) {
for (int i = 0; i < types.length; i++) {
assertTrue(isSupertype(types[i], types[i]));
for (int j = i + 1; j < types.length; j++) {
testExactSuperclass(types[i], types[j]);
}
}
}
private <T, U extends T> void checkedTestInexactSupertypeChain(TypeToken<T> type1, TypeToken<U> type2, TypeToken<? extends U> type3) {
testInexactSupertypeChain(type1, type2, type3);
}
// private Type getReturnType(String methodName, Type forType) {
// try {
// Class<?> clazz = getClass(forType);
// return strategy.getExactReturnType(clazz.getMethod(methodName), forType);
// } catch (NoSuchMethodException e) {
// throw new RuntimeException("Error in test: can't find method " + methodName, e);
// }
// }
private void testInexactSupertypeChain(TypeToken<?>... types) {
for (int i = 0; i < types.length; i++) {
assertTrue(isSupertype(types[i], types[i]));
for (int j = i + 1; j < types.length; j++) {
testInexactSupertype(types[i], types[j]);
}
}
}
/**
* Test that type1 is not a supertype of type2 (and, while we're at it, not vice-versa either).
*/
private void testNotSupertypes(TypeToken<?>... types) {
for (int i = 0; i < types.length; i++) {
for (int j = i + 1; j < types.length; j++) {
assertFalse(isSupertype(types[i], types[j]));
assertFalse(isSupertype(types[j], types[i]));
}
}
}
private <T> TypeToken<T> tt(Class<T> t) {
return TypeToken.get(t);
}
public void testBasic() {
checkedTestExactSuperclassChain(tt(Object.class), tt(Number.class), tt(Integer.class));
testNotSupertypes(tt(Integer.class), tt(Double.class));
}
public void testSimpleTypeParam() {
checkedTestExactSuperclassChain(COLLECTION_OF_STRING, LIST_OF_STRING, ARRAYLIST_OF_STRING);
testNotSupertypes(COLLECTION_OF_STRING, new TypeToken<ArrayList<Integer>>() {
});
}
/**
* Dummy method to force the compiler to see the reference to the given local class.
* Workaround for Issue 15 (http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=7003595)
*/
private void use(Class<?> clazz) {
}
public void testStringList() {
checkedTestExactSuperclassChain(COLLECTION_OF_STRING, LIST_OF_STRING, tt(StringList.class));
}
@SuppressWarnings({"unchecked", "rawtypes"})
// public void testMultiBoundParametrizedStringList() {
// class C<T extends Object & StringList> implements WithF<T>{
// @SuppressWarnings("unused")
// public T f;
// }
// // raw
// new C().f = new Object(); // compile check
// assertEquals(tt(Object.class), getFieldType(C.class, "f"));
// // wildcard
// TypeToken<? extends StringList> ft = getF(new TypeToken<C<?>>(){});
// checkedTestExactSuperclassChain(LIST_OF_STRING, tt(StringList.class), ft);
// }
public void testFListOfT_String() {
class C<T> implements WithF<List<T>> {
@SuppressWarnings("unused")
public List<T> f;
}
use(C.class);
TypeToken<List<String>> ft = getStrictF(new TypeToken<C<String>>() {
});
assertCheckedTypeEquals(LIST_OF_STRING, ft);
}
public void testOfListOfString() {
checkedTestExactSuperclassChain(COLLECTION_OF_LIST_OF_STRING, LIST_OF_LIST_OF_STRING, ARRAYLIST_OF_LIST_OF_STRING);
testNotSupertypes(COLLECTION_OF_LIST_OF_STRING, new TypeToken<ArrayList<List<Integer>>>() {
});
}
public void testFListOfListOfT_String() {
class C<T> implements WithF<List<List<T>>> {
@SuppressWarnings("unused")
public List<List<T>> f;
}
use(C.class);
TypeToken<List<List<String>>> ft = getStrictF(new TypeToken<C<String>>() {
});
assertCheckedTypeEquals(LIST_OF_LIST_OF_STRING, ft);
}
public void testListOfListOfT_String() {
checkedTestExactSuperclassChain(COLLECTION_OF_LIST_OF_STRING, LIST_OF_LIST_OF_STRING, new TypeToken<ListOfListOfT<String>>() {
});
}
// public void testTextendsStringList() {
// class C<T extends StringList> implements WithF<T>{
// public T f;
// }
//
// // raw
// if (COMPILE_CHECK) {
// @SuppressWarnings("rawtypes")
// C c = null;
// List<String> listOfString = c.f;
// }
// testExactSuperclass(LIST_OF_STRING, getFieldType(C.class, "f"));
//
// // wildcard
// TypeToken<? extends StringList> ft = getF(new TypeToken<C<?>>(){});
// checkedTestExactSuperclassChain(LIST_OF_STRING, tt(StringList.class), ft);
// }
// public void testExtendViaOtherTypeParam() {
// class C<T extends StringList, U extends T> implements WithF<U> {
// @SuppressWarnings("unused")
// public U f;
// }
// // raw
// testExactSuperclass(LIST_OF_STRING, getFieldType(C.class, "f"));
// // wildcard
// TypeToken<? extends StringList> ft = getF(new TypeToken<C<?,?>>(){});
// checkedTestExactSuperclassChain(LIST_OF_STRING, tt(StringList.class), ft);
// }
public void testListOfListOfT_StringInterface() {
checkedTestExactSuperclassChain(COLLECTION_OF_LIST_OF_STRING, LIST_OF_LIST_OF_STRING, tt(ListOfListOfT_String.class));
}
public void testListOfListOfStringInterface() {
checkedTestExactSuperclassChain(COLLECTION_OF_LIST_OF_STRING, LIST_OF_LIST_OF_STRING, tt(ListOfListOfString.class));
}
public void testExtWildcard() {
checkedTestExactSuperclass(COLLECTION_OF_EXT_STRING, ARRAYLIST_OF_EXT_STRING);
checkedTestExactSuperclass(COLLECTION_OF_LIST_OF_EXT_STRING, ARRAYLIST_OF_LIST_OF_EXT_STRING);
testNotSupertypes(COLLECTION_OF_EXT_STRING, new TypeToken<ArrayList<Integer>>() {
});
testNotSupertypes(COLLECTION_OF_EXT_STRING, new TypeToken<ArrayList<Object>>() {
});
}
public void testListOfListOfExtT_String() {
checkedTestExactSuperclass(COLLECTION_OF_LIST_OF_EXT_STRING, new TypeToken<ListOfListOfExtT<String>>() {
});
}
public void testListOfExtT() {
class C<T> implements WithF<List<? extends T>> {
@SuppressWarnings("unused")
public List<? extends T> f;
}
use(C.class);
TypeToken<? extends List<? extends String>> ft = getF(new TypeToken<C<String>>() {
});
checkedTestExactSuperclass(COLLECTION_OF_EXT_STRING, ft);
}
public void testListOfSuperT() {
class C<T> implements WithF<List<? super T>> {
@SuppressWarnings("unused")
public List<? super T> f;
}
use(C.class);
TypeToken<? extends List<? super String>> ft = getF(new TypeToken<C<String>>() {
});
checkedTestExactSuperclass(COLLECTION_OF_SUPER_STRING, ft);
}
public void testInnerFieldWithTypeOfOuter() {
class Outer<T> {
@SuppressWarnings("unused")
class Inner implements WithF<T> {
public T f;
}
class Inner2 implements WithF<List<List<? extends T>>> {
@SuppressWarnings("unused")
public List<List<? extends T>> f;
}
}
use(Outer.class);
TypeToken<String> ft = getStrictF(new TypeToken<Outer<String>.Inner>() {
});
assertCheckedTypeEquals(tt(String.class), ft);
TypeToken<List<List<? extends String>>> ft2 = getStrictF(new TypeToken<Outer<String>.Inner2>() {
});
assertCheckedTypeEquals(LIST_OF_LIST_OF_EXT_STRING, ft2);
}
public void testInnerExtendsWithTypeOfOuter() {
class Outer<T> {
class Inner extends ArrayList<T> {
}
}
use(Outer.class);
checkedTestExactSuperclass(COLLECTION_OF_STRING, new TypeToken<Outer<String>.Inner>() {
});
}
public void testInnerDifferentParams() {
class Outer<T> {
class Inner<S> {
}
}
use(Outer.class);
// inner param different
testNotSupertypes(new TypeToken<Outer<String>.Inner<Integer>>() {
}, new TypeToken<Outer<String>.Inner<String>>() {
});
// outer param different
testNotSupertypes(new TypeToken<Outer<Integer>.Inner<String>>() {
}, new TypeToken<Outer<String>.Inner<String>>() {
});
}
// public void testWildcardTExtendsListOfListOfString() {
// class C<T extends List<List<String>>> implements WithF<T> {
// @SuppressWarnings("unused")
// public T f;
// }
// use(C.class);
//
// TypeToken<? extends List<List<String>>> ft = getF(new TypeToken<C<?>>(){});
// checkedTestExactSuperclass(COLLECTION_OF_LIST_OF_STRING, ft);
// }
/**
* Supertype of a raw type is erased
*/
@SuppressWarnings({"unchecked", "rawtypes"})
public void testSubclassRaw() {
class Superclass<T extends Number> {
public T t;
}
class Subclass<U> extends Superclass<Integer> {
}
use(Superclass.class);
assertEquals(tt(Number.class), getFieldType(Subclass.class, "t"));
Number n = new Subclass().t; // compile check
new Subclass().t = n; // compile check
}
/**
* Supertype of a raw type is erased. (And there's no such thing as a ParameterizedType with
* some type parameters raw and others not)
*/
@SuppressWarnings({"unchecked", "rawtypes"})
public void testSubclassRawMix() {
class Superclass<T, U extends Number> {
// public T t;
public U u;
}
class Subclass<T> extends Superclass<T, Integer> {
}
use(Superclass.class);
assertEquals(tt(Number.class), getFieldType(Subclass.class, "u"));
Number n = new Subclass().u; // compile check
new Subclass().u = n; // compile check
}
/**
* If a type has no parameters, it doesn't matter that it got erased.
* So even though Middleclass was erased, its supertype is not.
*/
public void testSubclassRawViaUnparameterized() {
class Superclass<T extends Number> implements WithF<T> {
@SuppressWarnings("unused")
public T f;
}
class Middleclass extends Superclass<Integer> {
}
class Subclass<U> extends Middleclass {
}
use(Superclass.class);
// doesn't compile with sun compiler (but does work in eclipse)
// TypeToken<Integer> ft = getStrictF(tt(Subclass.class));
// assertCheckedTypeEquals(tt(Integer.class), ft);
assertEquals(tt(Integer.class), getFieldType(Subclass.class, "f"));
}
// public void testUExtendsListOfExtT() {
// class C<T, U extends List<? extends T>> implements WithF<U> {
// @SuppressWarnings("unused")
// public U f;
// }
//
// // this doesn't compile in eclipse nor with sun compiler, so we hold the compilers hand by adding some steps in between
// // TypeToken<? extends List<? extends String>> ft = getF(new TypeToken<C<? extends String, ?>>(){});
// TypeToken<? extends C<? extends String, ?>> tt = new TypeToken<C<? extends String, ?>>(){};
// TypeToken<? extends C<? extends String, ? extends List<? extends String>>> ttt = tt;
// TypeToken<? extends List<? extends String>> ft = getF(ttt);
//
// checkedTestInexactSupertype(COLLECTION_OF_EXT_STRING, ft);
// }
/**
* Similar for inner types: the outer type of a raw inner type is also erased
*/
@SuppressWarnings("unchecked")
public void testInnerRaw() {
class Outer<T extends Number> {
@SuppressWarnings("rawtypes")
public Inner rawInner;
class Inner<U extends T> {
public T t;
public U u;
}
}
assertEquals(tt(Outer.Inner.class), getFieldType(Outer.class, "rawInner"));
assertEquals(tt(Number.class), getFieldType(Outer.Inner.class, "t"));
assertEquals(tt(Number.class), getFieldType(Outer.Inner.class, "u"));
if (COMPILE_CHECK) {
Number n = new Outer<Integer>().rawInner.t; // compile check
new Outer<Integer>().rawInner.t = n; // compile check
n = new Outer<Integer>().rawInner.u; // compile check
new Outer<Integer>().rawInner.u = n; // compile check
}
}
public void testSuperWildcard() {
Box<? super Integer> b = new Box<Integer>(); // compile check
b.f = new Integer(0); // compile check
testInexactSupertype(getFieldType(new TypeToken<Box<? super Integer>>() {
}, "f"), tt(Integer.class));
TypeToken<? super Integer> ft = getFToken(new TypeToken<Box<? super Integer>>() {
});
checkedTestInexactSupertype(ft, tt(Integer.class));
}
public void testContainment() {
checkedTestInexactSupertypeChain(new TypeToken<List<?>>() {
},
new TypeToken<List<? extends Number>>() {
},
new TypeToken<List<Integer>>() {
});
checkedTestInexactSupertypeChain(new TypeToken<List<?>>() {
},
new TypeToken<List<? super Integer>>() {
},
new TypeToken<List<Object>>() {
});
}
public void testArrays() {
checkedTestExactSuperclassChain(tt(Object[].class), tt(Number[].class), tt(Integer[].class));
testNotSupertypes(new TypeToken<Integer[]>() {
}, new TypeToken<String[]>() {
});
checkedTestExactSuperclassChain(tt(Object.class), tt(Object[].class), tt(Object[][].class));
checkedTestExactSuperclass(tt(Serializable.class), tt(Integer[].class));
checkedTestExactSuperclass(tt(Cloneable[].class), tt(Object[][].class));
}
public void testGenericArrays() {
checkedTestExactSuperclass(new TypeToken<Collection<String>[]>() {
}, new TypeToken<ArrayList<String>[]>() {
});
checkedTestInexactSupertype(new TypeToken<Collection<? extends Number>[]>() {
}, new TypeToken<ArrayList<Integer>[]>() {
});
checkedTestExactSuperclass(tt(RandomAccess[].class), new TypeToken<ArrayList<Integer>[]>() {
});
assertTrue(isSupertype(tt(ArrayList[].class), new TypeToken<ArrayList<Integer>[]>() {
})); // not checked* because we're avoiding the inverse test
}
public void testArrayOfT() {
class C<T> implements WithF<T[]> {
@SuppressWarnings("unused")
public T[] f;
}
use(C.class);
TypeToken<String[]> ft = getStrictF(new TypeToken<C<String>>() {
});
assertCheckedTypeEquals(tt(String[].class), ft);
}
public void testArrayOfListOfT() {
class C<T> implements WithF<List<T>[]> {
@SuppressWarnings("unused")
public List<T>[] f;
}
use(C.class);
TypeToken<List<String>[]> ft = getStrictF(new TypeToken<C<String>>() {
});
assertCheckedTypeEquals(new TypeToken<List<String>[]>() {
}, ft);
}
@SuppressWarnings({"unchecked", "rawtypes"})
public void testArrayRaw() {
class C<T> {
@SuppressWarnings("unused")
public List<String> f;
}
new C().f = new ArrayList<Integer>(); // compile check
assertEquals(tt(List.class), getFieldType(new TypeToken<C>() {
}, "f"));
}
public void testPrimitiveArray() {
testNotSupertypes(tt(double[].class), tt(float[].class));
testNotSupertypes(tt(int[].class), tt(Integer[].class));
}
public void testCapture() {
TypeToken<Box<?>> bw = new TypeToken<Box<?>>() {
};
TypeToken<?> capture1 = getF(bw);
TypeToken<?> capture2 = getF(bw);
assertNotEquals(capture1.getType(), capture2.getType());
// if these were equal, this would be valid:
// Box<?> b1 = new Box<Integer>();
// Box<?> b2 = new Box<String>();
// b1.f = b2.f;
// but the capture is still equal to itself
assertEquals(capture1, capture1);
}
public void testCaptureBeforeReplaceSupertype() {
class C<T> extends ArrayList<List<T>> {
}
use(C.class);
testNotSupertypes(LIST_OF_LIST_OF_EXT_STRING, new TypeToken<C<? extends String>>() {
});
// if it was a supertype, this would be valid:
// List<List<? extends String>> o = new C<? extends String>();
}
public void testGraphCapture() throws NoSuchFieldException {
Field e = Node.class.getField("e");
Field n = Edge.class.getField("n");
TypeToken<?> node = new TypeToken<Node<?, ?>>() {
};
TypeToken<?> edgeOfNode = getFieldType(node.getType(), e);
TypeToken<?> nodeOfEdgeOfNode = getFieldType(edgeOfNode.getType(), n);
TypeToken<?> edgeOfNodeOfEdgeOfNode = getFieldType(nodeOfEdgeOfNode.getType(), e);
assertEquals(edgeOfNode.getType(), edgeOfNodeOfEdgeOfNode.getType());
assertNotEquals(node, nodeOfEdgeOfNode); // node is not captured, nodeOfEdgeOfNode is
}
/**
* This test shows the need for capturing in isSupertype: the type parameters aren't contained,
* but the capture of them is because of the bound on type variable
*/
public void testCaptureContainment() {
class C<T extends Number> {
}
use(C.class);
checkedTestMutualSupertypes(new TypeToken<C<? extends Number>>() {
},
new TypeToken<C<?>>() {
});
}
public void testCaptureContainmentViaOtherParam() {
class C<T extends Number, S extends List<T>> {
}
C<? extends Number, ? extends List<? extends Number>> c1 = null;
C<? extends Number, ?> c2 = null;
c1 = c2;
c2 = c1;
testMutualSupertypes(new TypeToken<C<? extends Number, ? extends List<? extends Number>>>() {
},
new TypeToken<C<? extends Number, ?>>() {
});
}
// Issue #4
public void testClassInMethod() throws NoSuchFieldException {
class Outer<T> {
Class<?> getInnerClass() {
class Inner implements WithF<T> {
@SuppressWarnings("unused")
public T f;
}
return Inner.class;
}
}
Class<?> inner = new Outer<String>().getInnerClass();
assertEquals(WithF.class, GenericTypeReflector.getExactSuperType(inner, WithF.class));
assertEquals(Object.class, GenericTypeReflector.getExactFieldType(inner.getField("f"), inner));
}
/**
* Marker interface to mark the type of the field f.
* Note: we could use a method instead of a field, so the method could be in the interface,
* enforcing correct usage, but that would influence the actual test too much.
*/
interface WithF<T> {
}
/**
* Variant on WithF, where the type parameter is a TypeToken.
* TODO do we really need this?
*/
interface WithFToken<T extends TypeToken<?>> {
}
public interface StringList extends List<String> {
}
public interface ListOfListOfT<T> extends List<List<T>> {
}
public interface ListOfListOfT_String extends ListOfListOfT<String> {
}
public interface ListOfListOfString extends List<List<String>> {
}
// public void testGraphWildcard() {
// TypeToken<? extends List<? extends Edge<? extends Node<?,?>,?>>> ft = getF(new TypeToken<Node<?, ?>>(){});
// testInexactSupertype(new TypeToken<List<? extends Edge<? extends Node<?,?>,?>>>(){}, ft);
// }
public interface ListOfListOfExtT<T> extends List<List<? extends T>> {
}
class Box<T> implements WithF<T>, WithFToken<TypeToken<T>> {
public T f;
}
class Node<N extends Node<N, E>, E extends Edge<N, E>> implements WithF<List<E>> {
public List<E> f;
public E e;
}
class Edge<N extends Node<N, E>, E extends Edge<N, E>> implements WithF<List<N>> {
public List<N> f;
public N n;
}
}
| apache-2.0 |
odnoklassniki/apache-cassandra | src/java/org/apache/cassandra/db/proc/RemoveDeletedRowProcessor.java | 2159 | /*
* @(#) RemoveTombstonesRowProcessor.java
* Created May 25, 2012 by oleg
* (C) ONE, SIA
*/
package org.apache.cassandra.db.proc;
import java.util.Properties;
import org.apache.cassandra.db.ColumnFamily;
import org.apache.cassandra.db.ColumnFamilyStore;
import org.apache.cassandra.db.DecoratedKey;
/**
* This processor removes tombstones after GCGracePeriod expiration
*
* @author Oleg Anastasyev<oa@hq.one.lv>
*
*/
public class RemoveDeletedRowProcessor implements IRowProcessor
{
/**
* removes tombstones created earlier than this millis
*/
private int gcBefore;
public RemoveDeletedRowProcessor(int gcBefore)
{
this.gcBefore = gcBefore;
}
/* (non-Javadoc)
* @see org.apache.cassandra.db.proc.IRowProcessor#setConfiguration(org.w3c.dom.Node)
*/
@Override
public void setConfiguration(Properties config)
{
}
/* (non-Javadoc)
* @see org.apache.cassandra.db.proc.IRowProcessor#setColumnFamilyStore(org.apache.cassandra.db.ColumnFamilyStore)
*/
@Override
public void setColumnFamilyStore(ColumnFamilyStore cfs)
{
}
/* (non-Javadoc)
* @see org.apache.cassandra.db.proc.IRowProcessor#shouldProcessIncomplete()
*/
@Override
public boolean shouldProcessIncomplete()
{
return false;
}
/* (non-Javadoc)
* @see org.apache.cassandra.db.proc.IRowProcessor#shouldProcessUnchanged()
*/
@Override
public boolean shouldProcessUnchanged()
{
return false;
}
/* (non-Javadoc)
* @see org.apache.cassandra.db.proc.IRowProcessor.shouldProcessEmpty()
*/
@Override
public boolean shouldProcessEmpty()
{
return false;
}
/* (non-Javadoc)
* @see org.apache.cassandra.db.proc.IRowProcessor#process(org.apache.cassandra.db.DecoratedKey, org.apache.cassandra.db.ColumnFamily, boolean)
*/
@Override
public ColumnFamily process(DecoratedKey key, ColumnFamily columns,
boolean incomplete)
{
assert !incomplete;
return ColumnFamilyStore.removeDeleted(columns, gcBefore);
}
}
| apache-2.0 |
zouzhberk/ambaridemo | demo-server/src/main/java/org/apache/ambari/server/serveraction/AbstractServerAction.java | 7061 | /*
* 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.ambari.server.serveraction;
import org.apache.ambari.server.RoleCommand;
import org.apache.ambari.server.actionmanager.ExecutionCommandWrapper;
import org.apache.ambari.server.actionmanager.HostRoleCommand;
import org.apache.ambari.server.actionmanager.HostRoleStatus;
import org.apache.ambari.server.agent.CommandReport;
import org.apache.ambari.server.agent.ExecutionCommand;
import org.apache.ambari.server.utils.StageUtils;
import java.util.Collections;
import java.util.Map;
/**
* AbstractServerActionImpl is an abstract implementation of a ServerAction.
* <p/>
* This abstract implementation provides common facilities for all ServerActions, such as
* maintaining the ExecutionCommand and HostRoleCommand properties. It also provides a convenient
* way to generate CommandReports for reporting status.
*/
public abstract class AbstractServerAction implements ServerAction {
/**
* The ExecutionCommand containing data related to this ServerAction implementation
*/
private ExecutionCommand executionCommand = null;
/**
* The HostRoleCommand containing data related to this ServerAction implementation
*/
private HostRoleCommand hostRoleCommand = null;
/**
* The ActionLog that used to log execution progress of ServerAction
*/
protected ActionLog actionLog = new ActionLog();
@Override
public ExecutionCommand getExecutionCommand() {
return this.executionCommand;
}
@Override
public void setExecutionCommand(ExecutionCommand executionCommand) {
this.executionCommand = executionCommand;
}
@Override
public HostRoleCommand getHostRoleCommand() {
return this.hostRoleCommand;
}
@Override
public void setHostRoleCommand(HostRoleCommand hostRoleCommand) {
this.hostRoleCommand = hostRoleCommand;
}
/**
* Creates a CommandReport used to report back to Ambari the status of this ServerAction.
*
* @param exitCode an integer value declaring the exit code for this action - 0 typically
* indicates success.
* @param status a HostRoleStatus indicating the status of this action
* @param structuredOut a String containing the (typically) JSON-formatted data representing the
* output from this action (this data is stored in the database, along with
* the command status)
* @param stdout A string containing the data from the standard out stream (this data is stored in
* the database, along with the command status)
* @param stderr A string containing the data from the standard error stream (this data is stored
* in the database, along with the command status)
* @return the generated CommandReport, or null if the HostRoleCommand or ExecutionCommand
* properties are missing
*/
protected CommandReport createCommandReport(int exitCode, HostRoleStatus status, String structuredOut,
String stdout, String stderr) {
CommandReport report = null;
if (hostRoleCommand != null) {
if (executionCommand == null) {
ExecutionCommandWrapper wrapper = hostRoleCommand.getExecutionCommandWrapper();
if (wrapper != null) {
executionCommand = wrapper.getExecutionCommand();
}
}
if (executionCommand != null) {
RoleCommand roleCommand = executionCommand.getRoleCommand();
report = new CommandReport();
report.setActionId(StageUtils.getActionId(hostRoleCommand.getRequestId(), hostRoleCommand.getStageId()));
report.setClusterName(executionCommand.getClusterName());
report.setConfigurationTags(executionCommand.getConfigurationTags());
report.setRole(executionCommand.getRole());
report.setRoleCommand((roleCommand == null) ? null : roleCommand.toString());
report.setServiceName(executionCommand.getServiceName());
report.setTaskId(executionCommand.getTaskId());
report.setStructuredOut(structuredOut);
report.setStdErr((stderr == null) ? "" : stderr);
report.setStdOut((stdout == null) ? "" : stdout);
report.setStatus((status == null) ? null : status.toString());
report.setExitCode(exitCode);
}
}
return report;
}
/**
* Returns the command parameters value from the ExecutionCommand
* <p/>
* The returned map should be assumed to be read-only.
*
* @return the (assumed read-only) command parameters value from the ExecutionCommand
*/
protected Map<String, String> getCommandParameters() {
if (executionCommand == null) {
return Collections.emptyMap();
} else {
return executionCommand.getCommandParams();
}
}
/**
* Attempts to safely retrieve a property with the specified name from the this action's relevant
* command parameters Map.
*
* @param propertyName a String declaring the name of the item from commandParameters to retrieve
* @return the value of the requested property, or null if not found or set
*/
protected String getCommandParameterValue(String propertyName) {
Map<String, String> commandParameters = getCommandParameters();
return (commandParameters == null) ? null : commandParameters.get(propertyName);
}
/**
* Returns the configurations value from the ExecutionCommand
* <p/>
* The returned map should be assumed to be read-only.
*
* @return the (assumed read-only) configurations value from the ExecutionCommand
*/
protected Map<String, Map<String, String>> getConfigurations() {
return (executionCommand == null) ? Collections.<String, Map<String, String>>emptyMap() : executionCommand.getConfigurations();
}
/**
* Returns the requested configuration Map from the ExecutionCommand
* <p/>
* The returned map should be assumed to be read-only.
*
* @param configurationName a String indicating the name of the configuration data to retrieve
* @return the (assumed read-only) configuration Map from the ExecutionCommand, or null if not available
*/
protected Map<String, String> getConfiguration(String configurationName) {
return getConfigurations().get(configurationName);
}
}
| apache-2.0 |
jkatzer/jkatzer-wave | src/org/waveprotocol/wave/examples/client/webclient/client/events/WaveSelectionEvent.java | 1266 | /**
* Copyright 2010 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 org.waveprotocol.wave.examples.client.webclient.client.events;
import com.google.gwt.event.shared.GwtEvent;
import org.waveprotocol.wave.model.id.WaveId;
public class WaveSelectionEvent extends
GwtEvent<WaveSelectionEventHandler> {
public static final GwtEvent.Type<WaveSelectionEventHandler> TYPE = new GwtEvent.Type<WaveSelectionEventHandler>();
private final WaveId id;
public WaveSelectionEvent(WaveId id) {
this.id = id;
}
@Override
public Type<WaveSelectionEventHandler> getAssociatedType() {
return TYPE;
}
@Override
protected void dispatch(WaveSelectionEventHandler handler) {
handler.onSelection(id);
}
}
| apache-2.0 |
ConsecroMUD/ConsecroMUD | com/suscipio_solutions/consecro_mud/Abilities/Songs/Dance_Manipuri.java | 2651 | package com.suscipio_solutions.consecro_mud.Abilities.Songs;
import java.util.Vector;
import com.suscipio_solutions.consecro_mud.Abilities.interfaces.Ability;
import com.suscipio_solutions.consecro_mud.Common.interfaces.CMMsg;
import com.suscipio_solutions.consecro_mud.Locales.interfaces.Room;
import com.suscipio_solutions.consecro_mud.MOBS.interfaces.MOB;
import com.suscipio_solutions.consecro_mud.core.CMLib;
import com.suscipio_solutions.consecro_mud.core.CMath;
import com.suscipio_solutions.consecro_mud.core.interfaces.Environmental;
import com.suscipio_solutions.consecro_mud.core.interfaces.Physical;
import com.suscipio_solutions.consecro_mud.core.interfaces.Tickable;
@SuppressWarnings("rawtypes")
public class Dance_Manipuri extends Dance
{
@Override public String ID() { return "Dance_Manipuri"; }
private final static String localizedName = CMLib.lang().L("Manipuri");
@Override public String name() { return localizedName; }
@Override public int abstractQuality(){ return Ability.QUALITY_BENEFICIAL_SELF;}
@Override protected String danceOf(){return name()+" Dance";}
protected Room lastRoom=null;
protected int count=3;
@Override
public boolean tick(Tickable ticking, int tickID)
{
if(!super.tick(ticking,tickID))
return false;
if(!(affected instanceof MOB))
return true;
final MOB mob=(MOB)affected;
if(mob.location()!=lastRoom)
{
count=3+getXLEVELLevel(invoker());
lastRoom=mob.location();
}
else
count--;
return true;
}
@Override
public boolean okMessage(final Environmental myHost, final CMMsg msg)
{
final MOB mob=(MOB)affected;
if(((msg.targetMajor()&CMMsg.MASK_MALICIOUS)>0)
&&(!CMath.bset(msg.sourceMajor(),CMMsg.MASK_ALWAYS))
&&(mob.location()!=null)
&&((msg.amITarget(mob)))
&&((count>0)||(lastRoom==null)||(lastRoom!=mob.location())))
{
final MOB target=(MOB)msg.target();
if((!target.isInCombat())
&&(msg.source().getVictim()!=target))
{
msg.source().tell(L("You feel like letting @x1 be for awhile.",target.name(msg.source())));
if(target.getVictim()==msg.source())
{
target.makePeace();
target.setVictim(null);
}
return false;
}
}
return super.okMessage(myHost,msg);
}
@Override
public int castingQuality(MOB mob, Physical target)
{
if(mob!=null)
{
if(mob.isInCombat())
return Ability.QUALITY_INDIFFERENT;
}
return super.castingQuality(mob,target);
}
@Override
public boolean invoke(MOB mob, Vector commands, Physical givenTarget, boolean auto, int asLevel)
{
count=3;
if(!super.invoke(mob,commands,givenTarget,auto,asLevel))
return false;
count=3;
return true;
}
}
| apache-2.0 |
DarrenAtherton49/MaterialCV | app/src/main/java/com/atherton/darren/presentation/main/MainViewPagerAdapter.java | 1033 | package com.atherton.darren.presentation.main;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import java.util.ArrayList;
import java.util.List;
import javax.inject.Inject;
public class MainViewPagerAdapter extends FragmentPagerAdapter {
private final List<Fragment> fragmentList = new ArrayList<>();
private final List<String> fragmentTitleList = new ArrayList<>();
@Inject
public MainViewPagerAdapter(FragmentManager fm) {
super(fm);
}
@Override public int getCount() {
return fragmentList.size();
}
@Override public Fragment getItem(int position) {
return fragmentList.get(position);
}
public void addFragment(Fragment fragment, String fragmentTitle) {
fragmentList.add(fragment);
fragmentTitleList.add(fragmentTitle);
}
@Override
public CharSequence getPageTitle(int position) {
return fragmentTitleList.get(position);
}
}
| apache-2.0 |
oehme/analysing-gradle-performance | commons/src/main/java/org/gradle/test/performance/mediummonolithicjavaproject/p2/Production44.java | 1887 | package org.gradle.test.performance.mediummonolithicjavaproject.p2;
public class Production44 {
private String property0;
public String getProperty0() {
return property0;
}
public void setProperty0(String value) {
property0 = value;
}
private String property1;
public String getProperty1() {
return property1;
}
public void setProperty1(String value) {
property1 = value;
}
private String property2;
public String getProperty2() {
return property2;
}
public void setProperty2(String value) {
property2 = value;
}
private String property3;
public String getProperty3() {
return property3;
}
public void setProperty3(String value) {
property3 = value;
}
private String property4;
public String getProperty4() {
return property4;
}
public void setProperty4(String value) {
property4 = value;
}
private String property5;
public String getProperty5() {
return property5;
}
public void setProperty5(String value) {
property5 = value;
}
private String property6;
public String getProperty6() {
return property6;
}
public void setProperty6(String value) {
property6 = value;
}
private String property7;
public String getProperty7() {
return property7;
}
public void setProperty7(String value) {
property7 = value;
}
private String property8;
public String getProperty8() {
return property8;
}
public void setProperty8(String value) {
property8 = value;
}
private String property9;
public String getProperty9() {
return property9;
}
public void setProperty9(String value) {
property9 = value;
}
} | apache-2.0 |
sakebook/android-sample-cardboard | app/src/androidTest/java/com/sakebook/android/sample/cardboardsample/ApplicationTest.java | 374 | package com.sakebook.android.sample.cardboardsample;
import android.app.Application;
import android.test.ApplicationTestCase;
/**
* <a href="http://d.android.com/tools/testing/testing_android.html">Testing Fundamentals</a>
*/
public class ApplicationTest extends ApplicationTestCase<Application> {
public ApplicationTest() {
super(Application.class);
}
} | apache-2.0 |
everttigchelaar/camel-svn | components/camel-spring/src/test/java/org/apache/camel/spring/config/NamespacePrefixTest.java | 1725 | /**
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.camel.spring.config;
import org.apache.camel.EndpointInject;
import org.apache.camel.ProducerTemplate;
import org.apache.camel.component.mock.MockEndpoint;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit38.AbstractJUnit38SpringContextTests;
/**
* @version
*/
@ContextConfiguration
public class NamespacePrefixTest extends AbstractJUnit38SpringContextTests {
protected String body = "Hello";
@Autowired
private ProducerTemplate template;
@EndpointInject(uri = "mock:results")
private MockEndpoint endpoint;
public void testAssertThatInjectionWorks() throws Exception {
assertNotNull("Bean should be injected", template);
assertNotNull("endpoint should be injected", endpoint);
}
} | apache-2.0 |
dagnir/aws-sdk-java | aws-java-sdk-codecommit/src/main/java/com/amazonaws/services/codecommit/model/BranchInfo.java | 5296 | /*
* 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.codecommit.model;
import java.io.Serializable;
import javax.annotation.Generated;
import com.amazonaws.protocol.StructuredPojo;
import com.amazonaws.protocol.ProtocolMarshaller;
/**
* <p>
* Returns information about a branch.
* </p>
*
* @see <a href="http://docs.aws.amazon.com/goto/WebAPI/codecommit-2015-04-13/BranchInfo" target="_top">AWS API
* Documentation</a>
*/
@Generated("com.amazonaws:aws-java-sdk-code-generator")
public class BranchInfo implements Serializable, Cloneable, StructuredPojo {
/**
* <p>
* The name of the branch.
* </p>
*/
private String branchName;
/**
* <p>
* The ID of the last commit made to the branch.
* </p>
*/
private String commitId;
/**
* <p>
* The name of the branch.
* </p>
*
* @param branchName
* The name of the branch.
*/
public void setBranchName(String branchName) {
this.branchName = branchName;
}
/**
* <p>
* The name of the branch.
* </p>
*
* @return The name of the branch.
*/
public String getBranchName() {
return this.branchName;
}
/**
* <p>
* The name of the branch.
* </p>
*
* @param branchName
* The name of the branch.
* @return Returns a reference to this object so that method calls can be chained together.
*/
public BranchInfo withBranchName(String branchName) {
setBranchName(branchName);
return this;
}
/**
* <p>
* The ID of the last commit made to the branch.
* </p>
*
* @param commitId
* The ID of the last commit made to the branch.
*/
public void setCommitId(String commitId) {
this.commitId = commitId;
}
/**
* <p>
* The ID of the last commit made to the branch.
* </p>
*
* @return The ID of the last commit made to the branch.
*/
public String getCommitId() {
return this.commitId;
}
/**
* <p>
* The ID of the last commit made to the branch.
* </p>
*
* @param commitId
* The ID of the last commit made to the branch.
* @return Returns a reference to this object so that method calls can be chained together.
*/
public BranchInfo withCommitId(String commitId) {
setCommitId(commitId);
return this;
}
/**
* Returns a string representation of this object; useful for testing and debugging.
*
* @return A string representation of this object.
*
* @see java.lang.Object#toString()
*/
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("{");
if (getBranchName() != null)
sb.append("BranchName: ").append(getBranchName()).append(",");
if (getCommitId() != null)
sb.append("CommitId: ").append(getCommitId());
sb.append("}");
return sb.toString();
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (obj instanceof BranchInfo == false)
return false;
BranchInfo other = (BranchInfo) obj;
if (other.getBranchName() == null ^ this.getBranchName() == null)
return false;
if (other.getBranchName() != null && other.getBranchName().equals(this.getBranchName()) == false)
return false;
if (other.getCommitId() == null ^ this.getCommitId() == null)
return false;
if (other.getCommitId() != null && other.getCommitId().equals(this.getCommitId()) == false)
return false;
return true;
}
@Override
public int hashCode() {
final int prime = 31;
int hashCode = 1;
hashCode = prime * hashCode + ((getBranchName() == null) ? 0 : getBranchName().hashCode());
hashCode = prime * hashCode + ((getCommitId() == null) ? 0 : getCommitId().hashCode());
return hashCode;
}
@Override
public BranchInfo clone() {
try {
return (BranchInfo) super.clone();
} catch (CloneNotSupportedException e) {
throw new IllegalStateException("Got a CloneNotSupportedException from Object.clone() " + "even though we're Cloneable!", e);
}
}
@com.amazonaws.annotation.SdkInternalApi
@Override
public void marshall(ProtocolMarshaller protocolMarshaller) {
com.amazonaws.services.codecommit.model.transform.BranchInfoMarshaller.getInstance().marshall(this, protocolMarshaller);
}
}
| apache-2.0 |
rvarago/tracking2u | src/br/edu/ufabc/tracking2u/entity/Entidade.java | 584 | package br.edu.ufabc.tracking2u.entity;
import java.io.Serializable;
import java.util.Objects;
/**
* @author rvarago
*/
public abstract class Entidade implements Serializable {
private static final long serialVersionUID = 1L;
private Long id;
public Long getId() {
return this.id;
}
public void setId(Long id) {
this.id = id;
}
@Override
public boolean equals(Object obj) {
if (!(obj instanceof Entidade)) {
return false;
}
return Objects.equals(this.id, ((Entidade) obj).id);
}
@Override
public int hashCode() {
return Objects.hash(this.id);
}
}
| apache-2.0 |
raner/projo | projo-template-generation/src/main/java/$package/$InterfaceTemplate.java | 1850 | // //
// Copyright 2019 - 2021 Mirko Raner //
// //
// 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 $package;
/* *#**#/
#foreach ($import in $imports)
import $import;
#end
/* */
/**
*#*
* The {@link $package.$InterfaceTemplate} interface provides the Velocity template for Projo's interface scraping
* mechanism. The class is both a completely valid Java class and a valid Apache Velocity template (which is why
* the specific definition of its template references may appear a little funky at first glance), though it is
* currently treated as a resource, not a Java source.
*#
* $javadoc
*#*
* @author Mirko Raner
*#
**/
/* *#**#/
$generatedBy
/* */
public interface $InterfaceTemplate
{
/* *#**#/
#foreach ($method in $methods)
$method;
#end
/* */
}
| apache-2.0 |
samebug/samebug-eclipse-plugin | bundles/com.samebug.clients.eclipse.search/src/com/samebug/clients/http/entities/user/User.java | 1012 | /*
* Copyright 2017 Samebug, 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
* <p>
* http://www.apache.org/licenses/LICENSE-2.0
* <p>
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.samebug.clients.http.entities.user;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.net.URL;
public abstract class User {
private URL avatarUrl;
@NotNull
public abstract String getDisplayName();
@Nullable
public final URL getAvatarUrl() {
return avatarUrl;
}
@Nullable
public abstract URL getUrl();
}
| apache-2.0 |
vyouzhis/oc | src/com/lib/plug/echarts/echarts.java | 2916 | package com.lib.plug.echarts;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import com.github.abel533.echarts.axis.CategoryAxis;
import com.github.abel533.echarts.axis.ValueAxis;
import com.github.abel533.echarts.code.Magic;
import com.github.abel533.echarts.code.Tool;
import com.github.abel533.echarts.code.Trigger;
import com.github.abel533.echarts.feature.MagicType;
import com.github.abel533.echarts.json.GsonOption;
import com.github.abel533.echarts.series.Line;
/**
* @since old
* @author
*
*/
public class echarts {
public final static String Center ="center";
public List<String> trigger;
public List<String> formatter;
private String legend_y = "bottom";
private List<String> legendData;
public echarts() {
// TODO Auto-generated constructor stub
trigger = new ArrayList<>();
trigger.add("axis");
trigger.add("item");
formatter = new ArrayList<>();
formatter.add("{a} <br/>{b} : {c} ({d}%)");
formatter.add("{a} <br/>{b} : ({c}%)");
}
public String BuildBar() {
trigger.get(0);
return null;
}
public String BuildLine() {
trigger.get(0);
return null;
}
public String BuildPie() {
trigger.get(1);
return null;
}
public String BuildScatter() {
trigger.get(0);
return null;
}
public String BuildFunnel() {
trigger.get(1);
return null;
}
public Map<String, String> Title(String title, String subtext, String x) {
Map<String, String> t = new HashMap<String, String>();
t.put("text", title);
t.put("subtext", subtext);
t.put("x", x);
return t;
}
public List<String> getLegendData() {
return legendData;
}
public void setLegendData(List<String> legendData) {
this.legendData = legendData;
}
public String getResult() {
GsonOption option = new GsonOption();
option.legend("高度(km)与气温(°C)变化关系");
option.toolbox().show(true).feature(Tool.mark, Tool.dataView, new MagicType(Magic.line, Magic.bar), Tool.restore, Tool.saveAsImage);
option.calculable(true);
option.tooltip().trigger(Trigger.axis).formatter("Temperature : <br/>{b}km : {c}°C");
ValueAxis valueAxis = new ValueAxis();
valueAxis.axisLabel().formatter("{value} °C");
option.xAxis(valueAxis);
CategoryAxis categoryAxis = new CategoryAxis();
categoryAxis.axisLine().onZero(false);
categoryAxis.axisLabel().formatter("{value} km");
categoryAxis.boundaryGap(false);
categoryAxis.data(0, 10, 20, 30, 40, 50, 60, 70, 80);
option.yAxis(categoryAxis);
Line line = new Line();
line.smooth(true).name("高度(km)与气温(°C)变化关系").data(15, -50, -56.5, -46.5, -22.1, -2.5, -27.7, -55.7, -76.5).itemStyle().normal().lineStyle().shadowColor("rgba(0,0,0,0.4)");
option.series(line);
//option.exportToHtml("line5.html");
//option.view();
return option.toString();
}
}
| apache-2.0 |
BeholderTAF/beholder | src/main/java/br/ufmg/dcc/saotome/beholder/ui/event/Clickable.java | 1215 | /* Copyright 2014 Ícaro Clever da Fonseca Braga
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 br.ufmg.dcc.saotome.beholder.ui.event;
/** Components that implements this interface starts a event when it's
* clicked by a user.
* @author Ícaro Clever F. Braga (icaroclever@gmail.com)
*/
public interface Clickable {
/** An action is executed when this method is called. It represents
* when a user clicks on the component by the user.
*/
void click();
}
| apache-2.0 |
tomkren/pikater | src/org/pikater/core/ontology/subtrees/recommend/Recommend.java | 936 | package org.pikater.core.ontology.subtrees.recommend;
import org.pikater.core.ontology.subtrees.data.Datas;
import org.pikater.core.ontology.subtrees.management.Agent;
import jade.content.AgentAction;
import org.pikater.core.ontology.subtrees.task.Evaluation;
public class Recommend implements AgentAction {
/**
*
*/
private static final long serialVersionUID = -4556943676301959461L;
private Datas datas;
private Agent recommender;
private Evaluation previousError;
public Datas getDatas() {
return datas;
}
public void setDatas(Datas datas) {
this.datas = datas;
}
public Agent getRecommender() {
return recommender;
}
public void setRecommender(Agent recommender) {
this.recommender = recommender;
}
public Evaluation getPreviousError() {
return previousError;
}
public void setPreviousError(Evaluation previousError) {
this.previousError = previousError;
}
}
| apache-2.0 |
liftting/algorithm-learn | learn-leet/easy/list/ListNode.java | 184 | package easy.list;
/**
* Created by wm on 16/3/15.
*/
public class ListNode {
public int val;
public ListNode next;
public ListNode(int x) {
val = x;
}
}
| apache-2.0 |
erichwang/presto | presto-main/src/main/java/io/prestosql/sql/planner/TypeAnalyzer.java | 2648 | /*
* 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.prestosql.sql.planner;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.ImmutableSet;
import io.prestosql.Session;
import io.prestosql.execution.warnings.WarningCollector;
import io.prestosql.metadata.Metadata;
import io.prestosql.security.AllowAllAccessControl;
import io.prestosql.spi.type.Type;
import io.prestosql.sql.parser.SqlParser;
import io.prestosql.sql.tree.Expression;
import io.prestosql.sql.tree.NodeRef;
import javax.inject.Inject;
import java.util.Map;
import static io.prestosql.sql.analyzer.ExpressionAnalyzer.analyzeExpressions;
/**
* This class is to facilitate obtaining the type of an expression and its subexpressions
* during planning (i.e., when interacting with IR expression). It will eventually get
* removed when we split the AST from the IR and we encode the type directly into IR expressions.
*/
public class TypeAnalyzer
{
private final SqlParser parser;
private final Metadata metadata;
@Inject
public TypeAnalyzer(SqlParser parser, Metadata metadata)
{
this.parser = parser;
this.metadata = metadata;
}
public Map<NodeRef<Expression>, Type> getTypes(Session session, TypeProvider inputTypes, Iterable<Expression> expressions)
{
return analyzeExpressions(session,
metadata,
user -> ImmutableSet.of(),
new AllowAllAccessControl(),
parser,
inputTypes,
expressions,
ImmutableMap.of(),
WarningCollector.NOOP,
false)
.getExpressionTypes();
}
public Map<NodeRef<Expression>, Type> getTypes(Session session, TypeProvider inputTypes, Expression expression)
{
return getTypes(session, inputTypes, ImmutableList.of(expression));
}
public Type getType(Session session, TypeProvider inputTypes, Expression expression)
{
return getTypes(session, inputTypes, expression).get(NodeRef.of(expression));
}
}
| apache-2.0 |
99soft/junice | src/main/java/org/nnsoft/guice/junice/mock/framework/EasyMockFramework.java | 1696 | package org.nnsoft.guice.junice.mock.framework;
/*
* Copyright 2010-2012 The 99 Software Foundation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import org.easymock.classextension.EasyMock;
import org.nnsoft.guice.junice.annotation.MockObjType;
import org.nnsoft.guice.junice.mock.MockEngine;
/**
* Specifies the Easy-Mock Framework.
*
* @see MockEngine
*/
public class EasyMockFramework
implements MockEngine
{
/**
* {@inheritDoc}
*/
public void resetMock( Object... objects )
{
EasyMock.reset( objects );
}
/**
* {@inheritDoc}
*/
public <T> T createMock( Class<T> cls, MockObjType type )
{
switch ( type )
{
case EASY_MOCK_NICE:
return EasyMock.createNiceMock( cls );
case EASY_MOCK_STRICT:
return EasyMock.createStrictMock( cls );
case EASY_MOCK_NORMAL:
case DEFAULT:
return EasyMock.createMock( cls );
default:
throw new IllegalArgumentException( "Unsupported mock type '" + type + "' for Easy-Mock Framework." );
}
}
}
| apache-2.0 |
pipipark/Tool | PPPark-Cache/src/main/java/com/pipipark/cache/client/CacheClientScaner.java | 213 | package com.pipipark.cache.client;
import com.pipipark.scaner.core.ClassesScaner;
@SuppressWarnings({ "serial", "rawtypes" })
public class CacheClientScaner extends ClassesScaner<PPParkCacheClient> {
}
| apache-2.0 |
Salaboy/uberfire | uberfire-extensions/uberfire-layout-editor/uberfire-layout-editor-client/src/main/java/org/uberfire/ext/layout/editor/client/components/rows/EmptyDropRowView.java | 1473 | package org.uberfire.ext.layout.editor.client.components.rows;
import com.google.gwt.event.dom.client.DragLeaveEvent;
import com.google.gwt.event.dom.client.DragOverEvent;
import com.google.gwt.event.dom.client.DropEvent;
import com.google.gwt.user.client.DOM;
import com.google.gwt.user.client.Element;
import com.google.gwt.user.client.ui.Composite;
import org.jboss.errai.ui.shared.api.annotations.DataField;
import org.jboss.errai.ui.shared.api.annotations.EventHandler;
import org.jboss.errai.ui.shared.api.annotations.Templated;
import org.uberfire.client.mvp.UberView;
import javax.enterprise.context.Dependent;
@Dependent
@Templated
public class EmptyDropRowView extends Composite
implements UberView<EmptyDropRow>,
EmptyDropRow.View {
private EmptyDropRow presenter;
@DataField
private Element row = DOM.createDiv();
@Override
public void init( EmptyDropRow presenter ) {
this.presenter = presenter;
}
@EventHandler( "row" )
public void dragOverRow( DragOverEvent e ) {
e.preventDefault();
row.addClassName( "rowDropPreview" );
}
@EventHandler( "row" )
public void dragLeaveUpper( DragLeaveEvent e ) {
e.preventDefault();
row.removeClassName( "rowDropPreview" );
}
@EventHandler( "row" )
public void dropRow( DropEvent e ) {
e.preventDefault();
row.removeClassName( "rowDropPreview" );
presenter.drop( e );
}
}
| apache-2.0 |
mbalassi/streaming-performance | src/main/java/org/apache/flink/streaming/performance/legacy/latency/wordcount/WordCountLatencyCounter.java | 1927 | /**
*
* 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.flink.streaming.performance.legacy.latency.wordcount;
import java.util.HashMap;
import java.util.Map;
import org.apache.flink.api.common.functions.RichMapFunction;
import org.apache.flink.api.java.tuple.Tuple2;
import org.apache.flink.api.java.tuple.Tuple3;
public class WordCountLatencyCounter extends RichMapFunction<Tuple2<String, Long>, Tuple3<String, Integer, Long>> {
private static final long serialVersionUID = 1L;
private Map<String, Integer> wordCounts = new HashMap<String, Integer>();
private String word = "";
private Integer count = 0;
private Tuple3<String, Integer, Long> outTuple = new Tuple3<String, Integer, Long>();
// Increments the counter of the occurrence of the input word
@Override
public Tuple3<String, Integer, Long> map(Tuple2<String, Long> inTuple) throws Exception {
word = inTuple.f0;
if (wordCounts.containsKey(word)) {
count = wordCounts.get(word) + 1;
wordCounts.put(word, count);
} else {
count = 1;
wordCounts.put(word, 1);
}
outTuple.f0 = word;
outTuple.f1 = count;
outTuple.f2 = inTuple.f1;
return outTuple;
}
}
| apache-2.0 |
already/seedweb | seedweb-frame/src/main/java/com/kifanle/seedweb/context/MethodContext.java | 1670 | package com.kifanle.seedweb.context;
import java.lang.reflect.Method;
import java.util.LinkedHashSet;
/**
* 记录spring代理情况下proxy方法信息
* @author zhouqin
*
*/
public class MethodContext {
private String path;
private String clzName;
private Method proxyMethod;
private Object proxyObject;
private String methodName;
private LinkedHashSet<String> restParams = new LinkedHashSet<String>();
public String getPath() {
return path;
}
public MethodContext setPath(String path) {
this.path = path;
return this;
}
public String getClzName() {
return clzName;
}
public MethodContext setClzName(String clzName) {
this.clzName = clzName;
return this;
}
public Method getProxyMethod() {
return proxyMethod;
}
public MethodContext setProxyMethod(Method proxyMethod) {
this.proxyMethod = proxyMethod;
return this;
}
public Object getProxyObject() {
return proxyObject;
}
public MethodContext setProxyObject(Object proxyObject) {
this.proxyObject = proxyObject;
return this;
}
public String getMethodName() {
return methodName;
}
public MethodContext setMethodName(String methodName) {
this.methodName = methodName;
return this;
}
public LinkedHashSet<String> getRestParams() {
return restParams;
}
public MethodContext setRestParams(LinkedHashSet<String> restParams) {
this.restParams = restParams;
return this;
}
private String steps;
public String getSteps() {
return steps;
}
public MethodContext setSteps(String steps) {
this.steps = steps;
return this;
}
}
| apache-2.0 |
bingoohuang/npf-blackcat | npf-mock/src/main/java/com/ailk/ecs/esf/service/microflow/wiring/DaoSqlMapAutoWiring.java | 530 | package com.ailk.ecs.esf.service.microflow.wiring;
import com.ailk.ecs.esf.service.microflow.annotations.DaoSqlMap;
import java.lang.annotation.Annotation;
import java.lang.reflect.Field;
/**
* DAO标注字段注入.
*
* @author Bingoo Huang
*
*/
public class DaoSqlMapAutoWiring implements FieldAutoWirable {
@Override
public void autoWiring(Object object, Class<?> cls, Field field) {
}
@Override
public Class<? extends Annotation> getAnnotationClass() {
return DaoSqlMap.class;
}
}
| apache-2.0 |
PATRIC3/p3_solr | lucene/core/src/java/org/apache/lucene/search/ScoringRewrite.java | 7895 | package org.apache.lucene.search;
/*
* 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 java.io.IOException;
import org.apache.lucene.index.IndexReader;
import org.apache.lucene.index.Term;
import org.apache.lucene.index.TermContext;
import org.apache.lucene.index.TermState;
import org.apache.lucene.index.TermsEnum;
import org.apache.lucene.search.MultiTermQuery.RewriteMethod;
import org.apache.lucene.util.ArrayUtil;
import org.apache.lucene.util.ByteBlockPool;
import org.apache.lucene.util.BytesRef;
import org.apache.lucene.util.BytesRefHash.DirectBytesStartArray;
import org.apache.lucene.util.BytesRefHash;
import org.apache.lucene.util.RamUsageEstimator;
/**
* Base rewrite method that translates each term into a query, and keeps
* the scores as computed by the query.
* <p>
* @lucene.internal Only public to be accessible by spans package. */
public abstract class ScoringRewrite<B> extends TermCollectingRewrite<B> {
/** A rewrite method that first translates each term into
* {@link BooleanClause.Occur#SHOULD} clause in a
* BooleanQuery, and keeps the scores as computed by the
* query. Note that typically such scores are
* meaningless to the user, and require non-trivial CPU
* to compute, so it's almost always better to use {@link
* MultiTermQuery#CONSTANT_SCORE_REWRITE} instead.
*
* <p><b>NOTE</b>: This rewrite method will hit {@link
* BooleanQuery.TooManyClauses} if the number of terms
* exceeds {@link BooleanQuery#getMaxClauseCount}.
*
* @see MultiTermQuery#setRewriteMethod */
public final static ScoringRewrite<BooleanQuery.Builder> SCORING_BOOLEAN_REWRITE = new ScoringRewrite<BooleanQuery.Builder>() {
@Override
protected BooleanQuery.Builder getTopLevelBuilder() {
BooleanQuery.Builder builder = new BooleanQuery.Builder();
builder.setDisableCoord(true);
return builder;
}
protected Query build(BooleanQuery.Builder builder) {
return builder.build();
}
@Override
protected void addClause(BooleanQuery.Builder topLevel, Term term, int docCount,
float boost, TermContext states) {
final TermQuery tq = new TermQuery(term, states);
topLevel.add(new BoostQuery(tq, boost), BooleanClause.Occur.SHOULD);
}
@Override
protected void checkMaxClauseCount(int count) {
if (count > BooleanQuery.getMaxClauseCount())
throw new BooleanQuery.TooManyClauses();
}
};
/** Like {@link #SCORING_BOOLEAN_REWRITE} except
* scores are not computed. Instead, each matching
* document receives a constant score equal to the
* query's boost.
*
* <p><b>NOTE</b>: This rewrite method will hit {@link
* BooleanQuery.TooManyClauses} if the number of terms
* exceeds {@link BooleanQuery#getMaxClauseCount}.
*
* @see MultiTermQuery#setRewriteMethod */
public final static RewriteMethod CONSTANT_SCORE_BOOLEAN_REWRITE = new RewriteMethod() {
@Override
public Query rewrite(IndexReader reader, MultiTermQuery query) throws IOException {
final Query bq = SCORING_BOOLEAN_REWRITE.rewrite(reader, query);
// strip the scores off
return new ConstantScoreQuery(bq);
}
};
/** This method is called after every new term to check if the number of max clauses
* (e.g. in BooleanQuery) is not exceeded. Throws the corresponding {@link RuntimeException}. */
protected abstract void checkMaxClauseCount(int count) throws IOException;
@Override
public final Query rewrite(final IndexReader reader, final MultiTermQuery query) throws IOException {
final B builder = getTopLevelBuilder();
final ParallelArraysTermCollector col = new ParallelArraysTermCollector();
collectTerms(reader, query, col);
final int size = col.terms.size();
if (size > 0) {
final int sort[] = col.terms.sort(BytesRef.getUTF8SortedAsUnicodeComparator());
final float[] boost = col.array.boost;
final TermContext[] termStates = col.array.termState;
for (int i = 0; i < size; i++) {
final int pos = sort[i];
final Term term = new Term(query.getField(), col.terms.get(pos, new BytesRef()));
assert termStates[pos].hasOnlyRealTerms() == false || reader.docFreq(term) == termStates[pos].docFreq();
addClause(builder, term, termStates[pos].docFreq(), boost[pos], termStates[pos]);
}
}
return build(builder);
}
final class ParallelArraysTermCollector extends TermCollector {
final TermFreqBoostByteStart array = new TermFreqBoostByteStart(16);
final BytesRefHash terms = new BytesRefHash(new ByteBlockPool(new ByteBlockPool.DirectAllocator()), 16, array);
TermsEnum termsEnum;
private BoostAttribute boostAtt;
@Override
public void setNextEnum(TermsEnum termsEnum) {
this.termsEnum = termsEnum;
this.boostAtt = termsEnum.attributes().addAttribute(BoostAttribute.class);
}
@Override
public boolean collect(BytesRef bytes) throws IOException {
final int e = terms.add(bytes);
final TermState state = termsEnum.termState();
assert state != null;
if (e < 0) {
// duplicate term: update docFreq
final int pos = (-e)-1;
array.termState[pos].register(state, readerContext.ord, termsEnum.docFreq(), termsEnum.totalTermFreq());
assert array.boost[pos] == boostAtt.getBoost() : "boost should be equal in all segment TermsEnums";
} else {
// new entry: we populate the entry initially
array.boost[e] = boostAtt.getBoost();
array.termState[e] = new TermContext(topReaderContext, state, readerContext.ord, termsEnum.docFreq(), termsEnum.totalTermFreq());
ScoringRewrite.this.checkMaxClauseCount(terms.size());
}
return true;
}
}
/** Special implementation of BytesStartArray that keeps parallel arrays for boost and docFreq */
static final class TermFreqBoostByteStart extends DirectBytesStartArray {
float[] boost;
TermContext[] termState;
public TermFreqBoostByteStart(int initSize) {
super(initSize);
}
@Override
public int[] init() {
final int[] ord = super.init();
boost = new float[ArrayUtil.oversize(ord.length, RamUsageEstimator.NUM_BYTES_FLOAT)];
termState = new TermContext[ArrayUtil.oversize(ord.length, RamUsageEstimator.NUM_BYTES_OBJECT_REF)];
assert termState.length >= ord.length && boost.length >= ord.length;
return ord;
}
@Override
public int[] grow() {
final int[] ord = super.grow();
boost = ArrayUtil.grow(boost, ord.length);
if (termState.length < ord.length) {
TermContext[] tmpTermState = new TermContext[ArrayUtil.oversize(ord.length, RamUsageEstimator.NUM_BYTES_OBJECT_REF)];
System.arraycopy(termState, 0, tmpTermState, 0, termState.length);
termState = tmpTermState;
}
assert termState.length >= ord.length && boost.length >= ord.length;
return ord;
}
@Override
public int[] clear() {
boost = null;
termState = null;
return super.clear();
}
}
}
| apache-2.0 |
XClouded/t4f-core | java/io/src/main/java/io/aos/endpoint/socket/bio/BioMulticastServerThread.java | 4069 | /****************************************************************
* Licensed to the AOS Community (AOS) under one or more *
* contributor license agreements. See the NOTICE file *
* distributed with this work for additional information *
* regarding copyright ownership. The AOS 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. *
****************************************************************/
/*
* Copyright (c) 1995, 2008, Oracle and/or its affiliates. All rights reserved.
*
* Redistribution and use inputStreamsource and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* - Redistributions of source code must retainputStreamthe above copyright
* notice, this list of conditions and the following disclaimer.
*
* - Redistributions inputStreambinary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer inputStreamthe
* documentation and/or other materials provided with the distribution.
*
* - Neither the name of Oracle or the names of its
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
* IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
* THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package io.aos.endpoint.socket.bio;
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.InetAddress;
import java.util.Date;
public class BioMulticastServerThread extends BioUdpQuoteThread {
private long FIVE_SECONDS = 5000;
public BioMulticastServerThread() throws IOException {
super("MulticastServerThread");
}
public void run() {
while (moreQuotes) {
try {
byte[] buf = new byte[256];
// construct quote
String dString = null;
if (inputStream== null)
dString = new Date().toString();
else
dString = getNextQuote();
buf = dString.getBytes();
// send it
InetAddress group = InetAddress.getByName("230.0.0.1");
DatagramPacket packet = new DatagramPacket(buf, buf.length, group, 4446);
socket.send(packet);
// sleep for a while
try {
sleep((long)(Math.random() * FIVE_SECONDS));
} catch (InterruptedException e) { }
} catch (IOException e) {
e.printStackTrace();
moreQuotes = false;
}
}
socket.close();
}
}
| apache-2.0 |
nchambers/schemas | src/main/java/nate/Database.java | 2096 | package nate;
/**
* This uses MySQL Connector/J, JDBC driver for MySQL.
* (com.mysql.jdbc.*)
*/
// java sql
import java.sql.ResultSet;
import java.sql.Statement;
import java.sql.DriverManager;
import java.sql.Connection;
public class Database {
private Connection myCon;
String domain = "mainteach";
String username = "nchambers";
Statement myStmt;
/**
* @param domain The SQL database name
*/
Database(String domain) {
this.domain = domain;
try {
Class.forName("com.mysql.jdbc.Driver").newInstance();
// Connect to an instance of mysql with the follow details:
// machine address: pc236nt.napier.ac.uk
// database : gisq
// user name : scott
// password : tiger
myCon = DriverManager.getConnection("jdbc:mysql://localhost/" + domain + "?user=" + username);
myStmt = myCon.createStatement();
}
catch (Exception sqlEx){
sqlEx.printStackTrace();
}
}
public ResultSet query(String query) {
try {
return myStmt.executeQuery(query);
/*
// format each row of the returned rows
while (result.next()) {
// get the value in each column
// for( int i = 0; i < columns.length; i++ ) {
System.out.println("column = " + result.getString("keywords"));
// }
}
*/
} catch (Exception sqlEx){
sqlEx.printStackTrace();
}
return null;
}
public ResultSet insert(String insert, String keys[]) {
try {
myStmt.executeUpdate(insert,keys);
return myStmt.getGeneratedKeys();
} catch (Exception sqlEx){
sqlEx.printStackTrace();
}
return null;
}
public void insert(String insert) {
try {
myStmt.executeUpdate(insert);
} catch (Exception sqlEx){
sqlEx.printStackTrace();
}
}
public void addBatch(String insert) {
try {
myStmt.addBatch(insert);
} catch( Exception ex ) { ex.printStackTrace(); }
}
public void executeBatch() {
try {
myStmt.executeBatch();
} catch( Exception ex ) { ex.printStackTrace(); }
}
}
| apache-2.0 |
venusdrogon/feilong-core | src/main/java/com/feilong/core/util/predicate/BeanPredicateUtil.java | 27013 | /*
* Copyright (C) 2008 feilong
*
* 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.feilong.core.util.predicate;
import static com.feilong.core.Validator.isNotNullOrEmpty;
import java.lang.reflect.Array;
import java.util.Collection;
import java.util.Comparator;
import java.util.Map;
import org.apache.commons.collections4.ComparatorUtils;
import org.apache.commons.collections4.Predicate;
import org.apache.commons.collections4.PredicateUtils;
import org.apache.commons.collections4.functors.ComparatorPredicate;
import org.apache.commons.collections4.functors.ComparatorPredicate.Criterion;
import org.apache.commons.collections4.functors.EqualPredicate;
import org.apache.commons.lang3.Validate;
import com.feilong.core.bean.PropertyUtil;
import com.feilong.core.lang.ArrayUtil;
import com.feilong.core.util.AggregateUtil;
import com.feilong.core.util.CollectionsUtil;
import com.feilong.core.util.equator.IgnoreCaseEquator;
/**
* 专门针对bean,提供的 BeanPredicateUtil.
*
* @author <a href="http://feitianbenyue.iteye.com/">feilong</a>
* @see org.apache.commons.collections4.PredicateUtils
* @see com.feilong.core.util.predicate.BeanPredicate
* @since 1.8.0
*/
public final class BeanPredicateUtil{
/** Don't let anyone instantiate this class. */
private BeanPredicateUtil(){
//AssertionError不是必须的. 但它可以避免不小心在类的内部调用构造器. 保证该类在任何情况下都不会被实例化.
//see 《Effective Java》 2nd
throw new AssertionError("No " + getClass().getName() + " instances for you!");
}
//---------------------------------------------------------------
/**
* 用来指定 <code>T</code> 对象的特定属性 <code>propertyName</code> equals 指定的 <code>propertyValue</code>.
*
* <h3>说明:</h3>
* <blockquote>
* <ol>
* <li>
* 常用于解析集合,如 {@link CollectionsUtil#select(Iterable, Predicate) select},{@link CollectionsUtil#find(Iterable, Predicate) find},
* {@link CollectionsUtil#selectRejected(Iterable, Predicate) selectRejected},
* {@link CollectionsUtil#group(Iterable, String, Predicate) group},
* {@link AggregateUtil#groupCount(Iterable, String, Predicate) groupCount},
* {@link AggregateUtil#sum(Iterable, String, Predicate) sum} 等方法.
* </li>
* </ol>
* </blockquote>
*
* <h3>示例:</h3>
*
* <blockquote>
*
* <p>
* <b>场景:</b> 在list中查找 名字是 关羽,并且 年龄是30 的user
* </p>
*
* <pre class="code">
*
* User guanyu30 = new User("关羽", 30);
* List{@code <User>} list = toList(//
* new User("张飞", 23),
* new User("关羽", 24),
* new User("刘备", 25),
* guanyu30);
*
* Predicate{@code <User>} predicate = PredicateUtils
* .andPredicate(BeanPredicateUtil.equalPredicate("name", "关羽"), BeanPredicateUtil.equalPredicate("age", 30));
*
* assertEquals(guanyu30, CollectionsUtil.find(list, predicate));
*
* </pre>
*
* </blockquote>
*
* @param <T>
* the generic type
* @param <V>
* the value type
* @param propertyName
* 泛型T对象指定的属性名称,Possibly indexed and/or nested name of the property to be modified,参见
* <a href="../../bean/BeanUtil.html#propertyName">propertyName</a>
* @param propertyValue
* the property value
* @return 如果 <code>propertyName</code> 是null,抛出 {@link NullPointerException}<br>
* 如果 <code>propertyName</code> 是blank,抛出 {@link IllegalArgumentException}<br>
* @see org.apache.commons.collections4.PredicateUtils#equalPredicate(Object)
*/
public static <T, V> Predicate<T> equalPredicate(String propertyName,V propertyValue){
Validate.notBlank(propertyName, "propertyName can't be blank!");
return new BeanPredicate<>(propertyName, PredicateUtils.equalPredicate(propertyValue));
}
/**
* 用来指定 <code>T</code> 对象的特定属性 <code>propertyName</code> equalsIgnoreCase 指定的 <code>propertyValue</code>.
*
* <h3>说明:</h3>
* <blockquote>
* <ol>
* <li>
* 常用于解析集合,如 {@link CollectionsUtil#select(Iterable, Predicate) select},{@link CollectionsUtil#find(Iterable, Predicate) find},
* {@link CollectionsUtil#selectRejected(Iterable, Predicate) selectRejected},
* {@link CollectionsUtil#group(Iterable, String, Predicate) group},
* {@link AggregateUtil#groupCount(Iterable, String, Predicate) groupCount},
* {@link AggregateUtil#sum(Iterable, String, Predicate) sum} 等方法.
* </li>
* </ol>
* </blockquote>
*
* <h3>示例:</h3>
*
* <blockquote>
*
* <p>
* <b>场景:</b> 在list中查找 name是 zhangfei(忽视大小写) 的user
* </p>
*
* <pre class="code">
* User zhangfei1 = new User("zhangfei", 22);
* User zhangfei2 = new User("zhangFei", 22);
* User zhangfei3 = new User("Zhangfei", 22);
* User zhangfeinull = new User((String) null, 22);
* User guanyu = new User("guanyu", 25);
* User liubei = new User("liubei", 30);
*
* List{@code <User>} list = toList(zhangfei1, zhangfei2, zhangfei3, zhangfeinull, guanyu, liubei);
*
* List{@code <User>} select = select(list, BeanPredicateUtil.{@code <User>} equalIgnoreCasePredicate("name", "zhangfei"));
*
* assertThat(select, allOf(//
* hasItem(zhangfei1),
* hasItem(zhangfei2),
* hasItem(zhangfei3),
*
* not(hasItem(zhangfeinull)),
* not(hasItem(guanyu)),
* not(hasItem(liubei))
* //
* ));
* </pre>
*
* </blockquote>
*
* @param <T>
* the generic type
* @param propertyName
* 泛型T对象指定的属性名称,Possibly indexed and/or nested name of the property to be modified,参见
* <a href="../../bean/BeanUtil.html#propertyName">propertyName</a>
* @param propertyValue
* the property value
* @return 如果 <code>propertyName</code> 是null,抛出 {@link NullPointerException}<br>
* 如果 <code>propertyName</code> 是blank,抛出 {@link IllegalArgumentException}<br>
* @see org.apache.commons.collections4.PredicateUtils#equalPredicate(Object)
* @see com.feilong.core.util.equator.IgnoreCaseEquator#INSTANCE
* @since 1.10.1
*/
public static <T> Predicate<T> equalIgnoreCasePredicate(String propertyName,String propertyValue){
Validate.notBlank(propertyName, "propertyName can't be blank!");
return new BeanPredicate<>(propertyName, EqualPredicate.equalPredicate(propertyValue, IgnoreCaseEquator.INSTANCE));
}
/**
* 用来判断一个对象指定的属性以及属性值是否相等.
*
* <h3>说明:</h3>
* <blockquote>
* <ol>
* <li>
* 常用于解析集合,如 {@link CollectionsUtil#select(Iterable, Predicate) select},{@link CollectionsUtil#find(Iterable, Predicate) find},
* {@link CollectionsUtil#selectRejected(Iterable, Predicate) selectRejected},
* {@link CollectionsUtil#group(Iterable, String, Predicate) group},
* {@link AggregateUtil#groupCount(Iterable, String, Predicate) groupCount},
* {@link AggregateUtil#sum(Iterable, String, Predicate) sum} 等方法.
* </li>
* </ol>
* </blockquote>
*
* <h3>示例:</h3>
*
* <blockquote>
*
* <p>
* <b>场景:</b> 在list中查找 名字是 关羽,并且 年龄是30 的user
* </p>
*
* <pre class="code">
*
* User guanyu30 = new User("关羽", 30);
* List{@code <User>} list = toList(//
* new User("张飞", 23),
* new User("关羽", 24),
* new User("刘备", 25),
* guanyu30);
*
* Predicate{@code <User>} predicate = PredicateUtils
* .andPredicate(BeanPredicateUtil.equalPredicate("name", "关羽"), BeanPredicateUtil.equalPredicate("age", 30));
*
* assertEquals(guanyu30, CollectionsUtil.find(list, predicate));
* </pre>
*
* <p>
* 此时你可以优化成:
* </p>
*
* <pre class="code">
*
* User guanyu30 = new User("关羽", 30);
* List{@code <User>} list = toList(//
* new User("张飞", 23),
* new User("关羽", 24),
* new User("刘备", 25),
* guanyu30);
*
* Map{@code <String, Object>} map = ConvertUtil.toMap("name", "关羽", "age", 30);
* assertEquals(guanyu30, find(list, BeanPredicateUtil.{@code <User>} equalPredicate(map)));
* </pre>
*
* </blockquote>
*
* @param <T>
* the generic type
* @param propertyNameAndPropertyValueMap
* 属性和指定属性值对应的map,其中key是泛型T对象指定的属性名称,Possibly indexed and/or nested name of the property to be modified,参见
* <a href="../../bean/BeanUtil.html#propertyName">propertyName</a>
* @return 如果 <code>propertyNameAndPropertyValueMap</code> 是null,抛出 {@link NullPointerException}<br>
* 如果 <code>propertyNameAndPropertyValueMap</code> 是empty,抛出{@link IllegalArgumentException}<br>
* 如果 <code>propertyNameAndPropertyValueMap</code> 中有key是null,抛出{@link NullPointerException}<br>
* 如果 <code>propertyNameAndPropertyValueMap</code> 中有key是blank,抛出{@link IllegalArgumentException}<br>
* @see #equalPredicate(String, Object)
* @since 1.9.5
*/
public static <T> Predicate<T> equalPredicate(Map<String, ?> propertyNameAndPropertyValueMap){
Validate.notEmpty(propertyNameAndPropertyValueMap, "propertyNameAndPropertyValueMap can't be null!");
@SuppressWarnings("unchecked")
BeanPredicate<T>[] beanPredicates = ArrayUtil.newArray(BeanPredicate.class, propertyNameAndPropertyValueMap.size());
int index = 0;
for (Map.Entry<String, ?> entry : propertyNameAndPropertyValueMap.entrySet()){
String propertyName = entry.getKey();
Object propertyValue = entry.getValue();
Validate.notBlank(propertyName, "propertyName can't be blank!");
Array.set(beanPredicates, index, equalPredicate(propertyName, propertyValue));
index++;
}
return PredicateUtils.allPredicate(beanPredicates);
}
/**
* 构造属性与一个指定对象 <code>bean</code> 的一组属性的值 <code>propertyNames</code> 都相等的判断器.
*
* <h3>说明:</h3>
* <blockquote>
* <ol>
* <li>
* 常用于解析集合,如 {@link CollectionsUtil#select(Iterable, Predicate) select},{@link CollectionsUtil#find(Iterable, Predicate) find},
* {@link CollectionsUtil#selectRejected(Iterable, Predicate) selectRejected},
* {@link CollectionsUtil#group(Iterable, String, Predicate) group},
* {@link AggregateUtil#groupCount(Iterable, String, Predicate) groupCount},
* {@link AggregateUtil#sum(Iterable, String, Predicate) sum} 等方法.
* </li>
* </ol>
* </blockquote>
*
* <h3>示例:</h3>
*
* <blockquote>
*
* <p>
* <b>场景:</b> 在list中查找 名字是 关羽,并且 年龄是30 的user
* </p>
*
* <pre class="code">
*
* User guanyu30 = new User("关羽", 30);
* List{@code <User>} list = toList(//
* new User("张飞", 23),
* new User("关羽", 24),
* new User("刘备", 25),
* guanyu30);
*
* Predicate{@code <User>} predicate = PredicateUtils
* .andPredicate(BeanPredicateUtil.equalPredicate("name", "关羽"), BeanPredicateUtil.equalPredicate("age", 30));
*
* assertEquals(guanyu30, CollectionsUtil.find(list, predicate));
* </pre>
*
* <p>
* 此时你可以优化成:
* </p>
*
* <pre class="code">
*
* User guanyu30 = new User("关羽", 30);
* List{@code <User>} list = toList(//
* new User("张飞", 23),
* new User("关羽", 24),
* new User("刘备", 25),
* guanyu30);
*
* assertEquals(guanyu30, find(list, BeanPredicateUtil.equalPredicate(guanyu30, "name", "age")));
* </pre>
*
* </blockquote>
*
* @param <T>
* the generic type
* @param bean
* the bean
* @param propertyNames
* 如果 <code>propertyNames</code> 是null或者empty 那么取所有属性值.
* @return 如果 <code>bean</code> 是null,返回 {@link org.apache.commons.collections4.PredicateUtils#nullPredicate()}<br>
* 否则 调用 {@link com.feilong.core.bean.PropertyUtil#describe(Object, String...)} 提取属性值,再调用 {@link #equalPredicate(Map)}
* @see #equalPredicate(String, Object)
* @see com.feilong.core.bean.PropertyUtil#describe(Object, String...)
* @since 1.10.6
*/
public static <T> Predicate<T> equalPredicate(T bean,String...propertyNames){
if (null == bean){
return PredicateUtils.nullPredicate();
}
Map<String, ?> propertyNameAndPropertyValueMap = PropertyUtil.describe(bean, propertyNames);
return equalPredicate(propertyNameAndPropertyValueMap);
}
//---------------------------------------------------------------
/**
* 调用 {@link PropertyUtil#getProperty(Object, String)} 获得 <code>propertyName</code>的值,使用
* {@link org.apache.commons.lang3.ArrayUtils#contains(Object[], Object) ArrayUtils.contains} 判断是否在 <code>values</code>数组中.
*
* <h3>说明:</h3>
* <blockquote>
* <ol>
* <li>
* 常用于解析集合,如 {@link CollectionsUtil#select(Iterable, Predicate) select},{@link CollectionsUtil#find(Iterable, Predicate) find},
* {@link CollectionsUtil#selectRejected(Iterable, Predicate) selectRejected},
* {@link CollectionsUtil#group(Iterable, String, Predicate) group},
* {@link AggregateUtil#groupCount(Iterable, String, Predicate) groupCount},
* {@link AggregateUtil#sum(Iterable, String, Predicate) sum} 等方法.
* </li>
* </ol>
* </blockquote>
*
* @param <T>
* the generic type
* @param <V>
* the value type
* @param propertyName
* 泛型T对象指定的属性名称,Possibly indexed and/or nested name of the property to be modified,参见
* <a href="../../bean/BeanUtil.html#propertyName">propertyName</a>
* @param propertyValues
* the property values
* @return 如果 <code>propertyName</code> 是null,抛出 {@link NullPointerException}<br>
* 如果 <code>propertyName</code> 是blank,抛出 {@link IllegalArgumentException}<br>
* @see org.apache.commons.lang3.ArrayUtils#contains(Object[], Object)
*/
@SafeVarargs
public static <T, V> Predicate<T> containsPredicate(final String propertyName,final V...propertyValues){
Validate.notBlank(propertyName, "propertyName can't be blank!");
return new BeanPredicate<>(propertyName, new Predicate<V>(){
@Override
public boolean evaluate(V propertyValue){
return org.apache.commons.lang3.ArrayUtils.contains(propertyValues, propertyValue);
}
});
}
/**
* 调用 {@link PropertyUtil#getProperty(Object, String)} 获得 <code>propertyName</code>的值,使用{@link java.util.Collection#contains(Object)
* Collection.contains} 判断是否在<code>values</code>集合中.
*
* <h3>说明:</h3>
* <blockquote>
* <ol>
* <li>
* 常用于解析集合,如 {@link CollectionsUtil#select(Iterable, Predicate) select},{@link CollectionsUtil#find(Iterable, Predicate) find},
* {@link CollectionsUtil#selectRejected(Iterable, Predicate) selectRejected},
* {@link CollectionsUtil#group(Iterable, String, Predicate) group},
* {@link AggregateUtil#groupCount(Iterable, String, Predicate) groupCount},
* {@link AggregateUtil#sum(Iterable, String, Predicate) sum} 等方法.
* </li>
* </ol>
* </blockquote>
*
* @param <T>
* the generic type
* @param <V>
* the value type
* @param propertyName
* 泛型T对象指定的属性名称,Possibly indexed and/or nested name of the property to be modified,参见
* <a href="../../bean/BeanUtil.html#propertyName">propertyName</a>
* @param propertyValueList
* the property value list
* @return 如果 <code>propertyName</code> 是null,抛出 {@link NullPointerException}<br>
* 如果 <code>propertyName</code> 是blank,抛出 {@link IllegalArgumentException}<br>
* @see java.util.Collection#contains(Object)
*/
public static <T, V> Predicate<T> containsPredicate(final String propertyName,final Collection<V> propertyValueList){
Validate.notBlank(propertyName, "propertyName can't be blank!");
return new BeanPredicate<>(propertyName, new Predicate<V>(){
@Override
public boolean evaluate(V propertyValue){
return isNotNullOrEmpty(propertyValueList) && propertyValueList.contains(propertyValue);
}
});
}
//---------------------------------------------------------------
/**
* 判断指定的值 <code>valueToCompare</code> <code>criterion</code> 提取的bean对象属性<code>propertyName</code>的值 .
*
* <p>
* 注意: 是参数 <code>valueToCompare</code> 和 属性值进行比较 <code>criterion</code>, BeanPredicateUtil.comparatorPredicate("age", 20,
* Criterion.LESS) 表示提取所有比20 大的结果
* </p>
*
* <h3>说明:</h3>
* <blockquote>
* <ol>
* <li>使用 {@link ComparatorUtils#naturalComparator()} 自然排序比较器.</li>
* <li>比较 <code><b><span style="color:red">comparator.compare(valueToCompare, propertyValue)</span></b></code>.</li>
* <li>
* 常用于解析集合,如 {@link CollectionsUtil#select(Iterable, Predicate) select},{@link CollectionsUtil#find(Iterable, Predicate) find},
* {@link CollectionsUtil#selectRejected(Iterable, Predicate) selectRejected},
* {@link CollectionsUtil#group(Iterable, String, Predicate) group},
* {@link AggregateUtil#groupCount(Iterable, String, Predicate) groupCount},
* {@link AggregateUtil#sum(Iterable, String, Predicate) sum} 等方法.
* </li>
* </ol>
* </blockquote>
*
* <h3>关于 {@link Criterion}:</h3>
*
* <blockquote>
* <table border="1" cellspacing="0" cellpadding="4" summary="">
*
* <tr style="background-color:#ccccff">
* <th align="left">字段</th>
* <th align="left">说明</th>
* </tr>
*
*
* <tr valign="top">
* <td>{@link Criterion#EQUAL}</td>
* <td>comparator.compare(valueToCompare, propertyValue) == 0</td>
* </tr>
*
* <tr valign="top" style="background-color:#eeeeff">
* <td>{@link Criterion#LESS}</td>
* <td>comparator.compare(valueToCompare, propertyValue) {@code <} 0</td>
* </tr>
*
* <tr valign="top">
* <td>{@link Criterion#GREATER}</td>
* <td>comparator.compare(valueToCompare, propertyValue) {@code >} 0</td>
* </tr>
*
* <tr valign="top" style="background-color:#eeeeff">
* <td>{@link Criterion#GREATER_OR_EQUAL}</td>
* <td>comparator.compare(valueToCompare, propertyValue) {@code >=} 0</td>
* </tr>
*
* <tr valign="top">
* <td>{@link Criterion#LESS_OR_EQUAL}</td>
* <td>comparator.compare(valueToCompare, propertyValue) {@code <=} 0</td>
* </tr>
*
* </table>
* </blockquote>
*
* <h3>通常对于以下代码:</h3>
*
* <blockquote>
*
* <p>
* <b>场景:</b> 大于20岁的人分个组
* </p>
*
* <pre class="code">
* List{@code <User>} list = toList(//
* new User("张飞", 10),
* new User("张飞", 28),
* new User("刘备", 32),
* new User("刘备", 30),
* new User("刘备", 10));
*
* Map{@code <String, List<User>>} map = CollectionsUtil.group(list, "name", new Predicate{@code <User>}(){
*
* {@code @Override}
* public boolean evaluate(User user){
* return user.getAge() {@code >} 20;
* }
* });
*
* </pre>
*
* 你可以简化成:
*
* <pre class="code">
*
* List{@code <User>} list = toList(//
* new User("张飞", 10),
* new User("张飞", 28),
* new User("刘备", 32),
* new User("刘备", 30),
* new User("刘备", 10));
*
* Predicate{@code <User>} comparatorPredicate = BeanPredicateUtil.comparatorPredicate("age", 20, Criterion.LESS);
* </pre>
*
* </blockquote>
*
* @param <T>
* the generic type
* @param <V>
* the value type
* @param propertyName
* 泛型T对象指定的属性名称,Possibly indexed and/or nested name of the property to be modified,参见
* <a href="../../bean/BeanUtil.html#propertyName">propertyName</a>
* @param valueToCompare
* the value to compare
* @param criterion
* the criterion
* @return 如果 <code>propertyName</code> 是null,抛出 {@link NullPointerException}<br>
* 如果 <code>propertyName</code> 是blank,抛出 {@link IllegalArgumentException}<br>
* @see ComparatorUtils#naturalComparator()
* @see #comparatorPredicate(String, Comparable, Comparator, Criterion)
* @since commons-collections 4
*/
public static <T, V extends Comparable<? super V>> Predicate<T> comparatorPredicate(
String propertyName,
V valueToCompare,
Criterion criterion){
Validate.notBlank(propertyName, "propertyName can't be blank!");
return comparatorPredicate(propertyName, valueToCompare, ComparatorUtils.<V> naturalComparator(), criterion);
}
/**
* 判断指定的值 <code>valueToCompare</code> <code>criterion</code> 提取的bean对象属性<code>propertyName</code>的值 .
*
* <h3>说明:</h3>
* <blockquote>
* <ol>
* <li>使用 <code>comparator</code> 比较器</li>
* <li>比较 <code><b><span style="color:red">comparator.compare(valueToCompare, propertyValue)</span></b></code>.</li>
* <li>
* 常用于解析集合,如 {@link CollectionsUtil#select(Iterable, Predicate) select},{@link CollectionsUtil#find(Iterable, Predicate) find},
* {@link CollectionsUtil#selectRejected(Iterable, Predicate) selectRejected},
* {@link CollectionsUtil#group(Iterable, String, Predicate) group},
* {@link AggregateUtil#groupCount(Iterable, String, Predicate) groupCount},
* {@link AggregateUtil#sum(Iterable, String, Predicate) sum} 等方法.
* </li>
* </ol>
* </blockquote>
*
* <h3>关于 {@link Criterion}:</h3>
*
* <blockquote>
* <table border="1" cellspacing="0" cellpadding="4" summary="">
*
* <tr style="background-color:#ccccff">
* <th align="left">字段</th>
* <th align="left">说明</th>
* </tr>
*
*
* <tr valign="top">
* <td>{@link Criterion#EQUAL}</td>
* <td>comparator.compare(valueToCompare, propertyValue) == 0</td>
* </tr>
*
* <tr valign="top" style="background-color:#eeeeff">
* <td>{@link Criterion#LESS}</td>
* <td>comparator.compare(valueToCompare, propertyValue) {@code <} 0</td>
* </tr>
*
* <tr valign="top">
* <td>{@link Criterion#GREATER}</td>
* <td>comparator.compare(valueToCompare, propertyValue) {@code >} 0</td>
* </tr>
*
* <tr valign="top" style="background-color:#eeeeff">
* <td>{@link Criterion#GREATER_OR_EQUAL}</td>
* <td>comparator.compare(valueToCompare, propertyValue) {@code >=} 0</td>
* </tr>
*
* <tr valign="top">
* <td>{@link Criterion#LESS_OR_EQUAL}</td>
* <td>comparator.compare(valueToCompare, propertyValue) {@code <=} 0</td>
* </tr>
*
* </table>
* </blockquote>
*
* @param <T>
* the generic type
* @param <V>
* the value type
* @param propertyName
* 泛型T对象指定的属性名称,Possibly indexed and/or nested name of the property to be modified,参见
* <a href="../../bean/BeanUtil.html#propertyName">propertyName</a>
* @param valueToCompare
* the value to compare
* @param comparator
* the comparator
* @param criterion
* the criterion
* @return 如果 <code>propertyName</code> 是null,抛出 {@link NullPointerException}<br>
* 如果 <code>propertyName</code> 是blank,抛出 {@link IllegalArgumentException}<br>
* @see org.apache.commons.collections4.functors.ComparatorPredicate
* @since commons-collections 4
*/
public static <T, V extends Comparable<? super V>> Predicate<T> comparatorPredicate(
String propertyName,
V valueToCompare,
Comparator<V> comparator,
Criterion criterion){
Validate.notBlank(propertyName, "propertyName can't be blank!");
return new BeanPredicate<>(propertyName, new ComparatorPredicate<V>(valueToCompare, comparator, criterion));
}
}
| apache-2.0 |
aws/aws-sdk-java | aws-java-sdk-ioteventsdata/src/main/java/com/amazonaws/services/ioteventsdata/model/transform/BatchPutMessageRequestMarshaller.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.ioteventsdata.model.transform;
import java.util.List;
import javax.annotation.Generated;
import com.amazonaws.SdkClientException;
import com.amazonaws.services.ioteventsdata.model.*;
import com.amazonaws.protocol.*;
import com.amazonaws.annotation.SdkInternalApi;
/**
* BatchPutMessageRequestMarshaller
*/
@Generated("com.amazonaws:aws-java-sdk-code-generator")
@SdkInternalApi
public class BatchPutMessageRequestMarshaller {
private static final MarshallingInfo<List> MESSAGES_BINDING = MarshallingInfo.builder(MarshallingType.LIST).marshallLocation(MarshallLocation.PAYLOAD)
.marshallLocationName("messages").build();
private static final BatchPutMessageRequestMarshaller instance = new BatchPutMessageRequestMarshaller();
public static BatchPutMessageRequestMarshaller getInstance() {
return instance;
}
/**
* Marshall the given parameter object.
*/
public void marshall(BatchPutMessageRequest batchPutMessageRequest, ProtocolMarshaller protocolMarshaller) {
if (batchPutMessageRequest == null) {
throw new SdkClientException("Invalid argument passed to marshall(...)");
}
try {
protocolMarshaller.marshall(batchPutMessageRequest.getMessages(), MESSAGES_BINDING);
} catch (Exception e) {
throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e);
}
}
}
| apache-2.0 |
zalando-stups/fullstop | fullstop-whitelist/src/main/java/org/zalando/stups/fullstop/whitelist/config/WhitelistConfig.java | 795 | package org.zalando.stups.fullstop.whitelist.config;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.zalando.stups.fullstop.rule.service.RuleEntityService;
import org.zalando.stups.fullstop.whitelist.WhitelistRules;
import org.zalando.stups.fullstop.whitelist.WhitelistRulesEvaluator;
@Configuration
public class WhitelistConfig {
@Autowired
private RuleEntityService ruleEntityService;
@Bean
WhitelistRulesEvaluator whitelistRulesEvaluator() {
return new WhitelistRulesEvaluator();
}
@Bean
WhitelistRules whitelistRules() {
return new WhitelistRules(whitelistRulesEvaluator(), ruleEntityService);
}
}
| apache-2.0 |
menacher/netty | buffer/src/main/java/io/netty/buffer/AbstractDerivedByteBuf.java | 1743 | /*
* Copyright 2013 The Netty Project
*
* The Netty Project licenses this file to you under the Apache License,
* version 2.0 (the "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at:
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*/
package io.netty.buffer;
/**
* Abstract base class for {@link ByteBuf} implementations that wrap another
* {@link ByteBuf}.
*/
public abstract class AbstractDerivedByteBuf extends AbstractByteBuf {
protected AbstractDerivedByteBuf(int maxCapacity) {
super(maxCapacity);
}
@Override
public final int refCnt() {
return unwrap().refCnt();
}
@Override
public final ByteBuf retain() {
unwrap().retain();
return this;
}
@Override
public final ByteBuf retain(int increment) {
unwrap().retain(increment);
return this;
}
@Override
public final boolean release() {
return unwrap().release();
}
@Override
public final boolean release(int decrement) {
return unwrap().release(decrement);
}
@Override
public final ByteBuf suspendIntermediaryDeallocations() {
throw new UnsupportedOperationException("derived");
}
@Override
public final ByteBuf resumeIntermediaryDeallocations() {
throw new UnsupportedOperationException("derived");
}
}
| apache-2.0 |
javalite/activejdbc | activeweb-testing/src/test/java/app/controllers/SessionObjectConverterController.java | 1331 | /*
Copyright 2009-(CURRENT YEAR) Igor Polevoy
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 app.controllers;
import org.javalite.activeweb.AppController;
/**
* @author Igor Polevoy
*/
public class SessionObjectConverterController extends AppController {
public void inSpec(){
session("name", "John");
session("int", 1);
session("double", 1);
session("float", 1);
session("long", 1);
session("boolean", true);
}
public void inController(){
session("last_name", "Smith");
view("name", sessionObject("name"));
view("int", sessionObject("int"));
view("double", sessionObject("double"));
view("float", sessionObject("float"));
view("long", sessionObject("long"));
view("boolean", sessionObject("boolean"));
}
}
| apache-2.0 |
johnjianfang/jxse | src/main/java/net/jxta/impl/rendezvous/rpv/PeerViewRandomWithReplaceStrategy.java | 3823 | /*
* Copyright (c) 2002 Sun Microsystems, Inc. All rights reserved.
*
* The Sun Project JXTA(TM) Software License
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* 3. The end-user documentation included with the redistribution, if any, must
* include the following acknowledgment: "This product includes software
* developed by Sun Microsystems, Inc. for JXTA(TM) technology."
* Alternately, this acknowledgment may appear in the software itself, if
* and wherever such third-party acknowledgments normally appear.
*
* 4. The names "Sun", "Sun Microsystems, Inc.", "JXTA" and "Project JXTA" must
* not be used to endorse or promote products derived from this software
* without prior written permission. For written permission, please contact
* Project JXTA at http://www.jxta.org.
*
* 5. Products derived from this software may not be called "JXTA", nor may
* "JXTA" appear in their name, without prior written permission of Sun.
*
* THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES,
* INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
* FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL SUN
* MICROSYSTEMS OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA,
* OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
* EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* JXTA is a registered trademark of Sun Microsystems, Inc. in the United
* States and other countries.
*
* Please see the license information page at :
* <http://www.jxta.org/project/www/license.html> for instructions on use of
* the license in source files.
*
* ====================================================================
*
* This software consists of voluntary contributions made by many individuals
* on behalf of Project JXTA. For more information on Project JXTA, please see
* http://www.jxta.org.
*
* This license is based on the BSD license adopted by the Apache Foundation.
*/
package net.jxta.impl.rendezvous.rpv;
import java.util.Iterator;
import java.util.Random;
import java.util.SortedSet;
/**
* Random with replacement
*/
class PeerViewRandomWithReplaceStrategy implements PeerViewStrategy {
private static Random random = new Random();
private SortedSet set = null;
PeerViewRandomWithReplaceStrategy(SortedSet set) {
this.set = set;
}
/**
* {@inheritDoc}
*/
public void reset() {
}
/**
* {@inheritDoc}
*/
public PeerViewElement next() {
synchronized (set) {
if (set.isEmpty()) {
return null;
}
int i = random.nextInt(set.size());
// return the ith element
int n = 0;
Iterator si = set.iterator();
while (n < i) {
si.next();
n++;
}
return (PeerViewElement) si.next();
}
}
}
| apache-2.0 |
wmeints/intentify | src/main/java/nl/fizzylogic/intentify/entities/TrainingSample.java | 431 | package nl.fizzylogic.intentify.entities;
/**
* Represents a single training sample
*/
public final class TrainingSample {
private final String text;
private final String intent;
public TrainingSample(String intent, String text) {
this.text = text;
this.intent = intent;
}
public String getText() {
return text;
}
public String getIntent() {
return intent;
}
}
| apache-2.0 |
amezgin/amezgin | chapter_001/JVM/src/test/java/ru/job4j/CalculateTest.java | 607 | package ru.job4j;
import org.junit.Test;
import java.io.ByteArrayOutputStream;
import java.io.PrintStream;
import static org.hamcrest.core.Is.is;
import static org.junit.Assert.assertThat;
/**
* Test.
*
* @author Alexander Mezgin
* @version 1
* @since 14.11.2016
*/
public class CalculateTest {
/**
* Test add.
*/
@Test
public void whenExecuteMainThenPrintToConsole() {
ByteArrayOutputStream out = new ByteArrayOutputStream();
System.setOut(new PrintStream(out));
Calculate.main(null);
assertThat(out.toString(), is("Hello World!\r\n"));
}
} | apache-2.0 |
chrisvest/stormpot | src/test/java/stormpot/ThreadLocalWeakRefTest.java | 3223 | /*
* Copyright (C) 2011-2014 Chris Vest (mr.chrisvest@gmail.com)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package stormpot;
import org.junit.Ignore;
import org.junit.Test;
import java.lang.ref.WeakReference;
import static org.junit.Assert.assertNull;
public class ThreadLocalWeakRefTest {
/**
* Many Java web servers and containers go out of their way to find and null
* out ThreadLocals that an application might have created. Question is, is
* that really necessary?
*/
@Ignore
@Test public void
threadsWeaklyReferenceThreadLocalValues() {
// Hypothesis: When we loose the reference to a ThreadLocal (e.g. by a
// web app being redeployed and getting a soft restart), and no other
// references to that object exists, then it should eventually be garbage
// collected.
Object obj = new Object();
ThreadLocal<Object> threadLocal = new ThreadLocal<Object>();
WeakReference<Object> weakReference = new WeakReference<Object>(obj);
threadLocal.set(obj);
// The stack of every thread is a GC-root. We have a strong reference to
// obj through the variable on our stack. When we clear it out, the only
// strong reference that will be left, will be through the threadLocal.
obj = null;
// When we loose the reference to the threadLocal, then the values it
// referred to will no longer be strongly referenced by our thread.
threadLocal = null;
// Our obj is now in principle garbage, though we still have a
// weakReference to it. The GC does not yet know this, because only the
// threadLocal object itself is now weakly referenced. We clear out that
// weak reference with a run of the GC.
System.gc();
// The entry in our ThreadLocalMap is now stale. It still exists, and
// strongly references our obj, but it will be cleared next time our
// ThreadLocalMap does its clean-up procedure. We cannot invoke the
// clean-up procedure directly, but sufficient perturbation of the
// ThreadLocalMap will bring it about.
ThreadLocal<Object> a = new ThreadLocal<Object>();
a.set(new Object());
ThreadLocal<Object> b = new ThreadLocal<Object>();
b.set(new Object());
// The entry has now been removed, and our obj is now weakly referenced
// by our weakReference above. Invoking another round of GC will clear it.
System.gc();
// The obj has now been collected because all references are gone.
// We observe this by the weakReference being null.
assertNull(weakReference.get());
// This test passes on Java 6, 7 and 8, with default GC settings.
// I haven't tried alternative GC settings, but you are welcome to do that.
}
}
| apache-2.0 |
crnk-project/crnk-framework | crnk-client/src/test/java/io/crnk/client/ResourceIdentifierBasedRelationshipTest.java | 3146 | package io.crnk.client;
import java.util.Arrays;
import java.util.Map;
import io.crnk.core.engine.document.ResourceIdentifier;
import io.crnk.core.queryspec.PathSpec;
import io.crnk.core.queryspec.QuerySpec;
import io.crnk.core.repository.ManyRelationshipRepository;
import io.crnk.core.repository.OneRelationshipRepository;
import io.crnk.core.repository.ResourceRepository;
import io.crnk.core.resource.list.ResourceList;
import io.crnk.test.mock.models.ResourceIdentifierBasedRelationshipResource;
import io.crnk.test.mock.models.Task;
import org.junit.Assert;
import org.junit.Test;
/**
* Make use of ResourceIdentifier with @JsonRelationId. Brings the benefit of having both type information and id within ResourceIdentifier.
*/
public class ResourceIdentifierBasedRelationshipTest extends AbstractClientTest {
@Test
public void test() {
ResourceRepository<Task, Object> tasks = client.getRepositoryForType(Task.class);
Task task = new Task();
task.setId(1L);
task.setName("someTask");
tasks.create(task);
ResourceRepository<ResourceIdentifierBasedRelationshipResource, Object> repository = client.getRepositoryForType(ResourceIdentifierBasedRelationshipResource.class);
ResourceIdentifierBasedRelationshipResource resource = new ResourceIdentifierBasedRelationshipResource();
resource.setId(2L);
resource.setTaskId(new ResourceIdentifier("1", "tasks"));
resource.setTaskIds(Arrays.asList(new ResourceIdentifier("1", "tasks")));
repository.create(resource);
QuerySpec querySpec = new QuerySpec(ResourceIdentifierBasedRelationshipResource.class);
querySpec.includeRelation(PathSpec.of("task"));
ResourceList<ResourceIdentifierBasedRelationshipResource> list = repository.findAll(querySpec);
Assert.assertEquals(1, list.size());
resource = list.get(0);
Assert.assertEquals(2L, resource.getId());
Assert.assertEquals(new ResourceIdentifier("1", "tasks"), resource.getTaskId());
Assert.assertNotNull(resource.getTask());
Assert.assertEquals("someTask", resource.getTask().getName());
OneRelationshipRepository<ResourceIdentifierBasedRelationshipResource, Object, Task, Object> oneRelationshipRepository =
client.getOneRepositoryForType(ResourceIdentifierBasedRelationshipResource.class, Task.class);
Map<Object, Task> relationships = oneRelationshipRepository.findOneRelations(Arrays.asList(2L), "task", new QuerySpec(Task.class));
Assert.assertEquals(1, relationships.size());
Assert.assertNotNull(relationships.get(2L));
Assert.assertNotNull(relationships.get(2L) instanceof Task);
ManyRelationshipRepository<ResourceIdentifierBasedRelationshipResource, Object, Task, Object> manyRelationshipRepository =
client.getManyRepositoryForType(ResourceIdentifierBasedRelationshipResource.class, Task.class);
Map<Object, ResourceList<Task>> manyRelationships = manyRelationshipRepository.findManyRelations(Arrays.asList(2L), "tasks", new QuerySpec(Task.class));
Assert.assertEquals(1, manyRelationships.size());
ResourceList<Task> manyList = manyRelationships.get(2L);
Assert.assertEquals(1, manyList.size());
Assert.assertNotNull(manyList.get(0) instanceof Task);
}
} | apache-2.0 |
wouwouwou/module_8 | src/test/java/pp/block3/SymbolTableTest.java | 2335 | package pp.block3;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import pp.block3.cc.symbol.MySymbolTable;
import pp.block3.cc.symbol.SymbolTable;
public class SymbolTableTest {
private SymbolTable table;
@Before
public void initTable() {
table = new MySymbolTable(); // construct an instance of your implementation
}
@Test
public void testEmpty() {
try {
this.table.contains("aap");
} catch (RuntimeException e) {
Assert.fail("Using an empty table should not fail");
// this is the expected behaviour
}
try {
this.table.closeScope();
Assert.fail("Closing the top-level scope should fail");
} catch (RuntimeException e) {
// this is the expected behaviour
}
this.table.openScope();
this.table.closeScope();
try {
this.table.closeScope();
Assert.fail("Closing the top-level scope should fail");
} catch (RuntimeException e) {
// this is the expected behaviour
}
}
@Test
public void testLookup() {
assertFalse(this.table.contains("aap"));
assertTrue(this.table.add("aap"));
assertTrue(this.table.contains("aap"));
assertFalse(this.table.add("aap"));
assertFalse(this.table.contains("noot"));
this.table.openScope();
assertTrue(this.table.contains("aap"));
assertFalse(this.table.contains("noot"));
assertTrue(this.table.add("aap"));
assertTrue(this.table.add("noot"));
this.table.closeScope();
assertTrue(this.table.contains("aap"));
assertFalse(this.table.contains("noot"));
}
@Test
public void testNesting() {
this.table.openScope();
assertTrue(this.table.add("aap"));
this.table.openScope();
assertTrue(this.table.add("aap"));
this.table.openScope();
assertTrue(this.table.contains("aap"));
assertTrue(this.table.add("noot"));
assertTrue(this.table.contains("noot"));
this.table.closeScope();
assertFalse(this.table.contains("noot"));
this.table.openScope();
assertFalse(this.table.contains("noot"));
assertTrue(this.table.add("noot"));
assertTrue(this.table.contains("noot"));
this.table.closeScope();
assertFalse(this.table.contains("noot"));
this.table.closeScope();
this.table.closeScope();
assertFalse(this.table.contains("aap"));
assertFalse(this.table.contains("noot"));
}
}
| apache-2.0 |
actframework/act-demo-apps | fullstack-app.obsolete/doc-sample/src/main/java/act/doc/sample/ContactCreated.java | 368 | package act.doc.sample;
import act.event.ActEvent;
import act.event.ActEventListenerBase;
import act.util.Async;
@Async
public class ContactCreated extends ActEventListenerBase<ActEvent<Contact>> {
@Override
public void on(ActEvent<Contact> event) throws Exception {
Contact contact = event.source();
// send welcome email to contact
}
}
| apache-2.0 |
zzhbug/BlackMovie | app/src/main/java/com/zzh/blackmovie/fragment/MovieHistoryFragment.java | 2156 | package com.zzh.blackmovie.fragment;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import com.zzh.blackmovie.R;
import com.zzh.blackmovie.base.BaseFragment;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
/**
* Created by Administrator on 2016/9/22 0022.
*/
public class MovieHistoryFragment extends BaseFragment {
public static final String TAG = MovieHistoryFragment.class.getSimpleName();
@BindView(R.id.imgTopbarBack)
ImageView imgTopbarBack;
@BindView(R.id.textTopbarTitle)
TextView textTopbarTitle;
@BindView(R.id.imgTopbarSearch)
ImageView imgTopbarSearch;
@BindView(R.id.textComment)
TextView textComment;
@BindView(R.id.textNothing)
TextView textNothing;
@BindView(R.id.recyclerMovie)
RecyclerView recyclerMovie;
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
layout = inflater.inflate(R.layout.fragment_history,container,false);
ButterKnife.bind(this, layout);
return layout;
}
@Override
public void onActivityCreated(@Nullable Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
initView();
}
private void initView() {
textTopbarTitle.setText("观影历史");
imgTopbarSearch.setImageResource(R.drawable.delete_bg);
imgTopbarSearch.setMaxWidth(5);
imgTopbarSearch.setMaxHeight(5);
// imgTopbarSearch.setPadding(10,10,10,10);
imgTopbarSearch.setClickable(false);
}
@OnClick({R.id.imgTopbarBack, R.id.imgTopbarSearch})
public void onClick(View view) {
switch (view.getId()) {
case R.id.imgTopbarBack:
getActivity().finish();
break;
case R.id.imgTopbarSearch:
break;
}
}
}
| apache-2.0 |
jentfoo/aws-sdk-java | aws-java-sdk-guardduty/src/main/java/com/amazonaws/services/guardduty/model/ListDetectorsRequest.java | 7610 | /*
* 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.guardduty.model;
import java.io.Serializable;
import javax.annotation.Generated;
import com.amazonaws.AmazonWebServiceRequest;
/**
*
* @see <a href="http://docs.aws.amazon.com/goto/WebAPI/guardduty-2017-11-28/ListDetectors" target="_top">AWS API
* Documentation</a>
*/
@Generated("com.amazonaws:aws-java-sdk-code-generator")
public class ListDetectorsRequest extends com.amazonaws.AmazonWebServiceRequest implements Serializable, Cloneable {
/**
* <p>
* You can use this parameter to indicate the maximum number of items you want in the response. The default value is
* 50. The maximum value is 50.
* </p>
*/
private Integer maxResults;
/**
* <p>
* You can use this parameter when paginating results. Set the value of this parameter to null on your first call to
* the list action. For subsequent calls to the action fill nextToken in the request with the value of NextToken
* from the previous response to continue listing data.
* </p>
*/
private String nextToken;
/**
* <p>
* You can use this parameter to indicate the maximum number of items you want in the response. The default value is
* 50. The maximum value is 50.
* </p>
*
* @param maxResults
* You can use this parameter to indicate the maximum number of items you want in the response. The default
* value is 50. The maximum value is 50.
*/
public void setMaxResults(Integer maxResults) {
this.maxResults = maxResults;
}
/**
* <p>
* You can use this parameter to indicate the maximum number of items you want in the response. The default value is
* 50. The maximum value is 50.
* </p>
*
* @return You can use this parameter to indicate the maximum number of items you want in the response. The default
* value is 50. The maximum value is 50.
*/
public Integer getMaxResults() {
return this.maxResults;
}
/**
* <p>
* You can use this parameter to indicate the maximum number of items you want in the response. The default value is
* 50. The maximum value is 50.
* </p>
*
* @param maxResults
* You can use this parameter to indicate the maximum number of items you want in the response. The default
* value is 50. The maximum value is 50.
* @return Returns a reference to this object so that method calls can be chained together.
*/
public ListDetectorsRequest withMaxResults(Integer maxResults) {
setMaxResults(maxResults);
return this;
}
/**
* <p>
* You can use this parameter when paginating results. Set the value of this parameter to null on your first call to
* the list action. For subsequent calls to the action fill nextToken in the request with the value of NextToken
* from the previous response to continue listing data.
* </p>
*
* @param nextToken
* You can use this parameter when paginating results. Set the value of this parameter to null on your first
* call to the list action. For subsequent calls to the action fill nextToken in the request with the value
* of NextToken from the previous response to continue listing data.
*/
public void setNextToken(String nextToken) {
this.nextToken = nextToken;
}
/**
* <p>
* You can use this parameter when paginating results. Set the value of this parameter to null on your first call to
* the list action. For subsequent calls to the action fill nextToken in the request with the value of NextToken
* from the previous response to continue listing data.
* </p>
*
* @return You can use this parameter when paginating results. Set the value of this parameter to null on your first
* call to the list action. For subsequent calls to the action fill nextToken in the request with the value
* of NextToken from the previous response to continue listing data.
*/
public String getNextToken() {
return this.nextToken;
}
/**
* <p>
* You can use this parameter when paginating results. Set the value of this parameter to null on your first call to
* the list action. For subsequent calls to the action fill nextToken in the request with the value of NextToken
* from the previous response to continue listing data.
* </p>
*
* @param nextToken
* You can use this parameter when paginating results. Set the value of this parameter to null on your first
* call to the list action. For subsequent calls to the action fill nextToken in the request with the value
* of NextToken from the previous response to continue listing data.
* @return Returns a reference to this object so that method calls can be chained together.
*/
public ListDetectorsRequest withNextToken(String nextToken) {
setNextToken(nextToken);
return this;
}
/**
* Returns a string representation of this object. This is useful for testing and debugging. Sensitive data will be
* redacted from this string using a placeholder value.
*
* @return A string representation of this object.
*
* @see java.lang.Object#toString()
*/
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("{");
if (getMaxResults() != null)
sb.append("MaxResults: ").append(getMaxResults()).append(",");
if (getNextToken() != null)
sb.append("NextToken: ").append(getNextToken());
sb.append("}");
return sb.toString();
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (obj instanceof ListDetectorsRequest == false)
return false;
ListDetectorsRequest other = (ListDetectorsRequest) obj;
if (other.getMaxResults() == null ^ this.getMaxResults() == null)
return false;
if (other.getMaxResults() != null && other.getMaxResults().equals(this.getMaxResults()) == false)
return false;
if (other.getNextToken() == null ^ this.getNextToken() == null)
return false;
if (other.getNextToken() != null && other.getNextToken().equals(this.getNextToken()) == false)
return false;
return true;
}
@Override
public int hashCode() {
final int prime = 31;
int hashCode = 1;
hashCode = prime * hashCode + ((getMaxResults() == null) ? 0 : getMaxResults().hashCode());
hashCode = prime * hashCode + ((getNextToken() == null) ? 0 : getNextToken().hashCode());
return hashCode;
}
@Override
public ListDetectorsRequest clone() {
return (ListDetectorsRequest) super.clone();
}
}
| apache-2.0 |