text
stringlengths 7
1.01M
|
|---|
/**
*
* Copyright 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.jivesoftware.smackx.filetransfer;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PushbackInputStream;
import org.jivesoftware.smack.SmackException;
import org.jivesoftware.smack.SmackException.NoResponseException;
import org.jivesoftware.smack.XMPPConnection;
import org.jivesoftware.smack.XMPPException;
import org.jivesoftware.smack.XMPPException.XMPPErrorException;
import org.jivesoftware.smack.packet.Stanza;
import org.jivesoftware.smackx.bytestreams.socks5.Socks5BytestreamManager;
import org.jivesoftware.smackx.bytestreams.socks5.Socks5BytestreamRequest;
import org.jivesoftware.smackx.bytestreams.socks5.Socks5BytestreamSession;
import org.jivesoftware.smackx.bytestreams.socks5.packet.Bytestream;
import org.jivesoftware.smackx.si.packet.StreamInitiation;
import org.jxmpp.jid.Jid;
/**
* Negotiates a SOCKS5 Bytestream to be used for file transfers. The implementation is based on the
* {@link Socks5BytestreamManager} and the {@link Socks5BytestreamRequest}.
*
* @author Henning Staib
* @see <a href="http://xmpp.org/extensions/xep-0065.html">XEP-0065: SOCKS5 Bytestreams</a>
*/
public class Socks5TransferNegotiator extends StreamNegotiator {
private Socks5BytestreamManager manager;
Socks5TransferNegotiator(XMPPConnection connection) {
super(connection);
this.manager = Socks5BytestreamManager.getBytestreamManager(connection);
}
@Override
public OutputStream createOutgoingStream(String streamID, Jid initiator, Jid target) throws NoResponseException, SmackException, XMPPException
{
try {
return this.manager.establishSession(target, streamID).getOutputStream();
}
catch (IOException e) {
throw new SmackException("error establishing SOCKS5 Bytestream", e);
}
catch (InterruptedException e) {
throw new SmackException("error establishing SOCKS5 Bytestream", e);
}
}
@Override
public InputStream createIncomingStream(StreamInitiation initiation) throws XMPPErrorException,
InterruptedException, SmackException {
/*
* SOCKS5 initiation listener must ignore next SOCKS5 Bytestream request with given session
* ID
*/
this.manager.ignoreBytestreamRequestOnce(initiation.getSessionID());
Stanza streamInitiation = initiateIncomingStream(connection(), initiation);
return negotiateIncomingStream(streamInitiation);
}
@Override
public void newStreamInitiation(final Jid from, String streamID) {
/*
* this method is always called prior to #negotiateIncomingStream() so the SOCKS5
* InitiationListener must ignore the next SOCKS5 Bytestream request with the given session
* ID
*/
this.manager.ignoreBytestreamRequestOnce(streamID);
}
@Override
public String[] getNamespaces() {
return new String[] { Bytestream.NAMESPACE };
}
@Override
InputStream negotiateIncomingStream(Stanza streamInitiation) throws InterruptedException,
SmackException, XMPPErrorException {
// build SOCKS5 Bytestream request
Socks5BytestreamRequest request = new ByteStreamRequest(this.manager,
(Bytestream) streamInitiation);
// always accept the request
Socks5BytestreamSession session = request.accept();
// test input stream
try {
PushbackInputStream stream = new PushbackInputStream(session.getInputStream());
int firstByte = stream.read();
stream.unread(firstByte);
return stream;
}
catch (IOException e) {
throw new SmackException("Error establishing input stream", e);
}
}
/**
* Derive from Socks5BytestreamRequest to access protected constructor.
*/
private static final class ByteStreamRequest extends Socks5BytestreamRequest {
private ByteStreamRequest(Socks5BytestreamManager manager, Bytestream byteStreamRequest) {
super(manager, byteStreamRequest);
}
}
}
|
/*****************************************************************
* 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.cayenne.modeler.action;
import org.apache.cayenne.configuration.DataChannelDescriptor;
import org.apache.cayenne.configuration.DataNodeDescriptor;
import org.apache.cayenne.configuration.event.DataNodeEvent;
import org.apache.cayenne.map.DataMap;
import org.apache.cayenne.modeler.Application;
import org.apache.cayenne.modeler.ProjectController;
import org.apache.cayenne.modeler.undo.LinkDataMapsUndoableEdit;
import org.apache.cayenne.modeler.util.CayenneAction;
import java.awt.event.ActionEvent;
import java.util.ArrayList;
import java.util.Collection;
public class LinkDataMapsAction extends CayenneAction {
public static String getActionName() {
return "Link unlinked DataMaps";
}
/**
* Constructor for LinkDataMapsAction.
*
* @param application
*/
public LinkDataMapsAction(Application application) {
super(getActionName(), application);
}
@Override
public String getIconName() {
return "icon-sync.gif";
}
@Override
public void performAction(ActionEvent e) {
ProjectController mediator = getProjectController();
DataChannelDescriptor dataChannelDescriptor = (DataChannelDescriptor) mediator.getProject().getRootNode();
Collection<String> linkedDataMaps = new ArrayList<String>();
DataNodeDescriptor dataNodeDescriptor = mediator.getCurrentDataNode();
for (DataNodeDescriptor dataNodeDesc : dataChannelDescriptor.getNodeDescriptors()) {
linkedDataMaps.addAll(dataNodeDesc.getDataMapNames());
}
for (DataMap dataMap : dataChannelDescriptor.getDataMaps()) {
if (!linkedDataMaps.contains(dataMap.getName())) {
dataNodeDescriptor.getDataMapNames().add(dataMap.getName());
mediator.fireDataNodeEvent(new DataNodeEvent(this, dataNodeDescriptor));
}
}
application.getUndoManager().addEdit(
new LinkDataMapsUndoableEdit(dataNodeDescriptor, linkedDataMaps, mediator));
}
}
|
package io.datatok.djobi.exceptions;
import io.datatok.djobi.engine.stage.Stage;
public class NetworkAccessException extends StageException {
public NetworkAccessException(Stage stage, String message) {
super(stage, message);
}
}
|
package com.face.recognition.websocket;
import java.io.IOException;
import java.util.Collections;
import java.util.HashSet;
import java.util.Set;
import javax.websocket.OnClose;
import javax.websocket.OnError;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.ServerEndpoint;
import org.apache.log4j.Logger;
@ServerEndpoint("/echo")
public class WebSocketStringServer {
private Logger logger = Logger.getLogger(WebSocketStringServer.class);
private static Set<Session> clients = Collections.synchronizedSet(new HashSet<Session>());
@OnOpen
public void onOpen (Session session) {
// Add session to the connected sessions set
clients.add(session);
this.logger.info("Client " + session.getId() + " connected.");
}
@OnClose
public void onClose (Session session) {
// Remove session from the connected sessions set
clients.remove(session);
this.logger.info("Client " + session.getId() + " disconnected.");
}
@OnError
public void onError(Throwable error) {
this.logger.error(error.getMessage());
}
@OnMessage
public void echoTextMessage(Session session, String msg, boolean last) {
try {
if (session.isOpen()) {
session.getBasicRemote().sendText(msg, last);
}
} catch (IOException e) {
try {
session.close();
} catch (IOException e1) {
}
}
}
}
|
/*
* Copyright (c) 2021, Peter Abeles. All Rights Reserved.
*
* This file is part of BoofCV (http://boofcv.org).
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package boofcv.demonstrations.feature.detect.interest;
import boofcv.abst.feature.detect.interest.ConfigFastCorner;
import boofcv.abst.feature.detect.interest.ConfigGeneralDetector;
import boofcv.abst.feature.detect.interest.ConfigHarrisCorner;
import boofcv.abst.feature.detect.interest.ConfigShiTomasi;
import boofcv.alg.feature.detect.intensity.HessianBlobIntensity;
import boofcv.alg.feature.detect.interest.EasyGeneralFeatureDetector;
import boofcv.alg.feature.detect.interest.GeneralFeatureDetector;
import boofcv.demonstrations.feature.detect.ImageCorruptPanel;
import boofcv.factory.feature.detect.interest.FactoryDetectPoint;
import boofcv.gui.SelectAlgorithmAndInputPanel;
import boofcv.gui.feature.FancyInterestPointRender;
import boofcv.gui.image.ImagePanel;
import boofcv.gui.image.ShowImages;
import boofcv.io.PathLabel;
import boofcv.io.UtilIO;
import boofcv.io.image.ConvertBufferedImage;
import boofcv.misc.BoofMiscOps;
import boofcv.struct.QueueCorner;
import boofcv.struct.image.GrayF32;
import boofcv.struct.image.ImageGray;
import georegression.struct.point.Point2D_I16;
import javax.swing.*;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.util.ArrayList;
import java.util.List;
/**
* Displays a window showing the selected point features. Local maximums and minimums are shown using different
* colors.
*
* @author Peter Abeles
*/
public class DetectPointsWithNoiseApp<T extends ImageGray<T>, D extends ImageGray<D>>
extends SelectAlgorithmAndInputPanel implements ImageCorruptPanel.Listener {
static int maxFeatures = 400;
static int maxScaleFeatures = maxFeatures/3;
public double[] scales = new double[]{1, 1.5, 2, 3, 4, 6, 8, 12};
int radius = 2;
float thresh = 1;
T grayImage;
T corruptImage;
Class<T> imageType;
boolean processImage = false;
BufferedImage input;
BufferedImage workImage;
FancyInterestPointRender render = new FancyInterestPointRender();
ImagePanel panel;
ImageCorruptPanel corruptPanel;
public DetectPointsWithNoiseApp( Class<T> imageType, Class<D> derivType ) {
super(1);
this.imageType = imageType;
GeneralFeatureDetector<T, D> alg;
ConfigGeneralDetector configExtract = new ConfigGeneralDetector(maxFeatures, radius, thresh);
alg = FactoryDetectPoint.createHarris(configExtract, null, derivType);
addAlgorithm(0, "Harris", new EasyGeneralFeatureDetector<>(alg, imageType, derivType));
alg = FactoryDetectPoint.createHarris(configExtract, new ConfigHarrisCorner(true, radius), derivType);
addAlgorithm(0, "Harris Weighted", new EasyGeneralFeatureDetector<>(alg, imageType, derivType));
alg = FactoryDetectPoint.createShiTomasi(configExtract, null, derivType);
addAlgorithm(0, "Shi-Tomasi", new EasyGeneralFeatureDetector<>(alg, imageType, derivType));
alg = FactoryDetectPoint.createShiTomasi(configExtract, new ConfigShiTomasi(true, radius), derivType);
addAlgorithm(0, "Shi-Tomasi Weighted", new EasyGeneralFeatureDetector<>(alg, imageType, derivType));
configExtract.detectMinimums = true;
configExtract.threshold = 10;
alg = FactoryDetectPoint.createFast(configExtract, new ConfigFastCorner(10, 9), imageType);
configExtract.detectMinimums = false;
configExtract.threshold = thresh;
addAlgorithm(0, "Fast", new EasyGeneralFeatureDetector<>(alg, imageType, derivType));
alg = FactoryDetectPoint.createKitRos(configExtract, derivType);
addAlgorithm(0, "KitRos", new EasyGeneralFeatureDetector<>(alg, imageType, derivType));
alg = FactoryDetectPoint.createMedian(configExtract, imageType);
addAlgorithm(0, "Median", new EasyGeneralFeatureDetector<>(alg, imageType, derivType));
alg = FactoryDetectPoint.createHessianDeriv(configExtract, HessianBlobIntensity.Type.DETERMINANT, derivType);
addAlgorithm(0, "Hessian", new EasyGeneralFeatureDetector<>(alg, imageType, derivType));
configExtract.detectMinimums = true;
alg = FactoryDetectPoint.createHessianDeriv(configExtract, HessianBlobIntensity.Type.TRACE, derivType);
addAlgorithm(0, "Laplace", new EasyGeneralFeatureDetector<>(alg, imageType, derivType));
JPanel viewArea = new JPanel(new BorderLayout());
corruptPanel = new ImageCorruptPanel();
corruptPanel.setListener(this);
panel = new ImagePanel();
viewArea.add(corruptPanel, BorderLayout.WEST);
viewArea.add(panel, BorderLayout.CENTER);
setMainGUI(viewArea);
}
public void process( BufferedImage input ) {
setInputImage(input);
this.input = input;
grayImage = ConvertBufferedImage.convertFromSingle(input, null, imageType);
corruptImage = (T)grayImage.createNew(grayImage.width, grayImage.height);
workImage = new BufferedImage(input.getWidth(), input.getHeight(), BufferedImage.TYPE_INT_BGR);
panel.setImage(workImage);
panel.setPreferredSize(new Dimension(workImage.getWidth(), workImage.getHeight()));
doRefreshAll();
SwingUtilities.invokeLater(() -> {
revalidate();
processImage = true;
});
}
@Override
public void loadConfigurationFile( String fileName ) {
}
@Override
public void refreshAll( Object[] cookies ) {
setActiveAlgorithm(0, null, cookies[0]);
}
@Override
public synchronized void setActiveAlgorithm( int indexFamily, String name, Object cookie ) {
if (input == null)
return;
// corrupt the input image
corruptPanel.corruptImage(grayImage, corruptImage);
final EasyGeneralFeatureDetector<T, D> det = (EasyGeneralFeatureDetector<T, D>)cookie;
det.detect(corruptImage, null);
render.reset();
if (det.getDetector().isDetectMinimums()) {
QueueCorner l = det.getMinimums();
for (int i = 0; i < l.size; i++) {
Point2D_I16 p = l.get(i);
render.addPoint(p.x, p.y, 3, Color.BLUE);
}
}
if (det.getDetector().isDetectMaximums()) {
QueueCorner l = det.getMaximums();
for (int i = 0; i < l.size; i++) {
Point2D_I16 p = l.get(i);
render.addPoint(p.x, p.y, 3, Color.RED);
}
}
SwingUtilities.invokeLater(() -> {
ConvertBufferedImage.convertTo(corruptImage, workImage, true);
Graphics2D g2 = workImage.createGraphics();
g2.setStroke(new BasicStroke(3));
render.draw(g2);
panel.repaint();
});
}
@Override
public void changeInput( String name, int index ) {
BufferedImage image = media.openImage(inputRefs.get(index).getPath());
if (image != null) {
process(image);
}
}
@Override
public boolean getHasProcessedImage() {
return processImage;
}
@Override
public synchronized void corruptImageChange() {
doRefreshAll();
}
public static void main( String[] args ) {
DetectPointsWithNoiseApp app = new DetectPointsWithNoiseApp(GrayF32.class, GrayF32.class);
// DetectPointsWithNoiseApp app = new DetectPointsWithNoiseApp(GrayU8.class,GrayS16.class);
List<PathLabel> inputs = new ArrayList<>();
inputs.add(new PathLabel("Square Grid", UtilIO.pathExample("calibration/mono/Sony_DSC-HX5V_Square/frame06.jpg")));
inputs.add(new PathLabel("sunflowers", UtilIO.pathExample("sunflowers.jpg")));
inputs.add(new PathLabel("amoeba", UtilIO.pathExample("amoeba_shapes.jpg")));
inputs.add(new PathLabel("beach", UtilIO.pathExample("scale/beach02.jpg")));
inputs.add(new PathLabel("shapes", UtilIO.pathExample("shapes/shapes01.png")));
app.setInputList(inputs);
// wait for it to process one image so that the size isn't all screwed up
while (!app.getHasProcessedImage()) {
BoofMiscOps.sleep(10);
}
ShowImages.showWindow(app, "Detect Scale Point" +
" with Noise", true);
}
}
|
package com.nutrymaco.orm.migration;
import com.nutrymaco.orm.config.ConfigurationOwner;
import com.nutrymaco.orm.query.Database;
import com.nutrymaco.orm.query.insert.InsertQueryBuilder;
import com.nutrymaco.orm.schema.Schema;
import com.nutrymaco.orm.schema.db.Table;
import com.nutrymaco.orm.schema.lang.Entity;
import com.nutrymaco.orm.schema.lang.Field;
import com.nutrymaco.orm.util.ClassUtil;
import java.util.Collection;
import java.util.Comparator;
import java.util.List;
import java.util.Optional;
import java.util.logging.Logger;
class SynchronisationManagerImpl implements SynchronisationManager {
private static final String KEYSPACE = ConfigurationOwner.getConfiguration().keyspace();
private static final Database database = ConfigurationOwner.getConfiguration().database();
private static final Logger logger = Logger.getLogger(SynchronisationManager.class.getSimpleName());
private static SynchronisationManagerImpl instance;
private final Schema schema;
private final TableSynchronizationStrategy synchronizationStrategy;
private final MigrationTableManager migrationTableManager;
synchronized public static SynchronisationManagerImpl getInstance() {
if (instance == null) {
instance = new SynchronisationManagerImpl();
}
return instance;
}
private SynchronisationManagerImpl() {
this.schema = Schema.getInstance();
this.synchronizationStrategy = TableSynchronizationStrategy.getInstance();
this.migrationTableManager = MigrationTableManager.getInstance();
schema.getTables().forEach(this::addTable);
}
private void syncId(Entity entity, Object id) {
logger.info("syncing id : %s for entity : %s".formatted(id, entity.getName()));
schema.getTablesByEntity(entity).stream()
.filter(table -> !isSync(table))
.forEach(table -> {
logger.info("syncing id for table : %s".formatted(table.name()));
migrationTableManager.syncId(table, id);
});
}
public void syncObject(Entity entity, Object object) {
logger.info("syncing for entity : %s object : %s".formatted(entity.getName(), object));
// пишем в не синхронизированные таблицы
schema.getTablesByEntity(entity).stream()
.filter(table -> !synchronizationStrategy.isSync(table))
.flatMap(notSyncTable -> InsertQueryBuilder.of(List.of(notSyncTable), object).getCql().stream())
.forEach(database::execute);
// вытаскиваем id
entity.getFields().stream()
.filter(Field::isUnique)
.findFirst()
.ifPresent(idField -> {
var idValue = ClassUtil.getValueByPath(object, idField.getName()).get(0);
logger.info("getting id value : %s by field : %s".formatted(idValue, idField.getName()));
syncId(entity, idValue);
});
}
public boolean isSync(Table table) {
return synchronizationStrategy.isSync(table);
}
//todo - добавить статистику по времени запроса??
// todo - проверять что есть все необходимые колонки (не базовые и если нет, то надо вручную идти по базе)
public Optional<Table> getNearestTable(Table table) {
logger.info("start searching nearest table for table : %s".formatted(table.name()));
var res = schema.getTables().stream()
.filter(this::isSync)
.filter(syncTable -> syncTable.primaryKey().partitionColumns().containsAll(
table.primaryKey().partitionColumns()))
.findFirst();
if (res.isPresent()) {
logger.info("found nearest table : %s".formatted(res.get().name()));
} else {
logger.info("not found nearest table");
}
return res;
}
public void addTable(Table table) {
synchronizationStrategy.addTable(table);
}
private static int diff(Collection<?> collection1, Collection<?> collection2) {
return (int) collection1.stream()
.filter(collection2::contains)
.count();
}
}
|
/**
* Copyright 2012-2018 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package com.amazonaws.services.simpleworkflow.flow.examples.cronwithretry;
import java.util.List;
import com.amazonaws.services.simpleworkflow.flow.common.FlowConstants;
import com.amazonaws.services.simpleworkflow.flow.interceptors.ExponentialRetryPolicy;
import com.amazonaws.services.simpleworkflow.model.ActivityType;
/**
* See {@link ExponentialRetryPolicy} for description of retry related
* properties.
*
* @author fateev
*/
public class CronWithRetryWorkflowOptions {
private ActivityType activity;
private Object[] activityArguments;
private String cronExpression;
private String timeZone;
private int continueAsNewAfterSeconds;
private List<String> exceptionsToRetry;
private List<String> exceptionsToExclude;
private long initialRetryIntervalSeconds = 60;
private long maximumRetryIntervalSeconds = 3600;
private long retryExpirationIntervalSeconds = FlowConstants.NONE;
private double backoffCoefficient = 2.0;
private int maximumAttempts = FlowConstants.NONE;
public ActivityType getActivity() {
return activity;
}
public void setActivity(ActivityType activity) {
this.activity = activity;
}
public Object[] getActivityArguments() {
return activityArguments;
}
public void setActivityArguments(Object[] activityArguments) {
this.activityArguments = activityArguments;
}
public String getCronExpression() {
return cronExpression;
}
public void setCronExpression(String cronExpression) {
this.cronExpression = cronExpression;
}
public String getTimeZone() {
return timeZone;
}
public void setTimeZone(String timeZone) {
this.timeZone = timeZone;
}
public int getContinueAsNewAfterSeconds() {
return continueAsNewAfterSeconds;
}
public void setContinueAsNewAfterSeconds(int continueAsNewAfterSeconds) {
this.continueAsNewAfterSeconds = continueAsNewAfterSeconds;
}
public List<String> getExceptionsToRetry() {
return exceptionsToRetry;
}
public void setExceptionsToRetry(List<String> exceptionsToRetry) {
this.exceptionsToRetry = exceptionsToRetry;
}
public List<String> getExceptionsToExclude() {
return exceptionsToExclude;
}
public void setExceptionsToExclude(List<String> exceptionsToExclude) {
this.exceptionsToExclude = exceptionsToExclude;
}
public long getInitialRetryIntervalSeconds() {
return initialRetryIntervalSeconds;
}
public void setInitialRetryIntervalSeconds(long initialRetryIntervalSeconds) {
this.initialRetryIntervalSeconds = initialRetryIntervalSeconds;
}
public long getMaximumRetryIntervalSeconds() {
return maximumRetryIntervalSeconds;
}
public void setMaximumRetryIntervalSeconds(long maximumRetryIntervalSeconds) {
this.maximumRetryIntervalSeconds = maximumRetryIntervalSeconds;
}
public long getRetryExpirationIntervalSeconds() {
return retryExpirationIntervalSeconds;
}
public void setRetryExpirationIntervalSeconds(long retryExpirationIntervalSeconds) {
this.retryExpirationIntervalSeconds = retryExpirationIntervalSeconds;
}
public double getBackoffCoefficient() {
return backoffCoefficient;
}
public void setBackoffCoefficient(double backoffCoefficient) {
this.backoffCoefficient = backoffCoefficient;
}
public int getMaximumAttempts() {
return maximumAttempts;
}
public void setMaximumAttempts(int maximumAttempts) {
this.maximumAttempts = maximumAttempts;
}
}
|
// Copyright 2019 Oath Inc. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.vespa.hosted.provision.provisioning;
import com.yahoo.config.provision.Flavor;
import com.yahoo.vespa.hosted.provision.Node;
import java.util.List;
import java.util.Set;
/**
* Service for provisioning physical docker tenant hosts inside the zone.
*
* @author freva
*/
public interface HostProvisioner {
/**
* Schedule provisioning of a given number of hosts.
*
* @param provisionIndexes List of unique provision indexes which will be used to generate the host hostnames
* on the form of <code>[prefix][index].[domain]</code>
* @param nodeFlavor Vespa flavor of the node that will run on this host. The resulting provisioned host
* will be of a flavor that is at least as big or bigger than this.
* @return list of {@link ProvisionedHost} describing the provisioned hosts and nodes on them.
*/
List<ProvisionedHost> provisionHosts(List<Integer> provisionIndexes, Flavor nodeFlavor);
/**
* Continue provisioning of given list of Nodes.
*
* @param host the host to provision
* @param children list of all the nodes that run on the given host
* @return a subset of {@code host} and {@code children} where the values have been modified and should
* be written back to node-repository.
* @throws FatalProvisioningException if the provisioning has irrecoverably failed and the input nodes
* should be deleted from node-repo.
*/
List<Node> provision(Node host, Set<Node> children) throws FatalProvisioningException;
/**
* Deprovisions a given host and resources associated with it and its children (such as DNS entries).
* This method will only perform the actual deprovisioning of the host and does NOT:
* - verify whether it is safe to do
* - clean up config server references to this node or any of its children
* Therefore, this method should probably only be called for hosts that have no children.
*
* @param host host to deprovision.
*/
void deprovision(Node host);
}
|
package org.smicon.rest.emberwiring.general.factories;
public interface FactoryI<I, C>
{
C getConfiguration();
I create();
}
|
package com.easemob.chatuidemo.parse;
import android.content.Context;
import com.easemob.EMValueCallBack;
import com.easemob.chat.EMChatManager;
import com.easemob.chatuidemo.DemoHelper;
import com.easemob.easeui.domain.EaseUser;
import com.easemob.easeui.utils.EaseCommonUtils;
import com.easemob.util.EMLog;
import com.parse.FindCallback;
import com.parse.GetCallback;
import com.parse.Parse;
import com.parse.ParseException;
import com.parse.ParseFile;
import com.parse.ParseObject;
import com.parse.ParseQuery;
import com.parse.SaveCallback;
import java.util.ArrayList;
import java.util.List;
public class ParseManager {
private static final String TAG = ParseManager.class.getSimpleName();
private static final String ParseAppID = "UUL8TxlHwKj7ZXEUr2brF3ydOxirCXdIj9LscvJs";
private static final String ParseClientKey = "B1jH9bmxuYyTcpoFfpeVslhmLYsytWTxqYqKQhBJ";
private static final String CONFIG_TABLE_NAME = "hxuser";
private static final String CONFIG_USERNAME = "username";
private static final String CONFIG_NICK = "nickname";
private static final String CONFIG_AVATAR = "avatar";
private Context appContext;
private static ParseManager instance = new ParseManager();
private ParseManager() {
}
public static ParseManager getInstance() {
return instance;
}
public void onInit(Context context) {
this.appContext = context.getApplicationContext();
Parse.enableLocalDatastore(appContext);
Parse.initialize(context, ParseAppID, ParseClientKey);
}
public boolean updateParseNickName(final String nickname) {
String username = EMChatManager.getInstance().getCurrentUser();
ParseQuery<ParseObject> pQuery = ParseQuery.getQuery(CONFIG_TABLE_NAME);
pQuery.whereEqualTo(CONFIG_USERNAME, username);
ParseObject pUser = null;
try {
pUser = pQuery.getFirst();
if (pUser == null) {
return false;
}
pUser.put(CONFIG_NICK, nickname);
pUser.save();
return true;
} catch (ParseException e) {
if (e.getCode() == ParseException.OBJECT_NOT_FOUND) {
pUser = new ParseObject(CONFIG_TABLE_NAME);
pUser.put(CONFIG_USERNAME, username);
pUser.put(CONFIG_NICK, nickname);
try {
pUser.save();
return true;
} catch (ParseException e1) {
e1.printStackTrace();
EMLog.e(TAG, "parse error " + e1.getMessage());
}
}
e.printStackTrace();
EMLog.e(TAG, "parse error " + e.getMessage());
}
return false;
}
public void getContactInfos(List<String> usernames, final EMValueCallBack<List<EaseUser>> callback) {
ParseQuery<ParseObject> pQuery = ParseQuery.getQuery(CONFIG_TABLE_NAME);
pQuery.whereContainedIn(CONFIG_USERNAME, usernames);
pQuery.findInBackground(new FindCallback<ParseObject>() {
@Override
public void done(List<ParseObject> arg0, ParseException arg1) {
if (arg0 != null) {
List<EaseUser> mList = new ArrayList<EaseUser>();
for (ParseObject pObject : arg0) {
EaseUser user = new EaseUser(pObject.getString(CONFIG_USERNAME));
ParseFile parseFile = pObject.getParseFile(CONFIG_AVATAR);
if (parseFile != null) {
user.setAvatar(parseFile.getUrl());
}
user.setNick(pObject.getString(CONFIG_NICK));
EaseCommonUtils.setUserInitialLetter(user);
mList.add(user);
}
callback.onSuccess(mList);
} else {
callback.onError(arg1.getCode(), arg1.getMessage());
}
}
});
}
public void asyncGetCurrentUserInfo(final EMValueCallBack<EaseUser> callback) {
final String username = EMChatManager.getInstance().getCurrentUser();
asyncGetUserInfo(username, new EMValueCallBack<EaseUser>() {
@Override
public void onSuccess(EaseUser value) {
callback.onSuccess(value);
}
@Override
public void onError(int error, String errorMsg) {
if (error == ParseException.OBJECT_NOT_FOUND) {
ParseObject pUser = new ParseObject(CONFIG_TABLE_NAME);
pUser.put(CONFIG_USERNAME, username);
pUser.saveInBackground(new SaveCallback() {
@Override
public void done(ParseException arg0) {
if (arg0 == null) {
callback.onSuccess(new EaseUser(username));
}
}
});
} else {
callback.onError(error, errorMsg);
}
}
});
}
public void asyncGetUserInfo(final String username, final EMValueCallBack<EaseUser> callback) {
ParseQuery<ParseObject> pQuery = ParseQuery.getQuery(CONFIG_TABLE_NAME);
pQuery.whereEqualTo(CONFIG_USERNAME, username);
pQuery.getFirstInBackground(new GetCallback<ParseObject>() {
@Override
public void done(ParseObject pUser, ParseException e) {
if (pUser != null) {
String nick = pUser.getString(CONFIG_NICK);
ParseFile pFile = pUser.getParseFile(CONFIG_AVATAR);
if (callback != null) {
EaseUser user = DemoHelper.getInstance().getContactList().get(username);
if (user != null) {
user.setNick(nick);
if (pFile != null && pFile.getUrl() != null) {
user.setAvatar(pFile.getUrl());
}
} else {
user = new EaseUser(username);
user.setNick(nick);
if (pFile != null && pFile.getUrl() != null) {
user.setAvatar(pFile.getUrl());
}
}
callback.onSuccess(user);
}
} else {
if (callback != null) {
callback.onError(e.getCode(), e.getMessage());
}
}
}
});
}
public String uploadParseAvatar(byte[] data) {
String username = EMChatManager.getInstance().getCurrentUser();
ParseQuery<ParseObject> pQuery = ParseQuery.getQuery(CONFIG_TABLE_NAME);
pQuery.whereEqualTo(CONFIG_USERNAME, username);
ParseObject pUser = null;
try {
pUser = pQuery.getFirst();
if (pUser == null) {
pUser = new ParseObject(CONFIG_TABLE_NAME);
pUser.put(CONFIG_USERNAME, username);
}
ParseFile pFile = new ParseFile(data);
pUser.put(CONFIG_AVATAR, pFile);
pUser.save();
return pFile.getUrl();
} catch (ParseException e) {
if (e.getCode() == ParseException.OBJECT_NOT_FOUND) {
try {
pUser = new ParseObject(CONFIG_TABLE_NAME);
pUser.put(CONFIG_USERNAME, username);
ParseFile pFile = new ParseFile(data);
pUser.put(CONFIG_AVATAR, pFile);
pUser.save();
return pFile.getUrl();
} catch (ParseException e1) {
e1.printStackTrace();
EMLog.e(TAG, "parse error " + e1.getMessage());
}
} else {
e.printStackTrace();
EMLog.e(TAG, "parse error " + e.getMessage());
}
}
return null;
}
}
|
/*
* MIT License
*
* Copyright (c) 2022 MASES s.r.l.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
/**************************************************************************************
* <auto-generated>
* This code was generated from a template using JCOReflector
*
* Manual changes to this file may cause unexpected behavior in your application.
* Manual changes to this file will be overwritten if the code is regenerated.
* </auto-generated>
*************************************************************************************/
package system.windows.annotations;
import org.mases.jcobridge.*;
import org.mases.jcobridge.netreflection.*;
// Import section
// PACKAGE_IMPORT_SECTION
/**
* The base .NET class managing System.Windows.Annotations.AnnotationAction, PresentationFramework, Version=6.0.2.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35.
* <p>
*
* See: <a href="https://docs.microsoft.com/en-us/dotnet/api/System.Windows.Annotations.AnnotationAction" target="_top">https://docs.microsoft.com/en-us/dotnet/api/System.Windows.Annotations.AnnotationAction</a>
*/
public class AnnotationAction extends NetObject {
/**
* Fully assembly qualified name: PresentationFramework, Version=6.0.2.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35
*/
public static final String assemblyFullName = "PresentationFramework, Version=6.0.2.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35";
/**
* Assembly name: PresentationFramework
*/
public static final String assemblyShortName = "PresentationFramework";
/**
* Qualified class name: System.Windows.Annotations.AnnotationAction
*/
public static final String className = "System.Windows.Annotations.AnnotationAction";
static JCOBridge bridge = JCOBridgeInstance.getInstance(assemblyFullName);
/**
* The type managed from JCOBridge. See {@link JCType}
*/
public static JCType classType = createType();
static JCEnum enumReflected = createEnum();
JCEnum classInstance = null;
static JCType createType() {
try {
String classToCreate = className + ", "
+ (JCOReflector.getUseFullAssemblyName() ? assemblyFullName : assemblyShortName);
if (JCOReflector.getDebug())
JCOReflector.writeLog("Creating %s", classToCreate);
JCType typeCreated = bridge.GetType(classToCreate);
if (JCOReflector.getDebug())
JCOReflector.writeLog("Created: %s",
(typeCreated != null) ? typeCreated.toString() : "Returned null value");
return typeCreated;
} catch (JCException e) {
JCOReflector.writeLog(e);
return null;
}
}
static JCEnum createEnum() {
try {
String enumToCreate = className + ", "
+ (JCOReflector.getUseFullAssemblyName() ? assemblyFullName : assemblyShortName);
if (JCOReflector.getDebug())
JCOReflector.writeLog("Creating Enum %s", enumToCreate);
JCEnum enumCreated = bridge.GetEnum(enumToCreate);
if (JCOReflector.getDebug())
JCOReflector.writeLog("Created Enum: %s",
(enumCreated != null) ? enumCreated.toString() : "Returned null value");
return enumCreated;
} catch (JCException e) {
JCOReflector.writeLog(e);
return null;
}
}
void addReference(String ref) throws Throwable {
try {
bridge.AddReference(ref);
} catch (JCNativeException jcne) {
throw translateException(jcne);
}
}
/**
* Internal constructor. Use with caution
*/
public AnnotationAction(java.lang.Object instance) {
super(instance);
if (instance instanceof JCObject) {
try {
String enumName = NetEnum.GetName(classType, (JCObject)instance);
classInstance = enumReflected.fromValue(enumName);
} catch (Throwable t) {
JCOReflector.writeLog(t);
classInstance = enumReflected;
}
} else if (instance instanceof JCEnum) {
classInstance = (JCEnum)instance;
}
}
public AnnotationAction() {
super();
// add reference to assemblyName.dll file
try {
addReference(JCOReflector.getUseFullAssemblyName() ? assemblyFullName : assemblyShortName);
} catch (Throwable jcne) {
JCOReflector.writeLog(jcne);
}
}
public String getJCOAssemblyName() {
return assemblyFullName;
}
public String getJCOClassName() {
return className;
}
public String getJCOObjectName() {
return className + ", " + (JCOReflector.getUseFullAssemblyName() ? assemblyFullName : assemblyShortName);
}
public java.lang.Object getJCOInstance() {
return classInstance;
}
public JCType getJCOType() {
return classType;
}
final static AnnotationAction getFrom(JCEnum object, String value) {
try {
return new AnnotationAction(object.fromValue(value));
} catch (JCException e) {
return new AnnotationAction(object);
}
}
// Enum fields section
public static AnnotationAction Added = getFrom(enumReflected, "Added");
public static AnnotationAction Removed = getFrom(enumReflected, "Removed");
public static AnnotationAction Modified = getFrom(enumReflected, "Modified");
// Flags management section
}
|
/*
* The MIT License (MIT)
*
* Copyright (c) 2016. Diorite (by Bartłomiej Mazur (aka GotoFinal))
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package org.diorite.impl.connection.packets.login;
import org.diorite.impl.connection.listeners.PacketLoginListener;
import org.diorite.impl.connection.packets.login.serverbound.PacketLoginServerboundEncryptionBegin;
import org.diorite.impl.connection.packets.login.serverbound.PacketLoginServerboundStart;
public interface PacketLoginServerboundListener extends PacketLoginListener
{
void tick();
void handle(PacketLoginServerboundStart packet);
void handle(PacketLoginServerboundEncryptionBegin packet);
}
|
/*
* Copyright (C) 2015 The Minium 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 minium.web.internal.actions;
import org.openqa.selenium.StaleElementReferenceException;
public class DefaultOnStaleElementReferenceInteractionListener extends DefaultOnExceptionInteractionListener {
@SuppressWarnings("unchecked")
public DefaultOnStaleElementReferenceInteractionListener() {
super(StaleElementReferenceException.class);
}
}
|
package data.entities;
import data.entities.abstracts.AbstractEntity;
import data.models.Column;
import data.models.CountMethod;
import static data.entities.abstracts.DataType.*;
@SuppressWarnings("all")
public class Company extends AbstractEntity {
Column companyName = of(DESCRIPTION);
Column companyDesc = of(DESCRIPTION);
Column hotLine = of(PHONE);
Column isLock = of(FALSE);
CountMethod totalEmployees = count(Employee.class);
CountMethod totalBusses = count(Buss.class);
CountMethod totalBussEmployees = count(BussEmployee.class);
CountMethod totalTrips = count(Trip.class);
CountMethod totalSchedules = count(BussSchedule.class);
@Override
public boolean hasProfileImage() {
return true;
}
}
|
package top.wilsonlv.jaguar.cloud.handlerlog.client.dto;
import lombok.Data;
import lombok.EqualsAndHashCode;
import top.wilsonlv.jaguar.commons.web.base.BaseDTO;
import java.time.LocalDateTime;
/**
* @author lvws
* @since 2021/8/6
*/
@Data
@EqualsAndHashCode(callSuper = true)
public class HandlerLogSaveDTO extends BaseDTO {
/**
* 会话ID
*/
private String sessionId;
/**
* authorization
*/
private String authorization;
/**
* 访问时间
*/
private LocalDateTime accessTime;
/**
* 客户端IP
*/
private String clientHost;
/**
* 请求地址
*/
private String requestUri;
/**
* 接口操作名称
*/
private String apiOperation;
/**
* 请求参数
*/
private String parameters;
/**
* 请求方式
*/
private String method;
/**
* 客户端引擎
*/
private String userAgent;
/**
* http响应状态码
*/
private Integer status;
/**
* 错误信息
*/
private String errorMsg;
/**
* 响应时长
*/
private Long duration;
/**
* 创建人
*/
private String createBy;
/**
* 创建人ID
*/
private Long createUserId;
/**
* 响应结果
*/
private String jsonResult;
}
|
package com.samourai.wallet.home;
import android.Manifest;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.arch.lifecycle.Observer;
import android.arch.lifecycle.ViewModelProviders;
import android.content.BroadcastReceiver;
import android.content.ClipData;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.ActivityInfo;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.support.annotation.Nullable;
import android.support.design.widget.AppBarLayout;
import android.support.design.widget.CollapsingToolbarLayout;
import android.support.transition.ChangeBounds;
import android.support.transition.TransitionManager;
import android.support.v4.content.LocalBroadcastManager;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.text.InputType;
import android.util.Log;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.Toast;
import org.bitcoinj.core.ECKey;
import org.bitcoinj.core.Coin;
import org.bitcoinj.crypto.BIP38PrivateKey;
import org.bitcoinj.crypto.MnemonicException;
import org.bitcoinj.script.Script;
import com.dm.zbar.android.scanner.ZBarConstants;
import com.dm.zbar.android.scanner.ZBarScannerActivity;
import com.samourai.wallet.ExodusActivity;
import com.samourai.wallet.JSONRPC.JSONRPC;
import com.samourai.wallet.JSONRPC.PoW;
import com.samourai.wallet.JSONRPC.TrustedNodeUtil;
import com.samourai.wallet.R;
import com.samourai.wallet.ReceiveActivity;
import com.samourai.wallet.SamouraiWallet;
import com.samourai.wallet.SendActivity;
import com.samourai.wallet.SettingsActivity;
import com.samourai.wallet.UTXOActivity;
import com.samourai.wallet.access.AccessFactory;
import com.samourai.wallet.api.APIFactory;
import com.samourai.wallet.api.Tx;
import com.samourai.wallet.bip47.BIP47Meta;
import com.samourai.wallet.bip47.BIP47Util;
import com.samourai.wallet.bip47.paynym.ClaimPayNymActivity;
import com.samourai.wallet.cahoots.Cahoots;
import com.samourai.wallet.cahoots.util.CahootsUtil;
import com.samourai.wallet.crypto.AESUtil;
import com.samourai.wallet.crypto.DecryptionException;
import com.samourai.wallet.hd.HD_Wallet;
import com.samourai.wallet.hd.HD_WalletFactory;
import com.samourai.wallet.home.adapters.ItemDividerDecorator;
import com.samourai.wallet.home.adapters.TxAdapter;
import com.samourai.wallet.network.NetworkDashboard;
import com.samourai.wallet.network.dojo.DojoUtil;
import com.samourai.wallet.payload.PayloadUtil;
import com.samourai.wallet.permissions.PermissionsUtil;
import com.samourai.wallet.ricochet.RicochetMeta;
import com.samourai.wallet.segwit.bech32.Bech32Util;
import com.samourai.wallet.send.BlockedUTXO;
import com.samourai.wallet.send.MyTransactionOutPoint;
import com.samourai.wallet.send.SweepUtil;
import com.samourai.wallet.send.UTXO;
import com.samourai.wallet.service.RefreshService;
import com.samourai.wallet.service.WebSocketService;
import com.samourai.wallet.tor.TorManager;
import com.samourai.wallet.tor.TorService;
import com.samourai.wallet.tx.TxDetailsActivity;
import com.samourai.wallet.util.AppUtil;
import com.samourai.wallet.util.CharSequenceX;
import com.samourai.wallet.util.FormatsUtil;
import com.samourai.wallet.util.MessageSignUtil;
import com.samourai.wallet.util.MonetaryUtil;
import com.samourai.wallet.util.PrefsUtil;
import com.samourai.wallet.util.PrivKeyReader;
import com.samourai.wallet.util.TimeOutUtil;
import com.samourai.wallet.util.TorUtil;
import com.samourai.wallet.util.TypefaceUtil;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.bouncycastle.util.encoders.Hex;
import net.i2p.android.ext.floatingactionbutton.FloatingActionButton;
import net.i2p.android.ext.floatingactionbutton.FloatingActionsMenu;
import com.squareup.picasso.Callback;
import com.squareup.picasso.Picasso;
import com.yanzhenjie.zbar.Symbol;
import org.bouncycastle.util.encoders.Hex;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.IOException;
import java.text.DecimalFormat;
import java.text.DecimalFormatSymbols;
import java.util.ArrayList;
import java.util.Collections;
import java.util.ConcurrentModificationException;
import java.util.Iterator;
import java.util.List;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.CompositeDisposable;
import io.reactivex.disposables.Disposable;
import io.reactivex.schedulers.Schedulers;
public class BalanceActivity extends AppCompatActivity {
private final static int SCAN_COLD_STORAGE = 2011;
private final static int SCAN_QR = 2012;
private static final String TAG = "BalanceActivity";
private List<Tx> txs = null;
private RecyclerView TxRecyclerView;
private ProgressBar progressBar;
private BalanceViewModel balanceViewModel;
private PoWTask powTask = null;
private RicochetQueueTask ricochetQueueTask = null;
private com.github.clans.fab.FloatingActionMenu menuFab;
private SwipeRefreshLayout txSwipeLayout;
private CollapsingToolbarLayout mCollapsingToolbar;
private CompositeDisposable compositeDisposable = new CompositeDisposable();
private Toolbar toolbar;
private Menu menu;
private ImageView menuTorIcon;
private ProgressBar progressBarMenu;
public static final String ACTION_INTENT = "com.samourai.wallet.BalanceFragment.REFRESH";
protected BroadcastReceiver receiver = new BroadcastReceiver() {
@Override
public void onReceive(final Context context, Intent intent) {
if (ACTION_INTENT.equals(intent.getAction())) {
if (progressBar != null) {
progressBar.setVisibility(View.VISIBLE);
}
final boolean notifTx = intent.getBooleanExtra("notifTx", false);
final boolean fetch = intent.getBooleanExtra("fetch", false);
final String rbfHash;
final String blkHash;
if (intent.hasExtra("rbf")) {
rbfHash = intent.getStringExtra("rbf");
} else {
rbfHash = null;
}
if (intent.hasExtra("hash")) {
blkHash = intent.getStringExtra("hash");
} else {
blkHash = null;
}
Handler handler = new Handler();
handler.post(() -> {
refreshTx(notifTx, false, false);
if (BalanceActivity.this != null) {
if (rbfHash != null) {
new AlertDialog.Builder(BalanceActivity.this)
.setTitle(R.string.app_name)
.setMessage(rbfHash + "\n\n" + getString(R.string.rbf_incoming))
.setCancelable(true)
.setPositiveButton(R.string.yes, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
doExplorerView(rbfHash);
}
})
.setNegativeButton(R.string.no, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
;
}
}).show();
}
}
});
if (BalanceActivity.this != null && blkHash != null && PrefsUtil.getInstance(BalanceActivity.this).getValue(PrefsUtil.USE_TRUSTED_NODE, false) == true && TrustedNodeUtil.getInstance().isSet()) {
// BalanceActivity.this.runOnUiThread(new Runnable() {
// @Override
handler.post(new Runnable() {
public void run() {
if (powTask == null || powTask.getStatus().equals(AsyncTask.Status.FINISHED)) {
powTask = new PoWTask();
powTask.executeOnExecutor(AsyncTask.SERIAL_EXECUTOR, blkHash);
}
}
});
}
}
}
};
public static final String DISPLAY_INTENT = "com.samourai.wallet.BalanceFragment.DISPLAY";
protected BroadcastReceiver receiverDisplay = new BroadcastReceiver() {
@Override
public void onReceive(final Context context, Intent intent) {
if (DISPLAY_INTENT.equals(intent.getAction())) {
updateDisplay(true);
List<UTXO> utxos = APIFactory.getInstance(BalanceActivity.this).getUtxos(false);
for (UTXO utxo : utxos) {
List<MyTransactionOutPoint> outpoints = utxo.getOutpoints();
for (MyTransactionOutPoint out : outpoints) {
byte[] scriptBytes = out.getScriptBytes();
String address = null;
try {
if (Bech32Util.getInstance().isBech32Script(Hex.toHexString(scriptBytes))) {
address = Bech32Util.getInstance().getAddressFromScript(Hex.toHexString(scriptBytes));
} else {
address = new Script(scriptBytes).getToAddress(SamouraiWallet.getInstance().getCurrentNetworkParams()).toString();
}
} catch (Exception e) {
}
String path = APIFactory.getInstance(BalanceActivity.this).getUnspentPaths().get(address);
if (path != null && path.startsWith("M/1/")) {
continue;
}
final String hash = out.getHash().toString();
final int idx = out.getTxOutputN();
final long amount = out.getValue().longValue();
if (amount < BlockedUTXO.BLOCKED_UTXO_THRESHOLD &&
!BlockedUTXO.getInstance().contains(hash, idx) &&
!BlockedUTXO.getInstance().containsNotDusted(hash, idx)) {
// BalanceActivity.this.runOnUiThread(new Runnable() {
// @Override
Handler handler = new Handler();
handler.post(new Runnable() {
public void run() {
String message = BalanceActivity.this.getString(R.string.dusting_attempt);
message += "\n\n";
message += BalanceActivity.this.getString(R.string.dusting_attempt_amount);
message += " ";
message += Coin.valueOf(amount).toPlainString();
message += " BTC\n";
message += BalanceActivity.this.getString(R.string.dusting_attempt_id);
message += " ";
message += hash + "-" + idx;
AlertDialog.Builder dlg = new AlertDialog.Builder(BalanceActivity.this)
.setTitle(R.string.dusting_tx)
.setMessage(message)
.setCancelable(false)
.setPositiveButton(R.string.dusting_attempt_mark_unspendable, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
BlockedUTXO.getInstance().add(hash, idx, amount);
}
}).setNegativeButton(R.string.dusting_attempt_ignore, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
BlockedUTXO.getInstance().addNotDusted(hash, idx);
}
});
if (!isFinishing()) {
dlg.show();
}
}
});
}
}
}
}
}
};
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_balance);
balanceViewModel = ViewModelProviders.of(this).get(BalanceViewModel.class);
makePaynymAvatarcache();
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
TxRecyclerView = findViewById(R.id.rv_txes);
progressBar = findViewById(R.id.progressBar);
toolbar = findViewById(R.id.toolbar);
mCollapsingToolbar = findViewById(R.id.toolbar_layout);
txSwipeLayout = findViewById(R.id.tx_swipe_container);
setSupportActionBar(toolbar);
TxRecyclerView.setLayoutManager(new LinearLayoutManager(this));
TxRecyclerView.addItemDecoration(new ItemDividerDecorator(getApplicationContext()));
menuFab = findViewById(R.id.fab_menu);
findViewById(R.id.send_fab).setOnClickListener(view -> {
Intent intent = new Intent(BalanceActivity.this, SendActivity.class);
intent.putExtra("via_menu", true);
startActivity(intent);
menuFab.toggle(true);
});
setBalance(0L, false);
findViewById(R.id.receive_fab).setOnClickListener(view -> {
menuFab.toggle(true);
try {
HD_Wallet hdw = HD_WalletFactory.getInstance(BalanceActivity.this).get();
if (hdw != null) {
Intent intent = new Intent(BalanceActivity.this, ReceiveActivity.class);
startActivity(intent);
}
} catch (IOException | MnemonicException.MnemonicLengthException e) {
}
});
findViewById(R.id.paynym_fab).setOnClickListener(view -> {
menuFab.toggle(true);
Intent intent = new Intent(BalanceActivity.this, com.samourai.wallet.bip47.BIP47Activity.class);
startActivity(intent);
});
getSupportActionBar().setIcon(R.drawable.ic_samourai_logo_toolbar);
txSwipeLayout.setOnRefreshListener(() -> {
refreshTx(false, true, false);
txSwipeLayout.setRefreshing(false);
progressBar.setVisibility(View.VISIBLE);
});
IntentFilter filter = new IntentFilter(ACTION_INTENT);
LocalBroadcastManager.getInstance(BalanceActivity.this).registerReceiver(receiver, filter);
IntentFilter filterDisplay = new IntentFilter(DISPLAY_INTENT);
LocalBroadcastManager.getInstance(BalanceActivity.this).registerReceiver(receiverDisplay, filterDisplay);
if (!PermissionsUtil.getInstance(BalanceActivity.this).hasPermission(Manifest.permission.READ_EXTERNAL_STORAGE) || !PermissionsUtil.getInstance(BalanceActivity.this).hasPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
PermissionsUtil.getInstance(BalanceActivity.this).showRequestPermissionsInfoAlertDialog(PermissionsUtil.READ_WRITE_EXTERNAL_PERMISSION_CODE);
}
if (!PermissionsUtil.getInstance(BalanceActivity.this).hasPermission(Manifest.permission.CAMERA)) {
PermissionsUtil.getInstance(BalanceActivity.this).showRequestPermissionsInfoAlertDialog(PermissionsUtil.CAMERA_PERMISSION_CODE);
}
if (PrefsUtil.getInstance(BalanceActivity.this).getValue(PrefsUtil.PAYNYM_CLAIMED, false) == true && PrefsUtil.getInstance(BalanceActivity.this).getValue(PrefsUtil.PAYNYM_FEATURED_SEGWIT, false) == false) {
doFeaturePayNymUpdate();
} else if (PrefsUtil.getInstance(BalanceActivity.this).getValue(PrefsUtil.PAYNYM_CLAIMED, false) == false &&
PrefsUtil.getInstance(BalanceActivity.this).getValue(PrefsUtil.PAYNYM_REFUSED, false) == false) {
doClaimPayNym();
} else {
}
if (RicochetMeta.getInstance(BalanceActivity.this).getQueue().size() > 0) {
if (ricochetQueueTask == null || ricochetQueueTask.getStatus().equals(AsyncTask.Status.FINISHED)) {
ricochetQueueTask = new RicochetQueueTask();
ricochetQueueTask.executeOnExecutor(AsyncTask.SERIAL_EXECUTOR);
}
}
if (!AppUtil.getInstance(BalanceActivity.this).isClipboardSeen()) {
doClipboardCheck();
}
final Handler delayedHandler = new Handler();
delayedHandler.postDelayed(() -> {
boolean notifTx = false;
Bundle extras = getIntent().getExtras();
if (extras != null && extras.containsKey("notifTx")) {
notifTx = extras.getBoolean("notifTx");
}
refreshTx(notifTx, false, true);
updateDisplay(false);
}, 100L);
if (!AppUtil.getInstance(BalanceActivity.this.getApplicationContext()).isServiceRunning(WebSocketService.class)) {
startService(new Intent(BalanceActivity.this.getApplicationContext(), WebSocketService.class));
}
setUpTor();
initViewModel();
updateDisplay(false);
progressBar.setVisibility(View.VISIBLE);
}
private void initViewModel() {
TxAdapter adapter = new TxAdapter(getApplicationContext(), new ArrayList<>());
adapter.setHasStableIds(true);
adapter.setClickListner((position, tx) -> txDetails(tx));
TxRecyclerView.setAdapter(adapter);
balanceViewModel.getBalance().observe(this, balance -> {
if (balanceViewModel.getSatState().getValue() != null) {
setBalance(balance, balanceViewModel.getSatState().getValue());
} else {
setBalance(balance, false);
}
});
adapter.setTxes(balanceViewModel.getTxs().getValue());
setBalance(balanceViewModel.getBalance().getValue(), false);
balanceViewModel.getSatState().observe(this, state -> {
if (state == null) {
state = false;
}
setBalance(balanceViewModel.getBalance().getValue(), state);
adapter.toggleDisplayUnit(state);
});
balanceViewModel.getTxs().observe(this, new Observer<List<Tx>>() {
@Override
public void onChanged(@Nullable List<Tx> list) {
adapter.setTxes(list);
}
});
mCollapsingToolbar.setOnClickListener(view -> balanceViewModel.toggleSat());
}
private void setBalance(Long balance, boolean isSat) {
if (balance == null) {
return;
}
if (getSupportActionBar() != null) {
TransitionManager.beginDelayedTransition(mCollapsingToolbar, new ChangeBounds());
String displayAmount = "".concat(isSat ? getSatoshiDisplayAmount(balance) : getBTCDisplayAmount(balance));
String Unit = isSat ? getSatoshiDisplayUnits() : getBTCDisplayUnits();
displayAmount = displayAmount.concat(" ").concat(Unit);
toolbar.setTitle(displayAmount);
setTitle(displayAmount);
mCollapsingToolbar.setTitle(displayAmount);
}
Log.i(TAG, "setBalance: ".concat(getBTCDisplayAmount(balance)));
}
@Override
public void onResume() {
super.onResume();
// IntentFilter filter = new IntentFilter(ACTION_INTENT);
// LocalBroadcastManager.getInstance(BalanceActivity.this).registerReceiver(receiver, filter);
AppUtil.getInstance(BalanceActivity.this).checkTimeOut();
Intent intent = new Intent("com.samourai.wallet.MainActivity2.RESTART_SERVICE");
LocalBroadcastManager.getInstance(BalanceActivity.this).sendBroadcast(intent);
}
@Override
public void onPause() {
super.onPause();
// ibQuickSend.collapse();
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O && AppUtil.getInstance(BalanceActivity.this.getApplicationContext()).isServiceRunning(WebSocketService.class)) {
stopService(new Intent(BalanceActivity.this.getApplicationContext(), WebSocketService.class));
}
}
private void makePaynymAvatarcache() {
try {
ArrayList<String> paymentCodes = new ArrayList<>(BIP47Meta.getInstance().getSortedByLabels(false, true));
for (String code : paymentCodes) {
Picasso.with(getBaseContext())
.load(com.samourai.wallet.bip47.paynym.WebUtil.PAYNYM_API + code + "/avatar").fetch(new Callback() {
@Override
public void onSuccess() {
/*NO OP*/
}
@Override
public void onError() {
/*NO OP*/
}
});
}
} catch (Exception ignored) {
}
}
@Override
public void onDestroy() {
LocalBroadcastManager.getInstance(BalanceActivity.this).unregisterReceiver(receiver);
LocalBroadcastManager.getInstance(BalanceActivity.this).unregisterReceiver(receiverDisplay);
if (AppUtil.getInstance(BalanceActivity.this.getApplicationContext()).isServiceRunning(WebSocketService.class)) {
stopService(new Intent(BalanceActivity.this.getApplicationContext(), WebSocketService.class));
}
compositeDisposable.dispose();
super.onDestroy();
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main, menu);
menu.findItem(R.id.action_refresh).setVisible(false);
menu.findItem(R.id.action_share_receive).setVisible(false);
menu.findItem(R.id.action_ricochet).setVisible(false);
menu.findItem(R.id.action_empty_ricochet).setVisible(false);
menu.findItem(R.id.action_sign).setVisible(false);
menu.findItem(R.id.action_fees).setVisible(false);
menu.findItem(R.id.action_batch).setVisible(false);
this.menu = menu;
return super.onCreateOptionsMenu(menu);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
// noinspection SimplifiableIfStatement
if(id == R.id.action_network_dashboard){
startActivity(new Intent(this, NetworkDashboard.class));
}
if (id == R.id.action_settings) {
doSettings();
} else if (id == R.id.action_support) {
doSupport();
} else if (id == R.id.action_sweep) {
if (!AppUtil.getInstance(BalanceActivity.this).isOfflineMode()) {
doSweep();
} else {
Toast.makeText(BalanceActivity.this, R.string.in_offline_mode, Toast.LENGTH_SHORT).show();
}
} else if (id == R.id.action_utxo) {
doUTXO();
} else if (id == R.id.action_backup) {
if (SamouraiWallet.getInstance().hasPassphrase(BalanceActivity.this)) {
try {
if (HD_WalletFactory.getInstance(BalanceActivity.this).get() != null && SamouraiWallet.getInstance().hasPassphrase(BalanceActivity.this)) {
doBackup();
} else {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setMessage(R.string.passphrase_needed_for_backup).setCancelable(false);
AlertDialog alert = builder.create();
alert.setButton(AlertDialog.BUTTON_POSITIVE, getString(R.string.ok), new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.dismiss();
}
});
if (!isFinishing()) {
alert.show();
}
}
} catch (MnemonicException.MnemonicLengthException mle) {
} catch (IOException ioe) {
}
} else {
Toast.makeText(BalanceActivity.this, R.string.passphrase_required, Toast.LENGTH_SHORT).show();
}
} else if (id == R.id.action_scan_qr) {
doScan();
} else {
}
return super.onOptionsItemSelected(item);
}
private void startTor() {
progressBarMenu.setVisibility(View.VISIBLE);
Intent startIntent = new Intent(getApplicationContext(), TorService.class);
startIntent.setAction(TorService.START_SERVICE);
startService(startIntent);
}
private void stopTor() {
Intent startIntent = new Intent(getApplicationContext(), TorService.class);
startIntent.setAction(TorService.STOP_SERVICE);
startService(startIntent);
}
private void setUpTor() {
Disposable disposable = TorManager.getInstance(this)
.torStatus
.subscribeOn(Schedulers.newThread())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(state -> {
if (state == TorManager.CONNECTION_STATES.CONNECTED) {
PrefsUtil.getInstance(this).setValue(PrefsUtil.ENABLE_TOR, true);
if (this.progressBarMenu != null) {
this.progressBarMenu.setVisibility(View.INVISIBLE);
this.menuTorIcon.setImageResource(R.drawable.tor_on);
}
} else if (state == TorManager.CONNECTION_STATES.CONNECTING) {
if (this.progressBarMenu != null) {
this.progressBarMenu.setVisibility(View.VISIBLE);
this.menuTorIcon.setImageResource(R.drawable.tor_on);
}
} else {
if (this.progressBarMenu != null) {
this.progressBarMenu.setVisibility(View.INVISIBLE);
this.menuTorIcon.setImageResource(R.drawable.tor_off);
}
}
});
compositeDisposable.add(disposable);
}
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == Activity.RESULT_OK && requestCode == SCAN_COLD_STORAGE) {
if (data != null && data.getStringExtra(ZBarConstants.SCAN_RESULT) != null) {
final String strResult = data.getStringExtra(ZBarConstants.SCAN_RESULT);
doPrivKey(strResult);
}
} else if (resultCode == Activity.RESULT_CANCELED && requestCode == SCAN_COLD_STORAGE) {
} else if (resultCode == Activity.RESULT_OK && requestCode == SCAN_QR) {
if (data != null && data.getStringExtra(ZBarConstants.SCAN_RESULT) != null) {
final String strResult = data.getStringExtra(ZBarConstants.SCAN_RESULT);
PrivKeyReader privKeyReader = new PrivKeyReader(new CharSequenceX(strResult.trim()));
try {
if (privKeyReader.getFormat() != null) {
doPrivKey(strResult.trim());
} else if (Cahoots.isCahoots(strResult.trim())) {
CahootsUtil.getInstance(BalanceActivity.this).processCahoots(strResult.trim());
} else if (FormatsUtil.getInstance().isPSBT(strResult.trim())) {
CahootsUtil.getInstance(BalanceActivity.this).doPSBT(strResult.trim());
} else if (DojoUtil.getInstance().isValidPairingPayload(strResult.trim())) {
Toast.makeText(BalanceActivity.this, "Samourai Dojo full node coming soon.", Toast.LENGTH_SHORT).show();
} else {
Intent intent = new Intent(BalanceActivity.this, SendActivity.class);
intent.putExtra("uri", strResult.trim());
startActivity(intent);
}
} catch (Exception e) {
}
}
} else if (resultCode == Activity.RESULT_CANCELED && requestCode == SCAN_QR) {
} else {
;
}
}
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_BACK) {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setMessage(R.string.ask_you_sure_exit).setCancelable(false);
AlertDialog alert = builder.create();
alert.setButton(AlertDialog.BUTTON_POSITIVE, getString(R.string.yes), new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
try {
PayloadUtil.getInstance(BalanceActivity.this).saveWalletToJSON(new CharSequenceX(AccessFactory.getInstance(BalanceActivity.this).getGUID() + AccessFactory.getInstance(BalanceActivity.this).getPIN()));
} catch (MnemonicException.MnemonicLengthException mle) {
} catch (JSONException je) {
} catch (IOException ioe) {
} catch (DecryptionException de) {
}
Intent intent = new Intent(BalanceActivity.this, ExodusActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS | Intent.FLAG_ACTIVITY_SINGLE_TOP);
BalanceActivity.this.startActivity(intent);
}
});
alert.setButton(AlertDialog.BUTTON_NEGATIVE, getString(R.string.no), new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.dismiss();
}
});
if (!isFinishing()) {
alert.show();
}
return true;
} else {
}
return false;
}
private void updateDisplay(boolean fromRefreshService) {
txs = APIFactory.getInstance(BalanceActivity.this).getAllXpubTxs();
long balance = 0L;
try {
balance = APIFactory.getInstance(BalanceActivity.this).getXpubAmounts().get(HD_WalletFactory.getInstance(BalanceActivity.this).get().getAccount(0).xpubstr());
} catch (IOException ioe) {
} catch (MnemonicException.MnemonicLengthException mle) {
} catch (NullPointerException npe) {
}
if (balanceViewModel.getBalance().getValue() != null) {
if (balance != 0L) {
balanceViewModel.setBalance(balance);
}
} else {
balanceViewModel.setBalance(balance);
}
if (txs.size() != 0) {
balanceViewModel.setTx(txs);
} else {
if (balanceViewModel.getTxs().getValue() != null && balanceViewModel.getTxs().getValue().size() == 0) {
balanceViewModel.setTx(txs);
}
}
if (progressBar.getVisibility() == View.VISIBLE && fromRefreshService) {
progressBar.setVisibility(View.INVISIBLE);
}
if (txs != null) {
Collections.sort(txs, new APIFactory.TxMostRecentDateComparator());
}
// displayBalance();
// txAdapter.notifyDataSetChanged();
}
private void doClaimPayNym() {
Intent intent = new Intent(BalanceActivity.this, ClaimPayNymActivity.class);
startActivity(intent);
}
private void doSettings() {
TimeOutUtil.getInstance().updatePin();
Intent intent = new Intent(BalanceActivity.this, SettingsActivity.class);
startActivity(intent);
}
private void doSupport() {
Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse("https://samourai.kayako.com/"));
startActivity(intent);
}
private void doUTXO() {
Intent intent = new Intent(BalanceActivity.this, UTXOActivity.class);
startActivity(intent);
}
private void doScan() {
Intent intent = new Intent(BalanceActivity.this, ZBarScannerActivity.class);
intent.putExtra(ZBarConstants.SCAN_MODES, new int[]{Symbol.QRCODE});
startActivityForResult(intent, SCAN_QR);
}
private void doSweepViaScan() {
Intent intent = new Intent(BalanceActivity.this, ZBarScannerActivity.class);
intent.putExtra(ZBarConstants.SCAN_MODES, new int[]{Symbol.QRCODE});
startActivityForResult(intent, SCAN_COLD_STORAGE);
}
private void doSweep() {
AlertDialog.Builder dlg = new AlertDialog.Builder(BalanceActivity.this)
.setTitle(R.string.app_name)
.setMessage(R.string.action_sweep)
.setCancelable(true)
.setPositiveButton(R.string.enter_privkey, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
final EditText privkey = new EditText(BalanceActivity.this);
privkey.setInputType(InputType.TYPE_TEXT_FLAG_NO_SUGGESTIONS);
AlertDialog.Builder dlg = new AlertDialog.Builder(BalanceActivity.this)
.setTitle(R.string.app_name)
.setMessage(R.string.enter_privkey)
.setView(privkey)
.setCancelable(false)
.setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
final String strPrivKey = privkey.getText().toString();
if (strPrivKey != null && strPrivKey.length() > 0) {
doPrivKey(strPrivKey);
}
}
}).setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
dialog.dismiss();
}
});
if (!isFinishing()) {
dlg.show();
}
}
}).setNegativeButton(R.string.scan, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
doSweepViaScan();
}
});
if (!isFinishing()) {
dlg.show();
}
}
private void doPrivKey(final String data) {
PrivKeyReader privKeyReader = null;
String format = null;
try {
privKeyReader = new PrivKeyReader(new CharSequenceX(data), null);
format = privKeyReader.getFormat();
} catch (Exception e) {
Toast.makeText(BalanceActivity.this, e.getMessage(), Toast.LENGTH_SHORT).show();
return;
}
if (format != null) {
if (format.equals(PrivKeyReader.BIP38)) {
final PrivKeyReader pvr = privKeyReader;
final EditText password38 = new EditText(BalanceActivity.this);
password38.setSingleLine(true);
password38.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_PASSWORD | InputType.TYPE_TEXT_FLAG_NO_SUGGESTIONS);
AlertDialog.Builder dlg = new AlertDialog.Builder(BalanceActivity.this)
.setTitle(R.string.app_name)
.setMessage(R.string.bip38_pw)
.setView(password38)
.setCancelable(false)
.setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
String password = password38.getText().toString();
ProgressDialog progress = new ProgressDialog(BalanceActivity.this);
progress.setCancelable(false);
progress.setTitle(R.string.app_name);
progress.setMessage(getString(R.string.decrypting_bip38));
progress.show();
boolean keyDecoded = false;
try {
BIP38PrivateKey bip38 = new BIP38PrivateKey(SamouraiWallet.getInstance().getCurrentNetworkParams(), data);
final ECKey ecKey = bip38.decrypt(password);
if (ecKey != null && ecKey.hasPrivKey()) {
if (progress != null && progress.isShowing()) {
progress.cancel();
}
pvr.setPassword(new CharSequenceX(password));
keyDecoded = true;
Toast.makeText(BalanceActivity.this, pvr.getFormat(), Toast.LENGTH_SHORT).show();
Toast.makeText(BalanceActivity.this, pvr.getKey().toAddress(SamouraiWallet.getInstance().getCurrentNetworkParams()).toString(), Toast.LENGTH_SHORT).show();
}
} catch (Exception e) {
e.printStackTrace();
Toast.makeText(BalanceActivity.this, R.string.bip38_pw_error, Toast.LENGTH_SHORT).show();
}
if (progress != null && progress.isShowing()) {
progress.cancel();
}
if (keyDecoded) {
SweepUtil.getInstance(BalanceActivity.this).sweep(pvr, SweepUtil.TYPE_P2PKH);
}
}
}).setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
Toast.makeText(BalanceActivity.this, R.string.bip38_pw_error, Toast.LENGTH_SHORT).show();
}
});
if (!isFinishing()) {
dlg.show();
}
} else if (privKeyReader != null) {
SweepUtil.getInstance(BalanceActivity.this).sweep(privKeyReader, SweepUtil.TYPE_P2PKH);
} else {
;
}
} else {
Toast.makeText(BalanceActivity.this, R.string.cannot_recognize_privkey, Toast.LENGTH_SHORT).show();
}
}
private void doBackup() {
try {
final String passphrase = HD_WalletFactory.getInstance(BalanceActivity.this).get().getPassphrase();
final String[] export_methods = new String[2];
export_methods[0] = getString(R.string.export_to_clipboard);
export_methods[1] = getString(R.string.export_to_email);
new AlertDialog.Builder(BalanceActivity.this)
.setTitle(R.string.options_export)
.setSingleChoiceItems(export_methods, 0, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
try {
PayloadUtil.getInstance(BalanceActivity.this).saveWalletToJSON(new CharSequenceX(AccessFactory.getInstance(BalanceActivity.this).getGUID() + AccessFactory.getInstance(BalanceActivity.this).getPIN()));
} catch (IOException ioe) {
;
} catch (JSONException je) {
;
} catch (DecryptionException de) {
;
} catch (MnemonicException.MnemonicLengthException mle) {
;
}
String encrypted = null;
try {
encrypted = AESUtil.encrypt(PayloadUtil.getInstance(BalanceActivity.this).getPayload().toString(), new CharSequenceX(passphrase), AESUtil.DefaultPBKDF2Iterations);
} catch (Exception e) {
Toast.makeText(BalanceActivity.this, e.getMessage(), Toast.LENGTH_SHORT).show();
} finally {
if (encrypted == null) {
Toast.makeText(BalanceActivity.this, R.string.encryption_error, Toast.LENGTH_SHORT).show();
return;
}
}
JSONObject obj = PayloadUtil.getInstance(BalanceActivity.this).putPayload(encrypted, true);
if (which == 0) {
android.content.ClipboardManager clipboard = (android.content.ClipboardManager) getSystemService(android.content.Context.CLIPBOARD_SERVICE);
android.content.ClipData clip = null;
clip = android.content.ClipData.newPlainText("Wallet backup", obj.toString());
clipboard.setPrimaryClip(clip);
Toast.makeText(BalanceActivity.this, R.string.copied_to_clipboard, Toast.LENGTH_SHORT).show();
} else {
Intent email = new Intent(Intent.ACTION_SEND);
email.putExtra(Intent.EXTRA_SUBJECT, "Samourai Wallet backup");
email.putExtra(Intent.EXTRA_TEXT, obj.toString());
email.setType("message/rfc822");
startActivity(Intent.createChooser(email, BalanceActivity.this.getText(R.string.choose_email_client)));
}
dialog.dismiss();
}
}
).show();
} catch (IOException ioe) {
ioe.printStackTrace();
Toast.makeText(BalanceActivity.this, "HD wallet error", Toast.LENGTH_SHORT).show();
} catch (MnemonicException.MnemonicLengthException mle) {
mle.printStackTrace();
Toast.makeText(BalanceActivity.this, "HD wallet error", Toast.LENGTH_SHORT).show();
}
}
private void doClipboardCheck() {
final android.content.ClipboardManager clipboard = (android.content.ClipboardManager) BalanceActivity.this.getSystemService(android.content.Context.CLIPBOARD_SERVICE);
if (clipboard.hasPrimaryClip()) {
final ClipData clip = clipboard.getPrimaryClip();
ClipData.Item item = clip.getItemAt(0);
if (item.getText() != null) {
String text = item.getText().toString();
String[] s = text.split("\\s+");
try {
for (int i = 0; i < s.length; i++) {
PrivKeyReader privKeyReader = new PrivKeyReader(new CharSequenceX(s[i]));
if (privKeyReader.getFormat() != null &&
(privKeyReader.getFormat().equals(PrivKeyReader.WIF_COMPRESSED) ||
privKeyReader.getFormat().equals(PrivKeyReader.WIF_UNCOMPRESSED) ||
privKeyReader.getFormat().equals(PrivKeyReader.BIP38) ||
FormatsUtil.getInstance().isValidXprv(s[i])
)
) {
new AlertDialog.Builder(BalanceActivity.this)
.setTitle(R.string.app_name)
.setMessage(R.string.privkey_clipboard)
.setCancelable(false)
.setPositiveButton(R.string.yes, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
clipboard.setPrimaryClip(ClipData.newPlainText("", ""));
}
}).setNegativeButton(R.string.no, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
;
}
}).show();
}
}
} catch (Exception e) {
;
}
}
}
}
private void refreshTx(final boolean notifTx, final boolean dragged, final boolean launch) {
if (AppUtil.getInstance(BalanceActivity.this).isOfflineMode()) {
Toast.makeText(BalanceActivity.this, R.string.in_offline_mode, Toast.LENGTH_SHORT).show();
/*
CoordinatorLayout coordinatorLayout = new CoordinatorLayout(BalanceActivity.this);
Snackbar snackbar = Snackbar.make(coordinatorLayout, R.string.in_offline_mode, Snackbar.LENGTH_LONG);
snackbar.show();
*/
}
Intent intent = new Intent(BalanceActivity.this, RefreshService.class);
intent.putExtra("notifTx", notifTx);
intent.putExtra("dragged", dragged);
intent.putExtra("launch", launch);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
startForegroundService(intent);
} else {
startService(intent);
}
}
private String getBTCDisplayAmount(long value) {
return Coin.valueOf(value).toPlainString();
}
private String getSatoshiDisplayAmount(long value) {
DecimalFormatSymbols symbols = new DecimalFormatSymbols();
symbols.setGroupingSeparator(' ');
DecimalFormat df = new DecimalFormat("#", symbols);
df.setMinimumIntegerDigits(1);
df.setMaximumIntegerDigits(16);
df.setGroupingUsed(true);
df.setGroupingSize(3);
return df.format(value);
}
private String getBTCDisplayUnits() {
return MonetaryUtil.getInstance().getBTCUnits();
}
private String getSatoshiDisplayUnits() {
return MonetaryUtil.getInstance().getSatoshiUnits();
}
private void doExplorerView(String strHash) {
if (strHash != null) {
String blockExplorer = "https://m.oxt.me/transaction/";
if (SamouraiWallet.getInstance().isTestNet()) {
blockExplorer = "https://blockstream.info/testnet/";
}
Intent browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse(blockExplorer + strHash));
startActivity(browserIntent);
}
}
private void txDetails(Tx tx) {
Intent txIntent = new Intent(this, TxDetailsActivity.class);
txIntent.putExtra("TX", tx.toJSON().toString());
startActivity(txIntent);
}
private class RicochetQueueTask extends AsyncTask<String, Void, String> {
@Override
protected String doInBackground(String... params) {
if (RicochetMeta.getInstance(BalanceActivity.this).getQueue().size() > 0) {
int count = 0;
final Iterator<JSONObject> itr = RicochetMeta.getInstance(BalanceActivity.this).getIterator();
while (itr.hasNext()) {
if (count == 3) {
break;
}
try {
JSONObject jObj = itr.next();
JSONArray jHops = jObj.getJSONArray("hops");
if (jHops.length() > 0) {
JSONObject jHop = jHops.getJSONObject(jHops.length() - 1);
String txHash = jHop.getString("hash");
JSONObject txObj = APIFactory.getInstance(BalanceActivity.this).getTxInfo(txHash);
if (txObj != null && txObj.has("block_height") && txObj.getInt("block_height") != -1) {
itr.remove();
count++;
}
}
} catch (JSONException je) {
;
}
}
}
if (RicochetMeta.getInstance(BalanceActivity.this).getStaggered().size() > 0) {
int count = 0;
List<JSONObject> staggered = RicochetMeta.getInstance(BalanceActivity.this).getStaggered();
List<JSONObject> _staggered = new ArrayList<JSONObject>();
for (JSONObject jObj : staggered) {
if (count == 3) {
break;
}
try {
JSONArray jHops = jObj.getJSONArray("script");
if (jHops.length() > 0) {
JSONObject jHop = jHops.getJSONObject(jHops.length() - 1);
String txHash = jHop.getString("tx");
JSONObject txObj = APIFactory.getInstance(BalanceActivity.this).getTxInfo(txHash);
if (txObj != null && txObj.has("block_height") && txObj.getInt("block_height") != -1) {
count++;
} else {
_staggered.add(jObj);
}
}
} catch (JSONException je) {
;
} catch (ConcurrentModificationException cme) {
;
}
}
}
return "OK";
}
@Override
protected void onPostExecute(String result) {
;
}
@Override
protected void onPreExecute() {
;
}
}
private class PoWTask extends AsyncTask<String, Void, String> {
private boolean isOK = true;
private String strBlockHash = null;
@Override
protected String doInBackground(String... params) {
strBlockHash = params[0];
JSONRPC jsonrpc = new JSONRPC(TrustedNodeUtil.getInstance().getUser(), TrustedNodeUtil.getInstance().getPassword(), TrustedNodeUtil.getInstance().getNode(), TrustedNodeUtil.getInstance().getPort());
JSONObject nodeObj = jsonrpc.getBlockHeader(strBlockHash);
if (nodeObj != null && nodeObj.has("hash")) {
PoW pow = new PoW(strBlockHash);
String hash = pow.calcHash(nodeObj);
if (hash != null && hash.toLowerCase().equals(strBlockHash.toLowerCase())) {
JSONObject headerObj = APIFactory.getInstance(BalanceActivity.this).getBlockHeader(strBlockHash);
if (headerObj != null && headerObj.has("")) {
if (!pow.check(headerObj, nodeObj, hash)) {
isOK = false;
}
}
} else {
isOK = false;
}
}
return "OK";
}
@Override
protected void onPostExecute(String result) {
if (!isOK) {
new AlertDialog.Builder(BalanceActivity.this)
.setTitle(R.string.app_name)
.setMessage(getString(R.string.trusted_node_pow_failed) + "\n" + "Block hash:" + strBlockHash)
.setCancelable(false)
.setPositiveButton(R.string.close, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
dialog.dismiss();
}
}).show();
}
}
@Override
protected void onPreExecute() {
;
}
}
private void doFeaturePayNymUpdate() {
new Thread(new Runnable() {
private Handler handler = new Handler();
@Override
public void run() {
Looper.prepare();
try {
JSONObject obj = new JSONObject();
obj.put("code", BIP47Util.getInstance(BalanceActivity.this).getPaymentCode().toString());
// Log.d("BalanceActivity", obj.toString());
String res = com.samourai.wallet.bip47.paynym.WebUtil.getInstance(BalanceActivity.this).postURL("application/json", null, com.samourai.wallet.bip47.paynym.WebUtil.PAYNYM_API + "api/v1/token", obj.toString());
// Log.d("BalanceActivity", res);
JSONObject responseObj = new JSONObject(res);
if (responseObj.has("token")) {
String token = responseObj.getString("token");
String sig = MessageSignUtil.getInstance(BalanceActivity.this).signMessage(BIP47Util.getInstance(BalanceActivity.this).getNotificationAddress().getECKey(), token);
// Log.d("BalanceActivity", sig);
obj = new JSONObject();
obj.put("nym", BIP47Util.getInstance(BalanceActivity.this).getPaymentCode().toString());
obj.put("code", BIP47Util.getInstance(BalanceActivity.this).getFeaturePaymentCode().toString());
obj.put("signature", sig);
// Log.d("BalanceActivity", "nym/add:" + obj.toString());
res = com.samourai.wallet.bip47.paynym.WebUtil.getInstance(BalanceActivity.this).postURL("application/json", token, com.samourai.wallet.bip47.paynym.WebUtil.PAYNYM_API + "api/v1/nym/add", obj.toString());
// Log.d("BalanceActivity", res);
responseObj = new JSONObject(res);
if (responseObj.has("segwit") && responseObj.has("token")) {
PrefsUtil.getInstance(BalanceActivity.this).setValue(PrefsUtil.PAYNYM_FEATURED_SEGWIT, true);
} else if (responseObj.has("claimed") && responseObj.getBoolean("claimed") == true) {
PrefsUtil.getInstance(BalanceActivity.this).setValue(PrefsUtil.PAYNYM_FEATURED_SEGWIT, true);
} else {
;
}
} else {
;
}
} catch (JSONException je) {
je.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
Looper.loop();
}
}).start();
}
}
|
package cn.dhbin.minion.upms.model.enums;
import cn.dhbin.minion.core.common.IEnum;
import com.baomidou.mybatisplus.annotation.EnumValue;
import com.fasterxml.jackson.annotation.JsonValue;
import lombok.Getter;
import lombok.RequiredArgsConstructor;
/**
* @author donghaibin
* @date 2020/3/18
*/
@RequiredArgsConstructor
@Getter
public enum MenuType implements IEnum<Integer> {
/**
* 顶部菜单
*/
TOP_MENU(1, "顶部菜单"),
/**
* 左侧菜单
*/
MENU(2, "左侧菜单"),
/**
* 按钮
*/
BUTTON(3, "按钮");
@EnumValue
private final Integer value;
@JsonValue
private final String desc;
}
|
/*
* Copyright 2011 Google Inc.
* Copyright 2014 Andreas Schildbach
* Copyright 2017 Thomas König
*
* 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.bitcoinj.script;
import org.bitcoinj.core.*;
import org.bitcoinj.params.MainNetParams;
import org.bouncycastle.util.encoders.Hex;
import org.junit.Test;
import java.nio.charset.StandardCharsets;
import java.util.LinkedList;
import static org.bitcoinj.core.Utils.HEX;
import static org.junit.Assert.assertEquals;
public class ScriptReverseBytesTest {
@Test
public void testReverseBytes() throws Exception {
byte[] opReverseBytes = HEX.decode("6173616e74616c69766564617361646576696c61746e617361");
ScriptBuilder opReverseBytesTestScriptBuilder = new ScriptBuilder().data(opReverseBytes).op(ScriptOpCodes.OP_DUP).op(ScriptOpCodes.OP_REVERSEBYTES).op(ScriptOpCodes.OP_EQUAL);
Script opReverseBytesTestScript = opReverseBytesTestScriptBuilder.build();
LinkedList<byte[]> stack = new LinkedList<>();
Script.executeScript(null, 0, opReverseBytesTestScript, stack, Script.ALL_VERIFY_FLAGS);
byte[] success = new byte[]{1};
assertEquals(success[0], stack.get(0)[0]);
byte[] opReverseBytesInvalid = HEX.decode("116173616e74616c69766564617361646576696c61746e617361");
ScriptBuilder opReverseBytesTestScriptInvalidBuilder = new ScriptBuilder().data(opReverseBytesInvalid).op(ScriptOpCodes.OP_DUP).op(ScriptOpCodes.OP_REVERSEBYTES).op(ScriptOpCodes.OP_EQUAL);
Script opReverseBytesTestScriptInvalid = opReverseBytesTestScriptInvalidBuilder.build();
LinkedList<byte[]> stackInvalid = new LinkedList<>();
Script.executeScript(null, 0, opReverseBytesTestScriptInvalid, stackInvalid, Script.ALL_VERIFY_FLAGS);
assertEquals(0, stackInvalid.get(0).length);
}
@Test
public void redeemTobiasExample() {
/*
This test takes Tobias Ruck's example OP_REVERSEBYTES P2SH address.
Tobias deposited coins into 9 UTXOs to 3PVEFPCAVBuqq4qtsnPMiadAgFLDXrq6id
The tx: 21e8c0172050469425f2d699b96bbf638db8143e9223a257ef4032dc9816ac62
The raw tx: 0100000001adb1f29a49e600513ce64277f827116f0b78092a57bfaa5d3e36774ae65570b802000000644174d3d48575092bc9deb78f64d310e4004ccff246bfaa18901f28d8e396412862b01f65b70547f26a0d55f2aa36f5ab5f225655890135e612158adef95a11bb8d4121033cfa001d54e0ba57ca874685cc25992ada3a8ae43856b7be2ba3a482fbcd9f6cfeffffff0be80300000000000017a914ef18105eb5b3189c0c1f91c5c9c182addd73021887e80300000000000017a914ef18105eb5b3189c0c1f91c5c9c182addd73021887e80300000000000017a914ef18105eb5b3189c0c1f91c5c9c182addd73021887e80300000000000017a914ef18105eb5b3189c0c1f91c5c9c182addd73021887e80300000000000017a914ef18105eb5b3189c0c1f91c5c9c182addd73021887e80300000000000017a914ef18105eb5b3189c0c1f91c5c9c182addd73021887e80300000000000017a914ef18105eb5b3189c0c1f91c5c9c182addd73021887e80300000000000017a914ef18105eb5b3189c0c1f91c5c9c182addd73021887e80300000000000017a914ef18105eb5b3189c0c1f91c5c9c182addd73021887e80300000000000017a914ef18105eb5b3189c0c1f91c5c9c182addd7302188784f80500000000001976a9141e5fa394f88399d1c879bc3ce61113838ef7cd6d88ac5ab10900
This test takes an output from the deposit tx, and creates the proper redeem script to spend the coins.
The script is OP_DUP OP_REVERSEBYTES OP_EQUAL.
*/
NetworkParameters params = MainNetParams.get();
ScriptBuilder originalScriptBuilder = new ScriptBuilder().op(ScriptOpCodes.OP_DUP).op(ScriptOpCodes.OP_REVERSEBYTES).op(ScriptOpCodes.OP_EQUAL);
Script originalScript = originalScriptBuilder.build();
String legacyAddress = ScriptBuilder.createP2SHOutputScript(originalScript).getToAddress(params).toString();
System.out.println(legacyAddress);
Transaction tobiasTx = new Transaction(params, Hex.decode("0100000001adb1f29a49e600513ce64277f827116f0b78092a57bfaa5d3e36774ae65570b802000000644174d3d48575092bc9deb78f64d310e4004ccff246bfaa18901f28d8e396412862b01f65b70547f26a0d55f2aa36f5ab5f225655890135e612158adef95a11bb8d4121033cfa001d54e0ba57ca874685cc25992ada3a8ae43856b7be2ba3a482fbcd9f6cfeffffff0be80300000000000017a914ef18105eb5b3189c0c1f91c5c9c182addd73021887e80300000000000017a914ef18105eb5b3189c0c1f91c5c9c182addd73021887e80300000000000017a914ef18105eb5b3189c0c1f91c5c9c182addd73021887e80300000000000017a914ef18105eb5b3189c0c1f91c5c9c182addd73021887e80300000000000017a914ef18105eb5b3189c0c1f91c5c9c182addd73021887e80300000000000017a914ef18105eb5b3189c0c1f91c5c9c182addd73021887e80300000000000017a914ef18105eb5b3189c0c1f91c5c9c182addd73021887e80300000000000017a914ef18105eb5b3189c0c1f91c5c9c182addd73021887e80300000000000017a914ef18105eb5b3189c0c1f91c5c9c182addd73021887e80300000000000017a914ef18105eb5b3189c0c1f91c5c9c182addd7302188784f80500000000001976a9141e5fa394f88399d1c879bc3ce61113838ef7cd6d88ac5ab10900"));
TransactionOutput utxo = tobiasTx.getOutput(8);
Transaction spendTx = new Transaction(params);
spendTx.setVersion(2);
TransactionInput input = spendTx.addInput(utxo);
String scriptHex = Integer.toHexString(ScriptOpCodes.OP_DUP) + Integer.toHexString(ScriptOpCodes.OP_REVERSEBYTES) + Integer.toHexString(ScriptOpCodes.OP_EQUAL);
ScriptBuilder redeemScriptBuilder = new ScriptBuilder().data(Hex.decode("616e7574666f72616a61726f6674756e61")).data(Hex.decode(scriptHex));
Script redeemScript = redeemScriptBuilder.build();
spendTx.addOutput(utxo.getMinNonDustValue(), CashAddressFactory.create().getFromFormattedAddress(params, "bitcoincash:qzznfgmmxznnhdngj0564mqfezu33wcps577em9prn"));
input.setScriptSig(redeemScript);
byte[] serializedTx = spendTx.bitcoinSerialize();
byte[] hexEncodedTx = Hex.encode(serializedTx);
String rawTxString = new String(hexEncodedTx, StandardCharsets.UTF_8);
System.out.println(rawTxString);
}
}
|
package net.sourceforge.ondex.parser.biocyc.handler;
import java.util.Set;
import org.biopax.paxtools.model.level2.physicalEntity;
import org.biopax.paxtools.model.level2.protein;
import org.biopax.paxtools.model.level2.smallMolecule;
import net.sourceforge.ondex.core.ConceptClass;
import net.sourceforge.ondex.core.DataSource;
import net.sourceforge.ondex.core.EvidenceType;
import net.sourceforge.ondex.core.ONDEXConcept;
import net.sourceforge.ondex.core.ONDEXGraph;
import net.sourceforge.ondex.exception.type.ConceptClassMissingException;
import net.sourceforge.ondex.exception.type.EvidenceTypeMissingException;
/**
* Translates physicalEntitys entities into concepts.
*
* @author taubertj
*
*/
public class PhysicalEntityHandler extends DefaultHandler {
/**
* Processes set of physicalEntitys and creates concepts in given graph.
*
* @param g
* ONDEXGraph to create concepts in
* @param entities
* Set of physicalEntitys
*/
public PhysicalEntityHandler(ONDEXGraph g, Set<physicalEntity> entities)
throws Exception {
this.graph = g;
for (physicalEntity s : entities)
processPhysicalEntity(s);
}
/**
* Translate given physicalEntity into concept.
*
* @param e
* physicalEntity to translate
*/
private void processPhysicalEntity(physicalEntity e) throws Exception {
// check for evidence type
EvidenceType evidence = graph.getMetaData().getEvidenceType(etIMPD);
if (evidence == null)
throw new EvidenceTypeMissingException(etIMPD + " is missing.");
// check for concept classes
ConceptClass ofType = graph.getMetaData().getConceptClass(ccThing);
if (ofType == null)
throw new ConceptClassMissingException(ccThing + " is missing.");
// decide on type of physicalEntity
if (!e.getModelInterface().equals(protein.class)
&& !e.getModelInterface().equals(smallMolecule.class)) {
// extract DataSource of entity
DataSource elementOf = getDataSource(e);
// create concept
ONDEXConcept c = graph.getFactory().createConcept(e.getUri(),
elementOf, ofType, evidence);
rdf2Concept.put(e.getUri(), c);
// add synonyms
addConceptNames(c, e);
// add description
addDescription(c, e);
// add references
addConceptAccessions(c, e);
}
}
}
|
/*
* Copyright (c) 2011-2013, Peter Abeles. All Rights Reserved.
*
* This file is part of BoofCV (http://boofcv.org).
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package boofcv.alg.sfm.robust;
import boofcv.struct.geo.AssociatedPair;
import georegression.struct.affine.Affine2D_F64;
import georegression.struct.point.Point2D_F64;
import georegression.transform.affine.AffinePointOps_F64;
import org.ddogleg.fitting.modelset.DistanceFromModel;
import java.util.List;
/**
* Applies an affine transformation to the associated pair and computes the euclidean distance
* between their locations. The transform is applied to the "keyLoc".
*
* @author Peter Abeles
*/
public class DistanceAffine2D implements DistanceFromModel<Affine2D_F64,AssociatedPair> {
Affine2D_F64 model;
Point2D_F64 expected = new Point2D_F64();
@Override
public void setModel(Affine2D_F64 model ) {
this.model = model;
}
@Override
public double computeDistance(AssociatedPair pt) {
AffinePointOps_F64.transform(model, pt.p1, expected);
return expected.distance(pt.p2);
}
@Override
public void computeDistance(List<AssociatedPair> points, double[] distance) {
for( int i = 0; i < points.size(); i++ ) {
AssociatedPair p = points.get(i);
AffinePointOps_F64.transform(model,p.p1,expected);
distance[i] = expected.distance(p.p2);
}
}
}
|
package com.miu360.taxi_check.map;
import java.util.ArrayList;
import java.util.List;
import com.baidu.location.BDLocation;
import com.baidu.mapapi.map.BaiduMap;
import com.baidu.mapapi.map.BitmapDescriptor;
import com.baidu.mapapi.map.BitmapDescriptorFactory;
import com.baidu.mapapi.map.MapStatusUpdateFactory;
import com.baidu.mapapi.map.MapView;
import com.baidu.mapapi.map.Marker;
import com.baidu.mapapi.map.MarkerOptions;
import com.baidu.mapapi.map.Overlay;
import com.baidu.mapapi.map.OverlayOptions;
import com.baidu.mapapi.map.Polyline;
import com.baidu.mapapi.map.PolylineOptions;
import com.baidu.mapapi.model.LatLng;
import com.baidu.mapapi.model.LatLngBounds;
import com.baidu.mapapi.utils.CoordinateConverter;
import com.baidu.mapapi.utils.CoordinateConverter.CoordType;
import com.lubao.lubao.async.DirectionUtil;
import com.lubao.lubao.async.DirectionUtil.DirectLatLng;
import com.miu360.inspect.R;
import com.miu360.taxi_check.common.VehicleStatus;
import com.miu360.taxi_check.data.device;
import com.miu360.taxi_check.model.LatLngDir;
import android.app.Activity;
import android.util.Log;
public class MapUtils {
MapView mMapView;
public BaiduMap mBaiduMap;
public void initMap(Activity act, MapView mMapView, BaiduMap mBaiduMap) {
this.mMapView = mMapView;
this.mBaiduMap = mBaiduMap;
// 地图初始化
mBaiduMap = mMapView.getMap();
}
public Overlay drawLine(List<LatLng> points, int color, int width) {
// 构造纹理资源
// BitmapDescriptor custom2 = BitmapDescriptorFactory
// .fromResource(R.drawable.icon_road_green_arrow);
// 构造对象
OverlayOptions ooPolyline = new PolylineOptions().width(width).color(color).points(points);
// 添加到地图
return mBaiduMap.addOverlay(ooPolyline);
}
BitmapDescriptor bdA = BitmapDescriptorFactory.fromResource(R.drawable.direction_biaoshi);
BitmapDescriptor bdB = BitmapDescriptorFactory.fromResource(R.drawable.direction_biaoshi_other);
/**
* 设置标示方向的图片
*/
public void drawPoint(List<LatLng> points,List<Short> direction, int index) {
// 构造纹理资源
// BitmapDescriptor custom2 = BitmapDescriptorFactory
// .fromResource(R.drawable.icon_road_green_arrow);
// 计算没有转过的角度
// device.direct = (short) DirectionUtil.getAngle(
// new DirectLatLng(device.lng / (double) 1E6, device.lat / (double)
// 1E6),
// new DirectLatLng(lng / (double) 1E6, lat / (double) 1E6));
/*
* 计算两个坐标之间的方位角
*/
// ArrayList<Short> direction = new ArrayList<>();
// for (int i = 1; i < points.size(); i++) {
// DirectLatLng A = new DirectLatLng(points.get(i - 1).longitude, points.get(i - 1).latitude);
// DirectLatLng B = new DirectLatLng(points.get(i).longitude, points.get(i).latitude);
// short direct = (short) DirectionUtil.getAngle(A, B);
// direction.add(direct);
// }
// MarkerOptions ooA = null;
for (int i = 0; i < points.size(); i++) {
MarkerOptions ooA = new MarkerOptions().position(points.get(i)).icon(bdB).zIndex(index).rotate(360 - direction.get(i));
mBaiduMap.addOverlay(ooA);
}
}
public Overlay drawLine2(List<LatLng> points, int color, int width, int index) {
// 构造纹理资源
// BitmapDescriptor custom2 = BitmapDescriptorFactory
// .fromResource(R.drawable.icon_road_green_arrow);
// 构造对象
OverlayOptions ooPolyline = new PolylineOptions().width(width).color(color).points(points).zIndex(index);
// 添加到地图
return mBaiduMap.addOverlay(ooPolyline);
}
public Overlay drawLineKZ(List<List<LatLng>> allRoute,List<Integer> color, int width, int index) {
// 构造纹理资源List<VehicleStatus>
// BitmapDescriptor custom2 = BitmapDescriptorFactory
// .fromResource(R.drawable.icon_road_green_arrow);
List<LatLng> kPoints=new ArrayList<>();
int colors=0;
OverlayOptions ooPolyline=null;
for (int i = 0; i < allRoute.size(); i++) {
kPoints=allRoute.get(i);
if(color.get(i)==0){
colors=R.color.kong_lujin_color;
}else{
colors=R.color.zhong_lujin_color;
}
ooPolyline = new PolylineOptions().width(width).color(1).points(kPoints).zIndex(index);
}
// 构造对象
// 添加到地图
return mBaiduMap.addOverlay(ooPolyline);
}
/*
* 绘制最佳路线
*/
public Overlay drawLine3(List<LatLngDir> latLngDir, int color, int width, int index) {
ArrayList<LatLng> points = new ArrayList<>();
for (LatLngDir latLngDir2 : latLngDir) {
LatLng latLng = new LatLng(latLngDir2.lat, latLngDir2.lng);
points.add(latLng);
MarkerOptions ooA = null;
// 获取方位角
if (latLngDir2.dir != -1) {
float rot = 0;
switch ((int) latLngDir2.dir) {
case 0:
rot = 0;
break;
case 1:
rot = 30;
break;
case 2:
rot = 60;
break;
case 3:
rot = 90;
break;
case 4:
rot = 120;
break;
case 5:
rot = 150;
break;
case 6:
rot = 180;
break;
case 7:
rot = 210;
break;
case 8:
rot = 240;
break;
case 9:
rot = 270;
break;
case 10:
rot = 300;
break;
case 11:
rot = 330;
break;
default:
break;
}
ooA = new MarkerOptions().position(latLng).icon(bdA).zIndex(index + 1).rotate((float) 360 - rot);
mBaiduMap.addOverlay(ooA);
}
}
// 构造对象
OverlayOptions ooPolyline = new PolylineOptions().width(width).color(color).points(points).zIndex(index);
// 添加到地图
return mBaiduMap.addOverlay(ooPolyline);
}
/**
* 将地图缩放到可以显示整个路径的比例
*
* @param mBaiduMap
* @param overlayList
*/
public void zoomToSpan(BaiduMap mBaiduMap, List<Overlay> overlayList) {
try {
if (mBaiduMap == null) {
return;
}
if (overlayList.size() > 0) {
LatLngBounds.Builder builder = new LatLngBounds.Builder();
for (Overlay overlay : overlayList) {
if (overlay instanceof Marker) {
builder.include(((Marker) overlay).getPosition());
} else if (overlay instanceof Polyline) {
List<LatLng> ps = ((Polyline) overlay).getPoints();
for (LatLng latLng : ps) {
builder.include(latLng);
}
}
}
mBaiduMap.setMaxAndMinZoomLevel(20, 12);
mBaiduMap.animateMapStatus(MapStatusUpdateFactory.newLatLngBounds(builder.build()));
}
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* 地图坐标转换方法
*/
public static LatLng convertor(LatLng sourceLatLng) {
// 将google地图、soso地图、aliyun地图、mapabc地图和amap地图// 所用坐标转换成百度坐标
/*
* CoordinateConverter converter = new CoordinateConverter();
* converter.from(CoordType.COMMON); // sourceLatLng待转换坐标
* converter.coord(sourceLatLng); LatLng desLatLng =
* converter.convert();
*/
// 将GPS设备采集的原始GPS坐标转换成百度坐标
CoordinateConverter converter = new CoordinateConverter();
converter.from(CoordType.GPS);
// sourceLatLng待转换坐标
converter.coord(sourceLatLng);
LatLng desLatLng = converter.convert();
return desLatLng;
}
/**
* 记录坐标
*/
public static void savePoints() {
BDLocation location = new BDLocation();
// TO-DO 弄个集合,封装起来,提交的时候转换为json
LatLng ll = new LatLng(location.getLatitude(), location.getLongitude());
}
}
|
package binaryTree;
public class BT_Problem_08_b {
// Root of Binary Tree
Node root;
// Constructor
BT_Problem_08_b(){
root = null;
}
// Given a binary tree, print its nodes according to the "bottom-up" post-order traversal.
void printPostorder(Node node) {
//base case
if(node == null)
return;
// first recur on left subtree
printPostorder(node.left);
// then recur on right subtree
printPostorder(node.right);
// now deal with the node
System.out.print(node.data + " ");
}
// Wrapper over above recursive function
void printPostorder() {
printPostorder(root);
}
//Driver Code
public static void main(String[] args) {
BT_Problem_08_b tree = new BT_Problem_08_b();
tree.root = new Node(1);
tree.root.left = new Node(2);
tree.root.right = new Node(3);
tree.root.left.left = new Node(4);
tree.root.left.right = new Node(5);
System.out.println("\nPostorder traversal of binary tree is ");
tree.printPostorder();
}
}
|
package org.linlinjava.litemall.core;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.linlinjava.litemall.core.storage.LocalStorage;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.core.io.Resource;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.web.WebAppConfiguration;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
@WebAppConfiguration
@RunWith(SpringJUnit4ClassRunner.class)
@SpringBootTest
public class LocalStorageTest {
private final Log logger = LogFactory.getLog(LocalStorageTest.class);
@Autowired
private LocalStorage localStorage;
@Test
public void test() throws IOException {
String test = getClass().getClassLoader().getResource("litemall.png").getFile();
File testFile = new File(test);
localStorage.store(new FileInputStream(test), testFile.length(), "image/png", "litemall.png");
Resource resource = localStorage.loadAsResource("litemall.png");
String url = localStorage.generateUrl("litemall.png");
logger.info("test file " + test);
logger.info("store file " + resource.getURI());
logger.info("generate url " + url);
}
}
|
/**
*/
package com.zipc.garden.model.bp;
import org.eclipse.emf.ecore.EObject;
/**
* <!-- begin-user-doc --> A representation of the model object '<em><b>Event</b></em>'. <!-- end-user-doc -->
* <p>
* The following features are supported:
* </p>
* <ul>
* <li>{@link com.zipc.garden.model.bp.BPEvent#getName <em>Name</em>}</li>
* <li>{@link com.zipc.garden.model.bp.BPEvent#getValue <em>Value</em>}</li>
* </ul>
* @see com.zipc.garden.model.bp.BPPackage#getBPEvent()
* @model
* @generated
*/
public interface BPEvent extends EObject {
/**
* Returns the value of the '<em><b>Name</b></em>' attribute. <!-- begin-user-doc --> <!-- end-user-doc -->
* @return the value of the '<em>Name</em>' attribute.
* @see #setName(String)
* @see com.zipc.garden.model.bp.BPPackage#getBPEvent_Name()
* @model required="true"
* @generated
*/
String getName();
/**
* Sets the value of the '{@link com.zipc.garden.model.bp.BPEvent#getName <em>Name</em>}' attribute. <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @param value the new value of the '<em>Name</em>' attribute.
* @see #getName()
* @generated
*/
void setName(String value);
/**
* Returns the value of the '<em><b>Value</b></em>' attribute. <!-- begin-user-doc --> <!-- end-user-doc -->
* @return the value of the '<em>Value</em>' attribute.
* @see #setValue(String)
* @see com.zipc.garden.model.bp.BPPackage#getBPEvent_Value()
* @model required="true"
* @generated
*/
String getValue();
/**
* Sets the value of the '{@link com.zipc.garden.model.bp.BPEvent#getValue <em>Value</em>}' attribute. <!-- begin-user-doc
* --> <!-- end-user-doc -->
* @param value the new value of the '<em>Value</em>' attribute.
* @see #getValue()
* @generated
*/
void setValue(String value);
} // BPEvent
|
/*******************************************************************************
* Copyright (c) 2017 Intuit
*
* 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.intuit.ipp.interceptors;
import com.intuit.ipp.core.Context;
import com.intuit.ipp.core.ServiceType;
import com.intuit.ipp.exception.FMSException;
import com.intuit.ipp.security.OAuthAuthorizer;
import com.intuit.ipp.util.Config;
import com.intuit.ipp.util.StringUtils;
import org.testng.Assert;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.AfterTest;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test;
public class PrepareRequestInterceptorTest {
private PrepareRequestInterceptor instance = new PrepareRequestInterceptor();
private IntuitMessage message = new IntuitMessage();
private Context context;
@BeforeClass
public void setUp() throws FMSException {
context = new Context(new OAuthAuthorizer("fakeTicket","fakeToken", "fakeToken", "fakeToken"), ServiceType.QBO, "fakeRealm");
context.setRequestID("anyRequestID");
message.getRequestElements().setAction("fakeAction");
message.getRequestElements().setContext(context);
}
@AfterMethod
public void tearDown() {
message.getRequestElements().getRequestParameters().remove(RequestElements.REQ_PARAM_SENDTO);
message.getRequestElements().getRequestParameters().remove(RequestElements.REQ_PARAM_ENTITY_SELECTOR);
}
@Test
// Unit-like test which verifies URL generation
public void testExecute_QBO_URI() throws FMSException {
instance.execute(message);
String actual = message.getRequestElements().getRequestParameters().get("uri");
Assert.assertEquals(actual, Config.getProperty(Config.BASE_URL_QBO) + "/fakeRealm/fakeAction?requestid=anyRequestID&minorversion=12&");
//change by nidhi for testing
//Assert.assertEquals(actual, Config.getProperty(Config.BASE_URL_QBO) + "/fakeRealm/fakeAction?requestid=anyRequestID&include=updateaccountontxnsminorversion=5&");
}
@Test
public void testPrepareDataServiceRequestForPDF_SmallCaps() throws FMSException{
message.getRequestElements().getRequestParameters().put(RequestElements.REQ_PARAM_ENTITY_SELECTOR,"pdf");
instance.execute(message);
String actual = message.getRequestElements().getRequestParameters().get("uri");
Assert.assertTrue(actual.contains(Config.getProperty(Config.BASE_URL_QBO) + "/fakeRealm/fakeAction/pdf?requestid"));
}
@Test
public void testPrepareDataServiceRequestForPDF_BigCaps() throws FMSException{
message.getRequestElements().getRequestParameters().put(RequestElements.REQ_PARAM_ENTITY_SELECTOR,"PDF");
instance.execute(message);
String actual = message.getRequestElements().getRequestParameters().get("uri");
Assert.assertTrue(actual.contains(Config.getProperty(Config.BASE_URL_QBO) + "/fakeRealm/fakeAction/PDF?requestid"));
Assert.assertFalse(actual.contains(Config.getProperty(Config.BASE_URL_QBO) + "/fakeRealm/fakeAction/pdf?requestid"));
}
@Test
public void testPrepareDataServiceRequestForSendMail_SmallCaps() throws FMSException{
message.getRequestElements().getRequestParameters().put(RequestElements.REQ_PARAM_ENTITY_SELECTOR, "send");
instance.execute(message);
String actual = message.getRequestElements().getRequestParameters().get("uri");
Assert.assertTrue(actual.contains(Config.getProperty(Config.BASE_URL_QBO) + "/fakeRealm/fakeAction/send?requestid"));
}
@Test
public void testPrepareDataServiceRequestForSendMailViaAddress_SmallCaps() throws FMSException{
message.getRequestElements().getRequestParameters().put(RequestElements.REQ_PARAM_ENTITY_SELECTOR,"send");
message.getRequestElements().getRequestParameters().put(RequestElements.REQ_PARAM_SENDTO,"fake@fake.domain");
instance.execute(message);
String actual = message.getRequestElements().getRequestParameters().get("uri");
Assert.assertTrue(actual.contains(Config.getProperty(Config.BASE_URL_QBO) + "/fakeRealm/fakeAction/send?sendTo=fake@fake.domain&requestid"));
}
@Test
public void testPrepareDataServiceRequestForSendMailViaAddress_CamelCaps() throws FMSException{
message.getRequestElements().getRequestParameters().put(RequestElements.REQ_PARAM_ENTITY_SELECTOR,"send");
message.getRequestElements().getRequestParameters().put(RequestElements.REQ_PARAM_SENDTO,"FaKe@FaKe.domain");
instance.execute(message);
String actual = message.getRequestElements().getRequestParameters().get("uri");
Assert.assertTrue(actual.contains(Config.getProperty(Config.BASE_URL_QBO) + "/fakeRealm/fakeAction/send?sendTo=FaKe@FaKe.domain&requestid"));
}
@Test
public void testPrepareDataServiceRequestForSendMail_BigCaps() throws FMSException{
message.getRequestElements().getRequestParameters().put(RequestElements.REQ_PARAM_ENTITY_SELECTOR,"SEND");
instance.execute(message);
String actual = message.getRequestElements().getRequestParameters().get("uri");
Assert.assertTrue(actual.contains(Config.getProperty(Config.BASE_URL_QBO) + "/fakeRealm/fakeAction/SEND?requestid"));
Assert.assertFalse(actual.contains(Config.getProperty(Config.BASE_URL_QBO) + "/fakeRealm/fakeAction/send?requestid"));
}
@Test
public void testPrepareDataServiceRequestForVoid() throws FMSException{
message.getRequestElements().getRequestParameters().put(RequestElements.REQ_PARAM_INCLUDE, "void");
instance.execute(message);
String actual = message.getRequestElements().getRequestParameters().get("uri");
Assert.assertTrue(actual.contains(Config.getProperty(Config.BASE_URL_QBO) + "/fakeRealm/fakeAction?include=void&requestid"));
}
}
|
package Problem_1229;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
public class Solution {
public static void main(String[] args) throws NumberFormatException, IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
for (int t = 1; t <= 10; t++) {
int k = Integer.parseInt(br.readLine());
List<String> arr = new ArrayList<>();
String[] s = br.readLine().trim().split(" ");
for (int i = 0; i < s.length; i++) {
arr.add(s[i]);
}
int n = Integer.parseInt(br.readLine());
String[] op = br.readLine().trim().split(" ");
int cnt = 0;
for (int i = 0; i < n; i++) {
String option = op[cnt++];
int start = Integer.parseInt(op[cnt++]);
int count = Integer.parseInt(op[cnt++]);
if(option.equals("I"))
{
String[] temp = new String[count];
for (int j = temp.length - 1; j >= 0; j--) {
temp[j] = op[cnt++];
}
for (int j = 0; j < temp.length; j++) {
arr.add(start, temp[j]);
}
}
else if(option.equals("D")) {
for(int j = 0; j<count;j++) arr.remove(start);
}
}
StringBuilder sb = new StringBuilder();
for (int i = 0; i < 10; i++)
sb.append(arr.get(i) + " ");
System.out.printf("#%d %s\n", t, sb.toString());
}
}
}
|
/* Generated by camel build tools - do NOT edit this file! */
package org.apache.camel.component.crypto;
import java.util.Map;
import org.apache.camel.CamelContext;
import org.apache.camel.spi.ExtendedPropertyConfigurerGetter;
import org.apache.camel.spi.PropertyConfigurerGetter;
import org.apache.camel.spi.ConfigurerStrategy;
import org.apache.camel.spi.GeneratedPropertyConfigurer;
import org.apache.camel.util.CaseInsensitiveMap;
import org.apache.camel.support.component.PropertyConfigurerSupport;
/**
* Generated by camel build tools - do NOT edit this file!
*/
@SuppressWarnings("unchecked")
public class DigitalSignatureComponentConfigurer extends PropertyConfigurerSupport implements GeneratedPropertyConfigurer, PropertyConfigurerGetter {
private org.apache.camel.component.crypto.DigitalSignatureConfiguration getOrCreateConfiguration(DigitalSignatureComponent target) {
if (target.getConfiguration() == null) {
target.setConfiguration(new org.apache.camel.component.crypto.DigitalSignatureConfiguration());
}
return target.getConfiguration();
}
@Override
public boolean configure(CamelContext camelContext, Object obj, String name, Object value, boolean ignoreCase) {
DigitalSignatureComponent target = (DigitalSignatureComponent) obj;
switch (ignoreCase ? name.toLowerCase() : name) {
case "algorithm": getOrCreateConfiguration(target).setAlgorithm(property(camelContext, java.lang.String.class, value)); return true;
case "alias": getOrCreateConfiguration(target).setAlias(property(camelContext, java.lang.String.class, value)); return true;
case "autowiredenabled":
case "autowiredEnabled": target.setAutowiredEnabled(property(camelContext, boolean.class, value)); return true;
case "buffersize":
case "bufferSize": getOrCreateConfiguration(target).setBufferSize(property(camelContext, java.lang.Integer.class, value)); return true;
case "certificate": getOrCreateConfiguration(target).setCertificate(property(camelContext, java.security.cert.Certificate.class, value)); return true;
case "certificatename":
case "certificateName": getOrCreateConfiguration(target).setCertificateName(property(camelContext, java.lang.String.class, value)); return true;
case "clearheaders":
case "clearHeaders": getOrCreateConfiguration(target).setClearHeaders(property(camelContext, boolean.class, value)); return true;
case "configuration": target.setConfiguration(property(camelContext, org.apache.camel.component.crypto.DigitalSignatureConfiguration.class, value)); return true;
case "keystoreparameters":
case "keyStoreParameters": getOrCreateConfiguration(target).setKeyStoreParameters(property(camelContext, org.apache.camel.support.jsse.KeyStoreParameters.class, value)); return true;
case "keystore": getOrCreateConfiguration(target).setKeystore(property(camelContext, java.security.KeyStore.class, value)); return true;
case "keystorename":
case "keystoreName": getOrCreateConfiguration(target).setKeystoreName(property(camelContext, java.lang.String.class, value)); return true;
case "lazystartproducer":
case "lazyStartProducer": target.setLazyStartProducer(property(camelContext, boolean.class, value)); return true;
case "password": getOrCreateConfiguration(target).setPassword(property(camelContext, java.lang.String.class, value)); return true;
case "privatekey":
case "privateKey": getOrCreateConfiguration(target).setPrivateKey(property(camelContext, java.security.PrivateKey.class, value)); return true;
case "privatekeyname":
case "privateKeyName": getOrCreateConfiguration(target).setPrivateKeyName(property(camelContext, java.lang.String.class, value)); return true;
case "provider": getOrCreateConfiguration(target).setProvider(property(camelContext, java.lang.String.class, value)); return true;
case "publickey":
case "publicKey": getOrCreateConfiguration(target).setPublicKey(property(camelContext, java.security.PublicKey.class, value)); return true;
case "publickeyname":
case "publicKeyName": getOrCreateConfiguration(target).setPublicKeyName(property(camelContext, java.lang.String.class, value)); return true;
case "securerandom":
case "secureRandom": getOrCreateConfiguration(target).setSecureRandom(property(camelContext, java.security.SecureRandom.class, value)); return true;
case "securerandomname":
case "secureRandomName": getOrCreateConfiguration(target).setSecureRandomName(property(camelContext, java.lang.String.class, value)); return true;
case "signatureheadername":
case "signatureHeaderName": getOrCreateConfiguration(target).setSignatureHeaderName(property(camelContext, java.lang.String.class, value)); return true;
default: return false;
}
}
@Override
public Class<?> getOptionType(String name, boolean ignoreCase) {
switch (ignoreCase ? name.toLowerCase() : name) {
case "algorithm": return java.lang.String.class;
case "alias": return java.lang.String.class;
case "autowiredenabled":
case "autowiredEnabled": return boolean.class;
case "buffersize":
case "bufferSize": return java.lang.Integer.class;
case "certificate": return java.security.cert.Certificate.class;
case "certificatename":
case "certificateName": return java.lang.String.class;
case "clearheaders":
case "clearHeaders": return boolean.class;
case "configuration": return org.apache.camel.component.crypto.DigitalSignatureConfiguration.class;
case "keystoreparameters":
case "keyStoreParameters": return org.apache.camel.support.jsse.KeyStoreParameters.class;
case "keystore": return java.security.KeyStore.class;
case "keystorename":
case "keystoreName": return java.lang.String.class;
case "lazystartproducer":
case "lazyStartProducer": return boolean.class;
case "password": return java.lang.String.class;
case "privatekey":
case "privateKey": return java.security.PrivateKey.class;
case "privatekeyname":
case "privateKeyName": return java.lang.String.class;
case "provider": return java.lang.String.class;
case "publickey":
case "publicKey": return java.security.PublicKey.class;
case "publickeyname":
case "publicKeyName": return java.lang.String.class;
case "securerandom":
case "secureRandom": return java.security.SecureRandom.class;
case "securerandomname":
case "secureRandomName": return java.lang.String.class;
case "signatureheadername":
case "signatureHeaderName": return java.lang.String.class;
default: return null;
}
}
@Override
public Object getOptionValue(Object obj, String name, boolean ignoreCase) {
DigitalSignatureComponent target = (DigitalSignatureComponent) obj;
switch (ignoreCase ? name.toLowerCase() : name) {
case "algorithm": return getOrCreateConfiguration(target).getAlgorithm();
case "alias": return getOrCreateConfiguration(target).getAlias();
case "autowiredenabled":
case "autowiredEnabled": return target.isAutowiredEnabled();
case "buffersize":
case "bufferSize": return getOrCreateConfiguration(target).getBufferSize();
case "certificate": return getOrCreateConfiguration(target).getCertificate();
case "certificatename":
case "certificateName": return getOrCreateConfiguration(target).getCertificateName();
case "clearheaders":
case "clearHeaders": return getOrCreateConfiguration(target).isClearHeaders();
case "configuration": return target.getConfiguration();
case "keystoreparameters":
case "keyStoreParameters": return getOrCreateConfiguration(target).getKeyStoreParameters();
case "keystore": return getOrCreateConfiguration(target).getKeystore();
case "keystorename":
case "keystoreName": return getOrCreateConfiguration(target).getKeystoreName();
case "lazystartproducer":
case "lazyStartProducer": return target.isLazyStartProducer();
case "password": return getOrCreateConfiguration(target).getPassword();
case "privatekey":
case "privateKey": return getOrCreateConfiguration(target).getPrivateKey();
case "privatekeyname":
case "privateKeyName": return getOrCreateConfiguration(target).getPrivateKeyName();
case "provider": return getOrCreateConfiguration(target).getProvider();
case "publickey":
case "publicKey": return getOrCreateConfiguration(target).getPublicKey();
case "publickeyname":
case "publicKeyName": return getOrCreateConfiguration(target).getPublicKeyName();
case "securerandom":
case "secureRandom": return getOrCreateConfiguration(target).getSecureRandom();
case "securerandomname":
case "secureRandomName": return getOrCreateConfiguration(target).getSecureRandomName();
case "signatureheadername":
case "signatureHeaderName": return getOrCreateConfiguration(target).getSignatureHeaderName();
default: return null;
}
}
}
|
package org.apache.ctakes.gui.dictionary.umls;
import org.apache.log4j.Logger;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
/**
* Author: SPF
* Affiliation: CHIP-NLP
* Date: 9/5/2014
*/
public enum CuiCodeUtil {
INSTANCE;
static public CuiCodeUtil getInstance() {
return INSTANCE;
}
static private final Logger LOGGER = Logger.getLogger( "CuiCodeUtil" );
static private final long PREFIX_MULTIPLIER = 100000000;
final private List<PrefixerPair> _prefixerPairList = new ArrayList<>();
CuiCodeUtil() {
// Add the standard C as the default encoding prefix
_prefixerPairList.add( new PrefixerPair( "C0000000" ) );
}
public String getAsCui( final Long code ) {
final long multiplier = code / PREFIX_MULTIPLIER;
if ( code < 0 || multiplier < 0 || multiplier >= _prefixerPairList.size() ) {
LOGGER.error( "Could not create Cui String for " + code );
return "" + code;
}
return _prefixerPairList.get( (int)multiplier ).getAsCui( code % PREFIX_MULTIPLIER );
}
public Long getCuiCode( final String cui ) {
final PrefixerPair prefixerPair = new PrefixerPair( cui );
int prefixerIndex = _prefixerPairList.indexOf( prefixerPair );
if ( prefixerIndex < 0 ) {
prefixerIndex = _prefixerPairList.size();
_prefixerPairList.add( prefixerPair );
}
return prefixerPair.getCuiCode( cui, prefixerIndex );
}
static private final class PrefixerPair {
final private int __digitCount;
final private char[] __prefix;
final private int __hashCode;
private PrefixerPair( final String cui ) {
final char[] chars = cui.toCharArray();
int digitCount = 0;
while ( digitCount < chars.length
&& digitCount < 7
&& Character.isDigit( chars[ chars.length - 1 - digitCount ] ) ) {
digitCount++;
}
__digitCount = digitCount;
__prefix = Arrays.copyOfRange( chars, 0, chars.length - digitCount );
__hashCode = digitCount + Arrays.hashCode( __prefix );
}
private Long getCuiCode( final String cui, final int multiplier ) {
final String cuiNum = cui.substring( cui.length() - __digitCount, cui.length() );
try {
return PREFIX_MULTIPLIER * multiplier + Long.parseLong( cuiNum );
} catch ( NumberFormatException nfE ) {
LOGGER.error( "Could not create Cui Code for " + cui );
}
return -1l;
}
private String getAsCui( final Long code ) {
final char[] codeChars = String.valueOf( code ).toCharArray();
if ( codeChars.length > __digitCount ) {
LOGGER.error( "Invalid code " + code + " for prefix " + __prefix
+ " has more than " + __digitCount + " digits" );
return String.valueOf( __prefix ) + String.valueOf( codeChars );
}
final int cuiLength = __prefix.length + __digitCount;
final char[] cuiChars = new char[ cuiLength ];
System.arraycopy( __prefix, 0, cuiChars, 0, __prefix.length );
System.arraycopy( codeChars, 0, cuiChars, cuiLength - codeChars.length, codeChars.length );
for ( int i = __prefix.length; i < cuiLength - codeChars.length; i++ ) {
cuiChars[ i ] = '0';
}
return String.valueOf( cuiChars );
}
public int hashCode() {
return __hashCode;
}
public boolean equals( final Object other ) {
return other instanceof PrefixerPair
&& __hashCode == ((PrefixerPair)other).__hashCode
&& __digitCount == ((PrefixerPair)other).__digitCount
&& Arrays.equals( __prefix, ((PrefixerPair)other).__prefix );
}
}
// todo
// todo switch to int: 32 bit signed, max = 2,147,483,647
// todo if we keep final 7 digits for the numerical then we have 213 possible prefixes
// todo
// todo can probably change the code and the db will be fine, change the db too
// todo
}
|
/*
* Copyright (c) 2003-2019 Broad Institute, Inc., Massachusetts Institute of Technology, and Regents of the University of California. All rights reserved.
*/
package edu.mit.broad.genome.objects;
import edu.mit.broad.genome.math.*;
import edu.mit.broad.genome.math.ColorSchemes.ColorScheme;
import java.awt.*;
/**
* A Dataset with logic to assign a Color to each element corresponding
* to its float value.
*
* @author Aravind Subramanian
* @version %I%, %G%
*/
public class ColorDatasetImpl extends DatasetProxy implements ColorDataset {
//TODO: evaluate if these instance variables are really needed.
// These are set but never used; they are protected but there are no subclasses
protected ScaleMode fScaleMode;
protected Orientation fOrientType;
protected ColorScheme fColorScheme;
protected GraphMode fGraphMode;
private Color[][] fColors;
/**
* Class Constructor.
*
* @param ds
* @param smode
* @param colorScheme
* @param orient
*/
public ColorDatasetImpl(final Dataset ds,
final ScaleMode smode,
final ColorScheme colorScheme,
final Orientation orient,
final GraphMode gmode) {
super("colored." + ds.getName(), ds);
this.fScaleMode = smode;
this.fColorScheme = colorScheme;
this.fOrientType = orient;
this.fGraphMode = gmode;
cacheColors();
}
/**
* Class Constructor.
*
* @param ds
* @param colorScheme
*/
public ColorDatasetImpl(final Dataset ds, final ColorScheme colorScheme) {
this(ds, DEFAULT_SCALE_MODE, colorScheme, DEFAULT_ORIENTATION, DEFAULT_GRAPH_MODE);
}
public ColorDatasetImpl(final Dataset ds, final ScaleMode scaleMode, final ColorScheme colorScheme) {
this(ds, scaleMode, colorScheme, DEFAULT_ORIENTATION, DEFAULT_GRAPH_MODE);
}
protected void cacheColors() {
if (fOrientType.isByRow()) {
cacheColorsByRow();
} else if (fOrientType.isByCol()) {
cacheColorsByColumn();
} else {
throw new IllegalStateException("Unknown orientType option: " + fOrientType);
}
}
protected void cacheColorsByRow() {
// wierd for loop structure as trying to optimize calcs
//log.debug("Beginning to cache fColors by ROW from: " + this.getClass());
fColors = new Color[getNumRow()][getNumCol()];
for (int r = 0; r < getNumRow(); r++) {
Vector vr = getRow(r);
Vector v = vr.toVectorNaNless(); // @note
if (fScaleMode.isRelative()) {
double center = v.meanOrMedian(fScaleMode.isMean());
double max = v.max();
double min = v.min();
for (int c = 0; c < getNumCol(); c++) {
if (fScaleMode.isMean()) {
boolean coloraswhite = false;
if (fScaleMode == ScaleMode.REL_MEAN_ZERO_OMITTED) { // @todo improve
coloraswhite = true;
}
//fColors[r][c] = Helper.computeRelativeMeanColor(getElement(r, c), min, max, center, fGraphMode, fColorScheme);
fColors[r][c] = Helper.computeRelativeMeanColor(getElement(r, c), min, max, center, fGraphMode, fColorScheme, coloraswhite);
} else {
fColors[r][c] = Helper.computeRelativeMedianColor(getElement(r, c), min, max,
center, fGraphMode, fColorScheme);
}
}
} else {
for (int c = 0; c < getNumCol(); c++) {
fColors[r][c] = Helper.computeAbsoluteColor(getElement(r, c), fGraphMode, fColorScheme);
//if (fScaleMode == SCALE_OPTIONS[2]) fColors[r][c] = computeAbsoluteColor(getElement(r, c), v);
//else if (fScaleMode == FOUR_COLOR) fColors[r][c] = computeFourColor(getElement(r, c), v);
//else throw new IllegalArgumentException("Unknwon ScaleMode" + fScaleMode);
}
}
}
//log.debug("Finished caching Colors: " + this.getClass());
}
protected void cacheColorsByColumn() {
// wierd for loop structure as trying to optimize calcs
log.info("Beginning to cache fColors by COL from: " + this.getClass());
fColors = new Color[getNumRow()][getNumCol()];
for (int c = 0; c < getNumCol(); c++) {
Vector v = getColumn(c);
if (fScaleMode.isRelative()) {
double mean = v.mean();
double median = v.median();
double max = v.max();
double min = v.min();
for (int r = 0; r < getNumRow(); r++) {
if (fScaleMode.isMean()) {
fColors[r][c] = Helper.computeRelativeMeanColor(getElement(r, c), min, max, mean, fGraphMode, fColorScheme, false);
} else {
fColors[r][c] = Helper.computeRelativeMedianColor(getElement(r, c), min, max,
median, fGraphMode, fColorScheme);
}
}
} else {
for (int r = 0; r < getNumRow(); r++) {
fColors[r][c] = Helper.computeAbsoluteColor(getElement(r, c), fGraphMode, fColorScheme);
//if (fScaleMode == SCALE_OPTIONS[2]) fColors[r][c] = computeAbsoluteColor(getElement(r, c), v);
//else if (fScaleMode == FOUR_COLOR) fColors[r][c] = computeFourColor(getElement(r, c), v);
//else throw new IllegalArgumentException("Unknwon ScaleMode" + fScaleMode);
}
}
}
log.info("Finished caching Colors: " + this.getClass());
}
public Color getColor(int row, int col) {
return fColors[row][col];
}
} // End ColorDataset
|
package com.atguigu.gmall.oms.mapper;
import com.atguigu.gmall.oms.entity.OrderReturnReasonEntity;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import org.apache.ibatis.annotations.Mapper;
/**
* 退货原因
*
* @author GuanFuQing
* @email moumouguan@gmail.com
* @date 2021-12-20 21:59:57
*/
@Mapper
public interface OrderReturnReasonMapper extends BaseMapper<OrderReturnReasonEntity> {
}
|
package zhou.demo;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.TextView;
import android.widget.Toast;
import com.zzhoujay.richtext.ImageHolder;
import com.zzhoujay.richtext.RichText;
import com.zzhoujay.richtext.RichType;
import com.zzhoujay.richtext.callback.OnImageClickListener;
import java.util.List;
public class MainActivity extends AppCompatActivity {
private static final String IMAGE = "<img title=\"\" src=\"http://g.hiphotos.baidu.com/image/pic/item/241f95cad1c8a7866f726fe06309c93d71cf5087.jpg\" style=\"cursor: pointer;\"><br><br>" +
"<img src=\"http://img.ugirls.com/uploads/cooperate/baidu/20160519menghuli.jpg\" width=\"1080\" height=\"1620\"/><a href=\"http://www.baidu.com\">baidu</a>" +
"hello asdkjfgsduk <a href=\"http://www.jd.com\">jd</a>";
private static final String IMAGE1 = "<h1>RichText</h1><p>Android平台下的富文本解析器</p><img title=\"\" src=\"http://g.hiphotos.baidu.com/image/pic/item/241f95cad1c8a7866f726fe06309c93d71cf5087.jpg\" style=\"cursor: pointer;\"><br><br>" +
"<h3>点击菜单查看更多Demo</h3><img src=\"http://ww2.sinaimg.cn/bmiddle/813a1fc7jw1ee4xpejq4lj20g00o0gnu.jpg\" /><p><a href=\"http://www.baidu.com\">baidu</a>" +
"hello asdkjfgsduk <a href=\"http://www.jd.com\">jd</a></p><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br>bottom";
private static final String GIF_TEST = "<img src=\"http://ww4.sinaimg.cn/large/5cfc088ejw1f3jcujb6d6g20ap08mb2c.gif\">";
private static final String markdown_test = "image:\n[link](https://github.com/zzhoujay/RichText/issues)";
private static final String gif_test = "<h3>Test1</h3><img src=\"http://www.aikf.com/ask/resources/images/facialExpression/qq/1.gif\" />" +
" <h3>Test2</h3><img src=\"http://www.aikf.com/ask/resources/images/facialExpression/qq/2.gif\" />" +
" <h3>Test3</h3><img src=\"http://www.aikf.com/ask/resources/images/facialExpression/qq/3.gif\" />" +
" <h3>Test4</h3><img src=\"http://www.aikf.com/ask/resources/images/facialExpression/qq/4.gif\" />" +
" <h3>Test5</h3><img src=\"http://www.aikf.com/ask/resources/images/facialExpression/qq/5.gif\" />" +
" <h3>Test6</h3><img src=\"http://www.aikf.com/ask/resources/images/facialExpression/qq/6.gif\" />" +
" <h3>Test7</h3><img src=\"http://www.aikf.com/ask/resources/images/facialExpression/qq/7.gif\" />" +
" <h3>Test8</h3><img src=\"http://www.aikf.com/ask/resources/images/facialExpression/qq/8.gif\" />" +
" <h3>Test9</h3><img src=\"http://www.aikf.com/ask/resources/images/facialExpression/qq/9.gif\" />";
private static final String list_test = "<ol>\n" +
" <li>Coffee</li>\n" +
" <li>Tea</li>\n" +
" <li>Milk</li>\n" +
"</ol>\n" +
"\n" +
"<ul>\n" +
" <li>Coffee</li>\n" +
" <li>Tea</li>\n" +
" <li>Milk</li>\n" +
"</ul>";
private static final String large_image = "<img src=\"http://static.tme.im/article_1_1471686391302fue\"/>";
private static final String text = "";
private final String issue142 = "<p><img src=\"http://image.wangchao.net.cn/it/1233190350268.gif?size=528*388\" width=\"528\" height=\"388\" /></p>";
private final String issue143 = "<img src=\"file:///C:\\Users\\ADMINI~1\\AppData\\Local\\Temp\\ksohtml\\wpsB8DD.tmp.png\">";
private final String issue147 = "<div class=\"pictureBox\"> \n" +
" <img src=\"http://static.storeer.com/wlwb/productDetail/234be0ec-e90a-4eda-90bd-98d64b55280a_580x4339.jpeg\">\n" +
"</div>";
private final String issue149 = null;
private final String issue150 = "<img src='http://cuncxforum-10008003.image.myqcloud.com/642def77-373f-434f-8e68-42dedbd9f880'/><br><img src='http://cuncxforum-10008003.image.myqcloud.com/bf153d9f-e8c3-4dcc-a23e-bfe0358cb429'/>";
private static final String assets_image_test = "<h1>Assets Image Test</h1><img src=\"file:///android_asset/doge.jpg\">";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Glide.with(this).from("").sizeMultiplier(
RichText.initCacheDir(this);
final TextView textView = (TextView) findViewById(R.id.text);
// ichText
RichText.from("<p>我是文本内容 <img src='http://wx1.sinaimg.cn/mw690/eaaf2affly1fihvjpekzwj21el0qotfq.jpg' /> 下一个" +
"<img src='http://wx1.sinaimg.cn/mw690/eaaf2affly1fihvjpekzwj21el0qotfq.jpg' />似懂非懂撒范德萨咖啡机盛大开放惊世毒妃</p>")
.type(RichType.HTML)
// .autoFix(false)
.scaleType(ImageHolder.ScaleType.CENTER_INSIDE)
.imageClick(new OnImageClickListener() {
@Override
public void imageClicked(List<String> imageUrls, int position) {
Toast.makeText(MainActivity.this, imageUrls.get(position), Toast.LENGTH_SHORT).show();
}
})
.size(dip2px(120), dip2px(120))
.into(textView);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
menu.add(0, 0, 0, "RecyclerView");
menu.add(0, 1, 1, "ListView");
menu.add(0, 2, 2, "Gif");
menu.add(0, 3, 3, "Test");
return super.onCreateOptionsMenu(menu);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
if (item.getItemId() == 0) {
startActivity(new Intent(this, RecyclerViewActivity.class));
} else if (item.getItemId() == 1) {
startActivity(new Intent(this, ListViewActivity.class));
} else if (item.getItemId() == 2) {
startActivity(new Intent(this, GifActivity.class));
} else if (item.getItemId() == 3) {
startActivity(new Intent(this, TestActivity.class));
}
return super.onOptionsItemSelected(item);
}
@Override
protected void onDestroy() {
super.onDestroy();
RichText.recycle();
}
public int dip2px(float dpValue) {
final float scale = getResources().getDisplayMetrics().density;
return (int) (dpValue * scale + 0.5f);
}
}
|
package com.soccer.scores.network;
import com.soccer.scores.network.datamodel.Matches;
import retrofit2.Call;
import retrofit2.http.GET;
import retrofit2.http.Query;
import retrofit2.http.Url;
public interface IClient {
@GET("/v2/matches")
Call<Matches> getMatchesList(@Query("dateFrom") String dateFrom, @Query("dateTo") String dateTo);
}
|
/*
* 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.jena.sparql.algebra.optimize;
import java.util.Collection ;
import java.util.HashSet;
import java.util.Set;
import org.apache.jena.query.SortCondition ;
import org.apache.jena.sparql.algebra.Op ;
import org.apache.jena.sparql.algebra.OpVars ;
import org.apache.jena.sparql.algebra.TransformCopy ;
import org.apache.jena.sparql.algebra.op.OpDistinct ;
import org.apache.jena.sparql.algebra.op.OpOrder ;
import org.apache.jena.sparql.algebra.op.OpProject ;
import org.apache.jena.sparql.algebra.op.OpReduced ;
import org.apache.jena.sparql.core.Var ;
/**
* <p>
* Transforms generic {@code DISTINCT} plus {@code ORDER BY} combinations to
* {@code REDUCED} plus {@code ORDER BY} which typically gives better
* performance and memory consumption because engines have to keep less data
* in-memory to evaluate it.
* </p>
* <p>
* As with most optimizations this is only applied when it is safe to do so. The
* criteria for being safe to do so are as follows:
* </p>
* <ul>
* <li>Uses both {@code ORDER BY} and {@code DISTINCT} on the same level of the
* query</li>
* <li>There is a fixed list of variables to project i.e. not {@code SELECT *}</li>
* <li>{@code ORDER BY} conditions cover all the projected variables prior to
* the use of any other variables</li>
* </ul>
* <h3>Related Optimizations</h3>
* <p>
* See also {@link TransformOrderByDistinctApplication} which is a better
* optimization for these kinds of queries but only applies to a more limited range
* of queries. Where possible that optimization is applied in preference to this
* one.
* </p>
* <p>
* {@link TransformTopN} covers the case of {@code DISTINCT} plus
* {@code ORDER BY} where there is also a {@code LIMIT}. Where possible that
* optimization is applied in preference to either this or
* {@link TransformOrderByDistinctApplication}.
* </p>
*/
public class TransformDistinctToReduced extends TransformCopy {
public TransformDistinctToReduced() {}
// Best is this is after TransformTopN but they are order independent
// TopN of "reduced or distinct of order" is handled.
//@Override
public Op transform1(OpDistinct opDistinct, Op subOp) {
if (subOp instanceof OpProject) {
OpProject opProject = (OpProject) subOp;
if (opProject.getSubOp() instanceof OpOrder) {
OpOrder opOrder = (OpOrder) opProject.getSubOp();
Set<Var> projectVars = Set.copyOf(opProject.getVars()) ;
if (isSafe(projectVars, opOrder)) {
return OpReduced.create(subOp);
}
}
}
return super.transform(opDistinct, subOp);
}
@Override
public Op transform(OpDistinct opDistinct, Op subOp) {
OpOrder opOrder = null ;
Set<Var> projectVars = null ;
/* SELECT DISTINCT * {} ORDER BY
* giving an alegbra expression of the form:
* (distinct
* (order
*/
if (subOp instanceof OpOrder) {
opOrder = (OpOrder) subOp;
projectVars = OpVars.visibleVars(subOp) ;
} else if (subOp instanceof OpProject) {
OpProject opProject = (OpProject) subOp;
if (opProject.getSubOp() instanceof OpOrder) {
projectVars = new HashSet<>(opProject.getVars()) ;
opOrder = (OpOrder) opProject.getSubOp();
}
}
if ( projectVars == null )
return super.transform(opDistinct, subOp) ;
if (isSafe(projectVars, opOrder))
return OpReduced.create(subOp);
return super.transform(opDistinct, subOp);
}
protected boolean isSafe(Set<Var> projectVars, OpOrder opOrder) {
Set<Var> seenVars = new HashSet<>();
// For the optimization to be safe all project variables must appear in
// the ordering prior to any unprojected variables
// Ordering by expressions is fine provided they use only projected
// variables
boolean ok = true;
for (SortCondition cond : opOrder.getConditions()) {
if (!isValidSortCondition(cond, projectVars, seenVars)) {
ok = false;
break;
}
// As soon as we've seen all variables we know this is safe and any
// further sort conditions are irrelevant
if (seenVars.size() == projectVars.size())
return true ;
}
// The projects vars must all have been seen.
return (seenVars.size() == projectVars.size()) ;
}
/**
* Determines whether a sort condition is valid in terms of this optimizer
*
* @param cond
* Sort Condition
* @param projectVars
* Project Variables
* @return True if valid, false otherwise
*/
private boolean isValidSortCondition(SortCondition cond, Collection<Var> projectVars, Set<Var> seenVars) {
if (cond.getExpression().isVariable()) {
if (projectVars.contains(cond.getExpression().asVar())) {
seenVars.add(cond.getExpression().asVar());
return true;
}
return false;
} else {
for (Var v : cond.getExpression().getVarsMentioned()) {
if (!projectVars.contains(v))
return false;
seenVars.add(v);
}
return true;
}
}
}
|
package com.ontotext.trree.plugin.proof;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import org.eclipse.rdf4j.model.Value;
import org.eclipse.rdf4j.model.vocabulary.OWL;
import org.eclipse.rdf4j.model.vocabulary.RDFS;
import org.eclipse.rdf4j.query.Binding;
import org.eclipse.rdf4j.query.BindingSet;
import org.eclipse.rdf4j.query.MalformedQueryException;
import org.eclipse.rdf4j.query.QueryEvaluationException;
import org.eclipse.rdf4j.query.TupleQueryResult;
import org.eclipse.rdf4j.repository.RepositoryConnection;
import org.eclipse.rdf4j.repository.RepositoryException;
import org.eclipse.rdf4j.repository.sail.SailRepository;
import org.eclipse.rdf4j.rio.RDFFormat;
import org.eclipse.rdf4j.rio.RDFParseException;
import org.junit.Rule;
import org.junit.Test;
import com.ontotext.test.TemporaryLocalFolder;
import com.ontotext.trree.OwlimSchemaRepository;
import com.ontotext.trree.plugin.proof.ProofPlugin;
public class TestExplainWithProofPlugin {
@Rule
public TemporaryLocalFolder tmpFolder = new TemporaryLocalFolder();
String query = "PREFIX pr: <http://www.ontotext.com/proof/>\r\n" +
"PREFIX food: <http://www.w3.org/TR/2003/PR-owl-guide-20031209/food#>\r\n" +
"PREFIX onto: <http://www.ontotext.com/>\r\n" +
"\r\n" +
"select ?ctx ?s ?p ?o ?rule ?context ?subj ?pred ?obj\r\n" +
"from named onto:implicit \r\n" +
"from named onto:explicit \r\n" +
"{\r\n" +
"# values (?s ?p ?o) {(food:Fruit UNDEF UNDEF)} \r\n"+
" graph ?g {?s ?p ?o} \r\n"+
" filter(strstarts(str(?s),str(food:)))\r\n" +
" ?ctx pr:explain (?s ?p ?o) .\r\n" +
" ?ctx pr:rule ?rule .\r\n" +
" ?ctx pr:subject ?subj .\r\n" +
" ?ctx pr:predicate ?pred .\r\n" +
" ?ctx pr:object ?obj .\r\n" +
" ?ctx pr:context ?context .\r\n" +
"}\r\n" +
"";
@Test
public void testBasicInference() throws RepositoryException, MalformedQueryException, QueryEvaluationException, RDFParseException, IOException {
Map<String, String> params = new HashMap<String, String>();
OwlimSchemaRepository sail = new OwlimSchemaRepository();
params.put("register-plugins", ProofPlugin.class.getName());
sail.setParameters(params);
SailRepository rep = new SailRepository(sail);
rep.setDataDir(tmpFolder.newFolder("proof-plugin-explain"));
rep.init();
try {
RepositoryConnection conn = rep.getConnection();
try {
String dataFile = Thread.currentThread().getContextClassLoader().getResource("proof/sample.trig").getFile();
conn.add(new File(dataFile), "http://base.uri", RDFFormat.TRIG);
conn.add(OWL.CLASS, RDFS.SUBCLASSOF, RDFS.CLASS);
TupleQueryResult res = conn.prepareTupleQuery(query).evaluate();
HashSet<Value> ctxs = new HashSet<Value>();
int count = 0;
while (res.hasNext()) {
BindingSet bs = res.next();
Binding cB = bs.getBinding("ctx");
assertNotNull("Expected object to be always bound", cB);
assertNotNull("Expected object to be not null", cB.getValue());
ctxs.add(cB.getValue());
count ++;
}
assertEquals("total iterations",11, ctxs.size());
assertEquals("total results", 13, count);
res.close();
} finally {
conn.close();
}
} finally {
rep.shutDown();
}
}
}
|
/**
* File Name: AbstractTask.java
* Date: 2019-06-13 10:14:46
*/
package me.belucky.easytool.task;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import me.belucky.easytool.util.CacheUtils;
/**
* 功能说明:任务抽象处理类
* @author shenzl
* @date 2019-06-13
* @version 1.0
*/
public abstract class AbstractTask implements ITask{
protected Logger log = LoggerFactory.getLogger(super.getClass());
/**
* 缓存任务名称
*/
private String taskName;
public AbstractTask(String taskName) {
super();
this.taskName = taskName;
}
public void go() {
long start = System.currentTimeMillis();
log.info("开始执行任务:{}", taskName);
execute();
long end = System.currentTimeMillis();
log.info("任务【{}】运行成功,耗时:{}ms", taskName, end - start);
}
/**
* 子类实现的方法
*/
public abstract void execute();
public String getTaskName() {
return taskName;
}
public void setTaskName(String taskName) {
this.taskName = taskName;
}
public <T> T getObjectFromCacheInit(String key, T t) {
T v = CacheUtils.getCache(key);
if(v == null) {
v = t;
}
return v;
}
}
|
package com.prowidesoftware.swift.model.mx.dic;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlType;
import org.apache.commons.lang3.builder.EqualsBuilder;
import org.apache.commons.lang3.builder.HashCodeBuilder;
import org.apache.commons.lang3.builder.ToStringBuilder;
import org.apache.commons.lang3.builder.ToStringStyle;
/**
* Provides information about the corporate action event.
*
*
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "CorporateAction24", propOrder = {
"dtDtls",
"evtStag",
"ltryTp"
})
public class CorporateAction24 {
@XmlElement(name = "DtDtls")
protected CorporateActionDate41 dtDtls;
@XmlElement(name = "EvtStag")
protected CorporateActionEventStageFormat6Choice evtStag;
@XmlElement(name = "LtryTp")
protected LotteryTypeFormat1Choice ltryTp;
/**
* Gets the value of the dtDtls property.
*
* @return
* possible object is
* {@link CorporateActionDate41 }
*
*/
public CorporateActionDate41 getDtDtls() {
return dtDtls;
}
/**
* Sets the value of the dtDtls property.
*
* @param value
* allowed object is
* {@link CorporateActionDate41 }
*
*/
public CorporateAction24 setDtDtls(CorporateActionDate41 value) {
this.dtDtls = value;
return this;
}
/**
* Gets the value of the evtStag property.
*
* @return
* possible object is
* {@link CorporateActionEventStageFormat6Choice }
*
*/
public CorporateActionEventStageFormat6Choice getEvtStag() {
return evtStag;
}
/**
* Sets the value of the evtStag property.
*
* @param value
* allowed object is
* {@link CorporateActionEventStageFormat6Choice }
*
*/
public CorporateAction24 setEvtStag(CorporateActionEventStageFormat6Choice value) {
this.evtStag = value;
return this;
}
/**
* Gets the value of the ltryTp property.
*
* @return
* possible object is
* {@link LotteryTypeFormat1Choice }
*
*/
public LotteryTypeFormat1Choice getLtryTp() {
return ltryTp;
}
/**
* Sets the value of the ltryTp property.
*
* @param value
* allowed object is
* {@link LotteryTypeFormat1Choice }
*
*/
public CorporateAction24 setLtryTp(LotteryTypeFormat1Choice value) {
this.ltryTp = value;
return this;
}
@Override
public String toString() {
return ToStringBuilder.reflectionToString(this, ToStringStyle.MULTI_LINE_STYLE);
}
@Override
public boolean equals(Object that) {
return EqualsBuilder.reflectionEquals(this, that);
}
@Override
public int hashCode() {
return HashCodeBuilder.reflectionHashCode(this);
}
}
|
package ru.stqa.pft.mantis.tests;
import org.testng.annotations.Test;
import ru.stqa.pft.mantis.Model.Issue;
import ru.stqa.pft.mantis.Model.Project;
import javax.xml.rpc.ServiceException;
import java.net.MalformedURLException;
import java.rmi.RemoteException;
import java.util.Set;
import static org.testng.Assert.assertEquals;
/**
* Created by SerejKa on 06.06.2017.
*/
public class SoapTests extends TestBase{
@Test
public void testGetProgects() throws MalformedURLException, ServiceException, RemoteException {
skipIfNotFixed(2);
Set<Project> projects = app.soap().getProjects();
System.out.println(projects.size());
for (Project project : projects){
System.out.println(project.getName());
}
}
@Test
public void testCreateIssue() throws MalformedURLException, ServiceException, RemoteException {
skipIfNotFixed(1);
Set<Project> projects = app.soap().getProjects();
Issue issue = new Issue().withSummary("Summary").withDescription("description").withProject(projects.iterator().next());
Issue created = app.soap().addIssue(issue);
assertEquals(issue.getSummary(), created.getSummary());
}
}
|
package ir.taghizadeh.dagger2.activities.tvShowsActivity;
import android.support.v7.widget.RecyclerView;
import android.text.Html;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import com.squareup.picasso.Picasso;
import ir.taghizadeh.dagger2.R;
import ir.taghizadeh.dagger2.model.TvShows;
public class TvShowsListViewHolder extends RecyclerView.ViewHolder {
private ImageView image_item_avatar;
private TextView text_item_name;
private TextView text_item_genres;
private TextView text_item_rate;
private TextView text_item_status;
private TextView text_item_summary;
public TvShowsListViewHolder(View itemView) {
super(itemView);
this.image_item_avatar = itemView.findViewById(R.id.image_item_avatar);
this.text_item_name = itemView.findViewById(R.id.text_item_name);
this.text_item_genres = itemView.findViewById(R.id.text_item_genres);
this.text_item_rate = itemView.findViewById(R.id.text_item_rate);
this.text_item_status = itemView.findViewById(R.id.text_item_status);
this.text_item_summary = itemView.findViewById(R.id.text_item_summary);
}
public void configureWith(TvShows tvShows, Picasso picasso) {
text_item_name.setText(tvShows.name);
text_item_genres.setText(tvShows.genres.get(0));
text_item_rate.setText(String.format("Rating : %s", tvShows.rating.average));
text_item_status.setText(tvShows.status);
text_item_summary.setText(Html.fromHtml(tvShows.summary));
picasso.load(tvShows.image.original)
.placeholder(R.drawable.ic_twotone_movie_24px)
.into(image_item_avatar);
}
}
|
package com.gildedrose;
import org.junit.Test;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.IntStream;
import static org.junit.Assert.assertEquals;
public class TexttestFixture {
private static List<String> msgs;
private final int days = 10;
@Test
public void goldenMaster(){
msgs = new ArrayList<>();
log("OMGHAI!");
Item[] items = new Item[]{
new Item("+5 Dexterity Vest", 10, 20), //
new Item("Aged Brie", 2, 0), //
new Item("Elixir of the Mongoose", 5, 7), //
new Item("Sulfuras, Hand of Ragnaros", 0, 80), //
new Item("Sulfuras, Hand of Ragnaros", -1, 80),
new Item("Backstage passes to a TAFKAL80ETC concert", 15, 20),
new Item("Backstage passes to a TAFKAL80ETC concert", 10, 49),
new Item("Backstage passes to a TAFKAL80ETC concert", 5, 49),
new Item("Conjured Mana Cake", 3, 6)};
GildedRose app = new GildedRose(items);
for (int i = 0; i < days; i++) {
log("-------- day " + i + " --------");
log("name, sellIn, quality");
for (Item item : items) {
log(item.toString());
}
log("");
app.updateQuality();
}
assertWithGoldenMaster();
}
private static void assertWithGoldenMaster() {
Path gm = Paths.get("src/test/goldenmaster.txt");
try {
List<String> lines = Files.readAllLines(gm);
assertEquals(msgs.size(), lines.size());
IntStream.range(0, msgs.size()).forEach(i -> {
assertEquals(msgs.get(i), lines.get(i));
});
} catch (IOException e) {
throw new RuntimeException(e);
}
}
private static void log(String msg) {
msgs.add(msg);
}
}
|
/*****************************************************************
* 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.cayenne.migration;
import java.util.Collections;
import junit.framework.TestCase;
import org.apache.cayenne.access.DataNode;
import org.apache.cayenne.access.types.DefaultValueObjectTypeRegistry;
import org.apache.cayenne.configuration.DefaultRuntimeProperties;
import org.apache.cayenne.configuration.RuntimeProperties;
import org.apache.cayenne.dba.postgres.PostgresAdapter;
import org.apache.cayenne.di.spi.DefaultClassLoaderManager;
import org.apache.cayenne.merge.ArbitrarySqlToDb;
import org.apache.cayenne.resource.ClassLoaderResourceLocator;
public class SqlFileMigrationTest extends TestCase {
private DataNode node;
@Override
protected void setUp() throws Exception {
super.setUp();
node = new DataNode("node");
RuntimeProperties props = new DefaultRuntimeProperties(Collections.EMPTY_MAP);
ClassLoaderResourceLocator resourceLocator = new ClassLoaderResourceLocator(new DefaultClassLoaderManager());
PostgresAdapter adapter = new PostgresAdapter(props, Collections.EMPTY_LIST, Collections.EMPTY_LIST, Collections.EMPTY_LIST, resourceLocator, new DefaultValueObjectTypeRegistry(Collections.emptyList()));
node.setAdapter(adapter);
}
private static class Node0 extends SqlFileMigration {
public Node0(DataNode node) {
super(node);
}
}
private static class Node1 extends SqlFileMigration {
public Node1(DataNode node) {
super(node);
}
}
// TODO: Add H2 in memory database for unit testing
// public void testDatabaseSpecificSqlFilename() {
// Node0 migration = new Node0(node);
// assertEquals("Node0-PostgreSQL.sql", migration.databaseSpecificSqlFilename());
// }
public void testGenericSqlFilename() {
Node0 migration = new Node0(node);
assertEquals("Node0.sql", migration.genericSqlFilename());
}
// public void testSqlFilename() {
// Node0 migration0 = new Node0(node);
// assertEquals("Node0.sql", migration0.sqlFilename());
//
// Node1 migration1 = new Node1(node);
// assertEquals("Node1-PostgreSQL.sql", migration1.sqlFilename());
// }
//
// public void testUpgrade() {
// Node0 migration = new Node0(node);
// migration.upgrade(migration.getDatabase());
//
// assertEquals(1, migration.getDatabase().getOperations().size());
// assertTrue(migration.getDatabase().getOperations().get(0) instanceof ArbitrarySqlToDb);
//
// ArbitrarySqlToDb operation = (ArbitrarySqlToDb) migration.getDatabase().getOperations().get(0);
// assertEquals("UPDATE x SET y=1;", operation.getTokenValue());
// }
}
|
package io.onemfive.core;
/**
* TODO: Add Description
*
* @author objectorange
*/
public class ServiceNotFoundException extends OneMFiveException {
}
|
package epilepsy_nitkkr.epilepsypredictor;
import android.util.Log;
import java.util.Date;
import java.util.TimerTask;
public class ScheduledTask extends TimerTask {
private static final String TAG = "My Scheduled Task";
Date now;
public void run() {
this.now = new Date();
Log.d(TAG, "run: " + this.now);
}
}
|
// HelloMVC: a simple MVC example
// the canvasModel is just a counter
// inspired by code by Joseph Mack, http://www.austintek.com/mvc/
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.awt.geom.Ellipse2D;
import java.awt.geom.Rectangle2D;
import java.util.ArrayList;
import java.util.Observable;
import java.util.Observer;
@SuppressWarnings("serial")
class CanvasView extends JPanel implements Observer, MouseListener, MouseMotionListener {
// the view's main user interface
private boolean drawingShape = false;
private int mouseX;
private int mouseY;
private int initialX;
private int initialY;
private int dragX;
private int dragY;
private boolean draggingShape = false;
// the canvasModel that this view is showing
private Model model;
private Model.SideBarTool selectedTool;
private Model.ColorPalleteModel.SideBarSelectedColor selectedColor;
private Model.SideBarLineWidth selectedLineWidth;
private ArrayList<ShapeModel> shapes;
private int selectedShapeIndex;
private int currentShapeIndex;
private boolean fullSize;
private boolean fitToWindow;
private JScrollPane container;
CanvasView(Model model_) {
// create the view UI
this.setSize(500,500);
this.setPreferredSize(new Dimension(1000,800));
this.setMaximumSize(new Dimension(1000,800));
// the widget in the window
this.setLayout(new BorderLayout());
//this.add(button, new GridBagConstraints());
this.setBackground(Color.LIGHT_GRAY);
// set the canvasModel
model = model_;
selectedTool = model.toolsModel.getSelectedTool();
selectedColor = model.colorPalleteModel.getSideBarSelectedColor();
selectedLineWidth = model.linePalleteModel.getSelectedWidth();
shapes = new ArrayList<>();
selectedShapeIndex = -1;
fullSize = model.menuBarModel.getFullSize();
fitToWindow = model.menuBarModel.getFitToWindow();
this.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(
KeyStroke.getKeyStroke(KeyEvent.VK_ESCAPE, 0), ESCAPE);
this.getActionMap().put(
ESCAPE, escape);
this.setFocusable(true);
this.requestFocus();
addMouseListener(this);
addMouseMotionListener(this);
repaint();
}
private static final String ESCAPE = "escape";
private Action escape = new AbstractAction(ESCAPE) {
@Override
public void actionPerformed(ActionEvent e) {
System.out.println("pressed esc");
selectedShapeIndex = -1;
repaint();
}
};
// Observer interface
// this gets called from the canvasmodel when the model is updated
@Override
public void update(Observable arg0, Object arg1) {
if (arg0 instanceof Model.CanvasModel) {
System.out.println("CanvasView: update Canvas Model");
ShapeModel shapeToDraw = model.canvasModel.getMostRecentShape();
drawShape(shapeToDraw);
} else if (arg0 instanceof Model.ToolsModel) {
System.out.println("CanvasView: update Tools Model");
selectedTool = model.toolsModel.getSelectedTool();
if (selectedShapeIndex != -1) {
selectedShapeIndex = -1;
repaint();
}
} else if (arg0 instanceof Model.ColorPalleteModel) {
System.out.println("CanvasView: update Color Pallete Model");
selectedColor = model.colorPalleteModel.getSideBarSelectedColor();
ShapeModel selectedShape = null;
if (selectedShapeIndex != -1) {
selectedShape = shapes.get(selectedShapeIndex);
}
if (selectedShape != null) {
// change line color of shape
selectedShape.setLineColor(selectedColor.jColor);
repaint();
}
} else if (arg0 instanceof Model.LinePalleteModel) {
System.out.println("CanvasView: update Line Pallete Model");
ShapeModel selectedShape = null;
if (selectedShapeIndex != -1) {
selectedShape = shapes.get(selectedShapeIndex);
}
selectedLineWidth = model.linePalleteModel.getSelectedWidth();
if (selectedShape != null) {
// change line thickness of shape
ShapeModel.LineType lineType = selectedLineWidth == Model.SideBarLineWidth.MEDIUM ? ShapeModel.LineType.MEDIUM : selectedLineWidth == Model.SideBarLineWidth.THIN ? ShapeModel.LineType.THIN : ShapeModel.LineType.THICK;
selectedShape.setLineType(lineType);
repaint();
}
} else if (arg0 instanceof Model.MenuBarModel) {
fitToWindow = model.menuBarModel.getFitToWindow();
fullSize = model.menuBarModel.getFullSize();
if (fullSize) {
container.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_ALWAYS);
container.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);
container.setEnabled(true);
} else {
container.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER);
container.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_NEVER);
container.setEnabled(false);
}
if (model.menuBarModel.isLoaded()) {
shapes = model.menuBarModel.getLoadedShapes();
}
repaint();
} else {
System.out.println("CanvasView: update some other model");
}
}
public void drawShape(ShapeModel shape) {
System.out.println("Drew some shape");
}
@Override
public void mouseClicked(MouseEvent e) {
int x = e.getX();
int y = e.getY();
if (fitToWindow) {
x = (int) getScaledMouseCoordinate(x);
y = (int) getScaledMouseCoordinate(y);
}
if (selectedTool == Model.SideBarTool.FILL || selectedTool == Model.SideBarTool.ERASER || selectedTool == Model.SideBarTool.SELECTION) {
// iterate over the list of shapes (from top shapes to bottom + fill the first encountered shape)
for (int i = shapes.size() - 1 ; i >= 0 ; i--) {
if (shapes.get(i) instanceof CircleModel) {
CircleModel c = (CircleModel) shapes.get(i);
int radius = c.getHeight()/2;
int centreX = c.getOriginX() + radius;
int centreY = c.getOriginY() + radius;
if ((Math.sqrt((x - centreX)*(x - centreX) + (y-centreY) * (y - centreY)) < radius)) {
if (selectedTool == Model.SideBarTool.FILL) {
c.setFillColor(selectedColor.jColor);
} else if (selectedTool == Model.SideBarTool.ERASER) {
// remove
System.out.println("CanvasView: remove circ");
shapes.remove(i);
}
repaint();
break;
}
} else if (shapes.get(i) instanceof RectModel) {
RectModel r = (RectModel) shapes.get(i);
if (r.getOriginX() <= x && x <= r.getOriginX() + r.getWidth() && r.getOriginY() <= y && y <= r.getOriginY() + r.getHeight()) {
if (selectedTool == Model.SideBarTool.FILL) {
r.setFillColor(selectedColor.jColor);
} else if (selectedTool == Model.SideBarTool.ERASER) {
// remove
System.out.println("CanvasView: remove rect");
shapes.remove(i);
}
repaint();
break;
}
} else if (shapes.get(i) instanceof LineModel) {
LineModel l = (LineModel) shapes.get(i);
int shortestDistance = distanceFromPointToLine(x, y, l.getOriginX(), l.getOriginY(), l.getEndX(), l.getEndY());
if (shortestDistance <= 3) {
if (selectedTool == Model.SideBarTool.ERASER) {
// remove
System.out.println("CanvasView: remove line");
shapes.remove(i);
}
repaint();
break;
}
}
}
}
drawingShape = false;
draggingShape = false;
}
private int distanceFromPointToLine(int x, int y, int originX, int originY, int endX, int endY) {
double num = (Math.abs(((endY - originY) * x) - ((endX - originX) * y) + endX*originY - endY*originX));
double demom = (Math.sqrt(Math.pow(endY - originY, 2) + Math.pow(endX - originX, 2)));
return ((int) (num / demom));
}
//todo: change mouse pointer if shape is selectable
@Override
public void mousePressed(MouseEvent e) {
System.out.println("CanvasView: mouse pressed");
int x = e.getX();
int y = e.getY();
if (fitToWindow) {
x = (int) getScaledMouseCoordinate(x);
y = (int) getScaledMouseCoordinate(y);
}
if (selectedTool == Model.SideBarTool.RECT || selectedTool == Model.SideBarTool.CIRCLE || selectedTool == Model.SideBarTool.LINE) {
drawingShape = true;
System.out.println("CanvasView: mouse pressed here");
initialX = x;
initialY = y;
mouseX = initialX;
mouseY = initialY;
ShapeModel currentShape;
ShapeModel.LineType lineType = selectedLineWidth == Model.SideBarLineWidth.MEDIUM ? ShapeModel.LineType.MEDIUM : selectedLineWidth == Model.SideBarLineWidth.THIN ? ShapeModel.LineType.THIN : ShapeModel.LineType.THICK;
if (selectedTool == Model.SideBarTool.RECT) {
currentShape = new RectModel(initialX, initialY, 1, 1, lineType, selectedColor.jColor, new Color(255, 255, 255, 0));
shapes.add(currentShape);
currentShapeIndex = shapes.indexOf(currentShape);
} else if (selectedTool == Model.SideBarTool.CIRCLE) {
currentShape = new CircleModel(initialX, initialY, 1, 1, lineType, selectedColor.jColor, new Color(255, 255, 255, 0));
shapes.add(currentShape);
currentShapeIndex = shapes.indexOf(currentShape);
} else if (selectedTool == Model.SideBarTool.LINE) {
currentShape = new LineModel(initialX, initialY, initialX + 1, initialY + 1, lineType, selectedColor.jColor);
shapes.add(currentShape);
currentShapeIndex = shapes.indexOf(currentShape);
}
repaint();
} else if (selectedTool == Model.SideBarTool.SELECTION) {
selectedShapeIndex = -1;
for (int i = shapes.size() - 1 ; i >= 0 ; i--) {
if (shapes.get(i) instanceof CircleModel) {
CircleModel c = (CircleModel) shapes.get(i);
int radius = c.getHeight()/2;
int centreX = c.getOriginX() + radius;
int centreY = c.getOriginY() + radius;
if ((Math.sqrt((x - centreX)*(x - centreX) + (y-centreY) * (y - centreY)) < radius)) {
if (selectedTool == Model.SideBarTool.SELECTION) {
selectedShapeIndex = i;
dragX = x;
dragY = y;
draggingShape = true;
Model.SideBarLineWidth lineType = c.getLineType() == ShapeModel.LineType.MEDIUM ? Model.SideBarLineWidth.MEDIUM : c.getLineType() == ShapeModel.LineType.THIN ? Model.SideBarLineWidth.THIN : Model.SideBarLineWidth.THICK;
Model.SideBarColor color;
Color cColor = c.getLineColor();
if (cColor == Color.black) {
color = Model.SideBarColor.BLACK;
} else if (cColor == Color.RED) {
color = Model.SideBarColor.RED;
} else if (cColor == Color.GREEN) {
color = Model.SideBarColor.GREEN;
} else if (cColor == Color.BLUE) {
color = Model.SideBarColor.BLUE;
} else if (cColor == Color.ORANGE) {
color = Model.SideBarColor.ORANGE;
} else if (cColor == Color.PINK) {
color = Model.SideBarColor.PINK;
} else {
color = Model.SideBarColor.OTHER;
model.colorPalleteModel.selectCustomSideBarColor(cColor);
}
model.colorPalleteModel.selectSideBarColor(color);
model.linePalleteModel.selectWidth(lineType);
}
repaint();
break;
}
} else if (shapes.get(i) instanceof RectModel) {
RectModel r = (RectModel) shapes.get(i);
if (r.getOriginX() <= x && x <= r.getOriginX() + r.getWidth() && r.getOriginY() <= y && y <= r.getOriginY() + r.getHeight()) {
if (selectedTool == Model.SideBarTool.SELECTION) {
selectedShapeIndex = i;
dragX = x;
dragY = y;
draggingShape = true;
Model.SideBarLineWidth lineType = r.getLineType() == ShapeModel.LineType.MEDIUM ? Model.SideBarLineWidth.MEDIUM : r.getLineType() == ShapeModel.LineType.THIN ? Model.SideBarLineWidth.THIN : Model.SideBarLineWidth.THICK;
Model.SideBarColor color;
Color cColor = r.getLineColor();
if (cColor == Color.black) {
color = Model.SideBarColor.BLACK;
} else if (cColor == Color.RED) {
color = Model.SideBarColor.RED;
} else if (cColor == Color.GREEN) {
color = Model.SideBarColor.GREEN;
} else if (cColor == Color.BLUE) {
color = Model.SideBarColor.BLUE;
} else if (cColor == Color.ORANGE) {
color = Model.SideBarColor.ORANGE;
} else if (cColor == Color.PINK) {
color = Model.SideBarColor.PINK;
} else {
color = Model.SideBarColor.OTHER;
model.colorPalleteModel.selectCustomSideBarColor(cColor);
}
model.colorPalleteModel.selectSideBarColor(color);
model.linePalleteModel.selectWidth(lineType);
}
repaint();
break;
}
} else if (shapes.get(i) instanceof LineModel) {
LineModel l = (LineModel) shapes.get(i);
int shortestDistance = distanceFromPointToLine(x, y, l.getOriginX(), l.getOriginY(), l.getEndX(), l.getEndY());
if (shortestDistance <= 3) {
if (selectedTool == Model.SideBarTool.SELECTION) {
selectedShapeIndex = i;
dragX = x;
dragY = y;
draggingShape = true;
Model.SideBarLineWidth lineType = l.getLineType() == ShapeModel.LineType.MEDIUM ? Model.SideBarLineWidth.MEDIUM : l.getLineType() == ShapeModel.LineType.THIN ? Model.SideBarLineWidth.THIN : Model.SideBarLineWidth.THICK;
Model.SideBarColor color;
Color cColor = l.getLineColor();
if (cColor == Color.black) {
color = Model.SideBarColor.BLACK;
} else if (cColor == Color.RED) {
color = Model.SideBarColor.RED;
} else if (cColor == Color.GREEN) {
color = Model.SideBarColor.GREEN;
} else if (cColor == Color.BLUE) {
color = Model.SideBarColor.BLUE;
} else if (cColor == Color.ORANGE) {
color = Model.SideBarColor.ORANGE;
} else if (cColor == Color.PINK) {
color = Model.SideBarColor.PINK;
} else {
color = Model.SideBarColor.OTHER;
model.colorPalleteModel.selectCustomSideBarColor(cColor);
}
model.colorPalleteModel.selectSideBarColor(color);
model.linePalleteModel.selectWidth(lineType);
}
repaint();
break;
}
} else {
selectedShapeIndex = -1;
}
}
}
}
private int distanceBetween(int x1, int y1, int x2, int y2) {
int dx = x1 - x2;
int dy = y1 - y2;
int distance = (int) Math.sqrt(dx * dx + dy * dy);
return distance;
}
@Override
public void mouseDragged(MouseEvent e) {
if (drawingShape) {
int x = e.getX();
int y = e.getY();
if (fitToWindow) {
x = (int) getScaledMouseCoordinate(x);
y = (int) getScaledMouseCoordinate(y);
}
if (shapes.get(currentShapeIndex) instanceof CircleModel) {
int minHeight = Math.min(Math.abs(x - shapes.get(currentShapeIndex).getStartX()), Math.abs(y - shapes.get(currentShapeIndex).getStartY()));
if (x <= shapes.get(currentShapeIndex).getStartX()) {
((CircleModel) shapes.get(currentShapeIndex)).setOriginX(shapes.get(currentShapeIndex).getStartX() - minHeight);
} else {
((CircleModel) shapes.get(currentShapeIndex)).setOriginX(shapes.get(currentShapeIndex).getStartX());
}
if (y <= shapes.get(currentShapeIndex).getStartY()) {
((CircleModel) shapes.get(currentShapeIndex)).setOriginY(shapes.get(currentShapeIndex).getStartY() - minHeight);
} else {
((CircleModel) shapes.get(currentShapeIndex)).setOriginY(shapes.get(currentShapeIndex).getStartY());
}
((CircleModel) shapes.get(currentShapeIndex)).setWidth(minHeight);
((CircleModel) shapes.get(currentShapeIndex)).setHeight(minHeight);
} else if (shapes.get(currentShapeIndex) instanceof RectModel) {
((RectModel) shapes.get(currentShapeIndex)).setOriginX(Math.min(x, shapes.get(currentShapeIndex).getStartX()));
((RectModel) shapes.get(currentShapeIndex)).setOriginY(Math.min(y, shapes.get(currentShapeIndex).getStartY()));
((RectModel) shapes.get(currentShapeIndex)).setWidth(Math.abs(x - shapes.get(currentShapeIndex).getStartX()));
((RectModel) shapes.get(currentShapeIndex)).setHeight(Math.abs(y - shapes.get(currentShapeIndex).getStartY()));
} else if (shapes.get(currentShapeIndex) instanceof LineModel) {
((LineModel) shapes.get(currentShapeIndex)).setEndX(x);
((LineModel) shapes.get(currentShapeIndex)).setEndY(y);
}
repaint();
}
if (draggingShape && selectedShapeIndex != -1) {
//System.out.println("dragging");
int x = e.getX();
int y = e.getY();
if (fitToWindow) {
x = (int) getScaledMouseCoordinate(x);
y = (int) getScaledMouseCoordinate(y);
}
int translationX = x - dragX;
int translationY = y - dragY;
ShapeModel shapeToMove = shapes.get(selectedShapeIndex);
shapeToMove.originY = shapeToMove.originY + translationY;
shapeToMove.originX = shapeToMove.originX + translationX;
if (shapeToMove instanceof LineModel) {
((LineModel) shapeToMove).setEndX(((LineModel) shapeToMove).getEndX() + translationX);
((LineModel) shapeToMove).setEndY(((LineModel) shapeToMove).getEndY() + translationY);
}
dragX = x;
dragY = y;
repaint();
}
}
@Override
public void mouseMoved(MouseEvent e) {
}
@Override
public void mouseReleased(MouseEvent e) {
drawingShape = false;
draggingShape = false;
}
@Override
public void mouseEntered(MouseEvent e) {
}
@Override
public void mouseExited(MouseEvent e) {
}
public double getScaledMouseCoordinate(int x) {
double width = container.getSize().getWidth();
double height = container.getSize().getHeight();
double scaleWidth = width / this.getPreferredSize().getWidth();
double scaleHeight = height / this.getPreferredSize().getHeight();
if (scaleHeight >= scaleWidth) {
return x / scaleWidth;//(1 - scaleWidth) / scaleWidth;
} else {
return x / scaleHeight;//(1 - scaleHeight) / scaleHeight;
}
}
@Override
public void paint(Graphics g) {
Graphics2D g2 = (Graphics2D) g;
Stroke stroke;
if (fitToWindow) {
double width = container.getSize().getWidth();
double height = container.getSize().getHeight();
double scaleWidth = width / this.getPreferredSize().getWidth();
double scaleHeight = height / this.getPreferredSize().getHeight();
//System.out.println(width + " " + height + " " + scaleHeight + " " + scaleWidth);
if (scaleHeight >= scaleWidth) {
g2.scale(scaleWidth, scaleWidth);
} else {
g2.scale(scaleHeight, scaleHeight);
}
}
g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
// backgrounds
g2.setColor(Color.LIGHT_GRAY);
g2.fillRect(0, 0, 5000, 5000);
g2.setColor(Color.white);
g2.fillRect(0, 0, 1000, 800);
g2.setClip(new Rectangle2D.Double(0, 0, 1000, 800));
for (ShapeModel s: shapes) {
if (s.lineType == ShapeModel.LineType.THIN) {
stroke = new BasicStroke(5);
} else if (s.lineType == ShapeModel.LineType.MEDIUM) {
stroke = new BasicStroke(10);
} else { //if (selectedLineWidth == Model.SideBarLineWidth.THICK) {
stroke = new BasicStroke(20);
}
g2.setStroke(stroke);
g2.setColor(s.getLineColor());
if (s instanceof CircleModel) {
g2.drawOval(s.getOriginX(), s.getOriginY(), ((CircleModel) s).getWidth(), ((CircleModel) s).getHeight());
g2.setColor(((CircleModel) s).getFillColor());
g2.fillOval(s.getOriginX(), s.getOriginY(), ((CircleModel) s).getWidth(), ((CircleModel) s).getHeight());
} else if (s instanceof RectModel) {
g2.drawRect(s.getOriginX(), s.getOriginY(), ((RectModel) s).getWidth(), ((RectModel) s).getHeight());
g2.setColor(((RectModel) s).getFillColor());
g2.fillRect(s.getOriginX(), s.getOriginY(), ((RectModel) s).getWidth(), ((RectModel) s).getHeight());
} else { // LineModel
g2.drawLine(s.getOriginX(), s.getOriginY(), ((LineModel)s).getEndX(), ((LineModel)s).getEndY());
}
ShapeModel selectedShape = null;
if (selectedShapeIndex != -1 && selectedShapeIndex == shapes.indexOf(s)) {
selectedShape = shapes.get(selectedShapeIndex);
}
if (selectedShape != null) {
Stroke dashed = new BasicStroke(2, BasicStroke.CAP_BUTT, BasicStroke.JOIN_BEVEL, 0, new float[]{9}, 0);
g2.setStroke(dashed);
g2.setColor(Color.LIGHT_GRAY);
if (selectedShape instanceof LineModel) {
g2.drawLine(selectedShape.getOriginX(), selectedShape.getOriginY(), ((LineModel) selectedShape).getEndX(), ((LineModel) selectedShape).getEndY());
} else if (selectedShape instanceof CircleModel) {
g2.drawOval(selectedShape.getOriginX(), selectedShape.getOriginY(), ((CircleModel) selectedShape).getWidth(), ((CircleModel) selectedShape).getHeight());
} else if (selectedShape instanceof RectModel) {
g2.drawRect(selectedShape.getOriginX(), selectedShape.getOriginY(), ((RectModel) selectedShape).getWidth(), ((RectModel) selectedShape).getHeight());
}
}
}
model.menuBarModel.setShapesToSave(shapes);
}
public void setContainer(JScrollPane container) {
this.container = container;
}
}
|
/*
* Hibernate, Relational Persistence for Idiomatic Java
*
* Copyright (c) 2008, Red Hat Middleware LLC or third-party contributors as
* indicated by the @author tags or express copyright attribution
* statements applied by the authors. All third-party contributions are
* distributed under license by Red Hat Middleware LLC.
*
* This copyrighted material is made available to anyone wishing to use, modify,
* copy, or redistribute it subject to the terms and conditions of the GNU
* Lesser General Public License, as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
* or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License
* for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this distribution; if not, write to:
* Free Software Foundation, Inc.
* 51 Franklin Street, Fifth Floor
* Boston, MA 02110-1301 USA
*/
package org.hibernate.envers.test.integration.inheritance.tableperclass.relation;
import java.util.Set;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.OneToMany;
import org.hibernate.envers.Audited;
/**
* @author Adam Warski (adam at warski dot org)
*/
@Entity
@Audited
public class ReferencedEntity {
@Id
private Integer id;
@OneToMany(mappedBy = "referenced")
private Set<ParentIngEntity> referencing;
public ReferencedEntity() {
}
public ReferencedEntity(Integer id) {
this.id = id;
}
public Set<ParentIngEntity> getReferencing() {
return referencing;
}
public void setReferencing(Set<ParentIngEntity> referencing) {
this.referencing = referencing;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public boolean equals(Object o) {
if (this == o) return true;
if (!(o instanceof ReferencedEntity)) return false;
ReferencedEntity that = (ReferencedEntity) o;
if (id != null ? !id.equals(that.id) : that.id != null) return false;
return true;
}
public int hashCode() {
return id;
}
public String toString() {
return "ReferencedEntity(id = " + getId() + ")";
}
}
|
/*
* Copyright 2018 ConsenSys AG.
*
* 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 tech.pegasys.pantheon.ethereum.permissioning;
import static java.util.Collections.singletonList;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.catchThrowable;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.doThrow;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.verifyNoMoreInteractions;
import static org.mockito.Mockito.verifyZeroInteractions;
import static org.mockito.Mockito.when;
import static tech.pegasys.pantheon.ethereum.permissioning.NodeLocalConfigPermissioningController.NodesWhitelistResult;
import tech.pegasys.pantheon.ethereum.p2p.peers.EnodeURL;
import tech.pegasys.pantheon.ethereum.permissioning.node.NodeWhitelistUpdatedEvent;
import tech.pegasys.pantheon.metrics.Counter;
import tech.pegasys.pantheon.metrics.MetricsSystem;
import tech.pegasys.pantheon.metrics.PantheonMetricCategory;
import java.io.IOException;
import java.net.URI;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.function.Consumer;
import com.google.common.collect.Lists;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.junit.MockitoJUnitRunner;
@RunWith(MockitoJUnitRunner.StrictStubs.class)
public class NodeLocalConfigPermissioningControllerTest {
@Mock private WhitelistPersistor whitelistPersistor;
private final List<EnodeURL> bootnodesList = new ArrayList<>();
private NodeLocalConfigPermissioningController controller;
private final String enode1 =
"enode://6f8a80d14311c39f35f516fa664deaaaa13e85b2f7493f37f6144d86991ec012937307647bd3b9a82abe2974e1407241d54947bbb39763a4cac9f77166ad92a0@192.168.0.10:4567";
private final String enode2 =
"enode://5f8a80d14311c39f35f516fa664deaaaa13e85b2f7493f37f6144d86991ec012937307647bd3b9a82abe2974e1407241d54947bbb39763a4cac9f77166ad92a0@192.168.0.10:4567";
private final EnodeURL selfEnode =
EnodeURL.fromString(
"enode://5f8a80d14311c39f35f516fa664deaaaa13e85b2f7493f37f6144d86991ec012937307647bd3b9a82abe2974e1407241d54947bbb39763a4cac9f77166ad92a0@192.168.0.10:1111");
@Mock private MetricsSystem metricsSystem;
@Mock private Counter checkCounter;
@Mock private Counter checkPermittedCounter;
@Mock private Counter checkUnpermittedCounter;
@Before
public void setUp() {
bootnodesList.clear();
when(metricsSystem.createCounter(
PantheonMetricCategory.PERMISSIONING,
"node_local_check_count",
"Number of times the node local permissioning provider has been checked"))
.thenReturn(checkCounter);
when(metricsSystem.createCounter(
PantheonMetricCategory.PERMISSIONING,
"node_local_check_count_permitted",
"Number of times the node local permissioning provider has been checked and returned permitted"))
.thenReturn(checkPermittedCounter);
when(metricsSystem.createCounter(
PantheonMetricCategory.PERMISSIONING,
"node_local_check_count_unpermitted",
"Number of times the node local permissioning provider has been checked and returned unpermitted"))
.thenReturn(checkUnpermittedCounter);
controller =
new NodeLocalConfigPermissioningController(
LocalPermissioningConfiguration.createDefault(),
bootnodesList,
selfEnode.getNodeId(),
whitelistPersistor,
metricsSystem);
}
@Test
public void whenAddNodesWithValidInputShouldReturnSuccess() {
NodesWhitelistResult expected = new NodesWhitelistResult(WhitelistOperationResult.SUCCESS);
NodesWhitelistResult actualResult = controller.addNodes(Lists.newArrayList(enode1));
assertThat(actualResult).isEqualToComparingOnlyGivenFields(expected, "result");
assertThat(controller.getNodesWhitelist()).containsExactly(enode1);
}
@Test
public void whenAddNodesInputHasExistingNodeShouldReturnAddErrorExistingEntry() {
controller.addNodes(Arrays.asList(enode1));
NodesWhitelistResult expected =
new NodesWhitelistResult(WhitelistOperationResult.ERROR_EXISTING_ENTRY);
NodesWhitelistResult actualResult = controller.addNodes(Lists.newArrayList(enode1, enode2));
assertThat(actualResult).isEqualToComparingOnlyGivenFields(expected, "result");
}
@Test
public void whenAddNodesInputHasDuplicatedNodesShouldReturnDuplicatedEntryError() {
NodesWhitelistResult expected =
new NodesWhitelistResult(WhitelistOperationResult.ERROR_DUPLICATED_ENTRY);
NodesWhitelistResult actualResult = controller.addNodes(Arrays.asList(enode1, enode1));
assertThat(actualResult).isEqualToComparingOnlyGivenFields(expected, "result");
}
@Test
public void whenAddNodesInputHasEmptyListOfNodesShouldReturnErrorEmptyEntry() {
NodesWhitelistResult expected =
new NodesWhitelistResult(WhitelistOperationResult.ERROR_EMPTY_ENTRY);
NodesWhitelistResult actualResult = controller.removeNodes(new ArrayList<>());
assertThat(actualResult).isEqualToComparingOnlyGivenFields(expected, "result");
}
@Test
public void whenAddNodesInputHasNullListOfNodesShouldReturnErrorEmptyEntry() {
NodesWhitelistResult expected =
new NodesWhitelistResult(WhitelistOperationResult.ERROR_EMPTY_ENTRY);
NodesWhitelistResult actualResult = controller.removeNodes(null);
assertThat(actualResult).isEqualToComparingOnlyGivenFields(expected, "result");
}
@Test
public void whenRemoveNodesInputHasAbsentNodeShouldReturnRemoveErrorAbsentEntry() {
NodesWhitelistResult expected =
new NodesWhitelistResult(WhitelistOperationResult.ERROR_ABSENT_ENTRY);
NodesWhitelistResult actualResult = controller.removeNodes(Lists.newArrayList(enode1, enode2));
assertThat(actualResult).isEqualToComparingOnlyGivenFields(expected, "result");
}
@Test
public void whenRemoveNodesInputHasDuplicateNodesShouldReturnErrorDuplicatedEntry() {
NodesWhitelistResult expected =
new NodesWhitelistResult(WhitelistOperationResult.ERROR_DUPLICATED_ENTRY);
NodesWhitelistResult actualResult = controller.removeNodes(Lists.newArrayList(enode1, enode1));
assertThat(actualResult).isEqualToComparingOnlyGivenFields(expected, "result");
}
@Test
public void whenRemoveNodesInputHasEmptyListOfNodesShouldReturnErrorEmptyEntry() {
NodesWhitelistResult expected =
new NodesWhitelistResult(WhitelistOperationResult.ERROR_EMPTY_ENTRY);
NodesWhitelistResult actualResult = controller.removeNodes(new ArrayList<>());
assertThat(actualResult).isEqualToComparingOnlyGivenFields(expected, "result");
}
@Test
public void whenRemoveNodesInputHasNullListOfNodesShouldReturnErrorEmptyEntry() {
NodesWhitelistResult expected =
new NodesWhitelistResult(WhitelistOperationResult.ERROR_EMPTY_ENTRY);
NodesWhitelistResult actualResult = controller.removeNodes(null);
assertThat(actualResult).isEqualToComparingOnlyGivenFields(expected, "result");
}
@Test
public void whenNodeIdsAreDifferentItShouldNotBePermitted() {
String peer1 =
"enode://aaaa80d14311c39f35f516fa664deaaaa13e85b2f7493f37f6144d86991ec012937307647bd3b9a82abe2974e1407241d54947bbb39763a4cac9f77166ad92a0@127.0.0.1:30303";
String peer2 =
"enode://bbbb80d14311c39f35f516fa664deaaaa13e85b2f7493f37f6144d86991ec012937307647bd3b9a82abe2974e1407241d54947bbb39763a4cac9f77166ad92a0@127.0.0.1:30303";
controller.addNodes(Arrays.asList(peer1));
assertThat(controller.isPermitted(peer2)).isFalse();
verifyCountersUntouched();
assertThat(controller.isPermitted(EnodeURL.fromString(peer2), EnodeURL.fromString(peer1)))
.isFalse();
verifyCountersUnpermitted();
}
@Test
public void whenNodesHostsAreDifferentItShouldNotBePermitted() {
String peer1 =
"enode://aaaa80d14311c39f35f516fa664deaaaa13e85b2f7493f37f6144d86991ec012937307647bd3b9a82abe2974e1407241d54947bbb39763a4cac9f77166ad92a0@127.0.0.1:30303";
String peer2 =
"enode://aaaa80d14311c39f35f516fa664deaaaa13e85b2f7493f37f6144d86991ec012937307647bd3b9a82abe2974e1407241d54947bbb39763a4cac9f77166ad92a0@127.0.0.2:30303";
controller.addNodes(Arrays.asList(peer1));
assertThat(controller.isPermitted(peer2)).isFalse();
}
@Test
public void whenNodesListeningPortsAreDifferentItShouldNotBePermitted() {
String peer1 =
"enode://aaaa80d14311c39f35f516fa664deaaaa13e85b2f7493f37f6144d86991ec012937307647bd3b9a82abe2974e1407241d54947bbb39763a4cac9f77166ad92a0@127.0.0.1:30301";
String peer2 =
"enode://aaaa80d14311c39f35f516fa664deaaaa13e85b2f7493f37f6144d86991ec012937307647bd3b9a82abe2974e1407241d54947bbb39763a4cac9f77166ad92a0@127.0.0.1:30302";
controller.addNodes(Arrays.asList(peer1));
assertThat(controller.isPermitted(peer2)).isFalse();
}
@Test
public void
whenCheckingIfNodeIsPermittedDiscoveryPortShouldNotBeConsidered_implicitDiscPortMismatch() {
String peerWithDiscoveryPortSet =
"enode://aaaa80d14311c39f35f516fa664deaaaa13e85b2f7493f37f6144d86991ec012937307647bd3b9a82abe2974e1407241d54947bbb39763a4cac9f77166ad92a0@127.0.0.1:30303?discport=10001";
String peerWithoutDiscoveryPortSet =
"enode://aaaa80d14311c39f35f516fa664deaaaa13e85b2f7493f37f6144d86991ec012937307647bd3b9a82abe2974e1407241d54947bbb39763a4cac9f77166ad92a0@127.0.0.1:30303";
controller.addNodes(Arrays.asList(peerWithDiscoveryPortSet));
assertThat(controller.isPermitted(peerWithoutDiscoveryPortSet)).isTrue();
}
@Test
public void
whenCheckingIfNodeIsPermittedDiscoveryPortShouldBeNotConsidered_explicitDiscPortMismatch() {
String peerWithDiscoveryPortSet =
"enode://aaaa80d14311c39f35f516fa664deaaaa13e85b2f7493f37f6144d86991ec012937307647bd3b9a82abe2974e1407241d54947bbb39763a4cac9f77166ad92a0@127.0.0.1:30303?discport=10001";
String peerWithDifferentDiscoveryPortSet =
"enode://aaaa80d14311c39f35f516fa664deaaaa13e85b2f7493f37f6144d86991ec012937307647bd3b9a82abe2974e1407241d54947bbb39763a4cac9f77166ad92a0@127.0.0.1:30303?discport=10002";
controller.addNodes(Arrays.asList(peerWithDifferentDiscoveryPortSet));
assertThat(controller.isPermitted(peerWithDiscoveryPortSet)).isTrue();
}
@Test
public void
whenCheckingIfNodeIsPermittedDiscoveryPortShouldNotBeConsidered_nodeToCheckHasDiscDisabled() {
String peerWithDiscoveryPortSet =
"enode://aaaa80d14311c39f35f516fa664deaaaa13e85b2f7493f37f6144d86991ec012937307647bd3b9a82abe2974e1407241d54947bbb39763a4cac9f77166ad92a0@127.0.0.1:30303?discport=10001";
String peerWithoutDiscoveryPortSet =
"enode://aaaa80d14311c39f35f516fa664deaaaa13e85b2f7493f37f6144d86991ec012937307647bd3b9a82abe2974e1407241d54947bbb39763a4cac9f77166ad92a0@127.0.0.1:30303?discport=0";
controller.addNodes(Arrays.asList(peerWithDiscoveryPortSet));
assertThat(controller.isPermitted(peerWithoutDiscoveryPortSet)).isTrue();
}
@Test
public void
whenCheckingIfNodeIsPermittedDiscoveryPortShouldNotBeConsidered_whitelistedNodeHasDiscDisabled() {
String peerWithDiscoveryPortSet =
"enode://aaaa80d14311c39f35f516fa664deaaaa13e85b2f7493f37f6144d86991ec012937307647bd3b9a82abe2974e1407241d54947bbb39763a4cac9f77166ad92a0@127.0.0.1:30303?discport=0";
String peerWithoutDiscoveryPortSet =
"enode://aaaa80d14311c39f35f516fa664deaaaa13e85b2f7493f37f6144d86991ec012937307647bd3b9a82abe2974e1407241d54947bbb39763a4cac9f77166ad92a0@127.0.0.1:30303?discport=123";
controller.addNodes(Arrays.asList(peerWithDiscoveryPortSet));
assertThat(controller.isPermitted(peerWithoutDiscoveryPortSet)).isTrue();
}
@Test
public void
whenCheckingIfNodeIsPermittedDiscoveryPortShouldNotBeConsidered_whitelistAndNodeHaveDiscDisabled() {
String peerWithDiscoveryPortSet =
"enode://aaaa80d14311c39f35f516fa664deaaaa13e85b2f7493f37f6144d86991ec012937307647bd3b9a82abe2974e1407241d54947bbb39763a4cac9f77166ad92a0@127.0.0.1:30303?discport=0";
String peerWithoutDiscoveryPortSet =
"enode://aaaa80d14311c39f35f516fa664deaaaa13e85b2f7493f37f6144d86991ec012937307647bd3b9a82abe2974e1407241d54947bbb39763a4cac9f77166ad92a0@127.0.0.1:30303?discport=0";
controller.addNodes(Arrays.asList(peerWithDiscoveryPortSet));
assertThat(controller.isPermitted(peerWithoutDiscoveryPortSet)).isTrue();
}
@Test
public void whenCheckingIfNodeIsPermittedOrderDoesNotMatter() {
controller.addNodes(Arrays.asList(enode1));
verifyCountersUntouched();
assertThat(controller.isPermitted(EnodeURL.fromString(enode1), selfEnode)).isTrue();
verifyCountersPermitted();
assertThat(controller.isPermitted(selfEnode, EnodeURL.fromString(enode1))).isTrue();
}
@Test
public void stateShouldRevertIfWhitelistPersistFails()
throws IOException, WhitelistFileSyncException {
List<String> newNode1 = singletonList(EnodeURL.fromString(enode1).toString());
List<String> newNode2 = singletonList(EnodeURL.fromString(enode2).toString());
assertThat(controller.getNodesWhitelist().size()).isEqualTo(0);
controller.addNodes(newNode1);
assertThat(controller.getNodesWhitelist().size()).isEqualTo(1);
doThrow(new IOException()).when(whitelistPersistor).updateConfig(any(), any());
controller.addNodes(newNode2);
assertThat(controller.getNodesWhitelist().size()).isEqualTo(1);
assertThat(controller.getNodesWhitelist()).isEqualTo(newNode1);
verify(whitelistPersistor, times(3)).verifyConfigFileMatchesState(any(), any());
verify(whitelistPersistor, times(2)).updateConfig(any(), any());
verifyNoMoreInteractions(whitelistPersistor);
}
@Test
public void reloadNodeWhitelistWithValidConfigFileShouldUpdateWhitelist() throws Exception {
final String expectedEnodeURL =
"enode://6f8a80d14311c39f35f516fa664deaaaa13e85b2f7493f37f6144d86991ec012937307647bd3b9a82abe2974e1407241d54947bbb39763a4cac9f77166ad92a0@192.168.0.9:4567";
final Path permissionsFile = createPermissionsFileWithNode(expectedEnodeURL);
final LocalPermissioningConfiguration permissioningConfig =
mock(LocalPermissioningConfiguration.class);
when(permissioningConfig.getNodePermissioningConfigFilePath())
.thenReturn(permissionsFile.toAbsolutePath().toString());
when(permissioningConfig.isNodeWhitelistEnabled()).thenReturn(true);
when(permissioningConfig.getNodeWhitelist())
.thenReturn(Arrays.asList(URI.create(expectedEnodeURL)));
controller =
new NodeLocalConfigPermissioningController(
permissioningConfig, bootnodesList, selfEnode.getNodeId(), metricsSystem);
controller.reload();
assertThat(controller.getNodesWhitelist()).containsExactly(expectedEnodeURL);
}
@Test
public void reloadNodeWhitelistWithErrorReadingConfigFileShouldKeepOldWhitelist() {
final String expectedEnodeURI =
"enode://aaaa80d14311c39f35f516fa664deaaaa13e85b2f7493f37f6144d86991ec012937307647bd3b9a82abe2974e1407241d54947bbb39763a4cac9f77166ad92a0@192.168.0.9:4567";
final LocalPermissioningConfiguration permissioningConfig =
mock(LocalPermissioningConfiguration.class);
when(permissioningConfig.getNodePermissioningConfigFilePath()).thenReturn("foo");
when(permissioningConfig.isNodeWhitelistEnabled()).thenReturn(true);
when(permissioningConfig.getNodeWhitelist())
.thenReturn(Arrays.asList(URI.create(expectedEnodeURI)));
controller =
new NodeLocalConfigPermissioningController(
permissioningConfig, bootnodesList, selfEnode.getNodeId(), metricsSystem);
final Throwable thrown = catchThrowable(() -> controller.reload());
assertThat(thrown)
.isInstanceOf(RuntimeException.class)
.hasMessageContaining("Unable to read permissioning TOML config file");
assertThat(controller.getNodesWhitelist()).containsExactly(expectedEnodeURI);
}
@Test
@SuppressWarnings("unchecked")
public void whenAddingNodeShouldNotifyWhitelistModifiedSubscribers() {
final Consumer<NodeWhitelistUpdatedEvent> consumer = mock(Consumer.class);
final NodeWhitelistUpdatedEvent expectedEvent =
new NodeWhitelistUpdatedEvent(
Lists.newArrayList(EnodeURL.fromString(enode1)), Collections.emptyList());
controller.subscribeToListUpdatedEvent(consumer);
controller.addNodes(Lists.newArrayList(enode1));
verify(consumer).accept(eq(expectedEvent));
}
@Test
@SuppressWarnings("unchecked")
public void whenAddingNodeDoesNotAddShouldNotNotifyWhitelistModifiedSubscribers() {
// adding node before subscribing to whitelist modified events
controller.addNodes(Lists.newArrayList(enode1));
final Consumer<NodeWhitelistUpdatedEvent> consumer = mock(Consumer.class);
controller.subscribeToListUpdatedEvent(consumer);
// won't add duplicate node
controller.addNodes(Lists.newArrayList(enode1));
verifyZeroInteractions(consumer);
}
@Test
@SuppressWarnings("unchecked")
public void whenRemovingNodeShouldNotifyWhitelistModifiedSubscribers() {
// adding node before subscribing to whitelist modified events
controller.addNodes(Lists.newArrayList(enode1));
final Consumer<NodeWhitelistUpdatedEvent> consumer = mock(Consumer.class);
final NodeWhitelistUpdatedEvent expectedEvent =
new NodeWhitelistUpdatedEvent(
Collections.emptyList(), Lists.newArrayList(EnodeURL.fromString(enode1)));
controller.subscribeToListUpdatedEvent(consumer);
controller.removeNodes(Lists.newArrayList(enode1));
verify(consumer).accept(eq(expectedEvent));
}
@Test
@SuppressWarnings("unchecked")
public void whenRemovingNodeDoesNotRemoveShouldNotifyWhitelistModifiedSubscribers() {
final Consumer<NodeWhitelistUpdatedEvent> consumer = mock(Consumer.class);
controller.subscribeToListUpdatedEvent(consumer);
// won't remove absent node
controller.removeNodes(Lists.newArrayList(enode1));
verifyZeroInteractions(consumer);
}
@Test
public void whenRemovingBootnodeShouldReturnRemoveBootnodeError() {
NodesWhitelistResult expected =
new NodesWhitelistResult(WhitelistOperationResult.ERROR_FIXED_NODE_CANNOT_BE_REMOVED);
bootnodesList.add(EnodeURL.fromString(enode1));
controller.addNodes(Lists.newArrayList(enode1, enode2));
NodesWhitelistResult actualResult = controller.removeNodes(Lists.newArrayList(enode1));
assertThat(actualResult).isEqualToComparingOnlyGivenFields(expected, "result");
assertThat(controller.getNodesWhitelist()).containsExactly(enode1, enode2);
}
@Test
@SuppressWarnings("unchecked")
public void whenReloadingWhitelistShouldNotifyWhitelistModifiedSubscribers() throws Exception {
final Path permissionsFile = createPermissionsFileWithNode(enode2);
final LocalPermissioningConfiguration permissioningConfig =
mock(LocalPermissioningConfiguration.class);
final Consumer<NodeWhitelistUpdatedEvent> consumer = mock(Consumer.class);
final NodeWhitelistUpdatedEvent expectedEvent =
new NodeWhitelistUpdatedEvent(
Lists.newArrayList(EnodeURL.fromString(enode2)),
Lists.newArrayList(EnodeURL.fromString(enode1)));
when(permissioningConfig.getNodePermissioningConfigFilePath())
.thenReturn(permissionsFile.toAbsolutePath().toString());
when(permissioningConfig.isNodeWhitelistEnabled()).thenReturn(true);
when(permissioningConfig.getNodeWhitelist()).thenReturn(Arrays.asList(URI.create(enode1)));
controller =
new NodeLocalConfigPermissioningController(
permissioningConfig, bootnodesList, selfEnode.getNodeId(), metricsSystem);
controller.subscribeToListUpdatedEvent(consumer);
controller.reload();
verify(consumer).accept(eq(expectedEvent));
}
@Test
@SuppressWarnings("unchecked")
public void whenReloadingWhitelistAndNothingChangesShouldNotNotifyWhitelistModifiedSubscribers()
throws Exception {
final Path permissionsFile = createPermissionsFileWithNode(enode1);
final LocalPermissioningConfiguration permissioningConfig =
mock(LocalPermissioningConfiguration.class);
final Consumer<NodeWhitelistUpdatedEvent> consumer = mock(Consumer.class);
when(permissioningConfig.getNodePermissioningConfigFilePath())
.thenReturn(permissionsFile.toAbsolutePath().toString());
when(permissioningConfig.isNodeWhitelistEnabled()).thenReturn(true);
when(permissioningConfig.getNodeWhitelist()).thenReturn(Arrays.asList(URI.create(enode1)));
controller =
new NodeLocalConfigPermissioningController(
permissioningConfig, bootnodesList, selfEnode.getNodeId(), metricsSystem);
controller.subscribeToListUpdatedEvent(consumer);
controller.reload();
verifyZeroInteractions(consumer);
}
private Path createPermissionsFileWithNode(final String node) throws IOException {
final String nodePermissionsFileContent = "nodes-whitelist=[\"" + node + "\"]";
final Path permissionsFile = Files.createTempFile("node_permissions", "");
permissionsFile.toFile().deleteOnExit();
Files.write(permissionsFile, nodePermissionsFileContent.getBytes(StandardCharsets.UTF_8));
return permissionsFile;
}
private void verifyCountersUntouched() {
verify(checkCounter, times(0)).inc();
verify(checkPermittedCounter, times(0)).inc();
verify(checkUnpermittedCounter, times(0)).inc();
}
private void verifyCountersPermitted() {
verify(checkCounter, times(1)).inc();
verify(checkPermittedCounter, times(1)).inc();
verify(checkUnpermittedCounter, times(0)).inc();
}
private void verifyCountersUnpermitted() {
verify(checkCounter, times(1)).inc();
verify(checkPermittedCounter, times(0)).inc();
verify(checkUnpermittedCounter, times(1)).inc();
}
}
|
/*
* Copyright (c) 2005 - 2015, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy
* of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed
* under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
* CONDITIONS OF ANY KIND, either express or implied. See the License for the
* specific language governing permissions and limitations under the License.
*/
package org.wso2.siddhi.query.api.execution.query.input.state;
import org.wso2.siddhi.query.api.expression.constant.TimeConstant;
public class CountStateElement implements StateElement {
public static final int ANY = -1;
private StreamStateElement streamStateElement;
private TimeConstant within;
private int minCount = ANY;
private int maxCount = ANY;
public CountStateElement(StreamStateElement streamStateElement, int minCount, int maxCount, TimeConstant within) {
this.streamStateElement = streamStateElement;
this.within = within;
this.minCount = minCount;
this.maxCount = maxCount;
}
public CountStateElement(StreamStateElement streamStateElement, int minCount, int maxCount) {
this.streamStateElement = streamStateElement;
this.minCount = minCount;
this.maxCount = maxCount;
}
public int getMinCount() {
return minCount;
}
public int getMaxCount() {
return maxCount;
}
public StreamStateElement getStreamStateElement() {
return streamStateElement;
}
@Override
public TimeConstant getWithin() {
return within;
}
public void setWithin(TimeConstant within) {
this.within = within;
}
@Override
public String toString() {
return "CountStateElement{" +
"streamStateElement=" + streamStateElement +
", within=" + within +
", minCount=" + minCount +
", maxCount=" + maxCount +
'}';
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (!(o instanceof CountStateElement)) return false;
CountStateElement that = (CountStateElement) o;
if (maxCount != that.maxCount) return false;
if (minCount != that.minCount) return false;
if (streamStateElement != null ? !streamStateElement.equals(that.streamStateElement) : that.streamStateElement != null)
return false;
if (within != null ? !within.equals(that.within) : that.within != null) return false;
return true;
}
@Override
public int hashCode() {
int result = streamStateElement != null ? streamStateElement.hashCode() : 0;
result = 31 * result + (within != null ? within.hashCode() : 0);
result = 31 * result + minCount;
result = 31 * result + maxCount;
return result;
}
}
|
package jp.co.tis.action.test;
import javax.inject.Inject;
import java.io.Serializable;
import oscana.s2n.struts.GenericsUtil;
import nablarch.core.db.connection.DbConnectionContext;
import oscana.s2n.common.ParamFilter;
import nablarch.fw.dicontainer.web.RequestScoped;
import nablarch.fw.dicontainer.web.SessionScoped;
import nablarch.fw.dicontainer.Prototype;
import javax.inject.Singleton;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import oscana.s2n.struts.action.ActionMapping;
import oscana.s2n.struts.OscanaHttpResourceConverUtil;
import oscana.s2n.common.web.interceptor.Execute;
import nablarch.common.dao.DeferredEntityList;
import nablarch.common.dao.UniversalDao;
import nablarch.common.databind.ObjectMapper;
import nablarch.common.databind.ObjectMapperFactory;
import nablarch.common.web.download.FileResponse;
import nablarch.common.web.token.OnDoubleSubmission;
import nablarch.core.message.ApplicationException;
import nablarch.core.message.MessageLevel;
import nablarch.core.message.MessageUtil;
import nablarch.fw.ExecutionContext;
import nablarch.fw.web.HttpRequest;
import nablarch.fw.web.HttpResponse;
import nablarch.fw.web.interceptor.OnError;
import oscana.s2n.common.OscanaActionForm;
/**
* 変換用テストデータファイル
*
* @author Ko Ho
*/
public class TestConvertCommondaction {
@Inject
@OscanaActionForm
@ActionForm
public TestForm testForm;
/** エンティティのリスト */
public List list;
/**
* 検索一覧画面を表示する。
*
* @return 遷移先画面
*/
public String index() {
return "searchList.jsp";
}
}
|
/**
*/
package petstore;
import com.microsoft.azure.CloudException;
import com.microsoft.rest.ServiceCall;
import com.microsoft.rest.ServiceCallback;
import com.microsoft.rest.ServiceResponse;
import java.io.IOException;
import java.util.List;
import petstore.models.Usage;
/**
* An instance of this class provides access to all the operations defined
* in Usage.
*/
public interface Usage {
/**
* Gets the current usage count and the limit for the resources under the subscription.
*
* @throws CloudException exception thrown from REST call
* @throws IOException exception thrown from serialization/deserialization
* @throws IllegalArgumentException exception thrown from invalid parameters
* @return the List<Usage> object wrapped in {@link ServiceResponse} if successful.
*/
ServiceResponse<List<Usage>> list() throws CloudException, IOException, IllegalArgumentException;
/**
* Gets the current usage count and the limit for the resources under the subscription.
*
* @param serviceCallback the async ServiceCallback to handle successful and failed responses.
* @throws IllegalArgumentException thrown if callback is null
* @return the {@link ServiceCall} object
*/
ServiceCall listAsync(final ServiceCallback<List<Usage>> serviceCallback) throws IllegalArgumentException;
}
|
/*
* MIT License
*
* Copyright (c) 2021 MASES s.r.l.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
/**************************************************************************************
* <auto-generated>
* This code was generated from a template using JCOReflector
*
* Manual changes to this file may cause unexpected behavior in your application.
* Manual changes to this file will be overwritten if the code is regenerated.
* </auto-generated>
*************************************************************************************/
package microsoft.visualbasic;
import org.mases.jcobridge.*;
import org.mases.jcobridge.netreflection.*;
// Import section
// PACKAGE_IMPORT_SECTION
/**
* The base .NET class managing Microsoft.VisualBasic.VbStrConv, Microsoft.VisualBasic, Version=10.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a. Extends {@link NetObject}.
* <p>
*
* See: <a href="https://docs.microsoft.com/en-us/dotnet/api/Microsoft.VisualBasic.VbStrConv" target="_top">https://docs.microsoft.com/en-us/dotnet/api/Microsoft.VisualBasic.VbStrConv</a>
*/
public class VbStrConv extends NetObject {
/**
* Fully assembly qualified name: Microsoft.VisualBasic, Version=10.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a
*/
public static final String assemblyFullName = "Microsoft.VisualBasic, Version=10.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a";
/**
* Assembly name: Microsoft.VisualBasic
*/
public static final String assemblyShortName = "Microsoft.VisualBasic";
/**
* Qualified class name: Microsoft.VisualBasic.VbStrConv
*/
public static final String className = "Microsoft.VisualBasic.VbStrConv";
static JCOBridge bridge = JCOBridgeInstance.getInstance(assemblyFullName);
/**
* The type managed from JCOBridge. See {@link JCType}
*/
public static JCType classType = createType();
static JCEnum enumReflected = createEnum();
JCEnum classInstance = null;
static JCType createType() {
try {
String classToCreate = className + ", "
+ (JCOReflector.getUseFullAssemblyName() ? assemblyFullName : assemblyShortName);
if (JCOReflector.getDebug())
JCOReflector.writeLog("Creating %s", classToCreate);
JCType typeCreated = bridge.GetType(classToCreate);
if (JCOReflector.getDebug())
JCOReflector.writeLog("Created: %s",
(typeCreated != null) ? typeCreated.toString() : "Returned null value");
return typeCreated;
} catch (JCException e) {
JCOReflector.writeLog(e);
return null;
}
}
static JCEnum createEnum() {
try {
String enumToCreate = className + ", "
+ (JCOReflector.getUseFullAssemblyName() ? assemblyFullName : assemblyShortName);
if (JCOReflector.getDebug())
JCOReflector.writeLog("Creating Enum %s", enumToCreate);
JCEnum enumCreated = bridge.GetEnum(enumToCreate);
if (JCOReflector.getDebug())
JCOReflector.writeLog("Created Enum: %s",
(enumCreated != null) ? enumCreated.toString() : "Returned null value");
return enumCreated;
} catch (JCException e) {
JCOReflector.writeLog(e);
return null;
}
}
void addReference(String ref) throws Throwable {
try {
bridge.AddReference(ref);
} catch (JCNativeException jcne) {
throw translateException(jcne);
}
}
public VbStrConv(Object instance) {
super(instance);
if (instance instanceof JCObject) {
try {
String enumName = NetEnum.GetName(classType, (JCObject)instance);
classInstance = enumReflected.fromValue(enumName);
} catch (Throwable t) {
JCOReflector.writeLog(t);
classInstance = enumReflected;
}
} else if (instance instanceof JCEnum) {
classInstance = (JCEnum)instance;
}
}
public VbStrConv() {
super();
// add reference to assemblyName.dll file
try {
addReference(JCOReflector.getUseFullAssemblyName() ? assemblyFullName : assemblyShortName);
} catch (Throwable jcne) {
JCOReflector.writeLog(jcne);
}
}
public String getJCOAssemblyName() {
return assemblyFullName;
}
public String getJCOClassName() {
return className;
}
public String getJCOObjectName() {
return className + ", " + (JCOReflector.getUseFullAssemblyName() ? assemblyFullName : assemblyShortName);
}
public Object getJCOInstance() {
return classInstance;
}
public JCType getJCOType() {
return classType;
}
final static VbStrConv getFrom(JCEnum object, String value) {
try {
return new VbStrConv(object.fromValue(value));
} catch (JCException e) {
return new VbStrConv(object);
}
}
// Enum fields section
public static VbStrConv None = getFrom(enumReflected, "None");
public static VbStrConv Uppercase = getFrom(enumReflected, "Uppercase");
public static VbStrConv Lowercase = getFrom(enumReflected, "Lowercase");
public static VbStrConv ProperCase = getFrom(enumReflected, "ProperCase");
public static VbStrConv Wide = getFrom(enumReflected, "Wide");
public static VbStrConv Narrow = getFrom(enumReflected, "Narrow");
public static VbStrConv Katakana = getFrom(enumReflected, "Katakana");
public static VbStrConv Hiragana = getFrom(enumReflected, "Hiragana");
public static VbStrConv SimplifiedChinese = getFrom(enumReflected, "SimplifiedChinese");
public static VbStrConv TraditionalChinese = getFrom(enumReflected, "TraditionalChinese");
public static VbStrConv LinguisticCasing = getFrom(enumReflected, "LinguisticCasing");
// Flags management section
public final VbStrConv add(VbStrConv val) throws Throwable {
return new VbStrConv(NetEnum.add(classInstance, val.classInstance));
}
public final VbStrConv remove(VbStrConv val) throws Throwable {
return new VbStrConv(NetEnum.remove(classInstance, val.classInstance));
}
public final boolean is(VbStrConv val) throws Throwable {
return NetEnum.is(classInstance, val.classInstance);
}
public final boolean has(VbStrConv val) throws Throwable {
return NetEnum.has(classInstance, val.classInstance);
}
}
|
/*
* Copyright 2018 Feedzai
*
* 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.feedzai.util;
import com.feedzai.openml.data.schema.CategoricalValueSchema;
import com.feedzai.openml.data.schema.DatasetSchema;
import com.feedzai.openml.data.schema.FieldSchema;
import com.feedzai.openml.data.schema.NumericValueSchema;
import com.feedzai.util.data.ClassificationDatasetSchemaUtil;
import com.google.common.collect.ImmutableList;
import org.junit.Test;
import java.util.Set;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
/**
* Tests for utilities that manage dataset schemas for classification problems.
*
* @author Nuno Diegues (nuno.diegues@feedzai.com)
* @since 0.1.0
*/
public class ClassificationDatasetSchemaUtilTest {
/**
* Tests that a valid categorical field as target variable yields the right number of classes.
*/
@Test
public void testValidTarget() {
IntStream.range(0, 10)
.forEach(numClasses ->
assertThat(ClassificationDatasetSchemaUtil.getNumClassValues(createClassificationDatasetSchema(numClasses)))
.as("The number of classes")
.isEqualTo(numClasses));
}
/**
* Tests that a non-categorical field yields an error as expected.
*/
@Test
public void testInvalidTarget() {
final DatasetSchema datasetSchema = new DatasetSchema(
0,
ImmutableList.of(new FieldSchema(
"some number",
0,
new NumericValueSchema(false)
))
);
assertThatThrownBy(() -> ClassificationDatasetSchemaUtil.getNumClassValues(datasetSchema))
.as("The error for not having a categorical target")
.isInstanceOf(RuntimeException.class);
}
/**
* Creates a dataset schema for a classification problem.
*
* @param numberClasses The number of classes expected.
* @return The schema.
*/
private DatasetSchema createClassificationDatasetSchema(final int numberClasses) {
final Set<String> possibleValues = IntStream.range(0, numberClasses)
.mapToObj(idx -> "targetValue" + idx)
.collect(Collectors.toSet());
return new DatasetSchema(
0,
ImmutableList.of(new FieldSchema(
"isFraud",
0,
new CategoricalValueSchema(false, possibleValues)
))
);
}
}
|
/*
* Copyright The OpenTelemetry Authors
* SPDX-License-Identifier: Apache-2.0
*/
package io.opentelemetry.sdk.testing.assertj;
import io.opentelemetry.sdk.common.InstrumentationLibraryInfo;
import io.opentelemetry.sdk.metrics.data.DoublePointData;
import io.opentelemetry.sdk.metrics.data.LongPointData;
import io.opentelemetry.sdk.metrics.data.MetricData;
import io.opentelemetry.sdk.metrics.data.MetricDataType;
import io.opentelemetry.sdk.metrics.internal.data.exponentialhistogram.ExponentialHistogramData;
import io.opentelemetry.sdk.resources.Resource;
import org.assertj.core.api.AbstractAssert;
/** Test assertions for {@link MetricData}. */
public class MetricDataAssert extends AbstractAssert<MetricDataAssert, MetricData> {
protected MetricDataAssert(MetricData actual) {
super(actual, MetricDataAssert.class);
}
/** Ensures the {@link Resource} associated with a metric matches the expected value. */
public MetricDataAssert hasResource(Resource resource) {
isNotNull();
if (!actual.getResource().equals(resource)) {
failWithActualExpectedAndMessage(
actual,
"resource: " + resource,
"Expected MetricData to have resource <%s> but found <%s>",
resource,
actual.getResource());
}
return this;
}
/**
* Ensures the {@link InstrumentationLibraryInfo} associated with a metric matches the expected
* value.
*/
public MetricDataAssert hasInstrumentationLibrary(
InstrumentationLibraryInfo instrumentationLibrary) {
isNotNull();
if (!actual.getInstrumentationLibraryInfo().equals(instrumentationLibrary)) {
failWithActualExpectedAndMessage(
actual,
"instrumentation library: " + instrumentationLibrary,
"Expected MetricData to have resource <%s> but found <%s>",
instrumentationLibrary,
actual.getInstrumentationLibraryInfo());
}
return this;
}
/** Ensures the {@code name} field matches the expected value. */
public MetricDataAssert hasName(String name) {
isNotNull();
if (!actual.getName().equals(name)) {
failWithActualExpectedAndMessage(
actual,
"name: " + name,
"Expected MetricData to have name <%s> but found <%s>",
name,
actual.getName());
}
return this;
}
/** Ensures the {@code description} field matches the expected value. */
public MetricDataAssert hasDescription(String description) {
isNotNull();
if (!actual.getDescription().equals(description)) {
failWithActualExpectedAndMessage(
actual,
"description: " + description,
"Expected MetricData to have description <%s> but found <%s>",
description,
actual.getDescription());
}
return this;
}
/** Ensures the {@code unit} field matches the expected value. */
public MetricDataAssert hasUnit(String unit) {
isNotNull();
if (!actual.getUnit().equals(unit)) {
failWithActualExpectedAndMessage(
actual,
"unit: " + unit,
"Expected MetricData to have unit <%s> but found <%s>",
unit,
actual.getUnit());
}
return this;
}
/**
* Ensures this {@link MetricData} is a {@code DoubleHistogram}.
*
* @return convenience API to assert against the {@code DoubleHistogram}.
*/
public HistogramAssert hasDoubleHistogram() {
isNotNull();
if (actual.getType() != MetricDataType.HISTOGRAM) {
failWithActualExpectedAndMessage(
actual,
"type: HISTOGRAM",
"Expected MetricData to have type <%s> but found <%s>",
MetricDataType.HISTOGRAM,
actual.getType());
}
return new HistogramAssert(actual.getHistogramData());
}
/**
* Ensures this {@link MetricData} is a {@code ExponentialHistogram}.
*
* @return convenience API to assert against the {@code ExponentialHistogram}.
*/
public ExponentialHistogramAssert hasExponentialHistogram() {
isNotNull();
if (actual.getType() != MetricDataType.EXPONENTIAL_HISTOGRAM) {
failWithActualExpectedAndMessage(
actual,
"type: EXPONENTIAL_HISTOGRAM",
"Expected MetricData to have type <%s> but found <%s>",
MetricDataType.EXPONENTIAL_HISTOGRAM,
actual.getType());
}
return new ExponentialHistogramAssert(ExponentialHistogramData.fromMetricData(actual));
}
/**
* Ensures this {@link MetricData} is a {@code DoubleGauge}.
*
* @return convenience API to assert against the {@code DoubleGauge}.
*/
public GaugeAssert<DoublePointData> hasDoubleGauge() {
isNotNull();
if (actual.getType() != MetricDataType.DOUBLE_GAUGE) {
failWithActualExpectedAndMessage(
actual,
"type: DOUBLE_GAUGE",
"Expected MetricData to have type <%s> but found <%s>",
MetricDataType.DOUBLE_GAUGE,
actual.getType());
}
return new GaugeAssert<>(actual.getDoubleGaugeData());
}
/**
* Ensures this {@link MetricData} is a {@code DoubleSum}.
*
* @return convenience API to assert against the {@code DoubleSum}.
*/
public SumDataAssert<DoublePointData> hasDoubleSum() {
isNotNull();
if (actual.getType() != MetricDataType.DOUBLE_SUM) {
failWithActualExpectedAndMessage(
actual,
"type: DOUBLE_SUM",
"Expected MetricData to have type <%s> but found <%s>",
MetricDataType.DOUBLE_SUM,
actual.getType());
}
return new SumDataAssert<>(actual.getDoubleSumData());
}
/**
* Ensures this {@link MetricData} is a {@code LongGauge}.
*
* @return convenience API to assert against the {@code LongGauge}.
*/
public GaugeAssert<LongPointData> hasLongGauge() {
isNotNull();
if (actual.getType() != MetricDataType.LONG_GAUGE) {
failWithActualExpectedAndMessage(
actual,
"type: LONG_GAUGE",
"Expected MetricData to have type <%s> but found <%s>",
MetricDataType.LONG_GAUGE,
actual.getType());
}
return new GaugeAssert<>(actual.getLongGaugeData());
}
/**
* Ensures this {@link MetricData} is a {@code LongSum}.
*
* @return convenience API to assert against the {@code LongSum}.
*/
public SumDataAssert<LongPointData> hasLongSum() {
isNotNull();
if (actual.getType() != MetricDataType.LONG_SUM) {
failWithActualExpectedAndMessage(
actual,
"type: LONG_SUM",
"Expected MetricData to have type <%s> but found <%s>",
MetricDataType.LONG_SUM,
actual.getType());
}
return new SumDataAssert<>(actual.getLongSumData());
}
/**
* Ensures this {@link MetricData} is a {@code DoubleSummaryData}.
*
* @return convenience API to assert against the {@code DoubleSummaryData}.
*/
public SummaryDataAssert hasDoubleSummary() {
isNotNull();
if (actual.getType() != MetricDataType.SUMMARY) {
failWithActualExpectedAndMessage(
actual,
"type: SUMMARY",
"Expected MetricData to have type <%s> but found <%s>",
MetricDataType.SUMMARY,
actual.getType());
}
return new SummaryDataAssert(actual.getSummaryData());
}
}
|
/*
* Licensed to Elasticsearch under one or more contributor
* license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright
* ownership. Elasticsearch licenses this file to you under
* the Apache License, Version 2.0 (the "License"); you may
* not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.elasticsearch.indices.cluster;
import com.carrotsearch.hppc.IntOpenHashSet;
import com.carrotsearch.hppc.ObjectContainer;
import com.carrotsearch.hppc.cursors.ObjectCursor;
import com.google.common.collect.Lists;
import org.elasticsearch.ElasticsearchException;
import org.elasticsearch.ElasticsearchIllegalStateException;
import org.elasticsearch.ExceptionsHelper;
import org.elasticsearch.cluster.ClusterChangedEvent;
import org.elasticsearch.cluster.ClusterService;
import org.elasticsearch.cluster.ClusterState;
import org.elasticsearch.cluster.ClusterStateListener;
import org.elasticsearch.cluster.action.index.NodeIndexDeletedAction;
import org.elasticsearch.cluster.action.index.NodeMappingRefreshAction;
import org.elasticsearch.cluster.action.shard.ShardStateAction;
import org.elasticsearch.cluster.metadata.AliasMetaData;
import org.elasticsearch.cluster.metadata.IndexMetaData;
import org.elasticsearch.cluster.metadata.MappingMetaData;
import org.elasticsearch.cluster.node.DiscoveryNode;
import org.elasticsearch.cluster.node.DiscoveryNodes;
import org.elasticsearch.cluster.routing.*;
import org.elasticsearch.common.Nullable;
import org.elasticsearch.common.collect.Tuple;
import org.elasticsearch.common.component.AbstractLifecycleComponent;
import org.elasticsearch.common.compress.CompressedString;
import org.elasticsearch.common.inject.Inject;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.unit.TimeValue;
import org.elasticsearch.common.util.concurrent.ConcurrentCollections;
import org.elasticsearch.index.IndexService;
import org.elasticsearch.index.IndexShardAlreadyExistsException;
import org.elasticsearch.index.IndexShardMissingException;
import org.elasticsearch.index.aliases.IndexAlias;
import org.elasticsearch.index.aliases.IndexAliasesService;
import org.elasticsearch.index.engine.Engine;
import org.elasticsearch.index.gateway.IndexShardGatewayRecoveryException;
import org.elasticsearch.index.gateway.IndexShardGatewayService;
import org.elasticsearch.index.mapper.DocumentMapper;
import org.elasticsearch.index.mapper.MapperService;
import org.elasticsearch.index.settings.IndexSettingsService;
import org.elasticsearch.index.shard.IndexShard;
import org.elasticsearch.index.shard.IndexShardState;
import org.elasticsearch.index.shard.ShardId;
import org.elasticsearch.indices.IndicesService;
import org.elasticsearch.indices.recovery.RecoveryFailedException;
import org.elasticsearch.indices.recovery.RecoveryState;
import org.elasticsearch.indices.recovery.RecoveryTarget;
import org.elasticsearch.threadpool.ThreadPool;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentMap;
import static com.google.common.collect.Maps.newHashMap;
import static org.elasticsearch.ExceptionsHelper.detailedMessage;
/**
*
*/
public class IndicesClusterStateService extends AbstractLifecycleComponent<IndicesClusterStateService> implements ClusterStateListener {
private final IndicesService indicesService;
private final ClusterService clusterService;
private final ThreadPool threadPool;
private final RecoveryTarget recoveryTarget;
private final ShardStateAction shardStateAction;
private final NodeIndexDeletedAction nodeIndexDeletedAction;
private final NodeMappingRefreshAction nodeMappingRefreshAction;
// a map of mappings type we have seen per index due to cluster state
// we need this so we won't remove types automatically created as part of the indexing process
private final ConcurrentMap<Tuple<String, String>, Boolean> seenMappings = ConcurrentCollections.newConcurrentMap();
// a list of shards that failed during recovery
// we keep track of these shards in order to prevent repeated recovery of these shards on each cluster state update
private final ConcurrentMap<ShardId, FailedShard> failedShards = ConcurrentCollections.newConcurrentMap();
static class FailedShard {
public final long version;
public final long timestamp;
FailedShard(long version) {
this.version = version;
this.timestamp = System.currentTimeMillis();
}
}
private final Object mutex = new Object();
private final FailedEngineHandler failedEngineHandler = new FailedEngineHandler();
private final boolean sendRefreshMapping;
@Inject
public IndicesClusterStateService(Settings settings, IndicesService indicesService, ClusterService clusterService,
ThreadPool threadPool, RecoveryTarget recoveryTarget,
ShardStateAction shardStateAction,
NodeIndexDeletedAction nodeIndexDeletedAction,
NodeMappingRefreshAction nodeMappingRefreshAction) {
super(settings);
this.indicesService = indicesService;
this.clusterService = clusterService;
this.threadPool = threadPool;
this.recoveryTarget = recoveryTarget;
this.shardStateAction = shardStateAction;
this.nodeIndexDeletedAction = nodeIndexDeletedAction;
this.nodeMappingRefreshAction = nodeMappingRefreshAction;
this.sendRefreshMapping = this.settings.getAsBoolean("indices.cluster.send_refresh_mapping", true);
}
@Override
protected void doStart() throws ElasticsearchException {
clusterService.addFirst(this);
}
@Override
protected void doStop() throws ElasticsearchException {
clusterService.remove(this);
}
@Override
protected void doClose() throws ElasticsearchException {
}
@Override
public void clusterChanged(final ClusterChangedEvent event) {
if (!indicesService.changesAllowed()) {
return;
}
if (!lifecycle.started()) {
return;
}
synchronized (mutex) {
// we need to clean the shards and indices we have on this node, since we
// are going to recover them again once state persistence is disabled (no master / not recovered)
// TODO: this feels a bit hacky here, a block disables state persistence, and then we clean the allocated shards, maybe another flag in blocks?
if (event.state().blocks().disableStatePersistence()) {
for (IndexService indexService : indicesService) {
String index = indexService.index().getName();
for (Integer shardId : indexService.shardIds()) {
logger.debug("[{}][{}] removing shard (disabled block persistence)", index, shardId);
try {
indexService.removeShard(shardId, "removing shard (disabled block persistence)");
} catch (Throwable e) {
logger.warn("[{}] failed to remove shard (disabled block persistence)", e, index);
}
}
removeIndex(index, "cleaning index (disabled block persistence)");
}
return;
}
cleanFailedShards(event);
applyDeletedIndices(event);
applyNewIndices(event);
applyMappings(event);
applyAliases(event);
applyNewOrUpdatedShards(event);
applyDeletedShards(event);
applyCleanedIndices(event);
applySettings(event);
}
}
private void applyCleanedIndices(final ClusterChangedEvent event) {
// handle closed indices, since they are not allocated on a node once they are closed
// so applyDeletedIndices might not take them into account
for (IndexService indexService : indicesService) {
String index = indexService.index().getName();
IndexMetaData indexMetaData = event.state().metaData().index(index);
if (indexMetaData != null && indexMetaData.state() == IndexMetaData.State.CLOSE) {
for (Integer shardId : indexService.shardIds()) {
logger.debug("[{}][{}] removing shard (index is closed)", index, shardId);
try {
indexService.removeShard(shardId, "removing shard (index is closed)");
} catch (Throwable e) {
logger.warn("[{}] failed to remove shard (index is closed)", e, index);
}
}
}
}
for (IndexService indexService : indicesService) {
String index = indexService.index().getName();
if (indexService.shardIds().isEmpty()) {
if (logger.isDebugEnabled()) {
logger.debug("[{}] cleaning index (no shards allocated)", index);
}
// clean the index
removeIndex(index, "removing index (no shards allocated)");
}
}
}
private void applyDeletedIndices(final ClusterChangedEvent event) {
final ClusterState previousState = event.previousState();
final String localNodeId = event.state().nodes().localNodeId();
assert localNodeId != null;
for (IndexService indexService : indicesService) {
IndexMetaData indexMetaData = event.state().metaData().index(indexService.index().name());
if (indexMetaData != null) {
if (!indexMetaData.isSameUUID(indexService.indexUUID())) {
logger.debug("[{}] mismatch on index UUIDs between cluster state and local state, cleaning the index so it will be recreated", indexMetaData.index());
deleteIndex(indexMetaData.index(), "mismatch on index UUIDs between cluster state and local state, cleaning the index so it will be recreated");
}
}
}
for (String index : event.indicesDeleted()) {
if (logger.isDebugEnabled()) {
logger.debug("[{}] cleaning index, no longer part of the metadata", index);
}
final Settings indexSettings;
final IndexService idxService = indicesService.indexService(index);
if (idxService != null) {
indexSettings = idxService.getIndexSettings();
deleteIndex(index, "index no longer part of the metadata");
} else {
final IndexMetaData metaData = previousState.metaData().index(index);
assert metaData != null;
indexSettings = metaData.settings();
indicesService.deleteClosedIndex("closed index no longer part of the metadata", metaData, event.state());
}
try {
nodeIndexDeletedAction.nodeIndexDeleted(event.state(), index, indexSettings, localNodeId);
} catch (Throwable e) {
logger.debug("failed to send to master index {} deleted event", e, index);
}
}
}
private void applyDeletedShards(final ClusterChangedEvent event) {
RoutingNodes.RoutingNodeIterator routingNode = event.state().readOnlyRoutingNodes().routingNodeIter(event.state().nodes().localNodeId());
if (routingNode == null) {
return;
}
IntOpenHashSet newShardIds = new IntOpenHashSet();
for (IndexService indexService : indicesService) {
String index = indexService.index().name();
IndexMetaData indexMetaData = event.state().metaData().index(index);
if (indexMetaData == null) {
continue;
}
// now, go over and delete shards that needs to get deleted
newShardIds.clear();
for (MutableShardRouting shard : routingNode) {
if (shard.index().equals(index)) {
newShardIds.add(shard.id());
}
}
for (Integer existingShardId : indexService.shardIds()) {
if (!newShardIds.contains(existingShardId)) {
if (indexMetaData.state() == IndexMetaData.State.CLOSE) {
if (logger.isDebugEnabled()) {
logger.debug("[{}][{}] removing shard (index is closed)", index, existingShardId);
}
indexService.removeShard(existingShardId, "removing shard (index is closed)");
} else {
// we can just remove the shard, without cleaning it locally, since we will clean it
// when all shards are allocated in the IndicesStore
if (logger.isDebugEnabled()) {
logger.debug("[{}][{}] removing shard (not allocated)", index, existingShardId);
}
indexService.removeShard(existingShardId, "removing shard (not allocated)");
}
}
}
}
}
private void applyNewIndices(final ClusterChangedEvent event) {
// we only create indices for shards that are allocated
RoutingNodes.RoutingNodeIterator routingNode = event.state().readOnlyRoutingNodes().routingNodeIter(event.state().nodes().localNodeId());
if (routingNode == null) {
return;
}
for (MutableShardRouting shard : routingNode) {
if (!indicesService.hasIndex(shard.index())) {
final IndexMetaData indexMetaData = event.state().metaData().index(shard.index());
if (logger.isDebugEnabled()) {
logger.debug("[{}] creating index", indexMetaData.index());
}
try {
indicesService.createIndex(indexMetaData.index(), indexMetaData.settings(), event.state().nodes().localNode().id());
} catch (Exception e) {
logger.warn("[{}] failed to create index", e, indexMetaData.index());
}
}
}
}
private void applySettings(ClusterChangedEvent event) {
if (!event.metaDataChanged()) {
return;
}
for (IndexMetaData indexMetaData : event.state().metaData()) {
if (!indicesService.hasIndex(indexMetaData.index())) {
// we only create / update here
continue;
}
// if the index meta data didn't change, no need check for refreshed settings
if (!event.indexMetaDataChanged(indexMetaData)) {
continue;
}
String index = indexMetaData.index();
IndexService indexService = indicesService.indexService(index);
if (indexService == null) {
// already deleted on us, ignore it
continue;
}
IndexSettingsService indexSettingsService = indexService.injector().getInstance(IndexSettingsService.class);
indexSettingsService.refreshSettings(indexMetaData.settings());
}
}
private void applyMappings(ClusterChangedEvent event) {
// go over and update mappings
for (IndexMetaData indexMetaData : event.state().metaData()) {
if (!indicesService.hasIndex(indexMetaData.index())) {
// we only create / update here
continue;
}
List<String> typesToRefresh = Lists.newArrayList();
String index = indexMetaData.index();
IndexService indexService = indicesService.indexService(index);
if (indexService == null) {
// got deleted on us, ignore (closing the node)
return;
}
MapperService mapperService = indexService.mapperService();
// first, go over and update the _default_ mapping (if exists)
if (indexMetaData.mappings().containsKey(MapperService.DEFAULT_MAPPING)) {
boolean requireRefresh = processMapping(index, mapperService, MapperService.DEFAULT_MAPPING, indexMetaData.mapping(MapperService.DEFAULT_MAPPING).source());
if (requireRefresh) {
typesToRefresh.add(MapperService.DEFAULT_MAPPING);
}
}
// go over and add the relevant mappings (or update them)
for (ObjectCursor<MappingMetaData> cursor : indexMetaData.mappings().values()) {
MappingMetaData mappingMd = cursor.value;
String mappingType = mappingMd.type();
CompressedString mappingSource = mappingMd.source();
if (mappingType.equals(MapperService.DEFAULT_MAPPING)) { // we processed _default_ first
continue;
}
boolean requireRefresh = processMapping(index, mapperService, mappingType, mappingSource);
if (requireRefresh) {
typesToRefresh.add(mappingType);
}
}
if (!typesToRefresh.isEmpty() && sendRefreshMapping) {
nodeMappingRefreshAction.nodeMappingRefresh(event.state(),
new NodeMappingRefreshAction.NodeMappingRefreshRequest(index, indexMetaData.uuid(),
typesToRefresh.toArray(new String[typesToRefresh.size()]), event.state().nodes().localNodeId())
);
}
// go over and remove mappings
for (DocumentMapper documentMapper : mapperService.docMappers(true)) {
if (seenMappings.containsKey(new Tuple<>(index, documentMapper.type())) && !indexMetaData.mappings().containsKey(documentMapper.type())) {
// we have it in our mappings, but not in the metadata, and we have seen it in the cluster state, remove it
mapperService.remove(documentMapper.type());
seenMappings.remove(new Tuple<>(index, documentMapper.type()));
}
}
}
}
private boolean processMapping(String index, MapperService mapperService, String mappingType, CompressedString mappingSource) {
if (!seenMappings.containsKey(new Tuple<>(index, mappingType))) {
seenMappings.put(new Tuple<>(index, mappingType), true);
}
// refresh mapping can happen for 2 reasons. The first is less urgent, and happens when the mapping on this
// node is ahead of what there is in the cluster state (yet an update-mapping has been sent to it already,
// it just hasn't been processed yet and published). Eventually, the mappings will converge, and the refresh
// mapping sent is more of a safe keeping (assuming the update mapping failed to reach the master, ...)
// the second case is where the parsing/merging of the mapping from the metadata doesn't result in the same
// mapping, in this case, we send to the master to refresh its own version of the mappings (to conform with the
// merge version of it, which it does when refreshing the mappings), and warn log it.
boolean requiresRefresh = false;
try {
if (!mapperService.hasMapping(mappingType)) {
if (logger.isDebugEnabled() && mappingSource.compressed().length < 512) {
logger.debug("[{}] adding mapping [{}], source [{}]", index, mappingType, mappingSource.string());
} else if (logger.isTraceEnabled()) {
logger.trace("[{}] adding mapping [{}], source [{}]", index, mappingType, mappingSource.string());
} else {
logger.debug("[{}] adding mapping [{}] (source suppressed due to length, use TRACE level if needed)", index, mappingType);
}
// we don't apply default, since it has been applied when the mappings were parsed initially
mapperService.merge(mappingType, mappingSource, false);
if (!mapperService.documentMapper(mappingType).mappingSource().equals(mappingSource)) {
logger.debug("[{}] parsed mapping [{}], and got different sources\noriginal:\n{}\nparsed:\n{}", index, mappingType, mappingSource, mapperService.documentMapper(mappingType).mappingSource());
requiresRefresh = true;
}
} else {
DocumentMapper existingMapper = mapperService.documentMapper(mappingType);
if (!mappingSource.equals(existingMapper.mappingSource())) {
// mapping changed, update it
if (logger.isDebugEnabled() && mappingSource.compressed().length < 512) {
logger.debug("[{}] updating mapping [{}], source [{}]", index, mappingType, mappingSource.string());
} else if (logger.isTraceEnabled()) {
logger.trace("[{}] updating mapping [{}], source [{}]", index, mappingType, mappingSource.string());
} else {
logger.debug("[{}] updating mapping [{}] (source suppressed due to length, use TRACE level if needed)", index, mappingType);
}
// we don't apply default, since it has been applied when the mappings were parsed initially
mapperService.merge(mappingType, mappingSource, false);
if (!mapperService.documentMapper(mappingType).mappingSource().equals(mappingSource)) {
requiresRefresh = true;
logger.debug("[{}] parsed mapping [{}], and got different sources\noriginal:\n{}\nparsed:\n{}", index, mappingType, mappingSource, mapperService.documentMapper(mappingType).mappingSource());
}
}
}
} catch (Throwable e) {
logger.warn("[{}] failed to add mapping [{}], source [{}]", e, index, mappingType, mappingSource);
}
return requiresRefresh;
}
private boolean aliasesChanged(ClusterChangedEvent event) {
return !event.state().metaData().aliases().equals(event.previousState().metaData().aliases()) ||
!event.state().routingTable().equals(event.previousState().routingTable());
}
private void applyAliases(ClusterChangedEvent event) {
// check if aliases changed
if (aliasesChanged(event)) {
// go over and update aliases
for (IndexMetaData indexMetaData : event.state().metaData()) {
String index = indexMetaData.index();
IndexService indexService = indicesService.indexService(index);
if (indexService == null) {
// we only create / update here
continue;
}
IndexAliasesService indexAliasesService = indexService.aliasesService();
processAliases(index, indexMetaData.aliases().values(), indexAliasesService);
// go over and remove aliases
for (IndexAlias indexAlias : indexAliasesService) {
if (!indexMetaData.aliases().containsKey(indexAlias.alias())) {
// we have it in our aliases, but not in the metadata, remove it
indexAliasesService.remove(indexAlias.alias());
}
}
}
}
}
private void processAliases(String index, ObjectContainer<AliasMetaData> aliases, IndexAliasesService indexAliasesService) {
HashMap<String, IndexAlias> newAliases = newHashMap();
for (ObjectCursor<AliasMetaData> cursor : aliases) {
AliasMetaData aliasMd = cursor.value;
String alias = aliasMd.alias();
CompressedString filter = aliasMd.filter();
try {
if (!indexAliasesService.hasAlias(alias)) {
if (logger.isDebugEnabled()) {
logger.debug("[{}] adding alias [{}], filter [{}]", index, alias, filter);
}
newAliases.put(alias, indexAliasesService.create(alias, filter));
} else {
if ((filter == null && indexAliasesService.alias(alias).filter() != null) ||
(filter != null && !filter.equals(indexAliasesService.alias(alias).filter()))) {
if (logger.isDebugEnabled()) {
logger.debug("[{}] updating alias [{}], filter [{}]", index, alias, filter);
}
newAliases.put(alias, indexAliasesService.create(alias, filter));
}
}
} catch (Throwable e) {
logger.warn("[{}] failed to add alias [{}], filter [{}]", e, index, alias, filter);
}
}
indexAliasesService.addAll(newAliases);
}
private void applyNewOrUpdatedShards(final ClusterChangedEvent event) throws ElasticsearchException {
if (!indicesService.changesAllowed()) {
return;
}
RoutingTable routingTable = event.state().routingTable();
RoutingNodes.RoutingNodeIterator routingNode = event.state().readOnlyRoutingNodes().routingNodeIter(event.state().nodes().localNodeId());
if (routingNode == null) {
failedShards.clear();
return;
}
DiscoveryNodes nodes = event.state().nodes();
for (final ShardRouting shardRouting : routingNode) {
final IndexService indexService = indicesService.indexService(shardRouting.index());
if (indexService == null) {
// got deleted on us, ignore
continue;
}
final IndexMetaData indexMetaData = event.state().metaData().index(shardRouting.index());
if (indexMetaData == null) {
// the index got deleted on the metadata, we will clean it later in the apply deleted method call
continue;
}
final int shardId = shardRouting.id();
if (!indexService.hasShard(shardId) && shardRouting.started()) {
if (failedShards.containsKey(shardRouting.shardId())) {
if (nodes.masterNode() != null) {
shardStateAction.resendShardFailed(shardRouting, indexMetaData.getUUID(),
"master " + nodes.masterNode() + " marked shard as started, but shard has previous failed. resending shard failure.",
nodes.masterNode()
);
}
} else {
// the master thinks we are started, but we don't have this shard at all, mark it as failed
logger.warn("[{}][{}] master [{}] marked shard as started, but shard has not been created, mark shard as failed", shardRouting.index(), shardId, nodes.masterNode());
failedShards.put(shardRouting.shardId(), new FailedShard(shardRouting.version()));
if (nodes.masterNode() != null) {
shardStateAction.shardFailed(shardRouting, indexMetaData.getUUID(),
"master " + nodes.masterNode() + " marked shard as started, but shard has not been created, mark shard as failed",
nodes.masterNode()
);
}
}
continue;
}
IndexShard indexShard = indexService.shard(shardId);
if (indexShard != null) {
ShardRouting currentRoutingEntry = indexShard.routingEntry();
// if the current and global routing are initializing, but are still not the same, its a different "shard" being allocated
// for example: a shard that recovers from one node and now needs to recover to another node,
// or a replica allocated and then allocating a primary because the primary failed on another node
boolean shardHasBeenRemoved = false;
if (currentRoutingEntry.initializing() && shardRouting.initializing() && !currentRoutingEntry.equals(shardRouting)) {
logger.debug("[{}][{}] removing shard (different instance of it allocated on this node, current [{}], global [{}])", shardRouting.index(), shardRouting.id(), currentRoutingEntry, shardRouting);
// closing the shard will also cancel any ongoing recovery.
indexService.removeShard(shardRouting.id(), "removing shard (different instance of it allocated on this node)");
shardHasBeenRemoved = true;
} else if (isPeerRecovery(shardRouting)) {
// check if there is an existing recovery going, and if so, and the source node is not the same, cancel the recovery to restart it
RecoveryState recoveryState = recoveryTarget.recoveryState(indexShard);
if (recoveryState != null && recoveryState.getStage() != RecoveryState.Stage.DONE) {
// we have an ongoing recovery, find the source based on current routing and compare them
DiscoveryNode sourceNode = findSourceNodeForPeerRecovery(routingTable, nodes, shardRouting);
if (!recoveryState.getSourceNode().equals(sourceNode)) {
logger.debug("[{}][{}] removing shard (recovery source changed), current [{}], global [{}])", shardRouting.index(), shardRouting.id(), currentRoutingEntry, shardRouting);
// closing the shard will also cancel any ongoing recovery.
indexService.removeShard(shardRouting.id(), "removing shard (recovery source node changed)");
shardHasBeenRemoved = true;
}
}
}
if (shardHasBeenRemoved == false && (shardRouting.equals(indexShard.routingEntry()) == false || shardRouting.version() > indexShard.routingEntry().version())) {
if (shardRouting.primary() && indexShard.routingEntry().primary() == false && shardRouting.initializing() && indexShard.allowsPrimaryPromotion() == false) {
logger.debug("{} reinitialize shard on primary promotion", indexShard.shardId());
indexService.removeShard(shardId, "promoted to primary");
} else {
// if we happen to remove the shardRouting by id above we don't need to jump in here!
indexShard.updateRoutingEntry(shardRouting, event.state().blocks().disableStatePersistence() == false);
indexService.shardInjectorSafe(shardId).getInstance(IndexShardGatewayService.class).routingStateChanged();
}
}
}
if (shardRouting.initializing()) {
applyInitializingShard(event.state(),indexMetaData, shardRouting);
}
}
}
private void cleanFailedShards(final ClusterChangedEvent event) {
RoutingTable routingTable = event.state().routingTable();
RoutingNodes.RoutingNodeIterator routingNode = event.state().readOnlyRoutingNodes().routingNodeIter(event.state().nodes().localNodeId());
if (routingNode == null) {
failedShards.clear();
return;
}
DiscoveryNodes nodes = event.state().nodes();
long now = System.currentTimeMillis();
String localNodeId = nodes.localNodeId();
Iterator<Map.Entry<ShardId, FailedShard>> iterator = failedShards.entrySet().iterator();
shards:
while (iterator.hasNext()) {
Map.Entry<ShardId, FailedShard> entry = iterator.next();
FailedShard failedShard = entry.getValue();
IndexRoutingTable indexRoutingTable = routingTable.index(entry.getKey().getIndex());
if (indexRoutingTable != null) {
IndexShardRoutingTable shardRoutingTable = indexRoutingTable.shard(entry.getKey().id());
if (shardRoutingTable != null) {
for (ShardRouting shardRouting : shardRoutingTable.assignedShards()) {
if (localNodeId.equals(shardRouting.currentNodeId())) {
// we have a timeout here just to make sure we don't have dangled failed shards for some reason
// its just another safely layer
if (shardRouting.version() == failedShard.version && ((now - failedShard.timestamp) < TimeValue.timeValueMinutes(60).millis())) {
// It's the same failed shard - keep it if it hasn't timed out
continue shards;
} else {
// Different version or expired, remove it
break;
}
}
}
}
}
iterator.remove();
}
}
private void applyInitializingShard(final ClusterState state, final IndexMetaData indexMetaData, final ShardRouting shardRouting) throws ElasticsearchException {
final IndexService indexService = indicesService.indexService(shardRouting.index());
if (indexService == null) {
// got deleted on us, ignore
return;
}
final RoutingTable routingTable = state.routingTable();
final DiscoveryNodes nodes = state.getNodes();
final int shardId = shardRouting.id();
if (indexService.hasShard(shardId)) {
IndexShard indexShard = indexService.shardSafe(shardId);
if (indexShard.state() == IndexShardState.STARTED || indexShard.state() == IndexShardState.POST_RECOVERY) {
// the master thinks we are initializing, but we are already started or on POST_RECOVERY and waiting
// for master to confirm a shard started message (either master failover, or a cluster event before
// we managed to tell the master we started), mark us as started
if (logger.isTraceEnabled()) {
logger.trace("{} master marked shard as initializing, but shard has state [{}], resending shard started to {}",
indexShard.shardId(), indexShard.state(), nodes.masterNode());
}
if (nodes.masterNode() != null) {
shardStateAction.shardStarted(shardRouting, indexMetaData.getUUID(),
"master " + nodes.masterNode() + " marked shard as initializing, but shard state is [" + indexShard.state() + "], mark shard as started",
nodes.masterNode());
}
return;
} else {
if (indexShard.ignoreRecoveryAttempt()) {
logger.trace("ignoring recovery instruction for an existing shard {} (shard state: [{}])", indexShard.shardId(), indexShard.state());
return;
}
}
}
// if we're in peer recovery, try to find out the source node now so in case it fails, we will not create the index shard
DiscoveryNode sourceNode = null;
if (isPeerRecovery(shardRouting)) {
sourceNode = findSourceNodeForPeerRecovery(routingTable, nodes, shardRouting);
if (sourceNode == null) {
logger.trace("ignoring initializing shard {} - no source node can be found.", shardRouting.shardId());
return;
}
}
// if there is no shard, create it
if (!indexService.hasShard(shardId)) {
if (failedShards.containsKey(shardRouting.shardId())) {
if (nodes.masterNode() != null) {
shardStateAction.resendShardFailed(shardRouting, indexMetaData.getUUID(),
"master " + nodes.masterNode() + " marked shard as initializing, but shard is marked as failed, resend shard failure",
nodes.masterNode());
}
return;
}
try {
if (logger.isDebugEnabled()) {
logger.debug("[{}][{}] creating shard", shardRouting.index(), shardId);
}
IndexShard indexShard = indexService.createShard(shardId, shardRouting.primary());
indexShard.updateRoutingEntry(shardRouting, state.blocks().disableStatePersistence() == false);
indexShard.addFailedEngineListener(failedEngineHandler);
} catch (IndexShardAlreadyExistsException e) {
// ignore this, the method call can happen several times
} catch (Throwable e) {
logger.warn("[{}][{}] failed to create shard", e, shardRouting.index(), shardRouting.id());
try {
indexService.removeShard(shardId, "failed to create [" + ExceptionsHelper.detailedMessage(e) + "]");
} catch (IndexShardMissingException e1) {
// ignore
} catch (Throwable e1) {
logger.warn("[{}][{}] failed to remove shard after failed creation", e1, shardRouting.index(), shardRouting.id());
}
failedShards.put(shardRouting.shardId(), new FailedShard(shardRouting.version()));
if (nodes.masterNode() != null) {
shardStateAction.shardFailed(shardRouting, indexMetaData.getUUID(), "Failed to create shard, message [" + detailedMessage(e) + "]",
nodes.masterNode()
);
} else {
logger.debug("can't send shard failed for {} as there is no current master", shardRouting.shardId());
}
return;
}
}
final IndexShard indexShard = indexService.shardSafe(shardId);
if (indexShard.ignoreRecoveryAttempt()) {
// we are already recovering (we can get to this state since the cluster event can happen several
// times while we recover)
logger.trace("ignoring recovery instruction for shard {} (shard state: [{}])", indexShard.shardId(), indexShard.state());
return;
}
if (isPeerRecovery(shardRouting)) {
try {
assert sourceNode != null : "peer recovery started but sourceNode is null";
// we don't mark this one as relocated at the end.
// For primaries: requests in any case are routed to both when its relocating and that way we handle
// the edge case where its mark as relocated, and we might need to roll it back...
// For replicas: we are recovering a backup from a primary
RecoveryState.Type type = shardRouting.primary() ? RecoveryState.Type.RELOCATION : RecoveryState.Type.REPLICA;
recoveryTarget.startRecovery(indexShard, type, sourceNode, new PeerRecoveryListener(shardRouting, indexService, indexMetaData));
} catch (Throwable e) {
indexShard.failShard("corrupted preexisting index", e);
handleRecoveryFailure(indexService, indexMetaData, shardRouting, true, e);
}
} else {
final IndexShardRoutingTable indexShardRouting = routingTable.index(shardRouting.index()).shard(shardRouting.id());
// we are the first primary, recover from the gateway
// if its post api allocation, the index should exists
boolean indexShouldExists = indexShardRouting.primaryAllocatedPostApi();
IndexShardGatewayService shardGatewayService = indexService.shardInjectorSafe(shardId).getInstance(IndexShardGatewayService.class);
shardGatewayService.recover(indexShouldExists, new IndexShardGatewayService.RecoveryListener() {
@Override
public void onRecoveryDone() {
shardStateAction.shardStarted(shardRouting, indexMetaData.getUUID(), "after recovery from gateway");
}
@Override
public void onIgnoreRecovery(String reason) {
}
@Override
public void onRecoveryFailed(IndexShardGatewayRecoveryException e) {
handleRecoveryFailure(indexService, indexMetaData, shardRouting, true, e);
}
});
}
}
/**
* Finds the routing source node for peer recovery, return null if its not found. Note, this method expects the shard
* routing to *require* peer recovery, use {@link #isPeerRecovery(org.elasticsearch.cluster.routing.ShardRouting)} to
* check if its needed or not.
*/
private DiscoveryNode findSourceNodeForPeerRecovery(RoutingTable routingTable, DiscoveryNodes nodes, ShardRouting shardRouting) {
DiscoveryNode sourceNode = null;
if (!shardRouting.primary()) {
IndexShardRoutingTable shardRoutingTable = routingTable.index(shardRouting.index()).shard(shardRouting.id());
for (ShardRouting entry : shardRoutingTable) {
if (entry.primary() && entry.started()) {
// only recover from started primary, if we can't find one, we will do it next round
sourceNode = nodes.get(entry.currentNodeId());
if (sourceNode == null) {
logger.trace("can't find replica source node because primary shard {} is assigned to an unknown node.", entry);
return null;
}
break;
}
}
if (sourceNode == null) {
logger.trace("can't find replica source node for {} because a primary shard can not be found.", shardRouting.shardId());
}
} else if (shardRouting.relocatingNodeId() != null) {
sourceNode = nodes.get(shardRouting.relocatingNodeId());
if (sourceNode == null) {
logger.trace("can't find relocation source node for shard {} because it is assigned to an unknown node [{}].", shardRouting.shardId(), shardRouting.relocatingNodeId());
}
} else {
throw new ElasticsearchIllegalStateException("trying to find source node for peer recovery when routing state means no peer recovery: " + shardRouting);
}
return sourceNode;
}
private boolean isPeerRecovery(ShardRouting shardRouting) {
return !shardRouting.primary() || shardRouting.relocatingNodeId() != null;
}
private class PeerRecoveryListener implements RecoveryTarget.RecoveryListener {
private final ShardRouting shardRouting;
private final IndexService indexService;
private final IndexMetaData indexMetaData;
private PeerRecoveryListener(ShardRouting shardRouting, IndexService indexService, IndexMetaData indexMetaData) {
this.shardRouting = shardRouting;
this.indexService = indexService;
this.indexMetaData = indexMetaData;
}
@Override
public void onRecoveryDone(RecoveryState state) {
shardStateAction.shardStarted(shardRouting, indexMetaData.getUUID(), "after recovery (replica) from node [" + state.getSourceNode() + "]");
}
@Override
public void onRecoveryFailure(RecoveryState state, RecoveryFailedException e, boolean sendShardFailure) {
handleRecoveryFailure(indexService, indexMetaData, shardRouting, sendShardFailure, e);
}
}
private void handleRecoveryFailure(IndexService indexService, IndexMetaData indexMetaData, ShardRouting shardRouting, boolean sendShardFailure, Throwable failure) {
synchronized (mutex) {
if (indexService.hasShard(shardRouting.shardId().id())) {
try {
logger.debug("[{}][{}] removing shard on failed recovery [{}]", shardRouting.index(), shardRouting.shardId().id(), failure.getMessage());
indexService.removeShard(shardRouting.shardId().id(), "recovery failure [" + ExceptionsHelper.detailedMessage(failure) + "]");
} catch (IndexShardMissingException e) {
// the node got closed on us, ignore it
} catch (Throwable e1) {
logger.warn("[{}][{}] failed to delete shard after recovery failure", e1, indexService.index().name(), shardRouting.shardId().id());
}
}
if (sendShardFailure) {
logger.warn("[{}][{}] sending failed shard after recovery failure", failure, indexService.index().name(), shardRouting.shardId().id());
try {
failedShards.put(shardRouting.shardId(), new FailedShard(shardRouting.version()));
shardStateAction.shardFailed(shardRouting, indexMetaData.getUUID(), "Failed to start shard, message [" + detailedMessage(failure) + "]");
} catch (Throwable e1) {
logger.warn("[{}][{}] failed to mark shard as failed after a failed start", e1, indexService.index().name(), shardRouting.id());
}
}
}
}
private void removeIndex(String index, String reason) {
try {
indicesService.removeIndex(index, reason);
} catch (Throwable e) {
logger.warn("failed to clean index ({})", e, reason);
}
clearSeenMappings(index);
}
private void clearSeenMappings(String index) {
// clear seen mappings as well
for (Tuple<String, String> tuple : seenMappings.keySet()) {
if (tuple.v1().equals(index)) {
seenMappings.remove(tuple);
}
}
}
private void deleteIndex(String index, String reason) {
try {
indicesService.deleteIndex(index, reason);
} catch (Throwable e) {
logger.warn("failed to delete index ({})", e, reason);
}
// clear seen mappings as well
clearSeenMappings(index);
}
private class FailedEngineHandler implements Engine.FailedEngineListener {
@Override
public void onFailedEngine(final ShardId shardId, final String reason, final @Nullable Throwable failure) {
ShardRouting shardRouting = null;
final IndexService indexService = indicesService.indexService(shardId.index().name());
if (indexService != null) {
IndexShard indexShard = indexService.shard(shardId.id());
if (indexShard != null) {
shardRouting = indexShard.routingEntry();
}
}
if (shardRouting == null) {
logger.warn("[{}][{}] engine failed, but can't find index shard. failure reason: [{}]",
shardId.index().name(), shardId.id(), reason);
return;
}
final ShardRouting fShardRouting = shardRouting;
final String indexUUID = indexService.indexUUID(); // we know indexService is not null here.
final String failureMessage = "engine failure, message [" + reason + "]" +
(failure == null ? "" : "[" + detailedMessage(failure) + "]");
threadPool.generic().execute(new Runnable() {
@Override
public void run() {
synchronized (mutex) {
if (indexService.hasShard(shardId.id())) {
try {
indexService.removeShard(shardId.id(), failureMessage);
} catch (IndexShardMissingException e) {
// the node got closed on us, ignore it
} catch (Throwable e1) {
logger.warn("[{}][{}] failed to delete shard after failed engine ([{}])", e1, indexService.index().name(), shardId.id(), reason);
}
}
try {
failedShards.put(fShardRouting.shardId(), new FailedShard(fShardRouting.version()));
shardStateAction.shardFailed(fShardRouting, indexUUID, failureMessage);
} catch (Throwable e1) {
logger.warn("[{}][{}] failed to mark shard as failed after a failed engine ([{}])", e1, indexService.index().name(), shardId.id(), reason);
}
}
}
});
}
}
}
|
/*
* Copyright (C), 1987-2099, Winter All Rights Reserved.
*/
package com.winterframework.context.weaving;
import com.winterframework.beans.factory.HierarchicalBeanFactory;
import com.winterframework.beans.factory.ListableBeanFactory;
import com.winterframework.context.ApplicationEventPublisher;
import com.winterframework.context.MessageSource;
import com.winterframework.core.env.EnvironmentCapable;
import com.winterframework.core.io.ResourcePatternResolver;
/**
* @author huangwh@paraview.cn
* @since 2021/07/19
*/
public interface ApplicationContext
extends
EnvironmentCapable,
ListableBeanFactory,
HierarchicalBeanFactory,
MessageSource,
ApplicationEventPublisher,
ResourcePatternResolver {
}
|
package de.andipopp.poodle.views.vote;
import java.time.Duration;
import java.time.Instant;
import org.jsoup.Jsoup;
import com.vaadin.flow.component.Component;
import com.vaadin.flow.component.Html;
import com.vaadin.flow.component.UI;
import com.vaadin.flow.component.avatar.Avatar;
import com.vaadin.flow.component.avatar.AvatarVariant;
import com.vaadin.flow.component.button.Button;
import com.vaadin.flow.component.button.ButtonVariant;
import com.vaadin.flow.component.contextmenu.ContextMenu;
import com.vaadin.flow.component.contextmenu.MenuItem;
import com.vaadin.flow.component.html.H6;
import com.vaadin.flow.component.icon.Icon;
import com.vaadin.flow.component.icon.VaadinIcon;
import com.vaadin.flow.component.orderedlayout.HorizontalLayout;
import com.vaadin.flow.component.orderedlayout.VerticalLayout;
import com.vaadin.flow.router.HasDynamicTitle;
import com.vaadin.flow.router.Route;
import com.vaadin.flow.server.auth.AnonymousAllowed;
import de.andipopp.poodle.data.entity.polls.AbstractPoll;
import de.andipopp.poodle.data.entity.polls.DatePoll;
import de.andipopp.poodle.data.entity.polls.SimplePoll;
import de.andipopp.poodle.data.service.PollService;
import de.andipopp.poodle.data.service.VoteService;
import de.andipopp.poodle.security.AuthenticatedUser;
import de.andipopp.poodle.util.HtmlUtils;
import de.andipopp.poodle.util.JSoupUtils;
import de.andipopp.poodle.util.UUIDUtils;
import de.andipopp.poodle.views.MainLayout;
import de.andipopp.poodle.views.PollView;
import de.andipopp.poodle.views.components.LineAwesomeMenuIcon;
import de.andipopp.poodle.views.vote.date.DateOptionsVoteListView;
import de.andipopp.poodle.views.vote.simple.SimpleOptionsVoteListView;
@Route(value = "poll", layout = MainLayout.class)
@AnonymousAllowed
/**
* View to participate (i.e. mostly vote) in a specific poll.
* @author Andi Popp
*
*/
public class PollVoteView extends PollView implements HasDynamicTitle {
private VoteService voteService;
/* =====================
* = Layout Components =
* ===================== */
private VerticalLayout content;
private VerticalLayout pollContent;
private HorizontalLayout header = new HorizontalLayout();
private H6 subtitle = new H6();
private VerticalLayout info = new VerticalLayout();
ViewToggleState state = ViewToggleState.LIST;
private enum ViewToggleState {
LIST, TABLE
}
OptionsVoteListView<?, ?> listView;
public PollVoteView(AuthenticatedUser authenticatedUser, PollService pollService, VoteService voteService) {
super(authenticatedUser, pollService);
//hookup the vote service
this.voteService = voteService;
//set the toggle state to default
state = ViewToggleState.LIST; //TODO decide default on Mobile or Desktop Browser
this.setDefaultHorizontalComponentAlignment(Alignment.START);
//we use content as an intermediary, so we remove padding from this
this.setPadding(false);
//add a not found as default content
this.content = new VerticalLayout();
this.content.add(notFound());
this.add(content);
}
@Override
protected void loadPoll(AbstractPoll<?,?> poll) {
//load the poll itself
super.loadPoll(poll);
//add the poll specific content
this.pollContent = new VerticalLayout();
this.pollContent.setPadding(false);
this.pollContent.add(metaInfBlock());
this.pollContent.setSpacing(false);
this.pollContent.setDefaultHorizontalComponentAlignment(Alignment.CENTER);
if (poll instanceof DatePoll) {
listView = new DateOptionsVoteListView((DatePoll) poll, getCurrentUser(), voteService, pollService);
//TODO also build table view
} else if (poll instanceof SimplePoll) {
listView = new SimpleOptionsVoteListView((SimplePoll) poll, getCurrentUser(), voteService, pollService);
//TODO also build table view
}
listView.guessVote(currentUser);
listView.addListener(OptionsVoteListView.ViewChangeEvent.class, e -> configureTopRightContextMenu());
if (state == ViewToggleState.LIST) this.pollContent.add(listView);
//now that we know the view toggle state, we can build the top right context menu
configureTopRightContextMenu();
//strip content from all its components (especially the "not found")
this.content.removeAll();
HorizontalLayout pollContentWrapper = new HorizontalLayout(pollContent);
pollContentWrapper.setPadding(false);
pollContentWrapper.setMinWidth("50%");
VerticalLayout horizontalAlignmentWrapper = new VerticalLayout();
horizontalAlignmentWrapper.setSizeFull();
horizontalAlignmentWrapper.setDefaultHorizontalComponentAlignment(Alignment.CENTER);
horizontalAlignmentWrapper.add(pollContentWrapper);
horizontalAlignmentWrapper.setPadding(false);
this.content.add(horizontalAlignmentWrapper);
}
@Override
public String getPageTitle() {
String title = "Poll not found";
if (poll != null && poll.getTitle() != null) title = poll.getTitle();
return title;
}
/* ===============
* = Sub-Layouts =
* =============== */
private Component metaInfBlock() {
VerticalLayout metaInfBlock = new VerticalLayout();
metaInfBlock.setPadding(false);
metaInfBlock.setDefaultHorizontalComponentAlignment(Alignment.START);
metaInfBlock.add(configureHeader());
metaInfBlock.add(configureInfo());
metaInfBlock.add(HtmlUtils.pollShareScript(getPoll()));
return metaInfBlock;
}
private Component configureHeader() {
header.removeAll();
header.setWidthFull();
header.setDefaultVerticalComponentAlignment(Alignment.START);
Avatar avatar = poll.getAvatar();
avatar.addThemeVariants(AvatarVariant.LUMO_SMALL);
avatar.getStyle().set("border", "1px solid black") ;
this.content.add(avatar);
HorizontalLayout avatarAndTitleWrapper = new HorizontalLayout(avatar, configureSubtitle());
avatarAndTitleWrapper.setDefaultVerticalComponentAlignment(Alignment.CENTER);
avatarAndTitleWrapper.setWidthFull();
header.add(avatarAndTitleWrapper);
//build the menu button:
topRightMenu = new Button();
topRightMenu.addClassName("primary-text");
topRightMenu.setIcon(new Icon(VaadinIcon.MENU));
topRightMenu.addThemeVariants(ButtonVariant.LUMO_ICON);
HorizontalLayout headerMenuButtonWrapper = new HorizontalLayout(topRightMenu);
headerMenuButtonWrapper.setHeightFull();
headerMenuButtonWrapper.setDefaultVerticalComponentAlignment(Alignment.START);
header.add(headerMenuButtonWrapper);
return header;
}
private Component configureSubtitle() {
String text = "created ";
Duration duration = Duration.between(poll.getCreateDate(), Instant.now());
text += duration.toDays() +" day(s) ago ";
if (poll.getOwner() != null && poll.getOwner().getDisplayName() != null) text += "by " + poll.getOwner().getDisplayName();
text += " and retained until "+poll.getDeleteDate();
subtitle.setText(text);
subtitle.getStyle().set("margin-top", "0ex");
return subtitle;
}
private Component configureInfo() {
info.removeAll();
if (poll.getDescription() != null && !poll.getDescription().isBlank()) {
HorizontalLayout description = new HorizontalInfoContainer(true);
description.add(new Html("<p>" + Jsoup.clean(poll.getDescription(), JSoupUtils.BASIC) + "</p>"));
description.setJustifyContentMode(JustifyContentMode.BETWEEN);
info.add(description);
}
if (poll instanceof DatePoll) {
DatePoll datePoll = (DatePoll) poll;
if (datePoll.getLocation() != null && !datePoll.getLocation().isBlank()) {
HorizontalLayout location = new HorizontalInfoContainer(true);
location.add(new HorizontalInfoContainer(false, new Icon(VaadinIcon.MAP_MARKER), new Html("<span>"+Jsoup.clean(datePoll.getLocation(), JSoupUtils.BASIC)+"</span>")));
location.setJustifyContentMode(JustifyContentMode.BETWEEN);
info.add(location);
}
};
info.setSpacing(false);
info.setPadding(false);
return info;
}
/* ==================================
* = Members to configure poll menu =
* ================================== */
/**
* The button to open the poll menu
*/
private Button topRightMenu;
/**
* The actual menu
*/
private ContextMenu topRightContextMenu;
/**
* Remember the item to switch to table view to toggle visibility
*/
private MenuItem switchToTableView;
/**
* Remember the item to switch to list view to toggle visibility
*/
private MenuItem switchToListView;
/**
* Remember the closing item to switch labels
*/
private MenuItem close;
private void configureTopRightContextMenu() {
if (topRightContextMenu != null) topRightContextMenu.setTarget(null);
topRightContextMenu = new ContextMenu();
topRightContextMenu.removeAll();
topRightContextMenu.addItem(new Html("<span onclick=\""
+ "share_" + UUIDUtils.uuidToBase64url(poll.getId()) + "()"
+ "\"><span class=\"las la-share menu-pretext-icon\"></span> Share"
+ "</span>"));
if (currentUser != null && currentUser.equals(poll.getOwner())) {
MenuItem edit = topRightContextMenu.addItem(" Edit", e ->
UI.getCurrent().navigate("edit", getPoll().buildQueryParameters(true))
);
edit.addComponentAsFirst(new LineAwesomeMenuIcon("la-edit"));
if (poll.isClosed()) {
MenuItem reopen = topRightContextMenu.addItem(" Reopen Poll", e -> {
poll.setClosed(false);
listView.buildAll();
configureTopRightContextMenu();
});
reopen.addComponentAsFirst(new LineAwesomeMenuIcon("la-lock-open"));
} else {
String closeLabelOpen = " Select Winners";
String closeLabelClosing = " Exit Winner Select";
close = topRightContextMenu.addItem(closeLabelOpen, e->{
listView.toggleClosingMode();
if (listView.isClosingMode()) close.setText(closeLabelClosing);
else close.setText(closeLabelOpen);
close.addComponentAsFirst(new LineAwesomeMenuIcon("la-award"));
});
close.addComponentAsFirst(new LineAwesomeMenuIcon("la-award"));
}
}
switchToTableView = topRightContextMenu.addItem(" Table View", e -> {});
switchToTableView.addComponentAsFirst(new LineAwesomeMenuIcon("la-table"));
switchToTableView.setVisible(state == ViewToggleState.LIST);
switchToListView = topRightContextMenu.addItem(" List View", e -> {});
switchToListView.addComponentAsFirst(new LineAwesomeMenuIcon("la-list-ul"));
switchToListView.setVisible(state == ViewToggleState.TABLE);
if (listView instanceof DateOptionsVoteListView) {
MenuItem conflictSettings = topRightContextMenu.addItem(" Date Conflicts", e -> ((DateOptionsVoteListView) listView).openIcsPathsDialog());
conflictSettings.addComponentAsFirst(new LineAwesomeMenuIcon("la-calendar-times"));
}
topRightContextMenu.setOpenOnClick(true);
topRightContextMenu.setTarget(topRightMenu);
}
private static class HorizontalInfoContainer extends HorizontalLayout {
/**
*
*/
public HorizontalInfoContainer(boolean fullWidth) {
super();
setAttributes(fullWidth);
}
/**
* @param children
*/
public HorizontalInfoContainer(boolean fullWidth, Component... children) {
super(children);
setAttributes(fullWidth);
}
private void setAttributes(boolean fullWidth) {
this.setPadding(false);
if (fullWidth) this.setWidthFull();
this.setDefaultVerticalComponentAlignment(Alignment.CENTER);
}
}
}
|
// Code generated by lark suite oapi sdk gen
package com.larksuite.oapi.service.sheets.v2.model;
import com.google.gson.annotations.SerializedName;
public class DimensionProperties {
@SerializedName("visible")
private Boolean visible;
@SerializedName("fixedSize")
private Integer fixedSize;
public Boolean getVisible() {
return this.visible;
}
public void setVisible(Boolean visible) {
this.visible = visible;
}
public Integer getFixedSize() {
return this.fixedSize;
}
public void setFixedSize(Integer fixedSize) {
this.fixedSize = fixedSize;
}
}
|
package test;
public class dtoMoment {
}
|
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package com.insightfullogic.java8.examples.chapter1;
import java.util.List;
import java.util.stream.Collectors;
/**
*
* @author richard
*/
public class Chapter1 extends MusicChapter {
public List<String> getNamesOfArtists_Lambda() {
return artists.stream()
.map(artist -> artist.getName())
.collect(Collectors.toList());
}
public List<String> getNamesOfArtists_MethodReference() {
return artists.stream()
.map(Artist::getName)
.collect(Collectors.toList());
}
public List<Artist> artistsLivingInLondon() {
return (List<Artist>) artists.stream()
.filter(
artist -> {
//System.out.println(artists.toString());
return "UK".equals(artist.getNationality());
})
.collect(Collectors.toList());
}
public static void main(String[] args) {
System.out.println(new Chapter1().getNamesOfArtists_Lambda());
//System.out.println(new Chapter1().getNamesOfArtists_MethodReference());
System.out.println(new Chapter1().artistsLivingInLondon());
}
}
|
/*
* This file is part of TechReborn, licensed under the MIT License (MIT).
*
* Copyright (c) 2020 TechReborn
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package techreborn.blockentity.storage.energy.idsu;
import net.minecraft.block.BlockState;
import net.minecraft.entity.player.PlayerEntity;
import net.minecraft.nbt.NbtCompound;
import net.minecraft.util.math.BlockPos;
import org.apache.commons.lang3.StringUtils;
import reborncore.client.screen.BuiltScreenHandlerProvider;
import reborncore.client.screen.builder.BuiltScreenHandler;
import reborncore.client.screen.builder.ScreenHandlerBuilder;
import reborncore.common.powerSystem.RcEnergyTier;
import techreborn.blockentity.storage.energy.EnergyStorageBlockEntity;
import techreborn.config.TechRebornConfig;
import techreborn.init.TRBlockEntities;
import techreborn.init.TRContent;
public class InterdimensionalSUBlockEntity extends EnergyStorageBlockEntity implements BuiltScreenHandlerProvider {
public String ownerUdid;
//This is the energy value that is synced to the client
private long clientEnergy;
public InterdimensionalSUBlockEntity(BlockPos pos, BlockState state) {
super(TRBlockEntities.INTERDIMENSIONAL_SU, pos, state, "IDSU", 2, TRContent.Machine.INTERDIMENSIONAL_SU.block, RcEnergyTier.INSANE, TechRebornConfig.idsuMaxEnergy);
}
@Override
public long getStored() {
if (ownerUdid == null || ownerUdid.isEmpty()) {
return 0;
}
if (world.isClient) {
return clientEnergy;
}
return IDSUManager.getPlayer(world.getServer(), ownerUdid).getEnergy();
}
@Override
public void setStored(long energy) {
if (ownerUdid == null || ownerUdid.isEmpty()) {
return;
}
if (world.isClient) {
clientEnergy = energy;
} else {
IDSUManager.getPlayer(world.getServer(), ownerUdid).setEnergy(energy);
}
}
@Override
public void useEnergy(long extract) {
if (ownerUdid == null || ownerUdid.isEmpty()) {
return;
}
if (world.isClient) {
throw new UnsupportedOperationException("cannot set energy on the client!");
}
long energy = IDSUManager.getPlayer(world.getServer(), ownerUdid).getEnergy();
if (extract > energy) {
extract = energy;
}
setStored(energy - extract);
return;
}
@Override
protected boolean shouldHandleEnergyNBT() {
return false;
}
@Override
public void readNbt(NbtCompound nbttagcompound) {
super.readNbt(nbttagcompound);
this.ownerUdid = nbttagcompound.getString("ownerUdid");
}
@Override
public NbtCompound writeNbt(NbtCompound nbttagcompound) {
super.writeNbt(nbttagcompound);
if (ownerUdid == null || StringUtils.isEmpty(ownerUdid)) {
return nbttagcompound;
}
nbttagcompound.putString("ownerUdid", this.ownerUdid);
return nbttagcompound;
}
@Override
public BuiltScreenHandler createScreenHandler(int syncID, final PlayerEntity player) {
return new ScreenHandlerBuilder("idsu").player(player.getInventory()).inventory().hotbar().armor()
.complete(8, 18).addArmor().addInventory().blockEntity(this).energySlot(0, 62, 45).energySlot(1, 98, 45)
.syncEnergyValue().addInventory().create(this, syncID);
}
}
|
class Test {
void test() {
String block = """<caret>
text""";
}
}
|
/*
* Copyright 2019 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
// Generated by the protocol buffer compiler. DO NOT EDIT!
// source: google/cloud/dialogflow/v2beta1/context.proto
package com.google.cloud.dialogflow.v2beta1;
public interface UpdateContextRequestOrBuilder
extends
// @@protoc_insertion_point(interface_extends:google.cloud.dialogflow.v2beta1.UpdateContextRequest)
com.google.protobuf.MessageOrBuilder {
/**
*
*
* <pre>
* Required. The context to update.
* </pre>
*
* <code>.google.cloud.dialogflow.v2beta1.Context context = 1;</code>
*
* @return Whether the context field is set.
*/
boolean hasContext();
/**
*
*
* <pre>
* Required. The context to update.
* </pre>
*
* <code>.google.cloud.dialogflow.v2beta1.Context context = 1;</code>
*
* @return The context.
*/
com.google.cloud.dialogflow.v2beta1.Context getContext();
/**
*
*
* <pre>
* Required. The context to update.
* </pre>
*
* <code>.google.cloud.dialogflow.v2beta1.Context context = 1;</code>
*/
com.google.cloud.dialogflow.v2beta1.ContextOrBuilder getContextOrBuilder();
/**
*
*
* <pre>
* Optional. The mask to control which fields get updated.
* </pre>
*
* <code>.google.protobuf.FieldMask update_mask = 2;</code>
*
* @return Whether the updateMask field is set.
*/
boolean hasUpdateMask();
/**
*
*
* <pre>
* Optional. The mask to control which fields get updated.
* </pre>
*
* <code>.google.protobuf.FieldMask update_mask = 2;</code>
*
* @return The updateMask.
*/
com.google.protobuf.FieldMask getUpdateMask();
/**
*
*
* <pre>
* Optional. The mask to control which fields get updated.
* </pre>
*
* <code>.google.protobuf.FieldMask update_mask = 2;</code>
*/
com.google.protobuf.FieldMaskOrBuilder getUpdateMaskOrBuilder();
}
|
package de.codingair.tradesystem.spigot.events;
import de.codingair.tradesystem.spigot.trade.Trade;
import org.bukkit.Bukkit;
import org.bukkit.entity.Player;
import org.bukkit.event.Event;
import org.bukkit.event.HandlerList;
import org.bukkit.inventory.ItemStack;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
/**
* Called when a player trades an item with another player.
*
* @author CodingAir
*/
public class TradeItemEvent extends Event {
private static final HandlerList handlerList = new HandlerList();
private final Player receiver;
private final String sender;
private final Player sendingPlayer;
private ItemStack item;
/**
* Indicates a proxy trade.
*
* @param receiver The {@link Player} who received the item.
* @param sender The name of the player who trades the item.
* @param item The item being transferred.
*/
public TradeItemEvent(@NotNull Player receiver, @NotNull String sender, @NotNull ItemStack item) {
this.receiver = receiver;
this.sender = sender;
this.item = item;
this.sendingPlayer = null;
}
/**
* Indicates a bukkit trade.
*
* @param receiver The {@link Player} who received the item.
* @param sendingPlayer The {@link Player} who trades the item.
* @param item The item being transferred.
*/
public TradeItemEvent(@NotNull Player receiver, @NotNull Player sendingPlayer, @NotNull ItemStack item) {
this.receiver = receiver;
this.sendingPlayer = sendingPlayer;
this.item = item;
this.sender = sendingPlayer.getName();
}
public static HandlerList getHandlerList() {
return handlerList;
}
@NotNull
@Override
public HandlerList getHandlers() {
return getHandlerList();
}
/**
* @return The {@link Player} who receives the item.
*/
public @NotNull Player getReceiver() {
return this.receiver;
}
/**
* @return The {@link Player} who trades the item. Is null if this is a proxy trade and the sender is on another server.
*/
public @Nullable Player getSendingPlayer() {
return this.sendingPlayer;
}
/**
* @return {@link Boolean#TRUE} if the sender is on another server.
*/
public boolean isProxyTrade() {
return getSendingPlayer() == null;
}
/**
* @return The name of the player who trades the item.
*/
public @NotNull String getSender() {
return this.sender;
}
/**
* @return The item being transferred.
*/
public @NotNull ItemStack getItem() {
return this.item;
}
/**
* @param item The new {@link ItemStack} which will be traded instead. Null values will remove this item from the trade.
*/
public void setItem(@Nullable ItemStack item) {
this.item = item;
}
/**
* @return {@link Boolean#TRUE} if this item will be dropped on exchange.
*/
public boolean isAboutToDrop() {
if (this.item == null) return false;
return Trade.fit(receiver, item) > 0;
}
}
|
package edu.wzu.steve.trafficanalyser;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import org.restlet.resource.ResourceException;
import org.restlet.resource.ServerResource;
import net.floodlightcontroller.counter.CounterValue;
import net.floodlightcontroller.counter.ICounter;
import net.floodlightcontroller.packet.Ethernet;
import net.floodlightcontroller.packet.IPv4;
import org.restlet.resource.Get;
import net.floodlightcontroller.core.FloodlightContext;
import net.floodlightcontroller.core.IFloodlightProviderService;
import net.floodlightcontroller.core.IOFMessageListener;
import net.floodlightcontroller.core.IOFSwitch;
import net.floodlightcontroller.core.module.FloodlightModuleContext;
import net.floodlightcontroller.core.module.FloodlightModuleException;
import net.floodlightcontroller.core.module.IFloodlightModule;
import net.floodlightcontroller.core.module.IFloodlightService;
import net.floodlightcontroller.counter.ICounterStoreService;
import org.openflow.protocol.OFMessage;
import org.openflow.protocol.OFType;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class TrafficAnalyser extends ServerResource implements IOFMessageListener, IFloodlightModule{
public final static String BROADCAST = "broadcast";
public final static String MULTICAST = "multicast";
public final static String UNICAST = "unicast";
protected ICounterStoreService counterStore;
protected IFloodlightProviderService floodlightProvider;
protected static Logger logger;
@Override
public String getName() {
// TODO Auto-generated method stub
return TrafficAnalyser.class.getSimpleName();
}
@Override
public boolean isCallbackOrderingPrereq(OFType type, String name) {
// TODO Auto-generated method stub
return false;
}
@Override
public boolean isCallbackOrderingPostreq(OFType type, String name) {
// TODO Auto-generated method stub
return false;
}
@Override
public Collection<Class<? extends IFloodlightService>> getModuleServices() {
// TODO Auto-generated method stub
return null;
}
@Override
public Map<Class<? extends IFloodlightService>, IFloodlightService> getServiceImpls() {
// TODO Auto-generated method stub
return null;
}
@Override
public Collection<Class<? extends IFloodlightService>> getModuleDependencies() {
// TODO Auto-generated method stub
Collection<Class<? extends IFloodlightService>> l =
new ArrayList<Class<? extends IFloodlightService>>();
l.add(IFloodlightProviderService.class);
return l;
}
@Override
public void init(FloodlightModuleContext context)
throws FloodlightModuleException {
this.floodlightProvider = context.getServiceImpl(IFloodlightProviderService.class);
this.counterStore = context.getServiceImpl(ICounterStoreService.class);
logger = LoggerFactory.getLogger(TrafficAnalyser.class);
}
@Override
public void startUp(FloodlightModuleContext context) {
floodlightProvider.addOFMessageListener(OFType.PACKET_IN, this);
}
@Get("json")
public Map<String, Object> retrieve(){
Map<String, Object> model = new HashMap<String,Object>();
CounterValue v;
Map<String, ICounter> counters = this.counterStore.getAll();
if (counters != null) {
Iterator<Map.Entry<String, ICounter>> it =
counters.entrySet().iterator();
while (it.hasNext()) {
Entry<String, ICounter> entry = it.next();
String counterName = entry.getKey();
v = entry.getValue().getCounterValue();
if (CounterValue.CounterType.LONG == v.getType()) {
model.put(counterName, v.getLong());
} else if (v.getType() == CounterValue.CounterType.DOUBLE) {
model.put(counterName, v.getDouble());
}
}
}
return model;
}
protected List<String> PacketInType(IOFSwitch sw, OFMessage m, Ethernet eth) {
int l3type = eth.getEtherType() & 0xffff;
String switchIdHex = sw.getStringId();
String etherType = String.format("%04x", eth.getEtherType());
String packetName = m.getType().toClass().getName();
packetName = packetName.substring(packetName.lastIndexOf('.')+1);
// L2 Type
String l2Type = null;
if (eth.isBroadcast()) {
l2Type = BROADCAST;
}
else if (eth.isMulticast()) {
l2Type = MULTICAST;
}
else {
l2Type = UNICAST;
}
// Use alias for L3 type
// Valid EtherType must be greater than or equal to 0x0600
// It is V1 Ethernet Frame if EtherType < 0x0600
if (l3type < 0x0600) {
etherType = "0599";
}
if (TypeAnalyser.l3TypeAliasMap != null &&
TypeAnalyser.l3TypeAliasMap.containsKey(etherType)) {
etherType = TypeAnalyser.l3TypeAliasMap.get(etherType);
}
else {
etherType = "L3_" + etherType;
}
// L4 counters
if (eth.getPayload() instanceof IPv4) {
// resolve protocol alias
IPv4 ipV4 = (IPv4)eth.getPayload();
String l4name = String.format("%02x", ipV4.getProtocol());
if (TypeAnalyser.l4TypeAliasMap != null &&
TypeAnalyser.l4TypeAliasMap.containsKey(l4name)) {
l4name = TypeAnalyser.l4TypeAliasMap.get(l4name);
}
else {
l4name = "L4_" + l4name;
}
List<String>list = new ArrayList<String>();
list.add(l2Type);
list.add(etherType);
list.add(l4name);
//使用Iterator迭代器遍历出集合的元素并打印
for(Iterator<String> i = list.iterator();i.hasNext(); ){
String str = (String) i.next();
System.out.println(str);
}
}
return null;
}
protected void doInit() throws ResourceException {
super.doInit();
counterStore =
(ICounterStoreService)getContext().getAttributes().
get(ICounterStoreService.class.getCanonicalName());
}
@Override
public net.floodlightcontroller.core.IListener.Command receive(IOFSwitch sw, OFMessage msg, FloodlightContext cntx) {
System.out.println(retrieve().toString());
return Command.CONTINUE;
}
}
|
/*
* #%L
* BigDataViewer core classes with minimal dependencies.
* %%
* Copyright (C) 2012 - 2020 BigDataViewer developers.
* %%
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS 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.
* #L%
*/
package bdv.viewer.render;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ExecutorService;
import net.imglib2.Interval;
import net.imglib2.RandomAccessibleInterval;
import net.imglib2.Volatile;
import net.imglib2.cache.iotiming.CacheIoTiming;
import net.imglib2.realtransform.AffineTransform3D;
import net.imglib2.type.numeric.ARGBType;
import net.imglib2.util.Intervals;
import bdv.cache.CacheControl;
import bdv.util.MovingAverage;
import bdv.viewer.RequestRepaint;
import bdv.viewer.SourceAndConverter;
import bdv.viewer.ViewerState;
import bdv.viewer.render.ScreenScales.IntervalRenderData;
import bdv.viewer.render.ScreenScales.ScreenScale;
/**
* A renderer that uses a coarse-to-fine rendering scheme. First, a small target
* image at a fraction of the canvas resolution is rendered. Then, increasingly
* larger images are rendered, until the full canvas resolution is reached.
* <p>
* When drawing the low-resolution target images to the screen, they will be
* scaled up by Java2D (or JavaFX, etc) to the full canvas size, which is
* relatively fast. Rendering the small, low-resolution images is usually very
* fast, such that the display is very interactive while the user changes the
* viewing transformation for example. When the transformation remains fixed for
* a longer period, higher-resolution details are filled in successively.
* <p>
* The renderer allocates a {@code RenderResult} for each of a predefined set of
* <em>screen scales</em> (a screen scale of 1 means that 1 pixel in the screen
* image is displayed as 1 pixel on the canvas, a screen scale of 0.5 means 1
* pixel in the screen image is displayed as 2 pixel on the canvas, etc.)
* <p>
* At any time, one of these screen scales is selected as the <em>highest screen
* scale</em>. Rendering starts with this highest screen scale and then proceeds
* to lower screen scales (higher resolution images). Unless the highest screen
* scale is currently rendering, {@link #requestRepaint() repaint request} will
* cancel rendering, such that display remains interactive.
* <p>
* The renderer tries to maintain a per-frame rendering time close to
* {@code targetRenderNanos} nanoseconds. The current highest screen scale is
* chosen to match this time based on per-output-pixel time measured in previous
* frames.
* <p>
* The renderer uses multiple threads (if desired).
* <p>
* The renderer supports rendering of {@link Volatile} sources. In each
* rendering pass, all currently valid data for the best fitting mipmap level
* and all coarser levels is rendered to a temporary image for each visible
* source. Then the temporary images are combined to the final image for
* display. The number of passes required until all data is valid might differ
* between visible sources.
* <p>
* Rendering timing is tied to a {@link CacheControl} control for IO budgeting,
* etc.
*
* @author Tobias Pietzsch
*/
public class MultiResolutionRenderer
{
/**
* Receiver for the {@code BufferedImage BufferedImages} that we render.
*/
private final RenderTarget< ? > display;
/**
* Thread that triggers repainting of the display.
* Requests for repainting are send there.
*/
private final RequestRepaint painterThread;
/**
* Creates projectors for rendering current {@code ViewerState} to a
* {@code screenImage}.
*/
private final ProjectorFactory projectorFactory;
/**
* Controls IO budgeting and fetcher queue.
*/
private final CacheControl cacheControl;
// TODO: should be settable
private final long[] iobudget = new long[] { 100l * 1000000l, 10l * 1000000l };
/**
* Maintains current sizes and transforms at every screen scale level.
* Records interval rendering requests.
*/
private final ScreenScales screenScales;
/**
* Maintains arrays for intermediate per-source render images and masks.
*/
private final RenderStorage renderStorage;
/**
* Estimate of the time it takes to render one screen pixel from one source,
* in nanoseconds.
*/
private final MovingAverage renderNanosPerPixelAndSource;
/**
* Currently active projector, used to re-paint the display. It maps the
* source data to {@code ©screenImages}. {@code projector.cancel()} can be
* used to cancel the ongoing rendering operation.
*/
private VolatileProjector projector;
/**
* Whether the current rendering operation may be cancelled (to start a new
* one). Rendering may be cancelled unless we are rendering at the
* (estimated) coarsest screen scale meeting the rendering time threshold.
*/
private boolean renderingMayBeCancelled;
/**
* Snapshot of the ViewerState that is currently being rendered.
* A new snapshot is taken in the first {@code paint()} pass after a (full frame) {@link #requestRepaint()}
*/
private ViewerState currentViewerState;
/**
* The sources that are actually visible on screen currently. This means
* that the sources both are visible in the {@link #currentViewerState} (via
* {@link ViewerState#getVisibleAndPresentSources()
* getVisibleAndPresentSources}) and, when transformed to viewer
* coordinates, overlap the screen area ({@link #display}).
*/
private final List< SourceAndConverter< ? > > currentVisibleSourcesOnScreen;
/**
* The last successfully rendered (not cancelled) full frame result.
* This result is by full frame refinement passes and/or interval rendering passes.
*/
private RenderResult currentRenderResult;
/**
* If {@code true}, then we are painting intervals currently.
* If {@code false}, then we are painting full frames.
*/
private boolean intervalMode;
/*
*
* === FULL FRAME RENDERING ===
*
*/
/**
* Screen scale of the last successful (not cancelled) rendering pass in
* full-frame mode.
*/
private int currentScreenScaleIndex;
/**
* The index of the screen scale which should be rendered next in full-frame
* mode.
*/
private int requestedScreenScaleIndex;
/**
* Whether a full frame repaint was {@link #requestRepaint() requested}.
* Supersedes {@link #newIntervalRequest}.
*/
private boolean newFrameRequest;
/*
*
* === INTERVAL RENDERING ===
*
*/
/**
* Screen scale of the last successful (not cancelled) rendering pass in
* interval mode.
*/
private int currentIntervalScaleIndex;
/**
* The index of the screen scale which should be rendered next in interval
* mode.
*/
private int requestedIntervalScaleIndex;
/**
* Whether repainting of an interval was {@link #requestRepaint(Interval)
* requested}. The union of all pending intervals are recorded in
* {@link #screenScales}. Pending interval requests are obsoleted by full
* frame repaints requests ({@link #newFrameRequest}).
*/
private boolean newIntervalRequest;
/**
* Re-used for all interval rendering.
*/
private final RenderResult intervalResult;
/**
* Currently rendering interval. This is pulled from {@link #screenScales}
* at the start of {@code paint()}, which clears requested intervals at
* {@link #currentIntervalScaleIndex} or coarser. (This ensures that new
* interval requests arriving during rendering are not missed. If the
* requested intervals would be cleared after rendering, this might happen.
* Instead we re-request the pulled intervals, if rendering fails.)
*/
private IntervalRenderData intervalRenderData;
/**
* @param display
* The canvas that will display the images we render.
* @param painterThread
* Thread that triggers repainting of the display. Requests for
* repainting are send there.
* @param screenScaleFactors
* Scale factors from the viewer canvas to screen images of
* different resolutions. A scale factor of 1 means 1 pixel in
* the screen image is displayed as 1 pixel on the canvas, a
* scale factor of 0.5 means 1 pixel in the screen image is
* displayed as 2 pixel on the canvas, etc.
* @param targetRenderNanos
* Target rendering time in nanoseconds. The rendering time for
* the coarsest rendered scale should be below this threshold.
* @param numRenderingThreads
* How many threads to use for rendering.
* @param renderingExecutorService
* if non-null, this is used for rendering. Note, that it is
* still important to supply the numRenderingThreads parameter,
* because that is used to determine into how many sub-tasks
* rendering is split.
* @param useVolatileIfAvailable
* whether volatile versions of sources should be used if
* available.
* @param accumulateProjectorFactory
* can be used to customize how sources are combined.
* @param cacheControl
* the cache controls IO budgeting and fetcher queue.
*/
public MultiResolutionRenderer(
final RenderTarget< ? > display,
final RequestRepaint painterThread,
final double[] screenScaleFactors,
final long targetRenderNanos,
final int numRenderingThreads,
final ExecutorService renderingExecutorService,
final boolean useVolatileIfAvailable,
final AccumulateProjectorFactory< ARGBType > accumulateProjectorFactory,
final CacheControl cacheControl )
{
this.display = display;
this.painterThread = painterThread;
projector = null;
currentScreenScaleIndex = -1;
currentVisibleSourcesOnScreen = new ArrayList<>();
screenScales = new ScreenScales( screenScaleFactors, targetRenderNanos );
renderStorage = new RenderStorage();
renderNanosPerPixelAndSource = new MovingAverage( 3 );
renderNanosPerPixelAndSource.init( 500 );
requestedScreenScaleIndex = screenScales.size() - 1;
renderingMayBeCancelled = false;
this.cacheControl = cacheControl;
newFrameRequest = false;
intervalResult = display.createRenderResult();
projectorFactory = new ProjectorFactory(
numRenderingThreads,
renderingExecutorService,
useVolatileIfAvailable,
accumulateProjectorFactory );
}
/**
* Request a repaint of the display from the painter thread. The painter
* thread will trigger a {@link #paint} as soon as possible (that is,
* immediately or after the currently running {@link #paint} has completed).
*/
public synchronized void requestRepaint()
{
if ( renderingMayBeCancelled && projector != null )
projector.cancel();
newFrameRequest = true;
painterThread.requestRepaint();
}
/**
* Request a repaint of the given {@code interval} of the display from the
* painter thread. The painter thread will trigger a {@link #paint} as soon
* as possible (that is, immediately or after the currently running
* {@link #paint} has completed).
*/
public synchronized void requestRepaint( final Interval interval )
{
// if interval doesn't overlap the screen, do nothing
if ( Intervals.isEmpty( screenScales.clipToScreen( interval ) ) )
return;
if ( !intervalMode && !renderingMayBeCancelled )
{
/*
* We are currently rendering a full frame at the coarsest
* resolution. There is no point in painting an interval now. Just
* request a new full frame.
*/
newFrameRequest = true;
}
else
{
if ( renderingMayBeCancelled && projector != null )
projector.cancel();
screenScales.requestInterval( interval );
newIntervalRequest = true;
}
painterThread.requestRepaint();
}
/**
* DON'T USE THIS.
* <p>
* This is a work around for JDK bug
* https://bugs.openjdk.java.net/browse/JDK-8029147 which leads to
* ViewerPanel not being garbage-collected when ViewerFrame is closed. So
* instead we need to manually let go of resources...
*/
public void kill()
{
projector = null;
currentViewerState = null;
currentRenderResult = null;
currentVisibleSourcesOnScreen.clear();
renderStorage.clear();
}
/**
* Render image at the {@link #requestedScreenScaleIndex requested screen
* scale}.
*/
public boolean paint( final ViewerState viewerState )
{
final int screenW = display.getWidth();
final int screenH = display.getHeight();
if ( screenW <= 0 || screenH <= 0 )
return false;
final boolean newFrame;
final boolean newInterval;
final boolean prepareNextFrame;
final boolean createProjector;
synchronized ( this )
{
final boolean resized = screenScales.checkResize( screenW, screenH );
newFrame = newFrameRequest || resized;
if ( newFrame )
{
intervalMode = false;
screenScales.clearRequestedIntervals();
}
newInterval = newIntervalRequest && !newFrame;
if ( newInterval )
{
intervalMode = true;
final int numSources = currentVisibleSourcesOnScreen.size();
final double renderNanosPerPixel = renderNanosPerPixelAndSource.getAverage() * numSources;
requestedIntervalScaleIndex = screenScales.suggestIntervalScreenScale( renderNanosPerPixel, currentScreenScaleIndex );
}
prepareNextFrame = newFrame || newInterval;
renderingMayBeCancelled = !prepareNextFrame;
if ( intervalMode )
{
createProjector = newInterval || ( requestedIntervalScaleIndex != currentIntervalScaleIndex );
if ( createProjector )
intervalRenderData = screenScales.pullIntervalRenderData( requestedIntervalScaleIndex, currentScreenScaleIndex );
}
else
createProjector = newFrame || ( requestedScreenScaleIndex != currentScreenScaleIndex );
newFrameRequest = false;
newIntervalRequest = false;
}
if ( prepareNextFrame )
cacheControl.prepareNextFrame();
if ( newFrame )
{
currentViewerState = viewerState.snapshot();
VisibilityUtils.computeVisibleSourcesOnScreen( currentViewerState, screenScales.get( 0 ), currentVisibleSourcesOnScreen );
final int numSources = currentVisibleSourcesOnScreen.size();
final double renderNanosPerPixel = renderNanosPerPixelAndSource.getAverage() * numSources;
requestedScreenScaleIndex = screenScales.suggestScreenScale( renderNanosPerPixel );
}
if ( !intervalMode && requestedScreenScaleIndex < 0 )
return true;
return intervalMode
? paintInterval( createProjector )
: paintFullFrame( createProjector );
}
private boolean paintFullFrame( final boolean createProjector )
{
// the projector that paints to the screenImage.
final VolatileProjector p;
// holds new RenderResult, in case that a new projector is created in full frame mode
RenderResult renderResult = null;
// whether to request a newFrame, in case that a new projector is created in full frame mode
boolean requestNewFrameIfIncomplete = false;
synchronized ( this )
{
if ( createProjector )
{
final ScreenScale screenScale = screenScales.get( requestedScreenScaleIndex );
renderResult = display.getReusableRenderResult();
renderResult.init( screenScale.width(), screenScale.height() );
renderResult.setScaleFactor( screenScale.scale() );
currentViewerState.getViewerTransform( renderResult.getViewerTransform() );
renderStorage.checkRenewData( screenScales.get( 0 ).width(), screenScales.get( 0 ).height(), currentVisibleSourcesOnScreen.size() );
projector = createProjector( currentViewerState, currentVisibleSourcesOnScreen, requestedScreenScaleIndex, renderResult.getTargetImage(), 0, 0 );
requestNewFrameIfIncomplete = projectorFactory.requestNewFrameIfIncomplete();
}
p = projector;
}
// try rendering
final boolean success = p.map( createProjector );
final long rendertime = p.getLastFrameRenderNanoTime();
synchronized ( this )
{
// if rendering was not cancelled...
if ( success )
{
currentScreenScaleIndex = requestedScreenScaleIndex;
if ( createProjector )
{
renderResult.setUpdated();
( ( RenderTarget ) display ).setRenderResult( renderResult );
currentRenderResult = renderResult;
recordRenderTime( renderResult, rendertime );
}
else
currentRenderResult.setUpdated();
if ( !p.isValid() && requestNewFrameIfIncomplete )
requestRepaint();
else if ( p.isValid() && currentScreenScaleIndex == 0 )
// indicate that rendering is complete
requestedScreenScaleIndex = -1;
else
iterateRepaint( Math.max( 0, currentScreenScaleIndex - 1 ) );
}
}
return success;
}
private boolean paintInterval( final boolean createProjector )
{
// the projector that paints to the screenImage.
final VolatileProjector p;
synchronized ( this )
{
if ( createProjector )
{
intervalResult.init( intervalRenderData.width(), intervalRenderData.height() );
intervalResult.setScaleFactor( intervalRenderData.scale() );
projector = createProjector( currentViewerState, currentVisibleSourcesOnScreen, requestedIntervalScaleIndex, intervalResult.getTargetImage(), intervalRenderData.offsetX(), intervalRenderData.offsetY() );
}
p = projector;
}
// try rendering
final boolean success = p.map( createProjector );
final long rendertime = p.getLastFrameRenderNanoTime();
synchronized ( this )
{
// if rendering was not cancelled...
if ( success )
{
currentIntervalScaleIndex = requestedIntervalScaleIndex;
currentRenderResult.patch( intervalResult, intervalRenderData.targetInterval(), intervalRenderData.tx(), intervalRenderData.ty() );
if ( createProjector )
recordRenderTime( intervalResult, rendertime );
if ( currentIntervalScaleIndex > currentScreenScaleIndex )
iterateRepaintInterval( currentIntervalScaleIndex - 1 );
else if ( p.isValid() )
{
// if full frame rendering was not yet complete
if ( requestedScreenScaleIndex >= 0 )
{
// go back to full frame rendering
intervalMode = false;
if ( requestedScreenScaleIndex == currentScreenScaleIndex )
++currentScreenScaleIndex;
painterThread.requestRepaint();
}
}
else
iterateRepaintInterval( currentIntervalScaleIndex );
}
// if rendering was cancelled...
else
intervalRenderData.reRequest();
}
return success;
}
private void recordRenderTime( final RenderResult result, final long renderNanos )
{
final int numSources = currentVisibleSourcesOnScreen.size();
final int numRenderPixels = ( int ) Intervals.numElements( result.getTargetImage() ) * numSources;
if ( numRenderPixels >= 4096 )
renderNanosPerPixelAndSource.add( renderNanos / ( double ) numRenderPixels );
}
/**
* Request iterated repaint at the specified {@code screenScaleIndex}. This
* is used to repaint the {@code currentViewerState} in a loop, until
* everything is painted at highest resolution from valid data (or until
* painting is interrupted by a new request}.
*/
private void iterateRepaint( final int screenScaleIndex )
{
if ( screenScaleIndex == currentScreenScaleIndex )
usleep();
requestedScreenScaleIndex = screenScaleIndex;
painterThread.requestRepaint();
}
/**
* Request iterated repaint at the specified {@code intervalScaleIndex}.
* This is used to repaint the current interval in a loop, until everything
* is painted at highest resolution from valid data (or until painting is
* interrupted by a new request}.
*/
private void iterateRepaintInterval( final int intervalScaleIndex )
{
if ( intervalScaleIndex == currentIntervalScaleIndex )
{
intervalRenderData.reRequest();
usleep();
}
requestedIntervalScaleIndex = intervalScaleIndex;
painterThread.requestRepaint();
}
/**
* Wait for 1ms so that fetcher threads get a chance to do work.
*/
private void usleep()
{
try
{
Thread.sleep( 1 );
}
catch ( final InterruptedException e )
{
// restore interrupted state
Thread.currentThread().interrupt();
}
}
private VolatileProjector createProjector(
final ViewerState viewerState,
final List< SourceAndConverter< ? > > visibleSourcesOnScreen,
final int screenScaleIndex,
final RandomAccessibleInterval< ARGBType > screenImage,
final int offsetX,
final int offsetY )
{
final AffineTransform3D screenScaleTransform = screenScales.get( screenScaleIndex ).scaleTransform();
final AffineTransform3D screenTransform = viewerState.getViewerTransform();
screenTransform.preConcatenate( screenScaleTransform );
screenTransform.translate( -offsetX, -offsetY, 0 );
final VolatileProjector projector = projectorFactory.createProjector(
viewerState,
visibleSourcesOnScreen,
screenImage,
screenTransform,
renderStorage );
CacheIoTiming.getIoTimeBudget().reset( iobudget );
return projector;
}
}
|
package com.jnape.palatable.lambda.functor.builtin;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
public class IdentityTest {
@Test
public void functorProperties() {
assertEquals("FOO", new Identity<>("foo").fmap(String::toUpperCase).runIdentity());
}
}
|
package com.blossomproject.ui.current_user;
import com.blossomproject.core.user.UserDTO;
public class UserDTOBuilder {
private String identifier;
private String passwordHash;
public UserDTOBuilder identifier(String identifier) {
this.identifier = identifier;
return this;
}
public UserDTOBuilder passwordHash(String passwordHash) {
this.passwordHash = passwordHash;
return this;
}
public UserDTO toUserDTO() {
UserDTO user = new UserDTO();
user.setIdentifier(identifier);
user.setPasswordHash(passwordHash);
return user;
}
}
|
/*
* Wegas
* http://wegas.albasim.ch
*
* Copyright (c) 2013 School of Business and Engineering Vaud, Comem
* Licensed under the MIT License
*/
package com.wegas.app;
import com.wegas.core.Helper;
import com.wegas.core.ejb.GameModelFacade;
import com.wegas.core.ejb.VariableDescriptorFacade;
import com.wegas.core.persistence.game.GameModel;
import com.wegas.core.persistence.game.Player;
import com.wegas.core.rest.ScriptController;
import com.wegas.core.security.ejb.UserFacade;
import java.io.File;
import java.util.HashMap;
import java.util.Map;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.ejb.embeddable.EJBContainer;
import javax.naming.NamingException;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.config.IniSecurityManagerFactory;
import org.glassfish.embeddable.GlassFishException;
import org.junit.AfterClass;
import org.junit.BeforeClass;
/**
*
* @author Cyril Junod <cyril.junod at gmail.com>
*/
public abstract class AbstractEJBContainerTest extends AbstractTest {
private static EJBContainer container;
protected static GameModelFacade gmFacade;
@BeforeClass
public static void setUp() throws Exception {
Map<String, Object> properties = new HashMap<>(); // Init Ejb container
properties.put(EJBContainer.MODULES, new File[]{new File("../wegas-core/target/embed-classes")});
properties.put("org.glassfish.ejb.embedded.glassfish.installation.root", "../wegas-core/src/test/glassfish");
//properties.put(EJBContainer.APP_NAME,"class");
//ejbContainer.getContext().rebind("inject", this);
// Init shiro
SecurityUtils.setSecurityManager(new IniSecurityManagerFactory("classpath:shiro.ini").getInstance());
Logger.getLogger("javax.enterprise.system.tools.deployment").setLevel(Level.OFF);
Logger.getLogger("javax.enterprise.system").setLevel(Level.OFF);
container = EJBContainer.createEJBContainer(properties);
Helper.lookupBy(container.getContext(), UserFacade.class, UserFacade.class).guestLogin(); //login as guest
gmFacade = Helper.lookupBy(container.getContext(), GameModelFacade.class, GameModelFacade.class);
}
@AfterClass
public static void tearDown() throws GlassFishException {
container.close();
}
protected <T> T lookup(Class<T> className) {
try {
return Helper.lookupBy(container.getContext(), className, className);
} catch (NamingException ex) {
return null;
}
}
@Override
protected ScriptController getScriptController() {
return lookup(ScriptController.class);
}
@Override
protected VariableDescriptorFacade getVariableDescriptorFacade() {
return lookup(VariableDescriptorFacade.class);
}
}
|
/**
* Automatically generated file. DO NOT MODIFY
*/
package com.incomingcall;
public final class BuildConfig {
public static final boolean DEBUG = Boolean.parseBoolean("true");
public static final String LIBRARY_PACKAGE_NAME = "com.incomingcall";
public static final String BUILD_TYPE = "debug";
}
|
/*
* Copyright 2018 ImpactDevelopment
*
* 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 clientapi.event.task;
/**
* @author Brady
* @since 11/30/2017
*/
public interface TaskManager {
/**
* Attempts to start the specified task. The task can only
* be started if there isn't a task currently running, or if
* the current task running has a lower priority than the specified
* task.
*
* @param task The task to start
* @return Whether or not the task could be started
*/
boolean start(Task task);
/**
* Attempts to start the specified task. The task can only be started
* if there isn't a task currently running, or if the current task
* running has a lower priority than the specified task. If the task
* cannot be started, it is added to a queue, and when the current
* task is finished by calling {@link TaskManager#finish}, the queued
* task will be called. Queued tasks will not be called when a task is
* being started that overpowers the priority level of the current task.
*
* @param task The task to start
* @return Whether or not the task could be started
*/
boolean startOrQueue(Task task);
/**
* Finishes the specified task. This is done by setting the
* current task's active state to {@code false}, indicating
* that it may no longer execute. Returns whether or not there
* is an active task. If there are tasks waiting in the queue,
* they will be started.
*
* @return Whether or not there is an active task
*/
boolean finish();
/**
* @return The current task that is active in this manager, null if none.
*/
Task getCurrentTask();
}
|
/*
* Copyright (C) 2015 Ayelen Chavez y Joaquín Rinaudo
*
* 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.
*
* Contributors:
*
* Ayelen Chavez ashy.on.line@gmail.com
* Joaquin Rinaudo jmrinaudo@gmail.com
*
*/
package com.codingbad.vpntoggle.task;
import android.app.ProgressDialog;
import android.content.Context;
import android.os.AsyncTask;
import android.widget.Toast;
import java.util.List;
import eu.chainfire.libsuperuser.Shell;
/**
* Created by ayi on 8/13/15.
*/
public class Startup extends AsyncTask<Void, Void, Void> {
private ProgressDialog dialog = null;
private Context context = null;
private boolean suAvailable = false;
private String suVersion = null;
private String suVersionInternal = null;
private List<String> suResult = null;
public Startup setContext(Context context) {
this.context = context;
return this;
}
@Override
protected void onPreExecute() {
// We're creating a progress dialog here because we want the user to wait.
// If in your app your user can just continue on with clicking other things,
// don't do the dialog thing.
dialog = new ProgressDialog(context);
dialog.setTitle("Some title");
dialog.setMessage("Doing something interesting ...");
dialog.setIndeterminate(true);
dialog.setCancelable(false);
dialog.show();
}
@Override
protected Void doInBackground(Void... params) {
// Let's do some SU stuff
suAvailable = Shell.SU.available();
if (suAvailable) {
suVersion = Shell.SU.version(false);
suVersionInternal = Shell.SU.version(true);
suResult = Shell.SU.run(new String[]{
"id",
"ls -l /"
});
}
// This is just so you see we had a progress dialog,
// don't do this in production code
try {
Thread.sleep(5000);
} catch (Exception e) {
}
return null;
}
@Override
protected void onPostExecute(Void result) {
dialog.dismiss();
// output
StringBuilder sb = (new StringBuilder()).
append("Root? ").append(suAvailable ? "Yes" : "No").append((char) 10).
append("Version: ").append(suVersion == null ? "N/A" : suVersion).append((char) 10).
append("Version (internal): ").append(suVersionInternal == null ? "N/A" : suVersionInternal).append((char) 10).
append((char) 10);
if (suResult != null) {
for (String line : suResult) {
sb.append(line).append((char) 10);
}
}
Toast.makeText(context, sb.toString(), Toast.LENGTH_LONG).show();
}
}
|
package blocksworld;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
public class Predicate
{
// Definition of the class predicate
/////////////////
// Inputs:
// ** type: type of the predicate: {on_table,on,picked_up,free,free_arm}
// ** block1:
// ** block2:
// ** value: in order to implement the heuristics
/////////////////
// Outputs:
// ** It outputs the predicate as a class
/////////////////
// Author: 'Toño G. Quintela' tgq.spm@gmail.com with the unaffordable help of C.Levinas
private PredicateName predicateName;
private Block block1;
private Block block2;
private int value;
public Predicate(PredicateName type, Block block1, Block block2, int value)
{
this.predicateName = type;
this.block1 = block1;
this.block2 = block2;
this.value = value;
}
public PredicateName getType()
{
return this.predicateName;
}
public PredicateName getPredicateName()
{
return this.predicateName;
}
public void setPredicateName(PredicateName type)
{
this.predicateName = type;
}
public Block getBlock1()
{
return this.block1;
}
public void setBlock1(Block block1)
{
this.block1 = block1;
}
public Block getBlock2()
{
return this.block2;
}
public void setBlock2(Block block2)
{
this.block2 = block2;
}
public int getValue()
{
return this.value;
}
public void setValue(int value)
{
this.value = value;
}
public boolean isInstantiated()
{
return (((this.block1 == null) || this.block1.isInstantiated()) &&
((this.block2 == null) || this.block2.isInstantiated()));
}
public List<Operator> getOperatorsThatSolve(PredicatesList currentState)
{
ArrayList<Operator> operators = new ArrayList<Operator>();
Operator operator;
switch (this.predicateName)
{
case on_table:
operator = new Operator(OperatorName.leave, this.block1, null);
operators.add(operator);
break;
case on:
operator = new Operator(OperatorName.stack, this.block1, this.block2);
operators.add(operator);
break;
case picked_up:
// Choose to pick_up or unstack, depending on the situation of block
List<Predicate> onTablePredicates = currentState.getMatches(PredicateName.on_table);
boolean blockOnTable = false;
for (Predicate onTablePredicate : onTablePredicates)
{
if (onTablePredicate.block1.equals(this.block1))
{
blockOnTable = true;
break;
}
}
if (blockOnTable)
{
operator = new Operator(OperatorName.pick_up, this.block1, null);
operators.add(operator);
}
else
{
operator = new Operator(OperatorName.unstack, this.block1, Planner.Y);
operators.add(operator);
}
break;
case free:
operator = new Operator(OperatorName.unstack, Planner.X, this.block1);
operators.add(operator);
break;
case free_arm:
// TBD: Choose intelligently between these two options
operator = new Operator(OperatorName.stack, Planner.X, Planner.Y);
operators.add(operator);
operator = new Operator(OperatorName.leave, Planner.X, null);
operators.add(operator);
break;
}
return operators;
}
@Override
public boolean equals(Object obj)
{
if (obj == null)
{
return false;
}
if (getClass() != obj.getClass())
{
return false;
}
final Predicate other = (Predicate) obj;
if (this.predicateName != other.predicateName)
{
return false;
}
if (!Objects.equals(this.block1, other.block1))
{
return false;
}
if (!Objects.equals(this.block2, other.block2))
{
return false;
}
if (this.value != other.value)
{
return false;
}
return true;
}
@Override
public int hashCode()
{
int hash = 3;
hash = 83 * hash + (this.predicateName != null ? this.predicateName.hashCode() : 0);
hash = 83 * hash + Objects.hashCode(this.block1);
hash = 83 * hash + Objects.hashCode(this.block2);
hash = 83 * hash + this.value;
return hash;
}
}
|
package com.example.alexandermelnikov.yandexgallerytask.data;
import android.support.annotation.NonNull;
import com.example.alexandermelnikov.yandexgallerytask.model.realm.ImageSrc;
import java.util.ArrayList;
import io.realm.Realm;
/**
* ImageSrcRepository.java – helper class for working with ImageSrc table in Realm
* @author Alexander Melnikov
*/
public class ImageSrcRepository {
/**
* Insert new ImageSrc object to Realm database
* @param source The ImageSrc object to be inserted
*/
public void insertImageSrcToRealm(@NonNull ImageSrc source) {
Realm realm = Realm.getDefaultInstance();
realm.executeTransaction(r -> {
int nextID;
try {
// Incrementing primary key manually
nextID = realm.where(ImageSrc.class).max("id").intValue() + 1;
} catch (NullPointerException e) {
// If there is first item, being added to cache, give it id = 0
nextID = 0;
}
source.setId(nextID);
realm.insertOrUpdate(source);
});
realm.close();
}
/**
* Get image sources objects from Realm by their phrase variable value
* @param phrase The desirable phrase String value
* @return List of ImageSrc objects
*/
public ArrayList<ImageSrc> getImageSrcByRequestPhrase(String phrase) {
ArrayList<ImageSrc> sources;
Realm realm = Realm.getDefaultInstance();
sources = new ArrayList<>(realm.where(ImageSrc.class)
.equalTo("requestPhrase", phrase)
.findAll());
return sources;
}
}
|
package guicassolato.java.n2w.converters;
public interface IConjunctionApplicable {
/**
* Decides if the a conjunction word is required between quotient and remainder
*
* @return true if a conjunction is required; false otherwise.
*/
abstract boolean requiresConjunction();
}
|
/*
* Elastic Cloud API
* No description provided (generated by Swagger Codegen https://github.com/swagger-api/swagger-codegen)
*
* OpenAPI spec version: 1
*
*
* NOTE: This class is auto generated by the swagger code generator program.
* https://github.com/swagger-api/swagger-codegen.git
* Do not edit the class manually.
*/
package io.swagger.client.model;
import java.util.Objects;
import java.util.Arrays;
import com.google.gson.TypeAdapter;
import com.google.gson.annotations.JsonAdapter;
import com.google.gson.annotations.SerializedName;
import com.google.gson.stream.JsonReader;
import com.google.gson.stream.JsonWriter;
import io.swagger.v3.oas.annotations.media.Schema;
import java.io.IOException;
/**
* DeploymentResourceUpgradeResponse
*/
@javax.annotation.Generated(value = "io.swagger.codegen.v3.generators.java.JavaClientCodegen", date = "2020-03-10T16:33:30.970+05:30[Asia/Kolkata]")
public class DeploymentResourceUpgradeResponse {
@SerializedName("resource_id")
private String resourceId = null;
@SerializedName("stack_version")
private String stackVersion = null;
public DeploymentResourceUpgradeResponse resourceId(String resourceId) {
this.resourceId = resourceId;
return this;
}
/**
* Get resourceId
* @return resourceId
**/
@Schema(description = "")
public String getResourceId() {
return resourceId;
}
public void setResourceId(String resourceId) {
this.resourceId = resourceId;
}
public DeploymentResourceUpgradeResponse stackVersion(String stackVersion) {
this.stackVersion = stackVersion;
return this;
}
/**
* Get stackVersion
* @return stackVersion
**/
@Schema(description = "")
public String getStackVersion() {
return stackVersion;
}
public void setStackVersion(String stackVersion) {
this.stackVersion = stackVersion;
}
@Override
public boolean equals(java.lang.Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
DeploymentResourceUpgradeResponse deploymentResourceUpgradeResponse = (DeploymentResourceUpgradeResponse) o;
return Objects.equals(this.resourceId, deploymentResourceUpgradeResponse.resourceId) &&
Objects.equals(this.stackVersion, deploymentResourceUpgradeResponse.stackVersion);
}
@Override
public int hashCode() {
return Objects.hash(resourceId, stackVersion);
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("class DeploymentResourceUpgradeResponse {\n");
sb.append(" resourceId: ").append(toIndentedString(resourceId)).append("\n");
sb.append(" stackVersion: ").append(toIndentedString(stackVersion)).append("\n");
sb.append("}");
return sb.toString();
}
/**
* Convert the given object to string with each line indented by 4 spaces
* (except the first line).
*/
private String toIndentedString(java.lang.Object o) {
if (o == null) {
return "null";
}
return o.toString().replace("\n", "\n ");
}
}
|
/*
* Copyright (c) Thomas Parker, 2009.
*
* This program is free software; you can redistribute it and/or modify it under
* the terms of the GNU Lesser General Public License as published by the Free
* Software Foundation; either version 2.1 of the License, or (at your option)
* any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more
* details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this library; if not, write to the Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA
*/
package pcgen.cdom.facet;
import java.util.Collection;
import pcgen.cdom.base.CDOMObject;
import pcgen.cdom.base.CDOMReference;
import pcgen.cdom.enumeration.CharID;
import pcgen.cdom.facet.base.AbstractSourcedListFacet;
import pcgen.cdom.facet.event.DataFacetChangeEvent;
import pcgen.cdom.facet.event.DataFacetChangeListener;
import pcgen.cdom.facet.model.ClassFacet;
import pcgen.cdom.facet.model.RaceFacet;
import pcgen.cdom.facet.model.TemplateFacet;
import pcgen.core.Language;
/**
* StartingLanguageFacet is a Facet that tracks the Languages that are available
* to a Player Character from the LANGBONUS token.
*
* @author Thomas Parker (thpr [at] yahoo.com)
*/
public class StartingLanguageFacet extends AbstractSourcedListFacet<CharID, Language>
implements DataFacetChangeListener<CharID, CDOMObject>
{
private ClassFacet classFacet;
private RaceFacet raceFacet;
private TemplateFacet templateFacet;
/**
* Adds available Languages to this facet when a CDOMObject added to a
* Player Character makes Languages available to the Player Character.
*
* Triggered when one of the Facets to which StartingLanguageFacet listens
* fires a DataFacetChangeEvent to indicate a CDOMObject was added to a
* Player Character.
*
* @param dfce
* The DataFacetChangeEvent containing the information about the
* change
*
* @see pcgen.cdom.facet.event.DataFacetChangeListener#dataAdded(pcgen.cdom.facet.event.DataFacetChangeEvent)
*/
@Override
public void dataAdded(DataFacetChangeEvent<CharID, CDOMObject> dfce)
{
CDOMObject cdo = dfce.getCDOMObject();
Collection<CDOMReference<Language>> list = cdo
.getListMods(Language.STARTING_LIST);
if (list != null)
{
CharID id = dfce.getCharID();
for (CDOMReference<Language> ref : list)
{
addAll(id, ref.getContainedObjects(), cdo);
}
}
}
/**
* Removes available Languages from this facet when a CDOMObject removed
* from a Player Character makes Languages available to the Player
* Character.
*
* Triggered when one of the Facets to which StartingLanguageFacet listens
* fires a DataFacetChangeEvent to indicate a CDOMObject was removed from a
* Player Character.
*
* @param dfce
* The DataFacetChangeEvent containing the information about the
* change
*
* @see pcgen.cdom.facet.event.DataFacetChangeListener#dataRemoved(pcgen.cdom.facet.event.DataFacetChangeEvent)
*/
@Override
public void dataRemoved(DataFacetChangeEvent<CharID, CDOMObject> dfce)
{
removeAll(dfce.getCharID(), dfce.getCDOMObject());
}
public void setClassFacet(ClassFacet classFacet)
{
this.classFacet = classFacet;
}
public void setRaceFacet(RaceFacet raceFacet)
{
this.raceFacet = raceFacet;
}
public void setTemplateFacet(TemplateFacet templateFacet)
{
this.templateFacet = templateFacet;
}
/**
* Initializes the connections for StartingLanguageFacet to other facets.
*
* This method is automatically called by the Spring framework during
* initialization of the StartingLanguageFacet.
*/
public void init()
{
raceFacet.addDataFacetChangeListener(this);
templateFacet.addDataFacetChangeListener(this);
classFacet.addDataFacetChangeListener(this);
}
}
|
package rps;
/**
* A basic message interface
*/
public interface IMessage {
/**
* getter of the payload of the message, i.e., the information contained
* inside the message
*
* @return an Object which must be carefully cast afterwards
*/
Object getPayload();
}
|
/*******************************************************************************
*
* Copyright FUJITSU LIMITED 2016
*
* Creation Date: 30.06.2010
*
*******************************************************************************/
package org.oscm.serviceprovisioningservice.bean;
import static org.mockito.Mockito.mock;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.Callable;
import javax.persistence.Query;
import org.junit.Assert;
import org.junit.Test;
import org.oscm.accountservice.assembler.OrganizationAssembler;
import org.oscm.accountservice.local.MarketingPermissionServiceLocal;
import org.oscm.converter.ParameterizedTypes;
import org.oscm.dataservice.bean.DataServiceBean;
import org.oscm.dataservice.local.DataService;
import org.oscm.domobjects.BillingContact;
import org.oscm.domobjects.DomainHistoryObject;
import org.oscm.domobjects.ImageResource;
import org.oscm.domobjects.Organization;
import org.oscm.domobjects.Parameter;
import org.oscm.domobjects.ParameterDefinition;
import org.oscm.domobjects.ParameterOption;
import org.oscm.domobjects.PaymentInfo;
import org.oscm.domobjects.PaymentType;
import org.oscm.domobjects.PlatformUser;
import org.oscm.domobjects.PricedProductRole;
import org.oscm.domobjects.PricedProductRoleHistory;
import org.oscm.domobjects.Product;
import org.oscm.domobjects.RoleDefinition;
import org.oscm.domobjects.Subscription;
import org.oscm.domobjects.TechnicalProduct;
import org.oscm.domobjects.enums.ModificationType;
import org.oscm.i18nservice.bean.LocalizerFacade;
import org.oscm.i18nservice.bean.LocalizerServiceBean;
import org.oscm.i18nservice.local.LocalizerServiceLocal;
import org.oscm.tenantprovisioningservice.bean.TenantProvisioningServiceBean;
import org.oscm.test.EJBTestBase;
import org.oscm.test.data.Organizations;
import org.oscm.test.data.PaymentInfos;
import org.oscm.test.data.Products;
import org.oscm.test.data.Scenario;
import org.oscm.test.data.Subscriptions;
import org.oscm.test.data.SupportedCountries;
import org.oscm.test.data.TechnicalProducts;
import org.oscm.test.ejb.TestContainer;
import org.oscm.test.stubs.ApplicationServiceStub;
import org.oscm.test.stubs.CommunicationServiceStub;
import org.oscm.test.stubs.ConfigurationServiceStub;
import org.oscm.test.stubs.ImageResourceServiceStub;
import org.oscm.test.stubs.MarketplaceServiceStub;
import org.oscm.test.stubs.SessionServiceStub;
import org.oscm.test.stubs.TriggerQueueServiceStub;
import org.oscm.internal.intf.ServiceProvisioningService;
import org.oscm.internal.types.enumtypes.ImageType;
import org.oscm.internal.types.enumtypes.OrganizationRoleType;
import org.oscm.internal.types.enumtypes.ParameterType;
import org.oscm.internal.types.enumtypes.ParameterValueType;
import org.oscm.internal.types.enumtypes.PriceModelType;
import org.oscm.internal.types.enumtypes.PricingPeriod;
import org.oscm.internal.types.enumtypes.ServiceAccessType;
import org.oscm.internal.types.enumtypes.ServiceStatus;
import org.oscm.internal.types.exception.OperationNotPermittedException;
import org.oscm.internal.types.exception.ValidationException;
import org.oscm.internal.vo.VOOrganization;
import org.oscm.internal.vo.VOParameter;
import org.oscm.internal.vo.VOPriceModel;
import org.oscm.internal.vo.VOPricedEvent;
import org.oscm.internal.vo.VOPricedOption;
import org.oscm.internal.vo.VOPricedParameter;
import org.oscm.internal.vo.VOPricedRole;
import org.oscm.internal.vo.VORoleDefinition;
import org.oscm.internal.vo.VOService;
import org.oscm.internal.vo.VOServiceDetails;
/**
* Tests for the service provisiong that test the handling of role related
* prices.
*
* @author Mike Jäger
*
*/
public class ServiceProvisioningRolePricingIT extends EJBTestBase {
private DataService dm;
private LocalizerServiceLocal localizer;
private ServiceProvisioningService svcProv;
private Organization supplierAndProvider;
private Organization customer;
private TechnicalProduct techProd;
private Product product;
private Subscription sub;
@Override
protected void setup(TestContainer container) throws Exception {
container.enableInterfaceMocking(true);
container.addBean(new DataServiceBean());
container.addBean(new SessionServiceStub());
container.addBean(new CommunicationServiceStub());
container.addBean(new ApplicationServiceStub());
container.addBean(new LocalizerServiceBean());
localizer = container.get(LocalizerServiceLocal.class);
container.addBean(new ImageResourceServiceStub() {
ImageResource saved;
@Override
public ImageResource read(long objectKey, ImageType imageType) {
return saved;
}
@Override
public void save(ImageResource imageResource) {
saved = imageResource;
}
@Override
public void delete(long objectKey, ImageType imageType) {
saved = null;
}
});
container.addBean(mock(TenantProvisioningServiceBean.class));
container.addBean(new TriggerQueueServiceStub());
container.addBean(new ConfigurationServiceStub());
container.addBean(new TagServiceBean());
container.addBean(mock(MarketingPermissionServiceLocal.class));
container.addBean(new MarketplaceServiceStub());
container.addBean(new ServiceProvisioningServiceBean());
dm = container.get(DataService.class);
svcProv = container.get(ServiceProvisioningService.class);
runTX(new Callable<Void>() {
@Override
public Void call() throws Exception {
SupportedCountries.createSomeSupportedCountries(dm);
return null;
}
});
PlatformUser user = init();
container.login(String.valueOf(user.getKey()), ROLE_SERVICE_MANAGER);
}
/**
* Creates the required test scenario and assigns created objects to the
* appropriate global fields.
*
* @throws Exception
*/
private PlatformUser init() throws Exception {
return runTX(new Callable<PlatformUser>() {
private ParameterDefinition paramDef;
private ParameterDefinition optionParamDef;
@Override
public PlatformUser call() throws Exception {
// create roles and currency
createOrganizationRoles(dm);
createSupportedCurrencies(dm);
createPaymentTypes(dm);
// create organization
supplierAndProvider = Organizations.createOrganization(dm,
OrganizationRoleType.TECHNOLOGY_PROVIDER,
OrganizationRoleType.SUPPLIER);
PlatformUser user = Organizations.createUserForOrg(dm,
supplierAndProvider, true, "admin");
customer = Organizations
.createCustomer(dm, supplierAndProvider);
// create technical product with roles};
techProd = TechnicalProducts.createTechnicalProduct(dm,
supplierAndProvider, "prodId", false,
ServiceAccessType.LOGIN);
RoleDefinition rd = new RoleDefinition();
rd.setTechnicalProduct(techProd);
rd.setRoleId("role1");
RoleDefinition rd2 = new RoleDefinition();
rd2.setTechnicalProduct(techProd);
rd2.setRoleId("role2");
dm.persist(rd);
dm.persist(rd2);
ArrayList<RoleDefinition> roles = new ArrayList<RoleDefinition>();
techProd.setRoleDefinitions(roles);
paramDef = TechnicalProducts.addParameterDefinition(
ParameterValueType.INTEGER, "intParam",
ParameterType.SERVICE_PARAMETER, techProd, dm, null,
null, true);
optionParamDef = TechnicalProducts.addParameterDefinition(
ParameterValueType.ENUMERATION, "enumParam",
ParameterType.SERVICE_PARAMETER, techProd, dm, null,
null, true);
ParameterOption po = new ParameterOption();
po.setOptionId("optionId");
po.setParameterDefinition(optionParamDef);
optionParamDef.setOptionList(Collections.singletonList(po));
dm.persist(po);
// create a product for the technical product
product = Products.createProduct(supplierAndProvider, techProd,
true, "product", null, dm);
product.setStatus(ServiceStatus.INACTIVE);
Parameter param = new Parameter();
param.setValue("123");
param.setParameterSet(product.getParameterSet());
param.setParameterDefinition(paramDef);
param.setConfigurable(true);
dm.persist(param);
Parameter param2 = new Parameter();
param2.setParameterSet(product.getParameterSet());
param2.setParameterDefinition(optionParamDef);
param2.setConfigurable(true);
param2.setValue("optionId");
dm.persist(param2);
// set payment information for the customer
PaymentType paymentType = findPaymentType(INVOICE, dm);
PaymentInfo pi = PaymentInfos.createPaymentInfo(customer, dm,
paymentType);
// create sub
sub = Subscriptions.createSubscription(dm,
customer.getOrganizationId(), "product", "subId",
supplierAndProvider);
sub.setPaymentInfo(pi);
BillingContact bc = PaymentInfos.createBillingContact(dm,
customer);
sub.setBillingContact(bc);
return user;
}
});
}
/**
* Asserts that the created product and price model are correct.
*
* @param roleDefinitions
* The role definition a price has been stored for.
* @param savedProduct
* The product to validate.
* @param expectedRoleDefCount
* The number of role definitions the saved product should have.
* @param isCustomerSpecific
* Indicates whether the created product should be validated to
* be customer specific or not.
* @param isSubscriptionSpecific
* Indicates whether the created product should be validated to
* be subscription specific or not.
* @param expectedBasePrice
* The base price to check for.
* @param isUpdate
* Indicates whether the test performed an update. If so, there
* will be more than only one history entry...
* @param createsNewEntry
* Indicates whether a new entry has been created so that this
* must be checked accordingly.
* @param removedPricedProductRole
* A priced product role that was removed. History has to be
* checked accordingly.
*/
private void assertCreatedProductSettings(
List<VORoleDefinition> roleDefinitions,
final VOServiceDetails savedProduct,
final int expectedRoleDefCount, final boolean isCustomerSpecific,
final boolean isSubscriptionSpecific,
final BigDecimal expectedBasePrice, final boolean isUpdate,
final VOPricedRole removedPricedProductRole) throws Exception {
runTX(new Callable<Void>() {
@Override
public Void call() throws Exception {
for (int i = 0; i < expectedRoleDefCount; i++) {
Product createdProduct = dm.getReference(Product.class,
savedProduct.getKey());
List<PricedProductRole> roleSpecificUserPrices = createdProduct
.getPriceModel().getRoleSpecificUserPrices();
Assert.assertEquals(expectedRoleDefCount,
roleSpecificUserPrices.size());
PricedProductRole pricedProductRole = roleSpecificUserPrices
.get(i);
Assert.assertEquals(
createdProduct.getPriceModel().getKey(),
pricedProductRole.getPriceModel().getKey());
Assert.assertNull(pricedProductRole.getPricedParameter());
Assert.assertNull(pricedProductRole.getPricedOption());
Assert.assertEquals(
expectedBasePrice.multiply(new BigDecimal(i + 1)),
pricedProductRole.getPricePerUser());
RoleDefinition role = pricedProductRole.getRoleDefinition();
List<DomainHistoryObject<?>> findHistory = dm
.findHistory(pricedProductRole);
{
Assert.assertEquals(createdProduct
.getTechnicalProduct().getRoleDefinitions()
.get(i), role);
PricedProductRoleHistory history = (PricedProductRoleHistory) findHistory
.get(0);
Assert.assertEquals(ModificationType.ADD,
history.getModtype());
Assert.assertNull(history.getPricedOptionObjKey());
Assert.assertNull(history.getPricedParameterObjKey());
Assert.assertEquals(createdProduct.getPriceModel()
.getKey(), history.getPriceModelObjKey()
.longValue());
Assert.assertEquals(createdProduct
.getTechnicalProduct().getRoleDefinitions()
.get(i).getKey(),
history.getRoleDefinitionObjKey());
}
if (!isCustomerSpecific && !isSubscriptionSpecific) {
Assert.assertNull(createdProduct.getTemplate());
Assert.assertNull(createdProduct
.getOwningSubscription());
}
if (isCustomerSpecific) {
Assert.assertNotNull(createdProduct.getTemplate());
Assert.assertEquals(customer.getKey(), createdProduct
.getTargetCustomer().getKey());
}
if (isSubscriptionSpecific) {
Assert.assertNotNull(createdProduct.getTemplate());
Assert.assertEquals(sub.getKey(), createdProduct
.getOwningSubscription().getKey());
}
}
if (removedPricedProductRole != null) {
PricedProductRole ppr = new PricedProductRole();
ppr.setKey(removedPricedProductRole.getKey());
List<PricedProductRoleHistory> findHistory = ParameterizedTypes
.list(dm.findHistory(ppr),
PricedProductRoleHistory.class);
Assert.assertEquals(2, findHistory.size());
Assert.assertEquals(ModificationType.DELETE, findHistory
.get(1).getModtype());
}
return null;
}
});
List<VOPricedRole> roleSpecificUserPrices = savedProduct
.getPriceModel().getRoleSpecificUserPrices();
Assert.assertEquals(expectedRoleDefCount, roleSpecificUserPrices.size());
Assert.assertEquals(expectedBasePrice, roleSpecificUserPrices.get(0)
.getPricePerUser());
if (isUpdate) {
Assert.assertEquals(roleDefinitions.get(0).getKey(),
roleSpecificUserPrices.get(0).getRole().getKey());
} else {
Assert.assertEquals(roleDefinitions.get(0).getKey(),
roleSpecificUserPrices.get(0).getRole().getKey());
}
if (expectedRoleDefCount == 2) {
VOPricedRole voPricedProductRole = roleSpecificUserPrices.get(1);
Assert.assertEquals(expectedBasePrice.multiply(new BigDecimal(2)),
voPricedProductRole.getPricePerUser());
Assert.assertEquals(roleDefinitions.get(1).getKey(),
roleSpecificUserPrices.get(1).getRole().getKey());
}
}
/**
* Initializes a price model object.
*
* @param ppr
* The priced product role to be set.
* @return The price model that was initialized.
*/
private VOPriceModel createPriceModelDefinition(List<VOPricedRole> ppr,
VOServiceDetails productDetails) {
VOPriceModel pm = productDetails.getPriceModel();
pm.setType(PriceModelType.PRO_RATA);
pm.setConsideredEvents(new ArrayList<VOPricedEvent>());
pm.setCurrencyISOCode("EUR");
pm.setDescription("desc");
pm.setOneTimeFee(BigDecimal.ZERO);
pm.setPeriod(PricingPeriod.MONTH);
pm.setPricePerPeriod(BigDecimal.valueOf(10L));
pm.setPricePerUserAssignment(BigDecimal.valueOf(22L));
pm.setSelectedParameters(new ArrayList<VOPricedParameter>());
pm.setRoleSpecificUserPrices(ppr);
return pm;
}
/**
* Returns the product for a vo product.
*
* @param prod
* The product as value object.
* @return The product as domain object.
* @throws Exception
*/
private Product getProduct(final VOService prod) throws Exception {
return runTX(new Callable<Product>() {
@Override
public Product call() throws Exception {
Product doProduct = dm.find(Product.class, prod.getKey());
doProduct.getPriceModel().getRoleSpecificUserPrices().size();
return doProduct;
}
});
}
@Test(expected = OperationNotPermittedException.class)
public void savePriceModelInvalidRolePriceData() throws Exception {
List<VOService> products = svcProv.getSuppliedServices();
VOService product = products.get(0);
VOServiceDetails productDetails = svcProv.getServiceDetails(product);
VORoleDefinition roleDefinition = new VORoleDefinition();
roleDefinition.setKey(Long.MAX_VALUE);
VOPricedRole ppr = new VOPricedRole();
ppr.setRole(roleDefinition);
ppr.setPricePerUser(BigDecimal.valueOf(33L));
VOPriceModel pm = createPriceModelDefinition(
Collections.singletonList(ppr), productDetails);
svcProv.savePriceModel(productDetails, pm);
}
@Test(expected = ValidationException.class)
public void savePriceModelInvalidRolePriceDataNegativePrice()
throws Exception {
List<VOService> products = svcProv.getSuppliedServices();
VOService product = products.get(0);
VOServiceDetails productDetails = svcProv.getServiceDetails(product);
List<VORoleDefinition> roleDefinitions = productDetails
.getTechnicalService().getRoleDefinitions();
Assert.assertEquals(2, roleDefinitions.size());
VORoleDefinition roleDefinition = roleDefinitions.get(0);
VOPricedRole ppr = new VOPricedRole();
ppr.setRole(roleDefinition);
ppr.setPricePerUser(BigDecimal.valueOf(-33L));
VOPriceModel pm = createPriceModelDefinition(
Collections.singletonList(ppr), productDetails);
svcProv.savePriceModel(productDetails, pm);
}
@Test
public void testSavePriceModelOneRolePrice() throws Exception {
VOServiceDetails productDetails = getProductDetails();
List<VORoleDefinition> roleDefinitions = productDetails
.getTechnicalService().getRoleDefinitions();
Assert.assertEquals(2, roleDefinitions.size());
ArrayList<VORoleDefinition> roleDefs = defineRoleDefinitionsForPM(
productDetails, 1);
VOPricedRole ppr = new VOPricedRole();
ppr.setRole(roleDefs.get(0));
ppr.setPricePerUser(BigDecimal.valueOf(33L));
VOPriceModel pm = createPriceModelDefinition(
Collections.singletonList(ppr), productDetails);
final VOServiceDetails savedProduct = svcProv.savePriceModel(
productDetails, pm);
// and also assert domain object integrity and history object existence
assertCreatedProductSettings(roleDefs, savedProduct, 1, false, false,
new BigDecimal(33), false, null);
}
@Test
public void testSavePriceModelOneRolePriceAndUpdateToUpdatePriceValue()
throws Exception {
VOServiceDetails productDetails = getProductDetails();
List<VORoleDefinition> roleDefinitions = productDetails
.getTechnicalService().getRoleDefinitions();
Assert.assertEquals(2, roleDefinitions.size());
ArrayList<VORoleDefinition> roleDefs = defineRoleDefinitionsForPM(
productDetails, 1);
VOPricedRole ppr = new VOPricedRole();
ppr.setRole(roleDefs.get(0));
ppr.setPricePerUser(BigDecimal.valueOf(33L));
VOPriceModel pm = createPriceModelDefinition(
Collections.singletonList(ppr), productDetails);
VOServiceDetails savedProduct = svcProv.savePriceModel(productDetails,
pm);
VOPricedRole voPricedProductRole = savedProduct.getPriceModel()
.getRoleSpecificUserPrices().get(0);
voPricedProductRole.setPricePerUser(BigDecimal.valueOf(123L));
savedProduct = svcProv.savePriceModel(
svcProv.getServiceDetails(savedProduct),
savedProduct.getPriceModel());
// and also assert domain object integrity and history object existence
assertCreatedProductSettings(roleDefs, savedProduct, 1, false, false,
new BigDecimal(123), true, null);
}
// see bug 5586
@Test
public void testSavePriceModelOneRolePriceAndUpdateToUpdatePriceValueCustomerSpecific()
throws Exception {
VOServiceDetails productDetails = getProductDetails();
List<VORoleDefinition> roleDefinitions = productDetails
.getTechnicalService().getRoleDefinitions();
Assert.assertEquals(2, roleDefinitions.size());
ArrayList<VORoleDefinition> roleDefs = defineRoleDefinitionsForPM(
productDetails, 1);
VOPricedRole ppr = new VOPricedRole();
ppr.setRole(productDetails.getTechnicalService().getRoleDefinitions()
.get(1));
ppr.setPricePerUser(BigDecimal.valueOf(33L));
VOPriceModel pm = createPriceModelDefinition(
Collections.singletonList(ppr), productDetails);
VOServiceDetails savedProduct = svcProv.savePriceModel(productDetails,
pm);
VOPricedRole voPricedProductRole = savedProduct.getPriceModel()
.getRoleSpecificUserPrices().get(0);
voPricedProductRole.setPricePerUser(BigDecimal.valueOf(123L));
List<VOPricedRole> currentPricedRoles = savedProduct.getPriceModel()
.getRoleSpecificUserPrices();
VORoleDefinition newRole = productDetails.getTechnicalService()
.getRoleDefinitions().get(0);
VOPricedRole voPricedProductRole2 = new VOPricedRole();
voPricedProductRole2.setRole(newRole);
voPricedProductRole2.setPricePerUser(BigDecimal.valueOf(246L));
currentPricedRoles.add(voPricedProductRole2);
roleDefs.add(0, newRole);
VOOrganization organization = runTX(new Callable<VOOrganization>() {
@Override
public VOOrganization call() throws Exception {
return OrganizationAssembler.toVOOrganization(customer, false,
new LocalizerFacade(localizer, "en"));
}
});
savedProduct = svcProv.savePriceModelForCustomer(
svcProv.getServiceDetails(savedProduct),
savedProduct.getPriceModel(), organization);
// and also assert domain object integrity and history object existence
// for product
Assert.assertEquals(2, savedProduct.getTechnicalService()
.getRoleDefinitions().size());
Product storedProduct = getProduct(savedProduct);
Assert.assertNotNull(storedProduct.getTemplate());
// priced roles
List<PricedProductRole> roleSpecificUserPrices = storedProduct
.getPriceModel().getRoleSpecificUserPrices();
for (PricedProductRole pricedProductRole : roleSpecificUserPrices) {
if (pricedProductRole.getRoleDefinition().getKey() == savedProduct
.getTechnicalService().getRoleDefinitions().get(0).getKey()) {
Assert.assertEquals(0, pricedProductRole.getVersion());
Assert.assertEquals(new BigDecimal(246L),
pricedProductRole.getPricePerUser());
} else {
Assert.assertEquals(1, pricedProductRole.getVersion());
Assert.assertEquals(new BigDecimal(123L),
pricedProductRole.getPricePerUser());
}
}
}
@Test
public void testSavePriceModelOneRolePriceRemoveAllCustomerSpecific()
throws Exception {
final VOServiceDetails productDetails = getProductDetails();
List<VORoleDefinition> roleDefinitions = productDetails
.getTechnicalService().getRoleDefinitions();
Assert.assertEquals(2, roleDefinitions.size());
VOPricedRole ppr = new VOPricedRole();
ppr.setRole(productDetails.getTechnicalService().getRoleDefinitions()
.get(1));
ppr.setPricePerUser(BigDecimal.valueOf(33L));
final VOPriceModel pm = createPriceModelDefinition(
Collections.singletonList(ppr), productDetails);
VOServiceDetails savedProduct = runTX(new Callable<VOServiceDetails>() {
@Override
public VOServiceDetails call() throws Exception {
return svcProv.savePriceModel(productDetails, pm);
}
});
savedProduct.getPriceModel().getRoleSpecificUserPrices().clear();
final VOOrganization orga = runTX(new Callable<VOOrganization>() {
@Override
public VOOrganization call() throws Exception {
return OrganizationAssembler.toVOOrganization(customer, false,
new LocalizerFacade(localizer, "en"));
}
});
savedProduct = svcProv.savePriceModelForCustomer(
svcProv.getServiceDetails(savedProduct),
savedProduct.getPriceModel(), orga);
// and also assert domain object integrity and history object existence
// for product
final VOPriceModel savedPriceModel = savedProduct.getPriceModel();
Assert.assertEquals(0, savedPriceModel.getRoleSpecificUserPrices()
.size());
Product storedProduct = getProduct(savedProduct);
Assert.assertNotNull(storedProduct.getTemplate());
// priced roles - assert that history count is 2 for the removed object
runTX(new Callable<Void>() {
@Override
public Void call() throws Exception {
Query query = dm
.createQuery("SELECT ph FROM PricedProductRoleHistory ph WHERE ph.priceModelObjKey = "
+ savedPriceModel.getKey() + " ORDER BY ph.key");
List<PricedProductRoleHistory> list = ParameterizedTypes.list(
query.getResultList(), PricedProductRoleHistory.class);
Assert.assertEquals(2, list.size());
Assert.assertEquals(ModificationType.DELETE, list.get(1)
.getModtype());
return null;
}
});
}
@Test
public void testSavePriceModelOneRolePriceAndUpdateToCreateValue()
throws Exception {
VOServiceDetails productDetails = getProductDetails();
List<VORoleDefinition> roleDefinitions = productDetails
.getTechnicalService().getRoleDefinitions();
Assert.assertEquals(2, roleDefinitions.size());
ArrayList<VORoleDefinition> roleDefs = defineRoleDefinitionsForPM(
productDetails, 1);
VOPricedRole ppr = new VOPricedRole();
ppr.setRole(roleDefs.get(0));
ppr.setPricePerUser(BigDecimal.valueOf(33L));
VOPriceModel pm = createPriceModelDefinition(
Collections.singletonList(ppr), productDetails);
VOServiceDetails savedProduct = svcProv.savePriceModel(productDetails,
pm);
VOPricedRole newRolePrice = new VOPricedRole();
newRolePrice.setPricePerUser(BigDecimal.valueOf(66L));
newRolePrice.setRole(productDetails.getTechnicalService()
.getRoleDefinitions().get(1));
savedProduct.getPriceModel().getRoleSpecificUserPrices()
.add(newRolePrice);
savedProduct = svcProv.savePriceModel(
svcProv.getServiceDetails(savedProduct),
savedProduct.getPriceModel());
roleDefs.add(newRolePrice.getRole());
// and also assert domain object integrity and history object existence
assertCreatedProductSettings(roleDefs, savedProduct, 2, false, false,
new BigDecimal(33), false, null);
}
@Test
public void testSavePriceModelTwoRolePrices() throws Exception {
VOServiceDetails productDetails = getProductDetails();
List<VORoleDefinition> roleDefinitions = productDetails
.getTechnicalService().getRoleDefinitions();
Assert.assertEquals(2, roleDefinitions.size());
ArrayList<VORoleDefinition> roleDefs = defineRoleDefinitionsForPM(
productDetails, 2);
ArrayList<VOPricedRole> pricedRoles = definePricedProductRoles(roleDefs);
VOPriceModel pm = createPriceModelDefinition(pricedRoles,
productDetails);
final VOServiceDetails savedProduct = svcProv.savePriceModel(
productDetails, pm);
// and also assert domain object integrity and history object existence
assertCreatedProductSettings(roleDefs, savedProduct, 2, false, false,
new BigDecimal(33), false, null);
}
@Test(expected = ValidationException.class)
public void testSavePriceModelTwoRolePricesForOneRole() throws Exception {
VOServiceDetails productDetails = getProductDetails();
List<VORoleDefinition> roleDefinitions = productDetails
.getTechnicalService().getRoleDefinitions();
Assert.assertEquals(2, roleDefinitions.size());
ArrayList<VORoleDefinition> roleDefs = defineRoleDefinitionsForPM(
productDetails, 2);
ArrayList<VOPricedRole> pricedRoles = definePricedProductRoles(roleDefs);
pricedRoles.get(1).setRole(pricedRoles.get(0).getRole());
VOPriceModel pm = createPriceModelDefinition(pricedRoles,
productDetails);
svcProv.savePriceModel(productDetails, pm);
}
@Test
public void testSavePriceModelOneRolePriceAndUpdateToRemoveValue()
throws Exception {
VOServiceDetails productDetails = getProductDetails();
List<VORoleDefinition> roleDefinitions = productDetails
.getTechnicalService().getRoleDefinitions();
Assert.assertEquals(2, roleDefinitions.size());
ArrayList<VORoleDefinition> roleDefs = defineRoleDefinitionsForPM(
productDetails, 2);
ArrayList<VOPricedRole> pricedRoles = definePricedProductRoles(roleDefs);
VOPriceModel pm = createPriceModelDefinition(pricedRoles,
productDetails);
VOServiceDetails savedProduct = svcProv.savePriceModel(productDetails,
pm);
VOPricedRole removedPricedRole = savedProduct.getPriceModel()
.getRoleSpecificUserPrices().remove(1);
productDetails = svcProv.getServiceDetails(savedProduct);
savedProduct = svcProv.savePriceModel(productDetails,
savedProduct.getPriceModel());
assertCreatedProductSettings(roleDefs, savedProduct, 1, false, false,
new BigDecimal(33), true, removedPricedRole);
}
@Test
public void testSavePriceModelForCustomer() throws Exception {
final VOServiceDetails productDetails = getProductDetails();
ArrayList<VORoleDefinition> roleDefs = runTX(new Callable<ArrayList<VORoleDefinition>>() {
@Override
public ArrayList<VORoleDefinition> call() throws Exception {
return defineRoleDefinitionsForPM(productDetails, 2);
}
});
ArrayList<VOPricedRole> pricedRoles = definePricedProductRoles(roleDefs);
final VOPriceModel pm = createPriceModelDefinition(pricedRoles,
productDetails);
final VOOrganization orga = runTX(new Callable<VOOrganization>() {
@Override
public VOOrganization call() throws Exception {
return OrganizationAssembler.toVOOrganization(customer, false,
new LocalizerFacade(localizer, "en"));
}
});
VOServiceDetails savedProduct = runTX(new Callable<VOServiceDetails>() {
@Override
public VOServiceDetails call() throws Exception {
return svcProv.savePriceModelForCustomer(productDetails, pm,
orga);
}
});
// and also assert domain object integrity and history object existence
assertCreatedProductSettings(roleDefs, savedProduct, 2, true, false,
new BigDecimal(33), false, null);
}
@Test
public void testSavePriceModelForSubscription() throws Exception {
VOService template = new VOService();
template.setKey(sub.getProduct().getKey());
VOServiceDetails productDetails = svcProv.getServiceDetails(template);
ArrayList<VORoleDefinition> roleDefs = defineRoleDefinitionsForPM(
productDetails, 2);
ArrayList<VOPricedRole> pricedRoles = definePricedProductRoles(roleDefs);
VOPriceModel pm = createPriceModelDefinition(pricedRoles,
productDetails);
pm.setPeriod(PricingPeriod.DAY);
final VOServiceDetails savedProduct = svcProv
.savePriceModelForSubscription(productDetails, pm);
// and also assert domain object integrity and history object existence
assertCreatedProductSettings(roleDefs, savedProduct, 2, false, true,
new BigDecimal(33), false, null);
}
@Test(expected = ValidationException.class)
public void testSavePriceModelPricedParameterNegativePrice()
throws Exception {
VOServiceDetails productDetails = getProductDetails();
ArrayList<VORoleDefinition> roleDefs = defineRoleDefinitionsForPM(
productDetails, 2);
VOPriceModel pm = createPriceModelForParameter(productDetails,
roleDefs, new BigDecimal(-12), null);
svcProv.savePriceModel(productDetails, pm);
}
@Test(expected = OperationNotPermittedException.class)
public void testSavePriceModelPricedParameterInvalidRole() throws Exception {
VOServiceDetails productDetails = getProductDetails();
ArrayList<VORoleDefinition> roleDefs = defineRoleDefinitionsForPM(
productDetails, 2);
VOPriceModel pm = createPriceModelForParameter(productDetails,
roleDefs, null, Long.valueOf(500L));
svcProv.savePriceModel(productDetails, pm);
}
@Test
public void testSavePriceModelPricedParameter() throws Exception {
VOServiceDetails productDetails = getProductDetails();
ArrayList<VORoleDefinition> roleDefs = defineRoleDefinitionsForPM(
productDetails, 2);
VOPriceModel pm = createPriceModelForParameter(productDetails,
roleDefs, null, null);
final VOServiceDetails savedProduct = svcProv.savePriceModel(
productDetails, pm);
// check that the priced product roles have been created
runTX(new Callable<Void>() {
@Override
public Void call() throws Exception {
Product storedProduct = dm.getReference(Product.class,
savedProduct.getKey());
List<PricedProductRole> storedRolePricesForParam = storedProduct
.getPriceModel().getSelectedParameters().get(0)
.getRoleSpecificUserPrices();
Assert.assertEquals(2, storedRolePricesForParam.size());
PricedProductRole ppr = storedRolePricesForParam.get(0);
Assert.assertEquals(new BigDecimal(33), ppr.getPricePerUser());
Assert.assertEquals(storedProduct.getTechnicalProduct()
.getRoleDefinitions().get(0), ppr.getRoleDefinition());
Assert.assertNull(ppr.getPriceModel());
Assert.assertNull(ppr.getPricedOption());
Assert.assertNotNull(ppr.getPricedParameter());
List<DomainHistoryObject<?>> hist = dm.findHistory(ppr);
Assert.assertEquals(1, hist.size());
Assert.assertEquals(ModificationType.ADD, hist.get(0)
.getModtype());
return null;
}
});
// also validate correctness of the value object
List<VOPricedRole> roleSpecificUserPrices = savedProduct
.getPriceModel().getSelectedParameters().get(0)
.getRoleSpecificUserPrices();
Assert.assertNotNull(roleSpecificUserPrices);
Assert.assertEquals(2, roleSpecificUserPrices.size());
VOPricedRole voPricedProductRole = roleSpecificUserPrices.get(0);
Assert.assertEquals(BigDecimal.valueOf(33),
voPricedProductRole.getPricePerUser());
Assert.assertEquals(savedProduct.getTechnicalService()
.getRoleDefinitions().get(0).getKey(), voPricedProductRole
.getRole().getKey());
}
@Test(expected = ValidationException.class)
public void testSavePriceModelPricedParameterUpdateDuplicateRoleDefinitionReference()
throws Exception {
VOServiceDetails productDetails = getProductDetails();
ArrayList<VORoleDefinition> roleDefs = defineRoleDefinitionsForPM(
productDetails, 2);
VOPriceModel pm = createPriceModelForParameter(productDetails,
roleDefs, null, null);
VOServiceDetails savedProduct = svcProv.savePriceModel(productDetails,
pm);
// update the parameter list and save it again
VOPriceModel updatedPM = savedProduct.getPriceModel();
VOPricedRole voPricedProductRole = updatedPM.getSelectedParameters()
.get(0).getRoleSpecificUserPrices().get(0);
voPricedProductRole.setKey(0);
voPricedProductRole.setPricePerUser(BigDecimal.valueOf(111L));
updatedPM.getSelectedParameters().get(0).getRoleSpecificUserPrices()
.add(voPricedProductRole);
savedProduct = svcProv.savePriceModel(productDetails, updatedPM);
}
@Test
public void testSavePriceModelPricedParameterUpdateRoleDefinitionReference()
throws Exception {
VOServiceDetails productDetails = getProductDetails();
ArrayList<VORoleDefinition> roleDefs = defineRoleDefinitionsForPM(
productDetails, 2);
VOPriceModel pm = createPriceModelForParameter(productDetails,
roleDefs, null, null);
VOServiceDetails savedProduct = svcProv.savePriceModel(productDetails,
pm);
// update the parameter list and save it again
VOPriceModel updatedPM = savedProduct.getPriceModel();
List<VOPricedRole> roleSpecificUserPrices = updatedPM
.getSelectedParameters().get(0).getRoleSpecificUserPrices();
VOPricedRole voPricedProductRole = roleSpecificUserPrices.get(0);
voPricedProductRole.setPricePerUser(BigDecimal.valueOf(111L));
roleSpecificUserPrices.set(0, voPricedProductRole);
savedProduct = svcProv.savePriceModel(productDetails, updatedPM);
// ensure that only one priced product role is stored for this role
// definition (the old one must have been deleted)
Assert.assertEquals(2, roleSpecificUserPrices.size());
VOPricedRole rolePricing = savedProduct.getPriceModel()
.getSelectedParameters().get(0).getRoleSpecificUserPrices()
.get(0);
Assert.assertEquals(BigDecimal.valueOf(111L),
rolePricing.getPricePerUser());
Assert.assertEquals(1, rolePricing.getVersion());
}
@Test
public void testSavePriceModelPricedParameterUpdateRoleDefinitionReferenceRemoveOldAddNew()
throws Exception {
VOServiceDetails productDetails = getProductDetails();
ArrayList<VORoleDefinition> roleDefs = defineRoleDefinitionsForPM(
productDetails, 2);
VOPriceModel pm = createPriceModelForParameter(productDetails,
roleDefs, null, null);
VOServiceDetails savedProduct = svcProv.savePriceModel(productDetails,
pm);
// update the parameter list and save it again
VOPriceModel updatedPM = savedProduct.getPriceModel();
List<VOPricedRole> roleSpecificUserPrices = updatedPM
.getSelectedParameters().get(0).getRoleSpecificUserPrices();
VOPricedRole voPricedProductRole = roleSpecificUserPrices.remove(0);
savedProduct = svcProv.savePriceModel(savedProduct, updatedPM);
updatedPM = savedProduct.getPriceModel();
roleSpecificUserPrices = updatedPM.getSelectedParameters().get(0)
.getRoleSpecificUserPrices();
Assert.assertEquals(1, roleSpecificUserPrices.size());
voPricedProductRole.setKey(0);
voPricedProductRole.setPricePerUser(BigDecimal.valueOf(111L));
roleSpecificUserPrices.add(voPricedProductRole);
savedProduct = svcProv.savePriceModel(savedProduct, updatedPM);
voPricedProductRole = savedProduct.getPriceModel()
.getSelectedParameters().get(0).getRoleSpecificUserPrices()
.get(1);
Assert.assertNotNull(roleSpecificUserPrices);
Assert.assertEquals(2, roleSpecificUserPrices.size());
Assert.assertEquals(BigDecimal.valueOf(111L),
voPricedProductRole.getPricePerUser());
Assert.assertEquals(savedProduct.getTechnicalService()
.getRoleDefinitions().get(0).getKey(), voPricedProductRole
.getRole().getKey());
}
@Test(expected = ValidationException.class)
public void testSavePriceModelPricedOptionNegativePrice() throws Exception {
VOServiceDetails productDetails = getProductDetails();
ArrayList<VORoleDefinition> roleDefs = defineRoleDefinitionsForPM(
productDetails, 2);
VOPriceModel pm = setupPricedOptions(productDetails, roleDefs,
new BigDecimal(-123), null);
svcProv.savePriceModel(productDetails, pm);
}
@Test(expected = OperationNotPermittedException.class)
public void testSavePriceModelPricedOptionInvalidRole() throws Exception {
VOServiceDetails productDetails = getProductDetails();
ArrayList<VORoleDefinition> roleDefs = defineRoleDefinitionsForPM(
productDetails, 2);
VOPriceModel pm = setupPricedOptions(productDetails, roleDefs, null,
Long.valueOf(500L));
svcProv.savePriceModel(productDetails, pm);
}
@Test
public void testSavePriceModelPricedOption() throws Exception {
VOServiceDetails productDetails = getProductDetails();
ArrayList<VORoleDefinition> roleDefs = defineRoleDefinitionsForPM(
productDetails, 2);
VOPriceModel pm = setupPricedOptions(productDetails, roleDefs, null,
null);
final VOServiceDetails savedProduct = svcProv.savePriceModel(
productDetails, pm);
// read and verify the priced option role settings
// check that the priced product roles have been created
runTX(new Callable<Void>() {
@Override
public Void call() throws Exception {
Product storedProduct = dm.getReference(Product.class,
savedProduct.getKey());
List<PricedProductRole> storedRolePricesForOption = storedProduct
.getPriceModel().getSelectedParameters().get(0)
.getPricedOptionList().get(0)
.getRoleSpecificUserPrices();
Assert.assertEquals(2, storedRolePricesForOption.size());
PricedProductRole ppr = storedRolePricesForOption.get(0);
Assert.assertEquals(new BigDecimal(33), ppr.getPricePerUser());
Assert.assertEquals(storedProduct.getTechnicalProduct()
.getRoleDefinitions().get(0), ppr.getRoleDefinition());
Assert.assertNull(ppr.getPriceModel());
Assert.assertNotNull(ppr.getPricedOption());
Assert.assertNull(ppr.getPricedParameter());
List<DomainHistoryObject<?>> hist = dm.findHistory(ppr);
Assert.assertEquals(1, hist.size());
Assert.assertEquals(ModificationType.ADD, hist.get(0)
.getModtype());
return null;
}
});
// and also check the value object representation
List<VOPricedRole> roleSpecificUserPrices = savedProduct
.getPriceModel().getSelectedParameters().get(0)
.getPricedOptions().get(0).getRoleSpecificUserPrices();
Assert.assertNotNull(roleSpecificUserPrices);
Assert.assertEquals(2, roleSpecificUserPrices.size());
VOPricedRole voPricedProductRole = roleSpecificUserPrices.get(0);
Assert.assertEquals(BigDecimal.valueOf(33L),
voPricedProductRole.getPricePerUser());
Assert.assertEquals(savedProduct.getTechnicalService()
.getRoleDefinitions().get(0).getKey(), voPricedProductRole
.getRole().getKey());
}
@Test
public void testSavePriceModelPricedOptionUpdateCreateNewRemoveOld()
throws Exception {
runTX(new Callable<Void>() {
@Override
public Void call() throws Exception {
Scenario.setup(container, false);
return null;
}
});
container.login(Scenario.getSupplierAdminUser().getKey(),
ROLE_SERVICE_MANAGER);
supplierAndProvider = Scenario.getSupplier();
String productId = Scenario.getProduct().getProductId();
List<VOService> services = svcProv.getSuppliedServices();
VOServiceDetails serviceDetails = null;
for (VOService voService : services) {
if (voService.getServiceId().equals(productId)) {
serviceDetails = svcProv.getServiceDetails(voService);
}
}
if (serviceDetails == null) {
Assert.fail("Service not found.");
return;
}
VOPriceModel priceModel = serviceDetails.getPriceModel();
List<VOPricedRole> roleSpecificUserPrices = priceModel
.getSelectedParameters().get(2).getPricedOptions().get(0)
.getRoleSpecificUserPrices();
roleSpecificUserPrices.remove(0);
priceModel = serviceDetails.getPriceModel();
roleSpecificUserPrices = priceModel.getSelectedParameters().get(2)
.getPricedOptions().get(0).getRoleSpecificUserPrices();
VOPricedRole pricedRole = new VOPricedRole();
pricedRole.setPricePerUser(BigDecimal.valueOf(11111L));
VORoleDefinition role = serviceDetails.getTechnicalService()
.getRoleDefinitions().get(1);
pricedRole.setRole(role);
roleSpecificUserPrices.add(pricedRole);
VOServiceDetails savedProduct = svcProv.savePriceModel(serviceDetails,
priceModel);
roleSpecificUserPrices = priceModel.getSelectedParameters().get(2)
.getPricedOptions().get(0).getRoleSpecificUserPrices();
Assert.assertEquals(1, roleSpecificUserPrices.size());
final VOPricedRole voPricedProductRole2 = savedProduct.getPriceModel()
.getSelectedParameters().get(2).getPricedOptions().get(0)
.getRoleSpecificUserPrices().get(0);
// new entry must have version 0 with new price
Assert.assertEquals(0, voPricedProductRole2.getVersion());
Assert.assertEquals(BigDecimal.valueOf(11111L),
voPricedProductRole2.getPricePerUser());
Assert.assertEquals(savedProduct.getTechnicalService()
.getRoleDefinitions().get(1).getKey(), voPricedProductRole2
.getRole().getKey());
// and assert that the latest history entry for that priced role also
// has the correct pricing
runTX(new Callable<Void>() {
@Override
public Void call() throws Exception {
PricedProductRole role = new PricedProductRole();
role.setKey(voPricedProductRole2.getKey());
List<PricedProductRoleHistory> list = ParameterizedTypes.list(
dm.findHistory(role), PricedProductRoleHistory.class);
Assert.assertEquals(1, list.size());
Assert.assertEquals(new BigDecimal(11111L), list.get(0)
.getPricePerUser());
Assert.assertEquals(ModificationType.ADD, list.get(0)
.getModtype());
return null;
}
});
}
@Test
public void testSavePriceModelPricedOptionUpdateExistingEntry()
throws Exception {
VOServiceDetails productDetails = getProductDetails();
ArrayList<VORoleDefinition> roleDefs = defineRoleDefinitionsForPM(
productDetails, 2);
VOPriceModel pm = setupPricedOptions(productDetails, roleDefs, null,
null);
VOServiceDetails savedProduct = svcProv.savePriceModel(productDetails,
pm);
pm = savedProduct.getPriceModel();
VOPricedRole ppr = pm.getSelectedParameters().get(0).getPricedOptions()
.get(0).getRoleSpecificUserPrices().get(0);
ppr.setPricePerUser(BigDecimal.valueOf(11111L));
savedProduct = svcProv.savePriceModel(savedProduct, pm);
VOPricedRole voPricedProductRole = savedProduct.getPriceModel()
.getSelectedParameters().get(0).getPricedOptions().get(0)
.getRoleSpecificUserPrices().get(0);
// modified entry must have version 1 with new price
Assert.assertEquals(1, voPricedProductRole.getVersion());
Assert.assertEquals(BigDecimal.valueOf(11111L),
voPricedProductRole.getPricePerUser());
Assert.assertEquals(savedProduct.getTechnicalService()
.getRoleDefinitions().get(0).getKey(), voPricedProductRole
.getRole().getKey());
VOPricedRole voPricedProductRole1 = savedProduct.getPriceModel()
.getSelectedParameters().get(0).getPricedOptions().get(0)
.getRoleSpecificUserPrices().get(1);
// assert remaining one is unchanged in version 0 with old pricing 66
Assert.assertEquals(BigDecimal.valueOf(66L),
voPricedProductRole1.getPricePerUser());
Assert.assertEquals(0, voPricedProductRole1.getVersion());
Assert.assertEquals(savedProduct.getTechnicalService()
.getRoleDefinitions().get(1).getKey(), voPricedProductRole1
.getRole().getKey());
}
/**
* Configures a price model with priced product roles for a priced
* parameter.
*
* @param productDetails
* The details of the affected product.
* @param roleDefs
* The role definitions to use in the priced roles.
* @param rolePrice
* The price to be set for the priced role.
* @param roleKey
* The key to be set for the role definition.
* @return A price model containing priced roles for a priced parameter.
*/
private VOPriceModel createPriceModelForParameter(
VOServiceDetails productDetails,
ArrayList<VORoleDefinition> roleDefs, BigDecimal rolePrice,
Long roleKey) {
ArrayList<VOPricedRole> pricedRoles = definePricedProductRoles(roleDefs);
if (rolePrice != null) {
pricedRoles.get(0).setPricePerUser(rolePrice);
}
if (roleKey != null) {
pricedRoles.get(0).getRole().setKey(roleKey.longValue());
}
VOPriceModel pm = createPriceModelDefinition(pricedRoles,
productDetails);
pm.setRoleSpecificUserPrices(new ArrayList<VOPricedRole>());
VOPricedParameter pricedParameter = new VOPricedParameter();
pricedParameter.setPricePerSubscription(BigDecimal.valueOf(12L));
pricedParameter.setPricePerUser(BigDecimal.valueOf(999L));
pricedParameter.setVoParameterDef(productDetails.getParameters().get(0)
.getParameterDefinition());
pricedParameter.setRoleSpecificUserPrices(pricedRoles);
pm.setSelectedParameters(Collections.singletonList(pricedParameter));
return pm;
}
/**
* Configures a price model to use a priced option with priced product
* roles.
*
* @param productDetails
* The product details for the affected product.
* @param roleDefs
* The role definitions for the price model.
* @param priceForRole
* The option price per user.
* @param roleKey
* The key to be set for the role definition.
* @return The price model containing the priced option.
*/
private VOPriceModel setupPricedOptions(VOServiceDetails productDetails,
ArrayList<VORoleDefinition> roleDefs, BigDecimal priceForRole,
Long roleKey) {
ArrayList<VOPricedRole> pricedRoles = definePricedProductRoles(roleDefs);
if (priceForRole != null) {
pricedRoles.get(0).setPricePerUser(priceForRole);
}
if (roleKey != null) {
pricedRoles.get(0).getRole().setKey(roleKey.longValue());
}
VOPriceModel pm = createPriceModelDefinition(pricedRoles,
productDetails);
pm.setRoleSpecificUserPrices(new ArrayList<VOPricedRole>());
VOPricedParameter pricedParameter = new VOPricedParameter();
pricedParameter.setPricePerSubscription(BigDecimal.valueOf(12L));
pricedParameter.setPricePerUser(BigDecimal.valueOf(999L));
List<VOParameter> parameters = productDetails.getParameters();
for (VOParameter voParameter : parameters) {
if (voParameter.getParameterDefinition().getValueType() == ParameterValueType.ENUMERATION) {
pricedParameter.setVoParameterDef(voParameter
.getParameterDefinition());
}
}
VOPricedOption vpo = new VOPricedOption();
vpo.setParameterOptionKey(productDetails.getTechnicalService()
.getParameterDefinitions().get(1).getParameterOptions().get(0)
.getKey());
vpo.setPricePerUser(BigDecimal.valueOf(33L));
vpo.setPricePerSubscription(BigDecimal.ZERO);
pricedParameter.setPricedOptions(Collections.singletonList(vpo));
pm.setSelectedParameters(Collections.singletonList(pricedParameter));
vpo.setRoleSpecificUserPrices(pricedRoles);
return pm;
}
/**
* Retrieves the product details.
*
* @return The product details.
*/
private VOServiceDetails getProductDetails() throws Exception {
List<VOService> products = svcProv.getSuppliedServices();
Assert.assertEquals(1, products.size());
VOService product = products.get(0);
VOServiceDetails productDetails = svcProv.getServiceDetails(product);
return productDetails;
}
/**
* Defines role definitions.
*
* @param productDetails
* The product details to retrieve the available role definitions
* from.
* @param amount
* The number of definitions to be created, can be 1 or 2.
* @return A list of role definitions to be used for the price model
* definition.
*/
private ArrayList<VORoleDefinition> defineRoleDefinitionsForPM(
VOServiceDetails productDetails, int amount) {
List<VORoleDefinition> roleDefinitions = productDetails
.getTechnicalService().getRoleDefinitions();
Assert.assertEquals(2, roleDefinitions.size());
VORoleDefinition roleDefinition1 = roleDefinitions.get(0);
VORoleDefinition roleDefinition2 = roleDefinitions.get(1);
ArrayList<VORoleDefinition> roleDefs = new ArrayList<VORoleDefinition>();
roleDefs.add(roleDefinition1);
if (amount == 2) {
roleDefs.add(roleDefinition2);
}
return roleDefs;
}
/**
* Defines the priced product roles definitions to be used for the test.
*
* @param roleDefs
* The role definitions serving as base.
* @return The priced product roles.
*/
private ArrayList<VOPricedRole> definePricedProductRoles(
ArrayList<VORoleDefinition> roleDefs) {
VOPricedRole ppr = new VOPricedRole();
ppr.setRole(roleDefs.get(0));
ppr.setPricePerUser(BigDecimal.valueOf(33L));
VOPricedRole ppr2 = new VOPricedRole();
ppr2.setRole(roleDefs.get(1));
ppr2.setPricePerUser(BigDecimal.valueOf(66L));
ArrayList<VOPricedRole> pricedRoles = new ArrayList<VOPricedRole>();
pricedRoles.add(ppr);
pricedRoles.add(ppr2);
return pricedRoles;
}
@Test
public void testModifyPricedParam() throws Exception {
VOServiceDetails productDetails = getProductDetails();
ArrayList<VORoleDefinition> roleDefs = defineRoleDefinitionsForPM(
productDetails, 2);
VOPriceModel pm = createPriceModelForParameter(productDetails,
roleDefs, null, null);
VOServiceDetails savedProduct = svcProv.savePriceModel(productDetails,
pm);
VOPriceModel storedPM = savedProduct.getPriceModel();
VOPricedParameter voPricedParameter = storedPM.getSelectedParameters()
.get(0);
Assert.assertEquals(BigDecimal.valueOf(999),
voPricedParameter.getPricePerUser());
voPricedParameter.setPricePerUser(BigDecimal.ONE);
savedProduct = svcProv.savePriceModel(productDetails, storedPM);
storedPM = savedProduct.getPriceModel();
voPricedParameter = storedPM.getSelectedParameters().get(0);
Assert.assertEquals(BigDecimal.ONE, voPricedParameter.getPricePerUser());
}
@Test
public void testModifyPricedParamOption() throws Exception {
VOServiceDetails productDetails = getProductDetails();
ArrayList<VORoleDefinition> roleDefs = defineRoleDefinitionsForPM(
productDetails, 2);
VOPriceModel pm = setupPricedOptions(productDetails, roleDefs, null,
null);
VOServiceDetails savedProduct = svcProv.savePriceModel(productDetails,
pm);
VOPriceModel storedPM = savedProduct.getPriceModel();
VOPricedOption voPricedOption = storedPM.getSelectedParameters().get(0)
.getPricedOptions().get(0);
Assert.assertEquals(BigDecimal.valueOf(33),
voPricedOption.getPricePerUser());
voPricedOption.setPricePerUser(BigDecimal.valueOf(1));
savedProduct = svcProv.savePriceModel(savedProduct, storedPM);
storedPM = savedProduct.getPriceModel();
voPricedOption = storedPM.getSelectedParameters().get(0)
.getPricedOptions().get(0);
Assert.assertEquals(BigDecimal.valueOf(1),
voPricedOption.getPricePerUser());
}
}
|
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
// Code generated by Microsoft (R) AutoRest Code Generator.
package com.azure.resourcemanager.compute.models;
import com.azure.core.annotation.Fluent;
import com.fasterxml.jackson.annotation.JsonProperty;
/**
* Specifies the Spot-Try-Restore properties for the virtual machine scale set. <br><br> With this property
* customer can enable or disable automatic restore of the evicted Spot VMSS VM instances opportunistically based on
* capacity availability and pricing constraint.
*/
@Fluent
public final class SpotRestorePolicy {
/*
* Enables the Spot-Try-Restore feature where evicted VMSS SPOT instances
* will be tried to be restored opportunistically based on capacity
* availability and pricing constraints
*/
@JsonProperty(value = "enabled")
private Boolean enabled;
/*
* Timeout value expressed as an ISO 8601 time duration after which the
* platform will not try to restore the VMSS SPOT instances
*/
@JsonProperty(value = "restoreTimeout")
private String restoreTimeout;
/**
* Get the enabled property: Enables the Spot-Try-Restore feature where evicted VMSS SPOT instances will be tried to
* be restored opportunistically based on capacity availability and pricing constraints.
*
* @return the enabled value.
*/
public Boolean enabled() {
return this.enabled;
}
/**
* Set the enabled property: Enables the Spot-Try-Restore feature where evicted VMSS SPOT instances will be tried to
* be restored opportunistically based on capacity availability and pricing constraints.
*
* @param enabled the enabled value to set.
* @return the SpotRestorePolicy object itself.
*/
public SpotRestorePolicy withEnabled(Boolean enabled) {
this.enabled = enabled;
return this;
}
/**
* Get the restoreTimeout property: Timeout value expressed as an ISO 8601 time duration after which the platform
* will not try to restore the VMSS SPOT instances.
*
* @return the restoreTimeout value.
*/
public String restoreTimeout() {
return this.restoreTimeout;
}
/**
* Set the restoreTimeout property: Timeout value expressed as an ISO 8601 time duration after which the platform
* will not try to restore the VMSS SPOT instances.
*
* @param restoreTimeout the restoreTimeout value to set.
* @return the SpotRestorePolicy object itself.
*/
public SpotRestorePolicy withRestoreTimeout(String restoreTimeout) {
this.restoreTimeout = restoreTimeout;
return this;
}
/**
* Validates the instance.
*
* @throws IllegalArgumentException thrown if the instance is not valid.
*/
public void validate() {
}
}
|
/*
* @(#)FloatConverter.java 3/9/2005
*
* Copyright 2002 - 2005 JIDE Software Inc. All rights reserved.
*/
package com.jidesoft.converter;
import java.text.NumberFormat;
/**
* Converter which converts Float to String and converts it back.
*/
public class FloatConverter extends NumberConverter {
public FloatConverter() {
}
public FloatConverter(NumberFormat format) {
super(format);
}
public Object fromString(String string, ConverterContext context) {
Number number = parseNumber(string);
return number != null ? number.floatValue() : null;
}
public boolean supportFromString(String string, ConverterContext context) {
return true;
}
}
|
package net.silentchaos512.mechanisms.init;
import net.minecraft.inventory.container.Container;
import net.minecraft.inventory.container.ContainerType;
import net.minecraft.tileentity.TileEntityType;
import net.silentchaos512.mechanisms.block.AbstractMachineBaseTileEntity;
import net.silentchaos512.mechanisms.block.alloysmelter.AlloySmelterContainer;
import net.silentchaos512.mechanisms.block.alloysmelter.AlloySmelterTileEntity;
import net.silentchaos512.mechanisms.block.crusher.CrusherContainer;
import net.silentchaos512.mechanisms.block.crusher.CrusherTileEntity;
import net.silentchaos512.mechanisms.util.MachineTier;
import net.silentchaos512.utils.Lazy;
import java.util.Objects;
import java.util.function.Supplier;
public class MachineType<T extends AbstractMachineBaseTileEntity, B extends T, S extends T, C extends Container> {
public static final MachineType<AlloySmelterTileEntity, AlloySmelterTileEntity.Basic, AlloySmelterTileEntity, AlloySmelterContainer> ALLOY_SMELTER = new MachineType<>(
() -> TileEntityType.Builder.create(AlloySmelterTileEntity.Basic::new, ModBlocks.basicAlloySmelter),
() -> TileEntityType.Builder.create(AlloySmelterTileEntity::new, ModBlocks.alloySmelter),
(id, inv) -> new AlloySmelterContainer(id, inv, MachineTier.BASIC),
(id, inv) -> new AlloySmelterContainer(id, inv, MachineTier.STANDARD)
);
public static final MachineType<CrusherTileEntity, CrusherTileEntity.Basic, CrusherTileEntity, CrusherContainer> CRUSHER = new MachineType<>(
() -> TileEntityType.Builder.create(CrusherTileEntity.Basic::new, ModBlocks.basicCrusher),
() -> TileEntityType.Builder.create(CrusherTileEntity::new, ModBlocks.crusher),
(id, inv) -> new CrusherContainer(id, inv, MachineTier.BASIC),
(id, inv) -> new CrusherContainer(id, inv, MachineTier.STANDARD)
);
private final Lazy<TileEntityType<B>> basicTileEntityType;
private final Lazy<TileEntityType<S>> standardTileEntityType;
private final Lazy<ContainerType<C>> basicContainerType;
private final Lazy<ContainerType<C>> standardContainerType;
public MachineType(
Supplier<TileEntityType.Builder<B>> basic,
Supplier<TileEntityType.Builder<S>> standard,
ContainerType.IFactory<C> basicContainer,
ContainerType.IFactory<C> standardContainer
) {
this.basicTileEntityType = Lazy.of(() -> basic.get().build(null));
this.standardTileEntityType = Lazy.of(() -> standard.get().build(null));
this.basicContainerType = Lazy.of(() -> new ContainerType<>(basicContainer));
this.standardContainerType = Lazy.of(() -> new ContainerType<>(standardContainer));
}
public TileEntityType<? extends T> getTileEntityType(MachineTier tier) {
switch (tier) {
case BASIC:
return basicTileEntityType.get();
case STANDARD:
return standardTileEntityType.get();
default:
throw new IllegalArgumentException("Unknown MachineTier: " + tier);
}
}
public TileEntityType<B> getBasicTileEntityType() {
return basicTileEntityType.get();
}
public TileEntityType<S> getStandardTileEntityType() {
return standardTileEntityType.get();
}
public T create(MachineTier tier) {
return Objects.requireNonNull(getTileEntityType(tier).create());
}
public ContainerType<C> getContainerType(MachineTier tier) {
switch (tier) {
case BASIC:
return basicContainerType.get();
case STANDARD:
return standardContainerType.get();
default:
throw new IllegalArgumentException("Unknown MachineTier: " + tier);
}
}
}
|
package com.github.sviengine.particle;
import com.github.sviengine.SVIEngineDesc;
import com.github.sviengine.SVIEngineThreadProtection;
import com.github.sviengine.animation.SVIAnimation;
import com.github.sviengine.basetype.SVIColor;
import com.github.sviengine.basetype.SVIImage;
import com.github.sviengine.basetype.SVIVector3;
import com.github.sviengine.glsurface.SVIGLSurface;
import com.github.sviengine.particle.SVIParticles;
/**
* particles information
*/
public class SVIParticles {
public interface ParticleBlendType {
public static final int BLEND_MULTIPLY = 0;
public static final int BLEND_ADD = 1;
}
public SVIParticles() {
this(null);
}
public SVIParticles(SVIGLSurface surface) {
surface = SVIGLSurface.getSurface(surface);
mNativeHandle = -1;
initialize();
mNativeHandle = nativeCreateParticles(surface.getNativeHandle());
}
protected void initialize() {
SVIEngineThreadProtection.validateMainThread();
mParticleCount = 0;
mTextureFileName = null;
mMaxDuration = 0;
mRandomDuration = 0;
mBlendType = ParticleBlendType.BLEND_MULTIPLY;
mScaleKeyFrameDuration = 0;
mScaleKeyFrameInterpolaterType = SVIAnimation.InterpolatorType.ACCELERATE_DECELERATE;
mColorKeyFrameDuration = 0;
mColorKeyFrameInterpolaterType = SVIAnimation.InterpolatorType.ACCELERATE_DECELERATE;
mPositionKeyFrameDuration = 0;
mPositionKeyFrameInterpolaterType = SVIAnimation.InterpolatorType.ACCELERATE_DECELERATE;
/// create member field
mDefaultPosition = new SVIVector3();
mRandomPosition = new SVIVector3();
mMaxColor = new SVIColor();
mRandomColor = new SVIColor();
mDefaultGravity = new SVIVector3();
mRandomGravity = new SVIVector3();
mDefaultForce = new SVIVector3();
mRandomForce = new SVIVector3();
mMaxParticleSize = new SVIVector3();
mRandomParticleSize = new SVIVector3();
/// set member field value
mDefaultPosition.mX = mDefaultPosition.mY = mDefaultPosition.mZ = 0.0f;
mRandomPosition.mX = mRandomPosition.mY = mRandomPosition.mZ = 0.0f;
mMaxColor.mR = mMaxColor.mG = mMaxColor.mB = mMaxColor.mA = 1.0f;
mRandomColor.mR = mRandomColor.mG = mRandomColor.mB = mRandomColor.mA = 0.0f;
mDefaultGravity.mX = mDefaultGravity.mY = mDefaultGravity.mZ = 0.0f;
mRandomGravity.mX = mRandomGravity.mY = mRandomGravity.mZ = 0.0f;
mDefaultForce.mX = mDefaultForce.mY = mDefaultForce.mZ = 0.0f;
mRandomForce.mX = mRandomForce.mY = mRandomForce.mZ = 0.0f;
mMaxMass = 1.0f;
mRandomMass = 0.0f;
mMaxParticleSize.mX = mMaxParticleSize.mY = mMaxParticleSize.mZ = 1.0f;
mRandomParticleSize.mX = mRandomParticleSize.mY = mRandomParticleSize.mZ = 0.0f;
mImage = null;
mScaleKeyFrameDuration = 0;
mScaleKeyFrameInterpolaterType = SVIAnimation.InterpolatorType.ACCELERATE_DECELERATE;
mColorKeyFrameDuration = 0;
mColorKeyFrameInterpolaterType = SVIAnimation.InterpolatorType.ACCELERATE_DECELERATE;
mPositionKeyFrameDuration = 0;
mPositionKeyFrameInterpolaterType = SVIAnimation.InterpolatorType.ACCELERATE_DECELERATE;
}
protected void finalize() throws Throwable {
if (mNativeHandle != -1) {
mImage = null;
//nativeDestroy(mNativeHandle);
mNativeHandle = -1;
}
super.finalize();
}
public void copy(SVIParticles info) {
info.mParticleCount = mParticleCount;
info.mTextureFileName = mTextureFileName;
info.mMaxDuration = mMaxDuration;
info.mRandomDuration = mRandomDuration;
info.mScaleKeyFrameDuration = mScaleKeyFrameDuration;
info.mScaleKeyFrameInterpolaterType = mScaleKeyFrameInterpolaterType;
info.mColorKeyFrameDuration = mColorKeyFrameDuration;
info.mColorKeyFrameInterpolaterType = mColorKeyFrameInterpolaterType;
info.mPositionKeyFrameDuration = mPositionKeyFrameDuration;
info.mPositionKeyFrameInterpolaterType = mPositionKeyFrameInterpolaterType;
info.mDefaultPosition.mX = mDefaultPosition.mX;
info.mDefaultPosition.mY = mDefaultPosition.mY;
info.mDefaultPosition.mZ = mDefaultPosition.mZ;
info.mRandomPosition.mX = mRandomPosition.mX;
info.mRandomPosition.mY = mRandomPosition.mY;
info.mRandomPosition.mZ = mRandomPosition.mZ;
info.mMaxColor.mR = mMaxColor.mR;
info.mMaxColor.mG = mMaxColor.mG;
info.mMaxColor.mB = mMaxColor.mB;
info.mMaxColor.mA = mMaxColor.mA;
info.mRandomColor.mR = mRandomColor.mR;
info.mRandomColor.mG = mRandomColor.mG;
info.mRandomColor.mB = mRandomColor.mB;
info.mRandomColor.mA = mRandomColor.mA;
info.mDefaultGravity.mX = mDefaultGravity.mX;
info.mDefaultGravity.mY = mDefaultGravity.mY;
info.mDefaultGravity.mZ = mDefaultGravity.mZ;
info.mRandomGravity.mX = mRandomGravity.mX;
info.mRandomGravity.mY = mRandomGravity.mY;
info.mRandomGravity.mZ = mRandomGravity.mZ;
info.mDefaultForce.mX = mDefaultForce.mX;
info.mDefaultForce.mY = mDefaultForce.mY;
info.mDefaultForce.mZ = mDefaultForce.mZ;
info.mRandomForce.mX = mRandomForce.mX;
info.mRandomForce.mY = mRandomForce.mY;
info.mRandomForce.mZ = mRandomForce.mZ;
info.mMaxMass = mMaxMass;
info.mRandomMass = mRandomMass;
info.mMaxParticleSize.mX = mMaxParticleSize.mX;
info.mMaxParticleSize.mY = mMaxParticleSize.mY;
info.mMaxParticleSize.mZ = mMaxParticleSize.mZ;
info.mRandomParticleSize.mX = mRandomParticleSize.mX;
info.mRandomParticleSize.mY = mRandomParticleSize.mY;
info.mRandomParticleSize.mZ = mRandomParticleSize.mZ;
info.mImage = mImage;
mScaleKeyFrameDuration = 0;
mScaleKeyFrameInterpolaterType = SVIAnimation.InterpolatorType.ACCELERATE_DECELERATE;
mColorKeyFrameDuration = 0;
mColorKeyFrameInterpolaterType = SVIAnimation.InterpolatorType.ACCELERATE_DECELERATE;
mPositionKeyFrameDuration = 0;
mPositionKeyFrameInterpolaterType = SVIAnimation.InterpolatorType.ACCELERATE_DECELERATE;
}
public void setTextureFile(String textureFileName, SVIImage image) {
SVIEngineThreadProtection.validateMainThread();
mTextureFileName = textureFileName;
mImage = image;
nativeSetTextureFile(mNativeHandle, mTextureFileName, mImage.getNativeHandle());
}
public void setParticleCount(int particleCount) {
SVIEngineThreadProtection.validateMainThread();
mParticleCount = particleCount;
nativeSetParticleCount(mNativeHandle, mParticleCount);
}
public void setMaxDuration(int duration) {
SVIEngineThreadProtection.validateMainThread();
mMaxDuration = duration;
nativeSetMaxDuration(mNativeHandle, duration);
}
public void setRandomDuration(int duration) {
SVIEngineThreadProtection.validateMainThread();
mRandomDuration = duration;
nativeSetRandomDuration(mNativeHandle, duration);
}
public void setMaxSize(float x, float y, float z) {
SVIEngineThreadProtection.validateMainThread();
mMaxParticleSize.mX = x;
mMaxParticleSize.mY = y;
mMaxParticleSize.mZ = z;
nativeSetMaxSize(mNativeHandle, x, y, z);
}
public void setRandomSize(float x, float y, float z) {
SVIEngineThreadProtection.validateMainThread();
mRandomParticleSize.mX = x;
mRandomParticleSize.mY = y;
mRandomParticleSize.mZ = z;
nativeSetRandomSize(mNativeHandle, x, y, z);
}
public void setDefaultPosition(float x, float y, float z) {
SVIEngineThreadProtection.validateMainThread();
mDefaultPosition.mX = x;
mDefaultPosition.mY = y;
mDefaultPosition.mZ = z;
nativeSetDefaultPosition(mNativeHandle, x, y, z);
}
public void setRandomPosition(float x, float y, float z) {
SVIEngineThreadProtection.validateMainThread();
mRandomPosition.mX = x;
mRandomPosition.mY = y;
mRandomPosition.mZ = z;
nativeSetRandomPosition(mNativeHandle, x, y, z);
}
public void setMaxColor(float r, float g, float b, float a) {
SVIEngineThreadProtection.validateMainThread();
mMaxColor.mR = r;
mMaxColor.mG = g;
mMaxColor.mB = b;
mMaxColor.mA = a;
nativeSetMaxColor(mNativeHandle, r, g, b, a);
}
public void setRandomColor(float r, float g, float b, float a) {
SVIEngineThreadProtection.validateMainThread();
mRandomColor.mR = r;
mRandomColor.mG = g;
mRandomColor.mB = b;
mRandomColor.mA = a;
nativeSetRandomColor(mNativeHandle, r, g, b, a);
}
public void setDefaultGravity(float x, float y, float z) {
SVIEngineThreadProtection.validateMainThread();
mDefaultGravity.mX = x;
mDefaultGravity.mY = y;
mDefaultGravity.mZ = z;
nativeSetDefaultGravity(mNativeHandle, x, y, z);
}
public void setRandomGravity(float x, float y, float z) {
SVIEngineThreadProtection.validateMainThread();
mRandomGravity.mX = x;
mRandomGravity.mY = y;
mRandomGravity.mZ = z;
nativeSetRandomGravity(mNativeHandle, x, y, z);
}
public void setDefaultForce(float x, float y, float z) {
SVIEngineThreadProtection.validateMainThread();
mDefaultForce.mX = x;
mDefaultForce.mY = y;
mDefaultForce.mZ = z;
nativeSetDefaultForce(mNativeHandle, x, y, z);
}
public void setRandomForce(float x, float y, float z) {
SVIEngineThreadProtection.validateMainThread();
mRandomForce.mX = x;
mRandomForce.mY = y;
mRandomForce.mZ = z;
nativeSetRandomForce(mNativeHandle, x, y, z);
}
public void setMaxMass(float mass) {
SVIEngineThreadProtection.validateMainThread();
mMaxMass = mass;
nativeSetMaxMass(mNativeHandle, mass);
}
public void setRandomMass(float mass) {
SVIEngineThreadProtection.validateMainThread();
mRandomMass = mass;
nativeSetRandomMass(mNativeHandle, mass);
}
public void setScaleKeyFrameAnimationProperty(int duration, int interpolatorType, boolean keyValueReset) {
SVIEngineThreadProtection.validateMainThread();
mScaleKeyFrameDuration = duration;
mScaleKeyFrameInterpolaterType = interpolatorType;
int reset = 0;
if(keyValueReset == true)
reset = 1;
nativeSetScaleKeyFrameAnimationProperty(mNativeHandle, mScaleKeyFrameDuration, mScaleKeyFrameInterpolaterType, reset);
}
public void setColorKeyFrameAnimationProperty(int duration, int interpolatorType, boolean keyValueReset) {
SVIEngineThreadProtection.validateMainThread();
mColorKeyFrameDuration = duration;
mColorKeyFrameInterpolaterType = interpolatorType;
int reset = 0;
if(keyValueReset == true)
reset = 1;
nativeSetColorKeyFrameAnimationProperty(mNativeHandle, mColorKeyFrameDuration, mColorKeyFrameInterpolaterType, reset);
}
public void setPositionKeyFrameAnimationProperty(int duration, int interpolatorType, boolean keyValueReset) {
SVIEngineThreadProtection.validateMainThread();
mPositionKeyFrameDuration = duration;
mPositionKeyFrameInterpolaterType = interpolatorType;
int reset = 0;
if(keyValueReset == true)
reset = 1;
nativeSetPositionKeyFrameAnimationProperty(mNativeHandle, mPositionKeyFrameDuration, mPositionKeyFrameInterpolaterType, reset);
}
public void addScaleKeyFrame(float keyTime, SVIVector3 scale) {
SVIEngineThreadProtection.validateMainThread();
nativeAddScaleKeyFrame(mNativeHandle, keyTime, scale.mX, scale.mY, scale.mZ);
}
public void addColorKeyFrame(float keyTime, SVIColor color) {
SVIEngineThreadProtection.validateMainThread();
nativeAddColorKeyFrame(mNativeHandle, keyTime, color.mR, color.mG, color.mB, color.mA);
}
public void addPositionKeyFrame(float keyTime, SVIVector3 position) {
SVIEngineThreadProtection.validateMainThread();
nativeAddPositionKeyFrame(mNativeHandle, keyTime, position.mX, position.mY, position.mZ);
}
public int getNativeHandle() {
return mNativeHandle;
}
protected int mParticleCount;
protected int mMaxDuration;
protected int mRandomDuration;
protected int mBlendType;
protected int mScaleKeyFrameDuration;
protected int mScaleKeyFrameInterpolaterType;
protected int mColorKeyFrameDuration;
protected int mColorKeyFrameInterpolaterType;
protected int mPositionKeyFrameDuration;
protected int mPositionKeyFrameInterpolaterType;
protected SVIVector3 mDefaultPosition;
protected SVIVector3 mRandomPosition;
protected SVIColor mMaxColor;
protected SVIColor mRandomColor;
protected SVIVector3 mDefaultGravity;
protected SVIVector3 mRandomGravity;
protected SVIVector3 mDefaultForce;
protected SVIVector3 mRandomForce;
protected float mMaxMass;
protected float mRandomMass;
protected SVIVector3 mMaxParticleSize;
protected SVIVector3 mRandomParticleSize;
protected String mTextureFileName;
protected SVIImage mImage;
private int mNativeHandle;
/*****************************************************************************************************************/
/**
* SVIParticles native interface.
*
*/
static {
System.loadLibrary(SVIEngineDesc.mName);
}
private static native int nativeCreateParticles(int surfaceNativeHandle);
protected static native void nativeSetTextureFile(int particlesHandle, String textureFileName, int imageHandle);
protected static native void nativeSetParticleCount(int particlesHandle, int particleCount);
protected static native void nativeSetMaxDuration(int particlesHandle, int duration);
protected static native void nativeSetRandomDuration(int particlesHandle, int duration);
protected static native void nativeSetMaxSize(int particlesHandle, float x, float y, float z);
protected static native void nativeSetRandomSize(int particlesHandle, float x, float y, float z);
protected static native void nativeSetDefaultPosition(int particlesHandle, float x, float y, float z);
protected static native void nativeSetRandomPosition(int particlesHandle, float x, float y, float z);
protected static native void nativeSetMaxColor(int particlesHandle, float r, float g, float b, float a);
protected static native void nativeSetRandomColor(int particlesHandle, float r, float g, float b, float a);
protected static native void nativeSetDefaultGravity(int particlesHandle, float x, float y, float z);
protected static native void nativeSetRandomGravity(int particlesHandle, float x, float y, float z);
protected static native void nativeSetDefaultForce(int particlesHandle, float x, float y, float z);
protected static native void nativeSetRandomForce(int particlesHandle, float x, float y, float z);
protected static native void nativeSetMaxMass(int particlesHandle, float mass);
protected static native void nativeSetRandomMass(int particlesHandle, float mass);
protected static native void nativeSetScaleKeyFrameAnimationProperty(int particlesHandle, int duration, int interpolatorType, int reset);
protected static native void nativeSetColorKeyFrameAnimationProperty(int particlesHandle, int duration, int interpolatorType, int reset);
protected static native void nativeSetPositionKeyFrameAnimationProperty(int particlesHandle, int duration, int interpolatorType, int reset);
protected static native void nativeAddScaleKeyFrame(int particlesHandle, float keyTime, float x, float y, float z);
protected static native void nativeAddColorKeyFrame(int particlesHandle, float keyTime, float r, float g, float b, float a);
protected static native void nativeAddPositionKeyFrame(int particlesHandle, float keyTime, float x, float y, float z);
} // end definition SVIParticlesInfo
|
package rocks.gioac96.veronica.auth;
import rocks.gioac96.veronica.core.PipelineBreakException;
import rocks.gioac96.veronica.core.Response;
/**
* Breaks the pipeline on authentication failure.
*/
public class AuthenticationException extends PipelineBreakException {
public AuthenticationException(Response response) {
super(response);
}
public AuthenticationException(Throwable cause, Response response) {
super(cause, response);
}
}
|
/*
* 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.glue.model;
import java.io.Serializable;
import javax.annotation.Generated;
import com.amazonaws.AmazonWebServiceRequest;
/**
*
* @see <a href="http://docs.aws.amazon.com/goto/WebAPI/glue-2017-03-31/UpdateColumnStatisticsForTable"
* target="_top">AWS API Documentation</a>
*/
@Generated("com.amazonaws:aws-java-sdk-code-generator")
public class UpdateColumnStatisticsForTableRequest extends com.amazonaws.AmazonWebServiceRequest implements Serializable, Cloneable {
/**
* <p>
* The ID of the Data Catalog where the partitions in question reside. If none is supplied, the Amazon Web Services
* account ID is used by default.
* </p>
*/
private String catalogId;
/**
* <p>
* The name of the catalog database where the partitions reside.
* </p>
*/
private String databaseName;
/**
* <p>
* The name of the partitions' table.
* </p>
*/
private String tableName;
/**
* <p>
* A list of the column statistics.
* </p>
*/
private java.util.List<ColumnStatistics> columnStatisticsList;
/**
* <p>
* The ID of the Data Catalog where the partitions in question reside. If none is supplied, the Amazon Web Services
* account ID is used by default.
* </p>
*
* @param catalogId
* The ID of the Data Catalog where the partitions in question reside. If none is supplied, the Amazon Web
* Services account ID is used by default.
*/
public void setCatalogId(String catalogId) {
this.catalogId = catalogId;
}
/**
* <p>
* The ID of the Data Catalog where the partitions in question reside. If none is supplied, the Amazon Web Services
* account ID is used by default.
* </p>
*
* @return The ID of the Data Catalog where the partitions in question reside. If none is supplied, the Amazon Web
* Services account ID is used by default.
*/
public String getCatalogId() {
return this.catalogId;
}
/**
* <p>
* The ID of the Data Catalog where the partitions in question reside. If none is supplied, the Amazon Web Services
* account ID is used by default.
* </p>
*
* @param catalogId
* The ID of the Data Catalog where the partitions in question reside. If none is supplied, the Amazon Web
* Services account ID is used by default.
* @return Returns a reference to this object so that method calls can be chained together.
*/
public UpdateColumnStatisticsForTableRequest withCatalogId(String catalogId) {
setCatalogId(catalogId);
return this;
}
/**
* <p>
* The name of the catalog database where the partitions reside.
* </p>
*
* @param databaseName
* The name of the catalog database where the partitions reside.
*/
public void setDatabaseName(String databaseName) {
this.databaseName = databaseName;
}
/**
* <p>
* The name of the catalog database where the partitions reside.
* </p>
*
* @return The name of the catalog database where the partitions reside.
*/
public String getDatabaseName() {
return this.databaseName;
}
/**
* <p>
* The name of the catalog database where the partitions reside.
* </p>
*
* @param databaseName
* The name of the catalog database where the partitions reside.
* @return Returns a reference to this object so that method calls can be chained together.
*/
public UpdateColumnStatisticsForTableRequest withDatabaseName(String databaseName) {
setDatabaseName(databaseName);
return this;
}
/**
* <p>
* The name of the partitions' table.
* </p>
*
* @param tableName
* The name of the partitions' table.
*/
public void setTableName(String tableName) {
this.tableName = tableName;
}
/**
* <p>
* The name of the partitions' table.
* </p>
*
* @return The name of the partitions' table.
*/
public String getTableName() {
return this.tableName;
}
/**
* <p>
* The name of the partitions' table.
* </p>
*
* @param tableName
* The name of the partitions' table.
* @return Returns a reference to this object so that method calls can be chained together.
*/
public UpdateColumnStatisticsForTableRequest withTableName(String tableName) {
setTableName(tableName);
return this;
}
/**
* <p>
* A list of the column statistics.
* </p>
*
* @return A list of the column statistics.
*/
public java.util.List<ColumnStatistics> getColumnStatisticsList() {
return columnStatisticsList;
}
/**
* <p>
* A list of the column statistics.
* </p>
*
* @param columnStatisticsList
* A list of the column statistics.
*/
public void setColumnStatisticsList(java.util.Collection<ColumnStatistics> columnStatisticsList) {
if (columnStatisticsList == null) {
this.columnStatisticsList = null;
return;
}
this.columnStatisticsList = new java.util.ArrayList<ColumnStatistics>(columnStatisticsList);
}
/**
* <p>
* A list of the column statistics.
* </p>
* <p>
* <b>NOTE:</b> This method appends the values to the existing list (if any). Use
* {@link #setColumnStatisticsList(java.util.Collection)} or {@link #withColumnStatisticsList(java.util.Collection)}
* if you want to override the existing values.
* </p>
*
* @param columnStatisticsList
* A list of the column statistics.
* @return Returns a reference to this object so that method calls can be chained together.
*/
public UpdateColumnStatisticsForTableRequest withColumnStatisticsList(ColumnStatistics... columnStatisticsList) {
if (this.columnStatisticsList == null) {
setColumnStatisticsList(new java.util.ArrayList<ColumnStatistics>(columnStatisticsList.length));
}
for (ColumnStatistics ele : columnStatisticsList) {
this.columnStatisticsList.add(ele);
}
return this;
}
/**
* <p>
* A list of the column statistics.
* </p>
*
* @param columnStatisticsList
* A list of the column statistics.
* @return Returns a reference to this object so that method calls can be chained together.
*/
public UpdateColumnStatisticsForTableRequest withColumnStatisticsList(java.util.Collection<ColumnStatistics> columnStatisticsList) {
setColumnStatisticsList(columnStatisticsList);
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 (getCatalogId() != null)
sb.append("CatalogId: ").append(getCatalogId()).append(",");
if (getDatabaseName() != null)
sb.append("DatabaseName: ").append(getDatabaseName()).append(",");
if (getTableName() != null)
sb.append("TableName: ").append(getTableName()).append(",");
if (getColumnStatisticsList() != null)
sb.append("ColumnStatisticsList: ").append(getColumnStatisticsList());
sb.append("}");
return sb.toString();
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (obj instanceof UpdateColumnStatisticsForTableRequest == false)
return false;
UpdateColumnStatisticsForTableRequest other = (UpdateColumnStatisticsForTableRequest) obj;
if (other.getCatalogId() == null ^ this.getCatalogId() == null)
return false;
if (other.getCatalogId() != null && other.getCatalogId().equals(this.getCatalogId()) == false)
return false;
if (other.getDatabaseName() == null ^ this.getDatabaseName() == null)
return false;
if (other.getDatabaseName() != null && other.getDatabaseName().equals(this.getDatabaseName()) == false)
return false;
if (other.getTableName() == null ^ this.getTableName() == null)
return false;
if (other.getTableName() != null && other.getTableName().equals(this.getTableName()) == false)
return false;
if (other.getColumnStatisticsList() == null ^ this.getColumnStatisticsList() == null)
return false;
if (other.getColumnStatisticsList() != null && other.getColumnStatisticsList().equals(this.getColumnStatisticsList()) == false)
return false;
return true;
}
@Override
public int hashCode() {
final int prime = 31;
int hashCode = 1;
hashCode = prime * hashCode + ((getCatalogId() == null) ? 0 : getCatalogId().hashCode());
hashCode = prime * hashCode + ((getDatabaseName() == null) ? 0 : getDatabaseName().hashCode());
hashCode = prime * hashCode + ((getTableName() == null) ? 0 : getTableName().hashCode());
hashCode = prime * hashCode + ((getColumnStatisticsList() == null) ? 0 : getColumnStatisticsList().hashCode());
return hashCode;
}
@Override
public UpdateColumnStatisticsForTableRequest clone() {
return (UpdateColumnStatisticsForTableRequest) super.clone();
}
}
|
/*
* 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.coppertine.tafe.java;
/**
*
* @author Coppertine
*/
public class Declarator {
/**
* Object for Declarator.
*/
private Object obj;
/**
* String that is used for labels, text or simular.
*/
private String name;
/**
* Vector2 of the position.
*/
private Vector2 pos;
/**
* Width of the object.
*/
private int width;
/**
* Length of the object.
*/
private int length;
/**
*
* @param object Object that is used to be Generated.
* @param inputName String of the object label.
* @param position Vector2 of the Position
* @param sizeWidth Width of the object
* @param sizeLength Length of the object
*/
public Declarator(
final Object object, final String inputName,
final Vector2 position, final int sizeWidth,
final int sizeLength) {
this.obj = object;
this.name = inputName;
this.pos = position;
this.width = sizeWidth;
this.length = sizeLength;
}
/**
*
* @return Object Declarator object
*/
public final Object getObj() {
return obj;
}
/**
*
* @param objInput Object of the declarator.
*/
public final void setObj(final Object objInput) {
this.obj = objInput;
}
/**
*
* @return String Object name.
*/
public final String getName() {
return name;
}
/**
*
* @param nameInput label string of the object.
*/
public final void setName(final String nameInput) {
this.name = nameInput;
}
/**
*
* @return Vector2 Position.
*/
public final Vector2 getPos() {
return pos;
}
/**
*
* @param posInput Vector2 Position.
*/
public final void setPos(final Vector2 posInput) {
this.pos = posInput;
}
/**
*
* @return Integer width of the object.
*/
public final int getWidth() {
return width;
}
/**
*
* @param widthInput Integer width of the object.
*/
public final void setWidth(final int widthInput) {
this.width = widthInput;
}
/**
*
* @return Integer Length of the object.
*/
public final int getLength() {
return length;
}
/**
*
* @param lengthInput Integer Length of the object.
*/
public final void setLength(final int lengthInput) {
this.length = lengthInput;
}
}
|
package com.openhack.hackacross;
import androidx.annotation.DrawableRes;
import com.google.android.gms.maps.model.BitmapDescriptor;
import com.google.android.gms.maps.model.BitmapDescriptorFactory;
import com.google.android.gms.maps.model.LatLng;
import com.google.maps.android.clustering.ClusterItem;
public class MyItem implements ClusterItem {
private final LatLng mPosition;
private String mTitle;
private String mSnippet;
private int mDrawable;
public MyItem(double lat, double lng, String title, String snippet, int drawable) {
mPosition = new LatLng(lat, lng);
mTitle = title;
mSnippet = snippet;
mDrawable = drawable;
}
@Override
public LatLng getPosition() {
return mPosition;
}
@Override
public String getTitle() {
return mTitle;
}
@Override
public String getSnippet() {
return mSnippet;
}
public BitmapDescriptor getIcon() {
return BitmapDescriptorFactory.fromResource(mDrawable);
}
}
|
/*
* Copyright (c) 2010-2017. Axon Framework
* 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.axonframework.eventhandling;
import java.util.List;
/**
* Describes the context of an error.
*/
public class ErrorContext {
private final String eventProcessor;
private final Exception error;
private final List<? extends EventMessage<?>> failedEvents;
/**
* @param eventProcessor The name of the event processor that failed to process the given events
* @param error The error that was raised during processing
* @param failedEvents The list of events that triggered the error
*/
public ErrorContext(String eventProcessor, Exception error, List<? extends EventMessage<?>> failedEvents) {
this.eventProcessor = eventProcessor;
this.error = error;
this.failedEvents = failedEvents;
}
/**
* Returns the name of the Event Processor where the error occurred.
*
* @return the name of the Event Processor where the error occurred
*/
public String eventProcessor() {
return eventProcessor;
}
/**
* Returns the error that was raised in the processor
*
* @return the error that was raised in the processor
*/
public Exception error() {
return error;
}
/**
* The events part of the batch that failed. May be empty if an error occurred outside of the scope of processing a
* batch (e.g. while preparing the next batch).
*
* @return events part of the batch that failed, if any
*/
public List<? extends EventMessage<?>> failedEvents() {
return failedEvents;
}
}
|
/*
This file is part of the iText (R) project.
Copyright (c) 1998-2021 iText Group NV
Authors: iText Software.
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License version 3
as published by the Free Software Foundation with the addition of the
following permission added to Section 15 as permitted in Section 7(a):
FOR ANY PART OF THE COVERED WORK IN WHICH THE COPYRIGHT IS OWNED BY
ITEXT GROUP. ITEXT GROUP DISCLAIMS THE WARRANTY OF NON INFRINGEMENT
OF THIRD PARTY RIGHTS
This program is distributed in the hope that it will be useful, but
WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
or FITNESS FOR A PARTICULAR PURPOSE.
See the GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program; if not, see http://www.gnu.org/licenses or write to
the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
Boston, MA, 02110-1301 USA, or download the license from the following URL:
http://itextpdf.com/terms-of-use/
The interactive user interfaces in modified source and object code versions
of this program must display Appropriate Legal Notices, as required under
Section 5 of the GNU Affero General Public License.
In accordance with Section 7(b) of the GNU Affero General Public License,
a covered work must retain the producer line in every PDF that is created
or manipulated using iText.
You can be released from the requirements of the license by purchasing
a commercial license. Buying such a license is mandatory as soon as you
develop commercial activities involving the iText software without
disclosing the source code of your own applications.
These activities include: offering paid services to customers as an ASP,
serving PDFs on the fly in a web application, shipping iText with a closed
source product.
For more information, please contact iText Software Corp. at this
address: sales@itextpdf.com
*/
package com.itextpdf.html2pdf.element;
import com.itextpdf.html2pdf.HtmlConverter;
import com.itextpdf.kernel.utils.CompareTool;
import com.itextpdf.test.ExtendedITextTest;
import com.itextpdf.test.annotations.type.IntegrationTest;
import java.io.File;
import java.io.IOException;
import org.junit.Assert;
import org.junit.BeforeClass;
import org.junit.Test;
import org.junit.experimental.categories.Category;
@Category(IntegrationTest.class)
public class CodeTest extends ExtendedITextTest {
public static final String sourceFolder = "./src/test/resources/com/itextpdf/html2pdf/element/CodeTest/";
public static final String destinationFolder = "./target/test/com/itextpdf/html2pdf/element/CodeTest/";
@BeforeClass
public static void beforeClass() {
createDestinationFolder(destinationFolder);
}
@Test
public void code01Test() throws IOException, InterruptedException {
HtmlConverter.convertToPdf(new File(sourceFolder + "codeTest01.html"), new File(destinationFolder + "codeTest01.pdf"));
Assert.assertNull(new CompareTool().compareByContent(destinationFolder + "codeTest01.pdf", sourceFolder + "cmp_codeTest01.pdf", destinationFolder, "diff01_"));
}
@Test
public void code02Test() throws IOException, InterruptedException {
HtmlConverter.convertToPdf(new File(sourceFolder + "codeTest02.html"), new File(destinationFolder + "codeTest02.pdf"));
Assert.assertNull(new CompareTool().compareByContent(destinationFolder + "codeTest02.pdf", sourceFolder + "cmp_codeTest02.pdf", destinationFolder, "diff02_"));
}
@Test
public void code03Test() throws IOException, InterruptedException {
HtmlConverter.convertToPdf(new File(sourceFolder + "codeTest03.html"), new File(destinationFolder + "codeTest03.pdf"));
Assert.assertNull(new CompareTool().compareByContent(destinationFolder + "codeTest03.pdf", sourceFolder + "cmp_codeTest03.pdf", destinationFolder, "diff02_"));
}
}
|
/*
* This is free and unencumbered software released into the public domain.
*
* Anyone is free to copy, modify, publish, use, compile, sell, or
* distribute this software, either in source code form or as a compiled
* binary, for any purpose, commercial or non-commercial, and by any
* means.
*
* In jurisdictions that recognize copyright laws, the author or authors
* of this software dedicate any and all copyright interest in the
* software to the public domain. We make this dedication for the benefit
* of the public at large and to the detriment of our heirs and
* successors. We intend this dedication to be an overt act of
* relinquishment in perpetuity of all present and future rights to this
* software under copyright law.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
* IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR
* OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
* ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
* OTHER DEALINGS IN THE SOFTWARE.
*
* For more information, please refer to <http://unlicense.org/>
*/
package au.id.soundadvice.systemdesign.moduleapi.tree;
import au.id.soundadvice.systemdesign.moduleapi.collection.Baseline;
import au.id.soundadvice.systemdesign.moduleapi.entity.Identifiable;
import au.id.soundadvice.systemdesign.moduleapi.collection.WhyHowPair;
import au.id.soundadvice.systemdesign.moduleapi.entity.Record;
import au.id.soundadvice.systemdesign.moduleapi.interaction.MenuItems;
import java.util.Optional;
import java.util.stream.Stream;
/**
*
* @author Benjamin Carlyle <benjamincarlyle@soundadvice.id.au>
*/
public interface TreeNode extends Identifiable, Comparable<TreeNode> {
/**
* Implementations must include a toString method
*/
@Override
public String toString();
public WhyHowPair<Baseline> setLabel(WhyHowPair<Baseline> baselines, String now, String value);
public WhyHowPair<Baseline> removeFrom(WhyHowPair<Baseline> baselines);
public Stream<TreeNode> getChildren();
public Optional<Record> getDragDropObject();
public Optional<MenuItems> getContextMenu();
@Override
default public int compareTo(TreeNode o) {
return toString().compareTo(o.toString());
}
}
|
package dev.client.tenacity.module.impl.exploit;
import dev.client.tenacity.module.Category;
import dev.client.tenacity.module.Module;
import dev.event.EventListener;
import dev.event.impl.network.PacketReceiveEvent;
import net.minecraft.network.play.server.S02PacketChat;
public final class TPKiller extends Module {
private final EventListener<PacketReceiveEvent> packetReceiveEventEventListener = event -> {
if (event.getPacket() instanceof S02PacketChat) {
S02PacketChat s02PacketChat = (S02PacketChat) event.getPacket();
if (s02PacketChat.getChatComponent().getUnformattedText().contains("tpa") || s02PacketChat.getChatComponent().getUnformattedText().contains("request")) {
mc.thePlayer.setPosition(mc.thePlayer.posX, mc.thePlayer.posY - 6, mc.thePlayer.posZ);
mc.thePlayer.sendChatMessage("/tpa accept");
if (mc.thePlayer.ticksExisted % 2 == 0) {
mc.thePlayer.setPosition(mc.thePlayer.posX, mc.thePlayer.posY + 6, mc.thePlayer.posZ);
}
}
}
};
public TPKiller() {
super("TPKiller", Category.EXPLOIT, "when someone tpas to you they will suffocate");
}
}
|
package nimra.mandelexplorer.palette;
import nimra.mandelexplorer.PaletteMapper;
import nimra.mandelexplorer.util.ColorUtils;
import org.beryx.awt.color.ColorFactory;
import org.json.JSONArray;
import org.json.JSONObject;
import java.awt.Color;
import java.util.ArrayList;
import java.util.List;
/**
* Created: 29.12.19 by: Armin Haaf
*
* @author Armin Haaf
*/
public abstract class GradientPaletteMapper extends PaletteMapper {
protected List<Gradient> gradients = new ArrayList<>();
public GradientPaletteMapper() {
initDefaults();
}
protected void initDefaults() {
gradients.add(new Gradient(Color.red, Color.blue));
}
// expect value between 0 and 1
protected int getRBGColor(float pValue) {
float tRatio = Math.abs(pValue) % 1.0f;
float tSlicePercent = 0;
for (int i = 0; i < gradients.size(); i++) {
Gradient tGradient = gradients.get(i);
float tNextSlicePercent;
if (tGradient.slicePercent > 0) {
tNextSlicePercent = tSlicePercent + tGradient.slicePercent;
} else {
tNextSlicePercent = tSlicePercent + 100.0f / (float)gradients.size();
}
if (tRatio * 100.0f < tNextSlicePercent || i + 1 == gradients.size()) {
tRatio = (tRatio - tSlicePercent / 100.0f) * 100f / (tNextSlicePercent - tSlicePercent);
return tGradient.getRBGColor(Math.min(tRatio, 1));
}
tSlicePercent = tNextSlicePercent;
}
return -1;
}
@Override
protected void toJson(final JSONObject pJSONObject) {
super.toJson(pJSONObject);
JSONArray tJsonGradients = new JSONArray();
for (int i = 0; i < gradients.size(); i++) {
Gradient tGradient = gradients.get(i);
tJsonGradients.put(i, tGradient.toJson());
}
pJSONObject.put("gradients", tJsonGradients);
}
@Override
public void fromJson(final JSONObject pJSONObject) {
super.fromJson(pJSONObject);
gradients.clear();
if (pJSONObject.has("gradients")) {
JSONArray tJsonGradients = pJSONObject.getJSONArray("gradients");
for (Object tJsonGradient : tJsonGradients) {
final Gradient tGradient = new Gradient();
tGradient.fromJson((JSONObject)tJsonGradient);
gradients.add(tGradient);
}
}
}
static class Gradient {
Color fromColor;
Color toColor;
int slicePercent = 100;
GradientType type = GradientType.LINEAR;
public Gradient(final Color pFromColor, final Color pToColor) {
fromColor = pFromColor;
toColor = pToColor;
}
public Gradient() {
}
public int getRBGColor(float pRatio) {
return getLinearRBGColor(pRatio);
}
public int getLinearRBGColor(float pRatio) {
int red = (int)(toColor.getRed() * pRatio + fromColor.getRed() * (1 - pRatio));
int green = (int)(toColor.getGreen() * pRatio + fromColor.getGreen() * (1 - pRatio));
int blue = (int)(toColor.getBlue() * pRatio + fromColor.getBlue() * (1 - pRatio));
return ((red & 0xFF) << 16) |
((green & 0xFF) << 8) |
((blue & 0xFF));
}
public JSONObject toJson() {
final JSONObject tJSONObject = new JSONObject();
tJSONObject.put("fromColor", ColorUtils.toColorString(fromColor));
tJSONObject.put("toColor", ColorUtils.toColorString(toColor));
if (slicePercent > 0) {
tJSONObject.put("slicePercent", slicePercent);
}
return tJSONObject;
}
public void fromJson(final JSONObject pJSONObject) {
fromColor = ColorFactory.valueOf(pJSONObject.optString("fromColor", "red"));
toColor = ColorFactory.valueOf(pJSONObject.optString("toColor", "blue"));
slicePercent = Integer.parseInt(pJSONObject.optString("slicePercent", "0"));
}
}
enum GradientType {
LINEAR;
}
}
|
// Generated by the protocol buffer compiler. DO NOT EDIT!
// source: google/cloud/filestore/v1/cloud_filestore_service.proto
package com.google.cloud.filestore.v1;
/**
* <pre>
* NFS export options specifications.
* </pre>
*
* Protobuf type {@code google.cloud.filestore.v1.NfsExportOptions}
*/
public final class NfsExportOptions extends
com.google.protobuf.GeneratedMessageV3 implements
// @@protoc_insertion_point(message_implements:google.cloud.filestore.v1.NfsExportOptions)
NfsExportOptionsOrBuilder {
private static final long serialVersionUID = 0L;
// Use NfsExportOptions.newBuilder() to construct.
private NfsExportOptions(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) {
super(builder);
}
private NfsExportOptions() {
ipRanges_ = com.google.protobuf.LazyStringArrayList.EMPTY;
accessMode_ = 0;
squashMode_ = 0;
}
@java.lang.Override
@SuppressWarnings({"unused"})
protected java.lang.Object newInstance(
UnusedPrivateParameter unused) {
return new NfsExportOptions();
}
@java.lang.Override
public final com.google.protobuf.UnknownFieldSet
getUnknownFields() {
return this.unknownFields;
}
private NfsExportOptions(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
this();
if (extensionRegistry == null) {
throw new java.lang.NullPointerException();
}
int mutable_bitField0_ = 0;
com.google.protobuf.UnknownFieldSet.Builder unknownFields =
com.google.protobuf.UnknownFieldSet.newBuilder();
try {
boolean done = false;
while (!done) {
int tag = input.readTag();
switch (tag) {
case 0:
done = true;
break;
case 10: {
java.lang.String s = input.readStringRequireUtf8();
if (!((mutable_bitField0_ & 0x00000001) != 0)) {
ipRanges_ = new com.google.protobuf.LazyStringArrayList();
mutable_bitField0_ |= 0x00000001;
}
ipRanges_.add(s);
break;
}
case 16: {
int rawValue = input.readEnum();
accessMode_ = rawValue;
break;
}
case 24: {
int rawValue = input.readEnum();
squashMode_ = rawValue;
break;
}
case 32: {
anonUid_ = input.readInt64();
break;
}
case 40: {
anonGid_ = input.readInt64();
break;
}
default: {
if (!parseUnknownField(
input, unknownFields, extensionRegistry, tag)) {
done = true;
}
break;
}
}
}
} catch (com.google.protobuf.InvalidProtocolBufferException e) {
throw e.setUnfinishedMessage(this);
} catch (java.io.IOException e) {
throw new com.google.protobuf.InvalidProtocolBufferException(
e).setUnfinishedMessage(this);
} finally {
if (((mutable_bitField0_ & 0x00000001) != 0)) {
ipRanges_ = ipRanges_.getUnmodifiableView();
}
this.unknownFields = unknownFields.build();
makeExtensionsImmutable();
}
}
public static final com.google.protobuf.Descriptors.Descriptor
getDescriptor() {
return com.google.cloud.filestore.v1.CloudFilestoreServiceProto.internal_static_google_cloud_filestore_v1_NfsExportOptions_descriptor;
}
@java.lang.Override
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return com.google.cloud.filestore.v1.CloudFilestoreServiceProto.internal_static_google_cloud_filestore_v1_NfsExportOptions_fieldAccessorTable
.ensureFieldAccessorsInitialized(
com.google.cloud.filestore.v1.NfsExportOptions.class, com.google.cloud.filestore.v1.NfsExportOptions.Builder.class);
}
/**
* <pre>
* The access mode.
* </pre>
*
* Protobuf enum {@code google.cloud.filestore.v1.NfsExportOptions.AccessMode}
*/
public enum AccessMode
implements com.google.protobuf.ProtocolMessageEnum {
/**
* <pre>
* AccessMode not set.
* </pre>
*
* <code>ACCESS_MODE_UNSPECIFIED = 0;</code>
*/
ACCESS_MODE_UNSPECIFIED(0),
/**
* <pre>
* The client can only read the file share.
* </pre>
*
* <code>READ_ONLY = 1;</code>
*/
READ_ONLY(1),
/**
* <pre>
* The client can read and write the file share (default).
* </pre>
*
* <code>READ_WRITE = 2;</code>
*/
READ_WRITE(2),
UNRECOGNIZED(-1),
;
/**
* <pre>
* AccessMode not set.
* </pre>
*
* <code>ACCESS_MODE_UNSPECIFIED = 0;</code>
*/
public static final int ACCESS_MODE_UNSPECIFIED_VALUE = 0;
/**
* <pre>
* The client can only read the file share.
* </pre>
*
* <code>READ_ONLY = 1;</code>
*/
public static final int READ_ONLY_VALUE = 1;
/**
* <pre>
* The client can read and write the file share (default).
* </pre>
*
* <code>READ_WRITE = 2;</code>
*/
public static final int READ_WRITE_VALUE = 2;
public final int getNumber() {
if (this == UNRECOGNIZED) {
throw new java.lang.IllegalArgumentException(
"Can't get the number of an unknown enum value.");
}
return value;
}
/**
* @param value The numeric wire value of the corresponding enum entry.
* @return The enum associated with the given numeric wire value.
* @deprecated Use {@link #forNumber(int)} instead.
*/
@java.lang.Deprecated
public static AccessMode valueOf(int value) {
return forNumber(value);
}
/**
* @param value The numeric wire value of the corresponding enum entry.
* @return The enum associated with the given numeric wire value.
*/
public static AccessMode forNumber(int value) {
switch (value) {
case 0: return ACCESS_MODE_UNSPECIFIED;
case 1: return READ_ONLY;
case 2: return READ_WRITE;
default: return null;
}
}
public static com.google.protobuf.Internal.EnumLiteMap<AccessMode>
internalGetValueMap() {
return internalValueMap;
}
private static final com.google.protobuf.Internal.EnumLiteMap<
AccessMode> internalValueMap =
new com.google.protobuf.Internal.EnumLiteMap<AccessMode>() {
public AccessMode findValueByNumber(int number) {
return AccessMode.forNumber(number);
}
};
public final com.google.protobuf.Descriptors.EnumValueDescriptor
getValueDescriptor() {
if (this == UNRECOGNIZED) {
throw new java.lang.IllegalStateException(
"Can't get the descriptor of an unrecognized enum value.");
}
return getDescriptor().getValues().get(ordinal());
}
public final com.google.protobuf.Descriptors.EnumDescriptor
getDescriptorForType() {
return getDescriptor();
}
public static final com.google.protobuf.Descriptors.EnumDescriptor
getDescriptor() {
return com.google.cloud.filestore.v1.NfsExportOptions.getDescriptor().getEnumTypes().get(0);
}
private static final AccessMode[] VALUES = values();
public static AccessMode valueOf(
com.google.protobuf.Descriptors.EnumValueDescriptor desc) {
if (desc.getType() != getDescriptor()) {
throw new java.lang.IllegalArgumentException(
"EnumValueDescriptor is not for this type.");
}
if (desc.getIndex() == -1) {
return UNRECOGNIZED;
}
return VALUES[desc.getIndex()];
}
private final int value;
private AccessMode(int value) {
this.value = value;
}
// @@protoc_insertion_point(enum_scope:google.cloud.filestore.v1.NfsExportOptions.AccessMode)
}
/**
* <pre>
* The squash mode.
* </pre>
*
* Protobuf enum {@code google.cloud.filestore.v1.NfsExportOptions.SquashMode}
*/
public enum SquashMode
implements com.google.protobuf.ProtocolMessageEnum {
/**
* <pre>
* SquashMode not set.
* </pre>
*
* <code>SQUASH_MODE_UNSPECIFIED = 0;</code>
*/
SQUASH_MODE_UNSPECIFIED(0),
/**
* <pre>
* The Root user has root access to the file share (default).
* </pre>
*
* <code>NO_ROOT_SQUASH = 1;</code>
*/
NO_ROOT_SQUASH(1),
/**
* <pre>
* The Root user has squashed access to the anonymous uid/gid.
* </pre>
*
* <code>ROOT_SQUASH = 2;</code>
*/
ROOT_SQUASH(2),
UNRECOGNIZED(-1),
;
/**
* <pre>
* SquashMode not set.
* </pre>
*
* <code>SQUASH_MODE_UNSPECIFIED = 0;</code>
*/
public static final int SQUASH_MODE_UNSPECIFIED_VALUE = 0;
/**
* <pre>
* The Root user has root access to the file share (default).
* </pre>
*
* <code>NO_ROOT_SQUASH = 1;</code>
*/
public static final int NO_ROOT_SQUASH_VALUE = 1;
/**
* <pre>
* The Root user has squashed access to the anonymous uid/gid.
* </pre>
*
* <code>ROOT_SQUASH = 2;</code>
*/
public static final int ROOT_SQUASH_VALUE = 2;
public final int getNumber() {
if (this == UNRECOGNIZED) {
throw new java.lang.IllegalArgumentException(
"Can't get the number of an unknown enum value.");
}
return value;
}
/**
* @param value The numeric wire value of the corresponding enum entry.
* @return The enum associated with the given numeric wire value.
* @deprecated Use {@link #forNumber(int)} instead.
*/
@java.lang.Deprecated
public static SquashMode valueOf(int value) {
return forNumber(value);
}
/**
* @param value The numeric wire value of the corresponding enum entry.
* @return The enum associated with the given numeric wire value.
*/
public static SquashMode forNumber(int value) {
switch (value) {
case 0: return SQUASH_MODE_UNSPECIFIED;
case 1: return NO_ROOT_SQUASH;
case 2: return ROOT_SQUASH;
default: return null;
}
}
public static com.google.protobuf.Internal.EnumLiteMap<SquashMode>
internalGetValueMap() {
return internalValueMap;
}
private static final com.google.protobuf.Internal.EnumLiteMap<
SquashMode> internalValueMap =
new com.google.protobuf.Internal.EnumLiteMap<SquashMode>() {
public SquashMode findValueByNumber(int number) {
return SquashMode.forNumber(number);
}
};
public final com.google.protobuf.Descriptors.EnumValueDescriptor
getValueDescriptor() {
if (this == UNRECOGNIZED) {
throw new java.lang.IllegalStateException(
"Can't get the descriptor of an unrecognized enum value.");
}
return getDescriptor().getValues().get(ordinal());
}
public final com.google.protobuf.Descriptors.EnumDescriptor
getDescriptorForType() {
return getDescriptor();
}
public static final com.google.protobuf.Descriptors.EnumDescriptor
getDescriptor() {
return com.google.cloud.filestore.v1.NfsExportOptions.getDescriptor().getEnumTypes().get(1);
}
private static final SquashMode[] VALUES = values();
public static SquashMode valueOf(
com.google.protobuf.Descriptors.EnumValueDescriptor desc) {
if (desc.getType() != getDescriptor()) {
throw new java.lang.IllegalArgumentException(
"EnumValueDescriptor is not for this type.");
}
if (desc.getIndex() == -1) {
return UNRECOGNIZED;
}
return VALUES[desc.getIndex()];
}
private final int value;
private SquashMode(int value) {
this.value = value;
}
// @@protoc_insertion_point(enum_scope:google.cloud.filestore.v1.NfsExportOptions.SquashMode)
}
public static final int IP_RANGES_FIELD_NUMBER = 1;
private com.google.protobuf.LazyStringList ipRanges_;
/**
* <pre>
* List of either an IPv4 addresses in the format
* `{octet1}.{octet2}.{octet3}.{octet4}` or CIDR ranges in the format
* `{octet1}.{octet2}.{octet3}.{octet4}/{mask size}` which may mount the
* file share.
* Overlapping IP ranges are not allowed, both within and across
* NfsExportOptions. An error will be returned.
* The limit is 64 IP ranges/addresses for each FileShareConfig among all
* NfsExportOptions.
* </pre>
*
* <code>repeated string ip_ranges = 1;</code>
* @return A list containing the ipRanges.
*/
public com.google.protobuf.ProtocolStringList
getIpRangesList() {
return ipRanges_;
}
/**
* <pre>
* List of either an IPv4 addresses in the format
* `{octet1}.{octet2}.{octet3}.{octet4}` or CIDR ranges in the format
* `{octet1}.{octet2}.{octet3}.{octet4}/{mask size}` which may mount the
* file share.
* Overlapping IP ranges are not allowed, both within and across
* NfsExportOptions. An error will be returned.
* The limit is 64 IP ranges/addresses for each FileShareConfig among all
* NfsExportOptions.
* </pre>
*
* <code>repeated string ip_ranges = 1;</code>
* @return The count of ipRanges.
*/
public int getIpRangesCount() {
return ipRanges_.size();
}
/**
* <pre>
* List of either an IPv4 addresses in the format
* `{octet1}.{octet2}.{octet3}.{octet4}` or CIDR ranges in the format
* `{octet1}.{octet2}.{octet3}.{octet4}/{mask size}` which may mount the
* file share.
* Overlapping IP ranges are not allowed, both within and across
* NfsExportOptions. An error will be returned.
* The limit is 64 IP ranges/addresses for each FileShareConfig among all
* NfsExportOptions.
* </pre>
*
* <code>repeated string ip_ranges = 1;</code>
* @param index The index of the element to return.
* @return The ipRanges at the given index.
*/
public java.lang.String getIpRanges(int index) {
return ipRanges_.get(index);
}
/**
* <pre>
* List of either an IPv4 addresses in the format
* `{octet1}.{octet2}.{octet3}.{octet4}` or CIDR ranges in the format
* `{octet1}.{octet2}.{octet3}.{octet4}/{mask size}` which may mount the
* file share.
* Overlapping IP ranges are not allowed, both within and across
* NfsExportOptions. An error will be returned.
* The limit is 64 IP ranges/addresses for each FileShareConfig among all
* NfsExportOptions.
* </pre>
*
* <code>repeated string ip_ranges = 1;</code>
* @param index The index of the value to return.
* @return The bytes of the ipRanges at the given index.
*/
public com.google.protobuf.ByteString
getIpRangesBytes(int index) {
return ipRanges_.getByteString(index);
}
public static final int ACCESS_MODE_FIELD_NUMBER = 2;
private int accessMode_;
/**
* <pre>
* Either READ_ONLY, for allowing only read requests on the exported
* directory, or READ_WRITE, for allowing both read and write requests.
* The default is READ_WRITE.
* </pre>
*
* <code>.google.cloud.filestore.v1.NfsExportOptions.AccessMode access_mode = 2;</code>
* @return The enum numeric value on the wire for accessMode.
*/
@java.lang.Override public int getAccessModeValue() {
return accessMode_;
}
/**
* <pre>
* Either READ_ONLY, for allowing only read requests on the exported
* directory, or READ_WRITE, for allowing both read and write requests.
* The default is READ_WRITE.
* </pre>
*
* <code>.google.cloud.filestore.v1.NfsExportOptions.AccessMode access_mode = 2;</code>
* @return The accessMode.
*/
@java.lang.Override public com.google.cloud.filestore.v1.NfsExportOptions.AccessMode getAccessMode() {
@SuppressWarnings("deprecation")
com.google.cloud.filestore.v1.NfsExportOptions.AccessMode result = com.google.cloud.filestore.v1.NfsExportOptions.AccessMode.valueOf(accessMode_);
return result == null ? com.google.cloud.filestore.v1.NfsExportOptions.AccessMode.UNRECOGNIZED : result;
}
public static final int SQUASH_MODE_FIELD_NUMBER = 3;
private int squashMode_;
/**
* <pre>
* Either NO_ROOT_SQUASH, for allowing root access on the exported directory,
* or ROOT_SQUASH, for not allowing root access. The default is
* NO_ROOT_SQUASH.
* </pre>
*
* <code>.google.cloud.filestore.v1.NfsExportOptions.SquashMode squash_mode = 3;</code>
* @return The enum numeric value on the wire for squashMode.
*/
@java.lang.Override public int getSquashModeValue() {
return squashMode_;
}
/**
* <pre>
* Either NO_ROOT_SQUASH, for allowing root access on the exported directory,
* or ROOT_SQUASH, for not allowing root access. The default is
* NO_ROOT_SQUASH.
* </pre>
*
* <code>.google.cloud.filestore.v1.NfsExportOptions.SquashMode squash_mode = 3;</code>
* @return The squashMode.
*/
@java.lang.Override public com.google.cloud.filestore.v1.NfsExportOptions.SquashMode getSquashMode() {
@SuppressWarnings("deprecation")
com.google.cloud.filestore.v1.NfsExportOptions.SquashMode result = com.google.cloud.filestore.v1.NfsExportOptions.SquashMode.valueOf(squashMode_);
return result == null ? com.google.cloud.filestore.v1.NfsExportOptions.SquashMode.UNRECOGNIZED : result;
}
public static final int ANON_UID_FIELD_NUMBER = 4;
private long anonUid_;
/**
* <pre>
* An integer representing the anonymous user id with a default value of
* 65534.
* Anon_uid may only be set with squash_mode of ROOT_SQUASH. An error will be
* returned if this field is specified for other squash_mode settings.
* </pre>
*
* <code>int64 anon_uid = 4;</code>
* @return The anonUid.
*/
@java.lang.Override
public long getAnonUid() {
return anonUid_;
}
public static final int ANON_GID_FIELD_NUMBER = 5;
private long anonGid_;
/**
* <pre>
* An integer representing the anonymous group id with a default value of
* 65534.
* Anon_gid may only be set with squash_mode of ROOT_SQUASH. An error will be
* returned if this field is specified for other squash_mode settings.
* </pre>
*
* <code>int64 anon_gid = 5;</code>
* @return The anonGid.
*/
@java.lang.Override
public long getAnonGid() {
return anonGid_;
}
private byte memoizedIsInitialized = -1;
@java.lang.Override
public final boolean isInitialized() {
byte isInitialized = memoizedIsInitialized;
if (isInitialized == 1) return true;
if (isInitialized == 0) return false;
memoizedIsInitialized = 1;
return true;
}
@java.lang.Override
public void writeTo(com.google.protobuf.CodedOutputStream output)
throws java.io.IOException {
for (int i = 0; i < ipRanges_.size(); i++) {
com.google.protobuf.GeneratedMessageV3.writeString(output, 1, ipRanges_.getRaw(i));
}
if (accessMode_ != com.google.cloud.filestore.v1.NfsExportOptions.AccessMode.ACCESS_MODE_UNSPECIFIED.getNumber()) {
output.writeEnum(2, accessMode_);
}
if (squashMode_ != com.google.cloud.filestore.v1.NfsExportOptions.SquashMode.SQUASH_MODE_UNSPECIFIED.getNumber()) {
output.writeEnum(3, squashMode_);
}
if (anonUid_ != 0L) {
output.writeInt64(4, anonUid_);
}
if (anonGid_ != 0L) {
output.writeInt64(5, anonGid_);
}
unknownFields.writeTo(output);
}
@java.lang.Override
public int getSerializedSize() {
int size = memoizedSize;
if (size != -1) return size;
size = 0;
{
int dataSize = 0;
for (int i = 0; i < ipRanges_.size(); i++) {
dataSize += computeStringSizeNoTag(ipRanges_.getRaw(i));
}
size += dataSize;
size += 1 * getIpRangesList().size();
}
if (accessMode_ != com.google.cloud.filestore.v1.NfsExportOptions.AccessMode.ACCESS_MODE_UNSPECIFIED.getNumber()) {
size += com.google.protobuf.CodedOutputStream
.computeEnumSize(2, accessMode_);
}
if (squashMode_ != com.google.cloud.filestore.v1.NfsExportOptions.SquashMode.SQUASH_MODE_UNSPECIFIED.getNumber()) {
size += com.google.protobuf.CodedOutputStream
.computeEnumSize(3, squashMode_);
}
if (anonUid_ != 0L) {
size += com.google.protobuf.CodedOutputStream
.computeInt64Size(4, anonUid_);
}
if (anonGid_ != 0L) {
size += com.google.protobuf.CodedOutputStream
.computeInt64Size(5, anonGid_);
}
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.cloud.filestore.v1.NfsExportOptions)) {
return super.equals(obj);
}
com.google.cloud.filestore.v1.NfsExportOptions other = (com.google.cloud.filestore.v1.NfsExportOptions) obj;
if (!getIpRangesList()
.equals(other.getIpRangesList())) return false;
if (accessMode_ != other.accessMode_) return false;
if (squashMode_ != other.squashMode_) return false;
if (getAnonUid()
!= other.getAnonUid()) return false;
if (getAnonGid()
!= other.getAnonGid()) return false;
if (!unknownFields.equals(other.unknownFields)) return false;
return true;
}
@java.lang.Override
public int hashCode() {
if (memoizedHashCode != 0) {
return memoizedHashCode;
}
int hash = 41;
hash = (19 * hash) + getDescriptor().hashCode();
if (getIpRangesCount() > 0) {
hash = (37 * hash) + IP_RANGES_FIELD_NUMBER;
hash = (53 * hash) + getIpRangesList().hashCode();
}
hash = (37 * hash) + ACCESS_MODE_FIELD_NUMBER;
hash = (53 * hash) + accessMode_;
hash = (37 * hash) + SQUASH_MODE_FIELD_NUMBER;
hash = (53 * hash) + squashMode_;
hash = (37 * hash) + ANON_UID_FIELD_NUMBER;
hash = (53 * hash) + com.google.protobuf.Internal.hashLong(
getAnonUid());
hash = (37 * hash) + ANON_GID_FIELD_NUMBER;
hash = (53 * hash) + com.google.protobuf.Internal.hashLong(
getAnonGid());
hash = (29 * hash) + unknownFields.hashCode();
memoizedHashCode = hash;
return hash;
}
public static com.google.cloud.filestore.v1.NfsExportOptions parseFrom(
java.nio.ByteBuffer data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.cloud.filestore.v1.NfsExportOptions parseFrom(
java.nio.ByteBuffer data,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static com.google.cloud.filestore.v1.NfsExportOptions parseFrom(
com.google.protobuf.ByteString data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.cloud.filestore.v1.NfsExportOptions 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.cloud.filestore.v1.NfsExportOptions parseFrom(byte[] data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.cloud.filestore.v1.NfsExportOptions parseFrom(
byte[] data,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static com.google.cloud.filestore.v1.NfsExportOptions parseFrom(java.io.InputStream input)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3
.parseWithIOException(PARSER, input);
}
public static com.google.cloud.filestore.v1.NfsExportOptions 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.cloud.filestore.v1.NfsExportOptions parseDelimitedFrom(java.io.InputStream input)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3
.parseDelimitedWithIOException(PARSER, input);
}
public static com.google.cloud.filestore.v1.NfsExportOptions 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.cloud.filestore.v1.NfsExportOptions parseFrom(
com.google.protobuf.CodedInputStream input)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3
.parseWithIOException(PARSER, input);
}
public static com.google.cloud.filestore.v1.NfsExportOptions 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.cloud.filestore.v1.NfsExportOptions 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>
* NFS export options specifications.
* </pre>
*
* Protobuf type {@code google.cloud.filestore.v1.NfsExportOptions}
*/
public static final class Builder extends
com.google.protobuf.GeneratedMessageV3.Builder<Builder> implements
// @@protoc_insertion_point(builder_implements:google.cloud.filestore.v1.NfsExportOptions)
com.google.cloud.filestore.v1.NfsExportOptionsOrBuilder {
public static final com.google.protobuf.Descriptors.Descriptor
getDescriptor() {
return com.google.cloud.filestore.v1.CloudFilestoreServiceProto.internal_static_google_cloud_filestore_v1_NfsExportOptions_descriptor;
}
@java.lang.Override
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return com.google.cloud.filestore.v1.CloudFilestoreServiceProto.internal_static_google_cloud_filestore_v1_NfsExportOptions_fieldAccessorTable
.ensureFieldAccessorsInitialized(
com.google.cloud.filestore.v1.NfsExportOptions.class, com.google.cloud.filestore.v1.NfsExportOptions.Builder.class);
}
// Construct using com.google.cloud.filestore.v1.NfsExportOptions.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();
ipRanges_ = com.google.protobuf.LazyStringArrayList.EMPTY;
bitField0_ = (bitField0_ & ~0x00000001);
accessMode_ = 0;
squashMode_ = 0;
anonUid_ = 0L;
anonGid_ = 0L;
return this;
}
@java.lang.Override
public com.google.protobuf.Descriptors.Descriptor
getDescriptorForType() {
return com.google.cloud.filestore.v1.CloudFilestoreServiceProto.internal_static_google_cloud_filestore_v1_NfsExportOptions_descriptor;
}
@java.lang.Override
public com.google.cloud.filestore.v1.NfsExportOptions getDefaultInstanceForType() {
return com.google.cloud.filestore.v1.NfsExportOptions.getDefaultInstance();
}
@java.lang.Override
public com.google.cloud.filestore.v1.NfsExportOptions build() {
com.google.cloud.filestore.v1.NfsExportOptions result = buildPartial();
if (!result.isInitialized()) {
throw newUninitializedMessageException(result);
}
return result;
}
@java.lang.Override
public com.google.cloud.filestore.v1.NfsExportOptions buildPartial() {
com.google.cloud.filestore.v1.NfsExportOptions result = new com.google.cloud.filestore.v1.NfsExportOptions(this);
int from_bitField0_ = bitField0_;
if (((bitField0_ & 0x00000001) != 0)) {
ipRanges_ = ipRanges_.getUnmodifiableView();
bitField0_ = (bitField0_ & ~0x00000001);
}
result.ipRanges_ = ipRanges_;
result.accessMode_ = accessMode_;
result.squashMode_ = squashMode_;
result.anonUid_ = anonUid_;
result.anonGid_ = anonGid_;
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.cloud.filestore.v1.NfsExportOptions) {
return mergeFrom((com.google.cloud.filestore.v1.NfsExportOptions)other);
} else {
super.mergeFrom(other);
return this;
}
}
public Builder mergeFrom(com.google.cloud.filestore.v1.NfsExportOptions other) {
if (other == com.google.cloud.filestore.v1.NfsExportOptions.getDefaultInstance()) return this;
if (!other.ipRanges_.isEmpty()) {
if (ipRanges_.isEmpty()) {
ipRanges_ = other.ipRanges_;
bitField0_ = (bitField0_ & ~0x00000001);
} else {
ensureIpRangesIsMutable();
ipRanges_.addAll(other.ipRanges_);
}
onChanged();
}
if (other.accessMode_ != 0) {
setAccessModeValue(other.getAccessModeValue());
}
if (other.squashMode_ != 0) {
setSquashModeValue(other.getSquashModeValue());
}
if (other.getAnonUid() != 0L) {
setAnonUid(other.getAnonUid());
}
if (other.getAnonGid() != 0L) {
setAnonGid(other.getAnonGid());
}
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.cloud.filestore.v1.NfsExportOptions parsedMessage = null;
try {
parsedMessage = PARSER.parsePartialFrom(input, extensionRegistry);
} catch (com.google.protobuf.InvalidProtocolBufferException e) {
parsedMessage = (com.google.cloud.filestore.v1.NfsExportOptions) e.getUnfinishedMessage();
throw e.unwrapIOException();
} finally {
if (parsedMessage != null) {
mergeFrom(parsedMessage);
}
}
return this;
}
private int bitField0_;
private com.google.protobuf.LazyStringList ipRanges_ = com.google.protobuf.LazyStringArrayList.EMPTY;
private void ensureIpRangesIsMutable() {
if (!((bitField0_ & 0x00000001) != 0)) {
ipRanges_ = new com.google.protobuf.LazyStringArrayList(ipRanges_);
bitField0_ |= 0x00000001;
}
}
/**
* <pre>
* List of either an IPv4 addresses in the format
* `{octet1}.{octet2}.{octet3}.{octet4}` or CIDR ranges in the format
* `{octet1}.{octet2}.{octet3}.{octet4}/{mask size}` which may mount the
* file share.
* Overlapping IP ranges are not allowed, both within and across
* NfsExportOptions. An error will be returned.
* The limit is 64 IP ranges/addresses for each FileShareConfig among all
* NfsExportOptions.
* </pre>
*
* <code>repeated string ip_ranges = 1;</code>
* @return A list containing the ipRanges.
*/
public com.google.protobuf.ProtocolStringList
getIpRangesList() {
return ipRanges_.getUnmodifiableView();
}
/**
* <pre>
* List of either an IPv4 addresses in the format
* `{octet1}.{octet2}.{octet3}.{octet4}` or CIDR ranges in the format
* `{octet1}.{octet2}.{octet3}.{octet4}/{mask size}` which may mount the
* file share.
* Overlapping IP ranges are not allowed, both within and across
* NfsExportOptions. An error will be returned.
* The limit is 64 IP ranges/addresses for each FileShareConfig among all
* NfsExportOptions.
* </pre>
*
* <code>repeated string ip_ranges = 1;</code>
* @return The count of ipRanges.
*/
public int getIpRangesCount() {
return ipRanges_.size();
}
/**
* <pre>
* List of either an IPv4 addresses in the format
* `{octet1}.{octet2}.{octet3}.{octet4}` or CIDR ranges in the format
* `{octet1}.{octet2}.{octet3}.{octet4}/{mask size}` which may mount the
* file share.
* Overlapping IP ranges are not allowed, both within and across
* NfsExportOptions. An error will be returned.
* The limit is 64 IP ranges/addresses for each FileShareConfig among all
* NfsExportOptions.
* </pre>
*
* <code>repeated string ip_ranges = 1;</code>
* @param index The index of the element to return.
* @return The ipRanges at the given index.
*/
public java.lang.String getIpRanges(int index) {
return ipRanges_.get(index);
}
/**
* <pre>
* List of either an IPv4 addresses in the format
* `{octet1}.{octet2}.{octet3}.{octet4}` or CIDR ranges in the format
* `{octet1}.{octet2}.{octet3}.{octet4}/{mask size}` which may mount the
* file share.
* Overlapping IP ranges are not allowed, both within and across
* NfsExportOptions. An error will be returned.
* The limit is 64 IP ranges/addresses for each FileShareConfig among all
* NfsExportOptions.
* </pre>
*
* <code>repeated string ip_ranges = 1;</code>
* @param index The index of the value to return.
* @return The bytes of the ipRanges at the given index.
*/
public com.google.protobuf.ByteString
getIpRangesBytes(int index) {
return ipRanges_.getByteString(index);
}
/**
* <pre>
* List of either an IPv4 addresses in the format
* `{octet1}.{octet2}.{octet3}.{octet4}` or CIDR ranges in the format
* `{octet1}.{octet2}.{octet3}.{octet4}/{mask size}` which may mount the
* file share.
* Overlapping IP ranges are not allowed, both within and across
* NfsExportOptions. An error will be returned.
* The limit is 64 IP ranges/addresses for each FileShareConfig among all
* NfsExportOptions.
* </pre>
*
* <code>repeated string ip_ranges = 1;</code>
* @param index The index to set the value at.
* @param value The ipRanges to set.
* @return This builder for chaining.
*/
public Builder setIpRanges(
int index, java.lang.String value) {
if (value == null) {
throw new NullPointerException();
}
ensureIpRangesIsMutable();
ipRanges_.set(index, value);
onChanged();
return this;
}
/**
* <pre>
* List of either an IPv4 addresses in the format
* `{octet1}.{octet2}.{octet3}.{octet4}` or CIDR ranges in the format
* `{octet1}.{octet2}.{octet3}.{octet4}/{mask size}` which may mount the
* file share.
* Overlapping IP ranges are not allowed, both within and across
* NfsExportOptions. An error will be returned.
* The limit is 64 IP ranges/addresses for each FileShareConfig among all
* NfsExportOptions.
* </pre>
*
* <code>repeated string ip_ranges = 1;</code>
* @param value The ipRanges to add.
* @return This builder for chaining.
*/
public Builder addIpRanges(
java.lang.String value) {
if (value == null) {
throw new NullPointerException();
}
ensureIpRangesIsMutable();
ipRanges_.add(value);
onChanged();
return this;
}
/**
* <pre>
* List of either an IPv4 addresses in the format
* `{octet1}.{octet2}.{octet3}.{octet4}` or CIDR ranges in the format
* `{octet1}.{octet2}.{octet3}.{octet4}/{mask size}` which may mount the
* file share.
* Overlapping IP ranges are not allowed, both within and across
* NfsExportOptions. An error will be returned.
* The limit is 64 IP ranges/addresses for each FileShareConfig among all
* NfsExportOptions.
* </pre>
*
* <code>repeated string ip_ranges = 1;</code>
* @param values The ipRanges to add.
* @return This builder for chaining.
*/
public Builder addAllIpRanges(
java.lang.Iterable<java.lang.String> values) {
ensureIpRangesIsMutable();
com.google.protobuf.AbstractMessageLite.Builder.addAll(
values, ipRanges_);
onChanged();
return this;
}
/**
* <pre>
* List of either an IPv4 addresses in the format
* `{octet1}.{octet2}.{octet3}.{octet4}` or CIDR ranges in the format
* `{octet1}.{octet2}.{octet3}.{octet4}/{mask size}` which may mount the
* file share.
* Overlapping IP ranges are not allowed, both within and across
* NfsExportOptions. An error will be returned.
* The limit is 64 IP ranges/addresses for each FileShareConfig among all
* NfsExportOptions.
* </pre>
*
* <code>repeated string ip_ranges = 1;</code>
* @return This builder for chaining.
*/
public Builder clearIpRanges() {
ipRanges_ = com.google.protobuf.LazyStringArrayList.EMPTY;
bitField0_ = (bitField0_ & ~0x00000001);
onChanged();
return this;
}
/**
* <pre>
* List of either an IPv4 addresses in the format
* `{octet1}.{octet2}.{octet3}.{octet4}` or CIDR ranges in the format
* `{octet1}.{octet2}.{octet3}.{octet4}/{mask size}` which may mount the
* file share.
* Overlapping IP ranges are not allowed, both within and across
* NfsExportOptions. An error will be returned.
* The limit is 64 IP ranges/addresses for each FileShareConfig among all
* NfsExportOptions.
* </pre>
*
* <code>repeated string ip_ranges = 1;</code>
* @param value The bytes of the ipRanges to add.
* @return This builder for chaining.
*/
public Builder addIpRangesBytes(
com.google.protobuf.ByteString value) {
if (value == null) {
throw new NullPointerException();
}
checkByteStringIsUtf8(value);
ensureIpRangesIsMutable();
ipRanges_.add(value);
onChanged();
return this;
}
private int accessMode_ = 0;
/**
* <pre>
* Either READ_ONLY, for allowing only read requests on the exported
* directory, or READ_WRITE, for allowing both read and write requests.
* The default is READ_WRITE.
* </pre>
*
* <code>.google.cloud.filestore.v1.NfsExportOptions.AccessMode access_mode = 2;</code>
* @return The enum numeric value on the wire for accessMode.
*/
@java.lang.Override public int getAccessModeValue() {
return accessMode_;
}
/**
* <pre>
* Either READ_ONLY, for allowing only read requests on the exported
* directory, or READ_WRITE, for allowing both read and write requests.
* The default is READ_WRITE.
* </pre>
*
* <code>.google.cloud.filestore.v1.NfsExportOptions.AccessMode access_mode = 2;</code>
* @param value The enum numeric value on the wire for accessMode to set.
* @return This builder for chaining.
*/
public Builder setAccessModeValue(int value) {
accessMode_ = value;
onChanged();
return this;
}
/**
* <pre>
* Either READ_ONLY, for allowing only read requests on the exported
* directory, or READ_WRITE, for allowing both read and write requests.
* The default is READ_WRITE.
* </pre>
*
* <code>.google.cloud.filestore.v1.NfsExportOptions.AccessMode access_mode = 2;</code>
* @return The accessMode.
*/
@java.lang.Override
public com.google.cloud.filestore.v1.NfsExportOptions.AccessMode getAccessMode() {
@SuppressWarnings("deprecation")
com.google.cloud.filestore.v1.NfsExportOptions.AccessMode result = com.google.cloud.filestore.v1.NfsExportOptions.AccessMode.valueOf(accessMode_);
return result == null ? com.google.cloud.filestore.v1.NfsExportOptions.AccessMode.UNRECOGNIZED : result;
}
/**
* <pre>
* Either READ_ONLY, for allowing only read requests on the exported
* directory, or READ_WRITE, for allowing both read and write requests.
* The default is READ_WRITE.
* </pre>
*
* <code>.google.cloud.filestore.v1.NfsExportOptions.AccessMode access_mode = 2;</code>
* @param value The accessMode to set.
* @return This builder for chaining.
*/
public Builder setAccessMode(com.google.cloud.filestore.v1.NfsExportOptions.AccessMode value) {
if (value == null) {
throw new NullPointerException();
}
accessMode_ = value.getNumber();
onChanged();
return this;
}
/**
* <pre>
* Either READ_ONLY, for allowing only read requests on the exported
* directory, or READ_WRITE, for allowing both read and write requests.
* The default is READ_WRITE.
* </pre>
*
* <code>.google.cloud.filestore.v1.NfsExportOptions.AccessMode access_mode = 2;</code>
* @return This builder for chaining.
*/
public Builder clearAccessMode() {
accessMode_ = 0;
onChanged();
return this;
}
private int squashMode_ = 0;
/**
* <pre>
* Either NO_ROOT_SQUASH, for allowing root access on the exported directory,
* or ROOT_SQUASH, for not allowing root access. The default is
* NO_ROOT_SQUASH.
* </pre>
*
* <code>.google.cloud.filestore.v1.NfsExportOptions.SquashMode squash_mode = 3;</code>
* @return The enum numeric value on the wire for squashMode.
*/
@java.lang.Override public int getSquashModeValue() {
return squashMode_;
}
/**
* <pre>
* Either NO_ROOT_SQUASH, for allowing root access on the exported directory,
* or ROOT_SQUASH, for not allowing root access. The default is
* NO_ROOT_SQUASH.
* </pre>
*
* <code>.google.cloud.filestore.v1.NfsExportOptions.SquashMode squash_mode = 3;</code>
* @param value The enum numeric value on the wire for squashMode to set.
* @return This builder for chaining.
*/
public Builder setSquashModeValue(int value) {
squashMode_ = value;
onChanged();
return this;
}
/**
* <pre>
* Either NO_ROOT_SQUASH, for allowing root access on the exported directory,
* or ROOT_SQUASH, for not allowing root access. The default is
* NO_ROOT_SQUASH.
* </pre>
*
* <code>.google.cloud.filestore.v1.NfsExportOptions.SquashMode squash_mode = 3;</code>
* @return The squashMode.
*/
@java.lang.Override
public com.google.cloud.filestore.v1.NfsExportOptions.SquashMode getSquashMode() {
@SuppressWarnings("deprecation")
com.google.cloud.filestore.v1.NfsExportOptions.SquashMode result = com.google.cloud.filestore.v1.NfsExportOptions.SquashMode.valueOf(squashMode_);
return result == null ? com.google.cloud.filestore.v1.NfsExportOptions.SquashMode.UNRECOGNIZED : result;
}
/**
* <pre>
* Either NO_ROOT_SQUASH, for allowing root access on the exported directory,
* or ROOT_SQUASH, for not allowing root access. The default is
* NO_ROOT_SQUASH.
* </pre>
*
* <code>.google.cloud.filestore.v1.NfsExportOptions.SquashMode squash_mode = 3;</code>
* @param value The squashMode to set.
* @return This builder for chaining.
*/
public Builder setSquashMode(com.google.cloud.filestore.v1.NfsExportOptions.SquashMode value) {
if (value == null) {
throw new NullPointerException();
}
squashMode_ = value.getNumber();
onChanged();
return this;
}
/**
* <pre>
* Either NO_ROOT_SQUASH, for allowing root access on the exported directory,
* or ROOT_SQUASH, for not allowing root access. The default is
* NO_ROOT_SQUASH.
* </pre>
*
* <code>.google.cloud.filestore.v1.NfsExportOptions.SquashMode squash_mode = 3;</code>
* @return This builder for chaining.
*/
public Builder clearSquashMode() {
squashMode_ = 0;
onChanged();
return this;
}
private long anonUid_ ;
/**
* <pre>
* An integer representing the anonymous user id with a default value of
* 65534.
* Anon_uid may only be set with squash_mode of ROOT_SQUASH. An error will be
* returned if this field is specified for other squash_mode settings.
* </pre>
*
* <code>int64 anon_uid = 4;</code>
* @return The anonUid.
*/
@java.lang.Override
public long getAnonUid() {
return anonUid_;
}
/**
* <pre>
* An integer representing the anonymous user id with a default value of
* 65534.
* Anon_uid may only be set with squash_mode of ROOT_SQUASH. An error will be
* returned if this field is specified for other squash_mode settings.
* </pre>
*
* <code>int64 anon_uid = 4;</code>
* @param value The anonUid to set.
* @return This builder for chaining.
*/
public Builder setAnonUid(long value) {
anonUid_ = value;
onChanged();
return this;
}
/**
* <pre>
* An integer representing the anonymous user id with a default value of
* 65534.
* Anon_uid may only be set with squash_mode of ROOT_SQUASH. An error will be
* returned if this field is specified for other squash_mode settings.
* </pre>
*
* <code>int64 anon_uid = 4;</code>
* @return This builder for chaining.
*/
public Builder clearAnonUid() {
anonUid_ = 0L;
onChanged();
return this;
}
private long anonGid_ ;
/**
* <pre>
* An integer representing the anonymous group id with a default value of
* 65534.
* Anon_gid may only be set with squash_mode of ROOT_SQUASH. An error will be
* returned if this field is specified for other squash_mode settings.
* </pre>
*
* <code>int64 anon_gid = 5;</code>
* @return The anonGid.
*/
@java.lang.Override
public long getAnonGid() {
return anonGid_;
}
/**
* <pre>
* An integer representing the anonymous group id with a default value of
* 65534.
* Anon_gid may only be set with squash_mode of ROOT_SQUASH. An error will be
* returned if this field is specified for other squash_mode settings.
* </pre>
*
* <code>int64 anon_gid = 5;</code>
* @param value The anonGid to set.
* @return This builder for chaining.
*/
public Builder setAnonGid(long value) {
anonGid_ = value;
onChanged();
return this;
}
/**
* <pre>
* An integer representing the anonymous group id with a default value of
* 65534.
* Anon_gid may only be set with squash_mode of ROOT_SQUASH. An error will be
* returned if this field is specified for other squash_mode settings.
* </pre>
*
* <code>int64 anon_gid = 5;</code>
* @return This builder for chaining.
*/
public Builder clearAnonGid() {
anonGid_ = 0L;
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.cloud.filestore.v1.NfsExportOptions)
}
// @@protoc_insertion_point(class_scope:google.cloud.filestore.v1.NfsExportOptions)
private static final com.google.cloud.filestore.v1.NfsExportOptions DEFAULT_INSTANCE;
static {
DEFAULT_INSTANCE = new com.google.cloud.filestore.v1.NfsExportOptions();
}
public static com.google.cloud.filestore.v1.NfsExportOptions getDefaultInstance() {
return DEFAULT_INSTANCE;
}
private static final com.google.protobuf.Parser<NfsExportOptions>
PARSER = new com.google.protobuf.AbstractParser<NfsExportOptions>() {
@java.lang.Override
public NfsExportOptions parsePartialFrom(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return new NfsExportOptions(input, extensionRegistry);
}
};
public static com.google.protobuf.Parser<NfsExportOptions> parser() {
return PARSER;
}
@java.lang.Override
public com.google.protobuf.Parser<NfsExportOptions> getParserForType() {
return PARSER;
}
@java.lang.Override
public com.google.cloud.filestore.v1.NfsExportOptions getDefaultInstanceForType() {
return DEFAULT_INSTANCE;
}
}
|
package edu.colorado.cs.cirrus.android;
import android.content.Context;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import edu.colorado.cs.cirrus.android.R;
import android.app.Activity;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.preference.Preference;
import android.preference.Preference.OnPreferenceClickListener;
import android.preference.PreferenceActivity;
import android.widget.Toast;
public class CirrusPreferenceActivity extends PreferenceActivity {
private SharedPreferences customCirrusPrefs;
private Preference setHomeLocPref;
private Preference gpsFreqPref;
private LocationManager locManager;
private LocationListener locListener;
private simplePreferenceClickListener myPreferenceClickListener;
private double latitude = 0.0;
private double longitude = 0.0;
@Override
protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
//Setup layout
addPreferencesFromResource(R.xml.preferences);
//On click listener
myPreferenceClickListener = new simplePreferenceClickListener();
//Attach to the Preferences from the layout
setHomeLocPref = (Preference) findPreference("setHomeLocPref");
gpsFreqPref = (Preference) findPreference("gpsFreqPref");
//Set on click listener
setHomeLocPref.setOnPreferenceClickListener(myPreferenceClickListener);
// Setup the location stuff
locManager = (LocationManager) getSystemService(
Context.LOCATION_SERVICE);
locListener = new MyLocationListener();
}
@Override
protected void onResume() {
super.onResume();
//Do work for restoring saved prefs
customCirrusPrefs = getSharedPreferences( "customCirrusPrefs", Activity.MODE_PRIVATE);
//Start polling for GPS information every 2 seconds
locManager.requestLocationUpdates(
LocationManager.GPS_PROVIDER, 2000, 0, locListener);
}
@Override
protected void onPause() {
//Stop polling for GPS info
locManager.removeUpdates(locListener);
super.onPause();
}
class simplePreferenceClickListener implements OnPreferenceClickListener{
public boolean onPreferenceClick(Preference preference) {
// Get ready to edit the saved preferences
SharedPreferences.Editor editor = customCirrusPrefs.edit();
if ( preference.equals(setHomeLocPref) ){
Toast.makeText(getBaseContext(), "Setting home location",
Toast.LENGTH_SHORT).show();
if( latitude == 0.0 || longitude == 0.0 ){
Toast.makeText(getBaseContext(), "Error getting GPS info",
Toast.LENGTH_LONG).show();
return false;
}
editor.putFloat("homeLatitude", (float) latitude);
editor.putFloat("homeLongitude", (float) longitude);
Toast.makeText(getBaseContext(), "Latitude: " + latitude
+ ", Longitude: " + longitude,
Toast.LENGTH_SHORT).show();
} else if ( preference.equals(gpsFreqPref) ) {
editor.putString("gpsFreq", gpsFreqPref.getKey());
Toast.makeText(getBaseContext(), "gpsFreq: "
+ gpsFreqPref.getKey(), Toast.LENGTH_SHORT).show();
}
//Actually do the saving
return editor.commit();
}
}
class MyLocationListener implements LocationListener {
public void onLocationChanged(Location loc) {
//Just update latitude and longitude
latitude = loc.getLatitude();
longitude = loc.getLongitude();
}
public void onProviderDisabled(String provider) {
Toast.makeText(getBaseContext(), "GPS Disabled",
Toast.LENGTH_SHORT).show();
}
public void onProviderEnabled(String provider) {
Toast.makeText(getBaseContext(), "GPS Enabled",
Toast.LENGTH_SHORT).show();
}
public void onStatusChanged(String provider, int status,
Bundle extras) {
}
}
}
|
package com.yangdb.fuse.executor.cursor.discrete;
import com.yangdb.fuse.executor.CompositeTraversalCursorContext;
import com.yangdb.fuse.executor.cursor.TraversalCursorContext;
import com.yangdb.fuse.model.results.AssignmentsQueryResult;
import com.yangdb.fuse.model.results.Entity;
import com.yangdb.fuse.model.results.Relationship;
import javaslang.collection.Stream;
import org.junit.Assert;
import org.junit.Test;
import org.mockito.Mockito;
import java.util.Collections;
import static com.yangdb.fuse.model.results.Assignment.Builder.instance;
import static org.mockito.Matchers.anyInt;
import static org.mockito.Mockito.when;
public class InnerQueryCursorTest {
@Test
public void testSingleElement() {
TraversalCursorContext context = Mockito.mock(TraversalCursorContext.class);
PathsTraversalCursor cursorMock = Mockito.mock(PathsTraversalCursor.class);
AssignmentsQueryResult res1 = AssignmentsQueryResult.Builder.instance().
withAssignment(
instance().withEntity(Entity.Builder.instance().withEID("123")
.withETag(Stream.of("Child").toJavaSet())
.withEType("Entity").build()).build())
.build();
when(cursorMock.getNextResults(anyInt())).thenReturn(res1, AssignmentsQueryResult.Builder.instance().build());
InnerQueryCursor cursor = new InnerQueryCursor(new CompositeTraversalCursorContext(context,Collections.emptyList()), cursorMock, null);
AssignmentsQueryResult<Entity, Relationship> nextResults = (AssignmentsQueryResult<Entity, Relationship>) cursor.getNextResults(1000);
Assert.assertEquals(1, nextResults.getAssignments().size());
Assert.assertEquals(1, nextResults.getAssignments().get(0).getEntities().size());
Assert.assertEquals("123", nextResults.getAssignments().get(0).getEntities().get(0).geteID());
Assert.assertTrue(nextResults.getAssignments().get(0).getEntities().get(0).geteTag().contains("Child"));
Assert.assertEquals("Entity", nextResults.getAssignments().get(0).getEntities().get(0).geteType());
}
@Test
public void testOnlyRootsElement() {
//todo
}
@Test
public void testSinglePath() {
//todo
}
}
|
/*
* 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.ecs.model;
import java.io.Serializable;
import javax.annotation.Generated;
import com.amazonaws.protocol.StructuredPojo;
import com.amazonaws.protocol.ProtocolMarshaller;
/**
* <p>
* An object representing a container health check. Health check parameters that are specified in a container definition
* override any Docker health checks that exist in the container image (such as those specified in a parent image or
* from the image's Dockerfile).
* </p>
* <p>
* The following are notes about container health check support:
* </p>
* <ul>
* <li>
* <p>
* Container health checks require version 1.17.0 or greater of the Amazon ECS container agent. For more information,
* see <a href="https://docs.aws.amazon.com/AmazonECS/latest/developerguide/ecs-agent-update.html">Updating the Amazon
* ECS Container Agent</a>.
* </p>
* </li>
* <li>
* <p>
* Container health checks are supported for Fargate tasks if you are using platform version 1.1.0 or greater. For more
* information, see <a href="https://docs.aws.amazon.com/AmazonECS/latest/developerguide/platform_versions.html">AWS
* Fargate Platform Versions</a>.
* </p>
* </li>
* <li>
* <p>
* Container health checks are not supported for tasks that are part of a service that is configured to use a Classic
* Load Balancer.
* </p>
* </li>
* </ul>
*
* @see <a href="http://docs.aws.amazon.com/goto/WebAPI/ecs-2014-11-13/HealthCheck" target="_top">AWS API
* Documentation</a>
*/
@Generated("com.amazonaws:aws-java-sdk-code-generator")
public class HealthCheck implements Serializable, Cloneable, StructuredPojo {
/**
* <p>
* A string array representing the command that the container runs to determine if it is healthy. The string array
* must start with <code>CMD</code> to execute the command arguments directly, or <code>CMD-SHELL</code> to run the
* command with the container's default shell. For example:
* </p>
* <p>
* <code>[ "CMD-SHELL", "curl -f http://localhost/ || exit 1" ]</code>
* </p>
* <p>
* An exit code of 0 indicates success, and non-zero exit code indicates failure. For more information, see
* <code>HealthCheck</code> in the <a
* href="https://docs.docker.com/engine/api/v1.35/#operation/ContainerCreate">Create a container</a> section of the
* <a href="https://docs.docker.com/engine/api/v1.35/">Docker Remote API</a>.
* </p>
*/
private com.amazonaws.internal.SdkInternalList<String> command;
/**
* <p>
* The time period in seconds between each health check execution. You may specify between 5 and 300 seconds. The
* default value is 30 seconds.
* </p>
*/
private Integer interval;
/**
* <p>
* The time period in seconds to wait for a health check to succeed before it is considered a failure. You may
* specify between 2 and 60 seconds. The default value is 5.
* </p>
*/
private Integer timeout;
/**
* <p>
* The number of times to retry a failed health check before the container is considered unhealthy. You may specify
* between 1 and 10 retries. The default value is 3.
* </p>
*/
private Integer retries;
/**
* <p>
* The optional grace period within which to provide containers time to bootstrap before failed health checks count
* towards the maximum number of retries. You may specify between 0 and 300 seconds. The <code>startPeriod</code> is
* disabled by default.
* </p>
* <note>
* <p>
* If a health check succeeds within the <code>startPeriod</code>, then the container is considered healthy and any
* subsequent failures count toward the maximum number of retries.
* </p>
* </note>
*/
private Integer startPeriod;
/**
* <p>
* A string array representing the command that the container runs to determine if it is healthy. The string array
* must start with <code>CMD</code> to execute the command arguments directly, or <code>CMD-SHELL</code> to run the
* command with the container's default shell. For example:
* </p>
* <p>
* <code>[ "CMD-SHELL", "curl -f http://localhost/ || exit 1" ]</code>
* </p>
* <p>
* An exit code of 0 indicates success, and non-zero exit code indicates failure. For more information, see
* <code>HealthCheck</code> in the <a
* href="https://docs.docker.com/engine/api/v1.35/#operation/ContainerCreate">Create a container</a> section of the
* <a href="https://docs.docker.com/engine/api/v1.35/">Docker Remote API</a>.
* </p>
*
* @return A string array representing the command that the container runs to determine if it is healthy. The string
* array must start with <code>CMD</code> to execute the command arguments directly, or
* <code>CMD-SHELL</code> to run the command with the container's default shell. For example:</p>
* <p>
* <code>[ "CMD-SHELL", "curl -f http://localhost/ || exit 1" ]</code>
* </p>
* <p>
* An exit code of 0 indicates success, and non-zero exit code indicates failure. For more information, see
* <code>HealthCheck</code> in the <a
* href="https://docs.docker.com/engine/api/v1.35/#operation/ContainerCreate">Create a container</a> section
* of the <a href="https://docs.docker.com/engine/api/v1.35/">Docker Remote API</a>.
*/
public java.util.List<String> getCommand() {
if (command == null) {
command = new com.amazonaws.internal.SdkInternalList<String>();
}
return command;
}
/**
* <p>
* A string array representing the command that the container runs to determine if it is healthy. The string array
* must start with <code>CMD</code> to execute the command arguments directly, or <code>CMD-SHELL</code> to run the
* command with the container's default shell. For example:
* </p>
* <p>
* <code>[ "CMD-SHELL", "curl -f http://localhost/ || exit 1" ]</code>
* </p>
* <p>
* An exit code of 0 indicates success, and non-zero exit code indicates failure. For more information, see
* <code>HealthCheck</code> in the <a
* href="https://docs.docker.com/engine/api/v1.35/#operation/ContainerCreate">Create a container</a> section of the
* <a href="https://docs.docker.com/engine/api/v1.35/">Docker Remote API</a>.
* </p>
*
* @param command
* A string array representing the command that the container runs to determine if it is healthy. The string
* array must start with <code>CMD</code> to execute the command arguments directly, or
* <code>CMD-SHELL</code> to run the command with the container's default shell. For example:</p>
* <p>
* <code>[ "CMD-SHELL", "curl -f http://localhost/ || exit 1" ]</code>
* </p>
* <p>
* An exit code of 0 indicates success, and non-zero exit code indicates failure. For more information, see
* <code>HealthCheck</code> in the <a
* href="https://docs.docker.com/engine/api/v1.35/#operation/ContainerCreate">Create a container</a> section
* of the <a href="https://docs.docker.com/engine/api/v1.35/">Docker Remote API</a>.
*/
public void setCommand(java.util.Collection<String> command) {
if (command == null) {
this.command = null;
return;
}
this.command = new com.amazonaws.internal.SdkInternalList<String>(command);
}
/**
* <p>
* A string array representing the command that the container runs to determine if it is healthy. The string array
* must start with <code>CMD</code> to execute the command arguments directly, or <code>CMD-SHELL</code> to run the
* command with the container's default shell. For example:
* </p>
* <p>
* <code>[ "CMD-SHELL", "curl -f http://localhost/ || exit 1" ]</code>
* </p>
* <p>
* An exit code of 0 indicates success, and non-zero exit code indicates failure. For more information, see
* <code>HealthCheck</code> in the <a
* href="https://docs.docker.com/engine/api/v1.35/#operation/ContainerCreate">Create a container</a> section of the
* <a href="https://docs.docker.com/engine/api/v1.35/">Docker Remote API</a>.
* </p>
* <p>
* <b>NOTE:</b> This method appends the values to the existing list (if any). Use
* {@link #setCommand(java.util.Collection)} or {@link #withCommand(java.util.Collection)} if you want to override
* the existing values.
* </p>
*
* @param command
* A string array representing the command that the container runs to determine if it is healthy. The string
* array must start with <code>CMD</code> to execute the command arguments directly, or
* <code>CMD-SHELL</code> to run the command with the container's default shell. For example:</p>
* <p>
* <code>[ "CMD-SHELL", "curl -f http://localhost/ || exit 1" ]</code>
* </p>
* <p>
* An exit code of 0 indicates success, and non-zero exit code indicates failure. For more information, see
* <code>HealthCheck</code> in the <a
* href="https://docs.docker.com/engine/api/v1.35/#operation/ContainerCreate">Create a container</a> section
* of the <a href="https://docs.docker.com/engine/api/v1.35/">Docker Remote API</a>.
* @return Returns a reference to this object so that method calls can be chained together.
*/
public HealthCheck withCommand(String... command) {
if (this.command == null) {
setCommand(new com.amazonaws.internal.SdkInternalList<String>(command.length));
}
for (String ele : command) {
this.command.add(ele);
}
return this;
}
/**
* <p>
* A string array representing the command that the container runs to determine if it is healthy. The string array
* must start with <code>CMD</code> to execute the command arguments directly, or <code>CMD-SHELL</code> to run the
* command with the container's default shell. For example:
* </p>
* <p>
* <code>[ "CMD-SHELL", "curl -f http://localhost/ || exit 1" ]</code>
* </p>
* <p>
* An exit code of 0 indicates success, and non-zero exit code indicates failure. For more information, see
* <code>HealthCheck</code> in the <a
* href="https://docs.docker.com/engine/api/v1.35/#operation/ContainerCreate">Create a container</a> section of the
* <a href="https://docs.docker.com/engine/api/v1.35/">Docker Remote API</a>.
* </p>
*
* @param command
* A string array representing the command that the container runs to determine if it is healthy. The string
* array must start with <code>CMD</code> to execute the command arguments directly, or
* <code>CMD-SHELL</code> to run the command with the container's default shell. For example:</p>
* <p>
* <code>[ "CMD-SHELL", "curl -f http://localhost/ || exit 1" ]</code>
* </p>
* <p>
* An exit code of 0 indicates success, and non-zero exit code indicates failure. For more information, see
* <code>HealthCheck</code> in the <a
* href="https://docs.docker.com/engine/api/v1.35/#operation/ContainerCreate">Create a container</a> section
* of the <a href="https://docs.docker.com/engine/api/v1.35/">Docker Remote API</a>.
* @return Returns a reference to this object so that method calls can be chained together.
*/
public HealthCheck withCommand(java.util.Collection<String> command) {
setCommand(command);
return this;
}
/**
* <p>
* The time period in seconds between each health check execution. You may specify between 5 and 300 seconds. The
* default value is 30 seconds.
* </p>
*
* @param interval
* The time period in seconds between each health check execution. You may specify between 5 and 300 seconds.
* The default value is 30 seconds.
*/
public void setInterval(Integer interval) {
this.interval = interval;
}
/**
* <p>
* The time period in seconds between each health check execution. You may specify between 5 and 300 seconds. The
* default value is 30 seconds.
* </p>
*
* @return The time period in seconds between each health check execution. You may specify between 5 and 300
* seconds. The default value is 30 seconds.
*/
public Integer getInterval() {
return this.interval;
}
/**
* <p>
* The time period in seconds between each health check execution. You may specify between 5 and 300 seconds. The
* default value is 30 seconds.
* </p>
*
* @param interval
* The time period in seconds between each health check execution. You may specify between 5 and 300 seconds.
* The default value is 30 seconds.
* @return Returns a reference to this object so that method calls can be chained together.
*/
public HealthCheck withInterval(Integer interval) {
setInterval(interval);
return this;
}
/**
* <p>
* The time period in seconds to wait for a health check to succeed before it is considered a failure. You may
* specify between 2 and 60 seconds. The default value is 5.
* </p>
*
* @param timeout
* The time period in seconds to wait for a health check to succeed before it is considered a failure. You
* may specify between 2 and 60 seconds. The default value is 5.
*/
public void setTimeout(Integer timeout) {
this.timeout = timeout;
}
/**
* <p>
* The time period in seconds to wait for a health check to succeed before it is considered a failure. You may
* specify between 2 and 60 seconds. The default value is 5.
* </p>
*
* @return The time period in seconds to wait for a health check to succeed before it is considered a failure. You
* may specify between 2 and 60 seconds. The default value is 5.
*/
public Integer getTimeout() {
return this.timeout;
}
/**
* <p>
* The time period in seconds to wait for a health check to succeed before it is considered a failure. You may
* specify between 2 and 60 seconds. The default value is 5.
* </p>
*
* @param timeout
* The time period in seconds to wait for a health check to succeed before it is considered a failure. You
* may specify between 2 and 60 seconds. The default value is 5.
* @return Returns a reference to this object so that method calls can be chained together.
*/
public HealthCheck withTimeout(Integer timeout) {
setTimeout(timeout);
return this;
}
/**
* <p>
* The number of times to retry a failed health check before the container is considered unhealthy. You may specify
* between 1 and 10 retries. The default value is 3.
* </p>
*
* @param retries
* The number of times to retry a failed health check before the container is considered unhealthy. You may
* specify between 1 and 10 retries. The default value is 3.
*/
public void setRetries(Integer retries) {
this.retries = retries;
}
/**
* <p>
* The number of times to retry a failed health check before the container is considered unhealthy. You may specify
* between 1 and 10 retries. The default value is 3.
* </p>
*
* @return The number of times to retry a failed health check before the container is considered unhealthy. You may
* specify between 1 and 10 retries. The default value is 3.
*/
public Integer getRetries() {
return this.retries;
}
/**
* <p>
* The number of times to retry a failed health check before the container is considered unhealthy. You may specify
* between 1 and 10 retries. The default value is 3.
* </p>
*
* @param retries
* The number of times to retry a failed health check before the container is considered unhealthy. You may
* specify between 1 and 10 retries. The default value is 3.
* @return Returns a reference to this object so that method calls can be chained together.
*/
public HealthCheck withRetries(Integer retries) {
setRetries(retries);
return this;
}
/**
* <p>
* The optional grace period within which to provide containers time to bootstrap before failed health checks count
* towards the maximum number of retries. You may specify between 0 and 300 seconds. The <code>startPeriod</code> is
* disabled by default.
* </p>
* <note>
* <p>
* If a health check succeeds within the <code>startPeriod</code>, then the container is considered healthy and any
* subsequent failures count toward the maximum number of retries.
* </p>
* </note>
*
* @param startPeriod
* The optional grace period within which to provide containers time to bootstrap before failed health checks
* count towards the maximum number of retries. You may specify between 0 and 300 seconds. The
* <code>startPeriod</code> is disabled by default.</p> <note>
* <p>
* If a health check succeeds within the <code>startPeriod</code>, then the container is considered healthy
* and any subsequent failures count toward the maximum number of retries.
* </p>
*/
public void setStartPeriod(Integer startPeriod) {
this.startPeriod = startPeriod;
}
/**
* <p>
* The optional grace period within which to provide containers time to bootstrap before failed health checks count
* towards the maximum number of retries. You may specify between 0 and 300 seconds. The <code>startPeriod</code> is
* disabled by default.
* </p>
* <note>
* <p>
* If a health check succeeds within the <code>startPeriod</code>, then the container is considered healthy and any
* subsequent failures count toward the maximum number of retries.
* </p>
* </note>
*
* @return The optional grace period within which to provide containers time to bootstrap before failed health
* checks count towards the maximum number of retries. You may specify between 0 and 300 seconds. The
* <code>startPeriod</code> is disabled by default.</p> <note>
* <p>
* If a health check succeeds within the <code>startPeriod</code>, then the container is considered healthy
* and any subsequent failures count toward the maximum number of retries.
* </p>
*/
public Integer getStartPeriod() {
return this.startPeriod;
}
/**
* <p>
* The optional grace period within which to provide containers time to bootstrap before failed health checks count
* towards the maximum number of retries. You may specify between 0 and 300 seconds. The <code>startPeriod</code> is
* disabled by default.
* </p>
* <note>
* <p>
* If a health check succeeds within the <code>startPeriod</code>, then the container is considered healthy and any
* subsequent failures count toward the maximum number of retries.
* </p>
* </note>
*
* @param startPeriod
* The optional grace period within which to provide containers time to bootstrap before failed health checks
* count towards the maximum number of retries. You may specify between 0 and 300 seconds. The
* <code>startPeriod</code> is disabled by default.</p> <note>
* <p>
* If a health check succeeds within the <code>startPeriod</code>, then the container is considered healthy
* and any subsequent failures count toward the maximum number of retries.
* </p>
* @return Returns a reference to this object so that method calls can be chained together.
*/
public HealthCheck withStartPeriod(Integer startPeriod) {
setStartPeriod(startPeriod);
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 (getCommand() != null)
sb.append("Command: ").append(getCommand()).append(",");
if (getInterval() != null)
sb.append("Interval: ").append(getInterval()).append(",");
if (getTimeout() != null)
sb.append("Timeout: ").append(getTimeout()).append(",");
if (getRetries() != null)
sb.append("Retries: ").append(getRetries()).append(",");
if (getStartPeriod() != null)
sb.append("StartPeriod: ").append(getStartPeriod());
sb.append("}");
return sb.toString();
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (obj instanceof HealthCheck == false)
return false;
HealthCheck other = (HealthCheck) obj;
if (other.getCommand() == null ^ this.getCommand() == null)
return false;
if (other.getCommand() != null && other.getCommand().equals(this.getCommand()) == false)
return false;
if (other.getInterval() == null ^ this.getInterval() == null)
return false;
if (other.getInterval() != null && other.getInterval().equals(this.getInterval()) == false)
return false;
if (other.getTimeout() == null ^ this.getTimeout() == null)
return false;
if (other.getTimeout() != null && other.getTimeout().equals(this.getTimeout()) == false)
return false;
if (other.getRetries() == null ^ this.getRetries() == null)
return false;
if (other.getRetries() != null && other.getRetries().equals(this.getRetries()) == false)
return false;
if (other.getStartPeriod() == null ^ this.getStartPeriod() == null)
return false;
if (other.getStartPeriod() != null && other.getStartPeriod().equals(this.getStartPeriod()) == false)
return false;
return true;
}
@Override
public int hashCode() {
final int prime = 31;
int hashCode = 1;
hashCode = prime * hashCode + ((getCommand() == null) ? 0 : getCommand().hashCode());
hashCode = prime * hashCode + ((getInterval() == null) ? 0 : getInterval().hashCode());
hashCode = prime * hashCode + ((getTimeout() == null) ? 0 : getTimeout().hashCode());
hashCode = prime * hashCode + ((getRetries() == null) ? 0 : getRetries().hashCode());
hashCode = prime * hashCode + ((getStartPeriod() == null) ? 0 : getStartPeriod().hashCode());
return hashCode;
}
@Override
public HealthCheck clone() {
try {
return (HealthCheck) 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.ecs.model.transform.HealthCheckMarshaller.getInstance().marshall(this, protocolMarshaller);
}
}
|
package org.semanticweb.rulewerk.examples.rdf;
/*-
* #%L
* Rulewerk Examples
* %%
* Copyright (C) 2018 - 2020 Rulewerk Developers
* %%
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* #L%
*/
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;
import java.util.Set;
import org.openrdf.model.Model;
import org.openrdf.model.impl.LinkedHashModel;
import org.openrdf.rio.RDFFormat;
import org.openrdf.rio.RDFHandlerException;
import org.openrdf.rio.RDFParseException;
import org.openrdf.rio.RDFParser;
import org.openrdf.rio.Rio;
import org.openrdf.rio.helpers.StatementCollector;
import org.semanticweb.rulewerk.core.model.api.Constant;
import org.semanticweb.rulewerk.core.model.api.Fact;
import org.semanticweb.rulewerk.core.model.api.PositiveLiteral;
import org.semanticweb.rulewerk.core.model.api.Predicate;
import org.semanticweb.rulewerk.core.model.api.Variable;
import org.semanticweb.rulewerk.core.model.implementation.Expressions;
import org.semanticweb.rulewerk.core.reasoner.KnowledgeBase;
import org.semanticweb.rulewerk.core.reasoner.QueryResultIterator;
import org.semanticweb.rulewerk.reasoner.vlog.VLogReasoner;
import org.semanticweb.rulewerk.examples.ExamplesUtils;
import org.semanticweb.rulewerk.parser.ParsingException;
import org.semanticweb.rulewerk.parser.RuleParser;
import org.semanticweb.rulewerk.rdf.RdfModelConverter;
/**
* This example shows how <b>rulewerk-rdf</b> library's utility class
* {@link RdfModelConverter} can be used to convert RDF {@link Model}s from
* various types of RDF resources to <b>rulewerk-core</b> {@code Atom} sets.
*
* @author Irina Dragoste
*
*/
public class AddDataFromRdfModel {
public static void main(final String[] args)
throws IOException, RDFParseException, RDFHandlerException, URISyntaxException {
ExamplesUtils.configureLogging();
/*
* Local file containing metadata of publications from ISWC'16 conference, in
* RDF/XML format.
*/
final File rdfXMLResourceFile = new File(ExamplesUtils.INPUT_FOLDER + "rdf/iswc-2016-complete-alignments.rdf");
final FileInputStream inputStreamISWC2016 = new FileInputStream(rdfXMLResourceFile);
/* An RDF Model is obtained from parsing the RDF/XML resource. */
final Model rdfModelISWC2016 = parseRdfResource(inputStreamISWC2016, rdfXMLResourceFile.toURI(),
RDFFormat.RDFXML);
/*
* Using rulewerk-rdf library, we convert RDF Model triples to facts, each having
* the ternary predicate "TRIPLE".
*/
final Set<Fact> tripleFactsISWC2016 = RdfModelConverter.rdfModelToFacts(rdfModelISWC2016);
System.out.println("Example triple fact from iswc-2016 dataset:");
System.out.println(" - " + tripleFactsISWC2016.iterator().next());
/*
* URL of online resource containing metadata of publications from ISWC'17
* conference, in TURTLE format.
*/
final URL turtleResourceURL = new URL(
"http://www.scholarlydata.org/dumps/conferences/alignments/iswc-2017-complete-alignments.ttl");
final InputStream inputStreamISWC2017 = turtleResourceURL.openStream();
/* An RDF Model is obtained from parsing the TURTLE resource. */
final Model rdfModelISWC2017 = parseRdfResource(inputStreamISWC2017, turtleResourceURL.toURI(),
RDFFormat.TURTLE);
/*
* Using rulewerk-rdf library, we convert RDF Model triples to facts, each having
* the ternary predicate "TRIPLE".
*/
final Set<Fact> tripleFactsISWC2017 = RdfModelConverter.rdfModelToFacts(rdfModelISWC2017);
System.out.println("Example triple fact from iswc-2017 dataset:");
System.out.println(" - " + tripleFactsISWC2017.iterator().next());
/**
* We wish to combine triples about a person's affiliation, an affiliation's
* organization and an organization's name, to find a person's organization
* name.
*/
/* Predicate names of the triples found in both RDF files. */
final Variable varPerson = Expressions.makeUniversalVariable("person");
final Predicate predicateHasOrganizationName = Expressions.makePredicate("hasOrganizationName", 2);
/*
* Rule that retrieves pairs of persons and their organization name:
*/
final String rules = "%%%% We specify the rules syntactically for convenience %%%\n"
+ "@prefix cnf: <https://w3id.org/scholarlydata/ontology/conference-ontology.owl#> ."
+ "hasOrganizationName(?Person, ?OrgName) :- "
+ " TRIPLE(?Person, cnf:hasAffiliation, ?Aff), TRIPLE(?Aff, cnf:withOrganisation, ?Org),"
+ " TRIPLE(?Org, cnf:name, ?OrgName) .";
KnowledgeBase kb;
try {
kb = RuleParser.parse(rules);
} catch (final ParsingException e) {
System.out.println("Failed to parse rules: " + e.getMessage());
return;
}
kb.addStatements(tripleFactsISWC2016);
kb.addStatements(tripleFactsISWC2017);
try (VLogReasoner reasoner = new VLogReasoner(kb)) {
reasoner.reason();
/* We query for persons whose organization name is "TU Dresden" . */
final Constant constantTuDresden = Expressions.makeDatatypeConstant("TU Dresden",
"http://www.w3.org/2001/XMLSchema#string");
/* hasOrganizationName(?person, "TU Dresden") */
final PositiveLiteral queryTUDresdenParticipantsAtISWC = Expressions
.makePositiveLiteral(predicateHasOrganizationName, varPerson, constantTuDresden);
System.out.println("\nParticipants at ISWC'16 and '17 from Organization 'TU Dresden':");
System.out.println("(Answers to query " + queryTUDresdenParticipantsAtISWC + ")\n");
try (QueryResultIterator queryResultIterator = reasoner.answerQuery(queryTUDresdenParticipantsAtISWC,
false)) {
queryResultIterator.forEachRemaining(answer -> System.out
.println(" - " + answer.getTerms().get(0) + ", organization " + answer.getTerms().get(1)));
}
}
}
/**
* Parses the data from the supplied InputStream, using the supplied baseURI to
* resolve any relative URI references.
*
* @param inputStream The content to be parsed, expected to be in the given
* {@code rdfFormat}.
* @param baseURI The URI associated with the data in the InputStream.
* @param rdfFormat The expected RDFformat of the inputStream resource that is
* to be parsed.
* @return A Model containing the RDF triples. Blanks have unique ids across
* different models.
* @throws IOException If an I/O error occurred while data was read from
* the InputStream.
* @throws RDFParseException If the parser has found an unrecoverable parse
* error.
* @throws RDFHandlerException If the configured statement handler has
* encountered an unrecoverable error.
*/
private static Model parseRdfResource(final InputStream inputStream, final URI baseURI, final RDFFormat rdfFormat)
throws IOException, RDFParseException, RDFHandlerException {
final Model model = new LinkedHashModel();
final RDFParser rdfParser = Rio.createParser(rdfFormat);
rdfParser.setRDFHandler(new StatementCollector(model));
rdfParser.parse(inputStream, baseURI.toString());
return model;
}
}
|
package four;
import java.awt.Color;
import java.awt.Graphics;
import javax.swing.JPanel;
public class Runtime extends JPanel implements Runnable{
/**
*
*/
private static final long serialVersionUID = 1L;
int x = 0;
int y = 0;
int count = 10;
Pcb node;
public Runtime(Pcb node) {
this.node = node;
}
public Runtime() {
node = new Pcb();
node.setName("无");
}
public Pcb getNode() {
return node;
}
public void setNode(Pcb node) {
this.node = node;
}
@Override
public void paint(Graphics g) {
super.paint(g);
g.setColor(new Color(131, 175, 155));//设置画笔颜色
g.fillRect(0, 0, 80, 40);
g.setColor(Color.black);//设置画笔颜色
g.drawString(node.getName(), 33, 23);
g.drawRect(0, 0, 80, 40);
}
@Override
public void run() {
while(true){
repaint();
}
}
}
|
package com.appcutt.demo.request;
import com.appcutt.libs.net.http.JsonHttpResponseHandler;
import org.apache.http.Header;
import org.apache.http.HttpStatus;
import org.json.JSONArray;
import org.json.JSONObject;
/**
* 解析业务返回数据
*
* Created by ouyangjinmiao on 18/5/15.
*/
public abstract class AbsBusinessResponseHandler extends JsonHttpResponseHandler {
/**
* 成功
*
* @param headers
* @param jsonObj
*/
protected abstract void onRequestSuccess(int statusCode, Header[] headers, Object jsonObj);
/**
* 失败
*
* @param headers
* @param statusCode
*/
protected abstract void onRequestFail(int statusCode, Header[] headers);
/**
* 解析服务器返回的数据
*
* @param jsonObj
* @return
*/
protected abstract Object parseResponse(Object jsonObj) throws Exception;
@Override
public final void onSuccess(int statusCode, Header[] headers, JSONObject jsonObj) {
try {
Object response = parseResponse(jsonObj);
if (response != null) {
onRequestSuccess(statusCode, headers, response);
} else {
sendRequestFail(statusCode, headers);
}
} catch (Exception e) {
sendRequestFail(statusCode, headers);
}
}
@Override
public final void onSuccess(int statusCode, Header[] headers, JSONArray jsonArray) {
try {
Object response = parseResponse(jsonArray);
if (response != null) {
onRequestSuccess(statusCode, headers, response);
} else {
sendRequestFail(statusCode, headers);
}
} catch (Exception e) {
sendRequestFail(statusCode, headers);
}
}
@Override
public final void onFailure(int statusCode, Header[] headers, Throwable throwable, JSONObject errorResponse) {
sendRequestFail(statusCode, headers);
}
/**
* 这个方法统一输出错误日志,并上报错误日志
*
* @param headers
* @param statusCode
*/
private void sendRequestFail(int statusCode, Header[] headers) {
onRequestFail(statusCode,headers);
}
}
|
/*
* Copyright 2002-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.test.web.servlet.htmlunit;
import com.gargoylesoftware.htmlunit.FormEncodingType;
import com.gargoylesoftware.htmlunit.HttpMethod;
import com.gargoylesoftware.htmlunit.WebClient;
import com.gargoylesoftware.htmlunit.WebRequest;
import com.gargoylesoftware.htmlunit.util.NameValuePair;
import org.apache.commons.io.IOUtils;
import org.apache.http.auth.UsernamePasswordCredentials;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.springframework.mock.web.MockHttpServletRequest;
import org.springframework.mock.web.MockHttpSession;
import org.springframework.mock.web.MockServletContext;
import org.springframework.test.util.ReflectionTestUtils;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import javax.servlet.ServletContext;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpSession;
import java.net.MalformedURLException;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.util.*;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
/**
* Unit tests for {@link HtmlUnitRequestBuilder}.
*
* @author Rob Winch
* @author Sam Brannen
* @since 4.2
*/
public class HtmlUnitRequestBuilderTests {
private final WebClient webClient = new WebClient();
private final ServletContext servletContext = new MockServletContext();
private final Map<String, MockHttpSession> sessions = new HashMap<>();
private WebRequest webRequest;
private HtmlUnitRequestBuilder requestBuilder;
@BeforeEach
public void setup() throws Exception {
webRequest = new WebRequest(new URL("https://example.com/test/this/here"));
webRequest.setHttpMethod(HttpMethod.GET);
requestBuilder = new HtmlUnitRequestBuilder(sessions, webClient, webRequest);
}
// --- constructor
@Test
public void constructorNullSessions() {
assertThatIllegalArgumentException().isThrownBy(() ->
new HtmlUnitRequestBuilder(null, webClient, webRequest));
}
@Test
public void constructorNullWebClient() {
assertThatIllegalArgumentException().isThrownBy(() ->
new HtmlUnitRequestBuilder(sessions, null, webRequest));
}
@Test
public void constructorNullWebRequest() {
assertThatIllegalArgumentException().isThrownBy(() ->
new HtmlUnitRequestBuilder(sessions, webClient, null));
}
// --- buildRequest
@Test
@SuppressWarnings("deprecation")
public void buildRequestBasicAuth() {
String base64Credentials = "dXNlcm5hbWU6cGFzc3dvcmQ=";
String authzHeaderValue = "Basic: " + base64Credentials;
UsernamePasswordCredentials credentials = new UsernamePasswordCredentials(base64Credentials);
webRequest.setCredentials(credentials);
webRequest.setAdditionalHeader("Authorization", authzHeaderValue);
MockHttpServletRequest actualRequest = requestBuilder.buildRequest(servletContext);
assertThat(actualRequest.getAuthType()).isEqualTo("Basic");
assertThat(actualRequest.getHeader("Authorization")).isEqualTo(authzHeaderValue);
}
@Test
public void buildRequestCharacterEncoding() {
webRequest.setCharset(StandardCharsets.UTF_8);
MockHttpServletRequest actualRequest = requestBuilder.buildRequest(servletContext);
assertThat(actualRequest.getCharacterEncoding()).isEqualTo("UTF-8");
}
@Test
public void buildRequestDefaultCharacterEncoding() {
MockHttpServletRequest actualRequest = requestBuilder.buildRequest(servletContext);
assertThat(actualRequest.getCharacterEncoding()).isEqualTo("ISO-8859-1");
}
@Test
public void buildRequestContentLength() {
String content = "some content that has length";
webRequest.setHttpMethod(HttpMethod.POST);
webRequest.setRequestBody(content);
MockHttpServletRequest actualRequest = requestBuilder.buildRequest(servletContext);
assertThat(actualRequest.getContentLength()).isEqualTo(content.length());
}
@Test
public void buildRequestContentType() {
String contentType = "text/html;charset=UTF-8";
webRequest.setAdditionalHeader("Content-Type", contentType);
MockHttpServletRequest actualRequest = requestBuilder.buildRequest(servletContext);
assertThat(actualRequest.getContentType()).isEqualTo(contentType);
assertThat(actualRequest.getHeader("Content-Type")).isEqualTo(contentType);
}
@Test // SPR-14916
public void buildRequestContentTypeWithFormSubmission() {
webRequest.setEncodingType(FormEncodingType.URL_ENCODED);
MockHttpServletRequest actualRequest = requestBuilder.buildRequest(servletContext);
assertThat(actualRequest.getContentType()).isEqualTo("application/x-www-form-urlencoded");
assertThat(actualRequest.getHeader("Content-Type"))
.isEqualTo("application/x-www-form-urlencoded;charset=ISO-8859-1");
}
@Test
public void buildRequestContextPathUsesFirstSegmentByDefault() {
String contextPath = requestBuilder.buildRequest(servletContext).getContextPath();
assertThat(contextPath).isEqualTo("/test");
}
@Test
public void buildRequestContextPathUsesNoFirstSegmentWithDefault() throws MalformedURLException {
webRequest.setUrl(new URL("https://example.com/"));
String contextPath = requestBuilder.buildRequest(servletContext).getContextPath();
assertThat(contextPath).isEqualTo("");
}
@Test
public void buildRequestContextPathInvalid() {
requestBuilder.setContextPath("/invalid");
assertThatIllegalArgumentException().isThrownBy(() ->
requestBuilder.buildRequest(servletContext).getContextPath());
}
@Test
public void buildRequestContextPathEmpty() {
String expected = "";
requestBuilder.setContextPath(expected);
String contextPath = requestBuilder.buildRequest(servletContext).getContextPath();
assertThat(contextPath).isEqualTo(expected);
}
@Test
public void buildRequestContextPathExplicit() {
String expected = "/test";
requestBuilder.setContextPath(expected);
String contextPath = requestBuilder.buildRequest(servletContext).getContextPath();
assertThat(contextPath).isEqualTo(expected);
}
@Test
public void buildRequestContextPathMulti() {
String expected = "/test/this";
requestBuilder.setContextPath(expected);
String contextPath = requestBuilder.buildRequest(servletContext).getContextPath();
assertThat(contextPath).isEqualTo(expected);
}
@Test
public void buildRequestCookiesNull() {
MockHttpServletRequest actualRequest = requestBuilder.buildRequest(servletContext);
assertThat(actualRequest.getCookies()).isNull();
}
@Test
public void buildRequestCookiesSingle() {
webRequest.setAdditionalHeader("Cookie", "name=value");
MockHttpServletRequest actualRequest = requestBuilder.buildRequest(servletContext);
Cookie[] cookies = actualRequest.getCookies();
assertThat(cookies.length).isEqualTo(1);
assertThat(cookies[0].getName()).isEqualTo("name");
assertThat(cookies[0].getValue()).isEqualTo("value");
}
@Test
public void buildRequestCookiesMulti() {
webRequest.setAdditionalHeader("Cookie", "name=value; name2=value2");
MockHttpServletRequest actualRequest = requestBuilder.buildRequest(servletContext);
Cookie[] cookies = actualRequest.getCookies();
assertThat(cookies.length).isEqualTo(2);
Cookie cookie = cookies[0];
assertThat(cookie.getName()).isEqualTo("name");
assertThat(cookie.getValue()).isEqualTo("value");
cookie = cookies[1];
assertThat(cookie.getName()).isEqualTo("name2");
assertThat(cookie.getValue()).isEqualTo("value2");
}
@Test
@SuppressWarnings("deprecation")
public void buildRequestInputStream() throws Exception {
String content = "some content that has length";
webRequest.setHttpMethod(HttpMethod.POST);
webRequest.setRequestBody(content);
MockHttpServletRequest actualRequest = requestBuilder.buildRequest(servletContext);
assertThat(IOUtils.toString(actualRequest.getInputStream())).isEqualTo(content);
}
@Test
public void buildRequestLocalAddr() {
MockHttpServletRequest actualRequest = requestBuilder.buildRequest(servletContext);
assertThat(actualRequest.getLocalAddr()).isEqualTo("127.0.0.1");
}
@Test
public void buildRequestLocaleDefault() {
MockHttpServletRequest actualRequest = requestBuilder.buildRequest(servletContext);
assertThat(actualRequest.getLocale()).isEqualTo(Locale.getDefault());
}
@Test
public void buildRequestLocaleDa() {
webRequest.setAdditionalHeader("Accept-Language", "da");
MockHttpServletRequest actualRequest = requestBuilder.buildRequest(servletContext);
assertThat(actualRequest.getLocale()).isEqualTo(new Locale("da"));
}
@Test
public void buildRequestLocaleEnGbQ08() {
webRequest.setAdditionalHeader("Accept-Language", "en-gb;q=0.8");
MockHttpServletRequest actualRequest = requestBuilder.buildRequest(servletContext);
assertThat(actualRequest.getLocale()).isEqualTo(new Locale("en", "gb"));
}
@Test
public void buildRequestLocaleEnQ07() {
webRequest.setAdditionalHeader("Accept-Language", "en");
MockHttpServletRequest actualRequest = requestBuilder.buildRequest(servletContext);
assertThat(actualRequest.getLocale()).isEqualTo(new Locale("en", ""));
}
@Test
public void buildRequestLocaleEnUs() {
webRequest.setAdditionalHeader("Accept-Language", "en-US");
MockHttpServletRequest actualRequest = requestBuilder.buildRequest(servletContext);
assertThat(actualRequest.getLocale()).isEqualTo(Locale.US);
}
@Test
public void buildRequestLocaleFr() {
webRequest.setAdditionalHeader("Accept-Language", "fr");
MockHttpServletRequest actualRequest = requestBuilder.buildRequest(servletContext);
assertThat(actualRequest.getLocale()).isEqualTo(Locale.FRENCH);
}
@Test
public void buildRequestLocaleMulti() {
webRequest.setAdditionalHeader("Accept-Language", "en-gb;q=0.8, da, en;q=0.7");
MockHttpServletRequest actualRequest = requestBuilder.buildRequest(servletContext);
assertThat(Collections.list(actualRequest.getLocales()))
.containsExactly(new Locale("da"), new Locale("en", "gb"), new Locale("en", ""));
}
@Test
public void buildRequestLocalName() {
MockHttpServletRequest actualRequest = requestBuilder.buildRequest(servletContext);
assertThat(actualRequest.getLocalName()).isEqualTo("localhost");
}
@Test
public void buildRequestLocalPort() throws Exception {
webRequest.setUrl(new URL("http://localhost:80/test/this/here"));
MockHttpServletRequest actualRequest = requestBuilder.buildRequest(servletContext);
assertThat(actualRequest.getLocalPort()).isEqualTo(80);
}
@Test
public void buildRequestLocalMissing() throws Exception {
webRequest.setUrl(new URL("http://localhost/test/this"));
MockHttpServletRequest actualRequest = requestBuilder.buildRequest(servletContext);
assertThat(actualRequest.getLocalPort()).isEqualTo(-1);
}
@Test
public void buildRequestMethods() {
for (HttpMethod expectedMethod : HttpMethod.values()) {
webRequest.setHttpMethod(expectedMethod);
String actualMethod = requestBuilder.buildRequest(servletContext).getMethod();
assertThat(actualMethod).isEqualTo(expectedMethod.name());
}
}
@Test
public void buildRequestParameterMapViaWebRequestDotSetRequestParametersWithSingleRequestParam() {
webRequest.setRequestParameters(Arrays.asList(new NameValuePair("name", "value")));
MockHttpServletRequest actualRequest = requestBuilder.buildRequest(servletContext);
assertThat(actualRequest.getParameterMap().size()).isEqualTo(1);
assertThat(actualRequest.getParameter("name")).isEqualTo("value");
}
@Test
public void buildRequestParameterMapViaWebRequestDotSetRequestParametersWithSingleRequestParamWithNullValue() {
webRequest.setRequestParameters(Arrays.asList(new NameValuePair("name", null)));
MockHttpServletRequest actualRequest = requestBuilder.buildRequest(servletContext);
assertThat(actualRequest.getParameterMap().size()).isEqualTo(1);
assertThat(actualRequest.getParameter("name")).isNull();
}
@Test
public void buildRequestParameterMapViaWebRequestDotSetRequestParametersWithSingleRequestParamWithEmptyValue() {
webRequest.setRequestParameters(Arrays.asList(new NameValuePair("name", "")));
MockHttpServletRequest actualRequest = requestBuilder.buildRequest(servletContext);
assertThat(actualRequest.getParameterMap().size()).isEqualTo(1);
assertThat(actualRequest.getParameter("name")).isEqualTo("");
}
@Test
public void buildRequestParameterMapViaWebRequestDotSetRequestParametersWithSingleRequestParamWithValueSetToSpace() {
webRequest.setRequestParameters(Arrays.asList(new NameValuePair("name", " ")));
MockHttpServletRequest actualRequest = requestBuilder.buildRequest(servletContext);
assertThat(actualRequest.getParameterMap().size()).isEqualTo(1);
assertThat(actualRequest.getParameter("name")).isEqualTo(" ");
}
@Test
public void buildRequestParameterMapViaWebRequestDotSetRequestParametersWithMultipleRequestParams() {
webRequest.setRequestParameters(Arrays.asList(new NameValuePair("name1", "value1"), new NameValuePair("name2", "value2")));
MockHttpServletRequest actualRequest = requestBuilder.buildRequest(servletContext);
assertThat(actualRequest.getParameterMap().size()).isEqualTo(2);
assertThat(actualRequest.getParameter("name1")).isEqualTo("value1");
assertThat(actualRequest.getParameter("name2")).isEqualTo("value2");
}
@Test
public void buildRequestParameterMapFromSingleQueryParam() throws Exception {
webRequest.setUrl(new URL("https://example.com/example/?name=value"));
MockHttpServletRequest actualRequest = requestBuilder.buildRequest(servletContext);
assertThat(actualRequest.getParameterMap().size()).isEqualTo(1);
assertThat(actualRequest.getParameter("name")).isEqualTo("value");
}
// SPR-14177
@Test
public void buildRequestParameterMapDecodesParameterName() throws Exception {
webRequest.setUrl(new URL("https://example.com/example/?row%5B0%5D=value"));
MockHttpServletRequest actualRequest = requestBuilder.buildRequest(servletContext);
assertThat(actualRequest.getParameterMap().size()).isEqualTo(1);
assertThat(actualRequest.getParameter("row[0]")).isEqualTo("value");
}
@Test
public void buildRequestParameterMapDecodesParameterValue() throws Exception {
webRequest.setUrl(new URL("https://example.com/example/?name=row%5B0%5D"));
MockHttpServletRequest actualRequest = requestBuilder.buildRequest(servletContext);
assertThat(actualRequest.getParameterMap().size()).isEqualTo(1);
assertThat(actualRequest.getParameter("name")).isEqualTo("row[0]");
}
@Test
public void buildRequestParameterMapFromSingleQueryParamWithoutValueAndWithoutEqualsSign() throws Exception {
webRequest.setUrl(new URL("https://example.com/example/?name"));
MockHttpServletRequest actualRequest = requestBuilder.buildRequest(servletContext);
assertThat(actualRequest.getParameterMap().size()).isEqualTo(1);
assertThat(actualRequest.getParameter("name")).isEqualTo("");
}
@Test
public void buildRequestParameterMapFromSingleQueryParamWithoutValueButWithEqualsSign() throws Exception {
webRequest.setUrl(new URL("https://example.com/example/?name="));
MockHttpServletRequest actualRequest = requestBuilder.buildRequest(servletContext);
assertThat(actualRequest.getParameterMap().size()).isEqualTo(1);
assertThat(actualRequest.getParameter("name")).isEqualTo("");
}
@Test
public void buildRequestParameterMapFromSingleQueryParamWithValueSetToEncodedSpace() throws Exception {
webRequest.setUrl(new URL("https://example.com/example/?name=%20"));
MockHttpServletRequest actualRequest = requestBuilder.buildRequest(servletContext);
assertThat(actualRequest.getParameterMap().size()).isEqualTo(1);
assertThat(actualRequest.getParameter("name")).isEqualTo(" ");
}
@Test
public void buildRequestParameterMapFromMultipleQueryParams() throws Exception {
webRequest.setUrl(new URL("https://example.com/example/?name=value¶m2=value+2"));
MockHttpServletRequest actualRequest = requestBuilder.buildRequest(servletContext);
assertThat(actualRequest.getParameterMap().size()).isEqualTo(2);
assertThat(actualRequest.getParameter("name")).isEqualTo("value");
assertThat(actualRequest.getParameter("param2")).isEqualTo("value 2");
}
@Test
public void buildRequestPathInfo() throws Exception {
MockHttpServletRequest actualRequest = requestBuilder.buildRequest(servletContext);
assertThat(actualRequest.getPathInfo()).isNull();
}
@Test
public void buildRequestPathInfoNull() throws Exception {
webRequest.setUrl(new URL("https://example.com/example"));
MockHttpServletRequest actualRequest = requestBuilder.buildRequest(servletContext);
assertThat(actualRequest.getPathInfo()).isNull();
}
@Test
public void buildRequestAndAntPathRequestMatcher() throws Exception {
webRequest.setUrl(new URL("https://example.com/app/login/authenticate"));
MockHttpServletRequest actualRequest = requestBuilder.buildRequest(servletContext);
// verify it is going to work with Spring Security's AntPathRequestMatcher
assertThat(actualRequest.getPathInfo()).isNull();
assertThat(actualRequest.getServletPath()).isEqualTo("/login/authenticate");
}
@Test
public void buildRequestProtocol() throws Exception {
MockHttpServletRequest actualRequest = requestBuilder.buildRequest(servletContext);
assertThat(actualRequest.getProtocol()).isEqualTo("HTTP/1.1");
}
@Test
public void buildRequestQueryWithSingleQueryParam() throws Exception {
String expectedQuery = "param=value";
webRequest.setUrl(new URL("https://example.com/example?" + expectedQuery));
MockHttpServletRequest actualRequest = requestBuilder.buildRequest(servletContext);
assertThat(actualRequest.getQueryString()).isEqualTo(expectedQuery);
}
@Test
public void buildRequestQueryWithSingleQueryParamWithoutValueAndWithoutEqualsSign() throws Exception {
String expectedQuery = "param";
webRequest.setUrl(new URL("https://example.com/example?" + expectedQuery));
MockHttpServletRequest actualRequest = requestBuilder.buildRequest(servletContext);
assertThat(actualRequest.getQueryString()).isEqualTo(expectedQuery);
}
@Test
public void buildRequestQueryWithSingleQueryParamWithoutValueButWithEqualsSign() throws Exception {
String expectedQuery = "param=";
webRequest.setUrl(new URL("https://example.com/example?" + expectedQuery));
MockHttpServletRequest actualRequest = requestBuilder.buildRequest(servletContext);
assertThat(actualRequest.getQueryString()).isEqualTo(expectedQuery);
}
@Test
public void buildRequestQueryWithSingleQueryParamWithValueSetToEncodedSpace() throws Exception {
String expectedQuery = "param=%20";
webRequest.setUrl(new URL("https://example.com/example?" + expectedQuery));
MockHttpServletRequest actualRequest = requestBuilder.buildRequest(servletContext);
assertThat(actualRequest.getQueryString()).isEqualTo(expectedQuery);
}
@Test
public void buildRequestQueryWithMultipleQueryParams() throws Exception {
String expectedQuery = "param1=value1¶m2=value2";
webRequest.setUrl(new URL("https://example.com/example?" + expectedQuery));
MockHttpServletRequest actualRequest = requestBuilder.buildRequest(servletContext);
assertThat(actualRequest.getQueryString()).isEqualTo(expectedQuery);
}
@Test
public void buildRequestReader() throws Exception {
String expectedBody = "request body";
webRequest.setHttpMethod(HttpMethod.POST);
webRequest.setRequestBody(expectedBody);
MockHttpServletRequest actualRequest = requestBuilder.buildRequest(servletContext);
assertThat(IOUtils.toString(actualRequest.getReader())).isEqualTo(expectedBody);
}
@Test
public void buildRequestRemoteAddr() throws Exception {
MockHttpServletRequest actualRequest = requestBuilder.buildRequest(servletContext);
assertThat(actualRequest.getRemoteAddr()).isEqualTo("127.0.0.1");
}
@Test
public void buildRequestRemoteHost() throws Exception {
MockHttpServletRequest actualRequest = requestBuilder.buildRequest(servletContext);
assertThat(actualRequest.getRemoteAddr()).isEqualTo("127.0.0.1");
}
@Test
public void buildRequestRemotePort() throws Exception {
webRequest.setUrl(new URL("http://localhost:80/test/this/here"));
MockHttpServletRequest actualRequest = requestBuilder.buildRequest(servletContext);
assertThat(actualRequest.getRemotePort()).isEqualTo(80);
}
@Test
public void buildRequestRemotePort8080() throws Exception {
webRequest.setUrl(new URL("https://example.com:8080/"));
MockHttpServletRequest actualRequest = requestBuilder.buildRequest(servletContext);
assertThat(actualRequest.getRemotePort()).isEqualTo(8080);
}
@Test
public void buildRequestRemotePort80WithDefault() throws Exception {
webRequest.setUrl(new URL("http://company.example/"));
MockHttpServletRequest actualRequest = requestBuilder.buildRequest(servletContext);
assertThat(actualRequest.getRemotePort()).isEqualTo(80);
}
@Test
public void buildRequestRequestedSessionId() throws Exception {
String sessionId = "session-id";
webRequest.setAdditionalHeader("Cookie", "JSESSIONID=" + sessionId);
MockHttpServletRequest actualRequest = requestBuilder.buildRequest(servletContext);
assertThat(actualRequest.getRequestedSessionId()).isEqualTo(sessionId);
}
@Test
public void buildRequestRequestedSessionIdNull() throws Exception {
MockHttpServletRequest actualRequest = requestBuilder.buildRequest(servletContext);
assertThat(actualRequest.getRequestedSessionId()).isNull();
}
@Test
public void buildRequestUri() {
String uri = requestBuilder.buildRequest(servletContext).getRequestURI();
assertThat(uri).isEqualTo("/test/this/here");
}
@Test
public void buildRequestUrl() {
String uri = requestBuilder.buildRequest(servletContext).getRequestURL().toString();
assertThat(uri).isEqualTo("https://example.com/test/this/here");
}
@Test
public void buildRequestSchemeHttp() throws Exception {
webRequest.setUrl(new URL("http://localhost:80/test/this/here"));
MockHttpServletRequest actualRequest = requestBuilder.buildRequest(servletContext);
assertThat(actualRequest.getScheme()).isEqualTo("http");
}
@Test
public void buildRequestSchemeHttps() throws Exception {
webRequest.setUrl(new URL("https://example.com/"));
MockHttpServletRequest actualRequest = requestBuilder.buildRequest(servletContext);
assertThat(actualRequest.getScheme()).isEqualTo("https");
}
@Test
public void buildRequestServerName() throws Exception {
MockHttpServletRequest actualRequest = requestBuilder.buildRequest(servletContext);
assertThat(actualRequest.getServerName()).isEqualTo("example.com");
}
@Test
public void buildRequestServerPort() throws Exception {
webRequest.setUrl(new URL("http://localhost:80/test/this/here"));
MockHttpServletRequest actualRequest = requestBuilder.buildRequest(servletContext);
assertThat(actualRequest.getServerPort()).isEqualTo(80);
}
@Test
public void buildRequestServerPortDefault() throws Exception {
webRequest.setUrl(new URL("https://example.com/"));
MockHttpServletRequest actualRequest = requestBuilder.buildRequest(servletContext);
assertThat(actualRequest.getServerPort()).isEqualTo(-1);
}
@Test
public void buildRequestServletContext() throws Exception {
MockHttpServletRequest actualRequest = requestBuilder.buildRequest(servletContext);
assertThat(actualRequest.getServletContext()).isEqualTo(servletContext);
}
@Test
public void buildRequestServletPath() throws Exception {
MockHttpServletRequest actualRequest = requestBuilder.buildRequest(servletContext);
assertThat(actualRequest.getServletPath()).isEqualTo("/this/here");
}
@Test
public void buildRequestSession() throws Exception {
MockHttpServletRequest actualRequest = requestBuilder.buildRequest(servletContext);
HttpSession newSession = actualRequest.getSession();
assertThat(newSession).isNotNull();
assertSingleSessionCookie(
"JSESSIONID=" + newSession.getId() + "; Path=/test; Domain=example.com");
webRequest.setAdditionalHeader("Cookie", "JSESSIONID=" + newSession.getId());
requestBuilder = new HtmlUnitRequestBuilder(sessions, webClient, webRequest);
actualRequest = requestBuilder.buildRequest(servletContext);
assertThat(actualRequest.getSession()).isSameAs(newSession);
}
@Test
public void buildRequestSessionWithExistingSession() throws Exception {
String sessionId = "session-id";
webRequest.setAdditionalHeader("Cookie", "JSESSIONID=" + sessionId);
MockHttpServletRequest actualRequest = requestBuilder.buildRequest(servletContext);
HttpSession session = actualRequest.getSession();
assertThat(session.getId()).isEqualTo(sessionId);
assertSingleSessionCookie("JSESSIONID=" + session.getId() + "; Path=/test; Domain=example.com");
requestBuilder = new HtmlUnitRequestBuilder(sessions, webClient, webRequest);
actualRequest = requestBuilder.buildRequest(servletContext);
assertThat(actualRequest.getSession()).isEqualTo(session);
webRequest.setAdditionalHeader("Cookie", "JSESSIONID=" + sessionId + "NEW");
actualRequest = requestBuilder.buildRequest(servletContext);
assertThat(actualRequest.getSession()).isNotEqualTo(session);
assertSingleSessionCookie("JSESSIONID=" + actualRequest.getSession().getId()
+ "; Path=/test; Domain=example.com");
}
@Test
public void buildRequestSessionTrue() throws Exception {
MockHttpServletRequest actualRequest = requestBuilder.buildRequest(servletContext);
HttpSession session = actualRequest.getSession(true);
assertThat(session).isNotNull();
}
@Test
public void buildRequestSessionFalseIsNull() throws Exception {
MockHttpServletRequest actualRequest = requestBuilder.buildRequest(servletContext);
HttpSession session = actualRequest.getSession(false);
assertThat(session).isNull();
}
@Test
public void buildRequestSessionFalseWithExistingSession() throws Exception {
String sessionId = "session-id";
webRequest.setAdditionalHeader("Cookie", "JSESSIONID=" + sessionId);
MockHttpServletRequest actualRequest = requestBuilder.buildRequest(servletContext);
HttpSession session = actualRequest.getSession(false);
assertThat(session).isNotNull();
}
@Test
public void buildRequestSessionIsNew() throws Exception {
MockHttpServletRequest actualRequest = requestBuilder.buildRequest(servletContext);
assertThat(actualRequest.getSession().isNew()).isEqualTo(true);
}
@Test
public void buildRequestSessionIsNewFalse() throws Exception {
String sessionId = "session-id";
webRequest.setAdditionalHeader("Cookie", "JSESSIONID=" + sessionId);
MockHttpServletRequest actualRequest = requestBuilder.buildRequest(servletContext);
assertThat(actualRequest.getSession().isNew()).isEqualTo(false);
}
@Test
public void buildRequestSessionInvalidate() throws Exception {
String sessionId = "session-id";
webRequest.setAdditionalHeader("Cookie", "JSESSIONID=" + sessionId);
MockHttpServletRequest actualRequest = requestBuilder.buildRequest(servletContext);
HttpSession sessionToRemove = actualRequest.getSession();
sessionToRemove.invalidate();
assertThat(sessions.containsKey(sessionToRemove.getId())).isEqualTo(false);
assertSingleSessionCookie("JSESSIONID=" + sessionToRemove.getId()
+ "; Expires=Thu, 01-Jan-1970 00:00:01 GMT; Path=/test; Domain=example.com");
webRequest.removeAdditionalHeader("Cookie");
requestBuilder = new HtmlUnitRequestBuilder(sessions, webClient, webRequest);
actualRequest = requestBuilder.buildRequest(servletContext);
assertThat(actualRequest.getSession().isNew()).isEqualTo(true);
assertThat(sessions.containsKey(sessionToRemove.getId())).isEqualTo(false);
}
// --- setContextPath
@Test
public void setContextPathNull() {
requestBuilder.setContextPath(null);
assertThat(getContextPath()).isNull();
}
@Test
public void setContextPathEmptyString() {
requestBuilder.setContextPath("");
assertThat(getContextPath()).isEmpty();
}
@Test
public void setContextPathDoesNotStartWithSlash() {
assertThatIllegalArgumentException().isThrownBy(() ->
requestBuilder.setContextPath("abc/def"));
}
@Test
public void setContextPathEndsWithSlash() {
assertThatIllegalArgumentException().isThrownBy(() ->
requestBuilder.setContextPath("/abc/def/"));
}
@Test
public void setContextPath() {
String expectedContextPath = "/abc/def";
requestBuilder.setContextPath(expectedContextPath);
assertThat(getContextPath()).isEqualTo(expectedContextPath);
}
@Test
public void mergeHeader() throws Exception {
String headerName = "PARENT";
String headerValue = "VALUE";
MockMvc mockMvc = MockMvcBuilders.standaloneSetup(new HelloController())
.defaultRequest(get("/").header(headerName, headerValue))
.build();
assertThat(mockMvc.perform(requestBuilder).andReturn().getRequest().getHeader(headerName)).isEqualTo(headerValue);
}
@Test
public void mergeSession() throws Exception {
String attrName = "PARENT";
String attrValue = "VALUE";
MockMvc mockMvc = MockMvcBuilders.standaloneSetup(new HelloController())
.defaultRequest(get("/").sessionAttr(attrName, attrValue))
.build();
assertThat(mockMvc.perform(requestBuilder).andReturn().getRequest().getSession().getAttribute(attrName)).isEqualTo(attrValue);
}
@Test
public void mergeSessionNotInitialized() throws Exception {
MockMvc mockMvc = MockMvcBuilders.standaloneSetup(new HelloController())
.defaultRequest(get("/"))
.build();
assertThat(mockMvc.perform(requestBuilder).andReturn().getRequest().getSession(false)).isNull();
}
@Test
public void mergeParameter() throws Exception {
String paramName = "PARENT";
String paramValue = "VALUE";
String paramValue2 = "VALUE2";
MockMvc mockMvc = MockMvcBuilders.standaloneSetup(new HelloController())
.defaultRequest(get("/").param(paramName, paramValue, paramValue2))
.build();
MockHttpServletRequest performedRequest = mockMvc.perform(requestBuilder).andReturn().getRequest();
assertThat(performedRequest.getParameterValues(paramName)).containsExactly(paramValue, paramValue2);
}
@Test
public void mergeCookie() throws Exception {
String cookieName = "PARENT";
String cookieValue = "VALUE";
MockMvc mockMvc = MockMvcBuilders.standaloneSetup(new HelloController())
.defaultRequest(get("/").cookie(new Cookie(cookieName, cookieValue)))
.build();
Cookie[] cookies = mockMvc.perform(requestBuilder).andReturn().getRequest().getCookies();
assertThat(cookies).isNotNull();
assertThat(cookies.length).isEqualTo(1);
Cookie cookie = cookies[0];
assertThat(cookie.getName()).isEqualTo(cookieName);
assertThat(cookie.getValue()).isEqualTo(cookieValue);
}
@Test
public void mergeRequestAttribute() throws Exception {
String attrName = "PARENT";
String attrValue = "VALUE";
MockMvc mockMvc = MockMvcBuilders.standaloneSetup(new HelloController())
.defaultRequest(get("/").requestAttr(attrName, attrValue))
.build();
assertThat(mockMvc.perform(requestBuilder).andReturn().getRequest().getAttribute(attrName)).isEqualTo(attrValue);
}
@Test // SPR-14584
public void mergeDoesNotCorruptPathInfoOnParent() throws Exception {
String pathInfo = "/foo/bar";
MockMvc mockMvc = MockMvcBuilders.standaloneSetup(new HelloController())
.defaultRequest(get("/"))
.build();
assertThat(mockMvc.perform(get(pathInfo)).andReturn().getRequest().getPathInfo()).isEqualTo(pathInfo);
mockMvc.perform(requestBuilder);
assertThat(mockMvc.perform(get(pathInfo)).andReturn().getRequest().getPathInfo()).isEqualTo(pathInfo);
}
private void assertSingleSessionCookie(String expected) {
com.gargoylesoftware.htmlunit.util.Cookie jsessionidCookie = webClient.getCookieManager().getCookie("JSESSIONID");
if (expected == null || expected.contains("Expires=Thu, 01-Jan-1970 00:00:01 GMT")) {
assertThat(jsessionidCookie).isNull();
return;
}
String actual = jsessionidCookie.getValue();
assertThat("JSESSIONID=" + actual + "; Path=/test; Domain=example.com").isEqualTo(expected);
}
private String getContextPath() {
return (String) ReflectionTestUtils.getField(requestBuilder, "contextPath");
}
}
|
/*
* Copyright (c) 2020 by Bart Cremers
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
* DEALINGS IN THE SOFTWARE.
*/
package net.sf.intelliplugin.calc.calculator.operator;
import net.sf.intelliplugin.calc.calculator.Operator;
import net.sf.intelliplugin.calc.calculator.BigMath;
import org.jetbrains.annotations.NotNull;
import java.math.BigDecimal;
/**
* Logarithm to base 10 operator.
*
* @author Bart Cremers
* @since 2.0
*/
public class Logarithm10 extends Operator {
public Logarithm10() {
super(1);
}
@NotNull
protected BigDecimal doExecute(BigDecimal... values) {
return BigMath.log10(values[0]);
}
}
|
package com.fr.swift.cloud.util.qm.cal;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
/**
* Created by Lyon on 2018/4/21.
*/
public class BitUtilsTest {
@Test
public void binLength() {
assertTrue(BitUtils.binLength(10) == 4);
assertTrue(BitUtils.binLength(0) == 1);
assertTrue(BitUtils.binLength(2) == 2);
assertTrue(BitUtils.binLength(8) == 4);
}
@Test
public void countOf1InBinary() {
assertEquals(BitUtils.countOf1InBinary(4), 1);
assertEquals(BitUtils.countOf1InBinary(5), 2);
assertEquals(BitUtils.countOf1InBinary(13), 3);
}
}
|
package com.example.android.todolist.database;
import androidx.room.Entity;
import androidx.room.Ignore;
import androidx.room.PrimaryKey;
import java.util.Date;
// TODO (2) Annotate the class with Entity. Use "task" for the table name
@Entity
public class TaskEntry {
// TODO (3) Annotate the id as PrimaryKey. Set autoGenerate to true.
@PrimaryKey(autoGenerate = true)
private int id;
private String description;
private int priority;
private Date updatedAt;
// TODO (4) Use the Ignore annotation so Room knows that it has to use the other constructor instead
@Ignore
public TaskEntry(String description, int priority, Date updatedAt) {
this.description = description;
this.priority = priority;
this.updatedAt = updatedAt;
}
public TaskEntry(int id, String description, int priority, Date updatedAt) {
this.id = id;
this.description = description;
this.priority = priority;
this.updatedAt = updatedAt;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public int getPriority() {
return priority;
}
public void setPriority(int priority) {
this.priority = priority;
}
public Date getUpdatedAt() {
return updatedAt;
}
public void setUpdatedAt(Date updatedAt) {
this.updatedAt = updatedAt;
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.