text
stringlengths
7
1.01M
/* * Created on 6 Feb 2008 */ package uk.org.ponder.rsf.bare; import uk.org.ponder.rsf.viewstate.AnyViewParameters; /** Represents the output from an RSF render cycle **/ public class RenderResponse extends RequestResponse { /** A ViewWrapper object wrapping the returned component tree, if any **/ public ViewWrapper viewWrapper; /** A string holding the rendered markup, if any **/ public String markup; /** If the request concluded in error or with a client redirect for another * reason, the target of the redirect, else <code>null</code>. */ public AnyViewParameters redirect; }
package org.semanticweb.elk.reasoner.indexing.factories; import org.semanticweb.elk.reasoner.indexing.modifiable.ModifiableIndexedPropertyChain; /* * #%L * ELK Reasoner * $Id:$ * $HeadURL:$ * %% * Copyright (C) 2011 - 2012 Department of Computer Science, University of Oxford * %% * 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% */ /** * A factory for creating instances of {@link ModifiableIndexedPropertyChain} * * @author "Yevgeny Kazakov" * */ public interface ModifiableIndexedPropertyChainFactory extends ModifiableIndexedObjectPropertyFactory, ModifiableIndexedBinaryPropertyChainFactory { // combined interface }
/* * 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.mq.model.transform; import java.math.*; import javax.annotation.Generated; import com.amazonaws.services.mq.model.*; import com.amazonaws.transform.SimpleTypeJsonUnmarshallers.*; import com.amazonaws.transform.*; import com.fasterxml.jackson.core.JsonToken; import static com.fasterxml.jackson.core.JsonToken.*; /** * PendingLogs JSON Unmarshaller */ @Generated("com.amazonaws:aws-java-sdk-code-generator") public class PendingLogsJsonUnmarshaller implements Unmarshaller<PendingLogs, JsonUnmarshallerContext> { public PendingLogs unmarshall(JsonUnmarshallerContext context) throws Exception { PendingLogs pendingLogs = new PendingLogs(); int originalDepth = context.getCurrentDepth(); String currentParentElement = context.getCurrentParentElement(); int targetDepth = originalDepth + 1; JsonToken token = context.getCurrentToken(); if (token == null) token = context.nextToken(); if (token == VALUE_NULL) { return null; } while (true) { if (token == null) break; if (token == FIELD_NAME || token == START_OBJECT) { if (context.testExpression("audit", targetDepth)) { context.nextToken(); pendingLogs.setAudit(context.getUnmarshaller(Boolean.class).unmarshall(context)); } if (context.testExpression("general", targetDepth)) { context.nextToken(); pendingLogs.setGeneral(context.getUnmarshaller(Boolean.class).unmarshall(context)); } } else if (token == END_ARRAY || token == END_OBJECT) { if (context.getLastParsedParentElement() == null || context.getLastParsedParentElement().equals(currentParentElement)) { if (context.getCurrentDepth() <= originalDepth) break; } } token = context.nextToken(); } return pendingLogs; } private static PendingLogsJsonUnmarshaller instance; public static PendingLogsJsonUnmarshaller getInstance() { if (instance == null) instance = new PendingLogsJsonUnmarshaller(); return instance; } }
package ua.training.repairagency.controller.commands; import java.util.List; import java.util.Map; import java.util.ResourceBundle; import javax.servlet.http.HttpServletRequest; import ua.training.repairagency.model.dao.services.ServiceFactory; public abstract class AbstractCommand implements Command { protected ResourceBundle messageBundle; protected ServiceFactory serviceFactory = ServiceFactory.getInstance(); protected List<String> infoMessages; protected List<String> errorMessages; protected String page; public AbstractCommand(String path, Map<String, Command> commands) { commands.put(path, this); } @Override public abstract String execute(HttpServletRequest request); }
package info.u250.c2d.box2deditor.ui.controls; import info.u250.c2d.box2deditor.adapter.PrismaticJointDefModel; import info.u250.c2d.box2deditor.gdx.support.Geometry; import info.u250.c2d.box2deditor.ui.Binder; import javax.swing.*; import java.awt.*; import java.awt.event.ItemEvent; import java.awt.event.ItemListener; public class PrismaticJointDefPropertiesPanel extends JointDefPropertiesPanel { public PrismaticJointDefPropertiesPanel() { lblLocalaxisax = new JLabel("localAxisAx:"); GridBagConstraints gbc_lblLocalaxisax = new GridBagConstraints(); gbc_lblLocalaxisax.insets = new Insets(0, 0, 5, 5); gbc_lblLocalaxisax.gridx = 0; gbc_lblLocalaxisax.gridy = 6; getPanel().add(lblLocalaxisax, gbc_lblLocalaxisax); spinnerLocalAxisAx = new JSpinner(); spinnerLocalAxisAx.setModel(new SpinnerNumberModel(new Float(0), null, null, new Float(1))); GridBagConstraints gbc_spinnerLocalAxisAx = new GridBagConstraints(); gbc_spinnerLocalAxisAx.fill = GridBagConstraints.HORIZONTAL; gbc_spinnerLocalAxisAx.insets = new Insets(0, 0, 5, 0); gbc_spinnerLocalAxisAx.gridx = 1; gbc_spinnerLocalAxisAx.gridy = 6; getPanel().add(spinnerLocalAxisAx, gbc_spinnerLocalAxisAx); lblLocalAxisAy = new JLabel("localAxisAy:"); GridBagConstraints gbc_lblLocalAxisAy = new GridBagConstraints(); gbc_lblLocalAxisAy.insets = new Insets(0, 0, 5, 5); gbc_lblLocalAxisAy.gridx = 0; gbc_lblLocalAxisAy.gridy = 7; getPanel().add(lblLocalAxisAy, gbc_lblLocalAxisAy); spinnerLocalAxisAy = new JSpinner(); spinnerLocalAxisAy.setModel(new SpinnerNumberModel(new Float(0), null, null, new Float(1))); GridBagConstraints gbc_spinnerLocalAxisA = new GridBagConstraints(); gbc_spinnerLocalAxisA.fill = GridBagConstraints.HORIZONTAL; gbc_spinnerLocalAxisA.insets = new Insets(0, 0, 5, 0); gbc_spinnerLocalAxisA.gridx = 1; gbc_spinnerLocalAxisA.gridy = 7; getPanel().add(spinnerLocalAxisAy, gbc_spinnerLocalAxisA); chckbxUseBodyabCenter = new JCheckBox("Use BodyA/B Center Line"); GridBagConstraints gbc_chckbxUseBodyabCenter = new GridBagConstraints(); gbc_chckbxUseBodyabCenter.anchor = GridBagConstraints.WEST; gbc_chckbxUseBodyabCenter.insets = new Insets(0, 0, 5, 0); gbc_chckbxUseBodyabCenter.gridx = 1; gbc_chckbxUseBodyabCenter.gridy = 8; getPanel().add(chckbxUseBodyabCenter, gbc_chckbxUseBodyabCenter); JLabel lblLocalanchorax = new JLabel("localAnchorA-x:"); GridBagConstraints gbc_lblLocalanchorax = new GridBagConstraints(); gbc_lblLocalanchorax.insets = new Insets(0, 0, 5, 5); gbc_lblLocalanchorax.gridx = 0; gbc_lblLocalanchorax.gridy = 9; getPanel().add(lblLocalanchorax, gbc_lblLocalanchorax); spinnerLocalAnchorAX = new JSpinner(); spinnerLocalAnchorAX.setEnabled(false); spinnerLocalAnchorAX.setModel(new SpinnerNumberModel(new Float(0), null, null, new Float(1))); GridBagConstraints gbc_spinnerLocalAnchorAX = new GridBagConstraints(); gbc_spinnerLocalAnchorAX.insets = new Insets(0, 0, 5, 0); gbc_spinnerLocalAnchorAX.fill = GridBagConstraints.HORIZONTAL; gbc_spinnerLocalAnchorAX.gridx = 1; gbc_spinnerLocalAnchorAX.gridy = 9; getPanel().add(spinnerLocalAnchorAX, gbc_spinnerLocalAnchorAX); JLabel lblLocalanchoray = new JLabel("localAnchorA-y:"); GridBagConstraints gbc_lblLocalanchoray = new GridBagConstraints(); gbc_lblLocalanchoray.insets = new Insets(0, 0, 5, 5); gbc_lblLocalanchoray.gridx = 0; gbc_lblLocalanchoray.gridy = 10; getPanel().add(lblLocalanchoray, gbc_lblLocalanchoray); spinnerLocalAnchorAY = new JSpinner(); spinnerLocalAnchorAY.setEnabled(false); spinnerLocalAnchorAY.setModel(new SpinnerNumberModel(new Float(0), null, null, new Float(1))); GridBagConstraints gbc_spinnerLocalAnchorAY = new GridBagConstraints(); gbc_spinnerLocalAnchorAY.fill = GridBagConstraints.HORIZONTAL; gbc_spinnerLocalAnchorAY.insets = new Insets(0, 0, 5, 0); gbc_spinnerLocalAnchorAY.gridx = 1; gbc_spinnerLocalAnchorAY.gridy = 10; getPanel().add(spinnerLocalAnchorAY, gbc_spinnerLocalAnchorAY); chckbxUseBodyaCenter = new JCheckBox("Use BodyA Center"); GridBagConstraints gbc_chckbxUseBodyaCenter = new GridBagConstraints(); gbc_chckbxUseBodyaCenter.anchor = GridBagConstraints.WEST; gbc_chckbxUseBodyaCenter.insets = new Insets(0, 0, 5, 0); gbc_chckbxUseBodyaCenter.gridx = 1; gbc_chckbxUseBodyaCenter.gridy = 11; getPanel().add(chckbxUseBodyaCenter, gbc_chckbxUseBodyaCenter); JLabel lblLocalanchorbx = new JLabel("localAnchorB-x:"); GridBagConstraints gbc_lblLocalanchorbx = new GridBagConstraints(); gbc_lblLocalanchorbx.insets = new Insets(0, 0, 5, 5); gbc_lblLocalanchorbx.gridx = 0; gbc_lblLocalanchorbx.gridy = 12; getPanel().add(lblLocalanchorbx, gbc_lblLocalanchorbx); spinnerLocalAnchorBx = new JSpinner(); spinnerLocalAnchorBx.setEnabled(false); spinnerLocalAnchorBx.setModel(new SpinnerNumberModel(new Float(0), null, null, new Float(1))); GridBagConstraints gbc_spinnerLocalAnchorBx = new GridBagConstraints(); gbc_spinnerLocalAnchorBx.fill = GridBagConstraints.HORIZONTAL; gbc_spinnerLocalAnchorBx.insets = new Insets(0, 0, 5, 0); gbc_spinnerLocalAnchorBx.gridx = 1; gbc_spinnerLocalAnchorBx.gridy = 12; getPanel().add(spinnerLocalAnchorBx, gbc_spinnerLocalAnchorBx); JLabel lblLocalanchorby = new JLabel("localAnchorB-y:"); GridBagConstraints gbc_lblLocalanchorby = new GridBagConstraints(); gbc_lblLocalanchorby.insets = new Insets(0, 0, 5, 5); gbc_lblLocalanchorby.gridx = 0; gbc_lblLocalanchorby.gridy = 13; getPanel().add(lblLocalanchorby, gbc_lblLocalanchorby); spinnerLocalAnchorBy = new JSpinner(); spinnerLocalAnchorBy.setEnabled(false); spinnerLocalAnchorBy.setModel(new SpinnerNumberModel(new Float(0), null, null, new Float(1))); GridBagConstraints gbc_spinnerLocalAnchorBy = new GridBagConstraints(); gbc_spinnerLocalAnchorBy.fill = GridBagConstraints.HORIZONTAL; gbc_spinnerLocalAnchorBy.insets = new Insets(0, 0, 5, 0); gbc_spinnerLocalAnchorBy.gridx = 1; gbc_spinnerLocalAnchorBy.gridy = 13; getPanel().add(spinnerLocalAnchorBy, gbc_spinnerLocalAnchorBy); chckbxUseBodybCenter = new JCheckBox("Use BodyB Center"); GridBagConstraints gbc_chckbxUseBodybCenter = new GridBagConstraints(); gbc_chckbxUseBodybCenter.anchor = GridBagConstraints.WEST; gbc_chckbxUseBodybCenter.insets = new Insets(0, 0, 5, 0); gbc_chckbxUseBodybCenter.gridx = 1; gbc_chckbxUseBodybCenter.gridy = 14; getPanel().add(chckbxUseBodybCenter, gbc_chckbxUseBodybCenter); lblReferenceangle = new JLabel("referenceAngle:"); GridBagConstraints gbc_lblReferenceangle = new GridBagConstraints(); gbc_lblReferenceangle.insets = new Insets(0, 0, 5, 5); gbc_lblReferenceangle.gridx = 0; gbc_lblReferenceangle.gridy = 15; getPanel().add(lblReferenceangle, gbc_lblReferenceangle); spinnerReferenceAngle = new JSpinner(); spinnerReferenceAngle.setEnabled(false); spinnerReferenceAngle.setModel(new SpinnerNumberModel(new Float(0), null, null, new Float(1))); GridBagConstraints gbc_spinnerReferenceAngle = new GridBagConstraints(); gbc_spinnerReferenceAngle.fill = GridBagConstraints.HORIZONTAL; gbc_spinnerReferenceAngle.insets = new Insets(0, 0, 5, 0); gbc_spinnerReferenceAngle.gridx = 1; gbc_spinnerReferenceAngle.gridy = 15; getPanel().add(spinnerReferenceAngle, gbc_spinnerReferenceAngle); lblAnchorx = new JLabel("anchorX:"); GridBagConstraints gbc_lblAnchorx = new GridBagConstraints(); gbc_lblAnchorx.insets = new Insets(0, 0, 5, 5); gbc_lblAnchorx.gridx = 0; gbc_lblAnchorx.gridy = 16; getPanel().add(lblAnchorx, gbc_lblAnchorx); spinnerAnchorx = new JSpinner(); spinnerAnchorx.setModel(new SpinnerNumberModel(new Float(0), null, null, new Float(1))); GridBagConstraints gbc_spinnerAnchorx = new GridBagConstraints(); gbc_spinnerAnchorx.fill = GridBagConstraints.HORIZONTAL; gbc_spinnerAnchorx.insets = new Insets(0, 0, 5, 0); gbc_spinnerAnchorx.gridx = 1; gbc_spinnerAnchorx.gridy = 16; getPanel().add(spinnerAnchorx, gbc_spinnerAnchorx); lblAnchory = new JLabel("anchorY:"); GridBagConstraints gbc_lblAnchory = new GridBagConstraints(); gbc_lblAnchory.insets = new Insets(0, 0, 5, 5); gbc_lblAnchory.gridx = 0; gbc_lblAnchory.gridy = 17; getPanel().add(lblAnchory, gbc_lblAnchory); spinnerAnchory = new JSpinner(); spinnerAnchory.setModel(new SpinnerNumberModel(new Float(0), null, null, new Float(1))); GridBagConstraints gbc_spinnerAnchory = new GridBagConstraints(); gbc_spinnerAnchory.fill = GridBagConstraints.HORIZONTAL; gbc_spinnerAnchory.insets = new Insets(0, 0, 5, 0); gbc_spinnerAnchory.gridx = 1; gbc_spinnerAnchory.gridy = 17; getPanel().add(spinnerAnchory, gbc_spinnerAnchory); lblEnablelimit = new JLabel("enableLimit:"); GridBagConstraints gbc_lblEnablelimit = new GridBagConstraints(); gbc_lblEnablelimit.insets = new Insets(0, 0, 5, 5); gbc_lblEnablelimit.gridx = 0; gbc_lblEnablelimit.gridy = 18; getPanel().add(lblEnablelimit, gbc_lblEnablelimit); chckbxEnablelimit = new JCheckBox("enableLimit"); GridBagConstraints gbc_chckbxEnablelimit = new GridBagConstraints(); gbc_chckbxEnablelimit.anchor = GridBagConstraints.WEST; gbc_chckbxEnablelimit.insets = new Insets(0, 0, 5, 0); gbc_chckbxEnablelimit.gridx = 1; gbc_chckbxEnablelimit.gridy = 18; getPanel().add(chckbxEnablelimit, gbc_chckbxEnablelimit); lblLowerTranslation = new JLabel("lowerTranslation:"); GridBagConstraints gbc_lblLowerTranslation = new GridBagConstraints(); gbc_lblLowerTranslation.insets = new Insets(0, 0, 5, 5); gbc_lblLowerTranslation.gridx = 0; gbc_lblLowerTranslation.gridy = 19; getPanel().add(lblLowerTranslation, gbc_lblLowerTranslation); spinnerLowerTranslation = new JSpinner(); spinnerLowerTranslation.setModel(new SpinnerNumberModel(new Float(0), null, null, new Float(1))); GridBagConstraints gbc_spinnerLowerTranslation = new GridBagConstraints(); gbc_spinnerLowerTranslation.fill = GridBagConstraints.HORIZONTAL; gbc_spinnerLowerTranslation.insets = new Insets(0, 0, 5, 0); gbc_spinnerLowerTranslation.gridx = 1; gbc_spinnerLowerTranslation.gridy = 19; getPanel().add(spinnerLowerTranslation, gbc_spinnerLowerTranslation); lblUpperTranslation = new JLabel("upperTranslation:"); GridBagConstraints gbc_lblUpperTranslation = new GridBagConstraints(); gbc_lblUpperTranslation.insets = new Insets(0, 0, 5, 5); gbc_lblUpperTranslation.gridx = 0; gbc_lblUpperTranslation.gridy = 20; getPanel().add(lblUpperTranslation, gbc_lblUpperTranslation); spinnerUpperTranslation = new JSpinner(); spinnerUpperTranslation.setModel(new SpinnerNumberModel(new Float(0), null, null, new Float(1))); GridBagConstraints gbc_spinnerUpperTranslation = new GridBagConstraints(); gbc_spinnerUpperTranslation.fill = GridBagConstraints.HORIZONTAL; gbc_spinnerUpperTranslation.insets = new Insets(0, 0, 5, 0); gbc_spinnerUpperTranslation.gridx = 1; gbc_spinnerUpperTranslation.gridy = 20; getPanel().add(spinnerUpperTranslation, gbc_spinnerUpperTranslation); lblEnablemotor = new JLabel("enableMotor:"); GridBagConstraints gbc_lblEnablemotor = new GridBagConstraints(); gbc_lblEnablemotor.insets = new Insets(0, 0, 5, 5); gbc_lblEnablemotor.gridx = 0; gbc_lblEnablemotor.gridy = 21; getPanel().add(lblEnablemotor, gbc_lblEnablemotor); chckbxEnablemotor = new JCheckBox("enableMotor"); GridBagConstraints gbc_chckbxEnablemotor = new GridBagConstraints(); gbc_chckbxEnablemotor.anchor = GridBagConstraints.WEST; gbc_chckbxEnablemotor.insets = new Insets(0, 0, 5, 0); gbc_chckbxEnablemotor.gridx = 1; gbc_chckbxEnablemotor.gridy = 21; getPanel().add(chckbxEnablemotor, gbc_chckbxEnablemotor); lblMotorspeed = new JLabel("motorSpeed:"); GridBagConstraints gbc_lblMotorspeed = new GridBagConstraints(); gbc_lblMotorspeed.insets = new Insets(0, 0, 5, 5); gbc_lblMotorspeed.gridx = 0; gbc_lblMotorspeed.gridy = 22; getPanel().add(lblMotorspeed, gbc_lblMotorspeed); spinnerMotorSpeed = new JSpinner(); spinnerMotorSpeed.setModel(new SpinnerNumberModel(new Float(0), null, null, new Float(1))); GridBagConstraints gbc_spinnerMotorSpeed = new GridBagConstraints(); gbc_spinnerMotorSpeed.fill = GridBagConstraints.HORIZONTAL; gbc_spinnerMotorSpeed.insets = new Insets(0, 0, 5, 0); gbc_spinnerMotorSpeed.gridx = 1; gbc_spinnerMotorSpeed.gridy = 22; getPanel().add(spinnerMotorSpeed, gbc_spinnerMotorSpeed); lblMaxMotorForce = new JLabel("maxMotorForce:"); GridBagConstraints gbc_lblMaxMotorForce = new GridBagConstraints(); gbc_lblMaxMotorForce.insets = new Insets(0, 0, 5, 5); gbc_lblMaxMotorForce.gridx = 0; gbc_lblMaxMotorForce.gridy = 23; getPanel().add(lblMaxMotorForce, gbc_lblMaxMotorForce); spinnerMaxMotorForce = new JSpinner(); spinnerMaxMotorForce.setModel(new SpinnerNumberModel(new Float(0), null, null, new Float(1))); GridBagConstraints gbc_spinnerMaxMotorForce = new GridBagConstraints(); gbc_spinnerMaxMotorForce.fill = GridBagConstraints.HORIZONTAL; gbc_spinnerMaxMotorForce.insets = new Insets(0, 0, 5, 0); gbc_spinnerMaxMotorForce.gridx = 1; gbc_spinnerMaxMotorForce.gridy = 23; getPanel().add(spinnerMaxMotorForce, gbc_spinnerMaxMotorForce); chckbxUseBodyaCenter.addItemListener(new ItemListener() { public void itemStateChanged(ItemEvent e) { if (chckbxUseBodyaCenter.isSelected()) { PrismaticJointDefModel.class.cast(object).useBodyBCenter = false; chckbxUseBodybCenter.setSelected(false); } } }); chckbxUseBodybCenter.addItemListener(new ItemListener() { public void itemStateChanged(ItemEvent e) { if (chckbxUseBodybCenter.isSelected()) { PrismaticJointDefModel.class.cast(object).useBodyACenter = false; chckbxUseBodyaCenter.setSelected(false); } } }); } private static final long serialVersionUID = -2033825670615410634L; private JSpinner spinnerLocalAnchorAX; private JSpinner spinnerLocalAnchorBy; private JSpinner spinnerLocalAnchorBx; private JSpinner spinnerLocalAnchorAY; private JLabel lblAnchorx; private JSpinner spinnerAnchorx; private JLabel lblAnchory; private JSpinner spinnerAnchory; private JLabel lblReferenceangle; private JSpinner spinnerReferenceAngle; private JLabel lblEnablelimit; private JCheckBox chckbxEnablelimit; private JLabel lblLowerTranslation; private JSpinner spinnerLowerTranslation; private JLabel lblUpperTranslation; private JSpinner spinnerUpperTranslation; private JLabel lblEnablemotor; private JCheckBox chckbxEnablemotor; private JLabel lblMotorspeed; private JSpinner spinnerMotorSpeed; private JLabel lblMaxMotorForce; private JSpinner spinnerMaxMotorForce; private JLabel lblLocalaxisax; private JSpinner spinnerLocalAxisAx; private JLabel lblLocalAxisAy; private JSpinner spinnerLocalAxisAy; private JCheckBox chckbxUseBodyaCenter; private JCheckBox chckbxUseBodybCenter; private JCheckBox chckbxUseBodyabCenter; @Override public Class<PrismaticJointDefModel> getType() { return PrismaticJointDefModel.class; } @Override public void doBinder() { super.doBinder(); PrismaticJointDefModel model = PrismaticJointDefModel.class.cast(object); bind(model.anchor, "x", spinnerAnchorx); bind(model.anchor, "y", spinnerAnchory); bind(model, "maxMotorForce", spinnerMaxMotorForce); bind(model, "motorSpeed", spinnerMotorSpeed); bind(model, "enableMotor", chckbxEnablemotor); bind(model, "upperTranslation", spinnerUpperTranslation); bind(model, "lowerTranslation", spinnerLowerTranslation); bind(model, "enableLimit", chckbxEnablelimit); bind(model, "useBodyACenter", chckbxUseBodyaCenter); bind(model, "useBodyBCenter", chckbxUseBodybCenter); bind(model, "useABCenterLine", chckbxUseBodyabCenter); bind(model.localAxisA, "x", spinnerLocalAxisAx); bind(model.localAxisA, "y", spinnerLocalAxisAy); } @Override public Binder getBinder(Object obj, String name, final JComponent widget) { return new Binder(obj, name, widget) { @Override protected void postSolve() { PrismaticJointDefModel model = PrismaticJointDefModel.class.cast(object); Geometry.ajustJoint(model); if (chckbxUseBodyaCenter.isSelected()) { spinnerAnchorx.setValue(model.bodyA.position.x); spinnerAnchory.setValue(model.bodyA.position.y); } else { if (chckbxUseBodybCenter.isSelected()) { spinnerAnchorx.setValue(model.bodyB.position.x); spinnerAnchory.setValue(model.bodyB.position.y); } } spinnerLocalAnchorAX.setValue(model.localAnchorA.x); spinnerLocalAnchorAY.setValue(model.localAnchorA.y); spinnerLocalAnchorBx.setValue(model.localAnchorB.x); spinnerLocalAnchorBy.setValue(model.localAnchorB.y); spinnerReferenceAngle.setValue(model.referenceDegrees); if (widget != spinnerLocalAxisAx) spinnerLocalAxisAx.setValue(model.localAxisA.x); if (widget != spinnerLocalAxisAy) spinnerLocalAxisAy.setValue(model.localAxisA.y); } }; } }
package com.flipper.models; import lombok.Data; @Data public class Wiki24hPrice { public int avgHighPrice; public int highPriceVolume; public int avgLowPrice; public int lowPriceVolume; }
/* * Redistribution and use in source and binary forms, with or without modification, are permitted provided that the * following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following * disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the * following disclaimer in the documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * */ package org.postgresql.ext.javatutorial.common.data; public class BikeStation { private final int id; private final String name; private final double latitude; private final double longitude; public BikeStation(int id, String name, double latitude, double longitude) { this.id = id; this.name = name; this.latitude = latitude; this.longitude = longitude; } public BikeStation(String id, String name, String latitude, String longitude) { this( Integer.parseInt(id), name, Double.parseDouble(latitude), Double.parseDouble(longitude) ); } public int getId() { return id; } public String getName() { return name; } public double getLatitude() { return latitude; } public double getLongitude() { return longitude; } @Override public String toString() { return "BikeStation{" + "id=" + id + ", name='" + name + '\'' + ", latitude=" + latitude + ", longitude=" + longitude + '}'; } }
package com.akash2099.fragment_tutorial; import androidx.appcompat.app.AppCompatActivity; import android.os.Bundle; public class SendDataBetweenFragmentsThroughActivity extends AppCompatActivity implements FragmentA.FragmentAListener, FragmentB.FragmentBListener{ private FragmentA fragmentA; private FragmentB fragmentB; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_send_data_between_fragments_through); fragmentA = new FragmentA(); fragmentB = new FragmentB(); // System.out.println("Hi how 2"); getSupportFragmentManager().beginTransaction() .replace(R.id.container_a, fragmentA) .replace(R.id.container_b, fragmentB) .commit(); } @Override public void onInputASent(CharSequence input) { fragmentB.updateEditText(input); } @Override public void onInputBSent(CharSequence input) { fragmentA.updateEditText(input); } }
/* Gemma: An RPG Copyright (C) 2013-2014 Eric Ahnell Any questions should be directed to the author via email at: support@puttysoftware.com */ package com.puttysoftware.gemma.support.map.generic; import com.puttysoftware.gemma.support.Support; import com.puttysoftware.gemma.support.map.MapConstants; import com.puttysoftware.gemma.support.resourcemanagers.GameSoundConstants; import com.puttysoftware.gemma.support.scripts.internal.InternalScript; import com.puttysoftware.gemma.support.scripts.internal.InternalScriptActionCode; import com.puttysoftware.gemma.support.scripts.internal.InternalScriptEntry; import com.puttysoftware.gemma.support.scripts.internal.InternalScriptEntryArgument; import com.puttysoftware.randomrange.RandomRange; public abstract class GenericTeleport extends MapObject { // Fields private int destRow; private int destCol; private int destFloor; private final InternalScript postMove; // Constructors protected GenericTeleport() { super(false); this.setTemplateTransform(new TemplateTransform(0.25, 0.5, 1.0)); RandomRange r = new RandomRange(0, Support.getGameMapSize() - 1); RandomRange rf = new RandomRange(0, Support.getGameMapFloorSize() - 1); this.destRow = r.generate(); this.destCol = r.generate(); this.destFloor = rf.generate(); // Create post-move script this.postMove = new InternalScript(); InternalScriptEntry act0 = new InternalScriptEntry(); act0.setActionCode(InternalScriptActionCode.MOVE); act0.addActionArg(new InternalScriptEntryArgument(true)); act0.addActionArg(new InternalScriptEntryArgument(false)); act0.addActionArg(new InternalScriptEntryArgument(this.destRow)); act0.addActionArg(new InternalScriptEntryArgument(this.destCol)); act0.addActionArg(new InternalScriptEntryArgument(this.destFloor)); act0.finalizeActionArgs(); this.postMove.addAction(act0); InternalScriptEntry act1 = new InternalScriptEntry(); act1.setActionCode(InternalScriptActionCode.SOUND); act1.addActionArg(new InternalScriptEntryArgument( GameSoundConstants.SOUND_TELEPORT)); act1.finalizeActionArgs(); this.postMove.addAction(act1); this.postMove.finalizeActions(); } @Override public boolean equals(Object obj) { if (obj == null) { return false; } if (this.getClass() != obj.getClass()) { return false; } final GenericTeleport other = (GenericTeleport) obj; if (this.destRow != other.destRow) { return false; } if (this.destCol != other.destCol) { return false; } if (this.destFloor != other.destFloor) { return false; } return true; } @Override public int hashCode() { int hash = 7; hash = 67 * hash + this.destRow; hash = 67 * hash + this.destCol; return 67 * hash + this.destFloor; } @Override public GenericTeleport clone() { GenericTeleport copy = (GenericTeleport) super.clone(); copy.destCol = this.destCol; copy.destFloor = this.destFloor; copy.destRow = this.destRow; return copy; } // Scriptability @Override public InternalScript getPostMoveScript(final boolean ie, final int dirX, final int dirY, final int dirZ) { return this.postMove; } @Override public abstract String getName(); @Override public int getLayer() { return MapConstants.LAYER_OBJECT; } @Override protected void setTypes() { this.type.set(TypeConstants.TYPE_TELEPORT); } @Override public boolean defersSetProperties() { return true; } @Override public int getCustomProperty(int propID) { switch (propID) { case 1: return this.destRow; case 2: return this.destCol; case 3: return this.destFloor; default: return MapObject.DEFAULT_CUSTOM_VALUE; } } @Override public void setCustomProperty(int propID, int value) { switch (propID) { case 1: this.destRow = value; break; case 2: this.destCol = value; break; case 3: this.destFloor = value; break; default: break; } } @Override public int getCustomFormat() { return 3; } @Override public boolean enabledInBattle() { return false; } }
/** * 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.kafka.streams.kstream.internals; import org.apache.kafka.common.serialization.Serde; import org.apache.kafka.common.serialization.Serdes; import org.apache.kafka.common.utils.Utils; import org.apache.kafka.streams.KeyValue; import org.apache.kafka.streams.kstream.KStreamBuilder; import org.apache.kafka.streams.kstream.KTable; import org.apache.kafka.streams.kstream.KeyValueMapper; import org.apache.kafka.test.KStreamTestDriver; import org.apache.kafka.test.MockAggregator; import org.apache.kafka.test.MockInitializer; import org.apache.kafka.test.MockKeyValueMapper; import org.apache.kafka.test.MockProcessorSupplier; import org.apache.kafka.test.TestUtils; import org.junit.After; import org.junit.Before; import org.junit.Test; import java.io.File; import java.io.IOException; import static org.junit.Assert.assertEquals; public class KTableAggregateTest { final private Serde<String> stringSerde = Serdes.String(); private KStreamTestDriver driver = null; private File stateDir = null; @After public void tearDown() { if (driver != null) { driver.close(); } driver = null; } @Before public void setUp() throws IOException { stateDir = TestUtils.tempDirectory("kafka-test"); } @Test public void testAggBasic() throws Exception { final KStreamBuilder builder = new KStreamBuilder(); String topic1 = "topic1"; KTable<String, String> table1 = builder.table(stringSerde, stringSerde, topic1); KTable<String, String> table2 = table1.groupBy(MockKeyValueMapper.<String, String>NoOpKeyValueMapper(), stringSerde, stringSerde ).aggregate(MockInitializer.STRING_INIT, MockAggregator.STRING_ADDER, MockAggregator.STRING_REMOVER, stringSerde, "topic1-Canonized"); MockProcessorSupplier<String, String> proc = new MockProcessorSupplier<>(); table2.toStream().process(proc); driver = new KStreamTestDriver(builder, stateDir); driver.process(topic1, "A", "1"); driver.process(topic1, "B", "2"); driver.process(topic1, "A", "3"); driver.process(topic1, "B", "4"); driver.process(topic1, "C", "5"); driver.process(topic1, "D", "6"); driver.process(topic1, "B", "7"); driver.process(topic1, "C", "8"); assertEquals(Utils.mkList( "A:0+1", "B:0+2", "A:0+1-1", "A:0+1-1+3", "B:0+2-2", "B:0+2-2+4", "C:0+5", "D:0+6", "B:0+2-2+4-4", "B:0+2-2+4-4+7", "C:0+5-5", "C:0+5-5+8"), proc.processed); } @Test public void testAggRepartition() throws Exception { final KStreamBuilder builder = new KStreamBuilder(); String topic1 = "topic1"; KTable<String, String> table1 = builder.table(stringSerde, stringSerde, topic1); KTable<String, String> table2 = table1.groupBy(new KeyValueMapper<String, String, KeyValue<String, String>>() { @Override public KeyValue<String, String> apply(String key, String value) { if (key.equals("null")) { return KeyValue.pair(null, value); } else if (key.equals("NULL")) { return null; } else { return KeyValue.pair(value, value); } } }, stringSerde, stringSerde ) .aggregate(MockInitializer.STRING_INIT, MockAggregator.STRING_ADDER, MockAggregator.STRING_REMOVER, stringSerde, "topic1-Canonized"); MockProcessorSupplier<String, String> proc = new MockProcessorSupplier<>(); table2.toStream().process(proc); driver = new KStreamTestDriver(builder, stateDir); driver.process(topic1, "A", "1"); driver.process(topic1, "A", null); driver.process(topic1, "A", "1"); driver.process(topic1, "B", "2"); driver.process(topic1, "null", "3"); driver.process(topic1, "B", "4"); driver.process(topic1, "NULL", "5"); driver.process(topic1, "B", "7"); assertEquals(Utils.mkList( "1:0+1", "1:0+1-1", "1:0+1-1+1", "2:0+2", // noop "2:0+2-2", "4:0+4", // noop "4:0+4-4", "7:0+7" ), proc.processed); } }
package io.smallrye.graphql.execution; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertNotNull; import javax.json.JsonArray; import javax.json.JsonObject; import org.junit.jupiter.api.Test; /** * Test a basic query * * @author Phillip Kruger (phillip.kruger@redhat.com) */ public class ExecutionTest extends ExecutionTestBase { @Test public void testBasicQuery() { JsonObject data = executeAndGetData(TEST_QUERY); JsonObject testObject = data.getJsonObject("testObject"); assertNotNull(testObject); assertFalse(testObject.isNull("name"), "name should not be null"); assertEquals("Phillip", testObject.getString("name")); assertFalse(testObject.isNull("id"), "id should not be null"); // Testing source assertFalse(testObject.isNull("timestamp"), "timestamp should not be null"); assertFalse(testObject.get("timestamp").asJsonObject().isNull("value"), "timestamp value should not be null"); } @Test public void testBasicListQuery() { JsonObject data = executeAndGetData(TEST_LIST_QUERY); JsonArray testObjects = data.getJsonArray("testObjects"); assertNotNull(testObjects); assertEquals(2, testObjects.size()); JsonObject testObject = testObjects.getJsonObject(0); assertNotNull(testObject); assertFalse(testObject.isNull("name"), "name should not be null"); assertEquals("Phillip", testObject.getString("name")); assertFalse(testObject.isNull("id"), "id should not be null"); // Testing batch assertFalse(testObject.isNull("timestamp"), "timestamp should not be null"); assertFalse(testObject.get("timestamp").asJsonObject().isNull("value"), "timestamp value should not be null"); } private static final String TEST_QUERY = "{\n" + " testObject(yourname:\"Phillip\") {\n" + " id\n" + " name\n" + " timestamp {\n" + " value\n" + " }\n" + " }\n" + "}"; private static final String TEST_LIST_QUERY = "{\n" + " testObjects {\n" + " id\n" + " name\n" + " timestamp {\n" + " value\n" + " }\n" + " }\n" + "}"; }
package org.github.rwynn.wellington.cache; import net.sf.ehcache.Cache; import org.springframework.cache.annotation.EnableCaching; import org.springframework.cache.ehcache.EhCacheCacheManager; import org.springframework.cache.ehcache.EhCacheManagerFactoryBean; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.core.io.ClassPathResource; import org.springframework.security.core.userdetails.cache.EhCacheBasedUserCache; @Configuration public class EhcacheConfig { @Bean public EhCacheManagerFactoryBean ehCacheManagerFactoryBean() { EhCacheManagerFactoryBean ehCacheManagerFactoryBean = new EhCacheManagerFactoryBean(); ehCacheManagerFactoryBean.setCacheManagerName("CACHE_MANAGER"); ehCacheManagerFactoryBean.setShared(true); ehCacheManagerFactoryBean.setConfigLocation(new ClassPathResource("ehcache.xml")); return ehCacheManagerFactoryBean; } @Bean public EhCacheCacheManager ehCacheCacheManager(EhCacheManagerFactoryBean ehCacheManagerFactoryBean) { EhCacheCacheManager ehCacheCacheManager = new EhCacheCacheManager(ehCacheManagerFactoryBean.getObject()); return ehCacheCacheManager; } @Bean public EhCacheBasedUserCache ehCacheBasedUserCache(EhCacheCacheManager ehCacheCacheManager) { EhCacheBasedUserCache ehCacheBasedUserCache = new EhCacheBasedUserCache(); ehCacheBasedUserCache.setCache((Cache) ehCacheCacheManager.getCache("userCache").getNativeCache()); return ehCacheBasedUserCache; } }
package com.superman.generator.service.impl; import com.superman.utils.text.Convert; import com.superman.generator.domain.GenTableColumn; import com.superman.generator.mapper.GenTableColumnMapper; import com.superman.generator.service.IGenTableColumnService; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; /** * 业务字段 服务层实现 * * @author ruoyi */ @Service public class GenTableColumnServiceImpl implements IGenTableColumnService { @Autowired private GenTableColumnMapper genTableColumnMapper; /** * 查询业务字段列表 * * @param genTableColumn 业务字段信息 * @return 业务字段集合 */ @Override public List<GenTableColumn> selectGenTableColumnListByTableId(GenTableColumn genTableColumn) { return genTableColumnMapper.selectGenTableColumnListByTableId(genTableColumn); } /** * 新增业务字段 * * @param genTableColumn 业务字段信息 * @return 结果 */ @Override public int insertGenTableColumn(GenTableColumn genTableColumn) { return genTableColumnMapper.insertGenTableColumn(genTableColumn); } /** * 修改业务字段 * * @param genTableColumn 业务字段信息 * @return 结果 */ @Override public int updateGenTableColumn(GenTableColumn genTableColumn) { return genTableColumnMapper.updateGenTableColumn(genTableColumn); } /** * 删除业务字段对象 * * @param ids 需要删除的数据ID * @return 结果 */ @Override public int deleteGenTableColumnByIds(String ids) { return genTableColumnMapper.deleteGenTableColumnByIds(Convert.toLongArray(ids)); } }
package org.togetherjava.command.commands.javadoc.formatting; import de.ialistannen.htmljavadocparser.model.doc.JavadocComment; import de.ialistannen.htmljavadocparser.model.properties.JavadocElement; import java.util.List; import java.util.Optional; import java.util.stream.Collectors; import net.dv8tion.jda.api.entities.MessageChannel; import org.togetherjava.messaging.BotMessage.MessageCategory; import org.togetherjava.messaging.ComplexMessage; import org.togetherjava.messaging.SimpleMessage; import org.togetherjava.messaging.sending.MessageSender; /** * Sends result messages for javadoc queries. */ public class JavadocMessageSender { private final JavadocMessageFormatter messageFormatter; /** * Creates a new Javadoc message sender. * * @param messageFormatter the message formatter to use */ public JavadocMessageSender(JavadocMessageFormatter messageFormatter) { this.messageFormatter = messageFormatter; } /** * Sends a message containing the javadoc results. Either a single javadoc, a list with found * classes or an error. * * @param elements the found elements * @param sender the message sender * @param channel the channel to send it to */ public void sendResult(List<? extends JavadocElement> elements, MessageSender sender, MessageChannel channel) { if (elements.isEmpty()) { sendNothingFound(channel, sender); return; } if (elements.size() == 1) { sendSingleJavadoc(channel, sender, elements.get(0)); return; } sendMultipleFoundError(channel, sender, elements); } /** * Sends a single javadoc result. * * @param channel the channel to send it to * @param sender the message sender * @param element the element */ public void sendSingleJavadoc(MessageChannel channel, MessageSender sender, JavadocElement element) { ComplexMessage message = new ComplexMessage(MessageCategory.NONE); Optional<JavadocComment> javadoc = element.getJavadoc(); if (javadoc.isEmpty()) { message.setCategory(MessageCategory.ERROR) .editEmbed(eb -> eb.setDescription("No javadoc found on that element")); } else { messageFormatter.format(message, element); } sender.sendMessage(message, channel); } /** * Sends an error message saying that no types were found. * * @param channel the channel to send it to * @param sender the message sender */ public void sendNothingFound(MessageChannel channel, MessageSender sender) { sender.sendMessage(SimpleMessage.error("Nothing found :("), channel); } /** * Sends an error with a list of the found elements. * * @param channel the channel to send it to * @param sender the message sender * @param foundElements the found elements */ public void sendMultipleFoundError(MessageChannel channel, MessageSender sender, List<? extends JavadocElement> foundElements) { String types = foundElements.stream() .map(JavadocElement::getFullyQualifiedName) .map(s -> "`" + s + "`") .limit(10) .collect(Collectors.joining("\n**\\*** ", "**\\*** ", "")); ComplexMessage message = new ComplexMessage(MessageCategory.ERROR) .editEmbed(eb -> eb.setTitle("I found at least the following types:")) .editEmbed(eb -> eb.setDescription(types)); sender.sendMessage(message, channel); } }
package dp.observer.restaurant; import dp.observer.interfaces.Hauptgericht; import dp.observer.interfaces.HauptgerichtObserver; public class Bueffetier implements HauptgerichtObserver { private String name; public Bueffetier(String name) { this.name = name; } @Override public String getName() { return name; } @Override public void setName(String name) { this.name = name; } @Override public void benachrichtigungBearbeiten(Hauptgericht hauptgericht) { String simpleName = getClass().getSimpleName(); String meldung = simpleName + " " + name + " wurde informiert wegen " + hauptgericht.getClass().getSimpleName() + " ID: " + hauptgericht.getId(); System.out.println(meldung); } }
package hu.mta.sztaki.lpds.cloud.entice.imageoptimizer.iaashandler.amazontarget; import static org.junit.Assert.*; import org.junit.Before; import org.junit.Test; public class TestEC2VirtualMachine { private EC2VirtualMachine t = null; @Before public void init() { System.setProperty("hu.mta.sztaki.lpds.cloud.entice.imageoptimizer.maxUsableCPUs", "10"); t = new EC2VirtualMachine("vaid", null, false); } @Test public void getInstanceId() { assertNull(t.getInstanceId()); } @Test public void getImageId() { assertNotNull(t.getImageId()); } @Test public void getIP() throws Exception { assertNull(t.getIP()); } @Test public void getPort() throws Exception { assertNull(t.getPort()); } }
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.hadoop.hbase.master.procedure; import java.io.IOException; import java.util.Collections; import java.util.List; import java.util.stream.Collectors; import org.apache.hadoop.hbase.HBaseIOException; import org.apache.hadoop.hbase.HRegionLocation; import org.apache.hadoop.hbase.TableName; import org.apache.hadoop.hbase.master.RegionPlan; import org.apache.hadoop.hbase.master.assignment.MoveRegionProcedure; import org.apache.hadoop.hbase.procedure2.ProcedureStateSerializer; import org.apache.hadoop.hbase.procedure2.ProcedureSuspendedException; import org.apache.hadoop.hbase.procedure2.ProcedureYieldException; import org.apache.yetus.audience.InterfaceAudience; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.apache.hadoop.hbase.shaded.protobuf.ProtobufUtil; import org.apache.hadoop.hbase.shaded.protobuf.generated.MasterProcedureProtos.ReopenTableRegionsState; import org.apache.hadoop.hbase.shaded.protobuf.generated.MasterProcedureProtos.ReopenTableRegionsStateData; /** * Used for reopening the regions for a table. * <p/> * Currently we use {@link MoveRegionProcedure} to reopen regions. */ @InterfaceAudience.Private public class ReopenTableRegionsProcedure extends AbstractStateMachineTableProcedure<ReopenTableRegionsState> { private static final Logger LOG = LoggerFactory.getLogger(ReopenTableRegionsProcedure.class); private TableName tableName; private List<HRegionLocation> regions = Collections.emptyList(); public ReopenTableRegionsProcedure() { } public ReopenTableRegionsProcedure(TableName tableName) { this.tableName = tableName; } @Override public TableName getTableName() { return tableName; } @Override public TableOperationType getTableOperationType() { return TableOperationType.REGION_EDIT; } private MoveRegionProcedure createReopenProcedure(MasterProcedureEnv env, HRegionLocation loc) { try { return new MoveRegionProcedure(env, new RegionPlan(loc.getRegion(), loc.getServerName(), loc.getServerName()), false); } catch (HBaseIOException e) { // we skip the checks so this should not happen throw new AssertionError(e); } } @Override protected Flow executeFromState(MasterProcedureEnv env, ReopenTableRegionsState state) throws ProcedureSuspendedException, ProcedureYieldException, InterruptedException { switch (state) { case REOPEN_TABLE_REGIONS_GET_REGIONS: if (!env.getAssignmentManager().isTableEnabled(tableName)) { LOG.info("Table {} is disabled, give up reopening its regions"); return Flow.NO_MORE_STATE; } regions = env.getAssignmentManager().getRegionStates().getRegionsOfTableForReopen(tableName); setNextState(ReopenTableRegionsState.REOPEN_TABLE_REGIONS_REOPEN_REGIONS); return Flow.HAS_MORE_STATE; case REOPEN_TABLE_REGIONS_REOPEN_REGIONS: addChildProcedure(regions.stream().filter(l -> l.getSeqNum() >= 0) .map(l -> createReopenProcedure(env, l)).toArray(MoveRegionProcedure[]::new)); setNextState(ReopenTableRegionsState.REOPEN_TABLE_REGIONS_CONFIRM_REOPENED); return Flow.HAS_MORE_STATE; case REOPEN_TABLE_REGIONS_CONFIRM_REOPENED: regions = regions.stream().map(env.getAssignmentManager().getRegionStates()::checkReopened) .filter(l -> l != null).collect(Collectors.toList()); if (regions.isEmpty()) { return Flow.NO_MORE_STATE; } if (regions.stream().anyMatch(l -> l.getSeqNum() >= 0)) { setNextState(ReopenTableRegionsState.REOPEN_TABLE_REGIONS_REOPEN_REGIONS); return Flow.HAS_MORE_STATE; } LOG.info("There are still {} region(s) which need to be reopened for table {} are in " + "OPENING state, try again later", regions.size(), tableName); // All the regions need to reopen are in OPENING state which means we can not schedule any // MRPs. Then sleep for one second, and yield the procedure to let other procedures run // first and hope next time we can get some regions in other state to make progress. // TODO: add a delay for ProcedureYieldException so that we do not need to sleep here which // blocks a procedure worker. Thread.sleep(1000); throw new ProcedureYieldException(); default: throw new UnsupportedOperationException("unhandled state=" + state); } } @Override protected void rollbackState(MasterProcedureEnv env, ReopenTableRegionsState state) throws IOException, InterruptedException { throw new UnsupportedOperationException(); } @Override protected ReopenTableRegionsState getState(int stateId) { return ReopenTableRegionsState.forNumber(stateId); } @Override protected int getStateId(ReopenTableRegionsState state) { return state.getNumber(); } @Override protected ReopenTableRegionsState getInitialState() { return ReopenTableRegionsState.REOPEN_TABLE_REGIONS_GET_REGIONS; } @Override protected void serializeStateData(ProcedureStateSerializer serializer) throws IOException { super.serializeStateData(serializer); ReopenTableRegionsStateData.Builder builder = ReopenTableRegionsStateData.newBuilder() .setTableName(ProtobufUtil.toProtoTableName(tableName)); regions.stream().map(ProtobufUtil::toRegionLocation).forEachOrdered(builder::addRegion); serializer.serialize(builder.build()); } @Override protected void deserializeStateData(ProcedureStateSerializer serializer) throws IOException { super.deserializeStateData(serializer); ReopenTableRegionsStateData data = serializer.deserialize(ReopenTableRegionsStateData.class); tableName = ProtobufUtil.toTableName(data.getTableName()); regions = data.getRegionList().stream().map(ProtobufUtil::toRegionLocation) .collect(Collectors.toList()); } }
package io.dronefleet.mavlink.common; import io.dronefleet.mavlink.annotations.MavlinkFieldInfo; import io.dronefleet.mavlink.annotations.MavlinkMessageBuilder; import io.dronefleet.mavlink.annotations.MavlinkMessageInfo; import io.dronefleet.mavlink.util.EnumValue; import java.lang.Enum; import java.lang.Object; import java.lang.Override; import java.lang.String; import java.util.Collection; import java.util.Objects; /** * Emit the value of a onboard parameter. The inclusion of param_count and param_index in the * message allows the recipient to keep track of received parameters and allows him to re-request * missing parameters after a loss or timeout. The parameter microservice is documented at * https://mavlink.io/en/services/parameter.html */ @MavlinkMessageInfo( id = 22, crc = 220, description = "Emit the value of a onboard parameter. The inclusion of param_count and param_index in the message allows the recipient to keep track of received parameters and allows him to re-request missing parameters after a loss or timeout. The parameter microservice is documented at https://mavlink.io/en/services/parameter.html" ) public final class ParamValue { private final String paramId; private final float paramValue; private final EnumValue<MavParamType> paramType; private final int paramCount; private final int paramIndex; private ParamValue(String paramId, float paramValue, EnumValue<MavParamType> paramType, int paramCount, int paramIndex) { this.paramId = paramId; this.paramValue = paramValue; this.paramType = paramType; this.paramCount = paramCount; this.paramIndex = paramIndex; } /** * Returns a builder instance for this message. */ @MavlinkMessageBuilder public static Builder builder() { return new Builder(); } /** * Onboard parameter id, terminated by NULL if the length is less than 16 human-readable chars and * WITHOUT null termination (NULL) byte if the length is exactly 16 chars - applications have to * provide 16+1 bytes storage if the ID is stored as string */ @MavlinkFieldInfo( position = 1, unitSize = 1, arraySize = 16, description = "Onboard parameter id, terminated by NULL if the length is less than 16 human-readable chars and WITHOUT null termination (NULL) byte if the length is exactly 16 chars - applications have to provide 16+1 bytes storage if the ID is stored as string" ) public final String paramId() { return this.paramId; } /** * Onboard parameter value */ @MavlinkFieldInfo( position = 2, unitSize = 4, description = "Onboard parameter value" ) public final float paramValue() { return this.paramValue; } /** * Onboard parameter type. */ @MavlinkFieldInfo( position = 3, unitSize = 1, enumType = MavParamType.class, description = "Onboard parameter type." ) public final EnumValue<MavParamType> paramType() { return this.paramType; } /** * Total number of onboard parameters */ @MavlinkFieldInfo( position = 4, unitSize = 2, description = "Total number of onboard parameters" ) public final int paramCount() { return this.paramCount; } /** * Index of this onboard parameter */ @MavlinkFieldInfo( position = 5, unitSize = 2, description = "Index of this onboard parameter" ) public final int paramIndex() { return this.paramIndex; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || !getClass().equals(o.getClass())) return false; ParamValue other = (ParamValue)o; if (!Objects.deepEquals(paramId, other.paramId)) return false; if (!Objects.deepEquals(paramValue, other.paramValue)) return false; if (!Objects.deepEquals(paramType, other.paramType)) return false; if (!Objects.deepEquals(paramCount, other.paramCount)) return false; if (!Objects.deepEquals(paramIndex, other.paramIndex)) return false; return true; } @Override public int hashCode() { int result = 0; result = 31 * result + Objects.hashCode(paramId); result = 31 * result + Objects.hashCode(paramValue); result = 31 * result + Objects.hashCode(paramType); result = 31 * result + Objects.hashCode(paramCount); result = 31 * result + Objects.hashCode(paramIndex); return result; } @Override public String toString() { return "ParamValue{paramId=" + paramId + ", paramValue=" + paramValue + ", paramType=" + paramType + ", paramCount=" + paramCount + ", paramIndex=" + paramIndex + "}"; } public static final class Builder { private String paramId; private float paramValue; private EnumValue<MavParamType> paramType; private int paramCount; private int paramIndex; /** * Onboard parameter id, terminated by NULL if the length is less than 16 human-readable chars and * WITHOUT null termination (NULL) byte if the length is exactly 16 chars - applications have to * provide 16+1 bytes storage if the ID is stored as string */ @MavlinkFieldInfo( position = 1, unitSize = 1, arraySize = 16, description = "Onboard parameter id, terminated by NULL if the length is less than 16 human-readable chars and WITHOUT null termination (NULL) byte if the length is exactly 16 chars - applications have to provide 16+1 bytes storage if the ID is stored as string" ) public final Builder paramId(String paramId) { this.paramId = paramId; return this; } /** * Onboard parameter value */ @MavlinkFieldInfo( position = 2, unitSize = 4, description = "Onboard parameter value" ) public final Builder paramValue(float paramValue) { this.paramValue = paramValue; return this; } /** * Onboard parameter type. */ @MavlinkFieldInfo( position = 3, unitSize = 1, enumType = MavParamType.class, description = "Onboard parameter type." ) public final Builder paramType(EnumValue<MavParamType> paramType) { this.paramType = paramType; return this; } /** * Onboard parameter type. */ public final Builder paramType(MavParamType entry) { return paramType(EnumValue.of(entry)); } /** * Onboard parameter type. */ public final Builder paramType(Enum... flags) { return paramType(EnumValue.create(flags)); } /** * Onboard parameter type. */ public final Builder paramType(Collection<Enum> flags) { return paramType(EnumValue.create(flags)); } /** * Total number of onboard parameters */ @MavlinkFieldInfo( position = 4, unitSize = 2, description = "Total number of onboard parameters" ) public final Builder paramCount(int paramCount) { this.paramCount = paramCount; return this; } /** * Index of this onboard parameter */ @MavlinkFieldInfo( position = 5, unitSize = 2, description = "Index of this onboard parameter" ) public final Builder paramIndex(int paramIndex) { this.paramIndex = paramIndex; return this; } public final ParamValue build() { return new ParamValue(paramId, paramValue, paramType, paramCount, paramIndex); } } }
package weixin.popular.api; import java.io.UnsupportedEncodingException; import java.net.URLEncoder; import org.apache.http.client.methods.HttpUriRequest; import org.apache.http.client.methods.RequestBuilder; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import weixin.popular.bean.BaseResult; import weixin.popular.bean.sns.Jscode2sessionResult; import weixin.popular.bean.sns.SnsToken; import weixin.popular.bean.user.User; import weixin.popular.client.LocalHttpClient; import weixin.popular.util.EmojiUtil; /** * 网页授权 * @author LiYi * */ public class SnsAPI extends BaseAPI{ private static Logger logger = LoggerFactory.getLogger(SnsAPI.class); /** * 通过code换取网页授权access_token * @param appid appid * @param secret secret * @param code code * @return SnsToken */ public static SnsToken oauth2AccessToken(String appid,String secret,String code){ HttpUriRequest httpUriRequest = RequestBuilder.post() .setUri(BASE_URI + "/sns/oauth2/access_token") .addParameter("appid", appid) .addParameter("secret", secret) .addParameter("code", code) .addParameter("grant_type", "authorization_code") .build(); return LocalHttpClient.executeJsonResult(httpUriRequest,SnsToken.class); } /** * 通过code换取网页授权access_token (第三方平台开发) * @param appid appid * @param code code * @param component_appid 服务开发方的appid * @param component_access_token 服务开发方的access_token * @return SnsToken */ public static SnsToken oauth2ComponentAccessToken(String appid,String code,String component_appid,String component_access_token ){ HttpUriRequest httpUriRequest = RequestBuilder.post() .setUri(BASE_URI + "/sns/oauth2/component/access_token") .addParameter("appid", appid) .addParameter("code", code) .addParameter("grant_type", "authorization_code") .addParameter("component_appid", component_appid) .addParameter("component_access_token", component_access_token) .build(); return LocalHttpClient.executeJsonResult(httpUriRequest,SnsToken.class); } /** * 刷新access_token * @param appid appid * @param refresh_token refresh_token * @return SnsToken */ public static SnsToken oauth2RefreshToken(String appid,String refresh_token){ HttpUriRequest httpUriRequest = RequestBuilder.post() .setUri(BASE_URI + "/sns/oauth2/refresh_token") .addParameter("appid", appid) .addParameter("refresh_token", refresh_token) .addParameter("grant_type", "refresh_token") .build(); return LocalHttpClient.executeJsonResult(httpUriRequest,SnsToken.class); } /** * 刷新access_token (第三方平台开发) * @param appid appid * @param refresh_token refresh_token * @param component_appid 服务开发商的appid * @param component_access_token 服务开发方的access_token * @return SnsToken */ public static SnsToken oauth2ComponentRefreshToken(String appid,String refresh_token,String component_appid,String component_access_token){ HttpUriRequest httpUriRequest = RequestBuilder.post() .setUri(BASE_URI + "/sns/oauth2/component/refresh_token") .addParameter("appid", appid) .addParameter("refresh_token", refresh_token) .addParameter("grant_type", "refresh_token") .addParameter("component_appid", component_appid) .addParameter("component_access_token", component_access_token) .build(); return LocalHttpClient.executeJsonResult(httpUriRequest,SnsToken.class); } /** * 检验授权凭证(access_token)是否有效 * @since 2.8.1 * @param access_token access_token * @param openid openid * @return result */ public static BaseResult auth(String access_token,String openid){ HttpUriRequest httpUriRequest = RequestBuilder.get() .setUri(BASE_URI + "/sns/auth") .addParameter(PARAM_ACCESS_TOKEN, API.accessToken(access_token)) .addParameter("openid", openid) .build(); return LocalHttpClient.executeJsonResult(httpUriRequest,BaseResult.class); } /** * 拉取用户信息(需scope为 snsapi_userinfo) * @since 2.7.1 * @param access_token access_token * @param openid openid * @param lang 国家地区语言版本,zh_CN 简体,zh_TW 繁体,en 英语 * @param emoji 表情解析方式<br> * 0 不设置 <br> * 1 HtmlHex 格式<br> * 2 HtmlTag 格式<br> * 3 Alias 格式<br> * 4 HtmlDec 格式<br> * 5 PureText 纯文本<br> * @return User */ public static User userinfo(String access_token,String openid,String lang,int emoji){ HttpUriRequest httpUriRequest = RequestBuilder.get() .setUri(BASE_URI + "/sns/userinfo") .addParameter(PARAM_ACCESS_TOKEN, access_token) .addParameter("openid", openid) .addParameter("lang", lang) .build(); User user = LocalHttpClient.executeJsonResult(httpUriRequest,User.class); if(emoji != 0 && user != null && user.getNickname() != null){ user.setNickname_emoji(EmojiUtil.parse(user.getNickname(), emoji)); } return user; } /** * 拉取用户信息(需scope为 snsapi_userinfo) * @param access_token access_token * @param openid openid * @param lang 国家地区语言版本,zh_CN 简体,zh_TW 繁体,en 英语 * @return User */ public static User userinfo(String access_token,String openid,String lang){ return userinfo(access_token, openid, lang,0); } /** * 生成网页授权 URL * @param appid appid * @param redirect_uri 自动URLEncoder * @param snsapi_userinfo snsapi_userinfo * @param state 可以为空 * @return url */ public static String connectOauth2Authorize(String appid,String redirect_uri,boolean snsapi_userinfo,String state){ return connectOauth2Authorize(appid, redirect_uri, snsapi_userinfo, state, null); } /** * 生成网页授权 URL (第三方平台开发) * @param appid appid * @param redirect_uri 自动URLEncoder * @param snsapi_userinfo snsapi_userinfo * @param state 可以为空 * @param component_appid 第三方平台开发,可以为空。 * 服务方的appid,在申请创建公众号服务成功后,可在公众号服务详情页找到 * @return url */ public static String connectOauth2Authorize(String appid,String redirect_uri,boolean snsapi_userinfo,String state,String component_appid){ try { StringBuilder sb = new StringBuilder(); sb.append(OPEN_URI + "/connect/oauth2/authorize?") .append("appid=").append(appid) .append("&redirect_uri=").append(URLEncoder.encode(redirect_uri, "utf-8")) .append("&response_type=code") .append("&scope=").append(snsapi_userinfo?"snsapi_userinfo":"snsapi_base") .append("&state=").append(state==null?"":state); if(component_appid!=null){ sb.append("&component_appid=").append(component_appid); } sb.append("#wechat_redirect"); return sb.toString(); } catch (UnsupportedEncodingException e) { logger.error("", e); } return null; } /** * 生成网页授权 URL (网站应用微信登录) * 2.5.3 * @param appid appid * @param redirect_uri 自动URLEncoder * @param state 可以为空 * @return url */ public static String connectQrconnect(String appid,String redirect_uri,String state){ try { StringBuilder sb = new StringBuilder(); sb.append(OPEN_URI + "/connect/qrconnect?") .append("appid=").append(appid) .append("&redirect_uri=").append(URLEncoder.encode(redirect_uri, "utf-8")) .append("&response_type=code") .append("&scope=snsapi_login") .append("&state=").append(state==null?"":state) .append("#wechat_redirect"); return sb.toString(); } catch (UnsupportedEncodingException e) { logger.error("", e); } return null; } /** * code 换取 session_key(微信小程序) * @since 2.8.3 * @param appid appid * @param secret secret * @param js_code js_code * @return result */ public static Jscode2sessionResult jscode2session(String appid,String secret,String js_code){ HttpUriRequest httpUriRequest = RequestBuilder.get() .setUri(BASE_URI + "/sns/jscode2session") .addParameter("appid",appid) .addParameter("secret",secret) .addParameter("js_code",js_code) .addParameter("grant_type","authorization_code") .build(); return LocalHttpClient.executeJsonResult(httpUriRequest,Jscode2sessionResult.class); } /** * code 换取 session_key(微信小程序 第三方平台) * @since 2.8.9 * @param appid appid * @param js_code js_code * @param component_appid component_appid * @param component_access_token component_access_token * @return result */ public static Jscode2sessionResult componentJscode2session(String appid,String js_code,String component_appid,String component_access_token){ HttpUriRequest httpUriRequest = RequestBuilder.get() .setUri(BASE_URI + "/sns/component/jscode2session") .addParameter("appid",appid) .addParameter("js_code",js_code) .addParameter("grant_type","authorization_code") .addParameter("component_appid",component_appid) .addParameter("component_access_token",API.componentAccessToken(component_access_token)) .build(); return LocalHttpClient.executeJsonResult(httpUriRequest,Jscode2sessionResult.class); } }
/* * API de Integração com GCC - Conteúdo * Provê funcionalidades para criação, recuperação e atualização de conteúdo no repositório GCC * * OpenAPI spec version: 1.2.0 * * * 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 cgcc.integracao.conteudo; 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.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; import java.io.IOException; /** * Contempla as informações a serem enviadas na requisição de exclusão de conteúdo, através de seu ID, no repositório GCC */ @ApiModel(description = "Contempla as informações a serem enviadas na requisição de exclusão de conteúdo, através de seu ID, no repositório GCC") @javax.annotation.Generated(value = "io.swagger.codegen.languages.JavaClientCodegen", date = "2020-06-02T20:33:16.213Z") public class RequestExcluirPorId { @SerializedName("centroCusto") private String centroCusto = null; @SerializedName("canal") private String canal = null; @SerializedName("usuario") private String usuario = null; @SerializedName("senha") private String senha = null; @SerializedName("objectStore") private String objectStore = null; @SerializedName("id") private String id = null; public RequestExcluirPorId centroCusto(String centroCusto) { this.centroCusto = centroCusto; return this; } /** * Centro de custo que esta executando a requisição * @return centroCusto **/ @ApiModelProperty(required = true, value = "Centro de custo que esta executando a requisição") public String getCentroCusto() { return centroCusto; } public void setCentroCusto(String centroCusto) { this.centroCusto = centroCusto; } public RequestExcluirPorId canal(String canal) { this.canal = canal; return this; } /** * Canal que está executando a requisição * @return canal **/ @ApiModelProperty(required = true, value = "Canal que está executando a requisição") public String getCanal() { return canal; } public void setCanal(String canal) { this.canal = canal; } public RequestExcluirPorId usuario(String usuario) { this.usuario = usuario; return this; } /** * Usuário para autenticação no repositório GCC (o usuário deve estar criptografado no padrão GCC) * @return usuario **/ @ApiModelProperty(required = true, value = "Usuário para autenticação no repositório GCC (o usuário deve estar criptografado no padrão GCC)") public String getUsuario() { return usuario; } public void setUsuario(String usuario) { this.usuario = usuario; } public RequestExcluirPorId senha(String senha) { this.senha = senha; return this; } /** * Senha para autenticação no repositório GCC (a senha deve estar criptografada no padrão GCC) * @return senha **/ @ApiModelProperty(required = true, value = "Senha para autenticação no repositório GCC (a senha deve estar criptografada no padrão GCC)") public String getSenha() { return senha; } public void setSenha(String senha) { this.senha = senha; } public RequestExcluirPorId objectStore(String objectStore) { this.objectStore = objectStore; return this; } /** * ObjectStore onde será executada a operação no repositório * @return objectStore **/ @ApiModelProperty(example = "OS-CAMBIO", required = true, value = "ObjectStore onde será executada a operação no repositório") public String getObjectStore() { return objectStore; } public void setObjectStore(String objectStore) { this.objectStore = objectStore; } public RequestExcluirPorId id(String id) { this.id = id; return this; } /** * ID do conteúdo * @return id **/ @ApiModelProperty(example = "{6032036D-0000-C13A-9A1C-4651367FC6E7}", required = true, value = "ID do conteúdo") public String getId() { return id; } public void setId(String id) { this.id = id; } @Override public boolean equals(java.lang.Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } RequestExcluirPorId requestExcluirPorId = (RequestExcluirPorId) o; return Objects.equals(this.centroCusto, requestExcluirPorId.centroCusto) && Objects.equals(this.canal, requestExcluirPorId.canal) && Objects.equals(this.usuario, requestExcluirPorId.usuario) && Objects.equals(this.senha, requestExcluirPorId.senha) && Objects.equals(this.objectStore, requestExcluirPorId.objectStore) && Objects.equals(this.id, requestExcluirPorId.id); } @Override public int hashCode() { return Objects.hash(centroCusto, canal, usuario, senha, objectStore, id); } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("class RequestExcluirPorId {\n"); sb.append(" centroCusto: ").append(toIndentedString(centroCusto)).append("\n"); sb.append(" canal: ").append(toIndentedString(canal)).append("\n"); sb.append(" usuario: ").append(toIndentedString(usuario)).append("\n"); sb.append(" senha: ").append(toIndentedString(senha)).append("\n"); sb.append(" objectStore: ").append(toIndentedString(objectStore)).append("\n"); sb.append(" id: ").append(toIndentedString(id)).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 "); } }
package io.anemos.protobeam.convert; import com.google.protobuf.Descriptors; import com.google.protobuf.Message; import org.apache.beam.sdk.schemas.Schema; public class SchemaProtoToBeamSQL { SchemaProtoContext context = new SchemaProtoContext(); public <T extends Message> Schema getSchema(Class<T> messageClass) { Descriptors.Descriptor descriptor = null; try { descriptor = (Descriptors.Descriptor) messageClass.getMethod("getDescriptor").invoke(null); } catch (Exception e) { throw new RuntimeException("ProtoBeam: Unable to get descriptor from Message. Maybe the class is not a Message?", e); } return getSchema(descriptor); } public Schema getSchema(Descriptors.Descriptor descriptor) { Schema.Builder schemaBuilder = new Schema.Builder(); for (Descriptors.FieldDescriptor fieldDescriptor : descriptor.getFields()) { schemaBuilder.addField(convertField(fieldDescriptor)); } return schemaBuilder.build(); } private Schema.FieldType convertMessage(Descriptors.FieldDescriptor fieldDescriptor) { Schema.FieldType fieldType = Schema.FieldType.row(getSchema(fieldDescriptor.getMessageType())); return fieldType; } private Schema.Field convertField(Descriptors.FieldDescriptor fieldDescriptor) { Schema.FieldType fieldType = null; boolean isNullable = false; if (context.isPrimitiveField(fieldDescriptor)) { fieldType = extractFieldType(fieldDescriptor); if (context.isTimestamp(fieldDescriptor) || context.isDecimal(fieldDescriptor)) { isNullable = true; } } else if (context.isWrapper(fieldDescriptor)) { Descriptors.FieldDescriptor valueFieldDescriptor = fieldDescriptor.getMessageType().findFieldByName("value"); fieldType = extractFieldType(valueFieldDescriptor); return Schema.Field.nullable(fieldDescriptor.getName(), fieldType); } else { fieldType = convertMessage(fieldDescriptor); isNullable = true; } if (fieldDescriptor.isRepeated()) { fieldType = Schema.FieldType.array(fieldType); } if (fieldType == null) { throw new RuntimeException(); } String fieldName = fieldDescriptor.getName(); if (context.hasRenameTo(fieldDescriptor)) { fieldName = context.getRenameTo(fieldDescriptor); } return Schema.Field.of(fieldName, fieldType).withNullable(isNullable); } private Schema.FieldType extractFieldType(Descriptors.FieldDescriptor fieldDescriptor) { if (context.isTimestamp(fieldDescriptor)) return Schema.FieldType.DATETIME; if (context.isDecimal(fieldDescriptor)) return Schema.FieldType.DECIMAL; Descriptors.FieldDescriptor.Type fieldType = fieldDescriptor.getType(); switch (fieldType) { case DOUBLE: return Schema.FieldType.DOUBLE; case FLOAT: return Schema.FieldType.FLOAT; case INT64: case UINT64: case SINT64: case FIXED64: case SFIXED64: return Schema.FieldType.INT64; case INT32: case FIXED32: case UINT32: case SFIXED32: case SINT32: return Schema.FieldType.INT32; case BOOL: return Schema.FieldType.BOOLEAN; case STRING: return Schema.FieldType.STRING; case BYTES: return Schema.FieldType.BYTES; case ENUM: return Schema.FieldType.STRING; case MESSAGE: return null; } throw new RuntimeException("Field type not matched."); } }
package org.greenscape.core.impl.config.json; public class WebletConfig extends ResourceConfig { public String name; public String title; public String icon; public Boolean instanceable; public String viewURL; public String helpURL; public String loadJS; public String loadCSS; @Override public String toString() { StringBuilder string = new StringBuilder(); string.append("webletResource={").append("name=").append(name).append(",title=").append(title).append(",icon=") .append(icon).append(",instanceable=").append(instanceable).append(",viewURL=").append(viewURL) .append(",helpURL=").append(helpURL).append(",loadJS=").append(loadJS).append(",loadCSS=") .append(loadCSS).append(",permissions=").append(permissions).append("}"); return string.toString(); } }
/* * Copyright 2020 StreamThoughts. * * 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 io.streamthoughts.kafka.specs.acl; import io.streamthoughts.kafka.specs.resources.ClusterResource; import org.apache.kafka.common.acl.AclOperation; import org.apache.kafka.common.acl.AclPermissionType; import org.apache.kafka.common.resource.PatternType; import org.apache.kafka.common.resource.ResourceType; import java.util.Objects; public class AclRule implements ClusterResource { private final String principalType; private final String principalName; private final String resourcePattern ; private final PatternType patternType ; private final ResourceType resourceType; private final AclOperation operation; private final AclPermissionType permission; private final String host; public static AclRuleBuilder newBuilder() { return new AclRuleBuilder(); } /** * Creates a new {@link AclRule} instance. */ AclRule(final String principalType, final String principalName, final String resourcePattern, final PatternType patternType, final ResourceType resourceType, final AclPermissionType permission, final AclOperation operation, final String host) { Objects.requireNonNull(principalName, "principalName cannot be null"); Objects.requireNonNull(resourcePattern, "resourcePattern cannot be null"); Objects.requireNonNull(patternType, "patternType cannot be null"); Objects.requireNonNull(permission, "permission cannot be null"); Objects.requireNonNull(resourceType, "resourceType cannot be null"); Objects.requireNonNull(operation, "operation cannot be null"); Objects.requireNonNull(host, "host cannot be null"); this.principalType = principalType; this.principalName = principalName; this.resourcePattern = resourcePattern; this.patternType = patternType; this.permission = permission; this.resourceType = resourceType; this.operation = operation; this.host = host; } public String principalName() { return principalName; } public AclPermissionType permission() { return permission; } public String principal() { return this.principalType + ":" + this.principalName; } public String principalType() { return principalType; } public String resourcePattern() { return resourcePattern; } public PatternType patternType() { return patternType; } public ResourceType resourceType() { return resourceType; } public AclOperation operation() { return operation; } public String host() { return host; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; AclRule rule = (AclRule) o; return Objects.equals(principalType, rule.principalType) && Objects.equals(principalName, rule.principalName) && Objects.equals(resourcePattern, rule.resourcePattern) && patternType == rule.patternType && resourceType == rule.resourceType && operation == rule.operation && permission == rule.permission && Objects.equals(host, rule.host); } @Override public int hashCode() { return Objects.hash(principalType, principalName, resourcePattern, patternType, resourceType, operation, permission, host); } @Override public String toString() { return "AclRule{" + "principalType=" + principalType + ", principalName='" + principalName + '\'' + ", resourcePattern='" + resourcePattern + '\'' + ", patternType='" + patternType + '\'' + ", resourceType=" + resourceType + ", operation=" + operation + ", permission=" + permission + ", host='" + host + '\'' + '}'; } }
package com.yueyue.seeweather.common.utils; import android.app.Activity; import android.content.Context; import android.graphics.Color; import android.support.annotation.NonNull; import android.support.v7.widget.Toolbar; import android.view.View; import android.view.ViewGroup; import android.view.WindowManager; public class StatusBarUtil { public static void setImmersiveStatusBar(@NonNull Activity activity) { if (SdkUtil.sdkVersionGe21()) { activity.getWindow().setStatusBarColor(Color.TRANSPARENT); } if (SdkUtil.sdkVersionEq(19)) { activity.getWindow().setFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS, WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS); } activity.getWindow() .getDecorView() .setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_STABLE | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN); } public static void setImmersiveStatusBarToolbar(@NonNull Toolbar toolbar, Context context) { ViewGroup.MarginLayoutParams toolLayoutParams = (ViewGroup.MarginLayoutParams) toolbar.getLayoutParams(); toolLayoutParams.height = EnvUtil.getStatusBarHeight() + EnvUtil.getActionBarSize(context); toolbar.setLayoutParams(toolLayoutParams); toolbar.setPadding(0, EnvUtil.getStatusBarHeight(), 0, 0); toolbar.requestLayout(); } }
// Copyright 2017 The Nomulus Authors. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package google.registry.tools; import static com.google.common.base.Preconditions.checkArgument; import static google.registry.model.registry.Registries.getTldsOfType; import static google.registry.util.CollectionUtils.isNullOrEmpty; import com.beust.jcommander.Parameter; import com.beust.jcommander.Parameters; import com.google.common.base.Joiner; import com.google.common.collect.ImmutableMap; import google.registry.model.registry.Registry.TldType; import google.registry.tools.server.ListDomainsAction; import java.util.List; /** Command to list all second-level domains on specified TLD(s). */ @Parameters(separators = " =", commandDescription = "List domains on TLD(s).") final class ListDomainsCommand extends ListObjectsCommand { @Parameter( names = {"-t", "--tld", "--tlds"}, description = "Comma-delimited list of TLDs to list domains on; defaults to all REAL TLDs.") private List<String> tlds; @Parameter( names = {"-n", "--limit"}, description = "Max number of domains to list, most recent first; defaults to no limit." ) private int maxDomains = Integer.MAX_VALUE; @Override String getCommandPath() { return ListDomainsAction.PATH; } /** Returns a map of parameters to be sent to the server (in addition to the usual ones). */ @Override ImmutableMap<String, Object> getParameterMap() { // Default to all REAL TLDs if not specified. if (isNullOrEmpty(tlds)) { tlds = getTldsOfType(TldType.REAL).asList(); } String tldsParam = Joiner.on(',').join(tlds); checkArgument(tldsParam.length() < 1024, "Total length of TLDs is too long for URL parameter"); return ImmutableMap.of("tlds", tldsParam, "limit", maxDomains); } }
/* * Copyright (C) 2016 Red Hat, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.syndesis.connector.odata.meta; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import org.apache.camel.CamelContext; import org.apache.camel.component.extension.MetaDataExtension; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.module.jsonSchema.JsonSchema; import com.fasterxml.jackson.module.jsonSchema.factories.JsonSchemaFactory; import com.fasterxml.jackson.module.jsonSchema.types.ArraySchema; import com.fasterxml.jackson.module.jsonSchema.types.ContainerTypeSchema; import com.fasterxml.jackson.module.jsonSchema.types.ObjectSchema; import io.syndesis.common.model.DataShape; import io.syndesis.common.model.DataShapeKinds; import io.syndesis.common.util.Json; import io.syndesis.connector.odata.ODataConstants; import io.syndesis.connector.odata.meta.ODataMetadata.PropertyMetadata; import io.syndesis.connector.odata.meta.ODataMetadata.PropertyMetadata.TypeClass; import io.syndesis.connector.support.verifier.api.ComponentMetadataRetrieval; import io.syndesis.connector.support.verifier.api.PropertyPair; import io.syndesis.connector.support.verifier.api.SyndesisMetadata; public class ODataMetaDataRetrieval extends ComponentMetadataRetrieval implements ODataConstants { private JsonSchemaFactory factory = new JsonSchemaFactory(); @Override protected MetaDataExtension resolveMetaDataExtension(CamelContext context, Class<? extends MetaDataExtension> metaDataExtensionClass, String componentId, String actionId) { return new ODataMetaDataExtension(context); } @SuppressWarnings({"PMD"}) @Override protected SyndesisMetadata adapt(CamelContext context, String componentId, String actionId, Map<String, Object> properties, MetaDataExtension.MetaData metadata) { ODataMetadata odataMetadata = (ODataMetadata) metadata.getPayload(); Map<String, List<PropertyPair>> enrichedProperties = new HashMap<>(); if (odataMetadata.hasEntityNames()) { List<PropertyPair> resourcesResult = new ArrayList<>(); odataMetadata.getEntityNames().stream().forEach( t -> resourcesResult.add(new PropertyPair(t, t)) ); enrichedProperties.put(RESOURCE_PATH, resourcesResult); } // // Do things differently depending on which action is being sought // if (actionId.endsWith(Methods.READ.connectorId())) { return genReadDataShape(odataMetadata, properties, enrichedProperties); } else if(actionId.endsWith(Methods.CREATE.connectorId())) { return genCreateDataShape(odataMetadata, enrichedProperties); } else if (actionId.endsWith(Methods.DELETE.connectorId())) { return genDeleteDataShape(enrichedProperties, actionId); } else if (actionId.endsWith(Methods.PATCH.connectorId())) { return genPatchDataShape(odataMetadata, enrichedProperties, actionId); } return SyndesisMetadata.of(enrichedProperties); } private SyndesisMetadata createSyndesisMetadata( Map<String, List<PropertyPair>> enrichedProperties, DataShape.Builder inDataShapeBuilder, DataShape.Builder outDataShapeBuilder) { return new SyndesisMetadata(enrichedProperties, inDataShapeBuilder.build(), outDataShapeBuilder.build()); } private ObjectSchema createEntitySchema() { ObjectSchema entitySchema = new ObjectSchema(); entitySchema.setTitle("ODATA_ENTITY_PROPERTIES"); entitySchema.set$schema("http://json-schema.org/schema#"); return entitySchema; } private void populateEntitySchema(ODataMetadata odataMetadata, ObjectSchema entitySchema) { if (! odataMetadata.hasEntityProperties()) { return; } for (PropertyMetadata entityProperty : odataMetadata.getEntityProperties()) { JsonSchema propSchema = schemaFor(entityProperty); boolean required = propSchema.getRequired(); entitySchema.putProperty(entityProperty.getName(), propSchema); // // Workaround oddity where ObjectSchema#putProperty sets required to true // propSchema.setRequired(required); } } private boolean isSplit(Map<String, Object> properties) { Object splitProp = properties.get(SPLIT_RESULT); return splitProp != null && Boolean.parseBoolean(splitProp.toString()); } private String serializeSpecification(ContainerTypeSchema schema) { try { return Json.writer().writeValueAsString(schema); } catch (JsonProcessingException e) { throw new IllegalStateException("Unable to serialize schema", e); } } private void applyEntitySchemaSpecification(ContainerTypeSchema schema, DataShape.Builder dataShapeBuilder) { final String specification = serializeSpecification(schema); dataShapeBuilder .kind(DataShapeKinds.JSON_SCHEMA) .name("Entity Schema") .description("Schema of OData result entities") .specification(specification); if (schema instanceof ArraySchema) { dataShapeBuilder.putMetadata("variant", "collection"); } } @SuppressWarnings("PMD") private JsonSchema schemaFor(PropertyMetadata propertyMetadata) { JsonSchema schema; TypeClass type = propertyMetadata.getType(); switch (type) { case STRING: schema = factory.stringSchema(); break; case BOOLEAN: schema = factory.booleanSchema(); break; case NUMBER: schema = factory.numberSchema(); break; case OBJECT: schema = factory.objectSchema(); break; default: schema = factory.anySchema(); } if (propertyMetadata.isArray()) { ArraySchema arraySchema = factory.arraySchema(); arraySchema.setItemsSchema(schema); schema = arraySchema; } schema.setRequired(propertyMetadata.isRequired()); return schema; } /* * READ * - In has NO shape * - Out has the json entity schema */ private SyndesisMetadata genReadDataShape(ODataMetadata odataMetadata, Map<String, Object> basicProperties, Map<String, List<PropertyPair>> enrichedProperties) { ObjectSchema entitySchema = createEntitySchema(); DataShape.Builder inDataShapeBuilder = new DataShape.Builder() .kind(DataShapeKinds.NONE); DataShape.Builder outDataShapeBuilder = new DataShape.Builder() .kind(DataShapeKinds.NONE) .type(entitySchema.getTitle()); populateEntitySchema(odataMetadata, entitySchema); boolean isSplit = isSplit(basicProperties); if (! entitySchema.getProperties().isEmpty()) { if (isSplit) { // // A split will mean that the schema is no longer an array schema // applyEntitySchemaSpecification(entitySchema, outDataShapeBuilder); } else { ArraySchema collectionSchema = new ArraySchema(); collectionSchema.set$schema("http://json-schema.org/schema#"); collectionSchema.setItemsSchema(entitySchema); applyEntitySchemaSpecification(collectionSchema, outDataShapeBuilder); } } return createSyndesisMetadata(enrichedProperties, inDataShapeBuilder, outDataShapeBuilder); } /* *CREATE * - In has the json entity schema * - Out has the same json entity schema (since create returns the new entity) */ private SyndesisMetadata genCreateDataShape(ODataMetadata odataMetadata, Map<String, List<PropertyPair>> enrichedProperties) { ObjectSchema entitySchema = createEntitySchema(); populateEntitySchema(odataMetadata, entitySchema); DataShape.Builder inDataShapeBuilder = new DataShape.Builder() .kind(DataShapeKinds.NONE) .type(entitySchema.getTitle()); DataShape.Builder outDataShapeBuilder = new DataShape.Builder() .kind(DataShapeKinds.NONE) .type(entitySchema.getTitle()); if (! entitySchema.getProperties().isEmpty()) { applyEntitySchemaSpecification(entitySchema, inDataShapeBuilder); applyEntitySchemaSpecification(entitySchema, outDataShapeBuilder); } return createSyndesisMetadata(enrichedProperties, inDataShapeBuilder, outDataShapeBuilder); } /* * PATCH * - In has the json entity schema * - Out has the json instance representing a status outcome */ private SyndesisMetadata genPatchDataShape(ODataMetadata odataMetadata, Map<String, List<PropertyPair>> enrichedProperties, String actionId) { ObjectSchema entitySchema = createEntitySchema(); populateEntitySchema(odataMetadata, entitySchema); // // Need to add a KEY_PREDICATE to the json schema to allow identification // of the entity to be patched. // entitySchema.putProperty(KEY_PREDICATE, factory.stringSchema()); DataShape.Builder inDataShapeBuilder = new DataShape.Builder() .kind(DataShapeKinds.NONE) .type(entitySchema.getTitle()) .name("Entity Properties"); if (! entitySchema.getProperties().isEmpty()) { applyEntitySchemaSpecification(entitySchema, inDataShapeBuilder); } DataShape.Builder outDataShapeBuilder = new DataShape.Builder() .kind(DataShapeKinds.JSON_INSTANCE) .description("OData " + actionId) .name(actionId); return createSyndesisMetadata(enrichedProperties, inDataShapeBuilder, outDataShapeBuilder); } /* * DELETE * - In has the json object with the key predicate in it * - Out has the json instance representing a status outcome */ private SyndesisMetadata genDeleteDataShape(Map<String, List<PropertyPair>> enrichedProperties, String actionId) { // // Need to add a KEY_PREDICATE to the json schema to allow identification // of the entity to be patched. // ObjectSchema entitySchema = createEntitySchema(); entitySchema.putProperty(KEY_PREDICATE, factory.stringSchema()); DataShape.Builder inDataShapeBuilder = new DataShape.Builder() .kind(DataShapeKinds.JSON_SCHEMA) .type(entitySchema.getTitle()) .name("Entity Properties") .specification(serializeSpecification(entitySchema)); DataShape.Builder outDataShapeBuilder = new DataShape.Builder() .kind(DataShapeKinds.JSON_INSTANCE) .description("OData " + actionId) .name(actionId); return createSyndesisMetadata(enrichedProperties, inDataShapeBuilder, outDataShapeBuilder); } }
/* * 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 dungeon.souls.modding.tool.ui; import org.junit.After; import org.junit.AfterClass; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; import static org.junit.Assert.*; /** * * @author Diogo */ public class HelpFrameIT { public HelpFrameIT() { } @BeforeClass public static void setUpClass() { } @AfterClass public static void tearDownClass() { } @Before public void setUp() { } @After public void tearDown() { } @Test public void testSomeMethod() { // TODO review the generated test code and remove the default call to fail. fail("The test case is a prototype."); } }
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.rocketmq.client.latency; import java.util.Collections; import java.util.Enumeration; import java.util.LinkedList; import java.util.List; import java.util.concurrent.ConcurrentHashMap; import org.apache.rocketmq.client.common.ThreadLocalIndex; public class LatencyFaultToleranceImpl implements LatencyFaultTolerance<String> { private final ConcurrentHashMap<String, FaultItem> faultItemTable = new ConcurrentHashMap<String, FaultItem>(16); private final ThreadLocalIndex whichItemWorst = new ThreadLocalIndex(); @Override public void updateFaultItem(final String name, final long currentLatency, final long notAvailableDuration) { FaultItem old = this.faultItemTable.get(name); if (null == old) { final FaultItem faultItem = new FaultItem(name); faultItem.setCurrentLatency(currentLatency); //当前时间加延后 notAvailableDuration 这么长时间不可用 faultItem.setStartTimestamp(System.currentTimeMillis() + notAvailableDuration); old = this.faultItemTable.putIfAbsent(name, faultItem); if (old != null) { old.setCurrentLatency(currentLatency); old.setStartTimestamp(System.currentTimeMillis() + notAvailableDuration); } } else { //有的话 更新 old.setCurrentLatency(currentLatency); old.setStartTimestamp(System.currentTimeMillis() + notAvailableDuration); } } @Override public boolean isAvailable(final String name) { final FaultItem faultItem = this.faultItemTable.get(name); if (faultItem != null) { return faultItem.isAvailable(); } return true; } @Override public void remove(final String name) { this.faultItemTable.remove(name); } @Override public String pickOneAtLeast() { final Enumeration<FaultItem> elements = this.faultItemTable.elements(); List<FaultItem> tmpList = new LinkedList<FaultItem>(); while (elements.hasMoreElements()) { final FaultItem faultItem = elements.nextElement(); tmpList.add(faultItem); } if (!tmpList.isEmpty()) { Collections.shuffle(tmpList); Collections.sort(tmpList); final int half = tmpList.size() / 2; if (half <= 0) { return tmpList.get(0).getName(); } else { final int i = this.whichItemWorst.getAndIncrement() % half; return tmpList.get(i).getName(); } } return null; } @Override public String toString() { return "LatencyFaultToleranceImpl{" + "faultItemTable=" + faultItemTable + ", whichItemWorst=" + whichItemWorst + '}'; } /** * 计算出来的延迟值+加上本次消息的延迟值,设置 为FaultItem 的 startTimestamp,表示当前时间必须大于该 startTimestamp 时 * 该 broker 才重新参与 MessageQueue 的负载。 */ class FaultItem implements Comparable<FaultItem> { private final String name; private volatile long currentLatency; private volatile long startTimestamp; public FaultItem(final String name) { this.name = name; } @Override public int compareTo(final FaultItem other) { if (this.isAvailable() != other.isAvailable()) { if (this.isAvailable()) return -1; if (other.isAvailable()) return 1; } if (this.currentLatency < other.currentLatency) return -1; else if (this.currentLatency > other.currentLatency) { return 1; } if (this.startTimestamp < other.startTimestamp) return -1; else if (this.startTimestamp > other.startTimestamp) { return 1; } return 0; } public boolean isAvailable() { return (System.currentTimeMillis() - startTimestamp) >= 0; } @Override public int hashCode() { int result = getName() != null ? getName().hashCode() : 0; result = 31 * result + (int) (getCurrentLatency() ^ (getCurrentLatency() >>> 32)); result = 31 * result + (int) (getStartTimestamp() ^ (getStartTimestamp() >>> 32)); return result; } @Override public boolean equals(final Object o) { if (this == o) return true; if (!(o instanceof FaultItem)) return false; final FaultItem faultItem = (FaultItem) o; if (getCurrentLatency() != faultItem.getCurrentLatency()) return false; if (getStartTimestamp() != faultItem.getStartTimestamp()) return false; return getName() != null ? getName().equals(faultItem.getName()) : faultItem.getName() == null; } @Override public String toString() { return "FaultItem{" + "name='" + name + '\'' + ", currentLatency=" + currentLatency + ", startTimestamp=" + startTimestamp + '}'; } public String getName() { return name; } public long getCurrentLatency() { return currentLatency; } public void setCurrentLatency(final long currentLatency) { this.currentLatency = currentLatency; } public long getStartTimestamp() { return startTimestamp; } public void setStartTimestamp(final long startTimestamp) { this.startTimestamp = startTimestamp; } } }
package net.bartzz.pexmanager.listener; import org.bukkit.entity.Player; import org.bukkit.event.EventHandler; import org.bukkit.event.EventPriority; import org.bukkit.event.Listener; import org.bukkit.event.player.PlayerJoinEvent; import net.bartzz.pexmanager.data.PermissionPlayer; public class JoinListener implements Listener { @EventHandler (priority = EventPriority.HIGH) public void onJoin(PlayerJoinEvent e) { Player player = e.getPlayer(); PermissionPlayer pPlayer = PermissionPlayer.getPermissionPlayer(player.getUniqueId()); if(pPlayer == null) { pPlayer = new PermissionPlayer(player.getUniqueId(), player.getName(), null, null); } } }
package com.sdl.demo.extjs3.form; import com.sdl.selenium.extjs3.button.Button; import com.sdl.selenium.extjs3.button.DownloadButton; import com.sdl.selenium.extjs3.button.UploadButton; import com.sdl.selenium.extjs3.form.CheckBox; import com.sdl.selenium.extjs3.panel.Panel; public class SimpleForm extends Panel { public SimpleForm(String title) { super(title); } public SimpleForm() { this("Simple Form"); } public UploadButton uploadButton = new UploadButton(this, "Browse"); public DownloadButton downloadButton = new DownloadButton(this, "Download"); public DownloadButton downloadWithSpacesButton = new DownloadButton(this, "Download with spaces"); public DownloadButton downloadFileButton = new DownloadButton(this, "Download File"); public CheckBox rightCheckBox = new CheckBox(this).setLabel("CatRight").setLabelPosition("//preceding-sibling::"); public CheckBox leftCheckBox = new CheckBox(this).setLabel("CatLeft:"); public Button cancelButton = new Button(this, "Cancel"); }
package p; public class A { class Inner1 { public Inner1(int param) { } } public void doit(final int a, final String param) { Object o = new Inner1(a) { public void m1(String s2) { String s3 = param + s2; } }; } }
package bzh.medek.server.json.admin.user; public class JsonAdminUser { private Integer id; private String login; private String email; private String password; private String confpassword; public JsonAdminUser() { super(); } public JsonAdminUser(Integer id, String login, String email) { super(); this.id = id; this.login = login; this.email = email; } public JsonAdminUser(Integer id, String login, String email, String password) { super(); this.id = id; this.login = login; this.email = email; this.password = password; } public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getLogin() { return login; } public void setLogin(String login) { this.login = login; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } public String getConfpassword() { return confpassword; } public void setConfpassword(String confpassword) { this.confpassword = confpassword; } }
package it.smartcommunitylab.cartella.asl.model.ext; public class ProfessorClassInfoTn { private String extId; private String origin; private String classroom; private Corso course; private String datefrom; private String dateto; private String extIdInstitute; private String schoolyear; private Teacher teacher; public String getExtId() { return extId; } public String getExtIdInstitute() { return extIdInstitute; } public void setExtIdInstitute(String extIdInstitute) { this.extIdInstitute = extIdInstitute; } public void setExtId(String extId) { this.extId = extId; } public String getOrigin() { return origin; } public void setOrigin(String origin) { this.origin = origin; } public String getClassroom() { return classroom; } public void setClassroom(String classroom) { this.classroom = classroom; } public Corso getCourse() { return course; } public void setCourse(Corso course) { this.course = course; } public String getDatefrom() { return datefrom; } public void setDatefrom(String datefrom) { this.datefrom = datefrom; } public String getDateto() { return dateto; } public void setDateto(String dateto) { this.dateto = dateto; } public String getSchoolyear() { return schoolyear; } public void setSchoolyear(String schoolyear) { this.schoolyear = schoolyear; } public Teacher getTeacher() { return teacher; } public void setTeacher(Teacher teacher) { this.teacher = teacher; } }
/* * * Copyright (c) Microsoft. All rights reserved. * Licensed under the MIT license. * * Project Oxford: http://ProjectOxford.ai * * Project Oxford Mimicker Alarm Github: * https://github.com/Microsoft/ProjectOxford-Apps-MimickerAlarm * * Copyright (c) Microsoft Corporation * All rights reserved. * * MIT License: * 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 com.microsoft.mimickeralarm.model; import android.content.ContentValues; import android.content.Context; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import com.microsoft.mimickeralarm.database.AlarmCursorWrapper; import com.microsoft.mimickeralarm.database.AlarmDatabaseHelper; import com.microsoft.mimickeralarm.database.AlarmDbSchema.AlarmTable; import java.util.ArrayList; import java.util.List; import java.util.UUID; /** * This class is a singleton which represents the current list of alarms. This is the class via * which we interact with the database. This class enables us to query, update and delete alarm * information from the database. */ public class AlarmList { private static final String ORDER_BY = AlarmTable.Columns.HOUR + ", " + AlarmTable.Columns.MINUTE; private static AlarmList sAlarmList; private Context mContext; private SQLiteDatabase mDatabase; private AlarmList(Context context) { mContext = context.getApplicationContext(); mDatabase = new AlarmDatabaseHelper(mContext) .getWritableDatabase(); } public static AlarmList get(Context context) { if (sAlarmList == null) { sAlarmList = new AlarmList(context); } return sAlarmList; } private static ContentValues populateContentValues(Alarm alarm) { ContentValues values = new ContentValues(); values.put(AlarmTable.Columns.UUID, alarm.getId().toString()); values.put(AlarmTable.Columns.TITLE, alarm.getTitle()); values.put(AlarmTable.Columns.ENABLED, alarm.isEnabled() ? 1 : 0); values.put(AlarmTable.Columns.HOUR, alarm.getTimeHour()); values.put(AlarmTable.Columns.MINUTE, alarm.getTimeMinute()); values.put(AlarmTable.Columns.TONE, alarm.getAlarmTone() != null ? alarm.getAlarmTone().toString() : ""); String repeatingDays = ""; for (int i = 0; i < 7; ++i) { repeatingDays += alarm.getRepeatingDay(i) + ","; } values.put(AlarmTable.Columns.DAYS, repeatingDays); values.put(AlarmTable.Columns.VIBRATE, alarm.shouldVibrate()); values.put(AlarmTable.Columns.TONGUE_TWISTER, alarm.isTongueTwisterEnabled()); values.put(AlarmTable.Columns.COLOR_CAPTURE, alarm.isColorCaptureEnabled()); values.put(AlarmTable.Columns.EXPRESS_YOURSELF, alarm.isExpressYourselfEnabled()); values.put(AlarmTable.Columns.NEW, alarm.isNew() ? 1 : 0); values.put(AlarmTable.Columns.SNOOZED, alarm.isSnoozed() ? 1 : 0); values.put(AlarmTable.Columns.SNOOZED_HOUR, alarm.getSnoozeHour()); values.put(AlarmTable.Columns.SNOOZED_MINUTE, alarm.getSnoozeMinute()); values.put(AlarmTable.Columns.SNOOZED_SECONDS, alarm.getSnoozeSeconds()); return values; } public void addAlarm(Alarm alarm) { ContentValues values = populateContentValues(alarm); mDatabase.insert(AlarmTable.NAME, null, values); } public List<Alarm> getAlarms() { List<Alarm> alarms = new ArrayList<>(); AlarmCursorWrapper cursor = queryAlarms(null, null, ORDER_BY); cursor.moveToFirst(); while (!cursor.isAfterLast()) { alarms.add(cursor.getAlarm()); cursor.moveToNext(); } cursor.close(); return alarms; } public Alarm getAlarm(UUID id) { AlarmCursorWrapper cursor = queryAlarms( AlarmTable.Columns.UUID + " = ?", new String[]{id.toString()}, null ); try { if (cursor.getCount() == 0) { return null; } cursor.moveToFirst(); return cursor.getAlarm(); } finally { cursor.close(); } } public void updateAlarm(Alarm alarm) { ContentValues values = populateContentValues(alarm); mDatabase.update(AlarmTable.NAME, values, AlarmTable.Columns.UUID + " = ?", new String[]{alarm.getId().toString()}); } public void deleteAlarm(Alarm alarm) { mDatabase.delete(AlarmTable.NAME, AlarmTable.Columns.UUID + " = ?", new String[] { alarm.getId().toString() }); } private AlarmCursorWrapper queryAlarms(String queryClause, String[] queryArgs, String orderBy) { Cursor cursor = mDatabase.query( AlarmTable.NAME, null, // gets all columns queryClause, queryArgs, null, null, orderBy ); return new AlarmCursorWrapper(cursor); } }
/** Copyright (c) 2017 HF Robotics (http://www.hfrobots.com) 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 com.hfrobots.tnt.season1819; import android.util.Log; import com.ftc9929.corelib.control.DebouncedButton; import com.ftc9929.corelib.control.LowPassFilteredRangeInput; import com.ftc9929.corelib.control.NinjaGamePad; import com.ftc9929.corelib.control.OnOffButton; import com.ftc9929.corelib.control.ParametricScaledRangeInput; import com.ftc9929.corelib.control.RangeInput; import com.ftc9929.corelib.control.RangeInputButton; import com.ftc9929.corelib.state.State; import com.hfrobots.tnt.corelib.drive.ExtendedDcMotor; import com.hfrobots.tnt.corelib.drive.NinjaMotor; import com.qualcomm.hardware.bosch.BNO055IMU; import com.qualcomm.hardware.lynx.LynxEmbeddedIMU; import com.qualcomm.robotcore.eventloop.opmode.OpMode; import com.qualcomm.robotcore.hardware.DcMotor; import com.qualcomm.robotcore.hardware.DcMotorEx; import com.qualcomm.robotcore.hardware.DcMotorSimple; import com.qualcomm.robotcore.hardware.DigitalChannel; import com.qualcomm.robotcore.hardware.Servo; import com.qualcomm.robotcore.hardware.VoltageSensor; import java.util.Iterator; import java.util.concurrent.TimeUnit; import static com.hfrobots.tnt.corelib.Constants.LOG_TAG; public abstract class RoverRuckusHardware extends OpMode { protected float throttleGain = 0.7F; protected float throttleExponent = 5; // MUST BE AN ODD NUMBER! protected float throttleDeadband = 0; protected boolean imuNeeded = true; /** * Indicate whether a message is a available to the class user. */ private boolean warningGenerated = false; /** * Store a message to the user if one has been generated. */ private String warningMessage; protected NinjaGamePad driversGamepad; protected NinjaGamePad operatorsGamepad; // Drivebase protected ExtendedDcMotor leftFrontDriveMotor; protected ExtendedDcMotor rightFrontDriveMotor; protected ExtendedDcMotor leftRearDriveMotor; protected ExtendedDcMotor rightRearDriveMotor; protected MecanumDrive mecanumDrive; protected LynxEmbeddedIMU imu; protected VoltageSensor voltageSensor; protected DcMotor acDcMotor; protected DcMotor collectorDeployMotor; protected DcMotor collectorSweepMotor; protected RangeInput collectorDeployInput; protected RangeInput collectorSweepInput; protected DigitalChannel acDcLimitSwitch; protected DigitalChannel collectorStowLimitSwitch; protected DigitalChannel scoreBoxReadyToLoadLimitSwitch; protected LinearActuator ascenderDescender; protected RangeInput driverLeftStickX; protected RangeInput driverLeftStickY; protected RangeInput driverRightStickX; protected RangeInput driverRightStickY; protected RangeInput driveForwardReverse; protected RangeInput driveStrafe; protected RangeInput driveRotate; protected DebouncedButton driverDpadUp; protected DebouncedButton driverDpadDown; protected DebouncedButton driverDpadLeft; protected DebouncedButton driverDpadRight; protected DebouncedButton driverXBlueButton; protected DebouncedButton driverBRedButton; protected DebouncedButton driverYYellowButton; protected DebouncedButton driverAGreenButton; protected DebouncedButton driverRightBumper; protected DebouncedButton driverLeftBumper; protected DebouncedButton lockButton; protected DebouncedButton unlockButton; protected OnOffButton driveInvertedButton; protected OnOffButton driveFastButton; protected OnOffButton driveBumpStrafeRightButton; protected OnOffButton driveBumpStrafeLeftButton; protected OnOffButton acDcExtendButton; protected OnOffButton acDcRetractButton; protected DebouncedButton acDcHomeButton; protected OnOffButton acDcLimitOverrideButton; protected DebouncedButton acDcStopButton; protected OnOffButton elevatorCommandUpButton; protected OnOffButton elevatorCommandDownButton; protected DebouncedButton elevatorUpperLimitButton; protected DebouncedButton elevatorLowerLimitButton; protected DebouncedButton elevatorEmergencyStopButton; protected OnOffButton loadToBoxButton; protected OnOffButton boxTipButton; protected DcMotorEx particleScoreElevatorMotor; protected Servo boxTipServo; protected Servo boxGateServo; protected Servo collectorGateServo; protected Servo teamMarkerServo; protected ParticleScoringMechanism particleScoringMechanism; protected OnOffButton limitOverrideButton; protected Servo m3ArmServo; protected Servo m3FlagServo; /* * Perform any actions that are necessary when the OpMode is enabled. * <p/> * The system calls this member once when the OpMode is enabled. */ @Override public void init() { setupDriverControls(); setupOperatorControls(); setupDrivebase(); setupAscenderDescender(); setupCollector(); setupParticleScoringMechanism(); setupTeamMarker(); setupM3(); if (imuNeeded) { initImu(); } else { Log.d(LOG_TAG, "IMU not required, not initializing"); } Iterator<VoltageSensor> voltageSensors = hardwareMap.voltageSensor.iterator(); if (voltageSensors.hasNext()) { voltageSensor = voltageSensors.next(); } } protected static double M3_ARM_OUT_POSITION = 0; protected static double M3_ARM_UP_POSITION = .49; protected static double M3_FLAG_STOWED_POSITION = .5111; protected static double M3_FLAG_DEPLOYED_POSITION = .891; protected void setupM3() { // arm servo - out_position = 0 // arm servo - up-position=.49 // Flag servo stowed=.494 // Flag servo deployed=.891 m3ArmServo = hardwareMap.get(Servo.class, "m3ArmServo"); m3FlagServo = hardwareMap.get(Servo.class, "m3FlagServo"); m3FlagUp(); try { Thread.currentThread().sleep(500); } catch (InterruptedException intEx) { // do nothing } m3ArmUp(); } protected void m3ArmUp() { m3ArmServo.setPosition(M3_ARM_UP_POSITION); } protected void m3ArmOut() { m3ArmServo.setPosition(M3_ARM_OUT_POSITION);} protected void m3FlagUp() { m3FlagServo.setPosition(M3_FLAG_STOWED_POSITION); } protected void m3FlagOut() { m3FlagServo.setPosition(M3_FLAG_DEPLOYED_POSITION);} protected void setupParticleScoringMechanism() { try { particleScoreElevatorMotor = hardwareMap.get(DcMotorEx.class, "particleScoreElevatorMotor"); particleScoreElevatorMotor.setDirection(DcMotor.Direction.REVERSE); // Need to disable RUN_USING_ENCODER end ZPB.Brake to use a voltage feed forward for holding // but WHY? particleScoreElevatorMotor.setMode(DcMotor.RunMode.RUN_WITHOUT_ENCODER); particleScoreElevatorMotor.setZeroPowerBehavior(DcMotor.ZeroPowerBehavior.FLOAT); } catch (Exception ex) { appendWarningMessage("particleScoreElevatorMotor"); Log.e(LOG_TAG, ex.getLocalizedMessage()); particleScoreElevatorMotor = null; } try { scoreBoxReadyToLoadLimitSwitch = hardwareMap.digitalChannel.get("scoreBoxReadyToLoadLimitSwitch"); } catch (Exception ex) { appendWarningMessage("scoreBoxReadyToLoadLimitSwitch"); Log.e(LOG_TAG, ex.getLocalizedMessage()); scoreBoxReadyToLoadLimitSwitch = null; } boxTipServo = hardwareMap.servo.get("boxTipServo"); boxGateServo = hardwareMap.servo.get("boxGateServo"); particleScoringMechanism = new ParticleScoringMechanism(elevatorCommandUpButton, elevatorCommandDownButton, elevatorUpperLimitButton, elevatorLowerLimitButton, elevatorEmergencyStopButton, particleScoreElevatorMotor, null, null, telemetry, boxTipServo, boxTipButton, limitOverrideButton); } public static final double TEAM_MARKER_DUMP_POS = 1.0; // .25; public static final double TEAM_MARKER_STOWED_STATE = 0; // 1.0; protected void setupTeamMarker() { teamMarkerServo = hardwareMap.servo.get("teamMarkerServo"); teamMarkerServo.setPosition(TEAM_MARKER_STOWED_STATE); } protected void setupCollector() { try { collectorDeployMotor = hardwareMap.dcMotor.get("collectorDeployMotor"); collectorDeployMotor.setDirection(DcMotorSimple.Direction.REVERSE); collectorDeployMotor.setMode(DcMotor.RunMode.RUN_USING_ENCODER); collectorDeployMotor.setZeroPowerBehavior(DcMotor.ZeroPowerBehavior.BRAKE); // MM } catch (Exception ex) { appendWarningMessage("collectorDeployMotor"); Log.e(LOG_TAG, ex.getLocalizedMessage()); collectorDeployMotor = null; } try { collectorSweepMotor = hardwareMap.dcMotor.get("collectorSweepMotor"); } catch (Exception ex) { appendWarningMessage("collectorSweepMotor"); Log.e(LOG_TAG, ex.getLocalizedMessage()); collectorSweepMotor = null; } try { collectorStowLimitSwitch = hardwareMap.digitalChannel.get("collectorStowLimitSwitch"); } catch (Exception ex) { appendWarningMessage("collectorStowLimitSwitch"); Log.e(LOG_TAG, ex.getLocalizedMessage()); collectorStowLimitSwitch = null; } collectorGateServo = hardwareMap.servo.get("collectorGateServo"); } protected void setupDrivebase() { try { leftFrontDriveMotor = NinjaMotor.asNeverest20Orbital(hardwareMap.dcMotor.get("leftFrontDriveMotor")); leftFrontDriveMotor.setDirection(DcMotor.Direction.REVERSE); } catch (Exception ex) { appendWarningMessage("leftFrontDriveMotor"); Log.e(LOG_TAG, ex.getLocalizedMessage()); leftFrontDriveMotor = null; } try { leftRearDriveMotor = NinjaMotor.asNeverest20Orbital(hardwareMap.dcMotor.get("leftRearDriveMotor")); leftRearDriveMotor.setDirection(DcMotor.Direction.REVERSE); } catch (Exception ex) { appendWarningMessage("leftRearDriveMotor"); Log.e(LOG_TAG, ex.getLocalizedMessage()); leftRearDriveMotor = null; } try { rightFrontDriveMotor = NinjaMotor.asNeverest20Orbital(hardwareMap.dcMotor.get("rightFrontDriveMotor")); rightFrontDriveMotor.setDirection(DcMotor.Direction.FORWARD); } catch (Exception ex) { appendWarningMessage("rightFrontDriveMotor"); Log.e(LOG_TAG, ex.getLocalizedMessage()); rightFrontDriveMotor = null; } try { rightRearDriveMotor = NinjaMotor.asNeverest20Orbital(hardwareMap.dcMotor.get("rightRearDriveMotor")); rightRearDriveMotor.setDirection(DcMotor.Direction.FORWARD); } catch (Exception ex) { appendWarningMessage("rightRearDriveMotor"); Log.e(LOG_TAG, ex.getLocalizedMessage()); rightRearDriveMotor = null; } mecanumDrive = MecanumDrive.builder().leftFrontDriveMotor(leftFrontDriveMotor) .rightFrontDriveMotor(rightFrontDriveMotor) .leftRearDriveMotor(leftRearDriveMotor) .rightRearDriveMotor(rightRearDriveMotor).build(); } protected void initImu() { try { imu = hardwareMap.get(LynxEmbeddedIMU.class, "imu"); BNO055IMU.Parameters parameters = new BNO055IMU.Parameters(); parameters.mode = BNO055IMU.SensorMode.IMU; // yes, it's the default, but let's be sure parameters.angleUnit = BNO055IMU.AngleUnit.DEGREES; parameters.accelUnit = BNO055IMU.AccelUnit.METERS_PERSEC_PERSEC; //parameters.calibrationDataFile = "BNO055IMUCalibration.json"; // see the calibration sample opmode parameters.loggingEnabled = false; parameters.loggingTag = "IMU"; //parameters.accelerationIntegrationAlgorithm = new NaiveAccelerationIntegrator(); imu.initialize(parameters); imu.startAccelerationIntegration(null, null, 50); // not started by default? } catch (Exception ex) { appendWarningMessage("imu"); Log.e(LOG_TAG, ex.getLocalizedMessage()); imu = null; } } protected void setupAscenderDescender() { try { acDcMotor = NinjaMotor.asNeverest20Orbital(hardwareMap.dcMotor.get("acDcMotor")); acDcMotor.setDirection(DcMotorSimple.Direction.REVERSE); } catch (Exception ex) { appendWarningMessage("acDcMotor"); Log.e(LOG_TAG, ex.getLocalizedMessage()); acDcMotor = null; } try { acDcLimitSwitch = hardwareMap.digitalChannel.get("acDcLimitSwitch"); } catch (Exception ex) { appendWarningMessage("acDcLimitSwitch"); Log.e(LOG_TAG, ex.getLocalizedMessage()); acDcLimitSwitch = null; } if (acDcMotor != null && acDcLimitSwitch != null) { ascenderDescender = new LinearActuator(acDcMotor, acDcLimitSwitch); } } /** * Access whether a warning has been generated. */ boolean wasWarningGenerated() { return warningGenerated; } /** * Access the warning message. */ String getWarningMessage() { return warningMessage; } /** * Mutate the warning message by ADDING the specified message to the current * message; set the warning indicator to true. * <p/> * A comma will be added before the specified message if the message isn't * empty. */ void appendWarningMessage(String exceptionMessage) { if (warningGenerated) { warningMessage += ", "; } warningGenerated = true; warningMessage += exceptionMessage; } protected void logBatteryState(String opModeMethod) { if (voltageSensor == null) { Log.e("VV", String.format("No voltage sensor when logging voltage for %s")); return; } Log.d("VV", String.format("Robot battery voltage %5.2f at method %s()",voltageSensor.getVoltage(), opModeMethod)); } /** * Creates an instance of the "done" state which stops the robot and should be the * "end" state of all of our robot's state machines */ protected State newDoneState(String name) { return new State(name, telemetry) { private boolean issuedStop = false; @Override public State doStuffAndGetNextState() { if (!issuedStop) { mecanumDrive.stopAllDriveMotors(); issuedStop = true; } return this; } @Override public void resetToStart() { issuedStop = false; } }; } protected State newDelayState(String name, final int numberOfSeconds) { return new State(name, telemetry) { private long startTime = 0; private long thresholdTimeMs = TimeUnit.SECONDS.toMillis(numberOfSeconds); @Override public void resetToStart() { startTime = 0; } @Override public State doStuffAndGetNextState() { if (startTime == 0) { startTime = System.currentTimeMillis(); return this; } long now = System.currentTimeMillis(); long elapsedMs = now - startTime; if (elapsedMs > thresholdTimeMs) { return nextState; } telemetry.addData("04", "Delay: %d of %d ms", elapsedMs, thresholdTimeMs); return this; } }; } private void setupOperatorControls() { operatorsGamepad = new NinjaGamePad(gamepad2); // ---------------------- // Global operator controls // ---------------------- limitOverrideButton = new RangeInputButton( operatorsGamepad.getRightTrigger(), 0.65f); // MM: Tricky - used multiple places, need each usage to track own state OnOffButton eStopButton = operatorsGamepad.getBButton(); // ---------------------- // Ascender/Descender controls // ---------------------- // acdc - on-offs acDcExtendButton = operatorsGamepad.getDpadUp(); acDcRetractButton = operatorsGamepad.getDpadDown(); acDcLimitOverrideButton = limitOverrideButton; // acdc - debounced acDcStopButton = new DebouncedButton(eStopButton); acDcHomeButton = new DebouncedButton(operatorsGamepad.getRightBumper()); // ---------------------- // Elevator controls // ---------------------- elevatorCommandUpButton = operatorsGamepad.getLeftBumper(); elevatorCommandDownButton = new RangeInputButton( operatorsGamepad.getLeftTrigger(), .65f); elevatorUpperLimitButton = new DebouncedButton(operatorsGamepad.getYButton()); elevatorLowerLimitButton = new DebouncedButton(operatorsGamepad.getAButton()); elevatorEmergencyStopButton = new DebouncedButton(eStopButton); boxTipButton = operatorsGamepad.getXButton(); // ---------------------- // Collector controls // ---------------------- collectorDeployInput = operatorsGamepad.getRightStickY(); collectorSweepInput = operatorsGamepad.getLeftStickY(); loadToBoxButton = operatorsGamepad.getDpadRight(); } private final float lowPassFilterFactor = .92F; private void setupDriverControls() { driversGamepad = new NinjaGamePad(gamepad1); driverLeftStickX = driversGamepad.getLeftStickX(); driverLeftStickY = driversGamepad.getLeftStickY(); driverRightStickX = driversGamepad.getRightStickX(); driverRightStickY = driversGamepad.getRightStickY(); driveStrafe = new ParametricScaledRangeInput( new LowPassFilteredRangeInput(driverLeftStickX, lowPassFilterFactor), throttleDeadband, throttleGain, throttleExponent); driveForwardReverse = new ParametricScaledRangeInput( new LowPassFilteredRangeInput(driverLeftStickY, lowPassFilterFactor), throttleDeadband, throttleGain, throttleExponent); driveRotate = new LowPassFilteredRangeInput(driverRightStickX, lowPassFilterFactor); driverDpadDown = new DebouncedButton(driversGamepad.getDpadDown()); driverDpadUp = new DebouncedButton(driversGamepad.getDpadUp()); driverDpadLeft = new DebouncedButton(driversGamepad.getDpadLeft()); driverDpadRight = new DebouncedButton(driversGamepad.getDpadRight()); driverAGreenButton = new DebouncedButton(driversGamepad.getAButton()); driverBRedButton = new DebouncedButton(driversGamepad.getBButton()); driverXBlueButton = new DebouncedButton(driversGamepad.getXButton()); driverYYellowButton = new DebouncedButton(driversGamepad.getYButton()); driverLeftBumper = new DebouncedButton(driversGamepad.getLeftBumper()); driverRightBumper = new DebouncedButton(driversGamepad.getRightBumper()); lockButton = new DebouncedButton(driversGamepad.getLeftStickButton()); unlockButton = new DebouncedButton(driversGamepad.getRightStickButton()); driveFastButton = new RangeInputButton(driversGamepad.getLeftTrigger(), 0.65f); driveInvertedButton = new RangeInputButton(driversGamepad.getRightTrigger(), 0.65f); driveBumpStrafeLeftButton = driversGamepad.getLeftBumper(); driveBumpStrafeRightButton = driversGamepad.getRightBumper(); } protected void handleAscender() { if (acDcExtendButton.isPressed()){ ascenderDescender.extend(acDcLimitOverrideButton.isPressed()); } else if (acDcRetractButton.isPressed()){ ascenderDescender.retract(acDcLimitOverrideButton.isPressed()); } else if (acDcHomeButton.getRise()){ ascenderDescender.home(); } else if (acDcStopButton.getRise()) { ascenderDescender.stopMoving(); } else if (!ascenderDescender.isHoming()) { ascenderDescender.stopMoving(); } // do the periodic task on the linear actuator ascenderDescender.doPeriodicTask(); } }
import java.util.Scanner; public class ReversedChars { public static void main(String[] args) { Scanner scan = new Scanner(System.in); String sum = ""; for (int i = 0; i < 3; i++) { char next = scan.nextLine().charAt(0); sum = sum + next; } for (int i = sum.length() - 1; i >= 0; i--) { System.out.printf("%c ", sum.charAt(i)); } } }
package org.apereo.cas.web.view; import lombok.SneakyThrows; import lombok.extern.slf4j.Slf4j; import org.apereo.cas.CasProtocolConstants; import org.apereo.cas.CasViewConstants; import org.apereo.cas.authentication.CoreAuthenticationTestUtils; import org.apereo.cas.authentication.DefaultAuthenticationAttributeReleasePolicy; import org.apereo.cas.authentication.DefaultAuthenticationContextValidator; import org.apereo.cas.authentication.DefaultAuthenticationServiceSelectionPlan; import org.apereo.cas.authentication.DefaultAuthenticationServiceSelectionStrategy; import org.apereo.cas.authentication.DefaultMultifactorTriggerSelectionStrategy; import org.apereo.cas.authentication.ProtocolAttributeEncoder; import org.apereo.cas.authentication.UsernamePasswordCredential; import org.apereo.cas.authentication.support.DefaultCasProtocolAttributeEncoder; import org.apereo.cas.services.ServicesManager; import org.apereo.cas.util.EncodingUtils; import org.apereo.cas.util.cipher.NoOpCipherExecutor; import org.apereo.cas.util.crypto.PrivateKeyFactoryBean; import org.apereo.cas.validation.DefaultServiceTicketValidationAuthorizersExecutionPlan; import org.apereo.cas.web.AbstractServiceValidateController; import org.apereo.cas.web.AbstractServiceValidateControllerTests; import org.apereo.cas.web.ServiceValidateController; import org.junit.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.core.io.ClassPathResource; import org.springframework.http.MediaType; import org.springframework.mock.web.MockHttpServletRequest; import org.springframework.mock.web.MockHttpServletResponse; import org.springframework.mock.web.MockServletContext; import org.springframework.test.annotation.DirtiesContext; import org.springframework.test.context.TestPropertySource; import org.springframework.web.context.support.GenericWebApplicationContext; import org.springframework.web.servlet.ModelAndView; import org.springframework.web.servlet.View; import org.springframework.web.servlet.support.RequestContext; import javax.crypto.Cipher; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.nio.charset.StandardCharsets; import java.security.PrivateKey; import java.util.Map; import static org.junit.Assert.*; /** * Unit tests for {@link Cas30ResponseView}. * * @author Misagh Moayyed * @since 4.0.0 */ @DirtiesContext @TestPropertySource(properties = {"cas.clearpass.cacheCredential=true", "cas.clearpass.crypto.enabled=false"}) @Slf4j public class Cas30ResponseViewTests extends AbstractServiceValidateControllerTests { @Autowired @Qualifier("servicesManager") private ServicesManager servicesManager; @Autowired @Qualifier("cas3ServiceJsonView") private View cas3ServiceJsonView; @Autowired @Qualifier("cas3SuccessView") private View cas3SuccessView; @Autowired @Qualifier("cas3ServiceFailureView") private View cas3ServiceFailureView; @Override public AbstractServiceValidateController getServiceValidateControllerInstance() throws Exception { return new ServiceValidateController( getValidationSpecification(), getAuthenticationSystemSupport(), getServicesManager(), getCentralAuthenticationService(), getProxyHandler(), getArgumentExtractor(), new DefaultMultifactorTriggerSelectionStrategy("", ""), new DefaultAuthenticationContextValidator("", "OPEN", "test"), cas3ServiceJsonView, cas3SuccessView, cas3ServiceFailureView, "authenticationContext", new DefaultServiceTicketValidationAuthorizersExecutionPlan() ); } private Map<?, ?> renderView() throws Exception { final ModelAndView modelAndView = this.getModelAndViewUponServiceValidationWithSecurePgtUrl(); LOGGER.warn("Retrieved model and view [{}]", modelAndView.getModel()); final MockHttpServletRequest req = new MockHttpServletRequest(new MockServletContext()); req.setAttribute(RequestContext.WEB_APPLICATION_CONTEXT_ATTRIBUTE, new GenericWebApplicationContext(req.getServletContext())); final ProtocolAttributeEncoder encoder = new DefaultCasProtocolAttributeEncoder(this.servicesManager, NoOpCipherExecutor.getInstance()); final View viewDelegated = new View() { @Override public String getContentType() { return MediaType.TEXT_HTML_VALUE; } @Override public void render(final Map<String, ?> map, final HttpServletRequest request, final HttpServletResponse response) { LOGGER.warn("Setting attribute [{}]", map.keySet()); map.forEach(request::setAttribute); } }; final Cas30ResponseView view = new Cas30ResponseView(true, encoder, servicesManager, "attribute", viewDelegated, true, new DefaultAuthenticationAttributeReleasePolicy(), new DefaultAuthenticationServiceSelectionPlan(new DefaultAuthenticationServiceSelectionStrategy())); final MockHttpServletResponse resp = new MockHttpServletResponse(); view.render(modelAndView.getModel(), req, resp); return (Map<?, ?>) req.getAttribute(CasProtocolConstants.VALIDATION_CAS_MODEL_ATTRIBUTE_NAME_ATTRIBUTES); } @Test public void verifyViewAuthnAttributes() throws Exception { final Map<?, ?> attributes = renderView(); assertTrue(attributes.containsKey(CasProtocolConstants.VALIDATION_CAS_MODEL_ATTRIBUTE_NAME_AUTHENTICATION_DATE)); assertTrue(attributes.containsKey(CasProtocolConstants.VALIDATION_CAS_MODEL_ATTRIBUTE_NAME_FROM_NEW_LOGIN)); assertTrue(attributes.containsKey(CasProtocolConstants.VALIDATION_REMEMBER_ME_ATTRIBUTE_NAME)); } @Test public void verifyPasswordAsAuthenticationAttributeCanDecrypt() throws Exception { final Map<?, ?> attributes = renderView(); assertTrue(attributes.containsKey(CasViewConstants.MODEL_ATTRIBUTE_NAME_PRINCIPAL_CREDENTIAL)); final String encodedPsw = (String) attributes.get(CasViewConstants.MODEL_ATTRIBUTE_NAME_PRINCIPAL_CREDENTIAL); final String password = decryptCredential(encodedPsw); final UsernamePasswordCredential creds = CoreAuthenticationTestUtils.getCredentialsWithSameUsernameAndPassword(); assertEquals(password, creds.getPassword()); } @Test public void verifyProxyGrantingTicketAsAuthenticationAttributeCanDecrypt() throws Exception { final Map<?, ?> attributes = renderView(); LOGGER.warn("Attributes are [{}]", attributes.keySet()); assertTrue(attributes.containsKey(CasViewConstants.MODEL_ATTRIBUTE_NAME_PROXY_GRANTING_TICKET)); final String encodedPgt = (String) attributes.get(CasViewConstants.MODEL_ATTRIBUTE_NAME_PROXY_GRANTING_TICKET); final String pgt = decryptCredential(encodedPgt); assertNotNull(pgt); } @SneakyThrows private String decryptCredential(final String cred) { final PrivateKeyFactoryBean factory = new PrivateKeyFactoryBean(); factory.setAlgorithm("RSA"); factory.setLocation(new ClassPathResource("keys/RSA4096Private.p8")); factory.setSingleton(false); final PrivateKey privateKey = factory.getObject(); LOGGER.debug("Initializing cipher based on [{}]", privateKey.getAlgorithm()); final Cipher cipher = Cipher.getInstance(privateKey.getAlgorithm()); LOGGER.debug("Decoding value [{}]", cred); final byte[] cred64 = EncodingUtils.decodeBase64(cred); LOGGER.debug("Initializing decrypt-mode via private key [{}]", privateKey.getAlgorithm()); cipher.init(Cipher.DECRYPT_MODE, privateKey); final byte[] cipherData = cipher.doFinal(cred64); return new String(cipherData, StandardCharsets.UTF_8); } }
package edu.neu.android.wearwocketslib.services; import android.content.Context; import android.content.Intent; import android.os.AsyncTask; import android.os.Bundle; import com.google.android.gms.common.api.GoogleApiClient; import com.google.android.gms.common.data.FreezableUtils; import com.google.android.gms.wearable.Asset; import com.google.android.gms.wearable.DataEvent; import com.google.android.gms.wearable.DataEventBuffer; import com.google.android.gms.wearable.DataMapItem; import com.google.android.gms.wearable.MessageEvent; import com.google.android.gms.wearable.Node; import com.google.android.gms.wearable.NodeApi; import com.google.android.gms.wearable.Wearable; import com.google.android.gms.wearable.WearableListenerService; import org.apache.commons.io.FileUtils; import org.apache.commons.io.IOUtils; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.util.Collection; import java.util.Date; import java.util.HashSet; import java.util.List; import edu.neu.android.wearwocketslib.Globals; import edu.neu.android.wearwocketslib.core.repeatedwakefulservice.AlwaysOnService; import edu.neu.android.wearwocketslib.core.repeatedwakefulservice.WearableWakefulBroadcastAlarm; import edu.neu.android.wearwocketslib.core.repeatedwakefulservice.WearableWakefulService; import edu.neu.android.wearwocketslib.notification.LostConnectionWearableNotification; import edu.neu.android.wearwocketslib.notification.WearableNotification; import edu.neu.android.wearwocketslib.utils.log.Logger; import edu.neu.android.wearwocketslib.utils.system.DateHelper; import edu.neu.android.wearwocketslib.utils.log.Log; import edu.neu.android.wearwocketslib.utils.io.SharedPrefs; import edu.neu.android.wocketslib.mhealthformat.mHealthFormat; import static android.support.v4.content.WakefulBroadcastReceiver.startWakefulService; public class WearListenerService extends WearableListenerService implements GoogleApiClient.ConnectionCallbacks { private static final String TAG = "WearListenerService"; private static final String FILE_PATH = "/filefromphone"; private static final String FILE_KEY = "file"; protected static final String NOTE_PATH = "/notefromphone"; private static boolean isConnected = false; private Context mContext; private GoogleApiClient mGoogleApiClient = null; private Logger logger = null; @Override public void onCreate() { mContext = getApplicationContext(); logger = new Logger(TAG); logger.i("Inside onCreate", getApplicationContext()); mGoogleApiClient = new GoogleApiClient.Builder(this) .addApi(Wearable.API) .build(); if(mGoogleApiClient != null) mGoogleApiClient.connect(); new checkConnectionTask().execute(); super.onCreate(); } @Override public void onLowMemory() { logger.i("Inside onLowMemory", getApplicationContext()); super.onLowMemory(); } @Override public int onStartCommand(Intent intent, int flags, int startId) { logger.i("Inside onStart", getApplicationContext()); return super.onStartCommand(intent, flags, startId); } @Override public void onMessageReceived(MessageEvent messageEvent) { logger.i("Inside onMessageReceived: " + messageEvent.getPath(), getApplicationContext()); logger.i("Phone is in connection(from onMessageReceived)!",getApplicationContext()); SharedPrefs.setLong(Globals.LAST_PHONE_IN_CONNECTION_TIME, System.currentTimeMillis(), getApplicationContext()); if (WearableNotification.isShowing(WearableNotification.LOST_CONNECTION_NOTIFICATION)) { WearableNotification.cancel(WearableNotification.LOST_CONNECTION_NOTIFICATION); logger.i("Cancel lost connection notification", getApplicationContext()); } if(messageEvent.getPath().equals(NOTE_PATH)) { String message = new String(messageEvent.getData()); logger.i("Message Received - " + message, getApplicationContext()); if (message.contains("trigger")) { logger.i("Received message to start minute service", getApplicationContext()); // logger.i("Phone is in connection(from onMessageReceived)!",getApplicationContext()); // SharedPrefs.setLong(Globals.LAST_PHONE_IN_CONNECTION_TIME, System.currentTimeMillis(), getApplicationContext()); logger.i("starting always on service using intent",mContext); Intent alwaysOnServiceIntent = new Intent(mContext,AlwaysOnService.class); mContext.startService(alwaysOnServiceIntent); // startRepeatedWakefulService(); // setAlarm(getApplicationContext()); }else if(message.startsWith("TRANSFER_SUCCESS")){ String[] tokens = message.split(":"); File toBeDeleted = new File(tokens[1]); String subString = "ComputedFeature"; String name = toBeDeleted.getName(); if(!name.toLowerCase().contains(subString.toLowerCase())) { if (toBeDeleted.delete()) { Log.i(WearableWakefulService.TAG, "Successfully deleted file upon successful transfer: " + toBeDeleted.getAbsolutePath(), getApplicationContext()); } else { Log.e(WearableWakefulService.TAG, "Fail to delete original zip file upon successful transfer: " + toBeDeleted.getAbsolutePath(), getApplicationContext()); } } }else if(message.startsWith("TRANSFER_FAILURE")){ //add to queue to transfer again String[] tokens = message.split(":"); Log.i(WearableWakefulService.TAG, "Fail to transfer file: " + tokens[1], getApplicationContext()); }else if(message.startsWith("ENABLE_TRANSFER")){ SharedPrefs.setBoolean(WearableWakefulService.KEY_ENABLE_TRANSFER, true, getApplicationContext()); }else if(message.startsWith("DISABLE_TRANSFER")){ SharedPrefs.setBoolean(WearableWakefulService.KEY_ENABLE_TRANSFER, false, getApplicationContext()); } else{ logger.i("Received message: " + message, getApplicationContext()); } } } private void deleteSensorDataFile(String fullPath){ File toBeDeleted = new File(fullPath); if(!DateHelper.isHourBefore(mHealthFormat.extractDateFromFilename(toBeDeleted.getName()))){ logger.i("The file is still in collection, so skip deleting: " + fullPath, getApplicationContext()); return; } if(toBeDeleted.delete()){ logger.i("Delete file: " + fullPath + " after successful transfer", getApplicationContext()); }else{ if(toBeDeleted.exists()){ logger.i("Delete file: " + fullPath + " failed", getApplicationContext()); }else{ logger.i("File does not exist: " + fullPath + "; abort deleting", getApplicationContext()); } } } public static boolean isConnected(){ return isConnected; } public static void setConnection(boolean isConnected){ WearListenerService.isConnected = isConnected; } @Override public void onPeerConnected(Node node) { logger.i("Inside onPeerConnected", getApplicationContext()); logger.i("Node Connected - " + node.getDisplayName(), getApplicationContext()); isConnected = true; if (WearableNotification.isShowing(WearableNotification.LOST_CONNECTION_NOTIFICATION)) { WearableNotification.cancel(WearableNotification.LOST_CONNECTION_NOTIFICATION); logger.i("Cancel lost connection notification", getApplicationContext()); } } @Override public void onPeerDisconnected(Node node) { logger.i("Inside onPeerDisconnected", getApplicationContext()); logger.i("Node Disconnected - " + node.getDisplayName(), getApplicationContext()); isConnected = false; // LostConnectionWearableNotification notification = new LostConnectionWearableNotification("PHIRE: Connection lost", "Please check phone/watch connection", R.drawable.ic_launcher, true, WearableNotification.LOST_CONNECTION_NOTIFICATION, mContext); // notification.show(); } @Override public void onDataChanged(DataEventBuffer dataEventBuffer) { logger.i("Inside onDataChanged", getApplicationContext()); // logger.i("Phone is in connection(from onDataChanged)!",getApplicationContext()); SharedPrefs.setLong(Globals.LAST_PHONE_IN_CONNECTION_TIME, System.currentTimeMillis(), getApplicationContext()); final List<DataEvent> events = FreezableUtils.freezeIterable(dataEventBuffer); dataEventBuffer.close(); for (DataEvent event : events) { if(event.getType() == DataEvent.TYPE_CHANGED) { String path = event.getDataItem().getUri().getPath(); if(FILE_PATH.equals(path)) { DataMapItem dataMapItem = DataMapItem.fromDataItem(event.getDataItem()); Asset file = dataMapItem.getDataMap().getAsset(FILE_KEY); String filePath = dataMapItem.getDataMap().getString("path"); String fileName = dataMapItem.getDataMap().getString("name"); logger.i("File Received - " + filePath + "/" + fileName, getApplicationContext()); assetToFile(file, filePath, fileName); } } } } private void assetToFile(Asset asset, String path, String fileName) { logger.i("Inside loadFileFromAsset", getApplicationContext()); File filePath = new File(path); File file = new File(path + "/" + fileName); filePath.mkdirs(); try { InputStream assetInputStream = Wearable.DataApi.getFdForAsset( mGoogleApiClient, asset).await().getInputStream(); byte[] b = IOUtils.toByteArray(assetInputStream); FileUtils.writeByteArrayToFile(file, b); } catch (IOException e) { e.printStackTrace(); } logger.i("File write successfully - " + filePath + "/" + fileName, getApplicationContext()); } @Override public void onDestroy() { logger.i("Inside onDestroy", getApplicationContext()); logger.close(); super.onDestroy(); } public static void setAlarm(Context mContext) { WearableWakefulBroadcastAlarm alarm = new WearableWakefulBroadcastAlarm(mContext, "PHONE"); alarm.setAlarm(); } @Override public void onConnected(Bundle bundle) { logger.i("Google Api Connected", getApplicationContext()); if(Wearable.NodeApi.getConnectedNodes(mGoogleApiClient).await().getNodes().size() > 0){ isConnected = true; } } @Override public void onConnectionSuspended(int i) { logger.i("Google Api Suspended", getApplicationContext()); } private class checkConnectionTask extends AsyncTask<String, Void, Void> { @Override protected Void doInBackground(String... params){ Collection<String> nodes = getNodes(); if(nodes.size() > 0 && !WearListenerService.isConnected()){ WearListenerService.setConnection(true); // logger.i("Phone is in connection(from checkConnectionTask)!",getApplicationContext()); // SharedPrefs.setLong(Globals.LAST_PHONE_IN_CONNECTION_TIME, System.currentTimeMillis(), getApplicationContext()); }else if(nodes.size() == 0 && WearListenerService.isConnected()){ WearListenerService.setConnection(false); logger.i("Phone is not in connection!", getApplicationContext()); } return null; } } private Collection<String> getNodes() { HashSet<String> results = new HashSet<String>(); NodeApi.GetConnectedNodesResult nodes = Wearable.NodeApi.getConnectedNodes(mGoogleApiClient).await(); for (Node node : nodes.getNodes()) { results.add(node.getId()); } return results; } private void startRepeatedWakefulService(){ Intent wakefulService = new Intent(mContext, WearableWakefulService.class); if(!WearableWakefulService.isRunning()) { logger.i("Starting service @ " + new Date().toString(), mContext); startWakefulService(mContext, wakefulService); }else{ logger.i("Wakeful service is running, no need to start", mContext); } } }
/* * MIT License * * Copyright (c) 2020 Airbyte * * 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 io.airbyte.server.apis; import io.airbyte.api.model.CheckConnectionRead; import io.airbyte.api.model.CheckOperationRead; import io.airbyte.api.model.CompleteDestinationOAuthRequest; import io.airbyte.api.model.CompleteSourceOauthRequest; import io.airbyte.api.model.ConnectionCreate; import io.airbyte.api.model.ConnectionIdRequestBody; import io.airbyte.api.model.ConnectionRead; import io.airbyte.api.model.ConnectionReadList; import io.airbyte.api.model.ConnectionState; import io.airbyte.api.model.ConnectionUpdate; import io.airbyte.api.model.DbMigrationExecutionRead; import io.airbyte.api.model.DbMigrationReadList; import io.airbyte.api.model.DbMigrationRequestBody; import io.airbyte.api.model.DestinationCoreConfig; import io.airbyte.api.model.DestinationCreate; import io.airbyte.api.model.DestinationDefinitionCreate; import io.airbyte.api.model.DestinationDefinitionIdRequestBody; import io.airbyte.api.model.DestinationDefinitionRead; import io.airbyte.api.model.DestinationDefinitionReadList; import io.airbyte.api.model.DestinationDefinitionSpecificationRead; import io.airbyte.api.model.DestinationDefinitionUpdate; import io.airbyte.api.model.DestinationIdRequestBody; import io.airbyte.api.model.DestinationOauthConsentRequest; import io.airbyte.api.model.DestinationRead; import io.airbyte.api.model.DestinationReadList; import io.airbyte.api.model.DestinationUpdate; import io.airbyte.api.model.HealthCheckRead; import io.airbyte.api.model.ImportRead; import io.airbyte.api.model.ImportRequestBody; import io.airbyte.api.model.JobIdRequestBody; import io.airbyte.api.model.JobInfoRead; import io.airbyte.api.model.JobListRequestBody; import io.airbyte.api.model.JobReadList; import io.airbyte.api.model.LogsRequestBody; import io.airbyte.api.model.Notification; import io.airbyte.api.model.NotificationRead; import io.airbyte.api.model.OAuthConsentRead; import io.airbyte.api.model.OperationCreate; import io.airbyte.api.model.OperationIdRequestBody; import io.airbyte.api.model.OperationRead; import io.airbyte.api.model.OperationReadList; import io.airbyte.api.model.OperationUpdate; import io.airbyte.api.model.OperatorConfiguration; import io.airbyte.api.model.SetInstancewideDestinationOauthParamsRequestBody; import io.airbyte.api.model.SetInstancewideSourceOauthParamsRequestBody; import io.airbyte.api.model.SlugRequestBody; import io.airbyte.api.model.SourceCoreConfig; import io.airbyte.api.model.SourceCreate; import io.airbyte.api.model.SourceDefinitionCreate; import io.airbyte.api.model.SourceDefinitionIdRequestBody; import io.airbyte.api.model.SourceDefinitionRead; import io.airbyte.api.model.SourceDefinitionReadList; import io.airbyte.api.model.SourceDefinitionSpecificationRead; import io.airbyte.api.model.SourceDefinitionUpdate; import io.airbyte.api.model.SourceDiscoverSchemaRead; import io.airbyte.api.model.SourceIdRequestBody; import io.airbyte.api.model.SourceOauthConsentRequest; import io.airbyte.api.model.SourceRead; import io.airbyte.api.model.SourceReadList; import io.airbyte.api.model.SourceUpdate; import io.airbyte.api.model.UploadRead; import io.airbyte.api.model.WebBackendConnectionCreate; import io.airbyte.api.model.WebBackendConnectionRead; import io.airbyte.api.model.WebBackendConnectionReadList; import io.airbyte.api.model.WebBackendConnectionRequestBody; import io.airbyte.api.model.WebBackendConnectionSearch; import io.airbyte.api.model.WebBackendConnectionUpdate; import io.airbyte.api.model.WorkspaceCreate; import io.airbyte.api.model.WorkspaceIdRequestBody; import io.airbyte.api.model.WorkspaceRead; import io.airbyte.api.model.WorkspaceReadList; import io.airbyte.api.model.WorkspaceUpdate; import io.airbyte.commons.io.FileTtlManager; import io.airbyte.config.Configs; import io.airbyte.config.persistence.ConfigNotFoundException; import io.airbyte.config.persistence.ConfigPersistence; import io.airbyte.config.persistence.ConfigRepository; import io.airbyte.db.Database; import io.airbyte.scheduler.client.CachingSynchronousSchedulerClient; import io.airbyte.scheduler.client.SchedulerJobClient; import io.airbyte.scheduler.persistence.JobNotifier; import io.airbyte.scheduler.persistence.JobPersistence; import io.airbyte.scheduler.persistence.WorkspaceHelper; import io.airbyte.server.converters.SpecFetcher; import io.airbyte.server.errors.BadObjectSchemaKnownException; import io.airbyte.server.errors.IdNotFoundKnownException; import io.airbyte.server.handlers.ArchiveHandler; import io.airbyte.server.handlers.ConnectionsHandler; import io.airbyte.server.handlers.DbMigrationHandler; import io.airbyte.server.handlers.DestinationDefinitionsHandler; import io.airbyte.server.handlers.DestinationHandler; import io.airbyte.server.handlers.HealthCheckHandler; import io.airbyte.server.handlers.JobHistoryHandler; import io.airbyte.server.handlers.LogsHandler; import io.airbyte.server.handlers.OAuthHandler; import io.airbyte.server.handlers.OpenApiConfigHandler; import io.airbyte.server.handlers.OperationsHandler; import io.airbyte.server.handlers.SchedulerHandler; import io.airbyte.server.handlers.SourceDefinitionsHandler; import io.airbyte.server.handlers.SourceHandler; import io.airbyte.server.handlers.WebBackendConnectionsHandler; import io.airbyte.server.handlers.WebBackendDestinationsHandler; import io.airbyte.server.handlers.WebBackendSourcesHandler; import io.airbyte.server.handlers.WorkspacesHandler; import io.airbyte.server.validators.DockerImageValidator; import io.airbyte.validation.json.JsonSchemaValidator; import io.airbyte.validation.json.JsonValidationException; import io.temporal.serviceclient.WorkflowServiceStubs; import java.io.File; import java.io.IOException; import java.util.Map; @javax.ws.rs.Path("/v1") public class ConfigurationApi implements io.airbyte.api.V1Api { private final WorkspacesHandler workspacesHandler; private final SourceDefinitionsHandler sourceDefinitionsHandler; private final SourceHandler sourceHandler; private final DestinationDefinitionsHandler destinationDefinitionsHandler; private final DestinationHandler destinationHandler; private final ConnectionsHandler connectionsHandler; private final OperationsHandler operationsHandler; private final SchedulerHandler schedulerHandler; private final JobHistoryHandler jobHistoryHandler; private final WebBackendConnectionsHandler webBackendConnectionsHandler; private final WebBackendSourcesHandler webBackendSourcesHandler; private final WebBackendDestinationsHandler webBackendDestinationsHandler; private final HealthCheckHandler healthCheckHandler; private final ArchiveHandler archiveHandler; private final LogsHandler logsHandler; private final OpenApiConfigHandler openApiConfigHandler; private final DbMigrationHandler dbMigrationHandler; private final OAuthHandler oAuthHandler; private final Configs configs; public ConfigurationApi(final ConfigRepository configRepository, final JobPersistence jobPersistence, final ConfigPersistence seed, final SchedulerJobClient schedulerJobClient, final CachingSynchronousSchedulerClient synchronousSchedulerClient, final Configs configs, final FileTtlManager archiveTtlManager, final WorkflowServiceStubs temporalService, final Database configsDatabase, final Database jobsDatabase) { final SpecFetcher specFetcher = new SpecFetcher(synchronousSchedulerClient); final JsonSchemaValidator schemaValidator = new JsonSchemaValidator(); final JobNotifier jobNotifier = new JobNotifier(configs.getWebappUrl(), configRepository, new WorkspaceHelper(configRepository, jobPersistence)); schedulerHandler = new SchedulerHandler( configRepository, schedulerJobClient, synchronousSchedulerClient, jobPersistence, jobNotifier, temporalService); final DockerImageValidator dockerImageValidator = new DockerImageValidator(synchronousSchedulerClient); final WorkspaceHelper workspaceHelper = new WorkspaceHelper(configRepository, jobPersistence); sourceDefinitionsHandler = new SourceDefinitionsHandler(configRepository, dockerImageValidator, synchronousSchedulerClient); connectionsHandler = new ConnectionsHandler(configRepository, workspaceHelper); operationsHandler = new OperationsHandler(configRepository); destinationDefinitionsHandler = new DestinationDefinitionsHandler(configRepository, dockerImageValidator, synchronousSchedulerClient); destinationHandler = new DestinationHandler(configRepository, schemaValidator, specFetcher, connectionsHandler); sourceHandler = new SourceHandler(configRepository, schemaValidator, specFetcher, connectionsHandler); workspacesHandler = new WorkspacesHandler(configRepository, connectionsHandler, destinationHandler, sourceHandler); jobHistoryHandler = new JobHistoryHandler(jobPersistence); oAuthHandler = new OAuthHandler(configRepository); webBackendConnectionsHandler = new WebBackendConnectionsHandler( connectionsHandler, sourceHandler, destinationHandler, jobHistoryHandler, schedulerHandler, operationsHandler); webBackendSourcesHandler = new WebBackendSourcesHandler(sourceHandler, configRepository); webBackendDestinationsHandler = new WebBackendDestinationsHandler(destinationHandler, configRepository); healthCheckHandler = new HealthCheckHandler(configRepository); archiveHandler = new ArchiveHandler( configs.getAirbyteVersion(), configRepository, jobPersistence, seed, workspaceHelper, archiveTtlManager, specFetcher); logsHandler = new LogsHandler(); openApiConfigHandler = new OpenApiConfigHandler(); dbMigrationHandler = new DbMigrationHandler(configsDatabase, jobsDatabase); this.configs = configs; } // WORKSPACE @Override public WorkspaceReadList listWorkspaces() { return execute(workspacesHandler::listWorkspaces); } @Override public WorkspaceRead createWorkspace(final WorkspaceCreate workspaceCreate) { return execute(() -> workspacesHandler.createWorkspace(workspaceCreate)); } @Override public void deleteWorkspace(final WorkspaceIdRequestBody workspaceIdRequestBody) { execute(() -> { workspacesHandler.deleteWorkspace(workspaceIdRequestBody); return null; }); } @Override public WorkspaceRead getWorkspace(final WorkspaceIdRequestBody workspaceIdRequestBody) { return execute(() -> workspacesHandler.getWorkspace(workspaceIdRequestBody)); } @Override public WorkspaceRead getWorkspaceBySlug(final SlugRequestBody slugRequestBody) { return execute(() -> workspacesHandler.getWorkspaceBySlug(slugRequestBody)); } @Override public WorkspaceRead updateWorkspace(final WorkspaceUpdate workspaceUpdate) { return execute(() -> workspacesHandler.updateWorkspace(workspaceUpdate)); } @Override public NotificationRead tryNotificationConfig(final Notification notification) { return execute(() -> workspacesHandler.tryNotification(notification)); } // SOURCE @Override public SourceDefinitionReadList listSourceDefinitions() { return execute(sourceDefinitionsHandler::listSourceDefinitions); } @Override public SourceDefinitionReadList listLatestSourceDefinitions() { return execute(sourceDefinitionsHandler::listLatestSourceDefinitions); } @Override public SourceDefinitionRead getSourceDefinition(final SourceDefinitionIdRequestBody sourceDefinitionIdRequestBody) { return execute(() -> sourceDefinitionsHandler.getSourceDefinition(sourceDefinitionIdRequestBody)); } @Override public SourceDefinitionRead createSourceDefinition(final SourceDefinitionCreate sourceDefinitionCreate) { return execute(() -> sourceDefinitionsHandler.createSourceDefinition(sourceDefinitionCreate)); } @Override public SourceDefinitionRead updateSourceDefinition(final SourceDefinitionUpdate sourceDefinitionUpdate) { return execute(() -> sourceDefinitionsHandler.updateSourceDefinition(sourceDefinitionUpdate)); } // SOURCE SPECIFICATION @Override public SourceDefinitionSpecificationRead getSourceDefinitionSpecification(final SourceDefinitionIdRequestBody sourceDefinitionIdRequestBody) { return execute(() -> schedulerHandler.getSourceDefinitionSpecification(sourceDefinitionIdRequestBody)); } // OAUTH @Override public OAuthConsentRead getSourceOAuthConsent(final SourceOauthConsentRequest sourceOauthConsentRequest) { return execute(() -> oAuthHandler.getSourceOAuthConsent(sourceOauthConsentRequest)); } @Override public Map<String, Object> completeSourceOAuth(final CompleteSourceOauthRequest completeSourceOauthRequest) { return execute(() -> oAuthHandler.completeSourceOAuth(completeSourceOauthRequest)); } @Override public OAuthConsentRead getDestinationOAuthConsent(final DestinationOauthConsentRequest destinationOauthConsentRequest) { return execute(() -> oAuthHandler.getDestinationOAuthConsent(destinationOauthConsentRequest)); } @Override public Map<String, Object> completeDestinationOAuth(final CompleteDestinationOAuthRequest requestBody) { return execute(() -> oAuthHandler.completeDestinationOAuth(requestBody)); } @Override public void setInstancewideDestinationOauthParams(final SetInstancewideDestinationOauthParamsRequestBody requestBody) { execute(() -> { oAuthHandler.setDestinationInstancewideOauthParams(requestBody); return null; }); } @Override public void setInstancewideSourceOauthParams(final SetInstancewideSourceOauthParamsRequestBody requestBody) { execute(() -> { oAuthHandler.setSourceInstancewideOauthParams(requestBody); return null; }); } // SOURCE IMPLEMENTATION @Override public SourceRead createSource(final SourceCreate sourceCreate) { return execute(() -> sourceHandler.createSource(sourceCreate)); } @Override public SourceRead updateSource(final SourceUpdate sourceUpdate) { return execute(() -> sourceHandler.updateSource(sourceUpdate)); } @Override public SourceReadList listSourcesForWorkspace(final WorkspaceIdRequestBody workspaceIdRequestBody) { return execute(() -> sourceHandler.listSourcesForWorkspace(workspaceIdRequestBody)); } @Override public SourceRead getSource(final SourceIdRequestBody sourceIdRequestBody) { return execute(() -> sourceHandler.getSource(sourceIdRequestBody)); } @Override public void deleteSource(final SourceIdRequestBody sourceIdRequestBody) { execute(() -> { sourceHandler.deleteSource(sourceIdRequestBody); return null; }); } @Override public CheckConnectionRead checkConnectionToSource(final SourceIdRequestBody sourceIdRequestBody) { return execute(() -> schedulerHandler.checkSourceConnectionFromSourceId(sourceIdRequestBody)); } @Override public CheckConnectionRead checkConnectionToSourceForUpdate(final SourceUpdate sourceUpdate) { return execute(() -> schedulerHandler.checkSourceConnectionFromSourceIdForUpdate(sourceUpdate)); } @Override public SourceDiscoverSchemaRead discoverSchemaForSource(final SourceIdRequestBody sourceIdRequestBody) { return execute(() -> schedulerHandler.discoverSchemaForSourceFromSourceId(sourceIdRequestBody)); } // DB MIGRATION @Override public DbMigrationReadList listMigrations(final DbMigrationRequestBody request) { return execute(() -> dbMigrationHandler.list(request)); } @Override public DbMigrationExecutionRead executeMigrations(final DbMigrationRequestBody request) { return execute(() -> dbMigrationHandler.migrate(request)); } // DESTINATION @Override public DestinationDefinitionReadList listDestinationDefinitions() { return execute(destinationDefinitionsHandler::listDestinationDefinitions); } @Override public DestinationDefinitionReadList listLatestDestinationDefinitions() { return execute(destinationDefinitionsHandler::listLatestDestinationDefinitions); } @Override public DestinationDefinitionRead getDestinationDefinition(final DestinationDefinitionIdRequestBody destinationDefinitionIdRequestBody) { return execute(() -> destinationDefinitionsHandler.getDestinationDefinition(destinationDefinitionIdRequestBody)); } @Override public DestinationDefinitionRead createDestinationDefinition(final DestinationDefinitionCreate destinationDefinitionCreate) { return execute(() -> destinationDefinitionsHandler.createDestinationDefinition(destinationDefinitionCreate)); } @Override public DestinationDefinitionRead updateDestinationDefinition(final DestinationDefinitionUpdate destinationDefinitionUpdate) { return execute(() -> destinationDefinitionsHandler.updateDestinationDefinition(destinationDefinitionUpdate)); } // DESTINATION SPECIFICATION @Override public DestinationDefinitionSpecificationRead getDestinationDefinitionSpecification(final DestinationDefinitionIdRequestBody destinationDefinitionIdRequestBody) { return execute(() -> schedulerHandler.getDestinationSpecification(destinationDefinitionIdRequestBody)); } // DESTINATION IMPLEMENTATION @Override public DestinationRead createDestination(final DestinationCreate destinationCreate) { return execute(() -> destinationHandler.createDestination(destinationCreate)); } @Override public void deleteDestination(final DestinationIdRequestBody destinationIdRequestBody) { execute(() -> { destinationHandler.deleteDestination(destinationIdRequestBody); return null; }); } @Override public DestinationRead updateDestination(final DestinationUpdate destinationUpdate) { return execute(() -> destinationHandler.updateDestination(destinationUpdate)); } @Override public DestinationReadList listDestinationsForWorkspace(final WorkspaceIdRequestBody workspaceIdRequestBody) { return execute(() -> destinationHandler.listDestinationsForWorkspace(workspaceIdRequestBody)); } @Override public DestinationRead getDestination(final DestinationIdRequestBody destinationIdRequestBody) { return execute(() -> destinationHandler.getDestination(destinationIdRequestBody)); } @Override public CheckConnectionRead checkConnectionToDestination(final DestinationIdRequestBody destinationIdRequestBody) { return execute(() -> schedulerHandler.checkDestinationConnectionFromDestinationId(destinationIdRequestBody)); } @Override public CheckConnectionRead checkConnectionToDestinationForUpdate(final DestinationUpdate destinationUpdate) { return execute(() -> schedulerHandler.checkDestinationConnectionFromDestinationIdForUpdate(destinationUpdate)); } // CONNECTION @Override public ConnectionRead createConnection(final ConnectionCreate connectionCreate) { return execute(() -> connectionsHandler.createConnection(connectionCreate)); } @Override public ConnectionRead updateConnection(final ConnectionUpdate connectionUpdate) { return execute(() -> connectionsHandler.updateConnection(connectionUpdate)); } @Override public ConnectionReadList listConnectionsForWorkspace(final WorkspaceIdRequestBody workspaceIdRequestBody) { return execute(() -> connectionsHandler.listConnectionsForWorkspace(workspaceIdRequestBody)); } @Override public ConnectionRead getConnection(final ConnectionIdRequestBody connectionIdRequestBody) { return execute(() -> connectionsHandler.getConnection(connectionIdRequestBody)); } @Override public void deleteConnection(final ConnectionIdRequestBody connectionIdRequestBody) { execute(() -> { operationsHandler.deleteOperationsForConnection(connectionIdRequestBody); connectionsHandler.deleteConnection(connectionIdRequestBody); return null; }); } @Override public JobInfoRead syncConnection(final ConnectionIdRequestBody connectionIdRequestBody) { return execute(() -> schedulerHandler.syncConnection(connectionIdRequestBody)); } @Override public JobInfoRead resetConnection(final ConnectionIdRequestBody connectionIdRequestBody) { return execute(() -> schedulerHandler.resetConnection(connectionIdRequestBody)); } // Operations @Override public CheckOperationRead checkOperation(final OperatorConfiguration operatorConfiguration) { return execute(() -> operationsHandler.checkOperation(operatorConfiguration)); } @Override public OperationRead createOperation(final OperationCreate operationCreate) { return execute(() -> operationsHandler.createOperation(operationCreate)); } @Override public void deleteOperation(final OperationIdRequestBody operationIdRequestBody) { execute(() -> { operationsHandler.deleteOperation(operationIdRequestBody); return null; }); } @Override public OperationReadList listOperationsForConnection(final ConnectionIdRequestBody connectionIdRequestBody) { return execute(() -> operationsHandler.listOperationsForConnection(connectionIdRequestBody)); } @Override public OperationRead getOperation(final OperationIdRequestBody operationIdRequestBody) { return execute(() -> operationsHandler.getOperation(operationIdRequestBody)); } @Override public OperationRead updateOperation(final OperationUpdate operationUpdate) { return execute(() -> operationsHandler.updateOperation(operationUpdate)); } @Override public ConnectionState getState(final ConnectionIdRequestBody connectionIdRequestBody) { return execute(() -> schedulerHandler.getState(connectionIdRequestBody)); } // SCHEDULER @Override public CheckConnectionRead executeSourceCheckConnection(final SourceCoreConfig sourceConfig) { return execute(() -> schedulerHandler.checkSourceConnectionFromSourceCreate(sourceConfig)); } @Override public CheckConnectionRead executeDestinationCheckConnection(final DestinationCoreConfig destinationConfig) { return execute(() -> schedulerHandler.checkDestinationConnectionFromDestinationCreate(destinationConfig)); } @Override public SourceDiscoverSchemaRead executeSourceDiscoverSchema(final SourceCoreConfig sourceCreate) { return execute(() -> schedulerHandler.discoverSchemaForSourceFromSourceCreate(sourceCreate)); } @Override public JobInfoRead cancelJob(final JobIdRequestBody jobIdRequestBody) { return execute(() -> schedulerHandler.cancelJob(jobIdRequestBody)); } // JOB HISTORY @Override public JobReadList listJobsFor(final JobListRequestBody jobListRequestBody) { return execute(() -> jobHistoryHandler.listJobsFor(jobListRequestBody)); } @Override public JobInfoRead getJobInfo(final JobIdRequestBody jobIdRequestBody) { return execute(() -> jobHistoryHandler.getJobInfo(jobIdRequestBody)); } @Override public File getLogs(final LogsRequestBody logsRequestBody) { return execute(() -> logsHandler.getLogs(configs, logsRequestBody)); } @Override public File getOpenApiSpec() { return execute(openApiConfigHandler::getFile); } // HEALTH @Override public HealthCheckRead getHealthCheck() { return healthCheckHandler.health(); } // WEB BACKEND @Override public WebBackendConnectionReadList webBackendListConnectionsForWorkspace(final WorkspaceIdRequestBody workspaceIdRequestBody) { return execute(() -> webBackendConnectionsHandler.webBackendListConnectionsForWorkspace(workspaceIdRequestBody)); } @Override public WebBackendConnectionReadList webBackendConnectionSearch(final WebBackendConnectionSearch webBackendConnectionSearch) { return execute(() -> webBackendConnectionsHandler.webBackendSearchConnections(webBackendConnectionSearch)); } @Override public WebBackendConnectionRead webBackendGetConnection(final WebBackendConnectionRequestBody webBackendConnectionRequestBody) { return execute(() -> webBackendConnectionsHandler.webBackendGetConnection(webBackendConnectionRequestBody)); } @Override public WebBackendConnectionRead webBackendCreateConnection(final WebBackendConnectionCreate webBackendConnectionCreate) { return execute(() -> webBackendConnectionsHandler.webBackendCreateConnection(webBackendConnectionCreate)); } @Override public WebBackendConnectionRead webBackendUpdateConnection(final WebBackendConnectionUpdate webBackendConnectionUpdate) { return execute(() -> webBackendConnectionsHandler.webBackendUpdateConnection(webBackendConnectionUpdate)); } @Override public SourceRead webBackendCreateSource(final SourceCreate sourceCreate) { return execute(() -> webBackendSourcesHandler.webBackendCreateSource(sourceCreate)); } @Override public DestinationRead webBackendCreateDestination(final DestinationCreate destinationCreate) { return execute(() -> webBackendDestinationsHandler.webBackendCreateDestination(destinationCreate)); } // ARCHIVES @Override public File exportArchive() { return execute(archiveHandler::exportData); } @Override public ImportRead importArchive(final File archiveFile) { return execute(() -> archiveHandler.importData(archiveFile)); } @Override public File exportWorkspace(final WorkspaceIdRequestBody workspaceIdRequestBody) { return execute(() -> archiveHandler.exportWorkspace(workspaceIdRequestBody)); } @Override public UploadRead uploadArchiveResource(final File archiveFile) { return execute(() -> archiveHandler.uploadArchiveResource(archiveFile)); } @Override public ImportRead importIntoWorkspace(final ImportRequestBody importRequestBody) { return execute(() -> archiveHandler.importIntoWorkspace(importRequestBody)); } private <T> T execute(final HandlerCall<T> call) { try { return call.call(); } catch (final ConfigNotFoundException e) { throw new IdNotFoundKnownException(String.format("Could not find configuration for %s: %s.", e.getType().toString(), e.getConfigId()), e.getConfigId(), e); } catch (final JsonValidationException e) { throw new BadObjectSchemaKnownException( String.format("The provided configuration does not fulfill the specification. Errors: %s", e.getMessage()), e); } catch (final IOException e) { throw new RuntimeException(e); } } private interface HandlerCall<T> { T call() throws ConfigNotFoundException, IOException, JsonValidationException; } }
/* * Copyright 2021 Red Hat, Inc. and/or its affiliates. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.kie.server.api.model; import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.Set; import org.assertj.core.api.Assertions; import org.drools.core.command.runtime.BatchExecutionCommandImpl; import org.drools.core.command.runtime.rule.InsertObjectCommand; import org.junit.Test; import org.kie.api.KieServices; import org.kie.api.command.BatchExecutionCommand; import org.kie.api.command.Command; import org.kie.api.command.KieCommands; import org.kie.server.api.marshalling.BaseMarshallerBuilder; import org.kie.server.api.marshalling.Marshaller; import org.kie.server.api.marshalling.MarshallerBuilder; import org.kie.server.api.marshalling.MarshallingFormat; import org.kie.server.api.marshalling.objects.Pojo1; import org.kie.server.api.marshalling.objects.Pojo2; import org.kie.server.api.marshalling.objects.Pojo3; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import static org.junit.Assert.assertEquals; public class DroolsCommandNestedPojoMarshallingTest { private static final Logger logger = LoggerFactory.getLogger(DroolsCommandNestedPojoMarshallingTest.class); // NOTE: These expected payloads are actual results as of current version. They could be changed with a good reason. private static final String jaxbExpectedPayload = "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?>\n" + "<batch-execution>\n" + " <insert out-identifier=\"fact-pojo1\" return-object=\"true\" entry-point=\"DEFAULT\" disconnected=\"false\">\n" + " <object xsi:type=\"pojo1\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\">\n" + " <desc>C</desc>\n" + " <pojo2>\n" + " <desc2>B</desc2>\n" + " <pojo3>\n" + " <desc3>A</desc3>\n" + " </pojo3>\n" + " <primitiveBoolean>true</primitiveBoolean>\n" + " </pojo2>\n" + " </object>\n" + " </insert>\n" + " <fire-all-rules max=\"-1\" out-identifier=\"fire-result\"/>\n" + "</batch-execution>\n"; private static final String xstreamExpectedPayload = "<batch-execution>\n" + " <insert out-identifier=\"fact-pojo1\" return-object=\"true\" entry-point=\"DEFAULT\">\n" + " <org.kie.server.api.marshalling.objects.Pojo1>\n" + " <desc>C</desc>\n" + " <pojo2>\n" + " <desc2>B</desc2>\n" + " <primitiveBoolean>true</primitiveBoolean>\n" + " <pojo3>\n" + " <desc3>A</desc3>\n" + " </pojo3>\n" + " </pojo2>\n" + " </org.kie.server.api.marshalling.objects.Pojo1>\n" + " </insert>\n" + " <fire-all-rules out-identifier=\"fire-result\"/>\n" + "</batch-execution>"; private static final String jsonExpectedPayload = "{\n" + " \"lookup\" : null,\n" + " \"commands\" : [ {\n" + " \"insert\" : {\n" + " \"object\" : {\"org.kie.server.api.marshalling.objects.Pojo1\":{\n" + " \"desc\" : \"C\",\n" + " \"pojo2\" : {\n" + " \"desc2\" : \"B\",\n" + " \"primitiveBoolean\" : true,\n" + " \"pojo3\" : {\n" + " \"desc3\" : \"A\"\n" + " }\n" + " }\n" + "}},\n" + " \"out-identifier\" : \"fact-pojo1\",\n" + " \"return-object\" : true,\n" + " \"entry-point\" : \"DEFAULT\",\n" + " \"disconnected\" : false\n" + " }\n" + " }, {\n" + " \"fire-all-rules\" : {\n" + " \"max\" : -1,\n" + " \"agendaFilter\" : null,\n" + " \"out-identifier\" : \"fire-result\"\n" + " }\n" + " } ]\n" + "}"; private MarshallerBuilder marshallerBuilder = new BaseMarshallerBuilder(); // don't use MarshallerFactory to avoid CustomXstreamMarshallerBuilder private static BatchExecutionCommand createTestCommand() { KieCommands commandsFactory = KieServices.Factory.get().getCommands(); List<Command<?>> commands = new ArrayList<Command<?>>(); Pojo3 pojo3 = new Pojo3("A"); Pojo2 pojo2 = new Pojo2("B", true, pojo3); Pojo1 pojo1 = new Pojo1("C", pojo2); commands.add(commandsFactory.newInsert(pojo1, "fact-pojo1")); commands.add(commandsFactory.newFireAllRules("fire-result")); BatchExecutionCommand batchExecution = commandsFactory.newBatchExecution(commands); return batchExecution; } private Set<Class<?>> getCustomClasses() { HashSet<Class<?>> classes = new HashSet<Class<?>>(); classes.add(Pojo1.class); classes.add(Pojo2.class); classes.add(Pojo3.class); return classes; } @Test public void testJaxb() { Marshaller marshaller = marshallerBuilder.build(getCustomClasses(), MarshallingFormat.JAXB, getClass().getClassLoader()); verifyMarshallingRoundTrip(marshaller, createTestCommand(), jaxbExpectedPayload); } @Test public void testXStream() { Marshaller marshaller = marshallerBuilder.build(getCustomClasses(), MarshallingFormat.XSTREAM, getClass().getClassLoader()); verifyMarshallingRoundTrip(marshaller, createTestCommand(), xstreamExpectedPayload); } @Test public void testJSON() { Marshaller marshaller = marshallerBuilder.build(getCustomClasses(), MarshallingFormat.JSON, getClass().getClassLoader()); verifyMarshallingRoundTrip(marshaller, createTestCommand(), jsonExpectedPayload); } private void verifyMarshallingRoundTrip(Marshaller marshaller, BatchExecutionCommand inputCommand, String expectedPayload) { String rawContent = marshaller.marshall(inputCommand); logger.debug(rawContent); Assertions.assertThat(rawContent).isEqualToIgnoringWhitespace(expectedPayload); BatchExecutionCommandImpl inputBatch = (BatchExecutionCommandImpl) inputCommand; BatchExecutionCommandImpl resultBatch = (BatchExecutionCommandImpl) marshaller.unmarshall(rawContent, inputCommand.getClass()); assertEquals(inputBatch.getLookup(), resultBatch.getLookup()); assertEquals(inputBatch.getDistance(), resultBatch.getDistance()); InsertObjectCommand inputInsert = (InsertObjectCommand) inputBatch.getCommands().get(0); InsertObjectCommand resultInsert = (InsertObjectCommand) resultBatch.getCommands().get(0); assertEquals(inputInsert.getEntryPoint(), resultInsert.getEntryPoint()); assertEquals(inputInsert.getObject(), resultInsert.getObject()); assertEquals(inputInsert.getOutIdentifier(), resultInsert.getOutIdentifier()); assertEquals(inputInsert.isDisconnected(), resultInsert.isDisconnected()); assertEquals(inputInsert.isReturnObject(), resultInsert.isReturnObject()); } }
/* Copyright (c) 2020 Seva Safris, LibJ * Copyright (c) 2015-2016 Simon Klein, Google Inc. * * 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 AUTHOR 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 AUTHOR 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. * * The views and conclusions contained in the software and documentation are * those of the authors and should not be interpreted as representing official * policies, either expressed or implied, of the Huldra and the LibJ projects. */ package org.libj.math; import java.math.BigDecimal; import java.math.BigInteger; import java.math.RoundingMode; /** * An arbitrary-precision integer replacement for {@link java.math.BigInteger}, * with the following differences: * <ol> * <li><b>Mutable:</b> {@link BigInt} is mutable, to allow for reuse of * allocated arrays.</li> * <li><b>Faster arithmetic:</b> The arithmetic algorithms in {@link BigInt} are * implemented with the optimization of memory (heap allocation) and runtime * performance in mind.</li> * <li><b>Faster multiplication of large numbers:</b> Support parallel * multiplication algorithm for very large numbers.</li> * <li><b>Support for {@code int} and {@code long} parameters and return * types:</b> {@link BigInt} does not require its parameters or return types to * be {@link BigInt}, avoiding unnecessary instantiation of transient * {@link BigInt} objects.</li> * <li><b>No preemptive exception checking:</b> The {@link BigInt} does not * preemptively check for exceptions. If a programmer divides by zero he has * only himself to blame. And, it is ok to have undefined behavior.</li> * <li><b>Support for "object-less" operation</b> All methods in {@link BigInt} * are available in static form, allowing <i>bare {@code int[]} * {@linkplain #val() value-encoded number} arrays</i> to be used without a * {@link BigInt} instance, providing further reduction in heap memory * allocation.</li> * </ol> * * @author Seva Safris */ public class BigInt extends BigIntMath implements Comparable<BigInt>, Cloneable { /** * The {@linkplain #val() value-encoded number}. * * @see #val() */ private int[] val; /** * Returns the <i>{@linkplain #val() value-encoded number}</i>, which is an * {@code int[]} with the following encoding: * <ol> * <li><b>{@code val[0]}</b>: <i>signed length</i>: * <code>[-1 &lt;&lt; 26, .., -1, 0, 1, .., 1 &lt;&lt; 26]</code><br> * <ul> * <li>{@code Math.abs(val[0])}: The number of base-2<sup>32</sup> digits * (limbs) in the magnitude.</li> * <li>{@code Math.signum(val[0])}: The sign of the magnitude ({@code -1} for * negative, and {@code 1} for positive).</li> * <li>{@code val[0] == 0}: Magnitude is zero.</li> * </ul> * </li> * <li><b>{@code val[2,val[0]-1]}</b>: <i>digits</i>: * {@code [Integer.MIN_VALUE, Integer.MAX_VALUE]} * <ul> * <li>The base-2<sup>32</sup> digits of the number in <i>little-endian</i> * order.</li> * </ul> * </ol> * * @return The <i>{@linkplain #val() value-encoded number}</i>. */ public int[] val() { return val; } /** * Creates a {@link BigInt} from the provided {@linkplain #val() value-encoded * number}. * * @implNote The provided array will be used used as-is and not copied. * @param val The {@linkplain #val() value-encoded number}. * @complexity O(1) */ public BigInt(final int[] val) { this.val = val; } /** * Creates a {@link BigInt} from the provided byte array containing the * two's-complement binary representation of a {@linkplain #val() * value-encoded <code>int[]</code>}. * * @param mag The two's-complement binary representation of a * {@linkplain #val() value-encoded <code>int[]</code>}. * @param off The start offset of the binary representation. * @param len The number of bytes to use. * @param littleEndian Whether the specified byte array is encoded in * <i>little-endian</i> ({@code true}), or <i>big-endian</i> * ({@code false}). * @complexity O(n^2) */ public BigInt(final byte[] mag, int off, int len, final boolean littleEndian) { val = assign(emptyVal, mag, off, len, littleEndian); } /** * Creates a {@link BigInt} from the provided byte array containing the * two's-complement binary representation of a {@linkplain #val() * value-encoded <code>int[]</code>}. * * @param mag The two's-complement binary representation of a * {@linkplain #val() value-encoded <code>int[]</code>}. * @param littleEndian Whether the specified byte array is encoded in * <i>little-endian</i> ({@code true}), or <i>big-endian</i> * ({@code false}). * @complexity O(n^2) */ public BigInt(final byte[] mag, final boolean littleEndian) { val = assign(emptyVal, mag, 0, mag.length, littleEndian); } /** * Creates a {@link BigInt} from the provided <i>unsigned</i> {@code int} * magnitude. * * @param sig The sign of the unsigned {@code int}. * @param mag The magnitude (unsigned). * @complexity O(1) */ public BigInt(final int sig, final int mag) { val = mag == 0 ? alloc(1) : assignInPlace(alloc(2), sig, mag); } /** * Creates a {@link BigInt} from the provided <i>unsigned</i> {@code long} * magnitude. * * @param sig The sign of the unsigned {@code int}. * @param mag The magnitude (unsigned). * @complexity O(1) */ public BigInt(final int sig, final long mag) { if (mag == 0) { val = alloc(1); } else { final int magh = (int)(mag >>> 32); val = magh != 0 ? assignInPlace(alloc(3), sig, (int)mag, magh) : assignInPlace(alloc(2), sig, (int)mag); } } /** * Creates a {@link BigInt} from the provided {@code int} magnitude. * * @param mag The magnitude. * @complexity O(1) */ public BigInt(final int mag) { val = mag == 0 ? alloc(1) : mag < 0 ? assignInPlace(alloc(2), -1, -mag) : assignInPlace(alloc(2), 1, mag); } /** * Creates a {@link BigInt} from the provided {@code long} magnitude. * * @param mag The magnitude. * @complexity O(1) */ public BigInt(long mag) { if (mag == 0) { val = alloc(1); } else { int sig = 1; if (mag < 0) { mag = -mag; sig = -1; } final int magh = (int)(mag >>> 32); val = magh != 0 ? assignInPlace(alloc(3), sig, (int)mag, magh) : assignInPlace(alloc(2), sig, (int)mag); } } /** * Creates a {@link BigInt} from the provided number as a string. * * @param s The number as a string. * @complexity O(n) */ public BigInt(final String s) { val = assign(emptyVal, s); } /** * Creates a {@link BigInt} from the provided number as a {@code char[]}. * * @param s The number as a string. * @complexity O(n) */ public BigInt(final char[] s) { val = assign(emptyVal, s); } /** * Creates a {@link BigInt} from the provided {@link BigInt}. * * @implNote This is a <i>copy constructor</i> that sets the * {@linkplain #val() value-encoded number} of this {@link BigInt} * to a <b>clone</b> of the {@linkplain #val() value-encoded number} * of the provided {@link BigInt}. * @param b The {@link BigInt}. * @complexity O(n) * @see #clone() */ public BigInt(final BigInt b) { val = b.val.clone(); } /** * Creates a {@link BigInt} with the * magnitude of the provided {@link BigInteger}. * * @param b The {@link BigInteger}. * @complexity O(n^2) */ public BigInt(final BigInteger b) { val = valueOf(b); } /** * Assigns (copies) the value of the provided {@link BigInt} to this * {@link BigInt}. * * <pre> * this = b * </pre> * * @param b The {@link BigInt}. * @return {@code this} */ public BigInt assign(final BigInt b) { final int len = Math.abs(val[0]) + 1; copy(b.val, len, val, len); return this; } /** * Assigns the specified {@linkplain #val() value-encoded number} to this * {@link BigInt}. * * <pre> * this = val * </pre> * * @implNote The provided array will be copied. * @param val The {@linkplain #val() value-encoded number}. * @return {@code this} * @complexity O(1) */ public BigInt assign(final int[] val) { this.val = assign(this.val, val); // _debugLenSig(val); return this; } /** * Assigns a byte array containing the two's-complement binary representation * of a {@linkplain #val() value-encoded <code>int[]</code>} to this * {@link BigInt}. * * <pre> * this = mag * </pre> * * @param mag The two's-complement binary representation of a * {@linkplain #val() value-encoded <code>int[]</code>}. * @param off The start offset of the binary representation. * @param len The number of bytes to use. * @param littleEndian Whether the specified byte array is encoded in * <i>little-endian</i> ({@code true}), or <i>big-endian</i> * ({@code false}). * @return {@code this} * @complexity O(n^2) */ public BigInt assign(final byte[] mag, final int off, final int len, final boolean littleEndian) { val = assign(val, mag, off, len, littleEndian); return this; } /** * Assigns a byte array containing the two's-complement binary representation * of a {@linkplain #val() value-encoded <code>int[]</code>} to this * {@link BigInt}. * * <pre> * this = mag * </pre> * * @param mag The two's-complement binary representation of a * {@linkplain #val() value-encoded <code>int[]</code>}. * @param littleEndian Whether the specified byte array is encoded in * <i>little-endian</i> ({@code true}), or <i>big-endian</i> * ({@code false}). * @return {@code this} * @complexity O(n^2) */ public BigInt assign(final byte[] mag, final boolean littleEndian) { val = assign(val, mag, 0, mag.length, littleEndian); return this; } /** * Assigns the specified number as a string to this {@link BigInt}. * * <pre> * this = s * </pre> * * @param s The number as a {@code char[]}. * @return {@code this} * @complexity O(n^2) */ public BigInt assign(final String s) { val = assign(val, s); return this; } /** * Assigns the specified number as a {@code char[]} to this {@link BigInt}. * * <pre> * this = s * </pre> * * @param s The number as a {@code char[]}. * @return {@code this} * @complexity O(n^2) */ public BigInt assign(final char[] s) { val = assign(val, s); return this; } /** * Assigns an <i>unsigned</i> {@code int} magnitude to this {@link BigInt}. * * <pre> * this = mag * </pre> * * @param sig The sign of the unsigned {@code int}. * @param mag The magnitude (unsigned). * @return {@code this} * @complexity O(1) */ public BigInt assign(final int sig, final int mag) { val = assign(val, sig, mag); return this; } /** * Assigns an <i>unsigned</i> {@code long} magnitude to this {@link BigInt}. * * <pre> * this = mag * </pre> * * @param sig The sign of the unsigned {@code int}. * @param mag The magnitude (unsigned). * @return {@code this} * @complexity O(1) */ public BigInt assign(final int sig, final long mag) { val = assign(val, sig, mag); return this; } /** * Assigns an {@code int} magnitude to this {@link BigInt}. * * <pre> * this = mag * </pre> * * @param mag The magnitude. * @return {@code this} * @complexity O(1) */ public BigInt assign(final int mag) { val = assign(val, mag); return this; } /** * Assigns an {@code long} magnitude to this {@link BigInt}. * * <pre> * this = mag * </pre> * * @param mag The magnitude. * @return {@code this} * @complexity O(1) */ public BigInt assign(final long mag) { val = assign(val, mag); return this; } /** * Sets the magnitude of this {@link BigInt} to its absolute value. * * <pre> * this = | this | * </pre> * * @return {@code this} * @complexity O(1) */ public BigInt abs() { abs(val); return this; } /** * Sets the magnitude of this {@link BigInt} to its negated value. * * <pre> * this = -this * </pre> * * @return {@code this} */ public BigInt neg() { neg(val); return this; } /** * Returns the maximum of {@code this} and {@code v}. * * @param v Value with which the maximum is to be computed. * @return The {@link BigInt} whose value is the greater of {@code this} and * {@code v}. If they are equal, {@code v} will be returned. */ public BigInt max(final BigInt v) { return compareTo(v) > 0 ? this : v; } /** * Returns the minimum of {@code this} and {@code v}. * * @param v Value with which the minimum is to be computed. * @return The {@link BigInt} whose value is the greater of {@code this} and * {@code v}. If they are equal, {@code v} will be returned. */ public BigInt min(final BigInt v) { return compareTo(v) < 0 ? this : v; } /** * Returns the signum of this {@link BigInt}. * * @return -1, 0 or 1 as the value of the provided {@linkplain #val() * value-encoded number} is negative, zero or positive. * @complexity O(1) */ public int signum() { return signum(val); } /** * Tests if this {@link BigInt} is zero. * * @return {@code true} if this {@link BigInt} is zero, otherwise * {@code false}. * @complexity O(1) */ public boolean isZero() { return isZero(val); } /** * Sets this {@link BigInt} to zero. * * @return {@code this} * @complexity O(1) */ public BigInt setToZero() { setToZero(val); return this; } /** * Adds an <i>unsigned</i> {@code int} to this {@link BigInt}. * * <pre> * this = this + add * </pre> * * @param sig The sign of the unsigned {@code int} to add. * @param add The amount to add (unsigned). * @return {@code this} * @complexity O(n) */ public BigInt add(final int sig, final int add) { val = add(val, sig, add); return this; } /** * Adds an {@code int} to this {@link BigInt}. * * <pre> * this = this + add * </pre> * * @param add The amount to add. * @return {@code this} * @complexity O(n) */ public BigInt add(final int add) { val = add(val, add); return this; } /** * Adds an <i>unsigned</i> {@code long} to this {@link BigInt}. * * <pre> * this = this + add * </pre> * * @param sig The sign of the unsigned {@code long} to add. * @param add The amount to add (unsigned). * @return {@code this} * @complexity O(n) */ public BigInt add(final int sig, final long add) { val = add(val, sig, add); return this; } /** * Adds a {@code long} to this {@link BigInt}. * * <pre> * this = this + add * </pre> * * @param add The amount to add. * @return {@code this} * @complexity O(n) */ public BigInt add(final long add) { val = add(val, add); return this; } /** * Adds a {@link BigInt} to this {@link BigInt}. * * <pre> * this = this + add * </pre> * * @param add The {@link BigInt} to add. * @return {@code this} * @complexity O(n) */ public BigInt add(final BigInt add) { val = add(val, add.val); return this; } /** * Subtracts an <i>unsigned</i> {@code int} from this {@link BigInt}. * * <pre> * this = this - sub * </pre> * * @param sig The sign of the unsigned {@code int} to subtract. * @param sub The amount to subtract (unsigned). * @return {@code this} * @complexity O(n) */ public BigInt sub(final int sig, final int sub) { val = sub(val, sig, sub); return this; } /** * Subtracts an {@code int} from this {@link BigInt}. * * <pre> * this = this - sub * </pre> * * @param sub The amount to subtract. * @return {@code this} * @complexity O(n) */ public BigInt sub(final int sub) { val = sub(val, sub); return this; } /** * Subtracts an <i>unsigned</i> {@code long} from this {@link BigInt}. * * <pre> * this = this - sub * </pre> * * @param sig The sign of the unsigned {@code long} to subtract. * @param sub The amount to subtract (unsigned). * @return {@code this} * @complexity O(n) */ public BigInt sub(final int sig, final long sub) { val = sub(val, sig, sub); return this; } /** * Subtracts a {@code long} from this {@link BigInt}. * * <pre> * this = this - sub * </pre> * * @param sub The amount to subtract. * @return {@code this} * @complexity O(n) */ public BigInt sub(final long sub) { val = sub(val, sub); return this; } /** * Subtracts a {@link BigInt} from this {@link BigInt}. * * <pre> * this = this - sub * </pre> * * @param sub The {@link BigInt} to subtract. * @return {@code this} * @complexity O(n) */ public BigInt sub(final BigInt sub) { val = sub(val, sub.val); return this; } /** * Multiplies this {@link BigInt} by an <i>unsigned</i> {@code int} * multiplicand. * * <pre> * this = this * mul * </pre> * * @param sig The sign of the unsigned {@code int} multiplier. * @param mul The multiplier (unsigned). * @return {@code this} * @complexity O(n) */ public BigInt mul(final int sig, final int mul) { val = mul(val, sig, mul); return this; } /** * Multiplies this {@link BigInt} by an {@code int} multiplicand. * * <pre> * this = this * mul * </pre> * * @param mul The multiplier. * @return {@code this} * @complexity O(n) */ public BigInt mul(final int mul) { val = mul(val, mul); return this; } /** * Multiplies this {@link BigInt} by an <i>unsigned</i> {@code long} * multiplicand. * * <pre> * this = this * mul * </pre> * * @param sig The sign of the unsigned {@code int} multiplier. * @param mul The multiplier (unsigned). * @return {@code this} * @complexity O(n) */ public BigInt mul(final int sig, final long mul) { val = mul(val, sig, mul); return this; } /** * Multiplies this {@link BigInt} by a {@code long} multiplicand. * * <pre> * this = this * mul * </pre> * * @param mul The multiplier. * @return {@code this} * @complexity O(n) */ public BigInt mul(final long mul) { val = mul(val, mul); return this; } /** * Multiplies this {@link BigInt} by a {@link BigInt} multiplicand. * * <pre> * this = this * mul * </pre> * * @param mul The multiplier. * @return {@code this} * @complexity O(n^2) - O(n log n) */ public BigInt mul(final BigInt mul) { val = mul(val, mul.val); return this; } /** * Raises this {@link BigInt} to the power of the given exponent. * * <blockquote> * <code>this = this<sup>exp</sup></code> * </blockquote> * * If {@code exp < 0}, {@code this} is set to {@code 0}. * * @param exp The exponent to which this {@link BigInt} is to be raised. * @return <code>this<sup>exp</sup></code> * @complexity O(n^2 log exp) - O(n log n log exp) */ public BigInt pow(final int exp) { val = pow(val, exp); return this; } /** * Set this {@link BigInt} to the value of its square root, rounded as per the * provided {@link RoundingMode}. * * <blockquote> * <code>this = this<sup>1/2</sup></code> * </blockquote> * * @param rm The {@link RoundingMode}. * @return <code>this<sup>1/2</sup></code>, rounded as per the provided * {@link RoundingMode}. * @complexity O(n^2) - O(n log n) */ public BigInt sqrt(final RoundingMode rm) { val = sqrt(val, rm); return this; } /** * Set this {@link BigInt} to the value of its square root, rounding down. * * <blockquote> * <code>this = this<sup>1/2</sup></code> * </blockquote> * * @return <code>this<sup>1/2</sup></code>, rounded down. * @complexity O(n^2) - O(n log n) */ public BigInt sqrt() { val = sqrt(val, RoundingMode.DOWN); return this; } /** * Set this {@link BigInt} to the value of its natural logarithm, rounded as * per the provided {@link RoundingMode}. * * <pre> * this = log(this) * </pre> * * @param rm The {@link RoundingMode}. * @return {@code log(this)}, rounded as per the provided * {@link RoundingMode}. * @complexity O(1) */ public int log(final RoundingMode rm) { return log(val, rm); } /** * Set this {@link BigInt} to the value of its natural logarithm, rounded down. * * <pre> * this = log(this) * </pre> * * @return {@code log(this)}, rounded down. * @complexity O(1) */ public int log() { return log(val, RoundingMode.DOWN); } /** * Set this {@link BigInt} to the value of its logarithm of base {@code base}, * rounded as per the provided {@link RoundingMode}. * * <blockquote> * <code>this = log<sub>base</sub>(this)</code> * </blockquote> * * @param base The base of the logarithm. * @param rm The {@link RoundingMode}. * @return <code>log<sub>base</sub>(this)</code>, rounded as per the provided * {@link RoundingMode}. * @complexity O(1) */ public int log(final double base, final RoundingMode rm) { return log(val, base, rm); } /** * Set this {@link BigInt} to the value of its logarithm of base {@code base}, * rounded down. * * <blockquote> * <code>this = log<sub>base</sub>(this)</code> * </blockquote> * * @param base The base of the logarithm. * @return <code>log<sub>base</sub>(this)</code>, rounded down. * @complexity O(1) */ public int log(final double base) { return log(val, base, RoundingMode.DOWN); } /** * Set this {@link BigInt} to the value of its logarithm of base {@code 2}, * rounded as per the provided {@link RoundingMode}. * * <blockquote> * <code>this = log<sub>2</sub>(this)</code> * </blockquote> * * @param rm The {@link RoundingMode}. * @return <code>log<sub>2</sub>(this)</code>, rounded as per the provided * {@link RoundingMode}. * @complexity O(1) */ public int log2(final RoundingMode rm) { return log2(val, rm); } /** * Set this {@link BigInt} to the value of its logarithm of base {@code base}, * rounded down. * * <blockquote> * <code>this = log<sub>2</sub>(this)</code> * </blockquote> * * @return <code>log<sub>2</sub>(this)</code>, rounded down. * @complexity O(1) */ public int log2() { return log2(val, RoundingMode.DOWN); } /** * Set this {@link BigInt} to the value of its logarithm of base {@code 2}, * rounded as per the provided {@link RoundingMode}. * * <blockquote> * <code>this = log<sub>10</sub>(this)</code> * </blockquote> * * @param rm The {@link RoundingMode}. * @return <code>log<sub>10</sub>(this)</code>, rounded as per the provided * {@link RoundingMode}. * @complexity O(1) */ public int log10(final RoundingMode rm) { return log10(val, rm); } /** * Set this {@link BigInt} to the value of its logarithm of base {@code base}, * rounded down. * * <blockquote> * <code>this = log<sub>10</sub>(this)</code> * </blockquote> * * @return <code>log<sub>10</sub>(this)</code>, rounded down. * @complexity O(1) */ public int log10() { return log10(val, RoundingMode.DOWN); } /** * Divides this {@link BigInt} by the provided <i>unsigned</i> {@code int} * divisor. * * <pre> * this = this / div * </pre> * * @param sig The sign of the unsigned {@code int} divisor. * @param div The divisor (unsigned). * @return {@code this} * @complexity O(n^2) */ public BigInt div(final int sig, final int div) { divRem(val, sig, div); return this; } /** * Divides this {@link BigInt} by the provided {@code int} divisor. * * <pre> * this = this / div * </pre> * * @param div The divisor. * @return {@code this} * @complexity O(n^2) */ public BigInt div(final int div) { divRem(val, div); return this; } /** * Divides this {@link BigInt} by the provided <i>unsigned</i> {@code long} * divisor. * * <pre> * this = this / div * </pre> * * @param sig The sign of the unsigned {@code long} divisor. * @param div The divisor (unsigned). * @return {@code this} * @complexity O(n^2) */ public BigInt div(final int sig, final long div) { divRem(val, sig, div); return this; } /** * Divides this {@link BigInt} by the provided {@code long} divisor. * * <pre> * this = this / div * </pre> * * @param div The divisor. * @return {@code this} * @complexity O(n^2) */ public BigInt div(final long div) { divRem(val, div); return this; } /** * Divides this {@link BigInt} by the provided {@link BigInt} divisor. * * <pre> * this = this / div * </pre> * * @param div The divisor. * @return {@code this} * @complexity O(n^2) */ public BigInt div(final BigInt div) { val = div(val, div.val); return this; } /** * Divides this {@link BigInt} by the specified <i>unsigned</i> {@code int} * divisor, and returns the <i>absolute unsigned int</i> remainder. * * <pre> * rem = this % div * this = this / div * return rem * </pre> * * @param sig The sign of the unsigned {@code int} divisor. * @param div The divisor (unsigned). * @return The <i>absolute unsigned int</i> remainder resulting from the * division of this {@link BigInt} by the specified <i>unsigned</i> * {@code int} divisor. * @complexity O(n) */ public int divRem(final int sig, final int div) { return divRem(val, sig, div); } /** * Divides this {@link BigInt} by the specified {@code int} divisor, and * returns the remainder. * * <pre> * rem = this % div * this = this / div * return rem * </pre> * * @param div The divisor. * @return The remainder resulting from the division of this {@link BigInt} by * the specified {@code int} divisor. * @complexity O(n) */ public long divRem(final int div) { return divRem(val, div); } /** * Divides this {@link BigInt} by the specified <i>unsigned</i> {@code long} * divisor, and returns the <i>absolute unsigned long</i> remainder. * * <pre> * rem = this % div * this = this / div * return rem * </pre> * * @param sig The sign of the unsigned {@code long} divisor. * @param div The divisor (unsigned). * @return The <i>absolute unsigned long</i> remainder resulting from the * division of this {@link BigInt} by the specified <i>unsigned</i> * {@code long} divisor. * @complexity O(n) */ public long divRem(final int sig, final long div) { return divRem(val, sig, div); } /** * Divides this {@link BigInt} by the specified {@code long} divisor, and * returns the remainder. * * <pre> * rem = this % div * this = this / div * return rem * </pre> * * @param div The divisor. * @return The remainder resulting from the division of this {@link BigInt} by * the specified {@code long} divisor. * @complexity O(n) */ public long divRem(final long div) { return divRem(val, div); } /** * Divides this {@link BigInt} by the specified {@link BigInt} divisor, and * returns the remainder as a new {@link BigInt}. * * <pre> * rem = this % div * this = this / div * return rem * </pre> * * @param div The {@link BigInt} divisor. * @return A new {@link BigInt} with the remainder. * @complexity O(n^2) */ public BigInt divRem(final BigInt div) { return new BigInt(divRem(val, div.val)); } /** * Divides this {@link BigInt} by the provided <i>unsigned</i> {@code int} * divisor and sets the remainder as the value of this {@link BigInt}. * * <pre> * this = this % div * </pre> * * @param sig The sign of the unsigned {@code int} divisor. * @param div The divisor (unsigned). * @return {@code this} * @complexity O(n^2) */ public BigInt rem(final int sig, final int div) { rem(val, sig, div); return this; } /** * Divides this {@link BigInt} by the provided {@code int} divisor and sets * the remainder as the value of this {@link BigInt}. * * <pre> * this = this % div * </pre> * * @param div The divisor. * @return {@code this} * @complexity O(n^2) */ public BigInt rem(final int div) { rem(val, div); return this; } /** * Divides this {@link BigInt} by the provided <i>unsigned</i> {@code long} * divisor and sets the remainder as the value of this {@link BigInt}. * * <pre> * this = this % div * </pre> * * @param sig The sign of the unsigned {@code long} divisor. * @param div The divisor (unsigned). * @return {@code this} * @complexity O(n) */ public BigInt rem(final int sig, final long div) { rem(val, sig, div); return this; } /** * Divides this {@link BigInt} by the provided {@code long} divisor and sets * the remainder as the value of this {@link BigInt}. * * <pre> * this = this % div * </pre> * * @param div The divisor. * @return {@code this} * @complexity O(n^2) */ public BigInt rem(final long div) { rem(val, div); return this; } /** * Divides this {@link BigInt} by the provided {@code long} divisor and sets * the remainder as the value of this {@link BigInt}. * * <pre> * this = this % div * </pre> * * @param div The divisor. * @return {@code this} * @complexity O(n^2) */ public BigInt rem(final BigInt div) { val = rem(val, div.val); return this; } /** * Divides this {@link BigInt} by the specified {@code int} divisor and sets * the modulus as the value of this {@link BigInt}. * * <pre> * this = this % div * </pre> * * @implNote This method differs from {@link #rem(BigInt)} in that it always * returns a <i>non-negative</i> result. * @param div The {@link BigInt} divisor. * @return {@code this} * @complexity O(n^2) */ public BigInt mod(final int div) { val = mod(val, div); return this; } /** * Divides this {@link BigInt} by the specified {@code long} divisor and sets * the modulus as the value of this {@link BigInt}. * * <pre> * this = this % div * </pre> * * @implNote This method differs from {@link #rem(BigInt)} in that it always * returns a <i>non-negative</i> result. * @param div The {@link BigInt} divisor. * @return {@code this} * @complexity O(n^2) */ public BigInt mod(final long div) { val = mod(val, div); return this; } /** * Divides this {@link BigInt} by the specified {@link BigInt} divisor and * sets the modulus as the value of this {@link BigInt}. * * <pre> * this = this % div * </pre> * * @implNote This method differs from {@link #rem(BigInt)} in that it always * returns a <i>non-negative</i> result. * @param div The {@link BigInt} divisor. * @return {@code this} * @complexity O(n^2) */ public BigInt mod(final BigInt div) { val = mod(val, div.val); return this; } /** * Returns the number of bits in the two's complement representation of this * {@link BigInt} that differ from its sign bit. * * @return Number of bits in the two's complement representation of this * {@link BigInt} that differ from its sign bit. * @complexity O(n) */ public int bitCount() { return bitCount(val); } /** * Returns the number of bits in the minimal two's-complement representation * of this {@link BigInt}, <i>excluding</i> a sign bit. For positive numbers, * this is equivalent to the number of bits in the ordinary binary * representation. For zero this method returns {@code 0}. * * <pre> * ceil(log2(this &lt; 0 ? -this : this + 1)) * </pre> * * @return Number of bits in the minimal two's-complement representation of * this {@link BigInt}, <i>excluding</i> a sign bit. * @complexity O(n) */ public long bitLength() { return bitLength(val); } /** * Returns the index of the rightmost (lowest-order) one bit in this * {@link BigInt} (the number of zero bits to the right of the rightmost one * bit). Returns {@code -1} if number contains no one bits. * * <pre> * this == 0 ? -1 : log2(this &amp; -this) * </pre> * * @return The index of the rightmost (lowest-order) one bit in this * {@link BigInt}. */ public int getLowestSetBit() { return getLowestSetBit(val); } /** * Returns the number of digits in this {@link BigInt} (radix 10). * * @return The number of digits in this {@link BigInt} (radix 10). * @complexity O(n) */ public int precision() { return precision(val); } /** * Shifts this {@link BigInt} left by the specified number of bits. The shift * distance, {@code num}, may be negative, in which case this method performs * a right shift. * * <pre> * this = this &lt;&lt; num * </pre> * * @param num The amount by which to shift. * @return {@code this} * @complexity O(n) */ public BigInt shiftLeft(final int num) { val = shiftLeft(val, num); return this; } /** * Shifts this {@link BigInt} right by the specified number of bits. The shift * distance, {@code num}, may be negative, in which case this method performs * a left shift. * * <pre> * this = this &gt; &gt; num * </pre> * * @param num The amount by which to shift. * @return {@code this} * @complexity O(n) */ public BigInt shiftRight(final int num) { val = shiftRight(val, num); return this; } /** * Tests if the specified bit is set in this {@link BigInt}. * * <pre> * this | (1 &lt;&lt; n) * </pre> * * @param bit The index of the bit to test. * @return {@code true} if the given bit is set in this {@link BigInt}, * otherwise {@code false}. * @complexity O(n) */ public boolean testBit(final int bit) { return testBit(val, bit); } /** * Sets the specified bit in this {@link BigInt}. * * <pre> * this = this | (1 &lt;&lt; n) * </pre> * * @param bit The bit to set. * @return {@code this} * @complexity O(n) */ public BigInt setBit(final int bit) { val = setBit(val, bit); return this; } /** * Clears the specified bit in this {@link BigInt}. * * <pre> * this = this &amp; ~(1 &lt;&lt; n) * </pre> * * @param bit The bit to clear. * @return {@code this} * @complexity O(n) */ public BigInt clearBit(final int bit) { val = clearBit(val, bit); return this; } /** * Flips the specified bit in this {@link BigInt}. * * <pre> * this = this ^ (1 &lt;&lt; n) * </pre> * * @param bit The bit to flip. * @return {@code this} * @complexity O(n) */ public BigInt flipBit(final int bit) { val = flipBit(val, bit); return this; } /** * Performs a bitwise "and" of the specified {@link BigInt} mask onto this * {@link BigInt}. * * <pre> * this = this &amp; mask * </pre> * * @param mask The number with which to perform the bitwise "and". * @return {@code this} * @complexity O(n) */ public BigInt and(final BigInt mask) { val = and(val, mask.val); return this; } /** * Performs a bitwise "or" of the specified {@link BigInt} mask onto this * {@link BigInt}. * * <pre> * this = this | mask * </pre> * * @param mask The number with which to perform the bitwise "or". * @return {@code this} * @complexity O(n) */ public BigInt or(final BigInt mask) { val = or(val, mask.val); return this; } /** * Performs a bitwise "xor" of the specified {@link BigInt} mask onto this * {@link BigInt}. * * <pre> * this = this ^ mask * </pre> * * @param mask The number with which to perform the bitwise "xor". * @return {@code this} * @complexity O(n) */ public BigInt xor(final BigInt mask) { val = xor(val, mask.val); return this; } /** * Performs a bitwise "and-not" of the specified {@link BigInt} mask onto this * {@link BigInt}. * * <pre> * this = this &amp; ~mask * </pre> * * @param mask The number with which to perform the bitwise "and-not". * @return {@code this} * @complexity O(n) */ public BigInt andNot(final BigInt mask) { val = andNot(val, mask.val); return this; } /** * Inverts the sign and all bits of this {@link BigInt}. * * <pre> * val = ~val * </pre> * * The identity {@code -val = ~val + 1} holds. * * @implNote The returned number may be a {@code new int[]} instance if the * number resulting from the operation requires a larger array. * @return {@code this} * @complexity O(n) */ public BigInt not() { val = not(val); return this; } /** * Returns the value of this {@link BigInt} as a {@code byte}. * * @return The value of this {@link BigInt} as a {@code byte}. * @complexity O(1) */ @Override public byte byteValue() { return byteValue(val); } /** * Returns the value of this {@link BigInt} as a {@code short}. * * @return The value of this {@link BigInt} as a {@code short}. * @complexity O(1) */ @Override public short shortValue() { return shortValue(val); } /** * Returns the value of this {@link BigInt} as an {@code int}. * * @return The value of this {@link BigInt} as an {@code int}. * @complexity O(1) */ @Override public int intValue() { return intValue(val); } /** * Returns the value of this {@link BigInt} as a {@code long}. * * @return The value of this {@link BigInt} as a {@code long}. * @complexity O(1) */ @Override public long longValue() { return longValue(val); } /** * Returns the value of this {@link BigInt} as an <i>unsigned</i> * {@code long}. * * @return The value of this {@link BigInt} as an <i>unsigned</i> * {@code long}. * @complexity O(1) */ public long longValueUnsigned() { return longValueUnsigned(val); } /** * Returns the value of this {@link BigInt} as a {@code float}. * * @return The value of this {@link BigInt} as a {@code float}. * @complexity O(1) */ @Override public float floatValue() { return floatValue(val); } /** * Returns the value of this {@link BigInt} as a {@code double}. * * @return The value of this {@link BigInt} as a {@code double}. * @complexity O(1) */ @Override public double doubleValue() { return doubleValue(val); } /** * Returns a byte array containing the two's-complement representation of this * {@link BigInt}. The byte array will be in the endian order as specified by * the {@code littleEndian} argument. The array will contain the minimum * number of bytes required to represent this {@link BigInt}, including at * least one sign bit, which is {@code (ceil((bitLength(val) + 1) / 8))}. * * @param littleEndian Whether the produced byte array is to be encoded in * <i>little-endian</i> ({@code true}), or <i>big-endian</i> * ({@code false}). * @return A byte array containing the two's-complement representation of this * {@link BigInt}. */ public byte[] toByteArray(final boolean littleEndian) { return toByteArray(val, littleEndian); } /** * Returns a {@link BigInteger} representation of this {@link BigInt}. * * @return A {@link BigInteger} representation of this {@link BigInt}. */ public BigInteger toBigInteger() { return toBigInteger(val); } /** * Returns a {@link BigDecimal} representation of this {@link BigInt}. * * @return A {@link BigDecimal} representation of this {@link BigInt}. */ public BigDecimal toBigDecimal() { return toBigDecimal(val); } /** * Compares the absolute values of this {@link BigInt} to the provided * {@link BigInt}, and returns one of {@code -1}, {@code 0}, or {@code 1} * whether the absolute value of {@code this} is less than, equal to, or * greater than that of the provided {@link BigInt}, respectively. * * @param o The {@link BigInt} with which to compare. * @return One of {@code -1}, {@code 0}, or {@code 1} if the absolute value of * {@code this} is less than, equal to, or greater than that of he * provided {@link BigInt}, respectively. * @complexity O(n) */ public int compareToAbs(final BigInt o) { return compareToAbs(val, o.val); } /** * Compares the values of this {@link BigInt} to the provided {@link BigInt}, * and returns one of {@code -1}, {@code 0}, or {@code 1} whether the value of * {@code this} is less than, equal to, or greater than that of the provided * {@link BigInt}, respectively. * * @param o The {@link BigInt} with which to compare. * @return One of {@code -1}, {@code 0}, or {@code 1} if the value of * {@code this} is less than, equal to, or greater than that of he * provided {@link BigInt}, respectively. * @complexity O(n) */ @Override public int compareTo(final BigInt o) { return compareTo(val, o.val); } /** * Tests equality of this {@link BigInt} and the provided {@link BigInt}. * * @param n The {@link BigInt} with which to test for equality. * @return {@code true} if the two numbers are equal, otherwise {@code false}. * @complexity O(n) */ public boolean equals(final BigInt n) { return equals(val, n.val); } /** * Tests equality of this {@link BigInt} and the provided object. * * @param obj The object with which to test for equality. * @return {@code true} if this {@link BigInt} and the provided object are * equal, otherwise {@code false}. * @complexity O(n) */ @Override public boolean equals(final Object obj) { return obj == this || obj instanceof BigInt && equals((BigInt)obj); } /** * Computes the hash code of this {@link BigInt}. * * @return The hash code of this {@link BigInt}. * @complexity O(n) */ @Override public int hashCode() { return hashCode(val); } /** * Converts this {@link BigInt} into a string of radix 10. * * @return The string representation of this {@link BigInt} in radix 10. * @complexity O(n^2) */ @Override public String toString() { return toString(val); } /** * Returns a copy of this {@link BigInt}. * * @return A copy of this {@link BigInt}. * @complexity O(n) */ @Override public BigInt clone() { try { final BigInt clone = (BigInt)super.clone(); clone.val = val.clone(); return clone; } catch (final CloneNotSupportedException e) { throw new RuntimeException(e); } } }
package com.thvardhan.epicbanana; import com.thvardhan.epicbanana.handlers.RegistryHandler; import net.minecraft.block.Block; import net.minecraftforge.fml.common.event.FMLInitializationEvent; import net.minecraftforge.fml.common.event.FMLPostInitializationEvent; import net.minecraftforge.fml.common.event.FMLPreInitializationEvent; public class ClientProxy extends CommonProxy { @Override public void preInit(FMLPreInitializationEvent e) { super.preInit(e); } @Override public void init(FMLInitializationEvent e) { super.init(e); // RegistryHandler.registerBlockForRender(ModBlocks.bananaTrunk); renderAllBlocks(); } @Override public void postInit(FMLPostInitializationEvent e) { super.postInit(e); } private final void renderAllBlocks(){ for (Block key: ModBlocks.blocks.keySet()) { RegistryHandler.registerBlockForRender(key); } } }
/* * @(#)Token.java 4.1.0 2017-06-04 * * You may use this software under the condition of "Simplified BSD License" * * Copyright 2010-2017 MARIUSZ GROMADA. All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, are * permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, this list of * conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright notice, this list * of conditions and the following disclaimer in the documentation and/or other materials * provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY <MARIUSZ GROMADA> ``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 <COPYRIGHT HOLDER> OR * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * * The views and conclusions contained in the software and documentation are those of the * authors and should not be interpreted as representing official policies, either expressed * or implied, of MARIUSZ GROMADA. * * If you have any questions/bugs feel free to contact: * * Mariusz Gromada * mariuszgromada.org@gmail.com * http://mathparser.org * http://mathspace.pl * http://janetsudoku.mariuszgromada.org * http://github.com/mariuszgromada/MathParser.org-mXparser * http://mariuszgromada.github.io/MathParser.org-mXparser * http://mxparser.sourceforge.net * http://bitbucket.org/mariuszgromada/mxparser * http://mxparser.codeplex.com * http://github.com/mariuszgromada/Janet-Sudoku * http://janetsudoku.codeplex.com * http://sourceforge.net/projects/janetsudoku * http://bitbucket.org/mariuszgromada/janet-sudoku * http://github.com/mariuszgromada/MathParser.org-mXparser * http://scalarmath.org/ * https://play.google.com/store/apps/details?id=org.mathparser.scalar.lite * https://play.google.com/store/apps/details?id=org.mathparser.scalar.pro * * Asked if he believes in one God, a mathematician answered: * "Yes, up to isomorphism." */ package org.mariuszgromada.math.mxparser.parsertokens; /** * Token recognized by mXparser after string tokenization process. * * @author <b>Mariusz Gromada</b><br> * <a href="mailto:mariuszgromada.org@gmail.com">mariuszgromada.org@gmail.com</a><br> * <a href="http://mathspace.pl" target="_blank">MathSpace.pl</a><br> * <a href="http://mathparser.org" target="_blank">MathParser.org - mXparser project page</a><br> * <a href="http://github.com/mariuszgromada/MathParser.org-mXparser" target="_blank">mXparser on GitHub</a><br> * <a href="http://mxparser.sourceforge.net" target="_blank">mXparser on SourceForge</a><br> * <a href="http://bitbucket.org/mariuszgromada/mxparser" target="_blank">mXparser on Bitbucket</a><br> * <a href="http://mxparser.codeplex.com" target="_blank">mXparser on CodePlex</a><br> * <a href="http://janetsudoku.mariuszgromada.org" target="_blank">Janet Sudoku - project web page</a><br> * <a href="http://github.com/mariuszgromada/Janet-Sudoku" target="_blank">Janet Sudoku on GitHub</a><br> * <a href="http://janetsudoku.codeplex.com" target="_blank">Janet Sudoku on CodePlex</a><br> * <a href="http://sourceforge.net/projects/janetsudoku" target="_blank">Janet Sudoku on SourceForge</a><br> * <a href="http://bitbucket.org/mariuszgromada/janet-sudoku" target="_blank">Janet Sudoku on BitBucket</a><br> * <a href="https://play.google.com/store/apps/details?id=org.mathparser.scalar.lite" target="_blank">Scalar Free</a><br> * <a href="https://play.google.com/store/apps/details?id=org.mathparser.scalar.pro" target="_blank">Scalar Pro</a><br> * <a href="http://scalarmath.org/" target="_blank">ScalarMath.org</a><br> * * @version 4.1.0 */ public class Token { /** * Indicator that token was not matched */ public static final int NOT_MATCHED = KeyWord.NO_DEFINITION; /** * String token */ public String tokenStr; /** * Key word string (if matched) */ public String keyWord; /** * Token identifier */ public int tokenId; /** * Token type */ public int tokenTypeId; /** * Token level */ public int tokenLevel; /** * Token value if number */ public double tokenValue; /** * If token was not matched then * looksLike functionality is trying asses * the kind of token */ public String looksLike; /** * Default constructor */ public Token() { tokenStr = ""; keyWord = ""; tokenId = NOT_MATCHED; tokenTypeId = NOT_MATCHED; tokenLevel = -1; tokenValue = Double.NaN; looksLike = ""; } /** * Token cloning. */ public Token clone() { Token token = new Token(); token.keyWord = keyWord; token.tokenStr = tokenStr; token.tokenId = tokenId; token.tokenLevel = tokenLevel; token.tokenTypeId = tokenTypeId; token.tokenValue = tokenValue; token.looksLike = looksLike; return token; } }
package il.org.spartan.reflection; import java.lang.reflect.Constructor; import java.lang.reflect.Field; import java.lang.reflect.Method; /** A class realizing a recursive traversal of a reflection {@link Class} * object, applying the appropriate function supplied by a {@link Visitor} to * the object itself and to all data, function, and class members of this * object. * <p> * Each of these visitation functions returns an <code><b>int</b></code>. This * class computes the sum of all returned values. * <p> * Visitation functions are first invoked on all members, and only then it * recurses to members of inner classes. * * @author Yossi Gil * @since 04/08/2007 */ public final class ReflectionTraversal { /** where should visitation start */ public final Class<?> clazz; /** what should be done in each reflection node encountered? */ public final Visitor visitor; /** Setup the traversal pattern * * @param clazz where should traversal start, must not be * <code><b>null</b></code> . * @param visitor what should be done at each node, must not be * <code><b>null</b></code>. */ public ReflectionTraversal(final Class<?> clazz, final Visitor visitor) { assert clazz != null; assert visitor != null; this.clazz = clazz; this.visitor = visitor; } /** initiate the traversal * * @return sum of all visit functions on all visited object */ public int go() { return go(clazz); } private int go(final Class<?> from) { assert from != null; // Visit the class itself int $ = visitor.visit(from); // Visit all sorts of members for (final Field ¢ : from.getDeclaredFields()) $ += visitor.visit(¢); for (final Method ¢ : from.getDeclaredMethods()) $ += visitor.visit(¢); for (final Constructor<?> ¢ : from.getDeclaredConstructors()) $ += visitor.visit(¢); for (final Class<?> ¢ : from.getDeclaredClasses()) $ += visitor.visit(¢); // Recurse into inner, local and anonymous classes for (final Class<?> ¢ : from.getDeclaredClasses()) $ += go(¢); return $; } public interface Visitor { int visit(Class<?> c); int visit(Constructor<?> c); int visit(Field f); int visit(Method m); } }
/* * Copyright (c) 2019, Lawrence Livermore National Security, LLC. Produced at the Lawrence Livermore National Laboratory * CODE-743439. * All rights reserved. * This file is part of CCT. For details, see https://github.com/LLNL/coda-calibration-tool. * * Licensed under the Apache License, Version 2.0 (the “Licensee”); you may not use this file except in compliance with the License. You may obtain a copy of the License at: * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an “AS IS” BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and limitations under the license. * * This work was performed under the auspices of the U.S. Department of Energy * by Lawrence Livermore National Laboratory under Contract DE-AC52-07NA27344. */ package gov.llnl.gnem.apps.coda.calibration.service.impl; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertTrue; import java.time.Instant; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.Map; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.Mockito; import org.mockito.junit.jupiter.MockitoExtension; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import gov.llnl.gnem.apps.coda.calibration.model.domain.MdacParametersFI; import gov.llnl.gnem.apps.coda.calibration.model.domain.MdacParametersPS; import gov.llnl.gnem.apps.coda.calibration.model.domain.ReferenceMwParameters; import gov.llnl.gnem.apps.coda.calibration.model.domain.SiteFrequencyBandParameters; import gov.llnl.gnem.apps.coda.calibration.model.domain.SpectraMeasurement; import gov.llnl.gnem.apps.coda.calibration.model.domain.VelocityConfiguration; import gov.llnl.gnem.apps.coda.calibration.service.api.MdacParametersFiService; import gov.llnl.gnem.apps.coda.calibration.service.api.MdacParametersPsService; import gov.llnl.gnem.apps.coda.calibration.service.api.MeasuredMwsService; import gov.llnl.gnem.apps.coda.calibration.service.api.SiteFrequencyBandParametersService; import gov.llnl.gnem.apps.coda.calibration.service.impl.processing.MdacCalculatorService; import gov.llnl.gnem.apps.coda.calibration.service.impl.processing.SpectraCalculator; import gov.llnl.gnem.apps.coda.calibration.service.impl.processing.SyntheticCodaModel; import gov.llnl.gnem.apps.coda.common.model.domain.Event; import gov.llnl.gnem.apps.coda.common.model.domain.FrequencyBand; import gov.llnl.gnem.apps.coda.common.model.domain.SharedFrequencyBandParameters; import gov.llnl.gnem.apps.coda.common.model.domain.Station; import gov.llnl.gnem.apps.coda.common.model.domain.Stream; import gov.llnl.gnem.apps.coda.common.model.domain.Waveform; import gov.llnl.gnem.apps.coda.common.model.util.PICK_TYPES; import gov.llnl.gnem.apps.coda.common.service.util.WaveformToTimeSeriesConverter; @ExtendWith(MockitoExtension.class) public class SiteCalibrationServiceImplTest { private final Logger log = LoggerFactory.getLogger(this.getClass()); @Mock private MdacCalculatorService mdac; @Mock private MeasuredMwsService measuredMwsService; @Mock private SiteFrequencyBandParametersService siteParamsService; private WaveformToTimeSeriesConverter converter = new WaveformToTimeSeriesConverter(); @Mock private SyntheticCodaModel syntheticCodaModel; @Mock private MdacParametersFiService mdacFiService; @Mock private MdacParametersPsService mdacPsService; @Mock private VelocityConfiguration velConf; @Mock private ServiceConfig svcConf; @InjectMocks private SiteCalibrationServiceImpl siteCalibrationServiceImpl; @BeforeEach protected void setUp() throws Exception { Mockito.when(mdac.getCalculateMdacSourceSpectraFunction(Mockito.any(), Mockito.any(), Mockito.anyDouble())).thenReturn(f -> new double[] { 1.0, 1.0, 1.0, 1.0 }); Mockito.when(mdac.getCalculateMdacAmplitudeForMwFunction(Mockito.any(), Mockito.any(), Mockito.anyDouble(), Mockito.any(), Mockito.anyDouble())).thenReturn(f -> Double.valueOf(1.0d)); SpectraCalculator spectraCalc = new SpectraCalculator(converter, syntheticCodaModel, mdac, mdacFiService, mdacPsService, velConf); siteCalibrationServiceImpl.setSpectraCalc(spectraCalc); siteCalibrationServiceImpl.setServiceConfig(new ServiceConfig()); } @AfterEach protected void tearDown() throws Exception { } @Test public void testSiteCorrectionsOneStationEvent() throws Exception { //Testing a fix for a NPE caused when the following three statements are true. //1) You have a station that saw no calibration events ("InvalidEventStation") //2) That station shares a non-calibration event with a station that DID see a calibration event ("TEST" in this case) //3) The station with no calibration event ALSO has an event that no other station saw ("3456"). Waveform w1 = createWaveform(); Waveform w2 = createWaveform(); w2.getEvent().setEventId("2345"); Waveform w3 = createWaveform(); w3.getEvent().setEventId("2345"); w3.getStream().getStation().setStationName("InvalidEventStation"); Waveform w4 = createWaveform(); w4.getEvent().setEventId("3456"); w4.getStream().getStation().setStationName("InvalidEventStation"); SpectraMeasurement sm = new SpectraMeasurement(); sm.setWaveform(w1); sm.setPathCorrected(1d); sm.setRawAtMeasurementTime(1d); sm.setRawAtStart(1d); SpectraMeasurement sm2 = new SpectraMeasurement(); sm2.setWaveform(w2); sm2.setPathCorrected(1d); sm2.setRawAtMeasurementTime(1d); sm2.setRawAtStart(1d); SpectraMeasurement sm3 = new SpectraMeasurement(); sm3.setWaveform(w3); sm3.setPathCorrected(1d); sm3.setRawAtMeasurementTime(1d); sm3.setRawAtStart(1d); SpectraMeasurement sm4 = new SpectraMeasurement(); sm4.setWaveform(w4); sm4.setPathCorrected(1d); sm4.setRawAtMeasurementTime(1d); sm4.setRawAtStart(1d); List<SpectraMeasurement> spectra = new ArrayList<>(1); spectra.add(sm); spectra.add(sm2); spectra.add(sm3); spectra.add(sm4); Map<FrequencyBand, List<SpectraMeasurement>> spectraMap = new HashMap<>(); spectraMap.put(new FrequencyBand(0d, 1d), spectra); Map<PICK_TYPES, MdacParametersPS> mdacPsMap = new HashMap<>(); mdacPsMap.put(PICK_TYPES.LG, new MdacParametersPS()); Map<FrequencyBand, SharedFrequencyBandParameters> frequencyBandParameterMap = new HashMap<>(); frequencyBandParameterMap.put(new FrequencyBand(0d, 1d), new SharedFrequencyBandParameters()); Map<String, List<ReferenceMwParameters>> refEventMap = new HashMap<>(); refEventMap.put("1234", Collections.singletonList(new ReferenceMwParameters().setRefMw(5d).setEventId("1234"))); Map<FrequencyBand, Map<Station, SiteFrequencyBandParameters>> results = siteCalibrationServiceImpl.measureSiteCorrections( spectraMap, new MdacParametersFI(), mdacPsMap, refEventMap, frequencyBandParameterMap, PICK_TYPES.LG); assertEquals(1, results.size(), "Should have one frequency band"); Map<Station, SiteFrequencyBandParameters> stations = results.values().stream().findFirst().get(); assertEquals(2, stations.size(), "Should have two stations"); assertTrue(stations.values().stream().allMatch(sfb -> sfb.getSiteTerm() == 6.0), "Both stations should have the same site term"); } private Waveform createWaveform() { Date startTime = Date.from(Instant.now()); Date endTime = Date.from(startTime.toInstant().plusSeconds(1l)); Event event = new Event(); event.setEventId("1234"); event.setLatitude(1.0); event.setLongitude(1.0); Station station = new Station(); station.setLatitude(1.0); station.setLongitude(1.0); station.setStationName("TEST"); station.setNetworkName(null); Stream s1 = new Stream(); s1.setChannelName("BHE"); s1.setStation(station); double[] data = new double[400]; Arrays.fill(data, 0, 200, 1000.0); Arrays.fill(data, 2, 400, 2000.0); Waveform w1 = new Waveform(); w1.setEvent(event); w1.setStream(s1); w1.setSegment(data); w1.setBeginTime(startTime); w1.setEndTime(endTime); w1.setSampleRate(16d); w1.setLowFrequency(0d); w1.setHighFrequency(1d); return w1; } }
package org.prebid.server.auction; import com.iab.openrtb.request.BidRequest; import com.iab.openrtb.response.BidResponse; import io.vertx.core.Future; import io.vertx.ext.web.RoutingContext; import org.prebid.server.proto.response.AmpResponse; /** * A hook that is pulled prior sending the AMP RTC response back to the client. * It allows companies that host Prebid Server to add custom key values in the AMP RTC response. */ @FunctionalInterface public interface AmpResponsePostProcessor { /** * This method is called prior sending the response back to the client. * * @param bidRequest original auction request * @param bidResponse auction result * @param ampResponse AMP RTC response * @param routingContext request's context * @return a {@link Future} with (possibly modified) amp response result */ Future<AmpResponse> postProcess(BidRequest bidRequest, BidResponse bidResponse, AmpResponse ampResponse, RoutingContext routingContext); /** * Returns {@link NoOpAmpResponsePostProcessor} instance that just does nothing. */ static AmpResponsePostProcessor noOp() { return new NoOpAmpResponsePostProcessor(); } /** * Well, dump stub that gives back unaltered AMP response. */ class NoOpAmpResponsePostProcessor implements AmpResponsePostProcessor { @Override public Future<AmpResponse> postProcess(BidRequest bidRequest, BidResponse bidResponse, AmpResponse ampResponse, RoutingContext routingContext) { return Future.succeededFuture(ampResponse); } } }
/* * 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.uima.caseditor.editor.util; import java.util.ArrayList; import java.util.Collection; import org.apache.uima.cas.FeatureStructure; import org.apache.uima.cas.text.AnnotationFS; /** * TODO: add javadoc here. */ public class UimaUtil { /** * Casts a {@link FeatureStructure} collection to an {@link AnnotationFS} collection. * * @param annotations the annotations * @return the {@link AnnotationFS} collection */ public static Collection<FeatureStructure> cast(Collection<AnnotationFS> annotations) { Collection<FeatureStructure> structures = new ArrayList<FeatureStructure>(annotations.size()); for (AnnotationFS annotation : annotations) { structures.add(annotation); } return structures; } }
/*------------------------------------------------------------------------------ Copyright (c) CovertJaguar, 2011-2017 http://railcraft.info This code is the property of CovertJaguar and may only be used with explicit written permission unless otherwise specified on the license page at http://railcraft.info/wiki/info:license. -----------------------------------------------------------------------------*/ package mods.railcraft.common.plugins.forestry; import mods.railcraft.common.blocks.RailcraftBlocks; import mods.railcraft.common.blocks.aesthetics.materials.Materials; import mods.railcraft.common.util.inventory.InvTools; import mods.railcraft.common.util.inventory.filters.StackFilters; import mods.railcraft.common.util.inventory.manipulators.InventoryManipulator; import mods.railcraft.common.util.inventory.wrappers.InventoryComposite; import net.minecraft.init.Blocks; import net.minecraft.init.Items; import net.minecraft.inventory.IInventory; import net.minecraft.item.ItemStack; import net.minecraftforge.fml.common.Optional; import java.util.function.Predicate; /** * @author CovertJaguar <http://www.railcraft.info> */ @Optional.Interface(iface = "forestry.api.storage.IBackpackDefinition", modid = ForestryPlugin.FORESTRY_ID) public class IcemanBackpack extends BaseBackpack { private static IcemanBackpack instance; private static final ItemStack SNOWBALL = new ItemStack(Items.SNOWBALL); private static final ItemStack SNOW_BLOCK = new ItemStack(Blocks.SNOW); private static final Predicate<ItemStack> SNOWBALL_MATCHER = StackFilters.of(Items.SNOWBALL); private static final Predicate<ItemStack> SNOW_BLOCK_MATCHER = StackFilters.of(Blocks.SNOW); private static final String INV_TAG = "Items"; public static IcemanBackpack getInstance() { if (instance == null) { instance = new IcemanBackpack(); } return instance; } protected IcemanBackpack() { super("railcraft.iceman"); } public void setup() { add(Blocks.SNOW); add(Blocks.SNOW_LAYER); add(Blocks.ICE); add(Blocks.PACKED_ICE); for (Materials mat : Materials.MAT_SET_FROZEN) { add(RailcraftBlocks.WALL.getStack(mat)); add(RailcraftBlocks.STAIR.getStack(mat)); add(RailcraftBlocks.SLAB.getStack(mat)); } add(Items.SNOWBALL); } @Override public int getPrimaryColour() { return 0xFFFFFF; } @Override public int getSecondaryColour() { return 0xFFFFFF; } @Override public boolean stow(IInventory backpackInventory, ItemStack stackToStow) { manageSnow(backpackInventory); return false; } @Override public boolean resupply(IInventory backpackInventory) { manageSnow(backpackInventory); return false; } private void manageSnow(IInventory backpackInventory) { InventoryComposite inv = InventoryComposite.of(backpackInventory); if (!inv.isEmpty()) { int numSnowballs = InvTools.countItems(inv, SNOWBALL_MATCHER); InventoryManipulator im = InventoryManipulator.get(backpackInventory); while (numSnowballs > 16 && im.canRemoveItems(SNOWBALL_MATCHER, 4) && im.canAddStack(SNOW_BLOCK)) { im.removeItems(SNOWBALL_MATCHER, 4); im.addStack(new ItemStack(Blocks.SNOW)); numSnowballs -= 4; } while (numSnowballs < 8 && im.canRemoveItem(SNOW_BLOCK_MATCHER) && im.canAddStack(new ItemStack(Items.SNOWBALL, 4))) { im.removeItem(SNOW_BLOCK_MATCHER); im.addStack(new ItemStack(Items.SNOWBALL, 4)); numSnowballs += 4; } } } }
package models; import java.io.IOException; import java.util.Iterator; import java.util.List; import javax.persistence.*; import javax.validation.constraints.NotNull; import models.base.BaseNotifiable; import models.base.INotifiable; import models.services.ElasticsearchService; import play.db.jpa.JPA; import models.enums.LinkType; import play.libs.F; @Entity @Table(uniqueConstraints= @UniqueConstraint(columnNames = {"account_id", "friend_id"})) public class Friendship extends BaseNotifiable implements INotifiable { public static final String FRIEND_REQUEST_SUCCESS = "request_successful"; public static final String FRIEND_REQUEST_DECLINE = "request_decline"; public static final String FRIEND_NEW_REQUEST = "new_request"; public static final int PAGE = 1; @ManyToOne @NotNull public Account account; @ManyToOne @NotNull public Account friend; @Enumerated(EnumType.STRING) @NotNull public LinkType linkType; public Friendship() { } public Friendship(Account account, Account friend, LinkType type) { this.account = account; this.friend = friend; this.linkType = type; } public static Friendship findById(Long id) { return JPA.em().find(Friendship.class, id); } @Override public void create() { JPA.em().persist(this); } @Override public void update() { JPA.em().merge(this); // each account document contains information about their friends // if a user accepts a friendship -> (re)index this.account document try { ElasticsearchService.indexAccount(this.account); } catch (IOException e) { e.printStackTrace(); } } @Override public void delete() { JPA.em().remove(this); Notification.deleteReferences(this); // each account document contains information about their friends // if a user deletes his friendship -> (re)index this.account document try { ElasticsearchService.indexAccount(this.account); } catch (IOException e) { e.printStackTrace(); } } public static Friendship findRequest(Account me, Account potentialFriend) { try{ return (Friendship) JPA.em().createQuery("SELECT fs FROM Friendship fs WHERE fs.account.id = ?1 AND fs.friend.id = ?2 AND fs.linkType = ?3") .setParameter(1, me.id).setParameter(2, potentialFriend.id).setParameter(3, LinkType.request).getSingleResult(); } catch (NoResultException exp) { return null; } } public static Friendship findReverseRequest(Account me, Account potentialFriend) { try{ return (Friendship) JPA.em().createQuery("SELECT fs FROM Friendship fs WHERE fs.friend.id = ?1 AND fs.account.id = ?2 AND fs.linkType = ?3") .setParameter(1, me.id).setParameter(2, potentialFriend.id).setParameter(3, LinkType.request).getSingleResult(); } catch (NoResultException exp) { return null; } } public static Friendship findFriendLink(Account account, Account target) { try{ return (Friendship) JPA.em().createQuery("SELECT fs FROM Friendship fs WHERE fs.account.id = ?1 and fs.friend.id = ?2 AND fs.linkType = ?3") .setParameter(1, account.id).setParameter(2, target.id).setParameter(3, LinkType.establish).getSingleResult(); } catch (NoResultException exp) { return null; } } /** * Returns true, if two accounts have a friendly relationship. * * @param me Account instance * @param potentialFriend Account instance * @return True, if both accounts are friends */ public static boolean alreadyFriendly(Account me, Account potentialFriend) { try { JPA.em().createQuery("SELECT fs FROM Friendship fs WHERE fs.account.id = ?1 and fs.friend.id = ?2 AND fs.linkType = ?3") .setParameter(1, me.id).setParameter(2, potentialFriend.id).setParameter(3, LinkType.establish).getSingleResult(); } catch (NoResultException exp) { return false; } return true; } public static boolean alreadyRejected(Account me, Account potentialFriend) { try { JPA.em().createQuery("SELECT fs FROM Friendship fs WHERE fs.account.id = ?1 and fs.friend.id = ?2 AND fs.linkType = ?3") .setParameter(1, me.id).setParameter(2, potentialFriend.id).setParameter(3, LinkType.reject).getSingleResult(); } catch (NoResultException exp) { return false; } return true; } @SuppressWarnings("unchecked") public static List<Account> findFriends(final Account account){ return (List<Account>) JPA.em().createQuery("SELECT fs.friend FROM Friendship fs WHERE fs.account.id = ?1 AND fs.linkType = ?2 ORDER BY fs.friend.firstname ASC") .setParameter(1, account.id).setParameter(2, LinkType.establish).getResultList(); } @SuppressWarnings("unchecked") public static List<Long> findFriendsId(final Account account){ return (List<Long>) JPA.em().createQuery("SELECT fs.friend.id FROM Friendship fs WHERE fs.account.id = ?1 AND fs.linkType = ?2") .setParameter(1, account.id).setParameter(2, LinkType.establish).getResultList(); } @SuppressWarnings("unchecked") public static List<Friendship> findRequests(final Account account) { return (List<Friendship>) JPA.em().createQuery("SELECT fs FROM Friendship fs WHERE (fs.friend.id = ?1 OR fs.account.id = ?1) AND fs.linkType = ?2") .setParameter(1, account.id).setParameter(2, LinkType.request).getResultList(); } @SuppressWarnings("unchecked") public static List<Friendship> findRejects(final Account account) { return (List<Friendship>) JPA.em().createQuery("SELECT fs FROM Friendship fs WHERE fs.account.id = ?1 AND fs.linkType = ?2") .setParameter(1, account.id).setParameter(2, LinkType.reject).getResultList(); } public static List<Account> friendsToInvite(Account account, Group group) { List<Account> inevitableFriends = findFriends(account); if (inevitableFriends != null) { Iterator<Account> it = inevitableFriends.iterator(); Account friend; while(it.hasNext()) { friend = it.next(); //remove account from list if there is any type of link (requests, invite, already member) if (GroupAccount.hasLinkTypes(friend, group)) { it.remove(); } } } return inevitableFriends; } @Override public Account getSender() { return this.type.equals(Friendship.FRIEND_REQUEST_DECLINE) ? this.friend : this.account; } @Override public List<Account> getRecipients() { return this.type.equals(Friendship.FRIEND_REQUEST_DECLINE) ? this.getAsAccountList(this.account) : this.getAsAccountList(this.friend); } @Override public String getTargetUrl() { if (this.type.equals(Friendship.FRIEND_NEW_REQUEST) || this.type.equals(Friendship.FRIEND_REQUEST_DECLINE)) { return controllers.routes.FriendshipController.index().toString(); } if (this.type.equals(Friendship.FRIEND_REQUEST_SUCCESS)) { return controllers.routes.ProfileController.stream(this.account.id, Friendship.PAGE).toString(); } return super.getTargetUrl(); } }
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.pinot.core.query.selection.iterator; import java.io.Serializable; import org.apache.pinot.core.common.Block; /** * Iterator on long array column selection query. * */ public class LongArraySelectionColumnIterator extends SelectionMultiValueColumnIterator { public LongArraySelectionColumnIterator(Block block) { super(block); } @Override public Serializable getValue(int docId) { bvIter.skipTo(docId); int dictSize = bvIter.nextIntVal(dictIds); long[] rawIntRow = new long[dictSize]; for (int dictIdx = 0; dictIdx < dictSize; ++dictIdx) { rawIntRow[dictIdx] = (Long) (dict.get(dictIds[dictIdx])); } return rawIntRow; } }
// 2019-4-25 // 翻转字符串 // leetcode-151 import java.util.*; public class ReverseWordsInSentence { public String reverse(String str) { char[] charArray = str.toCharArray(); // 转换为数组 // 整个字符串翻转 int start = 0, end = charArray.length - 1; while (start < end) { char tmp = charArray[start]; charArray[start] = charArray[end]; charArray[end] = tmp; start++; end--; } System.out.println("reverse sentence: " + Arrays.toString(charArray)); // 单个字符串翻转 // 有错 // boolean flag = false; // int left = 0; // for (int i = 0; i < charArray.length; ++i) { // if (!flag) { // if (charArray[i] != ' ') { // left = i; // flag = true; // continue; // } // } // if ((charArray[i] == ' ')) { // swapRange(charArray, left, i - 1); // flag = false; // } // if ((i == charArray.length - 1) && flag) { // swapRange(charArray, left, i); // } // } int left = 0; // 记录左端索引 boolean canSwap = false; for (int i = 0; i < charArray.length; ++i) { if (charArray[i] == ' ') { if (canSwap) { swapRange(charArray, left, i - 1); canSwap = false; } left = i + 1; } else { canSwap = true; } if (i == charArray.length - 1 && canSwap) { swapRange(charArray, left, i); } } return new String(charArray); } public void swapRange(char[] array, int left, int right) { while (left < right) { char tmp = array[left]; array[left] = array[right]; array[right] = tmp; left++; right--; } } public void test(String testName, String str, String expect) { String ret = reverse(str); System.out.println(testName + ", expect: " + expect + ", result: " + ret + "."); } public static void main(String[] args) { ReverseWordsInSentence test = new ReverseWordsInSentence(); test.test("test-1", "i am a student.", "student. a am i"); test.test("test-1", " i am a student. ", " student. a am i "); } }
/** * MIT License Copyright (c) 2018 deepakshajan 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 com.initializr.socket; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Configuration; import org.springframework.web.socket.config.annotation.EnableWebSocket; import org.springframework.web.socket.config.annotation.WebSocketConfigurer; import org.springframework.web.socket.config.annotation.WebSocketHandlerRegistry; /** * @author Deepak Shajan */ @Configuration @EnableWebSocket public class WebSocketConfig implements WebSocketConfigurer { @Autowired WebSocketHandler webSocketHandler; @Override public void registerWebSocketHandlers(WebSocketHandlerRegistry webSocketHandlerRegistry) { webSocketHandlerRegistry.addHandler(webSocketHandler, "/webSocket"); } }
package com.sap.mlt.xliff12.impl.attribute; import static org.junit.Assert.assertEquals; import org.junit.Test; import com.sap.mlt.xliff12.api.attribute.ContextType; public class ContextTypeImplTest { @Test public void testContextTypeImplValue() { ContextTypeImpl attr = new ContextTypeImpl(ContextType.Value.LINENUMBER); assertEquals(ContextType.Value.LINENUMBER, attr.getEnumValue()); } @Test public void testContextTypeImplString() { ContextTypeImpl attr = new ContextTypeImpl("abc"); assertEquals("abc", attr.getXtendValue()); } }
//,temp,KeyValueHandler.java,519,544,temp,KeyValueHandler.java,487,514 //,3 public class xxx { ContainerCommandResponseProto handleDeleteKey( ContainerCommandRequestProto request, KeyValueContainer kvContainer) { if (!request.hasDeleteKey()) { LOG.debug("Malformed Delete Key request. trace ID: {}", request.getTraceID()); return ContainerUtils.malformedRequest(request); } try { checkContainerOpen(kvContainer); BlockID blockID = BlockID.getFromProtobuf( request.getDeleteKey().getBlockID()); keyManager.deleteKey(kvContainer, blockID); } catch (StorageContainerException ex) { return ContainerUtils.logAndReturnError(LOG, ex, request); } catch (IOException ex) { return ContainerUtils.logAndReturnError(LOG, new StorageContainerException("Delete Key failed", ex, IO_EXCEPTION), request); } return KeyUtils.getKeyResponseSuccess(request); } };
/* Copyright [2016] [Taqdir Ali] 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.uclab.imp.cdss.cardiovascular.service; import java.util.List; import org.uclab.imp.cdss.cardiovascular.datamodel.WellnessConceptsModel; import org.uclab.imp.cdss.cardiovascular.datamodel.WellnessConceptsRelationships; /** * This is service interface for the wellness model, it provides service interfaces to * create, update, retrieve of wellness concepts * @author Taqdir Ali * @version 1.0 * @since 2015-08-16 * */ public interface WellnessConceptsModelService { /** * This interface function is for add new wellness concept * @param objWellnessConceptsModel */ public void addWellnessConcept(WellnessConceptsModel objWellnessConceptsModel); /** * This interface function is for update the existing wellness concept * @param objWellnessConceptsModel */ public void updateWellnessConcept(WellnessConceptsModel objWellnessConceptsModel); /** * This function get all wellness concept * @return List of WellnessConceptsModel */ public List<WellnessConceptsModel> listWellnessConceptsModel(String strQuery); /** * This function get a specific wellness concept by wellness concept id (primary key) * @param id * @return Object of WellnessConceptsModel */ public WellnessConceptsModel getWellnessConceptById(int id); /** * This function delete a specific wellness concept by wellness concept id (primary key) * @param id */ public void removeWellnessConcept(int id); /** * This function retrieve a specific wellness concept by wellness concept key string * @param strSelectedKey * @param strQuery * @return List of WellnessConceptsRelationships */ public List<WellnessConceptsRelationships> listWellnessConceptsByKey(String strSelectedKey, String strQuery); }
/* * ----------------------------------------------------------------------------- * * Copyright 2019 - 2022 UDT-IA, IIIA-CSIC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * ----------------------------------------------------------------------------- */ package eu.internetofus.wenet_dummy.services; import eu.internetofus.common.components.profile_manager.WeNetProfileManager; import eu.internetofus.common.components.profile_manager.WeNetProfileManagerTestCase; import eu.internetofus.wenet_dummy.WeNetDummyIntegrationExtension; import org.junit.jupiter.api.extension.ExtendWith; /** * Test the interaction with the {@link WeNetProfileManager} * * @author UDT-IA, IIIA-CSIC */ @ExtendWith(WeNetDummyIntegrationExtension.class) public class WeNetProfileManagerIT extends WeNetProfileManagerTestCase { }
package com.github.sergueik.selenium_utils; import java.io.File; import java.lang.reflect.Method; import java.nio.file.Paths; import java.util.HashMap; import java.util.Map; import java.util.concurrent.TimeUnit; import java.util.logging.Level; import org.openqa.selenium.Alert; import org.openqa.selenium.By; import org.openqa.selenium.JavascriptExecutor; import org.openqa.selenium.Point; import org.openqa.selenium.TakesScreenshot; import org.openqa.selenium.UnsupportedCommandException; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.chrome.ChromeDriver; import org.openqa.selenium.chrome.ChromeOptions; import org.openqa.selenium.interactions.Actions; import org.openqa.selenium.logging.LogType; import org.openqa.selenium.logging.LoggingPreferences; import org.openqa.selenium.remote.CapabilityType; import org.openqa.selenium.remote.DesiredCapabilities; import org.openqa.selenium.support.ui.ExpectedCondition; import org.openqa.selenium.support.ui.WebDriverWait; import org.testng.ITestResult; import org.testng.annotations.AfterMethod; import org.testng.annotations.AfterTest; import org.testng.annotations.BeforeClass; import org.testng.annotations.BeforeMethod; import org.testng.annotations.Test; /** * Stoppable test example (eclipse SWT version) * @author: Serguei Kouzmine (kouzmine_serguei@yahoo.com) */ public class StoppableTest { public int scriptTimeout = 5; public int flexibleWait = 60; // too long public int implicitWait = 1; public int pollingInterval = 500; private static final boolean headless = Boolean .parseBoolean(System.getenv("HEADLESS")); private static String baseURL = "https://www.linux.org"; // "https://www.urbandictionary.com/"; // NOTE: some sites may be blocked via content filtering // Sorry, www.urbandictionary.com has been blocked by your network // administrator. private static String osName = getOSName(); private static int instanceCount = 0; private static String altURL = "https://www.linux.org.ru/"; private static final StringBuffer verificationErrors = new StringBuffer(); public WebDriver driver; public WebDriverWait wait; public Actions actions; public Alert alert; public JavascriptExecutor js; public TakesScreenshot screenshot; @SuppressWarnings("deprecation") @BeforeClass public void beforeClass() { System .setProperty("webdriver.chrome.driver", Paths.get(System.getProperty("user.home")) .resolve("Downloads").resolve(osName.equals("windows") ? "chromedriver.exe" : "chromedriver") .toAbsolutePath().toString()); ChromeOptions options = new ChromeOptions(); // see also: // https://ivanderevianko.com/2020/04/disable-logging-in-selenium-chromedriver // https://antoinevastel.com/bot%20detection/2017/08/05/detect-chrome-headless.html // @formatter:off for (String optionAgrument : (new String[] { "--allow-insecure-localhost", "--allow-running-insecure-content", "--browser.download.folderList=2", "--browser.helperApps.neverAsk.saveToDisk=image/jpg,text/csv,text/xml,application/xml,application/vnd.ms-excel,application/x-excel,application/x-msexcel,application/excel,application/pdf", "--disable-blink-features=AutomationControlled", "--disable-default-app", "--disable-dev-shm-usage", "--disable-extensions", "--disable-gpu", "--disable-infobars", "--disable-in-process-stack-traces", "--disable-logging", "--disable-notifications", "--disable-popup-blocking", "--disable-save-password-bubble", "--disable-translate", "--disable-web-security", "--enable-local-file-accesses", "--ignore-certificate-errors", "--ignore-certificate-errors", "--ignore-ssl-errors=true", "--log-level=3", "--no-proxy-server", "--no-sandbox", "--output=/dev/null", "--ssl-protocol=any", // "--start-fullscreen", // "--start-maximized" , "--user-agent=Mozilla/5.0 (Windows NT 6.1; WOW64; rv:33.0) Gecko/20120101 Firefox/33.0", // String.format("--browser.download.dir=%s", downloadFilepath) /* * "--user-data-dir=/path/to/your/custom/profile", * "--profile-directory=name_of_custom_profile_directory", */ })) { options.addArguments(optionAgrument); } // @formatter:on driver = new ChromeDriver(options); // driver.setLogLevel(Level.ALL); wait = new WebDriverWait(driver, flexibleWait); // Selenium Driver version sensitive code: 3.13.0 vs. 3.8.0 and older // java has no precompiler #ifdef // wait.pollingEvery(Duration.ofMillis(pollingInterval)); // wait.pollingEvery(pollingInterval, TimeUnit.MILLISECONDS); screenshot = ((TakesScreenshot) driver); js = ((JavascriptExecutor) driver); } @BeforeMethod public void BeforeMethod(Method method) { driver.get(baseURL); ExpectedCondition<Boolean> urlChange = driver -> driver.getCurrentUrl() .matches(String.format("^%s.*", baseURL)); wait.until(urlChange); System.err.println("BeforeMethod: Current URL: " + driver.getCurrentUrl()); } @AfterMethod public void AfterMethod(ITestResult result) { if (verificationErrors.length() != 0) { throw new RuntimeException(String.format("Error(s) in the method %s : %s", result.getMethod().getMethodName(), verificationErrors.toString())); } driver.get("about:blank"); } @AfterTest(alwaysRun = true) public void afterTest() { System.err.println("Finish the test"); driver.quit(); } @Test(enabled = true) public void test1() { // String handle = createWindow(altURL); String name = "Window_" + instanceCount++; // inject an anchor element - will likely appear at the bottom of the page injectElement(name); WebElement element = driver.findElement(By.id(name)); sleep(1000); // scroll to the new page element scroll(element); // stop the test until user chooses to continue TestDialog.show("This is Selenium test supplied message...", false, 10); // TestDialog.show("This is Selenium test supplied message...", true, 10); // continue the test element.click(); sleep(5000); } private void injectElement(String name) { // Inject an anchor element executeScript( "var anchorTag = document.createElement('a'); " + "anchorTag.appendChild(document.createTextNode('nwh'));" + "anchorTag.setAttribute('id', arguments[0]);" + "anchorTag.setAttribute('href', arguments[1]);" + "anchorTag.setAttribute('target', '_blank');" + "anchorTag.setAttribute('style', 'display:block;');" + "var firstElement = document.getElementsByTagName('body')[0].getElementsByTagName('*')[0];" + "firstElement.parentElement.appendChild(anchorTag);", name, altURL); // common error with this approach: Element is not clickable at point // HTML, HEAD, BODY, some element } private void scroll(WebElement element) { try { // element.getLocation() Point location = element.getLocation(); System.err.println("Scrolling to " + location.y); scroll(location.x, location.y); } catch (UnsupportedCommandException e) { System.err.println("Exception (ignored) " + e.toString()); // ignore } } // Scroll public void scroll(final int x, final int y) { final JavascriptExecutor js = (JavascriptExecutor) driver; for (int i = 0; i <= x; i = i + 50) { js.executeScript("scroll(" + i + ",0)"); } for (int j = 0; j <= y; j = j + 50) { js.executeScript("scroll(0," + j + ")"); } } // Utilities private static String getOSName() { if (osName == null) { osName = System.getProperty("os.name").toLowerCase(); if (osName.startsWith("windows")) { osName = "windows"; } } return osName; } public void sleep(Integer milliSeconds) { try { Thread.sleep((long) milliSeconds); } catch (InterruptedException e) { e.printStackTrace(); } } public Object executeScript(String script, Object... arguments) { if (driver instanceof JavascriptExecutor) { JavascriptExecutor javascriptExecutor = JavascriptExecutor.class .cast(driver); return javascriptExecutor.executeScript(script, arguments); } else { throw new RuntimeException("Script execution failed."); } } }
/* * Copyright 2010 JBoss Inc * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.drools.guvnor.client.rpc; import java.util.List; import org.drools.ide.common.client.modeldriven.testing.Scenario; import com.google.gwt.user.client.rpc.IsSerializable; /** * This is essentially a "Either" class. * It will either be a list of rule compiler errors (should it have to compile), or the scenario run results. */ public class ScenarioRunResult implements IsSerializable { private List<BuilderResultLine> errors; private Scenario scenario; public ScenarioRunResult() { } public ScenarioRunResult(List<BuilderResultLine> errors, Scenario scenario) { this.errors = errors; this.scenario = scenario; } public Scenario getScenario() { return scenario; } public List<BuilderResultLine> getErrors() { return errors; } }
/* * Copyright (C) 2004, 2005 Joe Walnes. * Copyright (C) 2006, 2007, 2009, 2011, 2015 XStream Committers. * All rights reserved. * * The software in this package is published under the terms of the BSD * style license a copy of which has been included with this distribution in * the LICENSE.txt file. * * Created on 07. March 2004 by Joe Walnes */ package com.thoughtworks.xstream.io.xml; import com.thoughtworks.xstream.XStreamException; import com.thoughtworks.xstream.io.HierarchicalStreamReader; import com.thoughtworks.xstream.io.xml.xppdom.XppDom; import com.thoughtworks.xstream.io.xml.xppdom.XppFactory; import java.io.StringReader; import java.util.HashMap; import java.util.Map; public class XppDomReaderTest extends AbstractXMLReaderTest { protected HierarchicalStreamReader createReader(String xml) throws Exception { return new Xpp3DomDriver().createReader(new StringReader(xml)); } public void testCanReadFromElementOfLargerDocument() throws Exception { String xml = "<big>" + " <small>" + " <tiny/>" + " </small>" + " <small-two>" + " </small-two>" + "</big>"; XppDom document = XppFactory.buildDom(xml); XppDom small = document.getChild("small"); HierarchicalStreamReader xmlReader = new XppDomReader(small); assertEquals("small", xmlReader.getNodeName()); xmlReader.moveDown(); assertEquals("tiny", xmlReader.getNodeName()); } public void testExposesAttributesKeysAndValuesByIndex() throws Exception { // overrides test in superclass, because XppDom does not retain order of actualAttributes. HierarchicalStreamReader xmlReader = createReader("<node hello='world' a='b' c='d'><empty/></node>"); assertEquals(3, xmlReader.getAttributeCount()); Map expectedAttributes = new HashMap(); expectedAttributes.put("hello", "world"); expectedAttributes.put("a", "b"); expectedAttributes.put("c", "d"); Map actualAttributes = new HashMap(); for (int i = 0; i < xmlReader.getAttributeCount(); i++) { String name = xmlReader.getAttributeName(i); String value = xmlReader.getAttribute(i); actualAttributes.put(name, value); } assertEquals(expectedAttributes, actualAttributes); xmlReader.moveDown(); assertEquals("empty", xmlReader.getNodeName()); assertEquals(0, xmlReader.getAttributeCount()); } @Override public void testIsXXEVulnerableWithExternalGeneralEntity() throws Exception { try { super.testIsXXEVulnerableWithExternalGeneralEntity(); fail("Thrown " + XStreamException.class.getName() + " expected"); } catch (final XStreamException e) { final String message = e.getMessage(); if (!message.contains("resolve entity")) { throw e; } } } }
/* * 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 * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.google.zetasql; import com.google.common.base.Preconditions; import com.google.common.collect.ImmutableList; import com.google.protobuf.BoolValue; import com.google.protobuf.BytesValue; import com.google.protobuf.DescriptorProtos.EnumValueDescriptorProto; import com.google.protobuf.DoubleValue; import com.google.protobuf.FloatValue; import com.google.protobuf.Int32Value; import com.google.protobuf.Int64Value; import com.google.protobuf.StringValue; import com.google.protobuf.Timestamp; import com.google.protobuf.UInt32Value; import com.google.protobuf.UInt64Value; import com.google.zetasql.FunctionProtos.FunctionProto; import com.google.zetasql.FunctionProtos.ProcedureProto; import com.google.zetasql.FunctionProtos.TableValuedFunctionProto; import com.google.zetasql.ZetaSQLDescriptorPool.ZetaSQLDescriptor; import com.google.zetasql.ZetaSQLDescriptorPool.ZetaSQLEnumDescriptor; import com.google.zetasql.ZetaSQLOptionsProto.ZetaSQLBuiltinFunctionOptionsProto; import com.google.zetasql.ZetaSQLType.TypeProto; import com.google.zetasql.LocalService.AddSimpleTableRequest; import com.google.zetasql.LocalService.GetBuiltinFunctionsResponse; import com.google.zetasql.LocalService.RegisterCatalogRequest; import com.google.zetasql.LocalService.RegisterResponse; import com.google.zetasql.LocalService.UnregisterRequest; import com.google.zetasql.SimpleCatalogProtos.SimpleCatalogProto; import com.google.zetasql.SimpleCatalogProtos.SimpleCatalogProto.NamedTypeProto; import com.google.zetasql.SimpleConstantProtos.SimpleConstantProto; import com.google.zetasql.SimpleTableProtos.SimpleTableProto; import com.google.zetasql.functions.ZetaSQLDateTime.DateTimestampPart; import com.google.zetasql.functions.ZetaSQLNormalizeMode.NormalizeMode; import com.google.type.Date; import com.google.type.LatLng; import com.google.type.TimeOfDay; import io.grpc.StatusRuntimeException; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.logging.Logger; /** * SimpleCatalog is a concrete implementation of the Catalog interface. It acts as a simple * container for objects in the Catalog. * * <p>This class and related SimpleX classes are final by design because a subclass is unlikely to * get serialize method right. The serialize method returns a SimpleCatalogProto. A subclass most * likely needs more fields and hence needs a different proto. But proto class is final so a * subclass cannot override this class's serialize method and return a subclass of * SimpleCatalogProto. TODO: Add findTableById. * * <p>To improve RPC performance, a SimpleCatalog can be registered on the local server, and later * requests involving this SimpleCatalog will only pass the registered ID instead of the fully * serialized form. A registered SimpleCatalog can and should be unregistered when it is no longer * used. The unregister() method is called in finalize(), but users shouldn't rely on that because * the JVM doesn't know of the memory resource taken by the registered catalog on the local * server, and may start the garbage collector later than necessary. */ public class SimpleCatalog extends Catalog { private static final Logger logger = Logger.getLogger(SimpleCatalog.class.getName()); private final String name; private final TypeFactory typeFactory; // All String keys are stored in lower case. private final Map<String, Constant> constants = new HashMap<>(); private final Map<String, SimpleTable> tables = new HashMap<>(); private final Map<String, Type> types = new HashMap<>(); private final Map<String, SimpleCatalog> catalogs = new HashMap<>(); private final Map<Long, SimpleTable> tablesById = new HashMap<>(); private final Map<String, Function> customFunctions = new HashMap<>(); private final Map<String, TableValuedFunction> tvfs = new HashMap<>(); private final Map<String, Function> functionsByFullName = new HashMap<>(); private final Map<String, Procedure> procedures = new HashMap<>(); private ZetaSQLDescriptorPool descriptorPool; ZetaSQLBuiltinFunctionOptionsProto builtinFunctionOptions; boolean registered = false; long registeredId = -1; FileDescriptorSetsBuilder registeredFileDescriptorSetsBuilder = null; public SimpleCatalog(String name, TypeFactory typeFactory) { this.name = name; this.typeFactory = Preconditions.checkNotNull(typeFactory); } public SimpleCatalog(String name) { this(name, TypeFactory.nonUniqueNames()); } /** * Register this catalog to local server, so that it can be reused without passing through RPC * every time. * * @return An AutoCloseable object that can be used to unregister the catalog in * try-with-resources structure. */ public AutoUnregister register() { Preconditions.checkState(!registered); registeredFileDescriptorSetsBuilder = new FileDescriptorSetsBuilder(); RegisterCatalogRequest.Builder builder = RegisterCatalogRequest.newBuilder(); builder.setSimpleCatalog(serialize(registeredFileDescriptorSetsBuilder)); builder.addAllFileDescriptorSet(registeredFileDescriptorSetsBuilder.build()); try { RegisterResponse resp = Client.getStub().registerCatalog(builder.build()); registeredId = resp.getRegisteredId(); } catch (StatusRuntimeException e) { throw new SqlException(e); } registered = true; return new AutoUnregister(); } public void unregister() { Preconditions.checkState(registered); try { Client.getStub() .unregisterCatalog(UnregisterRequest.newBuilder().setRegisteredId(registeredId).build()); } catch (StatusRuntimeException e) { // Maybe caused by double unregistering (in race conditions) or RPC // failure. The latter may cause leak but it's likely due to more serious // problems and there is no good way to recover. Just log and ignore. logger.severe("Failed to unregister catalog: " + e.getMessage()); } finally { registered = false; registeredId = -1; registeredFileDescriptorSetsBuilder = null; } } public boolean isRegistered() { return registered; } long getRegisteredId() { Preconditions.checkState(registered); return registeredId; } @Override protected void finalize() { if (registered) { unregister(); } } FileDescriptorSetsBuilder getRegisteredFileDescriptorSetsBuilder() { Preconditions.checkState(registered); return registeredFileDescriptorSetsBuilder; } /** * Serialize this catalog into protobuf, with FileDescriptors emitted to the builder as needed. */ public SimpleCatalogProto serialize(FileDescriptorSetsBuilder fileDescriptorSetsBuilder) { SimpleCatalogProto.Builder builder = SimpleCatalogProto.newBuilder(); builder.setName(name); // The built-in function definations are not serialized. Instead, the BuiltinFunctionOptions // which specify which functions to include and exclude will be serialized, and the C++ // deserialization will recreate the same built-in function signatures according to this. if (builtinFunctionOptions != null) { builder.setBuiltinFunctionOptions(builtinFunctionOptions); } for (Entry<String, SimpleTable> table : tables.entrySet()) { SimpleTableProto.Builder tableBuilder = builder.addTableBuilder(); tableBuilder.mergeFrom(table.getValue().serialize(fileDescriptorSetsBuilder)); if (!table.getKey().equals(tableBuilder.getName().toLowerCase())) { tableBuilder.setNameInCatalog(table.getKey()); } } for (Entry<String, Type> type : types.entrySet()) { TypeProto.Builder typeProtoBuilder = TypeProto.newBuilder(); type.getValue().serialize(typeProtoBuilder, fileDescriptorSetsBuilder); builder.addNamedType( NamedTypeProto.newBuilder().setName(type.getKey()).setType(typeProtoBuilder.build())); } for (Entry<String, SimpleCatalog> catalog : catalogs.entrySet()) { builder.addCatalog(catalog.getValue().serialize(fileDescriptorSetsBuilder)); } for (Entry<String, TableValuedFunction> tvf : tvfs.entrySet()) { builder.addCustomTvf(tvf.getValue().serialize(fileDescriptorSetsBuilder)); } for (Entry<String, Constant> constant : constants.entrySet()) { builder.addConstant(constant.getValue().serialize(fileDescriptorSetsBuilder)); } for (Entry<String, Function> function : customFunctions.entrySet()) { builder.addCustomFunction(function.getValue().serialize(fileDescriptorSetsBuilder)); } for (Entry<String, Procedure> procedure : procedures.entrySet()) { builder.addProcedure(procedure.getValue().serialize(fileDescriptorSetsBuilder)); } if (descriptorPool != null) { builder.setFileDescriptorSetIndex( fileDescriptorSetsBuilder.addAllFileDescriptors(descriptorPool)); } return builder.build(); } /** Add simple constant into this catalog. Constant names are case insensitive. */ public void addConstant(Constant constant) { Preconditions.checkState(!registered); Preconditions.checkArgument(!constants.containsKey(constant.getFullName().toLowerCase())); List<String> namePath = constant.getNamePath(); Preconditions.checkArgument(!namePath.isEmpty()); constants.put(namePath.get(namePath.size() - 1).toLowerCase(), constant); } /** * Add simple table into this catalog. Table names are case insensitive. * * @param table */ public void addSimpleTable(SimpleTable table) { addSimpleTable(table.getName(), table); } public void addSimpleTable(String name, SimpleTable table) { Preconditions.checkArgument(!tables.containsKey(name.toLowerCase()), "duplicate key: %s", name); if (registered) { synchronized (this) { try { FileDescriptorSetsBuilder temp = new FileDescriptorSetsBuilder(); temp.importDescriptorPoolIndex(registeredFileDescriptorSetsBuilder); SimpleTableProto tableProto = table.serialize(temp); FileDescriptorSetsBuilder diff = registeredFileDescriptorSetsBuilder.mergeDiff(temp); AddSimpleTableRequest.Builder requestBuilder = AddSimpleTableRequest.newBuilder(); requestBuilder.setRegisteredCatalogId(registeredId); requestBuilder.setTable(tableProto); requestBuilder.addAllFileDescriptorSet(diff.build()); Client.getStub().addSimpleTable(requestBuilder.build()); } catch (StatusRuntimeException e) { throw new SqlException(e); } } } tables.put(name.toLowerCase(), table); tablesById.put(table.getId(), table); } /** * Removes a simple table from this catalog. */ public void removeSimpleTable(SimpleTable table) { removeSimpleTable(table.getName()); } /** * Removes a simple table from this catalog. Table names are case insensitive. */ public void removeSimpleTable(String name) { Preconditions.checkState(!registered); Preconditions.checkArgument(tables.containsKey(name.toLowerCase()), "missing key: %s", name); SimpleTable table = tables.remove(name.toLowerCase()); tablesById.remove(table.getId()); } /** * Add type into this catalog. Type names are case insensitive. * * @param name * @param type */ public void addType(String name, Type type) { Preconditions.checkState(!registered); Preconditions.checkArgument(!types.containsKey(name.toLowerCase()), "duplicate key: %s", name); types.put(name.toLowerCase(), type); } /** * Removes the type with the passed name from this catalog. Type names are case insensitive. */ public void removeType(String name) { Preconditions.checkState(!registered); Preconditions.checkArgument(types.containsKey(name.toLowerCase()), "missing key: %s", name); types.remove(name.toLowerCase()); } /** * Add sub catalog into this catalog. Catalog names are case insensitive. * * @param catalog */ public void addSimpleCatalog(SimpleCatalog catalog) { Preconditions.checkState(!registered); Preconditions.checkArgument( !catalogs.containsKey(catalog.getFullName().toLowerCase()), "duplicate key: %s", catalog.getFullName()); catalogs.put(catalog.getFullName().toLowerCase(), catalog); } /** * Create a new catalog and add the new catalog into this catalog and return the new sub catalog. * Catalog names are case insensitive. * * @param name * @return the created new sub catalog */ public SimpleCatalog addNewSimpleCatalog(String name) { Preconditions.checkState(!registered); SimpleCatalog newCatalog = new SimpleCatalog(name, getTypeFactory()); addSimpleCatalog(newCatalog); return newCatalog; } /** * Removes the passed sub catalog from this catalog. */ public void removeSimpleCatalog(SimpleCatalog catalog) { removeSimpleCatalog(catalog.getFullName()); } /** * Removes the sub catalog with the passed name from this catalog. Catalog names are case * insensitive. */ public void removeSimpleCatalog(String fullName) { Preconditions.checkState(!registered); Preconditions.checkArgument(catalogs.containsKey(fullName.toLowerCase()), "missing key: %s", fullName); catalogs.remove(fullName.toLowerCase()); } /** * Add ZetaSQL built-in function definitions into this catalog. Function names are case * insensitive. * * @param options used to select which functions get loaded. */ public void addZetaSQLFunctions(ZetaSQLBuiltinFunctionOptions options) { Preconditions.checkNotNull(options); Preconditions.checkState(builtinFunctionOptions == null); builtinFunctionOptions = options.serialize(); try { GetBuiltinFunctionsResponse response = Client.getStub().getBuiltinFunctions(builtinFunctionOptions); processGetBuiltinFunctionsResponse(response); } catch (StatusRuntimeException e) { throw new SqlException(e); } } void processGetBuiltinFunctionsResponse(GetBuiltinFunctionsResponse response) { // Datetime and string normalization functions have arguments of enum types, which needs to // import the enum descriptor to descriptor pool so that these argument types can be // deserialized properly. // This should be updated when new built in functions with enum or proto type arguments // are added. ZetaSQLDescriptorPool.importIntoGeneratedPool(DateTimestampPart.getDescriptor()); ZetaSQLDescriptorPool.importIntoGeneratedPool(NormalizeMode.getDescriptor()); ZetaSQLDescriptorPool.importIntoGeneratedPool(Timestamp.getDescriptor()); ZetaSQLDescriptorPool.importIntoGeneratedPool(Date.getDescriptor()); ZetaSQLDescriptorPool.importIntoGeneratedPool(TimeOfDay.getDescriptor()); ZetaSQLDescriptorPool.importIntoGeneratedPool(LatLng.getDescriptor()); ZetaSQLDescriptorPool.importIntoGeneratedPool(DoubleValue.getDescriptor()); ZetaSQLDescriptorPool.importIntoGeneratedPool(FloatValue.getDescriptor()); ZetaSQLDescriptorPool.importIntoGeneratedPool(Int64Value.getDescriptor()); ZetaSQLDescriptorPool.importIntoGeneratedPool(UInt64Value.getDescriptor()); ZetaSQLDescriptorPool.importIntoGeneratedPool(Int32Value.getDescriptor()); ZetaSQLDescriptorPool.importIntoGeneratedPool(UInt32Value.getDescriptor()); ZetaSQLDescriptorPool.importIntoGeneratedPool(BoolValue.getDescriptor()); ZetaSQLDescriptorPool.importIntoGeneratedPool(StringValue.getDescriptor()); ZetaSQLDescriptorPool.importIntoGeneratedPool(BytesValue.getDescriptor()); ZetaSQLDescriptorPool.importIntoGeneratedPool(EnumValueDescriptorProto.getDescriptor()); ImmutableList<ZetaSQLDescriptorPool> pools = ImmutableList.of(ZetaSQLDescriptorPool.getGeneratedPool()); for (FunctionProto proto : response.getFunctionList()) { addFunctionToFullNameMap(Function.deserialize(proto, pools)); } } /** * Add function into this catalog. Function name and alias name will both be stored if different. * Names are case insensitive. * * @param function */ public void addFunction(Function function) { Preconditions.checkState(!registered); Preconditions.checkArgument(!customFunctions.containsKey(function.getName().toLowerCase())); customFunctions.put(function.getName().toLowerCase(), function); if (!function.getOptions().getAliasName().isEmpty() && !function.getOptions().getAliasName().equals(function.getName())) { Preconditions.checkArgument( !customFunctions.containsKey(function.getOptions().getAliasName().toLowerCase())); customFunctions.put(function.getOptions().getAliasName().toLowerCase(), function); } addFunctionToFullNameMap(function); } private void addFunctionToFullNameMap(Function function) { String functionName = function.getFullName().toLowerCase(); Preconditions.checkArgument( !functionsByFullName.containsKey(functionName), functionName + " already exists."); functionsByFullName.put(functionName, function); } /** * Removes the passed function from this catalog. */ public void removeFunction(Function function) { removeFunction(function.getFullName()); } /** * Removes the function with the passed full name from this catalog. */ public void removeFunction(String fullName) { Preconditions.checkState(!registered); Function function = getFunctionByFullName(fullName); Preconditions.checkArgument(function != null); Preconditions.checkArgument(customFunctions.containsKey(function.getName().toLowerCase())); customFunctions.remove(function.getName().toLowerCase()); if (!function.getOptions().getAliasName().isEmpty()) { customFunctions.remove(function.getOptions().getAliasName().toLowerCase()); } removeFunctionFromFullNameMap(function); } /** Add the given {@code tvf} to this catalog. Names are case insensitive. */ public void addTableValuedFunction(TableValuedFunction tvf) { Preconditions.checkState(!registered); String tvfName = tvf.getName().toLowerCase(); Preconditions.checkArgument(!tvfs.containsKey(tvfName)); tvfs.put(tvfName, tvf); } /** Removes the passed TVF from this catalog. */ public void removeTableValuedFunction(TableValuedFunction tvf) { removeTableValuedFunction(tvf.getFullName()); } /** Removes the TVF with the passed full name from this catalog. */ public void removeTableValuedFunction(String name) { Preconditions.checkState(!registered); String lowerCaseName = name.toLowerCase(); TableValuedFunction tvf = getTVFByName(lowerCaseName); Preconditions.checkArgument(tvf != null); tvfs.remove(lowerCaseName); } private void removeFunctionFromFullNameMap(Function function) { Preconditions.checkArgument( functionsByFullName.containsKey(function.getFullName().toLowerCase())); functionsByFullName.remove(function.getFullName().toLowerCase()); } /** * Add procedure into this catalog. Names are case insensitive. * * @param procedure */ public void addProcedure(Procedure procedure) { Preconditions.checkState(!registered); Preconditions.checkArgument(!procedures.containsKey(procedure.getName().toLowerCase())); procedures.put(procedure.getName().toLowerCase(), procedure); } /** * Removes the passed procedure from this catalog. */ public void removeProcedure(Procedure procedure) { removeProcedure(procedure.getName()); } /** * Removes the procedure with the passed name from this catalog. Names are case insensitive. */ public void removeProcedure(String name) { Preconditions.checkState(!registered); Preconditions.checkArgument(procedures.containsKey(name.toLowerCase())); procedures.remove(name.toLowerCase()); } public void setDescriptorPool(ZetaSQLDescriptorPool descriptorPool) { Preconditions.checkState(!registered); Preconditions.checkState(this.descriptorPool == null); this.descriptorPool = descriptorPool; } @Override public String getFullName() { return name; } public TypeFactory getTypeFactory() { return typeFactory; } public ImmutableList<String> getTableNameList() { return ImmutableList.copyOf(tables.keySet()); } public ImmutableList<SimpleTable> getTableList() { return ImmutableList.copyOf(tables.values()); } public ImmutableList<Type> getTypeList() { return ImmutableList.copyOf(types.values()); } public ImmutableList<SimpleCatalog> getCatalogList() { return ImmutableList.copyOf(catalogs.values()); } public ImmutableList<Function> getFunctionList() { return ImmutableList.copyOf(functionsByFullName.values()); } public ImmutableList<TableValuedFunction> getTVFList() { return ImmutableList.copyOf(tvfs.values()); } public ImmutableList<String> getFunctionNameList() { return ImmutableList.copyOf(functionsByFullName.keySet()); } public ImmutableList<String> getTVFNameList() { return ImmutableList.copyOf(tvfs.keySet()); } public ImmutableList<Procedure> getProcedureList() { return ImmutableList.copyOf(procedures.values()); } @Override protected Constant getConstant(String name, FindOptions options) { return constants.get(name.toLowerCase()); } @Override public SimpleTable getTable(String name, FindOptions options) { return tables.get(name.toLowerCase()); } @Override public Type getType(String name, FindOptions options) { if (types.containsKey(name.toLowerCase())) { return types.get(name.toLowerCase()); } if (descriptorPool != null) { ZetaSQLDescriptor descriptor = descriptorPool.findMessageTypeByName(name); if (descriptor != null) { return getTypeFactory().createProtoType(descriptor); } ZetaSQLEnumDescriptor enumDescriptor = descriptorPool.findEnumTypeByName(name); if (enumDescriptor != null) { return getTypeFactory().createEnumType(enumDescriptor); } } return null; } @Override public SimpleCatalog getCatalog(String name, FindOptions options) { return catalogs.get(name.toLowerCase()); } public Function getFunctionByFullName(String fullName) { Function function = functionsByFullName.get(fullName.toLowerCase()); if (function == null) { for (SimpleCatalog catalog : catalogs.values()) { function = catalog.getFunctionByFullName(fullName); if (function != null) { break; } } } return function; } public TableValuedFunction getTVFByName(String name) { return tvfs.get(name.toLowerCase()); } public SimpleTable getTableById(long serializationId) { SimpleTable table = tablesById.get(serializationId); if (table == null) { for (SimpleCatalog catalog : catalogs.values()) { table = catalog.getTableById(serializationId); if (table != null) { break; } } } return table; } public SimpleModel getModelById(long serializationId) { // TODO: Add support for Model in the Java implementation. return null; } public SimpleConnection getConnectionByFullName(String fullName) { // TODO: Add support for Connection in the Java implementation. return null; } @Override protected Procedure getProcedure(String name, FindOptions options) { return procedures.get(name.toLowerCase()); } /** * AutoCloseable implementation that unregisters the SimpleCatalog automatically when used in * try-with-resources. */ public class AutoUnregister implements AutoCloseable { @Override public void close() { unregister(); } } public static SimpleCatalog deserialize( SimpleCatalogProto proto, ImmutableList<ZetaSQLDescriptorPool> pools) { SimpleCatalog catalog = new SimpleCatalog(proto.getName()); for (SimpleTableProto tableProto : proto.getTableList()) { String name = tableProto.hasNameInCatalog() ? tableProto.getNameInCatalog() : tableProto.getName(); catalog.addSimpleTable( name, SimpleTable.deserialize(tableProto, pools, catalog.getTypeFactory())); } for (NamedTypeProto typeProto : proto.getNamedTypeList()) { catalog.addType( typeProto.getName(), catalog.getTypeFactory().deserialize(typeProto.getType(), pools)); } for (SimpleCatalogProto catalogProto : proto.getCatalogList()) { catalog.addSimpleCatalog(SimpleCatalog.deserialize(catalogProto, pools)); } for (SimpleConstantProto constantProto : proto.getConstantList()) { catalog.addConstant(Constant.deserialize(constantProto, pools, catalog.getTypeFactory())); } for (TableValuedFunctionProto tvfProto : proto.getCustomTvfList()) { catalog.addTableValuedFunction( TableValuedFunction.deserialize(tvfProto, pools, catalog.getTypeFactory())); } for (FunctionProto functionProto : proto.getCustomFunctionList()) { catalog.addFunction(Function.deserialize(functionProto, pools)); } for (ProcedureProto procedureProto : proto.getProcedureList()) { catalog.addProcedure(Procedure.deserialize(procedureProto, pools)); } if (proto.hasBuiltinFunctionOptions()) { ZetaSQLBuiltinFunctionOptions options = new ZetaSQLBuiltinFunctionOptions(proto.getBuiltinFunctionOptions()); catalog.addZetaSQLFunctions(options); } if (proto.hasFileDescriptorSetIndex()) { catalog.setDescriptorPool(pools.get(proto.getFileDescriptorSetIndex())); } return catalog; } }
package com.mindao.entity; import java.io.Serializable; import java.util.Date; import java.util.List; /** * * * @author liguocai * @email 153277817@qq.com * @date 2017-06-14 14:02:08 */ public class UserEntity implements Serializable { private static final long serialVersionUID = 1L; public static final String STATUS_ACTIVE="1"; public static final String STATUS_INACTIVE="0"; // private String uid; // private String email; // private String mobile; //MD5加密 private String password; //0-未验证 1-验证 private String emailFlag; //0-绑定 1-绑定 private String mobileFlag; //按照普通路径存储 private String avatar; // private String nickName; //0-未锁住 1-锁住 private String isLocked; // private String retryTimes; // private Date registerTime; //CN-中国 USA-美国 private String registerRegion; // private Date lastModifyTime; // private Integer lid; //S01-IPC S02-JustFit S03-SmartThemetre private String registerFrom; // private String activeCode; // private Date lastActiveTime; //0-未激活 1-激活 private String status; //注册类型:0:email,1:mobile private String accType; // private Float timezone; //手机类型1苹果,2安卓,3微软mp private Integer mobileType; //消息平台类型:10苹果原生20Google原生21 极光24小米25华为… private Integer msgPlatformType; //云消息平台的注册id private String msgRegId; // private Date msgRegTime; //手机设备id private String mobileDeviceId; // private Date loginTime; // private Integer loginState; //前台用的字段===================================== //按照普通路径存储,全路径, private String avatarPath; //0-未激活 1-激活 // private String statusName; private List<UserDeviceEntity> devices; /** * 设置: */ public void setUid(String uid) { this.uid = uid; } /** * 获取: */ public String getUid() { return uid; } /** * 设置: */ public void setEmail(String email) { this.email = email; } /** * 获取: */ public String getEmail() { return email; } /** * 设置: */ public void setMobile(String mobile) { this.mobile = mobile; } /** * 获取: */ public String getMobile() { return mobile; } /** * 设置:MD5加密 */ public void setPassword(String password) { this.password = password; } /** * 获取:MD5加密 */ public String getPassword() { return password; } /** * 设置:0-未验证 1-验证 */ public void setEmailFlag(String emailFlag) { this.emailFlag = emailFlag; } /** * 获取:0-未验证 1-验证 */ public String getEmailFlag() { return emailFlag; } /** * 设置:0-绑定 1-绑定 */ public void setMobileFlag(String mobileFlag) { this.mobileFlag = mobileFlag; } /** * 获取:0-绑定 1-绑定 */ public String getMobileFlag() { return mobileFlag; } /** * 设置:S3:开头按照S3存储 NOR:开头按照普通路径存储 */ public void setAvatar(String avatar) { this.avatar = avatar; } /** * 获取:S3:开头按照S3存储 NOR:开头按照普通路径存储 */ public String getAvatar() { return avatar; } /** * 设置: */ public void setNickName(String nickName) { this.nickName = nickName; } /** * 获取: */ public String getNickName() { return nickName; } /** * 设置:0-未锁住 1-锁住 */ public void setIsLocked(String isLocked) { this.isLocked = isLocked; } /** * 获取:0-未锁住 1-锁住 */ public String getIsLocked() { return isLocked; } /** * 设置: */ public void setRetryTimes(String retryTimes) { this.retryTimes = retryTimes; } /** * 获取: */ public String getRetryTimes() { return retryTimes; } /** * 设置: */ public void setRegisterTime(Date registerTime) { this.registerTime = registerTime; } /** * 获取: */ public Date getRegisterTime() { return registerTime; } /** * 设置:CN-中国 USA-美国 */ public void setRegisterRegion(String registerRegion) { this.registerRegion = registerRegion; } /** * 获取:CN-中国 USA-美国 */ public String getRegisterRegion() { return registerRegion; } /** * 设置: */ public void setLastModifyTime(Date lastModifyTime) { this.lastModifyTime = lastModifyTime; } /** * 获取: */ public Date getLastModifyTime() { return lastModifyTime; } /** * 设置: */ public void setLid(Integer lid) { this.lid = lid; } /** * 获取: */ public Integer getLid() { return lid; } /** * 设置:S01-IPC S02-JustFit S03-SmartThemetre */ public void setRegisterFrom(String registerFrom) { this.registerFrom = registerFrom; } /** * 获取:S01-IPC S02-JustFit S03-SmartThemetre */ public String getRegisterFrom() { return registerFrom; } /** * 设置: */ public void setActiveCode(String activeCode) { this.activeCode = activeCode; } /** * 获取: */ public String getActiveCode() { return activeCode; } /** * 设置: */ public void setLastActiveTime(Date lastActiveTime) { this.lastActiveTime = lastActiveTime; } /** * 获取: */ public Date getLastActiveTime() { return lastActiveTime; } /** * 设置:0-未激活 1-激活 */ public void setStatus(String status) { this.status = status; } /** * 获取:0-未激活 1-激活 */ public String getStatus() { return status; } /** * 设置:注册类型:0:email,1:mobile */ public void setAccType(String accType) { this.accType = accType; } /** * 获取:注册类型:0:email,1:mobile */ public String getAccType() { return accType; } /** * 设置: */ public void setTimezone(Float timezone) { this.timezone = timezone; } /** * 获取: */ public Float getTimezone() { return timezone; } /** * 设置:手机类型1苹果,2安卓,3微软mp */ public void setMobileType(Integer mobileType) { this.mobileType = mobileType; } /** * 获取:手机类型1苹果,2安卓,3微软mp */ public Integer getMobileType() { return mobileType; } /** * 设置:消息平台类型:10苹果原生20Google原生21 极光24小米25华为… */ public void setMsgPlatformType(Integer msgPlatformType) { this.msgPlatformType = msgPlatformType; } /** * 获取:消息平台类型:10苹果原生20Google原生21 极光24小米25华为… */ public Integer getMsgPlatformType() { return msgPlatformType; } /** * 设置:云消息平台的注册id */ public void setMsgRegId(String msgRegId) { this.msgRegId = msgRegId; } /** * 获取:云消息平台的注册id */ public String getMsgRegId() { return msgRegId; } /** * 设置: */ public void setMsgRegTime(Date msgRegTime) { this.msgRegTime = msgRegTime; } /** * 获取: */ public Date getMsgRegTime() { return msgRegTime; } /** * 设置:手机设备id */ public void setMobileDeviceId(String mobileDeviceId) { this.mobileDeviceId = mobileDeviceId; } /** * 获取:手机设备id */ public String getMobileDeviceId() { return mobileDeviceId; } /** * 设置: */ public void setLoginTime(Date loginTime) { this.loginTime = loginTime; } /** * 获取: */ public Date getLoginTime() { return loginTime; } /** * 设置: */ public void setLoginState(Integer loginState) { this.loginState = loginState; } /** * 获取: */ public Integer getLoginState() { return loginState; } public String getAvatarPath() { return avatarPath; } public void setAvatarPath(String avatarPath) { this.avatarPath = avatarPath; } public String getStatusName() { if (STATUS_ACTIVE.equals(status)){ return "已激活(active)"; }else{ return "未激活(inactive)"; } } // public void setStatusName(String statusName) { // this.statusName = statusName; // } public List<UserDeviceEntity> getDevices() { return devices; } public void setDevices(List<UserDeviceEntity> devices) { this.devices = devices; } }
package com.planet_ink.coffee_mud.Abilities.Poisons; import com.planet_ink.coffee_mud.core.interfaces.*; import com.planet_ink.coffee_mud.core.*; import com.planet_ink.coffee_mud.core.collections.*; import com.planet_ink.coffee_mud.Abilities.interfaces.*; import com.planet_ink.coffee_mud.Areas.interfaces.*; import com.planet_ink.coffee_mud.Behaviors.interfaces.*; import com.planet_ink.coffee_mud.CharClasses.interfaces.*; import com.planet_ink.coffee_mud.Commands.interfaces.*; import com.planet_ink.coffee_mud.Common.interfaces.*; import com.planet_ink.coffee_mud.Exits.interfaces.*; import com.planet_ink.coffee_mud.Items.interfaces.*; import com.planet_ink.coffee_mud.Libraries.interfaces.*; import com.planet_ink.coffee_mud.Locales.interfaces.*; import com.planet_ink.coffee_mud.MOBS.interfaces.*; import com.planet_ink.coffee_mud.Races.interfaces.*; import java.util.*; /* Copyright 2003-2018 Bo Zimmerman Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ public class Poison_Venom extends Poison { @Override public String ID() { return "Poison_Venom"; } private final static String localizedName = CMLib.lang().L("Venom"); @Override public String name() { return localizedName; } private static final String[] triggerStrings =I(new String[] {"POISONBITE"}); @Override public String[] triggerStrings() { return triggerStrings; } @Override protected int POISON_TICKS() { return 25; } // 0 means no adjustment! @Override protected int POISON_DELAY() { return 2; } @Override protected String POISON_DONE() { return "The venom runs its course."; } @Override protected String POISON_START() { return "^G<S-NAME> turn(s) green.^?"; } @Override protected String POISON_AFFECT() { return "<S-NAME> cringe(s) as the venom courses through <S-HIS-HER> blood."; } @Override protected String POISON_CAST() { return "^F^<FIGHT^><S-NAME> bite(s) <T-NAMESELF>!^</FIGHT^>^?"; } @Override protected String POISON_FAIL() { return "<S-NAME> attempt(s) to bite <T-NAMESELF>, but fail(s)."; } @Override protected int POISON_DAMAGE() { return (invoker!=null)?CMLib.dice().roll(1,9,1):0; } @Override public void affectCharStats(final MOB affected, final CharStats affectableStats) { affectableStats.setStat(CharStats.STAT_CONSTITUTION,affectableStats.getStat(CharStats.STAT_CONSTITUTION)-7); affectableStats.setStat(CharStats.STAT_STRENGTH,affectableStats.getStat(CharStats.STAT_STRENGTH)-3); if(affectableStats.getStat(CharStats.STAT_CONSTITUTION)<=0) affectableStats.setStat(CharStats.STAT_CONSTITUTION,1); if(affectableStats.getStat(CharStats.STAT_STRENGTH)<=0) affectableStats.setStat(CharStats.STAT_STRENGTH,1); } }
package it.polimi.ingsw.network; import it.polimi.ingsw.commons.User; import it.polimi.ingsw.utils.GameMode; import it.polimi.ingsw.utils.messages.clientMessages.*; import it.polimi.ingsw.utils.messages.serverMessages.*; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.net.Socket; import java.net.SocketTimeoutException; import java.util.List; import java.util.logging.Level; import java.util.logging.Logger; /** * This is a Runnable class that is instantiated whenever a client connects to the server and * it holds the communication until a disconnection occurs. * It handles configuration messages and delegates game messages to remote view. */ public class ClientStatus implements Runnable { private Server server; private NetworkRemoteView remoteView; private boolean isActive; private ObjectOutputStream outputStreamToClient; private ObjectInputStream inputFromClient; private final Socket socket; private String nickname; private GameMode mode; private int numOfPlayers; /** * State of connection that allows to know which kind of message is to expect */ private ConnectionStates connectionState; private final Logger LOGGER = Logger.getLogger(ClientStatus.class.getName()); /** * Initializes an active ClientStatus * @param socket socket that identifies the client that has to be handled by this instance * @param server server to which it belongs. */ public ClientStatus(Socket socket, Server server) { this.socket = socket; this.server = server; this.isActive = true; this.connectionState = ConnectionStates.CONFIGURATION; } /** * Synchronized method called by remote view to send message to the client. * @param serverMessage an instance of a server message to be sent. */ public synchronized void send(ServerMessage serverMessage) { try { outputStreamToClient.reset(); outputStreamToClient.writeObject(serverMessage); outputStreamToClient.flush(); } catch (IOException e) { e.printStackTrace(System.out); LOGGER.log(Level.SEVERE, "Disconnection detected while sending a message"); isActive = false; } } /** * Method that runs until the connection is open. * It receives all the messages sent from remote host and forwards them to remote view, if required. * According to the state of connection, it handles {@link SocketTimeoutException} and {@link IOException} * if the connection with client goes lost. */ public void run(){ try { outputStreamToClient = new ObjectOutputStream(socket.getOutputStream()); outputStreamToClient.flush(); //This is required otherwise following instantiation of ObjectInputStream will block forever inputFromClient = new ObjectInputStream(socket.getInputStream()); send(new ServerAsksForNickname()); while(isActive) { Object message = inputFromClient.readObject(); if(message instanceof PingMessage) { server.reply(() -> { send(new PongMessage()); }); } else { try { if (connectionState == ConnectionStates.CONFIGURATION) { ((ConfigurationMessage)message).handleConfigurationMessage(this); } else if (connectionState == ConnectionStates.INGAME) { GameControllerHandleable messageFromClient = (GameControllerHandleable) message; remoteView.handleClientMessage(messageFromClient); LOGGER.log(Level.INFO, "Message from client of type "+messageFromClient.getClass().getName()); } } catch (ClassCastException e) { LOGGER.log(Level.INFO, ""+message.getClass().getName()); LOGGER.log(Level.INFO, "Wrong type message"); } } } } catch (SocketTimeoutException e) { if(this.connectionState == ConnectionStates.INGAME) { isActive = false; this.connectionState = ConnectionStates.DISCONNECTED; remoteView.handlePlayerDisconnection(); LOGGER.log(Level.SEVERE, "Client disconnected while playing a match"); } if(this.connectionState == ConnectionStates.CONFIGURATION) { isActive = false; this.connectionState = ConnectionStates.DISCONNECTED; server.removeNotSetupPlayer(this); LOGGER.log(Level.INFO, "Client disconnected while waiting for a game to start"); } } catch (IOException e) { if(this.connectionState == ConnectionStates.INGAME) { isActive = false; this.connectionState = ConnectionStates.DISCONNECTED; remoteView.handlePlayerDisconnection(); LOGGER.log(Level.SEVERE, "Client disconnected while playing a match"); } if(this.connectionState == ConnectionStates.CONFIGURATION) { isActive = false; this.connectionState = ConnectionStates.DISCONNECTED; server.removeNotSetupPlayer(this); LOGGER.log(Level.INFO, "Client disconnected while waiting for a game to start"); } } catch (ClassNotFoundException e) { LOGGER.log(Level.SEVERE, "Error in receiving message from client"); } } /** * This method is used when a game has been initialized by Server. When a client connects * it hasn't any game instance yet, so after game creation a {@link NetworkRemoteView} is instantiated inside the ClientStatus. */ public void bindRemoteView(NetworkRemoteView remoteView) { this.remoteView = remoteView; this.connectionState = ConnectionStates.INGAME; } /** * It handles the first step in client configuration. It ensures that a valid nickname is chosen * and if required, it allows player reconnection. * @param messageFromClient message containing nickname chosen by client. */ public void nicknameChoice(UsernameChoiceMessage messageFromClient) { String nickname; nickname = messageFromClient.getNickname(); if (server.isPlayerWithSameNicknamePlaying(nickname)) { send(new NotAvailableNicknameMessage()); LOGGER.log(Level.INFO, "Player has chosen an unavailable nickname, connection refused "); } else { this.nickname = nickname; if (server.inactivePlayerAlreadyRegistered(nickname)) { LOGGER.log(Level.INFO, "User " + nickname + " wants to resume game"); server.resumeGame(this); } else { server.addWaitingPlayer(this); server.registerClientStatus(nickname,this); send(new ServerAskForGameMode(this.nickname)); } } } /** * It handles game mode choice. * In case of multiplayer mode, it will ask the client for number of players required. * @param message message containing game mode. */ public void gameChoice(GameModeChoiceMessage message) { String choice = message.getGameModeChoice(); if(choice.equalsIgnoreCase("multiplayer")) { mode = GameMode.MULTIPLAYER; send(new ServerAskForNumOfPlayer()); } else { if(choice.equalsIgnoreCase("solo")){ mode = GameMode.SOLO; server.initializeGame(this); } } } /** * This method handles number of players selection end, at the end, adds itself to server lobby. * @param message message containing number of players selected if a multiplayer mode has been chosen. */ public void numOfPlayersChoice(NumOfPlayerChoiceMessage message) { numOfPlayers = message.getNumOfPlayers(); server.notifyLobbyJoin(numOfPlayers,nickname); LOGGER.log(Level.INFO, "Client " + nickname + " connected and " + numOfPlayers + " players chosen"); server.lobby(this); } /** * It closes communication with remote view and client, after that a disconnection has been detected. */ public void closeConnection() { try { remoteView = null; isActive = false; outputStreamToClient.close(); inputFromClient.close(); socket.close(); } catch (IOException e) { LOGGER.log(Level.INFO, "Unable to close connection"); } } /** * This method is triggered from {@link NetworkRemoteView} and it is called in order to clear a match that has been paused * for a certain time after all players disconnection. * @param usersInAPausedMatch list of users that the server has to delete. */ public void deleteMatch(List<User> usersInAPausedMatch) { server.deleteMatch(usersInAPausedMatch); } public boolean isActive() { return isActive; } public NetworkRemoteView getRemoteView() { return remoteView; } public String getNickname() { return nickname; } public int getNumOfPlayers() { return numOfPlayers; } }
package util; /** * * @author juanluis */ public class Subscription_check { public enum Result { OKAY, NO_TOPIC, NO_SUBSCRIPTION }; public Topic topic; public Result result; public Subscription_check(Topic topic, Result result) { this.topic = topic; this.result = result; } public Subscription_check(){} }
/******************************************************************************* * 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.ofbiz.accounting.agreement; import java.math.BigDecimal; import java.util.List; import java.util.Locale; import java.util.Map; import javolution.util.FastList; import org.ofbiz.base.util.Debug; import org.ofbiz.base.util.UtilMisc; import org.ofbiz.base.util.UtilNumber; import org.ofbiz.base.util.UtilProperties; import org.ofbiz.entity.Delegator; import org.ofbiz.entity.GenericEntity; import org.ofbiz.entity.GenericEntityException; import org.ofbiz.entity.GenericValue; import org.ofbiz.entity.util.EntityUtil; import org.ofbiz.service.DispatchContext; import org.ofbiz.service.ModelService; import org.ofbiz.service.ServiceUtil; /** * Services for Agreement (Accounting) */ public class AgreementServices { public static final String module = AgreementServices.class.getName(); // set some BigDecimal properties private static BigDecimal ZERO = BigDecimal.ZERO; private static int decimals = -1; private static int rounding = -1; static { decimals = UtilNumber.getBigDecimalScale("invoice.decimals"); rounding = UtilNumber.getBigDecimalRoundingMode("invoice.rounding"); // set zero to the proper scale if (decimals != -1) ZERO = ZERO.setScale(decimals, rounding); } public static final String resource = "AccountingUiLabels"; /** * Determines commission receiving parties and amounts for the provided product, price, and quantity * @param ctx The DispatchContext that this service is operating in. * @param context Map containing the input parameters. * productId String Product Id * invoiceItemTypeId String Invoice Type * amount BigDecimal Entire amount * quantity BigDecimal Quantity * @return Map with the result of the service, the output parameters. * commissions List List of Maps each containing * partyIdFrom String commission paying party * partyIdTo String commission receiving party * commission BigDecimal Commission * days Long term days * currencyUomId String Currency * productId String Product Id */ public static Map<String, Object> getCommissionForProduct(DispatchContext ctx, Map<String, Object> context) { Delegator delegator = ctx.getDelegator(); Locale locale = (Locale) context.get("locale"); String errMsg = null; List<Map<String, Object>> commissions = FastList.newInstance(); try { BigDecimal amount = ((BigDecimal)context.get("amount")); BigDecimal quantity = (BigDecimal)context.get("quantity"); quantity = quantity == null ? BigDecimal.ONE : quantity; boolean negative = amount.signum() < 0; // Ensure that price and quantity are positive since the terms may not be linear. amount = amount.abs(); quantity = quantity.abs(); String productId = (String) context.get("productId"); String invoiceItemTypeId = (String) context.get("invoiceItemTypeId"); String invoiceItemSeqId = (String) context.get("invoiceItemSeqId"); String invoiceId = (String) context.get("invoiceId"); // Collect agreementItems applicable to this orderItem/returnItem // TODO: partyIds should be part of this query! List<GenericValue> agreementItems = delegator.findByAnd("AgreementItemAndProductAppl", UtilMisc.toMap( "productId", productId, "agreementItemTypeId", "AGREEMENT_COMMISSION"), null, true); // Try the first available virtual product if this is a variant product if (agreementItems.size() == 0) { List<GenericValue> productAssocs = delegator.findByAnd("ProductAssoc", UtilMisc.toMap( "productIdTo", productId, "productAssocTypeId", "PRODUCT_VARIANT"), null, true); productAssocs = EntityUtil.filterByDate(productAssocs); if (productAssocs.size() > 0) { GenericEntity productAssoc = EntityUtil.getFirst(productAssocs); agreementItems = delegator.findByAnd("AgreementItemAndProductAppl", UtilMisc.toMap( "productId", productAssoc.getString("productId"), "agreementItemTypeId", "AGREEMENT_COMMISSION"), null, true); } } // this is not very efficient if there were many agreementItems = EntityUtil.filterByDate(agreementItems); for (GenericValue agreementItem : agreementItems) { List<GenericValue> terms = delegator.findByAnd("AgreementTerm", UtilMisc.toMap( "agreementId", agreementItem.getString("agreementId"), "agreementItemSeqId", agreementItem.getString("agreementItemSeqId"), "invoiceItemTypeId", invoiceItemTypeId), null, true); if (terms.size() > 0) { BigDecimal commission = ZERO; BigDecimal min = new BigDecimal("-1e12"); // Limit to 1 trillion commission BigDecimal max = new BigDecimal("1e12"); // number of days due for commission, which will be the lowest termDays of all the AgreementTerms long days = -1; for (GenericValue term : terms) { String termTypeId = term.getString("termTypeId"); BigDecimal termValue = term.getBigDecimal("termValue"); if (termValue != null) { if (termTypeId.equals("FIN_COMM_FIXED")) { commission = commission.add(termValue); } else if (termTypeId.equals("FIN_COMM_VARIABLE")) { // if variable percentage commission, need to divide by 100, because 5% is stored as termValue of 5.0 commission = commission.add(termValue.multiply(amount).divide(new BigDecimal("100"), 12, rounding)); } else if (termTypeId.equals("FIN_COMM_MIN")) { min = termValue; } else if (termTypeId.equals("FIN_COMM_MAX")) { max = termValue; } // TODO: Add other type of terms and handling here } // see if we need to update the number of days for paying commission Long termDays = term.getLong("termDays"); if (termDays != null) { // if days is greater than zero, then it has been set with another value, so we use the lowest term days // if days is less than zero, then it has not been set yet. if (days > 0) { days = Math.min(days, termDays.longValue()); } else { days = termDays.longValue(); } } } if (commission.compareTo(min) < 0) commission = min; if (commission.compareTo(max) > 0) commission = max; commission = negative ? commission.negate() : commission; commission = commission.setScale(decimals, rounding); Map<String, Object> partyCommissionResult = UtilMisc.toMap( "partyIdFrom", agreementItem.getString("partyIdFrom"), "partyIdTo", agreementItem.getString("partyIdTo"), "invoiceItemSeqId", invoiceItemSeqId, "invoiceId", invoiceId, "commission", commission, "quantity", quantity, "currencyUomId", agreementItem.getString("currencyUomId"), "productId", productId); if (days >= 0) { partyCommissionResult.put("days", Long.valueOf(days)); } if (!commissions.contains(partyCommissionResult)) { commissions.add(partyCommissionResult); } } } } catch (GenericEntityException e) { Debug.logWarning(e, module); Map<String, String> messageMap = UtilMisc.toMap("errMessage", e.getMessage()); errMsg = UtilProperties.getMessage("CommonUiLabels", "CommonDatabaseProblem", messageMap, locale); return ServiceUtil.returnError(errMsg); } return UtilMisc.toMap( "commissions", commissions, ModelService.RESPONSE_MESSAGE, ModelService.RESPOND_SUCCESS); } }
package mil.nga.giat.mage.sdk.http.converter; import android.content.Context; import com.squareup.okhttp.ResponseBody; import java.io.IOException; import mil.nga.giat.mage.sdk.datastore.user.User; import mil.nga.giat.mage.sdk.jackson.deserializer.UserDeserializer; import retrofit.Converter; /** * Retrofit location response body converter * * Handles Jackson deserialization for locations * * @author newmanw * */ public class UserResponseBodyConverter implements Converter<ResponseBody, User> { private Context context; public UserResponseBodyConverter(Context context) { this.context = context; } @Override public User convert(ResponseBody body) throws IOException { UserDeserializer deserializer = new UserDeserializer(context); return deserializer.parseUser(body.byteStream()); } }
package com.adevinta.android.barista.sample; import androidx.test.rule.ActivityTestRule; import androidx.test.runner.AndroidJUnit4; import com.adevinta.android.barista.sample.util.FailureHandlerValidatorRule; import org.junit.Rule; import org.junit.Test; import org.junit.runner.RunWith; import static com.adevinta.android.barista.assertion.BaristaVisibilityAssertions.assertDisplayed; import static com.adevinta.android.barista.interaction.BaristaClickInteractions.clickOn; @RunWith(AndroidJUnit4.class) public class ClickInsideViewPagerTest { @Rule public ActivityTestRule<ViewPagerWithFiveSamePagesActivity> activityRule = new ActivityTestRule<>(ViewPagerWithFiveSamePagesActivity.class); @Rule public FailureHandlerValidatorRule handlerValidator = new FailureHandlerValidatorRule(); @Test public void clickWorksAlsoWhenButtonIsRepeatedInMultipleViewPagerViews_byId() { clickOn(R.id.button); assertDisplayed(R.string.click); } @Test public void clickWorksAlsoWhenButtonIsRepeatedInMultipleViewPagerViews_byText() { clickOn("Centered button"); assertDisplayed(R.string.click); } @Test public void clickWorksAlsoWhenButtonIsRepeatedInMultipleViewPagerViews_belowScroll_byText() { clickOn("Really far away button"); assertDisplayed(R.string.click_far_away); } }
package numbers; import junit.framework.TestCase; import org.apache.kafka.clients.consumer.ConsumerRecord; import org.apache.kafka.clients.producer.ProducerRecord; import org.apache.kafka.common.serialization.StringDeserializer; import org.apache.kafka.common.serialization.StringSerializer; import org.apache.kafka.streams.KeyValue; import org.apache.kafka.streams.StreamsBuilder; import org.apache.kafka.streams.TopologyTestDriver; import org.apache.kafka.streams.kstream.KStream; import org.apache.kafka.streams.state.KeyValueIterator; import org.apache.kafka.streams.test.ConsumerRecordFactory; import java.util.List; public class ComputeTest extends TestCase { private static ConsumerRecordFactory<String, Object> recordFactory = new ConsumerRecordFactory<>("radio-logs", new StringSerializer(), new JsonSerializer<>()); private static ConsumerRecord<byte[], byte[]> createRecord(Message message) { return recordFactory.create("radio-logs", message.getName(), message); } private static Message readOutput(TopologyTestDriver driver) { ProducerRecord<String, Message> output = driver.readOutput("output", new StringDeserializer(), new JsonDeserializer<>(Message.class)); if (output != null) { return output.value(); } else { return null; } } List<Message> testMessages = List.of( new Message(1557125670789L, "GER", "085", -92, -30, List.of("eins", "null", "sechs")), new Message(1557125670790L, "UXX", "XRAY"), new Message(1557125670794L, "MOR", "425", 77, 25, List.of(".....", "----.")), new Message(1557125670795L, "UXX", "XRAY"), new Message(1557125670799L, "ENG", "NZ1", 166, -78, List.of("two")), new Message(1557125670807L, "ENG", "159", -55, -18, List.of("three", "five")), new Message(1557125670812L, "ENG", "426", 78, 26, List.of("six", "three")), new Message(1557125670814L, "GER", "085", -92, -30, List.of("drei", "neun")), new Message(1557125670819L, "MOR", "425", 77, 25, List.of(".----")), new Message(1557125670824L, "ENG", "NZ1", 166, -78, List.of("two")), new Message(1557125670827L, "ENG", "324", 27, 9, List.of("two", "nine")), new Message(1557125670829L, "GER", "460", 95, 31, List.of("fünf", "sieben")), new Message(1557125670831L, "GER", "355", 42, 14, List.of("sieben")), new Message(1557125670832L, "ENG", "159", -55, -18, List.of("three", "five")), new Message(1557125670837L, "ENG", "426", 78, 26, List.of("one")), new Message(1557125670839L, "GER", "085", -92, -30, List.of("fünf", "fünf")), new Message(1557125670840L, "GER", "505", 117, 39, List.of("eins", "null", "vier")), new Message(1557125670841L, "GER", "487", 108, 36, List.of("eins", "null", "neun")), new Message(1557125670842L, "MOR", "020", -125, -41, List.of("...--")), new Message(1557125670843L, "GER", "199", -35, -11, List.of("eins", "vier")) ); public void sendMessage(TopologyTestDriver driver, Message message) { driver.pipeInput(createRecord(message)); } public void sendMessages(TopologyTestDriver driver, List<Message> messages) { for (Message m : messages) { sendMessage(driver, m); } } // Confirm the timestamp extracted for a consumer record matches the time provided by the message public void testStreamTimestampExtraction() { StreamsBuilder builder = new StreamsBuilder(); KStream<String, Message> stream = Compute.createStream(builder); stream.to("output"); try (TopologyTestDriver driver = new TopologyTestDriver(builder.build(), Compute.config)) { sendMessage(driver, new Message(1557125670789L, "GER", "085", -92, -30, List.of("eins", "null", "sechs"))); ProducerRecord<String, Message> output = driver.readOutput("output", new StringDeserializer(), new JsonDeserializer<>(Message.class)); assertEquals((Long) 1557125670789L, output.timestamp()); } } // Demonstrate the ability to filter out messages that return false to Translator.knows(...) public void testFilterKnown() { StreamsBuilder builder = new StreamsBuilder(); KStream<String, Message> stream = Compute.createStream(builder); KStream<String, Message> filtered = Compute.filterKnown(stream); filtered.to("output"); try (TopologyTestDriver driver = new TopologyTestDriver(builder.build(), Compute.config)) { sendMessages(driver, testMessages); List<Message> expected = List.of( new Message(1557125670789L, "GER", "085", -92, -30, List.of("eins", "null", "sechs")), new Message(1557125670794L, "MOR", "425", 77, 25, List.of(".....", "----.")), new Message(1557125670799L, "ENG", "NZ1", 166, -78, List.of("two")), new Message(1557125670807L, "ENG", "159", -55, -18, List.of("three", "five")), new Message(1557125670812L, "ENG", "426", 78, 26, List.of("six", "three")) ); for (Message m : expected) { assertEquals(m, readOutput(driver)); } } } // Split the stream in two, testing the new rest-of-world stream first public void testBranchRestOfWorld() { StreamsBuilder builder = new StreamsBuilder(); KStream<String, Message> stream = Compute.createStream(builder); KStream<String, Message> filtered = Compute.filterKnown(stream); KStream[] branched = Compute.branchSpecial(filtered); branched[0].to("output"); try (TopologyTestDriver driver = new TopologyTestDriver(builder.build(), Compute.config)) { sendMessages(driver, testMessages); List<Message> expected = List.of( new Message(1557125670789L, "GER", "085", -92, -30, List.of("eins", "null", "sechs")), new Message(1557125670794L, "MOR", "425", 77, 25, List.of(".....", "----.")), new Message(1557125670807L, "ENG", "159", -55, -18, List.of("three", "five")), new Message(1557125670812L, "ENG", "426", 78, 26, List.of("six", "three")) ); for (Message m : expected) { assertEquals(m, readOutput(driver)); } } } // Split the stream in two, testing the new scott base stream second public void testBranchScottBase() { StreamsBuilder builder = new StreamsBuilder(); KStream<String, Message> stream = Compute.createStream(builder); KStream<String, Message> filtered = Compute.filterKnown(stream); KStream[] branched = Compute.branchSpecial(filtered); branched[1].to("output"); try (TopologyTestDriver driver = new TopologyTestDriver(builder.build(), Compute.config)) { sendMessages(driver, testMessages); List<Message> expected = List.of( new Message(1557125670799L, "ENG", "NZ1", 166, -78, List.of("two")) ); for (Message m : expected) { assertEquals(m, readOutput(driver)); } } } // Demonstrate the ability to mutate the stream, translating words into numeric strings public void testTranslate() { StreamsBuilder builder = new StreamsBuilder(); KStream<String, Message> stream = Compute.createStream(builder); stream = Compute.translate(Compute.filterKnown(stream)); stream.to("output"); try (TopologyTestDriver driver = new TopologyTestDriver(builder.build(), Compute.config)) { sendMessages(driver, testMessages); List<Message> expected = List.of( new Message(1557125670789L, "GER", "085", -92, -30, List.of("106")), new Message(1557125670794L, "MOR", "425", 77, 25, List.of("59")), new Message(1557125670799L, "ENG", "NZ1", 166, -78, List.of("2")), new Message(1557125670807L, "ENG", "159", -55, -18, List.of("35")), new Message(1557125670812L, "ENG", "426", 78, 26, List.of("63")) ); for (Message m : expected) { assertEquals(m, readOutput(driver)); } } } // Prove the result of grouping, windowing, and aggregating the stream into a k-table ("PT10S-Store") public void testCorrelate() { StreamsBuilder builder = new StreamsBuilder(); KStream<String, Message> stream = Compute.createStream(builder); Compute.correlate(Compute.translate(Compute.filterKnown(stream))); try (TopologyTestDriver driver = new TopologyTestDriver(builder.build(), Compute.config)) { sendMessages(driver, testMessages); try (KeyValueIterator iterator = driver.getWindowStore("PT10S-Store").fetch("085", (1557125670789L - 25000L), (1557125670789L + 100000L))) { Message expected = new Message(1557125670789L, "GER", "085", -92, -30, List.of("106", "39", "55")); Message actual = (Message) ((KeyValue) iterator.next()).value; assert (!iterator.hasNext()); assertEquals(expected, actual); } // Fetch from empty windows try (KeyValueIterator iterator2 = driver.getWindowStore("PT10S-Store").fetch("Unknown-Key", 0L, 10000L)) { assert (!iterator2.hasNext()); } } } }
package simulation; import java.awt.Point; import java.util.ArrayList; import java.util.List; import java.util.Set; import model.Cell; import model.Matrix; import model.Particle; public class CellIndexMethod { public static void calculateDistance(int sideLength, int M, double rc, List<Particle> particles, boolean edgeCondition) { double maxRadius = 0; for (Particle particle : particles) { maxRadius = particle.getRadius() > maxRadius ? particle.getRadius() : maxRadius; } double aux = (sideLength * 1.0) / (M * 1.0); if (aux <= rc + 2 * maxRadius) { throw new IllegalArgumentException("Invalid M"); } Matrix m = new Matrix(sideLength, M, particles); for (Particle particle : particles) { int row = (int) Math.floor(particle.getPosition().getX() * M / sideLength); int col = (int) Math.floor(particle.getPosition().getY() * M / sideLength); List<Point> indexes = CellIndexMethod.calculateCellNeighbors(row, col, M, edgeCondition); for (Point index : indexes) { Cell cell = m.getCell(index.x, index.y); if (cell == null && edgeCondition && (index.x == M || index.y == -1 || index.y == M)) { index.x = index.x == M ? 0 : index.x; index.y = index.y == M ? 0 : (index.y == -1 ? M - 1 : index.y); cell = m.getCell(index.x, index.y); } if (cell != null) { Set<Particle> cellParticles = cell.getParticles(); for (Particle cellParticle : cellParticles) { double xDistance = Math.abs(cellParticle.getPosition().getX() - particle.getPosition().getX()); xDistance = edgeCondition && xDistance > 2 * sideLength / M ? xDistance - sideLength : xDistance; double yDistance = cellParticle.getPosition().getY() - particle.getPosition().getY(); yDistance = edgeCondition && Math.abs(yDistance) > 2 * sideLength / M ? (yDistance > 0 ? Math.abs(yDistance - sideLength) : Math.abs(yDistance + sideLength)) : Math.abs(yDistance); double distance = Math.sqrt(Math.pow(xDistance, 2) + Math.pow(yDistance, 2)) - cellParticle.getRadius() - particle.getRadius(); if (cellParticle.getId() != particle.getId() && distance < rc) { particle.getNeighbors().add(cellParticle); if (row != index.x || col != index.y) { cellParticle.getNeighbors().add(particle); } } } } } } } private static List<Point> calculateCellNeighbors(int row, int col, int M, boolean edgeCondition) { List<Point> indexes = new ArrayList<Point>(); // cell indexes.add(new Point(row, col)); // upper indexes.add(new Point(row - 1, col)); // upper right indexes.add(new Point(row - 1, col + 1)); // right indexes.add(new Point(row, col + 1)); // lower right indexes.add(new Point(row + 1, col + 1)); return indexes; } }
package com.tyty.mybatis.generator.plugin; import org.mybatis.generator.api.GeneratedXmlFile; import org.mybatis.generator.api.IntrospectedTable; import org.mybatis.generator.api.PluginAdapter; import java.lang.reflect.Field; import java.util.List; /** * */ public class OverIsMergeablePlugin extends PluginAdapter { @Override public boolean validate(List<String> warnings) { return true; } @Override public boolean sqlMapGenerated(GeneratedXmlFile sqlMap, IntrospectedTable introspectedTable) { try { Field field = sqlMap.getClass().getDeclaredField("isMergeable"); boolean oldVal = field.isAccessible(); field.setAccessible(true); field.setBoolean(sqlMap, false); field.setAccessible(oldVal); } catch (Exception e) { e.printStackTrace(); } return true; } }
package com.tvd12.ezydata.mongodb.query; import java.util.function.Function; import org.bson.BsonValue; import com.tvd12.ezydata.database.query.EzyQLQuery; import com.tvd12.ezydata.mongodb.converter.EzyMongoDataConverter; public class EzyMongoQuery extends EzyQLQuery { public EzyMongoQuery(Builder builder) { super(builder); } @Override protected Function<Object, Object> getParameterConveter( EzyQLQuery.Builder builder) { Function<Object, Object> firstConverter = super.getParameterConveter(builder); EzyMongoDataConverter secondConverter = ((Builder)builder).dataConverter; return it -> secondConverter.bsonValueToString((BsonValue) firstConverter.apply(it)); } public static Builder builder() { return new Builder(); } public static class Builder extends EzyQLQuery.Builder { protected EzyMongoDataConverter dataConverter; public Builder dataConverter(EzyMongoDataConverter dataConverter) { this.dataConverter = dataConverter; return this; } @Override public EzyQLQuery build() { return new EzyMongoQuery(this); } } }
/* * Copyright 2002-2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.izforge.izpack.util.file.types.selectors; import java.io.File; import java.util.Enumeration; import com.izforge.izpack.api.data.InstallData; /** * This selector has a collection of other selectors, all of which have to * select a file in order for this selector to select it. */ public class AndSelector extends BaseSelectorContainer { /** * Default constructor. */ public AndSelector() { } /** * @return a string representation of the selector */ public String toString() { StringBuffer buf = new StringBuffer(); if (hasSelectors()) { buf.append("{andselect: "); buf.append(super.toString()); buf.append("}"); } return buf.toString(); } /** * Returns true (the file is selected) only if all other selectors * agree that the file should be selected. * * @param basedir the base directory the scan is being done from * @param filename the name of the file to check * @param file a java.io.File object for the filename that the selector * can use * @return whether the file should be selected or not */ public boolean isSelected(InstallData idata, File basedir, String filename, File file) throws Exception { validate(); Enumeration<FileSelector> e = selectorElements(); boolean result; while (e.hasMoreElements()) { result = e.nextElement().isSelected(idata, basedir, filename, file); if (!result) { return false; } } return true; } }
/* * Copyright 1999-2021 Alibaba Group Holding Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.alibaba.chaosblade.box.common.enums; /** * @author yefei */ public enum ExperimentDimension { HOST(DeviceType.HOST), NODE(DeviceType.NODE), POD(DeviceType.POD), CONTAINER(DeviceType.POD), APPLICATION; private DeviceType deviceType; ExperimentDimension() { } ExperimentDimension(DeviceType deviceType) { this.deviceType = deviceType; } public DeviceType getDeviceType() { return deviceType; } }
package eu.lucaventuri.fibry.distributed; import eu.lucaventuri.common.Exceptions; import java.io.IOException; import java.net.URI; import java.net.URLEncoder; import java.net.http.HttpClient; import java.net.http.HttpRequest; import java.net.http.HttpResponse; import java.nio.charset.StandardCharsets; import java.util.Base64; import java.util.concurrent.CompletableFuture; import java.util.concurrent.CompletionException; import java.util.concurrent.Executor; import java.util.function.Consumer; import java.util.function.Supplier; public class HttpChannel<T, R> implements RemoteActorChannel<T, R> { private final String url; private final Executor executor; private final boolean encodeBase64; private final HttpMethod method; private final Consumer<HttpRequest> requestCustomizer; private final HttpClient client = HttpClient.newBuilder().build(); public enum HttpMethod { GET(true) { @Override HttpRequest getRequest(String url, String remoteActorNameEncoded, String objectTypeEncoded, String messageEncoded, boolean waitResult) { return HttpRequest.newBuilder().GET().uri(URI.create(url + "?actorName=" + remoteActorNameEncoded + "&type=" + objectTypeEncoded + "&waitResult=" + waitResult + "&message=" + messageEncoded)).build(); } }, PUT(false) { @Override HttpRequest getRequest(String url, String remoteActorNameEncoded, String objectTypeEncoded, String message, boolean waitResult) { return HttpRequest.newBuilder().PUT(HttpRequest.BodyPublishers.ofString(message)).uri(URI.create(url + "?actorName=" + remoteActorNameEncoded + "&type=" + objectTypeEncoded + "&waitResult=" + waitResult)).build(); } }, POST(false) { @Override HttpRequest getRequest(String url, String remoteActorNameEncoded, String objectTypeEncoded, String message, boolean waitResult) { return HttpRequest.newBuilder().POST(HttpRequest.BodyPublishers.ofString(message)).uri(URI.create(url + "?actorName=" + remoteActorNameEncoded + "&type=" + objectTypeEncoded + "&waitResult=" + waitResult)).build(); } }; private final boolean encodeMessage; HttpMethod(boolean encodeMessage) { this.encodeMessage = encodeMessage; } private static HttpRequest.BodyPublisher dataAsPublisher(String remoteActorNameEncoded, String objectTypeEncoded, String messageEncoded) { var builder = new StringBuilder(); builder.append("actorName="); builder.append(remoteActorNameEncoded); builder.append("&type="); builder.append(objectTypeEncoded); builder.append("&message="); builder.append(messageEncoded); return HttpRequest.BodyPublishers.ofString(builder.toString()); } abstract HttpRequest getRequest(String url, String actorName, String objectType, String messageEncoded, boolean waitResult); } public HttpChannel(String url, HttpMethod method, Executor executor, Consumer<HttpRequest> requestCustomizer, boolean encodeBase64) { this.url = url; this.method = method; this.executor = executor; this.encodeBase64 = encodeBase64; this.requestCustomizer = requestCustomizer; } @Override public CompletableFuture<R> sendMessageReturn(String remoteActorName, ChannelSerializer<T> ser, ChannelDeserializer<R> deser, T message) { Supplier<R> supplier = () -> { try { final String messageToSend = prepareMessageToSend(ser, message); var request = method.getRequest(url, encodeValue(remoteActorName), encodeValue(message.getClass().getName()), messageToSend, true); return sendRequest(deser, request); } catch (Throwable t) { throw new CompletionException(t); } }; if (executor != null) return CompletableFuture.supplyAsync(supplier, executor); else return CompletableFuture.supplyAsync(supplier); } @Override public void sendMessage(String remoteActorName, ChannelSerializer<T> ser, T message) throws IOException { try { final String messageToSend = prepareMessageToSend(ser, message); var request = method.getRequest(url, encodeValue(remoteActorName), encodeValue(message.getClass().getName()), messageToSend, false); sendRequest(null, request); } catch (InterruptedException e) { throw new IOException(e); } } private R sendRequest(ChannelDeserializer<R> deser, HttpRequest request) throws java.io.IOException, InterruptedException { if (requestCustomizer != null) requestCustomizer.accept(request); var response = client.send(request, HttpResponse.BodyHandlers.ofString()); if (deser == null) return null; if (encodeBase64) return deser.deserialize(Base64.getDecoder().decode(response.body())); else return deser.deserializeString(response.body()); } private String prepareMessageToSend(ChannelSerializer<T> ser, T message) { final String messageToSend; if (method.encodeMessage) messageToSend = encodeBase64 ? Base64.getEncoder().encodeToString(ser.serialize(message)) : encodeValue(ser.serializeToString(message)); else messageToSend = ser.serializeToString(message); return messageToSend; } private static String encodeValue(String value) { return Exceptions.silence(() -> URLEncoder.encode(value, StandardCharsets.UTF_8.toString()), ""); } }
package com.genersoft.iot.vmp.service.impl; import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.JSONObject; import com.alibaba.fastjson.TypeReference; import com.genersoft.iot.vmp.gb28181.bean.GbStream; import com.genersoft.iot.vmp.media.zlm.ZLMRESTfulUtils; import com.genersoft.iot.vmp.media.zlm.dto.MediaItem; import com.genersoft.iot.vmp.media.zlm.dto.MediaServerItem; import com.genersoft.iot.vmp.media.zlm.dto.StreamPushItem; import com.genersoft.iot.vmp.service.IMediaServerService; import com.genersoft.iot.vmp.service.IStreamPushService; import com.genersoft.iot.vmp.storager.IRedisCatchStorage; import com.genersoft.iot.vmp.storager.dao.GbStreamMapper; import com.genersoft.iot.vmp.storager.dao.PlatformGbStreamMapper; import com.genersoft.iot.vmp.storager.dao.StreamPushMapper; import com.github.pagehelper.PageHelper; import com.github.pagehelper.PageInfo; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; @Service public class StreamPushServiceImpl implements IStreamPushService { @Autowired private GbStreamMapper gbStreamMapper; @Autowired private StreamPushMapper streamPushMapper; @Autowired private PlatformGbStreamMapper platformGbStreamMapper; @Autowired private ZLMRESTfulUtils zlmresTfulUtils; @Autowired private IRedisCatchStorage redisCatchStorage; @Autowired private IMediaServerService mediaServerService; @Override public List<StreamPushItem> handleJSON(String jsonData, MediaServerItem mediaServerItem) { if (jsonData == null) return null; Map<String, StreamPushItem> result = new HashMap<>(); List<MediaItem> mediaItems = JSON.parseObject(jsonData, new TypeReference<List<MediaItem>>() {}); for (MediaItem item : mediaItems) { // 不保存国标推理以及拉流代理的流 if (item.getOriginType() == 1 || item.getOriginType() == 2 || item.getOriginType() == 8) { String key = item.getApp() + "_" + item.getStream(); StreamPushItem streamPushItem = result.get(key); if (streamPushItem == null) { streamPushItem = transform(item); result.put(key, streamPushItem); } } } return new ArrayList<>(result.values()); } @Override public StreamPushItem transform(MediaItem item) { StreamPushItem streamPushItem = new StreamPushItem(); streamPushItem.setApp(item.getApp()); streamPushItem.setMediaServerId(item.getMediaServerId()); streamPushItem.setStream(item.getStream()); streamPushItem.setAliveSecond(item.getAliveSecond()); streamPushItem.setCreateStamp(item.getCreateStamp()); streamPushItem.setOriginSock(item.getOriginSock()); streamPushItem.setTotalReaderCount(item.getTotalReaderCount()); streamPushItem.setOriginType(item.getOriginType()); streamPushItem.setOriginTypeStr(item.getOriginTypeStr()); streamPushItem.setOriginUrl(item.getOriginUrl()); streamPushItem.setCreateStamp(item.getCreateStamp()); streamPushItem.setAliveSecond(item.getAliveSecond()); streamPushItem.setStatus(true); streamPushItem.setStreamType("push"); streamPushItem.setVhost(item.getVhost()); return streamPushItem; } @Override public PageInfo<StreamPushItem> getPushList(Integer page, Integer count) { PageHelper.startPage(page, count); List<StreamPushItem> all = streamPushMapper.selectAll(); return new PageInfo<>(all); } @Override public boolean saveToGB(GbStream stream) { stream.setStreamType("push"); stream.setStatus(true); int add = gbStreamMapper.add(stream); return add > 0; } @Override public boolean removeFromGB(GbStream stream) { int del = gbStreamMapper.del(stream.getApp(), stream.getStream()); MediaServerItem mediaInfo = mediaServerService.getOne(stream.getMediaServerId()); JSONObject mediaList = zlmresTfulUtils.getMediaList(mediaInfo, stream.getApp(), stream.getStream()); if (mediaList == null) { streamPushMapper.del(stream.getApp(), stream.getStream()); } return del > 0; } @Override public StreamPushItem getPush(String app, String streamId) { return streamPushMapper.selectOne(app, streamId); } @Override public boolean stop(String app, String streamId) { StreamPushItem streamPushItem = streamPushMapper.selectOne(app, streamId); int delStream = streamPushMapper.del(app, streamId); gbStreamMapper.del(app, streamId); platformGbStreamMapper.delByAppAndStream(app, streamId); if (delStream > 0) { MediaServerItem mediaServerItem = mediaServerService.getOne(streamPushItem.getMediaServerId()); zlmresTfulUtils.closeStreams(mediaServerItem,app, streamId); } return true; } }
/* * * Copyright 2015-2017 Vladimir Bukhtoyarov * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.github.bucket4j.grid.command; import io.github.bucket4j.Bandwidth; import io.github.bucket4j.BucketConfiguration; import io.github.bucket4j.BucketState; import io.github.bucket4j.grid.GridBucketState; public class AddTokensCommand implements GridCommand<Long> { private long tokensToAdd; public AddTokensCommand(long tokensToAdd) { this.tokensToAdd = tokensToAdd; } @Override public Long execute(GridBucketState gridState) { BucketConfiguration configuration = gridState.getBucketConfiguration(); BucketState state = gridState.getBucketState(); Bandwidth[] bandwidths = configuration.getBandwidths(); long currentTimeNanos = configuration.getTimeMeter().currentTimeNanos(); state.refillAllBandwidth(bandwidths, currentTimeNanos); state.addTokens(bandwidths, tokensToAdd); return null; } @Override public boolean isBucketStateModified() { return true; } }
package com.flc.util; import com.flc.service.system.menu.impl.MenuService; import com.flc.service.system.role.impl.RoleService; import com.flc.service.system.user.UserManager; /** * @author Administrator * 获取Spring容器中的service bean */ public final class ServiceHelper { public static Object getService(String serviceName){ //WebApplicationContextUtils. return Const.WEB_APP_CONTEXT.getBean(serviceName); } public static UserManager getUserService(){ return (UserManager) getService("userService"); } public static RoleService getRoleService(){ return (RoleService) getService("roleService"); } public static MenuService getMenuService(){ return (MenuService) getService("menuService"); } }
package info.androidhive.speechtotext; import java.io.IOException; import java.net.URL; import java.util.ArrayList; import java.util.Locale; import java.util.concurrent.ExecutionException; import java.util.regex.Pattern; import android.annotation.TargetApi; import android.app.Activity; import android.app.Dialog; import android.content.ActivityNotFoundException; import android.content.Context; import android.content.Intent; import android.media.audiofx.AcousticEchoCanceler; import android.os.AsyncTask; import android.os.Build; import android.os.Bundle; import android.speech.RecognizerIntent; import android.speech.tts.TextToSpeech; import android.util.Log; import android.view.Menu; import android.view.View; import android.webkit.WebView; import android.widget.ImageButton; import android.widget.TextView; import android.widget.Toast; import org.apache.http.HttpEntity; import org.apache.http.HttpResponse; import org.apache.http.client.HttpClient; import org.apache.http.client.methods.HttpGet; import org.apache.http.impl.client.DefaultHttpClient; import org.apache.http.util.EntityUtils; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; public class MainActivity extends Activity { private TextView txtSpeechInput; private ImageButton btnSpeak; private final int REQ_CODE_SPEECH_INPUT = 100; private final int REQ_CODE_ASK_NAME = 101; private final int REQ_CODE_RESP_NAME = 102; Dialog dia; private WebView imageView; TextToSpeech t1; String[] strArray={"0","1","2","3"}; String TryName=""; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); Context context = MainActivity.this; strArray[0] = getString(R.string.hello0); strArray[1] = getString(R.string.hello1); strArray[2] = getString(R.string.hello2); strArray[3] = getString(R.string.hello3); t1=new TextToSpeech(getApplicationContext(), new TextToSpeech.OnInitListener() { @Override public void onInit(int status) { if(status != TextToSpeech.ERROR) { t1.setLanguage(Locale.US); } } }); txtSpeechInput = (TextView) findViewById(R.id.txtSpeechInput); btnSpeak = (ImageButton) findViewById(R.id.btnSpeak); dia = new Dialog(context, R.style.edit_AlertDialog_style); dia.setContentView(R.layout.activity_start_dialog); imageView = (WebView) dia.findViewById(R.id.CameraImage); imageView.setScrollbarFadingEnabled(false); imageView.setWebViewClient(new myWebClient(dia));//show dia after loading the page //Disable the horizontal scroll bar imageView.setHorizontalScrollBarEnabled(false); //Enable JavaScript imageView.getSettings().setJavaScriptEnabled(true); //Set the user agent imageView.getSettings().setUserAgentString("AndroidWebView"); //Clear the cache imageView.clearCache(true); //Clear the cache // hide the action bar getActionBar().hide(); btnSpeak.setOnClickListener(new View.OnClickListener() { @TargetApi(Build.VERSION_CODES.JELLY_BEAN) @Override public void onClick(View v) { if(AcousticEchoCanceler.isAvailable()) { Log.v("voice","avaliable"); } else{ Log.v("voice","not avaliable"); } String hello = strArray[(int)(Math.random()*4)]; tts(hello); promptSpeechInput(REQ_CODE_SPEECH_INPUT); } }); } /** * Showing google speech input dialog * */ private void tts(String str){ txtSpeechInput.setText(str); t1.speak(str , TextToSpeech.QUEUE_FLUSH, null); while(t1.isSpeaking()){ ; } } private void promptSpeechInput(int ReqCode) { Intent intent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH); intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL, RecognizerIntent.LANGUAGE_MODEL_FREE_FORM); intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE, Locale.getDefault()); intent.putExtra(RecognizerIntent.EXTRA_PROMPT, getString(R.string.speech_prompt)); try { startActivityForResult(intent, ReqCode); } catch (ActivityNotFoundException a) { Toast.makeText(getApplicationContext(), getString(R.string.speech_not_supported), Toast.LENGTH_SHORT).show(); } } /** * Receiving speech input * */ @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); switch (requestCode) { case REQ_CODE_SPEECH_INPUT: { if (resultCode == RESULT_OK && null != data) { ArrayList<String> result = data .getStringArrayListExtra(RecognizerIntent.EXTRA_RESULTS); String res = result.get(0); if((Pattern.matches(".*light.*",res)||Pattern.matches(".*bulb.*",res))&& (Pattern.matches(".*on.*",res))){ Log.e("Light","turn on"); try { String resp = new GetDeviceResponse().execute("http://192.168.1.177:8000/yeelight/turn_on").get(); Log.e("resp",resp); if(resp!=null) { txtSpeechInput.setText("Your light is on"); t1.speak("Your light is on", TextToSpeech.QUEUE_FLUSH, null); } } catch (InterruptedException e) { e.printStackTrace(); } catch (ExecutionException e) { e.printStackTrace(); } } else if( (Pattern.matches(".*light.*",res)||Pattern.matches(".*bulb.*",res))&& (Pattern.matches(".*off.*",res))){ Log.e("Light","turn off" + ""); try { if(new GetDeviceResponse().execute("http://192.168.1.177:8000/yeelight/turn_off").get()!=null) { txtSpeechInput.setText("Your light is off"); t1.speak("Your light is off", TextToSpeech.QUEUE_FLUSH, null); } } catch (InterruptedException e) { e.printStackTrace(); } catch (ExecutionException e) { e.printStackTrace(); } } else if((Pattern.matches(".*robot.*",res)||Pattern.matches(".*vacuum.*",res))&& (Pattern.matches(".*on.*",res)||Pattern.matches(".*start.*",res))){ try { if(new GetDeviceResponse().execute("http://192.168.1.177:8000/xiaomi_vacuum/turn_on").get()!=null) { txtSpeechInput.setText("Your robot is on"); t1.speak("Your robot is on", TextToSpeech.QUEUE_FLUSH, null); } } catch (InterruptedException e) { e.printStackTrace(); } catch (ExecutionException e) { e.printStackTrace(); } } else if((Pattern.matches(".*robot.*",res)||Pattern.matches(".*vacuum.*",res))&& (Pattern.matches(".*off.*",res)||Pattern.matches(".*stop.*",res))){ try { if(new GetDeviceResponse().execute("http://192.168.1.177:8000/xiaomi_vacuum/turn_off").get()!=null) { txtSpeechInput.setText("Your robot is off"); t1.speak("Your robot is off", TextToSpeech.QUEUE_FLUSH, null); } } catch (InterruptedException e) { e.printStackTrace(); } catch (ExecutionException e) { e.printStackTrace(); } } else if((Pattern.matches(".*change.*",res)||Pattern.matches(".*set.*",res))&& (Pattern.matches(".*color.*",res)||Pattern.matches(".*light.*",res))){ String[] words = res.split(" "); String color = words[words.length-1]; Log.e("Light",color); new GetDeviceResponse().execute("http://192.168.1.177:8000/yeelight/color_name?color_name="+color.toLowerCase()); txtSpeechInput.setText(color+", here it is"); t1.speak(color+",here it is", TextToSpeech.QUEUE_FLUSH, null); } else if((Pattern.matches(".*photo.*",res)||Pattern.matches(".*picture.*",res))&& (Pattern.matches(".*camera.*",res)||Pattern.matches(".*nest.*",res))){ Log.v("camera","camera called"); imageView.loadUrl("http://192.168.1.177:8000/nest_camera/snap_shot_response"); txtSpeechInput.setText("Here is what I see"); t1.speak("Here is what I see", TextToSpeech.QUEUE_FLUSH, null); //dia.show(); } else if((Pattern.matches(".*detect.*",res)||Pattern.matches(".*analy.*",res))&& (Pattern.matches(".*camera.*",res)||Pattern.matches(".*nest.*",res)||Pattern.matches(".*face.*",res))){ Log.v("camera","detect called"); imageView.loadUrl("http://192.168.1.177:8000/nest_camera/snap_shot_response"); try { String faceResp = new GetDeviceResponse().execute("http://192.168.1.177:8000/nest_camera/face_detect_response").get(); if(faceResp.equals("Please try again")) txtSpeechInput.setText("Please try again"); JSONObject jsonObj = new JSONObject(faceResp); JSONObject json_data = new JSONObject(jsonObj.get("data").toString()); JSONArray faces = new JSONArray(json_data.get("faces").toString()); JSONObject face1 = new JSONObject(faces.get(0).toString()); JSONObject attributes = new JSONObject(face1.get("attributes").toString()); JSONObject ethnicity = new JSONObject(attributes.get("ethnicity").toString()); txtSpeechInput.setText("ethnicity:"+ethnicity.get("value").toString()); JSONObject age = new JSONObject(attributes.get("age").toString()); txtSpeechInput.append("\nage:"+age.get("value").toString()); JSONObject smile = new JSONObject(attributes.get("smile").toString()); txtSpeechInput.append("\nsmile:"+smile.get("value").toString()); JSONObject gender = new JSONObject(attributes.get("gender").toString()); txtSpeechInput.append("\ngender:"+gender.get("value").toString()); } catch (InterruptedException e) { e.printStackTrace(); } catch (ExecutionException e) { e.printStackTrace(); } catch (JSONException e) { txtSpeechInput.setText("No face detected"); e.printStackTrace(); } } else if((Pattern.matches(".*remember.*",res)||Pattern.matches(".*keep.*",res))||Pattern.matches(".*create.*",res) && (Pattern.matches(".*person.*",res)||Pattern.matches(".*people.*",res)||Pattern.matches(".*face.*",res))){ Log.v("camera","saving called"); String str = "what is the name"; tts(str); txtSpeechInput.setText(str); promptSpeechInput(REQ_CODE_ASK_NAME); } else if((Pattern.matches(".*recognize.*",res)||Pattern.matches(".*name.*",res))||Pattern.matches(".*who is.*",res) && (Pattern.matches(".*person.*",res)||Pattern.matches(".*who .* is.*",res)||Pattern.matches(".*face.*",res))){ String faceResp=""; try { faceResp= new GetDeviceResponse().execute("http://192.168.1.177:8000/nest_camera/face_compare_response").get(); } catch (InterruptedException e) { e.printStackTrace(); } catch (ExecutionException e) { e.printStackTrace(); } if(!faceResp.equals("\"\"")){ Log.v("camera","compare called name:"+faceResp); String str = faceResp.substring(1,faceResp.length()-1); tts(str); txtSpeechInput.setText(str); }else{ Log.v("camera","no face"); String str = "I didn't see any person"; tts(str); txtSpeechInput.setText(str); } } else if((Pattern.matches(".*tv.*",res)||Pattern.matches(".*TV.*",res))&& (Pattern.matches(".*on.*",res))){ Log.v("camera","TV called"); try { new GetDeviceResponse().execute("http://192.168.1.177:8000/harmony/turn_on").get(); } catch (InterruptedException e) { e.printStackTrace(); } catch (ExecutionException e) { e.printStackTrace(); } txtSpeechInput.setText("Your TV is on"); t1.speak("Your TV is on", TextToSpeech.QUEUE_FLUSH, null); } else if((Pattern.matches(".*tv.*",res)||Pattern.matches(".*TV.*",res))&& (Pattern.matches(".*off.*",res))){ Log.v("camera","TV called"); try { new GetDeviceResponse().execute("http://192.168.1.177:8000/harmony/turn_off").get(); } catch (InterruptedException e) { e.printStackTrace(); } catch (ExecutionException e) { e.printStackTrace(); } txtSpeechInput.setText("Your TV is off"); t1.speak("Your TV is off", TextToSpeech.QUEUE_FLUSH, null); } else txtSpeechInput.setText(res); } break; } case REQ_CODE_ASK_NAME: { if (resultCode == RESULT_OK && null != data) { ArrayList<String> result = data .getStringArrayListExtra(RecognizerIntent.EXTRA_RESULTS); TryName = result.get(0); String str =TryName+", is that correct?"; txtSpeechInput.setText(str); tts(str); promptSpeechInput(REQ_CODE_RESP_NAME); } } case REQ_CODE_RESP_NAME: { if (resultCode == RESULT_OK && null != data) { ArrayList<String> result = data .getStringArrayListExtra(RecognizerIntent.EXTRA_RESULTS); String res = result.get(0); if((Pattern.matches(".*yes.*",res)||Pattern.matches(".*correct.*",res))){ String str = TryName+"'s Face data saved"; tts(str); txtSpeechInput.setText(str); imageView.loadUrl("http://192.168.1.177:8000/nest_camera/snap_shot_response"); new GetDeviceResponse().execute("http://192.168.1.177:8000/nest_camera/snap_shot_image?name="+TryName); } if((Pattern.matches(".*no.*",res)||Pattern.matches(".*not.*",res))){ String str = "oops, lets try again, what is the name"; tts(str); txtSpeechInput.setText(str); promptSpeechInput(REQ_CODE_ASK_NAME); } } } } } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.main, menu); return true; } public class GetDeviceResponse extends AsyncTask<String, Void, String> { @Override protected String doInBackground(String... urls) { String searchUrl = urls[0]; String Response = "invalid"; try { Response=GetDeviceResponse(searchUrl); } catch (IOException e){ e.printStackTrace(); } return Response; } public String GetDeviceResponse(String urlstring) throws IOException { StringBuilder buf = new StringBuilder(urlstring); URL url = new URL(buf.toString()); HttpClient httpclient = new DefaultHttpClient(); HttpGet httpget = new HttpGet(url.toString()); HttpResponse response = httpclient.execute(httpget); HttpEntity entity = response.getEntity(); return EntityUtils.toString(entity); } @Override protected void onPostExecute(String s) { if(s!=null && !s.equals("")){ ; } super.onPostExecute(s); } } }
/* * Licensed under MIT (https://github.com/ligoj/ligoj/blob/master/LICENSE) */ package org.ligoj.app.api; /** * A configurable plug-in manage some extra configuration. */ @FunctionalInterface public interface ConfigurablePlugin { /** * Return the configuration of given subscription. * * @param subscription the subscription attached to a configurable service or tool. * @return the configuration of given subscription. * @throws Exception Configuration build failed. This error is caught at higher level. */ Object getConfiguration(int subscription) throws Exception; // NOSONAR Every thing could happen }
/* * Copyright 2016 Pascal Mainini * Licensed under MIT license, see included file LICENSE or * http://opensource.org/licenses/MIT */ package ch.mainini.famodulus.server; import java.util.logging.Logger; import javax.ws.rs.container.ContainerRequestContext; import javax.ws.rs.container.ContainerResponseContext; import javax.ws.rs.container.ContainerResponseFilter; import javax.ws.rs.core.MultivaluedMap; import javax.ws.rs.ext.Provider; /** * A filter which adds CORS-headers to all responses. * @author Pascal Mainini */ @Provider public class CORSResponseFilter implements ContainerResponseFilter { //////////////////////////////////////// Constants private static final Logger LOG = Logger.getLogger(CORSResponseFilter.class.getName()); private static final String DEFAULT_ALLOW_ORIGIN = "*"; private final String origin; //////////////////////////////////////// Constructors /** * Default constructor, retrieves the origin parameter from system properites */ public CORSResponseFilter() { this.origin = System.getProperty("famodulus.allow_origin", DEFAULT_ALLOW_ORIGIN); LOG.finest(String.format("Filter instantiated! Allowing origin: %s", origin)); } //////////////////////////////////////// Methods /** * Filter-method which adds all relevant CORS headers to outgoing responses. * @param ctx the context of the request * @param res the context of the response */ @Override public void filter(ContainerRequestContext ctx, ContainerResponseContext res) { MultivaluedMap<String, Object> headers = res.getHeaders(); headers.add("Access-Control-Allow-Origin", origin); headers.add("Access-Control-Allow-Methods", "GET, POST"); headers.add("Access-Control-Allow-Headers", "X-Requested-With, Content-Type"); } }
package it.unibo.comm2022.tcp; import java.net.Socket; import it.unibo.comm2022.interfaces.Interaction2021; import it.unibo.comm2022.utils.ColorsOut; public class TcpClientSupport { // private Socket socket; public static Interaction2021 connect(String host, int port, int nattempts ) throws Exception { // TcpClient tcpc = new TcpClient(host, port, nattempts); // return new TcpConnection( tcpc.getSocket() ); for( int i=1; i<=nattempts; i++ ) { try { Socket socket = new Socket( host, port ); Interaction2021 conn = new TcpConnection( socket ); return conn; }catch(Exception e) { ColorsOut.out("TcpClient | Another attempt to connect with host:" + host + " port=" + port); Thread.sleep(500); } }//for throw new Exception("TcpClient | Unable to connect to host:" + host); } }
package com.beeva.beenote; /** * Created by marianclaudiu on 5/06/15. */ import com.amazonaws.mobileconnectors.lambdainvoker.LambdaFunction; import com.beeva.beenote.models.MetaNoteMessage; import com.beeva.beenote.models.MetaNoteResponse; public interface NoteProxy { @LambdaFunction(functionName = "TestUbiq") MetaNoteResponse invoke(MetaNoteMessage message); }
package com.skytala.eCommerce.domain.order.relations.returnStatus.mapper; import java.math.BigDecimal; import java.sql.Timestamp; import java.util.HashMap; import java.util.Map; import javax.servlet.http.HttpServletRequest; import org.apache.ofbiz.entity.GenericValue; import com.skytala.eCommerce.domain.order.relations.returnStatus.model.ReturnStatus; public class ReturnStatusMapper { public static Map<String, Object> map(ReturnStatus returnstatus) { Map<String, Object> returnVal = new HashMap<String, Object>(); if(returnstatus.getReturnStatusId() != null ){ returnVal.put("returnStatusId",returnstatus.getReturnStatusId()); } if(returnstatus.getStatusId() != null ){ returnVal.put("statusId",returnstatus.getStatusId()); } if(returnstatus.getReturnId() != null ){ returnVal.put("returnId",returnstatus.getReturnId()); } if(returnstatus.getReturnItemSeqId() != null ){ returnVal.put("returnItemSeqId",returnstatus.getReturnItemSeqId()); } if(returnstatus.getChangeByUserLoginId() != null ){ returnVal.put("changeByUserLoginId",returnstatus.getChangeByUserLoginId()); } if(returnstatus.getStatusDatetime() != null ){ returnVal.put("statusDatetime",returnstatus.getStatusDatetime()); } return returnVal; } public static ReturnStatus map(Map<String, Object> fields) { ReturnStatus returnVal = new ReturnStatus(); if(fields.get("returnStatusId") != null) { returnVal.setReturnStatusId((String) fields.get("returnStatusId")); } if(fields.get("statusId") != null) { returnVal.setStatusId((String) fields.get("statusId")); } if(fields.get("returnId") != null) { returnVal.setReturnId((String) fields.get("returnId")); } if(fields.get("returnItemSeqId") != null) { returnVal.setReturnItemSeqId((String) fields.get("returnItemSeqId")); } if(fields.get("changeByUserLoginId") != null) { returnVal.setChangeByUserLoginId((String) fields.get("changeByUserLoginId")); } if(fields.get("statusDatetime") != null) { returnVal.setStatusDatetime((Timestamp) fields.get("statusDatetime")); } return returnVal; } public static ReturnStatus mapstrstr(Map<String, String> fields) throws Exception { ReturnStatus returnVal = new ReturnStatus(); if(fields.get("returnStatusId") != null) { returnVal.setReturnStatusId((String) fields.get("returnStatusId")); } if(fields.get("statusId") != null) { returnVal.setStatusId((String) fields.get("statusId")); } if(fields.get("returnId") != null) { returnVal.setReturnId((String) fields.get("returnId")); } if(fields.get("returnItemSeqId") != null) { returnVal.setReturnItemSeqId((String) fields.get("returnItemSeqId")); } if(fields.get("changeByUserLoginId") != null) { returnVal.setChangeByUserLoginId((String) fields.get("changeByUserLoginId")); } if(fields.get("statusDatetime") != null) { String buf = fields.get("statusDatetime"); Timestamp ibuf = Timestamp.valueOf(buf); returnVal.setStatusDatetime(ibuf); } return returnVal; } public static ReturnStatus map(GenericValue val) { ReturnStatus returnVal = new ReturnStatus(); returnVal.setReturnStatusId(val.getString("returnStatusId")); returnVal.setStatusId(val.getString("statusId")); returnVal.setReturnId(val.getString("returnId")); returnVal.setReturnItemSeqId(val.getString("returnItemSeqId")); returnVal.setChangeByUserLoginId(val.getString("changeByUserLoginId")); returnVal.setStatusDatetime(val.getTimestamp("statusDatetime")); return returnVal; } public static ReturnStatus map(HttpServletRequest request) throws Exception { ReturnStatus returnVal = new ReturnStatus(); Map<String, String[]> paramMap = request.getParameterMap(); if(paramMap.containsKey("returnStatusId")) { returnVal.setReturnStatusId(request.getParameter("returnStatusId")); } if(paramMap.containsKey("statusId")) { returnVal.setStatusId(request.getParameter("statusId")); } if(paramMap.containsKey("returnId")) { returnVal.setReturnId(request.getParameter("returnId")); } if(paramMap.containsKey("returnItemSeqId")) { returnVal.setReturnItemSeqId(request.getParameter("returnItemSeqId")); } if(paramMap.containsKey("changeByUserLoginId")) { returnVal.setChangeByUserLoginId(request.getParameter("changeByUserLoginId")); } if(paramMap.containsKey("statusDatetime")) { String buf = request.getParameter("statusDatetime"); Timestamp ibuf = Timestamp.valueOf(buf); returnVal.setStatusDatetime(ibuf); } return returnVal; } }
package usi.dbdp.uic.base.dao.impl4mysql; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.util.ArrayList; import java.util.List; import org.springframework.jdbc.core.PreparedStatementSetter; import org.springframework.jdbc.core.RowMapper; import org.springframework.stereotype.Repository; import usi.common.annotation.MysqlDb; import usi.dbdp.portal.util.JdbcDaoSupport4mysql; import usi.dbdp.uic.base.dao.AppRegisterDao; import usi.dbdp.uic.dto.AppRegisterInfo; import usi.dbdp.uic.dto.PageObj; import usi.dbdp.uic.entity.AppRegister; /** * 应用注册服务dao * @author nie.zhengqian * 创建时间:2015年3月10日 下午5:15:07 */ @MysqlDb @Repository public class AppRegisterDaoImpl extends JdbcDaoSupport4mysql implements AppRegisterDao{ /** * 应用code 个数 * @param appCode * @return 应用code 个数 */ public int judgeAppByAppCode(String appCode){ String sql = "select count(*) from uic_app where APP_CODE = ?"; return this.getJdbcTemplate().queryForObject(sql, new Object[]{appCode}, Integer.class); } /** * 增加一个应用 * @param AppRegister 应用信息对象 * @return 1表示操作成功,0表示操作失败 */ public int addApp(final AppRegister appRegister){ String sql = " INSERT INTO uic_app (" +" APP_CODE," +" APP_NAME," +" APP_IMG_PATH," +" APP_URL," +" TODO_URL," +" APP_CHECKSUM," +" STATE," +" APP_MEMO," +" REG_TIME," +" USER_GUIDE_PATH," +" APP_TYPE," +"display_order" +" )" +" VALUES" +"(?,?,?,?,?,?,?,?,now(),?,?,?)"; return this.getJdbcTemplate().update(sql, new PreparedStatementSetter(){ @Override public void setValues(PreparedStatement ps) throws SQLException { ps.setString(1, appRegister.getAppCode()); ps.setString(2, appRegister.getAppName()); ps.setString(3, appRegister.getAppImgPath()); ps.setString(4, appRegister.getAppUrl()); ps.setString(5, appRegister.getTodoUrl()); ps.setString(6, appRegister.getAppChecksum()); ps.setInt(7, appRegister.getState()); ps.setString(8, appRegister.getAppMmemo()); ps.setString(9, appRegister.getUserGuidePath()); ps.setInt(10, appRegister.getAppType()); ps.setInt(11, appRegister.getDisplayOrder()); } }); } /** * 更新某应用信息 * @param AppRegister 应用信息对象 * @return 1表示操作成功,0表示操作失败 */ public int updateApp(final AppRegister appRegister) { String sql = " UPDATE " +" uic_app " +" SET" +" APP_NAME = ?," +" APP_IMG_PATH = ?," +" APP_URL = ?," +" TODO_URL = ?," +" APP_CHECKSUM = ?," +" STATE = ?," +" APP_MEMO = ?," +" REG_TIME = now(), " +" USER_GUIDE_PATH = ?, " +" APP_TYPE = ? , " + " display_order =? " +" WHERE APP_CODE = ? "; return this.getJdbcTemplate().update(sql, new PreparedStatementSetter() { @Override public void setValues(PreparedStatement ps) throws SQLException { ps.setString(1, appRegister.getAppName()); ps.setString(2, appRegister.getAppImgPath()); ps.setString(3, appRegister.getAppUrl()); ps.setString(4, appRegister.getTodoUrl()); ps.setString(5, appRegister.getAppChecksum()); ps.setInt(6, appRegister.getState()); ps.setString(7, appRegister.getAppMmemo()); ps.setString(8, appRegister.getUserGuidePath()); ps.setInt(9, appRegister.getAppType()); ps.setInt(10, appRegister.getDisplayOrder()); ps.setString(11, appRegister.getAppCode()); } }); } /** * 根据应用appCode查应用信息 * @param appCode 应用code * @return 应用信息对象 */ public List<AppRegister> queryAppByAppCode(String appCode) { String sql = " SELECT " +" APP_CODE," +" APP_NAME," +" APP_IMG_PATH," +" APP_URL," +" TODO_URL," +" APP_CHECKSUM," +" STATE," +" APP_MEMO," +" REG_TIME, " +" USER_GUIDE_PATH ," +" app_type, " +" display_order " +" FROM" +" uic_app " +" WHERE APP_CODE = ?"; return this.getJdbcTemplate().query(sql,new Object[]{appCode}, new RowMapper<AppRegister>(){ @Override public AppRegister mapRow(ResultSet rs, int rowNum) throws SQLException { AppRegister appRegister = new AppRegister(); appRegister.setAppCode(rs.getString("APP_CODE")); appRegister.setAppName(rs.getString("APP_NAME")); appRegister.setAppImgPath(rs.getString("APP_IMG_PATH")); appRegister.setAppUrl(rs.getString("APP_URL")); appRegister.setTodoUrl(rs.getString("TODO_URL")); appRegister.setAppChecksum(rs.getString("APP_CHECKSUM")); appRegister.setState(rs.getInt("STATE")); appRegister.setAppMmemo(rs.getString("APP_MEMO")); appRegister.setRegTime(rs.getDate("REG_TIME")); appRegister.setUserGuidePath(rs.getString("USER_GUIDE_PATH")); appRegister.setAppType(rs.getInt("app_type")); appRegister.setDisplayOrder(rs.getInt("display_order")); return appRegister; } }); } /** * 删除某应用(逻辑删除,设置应用信息状态为失效) * @param appCode 应用code * @return 1表示操作成功,0表示操作失败 */ public int deleteAppByAppCode(String appCode) { String sql = "UPDATE UIC_APP SET STATE = 0 WHERE APP_CODE=? "; return this.getJdbcTemplate().update(sql, new Object[]{appCode}); } /** * 激活某应用(将应用信息状态从失效状态改为生效) * @param appCode 应用code * @return 1表示操作成功,0表示操作失败 */ public int activateAppByAppCode(String appCode) { String sql = "UPDATE UIC_APP SET STATE = 1 WHERE APP_CODE=? "; return this.getJdbcTemplate().update(sql, new Object[]{appCode}); } /** * 查询所有激活的应用 * @return List<AppRegister> */ public List<AppRegister> queryAppByState() { String sql = " SELECT " +" APP_CODE," +" APP_NAME," +" APP_IMG_PATH," +" APP_URL," +" TODO_URL," +" APP_CHECKSUM," +" STATE," +" APP_MEMO," +" REG_TIME, " +" USER_GUIDE_PATH, " +" app_type, " +" display_order " +" FROM" +" uic_app " +" WHERE STATE = 1 order by display_order "; return this.getJdbcTemplate().query(sql, new RowMapper<AppRegister>(){ @Override public AppRegister mapRow(ResultSet rs, int rowNum) throws SQLException { AppRegister appRegister = new AppRegister(); appRegister.setAppCode(rs.getString("APP_CODE")); appRegister.setAppName(rs.getString("APP_NAME")); appRegister.setAppImgPath(rs.getString("APP_IMG_PATH")); appRegister.setAppUrl(rs.getString("APP_URL")); appRegister.setTodoUrl(rs.getString("TODO_URL")); appRegister.setAppChecksum(rs.getString("APP_CHECKSUM")); appRegister.setState(rs.getInt("STATE")); appRegister.setAppMmemo(rs.getString("APP_MEMO")); appRegister.setRegTime(rs.getDate("REG_TIME")); appRegister.setUserGuidePath(rs.getString("USER_GUIDE_PATH")); appRegister.setAppType(rs.getInt("app_type")); appRegister.setDisplayOrder(rs.getInt("display_order")); return appRegister; } }); } /** * 查询所有的应用 * @return List<AppRegister> */ public List<AppRegister> queryAllAppList() { String sql = " SELECT " +" APP_CODE," +" APP_NAME," +" APP_IMG_PATH," +" APP_URL," +" TODO_URL," +" APP_CHECKSUM," +" STATE," +" APP_MEMO," +" REG_TIME, " +" USER_GUIDE_PATH ," +" app_type, " +" display_order " +" FROM" +" uic_app where app_type>0 order by display_order "; return this.getJdbcTemplate().query(sql, new RowMapper<AppRegister>(){ @Override public AppRegister mapRow(ResultSet rs, int rowNum) throws SQLException { AppRegister appRegister = new AppRegister(); appRegister.setAppCode(rs.getString("APP_CODE")); appRegister.setAppName(rs.getString("APP_NAME")); appRegister.setAppImgPath(rs.getString("APP_IMG_PATH")); appRegister.setAppUrl(rs.getString("APP_URL")); appRegister.setTodoUrl(rs.getString("TODO_URL")); appRegister.setAppChecksum(rs.getString("APP_CHECKSUM")); appRegister.setState(rs.getInt("STATE")); appRegister.setAppMmemo(rs.getString("APP_MEMO")); appRegister.setRegTime(rs.getDate("REG_TIME")); appRegister.setUserGuidePath(rs.getString("USER_GUIDE_PATH")); appRegister.setAppType(rs.getInt("app_type")); appRegister.setDisplayOrder(rs.getInt("display_order")); return appRegister; } }); } /** * @author ma.guangming * 查询应用级应用 * @return List<AppRegister> */ public List<AppRegister> getNomalAppsByState() { String sql = " select app_code,app_name,app_img_path,app_url,todo_url,app_checksum,state,app_memo,reg_time,user_guide_path ,app_type , display_order " +" from uic_app " +" where state = 1 and app_type =1 order by display_order "; return this.getJdbcTemplate().query(sql, new RowMapper<AppRegister>(){ @Override public AppRegister mapRow(ResultSet rs, int rowNum) throws SQLException { AppRegister appRegister = new AppRegister(); appRegister.setAppCode(rs.getString("app_code")); appRegister.setAppName(rs.getString("app_name")); appRegister.setAppImgPath(rs.getString("app_img_path")); appRegister.setAppUrl(rs.getString("app_url")); appRegister.setTodoUrl(rs.getString("todo_url")); appRegister.setAppChecksum(rs.getString("app_checksum")); appRegister.setState(rs.getInt("state")); appRegister.setAppMmemo(rs.getString("app_memo")); appRegister.setRegTime(rs.getDate("reg_time")); appRegister.setUserGuidePath(rs.getString("user_guide_path")); appRegister.setAppType(rs.getInt("app_type")); appRegister.setDisplayOrder(rs.getInt("display_order")); return appRegister; } }); } /** * 获取某用户拥有菜单的非系统级应用(分页) * @param id 用户id * @return 应用dto */ public List<AppRegisterInfo> getAllAppsByUserIdWithPage(PageObj pageObj , String userId){ String sql = "SELECT DISTINCT " + " ar.app_name, " + " ar.app_checksum, " + " ar.app_code, " + " ar.app_img_path, " + " ar.app_memo, " + " ar.app_type, " + " ar.app_url, " + " ar.reg_time, " + " ar.state, " + " ar.display_order, " + " ar.todo_url, " + " ar.user_guide_path " + "FROM " + " uic_user u, " + " uic_user_has_role ur, " + " uic_role r, " + " uic_role_has_menu rm, " + " uic_menu m, " + " uic_app ar " + "WHERE u.id = ur.id " + " AND ur.role_id = r.role_id " + " AND r.role_id = rm.role_id " + " AND rm.menu_id = m.menu_id " + " AND m.app_code = ar.app_code " + " AND m.del_flag = 0 " + " AND r.del_flag = 0 " + " AND ar.state = 1 " + " AND ar.app_type = 1 " + " AND u.user_id = ? " + "ORDER BY ar.display_order"; return this.queryByPage(sql, new Object[]{userId}, new RowMapper<AppRegisterInfo>(){ @Override public AppRegisterInfo mapRow(ResultSet rs, int rowNum) throws SQLException { AppRegisterInfo appRegister = new AppRegisterInfo(); appRegister.setAppCode(rs.getString("APP_CODE")); appRegister.setAppName(rs.getString("APP_NAME")); appRegister.setAppImgPath(rs.getString("APP_IMG_PATH")); appRegister.setAppUrl(rs.getString("APP_URL")); appRegister.setTodoUrl(rs.getString("TODO_URL")); appRegister.setAppChecksum(rs.getString("APP_CHECKSUM")); appRegister.setState(rs.getInt("STATE")); appRegister.setAppMmemo(rs.getString("APP_MEMO")); appRegister.setRegTime(rs.getDate("REG_TIME")); appRegister.setUserGuidePath(rs.getString("USER_GUIDE_PATH")); return appRegister; } },pageObj); } /** * 查询所有的应用 * @param id 用户id * @return List<AppRegister> */ public List<AppRegister> queryAllAppList(long id) { ArrayList<Object> list = new ArrayList<Object>(); String sql = " SELECT a.app_checksum,a.app_code,a.app_img_path,a.app_memo,a.app_name,a.app_type,a.app_url,a.display_order,a.reg_time, " +" a.todo_url,a.user_guide_path,a.state" +" FROM uic_app a "; //如果是系统管理员直接查出所有应用 if(1!=id){ list.add(id); sql+="JOIN (SELECT DISTINCT c.app_code FROM uic_user_has_role b ,uic_role c WHERE b.id=? AND b.role_id=c.role_id ) t ON a.app_code =t.app_code "; } sql+=" where 1=? and a.state=1 and a.app_type > 0 ORDER BY a.DISPLAY_ORDER" ; list.add(1); return this.getJdbcTemplate().query(sql, list.toArray(),new RowMapper<AppRegister>(){ @Override public AppRegister mapRow(ResultSet rs, int rowNum) throws SQLException { AppRegister appRegister = new AppRegister(); appRegister.setAppCode(rs.getString("APP_CODE")); appRegister.setAppName(rs.getString("APP_NAME")); appRegister.setAppImgPath(rs.getString("APP_IMG_PATH")); appRegister.setAppUrl(rs.getString("APP_URL")); appRegister.setTodoUrl(rs.getString("TODO_URL")); appRegister.setAppChecksum(rs.getString("APP_CHECKSUM")); appRegister.setState(rs.getInt("STATE")); appRegister.setAppMmemo(rs.getString("APP_MEMO")); appRegister.setRegTime(rs.getDate("REG_TIME")); appRegister.setUserGuidePath(rs.getString("USER_GUIDE_PATH")); appRegister.setAppType(rs.getInt("app_type")); appRegister.setDisplayOrder(rs.getInt("display_order")); return appRegister; } }); } @Override public List<AppRegister> getAppCodes(long province) { String sql =" SELECT DISTINCT n.app_code ,n.app_name , n.DISPLAY_ORDER FROM uic_data_pri m , uic_app_register n WHERE n.state = 1 AND " + " m.PRIVILEGE_VALUE = n.APP_CODE AND m.user_id IN (SELECT a.user_id FROM uic_user a,uic_role b,uic_user_role_rel c ,uic_org d " + " WHERE a.id = c.id AND b.role_id = c.role_id AND a.state =1 AND b.state=1 AND a.org_id = d.org_id " + " AND b.role_code = 'role_appadmin' "; if(0!=province){ sql += " AND (d.org_id_seq LIKE CONCAT((SELECT f.org_id_seq FROM uic_org f WHERE f.org_id = ?),'%') ) "; } sql += " ) ORDER BY n.DISPLAY_ORDER "; if(0!=province){ return this.getJdbcTemplate().query(sql, new Object[]{province}, new RowMapper<AppRegister>(){ @Override public AppRegister mapRow(ResultSet rs, int rowNum) throws SQLException { AppRegister app = new AppRegister(); app.setAppCode(rs.getString("app_code")); app.setAppName(rs.getString("app_name")); return app; } }); }else{ return this.getJdbcTemplate().query(sql, new RowMapper<AppRegister>(){ @Override public AppRegister mapRow(ResultSet rs, int rowNum) throws SQLException { AppRegister app = new AppRegister(); app.setAppCode(rs.getString("app_code")); app.setAppName(rs.getString("app_name")); return app; } }); } } }
package com.tw.marsrover; /** * * @author vji */ public class UninitialisedPlateauException extends RuntimeException { public UninitialisedPlateauException(String message) { super(message); } }
/* * Copyright 2021 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.cloud.dialogflow.v2beta1; import com.google.api.core.ApiFuture; import com.google.api.core.ApiFutures; import com.google.api.core.BetaApi; import com.google.api.gax.core.BackgroundResource; import com.google.api.gax.longrunning.OperationFuture; import com.google.api.gax.paging.AbstractFixedSizeCollection; import com.google.api.gax.paging.AbstractPage; import com.google.api.gax.paging.AbstractPagedListResponse; import com.google.api.gax.rpc.OperationCallable; import com.google.api.gax.rpc.PageContext; import com.google.api.gax.rpc.UnaryCallable; import com.google.cloud.dialogflow.v2beta1.stub.AgentsStub; import com.google.cloud.dialogflow.v2beta1.stub.AgentsStubSettings; import com.google.common.util.concurrent.MoreExecutors; import com.google.longrunning.Operation; import com.google.longrunning.OperationsClient; import com.google.protobuf.Empty; import com.google.protobuf.Struct; import java.io.IOException; import java.util.List; import java.util.concurrent.TimeUnit; import javax.annotation.Generated; // AUTO-GENERATED DOCUMENTATION AND CLASS. /** * Service Description: Service for managing [Agents][google.cloud.dialogflow.v2beta1.Agent]. * * <p>This class provides the ability to make remote calls to the backing service through method * calls that map to API methods. Sample code to get started: * * <pre>{@code * try (AgentsClient agentsClient = AgentsClient.create()) { * LocationName parent = LocationName.of("[PROJECT]", "[LOCATION]"); * Agent response = agentsClient.getAgent(parent); * } * }</pre> * * <p>Note: close() needs to be called on the AgentsClient object to clean up resources such as * threads. In the example above, try-with-resources is used, which automatically calls close(). * * <p>The surface of this class includes several types of Java methods for each of the API's * methods: * * <ol> * <li>A "flattened" method. With this type of method, the fields of the request type have been * converted into function parameters. It may be the case that not all fields are available as * parameters, and not every API method will have a flattened method entry point. * <li>A "request object" method. This type of method only takes one parameter, a request object, * which must be constructed before the call. Not every API method will have a request object * method. * <li>A "callable" method. This type of method takes no parameters and returns an immutable API * callable object, which can be used to initiate calls to the service. * </ol> * * <p>See the individual methods for example code. * * <p>Many parameters require resource names to be formatted in a particular way. To assist with * these names, this class includes a format method for each type of name, and additionally a parse * method to extract the individual identifiers contained within names that are returned. * * <p>This class can be customized by passing in a custom instance of AgentsSettings to create(). * For example: * * <p>To customize credentials: * * <pre>{@code * AgentsSettings agentsSettings = * AgentsSettings.newBuilder() * .setCredentialsProvider(FixedCredentialsProvider.create(myCredentials)) * .build(); * AgentsClient agentsClient = AgentsClient.create(agentsSettings); * }</pre> * * <p>To customize the endpoint: * * <pre>{@code * AgentsSettings agentsSettings = AgentsSettings.newBuilder().setEndpoint(myEndpoint).build(); * AgentsClient agentsClient = AgentsClient.create(agentsSettings); * }</pre> * * <p>Please refer to the GitHub repository's samples for more quickstart code snippets. */ @BetaApi @Generated("by gapic-generator-java") public class AgentsClient implements BackgroundResource { private final AgentsSettings settings; private final AgentsStub stub; private final OperationsClient operationsClient; /** Constructs an instance of AgentsClient with default settings. */ public static final AgentsClient create() throws IOException { return create(AgentsSettings.newBuilder().build()); } /** * Constructs an instance of AgentsClient, using the given settings. The channels are created * based on the settings passed in, or defaults for any settings that are not set. */ public static final AgentsClient create(AgentsSettings settings) throws IOException { return new AgentsClient(settings); } /** * Constructs an instance of AgentsClient, using the given stub for making calls. This is for * advanced usage - prefer using create(AgentsSettings). */ @BetaApi("A restructuring of stub classes is planned, so this may break in the future") public static final AgentsClient create(AgentsStub stub) { return new AgentsClient(stub); } /** * Constructs an instance of AgentsClient, using the given settings. This is protected so that it * is easy to make a subclass, but otherwise, the static factory methods should be preferred. */ protected AgentsClient(AgentsSettings settings) throws IOException { this.settings = settings; this.stub = ((AgentsStubSettings) settings.getStubSettings()).createStub(); this.operationsClient = OperationsClient.create(this.stub.getOperationsStub()); } @BetaApi("A restructuring of stub classes is planned, so this may break in the future") protected AgentsClient(AgentsStub stub) { this.settings = null; this.stub = stub; this.operationsClient = OperationsClient.create(this.stub.getOperationsStub()); } public final AgentsSettings getSettings() { return settings; } @BetaApi("A restructuring of stub classes is planned, so this may break in the future") public AgentsStub getStub() { return stub; } /** * Returns the OperationsClient that can be used to query the status of a long-running operation * returned by another API method call. */ public final OperationsClient getOperationsClient() { return operationsClient; } // AUTO-GENERATED DOCUMENTATION AND METHOD. /** * Retrieves the specified agent. * * <p>Sample code: * * <pre>{@code * try (AgentsClient agentsClient = AgentsClient.create()) { * LocationName parent = LocationName.of("[PROJECT]", "[LOCATION]"); * Agent response = agentsClient.getAgent(parent); * } * }</pre> * * @param parent Required. The project that the agent to fetch is associated with. Format: * `projects/&lt;Project ID&gt;` or `projects/&lt;Project ID&gt;/locations/&lt;Location * ID&gt;`. * @throws com.google.api.gax.rpc.ApiException if the remote call fails */ public final Agent getAgent(LocationName parent) { GetAgentRequest request = GetAgentRequest.newBuilder().setParent(parent == null ? null : parent.toString()).build(); return getAgent(request); } // AUTO-GENERATED DOCUMENTATION AND METHOD. /** * Retrieves the specified agent. * * <p>Sample code: * * <pre>{@code * try (AgentsClient agentsClient = AgentsClient.create()) { * ProjectName parent = ProjectName.of("[PROJECT]"); * Agent response = agentsClient.getAgent(parent); * } * }</pre> * * @param parent Required. The project that the agent to fetch is associated with. Format: * `projects/&lt;Project ID&gt;` or `projects/&lt;Project ID&gt;/locations/&lt;Location * ID&gt;`. * @throws com.google.api.gax.rpc.ApiException if the remote call fails */ public final Agent getAgent(ProjectName parent) { GetAgentRequest request = GetAgentRequest.newBuilder().setParent(parent == null ? null : parent.toString()).build(); return getAgent(request); } // AUTO-GENERATED DOCUMENTATION AND METHOD. /** * Retrieves the specified agent. * * <p>Sample code: * * <pre>{@code * try (AgentsClient agentsClient = AgentsClient.create()) { * String parent = AgentName.ofProjectName("[PROJECT]").toString(); * Agent response = agentsClient.getAgent(parent); * } * }</pre> * * @param parent Required. The project that the agent to fetch is associated with. Format: * `projects/&lt;Project ID&gt;` or `projects/&lt;Project ID&gt;/locations/&lt;Location * ID&gt;`. * @throws com.google.api.gax.rpc.ApiException if the remote call fails */ public final Agent getAgent(String parent) { GetAgentRequest request = GetAgentRequest.newBuilder().setParent(parent).build(); return getAgent(request); } // AUTO-GENERATED DOCUMENTATION AND METHOD. /** * Retrieves the specified agent. * * <p>Sample code: * * <pre>{@code * try (AgentsClient agentsClient = AgentsClient.create()) { * GetAgentRequest request = * GetAgentRequest.newBuilder() * .setParent(AgentName.ofProjectName("[PROJECT]").toString()) * .build(); * Agent response = agentsClient.getAgent(request); * } * }</pre> * * @param request The request object containing all of the parameters for the API call. * @throws com.google.api.gax.rpc.ApiException if the remote call fails */ public final Agent getAgent(GetAgentRequest request) { return getAgentCallable().call(request); } // AUTO-GENERATED DOCUMENTATION AND METHOD. /** * Retrieves the specified agent. * * <p>Sample code: * * <pre>{@code * try (AgentsClient agentsClient = AgentsClient.create()) { * GetAgentRequest request = * GetAgentRequest.newBuilder() * .setParent(AgentName.ofProjectName("[PROJECT]").toString()) * .build(); * ApiFuture<Agent> future = agentsClient.getAgentCallable().futureCall(request); * // Do something. * Agent response = future.get(); * } * }</pre> */ public final UnaryCallable<GetAgentRequest, Agent> getAgentCallable() { return stub.getAgentCallable(); } // AUTO-GENERATED DOCUMENTATION AND METHOD. /** * Creates/updates the specified agent. * * <p>Note: You should always train an agent prior to sending it queries. See the [training * documentation](https://cloud.google.com/dialogflow/es/docs/training). * * <p>Sample code: * * <pre>{@code * try (AgentsClient agentsClient = AgentsClient.create()) { * Agent agent = Agent.newBuilder().build(); * Agent response = agentsClient.setAgent(agent); * } * }</pre> * * @param agent Required. The agent to update. * @throws com.google.api.gax.rpc.ApiException if the remote call fails */ public final Agent setAgent(Agent agent) { SetAgentRequest request = SetAgentRequest.newBuilder().setAgent(agent).build(); return setAgent(request); } // AUTO-GENERATED DOCUMENTATION AND METHOD. /** * Creates/updates the specified agent. * * <p>Note: You should always train an agent prior to sending it queries. See the [training * documentation](https://cloud.google.com/dialogflow/es/docs/training). * * <p>Sample code: * * <pre>{@code * try (AgentsClient agentsClient = AgentsClient.create()) { * SetAgentRequest request = * SetAgentRequest.newBuilder() * .setAgent(Agent.newBuilder().build()) * .setUpdateMask(FieldMask.newBuilder().build()) * .build(); * Agent response = agentsClient.setAgent(request); * } * }</pre> * * @param request The request object containing all of the parameters for the API call. * @throws com.google.api.gax.rpc.ApiException if the remote call fails */ public final Agent setAgent(SetAgentRequest request) { return setAgentCallable().call(request); } // AUTO-GENERATED DOCUMENTATION AND METHOD. /** * Creates/updates the specified agent. * * <p>Note: You should always train an agent prior to sending it queries. See the [training * documentation](https://cloud.google.com/dialogflow/es/docs/training). * * <p>Sample code: * * <pre>{@code * try (AgentsClient agentsClient = AgentsClient.create()) { * SetAgentRequest request = * SetAgentRequest.newBuilder() * .setAgent(Agent.newBuilder().build()) * .setUpdateMask(FieldMask.newBuilder().build()) * .build(); * ApiFuture<Agent> future = agentsClient.setAgentCallable().futureCall(request); * // Do something. * Agent response = future.get(); * } * }</pre> */ public final UnaryCallable<SetAgentRequest, Agent> setAgentCallable() { return stub.setAgentCallable(); } // AUTO-GENERATED DOCUMENTATION AND METHOD. /** * Deletes the specified agent. * * <p>Sample code: * * <pre>{@code * try (AgentsClient agentsClient = AgentsClient.create()) { * LocationName parent = LocationName.of("[PROJECT]", "[LOCATION]"); * agentsClient.deleteAgent(parent); * } * }</pre> * * @param parent Required. The project that the agent to delete is associated with. Format: * `projects/&lt;Project ID&gt;` or `projects/&lt;Project ID&gt;/locations/&lt;Location * ID&gt;`. * @throws com.google.api.gax.rpc.ApiException if the remote call fails */ public final void deleteAgent(LocationName parent) { DeleteAgentRequest request = DeleteAgentRequest.newBuilder() .setParent(parent == null ? null : parent.toString()) .build(); deleteAgent(request); } // AUTO-GENERATED DOCUMENTATION AND METHOD. /** * Deletes the specified agent. * * <p>Sample code: * * <pre>{@code * try (AgentsClient agentsClient = AgentsClient.create()) { * ProjectName parent = ProjectName.of("[PROJECT]"); * agentsClient.deleteAgent(parent); * } * }</pre> * * @param parent Required. The project that the agent to delete is associated with. Format: * `projects/&lt;Project ID&gt;` or `projects/&lt;Project ID&gt;/locations/&lt;Location * ID&gt;`. * @throws com.google.api.gax.rpc.ApiException if the remote call fails */ public final void deleteAgent(ProjectName parent) { DeleteAgentRequest request = DeleteAgentRequest.newBuilder() .setParent(parent == null ? null : parent.toString()) .build(); deleteAgent(request); } // AUTO-GENERATED DOCUMENTATION AND METHOD. /** * Deletes the specified agent. * * <p>Sample code: * * <pre>{@code * try (AgentsClient agentsClient = AgentsClient.create()) { * String parent = AgentName.ofProjectName("[PROJECT]").toString(); * agentsClient.deleteAgent(parent); * } * }</pre> * * @param parent Required. The project that the agent to delete is associated with. Format: * `projects/&lt;Project ID&gt;` or `projects/&lt;Project ID&gt;/locations/&lt;Location * ID&gt;`. * @throws com.google.api.gax.rpc.ApiException if the remote call fails */ public final void deleteAgent(String parent) { DeleteAgentRequest request = DeleteAgentRequest.newBuilder().setParent(parent).build(); deleteAgent(request); } // AUTO-GENERATED DOCUMENTATION AND METHOD. /** * Deletes the specified agent. * * <p>Sample code: * * <pre>{@code * try (AgentsClient agentsClient = AgentsClient.create()) { * DeleteAgentRequest request = * DeleteAgentRequest.newBuilder() * .setParent(AgentName.ofProjectName("[PROJECT]").toString()) * .build(); * agentsClient.deleteAgent(request); * } * }</pre> * * @param request The request object containing all of the parameters for the API call. * @throws com.google.api.gax.rpc.ApiException if the remote call fails */ public final void deleteAgent(DeleteAgentRequest request) { deleteAgentCallable().call(request); } // AUTO-GENERATED DOCUMENTATION AND METHOD. /** * Deletes the specified agent. * * <p>Sample code: * * <pre>{@code * try (AgentsClient agentsClient = AgentsClient.create()) { * DeleteAgentRequest request = * DeleteAgentRequest.newBuilder() * .setParent(AgentName.ofProjectName("[PROJECT]").toString()) * .build(); * ApiFuture<Empty> future = agentsClient.deleteAgentCallable().futureCall(request); * // Do something. * future.get(); * } * }</pre> */ public final UnaryCallable<DeleteAgentRequest, Empty> deleteAgentCallable() { return stub.deleteAgentCallable(); } // AUTO-GENERATED DOCUMENTATION AND METHOD. /** * Returns the list of agents. Since there is at most one conversational agent per project, this * method is useful primarily for listing all agents across projects the caller has access to. One * can achieve that with a wildcard project collection id "-". Refer to [List * Sub-Collections](https://cloud.google.com/apis/design/design_patterns#list_sub-collections). * * <p>Sample code: * * <pre>{@code * try (AgentsClient agentsClient = AgentsClient.create()) { * LocationName parent = LocationName.of("[PROJECT]", "[LOCATION]"); * for (Agent element : agentsClient.searchAgents(parent).iterateAll()) { * // doThingsWith(element); * } * } * }</pre> * * @param parent Required. The project to list agents from. Format: `projects/&lt;Project ID or * '-'&gt;` or `projects/&lt;Project ID or '-'&gt;/locations/&lt;Location ID&gt;`. * @throws com.google.api.gax.rpc.ApiException if the remote call fails */ public final SearchAgentsPagedResponse searchAgents(LocationName parent) { SearchAgentsRequest request = SearchAgentsRequest.newBuilder() .setParent(parent == null ? null : parent.toString()) .build(); return searchAgents(request); } // AUTO-GENERATED DOCUMENTATION AND METHOD. /** * Returns the list of agents. Since there is at most one conversational agent per project, this * method is useful primarily for listing all agents across projects the caller has access to. One * can achieve that with a wildcard project collection id "-". Refer to [List * Sub-Collections](https://cloud.google.com/apis/design/design_patterns#list_sub-collections). * * <p>Sample code: * * <pre>{@code * try (AgentsClient agentsClient = AgentsClient.create()) { * ProjectName parent = ProjectName.of("[PROJECT]"); * for (Agent element : agentsClient.searchAgents(parent).iterateAll()) { * // doThingsWith(element); * } * } * }</pre> * * @param parent Required. The project to list agents from. Format: `projects/&lt;Project ID or * '-'&gt;` or `projects/&lt;Project ID or '-'&gt;/locations/&lt;Location ID&gt;`. * @throws com.google.api.gax.rpc.ApiException if the remote call fails */ public final SearchAgentsPagedResponse searchAgents(ProjectName parent) { SearchAgentsRequest request = SearchAgentsRequest.newBuilder() .setParent(parent == null ? null : parent.toString()) .build(); return searchAgents(request); } // AUTO-GENERATED DOCUMENTATION AND METHOD. /** * Returns the list of agents. Since there is at most one conversational agent per project, this * method is useful primarily for listing all agents across projects the caller has access to. One * can achieve that with a wildcard project collection id "-". Refer to [List * Sub-Collections](https://cloud.google.com/apis/design/design_patterns#list_sub-collections). * * <p>Sample code: * * <pre>{@code * try (AgentsClient agentsClient = AgentsClient.create()) { * String parent = AgentName.ofProjectName("[PROJECT]").toString(); * for (Agent element : agentsClient.searchAgents(parent).iterateAll()) { * // doThingsWith(element); * } * } * }</pre> * * @param parent Required. The project to list agents from. Format: `projects/&lt;Project ID or * '-'&gt;` or `projects/&lt;Project ID or '-'&gt;/locations/&lt;Location ID&gt;`. * @throws com.google.api.gax.rpc.ApiException if the remote call fails */ public final SearchAgentsPagedResponse searchAgents(String parent) { SearchAgentsRequest request = SearchAgentsRequest.newBuilder().setParent(parent).build(); return searchAgents(request); } // AUTO-GENERATED DOCUMENTATION AND METHOD. /** * Returns the list of agents. Since there is at most one conversational agent per project, this * method is useful primarily for listing all agents across projects the caller has access to. One * can achieve that with a wildcard project collection id "-". Refer to [List * Sub-Collections](https://cloud.google.com/apis/design/design_patterns#list_sub-collections). * * <p>Sample code: * * <pre>{@code * try (AgentsClient agentsClient = AgentsClient.create()) { * SearchAgentsRequest request = * SearchAgentsRequest.newBuilder() * .setParent(AgentName.ofProjectName("[PROJECT]").toString()) * .setPageSize(883849137) * .setPageToken("pageToken873572522") * .build(); * for (Agent element : agentsClient.searchAgents(request).iterateAll()) { * // doThingsWith(element); * } * } * }</pre> * * @param request The request object containing all of the parameters for the API call. * @throws com.google.api.gax.rpc.ApiException if the remote call fails */ public final SearchAgentsPagedResponse searchAgents(SearchAgentsRequest request) { return searchAgentsPagedCallable().call(request); } // AUTO-GENERATED DOCUMENTATION AND METHOD. /** * Returns the list of agents. Since there is at most one conversational agent per project, this * method is useful primarily for listing all agents across projects the caller has access to. One * can achieve that with a wildcard project collection id "-". Refer to [List * Sub-Collections](https://cloud.google.com/apis/design/design_patterns#list_sub-collections). * * <p>Sample code: * * <pre>{@code * try (AgentsClient agentsClient = AgentsClient.create()) { * SearchAgentsRequest request = * SearchAgentsRequest.newBuilder() * .setParent(AgentName.ofProjectName("[PROJECT]").toString()) * .setPageSize(883849137) * .setPageToken("pageToken873572522") * .build(); * ApiFuture<Agent> future = agentsClient.searchAgentsPagedCallable().futureCall(request); * // Do something. * for (Agent element : future.get().iterateAll()) { * // doThingsWith(element); * } * } * }</pre> */ public final UnaryCallable<SearchAgentsRequest, SearchAgentsPagedResponse> searchAgentsPagedCallable() { return stub.searchAgentsPagedCallable(); } // AUTO-GENERATED DOCUMENTATION AND METHOD. /** * Returns the list of agents. Since there is at most one conversational agent per project, this * method is useful primarily for listing all agents across projects the caller has access to. One * can achieve that with a wildcard project collection id "-". Refer to [List * Sub-Collections](https://cloud.google.com/apis/design/design_patterns#list_sub-collections). * * <p>Sample code: * * <pre>{@code * try (AgentsClient agentsClient = AgentsClient.create()) { * SearchAgentsRequest request = * SearchAgentsRequest.newBuilder() * .setParent(AgentName.ofProjectName("[PROJECT]").toString()) * .setPageSize(883849137) * .setPageToken("pageToken873572522") * .build(); * while (true) { * SearchAgentsResponse response = agentsClient.searchAgentsCallable().call(request); * for (Agent element : response.getResponsesList()) { * // doThingsWith(element); * } * String nextPageToken = response.getNextPageToken(); * if (!Strings.isNullOrEmpty(nextPageToken)) { * request = request.toBuilder().setPageToken(nextPageToken).build(); * } else { * break; * } * } * } * }</pre> */ public final UnaryCallable<SearchAgentsRequest, SearchAgentsResponse> searchAgentsCallable() { return stub.searchAgentsCallable(); } // AUTO-GENERATED DOCUMENTATION AND METHOD. /** * Trains the specified agent. * * <p>This method is a [long-running * operation](https://cloud.google.com/dialogflow/es/docs/how/long-running-operations). The * returned `Operation` type has the following method-specific fields: * * <p>- `metadata`: An empty [Struct * message](https://developers.google.com/protocol-buffers/docs/reference/google.protobuf#struct) * - `response`: An [Empty * message](https://developers.google.com/protocol-buffers/docs/reference/google.protobuf#empty) * * <p>Note: You should always train an agent prior to sending it queries. See the [training * documentation](https://cloud.google.com/dialogflow/es/docs/training). * * <p>Sample code: * * <pre>{@code * try (AgentsClient agentsClient = AgentsClient.create()) { * LocationName parent = LocationName.of("[PROJECT]", "[LOCATION]"); * agentsClient.trainAgentAsync(parent).get(); * } * }</pre> * * @param parent Required. The project that the agent to train is associated with. Format: * `projects/&lt;Project ID&gt;` or `projects/&lt;Project ID&gt;/locations/&lt;Location * ID&gt;`. * @throws com.google.api.gax.rpc.ApiException if the remote call fails */ public final OperationFuture<Empty, Struct> trainAgentAsync(LocationName parent) { TrainAgentRequest request = TrainAgentRequest.newBuilder().setParent(parent == null ? null : parent.toString()).build(); return trainAgentAsync(request); } // AUTO-GENERATED DOCUMENTATION AND METHOD. /** * Trains the specified agent. * * <p>This method is a [long-running * operation](https://cloud.google.com/dialogflow/es/docs/how/long-running-operations). The * returned `Operation` type has the following method-specific fields: * * <p>- `metadata`: An empty [Struct * message](https://developers.google.com/protocol-buffers/docs/reference/google.protobuf#struct) * - `response`: An [Empty * message](https://developers.google.com/protocol-buffers/docs/reference/google.protobuf#empty) * * <p>Note: You should always train an agent prior to sending it queries. See the [training * documentation](https://cloud.google.com/dialogflow/es/docs/training). * * <p>Sample code: * * <pre>{@code * try (AgentsClient agentsClient = AgentsClient.create()) { * ProjectName parent = ProjectName.of("[PROJECT]"); * agentsClient.trainAgentAsync(parent).get(); * } * }</pre> * * @param parent Required. The project that the agent to train is associated with. Format: * `projects/&lt;Project ID&gt;` or `projects/&lt;Project ID&gt;/locations/&lt;Location * ID&gt;`. * @throws com.google.api.gax.rpc.ApiException if the remote call fails */ public final OperationFuture<Empty, Struct> trainAgentAsync(ProjectName parent) { TrainAgentRequest request = TrainAgentRequest.newBuilder().setParent(parent == null ? null : parent.toString()).build(); return trainAgentAsync(request); } // AUTO-GENERATED DOCUMENTATION AND METHOD. /** * Trains the specified agent. * * <p>This method is a [long-running * operation](https://cloud.google.com/dialogflow/es/docs/how/long-running-operations). The * returned `Operation` type has the following method-specific fields: * * <p>- `metadata`: An empty [Struct * message](https://developers.google.com/protocol-buffers/docs/reference/google.protobuf#struct) * - `response`: An [Empty * message](https://developers.google.com/protocol-buffers/docs/reference/google.protobuf#empty) * * <p>Note: You should always train an agent prior to sending it queries. See the [training * documentation](https://cloud.google.com/dialogflow/es/docs/training). * * <p>Sample code: * * <pre>{@code * try (AgentsClient agentsClient = AgentsClient.create()) { * String parent = AgentName.ofProjectName("[PROJECT]").toString(); * agentsClient.trainAgentAsync(parent).get(); * } * }</pre> * * @param parent Required. The project that the agent to train is associated with. Format: * `projects/&lt;Project ID&gt;` or `projects/&lt;Project ID&gt;/locations/&lt;Location * ID&gt;`. * @throws com.google.api.gax.rpc.ApiException if the remote call fails */ public final OperationFuture<Empty, Struct> trainAgentAsync(String parent) { TrainAgentRequest request = TrainAgentRequest.newBuilder().setParent(parent).build(); return trainAgentAsync(request); } // AUTO-GENERATED DOCUMENTATION AND METHOD. /** * Trains the specified agent. * * <p>This method is a [long-running * operation](https://cloud.google.com/dialogflow/es/docs/how/long-running-operations). The * returned `Operation` type has the following method-specific fields: * * <p>- `metadata`: An empty [Struct * message](https://developers.google.com/protocol-buffers/docs/reference/google.protobuf#struct) * - `response`: An [Empty * message](https://developers.google.com/protocol-buffers/docs/reference/google.protobuf#empty) * * <p>Note: You should always train an agent prior to sending it queries. See the [training * documentation](https://cloud.google.com/dialogflow/es/docs/training). * * <p>Sample code: * * <pre>{@code * try (AgentsClient agentsClient = AgentsClient.create()) { * TrainAgentRequest request = * TrainAgentRequest.newBuilder() * .setParent(AgentName.ofProjectName("[PROJECT]").toString()) * .build(); * agentsClient.trainAgentAsync(request).get(); * } * }</pre> * * @param request The request object containing all of the parameters for the API call. * @throws com.google.api.gax.rpc.ApiException if the remote call fails */ public final OperationFuture<Empty, Struct> trainAgentAsync(TrainAgentRequest request) { return trainAgentOperationCallable().futureCall(request); } // AUTO-GENERATED DOCUMENTATION AND METHOD. /** * Trains the specified agent. * * <p>This method is a [long-running * operation](https://cloud.google.com/dialogflow/es/docs/how/long-running-operations). The * returned `Operation` type has the following method-specific fields: * * <p>- `metadata`: An empty [Struct * message](https://developers.google.com/protocol-buffers/docs/reference/google.protobuf#struct) * - `response`: An [Empty * message](https://developers.google.com/protocol-buffers/docs/reference/google.protobuf#empty) * * <p>Note: You should always train an agent prior to sending it queries. See the [training * documentation](https://cloud.google.com/dialogflow/es/docs/training). * * <p>Sample code: * * <pre>{@code * try (AgentsClient agentsClient = AgentsClient.create()) { * TrainAgentRequest request = * TrainAgentRequest.newBuilder() * .setParent(AgentName.ofProjectName("[PROJECT]").toString()) * .build(); * OperationFuture<Empty, Struct> future = * agentsClient.trainAgentOperationCallable().futureCall(request); * // Do something. * future.get(); * } * }</pre> */ public final OperationCallable<TrainAgentRequest, Empty, Struct> trainAgentOperationCallable() { return stub.trainAgentOperationCallable(); } // AUTO-GENERATED DOCUMENTATION AND METHOD. /** * Trains the specified agent. * * <p>This method is a [long-running * operation](https://cloud.google.com/dialogflow/es/docs/how/long-running-operations). The * returned `Operation` type has the following method-specific fields: * * <p>- `metadata`: An empty [Struct * message](https://developers.google.com/protocol-buffers/docs/reference/google.protobuf#struct) * - `response`: An [Empty * message](https://developers.google.com/protocol-buffers/docs/reference/google.protobuf#empty) * * <p>Note: You should always train an agent prior to sending it queries. See the [training * documentation](https://cloud.google.com/dialogflow/es/docs/training). * * <p>Sample code: * * <pre>{@code * try (AgentsClient agentsClient = AgentsClient.create()) { * TrainAgentRequest request = * TrainAgentRequest.newBuilder() * .setParent(AgentName.ofProjectName("[PROJECT]").toString()) * .build(); * ApiFuture<Operation> future = agentsClient.trainAgentCallable().futureCall(request); * // Do something. * future.get(); * } * }</pre> */ public final UnaryCallable<TrainAgentRequest, Operation> trainAgentCallable() { return stub.trainAgentCallable(); } // AUTO-GENERATED DOCUMENTATION AND METHOD. /** * Exports the specified agent to a ZIP file. * * <p>This method is a [long-running * operation](https://cloud.google.com/dialogflow/es/docs/how/long-running-operations). The * returned `Operation` type has the following method-specific fields: * * <p>- `metadata`: An empty [Struct * message](https://developers.google.com/protocol-buffers/docs/reference/google.protobuf#struct) * - `response`: [ExportAgentResponse][google.cloud.dialogflow.v2beta1.ExportAgentResponse] * * <p>Sample code: * * <pre>{@code * try (AgentsClient agentsClient = AgentsClient.create()) { * LocationName parent = LocationName.of("[PROJECT]", "[LOCATION]"); * ExportAgentResponse response = agentsClient.exportAgentAsync(parent).get(); * } * }</pre> * * @param parent Required. The project that the agent to export is associated with. Format: * `projects/&lt;Project ID&gt;` or `projects/&lt;Project ID&gt;/locations/&lt;Location * ID&gt;`. * @throws com.google.api.gax.rpc.ApiException if the remote call fails */ public final OperationFuture<ExportAgentResponse, Struct> exportAgentAsync(LocationName parent) { ExportAgentRequest request = ExportAgentRequest.newBuilder() .setParent(parent == null ? null : parent.toString()) .build(); return exportAgentAsync(request); } // AUTO-GENERATED DOCUMENTATION AND METHOD. /** * Exports the specified agent to a ZIP file. * * <p>This method is a [long-running * operation](https://cloud.google.com/dialogflow/es/docs/how/long-running-operations). The * returned `Operation` type has the following method-specific fields: * * <p>- `metadata`: An empty [Struct * message](https://developers.google.com/protocol-buffers/docs/reference/google.protobuf#struct) * - `response`: [ExportAgentResponse][google.cloud.dialogflow.v2beta1.ExportAgentResponse] * * <p>Sample code: * * <pre>{@code * try (AgentsClient agentsClient = AgentsClient.create()) { * ProjectName parent = ProjectName.of("[PROJECT]"); * ExportAgentResponse response = agentsClient.exportAgentAsync(parent).get(); * } * }</pre> * * @param parent Required. The project that the agent to export is associated with. Format: * `projects/&lt;Project ID&gt;` or `projects/&lt;Project ID&gt;/locations/&lt;Location * ID&gt;`. * @throws com.google.api.gax.rpc.ApiException if the remote call fails */ public final OperationFuture<ExportAgentResponse, Struct> exportAgentAsync(ProjectName parent) { ExportAgentRequest request = ExportAgentRequest.newBuilder() .setParent(parent == null ? null : parent.toString()) .build(); return exportAgentAsync(request); } // AUTO-GENERATED DOCUMENTATION AND METHOD. /** * Exports the specified agent to a ZIP file. * * <p>This method is a [long-running * operation](https://cloud.google.com/dialogflow/es/docs/how/long-running-operations). The * returned `Operation` type has the following method-specific fields: * * <p>- `metadata`: An empty [Struct * message](https://developers.google.com/protocol-buffers/docs/reference/google.protobuf#struct) * - `response`: [ExportAgentResponse][google.cloud.dialogflow.v2beta1.ExportAgentResponse] * * <p>Sample code: * * <pre>{@code * try (AgentsClient agentsClient = AgentsClient.create()) { * String parent = AgentName.ofProjectName("[PROJECT]").toString(); * ExportAgentResponse response = agentsClient.exportAgentAsync(parent).get(); * } * }</pre> * * @param parent Required. The project that the agent to export is associated with. Format: * `projects/&lt;Project ID&gt;` or `projects/&lt;Project ID&gt;/locations/&lt;Location * ID&gt;`. * @throws com.google.api.gax.rpc.ApiException if the remote call fails */ public final OperationFuture<ExportAgentResponse, Struct> exportAgentAsync(String parent) { ExportAgentRequest request = ExportAgentRequest.newBuilder().setParent(parent).build(); return exportAgentAsync(request); } // AUTO-GENERATED DOCUMENTATION AND METHOD. /** * Exports the specified agent to a ZIP file. * * <p>This method is a [long-running * operation](https://cloud.google.com/dialogflow/es/docs/how/long-running-operations). The * returned `Operation` type has the following method-specific fields: * * <p>- `metadata`: An empty [Struct * message](https://developers.google.com/protocol-buffers/docs/reference/google.protobuf#struct) * - `response`: [ExportAgentResponse][google.cloud.dialogflow.v2beta1.ExportAgentResponse] * * <p>Sample code: * * <pre>{@code * try (AgentsClient agentsClient = AgentsClient.create()) { * ExportAgentRequest request = * ExportAgentRequest.newBuilder() * .setParent(AgentName.ofProjectName("[PROJECT]").toString()) * .setAgentUri("agentUri1469149223") * .build(); * ExportAgentResponse response = agentsClient.exportAgentAsync(request).get(); * } * }</pre> * * @param request The request object containing all of the parameters for the API call. * @throws com.google.api.gax.rpc.ApiException if the remote call fails */ public final OperationFuture<ExportAgentResponse, Struct> exportAgentAsync( ExportAgentRequest request) { return exportAgentOperationCallable().futureCall(request); } // AUTO-GENERATED DOCUMENTATION AND METHOD. /** * Exports the specified agent to a ZIP file. * * <p>This method is a [long-running * operation](https://cloud.google.com/dialogflow/es/docs/how/long-running-operations). The * returned `Operation` type has the following method-specific fields: * * <p>- `metadata`: An empty [Struct * message](https://developers.google.com/protocol-buffers/docs/reference/google.protobuf#struct) * - `response`: [ExportAgentResponse][google.cloud.dialogflow.v2beta1.ExportAgentResponse] * * <p>Sample code: * * <pre>{@code * try (AgentsClient agentsClient = AgentsClient.create()) { * ExportAgentRequest request = * ExportAgentRequest.newBuilder() * .setParent(AgentName.ofProjectName("[PROJECT]").toString()) * .setAgentUri("agentUri1469149223") * .build(); * OperationFuture<ExportAgentResponse, Struct> future = * agentsClient.exportAgentOperationCallable().futureCall(request); * // Do something. * ExportAgentResponse response = future.get(); * } * }</pre> */ public final OperationCallable<ExportAgentRequest, ExportAgentResponse, Struct> exportAgentOperationCallable() { return stub.exportAgentOperationCallable(); } // AUTO-GENERATED DOCUMENTATION AND METHOD. /** * Exports the specified agent to a ZIP file. * * <p>This method is a [long-running * operation](https://cloud.google.com/dialogflow/es/docs/how/long-running-operations). The * returned `Operation` type has the following method-specific fields: * * <p>- `metadata`: An empty [Struct * message](https://developers.google.com/protocol-buffers/docs/reference/google.protobuf#struct) * - `response`: [ExportAgentResponse][google.cloud.dialogflow.v2beta1.ExportAgentResponse] * * <p>Sample code: * * <pre>{@code * try (AgentsClient agentsClient = AgentsClient.create()) { * ExportAgentRequest request = * ExportAgentRequest.newBuilder() * .setParent(AgentName.ofProjectName("[PROJECT]").toString()) * .setAgentUri("agentUri1469149223") * .build(); * ApiFuture<Operation> future = agentsClient.exportAgentCallable().futureCall(request); * // Do something. * Operation response = future.get(); * } * }</pre> */ public final UnaryCallable<ExportAgentRequest, Operation> exportAgentCallable() { return stub.exportAgentCallable(); } // AUTO-GENERATED DOCUMENTATION AND METHOD. /** * Imports the specified agent from a ZIP file. * * <p>Uploads new intents and entity types without deleting the existing ones. Intents and entity * types with the same name are replaced with the new versions from * [ImportAgentRequest][google.cloud.dialogflow.v2beta1.ImportAgentRequest]. After the import, the * imported draft agent will be trained automatically (unless disabled in agent settings). * However, once the import is done, training may not be completed yet. Please call * [TrainAgent][google.cloud.dialogflow.v2beta1.Agents.TrainAgent] and wait for the operation it * returns in order to train explicitly. * * <p>This method is a [long-running * operation](https://cloud.google.com/dialogflow/es/docs/how/long-running-operations). The * returned `Operation` type has the following method-specific fields: * * <p>- `metadata`: An empty [Struct * message](https://developers.google.com/protocol-buffers/docs/reference/google.protobuf#struct) * - `response`: An [Empty * message](https://developers.google.com/protocol-buffers/docs/reference/google.protobuf#empty) * * <p>The operation only tracks when importing is complete, not when it is done training. * * <p>Note: You should always train an agent prior to sending it queries. See the [training * documentation](https://cloud.google.com/dialogflow/es/docs/training). * * <p>Sample code: * * <pre>{@code * try (AgentsClient agentsClient = AgentsClient.create()) { * ImportAgentRequest request = * ImportAgentRequest.newBuilder() * .setParent(AgentName.ofProjectName("[PROJECT]").toString()) * .build(); * agentsClient.importAgentAsync(request).get(); * } * }</pre> * * @param request The request object containing all of the parameters for the API call. * @throws com.google.api.gax.rpc.ApiException if the remote call fails */ public final OperationFuture<Empty, Struct> importAgentAsync(ImportAgentRequest request) { return importAgentOperationCallable().futureCall(request); } // AUTO-GENERATED DOCUMENTATION AND METHOD. /** * Imports the specified agent from a ZIP file. * * <p>Uploads new intents and entity types without deleting the existing ones. Intents and entity * types with the same name are replaced with the new versions from * [ImportAgentRequest][google.cloud.dialogflow.v2beta1.ImportAgentRequest]. After the import, the * imported draft agent will be trained automatically (unless disabled in agent settings). * However, once the import is done, training may not be completed yet. Please call * [TrainAgent][google.cloud.dialogflow.v2beta1.Agents.TrainAgent] and wait for the operation it * returns in order to train explicitly. * * <p>This method is a [long-running * operation](https://cloud.google.com/dialogflow/es/docs/how/long-running-operations). The * returned `Operation` type has the following method-specific fields: * * <p>- `metadata`: An empty [Struct * message](https://developers.google.com/protocol-buffers/docs/reference/google.protobuf#struct) * - `response`: An [Empty * message](https://developers.google.com/protocol-buffers/docs/reference/google.protobuf#empty) * * <p>The operation only tracks when importing is complete, not when it is done training. * * <p>Note: You should always train an agent prior to sending it queries. See the [training * documentation](https://cloud.google.com/dialogflow/es/docs/training). * * <p>Sample code: * * <pre>{@code * try (AgentsClient agentsClient = AgentsClient.create()) { * ImportAgentRequest request = * ImportAgentRequest.newBuilder() * .setParent(AgentName.ofProjectName("[PROJECT]").toString()) * .build(); * OperationFuture<Empty, Struct> future = * agentsClient.importAgentOperationCallable().futureCall(request); * // Do something. * future.get(); * } * }</pre> */ public final OperationCallable<ImportAgentRequest, Empty, Struct> importAgentOperationCallable() { return stub.importAgentOperationCallable(); } // AUTO-GENERATED DOCUMENTATION AND METHOD. /** * Imports the specified agent from a ZIP file. * * <p>Uploads new intents and entity types without deleting the existing ones. Intents and entity * types with the same name are replaced with the new versions from * [ImportAgentRequest][google.cloud.dialogflow.v2beta1.ImportAgentRequest]. After the import, the * imported draft agent will be trained automatically (unless disabled in agent settings). * However, once the import is done, training may not be completed yet. Please call * [TrainAgent][google.cloud.dialogflow.v2beta1.Agents.TrainAgent] and wait for the operation it * returns in order to train explicitly. * * <p>This method is a [long-running * operation](https://cloud.google.com/dialogflow/es/docs/how/long-running-operations). The * returned `Operation` type has the following method-specific fields: * * <p>- `metadata`: An empty [Struct * message](https://developers.google.com/protocol-buffers/docs/reference/google.protobuf#struct) * - `response`: An [Empty * message](https://developers.google.com/protocol-buffers/docs/reference/google.protobuf#empty) * * <p>The operation only tracks when importing is complete, not when it is done training. * * <p>Note: You should always train an agent prior to sending it queries. See the [training * documentation](https://cloud.google.com/dialogflow/es/docs/training). * * <p>Sample code: * * <pre>{@code * try (AgentsClient agentsClient = AgentsClient.create()) { * ImportAgentRequest request = * ImportAgentRequest.newBuilder() * .setParent(AgentName.ofProjectName("[PROJECT]").toString()) * .build(); * ApiFuture<Operation> future = agentsClient.importAgentCallable().futureCall(request); * // Do something. * future.get(); * } * }</pre> */ public final UnaryCallable<ImportAgentRequest, Operation> importAgentCallable() { return stub.importAgentCallable(); } // AUTO-GENERATED DOCUMENTATION AND METHOD. /** * Restores the specified agent from a ZIP file. * * <p>Replaces the current agent version with a new one. All the intents and entity types in the * older version are deleted. After the restore, the restored draft agent will be trained * automatically (unless disabled in agent settings). However, once the restore is done, training * may not be completed yet. Please call * [TrainAgent][google.cloud.dialogflow.v2beta1.Agents.TrainAgent] and wait for the operation it * returns in order to train explicitly. * * <p>This method is a [long-running * operation](https://cloud.google.com/dialogflow/es/docs/how/long-running-operations). The * returned `Operation` type has the following method-specific fields: * * <p>- `metadata`: An empty [Struct * message](https://developers.google.com/protocol-buffers/docs/reference/google.protobuf#struct) * - `response`: An [Empty * message](https://developers.google.com/protocol-buffers/docs/reference/google.protobuf#empty) * * <p>The operation only tracks when restoring is complete, not when it is done training. * * <p>Note: You should always train an agent prior to sending it queries. See the [training * documentation](https://cloud.google.com/dialogflow/es/docs/training). * * <p>Sample code: * * <pre>{@code * try (AgentsClient agentsClient = AgentsClient.create()) { * RestoreAgentRequest request = * RestoreAgentRequest.newBuilder() * .setParent(AgentName.ofProjectName("[PROJECT]").toString()) * .build(); * agentsClient.restoreAgentAsync(request).get(); * } * }</pre> * * @param request The request object containing all of the parameters for the API call. * @throws com.google.api.gax.rpc.ApiException if the remote call fails */ public final OperationFuture<Empty, Struct> restoreAgentAsync(RestoreAgentRequest request) { return restoreAgentOperationCallable().futureCall(request); } // AUTO-GENERATED DOCUMENTATION AND METHOD. /** * Restores the specified agent from a ZIP file. * * <p>Replaces the current agent version with a new one. All the intents and entity types in the * older version are deleted. After the restore, the restored draft agent will be trained * automatically (unless disabled in agent settings). However, once the restore is done, training * may not be completed yet. Please call * [TrainAgent][google.cloud.dialogflow.v2beta1.Agents.TrainAgent] and wait for the operation it * returns in order to train explicitly. * * <p>This method is a [long-running * operation](https://cloud.google.com/dialogflow/es/docs/how/long-running-operations). The * returned `Operation` type has the following method-specific fields: * * <p>- `metadata`: An empty [Struct * message](https://developers.google.com/protocol-buffers/docs/reference/google.protobuf#struct) * - `response`: An [Empty * message](https://developers.google.com/protocol-buffers/docs/reference/google.protobuf#empty) * * <p>The operation only tracks when restoring is complete, not when it is done training. * * <p>Note: You should always train an agent prior to sending it queries. See the [training * documentation](https://cloud.google.com/dialogflow/es/docs/training). * * <p>Sample code: * * <pre>{@code * try (AgentsClient agentsClient = AgentsClient.create()) { * RestoreAgentRequest request = * RestoreAgentRequest.newBuilder() * .setParent(AgentName.ofProjectName("[PROJECT]").toString()) * .build(); * OperationFuture<Empty, Struct> future = * agentsClient.restoreAgentOperationCallable().futureCall(request); * // Do something. * future.get(); * } * }</pre> */ public final OperationCallable<RestoreAgentRequest, Empty, Struct> restoreAgentOperationCallable() { return stub.restoreAgentOperationCallable(); } // AUTO-GENERATED DOCUMENTATION AND METHOD. /** * Restores the specified agent from a ZIP file. * * <p>Replaces the current agent version with a new one. All the intents and entity types in the * older version are deleted. After the restore, the restored draft agent will be trained * automatically (unless disabled in agent settings). However, once the restore is done, training * may not be completed yet. Please call * [TrainAgent][google.cloud.dialogflow.v2beta1.Agents.TrainAgent] and wait for the operation it * returns in order to train explicitly. * * <p>This method is a [long-running * operation](https://cloud.google.com/dialogflow/es/docs/how/long-running-operations). The * returned `Operation` type has the following method-specific fields: * * <p>- `metadata`: An empty [Struct * message](https://developers.google.com/protocol-buffers/docs/reference/google.protobuf#struct) * - `response`: An [Empty * message](https://developers.google.com/protocol-buffers/docs/reference/google.protobuf#empty) * * <p>The operation only tracks when restoring is complete, not when it is done training. * * <p>Note: You should always train an agent prior to sending it queries. See the [training * documentation](https://cloud.google.com/dialogflow/es/docs/training). * * <p>Sample code: * * <pre>{@code * try (AgentsClient agentsClient = AgentsClient.create()) { * RestoreAgentRequest request = * RestoreAgentRequest.newBuilder() * .setParent(AgentName.ofProjectName("[PROJECT]").toString()) * .build(); * ApiFuture<Operation> future = agentsClient.restoreAgentCallable().futureCall(request); * // Do something. * future.get(); * } * }</pre> */ public final UnaryCallable<RestoreAgentRequest, Operation> restoreAgentCallable() { return stub.restoreAgentCallable(); } // AUTO-GENERATED DOCUMENTATION AND METHOD. /** * Gets agent validation result. Agent validation is performed during training time and is updated * automatically when training is completed. * * <p>Sample code: * * <pre>{@code * try (AgentsClient agentsClient = AgentsClient.create()) { * GetValidationResultRequest request = * GetValidationResultRequest.newBuilder() * .setParent(AgentName.ofProjectName("[PROJECT]").toString()) * .setLanguageCode("languageCode-2092349083") * .build(); * ValidationResult response = agentsClient.getValidationResult(request); * } * }</pre> * * @param request The request object containing all of the parameters for the API call. * @throws com.google.api.gax.rpc.ApiException if the remote call fails */ public final ValidationResult getValidationResult(GetValidationResultRequest request) { return getValidationResultCallable().call(request); } // AUTO-GENERATED DOCUMENTATION AND METHOD. /** * Gets agent validation result. Agent validation is performed during training time and is updated * automatically when training is completed. * * <p>Sample code: * * <pre>{@code * try (AgentsClient agentsClient = AgentsClient.create()) { * GetValidationResultRequest request = * GetValidationResultRequest.newBuilder() * .setParent(AgentName.ofProjectName("[PROJECT]").toString()) * .setLanguageCode("languageCode-2092349083") * .build(); * ApiFuture<ValidationResult> future = * agentsClient.getValidationResultCallable().futureCall(request); * // Do something. * ValidationResult response = future.get(); * } * }</pre> */ public final UnaryCallable<GetValidationResultRequest, ValidationResult> getValidationResultCallable() { return stub.getValidationResultCallable(); } @Override public final void close() { stub.close(); } @Override public void shutdown() { stub.shutdown(); } @Override public boolean isShutdown() { return stub.isShutdown(); } @Override public boolean isTerminated() { return stub.isTerminated(); } @Override public void shutdownNow() { stub.shutdownNow(); } @Override public boolean awaitTermination(long duration, TimeUnit unit) throws InterruptedException { return stub.awaitTermination(duration, unit); } public static class SearchAgentsPagedResponse extends AbstractPagedListResponse< SearchAgentsRequest, SearchAgentsResponse, Agent, SearchAgentsPage, SearchAgentsFixedSizeCollection> { public static ApiFuture<SearchAgentsPagedResponse> createAsync( PageContext<SearchAgentsRequest, SearchAgentsResponse, Agent> context, ApiFuture<SearchAgentsResponse> futureResponse) { ApiFuture<SearchAgentsPage> futurePage = SearchAgentsPage.createEmptyPage().createPageAsync(context, futureResponse); return ApiFutures.transform( futurePage, input -> new SearchAgentsPagedResponse(input), MoreExecutors.directExecutor()); } private SearchAgentsPagedResponse(SearchAgentsPage page) { super(page, SearchAgentsFixedSizeCollection.createEmptyCollection()); } } public static class SearchAgentsPage extends AbstractPage<SearchAgentsRequest, SearchAgentsResponse, Agent, SearchAgentsPage> { private SearchAgentsPage( PageContext<SearchAgentsRequest, SearchAgentsResponse, Agent> context, SearchAgentsResponse response) { super(context, response); } private static SearchAgentsPage createEmptyPage() { return new SearchAgentsPage(null, null); } @Override protected SearchAgentsPage createPage( PageContext<SearchAgentsRequest, SearchAgentsResponse, Agent> context, SearchAgentsResponse response) { return new SearchAgentsPage(context, response); } @Override public ApiFuture<SearchAgentsPage> createPageAsync( PageContext<SearchAgentsRequest, SearchAgentsResponse, Agent> context, ApiFuture<SearchAgentsResponse> futureResponse) { return super.createPageAsync(context, futureResponse); } } public static class SearchAgentsFixedSizeCollection extends AbstractFixedSizeCollection< SearchAgentsRequest, SearchAgentsResponse, Agent, SearchAgentsPage, SearchAgentsFixedSizeCollection> { private SearchAgentsFixedSizeCollection(List<SearchAgentsPage> pages, int collectionSize) { super(pages, collectionSize); } private static SearchAgentsFixedSizeCollection createEmptyCollection() { return new SearchAgentsFixedSizeCollection(null, 0); } @Override protected SearchAgentsFixedSizeCollection createCollection( List<SearchAgentsPage> pages, int collectionSize) { return new SearchAgentsFixedSizeCollection(pages, collectionSize); } } }
/* ### * IP: GHIDRA * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package ghidra.pcode.exec; import java.util.HashMap; import java.util.Map; import ghidra.pcode.utils.Utils; import ghidra.program.model.address.Address; import ghidra.program.model.address.AddressSpace; public class AddressOfPcodeExecutorState implements PcodeExecutorStatePiece<byte[], Address> { private final boolean isBigEndian; private Map<Long, Address> unique = new HashMap<>(); public AddressOfPcodeExecutorState(boolean isBigEndian) { this.isBigEndian = isBigEndian; } @Override public byte[] longToOffset(AddressSpace space, long l) { return Utils.longToBytes(l, space.getPointerSize(), isBigEndian); } @Override public void setVar(AddressSpace space, byte[] offset, int size, boolean truncateAddressableUnit, Address val) { if (space != unique) { return; } long off = Utils.bytesToLong(offset, offset.length, isBigEndian); unique.put(off, val); } @Override public Address getVar(AddressSpace space, byte[] offset, int size, boolean truncateAddressableUnit) { long off = Utils.bytesToLong(offset, offset.length, isBigEndian); if (space != unique) { return space.getAddress(off); } return unique.get(off); } }
package playground.spring.jpa.attributeConverter.model; import lombok.Data; import lombok.NoArgsConstructor; import playground.spring.jpa.attributeConverter.PayloadConverter; import javax.persistence.Convert; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; @Entity @NoArgsConstructor @Data public class A { @Id @GeneratedValue(strategy = GenerationType.AUTO) private Long id; private String name; @Convert(converter = PayloadConverter.class) private String payload; }
package uk.org.binky.jchan.results; public interface SendResult { void run(final boolean ok); }
/* * 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.httprpc.beans; import java.math.BigInteger; import java.net.URL; import java.time.DayOfWeek; import java.time.Duration; import java.time.Instant; import java.time.LocalDate; import java.time.LocalDateTime; import java.time.LocalTime; import java.time.Period; import java.util.Date; import java.util.List; import java.util.Map; import java.util.UUID; public class TestBean implements TestInterface { public static class NestedBean implements NestedInterface { private boolean flag = false; @Override public boolean getFlag() { return flag; } public void setFlag(boolean flag) { this.flag = flag; } } private int i = 0; private long l = 0; private double d = 0; private String string = null; private BigInteger bigInteger = null; private DayOfWeek dayOfWeek = null; private Date date = null; private Instant instant = null; private LocalDate localDate = null; private LocalTime localTime = null; private LocalDateTime localDateTime = null; private Duration duration = null; private Period period = null; private UUID uuid = null; private URL url = null; private NestedBean nestedBean = null; private List<?> list = null; private List<Integer> integerList = null; private List<NestedBean> nestedBeanList = null; private Map<String, ?> map = null; private Map<String, Double> doubleMap = null; private Map<String, NestedBean> nestedBeanMap = null; @Key("i") @Override public int getInteger() { return i; } @Key("i") public void setInteger(int i) { this.i = i; } @Override public long getLong() { return l; } public void setLong(long l) { this.l = l; } @Override public double getDouble() { return d; } public void setDouble(double d) { this.d = d; } @Override public String getString() { return string; } public void setString(String string) { this.string = string; } @Override public BigInteger getBigInteger() { return bigInteger; } public void setBigInteger(BigInteger bigInteger) { this.bigInteger = bigInteger; } @Override public DayOfWeek getDayOfWeek() { return dayOfWeek; } public void setDayOfWeek(DayOfWeek dayOfWeek) { this.dayOfWeek = dayOfWeek; } @Override public Date getDate() { return date; } public void setDate(Date date) { this.date = date; } @Override public Instant getInstant() { return instant; } public void setInstant(Instant instant) { this.instant = instant; } @Override public LocalDate getLocalDate() { return localDate; } public void setLocalDate(LocalDate localDate) { this.localDate = localDate; } @Override public LocalTime getLocalTime() { return localTime; } public void setLocalTime(LocalTime localTime) { this.localTime = localTime; } @Override public LocalDateTime getLocalDateTime() { return localDateTime; } public void setLocalDateTime(LocalDateTime localDateTime) { this.localDateTime = localDateTime; } @Override public Duration getDuration() { return duration; } public void setDuration(Duration duration) { this.duration = duration; } @Override public Period getPeriod() { return period; } public void setPeriod(Period period) { this.period = period; } @Override public UUID getUUID() { return uuid; } public void setUUID(UUID uuid) { this.uuid = uuid; } @Override public URL getURL() { return url; } public void setURL(URL url) { this.url = url; } @Override public NestedBean getNestedBean() { return nestedBean; } public void setNestedBean(NestedBean nestedBean) { this.nestedBean = nestedBean; } @Override public List<?> getList() { return list; } public void setList(List<?> list) { this.list = list; } @Override public List<Integer> getIntegerList() { return integerList; } public void setIntegerList(List<Integer> integerList) { this.integerList = integerList; } @Override public List<NestedBean> getNestedBeanList() { return nestedBeanList; } public void setNestedBeanList(List<NestedBean> nestedBeanList) { this.nestedBeanList = nestedBeanList; } @Override public Map<String, ?> getMap() { return map; } public void setMap(Map<String, ?> map) { this.map = map; } @Override public Map<String, Double> getDoubleMap() { return doubleMap; } public void setDoubleMap(Map<String, Double> doubleMap) { this.doubleMap = doubleMap; } @Override public Map<String, NestedBean> getNestedBeanMap() { return nestedBeanMap; } public void setNestedBeanMap(Map<String, NestedBean> nestedBeanMap) { this.nestedBeanMap = nestedBeanMap; } public int get() { return 0; } public void getX() { // No-op } public boolean is() { return false; } public void isY() { // No-op } public void set(double value) { // No-op } public double setZ(double value) { return value; } }
/* * Copyright (C) 2015 Archie L. Cobbs. All rights reserved. */ package io.permazen.core; import com.google.common.base.Preconditions; import com.google.common.collect.Maps; import io.permazen.core.type.ReferenceFieldType; import io.permazen.core.util.ObjIdMap; import io.permazen.core.util.ObjIdSet; import io.permazen.kv.KVPair; import io.permazen.kv.KVTransaction; import io.permazen.kv.KVTransactionException; import io.permazen.kv.KeyRange; import io.permazen.kv.KeyRanges; import io.permazen.kv.util.NavigableMapKVStore; import io.permazen.util.ByteReader; import io.permazen.util.ByteUtil; import io.permazen.util.ByteWriter; import io.permazen.util.CloseableIterator; import io.permazen.util.NavigableSets; import io.permazen.util.UnsignedIntEncoder; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.LinkedHashSet; import java.util.List; import java.util.Map; import java.util.NavigableMap; import java.util.NavigableSet; import java.util.Set; import java.util.SortedSet; import java.util.TreeMap; import java.util.TreeSet; import java.util.function.Predicate; import javax.annotation.concurrent.GuardedBy; import javax.annotation.concurrent.ThreadSafe; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * A Permazen {@link Database} transaction. * * <p> * Note: this is the lower level, core API for {@link io.permazen.Permazen}. In most cases this API * will only be used indirectly through the higher level {@link io.permazen.Permazen}, {@link io.permazen.JTransaction}, * and {@link io.permazen.JObject} APIs. * * <p> * Methods in this class can be divided into the following categories: * * <p> * <b>Transaction Meta-Data</b> * <ul> * <li>{@link #getDatabase getDatabase()} - Get the associated {@link Database}</li> * <li>{@link #getKVTransaction getKVTransaction()} - Get the underlying key/value store transaction.</li> * <li>{@link #getSchemas getSchemas()} - Get the database {@link Schemas}, as seen by this transaction</li> * <li>{@link #getSchema() getSchema()} - Get the {@link Schema} that will be used by this transaction</li> * <li>{@link #deleteSchemaVersion deleteSchemaVersion()} - Delete a schema version that is no longer being used</li> * <li>{@link #getUserObject} - Get user object associated with this instance</li> * <li>{@link #setUserObject} - Set user object associated with this instance</li> * </ul> * * <p> * <b>Transaction Lifecycle</b> * <ul> * <li>{@link #commit commit()} - Commit transaction</li> * <li>{@link #rollback rollback()} - Roll back transaction</li> * <li>{@link #isValid isValid()} - Test transaction validity</li> * <li>{@link #setTimeout setTimeout()} - Set transaction timeout</li> * <li>{@link #setReadOnly setReadOnly()} - Set transaction to read-only</li> * <li>{@link #setRollbackOnly setRollbackOnly()} - Set transaction for rollack only</li> * <li>{@link #addCallback addCallback()} - Register a {@link Callback} on transaction completion</li> * <li>{@link #createSnapshotTransaction createSnapshotTransaction()} - Create a empty, in-memory copy of this transaction</li> * <li>{@link #isSnapshot} - Determine whether this transaction is a snapshot transaction</li> * </ul> * * <p> * <b>Object Lifecycle</b> * <ul> * <li>{@link #create(int) create()} - Create a database object</li> * <li>{@link #delete delete()} - Delete a database object</li> * <li>{@link #exists exists()} - Test whether a database object exists</li> * <li>{@link #copy copy()} - Copy an object into a (possibly different) transaction</li> * <li>{@link #addCreateListener addCreateListener()} - Register a {@link CreateListener} for notifications about new objects</li> * <li>{@link #removeCreateListener removeCreateListener()} - Unregister a {@link CreateListener}</li> * <li>{@link #addDeleteListener addDeleteListener()} - Register a {@link DeleteListener} for notifications * about object deletions</li> * <li>{@link #removeDeleteListener removeDeleteListener()} - Unregister a {@link DeleteListener}</li> * </ul> * * <p> * <b>Object Versioning</b> * <ul> * <li>{@link #getSchemaVersion(ObjId) getSchemaVersion()} - Inspect an object's schema version</li> * <li>{@link #updateSchemaVersion updateSchemaVersion()} - Update an object's schema version to match this transaction</li> * <li>{@link #queryVersion queryVersion()} - Locate objects by schema version</li> * <li>{@link #addVersionChangeListener addVersionChangeListener()} - Register a {@link VersionChangeListener} * for notifications about object version changes</li> * <li>{@link #removeVersionChangeListener removeVersionChangeListener()} - Unregister a {@link VersionChangeListener}</li> * </ul> * * <p> * <b>Object and Field Access</b> * <ul> * <li>{@link #getAll getAll(int)} - Get all objects, or all objects of a specific type</li> * <li>{@link #readSimpleField readSimpleField()} - Read the value of a {@link SimpleField} in an object</li> * <li>{@link #writeSimpleField writeSimpleField()} - Write the value of a {@link SimpleField} in an object</li> * <li>{@link #readCounterField readCounterField()} - Read the value of a {@link CounterField} in an object</li> * <li>{@link #writeCounterField writeCounterField()} - Write the value of a {@link CounterField} in an object</li> * <li>{@link #adjustCounterField adjustCounterField()} - Adjust the value of a {@link CounterField} in an object</li> * <li>{@link #readSetField readSetField()} - Access a {@link SetField} in an object as a {@link NavigableSet}</li> * <li>{@link #readListField readListField()} - Access a {@link ListField} in an object as a {@link List}</li> * <li>{@link #readMapField readMapField()} - Access a {@link MapField} in an object as a {@link NavigableMap}</li> * <li>{@link #getKey getKey(ObjId)} - Get the {@link io.permazen.kv.KVDatabase} key corresponding to an object</li> * <li>{@link #getKey getKey(ObjId, int)} - Get the {@link io.permazen.kv.KVDatabase} * key corresponding to a field in an object</li> * </ul> * * <p> * <b>Field Change Notifications</b> * <ul> * <li>{@link #addSimpleFieldChangeListener addSimpleFieldChangeListener()} - Register a {@link SimpleFieldChangeListener} for * notifications of changes in a {@link SimpleField}, as seen through a path of object references</li> * <li>{@link #addSetFieldChangeListener addSetFieldChangeListener()} - Register a {@link SetFieldChangeListener} for * notifications of changes in a {@link SetField}, as seen through a path of object references</li> * <li>{@link #addListFieldChangeListener addListFieldChangeListener()} - Register a {@link ListFieldChangeListener} for * notifications of changes in a {@link ListField}, as seen through a path of object references</li> * <li>{@link #addMapFieldChangeListener addMapFieldChangeListener()} - Register a {@link MapFieldChangeListener} for * notifications of changes in a {@link MapField}, as seen through a path of object references</li> * <li>{@link #removeSimpleFieldChangeListener removeSimpleFieldChangeListener()} - Unregister a previously registered * {@link SimpleFieldChangeListener}</li> * <li>{@link #removeSetFieldChangeListener removeSetFieldChangeListener()} - Unregister a previously registered * {@link SetFieldChangeListener}</li> * <li>{@link #removeListFieldChangeListener removeListFieldChangeListener()} - Unregister a previously registered * {@link ListFieldChangeListener}</li> * <li>{@link #removeMapFieldChangeListener removeMapFieldChangeListener()} - Unregister a previously registered * {@link MapFieldChangeListener}</li> * </ul> * * <p> * <b>Reference Paths</b> * <ul> * <li>{@link #followReferencePath followReferencePath()} - Find all objects referred to by any element in a given set * of starting objects through a specified reference path</li> * <li>{@link #invertReferencePath invertReferencePath()} - Find all objects that refer to any element in a given set * of target objects through a specified reference path</li> * </ul> * * <p> * <b>Index Queries</b> * <ul> * <li>{@link #queryIndex queryIndex()} - Query the index associated with a {@link SimpleField} * to identify all values and all objects having those values</li> * <li>{@link #queryListElementIndex queryListElementIndex()} - Query the index associated with a {@link ListField} * element sub-field to identify all list elements, all objects having those elements in the list, * and their corresponding indices</li> * <li>{@link #queryMapValueIndex queryMapValueIndex()} - Query the index associated with a {@link MapField} * value sub-field to identify all map values, all objects having those values in the map, and the corresponding keys</li> * <li>{@link #queryCompositeIndex queryCompositeIndex()} - Query any composite index</li> * <li>{@link #queryCompositeIndex2 queryCompositeIndex2()} - Query a composite index on two fields</li> * <li>{@link #queryCompositeIndex3 queryCompositeIndex3()} - Query a composite index on three fields</li> * <li>{@link #queryCompositeIndex3 queryCompositeIndex4()} - Query a composite index on four fields</li> * <!-- COMPOSITE-INDEX --> * </ul> * * <p> * <b>Listener Sets</b> * <ul> * <li>{@link #snapshotListeners} - Create an immutable snapshot of all registered listeners</li> * <li>{@link #setListeners setListeners()} - Bulk registration of listeners from a previously created snapshot</li> * </ul> * * <p> * All methods returning a set of values return a {@link NavigableSet}. * The {@link NavigableSets} utility class provides methods for the efficient {@link NavigableSets#intersection intersection}, * {@link NavigableSets#union union}, {@link NavigableSets#difference difference}, and * {@link NavigableSets#symmetricDifference symmetric difference} of {@link NavigableSet}s containing the same element type, * thereby providing the equivalent of traditional database joins. */ @ThreadSafe public class Transaction { private static final int MAX_GENERATED_KEY_ATTEMPTS = Integer.parseInt(System.getProperty(Transaction.class.getName() + ".MAX_GENERATED_KEY_ATTEMPTS", "64")); private static final int MAX_OBJ_INFO_CACHE_ENTRIES = Integer.parseInt(System.getProperty(Transaction.class.getName() + ".MAX_OBJ_INFO_CACHE_ENTRIES", "1000")); protected final Logger log = LoggerFactory.getLogger(this.getClass()); // Meta-data final Database db; final KVTransaction kvt; final Schemas schemas; final Schema schema; // TX state @GuardedBy("this") boolean stale; @GuardedBy("this") boolean ending; @GuardedBy("this") boolean rollbackOnly; @GuardedBy("this") boolean disableListenerNotifications; // Listeners @GuardedBy("this") private Set<VersionChangeListener> versionChangeListeners; @GuardedBy("this") private Set<CreateListener> createListeners; @GuardedBy("this") private Set<DeleteListener> deleteListeners; @GuardedBy("this") private NavigableMap<Integer, Set<FieldMonitor>> monitorMap; // key is field's storage ID @GuardedBy("this") private NavigableSet<Long> hasFieldMonitorCache; // optimization for hasFieldMonitor() @GuardedBy("this") private boolean listenerSetInstalled; // Callbacks @GuardedBy("this") private LinkedHashSet<Callback> callbacks; // Misc @GuardedBy("this") private final ThreadLocal<TreeMap<Integer, ArrayList<FieldChangeNotifier<?>>>> pendingNotifications = new ThreadLocal<>(); @GuardedBy("this") private final ObjIdMap<ObjInfo> objInfoCache = new ObjIdMap<>(); @GuardedBy("this") private Object userObject; // Recording of deleted assignments used during a copy() operation (otherwise should be null) private ObjIdMap<ReferenceField> deletedAssignments; private ObjIdMap<ObjId> copyIdMap; // Constructors Transaction(Database db, KVTransaction kvt, Schemas schemas) { this(db, kvt, schemas, schemas.versions.lastKey()); } Transaction(Database db, KVTransaction kvt, Schemas schemas, int versionNumber) { this(db, kvt, schemas, schemas.getVersion(versionNumber)); } Transaction(Database db, KVTransaction kvt, Schemas schemas, Schema schema) { assert db != null; assert kvt != null; assert schemas != null; assert schema != null; assert schema == schemas.getVersion(schema.versionNumber); this.db = db; this.kvt = kvt; this.schemas = schemas; this.schema = schema; } // Transaction Meta-Data /** * Get the database with which this transaction is associated. * * @return associated database */ public Database getDatabase() { return this.db; } /** * Get the database schema versions known to this transaction. * This reflects all schema versions currently recorded in the database. * * @return associated schemas */ public Schemas getSchemas() { return this.schemas; } /** * Get the database schema version associated with this transaction. * This is the schema version used for newly created objects, and the target schema version when * {@linkplain #updateSchemaVersion upgrading} objects. * * @return associated schema */ public Schema getSchema() { return this.schema; } /** * Delete a schema version that is no longer being used. There must be no objects with the given version * in the database, and {@code version} must not be the version being used by this transaction. * * @param version schema version to remove * @return true if schema version was found and removed, false if schema version does not exist in database * @throws InvalidSchemaException if one or more objects with schema version {@code version} still exist * @throws InvalidSchemaException if {@code version} is equal to this transaction's version * @throws IllegalArgumentException if {@code version} is zero or negative * @throws StaleTransactionException if this transaction is no longer usable */ public synchronized boolean deleteSchemaVersion(int version) { // Sanity check Preconditions.checkArgument(version > 0, "invalid non-positive schema version"); Preconditions.checkArgument(version != this.schema.getVersionNumber(), "version is this transaction's version"); if (this.stale) throw new StaleTransactionException(this); if (this.queryVersion().asMap().containsKey(version)) throw new InvalidSchemaException("one or more version " + version + " objects still exist in database"); // Delete schema version if (!this.schemas.deleteVersion(version)) return false; this.kvt.remove(Layout.getSchemaKey(version)); return true; } /** * Get the underlying key/value store transaction. * * <p> * <b>Warning:</b> making changes to the key/value store directly is not supported. If any changes * are made, all future behavior is undefined. * * @return the associated key/value transaction */ public KVTransaction getKVTransaction() { return this.kvt; } // Transaction Lifecycle /** * Commit this transaction. * * @throws StaleTransactionException if this transaction is no longer usable * @throws io.permazen.kv.RetryTransactionException from {@link KVTransaction#commit KVTransaction.commit()} * @throws RollbackOnlyTransactionException if this instance has been {@linkplain #setRollbackOnly marked} rollback only; * this instance will be automatically rolled back */ public synchronized void commit() { // Sanity check if (this.stale) throw new StaleTransactionException(this); if (this.ending) throw new StaleTransactionException(this, "commit() invoked re-entrantly from commit callback"); // Rollback only? if (this.rollbackOnly) { this.log.debug("commit() invoked on transaction " + this + " marked rollback-only, rolling back"); this.rollback(); throw new RollbackOnlyTransactionException(this); } this.ending = true; // Do beforeCommit() and beforeCompletion() callbacks if (this.log.isTraceEnabled()) this.log.trace("commit() invoked on" + (this.isReadOnly() ? " read-only" : "") + " transaction " + this); Callback failedCallback = null; try { if (this.callbacks != null) { for (Callback callback : this.callbacks) { failedCallback = callback; if (this.log.isTraceEnabled()) this.log.trace("commit() invoking beforeCommit() on transaction " + this + " callback " + callback); callback.beforeCommit(this.isReadOnly()); } failedCallback = null; } } finally { // TX operations no longer permitted this.stale = true; // Log the offending callback, if any if (failedCallback != null) { this.log.warn("error invoking beforeCommit() method on transaction " + this + " callback " + failedCallback + ", rolling back"); } // Do before completion callback this.triggerBeforeCompletion(); if (failedCallback != null) { try { try { this.kvt.rollback(); } catch (KVTransactionException e) { // ignore } } finally { this.triggerAfterCompletion(false); } } } // Commit KVTransaction and trigger after completion callbacks try { this.kvt.commit(); if (this.callbacks != null) { for (Callback callback : this.callbacks) { failedCallback = callback; if (this.log.isTraceEnabled()) this.log.trace("commit() invoking afterCommit() on transaction " + this + " callback " + callback); callback.afterCommit(); } failedCallback = null; } } finally { // Log the offending callback, if any if (failedCallback != null) this.log.warn("error invoking afterCommit() method on transaction " + this + " callback " + failedCallback); // Do after completion callback this.triggerAfterCompletion(true); } } /** * Roll back this transaction. * * <p> * This method may be invoked at any time, even after a previous invocation of * {@link #commit} or {@link #rollback}, in which case the invocation will be ignored. */ public synchronized void rollback() { // Sanity check if (this.stale) return; if (this.ending) { this.log.warn("rollback() invoked re-entrantly from commit callback (ignoring)"); return; } this.ending = true; if (this.log.isTraceEnabled()) this.log.trace("rollback() invoked on" + (this.isReadOnly() ? " read-only" : "") + " transaction " + this); // Do before completion callbacks try { this.triggerBeforeCompletion(); } finally { this.stale = true; } // Roll back KVTransaction and trigger after completion callbacks try { this.kvt.rollback(); } finally { this.triggerAfterCompletion(false); } } private /*synchronized*/ void triggerBeforeCompletion() { assert Thread.holdsLock(this); if (this.callbacks == null) return; for (Callback callback : this.callbacks) { if (this.log.isTraceEnabled()) this.log.trace("invoking beforeCompletion() on transaction " + this + " callback " + callback); try { callback.beforeCompletion(); } catch (Throwable t) { this.log.error("error from beforeCompletion() method of transaction " + this + " callback " + callback + " (ignoring)", t); } } } private /*synchronized*/ void triggerAfterCompletion(boolean committed) { assert Thread.holdsLock(this); if (this.callbacks == null) return; for (Callback callback : this.callbacks) { if (this.log.isTraceEnabled()) this.log.trace("invoking afterCompletion() on transaction " + this + " callback " + callback); try { callback.afterCompletion(committed); } catch (Throwable t) { this.log.error("error from afterCompletion() method of transaction " + this + " callback " + callback + " (ignoring)", t); } } } /** * Determine whether this transaction is still valid. If not, all other methods in this class * will throw {@link StaleTransactionException}. * * @return true if this instance is still usable */ public synchronized boolean isValid() { return !this.stale; } /** * Determine whether this transaction is read-only. * * <p> * This method just invokes {@link KVTransaction#isReadOnly} on the wrapped key/value transaction. * * @return true if this instance is read-only * @throws StaleTransactionException if this transaction is no longer usable */ public synchronized boolean isReadOnly() { if (this.stale) throw new StaleTransactionException(this); return this.kvt.isReadOnly(); } /** * Enable or disable read-only mode. * * <p> * Read-only transactions allow mutations, but all changes are discarded on {@link #commit}. * Registered {@link Callback}s are still processed normally. * * <p> * This method just invokes {@link KVTransaction#setReadOnly} on the wrapped key/value transaction. * * @param readOnly read-only setting * @throws StaleTransactionException if this transaction is no longer usable */ public synchronized void setReadOnly(boolean readOnly) { if (this.stale) throw new StaleTransactionException(this); this.kvt.setReadOnly(readOnly); } /** * Determine whether this transaction is marked rollback only. * * @return true if this instance is marked for rollback only */ public synchronized boolean isRollbackOnly() { return this.rollbackOnly; } /** * Mark this transaction for rollback only. A subsequent attempt to {@link #commit} will throw an exception. */ public synchronized void setRollbackOnly() { this.rollbackOnly = true; } /** * Change the timeout for this transaction from its default value (optional operation). * * @param timeout transaction timeout in milliseconds, or zero for unlimited * @throws UnsupportedOperationException if this transaction does not support timeouts * @throws IllegalArgumentException if {@code timeout} is negative * @throws StaleTransactionException if this transaction is no longer usable */ public synchronized void setTimeout(long timeout) { if (this.stale) throw new StaleTransactionException(this); this.kvt.setTimeout(timeout); } /** * Register a transaction {@link Callback} to be invoked when this transaction completes. * Callbacks will be invoked in the order they are registered, but <i>duplicate registrations are ignored</i>. * * <p> * Note: if you are using Spring for transaction demarcation (via {@link io.permazen.spring.PermazenTransactionManager}), * then you may also use Spring's * {@link org.springframework.transaction.support.TransactionSynchronizationManager#registerSynchronization * TransactionSynchronizationManager.registerSynchronization()} instead of this method. * * @param callback callback to invoke * @throws IllegalArgumentException if {@code callback} is null * @throws StaleTransactionException if this transaction is no longer usable */ public synchronized void addCallback(Callback callback) { Preconditions.checkArgument(callback != null, "null callback"); if (this.stale || this.ending) throw new StaleTransactionException(this); if (this.callbacks == null) this.callbacks = new LinkedHashSet<>(); this.callbacks.add(callback); } /** * Create an empty, in-memory "snapshot" transaction. * * <p> * The snapshot transaction will be initialized with the same schema meta-data as this instance but will be otherwise empty * (i.e., contain no objects). It can be used as a destination for "snapshot" copies of objects made via {@link #copy copy()}. * * <p> * The returned {@link SnapshotTransaction} does not support {@link #commit}, {@link #rollback}, * or {@link #addCallback addCallback()}, and can be used indefinitely after this transaction closes. * * @return empty in-memory snapshot transaction with compatible schema information * @see Database#createSnapshotTransaction Database.createSnapshotTransaction() */ public SnapshotTransaction createSnapshotTransaction() { final NavigableMapKVStore kvstore = new NavigableMapKVStore(); Layout.copyMetaData(this.kvt, kvstore); return new SnapshotTransaction(this.db, kvstore, this.schemas, this.schema); } /** * Determine whether this instance is a {@link SnapshotTransaction}. * * @return true if this instance is a {@link SnapshotTransaction}, otherwise false */ public boolean isSnapshot() { return false; } // Object Lifecycle /** * Create a new object with the given object ID, if it doesn't already exist. If it does exist, nothing happens. * * <p> * If the object doesn't already exist, all fields are set to their default values and the object's * schema version is set to {@linkplain #getSchema() the version associated with this transaction}. * * @param id object ID * @return true if the object did not exist and was created, false if the object already existed * @throws UnknownTypeException if {@code id} does not correspond to a known object type in this transaction's schema version * @throws IllegalArgumentException if {@code id} is null * @throws StaleTransactionException if this transaction is no longer usable */ public boolean create(ObjId id) { return this.create(id, this.schema.versionNumber); } /** * Create a new object with the given object ID, if it doesn't already exist. If it does exist, nothing happens. * * <p> * If the object doesn't already exist, all fields are set to their default values and the object's * schema version is set to the specified version. * * @param id object ID * @param versionNumber schema version number to use for newly created object * @return true if the object did not exist and was created, false if the object already existed * @throws UnknownTypeException if {@code id} does not correspond to a known object type in the specified schema version * @throws IllegalArgumentException if {@code id} is null * @throws IllegalArgumentException if {@code versionNumber} is invalid or unknown * @throws StaleTransactionException if this transaction is no longer usable */ public synchronized boolean create(ObjId id, int versionNumber) { // Sanity check Preconditions.checkArgument(id != null, "null id"); if (this.stale) throw new StaleTransactionException(this); // Does object already exist? if (this.exists(id)) return false; // Initialize object final Schema objSchema = versionNumber == this.schema.versionNumber ? this.schema : this.schemas.getVersion(versionNumber); final ObjType objType = objSchema.getObjType(id.getStorageId()); this.createObjectData(id, versionNumber, objSchema, objType); // Done return true; } /** * Create a new object with a randomly assigned object ID and having the given type. * * <p> * All fields will be set to their default values. * The object's schema version will be set to {@linkplain #getSchema() the version associated with this transaction}. * * @param storageId object type storage ID * @return object id of newly created object * @throws UnknownTypeException if {@code storageId} does not correspond to a known object type in this transaction's schema * @throws StaleTransactionException if this transaction is no longer usable */ public ObjId create(int storageId) { return this.create(storageId, this.schema.versionNumber); } /** * Create a new object with a randomly assigned object ID and having the given type and schema version. * * <p> * All fields will be set to their default values. * The object's schema version will be set to the specified version. * * @param storageId object type storage ID * @param versionNumber schema version number to use for newly created object * @return object id of newly created object * @throws UnknownTypeException if {@code storageId} does not correspond to a known object type in the specified schema version * @throws IllegalArgumentException if {@code versionNumber} is invalid or unknown * @throws StaleTransactionException if this transaction is no longer usable */ public synchronized ObjId create(int storageId, int versionNumber) { // Sanity check if (this.stale) throw new StaleTransactionException(this); final Schema objSchema = versionNumber == this.schema.versionNumber ? this.schema : this.schemas.getVersion(versionNumber); final ObjType objType = objSchema.getObjType(storageId); // Generate object ID final ObjId id = this.generateIdValidated(storageId); // Initialize object this.createObjectData(id, versionNumber, objSchema, objType); // Done return id; } /** * Generate a random, unused {@link ObjId} for the given storage ID. * * @param storageId object type storage ID * @return random unassigned object id * @throws UnknownTypeException if {@code storageId} does not correspond to any known object type * @throws StaleTransactionException if this transaction is no longer usable */ public synchronized ObjId generateId(int storageId) { // Sanity check if (this.stale) throw new StaleTransactionException(this); final ObjTypeStorageInfo info = this.schemas.verifyStorageInfo(storageId, ObjTypeStorageInfo.class); // Generate ID return this.generateIdValidated(info.storageId); } private /*synchronized*/ ObjId generateIdValidated(int storageId) { assert Thread.holdsLock(this); // Create a new, unique key final ByteWriter keyWriter = new ByteWriter(); for (int attempts = 0; attempts < MAX_GENERATED_KEY_ATTEMPTS; attempts++) { final ObjId id = new ObjId(storageId); id.writeTo(keyWriter); if (this.kvt.get(keyWriter.getBytes()) == null) return id; keyWriter.reset(0); } // Give up throw new DatabaseException("could not find a new, unused object ID after " + MAX_GENERATED_KEY_ATTEMPTS + " attempts; is our source of randomness truly random?"); } /** * Initialize key/value pairs for a new object. The object must not already exist. */ private synchronized void createObjectData(ObjId id, int versionNumber, Schema schema, ObjType objType) { // Sanity check if (this.stale) throw new StaleTransactionException(this); assert this.kvt.get(id.getBytes()) == null; assert this.objInfoCache.get(id) == null; // Write object meta-data and update object info cache ObjInfo.write(this, id, versionNumber, false); if (this.objInfoCache.size() >= MAX_OBJ_INFO_CACHE_ENTRIES) this.objInfoCache.removeOne(); this.objInfoCache.put(id, new ObjInfo(this, id, versionNumber, false, schema, objType)); // Write object version index entry this.kvt.put(Layout.buildVersionIndexKey(id, objType.schema.versionNumber), ByteUtil.EMPTY); // Initialize counters to zero if (!objType.counterFields.isEmpty()) { for (CounterField field : objType.counterFields.values()) this.kvt.put(field.buildKey(id), this.kvt.encodeCounter(0)); } // Write simple field index entries objType.indexedSimpleFields .forEach(field -> this.kvt.put(Transaction.buildSimpleIndexEntry(field, id, null), ByteUtil.EMPTY)); // Write composite index entries for (CompositeIndex index : objType.compositeIndexes.values()) this.kvt.put(Transaction.buildDefaultCompositeIndexEntry(id, index), ByteUtil.EMPTY); // Notify listeners if (!this.disableListenerNotifications && this.createListeners != null) { for (CreateListener listener : this.createListeners.toArray(new CreateListener[this.createListeners.size()])) listener.onCreate(this, id); } } /** * Delete an object. Does nothing if object does not exist (e.g., has already been deleted). * * <p> * This method does <i>not</i> change the object's schema version if it has a different version that this transaction. * * <p><b>Secondary Deletions</b></p> * * <p> * Deleting an object can trigger additional secondary deletions. Specifically, * (a) if the object contains reference fields with {@linkplain ReferenceField#cascadeDelete delete cascade} enabled, * any objects referred to through those fields will also be deleted, and (b) if the object is referred to by any other objects * through fields configured for {@link DeleteAction#DELETE}, those referring objects will be deleted. * * <p> * In any case, deletions occur one at a time, and only when an object is actually deleted are any associated secondary * deletions added to an internal deletion queue. However, the order in which objects on this deletion queue are * processed is unspecified. For an example of where this ordering matters, consider an object {@code A} referring to objects * {@code B} and {@code C} with delete cascading references, where B also refers to C with a {@link DeleteAction#EXCEPTION} * reference. Then if {@code A} is deleted, it's indeterminate whether a {@link ReferencedObjectException} will be thrown, * as that depends on whether {@code B} or {@code C} is deleted first (with the answer being, respectively, no and yes). * * @param id object ID of the object to delete * @return true if object was found and deleted, false if object was not found, * or if {@code id} specifies an unknown object type * @throws ReferencedObjectException if the object is referenced by some other object * through a reference field configured for {@link DeleteAction#EXCEPTION} * @throws IllegalArgumentException if {@code id} is null * @throws StaleTransactionException if this transaction is no longer usable */ public synchronized boolean delete(ObjId id) { // Sanity check Preconditions.checkArgument(id != null, "null id"); if (this.stale) throw new StaleTransactionException(this); // Does object exist? if (!this.exists(id)) return false; // Handle delete cascade and recurive DeleteAction.DELETE without hogging Java stack final ObjIdSet deletables = new ObjIdSet(); deletables.add(id); boolean found = false; while (!deletables.isEmpty()) found |= this.doDelete(deletables.iterator().next(), deletables); // Done return found; } private synchronized boolean doDelete(final ObjId id, ObjIdSet deletables) { // Loop here to handle any mutations within delete notification listener callbacks ObjInfo info; while (true) { // Get object info try { info = this.getObjectInfo(id, false); } catch (DeletedObjectException e) { // possibly due to a cycle of DeleteAction.DELETE references deletables.remove(id); return false; } catch (UnknownTypeException e) { throw new InconsistentDatabaseException("encountered reference with unknown type during delete cascade: " + id, e); } // Determine if any EXCEPTION reference fields refer to the object (from some other object); if so, throw exception for (Map.Entry<Integer, NavigableSet<ObjId>> entry : this.findReferrers(id, DeleteAction.EXCEPTION).entrySet()) { for (ObjId referrer : entry.getValue()) { if (!referrer.equals(id)) throw new ReferencedObjectException(this, id, referrer, entry.getKey()); } } // Do we need to issue delete notifications for the object being deleted? if (info.isDeleteNotified() || this.deleteListeners == null || this.deleteListeners.isEmpty()) break; // Set "delete notified" flag and update object info cache ObjInfo.write(this, id, info.getVersion(), true); this.objInfoCache.put(id, new ObjInfo(this, id, info.getVersion(), true, info.schema, info.objType)); // Issue delete notifications and retry if (!this.disableListenerNotifications && this.deleteListeners != null) { for (DeleteListener listener : this.deleteListeners.toArray(new DeleteListener[this.deleteListeners.size()])) listener.onDelete(this, id); } } // Find all objects referred to by a reference field with cascadeDelete = true and add them to deletables for (ReferenceField field : info.getObjType().referenceFieldsAndSubFields.values()) { if (!field.cascadeDelete) continue; final Iterable<ObjId> refs = field.parent != null ? field.parent.iterateSubField(this, id, field) : Collections.singleton(field.getValue(this, id)); for (ObjId ref : refs) { if (ref != null) deletables.add(ref); } } // Actually delete the object this.deleteObjectData(info); deletables.remove(id); // Find all UNREFERENCE references and unreference them for (Map.Entry<Integer, NavigableSet<ObjId>> entry : this.findReferrers(id, DeleteAction.UNREFERENCE).entrySet()) { final int storageId = entry.getKey(); final NavigableSet<ObjId> referrers = entry.getValue(); final SimpleFieldStorageInfo<?> fieldInfo = this.schemas.verifyStorageInfo(storageId, SimpleFieldStorageInfo.class); fieldInfo.unreferenceAll(this, id, referrers); } // Find all DELETE references and mark the containing object for deletion (caller will call us back to actually delete) this.findReferrers(id, DeleteAction.DELETE).values().forEach(deletables::addAll); // Done return true; } /** * Delete all of an object's data. The object must exist. * * <p> * This is the opposite of {@link #createObjectData}. */ private void deleteObjectData(ObjInfo info) { // Sanity check assert Thread.holdsLock(this); assert this.kvt.get(info.getId().getBytes()) != null; // Delete object's simple field index entries final ObjId id = info.getId(); final ObjType type = info.getObjType(); type.indexedSimpleFields .forEach(field -> this.kvt.remove(Transaction.buildSimpleIndexEntry(field, id, this.kvt.get(field.buildKey(id))))); // Delete object's composite index entries for (CompositeIndex index : type.compositeIndexes.values()) this.kvt.remove(this.buildCompositeIndexEntry(id, index)); // Delete object's complex field index entries for (ComplexField<?> field : type.complexFields.values()) field.removeIndexEntries(this, id); // Delete object meta-data and all field content final byte[] minKey = info.getId().getBytes(); final byte[] maxKey = ByteUtil.getKeyAfterPrefix(minKey); this.kvt.removeRange(minKey, maxKey); // Delete object schema version entry this.kvt.remove(Layout.buildVersionIndexKey(id, info.getVersion())); // Update ObjInfo cache this.objInfoCache.remove(id); } /** * Determine if an object exists. * * <p> * This method does <i>not</i> change the object's schema version if it exists * and has a different version that this transaction. * * @param id object ID of the object to find * @return true if object was found, false if object was not found, or if {@code id} specifies an unknown object type * @throws StaleTransactionException if this transaction is no longer usable * @throws IllegalArgumentException if {@code id} is null */ public synchronized boolean exists(ObjId id) { return this.getObjectInfoIfExists(id, false) != null; } /** * Copy an object into a (possibly different) transaction. * * <p> * This copies the object, including all of its field data, to {@code dest}. If the object already exists in {@code dest}, * the existing copy is completely replaced. * * <p> * Only the object itself is copied; any other objects it references are not copied. If the target object does not exist * in {@code dest}, it will be created first (and {@link CreateListener}s notified); otherwise, first the target object's * schema version will be upgraded if necessary to match {@code source} (and {@link VersionChangeListener}s notified). * Finally, as fields are copied, non-trivial changes to the target object's fields generate change listener notifications. * * <p> * If {@code updateVersion} is true, the {@code source} object is first upgraded to * {@linkplain #getSchema() the schema version associated with this transaction}. * In any case, the schema version associated with {@code source}, when copied, must be identical * in this transaction and {@code dest}. * * <p><b>Disabling Notifications</b></p> * * <p> * The {@code notifyListeners} flag controls whether notifications are delivered to {@link CreateListener}s * and field change listeners as objects are created and modified in {@code dest}. {@link VersionChangeListener}s * are always notified. * * <p><b>Deleted Assignments Handling</b></p> * * <p> * If a reference field configured to {@linkplain ReferenceField#isAllowDeleted disallow deleted assignments} is copied, * but the referenced object does not exist in {@code dest}, then a {@link DeletedObjectException} is thrown and no copy * is performed. However, this can present an impossible chicken-and-egg situation when multiple objects need to be copied * and there are cycles in the graph of references between objects. * * <p> * If {@code deletedAssignments} is non-null, then instead of triggering an exception, illegal references to deleted objects * are collected in {@code deletedAssignments}, which maps each deleted object to (some) referring field in the copied * object. This lets the caller to decide what to do about them. * * <p><b>Object ID Remapping</b></p> * * <p> * The optional {@code objectIdMap} parameter specifies how object ID's should be remapped as fields are copied into * {@code dest}. This remapping applies to all {@linkplain ReferenceField reference fields}, and also applies to * {@code source} itself, i.e., the target object ID may be different from {@code source}. * * <p><b>Return Value</b></p> * * <p> * If {@code dest} is this instance, and the {@code source} is not remapped (see below), no fields are changed and false is * returned; however, a schema update may still occur (if {@code updateVersion} is true), and deleted assignment checks are * applied. * * <p><b>Deadlocks</b></p> * * <p> * Note: if two threads attempt to copy objects between the same two transactions at the same time but in opposite directions, * deadlock could result. * * @param source object ID of the source object in this transaction * @param dest destination for the copy of {@code source} (possibly this transaction) * @param updateVersion true to automatically update {@code source}'s schema version prior to the copy, false to not change it * @param notifyListeners whether to notify {@link CreateListener}s and field change listeners * @param deletedAssignments if not null, collect assignments to deleted objects here instead of throwing * {@link DeletedObjectException}s, where the map key is the deleted object and the map value is some referring field * @param objectIdMap if not null, a remapping of object ID's in this transaction to object ID's in {@code dest} * @return false if the target object already existed in {@code dest}, true if it was newly created * @throws DeletedObjectException if no object with ID equal to {@code source} exists in this transaction * @throws DeletedObjectException if {@code deletedAssignments} is null, and a non-null reference field in {@code source} * that disallows deleted assignments contains a reference to an object that does not exist in {@code dest} * @throws UnknownTypeException if {@code source} or an ID in {@code objectIdMap} specifies an unknown object type * @throws IllegalArgumentException if {@code objectIdMap} maps an object ID to null * @throws IllegalArgumentException if {@code objectIdMap} maps {@code source} to a different object type * @throws IllegalArgumentException if {@code objectIdMap} maps the value of a reference field to an incompatible object type * @throws IllegalArgumentException if any parameter is null * @throws StaleTransactionException if this transaction or {@code dest} is no longer usable * @throws SchemaMismatchException if the schema version associated with {@code source} differs between * this transaction and {@code dest} * @throws TypeNotInSchemaVersionException {@code updateVersion} is true and the object could not be updated because * the object's type does not exist in the schema version associated with this transaction */ public synchronized boolean copy(ObjId source, final Transaction dest, final boolean updateVersion, final boolean notifyListeners, final ObjIdMap<ReferenceField> deletedAssignments, final ObjIdMap<ObjId> objectIdMap) { // Sanity check Preconditions.checkArgument(source != null, "null source"); Preconditions.checkArgument(dest != null, "null dest"); if (this.stale) throw new StaleTransactionException(this); // Get source object info final ObjInfo srcInfo = this.getObjectInfo(source, updateVersion); // Do the copy while both transactions are locked synchronized (dest) { // Sanity check if (dest.stale) throw new StaleTransactionException(dest); // Copy fields return dest.mutateAndNotify(() -> { final ObjIdMap<ObjId> previousCopyIdMap = dest.copyIdMap; dest.copyIdMap = objectIdMap; final ObjIdMap<ReferenceField> previousCopyDeletedAssignments = dest.deletedAssignments; dest.deletedAssignments = deletedAssignments; final boolean previousDisableListenerNotifications = dest.disableListenerNotifications; dest.disableListenerNotifications = !notifyListeners; try { return Transaction.doCopyFields(srcInfo, Transaction.this, dest, updateVersion); } finally { dest.copyIdMap = previousCopyIdMap; dest.deletedAssignments = previousCopyDeletedAssignments; dest.disableListenerNotifications = previousDisableListenerNotifications; } }); } } // This method assumes both transactions are locked private static boolean doCopyFields(ObjInfo srcInfo, Transaction srcTx, Transaction dstTx, boolean updateVersion) { // Sanity check assert Thread.holdsLock(srcTx); assert Thread.holdsLock(dstTx); // Get destination object ID and verify it is sensible final ObjId srcId = srcInfo.getId(); final ObjId dstId = dstTx.copyIdMap != null && dstTx.copyIdMap.containsKey(srcId) ? dstTx.copyIdMap.get(srcId) : srcId; if (dstId == null) throw new IllegalArgumentException("can't copy " + srcId + " because " + srcId + " is remapped to null"); final int typeStorageId = srcId.getStorageId(); if (dstId.getStorageId() != typeStorageId) { throw new IllegalArgumentException("can't copy " + srcId + " to " + dstId + " due to non-equal storage ID's (" + typeStorageId + " != " + dstId.getStorageId() + ")"); } // Upgrade source object if necessary if (updateVersion && srcInfo.getVersion() != srcTx.schema.versionNumber) { srcTx.changeVersion(srcInfo, srcTx.schema); srcInfo = srcTx.loadIntoCache(srcId); } final Schema srcSchema = srcInfo.getSchema(); // Find and verify the expected schema version in the destination transaction final int objectVersion = srcSchema.versionNumber; final Schema dstSchema; try { dstSchema = dstTx.schemas.getVersion(objectVersion); } catch (IllegalArgumentException e) { throw new SchemaMismatchException("destination transaction has no schema version " + objectVersion); } if (!Arrays.equals(srcSchema.encodedXML, dstSchema.encodedXML) && !srcSchema.schemaModel.isCompatibleWith(dstSchema.schemaModel)) { throw new SchemaMismatchException("destination transaction schema version " + objectVersion + " does not match source schema version " + objectVersion + "\n" + dstSchema.schemaModel.differencesFrom(srcSchema.schemaModel)); } // Determine if destination object already exists, and if so get info about it ObjInfo dstInfo = dstTx.getObjectInfoIfExists(dstId, false); final boolean existed = dstInfo != null; // If destination object already exists and has upgrade listeners, go through the normal upgrade process first if (existed && dstInfo.getVersion() != objectVersion && dstTx.versionChangeListeners != null && !dstTx.versionChangeListeners.isEmpty()) { dstTx.changeVersion(dstInfo, dstSchema); dstInfo = dstTx.loadIntoCache(dstId); } // Do field-by-field copy if there are change listeners or remapping, otherwise do fast copy of key/value pairs directly final ObjType srcType = srcSchema.getObjType(typeStorageId); final ObjType dstType = dstSchema.getObjType(typeStorageId); if (dstTx.copyIdMap != null || (!dstTx.disableListenerNotifications && dstTx.hasFieldMonitor(dstType))) { // Create destination object if it does not exist if (!existed) dstTx.createObjectData(dstId, objectVersion, dstSchema, dstType); // Copy fields for (Field<?> field : srcType.fields.values()) field.copy(srcId, dstId, srcTx, dstTx, dstTx.copyIdMap); } else { assert srcType.schema.versionNumber == dstType.schema.versionNumber; // Check for any deleted reference assignments for (ReferenceField field : dstType.referenceFieldsAndSubFields.values()) field.findAnyDeletedAssignments(srcTx, dstTx, dstId); // We can short circuit here if source and target are the same object in the same transaction if (srcId.equals(dstId) && srcTx.equals(dstTx)) return !existed; // Nuke previous destination object, if any if (dstInfo != null) dstTx.deleteObjectData(dstInfo); // Add schema version index entry dstTx.kvt.put(Layout.buildVersionIndexKey(dstId, objectVersion), ByteUtil.EMPTY); // Copy object meta-data and all field content in one key range sweep final KeyRange srcKeyRange = KeyRange.forPrefix(srcId.getBytes()); final ByteWriter dstWriter = new ByteWriter(); dstWriter.write(dstId.getBytes()); final int dstMark = dstWriter.mark(); try (CloseableIterator<KVPair> i = srcTx.kvt.getRange(srcKeyRange)) { while (i.hasNext()) { final KVPair kv = i.next(); assert srcKeyRange.contains(kv.getKey()); final ByteReader srcReader = new ByteReader(kv.getKey()); srcReader.skip(ObjId.NUM_BYTES); dstWriter.reset(dstMark); dstWriter.write(srcReader); dstTx.kvt.put(dstWriter.getBytes(), kv.getValue()); } } // Create object's simple field index entries dstType.indexedSimpleFields .forEach(field -> { final byte[] fieldValue = dstTx.kvt.get(field.buildKey(dstId)); // can be null (if field has default value) final byte[] indexKey = Transaction.buildSimpleIndexEntry(field, dstId, fieldValue); dstTx.kvt.put(indexKey, ByteUtil.EMPTY); }); // Create object's composite index entries for (CompositeIndex index : dstType.compositeIndexes.values()) dstTx.kvt.put(Transaction.buildCompositeIndexEntry(dstTx, dstId, index), ByteUtil.EMPTY); // Create object's complex field index entries for (ComplexField<?> field : dstType.complexFields.values()) { field.getSubFields().stream() .filter(subField -> subField.indexed) .forEach(subField -> field.addIndexEntries(dstTx, dstId, subField)); } } // Done return !existed; } /** * Add a {@link CreateListener} to this transaction. * * @param listener the listener to add * @throws IllegalArgumentException if {@code listener} is null * @throws StaleTransactionException if this transaction is no longer usable * @throws UnsupportedOperationException if {@link #setListeners setListeners()} has been invoked on this instance */ public synchronized void addCreateListener(CreateListener listener) { if (this.stale) throw new StaleTransactionException(this); Preconditions.checkArgument(listener != null, "null listener"); if (this.listenerSetInstalled) throw new UnsupportedOperationException("ListenerSet installed"); if (this.createListeners == null) this.createListeners = new HashSet<>(1); this.createListeners.add(listener); } /** * Remove an {@link CreateListener} from this transaction. * * @param listener the listener to remove * @throws StaleTransactionException if this transaction is no longer usable * @throws IllegalArgumentException if {@code listener} is null * @throws UnsupportedOperationException if {@link #setListeners setListeners()} has been invoked on this instance */ public synchronized void removeCreateListener(CreateListener listener) { if (this.stale) throw new StaleTransactionException(this); Preconditions.checkArgument(listener != null, "null listener"); if (this.listenerSetInstalled) throw new UnsupportedOperationException("ListenerSet installed"); if (this.createListeners == null) return; this.createListeners.remove(listener); } /** * Add a {@link DeleteListener} to this transaction. * * @param listener the listener to add * @throws IllegalArgumentException if {@code listener} is null * @throws StaleTransactionException if this transaction is no longer usable * @throws UnsupportedOperationException if {@link #setListeners setListeners()} has been invoked on this instance */ public synchronized void addDeleteListener(DeleteListener listener) { if (this.stale) throw new StaleTransactionException(this); Preconditions.checkArgument(listener != null, "null listener"); if (this.listenerSetInstalled) throw new UnsupportedOperationException("ListenerSet installed"); if (this.deleteListeners == null) this.deleteListeners = new HashSet<>(1); this.deleteListeners.add(listener); } /** * Remove an {@link DeleteListener} from this transaction. * * @param listener the listener to remove * @throws StaleTransactionException if this transaction is no longer usable * @throws IllegalArgumentException if {@code listener} is null * @throws UnsupportedOperationException if {@link #setListeners setListeners()} has been invoked on this instance */ public synchronized void removeDeleteListener(DeleteListener listener) { if (this.stale) throw new StaleTransactionException(this); Preconditions.checkArgument(listener != null, "null listener"); if (this.listenerSetInstalled) throw new UnsupportedOperationException("ListenerSet installed"); if (this.deleteListeners == null) return; this.deleteListeners.remove(listener); } // Object Versioning /** * Read the current schema version of the given object. Does not change the object's version. * * @param id object id * @return object's current schema version * @throws DeletedObjectException if no object with ID equal to {@code id} is found * @throws UnknownTypeException if {@code id} specifies an unknown object type * @throws StaleTransactionException if this transaction is no longer usable * @throws IllegalArgumentException if {@code id} is null */ public synchronized int getSchemaVersion(ObjId id) { // Sanity check if (this.stale) throw new StaleTransactionException(this); Preconditions.checkArgument(id != null, "null id"); // Get object version return this.getObjectInfo(id, false).getVersion(); } /** * Change the schema version of the specified object, if necessary, so that its version matches * {@linkplain #getSchema() the schema version associated with this transaction}. * * <p> * If a schema change occurs, any registered {@link VersionChangeListener}s will be notified prior * to this method returning. * * @param id object ID of the object to delete * @return true if the object schema version was changed, otherwise false * @throws StaleTransactionException if this transaction is no longer usable * @throws DeletedObjectException if no object with ID equal to {@code id} is found * @throws UnknownTypeException if {@code id} specifies an unknown object type * @throws IllegalArgumentException if {@code id} is null * @throws TypeNotInSchemaVersionException if the object version could not be updated because the object's type * does not exist in the schema version associated with this transaction * @see #getSchemaVersion(ObjId) */ public synchronized boolean updateSchemaVersion(ObjId id) { // Sanity check Preconditions.checkArgument(id != null, "null id"); if (this.stale) throw new StaleTransactionException(this); // Get object info final ObjInfo info = this.getObjectInfo(id, false); if (info.getVersion() == this.schema.versionNumber) return false; // Update schema version this.mutateAndNotify(new Mutation<Void>() { @Override public Void mutate() { Transaction.this.changeVersion(info, Transaction.this.schema); return null; } }); // Done return true; } /** * Migrate object's schema to the version specified and notify listeners. This assumes we are locked. * * @param info original object info * @param targetVersion version to change to */ private void changeVersion(final ObjInfo info, final Schema targetVersion) { // Get version numbers final ObjId id = info.getId(); final int oldVersion = info.getVersion(); final int newVersion = targetVersion.versionNumber; // Sanity check assert Thread.holdsLock(this); assert this.schemas.getVersion(targetVersion.versionNumber) == targetVersion; Preconditions.checkArgument(newVersion != oldVersion, "object already at version"); // Get old and new types final ObjType oldType = info.getObjType(); final ObjType newType; try { newType = targetVersion.getObjType(id.getStorageId()); } catch (UnknownTypeException e) { throw (TypeNotInSchemaVersionException)new TypeNotInSchemaVersionException(id, newVersion).initCause(e); } // Gather removed fields' values here for user migration if any VersionChangeListeners are registered final TreeMap<Integer, Object> oldValueMap = this.versionChangeListeners != null && !this.versionChangeListeners.isEmpty() ? new TreeMap<>() : null; //////// Remove the index entries corresponding to removed composite indexes // Remove index entries for composite indexes that are going away oldType.compositeIndexes.values().stream() .filter(index -> !newType.compositeIndexes.containsKey(index.storageId)) .forEach(index -> this.kvt.remove(this.buildCompositeIndexEntry(id, index))); //////// Determine Field Compatibility // Build a mapping from old field to compatible new field, or null if none final HashMap<Field<?>, Field<?>> compatibleFieldMap = new HashMap<>(oldType.fields.size()); for (Map.Entry<Integer, Field<?>> entry : oldType.fields.entrySet()) { final Integer storageId = entry.getKey(); final Field<?> oldField = entry.getValue(); final Field<?> newField = newType.fields.get(storageId); final boolean compatible = newField != null && newField.isUpgradeCompatible(oldField); compatibleFieldMap.put(oldField, compatible ? newField : null); } // Build a list of remaining new fields not compatible with some old field final ArrayList<Field<?>> incompatibleNewFields = new ArrayList<>(newType.fields.size()); for (Map.Entry<Integer, Field<?>> entry : newType.fields.entrySet()) { final Integer storageId = entry.getKey(); final Field<?> newField = entry.getValue(); final Field<?> oldField = oldType.fields.get(storageId); if (oldField == null || compatibleFieldMap.get(oldField) == null) incompatibleNewFields.add(newField); else assert compatibleFieldMap.get(oldField) == newField; } //////// Process old fields // Iterate over all the fields that existed in the old schema version for (Map.Entry<Field<?>, Field<?>> entry : compatibleFieldMap.entrySet()) { final Field<?> oldField = entry.getKey(); // Copy the old field's original value for the version change notification, if any if (oldValueMap != null) { oldField.visit(new FieldSwitchAdapter<Void>() { @Override @SuppressWarnings("shadow") public <T> Void caseSimpleField(SimpleField<T> oldField) { final byte[] key = Field.buildKey(id, oldField.storageId); final byte[] oldValue = Transaction.this.kvt.get(key); oldValueMap.put(oldField.storageId, oldValue != null ? oldField.fieldType.read(new ByteReader(oldValue)) : oldField.fieldType.getDefaultValueObject()); return null; } @Override @SuppressWarnings("shadow") public <T> Void caseComplexField(ComplexField<T> oldField) { oldValueMap.put(oldField.storageId, oldField.getValueReadOnlyCopy(Transaction.this, id)); return null; } @Override @SuppressWarnings("shadow") public Void caseCounterField(CounterField oldField) { final byte[] key = Field.buildKey(id, oldField.storageId); final byte[] oldValue = Transaction.this.kvt.get(key); oldValueMap.put(oldField.storageId, oldValue != null ? Transaction.this.kvt.decodeCounter(oldValue) : 0L); return null; } }); } // Reset the field's value and add/remove index entries as needed oldField.visit(new FieldSwitchAdapter<Void>() { @Override @SuppressWarnings("shadow") public Void caseReferenceField(ReferenceField oldField) { // We must reset a reference to an object type that is no longer allowed by the new reference field final ReferenceField newField = (ReferenceField)entry.getValue(); if (newField != null) { final SortedSet<Integer> xtypes = Transaction.this.findRemovedTypes(oldField, newField); if (!xtypes.isEmpty()) { final ObjId ref = oldField.getValue(Transaction.this, id); if (ref != null && xtypes.contains(ref.getStorageId())) { // Change new field to be incompatible, so it will get reset entry.setValue(null); incompatibleNewFields.add(newField); } } } // Proceed return this.caseSimpleField(oldField); } @Override @SuppressWarnings("shadow") public <T> Void caseSimpleField(SimpleField<T> oldField) { // Reset field? final SimpleField<?> newField = (SimpleField<?>)entry.getValue(); final boolean reset = newField == null; // Add/remove indexes as needed final byte[] key = Field.buildKey(id, oldField.storageId); if (oldField.indexed && (reset || !newField.indexed)) { final byte[] value = Transaction.this.kvt.get(key); Transaction.this.kvt.remove(Transaction.buildSimpleIndexEntry(oldField, id, value)); } if (newField != null && newField.indexed && (reset || !oldField.indexed)) { final byte[] value = !reset ? Transaction.this.kvt.get(key) : null; Transaction.this.kvt.put(Transaction.buildSimpleIndexEntry(newField, id, value), ByteUtil.EMPTY); } // Reset field value if needed if (reset) Transaction.this.kvt.remove(key); return null; } @Override @SuppressWarnings("shadow") public <E> Void caseComplexField(ComplexField<E> oldField) { // Reset field? final ComplexField<?> newField = (ComplexField<?>)entry.getValue(); final boolean reset = newField == null; // Add/remove index entries as needed final List<? extends SimpleField<?>> oldSubFields = oldField.getSubFields(); final List<? extends SimpleField<?>> newSubFields = !reset ? newField.getSubFields() : null; for (int i = 0; i < oldSubFields.size(); i++) { final SimpleField<?> oldSubField = oldSubFields.get(i); final SimpleField<?> newSubField = !reset ? newSubFields.get(i) : null; // We must also reset references to object types that are no longer allowed by the new reference field if (!reset && oldSubField instanceof ReferenceField) { final ReferenceField oldRefField = (ReferenceField)oldSubField; final ReferenceField newRefField = (ReferenceField)newSubField; final SortedSet<Integer> xtypes = Transaction.this.findRemovedTypes(oldRefField, newRefField); if (!xtypes.isEmpty()) oldField.unreferenceRemovedTypes(Transaction.this, id, oldRefField, xtypes); } // Add/remove sub-field indexes if (oldSubField.indexed && (reset || !newSubField.indexed)) oldField.removeIndexEntries(Transaction.this, id, oldSubField); if (!oldSubField.indexed && !reset && newSubField.indexed) newField.addIndexEntries(Transaction.this, id, newSubField); } // Reset field value if needed. For complex fields, a "reset" is equivalent to removing the field. if (reset) oldField.deleteContent(Transaction.this, id); return null; } @Override @SuppressWarnings("shadow") public Void caseCounterField(CounterField oldField) { // Reset field? final boolean reset = entry.getValue() == null; // Reset field value if needed if (reset) Transaction.this.kvt.remove(Field.buildKey(id, oldField.storageId)); return null; } }); } //////// For fields that are new or were reset, initialize values and add index entries // Iterate over the new fields that are truly new or got reset for (Field<?> newField : incompatibleNewFields) { newField.visit(new FieldSwitchAdapter<Void>() { @Override @SuppressWarnings("shadow") public <T> Void caseSimpleField(SimpleField<T> newField) { if (newField.indexed) Transaction.this.kvt.put(Transaction.buildSimpleIndexEntry(newField, id, null), ByteUtil.EMPTY); return null; } @Override @SuppressWarnings("shadow") public <E> Void caseComplexField(ComplexField<E> newField) { return null; // nothing to do! } @Override @SuppressWarnings("shadow") public Void caseCounterField(CounterField newField) { final byte[] key = Field.buildKey(id, newField.storageId); Transaction.this.kvt.put(key, Transaction.this.kvt.encodeCounter(0L)); return null; } }); } //////// Add composite index entries for newly added composite indexes // Add index entries for composite indexes that are newly added newType.compositeIndexes.values().stream() .filter(index -> !oldType.compositeIndexes.containsKey(index.storageId)) .forEach(index -> this.kvt.put(this.buildCompositeIndexEntry(id, index), ByteUtil.EMPTY)); //////// Update object version and corresponding index entry // Change object version and update object info cache ObjInfo.write(this, id, newVersion, info.isDeleteNotified()); this.objInfoCache.put(id, new ObjInfo(this, id, newVersion, info.isDeleteNotified(), targetVersion, newType)); // Update object version index entry this.kvt.remove(Layout.buildVersionIndexKey(id, oldVersion)); this.kvt.put(Layout.buildVersionIndexKey(id, newVersion), ByteUtil.EMPTY); //////// Notify listeners // Lock down old field values map final NavigableMap<Integer, Object> readOnlyOldValuesMap = oldValueMap != null ? Maps.unmodifiableNavigableMap(oldValueMap) : null; // Notify about version update if (this.versionChangeListeners != null) { for (VersionChangeListener listener : this.versionChangeListeners) listener.onVersionChange(this, id, oldVersion, newVersion, readOnlyOldValuesMap); } } /** * Find storage ID's which are no longer allowed by a reference field when upgrading to the specified * schema version and therefore need to be scrubbed during the upgrade. * * @return set of storage ID's that are no longer allowed and should be audited on upgrade */ private SortedSet<Integer> findRemovedTypes(ReferenceField oldField, ReferenceField newField) { // Check allowed storage IDs final SortedSet<Integer> newObjectTypes = newField.getObjectTypes(); if (newObjectTypes == null) return Collections.emptySortedSet(); // new field can refer to any type in any schema version SortedSet<Integer> oldObjectTypes = oldField.getObjectTypes(); if (oldObjectTypes == null) oldObjectTypes = this.schemas.objTypeStorageIds; // old field can refer to any type in any schema version // Identify storage IDs which are were allowed by old field but are no longer allowed by new field final TreeSet<Integer> removedObjectTypes = new TreeSet<>(oldObjectTypes); removedObjectTypes.removeAll(newObjectTypes); return removedObjectTypes; } /** * Query objects by schema version. * * @return read-only, real-time view of all database objects indexed by schema version * @throws StaleTransactionException if this transaction is no longer usable */ public synchronized CoreIndex<Integer, ObjId> queryVersion() { if (this.stale) throw new StaleTransactionException(this); return Layout.getVersionIndex(this.kvt); } /** * Add an {@link VersionChangeListener} to this transaction. * * @param listener the listener to add * @throws IllegalArgumentException if {@code listener} is null * @throws StaleTransactionException if this transaction is no longer usable * @throws UnsupportedOperationException if {@link #setListeners setListeners()} has been invoked on this instance */ public synchronized void addVersionChangeListener(VersionChangeListener listener) { if (this.stale) throw new StaleTransactionException(this); Preconditions.checkArgument(listener != null, "null listener"); if (this.listenerSetInstalled) throw new UnsupportedOperationException("ListenerSet installed"); if (this.versionChangeListeners == null) this.versionChangeListeners = new HashSet<>(1); this.versionChangeListeners.add(listener); } /** * Remove an {@link VersionChangeListener} from this transaction. * * @param listener the listener to remove * @throws StaleTransactionException if this transaction is no longer usable * @throws IllegalArgumentException if {@code listener} is null * @throws UnsupportedOperationException if {@link #setListeners setListeners()} has been invoked on this instance */ public synchronized void removeVersionChangeListener(VersionChangeListener listener) { if (this.stale) throw new StaleTransactionException(this); Preconditions.checkArgument(listener != null, "null listener"); if (this.listenerSetInstalled) throw new UnsupportedOperationException("ListenerSet installed"); if (this.versionChangeListeners == null) return; this.versionChangeListeners.remove(listener); } // Object and Field Access /** * Get all objects in the database. * * <p> * The returned set includes objects from all schema versions. Use {@link #queryVersion} to * find objects with a specific schema version. * * <p> * The returned set is mutable, with the exception that {@link NavigableSet#add add()} is not supported. * Deleting an element results in {@linkplain #delete deleting} the corresponding object. * * @return a live view of all database objects * @throws StaleTransactionException if this transaction is no longer usable * @see #getAll(int) */ public synchronized NavigableSet<ObjId> getAll() { // Sanity check if (this.stale) throw new StaleTransactionException(this); // Return objects return new ObjTypeSet(this); } /** * Get all objects whose object type has the specified storage ID. * * <p> * The returned set is mutable, with the exception that {@link NavigableSet#add add()} is not supported. * Deleting an element results in {@linkplain #delete deleting} the corresponding object. * * @param storageId object type storage ID * @return a live view of all database objects having the specified storage ID * @throws UnknownTypeException if {@code storageId} does not correspond to any known object type * @throws StaleTransactionException if this transaction is no longer usable * @see #getAll() */ public synchronized NavigableSet<ObjId> getAll(int storageId) { // Sanity check if (this.stale) throw new StaleTransactionException(this); this.schemas.verifyStorageInfo(storageId, ObjTypeStorageInfo.class); // Return objects return new ObjTypeSet(this, storageId); } /** * Read the value of a {@link SimpleField} from an object, optionally updating the object's schema version. * * <p> * If {@code updateVersion} is true, the schema version of the object will be automatically changed to match * {@linkplain #getSchema() the schema version associated with this transaction}, if necessary, prior to * reading the field. * * @param id object ID of the object * @param storageId storage ID of the {@link SimpleField} * @param updateVersion true to first automatically update the object's schema version, false to not change it * @return value of the field in the object * @throws StaleTransactionException if this transaction is no longer usable * @throws DeletedObjectException if no object with ID equal to {@code id} is found * @throws UnknownTypeException if {@code id} specifies an unknown object type * @throws UnknownFieldException if no {@link SimpleField} corresponding to {@code storageId} exists in the object * @throws IllegalArgumentException if {@code id} is null * @throws TypeNotInSchemaVersionException {@code updateVersion} is true and the object could not be updated because * the object's type does not exist in the schema version associated with this transaction */ public synchronized Object readSimpleField(ObjId id, int storageId, boolean updateVersion) { // Sanity check Preconditions.checkArgument(id != null, "null id"); this.checkStaleFieldAccess(id, storageId); // Get object info final ObjInfo info = this.getObjectInfo(id, updateVersion); // Find field final SimpleField<?> field = info.getObjType().simpleFields.get(storageId); if (field == null) throw new UnknownFieldException(info.getObjType(), storageId, "simple field"); // Read field final byte[] key = field.buildKey(id); final byte[] value = this.kvt.get(key); // Decode value return value != null ? field.fieldType.read(new ByteReader(value)) : field.fieldType.getDefaultValueObject(); } /** * Change the value of a {@link SimpleField} in an object, optionally updating the object's schema version. * * <p> * If {@code updateVersion} is true, the schema version of the object will be automatically changed to match * {@linkplain #getSchema() the schema version associated with this transaction}, if necessary, prior to * writing the field. * * @param id object ID of the object * @param storageId storage ID of the {@link SimpleField} * @param value new value for the field * @param updateVersion true to first automatically update the object's schema version, false to not change it * @throws StaleTransactionException if this transaction is no longer usable * @throws DeletedObjectException if no object with ID equal to {@code id} is found * @throws UnknownTypeException if {@code id} specifies an unknown object type * @throws UnknownFieldException if no {@link SimpleField} corresponding to {@code storageId} exists in the object * @throws TypeNotInSchemaVersionException {@code updateVersion} is true and the object could not be updated because * the object's type does not exist in the schema version associated with this transaction * @throws IllegalArgumentException if {@code value} is not an appropriate value for the field * @throws IllegalArgumentException if {@code id} is null */ public void writeSimpleField(final ObjId id, final int storageId, final Object value, final boolean updateVersion) { this.mutateAndNotify(id, () -> { this.doWriteSimpleField(id, storageId, value, updateVersion); return null; }); } private synchronized void doWriteSimpleField(ObjId id, int storageId, final Object newObj, boolean updateVersion) { // Get object info final ObjInfo info = this.getObjectInfo(id, updateVersion); // Find field final SimpleField<?> field = info.getObjType().simpleFields.get(storageId); if (field == null) throw new UnknownFieldException(info.getObjType(), storageId, "simple field"); // Check for deleted assignment if (field instanceof ReferenceField) this.checkDeletedAssignment(id, (ReferenceField)field, (ObjId)newObj); // Get new value final byte[] key = field.buildKey(id); final byte[] newValue = field.encode(newObj); // Before setting the new value, read the old value if one of the following is true: // - The field is being monitored -> we need to filter out "changes" that don't actually change anything // - The field is indexed -> we need the old value so we can remove the old index entry // If neither of the above is true, then there's no need to read the old value. byte[] oldValue = null; if (field.indexed || field.compositeIndexMap != null || (!this.disableListenerNotifications && this.hasFieldMonitor(id, field.storageId))) { // Get old value oldValue = this.kvt.get(key); // Compare new to old value if (oldValue != null ? newValue != null && Arrays.equals(oldValue, newValue) : newValue == null) return; } // Update value if (newValue != null) this.kvt.put(key, newValue); else this.kvt.remove(key); // Update simple index, if any if (field.indexed) { this.kvt.remove(Transaction.buildSimpleIndexEntry(field, id, oldValue)); this.kvt.put(Transaction.buildSimpleIndexEntry(field, id, newValue), ByteUtil.EMPTY); } // Update affected composite indexes, if any if (field.compositeIndexMap != null) { for (CompositeIndex index : field.compositeIndexMap.keySet()) { // Build old composite index entry final ByteWriter oldWriter = new ByteWriter(); UnsignedIntEncoder.write(oldWriter, index.storageId); int fieldStart = -1; int fieldEnd = -1; for (SimpleField<?> otherField : index.fields) { final byte[] otherValue; if (otherField == field) { fieldStart = oldWriter.getLength(); otherValue = oldValue; } else otherValue = this.kvt.get(otherField.buildKey(id)); // can be null (if field has default value) oldWriter.write(otherValue != null ? otherValue : otherField.fieldType.getDefaultValue()); if (otherField == field) fieldEnd = oldWriter.getLength(); } assert fieldStart != -1; assert fieldEnd != -1; id.writeTo(oldWriter); // Remove old composite index entry final byte[] oldIndexEntry = oldWriter.getBytes(); this.kvt.remove(oldIndexEntry); // Patch in new field value to create new composite index entry final ByteWriter newWriter = new ByteWriter(oldIndexEntry.length); newWriter.write(oldIndexEntry, 0, fieldStart); newWriter.write(newValue != null ? newValue : field.fieldType.getDefaultValue()); newWriter.write(oldIndexEntry, fieldEnd, oldIndexEntry.length - fieldEnd); // Add new composite index entry this.kvt.put(newWriter.getBytes(), ByteUtil.EMPTY); } } // Notify monitors if (!this.disableListenerNotifications) { final Object oldObj = oldValue != null ? field.fieldType.read(new ByteReader(oldValue)) : field.fieldType.getDefaultValueObject(); this.addFieldChangeNotification(new SimpleFieldChangeNotifier(field, id) { @Override @SuppressWarnings("unchecked") public void notify(Transaction tx, SimpleFieldChangeListener listener, int[] path, NavigableSet<ObjId> referrers) { listener.onSimpleFieldChange(tx, this.id, (SimpleField<Object>)field, path, referrers, oldObj, newObj); } }); } } /** * Check for an invalid assignment to the given reference field of a deleted object. * * @param id referring object * @param field reference field in referring object * @param targetId referred-to object that should exist * @throws DeletedObjectException if assignment is invalid */ void checkDeletedAssignment(ObjId id, ReferenceField field, ObjId targetId) { // Allow null if (targetId == null) return; // It's possible for target to be the same object during a copy of a self-referencing object; allow it if (targetId.equals(id)) return; // Is deleted assignment disallowed for this field? if ((this instanceof SnapshotTransaction) ? field.allowDeletedSnapshot : field.allowDeleted) return; // Is the target a deleted object? if (this.exists(targetId)) return; // Are we copying? If so defer the check if (this.deletedAssignments != null) { this.deletedAssignments.put(targetId, field); return; } // Not allowed throw new DeletedObjectException(targetId, "illegal assignment to " + field + " in " + this.getObjDescription(id) + " of reference to deleted object " + this.getObjDescription(targetId)); } /** * Build a simple index entry for the given field, object ID, and field value. * * @param field simple field * @param id ID of object containing the field * @param value encoded field value, or null for default value * @return index key */ private static byte[] buildSimpleIndexEntry(SimpleField<?> field, ObjId id, byte[] value) { if (value == null) value = field.fieldType.getDefaultValue(); final ByteWriter writer = new ByteWriter(UnsignedIntEncoder.encodeLength(field.storageId) + value.length + ObjId.NUM_BYTES); UnsignedIntEncoder.write(writer, field.storageId); writer.write(value); id.writeTo(writer); return writer.getBytes(); } /** * Get a description of the given object's type. * * @param id object ID * @return textual description of the specified object's type * @throws IllegalArgumentException if {@code id} is null */ public String getTypeDescription(ObjId id) { Preconditions.checkArgument(id != null, "null id"); final int storageId = id.getStorageId(); final ObjType type = this.schema.objTypeMap.get(id.getStorageId()); return type != null ? "type `" + type.getName() + "'" : "type #" + storageId; } String getObjDescription(ObjId id) { Preconditions.checkArgument(id != null, "null id"); return "object " + id + " (" + this.getTypeDescription(id) + ")"; } String getFieldDescription(ObjId id, int storageId) { Preconditions.checkArgument(id != null, "null id"); final ObjType type = this.schema.objTypeMap.get(id.getStorageId()); if (type == null) return "field #" + storageId; final Field<?> field; try { field = type.getField(storageId, true); } catch (UnknownFieldException e) { return "field #" + storageId; } return "field `" + field.getName() + "'"; } private void checkStaleFieldAccess(ObjId id, int storageId) { assert Thread.holdsLock(this); if (this.stale) { throw new StaleTransactionException(this, "can't access " + this.getFieldDescription(id, storageId) + " of " + this.getObjDescription(id) + ": " + StaleTransactionException.DEFAULT_MESSAGE); } } /** * Read the value of a {@link CounterField} from an object, optionally updating the object's schema version. * * <p> * If {@code updateVersion} is true, the schema version of the object will be automatically changed to match * {@linkplain #getSchema() the schema version associated with this transaction}, if necessary, prior to * reading the field. * * @param id object ID of the object * @param storageId storage ID of the {@link CounterField} * @param updateVersion true to first automatically update the object's schema version, false to not change it * @return value of the counter in the object * @throws StaleTransactionException if this transaction is no longer usable * @throws DeletedObjectException if no object with ID equal to {@code id} is found * @throws UnknownTypeException if {@code id} specifies an unknown object type * @throws UnknownFieldException if no {@link CounterField} corresponding to {@code storageId} exists in the object * @throws TypeNotInSchemaVersionException {@code updateVersion} is true and the object could not be updated because * the object's type does not exist in the schema version associated with this transaction * @throws IllegalArgumentException if {@code id} is null */ public synchronized long readCounterField(ObjId id, int storageId, boolean updateVersion) { // Sanity check Preconditions.checkArgument(id != null, "null id"); this.checkStaleFieldAccess(id, storageId); // Get object info final ObjInfo info = this.getObjectInfo(id, updateVersion); // Find field final CounterField field = info.getObjType().counterFields.get(storageId); if (field == null) throw new UnknownFieldException(info.getObjType(), storageId, "counter field"); // Read field final byte[] key = field.buildKey(id); final byte[] value = this.kvt.get(key); // Decode value return value != null ? this.kvt.decodeCounter(value) : 0; } /** * Set the value of a {@link CounterField} in an object, optionally updating the object's schema version. * * <p> * If {@code updateVersion} is true, the schema version of the object will be automatically changed to match * {@linkplain #getSchema() the schema version associated with this transaction}, if necessary, prior to * writing the field. * * @param id object ID of the object * @param storageId storage ID of the {@link CounterField} * @param value new counter value * @param updateVersion true to first automatically update the object's schema version, false to not change it * @throws StaleTransactionException if this transaction is no longer usable * @throws DeletedObjectException if no object with ID equal to {@code id} is found * @throws UnknownTypeException if {@code id} specifies an unknown object type * @throws UnknownFieldException if no {@link CounterField} corresponding to {@code storageId} exists in the object * @throws TypeNotInSchemaVersionException {@code updateVersion} is true and the object could not be updated because * the object's type does not exist in the schema version associated with this transaction * @throws IllegalArgumentException if {@code id} is null */ public synchronized void writeCounterField(final ObjId id, final int storageId, final long value, final boolean updateVersion) { // Sanity check Preconditions.checkArgument(id != null, "null id"); this.checkStaleFieldAccess(id, storageId); // Get object info final ObjInfo info = this.getObjectInfo(id, updateVersion); // Find field final CounterField field = info.getObjType().counterFields.get(storageId); if (field == null) throw new UnknownFieldException(info.getObjType(), storageId, "counter field"); // Set value final byte[] key = field.buildKey(id); this.kvt.put(key, this.kvt.encodeCounter(value)); } /** * Adjust the value of a {@link CounterField} in an object by some amount, optionally updating the object's schema version. * * <p> * If {@code updateVersion} is true, the schema version of the object will be automatically changed to match * {@linkplain #getSchema() the schema version associated with this transaction}, if necessary, prior to * writing the field. * * @param id object ID of the object * @param storageId storage ID of the {@link CounterField} * @param offset offset value to add to counter value * @param updateVersion true to first automatically update the object's schema version, false to not change it * @throws StaleTransactionException if this transaction is no longer usable * @throws DeletedObjectException if no object with ID equal to {@code id} is found * @throws UnknownTypeException if {@code id} specifies an unknown object type * @throws UnknownFieldException if no {@link CounterField} corresponding to {@code storageId} exists in the object * @throws TypeNotInSchemaVersionException {@code updateVersion} is true and the object could not be updated because * the object's type does not exist in the schema version associated with this transaction * @throws IllegalArgumentException if {@code id} is null */ public synchronized void adjustCounterField(ObjId id, int storageId, long offset, boolean updateVersion) { // Sanity check Preconditions.checkArgument(id != null, "null id"); this.checkStaleFieldAccess(id, storageId); // Optimize away non-change if (offset == 0) return; // Get object info final ObjInfo info = this.getObjectInfo(id, updateVersion); // Find field final CounterField field = info.getObjType().counterFields.get(storageId); if (field == null) throw new UnknownFieldException(info.getObjType(), storageId, "counter field"); // Adjust counter value this.kvt.adjustCounter(field.buildKey(id), offset); } /** * Access a {@link SetField} associated with an object, optionally updating the object's schema version. * * <p> * If {@code updateVersion} is true, the schema version of the object will be automatically changed to match * {@linkplain #getSchema() the schema version associated with this transaction}, if necessary. * * @param id object ID of the object * @param storageId storage ID of the {@link SetField} * @param updateVersion true to first automatically update the object's schema version, false to not change it * @return set field value * @throws StaleTransactionException if this transaction is no longer usable * @throws DeletedObjectException if no object with ID equal to {@code id} is found * @throws UnknownTypeException if {@code id} specifies an unknown object type * @throws UnknownFieldException if no {@link SetField} corresponding to {@code storageId} exists in the object * @throws TypeNotInSchemaVersionException {@code updateVersion} is true and the object could not be updated because * the object's type does not exist in the schema version associated with this transaction * @throws IllegalArgumentException if {@code id} is null */ public NavigableSet<?> readSetField(ObjId id, int storageId, boolean updateVersion) { return this.readComplexField(id, storageId, updateVersion, SetField.class, NavigableSet.class); } /** * Access a {@link ListField} associated with an object, optionally updating the object's schema version. * * <p> * If {@code updateVersion} is true, the schema version of the object will be automatically changed to match * {@linkplain #getSchema() the schema version associated with this transaction}, if necessary. * * @param id object ID of the object * @param storageId storage ID of the {@link ListField} * @param updateVersion true to first automatically update the object's schema version, false to not change it * @return list field value * @throws StaleTransactionException if this transaction is no longer usable * @throws DeletedObjectException if no object with ID equal to {@code id} is found * @throws UnknownTypeException if {@code id} specifies an unknown object type * @throws UnknownFieldException if no {@link ListField} corresponding to {@code storageId} exists in the object * @throws TypeNotInSchemaVersionException {@code updateVersion} is true and the object could not be updated because * the object's type does not exist in the schema version associated with this transaction * @throws IllegalArgumentException if {@code id} is null */ public List<?> readListField(ObjId id, int storageId, boolean updateVersion) { return this.readComplexField(id, storageId, updateVersion, ListField.class, List.class); } /** * Access a {@link MapField} associated with an object, optionally updating the object's schema version. * * <p> * If {@code updateVersion} is true, the schema version of the object will be automatically changed to match * {@linkplain #getSchema() the schema version associated with this transaction}, if necessary. * * @param id object ID of the object * @param storageId storage ID of the {@link MapField} * @param updateVersion true to first automatically update the object's schema version, false to not change it * @return map field value * @throws StaleTransactionException if this transaction is no longer usable * @throws DeletedObjectException if no object with ID equal to {@code id} is found * @throws UnknownTypeException if {@code id} specifies an unknown object type * @throws UnknownFieldException if no {@link MapField} corresponding to {@code storageId} exists in the object * @throws TypeNotInSchemaVersionException {@code updateVersion} is true and the object could not be updated because * the object's type does not exist in the schema version associated with this transaction * @throws IllegalArgumentException if {@code id} is null */ public NavigableMap<?, ?> readMapField(ObjId id, int storageId, boolean updateVersion) { return this.readComplexField(id, storageId, updateVersion, MapField.class, NavigableMap.class); } /** * Get the {@code byte[]} key in the underlying key/value store corresponding to the specified object. * * <p> * Notes: * <ul> * <li>This method does not check whether {@code id} is valid or the object actually exists.</li> * <li>Objects utilize multiple keys; the return value is the common prefix of all such keys.</li> * <li>The {@link io.permazen.kv.KVDatabase} should not be modified directly, otherwise behavior is undefined</li> * </ul> * * @param id object ID * @return the {@link io.permazen.kv.KVDatabase} key corresponding to {@code id} * @throws IllegalArgumentException if {@code id} is null * @see io.permazen.JTransaction#getKey(io.permazen.JObject) JTransaction.getKey() */ public byte[] getKey(ObjId id) { Preconditions.checkArgument(id != null, "null id"); return id.getBytes(); } /** * Get the {@code byte[]} key in the underlying key/value store corresponding to the specified field in the specified object. * * <p> * Notes: * <ul> * <li>This method does not check whether {@code id} is valid, the object exists, * or the field actually exists in the object's current schema version.</li> * <li>Complex fields utilize multiple keys; the return value is the common prefix of all such keys.</li> * <li>The {@link io.permazen.kv.KVDatabase} should not be modified directly, otherwise behavior is undefined</li> * </ul> * * @param id object ID * @param storageId field storage ID * @return the {@link io.permazen.kv.KVDatabase} key of the field in the specified object * @throws IllegalArgumentException if {@code storageId} is less than or equal to zero * @throws IllegalArgumentException if {@code id} is null * @see io.permazen.JTransaction#getKey(io.permazen.JObject, String) JTransaction.getKey() * @see io.permazen.kv.KVTransaction#watchKey KVTransaction.watchKey() */ public byte[] getKey(ObjId id, int storageId) { // Sanity check Preconditions.checkArgument(id != null, "null id"); Preconditions.checkArgument(storageId > 0, "non-positive storageId"); // Build key final ByteWriter writer = new ByteWriter(); id.writeTo(writer); UnsignedIntEncoder.write(writer, storageId); return writer.getBytes(); } synchronized boolean hasDefaultValue(ObjId id, SimpleField<?> field) { // Sanity check if (this.stale) throw new StaleTransactionException(this); Preconditions.checkArgument(id != null, "null id"); // Verify object exists if (!this.exists(id)) throw new DeletedObjectException(this, id); // Check whether non-default value stored in field return this.kvt.get(field.buildKey(id)) == null; } private synchronized <F, V> V readComplexField(ObjId id, int storageId, boolean updateVersion, Class<F> fieldClass, Class<V> valueType) { // Sanity check Preconditions.checkArgument(id != null, "null id"); this.checkStaleFieldAccess(id, storageId); // Get object info final ObjInfo info = this.getObjectInfo(id, updateVersion); // Get field final ComplexField<?> field = info.getObjType().complexFields.get(storageId); if (!fieldClass.isInstance(field)) throw new UnknownFieldException(info.getObjType(), storageId, fieldClass.getSimpleName()); // Return view return valueType.cast(field.getValueInternal(this, id)); } /** * If an object exists, read in its meta-data, also updating its schema version it in the process if requested. * * @param id object ID of the object * @param update true to update object's schema version to match this transaction, false to leave it alone * @return object info if object exists, otherwise null * @throws IllegalArgumentException if {@code id} is null */ private ObjInfo getObjectInfoIfExists(ObjId id, boolean update) { assert Thread.holdsLock(this); try { return this.getObjectInfo(id, update); } catch (DeletedObjectException | UnknownTypeException e) { return null; } } /** * Read an object's meta-data, updating its schema version it in the process if requested. * * @param id object ID of the object * @param update true to update object's schema version to match this transaction, false to leave it alone * @return object info * @throws UnknownTypeException if object ID specifies an unknown object type * @throws DeletedObjectException if no object with ID equal to {@code id} is found * @throws IllegalArgumentException if {@code id} is null */ private ObjInfo getObjectInfo(ObjId id, boolean update) { // Sanity check assert Thread.holdsLock(this); // Load object info into cache, if not already there ObjInfo info = this.objInfoCache.get(id); if (info == null) { // Verify that the object type encoded within the object ID is valid this.schemas.verifyStorageInfo(id.getStorageId(), ObjTypeStorageInfo.class); // Load the object's info into the cache (if object doesn't exist, we'll get an exception here) info = this.loadIntoCache(id); } // Is a schema update required? if (!update || info.getVersion() == this.schema.versionNumber) return info; // Update schema version final ObjInfo info2 = info; this.mutateAndNotify(new Mutation<Void>() { @Override public Void mutate() { Transaction.this.changeVersion(info2, Transaction.this.schema); return null; } }); // Load (updated) object info into cache return this.loadIntoCache(id); } /** * Get the specified object's info from the object info cache, loading it if necessary. * * @throws DeletedObjectException if object does not exist */ private ObjInfo loadIntoCache(ObjId id) { ObjInfo info = this.objInfoCache.get(id); if (info == null) { // Create info; we'll get an exception here if object does not exist info = new ObjInfo(this, id); // Add object info to the cache if (this.objInfoCache.size() >= MAX_OBJ_INFO_CACHE_ENTRIES) this.objInfoCache.removeOne(); this.objInfoCache.put(id, info); } return info; } // Field Change Notifications /** * Monitor for changes within this transaction of the value of the given field, as seen through a path of references. * * <p> * When the specified field is changed in some object T, a listener notification will be delivered for each object R * that refers to object T through the specified path of reference fields (if {@code path} is empty, then R = T). * Notifications are delivered at the end of the mutation operation just prior to returning to the caller. If the listener * method performs additional mutation(s) which are themselves being listened for, those notifications will also be delivered * prior to the returning to the original caller. Therefore, care must be taken to avoid change notification dependency * loops when listeners can themselves mutate fields, to avoid infinite loops. * * <p> * The {@code filters}, if any, are applied to {@link ObjId}'s at the corresponding steps in the path: {@code filters[0]} * is applied to the starting objects R, {@code filters[1]} is applied to the objects reachable from R via {@code path[0]}, * etc., up to {@code filters[path.length]}, which applies to the target objects T. {@code filters} or any element * therein may be null to indicate no restriction. * * <p> * A referring object R may refer to the changed object T through more than one sequence of objects matching {@code path}; * if so, R will still appear only once in the {@link NavigableSet} provided to the listener (this is of course required * by set semantics). * * <p> * Although the reference back-tracking algorithm does consolidate multiple paths between the same two objects, * be careful to avoid an explosion of notifications when objects in the {@code path} have a high degree of fan-in. * * <p> * When a {@link ReferenceField} in {@code path} also happens to be the field being changed, then there is ambiguity * about how the set of referring objects is calculated: does it use the field's value before or after the change? * This API guarantees that the answer is "after the change"; however, if another listener on the same field is * invoked before {@code listener} and mutates any reference field(s) in {@code path}, then whether that additional * change is also be included in the calculation is undefined. * * <p> * Therefore, for consistency, avoid changing any {@link ReferenceField} from within a listener callback when that * field is also in some other listener's reference path, and both listeners are watching the same field. * * <p> * Permazen allows a field's type to change across schema versions, therefore some schema version may exist in * which the field associated with {@code storageId} is not a {@link SimpleField}. In such cases, {@code listener} * will receive notifications about those changes if it also happens to implement the other listener interface. * In other words, this method delegates directly to {@link #addFieldChangeListener addFieldChangeListener()}. * * @param storageId storage ID of the field to monitor * @param path path of reference fields (represented by storage IDs) through which to monitor field; * negated values denote inverse traversal of the field * @param filters if not null, an array of length {@code path.length + 1} containing optional filters to be applied * to object ID's after the corresponding steps in the path * @param listener callback for notifications on changes in value * @throws UnknownFieldException if {@code path} contains a storage ID that does not correspond to a {@link ReferenceField} * @throws IllegalArgumentException if {@code path} or {@code listener} is null * @throws StaleTransactionException if this transaction is no longer usable * @throws UnsupportedOperationException if {@link #setListeners setListeners()} has been invoked on this instance */ public void addSimpleFieldChangeListener(int storageId, int[] path, KeyRanges[] filters, SimpleFieldChangeListener listener) { this.addFieldChangeListener(storageId, path, filters, listener); } /** * Monitor for changes within this transaction to the specified {@link SetField} as seen through a path of references. * * <p> * See {@link #addSimpleFieldChangeListener addSimpleFieldChangeListener()} for details on how notifications are delivered. * * <p> * Permazen allows a field's type to change across schema versions, therefore some schema version may exist in * which the field associated with {@code storageId} is not a {@link SetField}. In such cases, {@code listener} * will receive notifications about those changes if it also happens to implement the other listener interface. * In other words, this method delegates directly to {@link #addFieldChangeListener addFieldChangeListener()}. * * @param storageId storage ID of the field to monitor * @param path path of reference fields (represented by storage IDs) through which to monitor field; * negated values denote inverse traversal of the field * @param filters if not null, an array of length {@code path.length + 1} containing optional filters to be applied * to object ID's after the corresponding steps in the path * @param listener callback for notifications on changes in value * @throws UnknownFieldException if {@code path} contains a storage ID that does not correspond to a {@link ReferenceField} * @throws IllegalArgumentException if {@code path} or {@code listener} is null * @throws StaleTransactionException if this transaction is no longer usable * @throws UnsupportedOperationException if {@link #setListeners setListeners()} has been invoked on this instance */ public void addSetFieldChangeListener(int storageId, int[] path, KeyRanges[] filters, SetFieldChangeListener listener) { this.addFieldChangeListener(storageId, path, filters, listener); } /** * Monitor for changes within this transaction to the specified {@link ListField} as seen through a path of references. * * <p> * See {@link #addSimpleFieldChangeListener addSimpleFieldChangeListener()} for details on how notifications are delivered. * * <p> * Permazen allows a field's type to change across schema versions, therefore some schema version may exist in * which the field associated with {@code storageId} is not a {@link ListField}. In such cases, {@code listener} * will receive notifications about those changes if it also happens to implement the other listener interface. * In other words, this method delegates directly to {@link #addFieldChangeListener addFieldChangeListener()}. * * @param storageId storage ID of the field to monitor * @param path path of reference fields (represented by storage IDs) through which to monitor field; * negated values denote inverse traversal of the field * @param filters if not null, an array of length {@code path.length + 1} containing optional filters to be applied * to object ID's after the corresponding steps in the path * @param listener callback for notifications on changes in value * @throws UnknownFieldException if {@code path} contains a storage ID that does not correspond to a {@link ReferenceField} * @throws IllegalArgumentException if {@code path} or {@code listener} is null * @throws StaleTransactionException if this transaction is no longer usable * @throws UnsupportedOperationException if {@link #setListeners setListeners()} has been invoked on this instance */ public void addListFieldChangeListener(int storageId, int[] path, KeyRanges[] filters, ListFieldChangeListener listener) { this.addFieldChangeListener(storageId, path, filters, listener); } /** * Monitor for changes within this transaction to the specified {@link MapField} as seen through a path of references. * * <p> * See {@link #addSimpleFieldChangeListener addSimpleFieldChangeListener()} for details on how notifications are delivered. * * <p> * Permazen allows a field's type to change across schema versions, therefore some schema version may exist in * which the field associated with {@code storageId} is not a {@link MapField}. In such cases, {@code listener} * will receive notifications about those changes if it also happens to implement the other listener interface. * In other words, this method delegates directly to {@link #addFieldChangeListener addFieldChangeListener()}. * * @param storageId storage ID of the field to monitor * @param path path of reference fields (represented by storage IDs) through which to monitor field; * negated values denote inverse traversal of the field * @param filters if not null, an array of length {@code path.length + 1} containing optional filters to be applied * to object ID's after the corresponding steps in the path * @param listener callback for notifications on changes in value * @throws UnknownFieldException if {@code path} contains a storage ID that does not correspond to a {@link ReferenceField} * @throws IllegalArgumentException if {@code path} or {@code listener} is null * @throws StaleTransactionException if this transaction is no longer usable * @throws UnsupportedOperationException if {@link #setListeners setListeners()} has been invoked on this instance */ public void addMapFieldChangeListener(int storageId, int[] path, KeyRanges[] filters, MapFieldChangeListener listener) { this.addFieldChangeListener(storageId, path, filters, listener); } /** * Monitor for changes within this transaction to the specified {@link Field} as seen through a path of references. * * <p> * See {@link #addSimpleFieldChangeListener addSimpleFieldChangeListener()} for details on how notifications are delivered. * * <p> * Permazen allows a field's type to change across schema versions, therefore in different schema versions the * specified field may have different types. The {@code listener} will receive notifications about a field change * if it implements the interface appropriate for the field's current type (i.e., {@link SimpleFieldChangeListener}, * {@link ListFieldChangeListener}, {@link SetFieldChangeListener}, or {@link MapFieldChangeListener}) at the time * of the change. * * @param storageId storage ID of the field to monitor * @param path path of reference fields (represented by storage IDs) through which to monitor field; * negated values denote inverse traversal of the field * @param filters if not null, an array of length {@code path.length + 1} containing optional filters to be applied * to object ID's after the corresponding steps in the path * @param listener callback for notifications on changes in value * @throws UnknownFieldException if {@code path} contains a storage ID that does not correspond to a {@link ReferenceField} * @throws IllegalArgumentException if {@code path} or {@code listener} is null * @throws StaleTransactionException if this transaction is no longer usable * @throws UnsupportedOperationException if {@link #setListeners setListeners()} has been invoked on this instance */ public synchronized void addFieldChangeListener(int storageId, int[] path, KeyRanges[] filters, Object listener) { this.validateChangeListener(path, listener); this.getMonitorsForField(storageId, true).add(new FieldMonitor(storageId, path, filters, listener)); } /** * Remove a field monitor previously added via {@link #addSimpleFieldChangeListener addSimpleFieldChangeListener()} * (or {@link #addFieldChangeListener addFieldChangeListener()}). * * @param storageId storage ID of the field to no longer monitor * @param path path of reference fields (represented by storage IDs) through which to monitor field; * negated values denote inverse traversal of the field * @param filters if not null, an array of length {@code path.length + 1} containing optional filters to be applied * to object ID's after the corresponding steps in the path * @param listener callback for notifications on changes in value * @throws UnknownFieldException if {@code path} contains a storage ID that does not correspond to a {@link ReferenceField} * @throws IllegalArgumentException if {@code path} or {@code listener} is null * @throws StaleTransactionException if this transaction is no longer usable * @throws UnsupportedOperationException if {@link #setListeners setListeners()} has been invoked on this instance */ public void removeSimpleFieldChangeListener(int storageId, int[] path, KeyRanges[] filters, SimpleFieldChangeListener listener) { this.removeFieldChangeListener(storageId, path, filters, listener); } /** * Remove a field monitor previously added via {@link #addSetFieldChangeListener addSetFieldChangeListener()} * (or {@link #addFieldChangeListener addFieldChangeListener()}). * * @param storageId storage ID of the field to no longer monitor * @param path path of reference fields (represented by storage IDs) through which to monitor field; * negated values denote inverse traversal of the field * @param filters if not null, an array of length {@code path.length + 1} containing optional filters to be applied * to object ID's after the corresponding steps in the path * @param listener callback for notifications on changes in value * @throws UnknownFieldException if {@code path} contains a storage ID that does not correspond to a {@link ReferenceField} * @throws IllegalArgumentException if {@code path} or {@code listener} is null * @throws StaleTransactionException if this transaction is no longer usable * @throws UnsupportedOperationException if {@link #setListeners setListeners()} has been invoked on this instance */ public void removeSetFieldChangeListener(int storageId, int[] path, KeyRanges[] filters, SetFieldChangeListener listener) { this.removeFieldChangeListener(storageId, path, filters, listener); } /** * Remove a field monitor previously added via {@link #addListFieldChangeListener addListFieldChangeListener()} * (or {@link #addFieldChangeListener addFieldChangeListener()}). * * @param storageId storage ID of the field to no longer monitor * @param path path of reference fields (represented by storage IDs) through which to monitor field; * negated values denote inverse traversal of the field * @param filters if not null, an array of length {@code path.length + 1} containing optional filters to be applied * to object ID's after the corresponding steps in the path * @param listener callback for notifications on changes in value * @throws UnknownFieldException if {@code path} contains a storage ID that does not correspond to a {@link ReferenceField} * @throws IllegalArgumentException if {@code path} or {@code listener} is null * @throws StaleTransactionException if this transaction is no longer usable * @throws UnsupportedOperationException if {@link #setListeners setListeners()} has been invoked on this instance */ public void removeListFieldChangeListener(int storageId, int[] path, KeyRanges[] filters, ListFieldChangeListener listener) { this.removeFieldChangeListener(storageId, path, filters, listener); } /** * Remove a field monitor previously added via {@link #addMapFieldChangeListener addMapFieldChangeListener()} * (or {@link #addFieldChangeListener addFieldChangeListener()}). * * @param storageId storage ID of the field to no longer monitor * @param path path of reference fields (represented by storage IDs) through which to monitor field; * negated values denote inverse traversal of the field * @param filters if not null, an array of length {@code path.length + 1} containing optional filters to be applied * to object ID's after the corresponding steps in the path * @param listener callback for notifications on changes in value * @throws UnknownFieldException if {@code path} contains a storage ID that does not correspond to a {@link ReferenceField} * @throws IllegalArgumentException if {@code path} or {@code listener} is null * @throws StaleTransactionException if this transaction is no longer usable * @throws UnsupportedOperationException if {@link #setListeners setListeners()} has been invoked on this instance */ public void removeMapFieldChangeListener(int storageId, int[] path, KeyRanges[] filters, MapFieldChangeListener listener) { this.removeFieldChangeListener(storageId, path, filters, listener); } /** * Remove a field monitor previously added via {@link #addSimpleFieldChangeListener addSimpleFieldChangeListener()}, * {@link #addSetFieldChangeListener addSetFieldChangeListener()}, * {@link #addListFieldChangeListener addListFieldChangeListener()}, * {@link #addMapFieldChangeListener addMapFieldChangeListener()}, * or {@link #addFieldChangeListener addFieldChangeListener()}. * * @param storageId storage ID of the field to no longer monitor * @param path path of reference fields (represented by storage IDs) through which to monitor field; * negated values denote inverse traversal of the field * @param filters if not null, an array of length {@code path.length + 1} containing optional filters to be applied * to object ID's after the corresponding steps in the path * @param listener callback for notifications on changes in value * @throws UnknownFieldException if {@code path} contains a storage ID that does not correspond to a {@link ReferenceField} * @throws IllegalArgumentException if {@code path} or {@code listener} is null * @throws StaleTransactionException if this transaction is no longer usable * @throws UnsupportedOperationException if {@link #setListeners setListeners()} has been invoked on this instance */ public synchronized void removeFieldChangeListener(int storageId, int[] path, KeyRanges[] filters, Object listener) { this.validateChangeListener(path, listener); final Set<FieldMonitor> monitors = this.getMonitorsForField(storageId); if (monitors != null) monitors.remove(new FieldMonitor(storageId, path, filters, listener)); } private void validateChangeListener(int[] path, Object listener) { assert Thread.holdsLock(this); if (this.stale) throw new StaleTransactionException(this); Preconditions.checkArgument(path != null, "null path"); Preconditions.checkArgument(listener != null, "null listener"); if (this.listenerSetInstalled) throw new UnsupportedOperationException("ListenerSet installed"); this.verifyReferencePath(path); } private Set<FieldMonitor> getMonitorsForField(int storageId) { return this.getMonitorsForField(storageId, false); } private synchronized Set<FieldMonitor> getMonitorsForField(int storageId, boolean create) { Set<FieldMonitor> monitors; if (this.monitorMap == null) { if (!create) return null; this.monitorMap = new TreeMap<>(); monitors = null; } else monitors = this.monitorMap.get(storageId); if (monitors == null) { if (!create) return null; monitors = new HashSet<>(1); this.monitorMap.put(storageId, monitors); } return monitors; } /** * Add a pending notification for any {@link FieldMonitor}s watching the specified field in the specified object. * This method assumes only the appropriate type of monitor is registered as a listener on the field * and that the provided old and new values have the appropriate types. * * <p> * This method should only be invoked if this.disableListenerNotifications is false. */ void addFieldChangeNotification(FieldChangeNotifier<?> notifier) { assert Thread.holdsLock(this); assert !this.disableListenerNotifications; // Get info final ObjId id = notifier.getId(); final int fieldStorageId = notifier.getStorageId(); // Does anybody care? if (!this.hasFieldMonitor(id, fieldStorageId)) return; // Add a pending field monitor notification for the specified field this.pendingNotifications.get().computeIfAbsent(fieldStorageId, i -> new ArrayList<>(2)).add(notifier); } /** * Determine if there are any monitors watching the specified field in the specified object. */ boolean hasFieldMonitor(ObjId id, int fieldStorageId) { assert Thread.holdsLock(this); // Do quick check, if possible if (this.monitorMap == null) return false; final int objTypeStorageId = id.getStorageId(); if (this.hasFieldMonitorCache != null) return this.hasFieldMonitorCache.contains(this.buildHasFieldMonitorCacheKey(objTypeStorageId, fieldStorageId)); // Do slow check final Set<FieldMonitor> monitorsForField = this.getMonitorsForField(fieldStorageId); if (monitorsForField == null) return false; return monitorsForField.stream().anyMatch(new MonitoredPredicate(objTypeStorageId, fieldStorageId)); } /** * Determine if there are any monitors watching any field in the specified type. */ boolean hasFieldMonitor(ObjType objType) { assert Thread.holdsLock(this); // Do quick check, if possible if (this.monitorMap == null) return false; final int objTypeStorageId = objType.storageId; if (this.hasFieldMonitorCache != null) { final long minKey = this.buildHasFieldMonitorCacheKey(objTypeStorageId, 0); if (objTypeStorageId == Integer.MAX_VALUE) return this.hasFieldMonitorCache.ceiling(minKey) != null; final long maxKey = this.buildHasFieldMonitorCacheKey(objTypeStorageId + 1, 0); return !this.hasFieldMonitorCache.subSet(minKey, maxKey).isEmpty(); } // Do slow check for (int fieldStorageId : NavigableSets.intersection(objType.fields.navigableKeySet(), this.monitorMap.navigableKeySet())) { if (this.monitorMap.get(fieldStorageId).stream().anyMatch(new MonitoredPredicate(objTypeStorageId, fieldStorageId))) return true; } return false; } private long buildHasFieldMonitorCacheKey(int objTypeStorageId, int fieldStorageId) { return ((long)objTypeStorageId << 32) | (long)fieldStorageId & 0xffffffffL; } /** * Build a data structure that to optimize checking whether a field in an object type is being monitored. */ private synchronized NavigableSet<Long> buildHasFieldMonitorCache() { if (this.monitorMap == null) return Collections.emptyNavigableSet(); final TreeSet<Long> set = new TreeSet<>(); for (Schema otherSchema : this.schemas.versions.values()) { for (ObjType objType : otherSchema.objTypeMap.values()) { final int objTypeStorageId = objType.storageId; for (Field<?> field : objType.fieldsAndSubFields) { final int fieldStorageId = field.storageId; final Set<FieldMonitor> monitors = this.getMonitorsForField(fieldStorageId); if (monitors != null && monitors.stream().anyMatch(new MonitoredPredicate(objTypeStorageId, fieldStorageId))) set.add(this.buildHasFieldMonitorCacheKey(objTypeStorageId, fieldStorageId)); } } } return set; } /** * Verify the given object exists before proceeding with the given mutation via {@link #mutateAndNotify(Mutation)}. * * @param id object containing the mutated field; will be validated * @param mutation change to apply * @throws StaleTransactionException if this transaction is no longer usable * @throws IllegalArgumentException if {@code id} is null */ synchronized <V> V mutateAndNotify(ObjId id, Mutation<V> mutation) { // Verify object exists Preconditions.checkArgument(id != null, "null id"); if (this.stale) throw new StaleTransactionException(this); if (!this.exists(id)) throw new DeletedObjectException(this, id); // Perform mutation return this.mutateAndNotify(mutation); } /** * Perform some action and, when entirely done (including re-entrant invocation), issue pending notifications to monitors. * * @param mutation change to apply * @throws StaleTransactionException if this transaction is no longer usable * @throws NullPointerException if {@code mutation} is null */ private synchronized <V> V mutateAndNotify(Mutation<V> mutation) { // Validate transaction if (this.stale) throw new StaleTransactionException(this); // If re-entrant invocation, we're already set up if (this.pendingNotifications.get() != null) return mutation.mutate(); // Set up pending report list, perform mutation, and then issue reports this.pendingNotifications.set(new TreeMap<>()); try { return mutation.mutate(); } finally { try { final TreeMap<Integer, ArrayList<FieldChangeNotifier<?>>> pendingNotificationMap = this.pendingNotifications.get(); while (!pendingNotificationMap.isEmpty()) { // Get the next field with pending notifications final Map.Entry<Integer, ArrayList<FieldChangeNotifier<?>>> entry = pendingNotificationMap.pollFirstEntry(); final int storageId = entry.getKey(); // For all pending notifications, back-track references and notify all field monitors for the field for (FieldChangeNotifier<?> notifier : entry.getValue()) { assert notifier.getStorageId() == storageId; final Set<FieldMonitor> monitors = this.getMonitorsForField(storageId); if (monitors == null || monitors.isEmpty()) continue; this.notifyFieldMonitors(notifier, NavigableSets.singleton(notifier.getId()), new ArrayList<>(monitors), 0); } } } finally { this.pendingNotifications.remove(); } } } // Recursively back-track references along monitor paths and notify monitors when we reach the end (i.e., beginning) private void notifyFieldMonitors(FieldChangeNotifier<?> notifier, NavigableSet<ObjId> objects, ArrayList<FieldMonitor> monitorList, int step) { // Find the monitors for whom we have completed all the steps in their (inverse) path, // and group the remaining monitors by their next inverted reference path step. final HashMap<Integer, ArrayList<FieldMonitor>> remainingMonitorsMap = new HashMap<>(); for (FieldMonitor monitor : monitorList) { // Apply the monitor's type filter on the target object, if any if (step == 0) { final KeyRanges filter = monitor.getTargetFilter(); if (filter != null && !filter.contains(notifier.getId().getBytes())) continue; } // Issue notification callback if we have back-tracked through the whole path if (monitor.path.length == step) { this.notifyFieldChangeListener(notifier, monitor, objects); continue; } // Sort the unfinished monitors by their next (i.e., previous) reference field final int storageId = monitor.getStorageId(step); remainingMonitorsMap.computeIfAbsent(storageId, i -> new ArrayList<>()).add(monitor); } // Invert references for each group of remaining monitors and recurse for (Map.Entry<Integer, ArrayList<FieldMonitor>> entry : remainingMonitorsMap.entrySet()) { final int storageId = entry.getKey(); final ArrayList<FieldMonitor> monitors = entry.getValue(); assert monitors != null; final ArrayList<NavigableSet<ObjId>> refsList = new ArrayList<>(monitors.size()); for (FieldMonitor monitor : entry.getValue()) refsList.addAll(this.traverseReference(objects, -storageId, monitor.getFilter(step + 1))); if (!refsList.isEmpty()) this.notifyFieldMonitors(notifier, NavigableSets.union(refsList), monitors, step + 1); } } // Notify listener, if it has the appropriate type private <T> void notifyFieldChangeListener(FieldChangeNotifier<T> notifier, FieldMonitor monitor, NavigableSet<ObjId> objects) { final T listener; try { listener = notifier.getListenerType().cast(monitor.listener); } catch (ClassCastException e) { return; } notifier.notify(this, listener, monitor.path, objects); } // Reference Path Queries /** * Find all objects referred to by any object in the given start set through the specified path of references. * * <p> * Each value in {@code path} represents a reference field traversed in the path to some target object(s); if a * value in {@code path} is negated, then the field is traversed in the inverse direction. * * <p> * If {@code path} is empty, then {@code startObjects} is returned. * * <p> * The {@code filters}, if any, are applied to {@link ObjId}'s at the corresponding steps in the path: {@code filters[0]} * is applied to {@code startObjects}, {@code filters[1]} is applied to the objects reachable from {@code startObjects} * via {@code path[0]}, etc., up to {@code filters[path.length]}, which applies to the final target objects. {@code filters} * or any element therein may be null to indicate no restriction. * * @param startObjects starting objects * @param path path of zero or more reference fields (represented by storage IDs) through which to reach the target objects; * negated values denote an inverse traversal of the corresponding reference field * @param filters if not null, an array of length {@code path.length + 1} containing optional filters to be applied * to object ID's after the corresponding steps in the path * @return read-only set of objects referred to by the {@code startObjects} via {@code path} restricted by {@code filters} * @throws UnknownFieldException if {@code path} contains a storage ID that does not correspond to a {@link ReferenceField} * @throws IllegalArgumentException if {@code startObjects} or {@code path} is null * @throws IllegalArgumentException if {@code filters} is not null and does not have length {@code path.length + 1} * @throws StaleTransactionException if this transaction is no longer usable */ public NavigableSet<ObjId> followReferencePath(Iterable<? extends ObjId> startObjects, int[] path, KeyRanges[] filters) { // Sanity check Preconditions.checkArgument(startObjects != null, "null startObjects"); Preconditions.checkArgument(path != null, "null path"); Preconditions.checkArgument(filters == null || filters.length == path.length + 1, "invalid filters length"); // Perform initial filtering final ObjIdSet startIds = new ObjIdSet(); final KeyRanges firstFilter = filters != null ? filters[0] : null; for (ObjId id : startObjects) { if (firstFilter == null || firstFilter.contains(id.getBytes())) startIds.add(id); } if (path.length == 0) return startIds.sortedSnapshot(); // Traverse each reference in the path Set<ObjId> ids = startIds; for (int i = 0; i < path.length; i++) { final int pathId = path[i]; final KeyRanges filter = filters != null ? filters[i + 1] : null; // Traverse reference final ArrayList<NavigableSet<ObjId>> refsList = this.traverseReference(ids, pathId, filter); if (refsList.isEmpty()) return NavigableSets.empty(FieldTypeRegistry.OBJ_ID); // Recurse on the union of the resulting object sets ids = NavigableSets.union(refsList); } // Done return (NavigableSet<ObjId>)ids; } /** * Find all objects that refer to any object in the given target set through the specified path of references. * * <p> * Each value in {@code path} represents a reference field traversed in the path to the target object(s); if a * value in {@code path} is negated, then the field is traversed in the inverse direction. * * <p> * If {@code path} is empty, then {@code targetObjects} is returned. * * <p> * The {@code filters}, if any, are applied to {@link ObjId}'s at the corresponding steps in the path: * {@code filters[path.length]} is applied to {@code targetObjects}, {@code filters[path.length - 1]} is applied to the * objects referring to {@code targetObjects} via {@code path[path.length - 1]}, etc., down to {@code filters[0]}, which * applies to the objects at the start of the path being inverted. {@code filters} or any element therein may be null to * indicate no restriction. * * @param path path of zero or more reference fields (represented by storage IDs) through which to reach the target objects; * negated values denote an inverse traversal of the corresponding reference field * @param filters if not null, an array of length {@code path.length + 1} containing optional filters to be applied * to object ID's after the corresponding steps in the path * @param targetObjects target objects * @return read-only set of objects that refer to the {@code targetObjects} via {@code path} restricted by {@code filters} * @throws UnknownFieldException if {@code path} contains a storage ID that does not correspond to a {@link ReferenceField} * @throws IllegalArgumentException if {@code targetObjects} or {@code path} is null * @throws IllegalArgumentException if {@code filters} is not null and does not have length {@code path.length + 1} * @throws StaleTransactionException if this transaction is no longer usable */ public NavigableSet<ObjId> invertReferencePath(int[] path, KeyRanges[] filters, Iterable<? extends ObjId> targetObjects) { // Invert path final int[] invertedPath = new int[path.length]; int i = 0; int j = path.length; while (i < path.length) invertedPath[i++] = -path[--j]; // Invert filters final KeyRanges[] invertedFilters; if (filters != null) { invertedFilters = new KeyRanges[filters.length]; i = 0; j = invertedFilters.length; while (i < invertedFilters.length) invertedFilters[i++] = filters[--j]; } else invertedFilters = null; // Follow inverted path return this.followReferencePath(targetObjects, invertedPath, invertedFilters); } private ArrayList<NavigableSet<ObjId>> traverseReference(Iterable<? extends ObjId> objects, int referenceId, KeyRanges filter) { assert objects != null; // Check forward vs. inverse and get storage info final boolean inverse = referenceId < 0; final int storageId = inverse ? -referenceId : referenceId; final SimpleFieldStorageInfo<ObjId> info = this.verifyReferenceFieldStorageInfo(storageId); // Traverse reference from each object final ArrayList<NavigableSet<ObjId>> refsList = new ArrayList<>(); if (inverse) { // Get index and apply filter, if any CoreIndex<ObjId, ObjId> index = info.getIndex(this); if (filter != null) index = index.filter(1, filter); final NavigableMap<ObjId, NavigableSet<ObjId>> indexMap = index.asMap(); // Query for each ID in the index for (ObjId id : objects) { final NavigableSet<ObjId> refs = indexMap.get(id); if (refs != null) refsList.add(refs); } } else { final ObjIdSet refs = new ObjIdSet(); final Predicate<ObjId> idFilter = filter != null ? id -> filter.contains(id.getBytes()) : null; for (ObjId id : objects) info.readAllNonNull(this, id, refs, idFilter); if (!refs.isEmpty()) refsList.add(refs.sortedSnapshot()); } // Done return refsList; } // Verify all fields in the path are reference fields private void verifyReferencePath(int[] path) { for (int pathId : path) { final int storageId = pathId < 0 ? -pathId : pathId; this.verifyReferenceFieldStorageInfo(storageId); } } @SuppressWarnings("unchecked") private SimpleFieldStorageInfo<ObjId> verifyReferenceFieldStorageInfo(int storageId) { final SimpleFieldStorageInfo<?> info = this.schemas.verifyStorageInfo(storageId, SimpleFieldStorageInfo.class); if (!(info.fieldType instanceof ReferenceFieldType)) throw new IllegalArgumentException(info + " is not a reference field"); return (SimpleFieldStorageInfo<ObjId>)info; } // Index Queries /** * Find all values stored in the specified {@link SimpleField} and, for each value, * the set of all objects having that value in the field. * * <p> * The {@code storageId} may refer to any {@link SimpleField}, whether part of an object or a sub-field * of a {@link ComplexField}. * * <p> * The returned index contains objects from all recorded schema versions for which the field is indexed; * this method does not check whether any such schema versions exist. * * @param storageId {@link SimpleField}'s storage ID * @return read-only, real-time view of field values mapped to sets of objects with the value in the field * @throws UnknownFieldException if no {@link SimpleField} corresponding to {@code storageId} exists * @throws StaleTransactionException if this transaction is no longer usable */ public synchronized CoreIndex<?, ObjId> queryIndex(int storageId) { if (this.stale) throw new StaleTransactionException(this); final SimpleFieldStorageInfo<?> info = this.schemas.verifyStorageInfo(storageId, SimpleFieldStorageInfo.class); return info.getIndex(this); } /** * Find all values stored as an element in the specified {@link ListField} and, for each such value, * the set of all objects having that value as an element in the list and the corresponding list index. * * <p> * The returned index contains objects from all recorded schema versions for which the list element field is indexed; * this method does not check whether any such schema versions exist. * * @param storageId {@link ListField}'s element sub-field storage ID * @return read-only, real-time view of list element values, objects with the value in the list, and corresponding indices * @throws UnknownFieldException if no {@link ListField} element sub-field corresponding to {@code storageId} exists * @throws StaleTransactionException if this transaction is no longer usable */ public synchronized CoreIndex2<?, ObjId, Integer> queryListElementIndex(int storageId) { if (this.stale) throw new StaleTransactionException(this); final ListElementStorageInfo<?> info = this.schemas.verifyStorageInfo(storageId, ListElementStorageInfo.class); return info.getElementIndex(this); } /** * Find all values stored as a value in the specified {@link MapField} and, for each such value, * the set of all objects having that value as a value in the map and the corresponding key. * * <p> * The returned index contains objects from all recorded schema versions for which the map value field is indexed; * this method does not check whether any such schema versions exist. * * @param storageId {@link MapField}'s value sub-field storage ID * @return read-only, real-time view of map values, objects with the value in the map, and corresponding keys * @throws UnknownFieldException if no {@link MapField} value sub-field corresponding to {@code storageId} exists * @throws StaleTransactionException if this transaction is no longer usable */ public synchronized CoreIndex2<?, ObjId, ?> queryMapValueIndex(int storageId) { if (this.stale) throw new StaleTransactionException(this); final MapValueStorageInfo<?, ?> info = this.schemas.verifyStorageInfo(storageId, MapValueStorageInfo.class); return info.getValueIndex(this); } /** * Access a composite index on two fields. * * <p> * The returned index contains objects from all recorded schema versions in which the composite index is defined. * * @param storageId composite index's storage ID * @return read-only, real-time view of the fields' values and the objects having those values in the fields * @throws UnknownIndexException if {@code storageID} is unknown or does not correspond to a composite index on two fields * @throws StaleTransactionException if this transaction is no longer usable */ @SuppressWarnings("unchecked") public CoreIndex2<?, ?, ObjId> queryCompositeIndex2(int storageId) { final CompositeIndexStorageInfo indexInfo = this.schemas.verifyStorageInfo(storageId, CompositeIndexStorageInfo.class); final Object index = indexInfo.getIndex(this); if (!(index instanceof CoreIndex2)) { throw new UnknownIndexException(storageId, "the composite index with storage ID " + storageId + " is on " + indexInfo.storageIds.size() + " != 2 fields"); } return (CoreIndex2<?, ?, ObjId>)index; } /** * Access a composite index on three fields. * * <p> * The returned index contains objects from all recorded schema versions in which the composite index is defined. * * @param storageId composite index's storage ID * @return read-only, real-time view of the fields' values and the objects having those values in the fields * @throws UnknownIndexException if {@code storageID} is unknown or does not correspond to a composite index on two fields * @throws StaleTransactionException if this transaction is no longer usable */ @SuppressWarnings("unchecked") public CoreIndex3<?, ?, ?, ObjId> queryCompositeIndex3(int storageId) { final CompositeIndexStorageInfo indexInfo = this.schemas.verifyStorageInfo(storageId, CompositeIndexStorageInfo.class); final Object index = indexInfo.getIndex(this); if (!(index instanceof CoreIndex3)) { throw new UnknownIndexException(storageId, "the composite index with storage ID " + storageId + " is on " + indexInfo.storageIds.size() + " != 3 fields"); } return (CoreIndex3<?, ?, ?, ObjId>)index; } /** * Access a composite index on four fields. * * <p> * The returned index contains objects from all recorded schema versions in which the composite index is defined. * * @param storageId composite index's storage ID * @return read-only, real-time view of the fields' values and the objects having those values in the fields * @throws UnknownIndexException if {@code storageID} is unknown or does not correspond to a composite index on two fields * @throws StaleTransactionException if this transaction is no longer usable */ @SuppressWarnings("unchecked") public CoreIndex4<?, ?, ?, ?, ObjId> queryCompositeIndex4(int storageId) { final CompositeIndexStorageInfo indexInfo = this.schemas.verifyStorageInfo(storageId, CompositeIndexStorageInfo.class); final Object index = indexInfo.getIndex(this); if (!(index instanceof CoreIndex4)) { throw new UnknownIndexException(storageId, "the composite index with storage ID " + storageId + " is on " + indexInfo.storageIds.size() + " != 4 fields"); } return (CoreIndex4<?, ?, ?, ?, ObjId>)index; } /** * Access any composite index by storage ID, regardless of the number of fields indexed. * * <p> * The returned index contains objects from all recorded schema versions in which the composite index is defined. * * @param storageId composite index's storage ID * @return read-only, real-time view of the fields' values and the objects having those values in the fields * @throws UnknownIndexException if {@code storageID} is unknown or does not correspond to a composite index * @throws StaleTransactionException if this transaction is no longer usable */ public Object queryCompositeIndex(int storageId) { final CompositeIndexStorageInfo indexInfo = this.schemas.verifyStorageInfo(storageId, CompositeIndexStorageInfo.class); return indexInfo.getIndex(this); } /** * Find all objects that refer to the given target object through the/any reference field with the specified * {@link DeleteAction}. * * <p> * Because different schema versions can have different {@link DeleteAction}'s configured for the * same field, we have to iterate through each schema version separately. * * @param target referred-to object * @param onDelete {@link DeleteAction} to match * @return mapping from reference field storage ID to set of objects referring to {@code target} through a field whose * {@link DeleteAction} matches {@code onDelete} */ @SuppressWarnings("unchecked") private TreeMap<Integer, NavigableSet<ObjId>> findReferrers(ObjId target, DeleteAction onDelete) { assert Thread.holdsLock(this); // Get target object type storage ID final int targetStorageId = target.getStorageId(); // Determine which schema versions actually have objects that exist; if there's only one we can slightly optimize below final ArrayList<Map.Entry<Integer, NavigableSet<ObjId>>> versionList = new ArrayList<>(5); versionList.addAll(this.queryVersion().asMap().entrySet()); final boolean multipleVersions = versionList.size() > 1; // Search for objects one schema version at a time, and group them by reference field final TreeMap<Integer, Object> result = new TreeMap<>(); for (Map.Entry<Integer, NavigableSet<ObjId>> versionListEntry : versionList) { final int schemaVersionNumber = versionListEntry.getKey(); final NavigableSet<ObjId> schemaVersionRefs = versionListEntry.getValue(); // Get corresponding Schema object final Schema schemaVersion = this.schemas.versions.get(schemaVersionNumber); if (schemaVersion == null) throw new InconsistentDatabaseException("encountered objects with unknown schema version " + schemaVersionNumber); // Iterate over reference fields in this schema version that have the configured DeleteAction in some object type for (Map.Entry<ReferenceField, KeyRanges> fieldRangeEntry : schemaVersion.deleteActionKeyRanges.get(onDelete.ordinal()).entrySet()) { final ReferenceField field = fieldRangeEntry.getKey(); final KeyRanges keyRanges = fieldRangeEntry.getValue(); // Do a quick check to see whether this field can possibly refer to the target object final SortedSet<Integer> targetTypes = field.getObjectTypes(); if (targetTypes != null && !targetTypes.contains(targetStorageId)) continue; // Build the key prefix for the target object ID in this field's index final int fieldStorageId = field.storageId; final ByteWriter writer = new ByteWriter(UnsignedIntEncoder.encodeLength(fieldStorageId) + ObjId.NUM_BYTES); UnsignedIntEncoder.write(writer, fieldStorageId); target.writeTo(writer); final byte[] prefix = writer.getBytes(); // Query the index to get all objects referring to the target object through this field (in any schema version) final IndexSet<ObjId> indexSet = new IndexSet<>(this.kvt, FieldTypeRegistry.OBJ_ID, true, prefix); // Now restrict those referrers to only those object types where the field's DeleteAction matches (if necessary) NavigableSet<ObjId> referrers = keyRanges != null ? indexSet.filterKeys(keyRanges) : indexSet; // Anything there? if (referrers.isEmpty()) continue; // Add these referrers, restricted to the current schema version, to our list of referrers for this field if (multipleVersions) { ((ArrayList<NavigableSet<ObjId>>)result .computeIfAbsent(fieldStorageId, i -> new ArrayList<NavigableSet<ObjId>>(versionList.size()))) .add(NavigableSets.intersection(schemaVersionRefs, referrers)); } else result.put(fieldStorageId, referrers); // no schema version restriction necessary; no list needed } } // If there were multiple schema versions, for each reference field, take the union of the sets from each schema version if (multipleVersions) { for (Map.Entry<Integer, Object> entry : result.entrySet()) { final ArrayList<NavigableSet<ObjId>> list = (ArrayList<NavigableSet<ObjId>>)entry.getValue(); final NavigableSet<ObjId> union = list.size() == 1 ? list.get(0) : NavigableSets.union(list); entry.setValue(union); } } // Return referrer sets grouped by reference field return (TreeMap<Integer, NavigableSet<ObjId>>)(Object)result; } private byte[] buildCompositeIndexEntry(ObjId id, CompositeIndex index) { return Transaction.buildCompositeIndexEntry(this, id, index); } private static byte[] buildDefaultCompositeIndexEntry(ObjId id, CompositeIndex index) { return Transaction.buildCompositeIndexEntry(null, id, index); } private static byte[] buildCompositeIndexEntry(Transaction tx, ObjId id, CompositeIndex index) { final ByteWriter writer = new ByteWriter(); UnsignedIntEncoder.write(writer, index.storageId); for (SimpleField<?> field : index.fields) { final byte[] value = tx != null ? tx.kvt.get(field.buildKey(id)) : null; writer.write(value != null ? value : field.fieldType.getDefaultValue()); } id.writeTo(writer); return writer.getBytes(); } // Listener snapshots /** * Create a read-only snapshot of all ({@link CreateListener}s, {@link DeleteListener}s, {@link VersionChangeListener}s, * {@link SimpleFieldChangeListener}s, {@link SetFieldChangeListener}s, {@link ListFieldChangeListener}s, and * {@link MapFieldChangeListener}s currently registered on this instance. * * <p> * The snapshot can be applied to other transactions having compatible schemas via {@link #setListeners setListeners()}. * Use of a {@link ListenerSet} also allows certain internal optimizations. * * @return snapshot of listeners associated with this instance * @see #setListeners setListeners() */ public synchronized ListenerSet snapshotListeners() { return new ListenerSet(this); } /** * Apply a snapshot created via {@link #snapshotListeners} to this instance. * * <p> * Any currently registered listeners are unregistered and replaced by the listeners in {@code listeners}. * This method may be invoked multiple times; however, once this method has been invoked, any subsequent * attempts to register or unregister individual listeners will result in an {@link UnsupportedOperationException}. * * @param listeners listener set created by {@link #snapshotListeners} * @throws IllegalArgumentException if {@code listeners} was created from a transaction with an incompatible schema * @throws IllegalArgumentException if {@code listeners} is null */ public synchronized void setListeners(ListenerSet listeners) { Preconditions.checkArgument(listeners != null, "null listeners"); // Verify field change listeners are compatible with this transaction while (listeners.monitorMap != null) { // Do a quick check if (Arrays.equals(listeners.schema.encodedXML, this.schema.encodedXML)) break; // Do a slow check if (listeners.schema.schemaModel.isCompatibleWith(this.schema.schemaModel)) break; // Not compatible throw new IllegalArgumentException("listener set was created from a transaction having an incompatible schema"); } // Apply listeners to this instance this.versionChangeListeners = listeners.versionChangeListeners; this.createListeners = listeners.createListeners; this.deleteListeners = listeners.deleteListeners; this.monitorMap = listeners.monitorMap; this.hasFieldMonitorCache = listeners.hasFieldMonitorCache; this.listenerSetInstalled = true; } // User Object /** * Associate an arbitrary object with this instance. * * @param obj user object */ public synchronized void setUserObject(Object obj) { this.userObject = obj; } /** * Get the object with this instance by {@link #setUserObject setUserObject()}, if any. * * @return the associated user object, or null if none has been set */ public synchronized Object getUserObject() { return this.userObject; } // Mutation interface Mutation<V> { V mutate(); } // SimpleFieldChangeNotifier private abstract static class SimpleFieldChangeNotifier extends FieldChangeNotifier<SimpleFieldChangeListener> { SimpleFieldChangeNotifier(SimpleField<?> field, ObjId id) { super(SimpleFieldChangeListener.class, field.storageId, id); } } // Callback /** * Callback interface for notification of transaction completion events. * Callbacks are registered with a transaction via {@link Transaction#addCallback Transaction.addCallback()}, * and are executed in the order registered, in the same thread that just committed (or rolled back) the transaction. * * <p> * Modeled after Spring's {@link org.springframework.transaction.support.TransactionSynchronization} interface. * * @see Transaction#addCallback Transaction.addCallback() */ public interface Callback { /** * Invoked before transaction commit (and before {@link #beforeCompletion}). * This method is invoked when a transaction is intended to be committed; it may however still be rolled back. * * <p> * Any exceptions thrown will result in a transaction rollback and be propagated to the caller. * * @param readOnly true if the transaction {@linkplain Transaction#isReadOnly is marked read-only} */ void beforeCommit(boolean readOnly); /** * Invoked before transaction completion in any case (but after any {@link #beforeCommit beforeCommit()}). * This method is invoked whether the transaction is going to be committed or rolled back, * and is invoked even if {@link #beforeCommit beforeCommit()} throws an exception. * Typically used to clean up resources before transaction completion. * * <p> * Any exceptions thrown will be logged but will <b>not</b> propagate to the caller. */ void beforeCompletion(); /** * Invoked after successful transaction commit (and before {@link #afterCompletion afterCompletion()}). * * <p> * Any exceptions thrown will propagate to the caller. */ void afterCommit(); /** * Invoked after transaction completion (but after any {@link #afterCommit}). * This method is invoked in any case, whether the transaction was committed or rolled back. * Typically used to clean up resources after transaction completion. * * <p> * Any exceptions thrown will be logged but will <b>not</b> propagate to the caller. * * @param committed true if transaction was commited, false if transaction was rolled back */ void afterCompletion(boolean committed); } /** * Adapter class for {@link Callback}. * * <p> * All the implementations in this class do nothing. */ public static class CallbackAdapter implements Callback { @Override public void beforeCommit(boolean readOnly) { } @Override public void beforeCompletion() { } @Override public void afterCommit() { } @Override public void afterCompletion(boolean committed) { } } // Listeners /** * A fixed collection of listeners ({@link CreateListener}s, {@link DeleteListener}s, {@link VersionChangeListener}s, * {@link SimpleFieldChangeListener}s, {@link SetFieldChangeListener}s, {@link ListFieldChangeListener}s, and * {@link MapFieldChangeListener}s) that can be efficiently registered on a {@link Transaction} all at once. * * <p> * To create an instance of this class, use {@link Transaction#snapshotListeners} after registering the desired * set of listeners. Once created, the instance can be used repeatedly to configured the same set of listeners * on any other compatible {@link Transaction} via {@link Transaction#setListeners Transaction.setListeners()}. * Here "compatible" means field change listener paths and types are valid for the new transaction's schemas. */ public static final class ListenerSet { final Set<VersionChangeListener> versionChangeListeners; final Set<CreateListener> createListeners; final Set<DeleteListener> deleteListeners; final NavigableMap<Integer, Set<FieldMonitor>> monitorMap; final NavigableSet<Long> hasFieldMonitorCache; final Schema schema; private ListenerSet(Transaction tx) { assert Thread.holdsLock(tx); this.versionChangeListeners = tx.versionChangeListeners != null ? Collections.unmodifiableSet(new HashSet<>(tx.versionChangeListeners)) : null; this.createListeners = tx.createListeners != null ? Collections.unmodifiableSet(new HashSet<>(tx.createListeners)) : null; this.deleteListeners = tx.deleteListeners != null ? Collections.unmodifiableSet(new HashSet<>(tx.deleteListeners)) : null; if (tx.monitorMap != null) { final TreeMap<Integer, Set<FieldMonitor>> monitorMapSnapshot = new TreeMap<>(); for (Map.Entry<Integer, Set<FieldMonitor>> entry : tx.monitorMap.entrySet()) monitorMapSnapshot.put(entry.getKey(), Collections.unmodifiableSet(entry.getValue())); this.monitorMap = Collections.unmodifiableNavigableMap(monitorMapSnapshot); } else this.monitorMap = null; this.hasFieldMonitorCache = tx.buildHasFieldMonitorCache(); this.schema = tx.schema; } } // MonitoredPredicate // Matches FieldMonitors who monitor the specified field in the specified object type private static final class MonitoredPredicate implements Predicate<FieldMonitor> { private final byte[] objTypeBytes; private final int fieldStorageId; MonitoredPredicate(int objTypeStorageId, int fieldStorageId) { this.objTypeBytes = ObjId.getMin(objTypeStorageId).getBytes(); this.fieldStorageId = fieldStorageId; } @Override public boolean test(FieldMonitor monitor) { assert monitor != null; if (monitor.storageId != this.fieldStorageId) return false; final KeyRanges filter = monitor.getTargetFilter(); return filter == null || filter.contains(this.objTypeBytes); } } }
/* * Copyright 2002-2018 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.security.config.annotation.web.configuration; import java.lang.reflect.Field; import java.util.Arrays; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.springframework.aop.TargetSource; import org.springframework.aop.framework.Advised; import org.springframework.aop.target.LazyInitTargetSource; import org.springframework.beans.FatalBeanException; import org.springframework.beans.factory.BeanFactoryUtils; import org.springframework.beans.factory.NoSuchBeanDefinitionException; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.ApplicationContext; import org.springframework.core.annotation.Order; import org.springframework.core.io.support.SpringFactoriesLoader; import org.springframework.security.authentication.AuthenticationEventPublisher; import org.springframework.security.authentication.AuthenticationManager; import org.springframework.security.authentication.AuthenticationTrustResolver; import org.springframework.security.authentication.AuthenticationTrustResolverImpl; import org.springframework.security.authentication.DefaultAuthenticationEventPublisher; import org.springframework.security.config.annotation.ObjectPostProcessor; import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder; import org.springframework.security.config.annotation.authentication.configuration.AuthenticationConfiguration; import org.springframework.security.config.annotation.authentication.configurers.provisioning.InMemoryUserDetailsManagerConfigurer; import org.springframework.security.config.annotation.authentication.configurers.provisioning.JdbcUserDetailsManagerConfigurer; import org.springframework.security.config.annotation.authentication.configurers.userdetails.DaoAuthenticationConfigurer; import org.springframework.security.config.annotation.web.WebSecurityConfigurer; import org.springframework.security.config.annotation.web.builders.HttpSecurity; import org.springframework.security.config.annotation.web.builders.WebSecurity; import org.springframework.security.config.annotation.web.configurers.AbstractHttpConfigurer; import org.springframework.security.config.annotation.web.configurers.DefaultLoginPageConfigurer; import org.springframework.security.config.annotation.web.configurers.SecurityContextConfigurer; import org.springframework.security.core.Authentication; import org.springframework.security.core.AuthenticationException; import org.springframework.security.core.userdetails.UserDetails; import org.springframework.security.core.userdetails.UserDetailsService; import org.springframework.security.core.userdetails.UsernameNotFoundException; import org.springframework.security.crypto.factory.PasswordEncoderFactories; import org.springframework.security.crypto.password.PasswordEncoder; import org.springframework.security.web.access.intercept.FilterSecurityInterceptor; import org.springframework.security.web.context.request.async.WebAsyncManagerIntegrationFilter; import org.springframework.util.Assert; import org.springframework.util.ReflectionUtils; import org.springframework.web.accept.ContentNegotiationStrategy; import org.springframework.web.accept.HeaderContentNegotiationStrategy; /** * Provides a convenient base class for creating a {@link WebSecurityConfigurer} instance. * The implementation allows customization by overriding methods. * * <p> * Will automatically apply the result of looking up {@link AbstractHttpConfigurer} from * {@link SpringFactoriesLoader} to allow developers to extend the defaults. To do this, * you must create a class that extends AbstractHttpConfigurer and then create a file in * the classpath at "META-INF/spring.factories" that looks something like: * </p> * <pre> * org.springframework.security.config.annotation.web.configurers.AbstractHttpConfigurer = sample.MyClassThatExtendsAbstractHttpConfigurer * </pre> If you have multiple classes that should be added you can use "," to separate * the values. For example: * * <pre> * org.springframework.security.config.annotation.web.configurers.AbstractHttpConfigurer = sample.MyClassThatExtendsAbstractHttpConfigurer, sample.OtherThatExtendsAbstractHttpConfigurer * </pre> * * @see EnableWebSecurity * @author Rob Winch */ @Order(100) public abstract class WebSecurityConfigurerAdapter implements WebSecurityConfigurer<WebSecurity> { private final Log logger = LogFactory.getLog(WebSecurityConfigurerAdapter.class); private ApplicationContext context; private ContentNegotiationStrategy contentNegotiationStrategy = new HeaderContentNegotiationStrategy(); private ObjectPostProcessor<Object> objectPostProcessor = new ObjectPostProcessor<Object>() { @Override public <T> T postProcess(T object) { throw new IllegalStateException(ObjectPostProcessor.class.getName() + " is a required bean. Ensure you have used @EnableWebSecurity and @Configuration"); } }; private AuthenticationConfiguration authenticationConfiguration; private AuthenticationManagerBuilder authenticationBuilder; private AuthenticationManagerBuilder localConfigureAuthenticationBldr; private boolean disableLocalConfigureAuthenticationBldr; private boolean authenticationManagerInitialized; private AuthenticationManager authenticationManager; private AuthenticationTrustResolver trustResolver = new AuthenticationTrustResolverImpl(); private HttpSecurity http; private boolean disableDefaults; /** * Creates an instance with the default configuration enabled. */ protected WebSecurityConfigurerAdapter() { this(false); } /** * Creates an instance which allows specifying if the default configuration should be * enabled. Disabling the default configuration should be considered more advanced * usage as it requires more understanding of how the framework is implemented. * @param disableDefaults true if the default configuration should be disabled, else * false */ protected WebSecurityConfigurerAdapter(boolean disableDefaults) { this.disableDefaults = disableDefaults; } /** * Used by the default implementation of {@link #authenticationManager()} to attempt * to obtain an {@link AuthenticationManager}. If overridden, the * {@link AuthenticationManagerBuilder} should be used to specify the * {@link AuthenticationManager}. * * <p> * The {@link #authenticationManagerBean()} method can be used to expose the resulting * {@link AuthenticationManager} as a Bean. The {@link #userDetailsServiceBean()} can * be used to expose the last populated {@link UserDetailsService} that is created * with the {@link AuthenticationManagerBuilder} as a Bean. The * {@link UserDetailsService} will also automatically be populated on * {@link HttpSecurity#getSharedObject(Class)} for use with other * {@link SecurityContextConfigurer} (i.e. RememberMeConfigurer ) * </p> * * <p> * For example, the following configuration could be used to register in memory * authentication that exposes an in memory {@link UserDetailsService}: * </p> * * <pre> * &#064;Override * protected void configure(AuthenticationManagerBuilder auth) { * auth * // enable in memory based authentication with a user named * // &quot;user&quot; and &quot;admin&quot; * .inMemoryAuthentication().withUser(&quot;user&quot;).password(&quot;password&quot;).roles(&quot;USER&quot;).and() * .withUser(&quot;admin&quot;).password(&quot;password&quot;).roles(&quot;USER&quot;, &quot;ADMIN&quot;); * } * * // Expose the UserDetailsService as a Bean * &#064;Bean * &#064;Override * public UserDetailsService userDetailsServiceBean() throws Exception { * return super.userDetailsServiceBean(); * } * * </pre> * @param auth the {@link AuthenticationManagerBuilder} to use * @throws Exception */ protected void configure(AuthenticationManagerBuilder auth) throws Exception { this.disableLocalConfigureAuthenticationBldr = true; } /** * Creates the {@link HttpSecurity} or returns the current instance * @return the {@link HttpSecurity} * @throws Exception */ @SuppressWarnings({ "rawtypes", "unchecked" }) protected final HttpSecurity getHttp() throws Exception { if (this.http != null) { return this.http; } AuthenticationEventPublisher eventPublisher = getAuthenticationEventPublisher(); this.localConfigureAuthenticationBldr.authenticationEventPublisher(eventPublisher); AuthenticationManager authenticationManager = authenticationManager(); this.authenticationBuilder.parentAuthenticationManager(authenticationManager); Map<Class<?>, Object> sharedObjects = createSharedObjects(); this.http = new HttpSecurity(this.objectPostProcessor, this.authenticationBuilder, sharedObjects); if (!this.disableDefaults) { applyDefaultConfiguration(this.http); ClassLoader classLoader = this.context.getClassLoader(); List<AbstractHttpConfigurer> defaultHttpConfigurers = SpringFactoriesLoader .loadFactories(AbstractHttpConfigurer.class, classLoader); for (AbstractHttpConfigurer configurer : defaultHttpConfigurers) { this.http.apply(configurer); } } configure(this.http); return this.http; } private void applyDefaultConfiguration(HttpSecurity http) throws Exception { http.csrf(); http.addFilter(new WebAsyncManagerIntegrationFilter()); http.exceptionHandling(); http.headers(); http.sessionManagement(); http.securityContext(); http.requestCache(); http.anonymous(); http.servletApi(); http.apply(new DefaultLoginPageConfigurer<>()); http.logout(); } /** * Override this method to expose the {@link AuthenticationManager} from * {@link #configure(AuthenticationManagerBuilder)} to be exposed as a Bean. For * example: * * <pre> * &#064;Bean(name name="myAuthenticationManager") * &#064;Override * public AuthenticationManager authenticationManagerBean() throws Exception { * return super.authenticationManagerBean(); * } * </pre> * @return the {@link AuthenticationManager} * @throws Exception */ public AuthenticationManager authenticationManagerBean() throws Exception { return new AuthenticationManagerDelegator(this.authenticationBuilder, this.context); } /** * Gets the {@link AuthenticationManager} to use. The default strategy is if * {@link #configure(AuthenticationManagerBuilder)} method is overridden to use the * {@link AuthenticationManagerBuilder} that was passed in. Otherwise, autowire the * {@link AuthenticationManager} by type. * @return the {@link AuthenticationManager} to use * @throws Exception */ protected AuthenticationManager authenticationManager() throws Exception { if (!this.authenticationManagerInitialized) { configure(this.localConfigureAuthenticationBldr); if (this.disableLocalConfigureAuthenticationBldr) { this.authenticationManager = this.authenticationConfiguration.getAuthenticationManager(); } else { this.authenticationManager = this.localConfigureAuthenticationBldr.build(); } this.authenticationManagerInitialized = true; } return this.authenticationManager; } /** * Override this method to expose a {@link UserDetailsService} created from * {@link #configure(AuthenticationManagerBuilder)} as a bean. In general only the * following override should be done of this method: * * <pre> * &#064;Bean(name = &quot;myUserDetailsService&quot;) * // any or no name specified is allowed * &#064;Override * public UserDetailsService userDetailsServiceBean() throws Exception { * return super.userDetailsServiceBean(); * } * </pre> * * To change the instance returned, developers should change * {@link #userDetailsService()} instead * @return the {@link UserDetailsService} * @throws Exception * @see #userDetailsService() */ public UserDetailsService userDetailsServiceBean() throws Exception { AuthenticationManagerBuilder globalAuthBuilder = this.context.getBean(AuthenticationManagerBuilder.class); return new UserDetailsServiceDelegator(Arrays.asList(this.localConfigureAuthenticationBldr, globalAuthBuilder)); } /** * Allows modifying and accessing the {@link UserDetailsService} from * {@link #userDetailsServiceBean()} without interacting with the * {@link ApplicationContext}. Developers should override this method when changing * the instance of {@link #userDetailsServiceBean()}. * @return the {@link UserDetailsService} to use */ protected UserDetailsService userDetailsService() { AuthenticationManagerBuilder globalAuthBuilder = this.context.getBean(AuthenticationManagerBuilder.class); return new UserDetailsServiceDelegator(Arrays.asList(this.localConfigureAuthenticationBldr, globalAuthBuilder)); } @Override public void init(WebSecurity web) throws Exception { HttpSecurity http = getHttp(); /** * 把HttpSecurity作为一条过滤器添加到过滤器链中 */ web.addSecurityFilterChainBuilder(http).postBuildAction(() -> { FilterSecurityInterceptor securityInterceptor = http.getSharedObject(FilterSecurityInterceptor.class); web.securityInterceptor(securityInterceptor); }); } /** * Override this method to configure {@link WebSecurity}. For example, if you wish to * ignore certain requests. * * Endpoints specified in this method will be ignored by Spring Security, meaning it * will not protect them from CSRF, XSS, Clickjacking, and so on. * * Instead, if you want to protect endpoints against common vulnerabilities, then see * {@link #configure(HttpSecurity)} and the {@link HttpSecurity#authorizeRequests} * configuration method. */ @Override public void configure(WebSecurity web) throws Exception { } /** * Override this method to configure the {@link HttpSecurity}. Typically subclasses * should not invoke this method by calling super as it may override their * configuration. The default configuration is: * * <pre> * http.authorizeRequests().anyRequest().authenticated().and().formLogin().and().httpBasic(); * </pre> * * Any endpoint that requires defense against common vulnerabilities can be specified * here, including public ones. See {@link HttpSecurity#authorizeRequests} and the * `permitAll()` authorization rule for more details on public endpoints. * @param http the {@link HttpSecurity} to modify * @throws Exception if an error occurs */ protected void configure(HttpSecurity http) throws Exception { this.logger.debug("Using default configure(HttpSecurity). " + "If subclassed this will potentially override subclass configure(HttpSecurity)."); http.authorizeRequests((requests) -> requests.anyRequest().authenticated()); http.formLogin(); http.httpBasic(); } /** * Gets the ApplicationContext * @return the context */ protected final ApplicationContext getApplicationContext() { return this.context; } @Autowired public void setApplicationContext(ApplicationContext context) { this.context = context; ObjectPostProcessor<Object> objectPostProcessor = context.getBean(ObjectPostProcessor.class); /** * 生成passwordEncoder */ LazyPasswordEncoder passwordEncoder = new LazyPasswordEncoder(context); this.authenticationBuilder = new DefaultPasswordEncoderAuthenticationManagerBuilder(objectPostProcessor, passwordEncoder); this.localConfigureAuthenticationBldr = new DefaultPasswordEncoderAuthenticationManagerBuilder( objectPostProcessor, passwordEncoder) { @Override public AuthenticationManagerBuilder eraseCredentials(boolean eraseCredentials) { WebSecurityConfigurerAdapter.this.authenticationBuilder.eraseCredentials(eraseCredentials); return super.eraseCredentials(eraseCredentials); } @Override public AuthenticationManagerBuilder authenticationEventPublisher( AuthenticationEventPublisher eventPublisher) { WebSecurityConfigurerAdapter.this.authenticationBuilder.authenticationEventPublisher(eventPublisher); return super.authenticationEventPublisher(eventPublisher); } }; } @Autowired(required = false) public void setTrustResolver(AuthenticationTrustResolver trustResolver) { this.trustResolver = trustResolver; } @Autowired(required = false) public void setContentNegotationStrategy(ContentNegotiationStrategy contentNegotiationStrategy) { this.contentNegotiationStrategy = contentNegotiationStrategy; } @Autowired public void setObjectPostProcessor(ObjectPostProcessor<Object> objectPostProcessor) { this.objectPostProcessor = objectPostProcessor; } @Autowired public void setAuthenticationConfiguration(AuthenticationConfiguration authenticationConfiguration) { this.authenticationConfiguration = authenticationConfiguration; } private AuthenticationEventPublisher getAuthenticationEventPublisher() { if (this.context.getBeanNamesForType(AuthenticationEventPublisher.class).length > 0) { return this.context.getBean(AuthenticationEventPublisher.class); } return this.objectPostProcessor.postProcess(new DefaultAuthenticationEventPublisher()); } /** * Creates the shared objects * @return the shared Objects * 将 */ private Map<Class<?>, Object> createSharedObjects() { Map<Class<?>, Object> sharedObjects = new HashMap<>(); sharedObjects.putAll(this.localConfigureAuthenticationBldr.getSharedObjects()); sharedObjects.put(UserDetailsService.class, userDetailsService()); sharedObjects.put(ApplicationContext.class, this.context); sharedObjects.put(ContentNegotiationStrategy.class, this.contentNegotiationStrategy); sharedObjects.put(AuthenticationTrustResolver.class, this.trustResolver); return sharedObjects; } /** * Delays the use of the {@link UserDetailsService} from the * {@link AuthenticationManagerBuilder} to ensure that it has been fully configured. * * @author Rob Winch * @since 3.2 */ static final class UserDetailsServiceDelegator implements UserDetailsService { private List<AuthenticationManagerBuilder> delegateBuilders; private UserDetailsService delegate; private final Object delegateMonitor = new Object(); UserDetailsServiceDelegator(List<AuthenticationManagerBuilder> delegateBuilders) { Assert.isTrue(!delegateBuilders.contains(null), () -> "delegateBuilders cannot contain null values. Got " + delegateBuilders); this.delegateBuilders = delegateBuilders; } @Override public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException { if (this.delegate != null) { return this.delegate.loadUserByUsername(username); } synchronized (this.delegateMonitor) { if (this.delegate == null) { for (AuthenticationManagerBuilder delegateBuilder : this.delegateBuilders) { this.delegate = delegateBuilder.getDefaultUserDetailsService(); if (this.delegate != null) { break; } } if (this.delegate == null) { throw new IllegalStateException("UserDetailsService is required."); } this.delegateBuilders = null; } } return this.delegate.loadUserByUsername(username); } } /** * Delays the use of the {@link AuthenticationManager} build from the * {@link AuthenticationManagerBuilder} to ensure that it has been fully configured. * * @author Rob Winch * @since 3.2 */ static final class AuthenticationManagerDelegator implements AuthenticationManager { private AuthenticationManagerBuilder delegateBuilder; private AuthenticationManager delegate; private final Object delegateMonitor = new Object(); private Set<String> beanNames; AuthenticationManagerDelegator(AuthenticationManagerBuilder delegateBuilder, ApplicationContext context) { Assert.notNull(delegateBuilder, "delegateBuilder cannot be null"); Field parentAuthMgrField = ReflectionUtils.findField(AuthenticationManagerBuilder.class, "parentAuthenticationManager"); ReflectionUtils.makeAccessible(parentAuthMgrField); this.beanNames = getAuthenticationManagerBeanNames(context); validateBeanCycle(ReflectionUtils.getField(parentAuthMgrField, delegateBuilder), this.beanNames); this.delegateBuilder = delegateBuilder; } @Override public Authentication authenticate(Authentication authentication) throws AuthenticationException { if (this.delegate != null) { return this.delegate.authenticate(authentication); } synchronized (this.delegateMonitor) { if (this.delegate == null) { this.delegate = this.delegateBuilder.getObject(); this.delegateBuilder = null; } } return this.delegate.authenticate(authentication); } private static Set<String> getAuthenticationManagerBeanNames(ApplicationContext applicationContext) { String[] beanNamesForType = BeanFactoryUtils.beanNamesForTypeIncludingAncestors(applicationContext, AuthenticationManager.class); return new HashSet<>(Arrays.asList(beanNamesForType)); } private static void validateBeanCycle(Object auth, Set<String> beanNames) { if (auth == null || beanNames.isEmpty() || !(auth instanceof Advised)) { return; } TargetSource targetSource = ((Advised) auth).getTargetSource(); if (!(targetSource instanceof LazyInitTargetSource)) { return; } LazyInitTargetSource lits = (LazyInitTargetSource) targetSource; if (beanNames.contains(lits.getTargetBeanName())) { throw new FatalBeanException( "A dependency cycle was detected when trying to resolve the AuthenticationManager. " + "Please ensure you have configured authentication."); } } } static class DefaultPasswordEncoderAuthenticationManagerBuilder extends AuthenticationManagerBuilder { private PasswordEncoder defaultPasswordEncoder; /** * Creates a new instance * @param objectPostProcessor the {@link ObjectPostProcessor} instance to use. */ DefaultPasswordEncoderAuthenticationManagerBuilder(ObjectPostProcessor<Object> objectPostProcessor, PasswordEncoder defaultPasswordEncoder) { super(objectPostProcessor); this.defaultPasswordEncoder = defaultPasswordEncoder; } @Override public InMemoryUserDetailsManagerConfigurer<AuthenticationManagerBuilder> inMemoryAuthentication() throws Exception { return super.inMemoryAuthentication().passwordEncoder(this.defaultPasswordEncoder); } @Override public JdbcUserDetailsManagerConfigurer<AuthenticationManagerBuilder> jdbcAuthentication() throws Exception { return super.jdbcAuthentication().passwordEncoder(this.defaultPasswordEncoder); } @Override public <T extends UserDetailsService> DaoAuthenticationConfigurer<AuthenticationManagerBuilder, T> userDetailsService( T userDetailsService) throws Exception { return super.userDetailsService(userDetailsService).passwordEncoder(this.defaultPasswordEncoder); } } static class LazyPasswordEncoder implements PasswordEncoder { private ApplicationContext applicationContext; private PasswordEncoder passwordEncoder; LazyPasswordEncoder(ApplicationContext applicationContext) { this.applicationContext = applicationContext; } @Override public String encode(CharSequence rawPassword) { return getPasswordEncoder().encode(rawPassword); } @Override public boolean matches(CharSequence rawPassword, String encodedPassword) { return getPasswordEncoder().matches(rawPassword, encodedPassword); } @Override public boolean upgradeEncoding(String encodedPassword) { return getPasswordEncoder().upgradeEncoding(encodedPassword); } private PasswordEncoder getPasswordEncoder() { if (this.passwordEncoder != null) { return this.passwordEncoder; } /** * 如果spring容器中存在PasswordEncoder,就复用,如果不存在,则使用默认的 */ PasswordEncoder passwordEncoder = getBeanOrNull(PasswordEncoder.class); if (passwordEncoder == null) { passwordEncoder = PasswordEncoderFactories.createDelegatingPasswordEncoder(); } this.passwordEncoder = passwordEncoder; return passwordEncoder; } private <T> T getBeanOrNull(Class<T> type) { try { return this.applicationContext.getBean(type); } catch (NoSuchBeanDefinitionException ex) { return null; } } @Override public String toString() { return getPasswordEncoder().toString(); } } }
package com.linkedpipes.plugin.loader.wikibase.model; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.wikidata.wdtk.datamodel.helpers.Datamodel; import org.wikidata.wdtk.datamodel.helpers.ItemDocumentBuilder; import org.wikidata.wdtk.datamodel.helpers.StatementBuilder; import org.wikidata.wdtk.datamodel.interfaces.ItemDocument; import org.wikidata.wdtk.datamodel.interfaces.MonolingualTextValue; import org.wikidata.wdtk.datamodel.interfaces.PropertyIdValue; import org.wikidata.wdtk.datamodel.interfaces.Snak; import org.wikidata.wdtk.datamodel.interfaces.SnakGroup; import org.wikidata.wdtk.datamodel.interfaces.Statement; import org.wikidata.wdtk.datamodel.interfaces.StatementGroup; import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import java.util.stream.Collectors; /** * Should be used only if merge strategy is {@link MergeStrategy#MERGE} * for the whole document. * <p> * As for other strategies respective API operation should be used. * The statements may use other merging strategy. * <p> * The final operation may not be merge is some statements should be removed. */ public class DocumentMerger { private static class StatementId { public final String id; public final PropertyIdValue property; public StatementId(Statement st, PropertyIdValue property) { this.id = st.getStatementId(); this.property = property; } @Override public boolean equals(Object obj) { if (!(obj instanceof StatementId)) { return false; } StatementId right = (StatementId) obj; return this.id.equals(right.id) && this.property.getId().equals(right.property.getId()); } @Override public int hashCode() { // We use only property name hash as they can have // different prefix. return this.id.hashCode() + this.property.getId().hashCode(); } } private static final Logger LOG = LoggerFactory.getLogger(DocumentMerger.class); private final ItemDocument localDocument; private final ItemDocument remoteDocument; private final Map<Object, MergeStrategy> mergeStrategy; private Map<String, String> labelsToAdd = new HashMap<>(); private Map<String, String> labelsToDelete = new HashMap<>(); private Map<String, String> labelsToKeep = new HashMap<>(); private Map<String, String> descriptionsToAdd = new HashMap<>(); private Map<String, String> descriptionsToDelete = new HashMap<>(); private Map<String, String> descriptionsToKeep = new HashMap<>(); private Map<String, Set<String>> aliasesToAdd = new HashMap<>(); private Map<String, Set<String>> aliasesToDelete = new HashMap<>(); private Map<String, Set<String>> aliasesToKeep = new HashMap<>(); private List<Statement> statementsToAdd = new ArrayList<>(); private List<Statement> statementsToDelete = new ArrayList<>(); /** * Statements that have changed. */ private List<Statement> statementsToUpdate = new ArrayList<>(); /** * Statements that does not change. */ private List<Statement> statementsToKeep = new ArrayList<>(); private boolean merged = false; private final SnakEqual snakEqualStrategy; public DocumentMerger( ItemDocument local, ItemDocument remote, Map<Object, MergeStrategy> mergeStrategy, SnakEqual snakEqualStrategy) { this.localDocument = local; this.remoteDocument = remote; this.mergeStrategy = mergeStrategy; this.snakEqualStrategy = snakEqualStrategy; merge(); } private void merge() { if (merged) { return; } merged = true; mergeStringMap( collectAsMap(localDocument.getLabels()), collectAsMap(remoteDocument.getLabels()), labelsToAdd, labelsToDelete, labelsToKeep); mergeStringMap( collectAsMap(localDocument.getDescriptions()), collectAsMap(remoteDocument.getDescriptions()), descriptionsToAdd, descriptionsToDelete, descriptionsToKeep); mergeStringListMap( collectAsListMap(localDocument.getAliases()), collectAsListMap(remoteDocument.getAliases()), aliasesToAdd, aliasesToDelete, aliasesToKeep); mergeStatements(); } private void mergeStringMap( Map<String, String> localMap, Map<String, String> remoteMap, Map<String, String> toAdd, Map<String, String> toDelete, Map<String, String> toKeep) { // By default keep all from remote. toKeep.putAll(remoteMap); // And update with local values. for (Map.Entry<String, String> entry : localMap.entrySet()) { String key = entry.getKey(); if (!toKeep.containsKey(key)) { // This is a new value, so just add it. toAdd.put(key, entry.getValue()); continue; } if (toKeep.get(key).equals(entry.getValue())) { // The values are the same. continue; } // Values are different so we need to replace them. toDelete.put(key, toKeep.get(key)); toAdd.put(key, entry.getValue()); toKeep.remove(key); } } private Map<String, String> collectAsMap( Map<String, MonolingualTextValue> values) { Map<String, String> result = new HashMap<>(); for (Map.Entry<String, MonolingualTextValue> entry : values.entrySet()) { result.put(entry.getKey(), entry.getValue().getText()); } return result; } private void mergeStringListMap( Map<String, Set<String>> localMap, Map<String, Set<String>> remoteMap, Map<String, Set<String>> toAdd, Map<String, Set<String>> toDelete, Map<String, Set<String>> toKeep) { // By default keep all from remote. toKeep.putAll(remoteMap); // And update with local values. for (Map.Entry<String, Set<String>> entry : localMap.entrySet()) { String key = entry.getKey(); if (!toKeep.containsKey(key)) { // This is a new value, so just add it. toAdd.put(key, entry.getValue()); continue; } // There are values in local and remote, we need to merge them. Set<String> localSet = entry.getValue(); Set<String> remoteSet = remoteMap.get(key); Set<String> deleteSet = new HashSet<>(remoteSet); deleteSet.removeAll(localSet); Set<String> addSet = new HashSet<>(localSet); localSet.removeAll(remoteSet); Set<String> keepSet = new HashSet<>(localSet); keepSet.retainAll(remoteSet); // toDelete.put(key, deleteSet); toAdd.put(key, addSet); if (keepSet.isEmpty()) { toKeep.remove(key); } else { toKeep.put(key, keepSet); } } } private Map<String, Set<String>> collectAsListMap( Map<String, List<MonolingualTextValue>> values) { Map<String, Set<String>> result = new HashMap<>(); for (Map.Entry<String, List<MonolingualTextValue>> entry : values.entrySet()) { String lang = entry.getKey(); Set<String> output = result.computeIfAbsent(lang, (key) -> new HashSet<>()); for (MonolingualTextValue value : entry.getValue()) { if (!lang.equals(value.getLanguageCode())) { LOG.warn( "Alias language mismatch {} {}", lang, value.getLanguageCode()); } output.add(value.getText()); } } return result; } private void mergeStatements() { // New items can be only added. List<Statement> localNewSt = collectNewStatements(localDocument); for (Statement statement : localNewSt) { MergeStrategy mergeStrategy = getMergeStrategy(statement); switch (mergeStrategy) { case NEW: statementsToAdd.add(statement); break; case DELETE: case REPLACE: case MERGE: default: throwUnsupportedStrategyForNew(mergeStrategy); } } // Map rest of the items. Map<StatementId, Statement> localSt = statementMap(localDocument); Map<StatementId, Statement> remoteSt = statementMap(remoteDocument); for (Map.Entry<StatementId, Statement> entry : localSt.entrySet()) { MergeStrategy mergeStrategy = getMergeStrategy(entry.getValue()); switch (mergeStrategy) { case DELETE: if (remoteSt.containsKey(entry.getKey())) { remoteSt.remove(entry.getKey()); statementsToDelete.add(entry.getValue()); } break; case NEW: statementsToAdd.add(entry.getValue()); break; case REPLACE: remoteSt.remove(entry.getKey()); statementsToUpdate.add(entry.getValue()); break; case MERGE: if (remoteSt.containsKey(entry.getKey())) { mergeStatement( entry.getValue(), remoteSt.remove(entry.getKey()), entry.getKey().property); } else { statementsToAdd.add(entry.getValue()); } break; default: throwUnsupportedStrategy(entry.getValue(), mergeStrategy); } } // We have some statements in the remoteSt that were not used // these should be kept as they are. statementsToKeep.addAll(remoteSt.values()); } private void throwUnsupportedStrategyForNew(MergeStrategy strategy) { throw new RuntimeException("Unsupported strategy: " + strategy); } private void throwUnsupportedStrategy( Statement statement, MergeStrategy strategy) { throw new RuntimeException( "Unsupported strategy: " + strategy + " for: " + statement.getStatementId()); } private List<Statement> collectNewStatements(ItemDocument document) { List<Statement> result = new ArrayList<>(); for (StatementGroup group : document.getStatementGroups()) { for (Statement statement : group) { if (isNewStatement(statement)) { result.add(statement); } } } return result; } private boolean isNewStatement(Statement st) { return st.getStatementId().equals(""); } private Map<StatementId, Statement> statementMap(ItemDocument document) { Map<StatementId, Statement> results = new HashMap<>(); for (StatementGroup group : document.getStatementGroups()) { PropertyIdValue property = group.getProperty(); for (Statement statement : group) { if (isNewStatement(statement)) { // Ignore new statements, statements from wiki always have // ID so they would not collide here. continue; } StatementId key = new StatementId(statement, property); if (results.containsKey(key)) { throw new RuntimeException( "Key collision: " + statement.getStatementId()); } results.put(key, statement); } } return results; } private MergeStrategy getMergeStrategy(Object object) { return mergeStrategy.getOrDefault(object, MergeStrategy.MERGE); } private void mergeStatement( Statement local, Statement remote, PropertyIdValue property) { if (local.equals(remote)) { statementsToKeep.add(remote); return; } StatementBuilder builder = StatementBuilder.forSubjectAndProperty( remote.getSubject(), property); // Defaults and not supported values. builder.withId(remote.getStatementId()); builder.withRank(remote.getRank()); if (local.getValue() == null) { // If no local value is give, then use remote value to // allow user not specify a local value. builder.withValue(remote.getValue()); } else { builder.withValue(local.getValue()); } // ReferenceMerger referenceMerger = new ReferenceMerger(mergeStrategy, snakEqualStrategy); builder.withReferences(referenceMerger.merge( local.getReferences(), remote.getReferences())); builder.withQualifiers(mergeQualifierLists( local.getQualifiers(), remote.getQualifiers())); // Statement result = builder.build(); statementsToUpdate.add(result); } private List<SnakGroup> mergeQualifierLists( List<SnakGroup> local, List<SnakGroup> remote) { List<SnakGroup> result = new ArrayList<>(); SnakMerger snakMerger = new SnakMerger(snakEqualStrategy); snakMerger.merge(local, remote).entrySet().forEach((entry) -> { PropertyIdValue property = entry.getKey(); List<Snak> snaks = entry.getValue().stream() .map((value) -> Datamodel.makeValueSnak(property, value)) .collect(Collectors.toList()); result.add(Datamodel.makeSnakGroup(snaks)); }); return result; } public ItemDocument assembleMergeDocument() { ItemDocumentBuilder builder = ItemDocumentBuilder.forItemId(localDocument.getEntityId()); addNewOrChanged(builder); addUnsupportedStatementProps(builder); return builder.build(); } private void addNewOrChanged(ItemDocumentBuilder builder) { // Labels. for (Map.Entry<String, String> entry : labelsToAdd.entrySet()) { builder.withLabel(entry.getValue(), entry.getKey()); } // Description. for (Map.Entry<String, String> entry : descriptionsToAdd.entrySet()) { builder.withDescription(entry.getValue(), entry.getKey()); } // Aliases. for (Map.Entry<String, Set<String>> entry : aliasesToAdd.entrySet()) { for (String value : entry.getValue()) { builder.withAlias(value, entry.getKey()); } } // Statements - just new or changed. for (Statement statement : statementsToAdd) { builder.withStatement(statement); } for (Statement statement : statementsToUpdate) { builder.withStatement(statement); } } private void addUnsupportedStatementProps(ItemDocumentBuilder builder) { remoteDocument.getSiteLinks().values().forEach( (link) -> builder.withSiteLink(link)); remoteDocument.getAliases().values().forEach( (aliases) -> aliases.forEach( (alias) -> builder.withAlias(alias))); } public ItemDocument assembleReplaceDocument() { ItemDocumentBuilder builder = ItemDocumentBuilder.forItemId(localDocument.getEntityId()); addNewOrChanged(builder); addToKeep(builder); addUnsupportedStatementProps(builder); return builder.build(); } private void addToKeep(ItemDocumentBuilder builder) { for (Map.Entry<String, String> entry : labelsToKeep.entrySet()) { builder.withLabel(entry.getValue(), entry.getKey()); } for (Map.Entry<String, String> entry : descriptionsToKeep.entrySet()) { builder.withDescription(entry.getValue(), entry.getKey()); } for (Map.Entry<String, Set<String>> entry : aliasesToKeep.entrySet()) { for (String value : entry.getValue()) { builder.withAlias(value, entry.getKey()); } } for (Statement statement : statementsToKeep) { builder.withStatement(statement); } } public boolean canUpdateExisting() { return labelsToDelete.isEmpty() && descriptionsToAdd.isEmpty() && aliasesToDelete.isEmpty() && statementsToDelete.isEmpty(); } }
package io.hibit.rxcontroller.application; import android.content.Context; import android.support.test.InstrumentationRegistry; import android.support.test.runner.AndroidJUnit4; import org.junit.Test; import org.junit.runner.RunWith; import static org.junit.Assert.*; /** * Instrumentation test, which will execute on an Android device. * * @see <a href="http://d.android.com/tools/testing">Testing documentation</a> */ @RunWith(AndroidJUnit4.class) public class ExampleInstrumentedTest { @Test public void useAppContext() throws Exception { // Context of the app under test. Context appContext = InstrumentationRegistry.getTargetContext(); assertEquals("io.hibit.rxcontroller.application", appContext.getPackageName()); } }
package anichan.parser; import anichan.commands.Command; import anichan.commands.RemoveCommand; import org.junit.jupiter.api.Test; import anichan.exception.AniException; import static org.junit.jupiter.api.Assertions.assertThrows; import static org.junit.jupiter.api.Assertions.assertTrue; //@@author michaeldinata class RemoveCommandParserTest { private static final String EMPTY_DESCRIPTION1 = ""; private static final String EMPTY_DESCRIPTION2 = " "; private static final String NON_INTEGER_FIELD1 = "Trigun"; private static final String NON_INTEGER_FIELD2 = "-a"; private static final String TOO_MANY_FIELDS = "123 211"; private static final String LARGE_INTEGER_ERROR = "1111111111111"; private static final String VALID_FIELD_VALUE1 = "1"; private static final String VALID_FIELD_VALUE2 = " 1"; private static final String VALID_FIELD_VALUE3 = "1 "; @Test void parse_emptyDescription_throwsAniException() { RemoveCommandParser testParse1 = new RemoveCommandParser(); assertThrows(AniException.class, () -> { testParse1.parse(EMPTY_DESCRIPTION1); }); RemoveCommandParser testParse2 = new RemoveCommandParser(); assertThrows(AniException.class, () -> { testParse2.parse(EMPTY_DESCRIPTION2); }); } @Test void parse_nonIntegerField_throwsAniException() { RemoveCommandParser testParse1 = new RemoveCommandParser(); assertThrows(AniException.class, () -> { testParse1.parse(NON_INTEGER_FIELD1); }); RemoveCommandParser testParse2 = new RemoveCommandParser(); assertThrows(AniException.class, () -> { testParse2.parse(NON_INTEGER_FIELD2); }); } @Test void parse_tooManyParameters_throwsAniException() { RemoveCommandParser testParse = new RemoveCommandParser(); assertThrows(AniException.class, () -> { testParse.parse(TOO_MANY_FIELDS); }); } @Test void parse_largeIntegerError_throwsAniException() { RemoveCommandParser testParse = new RemoveCommandParser(); assertThrows(AniException.class, () -> { testParse.parse(LARGE_INTEGER_ERROR); }); } @Test void parse_validValue_returnsInfoCommand() throws AniException { RemoveCommandParser testParse1 = new RemoveCommandParser(); Command command1 = testParse1.parse(VALID_FIELD_VALUE1); assertTrue(command1 instanceof RemoveCommand); RemoveCommandParser testParse2 = new RemoveCommandParser(); Command command2 = testParse2.parse(VALID_FIELD_VALUE2); assertTrue(command2 instanceof RemoveCommand); RemoveCommandParser testParse3 = new RemoveCommandParser(); Command command3 = testParse3.parse(VALID_FIELD_VALUE3); assertTrue(command3 instanceof RemoveCommand); } }
/* * * Copyright 2020 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://www.apache.org/licenses/LICENSE-2.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.amazon.opendistroforelasticsearch.sql.data.type; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableMap; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.Map; import java.util.stream.Collectors; /** * Expression Type. */ public enum ExprCoreType implements ExprType { /** * Unknown due to unsupported data type. */ UNKNOWN, /** * Undefined type for special literal such as NULL. * As the root of data type tree, it is compatible with any other type. * In other word, undefined type is the "narrowest" type. */ UNDEFINED, /** * Numbers. */ BYTE(UNDEFINED), SHORT(BYTE), INTEGER(SHORT), LONG(INTEGER), FLOAT(LONG), DOUBLE(FLOAT), /** * Boolean. */ BOOLEAN(UNDEFINED), /** * String. */ STRING(UNDEFINED), /** * Date. * Todo. compatible relationship. */ TIMESTAMP(UNDEFINED), DATE(UNDEFINED), TIME(UNDEFINED), DATETIME(UNDEFINED), INTERVAL(UNDEFINED), /** * Struct. */ STRUCT(UNDEFINED), /** * Array. */ ARRAY(UNDEFINED); /** * Parents (wider/compatible types) of current base type. */ private final List<ExprType> parents = new ArrayList<>(); /** * The mapping between Type and legacy JDBC type name. */ private static final Map<ExprCoreType, String> LEGACY_TYPE_NAME_MAPPING = new ImmutableMap.Builder<ExprCoreType, String>() .put(STRUCT, "object") .put(ARRAY, "nested") .put(STRING, "keyword") .build(); ExprCoreType(ExprCoreType... compatibleTypes) { for (ExprCoreType subType : compatibleTypes) { subType.parents.add(this); } } @Override public List<ExprType> getParent() { return parents.isEmpty() ? ExprType.super.getParent() : parents; } @Override public String typeName() { return this.name(); } @Override public String legacyTypeName() { return LEGACY_TYPE_NAME_MAPPING.getOrDefault(this, this.name()); } /** * Return all the valid ExprCoreType. */ public static List<ExprCoreType> coreTypes() { return Arrays.stream(ExprCoreType.values()) .filter(type -> type != UNKNOWN) .filter(type -> type != UNDEFINED) .collect(Collectors.toList()); } public static List<ExprType> numberTypes() { return ImmutableList.of(INTEGER, LONG, FLOAT, DOUBLE); } }
package io.ketill.hidusb.psx; import io.ketill.MappedFeatureRegistry; import io.ketill.psx.Ps4Controller; import org.hid4java.HidDevice; import org.jetbrains.annotations.NotNull; import static io.ketill.psx.Ps4Controller.*; public final class HidPs4AdapterUsb extends HidPs4Adapter { private static final byte INPUT_ID = (byte) 0x01; private static final byte OUTPUT_ID = (byte) 0x05; private static final int INPUT_LEN = 78; private static final int OUTPUT_LEN = 74; /** * @param controller the controller which owns this adapter. * @param registry the controller's mapped feature registry. * @param hidDevice the HID device, must be open. * @throws NullPointerException if {@code controller}, {@code registry}, * or {@code hidDevice} are {@code} null. * @throws IllegalStateException if {@code hidDevice} is not open. */ public HidPs4AdapterUsb(@NotNull Ps4Controller controller, @NotNull MappedFeatureRegistry registry, @NotNull HidDevice hidDevice) { super(controller, registry, hidDevice, INPUT_ID, OUTPUT_ID); } @Override protected byte[] generateInputReport() { byte[] report = new byte[INPUT_LEN]; report[0] = INPUT_ID; populateInputReport(report, 1); return report; } @Override protected byte[] generateOutputReport() { byte[] report = new byte[OUTPUT_LEN]; report[0] = (byte) 0xF7; /* enable all features */ report[1] = (byte) 0x04; /* unknown */ return report; } @Override protected void initAdapter() { this.mapDpad(BUTTON_UP, 5, DPAD_PATTERNS_UP); this.mapDpad(BUTTON_DOWN, 5, DPAD_PATTERNS_DOWN); this.mapDpad(BUTTON_LEFT, 5, DPAD_PATTERNS_LEFT); this.mapDpad(BUTTON_RIGHT, 5, DPAD_PATTERNS_RIGHT); this.mapButton(BUTTON_SQUARE, 5, 4); this.mapButton(BUTTON_CROSS, 5, 5); this.mapButton(BUTTON_CIRCLE, 5, 6); this.mapButton(BUTTON_TRIANGLE, 5, 7); this.mapButton(BUTTON_L1, 6, 0); this.mapButton(BUTTON_R1, 6, 1); this.mapButton(BUTTON_L2, 6, 2); this.mapButton(BUTTON_R2, 6, 3); this.mapButton(BUTTON_SHARE, 6, 4); this.mapButton(BUTTON_OPTIONS, 6, 5); this.mapButton(BUTTON_L_THUMB, 6, 6); this.mapButton(BUTTON_R_THUMB, 6, 7); this.mapButton(BUTTON_PS, 7, 0); this.mapButton(BUTTON_TPAD, 7, 1); this.mapStick(STICK_LS, 1, 2, 6, 6); this.mapStick(STICK_RS, 3, 4, 6, 7); this.mapTrigger(TRIGGER_LT, 8); this.mapTrigger(TRIGGER_RT, 9); this.mapMotor(MOTOR_WEAK, 3); this.mapMotor(MOTOR_STRONG, 4); this.mapLightbar(5); } }
/* * Copyright 2014-2022 The Ideal Authors. All rights reserved. * * Use of this source code is governed by a BSD-style * license that can be found in the LICENSE file or at * https://theideal.org/license/ */ package ideal.development.analyzers; import ideal.library.elements.*; import ideal.runtime.elements.*; import ideal.machine.annotations.dont_display; import ideal.runtime.logs.*; import ideal.development.elements.*; import ideal.development.actions.*; import ideal.development.constructs.*; import ideal.development.names.*; import ideal.development.types.*; import ideal.development.kinds.*; import ideal.development.flavors.*; import ideal.development.notifications.*; import javax.annotation.Nullable; public abstract class single_pass_analyzer extends base_analyzer { @dont_display private @Nullable analysis_result saved_result; public single_pass_analyzer(origin the_origin) { super(the_origin); } protected single_pass_analyzer(origin the_origin, @Nullable principal_type parent, @Nullable analysis_context context) { super(the_origin, parent, context); } public principal_type declared_in_type() { return parent(); } protected abstract analysis_result do_single_pass_analysis(); protected boolean has_saved_result() { return saved_result != null; } protected void set_saved_result(analysis_result saved_result) { assert this.saved_result == null; assert saved_result != null; this.saved_result = saved_result; if (saved_result instanceof error_signal) { ((error_signal) saved_result).report_not_cascading(); } } @Override protected void handle_error(error_signal the_error_signal) { super.handle_error(the_error_signal); if (saved_result == null) { saved_result = the_error_signal; } } @Override public final analysis_result analyze() { if (saved_result == null) { set_saved_result(do_single_pass_analysis()); } return saved_result; } @Override public boolean has_errors() { return saved_result instanceof error_signal; } }
package limax.xmlgen; public final class TypeInt extends Type { TypeInt() { super("int"); } @Override public boolean resolve() { return true; } @Override public void accept(Visitor visitor) { visitor.visit(this); } @Override public boolean isConstType() { return true; } @Override public boolean isAny() { return false; } @Override public boolean isJSONSerializable() { return true; } }
package maru.ui.wizards; import org.eclipse.swt.SWT; import org.eclipse.swt.layout.GridData; import org.eclipse.swt.layout.GridLayout; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Label; import org.eclipse.swt.widgets.Text; import org.eclipse.ui.dialogs.WizardNewProjectCreationPage; public class ScenarioProjectWizardPage extends WizardNewProjectCreationPage { private static final String PAGE_NAME = "Scenario Project Wizard"; private static final String PAGE_TITLE = "Scenario"; private static final String PAGE_DESCRIPTION = "Create a new scenario."; private Text comment; public ScenarioProjectWizardPage() { super(PAGE_NAME); setTitle(PAGE_TITLE); setDescription(PAGE_DESCRIPTION); } @Override public void createControl(Composite parent) { Composite container = new Composite(parent, SWT.NONE); container.setLayout(new GridLayout()); // default entries so dummy scenarios can be created quicker setInitialProjectName("New Scenario"); // create the default new-project controls super.createControl(container); createLine(container, 1); Composite subContainer = new Composite(container, SWT.NONE); subContainer.setLayout(new GridLayout(2, false)); subContainer.setLayoutData(new GridData(GridData.FILL_BOTH)); new Label(subContainer, SWT.NONE).setText("Comment:"); comment = new Text(subContainer, SWT.BORDER | SWT.MULTI); comment.setText("Comment"); comment.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true)); setControl(container); } public String getComment() { return comment.getText(); } private static void createLine(Composite parent, int columns) { Label line = new Label(parent, SWT.SEPARATOR | SWT.HORIZONTAL | SWT.BOLD); GridData gridData = new GridData(GridData.FILL_HORIZONTAL); gridData.horizontalSpan = columns; line.setLayoutData(gridData); } }