repo_name
stringlengths
5
108
path
stringlengths
6
333
size
stringlengths
1
6
content
stringlengths
4
977k
license
stringclasses
15 values
clarkparsia/ontop
obdalib-core/src/main/java/it/unibz/krdb/obda/model/impl/BooleanOperationPredicateImpl.java
1326
package it.unibz.krdb.obda.model.impl; /* * #%L * ontop-obdalib-core * %% * Copyright (C) 2009 - 2014 Free University of Bozen-Bolzano * %% * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * #L% */ import it.unibz.krdb.obda.model.BooleanOperationPredicate; public class BooleanOperationPredicateImpl extends PredicateImpl implements BooleanOperationPredicate { private static final long serialVersionUID = 360476649400908702L; protected BooleanOperationPredicateImpl(String name) { super(name, 1, null); } protected BooleanOperationPredicateImpl(String name, int arity) { super(name, arity, null); } protected BooleanOperationPredicateImpl(String name, int arity, COL_TYPE[] types) { super(name, arity, types); } @Override public BooleanOperationPredicate clone() { return this; } }
apache-2.0
arnaudsj/titanium_mobile
android/titanium/src/org/appcelerator/titanium/util/TiOrientationHelper.java
1249
/** * Appcelerator Titanium Mobile * Copyright (c) 2009-2011 by Appcelerator, Inc. All Rights Reserved. * Licensed under the terms of the Apache Public License * Please see the LICENSE included with this distribution for details. */ package org.appcelerator.titanium.util; import android.content.res.Configuration; public class TiOrientationHelper { // public member public static final int ORIENTATION_UNKNOWN = 0; public static final int ORIENTATION_PORTRAIT = 1; public static final int ORIENTATION_LANDSCAPE = 2; public static final int ORIENTATION_PORTRAIT_REVERSE = 3; public static final int ORIENTATION_LANDSCAPE_REVERSE = 4; public static final int ORIENTATION_SQUARE = 5; // private member declarations private static final String LCAT = "TiOrientationHelper"; private static final boolean DBG = TiConfig.LOGD; public static int convertConfigToTiOrientationMode (int configOrientationMode) { switch (configOrientationMode) { case Configuration.ORIENTATION_PORTRAIT: return ORIENTATION_PORTRAIT; case Configuration.ORIENTATION_LANDSCAPE: return ORIENTATION_LANDSCAPE; case Configuration.ORIENTATION_SQUARE: return ORIENTATION_SQUARE; default: return ORIENTATION_UNKNOWN; } } }
apache-2.0
o3project/mlo-net
mlo-srv/src/test/java/org/o3project/mlo/server/rpc/dto/SdtncAuthDtoTest.java
1920
/** * SdtncAuthDtoTest.java * (C) 2013,2015, Hitachi, Ltd. */ package org.o3project.mlo.server.rpc.dto; import static org.junit.Assert.*; import org.junit.After; import org.junit.Before; import org.junit.Test; import org.o3project.mlo.server.impl.rpc.service.SdtncSerdesImpl; import org.o3project.mlo.server.impl.rpc.service.SdtncTestUtil; import org.o3project.mlo.server.rpc.dto.SdtncAuthDto; import org.o3project.mlo.server.rpc.dto.SdtncReqPostLoginDto; import org.o3project.mlo.server.rpc.dto.SdtncRequestDto; import org.o3project.mlo.server.rpc.dto.SdtncResponseDto; /** * SdtncAuthDtoTest * */ public class SdtncAuthDtoTest { private static final String DATA_PATH = "src/test/resources/org/o3project/mlo/server/rpc/service/data"; private SdtncSerdesImpl serdes; /** * @throws java.lang.Exception */ @Before public void setUp() throws Exception { serdes = new SdtncSerdesImpl(); } /** * @throws java.lang.Exception */ @After public void tearDown() throws Exception { serdes = null; } /** * Test method for {@link org.o3project.mlo.server.impl.rpc.service.SdtncSerdesImpl#serializeToXml(SdtncRequestDto, java.io.OutputStream)}. * @throws Throwable */ @Test public void testSerializeToXml_auth_req() throws Throwable { SdtncReqPostLoginDto reqDto = new SdtncReqPostLoginDto(); SdtncAuthDto auth = new SdtncAuthDto(); auth.token = "myToken"; reqDto.auth = auth; assertTrue(SdtncTestUtil.isSameXmlAs(serdes, reqDto, DATA_PATH, "sdtnc.auth.req.xml")); } /** * Test method for {@link org.o3project.mlo.server.impl.rpc.service.SdtncSerdesImpl#deserializeFromXml(java.io.InputStream)}. * @throws Throwable */ @Test public void testDeserializeFromXml_auth_res() throws Throwable { SdtncResponseDto resDto = SdtncTestUtil.readResFromXml(serdes, DATA_PATH, "sdtnc.auth.res.xml"); assertNotNull(resDto); assertEquals("myToken", resDto.auth.token); } }
apache-2.0
oaqa/baseqa
src/main/java/edu/cmu/lti/oaqa/type/nlp/Focus_Type.java
4029
/* First created by JCasGen Sat Apr 11 19:49:33 EDT 2015 */ package edu.cmu.lti.oaqa.type.nlp; import org.apache.uima.jcas.JCas; import org.apache.uima.jcas.JCasRegistry; import org.apache.uima.cas.impl.CASImpl; import org.apache.uima.cas.impl.FSGenerator; import org.apache.uima.cas.FeatureStructure; import org.apache.uima.cas.impl.TypeImpl; import org.apache.uima.cas.Type; import org.apache.uima.cas.impl.FeatureImpl; import org.apache.uima.cas.Feature; import org.apache.uima.jcas.tcas.Annotation_Type; /** The phrase in the question that indicates the answer variable. * Updated by JCasGen Sun Apr 19 19:46:50 EDT 2015 * @generated */ public class Focus_Type extends Annotation_Type { /** @generated * @return the generator for this type */ @Override protected FSGenerator getFSGenerator() {return fsGenerator;} /** @generated */ private final FSGenerator fsGenerator = new FSGenerator() { public FeatureStructure createFS(int addr, CASImpl cas) { if (Focus_Type.this.useExistingInstance) { // Return eq fs instance if already created FeatureStructure fs = Focus_Type.this.jcas.getJfsFromCaddr(addr); if (null == fs) { fs = new Focus(addr, Focus_Type.this); Focus_Type.this.jcas.putJfsFromCaddr(addr, fs); return fs; } return fs; } else return new Focus(addr, Focus_Type.this); } }; /** @generated */ @SuppressWarnings ("hiding") public final static int typeIndexID = Focus.typeIndexID; /** @generated @modifiable */ @SuppressWarnings ("hiding") public final static boolean featOkTst = JCasRegistry.getFeatOkTst("edu.cmu.lti.oaqa.type.nlp.Focus"); /** @generated */ final Feature casFeat_token; /** @generated */ final int casFeatCode_token; /** @generated * @param addr low level Feature Structure reference * @return the feature value */ public int getToken(int addr) { if (featOkTst && casFeat_token == null) jcas.throwFeatMissing("token", "edu.cmu.lti.oaqa.type.nlp.Focus"); return ll_cas.ll_getRefValue(addr, casFeatCode_token); } /** @generated * @param addr low level Feature Structure reference * @param v value to set */ public void setToken(int addr, int v) { if (featOkTst && casFeat_token == null) jcas.throwFeatMissing("token", "edu.cmu.lti.oaqa.type.nlp.Focus"); ll_cas.ll_setRefValue(addr, casFeatCode_token, v);} /** @generated */ final Feature casFeat_label; /** @generated */ final int casFeatCode_label; /** @generated * @param addr low level Feature Structure reference * @return the feature value */ public String getLabel(int addr) { if (featOkTst && casFeat_label == null) jcas.throwFeatMissing("label", "edu.cmu.lti.oaqa.type.nlp.Focus"); return ll_cas.ll_getStringValue(addr, casFeatCode_label); } /** @generated * @param addr low level Feature Structure reference * @param v value to set */ public void setLabel(int addr, String v) { if (featOkTst && casFeat_label == null) jcas.throwFeatMissing("label", "edu.cmu.lti.oaqa.type.nlp.Focus"); ll_cas.ll_setStringValue(addr, casFeatCode_label, v);} /** initialize variables to correspond with Cas Type and Features * @generated * @param jcas JCas * @param casType Type */ public Focus_Type(JCas jcas, Type casType) { super(jcas, casType); casImpl.getFSClassRegistry().addGeneratorForType((TypeImpl)this.casType, getFSGenerator()); casFeat_token = jcas.getRequiredFeatureDE(casType, "token", "edu.cmu.lti.oaqa.type.nlp.Token", featOkTst); casFeatCode_token = (null == casFeat_token) ? JCas.INVALID_FEATURE_CODE : ((FeatureImpl)casFeat_token).getCode(); casFeat_label = jcas.getRequiredFeatureDE(casType, "label", "uima.cas.String", featOkTst); casFeatCode_label = (null == casFeat_label) ? JCas.INVALID_FEATURE_CODE : ((FeatureImpl)casFeat_label).getCode(); } }
apache-2.0
jGauravGupta/nbmodeler
modeler-impl/src/main/java/org/netbeans/modeler/widget/node/vmd/internal/AbstractPNodeWidget.java
16106
/** * Copyright 2013-2019 Gaurav Gupta * * 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.netbeans.modeler.widget.node.vmd.internal; //import org.netbeans.modeler.widget.INodeWidget; import java.awt.Color; import java.awt.Cursor; import java.awt.Dimension; import java.awt.Image; import java.awt.Rectangle; import java.awt.event.MouseEvent; import java.util.ArrayList; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.WeakHashMap; import org.netbeans.api.visual.action.WidgetAction; import org.netbeans.api.visual.anchor.Anchor; import org.netbeans.api.visual.anchor.AnchorFactory; import org.netbeans.api.visual.layout.LayoutFactory; import org.netbeans.api.visual.model.ObjectState; import org.netbeans.api.visual.model.StateModel; import org.netbeans.api.visual.vmd.VMDMinimizeAbility; import org.netbeans.api.visual.widget.ImageWidget; import org.netbeans.api.visual.widget.LabelWidget; import org.netbeans.api.visual.widget.Scene; import org.netbeans.api.visual.widget.SeparatorWidget; import org.netbeans.api.visual.widget.Widget; import org.netbeans.modeler.anchors.PNodeAnchor; import org.netbeans.modeler.scene.vmd.AbstractPModelerScene; import org.netbeans.modeler.specification.model.document.IColorScheme; import org.netbeans.modeler.widget.node.IPNodeWidget; import org.netbeans.modeler.widget.node.IWidgetStateHandler; import org.netbeans.modeler.widget.pin.IPinSeperatorWidget; import org.netbeans.modeler.widget.state.WidgetStateHandler; import org.netbeans.modeler.widget.design.ITextDesign; import org.netbeans.modeler.widget.design.NodeTextDesign; public abstract class AbstractPNodeWidget extends Widget implements IPNodeWidget, StateModel.Listener, VMDMinimizeAbility { private final Widget header; private final ImageWidget minimizeWidget; private final AdvanceImageWidget imageWidget; private final LabelWidget nameWidget; private final LabelWidget typeWidget; private final SeparatorWidget pinsSeparator; private Map<String, IPinSeperatorWidget> pinCategoryWidgets = new HashMap<>(); private StateModel stateModel = new StateModel(2); private final PNodeAnchor nodeAnchor; private IColorScheme colorScheme; private ITextDesign textDesign; private final IWidgetStateHandler stateHandler; private final WeakHashMap<Anchor, Anchor> proxyAnchorCache = new WeakHashMap<>(); /** * Creates a node widget with a specific color scheme. * * @param scene the scene * @param colorScheme the color scheme * @param textDesign */ public AbstractPNodeWidget(Scene scene, IColorScheme colorScheme, ITextDesign textDesign) { super(scene); this.colorScheme = colorScheme; this.textDesign = textDesign; nodeAnchor = new PNodeAnchor(this, true); setLayout(LayoutFactory.createVerticalFlowLayout()); setMinimumSize(new Dimension(128, 8)); header = new Widget(scene); header.setLayout(LayoutFactory.createHorizontalFlowLayout(LayoutFactory.SerialAlignment.CENTER, 8)); addChild(header); boolean right = colorScheme.isNodeMinimizeButtonOnRight(this); minimizeWidget = new ImageWidget(scene, colorScheme.getMinimizeWidgetImage(this)); minimizeWidget.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR)); minimizeWidget.getActions().addAction(new ToggleMinimizedAction()); if (!right) { header.addChild(minimizeWidget); } imageWidget = new AdvanceImageWidget(scene); stateHandler = new WidgetStateHandler(imageWidget); header.addChild(imageWidget); nameWidget = new LabelWidget(scene); header.addChild(nameWidget); typeWidget = new LabelWidget(scene); typeWidget.setForeground(Color.BLACK); header.addChild(typeWidget); if (right) { Widget widget = new Widget(scene); // widget.setOpaque(false); header.addChild(widget, 1000); header.addChild(minimizeWidget); } pinsSeparator = new SeparatorWidget(scene, SeparatorWidget.Orientation.HORIZONTAL); addChild(pinsSeparator); Widget topLayer = new Widget(scene); addChild(topLayer); stateModel = new StateModel(); stateModel.addListener(this); if(!((AbstractPModelerScene)this.getScene()).isSceneGenerating()){ colorScheme.installUI(this); } notifyStateChanged(ObjectState.createNormal(), ObjectState.createNormal()); } /** * Called to check whether a particular widget is minimizable. By default it * returns true. The result have to be the same for whole life-time of the * widget. If not, then the revalidation has to be invoked manually. An * anchor (created by <code>VMDNodeWidget.createPinAnchor</code> is not * affected by this method. * * @param widget the widget * @return true, if the widget is minimizable; false, if the widget is not * minimizable */ protected boolean isMinimizableWidget(Widget widget) { return true; } /** * Check the minimized state. * * @return true, if minimized */ @Override public boolean isMinimized() { return stateModel.getBooleanState(); } /** * Set the minimized state. This method will show/hide child widgets of this * Widget and switches anchors between node and pin widgets. * * @param minimized if true, then the widget is going to be minimized */ @Override public void setMinimized(boolean minimized) { stateModel.setBooleanState(minimized); } /** * Toggles the minimized state. This method will show/hide child widgets of * this Widget and switches anchors between node and pin widgets. */ @Override public void toggleMinimized() { stateModel.toggleBooleanState(); } /** * Called when a minimized state is changed. This method will show/hide * child widgets of this Widget and switches anchors between node and pin * widgets. */ @Override public void stateChanged() { boolean minimized = stateModel.getBooleanState(); if(this.getModelerScene().isSceneGenerating()){ return; } Rectangle rectangle = minimized ? new Rectangle(0, 0, (int) getBounds().getWidth(), 0) : null; //getBounds().getWidth() dont need to change width for (Widget widget : getChildren()) { if (widget != header && widget != pinsSeparator) { getScene().getSceneAnimator().animatePreferredBounds(widget, minimized && isMinimizableWidget(widget) ? rectangle : null); } } minimizeWidget.setImage(colorScheme.getMinimizeWidgetImage(this)); } /** * Called to notify about the change of the widget state. * * @param previousState the previous state * @param state the new state */ @Override protected void notifyStateChanged(ObjectState previousState, ObjectState state) { if (!this.isHighlightStatus()) { colorScheme.updateUI(this, previousState, state); } } /** * Sets a node image. * * @param image the image */ public void setImage(Image image) { getImageWidget().setImage(image); } /** * Returns a node name. * * @return the node name */ @Override public String getNodeName() { return nameWidget.getLabel(); } /** * Sets a node name. * * @param nodeName the node name */ @Override public void setNodeName(String nodeName) { nameWidget.setLabel(nodeName); revalidate (); } /** * Sets a node type (secondary name). * * @param nodeType the node type */ @Override public void setNodeType(String nodeType) { typeWidget.setLabel(nodeType != null ? "[" + nodeType + "]" : null); } /** * Attaches a pin widget to the node widget. * * @param widget the pin widget */ @Override public void attachPinWidget(Widget widget) { widget.setCheckClipping(true); addChild(widget); if (stateModel.getBooleanState() && isMinimizableWidget(widget)) { widget.setPreferredBounds(new Rectangle()); } } /** * Returns a node name widget. * * @return the node name widget */ @Override public LabelWidget getNodeNameWidget() { return nameWidget; } /** * Returns a node anchor. * * @return the node anchor */ @Override public Anchor getNodeAnchor() { return nodeAnchor; } /** * Creates an extended pin anchor with an ability of reconnecting to the * node anchor when the node is minimized. * * @param anchor the original pin anchor from which the extended anchor is * created * @return the extended pin anchor, the returned anchor is cached and * returns a single extended pin anchor instance of each original pin anchor */ @Override public Anchor createAnchorPin(Anchor anchor) { Anchor proxyAnchor = proxyAnchorCache.get(anchor); if (proxyAnchor == null) { proxyAnchor = AnchorFactory.createProxyAnchor(stateModel, anchor, nodeAnchor); proxyAnchorCache.put(anchor, proxyAnchor); } return proxyAnchor; } /** * Returns a list of pin widgets attached to the node. * * @return the list of pin widgets */ private List<Widget> getPinWidgets() { ArrayList<Widget> pins = new ArrayList<>(getChildren()); pins.remove(header); pins.remove(pinsSeparator); return pins; } /** * Sorts and assigns pins into categories. * * @param pinsCategories the map of category name as key and a list of pin * widgets as value */ @Override public void sortPins(Map<String, List<Widget>> pinsCategories) { List<Widget> previousPins = getPinWidgets(); List<Widget> unresolvedPins = new ArrayList<>(previousPins); for (Iterator<Widget> iterator = unresolvedPins.iterator(); iterator.hasNext();) { Widget widget = iterator.next(); if (pinCategoryWidgets.containsValue(widget)) { iterator.remove(); } } ArrayList<String> unusedCategories = new ArrayList<>(pinCategoryWidgets.keySet()); ArrayList<String> categoryNames = new ArrayList<>(pinsCategories.keySet()); ArrayList<Widget> newWidgets = new ArrayList<>(); for (String categoryName : categoryNames) { if (categoryName == null) { continue; } unusedCategories.remove(categoryName); if(!categoryName.isEmpty()){ newWidgets.add((Widget) createPinCategoryWidget(categoryName)); } List<Widget> widgets = pinsCategories.get(categoryName); for (Widget widget : widgets) { if (unresolvedPins.remove(widget)) { newWidgets.add(widget); } } } if (!unresolvedPins.isEmpty()) { newWidgets.addAll(0, unresolvedPins); } for (String category : unusedCategories) { getPinCategoryWidgets().remove(category); } removeChildren(previousPins); addChildren(newWidgets); ((AbstractPModelerScene) this.getScene()).validateComponent(); } private IPinSeperatorWidget createPinCategoryWidget(String categoryDisplayName) { IPinSeperatorWidget w = pinCategoryWidgets.get(categoryDisplayName); if (w != null) { return w; } IPinSeperatorWidget label = new PinSeperatorWidget(this.getScene(), categoryDisplayName); if(!((AbstractPModelerScene)this.getScene()).isSceneGenerating()){ colorScheme.installUI(label); } if (stateModel.getBooleanState()) { label.setPreferredBounds(new Rectangle()); } pinCategoryWidgets.put(categoryDisplayName, label); return label; } /** * Collapses the widget. */ @Override public void collapseWidget() { stateModel.setBooleanState(true); } /** * Expands the widget. */ @Override public void expandWidget() { stateModel.setBooleanState(false); } /** * Returns a header widget. * * @return the header widget */ @Override public Widget getHeader() { return header; } /** * Returns a minimize button widget. * * @return the miminize button widget */ @Override public ImageWidget getMinimizeButton() { return minimizeWidget; } /** * Returns a pins separator. * * @return the pins separator */ @Override public Widget getPinsSeparator() { return pinsSeparator; } /** * @return the imageWidget */ public AdvanceImageWidget getImageWidget() { return imageWidget; } /** * @return the pinCategoryWidgets */ @Override public Map<String, IPinSeperatorWidget> getPinCategoryWidgets() { return pinCategoryWidgets; } /** * @param pinCategoryWidgets the pinCategoryWidgets to set */ @Override public void setPinCategoryWidgets(HashMap<String, IPinSeperatorWidget> pinCategoryWidgets) { this.pinCategoryWidgets = pinCategoryWidgets; } /** * @return the stateHandler */ public IWidgetStateHandler getWidgetStateHandler() { return stateHandler; } private final class ToggleMinimizedAction extends WidgetAction.Adapter { @Override public WidgetAction.State mousePressed(Widget widget, WidgetAction.WidgetMouseEvent event) { if (event.getButton() == MouseEvent.BUTTON1 || event.getButton() == MouseEvent.BUTTON2) { stateModel.toggleBooleanState(); return WidgetAction.State.CONSUMED; } return WidgetAction.State.REJECTED; } } /** * @return the colorScheme */ @Override public IColorScheme getColorScheme() { return colorScheme; } /** * @param colorScheme the colorScheme to set */ @Override public void setColorScheme(IColorScheme colorScheme) { this.colorScheme = colorScheme; } /** * @return the textDesign */ @Override public ITextDesign getTextDesign() { if(textDesign == null){ textDesign = new NodeTextDesign(); } return textDesign; } /** * @param textDesign the textDesign to set */ @Override public void setTextDesign(ITextDesign textDesign) { this.textDesign = textDesign; } }
apache-2.0
muzafferorun/Projects
EGYS/src/tr/com/muzo/application/singleton/SingletonController.java
556
package tr.com.muzo.application.singleton; import java.io.Serializable; import org.springframework.context.annotation.Scope; import org.springframework.stereotype.Controller; import tr.com.muzo.db.entity.Kullanici; @Controller @Scope("singleton") public class SingletonController implements Serializable{ private static final long serialVersionUID = -2674312405512916645L; private Kullanici kullanici; public Kullanici getKullanici() { return kullanici; } public void setKullanici(Kullanici kullanici) { this.kullanici = kullanici; } }
apache-2.0
FinishX/coolweather
gradle/gradle-2.8/src/language-java/org/gradle/language/java/internal/JavaLanguagePluginServiceRegistry.java
1912
/* * Copyright 2014 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.gradle.language.java.internal; import org.gradle.api.internal.component.ArtifactType; import org.gradle.api.internal.component.ComponentTypeRegistry; import org.gradle.internal.service.ServiceRegistration; import org.gradle.internal.service.scopes.PluginServiceRegistry; import org.gradle.jvm.JvmLibrary; import org.gradle.language.java.artifact.JavadocArtifact; public class JavaLanguagePluginServiceRegistry implements PluginServiceRegistry { public void registerGlobalServices(ServiceRegistration registration) { } public void registerBuildSessionServices(ServiceRegistration registration) { } public void registerBuildServices(ServiceRegistration registration) { registration.addProvider(new ComponentRegistrationAction()); } public void registerGradleServices(ServiceRegistration registration) { } public void registerProjectServices(ServiceRegistration registration) { } private static class ComponentRegistrationAction { public void configure(ServiceRegistration registration, ComponentTypeRegistry componentTypeRegistry) { componentTypeRegistry.maybeRegisterComponentType(JvmLibrary.class) .registerArtifactType(JavadocArtifact.class, ArtifactType.JAVADOC); } } }
apache-2.0
EvilMcJerkface/atlasdb
atlasdb-ete-test-utils/src/main/java/com/palantir/atlasdb/todo/generated/SnapshotsStreamHashAidxTable.java
31748
package com.palantir.atlasdb.todo.generated; import java.util.Arrays; import java.util.Collection; import java.util.EnumSet; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.Objects; import java.util.Optional; import java.util.Set; import java.util.SortedMap; import java.util.UUID; import java.util.concurrent.Callable; import java.util.concurrent.TimeUnit; import java.util.function.BiFunction; import java.util.function.Supplier; import java.util.stream.Stream; import javax.annotation.Generated; import com.google.common.base.Function; import com.google.common.base.Joiner; import com.google.common.base.MoreObjects; import com.google.common.collect.ArrayListMultimap; import com.google.common.collect.Collections2; import com.google.common.collect.ComparisonChain; import com.google.common.collect.HashMultimap; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableMap; import com.google.common.collect.ImmutableMultimap; import com.google.common.collect.ImmutableSet; import com.google.common.collect.Iterables; import com.google.common.collect.Iterators; import com.google.common.collect.Lists; import com.google.common.collect.Maps; import com.google.common.collect.Multimap; import com.google.common.collect.Multimaps; import com.google.common.collect.Sets; import com.google.common.hash.Hashing; import com.google.common.primitives.Bytes; import com.google.common.primitives.UnsignedBytes; import com.google.protobuf.InvalidProtocolBufferException; import com.palantir.atlasdb.compress.CompressionUtils; import com.palantir.atlasdb.encoding.PtBytes; import com.palantir.atlasdb.keyvalue.api.BatchColumnRangeSelection; import com.palantir.atlasdb.keyvalue.api.Cell; import com.palantir.atlasdb.keyvalue.api.ColumnRangeSelection; import com.palantir.atlasdb.keyvalue.api.ColumnRangeSelections; import com.palantir.atlasdb.keyvalue.api.ColumnSelection; import com.palantir.atlasdb.keyvalue.api.Namespace; import com.palantir.atlasdb.keyvalue.api.Prefix; import com.palantir.atlasdb.keyvalue.api.RangeRequest; import com.palantir.atlasdb.keyvalue.api.RowResult; import com.palantir.atlasdb.keyvalue.api.TableReference; import com.palantir.atlasdb.keyvalue.impl.Cells; import com.palantir.atlasdb.ptobject.EncodingUtils; import com.palantir.atlasdb.table.api.AtlasDbDynamicMutablePersistentTable; import com.palantir.atlasdb.table.api.AtlasDbMutablePersistentTable; import com.palantir.atlasdb.table.api.AtlasDbNamedMutableTable; import com.palantir.atlasdb.table.api.AtlasDbNamedPersistentSet; import com.palantir.atlasdb.table.api.ColumnValue; import com.palantir.atlasdb.table.api.TypedRowResult; import com.palantir.atlasdb.table.description.ColumnValueDescription.Compression; import com.palantir.atlasdb.table.description.ValueType; import com.palantir.atlasdb.table.generation.ColumnValues; import com.palantir.atlasdb.table.generation.Descending; import com.palantir.atlasdb.table.generation.NamedColumnValue; import com.palantir.atlasdb.transaction.api.AtlasDbConstraintCheckingMode; import com.palantir.atlasdb.transaction.api.ConstraintCheckingTransaction; import com.palantir.atlasdb.transaction.api.ImmutableGetRangesQuery; import com.palantir.atlasdb.transaction.api.Transaction; import com.palantir.common.base.AbortingVisitor; import com.palantir.common.base.AbortingVisitors; import com.palantir.common.base.BatchingVisitable; import com.palantir.common.base.BatchingVisitableView; import com.palantir.common.base.BatchingVisitables; import com.palantir.common.base.Throwables; import com.palantir.common.collect.IterableView; import com.palantir.common.persist.Persistable; import com.palantir.common.persist.Persistable.Hydrator; import com.palantir.common.persist.Persistables; import com.palantir.util.AssertUtils; import com.palantir.util.crypto.Sha256Hash; @Generated("com.palantir.atlasdb.table.description.render.TableRenderer") @SuppressWarnings("all") public final class SnapshotsStreamHashAidxTable implements AtlasDbDynamicMutablePersistentTable<SnapshotsStreamHashAidxTable.SnapshotsStreamHashAidxRow, SnapshotsStreamHashAidxTable.SnapshotsStreamHashAidxColumn, SnapshotsStreamHashAidxTable.SnapshotsStreamHashAidxColumnValue, SnapshotsStreamHashAidxTable.SnapshotsStreamHashAidxRowResult> { private final Transaction t; private final List<SnapshotsStreamHashAidxTrigger> triggers; private final static String rawTableName = "snapshots_stream_hash_aidx"; private final TableReference tableRef; private final static ColumnSelection allColumns = ColumnSelection.all(); static SnapshotsStreamHashAidxTable of(Transaction t, Namespace namespace) { return new SnapshotsStreamHashAidxTable(t, namespace, ImmutableList.<SnapshotsStreamHashAidxTrigger>of()); } static SnapshotsStreamHashAidxTable of(Transaction t, Namespace namespace, SnapshotsStreamHashAidxTrigger trigger, SnapshotsStreamHashAidxTrigger... triggers) { return new SnapshotsStreamHashAidxTable(t, namespace, ImmutableList.<SnapshotsStreamHashAidxTrigger>builder().add(trigger).add(triggers).build()); } static SnapshotsStreamHashAidxTable of(Transaction t, Namespace namespace, List<SnapshotsStreamHashAidxTrigger> triggers) { return new SnapshotsStreamHashAidxTable(t, namespace, triggers); } private SnapshotsStreamHashAidxTable(Transaction t, Namespace namespace, List<SnapshotsStreamHashAidxTrigger> triggers) { this.t = t; this.tableRef = TableReference.create(namespace, rawTableName); this.triggers = triggers; } public static String getRawTableName() { return rawTableName; } public TableReference getTableRef() { return tableRef; } public String getTableName() { return tableRef.getQualifiedName(); } public Namespace getNamespace() { return tableRef.getNamespace(); } /** * <pre> * SnapshotsStreamHashAidxRow { * {@literal Sha256Hash hash}; * } * </pre> */ public static final class SnapshotsStreamHashAidxRow implements Persistable, Comparable<SnapshotsStreamHashAidxRow> { private final Sha256Hash hash; public static SnapshotsStreamHashAidxRow of(Sha256Hash hash) { return new SnapshotsStreamHashAidxRow(hash); } private SnapshotsStreamHashAidxRow(Sha256Hash hash) { this.hash = hash; } public Sha256Hash getHash() { return hash; } public static Function<SnapshotsStreamHashAidxRow, Sha256Hash> getHashFun() { return new Function<SnapshotsStreamHashAidxRow, Sha256Hash>() { @Override public Sha256Hash apply(SnapshotsStreamHashAidxRow row) { return row.hash; } }; } public static Function<Sha256Hash, SnapshotsStreamHashAidxRow> fromHashFun() { return new Function<Sha256Hash, SnapshotsStreamHashAidxRow>() { @Override public SnapshotsStreamHashAidxRow apply(Sha256Hash row) { return SnapshotsStreamHashAidxRow.of(row); } }; } @Override public byte[] persistToBytes() { byte[] hashBytes = hash.getBytes(); return EncodingUtils.add(hashBytes); } public static final Hydrator<SnapshotsStreamHashAidxRow> BYTES_HYDRATOR = new Hydrator<SnapshotsStreamHashAidxRow>() { @Override public SnapshotsStreamHashAidxRow hydrateFromBytes(byte[] __input) { int __index = 0; Sha256Hash hash = new Sha256Hash(EncodingUtils.get32Bytes(__input, __index)); __index += 32; return new SnapshotsStreamHashAidxRow(hash); } }; @Override public String toString() { return MoreObjects.toStringHelper(getClass().getSimpleName()) .add("hash", hash) .toString(); } @Override public boolean equals(Object obj) { if (this == obj) { return true; } if (obj == null) { return false; } if (getClass() != obj.getClass()) { return false; } SnapshotsStreamHashAidxRow other = (SnapshotsStreamHashAidxRow) obj; return Objects.equals(hash, other.hash); } @SuppressWarnings("ArrayHashCode") @Override public int hashCode() { return Objects.hashCode(hash); } @Override public int compareTo(SnapshotsStreamHashAidxRow o) { return ComparisonChain.start() .compare(this.hash, o.hash) .result(); } } /** * <pre> * SnapshotsStreamHashAidxColumn { * {@literal Long streamId}; * } * </pre> */ public static final class SnapshotsStreamHashAidxColumn implements Persistable, Comparable<SnapshotsStreamHashAidxColumn> { private final long streamId; public static SnapshotsStreamHashAidxColumn of(long streamId) { return new SnapshotsStreamHashAidxColumn(streamId); } private SnapshotsStreamHashAidxColumn(long streamId) { this.streamId = streamId; } public long getStreamId() { return streamId; } public static Function<SnapshotsStreamHashAidxColumn, Long> getStreamIdFun() { return new Function<SnapshotsStreamHashAidxColumn, Long>() { @Override public Long apply(SnapshotsStreamHashAidxColumn row) { return row.streamId; } }; } public static Function<Long, SnapshotsStreamHashAidxColumn> fromStreamIdFun() { return new Function<Long, SnapshotsStreamHashAidxColumn>() { @Override public SnapshotsStreamHashAidxColumn apply(Long row) { return SnapshotsStreamHashAidxColumn.of(row); } }; } @Override public byte[] persistToBytes() { byte[] streamIdBytes = PtBytes.toBytes(Long.MIN_VALUE ^ streamId); return EncodingUtils.add(streamIdBytes); } public static final Hydrator<SnapshotsStreamHashAidxColumn> BYTES_HYDRATOR = new Hydrator<SnapshotsStreamHashAidxColumn>() { @Override public SnapshotsStreamHashAidxColumn hydrateFromBytes(byte[] __input) { int __index = 0; Long streamId = Long.MIN_VALUE ^ PtBytes.toLong(__input, __index); __index += 8; return new SnapshotsStreamHashAidxColumn(streamId); } }; @Override public String toString() { return MoreObjects.toStringHelper(getClass().getSimpleName()) .add("streamId", streamId) .toString(); } @Override public boolean equals(Object obj) { if (this == obj) { return true; } if (obj == null) { return false; } if (getClass() != obj.getClass()) { return false; } SnapshotsStreamHashAidxColumn other = (SnapshotsStreamHashAidxColumn) obj; return Objects.equals(streamId, other.streamId); } @SuppressWarnings("ArrayHashCode") @Override public int hashCode() { return Objects.hashCode(streamId); } @Override public int compareTo(SnapshotsStreamHashAidxColumn o) { return ComparisonChain.start() .compare(this.streamId, o.streamId) .result(); } } public interface SnapshotsStreamHashAidxTrigger { public void putSnapshotsStreamHashAidx(Multimap<SnapshotsStreamHashAidxRow, ? extends SnapshotsStreamHashAidxColumnValue> newRows); } /** * <pre> * Column name description { * {@literal Long streamId}; * } * Column value description { * type: Long; * } * </pre> */ public static final class SnapshotsStreamHashAidxColumnValue implements ColumnValue<Long> { private final SnapshotsStreamHashAidxColumn columnName; private final Long value; public static SnapshotsStreamHashAidxColumnValue of(SnapshotsStreamHashAidxColumn columnName, Long value) { return new SnapshotsStreamHashAidxColumnValue(columnName, value); } private SnapshotsStreamHashAidxColumnValue(SnapshotsStreamHashAidxColumn columnName, Long value) { this.columnName = columnName; this.value = value; } public SnapshotsStreamHashAidxColumn getColumnName() { return columnName; } @Override public Long getValue() { return value; } @Override public byte[] persistColumnName() { return columnName.persistToBytes(); } @Override public byte[] persistValue() { byte[] bytes = EncodingUtils.encodeUnsignedVarLong(value); return CompressionUtils.compress(bytes, Compression.NONE); } public static Long hydrateValue(byte[] bytes) { bytes = CompressionUtils.decompress(bytes, Compression.NONE); return EncodingUtils.decodeUnsignedVarLong(bytes, 0); } public static Function<SnapshotsStreamHashAidxColumnValue, SnapshotsStreamHashAidxColumn> getColumnNameFun() { return new Function<SnapshotsStreamHashAidxColumnValue, SnapshotsStreamHashAidxColumn>() { @Override public SnapshotsStreamHashAidxColumn apply(SnapshotsStreamHashAidxColumnValue columnValue) { return columnValue.getColumnName(); } }; } public static Function<SnapshotsStreamHashAidxColumnValue, Long> getValueFun() { return new Function<SnapshotsStreamHashAidxColumnValue, Long>() { @Override public Long apply(SnapshotsStreamHashAidxColumnValue columnValue) { return columnValue.getValue(); } }; } @Override public String toString() { return MoreObjects.toStringHelper(getClass().getSimpleName()) .add("ColumnName", this.columnName) .add("Value", this.value) .toString(); } } public static final class SnapshotsStreamHashAidxRowResult implements TypedRowResult { private final SnapshotsStreamHashAidxRow rowName; private final ImmutableSet<SnapshotsStreamHashAidxColumnValue> columnValues; public static SnapshotsStreamHashAidxRowResult of(RowResult<byte[]> rowResult) { SnapshotsStreamHashAidxRow rowName = SnapshotsStreamHashAidxRow.BYTES_HYDRATOR.hydrateFromBytes(rowResult.getRowName()); Set<SnapshotsStreamHashAidxColumnValue> columnValues = Sets.newHashSetWithExpectedSize(rowResult.getColumns().size()); for (Entry<byte[], byte[]> e : rowResult.getColumns().entrySet()) { SnapshotsStreamHashAidxColumn col = SnapshotsStreamHashAidxColumn.BYTES_HYDRATOR.hydrateFromBytes(e.getKey()); Long value = SnapshotsStreamHashAidxColumnValue.hydrateValue(e.getValue()); columnValues.add(SnapshotsStreamHashAidxColumnValue.of(col, value)); } return new SnapshotsStreamHashAidxRowResult(rowName, ImmutableSet.copyOf(columnValues)); } private SnapshotsStreamHashAidxRowResult(SnapshotsStreamHashAidxRow rowName, ImmutableSet<SnapshotsStreamHashAidxColumnValue> columnValues) { this.rowName = rowName; this.columnValues = columnValues; } @Override public SnapshotsStreamHashAidxRow getRowName() { return rowName; } public Set<SnapshotsStreamHashAidxColumnValue> getColumnValues() { return columnValues; } public static Function<SnapshotsStreamHashAidxRowResult, SnapshotsStreamHashAidxRow> getRowNameFun() { return new Function<SnapshotsStreamHashAidxRowResult, SnapshotsStreamHashAidxRow>() { @Override public SnapshotsStreamHashAidxRow apply(SnapshotsStreamHashAidxRowResult rowResult) { return rowResult.rowName; } }; } public static Function<SnapshotsStreamHashAidxRowResult, ImmutableSet<SnapshotsStreamHashAidxColumnValue>> getColumnValuesFun() { return new Function<SnapshotsStreamHashAidxRowResult, ImmutableSet<SnapshotsStreamHashAidxColumnValue>>() { @Override public ImmutableSet<SnapshotsStreamHashAidxColumnValue> apply(SnapshotsStreamHashAidxRowResult rowResult) { return rowResult.columnValues; } }; } @Override public String toString() { return MoreObjects.toStringHelper(getClass().getSimpleName()) .add("RowName", getRowName()) .add("ColumnValues", getColumnValues()) .toString(); } } @Override public void delete(SnapshotsStreamHashAidxRow row, SnapshotsStreamHashAidxColumn column) { delete(ImmutableMultimap.of(row, column)); } @Override public void delete(Iterable<SnapshotsStreamHashAidxRow> rows) { Multimap<SnapshotsStreamHashAidxRow, SnapshotsStreamHashAidxColumn> toRemove = HashMultimap.create(); Multimap<SnapshotsStreamHashAidxRow, SnapshotsStreamHashAidxColumnValue> result = getRowsMultimap(rows); for (Entry<SnapshotsStreamHashAidxRow, SnapshotsStreamHashAidxColumnValue> e : result.entries()) { toRemove.put(e.getKey(), e.getValue().getColumnName()); } delete(toRemove); } @Override public void delete(Multimap<SnapshotsStreamHashAidxRow, SnapshotsStreamHashAidxColumn> values) { t.delete(tableRef, ColumnValues.toCells(values)); } @Override public void put(SnapshotsStreamHashAidxRow rowName, Iterable<SnapshotsStreamHashAidxColumnValue> values) { put(ImmutableMultimap.<SnapshotsStreamHashAidxRow, SnapshotsStreamHashAidxColumnValue>builder().putAll(rowName, values).build()); } @Override public void put(SnapshotsStreamHashAidxRow rowName, SnapshotsStreamHashAidxColumnValue... values) { put(ImmutableMultimap.<SnapshotsStreamHashAidxRow, SnapshotsStreamHashAidxColumnValue>builder().putAll(rowName, values).build()); } @Override public void put(Multimap<SnapshotsStreamHashAidxRow, ? extends SnapshotsStreamHashAidxColumnValue> values) { t.useTable(tableRef, this); t.put(tableRef, ColumnValues.toCellValues(values)); for (SnapshotsStreamHashAidxTrigger trigger : triggers) { trigger.putSnapshotsStreamHashAidx(values); } } @Override public void touch(Multimap<SnapshotsStreamHashAidxRow, SnapshotsStreamHashAidxColumn> values) { Multimap<SnapshotsStreamHashAidxRow, SnapshotsStreamHashAidxColumnValue> currentValues = get(values); put(currentValues); Multimap<SnapshotsStreamHashAidxRow, SnapshotsStreamHashAidxColumn> toDelete = HashMultimap.create(values); for (Map.Entry<SnapshotsStreamHashAidxRow, SnapshotsStreamHashAidxColumnValue> e : currentValues.entries()) { toDelete.remove(e.getKey(), e.getValue().getColumnName()); } delete(toDelete); } public static ColumnSelection getColumnSelection(Collection<SnapshotsStreamHashAidxColumn> cols) { return ColumnSelection.create(Collections2.transform(cols, Persistables.persistToBytesFunction())); } public static ColumnSelection getColumnSelection(SnapshotsStreamHashAidxColumn... cols) { return getColumnSelection(Arrays.asList(cols)); } @Override public Multimap<SnapshotsStreamHashAidxRow, SnapshotsStreamHashAidxColumnValue> get(Multimap<SnapshotsStreamHashAidxRow, SnapshotsStreamHashAidxColumn> cells) { Set<Cell> rawCells = ColumnValues.toCells(cells); Map<Cell, byte[]> rawResults = t.get(tableRef, rawCells); Multimap<SnapshotsStreamHashAidxRow, SnapshotsStreamHashAidxColumnValue> rowMap = HashMultimap.create(); for (Entry<Cell, byte[]> e : rawResults.entrySet()) { if (e.getValue().length > 0) { SnapshotsStreamHashAidxRow row = SnapshotsStreamHashAidxRow.BYTES_HYDRATOR.hydrateFromBytes(e.getKey().getRowName()); SnapshotsStreamHashAidxColumn col = SnapshotsStreamHashAidxColumn.BYTES_HYDRATOR.hydrateFromBytes(e.getKey().getColumnName()); Long val = SnapshotsStreamHashAidxColumnValue.hydrateValue(e.getValue()); rowMap.put(row, SnapshotsStreamHashAidxColumnValue.of(col, val)); } } return rowMap; } @Override public List<SnapshotsStreamHashAidxColumnValue> getRowColumns(SnapshotsStreamHashAidxRow row) { return getRowColumns(row, allColumns); } @Override public List<SnapshotsStreamHashAidxColumnValue> getRowColumns(SnapshotsStreamHashAidxRow row, ColumnSelection columns) { byte[] bytes = row.persistToBytes(); RowResult<byte[]> rowResult = t.getRows(tableRef, ImmutableSet.of(bytes), columns).get(bytes); if (rowResult == null) { return ImmutableList.of(); } else { List<SnapshotsStreamHashAidxColumnValue> ret = Lists.newArrayListWithCapacity(rowResult.getColumns().size()); for (Entry<byte[], byte[]> e : rowResult.getColumns().entrySet()) { SnapshotsStreamHashAidxColumn col = SnapshotsStreamHashAidxColumn.BYTES_HYDRATOR.hydrateFromBytes(e.getKey()); Long val = SnapshotsStreamHashAidxColumnValue.hydrateValue(e.getValue()); ret.add(SnapshotsStreamHashAidxColumnValue.of(col, val)); } return ret; } } @Override public Multimap<SnapshotsStreamHashAidxRow, SnapshotsStreamHashAidxColumnValue> getRowsMultimap(Iterable<SnapshotsStreamHashAidxRow> rows) { return getRowsMultimapInternal(rows, allColumns); } @Override public Multimap<SnapshotsStreamHashAidxRow, SnapshotsStreamHashAidxColumnValue> getRowsMultimap(Iterable<SnapshotsStreamHashAidxRow> rows, ColumnSelection columns) { return getRowsMultimapInternal(rows, columns); } private Multimap<SnapshotsStreamHashAidxRow, SnapshotsStreamHashAidxColumnValue> getRowsMultimapInternal(Iterable<SnapshotsStreamHashAidxRow> rows, ColumnSelection columns) { SortedMap<byte[], RowResult<byte[]>> results = t.getRows(tableRef, Persistables.persistAll(rows), columns); return getRowMapFromRowResults(results.values()); } private static Multimap<SnapshotsStreamHashAidxRow, SnapshotsStreamHashAidxColumnValue> getRowMapFromRowResults(Collection<RowResult<byte[]>> rowResults) { Multimap<SnapshotsStreamHashAidxRow, SnapshotsStreamHashAidxColumnValue> rowMap = HashMultimap.create(); for (RowResult<byte[]> result : rowResults) { SnapshotsStreamHashAidxRow row = SnapshotsStreamHashAidxRow.BYTES_HYDRATOR.hydrateFromBytes(result.getRowName()); for (Entry<byte[], byte[]> e : result.getColumns().entrySet()) { SnapshotsStreamHashAidxColumn col = SnapshotsStreamHashAidxColumn.BYTES_HYDRATOR.hydrateFromBytes(e.getKey()); Long val = SnapshotsStreamHashAidxColumnValue.hydrateValue(e.getValue()); rowMap.put(row, SnapshotsStreamHashAidxColumnValue.of(col, val)); } } return rowMap; } @Override public Map<SnapshotsStreamHashAidxRow, BatchingVisitable<SnapshotsStreamHashAidxColumnValue>> getRowsColumnRange(Iterable<SnapshotsStreamHashAidxRow> rows, BatchColumnRangeSelection columnRangeSelection) { Map<byte[], BatchingVisitable<Map.Entry<Cell, byte[]>>> results = t.getRowsColumnRange(tableRef, Persistables.persistAll(rows), columnRangeSelection); Map<SnapshotsStreamHashAidxRow, BatchingVisitable<SnapshotsStreamHashAidxColumnValue>> transformed = Maps.newHashMapWithExpectedSize(results.size()); for (Entry<byte[], BatchingVisitable<Map.Entry<Cell, byte[]>>> e : results.entrySet()) { SnapshotsStreamHashAidxRow row = SnapshotsStreamHashAidxRow.BYTES_HYDRATOR.hydrateFromBytes(e.getKey()); BatchingVisitable<SnapshotsStreamHashAidxColumnValue> bv = BatchingVisitables.transform(e.getValue(), result -> { SnapshotsStreamHashAidxColumn col = SnapshotsStreamHashAidxColumn.BYTES_HYDRATOR.hydrateFromBytes(result.getKey().getColumnName()); Long val = SnapshotsStreamHashAidxColumnValue.hydrateValue(result.getValue()); return SnapshotsStreamHashAidxColumnValue.of(col, val); }); transformed.put(row, bv); } return transformed; } @Override public Iterator<Map.Entry<SnapshotsStreamHashAidxRow, SnapshotsStreamHashAidxColumnValue>> getRowsColumnRange(Iterable<SnapshotsStreamHashAidxRow> rows, ColumnRangeSelection columnRangeSelection, int batchHint) { Iterator<Map.Entry<Cell, byte[]>> results = t.getRowsColumnRange(getTableRef(), Persistables.persistAll(rows), columnRangeSelection, batchHint); return Iterators.transform(results, e -> { SnapshotsStreamHashAidxRow row = SnapshotsStreamHashAidxRow.BYTES_HYDRATOR.hydrateFromBytes(e.getKey().getRowName()); SnapshotsStreamHashAidxColumn col = SnapshotsStreamHashAidxColumn.BYTES_HYDRATOR.hydrateFromBytes(e.getKey().getColumnName()); Long val = SnapshotsStreamHashAidxColumnValue.hydrateValue(e.getValue()); SnapshotsStreamHashAidxColumnValue colValue = SnapshotsStreamHashAidxColumnValue.of(col, val); return Maps.immutableEntry(row, colValue); }); } @Override public Map<SnapshotsStreamHashAidxRow, Iterator<SnapshotsStreamHashAidxColumnValue>> getRowsColumnRangeIterator(Iterable<SnapshotsStreamHashAidxRow> rows, BatchColumnRangeSelection columnRangeSelection) { Map<byte[], Iterator<Map.Entry<Cell, byte[]>>> results = t.getRowsColumnRangeIterator(tableRef, Persistables.persistAll(rows), columnRangeSelection); Map<SnapshotsStreamHashAidxRow, Iterator<SnapshotsStreamHashAidxColumnValue>> transformed = Maps.newHashMapWithExpectedSize(results.size()); for (Entry<byte[], Iterator<Map.Entry<Cell, byte[]>>> e : results.entrySet()) { SnapshotsStreamHashAidxRow row = SnapshotsStreamHashAidxRow.BYTES_HYDRATOR.hydrateFromBytes(e.getKey()); Iterator<SnapshotsStreamHashAidxColumnValue> bv = Iterators.transform(e.getValue(), result -> { SnapshotsStreamHashAidxColumn col = SnapshotsStreamHashAidxColumn.BYTES_HYDRATOR.hydrateFromBytes(result.getKey().getColumnName()); Long val = SnapshotsStreamHashAidxColumnValue.hydrateValue(result.getValue()); return SnapshotsStreamHashAidxColumnValue.of(col, val); }); transformed.put(row, bv); } return transformed; } private ColumnSelection optimizeColumnSelection(ColumnSelection columns) { if (columns.allColumnsSelected()) { return allColumns; } return columns; } public BatchingVisitableView<SnapshotsStreamHashAidxRowResult> getAllRowsUnordered() { return getAllRowsUnordered(allColumns); } public BatchingVisitableView<SnapshotsStreamHashAidxRowResult> getAllRowsUnordered(ColumnSelection columns) { return BatchingVisitables.transform(t.getRange(tableRef, RangeRequest.builder() .retainColumns(optimizeColumnSelection(columns)).build()), new Function<RowResult<byte[]>, SnapshotsStreamHashAidxRowResult>() { @Override public SnapshotsStreamHashAidxRowResult apply(RowResult<byte[]> input) { return SnapshotsStreamHashAidxRowResult.of(input); } }); } @Override public List<String> findConstraintFailures(Map<Cell, byte[]> writes, ConstraintCheckingTransaction transaction, AtlasDbConstraintCheckingMode constraintCheckingMode) { return ImmutableList.of(); } @Override public List<String> findConstraintFailuresNoRead(Map<Cell, byte[]> writes, AtlasDbConstraintCheckingMode constraintCheckingMode) { return ImmutableList.of(); } /** * This exists to avoid unused import warnings * {@link AbortingVisitor} * {@link AbortingVisitors} * {@link ArrayListMultimap} * {@link Arrays} * {@link AssertUtils} * {@link AtlasDbConstraintCheckingMode} * {@link AtlasDbDynamicMutablePersistentTable} * {@link AtlasDbMutablePersistentTable} * {@link AtlasDbNamedMutableTable} * {@link AtlasDbNamedPersistentSet} * {@link BatchColumnRangeSelection} * {@link BatchingVisitable} * {@link BatchingVisitableView} * {@link BatchingVisitables} * {@link BiFunction} * {@link Bytes} * {@link Callable} * {@link Cell} * {@link Cells} * {@link Collection} * {@link Collections2} * {@link ColumnRangeSelection} * {@link ColumnRangeSelections} * {@link ColumnSelection} * {@link ColumnValue} * {@link ColumnValues} * {@link ComparisonChain} * {@link Compression} * {@link CompressionUtils} * {@link ConstraintCheckingTransaction} * {@link Descending} * {@link EncodingUtils} * {@link Entry} * {@link EnumSet} * {@link Function} * {@link Generated} * {@link HashMultimap} * {@link HashSet} * {@link Hashing} * {@link Hydrator} * {@link ImmutableGetRangesQuery} * {@link ImmutableList} * {@link ImmutableMap} * {@link ImmutableMultimap} * {@link ImmutableSet} * {@link InvalidProtocolBufferException} * {@link IterableView} * {@link Iterables} * {@link Iterator} * {@link Iterators} * {@link Joiner} * {@link List} * {@link Lists} * {@link Map} * {@link Maps} * {@link MoreObjects} * {@link Multimap} * {@link Multimaps} * {@link NamedColumnValue} * {@link Namespace} * {@link Objects} * {@link Optional} * {@link Persistable} * {@link Persistables} * {@link Prefix} * {@link PtBytes} * {@link RangeRequest} * {@link RowResult} * {@link Set} * {@link Sets} * {@link Sha256Hash} * {@link SortedMap} * {@link Stream} * {@link Supplier} * {@link TableReference} * {@link Throwables} * {@link TimeUnit} * {@link Transaction} * {@link TypedRowResult} * {@link UUID} * {@link UnsignedBytes} * {@link ValueType} */ static String __CLASS_HASH = "kQk49iNV9kqn1ipdE8ve2g=="; }
apache-2.0
harism/android_wallpaper_flier
src/fi/harism/wallpaper/flier/FlierService.java
3883
/* Copyright 2012 Harri Smatt 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 fi.harism.wallpaper.flier; import android.content.Context; import android.content.SharedPreferences; import android.opengl.GLSurfaceView; import android.preference.PreferenceManager; import android.service.wallpaper.WallpaperService; import android.view.SurfaceHolder; /** * Main wallpaper service class. */ public final class FlierService extends WallpaperService { @Override public Engine onCreateEngine() { PreferenceManager.setDefaultValues(this, R.xml.preferences, true); return new WallpaperEngine(); } /** * Private wallpaper engine implementation. */ private final class WallpaperEngine extends Engine implements SharedPreferences.OnSharedPreferenceChangeListener { // Slightly modified GLSurfaceView. private WallpaperGLSurfaceView mGLSurfaceView; private SharedPreferences mPreferences; private FlierRenderer mRenderer; @Override public void onCreate(SurfaceHolder surfaceHolder) { // Uncomment for debugging. // android.os.Debug.waitForDebugger(); super.onCreate(surfaceHolder); mRenderer = new FlierRenderer(FlierService.this); mPreferences = PreferenceManager .getDefaultSharedPreferences(FlierService.this); mPreferences.registerOnSharedPreferenceChangeListener(this); mRenderer.setPreferences(mPreferences); mGLSurfaceView = new WallpaperGLSurfaceView(FlierService.this); mGLSurfaceView.setEGLContextClientVersion(2); mGLSurfaceView.setRenderer(mRenderer); mGLSurfaceView.setRenderMode(GLSurfaceView.RENDERMODE_CONTINUOUSLY); mGLSurfaceView.onPause(); } @Override public void onDestroy() { super.onDestroy(); mPreferences.unregisterOnSharedPreferenceChangeListener(this); mPreferences = null; mGLSurfaceView.onDestroy(); mGLSurfaceView = null; mRenderer = null; } @Override public void onOffsetsChanged(float xOffset, float yOffset, float xOffsetStep, float yOffsetStep, int xPixelOffset, int yPixelOffset) { super.onOffsetsChanged(xOffset, yOffset, xOffsetStep, yOffsetStep, xPixelOffset, yPixelOffset); mRenderer.setXOffset(xOffset); } @Override public void onSharedPreferenceChanged( SharedPreferences sharedPreferences, String key) { mRenderer.setPreferences(sharedPreferences); } @Override public void onVisibilityChanged(boolean visible) { super.onVisibilityChanged(visible); if (visible) { mGLSurfaceView.onResume(); } else { mGLSurfaceView.onPause(); } } /** * Lazy as I am, I din't bother using GLWallpaperService (found on * GitHub) project for wrapping OpenGL functionality into my wallpaper * service. Instead am using GLSurfaceView and trick it into hooking * into Engine provided SurfaceHolder instead of SurfaceView provided * one GLSurfaceView extends. */ private final class WallpaperGLSurfaceView extends GLSurfaceView { public WallpaperGLSurfaceView(Context context) { super(context); } @Override public SurfaceHolder getHolder() { return WallpaperEngine.this.getSurfaceHolder(); } /** * Should be called once underlying Engine is destroyed. Calling * onDetachedFromWindow() will stop rendering thread which is lost * otherwise. */ public void onDestroy() { super.onDetachedFromWindow(); } } } }
apache-2.0
excella-core/excella-reports
src/main/java/org/bbreak/excella/reports/tag/ReportsTagParser.java
2374
/*- * #%L * excella-reports * %% * Copyright (C) 2009 - 2019 bBreak Systems and contributors * %% * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * #L% */ package org.bbreak.excella.reports.tag; import org.apache.poi.ss.usermodel.Cell; import org.apache.poi.ss.usermodel.Sheet; import org.bbreak.excella.core.exception.ParseException; import org.bbreak.excella.core.tag.TagParser; import org.bbreak.excella.reports.model.ParamInfo; import org.bbreak.excella.reports.model.ParsedReportInfo; /** * 帳票処理のパーサークラス * * @param <T> パラメータを置換する値の型 * @since 1.0 */ public abstract class ReportsTagParser<T> extends TagParser<ParsedReportInfo> { /* * (non-Javadoc) * * @see org.bbreak.excella.core.tag.TagParser#parse(org.apache.poi.ss.usermodel.Sheet, org.apache.poi.ss.usermodel.Cell, java.lang.Object) */ @Override public abstract ParsedReportInfo parse( Sheet sheet, Cell tagCell, Object data) throws ParseException; /** * コンストラクタ * * @param tag タグ */ public ReportsTagParser( String tag) { super( tag); } /** * タグを制御行として扱うか否かを取得する。 * * @return true:制御行として削除/false:置換 */ public abstract boolean useControlRow(); /** * パラメータ情報よりパラメータ名で格納されている値を取得する。 * * @param paramInfo パラメータ情報 * @param paramName パラメータ名 * @return 置換する値 */ @SuppressWarnings( "unchecked") public T getParamData( ParamInfo paramInfo, String paramName) { if ( paramInfo == null || paramName == null) { return null; } return ( T) paramInfo.getParam( getTag(), paramName); } }
apache-2.0
boneman1231/org.apache.felix
trunk/gogo/shell/src/main/java/org/apache/felix/gogo/shell/Activator.java
5273
/* * 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.felix.gogo.shell; import java.util.Dictionary; import java.util.HashSet; import java.util.Hashtable; import java.util.Iterator; import java.util.Set; import org.apache.felix.service.command.CommandProcessor; import org.apache.felix.service.command.CommandSession; import org.apache.felix.service.command.Converter; import org.osgi.framework.BundleActivator; import org.osgi.framework.BundleContext; import org.osgi.framework.ServiceReference; import org.osgi.framework.ServiceRegistration; import org.osgi.util.tracker.ServiceTracker; public class Activator implements BundleActivator, Runnable { private BundleContext context; private ServiceTracker commandProcessorTracker; private Set<ServiceRegistration> regs = new HashSet<ServiceRegistration>(); private CommandSession session; private Shell shell; private Thread thread; public void start(final BundleContext ctxt) throws Exception { context = ctxt; commandProcessorTracker = processorTracker(); } public void stop(BundleContext context) throws Exception { if (thread != null) { thread.interrupt(); } commandProcessorTracker.close(); Iterator<ServiceRegistration> iterator = regs.iterator(); while (iterator.hasNext()) { ServiceRegistration reg = iterator.next(); reg.unregister(); iterator.remove(); } } public void run() { try { Thread.sleep(100); // wait for gosh command to be registered String args = context.getProperty("gosh.args"); args = (args == null) ? "" : args; session.execute("gosh --login " + args); } catch (Exception e) { Object loc = session.get(".location"); if (null == loc || !loc.toString().contains(":")) { loc = "gogo"; } System.err.println(loc + ": " + e.getClass().getSimpleName() + ": " + e.getMessage()); e.printStackTrace(); } finally { session.close(); } } private void startShell(BundleContext context, CommandProcessor processor) { Dictionary<String, Object> dict = new Hashtable<String, Object>(); dict.put(CommandProcessor.COMMAND_SCOPE, "gogo"); // register converters regs.add(context.registerService(Converter.class.getName(), new Converters(context), null)); // register commands dict.put(CommandProcessor.COMMAND_FUNCTION, Builtin.functions); regs.add(context.registerService(Builtin.class.getName(), new Builtin(), dict)); dict.put(CommandProcessor.COMMAND_FUNCTION, Procedural.functions); regs.add(context.registerService(Procedural.class.getName(), new Procedural(), dict)); dict.put(CommandProcessor.COMMAND_FUNCTION, Posix.functions); regs.add(context.registerService(Posix.class.getName(), new Posix(), dict)); dict.put(CommandProcessor.COMMAND_FUNCTION, Telnet.functions); regs.add(context.registerService(Telnet.class.getName(), new Telnet(processor), dict)); shell = new Shell(context, processor); dict.put(CommandProcessor.COMMAND_FUNCTION, Shell.functions); regs.add(context.registerService(Shell.class.getName(), shell, dict)); // start shell session = processor.createSession(System.in, System.out, System.err); thread = new Thread(this, "Gogo shell"); thread.start(); } private ServiceTracker processorTracker() { ServiceTracker t = new ServiceTracker(context, CommandProcessor.class.getName(), null) { @Override public Object addingService(ServiceReference reference) { CommandProcessor processor = (CommandProcessor) super.addingService(reference); startShell(context, processor); return processor; } @Override public void removedService(ServiceReference reference, Object service) { if (thread != null) { thread.interrupt(); } super.removedService(reference, service); } }; t.open(); return t; } }
apache-2.0
pymjer/pentaho-kettle
ui/src/org/pentaho/di/ui/job/entries/job/JobEntryJobDialog.java
63700
/*! ****************************************************************************** * * Pentaho Data Integration * * Copyright (C) 2002-2013 by Pentaho : http://www.pentaho.com * ******************************************************************************* * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ******************************************************************************/ package org.pentaho.di.ui.job.entries.job; import java.io.File; import java.io.IOException; import org.apache.commons.vfs2.FileObject; import org.eclipse.swt.SWT; import org.eclipse.swt.custom.CCombo; import org.eclipse.swt.custom.CTabFolder; import org.eclipse.swt.custom.CTabItem; import org.eclipse.swt.custom.ScrolledComposite; import org.eclipse.swt.events.ModifyEvent; import org.eclipse.swt.events.ModifyListener; import org.eclipse.swt.events.SelectionAdapter; import org.eclipse.swt.events.SelectionEvent; import org.eclipse.swt.events.ShellAdapter; import org.eclipse.swt.events.ShellEvent; import org.eclipse.swt.graphics.Rectangle; import org.eclipse.swt.layout.FillLayout; import org.eclipse.swt.layout.FormAttachment; import org.eclipse.swt.layout.FormData; import org.eclipse.swt.layout.FormLayout; import org.eclipse.swt.widgets.Button; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Display; import org.eclipse.swt.widgets.Event; import org.eclipse.swt.widgets.FileDialog; import org.eclipse.swt.widgets.Group; import org.eclipse.swt.widgets.Label; import org.eclipse.swt.widgets.Listener; import org.eclipse.swt.widgets.MessageBox; import org.eclipse.swt.widgets.Shell; import org.eclipse.swt.widgets.TableItem; import org.eclipse.swt.widgets.Text; import org.pentaho.di.cluster.SlaveServer; import org.pentaho.di.core.Const; import org.pentaho.di.core.ObjectLocationSpecificationMethod; import org.pentaho.di.core.Props; import org.pentaho.di.core.exception.KettleException; import org.pentaho.di.core.logging.LogLevel; import org.pentaho.di.core.vfs.KettleVFS; import org.pentaho.di.i18n.BaseMessages; import org.pentaho.di.job.JobMeta; import org.pentaho.di.job.entries.job.JobEntryJob; import org.pentaho.di.job.entry.JobEntryDialogInterface; import org.pentaho.di.job.entry.JobEntryInterface; import org.pentaho.di.repository.ObjectId; import org.pentaho.di.repository.Repository; import org.pentaho.di.repository.RepositoryElementMetaInterface; import org.pentaho.di.repository.RepositoryObject; import org.pentaho.di.repository.RepositoryObjectType; import org.pentaho.di.ui.core.dialog.ErrorDialog; import org.pentaho.di.ui.core.gui.GUIResource; import org.pentaho.di.ui.core.gui.WindowProperty; import org.pentaho.di.ui.core.widget.ColumnInfo; import org.pentaho.di.ui.core.widget.ComboVar; import org.pentaho.di.ui.core.widget.TableView; import org.pentaho.di.ui.core.widget.TextVar; import org.pentaho.di.ui.job.dialog.JobDialog; import org.pentaho.di.ui.job.entry.JobEntryDialog; import org.pentaho.di.ui.repository.dialog.SelectObjectDialog; import org.pentaho.di.ui.spoon.Spoon; import org.pentaho.di.ui.trans.step.BaseStepDialog; /** * This dialog allows you to edit the job job entry (JobEntryJob) * * @author Matt * @since 19-06-2003 */ public class JobEntryJobDialog extends JobEntryDialog implements JobEntryDialogInterface { private static Class<?> PKG = JobEntryJob.class; // for i18n purposes, needed by Translator2!! private static final String[] FILE_FILTERLOGNAMES = new String[] { BaseMessages.getString( PKG, "JobJob.Fileformat.TXT" ), BaseMessages.getString( PKG, "JobJob.Fileformat.LOG" ), BaseMessages.getString( PKG, "JobJob.Fileformat.All" ) }; private Label wlName; private Text wName; private Button wbJobname; private TextVar wJobname; private TextVar wDirectory; private Button wbFilename; private TextVar wFilename; private Button wNewJob; private Composite wLogging; private FormData fdLogging; private Label wlSetLogfile; private Button wSetLogfile; private FormData fdlSetLogfile, fdSetLogfile; private Label wlLogfile; private TextVar wLogfile; private FormData fdlLogfile, fdLogfile; private Button wbLogFilename; private FormData fdbLogFilename; private Label wlCreateParentFolder; private Button wCreateParentFolder; private FormData fdlCreateParentFolder, fdCreateParentFolder; private Label wlLogext; private TextVar wLogext; private FormData fdlLogext, fdLogext; private Label wlAddDate; private Button wAddDate; private FormData fdlAddDate, fdAddDate; private Label wlAddTime; private Button wAddTime; private FormData fdlAddTime, fdAddTime; private Label wlLoglevel; private CCombo wLoglevel; private FormData fdlLoglevel, fdLoglevel; private Label wlPrevious; private Button wPrevious; private FormData fdlPrevious, fdPrevious; private Label wlPrevToParams; private Button wPrevToParams; private FormData fdlPrevToParams, fdPrevToParams; private Label wlEveryRow; private Button wEveryRow; private FormData fdlEveryRow, fdEveryRow; private TableView wFields; private TableView wParameters; private Label wlSlaveServer; private ComboVar wSlaveServer; private FormData fdlSlaveServer, fdSlaveServer; private Label wlPassExport; private Button wPassExport; private FormData fdlPassExport, fdPassExport; private Label wlWaitingToFinish; private Button wWaitingToFinish; private FormData fdlWaitingToFinish, fdWaitingToFinish; private Label wlFollowingAbortRemotely; private Button wFollowingAbortRemotely; private FormData fdlFollowingAbortRemotely, fdFollowingAbortRemotely; private Label wlExpandRemote; private Button wExpandRemote; private FormData fdlExpandRemote, fdExpandRemote; private Label wlPassParams; private Button wPassParams; private FormData fdlPassParams, fdPassParams; private Button wbGetParams; private Button wOK, wCancel; private Listener lsOK, lsCancel; private Shell shell; private SelectionAdapter lsDef; private JobEntryJob jobEntry; private boolean backupChanged; private Label wlAppendLogfile; private Button wAppendLogfile; private FormData fdlAppendLogfile, fdAppendLogfile; private Display display; private Button radioFilename; private Button radioByName; private Button radioByReference; private Button wbByReference; private Text wByReference; private Composite wAdvanced; private ObjectId referenceObjectId; private ObjectLocationSpecificationMethod specificationMethod; private Button wForceSeparateLogging; public JobEntryJobDialog( Shell parent, JobEntryInterface jobEntryInt, Repository rep, JobMeta jobMeta ) { super( parent, jobEntryInt, rep, jobMeta ); jobEntry = (JobEntryJob) jobEntryInt; } public JobEntryInterface open() { Shell parent = getParent(); display = parent.getDisplay(); shell = new Shell( parent, props.getJobsDialogStyle() ); props.setLook( shell ); JobDialog.setShellImage( shell, jobEntry ); ModifyListener lsMod = new ModifyListener() { public void modifyText( ModifyEvent e ) { jobEntry.setChanged(); } }; backupChanged = jobEntry.hasChanged(); FormLayout formLayout = new FormLayout(); formLayout.marginWidth = Const.FORM_MARGIN; formLayout.marginHeight = Const.FORM_MARGIN; shell.setLayout( formLayout ); shell.setText( BaseMessages.getString( PKG, "JobJob.Title" ) ); int middle = props.getMiddlePct(); int margin = Const.MARGIN; // Name line wlName = new Label( shell, SWT.RIGHT ); wlName.setText( BaseMessages.getString( PKG, "JobJob.Name.Label" ) ); props.setLook( wlName ); FormData fdlName = new FormData(); fdlName.left = new FormAttachment( 0, 0 ); fdlName.top = new FormAttachment( 0, 0 ); fdlName.right = new FormAttachment( middle, -margin ); wlName.setLayoutData( fdlName ); wName = new Text( shell, SWT.SINGLE | SWT.LEFT | SWT.BORDER ); props.setLook( wName ); wName.addModifyListener( lsMod ); FormData fdName = new FormData(); fdName.top = new FormAttachment( 0, 0 ); fdName.left = new FormAttachment( middle, 0 ); fdName.right = new FormAttachment( 100, 0 ); wName.setLayoutData( fdName ); CTabFolder wTabFolder = new CTabFolder( shell, SWT.BORDER ); props.setLook( wTabFolder, Props.WIDGET_STYLE_TAB ); // Specification // CTabItem wSpecTab = new CTabItem( wTabFolder, SWT.NONE ); wSpecTab.setText( BaseMessages.getString( PKG, "JobJob.Specification.Group.Label" ) ); ScrolledComposite wSSpec = new ScrolledComposite( wTabFolder, SWT.V_SCROLL | SWT.H_SCROLL ); wSSpec.setLayout( new FillLayout() ); Composite wSpec = new Composite( wSSpec, SWT.SHADOW_NONE ); props.setLook( wSpec ); FormLayout specLayout = new FormLayout(); specLayout.marginWidth = Const.FORM_MARGIN; specLayout.marginHeight = Const.FORM_MARGIN; wSpec.setLayout( specLayout ); // The specify by filename option... // Group gFilename = new Group( wSpec, SWT.SHADOW_ETCHED_IN ); props.setLook( gFilename ); FormLayout gFileLayout = new FormLayout(); gFileLayout.marginWidth = Const.FORM_MARGIN; gFileLayout.marginHeight = Const.FORM_MARGIN; gFilename.setLayout( gFileLayout ); radioFilename = new Button( gFilename, SWT.RADIO ); props.setLook( radioFilename ); radioFilename.setText( BaseMessages.getString( PKG, "JobJob.JobFile.Label" ) ); FormData fdRadioFilename = new FormData(); fdRadioFilename.top = new FormAttachment( 0, 0 ); fdRadioFilename.left = new FormAttachment( 0, 0 ); fdRadioFilename.right = new FormAttachment( middle, -margin ); radioFilename.setLayoutData( fdRadioFilename ); radioFilename.addSelectionListener( new SelectionAdapter() { public void widgetSelected( SelectionEvent arg0 ) { specificationMethod = ObjectLocationSpecificationMethod.FILENAME; setRadioButtons(); } } ); wbFilename = new Button( gFilename, SWT.PUSH | SWT.CENTER ); props.setLook( wbFilename ); wbFilename.setImage( GUIResource.getInstance().getImageJobGraph() ); wbFilename.setToolTipText( BaseMessages.getString( PKG, "JobJob.SelectJob.Tooltip" ) ); FormData fdbFilename = new FormData(); fdbFilename.top = new FormAttachment( 0, 0 ); fdbFilename.right = new FormAttachment( 100, 0 ); wbFilename.setLayoutData( fdbFilename ); wFilename = new TextVar( jobMeta, gFilename, SWT.SINGLE | SWT.LEFT | SWT.BORDER ); props.setLook( wFilename ); wFilename.addModifyListener( lsMod ); FormData fdFilename = new FormData(); fdFilename.top = new FormAttachment( 0, 0 ); fdFilename.left = new FormAttachment( middle, 0 ); fdFilename.right = new FormAttachment( wbFilename, -margin ); wFilename.setLayoutData( fdFilename ); wFilename.addModifyListener( new ModifyListener() { public void modifyText( ModifyEvent arg0 ) { specificationMethod = ObjectLocationSpecificationMethod.FILENAME; setRadioButtons(); } } ); FormData fdgFilename = new FormData(); fdgFilename.top = new FormAttachment( 0, 0 ); fdgFilename.left = new FormAttachment( 0, 0 ); fdgFilename.right = new FormAttachment( 100, 0 ); gFilename.setLayoutData( fdgFilename ); // The repository : specify by name radio option... // Group gByName = new Group( wSpec, SWT.SHADOW_ETCHED_IN ); props.setLook( gByName ); FormLayout gByNameLayout = new FormLayout(); gByNameLayout.marginWidth = Const.FORM_MARGIN; gByNameLayout.marginHeight = Const.FORM_MARGIN; gByName.setLayout( gByNameLayout ); radioByName = new Button( gByName, SWT.RADIO ); props.setLook( radioByName ); radioByName.setText( BaseMessages.getString( PKG, "JobJob.NameOfJob.Label" ) ); FormData fdRadioByName = new FormData(); fdRadioByName.top = new FormAttachment( 0, 0 ); fdRadioByName.left = new FormAttachment( 0, 0 ); fdRadioByName.right = new FormAttachment( middle, -margin ); radioByName.setLayoutData( fdRadioByName ); radioByName.addSelectionListener( new SelectionAdapter() { public void widgetSelected( SelectionEvent arg0 ) { specificationMethod = ObjectLocationSpecificationMethod.REPOSITORY_BY_NAME; setRadioButtons(); } } ); wbJobname = new Button( gByName, SWT.PUSH | SWT.CENTER ); props.setLook( wbJobname ); wbJobname.setImage( GUIResource.getInstance().getImageJobGraph() ); wbJobname.setToolTipText( BaseMessages.getString( PKG, "JobJob.SelectJobRep.Tooltip" ) ); FormData fdbJobname = new FormData(); fdbJobname.top = new FormAttachment( 0, 0 ); fdbJobname.right = new FormAttachment( 100, 0 ); wbJobname.setLayoutData( fdbJobname ); wJobname = new TextVar( jobMeta, gByName, SWT.SINGLE | SWT.LEFT | SWT.BORDER ); props.setLook( wJobname ); wJobname.addModifyListener( lsMod ); FormData fdJobname = new FormData(); fdJobname.top = new FormAttachment( 0, 0 ); fdJobname.left = new FormAttachment( middle, 0 ); fdJobname.right = new FormAttachment( wbJobname, -margin ); wJobname.setLayoutData( fdJobname ); wDirectory = new TextVar( jobMeta, gByName, SWT.SINGLE | SWT.LEFT | SWT.BORDER ); props.setLook( wDirectory ); wDirectory.addModifyListener( lsMod ); FormData fdDirectory = new FormData(); fdDirectory.top = new FormAttachment( wJobname, margin * 2 ); fdDirectory.left = new FormAttachment( middle, 0 ); fdDirectory.right = new FormAttachment( 100, 0 ); wDirectory.setLayoutData( fdDirectory ); FormData fdgByName = new FormData(); fdgByName.top = new FormAttachment( gFilename, margin ); fdgByName.left = new FormAttachment( 0, 0 ); fdgByName.right = new FormAttachment( 100, 0 ); gByName.setLayoutData( fdgByName ); // The specify by filename option... // Group gByReference = new Group( wSpec, SWT.SHADOW_ETCHED_IN ); props.setLook( gByReference ); FormLayout gByReferenceLayout = new FormLayout(); gByReferenceLayout.marginWidth = Const.FORM_MARGIN; gByReferenceLayout.marginHeight = Const.FORM_MARGIN; gByReference.setLayout( gByReferenceLayout ); radioByReference = new Button( gByReference, SWT.RADIO ); props.setLook( radioByReference ); radioByReference.setText( BaseMessages.getString( PKG, "JobJob.JobByReference.Label" ) ); FormData fdRadioByReference = new FormData(); fdRadioByReference.top = new FormAttachment( 0, 0 ); fdRadioByReference.left = new FormAttachment( 0, 0 ); fdRadioByReference.right = new FormAttachment( middle, -margin ); radioByReference.setLayoutData( fdRadioByReference ); radioByReference.addSelectionListener( new SelectionAdapter() { public void widgetSelected( SelectionEvent arg0 ) { specificationMethod = ObjectLocationSpecificationMethod.REPOSITORY_BY_REFERENCE; setRadioButtons(); } } ); wbByReference = new Button( gByReference, SWT.PUSH | SWT.CENTER ); props.setLook( wbByReference ); wbByReference.setImage( GUIResource.getInstance().getImageJobGraph() ); wbByReference.setToolTipText( BaseMessages.getString( PKG, "JobJob.SelectJob.Tooltip" ) ); FormData fdbByReference = new FormData(); fdbByReference.top = new FormAttachment( 0, 0 ); fdbByReference.right = new FormAttachment( 100, 0 ); wbByReference.setLayoutData( fdbByReference ); wByReference = new Text( gByReference, SWT.SINGLE | SWT.LEFT | SWT.BORDER | SWT.READ_ONLY ); props.setLook( wByReference ); wByReference.addModifyListener( lsMod ); FormData fdByReference = new FormData(); fdByReference.top = new FormAttachment( 0, 0 ); fdByReference.left = new FormAttachment( middle, 0 ); fdByReference.right = new FormAttachment( wbByReference, -margin ); wByReference.setLayoutData( fdByReference ); FormData fdgByReference = new FormData(); fdgByReference.top = new FormAttachment( gByName, margin ); fdgByReference.left = new FormAttachment( 0, 0 ); fdgByReference.right = new FormAttachment( 100, 0 ); gByReference.setLayoutData( fdgByReference ); wNewJob = new Button( wSpec, SWT.PUSH ); wNewJob.setText( BaseMessages.getString( PKG, "JobJob.NewJobButton.Label" ) ); FormData fdNewJob = new FormData(); fdNewJob.bottom = new FormAttachment( 100, -margin ); fdNewJob.left = new FormAttachment( wByReference, 0, SWT.CENTER ); wNewJob.setLayoutData( fdNewJob ); wNewJob.addSelectionListener( new SelectionAdapter() { @Override public void widgetSelected( SelectionEvent event ) { newJob(); } } ); wSpec.pack(); Rectangle bounds = wSpec.getBounds(); wSSpec.setContent( wSpec ); wSSpec.setExpandHorizontal( true ); wSSpec.setExpandVertical( true ); wSSpec.setMinWidth( bounds.width ); wSSpec.setMinHeight( bounds.height ); wSpecTab.setControl( wSSpec ); FormData fdSpec = new FormData(); fdSpec.left = new FormAttachment( 0, 0 ); fdSpec.top = new FormAttachment( 0, 0 ); fdSpec.right = new FormAttachment( 100, 0 ); fdSpec.bottom = new FormAttachment( 100, 0 ); wSpec.setLayoutData( fdSpec ); // Advanced // CTabItem wAdvancedTab = new CTabItem( wTabFolder, SWT.NONE ); wAdvancedTab.setText( BaseMessages.getString( PKG, "JobJob.Advanced.Group.Label" ) ); ScrolledComposite wSAdvanced = new ScrolledComposite( wTabFolder, SWT.V_SCROLL | SWT.H_SCROLL ); wSAdvanced.setLayout( new FillLayout() ); wAdvanced = new Composite( wSAdvanced, SWT.SHADOW_NONE ); props.setLook( wAdvanced ); FormLayout advancedLayout = new FormLayout(); advancedLayout.marginWidth = Const.FORM_MARGIN; advancedLayout.marginHeight = Const.FORM_MARGIN; wAdvanced.setLayout( advancedLayout ); wlPrevious = new Label( wAdvanced, SWT.RIGHT ); wlPrevious.setText( BaseMessages.getString( PKG, "JobJob.Previous.Label" ) ); props.setLook( wlPrevious ); fdlPrevious = new FormData(); fdlPrevious.left = new FormAttachment( 0, 0 ); fdlPrevious.top = new FormAttachment( 0, 0 ); fdlPrevious.right = new FormAttachment( middle, -margin ); wlPrevious.setLayoutData( fdlPrevious ); wPrevious = new Button( wAdvanced, SWT.CHECK ); props.setLook( wPrevious ); wPrevious.setSelection( jobEntry.argFromPrevious ); wPrevious.setToolTipText( BaseMessages.getString( PKG, "JobJob.Previous.Tooltip" ) ); fdPrevious = new FormData(); fdPrevious.left = new FormAttachment( middle, 0 ); fdPrevious.top = new FormAttachment( 0, 0 ); fdPrevious.right = new FormAttachment( 100, 0 ); wPrevious.setLayoutData( fdPrevious ); wPrevious.addSelectionListener( new SelectionAdapter() { public void widgetSelected( SelectionEvent e ) { jobEntry.setChanged(); } } ); wlPrevToParams = new Label( wAdvanced, SWT.RIGHT ); wlPrevToParams.setText( BaseMessages.getString( PKG, "JobJob.PrevToParams.Label" ) ); props.setLook( wlPrevToParams ); fdlPrevToParams = new FormData(); fdlPrevToParams.left = new FormAttachment( 0, 0 ); fdlPrevToParams.top = new FormAttachment( wPrevious, margin * 3 ); fdlPrevToParams.right = new FormAttachment( middle, -margin ); wlPrevToParams.setLayoutData( fdlPrevToParams ); wPrevToParams = new Button( wAdvanced, SWT.CHECK ); props.setLook( wPrevToParams ); wPrevToParams.setSelection( jobEntry.paramsFromPrevious ); wPrevToParams.setToolTipText( BaseMessages.getString( PKG, "JobJob.PrevToParams.Tooltip" ) ); fdPrevToParams = new FormData(); fdPrevToParams.left = new FormAttachment( middle, 0 ); fdPrevToParams.top = new FormAttachment( wPrevious, margin * 3 ); fdPrevToParams.right = new FormAttachment( 100, 0 ); wPrevToParams.setLayoutData( fdPrevToParams ); wPrevToParams.addSelectionListener( new SelectionAdapter() { public void widgetSelected( SelectionEvent e ) { jobEntry.setChanged(); } } ); wlEveryRow = new Label( wAdvanced, SWT.RIGHT ); wlEveryRow.setText( BaseMessages.getString( PKG, "JobJob.ExecForEveryInputRow.Label" ) ); props.setLook( wlEveryRow ); fdlEveryRow = new FormData(); fdlEveryRow.left = new FormAttachment( 0, 0 ); fdlEveryRow.top = new FormAttachment( wPrevToParams, margin * 3 ); fdlEveryRow.right = new FormAttachment( middle, -margin ); wlEveryRow.setLayoutData( fdlEveryRow ); wEveryRow = new Button( wAdvanced, SWT.CHECK ); props.setLook( wEveryRow ); wEveryRow.setSelection( jobEntry.execPerRow ); wEveryRow.setToolTipText( BaseMessages.getString( PKG, "JobJob.ExecForEveryInputRow.Tooltip" ) ); fdEveryRow = new FormData(); fdEveryRow.left = new FormAttachment( middle, 0 ); fdEveryRow.top = new FormAttachment( wPrevToParams, margin * 3 ); fdEveryRow.right = new FormAttachment( 100, 0 ); wEveryRow.setLayoutData( fdEveryRow ); wEveryRow.addSelectionListener( new SelectionAdapter() { public void widgetSelected( SelectionEvent e ) { jobEntry.execPerRow = !jobEntry.execPerRow; jobEntry.setChanged(); } } ); // The remote slave server wlSlaveServer = new Label( wAdvanced, SWT.RIGHT ); wlSlaveServer.setText( BaseMessages.getString( PKG, "JobJob.SlaveServer.Label" ) ); wlSlaveServer.setToolTipText( BaseMessages.getString( PKG, "JobJob.SlaveServer.ToolTip" ) ); props.setLook( wlSlaveServer ); fdlSlaveServer = new FormData(); fdlSlaveServer.left = new FormAttachment( 0, 0 ); fdlSlaveServer.right = new FormAttachment( middle, -margin ); fdlSlaveServer.top = new FormAttachment( wEveryRow, margin ); wlSlaveServer.setLayoutData( fdlSlaveServer ); wSlaveServer = new ComboVar( jobMeta, wAdvanced, SWT.SINGLE | SWT.BORDER ); wSlaveServer.setItems( SlaveServer.getSlaveServerNames( jobMeta.getSlaveServers() ) ); wSlaveServer.setToolTipText( BaseMessages.getString( PKG, "JobJob.SlaveServer.ToolTip" ) ); props.setLook( wSlaveServer ); fdSlaveServer = new FormData(); fdSlaveServer.left = new FormAttachment( middle, 0 ); fdSlaveServer.top = new FormAttachment( wEveryRow, margin ); fdSlaveServer.right = new FormAttachment( 100, 0 ); wSlaveServer.setLayoutData( fdSlaveServer ); wSlaveServer.addSelectionListener( new SelectionAdapter() { public void widgetSelected( SelectionEvent e ) { setActive(); } } ); // Pass the export of this job as an export to the slave server // wlPassExport = new Label( wAdvanced, SWT.RIGHT ); wlPassExport.setText( BaseMessages.getString( PKG, "JobJob.PassExportToSlave.Label" ) ); props.setLook( wlPassExport ); fdlPassExport = new FormData(); fdlPassExport.left = new FormAttachment( 0, 0 ); fdlPassExport.top = new FormAttachment( wSlaveServer, margin ); fdlPassExport.right = new FormAttachment( middle, -margin ); wlPassExport.setLayoutData( fdlPassExport ); wPassExport = new Button( wAdvanced, SWT.CHECK ); props.setLook( wPassExport ); fdPassExport = new FormData(); fdPassExport.left = new FormAttachment( middle, 0 ); fdPassExport.top = new FormAttachment( wSlaveServer, margin ); fdPassExport.right = new FormAttachment( 100, 0 ); wPassExport.setLayoutData( fdPassExport ); // Wait for the remote transformation to finish? // wlWaitingToFinish = new Label( wAdvanced, SWT.RIGHT ); wlWaitingToFinish.setText( BaseMessages.getString( PKG, "JobJob.WaitToFinish.Label" ) ); props.setLook( wlWaitingToFinish ); fdlWaitingToFinish = new FormData(); fdlWaitingToFinish.left = new FormAttachment( 0, 0 ); fdlWaitingToFinish.top = new FormAttachment( wPassExport, margin ); fdlWaitingToFinish.right = new FormAttachment( middle, -margin ); wlWaitingToFinish.setLayoutData( fdlWaitingToFinish ); wWaitingToFinish = new Button( wAdvanced, SWT.CHECK ); props.setLook( wWaitingToFinish ); fdWaitingToFinish = new FormData(); fdWaitingToFinish.left = new FormAttachment( middle, 0 ); fdWaitingToFinish.top = new FormAttachment( wPassExport, margin ); fdWaitingToFinish.right = new FormAttachment( 100, 0 ); wWaitingToFinish.setLayoutData( fdWaitingToFinish ); wWaitingToFinish.addSelectionListener( new SelectionAdapter() { public void widgetSelected( SelectionEvent e ) { setActive(); } } ); // Follow a local abort remotely? // wlFollowingAbortRemotely = new Label( wAdvanced, SWT.RIGHT ); wlFollowingAbortRemotely.setText( BaseMessages.getString( PKG, "JobJob.AbortRemote.Label" ) ); props.setLook( wlFollowingAbortRemotely ); fdlFollowingAbortRemotely = new FormData(); fdlFollowingAbortRemotely.left = new FormAttachment( 0, 0 ); fdlFollowingAbortRemotely.top = new FormAttachment( wWaitingToFinish, margin ); fdlFollowingAbortRemotely.right = new FormAttachment( middle, -margin ); wlFollowingAbortRemotely.setLayoutData( fdlFollowingAbortRemotely ); wFollowingAbortRemotely = new Button( wAdvanced, SWT.CHECK ); props.setLook( wFollowingAbortRemotely ); fdFollowingAbortRemotely = new FormData(); fdFollowingAbortRemotely.left = new FormAttachment( middle, 0 ); fdFollowingAbortRemotely.top = new FormAttachment( wWaitingToFinish, margin ); fdFollowingAbortRemotely.right = new FormAttachment( 100, 0 ); wFollowingAbortRemotely.setLayoutData( fdFollowingAbortRemotely ); // Expand the job on the remote server, make the sub-jobs and transformations visible // wlExpandRemote = new Label( wAdvanced, SWT.RIGHT ); wlExpandRemote.setText( BaseMessages.getString( PKG, "JobEntryJobDialog.ExpandRemoteOnSlave.Label" ) ); props.setLook( wlExpandRemote ); fdlExpandRemote = new FormData(); fdlExpandRemote.left = new FormAttachment( 0, 0 ); fdlExpandRemote.top = new FormAttachment( wFollowingAbortRemotely, margin ); fdlExpandRemote.right = new FormAttachment( middle, -margin ); wlExpandRemote.setLayoutData( fdlExpandRemote ); wExpandRemote = new Button( wAdvanced, SWT.CHECK ); props.setLook( wExpandRemote ); fdExpandRemote = new FormData(); fdExpandRemote.left = new FormAttachment( middle, 0 ); fdExpandRemote.top = new FormAttachment( wFollowingAbortRemotely, margin ); fdExpandRemote.right = new FormAttachment( 100, 0 ); wExpandRemote.setLayoutData( fdExpandRemote ); wAdvanced.pack(); bounds = wAdvanced.getBounds(); wSAdvanced.setContent( wAdvanced ); wSAdvanced.setExpandHorizontal( true ); wSAdvanced.setExpandVertical( true ); wSAdvanced.setMinWidth( bounds.width ); wSAdvanced.setMinHeight( bounds.height ); wAdvancedTab.setControl( wSAdvanced ); // Logging // CTabItem wLoggingTab = new CTabItem( wTabFolder, SWT.NONE ); wLoggingTab.setText( BaseMessages.getString( PKG, "JobJob.LogSettings.Group.Label" ) ); ScrolledComposite wSLogging = new ScrolledComposite( wTabFolder, SWT.V_SCROLL | SWT.H_SCROLL ); wSLogging.setLayout( new FillLayout() ); wLogging = new Composite( wSLogging, SWT.SHADOW_NONE ); props.setLook( wLogging ); FormLayout groupLayout = new FormLayout(); groupLayout.marginWidth = Const.FORM_MARGIN; groupLayout.marginHeight = Const.FORM_MARGIN; wLogging.setLayout( groupLayout ); Label wlForceSeparateLogging = new Label( wLogging, SWT.RIGHT ); wlForceSeparateLogging.setText( BaseMessages.getString( PKG, "JobEntryJobDialog.ForceSeparateLogging.Label" ) ); props.setLook( wlForceSeparateLogging ); FormData fdlForceSeparateLogging = new FormData(); fdlForceSeparateLogging.left = new FormAttachment( 0, 0 ); fdlForceSeparateLogging.top = new FormAttachment( 0, margin ); fdlForceSeparateLogging.right = new FormAttachment( middle, -margin ); wlForceSeparateLogging.setLayoutData( fdlForceSeparateLogging ); wForceSeparateLogging = new Button( wLogging, SWT.CHECK ); props.setLook( wForceSeparateLogging ); wForceSeparateLogging.setToolTipText( BaseMessages.getString( PKG, "JobEntryJobDialog.ForceSeparateLogging.Tooltip" ) ); FormData fdForceSeparateLogging = new FormData(); fdForceSeparateLogging.left = new FormAttachment( middle, 0 ); fdForceSeparateLogging.top = new FormAttachment( 0, margin ); fdForceSeparateLogging.right = new FormAttachment( 100, 0 ); wForceSeparateLogging.setLayoutData( fdForceSeparateLogging ); // Set the logfile? // wlSetLogfile = new Label( wLogging, SWT.RIGHT ); wlSetLogfile.setText( BaseMessages.getString( PKG, "JobJob.Specify.Logfile.Label" ) ); props.setLook( wlSetLogfile ); fdlSetLogfile = new FormData(); fdlSetLogfile.left = new FormAttachment( 0, 0 ); fdlSetLogfile.top = new FormAttachment( wForceSeparateLogging, margin ); fdlSetLogfile.right = new FormAttachment( middle, -margin ); wlSetLogfile.setLayoutData( fdlSetLogfile ); wSetLogfile = new Button( wLogging, SWT.CHECK ); props.setLook( wSetLogfile ); fdSetLogfile = new FormData(); fdSetLogfile.left = new FormAttachment( middle, 0 ); fdSetLogfile.top = new FormAttachment( wForceSeparateLogging, margin ); fdSetLogfile.right = new FormAttachment( 100, 0 ); wSetLogfile.setLayoutData( fdSetLogfile ); wSetLogfile.addSelectionListener( new SelectionAdapter() { public void widgetSelected( SelectionEvent e ) { setActive(); } } ); // Append logfile? wlAppendLogfile = new Label( wLogging, SWT.RIGHT ); wlAppendLogfile.setText( BaseMessages.getString( PKG, "JobJob.Append.Logfile.Label" ) ); props.setLook( wlAppendLogfile ); fdlAppendLogfile = new FormData(); fdlAppendLogfile.left = new FormAttachment( 0, 0 ); fdlAppendLogfile.top = new FormAttachment( wSetLogfile, margin ); fdlAppendLogfile.right = new FormAttachment( middle, -margin ); wlAppendLogfile.setLayoutData( fdlAppendLogfile ); wAppendLogfile = new Button( wLogging, SWT.CHECK ); wAppendLogfile.setToolTipText( BaseMessages.getString( PKG, "JobJob.Append.Logfile.Tooltip" ) ); props.setLook( wAppendLogfile ); fdAppendLogfile = new FormData(); fdAppendLogfile.left = new FormAttachment( middle, 0 ); fdAppendLogfile.top = new FormAttachment( wSetLogfile, margin ); fdAppendLogfile.right = new FormAttachment( 100, 0 ); wAppendLogfile.setLayoutData( fdAppendLogfile ); wAppendLogfile.addSelectionListener( new SelectionAdapter() { public void widgetSelected( SelectionEvent e ) { } } ); // Set the logfile path + base-name wlLogfile = new Label( wLogging, SWT.RIGHT ); wlLogfile.setText( BaseMessages.getString( PKG, "JobJob.NameOfLogfile.Label" ) ); props.setLook( wlLogfile ); fdlLogfile = new FormData(); fdlLogfile.left = new FormAttachment( 0, 0 ); fdlLogfile.top = new FormAttachment( wAppendLogfile, margin ); fdlLogfile.right = new FormAttachment( middle, -margin ); wlLogfile.setLayoutData( fdlLogfile ); wbLogFilename = new Button( wLogging, SWT.PUSH | SWT.CENTER ); props.setLook( wbLogFilename ); wbLogFilename.setText( BaseMessages.getString( PKG, "JobJob.Browse.Label" ) ); fdbLogFilename = new FormData(); fdbLogFilename.top = new FormAttachment( wAppendLogfile, margin ); fdbLogFilename.right = new FormAttachment( 100, 0 ); wbLogFilename.setLayoutData( fdbLogFilename ); wLogfile = new TextVar( jobMeta, wLogging, SWT.SINGLE | SWT.LEFT | SWT.BORDER ); wLogfile.setText( "" ); props.setLook( wLogfile ); fdLogfile = new FormData(); fdLogfile.left = new FormAttachment( middle, 0 ); fdLogfile.top = new FormAttachment( wAppendLogfile, margin ); fdLogfile.right = new FormAttachment( wbLogFilename, -margin ); wLogfile.setLayoutData( fdLogfile ); // create parent folder? wlCreateParentFolder = new Label( wLogging, SWT.RIGHT ); wlCreateParentFolder.setText( BaseMessages.getString( PKG, "JobJob.Logfile.CreateParentFolder.Label" ) ); props.setLook( wlCreateParentFolder ); fdlCreateParentFolder = new FormData(); fdlCreateParentFolder.left = new FormAttachment( 0, 0 ); fdlCreateParentFolder.top = new FormAttachment( wLogfile, margin ); fdlCreateParentFolder.right = new FormAttachment( middle, -margin ); wlCreateParentFolder.setLayoutData( fdlCreateParentFolder ); wCreateParentFolder = new Button( wLogging, SWT.CHECK ); wCreateParentFolder .setToolTipText( BaseMessages.getString( PKG, "JobJob.Logfile.CreateParentFolder.Tooltip" ) ); props.setLook( wCreateParentFolder ); fdCreateParentFolder = new FormData(); fdCreateParentFolder.left = new FormAttachment( middle, 0 ); fdCreateParentFolder.top = new FormAttachment( wLogfile, margin ); fdCreateParentFolder.right = new FormAttachment( 100, 0 ); wCreateParentFolder.setLayoutData( fdCreateParentFolder ); wCreateParentFolder.addSelectionListener( new SelectionAdapter() { public void widgetSelected( SelectionEvent e ) { } } ); // Set the logfile filename extention wlLogext = new Label( wLogging, SWT.RIGHT ); wlLogext.setText( BaseMessages.getString( PKG, "JobJob.LogfileExtension.Label" ) ); props.setLook( wlLogext ); fdlLogext = new FormData(); fdlLogext.left = new FormAttachment( 0, 0 ); fdlLogext.top = new FormAttachment( wCreateParentFolder, margin ); fdlLogext.right = new FormAttachment( middle, -margin ); wlLogext.setLayoutData( fdlLogext ); wLogext = new TextVar( jobMeta, wLogging, SWT.SINGLE | SWT.LEFT | SWT.BORDER ); wLogext.setText( "" ); props.setLook( wLogext ); fdLogext = new FormData(); fdLogext.left = new FormAttachment( middle, 0 ); fdLogext.top = new FormAttachment( wCreateParentFolder, margin ); fdLogext.right = new FormAttachment( 100, 0 ); wLogext.setLayoutData( fdLogext ); // Add date to logfile name? wlAddDate = new Label( wLogging, SWT.RIGHT ); wlAddDate.setText( BaseMessages.getString( PKG, "JobJob.Logfile.IncludeDate.Label" ) ); props.setLook( wlAddDate ); fdlAddDate = new FormData(); fdlAddDate.left = new FormAttachment( 0, 0 ); fdlAddDate.top = new FormAttachment( wLogext, margin ); fdlAddDate.right = new FormAttachment( middle, -margin ); wlAddDate.setLayoutData( fdlAddDate ); wAddDate = new Button( wLogging, SWT.CHECK ); props.setLook( wAddDate ); fdAddDate = new FormData(); fdAddDate.left = new FormAttachment( middle, 0 ); fdAddDate.top = new FormAttachment( wLogext, margin ); fdAddDate.right = new FormAttachment( 100, 0 ); wAddDate.setLayoutData( fdAddDate ); // Add time to logfile name? wlAddTime = new Label( wLogging, SWT.RIGHT ); wlAddTime.setText( BaseMessages.getString( PKG, "JobJob.Logfile.IncludeTime.Label" ) ); props.setLook( wlAddTime ); fdlAddTime = new FormData(); fdlAddTime.left = new FormAttachment( 0, 0 ); fdlAddTime.top = new FormAttachment( wAddDate, margin ); fdlAddTime.right = new FormAttachment( middle, -margin ); wlAddTime.setLayoutData( fdlAddTime ); wAddTime = new Button( wLogging, SWT.CHECK ); props.setLook( wAddTime ); fdAddTime = new FormData(); fdAddTime.left = new FormAttachment( middle, 0 ); fdAddTime.top = new FormAttachment( wAddDate, margin ); fdAddTime.right = new FormAttachment( 100, 0 ); wAddTime.setLayoutData( fdAddTime ); wlLoglevel = new Label( wLogging, SWT.RIGHT ); wlLoglevel.setText( BaseMessages.getString( PKG, "JobJob.Loglevel.Label" ) ); props.setLook( wlLoglevel ); fdlLoglevel = new FormData(); fdlLoglevel.left = new FormAttachment( 0, 0 ); fdlLoglevel.right = new FormAttachment( middle, -margin ); fdlLoglevel.top = new FormAttachment( wAddTime, margin ); wlLoglevel.setLayoutData( fdlLoglevel ); wLoglevel = new CCombo( wLogging, SWT.SINGLE | SWT.READ_ONLY | SWT.BORDER ); wLoglevel.setItems( LogLevel.getLogLevelDescriptions() ); props.setLook( wLoglevel ); fdLoglevel = new FormData(); fdLoglevel.left = new FormAttachment( middle, 0 ); fdLoglevel.top = new FormAttachment( wAddTime, margin ); fdLoglevel.right = new FormAttachment( 100, 0 ); wLoglevel.setLayoutData( fdLoglevel ); fdLogging = new FormData(); fdLogging.left = new FormAttachment( 0, margin ); fdLogging.top = new FormAttachment( wbFilename, margin ); fdLogging.right = new FormAttachment( 100, -margin ); wLogging.setLayoutData( fdLogging ); wLogging.pack(); bounds = wLogging.getBounds(); wSLogging.setContent( wLogging ); wSLogging.setExpandHorizontal( true ); wSLogging.setExpandVertical( true ); wSLogging.setMinWidth( bounds.width ); wSLogging.setMinHeight( bounds.height ); wLoggingTab.setControl( wSLogging ); // Arguments // CTabItem wFieldTab = new CTabItem( wTabFolder, SWT.NONE ); wFieldTab.setText( BaseMessages.getString( PKG, "JobJob.Fields.Argument.Label" ) ); FormLayout fieldLayout = new FormLayout(); fieldLayout.marginWidth = Const.MARGIN; fieldLayout.marginHeight = Const.MARGIN; Composite wFieldComp = new Composite( wTabFolder, SWT.NONE ); props.setLook( wFieldComp ); wFieldComp.setLayout( fieldLayout ); final int FieldsCols = 1; int rows = jobEntry.arguments == null ? 1 : ( jobEntry.arguments.length == 0 ? 0 : jobEntry.arguments.length ); final int FieldsRows = rows; ColumnInfo[] colinf = new ColumnInfo[FieldsCols]; colinf[0] = new ColumnInfo( BaseMessages.getString( PKG, "JobJob.Fields.Argument.Label" ), ColumnInfo.COLUMN_TYPE_TEXT, false ); colinf[0].setUsingVariables( true ); wFields = new TableView( jobMeta, wFieldComp, SWT.BORDER | SWT.FULL_SELECTION | SWT.MULTI, colinf, FieldsRows, lsMod, props ); FormData fdFields = new FormData(); fdFields.left = new FormAttachment( 0, 0 ); fdFields.top = new FormAttachment( 0, margin ); fdFields.right = new FormAttachment( 100, 0 ); fdFields.bottom = new FormAttachment( 100, 0 ); wFields.setLayoutData( fdFields ); FormData fdFieldsComp = new FormData(); fdFieldsComp.left = new FormAttachment( 0, 0 ); fdFieldsComp.top = new FormAttachment( 0, 0 ); fdFieldsComp.right = new FormAttachment( 100, 0 ); fdFieldsComp.bottom = new FormAttachment( 100, 0 ); wFieldComp.setLayoutData( fdFieldsComp ); wFieldComp.layout(); wFieldTab.setControl( wFieldComp ); // The parameters tab CTabItem wParametersTab = new CTabItem( wTabFolder, SWT.NONE ); wParametersTab.setText( BaseMessages.getString( PKG, "JobJob.Fields.Parameters.Label" ) ); fieldLayout = new FormLayout(); fieldLayout.marginWidth = Const.MARGIN; fieldLayout.marginHeight = Const.MARGIN; Composite wParameterComp = new Composite( wTabFolder, SWT.NONE ); props.setLook( wParameterComp ); wParameterComp.setLayout( fieldLayout ); // Pass all parameters down // wlPassParams = new Label( wParameterComp, SWT.RIGHT ); wlPassParams.setText( BaseMessages.getString( PKG, "JobJob.PassAllParameters.Label" ) ); props.setLook( wlPassParams ); fdlPassParams = new FormData(); fdlPassParams.left = new FormAttachment( 0, 0 ); fdlPassParams.top = new FormAttachment( 0, 0 ); fdlPassParams.right = new FormAttachment( middle, -margin ); wlPassParams.setLayoutData( fdlPassParams ); wPassParams = new Button( wParameterComp, SWT.CHECK ); props.setLook( wPassParams ); fdPassParams = new FormData(); fdPassParams.left = new FormAttachment( middle, 0 ); fdPassParams.top = new FormAttachment( 0, 0 ); fdPassParams.right = new FormAttachment( 100, 0 ); wPassParams.setLayoutData( fdPassParams ); wbGetParams = new Button( wParameterComp, SWT.PUSH ); wbGetParams.setText( BaseMessages.getString( PKG, "JobJob.GetParameters.Button.Label" ) ); FormData fdGetParams = new FormData(); fdGetParams.top = new FormAttachment( wPassParams, margin ); fdGetParams.right = new FormAttachment( 100, 0 ); wbGetParams.setLayoutData( fdGetParams ); wbGetParams.addSelectionListener( new SelectionAdapter() { @Override public void widgetSelected( SelectionEvent arg0 ) { getParameters( null ); // null: reload file from specification } } ); final int parameterRows = jobEntry.parameters == null ? 0 : jobEntry.parameters.length; colinf = new ColumnInfo[] { new ColumnInfo( BaseMessages.getString( PKG, "JobJob.Parameters.Parameter.Label" ), ColumnInfo.COLUMN_TYPE_TEXT, false ), new ColumnInfo( BaseMessages.getString( PKG, "JobJob.Parameters.ColumnName.Label" ), ColumnInfo.COLUMN_TYPE_TEXT, false ), new ColumnInfo( BaseMessages.getString( PKG, "JobJob.Parameters.Value.Label" ), ColumnInfo.COLUMN_TYPE_TEXT, false ), }; colinf[2].setUsingVariables( true ); wParameters = new TableView( jobMeta, wParameterComp, SWT.BORDER | SWT.FULL_SELECTION | SWT.MULTI, colinf, parameterRows, lsMod, props ); FormData fdParameters = new FormData(); fdParameters.left = new FormAttachment( 0, 0 ); fdParameters.top = new FormAttachment( wPassParams, margin ); fdParameters.right = new FormAttachment( wbGetParams, -margin ); fdParameters.bottom = new FormAttachment( 100, 0 ); wParameters.setLayoutData( fdParameters ); FormData fdParametersComp = new FormData(); fdParametersComp.left = new FormAttachment( 0, 0 ); fdParametersComp.top = new FormAttachment( 0, 0 ); fdParametersComp.right = new FormAttachment( 100, 0 ); fdParametersComp.bottom = new FormAttachment( 100, 0 ); wParameterComp.setLayoutData( fdParametersComp ); wParameterComp.layout(); wParametersTab.setControl( wParameterComp ); FormData fdTabFolder = new FormData(); fdTabFolder.left = new FormAttachment( 0, 0 ); fdTabFolder.top = new FormAttachment( wName, margin * 3 ); fdTabFolder.right = new FormAttachment( 100, 0 ); fdTabFolder.bottom = new FormAttachment( 100, -50 ); wTabFolder.setLayoutData( fdTabFolder ); wTabFolder.setSelection( 0 ); // Some buttons wOK = new Button( shell, SWT.PUSH ); wOK.setText( BaseMessages.getString( PKG, "System.Button.OK" ) ); wCancel = new Button( shell, SWT.PUSH ); wCancel.setText( BaseMessages.getString( PKG, "System.Button.Cancel" ) ); BaseStepDialog.positionBottomButtons( shell, new Button[] { wOK, wCancel }, margin, wTabFolder ); // Add listeners lsCancel = new Listener() { public void handleEvent( Event e ) { cancel(); } }; lsOK = new Listener() { public void handleEvent( Event e ) { ok(); } }; wOK.addListener( SWT.Selection, lsOK ); wCancel.addListener( SWT.Selection, lsCancel ); lsDef = new SelectionAdapter() { public void widgetDefaultSelected( SelectionEvent e ) { ok(); } }; wName.addSelectionListener( lsDef ); wFilename.addSelectionListener( lsDef ); wbJobname.addSelectionListener( new SelectionAdapter() { public void widgetSelected( SelectionEvent e ) { selectJob(); } } ); wbFilename.addSelectionListener( new SelectionAdapter() { public void widgetSelected( SelectionEvent e ) { pickFileVFS(); } } ); wbByReference.addSelectionListener( new SelectionAdapter() { public void widgetSelected( SelectionEvent e ) { selectJobByReference(); } } ); wbLogFilename.addSelectionListener( new SelectionAdapter() { public void widgetSelected( SelectionEvent e ) { FileDialog dialog = new FileDialog( shell, SWT.SAVE ); dialog.setFilterExtensions( new String[] { "*.txt", "*.log", "*" } ); dialog.setFilterNames( FILE_FILTERLOGNAMES ); if ( wLogfile.getText() != null ) { dialog.setFileName( jobMeta.environmentSubstitute( wLogfile.getText() ) ); } if ( dialog.open() != null ) { wLogfile.setText( dialog.getFilterPath() + Const.FILE_SEPARATOR + dialog.getFileName() ); String filename = dialog.getFilterPath() + Const.FILE_SEPARATOR + dialog.getFileName(); FileObject file = null; try { file = KettleVFS.getFileObject( filename ); // Set file extension .. wLogext.setText( file.getName().getExtension() ); // Set filename without extension ... wLogfile.setText( wLogfile.getText().substring( 0, wLogfile.getText().length() - wLogext.getText().length() - 1 ) ); } catch ( Exception ex ) { // Ignore } if ( file != null ) { try { file.close(); } catch ( IOException ex ) { /* Ignore */ } } } } } ); // Detect [X] or ALT-F4 or something that kills this window... shell.addShellListener( new ShellAdapter() { public void shellClosed( ShellEvent e ) { cancel(); } } ); getData(); setActive(); BaseStepDialog.setSize( shell ); shell.open(); props.setDialogSize( shell, "JobJobDialogSize" ); while ( !shell.isDisposed() ) { if ( !display.readAndDispatch() ) { display.sleep(); } } return jobEntry; } /** * Ask the user to fill in the details... */ protected void newJob() { JobMeta newJobMeta = new JobMeta(); newJobMeta.getDatabases().addAll( jobMeta.getDatabases() ); newJobMeta.setRepository( jobMeta.getRepository() ); newJobMeta.setRepositoryDirectory( jobMeta.getRepositoryDirectory() ); newJobMeta.setMetaStore( metaStore ); JobDialog jobDialog = new JobDialog( shell, SWT.NONE, newJobMeta, rep ); if ( jobDialog.open() != null ) { Spoon spoon = Spoon.getInstance(); spoon.addJobGraph( newJobMeta ); boolean saved = false; try { if ( rep != null ) { if ( !Const.isEmpty( newJobMeta.getName() ) ) { wName.setText( newJobMeta.getName() ); } saved = spoon.saveToRepository( newJobMeta, false ); if ( rep.getRepositoryMeta().getRepositoryCapabilities().supportsReferences() ) { specificationMethod = ObjectLocationSpecificationMethod.REPOSITORY_BY_REFERENCE; } else { specificationMethod = ObjectLocationSpecificationMethod.REPOSITORY_BY_NAME; } } else { saved = spoon.saveToFile( newJobMeta ); specificationMethod = ObjectLocationSpecificationMethod.FILENAME; } } catch ( Exception e ) { new ErrorDialog( shell, "Error", "Error saving new job", e ); } if ( saved ) { setRadioButtons(); switch ( specificationMethod ) { case FILENAME: wFilename.setText( Const.NVL( newJobMeta.getFilename(), "" ) ); break; case REPOSITORY_BY_NAME: wJobname.setText( Const.NVL( newJobMeta.getName(), "" ) ); wDirectory.setText( newJobMeta.getRepositoryDirectory().getPath() ); break; case REPOSITORY_BY_REFERENCE: getByReferenceData( newJobMeta.getObjectId() ); break; default: break; } getParameters( newJobMeta ); } } } protected void getParameters( JobMeta inputJobMeta ) { try { if ( inputJobMeta == null ) { JobEntryJob jej = new JobEntryJob(); getInfo( jej ); inputJobMeta = jej.getJobMeta( rep, metaStore, jobMeta ); } String[] parameters = inputJobMeta.listParameters(); String[] existing = wParameters.getItems( 1 ); for ( int i = 0; i < parameters.length; i++ ) { if ( Const.indexOfString( parameters[i], existing ) < 0 ) { TableItem item = new TableItem( wParameters.table, SWT.NONE ); item.setText( 1, parameters[i] ); } } wParameters.removeEmptyRows(); wParameters.setRowNums(); wParameters.optWidth( true ); } catch ( Exception e ) { new ErrorDialog( shell, BaseMessages.getString( PKG, "JobEntryJobDialog.Exception.UnableToLoadJob.Title" ), BaseMessages .getString( PKG, "JobEntryJobDialog.Exception.UnableToLoadJob.Message" ), e ); } } protected void selectJob() { if ( rep != null ) { SelectObjectDialog sod = new SelectObjectDialog( shell, rep, false, true ); String jobname = sod.open(); if ( jobname != null ) { wJobname.setText( jobname ); wDirectory.setText( sod.getDirectory().getPath() ); // Copy it to the job entry name too... wName.setText( wJobname.getText() ); specificationMethod = ObjectLocationSpecificationMethod.REPOSITORY_BY_NAME; setRadioButtons(); } } } protected void setRadioButtons() { radioFilename.setSelection( specificationMethod == ObjectLocationSpecificationMethod.FILENAME ); radioByName.setSelection( specificationMethod == ObjectLocationSpecificationMethod.REPOSITORY_BY_NAME ); radioByReference .setSelection( specificationMethod == ObjectLocationSpecificationMethod.REPOSITORY_BY_REFERENCE ); setActive(); } private void getByReferenceData( RepositoryElementMetaInterface jobInf ) { String path = jobInf.getRepositoryDirectory().getPath(); if ( !path.endsWith( "/" ) ) { path += "/"; } path += jobInf.getName(); wByReference.setText( path ); } protected void selectJobByReference() { if ( rep != null ) { SelectObjectDialog sod = new SelectObjectDialog( shell, rep, false, true ); sod.open(); RepositoryElementMetaInterface repositoryObject = sod.getRepositoryObject(); if ( repositoryObject != null ) { getByReferenceData( repositoryObject ); referenceObjectId = repositoryObject.getObjectId(); specificationMethod = ObjectLocationSpecificationMethod.REPOSITORY_BY_REFERENCE; setRadioButtons(); } } } protected void pickFileVFS() { FileDialog dialog = new FileDialog( shell, SWT.OPEN ); dialog.setFilterExtensions( Const.STRING_JOB_FILTER_EXT ); dialog.setFilterNames( Const.getJobFilterNames() ); String prevName = jobMeta.environmentSubstitute( wFilename.getText() ); String parentFolder = null; try { parentFolder = KettleVFS.getFilename( KettleVFS .getFileObject( jobMeta.environmentSubstitute( jobMeta.getFilename() ) ).getParent() ); } catch ( Exception e ) { // not that important } if ( !Const.isEmpty( prevName ) ) { try { if ( KettleVFS.fileExists( prevName ) ) { dialog.setFilterPath( KettleVFS.getFilename( KettleVFS.getFileObject( prevName ).getParent() ) ); } else { if ( !prevName.endsWith( ".kjb" ) ) { prevName = "${" + Const.INTERNAL_VARIABLE_JOB_FILENAME_DIRECTORY + "}/" + Const.trim( wFilename.getText() ) + ".kjb"; } if ( KettleVFS.fileExists( prevName ) ) { wFilename.setText( prevName ); specificationMethod = ObjectLocationSpecificationMethod.FILENAME; setRadioButtons(); return; } else { // File specified doesn't exist. Ask if we should create the file... // MessageBox mb = new MessageBox( shell, SWT.YES | SWT.NO | SWT.ICON_QUESTION ); mb.setMessage( BaseMessages.getString( PKG, "JobJob.Dialog.CreateJobQuestion.Message" ) ); mb.setText( BaseMessages.getString( PKG, "JobJob.Dialog.CreateJobQuestion.Title" ) ); // Sorry! int answer = mb.open(); if ( answer == SWT.YES ) { Spoon spoon = Spoon.getInstance(); spoon.newJobFile(); JobMeta newJobMeta = spoon.getActiveJob(); newJobMeta.initializeVariablesFrom( jobEntry ); newJobMeta.setFilename( jobMeta.environmentSubstitute( prevName ) ); wFilename.setText( prevName ); specificationMethod = ObjectLocationSpecificationMethod.FILENAME; setRadioButtons(); spoon.saveFile(); return; } } } } catch ( Exception e ) { dialog.setFilterPath( parentFolder ); } } else if ( !Const.isEmpty( parentFolder ) ) { dialog.setFilterPath( parentFolder ); } String fname = dialog.open(); if ( fname != null ) { File file = new File( fname ); String name = file.getName(); String parentFolderSelection = file.getParentFile().toString(); if ( !Const.isEmpty( parentFolder ) && parentFolder.equals( parentFolderSelection ) ) { wFilename.setText( "${" + Const.INTERNAL_VARIABLE_JOB_FILENAME_DIRECTORY + "}/" + name ); } else { wFilename.setText( fname ); } } } public void dispose() { WindowProperty winprop = new WindowProperty( shell ); props.setScreen( winprop ); shell.dispose(); } public void setActive() { boolean supportsReferences = rep != null && rep.getRepositoryMeta().getRepositoryCapabilities().supportsReferences(); radioByName.setEnabled( rep != null ); radioByReference.setEnabled( rep != null && supportsReferences ); wFilename.setEnabled( radioFilename.getSelection() ); wbLogFilename.setEnabled( wSetLogfile.getSelection() ); wJobname.setEnabled( rep != null && radioByName.getSelection() ); wbJobname.setEnabled( rep != null ); wDirectory.setEnabled( rep != null && radioByName.getSelection() ); wByReference.setEnabled( rep != null && radioByReference.getSelection() && supportsReferences ); wbByReference.setEnabled( rep != null && supportsReferences ); wlLogfile.setEnabled( wSetLogfile.getSelection() ); wLogfile.setEnabled( wSetLogfile.getSelection() ); wlLogext.setEnabled( wSetLogfile.getSelection() ); wLogext.setEnabled( wSetLogfile.getSelection() ); wlCreateParentFolder.setEnabled( wSetLogfile.getSelection() ); wCreateParentFolder.setEnabled( wSetLogfile.getSelection() ); wlAddDate.setEnabled( wSetLogfile.getSelection() ); wAddDate.setEnabled( wSetLogfile.getSelection() ); wlAddTime.setEnabled( wSetLogfile.getSelection() ); wAddTime.setEnabled( wSetLogfile.getSelection() ); wlLoglevel.setEnabled( wSetLogfile.getSelection() ); wLoglevel.setEnabled( wSetLogfile.getSelection() ); wlAppendLogfile.setEnabled( wSetLogfile.getSelection() ); wAppendLogfile.setEnabled( wSetLogfile.getSelection() ); wlWaitingToFinish.setEnabled( !Const.isEmpty( wSlaveServer.getText() ) ); wWaitingToFinish.setEnabled( !Const.isEmpty( wSlaveServer.getText() ) ); wlFollowingAbortRemotely.setEnabled( wWaitingToFinish.getSelection() && !Const.isEmpty( wSlaveServer.getText() ) ); wFollowingAbortRemotely .setEnabled( wWaitingToFinish.getSelection() && !Const.isEmpty( wSlaveServer.getText() ) ); wlExpandRemote.setEnabled( !Const.isEmpty( wSlaveServer.getText() ) ); wExpandRemote.setEnabled( !Const.isEmpty( wSlaveServer.getText() ) ); } public void getData() { wName.setText( Const.NVL( jobEntry.getName(), "" ) ); specificationMethod = jobEntry.getSpecificationMethod(); switch ( specificationMethod ) { case FILENAME: wFilename.setText( Const.NVL( jobEntry.getFilename(), "" ) ); break; case REPOSITORY_BY_NAME: wDirectory.setText( Const.NVL( jobEntry.getDirectory(), "" ) ); wJobname.setText( Const.NVL( jobEntry.getJobName(), "" ) ); break; case REPOSITORY_BY_REFERENCE: referenceObjectId = jobEntry.getJobObjectId(); wByReference.setText( "" ); if ( rep != null ) { getByReferenceData( referenceObjectId ); } break; default: break; } setRadioButtons(); // Arguments if ( jobEntry.arguments != null ) { for ( int i = 0; i < jobEntry.arguments.length; i++ ) { TableItem ti = wFields.table.getItem( i ); if ( jobEntry.arguments[i] != null ) { ti.setText( 1, jobEntry.arguments[i] ); } } wFields.setRowNums(); wFields.optWidth( true ); } // Parameters if ( jobEntry.parameters != null ) { for ( int i = 0; i < jobEntry.parameters.length; i++ ) { TableItem ti = wParameters.table.getItem( i ); if ( !Const.isEmpty( jobEntry.parameters[i] ) ) { ti.setText( 1, Const.NVL( jobEntry.parameters[i], "" ) ); ti.setText( 2, Const.NVL( jobEntry.parameterFieldNames[i], "" ) ); ti.setText( 3, Const.NVL( jobEntry.parameterValues[i], "" ) ); } } wParameters.setRowNums(); wParameters.optWidth( true ); } wPassParams.setSelection( jobEntry.isPassingAllParameters() ); wPrevious.setSelection( jobEntry.argFromPrevious ); wPrevToParams.setSelection( jobEntry.paramsFromPrevious ); wSetLogfile.setSelection( jobEntry.setLogfile ); if ( jobEntry.logfile != null ) { wLogfile.setText( jobEntry.logfile ); } if ( jobEntry.logext != null ) { wLogext.setText( jobEntry.logext ); } wAddDate.setSelection( jobEntry.addDate ); wAddTime.setSelection( jobEntry.addTime ); if ( jobEntry.getRemoteSlaveServerName() != null ) { wSlaveServer.setText( jobEntry.getRemoteSlaveServerName() ); } wPassExport.setSelection( jobEntry.isPassingExport() ); wForceSeparateLogging.setSelection( jobEntry.isForcingSeparateLogging() ); if ( jobEntry.logFileLevel != null ) { wLoglevel.select( jobEntry.logFileLevel.getLevel() ); } else { // Set the default log level wLoglevel.select( JobEntryJob.DEFAULT_LOG_LEVEL.getLevel() ); } wAppendLogfile.setSelection( jobEntry.setAppendLogfile ); wCreateParentFolder.setSelection( jobEntry.createParentFolder ); wWaitingToFinish.setSelection( jobEntry.isWaitingToFinish() ); wFollowingAbortRemotely.setSelection( jobEntry.isFollowingAbortRemotely() ); wExpandRemote.setSelection( jobEntry.isExpandingRemoteJob() ); wName.selectAll(); wName.setFocus(); } private void getByReferenceData( ObjectId referenceObjectId ) { try { RepositoryObject jobInf = rep.getObjectInformation( referenceObjectId, RepositoryObjectType.JOB ); if ( jobInf != null ) { getByReferenceData( jobInf ); } } catch ( KettleException e ) { new ErrorDialog( shell, BaseMessages.getString( PKG, "JobEntryJobDialog.Exception.UnableToReferenceObjectId.Title" ), BaseMessages.getString( PKG, "JobEntryJobDialog.Exception.UnableToReferenceObjectId.Message" ), e ); } } private void cancel() { jobEntry.setChanged( backupChanged ); jobEntry = null; dispose(); } private void getInfo( JobEntryJob jej ) { jej.setName( wName.getText() ); jej.setSpecificationMethod( specificationMethod ); switch ( specificationMethod ) { case FILENAME: jej.setFileName( wFilename.getText() ); jej.setDirectory( null ); jej.setJobName( null ); jej.setJobObjectId( null ); break; case REPOSITORY_BY_NAME: jej.setFileName( null ); jej.setDirectory( wDirectory.getText() ); jej.setJobName( wJobname.getText() ); jej.setJobObjectId( null ); break; case REPOSITORY_BY_REFERENCE: jej.setFileName( null ); jej.setDirectory( null ); jej.setJobName( null ); jej.setJobObjectId( referenceObjectId ); break; default: break; } // Do the arguments int nritems = wFields.nrNonEmpty(); int nr = 0; for ( int i = 0; i < nritems; i++ ) { String arg = wFields.getNonEmpty( i ).getText( 1 ); if ( arg != null && arg.length() != 0 ) { nr++; } } jej.arguments = new String[nr]; nr = 0; for ( int i = 0; i < nritems; i++ ) { String arg = wFields.getNonEmpty( i ).getText( 1 ); if ( arg != null && arg.length() != 0 ) { jej.arguments[nr] = arg; nr++; } } // Do the parameters nritems = wParameters.nrNonEmpty(); nr = 0; for ( int i = 0; i < nritems; i++ ) { String param = wParameters.getNonEmpty( i ).getText( 1 ); if ( param != null && param.length() != 0 ) { nr++; } } jej.parameters = new String[nr]; jej.parameterFieldNames = new String[nr]; jej.parameterValues = new String[nr]; nr = 0; for ( int i = 0; i < nritems; i++ ) { String param = wParameters.getNonEmpty( i ).getText( 1 ); String fieldName = wParameters.getNonEmpty( i ).getText( 2 ); String value = wParameters.getNonEmpty( i ).getText( 3 ); jej.parameters[nr] = param; if ( !Const.isEmpty( Const.trim( fieldName ) ) ) { jej.parameterFieldNames[nr] = fieldName; } else { jej.parameterFieldNames[nr] = ""; } if ( !Const.isEmpty( Const.trim( value ) ) ) { jej.parameterValues[nr] = value; } else { jej.parameterValues[nr] = ""; } nr++; } jej.setPassingAllParameters( wPassParams.getSelection() ); jej.setForcingSeparateLogging( wForceSeparateLogging.getSelection() ); jej.setLogfile = wSetLogfile.getSelection(); jej.addDate = wAddDate.getSelection(); jej.addTime = wAddTime.getSelection(); jej.logfile = wLogfile.getText(); jej.logext = wLogext.getText(); if ( wLoglevel.getSelectionIndex() >= 0 ) { jej.logFileLevel = LogLevel.values()[wLoglevel.getSelectionIndex()]; } else { jej.logFileLevel = LogLevel.BASIC; } jej.argFromPrevious = wPrevious.getSelection(); jej.paramsFromPrevious = wPrevToParams.getSelection(); jej.execPerRow = wEveryRow.getSelection(); jej.setRemoteSlaveServerName( wSlaveServer.getText() ); jej.setPassingExport( wPassExport.getSelection() ); jej.setAppendLogfile = wAppendLogfile.getSelection(); jej.setWaitingToFinish( wWaitingToFinish.getSelection() ); jej.createParentFolder = wCreateParentFolder.getSelection(); jej.setFollowingAbortRemotely( wFollowingAbortRemotely.getSelection() ); jej.setExpandingRemoteJob( wExpandRemote.getSelection() ); } private void ok() { if ( Const.isEmpty( wName.getText() ) ) { MessageBox mb = new MessageBox( shell, SWT.OK | SWT.ICON_ERROR ); mb.setText( BaseMessages.getString( PKG, "System.StepJobEntryNameMissing.Title" ) ); mb.setMessage( BaseMessages.getString( PKG, "System.JobEntryNameMissing.Msg" ) ); mb.open(); return; } getInfo( jobEntry ); dispose(); } }
apache-2.0
sacjaya/siddhi-3
modules/siddhi-core/src/main/java/org/wso2/siddhi/core/executor/condition/compare/less_than/LessThanCompareConditionExecutorLongInt.java
1269
/* * Copyright (c) 2005 - 2014, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.wso2.siddhi.core.executor.condition.compare.less_than; import org.wso2.siddhi.core.executor.expression.ExpressionExecutor; public class LessThanCompareConditionExecutorLongInt extends LessThenCompareConditionExecutor { public LessThanCompareConditionExecutorLongInt(ExpressionExecutor leftExpressionExecutor, ExpressionExecutor rightExpressionExecutor) { super(leftExpressionExecutor, rightExpressionExecutor); } @Override protected Boolean execute(Object left, Object right) { return (Long) left < (Integer) right; } }
apache-2.0
peteryhwong/jabsc
src/main/java/bnfc/abs/Absyn/SIf.java
712
package bnfc.abs.Absyn; // Java Package generated by the BNF Converter. public class SIf extends Stm { public final PureExp pureexp_; public final Stm stm_; public SIf(PureExp p1, Stm p2) { pureexp_ = p1; stm_ = p2; } public <R,A> R accept(bnfc.abs.Absyn.Stm.Visitor<R,A> v, A arg) { return v.visit(this, arg); } public boolean equals(Object o) { if (this == o) return true; if (o instanceof bnfc.abs.Absyn.SIf) { bnfc.abs.Absyn.SIf x = (bnfc.abs.Absyn.SIf)o; return this.pureexp_.equals(x.pureexp_) && this.stm_.equals(x.stm_); } return false; } public int hashCode() { return 37*(this.pureexp_.hashCode())+this.stm_.hashCode(); } }
apache-2.0
alsash/reciper
app/src/main/java/com/alsash/reciper/ui/fragment/dialog/RecipeDialogAuthorFragment.java
1455
package com.alsash.reciper.ui.fragment.dialog; import android.content.Intent; import com.alsash.reciper.R; import com.alsash.reciper.app.ReciperApp; import com.alsash.reciper.logic.NavigationLogic; import com.alsash.reciper.mvp.model.entity.Author; import com.alsash.reciper.mvp.presenter.RecipeDialogAuthorPresenter; import com.alsash.reciper.mvp.view.RecipeDialogAuthorView; import javax.inject.Inject; /** * Complex Category selection dialog */ public class RecipeDialogAuthorFragment extends BaseSelectionDialogFragment<Author, RecipeDialogAuthorView> { @Inject RecipeDialogAuthorPresenter presenter; @Inject NavigationLogic navigator; public static RecipeDialogAuthorFragment newInstance(Intent intent) { return getThisFragment(new RecipeDialogAuthorFragment(), intent); } @Override protected Class<?> getEntityClass() { return Author.class; } @Override protected String getTitle() { return getString(R.string.fragment_recipe_dialog_author_title); } @Override protected Integer getLayoutRes() { return R.layout.fragment_recipe_dialog_author; } @Override protected RecipeDialogAuthorPresenter inject() { ((ReciperApp) getActivity().getApplicationContext()) .getUiDialogComponent() .inject(this); return presenter.setRestriction(navigator.getRestriction(getThisIntent(this))); } }
apache-2.0
webfirmframework/wff
wffweb/src/main/java/com/webfirmframework/wffweb/tag/html/ModifiedParentData.java
1614
/* * Copyright 2014-2022 Web Firm Framework * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.webfirmframework.wffweb.tag.html; import com.webfirmframework.wffweb.tag.html.SharedTagContent.Content; import com.webfirmframework.wffweb.tag.html.SharedTagContent.ContentFormatter; /** * NB: only for internal use * * @author WFF * @since 3.0.6 * */ final class ModifiedParentData<T> { private final AbstractHtml parent; private final SharedTagContent.Content<String> contentApplied; private final SharedTagContent.ContentFormatter<T> formatter; public ModifiedParentData(final AbstractHtml parent, final Content<String> contentApplied, final ContentFormatter<T> formatter) { super(); this.parent = parent; this.contentApplied = contentApplied; this.formatter = formatter; } AbstractHtml parent() { return parent; } SharedTagContent.Content<String> contentApplied() { return contentApplied; } SharedTagContent.ContentFormatter<T> formatter() { return formatter; } }
apache-2.0
KarloKnezevic/Ferko
src/java/hr/fer/zemris/jcms/caching/impl/JCMSCacheOSImpl.java
3489
package hr.fer.zemris.jcms.caching.impl; import hr.fer.zemris.jcms.JCMSSettings; import hr.fer.zemris.jcms.beans.cached.CourseScoreTable; import hr.fer.zemris.jcms.beans.cached.Dependencies; import hr.fer.zemris.jcms.caching.IJCMSCache; import java.io.File; import java.io.IOException; import java.util.Properties; import com.opensymphony.oscache.base.NeedsRefreshException; import com.opensymphony.oscache.general.GeneralCacheAdministrator; public class JCMSCacheOSImpl implements IJCMSCache { private GeneralCacheAdministrator gcaScoreTable; private GeneralCacheAdministrator gcaDependencies; public JCMSCacheOSImpl(Properties p) { gcaScoreTable = new GeneralCacheAdministrator(p); gcaDependencies = new GeneralCacheAdministrator(p); } public JCMSCacheOSImpl() throws IOException { File rootDir = JCMSSettings.getSettings().getRootDir(); File cacheDir = new File(rootDir,"jcms-oscache"); cacheDir.mkdir(); createCacheScoreTable(cacheDir); createCacheDependencies(cacheDir); } private void createCacheScoreTable(File cacheDir) throws IOException { File cacheDir1 = new File(cacheDir,"scoreTables"); cacheDir1.mkdir(); Properties p = new Properties(); p.setProperty("cache.memory", "true"); p.setProperty("cache.persistence.class", "com.opensymphony.oscache.plugins.diskpersistence.DiskPersistenceListener"); p.setProperty("cache.path", cacheDir1.getCanonicalPath()); p.setProperty("cache.persistence.overflow.only", "false"); p.setProperty("cache.algorithm", "com.opensymphony.oscache.base.algorithm.LRUCache"); p.setProperty("cache.blocking", "false"); p.setProperty("cache.capacity", "2"); p.setProperty("cache.unlimited.disk", "true"); gcaScoreTable = new GeneralCacheAdministrator(p); } private void createCacheDependencies(File cacheDir) throws IOException { File cacheDir1 = new File(cacheDir,"dependencies"); cacheDir1.mkdir(); Properties p = new Properties(); p.setProperty("cache.memory", "true"); p.setProperty("cache.persistence.class", "com.opensymphony.oscache.plugins.diskpersistence.DiskPersistenceListener"); p.setProperty("cache.path", cacheDir1.getCanonicalPath()); p.setProperty("cache.persistence.overflow.only", "false"); p.setProperty("cache.algorithm", "com.opensymphony.oscache.base.algorithm.LRUCache"); p.setProperty("cache.blocking", "false"); p.setProperty("cache.capacity", "100"); p.setProperty("cache.unlimited.disk", "true"); gcaDependencies = new GeneralCacheAdministrator(p); } @Override public CourseScoreTable getCourseScoreTable(String courseInstanceID) { String key = "CST:"+courseInstanceID; CourseScoreTable table; try { table = (CourseScoreTable)gcaScoreTable.getFromCache(key); } catch (NeedsRefreshException e) { table = (CourseScoreTable)e.getCacheContent(); gcaScoreTable.cancelUpdate(key); } return table; } @Override public void put(CourseScoreTable table) { gcaScoreTable.putInCache("CST:"+table.getCourseInstanceID(), table); } @Override public Dependencies getDependencies(String courseInstanceID) { String key = "DEP:"+courseInstanceID; Dependencies dep; try { dep = (Dependencies)gcaDependencies.getFromCache(key); } catch (NeedsRefreshException e) { dep = (Dependencies)e.getCacheContent(); gcaDependencies.cancelUpdate(key); } return dep; } @Override public void put(Dependencies dependencies) { gcaDependencies.putInCache("DEP:"+dependencies.getCourseInstanceID(), dependencies); } }
apache-2.0
jaschenk/jeffaschenk-commons
src/main/java/jeffaschenk/commons/parsers/AnnotationParser.java
19352
package jeffaschenk.commons.parsers; import javassist.*; import javassist.bytecode.AnnotationsAttribute; import jeffaschenk.commons.parsers.objects.ClassAnnotationData; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import java.lang.reflect.Method; import java.util.HashMap; import java.util.Map; /** * Simple Annotation Parser Simple Parsers a Classes Annotations and returns a * Collection Map of those attributes and properties of the Object class. This * parser uses Javassist to perform introspection of the Java ByteCode. * * @author jeffaschenk@gmail.com * @version $Id: $ */ public class AnnotationParser { // *************************************** // Logging /** * Constant <code>log</code> */ protected static Log log = LogFactory.getLog(AnnotationParser.class); // ******************************************* // ClassPool for Loading Compile time Classes ClassPool cp; /** * Prevent the Instantiation */ public AnnotationParser() { cp = ClassPool.getDefault(); cp.insertClassPath(new ClassClassPath(this.getClass())); } /** * Parse a Classes Annotations and return in an Named Value Association * Form, return Class, Field and Method Annotations. * * @param clazz a {@link java.lang.Class} object. * @return {@link jeffaschenk.commons.parsers.objects.ClassAnnotationData} object. */ public ClassAnnotationData parse(Class<?> clazz) { // ************************************ // Obtain Our Class. CtClass cc = null; try { cc = cp.get(clazz.getName()); } catch (javassist.NotFoundException nfe) { log.error("Class Not Found:[" + clazz.getName() + "], " + nfe.getMessage() + "."); } // ************************************ // Did we obtain the Javassist Object? if (cc == null) { return null; } // ************************************ // Obtain the Class Annotations. ClassAnnotationData ad = new ClassAnnotationData(cc.getName()); ad.setSimpleName(cc.getSimpleName()); ad.setClassAnnotations(this.parseClassAnnotations(cc)); ad.setFieldAnnotations(this.parseClassFieldAnnotations(cc)); ad.setMethodAnnotations(this .parseClassMethodAnnotations(cc)); // ************************************ // Return the Association Map. return ad; } /** * Parse a Classes Annotations and return in an Named Value Association * Form, return Class Annotations. * * @param clazz a {@link java.lang.Class} object. * @return {@link java.util.Map} object. */ public Map<String, String> parseClassAnnotations(Class<?> clazz) { CtClass cc = null; try { cc = cp.get(clazz.getName()); // ************************************ // Return the Association Map. return parseClassAnnotations(cc); } catch (javassist.NotFoundException nfe) { log.error("Class Not Found:[" + clazz.getName() + "], " + nfe.getMessage() + "."); return null; } } /** * Parse a Classes Annotations and return in an Named Value Association * Form, return Class, Field and Method Annotations. * * @param cc a {@link javassist.CtClass} object. * @return {@link java.util.Map} object. */ public Map<String, String> parseClassAnnotations(CtClass cc) { // ************************************* // Initialize. Map<String, String> annotations = new HashMap<String, String>(); // ************************************* // Parse the Annotations for this Class. if (log.isTraceEnabled()) { log.trace("Class:[" + cc.getSimpleName() + "]"); } // *************************************************** // Check for all Visible Annotations. AnnotationsAttribute attr = (AnnotationsAttribute) cc.getClassFile() .getAttribute(AnnotationsAttribute.visibleTag); if (attr != null) { for (javassist.bytecode.annotation.Annotation an : attr .getAnnotations()) { // ********************************************** // Check for any Annotation Members if (an.getMemberNames() != null) { for (Object name : an.getMemberNames()) { if (log.isTraceEnabled()) { log.trace("*** Class Annotation:[" + an.getTypeName() + "], Member Name:[" + name + "], Value:[" + an.getMemberValue(name.toString()) .toString().replace("\042", "").trim() + "]"); } // ************************************************ // Save Annotations in association Named Value Map. annotations.put(an.getTypeName() + "." + name.toString(), an.getMemberValue( name.toString()).toString().replace("\042", "").trim()); } // End of Inner For Each Loop for Annotation Members } else { if (log.isTraceEnabled()) { log.trace("*** Class Annotation:[" + an.getTypeName() + "]"); } // ************************************************ // Save Annotations in association Named Value Map. annotations.put(an.getTypeName(), ""); } } // End of Outer For Loop for Visible Annotations } // End of Check for Visible Annotations. // ************************************ // Return the Association Map. return annotations; } /** * Parse a Classes Annotations and return in an Named Value Association * Form, return Field Annotations. * * @param clazz a {@link java.lang.Class} object. * @return {@link java.util.Map} object. */ public Map<String, String> parseClassFieldAnnotations(Class<?> clazz) { CtClass cc = null; try { cc = cp.get(clazz.getName()); // ************************************ // Return the Association Map. return parseClassFieldAnnotations(cc); } catch (javassist.NotFoundException nfe) { log.error("Class Not Found:[" + clazz.getName() + "], " + nfe.getMessage() + "."); return null; } } /** * Parse a Classes Annotations and return in an Named Value Association * Form, return Field Annotations. * * @param cc a {@link javassist.CtClass} object. * @return {@link java.util.Map} object. */ public Map<String, String> parseClassFieldAnnotations(CtClass cc) { // ************************************* // Initialize. Map<String, String> annotations = new HashMap<String, String>(); // ******************************************* // Parse the Field Annotations for this Class. CtField[] fields = cc.getDeclaredFields(); if (fields == null) { return annotations; } for (CtField field : fields) { // ****************************************************** // Skip standard serialVersionUID Fields. if (field.getName().equalsIgnoreCase("serialVersionUID")) { continue; } if (log.isTraceEnabled()) { log.trace("*** Field:[" + field.getName() + "]"); } // *************************************************** // Check for all Visible Field Annotations. AnnotationsAttribute attr = (AnnotationsAttribute) field .getFieldInfo().getAttribute( AnnotationsAttribute.visibleTag); if (attr != null) { for (javassist.bytecode.annotation.Annotation an : attr .getAnnotations()) { // ********************************************** // Check for any Annotation Members if (an.getMemberNames() != null) { for (Object name : an.getMemberNames()) { if (log.isTraceEnabled()) { log.trace("*** Field:[" + field.getName() + "] Annotation:[" + an.getTypeName() + "], Member Name:[" + name + "], Value:[" + an.getMemberValue(name.toString()) .toString().replace("\042", "").trim() + "]"); } // ************************************************ // Save Annotations in association Named Value Map. annotations.put(field.getName() + ":" + an.getTypeName() + "." + name.toString(), an.getMemberValue( name.toString()).toString().replace("\042", "").trim()); } // End of Inner For Each Loop for Annotation // Members } else { if (log.isTraceEnabled()) { log .trace("*** Field:[" + field.getName() + "] Annotation:[" + an.getTypeName() + "]"); } // ************************************************ // Save Annotations in association Named Value Map. annotations.put(an.getTypeName(), ""); } } // End of Outer For Loop for Visible Annotations } // End of Check for Visible Annotations. } // End of Fields For Each Loop. // ************************************ // Return the Association Map. return annotations; } /** * Parse a Classes Annotations and return in an Named Value Association * Form, return Method Annotations. * * @param clazz a {@link java.lang.Class} object. * @return {@link java.util.Map} object. */ public Map<String, String> parseClassMethodAnnotations(Class<?> clazz) { CtClass cc = null; try { ClassPool cp = new ClassPool(); cc = cp.get(clazz.getName()); // ************************************ // Return the Association Map. return parseClassMethodAnnotations(cc); } catch (javassist.NotFoundException nfe) { log.error("Class Not Found:[" + clazz.getName() + "], " + nfe.getMessage() + "."); return null; } } /** * Parse a Classes Annotations and return in an Named Value Association * Form, return Method Annotations. * * @param cc a {@link javassist.CtClass} object. * @return {@link java.util.Map} object. */ public Map<String, String> parseClassMethodAnnotations(CtClass cc) { // ************************************* // Initialize. Map<String, String> annotations = new HashMap<String, String>(); // ******************************************* // Parse the Field Annotations for this Class. CtMethod[] methods = cc.getDeclaredMethods(); if (methods == null) { return annotations; } for (CtMethod method : methods) { if (log.isTraceEnabled()) { log.trace("*** Method:[" + method.getName() + "]"); } // *************************************************** // Check for all Visible Field Annotations. AnnotationsAttribute attr = (AnnotationsAttribute) method .getMethodInfo().getAttribute( AnnotationsAttribute.visibleTag); if (attr != null) { for (javassist.bytecode.annotation.Annotation an : attr .getAnnotations()) { // ********************************************** // Check for any Annotation Members if (an.getMemberNames() != null) { for (Object name : an.getMemberNames()) { if (log.isTraceEnabled()) { log.trace("*** Method:[" + method.getName() + "] Annotation:[" + an.getTypeName() + "], Member Name:[" + name + "], Value:[" + an.getMemberValue(name.toString()) .toString().replace("\042", "").trim() + "]"); } // ************************************************ // Save Annotations in association Named Value Map. annotations.put(method.getName() + ":" + an.getTypeName() + "." + name.toString(), an.getMemberValue( name.toString()).toString().replace("\042", "").trim()); } // End of Inner For Each Loop for Annotation // Members } else { if (log.isTraceEnabled()) { log .trace("*** Method:[" + method.getName() + "] Annotation:[" + an.getTypeName() + "]"); } // ************************************************ // Save Annotations in association Named Value Map. annotations.put(an.getTypeName(), ""); } } // End of Outer For Loop for Visible Annotations } // End of Check for Visible Annotations. } // End of Fields For Each Loop. // ************************************ // Return the Association Map. return annotations; } /** * Parse a Classes Annotations and return in an Named Value Association * Form, return Method Annotations. * * @param method a {@link java.lang.reflect.Method} object. * @return {@link java.util.Map} object. */ public Map<String, String> parseSpecificClassMethodAnnotations(Method method) { // ************************************* // Initialize. Map<String, String> annotations = new HashMap<String, String>(); // ************************************ // Obtain Our Class. CtClass cc = null; try { cc = cp.get(method.getDeclaringClass().getName()); } catch (javassist.NotFoundException nfe) { log.error("Class Not Found:[" + method.getDeclaringClass().getName() + "], " + nfe.getMessage() + "."); } // ************************************ // Did we obtain the Javassist Object? if (cc == null) { return null; } // ******************************************* // Parse the Annotations for this Method. CtMethod[] methods = cc.getDeclaredMethods(); if (methods == null) { return annotations; } for (CtMethod ctmethod : methods) { if (log.isTraceEnabled()) { log.trace("*** Method:[" + method.getName() + "]"); } // *************************************************** // Check for all Visible Field Annotations. AnnotationsAttribute attr = (AnnotationsAttribute) ctmethod .getMethodInfo().getAttribute( AnnotationsAttribute.visibleTag); if (attr != null) { for (javassist.bytecode.annotation.Annotation an : attr .getAnnotations()) { // ********************************************** // Check for any Annotation Members if (an.getMemberNames() != null) { for (Object name : an.getMemberNames()) { if (log.isTraceEnabled()) { log.trace("*** Method:[" + method.getName() + "] Annotation:[" + an.getTypeName() + "], Member Name:[" + name + "], Value:[" + an.getMemberValue(name.toString()) .toString().replace("\042", "").trim() + "]"); } // ************************************************ // Save Annotations in association Named Value Map. annotations.put(method.getName() + ":" + an.getTypeName() + "." + name.toString(), an.getMemberValue( name.toString()).toString().replace("\042", "").trim()); } // End of Inner For Each Loop for Annotation // Members } else { if (log.isTraceEnabled()) { log .trace("*** Method:[" + method.getName() + "] Annotation:[" + an.getTypeName() + "]"); } // ************************************************ // Save Annotations in association Named Value Map. annotations.put(an.getTypeName(), ""); } } // End of Outer For Loop for Visible Annotations } // End of Check for Visible Annotations. } // End of Fields For Each Loop. // ************************************ // Return the Association Map. return annotations; } }
apache-2.0
signed/intellij-community
platform/util/src/com/intellij/icons/AllIcons.java
117536
/* * Copyright 2000-2017 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.intellij.icons; import com.intellij.openapi.util.IconLoader; import javax.swing.*; /** * NOTE THIS FILE IS AUTO-GENERATED * DO NOT EDIT IT BY HAND, run build/scripts/icons.gant instead */ public class AllIcons { public static class Actions { public static final Icon AddFacesSupport = IconLoader.getIcon("/actions/addFacesSupport.png"); // 16x16 public static final Icon AddMulticaret = IconLoader.getIcon("/actions/AddMulticaret.png"); // 16x16 public static final Icon AllLeft = IconLoader.getIcon("/actions/allLeft.png"); // 16x16 public static final Icon AllRight = IconLoader.getIcon("/actions/allRight.png"); // 16x16 public static final Icon Annotate = IconLoader.getIcon("/actions/annotate.png"); // 16x16 public static final Icon Back = IconLoader.getIcon("/actions/back.png"); // 16x16 public static final Icon Browser_externalJavaDoc = IconLoader.getIcon("/actions/browser-externalJavaDoc.png"); // 16x16 public static final Icon Cancel = IconLoader.getIcon("/actions/cancel.png"); // 16x16 public static final Icon ChangeView = IconLoader.getIcon("/actions/changeView.png"); // 16x16 public static final Icon Checked = IconLoader.getIcon("/actions/checked.png"); // 12x12 public static final Icon Checked_selected = IconLoader.getIcon("/actions/checked_selected.png"); // 12x12 public static final Icon Checked_small = IconLoader.getIcon("/actions/checked_small.png"); // 11x11 public static final Icon Checked_small_selected = IconLoader.getIcon("/actions/checked_small_selected.png"); // 11x11 public static final Icon CheckedBlack = IconLoader.getIcon("/actions/checkedBlack.png"); // 12x12 public static final Icon CheckedGrey = IconLoader.getIcon("/actions/checkedGrey.png"); // 12x12 public static final Icon CheckMulticaret = IconLoader.getIcon("/actions/CheckMulticaret.png"); // 16x16 public static final Icon CheckOut = IconLoader.getIcon("/actions/checkOut.png"); // 16x16 public static final Icon Clean = IconLoader.getIcon("/actions/clean.png"); // 16x16 public static final Icon CleanLight = IconLoader.getIcon("/actions/cleanLight.png"); // 16x16 public static final Icon Clear = IconLoader.getIcon("/actions/clear.png"); // 16x16 public static final Icon Close = IconLoader.getIcon("/actions/close.png"); // 16x16 public static final Icon CloseHovered = IconLoader.getIcon("/actions/closeHovered.png"); // 16x16 public static final Icon CloseNew = IconLoader.getIcon("/actions/closeNew.png"); // 16x16 public static final Icon CloseNewHovered = IconLoader.getIcon("/actions/closeNewHovered.png"); // 16x16 public static final Icon Collapseall = IconLoader.getIcon("/actions/collapseall.png"); // 16x16 public static final Icon Commit = IconLoader.getIcon("/actions/commit.png"); // 16x16 public static final Icon Compile = IconLoader.getIcon("/actions/compile.png"); // 16x16 public static final Icon Copy = IconLoader.getIcon("/actions/copy.png"); // 16x16 public static final Icon CreateFromUsage = IconLoader.getIcon("/actions/createFromUsage.png"); // 16x16 public static final Icon CreatePatch = IconLoader.getIcon("/actions/createPatch.png"); // 16x16 public static final Icon Cross = IconLoader.getIcon("/actions/cross.png"); // 12x12 public static final Icon Delete = IconLoader.getIcon("/actions/delete.png"); // 16x16 public static final Icon DiagramDiff = IconLoader.getIcon("/actions/diagramDiff.png"); // 16x16 public static final Icon Diff = IconLoader.getIcon("/actions/diff.png"); // 16x16 public static final Icon DiffPreview = IconLoader.getIcon("/actions/diffPreview.png"); // 16x16 public static final Icon DiffWithClipboard = IconLoader.getIcon("/actions/diffWithClipboard.png"); // 16x16 public static final Icon DiffWithCurrent = IconLoader.getIcon("/actions/diffWithCurrent.png"); // 16x16 public static final Icon Down = IconLoader.getIcon("/actions/down.png"); // 16x16 public static final Icon Download = IconLoader.getIcon("/actions/download.png"); // 16x16 public static final Icon Dump = IconLoader.getIcon("/actions/dump.png"); // 16x16 public static final Icon Edit = IconLoader.getIcon("/actions/edit.png"); // 14x14 public static final Icon EditSource = IconLoader.getIcon("/actions/editSource.png"); // 16x16 public static final Icon ErDiagram = IconLoader.getIcon("/actions/erDiagram.png"); // 16x16 public static final Icon Exclude = IconLoader.getIcon("/actions/exclude.png"); // 14x14 public static final Icon Execute = IconLoader.getIcon("/actions/execute.png"); // 16x16 public static final Icon Exit = IconLoader.getIcon("/actions/exit.png"); // 16x16 public static final Icon Expandall = IconLoader.getIcon("/actions/expandall.png"); // 16x16 public static final Icon Export = IconLoader.getIcon("/actions/export.png"); // 16x16 @SuppressWarnings("unused") @Deprecated public static final Icon FileStatus = IconLoader.getIcon("/actions/fileStatus.png"); // 16x16 public static final Icon Filter_small = IconLoader.getIcon("/actions/filter_small.png"); // 16x16 public static final Icon Find = IconLoader.getIcon("/actions/find.png"); // 16x16 public static final Icon FindPlain = IconLoader.getIcon("/actions/findPlain.png"); // 16x16 public static final Icon FindWhite = IconLoader.getIcon("/actions/findWhite.png"); // 16x16 public static final Icon ForceRefresh = IconLoader.getIcon("/actions/forceRefresh.png"); // 16x16 public static final Icon Forward = IconLoader.getIcon("/actions/forward.png"); // 16x16 public static final Icon GC = IconLoader.getIcon("/actions/gc.png"); // 16x16 public static final Icon Get = IconLoader.getIcon("/actions/get.png"); // 16x16 public static final Icon GroupByClass = IconLoader.getIcon("/actions/GroupByClass.png"); // 16x16 public static final Icon GroupByFile = IconLoader.getIcon("/actions/GroupByFile.png"); // 16x16 public static final Icon GroupByMethod = IconLoader.getIcon("/actions/groupByMethod.png"); // 16x16 public static final Icon GroupByModule = IconLoader.getIcon("/actions/GroupByModule.png"); // 16x16 public static final Icon GroupByModuleGroup = IconLoader.getIcon("/actions/GroupByModuleGroup.png"); // 16x16 public static final Icon GroupByPackage = IconLoader.getIcon("/actions/GroupByPackage.png"); // 16x16 public static final Icon GroupByPrefix = IconLoader.getIcon("/actions/GroupByPrefix.png"); // 16x16 public static final Icon GroupByTestProduction = IconLoader.getIcon("/actions/groupByTestProduction.png"); // 16x16 public static final Icon Help = IconLoader.getIcon("/actions/help.png"); // 16x16 public static final Icon Install = IconLoader.getIcon("/actions/install.png"); // 16x16 public static final Icon IntentionBulb = IconLoader.getIcon("/actions/intentionBulb.png"); // 16x16 public static final Icon Left = IconLoader.getIcon("/actions/left.png"); // 16x16 public static final Icon Lightning = IconLoader.getIcon("/actions/lightning.png"); // 16x16 public static final Icon ListChanges = IconLoader.getIcon("/actions/listChanges.png"); // 16x16 public static final Icon Menu_cut = IconLoader.getIcon("/actions/menu-cut.png"); // 16x16 public static final Icon Menu_find = IconLoader.getIcon("/actions/menu-find.png"); // 16x16 public static final Icon Menu_help = IconLoader.getIcon("/actions/menu-help.png"); // 16x16 public static final Icon Menu_open = IconLoader.getIcon("/actions/menu-open.png"); // 16x16 public static final Icon Menu_paste = IconLoader.getIcon("/actions/menu-paste.png"); // 16x16 public static final Icon Menu_replace = IconLoader.getIcon("/actions/menu-replace.png"); // 16x16 public static final Icon Menu_saveall = IconLoader.getIcon("/actions/menu-saveall.png"); // 16x16 public static final Icon Minimize = IconLoader.getIcon("/actions/minimize.png"); // 16x16 public static final Icon Module = IconLoader.getIcon("/actions/module.png"); // 16x16 public static final Icon Move_to_button_top = IconLoader.getIcon("/actions/move-to-button-top.png"); // 11x12 public static final Icon Move_to_button = IconLoader.getIcon("/actions/move-to-button.png"); // 11x10 public static final Icon MoveDown = IconLoader.getIcon("/actions/moveDown.png"); // 14x14 public static final Icon MoveTo2 = IconLoader.getIcon("/actions/MoveTo2.png"); // 16x16 public static final Icon MoveToAnotherChangelist = IconLoader.getIcon("/actions/moveToAnotherChangelist.png"); // 16x16 public static final Icon MoveToStandardPlace = IconLoader.getIcon("/actions/moveToStandardPlace.png"); // 16x16 public static final Icon MoveUp = IconLoader.getIcon("/actions/moveUp.png"); // 14x14 public static final Icon New = IconLoader.getIcon("/actions/new.png"); // 16x16 public static final Icon NewFolder = IconLoader.getIcon("/actions/newFolder.png"); // 16x16 public static final Icon Nextfile = IconLoader.getIcon("/actions/nextfile.png"); // 16x16 public static final Icon NextOccurence = IconLoader.getIcon("/actions/nextOccurence.png"); // 16x16 public static final Icon Pause = IconLoader.getIcon("/actions/pause.png"); // 16x16 public static final Icon PopFrame = IconLoader.getIcon("/actions/popFrame.png"); // 16x16 public static final Icon Prevfile = IconLoader.getIcon("/actions/prevfile.png"); // 16x16 public static final Icon Preview = IconLoader.getIcon("/actions/preview.png"); // 16x16 public static final Icon PreviewDetails = IconLoader.getIcon("/actions/previewDetails.png"); // 16x16 public static final Icon PreviousOccurence = IconLoader.getIcon("/actions/previousOccurence.png"); // 14x14 public static final Icon Profile = IconLoader.getIcon("/actions/profile.png"); // 16x16 public static final Icon ProfileCPU = IconLoader.getIcon("/actions/profileCPU.png"); // 16x16 public static final Icon ProfileMemory = IconLoader.getIcon("/actions/profileMemory.png"); // 16x16 public static final Icon Properties = IconLoader.getIcon("/actions/properties.png"); // 16x16 public static final Icon QuickfixBulb = IconLoader.getIcon("/actions/quickfixBulb.png"); // 16x16 public static final Icon QuickfixOffBulb = IconLoader.getIcon("/actions/quickfixOffBulb.png"); // 16x16 public static final Icon QuickList = IconLoader.getIcon("/actions/quickList.png"); // 16x16 public static final Icon RealIntentionBulb = IconLoader.getIcon("/actions/realIntentionBulb.png"); // 16x16 public static final Icon RealIntentionOffBulb = IconLoader.getIcon("/actions/realIntentionOffBulb.png"); // 16x16 public static final Icon Redo = IconLoader.getIcon("/actions/redo.png"); // 16x16 public static final Icon RefactoringBulb = IconLoader.getIcon("/actions/refactoringBulb.png"); // 16x16 public static final Icon Refresh = IconLoader.getIcon("/actions/refresh.png"); // 16x16 public static final Icon RemoveMulticaret = IconLoader.getIcon("/actions/RemoveMulticaret.png"); // 16x16 public static final Icon Replace = IconLoader.getIcon("/actions/replace.png"); // 16x16 public static final Icon Rerun = IconLoader.getIcon("/actions/rerun.png"); // 16x16 public static final Icon Reset_to_default = IconLoader.getIcon("/actions/reset-to-default.png"); // 16x16 public static final Icon Reset = IconLoader.getIcon("/actions/reset.png"); // 16x16 public static final Icon Reset_to_empty = IconLoader.getIcon("/actions/Reset_to_empty.png"); // 16x16 public static final Icon Restart = IconLoader.getIcon("/actions/restart.png"); // 16x16 public static final Icon Resume = IconLoader.getIcon("/actions/resume.png"); // 16x16 public static final Icon Right = IconLoader.getIcon("/actions/right.png"); // 16x16 public static final Icon Rollback = IconLoader.getIcon("/actions/rollback.png"); // 16x16 public static final Icon RunToCursor = IconLoader.getIcon("/actions/runToCursor.png"); // 16x16 public static final Icon Scratch = IconLoader.getIcon("/actions/scratch.png"); // 16x16 public static final Icon Search = IconLoader.getIcon("/actions/search.png"); // 16x16 public static final Icon SearchNewLine = IconLoader.getIcon("/actions/searchNewLine.png"); // 16x16 public static final Icon SearchNewLineHover = IconLoader.getIcon("/actions/searchNewLineHover.png"); // 16x16 public static final Icon Selectall = IconLoader.getIcon("/actions/selectall.png"); // 16x16 public static final Icon Share = IconLoader.getIcon("/actions/share.png"); // 14x14 public static final Icon ShortcutFilter = IconLoader.getIcon("/actions/shortcutFilter.png"); // 16x16 public static final Icon ShowAsTree = IconLoader.getIcon("/actions/showAsTree.png"); // 16x16 public static final Icon ShowChangesOnly = IconLoader.getIcon("/actions/showChangesOnly.png"); // 16x16 public static final Icon ShowHiddens = IconLoader.getIcon("/actions/showHiddens.png"); // 16x16 public static final Icon ShowImportStatements = IconLoader.getIcon("/actions/showImportStatements.png"); // 16x16 public static final Icon ShowReadAccess = IconLoader.getIcon("/actions/showReadAccess.png"); // 16x16 public static final Icon ShowViewer = IconLoader.getIcon("/actions/showViewer.png"); // 16x16 public static final Icon ShowWriteAccess = IconLoader.getIcon("/actions/showWriteAccess.png"); // 16x16 public static final Icon SortAsc = IconLoader.getIcon("/actions/sortAsc.png"); // 9x8 public static final Icon SortDesc = IconLoader.getIcon("/actions/sortDesc.png"); // 9x8 public static final Icon SplitHorizontally = IconLoader.getIcon("/actions/splitHorizontally.png"); // 16x16 public static final Icon SplitVertically = IconLoader.getIcon("/actions/splitVertically.png"); // 16x16 public static final Icon StartDebugger = IconLoader.getIcon("/actions/startDebugger.png"); // 16x16 public static final Icon StepOut = IconLoader.getIcon("/actions/stepOut.png"); // 16x16 public static final Icon Submit1 = IconLoader.getIcon("/actions/submit1.png"); // 11x11 public static final Icon Suspend = IconLoader.getIcon("/actions/suspend.png"); // 16x16 public static final Icon SwapPanels = IconLoader.getIcon("/actions/swapPanels.png"); // 16x16 public static final Icon SynchronizeFS = IconLoader.getIcon("/actions/synchronizeFS.png"); // 16x16 public static final Icon SynchronizeScrolling = IconLoader.getIcon("/actions/synchronizeScrolling.png"); // 16x16 public static final Icon SyncPanels = IconLoader.getIcon("/actions/syncPanels.png"); // 16x16 public static final Icon ToggleSoftWrap = IconLoader.getIcon("/actions/toggleSoftWrap.png"); // 16x16 public static final Icon TraceInto = IconLoader.getIcon("/actions/traceInto.png"); // 16x16 public static final Icon TraceOver = IconLoader.getIcon("/actions/traceOver.png"); // 16x16 public static final Icon Undo = IconLoader.getIcon("/actions/undo.png"); // 16x16 public static final Icon Uninstall = IconLoader.getIcon("/actions/uninstall.png"); // 16x16 public static final Icon Unselectall = IconLoader.getIcon("/actions/unselectall.png"); // 16x16 public static final Icon Unshare = IconLoader.getIcon("/actions/unshare.png"); // 14x14 public static final Icon UP = IconLoader.getIcon("/actions/up.png"); // 16x16 public static final Icon Upload = IconLoader.getIcon("/actions/upload.png"); // 16x16 } public static class CodeStyle { public static final Icon AddNewSectionRule = IconLoader.getIcon("/codeStyle/AddNewSectionRule.png"); // 16x16 public static final Icon Gear = IconLoader.getIcon("/codeStyle/Gear.png"); // 16x16 public static class Mac { public static final Icon AddNewSectionRule = IconLoader.getIcon("/codeStyle/mac/AddNewSectionRule.png"); // 16x16 } } public static class Css { public static final Icon Atrule = IconLoader.getIcon("/css/atrule.png"); // 16x16 public static final Icon Custom_property = IconLoader.getIcon("/css/custom_property.png"); // 16x16 public static final Icon Import = IconLoader.getIcon("/css/import.png"); // 16x16 public static final Icon Property = IconLoader.getIcon("/css/property.png"); // 16x16 public static final Icon Pseudo_class = IconLoader.getIcon("/css/pseudo-class.png"); // 16x16 public static final Icon Pseudo_element = IconLoader.getIcon("/css/pseudo-element.png"); // 16x16 public static final Icon Toolwindow = IconLoader.getIcon("/css/toolwindow.png"); // 13x13 } public static class Darcula { public static final Icon DoubleComboArrow = IconLoader.getIcon("/darcula/doubleComboArrow.png"); // 7x11 public static final Icon TreeNodeCollapsed = IconLoader.getIcon("/darcula/treeNodeCollapsed.png"); // 9x9 public static final Icon TreeNodeExpanded = IconLoader.getIcon("/darcula/treeNodeExpanded.png"); // 9x9 } public static class Debugger { public static class Actions { public static final Icon Force_run_to_cursor = IconLoader.getIcon("/debugger/actions/force_run_to_cursor.png"); // 16x16 public static final Icon Force_step_into = IconLoader.getIcon("/debugger/actions/force_step_into.png"); // 16x16 public static final Icon Force_step_over = IconLoader.getIcon("/debugger/actions/force_step_over.png"); // 16x16 } public static final Icon AddToWatch = IconLoader.getIcon("/debugger/addToWatch.png"); // 16x16 public static final Icon AttachToProcess = IconLoader.getIcon("/debugger/attachToProcess.png"); // 16x16 public static final Icon AutoVariablesMode = IconLoader.getIcon("/debugger/autoVariablesMode.png"); // 16x16 public static final Icon BreakpointAlert = IconLoader.getIcon("/debugger/breakpointAlert.png"); // 16x16 public static final Icon Class_filter = IconLoader.getIcon("/debugger/class_filter.png"); // 16x16 public static final Icon CommandLine = IconLoader.getIcon("/debugger/commandLine.png"); // 16x16 public static final Icon Console = IconLoader.getIcon("/debugger/console.png"); // 16x16 public static final Icon Console_log = IconLoader.getIcon("/debugger/console_log.png"); // 16x16 public static final Icon Db_array = IconLoader.getIcon("/debugger/db_array.png"); // 16x16 public static final Icon Db_db_object = IconLoader.getIcon("/debugger/db_db_object.png"); // 16x16 public static final Icon Db_dep_exception_breakpoint = IconLoader.getIcon("/debugger/db_dep_exception_breakpoint.png"); // 12x12 public static final Icon Db_dep_field_breakpoint = IconLoader.getIcon("/debugger/db_dep_field_breakpoint.png"); // 12x12 public static final Icon Db_dep_line_breakpoint = IconLoader.getIcon("/debugger/db_dep_line_breakpoint.png"); // 12x12 public static final Icon Db_dep_method_breakpoint = IconLoader.getIcon("/debugger/db_dep_method_breakpoint.png"); // 12x12 public static final Icon Db_disabled_breakpoint = IconLoader.getIcon("/debugger/db_disabled_breakpoint.png"); // 12x12 public static final Icon Db_disabled_breakpoint_process = IconLoader.getIcon("/debugger/db_disabled_breakpoint_process.png"); // 16x16 public static final Icon Db_disabled_exception_breakpoint = IconLoader.getIcon("/debugger/db_disabled_exception_breakpoint.png"); // 12x12 public static final Icon Db_disabled_field_breakpoint = IconLoader.getIcon("/debugger/db_disabled_field_breakpoint.png"); // 12x12 public static final Icon Db_disabled_method_breakpoint = IconLoader.getIcon("/debugger/db_disabled_method_breakpoint.png"); // 12x12 public static final Icon Db_exception_breakpoint = IconLoader.getIcon("/debugger/db_exception_breakpoint.png"); // 12x12 public static final Icon Db_field_breakpoint = IconLoader.getIcon("/debugger/db_field_breakpoint.png"); // 12x12 public static final Icon Db_field_warning_breakpoint = IconLoader.getIcon("/debugger/db_field_warning_breakpoint.png"); // 16x16 public static final Icon Db_invalid_breakpoint = IconLoader.getIcon("/debugger/db_invalid_breakpoint.png"); // 12x12 public static final Icon Db_invalid_field_breakpoint = IconLoader.getIcon("/debugger/db_invalid_field_breakpoint.png"); // 12x12 public static final Icon Db_invalid_method_breakpoint = IconLoader.getIcon("/debugger/db_invalid_method_breakpoint.png"); // 12x12 public static final Icon Db_method_breakpoint = IconLoader.getIcon("/debugger/db_method_breakpoint.png"); // 12x12 public static final Icon Db_method_warning_breakpoint = IconLoader.getIcon("/debugger/db_method_warning_breakpoint.png"); // 16x16 public static final Icon Db_muted_breakpoint = IconLoader.getIcon("/debugger/db_muted_breakpoint.png"); // 12x12 public static final Icon Db_muted_dep_exception_breakpoint = IconLoader.getIcon("/debugger/db_muted_dep_exception_breakpoint.png"); // 12x12 public static final Icon Db_muted_dep_field_breakpoint = IconLoader.getIcon("/debugger/db_muted_dep_field_breakpoint.png"); // 12x12 public static final Icon Db_muted_dep_line_breakpoint = IconLoader.getIcon("/debugger/db_muted_dep_line_breakpoint.png"); // 12x12 public static final Icon Db_muted_dep_method_breakpoint = IconLoader.getIcon("/debugger/db_muted_dep_method_breakpoint.png"); // 12x12 public static final Icon Db_muted_disabled_breakpoint = IconLoader.getIcon("/debugger/db_muted_disabled_breakpoint.png"); // 12x12 public static final Icon Db_muted_disabled_breakpoint_process = IconLoader.getIcon("/debugger/db_muted_disabled_breakpoint_process.png"); // 16x16 public static final Icon Db_muted_disabled_exception_breakpoint = IconLoader.getIcon("/debugger/db_muted_disabled_exception_breakpoint.png"); // 12x12 public static final Icon Db_muted_disabled_field_breakpoint = IconLoader.getIcon("/debugger/db_muted_disabled_field_breakpoint.png"); // 12x12 public static final Icon Db_muted_disabled_method_breakpoint = IconLoader.getIcon("/debugger/db_muted_disabled_method_breakpoint.png"); // 12x12 public static final Icon Db_muted_exception_breakpoint = IconLoader.getIcon("/debugger/db_muted_exception_breakpoint.png"); // 12x12 public static final Icon Db_muted_field_breakpoint = IconLoader.getIcon("/debugger/db_muted_field_breakpoint.png"); // 12x12 public static final Icon Db_muted_field_warning_breakpoint = IconLoader.getIcon("/debugger/db_muted_field_warning_breakpoint.png"); // 16x16 public static final Icon Db_muted_invalid_breakpoint = IconLoader.getIcon("/debugger/db_muted_invalid_breakpoint.png"); // 12x12 public static final Icon Db_muted_invalid_field_breakpoint = IconLoader.getIcon("/debugger/db_muted_invalid_field_breakpoint.png"); // 12x12 public static final Icon Db_muted_invalid_method_breakpoint = IconLoader.getIcon("/debugger/db_muted_invalid_method_breakpoint.png"); // 12x12 public static final Icon Db_muted_method_breakpoint = IconLoader.getIcon("/debugger/db_muted_method_breakpoint.png"); // 12x12 public static final Icon Db_muted_method_warning_breakpoint = IconLoader.getIcon("/debugger/db_muted_method_warning_breakpoint.png"); // 16x16 public static final Icon Db_muted_temporary_breakpoint = IconLoader.getIcon("/debugger/db_muted_temporary_breakpoint.png"); // 12x12 public static final Icon Db_muted_verified_breakpoint = IconLoader.getIcon("/debugger/db_muted_verified_breakpoint.png"); // 12x12 public static final Icon Db_muted_verified_field_breakpoint = IconLoader.getIcon("/debugger/db_muted_verified_field_breakpoint.png"); // 12x12 public static final Icon Db_muted_verified_method_breakpoint = IconLoader.getIcon("/debugger/db_muted_verified_method_breakpoint.png"); // 12x12 public static final Icon Db_muted_verified_warning_breakpoint = IconLoader.getIcon("/debugger/db_muted_verified_warning_breakpoint.png"); // 16x16 public static final Icon Db_obsolete = IconLoader.getIcon("/debugger/db_obsolete.png"); // 12x12 public static final Icon Db_primitive = IconLoader.getIcon("/debugger/db_primitive.png"); // 16x16 public static final Icon Db_set_breakpoint = IconLoader.getIcon("/debugger/db_set_breakpoint.png"); // 12x12 public static final Icon Db_temporary_breakpoint = IconLoader.getIcon("/debugger/db_temporary_breakpoint.png"); // 12x12 public static final Icon Db_verified_breakpoint = IconLoader.getIcon("/debugger/db_verified_breakpoint.png"); // 12x12 public static final Icon Db_verified_field_breakpoint = IconLoader.getIcon("/debugger/db_verified_field_breakpoint.png"); // 12x12 public static final Icon Db_verified_method_breakpoint = IconLoader.getIcon("/debugger/db_verified_method_breakpoint.png"); // 12x12 public static final Icon Db_verified_warning_breakpoint = IconLoader.getIcon("/debugger/db_verified_warning_breakpoint.png"); // 16x16 public static final Icon Disable_value_calculation = IconLoader.getIcon("/debugger/disable_value_calculation.png"); // 16x16 public static final Icon EvaluateExpression = IconLoader.getIcon("/debugger/evaluateExpression.png"); // 16x16 public static final Icon Explosion = IconLoader.getIcon("/debugger/explosion.png"); // 256x256 public static final Icon Frame = IconLoader.getIcon("/debugger/frame.png"); // 16x16 public static final Icon KillProcess = IconLoader.getIcon("/debugger/killProcess.png"); // 16x16 public static final Icon LambdaBreakpoint = IconLoader.getIcon("/debugger/LambdaBreakpoint.png"); // 12x12 public static class MemoryView { public static final Icon Active = IconLoader.getIcon("/debugger/memoryView/active.png"); // 13x13 public static final Icon ClassTracked = IconLoader.getIcon("/debugger/memoryView/classTracked.png"); // 16x16 } public static final Icon MultipleBreakpoints = IconLoader.getIcon("/debugger/MultipleBreakpoints.png"); // 12x12 public static final Icon MuteBreakpoints = IconLoader.getIcon("/debugger/muteBreakpoints.png"); // 16x16 public static final Icon NewWatch = IconLoader.getIcon("/debugger/newWatch.png"); // 16x16 public static final Icon Question_badge = IconLoader.getIcon("/debugger/question_badge.png"); // 6x9 public static final Icon RestoreLayout = IconLoader.getIcon("/debugger/restoreLayout.png"); // 16x16 public static final Icon Selfreference = IconLoader.getIcon("/debugger/selfreference.png"); // 16x16 public static final Icon ShowCurrentFrame = IconLoader.getIcon("/debugger/showCurrentFrame.png"); // 16x16 public static final Icon SmartStepInto = IconLoader.getIcon("/debugger/smartStepInto.png"); // 16x16 public static final Icon StackFrame = IconLoader.getIcon("/debugger/stackFrame.png"); // 16x16 public static final Icon ThreadAtBreakpoint = IconLoader.getIcon("/debugger/threadAtBreakpoint.png"); // 16x16 public static final Icon ThreadCurrent = IconLoader.getIcon("/debugger/threadCurrent.png"); // 16x16 public static final Icon ThreadFrozen = IconLoader.getIcon("/debugger/threadFrozen.png"); // 16x16 public static final Icon ThreadGroup = IconLoader.getIcon("/debugger/threadGroup.png"); // 16x16 public static final Icon ThreadGroupCurrent = IconLoader.getIcon("/debugger/threadGroupCurrent.png"); // 16x16 public static final Icon ThreadRunning = IconLoader.getIcon("/debugger/threadRunning.png"); // 16x16 public static final Icon Threads = IconLoader.getIcon("/debugger/threads.png"); // 16x16 public static class ThreadStates { public static final Icon Daemon_sign = IconLoader.getIcon("/debugger/threadStates/daemon_sign.png"); // 16x16 public static final Icon EdtBusy = IconLoader.getIcon("/debugger/threadStates/edtBusy.png"); // 16x16 public static final Icon Exception = IconLoader.getIcon("/debugger/threadStates/exception.png"); // 16x16 public static final Icon Idle = IconLoader.getIcon("/debugger/threadStates/idle.png"); // 16x16 public static final Icon IO = IconLoader.getIcon("/debugger/threadStates/io.png"); // 16x16 public static final Icon Locked = IconLoader.getIcon("/debugger/threadStates/locked.png"); // 16x16 public static final Icon Paused = IconLoader.getIcon("/debugger/threadStates/paused.png"); // 16x16 public static final Icon Running = IconLoader.getIcon("/debugger/threadStates/running.png"); // 16x16 public static final Icon Socket = IconLoader.getIcon("/debugger/threadStates/socket.png"); // 16x16 public static final Icon Threaddump = IconLoader.getIcon("/debugger/threadStates/threaddump.png"); // 16x16 } public static final Icon ThreadSuspended = IconLoader.getIcon("/debugger/threadSuspended.png"); // 16x16 public static final Icon ToolConsole = IconLoader.getIcon("/debugger/toolConsole.png"); // 16x16 public static final Icon Value = IconLoader.getIcon("/debugger/value.png"); // 16x16 public static final Icon ViewBreakpoints = IconLoader.getIcon("/debugger/viewBreakpoints.png"); // 16x16 public static final Icon Watch = IconLoader.getIcon("/debugger/watch.png"); // 16x16 public static final Icon Watches = IconLoader.getIcon("/debugger/watches.png"); // 16x16 public static final Icon WatchLastReturnValue = IconLoader.getIcon("/debugger/watchLastReturnValue.png"); // 16x16 } public static class Diff { public static final Icon ApplyNotConflicts = IconLoader.getIcon("/diff/applyNotConflicts.png"); // 16x16 public static final Icon ApplyNotConflictsLeft = IconLoader.getIcon("/diff/applyNotConflictsLeft.png"); // 16x16 public static final Icon ApplyNotConflictsRight = IconLoader.getIcon("/diff/applyNotConflictsRight.png"); // 16x16 public static final Icon Arrow = IconLoader.getIcon("/diff/arrow.png"); // 11x11 public static final Icon ArrowLeftDown = IconLoader.getIcon("/diff/arrowLeftDown.png"); // 11x11 public static final Icon ArrowRight = IconLoader.getIcon("/diff/arrowRight.png"); // 11x11 public static final Icon ArrowRightDown = IconLoader.getIcon("/diff/arrowRightDown.png"); // 11x11 public static final Icon BranchDiff = IconLoader.getIcon("/diff/branchDiff.png"); // 16x16 public static final Icon Compare4LeftBottom = IconLoader.getIcon("/diff/compare4LeftBottom.png"); // 16x16 public static final Icon Compare4LeftMiddle = IconLoader.getIcon("/diff/compare4LeftMiddle.png"); // 16x16 public static final Icon Compare4LeftRight = IconLoader.getIcon("/diff/compare4LeftRight.png"); // 16x16 public static final Icon Compare4MiddleBottom = IconLoader.getIcon("/diff/compare4MiddleBottom.png"); // 16x16 public static final Icon Compare4MiddleRight = IconLoader.getIcon("/diff/compare4MiddleRight.png"); // 16x16 public static final Icon Compare4RightBottom = IconLoader.getIcon("/diff/compare4RightBottom.png"); // 16x16 public static final Icon CurrentLine = IconLoader.getIcon("/diff/currentLine.png"); // 16x16 @SuppressWarnings("unused") @Deprecated public static final Icon Diff = IconLoader.getIcon("/diff/Diff.png"); // 16x16 public static final Icon LeftDiff = IconLoader.getIcon("/diff/leftDiff.png"); // 16x16 public static final Icon MagicResolve = IconLoader.getIcon("/diff/magicResolve.png"); // 12x12 public static final Icon Remove = IconLoader.getIcon("/diff/remove.png"); // 11x11 public static final Icon RightDiff = IconLoader.getIcon("/diff/rightDiff.png"); // 16x16 } public static class Duplicates { public static final Icon SendToTheLeft = IconLoader.getIcon("/duplicates/sendToTheLeft.png"); // 16x16 public static final Icon SendToTheLeftGrayed = IconLoader.getIcon("/duplicates/sendToTheLeftGrayed.png"); // 16x16 public static final Icon SendToTheRight = IconLoader.getIcon("/duplicates/sendToTheRight.png"); // 16x16 public static final Icon SendToTheRightGrayed = IconLoader.getIcon("/duplicates/sendToTheRightGrayed.png"); // 16x16 } public static class FileTypes { public static final Icon Any_type = IconLoader.getIcon("/fileTypes/any_type.png"); // 16x16 public static final Icon Archive = IconLoader.getIcon("/fileTypes/archive.png"); // 16x16 public static final Icon AS = IconLoader.getIcon("/fileTypes/as.png"); // 16x16 public static final Icon Aspectj = IconLoader.getIcon("/fileTypes/aspectj.png"); // 16x16 public static final Icon Config = IconLoader.getIcon("/fileTypes/config.png"); // 16x16 public static final Icon Css = IconLoader.getIcon("/fileTypes/css.png"); // 16x16 public static final Icon Custom = IconLoader.getIcon("/fileTypes/custom.png"); // 16x16 public static final Icon Diagram = IconLoader.getIcon("/fileTypes/diagram.png"); // 16x16 public static final Icon Dtd = IconLoader.getIcon("/fileTypes/dtd.png"); // 16x16 public static final Icon Facelets = IconLoader.getIcon("/fileTypes/facelets.png"); // 16x16 public static final Icon FacesConfig = IconLoader.getIcon("/fileTypes/facesConfig.png"); // 16x16 public static final Icon Htaccess = IconLoader.getIcon("/fileTypes/htaccess.png"); // 16x16 public static final Icon Html = IconLoader.getIcon("/fileTypes/html.png"); // 16x16 public static final Icon Idl = IconLoader.getIcon("/fileTypes/idl.png"); // 16x16 public static final Icon Java = IconLoader.getIcon("/fileTypes/java.png"); // 16x16 public static final Icon JavaClass = IconLoader.getIcon("/fileTypes/javaClass.png"); // 16x16 public static final Icon JavaOutsideSource = IconLoader.getIcon("/fileTypes/javaOutsideSource.png"); // 16x16 public static final Icon JavaScript = IconLoader.getIcon("/fileTypes/javaScript.png"); // 16x16 public static final Icon Json = IconLoader.getIcon("/fileTypes/json.png"); // 16x16 public static final Icon JsonSchema = IconLoader.getIcon("/fileTypes/jsonSchema.png"); // 16x16 public static final Icon Jsp = IconLoader.getIcon("/fileTypes/jsp.png"); // 16x16 public static final Icon Jspx = IconLoader.getIcon("/fileTypes/jspx.png"); // 16x16 public static final Icon Manifest = IconLoader.getIcon("/fileTypes/manifest.png"); // 16x16 public static final Icon Properties = IconLoader.getIcon("/fileTypes/properties.png"); // 16x16 public static final Icon Text = IconLoader.getIcon("/fileTypes/text.png"); // 16x16 public static final Icon TypeScript = IconLoader.getIcon("/fileTypes/typeScript.png"); // 16x16 public static final Icon UiForm = IconLoader.getIcon("/fileTypes/uiForm.png"); // 16x16 public static final Icon Unknown = IconLoader.getIcon("/fileTypes/unknown.png"); // 16x16 public static final Icon WsdlFile = IconLoader.getIcon("/fileTypes/wsdlFile.png"); // 16x16 public static final Icon Xhtml = IconLoader.getIcon("/fileTypes/xhtml.png"); // 16x16 public static final Icon Xml = IconLoader.getIcon("/fileTypes/xml.png"); // 16x16 public static final Icon XsdFile = IconLoader.getIcon("/fileTypes/xsdFile.png"); // 16x16 } public static class General { public static final Icon Add = IconLoader.getIcon("/general/add.png"); // 16x16 public static final Icon AddFavoritesList = IconLoader.getIcon("/general/addFavoritesList.png"); // 16x16 public static final Icon AddJdk = IconLoader.getIcon("/general/addJdk.png"); // 16x16 public static final Icon ArrowDown = IconLoader.getIcon("/general/arrowDown.png"); // 7x6 public static final Icon ArrowDown_white = IconLoader.getIcon("/general/arrowDown_white.png"); // 7x6 public static final Icon AutohideOff = IconLoader.getIcon("/general/autohideOff.png"); // 14x14 public static final Icon AutohideOffInactive = IconLoader.getIcon("/general/autohideOffInactive.png"); // 14x14 public static final Icon AutohideOffPressed = IconLoader.getIcon("/general/autohideOffPressed.png"); // 22x20 public static final Icon AutoscrollFromSource = IconLoader.getIcon("/general/autoscrollFromSource.png"); // 16x16 public static final Icon AutoscrollToSource = IconLoader.getIcon("/general/autoscrollToSource.png"); // 16x16 public static final Icon Balloon = IconLoader.getIcon("/general/balloon.png"); // 16x16 public static final Icon BalloonClose = IconLoader.getIcon("/general/balloonClose.png"); // 32x32 public static final Icon BalloonError = IconLoader.getIcon("/general/balloonError.png"); // 16x16 public static final Icon BalloonInformation = IconLoader.getIcon("/general/balloonInformation.png"); // 16x16 public static final Icon BalloonWarning = IconLoader.getIcon("/general/balloonWarning.png"); // 16x16 public static final Icon Bullet = IconLoader.getIcon("/general/bullet.png"); // 16x16 public static final Icon CollapseAll = IconLoader.getIcon("/general/collapseAll.png"); // 11x16 public static final Icon CollapseAllHover = IconLoader.getIcon("/general/collapseAllHover.png"); // 11x16 public static final Icon Combo = IconLoader.getIcon("/general/combo.png"); // 16x16 public static final Icon Combo2 = IconLoader.getIcon("/general/combo2.png"); // 16x16 public static final Icon Combo3 = IconLoader.getIcon("/general/combo3.png"); // 16x16 public static final Icon ComboArrow = IconLoader.getIcon("/general/comboArrow.png"); // 16x16 public static final Icon ComboArrowDown = IconLoader.getIcon("/general/comboArrowDown.png"); // 9x5 public static final Icon ComboArrowLeft = IconLoader.getIcon("/general/comboArrowLeft.png"); // 5x9 public static final Icon ComboArrowLeftPassive = IconLoader.getIcon("/general/comboArrowLeftPassive.png"); // 5x9 public static final Icon ComboArrowRight = IconLoader.getIcon("/general/comboArrowRight.png"); // 5x9 public static final Icon ComboArrowRightPassive = IconLoader.getIcon("/general/comboArrowRightPassive.png"); // 5x9 public static final Icon ComboBoxButtonArrow = IconLoader.getIcon("/general/comboBoxButtonArrow.png"); // 16x16 public static final Icon ComboUpPassive = IconLoader.getIcon("/general/comboUpPassive.png"); // 16x16 public static final Icon ConfigurableDefault = IconLoader.getIcon("/general/configurableDefault.png"); // 32x32 public static final Icon Configure = IconLoader.getIcon("/general/Configure.png"); // 32x32 public static final Icon CreateNewProject = IconLoader.getIcon("/general/createNewProject.png"); // 32x32 public static final Icon CreateNewProjectfromExistingFiles = IconLoader.getIcon("/general/CreateNewProjectfromExistingFiles.png"); // 32x32 public static final Icon Debug = IconLoader.getIcon("/general/debug.png"); // 16x16 public static final Icon DefaultKeymap = IconLoader.getIcon("/general/defaultKeymap.png"); // 32x32 public static final Icon Divider = IconLoader.getIcon("/general/divider.png"); // 2x19 public static final Icon DownloadPlugin = IconLoader.getIcon("/general/downloadPlugin.png"); // 16x16 public static final Icon Dropdown = IconLoader.getIcon("/general/dropdown.png"); // 16x16 public static final Icon EditColors = IconLoader.getIcon("/general/editColors.png"); // 16x16 public static final Icon EditItemInSection = IconLoader.getIcon("/general/editItemInSection.png"); // 16x16 public static final Icon Ellipsis = IconLoader.getIcon("/general/ellipsis.png"); // 9x9 public static final Icon Error = IconLoader.getIcon("/general/error.png"); // 16x16 public static final Icon ErrorDialog = IconLoader.getIcon("/general/errorDialog.png"); // 32x32 public static final Icon ErrorsInProgress = IconLoader.getIcon("/general/errorsInProgress.png"); // 12x12 public static final Icon ExclMark = IconLoader.getIcon("/general/exclMark.png"); // 16x16 public static final Icon ExpandAll = IconLoader.getIcon("/general/expandAll.png"); // 11x16 public static final Icon ExpandAllHover = IconLoader.getIcon("/general/expandAllHover.png"); // 11x16 public static final Icon ExportSettings = IconLoader.getIcon("/general/ExportSettings.png"); // 32x32 public static final Icon ExternalTools = IconLoader.getIcon("/general/externalTools.png"); // 32x32 public static final Icon ExternalToolsSmall = IconLoader.getIcon("/general/externalToolsSmall.png"); // 16x16 public static final Icon Filter = IconLoader.getIcon("/general/filter.png"); // 16x16 public static final Icon Floating = IconLoader.getIcon("/general/floating.png"); // 14x14 public static final Icon Gear = IconLoader.getIcon("/general/gear.png"); // 21x16 public static final Icon GearHover = IconLoader.getIcon("/general/gearHover.png"); // 21x16 public static final Icon GearPlain = IconLoader.getIcon("/general/gearPlain.png"); // 16x16 public static final Icon GetProjectfromVCS = IconLoader.getIcon("/general/getProjectfromVCS.png"); // 32x32 public static final Icon Help = IconLoader.getIcon("/general/help.png"); // 10x10 public static final Icon Help_small = IconLoader.getIcon("/general/help_small.png"); // 16x16 public static final Icon HideDown = IconLoader.getIcon("/general/hideDown.png"); // 16x16 public static final Icon HideDownHover = IconLoader.getIcon("/general/hideDownHover.png"); // 16x16 public static final Icon HideDownPart = IconLoader.getIcon("/general/hideDownPart.png"); // 16x16 public static final Icon HideDownPartHover = IconLoader.getIcon("/general/hideDownPartHover.png"); // 16x16 public static final Icon HideLeft = IconLoader.getIcon("/general/hideLeft.png"); // 16x16 public static final Icon HideLeftHover = IconLoader.getIcon("/general/hideLeftHover.png"); // 16x16 public static final Icon HideLeftPart = IconLoader.getIcon("/general/hideLeftPart.png"); // 16x16 public static final Icon HideLeftPartHover = IconLoader.getIcon("/general/hideLeftPartHover.png"); // 16x16 public static final Icon HideRight = IconLoader.getIcon("/general/hideRight.png"); // 16x16 public static final Icon HideRightHover = IconLoader.getIcon("/general/hideRightHover.png"); // 16x16 public static final Icon HideRightPart = IconLoader.getIcon("/general/hideRightPart.png"); // 16x16 public static final Icon HideRightPartHover = IconLoader.getIcon("/general/hideRightPartHover.png"); // 16x16 public static final Icon HideToolWindow = IconLoader.getIcon("/general/hideToolWindow.png"); // 14x14 public static final Icon HideToolWindowInactive = IconLoader.getIcon("/general/hideToolWindowInactive.png"); // 14x14 public static final Icon HideWarnings = IconLoader.getIcon("/general/hideWarnings.png"); // 16x16 public static final Icon IjLogo = IconLoader.getIcon("/general/ijLogo.png"); // 16x16 public static final Icon ImplementingMethod = IconLoader.getIcon("/general/implementingMethod.png"); // 10x14 public static final Icon ImportProject = IconLoader.getIcon("/general/importProject.png"); // 32x32 public static final Icon ImportSettings = IconLoader.getIcon("/general/ImportSettings.png"); // 32x32 public static final Icon Information = IconLoader.getIcon("/general/information.png"); // 16x16 public static final Icon InformationDialog = IconLoader.getIcon("/general/informationDialog.png"); // 32x32 public static final Icon InheritedMethod = IconLoader.getIcon("/general/inheritedMethod.png"); // 11x14 public static final Icon InspectionsError = IconLoader.getIcon("/general/inspectionsError.png"); // 14x14 public static final Icon InspectionsEye = IconLoader.getIcon("/general/inspectionsEye.png"); // 14x14 public static final Icon InspectionsOff = IconLoader.getIcon("/general/inspectionsOff.png"); // 16x16 public static final Icon InspectionsOK = IconLoader.getIcon("/general/inspectionsOK.png"); // 14x14 public static final Icon InspectionsPause = IconLoader.getIcon("/general/inspectionsPause.png"); // 14x14 public static final Icon InspectionsTrafficOff = IconLoader.getIcon("/general/inspectionsTrafficOff.png"); // 14x14 public static final Icon InspectionsTypos = IconLoader.getIcon("/general/inspectionsTypos.png"); // 14x14 public static final Icon Jdk = IconLoader.getIcon("/general/jdk.png"); // 16x16 public static final Icon KeyboardShortcut = IconLoader.getIcon("/general/keyboardShortcut.png"); // 13x13 public static final Icon Keymap = IconLoader.getIcon("/general/keymap.png"); // 32x32 public static final Icon Locate = IconLoader.getIcon("/general/locate.png"); // 14x16 public static final Icon LocateHover = IconLoader.getIcon("/general/locateHover.png"); // 14x16 public static final Icon MacCorner = IconLoader.getIcon("/general/macCorner.png"); // 16x16 public static final Icon Mdot_empty = IconLoader.getIcon("/general/mdot-empty.png"); // 8x8 public static final Icon Mdot_white = IconLoader.getIcon("/general/mdot-white.png"); // 8x8 public static final Icon Mdot = IconLoader.getIcon("/general/mdot.png"); // 8x8 public static final Icon MessageHistory = IconLoader.getIcon("/general/messageHistory.png"); // 16x16 public static final Icon Modified = IconLoader.getIcon("/general/modified.png"); // 24x16 public static final Icon MoreTabs = IconLoader.getIcon("/general/moreTabs.png"); // 16x16 public static final Icon Mouse = IconLoader.getIcon("/general/mouse.png"); // 32x32 public static final Icon MouseShortcut = IconLoader.getIcon("/general/mouseShortcut.png"); // 13x13 public static final Icon NotificationError = IconLoader.getIcon("/general/notificationError.png"); // 24x24 public static final Icon NotificationInfo = IconLoader.getIcon("/general/notificationInfo.png"); // 24x24 public static final Icon NotificationWarning = IconLoader.getIcon("/general/notificationWarning.png"); // 24x24 public static final Icon OpenProject = IconLoader.getIcon("/general/openProject.png"); // 32x32 public static final Icon OverridenMethod = IconLoader.getIcon("/general/overridenMethod.png"); // 10x14 public static final Icon OverridingMethod = IconLoader.getIcon("/general/overridingMethod.png"); // 10x14 public static final Icon PackagesTab = IconLoader.getIcon("/general/packagesTab.png"); // 16x16 public static final Icon PasswordLock = IconLoader.getIcon("/general/passwordLock.png"); // 64x64 public static final Icon PathVariables = IconLoader.getIcon("/general/pathVariables.png"); // 32x32 public static final Icon Pin_tab = IconLoader.getIcon("/general/pin_tab.png"); // 16x16 public static final Icon PluginManager = IconLoader.getIcon("/general/pluginManager.png"); // 32x32 public static final Icon Progress = IconLoader.getIcon("/general/progress.png"); // 8x10 public static final Icon ProjectConfigurable = IconLoader.getIcon("/general/projectConfigurable.png"); // 9x9 public static final Icon ProjectConfigurableBanner = IconLoader.getIcon("/general/projectConfigurableBanner.png"); // 9x9 public static final Icon ProjectConfigurableSelected = IconLoader.getIcon("/general/projectConfigurableSelected.png"); // 9x9 public static final Icon ProjectSettings = IconLoader.getIcon("/general/projectSettings.png"); // 16x16 public static final Icon ProjectStructure = IconLoader.getIcon("/general/projectStructure.png"); // 16x16 public static final Icon ProjectTab = IconLoader.getIcon("/general/projectTab.png"); // 16x16 public static final Icon QuestionDialog = IconLoader.getIcon("/general/questionDialog.png"); // 32x32 public static final Icon ReadHelp = IconLoader.getIcon("/general/readHelp.png"); // 32x32 public static final Icon Recursive = IconLoader.getIcon("/general/recursive.png"); // 16x16 public static final Icon Remove = IconLoader.getIcon("/general/remove.png"); // 16x16 public static final Icon Reset = IconLoader.getIcon("/general/reset.png"); // 16x16 public static final Icon Run = IconLoader.getIcon("/general/run.png"); // 7x10 public static final Icon RunWithCoverage = IconLoader.getIcon("/general/runWithCoverage.png"); // 16x16 public static final Icon SafeMode = IconLoader.getIcon("/general/safeMode.png"); // 13x13 public static final Icon SearchEverywhereGear = IconLoader.getIcon("/general/searchEverywhereGear.png"); // 16x16 public static final Icon SecondaryGroup = IconLoader.getIcon("/general/secondaryGroup.png"); // 16x16 public static final Icon SeparatorH = IconLoader.getIcon("/general/separatorH.png"); // 17x11 public static final Icon Settings = IconLoader.getIcon("/general/settings.png"); // 16x16 public static final Icon Show_to_implement = IconLoader.getIcon("/general/show_to_implement.png"); // 16x16 public static final Icon Show_to_override = IconLoader.getIcon("/general/show_to_override.png"); // 16x16 public static final Icon SmallConfigurableVcs = IconLoader.getIcon("/general/smallConfigurableVcs.png"); // 16x16 public static final Icon SplitCenterH = IconLoader.getIcon("/general/splitCenterH.png"); // 7x7 public static final Icon SplitCenterV = IconLoader.getIcon("/general/splitCenterV.png"); // 6x7 public static final Icon SplitDown = IconLoader.getIcon("/general/splitDown.png"); // 7x7 public static final Icon SplitGlueH = IconLoader.getIcon("/general/splitGlueH.png"); // 6x17 public static final Icon SplitGlueV = IconLoader.getIcon("/general/splitGlueV.png"); // 17x6 public static final Icon SplitLeft = IconLoader.getIcon("/general/splitLeft.png"); // 7x7 public static final Icon SplitRight = IconLoader.getIcon("/general/splitRight.png"); // 7x7 public static final Icon SplitUp = IconLoader.getIcon("/general/splitUp.png"); // 7x7 public static final Icon Tab_white_center = IconLoader.getIcon("/general/tab-white-center.png"); // 1x17 public static final Icon Tab_white_left = IconLoader.getIcon("/general/tab-white-left.png"); // 4x17 public static final Icon Tab_white_right = IconLoader.getIcon("/general/tab-white-right.png"); // 4x17 public static final Icon Tab_grey_bckgrnd = IconLoader.getIcon("/general/tab_grey_bckgrnd.png"); // 1x17 public static final Icon Tab_grey_left = IconLoader.getIcon("/general/tab_grey_left.png"); // 4x17 public static final Icon Tab_grey_left_inner = IconLoader.getIcon("/general/tab_grey_left_inner.png"); // 4x17 public static final Icon Tab_grey_right = IconLoader.getIcon("/general/tab_grey_right.png"); // 4x17 public static final Icon Tab_grey_right_inner = IconLoader.getIcon("/general/tab_grey_right_inner.png"); // 4x17 public static final Icon TbHidden = IconLoader.getIcon("/general/tbHidden.png"); // 16x16 public static final Icon TbShown = IconLoader.getIcon("/general/tbShown.png"); // 16x16 public static final Icon TemplateProjectSettings = IconLoader.getIcon("/general/TemplateProjectSettings.png"); // 32x32 public static final Icon TemplateProjectStructure = IconLoader.getIcon("/general/TemplateProjectStructure.png"); // 32x32 public static final Icon Tip = IconLoader.getIcon("/general/tip.png"); // 32x32 public static final Icon TodoDefault = IconLoader.getIcon("/general/todoDefault.png"); // 12x12 public static final Icon TodoImportant = IconLoader.getIcon("/general/todoImportant.png"); // 12x12 public static final Icon TodoQuestion = IconLoader.getIcon("/general/todoQuestion.png"); // 12x12 public static final Icon UninstallPlugin = IconLoader.getIcon("/general/uninstallPlugin.png"); // 16x16 public static final Icon Warning = IconLoader.getIcon("/general/warning.png"); // 16x16 public static final Icon WarningDecorator = IconLoader.getIcon("/general/warningDecorator.png"); // 16x16 public static final Icon WarningDialog = IconLoader.getIcon("/general/warningDialog.png"); // 32x32 public static final Icon Web = IconLoader.getIcon("/general/web.png"); // 13x13 public static final Icon WebSettings = IconLoader.getIcon("/general/webSettings.png"); // 16x16 } public static class Graph { public static final Icon ActualZoom = IconLoader.getIcon("/graph/actualZoom.png"); // 16x16 public static final Icon Export = IconLoader.getIcon("/graph/export.png"); // 16x16 public static final Icon FitContent = IconLoader.getIcon("/graph/fitContent.png"); // 16x16 public static final Icon Grid = IconLoader.getIcon("/graph/grid.png"); // 16x16 public static final Icon Layout = IconLoader.getIcon("/graph/layout.png"); // 16x16 public static final Icon NodeSelectionMode = IconLoader.getIcon("/graph/nodeSelectionMode.png"); // 16x16 public static final Icon Print = IconLoader.getIcon("/graph/print.png"); // 16x16 public static final Icon PrintPreview = IconLoader.getIcon("/graph/printPreview.png"); // 16x16 public static final Icon SnapToGrid = IconLoader.getIcon("/graph/snapToGrid.png"); // 16x16 public static final Icon ZoomIn = IconLoader.getIcon("/graph/zoomIn.png"); // 16x16 public static final Icon ZoomOut = IconLoader.getIcon("/graph/zoomOut.png"); // 16x16 } public static class Gutter { public static final Icon Colors = IconLoader.getIcon("/gutter/colors.png"); // 12x12 public static final Icon ExtAnnotation = IconLoader.getIcon("/gutter/extAnnotation.png"); // 12x12 public static final Icon ImplementedMethod = IconLoader.getIcon("/gutter/implementedMethod.png"); // 12x12 public static final Icon ImplementingFunctionalInterface = IconLoader.getIcon("/gutter/implementingFunctionalInterface.png"); // 12x12 public static final Icon ImplementingMethod = IconLoader.getIcon("/gutter/implementingMethod.png"); // 12x12 public static final Icon OverridenMethod = IconLoader.getIcon("/gutter/overridenMethod.png"); // 12x12 public static final Icon OverridingMethod = IconLoader.getIcon("/gutter/overridingMethod.png"); // 12x12 public static final Icon RecursiveMethod = IconLoader.getIcon("/gutter/recursiveMethod.png"); // 12x12 public static final Icon SiblingInheritedMethod = IconLoader.getIcon("/gutter/siblingInheritedMethod.png"); // 12x12 public static final Icon Unique = IconLoader.getIcon("/gutter/unique.png"); // 8x8 } public static class Hierarchy { public static final Icon Base = IconLoader.getIcon("/hierarchy/base.png"); // 16x16 public static final Icon Callee = IconLoader.getIcon("/hierarchy/callee.png"); // 16x16 public static final Icon Caller = IconLoader.getIcon("/hierarchy/caller.png"); // 16x16 public static final Icon Class = IconLoader.getIcon("/hierarchy/class.png"); // 16x16 public static final Icon MethodDefined = IconLoader.getIcon("/hierarchy/methodDefined.png"); // 9x9 public static final Icon MethodNotDefined = IconLoader.getIcon("/hierarchy/methodNotDefined.png"); // 8x8 public static final Icon ShouldDefineMethod = IconLoader.getIcon("/hierarchy/shouldDefineMethod.png"); // 9x9 public static final Icon Subtypes = IconLoader.getIcon("/hierarchy/subtypes.png"); // 16x16 public static final Icon Supertypes = IconLoader.getIcon("/hierarchy/supertypes.png"); // 16x16 } public static final Icon Icon = IconLoader.getIcon("/icon.png"); // 32x32 public static final Icon Icon_128 = IconLoader.getIcon("/icon_128.png"); // 128x128 public static final Icon Icon_CE = IconLoader.getIcon("/icon_CE.png"); // 32x32 public static final Icon Icon_CE_128 = IconLoader.getIcon("/icon_CE_128.png"); // 128x128 public static final Icon Icon_CE_256 = IconLoader.getIcon("/icon_CE_256.png"); // 256x256 public static final Icon Icon_CE_512 = IconLoader.getIcon("/icon_CE_512.png"); // 512x512 public static final Icon Icon_CE_64 = IconLoader.getIcon("/icon_CE_64.png"); // 64x64 public static final Icon Icon_CEsmall = IconLoader.getIcon("/icon_CEsmall.png"); // 16x16 public static final Icon Icon_small = IconLoader.getIcon("/icon_small.png"); // 16x16 public static class Icons { public static class Ide { public static final Icon NextStep = IconLoader.getIcon("/icons/ide/nextStep.png"); // 12x12 public static final Icon NextStepGrayed = IconLoader.getIcon("/icons/ide/nextStepGrayed.png"); // 12x12 public static final Icon NextStepInverted = IconLoader.getIcon("/icons/ide/nextStepInverted.png"); // 12x12 public static final Icon SpeedSearchPrompt = IconLoader.getIcon("/icons/ide/speedSearchPrompt.png"); // 16x16 } } public static class Ide { public static class Dnd { public static final Icon Bottom = IconLoader.getIcon("/ide/dnd/bottom.png"); // 16x16 public static final Icon Left = IconLoader.getIcon("/ide/dnd/left.png"); // 16x16 public static final Icon Right = IconLoader.getIcon("/ide/dnd/right.png"); // 16x16 public static final Icon Top = IconLoader.getIcon("/ide/dnd/top.png"); // 16x16 } public static final Icon EmptyFatalError = IconLoader.getIcon("/ide/emptyFatalError.png"); // 16x16 public static final Icon Error = IconLoader.getIcon("/ide/error.png"); // 16x16 public static final Icon Error_notifications = IconLoader.getIcon("/ide/error_notifications.png"); // 16x16 public static final Icon ErrorPoint = IconLoader.getIcon("/ide/errorPoint.png"); // 6x6 public static final Icon FatalError_read = IconLoader.getIcon("/ide/fatalError-read.png"); // 16x16 public static final Icon FatalError = IconLoader.getIcon("/ide/fatalError.png"); // 16x16 public static final Icon HectorNo = IconLoader.getIcon("/ide/hectorNo.png"); // 16x16 public static final Icon HectorOff = IconLoader.getIcon("/ide/hectorOff.png"); // 16x16 public static final Icon HectorOn = IconLoader.getIcon("/ide/hectorOn.png"); // 16x16 public static final Icon HectorSyntax = IconLoader.getIcon("/ide/hectorSyntax.png"); // 16x16 public static final Icon IncomingChangesOff = IconLoader.getIcon("/ide/incomingChangesOff.png"); // 16x16 public static final Icon IncomingChangesOn = IconLoader.getIcon("/ide/incomingChangesOn.png"); // 16x16 public static final Icon Info_notifications = IconLoader.getIcon("/ide/info_notifications.png"); // 16x16 public static final Icon Link = IconLoader.getIcon("/ide/link.png"); // 12x12 public static final Icon LocalScope = IconLoader.getIcon("/ide/localScope.png"); // 16x16 public static final Icon LookupAlphanumeric = IconLoader.getIcon("/ide/lookupAlphanumeric.png"); // 12x12 public static final Icon LookupRelevance = IconLoader.getIcon("/ide/lookupRelevance.png"); // 12x12 public static class Macro { public static final Icon Recording_1 = IconLoader.getIcon("/ide/macro/recording_1.png"); // 16x16 public static final Icon Recording_2 = IconLoader.getIcon("/ide/macro/recording_2.png"); // 16x16 public static final Icon Recording_3 = IconLoader.getIcon("/ide/macro/recording_3.png"); // 16x16 public static final Icon Recording_4 = IconLoader.getIcon("/ide/macro/recording_4.png"); // 16x16 public static final Icon Recording_stop = IconLoader.getIcon("/ide/macro/recording_stop.png"); // 16x16 } public static final Icon NoNotifications13 = IconLoader.getIcon("/ide/noNotifications13.png"); // 13x13 public static class Notification { public static final Icon Close = IconLoader.getIcon("/ide/notification/close.png"); // 16x16 public static final Icon CloseHover = IconLoader.getIcon("/ide/notification/closeHover.png"); // 16x16 public static final Icon Collapse = IconLoader.getIcon("/ide/notification/collapse.png"); // 16x16 public static final Icon CollapseHover = IconLoader.getIcon("/ide/notification/collapseHover.png"); // 16x16 public static final Icon DropTriangle = IconLoader.getIcon("/ide/notification/dropTriangle.png"); // 11x8 public static final Icon ErrorEvents = IconLoader.getIcon("/ide/notification/errorEvents.png"); // 16x16 public static final Icon Expand = IconLoader.getIcon("/ide/notification/expand.png"); // 16x16 public static final Icon ExpandHover = IconLoader.getIcon("/ide/notification/expandHover.png"); // 16x16 public static final Icon Gear = IconLoader.getIcon("/ide/notification/gear.png"); // 16x16 public static final Icon GearHover = IconLoader.getIcon("/ide/notification/gearHover.png"); // 16x16 public static final Icon InfoEvents = IconLoader.getIcon("/ide/notification/infoEvents.png"); // 16x16 public static final Icon NoEvents = IconLoader.getIcon("/ide/notification/noEvents.png"); // 16x16 public static class Shadow { public static final Icon Bottom_left = IconLoader.getIcon("/ide/notification/shadow/bottom-left.png"); // 14x16 public static final Icon Bottom_right = IconLoader.getIcon("/ide/notification/shadow/bottom-right.png"); // 14x16 public static final Icon Bottom = IconLoader.getIcon("/ide/notification/shadow/bottom.png"); // 4x8 public static final Icon Left = IconLoader.getIcon("/ide/notification/shadow/left.png"); // 6x4 public static final Icon Right = IconLoader.getIcon("/ide/notification/shadow/right.png"); // 6x4 public static final Icon Top_left = IconLoader.getIcon("/ide/notification/shadow/top-left.png"); // 14x12 public static final Icon Top_right = IconLoader.getIcon("/ide/notification/shadow/top-right.png"); // 14x12 public static final Icon Top = IconLoader.getIcon("/ide/notification/shadow/top.png"); // 4x4 } public static final Icon WarningEvents = IconLoader.getIcon("/ide/notification/warningEvents.png"); // 16x16 } public static final Icon Notifications = IconLoader.getIcon("/ide/notifications.png"); // 16x16 public static final Icon OutgoingChangesOn = IconLoader.getIcon("/ide/outgoingChangesOn.png"); // 16x16 public static final Icon Pipette = IconLoader.getIcon("/ide/pipette.png"); // 16x16 public static final Icon Pipette_rollover = IconLoader.getIcon("/ide/pipette_rollover.png"); // 16x16 public static final Icon Rating = IconLoader.getIcon("/ide/rating.png"); // 11x11 public static final Icon Rating1 = IconLoader.getIcon("/ide/rating1.png"); // 11x11 public static final Icon Rating2 = IconLoader.getIcon("/ide/rating2.png"); // 11x11 public static final Icon Rating3 = IconLoader.getIcon("/ide/rating3.png"); // 11x11 public static final Icon Rating4 = IconLoader.getIcon("/ide/rating4.png"); // 11x11 public static final Icon Readonly = IconLoader.getIcon("/ide/readonly.png"); // 16x16 public static final Icon Readwrite = IconLoader.getIcon("/ide/readwrite.png"); // 16x16 public static class Shadow { public static final Icon Bottom_left = IconLoader.getIcon("/ide/shadow/bottom-left.png"); // 70x70 public static final Icon Bottom_right = IconLoader.getIcon("/ide/shadow/bottom-right.png"); // 70x70 public static final Icon Bottom = IconLoader.getIcon("/ide/shadow/bottom.png"); // 1x49 public static final Icon Left = IconLoader.getIcon("/ide/shadow/left.png"); // 35x1 public static class Popup { public static final Icon Bottom_left = IconLoader.getIcon("/ide/shadow/popup/bottom-left.png"); // 20x20 public static final Icon Bottom_right = IconLoader.getIcon("/ide/shadow/popup/bottom-right.png"); // 20x20 public static final Icon Bottom = IconLoader.getIcon("/ide/shadow/popup/bottom.png"); // 1x10 public static final Icon Left = IconLoader.getIcon("/ide/shadow/popup/left.png"); // 7x1 public static final Icon Right = IconLoader.getIcon("/ide/shadow/popup/right.png"); // 7x1 public static final Icon Top_left = IconLoader.getIcon("/ide/shadow/popup/top-left.png"); // 14x14 public static final Icon Top_right = IconLoader.getIcon("/ide/shadow/popup/top-right.png"); // 14x14 public static final Icon Top = IconLoader.getIcon("/ide/shadow/popup/top.png"); // 1x4 } public static final Icon Right = IconLoader.getIcon("/ide/shadow/right.png"); // 35x1 public static final Icon Top_left = IconLoader.getIcon("/ide/shadow/top-left.png"); // 70x70 public static final Icon Top_right = IconLoader.getIcon("/ide/shadow/top-right.png"); // 70x70 public static final Icon Top = IconLoader.getIcon("/ide/shadow/top.png"); // 1x20 } public static final Icon Statusbar_arrows = IconLoader.getIcon("/ide/statusbar_arrows.png"); // 7x10 public static final Icon UpDown = IconLoader.getIcon("/ide/upDown.png"); // 16x16 public static final Icon Warning_notifications = IconLoader.getIcon("/ide/warning_notifications.png"); // 16x16 } public static final Icon Idea_logo_background = IconLoader.getIcon("/idea_logo_background.png"); // 500x500 public static final Icon Idea_logo_welcome = IconLoader.getIcon("/idea_logo_welcome.png"); // 100x100 public static class Javaee { public static final Icon Application_xml = IconLoader.getIcon("/javaee/application_xml.png"); // 16x16 public static final Icon BuildOnFrameDeactivation = IconLoader.getIcon("/javaee/buildOnFrameDeactivation.png"); // 16x16 public static final Icon DataSourceImport = IconLoader.getIcon("/javaee/dataSourceImport.png"); // 16x16 public static final Icon DbSchemaImportBig = IconLoader.getIcon("/javaee/dbSchemaImportBig.png"); // 32x32 public static final Icon Ejb_jar_xml = IconLoader.getIcon("/javaee/ejb-jar_xml.png"); // 16x16 public static final Icon EjbClass = IconLoader.getIcon("/javaee/ejbClass.png"); // 16x16 public static final Icon EjbModule = IconLoader.getIcon("/javaee/ejbModule.png"); // 16x16 public static final Icon EmbeddedAttributeOverlay = IconLoader.getIcon("/javaee/embeddedAttributeOverlay.png"); // 16x16 public static final Icon EntityBean = IconLoader.getIcon("/javaee/entityBean.png"); // 16x16 public static final Icon EntityBeanBig = IconLoader.getIcon("/javaee/entityBeanBig.png"); // 24x24 public static final Icon Home = IconLoader.getIcon("/javaee/home.png"); // 16x16 public static final Icon InheritedAttributeOverlay = IconLoader.getIcon("/javaee/inheritedAttributeOverlay.png"); // 16x16 public static final Icon InterceptorClass = IconLoader.getIcon("/javaee/interceptorClass.png"); // 16x16 public static final Icon InterceptorMethod = IconLoader.getIcon("/javaee/interceptorMethod.png"); // 16x16 public static final Icon JavaeeAppModule = IconLoader.getIcon("/javaee/JavaeeAppModule.png"); // 16x16 public static final Icon JpaFacet = IconLoader.getIcon("/javaee/jpaFacet.png"); // 16x16 public static final Icon Local = IconLoader.getIcon("/javaee/local.png"); // 16x16 public static final Icon LocalHome = IconLoader.getIcon("/javaee/localHome.png"); // 16x16 public static final Icon MessageBean = IconLoader.getIcon("/javaee/messageBean.png"); // 16x16 public static final Icon PersistenceAttribute = IconLoader.getIcon("/javaee/persistenceAttribute.png"); // 16x16 public static final Icon PersistenceEmbeddable = IconLoader.getIcon("/javaee/persistenceEmbeddable.png"); // 16x16 public static final Icon PersistenceEntity = IconLoader.getIcon("/javaee/persistenceEntity.png"); // 16x16 public static final Icon PersistenceEntityListener = IconLoader.getIcon("/javaee/persistenceEntityListener.png"); // 16x16 public static final Icon PersistenceId = IconLoader.getIcon("/javaee/persistenceId.png"); // 16x16 public static final Icon PersistenceIdRelationship = IconLoader.getIcon("/javaee/persistenceIdRelationship.png"); // 16x16 public static final Icon PersistenceMappedSuperclass = IconLoader.getIcon("/javaee/persistenceMappedSuperclass.png"); // 16x16 public static final Icon PersistenceRelationship = IconLoader.getIcon("/javaee/persistenceRelationship.png"); // 16x16 public static final Icon PersistenceUnit = IconLoader.getIcon("/javaee/persistenceUnit.png"); // 16x16 public static final Icon Remote = IconLoader.getIcon("/javaee/remote.png"); // 16x16 public static final Icon SessionBean = IconLoader.getIcon("/javaee/sessionBean.png"); // 16x16 public static final Icon UpdateRunningApplication = IconLoader.getIcon("/javaee/updateRunningApplication.png"); // 16x16 public static final Icon Web_xml = IconLoader.getIcon("/javaee/web_xml.png"); // 16x16 public static final Icon WebModule = IconLoader.getIcon("/javaee/webModule.png"); // 16x16 public static final Icon WebModuleGroup = IconLoader.getIcon("/javaee/webModuleGroup.png"); // 16x16 public static final Icon WebService = IconLoader.getIcon("/javaee/WebService.png"); // 16x16 public static final Icon WebService2 = IconLoader.getIcon("/javaee/WebService2.png"); // 16x16 public static final Icon WebServiceClient = IconLoader.getIcon("/javaee/WebServiceClient.png"); // 16x16 public static final Icon WebServiceClient2 = IconLoader.getIcon("/javaee/WebServiceClient2.png"); // 16x16 } public static class Json { public static final Icon Array = IconLoader.getIcon("/json/array.png"); // 16x16 public static final Icon Object = IconLoader.getIcon("/json/object.png"); // 16x16 public static final Icon Property_braces = IconLoader.getIcon("/json/property_braces.png"); // 16x16 public static final Icon Property_brackets = IconLoader.getIcon("/json/property_brackets.png"); // 16x16 } public static final Icon Logo_welcomeScreen = IconLoader.getIcon("/Logo_welcomeScreen.png"); // 80x80 public static class Mac { public static final Icon AppIconOk512 = IconLoader.getIcon("/mac/appIconOk512.png"); // 55x55 public static final Icon Text = IconLoader.getIcon("/mac/text.gif"); // 32x32 public static final Icon Tree_white_down_arrow = IconLoader.getIcon("/mac/tree_white_down_arrow.png"); // 11x11 public static final Icon Tree_white_right_arrow = IconLoader.getIcon("/mac/tree_white_right_arrow.png"); // 11x11 public static final Icon YosemiteOptionButtonSelector = IconLoader.getIcon("/mac/yosemiteOptionButtonSelector.png"); // 8x12 } public static class Modules { public static final Icon AddContentEntry = IconLoader.getIcon("/modules/addContentEntry.png"); // 16x16 public static final Icon AddExcludedRoot = IconLoader.getIcon("/modules/addExcludedRoot.png"); // 16x16 public static final Icon Annotation = IconLoader.getIcon("/modules/annotation.png"); // 16x16 public static final Icon DeleteContentFolder = IconLoader.getIcon("/modules/deleteContentFolder.png"); // 9x9 public static final Icon DeleteContentFolderRollover = IconLoader.getIcon("/modules/deleteContentFolderRollover.png"); // 9x9 public static final Icon DeleteContentRoot = IconLoader.getIcon("/modules/deleteContentRoot.png"); // 9x9 public static final Icon DeleteContentRootRollover = IconLoader.getIcon("/modules/deleteContentRootRollover.png"); // 9x9 public static final Icon Edit = IconLoader.getIcon("/modules/edit.png"); // 16x16 public static final Icon EditFolder = IconLoader.getIcon("/modules/editFolder.png"); // 16x16 public static final Icon ExcludedGeneratedRoot = IconLoader.getIcon("/modules/excludedGeneratedRoot.png"); // 16x16 public static final Icon ExcludeRoot = IconLoader.getIcon("/modules/excludeRoot.png"); // 16x16 public static final Icon GeneratedFolder = IconLoader.getIcon("/modules/generatedFolder.png"); // 16x16 public static final Icon GeneratedSourceRoot = IconLoader.getIcon("/modules/generatedSourceRoot.png"); // 16x16 public static final Icon GeneratedTestRoot = IconLoader.getIcon("/modules/generatedTestRoot.png"); // 16x16 public static final Icon Library = IconLoader.getIcon("/modules/library.png"); // 16x16 public static final Icon Merge = IconLoader.getIcon("/modules/merge.png"); // 16x16 public static final Icon ModulesNode = IconLoader.getIcon("/modules/modulesNode.png"); // 16x16 public static final Icon Output = IconLoader.getIcon("/modules/output.png"); // 16x16 public static final Icon ResourcesRoot = IconLoader.getIcon("/modules/resourcesRoot.png"); // 16x16 public static final Icon SetPackagePrefix = IconLoader.getIcon("/modules/setPackagePrefix.png"); // 9x9 public static final Icon SetPackagePrefixRollover = IconLoader.getIcon("/modules/setPackagePrefixRollover.png"); // 9x9 public static final Icon SourceFolder = IconLoader.getIcon("/modules/sourceFolder.png"); // 16x16 public static final Icon SourceRoot = IconLoader.getIcon("/modules/sourceRoot.png"); // 16x16 public static final Icon Sources = IconLoader.getIcon("/modules/sources.png"); // 16x16 public static final Icon Split = IconLoader.getIcon("/modules/split.png"); // 16x16 public static final Icon TestResourcesRoot = IconLoader.getIcon("/modules/testResourcesRoot.png"); // 16x16 public static final Icon TestRoot = IconLoader.getIcon("/modules/testRoot.png"); // 16x16 public static final Icon TestSourceFolder = IconLoader.getIcon("/modules/testSourceFolder.png"); // 16x16 public static class Types { public static final Icon UserDefined = IconLoader.getIcon("/modules/types/userDefined.png"); // 16x16 } public static final Icon UnmarkWebroot = IconLoader.getIcon("/modules/unmarkWebroot.png"); // 16x16 public static final Icon WebRoot = IconLoader.getIcon("/modules/webRoot.png"); // 16x16 } public static class Nodes { public static final Icon AbstractClass = IconLoader.getIcon("/nodes/abstractClass.png"); // 16x16 public static final Icon AbstractException = IconLoader.getIcon("/nodes/abstractException.png"); // 16x16 public static final Icon AbstractMethod = IconLoader.getIcon("/nodes/abstractMethod.png"); // 16x16 public static final Icon Advice = IconLoader.getIcon("/nodes/advice.png"); // 16x16 public static final Icon Annotationtype = IconLoader.getIcon("/nodes/annotationtype.png"); // 16x16 public static final Icon AnonymousClass = IconLoader.getIcon("/nodes/anonymousClass.png"); // 16x16 public static final Icon Artifact = IconLoader.getIcon("/nodes/artifact.png"); // 16x16 public static final Icon Aspect = IconLoader.getIcon("/nodes/aspect.png"); // 16x16 public static final Icon C_plocal = IconLoader.getIcon("/nodes/c_plocal.png"); // 16x16 public static final Icon C_private = IconLoader.getIcon("/nodes/c_private.png"); // 16x16 public static final Icon C_protected = IconLoader.getIcon("/nodes/c_protected.png"); // 16x16 public static final Icon C_public = IconLoader.getIcon("/nodes/c_public.png"); // 16x16 public static final Icon Class = IconLoader.getIcon("/nodes/class.png"); // 16x16 public static final Icon ClassInitializer = IconLoader.getIcon("/nodes/classInitializer.png"); // 16x16 public static final Icon CollapseNode = IconLoader.getIcon("/nodes/collapseNode.png"); // 9x9 public static final Icon CompiledClassesFolder = IconLoader.getIcon("/nodes/compiledClassesFolder.png"); // 16x16 public static final Icon CopyOfFolder = IconLoader.getIcon("/nodes/copyOfFolder.png"); // 16x16 public static final Icon CustomRegion = IconLoader.getIcon("/nodes/customRegion.png"); // 16x16 public static final Icon Cvs_global = IconLoader.getIcon("/nodes/cvs_global.png"); // 16x16 public static final Icon Cvs_roots = IconLoader.getIcon("/nodes/cvs_roots.png"); // 16x16 public static final Icon DataColumn = IconLoader.getIcon("/nodes/dataColumn.png"); // 16x16 public static final Icon DataSchema = IconLoader.getIcon("/nodes/dataSchema.png"); // 16x16 public static final Icon DataSource = IconLoader.getIcon("/nodes/DataSource.png"); // 16x16 public static final Icon DataTables = IconLoader.getIcon("/nodes/DataTables.png"); // 16x16 public static final Icon DataView = IconLoader.getIcon("/nodes/dataView.png"); // 16x16 public static final Icon Deploy = IconLoader.getIcon("/nodes/deploy.png"); // 16x16 public static final Icon Desktop = IconLoader.getIcon("/nodes/desktop.png"); // 16x16 public static final Icon Ejb = IconLoader.getIcon("/nodes/ejb.png"); // 16x16 public static final Icon EjbBusinessMethod = IconLoader.getIcon("/nodes/ejbBusinessMethod.png"); // 16x16 public static final Icon EjbCmpField = IconLoader.getIcon("/nodes/ejbCmpField.png"); // 16x16 public static final Icon EjbCmrField = IconLoader.getIcon("/nodes/ejbCmrField.png"); // 16x16 public static final Icon EjbCreateMethod = IconLoader.getIcon("/nodes/ejbCreateMethod.png"); // 16x16 public static final Icon EjbFinderMethod = IconLoader.getIcon("/nodes/ejbFinderMethod.png"); // 16x16 public static final Icon EjbPrimaryKeyClass = IconLoader.getIcon("/nodes/ejbPrimaryKeyClass.png"); // 16x16 public static final Icon EjbReference = IconLoader.getIcon("/nodes/ejbReference.png"); // 16x16 public static final Icon EmptyNode = IconLoader.getIcon("/nodes/emptyNode.png"); // 18x18 public static final Icon EnterpriseProject = IconLoader.getIcon("/nodes/enterpriseProject.png"); // 16x16 public static final Icon EntryPoints = IconLoader.getIcon("/nodes/entryPoints.png"); // 16x16 public static final Icon Enum = IconLoader.getIcon("/nodes/enum.png"); // 16x16 public static final Icon ErrorIntroduction = IconLoader.getIcon("/nodes/errorIntroduction.png"); // 16x16 public static final Icon ErrorMark = IconLoader.getIcon("/nodes/errorMark.png"); // 16x16 public static final Icon ExceptionClass = IconLoader.getIcon("/nodes/exceptionClass.png"); // 16x16 public static final Icon ExcludedFromCompile = IconLoader.getIcon("/nodes/excludedFromCompile.png"); // 16x16 public static final Icon ExpandNode = IconLoader.getIcon("/nodes/expandNode.png"); // 9x9 public static final Icon ExtractedFolder = IconLoader.getIcon("/nodes/extractedFolder.png"); // 16x16 public static final Icon Field = IconLoader.getIcon("/nodes/field.png"); // 16x16 public static final Icon FieldPK = IconLoader.getIcon("/nodes/fieldPK.png"); // 16x16 public static final Icon FinalMark = IconLoader.getIcon("/nodes/finalMark.png"); // 16x16 public static final Icon Folder = IconLoader.getIcon("/nodes/folder.png"); // 16x16 public static final Icon Function = IconLoader.getIcon("/nodes/function.png"); // 16x16 public static final Icon HomeFolder = IconLoader.getIcon("/nodes/homeFolder.png"); // 16x16 public static final Icon IdeaModule = IconLoader.getIcon("/nodes/ideaModule.png"); // 16x16 public static final Icon IdeaProject = IconLoader.getIcon("/nodes/ideaProject.png"); // 16x16 public static final Icon InspectionResults = IconLoader.getIcon("/nodes/inspectionResults.png"); // 16x16 public static final Icon Interface = IconLoader.getIcon("/nodes/interface.png"); // 16x16 public static final Icon J2eeParameter = IconLoader.getIcon("/nodes/j2eeParameter.png"); // 16x16 public static final Icon JarDirectory = IconLoader.getIcon("/nodes/jarDirectory.png"); // 16x16 public static final Icon JavaDocFolder = IconLoader.getIcon("/nodes/javaDocFolder.png"); // 16x16 public static final Icon JavaModule = IconLoader.getIcon("/nodes/javaModule.png"); // 16x16 public static final Icon JavaModuleRoot = IconLoader.getIcon("/nodes/javaModuleRoot.png"); // 16x16 public static class Jsf { public static final Icon Component = IconLoader.getIcon("/nodes/jsf/component.png"); // 16x16 public static final Icon Converter = IconLoader.getIcon("/nodes/jsf/converter.png"); // 16x16 public static final Icon General = IconLoader.getIcon("/nodes/jsf/general.png"); // 16x16 public static final Icon GenericValue = IconLoader.getIcon("/nodes/jsf/genericValue.png"); // 16x16 public static final Icon ManagedBean = IconLoader.getIcon("/nodes/jsf/managedBean.png"); // 16x16 public static final Icon NavigationCase = IconLoader.getIcon("/nodes/jsf/navigationCase.png"); // 16x16 public static final Icon NavigationRule = IconLoader.getIcon("/nodes/jsf/navigationRule.png"); // 16x16 public static final Icon Renderer = IconLoader.getIcon("/nodes/jsf/renderer.png"); // 16x16 public static final Icon RenderKit = IconLoader.getIcon("/nodes/jsf/renderKit.png"); // 16x16 public static final Icon Validator = IconLoader.getIcon("/nodes/jsf/validator.png"); // 16x16 } public static final Icon Jsr45 = IconLoader.getIcon("/nodes/jsr45.png"); // 16x16 public static final Icon JunitTestMark = IconLoader.getIcon("/nodes/junitTestMark.png"); // 16x16 public static final Icon KeymapAnt = IconLoader.getIcon("/nodes/keymapAnt.png"); // 16x16 public static final Icon KeymapEditor = IconLoader.getIcon("/nodes/keymapEditor.png"); // 16x16 public static final Icon KeymapMainMenu = IconLoader.getIcon("/nodes/keymapMainMenu.png"); // 16x16 public static final Icon KeymapOther = IconLoader.getIcon("/nodes/keymapOther.png"); // 16x16 public static final Icon KeymapTools = IconLoader.getIcon("/nodes/keymapTools.png"); // 16x16 public static final Icon Locked = IconLoader.getIcon("/nodes/locked.png"); // 16x16 public static final Icon Method = IconLoader.getIcon("/nodes/method.png"); // 16x16 public static final Icon MethodReference = IconLoader.getIcon("/nodes/methodReference.png"); // 16x16 public static final Icon Module = IconLoader.getIcon("/nodes/Module.png"); // 16x16 public static final Icon ModuleGroup = IconLoader.getIcon("/nodes/moduleGroup.png"); // 16x16 public static final Icon NativeLibrariesFolder = IconLoader.getIcon("/nodes/nativeLibrariesFolder.png"); // 16x16 public static final Icon NewException = IconLoader.getIcon("/nodes/newException.png"); // 16x16 public static final Icon NewFolder = IconLoader.getIcon("/nodes/newFolder.png"); // 16x16 public static final Icon NewParameter = IconLoader.getIcon("/nodes/newParameter.png"); // 16x16 public static final Icon NodePlaceholder = IconLoader.getIcon("/nodes/nodePlaceholder.png"); // 16x16 public static final Icon Package = IconLoader.getIcon("/nodes/package.png"); // 16x16 public static final Icon Padlock = IconLoader.getIcon("/nodes/padlock.png"); // 16x16 public static final Icon Parameter = IconLoader.getIcon("/nodes/parameter.png"); // 16x16 public static final Icon PinToolWindow = IconLoader.getIcon("/nodes/pinToolWindow.png"); // 13x13 public static final Icon Plugin = IconLoader.getIcon("/nodes/plugin.png"); // 16x16 public static final Icon PluginJB = IconLoader.getIcon("/nodes/pluginJB.png"); // 16x16 public static final Icon PluginLogo = IconLoader.getIcon("/nodes/pluginLogo.png"); // 32x32 public static final Icon Pluginnotinstalled = IconLoader.getIcon("/nodes/pluginnotinstalled.png"); // 16x16 public static final Icon Pluginobsolete = IconLoader.getIcon("/nodes/pluginobsolete.png"); // 16x16 public static final Icon PluginRestart = IconLoader.getIcon("/nodes/pluginRestart.png"); // 16x16 public static final Icon PluginUpdate = IconLoader.getIcon("/nodes/pluginUpdate.png"); // 16x16 public static final Icon Pointcut = IconLoader.getIcon("/nodes/pointcut.png"); // 16x16 public static final Icon PpFile = IconLoader.getIcon("/nodes/ppFile.png"); // 16x16 public static final Icon PpInvalid = IconLoader.getIcon("/nodes/ppInvalid.png"); // 16x16 public static final Icon PpJar = IconLoader.getIcon("/nodes/ppJar.png"); // 16x16 public static final Icon PpJdk = IconLoader.getIcon("/nodes/ppJdk.png"); // 16x16 public static final Icon PpLib = IconLoader.getIcon("/nodes/ppLib.png"); // 16x16 public static final Icon PpLibFolder = IconLoader.getIcon("/nodes/ppLibFolder.png"); // 16x16 public static final Icon PpWeb = IconLoader.getIcon("/nodes/ppWeb.png"); // 16x16 public static final Icon PpWebLogo = IconLoader.getIcon("/nodes/ppWebLogo.png"); // 32x32 public static final Icon Project = IconLoader.getIcon("/nodes/project.png"); // 16x16 public static final Icon Property = IconLoader.getIcon("/nodes/property.png"); // 16x16 public static final Icon PropertyRead = IconLoader.getIcon("/nodes/propertyRead.png"); // 16x16 public static final Icon PropertyReadStatic = IconLoader.getIcon("/nodes/propertyReadStatic.png"); // 16x16 public static final Icon PropertyReadWrite = IconLoader.getIcon("/nodes/propertyReadWrite.png"); // 16x16 public static final Icon PropertyReadWriteStatic = IconLoader.getIcon("/nodes/propertyReadWriteStatic.png"); // 16x16 public static final Icon PropertyWrite = IconLoader.getIcon("/nodes/propertyWrite.png"); // 16x16 public static final Icon PropertyWriteStatic = IconLoader.getIcon("/nodes/propertyWriteStatic.png"); // 16x16 public static final Icon Read_access = IconLoader.getIcon("/nodes/read-access.png"); // 13x9 public static final Icon ResourceBundle = IconLoader.getIcon("/nodes/resourceBundle.png"); // 16x16 public static final Icon RunnableMark = IconLoader.getIcon("/nodes/runnableMark.png"); // 16x16 public static final Icon Rw_access = IconLoader.getIcon("/nodes/rw-access.png"); // 13x9 public static final Icon SecurityRole = IconLoader.getIcon("/nodes/SecurityRole.png"); // 16x16 public static final Icon Servlet = IconLoader.getIcon("/nodes/servlet.png"); // 16x16 public static final Icon Shared = IconLoader.getIcon("/nodes/shared.png"); // 16x16 public static final Icon SortBySeverity = IconLoader.getIcon("/nodes/sortBySeverity.png"); // 16x16 public static final Icon SourceFolder = IconLoader.getIcon("/nodes/sourceFolder.png"); // 16x16 public static final Icon Static = IconLoader.getIcon("/nodes/static.png"); // 16x16 public static final Icon StaticMark = IconLoader.getIcon("/nodes/staticMark.png"); // 16x16 public static final Icon Symlink = IconLoader.getIcon("/nodes/symlink.png"); // 16x16 public static final Icon TabAlert = IconLoader.getIcon("/nodes/tabAlert.png"); // 16x16 public static final Icon TabPin = IconLoader.getIcon("/nodes/tabPin.png"); // 16x16 public static final Icon Tag = IconLoader.getIcon("/nodes/tag.png"); // 16x16 public static final Icon TestSourceFolder = IconLoader.getIcon("/nodes/testSourceFolder.png"); // 16x16 public static final Icon TreeClosed = IconLoader.getIcon("/nodes/TreeClosed.png"); // 16x16 public static final Icon TreeCollapseNode = IconLoader.getIcon("/nodes/treeCollapseNode.png"); // 16x16 public static final Icon TreeDownArrow = IconLoader.getIcon("/nodes/treeDownArrow.png"); // 11x11 public static final Icon TreeExpandNode = IconLoader.getIcon("/nodes/treeExpandNode.png"); // 16x16 public static final Icon TreeOpen = IconLoader.getIcon("/nodes/TreeOpen.png"); // 16x16 public static final Icon TreeRightArrow = IconLoader.getIcon("/nodes/treeRightArrow.png"); // 11x11 public static final Icon Undeploy = IconLoader.getIcon("/nodes/undeploy.png"); // 16x16 public static final Icon UnknownJdk = IconLoader.getIcon("/nodes/unknownJdk.png"); // 16x16 public static final Icon UpFolder = IconLoader.getIcon("/nodes/upFolder.png"); // 16x16 public static final Icon UpLevel = IconLoader.getIcon("/nodes/upLevel.png"); // 16x16 public static final Icon Variable = IconLoader.getIcon("/nodes/variable.png"); // 16x16 public static final Icon WarningIntroduction = IconLoader.getIcon("/nodes/warningIntroduction.png"); // 16x16 public static final Icon WebFolder = IconLoader.getIcon("/nodes/webFolder.png"); // 16x16 public static final Icon Weblistener = IconLoader.getIcon("/nodes/weblistener.png"); // 16x16 public static final Icon Write_access = IconLoader.getIcon("/nodes/write-access.png"); // 13x9 } public static class ObjectBrowser { public static final Icon AbbreviatePackageNames = IconLoader.getIcon("/objectBrowser/abbreviatePackageNames.png"); // 16x16 public static final Icon CompactEmptyPackages = IconLoader.getIcon("/objectBrowser/compactEmptyPackages.png"); // 16x16 public static final Icon FlattenModules = IconLoader.getIcon("/objectBrowser/flattenModules.png"); // 16x16 public static final Icon FlattenPackages = IconLoader.getIcon("/objectBrowser/flattenPackages.png"); // 16x16 public static final Icon ShowEditorHighlighting = IconLoader.getIcon("/objectBrowser/showEditorHighlighting.png"); // 16x16 public static final Icon ShowLibraryContents = IconLoader.getIcon("/objectBrowser/showLibraryContents.png"); // 16x16 public static final Icon ShowMembers = IconLoader.getIcon("/objectBrowser/showMembers.png"); // 16x16 public static final Icon ShowModules = IconLoader.getIcon("/objectBrowser/showModules.png"); // 16x16 public static final Icon SortByType = IconLoader.getIcon("/objectBrowser/sortByType.png"); // 16x16 public static final Icon Sorted = IconLoader.getIcon("/objectBrowser/sorted.png"); // 16x16 public static final Icon SortedByUsage = IconLoader.getIcon("/objectBrowser/sortedByUsage.png"); // 16x16 public static final Icon VisibilitySort = IconLoader.getIcon("/objectBrowser/visibilitySort.png"); // 16x16 } public static class Preferences { public static final Icon Appearance = IconLoader.getIcon("/preferences/Appearance.png"); // 32x32 public static final Icon CodeStyle = IconLoader.getIcon("/preferences/CodeStyle.png"); // 32x32 public static final Icon Compiler = IconLoader.getIcon("/preferences/Compiler.png"); // 32x32 public static final Icon Editor = IconLoader.getIcon("/preferences/Editor.png"); // 32x32 public static final Icon FileColors = IconLoader.getIcon("/preferences/FileColors.png"); // 32x32 public static final Icon FileTypes = IconLoader.getIcon("/preferences/FileTypes.png"); // 32x32 public static final Icon General = IconLoader.getIcon("/preferences/General.png"); // 32x32 public static final Icon Keymap = IconLoader.getIcon("/preferences/Keymap.png"); // 32x32 public static final Icon Plugins = IconLoader.getIcon("/preferences/Plugins.png"); // 32x32 public static final Icon Updates = IconLoader.getIcon("/preferences/Updates.png"); // 32x32 public static final Icon VersionControl = IconLoader.getIcon("/preferences/VersionControl.png"); // 32x32 } public static class Process { public static class Big { public static final Icon Step_1 = IconLoader.getIcon("/process/big/step_1.png"); // 32x32 public static final Icon Step_10 = IconLoader.getIcon("/process/big/step_10.png"); // 32x32 public static final Icon Step_11 = IconLoader.getIcon("/process/big/step_11.png"); // 32x32 public static final Icon Step_12 = IconLoader.getIcon("/process/big/step_12.png"); // 32x32 public static final Icon Step_2 = IconLoader.getIcon("/process/big/step_2.png"); // 32x32 public static final Icon Step_3 = IconLoader.getIcon("/process/big/step_3.png"); // 32x32 public static final Icon Step_4 = IconLoader.getIcon("/process/big/step_4.png"); // 32x32 public static final Icon Step_5 = IconLoader.getIcon("/process/big/step_5.png"); // 32x32 public static final Icon Step_6 = IconLoader.getIcon("/process/big/step_6.png"); // 32x32 public static final Icon Step_7 = IconLoader.getIcon("/process/big/step_7.png"); // 32x32 public static final Icon Step_8 = IconLoader.getIcon("/process/big/step_8.png"); // 32x32 public static final Icon Step_9 = IconLoader.getIcon("/process/big/step_9.png"); // 32x32 public static final Icon Step_passive = IconLoader.getIcon("/process/big/step_passive.png"); // 32x32 } public static final Icon DisabledDebug = IconLoader.getIcon("/process/disabledDebug.png"); // 13x13 public static final Icon DisabledRun = IconLoader.getIcon("/process/disabledRun.png"); // 13x13 public static class FS { public static final Icon Step_1 = IconLoader.getIcon("/process/fs/step_1.png"); // 16x16 public static final Icon Step_10 = IconLoader.getIcon("/process/fs/step_10.png"); // 16x16 public static final Icon Step_11 = IconLoader.getIcon("/process/fs/step_11.png"); // 16x16 public static final Icon Step_12 = IconLoader.getIcon("/process/fs/step_12.png"); // 16x16 public static final Icon Step_13 = IconLoader.getIcon("/process/fs/step_13.png"); // 16x16 public static final Icon Step_14 = IconLoader.getIcon("/process/fs/step_14.png"); // 16x16 public static final Icon Step_15 = IconLoader.getIcon("/process/fs/step_15.png"); // 16x16 public static final Icon Step_16 = IconLoader.getIcon("/process/fs/step_16.png"); // 16x16 public static final Icon Step_17 = IconLoader.getIcon("/process/fs/step_17.png"); // 16x16 public static final Icon Step_18 = IconLoader.getIcon("/process/fs/step_18.png"); // 16x16 public static final Icon Step_2 = IconLoader.getIcon("/process/fs/step_2.png"); // 16x16 public static final Icon Step_3 = IconLoader.getIcon("/process/fs/step_3.png"); // 16x16 public static final Icon Step_4 = IconLoader.getIcon("/process/fs/step_4.png"); // 16x16 public static final Icon Step_5 = IconLoader.getIcon("/process/fs/step_5.png"); // 16x16 public static final Icon Step_6 = IconLoader.getIcon("/process/fs/step_6.png"); // 16x16 public static final Icon Step_7 = IconLoader.getIcon("/process/fs/step_7.png"); // 16x16 public static final Icon Step_8 = IconLoader.getIcon("/process/fs/step_8.png"); // 16x16 public static final Icon Step_9 = IconLoader.getIcon("/process/fs/step_9.png"); // 16x16 public static final Icon Step_mask = IconLoader.getIcon("/process/fs/step_mask.png"); // 16x16 public static final Icon Step_passive = IconLoader.getIcon("/process/fs/step_passive.png"); // 16x16 } public static class State { public static final Icon GreenOK = IconLoader.getIcon("/process/state/GreenOK.png"); // 16x16 public static final Icon GreyProgr = IconLoader.getIcon("/process/state/GreyProgr.png"); // 16x16 public static final Icon GreyProgr_1 = IconLoader.getIcon("/process/state/GreyProgr_1.png"); // 16x16 public static final Icon GreyProgr_2 = IconLoader.getIcon("/process/state/GreyProgr_2.png"); // 16x16 public static final Icon GreyProgr_3 = IconLoader.getIcon("/process/state/GreyProgr_3.png"); // 16x16 public static final Icon GreyProgr_4 = IconLoader.getIcon("/process/state/GreyProgr_4.png"); // 16x16 public static final Icon GreyProgr_5 = IconLoader.getIcon("/process/state/GreyProgr_5.png"); // 16x16 public static final Icon GreyProgr_6 = IconLoader.getIcon("/process/state/GreyProgr_6.png"); // 16x16 public static final Icon GreyProgr_7 = IconLoader.getIcon("/process/state/GreyProgr_7.png"); // 16x16 public static final Icon GreyProgr_8 = IconLoader.getIcon("/process/state/GreyProgr_8.png"); // 16x16 public static final Icon RedExcl = IconLoader.getIcon("/process/state/RedExcl.png"); // 16x16 public static final Icon YellowStr = IconLoader.getIcon("/process/state/YellowStr.png"); // 16x16 } public static final Icon Step_1 = IconLoader.getIcon("/process/step_1.png"); // 16x16 public static final Icon Step_10 = IconLoader.getIcon("/process/step_10.png"); // 16x16 public static final Icon Step_11 = IconLoader.getIcon("/process/step_11.png"); // 16x16 public static final Icon Step_12 = IconLoader.getIcon("/process/step_12.png"); // 16x16 public static final Icon Step_2 = IconLoader.getIcon("/process/step_2.png"); // 16x16 public static final Icon Step_3 = IconLoader.getIcon("/process/step_3.png"); // 16x16 public static final Icon Step_4 = IconLoader.getIcon("/process/step_4.png"); // 16x16 public static final Icon Step_5 = IconLoader.getIcon("/process/step_5.png"); // 16x16 public static final Icon Step_6 = IconLoader.getIcon("/process/step_6.png"); // 16x16 public static final Icon Step_7 = IconLoader.getIcon("/process/step_7.png"); // 16x16 public static final Icon Step_8 = IconLoader.getIcon("/process/step_8.png"); // 16x16 public static final Icon Step_9 = IconLoader.getIcon("/process/step_9.png"); // 16x16 public static final Icon Step_mask = IconLoader.getIcon("/process/step_mask.png"); // 16x16 public static final Icon Step_passive = IconLoader.getIcon("/process/step_passive.png"); // 16x16 public static final Icon Stop = IconLoader.getIcon("/process/stop.png"); // 16x16 public static final Icon StopHovered = IconLoader.getIcon("/process/stopHovered.png"); // 16x16 } public static class Providers { public static final Icon Apache = IconLoader.getIcon("/providers/apache.png"); // 16x16 public static final Icon ApacheDerby = IconLoader.getIcon("/providers/apacheDerby.png"); // 16x16 public static final Icon Bea = IconLoader.getIcon("/providers/bea.png"); // 16x16 public static final Icon Cvs = IconLoader.getIcon("/providers/cvs.png"); // 16x16 public static final Icon DB2 = IconLoader.getIcon("/providers/DB2.png"); // 16x16 public static final Icon Eclipse = IconLoader.getIcon("/providers/eclipse.png"); // 16x16 public static final Icon H2 = IconLoader.getIcon("/providers/h2.png"); // 16x16 public static final Icon Hibernate = IconLoader.getIcon("/providers/hibernate.png"); // 16x16 public static final Icon Hsqldb = IconLoader.getIcon("/providers/hsqldb.png"); // 16x16 public static final Icon Ibm = IconLoader.getIcon("/providers/ibm.png"); // 16x16 public static final Icon Microsoft = IconLoader.getIcon("/providers/microsoft.png"); // 16x16 public static final Icon Mysql = IconLoader.getIcon("/providers/mysql.png"); // 16x16 public static final Icon Oracle = IconLoader.getIcon("/providers/oracle.png"); // 16x16 public static final Icon Postgresql = IconLoader.getIcon("/providers/postgresql.png"); // 16x16 public static final Icon Sqlite = IconLoader.getIcon("/providers/sqlite.png"); // 16x16 public static final Icon SqlServer = IconLoader.getIcon("/providers/sqlServer.png"); // 16x16 public static final Icon Sun = IconLoader.getIcon("/providers/sun.png"); // 16x16 public static final Icon Sybase = IconLoader.getIcon("/providers/sybase.png"); // 16x16 } public static class RunConfigurations { public static final Icon Applet = IconLoader.getIcon("/runConfigurations/applet.png"); // 16x16 public static final Icon Application = IconLoader.getIcon("/runConfigurations/application.png"); // 16x16 public static final Icon ConfigurationWarning = IconLoader.getIcon("/runConfigurations/configurationWarning.png"); // 16x16 public static final Icon HideIgnored = IconLoader.getIcon("/runConfigurations/hideIgnored.png"); // 16x16 public static final Icon HidePassed = IconLoader.getIcon("/runConfigurations/hidePassed.png"); // 16x16 public static final Icon IgnoredTest = IconLoader.getIcon("/runConfigurations/ignoredTest.png"); // 16x16 public static final Icon IncludeNonStartedTests_Rerun = IconLoader.getIcon("/runConfigurations/includeNonStartedTests_Rerun.png"); // 16x16 public static final Icon InvalidConfigurationLayer = IconLoader.getIcon("/runConfigurations/invalidConfigurationLayer.png"); // 16x16 public static final Icon Junit = IconLoader.getIcon("/runConfigurations/junit.png"); // 16x16 public static final Icon LoadingTree = IconLoader.getIcon("/runConfigurations/loadingTree.png"); // 16x16 public static final Icon Ql_console = IconLoader.getIcon("/runConfigurations/ql_console.png"); // 16x16 public static final Icon Remote = IconLoader.getIcon("/runConfigurations/remote.png"); // 16x16 public static final Icon RerunFailedTests = IconLoader.getIcon("/runConfigurations/rerunFailedTests.png"); // 16x16 public static final Icon SaveTempConfig = IconLoader.getIcon("/runConfigurations/saveTempConfig.png"); // 16x16 public static final Icon Scroll_down = IconLoader.getIcon("/runConfigurations/scroll_down.png"); // 16x16 public static final Icon ScrollToStackTrace = IconLoader.getIcon("/runConfigurations/scrollToStackTrace.png"); // 16x16 public static final Icon SelectFirstDefect = IconLoader.getIcon("/runConfigurations/selectFirstDefect.png"); // 16x16 public static final Icon SortbyDuration = IconLoader.getIcon("/runConfigurations/sortbyDuration.png"); // 16x16 public static final Icon SourceAtException = IconLoader.getIcon("/runConfigurations/sourceAtException.png"); // 16x16 public static final Icon TestError = IconLoader.getIcon("/runConfigurations/testError.png"); // 16x16 public static final Icon TestFailed = IconLoader.getIcon("/runConfigurations/testFailed.png"); // 16x16 public static final Icon TestIgnored = IconLoader.getIcon("/runConfigurations/testIgnored.png"); // 16x16 public static final Icon TestInProgress1 = IconLoader.getIcon("/runConfigurations/testInProgress1.png"); // 16x16 public static final Icon TestInProgress2 = IconLoader.getIcon("/runConfigurations/testInProgress2.png"); // 16x16 public static final Icon TestInProgress3 = IconLoader.getIcon("/runConfigurations/testInProgress3.png"); // 16x16 public static final Icon TestInProgress4 = IconLoader.getIcon("/runConfigurations/testInProgress4.png"); // 16x16 public static final Icon TestInProgress5 = IconLoader.getIcon("/runConfigurations/testInProgress5.png"); // 16x16 public static final Icon TestInProgress6 = IconLoader.getIcon("/runConfigurations/testInProgress6.png"); // 16x16 public static final Icon TestInProgress7 = IconLoader.getIcon("/runConfigurations/testInProgress7.png"); // 16x16 public static final Icon TestInProgress8 = IconLoader.getIcon("/runConfigurations/testInProgress8.png"); // 16x16 public static final Icon TestMark = IconLoader.getIcon("/runConfigurations/testMark.png"); // 16x16 public static final Icon TestNotRan = IconLoader.getIcon("/runConfigurations/testNotRan.png"); // 16x16 public static final Icon TestPassed = IconLoader.getIcon("/runConfigurations/testPassed.png"); // 16x16 public static final Icon TestPaused = IconLoader.getIcon("/runConfigurations/testPaused.png"); // 16x16 public static final Icon TestSkipped = IconLoader.getIcon("/runConfigurations/testSkipped.png"); // 16x16 public static class TestState { public static final Icon Green2 = IconLoader.getIcon("/runConfigurations/testState/green2.png"); // 12x12 public static final Icon Red2 = IconLoader.getIcon("/runConfigurations/testState/red2.png"); // 12x12 public static final Icon Run = IconLoader.getIcon("/runConfigurations/testState/run.png"); // 12x12 public static final Icon Run_run = IconLoader.getIcon("/runConfigurations/testState/run_run.png"); // 12x12 public static final Icon Yellow2 = IconLoader.getIcon("/runConfigurations/testState/yellow2.png"); // 12x12 } public static final Icon TestTerminated = IconLoader.getIcon("/runConfigurations/testTerminated.png"); // 16x16 public static final Icon Tomcat = IconLoader.getIcon("/runConfigurations/tomcat.png"); // 16x16 public static final Icon TrackCoverage = IconLoader.getIcon("/runConfigurations/trackCoverage.png"); // 16x16 public static final Icon TrackTests = IconLoader.getIcon("/runConfigurations/trackTests.png"); // 16x16 public static final Icon Unknown = IconLoader.getIcon("/runConfigurations/unknown.png"); // 16x16 public static final Icon Variables = IconLoader.getIcon("/runConfigurations/variables.png"); // 16x16 public static final Icon Web_app = IconLoader.getIcon("/runConfigurations/web_app.png"); // 16x16 public static final Icon WithCoverageLayer = IconLoader.getIcon("/runConfigurations/withCoverageLayer.png"); // 16x16 } public static class Toolbar { public static final Icon Filterdups = IconLoader.getIcon("/toolbar/filterdups.png"); // 16x16 public static final Icon Folders = IconLoader.getIcon("/toolbar/folders.png"); // 16x16 public static final Icon Unknown = IconLoader.getIcon("/toolbar/unknown.png"); // 16x16 } public static class ToolbarDecorator { public static final Icon Add = IconLoader.getIcon("/toolbarDecorator/add.png"); // 14x14 public static final Icon AddBlankLine = IconLoader.getIcon("/toolbarDecorator/addBlankLine.png"); // 16x16 public static final Icon AddClass = IconLoader.getIcon("/toolbarDecorator/addClass.png"); // 16x16 public static final Icon AddFolder = IconLoader.getIcon("/toolbarDecorator/addFolder.png"); // 16x16 public static final Icon AddIcon = IconLoader.getIcon("/toolbarDecorator/addIcon.png"); // 16x16 public static final Icon AddJira = IconLoader.getIcon("/toolbarDecorator/addJira.png"); // 16x16 public static final Icon AddLink = IconLoader.getIcon("/toolbarDecorator/addLink.png"); // 16x16 public static final Icon AddPackage = IconLoader.getIcon("/toolbarDecorator/addPackage.png"); // 16x16 public static final Icon AddPattern = IconLoader.getIcon("/toolbarDecorator/addPattern.png"); // 16x16 public static final Icon AddRemoteDatasource = IconLoader.getIcon("/toolbarDecorator/addRemoteDatasource.png"); // 16x16 public static final Icon AddYouTrack = IconLoader.getIcon("/toolbarDecorator/addYouTrack.png"); // 16x16 public static final Icon Analyze = IconLoader.getIcon("/toolbarDecorator/analyze.png"); // 14x14 public static final Icon Edit = IconLoader.getIcon("/toolbarDecorator/edit.png"); // 14x14 public static final Icon Export = IconLoader.getIcon("/toolbarDecorator/export.png"); // 16x16 public static final Icon Import = IconLoader.getIcon("/toolbarDecorator/import.png"); // 16x16 public static class Mac { public static final Icon Add = IconLoader.getIcon("/toolbarDecorator/mac/add.png"); // 14x14 public static final Icon AddBlankLine = IconLoader.getIcon("/toolbarDecorator/mac/addBlankLine.png"); // 16x16 public static final Icon AddClass = IconLoader.getIcon("/toolbarDecorator/mac/addClass.png"); // 16x16 public static final Icon AddFolder = IconLoader.getIcon("/toolbarDecorator/mac/addFolder.png"); // 16x16 public static final Icon AddIcon = IconLoader.getIcon("/toolbarDecorator/mac/addIcon.png"); // 16x16 public static final Icon AddJira = IconLoader.getIcon("/toolbarDecorator/mac/addJira.png"); // 16x16 public static final Icon AddLink = IconLoader.getIcon("/toolbarDecorator/mac/addLink.png"); // 16x16 public static final Icon AddPackage = IconLoader.getIcon("/toolbarDecorator/mac/addPackage.png"); // 16x16 public static final Icon AddPattern = IconLoader.getIcon("/toolbarDecorator/mac/addPattern.png"); // 16x16 public static final Icon AddRemoteDatasource = IconLoader.getIcon("/toolbarDecorator/mac/addRemoteDatasource.png"); // 16x16 public static final Icon AddYouTrack = IconLoader.getIcon("/toolbarDecorator/mac/addYouTrack.png"); // 16x16 public static final Icon Analyze = IconLoader.getIcon("/toolbarDecorator/mac/analyze.png"); // 14x14 public static final Icon Edit = IconLoader.getIcon("/toolbarDecorator/mac/edit.png"); // 14x14 public static final Icon MoveDown = IconLoader.getIcon("/toolbarDecorator/mac/moveDown.png"); // 14x14 public static final Icon MoveUp = IconLoader.getIcon("/toolbarDecorator/mac/moveUp.png"); // 14x14 public static final Icon Remove = IconLoader.getIcon("/toolbarDecorator/mac/remove.png"); // 14x14 } public static final Icon MoveDown = IconLoader.getIcon("/toolbarDecorator/moveDown.png"); // 14x14 public static final Icon MoveUp = IconLoader.getIcon("/toolbarDecorator/moveUp.png"); // 14x14 public static final Icon Remove = IconLoader.getIcon("/toolbarDecorator/remove.png"); // 14x14 } public static class Toolwindows { public static final Icon Documentation = IconLoader.getIcon("/toolwindows/documentation.png"); // 13x13 public static final Icon Problems = IconLoader.getIcon("/toolwindows/problems.png"); // 13x13 public static final Icon ToolWindowAnt = IconLoader.getIcon("/toolwindows/toolWindowAnt.png"); // 13x13 public static final Icon ToolWindowChanges = IconLoader.getIcon("/toolwindows/toolWindowChanges.png"); // 13x13 public static final Icon ToolWindowCommander = IconLoader.getIcon("/toolwindows/toolWindowCommander.png"); // 13x13 public static final Icon ToolWindowCoverage = IconLoader.getIcon("/toolwindows/toolWindowCoverage.png"); // 13x13 public static final Icon ToolWindowCvs = IconLoader.getIcon("/toolwindows/toolWindowCvs.png"); // 13x13 public static final Icon ToolWindowDebugger = IconLoader.getIcon("/toolwindows/toolWindowDebugger.png"); // 13x13 public static final Icon ToolWindowFavorites = IconLoader.getIcon("/toolwindows/toolWindowFavorites.png"); // 13x13 public static final Icon ToolWindowFind = IconLoader.getIcon("/toolwindows/toolWindowFind.png"); // 13x13 public static final Icon ToolWindowHierarchy = IconLoader.getIcon("/toolwindows/toolWindowHierarchy.png"); // 13x13 public static final Icon ToolWindowInspection = IconLoader.getIcon("/toolwindows/toolWindowInspection.png"); // 13x13 public static final Icon ToolWindowMessages = IconLoader.getIcon("/toolwindows/toolWindowMessages.png"); // 13x13 public static final Icon ToolWindowModuleDependencies = IconLoader.getIcon("/toolwindows/toolWindowModuleDependencies.png"); // 13x13 public static final Icon ToolWindowPalette = IconLoader.getIcon("/toolwindows/toolWindowPalette.png"); // 13x13 public static final Icon ToolWindowPreview = IconLoader.getIcon("/toolwindows/toolWindowPreview.png"); // 13x13 public static final Icon ToolWindowProject = IconLoader.getIcon("/toolwindows/toolWindowProject.png"); // 13x13 public static final Icon ToolWindowRun = IconLoader.getIcon("/toolwindows/toolWindowRun.png"); // 13x13 public static final Icon ToolWindowStructure = IconLoader.getIcon("/toolwindows/toolWindowStructure.png"); // 13x13 public static final Icon ToolWindowTodo = IconLoader.getIcon("/toolwindows/toolWindowTodo.png"); // 13x13 public static final Icon VcsSmallTab = IconLoader.getIcon("/toolwindows/vcsSmallTab.png"); // 13x13 public static final Icon WebToolWindow = IconLoader.getIcon("/toolwindows/webToolWindow.png"); // 13x13 } public static class Vcs { public static final Icon Arrow_left = IconLoader.getIcon("/vcs/arrow_left.png"); // 16x16 public static final Icon Arrow_right = IconLoader.getIcon("/vcs/arrow_right.png"); // 16x16 public static final Icon CheckSpelling = IconLoader.getIcon("/vcs/checkSpelling.png"); // 16x16 public static final Icon Equal = IconLoader.getIcon("/vcs/equal.png"); // 16x16 public static final Icon History = IconLoader.getIcon("/vcs/history.png"); // 16x16 public static final Icon MapBase = IconLoader.getIcon("/vcs/mapBase.png"); // 16x16 public static final Icon Merge = IconLoader.getIcon("/vcs/merge.png"); // 12x12 public static final Icon MergeSourcesTree = IconLoader.getIcon("/vcs/mergeSourcesTree.png"); // 16x16 public static final Icon Not_equal = IconLoader.getIcon("/vcs/not_equal.png"); // 16x16 public static final Icon Patch = IconLoader.getIcon("/vcs/patch.png"); // 16x16 public static final Icon Patch_applied = IconLoader.getIcon("/vcs/patch_applied.png"); // 16x16 public static final Icon Push = IconLoader.getIcon("/vcs/push.png"); // 16x16 public static final Icon Remove = IconLoader.getIcon("/vcs/remove.png"); // 16x16 public static final Icon ResetStrip = IconLoader.getIcon("/vcs/resetStrip.png"); // 16x16 public static final Icon Shelve = IconLoader.getIcon("/vcs/Shelve.png"); // 16x16 public static final Icon ShelveSilent = IconLoader.getIcon("/vcs/shelveSilent.png"); // 16x16 public static final Icon ShowUnversionedFiles = IconLoader.getIcon("/vcs/ShowUnversionedFiles.png"); // 16x16 public static final Icon StripDown = IconLoader.getIcon("/vcs/stripDown.png"); // 16x16 public static final Icon StripNull = IconLoader.getIcon("/vcs/stripNull.png"); // 16x16 public static final Icon StripUp = IconLoader.getIcon("/vcs/stripUp.png"); // 16x16 public static final Icon Unshelve = IconLoader.getIcon("/vcs/Unshelve.png"); // 16x16 public static final Icon UnshelveSilent = IconLoader.getIcon("/vcs/unshelveSilent.png"); // 16x16 } public static class Webreferences { public static final Icon Server = IconLoader.getIcon("/webreferences/server.png"); // 16x16 } public static class Welcome { public static final Icon CreateDesktopEntry = IconLoader.getIcon("/welcome/createDesktopEntry.png"); // 32x32 public static final Icon CreateNewProject = IconLoader.getIcon("/welcome/createNewProject.png"); // 16x16 public static final Icon CreateNewProjectfromExistingFiles = IconLoader.getIcon("/welcome/CreateNewProjectfromExistingFiles.png"); // 16x16 public static final Icon FromVCS = IconLoader.getIcon("/welcome/fromVCS.png"); // 16x16 public static final Icon ImportProject = IconLoader.getIcon("/welcome/importProject.png"); // 16x16 public static final Icon OpenProject = IconLoader.getIcon("/welcome/openProject.png"); // 16x16 public static class Project { public static final Icon Remove_hover = IconLoader.getIcon("/welcome/project/remove-hover.png"); // 10x10 public static final Icon Remove = IconLoader.getIcon("/welcome/project/remove.png"); // 10x10 } public static final Icon Register = IconLoader.getIcon("/welcome/register.png"); // 32x32 } public static class Windows { public static final Icon CloseActive = IconLoader.getIcon("/windows/closeActive.png"); // 16x16 public static final Icon CloseHover = IconLoader.getIcon("/windows/closeHover.png"); // 16x16 public static final Icon CloseInactive = IconLoader.getIcon("/windows/closeInactive.png"); // 16x16 public static final Icon HelpButton = IconLoader.getIcon("/windows/helpButton.png"); // 16x16 public static final Icon Maximize = IconLoader.getIcon("/windows/maximize.png"); // 16x16 public static final Icon MaximizeInactive = IconLoader.getIcon("/windows/maximizeInactive.png"); // 16x16 public static final Icon Minimize = IconLoader.getIcon("/windows/minimize.png"); // 16x16 public static final Icon MinimizeInactive = IconLoader.getIcon("/windows/minimizeInactive.png"); // 16x16 public static final Icon Restore = IconLoader.getIcon("/windows/restore.png"); // 16x16 public static final Icon RestoreInactive = IconLoader.getIcon("/windows/restoreInactive.png"); // 16x16 public static class Shadow { public static final Icon Bottom = IconLoader.getIcon("/windows/shadow/bottom.png"); // 1x13 public static final Icon BottomLeft = IconLoader.getIcon("/windows/shadow/bottomLeft.png"); // 24x24 public static final Icon BottomRight = IconLoader.getIcon("/windows/shadow/bottomRight.png"); // 24x24 public static final Icon Left = IconLoader.getIcon("/windows/shadow/left.png"); // 13x1 public static final Icon Right = IconLoader.getIcon("/windows/shadow/right.png"); // 13x1 public static final Icon Top = IconLoader.getIcon("/windows/shadow/top.png"); // 1x13 public static final Icon TopLeft = IconLoader.getIcon("/windows/shadow/topLeft.png"); // 24x24 public static final Icon TopRight = IconLoader.getIcon("/windows/shadow/topRight.png"); // 24x24 } public static final Icon WinHelp = IconLoader.getIcon("/windows/winHelp.png"); // 16x16 } public static class Xml { public static class Browsers { public static final Icon Canary16 = IconLoader.getIcon("/xml/browsers/canary16.png"); // 16x16 public static final Icon Chrome16 = IconLoader.getIcon("/xml/browsers/chrome16.png"); // 16x16 public static final Icon Chromium16 = IconLoader.getIcon("/xml/browsers/chromium16.png"); // 16x16 public static final Icon Edge16 = IconLoader.getIcon("/xml/browsers/edge16.png"); // 16x16 public static final Icon Explorer16 = IconLoader.getIcon("/xml/browsers/explorer16.png"); // 16x16 public static final Icon Firefox16 = IconLoader.getIcon("/xml/browsers/firefox16.png"); // 16x16 public static final Icon Nwjs16 = IconLoader.getIcon("/xml/browsers/nwjs16.png"); // 16x16 public static final Icon Opera16 = IconLoader.getIcon("/xml/browsers/opera16.png"); // 16x16 public static final Icon Safari16 = IconLoader.getIcon("/xml/browsers/safari16.png"); // 16x16 public static final Icon Yandex16 = IconLoader.getIcon("/xml/browsers/yandex16.png"); // 16x16 } public static final Icon Css_class = IconLoader.getIcon("/xml/css_class.png"); // 16x16 public static final Icon Html5 = IconLoader.getIcon("/xml/html5.png"); // 16x16 public static final Icon Html_id = IconLoader.getIcon("/xml/html_id.png"); // 16x16 } }
apache-2.0
sharmaabhishek523/baseline
service/src/main/java/com/aerofs/baseline/logging/MinimalLayout.java
1202
/* * Copyright 2015 Air Computing Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.aerofs.baseline.logging; import ch.qos.logback.classic.LoggerContext; import ch.qos.logback.classic.PatternLayout; import javax.annotation.concurrent.ThreadSafe; /** * Minimal logging layout that encodes only: * <ul> * <li>Level</li> * <li>UTC ISO 8601 date</li> * <li>Message and/or exception</li> * </ul> */ @ThreadSafe final class MinimalLayout extends PatternLayout { MinimalLayout(LoggerContext context) { super(); setOutputPatternAsHeader(false); setPattern("%-5p [%d{ISO8601,UTC}]: %m%n%rEx"); setContext(context); } }
apache-2.0
rofinily/code-fragment
base/src/test/java/me/anchore/snippet/algorithm/FinderTest.java
1059
package me.anchore.snippet.algorithm; import me.anchore.test.DataSetUtil; import org.junit.Before; import org.junit.Ignore; import org.junit.Test; import java.util.Arrays; import static org.junit.Assert.assertTrue; public class FinderTest { private int[] a; private Finder f; @Before public void before() { a = DataSetUtil.getIntArray(1000000); f = new Finder(a); } @Ignore @Test public void testFindMth2Nth() { int m = a.length / 10, n = a.length / 2; f.findMth2Nth(m, n); assertTrue(checkResult(a, m, n)); } @Ignore @Test public void testFindKth() { int k = a.length / 2; f.findMth2Nth(k, k); assertTrue(checkResult(a, k, k)); } boolean checkResult(int[] a, int m, int n) { int[] aCopy = Arrays.copyOf(a, a.length); Arrays.sort(aCopy); for (int i = m; i <= n; i++) { if (a[i] != aCopy[i]) { return false; } } return true; } }
apache-2.0
blackcathacker/kc.preclean
coeus-code/src/main/java/org/kuali/coeus/common/framework/unit/Unit.java
7274
/* * Copyright 2005-2014 The Kuali Foundation * * Licensed under the Educational Community 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.osedu.org/licenses/ECL-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.kuali.coeus.common.framework.unit; import org.kuali.coeus.common.api.unit.UnitContract; import org.kuali.coeus.common.framework.org.Organization; import org.kuali.coeus.common.framework.unit.admin.UnitAdministrator; import org.kuali.coeus.sys.framework.model.KcPersistableBusinessObjectBase; import org.kuali.rice.core.api.mo.common.active.MutableInactivatable; import org.kuali.rice.krad.data.jpa.converters.BooleanYNConverter; import javax.persistence.*; import java.util.ArrayList; import java.util.Collections; import java.util.List; /** * This class is a Unit */ @Entity @Table(name = "UNIT") public class Unit extends KcPersistableBusinessObjectBase implements MutableInactivatable, UnitContract { private static final long serialVersionUID = 7170184898996866958L; @Id @Column(name = "UNIT_NUMBER") private String unitNumber; @Column(name = "PARENT_UNIT_NUMBER") private String parentUnitNumber; @Column(name = "ORGANIZATION_ID") private String organizationId; @Column(name = "UNIT_NAME") private String unitName; //maps to Campus-code @Transient private String code; @Column(name = "ACTIVE_FLAG") @Convert(converter = BooleanYNConverter.class) private boolean active; @ManyToOne(cascade = { CascadeType.REFRESH }) @JoinColumn(name = "PARENT_UNIT_NUMBER", referencedColumnName = "UNIT_NUMBER", insertable = false, updatable = false) private Unit parentUnit; @OneToMany(mappedBy = "unit") private List<UnitAdministrator> unitAdministrators; @ManyToOne(cascade = { CascadeType.REFRESH }) @JoinColumn(name = "ORGANIZATION_ID", referencedColumnName = "ORGANIZATION_ID", insertable = false, updatable = false) private Organization organization; public Unit() { super(); unitAdministrators = new ArrayList<UnitAdministrator>(); } @Override public String getUnitNumber() { return unitNumber; } public void setUnitNumber(String unitNumber) { this.unitNumber = unitNumber; } public String getParentUnitNumber() { return parentUnitNumber; } public void setParentUnitNumber(String parentUnitNumber) { this.parentUnitNumber = parentUnitNumber; } /** * Returns the organization id. If no organization id is found, recurses up the hierarchy until a valid organization id is found. * * @return an organization id in the hierarchy */ @Override public String getOrganizationId() { if (organizationId == null && this.getParentUnit() != null && this.getParentUnit().getUnitNumber() != null) { return this.getParentUnit().getOrganizationId(); } return organizationId; } public void setOrganizationId(String organizationId) { this.organizationId = organizationId; } @Override public String getUnitName() { return unitName; } public void setUnitName(String unitName) { this.unitName = unitName; } public String getCode() { return code; } public void setCode(String code) { this.code = code; } @Override public boolean isActive() { return active; } public void setActive(boolean active) { this.active = active; } /** * Returns the organization. If no organization is found, recurses up the hierarchy until a valid organization is found. * * @return an organization in the hierarchy */ public Organization getOrganization() { if (organization == null && this.getParentUnit() != null && this.getParentUnit().getUnitNumber() != null) { //will recurse up hierarchy until an Organization is found return this.getParentUnit().getOrganization(); } return organization; } public void setOrganization(Organization organization) { this.organization = organization; } @Override public Unit getParentUnit() { return parentUnit; } public void setParentUnit(Unit parentUnit) { this.parentUnit = parentUnit; } @Override public List<UnitAdministrator> getUnitAdministrators() { //KRACOEUS-5499 - Sort the List for better grouping. if (unitAdministrators != null) { Collections.sort(unitAdministrators); } return unitAdministrators; } public void setUnitAdministrators(List<UnitAdministrator> unitAdministrators) { this.unitAdministrators = unitAdministrators; } /** * Gets the organizationIdForMaintenance attribute. * @return Returns the organizationIdForMaintenance. */ public String getOrganizationIdForMaintenance() { return organizationId; } /** * Sets the organizationIdForMaintenance attribute value. * @param organizationIdForMaintenance The organizationIdForMaintenance to set. */ public void setOrganizationIdForMaintenance(String organizationIdForMaintenance) { this.organizationId = organizationIdForMaintenance; } /** * Determine whether the given unit is a parent (or grandparent, etc) of this unit. * @param parentCandidate * @return boolean */ public boolean isParentUnit(Unit parentCandidate) { if (this.getParentUnitNumber() != null) { if (this.getParentUnitNumber().equals(parentCandidate.getUnitNumber())) { return true; } else { return this.getParentUnit().isParentUnit(parentCandidate); } } return false; } @SuppressWarnings("unchecked") @Override public List buildListOfDeletionAwareLists() { // TODO : need this ? List managedLists = super.buildListOfDeletionAwareLists(); managedLists.add(getUnitAdministrators()); return managedLists; } @Override public int hashCode() { final int PRIME = 31; int result = 1; result = PRIME * result + ((unitNumber == null) ? 0 : unitNumber.hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj) { return true; } if (obj == null) { return false; } if (!(obj instanceof Unit)) { return false; } Unit other = (Unit) obj; if (unitNumber == null) { if (other.unitNumber != null) { return false; } } else if (!unitNumber.equals(other.unitNumber)) { return false; } return true; } }
apache-2.0
jamesgiang/AusSnowCam
src/com/jamesgiang/aussnowcam/BOMClient.java
491
package com.jamesgiang.aussnowcam; import com.loopj.android.http.*; public class BOMClient { private static final String BASE_URL = "http://reg.bom.gov.au/fwo/"; private static AsyncHttpClient client = new AsyncHttpClient(); public static void get(String url, RequestParams params, AsyncHttpResponseHandler responseHandler) { client.get(getAbsoluteUrl(url), params, responseHandler); } private static String getAbsoluteUrl(String relativeUrl) { return BASE_URL + relativeUrl; } }
apache-2.0
wso2/andes
modules/andes-core/broker/src/main/java/org/wso2/andes/server/exchange/DirectExchange.java
6144
/* * Copyright (c) 2005-2014, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. * * WSO2 Inc. 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.wso2.andes.server.exchange; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.wso2.andes.AMQException; import org.wso2.andes.exchange.ExchangeDefaults; import org.wso2.andes.framing.AMQShortString; import org.wso2.andes.framing.FieldTable; import org.wso2.andes.server.binding.Binding; import org.wso2.andes.server.message.InboundMessage; import org.wso2.andes.server.queue.AMQQueue; import org.wso2.andes.server.queue.BaseQueue; import org.wso2.andes.server.virtualhost.VirtualHost; import javax.management.JMException; import java.util.ArrayList; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.CopyOnWriteArraySet; public class DirectExchange extends AbstractExchange { private static final Log _logger = LogFactory.getLog(DirectExchange.class); private final ConcurrentHashMap<String, CopyOnWriteArraySet<Binding>> _bindingsByKey = new ConcurrentHashMap<String, CopyOnWriteArraySet<Binding>>(); public static final ExchangeType<DirectExchange> TYPE = new ExchangeType<DirectExchange>() { public AMQShortString getName() { return ExchangeDefaults.DIRECT_EXCHANGE_CLASS; } public Class<DirectExchange> getExchangeClass() { return DirectExchange.class; } public DirectExchange newInstance(VirtualHost host, AMQShortString name, boolean durable, int ticket, boolean autoDelete) throws AMQException { DirectExchange exch = new DirectExchange(); exch.initialise(host,name,durable,ticket,autoDelete); return exch; } public AMQShortString getDefaultExchangeName() { return ExchangeDefaults.DIRECT_EXCHANGE_NAME; } }; public DirectExchange() { super(TYPE); } protected AbstractExchangeMBean createMBean() throws JMException { return new DirectExchangeMBean(this); } public Log getLogger() { return _logger; } public ArrayList<? extends BaseQueue> doRoute(InboundMessage payload) { final String routingKey = payload.getRoutingKey(); CopyOnWriteArraySet<Binding> bindings = _bindingsByKey.get(routingKey == null ? "" : routingKey); if(bindings != null) { final ArrayList<BaseQueue> queues = new ArrayList<BaseQueue>(bindings.size()); for(Binding binding : bindings) { queues.add(binding.getQueue()); binding.incrementMatches(); } if (_logger.isDebugEnabled()) { _logger.debug("Publishing message to queue " + queues); } return queues; } else { return new ArrayList<BaseQueue>(0); } } public boolean isBound(AMQShortString routingKey, FieldTable arguments, AMQQueue queue) { return isBound(routingKey,queue); } public boolean isBound(AMQShortString routingKey, AMQQueue queue) { String bindingKey = (routingKey == null) ? "" : routingKey.toString(); CopyOnWriteArraySet<Binding> bindings = _bindingsByKey.get(bindingKey); if(bindings != null) { for(Binding binding : bindings) { if(binding.getQueue().equals(queue)) { return true; } } } return false; } public boolean isBound(AMQShortString routingKey) { String bindingKey = (routingKey == null) ? "" : routingKey.toString(); CopyOnWriteArraySet<Binding> bindings = _bindingsByKey.get(bindingKey); return bindings != null && !bindings.isEmpty(); } public boolean isBound(AMQQueue queue) { for (CopyOnWriteArraySet<Binding> bindings : _bindingsByKey.values()) { for(Binding binding : bindings) { if(binding.getQueue().equals(queue)) { return true; } } } return false; } public boolean hasBindings() { return !getBindings().isEmpty(); } protected void onBind(final Binding binding) { String bindingKey = binding.getBindingKey(); AMQQueue queue = binding.getQueue(); AMQShortString routingKey = AMQShortString.valueOf(bindingKey); assert queue != null; assert routingKey != null; CopyOnWriteArraySet<Binding> bindings = _bindingsByKey.get(bindingKey); if(bindings == null) { bindings = new CopyOnWriteArraySet<Binding>(); CopyOnWriteArraySet<Binding> newBindings; if((newBindings = _bindingsByKey.putIfAbsent(bindingKey, bindings)) != null) { bindings = newBindings; } } bindings.add(binding); } protected void onUnbind(final Binding binding) { assert binding != null; CopyOnWriteArraySet<Binding> bindings = _bindingsByKey.get(binding.getBindingKey()); if(bindings != null) { bindings.remove(binding); } } }
apache-2.0
FIXTradingCommunity/fix-orchestra
message-model/src/main/java/io/fixprotocol/orchestra/message/Validator.java
1218
/* * Copyright 2017-2020 FIX Protocol 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 io.fixprotocol.orchestra.message; import io.fixprotocol._2020.orchestra.repository.MessageType; /** * Validate a message against an Orchestra file * * @author Don Mendelson * * @param <M> message class */ public interface Validator<M> { /** * Validates a message. A {@code Validator} checks field presence, data range, and membership of a * code in a codeSet. * * @param message to validate * @param messageType Orchestra declaration of a message type * @throws TestException if a message is invalid */ void validate(M message, MessageType messageType) throws TestException; }
apache-2.0
McLeodMoores/starling
projects/master-db/src/main/java/com/opengamma/masterdb/security/hibernate/option/OptionPayoffStyleUserType.java
4696
/** * Copyright (C) 2009 - present by OpenGamma Inc. and the OpenGamma group of companies * * Please see distribution for license. */ package com.opengamma.masterdb.security.hibernate.option; import com.opengamma.financial.security.option.AssetOrNothingPayoffStyle; import com.opengamma.financial.security.option.AsymmetricPoweredPayoffStyle; import com.opengamma.financial.security.option.BarrierPayoffStyle; import com.opengamma.financial.security.option.CappedPoweredPayoffStyle; import com.opengamma.financial.security.option.CashOrNothingPayoffStyle; import com.opengamma.financial.security.option.ExtremeSpreadPayoffStyle; import com.opengamma.financial.security.option.FadeInPayoffStyle; import com.opengamma.financial.security.option.FixedStrikeLookbackPayoffStyle; import com.opengamma.financial.security.option.FloatingStrikeLookbackPayoffStyle; import com.opengamma.financial.security.option.GapPayoffStyle; import com.opengamma.financial.security.option.PayoffStyleVisitor; import com.opengamma.financial.security.option.PoweredPayoffStyle; import com.opengamma.financial.security.option.SimpleChooserPayoffStyle; import com.opengamma.financial.security.option.SupersharePayoffStyle; import com.opengamma.financial.security.option.VanillaPayoffStyle; import com.opengamma.masterdb.security.hibernate.EnumUserType; /** * Custom Hibernate usertype for the OptionPayoffStyle enum. */ public class OptionPayoffStyleUserType extends EnumUserType<OptionPayoffStyle> { private static final String ASSET_OR_NOTHING = "Asset-or-Nothing"; private static final String ASYMMETRIC_POWERED = "Asymmetric Powered"; private static final String BARRIER = "Barrier"; private static final String CAPPED_POWERED = "Capped Powered"; private static final String CASH_OR_NOTHING = "Cash-or-Nothing"; private static final String EXTREME_SPREAD = "Extreme Spread"; private static final String FADE_IN = "Fade-In"; private static final String FIXED_STRIKE_LOOKBACK = "Fixed-Strike Lookback"; private static final String FLOATING_STRIKE_LOOKBACK = "Floating-Strike Lookback"; private static final String GAP = "Gap"; private static final String POWERED = "Powered"; private static final String SIMPLE_CHOOSER = "Simple Chooser"; private static final String SUPERSHARE = "Supershare"; private static final String VANILLA = "Vanilla"; public OptionPayoffStyleUserType() { super(OptionPayoffStyle.class, OptionPayoffStyle.values()); } @Override protected String enumToStringNoCache(final OptionPayoffStyle value) { return value.accept(new PayoffStyleVisitor<String>() { @Override public String visitAssetOrNothingPayoffStyle(final AssetOrNothingPayoffStyle payoffStyle) { return ASSET_OR_NOTHING; } @Override public String visitAsymmetricPoweredPayoffStyle(final AsymmetricPoweredPayoffStyle payoffStyle) { return ASYMMETRIC_POWERED; } @Override public String visitBarrierPayoffStyle(final BarrierPayoffStyle payoffStyle) { return BARRIER; } @Override public String visitCappedPoweredPayoffStyle(final CappedPoweredPayoffStyle payoffStyle) { return CAPPED_POWERED; } @Override public String visitCashOrNothingPayoffStyle(final CashOrNothingPayoffStyle payoffStyle) { return CASH_OR_NOTHING; } @Override public String visitExtremeSpreadPayoffStyle(final ExtremeSpreadPayoffStyle payoffStyle) { return EXTREME_SPREAD; } @Override public String visitFadeInPayoffStyle(final FadeInPayoffStyle payoffStyle) { return FADE_IN; } @Override public String visitFixedStrikeLookbackPayoffStyle(final FixedStrikeLookbackPayoffStyle payoffStyle) { return FIXED_STRIKE_LOOKBACK; } @Override public String visitFloatingStrikeLookbackPayoffStyle(final FloatingStrikeLookbackPayoffStyle payoffStyle) { return FLOATING_STRIKE_LOOKBACK; } @Override public String visitGapPayoffStyle(final GapPayoffStyle payoffStyle) { return GAP; } @Override public String visitPoweredPayoffStyle(final PoweredPayoffStyle payoffStyle) { return POWERED; } @Override public String visitSimpleChooserPayoffStyle(final SimpleChooserPayoffStyle payoffStyle) { return SIMPLE_CHOOSER; } @Override public String visitSupersharePayoffStyle(final SupersharePayoffStyle payoffStyle) { return SUPERSHARE; } @Override public String visitVanillaPayoffStyle(final VanillaPayoffStyle payoffStyle) { return VANILLA; } }); } }
apache-2.0
johnktims/gh-event-api
src/main/java/com/github/shredder121/gh_event_api/filter/package-info.java
710
/* * Copyright 2016 Shredder121. * * 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. */ /** * Various filters for processing incoming requests. */ package com.github.shredder121.gh_event_api.filter;
apache-2.0
oehme/analysing-gradle-performance
my-app/src/test/java/org/gradle/test/performance/mediummonolithicjavaproject/p84/Test1695.java
2173
package org.gradle.test.performance.mediummonolithicjavaproject.p84; import org.junit.Test; import static org.junit.Assert.*; public class Test1695 { Production1695 objectUnderTest = new Production1695(); @Test public void testProperty0() { Production1692 value = new Production1692(); objectUnderTest.setProperty0(value); assertEquals(value, objectUnderTest.getProperty0()); } @Test public void testProperty1() { Production1693 value = new Production1693(); objectUnderTest.setProperty1(value); assertEquals(value, objectUnderTest.getProperty1()); } @Test public void testProperty2() { Production1694 value = new Production1694(); objectUnderTest.setProperty2(value); assertEquals(value, objectUnderTest.getProperty2()); } @Test public void testProperty3() { String value = "value"; objectUnderTest.setProperty3(value); assertEquals(value, objectUnderTest.getProperty3()); } @Test public void testProperty4() { String value = "value"; objectUnderTest.setProperty4(value); assertEquals(value, objectUnderTest.getProperty4()); } @Test public void testProperty5() { String value = "value"; objectUnderTest.setProperty5(value); assertEquals(value, objectUnderTest.getProperty5()); } @Test public void testProperty6() { String value = "value"; objectUnderTest.setProperty6(value); assertEquals(value, objectUnderTest.getProperty6()); } @Test public void testProperty7() { String value = "value"; objectUnderTest.setProperty7(value); assertEquals(value, objectUnderTest.getProperty7()); } @Test public void testProperty8() { String value = "value"; objectUnderTest.setProperty8(value); assertEquals(value, objectUnderTest.getProperty8()); } @Test public void testProperty9() { String value = "value"; objectUnderTest.setProperty9(value); assertEquals(value, objectUnderTest.getProperty9()); } }
apache-2.0
icza/sc2gears
src/hu/belicza/andras/sc2gears/services/plugins/PluginServicesImpl.java
2489
/* * Project Sc2gears * * Copyright (c) 2010 Andras Belicza <iczaaa@gmail.com> * * This software is the property of Andras Belicza. * Copying, modifying, distributing, refactoring without the authors permission * is prohibited and protected by Law. */ package hu.belicza.andras.sc2gears.services.plugins; import java.io.File; import hu.belicza.andras.sc2gears.Consts; import hu.belicza.andras.sc2gears.services.plugins.PluginControl; import hu.belicza.andras.sc2gears.ui.dialogs.PluginManagerDialog; import hu.belicza.andras.sc2gearspluginapi.PluginServices; import hu.belicza.andras.sc2gearspluginapi.api.SettingsApi; /** * A {@link PluginServices} provider. * * @author Andras Belicza */ public class PluginServicesImpl implements PluginServices { /** Implementation version. */ public static final String IMPL_VERSION = "2.2"; /** Reference to the plugin control. */ private final PluginControl pluginControl; /** The persistent settings of the plugin. */ private SettingsApi settings; /** * Creates a new PluginServicesImpl. * @param pluginControl reference to the plugin control */ public PluginServicesImpl( final PluginControl pluginControl ) { this.pluginControl = pluginControl; } @Override public String getImplementationVersion() { return IMPL_VERSION; } @Override public void openPluginDetailsInPluginManager() { new PluginManagerDialog( pluginControl ); } @Override public synchronized SettingsApi getSettingsApi() { if ( settings == null ) settings = new SettingsApiImpl( new File( Consts.FOLDER_PLUGIN_SETTINGS, pluginControl.pluginDescriptor.getMainClass() + ".xml" ) ); return settings; } /** * Returns the persistent settings of the plugin without creating it if it is not yet created. * @return the persistent settings of the plugin without creating it if it is not yet created */ public synchronized SettingsApi getSettingsWithoutCreating() { return settings; } @Override public File getPluginFileCacheFolder() { final File plguinFileCacheFolder = new File( Consts.FOLDER_PLUGIN_FILE_CACHE_BASE, pluginControl.pluginDescriptor.getMainClass() ); if ( !plguinFileCacheFolder.exists() ) plguinFileCacheFolder.mkdirs(); return plguinFileCacheFolder; } @Override public void reportFailure( final boolean requestRestart ) { pluginControl.reportFailure( requestRestart ); } }
apache-2.0
Aj-Apps/SlidingTabsColors
Application/src/main/java/com/ajapps/climatecars/slidingtabscolors/ContentFragment.java
1901
package com.ajapps.climatecars.slidingtabscolors; import android.os.Bundle; import android.support.v4.app.Fragment; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.TextView; public class ContentFragment extends Fragment { private static final String KEY_TITLE = "title"; private static final String KEY_INDICATOR_COLOR = "indicator_color"; private static final String KEY_DIVIDER_COLOR = "divider_color"; public static ContentFragment newInstance(CharSequence title, int indicatorColor, int dividerColor) { Bundle bundle = new Bundle(); bundle.putCharSequence(KEY_TITLE, title); bundle.putInt(KEY_INDICATOR_COLOR, indicatorColor); bundle.putInt(KEY_DIVIDER_COLOR, dividerColor); ContentFragment fragment = new ContentFragment(); fragment.setArguments(bundle); return fragment; } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { return inflater.inflate(R.layout.pager_item, container, false); } @Override public void onViewCreated(View view, Bundle savedInstanceState) { super.onViewCreated(view, savedInstanceState); Bundle args = getArguments(); if (args != null) { TextView title = (TextView) view.findViewById(R.id.item_title); title.setText("Title: " + args.getCharSequence(KEY_TITLE)); int indicatorColor = args.getInt(KEY_INDICATOR_COLOR); TextView indicatorColorView = (TextView) view.findViewById(R.id.item_indicator_color); indicatorColorView.setText("Indicator: #" + Integer.toHexString(indicatorColor)); indicatorColorView.setTextColor(indicatorColor); } } }
apache-2.0
cdegroot/river
src/com/sun/jini/jeri/internal/http/HttpServerManager.java
3584
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.sun.jini.jeri.internal.http; import com.sun.jini.thread.Executor; import com.sun.jini.thread.GetThreadPoolAction; import java.util.Iterator; import java.util.LinkedList; import java.util.Random; import net.jini.io.context.AcknowledgmentSource; /** * Class for managing server-side functions shared among multiple connections, * such as acknowledgment notification. * * * */ public class HttpServerManager { private static final Executor userThreadPool = (Executor) java.security.AccessController.doPrivileged( new GetThreadPoolAction(true)); private final AckListenerMap ackListeners; private final Object cookieLock = new Object(); private long nextCookie = new Random().nextLong(); /** * Creates new HttpServerManager which invalidates transport * acknowledgments after the given timeout. */ public HttpServerManager(long ackTimeout) { ackListeners = new AckListenerMap(ackTimeout); } /** * Returns unique cookie string. */ String newCookie() { synchronized (cookieLock) { return Long.toString(Math.abs(nextCookie++), 16); } } /** * Registers listener waiting for given cookie. */ void addAckListener(String cookie, AcknowledgmentSource.Listener listener) { if (cookie == null || listener == null) { throw new NullPointerException(); } synchronized (ackListeners) { LinkedList list = (LinkedList) ackListeners.get(cookie); if (list == null) { list = new LinkedList(); ackListeners.put(cookie, list); } list.add(listener); } } /** * Notifies all listeners waiting for given cookie with received == true. * Notifications are performed in a separate thread. */ void notifyAckListeners(String cookie) { if (cookie == null) { throw new NullPointerException(); } final LinkedList list = (LinkedList) ackListeners.remove(cookie); if (list != null) { userThreadPool.execute(new Runnable() { public void run() { doAckNotifications(list, true); } }, "Ack notifier"); } } /** * Notifies list of AcknowledgmentSource.Listeners. */ private static void doAckNotifications(LinkedList list, boolean recvd) { for (Iterator i = list.iterator(); i.hasNext(); ) { AcknowledgmentSource.Listener al = (AcknowledgmentSource.Listener) i.next(); try { al.acknowledgmentReceived(recvd); } catch (Throwable th) {} } } /** * Map for tracking registered AcknowledgmentSource.Listeners. */ private static class AckListenerMap extends TimedMap { AckListenerMap(long timeout) { super(userThreadPool, timeout); } void evicted(Object key, Object value) { doAckNotifications((LinkedList) value, false); } } }
apache-2.0
gsummer/cyNeo4j
src/main/java/nl/maastrichtuniversity/networklibrary/cyneo4j/internal/utils/CyUtils.java
11588
// cyNeo4j - Cytoscape app connecting to Neo4j // // Copyright 2014-2021 // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package nl.maastrichtuniversity.networklibrary.cyneo4j.internal.utils; import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.Set; import org.cytoscape.model.CyColumn; import org.cytoscape.model.CyEdge; import org.cytoscape.model.CyIdentifiable; import org.cytoscape.model.CyNetwork; import org.cytoscape.model.CyNode; import org.cytoscape.model.CyRow; import org.cytoscape.model.CyTable; import org.cytoscape.view.model.CyNetworkView; import org.cytoscape.view.vizmap.VisualMappingManager; import org.cytoscape.view.vizmap.VisualStyle; import com.fasterxml.jackson.databind.ObjectMapper; public class CyUtils { public static Set<CyNode> getNodesWithValue(final CyNetwork net, final CyTable table, final String colname, final Object value) { final Collection<CyRow> matchingRows = table.getMatchingRows(colname, value); final Set<CyNode> nodes = new HashSet<CyNode>(); final String primaryKeyColname = table.getPrimaryKey().getName(); for (final CyRow row : matchingRows) { final Long nodeId = row.get(primaryKeyColname, Long.class); if (nodeId == null) continue; final CyNode node = net.getNode(nodeId); if (node == null) continue; nodes.add(node); } return nodes; } public static Set<CyEdge> getEdgeWithValue(final CyNetwork net, final CyTable table, final String colname, final Object value) { final Collection<CyRow> matchingRows = table.getMatchingRows(colname, value); final Set<CyEdge> edges = new HashSet<CyEdge>(); final String primaryKeyColname = table.getPrimaryKey().getName(); for (final CyRow row : matchingRows) { final Long edgeId = row.get(primaryKeyColname, Long.class); if (edgeId == null) continue; final CyEdge edge = net.getEdge(edgeId); if (edge == null) continue; edges.add(edge); } return edges; } public static String convertCyAttributesToJson(CyIdentifiable item, CyTable tab) { String params = "{"; // needs to be rebuild to ensure proper typing! ObjectMapper mapper = new ObjectMapper(); for (CyColumn cyCol : tab.getColumns()) { String paramName = cyCol.getName(); if (paramName.equals("neoid")) continue; Object paramValue = tab.getRow(item.getSUID()).get(cyCol.getName(), cyCol.getType()); System.out.println(paramName + " = " + paramValue); String paramValueStr = ""; if (paramValue == null) { continue; } else { Class<?> colClass = cyCol.getType(); Class<?> colTypeClass = cyCol.getListElementType(); if (colClass.equals(List.class)) { paramValueStr = "["; List<? extends Object> l = tab.getRow(item.getSUID()).getList(cyCol.getName(), cyCol.getListElementType()); Iterator<? extends Object> it = l.iterator(); while (it.hasNext()) { paramValueStr = paramValueStr + translateToJSON(it.next(), colTypeClass); if (it.hasNext()) { paramValueStr = paramValueStr + ", "; } } paramValueStr = paramValueStr + "]"; } else { paramValueStr = paramValueStr + translateToJSON(paramValue, cyCol.getType()); } // if(cyCol.getType() == String.class){ // paramValueStr = "\"" + paramValue.toString() + "\""; // } else if(){ // // } else // { // paramValueStr = paramValue.toString(); // } } String jsonParam = "\"" + paramName + "\" : " + paramValueStr + ","; params = params + jsonParam; } params = params.substring(0, params.length() - 1); params = params + "}"; return params; } protected static String translateToJSON(Object obj, Class<?> objType) { String value = null; if (objType.equals(String.class)) { value = "\"" + obj.toString().replaceAll("\"", "\\\\\"") + "\""; } else { value = obj.toString(); } return value; } public static Long getNeoID(CyNetwork net, CyNode n) { return net.getDefaultNodeTable().getRow(n.getSUID()).get("neoid", Long.class); } public static CyNode getNodeByNeoId(CyNetwork network, Long neoId) { Set<CyNode> res = CyUtils.getNodesWithValue(network, network.getDefaultNodeTable(), "neoid", neoId); if (res.size() > 1) { throw new IllegalArgumentException("more than one start node found! " + res.toString()); } if (res.size() == 0) { return null; } CyNode n = res.iterator().next(); return n; } public static Long getNeoID(CyNetwork net, CyEdge e) { return net.getDefaultEdgeTable().getRow(e.getSUID()).get("neoid", Long.class); } public static CyEdge getEdgeByNeoId(CyNetwork network, Long neoId) { Set<CyEdge> res = CyUtils.getEdgeWithValue(network, network.getDefaultEdgeTable(), "neoid", neoId); if (res.size() > 1) { throw new IllegalArgumentException("more than one start node found! " + res.toString()); } if (res.size() == 0) { return null; } CyEdge e = res.iterator().next(); return e; } public static void updateVisualStyle(VisualMappingManager visualMappingMgr, CyNetworkView view, CyNetwork network) { VisualStyle vs = visualMappingMgr.getDefaultVisualStyle(); visualMappingMgr.setVisualStyle(vs, view); vs.apply(view); view.updateView(); } public static void updateDirectedVisualStyle(VisualMappingManager visualMappingMgr, CyNetworkView view, CyNetwork network) { VisualStyle vs = getVisualStyleByName(visualMappingMgr, "Directed"); visualMappingMgr.setVisualStyle(vs, view); vs.apply(view); view.updateView(); } private static VisualStyle getVisualStyleByName(VisualMappingManager visualMappingMgr, String styleName) { Set<VisualStyle> styles = visualMappingMgr.getAllVisualStyles(); // fix because styles can not be found by name for (VisualStyle style : styles) { if (style.getTitle().equals(styleName)) { return style; } } return visualMappingMgr.getDefaultVisualStyle(); } private static boolean matchingValues(Class<?> valueClass, Class<?> colClass) { if (valueClass.equals(colClass)) { return true; } if (colClass.equals(Long.class) && valueClass.equals(Integer.class)) { return true; } // both lists! if (valueClass.equals(ArrayList.class) && colClass.equals(List.class)) { return true; // in case the content of the arrays don't match I am screwed. Neo4j allows // properties to be of different array types // Cytoscape not; so I'd run into crazy issues with casting around. } else { return false; } } private static String detectImmutableProblem(String key, CyTable table, Class<?> valueClass, Class<?> colClass) { CyColumn col = table.getColumn(key); String newKey = key; // trying to make this less confusing with the extra variables if (col.isImmutable() && !matchingValues(valueClass, colClass)) { newKey = key + "_cannot_change_original"; // we had this problem before and fixed it, now use the fixed column instead of // the previous one! if (table.getColumn(newKey) == null) { if (table.getColumn(key).getListElementType() != null) { table.createListColumn(newKey, table.getColumn(key).getListElementType(), false); } else { table.createColumn(newKey, table.getColumn(key).getType(), false); } // populate the new column! List<CyRow> rows = table.getAllRows(); for (CyRow row : rows) { if (row.isSet(key)) { table.getRow(row.get("SUID", Long.class)).set(newKey, row.getRaw(key)); } } } } return newKey; } public static void addValueToTable(Long suid, String key, Object value, CyTable table) { // System.out.println("value "+value.getClass()); Class<?> valueClass = value.getClass(); String fixedKey = detectImmutableProblem(key, table, valueClass, table.getColumn(key).getType()); Class<?> colClass = table.getColumn(fixedKey).getType(); Class<?> colTypeClass = table.getColumn(fixedKey).getListElementType(); // System.out.println("element "+colClass); if (colClass.equals(Long.class) && valueClass.equals(Integer.class)) { table.getRow(suid).set(fixedKey, Long.valueOf(((Integer) value).longValue())); return; } if (valueClass.equals(colClass)) { table.getRow(suid).set(fixedKey, value); return; } // both lists! if (valueClass.equals(ArrayList.class) && colClass.equals(List.class)) { if (colTypeClass.equals(getArrayListType(value))) { table.getRow(suid).set(fixedKey, value); } else { System.out.println("same property but different value types in the arrays!!"); // why is here no else? because I don't want to start casting around! Neo4j // allows properties to be different between nodes // Cytoscape does not. } } else { // one is not a list!! if (valueClass.equals(ArrayList.class)) { // need to change the colClass // use the data from the original column! Map<Long, Object> currData = new HashMap<Long, Object>(); List<CyRow> rows = table.getAllRows(); for (CyRow row : rows) { if (row.isSet(fixedKey)) { currData.put(row.get("SUID", Long.class), row.getRaw(fixedKey)); } } // table.deleteColumn(fixedKey); table.createListColumn(fixedKey, getArrayListType(value), false); for (Entry<Long, Object> e : currData.entrySet()) { ArrayList fixedOldValue = new ArrayList(); fixedOldValue.add(e.getValue()); table.getRow(e.getKey()).set(fixedKey, fixedOldValue); } } if (colClass.equals(List.class)) { ArrayList newValue = new ArrayList(); newValue.add(value); table.getRow(suid).set(fixedKey, newValue); } } } // this assumes that all the items in the arraylist are the same as it is used // for neo4j property arrays // in reality this is not true! public static Class<?> getArrayListType(Object a) { if (a.getClass() != ArrayList.class) return null; ArrayList arraylist = (ArrayList) a; if (arraylist.isEmpty()) { return null; } else { return arraylist.get(0).getClass(); } } public static void addProperties(Long suid, CyTable table, Map<String, Object> props) { for (Entry<String, Object> obj : props.entrySet()) { if (table.getColumn(obj.getKey()) == null) { if (obj.getValue().getClass() == ArrayList.class) { table.createListColumn(obj.getKey(), CyUtils.getArrayListType((ArrayList) obj.getValue()), false); } else { // // try { // Integer.parseInt((String) obj.getValue()); // table.createColumn(obj.getKey(), Integer.class, false); // } // catch (NumberFormatException e){ // table.createColumn(obj.getKey(), obj.getValue().getClass(), false); // } // System.out.println("table "+obj.getValue().getClass()); // System.out.println("table "+obj.getValue()); // System.out.println("table "+obj.getKey()); table.createColumn(obj.getKey(), obj.getValue().getClass(), false); } } // CyUtils.addValueToTable(suid, obj.getKey(), obj.getValue(), table); } } }
apache-2.0
hxf0801/jbpm
jbpm-flow-builder/src/main/java/org/jbpm/compiler/xml/processes/ImportHandler.java
2025
package org.jbpm.compiler.xml.processes; import java.util.ArrayList; import java.util.HashSet; import org.kie.api.definition.process.Process; import org.drools.core.xml.BaseAbstractHandler; import org.drools.core.xml.ExtensibleXmlParser; import org.drools.core.xml.Handler; import org.jbpm.workflow.core.impl.WorkflowProcessImpl; import org.w3c.dom.Element; import org.xml.sax.Attributes; import org.xml.sax.SAXException; public class ImportHandler extends BaseAbstractHandler implements Handler { public ImportHandler() { if ( (this.validParents == null) && (this.validPeers == null) ) { this.validParents = new HashSet(); this.validParents.add( Process.class ); this.validPeers = new HashSet(); this.validPeers.add( null ); this.allowNesting = false; } } public Object start(final String uri, final String localName, final Attributes attrs, final ExtensibleXmlParser parser) throws SAXException { parser.startElementBuilder( localName, attrs ); WorkflowProcessImpl process = ( WorkflowProcessImpl ) parser.getParent(); final String name = attrs.getValue( "name" ); emptyAttributeCheck( localName, "name", name, parser ); java.util.List<String> list = process.getImports(); if ( list == null ) { list = new ArrayList<String>(); process.setImports( list ); } list.add( name ); return null; } public Object end(final String uri, final String localName, final ExtensibleXmlParser parser) throws SAXException { final Element element = parser.endElementBuilder(); return null; } public Class generateNodeFor() { return null; } }
apache-2.0
basho/riak-java-client
src/main/java/com/basho/riak/client/core/query/crdt/ops/GSetOp.java
1249
/* * Copyright 2016 Basho Technologies Inc * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.basho.riak.client.core.query.crdt.ops; import com.basho.riak.client.core.util.BinaryValue; import java.util.HashSet; import java.util.Set; public class GSetOp implements CrdtOp { protected final Set<BinaryValue> adds = new HashSet<>(); public GSetOp(Set<BinaryValue> adds) { this.adds.addAll(adds); } public GSetOp() {} public GSetOp add(BinaryValue element) { this.adds.add(element); return this; } public Set<BinaryValue> getAdds() { return adds; } @Override public String toString() { return "{Add: " + adds + "}"; } }
apache-2.0
JCE-Group/Cmput391-JCE
proj1/WEB-INF/classes/UploadImage.java
6314
/*** * A sample program to demonstrate how to use servlet to * load an image file from the client disk via a web browser * and insert the image into a table in Oracle DB. * * Copyright 2005 COMPUT 391 Team, CS, UofA * Author: Fan Deng * * 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. * * * the table shall be created using the following CREATE TABLE pictures ( pic_id int, pic_desc varchar(100), pic BLOB, primary key(pic_id) ); * * One may also need to create a sequence using the following * SQL statement to automatically generate a unique pic_id: * * CREATE SEQUENCE pic_id_sequence; * ***/ import java.io.*; import javax.servlet.*; import javax.servlet.http.*; import java.sql.*; import java.util.*; import oracle.sql.*; import oracle.jdbc.*; import java.awt.Image; import java.awt.image.BufferedImage; import javax.imageio.ImageIO; /** * The package commons-fileupload-1.0.jar is downloaded from * http://jakarta.apache.org/commons/fileupload/ * and it has to be put under WEB-INF/lib/ directory in your servlet context. * One shall also modify the CLASSPATH to include this jar file. */ import org.apache.commons.fileupload.DiskFileUpload; import org.apache.commons.fileupload.FileItem; public class UploadImage extends HttpServlet { public String response_message; public void doPost(HttpServletRequest request,HttpServletResponse response) throws ServletException, IOException { // change the following parameters to connect to the oracle database String username = "peijen"; String password = "z23867698"; String drivername = "oracle.jdbc.driver.OracleDriver"; String dbstring ="jdbc:oracle:thin:@gwynne.cs.ualberta.ca:1521:CRS"; int pic_id = 0; String success = "Error! Go back to your images"; int suc = 0; HttpSession session = request.getSession(); String owner =(String)session.getAttribute("username"); try { //Parse the HTTP request to get the image stream DiskFileUpload fu = new DiskFileUpload(); List FileItems = fu.parseRequest(request); // Process the uploaded items, assuming only 1 image file uploaded Iterator i = FileItems.iterator(); FileItem item = (FileItem) i.next(); while (i.hasNext() && item.isFormField()) { item = (FileItem) i.next(); } //Get the image stream InputStream instream = item.getInputStream(); BufferedImage img = ImageIO.read(instream); BufferedImage thumbNail = shrink(img, 5); // Connect to the database and create a statement Connection conn = getConnected(drivername,dbstring, username,password); Statement stmt = conn.createStatement(); /* * First, to generate a unique pic_id using an SQL sequence */ ResultSet rset1 = stmt.executeQuery("SELECT MAX(photo_id) from images"); rset1.next(); pic_id = rset1.getInt(1) + 1; //Insert an empty blob into the table first. Note that you have to //use the Oracle specific function empty_blob() to create an empty blob stmt.execute("INSERT INTO images VALUES("+pic_id+",\'"+ owner +"\',2 ,null, null, null, null,empty_blob(), empty_blob())"); // to retrieve the lob_locator // Note that you must use "FOR UPDATE" in the select statement String cmd = "SELECT * FROM images WHERE photo_id = "+pic_id+" FOR UPDATE"; ResultSet rset = stmt.executeQuery(cmd); rset.next(); BLOB myblob = ((OracleResultSet)rset).getBLOB("photo"); BLOB mythumbblob = ((OracleResultSet)rset).getBLOB("thumbnail"); //Write the thumbnail to blob OutputStream thumboutstream = mythumbblob.getBinaryOutputStream(); ImageIO.write(thumbNail, "jpg", thumboutstream); thumboutstream.close(); //Write the image to the blob object OutputStream outstream = myblob.getBinaryOutputStream(); ImageIO.write(img, "jpg", outstream); outstream.close(); instream.close(); outstream.close(); stmt.executeUpdate("commit"); response_message = " Upload OK! "; suc = 1; conn.close(); } catch( Exception ex ) { //System.out.println( ex.getMessage()); response_message = ex.getMessage(); } //Output response to the client response.setContentType("text/html"); if (suc == 0) { PrintWriter out = response.getWriter(); out.println("<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.0 " + "Transitional//EN\">\n" + "<HTML>\n" + "<HEAD><TITLE>Upload Message</TITLE></HEAD>\n" + "<BODY>\n" + "<H1>" + response_message + owner + "</H1>\n"+ "<td colspan=2> Error has occurred, press to go back: <a href = Private.jsp>Here</a></td>\n" + "</BODY></HTML>"); } else { response.sendRedirect("Update.jsp?" + pic_id); } } /* /* To connect to the specified database */ private static Connection getConnected( String drivername, String dbstring, String username, String password ) throws Exception { Class drvClass = Class.forName(drivername); DriverManager.registerDriver((Driver) drvClass.newInstance()); return( DriverManager.getConnection(dbstring,username,password)); } //shrink image by a factor of n, and return the shrinked image public static BufferedImage shrink(BufferedImage image, int n) { int w = image.getWidth() / n; int h = image.getHeight() / n; BufferedImage shrunkImage = new BufferedImage(w, h, image.getType()); for (int y=0; y < h; ++y) for (int x=0; x < w; ++x) shrunkImage.setRGB(x, y, image.getRGB(x*n, y*n)); return shrunkImage; } }
apache-2.0
EMBL-EBI-SUBS/subs
subs-aeagent/src/main/java/uk/ac/ebi/subs/arrayexpress/repo/SampleDataRelatioshipRepository.java
787
package uk.ac.ebi.subs.arrayexpress.repo; import org.springframework.data.domain.Page; import org.springframework.data.domain.Pageable; import org.springframework.data.mongodb.repository.MongoRepository; import org.springframework.data.mongodb.repository.Query; import uk.ac.ebi.subs.arrayexpress.model.SampleDataRelationship; import java.util.List; public interface SampleDataRelatioshipRepository extends MongoRepository<SampleDataRelationship, String> { @Query(value="{ 'assay.sampleUses.sampleRef.accession': ?0 }") Page<SampleDataRelationship> findBySampleAccession(String sampleAccession, Pageable pageable); @Query("{ 'assay.sampleUses.sampleRef.accession' : { $in : ?0 } }") List<SampleDataRelationship> findBySampleAccessions(String[] sampleAccessions); }
apache-2.0
nidi3/maven-tools
tools-maven-plugin/src/main/java/guru/nidi/maven/tools/dependency/IoUtil.java
1189
/* * Copyright © 2014 Stefan Niederhauser (nidin@gmx.ch) * * 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 guru.nidi.maven.tools.dependency; import java.io.*; class IoUtil { private IoUtil() { } static void copy(InputStream in, OutputStream out) throws IOException { final byte[] buf = new byte[10000]; int read; while ((read = in.read(buf)) > 0) { out.write(buf, 0, read); } } static void deleteAll(File dir) { for (File f : dir.listFiles()) { if (f.isDirectory()) { deleteAll(f); } else { f.delete(); } } } }
apache-2.0
clive-jevons/joynr
java/messaging/messaging-common/src/main/java/io/joynr/messaging/datatypes/package-info.java
676
package io.joynr.messaging.datatypes; /* * #%L * %% * Copyright (C) 2011 - 2017 BMW Car IT GmbH * %% * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * #L% */
apache-2.0
nadam/tg-bot-api
src/main/java/se/anyro/tgbotapi/types/inline/InputVenueMessageContent.java
673
package se.anyro.tgbotapi.types.inline; /** * @see <a href="https://core.telegram.org/bots/api#inputvenuemessagecontent">Official documentation of * InputVenueMessageContent</a> */ public class InputVenueMessageContent extends InputMessageContent { public float latitude; public float longitude; public String title; public String address; public String foursquare_id; public String foursquare_type; public InputVenueMessageContent(float latitude, float longitude, String title, String address) { this.latitude = latitude; this.longitude = longitude; this.title = title; this.address = address; } }
apache-2.0
lesfurets/dOOv
sample/example/src/main/java/io/doov/sample/validation/RulesOld.java
1921
/* * Copyright 2017 Courtanet * * 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.doov.sample.validation; import static java.time.temporal.ChronoUnit.YEARS; import java.time.LocalDate; import io.doov.sample.model.*; public class RulesOld { public static boolean validateEmail(Account account) { if (account == null) { return true; } if (account.getEmail() == null) { return true; } if (account.getEmail().matches("\\w+[@]\\w+\\.com")) { return true; } if (account.getEmail().matches("\\w+[@]\\w+\\.fr")) { return true; } return false; } public static boolean validateAccount(User user, Account account, Configuration config) { if (config == null) { return false; } if (user == null || user.getBirthDate() == null) { return false; } if (account == null || account.getCountry() == null || account.getPhoneNumber() == null) { return false; } if (YEARS.between(user.getBirthDate(), LocalDate.now()) >= 18 && account.getEmail().length() <= config.getMaxEmailSize() && account.getCompany() == Company.LES_FURETS && account.getPhoneNumber().startsWith("+33")) { return true; } return false; } }
apache-2.0
jsubercaze/wsrm
src/main/java/fr/tse/lt2c/satin/matrix/extraction/linkedmatrix/refactored/WSMRDecomposer.java
34036
package fr.tse.lt2c.satin.matrix.extraction.linkedmatrix.refactored; import java.awt.image.BufferedImage; import java.io.File; import java.io.IOException; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import javax.imageio.ImageIO; import org.apache.log4j.Level; import org.apache.log4j.Logger; import fr.tse.lt2c.satin.matrix.beans.BinaryMatrix; import fr.tse.lt2c.satin.matrix.beans.LinkedMatrix; import fr.tse.lt2c.satin.matrix.beans.LinkedMatrixElement; import fr.tse.lt2c.satin.matrix.beans.DecompositionResult; import fr.tse.lt2c.satin.matrix.beans.SortableRectangle; import fr.tse.lt2c.satin.matrix.beans.TemporaryRectangle; import fr.tse.lt2c.satin.matrix.movie.CreateMovieFromFiles; import fr.tse.lt2c.satin.matrix.utils.RectangleDeque; /** * Find the largest rectangle. Complexity : time O(n), space O(n). * * Add the optimisation if the removed rectangle in destacking is a point, leave * it to its parent * * @author Julien Subercaze * * 22/02/13 */ public class WSMRDecomposer { public static Level DEBUG_LEVEL = Level.DEBUG; /** * Minimum area for a rectangle to be kept in the final list */ private int MIN_AREA = 1; /** * The linked matrix */ BinaryMatrix binaryMatrix; /** * H1 in the paper (until fourth step, replaced by max) */ int[][] temp1; /** * W1 in the paper (until fourth step, replaced by max) */ int[][] temp2; /** * H2 in the paper */ int[][] temp3; /** * W2 in the paper */ int[][] temp4; // Matrix matrix; /** * Wether the matrix has been preprocessed */ boolean preprocessed; /** * Current point of the walker in the linked matrix */ private LinkedMatrixElement currentPoint; /** * Generate images to produce a movie of the decomposition (need to be * retested due to large modifications) */ private boolean generateImages; /** * Generate directly the movie */ private boolean movie; /** * Internal structure for generateing movie */ private ArrayList<BufferedImage> listImages; /** * Largest rectangle after {@link #fourthStep()} */ private SortableRectangle largestOne; /** * Heuristic : remove the largest rectangle prior to any other */ private boolean removeLargestFirst = false; /** * Various internal counters */ /** * Current area */ private int area = -1; /** * How many 1 to check on the columns */ private int xToCheck = -1; /** * How many 1 to check on the rows */ private int yToCheck = -1; /** * Number of 1 in this column */ private int xTotal = -1; /** * Number of 1 in this row */ private int yTotal = -1; // private LinkedMatrixElement currentBeginningLine; /** * Current step */ private int step = 0; /** * The linked matrix */ private LinkedMatrix linkedMatrix; /** * Storage for temporary area */ private int areaTmp; /** * Stack for rectangles */ private RectangleDeque stack; /** * List of extracted rectangles */ private List<SortableRectangle> rectangles; /** * Storage for previous point */ private LinkedMatrixElement lastpoint; /** * Create a decomposer for the given matrix * * @param m */ public WSMRDecomposer(BinaryMatrix m) { super(); this.binaryMatrix = m; temp1 = new int[m.getRow()][m.getCol()]; temp2 = new int[m.getRow()][m.getCol()]; } /** * Create a decomposer for the given matrix * * @param m * the matrix * @param images * create images at each step * @param movie * create a movie from the decomposition (experimental) */ public WSMRDecomposer(BinaryMatrix m, boolean images, boolean movie) { super(); this.binaryMatrix = m; temp1 = new int[m.getRow()][m.getCol()]; temp2 = new int[m.getRow()][m.getCol()]; this.generateImages = images; this.movie = movie; if (generateImages || movie) cleanfolder(); if (movie) listImages = new ArrayList<>(); } /** * Create a decomposer for the given matrix * * @param m * the matrix * @param images * create images at each step * @param movie * create a movie from the decomposition (experimental) * @param remove * the largest (approximated) rectangle first then process the * heuristic */ public WSMRDecomposer(BinaryMatrix m, boolean images, boolean movie, boolean removelargest) { super(); this.binaryMatrix = m; temp1 = new int[m.getRow()][m.getCol()]; temp2 = new int[m.getRow()][m.getCol()]; this.generateImages = images; this.movie = movie; if (generateImages || movie) cleanfolder(); if (movie) listImages = new ArrayList<>(); this.removeLargestFirst = removelargest; } /** * * @return the largest rectangle in this matrix (approximated, see paper) */ public SortableRectangle findLargestRectangle() { firstStep(); secondStep(); thirdStep(); fourthStep(); return firstLargestRectangle(); } /** * Compute for each column, i.e compute H1 matrix */ private void firstStep() { int current; for (int j = 0; j < binaryMatrix.getCol(); j++) { current = 1; for (int i = binaryMatrix.getRow() - 1; i >= 0; i--) { if (binaryMatrix.getMatrix()[i][j]) { temp1[i][j] = current; current++; } else { current = 1; } } } } /** * Compute for each row, W1 matrix */ private void secondStep() { int current; for (int i = 0; i < binaryMatrix.getRow(); i++) { current = 1; for (int j = binaryMatrix.getCol() - 1; j >= 0; j--) { if (binaryMatrix.getMatrix()[i][j]) { temp2[i][j] = current; current++; } else { current = 1; } } } } /** * The trick ! Compute both H2 and W2 */ private void thirdStep() { temp3 = new int[temp1.length][]; for (int i = 0; i < temp1.length; i++) temp3[i] = temp1[i].clone(); temp4 = new int[temp2.length][]; for (int i = 0; i < temp2.length; i++) temp4[i] = temp2[i].clone(); int previous; for (int i = 0; i < binaryMatrix.getRow(); i++) { previous = 0; for (int j = binaryMatrix.getCol() - 1; j >= 0; j--) { if (previous == 0) { // Leave unchanged previous = temp3[i][j]; } else if (temp3[i][j] <= previous) { previous = temp3[i][j]; } else { temp3[i][j] = previous; } } } // Et en colomnes for (int j = 0; j < binaryMatrix.getCol(); j++) { previous = 0; for (int i = binaryMatrix.getRow() - 1; i >= 0; i--) { if (previous == 0) previous = temp2[i][j]; else if (temp4[i][j] <= previous) { previous = temp2[i][j]; } else { temp4[i][j] = previous; } } } } /** * Replace temp1 and temp2 values with width and height for the largest * rectangle starting (top left) at the current point updated with removal * of zero in the matrix */ private void fourthStep() { int[] area_tmp = new int[2]; int largestArea = -1, x = 0, y = 0, width = 0, height = 0; linkedMatrix = new LinkedMatrix(binaryMatrix); LinkedMatrixElement current = linkedMatrix.getCurrentRoot(); for (int i = 0; i < binaryMatrix.getRow(); i++) { for (int j = 0; j < binaryMatrix.getCol(); j++) { current = current.getNextRight(); if (binaryMatrix.getMatrix()[i][j]) { area_tmp[0] = temp3[i][j] * temp2[i][j]; area_tmp[1] = temp1[i][j] * temp4[i][j]; int max = Math.max(area_tmp[0], area_tmp[1]); // logger.debug(i+","+j+" | "+area_tmp[0]+" "+area_tmp[1]+" "+max); if (max == area_tmp[0]) { temp2[i][j] = temp2[i][j]; temp1[i][j] = temp3[i][j]; } else { temp2[i][j] = temp4[i][j]; temp1[i][j] = temp1[i][j]; } // Update largest rectangle if (max > largestArea) { largestArea = max; linkedMatrix.setLargestRectangle(current); x = i; y = j; if (max == area_tmp[0]) { width = temp2[i][j]; height = temp3[i][j]; } else { width = temp4[i][j]; height = temp1[i][j]; } } } else { current = linkedMatrix.deleteZero(current); } } } if (largestArea != -1) largestOne = new SortableRectangle(x, y, width, height); } /** * * @return the largest rectangle */ private SortableRectangle firstLargestRectangle() { int area = 0; int x = 0; int y = 0; int width = 0; int height = 0; int[] area_tmp = new int[2]; for (int i = 0; i < binaryMatrix.getRow(); i++) { for (int j = 0; j < binaryMatrix.getCol(); j++) { if (binaryMatrix.getMatrix()[i][j]) { area_tmp[0] = temp3[i][j] * temp2[i][j]; area_tmp[1] = temp1[i][j] * temp4[i][j]; int max = Math.max(area_tmp[0], area_tmp[1]); // logger.debug(i+","+j+" | "+area_tmp[0]+" "+area_tmp[1]+" "+max); if (max > area) { x = i; y = j; if (max == area_tmp[0]) { width = temp2[i][j]; height = temp3[i][j]; } else { width = temp4[i][j]; height = temp1[i][j]; } area = max; } } } } return new SortableRectangle(x, y, width, height); } /** * Compute the DPs for the largest rectangle approximation */ public void preProcess() { firstStep(); secondStep(); thirdStep(); fourthStep(); preprocessed = true; } /** * Returns the list of maximum disjoint rectangles Sort criterium is the * area * * @return */ public DecompositionResult computeDecomposition(int min) { MIN_AREA = min; if (!preprocessed) preProcess(); // System.out.println(linkedMatrix); long t1 = System.nanoTime(); rectangles = new ArrayList<>(); stack = new RectangleDeque(linkedMatrix.getHeight(), linkedMatrix.getWidth()); if (removeLargestFirst) { LinkedMatrixElement largestUpperLeft = linkedMatrix .getLargestRectangle(); addRectangle(largestUpperLeft, largestOne.height, largestOne.width); } // matrix = new FastListMatrix(this.binaryMatrix.getRow(), // this.binaryMatrix.getCol()); // currentBeginningLine = null; currentPoint = linkedMatrix.getFirstElement(); step = 0; do { step++; if (currentPoint == null || currentPoint.isNull()) { // Move to the first element of the matrix currentPoint = linkedMatrix.getFirstElement(); } if (this.generateImages || movie) { generateImage(); } process(); } while (!linkedMatrix.isEmpty()); if (generateImages) { CreateMovieFromFiles.createMovieFromImages(listImages); } int ones = binaryMatrix.getNumberOfOnes(); temp1 = null; temp2 = null; temp3 = null; temp4 = null; binaryMatrix = null; return new DecompositionResult(System.nanoTime() - t1, rectangles, ones); } /** * Process a step in the matrix decomposition. Walk, stack, merge or remove. * */ private void process() { // if (lastpoint == currentPoint) // System.exit(-1); step++; if (stack.size() == 0) { // Add new rectangle if (stackNewRectangle()) { setCounters(); updateCounters(); goNextElementEmptyStack(); } else { lastpoint = currentPoint; currentPoint = linkedMatrix.getFirstElement(); } } else { areaTmp = getArea(currentPoint); if (areaTmp > area) { // Take care of previous rectangle checkUpdateOldRectangle(); // Start new rectangle if (stackNewRectangle()) { setCounters(); updateCounters(); // Try to merge tryMerge(); goNextElementStack(); } else currentPoint = linkedMatrix.getFirstElement(); } else { // Update counters updateCounters(); if (!foundAndMerge()) goNextElementStack(); } } } /** * First setting of counter, when new rectangle is stacked */ private void setCounters() { xToCheck = xTotal; yToCheck = yTotal; } /** * Check wether a rectangle has been found, if it could merge with previous * one and removes it */ private boolean foundAndMerge() { if (stack.size() == 0) return true;// can happen at the end if (!(xToCheck == 0)) return false; if (stack.size() == 1) { if (stack.peek().isValidated()) { removeCurrentRectangle(); return true; } else return false; } // Rectangle found if (!tryMerge()) { stack.peek().setValidated(true); stack.peek().setPotentialSecondArea(0); emptyStack(); } return true; } /** * * @return <code>true</code> if merging occurred, whether horizontal or * vertical */ private boolean tryMerge() { // if (DEBUG && stack.size()>0) // logger.debug("TryMerge " + stack); if (!mergeHorizontal()) { if (mergeVertical()) { if (stack.peek().isValidated()) { return false; } return true; } } else { return true; } return false; } /** * Remove the current rectangle from the matrix * * @return the upper left corner of the removed rectangle */ private LinkedMatrixElement removeCurrentRectangle() { TemporaryRectangle temp = stack.poll(); if (temp == null) return null; if (!temp.isValidated()) { potentialVSvalidated(-1, -1); } addRectangle(temp.getUpperLeftCorner(), temp.getHeight(), temp.getWidth()); // if (stack.size() > 0) // stack.peek().setRestartingPoint(temp.getUpperLeftCorner()); if (stack.size() > 0) { if (!stack.peek().isValidated()) { area = stack.peek().getArea(); } else area = 0; } return temp.getUpperLeftCorner(); } /** * Update the internal counters */ private void updateCounters() { stack.peek().setCurrentPosition(currentPoint); if (yToCheck == yTotal) stack.peek().setLastLineFirstElement(currentPoint); if (yToCheck > 0) { --yToCheck; } if (yToCheck == 0) { xToCheck--; if (xToCheck != 0) yToCheck = yTotal; else { if (stack.size() > 0) stack.peek().setValidated(true); } } } /** * After validation, check if rectangle finished, line finished. Update the * values of the counters accordingly */ private void checkUpdateOldRectangle() { // If current point is in the first line of the old rectangle, update // its width (case 1) if (stack.peek().isValidated()) return; if (stack.peek().getHeight() == 1) { stack.peek().setWidth( Math.max(currentPoint.getY() - stack.peek().getUpperLeftCorner().getY(), 1)); stack.peek().setValidated(true); } else if (xToCheck == xTotal) {// First line // Update width of the rectangle stack.peek().setWidth( currentPoint.getY() - stack.peek().getUpperLeftCorner().getY()); int potentialArea = (currentPoint.getY() - stack.peek() .getLastLineFirstElement().getY()) * (xToCheck - 1); } else if (stack.peek().getLastLineFirstElement() .isNextElementDownConsecutive() && stack.peek().getLastLineFirstElement().getNextDown() == currentPoint) { // Case 2 in the paper // Update the height stack.peek().setHeight(xTotal - xToCheck); stack.peek().setValidated(true); // nothing under } else { // Case 3 in the paper - compute potential size and cut if necessary int height = xToCheck - 1; height = height == 0 ? 1 : height; // int potentialArea = (currentPoint.getY() - // stack.peek().getLastLineFirstElement().getY()) * (height); // It will be checked after destacking if it is possible to continue // down on a new rectangle, with a new height and a reduced width } // Merge the rectangles. tryMerge(); // stack.peek().setRestartingPoint(currentPoint); } /** * Empty the stack, called whenever a rectangle is finished. Try to remove * other completed rectangles from the stack. If not, set the values for * next move */ private void emptyStack() { removeCurrentRectangle(); while (stack.size() > 0 && stack.peek().isValidated()) { removeCurrentRectangle(); } if (stack.size() > 0) { int potentialAreaVertical = (currentPoint.getY() - stack.peek().getLastLineFirstElement().getY() + 1) * (stack.peek().getHeight()); // Validated area int validatedArea = stack.peek().getWidth() * (currentPoint.getX() - stack.peek().getUpperLeftCorner() .getX()); // Choose the best cut potentialVSvalidated(validatedArea, potentialAreaVertical); } } /** * If the stack is empty, move to the next element of the linkedmatrix */ private void goNextElementEmptyStack() { if (yToCheck == yTotal) { if (!currentPoint.isNextElementDownConsecutive()) { stack.peek().setHeight(1); stack.peek().setWidth(1); stack.peek().setValidated(true); stack.peek().setPotentialSecondArea(0); // stack.peek().setUpperLeftCorner(oldCurrentPoint); if (!currentPoint.isNextElementRightConsecutive()) { // Remove removeCurrentRectangle(); currentPoint = linkedMatrix.getFirstElement(); } else { area = 0; mergeOrRemove(false); } } else { // if (currentPoint != null) lastpoint = currentPoint; currentPoint = currentPoint.getNextDown(); } } else { tryNextRight(); } } /** * Try to reach the point on the east */ private void tryNextRight() { if (currentPoint.isNextElementRightConsecutive()) { lastpoint = currentPoint; currentPoint = currentPoint.getNextRight(); } else { // Compute the potential second area if (stack.size() > 0) { mergeOrRemove(true); } else { lastpoint = currentPoint; currentPoint = linkedMatrix.getFirstElement(); } } } /** * * @param isRight * last move was on the eastern direction */ private void mergeOrRemove(boolean isRight) { if (isRight) { // case where we wanted to go right if (stack.size() == 1 && xToCheck == xTotal) {// First line of empty TemporaryRectangle tempRectangle = stack.peek(); stack.peek() .setWidth( tempRectangle.getCurrentPosition().getY() - tempRectangle.getUpperLeftCorner() .getY() + 1); stack.peek().setHeight(1); stack.peek().setValidated(true); yTotal = stack.peek().getWidth(); yToCheck = yTotal; xToCheck--;// EOL area = stack.peek().getArea(); stack.peek().setPotentialSecondArea(0); if (tempRectangle.getLastLineFirstElement() .isNextElementDownConsecutive()) { stack.peek().setHeight(2); xTotal++; xToCheck++; area = stack.peek().getArea(); stack.peek().setValidated(false); stack.peek().setPotentialSecondArea(-1); currentPoint = tempRectangle.getLastLineFirstElement() .getNextDown(); } else { removeCurrentRectangle(); currentPoint = linkedMatrix.getFirstElement(); } } else if (stack.size() > 1) { // try merge if (xToCheck == xTotal) {// on the first line // update width TemporaryRectangle tempRectangle = stack.peek(); stack.peek().setWidth( tempRectangle.getCurrentPosition().getY() - tempRectangle.getUpperLeftCorner().getY() + 1); // stack.peek().setHeight(1); int oldsize = stack.size(); // Update counters yTotal = stack.peek().getWidth(); yToCheck = yTotal; xToCheck--;// EOL if (xToCheck == 0) { stack.peek().setValidated(true); stack.peek().setPotentialSecondArea(0); } area = stack.peek().getArea(); if (!tryMerge()) { // Merge didn't work go next element if (stack.size() > 0) { if (oldsize != stack.size()) potentialVSvalidated(-1, -1); else goNextElementStack(); } else currentPoint = linkedMatrix.getFirstElement(); } else { // if (oldsize != stack.size()) // potentialVSvalidated(-1, -1); // else goNextElementStack(); } } else { potentialVSvalidated(-1, -1); } } else { potentialVSvalidated(-1, -1); } } else {// case where we wanted to go down - stack point stack.peek().setHeight(1); tryMerge(); lastpoint = currentPoint; currentPoint = currentPoint.getNextRight(); if (currentPoint == null) potentialVSvalidated(-1, -1); } } /** * Merge or remove a depoped rectangle * * @param isRight * last move was in the eastern direction */ private void mergeOrRemoveDepop(boolean isRight) { if (isRight) { // case where we wanted to go right // try merge if (xToCheck == xTotal) {// on the first line // update width TemporaryRectangle tempRectangle = stack.peek(); stack.peek().setWidth( tempRectangle.getCurrentPosition().getY() - tempRectangle.getUpperLeftCorner().getY()); stack.peek().setHeight(1); stack.peek().setValidated(true); stack.peek().setPotentialSecondArea(0); } if (stack.size() > 1) tryMerge(); } else {// case where we wanted to go down - stack point tryMerge(); lastpoint = currentPoint; currentPoint = currentPoint.getNextRight(); if (currentPoint == null) potentialVSvalidated(-1, -1); } } /** * Determine the best cut between the validated part and the potential * rectangle. Heuristic favors the surebet. * * @param validatedArea * @param potentialAreaVertical */ private void potentialVSvalidated(int validatedArea, int potentialAreaVertical) { if (stack.size() == 0) { currentPoint = linkedMatrix.getFirstElement(); return; } // Remove the validated part TemporaryRectangle tempRectangle = stack.peek(); if (tempRectangle.isValidated() && tempRectangle.getPotentialSecondArea() == 0) { removeCurrentRectangle(); if (stack.size() > 0) potentialVSvalidated(-1, -1); return; } // Case where cutpoint is current point if (tempRectangle.getCurrentPosition() == tempRectangle .getUpperLeftCorner()) { if (tempRectangle.getHeight() > 1 && tempRectangle.getWidth() == 1) { if (tempRectangle.getCurrentPosition() .isNextElementDownConsecutive()) { updateCounterToCurrentRectangle(); xToCheck--; tryNextDown(); } else { tempRectangle.setHeight(1); if (!tryMerge()) removeCurrentRectangle(); } } else { updateCounterToCurrentRectangle(); goNextElementStack(); } } else { LinkedMatrixElement cutPoint = tempRectangle.getCurrentPosition(); int height = cutPoint.getX() - tempRectangle.getUpperLeftCorner().getX(); // Case where first element is point if (height == 0 && (xToCheck == xTotal) && stack.size() == 1) { tempRectangle.setWidth(1); tempRectangle.setHeight(1); if (!tryMerge()) removeCurrentRectangle(); } else if (height != 0) { // Delete the rectangle stack.poll(); tempRectangle.setHeight(height); addRectangle(tempRectangle.getUpperLeftCorner(), height, tempRectangle.getWidth()); temp2[tempRectangle.getLastLineFirstElement().getX()][tempRectangle .getLastLineFirstElement().getY()] = tempRectangle .getCurrentPosition().getY() - tempRectangle.getUpperLeftCorner().getY() + 1; lastpoint = currentPoint; LinkedMatrixElement oldcurrent = currentPoint; currentPoint = tempRectangle.getLastLineFirstElement(); stackNewRectangle(); currentPoint = oldcurrent; setCounters(); // Set the end of line xToCheck--; if (stack.size() == 0) { return; } // Want to go to the right mergeOrRemoveDepop(true); } else { if (stack.size() == 0) return; // Change the width of the rectangle stack.peek() .setWidth( tempRectangle.getCurrentPosition().getY() - tempRectangle.getUpperLeftCorner() .getY() + 1); // Update the counters xToCheck = stack.peek().getHeight() - 1; xTotal = stack.peek().getHeight(); yTotal = stack.peek().getWidth(); yToCheck = stack.peek().getWidth(); tempRectangle.setLastLineFirstElement(tempRectangle .getUpperLeftCorner()); tryMerge(); } } if (!foundAndMerge() && stack.size() > 0) { tryNextDown(); } } /** * Try to acces the next point in the South direction */ private void tryNextDown() { if (!stack.peek().getLastLineFirstElement() .isNextElementDownConsecutive()) { // Update rectangle height int newHeight = stack.peek().getLastLineFirstElement().getX() - stack.peek().getUpperLeftCorner().getX() + 1; stack.peek().setHeight(newHeight); stack.peek().setValidated(true); stack.peek().setPotentialSecondArea(0); mergeVertical(); emptyStack(); } else { lastpoint = currentPoint; currentPoint = stack.peek().getLastLineFirstElement().getNextDown(); } } /** * Move to the next element */ private void goNextElementStack() { if (stack.size() > 0) { if (yToCheck == yTotal) { tryNextDown(); } else { tryNextRight(); } } else { currentPoint = linkedMatrix.getFirstElement(); } } /** * * @return <code>true</code> if a new rectangle is stacked */ private boolean stackNewRectangle() { int currentHeight = currentPoint.getX(); int currentWidth = currentPoint.getY(); int height = temp1[currentHeight][currentWidth]; int width = temp2[currentHeight][currentWidth]; LinkedMatrixElement restart; xTotal = height; yTotal = width; area = width * height; // If point remove and go if (area == 1) { stack.add(new TemporaryRectangle(height, width, area, currentPoint, currentPoint, currentPoint)); if (stack.size() > 1) { if (!tryMerge()) emptyStack(); } else { removeCurrentRectangle(); } return false; } else { if (yTotal == 1) {// Point de rédemérrage en fonction de // // largeur>1 ou // non restart = currentPoint.getNextDown(); // xToCheck--; // yToCheck=yTotal; } else { if (currentPoint.isNextElementRightConsecutive()) restart = currentPoint.getNextRight(); else restart = currentPoint; } stack.add(new TemporaryRectangle(height, width, area, currentPoint, currentPoint, restart)); stack.peek().setLastLineFirstElement(currentPoint); } return true; } /** * Return the area for a given point * * @param point * @return */ private int getArea(LinkedMatrixElement point) { int currentHeight = point.getX(); int currentWidth = point.getY(); return (temp1[currentHeight][currentWidth] * temp2[currentHeight][currentWidth]); } /** * Remove rectangle and add to the list * * @param origin * @param height * @param width */ private void addRectangle(LinkedMatrixElement origin, int height, int width) { if (width * height >= MIN_AREA) rectangles.add(new SortableRectangle(origin.getX(), origin.getY(), width, height)); linkedMatrix.removeRectangle(origin, height, width); } /** * * @return <code>true</code> if the vertical merging occured, * <code>false</code> otherwise */ private boolean mergeVertical() { if (stack.isVerticallyMergeable()) { // Two becomes one TemporaryRectangle oldlast = stack.poll(); TemporaryRectangle newLast = stack.peek(); int maxheightOld = oldlast.getUpperLeftCorner().getX() + oldlast.getHeight() - 1; int maxheightNew = newLast.getUpperLeftCorner().getX() + newLast.getHeight() - 1; if (maxheightOld > maxheightNew) {// New greater rectangle newLast.setHeight(maxheightOld - newLast.getUpperLeftCorner().getX() + 1); } stack.peek().setLastLineFirstElement( oldlast.getLastLineFirstElement()); area = newLast.getArea(); // Update counters xTotal = newLast.getHeight(); // Set xTocheck from the position xToCheck = Math.max(maxheightOld, maxheightNew) - oldlast.getLastLineFirstElement().getX(); yTotal = newLast.getWidth(); yToCheck = yTotal; stack.peek().setValidated(false); newLast.setCurrentPosition(oldlast.getCurrentPosition()); int expectedX = newLast.getUpperLeftCorner().getX() + newLast.getHeight() - 1; int expectedY = newLast.getUpperLeftCorner().getY() + newLast.getWidth() - 1; if (xToCheck == 0 || (expectedX == oldlast.getCurrentPosition().getX() && expectedY == oldlast .getCurrentPosition().getY())) { stack.peek().setValidated(true); stack.peek().setPotentialSecondArea(0); if (!newLast.getLastLineFirstElement() .isNextElementDownConsecutive() && !oldlast.getCurrentPosition() .isNextElementRightConsecutive()) { removeCurrentRectangle(); return false; } } return true; } else return false; } /** * * @return <code>true</code> if the horizontal merging occured */ private boolean mergeHorizontal() { if (stack.isHorizontallyMergeable()) { // Two becomes one TemporaryRectangle oldlast = stack.poll(); TemporaryRectangle newLast = stack.peek(); int maxWidthOld = oldlast.getUpperLeftCorner().getY() + oldlast.getWidth() - 1; int maxWidthNew = newLast.getUpperLeftCorner().getY() + newLast.getWidth() - 1; if (maxWidthOld > maxWidthNew) { newLast.setWidth(maxWidthOld - newLast.getUpperLeftCorner().getY() + 1); } newLast.setValidated(false); area = newLast.getArea(); // Update counters if (newLast.getHeight() > 1) { if (oldlast.getCurrentPosition().getX() > newLast .getCurrentPosition().getX()) {// Some // parts // of // the // old // have // not // been // validated newLast.setCurrentPosition(oldlast.getUpperLeftCorner()); } else newLast.setCurrentPosition(oldlast.getCurrentPosition()); } else newLast.setCurrentPosition(oldlast.getCurrentPosition()); updateCounterToCurrentRectangle(); if (yToCheck == 0) { xToCheck--; if (xToCheck == 0) { newLast.setPotentialSecondArea(0); newLast.setValidated(true); // Check if rectangle is to be removed if (!newLast.getLastLineFirstElement() .isNextElementDownConsecutive() && !oldlast.getCurrentPosition() .isNextElementRightConsecutive()) { removeCurrentRectangle(); return false; } } } return true; } return false; } /** * Update the counter after deletion */ private void updateCounterToCurrentRectangle() { TemporaryRectangle current = stack.peek(); yTotal = current.getWidth(); yToCheck = current.getWidth() - (current.getCurrentPosition().getY() - current.getUpperLeftCorner().getY() + 1); xTotal = current.getHeight(); xToCheck = xTotal - (current.getCurrentPosition().getX() - current.getUpperLeftCorner().getX() + 1) + 1; } /** * * @param temp * @return String representation of the matrix */ private String matrixToString(int[][] temp) { // Better output than deepToString StringBuilder s = new StringBuilder(); for (int i = 0; i < temp.length; i++) { s.append(Arrays.toString(temp[i]) + "\n"); } return s.toString(); } /** * Generate a picture of the current state * * @param linkedMatrix * @param rectangles * @param stack * @param currentPoint2 * @param step */ private void generateImage() { // Clean the folder int pixelsize = 1; if (linkedMatrix.getHeight() < 400 && linkedMatrix.getWidth() < 400) { // Compute size of pixels pixelsize = 400 / linkedMatrix.getHeight(); } BufferedImage img = new BufferedImage(pixelsize * linkedMatrix.getWidth(), pixelsize * linkedMatrix.getHeight(), BufferedImage.TYPE_3BYTE_BGR); // Create background matrix setImageBackground(img, linkedMatrix, pixelsize); // Set rectangles in stack and current one setRectangleStack(img, stack, pixelsize); // Set current Point setCurrentPoint(img, currentPoint, pixelsize); // Save image if (!movie) { try { ImageIO.write(img, "jpg", new File("images/image" + step + ".jpg")); } catch (IOException e) { e.printStackTrace(); } } else { listImages.add(img); } } private void cleanfolder() { File folder = new File("images/"); File[] files = folder.listFiles(); if (files != null) { // some JVMs return null for empty dirs for (File f : files) { if (!f.isDirectory()) { f.delete(); } } } } private void setImageBackground(BufferedImage img, LinkedMatrix linkedMatrix, int pixelsize) { for (int i = 0; i < img.getHeight(); i++) { for (int j = 0; j < img.getWidth(); j++) { img.setRGB(j, i, 8421504); } } // Set the matrix values LinkedMatrixElement current = linkedMatrix.getFirstElement(); while (current != null) { if (current.isValue()) setPoint(img, current, pixelsize, 0xA329B); current = current.getNextRight(); } } private void setRectangleStack(BufferedImage img, RectangleDeque stack2, int pixelsize) { TemporaryRectangle rect = stack2.peek(); if (rect != null) { LinkedMatrixElement point = rect.getUpperLeftCorner(); int xstart = point.getX(); int ystart = point.getY(); int color = 0xFFD700; for (int i = 0; i < rect.getHeight(); i++) { for (int j = 0; j < rect.getWidth(); j++) { setPoint(img, xstart + i, ystart + j, pixelsize, color); } } } } private void setCurrentPoint(BufferedImage img, LinkedMatrixElement currentPoint2, int pixelsize) { setPoint(img, currentPoint2, pixelsize, 0xCD1414); } private void setPoint(BufferedImage img, LinkedMatrixElement point, int pixelsize, int color) { int xstart = point.getX() * pixelsize; int ystart = point.getY() * pixelsize; for (int i = 0; i < pixelsize; i++) { for (int j = 0; j < pixelsize; j++) { img.setRGB(ystart + j, xstart + i, color); } } } private void setPoint(BufferedImage img, int x, int y, int pixelsize, int color) { int xstart = x * pixelsize; int ystart = y * pixelsize; for (int i = 0; i < pixelsize; i++) { for (int j = 0; j < pixelsize; j++) { img.setRGB(ystart + j, xstart + i, color); } } } }
apache-2.0
Knux14/PassManager
src/eu/knux/passmanager/helper/EncryptionHelper.java
858
package eu.knux.passmanager.helper; /** * Copyright 2015 Nathan, Knux14, J. * 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 EncryptionHelper { /** * @TODO * Encryption things */ public String encrypt(String password, String text) { return text; } public String decrypt(String password, String text) { return text; } }
apache-2.0
adaptris/interlok
interlok-core/src/main/java/com/adaptris/jdbc/StoredProcedureParameter.java
2112
/* * Copyright 2015 Adaptris 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.adaptris.jdbc; public class StoredProcedureParameter { private String name; private int order; private Object inValue; private Object outValue; private ParameterValueType parameterValueType; private ParameterType parameterType; public StoredProcedureParameter() { } public StoredProcedureParameter(String name, int order, ParameterValueType type, ParameterType parameterType, Object value) { this.setName(name); this.setOrder(order); this.setParameterValueType(type); this.setParameterType(parameterType); this.setInValue(value); } public String getName() { return name; } public void setName(String name) { this.name = name; } public int getOrder() { return order; } public void setOrder(int order) { this.order = order; } public Object getInValue() { return inValue; } public void setInValue(Object value) { this.inValue = value; } public ParameterValueType getParameterValueType() { return parameterValueType; } public void setParameterValueType(ParameterValueType parameterValueType) { this.parameterValueType = parameterValueType; } public ParameterType getParameterType() { return parameterType; } public void setParameterType(ParameterType parameterType) { this.parameterType = parameterType; } public Object getOutValue() { return outValue; } public void setOutValue(Object outValue) { this.outValue = outValue; } }
apache-2.0
trajano/maven
maven-core/src/main/java/org/apache/maven/execution/DefaultMavenExecutionRequest.java
30788
package org.apache.maven.execution; /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ import java.io.File; import java.util.ArrayList; import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Properties; import org.apache.commons.lang3.Validate; import org.apache.maven.artifact.repository.ArtifactRepository; import org.apache.maven.eventspy.internal.EventSpyDispatcher; import org.apache.maven.model.Profile; import org.apache.maven.project.DefaultProjectBuildingRequest; import org.apache.maven.project.ProjectBuildingRequest; import org.apache.maven.properties.internal.SystemProperties; import org.apache.maven.settings.Mirror; import org.apache.maven.settings.Proxy; import org.apache.maven.settings.Server; import org.apache.maven.toolchain.model.ToolchainModel; import org.eclipse.aether.DefaultRepositoryCache; import org.eclipse.aether.RepositoryCache; import org.eclipse.aether.repository.WorkspaceReader; import org.eclipse.aether.transfer.TransferListener; import com.google.common.collect.Maps; /** * @author Jason van Zyl */ public class DefaultMavenExecutionRequest implements MavenExecutionRequest { private RepositoryCache repositoryCache = new DefaultRepositoryCache(); private WorkspaceReader workspaceReader; private ArtifactRepository localRepository; private EventSpyDispatcher eventSpyDispatcher; private File localRepositoryPath; private boolean offline = false; private boolean interactiveMode = true; private boolean cacheTransferError; private boolean cacheNotFound; private List<Proxy> proxies; private List<Server> servers; private List<Mirror> mirrors; private List<Profile> profiles; private List<String> pluginGroups; private boolean isProjectPresent = true; // ---------------------------------------------------------------------------- // We need to allow per execution user and global settings as the embedder // might be running in a mode where its executing many threads with totally // different settings. // ---------------------------------------------------------------------------- private File userSettingsFile; private File globalSettingsFile; private File userToolchainsFile; private File globalToolchainsFile; // ---------------------------------------------------------------------------- // Request // ---------------------------------------------------------------------------- private File multiModuleProjectDirectory; private File basedir; private List<String> goals; private boolean useReactor = false; private boolean recursive = true; private File pom; private String reactorFailureBehavior = REACTOR_FAIL_FAST; private List<String> selectedProjects; private List<String> excludedProjects; private String resumeFrom; private String makeBehavior; private Properties systemProperties; private Properties userProperties; private Date startTime; private boolean showErrors = false; private List<String> activeProfiles; private List<String> inactiveProfiles; private TransferListener transferListener; private int loggingLevel = LOGGING_LEVEL_INFO; private String globalChecksumPolicy; private boolean updateSnapshots = false; private List<ArtifactRepository> remoteRepositories; private List<ArtifactRepository> pluginArtifactRepositories; private ExecutionListener executionListener; private int degreeOfConcurrency = 1; private String builderId = "singlethreaded"; private Map<String, List<ToolchainModel>> toolchains; /** * Suppress SNAPSHOT updates. * * @issue MNG-2681 */ private boolean noSnapshotUpdates; private boolean useLegacyLocalRepositoryManager = false; private Map<String, Object> data; public DefaultMavenExecutionRequest() { } public static MavenExecutionRequest copy( MavenExecutionRequest original ) { DefaultMavenExecutionRequest copy = new DefaultMavenExecutionRequest(); copy.setLocalRepository( original.getLocalRepository() ); copy.setLocalRepositoryPath( original.getLocalRepositoryPath() ); copy.setOffline( original.isOffline() ); copy.setInteractiveMode( original.isInteractiveMode() ); copy.setCacheNotFound( original.isCacheNotFound() ); copy.setCacheTransferError( original.isCacheTransferError() ); copy.setProxies( original.getProxies() ); copy.setServers( original.getServers() ); copy.setMirrors( original.getMirrors() ); copy.setProfiles( original.getProfiles() ); copy.setPluginGroups( original.getPluginGroups() ); copy.setProjectPresent( original.isProjectPresent() ); copy.setUserSettingsFile( original.getUserSettingsFile() ); copy.setGlobalSettingsFile( original.getGlobalSettingsFile() ); copy.setUserToolchainsFile( original.getUserToolchainsFile() ); copy.setGlobalToolchainsFile( original.getGlobalToolchainsFile() ); copy.setBaseDirectory( ( original.getBaseDirectory() != null ) ? new File( original.getBaseDirectory() ) : null ); copy.setGoals( original.getGoals() ); copy.setRecursive( original.isRecursive() ); copy.setPom( original.getPom() ); copy.setSystemProperties( original.getSystemProperties() ); copy.setUserProperties( original.getUserProperties() ); copy.setShowErrors( original.isShowErrors() ); copy.setActiveProfiles( original.getActiveProfiles() ); copy.setInactiveProfiles( original.getInactiveProfiles() ); copy.setTransferListener( original.getTransferListener() ); copy.setLoggingLevel( original.getLoggingLevel() ); copy.setGlobalChecksumPolicy( original.getGlobalChecksumPolicy() ); copy.setUpdateSnapshots( original.isUpdateSnapshots() ); copy.setRemoteRepositories( original.getRemoteRepositories() ); copy.setPluginArtifactRepositories( original.getPluginArtifactRepositories() ); copy.setRepositoryCache( original.getRepositoryCache() ); copy.setWorkspaceReader( original.getWorkspaceReader() ); copy.setNoSnapshotUpdates( original.isNoSnapshotUpdates() ); copy.setExecutionListener( original.getExecutionListener() ); copy.setUseLegacyLocalRepository( original.isUseLegacyLocalRepository() ); copy.setBuilderId( original.getBuilderId() ); return copy; } @Override public String getBaseDirectory() { if ( basedir == null ) { return null; } return basedir.getAbsolutePath(); } @Override public ArtifactRepository getLocalRepository() { return localRepository; } @Override public File getLocalRepositoryPath() { return localRepositoryPath; } @Override public List<String> getGoals() { if ( goals == null ) { goals = new ArrayList<>(); } return goals; } @Override public Properties getSystemProperties() { if ( systemProperties == null ) { systemProperties = new Properties(); } return systemProperties; } @Override public Properties getUserProperties() { if ( userProperties == null ) { userProperties = new Properties(); } return userProperties; } @Override public File getPom() { return pom; } @Override public String getReactorFailureBehavior() { return reactorFailureBehavior; } @Override public List<String> getSelectedProjects() { if ( selectedProjects == null ) { selectedProjects = new ArrayList<>(); } return selectedProjects; } @Override public List<String> getExcludedProjects() { if ( excludedProjects == null ) { excludedProjects = new ArrayList<>(); } return excludedProjects; } @Override public String getResumeFrom() { return resumeFrom; } @Override public String getMakeBehavior() { return makeBehavior; } @Override public Date getStartTime() { return startTime; } @Override public boolean isShowErrors() { return showErrors; } @Override public boolean isInteractiveMode() { return interactiveMode; } @Override public MavenExecutionRequest setActiveProfiles( List<String> activeProfiles ) { if ( activeProfiles != null ) { this.activeProfiles = new ArrayList<>( activeProfiles ); } else { this.activeProfiles = null; } return this; } @Override public MavenExecutionRequest setInactiveProfiles( List<String> inactiveProfiles ) { if ( inactiveProfiles != null ) { this.inactiveProfiles = new ArrayList<>( inactiveProfiles ); } else { this.inactiveProfiles = null; } return this; } @Override public MavenExecutionRequest setRemoteRepositories( List<ArtifactRepository> remoteRepositories ) { if ( remoteRepositories != null ) { this.remoteRepositories = new ArrayList<>( remoteRepositories ); } else { this.remoteRepositories = null; } return this; } @Override public MavenExecutionRequest setPluginArtifactRepositories( List<ArtifactRepository> pluginArtifactRepositories ) { if ( pluginArtifactRepositories != null ) { this.pluginArtifactRepositories = new ArrayList<>( pluginArtifactRepositories ); } else { this.pluginArtifactRepositories = null; } return this; } public void setProjectBuildingConfiguration( ProjectBuildingRequest projectBuildingConfiguration ) { this.projectBuildingRequest = projectBuildingConfiguration; } @Override public List<String> getActiveProfiles() { if ( activeProfiles == null ) { activeProfiles = new ArrayList<>(); } return activeProfiles; } @Override public List<String> getInactiveProfiles() { if ( inactiveProfiles == null ) { inactiveProfiles = new ArrayList<>(); } return inactiveProfiles; } @Override public TransferListener getTransferListener() { return transferListener; } @Override public int getLoggingLevel() { return loggingLevel; } @Override public boolean isOffline() { return offline; } @Override public boolean isUpdateSnapshots() { return updateSnapshots; } @Override public boolean isNoSnapshotUpdates() { return noSnapshotUpdates; } @Override public String getGlobalChecksumPolicy() { return globalChecksumPolicy; } @Override public boolean isRecursive() { return recursive; } // ---------------------------------------------------------------------- // // ---------------------------------------------------------------------- @Override public MavenExecutionRequest setBaseDirectory( File basedir ) { this.basedir = basedir; return this; } @Override public MavenExecutionRequest setStartTime( Date startTime ) { this.startTime = startTime; return this; } @Override public MavenExecutionRequest setShowErrors( boolean showErrors ) { this.showErrors = showErrors; return this; } @Override public MavenExecutionRequest setGoals( List<String> goals ) { if ( goals != null ) { this.goals = new ArrayList<>( goals ); } else { this.goals = null; } return this; } @Override public MavenExecutionRequest setLocalRepository( ArtifactRepository localRepository ) { this.localRepository = localRepository; if ( localRepository != null ) { setLocalRepositoryPath( new File( localRepository.getBasedir() ).getAbsoluteFile() ); } return this; } @Override public MavenExecutionRequest setLocalRepositoryPath( File localRepository ) { localRepositoryPath = localRepository; return this; } @Override public MavenExecutionRequest setLocalRepositoryPath( String localRepository ) { localRepositoryPath = ( localRepository != null ) ? new File( localRepository ) : null; return this; } @Override public MavenExecutionRequest setSystemProperties( Properties properties ) { if ( properties != null ) { this.systemProperties = SystemProperties.copyProperties( properties ); } else { this.systemProperties = null; } return this; } @Override public MavenExecutionRequest setUserProperties( Properties userProperties ) { if ( userProperties != null ) { this.userProperties = new Properties(); this.userProperties.putAll( userProperties ); } else { this.userProperties = null; } return this; } @Override public MavenExecutionRequest setReactorFailureBehavior( String failureBehavior ) { reactorFailureBehavior = failureBehavior; return this; } @Override public MavenExecutionRequest setSelectedProjects( List<String> selectedProjects ) { if ( selectedProjects != null ) { this.selectedProjects = new ArrayList<>( selectedProjects ); } else { this.selectedProjects = null; } return this; } @Override public MavenExecutionRequest setExcludedProjects( List<String> excludedProjects ) { if ( excludedProjects != null ) { this.excludedProjects = new ArrayList<>( excludedProjects ); } else { this.excludedProjects = null; } return this; } @Override public MavenExecutionRequest setResumeFrom( String project ) { this.resumeFrom = project; return this; } @Override public MavenExecutionRequest setMakeBehavior( String makeBehavior ) { this.makeBehavior = makeBehavior; return this; } @Override public MavenExecutionRequest addActiveProfile( String profile ) { if ( !getActiveProfiles().contains( profile ) ) { getActiveProfiles().add( profile ); } return this; } @Override public MavenExecutionRequest addInactiveProfile( String profile ) { if ( !getInactiveProfiles().contains( profile ) ) { getInactiveProfiles().add( profile ); } return this; } @Override public MavenExecutionRequest addActiveProfiles( List<String> profiles ) { for ( String profile : profiles ) { addActiveProfile( profile ); } return this; } @Override public MavenExecutionRequest addInactiveProfiles( List<String> profiles ) { for ( String profile : profiles ) { addInactiveProfile( profile ); } return this; } public MavenExecutionRequest setUseReactor( boolean reactorActive ) { useReactor = reactorActive; return this; } public boolean useReactor() { return useReactor; } /** @deprecated use {@link #setPom(File)} */ @Deprecated public MavenExecutionRequest setPomFile( String pomFilename ) { if ( pomFilename != null ) { pom = new File( pomFilename ); } return this; } @Override public MavenExecutionRequest setPom( File pom ) { this.pom = pom; return this; } @Override public MavenExecutionRequest setInteractiveMode( boolean interactive ) { interactiveMode = interactive; return this; } @Override public MavenExecutionRequest setTransferListener( TransferListener transferListener ) { this.transferListener = transferListener; return this; } @Override public MavenExecutionRequest setLoggingLevel( int loggingLevel ) { this.loggingLevel = loggingLevel; return this; } @Override public MavenExecutionRequest setOffline( boolean offline ) { this.offline = offline; return this; } @Override public MavenExecutionRequest setUpdateSnapshots( boolean updateSnapshots ) { this.updateSnapshots = updateSnapshots; return this; } @Override public MavenExecutionRequest setNoSnapshotUpdates( boolean noSnapshotUpdates ) { this.noSnapshotUpdates = noSnapshotUpdates; return this; } @Override public MavenExecutionRequest setGlobalChecksumPolicy( String globalChecksumPolicy ) { this.globalChecksumPolicy = globalChecksumPolicy; return this; } // ---------------------------------------------------------------------------- // Settings equivalents // ---------------------------------------------------------------------------- @Override public List<Proxy> getProxies() { if ( proxies == null ) { proxies = new ArrayList<>(); } return proxies; } @Override public MavenExecutionRequest setProxies( List<Proxy> proxies ) { if ( proxies != null ) { this.proxies = new ArrayList<>( proxies ); } else { this.proxies = null; } return this; } @Override public MavenExecutionRequest addProxy( Proxy proxy ) { Validate.notNull( proxy, "proxy cannot be null" ); for ( Proxy p : getProxies() ) { if ( p.getId() != null && p.getId().equals( proxy.getId() ) ) { return this; } } getProxies().add( proxy ); return this; } @Override public List<Server> getServers() { if ( servers == null ) { servers = new ArrayList<>(); } return servers; } @Override public MavenExecutionRequest setServers( List<Server> servers ) { if ( servers != null ) { this.servers = new ArrayList<>( servers ); } else { this.servers = null; } return this; } @Override public MavenExecutionRequest addServer( Server server ) { Validate.notNull( server, "server cannot be null" ); for ( Server p : getServers() ) { if ( p.getId() != null && p.getId().equals( server.getId() ) ) { return this; } } getServers().add( server ); return this; } @Override public List<Mirror> getMirrors() { if ( mirrors == null ) { mirrors = new ArrayList<>(); } return mirrors; } @Override public MavenExecutionRequest setMirrors( List<Mirror> mirrors ) { if ( mirrors != null ) { this.mirrors = new ArrayList<>( mirrors ); } else { this.mirrors = null; } return this; } @Override public MavenExecutionRequest addMirror( Mirror mirror ) { Validate.notNull( mirror, "mirror cannot be null" ); for ( Mirror p : getMirrors() ) { if ( p.getId() != null && p.getId().equals( mirror.getId() ) ) { return this; } } getMirrors().add( mirror ); return this; } @Override public List<Profile> getProfiles() { if ( profiles == null ) { profiles = new ArrayList<>(); } return profiles; } @Override public MavenExecutionRequest setProfiles( List<Profile> profiles ) { if ( profiles != null ) { this.profiles = new ArrayList<>( profiles ); } else { this.profiles = null; } return this; } @Override public List<String> getPluginGroups() { if ( pluginGroups == null ) { pluginGroups = new ArrayList<>(); } return pluginGroups; } @Override public MavenExecutionRequest setPluginGroups( List<String> pluginGroups ) { if ( pluginGroups != null ) { this.pluginGroups = new ArrayList<>( pluginGroups ); } else { this.pluginGroups = null; } return this; } @Override public MavenExecutionRequest addPluginGroup( String pluginGroup ) { if ( !getPluginGroups().contains( pluginGroup ) ) { getPluginGroups().add( pluginGroup ); } return this; } @Override public MavenExecutionRequest addPluginGroups( List<String> pluginGroups ) { for ( String pluginGroup : pluginGroups ) { addPluginGroup( pluginGroup ); } return this; } @Override public MavenExecutionRequest setRecursive( boolean recursive ) { this.recursive = recursive; return this; } // calculated from request attributes. private ProjectBuildingRequest projectBuildingRequest; @Override public boolean isProjectPresent() { return isProjectPresent; } @Override public MavenExecutionRequest setProjectPresent( boolean projectPresent ) { isProjectPresent = projectPresent; return this; } // Settings files @Override public File getUserSettingsFile() { return userSettingsFile; } @Override public MavenExecutionRequest setUserSettingsFile( File userSettingsFile ) { this.userSettingsFile = userSettingsFile; return this; } @Override public File getGlobalSettingsFile() { return globalSettingsFile; } @Override public MavenExecutionRequest setGlobalSettingsFile( File globalSettingsFile ) { this.globalSettingsFile = globalSettingsFile; return this; } @Override public File getUserToolchainsFile() { return userToolchainsFile; } @Override public MavenExecutionRequest setUserToolchainsFile( File userToolchainsFile ) { this.userToolchainsFile = userToolchainsFile; return this; } @Override public File getGlobalToolchainsFile() { return globalToolchainsFile; } @Override public MavenExecutionRequest setGlobalToolchainsFile( File globalToolchainsFile ) { this.globalToolchainsFile = globalToolchainsFile; return this; } @Override public MavenExecutionRequest addRemoteRepository( ArtifactRepository repository ) { for ( ArtifactRepository repo : getRemoteRepositories() ) { if ( repo.getId() != null && repo.getId().equals( repository.getId() ) ) { return this; } } getRemoteRepositories().add( repository ); return this; } @Override public List<ArtifactRepository> getRemoteRepositories() { if ( remoteRepositories == null ) { remoteRepositories = new ArrayList<>(); } return remoteRepositories; } @Override public MavenExecutionRequest addPluginArtifactRepository( ArtifactRepository repository ) { for ( ArtifactRepository repo : getPluginArtifactRepositories() ) { if ( repo.getId() != null && repo.getId().equals( repository.getId() ) ) { return this; } } getPluginArtifactRepositories().add( repository ); return this; } @Override public List<ArtifactRepository> getPluginArtifactRepositories() { if ( pluginArtifactRepositories == null ) { pluginArtifactRepositories = new ArrayList<>(); } return pluginArtifactRepositories; } // TODO: this does not belong here. @Override public ProjectBuildingRequest getProjectBuildingRequest() { if ( projectBuildingRequest == null ) { projectBuildingRequest = new DefaultProjectBuildingRequest(); projectBuildingRequest.setLocalRepository( getLocalRepository() ); projectBuildingRequest.setSystemProperties( getSystemProperties() ); projectBuildingRequest.setUserProperties( getUserProperties() ); projectBuildingRequest.setRemoteRepositories( getRemoteRepositories() ); projectBuildingRequest.setPluginArtifactRepositories( getPluginArtifactRepositories() ); projectBuildingRequest.setActiveProfileIds( getActiveProfiles() ); projectBuildingRequest.setInactiveProfileIds( getInactiveProfiles() ); projectBuildingRequest.setProfiles( getProfiles() ); projectBuildingRequest.setProcessPlugins( true ); projectBuildingRequest.setBuildStartTime( getStartTime() ); } return projectBuildingRequest; } @Override public MavenExecutionRequest addProfile( Profile profile ) { Validate.notNull( profile, "profile cannot be null" ); for ( Profile p : getProfiles() ) { if ( p.getId() != null && p.getId().equals( profile.getId() ) ) { return this; } } getProfiles().add( profile ); return this; } @Override public RepositoryCache getRepositoryCache() { return repositoryCache; } @Override public MavenExecutionRequest setRepositoryCache( RepositoryCache repositoryCache ) { this.repositoryCache = repositoryCache; return this; } @Override public ExecutionListener getExecutionListener() { return executionListener; } @Override public MavenExecutionRequest setExecutionListener( ExecutionListener executionListener ) { this.executionListener = executionListener; return this; } @Override public void setDegreeOfConcurrency( final int degreeOfConcurrency ) { this.degreeOfConcurrency = degreeOfConcurrency; } @Override public int getDegreeOfConcurrency() { return degreeOfConcurrency; } @Override public WorkspaceReader getWorkspaceReader() { return workspaceReader; } @Override public MavenExecutionRequest setWorkspaceReader( WorkspaceReader workspaceReader ) { this.workspaceReader = workspaceReader; return this; } @Override public boolean isCacheTransferError() { return cacheTransferError; } @Override public MavenExecutionRequest setCacheTransferError( boolean cacheTransferError ) { this.cacheTransferError = cacheTransferError; return this; } @Override public boolean isCacheNotFound() { return cacheNotFound; } @Override public MavenExecutionRequest setCacheNotFound( boolean cacheNotFound ) { this.cacheNotFound = cacheNotFound; return this; } @Override public boolean isUseLegacyLocalRepository() { return this.useLegacyLocalRepositoryManager; } @Override public MavenExecutionRequest setUseLegacyLocalRepository( boolean useLegacyLocalRepositoryManager ) { this.useLegacyLocalRepositoryManager = useLegacyLocalRepositoryManager; return this; } @Override public MavenExecutionRequest setBuilderId( String builderId ) { this.builderId = builderId; return this; } @Override public String getBuilderId() { return builderId; } @Override public Map<String, List<ToolchainModel>> getToolchains() { if ( toolchains == null ) { toolchains = new HashMap<>(); } return toolchains; } @Override public MavenExecutionRequest setToolchains( Map<String, List<ToolchainModel>> toolchains ) { this.toolchains = toolchains; return this; } @Override public void setMultiModuleProjectDirectory( File directory ) { this.multiModuleProjectDirectory = directory; } @Override public File getMultiModuleProjectDirectory() { return multiModuleProjectDirectory; } @Override public MavenExecutionRequest setEventSpyDispatcher( EventSpyDispatcher eventSpyDispatcher ) { this.eventSpyDispatcher = eventSpyDispatcher; return this; } @Override public EventSpyDispatcher getEventSpyDispatcher() { return eventSpyDispatcher; } @Override public Map<String, Object> getData() { if ( data == null ) { data = Maps.newHashMap(); } return data; } }
apache-2.0
davidmoten/rxjava2-jdbc
rxjava2-jdbc/src/main/java/org/davidmoten/rx/jdbc/internal/DelegatedConnection.java
7611
package org.davidmoten.rx.jdbc.internal; import java.sql.Array; import java.sql.Blob; import java.sql.CallableStatement; import java.sql.Clob; import java.sql.Connection; import java.sql.DatabaseMetaData; import java.sql.NClob; import java.sql.PreparedStatement; import java.sql.SQLClientInfoException; import java.sql.SQLException; import java.sql.SQLWarning; import java.sql.SQLXML; import java.sql.Savepoint; import java.sql.Statement; import java.sql.Struct; import java.util.Map; import java.util.Properties; import java.util.concurrent.Executor; public interface DelegatedConnection extends Connection { Connection con(); default <T> T unwrap(Class<T> iface) throws SQLException { return con().unwrap(iface); } default boolean isWrapperFor(Class<?> iface) throws SQLException { return con().isWrapperFor(iface); } default Statement createStatement() throws SQLException { return con().createStatement(); } default PreparedStatement prepareStatement(String sql) throws SQLException { return con().prepareStatement(sql); } default CallableStatement prepareCall(String sql) throws SQLException { return con().prepareCall(sql); } default String nativeSQL(String sql) throws SQLException { return con().nativeSQL(sql); } default void setAutoCommit(boolean autoCommit) throws SQLException { con().setAutoCommit(autoCommit); } default boolean getAutoCommit() throws SQLException { return con().getAutoCommit(); } default void commit() throws SQLException { con().commit(); } default void rollback() throws SQLException { con().rollback(); } default void close() throws SQLException { con().close(); } default boolean isClosed() throws SQLException { return con().isClosed(); } default DatabaseMetaData getMetaData() throws SQLException { return con().getMetaData(); } default void setReadOnly(boolean readOnly) throws SQLException { con().setReadOnly(readOnly); } default boolean isReadOnly() throws SQLException { return con().isReadOnly(); } default void setCatalog(String catalog) throws SQLException { con().setCatalog(catalog); } default String getCatalog() throws SQLException { return con().getCatalog(); } default void setTransactionIsolation(int level) throws SQLException { con().setTransactionIsolation(level); } default int getTransactionIsolation() throws SQLException { return con().getTransactionIsolation(); } default SQLWarning getWarnings() throws SQLException { return con().getWarnings(); } default void clearWarnings() throws SQLException { con().clearWarnings(); } default Statement createStatement(int resultSetType, int resultSetConcurrency) throws SQLException { return con().createStatement(resultSetType, resultSetConcurrency); } default PreparedStatement prepareStatement(String sql, int resultSetType, int resultSetConcurrency) throws SQLException { return con().prepareStatement(sql, resultSetType, resultSetConcurrency); } default CallableStatement prepareCall(String sql, int resultSetType, int resultSetConcurrency) throws SQLException { return con().prepareCall(sql, resultSetType, resultSetConcurrency); } default Map<String, Class<?>> getTypeMap() throws SQLException { return con().getTypeMap(); } default void setTypeMap(Map<String, Class<?>> map) throws SQLException { con().setTypeMap(map); } default void setHoldability(int holdability) throws SQLException { con().setHoldability(holdability); } default int getHoldability() throws SQLException { return con().getHoldability(); } default Savepoint setSavepoint() throws SQLException { return con().setSavepoint(); } default Savepoint setSavepoint(String name) throws SQLException { return con().setSavepoint(name); } default void rollback(Savepoint savepoint) throws SQLException { con().rollback(savepoint); } default void releaseSavepoint(Savepoint savepoint) throws SQLException { con().releaseSavepoint(savepoint); } default Statement createStatement(int resultSetType, int resultSetConcurrency, int resultSetHoldability) throws SQLException { return con().createStatement(resultSetType, resultSetConcurrency, resultSetHoldability); } default PreparedStatement prepareStatement(String sql, int resultSetType, int resultSetConcurrency, int resultSetHoldability) throws SQLException { return con().prepareStatement(sql, resultSetType, resultSetConcurrency, resultSetHoldability); } default CallableStatement prepareCall(String sql, int resultSetType, int resultSetConcurrency, int resultSetHoldability) throws SQLException { return con().prepareCall(sql, resultSetType, resultSetConcurrency, resultSetHoldability); } default PreparedStatement prepareStatement(String sql, int autoGeneratedKeys) throws SQLException { return con().prepareStatement(sql, autoGeneratedKeys); } default PreparedStatement prepareStatement(String sql, int[] columnIndexes) throws SQLException { return con().prepareStatement(sql, columnIndexes); } default PreparedStatement prepareStatement(String sql, String[] columnNames) throws SQLException { return con().prepareStatement(sql, columnNames); } default Clob createClob() throws SQLException { return con().createClob(); } default Blob createBlob() throws SQLException { return con().createBlob(); } default NClob createNClob() throws SQLException { return con().createNClob(); } default SQLXML createSQLXML() throws SQLException { return con().createSQLXML(); } default boolean isValid(int timeout) throws SQLException { return con().isValid(timeout); } default void setClientInfo(String name, String value) throws SQLClientInfoException { con().setClientInfo(name, value); } default void setClientInfo(Properties properties) throws SQLClientInfoException { con().setClientInfo(properties); } default String getClientInfo(String name) throws SQLException { return con().getClientInfo(name); } default Properties getClientInfo() throws SQLException { return con().getClientInfo(); } default Array createArrayOf(String typeName, Object[] elements) throws SQLException { return con().createArrayOf(typeName, elements); } default Struct createStruct(String typeName, Object[] attributes) throws SQLException { return con().createStruct(typeName, attributes); } default void setSchema(String schema) throws SQLException { con().setSchema(schema); } default String getSchema() throws SQLException { return con().getSchema(); } default void abort(Executor executor) throws SQLException { con().abort(executor); } default void setNetworkTimeout(Executor executor, int milliseconds) throws SQLException { con().setNetworkTimeout(executor, milliseconds); } default int getNetworkTimeout() throws SQLException { return con().getNetworkTimeout(); } }
apache-2.0
joewalnes/idea-community
plugins/tasks/jira-connector/src/atlassian/java/com/atlassian/theplugin/jira/api/JIRAActionFieldBean.java
1281
/** * Copyright (C) 2008 Atlassian * * 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.atlassian.theplugin.jira.api; public class JIRAActionFieldBean extends AbstractJIRAConstantBean implements JIRAActionField { private String fieldId; public JIRAActionFieldBean(String fieldId, String name) { super(fieldId.hashCode(), name, null); this.fieldId = fieldId; } public JIRAActionFieldBean(JIRAActionFieldBean other) { this(other.fieldId, other.name); } public String getQueryStringFragment() { // todo: I am almost absolutely sure this is wrong. Once we get // to actually handling action fields, this will have to be fixed return fieldId + "="; } public JIRAActionFieldBean getClone() { return new JIRAActionFieldBean(this); } }
apache-2.0
KernelHaven/FeatureEffectAnalysis
src/net/ssehub/kernel_haven/fe_analysis/fes/ThreadedFeatureEffectFinder.java
3319
/* * Copyright 2017-2019 University of Hildesheim, Software Systems Engineering * * 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 net.ssehub.kernel_haven.fe_analysis.fes; import static net.ssehub.kernel_haven.util.null_checks.NullHelpers.notNull; import net.ssehub.kernel_haven.SetUpException; import net.ssehub.kernel_haven.analysis.AnalysisComponent; import net.ssehub.kernel_haven.config.Configuration; import net.ssehub.kernel_haven.config.Setting; import net.ssehub.kernel_haven.config.Setting.Type; import net.ssehub.kernel_haven.fe_analysis.pcs.PcFinder.VariableWithPcs; import net.ssehub.kernel_haven.util.OrderPreservingParallelizer; import net.ssehub.kernel_haven.util.ProgressLogger; import net.ssehub.kernel_haven.util.null_checks.NonNull; /** * A {@link FeatureEffectFinder} that utilizes multiple threads. This helps with performance if simplification takes * long. * * @author Adam */ public class ThreadedFeatureEffectFinder extends FeatureEffectFinder { public static final @NonNull Setting<@NonNull Integer> THREAD_SETTING = new Setting<>( "analysis.fe_finder.threads", Type.INTEGER, true, "4", "Defines the number of threads the " + ThreadedFeatureEffectFinder.class.getSimpleName() + " should use."); private int numThreads; /** * Creates a new {@link ThreadedFeatureEffectFinder} for the given PC finder. * * @param config The global configuration. * @param pcFinder The component to get the PCs from. * * @throws SetUpException If creating this component fails. */ public ThreadedFeatureEffectFinder(@NonNull Configuration config, @NonNull AnalysisComponent<VariableWithPcs> pcFinder) throws SetUpException { super(config, pcFinder); config.registerSetting(THREAD_SETTING); numThreads = config.getValue(THREAD_SETTING); if (numThreads < 1) { throw new SetUpException("Number of threads can't be " + numThreads); } } @Override protected void execute() { ProgressLogger progress = new ProgressLogger(notNull(getClass().getSimpleName())); OrderPreservingParallelizer<VariableWithPcs, VariableWithFeatureEffect> parallelizer = new OrderPreservingParallelizer<>(this::processSingle, (result) -> { if (result != null) { addResult(result); } progress.processedOne(); }, numThreads); VariableWithPcs pcs; while ((pcs = pcFinder.getNextResult()) != null) { parallelizer.add(pcs); } parallelizer.end(); parallelizer.join(); progress.close(); } }
apache-2.0
iemejia/incubator-beam
runners/flink/src/test/java/org/apache/beam/runners/flink/FlinkSavepointTest.java
16347
/* * 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.beam.runners.flink; import static org.hamcrest.MatcherAssert.assertThat; import java.io.Serializable; import java.lang.reflect.Method; import java.net.URI; import java.util.Collections; import java.util.Objects; import java.util.concurrent.CompletableFuture; import java.util.concurrent.CountDownLatch; import java.util.concurrent.ExecutionException; import java.util.concurrent.Executors; import java.util.concurrent.TimeUnit; import org.apache.beam.model.pipeline.v1.RunnerApi; import org.apache.beam.runners.core.construction.Environments; import org.apache.beam.runners.core.construction.PipelineTranslation; import org.apache.beam.runners.jobsubmission.JobInvocation; import org.apache.beam.sdk.Pipeline; import org.apache.beam.sdk.io.GenerateSequence; import org.apache.beam.sdk.options.PipelineOptionsFactory; import org.apache.beam.sdk.options.PortablePipelineOptions; import org.apache.beam.sdk.state.BagState; import org.apache.beam.sdk.state.StateSpec; import org.apache.beam.sdk.state.StateSpecs; import org.apache.beam.sdk.state.TimeDomain; import org.apache.beam.sdk.state.Timer; import org.apache.beam.sdk.state.TimerSpec; import org.apache.beam.sdk.state.TimerSpecs; import org.apache.beam.sdk.state.ValueState; import org.apache.beam.sdk.transforms.DoFn; import org.apache.beam.sdk.transforms.Impulse; import org.apache.beam.sdk.transforms.InferableFunction; import org.apache.beam.sdk.transforms.MapElements; import org.apache.beam.sdk.transforms.ParDo; import org.apache.beam.sdk.values.KV; import org.apache.beam.sdk.values.PCollection; import org.apache.beam.vendor.guava.v26_0_jre.com.google.common.collect.Iterables; import org.apache.beam.vendor.guava.v26_0_jre.com.google.common.util.concurrent.ListeningExecutorService; import org.apache.beam.vendor.guava.v26_0_jre.com.google.common.util.concurrent.MoreExecutors; import org.apache.flink.api.common.JobID; import org.apache.flink.configuration.CheckpointingOptions; import org.apache.flink.configuration.Configuration; import org.apache.flink.configuration.RestOptions; import org.apache.flink.runtime.client.JobStatusMessage; import org.apache.flink.runtime.jobgraph.JobGraph; import org.apache.flink.runtime.jobgraph.SavepointRestoreSettings; import org.apache.flink.runtime.minicluster.MiniCluster; import org.apache.flink.runtime.minicluster.MiniClusterConfiguration; import org.hamcrest.Matchers; import org.hamcrest.core.IsIterableContaining; import org.joda.time.Instant; import org.junit.After; import org.junit.AfterClass; import org.junit.BeforeClass; import org.junit.ClassRule; import org.junit.Rule; import org.junit.Test; import org.junit.rules.TemporaryFolder; import org.junit.rules.Timeout; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * Tests that Flink's Savepoints work with the Flink Runner. This includes taking a savepoint of a * running pipeline, shutting down the pipeline, and restarting the pipeline from the savepoint with * a different parallelism. */ public class FlinkSavepointTest implements Serializable { private static final Logger LOG = LoggerFactory.getLogger(FlinkSavepointTest.class); /** Flink cluster that runs over the lifespan of the tests. */ private static transient MiniCluster flinkCluster; /** Static for synchronization between the pipeline state and the test. */ private static volatile CountDownLatch oneShotLatch; /** Temporary folder for savepoints. */ @ClassRule public static transient TemporaryFolder tempFolder = new TemporaryFolder(); /** Each test has a timeout of 60 seconds (for safety). */ @Rule public Timeout timeout = new Timeout(60, TimeUnit.SECONDS); @BeforeClass public static void beforeClass() throws Exception { Configuration config = new Configuration(); // Avoid port collision in parallel tests config.setInteger(RestOptions.PORT, 0); config.setString(CheckpointingOptions.STATE_BACKEND, "filesystem"); String savepointPath = "file://" + tempFolder.getRoot().getAbsolutePath(); LOG.info("Savepoints will be written to {}", savepointPath); // It is necessary to configure the checkpoint directory for the state backend, // even though we only create savepoints in this test. config.setString(CheckpointingOptions.CHECKPOINTS_DIRECTORY, savepointPath); // Checkpoints will go into a subdirectory of this directory config.setString(CheckpointingOptions.SAVEPOINT_DIRECTORY, savepointPath); MiniClusterConfiguration clusterConfig = new MiniClusterConfiguration.Builder() .setConfiguration(config) .setNumTaskManagers(2) .setNumSlotsPerTaskManager(2) .build(); flinkCluster = new MiniCluster(clusterConfig); flinkCluster.start(); } @AfterClass public static void afterClass() throws Exception { flinkCluster.close(); flinkCluster = null; } @After public void afterTest() throws Exception { for (JobStatusMessage jobStatusMessage : flinkCluster.listJobs().get()) { if (jobStatusMessage.getJobState().name().equals("RUNNING")) { flinkCluster.cancelJob(jobStatusMessage.getJobId()).get(); } } while (!flinkCluster.listJobs().get().stream() .allMatch(job -> job.getJobState().isTerminalState())) { Thread.sleep(50); } } @Test public void testSavepointRestoreLegacy() throws Exception { runSavepointAndRestore(false); } @Test public void testSavepointRestorePortable() throws Exception { runSavepointAndRestore(true); } private void runSavepointAndRestore(boolean isPortablePipeline) throws Exception { FlinkPipelineOptions options = PipelineOptionsFactory.as(FlinkPipelineOptions.class); options.setStreaming(true); // Initial parallelism options.setParallelism(2); options.setRunner(FlinkRunner.class); // Avoid any task from shutting down which would prevent savepointing options.setShutdownSourcesAfterIdleMs(Long.MAX_VALUE); oneShotLatch = new CountDownLatch(1); Pipeline pipeline = Pipeline.create(options); createStreamingJob(pipeline, false, isPortablePipeline); final JobID jobID; if (isPortablePipeline) { jobID = executePortable(pipeline); } else { jobID = executeLegacy(pipeline); } oneShotLatch.await(); String savepointDir = takeSavepointAndCancelJob(jobID); oneShotLatch = new CountDownLatch(1); // Increase parallelism options.setParallelism(4); pipeline = Pipeline.create(options); createStreamingJob(pipeline, true, isPortablePipeline); if (isPortablePipeline) { restoreFromSavepointPortable(pipeline, savepointDir); } else { restoreFromSavepointLegacy(pipeline, savepointDir); } oneShotLatch.await(); } private JobID executeLegacy(Pipeline pipeline) throws Exception { JobGraph jobGraph = getJobGraph(pipeline); flinkCluster.submitJob(jobGraph).get(); return jobGraph.getJobID(); } private JobID executePortable(Pipeline pipeline) throws Exception { pipeline .getOptions() .as(PortablePipelineOptions.class) .setDefaultEnvironmentType(Environments.ENVIRONMENT_EMBEDDED); pipeline.getOptions().as(FlinkPipelineOptions.class).setFlinkMaster(getFlinkMaster()); RunnerApi.Pipeline pipelineProto = PipelineTranslation.toProto(pipeline); ListeningExecutorService executorService = MoreExecutors.listeningDecorator(Executors.newFixedThreadPool(1)); FlinkPipelineOptions pipelineOptions = pipeline.getOptions().as(FlinkPipelineOptions.class); try { JobInvocation jobInvocation = FlinkJobInvoker.create(null) .createJobInvocation( "id", "none", executorService, pipelineProto, pipelineOptions, new FlinkPipelineRunner(pipelineOptions, null, Collections.emptyList())); jobInvocation.start(); return waitForJobToBeReady(); } finally { executorService.shutdown(); } } private String getFlinkMaster() throws Exception { final URI uri; Method getRestAddress = flinkCluster.getClass().getMethod("getRestAddress"); if (getRestAddress.getReturnType().equals(URI.class)) { // Flink 1.5 way uri = (URI) getRestAddress.invoke(flinkCluster); } else if (getRestAddress.getReturnType().equals(CompletableFuture.class)) { @SuppressWarnings("unchecked") CompletableFuture<URI> future = (CompletableFuture<URI>) getRestAddress.invoke(flinkCluster); uri = future.get(); } else { throw new RuntimeException("Could not determine Rest address for this Flink version."); } return uri.getHost() + ":" + uri.getPort(); } private JobID waitForJobToBeReady() throws InterruptedException, ExecutionException { while (true) { JobStatusMessage jobStatus = Iterables.getFirst(flinkCluster.listJobs().get(), null); if (jobStatus != null && jobStatus.getJobState().name().equals("RUNNING")) { return jobStatus.getJobId(); } Thread.sleep(100); } } private String takeSavepointAndCancelJob(JobID jobID) throws Exception { Exception exception = null; // try multiple times because the job might not be ready yet for (int i = 0; i < 10; i++) { try { return flinkCluster.triggerSavepoint(jobID, null, true).get(); } catch (Exception e) { exception = e; Thread.sleep(100); } } throw exception; } private void restoreFromSavepointLegacy(Pipeline pipeline, String savepointDir) throws ExecutionException, InterruptedException { JobGraph jobGraph = getJobGraph(pipeline); SavepointRestoreSettings savepointSettings = SavepointRestoreSettings.forPath(savepointDir); jobGraph.setSavepointRestoreSettings(savepointSettings); flinkCluster.submitJob(jobGraph).get(); } private void restoreFromSavepointPortable(Pipeline pipeline, String savepointDir) throws Exception { FlinkPipelineOptions flinkOptions = pipeline.getOptions().as(FlinkPipelineOptions.class); flinkOptions.setSavepointPath(savepointDir); executePortable(pipeline); } private JobGraph getJobGraph(Pipeline pipeline) { FlinkRunner flinkRunner = FlinkRunner.fromOptions(pipeline.getOptions()); return flinkRunner.getJobGraph(pipeline); } private static PCollection createStreamingJob( Pipeline pipeline, boolean restored, boolean isPortablePipeline) { final PCollection<KV<String, Long>> key; if (isPortablePipeline) { key = pipeline .apply("ImpulseStage", Impulse.create()) .apply( "KvMapperStage", MapElements.via( new InferableFunction<byte[], KV<String, Void>>() { @Override public KV<String, Void> apply(byte[] input) throws Exception { // This only writes data to one of the two initial partitions. // We want to test this due to // https://jira.apache.org/jira/browse/BEAM-7144 return KV.of("key", null); } })) .apply( "TimerStage", ParDo.of( new DoFn<KV<String, Void>, KV<String, Long>>() { @StateId("nextInteger") private final StateSpec<ValueState<Long>> valueStateSpec = StateSpecs.value(); @TimerId("timer") private final TimerSpec timer = TimerSpecs.timer(TimeDomain.EVENT_TIME); @ProcessElement public void processElement( ProcessContext context, @TimerId("timer") Timer timer) { timer.set(new Instant(0)); } @OnTimer("timer") public void onTimer( OnTimerContext context, @StateId("nextInteger") ValueState<Long> nextInteger, @TimerId("timer") Timer timer) { Long current = nextInteger.read(); current = current != null ? current : 0L; context.output(KV.of("key", current)); LOG.debug("triggering timer {}", current); nextInteger.write(current + 1); // Trigger timer again and continue to hold back the watermark timer.withOutputTimestamp(new Instant(0)).set(context.fireTimestamp()); } })); } else { key = pipeline .apply("IdGeneratorStage", GenerateSequence.from(0)) .apply( "KvMapperStage", ParDo.of( new DoFn<Long, KV<String, Long>>() { @ProcessElement public void processElement(ProcessContext context) { context.output(KV.of("key", context.element())); } })); } if (restored) { return key.apply( "VerificationStage", ParDo.of( new DoFn<KV<String, Long>, String>() { @StateId("valueState") private final StateSpec<ValueState<Integer>> valueStateSpec = StateSpecs.value(); @StateId("bagState") private final StateSpec<BagState<Integer>> bagStateSpec = StateSpecs.bag(); @ProcessElement public void processElement( ProcessContext context, @StateId("valueState") ValueState<Integer> intValueState, @StateId("bagState") BagState<Integer> intBagState) { assertThat(intValueState.read(), Matchers.is(42)); assertThat(intBagState.read(), IsIterableContaining.hasItems(40, 1, 1)); oneShotLatch.countDown(); } })); } else { return key.apply( "VerificationStage", ParDo.of( new DoFn<KV<String, Long>, String>() { @StateId("valueState") private final StateSpec<ValueState<Integer>> valueStateSpec = StateSpecs.value(); @StateId("bagState") private final StateSpec<BagState<Integer>> bagStateSpec = StateSpecs.bag(); @ProcessElement public void processElement( ProcessContext context, @StateId("valueState") ValueState<Integer> intValueState, @StateId("bagState") BagState<Integer> intBagState) { long value = Objects.requireNonNull(context.element().getValue()); LOG.debug("value: {} timestamp: {}", value, context.timestamp().getMillis()); if (value == 0L) { intValueState.write(42); intBagState.add(40); intBagState.add(1); intBagState.add(1); } else if (value >= 1) { oneShotLatch.countDown(); } } })); } } }
apache-2.0
thejettdurham/jinteg
src/main/java/com/jettdurham/jinteg/MethodNotStaticException.java
351
package com.jettdurham.jinteg; /** * Thrown when a method designed to be run as a test is not static. * * @author jettdurham * */ public class MethodNotStaticException extends Exception { private static final long serialVersionUID = -6889136974544927532L; public MethodNotStaticException(String message) { super(message); } }
apache-2.0
flash8627/icustom-boot
icustom.core/src/main/java/com/gwtjs/icustom/autoconfiguration/IApplicationPrincipal.java
1251
package com.gwtjs.icustom.autoconfiguration; import java.io.Serializable; /** * 应用程序凭证,含应用名、权限Scope、当前环境等信息 */ public interface IApplicationPrincipal extends Serializable { /** * 获得日志表格名称 * * @since 2013-6-7 * @return */ int getLogsTableIndex(); /** * 获取应用名 * * @return */ String getAppName(); /** * 获取权限的Scope * * @return */ String getScope(); /** * 获取当前的环境 * * @return */ String getEnviorment(); /** * 获取栏目视图名称,无视图时可能返回NULL * * @return */ String getSiteMapViewName(); /** * 应用上下文根,包含最后的/ * * @author l54883 * @since 2012-3-29 * @return */ String getContextPath(); /** * 获取当前网络环境 internet/intranet * * @author l54883 * @since 2012-6-29 * @return */ String getNetwork(); /** * 获取数据库类型[oracle,mysql] * * @author zWX304259 * @since 2016年2月25日 * @return */ String getDbType(); /** * 获取服务版本 * * @author gwx244051 * @since 2016年03月10日 * @return */ String getServiceVersion(); boolean isEnableAppPermissionPortal(); }
apache-2.0
googleads/google-ads-java
google-ads-stubs-v9/src/main/java/com/google/ads/googleads/v9/common/TargetSpend.java
25132
// Generated by the protocol buffer compiler. DO NOT EDIT! // source: google/ads/googleads/v9/common/bidding.proto package com.google.ads.googleads.v9.common; /** * <pre> * An automated bid strategy that sets your bids to help get as many clicks * as possible within your budget. * </pre> * * Protobuf type {@code google.ads.googleads.v9.common.TargetSpend} */ public final class TargetSpend extends com.google.protobuf.GeneratedMessageV3 implements // @@protoc_insertion_point(message_implements:google.ads.googleads.v9.common.TargetSpend) TargetSpendOrBuilder { private static final long serialVersionUID = 0L; // Use TargetSpend.newBuilder() to construct. private TargetSpend(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) { super(builder); } private TargetSpend() { } @java.lang.Override @SuppressWarnings({"unused"}) protected java.lang.Object newInstance( UnusedPrivateParameter unused) { return new TargetSpend(); } @java.lang.Override public final com.google.protobuf.UnknownFieldSet getUnknownFields() { return this.unknownFields; } private TargetSpend( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { this(); if (extensionRegistry == null) { throw new java.lang.NullPointerException(); } int mutable_bitField0_ = 0; com.google.protobuf.UnknownFieldSet.Builder unknownFields = com.google.protobuf.UnknownFieldSet.newBuilder(); try { boolean done = false; while (!done) { int tag = input.readTag(); switch (tag) { case 0: done = true; break; case 24: { bitField0_ |= 0x00000001; targetSpendMicros_ = input.readInt64(); break; } case 32: { bitField0_ |= 0x00000002; cpcBidCeilingMicros_ = input.readInt64(); break; } default: { if (!parseUnknownField( input, unknownFields, extensionRegistry, tag)) { done = true; } break; } } } } catch (com.google.protobuf.InvalidProtocolBufferException e) { throw e.setUnfinishedMessage(this); } catch (java.io.IOException e) { throw new com.google.protobuf.InvalidProtocolBufferException( e).setUnfinishedMessage(this); } finally { this.unknownFields = unknownFields.build(); makeExtensionsImmutable(); } } public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.google.ads.googleads.v9.common.BiddingProto.internal_static_google_ads_googleads_v9_common_TargetSpend_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.google.ads.googleads.v9.common.BiddingProto.internal_static_google_ads_googleads_v9_common_TargetSpend_fieldAccessorTable .ensureFieldAccessorsInitialized( com.google.ads.googleads.v9.common.TargetSpend.class, com.google.ads.googleads.v9.common.TargetSpend.Builder.class); } private int bitField0_; public static final int TARGET_SPEND_MICROS_FIELD_NUMBER = 3; private long targetSpendMicros_; /** * <pre> * The spend target under which to maximize clicks. * A TargetSpend bidder will attempt to spend the smaller of this value * or the natural throttling spend amount. * If not specified, the budget is used as the spend target. * This field is deprecated and should no longer be used. See * https://ads-developers.googleblog.com/2020/05/reminder-about-sunset-creation-of.html * for details. * </pre> * * <code>optional int64 target_spend_micros = 3 [deprecated = true];</code> * @return Whether the targetSpendMicros field is set. */ @java.lang.Override @java.lang.Deprecated public boolean hasTargetSpendMicros() { return ((bitField0_ & 0x00000001) != 0); } /** * <pre> * The spend target under which to maximize clicks. * A TargetSpend bidder will attempt to spend the smaller of this value * or the natural throttling spend amount. * If not specified, the budget is used as the spend target. * This field is deprecated and should no longer be used. See * https://ads-developers.googleblog.com/2020/05/reminder-about-sunset-creation-of.html * for details. * </pre> * * <code>optional int64 target_spend_micros = 3 [deprecated = true];</code> * @return The targetSpendMicros. */ @java.lang.Override @java.lang.Deprecated public long getTargetSpendMicros() { return targetSpendMicros_; } public static final int CPC_BID_CEILING_MICROS_FIELD_NUMBER = 4; private long cpcBidCeilingMicros_; /** * <pre> * Maximum bid limit that can be set by the bid strategy. * The limit applies to all keywords managed by the strategy. * </pre> * * <code>optional int64 cpc_bid_ceiling_micros = 4;</code> * @return Whether the cpcBidCeilingMicros field is set. */ @java.lang.Override public boolean hasCpcBidCeilingMicros() { return ((bitField0_ & 0x00000002) != 0); } /** * <pre> * Maximum bid limit that can be set by the bid strategy. * The limit applies to all keywords managed by the strategy. * </pre> * * <code>optional int64 cpc_bid_ceiling_micros = 4;</code> * @return The cpcBidCeilingMicros. */ @java.lang.Override public long getCpcBidCeilingMicros() { return cpcBidCeilingMicros_; } private byte memoizedIsInitialized = -1; @java.lang.Override public final boolean isInitialized() { byte isInitialized = memoizedIsInitialized; if (isInitialized == 1) return true; if (isInitialized == 0) return false; memoizedIsInitialized = 1; return true; } @java.lang.Override public void writeTo(com.google.protobuf.CodedOutputStream output) throws java.io.IOException { if (((bitField0_ & 0x00000001) != 0)) { output.writeInt64(3, targetSpendMicros_); } if (((bitField0_ & 0x00000002) != 0)) { output.writeInt64(4, cpcBidCeilingMicros_); } unknownFields.writeTo(output); } @java.lang.Override public int getSerializedSize() { int size = memoizedSize; if (size != -1) return size; size = 0; if (((bitField0_ & 0x00000001) != 0)) { size += com.google.protobuf.CodedOutputStream .computeInt64Size(3, targetSpendMicros_); } if (((bitField0_ & 0x00000002) != 0)) { size += com.google.protobuf.CodedOutputStream .computeInt64Size(4, cpcBidCeilingMicros_); } size += unknownFields.getSerializedSize(); memoizedSize = size; return size; } @java.lang.Override public boolean equals(final java.lang.Object obj) { if (obj == this) { return true; } if (!(obj instanceof com.google.ads.googleads.v9.common.TargetSpend)) { return super.equals(obj); } com.google.ads.googleads.v9.common.TargetSpend other = (com.google.ads.googleads.v9.common.TargetSpend) obj; if (hasTargetSpendMicros() != other.hasTargetSpendMicros()) return false; if (hasTargetSpendMicros()) { if (getTargetSpendMicros() != other.getTargetSpendMicros()) return false; } if (hasCpcBidCeilingMicros() != other.hasCpcBidCeilingMicros()) return false; if (hasCpcBidCeilingMicros()) { if (getCpcBidCeilingMicros() != other.getCpcBidCeilingMicros()) return false; } if (!unknownFields.equals(other.unknownFields)) return false; return true; } @java.lang.Override public int hashCode() { if (memoizedHashCode != 0) { return memoizedHashCode; } int hash = 41; hash = (19 * hash) + getDescriptor().hashCode(); if (hasTargetSpendMicros()) { hash = (37 * hash) + TARGET_SPEND_MICROS_FIELD_NUMBER; hash = (53 * hash) + com.google.protobuf.Internal.hashLong( getTargetSpendMicros()); } if (hasCpcBidCeilingMicros()) { hash = (37 * hash) + CPC_BID_CEILING_MICROS_FIELD_NUMBER; hash = (53 * hash) + com.google.protobuf.Internal.hashLong( getCpcBidCeilingMicros()); } hash = (29 * hash) + unknownFields.hashCode(); memoizedHashCode = hash; return hash; } public static com.google.ads.googleads.v9.common.TargetSpend parseFrom( java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.ads.googleads.v9.common.TargetSpend parseFrom( java.nio.ByteBuffer data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.google.ads.googleads.v9.common.TargetSpend parseFrom( com.google.protobuf.ByteString data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.ads.googleads.v9.common.TargetSpend parseFrom( com.google.protobuf.ByteString data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.google.ads.googleads.v9.common.TargetSpend parseFrom(byte[] data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.ads.googleads.v9.common.TargetSpend parseFrom( byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.google.ads.googleads.v9.common.TargetSpend parseFrom(java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseWithIOException(PARSER, input); } public static com.google.ads.googleads.v9.common.TargetSpend parseFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseWithIOException(PARSER, input, extensionRegistry); } public static com.google.ads.googleads.v9.common.TargetSpend parseDelimitedFrom(java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseDelimitedWithIOException(PARSER, input); } public static com.google.ads.googleads.v9.common.TargetSpend parseDelimitedFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseDelimitedWithIOException(PARSER, input, extensionRegistry); } public static com.google.ads.googleads.v9.common.TargetSpend parseFrom( com.google.protobuf.CodedInputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseWithIOException(PARSER, input); } public static com.google.ads.googleads.v9.common.TargetSpend parseFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseWithIOException(PARSER, input, extensionRegistry); } @java.lang.Override public Builder newBuilderForType() { return newBuilder(); } public static Builder newBuilder() { return DEFAULT_INSTANCE.toBuilder(); } public static Builder newBuilder(com.google.ads.googleads.v9.common.TargetSpend prototype) { return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype); } @java.lang.Override public Builder toBuilder() { return this == DEFAULT_INSTANCE ? new Builder() : new Builder().mergeFrom(this); } @java.lang.Override protected Builder newBuilderForType( com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { Builder builder = new Builder(parent); return builder; } /** * <pre> * An automated bid strategy that sets your bids to help get as many clicks * as possible within your budget. * </pre> * * Protobuf type {@code google.ads.googleads.v9.common.TargetSpend} */ public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder<Builder> implements // @@protoc_insertion_point(builder_implements:google.ads.googleads.v9.common.TargetSpend) com.google.ads.googleads.v9.common.TargetSpendOrBuilder { public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.google.ads.googleads.v9.common.BiddingProto.internal_static_google_ads_googleads_v9_common_TargetSpend_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.google.ads.googleads.v9.common.BiddingProto.internal_static_google_ads_googleads_v9_common_TargetSpend_fieldAccessorTable .ensureFieldAccessorsInitialized( com.google.ads.googleads.v9.common.TargetSpend.class, com.google.ads.googleads.v9.common.TargetSpend.Builder.class); } // Construct using com.google.ads.googleads.v9.common.TargetSpend.newBuilder() private Builder() { maybeForceBuilderInitialization(); } private Builder( com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { super(parent); maybeForceBuilderInitialization(); } private void maybeForceBuilderInitialization() { if (com.google.protobuf.GeneratedMessageV3 .alwaysUseFieldBuilders) { } } @java.lang.Override public Builder clear() { super.clear(); targetSpendMicros_ = 0L; bitField0_ = (bitField0_ & ~0x00000001); cpcBidCeilingMicros_ = 0L; bitField0_ = (bitField0_ & ~0x00000002); return this; } @java.lang.Override public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() { return com.google.ads.googleads.v9.common.BiddingProto.internal_static_google_ads_googleads_v9_common_TargetSpend_descriptor; } @java.lang.Override public com.google.ads.googleads.v9.common.TargetSpend getDefaultInstanceForType() { return com.google.ads.googleads.v9.common.TargetSpend.getDefaultInstance(); } @java.lang.Override public com.google.ads.googleads.v9.common.TargetSpend build() { com.google.ads.googleads.v9.common.TargetSpend result = buildPartial(); if (!result.isInitialized()) { throw newUninitializedMessageException(result); } return result; } @java.lang.Override public com.google.ads.googleads.v9.common.TargetSpend buildPartial() { com.google.ads.googleads.v9.common.TargetSpend result = new com.google.ads.googleads.v9.common.TargetSpend(this); int from_bitField0_ = bitField0_; int to_bitField0_ = 0; if (((from_bitField0_ & 0x00000001) != 0)) { result.targetSpendMicros_ = targetSpendMicros_; to_bitField0_ |= 0x00000001; } if (((from_bitField0_ & 0x00000002) != 0)) { result.cpcBidCeilingMicros_ = cpcBidCeilingMicros_; to_bitField0_ |= 0x00000002; } result.bitField0_ = to_bitField0_; onBuilt(); return result; } @java.lang.Override public Builder clone() { return super.clone(); } @java.lang.Override public Builder setField( com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) { return super.setField(field, value); } @java.lang.Override public Builder clearField( com.google.protobuf.Descriptors.FieldDescriptor field) { return super.clearField(field); } @java.lang.Override public Builder clearOneof( com.google.protobuf.Descriptors.OneofDescriptor oneof) { return super.clearOneof(oneof); } @java.lang.Override public Builder setRepeatedField( com.google.protobuf.Descriptors.FieldDescriptor field, int index, java.lang.Object value) { return super.setRepeatedField(field, index, value); } @java.lang.Override public Builder addRepeatedField( com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) { return super.addRepeatedField(field, value); } @java.lang.Override public Builder mergeFrom(com.google.protobuf.Message other) { if (other instanceof com.google.ads.googleads.v9.common.TargetSpend) { return mergeFrom((com.google.ads.googleads.v9.common.TargetSpend)other); } else { super.mergeFrom(other); return this; } } public Builder mergeFrom(com.google.ads.googleads.v9.common.TargetSpend other) { if (other == com.google.ads.googleads.v9.common.TargetSpend.getDefaultInstance()) return this; if (other.hasTargetSpendMicros()) { setTargetSpendMicros(other.getTargetSpendMicros()); } if (other.hasCpcBidCeilingMicros()) { setCpcBidCeilingMicros(other.getCpcBidCeilingMicros()); } this.mergeUnknownFields(other.unknownFields); onChanged(); return this; } @java.lang.Override public final boolean isInitialized() { return true; } @java.lang.Override public Builder mergeFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { com.google.ads.googleads.v9.common.TargetSpend parsedMessage = null; try { parsedMessage = PARSER.parsePartialFrom(input, extensionRegistry); } catch (com.google.protobuf.InvalidProtocolBufferException e) { parsedMessage = (com.google.ads.googleads.v9.common.TargetSpend) e.getUnfinishedMessage(); throw e.unwrapIOException(); } finally { if (parsedMessage != null) { mergeFrom(parsedMessage); } } return this; } private int bitField0_; private long targetSpendMicros_ ; /** * <pre> * The spend target under which to maximize clicks. * A TargetSpend bidder will attempt to spend the smaller of this value * or the natural throttling spend amount. * If not specified, the budget is used as the spend target. * This field is deprecated and should no longer be used. See * https://ads-developers.googleblog.com/2020/05/reminder-about-sunset-creation-of.html * for details. * </pre> * * <code>optional int64 target_spend_micros = 3 [deprecated = true];</code> * @return Whether the targetSpendMicros field is set. */ @java.lang.Override @java.lang.Deprecated public boolean hasTargetSpendMicros() { return ((bitField0_ & 0x00000001) != 0); } /** * <pre> * The spend target under which to maximize clicks. * A TargetSpend bidder will attempt to spend the smaller of this value * or the natural throttling spend amount. * If not specified, the budget is used as the spend target. * This field is deprecated and should no longer be used. See * https://ads-developers.googleblog.com/2020/05/reminder-about-sunset-creation-of.html * for details. * </pre> * * <code>optional int64 target_spend_micros = 3 [deprecated = true];</code> * @return The targetSpendMicros. */ @java.lang.Override @java.lang.Deprecated public long getTargetSpendMicros() { return targetSpendMicros_; } /** * <pre> * The spend target under which to maximize clicks. * A TargetSpend bidder will attempt to spend the smaller of this value * or the natural throttling spend amount. * If not specified, the budget is used as the spend target. * This field is deprecated and should no longer be used. See * https://ads-developers.googleblog.com/2020/05/reminder-about-sunset-creation-of.html * for details. * </pre> * * <code>optional int64 target_spend_micros = 3 [deprecated = true];</code> * @param value The targetSpendMicros to set. * @return This builder for chaining. */ @java.lang.Deprecated public Builder setTargetSpendMicros(long value) { bitField0_ |= 0x00000001; targetSpendMicros_ = value; onChanged(); return this; } /** * <pre> * The spend target under which to maximize clicks. * A TargetSpend bidder will attempt to spend the smaller of this value * or the natural throttling spend amount. * If not specified, the budget is used as the spend target. * This field is deprecated and should no longer be used. See * https://ads-developers.googleblog.com/2020/05/reminder-about-sunset-creation-of.html * for details. * </pre> * * <code>optional int64 target_spend_micros = 3 [deprecated = true];</code> * @return This builder for chaining. */ @java.lang.Deprecated public Builder clearTargetSpendMicros() { bitField0_ = (bitField0_ & ~0x00000001); targetSpendMicros_ = 0L; onChanged(); return this; } private long cpcBidCeilingMicros_ ; /** * <pre> * Maximum bid limit that can be set by the bid strategy. * The limit applies to all keywords managed by the strategy. * </pre> * * <code>optional int64 cpc_bid_ceiling_micros = 4;</code> * @return Whether the cpcBidCeilingMicros field is set. */ @java.lang.Override public boolean hasCpcBidCeilingMicros() { return ((bitField0_ & 0x00000002) != 0); } /** * <pre> * Maximum bid limit that can be set by the bid strategy. * The limit applies to all keywords managed by the strategy. * </pre> * * <code>optional int64 cpc_bid_ceiling_micros = 4;</code> * @return The cpcBidCeilingMicros. */ @java.lang.Override public long getCpcBidCeilingMicros() { return cpcBidCeilingMicros_; } /** * <pre> * Maximum bid limit that can be set by the bid strategy. * The limit applies to all keywords managed by the strategy. * </pre> * * <code>optional int64 cpc_bid_ceiling_micros = 4;</code> * @param value The cpcBidCeilingMicros to set. * @return This builder for chaining. */ public Builder setCpcBidCeilingMicros(long value) { bitField0_ |= 0x00000002; cpcBidCeilingMicros_ = value; onChanged(); return this; } /** * <pre> * Maximum bid limit that can be set by the bid strategy. * The limit applies to all keywords managed by the strategy. * </pre> * * <code>optional int64 cpc_bid_ceiling_micros = 4;</code> * @return This builder for chaining. */ public Builder clearCpcBidCeilingMicros() { bitField0_ = (bitField0_ & ~0x00000002); cpcBidCeilingMicros_ = 0L; onChanged(); return this; } @java.lang.Override public final Builder setUnknownFields( final com.google.protobuf.UnknownFieldSet unknownFields) { return super.setUnknownFields(unknownFields); } @java.lang.Override public final Builder mergeUnknownFields( final com.google.protobuf.UnknownFieldSet unknownFields) { return super.mergeUnknownFields(unknownFields); } // @@protoc_insertion_point(builder_scope:google.ads.googleads.v9.common.TargetSpend) } // @@protoc_insertion_point(class_scope:google.ads.googleads.v9.common.TargetSpend) private static final com.google.ads.googleads.v9.common.TargetSpend DEFAULT_INSTANCE; static { DEFAULT_INSTANCE = new com.google.ads.googleads.v9.common.TargetSpend(); } public static com.google.ads.googleads.v9.common.TargetSpend getDefaultInstance() { return DEFAULT_INSTANCE; } private static final com.google.protobuf.Parser<TargetSpend> PARSER = new com.google.protobuf.AbstractParser<TargetSpend>() { @java.lang.Override public TargetSpend parsePartialFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return new TargetSpend(input, extensionRegistry); } }; public static com.google.protobuf.Parser<TargetSpend> parser() { return PARSER; } @java.lang.Override public com.google.protobuf.Parser<TargetSpend> getParserForType() { return PARSER; } @java.lang.Override public com.google.ads.googleads.v9.common.TargetSpend getDefaultInstanceForType() { return DEFAULT_INSTANCE; } }
apache-2.0
jentfoo/aws-sdk-java
aws-java-sdk-iam/src/main/java/com/amazonaws/services/identitymanagement/model/transform/AddRoleToInstanceProfileResultStaxUnmarshaller.java
2365
/* * 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.identitymanagement.model.transform; import javax.xml.stream.events.XMLEvent; import javax.annotation.Generated; import com.amazonaws.services.identitymanagement.model.*; import com.amazonaws.transform.Unmarshaller; import com.amazonaws.transform.StaxUnmarshallerContext; import com.amazonaws.transform.SimpleTypeStaxUnmarshallers.*; /** * AddRoleToInstanceProfileResult StAX Unmarshaller */ @Generated("com.amazonaws:aws-java-sdk-code-generator") public class AddRoleToInstanceProfileResultStaxUnmarshaller implements Unmarshaller<AddRoleToInstanceProfileResult, StaxUnmarshallerContext> { public AddRoleToInstanceProfileResult unmarshall(StaxUnmarshallerContext context) throws Exception { AddRoleToInstanceProfileResult addRoleToInstanceProfileResult = new AddRoleToInstanceProfileResult(); int originalDepth = context.getCurrentDepth(); int targetDepth = originalDepth + 1; if (context.isStartOfDocument()) targetDepth += 1; while (true) { XMLEvent xmlEvent = context.nextEvent(); if (xmlEvent.isEndDocument()) return addRoleToInstanceProfileResult; if (xmlEvent.isAttribute() || xmlEvent.isStartElement()) { } else if (xmlEvent.isEndElement()) { if (context.getCurrentDepth() < originalDepth) { return addRoleToInstanceProfileResult; } } } } private static AddRoleToInstanceProfileResultStaxUnmarshaller instance; public static AddRoleToInstanceProfileResultStaxUnmarshaller getInstance() { if (instance == null) instance = new AddRoleToInstanceProfileResultStaxUnmarshaller(); return instance; } }
apache-2.0
gexiao01/thrall
thrall-core/src/main/java/org/xmly/thrall/core/protocol/WebResponseStatus.java
388
package org.xmly.thrall.core.protocol; public enum WebResponseStatus { SUCCESS(200, "success"), AUTH(401,"auth"), FAIL(400, "fail"); WebResponseStatus(int code, String desc) { this.code = code; this.desc = desc; } private int code; private String desc; public int getCode() { return code; } public String getDesc() { return desc; } }
apache-2.0
shenzeyu/recommend
src/main/java/com/usst/app/store/promote/action/PromoteAction.java
7493
package com.usst.app.store.promote.action; import java.io.PrintStream; import java.util.ArrayList; import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.Map; import javax.servlet.http.HttpServletRequest; import org.apache.commons.lang.StringUtils; import org.apache.log4j.Logger; import com.usst.app.component.file.service.FileUploadService; import com.usst.app.component.serialNumber.service.SerialNumberService; import com.usst.app.store.promote.model.Promote; import com.usst.app.store.promote.model.PromoteGood; import com.usst.app.store.promote.service.PromoteGoodService; import com.usst.app.store.promote.service.PromoteService; import com.usst.app.system.user.model.SysUser; import com.usst.code.struct.BaseAction; import com.usst.code.util.PageInfo; public class PromoteAction extends BaseAction { private static final long serialVersionUID = 1L; private static final Logger logger = Logger.getLogger(PromoteAction.class); private Promote promote; private PromoteService promoteService; private PromoteGood promoteGood; private PromoteGoodService promoteGoodService; private SerialNumberService serialNumberService; private String imgIdStr; private FileUploadService fileUploadService; private String[] goodIdArr; private String[] goodNameArr; private Double[] priceMarketArr; private Double[] pricePromoteArr; public String[] getGoodIdArr() { return this.goodIdArr; } public void setGoodIdArr(String[] goodIdArr) { this.goodIdArr = goodIdArr; } public String[] getGoodNameArr() { return this.goodNameArr; } public void setGoodNameArr(String[] goodNameArr) { this.goodNameArr = goodNameArr; } public Double[] getPriceMarketArr() { return this.priceMarketArr; } public void setPriceMarketArr(Double[] priceMarketArr) { this.priceMarketArr = priceMarketArr; } public Double[] getPricePromoteArr() { return this.pricePromoteArr; } public void setPricePromoteArr(Double[] pricePromoteArr) { this.pricePromoteArr = pricePromoteArr; } public String listJosn() { logger.info("start list promote"); List<Promote> resultList = null; int totalRows = 0; try { PageInfo pageInfo = createPageInfo(); if (this.promote == null) { this.promote = new Promote(); } resultList = this.promoteService.pageList(pageInfo, this.promote, true); totalRows = pageInfo.getCount(); } catch (Exception e) { logger.error("error occur when list promote", e); } if (resultList == null) { resultList = new ArrayList(); } this.jsonMap = new HashMap(); this.jsonMap.put("total", Integer.valueOf(totalRows)); this.jsonMap.put("rows", resultList); return "success"; } public String list() { logger.info("start to query promote information"); return "list_promote"; } public String edit() { SysUser loginMan = getSessionUserInfo(); if (this.promote == null) { this.promote = new Promote(); } try { if (StringUtils.isBlank(this.promote.getId())) { this.promote.setState("c"); initModel(true, this.promote, loginMan); try { this.promote.setCode(this.serialNumberService.getSerialNumberByDate("PT", "promote")); } catch (Exception e) { logger.error("error occur when get code", e); } } else { this.promote = ((Promote) this.promoteService.getModel(this.promote.getId())); initModel(false, this.promote, loginMan); } } catch (Exception e) { logger.error("error occur when list promote", e); responseFlag(false); } return "edit_promote"; } public void save() { HttpServletRequest request = getRequest(); String picId = request.getParameter("picId"); this.promote.setPicId(picId); System.out.println("picId:" + picId); logger.info("start to update promote information"); try { if (this.promote == null) { this.promote = new Promote(); } if (StringUtils.isBlank(this.promote.getId())) { this.promote.setId(this.promoteService.makeId()); this.promote.setState("c"); this.promote.setModifyTime(new Date()); this.promoteService.insertPromote(this.promote); } else { this.promoteService.update(this.promote); if (StringUtils.isNotBlank(picId)) { this.fileUploadService.cleanAppId(this.promote.getId()); this.fileUploadService.updateAppId(picId, this.promote.getId()); } } if (StringUtils.isNotBlank(this.imgIdStr)) { String[] imgIdArr = this.imgIdStr.split(","); for (int i = 0; i < imgIdArr.length; i++) { this.fileUploadService.updateAppId(imgIdArr[i], this.promote.getId()); } if (StringUtils.isNotBlank(picId)) { this.fileUploadService.updateAppId(picId, this.promote.getPicId()); } } responseFlag(true); } catch (Exception e) { logger.info("error occur when save promote information"); e.printStackTrace(); responseFlag(false); } try { this.promoteGoodService.deleteByPromoteId(this.promote.getId()); } catch (Exception e) { responseFlag(false); logger.error("error occur when delete promoteGood", e); } String promoteId = this.promote.getId(); if ((this.goodIdArr != null) && (this.goodIdArr.length != 0)) { for (int i = 0; i < this.goodIdArr.length; i++) { PromoteGood promoteGood = new PromoteGood(); promoteGood.setPromoteId(promoteId); promoteGood.setGoodId(this.goodIdArr[i]); promoteGood.setGoodName(this.goodNameArr[i]); promoteGood.setPriceMarket(this.priceMarketArr[i]); promoteGood.setPricePromote(this.pricePromoteArr[i]); promoteGood.setSort(Integer.valueOf(i)); try { this.promoteGoodService.insert(promoteGood); } catch (Exception e) { responseFlag(false); logger.error("error occur when insert promoteGood", e); } } } } public void delete() { SysUser loginMan = getSessionUserInfo(); try { if (this.promote == null) { this.promote = new Promote(); } this.promoteGoodService.deleteByPromoteId(this.promote.getId()); this.promoteService.delete(this.promote.getId()); logger.info(loginMan.getCode() + " delete promote,id:" + this.promote.getId()); responseFlag(true); } catch (Exception e) { responseFlag(false); logger.error("error occur when delete a promote!", e); } } public Promote getPromote() { return this.promote; } public void setPromote(Promote promote) { this.promote = promote; } public PromoteService getPromoteService() { return this.promoteService; } public void setPromoteService(PromoteService promoteService) { this.promoteService = promoteService; } public PromoteGood getPromoteGood() { return this.promoteGood; } public void setPromoteGood(PromoteGood promoteGood) { this.promoteGood = promoteGood; } public PromoteGoodService getPromoteGoodService() { return this.promoteGoodService; } public void setPromoteGoodService(PromoteGoodService promoteGoodService) { this.promoteGoodService = promoteGoodService; } public SerialNumberService getSerialNumberService() { return this.serialNumberService; } public void setSerialNumberService(SerialNumberService serialNumberService) { this.serialNumberService = serialNumberService; } public String getImgIdStr() { return this.imgIdStr; } public void setImgIdStr(String imgIdStr) { this.imgIdStr = imgIdStr; } public FileUploadService getFileUploadService() { return this.fileUploadService; } public void setFileUploadService(FileUploadService fileUploadService) { this.fileUploadService = fileUploadService; } }
apache-2.0
googleapis/java-aiplatform
proto-google-cloud-aiplatform-v1beta1/src/main/java/com/google/cloud/aiplatform/v1beta1/BatchCreateTensorboardTimeSeriesResponse.java
36500
/* * Copyright 2020 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ // Generated by the protocol buffer compiler. DO NOT EDIT! // source: google/cloud/aiplatform/v1beta1/tensorboard_service.proto package com.google.cloud.aiplatform.v1beta1; /** * * * <pre> * Response message for [TensorboardService.BatchCreateTensorboardTimeSeries][google.cloud.aiplatform.v1beta1.TensorboardService.BatchCreateTensorboardTimeSeries]. * </pre> * * Protobuf type {@code google.cloud.aiplatform.v1beta1.BatchCreateTensorboardTimeSeriesResponse} */ public final class BatchCreateTensorboardTimeSeriesResponse extends com.google.protobuf.GeneratedMessageV3 implements // @@protoc_insertion_point(message_implements:google.cloud.aiplatform.v1beta1.BatchCreateTensorboardTimeSeriesResponse) BatchCreateTensorboardTimeSeriesResponseOrBuilder { private static final long serialVersionUID = 0L; // Use BatchCreateTensorboardTimeSeriesResponse.newBuilder() to construct. private BatchCreateTensorboardTimeSeriesResponse( com.google.protobuf.GeneratedMessageV3.Builder<?> builder) { super(builder); } private BatchCreateTensorboardTimeSeriesResponse() { tensorboardTimeSeries_ = java.util.Collections.emptyList(); } @java.lang.Override @SuppressWarnings({"unused"}) protected java.lang.Object newInstance(UnusedPrivateParameter unused) { return new BatchCreateTensorboardTimeSeriesResponse(); } @java.lang.Override public final com.google.protobuf.UnknownFieldSet getUnknownFields() { return this.unknownFields; } private BatchCreateTensorboardTimeSeriesResponse( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { this(); if (extensionRegistry == null) { throw new java.lang.NullPointerException(); } int mutable_bitField0_ = 0; com.google.protobuf.UnknownFieldSet.Builder unknownFields = com.google.protobuf.UnknownFieldSet.newBuilder(); try { boolean done = false; while (!done) { int tag = input.readTag(); switch (tag) { case 0: done = true; break; case 10: { if (!((mutable_bitField0_ & 0x00000001) != 0)) { tensorboardTimeSeries_ = new java.util.ArrayList< com.google.cloud.aiplatform.v1beta1.TensorboardTimeSeries>(); mutable_bitField0_ |= 0x00000001; } tensorboardTimeSeries_.add( input.readMessage( com.google.cloud.aiplatform.v1beta1.TensorboardTimeSeries.parser(), extensionRegistry)); break; } default: { if (!parseUnknownField(input, unknownFields, extensionRegistry, tag)) { done = true; } break; } } } } catch (com.google.protobuf.InvalidProtocolBufferException e) { throw e.setUnfinishedMessage(this); } catch (java.io.IOException e) { throw new com.google.protobuf.InvalidProtocolBufferException(e).setUnfinishedMessage(this); } finally { if (((mutable_bitField0_ & 0x00000001) != 0)) { tensorboardTimeSeries_ = java.util.Collections.unmodifiableList(tensorboardTimeSeries_); } this.unknownFields = unknownFields.build(); makeExtensionsImmutable(); } } public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.google.cloud.aiplatform.v1beta1.TensorboardServiceProto .internal_static_google_cloud_aiplatform_v1beta1_BatchCreateTensorboardTimeSeriesResponse_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.google.cloud.aiplatform.v1beta1.TensorboardServiceProto .internal_static_google_cloud_aiplatform_v1beta1_BatchCreateTensorboardTimeSeriesResponse_fieldAccessorTable .ensureFieldAccessorsInitialized( com.google.cloud.aiplatform.v1beta1.BatchCreateTensorboardTimeSeriesResponse.class, com.google.cloud.aiplatform.v1beta1.BatchCreateTensorboardTimeSeriesResponse.Builder .class); } public static final int TENSORBOARD_TIME_SERIES_FIELD_NUMBER = 1; private java.util.List<com.google.cloud.aiplatform.v1beta1.TensorboardTimeSeries> tensorboardTimeSeries_; /** * * * <pre> * The created TensorboardTimeSeries. * </pre> * * <code> * repeated .google.cloud.aiplatform.v1beta1.TensorboardTimeSeries tensorboard_time_series = 1; * </code> */ @java.lang.Override public java.util.List<com.google.cloud.aiplatform.v1beta1.TensorboardTimeSeries> getTensorboardTimeSeriesList() { return tensorboardTimeSeries_; } /** * * * <pre> * The created TensorboardTimeSeries. * </pre> * * <code> * repeated .google.cloud.aiplatform.v1beta1.TensorboardTimeSeries tensorboard_time_series = 1; * </code> */ @java.lang.Override public java.util.List< ? extends com.google.cloud.aiplatform.v1beta1.TensorboardTimeSeriesOrBuilder> getTensorboardTimeSeriesOrBuilderList() { return tensorboardTimeSeries_; } /** * * * <pre> * The created TensorboardTimeSeries. * </pre> * * <code> * repeated .google.cloud.aiplatform.v1beta1.TensorboardTimeSeries tensorboard_time_series = 1; * </code> */ @java.lang.Override public int getTensorboardTimeSeriesCount() { return tensorboardTimeSeries_.size(); } /** * * * <pre> * The created TensorboardTimeSeries. * </pre> * * <code> * repeated .google.cloud.aiplatform.v1beta1.TensorboardTimeSeries tensorboard_time_series = 1; * </code> */ @java.lang.Override public com.google.cloud.aiplatform.v1beta1.TensorboardTimeSeries getTensorboardTimeSeries( int index) { return tensorboardTimeSeries_.get(index); } /** * * * <pre> * The created TensorboardTimeSeries. * </pre> * * <code> * repeated .google.cloud.aiplatform.v1beta1.TensorboardTimeSeries tensorboard_time_series = 1; * </code> */ @java.lang.Override public com.google.cloud.aiplatform.v1beta1.TensorboardTimeSeriesOrBuilder getTensorboardTimeSeriesOrBuilder(int index) { return tensorboardTimeSeries_.get(index); } private byte memoizedIsInitialized = -1; @java.lang.Override public final boolean isInitialized() { byte isInitialized = memoizedIsInitialized; if (isInitialized == 1) return true; if (isInitialized == 0) return false; memoizedIsInitialized = 1; return true; } @java.lang.Override public void writeTo(com.google.protobuf.CodedOutputStream output) throws java.io.IOException { for (int i = 0; i < tensorboardTimeSeries_.size(); i++) { output.writeMessage(1, tensorboardTimeSeries_.get(i)); } unknownFields.writeTo(output); } @java.lang.Override public int getSerializedSize() { int size = memoizedSize; if (size != -1) return size; size = 0; for (int i = 0; i < tensorboardTimeSeries_.size(); i++) { size += com.google.protobuf.CodedOutputStream.computeMessageSize( 1, tensorboardTimeSeries_.get(i)); } size += unknownFields.getSerializedSize(); memoizedSize = size; return size; } @java.lang.Override public boolean equals(final java.lang.Object obj) { if (obj == this) { return true; } if (!(obj instanceof com.google.cloud.aiplatform.v1beta1.BatchCreateTensorboardTimeSeriesResponse)) { return super.equals(obj); } com.google.cloud.aiplatform.v1beta1.BatchCreateTensorboardTimeSeriesResponse other = (com.google.cloud.aiplatform.v1beta1.BatchCreateTensorboardTimeSeriesResponse) obj; if (!getTensorboardTimeSeriesList().equals(other.getTensorboardTimeSeriesList())) return false; if (!unknownFields.equals(other.unknownFields)) return false; return true; } @java.lang.Override public int hashCode() { if (memoizedHashCode != 0) { return memoizedHashCode; } int hash = 41; hash = (19 * hash) + getDescriptor().hashCode(); if (getTensorboardTimeSeriesCount() > 0) { hash = (37 * hash) + TENSORBOARD_TIME_SERIES_FIELD_NUMBER; hash = (53 * hash) + getTensorboardTimeSeriesList().hashCode(); } hash = (29 * hash) + unknownFields.hashCode(); memoizedHashCode = hash; return hash; } public static com.google.cloud.aiplatform.v1beta1.BatchCreateTensorboardTimeSeriesResponse parseFrom(java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.cloud.aiplatform.v1beta1.BatchCreateTensorboardTimeSeriesResponse parseFrom( java.nio.ByteBuffer data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.google.cloud.aiplatform.v1beta1.BatchCreateTensorboardTimeSeriesResponse parseFrom(com.google.protobuf.ByteString data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.cloud.aiplatform.v1beta1.BatchCreateTensorboardTimeSeriesResponse parseFrom( com.google.protobuf.ByteString data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.google.cloud.aiplatform.v1beta1.BatchCreateTensorboardTimeSeriesResponse parseFrom(byte[] data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.cloud.aiplatform.v1beta1.BatchCreateTensorboardTimeSeriesResponse parseFrom(byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.google.cloud.aiplatform.v1beta1.BatchCreateTensorboardTimeSeriesResponse parseFrom(java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input); } public static com.google.cloud.aiplatform.v1beta1.BatchCreateTensorboardTimeSeriesResponse parseFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException( PARSER, input, extensionRegistry); } public static com.google.cloud.aiplatform.v1beta1.BatchCreateTensorboardTimeSeriesResponse parseDelimitedFrom(java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(PARSER, input); } public static com.google.cloud.aiplatform.v1beta1.BatchCreateTensorboardTimeSeriesResponse parseDelimitedFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException( PARSER, input, extensionRegistry); } public static com.google.cloud.aiplatform.v1beta1.BatchCreateTensorboardTimeSeriesResponse parseFrom(com.google.protobuf.CodedInputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input); } public static com.google.cloud.aiplatform.v1beta1.BatchCreateTensorboardTimeSeriesResponse parseFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException( PARSER, input, extensionRegistry); } @java.lang.Override public Builder newBuilderForType() { return newBuilder(); } public static Builder newBuilder() { return DEFAULT_INSTANCE.toBuilder(); } public static Builder newBuilder( com.google.cloud.aiplatform.v1beta1.BatchCreateTensorboardTimeSeriesResponse prototype) { return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype); } @java.lang.Override public Builder toBuilder() { return this == DEFAULT_INSTANCE ? new Builder() : new Builder().mergeFrom(this); } @java.lang.Override protected Builder newBuilderForType(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { Builder builder = new Builder(parent); return builder; } /** * * * <pre> * Response message for [TensorboardService.BatchCreateTensorboardTimeSeries][google.cloud.aiplatform.v1beta1.TensorboardService.BatchCreateTensorboardTimeSeries]. * </pre> * * Protobuf type {@code google.cloud.aiplatform.v1beta1.BatchCreateTensorboardTimeSeriesResponse} */ public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder<Builder> implements // @@protoc_insertion_point(builder_implements:google.cloud.aiplatform.v1beta1.BatchCreateTensorboardTimeSeriesResponse) com.google.cloud.aiplatform.v1beta1.BatchCreateTensorboardTimeSeriesResponseOrBuilder { public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.google.cloud.aiplatform.v1beta1.TensorboardServiceProto .internal_static_google_cloud_aiplatform_v1beta1_BatchCreateTensorboardTimeSeriesResponse_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.google.cloud.aiplatform.v1beta1.TensorboardServiceProto .internal_static_google_cloud_aiplatform_v1beta1_BatchCreateTensorboardTimeSeriesResponse_fieldAccessorTable .ensureFieldAccessorsInitialized( com.google.cloud.aiplatform.v1beta1.BatchCreateTensorboardTimeSeriesResponse.class, com.google.cloud.aiplatform.v1beta1.BatchCreateTensorboardTimeSeriesResponse.Builder .class); } // Construct using // com.google.cloud.aiplatform.v1beta1.BatchCreateTensorboardTimeSeriesResponse.newBuilder() private Builder() { maybeForceBuilderInitialization(); } private Builder(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { super(parent); maybeForceBuilderInitialization(); } private void maybeForceBuilderInitialization() { if (com.google.protobuf.GeneratedMessageV3.alwaysUseFieldBuilders) { getTensorboardTimeSeriesFieldBuilder(); } } @java.lang.Override public Builder clear() { super.clear(); if (tensorboardTimeSeriesBuilder_ == null) { tensorboardTimeSeries_ = java.util.Collections.emptyList(); bitField0_ = (bitField0_ & ~0x00000001); } else { tensorboardTimeSeriesBuilder_.clear(); } return this; } @java.lang.Override public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() { return com.google.cloud.aiplatform.v1beta1.TensorboardServiceProto .internal_static_google_cloud_aiplatform_v1beta1_BatchCreateTensorboardTimeSeriesResponse_descriptor; } @java.lang.Override public com.google.cloud.aiplatform.v1beta1.BatchCreateTensorboardTimeSeriesResponse getDefaultInstanceForType() { return com.google.cloud.aiplatform.v1beta1.BatchCreateTensorboardTimeSeriesResponse .getDefaultInstance(); } @java.lang.Override public com.google.cloud.aiplatform.v1beta1.BatchCreateTensorboardTimeSeriesResponse build() { com.google.cloud.aiplatform.v1beta1.BatchCreateTensorboardTimeSeriesResponse result = buildPartial(); if (!result.isInitialized()) { throw newUninitializedMessageException(result); } return result; } @java.lang.Override public com.google.cloud.aiplatform.v1beta1.BatchCreateTensorboardTimeSeriesResponse buildPartial() { com.google.cloud.aiplatform.v1beta1.BatchCreateTensorboardTimeSeriesResponse result = new com.google.cloud.aiplatform.v1beta1.BatchCreateTensorboardTimeSeriesResponse(this); int from_bitField0_ = bitField0_; if (tensorboardTimeSeriesBuilder_ == null) { if (((bitField0_ & 0x00000001) != 0)) { tensorboardTimeSeries_ = java.util.Collections.unmodifiableList(tensorboardTimeSeries_); bitField0_ = (bitField0_ & ~0x00000001); } result.tensorboardTimeSeries_ = tensorboardTimeSeries_; } else { result.tensorboardTimeSeries_ = tensorboardTimeSeriesBuilder_.build(); } onBuilt(); return result; } @java.lang.Override public Builder clone() { return super.clone(); } @java.lang.Override public Builder setField( com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) { return super.setField(field, value); } @java.lang.Override public Builder clearField(com.google.protobuf.Descriptors.FieldDescriptor field) { return super.clearField(field); } @java.lang.Override public Builder clearOneof(com.google.protobuf.Descriptors.OneofDescriptor oneof) { return super.clearOneof(oneof); } @java.lang.Override public Builder setRepeatedField( com.google.protobuf.Descriptors.FieldDescriptor field, int index, java.lang.Object value) { return super.setRepeatedField(field, index, value); } @java.lang.Override public Builder addRepeatedField( com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) { return super.addRepeatedField(field, value); } @java.lang.Override public Builder mergeFrom(com.google.protobuf.Message other) { if (other instanceof com.google.cloud.aiplatform.v1beta1.BatchCreateTensorboardTimeSeriesResponse) { return mergeFrom( (com.google.cloud.aiplatform.v1beta1.BatchCreateTensorboardTimeSeriesResponse) other); } else { super.mergeFrom(other); return this; } } public Builder mergeFrom( com.google.cloud.aiplatform.v1beta1.BatchCreateTensorboardTimeSeriesResponse other) { if (other == com.google.cloud.aiplatform.v1beta1.BatchCreateTensorboardTimeSeriesResponse .getDefaultInstance()) return this; if (tensorboardTimeSeriesBuilder_ == null) { if (!other.tensorboardTimeSeries_.isEmpty()) { if (tensorboardTimeSeries_.isEmpty()) { tensorboardTimeSeries_ = other.tensorboardTimeSeries_; bitField0_ = (bitField0_ & ~0x00000001); } else { ensureTensorboardTimeSeriesIsMutable(); tensorboardTimeSeries_.addAll(other.tensorboardTimeSeries_); } onChanged(); } } else { if (!other.tensorboardTimeSeries_.isEmpty()) { if (tensorboardTimeSeriesBuilder_.isEmpty()) { tensorboardTimeSeriesBuilder_.dispose(); tensorboardTimeSeriesBuilder_ = null; tensorboardTimeSeries_ = other.tensorboardTimeSeries_; bitField0_ = (bitField0_ & ~0x00000001); tensorboardTimeSeriesBuilder_ = com.google.protobuf.GeneratedMessageV3.alwaysUseFieldBuilders ? getTensorboardTimeSeriesFieldBuilder() : null; } else { tensorboardTimeSeriesBuilder_.addAllMessages(other.tensorboardTimeSeries_); } } } this.mergeUnknownFields(other.unknownFields); onChanged(); return this; } @java.lang.Override public final boolean isInitialized() { return true; } @java.lang.Override public Builder mergeFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { com.google.cloud.aiplatform.v1beta1.BatchCreateTensorboardTimeSeriesResponse parsedMessage = null; try { parsedMessage = PARSER.parsePartialFrom(input, extensionRegistry); } catch (com.google.protobuf.InvalidProtocolBufferException e) { parsedMessage = (com.google.cloud.aiplatform.v1beta1.BatchCreateTensorboardTimeSeriesResponse) e.getUnfinishedMessage(); throw e.unwrapIOException(); } finally { if (parsedMessage != null) { mergeFrom(parsedMessage); } } return this; } private int bitField0_; private java.util.List<com.google.cloud.aiplatform.v1beta1.TensorboardTimeSeries> tensorboardTimeSeries_ = java.util.Collections.emptyList(); private void ensureTensorboardTimeSeriesIsMutable() { if (!((bitField0_ & 0x00000001) != 0)) { tensorboardTimeSeries_ = new java.util.ArrayList<com.google.cloud.aiplatform.v1beta1.TensorboardTimeSeries>( tensorboardTimeSeries_); bitField0_ |= 0x00000001; } } private com.google.protobuf.RepeatedFieldBuilderV3< com.google.cloud.aiplatform.v1beta1.TensorboardTimeSeries, com.google.cloud.aiplatform.v1beta1.TensorboardTimeSeries.Builder, com.google.cloud.aiplatform.v1beta1.TensorboardTimeSeriesOrBuilder> tensorboardTimeSeriesBuilder_; /** * * * <pre> * The created TensorboardTimeSeries. * </pre> * * <code> * repeated .google.cloud.aiplatform.v1beta1.TensorboardTimeSeries tensorboard_time_series = 1; * </code> */ public java.util.List<com.google.cloud.aiplatform.v1beta1.TensorboardTimeSeries> getTensorboardTimeSeriesList() { if (tensorboardTimeSeriesBuilder_ == null) { return java.util.Collections.unmodifiableList(tensorboardTimeSeries_); } else { return tensorboardTimeSeriesBuilder_.getMessageList(); } } /** * * * <pre> * The created TensorboardTimeSeries. * </pre> * * <code> * repeated .google.cloud.aiplatform.v1beta1.TensorboardTimeSeries tensorboard_time_series = 1; * </code> */ public int getTensorboardTimeSeriesCount() { if (tensorboardTimeSeriesBuilder_ == null) { return tensorboardTimeSeries_.size(); } else { return tensorboardTimeSeriesBuilder_.getCount(); } } /** * * * <pre> * The created TensorboardTimeSeries. * </pre> * * <code> * repeated .google.cloud.aiplatform.v1beta1.TensorboardTimeSeries tensorboard_time_series = 1; * </code> */ public com.google.cloud.aiplatform.v1beta1.TensorboardTimeSeries getTensorboardTimeSeries( int index) { if (tensorboardTimeSeriesBuilder_ == null) { return tensorboardTimeSeries_.get(index); } else { return tensorboardTimeSeriesBuilder_.getMessage(index); } } /** * * * <pre> * The created TensorboardTimeSeries. * </pre> * * <code> * repeated .google.cloud.aiplatform.v1beta1.TensorboardTimeSeries tensorboard_time_series = 1; * </code> */ public Builder setTensorboardTimeSeries( int index, com.google.cloud.aiplatform.v1beta1.TensorboardTimeSeries value) { if (tensorboardTimeSeriesBuilder_ == null) { if (value == null) { throw new NullPointerException(); } ensureTensorboardTimeSeriesIsMutable(); tensorboardTimeSeries_.set(index, value); onChanged(); } else { tensorboardTimeSeriesBuilder_.setMessage(index, value); } return this; } /** * * * <pre> * The created TensorboardTimeSeries. * </pre> * * <code> * repeated .google.cloud.aiplatform.v1beta1.TensorboardTimeSeries tensorboard_time_series = 1; * </code> */ public Builder setTensorboardTimeSeries( int index, com.google.cloud.aiplatform.v1beta1.TensorboardTimeSeries.Builder builderForValue) { if (tensorboardTimeSeriesBuilder_ == null) { ensureTensorboardTimeSeriesIsMutable(); tensorboardTimeSeries_.set(index, builderForValue.build()); onChanged(); } else { tensorboardTimeSeriesBuilder_.setMessage(index, builderForValue.build()); } return this; } /** * * * <pre> * The created TensorboardTimeSeries. * </pre> * * <code> * repeated .google.cloud.aiplatform.v1beta1.TensorboardTimeSeries tensorboard_time_series = 1; * </code> */ public Builder addTensorboardTimeSeries( com.google.cloud.aiplatform.v1beta1.TensorboardTimeSeries value) { if (tensorboardTimeSeriesBuilder_ == null) { if (value == null) { throw new NullPointerException(); } ensureTensorboardTimeSeriesIsMutable(); tensorboardTimeSeries_.add(value); onChanged(); } else { tensorboardTimeSeriesBuilder_.addMessage(value); } return this; } /** * * * <pre> * The created TensorboardTimeSeries. * </pre> * * <code> * repeated .google.cloud.aiplatform.v1beta1.TensorboardTimeSeries tensorboard_time_series = 1; * </code> */ public Builder addTensorboardTimeSeries( int index, com.google.cloud.aiplatform.v1beta1.TensorboardTimeSeries value) { if (tensorboardTimeSeriesBuilder_ == null) { if (value == null) { throw new NullPointerException(); } ensureTensorboardTimeSeriesIsMutable(); tensorboardTimeSeries_.add(index, value); onChanged(); } else { tensorboardTimeSeriesBuilder_.addMessage(index, value); } return this; } /** * * * <pre> * The created TensorboardTimeSeries. * </pre> * * <code> * repeated .google.cloud.aiplatform.v1beta1.TensorboardTimeSeries tensorboard_time_series = 1; * </code> */ public Builder addTensorboardTimeSeries( com.google.cloud.aiplatform.v1beta1.TensorboardTimeSeries.Builder builderForValue) { if (tensorboardTimeSeriesBuilder_ == null) { ensureTensorboardTimeSeriesIsMutable(); tensorboardTimeSeries_.add(builderForValue.build()); onChanged(); } else { tensorboardTimeSeriesBuilder_.addMessage(builderForValue.build()); } return this; } /** * * * <pre> * The created TensorboardTimeSeries. * </pre> * * <code> * repeated .google.cloud.aiplatform.v1beta1.TensorboardTimeSeries tensorboard_time_series = 1; * </code> */ public Builder addTensorboardTimeSeries( int index, com.google.cloud.aiplatform.v1beta1.TensorboardTimeSeries.Builder builderForValue) { if (tensorboardTimeSeriesBuilder_ == null) { ensureTensorboardTimeSeriesIsMutable(); tensorboardTimeSeries_.add(index, builderForValue.build()); onChanged(); } else { tensorboardTimeSeriesBuilder_.addMessage(index, builderForValue.build()); } return this; } /** * * * <pre> * The created TensorboardTimeSeries. * </pre> * * <code> * repeated .google.cloud.aiplatform.v1beta1.TensorboardTimeSeries tensorboard_time_series = 1; * </code> */ public Builder addAllTensorboardTimeSeries( java.lang.Iterable<? extends com.google.cloud.aiplatform.v1beta1.TensorboardTimeSeries> values) { if (tensorboardTimeSeriesBuilder_ == null) { ensureTensorboardTimeSeriesIsMutable(); com.google.protobuf.AbstractMessageLite.Builder.addAll(values, tensorboardTimeSeries_); onChanged(); } else { tensorboardTimeSeriesBuilder_.addAllMessages(values); } return this; } /** * * * <pre> * The created TensorboardTimeSeries. * </pre> * * <code> * repeated .google.cloud.aiplatform.v1beta1.TensorboardTimeSeries tensorboard_time_series = 1; * </code> */ public Builder clearTensorboardTimeSeries() { if (tensorboardTimeSeriesBuilder_ == null) { tensorboardTimeSeries_ = java.util.Collections.emptyList(); bitField0_ = (bitField0_ & ~0x00000001); onChanged(); } else { tensorboardTimeSeriesBuilder_.clear(); } return this; } /** * * * <pre> * The created TensorboardTimeSeries. * </pre> * * <code> * repeated .google.cloud.aiplatform.v1beta1.TensorboardTimeSeries tensorboard_time_series = 1; * </code> */ public Builder removeTensorboardTimeSeries(int index) { if (tensorboardTimeSeriesBuilder_ == null) { ensureTensorboardTimeSeriesIsMutable(); tensorboardTimeSeries_.remove(index); onChanged(); } else { tensorboardTimeSeriesBuilder_.remove(index); } return this; } /** * * * <pre> * The created TensorboardTimeSeries. * </pre> * * <code> * repeated .google.cloud.aiplatform.v1beta1.TensorboardTimeSeries tensorboard_time_series = 1; * </code> */ public com.google.cloud.aiplatform.v1beta1.TensorboardTimeSeries.Builder getTensorboardTimeSeriesBuilder(int index) { return getTensorboardTimeSeriesFieldBuilder().getBuilder(index); } /** * * * <pre> * The created TensorboardTimeSeries. * </pre> * * <code> * repeated .google.cloud.aiplatform.v1beta1.TensorboardTimeSeries tensorboard_time_series = 1; * </code> */ public com.google.cloud.aiplatform.v1beta1.TensorboardTimeSeriesOrBuilder getTensorboardTimeSeriesOrBuilder(int index) { if (tensorboardTimeSeriesBuilder_ == null) { return tensorboardTimeSeries_.get(index); } else { return tensorboardTimeSeriesBuilder_.getMessageOrBuilder(index); } } /** * * * <pre> * The created TensorboardTimeSeries. * </pre> * * <code> * repeated .google.cloud.aiplatform.v1beta1.TensorboardTimeSeries tensorboard_time_series = 1; * </code> */ public java.util.List< ? extends com.google.cloud.aiplatform.v1beta1.TensorboardTimeSeriesOrBuilder> getTensorboardTimeSeriesOrBuilderList() { if (tensorboardTimeSeriesBuilder_ != null) { return tensorboardTimeSeriesBuilder_.getMessageOrBuilderList(); } else { return java.util.Collections.unmodifiableList(tensorboardTimeSeries_); } } /** * * * <pre> * The created TensorboardTimeSeries. * </pre> * * <code> * repeated .google.cloud.aiplatform.v1beta1.TensorboardTimeSeries tensorboard_time_series = 1; * </code> */ public com.google.cloud.aiplatform.v1beta1.TensorboardTimeSeries.Builder addTensorboardTimeSeriesBuilder() { return getTensorboardTimeSeriesFieldBuilder() .addBuilder( com.google.cloud.aiplatform.v1beta1.TensorboardTimeSeries.getDefaultInstance()); } /** * * * <pre> * The created TensorboardTimeSeries. * </pre> * * <code> * repeated .google.cloud.aiplatform.v1beta1.TensorboardTimeSeries tensorboard_time_series = 1; * </code> */ public com.google.cloud.aiplatform.v1beta1.TensorboardTimeSeries.Builder addTensorboardTimeSeriesBuilder(int index) { return getTensorboardTimeSeriesFieldBuilder() .addBuilder( index, com.google.cloud.aiplatform.v1beta1.TensorboardTimeSeries.getDefaultInstance()); } /** * * * <pre> * The created TensorboardTimeSeries. * </pre> * * <code> * repeated .google.cloud.aiplatform.v1beta1.TensorboardTimeSeries tensorboard_time_series = 1; * </code> */ public java.util.List<com.google.cloud.aiplatform.v1beta1.TensorboardTimeSeries.Builder> getTensorboardTimeSeriesBuilderList() { return getTensorboardTimeSeriesFieldBuilder().getBuilderList(); } private com.google.protobuf.RepeatedFieldBuilderV3< com.google.cloud.aiplatform.v1beta1.TensorboardTimeSeries, com.google.cloud.aiplatform.v1beta1.TensorboardTimeSeries.Builder, com.google.cloud.aiplatform.v1beta1.TensorboardTimeSeriesOrBuilder> getTensorboardTimeSeriesFieldBuilder() { if (tensorboardTimeSeriesBuilder_ == null) { tensorboardTimeSeriesBuilder_ = new com.google.protobuf.RepeatedFieldBuilderV3< com.google.cloud.aiplatform.v1beta1.TensorboardTimeSeries, com.google.cloud.aiplatform.v1beta1.TensorboardTimeSeries.Builder, com.google.cloud.aiplatform.v1beta1.TensorboardTimeSeriesOrBuilder>( tensorboardTimeSeries_, ((bitField0_ & 0x00000001) != 0), getParentForChildren(), isClean()); tensorboardTimeSeries_ = null; } return tensorboardTimeSeriesBuilder_; } @java.lang.Override public final Builder setUnknownFields(final com.google.protobuf.UnknownFieldSet unknownFields) { return super.setUnknownFields(unknownFields); } @java.lang.Override public final Builder mergeUnknownFields( final com.google.protobuf.UnknownFieldSet unknownFields) { return super.mergeUnknownFields(unknownFields); } // @@protoc_insertion_point(builder_scope:google.cloud.aiplatform.v1beta1.BatchCreateTensorboardTimeSeriesResponse) } // @@protoc_insertion_point(class_scope:google.cloud.aiplatform.v1beta1.BatchCreateTensorboardTimeSeriesResponse) private static final com.google.cloud.aiplatform.v1beta1.BatchCreateTensorboardTimeSeriesResponse DEFAULT_INSTANCE; static { DEFAULT_INSTANCE = new com.google.cloud.aiplatform.v1beta1.BatchCreateTensorboardTimeSeriesResponse(); } public static com.google.cloud.aiplatform.v1beta1.BatchCreateTensorboardTimeSeriesResponse getDefaultInstance() { return DEFAULT_INSTANCE; } private static final com.google.protobuf.Parser<BatchCreateTensorboardTimeSeriesResponse> PARSER = new com.google.protobuf.AbstractParser<BatchCreateTensorboardTimeSeriesResponse>() { @java.lang.Override public BatchCreateTensorboardTimeSeriesResponse parsePartialFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return new BatchCreateTensorboardTimeSeriesResponse(input, extensionRegistry); } }; public static com.google.protobuf.Parser<BatchCreateTensorboardTimeSeriesResponse> parser() { return PARSER; } @java.lang.Override public com.google.protobuf.Parser<BatchCreateTensorboardTimeSeriesResponse> getParserForType() { return PARSER; } @java.lang.Override public com.google.cloud.aiplatform.v1beta1.BatchCreateTensorboardTimeSeriesResponse getDefaultInstanceForType() { return DEFAULT_INSTANCE; } }
apache-2.0
Longi94/bptf
app/src/main/java/com/tlongdev/bktf/component/InteractorComponent.java
2788
package com.tlongdev.bktf.component; import com.tlongdev.bktf.interactor.BackpackTfPriceHistoryInteractor; import com.tlongdev.bktf.interactor.GetCurrencyExchangeRatesInteractor; import com.tlongdev.bktf.interactor.GetSearchedUserDataInteractor; import com.tlongdev.bktf.interactor.GetUserDataInteractor; import com.tlongdev.bktf.interactor.LoadCalculatorItemsInteractor; import com.tlongdev.bktf.interactor.LoadCurrencyPricesInteractor; import com.tlongdev.bktf.interactor.LoadFavoritesInteractor; import com.tlongdev.bktf.interactor.LoadItemDetailsInteractor; import com.tlongdev.bktf.interactor.LoadSearchItemsInteractor; import com.tlongdev.bktf.interactor.LoadSelectorItemsInteractor; import com.tlongdev.bktf.interactor.LoadUnusualEffectsInteractor; import com.tlongdev.bktf.interactor.LoadUnusualHatCategoriesInteractor; import com.tlongdev.bktf.interactor.LoadUnusualsInteractor; import com.tlongdev.bktf.interactor.SearchUserInteractor; import com.tlongdev.bktf.interactor.Tf2UserBackpackInteractor; import com.tlongdev.bktf.interactor.TlongdevItemSchemaInteractor; import com.tlongdev.bktf.interactor.TlongdevPriceListInteractor; import com.tlongdev.bktf.module.BptfAppModule; import com.tlongdev.bktf.module.NetworkModule; import com.tlongdev.bktf.module.StorageModule; import javax.inject.Singleton; import dagger.Component; /** * @author Long * @since 2016. 03. 10. */ @Singleton @Component(modules = {BptfAppModule.class, NetworkModule.class, StorageModule.class}) public interface InteractorComponent { void inject(TlongdevPriceListInteractor tlongdevPriceListInteractor); void inject(TlongdevItemSchemaInteractor tlongdevItemSchemaInteractor); void inject(LoadCalculatorItemsInteractor loadCalculatorItemsInteractor); void inject(LoadFavoritesInteractor loadFavoritesInteractor); void inject(LoadUnusualHatCategoriesInteractor loadUnusualHatsInteractor); void inject(LoadUnusualEffectsInteractor loadUnusualEffectsInteractor); void inject(GetUserDataInteractor getUserDataInteractor); void inject(BackpackTfPriceHistoryInteractor backpackTfPriceHistoryInteractor); void inject(Tf2UserBackpackInteractor tf2UserBackpackInteractor); void inject(LoadCurrencyPricesInteractor loadCurrencyPricesInteractor); void inject(GetSearchedUserDataInteractor getSearchedUserDataInteractor); void inject(LoadUnusualsInteractor loadUnusualsInteractor); void inject(LoadSelectorItemsInteractor loadSelectorItemsInteractor); void inject(SearchUserInteractor searchUserInteractor); void inject(LoadSearchItemsInteractor loadSearchItemsInteractor); void inject(LoadItemDetailsInteractor loadItemDetailsInteractor); void inject(GetCurrencyExchangeRatesInteractor getCurrencyExchangeRatesInteractor); }
apache-2.0
motorina0/flowable-engine
modules/flowable-dmn-spring/src/main/java/org/flowable/dmn/spring/DmnEngineFactoryBean.java
2656
/* Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.flowable.dmn.spring; import org.flowable.dmn.engine.DmnEngine; import org.flowable.dmn.engine.DmnEngineConfiguration; import org.springframework.beans.BeansException; import org.springframework.beans.factory.DisposableBean; import org.springframework.beans.factory.FactoryBean; import org.springframework.context.ApplicationContext; import org.springframework.context.ApplicationContextAware; /** * @author Dave Syer * @author Tijs Rademakers * @author Joram Barrez * @author Josh Long */ public class DmnEngineFactoryBean implements FactoryBean<DmnEngine>, DisposableBean, ApplicationContextAware { protected DmnEngineConfiguration dmnEngineConfiguration; protected ApplicationContext applicationContext; protected DmnEngine dmnEngine; public void destroy() throws Exception { if (dmnEngine != null) { dmnEngine.close(); } } public void setApplicationContext(ApplicationContext applicationContext) throws BeansException { this.applicationContext = applicationContext; } public DmnEngine getObject() throws Exception { configureExternallyManagedTransactions(); this.dmnEngine = dmnEngineConfiguration.buildDmnEngine(); return this.dmnEngine; } protected void configureExternallyManagedTransactions() { if (dmnEngineConfiguration instanceof SpringDmnEngineConfiguration) { // remark: any config can be injected, so we cannot have SpringConfiguration as member SpringDmnEngineConfiguration engineConfiguration = (SpringDmnEngineConfiguration) dmnEngineConfiguration; if (engineConfiguration.getTransactionManager() != null) { dmnEngineConfiguration.setTransactionsExternallyManaged(true); } } } public Class<DmnEngine> getObjectType() { return DmnEngine.class; } public boolean isSingleton() { return true; } public DmnEngineConfiguration getDmnEngineConfiguration() { return dmnEngineConfiguration; } public void setDmnEngineConfiguration(DmnEngineConfiguration dmnEngineConfiguration) { this.dmnEngineConfiguration = dmnEngineConfiguration; } }
apache-2.0
nextreports/nextreports-designer
src/ro/nextreports/designer/ReportLayoutPanel.java
14424
/* * 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 ro.nextreports.designer; import java.awt.Color; import java.awt.Component; import java.awt.Dimension; import java.awt.GridBagConstraints; import java.awt.GridBagLayout; import java.awt.Insets; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.InputEvent; import java.awt.event.ItemEvent; import java.awt.event.ItemListener; import java.awt.event.MouseWheelEvent; import java.awt.event.MouseWheelListener; import javax.swing.AbstractAction; import javax.swing.Action; import javax.swing.Box; import javax.swing.BoxLayout; import javax.swing.JCheckBox; import javax.swing.JComboBox; import javax.swing.JLabel; import javax.swing.JList; import javax.swing.JOptionPane; import javax.swing.JPanel; import javax.swing.JSpinner; import javax.swing.JTextField; import javax.swing.JToggleButton; import javax.swing.JToolBar; import javax.swing.SpinnerModel; import javax.swing.SpinnerNumberModel; import javax.swing.event.ChangeEvent; import javax.swing.event.ChangeListener; import javax.swing.event.EventListenerList; import javax.swing.plaf.basic.BasicComboBoxRenderer; import com.jgoodies.looks.HeaderStyle; import com.jgoodies.looks.Options; import ro.nextreports.designer.action.report.layout.cell.FormatPainterAction; import ro.nextreports.designer.action.report.layout.cell.FormatPickerAction; import ro.nextreports.designer.action.report.layout.export.ExportToCsvAction; import ro.nextreports.designer.action.report.layout.export.ExportToDocxAction; import ro.nextreports.designer.action.report.layout.export.ExportToExcelAction; import ro.nextreports.designer.action.report.layout.export.ExportToExcelXAction; import ro.nextreports.designer.action.report.layout.export.ExportToHtmlAction; import ro.nextreports.designer.action.report.layout.export.ExportToJSONFullAction; import ro.nextreports.designer.action.report.layout.export.ExportToJSONSimpleAction; import ro.nextreports.designer.action.report.layout.export.ExportToPdfAction; import ro.nextreports.designer.action.report.layout.export.ExportToRtfAction; import ro.nextreports.designer.action.report.layout.export.ExportToTsvAction; import ro.nextreports.designer.action.report.layout.export.ExportToTxtAction; import ro.nextreports.designer.action.report.layout.export.ExportToXmlAction; import ro.nextreports.designer.datasource.DataSource; import ro.nextreports.designer.datasource.DefaultDataSourceManager; import ro.nextreports.designer.querybuilder.RuntimeParametersPanel; import ro.nextreports.designer.template.report.action.ApplyTemplateAction; import ro.nextreports.designer.template.report.action.ExtractTemplateAction; import ro.nextreports.designer.ui.IntegerTextField; import ro.nextreports.designer.ui.zoom.ZoomEvent; import ro.nextreports.designer.ui.zoom.ZoomEventListener; import ro.nextreports.designer.util.DropDownButton; import ro.nextreports.designer.util.I18NSupport; import ro.nextreports.designer.util.ImageUtil; import ro.nextreports.designer.util.SwingUtil; /** * @author Decebal Suiu */ public class ReportLayoutPanel extends JPanel implements ChangeListener { public static final int PANEL_WIDTH = 700; public static final int PANEL_HEIGHT = 500; private ReportGridPanel reportGridPanel; private JToggleButton widthButton; private JCheckBox maxRecordsCheckBox; private JTextField maxRecordsTextField; private Dimension dim = new Dimension(40, 20); private Dimension spinnerDim = new Dimension(50, 20); private Dimension comboDim = new Dimension(100, 20); private JComboBox dataSourcesComboBox; private int minZoomValue = 50; private int maxZoomValue = 300; private int zoomDelta = 10; // initial value ,min,max, step private SpinnerModel spinnerModel = new SpinnerNumberModel(100, minZoomValue, maxZoomValue, zoomDelta); private EventListenerList zoomListenerList = new EventListenerList(); public ReportLayoutPanel() { super(); initComponents(); initZoomListeners(); } public ReportGridPanel getReportGridPanel() { return reportGridPanel; } public ReportGrid getReportGrid() { return reportGridPanel.getGrid(); } public void refresh() { getReportGridPanel().setReportLayout(LayoutHelper.getReportLayout()); getReportGrid().getSelectionModel().clearSelection(); } private void initComponents() { setLayout(new GridBagLayout()); add(createToolBar(), new GridBagConstraints(0, 0, 1, 1, 1.0, 0.0, GridBagConstraints.WEST, GridBagConstraints.HORIZONTAL, new Insets(0, 0, 0, 0), 0, 0)); reportGridPanel = new ReportGridPanel(0, 0); add(reportGridPanel, new GridBagConstraints(0, 1, 1, 1, 1.0, 1.0, GridBagConstraints.WEST, GridBagConstraints.BOTH, new Insets(0, 0, 0, 0), 0, 0)); setPreferredSize(new Dimension(PANEL_WIDTH, PANEL_HEIGHT)); } private void initZoomListeners() { addZoomListener(reportGridPanel); // zoom with CTRL & mouse wheel reportGridPanel.addMouseWheelListener(new MouseWheelListener() { public void mouseWheelMoved(MouseWheelEvent e) { if ((e.getModifiers() & InputEvent.CTRL_MASK) == InputEvent.CTRL_MASK) { int clicks = e.getWheelRotation(); int zoomValue; if (clicks < 0) { // zoom in zoomValue = ((Integer) spinnerModel.getValue()).intValue() + zoomDelta; } else { // zoom out zoomValue = ((Integer) spinnerModel.getValue()).intValue() - zoomDelta; } if (zoomValue < minZoomValue) { zoomValue = minZoomValue; } else if (zoomValue > maxZoomValue) { zoomValue = maxZoomValue; } spinnerModel.setValue(zoomValue); Integer percentage = (Integer) spinnerModel.getValue(); ZoomEvent zoomEvent = new ZoomEvent(percentage / 100f); fireZoomEvent(zoomEvent); } } }); } public void updateUseSize() { widthButton.setSelected(LayoutHelper.getReportLayout().isUseSize()); } public void removeEditor() { reportGridPanel.getGrid().removeEditor(); } private JToolBar createToolBar() { JToolBar toolBar = new JToolBar(); toolBar.putClientProperty("JToolBar.isRollover", Boolean.TRUE); // hide // buttons // borders toolBar.putClientProperty(Options.HEADER_STYLE_KEY, HeaderStyle.BOTH); toolBar.setBorderPainted(false); Action widthAction = new AbstractAction() { public void actionPerformed(ActionEvent event) { if (!widthButton.isSelected()) { int option = JOptionPane.showConfirmDialog(Globals.getMainFrame(), I18NSupport.getString("width.action.loose"), "", JOptionPane.YES_NO_OPTION); if (option != JOptionPane.YES_OPTION) { widthButton.setSelected(true); return; } } LayoutHelper.getReportLayout().setUseSize(widthButton.isSelected()); // repaint headers to show/hide ruler reportGridPanel.repaintHeaders(); ReportLayoutUtil.updateColumnWidth(Globals.getReportGrid()); if (!widthButton.isSelected()) { Globals.getReportDesignerPanel().refresh(); } } }; widthAction.putValue(Action.SMALL_ICON, ImageUtil.getImageIcon("width")); widthAction.putValue(Action.SHORT_DESCRIPTION, I18NSupport.getString("width.action")); widthButton = new JToggleButton(widthAction); toolBar.add(widthButton); SwingUtil.addCustomSeparator(toolBar); toolBar.add(new FormatPickerAction()); toolBar.add(new FormatPainterAction()); toolBar.add(new ApplyTemplateAction(true)); toolBar.add(new ExtractTemplateAction()); SwingUtil.addCustomSeparator(toolBar); toolBar.add(Globals.getReportUndoManager().getUndoAction()); toolBar.add(Globals.getReportUndoManager().getRedoAction()); SwingUtil.addCustomSeparator(toolBar); JPanel previewPanel = new JPanel(); previewPanel.setLayout(new BoxLayout(previewPanel, BoxLayout.X_AXIS)); previewPanel.setOpaque(false); maxRecordsCheckBox = new JCheckBox(I18NSupport.getString("max.records")); maxRecordsCheckBox.setOpaque(false); maxRecordsCheckBox.addItemListener(new ItemListener() { public void itemStateChanged(ItemEvent e) { if (e.getStateChange() == ItemEvent.SELECTED) { maxRecordsTextField.setEditable(true); } else { maxRecordsTextField.setEditable(false); } } }); previewPanel.add(maxRecordsCheckBox); previewPanel.add(Box.createHorizontalStrut(5)); maxRecordsTextField = new IntegerTextField(); maxRecordsTextField.setText("10"); maxRecordsTextField.setEditable(false); maxRecordsTextField.setPreferredSize(dim); maxRecordsTextField.setMinimumSize(dim); maxRecordsTextField.setMaximumSize(dim); previewPanel.add(maxRecordsTextField); dataSourcesComboBox = new JComboBox(); dataSourcesComboBox.setPreferredSize(comboDim); dataSourcesComboBox.setMinimumSize(comboDim); dataSourcesComboBox.setMaximumSize(comboDim); dataSourcesComboBox.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { // must reset parameters values because for a different data // source // we may have different values. RuntimeParametersPanel.resetParametersValues(); } }); previewPanel.add(Box.createHorizontalStrut(5)); previewPanel.add(dataSourcesComboBox); previewPanel.add(Box.createHorizontalStrut(5)); toolBar.add(previewPanel); DropDownButton dropDownButton = new DropDownButton(); dropDownButton.getPopupMenu().add(new ExportToExcelAction(null)); dropDownButton.getPopupMenu().add(new ExportToExcelXAction(null)); dropDownButton.getPopupMenu().add(new ExportToPdfAction(null)); dropDownButton.getPopupMenu().add(new ExportToDocxAction(null)); dropDownButton.getPopupMenu().add(new ExportToRtfAction(null)); dropDownButton.getPopupMenu().add(new ExportToCsvAction(null)); dropDownButton.getPopupMenu().add(new ExportToTsvAction(null)); dropDownButton.getPopupMenu().add(new ExportToXmlAction(null)); dropDownButton.getPopupMenu().add(new ExportToTxtAction(null)); dropDownButton.getPopupMenu().add(new ExportToJSONSimpleAction(null)); dropDownButton.getPopupMenu().add(new ExportToJSONFullAction(null)); dropDownButton.setAction(new ExportToHtmlAction(null)); dropDownButton.addToToolBar(toolBar); JSpinner zoomSpinner = new JSpinner(spinnerModel); zoomSpinner.setPreferredSize(spinnerDim); zoomSpinner.setMinimumSize(spinnerDim); zoomSpinner.setMaximumSize(spinnerDim); zoomSpinner.addChangeListener(this); JPanel zPanel = new JPanel(); zPanel.setLayout(new BoxLayout(zPanel, BoxLayout.X_AXIS)); zPanel.setOpaque(false); zPanel.add(Box.createHorizontalGlue()); zPanel.add(new JLabel(I18NSupport.getString("zoom"))); zPanel.add(Box.createHorizontalStrut(2)); zPanel.add(zoomSpinner); zPanel.add(Box.createHorizontalStrut(2)); zPanel.add(new JLabel("%")); zPanel.add(Box.createHorizontalStrut(5)); toolBar.add(zPanel); return toolBar; } // spinner change event public void stateChanged(ChangeEvent e) { Integer percentage = (Integer) spinnerModel.getValue(); ZoomEvent zoomEvent = new ZoomEvent(percentage / 100f); fireZoomEvent(zoomEvent); } class DataSourceComboBoxRenderer extends BasicComboBoxRenderer { public Component getListCellRendererComponent(JList list, Object value, int index, boolean isSelected, boolean cellHasFocus) { if (isSelected) { setBackground(list.getSelectionBackground()); setForeground(list.getSelectionForeground()); if (-1 < index) { list.setToolTipText(value.toString()); } } else { setForeground(list.getForeground()); if (DefaultDataSourceManager.getInstance().getConnectedDataSource().getName().equals(value)) { setBackground(new Color(204, 255, 255)); } else { setBackground(list.getBackground()); } } setFont(list.getFont()); setText((value == null) ? "" : value.toString()); return this; } } // 0 means all records public int getRecords() { if (maxRecordsCheckBox.isSelected()) { int records; try { records = Integer.parseInt(maxRecordsTextField.getText()); } catch (NumberFormatException nfe) { records = 0; } return records; } else { return 0; } } public void selectConnectedDataSource() { DataSource connectedDS = DefaultDataSourceManager.getInstance().getConnectedDataSource(); if (connectedDS == null) { return; } dataSourcesComboBox.removeAllItems(); dataSourcesComboBox.setRenderer(new DataSourceComboBoxRenderer()); for (DataSource ds : DefaultDataSourceManager.getInstance().getDataSources(connectedDS.getDriver())) { dataSourcesComboBox.addItem(ds.getName()); } dataSourcesComboBox.setSelectedItem(connectedDS.getName()); } public DataSource getRunDataSource() { if (dataSourcesComboBox.getSelectedItem() == null) { return DefaultDataSourceManager.getInstance().getConnectedDataSource(); } else { return DefaultDataSourceManager.getInstance().getDataSource((String) dataSourcesComboBox.getSelectedItem()); } } public void resetRunDataSource() { if (dataSourcesComboBox != null) { dataSourcesComboBox.removeAllItems(); } } private void addZoomListener(ZoomEventListener listener) { zoomListenerList.add(ZoomEventListener.class, listener); } private void removeZoomListener(ZoomEventListener listener) { zoomListenerList.remove(ZoomEventListener.class, listener); } private void fireZoomEvent(ZoomEvent evt) { Object[] listeners = zoomListenerList.getListenerList(); // Each listener occupies two elements - the first is the listener class // and the second is the listener instance for (int i = 0; i < listeners.length; i += 2) { if (listeners[i] == ZoomEventListener.class) { ((ZoomEventListener) listeners[i + 1]).notifyZoom(evt); } } } }
apache-2.0
saulbein/web3j
core/src/main/java/org/web3j/abi/FunctionReturnDecoder.java
5139
package org.web3j.abi; import java.util.ArrayList; import java.util.Collections; import java.util.List; import org.web3j.abi.datatypes.Array; import org.web3j.abi.datatypes.Bytes; import org.web3j.abi.datatypes.BytesType; import org.web3j.abi.datatypes.DynamicArray; import org.web3j.abi.datatypes.DynamicBytes; import org.web3j.abi.datatypes.StaticArray; import org.web3j.abi.datatypes.Type; import org.web3j.abi.datatypes.Utf8String; import org.web3j.abi.datatypes.generated.Bytes32; import org.web3j.utils.Numeric; import static org.web3j.abi.TypeDecoder.MAX_BYTE_LENGTH_FOR_HEX_STRING; /** * Decodes values returned by function or event calls. */ public class FunctionReturnDecoder { private FunctionReturnDecoder() { } /** * Decode ABI encoded return values from smart contract function call. * * @param rawInput ABI encoded input * @param outputParameters list of return types as {@link TypeReference} * @return {@link List} of values returned by function, {@link Collections#emptyList()} if * invalid response */ public static List<Type> decode( String rawInput, List<TypeReference<Type>> outputParameters) { String input = Numeric.cleanHexPrefix(rawInput); if (input.isEmpty()) { return Collections.emptyList(); } else { return build(input, outputParameters); } } /** * <p>Decodes an indexed parameter associated with an event. Indexed parameters are individually * encoded, unlike non-indexed parameters which are encoded as per ABI-encoded function * parameters and return values.</p> * * <p>If any of the following types are indexed, the Keccak-256 hashes of the values are * returned instead. These are returned as a bytes32 value.</p> * * <ul> * <li>Arrays</li> * <li>Strings</li> * <li>Bytes</li> * </ul> * * <p>See the * <a href="http://solidity.readthedocs.io/en/latest/contracts.html#events"> * Solidity documentation</a> for further information.</p> * * @param rawInput ABI encoded input * @param typeReference of expected result type * @param <T> type of TypeReference * @return the decode value */ public static <T extends Type> Type decodeIndexedValue( String rawInput, TypeReference<T> typeReference) { String input = Numeric.cleanHexPrefix(rawInput); try { Class<T> type = typeReference.getClassType(); if (Bytes.class.isAssignableFrom(type)) { return TypeDecoder.decodeBytes(input, (Class<Bytes>) Class.forName(type.getName())); } else if (Array.class.isAssignableFrom(type) || BytesType.class.isAssignableFrom(type) || Utf8String.class.isAssignableFrom(type)) { return TypeDecoder.decodeBytes(input, Bytes32.class); } else { return TypeDecoder.decode(input, type); } } catch (ClassNotFoundException e) { throw new UnsupportedOperationException("Invalid class reference provided", e); } } private static List<Type> build( String input, List<TypeReference<Type>> outputParameters) { List<Type> results = new ArrayList<>(outputParameters.size()); int offset = 0; for (TypeReference<?> typeReference:outputParameters) { try { Class<Type> type = (Class<Type>) typeReference.getClassType(); int hexStringDataOffset = getDataOffset(input, offset, type); Type result; if (DynamicArray.class.isAssignableFrom(type)) { result = TypeDecoder.decodeDynamicArray( input, hexStringDataOffset, typeReference); offset += MAX_BYTE_LENGTH_FOR_HEX_STRING; } else if (StaticArray.class.isAssignableFrom(type)) { int length = ((TypeReference.StaticArrayTypeReference) typeReference).getSize(); result = TypeDecoder.decodeStaticArray( input, hexStringDataOffset, typeReference, length); offset += length * MAX_BYTE_LENGTH_FOR_HEX_STRING; } else { result = TypeDecoder.decode(input, hexStringDataOffset, type); offset += MAX_BYTE_LENGTH_FOR_HEX_STRING; } results.add(result); } catch (ClassNotFoundException e) { throw new UnsupportedOperationException("Invalid class reference provided", e); } } return results; } private static <T extends Type> int getDataOffset(String input, int offset, Class<T> type) { if (DynamicBytes.class.isAssignableFrom(type) || Utf8String.class.isAssignableFrom(type) || DynamicArray.class.isAssignableFrom(type)) { return TypeDecoder.decodeUintAsInt(input, offset) << 1; } else { return offset; } } }
apache-2.0
tatemura/strudel
workload/src/main/java/com/nec/strudel/workload/worker/WorkGroup.java
12867
/******************************************************************************* * Copyright 2015, 2016 Junichi Tatemura * * 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.nec.strudel.workload.worker; import java.util.ArrayList; import java.util.List; import java.util.concurrent.Callable; import java.util.concurrent.ExecutionException; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.Future; import java.util.concurrent.atomic.AtomicLong; import javax.json.JsonObject; import org.apache.log4j.Logger; import com.nec.strudel.exceptions.WorkloadException; import com.nec.strudel.metrics.Report; import com.nec.strudel.workload.com.Caller; import com.nec.strudel.workload.job.WorkRequest; import com.nec.strudel.workload.server.WorkerClient; import com.nec.strudel.workload.util.TimeUtil; public class WorkGroup implements Caller { private static final AtomicLong LOCAL_ID_COUNTER = new AtomicLong(); protected static String newWorkId() { return "local." + Long.toHexString( LOCAL_ID_COUNTER.getAndIncrement()); } public static WorkGroup create(WorkRequest... workRequests) { ExecutorService exec = Executors.newCachedThreadPool(); List<Future<InitResult>> res = new ArrayList<Future<InitResult>>(); for (WorkRequest w : workRequests) { res.add(exec.submit(new Initialize(w))); } Worker[] workers = new Worker[workRequests.length]; for (int i = 0; i < workRequests.length; i++) { Future<InitResult> resultFuture = res.get(i); try { InitResult initRes = resultFuture.get(); workers[i] = initRes.getWorker(); } catch (InterruptedException ex) { LOGGER.error("initialization interrupted", ex); throw new WorkloadException( "initialization interrupted", ex); } catch (ExecutionException ex) { LOGGER.error("failed to initialize", ex); throw new WorkloadException( "failed to initialize", ex); } } return new WorkGroup(workers, exec); } private static final Logger LOGGER = Logger.getLogger(WorkGroup.class); private final Worker[] workers; private final ExecutorService exec; public WorkGroup(Worker[] works, ExecutorService exec) { this.workers = works; this.exec = exec; } public Worker[] getWorkers() { return workers; } public int size() { return workers.length; } public void close() { exec.shutdown(); } public <T> List<Future<T>> call(List<? extends Callable<T>> calls) { List<Future<T>> res = new ArrayList<Future<T>>(); for (Callable<T> c : calls) { res.add(exec.submit(c)); } return res; } public void operate(String name, JsonObject arg) throws InterruptedException { List<Future<CommandResult>> res = new ArrayList<Future<CommandResult>>(); for (Worker w : workers) { res.add(exec.submit( new Operate(w, name, arg))); } waitResults(res); } public void start() throws InterruptedException { List<Future<CommandResult>> res = new ArrayList<Future<CommandResult>>(); for (Worker w : workers) { res.add(exec.submit(new Start(w))); } waitResults(res); } public void stop() throws InterruptedException { List<Future<CommandResult>> res = new ArrayList<Future<CommandResult>>(); for (Worker w : workers) { res.add(exec.submit(new Stop(w))); } waitResults(res); } public void terminate() throws InterruptedException { List<Future<CommandResult>> res = new ArrayList<Future<CommandResult>>(); for (Worker w : workers) { res.add(exec.submit(new Terminate(w))); } waitResults(res); } public Report getReport() throws InterruptedException { List<Future<Report>> res = new ArrayList<Future<Report>>(); for (Worker w : workers) { res.add(exec.submit( new GetReport(w))); } Report[] reports = new Report[workers.length]; for (int i = 0; i < reports.length; i++) { try { reports[i] = res.get(i).get(); } catch (ExecutionException ex) { LOGGER.error("failed to get report", ex); throw new WorkloadException( "failed to get a report", ex); } } return Report.aggregate(reports); } public List<String> getStates() throws InterruptedException { List<Future<String>> res = new ArrayList<Future<String>>(); for (Worker w : workers) { res.add(exec.submit(new GetState(w))); } List<String> states = new ArrayList<String>(res.size()); for (Future<String> s : res) { try { states.add(s.get()); } catch (ExecutionException ex) { LOGGER.error("failed to get state", ex); throw new WorkloadException( "failed to get a state", ex); } } return states; } public String[] getStates(boolean[] mask) throws InterruptedException { String[] states = new String[workers.length]; @SuppressWarnings("unchecked") Future<String>[] futures = new Future[workers.length]; for (int i = 0; i < workers.length; i++) { if (mask[i]) { futures[i] = exec.submit( new GetState(workers[i])); } } for (int i = 0; i < workers.length; i++) { try { states[i] = futures[i].get(); } catch (ExecutionException ex) { LOGGER.error("failed to get state", ex); throw new WorkloadException( "failed to get a state", ex); } } return states; } private static final int SKEW_RATIO = 2; private static final int SLOW_TIME = 10000; private void waitResults(List<Future<CommandResult>> res) throws InterruptedException { long maxTime = 0; long timeSum = 0; String id = ""; int idx = 0; for (Future<CommandResult> r : res) { try { CommandResult cr = r.get(); long time = cr.getTime(); timeSum += time; if (time > maxTime) { maxTime = time; id = cr.getId(); } idx++; } catch (ExecutionException ex) { String workId = workers[idx].getWorkId(); LOGGER.error( "failed to execute a command at " + workId, ex); throw new WorkloadException( "failed to execute a command at " + workId, ex); } } int count = res.size(); if (count > 0) { long avg = timeSum / count; if (avg > 0 && maxTime > SLOW_TIME && maxTime / avg > SKEW_RATIO) { LOGGER.warn("slow command:" + id + " (" + TimeUtil.formatTimeMs(maxTime) + " avg = " + TimeUtil.formatTimeMs(avg)); } else { LOGGER.debug("slow command:" + id + " (" + TimeUtil.formatTimeMs(maxTime) + " avg = " + TimeUtil.formatTimeMs(avg)); } } } static class GetReport implements Callable<Report> { private final Worker worker; public GetReport(Worker worker) { this.worker = worker; } @Override public Report call() throws Exception { return worker.getReport(); } } static class CommandResult { private final String id; private final long time; CommandResult(String id, long time) { this.id = id; this.time = time; } public long getTime() { return time; } public String getId() { return id; } } static class InitResult extends CommandResult { private final Worker worker; InitResult(String id, Worker worker, long time) { super(id, time); this.worker = worker; } public Worker getWorker() { return worker; } } static class Initialize implements Callable<InitResult> { private final WorkRequest work; public Initialize(WorkRequest workRequest) { this.work = workRequest; } @Override public InitResult call() { long start = System.currentTimeMillis(); Worker worker = createWorker(); long time = System.currentTimeMillis() - start; return new InitResult(worker.getWorkId(), worker, time); } private Worker createWorker() { if (work.getNode().isLocal()) { return LocalWorker.create(newWorkId(), work); } else { WorkerClient client = new WorkerClient(); return client.create(work); } } } static class Operate implements Callable<CommandResult> { private final Worker worker; private final String name; private final JsonObject arg; Operate(Worker worker, String name, JsonObject arg) { this.worker = worker; this.name = name; this.arg = arg; } @Override public CommandResult call() throws Exception { long start = System.currentTimeMillis(); worker.operate(name, arg); long time = System.currentTimeMillis() - start; return new CommandResult(worker.getWorkId(), time); } } static class Start implements Callable<CommandResult> { private final Worker worker; Start(Worker worker) { this.worker = worker; } @Override public CommandResult call() throws Exception { long start = System.currentTimeMillis(); worker.start(); long time = System.currentTimeMillis() - start; return new CommandResult(worker.getWorkId(), time); } } static class Stop implements Callable<CommandResult> { private final Worker worker; Stop(Worker worker) { this.worker = worker; } @Override public CommandResult call() throws Exception { long start = System.currentTimeMillis(); worker.stop(); long time = System.currentTimeMillis() - start; return new CommandResult(worker.getWorkId(), time); } } static class Terminate implements Callable<CommandResult> { private final Worker worker; Terminate(Worker worker) { this.worker = worker; } @Override public CommandResult call() throws Exception { long start = System.currentTimeMillis(); worker.terminate(); long time = System.currentTimeMillis() - start; return new CommandResult(worker.getWorkId(), time); } } static class GetState implements Callable<String> { private final Worker worker; GetState(Worker worker) { this.worker = worker; } @Override public String call() throws Exception { return worker.getState(); } } }
apache-2.0
danielkocsis/playground
src/main/java/com/treasurehunter/server/persistence/dao/BaseDAO.java
2205
package com.treasurehunter.server.persistence.dao; import com.google.appengine.api.datastore.Key; import com.treasurehunter.server.persistence.PersistenceManagerFactoryUtil; import com.treasurehunter.server.persistence.model.DataStoreModel; import javax.jdo.PersistenceManager; import javax.jdo.PersistenceManagerFactory; import javax.jdo.Query; import javax.jdo.Transaction; import java.util.List; /** * @author Daniel Kocsis */ public abstract class BaseDAO<T extends DataStoreModel> implements DAO<T> { public T create(T model) { PersistenceManager persistenceManager = getPersistenceManager(); try { return persistenceManager.makePersistent(model); } finally { persistenceManager.close(); } } public void delete(T model) { PersistenceManager persistenceManager = getPersistenceManager(); try { persistenceManager.deletePersistent(model); } finally { persistenceManager.close(); } } public List<T> findAll(Class<T> clazz) { PersistenceManager persistenceManager = getPersistenceManager(); List entries; Query query = persistenceManager.newQuery(clazz); query.setFilter("flgNull == \"N\""); query.setOrdering("id asc"); try { entries = (List) query.execute(); return entries; } finally { persistenceManager.close(); } } @Override public T update(T model) { PersistenceManager persistenceManager = getPersistenceManager(); Transaction transaction = persistenceManager.currentTransaction(); try { transaction.begin(); model = persistenceManager.makePersistent(model); transaction.commit(); } finally { if (transaction.isActive()) { transaction.rollback(); } } return model; } protected T getModelByKey(Class<T> clazz, Key key) { PersistenceManager persistenceManager = getPersistenceManager(); try { T existingModel = persistenceManager.getObjectById(clazz, key); return persistenceManager.detachCopy(existingModel); } finally { persistenceManager.close(); } } protected PersistenceManager getPersistenceManager() { PersistenceManagerFactory pmf = PersistenceManagerFactoryUtil.getPersistenceManagerFactory(); return pmf.getPersistenceManager(); } }
apache-2.0
weblyzard/weblyzard_api
src/java/test/com/weblyzard/api/client/integration/RecognyzeClientIT.java
3440
package com.weblyzard.api.client.integration; import static org.junit.jupiter.api.Assertions.assertNotNull; import static org.junit.jupiter.api.Assertions.assertTrue; import static org.junit.jupiter.api.Assumptions.assumeTrue; import java.io.File; import java.io.IOException; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import com.fasterxml.jackson.databind.ObjectMapper; import com.weblyzard.api.client.RecognyzeClient; import com.weblyzard.api.client.WebserviceClientConfig; import com.weblyzard.api.model.annotation.Annotation; import com.weblyzard.api.model.document.Document; public class RecognyzeClientIT extends TestClientBase { private static final ObjectMapper objectMapper = new ObjectMapper(); private static final String profile = "JOBCOCKPIT"; private static final String PSALMS_DOCS_WEBLYZARDFORMAT = "resources/reference/weblyzard-example.json"; private static Document loadDocument() throws IOException { return objectMapper.readValue(new File(PSALMS_DOCS_WEBLYZARDFORMAT), Document.class); } private RecognyzeClient recognizeClient; @BeforeEach public void testLoadProfile() { recognizeClient = new RecognyzeClient(new WebserviceClientConfig()); assumeTrue(weblyzardServiceAvailable(recognizeClient)); boolean profileLoaded = recognizeClient.loadProfile(profile); assumeTrue(profileLoaded); } @Test public void testSearchDocument() throws IOException { assumeTrue(weblyzardServiceAvailable(recognizeClient)); Document request = loadDocument(); List<Annotation> result = recognizeClient.searchDocument(profile, request).getAnnotations(); // TODO: validate that the resultset is not empty (compose a small test // profile, find a nice sentence to test) assertNotNull(result); assertTrue(result.size() >= 1); } @Test public void testSearchDocuments() throws IOException { assumeTrue(weblyzardServiceAvailable(recognizeClient)); Set<Document> request = new HashSet<>(); Document document = loadDocument(); document.setId("1"); request.add(document); List<Document> result = recognizeClient.searchDocuments(profile, request); // TODO: validate that the resultset is not empty (compose a small test // profile, find a nice sentence to test) assertNotNull(result); assertTrue(result.size() >= 1); } @Test public void testSearchDocumentsWithoutId() throws IOException { assumeTrue(weblyzardServiceAvailable(recognizeClient)); Set<Document> request = new HashSet<>(); request.add(loadDocument()); List<Document> result = recognizeClient.searchDocuments(profile, request); // TODO: validate that the resultset is not empty (compose a small test // profile, find a nice sentence to test) assertNotNull(result); assertTrue(result.size() > 0); } @Test public void testStatus() { assumeTrue(weblyzardServiceAvailable(recognizeClient)); Map<String, Object> result = recognizeClient.status(); // TODO: validate that the resultset is not empty (compose a small test // profile, find a nice sentence to test) assertNotNull(result); } }
apache-2.0
googleads/googleads-java-lib
modules/dfp_appengine/src/main/java/com/google/api/ads/admanager/jaxws/v202108/AdExchangeCreative.java
3680
// 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 // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package com.google.api.ads.admanager.jaxws.v202108; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlType; /** * * An Ad Exchange dynamic allocation creative. * * * <p>Java class for AdExchangeCreative complex type. * * <p>The following schema fragment specifies the expected content contained within this class. * * <pre> * &lt;complexType name="AdExchangeCreative"> * &lt;complexContent> * &lt;extension base="{https://www.google.com/apis/ads/publisher/v202108}HasHtmlSnippetDynamicAllocationCreative"> * &lt;sequence> * &lt;element name="isNativeEligible" type="{http://www.w3.org/2001/XMLSchema}boolean" minOccurs="0"/> * &lt;element name="isInterstitial" type="{http://www.w3.org/2001/XMLSchema}boolean" minOccurs="0"/> * &lt;element name="isAllowsAllRequestedSizes" type="{http://www.w3.org/2001/XMLSchema}boolean" minOccurs="0"/> * &lt;/sequence> * &lt;/extension> * &lt;/complexContent> * &lt;/complexType> * </pre> * * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "AdExchangeCreative", propOrder = { "isNativeEligible", "isInterstitial", "isAllowsAllRequestedSizes" }) public class AdExchangeCreative extends HasHtmlSnippetDynamicAllocationCreative { protected Boolean isNativeEligible; protected Boolean isInterstitial; protected Boolean isAllowsAllRequestedSizes; /** * Gets the value of the isNativeEligible property. * * @return * possible object is * {@link Boolean } * */ public Boolean isIsNativeEligible() { return isNativeEligible; } /** * Sets the value of the isNativeEligible property. * * @param value * allowed object is * {@link Boolean } * */ public void setIsNativeEligible(Boolean value) { this.isNativeEligible = value; } /** * Gets the value of the isInterstitial property. * * @return * possible object is * {@link Boolean } * */ public Boolean isIsInterstitial() { return isInterstitial; } /** * Sets the value of the isInterstitial property. * * @param value * allowed object is * {@link Boolean } * */ public void setIsInterstitial(Boolean value) { this.isInterstitial = value; } /** * Gets the value of the isAllowsAllRequestedSizes property. * * @return * possible object is * {@link Boolean } * */ public Boolean isIsAllowsAllRequestedSizes() { return isAllowsAllRequestedSizes; } /** * Sets the value of the isAllowsAllRequestedSizes property. * * @param value * allowed object is * {@link Boolean } * */ public void setIsAllowsAllRequestedSizes(Boolean value) { this.isAllowsAllRequestedSizes = value; } }
apache-2.0
KingsCollegeHospital/rassyeyanie
rassyeyanie-framework/src/main/java/uk/nhs/kch/rassyeyanie/framework/CommonAlternateEncoding.java
780
package uk.nhs.kch.rassyeyanie.framework; import ca.uhn.hl7v2.HL7Exception; import ca.uhn.hl7v2.model.AbstractMessage; import ca.uhn.hl7v2.model.v24.datatype.ST; import ca.uhn.hl7v2.model.v24.segment.MSH; public class CommonAlternateEncoding extends AbstractProcessor { private static void insertEncodingCharactersToMSH(MSH msh) throws HL7Exception { ST encodingChars = msh.getEncodingCharacters(); encodingChars.setValue("^~\\,"); } public void transform(MSH msh) throws HL7Exception { insertEncodingCharactersToMSH(msh); } @Override protected void dispatchProcessFixture(AbstractMessage workingMessage) throws HL7Exception { this.transform(HapiUtil.get(workingMessage, MSH.class)); } }
apache-2.0
lasanthafdo/carbon-analytics-common
components/event-receiver/org.wso2.carbon.event.receiver.core/src/main/java/org/wso2/carbon/event/receiver/core/internal/type/wso2event/WSO2EventInputMapper.java
22192
/* * Copyright (c) 2015, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. * * WSO2 Inc. 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.wso2.carbon.event.receiver.core.internal.type.wso2event; import org.wso2.carbon.databridge.commons.Attribute; import org.wso2.carbon.databridge.commons.Event; import org.wso2.carbon.databridge.commons.StreamDefinition; import org.wso2.carbon.event.receiver.core.InputMapper; import org.wso2.carbon.event.receiver.core.config.EventReceiverConfiguration; import org.wso2.carbon.event.receiver.core.config.EventReceiverConstants; import org.wso2.carbon.event.receiver.core.config.InputMapping; import org.wso2.carbon.event.receiver.core.config.InputMappingAttribute; import org.wso2.carbon.event.receiver.core.config.mapping.WSO2EventInputMapping; import org.wso2.carbon.event.receiver.core.exception.EventReceiverConfigurationException; import org.wso2.carbon.event.receiver.core.exception.EventReceiverProcessingException; import org.wso2.carbon.event.receiver.core.exception.EventReceiverStreamValidationException; import org.wso2.carbon.event.receiver.core.internal.ds.EventReceiverServiceValueHolder; import org.wso2.carbon.event.receiver.core.internal.util.EventReceiverUtil; import org.wso2.carbon.event.receiver.core.internal.util.helper.EventReceiverConfigurationHelper; import org.wso2.carbon.event.stream.core.EventStreamService; import org.wso2.carbon.event.stream.core.exception.EventStreamConfigurationException; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.TreeMap; public class WSO2EventInputMapper implements InputMapper { private EventReceiverConfiguration eventReceiverConfiguration = null; private StreamDefinition exportedStreamDefinition = null; private StreamDefinition importedStreamDefinition = null; private Map<InputDataType, int[]> inputDataTypeSpecificPositionMap = null; private boolean arbitraryMapsEnabled = false; private int inputStreamSize = 0; private int outMetaSize = 0, outCorrelationSize = 0, outPayloadSize = 0; public WSO2EventInputMapper(EventReceiverConfiguration eventReceiverConfiguration, StreamDefinition exportedStreamDefinition) throws EventReceiverConfigurationException { //TODO It is better if logic to check from stream definition store can be moved outside of input mapper. EventStreamService eventStreamService = EventReceiverServiceValueHolder.getEventStreamService(); this.eventReceiverConfiguration = eventReceiverConfiguration; WSO2EventInputMapping wso2EventInputMapping = (WSO2EventInputMapping) this.eventReceiverConfiguration.getInputMapping(); String fromStreamName = wso2EventInputMapping.getFromEventName(); String fromStreamVersion = wso2EventInputMapping.getFromEventVersion(); this.arbitraryMapsEnabled = wso2EventInputMapping.isArbitraryMapsEnabled(); if (fromStreamName == null || fromStreamVersion == null || (fromStreamName.isEmpty()) || (fromStreamVersion.isEmpty())) { importedStreamDefinition = exportedStreamDefinition; } else { try { this.importedStreamDefinition = eventStreamService.getStreamDefinition(fromStreamName, fromStreamVersion); } catch (EventStreamConfigurationException e) { throw new EventReceiverStreamValidationException("Error while retrieving stream definition : " + e.getMessage(), fromStreamName + ":" + fromStreamVersion); } } this.exportedStreamDefinition = exportedStreamDefinition; boolean candidateForArbitraryMaps = isCandidateForArbitraryAttributes(eventReceiverConfiguration.getInputMapping(), importedStreamDefinition); if (!candidateForArbitraryMaps) { validateInputStreamAttributes(); } if (importedStreamDefinition != null && eventReceiverConfiguration.getInputMapping().isCustomMappingEnabled() && !candidateForArbitraryMaps) { this.inputDataTypeSpecificPositionMap = new HashMap<InputDataType, int[]>(); Map<Integer, Integer> payloadDataMap = new TreeMap<Integer, Integer>(); Map<Integer, Integer> metaDataMap = new TreeMap<Integer, Integer>(); Map<Integer, Integer> correlationDataMap = new TreeMap<Integer, Integer>(); List<Attribute> allAttributes = new ArrayList<Attribute>(); if (importedStreamDefinition.getMetaData() != null && !importedStreamDefinition.getMetaData().isEmpty()) { allAttributes.addAll(importedStreamDefinition.getMetaData()); } if (importedStreamDefinition.getCorrelationData() != null && !importedStreamDefinition.getCorrelationData().isEmpty()) { allAttributes.addAll(importedStreamDefinition.getCorrelationData()); } if (importedStreamDefinition.getPayloadData() != null && !importedStreamDefinition.getPayloadData().isEmpty()) { allAttributes.addAll(importedStreamDefinition.getPayloadData()); } int metaCount = 0, correlationCount = 0, payloadCount = 0; for (InputMappingAttribute inputMappingAttribute : wso2EventInputMapping.getInputMappingAttributes()) { if (inputMappingAttribute.getToElementKey().startsWith(EventReceiverConstants.META_DATA_PREFIX)) { for (int i = 0; i < allAttributes.size(); i++) { if (allAttributes.get(i).getName().equals(inputMappingAttribute.getFromElementKey())) { metaDataMap.put(metaCount, i); break; } } if (metaDataMap.get(metaCount++) == null) { this.inputDataTypeSpecificPositionMap = null; throw new EventReceiverStreamValidationException("Cannot find a corresponding meta data input attribute '" + inputMappingAttribute.getFromElementKey() + "' in stream with id " + importedStreamDefinition.getStreamId(), importedStreamDefinition.getStreamId()); } } else if (inputMappingAttribute.getToElementKey().startsWith(EventReceiverConstants.CORRELATION_DATA_PREFIX)) { for (int i = 0; i < allAttributes.size(); i++) { if (allAttributes.get(i).getName().equals(inputMappingAttribute.getFromElementKey())) { correlationDataMap.put(correlationCount, i); break; } } if (correlationDataMap.get(correlationCount++) == null) { this.inputDataTypeSpecificPositionMap = null; throw new EventReceiverStreamValidationException("Cannot find a corresponding correlation data input attribute '" + inputMappingAttribute.getFromElementKey() + "' in stream with id " + importedStreamDefinition.getStreamId(), importedStreamDefinition.getStreamId()); } } else { for (int i = 0; i < allAttributes.size(); i++) { if (allAttributes.get(i).getName().equals(inputMappingAttribute.getFromElementKey())) { payloadDataMap.put(payloadCount, i); break; } } if (payloadDataMap.get(payloadCount++) == null) { this.inputDataTypeSpecificPositionMap = null; throw new EventReceiverStreamValidationException("Cannot find a corresponding payload data input attribute '" + inputMappingAttribute.getFromElementKey() + "' in stream with id : " + importedStreamDefinition.getStreamId(), importedStreamDefinition.getStreamId()); } } } outMetaSize = metaDataMap.size(); outCorrelationSize = correlationDataMap.size(); outPayloadSize = payloadDataMap.size(); int[] metaPositions = new int[outMetaSize]; for (int i = 0; i < metaPositions.length; i++) { metaPositions[i] = metaDataMap.get(i); } inputDataTypeSpecificPositionMap.put(InputDataType.META_DATA, metaPositions); int[] correlationPositions = new int[outCorrelationSize]; for (int i = 0; i < correlationPositions.length; i++) { correlationPositions[i] = correlationDataMap.get(i); } inputDataTypeSpecificPositionMap.put(InputDataType.CORRELATION_DATA, correlationPositions); int[] payloadPositions = new int[outPayloadSize]; for (int i = 0; i < payloadPositions.length; i++) { payloadPositions[i] = payloadDataMap.get(i); } inputDataTypeSpecificPositionMap.put(InputDataType.PAYLOAD_DATA, payloadPositions); inputStreamSize = allAttributes.size(); } else if (importedStreamDefinition != null && (!eventReceiverConfiguration.getInputMapping().isCustomMappingEnabled())) { if (importedStreamDefinition.getCorrelationData() != null ? !importedStreamDefinition.getCorrelationData().equals(exportedStreamDefinition.getCorrelationData()) : exportedStreamDefinition.getCorrelationData() != null) { throw new EventReceiverStreamValidationException("Input stream definition : " + importedStreamDefinition + " not matching with output stream definition : " + exportedStreamDefinition + " to create pass-through link ", importedStreamDefinition.getStreamId()); } if (importedStreamDefinition.getMetaData() != null ? !importedStreamDefinition.getMetaData().equals(exportedStreamDefinition.getMetaData()) : exportedStreamDefinition.getMetaData() != null) { throw new EventReceiverStreamValidationException("Input stream definition : " + importedStreamDefinition + " not matching with output stream definition : " + exportedStreamDefinition + " to create pass-through link ", importedStreamDefinition.getStreamId()); } if (importedStreamDefinition.getPayloadData() != null ? !importedStreamDefinition.getPayloadData().equals(exportedStreamDefinition.getPayloadData()) : exportedStreamDefinition.getPayloadData() != null) { throw new EventReceiverStreamValidationException("Input stream definition : " + importedStreamDefinition + " not matching with output stream definition : " + exportedStreamDefinition + " to create pass-through link ", importedStreamDefinition.getStreamId()); } } else if (!candidateForArbitraryMaps) { throw new EventReceiverStreamValidationException("Error while retrieving stream definition : " + fromStreamName + ":" + fromStreamVersion); } } private boolean isCandidateForArbitraryAttributes(InputMapping inputMapping, StreamDefinition importedStreamDefinition) { for (InputMappingAttribute inputMappingAttribute : inputMapping.getInputMappingAttributes()) { if (EventReceiverConstants.META_DATA_VAL.equals(inputMappingAttribute.getFromElementType()) && !importedStreamDefinition.getMetaData().contains(new Attribute(inputMappingAttribute.getFromElementKey(), inputMappingAttribute.getToElementType()))) { return true; } if (EventReceiverConstants.CORRELATION_DATA_VAL.equals(inputMappingAttribute.getFromElementType()) && !importedStreamDefinition.getCorrelationData().contains(new Attribute(inputMappingAttribute.getFromElementKey(), inputMappingAttribute.getToElementType()))) { return true; } if (EventReceiverConstants.PAYLOAD_DATA_VAL.equals(inputMappingAttribute.getFromElementType()) && !importedStreamDefinition.getPayloadData().contains(new Attribute(inputMappingAttribute.getFromElementKey(), inputMappingAttribute.getToElementType()))) { return true; } } return false; } private void validateInputStreamAttributes() throws EventReceiverConfigurationException { if (this.importedStreamDefinition != null) { WSO2EventInputMapping wso2EventInputMapping = (WSO2EventInputMapping) eventReceiverConfiguration.getInputMapping(); List<InputMappingAttribute> inputMappingAttributes = wso2EventInputMapping.getInputMappingAttributes(); List<String> inputStreamMetaAttributeNames = getAttributeNamesList(importedStreamDefinition.getMetaData()); List<String> inputStreamCorrelationAttributeNames = getAttributeNamesList(importedStreamDefinition.getCorrelationData()); List<String> inputStreamPayloadAttributeNames = getAttributeNamesList(importedStreamDefinition.getPayloadData()); for (InputMappingAttribute inputMappingAttribute : inputMappingAttributes) { if (inputMappingAttribute.getToElementKey().startsWith(EventReceiverConstants.META_DATA_PREFIX) && !inputStreamMetaAttributeNames.contains(inputMappingAttribute.getFromElementKey())) { throw new EventReceiverStreamValidationException("Property " + inputMappingAttribute.getFromElementKey() + " is not in the input stream definition. ", importedStreamDefinition.getStreamId()); } else if (inputMappingAttribute.getToElementKey().startsWith(EventReceiverConstants.CORRELATION_DATA_PREFIX) && !inputStreamCorrelationAttributeNames.contains(inputMappingAttribute.getFromElementKey())) { throw new EventReceiverStreamValidationException("Property " + inputMappingAttribute.getFromElementKey() + " is not in the input stream definition. ", importedStreamDefinition.getStreamId()); } else if (!inputMappingAttribute.getToElementKey().startsWith(EventReceiverConstants.META_DATA_PREFIX) && !inputMappingAttribute.getToElementKey().startsWith(EventReceiverConstants.CORRELATION_DATA_PREFIX) && !inputStreamPayloadAttributeNames.contains(inputMappingAttribute.getFromElementKey())) { throw new EventReceiverStreamValidationException("Property " + inputMappingAttribute.getFromElementKey() + " is not in the input stream definition. ", importedStreamDefinition.getStreamId()); } } } } private List<String> getAttributeNamesList(List<Attribute> attributeList) { List<String> attributeNamesList = new ArrayList<String>(); if (attributeList != null) { for (Attribute attribute : attributeList) { attributeNamesList.add(attribute.getName()); } } return attributeNamesList; } @Override public Object convertToMappedInputEvent(Object obj) throws EventReceiverProcessingException { if (obj instanceof Event) { Event event = (Event) obj; Map<String, String> arbitraryMap = event.getArbitraryDataMap(); if (arbitraryMap != null && !arbitraryMap.isEmpty()) { return processArbitraryMap(event); } else if (inputDataTypeSpecificPositionMap != null) { Object[] outMetaAttrArray = new Object[outMetaSize]; Object[] outCorrelationAttrArray = new Object[outCorrelationSize]; Object[] outPayloadAttrArray = new Object[outPayloadSize]; // Construct input event as an array of attributes Object[] inEventArray = new Object[inputStreamSize]; int inEventArrayCount = 0; if (event.getMetaData() != null) { for (Object attribute : event.getMetaData()) { inEventArray[inEventArrayCount++] = attribute; } } if (event.getCorrelationData() != null) { for (Object attribute : event.getCorrelationData()) { inEventArray[inEventArrayCount++] = attribute; } } if (event.getPayloadData() != null) { for (Object attribute : event.getPayloadData()) { inEventArray[inEventArrayCount++] = attribute; } } // Finished construction of input event array int[] metaPositions = inputDataTypeSpecificPositionMap.get(InputDataType.META_DATA); for (int i = 0; i < metaPositions.length; i++) { outMetaAttrArray[i] = inEventArray[metaPositions[i]]; } int[] correlationPositions = inputDataTypeSpecificPositionMap.get(InputDataType.CORRELATION_DATA); for (int i = 0; i < correlationPositions.length; i++) { outCorrelationAttrArray[i] = inEventArray[correlationPositions[i]]; } int[] payloadPositions = inputDataTypeSpecificPositionMap.get(InputDataType.PAYLOAD_DATA); for (int i = 0; i < payloadPositions.length; i++) { outPayloadAttrArray[i] = inEventArray[payloadPositions[i]]; } return new Event(exportedStreamDefinition.getStreamId(), event.getTimeStamp(), outMetaAttrArray, outCorrelationAttrArray, outPayloadAttrArray); } else { return null; } } return null; } @Override public Object convertToTypedInputEvent(Object obj) throws EventReceiverProcessingException { if (obj instanceof Event) { return obj; } else { return null; } } @Override public Attribute[] getOutputAttributes() { WSO2EventInputMapping wso2EventInputMapping = (WSO2EventInputMapping) eventReceiverConfiguration.getInputMapping(); List<InputMappingAttribute> inputMappingAttributes = wso2EventInputMapping.getInputMappingAttributes(); return EventReceiverConfigurationHelper.getAttributes(inputMappingAttributes); } //TODO This method needs to be optimized for performance private Event processArbitraryMap(Event inEvent) { Map<String, String> arbitraryMap = inEvent.getArbitraryDataMap(); Object[] metaData, correlationData, payloadData; if (exportedStreamDefinition.getMetaData() != null) { metaData = new Object[exportedStreamDefinition.getMetaData().size()]; } else { metaData = new Object[0]; } if (exportedStreamDefinition.getCorrelationData() != null) { correlationData = new Object[exportedStreamDefinition.getCorrelationData().size()]; } else { correlationData = new Object[0]; } if (exportedStreamDefinition.getPayloadData() != null) { payloadData = new Object[exportedStreamDefinition.getPayloadData().size()]; } else { payloadData = new Object[0]; } for (int i = 0; i < metaData.length; i++) { Attribute metaAttribute = exportedStreamDefinition.getMetaData().get(i); String value = arbitraryMap.get(EventReceiverUtil.getMappedInputStreamAttributeName( metaAttribute.getName(), eventReceiverConfiguration.getInputMapping())); if (value != null) { Object attributeObj = EventReceiverUtil.getConvertedAttributeObject(value, metaAttribute.getType()); metaData[i] = attributeObj; } else { metaData[i] = inEvent.getMetaData()[i]; } } for (int i = 0; i < correlationData.length; i++) { Attribute correlationAttribute = exportedStreamDefinition.getCorrelationData().get(i); String value = arbitraryMap.get(EventReceiverUtil.getMappedInputStreamAttributeName( correlationAttribute.getName(), eventReceiverConfiguration.getInputMapping())); if (value != null) { Object attributeObj = EventReceiverUtil.getConvertedAttributeObject(value, correlationAttribute.getType()); correlationData[i] = attributeObj; } else { correlationData[i] = inEvent.getCorrelationData()[i]; } } for (int i = 0; i < payloadData.length; i++) { Attribute payloadAttribute = exportedStreamDefinition.getPayloadData().get(i); String value = arbitraryMap.get(EventReceiverUtil.getMappedInputStreamAttributeName( payloadAttribute.getName(), eventReceiverConfiguration.getInputMapping())); if (value != null) { Object attributeObj = EventReceiverUtil.getConvertedAttributeObject(value, payloadAttribute.getType()); payloadData[i] = attributeObj; } else { payloadData[i] = inEvent.getPayloadData()[i]; } } return new Event(inEvent.getStreamId(), inEvent.getTimeStamp(), metaData, correlationData, payloadData, arbitraryMap); } private enum InputDataType { META_DATA, CORRELATION_DATA, PAYLOAD_DATA } }
apache-2.0
tAsktoys/Archelon
src/main/java/com/tasktoys/archelon/data/dao/mongodb/MongoDbDiscussionContentDao.java
2151
/* * Copyright(C) 2014 tAsktoys. All rights reserved. */ package com.tasktoys.archelon.data.dao.mongodb; import com.mongodb.WriteResult; import com.tasktoys.archelon.data.dao.DiscussionContentDao; import com.tasktoys.archelon.data.entity.DiscussionContent; import java.util.logging.Level; import java.util.logging.Logger; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.mongodb.core.MongoTemplate; import org.springframework.data.mongodb.core.query.Criteria; import org.springframework.data.mongodb.core.query.Query; import org.springframework.data.mongodb.core.query.Update; import org.springframework.stereotype.Repository; /** * * @author mikan */ @Repository public class MongoDbDiscussionContentDao implements DiscussionContentDao { @Autowired MongoTemplate mongoTemplate; Logger log = Logger.getLogger(MongoDbDiscussionContentDao.class.getName()); @Override public DiscussionContent findByDiscussionId(long id) { Query query = new Query(Criteria.where("discussionId").is(id)); return mongoTemplate.findOne(query, DiscussionContent.class); } @Override public void insert(DiscussionContent content) { mongoTemplate.insert(content); } @Override public void update(DiscussionContent.Post post) { // TODO: implement thread-safe appending. } @Override public void insertPost(long discussionId, DiscussionContent.Post post) { Query query = new Query(Criteria.where("discussionId").is(discussionId)); WriteResult wr = mongoTemplate.updateFirst(query, new Update().addToSet("posts", post), DiscussionContent.class); log.log(Level.INFO, wr.toString()); log.log(Level.INFO, Boolean.toString(wr.isUpdateOfExisting())); } @Override public void insertParticipants(long discussionId, long userId) { Query query = new Query(Criteria.where("discussionId").is(discussionId)); mongoTemplate.updateFirst(query, new Update().addToSet("participants", userId), DiscussionContent.class); } }
apache-2.0
darranl/directory-shared
ldap/extras/codec/src/test/java/org/apache/directory/api/ldap/extras/extended/ads_impl/whoAmI/WhoAmIResponseTest.java
6926
/* * 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.directory.api.ldap.extras.extended.ads_impl.whoAmI; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.fail; import java.nio.ByteBuffer; import org.apache.directory.api.asn1.DecoderException; import org.apache.directory.api.asn1.EncoderException; import org.apache.directory.api.asn1.ber.Asn1Container; import org.apache.directory.api.asn1.ber.Asn1Decoder; import org.apache.directory.api.util.Strings; import org.junit.Test; import org.junit.runner.RunWith; import com.mycila.junit.concurrent.Concurrency; import com.mycila.junit.concurrent.ConcurrentJunitRunner; /* * TestCase for a WhoAmI response Extended Operation * * @author <a href="mailto:dev@directory.apache.org">Apache Directory Project</a> */ @RunWith(ConcurrentJunitRunner.class) @Concurrency() public class WhoAmIResponseTest { /** * Test the normal WhoAmI response message */ @Test public void testDecodeWhoAmINull() { Asn1Decoder whoAmIResponseDecoder = new WhoAmIResponseDecoder(); ByteBuffer stream = ByteBuffer.allocate( 0x00 ); stream.put( new byte[] {} ).flip(); Strings.dumpBytes( stream.array() ); // Allocate a WhoAmI Container Asn1Container whoAmIResponseContainer = new WhoAmIResponseContainer(); // Decode a WhoAmI message try { whoAmIResponseDecoder.decode( stream, whoAmIResponseContainer ); } catch ( DecoderException de ) { de.printStackTrace(); fail( de.getMessage() ); } WhoAmIResponseDecorator whoAmIResponse = ( ( WhoAmIResponseContainer ) whoAmIResponseContainer ).getWhoAmIResponse(); assertNull( whoAmIResponse ); } /** * Test a WhoAmI message with no authzId */ @Test public void testDecodeWhoAmINoWhoAmIAuthzIdEmpty() { Asn1Decoder whoAmIResponseDecoder = new WhoAmIResponseDecoder(); ByteBuffer stream = ByteBuffer.allocate( 0x02 ); stream.put( new byte[] { 0x04, 0x00 } ).flip(); String decodedPdu = Strings.dumpBytes( stream.array() ); // Allocate a WhoAmI Container Asn1Container whoAmIResponseContainer = new WhoAmIResponseContainer(); // Decode a WhoAmI message try { whoAmIResponseDecoder.decode( stream, whoAmIResponseContainer ); } catch ( DecoderException de ) { fail(); } WhoAmIResponseDecorator whoAmIResponse = ( (WhoAmIResponseContainer ) whoAmIResponseContainer ).getWhoAmIResponse(); assertNull( whoAmIResponse.getAuthzId() ); // Check the encoding try { ByteBuffer bb = whoAmIResponse.encodeInternal(); String encodedPdu = Strings.dumpBytes( bb.array() ); assertEquals( encodedPdu, decodedPdu ); } catch ( EncoderException ee ) { ee.printStackTrace(); fail( ee.getMessage() ); } } /** * Test a WhoAmI message with a DN authzId */ @Test public void testDecodeWhoAmINoWhoAmIAuthzIdDN() { Asn1Decoder whoAmIResponseDecoder = new WhoAmIResponseDecoder(); ByteBuffer stream = ByteBuffer.allocate( 0x0E ); stream.put( new byte[] { 0x04, 0x0C, 'd', 'n', ':', 'o', 'u', '=', 's', 'y', 's', 't', 'e', 'm' } ).flip(); String decodedPdu = Strings.dumpBytes( stream.array() ); // Allocate a WhoAmI Container Asn1Container whoAmIResponseContainer = new WhoAmIResponseContainer(); // Decode a WhoAmI message try { whoAmIResponseDecoder.decode( stream, whoAmIResponseContainer ); } catch ( DecoderException de ) { fail(); } WhoAmIResponseDecorator whoAmIResponse = ( (WhoAmIResponseContainer ) whoAmIResponseContainer ).getWhoAmIResponse(); assertNotNull( whoAmIResponse.getAuthzId() ); assertEquals( "dn:ou=system", Strings.utf8ToString( whoAmIResponse.getAuthzId() ) ); // Check the encoding try { ByteBuffer bb = whoAmIResponse.encodeInternal(); String encodedPdu = Strings.dumpBytes( bb.array() ); assertEquals( encodedPdu, decodedPdu ); } catch ( EncoderException ee ) { ee.printStackTrace(); fail( ee.getMessage() ); } } /** * Test a WhoAmI message with a UserId authzId */ @Test public void testDecodeWhoAmINoWhoAmIAuthzIdUserId() { Asn1Decoder whoAmIResponseDecoder = new WhoAmIResponseDecoder(); ByteBuffer stream = ByteBuffer.allocate( 0x09 ); stream.put( new byte[] { 0x04, 0x07, 'u', ':', 't', 'e', 's', 't', 0x00 } ).flip(); String decodedPdu = Strings.dumpBytes( stream.array() ); // Allocate a WhoAmI Container Asn1Container whoAmIResponseContainer = new WhoAmIResponseContainer(); // Decode a WhoAmI message try { whoAmIResponseDecoder.decode( stream, whoAmIResponseContainer ); } catch ( DecoderException de ) { fail(); } WhoAmIResponseDecorator whoAmIResponse = ( (WhoAmIResponseContainer ) whoAmIResponseContainer ).getWhoAmIResponse(); assertNotNull( whoAmIResponse.getAuthzId() ); // Check the encoding try { ByteBuffer bb = whoAmIResponse.encodeInternal(); String encodedPdu = Strings.dumpBytes( bb.array() ); assertEquals( encodedPdu, decodedPdu ); } catch ( EncoderException ee ) { ee.printStackTrace(); fail( ee.getMessage() ); } } }
apache-2.0
fizalihsan/Fig
src/main/java/com/fig/block/procedure/TaskDependencyCreator.java
985
package com.fig.block.procedure; import com.fig.annotations.ThreadSafe; import com.fig.domain.TaskDependency; import com.fig.manager.Neo4jTaskAdapter; import com.google.common.annotations.VisibleForTesting; import com.gs.collections.api.block.procedure.Procedure; import java.util.Collection; /** * Re-usable procedure to create task dependencies. * User: Fizal * Date: 11/24/13 * Time: 6:26 PM */ @ThreadSafe public class TaskDependencyCreator implements Procedure<Collection<TaskDependency>> { private final Neo4jTaskAdapter adapter = new Neo4jTaskAdapter(); @Override public void value(Collection<TaskDependency> taskDependencies) { for (TaskDependency dependency : taskDependencies) { for (String toTask : dependency.getToTasks()) { getAdapter().createTaskDependency(dependency.getFromTask(), toTask); } } } @VisibleForTesting Neo4jTaskAdapter getAdapter() { return adapter; } }
apache-2.0
HubSpot/Singularity
SingularityBase/src/main/java/com/hubspot/singularity/SingularityRequestBuilder.java
21354
package com.hubspot.singularity; import static com.google.common.base.Preconditions.checkNotNull; import java.util.List; import java.util.Map; import java.util.Objects; import java.util.Optional; import java.util.Set; public class SingularityRequestBuilder { private String id; private RequestType requestType; private Optional<List<String>> owners; private Optional<Integer> numRetriesOnFailure; private Optional<Integer> maxScale; private Optional<String> schedule; private Optional<String> quartzSchedule; private Optional<String> scheduleTimeZone; private Optional<ScheduleType> scheduleType; private Optional<Long> killOldNonLongRunningTasksAfterMillis; private Optional<Long> taskExecutionTimeLimitMillis; private Optional<Long> scheduledExpectedRuntimeMillis; private Optional<Long> waitAtLeastMillisAfterTaskFinishesForReschedule; private Optional<Integer> instances; private Optional<Boolean> skipHealthchecks; private Optional<Boolean> rackSensitive; private Optional<List<String>> rackAffinity; private Optional<AgentPlacement> agentPlacement; private Optional<Map<String, String>> requiredAgentAttributes; private Optional<Map<String, String>> allowedAgentAttributes; private Optional<Map<String, Map<String, Integer>>> agentAttributeMinimums; private Optional<Boolean> loadBalanced; private Optional<String> requiredRole; private Optional<String> group; private Optional<Set<String>> readWriteGroups; private Optional<Set<String>> readOnlyGroups; private Optional<Map<String, Set<SingularityUserFacingAction>>> actionPermissions; private Optional<Boolean> bounceAfterScale; private Optional<Map<SingularityEmailType, List<SingularityEmailDestination>>> emailConfigurationOverrides; private Optional<Boolean> hideEvenNumberAcrossRacksHint; private Optional<String> taskLogErrorRegex; private Optional<Boolean> taskLogErrorRegexCaseSensitive; private Optional<Double> taskPriorityLevel; private Optional<Integer> maxTasksPerOffer; private Optional<Boolean> allowBounceToSameHost; @Deprecated private Optional<String> dataCenter; public SingularityRequestBuilder(String id, RequestType requestType) { this.id = checkNotNull(id, "id cannot be null"); this.requestType = checkNotNull(requestType, "requestType cannot be null"); this.owners = Optional.empty(); this.numRetriesOnFailure = Optional.empty(); this.maxScale = Optional.empty(); this.schedule = Optional.empty(); this.scheduleType = Optional.empty(); this.killOldNonLongRunningTasksAfterMillis = Optional.empty(); this.taskExecutionTimeLimitMillis = Optional.empty(); this.instances = Optional.empty(); this.rackSensitive = Optional.empty(); this.loadBalanced = Optional.empty(); this.quartzSchedule = Optional.empty(); this.scheduleTimeZone = Optional.empty(); this.rackAffinity = Optional.empty(); this.agentPlacement = Optional.empty(); this.requiredAgentAttributes = Optional.empty(); this.allowedAgentAttributes = Optional.empty(); this.agentAttributeMinimums = Optional.empty(); this.scheduledExpectedRuntimeMillis = Optional.empty(); this.waitAtLeastMillisAfterTaskFinishesForReschedule = Optional.empty(); this.group = Optional.empty(); this.readWriteGroups = Optional.empty(); this.readOnlyGroups = Optional.empty(); this.actionPermissions = Optional.empty(); this.bounceAfterScale = Optional.empty(); this.emailConfigurationOverrides = Optional.empty(); this.skipHealthchecks = Optional.empty(); this.hideEvenNumberAcrossRacksHint = Optional.empty(); this.taskLogErrorRegex = Optional.empty(); this.taskLogErrorRegexCaseSensitive = Optional.empty(); this.taskPriorityLevel = Optional.empty(); this.maxTasksPerOffer = Optional.empty(); this.allowBounceToSameHost = Optional.empty(); this.requiredRole = Optional.empty(); this.dataCenter = Optional.empty(); } public SingularityRequest build() { return new SingularityRequest( id, requestType, owners, numRetriesOnFailure, maxScale, schedule, instances, rackSensitive, loadBalanced, killOldNonLongRunningTasksAfterMillis, taskExecutionTimeLimitMillis, scheduleType, quartzSchedule, scheduleTimeZone, rackAffinity, Optional.empty(), Optional.empty(), Optional.empty(), Optional.empty(), scheduledExpectedRuntimeMillis, waitAtLeastMillisAfterTaskFinishesForReschedule, group, readWriteGroups, readOnlyGroups, actionPermissions, bounceAfterScale, skipHealthchecks, emailConfigurationOverrides, Optional.<Boolean>empty(), hideEvenNumberAcrossRacksHint, taskLogErrorRegex, taskLogErrorRegexCaseSensitive, taskPriorityLevel, maxTasksPerOffer, allowBounceToSameHost, requiredRole, dataCenter, requiredAgentAttributes, allowedAgentAttributes, agentAttributeMinimums, agentPlacement ); } public Optional<Boolean> getSkipHealthchecks() { return skipHealthchecks; } public SingularityRequestBuilder setSkipHealthchecks( Optional<Boolean> skipHealthchecks ) { this.skipHealthchecks = skipHealthchecks; return this; } public Optional<Boolean> getLoadBalanced() { return loadBalanced; } public SingularityRequestBuilder setLoadBalanced(Optional<Boolean> loadBalanced) { this.loadBalanced = loadBalanced; return this; } public String getId() { return id; } public SingularityRequestBuilder setId(String id) { this.id = id; return this; } public Optional<List<String>> getOwners() { return owners; } public SingularityRequestBuilder setOwners(Optional<List<String>> owners) { this.owners = owners; return this; } public Optional<Integer> getNumRetriesOnFailure() { return numRetriesOnFailure; } public SingularityRequestBuilder setNumRetriesOnFailure( Optional<Integer> numRetriesOnFailure ) { this.numRetriesOnFailure = numRetriesOnFailure; return this; } public Optional<Integer> getMaxScale() { return maxScale; } public SingularityRequestBuilder setMaxScale(Optional<Integer> maxScale) { this.maxScale = maxScale; return this; } public Optional<String> getSchedule() { return schedule; } public SingularityRequestBuilder setSchedule(Optional<String> schedule) { this.schedule = schedule; return this; } public Optional<Integer> getInstances() { return instances; } public SingularityRequestBuilder setInstances(Optional<Integer> instances) { this.instances = instances; return this; } public SingularityRequestBuilder setRequiredRole(Optional<String> requiredRole) { this.requiredRole = requiredRole; return this; } public Optional<Boolean> getRackSensitive() { return rackSensitive; } public SingularityRequestBuilder setRackSensitive(Optional<Boolean> rackSensitive) { this.rackSensitive = rackSensitive; return this; } public Optional<Long> getKillOldNonLongRunningTasksAfterMillis() { return killOldNonLongRunningTasksAfterMillis; } public SingularityRequestBuilder setKillOldNonLongRunningTasksAfterMillis( Optional<Long> killOldNonLongRunningTasksAfterMillis ) { this.killOldNonLongRunningTasksAfterMillis = killOldNonLongRunningTasksAfterMillis; return this; } public Optional<Long> getTaskExecutionTimeLimitMillis() { return taskExecutionTimeLimitMillis; } public SingularityRequestBuilder setTaskExecutionTimeLimitMillis( Optional<Long> taskExecutionTimeLimitMillis ) { this.taskExecutionTimeLimitMillis = taskExecutionTimeLimitMillis; return this; } public Optional<ScheduleType> getScheduleType() { return scheduleType; } public SingularityRequestBuilder setScheduleType(Optional<ScheduleType> scheduleType) { this.scheduleType = scheduleType; return this; } public Optional<String> getQuartzSchedule() { return quartzSchedule; } public SingularityRequestBuilder setQuartzSchedule(Optional<String> quartzSchedule) { this.quartzSchedule = quartzSchedule; return this; } public Optional<String> getScheduleTimeZone() { return scheduleTimeZone; } public SingularityRequestBuilder setScheduleTimeZone( Optional<String> scheduleTimeZone ) { this.scheduleTimeZone = scheduleTimeZone; return this; } public Optional<List<String>> getRackAffinity() { return rackAffinity; } public SingularityRequestBuilder setRackAffinity(Optional<List<String>> rackAffinity) { this.rackAffinity = rackAffinity; return this; } public Optional<AgentPlacement> getAgentPlacement() { return agentPlacement; } public SingularityRequestBuilder setAgentPlacement( Optional<AgentPlacement> agentPlacement ) { this.agentPlacement = agentPlacement; return this; } @Deprecated public Optional<SlavePlacement> getSlavePlacement() { return agentPlacement.map(a -> SlavePlacement.valueOf(a.name())); } @Deprecated public SingularityRequestBuilder setSlavePlacement( Optional<SlavePlacement> agentPlacement ) { this.agentPlacement = agentPlacement.map(s -> AgentPlacement.valueOf(s.name())); return this; } public Optional<Long> getScheduledExpectedRuntimeMillis() { return scheduledExpectedRuntimeMillis; } public SingularityRequestBuilder setScheduledExpectedRuntimeMillis( Optional<Long> scheduledExpectedRuntimeMillis ) { this.scheduledExpectedRuntimeMillis = scheduledExpectedRuntimeMillis; return this; } public RequestType getRequestType() { return requestType; } public SingularityRequestBuilder setRequestType(RequestType requestType) { this.requestType = requestType; return this; } public Optional<Long> getWaitAtLeastMillisAfterTaskFinishesForReschedule() { return waitAtLeastMillisAfterTaskFinishesForReschedule; } public SingularityRequestBuilder setWaitAtLeastMillisAfterTaskFinishesForReschedule( Optional<Long> waitAtLeastMillisAfterTaskFinishesForReschedule ) { this.waitAtLeastMillisAfterTaskFinishesForReschedule = waitAtLeastMillisAfterTaskFinishesForReschedule; return this; } public Optional<String> getGroup() { return group; } public SingularityRequestBuilder setGroup(Optional<String> group) { this.group = group; return this; } public Optional<Set<String>> getReadWriteGroups() { return readWriteGroups; } public SingularityRequestBuilder setReadWriteGroups( Optional<Set<String>> readWriteGroups ) { this.readWriteGroups = readWriteGroups; return this; } public Optional<Map<String, Set<SingularityUserFacingAction>>> getActionPermissions() { return actionPermissions; } public SingularityRequestBuilder setActionPermissions( Optional<Map<String, Set<SingularityUserFacingAction>>> getActionPermissions ) { this.actionPermissions = getActionPermissions; return this; } public SingularityRequestBuilder setRequiredAgentAttributes( Optional<Map<String, String>> requiredAgentAttributes ) { this.requiredAgentAttributes = requiredAgentAttributes; return this; } public SingularityRequestBuilder setAllowedAgentAttributes( Optional<Map<String, String>> allowedAgentAttributes ) { this.allowedAgentAttributes = allowedAgentAttributes; return this; } public SingularityRequestBuilder setAgentAttributeMinimums( Optional<Map<String, Map<String, Integer>>> agentAttributeMinimums ) { this.agentAttributeMinimums = agentAttributeMinimums; return this; } @Deprecated public SingularityRequestBuilder setRequiredSlaveAttributes( Optional<Map<String, String>> requiredAgentAttributes ) { this.requiredAgentAttributes = requiredAgentAttributes; return this; } @Deprecated public SingularityRequestBuilder setAllowedSlaveAttributes( Optional<Map<String, String>> allowedAgentAttributes ) { this.allowedAgentAttributes = allowedAgentAttributes; return this; } @Deprecated public SingularityRequestBuilder setSlaveAttributeMinimums( Optional<Map<String, Map<String, Integer>>> agentAttributeMinimums ) { this.agentAttributeMinimums = agentAttributeMinimums; return this; } public Optional<Set<String>> getReadOnlyGroups() { return readOnlyGroups; } public SingularityRequestBuilder setReadOnlyGroups( Optional<Set<String>> readOnlyGroups ) { this.readOnlyGroups = readOnlyGroups; return this; } public Optional<Boolean> getBounceAfterScale() { return bounceAfterScale; } public SingularityRequestBuilder setBounceAfterScale( Optional<Boolean> bounceAfterScale ) { this.bounceAfterScale = bounceAfterScale; return this; } public Optional<Map<SingularityEmailType, List<SingularityEmailDestination>>> getEmailConfigurationOverrides() { return emailConfigurationOverrides; } public SingularityRequestBuilder setEmailConfigurationOverrides( Optional<Map<SingularityEmailType, List<SingularityEmailDestination>>> emailConfigurationOverrides ) { this.emailConfigurationOverrides = emailConfigurationOverrides; return this; } public Optional<Boolean> getHideEvenNumberAcrossRacksHint() { return hideEvenNumberAcrossRacksHint; } public SingularityRequestBuilder setHideEvenNumberAcrossRacksHint( Optional<Boolean> hideEvenNumberAcrossRacksHint ) { this.hideEvenNumberAcrossRacksHint = hideEvenNumberAcrossRacksHint; return this; } public Optional<String> getTaskLogErrorRegex() { return taskLogErrorRegex; } public SingularityRequestBuilder setTaskLogErrorRegex( Optional<String> taskLogErrorRegex ) { this.taskLogErrorRegex = taskLogErrorRegex; return this; } public Optional<Boolean> getTaskLogErrorRegexCaseSensitive() { return taskLogErrorRegexCaseSensitive; } public SingularityRequestBuilder setTaskLogErrorRegexCaseSensitive( Optional<Boolean> taskLogErrorRegexCaseSensitive ) { this.taskLogErrorRegexCaseSensitive = taskLogErrorRegexCaseSensitive; return this; } public Optional<Double> getTaskPriorityLevel() { return taskPriorityLevel; } public SingularityRequestBuilder setTaskPriorityLevel( Optional<Double> taskPriorityLevel ) { this.taskPriorityLevel = taskPriorityLevel; return this; } public Optional<Integer> getMaxTasksPerOffer() { return maxTasksPerOffer; } public SingularityRequestBuilder setMaxTasksPerOffer( Optional<Integer> maxTasksPerOffer ) { this.maxTasksPerOffer = maxTasksPerOffer; return this; } public Optional<Boolean> getAllowBounceToSameHost() { return allowBounceToSameHost; } public SingularityRequestBuilder setAllowBounceToSameHost( Optional<Boolean> allowBounceToSameHost ) { this.allowBounceToSameHost = allowBounceToSameHost; return this; } @Deprecated public Optional<String> getDataCenter() { return dataCenter; } @Deprecated public SingularityRequestBuilder setDataCenter(Optional<String> dataCenter) { this.dataCenter = dataCenter; return this; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } SingularityRequestBuilder that = (SingularityRequestBuilder) o; return ( Objects.equals(id, that.id) && requestType == that.requestType && Objects.equals(owners, that.owners) && Objects.equals(numRetriesOnFailure, that.numRetriesOnFailure) && Objects.equals(maxScale, that.maxScale) && Objects.equals(schedule, that.schedule) && Objects.equals(quartzSchedule, that.quartzSchedule) && Objects.equals(scheduleTimeZone, that.scheduleTimeZone) && Objects.equals(scheduleType, that.scheduleType) && Objects.equals( killOldNonLongRunningTasksAfterMillis, that.killOldNonLongRunningTasksAfterMillis ) && Objects.equals(taskExecutionTimeLimitMillis, that.taskExecutionTimeLimitMillis) && Objects.equals( scheduledExpectedRuntimeMillis, that.scheduledExpectedRuntimeMillis ) && Objects.equals( waitAtLeastMillisAfterTaskFinishesForReschedule, that.waitAtLeastMillisAfterTaskFinishesForReschedule ) && Objects.equals(instances, that.instances) && Objects.equals(skipHealthchecks, that.skipHealthchecks) && Objects.equals(rackSensitive, that.rackSensitive) && Objects.equals(rackAffinity, that.rackAffinity) && Objects.equals(agentPlacement, that.agentPlacement) && Objects.equals(requiredAgentAttributes, that.requiredAgentAttributes) && Objects.equals(allowedAgentAttributes, that.allowedAgentAttributes) && Objects.equals(agentAttributeMinimums, that.agentAttributeMinimums) && Objects.equals(loadBalanced, that.loadBalanced) && Objects.equals(requiredRole, that.requiredRole) && Objects.equals(group, that.group) && Objects.equals(readWriteGroups, that.readWriteGroups) && Objects.equals(readOnlyGroups, that.readOnlyGroups) && Objects.equals(actionPermissions, that.actionPermissions) && Objects.equals(bounceAfterScale, that.bounceAfterScale) && Objects.equals(emailConfigurationOverrides, that.emailConfigurationOverrides) && Objects.equals(hideEvenNumberAcrossRacksHint, that.hideEvenNumberAcrossRacksHint) && Objects.equals(taskLogErrorRegex, that.taskLogErrorRegex) && Objects.equals( taskLogErrorRegexCaseSensitive, that.taskLogErrorRegexCaseSensitive ) && Objects.equals(taskPriorityLevel, that.taskPriorityLevel) && Objects.equals(maxTasksPerOffer, that.maxTasksPerOffer) && Objects.equals(allowBounceToSameHost, that.allowBounceToSameHost) && Objects.equals(dataCenter, that.dataCenter) ); } @Override public int hashCode() { return Objects.hash( id, requestType, owners, numRetriesOnFailure, maxScale, schedule, quartzSchedule, scheduleTimeZone, scheduleType, killOldNonLongRunningTasksAfterMillis, taskExecutionTimeLimitMillis, scheduledExpectedRuntimeMillis, waitAtLeastMillisAfterTaskFinishesForReschedule, instances, skipHealthchecks, rackSensitive, rackAffinity, agentPlacement, requiredAgentAttributes, allowedAgentAttributes, agentAttributeMinimums, loadBalanced, requiredRole, group, readWriteGroups, readOnlyGroups, actionPermissions, bounceAfterScale, emailConfigurationOverrides, hideEvenNumberAcrossRacksHint, taskLogErrorRegex, taskLogErrorRegexCaseSensitive, taskPriorityLevel, maxTasksPerOffer, allowBounceToSameHost, dataCenter ); } @Override public String toString() { return ( "SingularityRequestBuilder{" + "id='" + id + '\'' + ", requestType=" + requestType + ", owners=" + owners + ", numRetriesOnFailure=" + numRetriesOnFailure + ", maxScale=" + maxScale + ", schedule=" + schedule + ", quartzSchedule=" + quartzSchedule + ", scheduleTimeZone=" + scheduleTimeZone + ", scheduleType=" + scheduleType + ", killOldNonLongRunningTasksAfterMillis=" + killOldNonLongRunningTasksAfterMillis + ", taskExecutionTimeLimitMillis=" + taskExecutionTimeLimitMillis + ", scheduledExpectedRuntimeMillis=" + scheduledExpectedRuntimeMillis + ", waitAtLeastMillisAfterTaskFinishesForReschedule=" + waitAtLeastMillisAfterTaskFinishesForReschedule + ", instances=" + instances + ", skipHealthchecks=" + skipHealthchecks + ", rackSensitive=" + rackSensitive + ", rackAffinity=" + rackAffinity + ", agentPlacement=" + agentPlacement + ", requiredAgentAttributes=" + requiredAgentAttributes + ", allowedAgentAttributes=" + allowedAgentAttributes + ", agentAttributeMinimums=" + agentAttributeMinimums + ", loadBalanced=" + loadBalanced + ", requiredRole=" + requiredRole + ", group=" + group + ", readWriteGroups=" + readWriteGroups + ", readOnlyGroups=" + readOnlyGroups + ", actionPermissions=" + actionPermissions + ", bounceAfterScale=" + bounceAfterScale + ", emailConfigurationOverrides=" + emailConfigurationOverrides + ", hideEvenNumberAcrossRacksHint=" + hideEvenNumberAcrossRacksHint + ", taskLogErrorRegex=" + taskLogErrorRegex + ", taskLogErrorRegexCaseSensitive=" + taskLogErrorRegexCaseSensitive + ", taskPriorityLevel=" + taskPriorityLevel + ", maxTasksPerOffer=" + maxTasksPerOffer + ", allowBounceToSameHost=" + allowBounceToSameHost + ", dataCenter=" + dataCenter + '}' ); } }
apache-2.0
gabrielalvesc/POO
Lista I - POO/src/com/ufpb/questao9/RetangulosTest.java
483
package com.ufpb.questao9; import static org.junit.Assert.*; import org.junit.Before; import org.junit.Test; public class RetangulosTest { Retangulos r; double base, altura; @Before public void setUp() throws Exception { base = 4; altura = 2; r = new Retangulos(base, altura); } @Test public void testCalculaArea() { assertEquals(8, r.calculaArea(), 0.1); } @Test public void testCalculaPerimetro(){ assertEquals(12, r.calculaPerimetro(), 0.1); } }
apache-2.0
Protino/Fad-Flicks
app/src/main/java/com/calgen/prodek/fadflicks/Activity/DetailActivity.java
7418
/* * Copyright 2016 Gurupad Mamadapur * * 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.calgen.prodek.fadflicks.activity; import android.content.Intent; import android.content.res.Configuration; import android.graphics.drawable.ColorDrawable; import android.graphics.drawable.Drawable; import android.os.Bundle; import android.support.design.widget.AppBarLayout; import android.support.design.widget.CoordinatorLayout; import android.support.design.widget.FloatingActionButton; import android.support.v4.widget.NestedScrollView; import android.support.v7.app.AppCompatActivity; import android.support.v7.app.AppCompatDelegate; import android.support.v7.widget.Toolbar; import android.view.MenuItem; import android.widget.ImageView; import com.calgen.prodek.fadflicks.R; import com.calgen.prodek.fadflicks.adapter.VideosAdapter; import com.calgen.prodek.fadflicks.fragment.MovieDetailFragment; import com.calgen.prodek.fadflicks.model.Movie; import com.calgen.prodek.fadflicks.utils.Cache; import com.calgen.prodek.fadflicks.utils.Parser; import com.calgen.prodek.fadflicks.utils.UI; import com.google.android.youtube.player.YouTubeThumbnailLoader; import com.squareup.picasso.Picasso; import butterknife.BindDrawable; import butterknife.BindView; import butterknife.ButterKnife; import butterknife.OnClick; import icepick.Icepick; import icepick.State; /** * Handles setup of detailFragment if not in two-pane UI mode. */ public class DetailActivity extends AppCompatActivity { //re-enable usage of vectors for devices(API 19 and lower) static { AppCompatDelegate.setCompatVectorFromResourcesEnabled(true); } //@formatter:off @BindView(R.id.fav_fab) public FloatingActionButton favFab; @BindView(R.id.toolbar) public Toolbar toolbar; @BindView(R.id.image_backdrop) public ImageView backdropImage; @BindView(R.id.nestedScrollView) public NestedScrollView nestedScrollView; @BindDrawable(R.drawable.ic_favorite_border_white_24dp) public Drawable notFavouriteDrawable; @BindDrawable(R.drawable.ic_favorite_white_24dp) public Drawable favouriteDrawable; @State public boolean isFavourite; @State public boolean isFavouriteOriginal; @State public Movie movie; //@formatter:on @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); Icepick.restoreInstanceState(this, savedInstanceState); setContentView(R.layout.activity_detail); ButterKnife.bind(this); setSupportActionBar(toolbar); getSupportActionBar().setDisplayHomeAsUpEnabled(true); getSupportActionBar().setDisplayShowTitleEnabled(false); movie = (Movie) getIntent().getSerializableExtra(Intent.EXTRA_TEXT); Picasso.with(this) .load(Parser.formatImageUrl(movie.backdropPath, getString(R.string.image_size_large))) .placeholder(new ColorDrawable(0xFFFFFF)) .into(backdropImage); if (savedInstanceState == null) { isFavourite = movie.isFavourite; isFavouriteOriginal = isFavourite; } Bundle arguments = new Bundle(); arguments.putSerializable(Intent.EXTRA_TEXT, movie); MovieDetailFragment movieDetailFragment = new MovieDetailFragment(); movieDetailFragment.setArguments(arguments); getSupportFragmentManager().beginTransaction() .replace(R.id.movie_detail_container, movieDetailFragment, MainActivity.MOVIE_DETAIL_FRAGMENT_TAG) .commit(); setFavButtonDrawable(); setUpLayoutMargins(); } @Override protected void onSaveInstanceState(Bundle outState) { super.onSaveInstanceState(outState); Icepick.saveInstanceState(this, outState); } /** * Changes margin of the content and {@link FloatingActionButton} according to the screen orientation. */ private void setUpLayoutMargins() { CoordinatorLayout.LayoutParams scrollViewParams = (CoordinatorLayout.LayoutParams) nestedScrollView.getLayoutParams(); AppBarLayout.ScrollingViewBehavior behavior = (AppBarLayout.ScrollingViewBehavior) scrollViewParams.getBehavior(); CoordinatorLayout.LayoutParams fabParams = (CoordinatorLayout.LayoutParams) favFab.getLayoutParams(); int overlayTopDimen = UI.dpToPx((int) getResources().getDimension(R.dimen.overlayTopDimen)); int wideMargin = UI.dpToPx((int) getResources().getDimension(R.dimen.content_detail_wide_margin)); int fabWideMargin = UI.dpToPx((int) getResources().getDimension(R.dimen.fab_margin)); if (getResources().getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE) { behavior.setOverlayTop(overlayTopDimen); scrollViewParams.setMargins(wideMargin, 0, wideMargin, 0); fabParams.setMargins(fabWideMargin, fabWideMargin, fabWideMargin, fabWideMargin); } else { behavior.setOverlayTop(0); scrollViewParams.setMargins(0, 0, 0, 0); } } @Override protected void onPause() { super.onPause(); overridePendingTransition(android.R.anim.fade_in, android.R.anim.fade_out); } @OnClick(R.id.fav_fab) public void onFabClick() { isFavourite = !isFavourite; setFavButtonDrawable(); } @Override public boolean onOptionsItemSelected(MenuItem item) { int id = item.getItemId(); switch (id) { case android.R.id.home: onBackPressed(); return true; default: break; } return super.onOptionsItemSelected(item); } @Override public void onBackPressed() { if (isFavouriteOriginal != isFavourite) { Cache.setFavouriteMovie(this, movie.getId(), isFavourite); Intent intent = new Intent(); intent.putExtra(getString(R.string.favourite_changed_key), true); intent.putExtra(getString(R.string.fav_movie_bool_key), isFavourite); intent.putExtra(getString(R.string.favourite_movie_id_key), movie.getId()); setResult(RESULT_OK, intent); finish(); } super.onBackPressed(); } @Override public void onStop() { super.onStop(); // Release loaders of YoutubeThumbnailView, otherwise Service connection leak occurs. if (VideosAdapter.viewLoaderMap == null) return; for (YouTubeThumbnailLoader loader : VideosAdapter.viewLoaderMap.values()) { loader.release(); } } private void setFavButtonDrawable() { favFab.setImageDrawable((isFavourite) ? favouriteDrawable : notFavouriteDrawable); } public void setFabVisibility(int visibility) { favFab.setVisibility(visibility); } }
apache-2.0
shopizer-ecommerce/shopizer
sm-shop/src/main/java/com/salesmanager/shop/store/api/v1/product/ProductGroupApi.java
9060
package com.salesmanager.shop.store.api.v1.product; import javax.inject.Inject; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.http.HttpStatus; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.DeleteMapping; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PatchMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.bind.annotation.ResponseStatus; import com.salesmanager.core.business.services.catalog.product.ProductService; import com.salesmanager.core.model.catalog.product.Product; import com.salesmanager.core.model.merchant.MerchantStore; import com.salesmanager.core.model.reference.language.Language; import com.salesmanager.shop.model.catalog.product.ReadableProductList; import com.salesmanager.shop.model.catalog.product.group.ProductGroup; import com.salesmanager.shop.store.controller.items.facade.ProductItemsFacade; import antlr.collections.List; import io.swagger.annotations.Api; import io.swagger.annotations.ApiImplicitParam; import io.swagger.annotations.ApiImplicitParams; import io.swagger.annotations.ApiOperation; import io.swagger.annotations.SwaggerDefinition; import io.swagger.annotations.Tag; import springfox.documentation.annotations.ApiIgnore; /** * Used for product grouping such as featured items * * @author carlsamson */ @Controller @RequestMapping("/api/v1") @Api(tags = { "Product groups management resource (Product Groups Management Api)" }) @SwaggerDefinition(tags = { @Tag(name = "Product groups management resource", description = "Product groups management") }) public class ProductGroupApi { @Inject private ProductService productService; @Inject private ProductItemsFacade productItemsFacade; private static final Logger LOGGER = LoggerFactory.getLogger(ProductGroupApi.class); @ResponseStatus(HttpStatus.OK) @PostMapping("/private/products/group") @ApiOperation(httpMethod = "POST", value = "Create product group", notes = "", response = ProductGroup.class) @ApiImplicitParams({ @ApiImplicitParam(name = "store", dataType = "String", defaultValue = "DEFAULT"), @ApiImplicitParam(name = "lang", dataType = "String", defaultValue = "en") }) public @ResponseBody ProductGroup creteGroup( @RequestBody ProductGroup group, @ApiIgnore MerchantStore merchantStore, @ApiIgnore Language language, HttpServletResponse response) throws Exception { return productItemsFacade.createProductGroup(group, merchantStore); } @ResponseStatus(HttpStatus.OK) @PatchMapping("/private/products/group/{code}") @ApiOperation(httpMethod = "PATCH", value = "Update product group visible flag", notes = "", response = ProductGroup.class) @ApiImplicitParams({ @ApiImplicitParam(name = "store", dataType = "String", defaultValue = "DEFAULT"), @ApiImplicitParam(name = "lang", dataType = "String", defaultValue = "en") }) public void updateGroup( @RequestBody ProductGroup group, @PathVariable String code, @ApiIgnore MerchantStore merchantStore, @ApiIgnore Language language, HttpServletResponse response) throws Exception { productItemsFacade.updateProductGroup(code, group, merchantStore); } @GetMapping("/private/products/groups") @ApiOperation(httpMethod = "GET", value = "Get products groups for a given merchant", notes = "", response = List.class) @ApiImplicitParams({ @ApiImplicitParam(name = "store", dataType = "String", defaultValue = "DEFAULT"), @ApiImplicitParam(name = "lang", dataType = "String", defaultValue = "en") }) public @ResponseBody java.util.List<ProductGroup> list( @ApiIgnore MerchantStore merchantStore, @ApiIgnore Language language, HttpServletResponse response) throws Exception { return productItemsFacade.listProductGroups(merchantStore, language); } /** * Query for a product group public/products/group/{code}?lang=fr|en no lang it will take session * lang or default store lang code can be any code used while creating product group, defeult * being FEATURED * * @param store * @param language * @param groupCode * @param request * @param response * @return * @throws Exception */ @ResponseStatus(HttpStatus.OK) @GetMapping("/products/group/{code}") @ApiOperation(httpMethod = "GET", value = "Get products by group code", notes = "", response = ReadableProductList.class) @ApiImplicitParams({ @ApiImplicitParam(name = "store", dataType = "String", defaultValue = "DEFAULT"), @ApiImplicitParam(name = "lang", dataType = "String", defaultValue = "en") }) public @ResponseBody ReadableProductList getProductItemsByGroup( @PathVariable final String code, @ApiIgnore MerchantStore merchantStore, @ApiIgnore Language language, HttpServletResponse response) throws Exception { try { ReadableProductList list = productItemsFacade.listItemsByGroup(code, merchantStore, language); if (list == null) { response.sendError(404, "Group not fount for code " + code); return null; } return list; } catch (Exception e) { LOGGER.error("Error while getting products", e); response.sendError(503, "An error occured while retrieving products " + e.getMessage()); } return null; } @ResponseStatus(HttpStatus.CREATED) @RequestMapping(value = "/private/products/{productId}/group/{code}", method = RequestMethod.POST) @ApiImplicitParams({ @ApiImplicitParam(name = "store", dataType = "String", defaultValue = "DEFAULT"), @ApiImplicitParam(name = "lang", dataType = "String", defaultValue = "en") }) public @ResponseBody ReadableProductList addProductToGroup( @PathVariable Long productId, @PathVariable String code, @ApiIgnore MerchantStore merchantStore, @ApiIgnore Language language, HttpServletResponse response) { Product product = null; try { // get the product product = productService.getById(productId); if (product == null) { response.sendError(404, "Product not fount for id " + productId); return null; } } catch (Exception e) { LOGGER.error("Error while adding product to group", e); try { response.sendError(503, "Error while adding product to group " + e.getMessage()); } catch (Exception ignore) { } return null; } ReadableProductList list = productItemsFacade.addItemToGroup(product, code, merchantStore, language); return list; } @ResponseStatus(HttpStatus.OK) @RequestMapping( value = "/private/products/{productId}/group/{code}", method = RequestMethod.DELETE) @ApiImplicitParams({ @ApiImplicitParam(name = "store", dataType = "String", defaultValue = "DEFAULT"), @ApiImplicitParam(name = "lang", dataType = "String", defaultValue = "en") }) public @ResponseBody ReadableProductList removeProductFromGroup( @PathVariable Long productId, @PathVariable String code, @ApiIgnore MerchantStore merchantStore, @ApiIgnore Language language, HttpServletRequest request, HttpServletResponse response) { try { // get the product Product product = productService.getById(productId); if (product == null) { response.sendError(404, "Product not fount for id " + productId); return null; } ReadableProductList list = productItemsFacade.removeItemFromGroup(product, code, merchantStore, language); return list; } catch (Exception e) { LOGGER.error("Error while removing product from category", e); try { response.sendError(503, "Error while removing product from category " + e.getMessage()); } catch (Exception ignore) { } return null; } } @ResponseStatus(HttpStatus.OK) @DeleteMapping("/products/group/{code}") @ApiOperation(httpMethod = "DELETE", value = "Delete product group by group code", notes = "", response = Void.class) @ApiImplicitParams({ @ApiImplicitParam(name = "store", dataType = "String", defaultValue = "DEFAULT"), @ApiImplicitParam(name = "lang", dataType = "String", defaultValue = "en") }) public void deleteGroup( @PathVariable final String code, @ApiIgnore MerchantStore merchantStore, @ApiIgnore Language language, HttpServletResponse response) { productItemsFacade.deleteGroup(code, merchantStore); } }
apache-2.0
aws/aws-sdk-java
aws-java-sdk-nimblestudio/src/main/java/com/amazonaws/services/nimblestudio/model/StreamingSessionStreamStatusCode.java
2130
/* * Copyright 2017-2022 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with * the License. A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR * CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions * and limitations under the License. */ package com.amazonaws.services.nimblestudio.model; import javax.annotation.Generated; /** * */ @Generated("com.amazonaws:aws-java-sdk-code-generator") public enum StreamingSessionStreamStatusCode { STREAM_CREATE_IN_PROGRESS("STREAM_CREATE_IN_PROGRESS"), STREAM_READY("STREAM_READY"), STREAM_DELETE_IN_PROGRESS("STREAM_DELETE_IN_PROGRESS"), STREAM_DELETED("STREAM_DELETED"), INTERNAL_ERROR("INTERNAL_ERROR"), NETWORK_CONNECTION_ERROR("NETWORK_CONNECTION_ERROR"); private String value; private StreamingSessionStreamStatusCode(String value) { this.value = value; } @Override public String toString() { return this.value; } /** * Use this in place of valueOf. * * @param value * real value * @return StreamingSessionStreamStatusCode corresponding to the value * * @throws IllegalArgumentException * If the specified value does not map to one of the known values in this enum. */ public static StreamingSessionStreamStatusCode fromValue(String value) { if (value == null || "".equals(value)) { throw new IllegalArgumentException("Value cannot be null or empty!"); } for (StreamingSessionStreamStatusCode enumEntry : StreamingSessionStreamStatusCode.values()) { if (enumEntry.toString().equals(value)) { return enumEntry; } } throw new IllegalArgumentException("Cannot create enum from " + value + " value!"); } }
apache-2.0
AlexandrebQueiroz/acal
src/TableModel/ContaHidrometroTableModel.java
305
/* * 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 TableModel; /** * * @author megalexandre */ public class ContaHidrometroTableModel { }
apache-2.0
chengzijian/Bibabo
Framework/src/main/java/com/bibabo/framework/utils/SecurityUtils.java
17239
package com.bibabo.framework.utils; import com.bibabo.framework.config.ConstantUtils; import java.io.UnsupportedEncodingException; import java.security.MessageDigest; import javax.crypto.Cipher; import javax.crypto.spec.IvParameterSpec; import javax.crypto.spec.SecretKeySpec; /** * @author hao.xiong * @version 1.0.0 */ public class SecurityUtils { private static final int ROUND_8BITS = 0x100; private static final int ROUND_4BITS = 0x10; private static final int RADIX_16 = 16; /** * Md5 Encryption * * @author hao.xiong * @version 1.0.0 */ public static class MD5 { private static final String ALGORITHM = "MD5"; /** * 对字符串进行md5加密处理 * * @param string 原始字符串 * @return 加密后的字符串 16位 */ public static String get16MD5String(String string) { byte[] md5 = stringToMD5(string); return to16HexString(md5); } /** * 对字符串进行md5加密处理 * * @param string 原始字符串 * @return 加密后的字符串 32位 */ public static String get32MD5String(String string) { byte[] md5 = stringToMD5(string); return to32HexString(md5); } private static byte[] stringToMD5(String string) { if (string == null) { return null; } try { MessageDigest digest = MessageDigest.getInstance(ALGORITHM); digest.update(string.getBytes()); return digest.digest(); } catch (Exception e) { e.printStackTrace(); } return null; } private static String to16HexString(byte[] md5) { if (md5 == null) { return null; } final int beginConvertIndex = 4; final int endConvertIndex = 11; final int intValueFF = 0xFF; StringBuilder stringBuffer = new StringBuilder(); for (int i = beginConvertIndex; i <= endConvertIndex; ++i) { stringBuffer.append(Integer.toHexString(intValueFF & md5[i])); } return stringBuffer.toString(); } private static String to32HexString(byte[] md5) { if (md5 == null) { return null; } int val; StringBuilder stringBuffer = new StringBuilder(""); for (byte b : md5) { val = b; if (val < 0) { val += ROUND_8BITS; } if (val < ROUND_4BITS) { stringBuffer.append("0"); } stringBuffer.append(Integer.toHexString(val)); } return stringBuffer.toString(); } } /** * TEA encrypt * * @author ke.di * @version 2.0.0 * @since Aug 12, 2011 */ public static final class TEA { private static final int DELTA = 0x9E3779B9; private static final int LOWER_LIMIT = 48; private static final int UPPER_LIMIT = 59; private static final int CONSTANT_5 = 5; private static final int CONSTANT_8 = 8; private static final int CONSTANT_10 = 10; private static final int CONSTANT_16 = 16; private static final int CONSTANT_32 = 32; private static final int INIT_SUM_ROUND32 = 0xC6EF3720; private static final int INIT_SUM_ROUND16 = 0xE3779B90; private static final int[] TEA_KEY = {0x091458856, 0x0FD2845C6, 0x0B681F893, 0x02F7C49B7}; private static final int DEFAULT_ROUND = 16; /** * 对字符串进行加密 * * @param string 原始字符串 * @return 加密后的字符串 */ public static String encrypt(String string) { if (StringUtils.isEmpty(string)) { return ConstantUtils.BLANK_STRING; } int[] plain = new int[2]; try { plain = preProcess(string); } catch (IllegalArgumentException e) { return ConstantUtils.BLANK_STRING; } int[] ret = teaEncrypt(plain, TEA_KEY, DEFAULT_ROUND); String values = String.format("%08x%08x", ret[0], ret[1]).toLowerCase(); StringBuilder result = new StringBuilder(); for (int i = 0; i < values.length(); i++) { String buffer = values.substring(i, i + 1); int nValues = Integer.valueOf(buffer, CONSTANT_16); if (nValues >= CONSTANT_10) { result.append(nValues - CONSTANT_10); } else { result.append(nValues); } } return result.toString(); } private static int[] preProcess(String string) { StringBuilder stringBuilder = new StringBuilder(string.trim()); if (stringBuilder.toString().equals("0")) { throw new IllegalArgumentException(); } boolean hasCharacter = false; for (int i = 0; i < stringBuilder.length(); i++) { int c = stringBuilder.charAt(i); if ((c < LOWER_LIMIT) || c > UPPER_LIMIT) { hasCharacter = true; break; } } if (stringBuilder.length() < CONSTANT_16) { while (stringBuilder.length() < CONSTANT_16) { stringBuilder.append("0"); } } long l1; long l2; if (hasCharacter) { Long tmp1 = Long.parseLong(stringBuilder.substring(0, CONSTANT_8), RADIX_16); Long tmp2 = Long.parseLong(stringBuilder.substring(CONSTANT_8, CONSTANT_16), RADIX_16); l1 = tmp1; l2 = tmp2; } else { l1 = Long.valueOf(stringBuilder.substring(0, CONSTANT_8), RADIX_16); l2 = Long.valueOf(stringBuilder.substring(CONSTANT_8, CONSTANT_16), RADIX_16); } int[] plain = new int[2]; plain[0] = (int) l1; plain[1] = (int) l2; return plain; } /** * encrypt with tea algorithm * * @param aIn input 4-bytes * @param aKey key used for encrypt * @param aRound loop count * @return encrypted output 4-bytes */ public static int[] teaEncrypt(int[] aIn, int[] aKey, int aRound) { int y = aIn[0], z = aIn[1], sum = 0; /* set up */ int a = aKey[0], b = aKey[1], c = aKey[2], d = aKey[3]; /* cache key */ int i; for (i = 0; i < aRound; i++) { /* basic cycle start */ sum += DELTA; y += ((z << 4) + a) ^ (z + sum) ^ ((z >>> CONSTANT_5) + b); z += ((y << 4) + c) ^ (y + sum) ^ ((y >>> CONSTANT_5) + d); /* end cycle */ } int[] out = new int[2]; out[0] = y; out[1] = z; return out; } /** * decrypt with tea algorithm * * @param aOut decrypt output 4-bytes * @param aIn encrypted input 4-bytes * @param aKey key used for decrypt * @param aRound loop count */ public static void teaDecrypt(int[] aOut, int[] aIn, int[] aKey, int aRound) { int y = aIn[0], z = aIn[1], sum; int a = aKey[0], b = aKey[1], c = aKey[2], d = aKey[3]; if (aRound == CONSTANT_32) { sum = INIT_SUM_ROUND32; } else if (aRound == CONSTANT_16) { sum = INIT_SUM_ROUND16; } else { sum = DELTA * aRound; } for (int i = 0; i < aRound; i++) { z -= (((y << 4) + c) ^ (y + sum) ^ ((y >>> CONSTANT_5) + d)); y -= (((z << 4) + a) ^ (z + sum) ^ ((z >>> CONSTANT_5) + b)); sum -= DELTA; } aOut[0] = y; aOut[1] = z; } } /** * CR4 加密简单版 * * @author yu.liu * @version 1.0.0 */ public static class RC4 { private static final int BYTE_MASK = 0xFF; private static final byte[] RAW_KEY = {99, 7, 66, 74, -81, -36, 45, -18, 106, 25, 126, 6, 71, -67, 47, 108, 116, 117, 113, 121, 78, 109, -119, 62, 29, 23, 24, 76, 125, -62, -89, 0, -72, 82, 102, 50, -51, 100, 81, 65, -105, -26, -65, 88, -74, 89, -69, 18, 87, 44, -23, -20, -63, 36, -88, 79, -32, 26, -115, -10, -127, -49, 124, -122, -6, 122, 91, 12, 70, -29, -31, 14, -2, -12, -123, 84, 27, 97, -87, -84, 98, 41, 120, 59, 39, -104, 52, 101, 33, 35, -17, 105, -86, -57, 75, -76, -128, 64, 3, -33, 119, 95, 57, -73, 60, -68, 1, 69, 46, 86, 42, -98, -99, -9, 118, -95, -16, -41, 54, -124, 17, -107, 10, -121, -97, -106, 55, -14, -96, -116, 110, -4, -94, 56, -21, 30, -55, -47, 31, 58, 37, -46, 83, -30, -93, 61, 123, -120, -85, -111, -66, -102, -113, -50, -110, -8, -91, 68, 107, 112, -27, -64, 90, -45, 4, -118, 115, -92, 72, -15, 67, -83, -56, -52, 51, -39, -19, -13, 114, 2, -53, -1, 16, -48, -7, -58, -117, -77, 93, 53, -101, -38, -126, -44, 11, -59, 103, 5, -80, 63, -82, -114, -5, -71, -28, -78, -42, -103, 19, 48, -43, 49, 34, -25, 22, 92, 80, -22, 32, 127, 104, -125, 20, 38, 15, 94, -11, -100, 8, -3, -79, 43, -24, 73, 9, -54, -108, -35, 96, -109, 111, -34, -40, -60, 77, 40, 28, 13, -70, 21, -75, -90, -37, -112, -61, 85}; /** * 加密 * * @param string 需要加密的字符串 * @return 加密后的数据 */ public static String encrypt(String string) { if (string == null) { return null; } try { string = asString(rc4Base(string.getBytes("UTF-8"))); } catch (UnsupportedEncodingException e) { string = ConstantUtils.BLANK_STRING; } return toHexString(string); } /** * 解密 * * @param string 需要解密的字符串 * @return 解密后的数据,错误返回 null */ public static String decrypt(String string) { if (string == null) { return null; } return new String(rc4Base(hexString2Bytes(string))); } private static String asString(byte[] buf) { StringBuffer stringBuffer = new StringBuffer(buf.length); for (int i = 0; i < buf.length; i++) { stringBuffer.append((char) buf[i]); } return stringBuffer.toString(); } private static String toHexString(String s) { String str = ""; for (int i = 0; i < s.length(); i++) { int ch = (int) s.charAt(i); String s4 = Integer.toHexString(ch & BYTE_MASK); if (s4.length() == 1) { s4 = '0' + s4; } str = str + s4; } return str; } private static byte[] hexString2Bytes(String src) { int size = src.length(); byte[] ret = new byte[size / 2]; byte[] tmp = src.getBytes(); for (int i = 0; i < size / 2; i++) { ret[i] = uniteBytes(tmp[i * 2], tmp[i * 2 + 1]); } return ret; } private static byte uniteBytes(byte src0, byte src1) { char b0 = (char) Byte.decode("0x" + new String(new byte[]{src0})) .byteValue(); final int bitOffset = 4; b0 = (char) (b0 << bitOffset); char b1 = (char) Byte.decode("0x" + new String(new byte[]{src1})) .byteValue(); byte ret = (byte) (b0 ^ b1); return ret; } private static byte[] rc4Base(byte[] input) { int x = 0; int y = 0; byte[] key = RAW_KEY.clone(); int xorIndex; byte[] result = new byte[input.length]; for (int i = 0; i < input.length; i++) { x = (x + 1) & BYTE_MASK; y = ((key[x] & BYTE_MASK) + y) & BYTE_MASK; byte tmp = key[x]; key[x] = key[y]; key[y] = tmp; xorIndex = ((key[x] & BYTE_MASK) + (key[y] & BYTE_MASK)) & BYTE_MASK; result[i] = (byte) (input[i] ^ key[xorIndex]); } return result; } } /** * @author yu.liu * @version 1.0.0 * @since 2012-10-17 * 注意: 加密后的byte数组是不能强制转换成字符串的, * 换言之:字符串和byte数组在这种情况下不是互逆的; * 要避免这种情况,方便外界调用 * 可以考虑将二进制数据转换成十六进制表示, * 故增加了 toHex 等几个函数进行封装 */ public static class AES { private static final String VIPARA = "0102030405060708"; private static final byte[] RAW_KEY = {84, 65, -33, 92, 57, 90, -104, 0, 112, 74, 69, -53, 106, -122, -107, -95}; private static final String ALGORITHM = "AES/CBC/PKCS5Padding"; /** * 对字符串进行AES加密 * * @param string 未加密的字符串 * @return 加密后的字符串 * @throws Exception e */ public static String encrypt(String string) throws Exception { byte[] encrypted = encrypt(RAW_KEY, string.getBytes()); return toHex(encrypted); } /** * 解密 * * @param string 已加密的字符串 * @return 解密后的字符串 * @throws Exception e */ public static String decrypt(String string) throws Exception { byte[] encrypted = toByte(string); byte[] result = decrypt(RAW_KEY, encrypted); return new String(result); } private static byte[] encrypt(byte[] raw, byte[] clear) throws Exception { IvParameterSpec zeroIv = new IvParameterSpec(VIPARA.getBytes()); SecretKeySpec keySpec = new SecretKeySpec(raw, "AES"); Cipher cipher = Cipher.getInstance(ALGORITHM); cipher.init(Cipher.ENCRYPT_MODE, keySpec, zeroIv); byte[] encrypted = cipher.doFinal(clear); return encrypted; } private static byte[] decrypt(byte[] raw, byte[] encrypted) throws Exception { IvParameterSpec zeroIv = new IvParameterSpec(VIPARA.getBytes()); SecretKeySpec keySpec = new SecretKeySpec(raw, "AES"); Cipher cipher = Cipher.getInstance(ALGORITHM); cipher.init(Cipher.DECRYPT_MODE, keySpec, zeroIv); byte[] decrypted = cipher.doFinal(encrypted); return decrypted; } private static byte[] toByte(String hexString) { int len = hexString.length() / 2; byte[] result = new byte[len]; for (int i = 0; i < len; i++) { result[i] = Integer.valueOf(hexString.substring(2 * i, 2 * i + 2), RADIX_16).byteValue(); } return result; } private static String toHex(byte[] buf) { if (buf == null) { return ""; } StringBuffer result = new StringBuffer(2 * buf.length); for (int i = 0; i < buf.length; i++) { appendHex(result, buf[i]); } return result.toString(); } private final static String HEX = "0123456789ABCDEF"; private static void appendHex(StringBuffer sb, byte b) { final int flagOfLowByte = 0x0f; final int shift = 4; sb.append(HEX.charAt((b >> shift) & flagOfLowByte)).append(HEX.charAt(b & flagOfLowByte)); } /** * 为避免每次都生成rawkey, 提高效率,记录了一次生成的rawkey, * 客户端和服务器端采用相同rawkey就可以加密解密了。 */ // private static byte[] getRawKey(byte[] seed) throws Exception { // KeyGenerator keyGenerator = KeyGenerator.getInstance("AES"); // SecureRandom sr = SecureRandom.getInstance("SHA1PRNG"); // sr.setSeed(seed); // final int kBitsOfAes = 128; // aes 的密钥长度 // keyGenerator.init(kBitsOfAes, sr); // 192 and 256 bits may not be available // SecretKey secretKey = keyGenerator.generateKey(); // byte[] raw = secretKey.getEncoded(); // return raw; // } } }
apache-2.0
JuananIBM/WebCompanies
src/main/java/com/juanan/pocs/companies/web/controller/InicioController.java
2702
package com.juanan.pocs.companies.web.controller; import javax.servlet.http.HttpSession; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.servlet.ModelAndView; import com.juanan.pocs.companies.web.bean.UsuarioSesion; @Controller @RequestMapping("AppStart") public class InicioController { final static Logger logger = LogManager.getLogger(InicioController.class); @RequestMapping(value = "", method = RequestMethod.GET) public ModelAndView cargaPaginaInicio(HttpSession session) { UsuarioSesion usuarioSesion = (UsuarioSesion) session.getAttribute("usuarioSesion"); if (usuarioSesion == null){ usuarioSesion = new UsuarioSesion(); session.setAttribute("usuarioSesion", usuarioSesion); //Comentar cuando se quiera utilizar la funcionalidad de logado //session.setAttribute("usuarioSesion", new UsuarioSesion("Juanan",true,"2016")); } ModelAndView modelAndView = new ModelAndView("paginaContenedora"); return modelAndView; } @RequestMapping(value = "Login", method = RequestMethod.POST) public String iniciarSesion( @RequestParam(value = "username", required = true) String username, @RequestParam(value = "password", required = true) String password, HttpSession session) { UsuarioSesion usuarioSesion = (UsuarioSesion) session.getAttribute("usuarioSesion"); if (usuarioSesion == null){ usuarioSesion = new UsuarioSesion(); } if ("juanan".equalsIgnoreCase(username) && "juanan".equals(password)){ usuarioSesion.setNombre("Juanan"); usuarioSesion.setAdministrador(true); } session.setAttribute("usuarioSesion", usuarioSesion); return "redirect:/AppStart"; } @RequestMapping(value = "Logout", method = RequestMethod.GET) public String finalizarSesion(HttpSession session) { UsuarioSesion usuarioSesion = new UsuarioSesion(); session.setAttribute("usuarioSesion", usuarioSesion); return "redirect:/AppStart"; } @RequestMapping(value = "ChangeYear", method = RequestMethod.POST) public String cambiarAnyo( @RequestParam(value = "anyo", required = true) String anyo, HttpSession session) { UsuarioSesion usuarioSesion = (UsuarioSesion) session.getAttribute("usuarioSesion"); if (usuarioSesion == null){ usuarioSesion = new UsuarioSesion(); } usuarioSesion.setAnyoMongoDB(anyo); session.setAttribute("usuarioSesion", usuarioSesion); return "redirect:/AppStart"; } }
apache-2.0
MissionCriticalCloud/cosmic
cosmic-model/src/main/java/com/cloud/legacymodel/to/PublicIpACLTO.java
3620
package com.cloud.legacymodel.to; import com.cloud.legacymodel.InternalIdentity; import com.cloud.legacymodel.network.vpc.NetworkACLItem; import com.cloud.legacymodel.network.vpc.NetworkACLItem.TrafficType; import java.util.ArrayList; import java.util.List; public class PublicIpACLTO implements InternalIdentity { long id; String publicIp; String protocol; int[] portRange; boolean revoked; boolean alreadyAdded; String action; int number; private List<String> cidrList; private Integer icmpType; private Integer icmpCode; private TrafficType trafficType; protected PublicIpACLTO() { } public PublicIpACLTO(final NetworkACLItem rule, final String publicIp, final TrafficType trafficType) { this(rule.getId(), publicIp, rule.getProtocol(), rule.getSourcePortStart(), rule.getSourcePortEnd(), rule.getState() == NetworkACLItem.State.Revoke, rule.getState() == NetworkACLItem.State.Active, rule.getSourceCidrList(), rule.getIcmpType(), rule.getIcmpCode(), trafficType, rule.getAction() == NetworkACLItem.Action.Allow, rule.getNumber()); } public PublicIpACLTO(final long id, final String publicIp, final String protocol, final Integer portStart, final Integer portEnd, final boolean revoked, final boolean alreadyAdded, final List<String> cidrList, final Integer icmpType, final Integer icmpCode, final TrafficType trafficType, final boolean allow, final int number) { this.publicIp = publicIp; this.protocol = protocol; if (portStart != null) { final List<Integer> range = new ArrayList<>(); range.add(portStart); if (portEnd != null) { range.add(portEnd); } portRange = new int[range.size()]; int i = 0; for (final Integer port : range) { portRange[i] = port.intValue(); i++; } } this.revoked = revoked; this.alreadyAdded = alreadyAdded; this.cidrList = cidrList; this.icmpType = icmpType; this.icmpCode = icmpCode; this.trafficType = trafficType; if (!allow) { this.action = "DROP"; } else { this.action = "ACCEPT"; } this.number = number; } @Override public long getId() { return id; } public String getPublicIp() { return publicIp; } public String getProtocol() { return protocol; } public int[] getSrcPortRange() { return portRange; } public Integer getIcmpType() { return icmpType; } public Integer getIcmpCode() { return icmpCode; } public String getStringPortRange() { if (portRange == null || portRange.length < 2) { return "0:0"; } else { return Integer.toString(portRange[0]) + ":" + Integer.toString(portRange[1]); } } public boolean revoked() { return revoked; } public List<String> getSourceCidrList() { return cidrList; } public boolean isAlreadyAdded() { return alreadyAdded; } public TrafficType getTrafficType() { return trafficType; } public String getAction() { return action; } public int getNumber() { return number; } }
apache-2.0
Sargul/dbeaver
plugins/org.jkiss.dbeaver.model/src/org/jkiss/dbeaver/model/access/DBASession.java
1359
/* * DBeaver - Universal Database Manager * Copyright (C) 2010-2021 DBeaver Corp and others * * 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.jkiss.dbeaver.model.access; import org.jkiss.code.NotNull; import org.jkiss.code.Nullable; import org.jkiss.dbeaver.model.DBPObject; import org.jkiss.dbeaver.model.app.DBPProject; import org.jkiss.dbeaver.model.auth.DBAAuthSpace; /** * Access session */ public interface DBASession extends DBPObject { /** * Session space */ @NotNull DBAAuthSpace getSessionSpace(); /** * Session unique ID */ @NotNull String getSessionId(); /** * Application session is a global singleton session */ boolean isApplicationSession(); /** * Singleton session project */ @Nullable DBPProject getSingletonProject(); }
apache-2.0
akarnokd/Reactive4JavaFlow
src/test/java/hu/akarnokd/reactive4javaflow/impl/operators/FolyamMapWhenTest.java
10364
/* * Copyright 2017 David Karnok * * 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 hu.akarnokd.reactive4javaflow.impl.operators; import hu.akarnokd.reactive4javaflow.*; import org.junit.Test; import java.io.IOException; public class FolyamMapWhenTest { @Test public void normal() { Folyam.range(1, 5) .mapWhen(Folyam::just) .test() .assertResult(1, 2, 3, 4, 5); } @Test public void normalConditional() { Folyam.range(1, 5) .mapWhen(Folyam::just) .filter(v -> true) .test() .assertResult(1, 2, 3, 4, 5); } @Test public void standard() { TestHelper.assertResult( Folyam.range(1, 5) .mapWhen(Folyam::just), 1, 2, 3, 4, 5); } @Test public void standardHidden() { TestHelper.assertResult( Folyam.range(1, 5) .mapWhen(item -> Folyam.just(item).hide()), 1, 2, 3, 4, 5); } @Test public void standard2() { TestHelper.assertResult( Folyam.range(1, 5) .mapWhen(Folyam::just, 1), 1, 2, 3, 4, 5); } @Test public void standard3() { TestHelper.assertResult( Folyam.range(1, 5) .mapWhen(Folyam::just, (a, b) -> a + b), 2, 4, 6, 8, 10); } @Test public void standard4() { TestHelper.assertResult( Folyam.range(1, 5) .mapWhen(Folyam::just, (a, b) -> a + b, 1), 2, 4, 6, 8, 10); } @Test public void standard5() { TestHelper.assertResult( Folyam.range(1, 5) .mapWhenDelayError(Folyam::just, (a, b) -> a + b, 128), 2, 4, 6, 8, 10); } @Test public void standard6() { TestHelper.assertResult( Folyam.range(1, 5) .mapWhenDelayError(Folyam::just, (a, b) -> a + b, 1), 2, 4, 6, 8, 10); } @Test public void standard7() { TestHelper.assertResult( Folyam.range(1, 5) .mapWhen(v -> Folyam.range(v, 2)), 1, 2, 3, 4, 5); } @Test public void emptyOuter() { TestHelper.assertResult( Folyam.empty() .mapWhen(Folyam::just) ); } @Test public void emptyInner() { TestHelper.assertResult( Folyam.range(1, 5) .mapWhen(v -> Folyam.empty()) ); } @Test public void emptyInnerHidden() { TestHelper.assertResult( Folyam.range(1, 5) .mapWhen(v -> Folyam.empty().hide()) ); } @Test public void mainError() { Folyam.error(new IOException()) .mapWhen(Folyam::just) .test() .assertFailure(IOException.class); } @Test public void mainErrorConditional() { Folyam.error(new IOException()) .mapWhen(Folyam::just) .filter(v -> true) .test() .assertFailure(IOException.class); } @Test public void innerError() { Folyam.just(1) .mapWhen(v -> Folyam.error(new IOException())) .test() .assertFailure(IOException.class); } @Test public void innerErrorConditional() { Folyam.just(1) .mapWhen(v -> Folyam.error(new IOException())) .filter(v -> true) .test() .assertFailure(IOException.class); } @Test public void innerErrorHidden() { Folyam.just(1) .mapWhen(v -> Folyam.error(new IOException()).hide()) .test() .assertFailure(IOException.class); } @Test public void innerErrorConditionalHidden() { Folyam.just(1) .mapWhen(v -> Folyam.error(new IOException()).hide()) .filter(v -> true) .test() .assertFailure(IOException.class); } @Test public void innerErrorDelayed() { Folyam.just(1) .mapWhenDelayError(v -> Folyam.error(new IOException())) .test() .assertFailure(IOException.class); } @Test public void innerErrorConditionalDelayed() { Folyam.just(1) .mapWhenDelayError(v -> Folyam.error(new IOException())) .filter(v -> true) .test() .assertFailure(IOException.class); } @Test public void someInnerErrorDelayed() { Folyam.range(1, 3) .mapWhenDelayError(v -> { if (v == 2) { return Folyam.error(new IOException()); } return Folyam.just(v); }) .test() .assertFailure(IOException.class, 1, 3); } @Test public void someInnerErrorDelayedConditional() { Folyam.range(1, 3) .mapWhenDelayError(v -> { if (v == 2) { return Folyam.error(new IOException()); } return Folyam.just(v); }) .filter(v -> true) .test() .assertFailure(IOException.class, 1, 3); } @Test public void mapperCrash() { Folyam.range(1, 3) .mapWhen(v -> { throw new IOException(); }) .test() .assertFailure(IOException.class); } @Test public void mapperCrashConditional() { Folyam.range(1, 3) .mapWhen(v -> { throw new IOException(); }) .filter(v -> true) .test() .assertFailure(IOException.class); } @Test public void mapperCrashDelayError() { Folyam.range(1, 3) .mapWhenDelayError(v -> { throw new IOException(); }) .test() .assertFailure(IOException.class); } @Test public void mapperCrashConditionalDelayError() { Folyam.range(1, 3) .mapWhenDelayError(v -> { throw new IOException(); }) .filter(v -> true) .test() .assertFailure(IOException.class); } @Test public void combinerCrash() { Folyam.range(1, 3) .mapWhen(Folyam::just, (a, b) -> { throw new IOException(); }) .test() .assertFailure(IOException.class); } @Test public void combinerCrashConditional() { Folyam.range(1, 3) .mapWhen(Folyam::just, (a, b) -> { throw new IOException(); }) .filter(v -> true) .test() .assertFailure(IOException.class); } @Test public void combinerCrashDelayError() { Folyam.range(1, 3) .mapWhenDelayError(Folyam::just, (a, b) -> { throw new IOException(); }) .test() .assertFailure(IOException.class); } @Test public void combinerCrashConditionalDelayError() { Folyam.range(1, 3) .mapWhenDelayError(Folyam::just, (a, b) -> { throw new IOException(); }) .filter(v -> true) .test() .assertFailure(IOException.class); } @Test public void normalLong() { Folyam.range(1, 1000) .mapWhen(Folyam::just) .test() .assertValueCount(1000) .assertNoErrors() .assertComplete(); } @Test public void normalLongConditional() { Folyam.range(1, 1000) .mapWhen(Folyam::just) .filter(v -> true) .test() .assertValueCount(1000) .assertNoErrors() .assertComplete(); } @Test public void combinerCrashDelayErrorHidden() { Folyam.range(1, 3) .mapWhenDelayError(v -> Folyam.just(1).hide(), (a, b) -> { throw new IOException(); }) .test() .assertFailure(IOException.class); } @Test public void combinerCrashConditionalDelayErrorHidden() { Folyam.range(1, 3) .mapWhenDelayError(v -> Folyam.just(1).hide(), (a, b) -> { throw new IOException(); }) .filter(v -> true) .test() .assertFailure(IOException.class); } @Test public void normalLongHidden() { Folyam.range(1, 1000) .mapWhen(v -> Folyam.just(v).hide()) .test() .assertValueCount(1000) .assertNoErrors() .assertComplete(); } @Test public void normalLongConditionalHidden() { Folyam.range(1, 1000) .mapWhen(v -> Folyam.just(v).hide()) .filter(v -> true) .test() .assertValueCount(1000) .assertNoErrors() .assertComplete(); } @Test public void emptyLongHidden() { Folyam.range(1, 1000) .mapWhen(v -> Folyam.empty().hide()) .test() .assertResult(); } @Test public void emptyLongConditionalHidden() { Folyam.range(1, 1000) .mapWhen(v -> Folyam.empty().hide()) .filter(v -> true) .test() .assertResult(); } }
apache-2.0
HuangLS/neo4j
community/kernel/src/test/java/org/neo4j/helpers/TestExceptions.java
5841
/* * Copyright (c) 2002-2018 "Neo Technology," * Network Engine for Objects in Lund AB [http://neotechnology.com] * * This file is part of Neo4j. * * Neo4j is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package org.neo4j.helpers; import org.junit.Test; import static org.junit.Assert.assertArrayEquals; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertSame; import static org.junit.Assert.assertTrue; public class TestExceptions { @Test public void canPeelExceptions() throws Exception { // given Throwable expected; Throwable exception = new LevelOneException( "", new LevelTwoException( "", new LevelThreeException( "", expected = new LevelThreeException( "include", new LevelFourException( "" ) ) ) ) ); // when Throwable peeled = Exceptions.peel( exception, new org.neo4j.function.Predicate<Throwable>() { @Override public boolean test( Throwable item ) { return !(item instanceof LevelThreeException) || !item.getMessage().contains( "include" ); } } ); // then assertEquals( expected, peeled ); } @Test public void canPeelUsingConveniencePredicate() throws Exception { // given Throwable expected; Throwable exception = new ARuntimeException( new AnotherRuntimeException( new LevelFourException( "", expected = new LevelThreeException( "", new LevelFourException( "" ) ) ) ) ); // when Throwable peeled = Exceptions.peel( exception, org.neo4j.function.Predicates.<Throwable>instanceOfAny( RuntimeException.class, LevelFourException.class ) ); // then assertEquals( expected, peeled ); } @Test public void shouldDetectContainsOneOfSome() throws Exception { // GIVEN Throwable cause = new ARuntimeException( new AnotherRuntimeException( new NullPointerException( "Some words" ) ) ); // THEN assertTrue( Exceptions.contains( cause, NullPointerException.class ) ); assertTrue( Exceptions.contains( cause, "words", NullPointerException.class ) ); assertFalse( Exceptions.contains( cause, "not", NullPointerException.class ) ); } @Test public void shouldSetMessage() throws Exception { // GIVEN String initialMessage = "Initial message"; LevelOneException exception = new LevelOneException( initialMessage ); // WHEN String prependedMessage = "Prepend this: " + exception.getMessage(); Exceptions.withMessage( exception, prependedMessage ); // THEN assertEquals( prependedMessage, exception.getMessage() ); } @Test public void shouldAddSuppressedExceptions() { // Given RuntimeException exception = new RuntimeException(); RuntimeException suppressed1 = new RuntimeException(); RuntimeException suppressed2 = new RuntimeException(); // When RuntimeException result = Exceptions.withSuppressed( exception, suppressed1, suppressed2 ); // Then assertSame( exception, result ); assertArrayEquals( new Throwable[]{suppressed1, suppressed2}, result.getSuppressed() ); } private static class LevelOneException extends Exception { public LevelOneException( String message ) { super( message ); } public LevelOneException( String message, Throwable cause ) { super( message, cause ); } } private static class LevelTwoException extends LevelOneException { public LevelTwoException( String message ) { super( message ); } public LevelTwoException( String message, Throwable cause ) { super( message, cause ); } } private static class LevelThreeException extends LevelTwoException { public LevelThreeException( String message ) { super( message ); } public LevelThreeException( String message, Throwable cause ) { super( message, cause ); } } private static class LevelFourException extends LevelThreeException { public LevelFourException( String message ) { super( message ); } public LevelFourException( String message, Throwable cause ) { super( message, cause ); } } private static class ARuntimeException extends RuntimeException { public ARuntimeException( Throwable cause ) { super( cause ); } } private static class AnotherRuntimeException extends RuntimeException { public AnotherRuntimeException( Throwable cause ) { super( cause ); } } }
apache-2.0
joy-inc/joy-library
library-joy/src/main/java/com/joy/library/share/weibo/openapi/legacy/TagsAPI.java
4888
/* * Copyright (C) 2010-2013 The SINA WEIBO Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.joy.library.share.weibo.openapi.legacy; import android.content.Context; import com.sina.weibo.sdk.auth.Oauth2AccessToken; import com.sina.weibo.sdk.net.RequestListener; import com.sina.weibo.sdk.net.WeiboParameters; import com.joy.library.share.weibo.openapi.AbsOpenAPI; /** * 该类封装了标签接口。 * 详情请参考<a href="http://t.cn/8F1nHUA">标签接口</a> * * @author SINA * @date 2014-03-03 */ public class TagsAPI extends AbsOpenAPI { public TagsAPI(Context context, String appKey, Oauth2AccessToken accessToken) { super(context, appKey, accessToken); } private static final String SERVER_URL_PRIX = API_SERVER + "/tags"; /** * 返回指定用户的标签列表。 * * @param uid 要获取的标签列表所属的用户ID * @param count 单页返回的记录条数,默认为20 * @param page 返回结果的页码,默认为1 * @param listener 异步请求回调接口 */ public void tags(long uid, int count, int page, RequestListener listener) { WeiboParameters params = new WeiboParameters(mAppKey); params.put("uid", uid); params.put("count", count); params.put("page", page); requestAsync(SERVER_URL_PRIX + ".json", params, HTTPMETHOD_GET, listener); } /** * 批量获取用户的标签列表。 * * @param uids 要获取标签的用户ID。最大20 * @param listener 异步请求回调接口 */ public void tagsBatch(String[] uids, RequestListener listener) { WeiboParameters params = new WeiboParameters(mAppKey); StringBuilder strb = new StringBuilder(); for (String uid : uids) { strb.append(uid).append(","); } strb.deleteCharAt(strb.length() - 1); params.put("uids", strb.toString()); requestAsync(SERVER_URL_PRIX + "/tags_batch.json", params, HTTPMETHOD_GET, listener); } /** * 获取系统推荐的标签列表。 * * @param count 返回记录数,默认10,最大10 * @param listener 异步请求回调接口 */ public void suggestions(int count, RequestListener listener) { WeiboParameters params = new WeiboParameters(mAppKey); params.put("count", count); requestAsync(SERVER_URL_PRIX + "/suggestions.json", params, HTTPMETHOD_GET, listener); } /** * 为当前登录用户添加新的用户标签(无论调用该接口次数多少,每个用户最多可以创建10个标签)。 * * @param tags 要创建的一组标签,每个标签的长度不可超过7个汉字,14个半角字符 * @param listener 异步请求回调接口 */ public void create(String[] tags, RequestListener listener) { WeiboParameters params = new WeiboParameters(mAppKey); StringBuilder strb = new StringBuilder(); for (String tag : tags) { strb.append(tag).append(","); } strb.deleteCharAt(strb.length() - 1); params.put("tags", strb.toString()); requestAsync(SERVER_URL_PRIX + "/create.json", params, HTTPMETHOD_POST, listener); } /** * 删除一个用户标签。 * * @param tag_id 要删除的标签ID * @param listener 异步请求回调接口 */ public void destroy(long tag_id, RequestListener listener) { WeiboParameters params = new WeiboParameters(mAppKey); params.put("tag_id", tag_id); requestAsync(SERVER_URL_PRIX + "/destroy.json", params, HTTPMETHOD_POST, listener); } /** * 批量删除一组标签。 * * @param ids 要删除的一组标签ID,一次最多提交10个ID * @param listener 异步请求回调接口 */ public void destroyBatch(String[] ids, RequestListener listener) { WeiboParameters params = new WeiboParameters(mAppKey); StringBuilder strb = new StringBuilder(); for (String id : ids) { strb.append(id).append(","); } strb.deleteCharAt(strb.length() - 1); params.put("ids", strb.toString()); requestAsync(SERVER_URL_PRIX + "/destroy_batch.json", params, HTTPMETHOD_POST, listener); } }
apache-2.0
cloudera-labs/phoenix
phoenix-core/src/main/java/org/apache/phoenix/parse/ParseNodeFactory.java
31006
/* * 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.phoenix.parse; import java.lang.reflect.Constructor; import java.sql.SQLException; import java.util.Arrays; import java.util.Collections; import java.util.List; import java.util.Map; import java.util.concurrent.atomic.AtomicInteger; import org.apache.hadoop.hbase.filter.CompareFilter.CompareOp; import org.apache.hadoop.hbase.util.Pair; import org.apache.phoenix.exception.UnknownFunctionException; import org.apache.phoenix.expression.Expression; import org.apache.phoenix.expression.ExpressionType; import org.apache.phoenix.expression.function.AvgAggregateFunction; import org.apache.phoenix.expression.function.CountAggregateFunction; import org.apache.phoenix.expression.function.CurrentDateFunction; import org.apache.phoenix.expression.function.CurrentTimeFunction; import org.apache.phoenix.expression.function.DistinctCountAggregateFunction; import org.apache.phoenix.expression.function.FunctionExpression; import org.apache.phoenix.parse.FunctionParseNode.BuiltInFunction; import org.apache.phoenix.parse.FunctionParseNode.BuiltInFunctionInfo; import org.apache.phoenix.parse.JoinTableNode.JoinType; import org.apache.phoenix.parse.LikeParseNode.LikeType; import org.apache.phoenix.schema.PIndexState; import org.apache.phoenix.schema.PTable.IndexType; import org.apache.phoenix.schema.PTableType; import org.apache.phoenix.schema.SortOrder; import org.apache.phoenix.schema.TypeMismatchException; import org.apache.phoenix.schema.stats.StatisticsCollectionScope; import org.apache.phoenix.schema.types.PDataType; import org.apache.phoenix.schema.types.PTimestamp; import org.apache.phoenix.util.SchemaUtil; import com.google.common.collect.ListMultimap; import com.google.common.collect.Lists; import com.google.common.collect.Maps; /** * * Factory used by parser to construct object model while parsing a SQL statement * * * @since 0.1 */ public class ParseNodeFactory { private static final String ARRAY_ELEM = "ARRAY_ELEM"; // TODO: Use Google's Reflection library instead to find aggregate functions @SuppressWarnings("unchecked") private static final List<Class<? extends FunctionExpression>> CLIENT_SIDE_BUILT_IN_FUNCTIONS = Arrays.<Class<? extends FunctionExpression>>asList( CurrentDateFunction.class, CurrentTimeFunction.class, AvgAggregateFunction.class ); private static final Map<BuiltInFunctionKey, BuiltInFunctionInfo> BUILT_IN_FUNCTION_MAP = Maps.newHashMap(); /** * * Key used to look up a built-in function using the combination of * the lowercase name and the number of arguments. This disambiguates * the aggregate MAX(<col>) from the non aggregate MAX(<col1>,<col2>). * * * @since 0.1 */ private static class BuiltInFunctionKey { private final String upperName; private final int argCount; private BuiltInFunctionKey(String lowerName, int argCount) { this.upperName = lowerName; this.argCount = argCount; } @Override public String toString() { return upperName; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + argCount; result = prime * result + ((upperName == null) ? 0 : upperName.hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; BuiltInFunctionKey other = (BuiltInFunctionKey)obj; if (argCount != other.argCount) return false; if (!upperName.equals(other.upperName)) return false; return true; } } private static void addBuiltInFunction(Class<? extends FunctionExpression> f) throws Exception { BuiltInFunction d = f.getAnnotation(BuiltInFunction.class); if (d == null) { return; } int nArgs = d.args().length; BuiltInFunctionInfo value = new BuiltInFunctionInfo(f, d); do { // Add function to function map, throwing if conflicts found // Add entry for each possible version of function based on arguments that are not required to be present (i.e. arg with default value) BuiltInFunctionKey key = new BuiltInFunctionKey(value.getName(), nArgs); if (BUILT_IN_FUNCTION_MAP.put(key, value) != null) { throw new IllegalStateException("Multiple " + value.getName() + " functions with " + nArgs + " arguments"); } } while (--nArgs >= 0 && d.args()[nArgs].defaultValue().length() > 0); // Look for default values that aren't at the end and throw while (--nArgs >= 0) { if (d.args()[nArgs].defaultValue().length() > 0) { throw new IllegalStateException("Function " + value.getName() + " has non trailing default value of '" + d.args()[nArgs].defaultValue() + "'. Only trailing arguments may have default values"); } } } /** * Reflect this class and populate static structures from it. * Don't initialize in static block because we have a circular dependency */ private synchronized static void initBuiltInFunctionMap() { if (!BUILT_IN_FUNCTION_MAP.isEmpty()) { return; } Class<? extends FunctionExpression> f = null; try { // Reflection based parsing which yields direct explicit function evaluation at runtime for (int i = 0; i < CLIENT_SIDE_BUILT_IN_FUNCTIONS.size(); i++) { f = CLIENT_SIDE_BUILT_IN_FUNCTIONS.get(i); addBuiltInFunction(f); } for (ExpressionType et : ExpressionType.values()) { Class<? extends Expression> ec = et.getExpressionClass(); if (FunctionExpression.class.isAssignableFrom(ec)) { @SuppressWarnings("unchecked") Class<? extends FunctionExpression> c = (Class<? extends FunctionExpression>)ec; addBuiltInFunction(f = c); } } } catch (Exception e) { throw new RuntimeException("Failed initialization of built-in functions at class '" + f + "'", e); } } private static BuiltInFunctionInfo getInfo(String name, List<ParseNode> children) { return get(SchemaUtil.normalizeIdentifier(name), children); } public static BuiltInFunctionInfo get(String normalizedName, List<ParseNode> children) { initBuiltInFunctionMap(); BuiltInFunctionInfo info = BUILT_IN_FUNCTION_MAP.get(new BuiltInFunctionKey(normalizedName,children.size())); if (info == null) { throw new UnknownFunctionException(normalizedName); } return info; } public ParseNodeFactory() { } private static AtomicInteger tempAliasCounter = new AtomicInteger(0); public static String createTempAlias() { return "$" + tempAliasCounter.incrementAndGet(); } public ExplainStatement explain(BindableStatement statement) { return new ExplainStatement(statement); } public AliasedNode aliasedNode(String alias, ParseNode expression) { return new AliasedNode(alias, expression); } public AddParseNode add(List<ParseNode> children) { return new AddParseNode(children); } public SubtractParseNode subtract(List<ParseNode> children) { return new SubtractParseNode(children); } public MultiplyParseNode multiply(List<ParseNode> children) { return new MultiplyParseNode(children); } public ModulusParseNode modulus(List<ParseNode> children) { return new ModulusParseNode(children); } public AndParseNode and(List<ParseNode> children) { return new AndParseNode(children); } public FamilyWildcardParseNode family(String familyName){ return new FamilyWildcardParseNode(familyName, false); } public TableWildcardParseNode tableWildcard(TableName tableName) { return new TableWildcardParseNode(tableName, false); } public WildcardParseNode wildcard() { return WildcardParseNode.INSTANCE; } public BetweenParseNode between(ParseNode l, ParseNode r1, ParseNode r2, boolean negate) { return new BetweenParseNode(l, r1, r2, negate); } public BindParseNode bind(String bind) { return new BindParseNode(bind); } public StringConcatParseNode concat(List<ParseNode> children) { return new StringConcatParseNode(children); } public ColumnParseNode column(TableName tableName, String columnName, String alias) { return new ColumnParseNode(tableName, columnName, alias); } public ColumnName columnName(String columnName) { return new ColumnName(columnName); } public ColumnName columnName(String familyName, String columnName) { return new ColumnName(familyName, columnName); } public PropertyName propertyName(String propertyName) { return new PropertyName(propertyName); } public PropertyName propertyName(String familyName, String propertyName) { return new PropertyName(familyName, propertyName); } public ColumnDef columnDef(ColumnName columnDefName, String sqlTypeName, boolean isNull, Integer maxLength, Integer scale, boolean isPK, SortOrder sortOrder, String expressionStr) { return new ColumnDef(columnDefName, sqlTypeName, isNull, maxLength, scale, isPK, sortOrder, expressionStr); } public ColumnDef columnDef(ColumnName columnDefName, String sqlTypeName, boolean isArray, Integer arrSize, Boolean isNull, Integer maxLength, Integer scale, boolean isPK, SortOrder sortOrder) { return new ColumnDef(columnDefName, sqlTypeName, isArray, arrSize, isNull, maxLength, scale, isPK, sortOrder, null); } public PrimaryKeyConstraint primaryKey(String name, List<Pair<ColumnName, SortOrder>> columnNameAndSortOrder) { return new PrimaryKeyConstraint(name, columnNameAndSortOrder); } public IndexKeyConstraint indexKey( List<Pair<ParseNode, SortOrder>> parseNodeAndSortOrder) { return new IndexKeyConstraint(parseNodeAndSortOrder); } public CreateTableStatement createTable(TableName tableName, ListMultimap<String,Pair<String,Object>> props, List<ColumnDef> columns, PrimaryKeyConstraint pkConstraint, List<ParseNode> splits, PTableType tableType, boolean ifNotExists, TableName baseTableName, ParseNode tableTypeIdNode, int bindCount) { return new CreateTableStatement(tableName, props, columns, pkConstraint, splits, tableType, ifNotExists, baseTableName, tableTypeIdNode, bindCount); } public CreateIndexStatement createIndex(NamedNode indexName, NamedTableNode dataTable, IndexKeyConstraint ikConstraint, List<ColumnName> includeColumns, List<ParseNode> splits, ListMultimap<String,Pair<String,Object>> props, boolean ifNotExists, IndexType indexType, int bindCount) { return new CreateIndexStatement(indexName, dataTable, ikConstraint, includeColumns, splits, props, ifNotExists, indexType, bindCount); } public CreateSequenceStatement createSequence(TableName tableName, ParseNode startsWith, ParseNode incrementBy, ParseNode cacheSize, ParseNode minValue, ParseNode maxValue, boolean cycle, boolean ifNotExits, int bindCount) { return new CreateSequenceStatement(tableName, startsWith, incrementBy, cacheSize, minValue, maxValue, cycle, ifNotExits, bindCount); } public DropSequenceStatement dropSequence(TableName tableName, boolean ifExits, int bindCount){ return new DropSequenceStatement(tableName, ifExits, bindCount); } public SequenceValueParseNode currentValueFor(TableName tableName) { return new SequenceValueParseNode(tableName, SequenceValueParseNode.Op.CURRENT_VALUE); } public SequenceValueParseNode nextValueFor(TableName tableName) { return new SequenceValueParseNode(tableName, SequenceValueParseNode.Op.NEXT_VALUE); } public AddColumnStatement addColumn(NamedTableNode table, PTableType tableType, List<ColumnDef> columnDefs, boolean ifNotExists, ListMultimap<String,Pair<String,Object>> props) { return new AddColumnStatement(table, tableType, columnDefs, ifNotExists, props); } public DropColumnStatement dropColumn(NamedTableNode table, PTableType tableType, List<ColumnName> columnNodes, boolean ifExists) { return new DropColumnStatement(table, tableType, columnNodes, ifExists); } public DropTableStatement dropTable(TableName tableName, PTableType tableType, boolean ifExists, boolean cascade) { return new DropTableStatement(tableName, tableType, ifExists, cascade); } public DropIndexStatement dropIndex(NamedNode indexName, TableName tableName, boolean ifExists) { return new DropIndexStatement(indexName, tableName, ifExists); } public AlterIndexStatement alterIndex(NamedTableNode indexTableNode, String dataTableName, boolean ifExists, PIndexState state) { return new AlterIndexStatement(indexTableNode, dataTableName, ifExists, state); } public TableName table(String schemaName, String tableName) { return TableName.createNormalized(schemaName,tableName); } public NamedNode indexName(String name) { return new NamedNode(name); } public NamedTableNode namedTable(String alias, TableName name) { return new NamedTableNode(alias, name); } public NamedTableNode namedTable(String alias, TableName name ,List<ColumnDef> dyn_columns) { return new NamedTableNode(alias, name,dyn_columns); } public BindTableNode bindTable(String alias, TableName name) { return new BindTableNode(alias, name); } public CaseParseNode caseWhen(List<ParseNode> children) { return new CaseParseNode(children); } public DivideParseNode divide(List<ParseNode> children) { return new DivideParseNode(children); } public UpdateStatisticsStatement updateStatistics(NamedTableNode table, StatisticsCollectionScope scope) { return new UpdateStatisticsStatement(table, scope); } public FunctionParseNode functionDistinct(String name, List<ParseNode> args) { if (CountAggregateFunction.NAME.equals(SchemaUtil.normalizeIdentifier(name))) { BuiltInFunctionInfo info = getInfo( SchemaUtil.normalizeIdentifier(DistinctCountAggregateFunction.NAME), args); return new DistinctCountParseNode(DistinctCountAggregateFunction.NAME, args, info); } else { throw new UnsupportedOperationException("DISTINCT not supported with " + name); } } public FunctionParseNode arrayElemRef(List<ParseNode> args) { return function(ARRAY_ELEM, args); } public FunctionParseNode function(String name, List<ParseNode> args) { BuiltInFunctionInfo info = getInfo(name, args); Constructor<? extends FunctionParseNode> ctor = info.getNodeCtor(); if (ctor == null) { return info.isAggregate() ? new AggregateFunctionParseNode(name, args, info) : new FunctionParseNode(name, args, info); } else { try { return ctor.newInstance(name, args, info); } catch (Exception e) { throw new RuntimeException(e); } } } public FunctionParseNode function(String name, List<ParseNode> valueNodes, List<ParseNode> columnNodes, boolean isAscending) { List<ParseNode> args = Lists.newArrayListWithExpectedSize(columnNodes.size() + valueNodes.size() + 1); args.addAll(columnNodes); args.add(new LiteralParseNode(Boolean.valueOf(isAscending))); args.addAll(valueNodes); BuiltInFunctionInfo info = getInfo(name, args); Constructor<? extends FunctionParseNode> ctor = info.getNodeCtor(); if (ctor == null) { return new AggregateFunctionWithinGroupParseNode(name, args, info); } else { try { return ctor.newInstance(name, args, info); } catch (Exception e) { throw new RuntimeException(e); } } } public HintNode hint(String hint) { return new HintNode(hint); } public InListParseNode inList(List<ParseNode> children, boolean negate) { return new InListParseNode(children, negate); } public ExistsParseNode exists(ParseNode child, boolean negate) { return new ExistsParseNode(child, negate); } public InParseNode in(ParseNode l, ParseNode r, boolean negate, boolean isSubqueryDistinct) { return new InParseNode(l, r, negate, isSubqueryDistinct); } public IsNullParseNode isNull(ParseNode child, boolean negate) { return new IsNullParseNode(child, negate); } public JoinTableNode join(JoinType type, TableNode lhs, TableNode rhs, ParseNode on, boolean singleValueOnly) { return new JoinTableNode(type, lhs, rhs, on, singleValueOnly); } public DerivedTableNode derivedTable (String alias, SelectStatement select) { return new DerivedTableNode(alias, select); } public LikeParseNode like(ParseNode lhs, ParseNode rhs, boolean negate, LikeType likeType) { return new LikeParseNode(lhs, rhs, negate, likeType); } public LiteralParseNode literal(Object value) { return new LiteralParseNode(value); } public CastParseNode cast(ParseNode expression, String dataType, Integer maxLength, Integer scale) { return new CastParseNode(expression, dataType, maxLength, scale, false); } public CastParseNode cast(ParseNode expression, PDataType dataType, Integer maxLength, Integer scale) { return new CastParseNode(expression, dataType, maxLength, scale, false); } public CastParseNode cast(ParseNode expression, PDataType dataType, Integer maxLength, Integer scale, boolean arr) { return new CastParseNode(expression, dataType, maxLength, scale, arr); } public CastParseNode cast(ParseNode expression, String dataType, Integer maxLength, Integer scale, boolean arr) { return new CastParseNode(expression, dataType, maxLength, scale, arr); } public ParseNode rowValueConstructor(List<ParseNode> l) { return new RowValueConstructorParseNode(l); } private void checkTypeMatch (PDataType expectedType, PDataType actualType) throws SQLException { if (!expectedType.isCoercibleTo(actualType)) { throw TypeMismatchException.newException(expectedType, actualType); } } public LiteralParseNode literal(Object value, PDataType expectedType) throws SQLException { PDataType actualType = PDataType.fromLiteral(value); if (actualType != null && actualType != expectedType) { checkTypeMatch(expectedType, actualType); value = expectedType.toObject(value, actualType); } return new LiteralParseNode(value); /* Object typedValue = expectedType.toObject(value.toString()); return new LiteralParseNode(typedValue); */ } public LiteralParseNode literal(String value, String sqlTypeName) throws SQLException { PDataType expectedType = sqlTypeName == null ? null : PDataType.fromSqlTypeName(SchemaUtil.normalizeIdentifier(sqlTypeName)); if (expectedType == null || !expectedType.isCoercibleTo(PTimestamp.INSTANCE)) { throw TypeMismatchException.newException(expectedType, PTimestamp.INSTANCE); } Object typedValue = expectedType.toObject(value); return new LiteralParseNode(typedValue); } public LiteralParseNode coerce(LiteralParseNode literalNode, PDataType expectedType) throws SQLException { PDataType actualType = literalNode.getType(); if (actualType != null) { Object before = literalNode.getValue(); checkTypeMatch(expectedType, actualType); Object after = expectedType.toObject(before, actualType); if (before != after) { literalNode = literal(after); } } return literalNode; } public ComparisonParseNode comparison(CompareOp op, ParseNode lhs, ParseNode rhs) { switch (op){ case LESS: return lt(lhs,rhs); case LESS_OR_EQUAL: return lte(lhs,rhs); case EQUAL: return equal(lhs,rhs); case NOT_EQUAL: return notEqual(lhs,rhs); case GREATER_OR_EQUAL: return gte(lhs,rhs); case GREATER: return gt(lhs,rhs); default: throw new IllegalArgumentException("Unexpcted CompareOp of " + op); } } public ArrayAnyComparisonNode arrayAny(ParseNode rhs, ComparisonParseNode compareNode) { return new ArrayAnyComparisonNode(rhs, compareNode); } public ArrayAllComparisonNode arrayAll(ParseNode rhs, ComparisonParseNode compareNode) { return new ArrayAllComparisonNode(rhs, compareNode); } public ArrayAnyComparisonNode wrapInAny(CompareOp op, ParseNode lhs, ParseNode rhs) { return new ArrayAnyComparisonNode(rhs, comparison(op, lhs, elementRef(Arrays.<ParseNode>asList(rhs, literal(1))))); } public ArrayAllComparisonNode wrapInAll(CompareOp op, ParseNode lhs, ParseNode rhs) { return new ArrayAllComparisonNode(rhs, comparison(op, lhs, elementRef(Arrays.<ParseNode>asList(rhs, literal(1))))); } public ArrayElemRefNode elementRef(List<ParseNode> parseNode) { return new ArrayElemRefNode(parseNode); } public GreaterThanParseNode gt(ParseNode lhs, ParseNode rhs) { return new GreaterThanParseNode(lhs, rhs); } public GreaterThanOrEqualParseNode gte(ParseNode lhs, ParseNode rhs) { return new GreaterThanOrEqualParseNode(lhs, rhs); } public LessThanParseNode lt(ParseNode lhs, ParseNode rhs) { return new LessThanParseNode(lhs, rhs); } public LessThanOrEqualParseNode lte(ParseNode lhs, ParseNode rhs) { return new LessThanOrEqualParseNode(lhs, rhs); } public EqualParseNode equal(ParseNode lhs, ParseNode rhs) { return new EqualParseNode(lhs, rhs); } public ArrayConstructorNode upsertStmtArrayNode(List<ParseNode> upsertStmtArray) { return new ArrayConstructorNode(upsertStmtArray); } public ParseNode negate(ParseNode child) { // Prevents reparsing of -1 from becoming 1*-1 and 1*1*-1 with each re-parsing if (LiteralParseNode.ONE.equals(child)) { return LiteralParseNode.MINUS_ONE; } return new MultiplyParseNode(Arrays.asList(child,LiteralParseNode.MINUS_ONE)); } public NotEqualParseNode notEqual(ParseNode lhs, ParseNode rhs) { return new NotEqualParseNode(lhs, rhs); } public ParseNode not(ParseNode child) { if (child instanceof ExistsParseNode) { return exists(child.getChildren().get(0), !((ExistsParseNode) child).isNegate()); } return new NotParseNode(child); } public OrParseNode or(List<ParseNode> children) { return new OrParseNode(children); } public OrderByNode orderBy(ParseNode expression, boolean nullsLast, boolean orderAscending) { return new OrderByNode(expression, nullsLast, orderAscending); } public SelectStatement select(TableNode from, HintNode hint, boolean isDistinct, List<AliasedNode> select, ParseNode where, List<ParseNode> groupBy, ParseNode having, List<OrderByNode> orderBy, LimitNode limit, int bindCount, boolean isAggregate, boolean hasSequence) { return new SelectStatement(from, hint, isDistinct, select, where, groupBy == null ? Collections.<ParseNode>emptyList() : groupBy, having, orderBy == null ? Collections.<OrderByNode>emptyList() : orderBy, limit, bindCount, isAggregate, hasSequence); } public UpsertStatement upsert(NamedTableNode table, HintNode hint, List<ColumnName> columns, List<ParseNode> values, SelectStatement select, int bindCount) { return new UpsertStatement(table, hint, columns, values, select, bindCount); } public DeleteStatement delete(NamedTableNode table, HintNode hint, ParseNode node, List<OrderByNode> orderBy, LimitNode limit, int bindCount) { return new DeleteStatement(table, hint, node, orderBy, limit, bindCount); } public SelectStatement select(SelectStatement statement, ParseNode where) { return select(statement.getFrom(), statement.getHint(), statement.isDistinct(), statement.getSelect(), where, statement.getGroupBy(), statement.getHaving(), statement.getOrderBy(), statement.getLimit(), statement.getBindCount(), statement.isAggregate(), statement.hasSequence()); } public SelectStatement select(SelectStatement statement, ParseNode where, ParseNode having) { return select(statement.getFrom(), statement.getHint(), statement.isDistinct(), statement.getSelect(), where, statement.getGroupBy(), having, statement.getOrderBy(), statement.getLimit(), statement.getBindCount(), statement.isAggregate(), statement.hasSequence()); } public SelectStatement select(SelectStatement statement, List<AliasedNode> select, ParseNode where, List<ParseNode> groupBy, ParseNode having, List<OrderByNode> orderBy) { return select(statement.getFrom(), statement.getHint(), statement.isDistinct(), select, where, groupBy, having, orderBy, statement.getLimit(), statement.getBindCount(), statement.isAggregate(), statement.hasSequence()); } public SelectStatement select(SelectStatement statement, TableNode table) { return select(table, statement.getHint(), statement.isDistinct(), statement.getSelect(), statement.getWhere(), statement.getGroupBy(), statement.getHaving(), statement.getOrderBy(), statement.getLimit(), statement.getBindCount(), statement.isAggregate(), statement.hasSequence()); } public SelectStatement select(SelectStatement statement, TableNode table, ParseNode where) { return select(table, statement.getHint(), statement.isDistinct(), statement.getSelect(), where, statement.getGroupBy(), statement.getHaving(), statement.getOrderBy(), statement.getLimit(), statement.getBindCount(), statement.isAggregate(), statement.hasSequence()); } public SelectStatement select(SelectStatement statement, boolean isDistinct, List<AliasedNode> select) { return select(statement.getFrom(), statement.getHint(), isDistinct, select, statement.getWhere(), statement.getGroupBy(), statement.getHaving(), statement.getOrderBy(), statement.getLimit(), statement.getBindCount(), statement.isAggregate(), statement.hasSequence()); } public SelectStatement select(SelectStatement statement, boolean isDistinct, List<AliasedNode> select, ParseNode where) { return select(statement.getFrom(), statement.getHint(), isDistinct, select, where, statement.getGroupBy(), statement.getHaving(), statement.getOrderBy(), statement.getLimit(), statement.getBindCount(), statement.isAggregate(), statement.hasSequence()); } public SelectStatement select(SelectStatement statement, boolean isDistinct, List<AliasedNode> select, ParseNode where, List<ParseNode> groupBy, boolean isAggregate) { return select(statement.getFrom(), statement.getHint(), isDistinct, select, where, groupBy, statement.getHaving(), statement.getOrderBy(), statement.getLimit(), statement.getBindCount(), isAggregate, statement.hasSequence()); } public SelectStatement select(SelectStatement statement, List<OrderByNode> orderBy) { return select(statement.getFrom(), statement.getHint(), statement.isDistinct(), statement.getSelect(), statement.getWhere(), statement.getGroupBy(), statement.getHaving(), orderBy, statement.getLimit(), statement.getBindCount(), statement.isAggregate(), statement.hasSequence()); } public SelectStatement select(SelectStatement statement, HintNode hint) { return hint == null || hint.isEmpty() ? statement : select(statement.getFrom(), hint, statement.isDistinct(), statement.getSelect(), statement.getWhere(), statement.getGroupBy(), statement.getHaving(), statement.getOrderBy(), statement.getLimit(), statement.getBindCount(), statement.isAggregate(), statement.hasSequence()); } public SelectStatement select(SelectStatement statement, HintNode hint, ParseNode where) { return select(statement.getFrom(), hint, statement.isDistinct(), statement.getSelect(), where, statement.getGroupBy(), statement.getHaving(), statement.getOrderBy(), statement.getLimit(), statement.getBindCount(), statement.isAggregate(), statement.hasSequence()); } public SelectStatement select(SelectStatement statement, LimitNode limit) { return select(statement.getFrom(), statement.getHint(), statement.isDistinct(), statement.getSelect(), statement.getWhere(), statement.getGroupBy(), statement.getHaving(), statement.getOrderBy(), limit, statement.getBindCount(), statement.isAggregate(), statement.hasSequence()); } public SubqueryParseNode subquery(SelectStatement select, boolean expectSingleRow) { return new SubqueryParseNode(select, expectSingleRow); } public LimitNode limit(BindParseNode b) { return new LimitNode(b); } public LimitNode limit(LiteralParseNode l) { return new LimitNode(l); } }
apache-2.0
IHTSDO/snow-owl
core/com.b2international.snowowl.datastore/src/com/b2international/snowowl/datastore/cdo/ICDOManagedItem.java
2782
/* * Copyright 2011-2015 B2i Healthcare Pte Ltd, http://b2i.sg * * 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.b2international.snowowl.datastore.cdo; import javax.annotation.Nullable; import org.eclipse.emf.cdo.common.model.CDOPackageRegistry; import org.eclipse.net4j.util.lifecycle.ILifecycle; /** * Representation of a managed CDO specific item. * @see ILifecycle * @see ICDOContainer */ public interface ICDOManagedItem<T extends ICDOManagedItem<T>> extends ILifecycle { /** * Sets the container for the current {@link ICDOManagedItem managed item.} Operation is not bidirectional. * @param container the appropriate container of the current managed item. */ void setContainer(final ICDOContainer<T> container); /** * Returns with the unique namespace ID of the current managed item. * @return the namespace ID. */ byte getNamespaceId(); /** * Returns with the unique ID of the current managed item. * @return the unique ID of the item. */ String getUuid(); /** * Returns with the human readable name of the associated repository for the current item. * @return the name of the associated repository. */ String getRepositoryName(); /** * Returns with the Snow Owl specific unique ID of the associated tooling support. * @return the unique application specific ID of the associated component. */ String getSnowOwlTerminologyComponentId(); /** * Returns with the application specific human readable name of component identified * by the {@link #getSnowOwlTerminologyComponentId() Snow Owl terminology component ID}. * @return the human readable name of the associated application specific component. */ String getSnowOwlTerminologyComponentName(); /** * Returns with the {@link CDOPackageRegistry package registry} for the underlying managed item. * @return the package registry for the managed item. */ CDOPackageRegistry getPackageRegistry(); /**Returns with {@code true} if the item is a meta managed item. Otherwise {@code false}.*/ boolean isMeta(); /**Returns with the UUID of a managed item where the current item depends on. *<br>May return with {@code null} if the managed item does not depend on any others.*/ @Nullable String getMasterUuid(); }
apache-2.0
aragozin/jvm-tools
sjk-stacktrace/src/test/java/org/gridkit/jvmtool/stacktrace/ThreadSamplerCheck.java
1849
package org.gridkit.jvmtool.stacktrace; import java.io.IOException; import java.lang.management.ManagementFactory; import org.junit.Test; public class ThreadSamplerCheck { @Test public void checkNoTraceNoPriming() throws IOException { ThreadDumpSampler sampler = new ThreadDumpSampler(); sampler.enableThreadStackTrace(false); sampler.connect(ManagementFactory.getThreadMXBean()); loop(sampler); } @Test public void checkTraceNoPriming() throws IOException { ThreadDumpSampler sampler = new ThreadDumpSampler(); sampler.enableThreadStackTrace(true); sampler.connect(ManagementFactory.getThreadMXBean()); loop(sampler); } @Test public void checkNoTracePriming() throws IOException { ThreadDumpSampler sampler = new ThreadDumpSampler(); sampler.enableThreadStackTrace(false); sampler.connect(ManagementFactory.getThreadMXBean()); sampler.prime(); loop(sampler); } @Test public void checkTracePriming() throws IOException { ThreadDumpSampler sampler = new ThreadDumpSampler(); sampler.enableThreadStackTrace(true); sampler.connect(ManagementFactory.getThreadMXBean()); sampler.prime(); loop(sampler); } protected void loop(ThreadDumpSampler sampler) throws IOException { while(true) { sampler.collect(new StackTraceWriter() { @Override public void write(ThreadSnapshot snap) throws IOException { System.out.println(snap.threadName() + " " + ((snap.stackTrace() == null) ? "No trcae" : (snap.stackTrace().depth() + " frames"))); } @Override public void close() { } }); } } }
apache-2.0
java110/MicroCommunity
service-common/src/main/java/com/java110/common/bmo/transactionLogMessage/ISaveTransactionLogMessageBMO.java
424
package com.java110.common.bmo.transactionLogMessage; import com.java110.po.transactionLog.TransactionLogMessagePo; import org.springframework.http.ResponseEntity; public interface ISaveTransactionLogMessageBMO { /** * 添加交互日志 * add by wuxw * * @param transactionLogMessagePo * @return */ ResponseEntity<String> save(TransactionLogMessagePo transactionLogMessagePo); }
apache-2.0
SrinivasanTarget/java-client
src/test/java/io/appium/java_client/ios/BaseIOSTest.java
2135
/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * See the NOTICE file distributed with this work for additional * information regarding copyright ownership. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.appium.java_client.ios; import io.appium.java_client.service.local.AppiumDriverLocalService; import io.appium.java_client.service.local.AppiumServiceBuilder; import org.junit.AfterClass; import java.net.InetAddress; import java.net.UnknownHostException; public class BaseIOSTest { protected static AppiumDriverLocalService service; protected static IOSDriver<IOSElement> driver; protected static final int PORT = 4723; public static final String DEVICE_NAME = System.getenv("IOS_DEVICE_NAME") != null ? System.getenv("IOS_DEVICE_NAME") : "iPhone X"; public static final String PLATFORM_VERSION = System.getenv("IOS_PLATFORM_VERSION") != null ? System.getenv("IOS_PLATFORM_VERSION") : "11.4"; /** * Starts a local server. * * @return ip of a local host * @throws UnknownHostException when it is impossible to get ip address of a local host */ public static String startAppiumServer() throws UnknownHostException { service = new AppiumServiceBuilder() .usingPort(PORT).build(); service.start(); InetAddress inetAddress = InetAddress.getLocalHost(); return inetAddress.getHostAddress(); } /** * finishing. */ @AfterClass public static void afterClass() { if (driver != null) { driver.quit(); } if (service != null) { service.stop(); } } }
apache-2.0
LightSun/data-mediator
data-mediator-compiler/src/main/java/com/heaven7/java/data/mediator/compiler/insert/TypeAdapterInsertDelegate.java
1918
package com.heaven7.java.data.mediator.compiler.insert; import com.heaven7.java.data.mediator.compiler.GlobalConfig; import com.heaven7.java.data.mediator.compiler.util.Util; import com.squareup.javapoet.AnnotationSpec; import com.squareup.javapoet.ClassName; import com.squareup.javapoet.CodeBlock; import com.squareup.javapoet.TypeSpec; import static com.heaven7.java.data.mediator.compiler.DataMediatorConstants.*; /*public*/ class TypeAdapterInsertDelegate extends TypeInsertDelegate { @Override public boolean addStaticCode(CodeBlock.Builder staticBuilder, Object param) { //disable or not generate json adapter. if(!getClassInfo().isGenerateJsonAdapter() || !GlobalConfig.getInstance().isJsonAdapterEnabled()){ return false; } ClassName cn_type_handler = ClassName.get(PKG_GSON_SUPPORT, SN_TYPE_HANDLER); ClassName cn_impl = ClassName.get(getClassInfo().getPackageName(), getClassInfo().getCurrentClassname()); ClassName cn_type_adapter = ClassName.get(getClassInfo().getPackageName(), Util.getTypeAdapterName(getClassInfo().getDirectParentInterfaceName())); staticBuilder.add("$T.registerTypeAdapter($T.class, new $T());\n", cn_type_handler, cn_impl, cn_type_adapter); return true; } @Override public void addClassAnnotation(TypeSpec.Builder typeBuilder) { if(!getClassInfo().isGenerateJsonAdapter() || !GlobalConfig.getInstance().isJsonAdapterEnabled()){ return ; } ClassName cn_type_adapter = ClassName.get(getClassInfo().getPackageName(), Util.getTypeAdapterName(getClassInfo().getDirectParentInterfaceName())); typeBuilder.addAnnotation(AnnotationSpec.builder(ClassName.get(PKG_GSON_ANNO, SN_GSON_JSON_ADAPTER)) .addMember("value", "$T.class", cn_type_adapter) .build()); } }
apache-2.0
Sellegit/j2objc
runtime/src/main/java/apple/coregraphics/CGPDFContentStream.java
530
package apple.coregraphics; import java.io.*; import java.nio.*; import java.util.*; import com.google.j2objc.annotations.*; import com.google.j2objc.runtime.*; import com.google.j2objc.runtime.block.*; import apple.audiotoolbox.*; import apple.corefoundation.*; import apple.coregraphics.*; import apple.coreservices.*; import apple.foundation.*; import apple.uikit.*; /*<javadoc>*/ /*</javadoc>*/ public class CGPDFContentStream extends Object { protected CGPDFContentStream() {} }
apache-2.0
dump247/aws-sdk-java
aws-java-sdk-opsworks/src/main/java/com/amazonaws/services/opsworks/model/Stack.java
55664
/* * Copyright 2010-2016 Amazon.com, Inc. or its affiliates. All Rights * Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package com.amazonaws.services.opsworks.model; import java.io.Serializable; /** * <p> * Describes a stack. * </p> */ public class Stack implements Serializable, Cloneable { /** * <p> * The stack ID. * </p> */ private String stackId; /** * <p> * The stack name. * </p> */ private String name; /** * <p> * The stack's ARN. * </p> */ private String arn; /** * <p> * The stack AWS region, such as "us-east-1". For more information about AWS * regions, see <a * href="http://docs.aws.amazon.com/general/latest/gr/rande.html">Regions * and Endpoints</a>. * </p> */ private String region; /** * <p> * The VPC ID; applicable only if the stack is running in a VPC. * </p> */ private String vpcId; /** * <p> * The stack's attributes. * </p> */ private com.amazonaws.internal.SdkInternalMap<String, String> attributes; /** * <p> * The stack AWS Identity and Access Management (IAM) role. * </p> */ private String serviceRoleArn; /** * <p> * The ARN of an IAM profile that is the default profile for all of the * stack's EC2 instances. For more information about IAM ARNs, see <a href= * "http://docs.aws.amazon.com/IAM/latest/UserGuide/Using_Identifiers.html" * >Using Identifiers</a>. * </p> */ private String defaultInstanceProfileArn; /** * <p> * The stack's default operating system. * </p> */ private String defaultOs; /** * <p> * The stack host name theme, with spaces replaced by underscores. * </p> */ private String hostnameTheme; /** * <p> * The stack's default Availability Zone. For more information, see <a * href="http://docs.aws.amazon.com/general/latest/gr/rande.html">Regions * and Endpoints</a>. * </p> */ private String defaultAvailabilityZone; /** * <p> * The default subnet ID; applicable only if the stack is running in a VPC. * </p> */ private String defaultSubnetId; /** * <p> * A JSON object that contains user-defined attributes to be added to the * stack configuration and deployment attributes. You can use custom JSON to * override the corresponding default stack configuration attribute values * or to pass data to recipes. The string should be in the following format * and must escape characters such as '"': * </p> * <p> * <code>"{\"key1\": \"value1\", \"key2\": \"value2\",...}"</code> * </p> * <p> * For more information on custom JSON, see <a href= * "http://docs.aws.amazon.com/opsworks/latest/userguide/workingstacks-json.html" * >Use Custom JSON to Modify the Stack Configuration Attributes</a>. * </p> */ private String customJson; /** * <p> * The configuration manager. * </p> */ private StackConfigurationManager configurationManager; /** * <p> * A <code>ChefConfiguration</code> object that specifies whether to enable * Berkshelf and the Berkshelf version. For more information, see <a href= * "http://docs.aws.amazon.com/opsworks/latest/userguide/workingstacks-creating.html" * >Create a New Stack</a>. * </p> */ private ChefConfiguration chefConfiguration; /** * <p> * Whether the stack uses custom cookbooks. * </p> */ private Boolean useCustomCookbooks; /** * <p> * Whether the stack automatically associates the AWS OpsWorks built-in * security groups with the stack's layers. * </p> */ private Boolean useOpsworksSecurityGroups; private Source customCookbooksSource; /** * <p> * A default Amazon EC2 key pair for the stack's instances. You can override * this value when you create or update an instance. * </p> */ private String defaultSshKeyName; /** * <p> * The date when the stack was created. * </p> */ private String createdAt; /** * <p> * The default root device type. This value is used by default for all * instances in the stack, but you can override it when you create an * instance. For more information, see <a href= * "http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ComponentsAMIs.html#storage-for-the-root-device" * >Storage for the Root Device</a>. * </p> */ private String defaultRootDeviceType; /** * <p> * The agent version. This parameter is set to <code>LATEST</code> for * auto-update. or a version number for a fixed agent version. * </p> */ private String agentVersion; /** * <p> * The stack ID. * </p> * * @param stackId * The stack ID. */ public void setStackId(String stackId) { this.stackId = stackId; } /** * <p> * The stack ID. * </p> * * @return The stack ID. */ public String getStackId() { return this.stackId; } /** * <p> * The stack ID. * </p> * * @param stackId * The stack ID. * @return Returns a reference to this object so that method calls can be * chained together. */ public Stack withStackId(String stackId) { setStackId(stackId); return this; } /** * <p> * The stack name. * </p> * * @param name * The stack name. */ public void setName(String name) { this.name = name; } /** * <p> * The stack name. * </p> * * @return The stack name. */ public String getName() { return this.name; } /** * <p> * The stack name. * </p> * * @param name * The stack name. * @return Returns a reference to this object so that method calls can be * chained together. */ public Stack withName(String name) { setName(name); return this; } /** * <p> * The stack's ARN. * </p> * * @param arn * The stack's ARN. */ public void setArn(String arn) { this.arn = arn; } /** * <p> * The stack's ARN. * </p> * * @return The stack's ARN. */ public String getArn() { return this.arn; } /** * <p> * The stack's ARN. * </p> * * @param arn * The stack's ARN. * @return Returns a reference to this object so that method calls can be * chained together. */ public Stack withArn(String arn) { setArn(arn); return this; } /** * <p> * The stack AWS region, such as "us-east-1". For more information about AWS * regions, see <a * href="http://docs.aws.amazon.com/general/latest/gr/rande.html">Regions * and Endpoints</a>. * </p> * * @param region * The stack AWS region, such as "us-east-1". For more information * about AWS regions, see <a * href="http://docs.aws.amazon.com/general/latest/gr/rande.html" * >Regions and Endpoints</a>. */ public void setRegion(String region) { this.region = region; } /** * <p> * The stack AWS region, such as "us-east-1". For more information about AWS * regions, see <a * href="http://docs.aws.amazon.com/general/latest/gr/rande.html">Regions * and Endpoints</a>. * </p> * * @return The stack AWS region, such as "us-east-1". For more information * about AWS regions, see <a * href="http://docs.aws.amazon.com/general/latest/gr/rande.html" * >Regions and Endpoints</a>. */ public String getRegion() { return this.region; } /** * <p> * The stack AWS region, such as "us-east-1". For more information about AWS * regions, see <a * href="http://docs.aws.amazon.com/general/latest/gr/rande.html">Regions * and Endpoints</a>. * </p> * * @param region * The stack AWS region, such as "us-east-1". For more information * about AWS regions, see <a * href="http://docs.aws.amazon.com/general/latest/gr/rande.html" * >Regions and Endpoints</a>. * @return Returns a reference to this object so that method calls can be * chained together. */ public Stack withRegion(String region) { setRegion(region); return this; } /** * <p> * The VPC ID; applicable only if the stack is running in a VPC. * </p> * * @param vpcId * The VPC ID; applicable only if the stack is running in a VPC. */ public void setVpcId(String vpcId) { this.vpcId = vpcId; } /** * <p> * The VPC ID; applicable only if the stack is running in a VPC. * </p> * * @return The VPC ID; applicable only if the stack is running in a VPC. */ public String getVpcId() { return this.vpcId; } /** * <p> * The VPC ID; applicable only if the stack is running in a VPC. * </p> * * @param vpcId * The VPC ID; applicable only if the stack is running in a VPC. * @return Returns a reference to this object so that method calls can be * chained together. */ public Stack withVpcId(String vpcId) { setVpcId(vpcId); return this; } /** * <p> * The stack's attributes. * </p> * * @return The stack's attributes. */ public java.util.Map<String, String> getAttributes() { if (attributes == null) { attributes = new com.amazonaws.internal.SdkInternalMap<String, String>(); } return attributes; } /** * <p> * The stack's attributes. * </p> * * @param attributes * The stack's attributes. */ public void setAttributes(java.util.Map<String, String> attributes) { this.attributes = attributes == null ? null : new com.amazonaws.internal.SdkInternalMap<String, String>( attributes); } /** * <p> * The stack's attributes. * </p> * * @param attributes * The stack's attributes. * @return Returns a reference to this object so that method calls can be * chained together. */ public Stack withAttributes(java.util.Map<String, String> attributes) { setAttributes(attributes); return this; } public Stack addAttributesEntry(String key, String value) { if (null == this.attributes) { this.attributes = new com.amazonaws.internal.SdkInternalMap<String, String>(); } if (this.attributes.containsKey(key)) throw new IllegalArgumentException("Duplicated keys (" + key.toString() + ") are provided."); this.attributes.put(key, value); return this; } /** * Removes all the entries added into Attributes. &lt;p> Returns a reference * to this object so that method calls can be chained together. */ public Stack clearAttributesEntries() { this.attributes = null; return this; } /** * <p> * The stack AWS Identity and Access Management (IAM) role. * </p> * * @param serviceRoleArn * The stack AWS Identity and Access Management (IAM) role. */ public void setServiceRoleArn(String serviceRoleArn) { this.serviceRoleArn = serviceRoleArn; } /** * <p> * The stack AWS Identity and Access Management (IAM) role. * </p> * * @return The stack AWS Identity and Access Management (IAM) role. */ public String getServiceRoleArn() { return this.serviceRoleArn; } /** * <p> * The stack AWS Identity and Access Management (IAM) role. * </p> * * @param serviceRoleArn * The stack AWS Identity and Access Management (IAM) role. * @return Returns a reference to this object so that method calls can be * chained together. */ public Stack withServiceRoleArn(String serviceRoleArn) { setServiceRoleArn(serviceRoleArn); return this; } /** * <p> * The ARN of an IAM profile that is the default profile for all of the * stack's EC2 instances. For more information about IAM ARNs, see <a href= * "http://docs.aws.amazon.com/IAM/latest/UserGuide/Using_Identifiers.html" * >Using Identifiers</a>. * </p> * * @param defaultInstanceProfileArn * The ARN of an IAM profile that is the default profile for all of * the stack's EC2 instances. For more information about IAM ARNs, * see <a href= * "http://docs.aws.amazon.com/IAM/latest/UserGuide/Using_Identifiers.html" * >Using Identifiers</a>. */ public void setDefaultInstanceProfileArn(String defaultInstanceProfileArn) { this.defaultInstanceProfileArn = defaultInstanceProfileArn; } /** * <p> * The ARN of an IAM profile that is the default profile for all of the * stack's EC2 instances. For more information about IAM ARNs, see <a href= * "http://docs.aws.amazon.com/IAM/latest/UserGuide/Using_Identifiers.html" * >Using Identifiers</a>. * </p> * * @return The ARN of an IAM profile that is the default profile for all of * the stack's EC2 instances. For more information about IAM ARNs, * see <a href= * "http://docs.aws.amazon.com/IAM/latest/UserGuide/Using_Identifiers.html" * >Using Identifiers</a>. */ public String getDefaultInstanceProfileArn() { return this.defaultInstanceProfileArn; } /** * <p> * The ARN of an IAM profile that is the default profile for all of the * stack's EC2 instances. For more information about IAM ARNs, see <a href= * "http://docs.aws.amazon.com/IAM/latest/UserGuide/Using_Identifiers.html" * >Using Identifiers</a>. * </p> * * @param defaultInstanceProfileArn * The ARN of an IAM profile that is the default profile for all of * the stack's EC2 instances. For more information about IAM ARNs, * see <a href= * "http://docs.aws.amazon.com/IAM/latest/UserGuide/Using_Identifiers.html" * >Using Identifiers</a>. * @return Returns a reference to this object so that method calls can be * chained together. */ public Stack withDefaultInstanceProfileArn(String defaultInstanceProfileArn) { setDefaultInstanceProfileArn(defaultInstanceProfileArn); return this; } /** * <p> * The stack's default operating system. * </p> * * @param defaultOs * The stack's default operating system. */ public void setDefaultOs(String defaultOs) { this.defaultOs = defaultOs; } /** * <p> * The stack's default operating system. * </p> * * @return The stack's default operating system. */ public String getDefaultOs() { return this.defaultOs; } /** * <p> * The stack's default operating system. * </p> * * @param defaultOs * The stack's default operating system. * @return Returns a reference to this object so that method calls can be * chained together. */ public Stack withDefaultOs(String defaultOs) { setDefaultOs(defaultOs); return this; } /** * <p> * The stack host name theme, with spaces replaced by underscores. * </p> * * @param hostnameTheme * The stack host name theme, with spaces replaced by underscores. */ public void setHostnameTheme(String hostnameTheme) { this.hostnameTheme = hostnameTheme; } /** * <p> * The stack host name theme, with spaces replaced by underscores. * </p> * * @return The stack host name theme, with spaces replaced by underscores. */ public String getHostnameTheme() { return this.hostnameTheme; } /** * <p> * The stack host name theme, with spaces replaced by underscores. * </p> * * @param hostnameTheme * The stack host name theme, with spaces replaced by underscores. * @return Returns a reference to this object so that method calls can be * chained together. */ public Stack withHostnameTheme(String hostnameTheme) { setHostnameTheme(hostnameTheme); return this; } /** * <p> * The stack's default Availability Zone. For more information, see <a * href="http://docs.aws.amazon.com/general/latest/gr/rande.html">Regions * and Endpoints</a>. * </p> * * @param defaultAvailabilityZone * The stack's default Availability Zone. For more information, see * <a href="http://docs.aws.amazon.com/general/latest/gr/rande.html"> * Regions and Endpoints</a>. */ public void setDefaultAvailabilityZone(String defaultAvailabilityZone) { this.defaultAvailabilityZone = defaultAvailabilityZone; } /** * <p> * The stack's default Availability Zone. For more information, see <a * href="http://docs.aws.amazon.com/general/latest/gr/rande.html">Regions * and Endpoints</a>. * </p> * * @return The stack's default Availability Zone. For more information, see * <a * href="http://docs.aws.amazon.com/general/latest/gr/rande.html"> * Regions and Endpoints</a>. */ public String getDefaultAvailabilityZone() { return this.defaultAvailabilityZone; } /** * <p> * The stack's default Availability Zone. For more information, see <a * href="http://docs.aws.amazon.com/general/latest/gr/rande.html">Regions * and Endpoints</a>. * </p> * * @param defaultAvailabilityZone * The stack's default Availability Zone. For more information, see * <a href="http://docs.aws.amazon.com/general/latest/gr/rande.html"> * Regions and Endpoints</a>. * @return Returns a reference to this object so that method calls can be * chained together. */ public Stack withDefaultAvailabilityZone(String defaultAvailabilityZone) { setDefaultAvailabilityZone(defaultAvailabilityZone); return this; } /** * <p> * The default subnet ID; applicable only if the stack is running in a VPC. * </p> * * @param defaultSubnetId * The default subnet ID; applicable only if the stack is running in * a VPC. */ public void setDefaultSubnetId(String defaultSubnetId) { this.defaultSubnetId = defaultSubnetId; } /** * <p> * The default subnet ID; applicable only if the stack is running in a VPC. * </p> * * @return The default subnet ID; applicable only if the stack is running in * a VPC. */ public String getDefaultSubnetId() { return this.defaultSubnetId; } /** * <p> * The default subnet ID; applicable only if the stack is running in a VPC. * </p> * * @param defaultSubnetId * The default subnet ID; applicable only if the stack is running in * a VPC. * @return Returns a reference to this object so that method calls can be * chained together. */ public Stack withDefaultSubnetId(String defaultSubnetId) { setDefaultSubnetId(defaultSubnetId); return this; } /** * <p> * A JSON object that contains user-defined attributes to be added to the * stack configuration and deployment attributes. You can use custom JSON to * override the corresponding default stack configuration attribute values * or to pass data to recipes. The string should be in the following format * and must escape characters such as '"': * </p> * <p> * <code>"{\"key1\": \"value1\", \"key2\": \"value2\",...}"</code> * </p> * <p> * For more information on custom JSON, see <a href= * "http://docs.aws.amazon.com/opsworks/latest/userguide/workingstacks-json.html" * >Use Custom JSON to Modify the Stack Configuration Attributes</a>. * </p> * * @param customJson * A JSON object that contains user-defined attributes to be added to * the stack configuration and deployment attributes. You can use * custom JSON to override the corresponding default stack * configuration attribute values or to pass data to recipes. The * string should be in the following format and must escape * characters such as '"':</p> * <p> * <code>"{\"key1\": \"value1\", \"key2\": \"value2\",...}"</code> * </p> * <p> * For more information on custom JSON, see <a href= * "http://docs.aws.amazon.com/opsworks/latest/userguide/workingstacks-json.html" * >Use Custom JSON to Modify the Stack Configuration Attributes</a>. */ public void setCustomJson(String customJson) { this.customJson = customJson; } /** * <p> * A JSON object that contains user-defined attributes to be added to the * stack configuration and deployment attributes. You can use custom JSON to * override the corresponding default stack configuration attribute values * or to pass data to recipes. The string should be in the following format * and must escape characters such as '"': * </p> * <p> * <code>"{\"key1\": \"value1\", \"key2\": \"value2\",...}"</code> * </p> * <p> * For more information on custom JSON, see <a href= * "http://docs.aws.amazon.com/opsworks/latest/userguide/workingstacks-json.html" * >Use Custom JSON to Modify the Stack Configuration Attributes</a>. * </p> * * @return A JSON object that contains user-defined attributes to be added * to the stack configuration and deployment attributes. You can use * custom JSON to override the corresponding default stack * configuration attribute values or to pass data to recipes. The * string should be in the following format and must escape * characters such as '"':</p> * <p> * <code>"{\"key1\": \"value1\", \"key2\": \"value2\",...}"</code> * </p> * <p> * For more information on custom JSON, see <a href= * "http://docs.aws.amazon.com/opsworks/latest/userguide/workingstacks-json.html" * >Use Custom JSON to Modify the Stack Configuration * Attributes</a>. */ public String getCustomJson() { return this.customJson; } /** * <p> * A JSON object that contains user-defined attributes to be added to the * stack configuration and deployment attributes. You can use custom JSON to * override the corresponding default stack configuration attribute values * or to pass data to recipes. The string should be in the following format * and must escape characters such as '"': * </p> * <p> * <code>"{\"key1\": \"value1\", \"key2\": \"value2\",...}"</code> * </p> * <p> * For more information on custom JSON, see <a href= * "http://docs.aws.amazon.com/opsworks/latest/userguide/workingstacks-json.html" * >Use Custom JSON to Modify the Stack Configuration Attributes</a>. * </p> * * @param customJson * A JSON object that contains user-defined attributes to be added to * the stack configuration and deployment attributes. You can use * custom JSON to override the corresponding default stack * configuration attribute values or to pass data to recipes. The * string should be in the following format and must escape * characters such as '"':</p> * <p> * <code>"{\"key1\": \"value1\", \"key2\": \"value2\",...}"</code> * </p> * <p> * For more information on custom JSON, see <a href= * "http://docs.aws.amazon.com/opsworks/latest/userguide/workingstacks-json.html" * >Use Custom JSON to Modify the Stack Configuration Attributes</a>. * @return Returns a reference to this object so that method calls can be * chained together. */ public Stack withCustomJson(String customJson) { setCustomJson(customJson); return this; } /** * <p> * The configuration manager. * </p> * * @param configurationManager * The configuration manager. */ public void setConfigurationManager( StackConfigurationManager configurationManager) { this.configurationManager = configurationManager; } /** * <p> * The configuration manager. * </p> * * @return The configuration manager. */ public StackConfigurationManager getConfigurationManager() { return this.configurationManager; } /** * <p> * The configuration manager. * </p> * * @param configurationManager * The configuration manager. * @return Returns a reference to this object so that method calls can be * chained together. */ public Stack withConfigurationManager( StackConfigurationManager configurationManager) { setConfigurationManager(configurationManager); return this; } /** * <p> * A <code>ChefConfiguration</code> object that specifies whether to enable * Berkshelf and the Berkshelf version. For more information, see <a href= * "http://docs.aws.amazon.com/opsworks/latest/userguide/workingstacks-creating.html" * >Create a New Stack</a>. * </p> * * @param chefConfiguration * A <code>ChefConfiguration</code> object that specifies whether to * enable Berkshelf and the Berkshelf version. For more information, * see <a href= * "http://docs.aws.amazon.com/opsworks/latest/userguide/workingstacks-creating.html" * >Create a New Stack</a>. */ public void setChefConfiguration(ChefConfiguration chefConfiguration) { this.chefConfiguration = chefConfiguration; } /** * <p> * A <code>ChefConfiguration</code> object that specifies whether to enable * Berkshelf and the Berkshelf version. For more information, see <a href= * "http://docs.aws.amazon.com/opsworks/latest/userguide/workingstacks-creating.html" * >Create a New Stack</a>. * </p> * * @return A <code>ChefConfiguration</code> object that specifies whether to * enable Berkshelf and the Berkshelf version. For more information, * see <a href= * "http://docs.aws.amazon.com/opsworks/latest/userguide/workingstacks-creating.html" * >Create a New Stack</a>. */ public ChefConfiguration getChefConfiguration() { return this.chefConfiguration; } /** * <p> * A <code>ChefConfiguration</code> object that specifies whether to enable * Berkshelf and the Berkshelf version. For more information, see <a href= * "http://docs.aws.amazon.com/opsworks/latest/userguide/workingstacks-creating.html" * >Create a New Stack</a>. * </p> * * @param chefConfiguration * A <code>ChefConfiguration</code> object that specifies whether to * enable Berkshelf and the Berkshelf version. For more information, * see <a href= * "http://docs.aws.amazon.com/opsworks/latest/userguide/workingstacks-creating.html" * >Create a New Stack</a>. * @return Returns a reference to this object so that method calls can be * chained together. */ public Stack withChefConfiguration(ChefConfiguration chefConfiguration) { setChefConfiguration(chefConfiguration); return this; } /** * <p> * Whether the stack uses custom cookbooks. * </p> * * @param useCustomCookbooks * Whether the stack uses custom cookbooks. */ public void setUseCustomCookbooks(Boolean useCustomCookbooks) { this.useCustomCookbooks = useCustomCookbooks; } /** * <p> * Whether the stack uses custom cookbooks. * </p> * * @return Whether the stack uses custom cookbooks. */ public Boolean getUseCustomCookbooks() { return this.useCustomCookbooks; } /** * <p> * Whether the stack uses custom cookbooks. * </p> * * @param useCustomCookbooks * Whether the stack uses custom cookbooks. * @return Returns a reference to this object so that method calls can be * chained together. */ public Stack withUseCustomCookbooks(Boolean useCustomCookbooks) { setUseCustomCookbooks(useCustomCookbooks); return this; } /** * <p> * Whether the stack uses custom cookbooks. * </p> * * @return Whether the stack uses custom cookbooks. */ public Boolean isUseCustomCookbooks() { return this.useCustomCookbooks; } /** * <p> * Whether the stack automatically associates the AWS OpsWorks built-in * security groups with the stack's layers. * </p> * * @param useOpsworksSecurityGroups * Whether the stack automatically associates the AWS OpsWorks * built-in security groups with the stack's layers. */ public void setUseOpsworksSecurityGroups(Boolean useOpsworksSecurityGroups) { this.useOpsworksSecurityGroups = useOpsworksSecurityGroups; } /** * <p> * Whether the stack automatically associates the AWS OpsWorks built-in * security groups with the stack's layers. * </p> * * @return Whether the stack automatically associates the AWS OpsWorks * built-in security groups with the stack's layers. */ public Boolean getUseOpsworksSecurityGroups() { return this.useOpsworksSecurityGroups; } /** * <p> * Whether the stack automatically associates the AWS OpsWorks built-in * security groups with the stack's layers. * </p> * * @param useOpsworksSecurityGroups * Whether the stack automatically associates the AWS OpsWorks * built-in security groups with the stack's layers. * @return Returns a reference to this object so that method calls can be * chained together. */ public Stack withUseOpsworksSecurityGroups(Boolean useOpsworksSecurityGroups) { setUseOpsworksSecurityGroups(useOpsworksSecurityGroups); return this; } /** * <p> * Whether the stack automatically associates the AWS OpsWorks built-in * security groups with the stack's layers. * </p> * * @return Whether the stack automatically associates the AWS OpsWorks * built-in security groups with the stack's layers. */ public Boolean isUseOpsworksSecurityGroups() { return this.useOpsworksSecurityGroups; } /** * @param customCookbooksSource */ public void setCustomCookbooksSource(Source customCookbooksSource) { this.customCookbooksSource = customCookbooksSource; } /** * @return */ public Source getCustomCookbooksSource() { return this.customCookbooksSource; } /** * @param customCookbooksSource * @return Returns a reference to this object so that method calls can be * chained together. */ public Stack withCustomCookbooksSource(Source customCookbooksSource) { setCustomCookbooksSource(customCookbooksSource); return this; } /** * <p> * A default Amazon EC2 key pair for the stack's instances. You can override * this value when you create or update an instance. * </p> * * @param defaultSshKeyName * A default Amazon EC2 key pair for the stack's instances. You can * override this value when you create or update an instance. */ public void setDefaultSshKeyName(String defaultSshKeyName) { this.defaultSshKeyName = defaultSshKeyName; } /** * <p> * A default Amazon EC2 key pair for the stack's instances. You can override * this value when you create or update an instance. * </p> * * @return A default Amazon EC2 key pair for the stack's instances. You can * override this value when you create or update an instance. */ public String getDefaultSshKeyName() { return this.defaultSshKeyName; } /** * <p> * A default Amazon EC2 key pair for the stack's instances. You can override * this value when you create or update an instance. * </p> * * @param defaultSshKeyName * A default Amazon EC2 key pair for the stack's instances. You can * override this value when you create or update an instance. * @return Returns a reference to this object so that method calls can be * chained together. */ public Stack withDefaultSshKeyName(String defaultSshKeyName) { setDefaultSshKeyName(defaultSshKeyName); return this; } /** * <p> * The date when the stack was created. * </p> * * @param createdAt * The date when the stack was created. */ public void setCreatedAt(String createdAt) { this.createdAt = createdAt; } /** * <p> * The date when the stack was created. * </p> * * @return The date when the stack was created. */ public String getCreatedAt() { return this.createdAt; } /** * <p> * The date when the stack was created. * </p> * * @param createdAt * The date when the stack was created. * @return Returns a reference to this object so that method calls can be * chained together. */ public Stack withCreatedAt(String createdAt) { setCreatedAt(createdAt); return this; } /** * <p> * The default root device type. This value is used by default for all * instances in the stack, but you can override it when you create an * instance. For more information, see <a href= * "http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ComponentsAMIs.html#storage-for-the-root-device" * >Storage for the Root Device</a>. * </p> * * @param defaultRootDeviceType * The default root device type. This value is used by default for * all instances in the stack, but you can override it when you * create an instance. For more information, see <a href= * "http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ComponentsAMIs.html#storage-for-the-root-device" * >Storage for the Root Device</a>. * @see RootDeviceType */ public void setDefaultRootDeviceType(String defaultRootDeviceType) { this.defaultRootDeviceType = defaultRootDeviceType; } /** * <p> * The default root device type. This value is used by default for all * instances in the stack, but you can override it when you create an * instance. For more information, see <a href= * "http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ComponentsAMIs.html#storage-for-the-root-device" * >Storage for the Root Device</a>. * </p> * * @return The default root device type. This value is used by default for * all instances in the stack, but you can override it when you * create an instance. For more information, see <a href= * "http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ComponentsAMIs.html#storage-for-the-root-device" * >Storage for the Root Device</a>. * @see RootDeviceType */ public String getDefaultRootDeviceType() { return this.defaultRootDeviceType; } /** * <p> * The default root device type. This value is used by default for all * instances in the stack, but you can override it when you create an * instance. For more information, see <a href= * "http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ComponentsAMIs.html#storage-for-the-root-device" * >Storage for the Root Device</a>. * </p> * * @param defaultRootDeviceType * The default root device type. This value is used by default for * all instances in the stack, but you can override it when you * create an instance. For more information, see <a href= * "http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ComponentsAMIs.html#storage-for-the-root-device" * >Storage for the Root Device</a>. * @return Returns a reference to this object so that method calls can be * chained together. * @see RootDeviceType */ public Stack withDefaultRootDeviceType(String defaultRootDeviceType) { setDefaultRootDeviceType(defaultRootDeviceType); return this; } /** * <p> * The default root device type. This value is used by default for all * instances in the stack, but you can override it when you create an * instance. For more information, see <a href= * "http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ComponentsAMIs.html#storage-for-the-root-device" * >Storage for the Root Device</a>. * </p> * * @param defaultRootDeviceType * The default root device type. This value is used by default for * all instances in the stack, but you can override it when you * create an instance. For more information, see <a href= * "http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ComponentsAMIs.html#storage-for-the-root-device" * >Storage for the Root Device</a>. * @return Returns a reference to this object so that method calls can be * chained together. * @see RootDeviceType */ public void setDefaultRootDeviceType(RootDeviceType defaultRootDeviceType) { this.defaultRootDeviceType = defaultRootDeviceType.toString(); } /** * <p> * The default root device type. This value is used by default for all * instances in the stack, but you can override it when you create an * instance. For more information, see <a href= * "http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ComponentsAMIs.html#storage-for-the-root-device" * >Storage for the Root Device</a>. * </p> * * @param defaultRootDeviceType * The default root device type. This value is used by default for * all instances in the stack, but you can override it when you * create an instance. For more information, see <a href= * "http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ComponentsAMIs.html#storage-for-the-root-device" * >Storage for the Root Device</a>. * @return Returns a reference to this object so that method calls can be * chained together. * @see RootDeviceType */ public Stack withDefaultRootDeviceType(RootDeviceType defaultRootDeviceType) { setDefaultRootDeviceType(defaultRootDeviceType); return this; } /** * <p> * The agent version. This parameter is set to <code>LATEST</code> for * auto-update. or a version number for a fixed agent version. * </p> * * @param agentVersion * The agent version. This parameter is set to <code>LATEST</code> * for auto-update. or a version number for a fixed agent version. */ public void setAgentVersion(String agentVersion) { this.agentVersion = agentVersion; } /** * <p> * The agent version. This parameter is set to <code>LATEST</code> for * auto-update. or a version number for a fixed agent version. * </p> * * @return The agent version. This parameter is set to <code>LATEST</code> * for auto-update. or a version number for a fixed agent version. */ public String getAgentVersion() { return this.agentVersion; } /** * <p> * The agent version. This parameter is set to <code>LATEST</code> for * auto-update. or a version number for a fixed agent version. * </p> * * @param agentVersion * The agent version. This parameter is set to <code>LATEST</code> * for auto-update. or a version number for a fixed agent version. * @return Returns a reference to this object so that method calls can be * chained together. */ public Stack withAgentVersion(String agentVersion) { setAgentVersion(agentVersion); return this; } /** * Returns a string representation of this object; useful for testing and * debugging. * * @return A string representation of this object. * * @see java.lang.Object#toString() */ @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("{"); if (getStackId() != null) sb.append("StackId: " + getStackId() + ","); if (getName() != null) sb.append("Name: " + getName() + ","); if (getArn() != null) sb.append("Arn: " + getArn() + ","); if (getRegion() != null) sb.append("Region: " + getRegion() + ","); if (getVpcId() != null) sb.append("VpcId: " + getVpcId() + ","); if (getAttributes() != null) sb.append("Attributes: " + getAttributes() + ","); if (getServiceRoleArn() != null) sb.append("ServiceRoleArn: " + getServiceRoleArn() + ","); if (getDefaultInstanceProfileArn() != null) sb.append("DefaultInstanceProfileArn: " + getDefaultInstanceProfileArn() + ","); if (getDefaultOs() != null) sb.append("DefaultOs: " + getDefaultOs() + ","); if (getHostnameTheme() != null) sb.append("HostnameTheme: " + getHostnameTheme() + ","); if (getDefaultAvailabilityZone() != null) sb.append("DefaultAvailabilityZone: " + getDefaultAvailabilityZone() + ","); if (getDefaultSubnetId() != null) sb.append("DefaultSubnetId: " + getDefaultSubnetId() + ","); if (getCustomJson() != null) sb.append("CustomJson: " + getCustomJson() + ","); if (getConfigurationManager() != null) sb.append("ConfigurationManager: " + getConfigurationManager() + ","); if (getChefConfiguration() != null) sb.append("ChefConfiguration: " + getChefConfiguration() + ","); if (getUseCustomCookbooks() != null) sb.append("UseCustomCookbooks: " + getUseCustomCookbooks() + ","); if (getUseOpsworksSecurityGroups() != null) sb.append("UseOpsworksSecurityGroups: " + getUseOpsworksSecurityGroups() + ","); if (getCustomCookbooksSource() != null) sb.append("CustomCookbooksSource: " + getCustomCookbooksSource() + ","); if (getDefaultSshKeyName() != null) sb.append("DefaultSshKeyName: " + getDefaultSshKeyName() + ","); if (getCreatedAt() != null) sb.append("CreatedAt: " + getCreatedAt() + ","); if (getDefaultRootDeviceType() != null) sb.append("DefaultRootDeviceType: " + getDefaultRootDeviceType() + ","); if (getAgentVersion() != null) sb.append("AgentVersion: " + getAgentVersion()); sb.append("}"); return sb.toString(); } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (obj instanceof Stack == false) return false; Stack other = (Stack) obj; if (other.getStackId() == null ^ this.getStackId() == null) return false; if (other.getStackId() != null && other.getStackId().equals(this.getStackId()) == false) return false; if (other.getName() == null ^ this.getName() == null) return false; if (other.getName() != null && other.getName().equals(this.getName()) == false) return false; if (other.getArn() == null ^ this.getArn() == null) return false; if (other.getArn() != null && other.getArn().equals(this.getArn()) == false) return false; if (other.getRegion() == null ^ this.getRegion() == null) return false; if (other.getRegion() != null && other.getRegion().equals(this.getRegion()) == false) return false; if (other.getVpcId() == null ^ this.getVpcId() == null) return false; if (other.getVpcId() != null && other.getVpcId().equals(this.getVpcId()) == false) return false; if (other.getAttributes() == null ^ this.getAttributes() == null) return false; if (other.getAttributes() != null && other.getAttributes().equals(this.getAttributes()) == false) return false; if (other.getServiceRoleArn() == null ^ this.getServiceRoleArn() == null) return false; if (other.getServiceRoleArn() != null && other.getServiceRoleArn().equals(this.getServiceRoleArn()) == false) return false; if (other.getDefaultInstanceProfileArn() == null ^ this.getDefaultInstanceProfileArn() == null) return false; if (other.getDefaultInstanceProfileArn() != null && other.getDefaultInstanceProfileArn().equals( this.getDefaultInstanceProfileArn()) == false) return false; if (other.getDefaultOs() == null ^ this.getDefaultOs() == null) return false; if (other.getDefaultOs() != null && other.getDefaultOs().equals(this.getDefaultOs()) == false) return false; if (other.getHostnameTheme() == null ^ this.getHostnameTheme() == null) return false; if (other.getHostnameTheme() != null && other.getHostnameTheme().equals(this.getHostnameTheme()) == false) return false; if (other.getDefaultAvailabilityZone() == null ^ this.getDefaultAvailabilityZone() == null) return false; if (other.getDefaultAvailabilityZone() != null && other.getDefaultAvailabilityZone().equals( this.getDefaultAvailabilityZone()) == false) return false; if (other.getDefaultSubnetId() == null ^ this.getDefaultSubnetId() == null) return false; if (other.getDefaultSubnetId() != null && other.getDefaultSubnetId().equals(this.getDefaultSubnetId()) == false) return false; if (other.getCustomJson() == null ^ this.getCustomJson() == null) return false; if (other.getCustomJson() != null && other.getCustomJson().equals(this.getCustomJson()) == false) return false; if (other.getConfigurationManager() == null ^ this.getConfigurationManager() == null) return false; if (other.getConfigurationManager() != null && other.getConfigurationManager().equals( this.getConfigurationManager()) == false) return false; if (other.getChefConfiguration() == null ^ this.getChefConfiguration() == null) return false; if (other.getChefConfiguration() != null && other.getChefConfiguration().equals( this.getChefConfiguration()) == false) return false; if (other.getUseCustomCookbooks() == null ^ this.getUseCustomCookbooks() == null) return false; if (other.getUseCustomCookbooks() != null && other.getUseCustomCookbooks().equals( this.getUseCustomCookbooks()) == false) return false; if (other.getUseOpsworksSecurityGroups() == null ^ this.getUseOpsworksSecurityGroups() == null) return false; if (other.getUseOpsworksSecurityGroups() != null && other.getUseOpsworksSecurityGroups().equals( this.getUseOpsworksSecurityGroups()) == false) return false; if (other.getCustomCookbooksSource() == null ^ this.getCustomCookbooksSource() == null) return false; if (other.getCustomCookbooksSource() != null && other.getCustomCookbooksSource().equals( this.getCustomCookbooksSource()) == false) return false; if (other.getDefaultSshKeyName() == null ^ this.getDefaultSshKeyName() == null) return false; if (other.getDefaultSshKeyName() != null && other.getDefaultSshKeyName().equals( this.getDefaultSshKeyName()) == false) return false; if (other.getCreatedAt() == null ^ this.getCreatedAt() == null) return false; if (other.getCreatedAt() != null && other.getCreatedAt().equals(this.getCreatedAt()) == false) return false; if (other.getDefaultRootDeviceType() == null ^ this.getDefaultRootDeviceType() == null) return false; if (other.getDefaultRootDeviceType() != null && other.getDefaultRootDeviceType().equals( this.getDefaultRootDeviceType()) == false) return false; if (other.getAgentVersion() == null ^ this.getAgentVersion() == null) return false; if (other.getAgentVersion() != null && other.getAgentVersion().equals(this.getAgentVersion()) == false) return false; return true; } @Override public int hashCode() { final int prime = 31; int hashCode = 1; hashCode = prime * hashCode + ((getStackId() == null) ? 0 : getStackId().hashCode()); hashCode = prime * hashCode + ((getName() == null) ? 0 : getName().hashCode()); hashCode = prime * hashCode + ((getArn() == null) ? 0 : getArn().hashCode()); hashCode = prime * hashCode + ((getRegion() == null) ? 0 : getRegion().hashCode()); hashCode = prime * hashCode + ((getVpcId() == null) ? 0 : getVpcId().hashCode()); hashCode = prime * hashCode + ((getAttributes() == null) ? 0 : getAttributes().hashCode()); hashCode = prime * hashCode + ((getServiceRoleArn() == null) ? 0 : getServiceRoleArn() .hashCode()); hashCode = prime * hashCode + ((getDefaultInstanceProfileArn() == null) ? 0 : getDefaultInstanceProfileArn().hashCode()); hashCode = prime * hashCode + ((getDefaultOs() == null) ? 0 : getDefaultOs().hashCode()); hashCode = prime * hashCode + ((getHostnameTheme() == null) ? 0 : getHostnameTheme() .hashCode()); hashCode = prime * hashCode + ((getDefaultAvailabilityZone() == null) ? 0 : getDefaultAvailabilityZone().hashCode()); hashCode = prime * hashCode + ((getDefaultSubnetId() == null) ? 0 : getDefaultSubnetId() .hashCode()); hashCode = prime * hashCode + ((getCustomJson() == null) ? 0 : getCustomJson().hashCode()); hashCode = prime * hashCode + ((getConfigurationManager() == null) ? 0 : getConfigurationManager().hashCode()); hashCode = prime * hashCode + ((getChefConfiguration() == null) ? 0 : getChefConfiguration().hashCode()); hashCode = prime * hashCode + ((getUseCustomCookbooks() == null) ? 0 : getUseCustomCookbooks().hashCode()); hashCode = prime * hashCode + ((getUseOpsworksSecurityGroups() == null) ? 0 : getUseOpsworksSecurityGroups().hashCode()); hashCode = prime * hashCode + ((getCustomCookbooksSource() == null) ? 0 : getCustomCookbooksSource().hashCode()); hashCode = prime * hashCode + ((getDefaultSshKeyName() == null) ? 0 : getDefaultSshKeyName().hashCode()); hashCode = prime * hashCode + ((getCreatedAt() == null) ? 0 : getCreatedAt().hashCode()); hashCode = prime * hashCode + ((getDefaultRootDeviceType() == null) ? 0 : getDefaultRootDeviceType().hashCode()); hashCode = prime * hashCode + ((getAgentVersion() == null) ? 0 : getAgentVersion() .hashCode()); return hashCode; } @Override public Stack clone() { try { return (Stack) super.clone(); } catch (CloneNotSupportedException e) { throw new IllegalStateException( "Got a CloneNotSupportedException from Object.clone() " + "even though we're Cloneable!", e); } } }
apache-2.0
compomics/compomics-utilities
src/main/java/com/compomics/util/io/export/features/peptideshaker/PsValidationFeature.java
7103
package com.compomics.util.io.export.features.peptideshaker; import com.compomics.util.io.export.ExportFeature; import com.google.gson.annotations.SerializedName; import java.util.ArrayList; import java.util.Arrays; /** * This enum lists the export features linked to the validation process. * * @author Marc Vaudel * @author Harald Barsnes */ public enum PsValidationFeature implements ExportFeature { @SerializedName("PsValidationFeature.validated_protein") validated_protein("#Validated", "The number of validated proteins.", false), @SerializedName("PsValidationFeature.total_protein") total_protein("Total Possible TP", "The estimated total number of true positive proteins.", false), @SerializedName("PsValidationFeature.protein_fdr") protein_fdr("FDR Limit", "The estimated protein False Discovery Rate (FDR).", false), @SerializedName("PsValidationFeature.protein_fnr") protein_fnr("FNR Limit", "The estimated protein False Negative Rate (FNR).", false), @SerializedName("PsValidationFeature.protein_confidence") protein_confidence("Confidence Limit", "The lowest confidence among validated proteins.", false), @SerializedName("PsValidationFeature.protein_pep") protein_pep("PEP Limit", "The highest Posterior Error Probability (PEP) among validated proteins.", false), @SerializedName("PsValidationFeature.protein_accuracy") protein_accuracy("Confidence Accuracy", "The estimated protein Posterior Error Probability (PEP) and confidence estimation accuracy.", false), @SerializedName("PsValidationFeature.validated_peptide") validated_peptide("#Validated", "The number of validated peptides. Note that peptides are grouped by modification status when statistical significance is ensured, see advanced validation parameters.", false), @SerializedName("PsValidationFeature.total_peptide") total_peptide("Total Possible TP", "The estimated total number of true positive peptides. Note that peptides are grouped by modification status when statistical significance is ensured, see advanced validation parameters.", false), @SerializedName("PsValidationFeature.peptide_fdr") peptide_fdr("FDR Limit", "The estimated peptide False Discovery Rate (FDR). Note that peptides are grouped by modification status when statistical significance is ensured, see advanced validation parameters.", false), @SerializedName("PsValidationFeature.peptide_fnr") peptide_fnr("FNR Limit", "The estimated peptide False Negative Rate (FNR). Note that peptides are grouped by modification status when statistical significance is ensured, see advanced validation parameters.", false), @SerializedName("PsValidationFeature.peptide_confidence") peptide_confidence("Confidence Limit", "The lowest confidence among validated peptides. Note that peptides are grouped by modification status when statistical significance is ensured, see advanced validation parameters.", false), @SerializedName("PsValidationFeature.peptide_pep") peptide_pep("PEP Limit", "The highest Posterior Error Probability (PEP) among validated peptides. Note that peptides are grouped by modification status when statistical significance is ensured, see advanced validation parameters.", false), @SerializedName("PsValidationFeature.peptide_accuracy") peptide_accuracy("Confidence Accuracy", "The estimated peptide Posterior Error Probability (PEP) and confidence estimation accuracy. Note that peptides are grouped by modification status when statistical significance is ensured, see advanced validation parameters.", false), @SerializedName("PsValidationFeature.validated_psm") validated_psm("#Validated PSM", "The number of validated Peptide Spectrum Matches (PSMs). Note that PSMs are grouped by identified charge when statistical significance is ensured, see advanced validation parameters.", false), @SerializedName("PsValidationFeature.total_psm") total_psm("Total Possible TP", "The estimated total number of true positive Peptide Spectrum Matches (PSMs). Note that PSMs are grouped by identified charge when statistical significance is ensured, see advanced validation parameters.", false), @SerializedName("PsValidationFeature.psm_fdr") psm_fdr("FDR Limit", "The estimated Peptide Spectrum Match (PSM) False Discovery Rate (FDR). Note that PSMs are grouped by identified charge when statistical significance is ensured, see advanced validation parameters.", false), @SerializedName("PsValidationFeature.psm_fnr") psm_fnr("FNR Limit", "The estimated Peptide Spectrum Match (PSM) False Negative Rate (FNR). Note that PSMs are grouped by identified charge when statistical significance is ensured, see advanced validation parameters.", false), @SerializedName("PsValidationFeature.psm_confidence") psm_confidence("Confidence Limit", "The lowest confidence among validated Peptide Spectrum Matches (PSMs). Note that PSMs are grouped by identified charge when statistical significance is ensured, see advanced validation parameters.", false), @SerializedName("PsValidationFeature.psm_pep") psm_pep("PEP Limit", "The highest Posterior Error Probability (PEP) among validated Peptide Spectrum Matches (PSMs). Note that PSMs are grouped by identified charge when statistical significance is ensured, see advanced validation parameters.", false), @SerializedName("PsValidationFeature.psm_accuracy") psm_accuracy("Confidence Accuracy", "The estimated Peptide Spectrum Match (PSM) Posterior Error Probability (PEP) and confidence estimation accuracy. Note that PSMs are grouped by identified charge when statistical significance is ensured, see advanced validation parameters.", false); /** * The title of the feature which will be used for column heading. */ public String title; /** * The description of the feature. */ public String description; /** * The type of export feature. */ public final static String type = "Validation Summary"; /** * Indicates whether a feature is for advanced user only. */ private final boolean advanced; /** * Constructor. * * @param title title of the feature * @param description description of the feature * @param advanced indicates whether a feature is for advanced user only */ private PsValidationFeature(String title, String description, boolean advanced) { this.title = title; this.description = description; this.advanced = advanced; } @Override public ArrayList<ExportFeature> getExportFeatures(boolean includeSubFeatures) { ArrayList<ExportFeature> result = new ArrayList<>(); result.addAll(Arrays.asList(values())); return result; } @Override public String getTitle() { return title; } @Override public String getDescription() { return description; } @Override public String getFeatureFamily() { return type; } @Override public boolean isAdvanced() { return advanced; } }
apache-2.0
SEEG-Oxford/ABRAID-MP
src/Common/src/uk/ac/ox/zoo/seeg/abraid/mp/common/service/workflow/DiseaseOccurrenceValidationService.java
917
package uk.ac.ox.zoo.seeg.abraid.mp.common.service.workflow; import uk.ac.ox.zoo.seeg.abraid.mp.common.domain.DiseaseOccurrence; import java.util.List; /** * Adds validation parameters to a disease occurrence. Marks it for manual validation (via the Data Validator GUI) * if appropriate. * * Copyright (c) 2014 University of Oxford */ public interface DiseaseOccurrenceValidationService { /** * Adds validation parameters to a disease occurrence, including various checks. * @param occurrence The disease occurrence. */ void addValidationParametersWithChecks(DiseaseOccurrence occurrence); /** * Adds validation parameters to a list of disease occurrences (without checks). Each occurrence must belong to * the same disease group. * @param occurrences The list of disease occurrences. */ void addValidationParameters(List<DiseaseOccurrence> occurrences); }
apache-2.0
3D-e-Chem/knime-pharmacophore
plugin/src/java/nl/esciencecenter/e3dchem/knime/pharmacophore/align/AlignDialog.java
1939
package nl.esciencecenter.e3dchem.knime.pharmacophore.align; import org.knime.core.node.defaultnodesettings.DefaultNodeSettingsPane; import org.knime.core.node.defaultnodesettings.DialogComponentColumnNameSelection; import org.knime.core.node.defaultnodesettings.DialogComponentMultiLineString; import org.knime.core.node.defaultnodesettings.DialogComponentNumber; import nl.esciencecenter.e3dchem.knime.pharmacophore.PharValue; /** * <code>NodeDialog</code> for the "AlignmentTransform" Node. * * This node dialog derives from {@link DefaultNodeSettingsPane} which allows creation of a simple dialog with standard * components. If you need a more complex dialog please derive directly from {@link org.knime.core.node.NodeDialogPane}. */ public class AlignDialog extends DefaultNodeSettingsPane { /** * New pane for configuring AlignmentTransform node dialog. This is just a suggestion to demonstrate possible default dialog * components. */ @SuppressWarnings("unchecked") protected AlignDialog() { super(); AlignConfig config = new AlignConfig(); addDialogComponent(new DialogComponentColumnNameSelection(config.getQueryColumn(), "Query Pharmacophore column", AlignModel.QUERY_PORT, PharValue.class)); addDialogComponent( new DialogComponentMultiLineString(config.getReferencePharmacophore(), "Reference Pharmacophore", true, 40, 10)); createNewTab("Advanced"); addDialogComponent(new DialogComponentNumber(config.getCutoff(), "Tolerance threshold for considering two distances to be equivalent", 0.1)); addDialogComponent(new DialogComponentNumber(config.getCliqueBreak(), "Break when set number of cliques is found", 1)); addDialogComponent(new DialogComponentNumber(config.getCliques2align(), "Number of cliques of each query pharmacophore to align", 1)); } }
apache-2.0
V1toss/JavaPA
part_5/iterator/src/main/java/vkaretko/PrimeNumberIterator.java
1945
package vkaretko; import java.util.Iterator; import java.util.regex.Matcher; import java.util.regex.Pattern; /** * Class PrimeNumberIterator for iterating prime numbers. * * @author Karetko Victor * @version 1.00 * @since 14.12.2016 */ public class PrimeNumberIterator implements Iterator { /** * Int values for iterator. */ private final int[] values; /** * Start index of array. */ private int index = 0; /** * Constructor of PrimeNumberIterator. * @param values array to iterate. */ public PrimeNumberIterator(int[] values) { this.values = values; } /** * Pattern for prime numbers. */ private static final Pattern PATTERN = Pattern.compile(".?|(..+?)\\1+"); /** * Method checks that number is prime. * @param n number to check * @return true if prime, false otherwise */ private boolean isPrime(int n) { Matcher m = PATTERN.matcher(new String(new char[n])); return !m.matches(); } /** * Method check that array has prime numbers. * @return true if array has prime numbers, false otherwise. */ @Override public boolean hasNext() { boolean result = false; for (int ind = index; ind < values.length; ind++) { if (isPrime(values[ind])) { result = true; break; } } return result; } /** * Method select next prime number in Array. * @return next prime number in array. */ @Override public Object next() { Integer result = null; if (hasNext()) { for (int ind = index; ind < values.length; ind++) { if (isPrime(values[ind])) { result = values[ind]; index = ind + 1; break; } } } return result; } }
apache-2.0
gsavastano/zaproxy
src/org/zaproxy/zap/extension/ascan/AllCategoryTableModel.java
9478
/* * * Paros and its related class files. * * Paros is an HTTP/HTTPS proxy for assessing web application security. * Copyright (C) 2003-2004 Chinotec Technologies Company * * This program is free software; you can redistribute it and/or * modify it under the terms of the Clarified Artistic License * as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * Clarified Artistic License for more details. * * You should have received a copy of the Clarified Artistic License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */ // ZAP: 2012/04/25 Added type argument to generic type and changed to use the // method Boolean.valueOf. // ZAP: 2012/05/03 Moved a statement in the method setValueAt(Object, int , int). // ZAP: 2013/11/28 Issue 923: Allow individual rule thresholds and strengths to be set via GUI // ZAP: 2014/05/20 Issue 377: Unfulfilled dependencies hang the active scan // ZAP: 2016/07/25 Change constructor's parameter to PluginFactory // ZAP: 2017/06/05 Take into account the enabled state of the plugin when showing the AlertThreshold of the category. package org.zaproxy.zap.extension.ascan; import java.util.HashMap; import java.util.Map; import javax.swing.table.DefaultTableModel; import org.parosproxy.paros.Constant; import org.parosproxy.paros.core.scanner.Category; import org.parosproxy.paros.core.scanner.Plugin; import org.parosproxy.paros.core.scanner.Plugin.AlertThreshold; import org.parosproxy.paros.core.scanner.Plugin.AttackStrength; import org.parosproxy.paros.core.scanner.PluginFactory; public class AllCategoryTableModel extends DefaultTableModel { private static final long serialVersionUID = 1L; private Map<String, String> i18nToStr = null; private static final String[] columnNames = { Constant.messages.getString("ascan.policy.table.category"), Constant.messages.getString("ascan.policy.table.threshold"), Constant.messages.getString("ascan.policy.table.strength")}; private PluginFactory pluginFactory; /** * Constructs an {@code AllCategoryTableModel} with the given plugin factory. * * @param pluginFactory the plugin factory * @see #setPluginFactory(PluginFactory) */ public AllCategoryTableModel(PluginFactory pluginFactory) { this.pluginFactory = pluginFactory; } public void setPluginFactory(PluginFactory pluginFactory) { this.pluginFactory = pluginFactory; fireTableDataChanged(); } @Override // ZAP: Added the type argument. public Class<?> getColumnClass(int c) { return String.class; } @Override public String getColumnName(int col) { return columnNames[col]; } @Override public boolean isCellEditable(int rowIndex, int columnIndex) { if (columnIndex > 0) { return true; } return false; } @Override public void setValueAt(Object value, int row, int col) { switch (col) { case 0: break; case 1: if (value.toString().isEmpty()) { break; } setPluginCategoryThreshold(row, AlertThreshold.valueOf(i18nToStr((String) value))); fireTableCellUpdated(row, col); break; case 2: if (value.toString().isEmpty()) { break; } setPluginCategoryStrength(row, AttackStrength.valueOf(i18nToStr((String) value))); fireTableCellUpdated(row, col); break; } } private String strToI18n(String str) { // I18n's threshold and strength enums return Constant.messages.getString("ascan.policy.level." + str.toLowerCase()); } private String i18nToStr(String str) { // Converts to i18n'ed names back to the enum names if (i18nToStr == null) { i18nToStr = new HashMap<>(); for (AlertThreshold at : AlertThreshold.values()) { i18nToStr.put(this.strToI18n(at.name()), at.name()); } for (AttackStrength as : AttackStrength.values()) { i18nToStr.put(this.strToI18n(as.name()), as.name()); } } return i18nToStr.get(str); } @Override public int getColumnCount() { return columnNames.length; } @Override public int getRowCount() { return Category.length(); } @Override public Object getValueAt(int row, int col) { Object result; switch (col) { case 0: result = Category.getName(row); break; case 1: result = getPluginCategoryThreshold(row); break; case 2: result = getPluginCategoryStrength(row); break; default: result = ""; } return result; } private String getPluginCategoryThreshold(int category) { AlertThreshold at = null; for (int i = 0; i < pluginFactory.getAllPlugin().size(); i++) { Plugin plugin = pluginFactory.getAllPlugin().get(i); if (plugin.getCategory() != category) { continue; } if (at == null) { at = getAlertThreshold(plugin); } else if (!at.equals(getAlertThreshold(plugin))) { // Not all the same return ""; } } if (at == null) { return ""; } return strToI18n(at.name()); } /** * Gets the appropriate {@code AlertThreshold} for the state of the given plugin. * <p> * If the plugin is disabled it returns {@link AlertThreshold#OFF}, otherwise it returns its {@code AlertThreshold}. * * @param plugin the plugin for which a {@code AlertThreshold} will be returned. * @return the appropriate {@code AlertThreshold} for the plugin's state. */ private static AlertThreshold getAlertThreshold(Plugin plugin) { if (!plugin.isEnabled()) { return AlertThreshold.OFF; } return plugin.getAlertThreshold(true); } private String getPluginCategoryStrength(int category) { AttackStrength at = null; for (int i = 0; i < pluginFactory.getAllPlugin().size(); i++) { Plugin plugin = pluginFactory.getAllPlugin().get(i); if (plugin.getCategory() != category) { continue; } if (at == null) { at = plugin.getAttackStrength(true); } else if (!at.equals(plugin.getAttackStrength(true))) { // Not all the same return ""; } } if (at == null) { return ""; } return strToI18n(at.name()); } private void setPluginCategoryThreshold(int category, AlertThreshold at) { boolean enable = !AlertThreshold.OFF.equals(at); for (int i = 0; i < pluginFactory.getAllPlugin().size(); i++) { Plugin plugin = pluginFactory.getAllPlugin().get(i); if (plugin.getCategory() != category) { continue; } if (enable) { String[] dependencies = plugin.getDependency(); if (dependencies != null && dependencies.length != 0) { if (!pluginFactory.hasAllDependenciesAvailable(plugin)) { continue; } } } plugin.setAlertThreshold(at); plugin.setEnabled(enable); } } private void setPluginCategoryStrength(int category, AttackStrength at) { for (int i = 0; i < pluginFactory.getAllPlugin().size(); i++) { Plugin plugin = pluginFactory.getAllPlugin().get(i); if (plugin.getCategory() != category) { continue; } plugin.setAttackStrength(at); } } void setAllCategoryEnabled(boolean enabled) { for (int i = 0; i < pluginFactory.getAllPlugin().size(); i++) { Plugin plugin = pluginFactory.getAllPlugin().get(i); plugin.setEnabled(enabled); } fireTableDataChanged(); } boolean isAllCategoryEnabled() { for (int i = 0; i < pluginFactory.getAllPlugin().size(); i++) { Plugin plugin = pluginFactory.getAllPlugin().get(i); if (!plugin.isEnabled()) { return false; } } return true; } }
apache-2.0
CharonChui/AndroidDevelopFramework
framework/src/main/java/com/charonchui/framework/util/ApkUtils.java
21539
package com.charonchui.framework.util; import android.content.Context; import android.content.Intent; import android.content.pm.ApplicationInfo; import android.content.pm.PackageInfo; import android.content.pm.PackageManager; import android.content.pm.PackageManager.NameNotFoundException; import android.content.pm.Signature; import android.content.res.Resources; import android.net.Uri; import android.os.Build; import android.util.DisplayMetrics; import android.util.Log; import java.io.File; import java.lang.reflect.Constructor; import java.lang.reflect.Field; import java.lang.reflect.Method; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.regex.Matcher; import java.util.regex.Pattern; public class ApkUtils { private final static String TAG = "ApkUtils"; // 已安装的所有应用 private static final int APP_TYPE_ALL = 0; // 已安装的非系统应用 private static final int APP_TYPE_NON_SYSTEM = 1; // 已安装的系统应用 private static final int APP_TYPE_SYSTEM = 2; public static final int APK_INSTALLED = 0; public static final int APK_UNINSTALLED = -2; public static final int APK_UPGRADE = 1; public static final int APK_DOWNGRADE = -1; public static int getInstallState(PackageInfo info, int tagretVersionCode) { int ret; if (info == null) { ret = ApkUtils.APK_UNINSTALLED; } else if (info.versionCode == tagretVersionCode) { ret = ApkUtils.APK_INSTALLED; } else if (info.versionCode < tagretVersionCode) { ret = ApkUtils.APK_UPGRADE; } else ret = ApkUtils.APK_DOWNGRADE; return ret; } public static PackageInfo getInstalledApp(Context context, PackageManager pm, String pname) { PackageInfo info = null; pm = context.getPackageManager(); try { info = pm.getPackageInfo(pname, 0); } catch (NameNotFoundException e) { e.printStackTrace(); } return info; } public static String getInstalledAppNameByPackageInfo(Context context, PackageManager pm, PackageInfo info) { if (pm == null) { pm = context.getPackageManager(); } return pm.getApplicationLabel(info.applicationInfo).toString(); } public static List<PackageInfo> getInstalledApps(Context context) { PackageManager pm = context.getPackageManager(); return getInstalledApps(context, pm); } public static List<PackageInfo> getInstalledApps(Context context, PackageManager pm) { return getAllApps(context, pm, APP_TYPE_ALL); } public static List<PackageInfo> getInstalledNonSystemApps(Context context, PackageManager pm) { return getAllApps(context, pm, APP_TYPE_NON_SYSTEM); } public static List<PackageInfo> getInstalledSystemApps(Context context, PackageManager pm) { return getAllApps(context, pm, APP_TYPE_SYSTEM); } private static List<PackageInfo> getAllApps(Context context, PackageManager pm, int appType) { List<PackageInfo> pkgs = new ArrayList<>(); List<PackageInfo> infos = pm .getInstalledPackages(PackageManager.GET_DISABLED_COMPONENTS); switch (appType) { case APP_TYPE_ALL: for (PackageInfo info : infos) { pkgs.add(info); } break; case APP_TYPE_NON_SYSTEM: for (PackageInfo info : infos) { if (!isSystemApp(info.applicationInfo)) { pkgs.add(info); } } break; case APP_TYPE_SYSTEM: for (PackageInfo info : infos) { if (isSystemApp(info.applicationInfo)) { pkgs.add(info); } } break; } return pkgs; } public static List<String> getInstalledAppPkgs(Context context) { List<String> pkgs = new ArrayList<String>(); List<PackageInfo> packages = context.getPackageManager() .getInstalledPackages(0); for (PackageInfo pi : packages) { if (!ApkUtils.isSystemApp(pi.applicationInfo)) { pkgs.add(pi.packageName); } } return pkgs; } public static List<PackageInfo> getInstalledPackages(PackageManager pm, int flags) { List<PackageInfo> infos = pm.getInstalledPackages(flags); return infos; } public static boolean isApkInstalled(Context context, String packageName) { if (packageName == null) { return false; } if (packageName.equals(context.getPackageName())) { return true; } boolean result = false; try { result = context.getPackageManager().getPackageInfo(packageName, PackageManager.GET_DISABLED_COMPONENTS) != null; } catch (NameNotFoundException e) { e.printStackTrace(); } return result; } public static boolean isApkInstalled(Context context, String packageName, String versionCode) { if (packageName == null) { return false; } if (packageName.equals(context.getPackageName())) { return true; } boolean result = false; try { PackageInfo info = context.getPackageManager().getPackageInfo(packageName, PackageManager.GET_DISABLED_COMPONENTS); if (info == null) { return false; } result = String.valueOf(info.versionCode).equals(versionCode); } catch (NameNotFoundException e) { e.printStackTrace(); } return result; } public static boolean isValidApk(String apkPath, Context context) { boolean bRet = false; try { if (FileUtil.isFileExist(apkPath)) { PackageManager pm = context.getPackageManager(); PackageInfo pkInfo = pm.getPackageArchiveInfo(apkPath, PackageManager.GET_CONFIGURATIONS); bRet = pkInfo != null; } } catch (Throwable t) { t.printStackTrace(); } return bRet; } public static void uninstall(Context mContext, String packageName) { Intent intent; Uri uri; try { uri = Uri.fromParts("package", packageName, null); intent = new Intent(Intent.ACTION_DELETE, uri); intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); mContext.startActivity(intent); } catch (Exception e) { e.printStackTrace(); } } public static boolean openApp(final Context context, final String packageName) { Intent mIntent = context.getPackageManager().getLaunchIntentForPackage(packageName); if (mIntent != null) { context.startActivity(mIntent); return true; } else { return false; } } public static boolean isSystemApp(ApplicationInfo info) { if ((info.flags & ApplicationInfo.FLAG_SYSTEM) > 0) { if (info.publicSourceDir.startsWith("data/dataapp") || info.publicSourceDir.startsWith("/data/dataapp")) { return false; } return true; } return false; } public static String getAppSignatureMd5(Context context, String packname) { try { PackageManager packageManager = context.getPackageManager(); PackageInfo info = packageManager.getPackageInfo(packname, PackageManager.GET_SIGNATURES); byte[] signature = info.signatures[0].toByteArray(); String hash = Md5Utils.md5LowerCase(Arrays.toString(signature)); return hash; } catch (NameNotFoundException e) { return null; } } private static String[] getPackageSignatures(Context context, String apkPath) { try { PackageManager pm = context.getPackageManager(); PackageInfo info = pm.getPackageArchiveInfo(apkPath, PackageManager.GET_SIGNATURES); if (info != null && info.signatures != null && info.signatures.length > 0) { byte[] signature = info.signatures[0].toByteArray(); String hash = HashUtils.getHash(Arrays.toString(signature)).toLowerCase(); String packageName = info.applicationInfo.packageName; return new String[]{hash, packageName}; } } catch (Throwable e) { e.printStackTrace(); } return null; } public static Object parsePackage(String archiveFilePath, int flags) { // 这是一个Package 解释器, 是隐藏的 try { Object packageParser; // 构造函数的参数只有一个, apk文件的路径 if (Build.VERSION.SDK_INT >= 21) {//android 5.0系统改方法做了改变 packageParser = ReflectUtils.getObjectConstructor(ReflectUtils.CLASSNAME_PAGEAGEPARSE) .newInstance(); } else { packageParser = ReflectUtils.getObjectConstructor(ReflectUtils.CLASSNAME_PAGEAGEPARSE, String.class) .newInstance(archiveFilePath); } // 这个是与显示有关的, 里面涉及到一些像素显示等等, 我们使用默认的情况 DisplayMetrics metrics = new DisplayMetrics(); metrics.setToDefaults(); final File sourceFile = new File(archiveFilePath); // 这里就是解析了, 四个参数, // 源文件File, // 目的文件路径(看Android安装器源码, 用的是源文件路径, 但名字却是destFileName) // 显示, DisplayMetrics metrics // flags, 这个标记类型,比如PackageManager.GET_SIGNATURES表示需要签名信息 Object pkg; if (Build.VERSION.SDK_INT >= 21) { Method parsePackageMethod = packageParser.getClass().getMethod("parsePackage", File.class, int.class); pkg = parsePackageMethod.invoke(packageParser, sourceFile, flags); } else { Method parsePackageMethod = packageParser.getClass().getMethod("parsePackage", File.class, String.class, DisplayMetrics.class, int.class); pkg = parsePackageMethod.invoke(packageParser, sourceFile, archiveFilePath, metrics, flags); } if (pkg == null) { Log.d(TAG, "---parsePackage is null------;;sourceFile=" + sourceFile.getAbsolutePath()); return null; } //这里只取出而不校验,如果要校验,第二个参数传0 if (Build.VERSION.SDK_INT >= 21) { Method collectCertificates = packageParser.getClass().getDeclaredMethod("collectCertificates", ReflectUtils.classForName(ReflectUtils.CLASSNAME_PAGEAGEPARSE_PACKAGE), File.class, int.class); collectCertificates.setAccessible(true); collectCertificates.invoke(packageParser, pkg, sourceFile, 1); } else { Method collectCertificates = packageParser.getClass().getDeclaredMethod("collectCertificates", ReflectUtils.classForName(ReflectUtils.CLASSNAME_PAGEAGEPARSE_PACKAGE), int.class); collectCertificates.invoke(packageParser, pkg, 1); } return pkg; } catch (Exception e) { e.printStackTrace(); } return null; // 应用程序信息包, 这个公开的, 不过有些函数, 变量没公开 // PackageInfo pkgInfo=null; // try { // pkgInfo=PackageParser.generatePackageInfo(pkg, null, flags,0,0); // } catch (Exception e) { // // TODO: handle exception // Log.e(TAG, "--generatePackageInfo error--"); // return null; // } // return pkgInfo; } public static String[] getApkFileSignatureAndPackageName(Context context, String apkPath) { try { String[] packageSignatureAndName = getPackageSignatures(context, apkPath); if (packageSignatureAndName != null) { return packageSignatureAndName; } //这种方式在nexus 5 android 5.0上会卡住。 Object pkg = null; try { //package太大,有可能导致oom pkg = parsePackage(apkPath, PackageManager.GET_SIGNATURES); } catch (OutOfMemoryError e) { pkg = null; } if (pkg == null) { return null; } Signature[] sigsApk = getApkSignature(pkg, apkPath); if (sigsApk != null && sigsApk.length > 0) { byte[] signature = sigsApk[0].toByteArray(); String hash = HashUtils.getHash(Arrays.toString(signature)).toLowerCase(); String packageName = (String) ReflectUtils.getObjectFieldNoDeclared(ReflectUtils.getField(pkg, "applicationInfo"), "packageName"); return new String[]{hash, packageName}; } else { return null; } } catch (Exception e) { e.printStackTrace(); return null; } } public static Signature[] getApkSignature(Object pkg, String apkPath) { Signature[] sigs = new Signature[0]; try { sigs = (Signature[]) ReflectUtils.getField(pkg, "mSignatures"); } catch (NoSuchFieldException e) { e.printStackTrace(); } catch (IllegalAccessException e) { e.printStackTrace(); } if (sigs == null) { return null;// 有一些系统应用获取不到签名信息(比如google电子市场),sigs会为空,所以做特别处理,以防报错 } if (sigs.length <= 0) { return null; } return sigs; } public static String[] getApkFileSignatureAndPackageNameEx(Context context, String apkPath) { try { Object info2 = parsePackage(apkPath, PackageManager.GET_SIGNATURES); if (info2 != null) { Signature[] sig = (Signature[]) ReflectUtils.getField(info2, "mSignatures"); if (sig == null || sig.length == 0) { return null; } byte[] signature = sig[0].toByteArray(); String hash = HashUtils.getHash(Arrays.toString(signature)).toLowerCase(); String packageName = (String) ReflectUtils.getField(info2, "packageName"); return new String[]{hash, packageName}; } } catch (Exception e) { e.printStackTrace(); return null; } return null; } public static boolean isValidAppPackageName(String pkg) {// 检查包名是否合法 String regex = "^[a-zA-Z_]\\w*(\\.[a-zA-Z_]\\w*)*$"; Pattern p = Pattern.compile(regex); Matcher m = p.matcher(pkg); return m.matches(); } public static String getApkFileLable(Context ctx, String path) { String PATH_PackageParser = "android.content.pm.PackageParser"; String PATH_AssetManager = "android.content.res.AssetManager"; try { String apkPath = path; Class pkgParserCls = Class.forName(PATH_PackageParser); Class[] typeArgs = new Class[1]; typeArgs[0] = String.class; Constructor pkgParserCt; if (Build.VERSION.SDK_INT >= 21) { pkgParserCt = pkgParserCls.getConstructor(); } else { pkgParserCt = pkgParserCls.getConstructor(typeArgs); } Object[] valueArgs = new Object[1]; valueArgs[0] = apkPath; Object pkgParser; if (Build.VERSION.SDK_INT >= 21) { pkgParser = pkgParserCt.newInstance(); } else { pkgParser = pkgParserCt.newInstance(valueArgs); } Log.d("DownloadUtils", "pkgParser:" + pkgParser.toString()); DisplayMetrics metrics = new DisplayMetrics(); metrics.setToDefaults(); Method pkgParser_parsePackageMtd; if (Build.VERSION.SDK_INT >= 21) { typeArgs = new Class[2]; typeArgs[0] = File.class; typeArgs[1] = int.class; } else { typeArgs = new Class[4]; typeArgs[0] = File.class; typeArgs[1] = String.class; typeArgs[2] = DisplayMetrics.class; typeArgs[3] = Integer.TYPE; } pkgParser_parsePackageMtd = pkgParserCls.getDeclaredMethod("parsePackage", typeArgs); if (Build.VERSION.SDK_INT >= 21) { valueArgs = new Object[2]; valueArgs[0] = new File(apkPath); valueArgs[1] = 0; } else { valueArgs = new Object[4]; valueArgs[0] = new File(apkPath); valueArgs[1] = apkPath; valueArgs[2] = metrics; valueArgs[3] = 0; } Object pkgParserPkg = pkgParser_parsePackageMtd.invoke(pkgParser, valueArgs); Field appInfoFld = pkgParserPkg.getClass().getDeclaredField("applicationInfo"); ApplicationInfo info = (ApplicationInfo) appInfoFld.get(pkgParserPkg); Log.d("DownloadUtils", "pkg:" + info.packageName + " uid=" + info.uid); Class assetMagCls = Class.forName(PATH_AssetManager); Constructor assetMagCt = assetMagCls.getConstructor((Class[]) null); Object assetMag = assetMagCt.newInstance((Object[]) null); typeArgs = new Class[1]; typeArgs[0] = String.class; Method assetMag_addAssetPathMtd = assetMagCls.getDeclaredMethod("addAssetPath", typeArgs); valueArgs = new Object[1]; valueArgs[0] = apkPath; assetMag_addAssetPathMtd.invoke(assetMag, valueArgs); Resources res = ctx.getResources(); typeArgs = new Class[3]; typeArgs[0] = assetMag.getClass(); typeArgs[1] = res.getDisplayMetrics().getClass(); typeArgs[2] = res.getConfiguration().getClass(); Constructor resCt = Resources.class.getConstructor(typeArgs); valueArgs = new Object[3]; valueArgs[0] = assetMag; valueArgs[1] = res.getDisplayMetrics(); valueArgs[2] = res.getConfiguration(); res = (Resources) resCt.newInstance(valueArgs); CharSequence label = null; if (info.labelRes != 0) { label = res.getText(info.labelRes); } Log.d("DownloadUtils", "label=" + label); return label.toString(); } catch (Exception e) { e.printStackTrace(); } return "-1"; } public static final String[] coreApks = {"com.android.phone", "com.android.inputmethod.latin", "android", "com.android.bluetooth", "com.android.certinstaller", "com.android.sidekick", "com.google.android.gsf", "com.google.android.partnersetup", "com.android.htmlviewer", "com.android.wallpaper.livepicker", "com.android.stk", "com.android.providers.userdictionary", "com.android.packageinstaller", "com.android.providers.telocation", "com.android.email", "com.android.providers.telephony", "com.android.calculator2", "com.android.providers.contacts", "com.android.browser", "com.android.monitor", "com.android.soundrecorder", "com.android.providers.media", "com.android.launcher", "com.android.calendar", "com.android.providers.calendar", "com.android.defcontainer", "com.android.settings", "com.android.providers.settings", "com.android.deskclock", "com.android.providers.drm", "com.android.providers.applications", "com.android.contacts", "com.android.gallery", "com.google.android.location", "com.android.fileexplorer", "com.android.updater", "com.android.providers.downloads.ui", "com.android.providers.downloads", "com.android.mms", "com.android.server.vpn", "com.android.providers.subscribedfeeds", "com.android.thememanager", "com.android.systemui", "com.android.wallpaper", "com.google.android.gm", "com.google.android.backup", "com.google.android.syncadapters.calendar", "com.google.android.syncadapters.contacts", "com.android.vending.updater", "com.android.vending", "com.google.android.feedback", "com.google.android.street", "com.android.setupwizard", "com.google.android.googlequicksearchbox", "com.google.android.apps.uploader", "com.android.camera", "com.google.android.apps.genie.geniewidget", "com.android.music", "com.android.musicvis", "com.google.android.voicesearch", "com.noshufou.android.su", "com.qihoo.root", "com.lbe.security.miui", "com.lbe.security.su", "com.lbe.security.shuame", "eu.chainfire.supersu", "com.miui.uac", "com.android.protips"}; }
apache-2.0
emistoolbox/emistoolbox
core/src/com/emistoolbox/common/model/mapping/EmisHierarchyDbMapEntry.java
1049
package com.emistoolbox.common.model.mapping; import com.emistoolbox.common.model.meta.EmisMetaDateEnum; import com.emistoolbox.common.model.meta.EmisMetaEntity; public abstract interface EmisHierarchyDbMapEntry extends EmisDbMapBase { public abstract EmisMetaEntity getParentEntity(); public abstract void setParentEntity(EmisMetaEntity paramEmisMetaEntity); public abstract EmisMetaDateEnum getDateType(); public abstract void setDateType(EmisMetaDateEnum paramEmisMetaDateEnum); public abstract DbRowDateAccess getDateAccess(); public abstract void setDateAccess(DbRowDateAccess paramDbRowDateAccess); public abstract DbRowAccess getParentAccess(); public abstract void setParentAccess(DbRowAccess paramDbRowAccess); public abstract EmisMetaEntity getChildEntity(); public abstract void setChildEntity(EmisMetaEntity paramEmisMetaEntity); public abstract DbRowAccess getChildAccess(); public abstract void setChildAccess(DbRowAccess paramDbRowAccess); }
apache-2.0
consulo/consulo-sql
src/com/dci/intellij/dbn/common/environment/EnvironmentChangeListener.java
1041
/* * Copyright 2012-2014 Dan Cioca * * 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.dci.intellij.dbn.common.environment; import com.intellij.util.messages.Topic; import java.util.EventListener; public interface EnvironmentChangeListener extends EventListener { Topic<EnvironmentChangeListener> TOPIC = Topic.create("Environment changed", EnvironmentChangeListener.class); void environmentConfigChanged(String environmentTypeId); void environmentVisibilitySettingsChanged(); }
apache-2.0
sculptor/sculptor
sculptor-examples/eda-samples/sculptor-betting/src/test/java/org/sculptor/betting/core/serviceapi/BettingEngineTest.java
1583
package org.sculptor.betting.core.serviceapi; import java.util.Set; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Disabled; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.sculptor.framework.accessimpl.mongodb.DbManager; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit.jupiter.SpringExtension; /** * Spring based test with MongoDB. */ @ExtendWith(SpringExtension.class) @ContextConfiguration(locations = { "classpath:applicationContext-test.xml" }) public class BettingEngineTest implements BettingEngineTestBase { @Autowired private DbManager dbManager; @Autowired private BettingEngine bettingEngine; @BeforeEach public void initTestData() { } @BeforeEach public void initDbManagerThreadInstance() throws Exception { // to be able to do lazy loading of associations inside test class DbManager.setThreadInstance(dbManager); } @AfterEach public void dropDatabase() { Set<String> names = dbManager.getDB().getCollectionNames(); for (String each : names) { if (!each.startsWith("system")) { dbManager.getDB().getCollection(each).drop(); } } // dbManager.getDB().dropDatabase(); } private int countRowsInDBCollection(String name) { return (int) dbManager.getDBCollection(name).getCount(); } @Test @Disabled public void testReceive() throws Exception { // TODO Auto-generated method stub } }
apache-2.0
realityforge/arez
core/src/test/java/arez/ZoneTest.java
3827
package arez; import java.text.ParseException; import org.realityforge.guiceyloops.shared.ValueUtil; import org.testng.annotations.Test; import static org.testng.Assert.*; public final class ZoneTest extends AbstractTest { @Test public void zone_safeRun_Function() { ArezTestUtil.enableZones(); final Zone zone1 = Arez.createZone(); assertEquals( ZoneHolder.getDefaultZone().getContext(), Arez.context() ); assertEquals( ZoneHolder.getZoneStack().size(), 0 ); assertFalse( zone1.isActive() ); final String expected = ValueUtil.randomString(); final String actual = zone1.safeRun( () -> { assertEquals( zone1.getContext(), Arez.context() ); assertEquals( ZoneHolder.getZoneStack().size(), 1 ); assertTrue( zone1.isActive() ); return expected; } ); assertEquals( actual, expected ); assertEquals( ZoneHolder.getDefaultZone().getContext(), Arez.context() ); assertEquals( ZoneHolder.getZoneStack().size(), 0 ); } @Test public void zone_safeRun_Procedure() { ArezTestUtil.enableZones(); final Zone zone1 = Arez.createZone(); assertEquals( ZoneHolder.getDefaultZone().getContext(), Arez.context() ); assertEquals( ZoneHolder.getZoneStack().size(), 0 ); assertFalse( zone1.isActive() ); zone1.safeRun( () -> { assertEquals( zone1.getContext(), Arez.context() ); assertEquals( ZoneHolder.getZoneStack().size(), 1 ); assertTrue( zone1.isActive() ); } ); assertEquals( ZoneHolder.getDefaultZone().getContext(), Arez.context() ); assertEquals( ZoneHolder.getZoneStack().size(), 0 ); } @Test public void zone_run_Function_throwsException() { ArezTestUtil.enableZones(); final Zone zone1 = Arez.createZone(); assertEquals( ZoneHolder.getDefaultZone().getContext(), Arez.context() ); assertEquals( ZoneHolder.getZoneStack().size(), 0 ); assertFalse( zone1.isActive() ); assertThrows( ParseException.class, () -> zone1.run( () -> { assertEquals( zone1.getContext(), Arez.context() ); assertEquals( ZoneHolder.getZoneStack().size(), 1 ); assertTrue( zone1.isActive() ); throw new ParseException( "", 1 ); } ) ); assertEquals( ZoneHolder.getDefaultZone().getContext(), Arez.context() ); assertEquals( ZoneHolder.getZoneStack().size(), 0 ); } @Test public void zone_run_Procedure_throwsException() { ArezTestUtil.enableZones(); final Zone zone1 = Arez.createZone(); assertEquals( ZoneHolder.getDefaultZone().getContext(), Arez.context() ); assertEquals( ZoneHolder.getZoneStack().size(), 0 ); assertFalse( zone1.isActive() ); final Procedure procedure = () -> { assertEquals( zone1.getContext(), Arez.context() ); assertEquals( ZoneHolder.getZoneStack().size(), 1 ); assertTrue( zone1.isActive() ); throw new ParseException( "", 1 ); }; assertThrows( ParseException.class, () -> zone1.run( procedure ) ); assertEquals( ZoneHolder.getDefaultZone().getContext(), Arez.context() ); assertEquals( ZoneHolder.getZoneStack().size(), 0 ); } @Test public void zone_run_Procedure_completesNormally() throws Throwable { ArezTestUtil.enableZones(); final Zone zone1 = Arez.createZone(); assertEquals( ZoneHolder.getDefaultZone().getContext(), Arez.context() ); assertEquals( ZoneHolder.getZoneStack().size(), 0 ); assertFalse( zone1.isActive() ); final Procedure procedure = () -> { assertEquals( zone1.getContext(), Arez.context() ); assertEquals( ZoneHolder.getZoneStack().size(), 1 ); assertTrue( zone1.isActive() ); }; zone1.run( procedure ); assertEquals( ZoneHolder.getDefaultZone().getContext(), Arez.context() ); assertEquals( ZoneHolder.getZoneStack().size(), 0 ); } }
apache-2.0
xiongwei-git/TedMemo
src/com/tedmemo/others/TComparator.java
835
package com.tedmemo.others; import android.text.Editable; import android.text.style.ImageSpan; import com.tedmemo.view.ImageEditText; import java.util.Comparator; /** * Created by Ted on 2014/9/10. */ public class TComparator implements Comparator<ImageSpan> { private Editable mEditable = null; private ImageEditText mImageEditText; public TComparator(ImageEditText imageEditText, Editable editable) { this.mEditable = editable; this.mImageEditText = imageEditText; } @Override public int compare(ImageSpan lhs, ImageSpan rhs) { if (this.mEditable.getSpanStart(lhs) > this.mEditable.getSpanStart(rhs)) { return 1; } if (this.mEditable.getSpanStart(lhs) == this.mEditable.getSpanStart(rhs)) { return 0; } return -1; } }
apache-2.0