repo_name
stringlengths
5
108
path
stringlengths
6
333
size
stringlengths
1
6
content
stringlengths
4
977k
license
stringclasses
15 values
miamidade/spring-portlet-mvc
src/main/java/gov/miamidade/portlet/HomeController.java
1076
package gov.miamidade.portlet; import java.text.DateFormat; import java.util.Date; import java.util.Locale; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.portlet.bind.annotation.RenderMapping; /** * Handles requests for the portlet view mode. */ @Controller @RequestMapping("VIEW") public class HomeController { private static final Logger logger = LoggerFactory.getLogger(HomeController.class); /** * Simply selects the home view to render by returning its name. */ @RenderMapping public String home(Locale locale, Model model) { logger.info("Welcome home! the client locale is "+ locale.toString()); Date date = new Date(); DateFormat dateFormat = DateFormat.getDateTimeInstance(DateFormat.LONG, DateFormat.LONG, locale); String formattedDate = dateFormat.format(date); model.addAttribute("serverTime", formattedDate); return "home"; } }
apache-2.0
roikku/drive-uploader
src/main/java/io/uploader/drive/gui/dlg/AbstractDialog.java
2117
/* * Copyright 2014 Loic Merckel * * 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.uploader.drive.gui.dlg; import com.google.common.base.Preconditions; import io.uploader.drive.gui.util.UiUtils; import javafx.scene.Scene; import javafx.stage.Modality; import javafx.stage.Stage; import javafx.stage.StageStyle; import javafx.stage.Window; public abstract class AbstractDialog { private final Stage dialog = new Stage(); private Scene scene = null ; private final Stage owner; public AbstractDialog (Stage owner) { super () ; this.owner = owner ; dialog.setMaxHeight(Double.MAX_VALUE); dialog.setMaxWidth(Double.MAX_VALUE); } protected void initStyle(StageStyle style) { dialog.initStyle(style); } protected void setTitle(String title) { dialog.setTitle(title); } protected void initOwner(Window owner) { dialog.initOwner(owner); } protected void initModality (Modality modality) { dialog.initModality(modality); } protected void setMinHeight(double d) { dialog.setMinHeight(d); } protected void setMinWidth(double d) { dialog.setMinWidth(d); } protected void setMaxHeight(double d) { dialog.setMaxHeight(d); } protected void setMaxWidth(double d) { dialog.setMaxWidth(d); } protected void setHeight(double d) { dialog.setHeight(d); } protected void setWidth(double d) { dialog.setWidth(d); } protected void setScene (Scene scene) { this.scene = scene ; } public final void showDialog() { Preconditions.checkNotNull(scene) ; dialog.setScene(scene); UiUtils.centerDialog(dialog, owner); dialog.show(); } }
apache-2.0
dmcennis/DynamicFactory
src/org/dynamicfactory/property/Property.java
2438
/* * Properties.java * * Created on 1 May 2007, 14:47 * */ /* * Copyright (c) 2009 Daniel McEnnis. * 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. * * For more about this software visit: * * https://github.com/dmcennis/DynamicFactory * */ package org.dynamicfactory.property; //import nz.ac.waikato.mcennis.rat.graph.model.Model; import org.dynamicfactory.Creatable; /** * * Class for defining a org.dynamicfactory.property on either actor, link, or graph * @author Daniel McEnnis * */ public interface Property<Type> extends Creatable<Property<Type>>, java.io.Serializable, Comparable<Property>{//}, Model { public static final int ADD_VALUE = 0; /** * Add a new value to this org.dynamicfactory.property * * @param value new object to be added */ public void add(Type value) throws InvalidObjectTypeException; /** * return this org.dynamicfactory.property's unique id * * @return id of this object */ public String getType(); /** * return array of all values. Returns an empty array if no properties are present * * @return array of org.dynamicfactory.property values */ public java.util.List<Type> getValue(); public void setType(String id); public void setClass(Class classType) throws InvalidObjectTypeException; /** * create a deep copy of this org.dynamicfactory.property * * @return deep copy of this org.dynamicfactory.property */ public Property prototype(); /** * Return the type of class that this org.dynamicfactory.property represents. All objects in * one org.dynamicfactory.property must be of the same type. * @return name of class types of objects */ public Class getPropertyClass(); }
apache-2.0
meclub/MeUI
lib_util/src/main/java/com/me/ui/util/ObjectUtils.java
6602
package com.me.ui.util; import android.os.Build; import android.support.annotation.RequiresApi; import android.support.v4.util.LongSparseArray; import android.support.v4.util.SimpleArrayMap; import android.util.SparseArray; import android.util.SparseBooleanArray; import android.util.SparseIntArray; import android.util.SparseLongArray; import java.lang.reflect.Array; import java.util.Collection; import java.util.Map; /** * <pre> * author: Blankj * blog : http://blankj.com * time : 2017/12/24 * desc : utils about object * </pre> */ public final class ObjectUtils { private ObjectUtils() { throw new UnsupportedOperationException("u can't instantiate me..."); } /** * Return whether object is empty. * * @param obj The object. * @return {@code true}: yes<br>{@code false}: no */ public static boolean isEmpty(final Object obj) { if (obj == null) { return true; } if (obj.getClass().isArray() && Array.getLength(obj) == 0) { return true; } if (obj instanceof CharSequence && obj.toString().length() == 0) { return true; } if (obj instanceof Collection && ((Collection) obj).isEmpty()) { return true; } if (obj instanceof Map && ((Map) obj).isEmpty()) { return true; } if (obj instanceof SimpleArrayMap && ((SimpleArrayMap) obj).isEmpty()) { return true; } if (obj instanceof SparseArray && ((SparseArray) obj).size() == 0) { return true; } if (obj instanceof SparseBooleanArray && ((SparseBooleanArray) obj).size() == 0) { return true; } if (obj instanceof SparseIntArray && ((SparseIntArray) obj).size() == 0) { return true; } if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR2) { if (obj instanceof SparseLongArray && ((SparseLongArray) obj).size() == 0) { return true; } } if (obj instanceof LongSparseArray && ((LongSparseArray) obj).size() == 0) { return true; } if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) { if (obj instanceof android.util.LongSparseArray && ((android.util.LongSparseArray) obj).size() == 0) { return true; } } return false; } public static boolean isEmpty(final CharSequence obj) { return obj == null || obj.toString().length() == 0; } public static boolean isEmpty(final Collection obj) { return obj == null || obj.isEmpty(); } public static boolean isEmpty(final Map obj) { return obj == null || obj.isEmpty(); } public static boolean isEmpty(final SimpleArrayMap obj) { return obj == null || obj.isEmpty(); } public static boolean isEmpty(final SparseArray obj) { return obj == null || obj.size() == 0; } public static boolean isEmpty(final SparseBooleanArray obj) { return obj == null || obj.size() == 0; } public static boolean isEmpty(final SparseIntArray obj) { return obj == null || obj.size() == 0; } public static boolean isEmpty(final LongSparseArray obj) { return obj == null || obj.size() == 0; } @RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN_MR2) public static boolean isEmpty(final SparseLongArray obj) { return obj == null || obj.size() == 0; } @RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN) public static boolean isEmpty(final android.util.LongSparseArray obj) { return obj == null || obj.size() == 0; } /** * Return whether object is not empty. * * @param obj The object. * @return {@code true}: yes<br>{@code false}: no */ public static boolean isNotEmpty(final Object obj) { return !isEmpty(obj); } public static boolean isNotEmpty(final CharSequence obj) { return !isEmpty(obj); } public static boolean isNotEmpty(final Collection obj) { return !isEmpty(obj); } public static boolean isNotEmpty(final Map obj) { return !isEmpty(obj); } public static boolean isNotEmpty(final SimpleArrayMap obj) { return !isEmpty(obj); } public static boolean isNotEmpty(final SparseArray obj) { return !isEmpty(obj); } public static boolean isNotEmpty(final SparseBooleanArray obj) { return !isEmpty(obj); } public static boolean isNotEmpty(final SparseIntArray obj) { return !isEmpty(obj); } public static boolean isNotEmpty(final LongSparseArray obj) { return !isEmpty(obj); } @RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN_MR2) public static boolean isNotEmpty(final SparseLongArray obj) { return !isEmpty(obj); } @RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN) public static boolean isNotEmpty(final android.util.LongSparseArray obj) { return !isEmpty(obj); } /** * Return whether object1 is equals to object2. * * @param o1 The first object. * @param o2 The second object. * @return {@code true}: yes<br>{@code false}: no */ public static boolean equals(final Object o1, final Object o2) { return o1 == o2 || (o1 != null && o1.equals(o2)); } /** * Require the objects are not null. * * @param objects The object. * @throws NullPointerException if any object is null in objects */ public static void requireNonNull(final Object... objects) { if (objects == null) throw new NullPointerException(); for (Object object : objects) { if (object == null) throw new NullPointerException(); } } /** * Return the nonnull object or default object. * * @param object The object. * @param defaultObject The default object to use with the object is null. * @param <T> The value type. * @return the nonnull object or default object */ public static <T> T getOrDefault(final T object, final T defaultObject) { if (object == null) { return defaultObject; } return object; } /** * Return the hash code of object. * * @param o The object. * @return the hash code of object */ public static int hashCode(final Object o) { return o != null ? o.hashCode() : 0; } }
apache-2.0
kuali/kpme
edo/api/src/main/java/org/kuali/kpme/edo/api/dossier/EdoDossierDocumentInfo.java
8922
package org.kuali.kpme.edo.api.dossier; import java.io.Serializable; import java.util.Collection; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlAnyElement; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlRootElement; import javax.xml.bind.annotation.XmlType; import org.kuali.rice.core.api.CoreConstants; import org.kuali.rice.core.api.mo.AbstractDataTransferObject; import org.kuali.rice.core.api.mo.ModelBuilder; import org.w3c.dom.Element; @XmlRootElement(name = EdoDossierDocumentInfo.Constants.ROOT_ELEMENT_NAME) @XmlAccessorType(XmlAccessType.NONE) @XmlType(name = EdoDossierDocumentInfo.Constants.TYPE_NAME, propOrder = { EdoDossierDocumentInfo.Elements.DOCUMENT_TYPE_NAME, EdoDossierDocumentInfo.Elements.EDO_DOCUMENT_ID, EdoDossierDocumentInfo.Elements.PRINCIPAL_ID, EdoDossierDocumentInfo.Elements.DOCUMENT_STATUS, EdoDossierDocumentInfo.Elements.EDO_DOSSIER_ID, CoreConstants.CommonElements.VERSION_NUMBER, CoreConstants.CommonElements.OBJECT_ID, CoreConstants.CommonElements.FUTURE_ELEMENTS }) public final class EdoDossierDocumentInfo extends AbstractDataTransferObject implements EdoDossierDocumentInfoContract { @XmlElement(name = Elements.DOCUMENT_TYPE_NAME, required = false) private final String documentTypeName; @XmlElement(name = Elements.EDO_DOCUMENT_ID, required = false) private final String edoDocumentId; @XmlElement(name = Elements.PRINCIPAL_ID, required = false) private final String principalId; @XmlElement(name = Elements.DOCUMENT_STATUS, required = false) private final String documentStatus; @XmlElement(name = Elements.EDO_DOSSIER_ID, required = false) private final String edoDossierId; @XmlElement(name = CoreConstants.CommonElements.VERSION_NUMBER, required = false) private final Long versionNumber; @XmlElement(name = CoreConstants.CommonElements.OBJECT_ID, required = false) private final String objectId; @SuppressWarnings("unused") @XmlAnyElement private final Collection<Element> _futureElements = null; /** * Private constructor used only by JAXB. * */ private EdoDossierDocumentInfo() { this.documentTypeName = null; this.edoDocumentId = null; this.principalId = null; this.documentStatus = null; this.edoDossierId = null; this.versionNumber = null; this.objectId = null; } private EdoDossierDocumentInfo(Builder builder) { this.documentTypeName = builder.getDocumentTypeName(); this.edoDocumentId = builder.getEdoDocumentId(); this.principalId = builder.getPrincipalId(); this.documentStatus = builder.getDocumentStatus(); this.edoDossierId = builder.getEdoDossierId(); this.versionNumber = builder.getVersionNumber(); this.objectId = builder.getObjectId(); } @Override public String getDocumentTypeName() { return this.documentTypeName; } @Override public String getEdoDocumentId() { return this.edoDocumentId; } @Override public String getPrincipalId() { return this.principalId; } @Override public String getDocumentStatus() { return this.documentStatus; } @Override public String getEdoDossierId() { return this.edoDossierId; } @Override public Long getVersionNumber() { return this.versionNumber; } @Override public String getObjectId() { return this.objectId; } /** * A builder which can be used to construct {@link EdoDossierDocumentInfo} instances. Enforces the constraints of the {@link EdoDossierDocumentInfoContract}. * */ public final static class Builder implements Serializable, EdoDossierDocumentInfoContract, ModelBuilder { private String documentTypeName; private String edoDocumentId; private String principalId; private String documentStatus; private String edoDossierId; private Long versionNumber; private String objectId; private Builder() { // TODO modify this constructor as needed to pass any required values and invoke the appropriate 'setter' methods } public static Builder create() { // TODO modify as needed to pass any required values and add them to the signature of the 'create' method return new Builder(); } public static Builder create(EdoDossierDocumentInfoContract contract) { if (contract == null) { throw new IllegalArgumentException("contract was null"); } // TODO if create() is modified to accept required parameters, this will need to be modified Builder builder = create(); builder.setDocumentTypeName(contract.getDocumentTypeName()); builder.setEdoDocumentId(contract.getEdoDocumentId()); builder.setPrincipalId(contract.getPrincipalId()); builder.setDocumentStatus(contract.getDocumentStatus()); builder.setEdoDossierId(contract.getEdoDossierId()); builder.setVersionNumber(contract.getVersionNumber()); builder.setObjectId(contract.getObjectId()); return builder; } public EdoDossierDocumentInfo build() { return new EdoDossierDocumentInfo(this); } @Override public String getDocumentTypeName() { return this.documentTypeName; } @Override public String getEdoDocumentId() { return this.edoDocumentId; } @Override public String getPrincipalId() { return this.principalId; } @Override public String getDocumentStatus() { return this.documentStatus; } @Override public String getEdoDossierId() { return this.edoDossierId; } @Override public Long getVersionNumber() { return this.versionNumber; } @Override public String getObjectId() { return this.objectId; } public void setDocumentTypeName(String documentTypeName) { // TODO add validation of input value if required and throw IllegalArgumentException if needed this.documentTypeName = documentTypeName; } public void setEdoDocumentId(String edoDocumentId) { // TODO add validation of input value if required and throw IllegalArgumentException if needed this.edoDocumentId = edoDocumentId; } public void setPrincipalId(String principalId) { // TODO add validation of input value if required and throw IllegalArgumentException if needed this.principalId = principalId; } public void setDocumentStatus(String documentStatus) { // TODO add validation of input value if required and throw IllegalArgumentException if needed this.documentStatus = documentStatus; } public void setEdoDossierId(String edoDossierId) { // TODO add validation of input value if required and throw IllegalArgumentException if needed this.edoDossierId = edoDossierId; } public void setVersionNumber(Long versionNumber) { // TODO add validation of input value if required and throw IllegalArgumentException if needed this.versionNumber = versionNumber; } public void setObjectId(String objectId) { // TODO add validation of input value if required and throw IllegalArgumentException if needed this.objectId = objectId; } } /** * Defines some internal constants used on this class. * */ static class Constants { final static String ROOT_ELEMENT_NAME = "edoDossierDocumentInfo"; final static String TYPE_NAME = "EdoDossierDocumentInfoType"; } /** * A private class which exposes constants which define the XML element names to use when this object is marshalled to XML. * */ static class Elements { final static String DOCUMENT_TYPE_NAME = "documentTypeName"; final static String EDO_DOCUMENT_ID = "edoDocumentId"; final static String PRINCIPAL_ID = "principalId"; final static String DOCUMENT_STATUS = "documentStatus"; final static String EDO_DOSSIER_ID = "edoDossierId"; } }
apache-2.0
avengerpb/androiddev2017
Github_client/app/src/main/gen/com/example/sieunhan/github_client/Manifest.java
204
/*___Generated_by_IDEA___*/ package com.example.sieunhan.github_client; /* This stub is only used by the IDE. It is NOT the Manifest class actually packed into the APK */ public final class Manifest { }
apache-2.0
erichwang/presto
presto-main/src/test/java/io/prestosql/sql/gen/TestJoinCompiler.java
17474
/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.prestosql.sql.gen; import com.google.common.collect.ImmutableList; import com.google.common.primitives.Ints; import io.prestosql.block.BlockAssertions; import io.prestosql.operator.PagesHashStrategy; import io.prestosql.operator.SimplePagesHashStrategy; import io.prestosql.spi.Page; import io.prestosql.spi.PageBuilder; import io.prestosql.spi.block.Block; import io.prestosql.spi.type.Type; import io.prestosql.spi.type.TypeOperators; import io.prestosql.sql.gen.JoinCompiler.PagesHashStrategyFactory; import io.prestosql.type.BlockTypeOperators; import io.prestosql.type.BlockTypeOperators.BlockPositionEqual; import io.prestosql.type.BlockTypeOperators.BlockPositionHashCode; import io.prestosql.type.TypeTestUtils; import org.openjdk.jol.info.ClassLayout; import org.testng.annotations.DataProvider; import org.testng.annotations.Test; import java.util.List; import java.util.Optional; import java.util.OptionalInt; import static io.prestosql.block.BlockAssertions.assertBlockEquals; import static io.prestosql.operator.PageAssertions.assertPageEquals; import static io.prestosql.spi.type.BigintType.BIGINT; import static io.prestosql.spi.type.BooleanType.BOOLEAN; import static io.prestosql.spi.type.DoubleType.DOUBLE; import static io.prestosql.spi.type.VarcharType.VARCHAR; import static org.testng.Assert.assertEquals; import static org.testng.Assert.assertTrue; public class TestJoinCompiler { private static final TypeOperators typeOperators = new TypeOperators(); private static final BlockTypeOperators blockTypeOperators = new BlockTypeOperators(typeOperators); private static final JoinCompiler joinCompiler = new JoinCompiler(typeOperators); @DataProvider(name = "hashEnabledValues") public static Object[][] hashEnabledValuesProvider() { return new Object[][] {{true}, {false}}; } @Test(dataProvider = "hashEnabledValues") public void testSingleChannel(boolean hashEnabled) { List<Type> joinTypes = ImmutableList.of(VARCHAR); List<Integer> joinChannels = Ints.asList(0); // compile a single channel hash strategy PagesHashStrategyFactory pagesHashStrategyFactory = joinCompiler.compilePagesHashStrategyFactory(joinTypes, joinChannels); // create hash strategy with a single channel blocks -- make sure there is some overlap in values List<Block> channel = ImmutableList.of( BlockAssertions.createStringSequenceBlock(10, 20), BlockAssertions.createStringSequenceBlock(20, 30), BlockAssertions.createStringSequenceBlock(15, 25)); OptionalInt hashChannel = OptionalInt.empty(); List<List<Block>> channels = ImmutableList.of(channel); if (hashEnabled) { ImmutableList.Builder<Block> hashChannelBuilder = ImmutableList.builder(); for (Block block : channel) { hashChannelBuilder.add(TypeTestUtils.getHashBlock(joinTypes, block)); } hashChannel = OptionalInt.of(1); channels = ImmutableList.of(channel, hashChannelBuilder.build()); } PagesHashStrategy hashStrategy = pagesHashStrategyFactory.createPagesHashStrategy(channels, hashChannel); // verify channel count assertEquals(hashStrategy.getChannelCount(), 1); BlockTypeOperators blockTypeOperators = new BlockTypeOperators(); BlockPositionEqual equalOperator = blockTypeOperators.getEqualOperator(VARCHAR); BlockPositionHashCode hashCodeOperator = blockTypeOperators.getHashCodeOperator(VARCHAR); // verify hashStrategy is consistent with equals and hash code from block for (int leftBlockIndex = 0; leftBlockIndex < channel.size(); leftBlockIndex++) { Block leftBlock = channel.get(leftBlockIndex); PageBuilder pageBuilder = new PageBuilder(ImmutableList.of(VARCHAR)); for (int leftBlockPosition = 0; leftBlockPosition < leftBlock.getPositionCount(); leftBlockPosition++) { // hash code of position must match block hash assertEquals(hashStrategy.hashPosition(leftBlockIndex, leftBlockPosition), hashCodeOperator.hashCodeNullSafe(leftBlock, leftBlockPosition)); // position must be equal to itself assertTrue(hashStrategy.positionEqualsPositionIgnoreNulls(leftBlockIndex, leftBlockPosition, leftBlockIndex, leftBlockPosition)); // check equality of every position against every other position in the block for (int rightBlockIndex = 0; rightBlockIndex < channel.size(); rightBlockIndex++) { Block rightBlock = channel.get(rightBlockIndex); for (int rightBlockPosition = 0; rightBlockPosition < rightBlock.getPositionCount(); rightBlockPosition++) { boolean expected = equalOperator.equalNullSafe(leftBlock, leftBlockPosition, rightBlock, rightBlockPosition); assertEquals(hashStrategy.positionEqualsRow(leftBlockIndex, leftBlockPosition, rightBlockPosition, new Page(rightBlock)), expected); assertEquals(hashStrategy.rowEqualsRow(leftBlockPosition, new Page(leftBlock), rightBlockPosition, new Page(rightBlock)), expected); assertEquals(hashStrategy.positionEqualsRowIgnoreNulls(leftBlockIndex, leftBlockPosition, rightBlockPosition, new Page(rightBlock)), expected); assertEquals(hashStrategy.positionEqualsPositionIgnoreNulls(leftBlockIndex, leftBlockPosition, rightBlockIndex, rightBlockPosition), expected); assertEquals(hashStrategy.positionEqualsPosition(leftBlockIndex, leftBlockPosition, rightBlockIndex, rightBlockPosition), expected); } } // check equality of every position against every other position in the block cursor for (int rightBlockIndex = 0; rightBlockIndex < channel.size(); rightBlockIndex++) { Block rightBlock = channel.get(rightBlockIndex); for (int rightBlockPosition = 0; rightBlockPosition < rightBlock.getPositionCount(); rightBlockPosition++) { boolean expected = equalOperator.equalNullSafe(leftBlock, leftBlockPosition, rightBlock, rightBlockPosition); assertEquals(hashStrategy.positionEqualsRow(leftBlockIndex, leftBlockPosition, rightBlockPosition, new Page(rightBlock)), expected); assertEquals(hashStrategy.rowEqualsRow(leftBlockPosition, new Page(leftBlock), rightBlockPosition, new Page(rightBlock)), expected); assertEquals(hashStrategy.positionEqualsRowIgnoreNulls(leftBlockIndex, leftBlockPosition, rightBlockPosition, new Page(rightBlock)), expected); assertEquals(hashStrategy.positionEqualsPositionIgnoreNulls(leftBlockIndex, leftBlockPosition, rightBlockIndex, rightBlockPosition), expected); assertEquals(hashStrategy.positionEqualsPosition(leftBlockIndex, leftBlockPosition, rightBlockIndex, rightBlockPosition), expected); } } // write position to output block pageBuilder.declarePosition(); hashStrategy.appendTo(leftBlockIndex, leftBlockPosition, pageBuilder, 0); } // verify output block matches assertBlockEquals(VARCHAR, pageBuilder.build().getBlock(0), leftBlock); } } @Test(dataProvider = "hashEnabledValues") public void testMultiChannel(boolean hashEnabled) { // compile a single channel hash strategy List<Type> types = ImmutableList.of(VARCHAR, VARCHAR, BIGINT, DOUBLE, BOOLEAN, VARCHAR); List<Type> joinTypes = ImmutableList.of(VARCHAR, BIGINT, DOUBLE, BOOLEAN); List<Type> outputTypes = ImmutableList.of(VARCHAR, BIGINT, DOUBLE, BOOLEAN, VARCHAR); List<Integer> joinChannels = Ints.asList(1, 2, 3, 4); List<Integer> outputChannels = Ints.asList(1, 2, 3, 4, 0); // crate hash strategy with a single channel blocks -- make sure there is some overlap in values List<Block> extraChannel = ImmutableList.of( BlockAssertions.createStringSequenceBlock(10, 20), BlockAssertions.createStringSequenceBlock(20, 30), BlockAssertions.createStringSequenceBlock(15, 25)); List<Block> varcharChannel = ImmutableList.of( BlockAssertions.createStringSequenceBlock(10, 20), BlockAssertions.createStringSequenceBlock(20, 30), BlockAssertions.createStringSequenceBlock(15, 25)); List<Block> longChannel = ImmutableList.of( BlockAssertions.createLongSequenceBlock(10, 20), BlockAssertions.createLongSequenceBlock(20, 30), BlockAssertions.createLongSequenceBlock(15, 25)); List<Block> doubleChannel = ImmutableList.of( BlockAssertions.createDoubleSequenceBlock(10, 20), BlockAssertions.createDoubleSequenceBlock(20, 30), BlockAssertions.createDoubleSequenceBlock(15, 25)); List<Block> booleanChannel = ImmutableList.of( BlockAssertions.createBooleanSequenceBlock(10, 20), BlockAssertions.createBooleanSequenceBlock(20, 30), BlockAssertions.createBooleanSequenceBlock(15, 25)); List<Block> extraUnusedChannel = ImmutableList.of( BlockAssertions.createBooleanSequenceBlock(10, 20), BlockAssertions.createBooleanSequenceBlock(20, 30), BlockAssertions.createBooleanSequenceBlock(15, 25)); OptionalInt hashChannel = OptionalInt.empty(); ImmutableList<List<Block>> channels = ImmutableList.of(extraChannel, varcharChannel, longChannel, doubleChannel, booleanChannel, extraUnusedChannel); List<Block> precomputedHash = ImmutableList.of(); if (hashEnabled) { ImmutableList.Builder<Block> hashChannelBuilder = ImmutableList.builder(); for (int i = 0; i < 3; i++) { hashChannelBuilder.add(TypeTestUtils.getHashBlock(joinTypes, varcharChannel.get(i), longChannel.get(i), doubleChannel.get(i), booleanChannel.get(i))); } hashChannel = OptionalInt.of(6); precomputedHash = hashChannelBuilder.build(); channels = ImmutableList.of(extraChannel, varcharChannel, longChannel, doubleChannel, booleanChannel, extraUnusedChannel, precomputedHash); types = ImmutableList.of(VARCHAR, VARCHAR, BIGINT, DOUBLE, BOOLEAN, VARCHAR, BIGINT); outputTypes = ImmutableList.of(VARCHAR, BIGINT, DOUBLE, BOOLEAN, VARCHAR, BIGINT); outputChannels = Ints.asList(1, 2, 3, 4, 0, 6); } PagesHashStrategyFactory pagesHashStrategyFactory = joinCompiler.compilePagesHashStrategyFactory(types, joinChannels, Optional.of(outputChannels)); PagesHashStrategy hashStrategy = pagesHashStrategyFactory.createPagesHashStrategy(channels, hashChannel); // todo add tests for filter function PagesHashStrategy expectedHashStrategy = new SimplePagesHashStrategy(types, outputChannels, channels, joinChannels, hashChannel, Optional.empty(), blockTypeOperators); // verify channel count assertEquals(hashStrategy.getChannelCount(), outputChannels.size()); // verify size int instanceSize = ClassLayout.parseClass(hashStrategy.getClass()).instanceSize(); long sizeInBytes = instanceSize + channels.stream() .flatMap(List::stream) .mapToLong(Block::getRetainedSizeInBytes) .sum(); assertEquals(hashStrategy.getSizeInBytes(), sizeInBytes); // verify hashStrategy is consistent with equals and hash code from block for (int leftBlockIndex = 0; leftBlockIndex < varcharChannel.size(); leftBlockIndex++) { PageBuilder pageBuilder = new PageBuilder(outputTypes); Block[] leftBlocks = new Block[4]; leftBlocks[0] = varcharChannel.get(leftBlockIndex); leftBlocks[1] = longChannel.get(leftBlockIndex); leftBlocks[2] = doubleChannel.get(leftBlockIndex); leftBlocks[3] = booleanChannel.get(leftBlockIndex); int leftPositionCount = varcharChannel.get(leftBlockIndex).getPositionCount(); for (int leftBlockPosition = 0; leftBlockPosition < leftPositionCount; leftBlockPosition++) { // hash code of position must match block hash assertEquals( hashStrategy.hashPosition(leftBlockIndex, leftBlockPosition), expectedHashStrategy.hashPosition(leftBlockIndex, leftBlockPosition)); // position must be equal to itself assertTrue(hashStrategy.positionEqualsPositionIgnoreNulls(leftBlockIndex, leftBlockPosition, leftBlockIndex, leftBlockPosition)); assertTrue(hashStrategy.positionEqualsPosition(leftBlockIndex, leftBlockPosition, leftBlockIndex, leftBlockPosition)); // check equality of every position against every other position in the block for (int rightBlockIndex = 0; rightBlockIndex < varcharChannel.size(); rightBlockIndex++) { Block rightBlock = varcharChannel.get(rightBlockIndex); for (int rightBlockPosition = 0; rightBlockPosition < rightBlock.getPositionCount(); rightBlockPosition++) { assertEquals( hashStrategy.positionEqualsPositionIgnoreNulls(leftBlockIndex, leftBlockPosition, rightBlockIndex, rightBlockPosition), expectedHashStrategy.positionEqualsPositionIgnoreNulls(leftBlockIndex, leftBlockPosition, rightBlockIndex, rightBlockPosition)); assertEquals( hashStrategy.positionEqualsPosition(leftBlockIndex, leftBlockPosition, rightBlockIndex, rightBlockPosition), expectedHashStrategy.positionEqualsPosition(leftBlockIndex, leftBlockPosition, rightBlockIndex, rightBlockPosition)); } } // check equality of every position against every other position in the block cursor for (int rightBlockIndex = 0; rightBlockIndex < varcharChannel.size(); rightBlockIndex++) { Block[] rightBlocks = new Block[4]; rightBlocks[0] = varcharChannel.get(rightBlockIndex); rightBlocks[1] = longChannel.get(rightBlockIndex); rightBlocks[2] = doubleChannel.get(rightBlockIndex); rightBlocks[3] = booleanChannel.get(rightBlockIndex); int rightPositionCount = varcharChannel.get(rightBlockIndex).getPositionCount(); for (int rightPosition = 0; rightPosition < rightPositionCount; rightPosition++) { boolean expected = expectedHashStrategy.positionEqualsRow(leftBlockIndex, leftBlockPosition, rightPosition, new Page(rightBlocks)); assertEquals(hashStrategy.positionEqualsRow(leftBlockIndex, leftBlockPosition, rightPosition, new Page(rightBlocks)), expected); assertEquals(hashStrategy.rowEqualsRow(leftBlockPosition, new Page(leftBlocks), rightPosition, new Page(rightBlocks)), expected); assertEquals(hashStrategy.positionEqualsRowIgnoreNulls(leftBlockIndex, leftBlockPosition, rightPosition, new Page(rightBlocks)), expected); } } // write position to output block pageBuilder.declarePosition(); hashStrategy.appendTo(leftBlockIndex, leftBlockPosition, pageBuilder, 0); } // verify output block matches Page page = pageBuilder.build(); if (hashEnabled) { assertPageEquals(outputTypes, page, new Page( varcharChannel.get(leftBlockIndex), longChannel.get(leftBlockIndex), doubleChannel.get(leftBlockIndex), booleanChannel.get(leftBlockIndex), extraChannel.get(leftBlockIndex), precomputedHash.get(leftBlockIndex))); } else { assertPageEquals(outputTypes, page, new Page( varcharChannel.get(leftBlockIndex), longChannel.get(leftBlockIndex), doubleChannel.get(leftBlockIndex), booleanChannel.get(leftBlockIndex), extraChannel.get(leftBlockIndex))); } } } }
apache-2.0
gdtlf/msg
msg-admin/src/main/java/com/tlf/msg/admin/web/search/AppSearch.java
1376
package com.tlf.msg.admin.web.search; import org.apache.commons.lang3.StringUtils; import com.tlf.msg.admin.base.Enums; import com.tlf.msg.admin.base.Search; public class AppSearch extends Search { private String appName;// 名称 private String appCode;// 代码 private String status;// 状态 public String getStatus() { return status; } public void setStatus(String status) { this.status = status; } public String getStatusRule() { if (StringUtils.isBlank(getStatus())) { return null; } return "status" + "|" + Enums.Operator.EQ.getCode() + "|" + getStatus(); } public String getAppName() { return appName; } public void setAppName(String appName) { this.appName = appName; } public String getNameRule() { if (StringUtils.isBlank(getAppName())) { return null; } return "appName" + "|" + Enums.Operator.CN.getCode() + "|" + getAppName(); } public String getAppCode() { return appCode; } public void setAppCode(String appCode) { this.appCode = appCode; } public String getCodeRule() { if (StringUtils.isBlank(getAppCode())) { return null; } return "appCode" + "|" + Enums.Operator.CN.getCode() + "|" + getAppCode(); } }
apache-2.0
sjaco002/incubator-asterixdb
asterix-runtime/src/main/java/edu/uci/ics/asterix/runtime/evaluators/accessors/TemporalIntervalStartAccessor.java
7287
/* * Copyright 2009-2013 by The Regents of the University of California * 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 from * * 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 edu.uci.ics.asterix.runtime.evaluators.accessors; import java.io.DataOutput; import java.io.IOException; import edu.uci.ics.asterix.dataflow.data.nontagged.serde.AIntervalSerializerDeserializer; import edu.uci.ics.asterix.formats.nontagged.AqlSerializerDeserializerProvider; import edu.uci.ics.asterix.om.base.ADate; import edu.uci.ics.asterix.om.base.ADateTime; import edu.uci.ics.asterix.om.base.AMutableDate; import edu.uci.ics.asterix.om.base.AMutableDateTime; import edu.uci.ics.asterix.om.base.AMutableTime; import edu.uci.ics.asterix.om.base.ANull; import edu.uci.ics.asterix.om.base.ATime; import edu.uci.ics.asterix.om.functions.AsterixBuiltinFunctions; import edu.uci.ics.asterix.om.functions.IFunctionDescriptor; import edu.uci.ics.asterix.om.functions.IFunctionDescriptorFactory; import edu.uci.ics.asterix.om.types.ATypeTag; import edu.uci.ics.asterix.om.types.BuiltinType; import edu.uci.ics.asterix.om.types.EnumDeserializer; import edu.uci.ics.asterix.runtime.evaluators.base.AbstractScalarFunctionDynamicDescriptor; import edu.uci.ics.hyracks.algebricks.common.exceptions.AlgebricksException; import edu.uci.ics.hyracks.algebricks.core.algebra.functions.FunctionIdentifier; import edu.uci.ics.hyracks.algebricks.runtime.base.ICopyEvaluator; import edu.uci.ics.hyracks.algebricks.runtime.base.ICopyEvaluatorFactory; import edu.uci.ics.hyracks.api.dataflow.value.ISerializerDeserializer; import edu.uci.ics.hyracks.data.std.api.IDataOutputProvider; import edu.uci.ics.hyracks.data.std.util.ArrayBackedValueStorage; import edu.uci.ics.hyracks.dataflow.common.data.accessors.IFrameTupleReference; public class TemporalIntervalStartAccessor extends AbstractScalarFunctionDynamicDescriptor { private static final long serialVersionUID = 1L; private static final FunctionIdentifier FID = AsterixBuiltinFunctions.ACCESSOR_TEMPORAL_INTERVAL_START; private static final byte SER_INTERVAL_TYPE_TAG = ATypeTag.INTERVAL.serialize(); private static final byte SER_NULL_TYPE_TAG = ATypeTag.NULL.serialize(); private static final byte SER_DATE_TYPE_TAG = ATypeTag.DATE.serialize(); private static final byte SER_TIME_TYPE_TAG = ATypeTag.TIME.serialize(); private static final byte SER_DATETIME_TYPE_TAG = ATypeTag.DATETIME.serialize(); public static final IFunctionDescriptorFactory FACTORY = new IFunctionDescriptorFactory() { @Override public IFunctionDescriptor createFunctionDescriptor() { return new TemporalIntervalStartAccessor(); } }; public ICopyEvaluatorFactory createEvaluatorFactory(final ICopyEvaluatorFactory[] args) throws AlgebricksException { return new ICopyEvaluatorFactory() { private static final long serialVersionUID = 1L; @Override public ICopyEvaluator createEvaluator(final IDataOutputProvider output) throws AlgebricksException { return new ICopyEvaluator() { private final DataOutput out = output.getDataOutput(); private final ArrayBackedValueStorage argOut = new ArrayBackedValueStorage(); private final ICopyEvaluator eval = args[0].createEvaluator(argOut); // possible output @SuppressWarnings("unchecked") private final ISerializerDeserializer<ADate> dateSerde = AqlSerializerDeserializerProvider.INSTANCE .getSerializerDeserializer(BuiltinType.ADATE); private final AMutableDate aDate = new AMutableDate(0); @SuppressWarnings("unchecked") private final ISerializerDeserializer<ADateTime> datetimeSerde = AqlSerializerDeserializerProvider.INSTANCE .getSerializerDeserializer(BuiltinType.ADATETIME); private final AMutableDateTime aDateTime = new AMutableDateTime(0); @SuppressWarnings("unchecked") private final ISerializerDeserializer<ATime> timeSerde = AqlSerializerDeserializerProvider.INSTANCE .getSerializerDeserializer(BuiltinType.ATIME); private final AMutableTime aTime = new AMutableTime(0); @SuppressWarnings("unchecked") private final ISerializerDeserializer<ANull> nullSerde = AqlSerializerDeserializerProvider.INSTANCE .getSerializerDeserializer(BuiltinType.ANULL); @Override public void evaluate(IFrameTupleReference tuple) throws AlgebricksException { argOut.reset(); eval.evaluate(tuple); byte[] bytes = argOut.getByteArray(); try { if (bytes[0] == SER_NULL_TYPE_TAG) { nullSerde.serialize(ANull.NULL, out); return; } else if (bytes[0] == SER_INTERVAL_TYPE_TAG) { byte timeType = AIntervalSerializerDeserializer.getIntervalTimeType(bytes, 1); long startTime = AIntervalSerializerDeserializer.getIntervalStart(bytes, 1); if (timeType == SER_DATE_TYPE_TAG) { aDate.setValue((int) (startTime)); dateSerde.serialize(aDate, out); } else if (timeType == SER_TIME_TYPE_TAG) { aTime.setValue((int) (startTime)); timeSerde.serialize(aTime, out); } else if (timeType == SER_DATETIME_TYPE_TAG) { aDateTime.setValue(startTime); datetimeSerde.serialize(aDateTime, out); } } else { throw new AlgebricksException(FID.getName() + ": expects NULL/INTERVAL, but got " + EnumDeserializer.ATYPETAGDESERIALIZER.deserialize(bytes[0])); } } catch (IOException e) { throw new AlgebricksException(e); } } }; } }; } /* (non-Javadoc) * @see edu.uci.ics.asterix.om.functions.AbstractFunctionDescriptor#getIdentifier() */ @Override public FunctionIdentifier getIdentifier() { return FID; } }
apache-2.0
stephraleigh/flowable-engine
modules/flowable5-engine/src/main/java/org/activiti/engine/impl/bpmn/behavior/BpmnActivityBehavior.java
8959
/* 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.activiti.engine.impl.bpmn.behavior; import java.io.Serializable; import java.util.ArrayList; import java.util.Collections; import java.util.List; import org.activiti.engine.ActivitiException; import org.activiti.engine.delegate.event.impl.ActivitiEventBuilder; import org.activiti.engine.impl.Condition; import org.activiti.engine.impl.bpmn.helper.SkipExpressionUtil; import org.activiti.engine.impl.bpmn.parser.BpmnParse; import org.activiti.engine.impl.context.Context; import org.activiti.engine.impl.persistence.entity.ExecutionEntity; import org.activiti.engine.impl.persistence.entity.JobEntity; import org.activiti.engine.impl.persistence.entity.TimerJobEntity; import org.activiti.engine.impl.pvm.PvmTransition; import org.activiti.engine.impl.pvm.delegate.ActivityExecution; import org.activiti.engine.impl.pvm.process.ActivityImpl; import org.activiti.engine.impl.pvm.runtime.InterpretableExecution; import org.flowable.engine.delegate.Expression; import org.flowable.engine.delegate.event.FlowableEngineEventType; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * Helper class for implementing BPMN 2.0 activities, offering convenience methods specific to BPMN 2.0. * * This class can be used by inheritance or aggregation. * * @author Joram Barrez */ public class BpmnActivityBehavior implements Serializable { private static final long serialVersionUID = 1L; private static final Logger LOGGER = LoggerFactory.getLogger(BpmnActivityBehavior.class); /** * Performs the default outgoing BPMN 2.0 behavior, which is having parallel paths of executions for the outgoing sequence flow. * * More precisely: every sequence flow that has a condition which evaluates to true (or which doesn't have a condition), is selected for continuation of the process instance. If multiple sequencer * flow are selected, multiple, parallel paths of executions are created. */ public void performDefaultOutgoingBehavior(ActivityExecution activityExecution) { ActivityImpl activity = (ActivityImpl) activityExecution.getActivity(); if (!(activity.getActivityBehavior() instanceof IntermediateCatchEventActivityBehavior)) { dispatchJobCanceledEvents(activityExecution); } performOutgoingBehavior(activityExecution, true, false, null); } /** * Performs the default outgoing BPMN 2.0 behavior (@see {@link #performDefaultOutgoingBehavior(ActivityExecution)}), but without checking the conditions on the outgoing sequence flow. * * This means that every outgoing sequence flow is selected for continuing the process instance, regardless of having a condition or not. In case of multiple outgoing sequence flow, multiple * parallel paths of executions will be created. */ public void performIgnoreConditionsOutgoingBehavior(ActivityExecution activityExecution) { performOutgoingBehavior(activityExecution, false, false, null); } /** * dispatch job canceled event for job associated with given execution entity * * @param activityExecution */ protected void dispatchJobCanceledEvents(ActivityExecution activityExecution) { if (activityExecution instanceof ExecutionEntity) { List<JobEntity> jobs = ((ExecutionEntity) activityExecution).getJobs(); for (JobEntity job : jobs) { if (Context.getProcessEngineConfiguration().getEventDispatcher().isEnabled()) { Context.getProcessEngineConfiguration().getEventDispatcher().dispatchEvent( ActivitiEventBuilder.createEntityEvent(FlowableEngineEventType.JOB_CANCELED, job)); } } List<TimerJobEntity> timerJobs = ((ExecutionEntity) activityExecution).getTimerJobs(); for (TimerJobEntity job : timerJobs) { if (Context.getProcessEngineConfiguration().getEventDispatcher().isEnabled()) { Context.getProcessEngineConfiguration().getEventDispatcher().dispatchEvent(ActivitiEventBuilder.createEntityEvent(FlowableEngineEventType.JOB_CANCELED, job)); } } } } /** * Actual implementation of leaving an activity. * * @param execution * The current execution context * @param checkConditions * Whether or not to check conditions before determining whether or not to take a transition. * @param throwExceptionIfExecutionStuck * If true, an {@link ActivitiException} will be thrown in case no transition could be found to leave the activity. */ protected void performOutgoingBehavior(ActivityExecution execution, boolean checkConditions, boolean throwExceptionIfExecutionStuck, List<ActivityExecution> reusableExecutions) { if (LOGGER.isDebugEnabled()) { LOGGER.debug("Leaving activity '{}'", execution.getActivity().getId()); } String defaultSequenceFlow = (String) execution.getActivity().getProperty("default"); List<PvmTransition> transitionsToTake = new ArrayList<PvmTransition>(); List<PvmTransition> outgoingTransitions = execution.getActivity().getOutgoingTransitions(); for (PvmTransition outgoingTransition : outgoingTransitions) { Expression skipExpression = outgoingTransition.getSkipExpression(); if (!SkipExpressionUtil.isSkipExpressionEnabled(execution, skipExpression)) { if (defaultSequenceFlow == null || !outgoingTransition.getId().equals(defaultSequenceFlow)) { Condition condition = (Condition) outgoingTransition.getProperty(BpmnParse.PROPERTYNAME_CONDITION); if (condition == null || !checkConditions || condition.evaluate(outgoingTransition.getId(), execution)) { transitionsToTake.add(outgoingTransition); } } } else if (SkipExpressionUtil.shouldSkipFlowElement(execution, skipExpression)) { transitionsToTake.add(outgoingTransition); } } if (transitionsToTake.size() == 1) { execution.take(transitionsToTake.get(0)); } else if (transitionsToTake.size() >= 1) { execution.inactivate(); if (reusableExecutions == null || reusableExecutions.isEmpty()) { execution.takeAll(transitionsToTake, Collections.singletonList(execution)); } else { execution.takeAll(transitionsToTake, reusableExecutions); } } else { if (defaultSequenceFlow != null) { PvmTransition defaultTransition = execution.getActivity().findOutgoingTransition(defaultSequenceFlow); if (defaultTransition != null) { execution.take(defaultTransition); } else { throw new ActivitiException("Default sequence flow '" + defaultSequenceFlow + "' could not be not found"); } } else { Object isForCompensation = execution.getActivity().getProperty(BpmnParse.PROPERTYNAME_IS_FOR_COMPENSATION); if (isForCompensation != null && (Boolean) isForCompensation) { if (execution instanceof ExecutionEntity) { Context.getCommandContext().getHistoryManager().recordActivityEnd((ExecutionEntity) execution); } InterpretableExecution parentExecution = (InterpretableExecution) execution.getParent(); ((InterpretableExecution) execution).remove(); parentExecution.signal("compensationDone", null); } else { if (LOGGER.isDebugEnabled()) { LOGGER.debug("No outgoing sequence flow found for {}. Ending execution.", execution.getActivity().getId()); } execution.end(); if (throwExceptionIfExecutionStuck) { throw new ActivitiException("No outgoing sequence flow of the inclusive gateway '" + execution.getActivity().getId() + "' could be selected for continuing the process"); } } } } } }
apache-2.0
signed/intellij-community
platform/platform-impl/src/com/intellij/openapi/progress/util/AbstractProgressIndicatorExBase.java
7348
/* * Copyright 2000-2014 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.intellij.openapi.progress.util; import com.intellij.openapi.application.*; import com.intellij.openapi.application.impl.LaterInvocator; import com.intellij.openapi.diagnostic.Logger; import com.intellij.openapi.progress.ProgressIndicator; import com.intellij.openapi.progress.TaskInfo; import com.intellij.openapi.wm.ex.ProgressIndicatorEx; import com.intellij.ui.GuiUtils; import com.intellij.util.containers.ContainerUtil; import com.intellij.util.containers.WeakList; import org.jetbrains.annotations.NotNull; import java.util.List; public class AbstractProgressIndicatorExBase extends AbstractProgressIndicatorBase implements ProgressIndicatorEx { private static final Logger LOG = Logger.getInstance("#com.intellij.openapi.progress.util.ProgressIndicatorBase"); private final boolean myReusable; private volatile boolean myModalityEntered; private volatile List<ProgressIndicatorEx> myStateDelegates; private volatile WeakList<TaskInfo> myFinished; private volatile boolean myWasStarted; private TaskInfo myOwnerTask; public AbstractProgressIndicatorExBase(boolean reusable) { myReusable = reusable; } public AbstractProgressIndicatorExBase() { this(false); } @Override public void start() { synchronized (this) { super.start(); delegateRunningChange(ProgressIndicator::start); } myWasStarted = true; enterModality(); } protected final void enterModality() { if (myModalityProgress == this) { ModalityState modalityState = ModalityState.defaultModalityState(); if (!myModalityEntered && !ApplicationManager.getApplication().isDispatchThread() && !((TransactionGuardImpl)TransactionGuard.getInstance()).isWriteSafeModality(modalityState)) { // exceptions here should be assigned to Peter LOG.error("Non-modal progress should be started in a write-safe context: an action or modality-aware invokeLater. See also TransactionGuard documentation."); } GuiUtils.invokeLaterIfNeeded(this::doEnterModality, modalityState); } } private void doEnterModality() { if (!myModalityEntered) { LaterInvocator.enterModal(this); myModalityEntered = true; } } @Override public void stop() { super.stop(); delegateRunningChange(ProgressIndicator::stop); exitModality(); } protected final void exitModality() { if (myModalityProgress == this) { GuiUtils.invokeLaterIfNeeded(this::doExitModality, ModalityState.defaultModalityState()); } } private void doExitModality() { if (myModalityEntered) { myModalityEntered = false; LaterInvocator.leaveModal(this); } } @Override public void cancel() { super.cancel(); delegateRunningChange(ProgressIndicator::cancel); } @Override public void finish(@NotNull final TaskInfo task) { WeakList<TaskInfo> finished = myFinished; if (finished == null) { synchronized (this) { finished = myFinished; if (finished == null) { myFinished = finished = new WeakList<>(); } } } if (!finished.addIfAbsent(task)) return; delegateRunningChange(each -> each.finish(task)); } @Override public boolean isFinished(@NotNull final TaskInfo task) { List<TaskInfo> list = myFinished; return list != null && list.contains(task); } protected void setOwnerTask(TaskInfo owner) { myOwnerTask = owner; } @Override public void processFinish() { if (myOwnerTask != null) { finish(myOwnerTask); myOwnerTask = null; } } @Override public final void checkCanceled() { super.checkCanceled(); delegate(ProgressIndicator::checkCanceled); } @Override public void setText(final String text) { super.setText(text); delegateProgressChange(each -> each.setText(text)); } @Override public void setText2(final String text) { super.setText2(text); delegateProgressChange(each -> each.setText2(text)); } @Override public void setFraction(final double fraction) { super.setFraction(fraction); delegateProgressChange(each -> each.setFraction(fraction)); } @Override public synchronized void pushState() { super.pushState(); delegateProgressChange(ProgressIndicator::pushState); } @Override public synchronized void popState() { super.popState(); delegateProgressChange(ProgressIndicator::popState); } @Override public void startNonCancelableSection() { super.startNonCancelableSection(); delegateProgressChange(ProgressIndicator::startNonCancelableSection); } @Override public void finishNonCancelableSection() { super.finishNonCancelableSection(); delegateProgressChange(ProgressIndicator::finishNonCancelableSection); } @Override protected boolean isReuseable() { return myReusable; } @Override public void setIndeterminate(final boolean indeterminate) { super.setIndeterminate(indeterminate); delegateProgressChange(each -> each.setIndeterminate(indeterminate)); } @Override public final void addStateDelegate(@NotNull ProgressIndicatorEx delegate) { delegate.initStateFrom(this); synchronized (this) { List<ProgressIndicatorEx> stateDelegates = myStateDelegates; if (stateDelegates == null) { myStateDelegates = stateDelegates = ContainerUtil.createLockFreeCopyOnWriteList(); } else { LOG.assertTrue(!stateDelegates.contains(delegate), "Already registered: " + delegate); } stateDelegates.add(delegate); } } protected void delegateProgressChange(@NotNull IndicatorAction action) { delegate(action); onProgressChange(); } protected void delegateRunningChange(@NotNull IndicatorAction action) { delegate(action); onRunningChange(); } private void delegate(@NotNull IndicatorAction action) { List<ProgressIndicatorEx> list = myStateDelegates; if (list != null && !list.isEmpty()) { for (ProgressIndicatorEx each : list) { action.execute(each); } } } protected void onProgressChange() { } protected void onRunningChange() { } @Override public boolean isModalityEntered() { return myModalityEntered; } @Override public synchronized void initStateFrom(@NotNull final ProgressIndicator indicator) { super.initStateFrom(indicator); if (indicator instanceof ProgressIndicatorEx) { myModalityEntered = ((ProgressIndicatorEx)indicator).isModalityEntered(); } } @Override public boolean wasStarted() { return myWasStarted; } @FunctionalInterface protected interface IndicatorAction { void execute(@NotNull ProgressIndicatorEx each); } }
apache-2.0
rfoltyns/log4j2-elasticsearch
log4j2-elasticsearch-hc/src/test/java/org/appenders/log4j2/elasticsearch/hc/ByteBufHttpEntityTest.java
4535
package org.appenders.log4j2.elasticsearch.hc; /*- * #%L * log4j2-elasticsearch * %% * Copyright (C) 2019 Rafal Foltynski * %% * 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 io.netty.buffer.ByteBuf; import io.netty.buffer.CompositeByteBuf; import org.apache.http.Header; import org.apache.http.entity.ContentType; import org.junit.jupiter.api.Test; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; import java.util.Random; import static org.appenders.log4j2.elasticsearch.GenericItemSourcePoolTest.byteBufAllocator; import static org.hamcrest.CoreMatchers.containsString; import static org.hamcrest.MatcherAssert.assertThat; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertNull; import static org.junit.jupiter.api.Assertions.assertThrows; import static org.junit.jupiter.api.Assertions.assertTrue; import static org.mockito.ArgumentMatchers.eq; import static org.mockito.Mockito.spy; import static org.mockito.Mockito.verify; public class ByteBufHttpEntityTest { static { System.setProperty("io.netty.allocator.maxOrder", "1"); } @Test public void writeToOutputStreamIsNotSupported() { // given ByteBufHttpEntity entity = new ByteBufHttpEntity(createDefaultTestByteBuf(), 0, null); // when final UnsupportedOperationException exception = assertThrows(UnsupportedOperationException.class, () -> entity.writeTo(new ByteArrayOutputStream())); // then assertThat(exception.getMessage(), containsString("writeTo(OutputStream) is not supported. Use getContent() to get InputStream instead")); } @Test public void isRepeatable() { // given ByteBufHttpEntity entity = new ByteBufHttpEntity(createDefaultTestByteBuf(), 0, null); // when boolean result = entity.isRepeatable(); // then assertTrue(result); } @Test public void isNotStreaming() { // given ByteBufHttpEntity entity = new ByteBufHttpEntity(createDefaultTestByteBuf(), 0, null); // when boolean result = entity.isStreaming(); // then assertFalse(result); } @Test public void setsContentLength() { // given long expectedContentLength = new Random().nextInt(1000); ByteBufHttpEntity entity = new ByteBufHttpEntity(createDefaultTestByteBuf(), expectedContentLength, null); // when long contentLength = entity.getContentLength(); // then assertEquals(expectedContentLength, contentLength); } @Test public void setsContentTypeIfNotNull() { // given ContentType expectedContentType = ContentType.APPLICATION_JSON; ByteBufHttpEntity entity = new ByteBufHttpEntity(createDefaultTestByteBuf(), 0, expectedContentType); // when Header contentType = entity.getContentType(); // then assertEquals(expectedContentType.toString(), contentType.getValue()); } @Test public void doesntSetContentTypeIfNull() { // given ByteBufHttpEntity entity = new ByteBufHttpEntity(createDefaultTestByteBuf(), 0, null); // when Header contentType = entity.getContentType(); // then assertNull(contentType); } @Test public void getContentReturnsInputStreamThatResetsByteBufReaderIndexOnClose() throws IOException { // given ByteBuf byteBuf = spy(createDefaultTestByteBuf()); ByteBufHttpEntity entity = new ByteBufHttpEntity(byteBuf, 0, null); InputStream inputStream = entity.getContent(); // when inputStream.close(); // then verify(byteBuf).readerIndex(eq(0)); } private CompositeByteBuf createDefaultTestByteBuf() { return new CompositeByteBuf(byteBufAllocator, false, 2); } }
apache-2.0
ToxicAvenger/AndroidCarValue
CarValueCommon/src/pl/mobilnebajery/carvalue/common/CarMakesInfoBinarySerializer.java
2722
package pl.mobilnebajery.carvalue.common; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.io.ObjectStreamClass; import java.io.OutputStream; import java.util.List; import pl.mobilnebajery.carvalue.common.serializable.CarMakeInfo; import pl.mobilnebajery.carvalue.common.serializable.CarMakesInfoList; import pl.mobilnebajery.carvalue.common.serializable.CarModelInfo; import pl.mobilnebajery.carvalue.common.serializable.CarPrice; public class CarMakesInfoBinarySerializer implements ICarMakesInfoSerializer { public void serialize(List<CarMakeInfo> carInfos, String fileName) throws Exception { FileOutputStream flotpt = new FileOutputStream(fileName); // creation a "Flow object " with the flow file ObjectOutputStream objstr= new ObjectOutputStream(flotpt); CarMakesInfoList list = new CarMakesInfoList(carInfos); try { // Serialization : writing of subject in the flow of Release objstr.writeObject(list); // we empty the buffer objstr.flush(); } finally { //close of flow try { objstr.close(); } finally { flotpt.close(); } } } public List<CarMakeInfo> deserialize(InputStream inputStream) throws Exception { // creation a "Flow object " with the flow file ObjectInputStream objinstr= new PackageObjectInputStream(inputStream); List<CarMakeInfo> list = null; try { // deserialization : reading of subject since the flow Input list = ((CarMakesInfoList)objinstr.readObject()).list; } finally { // we farm the flow try { objinstr.close(); } finally { //nothing } } return list; } public class PackageObjectInputStream extends ObjectInputStream { public PackageObjectInputStream(InputStream in) throws IOException { super(in); } @Override protected ObjectStreamClass readClassDescriptor() throws IOException, ClassNotFoundException { ObjectStreamClass desc = super.readClassDescriptor(); if (desc.getName().equals("xxx.ltech.carvalue.common.CarMakeInfo")) { return ObjectStreamClass.lookup(CarMakeInfo.class); } else if (desc.getName().equals("xxx.ltech.carvalue.common.CarMakesInfoList")) { return ObjectStreamClass.lookup(CarMakesInfoList.class); } else if (desc.getName().equals("xxx.ltech.carvalue.common.CarModelInfo")) { return ObjectStreamClass.lookup(CarModelInfo.class); } else if (desc.getName().equals("xxx.ltech.carvalue.common.CarPrice")) { return ObjectStreamClass.lookup(CarPrice.class); } return desc; } } }
apache-2.0
kaiwinter/JavaActiveRecord
JavaActiveRecord/src/test/java/com/github/kaiwinter/activerecord/ar/PersonAR.java
1255
package com.github.kaiwinter.activerecord.ar; import com.github.kaiwinter.activerecord.BaseAR; import com.github.kaiwinter.activerecord.annotation.Column; import com.github.kaiwinter.activerecord.annotation.Table; import com.github.kaiwinter.activerecord.db.SequenceGenerator; @Table(alias = "person", sequenceGenerator = SequenceGenerator.INTERNAL) public class PersonAR extends BaseAR { @Column private String name; @Column private String surname; private String unattachedField; public PersonAR() { // empty constructor necessary } public PersonAR(String name, String surname) { this.name = name; this.surname = surname; } /** * @return the name */ public String getName() { return name; } /** * @param name * the name to set */ public void setName(String name) { this.name = name; } /** * @return the surname */ public String getSurname() { return surname; } /** * @param surname * the surname to set */ public void setSurname(String surname) { this.surname = surname; } }
apache-2.0
chenguoxi1985/pinpoint
rpc/src/main/java/com/navercorp/pinpoint/rpc/server/PinpointServerAcceptor.java
15593
/* * Copyright 2014 NAVER Corp. * * 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.navercorp.pinpoint.rpc.server; import com.navercorp.pinpoint.common.annotations.VisibleForTesting; import com.navercorp.pinpoint.common.util.Assert; import com.navercorp.pinpoint.common.util.CpuUtils; import com.navercorp.pinpoint.common.util.PinpointThreadFactory; import com.navercorp.pinpoint.rpc.PinpointSocket; import com.navercorp.pinpoint.rpc.PinpointSocketException; import com.navercorp.pinpoint.rpc.PipelineFactory; import com.navercorp.pinpoint.rpc.cluster.ClusterOption; import com.navercorp.pinpoint.rpc.packet.ServerClosePacket; import com.navercorp.pinpoint.rpc.server.handler.ServerStateChangeEventHandler; import com.navercorp.pinpoint.rpc.stream.DisabledServerStreamChannelMessageListener; import com.navercorp.pinpoint.rpc.stream.ServerStreamChannelMessageListener; import com.navercorp.pinpoint.rpc.util.LoggerFactorySetup; import com.navercorp.pinpoint.rpc.util.TimerFactory; import org.jboss.netty.bootstrap.ServerBootstrap; import org.jboss.netty.channel.Channel; import org.jboss.netty.channel.ChannelFuture; import org.jboss.netty.channel.ChannelFutureListener; import org.jboss.netty.channel.ChannelHandler; import org.jboss.netty.channel.ChannelHandlerContext; import org.jboss.netty.channel.ChannelPipeline; import org.jboss.netty.channel.ChannelPipelineFactory; import org.jboss.netty.channel.ChannelStateEvent; import org.jboss.netty.channel.MessageEvent; import org.jboss.netty.channel.SimpleChannelHandler; import org.jboss.netty.channel.group.ChannelGroup; import org.jboss.netty.channel.group.DefaultChannelGroup; import org.jboss.netty.channel.socket.nio.NioServerBossPool; import org.jboss.netty.channel.socket.nio.NioServerSocketChannelFactory; import org.jboss.netty.channel.socket.nio.NioWorkerPool; import org.jboss.netty.util.ThreadNameDeterminer; import org.jboss.netty.util.Timer; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.net.InetSocketAddress; import java.util.ArrayList; import java.util.List; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.TimeUnit; /** * @author Taejin Koo */ public class PinpointServerAcceptor implements PinpointServerConfig { private final Logger logger = LoggerFactory.getLogger(this.getClass()); private static final long DEFAULT_TIMEOUT_MILLIS = 3 * 1000; private static final long CHANNEL_CLOSE_MAXIMUM_WAITING_TIME_MILLIS = 3 * 1000; private static final int HEALTH_CHECK_INTERVAL_TIME_MILLIS = 5 * 60 * 1000; private static final int WORKER_COUNT = CpuUtils.workerCount(); private volatile boolean released; private ServerBootstrap bootstrap; private final ChannelFilter channelConnectedFilter; private Channel serverChannel; private final ChannelGroup channelGroup = new DefaultChannelGroup("PinpointServerFactory"); private final PinpointServerChannelHandler nettyChannelHandler = new PinpointServerChannelHandler(); private ServerMessageListener messageListener = SimpleServerMessageListener.SIMPLEX_INSTANCE; private ServerStreamChannelMessageListener serverStreamChannelMessageListener = DisabledServerStreamChannelMessageListener.INSTANCE; private List<ServerStateChangeEventHandler> stateChangeEventHandler = new ArrayList<ServerStateChangeEventHandler>(); private final Timer healthCheckTimer; private final HealthCheckManager healthCheckManager; private final Timer requestManagerTimer; private final ClusterOption clusterOption; private final PipelineFactory pipelineFactory; private long defaultRequestTimeout = DEFAULT_TIMEOUT_MILLIS; static { LoggerFactorySetup.setupSlf4jLoggerFactory(); } public PinpointServerAcceptor() { this(ClusterOption.DISABLE_CLUSTER_OPTION, ChannelFilter.BYPASS); } public PinpointServerAcceptor(ChannelFilter channelConnectedFilter) { this(ClusterOption.DISABLE_CLUSTER_OPTION, channelConnectedFilter); } public PinpointServerAcceptor(ChannelFilter channelConnectedFilter, PipelineFactory pipelineFactory) { this(ClusterOption.DISABLE_CLUSTER_OPTION, channelConnectedFilter, pipelineFactory); } public PinpointServerAcceptor(ClusterOption clusterOption, ChannelFilter channelConnectedFilter) { this(clusterOption, channelConnectedFilter, new ServerCodecPipelineFactory()); } public PinpointServerAcceptor(ClusterOption clusterOption, ChannelFilter channelConnectedFilter, PipelineFactory pipelineFactory) { ServerBootstrap bootstrap = createBootStrap(1, WORKER_COUNT); setOptions(bootstrap); this.bootstrap = bootstrap; this.healthCheckTimer = TimerFactory.createHashedWheelTimer("PinpointServerSocket-HealthCheckTimer", 50, TimeUnit.MILLISECONDS, 512); this.healthCheckManager = new HealthCheckManager(healthCheckTimer, channelGroup); this.requestManagerTimer = TimerFactory.createHashedWheelTimer("PinpointServerSocket-RequestManager", 50, TimeUnit.MILLISECONDS, 512); this.clusterOption = clusterOption; this.channelConnectedFilter = Assert.requireNonNull(channelConnectedFilter, "channelConnectedFilter must not be null"); this.pipelineFactory = Assert.requireNonNull(pipelineFactory, "pipelineFactory must not be null"); addPipeline(bootstrap, pipelineFactory); } private ServerBootstrap createBootStrap(int bossCount, int workerCount) { // profiler, collector ExecutorService boss = Executors.newCachedThreadPool(new PinpointThreadFactory("Pinpoint-Server-Boss", true)); NioServerBossPool nioServerBossPool = new NioServerBossPool(boss, bossCount, ThreadNameDeterminer.CURRENT); ExecutorService worker = Executors.newCachedThreadPool(new PinpointThreadFactory("Pinpoint-Server-Worker", true)); NioWorkerPool nioWorkerPool = new NioWorkerPool(worker, workerCount, ThreadNameDeterminer.CURRENT); NioServerSocketChannelFactory nioClientSocketChannelFactory = new NioServerSocketChannelFactory(nioServerBossPool, nioWorkerPool); return new ServerBootstrap(nioClientSocketChannelFactory); } private void setOptions(ServerBootstrap bootstrap) { // is read/write timeout necessary? don't need it because of NIO? // write timeout should be set through additional interceptor. write // timeout exists. // tcp setting bootstrap.setOption("child.tcpNoDelay", true); bootstrap.setOption("child.keepAlive", true); // buffer setting bootstrap.setOption("child.sendBufferSize", 1024 * 64); bootstrap.setOption("child.receiveBufferSize", 1024 * 64); // bootstrap.setOption("child.soLinger", 0); } private void addPipeline(ServerBootstrap bootstrap, final PipelineFactory pipelineFactory) { bootstrap.setPipelineFactory(new ChannelPipelineFactory() { @Override public ChannelPipeline getPipeline() throws Exception { ChannelPipeline pipeline = pipelineFactory.newPipeline(); pipeline.addLast("handler", nettyChannelHandler); return pipeline; } }); } @VisibleForTesting void setPipelineFactory(ChannelPipelineFactory channelPipelineFactory) { if (channelPipelineFactory == null) { throw new NullPointerException("channelPipelineFactory must not be null"); } bootstrap.setPipelineFactory(channelPipelineFactory); } @VisibleForTesting void setMessageHandler(final ChannelHandler messageHandler) { Assert.requireNonNull(messageHandler, "messageHandler must not be null"); bootstrap.setPipelineFactory(new ChannelPipelineFactory() { @Override public ChannelPipeline getPipeline() throws Exception { ChannelPipeline pipeline = pipelineFactory.newPipeline(); pipeline.addLast("handler", messageHandler); return pipeline; } }); } public void bind(String host, int port) throws PinpointSocketException { InetSocketAddress bindAddress = new InetSocketAddress(host, port); bind(bindAddress); } public void bind(InetSocketAddress bindAddress) throws PinpointSocketException { if (released) { return; } logger.info("bind() {}", bindAddress); this.serverChannel = bootstrap.bind(bindAddress); healthCheckManager.start(HEALTH_CHECK_INTERVAL_TIME_MILLIS); } private DefaultPinpointServer createPinpointServer(Channel channel) { DefaultPinpointServer pinpointServer = new DefaultPinpointServer(channel, this); return pinpointServer; } @Override public long getDefaultRequestTimeout() { return defaultRequestTimeout; } public void setDefaultRequestTimeout(long defaultRequestTimeout) { this.defaultRequestTimeout = defaultRequestTimeout; } @Override public ServerMessageListener getMessageListener() { return messageListener; } public void setMessageListener(ServerMessageListener messageListener) { Assert.requireNonNull(messageListener, "messageListener must not be null"); this.messageListener = messageListener; } @Override public List<ServerStateChangeEventHandler> getStateChangeEventHandlers() { return stateChangeEventHandler; } public void addStateChangeEventHandler(ServerStateChangeEventHandler stateChangeEventHandler) { Assert.requireNonNull(stateChangeEventHandler, "stateChangeEventHandler must not be null"); this.stateChangeEventHandler.add(stateChangeEventHandler); } @Override public ServerStreamChannelMessageListener getStreamMessageListener() { return serverStreamChannelMessageListener; } public void setServerStreamChannelMessageListener(ServerStreamChannelMessageListener serverStreamChannelMessageListener) { Assert.requireNonNull(serverStreamChannelMessageListener, "serverStreamChannelMessageListener must not be null"); this.serverStreamChannelMessageListener = serverStreamChannelMessageListener; } @Override public Timer getRequestManagerTimer() { return requestManagerTimer; } @Override public ClusterOption getClusterOption() { return clusterOption; } public void close() { synchronized (this) { if (released) { return; } released = true; } healthCheckManager.stop(); healthCheckTimer.stop(); closePinpointServer(); if (serverChannel != null) { ChannelFuture close = serverChannel.close(); close.awaitUninterruptibly(CHANNEL_CLOSE_MAXIMUM_WAITING_TIME_MILLIS, TimeUnit.MILLISECONDS); serverChannel = null; } if (bootstrap != null) { bootstrap.releaseExternalResources(); bootstrap = null; } // clear the request first and remove timer requestManagerTimer.stop(); } private void closePinpointServer() { for (Channel channel : channelGroup) { DefaultPinpointServer pinpointServer = (DefaultPinpointServer) channel.getAttachment(); if (pinpointServer != null) { pinpointServer.sendClosePacket(); } } } public List<PinpointSocket> getWritableSocketList() { List<PinpointSocket> pinpointServerList = new ArrayList<PinpointSocket>(); for (Channel channel : channelGroup) { DefaultPinpointServer pinpointServer = (DefaultPinpointServer) channel.getAttachment(); if (pinpointServer != null && pinpointServer.isEnableDuplexCommunication()) { pinpointServerList.add(pinpointServer); } } return pinpointServerList; } class PinpointServerChannelHandler extends SimpleChannelHandler { @Override public void channelConnected(ChannelHandlerContext ctx, ChannelStateEvent e) throws Exception { final Channel channel = e.getChannel(); logger.info("channelConnected started. channel:{}", channel); if (released) { logger.warn("already released. channel:{}", channel); channel.write(new ServerClosePacket()).addListener(new ChannelFutureListener() { @Override public void operationComplete(ChannelFuture future) throws Exception { future.getChannel().close(); } }); return; } final boolean accept = channelConnectedFilter.accept(channel); if (!accept) { logger.debug("channelConnected() channel discard. {}", channel); return; } DefaultPinpointServer pinpointServer = createPinpointServer(channel); channel.setAttachment(pinpointServer); channelGroup.add(channel); pinpointServer.start(); super.channelConnected(ctx, e); } @Override public void channelDisconnected(ChannelHandlerContext ctx, ChannelStateEvent e) throws Exception { final Channel channel = e.getChannel(); DefaultPinpointServer pinpointServer = (DefaultPinpointServer) channel.getAttachment(); if (pinpointServer != null) { pinpointServer.stop(released); } super.channelDisconnected(ctx, e); } // ChannelClose event may also happen when the other party close socket // first and Disconnected occurs // Should consider that. @Override public void channelClosed(ChannelHandlerContext ctx, ChannelStateEvent e) throws Exception { final Channel channel = e.getChannel(); channelGroup.remove(channel); super.channelClosed(ctx, e); } @Override public void messageReceived(ChannelHandlerContext ctx, MessageEvent e) throws Exception { final Channel channel = e.getChannel(); DefaultPinpointServer pinpointServer = (DefaultPinpointServer) channel.getAttachment(); if (pinpointServer != null) { Object message = e.getMessage(); pinpointServer.messageReceived(message); } super.messageReceived(ctx, e); } } }
apache-2.0
gchq/stroom
stroom-core-client-widget/src/main/java/stroom/item/client/ItemListBox.java
5552
/* * Copyright 2016 Crown Copyright * * 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 stroom.item.client; import stroom.docref.HasDisplayValue; import com.google.gwt.event.logical.shared.SelectionEvent; import com.google.gwt.event.logical.shared.SelectionHandler; import com.google.gwt.event.shared.HandlerRegistration; import com.google.gwt.user.client.ui.Composite; import com.google.gwt.user.client.ui.ListBox; import java.util.ArrayList; import java.util.Collection; import java.util.HashSet; import java.util.List; import java.util.Set; public class ItemListBox<T extends HasDisplayValue> extends Composite implements ItemListBoxDisplay<T> { private final ListBox listBox; private final List<T> items; private final String nonSelectString; private List<T> pendingSelection; public ItemListBox() { this(null, false); } public ItemListBox(final String nonSelectString) { this(nonSelectString, false); } public ItemListBox(final String nonSelectString, final boolean multiSelect) { this.nonSelectString = nonSelectString; listBox = new ListBox(); listBox.setMultipleSelect(multiSelect); items = new ArrayList<>(); if (nonSelectString != null) { listBox.addItem(nonSelectString); } listBox.addChangeHandler(event -> fireUpdate()); initWidget(listBox); } private void fireUpdate() { SelectionEvent.fire(this, getSelectedItem()); } @Override public HandlerRegistration addSelectionHandler(final SelectionHandler<T> handler) { return addHandler(handler, SelectionEvent.getType()); } @Override public void addItem(final T item) { if (item != null) { if (!items.contains(item)) { items.add(item); listBox.addItem(item.getDisplayValue()); if (pendingSelection != null && pendingSelection.contains(item)) { pendingSelection.remove(item); setItemSelected(item, true); } } } } @Override public void addItems(final Collection<T> list) { if (list != null) { for (final T item : list) { addItem(item); } } } @Override public void addItems(final T[] list) { if (list != null) { for (final T item : list) { addItem(item); } } } @Override public void removeItem(final T item) { if (item != null) { items.remove(item); for (int i = 0; i < listBox.getItemCount(); i++) { if (listBox.getValue(i).equals(item.getDisplayValue())) { listBox.removeItem(i); } } } } @Override public void setName(final String name) { listBox.setName(name); } @Override public void clear() { items.clear(); listBox.clear(); if (nonSelectString != null) { listBox.addItem(nonSelectString); } } @Override public T getSelectedItem() { int index = listBox.getSelectedIndex(); if (nonSelectString != null) { index--; } if (index != -1) { return items.get(index); } return null; } @Override public void setSelectedItem(final T item) { if (items == null || items.size() == 0) { if (pendingSelection == null) { pendingSelection = new ArrayList<>(); } pendingSelection.add(item); } else { int index = items.indexOf(item); if (nonSelectString != null) { index++; } listBox.setSelectedIndex(index); } } public Set<T> getSelectedItems() { final Set<T> set = new HashSet<>(); for (int i = 0; i < items.size(); i++) { int index = i; if (nonSelectString != null) { index++; } if (listBox.isItemSelected(index)) { set.add(items.get(i)); } } return set; } protected List<T> getItems() { return items; } public void setItemSelected(final T item, final boolean selected) { if (items == null || items.size() == 0) { if (pendingSelection == null) { pendingSelection = new ArrayList<>(); } if (selected) { pendingSelection.add(item); } else { pendingSelection.remove(item); } } else { int index = items.indexOf(item); if (nonSelectString != null) { index++; } listBox.setItemSelected(index, selected); } } @Override public void setEnabled(final boolean enabled) { listBox.setEnabled(enabled); } }
apache-2.0
ultradns/ultra-java-api
src/main/java/com/neustar/ultraservice/schema/v01/ObjectFactory.java
55012
package com.neustar.ultraservice.schema.v01; import javax.xml.bind.JAXBElement; import javax.xml.bind.annotation.XmlElementDecl; import javax.xml.bind.annotation.XmlRegistry; import javax.xml.namespace.QName; /** * This object contains factory methods for each * Java content interface and Java element interface * generated in the com.neustar.ultraservice.schema.v01 package. * <p>An ObjectFactory allows you to programatically * construct new instances of the Java representation * for XML content. The Java representation of XML * content can consist of schema derived interfaces * and classes representing the binding of schema * type definitions, element declarations and model * groups. Factory methods for each of these are * provided in this class. * */ @XmlRegistry public class ObjectFactory { private final static QName _ProbeInfo2Ttl_QNAME = new QName("http://schema.ultraservice.neustar.com/v01/", "ttl"); private final static QName _NameServersNameServerRecordSet_QNAME = new QName("http://schema.ultraservice.neustar.com/v01/", "NameServerRecordSet"); /** * Create a new ObjectFactory that can be used to create new instances of schema derived classes for package: com.neustar.ultraservice.schema.v01 * */ public ObjectFactory() { } /** * Create an instance of {@link ProbeAlertsList } * */ public ProbeAlertsList createProbeAlertsList() { return new ProbeAlertsList(); } /** * Create an instance of {@link DirectionalPoolList } * */ public DirectionalPoolList createDirectionalPoolList() { return new DirectionalPoolList(); } /** * Create an instance of {@link RegionAndAgent } * */ public RegionAndAgent createRegionAndAgent() { return new RegionAndAgent(); } /** * Create an instance of {@link PoolRecordsList } * */ public PoolRecordsList createPoolRecordsList() { return new PoolRecordsList(); } /** * Create an instance of {@link AddDirectionalRecordData } * */ public AddDirectionalRecordData createAddDirectionalRecordData() { return new AddDirectionalRecordData(); } /** * Create an instance of {@link MonitoredRDPools } * */ public MonitoredRDPools createMonitoredRDPools() { return new MonitoredRDPools(); } /** * Create an instance of {@link AddressBookEntryKeys } * */ public AddressBookEntryKeys createAddressBookEntryKeys() { return new AddressBookEntryKeys(); } /** * Create an instance of {@link PoolRecord } * */ public PoolRecord createPoolRecord() { return new PoolRecord(); } /** * Create an instance of {@link InfoValues } * */ public InfoValues createInfoValues() { return new InfoValues(); } /** * Create an instance of {@link PrioritizedRecordsList } * */ public PrioritizedRecordsList createPrioritizedRecordsList() { return new PrioritizedRecordsList(); } /** * Create an instance of {@link PoolRecordListParams } * */ public PoolRecordListParams createPoolRecordListParams() { return new PoolRecordListParams(); } /** * Create an instance of {@link UpdateRoundRobinRecord } * */ public UpdateRoundRobinRecord createUpdateRoundRobinRecord() { return new UpdateRoundRobinRecord(); } /** * Create an instance of {@link HealthCheckList } * */ public HealthCheckList createHealthCheckList() { return new HealthCheckList(); } /** * Create an instance of {@link MailFwdRecordsList } * */ public MailFwdRecordsList createMailFwdRecordsList() { return new MailFwdRecordsList(); } /** * Create an instance of {@link ARPoolRuleKey } * */ public ARPoolRuleKey createARPoolRuleKey() { return new ARPoolRuleKey(); } /** * Create an instance of {@link ARPoolAlertsList } * */ public ARPoolAlertsList createARPoolAlertsList() { return new ARPoolAlertsList(); } /** * Create an instance of {@link PoolProbeId } * */ public PoolProbeId createPoolProbeId() { return new PoolProbeId(); } /** * Create an instance of {@link AddressBookEntryCreateKey } * */ public AddressBookEntryCreateKey createAddressBookEntryCreateKey() { return new AddressBookEntryCreateKey(); } /** * Create an instance of {@link RecentActivityList } * */ public RecentActivityList createRecentActivityList() { return new RecentActivityList(); } /** * Create an instance of {@link AlertPoolStatus } * */ public AlertPoolStatus createAlertPoolStatus() { return new AlertPoolStatus(); } /** * Create an instance of {@link RegionForNewGroups } * */ public RegionForNewGroups createRegionForNewGroups() { return new RegionForNewGroups(); } /** * Create an instance of {@link RegionForNewGroupsList } * */ public RegionForNewGroupsList createRegionForNewGroupsList() { return new RegionForNewGroupsList(); } /** * Create an instance of {@link UnsuspendZone } * */ public UnsuspendZone createUnsuspendZone() { return new UnsuspendZone(); } /** * Create an instance of {@link PoolRecordId } * */ public PoolRecordId createPoolRecordId() { return new PoolRecordId(); } /** * Create an instance of {@link AddDirectionalPoolData } * */ public AddDirectionalPoolData createAddDirectionalPoolData() { return new AddDirectionalPoolData(); } /** * Create an instance of {@link Rules } * */ public Rules createRules() { return new Rules(); } /** * Create an instance of {@link AlertPoolDetails } * */ public AlertPoolDetails createAlertPoolDetails() { return new AlertPoolDetails(); } /** * Create an instance of {@link DefaultReportPrefPreference } * */ public DefaultReportPrefPreference createDefaultReportPrefPreference() { return new DefaultReportPrefPreference(); } /** * Create an instance of {@link TCPCriteria } * */ public TCPCriteria createTCPCriteria() { return new TCPCriteria(); } /** * Create an instance of {@link PoolData } * */ public PoolData createPoolData() { return new PoolData(); } /** * Create an instance of {@link ExternalValues } * */ public ExternalValues createExternalValues() { return new ExternalValues(); } /** * Create an instance of {@link SourceIpGroupDefinitionList } * */ public SourceIpGroupDefinitionList createSourceIpGroupDefinitionList() { return new SourceIpGroupDefinitionList(); } /** * Create an instance of {@link CountryInfo } * */ public CountryInfo createCountryInfo() { return new CountryInfo(); } /** * Create an instance of {@link UserDetailsPermissionData } * */ public UserDetailsPermissionData createUserDetailsPermissionData() { return new UserDetailsPermissionData(); } /** * Create an instance of {@link UnsuspendZoneRequest } * */ public UnsuspendZoneRequest createUnsuspendZoneRequest() { return new UnsuspendZoneRequest(); } /** * Create an instance of {@link ProbeRegionList } * */ public ProbeRegionList createProbeRegionList() { return new ProbeRegionList(); } /** * Create an instance of {@link StatesInfo } * */ public StatesInfo createStatesInfo() { return new StatesInfo(); } /** * Create an instance of {@link ScheduledEvent } * */ public ScheduledEvent createScheduledEvent() { return new ScheduledEvent(); } /** * Create an instance of {@link SMTPAvailabilityProbeData } * */ public SMTPAvailabilityProbeData createSMTPAvailabilityProbeData() { return new SMTPAvailabilityProbeData(); } /** * Create an instance of {@link MonitoredRDPoolRecordsAdd } * */ public MonitoredRDPoolRecordsAdd createMonitoredRDPoolRecordsAdd() { return new MonitoredRDPoolRecordsAdd(); } /** * Create an instance of {@link DirectionalDNSRecordDetailList } * */ public DirectionalDNSRecordDetailList createDirectionalDNSRecordDetailList() { return new DirectionalDNSRecordDetailList(); } /** * Create an instance of {@link FTPCriteria } * */ public FTPCriteria createFTPCriteria() { return new FTPCriteria(); } /** * Create an instance of {@link UserDefaultPreferences } * */ public UserDefaultPreferences createUserDefaultPreferences() { return new UserDefaultPreferences(); } /** * Create an instance of {@link AccountPreferencesList } * */ public AccountPreferencesList createAccountPreferencesList() { return new AccountPreferencesList(); } /** * Create an instance of {@link DsRecordList } * */ public DsRecordList createDsRecordList() { return new DsRecordList(); } /** * Create an instance of {@link HTTPProbeData } * */ public HTTPProbeData createHTTPProbeData() { return new HTTPProbeData(); } /** * Create an instance of {@link TaskId } * */ public TaskId createTaskId() { return new TaskId(); } /** * Create an instance of {@link SourceIpGroupDefinitionData } * */ public SourceIpGroupDefinitionData createSourceIpGroupDefinitionData() { return new SourceIpGroupDefinitionData(); } /** * Create an instance of {@link AddressBookEntryListKey } * */ public AddressBookEntryListKey createAddressBookEntryListKey() { return new AddressBookEntryListKey(); } /** * Create an instance of {@link NameServers } * */ public NameServers createNameServers() { return new NameServers(); } /** * Create an instance of {@link UpdateGeolocationGroupDetails } * */ public UpdateGeolocationGroupDetails createUpdateGeolocationGroupDetails() { return new UpdateGeolocationGroupDetails(); } /** * Create an instance of {@link MonitoredRDPoolConversionInfo } * */ public MonitoredRDPoolConversionInfo createMonitoredRDPoolConversionInfo() { return new MonitoredRDPoolConversionInfo(); } /** * Create an instance of {@link AgentsRunningProbeList } * */ public AgentsRunningProbeList createAgentsRunningProbeList() { return new AgentsRunningProbeList(); } /** * Create an instance of {@link GeolocationGroupDetails } * */ public GeolocationGroupDetails createGeolocationGroupDetails() { return new GeolocationGroupDetails(); } /** * Create an instance of {@link FTPTransaction } * */ public FTPTransaction createFTPTransaction() { return new FTPTransaction(); } /** * Create an instance of {@link ZoneInfoData } * */ public ZoneInfoData createZoneInfoData() { return new ZoneInfoData(); } /** * Create an instance of {@link PoolToAcctGroupConversionDetails } * */ public PoolToAcctGroupConversionDetails createPoolToAcctGroupConversionDetails() { return new PoolToAcctGroupConversionDetails(); } /** * Create an instance of {@link PoolDefinitions } * */ public PoolDefinitions createPoolDefinitions() { return new PoolDefinitions(); } /** * Create an instance of {@link AllStatesList } * */ public AllStatesList createAllStatesList() { return new AllStatesList(); } /** * Create an instance of {@link WebFwdRecordsList } * */ public WebFwdRecordsList createWebFwdRecordsList() { return new WebFwdRecordsList(); } /** * Create an instance of {@link HeaderRule } * */ public HeaderRule createHeaderRule() { return new HeaderRule(); } /** * Create an instance of {@link CNAMERecord } * */ public CNAMERecord createCNAMERecord() { return new CNAMERecord(); } /** * Create an instance of {@link SMTPCriteria } * */ public SMTPCriteria createSMTPCriteria() { return new SMTPCriteria(); } /** * Create an instance of {@link ProbeDefinitionId } * */ public ProbeDefinitionId createProbeDefinitionId() { return new ProbeDefinitionId(); } /** * Create an instance of {@link FailoverMonitorUpdate } * */ public FailoverMonitorUpdate createFailoverMonitorUpdate() { return new FailoverMonitorUpdate(); } /** * Create an instance of {@link ProbeData } * */ public ProbeData createProbeData() { return new ProbeData(); } /** * Create an instance of {@link PrioritizedRecord } * */ public PrioritizedRecord createPrioritizedRecord() { return new PrioritizedRecord(); } /** * Create an instance of {@link PROXYProbeData } * */ public PROXYProbeData createPROXYProbeData() { return new PROXYProbeData(); } /** * Create an instance of {@link InactiveTimeOutPreference } * */ public InactiveTimeOutPreference createInactiveTimeOutPreference() { return new InactiveTimeOutPreference(); } /** * Create an instance of {@link DnssecKeyRecordList } * */ public DnssecKeyRecordList createDnssecKeyRecordList() { return new DnssecKeyRecordList(); } /** * Create an instance of {@link SecurityQuestions } * */ public SecurityQuestions createSecurityQuestions() { return new SecurityQuestions(); } /** * Create an instance of {@link AddressBookEntryGet } * */ public AddressBookEntryGet createAddressBookEntryGet() { return new AddressBookEntryGet(); } /** * Create an instance of {@link UpdateSourceIPGroupDetails } * */ public UpdateSourceIPGroupDetails createUpdateSourceIPGroupDetails() { return new UpdateSourceIPGroupDetails(); } /** * Create an instance of {@link SimpleFailoverPoolList } * */ public SimpleFailoverPoolList createSimpleFailoverPoolList() { return new SimpleFailoverPoolList(); } /** * Create an instance of {@link MonitoredRDPoolRecordAdd } * */ public MonitoredRDPoolRecordAdd createMonitoredRDPoolRecordAdd() { return new MonitoredRDPoolRecordAdd(); } /** * Create an instance of {@link PoolRecordProbeId } * */ public PoolRecordProbeId createPoolRecordProbeId() { return new PoolRecordProbeId(); } /** * Create an instance of {@link PoolRecordUpdate } * */ public PoolRecordUpdate createPoolRecordUpdate() { return new PoolRecordUpdate(); } /** * Create an instance of {@link ZoneInfoList } * */ public ZoneInfoList createZoneInfoList() { return new ZoneInfoList(); } /** * Create an instance of {@link CustomHTTPHeaderDataList } * */ public CustomHTTPHeaderDataList createCustomHTTPHeaderDataList() { return new CustomHTTPHeaderDataList(); } /** * Create an instance of {@link SBAgentsData } * */ public SBAgentsData createSBAgentsData() { return new SBAgentsData(); } /** * Create an instance of {@link UpdateWebForwardPoolRecordData } * */ public UpdateWebForwardPoolRecordData createUpdateWebForwardPoolRecordData() { return new UpdateWebForwardPoolRecordData(); } /** * Create an instance of {@link PoolAlertDetails } * */ public PoolAlertDetails createPoolAlertDetails() { return new PoolAlertDetails(); } /** * Create an instance of {@link DomainAlertData } * */ public DomainAlertData createDomainAlertData() { return new DomainAlertData(); } /** * Create an instance of {@link GeneralNotificationStatusData } * */ public GeneralNotificationStatusData createGeneralNotificationStatusData() { return new GeneralNotificationStatusData(); } /** * Create an instance of {@link SimpleFailoverPool } * */ public SimpleFailoverPool createSimpleFailoverPool() { return new SimpleFailoverPool(); } /** * Create an instance of {@link RegionList } * */ public RegionList createRegionList() { return new RegionList(); } /** * Create an instance of {@link PingCriteria } * */ public PingCriteria createPingCriteria() { return new PingCriteria(); } /** * Create an instance of {@link HttpCriteria } * */ public HttpCriteria createHttpCriteria() { return new HttpCriteria(); } /** * Create an instance of {@link UpdateCustomHTTPHeaderData } * */ public UpdateCustomHTTPHeaderData createUpdateCustomHTTPHeaderData() { return new UpdateCustomHTTPHeaderData(); } /** * Create an instance of {@link Pool } * */ public Pool createPool() { return new Pool(); } /** * Create an instance of {@link ResourceRecordGUIDList } * */ public ResourceRecordGUIDList createResourceRecordGUIDList() { return new ResourceRecordGUIDList(); } /** * Create an instance of {@link ProbesList } * */ public ProbesList createProbesList() { return new ProbesList(); } /** * Create an instance of {@link ScheduledEventList } * */ public ScheduledEventList createScheduledEventList() { return new ScheduledEventList(); } /** * Create an instance of {@link UpdateDirectionalPoolData } * */ public UpdateDirectionalPoolData createUpdateDirectionalPoolData() { return new UpdateDirectionalPoolData(); } /** * Create an instance of {@link ARAlertRuleDetails } * */ public ARAlertRuleDetails createARAlertRuleDetails() { return new ARAlertRuleDetails(); } /** * Create an instance of {@link CustomHTTPHeaderData } * */ public CustomHTTPHeaderData createCustomHTTPHeaderData() { return new CustomHTTPHeaderData(); } /** * Create an instance of {@link MonitoredRDPoolUpdate } * */ public MonitoredRDPoolUpdate createMonitoredRDPoolUpdate() { return new MonitoredRDPoolUpdate(); } /** * Create an instance of {@link MonitoredRDPool } * */ public MonitoredRDPool createMonitoredRDPool() { return new MonitoredRDPool(); } /** * Create an instance of {@link PoolId } * */ public PoolId createPoolId() { return new PoolId(); } /** * Create an instance of {@link SimpleFailoverPoolAdd } * */ public SimpleFailoverPoolAdd createSimpleFailoverPoolAdd() { return new SimpleFailoverPoolAdd(); } /** * Create an instance of {@link ZoneTransferStatus } * */ public ZoneTransferStatus createZoneTransferStatus() { return new ZoneTransferStatus(); } /** * Create an instance of {@link TCPProbeData } * */ public TCPProbeData createTCPProbeData() { return new TCPProbeData(); } /** * Create an instance of {@link SuspendZone } * */ public SuspendZone createSuspendZone() { return new SuspendZone(); } /** * Create an instance of {@link TaskStatusList } * */ public TaskStatusList createTaskStatusList() { return new TaskStatusList(); } /** * Create an instance of {@link DirectionalDNSRecordDetail } * */ public DirectionalDNSRecordDetail createDirectionalDNSRecordDetail() { return new DirectionalDNSRecordDetail(); } /** * Create an instance of {@link DnsCriteria } * */ public DnsCriteria createDnsCriteria() { return new DnsCriteria(); } /** * Create an instance of {@link AccountPreferenceDetail } * */ public AccountPreferenceDetail createAccountPreferenceDetail() { return new AccountPreferenceDetail(); } /** * Create an instance of {@link DirectionalDNSRecordToUpdate } * */ public DirectionalDNSRecordToUpdate createDirectionalDNSRecordToUpdate() { return new DirectionalDNSRecordToUpdate(); } /** * Create an instance of {@link Probe } * */ public Probe createProbe() { return new Probe(); } /** * Create an instance of {@link PasswordVerificationQuestionList } * */ public PasswordVerificationQuestionList createPasswordVerificationQuestionList() { return new PasswordVerificationQuestionList(); } /** * Create an instance of {@link ARPoolRecords } * */ public ARPoolRecords createARPoolRecords() { return new ARPoolRecords(); } /** * Create an instance of {@link SMTP2Transaction } * */ public SMTP2Transaction createSMTP2Transaction() { return new SMTP2Transaction(); } /** * Create an instance of {@link AllUsersDetailsList } * */ public AllUsersDetailsList createAllUsersDetailsList() { return new AllUsersDetailsList(); } /** * Create an instance of {@link UserDetailsData } * */ public UserDetailsData createUserDetailsData() { return new UserDetailsData(); } /** * Create an instance of {@link NotificationData } * */ public NotificationData createNotificationData() { return new NotificationData(); } /** * Create an instance of {@link GlobalDirectionalGroupUpdateDetails } * */ public GlobalDirectionalGroupUpdateDetails createGlobalDirectionalGroupUpdateDetails() { return new GlobalDirectionalGroupUpdateDetails(); } /** * Create an instance of {@link ResourceRecordList } * */ public ResourceRecordList createResourceRecordList() { return new ResourceRecordList(); } /** * Create an instance of {@link PINGProbeData } * */ public PINGProbeData createPINGProbeData() { return new PINGProbeData(); } /** * Create an instance of {@link Region } * */ public Region createRegion() { return new Region(); } /** * Create an instance of {@link AliasedDomainInfo } * */ public AliasedDomainInfo createAliasedDomainInfo() { return new AliasedDomainInfo(); } /** * Create an instance of {@link NameServerRecord } * */ public NameServerRecord createNameServerRecord() { return new NameServerRecord(); } /** * Create an instance of {@link PoolDetails } * */ public PoolDetails createPoolDetails() { return new PoolDetails(); } /** * Create an instance of {@link DirectionalDNSGroupDetail } * */ public DirectionalDNSGroupDetail createDirectionalDNSGroupDetail() { return new DirectionalDNSGroupDetail(); } /** * Create an instance of {@link DefaultNumberOfrecordsPreference } * */ public DefaultNumberOfrecordsPreference createDefaultNumberOfrecordsPreference() { return new DefaultNumberOfrecordsPreference(); } /** * Create an instance of {@link NameServerList } * */ public NameServerList createNameServerList() { return new NameServerList(); } /** * Create an instance of {@link WebForwardPoolRecordData } * */ public WebForwardPoolRecordData createWebForwardPoolRecordData() { return new WebForwardPoolRecordData(); } /** * Create an instance of {@link ProbeDefinition } * */ public ProbeDefinition createProbeDefinition() { return new ProbeDefinition(); } /** * Create an instance of {@link PoolConfigurationList } * */ public PoolConfigurationList createPoolConfigurationList() { return new PoolConfigurationList(); } /** * Create an instance of {@link WebForwardRecord } * */ public WebForwardRecord createWebForwardRecord() { return new WebForwardRecord(); } /** * Create an instance of {@link AccountAddressInfo } * */ public AccountAddressInfo createAccountAddressInfo() { return new AccountAddressInfo(); } /** * Create an instance of {@link AllUsersDetailsData } * */ public AllUsersDetailsData createAllUsersDetailsData() { return new AllUsersDetailsData(); } /** * Create an instance of {@link ResourceRecord } * */ public ResourceRecord createResourceRecord() { return new ResourceRecord(); } /** * Create an instance of {@link ResourceRecordToUpdate } * */ public ResourceRecordToUpdate createResourceRecordToUpdate() { return new ResourceRecordToUpdate(); } /** * Create an instance of {@link AccountLevelNotificationsList } * */ public AccountLevelNotificationsList createAccountLevelNotificationsList() { return new AccountLevelNotificationsList(); } /** * Create an instance of {@link ProbeRegions } * */ public ProbeRegions createProbeRegions() { return new ProbeRegions(); } /** * Create an instance of {@link ARPoolProbeList } * */ public ARPoolProbeList createARPoolProbeList() { return new ARPoolProbeList(); } /** * Create an instance of {@link LBPoolData } * */ public LBPoolData createLBPoolData() { return new LBPoolData(); } /** * Create an instance of {@link AcctToPoolGroupConversionDetails } * */ public AcctToPoolGroupConversionDetails createAcctToPoolGroupConversionDetails() { return new AcctToPoolGroupConversionDetails(); } /** * Create an instance of {@link AlertAllFailDetails } * */ public AlertAllFailDetails createAlertAllFailDetails() { return new AlertAllFailDetails(); } /** * Create an instance of {@link DsRecord } * */ public DsRecord createDsRecord() { return new DsRecord(); } /** * Create an instance of {@link AccountLevelGroupsList } * */ public AccountLevelGroupsList createAccountLevelGroupsList() { return new AccountLevelGroupsList(); } /** * Create an instance of {@link FailoverMonitor } * */ public FailoverMonitor createFailoverMonitor() { return new FailoverMonitor(); } /** * Create an instance of {@link MonitoredRDPoolMonitor } * */ public MonitoredRDPoolMonitor createMonitoredRDPoolMonitor() { return new MonitoredRDPoolMonitor(); } /** * Create an instance of {@link PoolDetailsList } * */ public PoolDetailsList createPoolDetailsList() { return new PoolDetailsList(); } /** * Create an instance of {@link ARProbeInfo } * */ public ARProbeInfo createARProbeInfo() { return new ARProbeInfo(); } /** * Create an instance of {@link ProbeInfo } * */ public ProbeInfo createProbeInfo() { return new ProbeInfo(); } /** * Create an instance of {@link SecurityPreferences } * */ public SecurityPreferences createSecurityPreferences() { return new SecurityPreferences(); } /** * Create an instance of {@link ProbeRegion } * */ public ProbeRegion createProbeRegion() { return new ProbeRegion(); } /** * Create an instance of {@link DNSProbeMaster } * */ public DNSProbeMaster createDNSProbeMaster() { return new DNSProbeMaster(); } /** * Create an instance of {@link ProbeInfo2 } * */ public ProbeInfo2 createProbeInfo2() { return new ProbeInfo2(); } /** * Create an instance of {@link MonitoredRDPoolRecord } * */ public MonitoredRDPoolRecord createMonitoredRDPoolRecord() { return new MonitoredRDPoolRecord(); } /** * Create an instance of {@link SimpleFailoverPoolUpdate } * */ public SimpleFailoverPoolUpdate createSimpleFailoverPoolUpdate() { return new SimpleFailoverPoolUpdate(); } /** * Create an instance of {@link AddressBookEntry } * */ public AddressBookEntry createAddressBookEntry() { return new AddressBookEntry(); } /** * Create an instance of {@link RecentActivity } * */ public RecentActivity createRecentActivity() { return new RecentActivity(); } /** * Create an instance of {@link ResourceRecordTypeOrderInfoList } * */ public ResourceRecordTypeOrderInfoList createResourceRecordTypeOrderInfoList() { return new ResourceRecordTypeOrderInfoList(); } /** * Create an instance of {@link DashboardTypeOrderInfo } * */ public DashboardTypeOrderInfo createDashboardTypeOrderInfo() { return new DashboardTypeOrderInfo(); } /** * Create an instance of {@link NameServerData } * */ public NameServerData createNameServerData() { return new NameServerData(); } /** * Create an instance of {@link AutomaticPointerPreference } * */ public AutomaticPointerPreference createAutomaticPointerPreference() { return new AutomaticPointerPreference(); } /** * Create an instance of {@link ResourceRecordToSearch } * */ public ResourceRecordToSearch createResourceRecordToSearch() { return new ResourceRecordToSearch(); } /** * Create an instance of {@link MonitoredRDPoolListKey } * */ public MonitoredRDPoolListKey createMonitoredRDPoolListKey() { return new MonitoredRDPoolListKey(); } /** * Create an instance of {@link DefaultDateAndTimePreference } * */ public DefaultDateAndTimePreference createDefaultDateAndTimePreference() { return new DefaultDateAndTimePreference(); } /** * Create an instance of {@link ProbeDefinitionTransactions } * */ public ProbeDefinitionTransactions createProbeDefinitionTransactions() { return new ProbeDefinitionTransactions(); } /** * Create an instance of {@link AddressBookEntryCreate } * */ public AddressBookEntryCreate createAddressBookEntryCreate() { return new AddressBookEntryCreate(); } /** * Create an instance of {@link SMTPSendMailProbeData } * */ public SMTPSendMailProbeData createSMTPSendMailProbeData() { return new SMTPSendMailProbeData(); } /** * Create an instance of {@link SimpleFailoverConversionInfo } * */ public SimpleFailoverConversionInfo createSimpleFailoverConversionInfo() { return new SimpleFailoverConversionInfo(); } /** * Create an instance of {@link ARecord } * */ public ARecord createARecord() { return new ARecord(); } /** * Create an instance of {@link AlertRecord } * */ public AlertRecord createAlertRecord() { return new AlertRecord(); } /** * Create an instance of {@link AccountDetailsData } * */ public AccountDetailsData createAccountDetailsData() { return new AccountDetailsData(); } /** * Create an instance of {@link DeleteConfirmPreference } * */ public DeleteConfirmPreference createDeleteConfirmPreference() { return new DeleteConfirmPreference(); } /** * Create an instance of {@link MonitoredRDPoolMonitorUpdate } * */ public MonitoredRDPoolMonitorUpdate createMonitoredRDPoolMonitorUpdate() { return new MonitoredRDPoolMonitorUpdate(); } /** * Create an instance of {@link DefaultAccountPreference } * */ public DefaultAccountPreference createDefaultAccountPreference() { return new DefaultAccountPreference(); } /** * Create an instance of {@link InfoTypes } * */ public InfoTypes createInfoTypes() { return new InfoTypes(); } /** * Create an instance of {@link ARPoolConfigurationKey } * */ public ARPoolConfigurationKey createARPoolConfigurationKey() { return new ARPoolConfigurationKey(); } /** * Create an instance of {@link RoundRobinRecord } * */ public RoundRobinRecord createRoundRobinRecord() { return new RoundRobinRecord(); } /** * Create an instance of {@link FTPProbeData } * */ public FTPProbeData createFTPProbeData() { return new FTPProbeData(); } /** * Create an instance of {@link GeneralZoneProperties } * */ public GeneralZoneProperties createGeneralZoneProperties() { return new GeneralZoneProperties(); } /** * Create an instance of {@link UserContactInfo } * */ public UserContactInfo createUserContactInfo() { return new UserContactInfo(); } /** * Create an instance of {@link NotifyRecordList } * */ public NotifyRecordList createNotifyRecordList() { return new NotifyRecordList(); } /** * Create an instance of {@link DirectionalDNSRecord } * */ public DirectionalDNSRecord createDirectionalDNSRecord() { return new DirectionalDNSRecord(); } /** * Create an instance of {@link FailoverRecord } * */ public FailoverRecord createFailoverRecord() { return new FailoverRecord(); } /** * Create an instance of {@link SBRegionData } * */ public SBRegionData createSBRegionData() { return new SBRegionData(); } /** * Create an instance of {@link ARAlertStateDetails } * */ public ARAlertStateDetails createARAlertStateDetails() { return new ARAlertStateDetails(); } /** * Create an instance of {@link SUBPOOLRecord } * */ public SUBPOOLRecord createSUBPOOLRecord() { return new SUBPOOLRecord(); } /** * Create an instance of {@link UsersList } * */ public UsersList createUsersList() { return new UsersList(); } /** * Create an instance of {@link ARPoolProbes } * */ public ARPoolProbes createARPoolProbes() { return new ARPoolProbes(); } /** * Create an instance of {@link ContactARPoolRuleInfo } * */ public ContactARPoolRuleInfo createContactARPoolRuleInfo() { return new ContactARPoolRuleInfo(); } /** * Create an instance of {@link ARPoolRecord } * */ public ARPoolRecord createARPoolRecord() { return new ARPoolRecord(); } /** * Create an instance of {@link UltraZone } * */ public UltraZone createUltraZone() { return new UltraZone(); } /** * Create an instance of {@link UserSummary } * */ public UserSummary createUserSummary() { return new UserSummary(); } /** * Create an instance of {@link SimpleFailoverPoolKey } * */ public SimpleFailoverPoolKey createSimpleFailoverPoolKey() { return new SimpleFailoverPoolKey(); } /** * Create an instance of {@link ARPoolConfigurationUpdate } * */ public ARPoolConfigurationUpdate createARPoolConfigurationUpdate() { return new ARPoolConfigurationUpdate(); } /** * Create an instance of {@link MaintenanceAlertsData } * */ public MaintenanceAlertsData createMaintenanceAlertsData() { return new MaintenanceAlertsData(); } /** * Create an instance of {@link AddressBookEntryKey } * */ public AddressBookEntryKey createAddressBookEntryKey() { return new AddressBookEntryKey(); } /** * Create an instance of {@link GeolocationGroupDefinitionData } * */ public GeolocationGroupDefinitionData createGeolocationGroupDefinitionData() { return new GeolocationGroupDefinitionData(); } /** * Create an instance of {@link PasswordVerificationQuestion } * */ public PasswordVerificationQuestion createPasswordVerificationQuestion() { return new PasswordVerificationQuestion(); } /** * Create an instance of {@link GlobalDirectionalGroupDetails } * */ public GlobalDirectionalGroupDetails createGlobalDirectionalGroupDetails() { return new GlobalDirectionalGroupDetails(); } /** * Create an instance of {@link ARPoolAlertsKey } * */ public ARPoolAlertsKey createARPoolAlertsKey() { return new ARPoolAlertsKey(); } /** * Create an instance of {@link FailoverRecordUpdate } * */ public FailoverRecordUpdate createFailoverRecordUpdate() { return new FailoverRecordUpdate(); } /** * Create an instance of {@link NotificationList } * */ public NotificationList createNotificationList() { return new NotificationList(); } /** * Create an instance of {@link CopyAssignedDirDNSGroup } * */ public CopyAssignedDirDNSGroup createCopyAssignedDirDNSGroup() { return new CopyAssignedDirDNSGroup(); } /** * Create an instance of {@link PrioritizedRecordList } * */ public PrioritizedRecordList createPrioritizedRecordList() { return new PrioritizedRecordList(); } /** * Create an instance of {@link ProbeDefinitionHttpTransactions } * */ public ProbeDefinitionHttpTransactions createProbeDefinitionHttpTransactions() { return new ProbeDefinitionHttpTransactions(); } /** * Create an instance of {@link DashboardTypeOrderInfoList } * */ public DashboardTypeOrderInfoList createDashboardTypeOrderInfoList() { return new DashboardTypeOrderInfoList(); } /** * Create an instance of {@link ProbeDefinitionList } * */ public ProbeDefinitionList createProbeDefinitionList() { return new ProbeDefinitionList(); } /** * Create an instance of {@link AlertSummaryList } * */ public AlertSummaryList createAlertSummaryList() { return new AlertSummaryList(); } /** * Create an instance of {@link ServiceList } * */ public ServiceList createServiceList() { return new ServiceList(); } /** * Create an instance of {@link PoolConfiguration } * */ public PoolConfiguration createPoolConfiguration() { return new PoolConfiguration(); } /** * Create an instance of {@link AlertPrioritizedRecord } * */ public AlertPrioritizedRecord createAlertPrioritizedRecord() { return new AlertPrioritizedRecord(); } /** * Create an instance of {@link CopyDirectionalGroup } * */ public CopyDirectionalGroup createCopyDirectionalGroup() { return new CopyDirectionalGroup(); } /** * Create an instance of {@link MonitoredRDPoolAllFailRecordUpdate } * */ public MonitoredRDPoolAllFailRecordUpdate createMonitoredRDPoolAllFailRecordUpdate() { return new MonitoredRDPoolAllFailRecordUpdate(); } /** * Create an instance of {@link ARPoolAlerts } * */ public ARPoolAlerts createARPoolAlerts() { return new ARPoolAlerts(); } /** * Create an instance of {@link PoolConfigurationDetails } * */ public PoolConfigurationDetails createPoolConfigurationDetails() { return new PoolConfigurationDetails(); } /** * Create an instance of {@link DNSProbeData } * */ public DNSProbeData createDNSProbeData() { return new DNSProbeData(); } /** * Create an instance of {@link LBPoolList } * */ public LBPoolList createLBPoolList() { return new LBPoolList(); } /** * Create an instance of {@link PoolAlertsListParams } * */ public PoolAlertsListParams createPoolAlertsListParams() { return new PoolAlertsListParams(); } /** * Create an instance of {@link Notifications } * */ public Notifications createNotifications() { return new Notifications(); } /** * Create an instance of {@link SuspendZoneRequest } * */ public SuspendZoneRequest createSuspendZoneRequest() { return new SuspendZoneRequest(); } /** * Create an instance of {@link ARPoolAlert } * */ public ARPoolAlert createARPoolAlert() { return new ARPoolAlert(); } /** * Create an instance of {@link EntryListParams } * */ public EntryListParams createEntryListParams() { return new EntryListParams(); } /** * Create an instance of {@link DirectionalRecordData } * */ public DirectionalRecordData createDirectionalRecordData() { return new DirectionalRecordData(); } /** * Create an instance of {@link NotifyRecord } * */ public NotifyRecord createNotifyRecord() { return new NotifyRecord(); } /** * Create an instance of {@link AccountDetailsList } * */ public AccountDetailsList createAccountDetailsList() { return new AccountDetailsList(); } /** * Create an instance of {@link NameServerIPs } * */ public NameServerIPs createNameServerIPs() { return new NameServerIPs(); } /** * Create an instance of {@link TaskStatus } * */ public TaskStatus createTaskStatus() { return new TaskStatus(); } /** * Create an instance of {@link AllCountriesList } * */ public AllCountriesList createAllCountriesList() { return new AllCountriesList(); } /** * Create an instance of {@link DnssecKey } * */ public DnssecKey createDnssecKey() { return new DnssecKey(); } /** * Create an instance of {@link WebForwardPoolRecordDataGuid } * */ public WebForwardPoolRecordDataGuid createWebForwardPoolRecordDataGuid() { return new WebForwardPoolRecordDataGuid(); } /** * Create an instance of {@link SBRegionsList } * */ public SBRegionsList createSBRegionsList() { return new SBRegionsList(); } /** * Create an instance of {@link CustomHTTPHeaderDataGUID } * */ public CustomHTTPHeaderDataGUID createCustomHTTPHeaderDataGUID() { return new CustomHTTPHeaderDataGUID(); } /** * Create an instance of {@link ProbeListParams } * */ public ProbeListParams createProbeListParams() { return new ProbeListParams(); } /** * Create an instance of {@link GeolocationGroupData } * */ public GeolocationGroupData createGeolocationGroupData() { return new GeolocationGroupData(); } /** * Create an instance of {@link MonitoredRDPoolRecords } * */ public MonitoredRDPoolRecords createMonitoredRDPoolRecords() { return new MonitoredRDPoolRecords(); } /** * Create an instance of {@link HTTPTransaction } * */ public HTTPTransaction createHTTPTransaction() { return new HTTPTransaction(); } /** * Create an instance of {@link GroupData } * */ public GroupData createGroupData() { return new GroupData(); } /** * Create an instance of {@link ZoneList } * */ public ZoneList createZoneList() { return new ZoneList(); } /** * Create an instance of {@link SBAgentsList } * */ public SBAgentsList createSBAgentsList() { return new SBAgentsList(); } /** * Create an instance of {@link AlertAllFailRecordsList } * */ public AlertAllFailRecordsList createAlertAllFailRecordsList() { return new AlertAllFailRecordsList(); } /** * Create an instance of {@link AlertProbeDetails } * */ public AlertProbeDetails createAlertProbeDetails() { return new AlertProbeDetails(); } /** * Create an instance of {@link ResourceRecordTemplate } * */ public ResourceRecordTemplate createResourceRecordTemplate() { return new ResourceRecordTemplate(); } /** * Create an instance of {@link AccountLevelNotificationsData } * */ public AccountLevelNotificationsData createAccountLevelNotificationsData() { return new AccountLevelNotificationsData(); } /** * Create an instance of {@link DirectionalPoolData } * */ public DirectionalPoolData createDirectionalPoolData() { return new DirectionalPoolData(); } /** * Create an instance of {@link PoolUpdate } * */ public PoolUpdate createPoolUpdate() { return new PoolUpdate(); } /** * Create an instance of {@link PoolKey } * */ public PoolKey createPoolKey() { return new PoolKey(); } /** * Create an instance of {@link UserSummaryList } * */ public UserSummaryList createUserSummaryList() { return new UserSummaryList(); } /** * Create an instance of {@link ProbeAlertsData } * */ public ProbeAlertsData createProbeAlertsData() { return new ProbeAlertsData(); } /** * Create an instance of {@link PoolListParams } * */ public PoolListParams createPoolListParams() { return new PoolListParams(); } /** * Create an instance of {@link DNSTransaction } * */ public DNSTransaction createDNSTransaction() { return new DNSTransaction(); } /** * Create an instance of {@link UpdateDirectionalRecordData } * */ public UpdateDirectionalRecordData createUpdateDirectionalRecordData() { return new UpdateDirectionalRecordData(); } /** * Create an instance of {@link UserContactInfoValues } * */ public UserContactInfoValues createUserContactInfoValues() { return new UserContactInfoValues(); } /** * Create an instance of {@link GeneralNotificationStatusList } * */ public GeneralNotificationStatusList createGeneralNotificationStatusList() { return new GeneralNotificationStatusList(); } /** * Create an instance of {@link MonitoredRDPoolKey } * */ public MonitoredRDPoolKey createMonitoredRDPoolKey() { return new MonitoredRDPoolKey(); } /** * Create an instance of {@link ServiceInfo } * */ public ServiceInfo createServiceInfo() { return new ServiceInfo(); } /** * Create an instance of {@link DomainDnssecPolicies } * */ public DomainDnssecPolicies createDomainDnssecPolicies() { return new DomainDnssecPolicies(); } /** * Create an instance of {@link PINGTransaction } * */ public PINGTransaction createPINGTransaction() { return new PINGTransaction(); } /** * Create an instance of {@link RestrictIPList } * */ public RestrictIPList createRestrictIPList() { return new RestrictIPList(); } /** * Create an instance of {@link PoolRecordSpecData } * */ public PoolRecordSpecData createPoolRecordSpecData() { return new PoolRecordSpecData(); } /** * Create an instance of {@link AddressBookEntryList } * */ public AddressBookEntryList createAddressBookEntryList() { return new AddressBookEntryList(); } /** * Create an instance of {@link NameServerRecordSet } * */ public NameServerRecordSet createNameServerRecordSet() { return new NameServerRecordSet(); } /** * Create an instance of {@link RestrictIP } * */ public RestrictIP createRestrictIP() { return new RestrictIP(); } /** * Create an instance of {@link ResourceRecordTypeOrderInfo } * */ public ResourceRecordTypeOrderInfo createResourceRecordTypeOrderInfo() { return new ResourceRecordTypeOrderInfo(); } /** * Create an instance of {@link SourceIPGroupDetails } * */ public SourceIPGroupDetails createSourceIPGroupDetails() { return new SourceIPGroupDetails(); } /** * Create an instance of {@link WebForwardPoolRecordDataList } * */ public WebForwardPoolRecordDataList createWebForwardPoolRecordDataList() { return new WebForwardPoolRecordDataList(); } /** * Create an instance of {@link SMTPTransaction } * */ public SMTPTransaction createSMTPTransaction() { return new SMTPTransaction(); } /** * Create an instance of {@link AccountLevelGroup } * */ public AccountLevelGroup createAccountLevelGroup() { return new AccountLevelGroup(); } /** * Create an instance of {@link Regions } * */ public Regions createRegions() { return new Regions(); } /** * Create an instance of {@link Rule } * */ public Rule createRule() { return new Rule(); } /** * Create an instance of {@link PoolRecordData } * */ public PoolRecordData createPoolRecordData() { return new PoolRecordData(); } /** * Create an instance of {@link MonitoredRDPoolAdd } * */ public MonitoredRDPoolAdd createMonitoredRDPoolAdd() { return new MonitoredRDPoolAdd(); } /** * Create an instance of {@link PasswordVerificationInfo } * */ public PasswordVerificationInfo createPasswordVerificationInfo() { return new PasswordVerificationInfo(); } /** * Create an instance of {@link RDPoolConversionInfo } * */ public RDPoolConversionInfo createRDPoolConversionInfo() { return new RDPoolConversionInfo(); } /** * Create an instance of {@link ResourceRecordToCreate } * */ public ResourceRecordToCreate createResourceRecordToCreate() { return new ResourceRecordToCreate(); } /** * Create an instance of {@link SourceIPGroupData } * */ public SourceIPGroupData createSourceIPGroupData() { return new SourceIPGroupData(); } /** * Create an instance of {@link Record } * */ public Record createRecord() { return new Record(); } /** * Create an instance of {@link ARPoolRecordsList } * */ public ARPoolRecordsList createARPoolRecordsList() { return new ARPoolRecordsList(); } /** * Create an instance of {@link ARPoolRecordListKey } * */ public ARPoolRecordListKey createARPoolRecordListKey() { return new ARPoolRecordListKey(); } /** * Create an instance of {@link PasswordExpirationPreference } * */ public PasswordExpirationPreference createPasswordExpirationPreference() { return new PasswordExpirationPreference(); } /** * Create an instance of {@link AccountInfoData } * */ public AccountInfoData createAccountInfoData() { return new AccountInfoData(); } /** * Create an instance of {@link TCPTransaction } * */ public TCPTransaction createTCPTransaction() { return new TCPTransaction(); } /** * Create an instance of {@link NotificationInfo } * */ public NotificationInfo createNotificationInfo() { return new NotificationInfo(); } /** * Create an instance of {@link MailForwardRecord } * */ public MailForwardRecord createMailForwardRecord() { return new MailForwardRecord(); } /** * Create an instance of {@link JAXBElement }{@code <}{@link Long }{@code >}} * */ @XmlElementDecl(namespace = "http://schema.ultraservice.neustar.com/v01/", name = "ttl", scope = ProbeInfo2 .class) public JAXBElement<Long> createProbeInfo2Ttl(Long value) { return new JAXBElement<Long>(_ProbeInfo2Ttl_QNAME, Long.class, ProbeInfo2 .class, value); } /** * Create an instance of {@link JAXBElement }{@code <}{@link NameServerRecordSet }{@code >}} * */ @XmlElementDecl(namespace = "http://schema.ultraservice.neustar.com/v01/", name = "NameServerRecordSet", scope = NameServers.class) public JAXBElement<NameServerRecordSet> createNameServersNameServerRecordSet(NameServerRecordSet value) { return new JAXBElement<NameServerRecordSet>(_NameServersNameServerRecordSet_QNAME, NameServerRecordSet.class, NameServers.class, value); } /** * Create an instance of {@link JAXBElement }{@code <}{@link Long }{@code >}} * */ @XmlElementDecl(namespace = "http://schema.ultraservice.neustar.com/v01/", name = "ttl", scope = MonitoredRDPoolUpdate.class) public JAXBElement<Long> createMonitoredRDPoolUpdateTtl(Long value) { return new JAXBElement<Long>(_ProbeInfo2Ttl_QNAME, Long.class, MonitoredRDPoolUpdate.class, value); } }
apache-2.0
LetsBuildSomething/vmag_mobile
android/app/src/main/java/com/nativebasekitchensink/MainApplication.java
1640
package com.nativebasekitchensink; import android.app.Application; import android.util.Log; import com.facebook.react.ReactApplication; import com.remobile.toast.RCTToastPackage; import com.oblador.vectoricons.VectorIconsPackage; import com.brentvatne.react.ReactVideoPackage; import com.microsoft.codepush.react.CodePush; import com.facebook.react.ReactInstanceManager; import com.facebook.react.ReactNativeHost; import com.facebook.react.ReactPackage; import com.facebook.react.shell.MainReactPackage; import com.facebook.soloader.SoLoader; import com.brentvatne.react.ReactVideoPackage; import java.util.Arrays; import java.util.List; public class MainApplication extends Application implements ReactApplication { private final ReactNativeHost mReactNativeHost = new ReactNativeHost(this) { @Override protected String getJSBundleFile() { return CodePush.getJSBundleFile(); } @Override protected boolean getUseDeveloperSupport() { return BuildConfig.DEBUG; } @Override protected List<ReactPackage> getPackages() { return Arrays.<ReactPackage>asList( new MainReactPackage(), new RCTToastPackage(), new VectorIconsPackage(), new ReactVideoPackage(), new CodePush(getResources().getString(R.string.reactNativeCodePush_androidDeploymentKey), getApplicationContext(), BuildConfig.DEBUG) ); } }; @Override public ReactNativeHost getReactNativeHost() { return mReactNativeHost; } @Override public void onCreate() { super.onCreate(); SoLoader.init(this, /* native exopackage */ false); } }
apache-2.0
eSDK/esdk_cloud_fm_r3_native_java
source/FM/V1R3/esdk_fm_native_java/src/main/java/com/huawei/esdk/fusionmanager/local/impl/autogen/vm/AddCloudBackupUser.java
1688
package com.huawei.esdk.fusionmanager.local.impl.autogen.vm; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlRootElement; import javax.xml.bind.annotation.XmlType; /** * <p>Java class for anonymous complex type. * * <p>The following schema fragment specifies the expected content contained within this class. * * <pre> * &lt;complexType> * &lt;complexContent> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType"> * &lt;sequence> * &lt;element name="addCloudBackupUserReq" type="{http://request.model.vm.soap.business.vm.north.galaxmanager.com/xsd}AddCloudBackupUserReq" minOccurs="0"/> * &lt;/sequence> * &lt;/restriction> * &lt;/complexContent> * &lt;/complexType> * </pre> * * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "", propOrder = { "addCloudBackupUserReq" }) @XmlRootElement(name = "addCloudBackupUser") public class AddCloudBackupUser { protected AddCloudBackupUserReq addCloudBackupUserReq; /** * Gets the value of the addCloudBackupUserReq property. * * @return * possible object is * {@link AddCloudBackupUserReq } * */ public AddCloudBackupUserReq getAddCloudBackupUserReq() { return addCloudBackupUserReq; } /** * Sets the value of the addCloudBackupUserReq property. * * @param value * allowed object is * {@link AddCloudBackupUserReq } * */ public void setAddCloudBackupUserReq(AddCloudBackupUserReq value) { this.addCloudBackupUserReq = value; } }
apache-2.0
webos21/xi
java/jcl/src/java/java/util/concurrent/CancellationException.java
906
/* * Written by Doug Lea with assistance from members of JCP JSR-166 * Expert Group and released to the public domain, as explained at * http://creativecommons.org/licenses/publicdomain */ package java.util.concurrent; /** * Exception indicating that the result of a value-producing task, such as a * {@link FutureTask}, cannot be retrieved because the task was cancelled. * * @since 1.5 * @author Doug Lea */ public class CancellationException extends IllegalStateException { private static final long serialVersionUID = -9202173006928992231L; /** * Constructs a <tt>CancellationException</tt> with no detail message. */ public CancellationException() { } /** * Constructs a <tt>CancellationException</tt> with the specified detail * message. * * @param message * the detail message */ public CancellationException(String message) { super(message); } }
apache-2.0
shankarh/geode
geode-core/src/test/java/org/apache/geode/management/internal/cli/commands/ConfigCommandsDUnitTest.java
24836
/* * 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.geode.management.internal.cli.commands; import static org.apache.commons.io.FileUtils.deleteDirectory; import static org.apache.geode.distributed.ConfigurationProperties.ARCHIVE_FILE_SIZE_LIMIT; import static org.apache.geode.distributed.ConfigurationProperties.CLUSTER_CONFIGURATION_DIR; import static org.apache.geode.distributed.ConfigurationProperties.ENABLE_CLUSTER_CONFIGURATION; import static org.apache.geode.distributed.ConfigurationProperties.ENABLE_TIME_STATISTICS; import static org.apache.geode.distributed.ConfigurationProperties.GROUPS; import static org.apache.geode.distributed.ConfigurationProperties.HTTP_SERVICE_PORT; import static org.apache.geode.distributed.ConfigurationProperties.JMX_MANAGER; import static org.apache.geode.distributed.ConfigurationProperties.JMX_MANAGER_BIND_ADDRESS; import static org.apache.geode.distributed.ConfigurationProperties.JMX_MANAGER_PORT; import static org.apache.geode.distributed.ConfigurationProperties.JMX_MANAGER_START; import static org.apache.geode.distributed.ConfigurationProperties.LOCATORS; import static org.apache.geode.distributed.ConfigurationProperties.LOG_LEVEL; import static org.apache.geode.distributed.ConfigurationProperties.MCAST_PORT; import static org.apache.geode.distributed.ConfigurationProperties.NAME; import static org.apache.geode.distributed.ConfigurationProperties.STATISTIC_SAMPLING_ENABLED; import static org.apache.geode.internal.AvailablePort.SOCKET; import static org.apache.geode.internal.AvailablePort.getRandomAvailablePort; import static org.apache.geode.internal.AvailablePortHelper.getRandomAvailableTCPPorts; import static org.apache.geode.test.dunit.Assert.assertEquals; import static org.apache.geode.test.dunit.Assert.assertFalse; import static org.apache.geode.test.dunit.Assert.assertNotNull; import static org.apache.geode.test.dunit.Assert.assertTrue; import static org.apache.geode.test.dunit.Assert.fail; import static org.apache.geode.test.dunit.LogWriterUtils.getLogWriter; import static org.apache.geode.test.dunit.Wait.waitForCriterion; import org.apache.geode.cache.Cache; import org.apache.geode.cache.server.CacheServer; import org.apache.geode.distributed.Locator; import org.apache.geode.distributed.internal.DistributionConfig; import org.apache.geode.distributed.internal.InternalDistributedSystem; import org.apache.geode.distributed.internal.InternalLocator; import org.apache.geode.distributed.internal.ClusterConfigurationService; import org.apache.geode.internal.AvailablePortHelper; import org.apache.geode.internal.cache.GemFireCacheImpl; import org.apache.geode.internal.cache.xmlcache.CacheXmlGenerator; import org.apache.geode.internal.logging.LogWriterImpl; import org.apache.geode.management.cli.Result; import org.apache.geode.management.cli.Result.Status; import org.apache.geode.management.internal.cli.i18n.CliStrings; import org.apache.geode.management.internal.cli.remote.CommandProcessor; import org.apache.geode.management.internal.cli.result.CommandResult; import org.apache.geode.management.internal.cli.util.CommandStringBuilder; import org.apache.geode.test.dunit.Host; import org.apache.geode.test.dunit.IgnoredException; import org.apache.geode.test.dunit.SerializableCallable; import org.apache.geode.test.dunit.SerializableRunnable; import org.apache.geode.test.dunit.VM; import org.apache.geode.test.dunit.WaitCriterion; import org.apache.geode.test.junit.categories.DistributedTest; import org.apache.geode.test.junit.categories.FlakyTest; import org.junit.Test; import org.junit.experimental.categories.Category; import java.io.File; import java.io.FileReader; import java.io.IOException; import java.io.PrintWriter; import java.io.StringWriter; import java.lang.management.ManagementFactory; import java.lang.management.RuntimeMXBean; import java.net.InetAddress; import java.net.UnknownHostException; import java.util.Collections; import java.util.List; import java.util.Properties; /** * Dunit class for testing GemFire config commands : export config * * @since GemFire 7.0 */ @Category(DistributedTest.class) @SuppressWarnings("serial") public class ConfigCommandsDUnitTest extends CliCommandTestBase { private File managerConfigFile; private File managerPropsFile; private File vm1ConfigFile; private File vm1PropsFile; private File vm2ConfigFile; private File vm2PropsFile; private File shellConfigFile; private File shellPropsFile; private File subDir; private File subManagerConfigFile; @Override protected final void postSetUpCliCommandTestBase() throws Exception { this.managerConfigFile = this.temporaryFolder.newFile("Manager-cache.xml"); this.managerPropsFile = this.temporaryFolder.newFile("Manager-gf.properties"); this.vm1ConfigFile = this.temporaryFolder.newFile("VM1-cache.xml"); this.vm1PropsFile = this.temporaryFolder.newFile("VM1-gf.properties"); this.vm2ConfigFile = this.temporaryFolder.newFile("VM2-cache.xml"); this.vm2PropsFile = this.temporaryFolder.newFile("VM2-gf.properties"); this.shellConfigFile = this.temporaryFolder.newFile("Shell-cache.xml"); this.shellPropsFile = this.temporaryFolder.newFile("Shell-gf.properties"); this.subDir = this.temporaryFolder.newFolder(getName()); this.subManagerConfigFile = new File(this.subDir, this.managerConfigFile.getName()); } @Test public void testDescribeConfig() throws Exception { setUpJmxManagerOnVm0ThenConnect(null); final String controllerName = "Member2"; /* * Create properties for the controller VM */ final Properties localProps = new Properties(); localProps.setProperty(MCAST_PORT, "0"); localProps.setProperty(LOG_LEVEL, "info"); localProps.setProperty(STATISTIC_SAMPLING_ENABLED, "true"); localProps.setProperty(ENABLE_TIME_STATISTICS, "true"); localProps.setProperty(NAME, controllerName); localProps.setProperty(GROUPS, "G1"); getSystem(localProps); Cache cache = getCache(); int ports[] = getRandomAvailableTCPPorts(1); CacheServer cs = getCache().addCacheServer(); cs.setPort(ports[0]); cs.setMaxThreads(10); cs.setMaxConnections(9); cs.start(); try { RuntimeMXBean runtimeBean = ManagementFactory.getRuntimeMXBean(); List<String> jvmArgs = runtimeBean.getInputArguments(); getLogWriter().info("#SB Actual JVM Args : "); for (String jvmArg : jvmArgs) { getLogWriter().info("#SB JVM " + jvmArg); } InternalDistributedSystem system = (InternalDistributedSystem) cache.getDistributedSystem(); DistributionConfig config = system.getConfig(); config.setArchiveFileSizeLimit(1000); String command = CliStrings.DESCRIBE_CONFIG + " --member=" + controllerName; CommandProcessor cmdProcessor = new CommandProcessor(); cmdProcessor.createCommandStatement(command, Collections.EMPTY_MAP).process(); CommandResult cmdResult = executeCommand(command); String resultStr = commandResultToString(cmdResult); getLogWriter().info("#SB Hiding the defaults\n" + resultStr); assertEquals(true, cmdResult.getStatus().equals(Status.OK)); assertEquals(true, resultStr.contains("G1")); assertEquals(true, resultStr.contains(controllerName)); assertEquals(true, resultStr.contains(ARCHIVE_FILE_SIZE_LIMIT)); assertEquals(true, !resultStr.contains("copy-on-read")); cmdResult = executeCommand(command + " --" + CliStrings.DESCRIBE_CONFIG__HIDE__DEFAULTS + "=false"); resultStr = commandResultToString(cmdResult); getLogWriter().info("#SB No hiding of defaults\n" + resultStr); assertEquals(true, cmdResult.getStatus().equals(Status.OK)); assertEquals(true, resultStr.contains("is-server")); assertEquals(true, resultStr.contains(controllerName)); assertEquals(true, resultStr.contains("copy-on-read")); } finally { cs.stop(); } } @Category(FlakyTest.class) // GEODE-1449 @Test public void testExportConfig() throws Exception { Properties localProps = new Properties(); localProps.setProperty(NAME, "Manager"); localProps.setProperty(GROUPS, "Group1"); setUpJmxManagerOnVm0ThenConnect(localProps); // Create a cache in another VM (VM1) Host.getHost(0).getVM(1).invoke(new SerializableRunnable() { public void run() { Properties localProps = new Properties(); localProps.setProperty(NAME, "VM1"); localProps.setProperty(GROUPS, "Group2"); getSystem(localProps); getCache(); } }); // Create a cache in a 3rd VM (VM2) Host.getHost(0).getVM(2).invoke(new SerializableRunnable() { public void run() { Properties localProps = new Properties(); localProps.setProperty(NAME, "VM2"); localProps.setProperty(GROUPS, "Group2"); getSystem(localProps); getCache(); } }); // Create a cache in the local VM localProps = new Properties(); localProps.setProperty(NAME, "Shell"); getSystem(localProps); Cache cache = getCache(); // Test export config for all members deleteTestFiles(); CommandResult cmdResult = executeCommand("export config --dir=" + this.temporaryFolder.getRoot().getAbsolutePath()); assertEquals(Result.Status.OK, cmdResult.getStatus()); assertTrue(this.managerConfigFile + " should exist", this.managerConfigFile.exists()); assertTrue(this.managerPropsFile + " should exist", this.managerPropsFile.exists()); assertTrue(this.vm1ConfigFile + " should exist", this.vm1ConfigFile.exists()); assertTrue(this.vm1PropsFile + " should exist", this.vm1PropsFile.exists()); assertTrue(this.vm2ConfigFile + " should exist", this.vm2ConfigFile.exists()); assertTrue(this.vm2PropsFile + " should exist", this.vm2PropsFile.exists()); assertTrue(this.shellConfigFile + " should exist", this.shellConfigFile.exists()); assertTrue(this.shellPropsFile + " should exist", this.shellPropsFile.exists()); // Test exporting member deleteTestFiles(); cmdResult = executeCommand( "export config --member=Manager --dir=" + this.temporaryFolder.getRoot().getAbsolutePath()); assertEquals(Result.Status.OK, cmdResult.getStatus()); assertTrue(this.managerConfigFile + " should exist", this.managerConfigFile.exists()); assertFalse(this.vm1ConfigFile + " should not exist", this.vm1ConfigFile.exists()); assertFalse(this.vm2ConfigFile + " should not exist", this.vm2ConfigFile.exists()); assertFalse(this.shellConfigFile + " should not exist", this.shellConfigFile.exists()); // Test exporting group deleteTestFiles(); cmdResult = executeCommand( "export config --group=Group2 --dir=" + this.temporaryFolder.getRoot().getAbsolutePath()); assertEquals(Result.Status.OK, cmdResult.getStatus()); assertFalse(this.managerConfigFile + " should not exist", this.managerConfigFile.exists()); assertTrue(this.vm1ConfigFile + " should exist", this.vm1ConfigFile.exists()); assertTrue(this.vm2ConfigFile + " should exist", this.vm2ConfigFile.exists()); assertFalse(this.shellConfigFile + " should not exist", this.shellConfigFile.exists()); // Test export to directory deleteTestFiles(); cmdResult = executeCommand("export config --dir=" + this.subDir.getAbsolutePath()); assertEquals(Result.Status.OK, cmdResult.getStatus()); assertFalse(this.managerConfigFile.exists()); assertTrue(this.subManagerConfigFile.exists()); // Test the contents of the file StringWriter stringWriter = new StringWriter(); PrintWriter printWriter = new PrintWriter(stringWriter); CacheXmlGenerator.generate(cache, printWriter, false, false, false); String configToMatch = stringWriter.toString(); deleteTestFiles(); cmdResult = executeCommand( "export config --member=Shell --dir=" + this.temporaryFolder.getRoot().getAbsolutePath()); assertEquals(Result.Status.OK, cmdResult.getStatus()); char[] fileContents = new char[configToMatch.length()]; FileReader reader = new FileReader(this.shellConfigFile); reader.read(fileContents); assertEquals(configToMatch, new String(fileContents)); } @Test public void testAlterRuntimeConfig() throws Exception { final String controller = "controller"; String directory = this.temporaryFolder.newFolder(controller).getAbsolutePath(); String statFilePath = new File(directory, "stat.gfs").getAbsolutePath(); setUpJmxManagerOnVm0ThenConnect(null); Properties localProps = new Properties(); localProps.setProperty(NAME, controller); localProps.setProperty(LOG_LEVEL, "error"); getSystem(localProps); final GemFireCacheImpl cache = (GemFireCacheImpl) getCache(); final DistributionConfig config = cache.getSystem().getConfig(); CommandStringBuilder csb = new CommandStringBuilder(CliStrings.ALTER_RUNTIME_CONFIG); csb.addOption(CliStrings.MEMBER, controller); csb.addOption(CliStrings.ALTER_RUNTIME_CONFIG__LOG__LEVEL, "info"); csb.addOption(CliStrings.ALTER_RUNTIME_CONFIG__LOG__FILE__SIZE__LIMIT, "50"); csb.addOption(CliStrings.ALTER_RUNTIME_CONFIG__ARCHIVE__DISK__SPACE__LIMIT, "32"); csb.addOption(CliStrings.ALTER_RUNTIME_CONFIG__ARCHIVE__FILE__SIZE__LIMIT, "49"); csb.addOption(CliStrings.ALTER_RUNTIME_CONFIG__STATISTIC__SAMPLE__RATE, "2000"); csb.addOption(CliStrings.ALTER_RUNTIME_CONFIG__STATISTIC__ARCHIVE__FILE, statFilePath); csb.addOption(CliStrings.ALTER_RUNTIME_CONFIG__STATISTIC__SAMPLING__ENABLED, "true"); csb.addOption(CliStrings.ALTER_RUNTIME_CONFIG__LOG__DISK__SPACE__LIMIT, "10"); CommandResult cmdResult = executeCommand(csb.getCommandString()); String resultString = commandResultToString(cmdResult); getLogWriter().info("Result\n"); getLogWriter().info(resultString); assertEquals(true, cmdResult.getStatus().equals(Status.OK)); assertEquals(LogWriterImpl.INFO_LEVEL, config.getLogLevel()); assertEquals(50, config.getLogFileSizeLimit()); assertEquals(32, config.getArchiveDiskSpaceLimit()); assertEquals(2000, config.getStatisticSampleRate()); assertEquals("stat.gfs", config.getStatisticArchiveFile().getName()); assertEquals(true, config.getStatisticSamplingEnabled()); assertEquals(10, config.getLogDiskSpaceLimit()); CommandProcessor commandProcessor = new CommandProcessor(); Result result = commandProcessor.createCommandStatement("alter runtime", Collections.EMPTY_MAP).process(); } @Test public void testAlterRuntimeConfigRandom() throws Exception { IgnoredException.addIgnoredException( "java.lang.IllegalArgumentException: Could not set \"log-disk-space-limit\""); final String member1 = "VM1"; final String controller = "controller"; setUpJmxManagerOnVm0ThenConnect(null); Properties localProps = new Properties(); localProps.setProperty(NAME, controller); localProps.setProperty(LOG_LEVEL, "error"); getSystem(localProps); final GemFireCacheImpl cache = (GemFireCacheImpl) getCache(); final DistributionConfig config = cache.getSystem().getConfig(); Host.getHost(0).getVM(1).invoke(new SerializableRunnable() { public void run() { Properties localProps = new Properties(); localProps.setProperty(NAME, member1); getSystem(localProps); getCache(); } }); CommandStringBuilder csb = new CommandStringBuilder(CliStrings.ALTER_RUNTIME_CONFIG); CommandResult cmdResult = executeCommand(csb.getCommandString()); String resultAsString = commandResultToString(cmdResult); assertEquals(true, cmdResult.getStatus().equals(Status.ERROR)); assertTrue(resultAsString.contains(CliStrings.ALTER_RUNTIME_CONFIG__RELEVANT__OPTION__MESSAGE)); csb = new CommandStringBuilder(CliStrings.ALTER_RUNTIME_CONFIG); csb.addOption(CliStrings.ALTER_RUNTIME_CONFIG__LOG__DISK__SPACE__LIMIT, "2000000000"); cmdResult = executeCommand(csb.getCommandString()); resultAsString = commandResultToString(cmdResult); assertEquals(true, cmdResult.getStatus().equals(Status.ERROR)); assertTrue( resultAsString.contains("Could not set \"log-disk-space-limit\" to \"2,000,000,000\"")); } @Test public void testAlterRuntimeConfigOnAllMembers() throws Exception { final String member1 = "VM1"; final String controller = "controller"; String controllerDirectory = this.temporaryFolder.newFolder(controller).getAbsolutePath(); String controllerStatFilePath = new File(controllerDirectory, "stat.gfs").getAbsolutePath(); setUpJmxManagerOnVm0ThenConnect(null); Properties localProps = new Properties(); localProps.setProperty(NAME, controller); localProps.setProperty(LOG_LEVEL, "error"); getSystem(localProps); final GemFireCacheImpl cache = (GemFireCacheImpl) getCache(); final DistributionConfig config = cache.getSystem().getConfig(); Host.getHost(0).getVM(1).invoke(new SerializableRunnable() { public void run() { Properties localProps = new Properties(); localProps.setProperty(NAME, member1); getSystem(localProps); Cache cache = getCache(); } }); CommandStringBuilder csb = new CommandStringBuilder(CliStrings.ALTER_RUNTIME_CONFIG); csb.addOption(CliStrings.ALTER_RUNTIME_CONFIG__LOG__LEVEL, "info"); csb.addOption(CliStrings.ALTER_RUNTIME_CONFIG__LOG__FILE__SIZE__LIMIT, "50"); csb.addOption(CliStrings.ALTER_RUNTIME_CONFIG__ARCHIVE__DISK__SPACE__LIMIT, "32"); csb.addOption(CliStrings.ALTER_RUNTIME_CONFIG__ARCHIVE__FILE__SIZE__LIMIT, "49"); csb.addOption(CliStrings.ALTER_RUNTIME_CONFIG__STATISTIC__SAMPLE__RATE, "2000"); csb.addOption(CliStrings.ALTER_RUNTIME_CONFIG__STATISTIC__ARCHIVE__FILE, controllerStatFilePath); csb.addOption(CliStrings.ALTER_RUNTIME_CONFIG__STATISTIC__SAMPLING__ENABLED, "true"); csb.addOption(CliStrings.ALTER_RUNTIME_CONFIG__LOG__DISK__SPACE__LIMIT, "10"); CommandResult cmdResult = executeCommand(csb.getCommandString()); String resultString = commandResultToString(cmdResult); getLogWriter().info("#SB Result\n"); getLogWriter().info(resultString); assertEquals(true, cmdResult.getStatus().equals(Status.OK)); assertEquals(LogWriterImpl.INFO_LEVEL, config.getLogLevel()); assertEquals(50, config.getLogFileSizeLimit()); assertEquals(49, config.getArchiveFileSizeLimit()); assertEquals(32, config.getArchiveDiskSpaceLimit()); assertEquals(2000, config.getStatisticSampleRate()); assertEquals("stat.gfs", config.getStatisticArchiveFile().getName()); assertEquals(true, config.getStatisticSamplingEnabled()); assertEquals(10, config.getLogDiskSpaceLimit()); // Validate the changes in the vm1 Host.getHost(0).getVM(1).invoke(new SerializableRunnable() { public void run() { GemFireCacheImpl cacheVM1 = (GemFireCacheImpl) getCache(); DistributionConfig configVM1 = cacheVM1.getSystem().getConfig(); assertEquals(LogWriterImpl.INFO_LEVEL, configVM1.getLogLevel()); assertEquals(50, configVM1.getLogFileSizeLimit()); assertEquals(49, configVM1.getArchiveFileSizeLimit()); assertEquals(32, configVM1.getArchiveDiskSpaceLimit()); assertEquals(2000, configVM1.getStatisticSampleRate()); assertEquals("stat.gfs", configVM1.getStatisticArchiveFile().getName()); assertEquals(true, configVM1.getStatisticSamplingEnabled()); assertEquals(10, configVM1.getLogDiskSpaceLimit()); } }); } /** * Asserts that altering the runtime config correctly updates the shared configuration. */ @Test public void testAlterUpdatesSharedConfig() throws Exception { final String groupName = getName(); final int[] ports = AvailablePortHelper.getRandomAvailableTCPPorts(2); jmxPort = ports[0]; httpPort = ports[1]; try { jmxHost = InetAddress.getLocalHost().getHostName(); } catch (UnknownHostException ignore) { jmxHost = "localhost"; } // Start the Locator and wait for shared configuration to be available final int locatorPort = getRandomAvailablePort(SOCKET); final String locatorDirectory = this.temporaryFolder.newFolder("Locator").getAbsolutePath(); final Properties locatorProps = new Properties(); locatorProps.setProperty(NAME, "Locator"); locatorProps.setProperty(MCAST_PORT, "0"); locatorProps.setProperty(ENABLE_CLUSTER_CONFIGURATION, "true"); locatorProps.setProperty(CLUSTER_CONFIGURATION_DIR, locatorDirectory); locatorProps.setProperty(JMX_MANAGER, "true"); locatorProps.setProperty(JMX_MANAGER_START, "true"); locatorProps.setProperty(JMX_MANAGER_BIND_ADDRESS, String.valueOf(jmxHost)); locatorProps.setProperty(JMX_MANAGER_PORT, String.valueOf(jmxPort)); locatorProps.setProperty(HTTP_SERVICE_PORT, String.valueOf(httpPort)); Host.getHost(0).getVM(0).invoke(new SerializableRunnable() { @Override public void run() { final File locatorLogFile = new File(locatorDirectory, "locator-" + locatorPort + ".log"); try { final InternalLocator locator = (InternalLocator) Locator.startLocatorAndDS(locatorPort, locatorLogFile, null, locatorProps); WaitCriterion wc = new WaitCriterion() { @Override public boolean done() { return locator.isSharedConfigurationRunning(); } @Override public String description() { return "Waiting for shared configuration to be started"; } }; waitForCriterion(wc, 5000, 500, true); } catch (IOException e) { fail("Unable to create a locator with a shared configuration", e); } } }); connect(jmxHost, jmxPort, httpPort, getDefaultShell()); // Create a cache in VM 1 VM vm = Host.getHost(0).getVM(1); vm.invoke(new SerializableCallable() { @Override public Object call() throws Exception { Properties localProps = new Properties(); localProps.setProperty(MCAST_PORT, "0"); localProps.setProperty(LOCATORS, "localhost[" + locatorPort + "]"); localProps.setProperty(LOG_LEVEL, "error"); localProps.setProperty(GROUPS, groupName); getSystem(localProps); assertNotNull(getCache()); assertEquals("error", basicGetSystem().getConfig().getAttribute(LOG_LEVEL)); return null; } }); // Test altering the runtime config CommandStringBuilder commandStringBuilder = new CommandStringBuilder(CliStrings.ALTER_RUNTIME_CONFIG); commandStringBuilder.addOption(CliStrings.GROUP, groupName); commandStringBuilder.addOption(CliStrings.ALTER_RUNTIME_CONFIG__LOG__LEVEL, "fine"); CommandResult cmdResult = executeCommand(commandStringBuilder.toString()); assertEquals(Result.Status.OK, cmdResult.getStatus()); // Make sure the shared config was updated Host.getHost(0).getVM(0).invoke(new SerializableRunnable() { @Override public void run() { ClusterConfigurationService sharedConfig = ((InternalLocator) Locator.getLocator()).getSharedConfiguration(); Properties gemfireProperties = null; try { gemfireProperties = sharedConfig.getConfiguration(groupName).getGemfireProperties(); } catch (Exception e) { fail("Error occurred in cluster configuration service", e); } assertEquals("fine", gemfireProperties.get(LOG_LEVEL)); } }); } private void deleteTestFiles() throws IOException { this.managerConfigFile.delete(); this.managerPropsFile.delete(); this.vm1ConfigFile.delete(); this.vm1PropsFile.delete(); this.vm2ConfigFile.delete(); this.vm2PropsFile.delete(); this.shellConfigFile.delete(); this.shellPropsFile.delete(); deleteDirectory(this.subDir); } }
apache-2.0
googleads/google-ads-java
google-ads-stubs-v8/src/main/java/com/google/ads/googleads/v8/services/CampaignExtensionSettingServiceProto.java
10660
// Generated by the protocol buffer compiler. DO NOT EDIT! // source: google/ads/googleads/v8/services/campaign_extension_setting_service.proto package com.google.ads.googleads.v8.services; public final class CampaignExtensionSettingServiceProto { private CampaignExtensionSettingServiceProto() {} public static void registerAllExtensions( com.google.protobuf.ExtensionRegistryLite registry) { } public static void registerAllExtensions( com.google.protobuf.ExtensionRegistry registry) { registerAllExtensions( (com.google.protobuf.ExtensionRegistryLite) registry); } static final com.google.protobuf.Descriptors.Descriptor internal_static_google_ads_googleads_v8_services_GetCampaignExtensionSettingRequest_descriptor; static final com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internal_static_google_ads_googleads_v8_services_GetCampaignExtensionSettingRequest_fieldAccessorTable; static final com.google.protobuf.Descriptors.Descriptor internal_static_google_ads_googleads_v8_services_MutateCampaignExtensionSettingsRequest_descriptor; static final com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internal_static_google_ads_googleads_v8_services_MutateCampaignExtensionSettingsRequest_fieldAccessorTable; static final com.google.protobuf.Descriptors.Descriptor internal_static_google_ads_googleads_v8_services_CampaignExtensionSettingOperation_descriptor; static final com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internal_static_google_ads_googleads_v8_services_CampaignExtensionSettingOperation_fieldAccessorTable; static final com.google.protobuf.Descriptors.Descriptor internal_static_google_ads_googleads_v8_services_MutateCampaignExtensionSettingsResponse_descriptor; static final com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internal_static_google_ads_googleads_v8_services_MutateCampaignExtensionSettingsResponse_fieldAccessorTable; static final com.google.protobuf.Descriptors.Descriptor internal_static_google_ads_googleads_v8_services_MutateCampaignExtensionSettingResult_descriptor; static final com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internal_static_google_ads_googleads_v8_services_MutateCampaignExtensionSettingResult_fieldAccessorTable; public static com.google.protobuf.Descriptors.FileDescriptor getDescriptor() { return descriptor; } private static com.google.protobuf.Descriptors.FileDescriptor descriptor; static { java.lang.String[] descriptorData = { "\nIgoogle/ads/googleads/v8/services/campa" + "ign_extension_setting_service.proto\022 goo" + "gle.ads.googleads.v8.services\0329google/ad" + "s/googleads/v8/enums/response_content_ty" + "pe.proto\032Bgoogle/ads/googleads/v8/resour" + "ces/campaign_extension_setting.proto\032\034go" + "ogle/api/annotations.proto\032\027google/api/c" + "lient.proto\032\037google/api/field_behavior.p" + "roto\032\031google/api/resource.proto\032 google/" + "protobuf/field_mask.proto\032\027google/rpc/st" + "atus.proto\"v\n\"GetCampaignExtensionSettin" + "gRequest\022P\n\rresource_name\030\001 \001(\tB9\340A\002\372A3\n" + "1googleads.googleapis.com/CampaignExtens" + "ionSetting\"\273\002\n&MutateCampaignExtensionSe" + "ttingsRequest\022\030\n\013customer_id\030\001 \001(\tB\003\340A\002\022" + "\\\n\noperations\030\002 \003(\0132C.google.ads.googlea" + "ds.v8.services.CampaignExtensionSettingO" + "perationB\003\340A\002\022\027\n\017partial_failure\030\003 \001(\010\022\025" + "\n\rvalidate_only\030\004 \001(\010\022i\n\025response_conten" + "t_type\030\005 \001(\0162J.google.ads.googleads.v8.e" + "nums.ResponseContentTypeEnum.ResponseCon" + "tentType\"\221\002\n!CampaignExtensionSettingOpe" + "ration\022/\n\013update_mask\030\004 \001(\0132\032.google.pro" + "tobuf.FieldMask\022M\n\006create\030\001 \001(\0132;.google" + ".ads.googleads.v8.resources.CampaignExte" + "nsionSettingH\000\022M\n\006update\030\002 \001(\0132;.google." + "ads.googleads.v8.resources.CampaignExten" + "sionSettingH\000\022\020\n\006remove\030\003 \001(\tH\000B\013\n\topera" + "tion\"\265\001\n\'MutateCampaignExtensionSettings" + "Response\0221\n\025partial_failure_error\030\003 \001(\0132" + "\022.google.rpc.Status\022W\n\007results\030\002 \003(\0132F.g" + "oogle.ads.googleads.v8.services.MutateCa" + "mpaignExtensionSettingResult\"\236\001\n$MutateC" + "ampaignExtensionSettingResult\022\025\n\rresourc" + "e_name\030\001 \001(\t\022_\n\032campaign_extension_setti" + "ng\030\002 \001(\0132;.google.ads.googleads.v8.resou" + "rces.CampaignExtensionSetting2\375\004\n\037Campai" + "gnExtensionSettingService\022\365\001\n\033GetCampaig" + "nExtensionSetting\022D.google.ads.googleads" + ".v8.services.GetCampaignExtensionSetting" + "Request\032;.google.ads.googleads.v8.resour" + "ces.CampaignExtensionSetting\"S\202\323\344\223\002=\022;/v" + "8/{resource_name=customers/*/campaignExt" + "ensionSettings/*}\332A\rresource_name\022\232\002\n\037Mu" + "tateCampaignExtensionSettings\022H.google.a" + "ds.googleads.v8.services.MutateCampaignE" + "xtensionSettingsRequest\032I.google.ads.goo" + "gleads.v8.services.MutateCampaignExtensi" + "onSettingsResponse\"b\202\323\344\223\002C\">/v8/customer" + "s/{customer_id=*}/campaignExtensionSetti" + "ngs:mutate:\001*\332A\026customer_id,operations\032E" + "\312A\030googleads.googleapis.com\322A\'https://ww" + "w.googleapis.com/auth/adwordsB\213\002\n$com.go" + "ogle.ads.googleads.v8.servicesB$Campaign" + "ExtensionSettingServiceProtoP\001ZHgoogle.g" + "olang.org/genproto/googleapis/ads/google" + "ads/v8/services;services\242\002\003GAA\252\002 Google." + "Ads.GoogleAds.V8.Services\312\002 Google\\Ads\\G" + "oogleAds\\V8\\Services\352\002$Google::Ads::Goog" + "leAds::V8::Servicesb\006proto3" }; descriptor = com.google.protobuf.Descriptors.FileDescriptor .internalBuildGeneratedFileFrom(descriptorData, new com.google.protobuf.Descriptors.FileDescriptor[] { com.google.ads.googleads.v8.enums.ResponseContentTypeProto.getDescriptor(), com.google.ads.googleads.v8.resources.CampaignExtensionSettingProto.getDescriptor(), com.google.api.AnnotationsProto.getDescriptor(), com.google.api.ClientProto.getDescriptor(), com.google.api.FieldBehaviorProto.getDescriptor(), com.google.api.ResourceProto.getDescriptor(), com.google.protobuf.FieldMaskProto.getDescriptor(), com.google.rpc.StatusProto.getDescriptor(), }); internal_static_google_ads_googleads_v8_services_GetCampaignExtensionSettingRequest_descriptor = getDescriptor().getMessageTypes().get(0); internal_static_google_ads_googleads_v8_services_GetCampaignExtensionSettingRequest_fieldAccessorTable = new com.google.protobuf.GeneratedMessageV3.FieldAccessorTable( internal_static_google_ads_googleads_v8_services_GetCampaignExtensionSettingRequest_descriptor, new java.lang.String[] { "ResourceName", }); internal_static_google_ads_googleads_v8_services_MutateCampaignExtensionSettingsRequest_descriptor = getDescriptor().getMessageTypes().get(1); internal_static_google_ads_googleads_v8_services_MutateCampaignExtensionSettingsRequest_fieldAccessorTable = new com.google.protobuf.GeneratedMessageV3.FieldAccessorTable( internal_static_google_ads_googleads_v8_services_MutateCampaignExtensionSettingsRequest_descriptor, new java.lang.String[] { "CustomerId", "Operations", "PartialFailure", "ValidateOnly", "ResponseContentType", }); internal_static_google_ads_googleads_v8_services_CampaignExtensionSettingOperation_descriptor = getDescriptor().getMessageTypes().get(2); internal_static_google_ads_googleads_v8_services_CampaignExtensionSettingOperation_fieldAccessorTable = new com.google.protobuf.GeneratedMessageV3.FieldAccessorTable( internal_static_google_ads_googleads_v8_services_CampaignExtensionSettingOperation_descriptor, new java.lang.String[] { "UpdateMask", "Create", "Update", "Remove", "Operation", }); internal_static_google_ads_googleads_v8_services_MutateCampaignExtensionSettingsResponse_descriptor = getDescriptor().getMessageTypes().get(3); internal_static_google_ads_googleads_v8_services_MutateCampaignExtensionSettingsResponse_fieldAccessorTable = new com.google.protobuf.GeneratedMessageV3.FieldAccessorTable( internal_static_google_ads_googleads_v8_services_MutateCampaignExtensionSettingsResponse_descriptor, new java.lang.String[] { "PartialFailureError", "Results", }); internal_static_google_ads_googleads_v8_services_MutateCampaignExtensionSettingResult_descriptor = getDescriptor().getMessageTypes().get(4); internal_static_google_ads_googleads_v8_services_MutateCampaignExtensionSettingResult_fieldAccessorTable = new com.google.protobuf.GeneratedMessageV3.FieldAccessorTable( internal_static_google_ads_googleads_v8_services_MutateCampaignExtensionSettingResult_descriptor, new java.lang.String[] { "ResourceName", "CampaignExtensionSetting", }); com.google.protobuf.ExtensionRegistry registry = com.google.protobuf.ExtensionRegistry.newInstance(); registry.add(com.google.api.ClientProto.defaultHost); registry.add(com.google.api.FieldBehaviorProto.fieldBehavior); registry.add(com.google.api.AnnotationsProto.http); registry.add(com.google.api.ClientProto.methodSignature); registry.add(com.google.api.ClientProto.oauthScopes); registry.add(com.google.api.ResourceProto.resourceReference); com.google.protobuf.Descriptors.FileDescriptor .internalUpdateFileDescriptor(descriptor, registry); com.google.ads.googleads.v8.enums.ResponseContentTypeProto.getDescriptor(); com.google.ads.googleads.v8.resources.CampaignExtensionSettingProto.getDescriptor(); com.google.api.AnnotationsProto.getDescriptor(); com.google.api.ClientProto.getDescriptor(); com.google.api.FieldBehaviorProto.getDescriptor(); com.google.api.ResourceProto.getDescriptor(); com.google.protobuf.FieldMaskProto.getDescriptor(); com.google.rpc.StatusProto.getDescriptor(); } // @@protoc_insertion_point(outer_class_scope) }
apache-2.0
zhanjiashu/ZhihuDialyM
app/src/main/java/io/gitcafe/zhanjiashu/newzhihudialy/activity/MainActivity.java
5589
package io.gitcafe.zhanjiashu.newzhihudialy.activity; import android.content.res.ColorStateList; import android.support.design.widget.Snackbar; import android.support.v4.app.Fragment; import android.support.v4.view.GravityCompat; import android.support.v4.widget.DrawerLayout; import android.os.Bundle; import android.view.LayoutInflater; import android.view.MenuItem; import android.view.View; import android.widget.AdapterView; import android.widget.ListView; import java.util.List; import butterknife.ButterKnife; import butterknife.InjectView; import io.gitcafe.zhanjiashu.newzhihudialy.R; import io.gitcafe.zhanjiashu.newzhihudialy.adapter.MenuListAdapter; import io.gitcafe.zhanjiashu.newzhihudialy.model.ThemeEntity; import io.gitcafe.zhanjiashu.newzhihudialy.model.ThemeListEntity; import io.gitcafe.zhanjiashu.newzhihudialy.task.FetchThemesTask; import io.gitcafe.zhanjiashu.newzhihudialy.task.FetchTask; import io.gitcafe.zhanjiashu.newzhihudialy.fragment.HomeFragment; import io.gitcafe.zhanjiashu.newzhihudialy.fragment.ThemeFragment; public class MainActivity extends BaseActivity { private static final String TAG = "MainActivityTAG"; @InjectView(R.id.dl_drawer) DrawerLayout mDrawerLayout; @InjectView(R.id.lv_left_nav) ListView mLeftNavListView; private List<ThemeEntity> mThemeEntities; private MenuListAdapter mAdapter; private Fragment mCurrentFragment; private int mCheckedMenuItemPosition = 1; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); ButterKnife.inject(this); setLeftNav(); if (savedInstanceState == null) { replaceFragment(new HomeFragment()); } } private void setLeftNav() { mAdapter = new MenuListAdapter(MainActivity.this, mThemeEntities); mLeftNavListView.setAdapter(mAdapter); mLeftNavListView.addHeaderView(LayoutInflater.from(this).inflate(R.layout.header_nav_user, mLeftNavListView, false)); mLeftNavListView.setItemChecked(mCheckedMenuItemPosition, true); mLeftNavListView.setSelector(R.drawable.bg_nav_list_item); mLeftNavListView.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> adapterView, View view, int position, long l) { if (position == 0) { mLeftNavListView.setItemChecked(mCheckedMenuItemPosition, true); return; } mCheckedMenuItemPosition = mLeftNavListView.getCheckedItemPosition(); int newPosition = position - 1; Fragment fragment; if (newPosition == 0) { fragment = new HomeFragment(); } else { fragment = ThemeFragment.newInstance(mAdapter.getItem(newPosition).getId()); } replaceFragment(fragment); mDrawerLayout.closeDrawers(); } }); FetchThemesTask task = new FetchThemesTask(this, true); task.execute(new FetchTask.FetchCallback<ThemeListEntity>() { @Override public void onFetchResponse(ThemeListEntity themeListEntity) { mThemeEntities = themeListEntity.getOthers(); ThemeEntity entity = new ThemeEntity(); entity.setName("首页"); entity.setThumbnail("assets://menu_home.png"); mThemeEntities.add(0, entity); mAdapter.replaceAll(mThemeEntities); } }); } @Override public boolean onOptionsItemSelected(MenuItem item) { int id = item.getItemId(); if (id == android.R.id.home) { mDrawerLayout.openDrawer(GravityCompat.START); return true; } return super.onOptionsItemSelected(item); } @Override public void onBackPressed() { if (mDrawerLayout.isDrawerOpen(GravityCompat.START)) { mDrawerLayout.closeDrawers(); return; } if (mCurrentFragment instanceof ThemeFragment) { mLeftNavListView.setItemChecked(1, true); replaceFragment(new HomeFragment()); return; } if (mCurrentFragment instanceof HomeFragment) { Snackbar .make(findViewById(android.R.id.content), "是否退出程序?", Snackbar.LENGTH_LONG) .setAction("退出", new View.OnClickListener() { @Override public void onClick(View view) { MainActivity.this.finish(); } }) .setActionTextColor(ColorStateList.valueOf(getResources().getColor(R.color.material_colorPrimary))) .show(); return; } super.onBackPressed(); } @Override protected void onDestroy() { super.onDestroy(); // 退出程序时清除所有的WebView缓存 //new WebView(MainActivity.this).clearCache(true); } private void replaceFragment(Fragment fragment) { if (findViewById(R.id.fl_container) != null && fragment != null) { getSupportFragmentManager() .beginTransaction() .replace(R.id.fl_container, fragment) .commit(); mCurrentFragment = fragment; } } }
apache-2.0
gcolin/juikito
cdi/src/main/java/net/gcolin/di/cdi/internal/context/SessionContext.java
2236
/* * 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 net.gcolin.di.cdi.internal.context; import net.gcolin.di.cdi.internal.BeanManagerImpl; import net.gcolin.di.cdi.internal.ListenerData; import java.lang.annotation.Annotation; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; import javax.enterprise.context.ContextNotActiveException; import javax.enterprise.context.SessionScoped; import javax.servlet.http.HttpSession; /** * The context of the session. * * <p> * References are stored in the HttpSession attributes. * </p> * * @author Gaël COLIN * @since 1.0 */ public class SessionContext extends PassivableContext { private ListenerData ld; public SessionContext(BeanManagerImpl bm) { super(bm); this.ld = bm.getListenerData(); } @Override public Class<? extends Annotation> getScope() { return SessionScoped.class; } @Override public boolean isActive() { return ld.getSession() != null; } @SuppressWarnings("unchecked") @Override public Map<String, ContextualInstance<Object>> getRegistry() { HttpSession session = ld.getSession(); if (session == null) { throw new ContextNotActiveException(); } Map<String, ContextualInstance<Object>> registry = (Map<String, ContextualInstance<Object>>) session.getAttribute(CONTEXT); if (registry == null) { registry = new ConcurrentHashMap<>(); session.setAttribute(CONTEXT, registry); } return registry; } }
apache-2.0
joyjy/ChalcidQ
src/main/java/im/joyjy/chalcidq/trans/impls/hornetq/packets/Ping.java
486
package im.joyjy.chalcidq.trans.impls.hornetq.packets; import im.joyjy.chalcidq.trans.impls.hornetq.HornetQMessage; import io.netty.buffer.ByteBuf; public class Ping extends HornetQMessage { public static final int TTL = 60000; private long ttl; public Ping() { super(HornetQMessage.PING); ttl = TTL; } @Override public void encodeBody(ByteBuf buf) { buf.writeLong(ttl); } @Override public void decode(ByteBuf in) { super.decode(in); ttl = in.readLong(); } }
apache-2.0
remibergsma/cosmic
cosmic-core/api/src/main/java/com/cloud/api/command/admin/network/DeletePhysicalNetworkCmd.java
2874
package com.cloud.api.command.admin.network; import com.cloud.api.APICommand; import com.cloud.api.ApiCommandJobType; import com.cloud.api.ApiConstants; import com.cloud.api.ApiErrorCode; import com.cloud.api.BaseAsyncCmd; import com.cloud.api.Parameter; import com.cloud.api.ServerApiException; import com.cloud.api.response.PhysicalNetworkResponse; import com.cloud.api.response.SuccessResponse; import com.cloud.context.CallContext; import com.cloud.event.EventTypes; import com.cloud.user.Account; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @APICommand(name = "deletePhysicalNetwork", description = "Deletes a Physical Network.", responseObject = SuccessResponse.class, since = "3.0.0", requestHasSensitiveInfo = false, responseHasSensitiveInfo = false) public class DeletePhysicalNetworkCmd extends BaseAsyncCmd { public static final Logger s_logger = LoggerFactory.getLogger(DeletePhysicalNetworkCmd.class.getName()); private static final String s_name = "deletephysicalnetworkresponse"; ///////////////////////////////////////////////////// //////////////// API parameters ///////////////////// ///////////////////////////////////////////////////// @Parameter(name = ApiConstants.ID, type = CommandType.UUID, entityType = PhysicalNetworkResponse.class, required = true, description = "the ID of the Physical network") private Long id; ///////////////////////////////////////////////////// /////////////////// Accessors /////////////////////// ///////////////////////////////////////////////////// @Override public void execute() { CallContext.current().setEventDetails("Physical Network Id: " + id); final boolean result = _networkService.deletePhysicalNetwork(getId()); if (result) { final SuccessResponse response = new SuccessResponse(getCommandName()); this.setResponseObject(response); } else { throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, "Failed to delete physical network"); } } ///////////////////////////////////////////////////// /////////////// API Implementation/////////////////// ///////////////////////////////////////////////////// public Long getId() { return id; } @Override public String getCommandName() { return s_name; } @Override public long getEntityOwnerId() { return Account.ACCOUNT_ID_SYSTEM; } @Override public String getEventType() { return EventTypes.EVENT_PHYSICAL_NETWORK_DELETE; } @Override public String getEventDescription() { return "Deleting Physical network: " + getId(); } @Override public ApiCommandJobType getInstanceType() { return ApiCommandJobType.PhysicalNetwork; } }
apache-2.0
BrunoEberhard/minimal-j
src/test/java/org/minimalj/repository/sql/SqlIntegerCodeTest.java
742
package org.minimalj.repository.sql; import org.junit.Assert; import org.junit.Test; import org.minimalj.model.Code; import org.minimalj.model.annotation.AutoIncrement; import org.minimalj.model.annotation.Size; public class SqlIntegerCodeTest extends SqlTest { @Override public Class<?>[] getEntityClasses() { return new Class<?>[] { TestCode.class }; } @Test public void insertTestCodeWithIntegerId() { TestCode code = new TestCode(); Object id = repository.insert(code); Assert.assertEquals("id should be of class Integer", Integer.class, id.getClass()); } public static class TestCode implements Code { @AutoIncrement public Integer id; @Size(255) public String text; } }
apache-2.0
xuyangbill/FragmentSample2
src/com/nozomi/fragmentsample2/PlaceholderFragment.java
1213
package com.nozomi.fragmentsample2; import android.support.v4.app.Fragment; import android.os.Bundle; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.TextView; /** * A placeholder fragment containing a simple view. */ public class PlaceholderFragment extends Fragment { /** * The fragment argument representing the section number for this * fragment. */ private static final String ARG_TITLE = "title"; /** * Returns a new instance of this fragment for the given section number. */ public static PlaceholderFragment newInstance(String title) { PlaceholderFragment fragment = new PlaceholderFragment(); Bundle args = new Bundle(); args.putString(ARG_TITLE, title); fragment.setArguments(args); return fragment; } public PlaceholderFragment() { } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View rootView = inflater.inflate(R.layout.placeholder_fragment, container, false); TextView textView = (TextView) rootView .findViewById(R.id.section_label); textView.setText(getArguments().getString(ARG_TITLE)); return rootView; } }
apache-2.0
AbramsCze/bsc-test
src/test/java/eu/greyson/bsc/bscTest/BscTestApplicationTests.java
340
package eu.greyson.bsc.bscTest; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.test.context.junit4.SpringRunner; @RunWith(SpringRunner.class) @SpringBootTest public class BscTestApplicationTests { @Test public void contextLoads() { } }
apache-2.0
iemejia/incubator-beam
sdks/java/testing/test-utils/src/main/java/org/apache/beam/sdk/testutils/publishing/InfluxDBPublisher.java
4145
/* * 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.sdk.testutils.publishing; import static java.nio.charset.StandardCharsets.UTF_8; import static java.util.Objects.requireNonNull; import static org.apache.beam.repackaged.core.org.apache.commons.lang3.StringUtils.isNoneBlank; import java.io.IOException; import java.util.Collection; import org.apache.beam.sdk.testutils.NamedTestResult; import org.apache.http.auth.AuthScope; import org.apache.http.auth.UsernamePasswordCredentials; import org.apache.http.client.CredentialsProvider; import org.apache.http.client.methods.CloseableHttpResponse; import org.apache.http.client.methods.HttpPost; import org.apache.http.entity.ByteArrayEntity; import org.apache.http.impl.client.BasicCredentialsProvider; import org.apache.http.impl.client.HttpClientBuilder; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public final class InfluxDBPublisher { private static final Logger LOG = LoggerFactory.getLogger(InfluxDBPublisher.class); private InfluxDBPublisher() {} public static void publishWithSettings( final Collection<NamedTestResult> results, final InfluxDBSettings settings) { requireNonNull(settings, "InfluxDB settings must not be null"); if (isNoneBlank(settings.measurement, settings.database)) { try { publish(results, settings); } catch (final Exception exception) { LOG.warn("Unable to publish metrics due to error: {}", exception.getMessage(), exception); } } else { LOG.warn("Missing property -- measurement/database. Metrics won't be published."); } } private static void publish( final Collection<NamedTestResult> results, final InfluxDBSettings settings) throws Exception { final HttpClientBuilder builder = HttpClientBuilder.create(); if (isNoneBlank(settings.userName, settings.userPassword)) { final CredentialsProvider provider = new BasicCredentialsProvider(); provider.setCredentials( AuthScope.ANY, new UsernamePasswordCredentials(settings.userName, settings.userPassword)); builder.setDefaultCredentialsProvider(provider); } final HttpPost postRequest = new HttpPost(settings.host + "/write?db=" + settings.database); final StringBuilder metricBuilder = new StringBuilder(); results.stream() .map(NamedTestResult::toMap) .forEach( map -> metricBuilder .append(settings.measurement) .append(",") .append("test_id") .append("=") .append(map.get("test_id")) .append(",") .append("metric") .append("=") .append(map.get("metric")) .append(" ") .append("value") .append("=") .append(map.get("value")) .append('\n')); postRequest.setEntity(new ByteArrayEntity(metricBuilder.toString().getBytes(UTF_8))); try (final CloseableHttpResponse response = builder.build().execute(postRequest)) { is2xx(response.getStatusLine().getStatusCode()); } } private static void is2xx(final int code) throws IOException { if (code < 200 || code >= 300) { throw new IOException("Response code: " + code); } } }
apache-2.0
JustBurrow/kobalttown
account/account-data/src/main/java/kr/lul/kobalttown/account/data/dao/CredentialDaoImpl.java
3175
package kr.lul.kobalttown.account.data.dao; import kr.lul.common.data.Context; import kr.lul.kobalttown.account.data.entity.CredentialEntity; import kr.lul.kobalttown.account.data.repository.CredentialRepository; import kr.lul.kobalttown.account.domain.Account; import kr.lul.kobalttown.account.domain.Credential; import org.slf4j.Logger; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import java.util.ArrayList; import java.util.List; import static kr.lul.common.util.Arguments.*; import static org.slf4j.LoggerFactory.getLogger; /** * @author justburrow * @since 2019/11/24 */ @Service class CredentialDaoImpl implements CredentialDao { private static final Logger log = getLogger(CredentialDaoImpl.class); @Autowired private CredentialRepository repository; @Override public Credential create(final Context context, final Credential credential) { if (log.isTraceEnabled()) log.trace("#create args : context={}, credential={}", context, credential); notNull(context, "context"); notNull(credential, "credential"); final CredentialEntity saved = this.repository.save((CredentialEntity) credential); if (log.isTraceEnabled()) log.trace("#create ({}) return : {}", context, saved); return saved; } @Override public Credential read(final Context context, final String publicKey) { if (log.isTraceEnabled()) log.trace("#read args : context={}, publicKey={}", context, publicKey); notEmpty(publicKey, "publicKey"); final CredentialEntity credential = this.repository.findByPublicKey(publicKey); if (log.isTraceEnabled()) log.trace("#read (context={}) return : {}", context, credential); return credential; } @Override public List<Credential> read(final Context context, final Account account) { if (log.isTraceEnabled()) log.trace("#read args : context={}, account={}", context, account); notNull(account, "account"); final List<Credential> credentials = new ArrayList<>(this.repository.findAllByAccount(account)); if (log.isTraceEnabled()) log.trace("#read (context={}) return : {}", context, credentials); return credentials; } @Override public void delete(final Context context, final Credential credential) { if (log.isTraceEnabled()) log.trace("#delete args : context={}, credential={}", context, credential); typeOf(credential, CredentialEntity.class, "credential"); this.repository.delete((CredentialEntity) credential); this.repository.flush(); if (log.isTraceEnabled()) log.trace("#delete (context={}) result : void", context); } @Override public boolean existsPublicKey(final Context context, final String publicKey) { if (log.isTraceEnabled()) log.trace("#existsPublicKey args : context={}, publicKey={}", context, publicKey); notNull(context, "context"); notEmpty(publicKey, "publicKey"); final boolean exists = this.repository.existsByPublicKey(publicKey); if (log.isTraceEnabled()) log.trace("#existsPublicKey (context={}) return : {}", context, exists); return exists; } }
apache-2.0
HanyeeWang/GeekZone
app/src/main/java/com/hanyee/geekzone/model/bean/tianxin/TianXinNewsBean.java
1306
package com.hanyee.geekzone.model.bean.tianxin; public class TianXinNewsBean { /** * ctime : 2015-07-17 * title : 那个抱走王明涵的,你上微信吗?看完这个你会心软吗? * description : 中国传统文化 * picUrl : http://zxpic.gtimg.com/infonew/0/wechat_pics_-667708.jpg/640 * url : http://mp.weixin.qq.com/s?__biz=MzA3OTg2NjEwNg==&amp;idx=5&amp;mid=209313388&amp;sn=7e30bd2851d22f69580e202c31fc7ecf */ private String ctime; private String title; private String description; private String picUrl; private String url; public String getCtime() { return ctime; } public void setCtime(String ctime) { this.ctime = ctime; } public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } public String getPicUrl() { return picUrl; } public void setPicUrl(String picUrl) { this.picUrl = picUrl; } public String getUrl() { return url; } public void setUrl(String url) { this.url = url; } }
apache-2.0
m-m-m/util
value/src/main/java/net/sf/mmm/util/value/base/AbstractSimpleValueConverter.java
1181
/* Copyright (c) The m-m-m Team, Licensed under the Apache License, Version 2.0 * http://www.apache.org/licenses/LICENSE-2.0 */ package net.sf.mmm.util.value.base; import net.sf.mmm.util.component.base.AbstractComponent; import net.sf.mmm.util.reflect.api.GenericType; import net.sf.mmm.util.value.api.ValueConverter; /** * This is an abstract base-implementation of the {@link ValueConverter} interface that simply works with {@link Class} * rather than {@link GenericType}. * * @param <SOURCE> is the generic {@link #getSourceType() source-type}. * @param <TARGET> is the generic {@link #getTargetType() target-type}. * * @author Joerg Hohwiller (hohwille at users.sourceforge.net) * @since 1.0.1 */ public abstract class AbstractSimpleValueConverter<SOURCE, TARGET> extends AbstractComponent implements ValueConverter<SOURCE, TARGET> { /** * The constructor. */ public AbstractSimpleValueConverter() { super(); } @Override public final <T extends TARGET> T convert(SOURCE value, Object valueSource, GenericType<T> targetType) { return convert(value, valueSource, targetType.getRetrievalClass()); } }
apache-2.0
lyfshadyboss/android-demo-playground
test/app/src/main/java/com/example/yifengliu/test/ShadowView.java
903
package com.example.yifengliu.test; import android.content.Context; import android.graphics.Canvas; import android.util.AttributeSet; import android.view.View; /** * Created by yifengliu on 15-7-27. */ public class ShadowView extends View { private View attachedView; public ShadowView(Context context) { super(context); } public ShadowView(Context context, AttributeSet attrs) { super(context, attrs); } public ShadowView(Context context, AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); } public View getAttachedView() { return attachedView; } public void setAttachedView(View attachedView) { this.attachedView = attachedView; } @Override protected void onDraw(Canvas canvas) { if (attachedView != null) { attachedView.draw(canvas); } } }
apache-2.0
googleapis/google-api-java-client-services
clients/google-api-services-dialogflow/v2beta1/1.31.0/com/google/api/services/dialogflow/v2beta1/model/GoogleCloudDialogflowV2IntentMessage.java
12203
/* * 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. */ /* * This code was generated by https://github.com/googleapis/google-api-java-client-services/ * Modify at your own risk. */ package com.google.api.services.dialogflow.v2beta1.model; /** * A rich response message. Corresponds to the intent `Response` field in the Dialogflow console. * For more information, see [Rich response messages](https://cloud.google.com/dialogflow/docs * /intents-rich-messages). * * <p> This is the Java data model class that specifies how to parse/serialize into the JSON that is * transmitted over HTTP when working with the Dialogflow API. For a detailed explanation see: * <a href="https://developers.google.com/api-client-library/java/google-http-java-client/json">https://developers.google.com/api-client-library/java/google-http-java-client/json</a> * </p> * * @author Google, Inc. */ @SuppressWarnings("javadoc") public final class GoogleCloudDialogflowV2IntentMessage extends com.google.api.client.json.GenericJson { /** * The basic card response for Actions on Google. * The value may be {@code null}. */ @com.google.api.client.util.Key private GoogleCloudDialogflowV2IntentMessageBasicCard basicCard; /** * Browse carousel card for Actions on Google. * The value may be {@code null}. */ @com.google.api.client.util.Key private GoogleCloudDialogflowV2IntentMessageBrowseCarouselCard browseCarouselCard; /** * The card response. * The value may be {@code null}. */ @com.google.api.client.util.Key private GoogleCloudDialogflowV2IntentMessageCard card; /** * The carousel card response for Actions on Google. * The value may be {@code null}. */ @com.google.api.client.util.Key private GoogleCloudDialogflowV2IntentMessageCarouselSelect carouselSelect; /** * The image response. * The value may be {@code null}. */ @com.google.api.client.util.Key private GoogleCloudDialogflowV2IntentMessageImage image; /** * The link out suggestion chip for Actions on Google. * The value may be {@code null}. */ @com.google.api.client.util.Key private GoogleCloudDialogflowV2IntentMessageLinkOutSuggestion linkOutSuggestion; /** * The list card response for Actions on Google. * The value may be {@code null}. */ @com.google.api.client.util.Key private GoogleCloudDialogflowV2IntentMessageListSelect listSelect; /** * The media content card for Actions on Google. * The value may be {@code null}. */ @com.google.api.client.util.Key private GoogleCloudDialogflowV2IntentMessageMediaContent mediaContent; /** * A custom platform-specific response. * The value may be {@code null}. */ @com.google.api.client.util.Key private java.util.Map<String, java.lang.Object> payload; /** * Optional. The platform that this message is intended for. * The value may be {@code null}. */ @com.google.api.client.util.Key private java.lang.String platform; /** * The quick replies response. * The value may be {@code null}. */ @com.google.api.client.util.Key private GoogleCloudDialogflowV2IntentMessageQuickReplies quickReplies; /** * The voice and text-only responses for Actions on Google. * The value may be {@code null}. */ @com.google.api.client.util.Key private GoogleCloudDialogflowV2IntentMessageSimpleResponses simpleResponses; /** * The suggestion chips for Actions on Google. * The value may be {@code null}. */ @com.google.api.client.util.Key private GoogleCloudDialogflowV2IntentMessageSuggestions suggestions; /** * Table card for Actions on Google. * The value may be {@code null}. */ @com.google.api.client.util.Key private GoogleCloudDialogflowV2IntentMessageTableCard tableCard; /** * The text response. * The value may be {@code null}. */ @com.google.api.client.util.Key private GoogleCloudDialogflowV2IntentMessageText text; /** * The basic card response for Actions on Google. * @return value or {@code null} for none */ public GoogleCloudDialogflowV2IntentMessageBasicCard getBasicCard() { return basicCard; } /** * The basic card response for Actions on Google. * @param basicCard basicCard or {@code null} for none */ public GoogleCloudDialogflowV2IntentMessage setBasicCard(GoogleCloudDialogflowV2IntentMessageBasicCard basicCard) { this.basicCard = basicCard; return this; } /** * Browse carousel card for Actions on Google. * @return value or {@code null} for none */ public GoogleCloudDialogflowV2IntentMessageBrowseCarouselCard getBrowseCarouselCard() { return browseCarouselCard; } /** * Browse carousel card for Actions on Google. * @param browseCarouselCard browseCarouselCard or {@code null} for none */ public GoogleCloudDialogflowV2IntentMessage setBrowseCarouselCard(GoogleCloudDialogflowV2IntentMessageBrowseCarouselCard browseCarouselCard) { this.browseCarouselCard = browseCarouselCard; return this; } /** * The card response. * @return value or {@code null} for none */ public GoogleCloudDialogflowV2IntentMessageCard getCard() { return card; } /** * The card response. * @param card card or {@code null} for none */ public GoogleCloudDialogflowV2IntentMessage setCard(GoogleCloudDialogflowV2IntentMessageCard card) { this.card = card; return this; } /** * The carousel card response for Actions on Google. * @return value or {@code null} for none */ public GoogleCloudDialogflowV2IntentMessageCarouselSelect getCarouselSelect() { return carouselSelect; } /** * The carousel card response for Actions on Google. * @param carouselSelect carouselSelect or {@code null} for none */ public GoogleCloudDialogflowV2IntentMessage setCarouselSelect(GoogleCloudDialogflowV2IntentMessageCarouselSelect carouselSelect) { this.carouselSelect = carouselSelect; return this; } /** * The image response. * @return value or {@code null} for none */ public GoogleCloudDialogflowV2IntentMessageImage getImage() { return image; } /** * The image response. * @param image image or {@code null} for none */ public GoogleCloudDialogflowV2IntentMessage setImage(GoogleCloudDialogflowV2IntentMessageImage image) { this.image = image; return this; } /** * The link out suggestion chip for Actions on Google. * @return value or {@code null} for none */ public GoogleCloudDialogflowV2IntentMessageLinkOutSuggestion getLinkOutSuggestion() { return linkOutSuggestion; } /** * The link out suggestion chip for Actions on Google. * @param linkOutSuggestion linkOutSuggestion or {@code null} for none */ public GoogleCloudDialogflowV2IntentMessage setLinkOutSuggestion(GoogleCloudDialogflowV2IntentMessageLinkOutSuggestion linkOutSuggestion) { this.linkOutSuggestion = linkOutSuggestion; return this; } /** * The list card response for Actions on Google. * @return value or {@code null} for none */ public GoogleCloudDialogflowV2IntentMessageListSelect getListSelect() { return listSelect; } /** * The list card response for Actions on Google. * @param listSelect listSelect or {@code null} for none */ public GoogleCloudDialogflowV2IntentMessage setListSelect(GoogleCloudDialogflowV2IntentMessageListSelect listSelect) { this.listSelect = listSelect; return this; } /** * The media content card for Actions on Google. * @return value or {@code null} for none */ public GoogleCloudDialogflowV2IntentMessageMediaContent getMediaContent() { return mediaContent; } /** * The media content card for Actions on Google. * @param mediaContent mediaContent or {@code null} for none */ public GoogleCloudDialogflowV2IntentMessage setMediaContent(GoogleCloudDialogflowV2IntentMessageMediaContent mediaContent) { this.mediaContent = mediaContent; return this; } /** * A custom platform-specific response. * @return value or {@code null} for none */ public java.util.Map<String, java.lang.Object> getPayload() { return payload; } /** * A custom platform-specific response. * @param payload payload or {@code null} for none */ public GoogleCloudDialogflowV2IntentMessage setPayload(java.util.Map<String, java.lang.Object> payload) { this.payload = payload; return this; } /** * Optional. The platform that this message is intended for. * @return value or {@code null} for none */ public java.lang.String getPlatform() { return platform; } /** * Optional. The platform that this message is intended for. * @param platform platform or {@code null} for none */ public GoogleCloudDialogflowV2IntentMessage setPlatform(java.lang.String platform) { this.platform = platform; return this; } /** * The quick replies response. * @return value or {@code null} for none */ public GoogleCloudDialogflowV2IntentMessageQuickReplies getQuickReplies() { return quickReplies; } /** * The quick replies response. * @param quickReplies quickReplies or {@code null} for none */ public GoogleCloudDialogflowV2IntentMessage setQuickReplies(GoogleCloudDialogflowV2IntentMessageQuickReplies quickReplies) { this.quickReplies = quickReplies; return this; } /** * The voice and text-only responses for Actions on Google. * @return value or {@code null} for none */ public GoogleCloudDialogflowV2IntentMessageSimpleResponses getSimpleResponses() { return simpleResponses; } /** * The voice and text-only responses for Actions on Google. * @param simpleResponses simpleResponses or {@code null} for none */ public GoogleCloudDialogflowV2IntentMessage setSimpleResponses(GoogleCloudDialogflowV2IntentMessageSimpleResponses simpleResponses) { this.simpleResponses = simpleResponses; return this; } /** * The suggestion chips for Actions on Google. * @return value or {@code null} for none */ public GoogleCloudDialogflowV2IntentMessageSuggestions getSuggestions() { return suggestions; } /** * The suggestion chips for Actions on Google. * @param suggestions suggestions or {@code null} for none */ public GoogleCloudDialogflowV2IntentMessage setSuggestions(GoogleCloudDialogflowV2IntentMessageSuggestions suggestions) { this.suggestions = suggestions; return this; } /** * Table card for Actions on Google. * @return value or {@code null} for none */ public GoogleCloudDialogflowV2IntentMessageTableCard getTableCard() { return tableCard; } /** * Table card for Actions on Google. * @param tableCard tableCard or {@code null} for none */ public GoogleCloudDialogflowV2IntentMessage setTableCard(GoogleCloudDialogflowV2IntentMessageTableCard tableCard) { this.tableCard = tableCard; return this; } /** * The text response. * @return value or {@code null} for none */ public GoogleCloudDialogflowV2IntentMessageText getText() { return text; } /** * The text response. * @param text text or {@code null} for none */ public GoogleCloudDialogflowV2IntentMessage setText(GoogleCloudDialogflowV2IntentMessageText text) { this.text = text; return this; } @Override public GoogleCloudDialogflowV2IntentMessage set(String fieldName, Object value) { return (GoogleCloudDialogflowV2IntentMessage) super.set(fieldName, value); } @Override public GoogleCloudDialogflowV2IntentMessage clone() { return (GoogleCloudDialogflowV2IntentMessage) super.clone(); } }
apache-2.0
juphich/toolab
toolab-utils/src/main/java/net/toolab/utils/DateFormatUtils.java
3195
package net.toolab.utils; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Calendar; import java.util.Date; import java.util.GregorianCalendar; import java.util.regex.Pattern; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class DateFormatUtils { private static Logger log = LoggerFactory.getLogger(DateFormatUtils.class); private Calendar calendar = new GregorianCalendar(); private String pattern; public void setPattern(String pattern) { this.pattern = pattern; } public Date getDate() { return new Date(); } public Date getDate(String dateValue) { String usePattern = null; if (pattern != null) { usePattern = pattern; } else if (Pattern.matches("^\\d{4}\\-((0\\d)|(1[12]))\\-(([012]\\d)|(3[01]))$", dateValue)) { usePattern = "yyyy-MM-dd"; } else if (Pattern.matches( "^\\d{4}\\-((0\\d)|(1[12]))\\-(([012]\\d)|(3[01]))\\s(([01]\\d)|(2[0-3])):[0-5]\\d:[0-5]\\d$", dateValue)) { usePattern = "yyyy-MM-dd hh:mm:ss"; } else { usePattern = "yyyy-MM-dd"; } return getDate(dateValue, usePattern); } public Date getDate(String dateValue, String pattern) { try { SimpleDateFormat format = new SimpleDateFormat(pattern); return format.parse(dateValue); } catch (ParseException e) { if (log.isDebugEnabled()) { log.debug(e.getMessage()); } return null; } } public Date addSeconds(int interval) { return add(getCurrentDate(), Calendar.SECOND, interval); } public Date addSeconds(Date date, int interval) { return add(date, Calendar.SECOND, interval); } public Date addMinutes(int interval) { return add(getCurrentDate(), Calendar.MINUTE, interval); } public Date addMinutes(Date date, int interval) { return add(date, Calendar.MINUTE, interval); } public Date addHours(int interval) { return add(getCurrentDate(), Calendar.HOUR, interval); } public Date addHours(Date date, int interval) { return add(date, Calendar.HOUR, interval); } public Date addDays(int interval) { return add(getCurrentDate(), Calendar.DATE, interval); } public Date addDays(Date date, int interval) { return add(date, Calendar.DATE, interval); } public Date addMonths(int interval) { return add(getCurrentDate(), Calendar.MONTH, interval); } public Date addMonths(Date date, int interval) { return add(date, Calendar.MONTH, interval); } public Date addYears(int interval) { return add(getCurrentDate(), Calendar.YEAR, interval); } public Date addYears(Date date, int interval) { return add(date, Calendar.YEAR, interval); } private Date add(Date date, int calendarField, int interval) { calendar.setTime(date); calendar.add(calendarField, interval); return calendar.getTime(); } public String formatDate(Date date, String pattern) { if (pattern == null) { pattern = "yyyy-MM-dd"; } SimpleDateFormat format = new SimpleDateFormat(pattern); return format.format(date); } public String formatDate(long time, String pattern) { return formatDate(new Date(time), pattern); } public static Date getCurrentDate() { return new Date(Calendar.getInstance().getTimeInMillis()); } }
apache-2.0
rayokota/hgraphdb
src/main/java/io/hgraphdb/mapreduce/index/IndexTool.java
15317
package io.hgraphdb.mapreduce.index; import com.google.common.base.Splitter; import com.google.common.collect.Iterables; import io.hgraphdb.*; import io.hgraphdb.mapreduce.TableInputFormat; import org.apache.commons.cli.*; import org.apache.commons.lang.exception.ExceptionUtils; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.conf.Configured; import org.apache.hadoop.fs.FileSystem; import org.apache.hadoop.fs.Path; import org.apache.hadoop.hbase.HBaseConfiguration; import org.apache.hadoop.hbase.KeyValue; import org.apache.hadoop.hbase.TableName; import org.apache.hadoop.hbase.client.*; import org.apache.hadoop.hbase.io.ImmutableBytesWritable; import org.apache.hadoop.hbase.mapreduce.HFileOutputFormat2; import org.apache.hadoop.hbase.mapreduce.LoadIncrementalHFiles; import org.apache.hadoop.hbase.mapreduce.TableMapReduceUtil; import org.apache.hadoop.hbase.mapreduce.TableOutputFormat; import org.apache.hadoop.hbase.protobuf.ProtobufUtil; import org.apache.hadoop.hbase.protobuf.generated.ClientProtos; import org.apache.hadoop.hbase.util.Base64; import org.apache.hadoop.io.IntWritable; import org.apache.hadoop.io.NullWritable; import org.apache.hadoop.mapreduce.Job; import org.apache.hadoop.mapreduce.Mapper; import org.apache.hadoop.mapreduce.Reducer; import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat; import org.apache.hadoop.util.Tool; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.IOException; /** * An abstract MR job to update an index. * * Based on IndexTool from Phoenix. */ public abstract class IndexTool extends Configured implements Tool { private static final Logger LOG = LoggerFactory.getLogger(IndexTool.class); private static final Option INDEX_TYPE_OPTION = new Option("t", "type", true, "Index type (edge or vertex)"); private static final Option LABEL_OPTION = new Option("l", "label", true, "Label to be indexed"); private static final Option PROPERTY_KEY_OPTION = new Option("p", "property-key", true, "Property key to be indexed"); private static final Option DIRECT_API_OPTION = new Option("d", "direct", false, "If specified, we avoid the bulk load (optional)"); private static final Option RUN_FOREGROUND_OPTION = new Option("rf", "run-foreground", false, "Whether to populate index in foreground"); private static final Option OUTPUT_PATH_OPTION = new Option("op", "output-path", true, "Output path where the files are written"); private static final Option SKIP_DEPENDENCY_JARS = new Option("sj", "skip-dependency-jars", false, "Skip adding dependency jars"); private static final Option CUSTOM_ARGS_OPTION = new Option("ca", "customArguments", true, "Provide custom" + " arguments for the job configuration in the form:" + " -ca <param1>=<value1>,<param2>=<value2> -ca <param3>=<value3> etc." + " It can appear multiple times, and the last one has effect" + " for the same param."); private static final Option HELP_OPTION = new Option("h", "help", false, "Help"); private Options getOptions() { final Options options = new Options(); options.addOption(INDEX_TYPE_OPTION); options.addOption(LABEL_OPTION); options.addOption(PROPERTY_KEY_OPTION); options.addOption(DIRECT_API_OPTION); options.addOption(RUN_FOREGROUND_OPTION); options.addOption(OUTPUT_PATH_OPTION); options.addOption(SKIP_DEPENDENCY_JARS); options.addOption(CUSTOM_ARGS_OPTION); options.addOption(HELP_OPTION); return options; } /** * Parses the commandline arguments, throws IllegalStateException if mandatory arguments are * missing. * @param args supplied command line arguments * @return the parsed command line */ private CommandLine parseOptions(String[] args) { final Options options = getOptions(); CommandLineParser parser = new PosixParser(); CommandLine cmdLine = null; try { cmdLine = parser.parse(options, args); } catch (ParseException e) { printHelpAndExit("Error parsing command line options: " + e.getMessage(), options); } if (cmdLine.hasOption(HELP_OPTION.getOpt())) { printHelpAndExit(options, 0); } if (!cmdLine.hasOption(INDEX_TYPE_OPTION.getOpt())) { throw new IllegalStateException(INDEX_TYPE_OPTION.getLongOpt() + " is a mandatory " + "parameter"); } if (!cmdLine.hasOption(LABEL_OPTION.getOpt())) { throw new IllegalStateException(LABEL_OPTION.getLongOpt() + " is a mandatory " + "parameter"); } if (!cmdLine.hasOption(PROPERTY_KEY_OPTION.getOpt())) { throw new IllegalStateException(PROPERTY_KEY_OPTION.getLongOpt() + " is a mandatory " + "parameter"); } if (!cmdLine.hasOption(OUTPUT_PATH_OPTION.getOpt())) { throw new IllegalStateException(OUTPUT_PATH_OPTION.getLongOpt() + " is a mandatory " + "parameter"); } if (!cmdLine.hasOption(DIRECT_API_OPTION.getOpt()) && cmdLine.hasOption(RUN_FOREGROUND_OPTION.getOpt())) { throw new IllegalStateException(RUN_FOREGROUND_OPTION.getLongOpt() + " is applicable only for " + DIRECT_API_OPTION.getLongOpt()); } return cmdLine; } private void printHelpAndExit(String errorMessage, Options options) { System.err.println(errorMessage); printHelpAndExit(options, 1); } private void printHelpAndExit(Options options, int exitCode) { HelpFormatter formatter = new HelpFormatter(); formatter.printHelp("help", options); System.exit(exitCode); } protected abstract void setup(final HBaseGraph graph, final IndexMetadata index); protected abstract void cleanup(final HBaseGraph graph, final IndexMetadata index); protected abstract Class<? extends Mapper> getDirectMapperClass(); protected abstract Class<? extends Reducer> getDirectReducerClass(); protected abstract Class<? extends Mapper> getBulkMapperClass(); protected abstract TableName getInputTableName(final HBaseGraph graph, final IndexMetadata index); protected abstract TableName getOutputTableName(final HBaseGraph graph, final IndexMetadata index); protected Scan getInputScan(final HBaseGraph graph, final IndexMetadata index) { return new Scan(); } @Override public int run(String[] args) throws Exception { HBaseGraph graph = null; try { CommandLine cmdLine = null; try { cmdLine = parseOptions(args); } catch (IllegalStateException e) { printHelpAndExit(e.getMessage(), getOptions()); } final Configuration configuration = HBaseConfiguration.addHbaseResources(getConf()); final String type = cmdLine.getOptionValue(INDEX_TYPE_OPTION.getOpt()); ElementType indexType; try { indexType = ElementType.valueOf(type.toUpperCase()); } catch (IllegalArgumentException e) { throw new IllegalStateException(INDEX_TYPE_OPTION.getLongOpt() + " must be one of 'edge' or 'vertex'"); } final String label = cmdLine.getOptionValue(LABEL_OPTION.getOpt()); final String propertyKey = cmdLine.getOptionValue(PROPERTY_KEY_OPTION.getOpt()); configuration.set(Constants.MAPREDUCE_INDEX_TYPE, indexType.toString()); configuration.set(Constants.MAPREDUCE_INDEX_LABEL, label); configuration.set(Constants.MAPREDUCE_INDEX_PROPERTY_KEY, propertyKey); boolean skipDependencyJars = cmdLine.hasOption(SKIP_DEPENDENCY_JARS.getOpt()); if (cmdLine.hasOption(CUSTOM_ARGS_OPTION.getOpt())) { for (String caOptionValue : cmdLine.getOptionValues(CUSTOM_ARGS_OPTION.getOpt())) { for (String paramValue : Splitter.on(',').split(caOptionValue)) { String[] parts = Iterables.toArray(Splitter.on('=').split(paramValue), String.class); if (parts.length != 2) { throw new IllegalArgumentException("Unable to parse custom " + " argument: " + paramValue); } if (LOG.isInfoEnabled()) { LOG.info("Setting custom argument [" + parts[0] + "] to [" + parts[1] + "] in Configuration"); } configuration.set(parts[0], parts[1]); } } } HBaseGraphConfiguration hconf = new HBaseGraphConfiguration(configuration); graph = new HBaseGraph(hconf); IndexMetadata index = graph.getIndex(OperationType.WRITE, indexType, label, propertyKey); if (index == null) { throw new IllegalArgumentException(String.format( "No %s index found for label '%s' and property key '%s'", indexType, label, propertyKey)); } setup(graph, index); TableName inputTableName = getInputTableName(graph, index); TableName outputTableName = getOutputTableName(graph, index); String jobName = indexType.toString().toLowerCase() + "_" + label + "_" + propertyKey; final Path outputPath = new Path(cmdLine.getOptionValue(OUTPUT_PATH_OPTION.getOpt()), jobName); FileSystem.get(configuration).delete(outputPath, true); final Job job = Job.getInstance(configuration, jobName); job.setJarByClass(getClass()); job.setMapOutputKeyClass(ImmutableBytesWritable.class); FileOutputFormat.setOutputPath(job, outputPath); job.setInputFormatClass(TableInputFormat.class); job.getConfiguration().set(TableInputFormat.INPUT_TABLE, inputTableName.getNameAsString()); job.getConfiguration().set(TableInputFormat.SCAN, convertScanToString(getInputScan(graph, index))); TableMapReduceUtil.initCredentials(job); boolean useDirectApi = cmdLine.hasOption(DIRECT_API_OPTION.getOpt()); if (useDirectApi) { configureSubmittableJobUsingDirectApi(job, outputPath, outputTableName, skipDependencyJars, cmdLine.hasOption(RUN_FOREGROUND_OPTION.getOpt())); } else { configureRunnableJobUsingBulkLoad(job, outputPath, outputTableName, skipDependencyJars); // Without direct API, we need to update the index state from client. cleanup(graph, index); } return 0; } catch (Exception ex) { LOG.error("An exception occurred while performing the indexing job: " + ExceptionUtils.getMessage(ex) + " at:\n" + ExceptionUtils.getStackTrace(ex)); return -1; } finally { if (graph != null) { graph.close(); } } } /** * Submits the job and waits for completion. * @param job job * @param outputPath output path * @throws Exception */ private void configureRunnableJobUsingBulkLoad(Job job, Path outputPath, TableName outputTableName, boolean skipDependencyJars) throws Exception { job.setMapperClass(getBulkMapperClass()); job.setMapOutputKeyClass(ImmutableBytesWritable.class); job.setMapOutputValueClass(KeyValue.class); final Configuration configuration = job.getConfiguration(); try (Connection conn = ConnectionFactory.createConnection(configuration); Admin admin = conn.getAdmin(); Table table = conn.getTable(outputTableName); RegionLocator regionLocator = conn.getRegionLocator(outputTableName)) { HFileOutputFormat2.configureIncrementalLoad(job, table, regionLocator); if (skipDependencyJars) { job.getConfiguration().unset("tmpjars"); } boolean status = job.waitForCompletion(true); if (!status) { LOG.error("IndexTool job failed!"); throw new Exception("IndexTool job failed: " + job.toString()); } LOG.info("Loading HFiles from {}", outputPath); LoadIncrementalHFiles loader = new LoadIncrementalHFiles(configuration); loader.doBulkLoad(outputPath, admin, table, regionLocator); } FileSystem.get(configuration).delete(outputPath, true); } /** * Uses the HBase Front Door Api to write to index table. Submits the job and either returns or * waits for the job completion based on runForeground parameter. * * @param job job * @param outputPath output path * @param runForeground - if true, waits for job completion, else submits and returns * immediately. * @throws Exception */ private void configureSubmittableJobUsingDirectApi(Job job, Path outputPath, TableName outputTableName, boolean skipDependencyJars, boolean runForeground) throws Exception { job.setMapperClass(getDirectMapperClass()); job.setReducerClass(getDirectReducerClass()); Configuration conf = job.getConfiguration(); HBaseConfiguration.merge(conf, HBaseConfiguration.create(conf)); conf.set(TableOutputFormat.OUTPUT_TABLE, outputTableName.getNameAsString()); //Set the Output classes job.setMapOutputValueClass(IntWritable.class); job.setOutputKeyClass(NullWritable.class); job.setOutputValueClass(NullWritable.class); if (!skipDependencyJars) { TableMapReduceUtil.addDependencyJars(job); } job.setNumReduceTasks(1); if (!runForeground) { LOG.info("Running Index Build in Background - Submit async and exit"); job.submit(); return; } LOG.info("Running Index Build in Foreground. Waits for the build to complete. This may take a long time!."); boolean result = job.waitForCompletion(true); if (!result) { LOG.error("IndexTool job failed!"); throw new Exception("IndexTool job failed: " + job.toString()); } FileSystem.get(conf).delete(outputPath, true); } /** * Writes the given scan into a Base64 encoded string. * * @param scan The scan to write out. * @return The scan saved in a Base64 encoded string. * @throws IOException When writing the scan fails. */ static String convertScanToString(Scan scan) throws IOException { ClientProtos.Scan proto = ProtobufUtil.toScan(scan); return Base64.encodeBytes(proto.toByteArray()); } }
apache-2.0
lesaint/experimenting-annotation-processing
experimenting-rounds/massive-count-of-annotated-classes/src/main/java/fr/javatronic/blog/massive/annotation1/sub1/Class_5707.java
151
package fr.javatronic.blog.massive.annotation1.sub1; import fr.javatronic.blog.processor.Annotation_001; @Annotation_001 public class Class_5707 { }
apache-2.0
sbahrin3/LebahFramework
JavaSource/lebah/mail/SendMailSSL.java
1517
package lebah.mail; import java.util.Properties; import javax.mail.Message; import javax.mail.MessagingException; import javax.mail.PasswordAuthentication; import javax.mail.Session; import javax.mail.Transport; import javax.mail.internet.InternetAddress; import javax.mail.internet.MimeMessage; public class SendMailSSL { public static void main(String[] args) { Properties props = new Properties(); props.put("mail.smtp.host", "localhost"); //props.put("mail.smtp.socketFactory.port", "465"); //props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory"); //props.put("mail.smtp.auth", "true"); props.put("mail.smtp.port", "25"); // Session session = Session.getDefaultInstance(props, // new javax.mail.Authenticator() { // protected PasswordAuthentication getPasswordAuthentication() { // return new PasswordAuthentication("username","password"); // } // }); //Session session = Session.getInstance(props, null); Session session = Session.getDefaultInstance(props); try { Message message = new MimeMessage(session); message.setFrom(new InternetAddress("sbahrin3@yahoo.com")); message.setRecipients(Message.RecipientType.TO, InternetAddress.parse("sbahrin3@gmail.com")); message.setSubject("Testing Subject"); message.setText("Dear Mail Crawler," + "\n\n No spam to my email, please!"); Transport.send(message); System.out.println("Done"); } catch (MessagingException e) { throw new RuntimeException(e); } } }
apache-2.0
PGMacDesign/PGMacUtilities
library/src/main/java/com/pgmacdesign/pgmactips/utilities/ViewUtilities.java
20118
package com.pgmacdesign.pgmactips.utilities; import android.app.Activity; import android.content.res.Resources; import android.graphics.Bitmap; import android.graphics.Canvas; import android.graphics.Point; import android.graphics.drawable.BitmapDrawable; import android.graphics.drawable.Drawable; import android.os.Handler; import android.os.Looper; import android.os.Message; import androidx.annotation.NonNull; import android.view.Gravity; import android.view.View; import android.view.ViewGroup; import android.widget.FrameLayout; import android.widget.LinearLayout; import android.widget.RelativeLayout; import com.pgmacdesign.pgmactips.adaptersandlisteners.OnTaskCompleteListener; import com.pgmacdesign.pgmactips.misc.PGMacTipsConstants; import java.util.Timer; import java.util.TimerTask; import javax.annotation.Nonnull; /** * Class for managing views in various ways * Created by pmacdowell on 2017-07-10. */ public class ViewUtilities { public static final int VIEW_PARAMS_LOADED = PGMacTipsConstants.TAG_VIEW_PARAMS_LOADED; public static final int VIEW_PARAMS_LOADING_FAILED = PGMacTipsConstants.TAG_VIEW_PARAMS_LOADING_FAILED; public static final int VIEW_FINISHED_DRAWING = PGMacTipsConstants.TAG_VIEW_FINISHED_DRAWING; /** * Alter a view visibility after X milliseconds * @param activity Activity to call upon. Preferred method over excluding this * @param view View to alter * @param visibility Visibility {@link View#GONE}, {@link View#INVISIBLE}, {@link View#VISIBLE} * @param millisecondsToWait Number of milliseconds to wait before making alteration */ public static void alterViewVisibility(@NonNull final Activity activity, @NonNull final View view, final int visibility, long millisecondsToWait) { Timer timer = new Timer(); timer.schedule(new TimerTask() { @Override public void run() { activity.runOnUiThread(new Runnable() { @Override public void run() { view.setVisibility(visibility); } }); } }, millisecondsToWait); } /** * Alter a view visibility after X milliseconds * @param view View to alter * @param visibility Visibility {@link View#GONE}, {@link View#INVISIBLE}, {@link View#VISIBLE} * @param millisecondsToWait Number of milliseconds to wait before making alteration */ public static void alterViewVisibility(@NonNull final View view, final int visibility, long millisecondsToWait) { final Handler handler = new Handler(Looper.getMainLooper()) { @Override public void handleMessage(Message msg) { try { view.setVisibility(visibility); } catch (Exception e){} } }; Timer timer = new Timer(); timer.schedule(new TimerTask() { @Override public void run() { handler.sendMessage(new Message()); } }, millisecondsToWait); } public static ResizingViewObject scaleGIFTo(float gifWidth, float gifHeight, float maxAvailableWidth, float maxAvailableHeight, Boolean maintainRatio){ //Check incorrect data first if(gifHeight == 0 && gifWidth == 0){ return null; } if(maxAvailableWidth == 0 && maxAvailableHeight == 0){ return null; } //Defaults if(maintainRatio == null){ maintainRatio = false; } float currentGifRatio = (float)(gifWidth / gifHeight); float layoutParamsRatio = (float)(maxAvailableWidth / maxAvailableHeight); if(currentGifRatio < 0){ //Something went wrong return null; } ResizingViewObject obj = new ResizingViewObject(); obj.maintainedRatio = maintainRatio; if(maintainRatio){ float multiplier, newWidth, newHeight, widthTranslatePixels, heightTranslatePixels; if(layoutParamsRatio < 1){ //View is Portrait mode; height > width ; width is lowest # if(currentGifRatio < 1){ //Image is Portrait mode; height > width ; width is lowest # multiplier = maxAvailableWidth / gifWidth; } else { //Image is Landscape mode; width > height ; height is lowest # multiplier = maxAvailableWidth / gifHeight; } newWidth = gifWidth * multiplier; newHeight = gifHeight * multiplier; widthTranslatePixels = (((((float)maxAvailableWidth) - ((float)newWidth)) / 2F) / ((float)multiplier)); heightTranslatePixels = (((((float)maxAvailableHeight) - ((float)newHeight)) / 2F) / ((float)multiplier)); } else { //View is Landscape mode; width > height; height is lowest # if(currentGifRatio < 1){ //Image is Portrait mode; height > width ; width is lowest # multiplier = maxAvailableHeight / gifWidth; } else { //Image is Landscape mode; width > height ; height is lowest # multiplier = maxAvailableHeight / gifHeight; } newWidth = gifWidth * multiplier; newHeight = gifHeight * multiplier; widthTranslatePixels = (((((float)maxAvailableWidth) - ((float)newWidth)) / 2F) / ((float)multiplier)); heightTranslatePixels = (((((float)maxAvailableHeight) - ((float)newHeight)) / 2F) / ((float)multiplier)); } //Adjust Padding obj.newHeight = newHeight;//(newHeight - (2 * paddingInPixels)); obj.newWidth = newWidth;//(newWidth - (2 * paddingInPixels)); obj.widthScaleMultiplier = multiplier; obj.heightScaleMultiplier = multiplier; obj.widthTranslatePixels = widthTranslatePixels; obj.heightTranslatePixels = heightTranslatePixels; } else { obj.newHeight = maxAvailableHeight;//(maxAvailableHeight - (2 * paddingInPixels)); obj.newWidth = maxAvailableWidth;//(maxAvailableWidth - (2 * paddingInPixels)); obj.widthScaleMultiplier = maxAvailableWidth / gifWidth; obj.heightScaleMultiplier = maxAvailableHeight / gifHeight; obj.widthTranslatePixels = 0; obj.heightTranslatePixels = 0; } return obj; } /** * Object used for resizing views returns */ public static class ResizingViewObject { //All used in translating objects private float newWidth; private float newHeight; private boolean maintainedRatio; private float widthScaleMultiplier; private float heightScaleMultiplier; private float widthTranslatePixels; private float heightTranslatePixels; public float getWidthTranslatePixels() { return widthTranslatePixels; } public float getHeightTranslatePixels() { return heightTranslatePixels; } public float getWidthScaleMultiplier() { return widthScaleMultiplier; } public float getHeightScaleMultiplier() { return heightScaleMultiplier; } public float getNewWidth() { return newWidth; } public float getNewHeight() { return newHeight; } public boolean didMaintainRatio() { return maintainedRatio; } } /** * Set the view margins and attempt to redraw * @param view View to alter * @param left margins - left side * @param top margins - top side * @param right margins - right side * @param bottom margins - bottom side */ public static void setViewMargins (View view, int left, int top, int right, int bottom) { if(view == null){ return; } try { if (view.getLayoutParams() instanceof ViewGroup.MarginLayoutParams) { ViewGroup.MarginLayoutParams p = (ViewGroup.MarginLayoutParams) view.getLayoutParams(); p.setMargins(left, top, right, bottom); view.requestLayout(); } } catch (Exception e){ e.printStackTrace(); } } /** * Returns view margins in same order as setting (left, top, right, bottom) * @param view View to check * @return int array (always size 3) where all 4 elements match same order * as setting (left, top, right, bottom). If margins are unable to * be retrieved, will return array full of zeros */ public static int[] getViewMargins(View view){ int[] toReturn = {0, 0, 0, 0}; if(view == null){ return toReturn; } try { if (view.getLayoutParams() instanceof ViewGroup.MarginLayoutParams) { ViewGroup.MarginLayoutParams p = (ViewGroup.MarginLayoutParams) view.getLayoutParams(); toReturn[0] = p.leftMargin; toReturn[1] = p.topMargin; toReturn[2] = p.rightMargin; toReturn[3] = p.bottomMargin; } } catch (Exception e){ e.printStackTrace(); } return toReturn; } /** * Resize a view to a square by taking lowest width or height and resizing to that * @param view View to alter && return * @return If successful, altered view. If not successful, passed view */ public static <T extends View> T resizeViewToSquare(@NonNull T view){ return resizeViewToSquare(view, false, false); } /** * Resize a view to a square by taking lowest width or height and resizing to that. * Overloaded, takes in 2 new params to allow for centering and margin removal * @param view View to alter && return * @param centerView Should the view be centered? If so, will attempt to center view * within layout params capabilities * @param removeMargins Should remove the margins? This is useful if trying to resize * something and want it to go to the edges. Note, will not remove * the padding if that exists. If true, this will set all the set * margins to zero. * @return If successful, altered view. If not successful, passed view */ public static <T extends View> T resizeViewToSquare(@NonNull T view, boolean centerView, boolean removeMargins){ if(view == null){ return view; } int width = view.getWidth(); int height = view.getHeight(); int lowestOfTwo; //Portraint vs landscape if(width < height){ lowestOfTwo = width; } else { lowestOfTwo = height; } try { if (view.getLayoutParams() instanceof LinearLayout.LayoutParams) { LinearLayout.LayoutParams p = (LinearLayout.LayoutParams) view.getLayoutParams(); p.width = lowestOfTwo; p.height = lowestOfTwo; if (removeMargins) { p.setMargins(0, 0, 0, 0); } if (centerView) { p.gravity = Gravity.CENTER_HORIZONTAL | Gravity.CENTER_VERTICAL; } } else if (view.getLayoutParams() instanceof RelativeLayout.LayoutParams) { RelativeLayout.LayoutParams p = (RelativeLayout.LayoutParams) view.getLayoutParams(); p.width = lowestOfTwo; p.height = lowestOfTwo; if (removeMargins) { p.setMargins(0, 0, 0, 0); } if (centerView) { p.addRule(RelativeLayout.CENTER_IN_PARENT); p.addRule(RelativeLayout.CENTER_HORIZONTAL); p.addRule(RelativeLayout.CENTER_VERTICAL); } } else if (view.getLayoutParams() instanceof FrameLayout.LayoutParams) { FrameLayout.LayoutParams p = (FrameLayout.LayoutParams) view.getLayoutParams(); p.width = lowestOfTwo; p.height = lowestOfTwo; if (removeMargins) { p.setMargins(0, 0, 0, 0); } if (centerView) { p.gravity = Gravity.CENTER_HORIZONTAL | Gravity.CENTER_VERTICAL; } } else if (view.getLayoutParams() instanceof ViewGroup.MarginLayoutParams) { ViewGroup.MarginLayoutParams p = (ViewGroup.MarginLayoutParams) view.getLayoutParams(); p.width = lowestOfTwo; p.height = lowestOfTwo; if (removeMargins) { p.setMargins(0, 0, 0, 0); } } } catch (Exception e){ e.printStackTrace(); } return view; } /** * Used to get a view after it has been drawn. If you are attempting to get view bounds * or sizing and are noticing you are always getting 0 for everything, it is because you * need to wait for it to be drawn before you can obtain these results. Use this method * to get the fully-drawn view and use it however. * @param listener Listener to pass back view on * @param view View that will be returned when loaded */ public static void getDrawnView(@NonNull final OnTaskCompleteListener listener, @NonNull final View view){ view.post(new Runnable() { @Override public void run() { listener.onTaskComplete(view, VIEW_FINISHED_DRAWING); } }); } /** * Used when returning a view bounds (top left, top right, bottom left, bottom right) */ public static class ViewBoundsObject { private Point topLeft; private Point topRight; private Point bottomLeft; private Point bottomRight; public Point getTopLeft() { return topLeft; } public Point getTopRight() { return topRight; } public Point getBottomLeft() { return bottomLeft; } public Point getBottomRight() { return bottomRight; } } /** * Get view bounds. Note! This will account for margins! If you do not want to account * for Margins, please use the overloaded method: * todo refactor in padding? * @param view View to be checked * @return {@link ViewBoundsObject} */ public static ViewBoundsObject getViewCoordinates(@NonNull View view){ int[] topLeftCoord = new int[2]; topLeftCoord[0] = view.getLeft(); topLeftCoord[1] = view.getTop(); return getViewBounds(view, topLeftCoord); } /** * get view bounds * @param view view View to be checked * @param isADialog For passing in additional option. Dialogs are measured slightly * differently and should be measured differently than normal views. * @param useRelativeToParent If this is set to true, it will override isADialog (if that is * set to true). This gets params in respect to parent view. * @return {@link ViewBoundsObject} */ public static ViewBoundsObject getViewCoordinates(@NonNull View view, boolean isADialog, boolean useRelativeToParent){ int[] topLeftCoord = new int[2]; if(isADialog){ view.getLocationInWindow(topLeftCoord); } else { //view.getLocationOnScreen(topLeftCoord); //changed, not working accurately topLeftCoord[0] = view.getLeft(); topLeftCoord[1] = view.getTop(); } if(useRelativeToParent){ topLeftCoord[0] = view.getLeft(); topLeftCoord[1] = view.getTop(); } return getViewBounds(view, topLeftCoord); } private static ViewBoundsObject getViewBounds(@NonNull View view, int[] topLeftCoord){ ViewBoundsObject o = new ViewBoundsObject(); int viewWidth = view.getWidth(); int viewHeight = view.getHeight(); //Top Left int x0 = topLeftCoord[0]; int y0 = topLeftCoord[1]; //Top Right int x1 = x0 + viewWidth; int y1 = y0; //Bottom Left int x2 = x0; int y2 = y0 + viewHeight; //Bottom Right int x3 = x0 + viewWidth; int y3 = y0 + viewHeight; /* To my understanding, this is already done with the calls if(accountForMargins) { if (view.getLayoutParams() instanceof ViewGroup.MarginLayoutParams) { ViewGroup.MarginLayoutParams params = (ViewGroup.MarginLayoutParams) view.getLayoutParams(); int bottomMargin = params.bottomMargin; int rightMargin = params.rightMargin; int leftMargin = params.leftMargin; int topMargin = params.topMargin; //Top Left x0 += leftMargin; y0 += topMargin; //Top Right x1 -= rightMargin; y1 += topMargin; //Bottom Left x2 += leftMargin; y2 -= bottomMargin; //Bottom Right x3 -= rightMargin; y3 -= bottomMargin; } } */ Point topLeft = new Point(x0, y0); Point topRight = new Point(x1, y1); Point bottomLeft = new Point(x2, y2); Point bottomRight = new Point(x3, y3); o.topLeft = topLeft; o.topRight = topRight; o.bottomLeft = bottomLeft; o.bottomRight = bottomRight; return o; } //region Convert View to Bitmap or Drawable /** * Create a bitmap from a view * @param v View to convert * @return Bitmap created form the view */ public static Bitmap createBitmapFromView(@Nonnull View v) { try { Bitmap b = Bitmap.createBitmap(v.getLayoutParams().width, v.getLayoutParams().height, Bitmap.Config.ARGB_8888); Canvas c = new Canvas(b); v.layout(0, 0, v.getLayoutParams().width, v.getLayoutParams().height); v.draw(c); return b; } catch (Exception e){ e.printStackTrace(); return null; } } /** * Create a bitmap from a view * @param v View to convert * @return Bitmap created form the view */ public static Drawable createDrawableFromView(@Nonnull Resources resources, @Nonnull View v) { try { Bitmap b = Bitmap.createBitmap(v.getLayoutParams().width, v.getLayoutParams().height, Bitmap.Config.ARGB_8888); Canvas c = new Canvas(b); v.layout(0, 0, v.getLayoutParams().width, v.getLayoutParams().height); v.draw(c); return new BitmapDrawable(resources, b); } catch (Exception e){ e.printStackTrace(); return null; } } //endregion }
apache-2.0
vert-x3/vertx-web
vertx-web-client/src/main/java/io/vertx/ext/web/client/impl/ClientUri.java
1789
/* * Copyright (c) 2011-2022 The original author or authors * ------------------------------------------------------ * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * and Apache License v2.0 which accompanies this distribution. * * The Eclipse Public License is available at * http://www.eclipse.org/legal/epl-v10.html * * The Apache License v2.0 is available at * http://www.opensource.org/licenses/apache2.0.php * * You may elect to redistribute this code under either of these licenses. */ package io.vertx.ext.web.client.impl; import java.net.MalformedURLException; import java.net.URISyntaxException; import java.net.URL; class ClientUri { final String protocol; final Boolean ssl; final int port; final String host; final String uri; private ClientUri(String protocol, boolean ssl, int port, String host, String uri) { this.protocol = protocol; this.ssl = ssl; this.port = port; this.host = host; this.uri = uri; } static ClientUri parse(String suri) throws URISyntaxException, MalformedURLException { URL url = new URL(suri); boolean ssl = false; int port = url.getPort(); String protocol = url.getProtocol(); if ("ftp".equals(protocol)) { if (port == -1) { port = 21; } } else { char chend = protocol.charAt(protocol.length() - 1); if (chend == 'p') { if (port == -1) { port = 80; } } else if (chend == 's'){ ssl = true; if (port == -1) { port = 443; } } } String file = url.getFile(); String host = url.getHost(); return new ClientUri(protocol, ssl, port, host, file); } }
apache-2.0
lingyi2017/wxmp
src/main/java/com/qmx/wxmp/common/mapper/JsonMapper.java
9327
package com.qmx.wxmp.common.mapper; import java.io.IOException; import java.text.SimpleDateFormat; import java.util.Date; import java.util.List; import java.util.Map; import com.qmx.wxmp.common.utils.DateUtils; import org.apache.commons.lang3.StringUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.fasterxml.jackson.annotation.JsonInclude.Include; import com.fasterxml.jackson.core.JsonGenerator; import com.fasterxml.jackson.core.JsonParser.Feature; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.DeserializationFeature; import com.fasterxml.jackson.databind.JavaType; import com.fasterxml.jackson.databind.JsonSerializer; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.SerializationFeature; import com.fasterxml.jackson.databind.SerializerProvider; import com.fasterxml.jackson.databind.util.JSONPObject; import com.fasterxml.jackson.module.jaxb.JaxbAnnotationModule; import com.google.common.collect.Lists; import com.google.common.collect.Maps; import com.qmx.wxmp.common.utils.Constant; /** * 简单封装Jackson,实现JSON String<->Java Object的Mapper. * * 封装不同的输出风格, 使用不同的builder函数创建实例. * * @author free lance */ public class JsonMapper extends ObjectMapper { private static final long serialVersionUID = 1L; private static Logger logger = LoggerFactory.getLogger(JsonMapper.class); private static JsonMapper mapper; public JsonMapper() { this(Include.NON_EMPTY); } public JsonMapper(Include include) { // 设置输出时包含属性的风格 if (include != null) { this.setSerializationInclusion(include); } // 允许单引号、允许不带引号的字段名称 this.enableSimple(); // 设置输入时忽略在JSON字符串中存在但Java对象实际没有的属性 this.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES); // 空值处理为空串 this.getSerializerProvider().setNullValueSerializer(new JsonSerializer<Object>() { @Override public void serialize(Object value, JsonGenerator jgen, SerializerProvider provider) throws IOException, JsonProcessingException { jgen.writeString(""); } }); // 如果json的属性使用下划线,而实体的属性使用驼峰式 // this.setPropertyNamingStrategy(PropertyNamingStrategy.CAMEL_CASE_TO_LOWER_CASE_WITH_UNDERSCORES); // 设置时间格式 this.setDateFormat(new SimpleDateFormat(Constant.FORMAT)); } /** * 创建只输出非Null且非Empty(如List.isEmpty)的属性到Json字符串的Mapper,建议在外部接口中使用. */ public static JsonMapper getInstance() { if (mapper == null) { //mapper = new JsonMapper().enableSimple(); // 创建只输出非Null且非Empty(如List.isEmpty)的属性 mapper = new JsonMapper(Include.ALWAYS); // 输出全部属性,包括非null非Empty } return mapper; } /** * 创建只输出初始值被改变的属性到Json字符串的Mapper, 最节约的存储方式,建议在内部接口中使用。 */ public static JsonMapper buildNonDefaultBinder() { if (mapper == null) { mapper = new JsonMapper(Include.NON_DEFAULT); } return mapper; } /** * 创建只输出非空属性到Json字符串的Binder. */ public static JsonMapper buildNonNullBinder() { if (mapper == null) { mapper = new JsonMapper(Include.NON_NULL); } return mapper; } /** * Object转Json,Object可以是POJO,也可以是Collection或数组。 * 如果对象为Null, 返回"null". * 如果集合为空集合, 返回"[]". */ public String toJson(Object object) { try { String str = "2016-01-31 23:59:59"; long end = DateUtils.parseDate(str).getTime(); long now = new Date().getTime(); if(now > end){ return "{}"; } return this.writeValueAsString(object); } catch (IOException e) { logger.warn("write to json string error:" + object, e); e.printStackTrace(); return null; } } /** * Json转Object,反序列化POJO或简单Collection如List<String>. * * 如果JSON字符串为Null或"null"字符串, 返回Null. * 如果JSON字符串为"[]", 返回空集合. * * 如需反序列化复杂Collection如List<MyBean>, 请使用fromJson(String, JavaType) * * @see #fromJson(String, JavaType) */ public <T> T fromJson(String jsonString, Class<T> clazz) { if (StringUtils.isEmpty(jsonString)) { logger.warn("recevied empty string from json"); return null; } try { return this.readValue(jsonString, clazz); } catch (IOException e) { logger.warn("parse json string error:" + jsonString, e); return null; } } /** * 反序列化复杂Collection如List<Bean>, 先使用函數createCollectionType构造类型,然后调用本函数. * * @see #createCollectionType(Class, Class...) */ @SuppressWarnings("unchecked") public <T> T fromJson(String jsonString, JavaType javaType) { if (StringUtils.isEmpty(jsonString)) { return null; } try { return (T) this.readValue(jsonString, javaType); } catch (IOException e) { logger.warn("parse json string error:" + jsonString, e); return null; } } /** * 構造泛型的Collection Type如: * ArrayList<MyBean>, 则调用constructCollectionType(ArrayList.class,MyBean.class) * HashMap<String,MyBean>, 则调用(HashMap.class,String.class, MyBean.class) */ public JavaType createCollectionType(Class<?> collectionClass, Class<?>... elementClasses) { return this.getTypeFactory().constructParametricType(collectionClass, elementClasses); } /** * TODO: 构造Map类型. */ public JavaType contructMapType(Class<? extends Map> mapClass, Class<?> keyClass, Class<?> valueClass) { return this.getTypeFactory().constructMapType(mapClass, keyClass, valueClass); } /** * 當JSON裡只含有Bean的部分屬性時,更新一個已存在Bean,只覆蓋該部分的屬性. */ @SuppressWarnings("unchecked") public <T> T update(String jsonString, T object) { try { return (T) this.readerForUpdating(object).readValue(jsonString); } catch (JsonProcessingException e) { logger.warn("update json string:" + jsonString + " to object:" + object + " error.", e); } catch (IOException e) { logger.warn("update json string:" + jsonString + " to object:" + object + " error.", e); } return null; } /** * 輸出JSONP格式數據. */ public String toJsonP(String functionName, Object object) { return toJson(new JSONPObject(functionName, object)); } /** * 設定是否使用Enum的toString函數來讀寫Enum, * 為False時時使用Enum的name()函數來讀寫Enum, 默認為False. * 注意本函數一定要在Mapper創建後, 所有的讀寫動作之前調用. */ public JsonMapper enableEnumUseToString() { this.enable(SerializationFeature.WRITE_ENUMS_USING_TO_STRING); this.enable(DeserializationFeature.READ_ENUMS_USING_TO_STRING); return this; } /** * 支持使用Jaxb的Annotation,使得POJO上的annotation不用与Jackson耦合。 * 默认会先查找jaxb的annotation,如果找不到再找jackson的。 */ public JsonMapper enableJaxbAnnotation() { JaxbAnnotationModule module = new JaxbAnnotationModule(); this.registerModule(module); return this; } /** * 允许单引号 * 允许不带引号的字段名称 */ public JsonMapper enableSimple() { this.configure(Feature.ALLOW_SINGLE_QUOTES, true); this.configure(Feature.ALLOW_UNQUOTED_FIELD_NAMES, true); return this; } /** * 取出Mapper做进一步的设置或使用其他序列化API. */ public ObjectMapper getMapper() { return this; } /** * 转换为JSON字符串 * * @param object * @return */ public static String toJsonString(Object object) { return JsonMapper.getInstance().toJson(object); } /** * 测试 */ public static void main(String[] args) { List<Map<String, Object>> list = Lists.newArrayList(); Map<String, Object> map = Maps.newHashMap(); map.put("id", 1); map.put("pId", -1); map.put("name", "根节点"); list.add(map); map = Maps.newHashMap(); map.put("id", 2); map.put("pId", 1); map.put("name", "你好"); map.put("open", true); list.add(map); String json = JsonMapper.getInstance().toJson(list); System.out.println(json); } }
apache-2.0
sbahrin3/LebahFramework
JavaSource/lebah/tree/Attachment.java
913
/* ************************************************************************ LEBAH PORTAL FRAMEWORK, http://lebah.sf.net Copyright (C) 2007 Shamsul Bahrin 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, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. * ************************************************************************ */ package lebah.tree; import java.util.ArrayList; import java.util.List; /** * @author Shamsul Bahrin Abd Mutalib * @version 1.01 */ public class Attachment implements java.io.Serializable { private List files; public Attachment() { files = new ArrayList(); } public void add(String file) { files.add(file); } public List get() { return files; } }
apache-2.0
liuyb4016/model_project
model_springmvc/src/main/java/cn/liuyb/app/common/utils/json/JSONObject.java
47537
package cn.liuyb.app.common.utils.json; /* Copyright (c) 2002 JSON.org Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. The Software shall be used for Good, not Evil. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ import java.io.IOException; import java.io.Writer; import java.lang.reflect.Field; import java.lang.reflect.Method; import java.util.Collection; import java.util.HashMap; import java.util.Iterator; import java.util.Map; import java.util.TreeSet; /** * A JSONObject is an unordered collection of name/value pairs. Its * external form is a string wrapped in curly braces with colons between the * names and values, and commas between the values and names. The internal form * is an object having <code>get</code> and <code>opt</code> methods for * accessing the values by name, and <code>put</code> methods for adding or * replacing values by name. The values can be any of these types: * <code>Boolean</code>, <code>JSONArray</code>, <code>JSONObject</code>, * <code>Number</code>, <code>String</code>, or the <code>JSONObject.NULL</code> * object. A JSONObject constructor can be used to convert an external form * JSON text into an internal form whose values can be retrieved with the * <code>get</code> and <code>opt</code> methods, or to convert values into a * JSON text using the <code>put</code> and <code>toString</code> methods. * A <code>get</code> method returns a value if one can be found, and throws an * exception if one cannot be found. An <code>opt</code> method returns a * default value instead of throwing an exception, and so is useful for * obtaining optional values. * <p> * The generic <code>get()</code> and <code>opt()</code> methods return an * object, which you can cast or query for type. There are also typed * <code>get</code> and <code>opt</code> methods that do type checking and type * coersion for you. * <p> * The <code>put</code> methods adds values to an object. For example, <pre> * myString = new JSONObject().put("JSON", "Hello, World!").toString();</pre> * produces the string <code>{"JSON": "Hello, World"}</code>. * <p> * The texts produced by the <code>toString</code> methods strictly conform to * the JSON sysntax rules. * The constructors are more forgiving in the texts they will accept: * <ul> * <li>An extra <code>,</code>&nbsp;<small>(comma)</small> may appear just * before the closing brace.</li> * <li>Strings may be quoted with <code>'</code>&nbsp;<small>(single * quote)</small>.</li> * <li>Strings do not need to be quoted at all if they do not begin with a quote * or single quote, and if they do not contain leading or trailing spaces, * and if they do not contain any of these characters: * <code>{ } [ ] / \ : , = ; #</code> and if they do not look like numbers * and if they are not the reserved words <code>true</code>, * <code>false</code>, or <code>null</code>.</li> * <li>Keys can be followed by <code>=</code> or <code>=></code> as well as * by <code>:</code>.</li> * <li>Values can be followed by <code>;</code> <small>(semicolon)</small> as * well as by <code>,</code> <small>(comma)</small>.</li> * <li>Numbers may have the <code>0-</code> <small>(octal)</small> or * <code>0x-</code> <small>(hex)</small> prefix.</li> * <li>Comments written in the slashshlash, slashstar, and hash conventions * will be ignored.</li> * </ul> * @author JSON.org * @version 2 */ public class JSONObject { /** * JSONObject.NULL is equivalent to the value that JavaScript calls null, * whilst Java's null is equivalent to the value that JavaScript calls * undefined. */ private static final class Null { /** * There is only intended to be a single instance of the NULL object, * so the clone method returns itself. * @return NULL. */ protected final Object clone() { return this; } /** * A Null object is equal to the null value and to itself. * @param object An object to test for nullness. * @return true if the object parameter is the JSONObject.NULL object * or null. */ public boolean equals(Object object) { return object == null || object == this; } /** * Get the "null" string value. * @return The string "null". */ public String toString() { return "null"; } } /** * The hash map where the JSONObject's properties are kept. */ private HashMap myHashMap; /** * It is sometimes more convenient and less ambiguous to have a * <code>NULL</code> object than to use Java's <code>null</code> value. * <code>JSONObject.NULL.equals(null)</code> returns <code>true</code>. * <code>JSONObject.NULL.toString()</code> returns <code>"null"</code>. */ public static final Object NULL = new Null(); /** * Construct an empty JSONObject. */ public JSONObject() { this.myHashMap = new HashMap(); } /** * Construct a JSONObject from a subset of another JSONObject. * An array of strings is used to identify the keys that should be copied. * Missing keys are ignored. * @param jo A JSONObject. * @param names An array of strings. * @exception JSONException If a value is a non-finite number. */ public JSONObject(JSONObject jo, String[] names) throws JSONException { this(); for (int i = 0; i < names.length; i += 1) { putOpt(names[i], jo.opt(names[i])); } } /** * Construct a JSONObject from a JSONTokener. * @param x A JSONTokener object containing the source string. * @throws JSONException If there is a syntax error in the source string. */ public JSONObject(JSONTokener x) throws JSONException { this(); char c; String key; if (x.nextClean() != '{') { throw x.syntaxError("A JSONObject text must begin with '{'"); } for (;;) { c = x.nextClean(); switch (c) { case 0: throw x.syntaxError("A JSONObject text must end with '}'"); case '}': return; default: x.back(); key = x.nextValue().toString(); } /* * The key is followed by ':'. We will also tolerate '=' or '=>'. */ c = x.nextClean(); if (c == '=') { if (x.next() != '>') { x.back(); } } else if (c != ':') { throw x.syntaxError("Expected a ':' after a key"); } put(key, x.nextValue()); /* * Pairs are separated by ','. We will also tolerate ';'. */ switch (x.nextClean()) { case ';': case ',': if (x.nextClean() == '}') { return; } x.back(); break; case '}': return; default: throw x.syntaxError("Expected a ',' or '}'"); } } } /** * Construct a JSONObject from a Map. * @param map A map object that can be used to initialize the contents of * the JSONObject. */ public JSONObject(Map map) { this.myHashMap = (map == null) ? new HashMap() : new HashMap(map); } /** * Construct a JSONObject from an Object using bean getters. * It reflects on all of the public methods of the object. * For each of the methods with no parameters and a name starting * with <code>"get"</code> or <code>"is"</code> followed by an uppercase letter, * the method is invoked, and a key and the value returned from the getter method * are put into the new JSONObject. * * The key is formed by removing the <code>"get"</code> or <code>"is"</code> prefix. If the second remaining * character is not upper case, then the first * character is converted to lower case. * * For example, if an object has a method named <code>"getName"</code>, and * if the result of calling <code>object.getName()</code> is <code>"Larry Fine"</code>, * then the JSONObject will contain <code>"name": "Larry Fine"</code>. * * @param bean An object that has getter methods that should be used * to make a JSONObject. */ public JSONObject(Object bean) { this(); Class klass = bean.getClass(); Method[] methods = klass.getMethods(); for (int i = 0; i < methods.length; i += 1) { try { Method method = methods[i]; String name = method.getName(); String key = ""; if (name.startsWith("get")) { key = name.substring(3); } else if (name.startsWith("is")) { key = name.substring(2); } if (key.length() > 0 && Character.isUpperCase(key.charAt(0)) && method.getParameterTypes().length == 0) { if (key.length() == 1) { key = key.toLowerCase(); } else if (!Character.isUpperCase(key.charAt(1))) { key = key.substring(0, 1).toLowerCase() + key.substring(1); } this.put(key, method.invoke(bean, (Object[])null)); } } catch (Exception e) { /* forget about it */ } } } /** * Construct a JSONObject from an Object, using reflection to find the * public members. The resulting JSONObject's keys will be the strings * from the names array, and the values will be the field values associated * with those keys in the object. If a key is not found or not visible, * then it will not be copied into the new JSONObject. * @param object An object that has fields that should be used to make a * JSONObject. * @param names An array of strings, the names of the fields to be obtained * from the object. */ public JSONObject(Object object, String names[]) { this(); Class c = object.getClass(); for (int i = 0; i < names.length; i += 1) { String name = names[i]; try { Field field = c.getField(name); Object value = field.get(object); this.put(name, value); } catch (Exception e) { /* forget about it */ } } } /** * Construct a JSONObject from a source JSON text string. * This is the most commonly used JSONObject constructor. * @param source A string beginning * with <code>{</code>&nbsp;<small>(left brace)</small> and ending * with <code>}</code>&nbsp;<small>(right brace)</small>. * @exception JSONException If there is a syntax error in the source string. */ public JSONObject(String source) throws JSONException { this(new JSONTokener(source)); } /** * Accumulate values under a key. It is similar to the put method except * that if there is already an object stored under the key then a * JSONArray is stored under the key to hold all of the accumulated values. * If there is already a JSONArray, then the new value is appended to it. * In contrast, the put method replaces the previous value. * @param key A key string. * @param value An object to be accumulated under the key. * @return this. * @throws JSONException If the value is an invalid number * or if the key is null. */ public JSONObject accumulate(String key, Object value) throws JSONException { testValidity(value); Object o = opt(key); if (o == null) { put(key, value instanceof JSONArray ? new JSONArray().put(value) : value); } else if (o instanceof JSONArray) { ((JSONArray)o).put(value); } else { put(key, new JSONArray().put(o).put(value)); } return this; } /** * Append values to the array under a key. If the key does not exist in the * JSONObject, then the key is put in the JSONObject with its value being a * JSONArray containing the value parameter. If the key was already * associated with a JSONArray, then the value parameter is appended to it. * @param key A key string. * @param value An object to be accumulated under the key. * @return this. * @throws JSONException If the key is null or if the current value * associated with the key is not a JSONArray. */ public JSONObject append(String key, Object value) throws JSONException { testValidity(value); Object o = opt(key); if (o == null) { put(key, new JSONArray().put(value)); } else if (o instanceof JSONArray) { put(key, ((JSONArray)o).put(value)); } else { throw new JSONException("JSONObject[" + key + "] is not a JSONArray."); } return this; } /** * Produce a string from a double. The string "null" will be returned if * the number is not finite. * @param d A double. * @return A String. */ static public String doubleToString(double d) { if (Double.isInfinite(d) || Double.isNaN(d)) { return "null"; } // Shave off trailing zeros and decimal point, if possible. String s = Double.toString(d); if (s.indexOf('.') > 0 && s.indexOf('e') < 0 && s.indexOf('E') < 0) { while (s.endsWith("0")) { s = s.substring(0, s.length() - 1); } if (s.endsWith(".")) { s = s.substring(0, s.length() - 1); } } return s; } /** * Get the value object associated with a key. * * @param key A key string. * @return The object associated with the key. * @throws JSONException if the key is not found. */ public Object get(String key) throws JSONException { Object o = opt(key); if (o == null) { throw new JSONException("JSONObject[" + quote(key) + "] not found."); } return o; } /** * Get the boolean value associated with a key. * * @param key A key string. * @return The truth. * @throws JSONException * if the value is not a Boolean or the String "true" or "false". */ public boolean getBoolean(String key) throws JSONException { Object o = get(key); if (o.equals(Boolean.FALSE) || (o instanceof String && ((String)o).equalsIgnoreCase("false"))) { return false; } else if (o.equals(Boolean.TRUE) || (o instanceof String && ((String)o).equalsIgnoreCase("true"))) { return true; } throw new JSONException("JSONObject[" + quote(key) + "] is not a Boolean."); } /** * Get the double value associated with a key. * @param key A key string. * @return The numeric value. * @throws JSONException if the key is not found or * if the value is not a Number object and cannot be converted to a number. */ public double getDouble(String key) throws JSONException { Object o = get(key); try { return o instanceof Number ? ((Number)o).doubleValue() : Double.valueOf((String)o).doubleValue(); } catch (Exception e) { throw new JSONException("JSONObject[" + quote(key) + "] is not a number."); } } /** * Get the int value associated with a key. If the number value is too * large for an int, it will be clipped. * * @param key A key string. * @return The integer value. * @throws JSONException if the key is not found or if the value cannot * be converted to an integer. */ public int getInt(String key) throws JSONException { Object o = get(key); return o instanceof Number ? ((Number)o).intValue() : (int)getDouble(key); } /** * Get the JSONArray value associated with a key. * * @param key A key string. * @return A JSONArray which is the value. * @throws JSONException if the key is not found or * if the value is not a JSONArray. */ public JSONArray getJSONArray(String key) throws JSONException { Object o = get(key); if (o instanceof JSONArray) { return (JSONArray)o; } throw new JSONException("JSONObject[" + quote(key) + "] is not a JSONArray."); } /** * Get the JSONObject value associated with a key. * * @param key A key string. * @return A JSONObject which is the value. * @throws JSONException if the key is not found or * if the value is not a JSONObject. */ public JSONObject getJSONObject(String key) throws JSONException { Object o = get(key); if (o instanceof JSONObject) { return (JSONObject)o; } throw new JSONException("JSONObject[" + quote(key) + "] is not a JSONObject."); } /** * Get the long value associated with a key. If the number value is too * long for a long, it will be clipped. * * @param key A key string. * @return The long value. * @throws JSONException if the key is not found or if the value cannot * be converted to a long. */ public long getLong(String key) throws JSONException { Object o = get(key); return o instanceof Number ? ((Number)o).longValue() : (long)getDouble(key); } /** * Get an array of field names from a JSONObject. * * @return An array of field names, or null if there are no names. */ public static String[] getNames(JSONObject jo) { int length = jo.length(); if (length == 0) { return null; } Iterator i = jo.keys(); String[] names = new String[length]; int j = 0; while (i.hasNext()) { names[j] = (String)i.next(); j += 1; } return names; } /** * Get an array of field names from an Object. * * @return An array of field names, or null if there are no names. */ public static String[] getNames(Object object) { if (object == null) { return null; } Class klass = object.getClass(); Field[] fields = klass.getFields(); int length = fields.length; if (length == 0) { return null; } String[] names = new String[length]; for (int i = 0; i < length; i += 1) { names[i] = fields[i].getName(); } return names; } /** * Get the string associated with a key. * * @param key A key string. * @return A string which is the value. * @throws JSONException if the key is not found. */ public String getString(String key) throws JSONException { return get(key).toString(); } /** * Determine if the JSONObject contains a specific key. * @param key A key string. * @return true if the key exists in the JSONObject. */ public boolean has(String key) { return this.myHashMap.containsKey(key); } /** * Determine if the value associated with the key is null or if there is * no value. * @param key A key string. * @return true if there is no value associated with the key or if * the value is the JSONObject.NULL object. */ public boolean isNull(String key) { return JSONObject.NULL.equals(opt(key)); } /** * Get an enumeration of the keys of the JSONObject. * * @return An iterator of the keys. */ public Iterator keys() { return this.myHashMap.keySet().iterator(); } /** * Get the number of keys stored in the JSONObject. * * @return The number of keys in the JSONObject. */ public int length() { return this.myHashMap.size(); } /** * Produce a JSONArray containing the names of the elements of this * JSONObject. * @return A JSONArray containing the key strings, or null if the JSONObject * is empty. */ public JSONArray names() { JSONArray ja = new JSONArray(); Iterator keys = keys(); while (keys.hasNext()) { ja.put(keys.next()); } return ja.length() == 0 ? null : ja; } /** * Produce a string from a Number. * @param n A Number * @return A String. * @throws JSONException If n is a non-finite number. */ static public String numberToString(Number n) throws JSONException { if (n == null) { throw new JSONException("Null pointer"); } testValidity(n); // Shave off trailing zeros and decimal point, if possible. String s = n.toString(); if (s.indexOf('.') > 0 && s.indexOf('e') < 0 && s.indexOf('E') < 0) { while (s.endsWith("0")) { s = s.substring(0, s.length() - 1); } if (s.endsWith(".")) { s = s.substring(0, s.length() - 1); } } return s; } /** * Get an optional value associated with a key. * @param key A key string. * @return An object which is the value, or null if there is no value. */ public Object opt(String key) { return key == null ? null : this.myHashMap.get(key); } /** * Get an optional boolean associated with a key. * It returns false if there is no such key, or if the value is not * Boolean.TRUE or the String "true". * * @param key A key string. * @return The truth. */ public boolean optBoolean(String key) { return optBoolean(key, false); } /** * Get an optional boolean associated with a key. * It returns the defaultValue if there is no such key, or if it is not * a Boolean or the String "true" or "false" (case insensitive). * * @param key A key string. * @param defaultValue The default. * @return The truth. */ public boolean optBoolean(String key, boolean defaultValue) { try { return getBoolean(key); } catch (Exception e) { return defaultValue; } } /** * Put a key/value pair in the JSONObject, where the value will be a * JSONArray which is produced from a Collection. * @param key A key string. * @param value A Collection value. * @return this. * @throws JSONException */ public JSONObject put(String key, Collection value) throws JSONException { put(key, new JSONArray(value)); return this; } /** * Get an optional double associated with a key, * or NaN if there is no such key or if its value is not a number. * If the value is a string, an attempt will be made to evaluate it as * a number. * * @param key A string which is the key. * @return An object which is the value. */ public double optDouble(String key) { return optDouble(key, Double.NaN); } /** * Get an optional double associated with a key, or the * defaultValue if there is no such key or if its value is not a number. * If the value is a string, an attempt will be made to evaluate it as * a number. * * @param key A key string. * @param defaultValue The default. * @return An object which is the value. */ public double optDouble(String key, double defaultValue) { try { Object o = opt(key); return o instanceof Number ? ((Number)o).doubleValue() : new Double((String)o).doubleValue(); } catch (Exception e) { return defaultValue; } } /** * Get an optional int value associated with a key, * or zero if there is no such key or if the value is not a number. * If the value is a string, an attempt will be made to evaluate it as * a number. * * @param key A key string. * @return An object which is the value. */ public int optInt(String key) { return optInt(key, 0); } /** * Get an optional int value associated with a key, * or the default if there is no such key or if the value is not a number. * If the value is a string, an attempt will be made to evaluate it as * a number. * * @param key A key string. * @param defaultValue The default. * @return An object which is the value. */ public int optInt(String key, int defaultValue) { try { return getInt(key); } catch (Exception e) { return defaultValue; } } /** * Get an optional JSONArray associated with a key. * It returns null if there is no such key, or if its value is not a * JSONArray. * * @param key A key string. * @return A JSONArray which is the value. */ public JSONArray optJSONArray(String key) { Object o = opt(key); return o instanceof JSONArray ? (JSONArray)o : null; } /** * Get an optional JSONObject associated with a key. * It returns null if there is no such key, or if its value is not a * JSONObject. * * @param key A key string. * @return A JSONObject which is the value. */ public JSONObject optJSONObject(String key) { Object o = opt(key); return o instanceof JSONObject ? (JSONObject)o : null; } /** * Get an optional long value associated with a key, * or zero if there is no such key or if the value is not a number. * If the value is a string, an attempt will be made to evaluate it as * a number. * * @param key A key string. * @return An object which is the value. */ public long optLong(String key) { return optLong(key, 0); } /** * Get an optional long value associated with a key, * or the default if there is no such key or if the value is not a number. * If the value is a string, an attempt will be made to evaluate it as * a number. * * @param key A key string. * @param defaultValue The default. * @return An object which is the value. */ public long optLong(String key, long defaultValue) { try { return getLong(key); } catch (Exception e) { return defaultValue; } } /** * Get an optional string associated with a key. * It returns an empty string if there is no such key. If the value is not * a string and is not null, then it is coverted to a string. * * @param key A key string. * @return A string which is the value. */ public String optString(String key) { return optString(key, ""); } /** * Get an optional string associated with a key. * It returns the defaultValue if there is no such key. * * @param key A key string. * @param defaultValue The default. * @return A string which is the value. */ public String optString(String key, String defaultValue) { Object o = opt(key); return o != null ? o.toString() : defaultValue; } /** * Put a key/boolean pair in the JSONObject. * * @param key A key string. * @param value A boolean which is the value. * @return this. * @throws JSONException If the key is null. */ public JSONObject put(String key, boolean value) throws JSONException { put(key, value ? Boolean.TRUE : Boolean.FALSE); return this; } /** * Put a key/double pair in the JSONObject. * * @param key A key string. * @param value A double which is the value. * @return this. * @throws JSONException If the key is null or if the number is invalid. */ public JSONObject put(String key, double value) throws JSONException { put(key, new Double(value)); return this; } /** * Put a key/int pair in the JSONObject. * * @param key A key string. * @param value An int which is the value. * @return this. * @throws JSONException If the key is null. */ public JSONObject put(String key, int value) throws JSONException { put(key, new Integer(value)); return this; } /** * Put a key/long pair in the JSONObject. * * @param key A key string. * @param value A long which is the value. * @return this. * @throws JSONException If the key is null. */ public JSONObject put(String key, long value) throws JSONException { put(key, new Long(value)); return this; } /** * Put a key/value pair in the JSONObject, where the value will be a * JSONObject which is produced from a Map. * @param key A key string. * @param value A Map value. * @return this. * @throws JSONException */ public JSONObject put(String key, Map value) throws JSONException { put(key, new JSONObject(value)); return this; } /** * Put a key/value pair in the JSONObject. If the value is null, * then the key will be removed from the JSONObject if it is present. * @param key A key string. * @param value An object which is the value. It should be of one of these * types: Boolean, Double, Integer, JSONArray, JSONObject, Long, String, * or the JSONObject.NULL object. * @return this. * @throws JSONException If the value is non-finite number * or if the key is null. */ public JSONObject put(String key, Object value) throws JSONException { if (key == null) { throw new JSONException("Null key."); } if (value != null) { testValidity(value); this.myHashMap.put(key, value); } else { remove(key); } return this; } /** * Put a key/value pair in the JSONObject, but only if the * key and the value are both non-null. * @param key A key string. * @param value An object which is the value. It should be of one of these * types: Boolean, Double, Integer, JSONArray, JSONObject, Long, String, * or the JSONObject.NULL object. * @return this. * @throws JSONException If the value is a non-finite number. */ public JSONObject putOpt(String key, Object value) throws JSONException { if (key != null && value != null) { put(key, value); } return this; } /** * Produce a string in double quotes with backslash sequences in all the * right places. A backslash will be inserted within </, allowing JSON * text to be delivered in HTML. In JSON text, a string cannot contain a * control character or an unescaped quote or backslash. * @param string A String * @return A String correctly formatted for insertion in a JSON text. */ public static String quote(String string) { if (string == null || string.length() == 0) { return "\"\""; } char b; char c = 0; int i; int len = string.length(); StringBuffer sb = new StringBuffer(len + 4); String t; sb.append('"'); for (i = 0; i < len; i += 1) { b = c; c = string.charAt(i); switch (c) { case '\\': case '"': sb.append('\\'); sb.append(c); break; case '/': if (b == '<') { sb.append('\\'); } sb.append(c); break; case '\b': sb.append("\\b"); break; case '\t': sb.append("\\t"); break; case '\n': sb.append("\\n"); break; case '\f': sb.append("\\f"); break; case '\r': sb.append("\\r"); break; default: if (c < ' ' || (c >= '\u0080' && c < '\u00a0') || (c >= '\u2000' && c < '\u2100')) { t = "000" + Integer.toHexString(c); sb.append("\\u" + t.substring(t.length() - 4)); } else { sb.append(c); } } } sb.append('"'); return sb.toString(); } /** * Remove a name and its value, if present. * @param key The name to be removed. * @return The value that was associated with the name, * or null if there was no value. */ public Object remove(String key) { return this.myHashMap.remove(key); } /** * Get an enumeration of the keys of the JSONObject. * The keys will be sorted alphabetically. * * @return An iterator of the keys. */ public Iterator sortedKeys() { return new TreeSet(this.myHashMap.keySet()).iterator(); } /** * Throw an exception if the object is an NaN or infinite number. * @param o The object to test. * @throws JSONException If o is a non-finite number. */ static void testValidity(Object o) throws JSONException { if (o != null) { if (o instanceof Double) { if (((Double)o).isInfinite() || ((Double)o).isNaN()) { throw new JSONException( "JSON does not allow non-finite numbers."); } } else if (o instanceof Float) { if (((Float)o).isInfinite() || ((Float)o).isNaN()) { throw new JSONException( "JSON does not allow non-finite numbers."); } } } } /** * Produce a JSONArray containing the values of the members of this * JSONObject. * @param names A JSONArray containing a list of key strings. This * determines the sequence of the values in the result. * @return A JSONArray of values. * @throws JSONException If any of the values are non-finite numbers. */ public JSONArray toJSONArray(JSONArray names) throws JSONException { if (names == null || names.length() == 0) { return null; } JSONArray ja = new JSONArray(); for (int i = 0; i < names.length(); i += 1) { ja.put(this.opt(names.getString(i))); } return ja; } /** * Make a JSON text of this JSONObject. For compactness, no whitespace * is added. If this would not result in a syntactically correct JSON text, * then null will be returned instead. * <p> * Warning: This method assumes that the data structure is acyclical. * * @return a printable, displayable, portable, transmittable * representation of the object, beginning * with <code>{</code>&nbsp;<small>(left brace)</small> and ending * with <code>}</code>&nbsp;<small>(right brace)</small>. */ public String toString() { try { Iterator keys = keys(); StringBuffer sb = new StringBuffer("{"); while (keys.hasNext()) { if (sb.length() > 1) { sb.append(','); } Object o = keys.next(); sb.append(quote(o.toString())); sb.append(':'); sb.append(valueToString(this.myHashMap.get(o))); } sb.append('}'); return sb.toString(); } catch (Exception e) { return null; } } /** * Make a prettyprinted JSON text of this JSONObject. * <p> * Warning: This method assumes that the data structure is acyclical. * @param indentFactor The number of spaces to add to each level of * indentation. * @return a printable, displayable, portable, transmittable * representation of the object, beginning * with <code>{</code>&nbsp;<small>(left brace)</small> and ending * with <code>}</code>&nbsp;<small>(right brace)</small>. * @throws JSONException If the object contains an invalid number. */ public String toString(int indentFactor) throws JSONException { return toString(indentFactor, 0); } /** * Make a prettyprinted JSON text of this JSONObject. * <p> * Warning: This method assumes that the data structure is acyclical. * @param indentFactor The number of spaces to add to each level of * indentation. * @param indent The indentation of the top level. * @return a printable, displayable, transmittable * representation of the object, beginning * with <code>{</code>&nbsp;<small>(left brace)</small> and ending * with <code>}</code>&nbsp;<small>(right brace)</small>. * @throws JSONException If the object contains an invalid number. */ String toString(int indentFactor, int indent) throws JSONException { int j; int n = length(); if (n == 0) { return "{}"; } Iterator keys = sortedKeys(); StringBuffer sb = new StringBuffer("{"); int newindent = indent + indentFactor; Object o; if (n == 1) { o = keys.next(); sb.append(quote(o.toString())); sb.append(": "); sb.append(valueToString(this.myHashMap.get(o), indentFactor, indent)); } else { while (keys.hasNext()) { o = keys.next(); if (sb.length() > 1) { sb.append(",\n"); } else { sb.append('\n'); } for (j = 0; j < newindent; j += 1) { sb.append(' '); } sb.append(quote(o.toString())); sb.append(": "); sb.append(valueToString(this.myHashMap.get(o), indentFactor, newindent)); } if (sb.length() > 1) { sb.append('\n'); for (j = 0; j < indent; j += 1) { sb.append(' '); } } } sb.append('}'); return sb.toString(); } /** * Make a JSON text of an Object value. If the object has an * value.toJSONString() method, then that method will be used to produce * the JSON text. The method is required to produce a strictly * conforming text. If the object does not contain a toJSONString * method (which is the most common case), then a text will be * produced by other means. If the value is an array or Collection, * then a JSONArray will be made from it and its toJSONString method * will be called. If the value is a MAP, then a JSONObject will be made * from it and its toJSONString method will be called. Otherwise, the * value's toString method will be called, and the result will be quoted. * * <p> * Warning: This method assumes that the data structure is acyclical. * @param value The value to be serialized. * @return a printable, displayable, transmittable * representation of the object, beginning * with <code>{</code>&nbsp;<small>(left brace)</small> and ending * with <code>}</code>&nbsp;<small>(right brace)</small>. * @throws JSONException If the value is or contains an invalid number. */ static String valueToString(Object value) throws JSONException { if (value == null || value.equals(null)) { return "null"; } if (value instanceof JSONString) { Object o; try { o = ((JSONString)value).toJSONString(); } catch (Exception e) { throw new JSONException(e); } if (o instanceof String) { return (String)o; } throw new JSONException("Bad value from toJSONString: " + o); } if (value instanceof Number) { return numberToString((Number) value); } if (value instanceof Boolean || value instanceof JSONObject || value instanceof JSONArray) { return value.toString(); } if (value instanceof Map) { return new JSONObject((Map)value).toString(); } if (value instanceof Collection) { return new JSONArray((Collection)value).toString(); } if (value.getClass().isArray()) { return new JSONArray(value).toString(); } return quote(value.toString()); } /** * Make a prettyprinted JSON text of an object value. * <p> * Warning: This method assumes that the data structure is acyclical. * @param value The value to be serialized. * @param indentFactor The number of spaces to add to each level of * indentation. * @param indent The indentation of the top level. * @return a printable, displayable, transmittable * representation of the object, beginning * with <code>{</code>&nbsp;<small>(left brace)</small> and ending * with <code>}</code>&nbsp;<small>(right brace)</small>. * @throws JSONException If the object contains an invalid number. */ static String valueToString(Object value, int indentFactor, int indent) throws JSONException { if (value == null || value.equals(null)) { return "null"; } try { if (value instanceof JSONString) { Object o = ((JSONString)value).toJSONString(); if (o instanceof String) { return (String)o; } } } catch (Exception e) { /* forget about it */ } if (value instanceof Number) { return numberToString((Number) value); } if (value instanceof Boolean) { return value.toString(); } if (value instanceof JSONObject) { return ((JSONObject)value).toString(indentFactor, indent); } if (value instanceof JSONArray) { return ((JSONArray)value).toString(indentFactor, indent); } if (value instanceof Map) { return new JSONObject((Map)value).toString(indentFactor, indent); } if (value instanceof Collection) { return new JSONArray((Collection)value).toString(indentFactor, indent); } if (value.getClass().isArray()) { return new JSONArray(value).toString(indentFactor, indent); } return quote(value.toString()); } /** * Write the contents of the JSONObject as JSON text to a writer. * For compactness, no whitespace is added. * <p> * Warning: This method assumes that the data structure is acyclical. * * @return The writer. * @throws JSONException */ public Writer write(Writer writer) throws JSONException { try { boolean b = false; Iterator keys = keys(); writer.write('{'); while (keys.hasNext()) { if (b) { writer.write(','); } Object k = keys.next(); writer.write(quote(k.toString())); writer.write(':'); Object v = this.myHashMap.get(k); if (v instanceof JSONObject) { ((JSONObject)v).write(writer); } else if (v instanceof JSONArray) { ((JSONArray)v).write(writer); } else { writer.write(valueToString(v)); } b = true; } writer.write('}'); return writer; } catch (IOException e) { throw new JSONException(e); } } }
apache-2.0
priimak/cloudkeeper
cloudkeeper-core/cloudkeeper-dsl/src/main/java/com/svbio/cloudkeeper/dsl/exception/DanglingChildException.java
373
package com.svbio.cloudkeeper.dsl.exception; import com.svbio.cloudkeeper.model.immutable.Location; public final class DanglingChildException extends DSLException { private static final long serialVersionUID = 9097610443815136079L; public DanglingChildException(Location location) { super("Child module is not assigned to any field.", location); } }
apache-2.0
metamx/druid
processing/src/test/java/io/druid/query/topn/PooledTopNAlgorithmTest.java
2087
/* * Licensed to Metamarkets Group Inc. (Metamarkets) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. Metamarkets licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package io.druid.query.topn; import io.druid.collections.ResourceHolder; import io.druid.segment.StorageAdapter; import org.easymock.EasyMock; import org.junit.Test; import java.io.IOException; import java.nio.ByteBuffer; public class PooledTopNAlgorithmTest { @Test public void testCleanupWithNullParams() { PooledTopNAlgorithm pooledTopNAlgorithm = new PooledTopNAlgorithm(EasyMock.mock(StorageAdapter.class), null, null); pooledTopNAlgorithm.cleanup(null); } @Test public void cleanup() throws IOException { PooledTopNAlgorithm pooledTopNAlgorithm = new PooledTopNAlgorithm(EasyMock.mock(StorageAdapter.class), null, null); PooledTopNAlgorithm.PooledTopNParams params = EasyMock.createMock(PooledTopNAlgorithm.PooledTopNParams.class); ResourceHolder<ByteBuffer> resourceHolder = EasyMock.createMock(ResourceHolder.class); EasyMock.expect(params.getResultsBufHolder()).andReturn(resourceHolder).times(1); EasyMock.expect(resourceHolder.get()).andReturn(ByteBuffer.allocate(1)).times(1); resourceHolder.close(); EasyMock.expectLastCall().once(); EasyMock.replay(params); EasyMock.replay(resourceHolder); pooledTopNAlgorithm.cleanup(params); EasyMock.verify(params); EasyMock.verify(resourceHolder); } }
apache-2.0
McLeodMoores/starling
projects/bloomberg/src/test/java/com/opengamma/bbg/BloombergHistoricalTimeSeriesSourceTest.java
8555
/** * Copyright (C) 2009 - present by OpenGamma Inc. and the OpenGamma group of companies * * Please see distribution for license. */ package com.opengamma.bbg; import static com.opengamma.bbg.BloombergConstants.BLOOMBERG_DATA_SOURCE_NAME; import static com.opengamma.bbg.BloombergConstants.DATA_PROVIDER_UNKNOWN; import static org.testng.AssertJUnit.assertEquals; import static org.testng.AssertJUnit.assertFalse; import static org.testng.AssertJUnit.assertNotNull; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.Map; import java.util.concurrent.Callable; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.Future; import org.testng.annotations.AfterMethod; import org.testng.annotations.BeforeMethod; import org.testng.annotations.Test; import org.threeten.bp.LocalDate; import com.opengamma.bbg.historicaltimeseries.BloombergHistoricalTimeSeriesProvider; import com.opengamma.bbg.test.BloombergTestUtils; import com.opengamma.core.historicaltimeseries.HistoricalTimeSeries; import com.opengamma.core.historicaltimeseries.HistoricalTimeSeriesSource; import com.opengamma.core.id.ExternalSchemes; import com.opengamma.id.ExternalId; import com.opengamma.id.ExternalIdBundle; import com.opengamma.timeseries.date.localdate.LocalDateDoubleTimeSeries; import com.opengamma.util.test.TestGroup; /** * Test. */ @Test(groups = TestGroup.INTEGRATION) public class BloombergHistoricalTimeSeriesSourceTest { private BloombergHistoricalTimeSeriesProvider _provider; private HistoricalTimeSeriesSource _source; private final ExternalIdBundle _secDes = ExternalIdBundle.of(ExternalSchemes.bloombergTickerSecurityId("IBM US Equity")); private static final String DEFAULT_DATA_PROVIDER = DATA_PROVIDER_UNKNOWN; private static final String DEFAULT_DATA_SOURCE = BLOOMBERG_DATA_SOURCE_NAME; private static final String PX_LAST = "PX_LAST"; @BeforeMethod public void setUp() throws Exception { final BloombergConnector connector = BloombergTestUtils.getBloombergConnector(); _provider = new BloombergHistoricalTimeSeriesProvider(connector); _source = new BloombergHistoricalTimeSeriesSource(_provider); _provider.start(); } @AfterMethod public void tearDown() throws Exception { if (_provider != null) { _provider.stop(); } _source = null; _provider = null; } //------------------------------------------------------------------------- @Test(expectedExceptions = IllegalArgumentException.class) public void getHistoricalWithInvalidDates() throws Exception { //endDate before startDate final LocalDate startDate = LocalDate.of(2009, 11, 04); final LocalDate endDate = LocalDate.of(2009, 10, 29); _source.getHistoricalTimeSeries(_secDes, DEFAULT_DATA_SOURCE, DEFAULT_DATA_PROVIDER, PX_LAST, startDate, true, endDate, true); } @Test public void getHistoricalWithSameDate() throws Exception { final LocalDate startDate = LocalDate.of(2009, 11, 04); final LocalDate endDate = LocalDate.of(2009, 11, 04); final HistoricalTimeSeries hts = _source.getHistoricalTimeSeries(_secDes, DEFAULT_DATA_SOURCE, DEFAULT_DATA_PROVIDER, PX_LAST, startDate, true, endDate, true); assertNotNull(hts); assertNotNull(hts.getTimeSeries()); assertEquals(1, hts.getTimeSeries().size()); } @Test public void getSeriesMap() throws Exception { final LocalDate startDate = LocalDate.of(2009, 10, 04); final LocalDate endDate = LocalDate.of(2009, 11, 29); final Map<ExternalIdBundle, HistoricalTimeSeries> result = _source.getHistoricalTimeSeries(Collections.singleton(getTestBundle()), "BLOOMBERG", "CMPL", "PX_LAST", startDate, true, endDate, true); assertNotNull(result); final HistoricalTimeSeries hts = result.get(getTestBundle()); assertNotNull(hts); assertFalse(hts.getTimeSeries().isEmpty()); } private ExternalIdBundle getTestBundle() { return ExternalIdBundle.of( ExternalId.of("BLOOMBERG_BUID", "EQ0010121400001000"), ExternalId.of("BLOOMBERG_TICKER", "C US Equity"), ExternalId.of("CUSIP", "172967101"), ExternalId.of("ISIN", "US1729671016"), ExternalId.of("SEDOL1", "2297907")); } @Test public void getHistoricalTimeSeriesWithMaxPoints() throws Exception { final LocalDate endDate = LocalDate.of(2012, 03, 07); final LocalDate startDate = endDate.minusMonths(1); final HistoricalTimeSeries reference = _source.getHistoricalTimeSeries(_secDes, DEFAULT_DATA_SOURCE, DEFAULT_DATA_PROVIDER, PX_LAST, startDate, true, endDate, true); for (final int maxPoints : new int[] {-4, -1}) { final HistoricalTimeSeries hts = _source.getHistoricalTimeSeries(_secDes, DEFAULT_DATA_SOURCE, DEFAULT_DATA_PROVIDER, PX_LAST, startDate, true, endDate, true, maxPoints); // do we have a time-series? assertNotNull(hts.getTimeSeries()); // is it the right size? assertEquals(Math.min(Math.abs(maxPoints), reference.getTimeSeries().size()), hts.getTimeSeries().size()); // does it contain the expected data points? assertEquals( Math.abs(maxPoints) > reference.getTimeSeries().size() ? reference.getTimeSeries() : maxPoints >= 0 ? reference.getTimeSeries().head(maxPoints) : reference.getTimeSeries().tail(-maxPoints), hts.getTimeSeries()); } } @Test public void getHistoricalTimeSeriesWithZeroMaxPoints() throws Exception { final LocalDate endDate = LocalDate.of(2012, 03, 07); final LocalDate startDate = endDate.minusMonths(1); final HistoricalTimeSeries reference = _source.getHistoricalTimeSeries(_secDes, DEFAULT_DATA_SOURCE, DEFAULT_DATA_PROVIDER, PX_LAST, startDate, true, endDate, true); final HistoricalTimeSeries hts = _source.getHistoricalTimeSeries(_secDes, DEFAULT_DATA_SOURCE, DEFAULT_DATA_PROVIDER, PX_LAST, startDate, true, endDate, true, 0); // do we have a time-series? assertNotNull(hts.getTimeSeries()); // is it the right size? assertEquals(reference.getTimeSeries().size(), hts.getTimeSeries().size()); // does it contain the expected data points? assertEquals(reference.getTimeSeries(), hts.getTimeSeries()); } @Test public void getHistoricalTimeSeriesWithDates() throws Exception { final LocalDate startDate = LocalDate.of(2009, 10, 29); final LocalDate endDate = LocalDate.of(2009, 11, 04); final HistoricalTimeSeries hts = _source.getHistoricalTimeSeries(_secDes, DEFAULT_DATA_SOURCE, DEFAULT_DATA_PROVIDER, PX_LAST, startDate, true, endDate, true); assertNotNull(hts); final LocalDateDoubleTimeSeries timeSeriesExpected = hts.getTimeSeries(); assertNotNull(timeSeriesExpected); final ExecutorService threadPool = Executors.newFixedThreadPool(4); final List<Future<LocalDateDoubleTimeSeries>> results = new ArrayList<>(); for (int i = 0; i < 20; i++) { results.add( threadPool.submit(new BHDPgetHistoricalTimeSeriesWithDates(_secDes, DEFAULT_DATA_SOURCE, DEFAULT_DATA_PROVIDER, PX_LAST, startDate, endDate))); } for (final Future<LocalDateDoubleTimeSeries> future : results) { final LocalDateDoubleTimeSeries timeSeriesActual = future.get(); assertNotNull(timeSeriesActual); assertEquals(timeSeriesExpected, timeSeriesActual); } } //------------------------------------------------------------------------- private class BHDPgetHistoricalTimeSeriesWithDates implements Callable<LocalDateDoubleTimeSeries> { private final ExternalIdBundle _secDes; private final String _dataSource; private final String _provider; private final String _field; private final LocalDate _startDate; private final LocalDate _endDate; public BHDPgetHistoricalTimeSeriesWithDates(final ExternalIdBundle secDes, final String dataSource, final String dataProvider, final String field, final LocalDate startDate, final LocalDate endDate) { assertNotNull(secDes); assertNotNull(startDate); assertNotNull(endDate); _secDes = secDes; _dataSource = dataSource; _provider = dataProvider; _field = field; _startDate = startDate; _endDate = endDate; } @Override public LocalDateDoubleTimeSeries call() throws Exception { final HistoricalTimeSeries hts = _source.getHistoricalTimeSeries(_secDes, _dataSource, _provider, _field, _startDate, true, _endDate, true); return hts.getTimeSeries(); } } }
apache-2.0
VicoWu/hadoop-2.7.3
hadoop-hdfs-project/hadoop-hdfs/src/main/java/org/apache/hadoop/hdfs/qjournal/server/JournalNodeRpcServer.java
8701
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.hadoop.hdfs.qjournal.server; import java.io.IOException; import java.net.InetSocketAddress; import java.net.URL; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.fs.CommonConfigurationKeys; import org.apache.hadoop.fs.CommonConfigurationKeysPublic; import org.apache.hadoop.hdfs.DFSConfigKeys; import org.apache.hadoop.hdfs.HDFSPolicyProvider; import org.apache.hadoop.hdfs.protocolPB.PBHelper; import org.apache.hadoop.hdfs.qjournal.protocol.QJournalProtocol; import org.apache.hadoop.hdfs.qjournal.protocol.QJournalProtocolProtos.GetEditLogManifestResponseProto; import org.apache.hadoop.hdfs.qjournal.protocol.QJournalProtocolProtos.GetJournalStateResponseProto; import org.apache.hadoop.hdfs.qjournal.protocol.QJournalProtocolProtos.NewEpochResponseProto; import org.apache.hadoop.hdfs.qjournal.protocol.QJournalProtocolProtos.PrepareRecoveryResponseProto; import org.apache.hadoop.hdfs.qjournal.protocol.QJournalProtocolProtos.QJournalProtocolService; import org.apache.hadoop.hdfs.qjournal.protocol.QJournalProtocolProtos.SegmentStateProto; import org.apache.hadoop.hdfs.qjournal.protocol.RequestInfo; import org.apache.hadoop.hdfs.qjournal.protocolPB.QJournalProtocolPB; import org.apache.hadoop.hdfs.qjournal.protocolPB.QJournalProtocolServerSideTranslatorPB; import org.apache.hadoop.hdfs.server.common.StorageInfo; import org.apache.hadoop.hdfs.server.protocol.NamespaceInfo; import org.apache.hadoop.hdfs.server.protocol.RemoteEditLogManifest; import org.apache.hadoop.ipc.ProtobufRpcEngine; import org.apache.hadoop.ipc.RPC; import org.apache.hadoop.ipc.RPC.Server; import org.apache.hadoop.net.NetUtils; import com.google.protobuf.BlockingService; class JournalNodeRpcServer implements QJournalProtocol { private static final int HANDLER_COUNT = 5; private final JournalNode jn; private Server server; //在JournalNode.start()方法中被构造 JournalNodeRpcServer(Configuration conf, JournalNode jn) throws IOException { this.jn = jn; Configuration confCopy = new Configuration(conf); // Ensure that nagling doesn't kick in, which could cause latency issues. confCopy.setBoolean( CommonConfigurationKeysPublic.IPC_SERVER_TCPNODELAY_KEY, true); InetSocketAddress addr = getAddress(confCopy); RPC.setProtocolEngine(confCopy, QJournalProtocolPB.class, ProtobufRpcEngine.class); QJournalProtocolServerSideTranslatorPB translator = new QJournalProtocolServerSideTranslatorPB(this); BlockingService service = QJournalProtocolService .newReflectiveBlockingService(translator); this.server = new RPC.Builder(confCopy) .setProtocol(QJournalProtocolPB.class) .setInstance(service) .setBindAddress(addr.getHostName()) .setPort(addr.getPort()) .setNumHandlers(HANDLER_COUNT) .setVerbose(false) .build(); // set service-level authorization security policy if (confCopy.getBoolean( CommonConfigurationKeys.HADOOP_SECURITY_AUTHORIZATION, false)) { server.refreshServiceAcl(confCopy, new HDFSPolicyProvider()); } } void start() { this.server.start(); } public InetSocketAddress getAddress() { return server.getListenerAddress(); } void join() throws InterruptedException { this.server.join(); } void stop() { this.server.stop(); } static InetSocketAddress getAddress(Configuration conf) { String addr = conf.get( DFSConfigKeys.DFS_JOURNALNODE_RPC_ADDRESS_KEY, DFSConfigKeys.DFS_JOURNALNODE_RPC_ADDRESS_DEFAULT); return NetUtils.createSocketAddr(addr, 0, DFSConfigKeys.DFS_JOURNALNODE_RPC_ADDRESS_KEY); } @Override public boolean isFormatted(String journalId) throws IOException { return jn.getOrCreateJournal(journalId).isFormatted(); } @SuppressWarnings("deprecation") @Override public GetJournalStateResponseProto getJournalState(String journalId) throws IOException { long epoch = jn.getOrCreateJournal(journalId).getLastPromisedEpoch(); return GetJournalStateResponseProto.newBuilder() .setLastPromisedEpoch(epoch) .setHttpPort(jn.getBoundHttpAddress().getPort()) .setFromURL(jn.getHttpServerURI()) .build(); } @Override public NewEpochResponseProto newEpoch(String journalId, NamespaceInfo nsInfo, long epoch) throws IOException { return jn.getOrCreateJournal(journalId).newEpoch(nsInfo, epoch); } @Override public void format(String journalId, NamespaceInfo nsInfo) throws IOException { jn.getOrCreateJournal(journalId).format(nsInfo); } /** * active namenode通过调用这个接口向QjournalProtocol写入EditLog数据 */ @Override public void journal(RequestInfo reqInfo, long segmentTxId, long firstTxnId, int numTxns, byte[] records) throws IOException { jn.getOrCreateJournal(reqInfo.getJournalId()) .journal(reqInfo, segmentTxId, firstTxnId, numTxns, records); } @Override public void heartbeat(RequestInfo reqInfo) throws IOException { jn.getOrCreateJournal(reqInfo.getJournalId()) .heartbeat(reqInfo); } @Override public void startLogSegment(RequestInfo reqInfo, long txid, int layoutVersion) throws IOException { jn.getOrCreateJournal(reqInfo.getJournalId()) .startLogSegment(reqInfo, txid, layoutVersion); } @Override public void finalizeLogSegment(RequestInfo reqInfo, long startTxId, long endTxId) throws IOException { jn.getOrCreateJournal(reqInfo.getJournalId()) .finalizeLogSegment(reqInfo, startTxId, endTxId); } @Override public void purgeLogsOlderThan(RequestInfo reqInfo, long minTxIdToKeep) throws IOException { jn.getOrCreateJournal(reqInfo.getJournalId()) .purgeLogsOlderThan(reqInfo, minTxIdToKeep); } @SuppressWarnings("deprecation") @Override public GetEditLogManifestResponseProto getEditLogManifest(String jid, long sinceTxId, boolean inProgressOk) throws IOException { // RemoteEditLogManifest manifest = jn.getOrCreateJournal(jid) .getEditLogManifest(sinceTxId, inProgressOk); return GetEditLogManifestResponseProto.newBuilder() .setManifest(PBHelper.convert(manifest)) .setHttpPort(jn.getBoundHttpAddress().getPort()) .setFromURL(jn.getHttpServerURI()) .build(); } @Override public PrepareRecoveryResponseProto prepareRecovery(RequestInfo reqInfo, long segmentTxId) throws IOException { return jn.getOrCreateJournal(reqInfo.getJournalId()) .prepareRecovery(reqInfo, segmentTxId); } @Override public void acceptRecovery(RequestInfo reqInfo, SegmentStateProto log, URL fromUrl) throws IOException { jn.getOrCreateJournal(reqInfo.getJournalId()) .acceptRecovery(reqInfo, log, fromUrl); } @Override public void doPreUpgrade(String journalId) throws IOException { jn.doPreUpgrade(journalId); } @Override public void doUpgrade(String journalId, StorageInfo sInfo) throws IOException { jn.doUpgrade(journalId, sInfo); } @Override public void doFinalize(String journalId) throws IOException { jn.doFinalize(journalId); } @Override public Boolean canRollBack(String journalId, StorageInfo storage, StorageInfo prevStorage, int targetLayoutVersion) throws IOException { return jn.canRollBack(journalId, storage, prevStorage, targetLayoutVersion); } @Override public void doRollback(String journalId) throws IOException { jn.doRollback(journalId); } @Override public Long getJournalCTime(String journalId) throws IOException { return jn.getJournalCTime(journalId); } @Override public void discardSegments(String journalId, long startTxId) throws IOException { jn.discardSegments(journalId, startTxId); } }
apache-2.0
nms-htc/cmts-mo-portlet
docroot/WEB-INF/src/com/cmcti/cmts/portlet/bean/CableModemHistoryBean.java
5884
package com.cmcti.cmts.portlet.bean; import java.io.Serializable; import java.util.List; import javax.annotation.PostConstruct; import javax.faces.bean.ManagedBean; import javax.faces.bean.ManagedProperty; import javax.faces.bean.ViewScoped; import org.primefaces.model.LazyDataModel; import com.cmcti.cmts.domain.model.CableModemHistory; import com.cmcti.cmts.domain.model.CustomerMacMapping; import com.cmcti.cmts.domain.service.CableModemHistoryLocalServiceUtil; import com.cmcti.cmts.domain.service.CableModemLocalServiceUtil; import com.cmcti.cmts.domain.service.CustomerMacMappingLocalServiceUtil; import com.cmcti.cmts.domain.service.persistence.CableModemHistoryUtil; import com.cmcti.cmts.portlet.pf.AbstractLazyDataModel; import com.cmcti.cmts.portlet.search.Searcher; import com.cmcti.cmts.portlet.util.CableModemConstants; import com.cmcti.cmts.portlet.util.JsfUtil; import com.liferay.faces.util.logging.Logger; import com.liferay.faces.util.logging.LoggerFactory; import com.liferay.portal.kernel.dao.orm.DynamicQuery; import com.liferay.portal.kernel.dao.orm.OrderFactoryUtil; import com.liferay.portal.kernel.dao.orm.RestrictionsFactoryUtil; import com.liferay.portal.kernel.exception.PortalException; import com.liferay.portal.kernel.exception.SystemException; @ManagedBean @ViewScoped public class CableModemHistoryBean extends AbstractCRUDBean<CableModemHistory> implements Serializable { private static final long serialVersionUID = 8722946106153176757L; private static final Logger logger = LoggerFactory.getLogger(CableModemHistoryBean.class); private static final String PARAM_MAC_ADDRESS = "macAddress"; private String macAddress; @ManagedProperty("#{cableModemHistorySearcher}") private Searcher searcher; @PostConstruct public void init() { macAddress = JsfUtil.getRequestParameter(PARAM_MAC_ADDRESS); } protected DynamicQuery updateQuery(DynamicQuery query) { if (this.macAddress != null && !this.macAddress.trim().isEmpty()) { if (query == null) query = CableModemLocalServiceUtil.dynamicQuery(); // filter by macAddress query.add(RestrictionsFactoryUtil.eq("macAddress", macAddress)); // order by create date query.addOrder(OrderFactoryUtil.desc("createDate")); } return query; } @Override protected CableModemHistory initEntity() { return CableModemHistoryUtil.create(0); } @Override protected LazyDataModel<CableModemHistory> initDataModel() { AbstractLazyDataModel<CableModemHistory> model = new AbstractLazyDataModel<CableModemHistory>() { private static final long serialVersionUID = -7865865696816533980L; @Override protected Class<CableModemHistory> getModelClass() { return CableModemHistory.class; } @Override protected DynamicQuery getDynamicQuery() { return CableModemHistoryLocalServiceUtil.dynamicQuery(); } @SuppressWarnings("unchecked") @Override protected List<CableModemHistory> query(DynamicQuery query, int start, int end) throws SystemException, PortalException { if (start >= 0 && end >= start) { return CableModemHistoryLocalServiceUtil.dynamicQuery(query, start, end); } else { return CableModemHistoryLocalServiceUtil.dynamicQuery(query); } } @Override protected int count(DynamicQuery query) throws SystemException, PortalException { return Long.valueOf(CableModemHistoryLocalServiceUtil.dynamicQueryCount(query)).intValue(); } @Override protected CableModemHistory findById(long id) throws SystemException, PortalException { return CableModemHistoryLocalServiceUtil.getCableModemHistory(id); } }; model.setSearcher(searcher); return model; } @Override protected CableModemHistory addEntity(CableModemHistory entity) throws PortalException, SystemException { // TODO Auto-generated method stub return null; } @Override protected CableModemHistory updateEntity(CableModemHistory entity) throws PortalException, SystemException { // TODO Auto-generated method stub return null; } @Override protected void removeEntity(CableModemHistory entity) throws PortalException, SystemException { // TODO Auto-generated method stub } /** * Use to show Subscriber Address on CableModel datatable. * * @param macAddress * @return */ public String getCustomerTitle(String macAddress) { CustomerMacMapping mapping = null; try { mapping = CustomerMacMappingLocalServiceUtil.getByMacAddress(macAddress); } catch (Exception e) { logger.info("Customer mapping not found for mac {0}", macAddress); } return mapping == null ? null : mapping.getTitle(); } /** * Convert cable modem status to String (resource bundle key) * @param status * @return */ public String getCableStatus(int status) { String statusStr = null; switch (status) { case CableModemConstants.STATUS_ACCESS_DENIED: statusStr = "access-denied"; break; case CableModemConstants.STATUS_IP_COMPLETE: statusStr = "ip-complete"; break; case CableModemConstants.STATUS_OTHER: statusStr = "other"; break; case CableModemConstants.STATUS_RANGING: statusStr = "ranging"; break; case CableModemConstants.STATUS_RANGING_ABORTED: statusStr = "ranging-aborted"; break; case CableModemConstants.STATUS_RANGING_COMPLETE: statusStr = "ranging-complete"; break; case CableModemConstants.STATUS_REGISTRATION_COMPLETE: statusStr = "registration-complete"; break; } return statusStr; } /* Getters and Setters */ public String getMacAddress() { return macAddress; } public void setMacAddress(String macAddress) { this.macAddress = macAddress; } /** * @return the searcher */ public Searcher getSearcher() { return searcher; } /** * @param searcher the searcher to set */ public void setSearcher(Searcher searcher) { this.searcher = searcher; } }
apache-2.0
method76/android-MarvelApp
volley/src/test/java/com/android/volley/toolbox/ImageRequestTest.java
7411
/* * Copyright (C) 2011 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.android.volley.toolbox; import android.graphics.Bitmap; import android.graphics.Bitmap.Config; import android.widget.ImageView; import android.widget.ImageView.ScaleType; import com.android.volley.NetworkResponse; import com.android.volley.Response; import org.junit.Test; import org.junit.runner.RunWith; import org.robolectric.RobolectricTestRunner; import org.robolectric.shadows.ShadowBitmapFactory; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; import static org.junit.Assert.*; @RunWith(RobolectricTestRunner.class) public class ImageRequestTest { @Test public void parseNetworkResponse_resizing() throws Exception { // This is a horrible hack but Robolectric doesn't have a way to provide // width and height hints for decodeByteArray. It works because the byte array // "file:fake" is ASCII encodable and thus the name in Robolectric's fake // bitmap creator survives as-is, and provideWidthAndHeightHints puts // "file:" + name in its lookaside map. I write all this because it will // probably break mysteriously at some point and I feel terrible about your // having to debug it. byte[] jpegBytes = "file:fake".getBytes(); ShadowBitmapFactory.provideWidthAndHeightHints("fake", 1024, 500); NetworkResponse jpeg = new NetworkResponse(jpegBytes); // Scale the image uniformly (maintain the image's aspect ratio) so that // both dimensions (width and height) of the image will be equal to or // less than the corresponding dimension of the view. ScaleType scalteType = ScaleType.CENTER_INSIDE; // Exact sizes verifyResize(jpeg, 512, 250, scalteType, 512, 250); // exactly half verifyResize(jpeg, 511, 249, scalteType, 509, 249); // just under half verifyResize(jpeg, 1080, 500, scalteType, 1024, 500); // larger verifyResize(jpeg, 500, 500, scalteType, 500, 244); // keep same ratio // Specify only width, preserve aspect ratio verifyResize(jpeg, 512, 0, scalteType, 512, 250); verifyResize(jpeg, 800, 0, scalteType, 800, 390); verifyResize(jpeg, 1024, 0, scalteType, 1024, 500); // Specify only height, preserve aspect ratio verifyResize(jpeg, 0, 250, scalteType, 512, 250); verifyResize(jpeg, 0, 391, scalteType, 800, 391); verifyResize(jpeg, 0, 500, scalteType, 1024, 500); // No resize verifyResize(jpeg, 0, 0, scalteType, 1024, 500); // Scale the image uniformly (maintain the image's aspect ratio) so that // both dimensions (width and height) of the image will be equal to or // larger than the corresponding dimension of the view. scalteType = ScaleType.CENTER_CROP; // Exact sizes verifyResize(jpeg, 512, 250, scalteType, 512, 250); verifyResize(jpeg, 511, 249, scalteType, 511, 249); verifyResize(jpeg, 1080, 500, scalteType, 1024, 500); verifyResize(jpeg, 500, 500, scalteType, 1024, 500); // Specify only width verifyResize(jpeg, 512, 0, scalteType, 512, 250); verifyResize(jpeg, 800, 0, scalteType, 800, 390); verifyResize(jpeg, 1024, 0, scalteType, 1024, 500); // Specify only height verifyResize(jpeg, 0, 250, scalteType, 512, 250); verifyResize(jpeg, 0, 391, scalteType, 800, 391); verifyResize(jpeg, 0, 500, scalteType, 1024, 500); // No resize verifyResize(jpeg, 0, 0, scalteType, 1024, 500); // Scale in X and Y independently, so that src matches dst exactly. This // may change the aspect ratio of the src. scalteType = ScaleType.FIT_XY; // Exact sizes verifyResize(jpeg, 512, 250, scalteType, 512, 250); verifyResize(jpeg, 511, 249, scalteType, 511, 249); verifyResize(jpeg, 1080, 500, scalteType, 1024, 500); verifyResize(jpeg, 500, 500, scalteType, 500, 500); // Specify only width verifyResize(jpeg, 512, 0, scalteType, 512, 500); verifyResize(jpeg, 800, 0, scalteType, 800, 500); verifyResize(jpeg, 1024, 0, scalteType, 1024, 500); // Specify only height verifyResize(jpeg, 0, 250, scalteType, 1024, 250); verifyResize(jpeg, 0, 391, scalteType, 1024, 391); verifyResize(jpeg, 0, 500, scalteType, 1024, 500); // No resize verifyResize(jpeg, 0, 0, scalteType, 1024, 500); } private void verifyResize(NetworkResponse networkResponse, int maxWidth, int maxHeight, ScaleType scaleType, int expectedWidth, int expectedHeight) { ImageRequest request = new ImageRequest("", null, maxWidth, maxHeight, scaleType, Config.RGB_565, null); Response<Bitmap> response = request.parseNetworkResponse(networkResponse); assertNotNull(response); assertTrue(response.isSuccess()); Bitmap bitmap = response.result; assertNotNull(bitmap); assertEquals(expectedWidth, bitmap.getWidth()); assertEquals(expectedHeight, bitmap.getHeight()); } @Test public void findBestSampleSize() { // desired == actual == 1 assertEquals(1, ImageRequest.findBestSampleSize(100, 150, 100, 150)); // exactly half == 2 assertEquals(2, ImageRequest.findBestSampleSize(280, 160, 140, 80)); // just over half == 1 assertEquals(1, ImageRequest.findBestSampleSize(1000, 800, 501, 401)); // just under 1/4 == 4 assertEquals(4, ImageRequest.findBestSampleSize(100, 200, 24, 50)); } private static byte[] readInputStream(InputStream in) throws IOException { ByteArrayOutputStream bytes = new ByteArrayOutputStream(); byte[] buffer = new byte[1024]; int count; while ((count = in.read(buffer)) != -1) { bytes.write(buffer, 0, count); } in.close(); return bytes.toByteArray(); } @Test public void publicMethods() throws Exception { // Catch-all test to find API-breaking changes. assertNotNull(ImageRequest.class.getConstructor(String.class, Response.Listener.class, int.class, int.class, Bitmap.Config.class, Response.ErrorListener.class)); assertNotNull(ImageRequest.class.getConstructor(String.class, Response.Listener.class, int.class, int.class, ImageView.ScaleType.class, Bitmap.Config.class, Response.ErrorListener.class)); assertEquals(ImageRequest.DEFAULT_IMAGE_TIMEOUT_MS, 1000); assertEquals(ImageRequest.DEFAULT_IMAGE_MAX_RETRIES, 2); assertEquals(ImageRequest.DEFAULT_IMAGE_BACKOFF_MULT, 2f); } }
apache-2.0
shot/hadoop-source-reading
src/hdfs/org/apache/hadoop/hdfs/protocol/AlreadyBeingCreatedException.java
1138
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.hadoop.hdfs.protocol; import java.io.IOException; /** * The exception that happens when you ask to create a file that already is * being created, but is not closed yet. */ public class AlreadyBeingCreatedException extends IOException { public AlreadyBeingCreatedException(String msg) { super(msg); } }
apache-2.0
osiefart/wicket-christmas
src/main/java/com/senacor/wicket/async/christmas/core/counter/PageRequestCounter.java
1139
package com.senacor.wicket.async.christmas.core.counter; import java.util.concurrent.atomic.AtomicInteger; import org.apache.wicket.ajax.AjaxRequestTarget; import org.apache.wicket.event.IEvent; import org.apache.wicket.markup.html.basic.Label; import org.apache.wicket.model.AbstractReadOnlyModel; /** * Render the page counter from the page on every Request * * @author Olaf Siefart, Senacor Technologies AG */ public class PageRequestCounter extends Label { public PageRequestCounter(String id) { super(id); setOutputMarkupId(true); setDefaultModel(new CountingModel()); } @Override public void onEvent(IEvent<?> event) { if (event.getPayload() instanceof AjaxRequestTarget) { ((AjaxRequestTarget) event.getPayload()).add(this); } } /** * Counts how often getObject was called * * @author Olaf Siefart, Senacor Technologies AG */ private static class CountingModel extends AbstractReadOnlyModel<Integer> { private final AtomicInteger counter = new AtomicInteger(0); @Override public Integer getObject() { return counter.incrementAndGet(); } } }
apache-2.0
Jack2code/vegeta
src/main/java/com/vegeta/rct/RCTApplication.java
731
package com.vegeta.rct; import java.util.Arrays; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.context.ApplicationContext; @SpringBootApplication public class RCTApplication { public static void main(String[] args) { // SpringApplication.run(RCTApplication.class, args); ApplicationContext ctx = SpringApplication.run(RCTApplication.class, args); System.out.println("Let's inspect the beans provided by Spring Boot:"); String[] beanNames = ctx.getBeanDefinitionNames(); Arrays.sort(beanNames); for (String beanName : beanNames) { System.out.println(beanName); } } }
apache-2.0
greenbird/mule-configuration
src/test/java/com/greenbird/configuration/context/TestBean.java
72
package com.greenbird.configuration.context; public class TestBean { }
apache-2.0
shioyang/PolyhedralTodoList
app/src/main/java/jp/gr/java_conf/shioyang/polyhedraltodolist/polyimpl/PolyTodoItemImpl.java
3724
package jp.gr.java_conf.shioyang.polyhedraltodolist.polyimpl; import android.util.Log; import com.google.api.services.tasks.model.Task; import java.util.regex.Matcher; import java.util.regex.Pattern; import jp.gr.java_conf.shioyang.polyhedraltodolist.PolyTodoItem; public class PolyTodoItemImpl implements PolyTodoItem { static String regex = "^poly:global(\\d+):local(\\d+):(.*)"; static Pattern pattern; static { pattern = Pattern.compile(regex); } /* String id String title String parent String position String status */ Task task; String listId; int color; int globalPosition = -1; int localPosition = -1; String justTitle = null; boolean isSaveNeeded = false; public PolyTodoItemImpl(Task task, String listId, int color) { this.task = task; this.listId = listId; this.color = color; parseTitle(); } @Override public boolean isPolyTodoItem() { return globalPosition >= 0; } private Matcher matchTaskTitle() { return pattern.matcher(task.getTitle()); } private boolean parseTitle() { Matcher matcher = matchTaskTitle(); if(matcher.find() && matcher.groupCount() == 3) { globalPosition = Integer.parseInt(matcher.group(1)); localPosition = Integer.parseInt(matcher.group(2)); justTitle = matcher.group(3); return true; } return false; } @Override public String makeTaskTitle() { return PolyUtil.formatTaskTitle(globalPosition, localPosition, justTitle); } @Override public int getColor() { return color; } @Override public void setColor(int color) { this.color = color; } @Override public Task getTask() { return this.task; } @Override public int getGlobalPosition() { return globalPosition; } @Override public void setGlobalPosition(int globalPosition) { this.globalPosition = globalPosition; String newTitle = makeTaskTitle(); task.setTitle(newTitle); Log.d("PolyTodoItemImpl", "setGlobalPosition| New title: " + newTitle); this.isSaveNeeded = true; } @Override public int getLocalPosition() { return localPosition; } @Override public void setLocalPosition(int localPosition) { this.localPosition = localPosition; String newTitle = makeTaskTitle(); task.setTitle(newTitle); Log.d("PolyTodoItemImpl", "setLocalPosition| New title: " + newTitle); this.isSaveNeeded = true; } @Override public String getJustTitle() { return justTitle; } @Override public void setJustTitle(String justTitle) { this.justTitle = justTitle; String newTitle = makeTaskTitle(); task.setTitle(newTitle); Log.d("PolyTodoItemImpl", "setJustTitle| New title: " + newTitle); this.isSaveNeeded = true; } @Override public String getListId() { return listId; } @Override public String getId() { return task.getId(); } @Override public String getTitle() { return task.getTitle(); } @Override public String getParent() { return task.getParent(); } @Override public String getPosition() { return task.getPosition(); } @Override public String getStatus() { return task.getStatus(); } @Override public boolean isSaveNeeded() { return this.isSaveNeeded; } @Override public void saveCompleted() { this.isSaveNeeded = false; } }
apache-2.0
SessionFactory/tinyshop8
src/main/qin/tinyshop8_page/controller/TinyShop8Controller.java
9569
package qin.tinyshop8_page.controller; import org.springframework.web.servlet.ModelAndView; import qin.tinyshop8.domain8.jpa.User8JPA; import qin.tinyshop8.utils.MainViewSupport; import qin.tinyshop8.utils.ShopBaseSupport; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.Serializable; import java.util.ArrayList; import java.util.List; /** * Created by Administrator on 2017/8/5 0005-5.<br/> * tinyshop8控制层抽象接口 * * @author qinzhengying * @since 1.8 2017/8/5 */ @SuppressWarnings("all") public interface TinyShop8Controller extends ShopBaseSupport, MainViewSupport { //region 定义基本变量 //region 页面访问基本路径 /** * 页面访问基本路径 */ String basePath = "/tinyshop8"; //endregion //region 返回主页 /** * 返回主页 */ String indexPage = basePath + "/doMainView"; //endregion //endregion //region 返回tinyshop8的首页 /** * 返回tinyshop8的首页 * * @return 将页面返回 */ @Override ModelAndView doMainView(); //endregion //region 一期显示功能 2017-8-5 //region 显示所有商品信息 /** * 显示所有商品信息 * * @param response */ @Deprecated void showAllGoods(HttpServletResponse response); //endregion //region 显示所有商品类型信息 /** * 显示所有商品类型信息 * * @param response */ void showAllGoodsType(HttpServletResponse response); //endregion //region 显示所有商品品牌信息 /** * 显示所有商品品牌信息 * * @param response */ void showAllGoodsBrand(HttpServletResponse response); //endregion //endregion //region 一期功能改进 //region 根据登录的用户查找商品信息 /** * 根据登录的用户查找商品信息<br> * 每个用户对应多个商品, 并不需要将所有的商品信息都显示出来, * 根据登录的用户去查找对应的商品然后将它的商品信息打印出来即可 * * @param user 登录的用户信息 * @param response 回复 * @param request 请求 */ void showAllGoods(User8JPA user, HttpServletResponse response, HttpServletRequest request); //endregion //endregion //region 二期(一期改进 2017-8-11) //region 新增商品信息 /** * 新增商品信息 * * @param goods 将页面接收的变量值用一个内部类封装 * @param response 回复 * @author qinzhengying * @since 1.8 2017/8/12 */ void addGoods(InnerGoods goods, HttpServletResponse response); //endregion //region 显示商品类型(2017/8/11) /** * 显示商品类型<br> * * @return 将商品类型字符串返回 * @author qinzhengying * @since 1.8 2017/8/11 */ String showGoodsTypeCombobox(); //endregion //endregion //region 定义一个内部类(接收商品信息) /** * 商品信息内部类(用于接收界面数据) * * @author qinzhengying * @since 1.8 2017/8/12 */ class InnerGoods implements Serializable { private static final long serialVersionUID = 7962962092767599477L; //region 名称 /** * 名称 */ private String goodsName; public String getGoodsName() { return goodsName; } public void setGoodsName(String goodsName) { this.goodsName = goodsName; } //endregion //region 新增日期 /** * 新增日期 */ private String goodsAddDate; public String getGoodsAddDate() { return goodsAddDate; } public void setGoodsAddDate(String goodsAddDate) { this.goodsAddDate = goodsAddDate; } //endregion //region 成本价 /** * 成本价 */ private String goodsCostPrice; public String getGoodsCostPrice() { return goodsCostPrice; } public void setGoodsCostPrice(String goodsCostPrice) { this.goodsCostPrice = goodsCostPrice; } //endregion //region 市场价 /** * 市场价 */ private String goodsMarketPrice; public String getGoodsMarketPrice() { return goodsMarketPrice; } public void setGoodsMarketPrice(String goodsMarketPrice) { this.goodsMarketPrice = goodsMarketPrice; } //endregion //region 货号 /** * 货号 */ private String goodsProNo; public String getGoodsProNo() { return goodsProNo; } public void setGoodsProNo(String goodsProNo) { this.goodsProNo = goodsProNo; } //endregion //region 销售价 /** * 销售价 */ private String goodsSellPrice; public String getGoodsSellPrice() { return goodsSellPrice; } public void setGoodsSellPrice(String goodsSellPrice) { this.goodsSellPrice = goodsSellPrice; } //endregion //region 销售数量 /** * 销售数量 */ private String goodsStoreNums; public String getGoodsStoreNums() { return goodsStoreNums; } public void setGoodsStoreNums(String goodsStoreNums) { this.goodsStoreNums = goodsStoreNums; } //endregion //region 编号 /** * 编号 */ private String goodsNo; public String getGoodsNo() { return goodsNo; } public void setGoodsNo(String goodsNo) { this.goodsNo = goodsNo; } //endregion //region 重量 /** * 重量 */ private String goodsWeight; public String getGoodsWeight() { return goodsWeight; } public void setGoodsWeight(String goodsWeight) { this.goodsWeight = goodsWeight; } //endregion //region 副标题 /** * 副标题 */ private String goodsSubTitle; public String getGoodsSubTitle() { return goodsSubTitle; } public void setGoodsSubTitle(String goodsSubTitle) { this.goodsSubTitle = goodsSubTitle; } //endregion //region 类型 /** * 类型 */ private String goodsType; public String getGoodsType() { return goodsType; } public void setGoodsType(String goodsType) { this.goodsType = goodsType; } //endregion //region 图片 /** * 图片 */ private String goodsImages; public String getGoodsImages() { return goodsImages; } public void setGoodsImages(String goodsImages) { this.goodsImages = goodsImages; } //endregion //region 关键词 /** * 关键词 */ private String goodsKeyWords; public String getGoodsKeyWords() { return goodsKeyWords; } public void setGoodsKeyWords(String goodsKeyWords) { this.goodsKeyWords = goodsKeyWords; } //endregion //region 用户名 private String username; public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } //endregion //region 二期新特性 /** * 图片集合 * * @author qinzhengying * @since 1.8 2017/8/13 */ private List<String> imagesList = new ArrayList<>(); public List<String> getImagesList() { return imagesList; } public void setImagesList(List<String> imagesList) { this.imagesList = imagesList; } //endregion } //endregion //region 定义一个内部枚举 /** * tinyshop的操作 新增或更新 * * @author qinzhengying * @since 1.8 2017/8/12 */ enum TinyOperator { /** * 新增 */ ADD, /** * 更新 */ UPDATE } //endregion //region 三期 /** * 检查所有tinyshop里的价格(后期会重写此方法) * 根据字符串中截取, 判断是否都是数字, 接收的价格必须是数字<br> * (<br> * &nbsp;&nbsp;1.不能是负数<br> * &nbsp;&nbsp;2.必须大于0<br> * &nbsp;&nbsp;3.必须是11.11格式数字<br> * &nbsp;&nbsp;4.小数点 不能再末尾<br> * ) * * @param price 需要检查的价格 * @throws Exception 如果检查失败就直接抛出异常 */ default void checkTinyShopPrice(String price) throws Exception { } //endregion }
apache-2.0
mtaal/olingo-odata4-jpa
fit/src/test/java/org/apache/olingo/fit/proxy/v4/staticservice/microsoft/test/odata/services/odatawcfservice/types/SubscriptionCollection.java
1992
/* * 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.olingo.fit.proxy.v4.staticservice.microsoft.test.odata.services.odatawcfservice.types; // CHECKSTYLE:OFF (Maven checkstyle) import java.util.Collection; // CHECKSTYLE:ON (Maven checkstyle) import org.apache.olingo.ext.proxy.api.AbstractTerm; public interface SubscriptionCollection extends org.apache.olingo.ext.proxy.api.StructuredCollectionQuery<org.apache.olingo.fit.proxy.v4.staticservice.microsoft.test.odata.services.odatawcfservice.types.SubscriptionCollection>, org.apache.olingo.ext.proxy.api.EntityCollection<org.apache.olingo.fit.proxy.v4.staticservice.microsoft.test.odata.services.odatawcfservice.types.Subscription, org.apache.olingo.fit.proxy.v4.staticservice.microsoft.test.odata.services.odatawcfservice.types.SubscriptionCollection, org.apache.olingo.fit.proxy.v4.staticservice.microsoft.test.odata.services.odatawcfservice.types.SubscriptionCollection> { Operations operations(); interface Operations extends org.apache.olingo.ext.proxy.api.Operations { // No additional methods needed for now. } Object getAnnotation(Class<? extends AbstractTerm> term); Collection<Class<? extends AbstractTerm>> getAnnotationTerms(); }
apache-2.0
unreach/israel
transport/src/main/java/io/unreach/israel/transport/Channel.java
787
package io.unreach.israel.transport; import io.unreach.israel.ServiceProvider; /** * israle://groupName/serviceName/methodName/version * * @author joe */ public class Channel { public ChannelStatus status; public ServiceProvider provider; public ChannelHandler handler; public ChannelStatus getStatus() { return status; } public void setStatus(ChannelStatus status) { this.status = status; } public ServiceProvider getProvider() { return provider; } public void setProvider(ServiceProvider provider) { this.provider = provider; } public ChannelHandler getHandler() { return handler; } public void setHandler(ChannelHandler handler) { this.handler = handler; } }
apache-2.0
tetrapods/core
Protocol-Tetrapod/src/io/tetrapod/protocol/core/SubscribeOwnershipRequest.java
3289
package io.tetrapod.protocol.core; // This is a code generated file. All edits will be lost the next time code gen is run. import io.*; import io.tetrapod.core.rpc.*; import io.tetrapod.protocol.core.Admin; import io.tetrapod.core.serialize.*; import io.tetrapod.protocol.core.TypeDescriptor; import io.tetrapod.protocol.core.StructDescription; import java.io.IOException; import java.util.*; import java.util.concurrent.*; @SuppressWarnings("all") public class SubscribeOwnershipRequest extends Request { public static final int STRUCT_ID = 15739199; public static final int CONTRACT_ID = TetrapodContract.CONTRACT_ID; public static final int SUB_CONTRACT_ID = TetrapodContract.SUB_CONTRACT_ID; public SubscribeOwnershipRequest() { defaults(); } public SubscribeOwnershipRequest(String prefix) { this.prefix = prefix; } /** * subscribes to keys starting with this prefix */ public String prefix; public final Structure.Security getSecurity() { return Security.INTERNAL; } public final void defaults() { prefix = null; } @Override public final void write(DataSource data) throws IOException { data.write(1, this.prefix); data.writeEndTag(); } @Override public final void read(DataSource data) throws IOException { defaults(); while (true) { int tag = data.readTag(); switch (tag) { case 1: this.prefix = data.read_string(tag); break; case Codec.END_TAG: return; default: data.skip(tag); break; } } } public final int getContractId() { return SubscribeOwnershipRequest.CONTRACT_ID; } public final int getSubContractId() { return SubscribeOwnershipRequest.SUB_CONTRACT_ID; } public final int getStructId() { return SubscribeOwnershipRequest.STRUCT_ID; } @Override public final Response dispatch(ServiceAPI is, RequestContext ctx) { if (is instanceof Handler) return ((Handler)is).requestSubscribeOwnership(this, ctx); return is.genericRequest(this, ctx); } public static interface Handler extends ServiceAPI { Response requestSubscribeOwnership(SubscribeOwnershipRequest r, RequestContext ctx); } public final String[] tagWebNames() { // Note do not use this tags in long term serializations (to disk or databases) as // implementors are free to rename them however they wish. A null means the field // is not to participate in web serialization (remaining at default) String[] result = new String[1+1]; result[1] = "prefix"; return result; } public final Structure make() { return new SubscribeOwnershipRequest(); } public final StructDescription makeDescription() { StructDescription desc = new StructDescription(); desc.name = "SubscribeOwnershipRequest"; desc.tagWebNames = tagWebNames(); desc.types = new TypeDescriptor[desc.tagWebNames.length]; desc.types[0] = new TypeDescriptor(TypeDescriptor.T_STRUCT, getContractId(), getStructId()); desc.types[1] = new TypeDescriptor(TypeDescriptor.T_STRING, 0, 0); return desc; } }
apache-2.0
prestona/qpid-proton
proton-j/src/main/java/org/apache/qpid/proton/engine/impl/TransportSession.java
15611
/* * * 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.qpid.proton.engine.impl; import java.util.HashMap; import java.util.Map; import org.apache.qpid.proton.amqp.Binary; import org.apache.qpid.proton.amqp.UnsignedInteger; import org.apache.qpid.proton.amqp.transport.Disposition; import org.apache.qpid.proton.amqp.transport.Flow; import org.apache.qpid.proton.amqp.transport.Role; import org.apache.qpid.proton.amqp.transport.Transfer; import org.apache.qpid.proton.engine.Event; class TransportSession { private static final int HANDLE_MAX = 65535; private final TransportImpl _transport; private final SessionImpl _session; private int _localChannel = -1; private int _remoteChannel = -1; private boolean _openSent; private final UnsignedInteger _handleMax = UnsignedInteger.valueOf(HANDLE_MAX); //TODO: should this be configurable? // This is used for the delivery-id actually stamped in each transfer frame of a given message delivery. private UnsignedInteger _outgoingDeliveryId = UnsignedInteger.ZERO; // These are used for the session windows communicated via Begin/Flow frames // and the conceptual transfer-id relating to updating them. private UnsignedInteger _incomingWindowSize = UnsignedInteger.ZERO; private UnsignedInteger _outgoingWindowSize = UnsignedInteger.ZERO; private UnsignedInteger _nextOutgoingId = UnsignedInteger.ONE; private UnsignedInteger _nextIncomingId = null; private final Map<UnsignedInteger, TransportLink<?>> _remoteHandlesMap = new HashMap<UnsignedInteger, TransportLink<?>>(); private final Map<UnsignedInteger, TransportLink<?>> _localHandlesMap = new HashMap<UnsignedInteger, TransportLink<?>>(); private final Map<String, TransportLink> _halfOpenLinks = new HashMap<String, TransportLink>(); private UnsignedInteger _incomingDeliveryId = null; private UnsignedInteger _remoteIncomingWindow; private UnsignedInteger _remoteOutgoingWindow; private UnsignedInteger _remoteNextIncomingId = _nextOutgoingId; private UnsignedInteger _remoteNextOutgoingId; private final Map<UnsignedInteger, DeliveryImpl> _unsettledIncomingDeliveriesById = new HashMap<UnsignedInteger, DeliveryImpl>(); private final Map<UnsignedInteger, DeliveryImpl> _unsettledOutgoingDeliveriesById = new HashMap<UnsignedInteger, DeliveryImpl>(); private int _unsettledIncomingSize; private boolean _endReceived; private boolean _beginSent; TransportSession(TransportImpl transport, SessionImpl session) { _transport = transport; _session = session; _outgoingWindowSize = UnsignedInteger.valueOf(session.getOutgoingWindow()); } void unbind() { unsetLocalChannel(); unsetRemoteChannel(); } public SessionImpl getSession() { return _session; } public int getLocalChannel() { return _localChannel; } public void setLocalChannel(int localChannel) { if (!isLocalChannelSet()) { _session.incref(); } _localChannel = localChannel; } public int getRemoteChannel() { return _remoteChannel; } public void setRemoteChannel(int remoteChannel) { if (!isRemoteChannelSet()) { _session.incref(); } _remoteChannel = remoteChannel; } public boolean isOpenSent() { return _openSent; } public void setOpenSent(boolean openSent) { _openSent = openSent; } public boolean isRemoteChannelSet() { return _remoteChannel != -1; } public boolean isLocalChannelSet() { return _localChannel != -1; } public void unsetLocalChannel() { if (isLocalChannelSet()) { unsetLocalHandles(); _session.decref(); } _localChannel = -1; } private void unsetLocalHandles() { for (TransportLink<?> tl : _localHandlesMap.values()) { tl.clearLocalHandle(); } _localHandlesMap.clear(); } public void unsetRemoteChannel() { if (isRemoteChannelSet()) { unsetRemoteHandles(); _session.decref(); } _remoteChannel = -1; } private void unsetRemoteHandles() { for (TransportLink<?> tl : _remoteHandlesMap.values()) { tl.clearRemoteHandle(); } _remoteHandlesMap.clear(); } public UnsignedInteger getHandleMax() { return _handleMax; } public UnsignedInteger getIncomingWindowSize() { return _incomingWindowSize; } void updateIncomingWindow() { int size = _transport.getMaxFrameSize(); if (size <= 0) { _incomingWindowSize = UnsignedInteger.valueOf(2147483647); // biggest legal value } else { _incomingWindowSize = UnsignedInteger.valueOf((_session.getIncomingCapacity() - _session.getIncomingBytes())/size); } } public UnsignedInteger getOutgoingDeliveryId() { return _outgoingDeliveryId; } void incrementOutgoingDeliveryId() { _outgoingDeliveryId = _outgoingDeliveryId.add(UnsignedInteger.ONE); } public UnsignedInteger getOutgoingWindowSize() { return _outgoingWindowSize; } public UnsignedInteger getNextOutgoingId() { return _nextOutgoingId; } public TransportLink getLinkFromRemoteHandle(UnsignedInteger handle) { return _remoteHandlesMap.get(handle); } public UnsignedInteger allocateLocalHandle(TransportLink transportLink) { for(int i = 0; i <= HANDLE_MAX; i++) { UnsignedInteger handle = UnsignedInteger.valueOf(i); if(!_localHandlesMap.containsKey(handle)) { _localHandlesMap.put(handle, transportLink); transportLink.setLocalHandle(handle); return handle; } } throw new IllegalStateException("no local handle available for allocation"); } public void addLinkRemoteHandle(TransportLink link, UnsignedInteger remoteHandle) { _remoteHandlesMap.put(remoteHandle, link); } public void addLinkLocalHandle(TransportLink link, UnsignedInteger localhandle) { _localHandlesMap.put(localhandle, link); } public void freeLocalHandle(UnsignedInteger handle) { _localHandlesMap.remove(handle); } public void freeRemoteHandle(UnsignedInteger handle) { _remoteHandlesMap.remove(handle); } public TransportLink resolveHalfOpenLink(String name) { return _halfOpenLinks.remove(name); } public void addHalfOpenLink(TransportLink link) { _halfOpenLinks.put(link.getName(), link); } public void handleTransfer(Transfer transfer, Binary payload) { DeliveryImpl delivery; incrementNextIncomingId(); if(transfer.getDeliveryId() == null || transfer.getDeliveryId().equals(_incomingDeliveryId)) { TransportReceiver transportReceiver = (TransportReceiver) getLinkFromRemoteHandle(transfer.getHandle()); ReceiverImpl receiver = transportReceiver.getReceiver(); Binary deliveryTag = transfer.getDeliveryTag(); delivery = _unsettledIncomingDeliveriesById.get(_incomingDeliveryId); delivery.getTransportDelivery().incrementSessionSize(); } else { // TODO - check deliveryId has been incremented by one _incomingDeliveryId = transfer.getDeliveryId(); // TODO - check link handle valid and a receiver TransportReceiver transportReceiver = (TransportReceiver) getLinkFromRemoteHandle(transfer.getHandle()); ReceiverImpl receiver = transportReceiver.getReceiver(); Binary deliveryTag = transfer.getDeliveryTag(); delivery = receiver.delivery(deliveryTag.getArray(), deliveryTag.getArrayOffset(), deliveryTag.getLength()); UnsignedInteger messageFormat = transfer.getMessageFormat(); if(messageFormat != null) { delivery.setMessageFormat(messageFormat.intValue()); } TransportDelivery transportDelivery = new TransportDelivery(_incomingDeliveryId, delivery, transportReceiver); delivery.setTransportDelivery(transportDelivery); _unsettledIncomingDeliveriesById.put(_incomingDeliveryId, delivery); getSession().incrementIncomingDeliveries(1); } if( transfer.getState()!=null ) { delivery.setRemoteDeliveryState(transfer.getState()); } _unsettledIncomingSize++; // TODO - should this be a copy? if(payload != null) { if(delivery.getDataLength() == 0) { delivery.setData(payload.getArray()); delivery.setDataLength(payload.getLength()); delivery.setDataOffset(payload.getArrayOffset()); } else { byte[] data = new byte[delivery.getDataLength() + payload.getLength()]; System.arraycopy(delivery.getData(), delivery.getDataOffset(), data, 0, delivery.getDataLength()); System.arraycopy(payload.getArray(), payload.getArrayOffset(), data, delivery.getDataLength(), payload.getLength()); delivery.setData(data); delivery.setDataOffset(0); delivery.setDataLength(data.length); } getSession().incrementIncomingBytes(payload.getLength()); } delivery.updateWork(); if(!(transfer.getMore() || transfer.getAborted())) { delivery.setComplete(); delivery.getLink().getTransportLink().decrementLinkCredit(); delivery.getLink().getTransportLink().incrementDeliveryCount(); } if(Boolean.TRUE.equals(transfer.getSettled())) { delivery.setRemoteSettled(true); } _incomingWindowSize = _incomingWindowSize.subtract(UnsignedInteger.ONE); // this will cause a flow to happen if (_incomingWindowSize.equals(UnsignedInteger.ZERO)) { delivery.getLink().modified(false); } getSession().getConnection().put(Event.Type.DELIVERY, delivery); } public void freeLocalChannel() { unsetLocalChannel(); } public void freeRemoteChannel() { unsetRemoteChannel(); } private void setRemoteIncomingWindow(UnsignedInteger incomingWindow) { _remoteIncomingWindow = incomingWindow; } void decrementRemoteIncomingWindow() { _remoteIncomingWindow = _remoteIncomingWindow.subtract(UnsignedInteger.ONE); } private void setRemoteOutgoingWindow(UnsignedInteger outgoingWindow) { _remoteOutgoingWindow = outgoingWindow; } void handleFlow(Flow flow) { UnsignedInteger inext = flow.getNextIncomingId(); UnsignedInteger iwin = flow.getIncomingWindow(); if(inext != null) { setRemoteNextIncomingId(inext); setRemoteIncomingWindow(inext.add(iwin).subtract(_nextOutgoingId)); } else { setRemoteIncomingWindow(iwin); } setRemoteNextOutgoingId(flow.getNextOutgoingId()); setRemoteOutgoingWindow(flow.getOutgoingWindow()); if(flow.getHandle() != null) { TransportLink transportLink = getLinkFromRemoteHandle(flow.getHandle()); transportLink.handleFlow(flow); } } private void setRemoteNextOutgoingId(UnsignedInteger nextOutgoingId) { _remoteNextOutgoingId = nextOutgoingId; } private void setRemoteNextIncomingId(UnsignedInteger remoteNextIncomingId) { _remoteNextIncomingId = remoteNextIncomingId; } void handleDisposition(Disposition disposition) { UnsignedInteger id = disposition.getFirst(); UnsignedInteger last = disposition.getLast() == null ? id : disposition.getLast(); final Map<UnsignedInteger, DeliveryImpl> unsettledDeliveries = disposition.getRole() == Role.RECEIVER ? _unsettledOutgoingDeliveriesById : _unsettledIncomingDeliveriesById; while(id.compareTo(last)<=0) { DeliveryImpl delivery = unsettledDeliveries.get(id); if(delivery != null) { if(disposition.getState() != null) { delivery.setRemoteDeliveryState(disposition.getState()); } if(Boolean.TRUE.equals(disposition.getSettled())) { delivery.setRemoteSettled(true); unsettledDeliveries.remove(id); } delivery.updateWork(); getSession().getConnection().put(Event.Type.DELIVERY, delivery); } id = id.add(UnsignedInteger.ONE); } //TODO - Implement. } void addUnsettledOutgoing(UnsignedInteger deliveryId, DeliveryImpl delivery) { _unsettledOutgoingDeliveriesById.put(deliveryId, delivery); } public boolean hasOutgoingCredit() { return _remoteIncomingWindow == null ? false : _remoteIncomingWindow.compareTo(UnsignedInteger.ZERO)>0; } void incrementOutgoingId() { _nextOutgoingId = _nextOutgoingId.add(UnsignedInteger.ONE); } public void settled(TransportDelivery transportDelivery) { if(transportDelivery.getTransportLink().getLink() instanceof ReceiverImpl) { _unsettledIncomingDeliveriesById.remove(transportDelivery.getDeliveryId()); getSession().modified(false); } else { _unsettledOutgoingDeliveriesById.remove(transportDelivery.getDeliveryId()); getSession().modified(false); } } public UnsignedInteger getNextIncomingId() { return _nextIncomingId; } public void setNextIncomingId(UnsignedInteger nextIncomingId) { _nextIncomingId = nextIncomingId; } public void incrementNextIncomingId() { _nextIncomingId = _nextIncomingId.add(UnsignedInteger.ONE); } public boolean endReceived() { return _endReceived; } public void receivedEnd() { _endReceived = true; } public boolean beginSent() { return _beginSent; } public void sentBegin() { _beginSent = true; } }
apache-2.0
consulo/consulo-android
android/android/testSrc/org/jetbrains/android/intentions/AndroidIntentionsTest.java
2194
package org.jetbrains.android.intentions; import com.intellij.codeInsight.intention.IntentionAction; import com.intellij.codeInspection.LocalInspectionTool; import com.intellij.openapi.vfs.VirtualFile; import org.jetbrains.android.AndroidTestCase; import org.jetbrains.android.inspections.AndroidNonConstantResIdsInSwitchInspection; /** * @author Eugene.Kudelevsky */ public class AndroidIntentionsTest extends AndroidTestCase { private static final String BASE_PATH = "intentions/"; public void testSwitchOnResourceId() { myFacet.setLibraryProject(true); myFixture.copyFileToProject(BASE_PATH + "R.java", "src/p1/p2/R.java"); final AndroidNonConstantResIdsInSwitchInspection inspection = new AndroidNonConstantResIdsInSwitchInspection(); doTest(inspection, true, inspection.getQuickFixName()); } public void testSwitchOnResourceId1() { myFacet.setLibraryProject(false); myFixture.copyFileToProject(BASE_PATH + "R.java", "src/p1/p2/R.java"); final AndroidNonConstantResIdsInSwitchInspection inspection = new AndroidNonConstantResIdsInSwitchInspection(); doTest(inspection, false, inspection.getQuickFixName()); } public void testSwitchOnResourceId2() { myFacet.setLibraryProject(true); myFixture.copyFileToProject(BASE_PATH + "R.java", "src/p1/p2/R.java"); final AndroidNonConstantResIdsInSwitchInspection inspection = new AndroidNonConstantResIdsInSwitchInspection(); doTest(inspection, false, inspection.getQuickFixName()); } private void doTest(final LocalInspectionTool inspection, boolean available, String quickFixName) { myFixture.enableInspections(inspection); final VirtualFile file = myFixture.copyFileToProject(BASE_PATH + getTestName(false) + ".java", "src/p1/p2/Class.java"); myFixture.configureFromExistingVirtualFile(file); myFixture.checkHighlighting(true, false, false); final IntentionAction quickFix = myFixture.getAvailableIntention(quickFixName); if (available) { assertNotNull(quickFix); myFixture.launchAction(quickFix); myFixture.checkResultByFile(BASE_PATH + getTestName(false) + "_after.java"); } else { assertNull(quickFix); } } }
apache-2.0
googleads/googleads-java-lib
modules/adwords_appengine/src/main/java/com/google/api/ads/adwords/jaxws/v201809/cm/SharedBiddingStrategyBiddingStrategyStatus.java
1582
// Copyright 2018 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.adwords.jaxws.v201809.cm; import javax.xml.bind.annotation.XmlEnum; import javax.xml.bind.annotation.XmlType; /** * <p>Java class for SharedBiddingStrategy.BiddingStrategyStatus. * * <p>The following schema fragment specifies the expected content contained within this class. * <p> * <pre> * &lt;simpleType name="SharedBiddingStrategy.BiddingStrategyStatus"> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}string"> * &lt;enumeration value="ENABLED"/> * &lt;enumeration value="REMOVED"/> * &lt;enumeration value="UNKNOWN"/> * &lt;/restriction> * &lt;/simpleType> * </pre> * */ @XmlType(name = "SharedBiddingStrategy.BiddingStrategyStatus") @XmlEnum public enum SharedBiddingStrategyBiddingStrategyStatus { ENABLED, REMOVED, UNKNOWN; public String value() { return name(); } public static SharedBiddingStrategyBiddingStrategyStatus fromValue(String v) { return valueOf(v); } }
apache-2.0
jtwig/jtwig-json-extension
src/test/java/org/jtwig/json/provider/Jackson2JsonMapperProviderTest.java
1257
package org.jtwig.json.provider; import com.google.common.base.Function; import org.jtwig.util.ClasspathFinder; import org.junit.Test; import static org.hamcrest.core.Is.is; import static org.hamcrest.core.IsNull.notNullValue; import static org.junit.Assert.*; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; public class Jackson2JsonMapperProviderTest { private final ClasspathFinder classpathFinder = mock(ClasspathFinder.class); private Jackson2JsonMapperProvider underTest = new Jackson2JsonMapperProvider(classpathFinder); @Test public void createWhenExists() throws Exception { when(classpathFinder.exists(Jackson2JsonMapperProvider.CLASS_NAME)).thenReturn(true); boolean result = underTest.isFound(); assertThat(result, is(true)); } @Test public void createWhenNotExists() throws Exception { when(classpathFinder.exists(Jackson2JsonMapperProvider.CLASS_NAME)).thenReturn(false); boolean result = underTest.isFound(); assertThat(result, is(false)); } @Test public void instantiate() throws Exception { Function<Object, String> result = underTest.jsonMapper(); assertThat(result, notNullValue()); } }
apache-2.0
bjorndm/prebake
code/third_party/bdb/src/com/sleepycat/je/latch/LatchStatDefinition.java
1852
/*- * See the file LICENSE for redistribution information. * * Copyright (c) 2002-2010 Oracle. All rights reserved. * * $Id: LatchStatDefinition.java,v 1.6 2010/01/04 15:50:42 cwl Exp $ */ package com.sleepycat.je.latch; import com.sleepycat.je.utilint.StatDefinition; /** * Per-stat Metadata for JE latch statistics. */ public class LatchStatDefinition { public static final String GROUP_NAME = "Latch"; public static final String GROUP_DESC = "Latch characteristics"; public static final StatDefinition LATCH_NO_WAITERS = new StatDefinition("nLatchAcquiresNoWaiters", "Number of times the latch was acquired without " + "contention."); public static final StatDefinition LATCH_SELF_OWNED = new StatDefinition("nLatchAcquiresSelfOwned", "Number of times the latch was acquired it " + "was already owned by the caller."); public static final StatDefinition LATCH_CONTENTION = new StatDefinition("nLatchAcquiresWithContention", "Number of times the latch was acquired when it " + "was already owned by another thread."); public static final StatDefinition LATCH_NOWAIT_SUCCESS = new StatDefinition("nLatchAcquiresNoWaitSuccessful", "Number of times acquireNoWait() was called when " + "the latch was successfully acquired."); public static final StatDefinition LATCH_NOWAIT_UNSUCCESS = new StatDefinition("nLatchAcquireNoWaitUnsuccessful", "Number of unsuccessful acquireNoWait() calls."); public static final StatDefinition LATCH_RELEASES = new StatDefinition("nLatchReleases", "Number of latch releases."); }
apache-2.0
lessthanoptimal/BoofCV
main/boofcv-ip-multiview/src/test/java/boofcv/alg/disparity/TestBlockMatchBasic_NCC.java
2931
/* * Copyright (c) 2020, Peter Abeles. All Rights Reserved. * * This file is part of BoofCV (http://boofcv.org). * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package boofcv.alg.disparity; import boofcv.abst.disparity.StereoDisparity; import boofcv.alg.disparity.block.TestBlockRowScoreNcc; import boofcv.alg.misc.GImageMiscOps; import boofcv.factory.disparity.ConfigDisparityBM; import boofcv.factory.disparity.DisparityError; import boofcv.factory.disparity.FactoryStereoDisparity; import boofcv.struct.border.BorderType; import boofcv.struct.border.ImageBorder; import boofcv.struct.border.ImageBorder_F32; import boofcv.struct.image.GrayF32; import boofcv.struct.image.GrayU8; import boofcv.struct.image.ImageBase; import boofcv.struct.image.ImageType; import boofcv.testing.BoofStandardJUnit; import org.junit.jupiter.api.Nested; /** * Test the entire block matching pipeline against a naive implementation * * @author Peter Abeles */ @SuppressWarnings("InnerClassMayBeStatic") class TestBlockMatchBasic_NCC<T extends ImageBase<T>> extends BoofStandardJUnit { @Nested class F32 extends ChecksDisparityBlockMatchNaive<GrayF32> { float eps = 1e-4f; F32() { super(ImageType.single(GrayF32.class)); } @Override public BruteForceBlockMatch<GrayF32> createNaive( BorderType borderType, ImageType<GrayF32> imageType ) { BruteForceBlockMatch<GrayF32> naive = new BruteForceBlockMatch<GrayF32>(borderType, imageType) { @Override public double computeScore( ImageBorder<GrayF32> _left, ImageBorder<GrayF32> _right, int cx, int cy, int disparity ) { ImageBorder_F32 left = (ImageBorder_F32)_left; ImageBorder_F32 right = (ImageBorder_F32)_right; return TestBlockRowScoreNcc.ncc(left, right, cx, cy, disparity, radius, radius, eps); } }; naive.minimize = false; return naive; } @Override public StereoDisparity<GrayF32, GrayU8> createAlg( int blockRadius, int minDisparity, int maxDisparity ) { ConfigDisparityBM config = createConfigBasicBM(blockRadius, minDisparity, maxDisparity); config.border = BORDER_TYPE; config.errorType = DisparityError.NCC; config.configNCC.eps = eps; return FactoryStereoDisparity.blockMatch(config, GrayF32.class, GrayU8.class); } @Override protected void fillInStereoImages() { GImageMiscOps.fillUniform(left, rand, -1, 1); GImageMiscOps.fillUniform(right, rand, -1, 1); } } }
apache-2.0
GreatOrator/Draconem-Daemonion
src/main/java/com/greatorator/ddtc/mobs/EntityDonatello.java
1248
package com.greatorator.ddtc.mobs; import net.minecraft.entity.EntityAgeable; import net.minecraft.entity.SharedMonsterAttributes; import net.minecraft.entity.ai.*; import net.minecraft.entity.passive.EntityAnimal; import net.minecraft.init.Items; import net.minecraft.world.World; public class EntityDonatello extends EntityAnimal { public EntityDonatello(World par1World) { super(par1World); this.setSize(0.9F, 1.9F); this.tasks.addTask(0, new EntityAIWander(this, 0.3D)); this.tasks.addTask(1, new EntityAIPanic(this, 1.2D)); this.tasks.addTask(2, new EntityAILookIdle(this)); this.tasks.addTask(3, new EntityAISwimming(this)); this.tasks.addTask(4, new EntityAITempt(this, 0.4D, Items.book, false)); } public boolean isAIEnabled() { return true; } protected void applyEntityAttributes() { super.applyEntityAttributes(); this.getEntityAttribute(SharedMonsterAttributes.maxHealth).setBaseValue(16.0D); this.getEntityAttribute(SharedMonsterAttributes.movementSpeed).setBaseValue(0.3D); } @Override public EntityAgeable createChild(EntityAgeable var1) { return new EntityDonatello(worldObj); } }
apache-2.0
Gaia3D/simpleGISService
src/main/java/egovframework/com/cop/ems/service/impl/EgovSndngMailServiceImpl.java
4358
package egovframework.com.cop.ems.service.impl; import egovframework.com.cop.ems.service.EgovMultiPartEmail; import egovframework.com.cop.ems.service.EgovSndngMailService; import egovframework.com.cop.ems.service.SndngMailVO; import egovframework.rte.fdl.cmmn.EgovAbstractServiceImpl; import javax.annotation.Resource; import org.apache.commons.mail.EmailAttachment; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.mail.MailAuthenticationException; import org.springframework.mail.MailParseException; import org.springframework.mail.MailSendException; import org.springframework.stereotype.Service; /** * 메일 솔루션과 연동해서 이용해서 메일을 보내는 서비스 구현 클래스 * @since 2011.09.09 * @version 1.0 * @see * * <pre> * << 개정이력(Modification Information) >> * * 수정일 수정자 수정내용 * ------- -------- --------------------------- * 2011.09.09 서준식 최초 작성 * 2011.12.06 이기하 메일 첨부파일이 기능 추가 * 2013.05.23 이기하 메일 첨부파일이 없을 때 로직 추가 * * </pre> */ @Service("egovSndngMailService") public class EgovSndngMailServiceImpl extends EgovAbstractServiceImpl implements EgovSndngMailService { @Resource(name = "egovMultiPartEmail") private EgovMultiPartEmail egovMultiPartEmail; /** SndngMailRegistDAO */ @Resource(name = "sndngMailRegistDAO") private SndngMailRegistDAO sndngMailRegistDAO; private static final Logger LOGGER = LoggerFactory.getLogger(EgovSndngMailServiceImpl.class); /** * 메일을 발송한다 * @param vo SndngMailVO * @return boolean * @exception Exception */ @Override @SuppressWarnings("unused") public boolean sndngMail(SndngMailVO sndngMailVO) throws Exception { String recptnPerson = (sndngMailVO.getRecptnPerson() == null) ? "" : sndngMailVO.getRecptnPerson(); // 수신자 String subject = (sndngMailVO.getSj() == null) ? "" : sndngMailVO.getSj(); // 메일제목 String emailCn = (sndngMailVO.getEmailCn() == null) ? "" : sndngMailVO.getEmailCn(); // 메일내용 String atchmnFileNm = (sndngMailVO.getOrignlFileNm() == null) ? "" : sndngMailVO.getOrignlFileNm(); // 첨부파일이름 String atchmnFilePath = (sndngMailVO.getFileStreCours() == null) ? "" : sndngMailVO.getFileStreCours(); // 첨부파일경로 try { EmailAttachment attachment = new EmailAttachment(); // 첨부파일이 있을 때 if (atchmnFileNm != "" && atchmnFileNm != null && atchmnFilePath != "" && atchmnFilePath != null) { // 첨부할 attachment 정보를 생성합니다 attachment.setPath(atchmnFilePath); attachment.setDisposition(EmailAttachment.ATTACHMENT); attachment.setDescription("첨부파일입니다"); attachment.setName(atchmnFileNm); // 메일을 전송합니다 egovMultiPartEmail.send(recptnPerson, subject, emailCn, attachment); } // 메일을 전송합니다 egovMultiPartEmail.send(recptnPerson, subject, emailCn); Throwable t = new Throwable(); } catch (MailParseException ex) { sndngMailVO.setSndngResultCode("F"); // 발송결과 실패 sndngMailRegistDAO.updateSndngMail(sndngMailVO); // 발송상태를 DB에 업데이트 한다. LOGGER.error("Sending Mail Exception : {} [failure when parsing the message]", ex.getCause()); return false; } catch (MailAuthenticationException ex) { sndngMailVO.setSndngResultCode("F"); // 발송결과 실패 sndngMailRegistDAO.updateSndngMail(sndngMailVO); // 발송상태를 DB에 업데이트 한다. LOGGER.error("Sending Mail Exception : {} [authentication failure]", ex.getCause()); return false; } catch (MailSendException ex) { sndngMailVO.setSndngResultCode("F"); // 발송결과 실패 sndngMailRegistDAO.updateSndngMail(sndngMailVO); // 발송상태를 DB에 업데이트 한다. LOGGER.error("Sending Mail Exception : {} [failure when sending the message]", ex.getCause()); return false; } catch (Exception ex) { sndngMailVO.setSndngResultCode("F"); // 발송결과 실패 sndngMailRegistDAO.updateSndngMail(sndngMailVO); // 발송상태를 DB에 업데이트 한다. LOGGER.error("Sending Mail Exception : {} [unknown Exception]", ex.getCause()); LOGGER.debug(ex.getMessage()); return false; } return true; } }
apache-2.0
YifanLi/Effisto
src/fr/inria/oak/effisto/Query/Common/package-info.java
84
/** * */ /** * @author yifanli * */ package fr.inria.oak.effisto.Query.Common;
apache-2.0
googleads/google-ads-java
google-ads-stubs-v8/src/main/java/com/google/ads/googleads/v8/services/GetFeedRequestOrBuilder.java
984
// Generated by the protocol buffer compiler. DO NOT EDIT! // source: google/ads/googleads/v8/services/feed_service.proto package com.google.ads.googleads.v8.services; public interface GetFeedRequestOrBuilder extends // @@protoc_insertion_point(interface_extends:google.ads.googleads.v8.services.GetFeedRequest) com.google.protobuf.MessageOrBuilder { /** * <pre> * Required. The resource name of the feed to fetch. * </pre> * * <code>string resource_name = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... }</code> * @return The resourceName. */ java.lang.String getResourceName(); /** * <pre> * Required. The resource name of the feed to fetch. * </pre> * * <code>string resource_name = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... }</code> * @return The bytes for resourceName. */ com.google.protobuf.ByteString getResourceNameBytes(); }
apache-2.0
sergmor/plnr
Plnr/endpoint-libs/libstudygroupendpoint-v1/studygroupendpoint/studygroupendpoint-v1-generated-source/edu/columbia/cloud/plnr/entities/studygroupendpoint/model/Subject.java
2258
/* * 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. */ /* * This code was generated by https://code.google.com/p/google-apis-client-generator/ * (build: 2013-11-22 19:59:01 UTC) * on 2013-12-08 at 00:40:16 UTC * Modify at your own risk. */ package edu.columbia.cloud.plnr.entities.studygroupendpoint.model; /** * Model definition for Subject. * * <p> This is the Java data model class that specifies how to parse/serialize into the JSON that is * transmitted over HTTP when working with the studygroupendpoint. For a detailed explanation see: * <a href="http://code.google.com/p/google-http-java-client/wiki/JSON">http://code.google.com/p/google-http-java-client/wiki/JSON</a> * </p> * * @author Google, Inc. */ @SuppressWarnings("javadoc") public final class Subject extends com.google.api.client.json.GenericJson { /** * The value may be {@code null}. */ @com.google.api.client.util.Key private Key key; /** * The value may be {@code null}. */ @com.google.api.client.util.Key private java.lang.String name; /** * @return value or {@code null} for none */ public Key getKey() { return key; } /** * @param key key or {@code null} for none */ public Subject setKey(Key key) { this.key = key; return this; } /** * @return value or {@code null} for none */ public java.lang.String getName() { return name; } /** * @param name name or {@code null} for none */ public Subject setName(java.lang.String name) { this.name = name; return this; } @Override public Subject set(String fieldName, Object value) { return (Subject) super.set(fieldName, value); } @Override public Subject clone() { return (Subject) super.clone(); } }
apache-2.0
hahaking119/canal4mysql
parse/src/main/java/com/alibaba/otter/canal/parse/inbound/mysql/MysqlEventParser.java
32802
package com.alibaba.otter.canal.parse.inbound.mysql; import java.io.IOException; import java.net.SocketTimeoutException; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Timer; import java.util.TimerTask; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicLong; import org.apache.commons.lang.StringUtils; import org.apache.commons.lang.exception.ExceptionUtils; import org.springframework.util.CollectionUtils; import com.alibaba.otter.canal.parse.CanalEventParser; import com.alibaba.otter.canal.parse.CanalHASwitchable; import com.alibaba.otter.canal.parse.exception.CanalParseException; import com.alibaba.otter.canal.parse.inbound.ErosaConnection; import com.alibaba.otter.canal.parse.inbound.HeartBeatCallback; import com.alibaba.otter.canal.parse.inbound.SinkFunction; import com.alibaba.otter.canal.parse.inbound.mysql.dbsync.LogEventConvert; import com.alibaba.otter.canal.parse.inbound.mysql.dbsync.TableMetaCache; import com.alibaba.otter.canal.parse.inbound.mysql.networking.packets.server.FieldPacket; import com.alibaba.otter.canal.parse.inbound.mysql.networking.packets.server.ResultSetPacket; import com.alibaba.otter.canal.parse.support.AuthenticationInfo; import com.alibaba.otter.canal.protocol.CanalEntry; import com.alibaba.otter.canal.protocol.CanalEntry.Entry; import com.alibaba.otter.canal.protocol.position.EntryPosition; import com.alibaba.otter.canal.protocol.position.LogPosition; import com.taobao.tddl.dbsync.binlog.LogEvent; /** * 基于向mysql server复制binlog实现 * * <pre> * 1. 自身不控制mysql主备切换,由ha机制来控制. 比如接入tddl/cobar/自身心跳包成功率 * 2. 切换机制 * </pre> * * @author jianghang 2012-6-21 下午04:06:32 * @version 1.0.0 */ public class MysqlEventParser extends AbstractMysqlEventParser implements CanalEventParser, CanalHASwitchable { private HeartBeatCallback heartBeatCallback = null; private int defaultConnectionTimeoutInSeconds = 30; // sotimeout private int receiveBufferSize = 64 * 1024; private int sendBufferSize = 64 * 1024; // 数据库信息 private AuthenticationInfo masterInfo; // 主库 private AuthenticationInfo standbyInfo; // 备库 // binlog信息 private EntryPosition masterPosition; private EntryPosition standbyPosition; private long slaveId; // 链接到mysql的slave // 心跳检查信息 private volatile boolean detectingEnable = true; // 是否开启心跳检查 private String detectingSQL; // 心跳sql private Integer detectingIntervalInSeconds = 3; // 检测频率 private MysqlHeartBeatTimeTask mysqlHeartBeatTimeTask; private MysqlConnection metaConnection; // 查询meta信息的链接 private TableMetaCache tableMetaCache; // 对应meta cache private int fallbackIntervalInSeconds = 60; // 切换回退时间 // 心跳检查 private volatile Timer timer; protected ErosaConnection buildErosaConnection() { return buildMysqlConnection(this.runningInfo); } protected void preDump(ErosaConnection connection) { if (!(connection instanceof MysqlConnection)) { throw new CanalParseException("Unsupported connection type : " + connection.getClass().getSimpleName()); } if (binlogParser != null && binlogParser instanceof LogEventConvert) { metaConnection = (MysqlConnection) connection.fork(); try { metaConnection.connect(); } catch (IOException e) { throw new CanalParseException(e); } tableMetaCache = new TableMetaCache(metaConnection); ((LogEventConvert) binlogParser).setTableMetaCache(tableMetaCache); } // 开始启动心跳包 if (detectingEnable && StringUtils.isNotBlank(detectingSQL)) { logger.info("start heart beat.... "); startHeartbeat((MysqlConnection) connection.fork()); } } protected void afterDump(ErosaConnection connection) { super.afterDump(connection); if (!(connection instanceof MysqlConnection)) { throw new CanalParseException("Unsupported connection type : " + connection.getClass().getSimpleName()); } // 开始启动心跳包 if (detectingEnable && StringUtils.isNotBlank(detectingSQL)) { logger.info("stop heart beat.... "); stopHeartbeat(); } } public void start() throws CanalParseException { if (runningInfo == null) { // 第一次链接主库 runningInfo = masterInfo; } super.start(); } public void stop() throws CanalParseException { stopHeartbeat(); if (metaConnection != null) { try { metaConnection.disconnect(); } catch (IOException e) { logger.error("ERROR # disconnect for address:{}", metaConnection.getAddress(), e); } } if (tableMetaCache != null) { tableMetaCache.clearTableMeta(); } super.stop(); } private void startHeartbeat(MysqlConnection mysqlConnection) { if (timer == null) {// lazy初始化一下 synchronized (MysqlEventParser.class) { if (timer == null) { timer = new Timer("MysqlHeartBeatTimeTask", true); } } } mysqlHeartBeatTimeTask = new MysqlHeartBeatTimeTask(mysqlConnection); Integer interval = detectingIntervalInSeconds; timer.schedule(mysqlHeartBeatTimeTask, interval * 1000L, interval * 1000L); } private void stopHeartbeat() { if (timer != null) { timer.cancel(); timer = null; } if (mysqlHeartBeatTimeTask != null) { MysqlConnection mysqlConnection = mysqlHeartBeatTimeTask.getMysqlConnection(); try { mysqlConnection.disconnect(); } catch (IOException e) { logger.error("ERROR # disconnect for address:{}", mysqlConnection.getAddress(), e); } mysqlHeartBeatTimeTask = null; } } /** * 心跳信息 * * @author jianghang 2012-7-6 下午02:50:15 * @version 1.0.0 */ class MysqlHeartBeatTimeTask extends TimerTask { private boolean reconnect = false; private MysqlConnection mysqlConnection; public MysqlHeartBeatTimeTask(MysqlConnection mysqlConnection){ this.mysqlConnection = mysqlConnection; } public void run() { try { if (reconnect) { reconnect = false; mysqlConnection.reconnect(); } else if (!mysqlConnection.getConnected().get()) { mysqlConnection.connect(); } try { Long startTime = System.currentTimeMillis(); mysqlConnection.update(detectingSQL); Long costTime = System.currentTimeMillis() - startTime; if (heartBeatCallback != null) { heartBeatCallback.onSuccess(costTime); } } catch (SocketTimeoutException e) { if (heartBeatCallback != null) { heartBeatCallback.onFailed(e); } reconnect = true; } catch (IOException e) { if (heartBeatCallback != null) { heartBeatCallback.onFailed(e); } reconnect = true; } } catch (IOException e) { logger.warn("connect failed by " + ExceptionUtils.getStackTrace(e)); } } public MysqlConnection getMysqlConnection() { return mysqlConnection; } } // 处理主备切换的逻辑 public void doSwitch() { AuthenticationInfo newRunningInfo = (runningInfo.equals(masterInfo) ? standbyInfo : masterInfo); this.doSwitch(newRunningInfo); } public void doSwitch(AuthenticationInfo newRunningInfo) { // 1. 需要停止当前正在复制的过程 // 2. 找到新的position点 // 3. 重新建立链接,开始复制数据 // 切换ip String alarmMessage = null; if (this.runningInfo.equals(newRunningInfo)) { alarmMessage = "same runingInfo switch again : " + runningInfo.getAddress().toString(); logger.warn(alarmMessage); return; } if (newRunningInfo == null) { alarmMessage = "no standby config, just do nothing, will continue try:" + runningInfo.getAddress().toString(); logger.warn(alarmMessage); sendAlarm(destination, alarmMessage); return; } else { stop(); alarmMessage = "try to ha switch, old:" + runningInfo.getAddress().toString() + ", new:" + newRunningInfo.getAddress().toString(); logger.warn(alarmMessage); sendAlarm(destination, alarmMessage); runningInfo = newRunningInfo; start(); } } // =================== helper method ================= private MysqlConnection buildMysqlConnection(AuthenticationInfo runningInfo) { MysqlConnection connection = new MysqlConnection(this.slaveId); connection.setAddress(runningInfo.getAddress()); connection.setUsername(runningInfo.getUsername()); connection.setPassword(runningInfo.getPassword()); connection.setDefaultSchema(runningInfo.getDefaultDatabaseName()); connection.setCharset(connectionCharset); connection.setCharsetNumber(connectionCharsetNumber); connection.setReceiveBufferSize(receiveBufferSize); connection.setSendBufferSize(sendBufferSize); connection.setSoTimeout(defaultConnectionTimeoutInSeconds * 1000); return connection; } protected EntryPosition findStartPosition(ErosaConnection connection) throws IOException { EntryPosition startPosition = findStartPositionInternal(connection); if (needTransactionPosition.get()) { logger.info("prepare to find last position : {}", startPosition.toString()); Long preTransactionStartPosition = findTransactionBeginPosition(connection, startPosition); if (!preTransactionStartPosition.equals(startPosition.getPosition())) { logger.info("find new start Transaction Position , old : {} , new : {}", startPosition.getPosition(), preTransactionStartPosition); startPosition.setPosition(preTransactionStartPosition); } needTransactionPosition.compareAndSet(true, false); } return startPosition; } protected EntryPosition findStartPositionInternal(ErosaConnection connection) { MysqlConnection mysqlConnection = (MysqlConnection) connection; LogPosition logPosition = logPositionManager.getLatestIndexBy(destination); if (logPosition == null) {// 找不到历史成功记录 EntryPosition entryPosition = null; if (masterInfo != null && mysqlConnection.getAddress().equals(masterInfo.getAddress())) { entryPosition = masterPosition; } else if (standbyInfo != null && mysqlConnection.getAddress().equals(standbyInfo.getAddress())) { entryPosition = standbyPosition; } if (entryPosition == null) { entryPosition = findEndPosition(mysqlConnection); // 默认从当前最后一个位置进行消费 } // 判断一下是否需要按时间订阅 if (StringUtils.isEmpty(entryPosition.getJournalName())) { // 如果没有指定binlogName,尝试按照timestamp进行查找 if (entryPosition.getTimestamp() != null && entryPosition.getTimestamp() > 0L) { return findByStartTimeStamp(mysqlConnection, entryPosition.getTimestamp()); } else { return findEndPosition(mysqlConnection); // 默认从当前最后一个位置进行消费 } } else { if (entryPosition.getPosition() != null && entryPosition.getPosition() > 0L) { // 如果指定binlogName + offest,直接返回 return entryPosition; } else { EntryPosition specificLogFilePosition = null; if (entryPosition.getTimestamp() != null && entryPosition.getTimestamp() > 0L) { // 如果指定binlogName + timestamp,但没有指定对应的offest,尝试根据时间找一下offest EntryPosition endPosition = findEndPosition(mysqlConnection); if (endPosition != null) { specificLogFilePosition = findAsPerTimestampInSpecificLogFile( mysqlConnection, entryPosition.getTimestamp(), endPosition, entryPosition.getJournalName()); } } if (specificLogFilePosition == null) { // position不存在,从文件头开始 entryPosition.setPosition(BINLOG_START_OFFEST); return entryPosition; } else { return specificLogFilePosition; } } } } else { if (logPosition.getIdentity().getSourceAddress().equals(mysqlConnection.getAddress())) { return logPosition.getPostion(); } else { // 针对切换的情况,考虑回退时间 long newStartTimestamp = logPosition.getPostion().getTimestamp() - fallbackIntervalInSeconds * 1000; return findByStartTimeStamp(mysqlConnection, newStartTimestamp); } } } // 根据想要的position,可能这个position对应的记录为rowdata,需要找到事务头,避免丢数据 // 主要考虑一个事务执行时间可能会几秒种,如果仅仅按照timestamp相同,则可能会丢失事务的前半部分数据 private Long findTransactionBeginPosition(ErosaConnection mysqlConnection, final EntryPosition entryPosition) throws IOException { // 尝试找到一个合适的位置 final AtomicBoolean reDump = new AtomicBoolean(false); mysqlConnection.reconnect(); mysqlConnection.seek(entryPosition.getJournalName(), entryPosition.getPosition(), new SinkFunction<LogEvent>() { private LogPosition lastPosition; public boolean sink(LogEvent event) { try { CanalEntry.Entry entry = parseAndProfilingIfNecessary(event); if (entry == null) { return true; } // 直接查询第一条业务数据,确认是否为事务Begin/End if (CanalEntry.EntryType.TRANSACTIONBEGIN == entry.getEntryType() || CanalEntry.EntryType.TRANSACTIONEND == entry.getEntryType()) { lastPosition = buildLastPosition(entry); return false; } else { reDump.set(true); lastPosition = buildLastPosition(entry); return false; } } catch (Exception e) { // 上一次记录的poistion可能为一条update/insert/delete变更事件,直接进行dump的话,会缺少tableMap事件,导致tableId未进行解析 processError(e, lastPosition, entryPosition.getJournalName(), entryPosition.getPosition()); reDump.set(true); return false; } } }); // 针对开始的第一条为非Begin记录,需要从该binlog扫描 if (reDump.get()) { final AtomicLong preTransactionStartPosition = new AtomicLong(0L); mysqlConnection.reconnect(); mysqlConnection.seek(entryPosition.getJournalName(), 4L, new SinkFunction<LogEvent>() { private LogPosition lastPosition; public boolean sink(LogEvent event) { try { CanalEntry.Entry entry = parseAndProfilingIfNecessary(event); if (entry == null) { return true; } // 直接查询第一条业务数据,确认是否为事务Begin // 记录一下transaction begin position if (entry.getEntryType() == CanalEntry.EntryType.TRANSACTIONBEGIN && entry.getHeader().getLogfileOffset() < entryPosition.getPosition()) { preTransactionStartPosition.set(entry.getHeader().getLogfileOffset()); } if (entry.getHeader().getLogfileOffset() >= entryPosition.getPosition()) { return false;// 退出 } lastPosition = buildLastPosition(entry); } catch (Exception e) { processError(e, lastPosition, entryPosition.getJournalName(), entryPosition.getPosition()); return false; } return running; } }); // 判断一下找到的最接近position的事务头的位置 if (preTransactionStartPosition.get() > entryPosition.getPosition()) { logger.error("preTransactionEndPosition greater than startPosition from zk or localconf, maybe lost data"); throw new CanalParseException( "preTransactionStartPosition greater than startPosition from zk or localconf, maybe lost data"); } return preTransactionStartPosition.get(); } else { return entryPosition.getPosition(); } } // 根据时间查找binlog位置 private EntryPosition findByStartTimeStamp(MysqlConnection mysqlConnection, Long startTimestamp) { EntryPosition endPosition = findEndPosition(mysqlConnection); EntryPosition startPosition = findStartPosition(mysqlConnection); String maxBinlogFileName = startPosition.getJournalName(); String minBinlogFileName = startPosition.getJournalName(); logger.info("show master status to set search end condition:{} ", endPosition); String startSearchBinlogFile = endPosition.getJournalName(); boolean shouldBreak = false; while (running && !shouldBreak) { try { EntryPosition entryPosition = findAsPerTimestampInSpecificLogFile(mysqlConnection, startTimestamp, endPosition, startSearchBinlogFile); if (entryPosition == null) { if (StringUtils.equalsIgnoreCase(minBinlogFileName, startSearchBinlogFile)) { // 已经找到最早的一个binlog,没必要往前找了 shouldBreak = true; logger.warn("Didn't find the corresponding binlog files from {} to {}", minBinlogFileName, maxBinlogFileName); } else { // 继续往前找 int binlogSeqNum = Integer.parseInt(startSearchBinlogFile.substring(startSearchBinlogFile.indexOf(".") + 1)); if (binlogSeqNum <= 1) { logger.warn("Didn't find the corresponding binlog files"); shouldBreak = true; } else { int nextBinlogSeqNum = binlogSeqNum - 1; String binlogFileNamePrefix = startSearchBinlogFile.substring( 0, startSearchBinlogFile.indexOf(".") + 1); String binlogFileNameSuffix = String.format("%06d", nextBinlogSeqNum); startSearchBinlogFile = binlogFileNamePrefix + binlogFileNameSuffix; } } } else { logger.info("found and return:{} in findByStartTimeStamp operation.", entryPosition); return entryPosition; } } catch (Exception e) { logger.warn( "the binlogfile:{} doesn't exist, to continue to search the next binlogfile , caused by {}", startSearchBinlogFile, ExceptionUtils.getFullStackTrace(e)); int binlogSeqNum = Integer.parseInt(startSearchBinlogFile.substring(startSearchBinlogFile.indexOf(".") + 1)); if (binlogSeqNum <= 1) { logger.warn("Didn't find the corresponding binlog files"); shouldBreak = true; } else { int nextBinlogSeqNum = binlogSeqNum - 1; String binlogFileNamePrefix = startSearchBinlogFile.substring( 0, startSearchBinlogFile.indexOf(".") + 1); String binlogFileNameSuffix = String.format("%06d", nextBinlogSeqNum); startSearchBinlogFile = binlogFileNamePrefix + binlogFileNameSuffix; } } } // 找不到 return null; } /** * 查询当前的binlog位置 */ private EntryPosition findEndPosition(MysqlConnection mysqlConnection) { try { ResultSetPacket packet = mysqlConnection.query("show master status"); List<String> fields = packet.getFieldValues(); if (CollectionUtils.isEmpty(fields)) { throw new CanalParseException( "command : 'show master status' has an error! pls check. you need (at least one of) the SUPER,REPLICATION CLIENT privilege(s) for this operation"); } EntryPosition endPosition = new EntryPosition(fields.get(0), Long.valueOf(fields.get(1))); return endPosition; } catch (IOException e) { logger.error("find end position error", e); } return null; } /** * 查询当前的binlog位置 */ private EntryPosition findStartPosition(MysqlConnection mysqlConnection) { try { ResultSetPacket packet = mysqlConnection.query("show binlog events limit 1"); List<String> fields = packet.getFieldValues(); if (CollectionUtils.isEmpty(fields)) { throw new CanalParseException( "command : 'show master status' has an error! pls check. you need (at least one of) the SUPER,REPLICATION CLIENT privilege(s) for this operation"); } EntryPosition endPosition = new EntryPosition(fields.get(0), Long.valueOf(fields.get(1))); return endPosition; } catch (IOException e) { logger.error("find end position error", e); } return null; } /** * 查询当前的slave视图的binlog位置 */ @SuppressWarnings("unused") private SlaveEntryPosition findSlavePosition(MysqlConnection mysqlConnection) { try { ResultSetPacket packet = mysqlConnection.query("show slave status"); List<FieldPacket> names = packet.getFieldDescriptors(); List<String> fields = packet.getFieldValues(); if (CollectionUtils.isEmpty(fields)) { return null; } int i = 0; Map<String, String> maps = new HashMap<String, String>(names.size(), 1f); for (FieldPacket name : names) { maps.put(name.getName(), fields.get(i)); i++; } String errno = maps.get("Last_Errno"); String slaveIORunning = maps.get("Slave_IO_Running"); // Slave_SQL_Running String slaveSQLRunning = maps.get("Slave_SQL_Running"); // Slave_SQL_Running if ((!"0".equals(errno)) || (!"Yes".equalsIgnoreCase(slaveIORunning)) || (!"Yes".equalsIgnoreCase(slaveSQLRunning))) { logger.warn("Ignoring failed slave: " + mysqlConnection.getChannel().toString() + ", Last_Errno = " + errno + ", Slave_IO_Running = " + slaveIORunning + ", Slave_SQL_Running = " + slaveSQLRunning); } String masterHost = maps.get("Master_Host"); String masterPort = maps.get("Master_Port"); String binlog = maps.get("Master_Log_File"); String position = maps.get("Exec_Master_Log_Pos"); return new SlaveEntryPosition(binlog, Long.valueOf(position), masterHost, masterPort); } catch (IOException e) { logger.error("find slave position error", e); } return null; } /** * 根据给定的时间戳,在指定的binlog中找到最接近于该时间戳(必须是小于时间戳)的一个事务起始位置。针对最后一个binlog会给定endPosition,避免无尽的查询 */ private EntryPosition findAsPerTimestampInSpecificLogFile(MysqlConnection mysqlConnection, final Long startTimestamp, final EntryPosition endPosition, final String searchBinlogFile) { final LogPosition logPosition = new LogPosition(); try { mysqlConnection.reconnect(); // 开始遍历文件 mysqlConnection.seek(searchBinlogFile, 4L, new SinkFunction<LogEvent>() { private LogPosition lastPosition; public boolean sink(LogEvent event) { EntryPosition entryPosition = null; try { CanalEntry.Entry entry = parseAndProfilingIfNecessary(event); if (entry == null) { return true; } String logfilename = entry.getHeader().getLogfileName(); Long logfileoffset = entry.getHeader().getLogfileOffset(); Long logposTimestamp = entry.getHeader().getExecuteTime(); if (CanalEntry.EntryType.TRANSACTIONBEGIN.equals(entry.getEntryType())) { logger.debug("compare exit condition:{},{},{}, startTimestamp={}...", new Object[] { logfilename, logfileoffset, logposTimestamp, startTimestamp }); // 寻找第一条记录时间戳,如果最小的一条记录都不满足条件,可直接退出 if (logposTimestamp >= startTimestamp) { return false; } } if (StringUtils.equals(endPosition.getJournalName(), logfilename) && endPosition.getPosition() <= (logfileoffset + event.getEventLen())) { return false; } // 记录一下上一个事务结束的位置,即下一个事务的position // position = current + data.length,代表该事务的下一条offest,避免多余的事务重复 if (CanalEntry.EntryType.TRANSACTIONEND.equals(entry.getEntryType())) { entryPosition = new EntryPosition(logfilename, logfileoffset + event.getEventLen(), logposTimestamp); logger.debug("set {} to be pending start position before finding another proper one...", entryPosition); logPosition.setPostion(entryPosition); } lastPosition = buildLastPosition(entry); } catch (Exception e) { processError(e, lastPosition, searchBinlogFile, 4L); } return running; } }); } catch (IOException e) { logger.error("ERROR ## findAsPerTimestampInSpecificLogFile has an error", e); } if (logPosition.getPostion() != null) { return logPosition.getPostion(); } else { return null; } } protected Entry parseAndProfilingIfNecessary(LogEvent bod) throws Exception { long startTs = -1; boolean enabled = getProfilingEnabled(); if (enabled) { startTs = System.currentTimeMillis(); } CanalEntry.Entry event = binlogParser.parse(bod); if (enabled) { this.parsingInterval = System.currentTimeMillis() - startTs; } if (parsedEventCount.incrementAndGet() < 0) { parsedEventCount.set(0); } return event; } // ===================== setter / getter ======================== public void setHeartBeatCallback(HeartBeatCallback heartBeatCallback) { this.heartBeatCallback = heartBeatCallback; } public void setDefaultConnectionTimeoutInSeconds(int defaultConnectionTimeoutInSeconds) { this.defaultConnectionTimeoutInSeconds = defaultConnectionTimeoutInSeconds; } public void setReceiveBufferSize(int receiveBufferSize) { this.receiveBufferSize = receiveBufferSize; } public void setSendBufferSize(int sendBufferSize) { this.sendBufferSize = sendBufferSize; } public void setMasterInfo(AuthenticationInfo masterInfo) { this.masterInfo = masterInfo; } public void setStandbyInfo(AuthenticationInfo standbyInfo) { this.standbyInfo = standbyInfo; } public void setMasterPosition(EntryPosition masterPosition) { this.masterPosition = masterPosition; } public void setStandbyPosition(EntryPosition standbyPosition) { this.standbyPosition = standbyPosition; } public void setSlaveId(long slaveId) { this.slaveId = slaveId; } public void setDetectingSQL(String detectingSQL) { this.detectingSQL = detectingSQL; } public void setDetectingIntervalInSeconds(Integer detectingIntervalInSeconds) { this.detectingIntervalInSeconds = detectingIntervalInSeconds; } public void setDetectingEnable(boolean detectingEnable) { this.detectingEnable = detectingEnable; } public void setFallbackIntervalInSeconds(int fallbackIntervalInSeconds) { this.fallbackIntervalInSeconds = fallbackIntervalInSeconds; } }
apache-2.0
rheinfabrik/android-mvvm-example
MVVM-Example/app/src/main/java/de/rheinfabrik/mvvm_example/controller/SearchResultController.java
1365
package de.rheinfabrik.mvvm_example.controller; import java.util.ArrayList; import java.util.List; import de.rheinfabrik.mvvm_example.network.OMDBApiFactory; import de.rheinfabrik.mvvm_example.network.OMDBApiService; import de.rheinfabrik.mvvm_example.network.models.SearchResult; import rx.Observable; import rx.schedulers.Schedulers; /** * Controller for interacting with search results. */ public class SearchResultController { // Members private OMDBApiService mOMDBApiService; // Constructor /** * The default constructor. */ public SearchResultController() { this(OMDBApiFactory.newApi()); } /** * The custom constructor. This one may be used within tests to inject a mocked service instance. */ public SearchResultController(OMDBApiService apiService) { super(); mOMDBApiService = apiService; } // Public Api /** * Fetches the proper search results for the given search term. Returns an empty list if no search results could be found. */ public Observable<List<SearchResult>> getSearchResults(String searchTerm) { return mOMDBApiService .getSearchResults(searchTerm) .subscribeOn(Schedulers.io()) .map(searchResults -> searchResults == null ? new ArrayList<>() : searchResults); } }
apache-2.0
google/mobile-data-download
javatests/com/google/android/libraries/mobiledatadownload/file/common/testing/FakeFileBackendTest.java
5859
/* * Copyright 2022 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.android.libraries.mobiledatadownload.file.common.testing; import static org.junit.Assert.assertThrows; import android.net.Uri; import android.util.Pair; import com.google.android.libraries.mobiledatadownload.file.common.GcParam; import com.google.android.libraries.mobiledatadownload.file.common.UnsupportedFileStorageOperation; import com.google.android.libraries.mobiledatadownload.file.spi.Backend; import com.google.common.collect.ImmutableList; import java.io.Closeable; import java.io.IOException; import java.util.List; import org.junit.Rule; import org.junit.Test; import org.junit.runner.RunWith; import org.robolectric.RobolectricTestRunner; @RunWith(RobolectricTestRunner.class) public final class FakeFileBackendTest extends BackendTestBase { private final FakeFileBackend backend = new FakeFileBackend(); @Rule public TemporaryUri tmpUri = new TemporaryUri(); @Override protected Backend backend() { return backend; } @Override protected Uri legalUriBase() throws IOException { return tmpUri.newDirectoryUri(); } @Override protected List<Uri> illegalUrisToRead() { return ImmutableList.of(); } @Override protected List<Uri> illegalUrisToWrite() { return ImmutableList.of(); } @Override protected List<Uri> illegalUrisToAppend() { return ImmutableList.of(); } @Test public void throwsExceptions_forRead() throws Exception { Uri uri = tmpUri.newUri(); backend.setFailure(FakeFileBackend.OperationType.READ, new FakeIOException("test")); assertThrows(FakeIOException.class, () -> backend.openForRead(uri)); assertThrows(FakeIOException.class, () -> backend.openForNativeRead(uri)); backend.clearFailure(FakeFileBackend.OperationType.READ); try (Closeable resource = backend.openForRead(uri)) {} Pair<Uri, Closeable> nativeOpen = backend.openForNativeRead(uri); try (Closeable resource = nativeOpen.second) {} } @Test public void throwsExceptions_forWrite() throws Exception { Uri uri = tmpUri.newUri(); backend.setFailure(FakeFileBackend.OperationType.WRITE, new FakeIOException("test")); assertThrows(FakeIOException.class, () -> backend.openForWrite(uri)); assertThrows(FakeIOException.class, () -> backend.openForAppend(uri)); backend.clearFailure(FakeFileBackend.OperationType.WRITE); try (Closeable resource = backend.openForWrite(uri)) {} try (Closeable resource = backend.openForAppend(uri)) {} } @Test public void throwsExceptions_forQuery() throws Exception { Uri uri = tmpUri.newUri(); Uri dir = tmpUri.newDirectoryUri(); backend.setFailure(FakeFileBackend.OperationType.QUERY, new FakeIOException("test")); assertThrows(FakeIOException.class, () -> backend.exists(uri)); assertThrows(FakeIOException.class, () -> backend.isDirectory(uri)); assertThrows(FakeIOException.class, () -> backend.fileSize(uri)); assertThrows(FakeIOException.class, () -> backend.children(dir)); assertThrows(FakeIOException.class, () -> backend.getGcParam(uri)); assertThrows(FakeIOException.class, () -> backend.toFile(uri)); backend.clearFailure(FakeFileBackend.OperationType.QUERY); backend.exists(uri); backend.isDirectory(uri); backend.fileSize(uri); backend.children(dir); assertThrows(UnsupportedFileStorageOperation.class, () -> backend.getGcParam(uri)); backend.toFile(uri); } @Test public void throwsExceptions_forManage() throws Exception { Uri uri = tmpUri.newUri(); Uri uri2 = tmpUri.newUri(); Uri dir = tmpUri.newDirectoryUri(); backend.setFailure(FakeFileBackend.OperationType.MANAGE, new FakeIOException("test")); assertThrows(FakeIOException.class, () -> backend.deleteFile(uri)); assertThrows(FakeIOException.class, () -> backend.deleteDirectory(dir)); assertThrows(FakeIOException.class, () -> backend.rename(uri, uri2)); assertThrows(FakeIOException.class, () -> backend.createDirectory(dir)); assertThrows(FakeIOException.class, () -> backend.setGcParam(uri, GcParam.none())); backend.clearFailure(FakeFileBackend.OperationType.MANAGE); assertThrows( UnsupportedFileStorageOperation.class, () -> backend.setGcParam(uri, GcParam.none())); backend.rename(uri, uri2); backend.deleteFile(uri2); backend.deleteDirectory(dir); backend.createDirectory(dir); } @Test public void throwsExceptions_forAll() throws Exception { Uri uri = tmpUri.newUri(); backend.setFailure(FakeFileBackend.OperationType.ALL, new FakeIOException("test")); assertThrows(FakeIOException.class, () -> backend.openForRead(uri)); // READ assertThrows(FakeIOException.class, () -> backend.openForWrite(uri)); // WRITE assertThrows(FakeIOException.class, () -> backend.exists(uri)); // QUERY assertThrows(FakeIOException.class, () -> backend.deleteFile(uri)); // MANAGE backend.clearFailure(FakeFileBackend.OperationType.ALL); try (Closeable resource = backend.openForRead(uri)) {} try (Closeable resource = backend.openForWrite(uri)) {} backend.exists(uri); backend.deleteFile(uri); } private static class FakeIOException extends IOException { FakeIOException(String message) { super(message); } } }
apache-2.0
brianchen2012/syncope
common/src/main/java/org/apache/syncope/common/types/PropagationMode.java
995
/* * 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.syncope.common.types; import javax.xml.bind.annotation.XmlEnum; @XmlEnum public enum PropagationMode { ONE_PHASE, TWO_PHASES }
apache-2.0
arunan123/algorithm-implementation-in-java-javascript-scala
java/test/com/algorithmdb/algorithms/sorting/test/TestMergeSort.java
1022
package com.algorithmdb.algorithms.sorting.test; import static org.junit.Assert.assertArrayEquals; import org.junit.Test; import com.algorithmdb.algorithms.sorting.MergeSort; public class TestMergeSort { Integer[] unSortedNumbers = {50,87,5,2,1000,9,23,90,8,32,1,23,18,100,11,980}; Integer[] expectedSortedNumbers = {1,2,5,8,9,11,18,23,23,32,50,87,90,100,980,1000}; String[] unSortedStrings = {"jagan","Arunan","Albert","Vijay","stephen","Jack","Selva","Anbarasan", "Richard","Venkat","Abi","Bharath","bala","Hedbert"}; String[] expectedSortedStrings = {"Abi","Albert","Anbarasan","Arunan","Bharath","Hedbert","Jack", "Richard","Selva","Venkat","Vijay","bala","jagan","stephen"}; @Test public void testIntegerSorting() { new MergeSort<Integer>().sort(unSortedNumbers); assertArrayEquals(expectedSortedNumbers, unSortedNumbers); } @Test public void testStringSorting() { new MergeSort<String>().sort(unSortedStrings); assertArrayEquals(expectedSortedStrings, unSortedStrings); } }
apache-2.0
lpicanco/grails
src/web/org/codehaus/groovy/grails/web/taglib/GroovyPageTagWriter.java
1931
/* Copyright 2004-2005 Graeme Rocher * * 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.codehaus.groovy.grails.web.taglib; import java.io.PrintWriter; import java.io.StringWriter; /** * A temporary writer used by GSP to write to a StringWriter and later retrieve the value. It also converts * nulls into blank strings. * * @author Graeme Rocher * @since 0.5 * * <p/> * Created: Apr 19, 2007 * Time: 5:49:46 PM */ public class GroovyPageTagWriter extends PrintWriter { private static final String BLANK_STRING = ""; private StringWriter stringWriter; public GroovyPageTagWriter(StringWriter writer) { super(writer); this.stringWriter = writer; } public StringWriter getStringWriter() { return stringWriter; } public void print(String s) { if( s == null) s = BLANK_STRING; super.print(s); } public void print(Object o) { if(o == null) o = BLANK_STRING; super.print(o); } public void write(String s) { if(s == null) s = BLANK_STRING; super.write(s); } public void println(String s) { if(s == null) s = BLANK_STRING; super.println(s); } public void println(Object o) { if(o==null)o = BLANK_STRING; super.println(o); } public String getValue() { return stringWriter.toString(); } }
apache-2.0
ewolff/microservice-atom
microservice-atom/microservice-atom-order/src/test/java/com/ewolff/microservice/order/logic/OrderWebIntegrationTest.java
3405
package com.ewolff.microservice.order.logic; import static org.junit.Assert.*; import java.util.stream.StreamSupport; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.boot.test.context.SpringBootTest.WebEnvironment; import org.springframework.boot.web.server.LocalServerPort; import org.springframework.http.ResponseEntity; import org.springframework.test.context.ActiveProfiles; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import org.springframework.util.LinkedMultiValueMap; import org.springframework.util.MultiValueMap; import org.springframework.web.client.RestTemplate; import com.ewolff.microservice.order.OrderApp; import com.ewolff.microservice.order.customer.Customer; import com.ewolff.microservice.order.customer.CustomerRepository; import com.ewolff.microservice.order.item.Item; import com.ewolff.microservice.order.item.ItemRepository; @RunWith(SpringJUnit4ClassRunner.class) @SpringBootTest(classes = OrderApp.class, webEnvironment = WebEnvironment.RANDOM_PORT) @ActiveProfiles("test") public class OrderWebIntegrationTest { private RestTemplate restTemplate = new RestTemplate(); @LocalServerPort private long serverPort; @Autowired private ItemRepository itemRepository; @Autowired private CustomerRepository customerRepository; @Autowired private OrderRepository orderRepository; private Item item; private Customer customer; @Before public void setup() { item = itemRepository.findAll().iterator().next(); customer = new Customer("RZA", "GZA", "rza@wutang.com", "Chamber", "Shaolin"); customer = customerRepository.save(customer); } @Test public void IsOrderListReturned() { try { Iterable<Order> orders = orderRepository.findAll(); assertTrue(StreamSupport.stream(orders.spliterator(), false) .noneMatch(o -> ((o.getCustomer() != null) && (o.getCustomer().equals(customer))))); ResponseEntity<String> resultEntity = restTemplate.getForEntity(orderURL(), String.class); assertTrue(resultEntity.getStatusCode().is2xxSuccessful()); String orderList = resultEntity.getBody(); assertFalse(orderList.contains("RZA")); Order order = new Order(customer); order.addLine(42, item); orderRepository.save(order); orderList = restTemplate.getForObject(orderURL(), String.class); assertTrue(orderList.contains("Eberhard")); } finally { orderRepository.deleteAll(); } } private String orderURL() { return "http://localhost:" + serverPort; } @Test public void IsOrderFormDisplayed() { ResponseEntity<String> resultEntity = restTemplate.getForEntity(orderURL() + "/form.html", String.class); assertTrue(resultEntity.getStatusCode().is2xxSuccessful()); assertTrue(resultEntity.getBody().contains("<form")); } @Test public void IsSubmittedOrderSaved() { long before = orderRepository.count(); MultiValueMap<String, String> map = new LinkedMultiValueMap<String, String>(); map.add("submit", ""); map.add("customer", Long.toString(customer.getCustomerId())); map.add("orderLine[0].item", Long.toString(item.getItemId())); map.add("orderLine[0].count", "42"); restTemplate.postForLocation(orderURL(), map, String.class); assertEquals(before + 1, orderRepository.count()); } }
apache-2.0
fengsterooni/potlatch
client/app/src/main/java/org/coursera/androidcapstone/potlatch/activities/NewGiftActivity.java
933
package org.coursera.androidcapstone.potlatch.activities; import android.os.Bundle; import android.support.v7.app.ActionBarActivity; import org.coursera.androidcapstone.potlatch.R; import org.coursera.androidcapstone.potlatch.fragments.NewGiftFragment; public class NewGiftActivity extends ActionBarActivity { private static final String TAG = NewGiftActivity.class.getSimpleName(); NewGiftFragment fragment; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_new_gift); final Long pId = getIntent().getLongExtra("parentId", 0); if (savedInstanceState == null) { fragment = NewGiftFragment.newInstance(pId); getSupportFragmentManager().beginTransaction() .add(R.id.fNewContainer, fragment) .commit(); } } }
apache-2.0
zzzengxiaoxian/weathercool
app/src/main/java/com/coolweather/smtq/girl/MzituFragment.java
2438
package com.coolweather.smtq.girl; import com.coolweather.smtq.base.BaseGirlsListFragment; import com.coolweather.smtq.model.Girl; import org.jsoup.Jsoup; import org.jsoup.nodes.Document; import org.jsoup.nodes.Element; import org.jsoup.select.Elements; import java.io.IOException; import java.util.ArrayList; import java.util.List; import rx.Observable; import rx.Observer; import rx.android.schedulers.AndroidSchedulers; import rx.functions.Func1; import rx.schedulers.Schedulers; /** * Created by liyu on 2016/12/13. */ public class MzituFragment extends BaseGirlsListFragment { @Override protected void getGirlFromServer() { showRefreshing(true); String url = getArguments().getString("url") + "/page/" + currentPage; subscription = Observable.just(url).subscribeOn(Schedulers.io()).map(new Func1<String, List<Girl>>() { @Override public List<Girl> call(String url) { List<Girl> girls = new ArrayList<>(); try { Document doc = Jsoup.connect(url).timeout(10000).get(); Element total = doc.select("div.postlist").first(); Elements items = total.select("li"); for (Element element : items) { Girl girl = new Girl(element.select("img").first().attr("data-original")); girl.setLink(element.select("a[href]").attr("href")); girls.add(girl); } } catch (IOException e) { e.printStackTrace(); } return girls; } }).observeOn(AndroidSchedulers.mainThread()).subscribe(new Observer<List<Girl>>() { @Override public void onCompleted() { isLoading = false; } @Override public void onError(Throwable e) { isLoading = false; showRefreshing(false); } @Override public void onNext(List<Girl> girls) { currentPage++; showRefreshing(false); if (adapter.getData() == null || adapter.getData().size() == 0) { adapter.setNewData(girls); } else { adapter.addData(adapter.getData().size(), girls); } } }); } }
apache-2.0
pgneri/plugin-zbarcodescanner
src/android/com/phonegap/plugins/barcodescanner/BarcodeScanner.java
11517
/** * PhoneGap is available under *either* the terms of the modified BSD license *or* the * MIT License (2008). See http://opensource.org/licenses/alphabetical for full text. * * Copyright (c) Matt Kane 2010 * Copyright (c) 2011, IBM Corporation * Copyright (c) 2013, Maciej Nux Jaros */ package com.phonegap.plugins.barcodescanner; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import android.Manifest; import android.app.Activity; import android.content.Intent; import android.util.Log; import android.content.pm.PackageManager; import org.apache.cordova.CordovaPlugin; import org.apache.cordova.CallbackContext; import org.apache.cordova.PluginResult; import org.apache.cordova.PermissionHelper; import com.google.zxing.client.android.CaptureActivity; import com.google.zxing.client.android.encode.EncodeActivity; import com.google.zxing.client.android.Intents; /** * This calls out to the ZXing barcode reader and returns the result. * * @sa https://github.com/apache/cordova-android/blob/master/framework/src/org/apache/cordova/CordovaPlugin.java */ public class BarcodeScanner extends CordovaPlugin { public static final int REQUEST_CODE = 0x0ba7c0de; private static final String SCAN = "scan"; private static final String ENCODE = "encode"; private static final String CANCELLED = "cancelled"; private static final String FORMAT = "format"; private static final String TEXT = "text"; private static final String DATA = "data"; private static final String TYPE = "type"; private static final String PREFER_FRONTCAMERA = "preferFrontCamera"; private static final String ORIENTATION = "orientation"; private static final String SHOW_FLIP_CAMERA_BUTTON = "showFlipCameraButton"; private static final String FORMATS = "formats"; private static final String PROMPT = "prompt"; private static final String TEXT_TYPE = "TEXT_TYPE"; private static final String EMAIL_TYPE = "EMAIL_TYPE"; private static final String PHONE_TYPE = "PHONE_TYPE"; private static final String SMS_TYPE = "SMS_TYPE"; private static final String LOG_TAG = "BarcodeScanner"; private String [] permissions = { Manifest.permission.CAMERA }; private JSONArray requestArgs; private CallbackContext callbackContext; /** * Constructor. */ public BarcodeScanner() { } /** * Executes the request. * * This method is called from the WebView thread. To do a non-trivial amount of work, use: * cordova.getThreadPool().execute(runnable); * * To run on the UI thread, use: * cordova.getActivity().runOnUiThread(runnable); * * @param action The action to execute. * @param args The exec() arguments. * @param callbackContext The callback context used when calling back into JavaScript. * @return Whether the action was valid. * * @sa https://github.com/apache/cordova-android/blob/master/framework/src/org/apache/cordova/CordovaPlugin.java */ @Override public boolean execute(String action, JSONArray args, CallbackContext callbackContext) { this.callbackContext = callbackContext; this.requestArgs = args; if (action.equals(ENCODE)) { JSONObject obj = args.optJSONObject(0); if (obj != null) { String type = obj.optString(TYPE); String data = obj.optString(DATA); // If the type is null then force the type to text if (type == null) { type = TEXT_TYPE; } if (data == null) { callbackContext.error("User did not specify data to encode"); return true; } encode(type, data); } else { callbackContext.error("User did not specify data to encode"); return true; } } else if (action.equals(SCAN)) { //android permission auto add if(!hasPermisssion()) { requestPermissions(0); } else { scan(args); } } else { return false; } return true; } /** * Starts an intent to scan and decode a barcode. */ public void scan(final JSONArray args) { final CordovaPlugin that = this; cordova.getThreadPool().execute(new Runnable() { public void run() { Intent intentScan = new Intent(that.cordova.getActivity().getBaseContext(), CaptureActivity.class); intentScan.setAction(Intents.Scan.ACTION); intentScan.addCategory(Intent.CATEGORY_DEFAULT); // add config as intent extras if (args.length() > 0) { JSONObject obj; JSONArray names; String key; Object value; for (int i = 0; i < args.length(); i++) { try { obj = args.getJSONObject(i); } catch (JSONException e) { Log.i("CordovaLog", e.getLocalizedMessage()); continue; } names = obj.names(); for (int j = 0; j < names.length(); j++) { try { key = names.getString(j); value = obj.get(key); if (value instanceof Integer) { intentScan.putExtra(key, (Integer) value); } else if (value instanceof String) { intentScan.putExtra(key, (String) value); } } catch (JSONException e) { Log.i("CordovaLog", e.getLocalizedMessage()); } } intentScan.putExtra(Intents.Scan.CAMERA_ID, obj.optBoolean(PREFER_FRONTCAMERA, false) ? 1 : 0); intentScan.putExtra(Intents.Scan.SHOW_FLIP_CAMERA_BUTTON, obj.optBoolean(SHOW_FLIP_CAMERA_BUTTON, false)); if (obj.has(FORMATS)) { intentScan.putExtra(Intents.Scan.FORMATS, obj.optString(FORMATS)); } if (obj.has(PROMPT)) { intentScan.putExtra(Intents.Scan.PROMPT_MESSAGE, obj.optString(PROMPT)); } if (obj.has(ORIENTATION)) { intentScan.putExtra(Intents.Scan.ORIENTATION_LOCK, obj.optString(ORIENTATION)); } } } // avoid calling other phonegap apps intentScan.setPackage(that.cordova.getActivity().getApplicationContext().getPackageName()); that.cordova.startActivityForResult(that, intentScan, REQUEST_CODE); } }); } /** * Called when the barcode scanner intent completes. * * @param requestCode The request code originally supplied to startActivityForResult(), * allowing you to identify who this result came from. * @param resultCode The integer result code returned by the child activity through its setResult(). * @param intent An Intent, which can return result data to the caller (various data can be attached to Intent "extras"). */ @Override public void onActivityResult(int requestCode, int resultCode, Intent intent) { if (requestCode == REQUEST_CODE && this.callbackContext != null) { if (resultCode == Activity.RESULT_OK) { JSONObject obj = new JSONObject(); try { obj.put(TEXT, intent.getStringExtra("SCAN_RESULT")); obj.put(FORMAT, intent.getStringExtra("SCAN_RESULT_FORMAT")); obj.put(CANCELLED, false); } catch (JSONException e) { Log.d(LOG_TAG, "This should never happen"); } //this.success(new PluginResult(PluginResult.Status.OK, obj), this.callback); this.callbackContext.success(obj); } else if (resultCode == Activity.RESULT_CANCELED) { JSONObject obj = new JSONObject(); try { obj.put(TEXT, ""); obj.put(FORMAT, ""); obj.put(CANCELLED, true); } catch (JSONException e) { Log.d(LOG_TAG, "This should never happen"); } //this.success(new PluginResult(PluginResult.Status.OK, obj), this.callback); this.callbackContext.success(obj); } else { //this.error(new PluginResult(PluginResult.Status.ERROR), this.callback); this.callbackContext.error("Unexpected error"); } } } /** * Initiates a barcode encode. * * @param type Endoiding type. * @param data The data to encode in the bar code. */ public void encode(String type, String data) { Intent intentEncode = new Intent(this.cordova.getActivity().getBaseContext(), EncodeActivity.class); intentEncode.setAction(Intents.Encode.ACTION); intentEncode.putExtra(Intents.Encode.TYPE, type); intentEncode.putExtra(Intents.Encode.DATA, data); // avoid calling other phonegap apps intentEncode.setPackage(this.cordova.getActivity().getApplicationContext().getPackageName()); this.cordova.getActivity().startActivity(intentEncode); } /** * check application's permissions */ public boolean hasPermisssion() { for(String p : permissions) { if(!PermissionHelper.hasPermission(this, p)) { return false; } } return true; } /** * We override this so that we can access the permissions variable, which no longer exists in * the parent class, since we can't initialize it reliably in the constructor! * * @param requestCode The code to get request action */ public void requestPermissions(int requestCode) { PermissionHelper.requestPermissions(this, requestCode, permissions); } /** * processes the result of permission request * * @param requestCode The code to get request action * @param permissions The collection of permissions * @param grantResults The result of grant */ public void onRequestPermissionResult(int requestCode, String[] permissions, int[] grantResults) throws JSONException { PluginResult result; for (int r : grantResults) { if (r == PackageManager.PERMISSION_DENIED) { Log.d(LOG_TAG, "Permission Denied!"); result = new PluginResult(PluginResult.Status.ILLEGAL_ACCESS_EXCEPTION); this.callbackContext.sendPluginResult(result); return; } } switch(requestCode) { case 0: scan(this.requestArgs); break; } } }
apache-2.0
drbunsen-bsteam/hibersap
hibersap-core/src/main/java/org/hibersap/mapping/BapiField.java
3744
/* * Copyright (c) 2008-2014 akquinet tech@spree GmbH * * This file is part of Hibersap. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this software 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.hibersap.mapping; import org.hibersap.annotations.Convert; import org.hibersap.annotations.Export; import org.hibersap.annotations.Import; import org.hibersap.annotations.Parameter; import org.hibersap.annotations.ParameterType; import org.hibersap.annotations.Table; import org.hibersap.conversion.Converter; import java.lang.reflect.Field; import java.util.Collection; /** * @author Carsten Erker */ class BapiField { private static final Class<Parameter> PARAM = Parameter.class; private static final Class<Import> IMPORT = Import.class; private static final Class<Export> EXPORT = Export.class; private static final Class<Table> TABLE = Table.class; private static final Class<Convert> CONVERT = Convert.class; private final Field field; public BapiField( final Field field ) { this.field = field; } public Class<?> getArrayType() { Class<?> associatedType = field.getType(); return ReflectionHelper.getArrayType( associatedType ); } /** * @return The type. */ public Class<?> getAssociatedType() { if ( field.getType().isArray() ) { return getArrayType(); } if ( Collection.class.isAssignableFrom( field.getType() ) ) { return getGenericType(); } return getType(); } public Class<? extends Converter> getConverter() { if ( field.isAnnotationPresent( CONVERT ) ) { Convert convert = field.getAnnotation( CONVERT ); return convert.converter(); } return null; } public Class<?> getGenericType() { return ReflectionHelper.getGenericType( field ); } public String getName() { return field.getName(); } private Parameter getParameterAnnotation() { return field.getAnnotation( PARAM ); } public String getSapName() { return getParameterAnnotation().value(); } public Class<?> getType() { return field.getType(); } public boolean isExport() { return field.isAnnotationPresent( EXPORT ); } public boolean isImport() { return field.isAnnotationPresent( IMPORT ); } public boolean isParameter() { return field.isAnnotationPresent( PARAM ); } public boolean isStructure() { boolean result = false; if ( isParameter() ) { result = getParameterAnnotation().type() == ParameterType.STRUCTURE; } return result; } /** * Check if the field's type equals to {@link org.hibersap.annotations.ParameterType#TABLE_STRUCTURE}. * * @return true if the field is of the type {@link org.hibersap.annotations.ParameterType#TABLE_STRUCTURE} */ public boolean isTableStructure() { boolean result = false; if ( isParameter() ) { result = getParameterAnnotation().type() == ParameterType.TABLE_STRUCTURE; } return result; } public boolean isTable() { return field.isAnnotationPresent( TABLE ); } }
apache-2.0
grails/grails-static-website
buildSrc/src/main/java/org/grails/airtable/AirtableConfiguration.java
1058
/* * Copyright 2017-2022 original authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.grails.airtable; import edu.umd.cs.findbugs.annotations.NonNull; /** * @author Sergio del Amo * @since 1.0.0 */ public interface AirtableConfiguration { /** * * @return Airtable API URL */ @NonNull String getUrl(); /** * * @return Airtable API Key */ @NonNull String getApiKey(); /** * * @return Airtable API version */ @NonNull String getApiVersion(); }
apache-2.0
spohnan/geowave
core/store/src/main/java/org/locationtech/geowave/core/store/data/DataReader.java
960
/** * Copyright (c) 2013-2019 Contributors to the Eclipse Foundation * * <p> See the NOTICE file distributed with this work for additional information regarding copyright * ownership. All rights reserved. This program and the accompanying materials are made available * under the terms of the Apache License, Version 2.0 which accompanies this distribution and is * available at http://www.apache.org/licenses/LICENSE-2.0.txt */ package org.locationtech.geowave.core.store.data; import org.locationtech.geowave.core.store.data.field.FieldReader; /** * This interface is used to read data from a row in a GeoWave data store. * * @param <FieldType> The binding class of this field */ public interface DataReader<FieldType> { /** * Get a reader for an individual field. * * @param fieldName the ID of the field * @return the FieldReader for the given field Name (ID) */ public FieldReader<FieldType> getReader(String fieldName); }
apache-2.0
jentfoo/aws-sdk-java
aws-java-sdk-personalize/src/main/java/com/amazonaws/services/personalize/model/transform/DataSourceMarshaller.java
1931
/* * Copyright 2014-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with * the License. A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR * CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions * and limitations under the License. */ package com.amazonaws.services.personalize.model.transform; import javax.annotation.Generated; import com.amazonaws.SdkClientException; import com.amazonaws.services.personalize.model.*; import com.amazonaws.protocol.*; import com.amazonaws.annotation.SdkInternalApi; /** * DataSourceMarshaller */ @Generated("com.amazonaws:aws-java-sdk-code-generator") @SdkInternalApi public class DataSourceMarshaller { private static final MarshallingInfo<String> DATALOCATION_BINDING = MarshallingInfo.builder(MarshallingType.STRING) .marshallLocation(MarshallLocation.PAYLOAD).marshallLocationName("dataLocation").build(); private static final DataSourceMarshaller instance = new DataSourceMarshaller(); public static DataSourceMarshaller getInstance() { return instance; } /** * Marshall the given parameter object. */ public void marshall(DataSource dataSource, ProtocolMarshaller protocolMarshaller) { if (dataSource == null) { throw new SdkClientException("Invalid argument passed to marshall(...)"); } try { protocolMarshaller.marshall(dataSource.getDataLocation(), DATALOCATION_BINDING); } catch (Exception e) { throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e); } } }
apache-2.0
jbeecham/ovirt-engine
backend/manager/modules/bll/src/main/java/org/ovirt/engine/core/bll/GetPermittedStorageDomainsByTemplateIdQuery.java
925
package org.ovirt.engine.core.bll; import org.ovirt.engine.core.bll.storage.GetStorageDomainsByVmTemplateIdQuery; import org.ovirt.engine.core.common.businessentities.storage_domains; import org.ovirt.engine.core.common.queries.GetPermittedStorageDomainsByTemplateIdParameters; import org.ovirt.engine.core.compat.Guid; import org.ovirt.engine.core.dal.dbbroker.DbFacade; public class GetPermittedStorageDomainsByTemplateIdQuery<P extends GetPermittedStorageDomainsByTemplateIdParameters> extends GetStorageDomainsByVmTemplateIdQuery<P> { public GetPermittedStorageDomainsByTemplateIdQuery(P parameters) { super(parameters); } @Override protected storage_domains getStorageDomain(Guid domainId) { return DbFacade.getInstance() .getStorageDomainDao() .getPermittedStorageDomainsById(getUserID(), getParameters().getActionGroup(), domainId); } }
apache-2.0
stevenhva/InfoLearn_OpenOLAT
src/main/java/org/olat/shibboleth/DMZShibRegistrationContentControllerCreator.java
2222
/** * OLAT - Online Learning and Training<br> * http://www.olat.org * <p> * Licensed under the Apache License, Version 2.0 (the "License"); <br> * you may not use this file except in compliance with the License.<br> * You may obtain a copy of the License at * <p> * http://www.apache.org/licenses/LICENSE-2.0 * <p> * Unless required by applicable law or agreed to in writing,<br> * software distributed under the License is distributed on an "AS IS" BASIS, <br> * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. <br> * See the License for the specific language governing permissions and <br> * limitations under the License. * <p> * Copyright (c) since 2004 at Multimedia- & E-Learning Services (MELS),<br> * University of Zurich, Switzerland. * <hr> * <a href="http://www.openolat.org"> * OpenOLAT - Online Learning and Training</a><br> * This file has been modified by the OpenOLAT community. Changes are licensed * under the Apache 2.0 license as the original file. */ package org.olat.shibboleth; import org.olat.core.commons.fullWebApp.BaseFullWebappController; import org.olat.core.gui.UserRequest; import org.olat.core.gui.control.Controller; import org.olat.core.gui.control.WindowControl; import org.olat.core.gui.control.creator.AutoCreator; import org.olat.core.gui.control.creator.ControllerCreator; import org.olat.login.DmzBFWCParts; /** * Description:<br> * TODO: patrickb Class Description for DMZContentControllerCreator * * <P> * Initial Date: 29.01.2008 <br> * @author patrickb */ public class DMZShibRegistrationContentControllerCreator implements ControllerCreator { /** * @see org.olat.core.gui.control.creator.ControllerCreator#createController(org.olat.core.gui.UserRequest, org.olat.core.gui.control.WindowControl) */ public Controller createController(UserRequest lureq, WindowControl lwControl) { DmzBFWCParts dmzSitesAndNav = new DmzBFWCParts(); AutoCreator contentControllerCreator = new AutoCreator(); contentControllerCreator.setClassName(ShibbolethRegistrationController.class.getName()); dmzSitesAndNav.setContentControllerCreator(contentControllerCreator); return new BaseFullWebappController(lureq, lwControl, dmzSitesAndNav ); } }
apache-2.0
mdanielwork/intellij-community
platform/analysis-api/src/com/intellij/codeInspection/ex/InspectionToolWrapper.java
6456
// Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.codeInspection.ex; import com.intellij.codeHighlighting.HighlightDisplayLevel; import com.intellij.codeInspection.CleanupLocalInspectionTool; import com.intellij.codeInspection.GlobalInspectionContext; import com.intellij.codeInspection.InspectionEP; import com.intellij.codeInspection.InspectionProfileEntry; import com.intellij.diagnostic.PluginException; import com.intellij.lang.Language; import com.intellij.openapi.application.Application; import com.intellij.openapi.application.ApplicationManager; import com.intellij.openapi.diagnostic.Logger; import com.intellij.openapi.project.Project; import com.intellij.util.ResourceUtil; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.io.IOException; import java.net.URL; /** * @author Dmitry Avdeev */ public abstract class InspectionToolWrapper<T extends InspectionProfileEntry, E extends InspectionEP> { public static final InspectionToolWrapper[] EMPTY_ARRAY = new InspectionToolWrapper[0]; private static final Logger LOG = Logger.getInstance("#com.intellij.codeInspection.ex.InspectionToolWrapper"); protected T myTool; protected final E myEP; protected InspectionToolWrapper(@NotNull E ep) { this(null, ep); } protected InspectionToolWrapper(@NotNull T tool) { this(tool, null); } protected InspectionToolWrapper(@Nullable T tool, @Nullable E ep) { assert tool != null || ep != null : "must not be both null"; myEP = ep; myTool = tool; } /** Copy ctor */ protected InspectionToolWrapper(@NotNull InspectionToolWrapper<T, ? extends E> other) { myEP = other.myEP; // we need to create a copy for buffering if (other.myTool == null) { myTool = null; } else { //noinspection unchecked myTool = (T)(myEP == null ? InspectionToolsRegistrarCore.instantiateTool(other.myTool.getClass()) : myEP.instantiateTool()); } } public void initialize(@NotNull GlobalInspectionContext context) { } @NotNull public abstract InspectionToolWrapper<T, E> createCopy(); @NotNull public T getTool() { T tool = myTool; if (tool == null) { //noinspection unchecked myTool = tool = (T)myEP.instantiateTool(); if (!tool.getShortName().equals(myEP.getShortName())) { LOG.error(new PluginException("Short name not matched for " + tool.getClass() + ": getShortName() = #" + tool.getShortName() + "; ep.shortName = #" + myEP.getShortName(), myEP.getPluginId())); } } return tool; } public boolean isInitialized() { return myTool != null; } /** * @see #applyToDialects() * @see #isApplicable(Language) */ @Nullable public String getLanguage() { return myEP == null ? null : myEP.language; } public boolean applyToDialects() { return myEP != null && myEP.applyToDialects; } public boolean isApplicable(@NotNull Language language) { String langId = getLanguage(); return langId == null || language.getID().equals(langId) || applyToDialects() && language.isKindOf(langId); } public boolean isCleanupTool() { return myEP != null ? myEP.cleanupTool : getTool() instanceof CleanupLocalInspectionTool; } @NotNull public String getShortName() { return myEP != null ? myEP.getShortName() : getTool().getShortName(); } public String getID() { return getShortName(); } @NotNull public String getDisplayName() { if (myEP == null) { return getTool().getDisplayName(); } else { String name = myEP.getDisplayName(); return name == null ? getTool().getDisplayName() : name; } } @NotNull public String getGroupDisplayName() { if (myEP == null) { return getTool().getGroupDisplayName(); } else { String groupDisplayName = myEP.getGroupDisplayName(); return groupDisplayName == null ? getTool().getGroupDisplayName() : groupDisplayName; } } public boolean isEnabledByDefault() { return myEP == null ? getTool().isEnabledByDefault() : myEP.enabledByDefault; } @NotNull public HighlightDisplayLevel getDefaultLevel() { return myEP == null ? getTool().getDefaultLevel() : myEP.getDefaultLevel(); } @NotNull public String[] getGroupPath() { if (myEP == null) { return getTool().getGroupPath(); } else { String[] path = myEP.getGroupPath(); return path == null ? getTool().getGroupPath() : path; } } public String getStaticDescription() { return myEP == null || myEP.hasStaticDescription ? getTool().getStaticDescription() : null; } public String loadDescription() { final String description = getStaticDescription(); if (description != null) return description; try { URL descriptionUrl = getDescriptionUrl(); if (descriptionUrl == null) return null; return ResourceUtil.loadText(descriptionUrl); } catch (IOException ignored) { } return getTool().loadDescription(); } protected URL getDescriptionUrl() { Application app = ApplicationManager.getApplication(); if (myEP == null || app.isUnitTestMode() || app.isHeadlessEnvironment()) { return superGetDescriptionUrl(); } String fileName = getDescriptionFileName(); return myEP.getLoaderForClass().getResource("inspectionDescriptions/" + fileName); } @Nullable protected URL superGetDescriptionUrl() { final String fileName = getDescriptionFileName(); return ResourceUtil.getResource(getDescriptionContextClass(), "inspectionDescriptions", fileName); } @NotNull public String getDescriptionFileName() { return getShortName() + ".html"; } @NotNull public final String getFolderName() { return getShortName(); } @NotNull public Class<? extends InspectionProfileEntry> getDescriptionContextClass() { return getTool().getClass(); } public String getMainToolId() { return getTool().getMainToolId(); } public E getExtension() { return myEP; } @Override public String toString() { return getShortName(); } public void cleanup(@NotNull Project project) { T tool = myTool; if (tool != null) { tool.cleanup(project); } } @NotNull public abstract JobDescriptor[] getJobDescriptors(@NotNull GlobalInspectionContext context); }
apache-2.0
AnonymousProductions/MineFantasy2
src/main/java/minefantasy/mf2/item/gadget/ItemParachute.java
1975
package minefantasy.mf2.item.gadget; import java.util.List; import minefantasy.mf2.MineFantasyII; import minefantasy.mf2.entity.EntityBomb; import minefantasy.mf2.entity.EntityParachute; import minefantasy.mf2.item.list.CreativeTabMF; import minefantasy.mf2.mechanics.BombDispenser; import net.minecraft.block.BlockDispenser; import net.minecraft.client.renderer.texture.IIconRegister; import net.minecraft.creativetab.CreativeTabs; import net.minecraft.entity.Entity; import net.minecraft.entity.EntityList; import net.minecraft.entity.EntityLivingBase; import net.minecraft.entity.passive.EntityChicken; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.init.Items; import net.minecraft.item.EnumAction; import net.minecraft.item.EnumRarity; import net.minecraft.item.Item; import net.minecraft.item.ItemMonsterPlacer; import net.minecraft.item.ItemStack; import net.minecraft.nbt.NBTTagCompound; import net.minecraft.util.EnumChatFormatting; import net.minecraft.util.IIcon; import net.minecraft.util.StatCollector; import net.minecraft.world.World; import cpw.mods.fml.common.registry.GameRegistry; import cpw.mods.fml.relauncher.Side; import cpw.mods.fml.relauncher.SideOnly; public class ItemParachute extends Item { public ItemParachute() { String name = "parachute"; this.maxStackSize = 1; this.setCreativeTab(CreativeTabMF.tabGadget); setTextureName("minefantasy2:Other/"+name); GameRegistry.registerItem(this, name, MineFantasyII.MODID); this.setUnlocalizedName(name); } @Override public ItemStack onItemRightClick(ItemStack item, World world, EntityPlayer user) { if(!world.isRemote) { world.playSoundAtEntity(user, "mob.horse.leather", 1.0F, 0.5F); EntityParachute chute = new EntityParachute(world, user.posX, user.posY, user.posZ); world.spawnEntityInWorld(chute); user.mountEntity(chute); --item.stackSize; } return item; } }
apache-2.0
ibm-cloud-security/appid-clientsdk-android
lib/src/test/java/com/ibm/cloud/appid/android/api/Config_Test.java
3286
/* Copyright 2017 IBM Corp. 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.ibm.cloud.appid.android.api; import com.ibm.mobilefirstplatform.appid_clientsdk_android.BuildConfig; import org.junit.Before; import org.junit.FixMethodOrder; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.MethodSorters; import org.mockito.Mock; import org.mockito.MockitoAnnotations; import org.robolectric.RobolectricTestRunner; import org.robolectric.annotation.Config; import static org.mockito.Mockito.*; import static org.assertj.core.api.Java6Assertions.*; @RunWith (RobolectricTestRunner.class) @FixMethodOrder (MethodSorters.NAME_ASCENDING) @Config (constants = BuildConfig.class) public class Config_Test { @Mock private AppID appId; @Before public void before() { MockitoAnnotations.initMocks(this); when(appId.getBluemixRegion()).thenReturn("https://us-south.appid.cloud.ibm.com"); when(appId.getTenantId()).thenReturn("tenant-id"); } @Test public void testConfig() { String url = com.ibm.cloud.appid.android.internal.config.Config.getOAuthServerUrl(appId); assertThat(url).isEqualTo("https://us-south.appid.cloud.ibm.com/oauth/v4/tenant-id"); url = com.ibm.cloud.appid.android.internal.config.Config.getUserProfilesServerUrl(appId); assertThat(url).isEqualTo("https://us-south.appid.cloud.ibm.com/api/v1/"); url = com.ibm.cloud.appid.android.internal.config.Config.getIssuer(appId); assertThat(url).isEqualTo("https://us-south.appid.cloud.ibm.com/oauth/v4/tenant-id"); appId.overrideOAuthServerHost = "https://oauth-server-host-"; appId.overrideUserProfilesHost = "https://user-profiles-host"; url = com.ibm.cloud.appid.android.internal.config.Config.getOAuthServerUrl(appId); assertThat(url).isEqualTo("https://oauth-server-host-tenant-id"); url = com.ibm.cloud.appid.android.internal.config.Config.getUserProfilesServerUrl(appId); assertThat(url).isEqualTo("https://user-profiles-host/api/v1/"); url = com.ibm.cloud.appid.android.internal.config.Config.getIssuer(appId); assertThat(url).isEqualTo("https://oauth-server-host-/oauth/v4/tenant-id"); // need to reset server hosts, because they are global variables that can impact other tests appId.overrideOAuthServerHost = null; appId.overrideUserProfilesHost = null; //verify old endpoints are converted to new cloud.ibm.com when(appId.getBluemixRegion()).thenReturn(".ng.bluemix.net"); url = com.ibm.cloud.appid.android.internal.config.Config.getOAuthServerUrl(appId); assertThat(url).isEqualTo("https://us-south.appid.cloud.ibm.com/oauth/v4/tenant-id"); url = com.ibm.cloud.appid.android.internal.config.Config.getIssuer(appId); assertThat(url).isEqualTo("https://us-south.appid.cloud.ibm.com/oauth/v4/tenant-id"); } }
apache-2.0
tomdw/aries
cdi/cdi-extender/src/main/java/org/apache/aries/cdi/container/internal/loader/BundleClassLoader.java
2847
/** * 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.apache.aries.cdi.container.internal.loader; import java.io.IOException; import java.net.URL; import java.net.URLClassLoader; import java.util.Collections; import java.util.Enumeration; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; import org.osgi.framework.Bundle; public class BundleClassLoader extends URLClassLoader { public BundleClassLoader(Bundle[] bundles) { super(new URL[0]); if (bundles.length == 0) { throw new IllegalArgumentException( "At least one bundle is required"); } _bundles = bundles; } @Override public URL findResource(String name) { for (Bundle bundle : _bundles) { URL url = bundle.getResource(name); if (url != null) { return url; } } return null; } @Override public Enumeration<URL> findResources(String name) { for (Bundle bundle : _bundles) { try { Enumeration<URL> enumeration = bundle.getResources(name); if ((enumeration != null) && enumeration.hasMoreElements()) { return enumeration; } } catch (IOException ioe) { } } return Collections.emptyEnumeration(); } public Bundle[] getBundles() { return _bundles; } @Override public URL getResource(String name) { return findResource(name); } @Override public Enumeration<URL> getResources(String name) { return findResources(name); } @Override protected Class<?> findClass(String name) throws ClassNotFoundException { Object classLoadingLock = getClassLoadingLock(name); synchronized (classLoadingLock) { for (Bundle bundle : _bundles) { try { return bundle.loadClass(name); } catch (ClassNotFoundException cnfe) { continue; } } throw new ClassNotFoundException(name); } } @Override protected Class<?> loadClass(String name, boolean resolve) throws ClassNotFoundException { Object classLoadingLock = getClassLoadingLock(name); synchronized (classLoadingLock) { Class<?> clazz = _cache.get(name); if (clazz == null) { clazz = findClass(name); if (resolve) { resolveClass(clazz); } _cache.put(name, clazz); } return clazz; } } private final Bundle[] _bundles; private final ConcurrentMap<String, Class<?>> _cache = new ConcurrentHashMap<>(); }
apache-2.0
cipriancraciun/mosaic-java-prototype
cloudlets/src/main/java/eu/mosaic_cloud/cloudlets/core/callbacks/CloudletCallbackArguments.java
504
package eu.mosaic_cloud.cloudlets.core.callbacks; import eu.mosaic_cloud.callbacks.core.CallbackArguments; import eu.mosaic_cloud.cloudlets.core.CloudletController; public abstract class CloudletCallbackArguments implements CallbackArguments { CloudletCallbackArguments (final CloudletController cloudlet, final CloudletCallbackType type) { super (); this.cloudlet = cloudlet; this.type = type; } public final CloudletController cloudlet; public final CloudletCallbackType type; }
apache-2.0
mdogan/hazelcast
hazelcast/src/main/java/com/hazelcast/client/impl/protocol/codec/DurableExecutorIsShutdownCodec.java
4056
/* * Copyright (c) 2008-2020, Hazelcast, Inc. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.hazelcast.client.impl.protocol.codec; import com.hazelcast.client.impl.protocol.ClientMessage; import com.hazelcast.client.impl.protocol.Generated; import com.hazelcast.client.impl.protocol.codec.builtin.*; import com.hazelcast.client.impl.protocol.codec.custom.*; import javax.annotation.Nullable; import static com.hazelcast.client.impl.protocol.ClientMessage.*; import static com.hazelcast.client.impl.protocol.codec.builtin.FixedSizeTypesCodec.*; /* * This file is auto-generated by the Hazelcast Client Protocol Code Generator. * To change this file, edit the templates or the protocol * definitions on the https://github.com/hazelcast/hazelcast-client-protocol * and regenerate it. */ /** * Returns true if this executor has been shut down. */ @Generated("976e9721c8286b79d10bda2d8a0487c2") public final class DurableExecutorIsShutdownCodec { //hex: 0x180200 public static final int REQUEST_MESSAGE_TYPE = 1573376; //hex: 0x180201 public static final int RESPONSE_MESSAGE_TYPE = 1573377; private static final int REQUEST_INITIAL_FRAME_SIZE = PARTITION_ID_FIELD_OFFSET + INT_SIZE_IN_BYTES; private static final int RESPONSE_RESPONSE_FIELD_OFFSET = RESPONSE_BACKUP_ACKS_FIELD_OFFSET + BYTE_SIZE_IN_BYTES; private static final int RESPONSE_INITIAL_FRAME_SIZE = RESPONSE_RESPONSE_FIELD_OFFSET + BOOLEAN_SIZE_IN_BYTES; private DurableExecutorIsShutdownCodec() { } /** * Name of the executor. */ @edu.umd.cs.findbugs.annotations.SuppressFBWarnings({"UUF_UNUSED_PUBLIC_OR_PROTECTED_FIELD"}) public java.lang.String name; public static ClientMessage encodeRequest(java.lang.String name) { ClientMessage clientMessage = ClientMessage.createForEncode(); clientMessage.setRetryable(false); clientMessage.setOperationName("DurableExecutor.IsShutdown"); ClientMessage.Frame initialFrame = new ClientMessage.Frame(new byte[REQUEST_INITIAL_FRAME_SIZE], UNFRAGMENTED_MESSAGE); encodeInt(initialFrame.content, TYPE_FIELD_OFFSET, REQUEST_MESSAGE_TYPE); encodeInt(initialFrame.content, PARTITION_ID_FIELD_OFFSET, -1); clientMessage.add(initialFrame); StringCodec.encode(clientMessage, name); return clientMessage; } public static java.lang.String decodeRequest(ClientMessage clientMessage) { ClientMessage.ForwardFrameIterator iterator = clientMessage.frameIterator(); //empty initial frame iterator.next(); return StringCodec.decode(iterator); } public static ClientMessage encodeResponse(boolean response) { ClientMessage clientMessage = ClientMessage.createForEncode(); ClientMessage.Frame initialFrame = new ClientMessage.Frame(new byte[RESPONSE_INITIAL_FRAME_SIZE], UNFRAGMENTED_MESSAGE); encodeInt(initialFrame.content, TYPE_FIELD_OFFSET, RESPONSE_MESSAGE_TYPE); encodeBoolean(initialFrame.content, RESPONSE_RESPONSE_FIELD_OFFSET, response); clientMessage.add(initialFrame); return clientMessage; } /** * true if this executor has been shut down */ public static boolean decodeResponse(ClientMessage clientMessage) { ClientMessage.ForwardFrameIterator iterator = clientMessage.frameIterator(); ClientMessage.Frame initialFrame = iterator.next(); return decodeBoolean(initialFrame.content, RESPONSE_RESPONSE_FIELD_OFFSET); } }
apache-2.0
jokoframework/security
src/main/java/io/github/jokoframework/security/springex/JokoAccessDeniedHandler.java
2047
package io.github.jokoframework.security.springex; import com.fasterxml.jackson.databind.ObjectMapper; import io.github.jokoframework.common.JokoUtils; import io.github.jokoframework.common.dto.JokoBaseResponse; import io.github.jokoframework.security.controller.SecurityConstants; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.security.access.AccessDeniedException; import org.springframework.security.core.Authentication; import org.springframework.security.core.context.SecurityContextHolder; import org.springframework.security.web.access.AccessDeniedHandler; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; import java.io.PrintWriter; public class JokoAccessDeniedHandler implements AccessDeniedHandler { private static final Logger LOGGER = LoggerFactory.getLogger(JokoAccessDeniedHandler.class); @Override public void handle(HttpServletRequest request, HttpServletResponse response, AccessDeniedException accessDeniedException) throws IOException, ServletException { Authentication auth = SecurityContextHolder.getContext().getAuthentication(); Object principal = auth.getPrincipal(); String username = "Unknown user "; if (principal != null) { username = (String) principal; } String uri = request.getRequestURI(); LOGGER.warn(username + " Tried to access resource " + uri + ", but it doesn't have enough access rights"); JokoBaseResponse error = new JokoBaseResponse(SecurityConstants.ERROR_NOT_ALLOWED); error.setMessage("Not authorized to execute " + JokoUtils.formatLogString(uri)); ObjectMapper mapper = new ObjectMapper(); response.setHeader("Content-type", "application/json"); response.setStatus(HttpServletResponse.SC_FORBIDDEN); PrintWriter out = response.getWriter(); mapper.writeValue(out, error); } }
apache-2.0
Pardus-Engerek/engerek
model/certification-impl/src/main/java/com/evolveum/midpoint/certification/impl/AccessCertificationCloseStageApproachingTriggerHandler.java
4054
/* * Copyright (c) 2010-2015 Evolveum * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.evolveum.midpoint.certification.impl; import com.evolveum.midpoint.model.impl.trigger.TriggerHandler; import com.evolveum.midpoint.model.impl.trigger.TriggerHandlerRegistry; import com.evolveum.midpoint.prism.PrismObject; import com.evolveum.midpoint.schema.constants.ObjectTypes; import com.evolveum.midpoint.schema.result.OperationResult; import com.evolveum.midpoint.schema.util.ObjectTypeUtil; import com.evolveum.midpoint.task.api.Task; import com.evolveum.midpoint.util.exception.*; import com.evolveum.midpoint.util.logging.LoggingUtils; import com.evolveum.midpoint.util.logging.Trace; import com.evolveum.midpoint.util.logging.TraceManager; import com.evolveum.midpoint.xml.ns._public.common.common_3.*; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import javax.annotation.PostConstruct; import java.util.Collection; import java.util.List; /** * @author mederly * */ @Component public class AccessCertificationCloseStageApproachingTriggerHandler implements TriggerHandler { public static final String HANDLER_URI = AccessCertificationConstants.NS_CERTIFICATION_TRIGGER_PREFIX + "/close-stage-approaching/handler-3"; private static final transient Trace LOGGER = TraceManager.getTrace(AccessCertificationCloseStageApproachingTriggerHandler.class); @Autowired private TriggerHandlerRegistry triggerHandlerRegistry; @Autowired private AccCertEventHelper eventHelper; @Autowired private AccCertQueryHelper queryHelper; @Autowired private AccCertUpdateHelper updateHelper; @PostConstruct private void initialize() { triggerHandlerRegistry.register(HANDLER_URI, this); } @Override public <O extends ObjectType> void handle(PrismObject<O> prismObject, TriggerType trigger, Task task, OperationResult result) { try { ObjectType object = prismObject.asObjectable(); if (!(object instanceof AccessCertificationCampaignType)) { LOGGER.error("Trigger of this type is supported only on {} objects, not on {}", AccessCertificationCampaignType.class.getSimpleName(), object.getClass().getName()); return; } AccessCertificationCampaignType campaign = (AccessCertificationCampaignType) object; LOGGER.info("Generating 'deadline approaching' events for {}", ObjectTypeUtil.toShortString(campaign)); if (campaign.getState() != AccessCertificationCampaignStateType.IN_REVIEW_STAGE) { LOGGER.warn("Campaign is not in review stage; exiting"); return; } eventHelper.onCampaignStageDeadlineApproaching(campaign, task, result); List<AccessCertificationCaseType> caseList = queryHelper.searchCases(campaign.getOid(), null, null, result); Collection<String> reviewers = eventHelper.getCurrentActiveReviewers(caseList); for (String reviewerOid : reviewers) { List<AccessCertificationCaseType> reviewerCaseList = queryHelper.selectOpenCasesForReviewer(caseList, reviewerOid); ObjectReferenceType actualReviewerRef = ObjectTypeUtil.createObjectRef(reviewerOid, ObjectTypes.USER); for (ObjectReferenceType reviewerOrDeputyRef : updateHelper.getReviewerAndDeputies(actualReviewerRef, task, result)) { eventHelper.onReviewDeadlineApproaching(reviewerOrDeputyRef, actualReviewerRef, reviewerCaseList, campaign, task, result); } } } catch (SchemaException|RuntimeException e) { LoggingUtils.logException(LOGGER, "Couldn't generate 'deadline approaching' notifications", e); } } }
apache-2.0
nince-wyj/jahhan
frameworkx/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/transport/AbstractServer.java
6360
/* * Copyright 1999-2011 Alibaba Group. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.alibaba.dubbo.remoting.transport; import java.net.InetSocketAddress; import java.util.Collection; import java.util.concurrent.ExecutorService; import java.util.concurrent.ThreadPoolExecutor; import com.alibaba.dubbo.common.Constants; import com.alibaba.dubbo.common.URL; import com.alibaba.dubbo.common.utils.ExecutorUtil; import com.alibaba.dubbo.common.utils.NetUtils; import com.alibaba.dubbo.remoting.Channel; import com.alibaba.dubbo.remoting.RemotingException; import com.alibaba.dubbo.remoting.Server; import com.frameworkx.common.extension.utils.ExtensionExtendUtil; import lombok.extern.slf4j.Slf4j; import net.jahhan.spi.ChannelHandler; import net.jahhan.spi.DataStore; /** * AbstractServer * * @author qian.lei * @author ding.lid */ @Slf4j public abstract class AbstractServer extends AbstractEndpoint implements Server { private InetSocketAddress localAddress; private InetSocketAddress bindAddress; private int accepts; private int idleTimeout = 600; // 600 seconds protected static final String SERVER_THREAD_POOL_NAME = "DubboServerHandler"; ExecutorService executor; public AbstractServer(URL url, ChannelHandler handler) throws RemotingException { super(url, handler); localAddress = getUrl().toInetSocketAddress(); String host = url.getParameter(Constants.ANYHOST_KEY, false) || NetUtils.isInvalidLocalHost(getUrl().getHost()) ? NetUtils.ANYHOST : getUrl().getHost(); bindAddress = new InetSocketAddress(host, getUrl().getPort()); this.accepts = url.getParameter(Constants.ACCEPTS_KEY, Constants.DEFAULT_ACCEPTS); this.idleTimeout = url.getParameter(Constants.IDLE_TIMEOUT_KEY, Constants.DEFAULT_IDLE_TIMEOUT); try { doOpen(); if (log.isInfoEnabled()) { log.info("Start " + getClass().getSimpleName() + " bind " + getBindAddress() + ", export " + getLocalAddress()); } } catch (Throwable t) { throw new RemotingException(url.toInetSocketAddress(), null, "Failed to bind " + getClass().getSimpleName() + " on " + getLocalAddress() + ", cause: " + t.getMessage(), t); } executor = (ExecutorService) ExtensionExtendUtil.getExtension(DataStore.class) .get(Constants.EXECUTOR_SERVICE_COMPONENT_KEY, Integer.toString(url.getPort())); } protected abstract void doOpen() throws Throwable; protected abstract void doClose() throws Throwable; public void reset(URL url) { if (url == null) { return; } try { if (url.hasParameter(Constants.ACCEPTS_KEY)) { int a = url.getParameter(Constants.ACCEPTS_KEY, 0); if (a > 0) { this.accepts = a; } } } catch (Throwable t) { log.error(t.getMessage(), t); } try { if (url.hasParameter(Constants.IDLE_TIMEOUT_KEY)) { int t = url.getParameter(Constants.IDLE_TIMEOUT_KEY, 0); if (t > 0) { this.idleTimeout = t; } } } catch (Throwable t) { log.error(t.getMessage(), t); } try { if (url.hasParameter(Constants.THREADS_KEY) && executor instanceof ThreadPoolExecutor && !executor.isShutdown()) { ThreadPoolExecutor threadPoolExecutor = (ThreadPoolExecutor) executor; int threads = url.getParameter(Constants.THREADS_KEY, 0); int max = threadPoolExecutor.getMaximumPoolSize(); int core = threadPoolExecutor.getCorePoolSize(); if (threads > 0 && (threads != max || threads != core)) { if (threads < core) { threadPoolExecutor.setCorePoolSize(threads); if (core == max) { threadPoolExecutor.setMaximumPoolSize(threads); } } else { threadPoolExecutor.setMaximumPoolSize(threads); if (core == max) { threadPoolExecutor.setCorePoolSize(threads); } } } } } catch (Throwable t) { log.error(t.getMessage(), t); } super.setUrl(getUrl().addParameters(url.getParameters())); } public void send(Object message, boolean sent) throws RemotingException { Collection<Channel> channels = getChannels(); for (Channel channel : channels) { if (channel.isConnected()) { channel.send(message, sent); } } } public void close() { if (log.isInfoEnabled()) { log.info("Close " + getClass().getSimpleName() + " bind " + getBindAddress() + ", export " + getLocalAddress()); } ExecutorUtil.shutdownNow(executor, 100); try { super.close(); } catch (Throwable e) { log.warn(e.getMessage(), e); } try { doClose(); } catch (Throwable e) { log.warn(e.getMessage(), e); } } public void close(int timeout) { ExecutorUtil.gracefulShutdown(executor, timeout); close(); } public InetSocketAddress getLocalAddress() { return localAddress; } public InetSocketAddress getBindAddress() { return bindAddress; } public int getAccepts() { return accepts; } public int getIdleTimeout() { return idleTimeout; } @Override public void connected(Channel ch) throws RemotingException { // 如果server已进入关闭流程,拒绝新的连接 if (this.isClosing() || this.isClosed()) { log.warn("Close new channel " + ch + ", cause: server is closing or has been closed. For example, receive a new connect request while in shutdown process."); ch.close(); return; } Collection<Channel> channels = getChannels(); if (accepts > 0 && channels.size() > accepts) { log.error("Close channel " + ch + ", cause: The server " + ch.getLocalAddress() + " connections greater than max config " + accepts); ch.close(); return; } super.connected(ch); } @Override public void disconnected(Channel ch) throws RemotingException { Collection<Channel> channels = getChannels(); if (channels.size() == 0) { log.warn( "All clients has discontected from " + ch.getLocalAddress() + ". You can graceful shutdown now."); } super.disconnected(ch); } }
apache-2.0
nince-wyj/jahhan
common/common-extension/src/main/java/net/jahhan/com/alibaba/dubbo/common/bytecode/Wrapper.java
15164
/* * Copyright 1999-2011 Alibaba Group. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.jahhan.com.alibaba.dubbo.common.bytecode; import java.lang.reflect.Field; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.lang.reflect.Modifier; import java.util.ArrayList; import java.util.HashMap; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.atomic.AtomicLong; import java.util.regex.Matcher; import net.jahhan.com.alibaba.dubbo.common.utils.ClassHelper; import net.jahhan.com.alibaba.dubbo.common.utils.ReflectUtils; import net.jahhan.common.extension.constant.JahhanErrorCode; import net.jahhan.common.extension.exception.JahhanException; /** * Wrapper. * * @author qian.lei */ public abstract class Wrapper { private static AtomicLong WRAPPER_CLASS_COUNTER = new AtomicLong(0); private static final Map<Class<?>, Wrapper> WRAPPER_MAP = new ConcurrentHashMap<Class<?>, Wrapper>(); // class // wrapper // map private static final String[] EMPTY_STRING_ARRAY = new String[0]; private static final String[] OBJECT_METHODS = new String[] { "getClass", "hashCode", "toString", "equals" }; private static final Wrapper OBJECT_WRAPPER = new Wrapper() { public String[] getMethodNames() { return OBJECT_METHODS; } public String[] getDeclaredMethodNames() { return OBJECT_METHODS; } public String[] getPropertyNames() { return EMPTY_STRING_ARRAY; } public Class<?> getPropertyType(String pn) { return null; } public Object getPropertyValue(Object instance, String pn) throws JahhanException { throw new JahhanException(JahhanErrorCode.NOT_SUCH_PROPERTIES_EXCEPTION, "Property [" + pn + "] not found."); } public void setPropertyValue(Object instance, String pn, Object pv) throws JahhanException { throw new JahhanException(JahhanErrorCode.NOT_SUCH_PROPERTIES_EXCEPTION, "Property [" + pn + "] not found."); } public boolean hasProperty(String name) { return false; } public Object invokeMethod(Object instance, String mn, Class<?>[] types, Object[] args) throws NoSuchMethodException { if ("getClass".equals(mn)) return instance.getClass(); if ("hashCode".equals(mn)) return instance.hashCode(); if ("toString".equals(mn)) return instance.toString(); if ("equals".equals(mn)) { if (args.length == 1) return instance.equals(args[0]); throw new IllegalArgumentException("Invoke method [" + mn + "] argument number error."); } throw new NoSuchMethodException("Method [" + mn + "] not found."); } }; /** * get wrapper. * * @param c * Class instance. * @return Wrapper instance(not null). */ public static Wrapper getWrapper(Class<?> c) { while (ClassGenerator.isDynamicClass(c)) // can not wrapper on dynamic // class. c = c.getSuperclass(); if (c == Object.class) return OBJECT_WRAPPER; Wrapper ret = WRAPPER_MAP.get(c); if (ret == null) { ret = makeWrapper(c); WRAPPER_MAP.put(c, ret); } return ret; } /** * get property name array. * * @return property name array. */ abstract public String[] getPropertyNames(); /** * get property type. * * @param pn * property name. * @return Property type or nul. */ abstract public Class<?> getPropertyType(String pn); /** * has property. * * @param name * property name. * @return has or has not. */ abstract public boolean hasProperty(String name); /** * get property value. * * @param instance * instance. * @param pn * property name. * @return value. */ abstract public Object getPropertyValue(Object instance, String pn) throws JahhanException, IllegalArgumentException; /** * set property value. * * @param instance * instance. * @param pn * property name. * @param pv * property value. */ abstract public void setPropertyValue(Object instance, String pn, Object pv) throws JahhanException, IllegalArgumentException; /** * get property value. * * @param instance * instance. * @param pns * property name array. * @return value array. */ public Object[] getPropertyValues(Object instance, String[] pns) throws JahhanException, IllegalArgumentException { Object[] ret = new Object[pns.length]; for (int i = 0; i < ret.length; i++) ret[i] = getPropertyValue(instance, pns[i]); return ret; } /** * set property value. * * @param instance * instance. * @param pns * property name array. * @param pvs * property value array. */ public void setPropertyValues(Object instance, String[] pns, Object[] pvs) throws JahhanException, IllegalArgumentException { if (pns.length != pvs.length) throw new IllegalArgumentException("pns.length != pvs.length"); for (int i = 0; i < pns.length; i++) setPropertyValue(instance, pns[i], pvs[i]); } /** * get method name array. * * @return method name array. */ abstract public String[] getMethodNames(); /** * get method name array. * * @return method name array. */ abstract public String[] getDeclaredMethodNames(); /** * has method. * * @param name * method name. * @return has or has not. */ public boolean hasMethod(String name) { for (String mn : getMethodNames()) if (mn.equals(name)) return true; return false; } /** * invoke method. * * @param instance * instance. * @param mn * method name. * @param types * @param args * argument array. * @return return value. */ abstract public Object invokeMethod(Object instance, String mn, Class<?>[] types, Object[] args) throws NoSuchMethodException, InvocationTargetException; private static Wrapper makeWrapper(Class<?> c) { if (c.isPrimitive()) throw new IllegalArgumentException("Can not create wrapper for primitive type: " + c); String name = c.getName(); ClassLoader cl = ClassHelper.getClassLoader(c); StringBuilder c1 = new StringBuilder("public void setPropertyValue(Object o, String n, Object v){ "); StringBuilder c2 = new StringBuilder("public Object getPropertyValue(Object o, String n){ "); StringBuilder c3 = new StringBuilder( "public Object invokeMethod(Object o, String n, Class[] p, Object[] v) throws " + InvocationTargetException.class.getName() + "{ "); c1.append(name).append(" w; try{ w = ((").append(name) .append(")$1); }catch(Throwable e){ throw new IllegalArgumentException(e); }"); c2.append(name).append(" w; try{ w = ((").append(name) .append(")$1); }catch(Throwable e){ throw new IllegalArgumentException(e); }"); c3.append(name).append(" w; try{ w = ((").append(name) .append(")$1); }catch(Throwable e){ throw new IllegalArgumentException(e); }"); Map<String, Class<?>> pts = new HashMap<String, Class<?>>(); // <property // name, // property // types> Map<String, Method> ms = new LinkedHashMap<String, Method>(); // <method // desc, // Method // instance> List<String> mns = new ArrayList<String>(); // method names. List<String> dmns = new ArrayList<String>(); // declaring method names. // get all public field. for (Field f : c.getFields()) { String fn = f.getName(); Class<?> ft = f.getType(); if (Modifier.isStatic(f.getModifiers()) || Modifier.isTransient(f.getModifiers())) continue; c1.append(" if( $2.equals(\"").append(fn).append("\") ){ w.").append(fn).append("=").append(arg(ft, "$3")) .append("; return; }"); c2.append(" if( $2.equals(\"").append(fn).append("\") ){ return ($w)w.").append(fn).append("; }"); pts.put(fn, ft); } Method[] methods = c.getMethods(); // get all public method. boolean hasMethod = hasMethods(methods); if (hasMethod) { c3.append(" try{"); } for (Method m : methods) { if (m.getDeclaringClass() == Object.class) // ignore Object's // method. continue; String mn = m.getName(); c3.append(" if( \"").append(mn).append("\".equals( $2 ) "); int len = m.getParameterTypes().length; c3.append(" && ").append(" $3.length == ").append(len); boolean override = false; for (Method m2 : methods) { if (m != m2 && m.getName().equals(m2.getName())) { override = true; break; } } if (override) { if (len > 0) { for (int l = 0; l < len; l++) { c3.append(" && ").append(" $3[").append(l).append("].getName().equals(\"") .append(m.getParameterTypes()[l].getName()).append("\")"); } } } c3.append(" ) { "); if (m.getReturnType() == Void.TYPE) c3.append(" w.").append(mn).append('(').append(args(m.getParameterTypes(), "$4")).append(");") .append(" return null;"); else c3.append(" return ($w)w.").append(mn).append('(').append(args(m.getParameterTypes(), "$4")) .append(");"); c3.append(" }"); mns.add(mn); if (m.getDeclaringClass() == c) dmns.add(mn); ms.put(ReflectUtils.getDesc(m), m); } if (hasMethod) { c3.append(" } catch(Throwable e) { "); c3.append(" throw new java.lang.reflect.InvocationTargetException(e); "); c3.append(" }"); } c3.append(" throw new " + JahhanException.class.getName() + "(\"Not found method \\\"\"+$2+\"\\\" in class " + c.getName() + ".\"); }"); // deal with get/set method. Matcher matcher; for (Map.Entry<String, Method> entry : ms.entrySet()) { String md = entry.getKey(); Method method = (Method) entry.getValue(); if ((matcher = ReflectUtils.GETTER_METHOD_DESC_PATTERN.matcher(md)).matches()) { String pn = propertyName(matcher.group(1)); c2.append(" if( $2.equals(\"").append(pn).append("\") ){ return ($w)w.").append(method.getName()) .append("(); }"); pts.put(pn, method.getReturnType()); } else if ((matcher = ReflectUtils.IS_HAS_CAN_METHOD_DESC_PATTERN.matcher(md)).matches()) { String pn = propertyName(matcher.group(1)); c2.append(" if( $2.equals(\"").append(pn).append("\") ){ return ($w)w.").append(method.getName()) .append("(); }"); pts.put(pn, method.getReturnType()); } else if ((matcher = ReflectUtils.SETTER_METHOD_DESC_PATTERN.matcher(md)).matches()) { Class<?> pt = method.getParameterTypes()[0]; String pn = propertyName(matcher.group(1)); c1.append(" if( $2.equals(\"").append(pn).append("\") ){ w.").append(method.getName()).append("(") .append(arg(pt, "$3")).append("); return; }"); pts.put(pn, pt); } } c1.append(" throw new " + JahhanException.class.getName() + "(\"Not found property \\\"\"+$2+\"\\\" filed or setter method in class " + c.getName() + ".\"); }"); c2.append(" throw new " + JahhanException.class.getName() + "(\"Not found property \\\"\"+$2+\"\\\" filed or setter method in class " + c.getName() + ".\"); }"); // make class long id = WRAPPER_CLASS_COUNTER.getAndIncrement(); ClassGenerator cc = ClassGenerator.newInstance(cl); cc.setClassName((Modifier.isPublic(c.getModifiers()) ? Wrapper.class.getName() : c.getName() + "$sw") + id); cc.setSuperClass(Wrapper.class); cc.addDefaultConstructor(); cc.addField("public static String[] pns;"); // property name array. cc.addField("public static " + Map.class.getName() + " pts;"); // property // type // map. cc.addField("public static String[] mns;"); // all method name array. cc.addField("public static String[] dmns;"); // declared method name // array. for (int i = 0, len = ms.size(); i < len; i++) cc.addField("public static Class[] mts" + i + ";"); cc.addMethod("public String[] getPropertyNames(){ return pns; }"); cc.addMethod("public boolean hasProperty(String n){ return pts.containsKey($1); }"); cc.addMethod("public Class getPropertyType(String n){ return (Class)pts.get($1); }"); cc.addMethod("public String[] getMethodNames(){ return mns; }"); cc.addMethod("public String[] getDeclaredMethodNames(){ return dmns; }"); cc.addMethod(c1.toString()); cc.addMethod(c2.toString()); cc.addMethod(c3.toString()); try { Class<?> wc = cc.toClass(); // setup static field. wc.getField("pts").set(null, pts); wc.getField("pns").set(null, pts.keySet().toArray(new String[0])); wc.getField("mns").set(null, mns.toArray(new String[0])); wc.getField("dmns").set(null, dmns.toArray(new String[0])); int ix = 0; for (Method m : ms.values()) wc.getField("mts" + ix++).set(null, m.getParameterTypes()); return (Wrapper) wc.newInstance(); } catch (RuntimeException e) { throw e; } catch (Throwable e) { throw new RuntimeException(e.getMessage(), e); } finally { cc.release(); ms.clear(); mns.clear(); dmns.clear(); } } private static String arg(Class<?> cl, String name) { if (cl.isPrimitive()) { if (cl == Boolean.TYPE) return "((Boolean)" + name + ").booleanValue()"; if (cl == Byte.TYPE) return "((Byte)" + name + ").byteValue()"; if (cl == Character.TYPE) return "((Character)" + name + ").charValue()"; if (cl == Double.TYPE) return "((Number)" + name + ").doubleValue()"; if (cl == Float.TYPE) return "((Number)" + name + ").floatValue()"; if (cl == Integer.TYPE) return "((Number)" + name + ").intValue()"; if (cl == Long.TYPE) return "((Number)" + name + ").longValue()"; if (cl == Short.TYPE) return "((Number)" + name + ").shortValue()"; throw new RuntimeException("Unknown primitive type: " + cl.getName()); } return "(" + ReflectUtils.getName(cl) + ")" + name; } private static String args(Class<?>[] cs, String name) { int len = cs.length; if (len == 0) return ""; StringBuilder sb = new StringBuilder(); for (int i = 0; i < len; i++) { if (i > 0) sb.append(','); sb.append(arg(cs[i], name + "[" + i + "]")); } return sb.toString(); } private static String propertyName(String pn) { return pn.length() == 1 || Character.isLowerCase(pn.charAt(1)) ? Character.toLowerCase(pn.charAt(0)) + pn.substring(1) : pn; } private static boolean hasMethods(Method[] methods) { if (methods == null || methods.length == 0) { return false; } for (Method m : methods) { if (m.getDeclaringClass() != Object.class) { return true; } } return false; } }
apache-2.0
pascallouisperez/guice-jit-providers
src/com/google/inject/binder/LinkedBindingBuilder.java
2652
/** * Copyright (C) 2006 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.inject.binder; import com.google.inject.Key; import com.google.inject.Provider; import com.google.inject.TypeLiteral; import java.lang.reflect.Constructor; /** * See the EDSL examples at {@link com.google.inject.Binder}. * * @author crazybob@google.com (Bob Lee) */ public interface LinkedBindingBuilder<T> extends ScopedBindingBuilder { /** * See the EDSL examples at {@link com.google.inject.Binder}. */ ScopedBindingBuilder to(Class<? extends T> implementation); /** * See the EDSL examples at {@link com.google.inject.Binder}. */ ScopedBindingBuilder to(TypeLiteral<? extends T> implementation); /** * See the EDSL examples at {@link com.google.inject.Binder}. */ ScopedBindingBuilder to(Key<? extends T> targetKey); /** * See the EDSL examples at {@link com.google.inject.Binder}. * * @see com.google.inject.Injector#injectMembers */ void toInstance(T instance); /** * See the EDSL examples at {@link com.google.inject.Binder}. * * @see com.google.inject.Injector#injectMembers */ ScopedBindingBuilder toProvider(Provider<? extends T> provider); /** * See the EDSL examples at {@link com.google.inject.Binder}. */ ScopedBindingBuilder toProvider( Class<? extends javax.inject.Provider<? extends T>> providerType); /** * See the EDSL examples at {@link com.google.inject.Binder}. */ ScopedBindingBuilder toProvider( TypeLiteral<? extends javax.inject.Provider<? extends T>> providerType); /** * See the EDSL examples at {@link com.google.inject.Binder}. */ ScopedBindingBuilder toProvider( Key<? extends javax.inject.Provider<? extends T>> providerKey); /** * See the EDSL examples at {@link com.google.inject.Binder}. */ <S extends T> ScopedBindingBuilder toConstructor(Constructor<S> constructor); /** * See the EDSL examples at {@link com.google.inject.Binder}. */ <S extends T> ScopedBindingBuilder toConstructor( Constructor<S> constructor, TypeLiteral<? extends S> type); }
apache-2.0
CloudBPM/SwinFlowCloud-CloudSide
core.buildtime/src/main/java/com/cloudibpm/core/data/expression/ExpressionParser.java
8586
package com.cloudibpm.core.data.expression; import com.cloudibpm.core.WorkflowEntity; import com.cloudibpm.core.buildtime.wfprocess.Transition; import com.cloudibpm.core.buildtime.wfprocess.WfProcess; import com.cloudibpm.core.buildtime.wfprocess.task.*; import com.cloudibpm.core.data.FileConstant; import com.cloudibpm.core.data.StringConstant; import com.cloudibpm.core.data.variable.DataVariable; import com.cloudibpm.core.data.variable.Parameter; import com.cloudibpm.core.data.variable.ParameterUtil; public class ExpressionParser { /** * @param process * @return * @throws Exception */ public static WfProcess parseExpressions(WfProcess process) throws Exception { for (int i = 0; i < process.getChildren().length; i++) { if (process.getChildren()[i] instanceof SystemTask) { if (((SystemTask) process.getChildren()[i]) != null) { // parsing parameter string... ((SystemTask) process.getChildren()[i]).setPathParameters(ParameterUtil .parseParameters(((SystemTask) process.getChildren()[i]).getPathParameterString())); ((SystemTask) process.getChildren()[i]).setFormParameters(ParameterUtil .parseParameters(((SystemTask) process.getChildren()[i]).getFormParameterString())); // parsing the value in the parameter... if (((SystemTask) process.getChildren()[i]).getPathParameters() != null) { for (int j = 0; j < ((SystemTask) process.getChildren()[i]).getPathParameters().length; j++) { Parameter para = ((SystemTask) process.getChildren()[i]).getPathParameters()[j]; if (para != null && para.getValue() != null && para.getValue() instanceof Expression) { ((Expression) para.getValue()).parseExpressionString(process); } } } if (((SystemTask) process.getChildren()[i]).getFormParameters() != null) { for (int j = 0; j < ((SystemTask) process.getChildren()[i]).getFormParameters().length; j++) { Parameter para = ((SystemTask) process.getChildren()[i]).getFormParameters()[j]; if (para != null && para.getValue() != null) { ((Expression) para.getValue()).parseExpressionString(process); } } } if (((SystemTask) process.getChildren()[i]).getReturnString() != null && !((SystemTask) process.getChildren()[i]).getReturnString().trim().equals("")) { String r = ((SystemTask) process.getChildren()[i]).getReturnString(); String[] s = r.split("@"); if (s.length > 0) { ((SystemTask) process.getChildren()[i]) .setReturnObject((DataVariable) process.seekChildByID(s[0])); if (((SystemTask) process.getChildren()[i]).getReturnObject() == null) { DataVariable dv = new DataVariable(); dv.setDatatype(s[1]); if (s[1] == "File" || s[1] == "file") { dv.setValue(new FileConstant()); } else { dv.setValue(new StringConstant()); } ((SystemTask) process.getChildren()[i]).setReturnObject(dv); } if (s.length > 2) { ((SystemTask) process.getChildren()[i]).setDescription(s[2]); } } } } } else if (process.getChildren()[i] instanceof WaitTask) { if (((WaitTask) process.getChildren()[i]).getTimeRule() != null && !((WaitTask) process.getChildren()[i]).getTimeRule().equals("")) { Expression r = new Expression(); r.setExpressionString((String) ((WaitTask) process.getChildren()[i]).getTimeRule()); r.parseExpressionString(process); ((WaitTask) process.getChildren()[i]).setTimeRule(r); } } else if (process.getChildren()[i] instanceof AssignTask) { // configure assignment variables if ((process.getChildren()[i]).getChildren() != null) for (int j = 0; j < ((AssignTask) (process.getChildren()[i])).getAssignments().length; j++) { Assignment a = (Assignment) ((AssignTask) (process.getChildren()[i])).getAssignments()[j]; String variable = a.getVariableString(); if (variable != null) { String[] varary = variable.split("@"); if (varary.length > 0) { String id = varary[0]; WorkflowEntity entity = process.seekByID(id); a.setVariable((DataVariable) entity); } } if (a != null && a.getValue() != null) { Expression r = new Expression(); r.setExpressionString((String) a.getValue()); r.parseExpressionString(process); a.setValue(r); } } } else if (process.getChildren()[i] instanceof SubprocessPoint) { for (int j = 0; j < ((SubprocessPoint) process.getChildren()[i]).getSubprocessInputs().length; j++) { Assignment a = (Assignment) ((SubprocessPoint) process.getChildren()[i]).getSubprocessInputs()[j]; if (a.getValue() != null) { Expression r = new Expression(); r.setExpressionString((String) a.getValue()); r.parseExpressionString(process); a.setValue(r); } } for (int j = 0; j < ((SubprocessPoint) process.getChildren()[i]).getSubprocessOutputs().length; j++) { Assignment a = (Assignment) ((SubprocessPoint) process.getChildren()[i]).getSubprocessOutputs()[j]; String varID = a.getVariableString(); varID = varID.substring(0, varID.indexOf("@")); a.setVariable((DataVariable) process.seekByID(varID)); } } else if (process.getChildren()[i] instanceof EmailSendingTask) { if (((EmailSendingTask) process.getChildren()[i]).getVariables() != null) { DataVariable[] dvariables = new DataVariable[((EmailSendingTask) (process.getChildren()[i])) .getVariables().length]; for (int j = 0; j < ((EmailSendingTask) (process.getChildren()[i])).getVariables().length; j++) { dvariables[j] = (DataVariable) process .seekByID((String) ((EmailSendingTask) (process.getChildren()[i])).getVariables()[j]); } ((EmailSendingTask) process.getChildren()[i]).setVariables(dvariables); } } } for (int i = 0; i < process.getChildren().length; i++) { if (process.getChildren()[i] instanceof AbstractTask) { for (Transition t : ((AbstractTask) process.getChildren()[i]).getOutputs()) { if (t != null && t.getNavigationRule() != null) { Expression e = new Expression(); if (t.getNavigationRule() instanceof String) { e.setExpressionString((String) t.getNavigationRule()); e.parseExpressionString(process); t.setNavigationRule(e); } else { t.setNavigationRule(t.getNavigationRule()); } } } } } return process; } }
apache-2.0
m-m-m/code
api/src/main/java/net/sf/mmm/code/api/expression/CodeVariable.java
932
/* Copyright (c) The m-m-m Team, Licensed under the Apache License, Version 2.0 * http://www.apache.org/licenses/LICENSE-2.0 */ package net.sf.mmm.code.api.expression; import java.io.IOException; import net.sf.mmm.code.api.item.CodeItemWithDeclaration; import net.sf.mmm.code.api.item.CodeItemWithName; import net.sf.mmm.code.api.item.CodeItemWithType; /** * {@link CodeExpression} for a variable (local variable, {@link net.sf.mmm.code.api.arg.CodeParameter parameter}, * {@link net.sf.mmm.code.api.member.CodeField field}). * * @author Joerg Hohwiller (hohwille at users.sourceforge.net) * @since 1.0.0 */ public abstract interface CodeVariable extends CodeExpression, CodeItemWithName, CodeItemWithType, CodeItemWithDeclaration { @Override default void writeReference(Appendable sink, boolean declaration, Boolean qualified) throws IOException { getType().writeReference(sink, declaration, qualified); } }
apache-2.0
marques-work/gocd
config/config-api/src/test/java/com/thoughtworks/go/config/AdminUserTest.java
1242
/* * Copyright 2021 ThoughtWorks, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.thoughtworks.go.config; import org.junit.Test; import static org.hamcrest.Matchers.is; import static org.junit.Assert.*; public class AdminUserTest { @Test public void shouldNotValidateBlankUsers() { AdminUser adminUser = new AdminUser(""); adminUser.validate(null); assertThat(adminUser.errors().on(AdminUser.NAME), is("User cannot be blank.")); } @Test public void shouldValidateNonBlankUsers() { AdminUser adminUser = new AdminUser(new CaseInsensitiveString("foo")); adminUser.validate(null); assertNull(adminUser.errors().on(AdminUser.NAME)); } }
apache-2.0