repo_name
stringlengths
5
108
path
stringlengths
6
333
size
stringlengths
1
6
content
stringlengths
4
977k
license
stringclasses
15 values
sboehm85/gbf
gbf-service/src/main/java/org/sboehm/gbf/common/AbstractMapper.java
573
package org.sboehm.gbf.common; import java.util.Collection; import java.util.function.Function; public abstract class AbstractMapper<BO extends BusinessObject, TO extends TransferObject> implements Mapper<BO, TO> { protected <PBO, PTO> void mapSomeProperties(Collection<PBO> propertiesFromBusinessObject, Collection<PTO> propertiesFromTransferObject, Function<PBO, PTO> propertyMapper) { propertiesFromBusinessObject // .stream() // .map(propertyMapper) // .forEach(propertiesFromTransferObject::add); } }
apache-2.0
lessthanoptimal/ejml
main/ejml-ddense/test/org/ejml/dense/row/TestCovarianceOps_DDRM.java
1893
/* * Copyright (c) 2021, Peter Abeles. All Rights Reserved. * * This file is part of Efficient Java Matrix Library (EJML). * * 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.ejml.dense.row; import org.ejml.EjmlStandardJUnit; import org.ejml.UtilEjml; import org.ejml.data.DMatrixRMaj; import org.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assertions.assertEquals; /** * @author Peter Abeles */ public class TestCovarianceOps_DDRM extends EjmlStandardJUnit { @Test public void invert_1x1() { DMatrixRMaj m = new DMatrixRMaj(1,1); m.set(0,0,2); DMatrixRMaj n = new DMatrixRMaj(1,1); CovarianceOps_DDRM.invert(m,n); assertEquals(0.5,n.get(0,0), UtilEjml.TEST_F64); } @Test public void isValid() { // nothing is wrong with it DMatrixRMaj m = CommonOps_DDRM.identity(3); assertEquals(0, CovarianceOps_DDRM.isValid(m)); // negative diagonal term m.set(1,1,-3); assertEquals(1, CovarianceOps_DDRM.isValid(m)); // not symetric m = CommonOps_DDRM.identity(3); m.set(1,0,30); assertEquals(2, CovarianceOps_DDRM.isValid(m)); // not positive definite m = CommonOps_DDRM.identity(3); m.set(1,2,-400); m.set(2,1,-400); assertEquals(3, CovarianceOps_DDRM.isValid(m)); } }
apache-2.0
jior/glaf
workspace/glaf-base/src/main/java/com/glaf/base/modules/sys/form/GenericFormBean.java
1010
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.glaf.base.modules.sys.form; public class GenericFormBean { private String name; public String getName() { return name; } public void setName(String name) { this.name = name; } }
apache-2.0
EvilMcJerkface/Aeron
aeron-cluster/src/test/java/io/aeron/cluster/TestNode.java
15055
/* * Copyright 2014-2020 Real Logic Limited. * * 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 io.aeron.cluster; import io.aeron.Counter; import io.aeron.ExclusivePublication; import io.aeron.Image; import io.aeron.archive.Archive; import io.aeron.archive.client.AeronArchive; import io.aeron.archive.status.RecordingPos; import io.aeron.cluster.codecs.CloseReason; import io.aeron.cluster.service.ClientSession; import io.aeron.cluster.service.Cluster; import io.aeron.cluster.service.ClusteredServiceContainer; import io.aeron.driver.MediaDriver; import io.aeron.driver.status.SystemCounterDescriptor; import io.aeron.logbuffer.FragmentHandler; import io.aeron.logbuffer.Header; import io.aeron.test.DataCollector; import org.agrona.CloseHelper; import org.agrona.DirectBuffer; import org.agrona.LangUtil; import org.agrona.concurrent.AgentTerminationException; import org.agrona.concurrent.UnsafeBuffer; import org.agrona.concurrent.status.CountersReader; import java.io.File; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicBoolean; import static io.aeron.Aeron.NULL_VALUE; import static io.aeron.archive.client.AeronArchive.NULL_POSITION; import static org.agrona.BitUtil.SIZE_OF_INT; import static org.junit.jupiter.api.Assertions.fail; class TestNode implements AutoCloseable { private final ClusteredMediaDriver clusteredMediaDriver; private final ClusteredServiceContainer container; private final TestService service; private final Context context; private boolean isClosed = false; TestNode(final Context context, final DataCollector dataCollector) { clusteredMediaDriver = ClusteredMediaDriver.launch( context.mediaDriverContext, context.archiveContext, context.consensusModuleContext .terminationHook(ClusterTests.dynamicTerminationHook( context.terminationExpected, context.memberWasTerminated))); container = ClusteredServiceContainer.launch( context.serviceContainerContext .terminationHook(ClusterTests.dynamicTerminationHook( context.terminationExpected, context.serviceWasTerminated))); service = context.service; this.context = context; dataCollector.add(container.context().clusterDir().toPath()); dataCollector.add(clusteredMediaDriver.consensusModule().context().clusterDir().toPath()); dataCollector.add(clusteredMediaDriver.archive().context().archiveDir().toPath()); dataCollector.add(clusteredMediaDriver.mediaDriver().context().aeronDirectory().toPath()); } ConsensusModule consensusModule() { return clusteredMediaDriver.consensusModule(); } ClusteredServiceContainer container() { return container; } TestService service() { return service; } public void close() { if (!isClosed) { isClosed = true; CloseHelper.closeAll(clusteredMediaDriver.consensusModule(), container, clusteredMediaDriver); } } void closeAndDelete() { Throwable error = null; try { if (!isClosed) { close(); } } catch (final Throwable t) { error = t; } try { if (null != container) { container.context().deleteDirectory(); } } catch (final Throwable t) { if (error == null) { error = t; } else { error.addSuppressed(t); } } try { if (null != clusteredMediaDriver) { clusteredMediaDriver.consensusModule().context().deleteDirectory(); clusteredMediaDriver.archive().context().deleteDirectory(); clusteredMediaDriver.mediaDriver().context().deleteDirectory(); } } catch (final Throwable t) { if (error == null) { error = t; } else { error.addSuppressed(t); } } if (null != error) { LangUtil.rethrowUnchecked(error); } } boolean isClosed() { return isClosed; } Cluster.Role role() { final Counter counter = clusteredMediaDriver.consensusModule().context().clusterNodeRoleCounter(); if (counter.isClosed()) { return Cluster.Role.FOLLOWER; } return Cluster.Role.get(counter); } ElectionState electionState() { final Counter counter = clusteredMediaDriver.consensusModule().context().electionStateCounter(); if (counter.isClosed()) { return ElectionState.CLOSED; } return ElectionState.get(counter); } ConsensusModule.State moduleState() { final Counter counter = clusteredMediaDriver.consensusModule().context().moduleStateCounter(); if (counter.isClosed()) { return ConsensusModule.State.CLOSED; } return ConsensusModule.State.get(counter); } long commitPosition() { final Counter counter = clusteredMediaDriver.consensusModule().context().commitPositionCounter(); if (counter.isClosed()) { return NULL_POSITION; } return counter.get(); } long appendPosition() { final long recordingId = consensusModule().context().recordingLog().findLastTermRecordingId(); if (RecordingPos.NULL_RECORDING_ID == recordingId) { fail("no recording for last term"); } final CountersReader countersReader = countersReader(); final int counterId = RecordingPos.findCounterIdByRecording(countersReader, recordingId); if (NULL_VALUE == counterId) { fail("recording not active " + recordingId); } return countersReader.getCounterValue(counterId); } boolean isLeader() { return role() == Cluster.Role.LEADER && moduleState() != ConsensusModule.State.CLOSED; } boolean isFollower() { return role() == Cluster.Role.FOLLOWER; } void terminationExpected(final boolean terminationExpected) { context.terminationExpected.set(terminationExpected); } boolean hasServiceTerminated() { return context.serviceWasTerminated.get(); } boolean hasMemberTerminated() { return context.memberWasTerminated.get(); } int index() { return service.index(); } CountersReader countersReader() { return clusteredMediaDriver.mediaDriver().context().countersManager(); } long errors() { return countersReader().getCounterValue(SystemCounterDescriptor.ERRORS.id()); } ClusterTool.ClusterMembership clusterMembership() { final ClusterTool.ClusterMembership clusterMembership = new ClusterTool.ClusterMembership(); final File clusterDir = clusteredMediaDriver.consensusModule().context().clusterDir(); if (!ClusterTool.listMembers(clusterMembership, clusterDir, TimeUnit.SECONDS.toMillis(3))) { throw new IllegalStateException("timeout waiting for cluster members info"); } return clusterMembership; } void removeMember(final int followerMemberId, final boolean isPassive) { final File clusterDir = clusteredMediaDriver.consensusModule().context().clusterDir(); if (!ClusterTool.removeMember(clusterDir, followerMemberId, isPassive)) { throw new IllegalStateException("could not remove member"); } } @SuppressWarnings("NonAtomicOperationOnVolatileField") static class TestService extends StubClusteredService { static final int SNAPSHOT_FRAGMENT_COUNT = 500; static final int SNAPSHOT_MSG_LENGTH = 1000; private int index; private volatile int activeSessionCount; private volatile int messageCount; private volatile boolean wasSnapshotTaken = false; private volatile boolean wasSnapshotLoaded = false; private volatile boolean hasReceivedUnexpectedMessage = false; private volatile Cluster.Role roleChangedTo = null; TestService index(final int index) { this.index = index; return this; } int index() { return index; } int activeSessionCount() { return activeSessionCount; } int messageCount() { return messageCount; } boolean wasSnapshotTaken() { return wasSnapshotTaken; } void resetSnapshotTaken() { wasSnapshotTaken = false; } boolean wasSnapshotLoaded() { return wasSnapshotLoaded; } Cluster.Role roleChangedTo() { return roleChangedTo; } Cluster cluster() { return cluster; } boolean hasReceivedUnexpectedMessage() { return hasReceivedUnexpectedMessage; } public void onStart(final Cluster cluster, final Image snapshotImage) { super.onStart(cluster, snapshotImage); if (null != snapshotImage) { activeSessionCount = cluster.clientSessions().size(); final FragmentHandler handler = (buffer, offset, length, header) -> messageCount = buffer.getInt(offset); int fragmentCount = 0; while (true) { final int fragments = snapshotImage.poll(handler, 10); fragmentCount += fragments; if (snapshotImage.isClosed() || snapshotImage.isEndOfStream()) { break; } idleStrategy.idle(fragments); } if (fragmentCount != SNAPSHOT_FRAGMENT_COUNT) { throw new AgentTerminationException( "unexpected snapshot length: expected=" + SNAPSHOT_FRAGMENT_COUNT + " actual=" + fragmentCount); } wasSnapshotLoaded = true; } } public void onSessionMessage( final ClientSession session, final long timestamp, final DirectBuffer buffer, final int offset, final int length, final Header header) { final String message = buffer.getStringWithoutLengthAscii(offset, length); if (message.equals(ClusterTests.REGISTER_TIMER_MSG)) { while (!cluster.scheduleTimer(1, cluster.time() + 1_000)) { idleStrategy.idle(); } } if (message.equals(ClusterTests.UNEXPECTED_MSG)) { hasReceivedUnexpectedMessage = true; throw new IllegalStateException("unexpected message received"); } if (message.equals(ClusterTests.ECHO_IPC_INGRESS_MSG)) { if (null != session) { while (cluster.offer(buffer, offset, length) < 0) { idleStrategy.idle(); } } else { for (final ClientSession clientSession : cluster.clientSessions()) { while (clientSession.offer(buffer, offset, length) < 0) { idleStrategy.idle(); } } } } else { if (null != session) { while (session.offer(buffer, offset, length) < 0) { idleStrategy.idle(); } } } ++messageCount; } public void onTakeSnapshot(final ExclusivePublication snapshotPublication) { final UnsafeBuffer buffer = new UnsafeBuffer(new byte[SNAPSHOT_MSG_LENGTH]); buffer.putInt(0, messageCount); buffer.putInt(SNAPSHOT_MSG_LENGTH - SIZE_OF_INT, messageCount); for (int i = 0; i < SNAPSHOT_FRAGMENT_COUNT; i++) { idleStrategy.reset(); while (snapshotPublication.offer(buffer, 0, SNAPSHOT_MSG_LENGTH) <= 0) { idleStrategy.idle(); } } wasSnapshotTaken = true; } public void onSessionOpen(final ClientSession session, final long timestamp) { super.onSessionOpen(session, timestamp); activeSessionCount += 1; } public void onSessionClose(final ClientSession session, final long timestamp, final CloseReason closeReason) { super.onSessionClose(session, timestamp, closeReason); activeSessionCount -= 1; } public void onRoleChange(final Cluster.Role newRole) { roleChangedTo = newRole; } } static class Context { final MediaDriver.Context mediaDriverContext = new MediaDriver.Context(); final Archive.Context archiveContext = new Archive.Context(); final AeronArchive.Context aeronArchiveContext = new AeronArchive.Context(); final ConsensusModule.Context consensusModuleContext = new ConsensusModule.Context(); final ClusteredServiceContainer.Context serviceContainerContext = new ClusteredServiceContainer.Context(); final AtomicBoolean terminationExpected = new AtomicBoolean(false); final AtomicBoolean memberWasTerminated = new AtomicBoolean(false); final AtomicBoolean serviceWasTerminated = new AtomicBoolean(false); final TestService service; Context(final TestService service) { this.service = service; } } }
apache-2.0
dagnir/aws-sdk-java
aws-java-sdk-rekognition/src/main/java/com/amazonaws/services/rekognition/model/IndexFacesResult.java
13322
/* * Copyright 2012-2017 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with * the License. A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR * CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions * and limitations under the License. */ package com.amazonaws.services.rekognition.model; import java.io.Serializable; import javax.annotation.Generated; @Generated("com.amazonaws:aws-java-sdk-code-generator") public class IndexFacesResult extends com.amazonaws.AmazonWebServiceResult<com.amazonaws.ResponseMetadata> implements Serializable, Cloneable { /** * <p> * An array of faces detected and added to the collection. For more information, see <a>howitworks-index-faces</a>. * </p> */ private java.util.List<FaceRecord> faceRecords; /** * <p> * The algorithm detects the image orientation. If it detects that the image was rotated, it returns the degree of * rotation. You can use this value to correct the orientation and also appropriately analyze the bounding box * coordinates that are returned. * </p> * <note> * <p> * If the source image Exif metadata populates the orientation field, Amazon Rekognition does not perform * orientation correction and the value of OrientationCorrection will be nil. * </p> * </note> */ private String orientationCorrection; /** * <p> * An array of faces detected and added to the collection. For more information, see <a>howitworks-index-faces</a>. * </p> * * @return An array of faces detected and added to the collection. For more information, see * <a>howitworks-index-faces</a>. */ public java.util.List<FaceRecord> getFaceRecords() { return faceRecords; } /** * <p> * An array of faces detected and added to the collection. For more information, see <a>howitworks-index-faces</a>. * </p> * * @param faceRecords * An array of faces detected and added to the collection. For more information, see * <a>howitworks-index-faces</a>. */ public void setFaceRecords(java.util.Collection<FaceRecord> faceRecords) { if (faceRecords == null) { this.faceRecords = null; return; } this.faceRecords = new java.util.ArrayList<FaceRecord>(faceRecords); } /** * <p> * An array of faces detected and added to the collection. For more information, see <a>howitworks-index-faces</a>. * </p> * <p> * <b>NOTE:</b> This method appends the values to the existing list (if any). Use * {@link #setFaceRecords(java.util.Collection)} or {@link #withFaceRecords(java.util.Collection)} if you want to * override the existing values. * </p> * * @param faceRecords * An array of faces detected and added to the collection. For more information, see * <a>howitworks-index-faces</a>. * @return Returns a reference to this object so that method calls can be chained together. */ public IndexFacesResult withFaceRecords(FaceRecord... faceRecords) { if (this.faceRecords == null) { setFaceRecords(new java.util.ArrayList<FaceRecord>(faceRecords.length)); } for (FaceRecord ele : faceRecords) { this.faceRecords.add(ele); } return this; } /** * <p> * An array of faces detected and added to the collection. For more information, see <a>howitworks-index-faces</a>. * </p> * * @param faceRecords * An array of faces detected and added to the collection. For more information, see * <a>howitworks-index-faces</a>. * @return Returns a reference to this object so that method calls can be chained together. */ public IndexFacesResult withFaceRecords(java.util.Collection<FaceRecord> faceRecords) { setFaceRecords(faceRecords); return this; } /** * <p> * The algorithm detects the image orientation. If it detects that the image was rotated, it returns the degree of * rotation. You can use this value to correct the orientation and also appropriately analyze the bounding box * coordinates that are returned. * </p> * <note> * <p> * If the source image Exif metadata populates the orientation field, Amazon Rekognition does not perform * orientation correction and the value of OrientationCorrection will be nil. * </p> * </note> * * @param orientationCorrection * The algorithm detects the image orientation. If it detects that the image was rotated, it returns the * degree of rotation. You can use this value to correct the orientation and also appropriately analyze the * bounding box coordinates that are returned. </p> <note> * <p> * If the source image Exif metadata populates the orientation field, Amazon Rekognition does not perform * orientation correction and the value of OrientationCorrection will be nil. * </p> * @see OrientationCorrection */ public void setOrientationCorrection(String orientationCorrection) { this.orientationCorrection = orientationCorrection; } /** * <p> * The algorithm detects the image orientation. If it detects that the image was rotated, it returns the degree of * rotation. You can use this value to correct the orientation and also appropriately analyze the bounding box * coordinates that are returned. * </p> * <note> * <p> * If the source image Exif metadata populates the orientation field, Amazon Rekognition does not perform * orientation correction and the value of OrientationCorrection will be nil. * </p> * </note> * * @return The algorithm detects the image orientation. If it detects that the image was rotated, it returns the * degree of rotation. You can use this value to correct the orientation and also appropriately analyze the * bounding box coordinates that are returned. </p> <note> * <p> * If the source image Exif metadata populates the orientation field, Amazon Rekognition does not perform * orientation correction and the value of OrientationCorrection will be nil. * </p> * @see OrientationCorrection */ public String getOrientationCorrection() { return this.orientationCorrection; } /** * <p> * The algorithm detects the image orientation. If it detects that the image was rotated, it returns the degree of * rotation. You can use this value to correct the orientation and also appropriately analyze the bounding box * coordinates that are returned. * </p> * <note> * <p> * If the source image Exif metadata populates the orientation field, Amazon Rekognition does not perform * orientation correction and the value of OrientationCorrection will be nil. * </p> * </note> * * @param orientationCorrection * The algorithm detects the image orientation. If it detects that the image was rotated, it returns the * degree of rotation. You can use this value to correct the orientation and also appropriately analyze the * bounding box coordinates that are returned. </p> <note> * <p> * If the source image Exif metadata populates the orientation field, Amazon Rekognition does not perform * orientation correction and the value of OrientationCorrection will be nil. * </p> * @return Returns a reference to this object so that method calls can be chained together. * @see OrientationCorrection */ public IndexFacesResult withOrientationCorrection(String orientationCorrection) { setOrientationCorrection(orientationCorrection); return this; } /** * <p> * The algorithm detects the image orientation. If it detects that the image was rotated, it returns the degree of * rotation. You can use this value to correct the orientation and also appropriately analyze the bounding box * coordinates that are returned. * </p> * <note> * <p> * If the source image Exif metadata populates the orientation field, Amazon Rekognition does not perform * orientation correction and the value of OrientationCorrection will be nil. * </p> * </note> * * @param orientationCorrection * The algorithm detects the image orientation. If it detects that the image was rotated, it returns the * degree of rotation. You can use this value to correct the orientation and also appropriately analyze the * bounding box coordinates that are returned. </p> <note> * <p> * If the source image Exif metadata populates the orientation field, Amazon Rekognition does not perform * orientation correction and the value of OrientationCorrection will be nil. * </p> * @see OrientationCorrection */ public void setOrientationCorrection(OrientationCorrection orientationCorrection) { this.orientationCorrection = orientationCorrection.toString(); } /** * <p> * The algorithm detects the image orientation. If it detects that the image was rotated, it returns the degree of * rotation. You can use this value to correct the orientation and also appropriately analyze the bounding box * coordinates that are returned. * </p> * <note> * <p> * If the source image Exif metadata populates the orientation field, Amazon Rekognition does not perform * orientation correction and the value of OrientationCorrection will be nil. * </p> * </note> * * @param orientationCorrection * The algorithm detects the image orientation. If it detects that the image was rotated, it returns the * degree of rotation. You can use this value to correct the orientation and also appropriately analyze the * bounding box coordinates that are returned. </p> <note> * <p> * If the source image Exif metadata populates the orientation field, Amazon Rekognition does not perform * orientation correction and the value of OrientationCorrection will be nil. * </p> * @return Returns a reference to this object so that method calls can be chained together. * @see OrientationCorrection */ public IndexFacesResult withOrientationCorrection(OrientationCorrection orientationCorrection) { setOrientationCorrection(orientationCorrection); return this; } /** * Returns a string representation of this object; useful for testing and debugging. * * @return A string representation of this object. * * @see java.lang.Object#toString() */ @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("{"); if (getFaceRecords() != null) sb.append("FaceRecords: ").append(getFaceRecords()).append(","); if (getOrientationCorrection() != null) sb.append("OrientationCorrection: ").append(getOrientationCorrection()); sb.append("}"); return sb.toString(); } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (obj instanceof IndexFacesResult == false) return false; IndexFacesResult other = (IndexFacesResult) obj; if (other.getFaceRecords() == null ^ this.getFaceRecords() == null) return false; if (other.getFaceRecords() != null && other.getFaceRecords().equals(this.getFaceRecords()) == false) return false; if (other.getOrientationCorrection() == null ^ this.getOrientationCorrection() == null) return false; if (other.getOrientationCorrection() != null && other.getOrientationCorrection().equals(this.getOrientationCorrection()) == false) return false; return true; } @Override public int hashCode() { final int prime = 31; int hashCode = 1; hashCode = prime * hashCode + ((getFaceRecords() == null) ? 0 : getFaceRecords().hashCode()); hashCode = prime * hashCode + ((getOrientationCorrection() == null) ? 0 : getOrientationCorrection().hashCode()); return hashCode; } @Override public IndexFacesResult clone() { try { return (IndexFacesResult) super.clone(); } catch (CloneNotSupportedException e) { throw new IllegalStateException("Got a CloneNotSupportedException from Object.clone() " + "even though we're Cloneable!", e); } } }
apache-2.0
pollseed/machine-learning
src/main/java/jp/com/pollseed/mahout/wrapper/user/AbstractUser.java
514
package jp.com.pollseed.mahout.wrapper.user; import jp.com.pollseed.mahout.wrapper.common.AbstractAnalyzer; import org.apache.mahout.cf.taste.model.DataModel; abstract class AbstractUser extends AbstractAnalyzer { protected final UserItemVO dto; protected AbstractUser(DataModel dataModel, UserItemVO dto) { super(dataModel); if (dto == null || dto.userMap == null || dto.userMap.isEmpty()) { throw new IllegalArgumentException(); } this.dto = dto; } }
apache-2.0
shiver-me-timbers/smt-http-mock-parent
smt-http-mock-tomcat-parent/smt-http-mock-tomcat-common/src/main/java/shiver/me/timbers/http/servlet/tomcat/TomcatContainer.java
3496
/* * Copyright 2016 Karl Bennett * * 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 shiver.me.timbers.http.servlet.tomcat; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.slf4j.bridge.SLF4JBridgeHandler; import shiver.me.timbers.http.Container; import shiver.me.timbers.http.Service; import shiver.me.timbers.http.servlet.ServiceToServletConverter; import java.util.concurrent.Callable; /** * @author Karl Bennett */ class TomcatContainer<H, J, E extends Exception> implements Container { static final String TEMP_DIR = ".tomcat_mock"; static { // Override the normal Tomcat Juli logging with slf4j. SLF4JBridgeHandler.removeHandlersForRootLogger(); SLF4JBridgeHandler.install(); } private final Logger log = LoggerFactory.getLogger(getClass()); private final CommonTomcat<H, J, E> tomcat; private final ServiceToServletConverter converter; private final CommonContext context; private final FileCleaner fileCleaner; private final String tempDir; TomcatContainer( TomcatConfigurer<H, J, E> configurer, CommonTomcat<H, J, E> tomcat, ServiceToServletConverter converter, String tempDir ) { this(tomcat, converter, configurer.configure(tomcat, tempDir), new FileCleaner(), tempDir); } TomcatContainer( CommonTomcat<H, J, E> tomcat, ServiceToServletConverter converter, CommonContext<J> context, FileCleaner fileCleaner, String tempDir ) { this.tomcat = tomcat; this.converter = converter; this.context = context; this.fileCleaner = fileCleaner; this.tempDir = tempDir; } @Override public void register(Service service) { tomcat.addServlet(context.getPath(), service.getName(), converter.convert(service)) .addMapping(service.getPath()); log.info( "Service ({}) registered with name ({}) and mapped to path ({}).", service.getClass().getName(), service.getName(), service.getPath() ); } @Override public void start() { withinLifecycle(new Callable<Void>() { @Override public Void call() throws Exception { tomcat.start(); return null; } }); } @Override public int getPort() { return tomcat.getConnector().getLocalPort(); } @Override public void stop() { withinLifecycle(new Callable<Void>() { @Override public Void call() throws Exception { tomcat.stop(); fileCleaner.cleanUp(tempDir); return null; } }); } private static void withinLifecycle(Callable<Void> callable) { try { callable.call(); } catch (Exception e) { throw new IllegalStateException(e); } } }
apache-2.0
KimuraTakaumi/digdag
digdag-spi/src/main/java/io/digdag/spi/Scheduler.java
648
package io.digdag.spi; import java.time.Instant; import java.time.ZoneId; public interface Scheduler { ZoneId getTimeZone(); // align this time with the last schedule time. // returned value is same with currentTime or after currentTime. ScheduleTime getFirstScheduleTime(Instant currentTime); // align this time with the next schedule time. // returned value is after lastScheduleTime. ScheduleTime nextScheduleTime(Instant lastScheduleTime); // align this time with the last schedule time. // returned value is before currentScheduleTime. ScheduleTime lastScheduleTime(Instant currentScheduleTime); }
apache-2.0
e-biz/dma-template-sample
native-android-sources/app/src/main/java/mobi/designmyapp/template/sample/ods/util/StreamUtils.java
1686
/* Copyright 2014 eBusiness Information 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 mobi.designmyapp.template.sample.ods.util; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; /** * StreamUtils class providing Stream to X converters * */ public class StreamUtils { /** * Converts a java.io.InputStream to a java.lang.String object * @throws java.lang.IllegalStateException if an error occurs while reading the stream or closing the reader * @param is * @return the String representation of the provided InputStream */ public static String inputStreamToString(InputStream is) { String line = ""; StringBuilder builder = new StringBuilder(); BufferedReader rd = new BufferedReader(new InputStreamReader(is)); try { while ((line = rd.readLine()) != null) { builder.append(line); } } catch (IOException e) { throw new IllegalStateException(e); } finally { try { if(rd != null) rd.close(); } catch (IOException e) { throw new IllegalStateException(e); } } return builder.toString(); } }
apache-2.0
al-t/sunshine
app/src/androidTest/java/ru/javabreeze/android/sunshine/app/data/TestProvider.java
24557
package ru.javabreeze.android.sunshine.app.data; /** * Created by Алексей on 04.09.2016. */ import android.content.ComponentName; import android.content.ContentUris; import android.content.ContentValues; import android.content.pm.PackageManager; import android.content.pm.ProviderInfo; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import android.net.Uri; import android.os.Build; import android.test.AndroidTestCase; import android.util.Log; import ru.javabreeze.android.sunshine.app.data.WeatherContract.LocationEntry; import ru.javabreeze.android.sunshine.app.data.WeatherContract.WeatherEntry; /* Note: This is not a complete set of tests of the Sunshine ContentProvider, but it does test that at least the basic functionality has been implemented correctly. Students: Uncomment the tests in this class as you implement the functionality in your ContentProvider to make sure that you've implemented things reasonably correctly. */ public class TestProvider extends AndroidTestCase { public static final String LOG_TAG = TestProvider.class.getSimpleName(); /* This helper function deletes all records from both database tables using the ContentProvider. It also queries the ContentProvider to make sure that the database has been successfully deleted, so it cannot be used until the Query and Delete functions have been written in the ContentProvider. Students: Replace the calls to deleteAllRecordsFromDB with this one after you have written the delete functionality in the ContentProvider. */ public void deleteAllRecordsFromProvider() { mContext.getContentResolver().delete( WeatherEntry.CONTENT_URI, null, null ); mContext.getContentResolver().delete( LocationEntry.CONTENT_URI, null, null ); Cursor cursor = mContext.getContentResolver().query( WeatherEntry.CONTENT_URI, null, null, null, null ); assertEquals("Error: Records not deleted from Weather table during delete", 0, cursor.getCount()); cursor.close(); cursor = mContext.getContentResolver().query( LocationEntry.CONTENT_URI, null, null, null, null ); assertEquals("Error: Records not deleted from Location table during delete", 0, cursor.getCount()); cursor.close(); } /* This helper function deletes all records from both database tables using the database functions only. This is designed to be used to reset the state of the database until the delete functionality is available in the ContentProvider. */ public void deleteAllRecordsFromDB() { WeatherDbHelper dbHelper = new WeatherDbHelper(mContext); SQLiteDatabase db = dbHelper.getWritableDatabase(); db.delete(WeatherEntry.TABLE_NAME, null, null); db.delete(LocationEntry.TABLE_NAME, null, null); db.close(); } /* Student: Refactor this function to use the deleteAllRecordsFromProvider functionality once you have implemented delete functionality there. */ public void deleteAllRecords() { deleteAllRecordsFromProvider(); } // Since we want each test to start with a clean slate, run deleteAllRecords // in setUp (called by the test runner before each test). @Override protected void setUp() throws Exception { super.setUp(); deleteAllRecords(); } /* This test checks to make sure that the content provider is registered correctly. Students: Uncomment this test to make sure you've correctly registered the WeatherProvider. */ public void testProviderRegistry() { PackageManager pm = mContext.getPackageManager(); // We define the component name based on the package name from the context and the // WeatherProvider class. ComponentName componentName = new ComponentName(mContext.getPackageName(), WeatherProvider.class.getName()); try { // Fetch the provider info using the component name from the PackageManager // This throws an exception if the provider isn't registered. ProviderInfo providerInfo = pm.getProviderInfo(componentName, 0); // Make sure that the registered authority matches the authority from the Contract. assertEquals("Error: WeatherProvider registered with authority: " + providerInfo.authority + " instead of authority: " + WeatherContract.CONTENT_AUTHORITY, providerInfo.authority, WeatherContract.CONTENT_AUTHORITY); } catch (PackageManager.NameNotFoundException e) { // I guess the provider isn't registered correctly. assertTrue("Error: WeatherProvider not registered at " + mContext.getPackageName(), false); } } /* This test doesn't touch the database. It verifies that the ContentProvider returns the correct type for each type of URI that it can handle. Students: Uncomment this test to verify that your implementation of GetType is functioning correctly. */ public void testGetType() { // content://com.example.android.sunshine.app/weather/ String type = mContext.getContentResolver().getType(WeatherEntry.CONTENT_URI); // vnd.android.cursor.dir/com.example.android.sunshine.app/weather assertEquals("Error: the WeatherEntry CONTENT_URI should return WeatherEntry.CONTENT_TYPE", WeatherEntry.CONTENT_TYPE, type); String testLocation = "94074"; // content://com.example.android.sunshine.app/weather/94074 type = mContext.getContentResolver().getType( WeatherEntry.buildWeatherLocation(testLocation)); // vnd.android.cursor.dir/com.example.android.sunshine.app/weather assertEquals("Error: the WeatherEntry CONTENT_URI with location should return WeatherEntry.CONTENT_TYPE", WeatherEntry.CONTENT_TYPE, type); long testDate = 1419120000L; // December 21st, 2014 // content://com.example.android.sunshine.app/weather/94074/20140612 type = mContext.getContentResolver().getType( WeatherEntry.buildWeatherLocationWithDate(testLocation, testDate)); // vnd.android.cursor.item/com.example.android.sunshine.app/weather/1419120000 assertEquals("Error: the WeatherEntry CONTENT_URI with location and date should return WeatherEntry.CONTENT_ITEM_TYPE", WeatherEntry.CONTENT_ITEM_TYPE, type); // content://com.example.android.sunshine.app/location/ type = mContext.getContentResolver().getType(LocationEntry.CONTENT_URI); // vnd.android.cursor.dir/com.example.android.sunshine.app/location assertEquals("Error: the LocationEntry CONTENT_URI should return LocationEntry.CONTENT_TYPE", LocationEntry.CONTENT_TYPE, type); } /* This test uses the database directly to insert and then uses the ContentProvider to read out the data. Uncomment this test to see if the basic weather query functionality given in the ContentProvider is working correctly. */ public void testBasicWeatherQuery() { // insert our test records into the database WeatherDbHelper dbHelper = new WeatherDbHelper(mContext); SQLiteDatabase db = dbHelper.getWritableDatabase(); ContentValues testValues = TestUtilities.createNorthPoleLocationValues(); long locationRowId = TestUtilities.insertNorthPoleLocationValues(mContext); // Fantastic. Now that we have a location, add some weather! ContentValues weatherValues = TestUtilities.createWeatherValues(locationRowId); long weatherRowId = db.insert(WeatherEntry.TABLE_NAME, null, weatherValues); assertTrue("Unable to Insert WeatherEntry into the Database", weatherRowId != -1); db.close(); // Test the basic content provider query Cursor weatherCursor = mContext.getContentResolver().query( WeatherEntry.CONTENT_URI, null, null, null, null ); // Make sure we get the correct cursor out of the database TestUtilities.validateCursor("testBasicWeatherQuery", weatherCursor, weatherValues); } /* This test uses the database directly to insert and then uses the ContentProvider to read out the data. Uncomment this test to see if your location queries are performing correctly. */ public void testBasicLocationQueries() { // insert our test records into the database WeatherDbHelper dbHelper = new WeatherDbHelper(mContext); SQLiteDatabase db = dbHelper.getWritableDatabase(); ContentValues testValues = TestUtilities.createNorthPoleLocationValues(); long locationRowId = TestUtilities.insertNorthPoleLocationValues(mContext); // Test the basic content provider query Cursor locationCursor = mContext.getContentResolver().query( LocationEntry.CONTENT_URI, null, null, null, null ); // Make sure we get the correct cursor out of the database TestUtilities.validateCursor("testBasicLocationQueries, location query", locationCursor, testValues); // Has the NotificationUri been set correctly? --- we can only test this easily against API // level 19 or greater because getNotificationUri was added in API level 19. if ( Build.VERSION.SDK_INT >= 19 ) { assertEquals("Error: Location Query did not properly set NotificationUri", locationCursor.getNotificationUri(), LocationEntry.CONTENT_URI); } } /* This test uses the provider to insert and then update the data. Uncomment this test to see if your update location is functioning correctly. */ public void testUpdateLocation() { // Create a new map of values, where column names are the keys ContentValues values = TestUtilities.createNorthPoleLocationValues(); Uri locationUri = mContext.getContentResolver(). insert(LocationEntry.CONTENT_URI, values); long locationRowId = ContentUris.parseId(locationUri); // Verify we got a row back. assertTrue(locationRowId != -1); Log.d(LOG_TAG, "New row id: " + locationRowId); ContentValues updatedValues = new ContentValues(values); updatedValues.put(LocationEntry._ID, locationRowId); updatedValues.put(LocationEntry.COLUMN_CITY_NAME, "Santa's Village"); // Create a cursor with observer to make sure that the content provider is notifying // the observers as expected Cursor locationCursor = mContext.getContentResolver().query(LocationEntry.CONTENT_URI, null, null, null, null); TestUtilities.TestContentObserver tco = TestUtilities.getTestContentObserver(); locationCursor.registerContentObserver(tco); int count = mContext.getContentResolver().update( LocationEntry.CONTENT_URI, updatedValues, LocationEntry._ID + "= ?", new String[] { Long.toString(locationRowId)}); assertEquals(count, 1); // Test to make sure our observer is called. If not, we throw an assertion. // // Students: If your code is failing here, it means that your content provider // isn't calling getContext().getContentResolver().notifyChange(uri, null); tco.waitForNotificationOrFail(); locationCursor.unregisterContentObserver(tco); locationCursor.close(); // A cursor is your primary interface to the query results. Cursor cursor = mContext.getContentResolver().query( LocationEntry.CONTENT_URI, null, // projection LocationEntry._ID + " = " + locationRowId, null, // Values for the "where" clause null // sort order ); TestUtilities.validateCursor("testUpdateLocation. Error validating location entry update.", cursor, updatedValues); cursor.close(); } // Make sure we can still delete after adding/updating stuff // // Student: Uncomment this test after you have completed writing the insert functionality // in your provider. It relies on insertions with testInsertReadProvider, so insert and // query functionality must also be complete before this test can be used. public void testInsertReadProvider() { ContentValues testValues = TestUtilities.createNorthPoleLocationValues(); // Register a content observer for our insert. This time, directly with the content resolver TestUtilities.TestContentObserver tco = TestUtilities.getTestContentObserver(); mContext.getContentResolver().registerContentObserver(LocationEntry.CONTENT_URI, true, tco); Uri locationUri = mContext.getContentResolver().insert(LocationEntry.CONTENT_URI, testValues); // Did our content observer get called? Students: If this fails, your insert location // isn't calling getContext().getContentResolver().notifyChange(uri, null); tco.waitForNotificationOrFail(); mContext.getContentResolver().unregisterContentObserver(tco); long locationRowId = ContentUris.parseId(locationUri); // Verify we got a row back. assertTrue(locationRowId != -1); // Data's inserted. IN THEORY. Now pull some out to stare at it and verify it made // the round trip. // A cursor is your primary interface to the query results. Cursor cursor = mContext.getContentResolver().query( LocationEntry.CONTENT_URI, null, // leaving "columns" null just returns all the columns. null, // cols for "where" clause null, // values for "where" clause null // sort order ); TestUtilities.validateCursor("testInsertReadProvider. Error validating LocationEntry.", cursor, testValues); // Fantastic. Now that we have a location, add some weather! ContentValues weatherValues = TestUtilities.createWeatherValues(locationRowId); // The TestContentObserver is a one-shot class tco = TestUtilities.getTestContentObserver(); mContext.getContentResolver().registerContentObserver(WeatherEntry.CONTENT_URI, true, tco); Uri weatherInsertUri = mContext.getContentResolver() .insert(WeatherEntry.CONTENT_URI, weatherValues); assertTrue(weatherInsertUri != null); // Did our content observer get called? Students: If this fails, your insert weather // in your ContentProvider isn't calling // getContext().getContentResolver().notifyChange(uri, null); tco.waitForNotificationOrFail(); mContext.getContentResolver().unregisterContentObserver(tco); // A cursor is your primary interface to the query results. Cursor weatherCursor = mContext.getContentResolver().query( WeatherEntry.CONTENT_URI, // Table to Query null, // leaving "columns" null just returns all the columns. null, // cols for "where" clause null, // values for "where" clause null // columns to group by ); TestUtilities.validateCursor("testInsertReadProvider. Error validating WeatherEntry insert.", weatherCursor, weatherValues); // Add the location values in with the weather data so that we can make // sure that the join worked and we actually get all the values back weatherValues.putAll(testValues); // Get the joined Weather and Location data weatherCursor = mContext.getContentResolver().query( WeatherEntry.buildWeatherLocation(TestUtilities.TEST_LOCATION), null, // leaving "columns" null just returns all the columns. null, // cols for "where" clause null, // values for "where" clause null // sort order ); TestUtilities.validateCursor("testInsertReadProvider. Error validating joined Weather and Location Data.", weatherCursor, weatherValues); // Get the joined Weather and Location data with a start date weatherCursor = mContext.getContentResolver().query( WeatherEntry.buildWeatherLocationWithStartDate( TestUtilities.TEST_LOCATION, TestUtilities.TEST_DATE), null, // leaving "columns" null just returns all the columns. null, // cols for "where" clause null, // values for "where" clause null // sort order ); TestUtilities.validateCursor("testInsertReadProvider. Error validating joined Weather and Location Data with start date.", weatherCursor, weatherValues); // Get the joined Weather data for a specific date weatherCursor = mContext.getContentResolver().query( WeatherEntry.buildWeatherLocationWithDate(TestUtilities.TEST_LOCATION, TestUtilities.TEST_DATE), null, null, null, null ); TestUtilities.validateCursor("testInsertReadProvider. Error validating joined Weather and Location data for a specific date.", weatherCursor, weatherValues); } // Make sure we can still delete after adding/updating stuff // // Student: Uncomment this test after you have completed writing the delete functionality // in your provider. It relies on insertions with testInsertReadProvider, so insert and // query functionality must also be complete before this test can be used. public void testDeleteRecords() { testInsertReadProvider(); // Register a content observer for our location delete. TestUtilities.TestContentObserver locationObserver = TestUtilities.getTestContentObserver(); mContext.getContentResolver().registerContentObserver(LocationEntry.CONTENT_URI, true, locationObserver); // Register a content observer for our weather delete. TestUtilities.TestContentObserver weatherObserver = TestUtilities.getTestContentObserver(); mContext.getContentResolver().registerContentObserver(WeatherEntry.CONTENT_URI, true, weatherObserver); deleteAllRecordsFromProvider(); // Students: If either of these fail, you most-likely are not calling the // getContext().getContentResolver().notifyChange(uri, null); in the ContentProvider // delete. (only if the insertReadProvider is succeeding) locationObserver.waitForNotificationOrFail(); weatherObserver.waitForNotificationOrFail(); mContext.getContentResolver().unregisterContentObserver(locationObserver); mContext.getContentResolver().unregisterContentObserver(weatherObserver); } static private final int BULK_INSERT_RECORDS_TO_INSERT = 10; static ContentValues[] createBulkInsertWeatherValues(long locationRowId) { long currentTestDate = TestUtilities.TEST_DATE; long millisecondsInADay = 1000*60*60*24; ContentValues[] returnContentValues = new ContentValues[BULK_INSERT_RECORDS_TO_INSERT]; for ( int i = 0; i < BULK_INSERT_RECORDS_TO_INSERT; i++, currentTestDate+= millisecondsInADay ) { ContentValues weatherValues = new ContentValues(); weatherValues.put(WeatherContract.WeatherEntry.COLUMN_LOC_KEY, locationRowId); weatherValues.put(WeatherContract.WeatherEntry.COLUMN_DATE, currentTestDate); weatherValues.put(WeatherContract.WeatherEntry.COLUMN_DEGREES, 1.1); weatherValues.put(WeatherContract.WeatherEntry.COLUMN_HUMIDITY, 1.2 + 0.01 * (float) i); weatherValues.put(WeatherContract.WeatherEntry.COLUMN_PRESSURE, 1.3 - 0.01 * (float) i); weatherValues.put(WeatherContract.WeatherEntry.COLUMN_MAX_TEMP, 75 + i); weatherValues.put(WeatherContract.WeatherEntry.COLUMN_MIN_TEMP, 65 - i); weatherValues.put(WeatherContract.WeatherEntry.COLUMN_SHORT_DESC, "Asteroids"); weatherValues.put(WeatherContract.WeatherEntry.COLUMN_WIND_SPEED, 5.5 + 0.2 * (float) i); weatherValues.put(WeatherContract.WeatherEntry.COLUMN_WEATHER_ID, 321); returnContentValues[i] = weatherValues; } return returnContentValues; } // Student: Uncomment this test after you have completed writing the BulkInsert functionality // in your provider. Note that this test will work with the built-in (default) provider // implementation, which just inserts records one-at-a-time, so really do implement the // BulkInsert ContentProvider function. public void testBulkInsert() { // first, let's create a location value ContentValues testValues = TestUtilities.createNorthPoleLocationValues(); Uri locationUri = mContext.getContentResolver().insert(LocationEntry.CONTENT_URI, testValues); long locationRowId = ContentUris.parseId(locationUri); // Verify we got a row back. assertTrue(locationRowId != -1); // Data's inserted. IN THEORY. Now pull some out to stare at it and verify it made // the round trip. // A cursor is your primary interface to the query results. Cursor cursor = mContext.getContentResolver().query( LocationEntry.CONTENT_URI, null, // leaving "columns" null just returns all the columns. null, // cols for "where" clause null, // values for "where" clause null // sort order ); TestUtilities.validateCursor("testBulkInsert. Error validating LocationEntry.", cursor, testValues); // Now we can bulkInsert some weather. In fact, we only implement BulkInsert for weather // entries. With ContentProviders, you really only have to implement the features you // use, after all. ContentValues[] bulkInsertContentValues = createBulkInsertWeatherValues(locationRowId); // Register a content observer for our bulk insert. TestUtilities.TestContentObserver weatherObserver = TestUtilities.getTestContentObserver(); mContext.getContentResolver().registerContentObserver(WeatherEntry.CONTENT_URI, true, weatherObserver); int insertCount = mContext.getContentResolver().bulkInsert(WeatherEntry.CONTENT_URI, bulkInsertContentValues); // Students: If this fails, it means that you most-likely are not calling the // getContext().getContentResolver().notifyChange(uri, null); in your BulkInsert // ContentProvider method. weatherObserver.waitForNotificationOrFail(); mContext.getContentResolver().unregisterContentObserver(weatherObserver); assertEquals(insertCount, BULK_INSERT_RECORDS_TO_INSERT); // A cursor is your primary interface to the query results. cursor = mContext.getContentResolver().query( WeatherEntry.CONTENT_URI, null, // leaving "columns" null just returns all the columns. null, // cols for "where" clause null, // values for "where" clause WeatherEntry.COLUMN_DATE + " ASC" // sort order == by DATE ASCENDING ); // we should have as many records in the database as we've inserted assertEquals(cursor.getCount(), BULK_INSERT_RECORDS_TO_INSERT); // and let's make sure they match the ones we created cursor.moveToFirst(); for ( int i = 0; i < BULK_INSERT_RECORDS_TO_INSERT; i++, cursor.moveToNext() ) { TestUtilities.validateCurrentRecord("testBulkInsert. Error validating WeatherEntry " + i, cursor, bulkInsertContentValues[i]); } cursor.close(); } }
apache-2.0
LucidWorks/solr-hadoop-common
solr-hadoop-io/src/test/java/com/lucidworks/hadoop/fusion/QueryPipelineClientTest.java
4002
package com.lucidworks.hadoop.fusion; import com.lucidworks.hadoop.io.LWDocument; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.apache.hadoop.mapred.Reporter; import org.apache.http.client.HttpResponseException; import org.apache.solr.common.SolrException; import org.junit.Test; import java.util.List; import static com.github.tomakehurst.wiremock.client.WireMock.aResponse; import static com.github.tomakehurst.wiremock.client.WireMock.post; import static com.github.tomakehurst.wiremock.client.WireMock.stubFor; import static com.github.tomakehurst.wiremock.client.WireMock.urlEqualTo; public class QueryPipelineClientTest extends FusionPipelineClientTest { private static final Log log = LogFactory.getLog(QueryPipelineClientTest.class); private String fusionEndpoints; private String badPathEndpoint; private String unauthPathEndpoint; private String notAnEndpoint; @Override public void setupWireMock() throws Exception { super.setupWireMock(); String badPath = "/api/apollo/query-pipelines/scottsCollection-default/collections/badCollection/index"; String unauthPath = "/api/apollo/query-pipeline/scottsCollection-default/collections/unauthCollection/index"; if (useWireMockRule) { // mock out the Pipeline API stubFor(post(urlEqualTo(fusionPipelineUrlWithoutHostAndPort)).willReturn(aResponse().withStatus(200))); // a bad node in the mix ... to test FusionPipelineClient error handling stubFor(post(urlEqualTo(badPath)).willReturn(aResponse().withStatus(500))); // another bad node in the mix which produces un-authorized errors... to test FusionPipelineClient error handling stubFor(post(urlEqualTo(unauthPath)).willReturn(aResponse().withStatus(401))); // mock out the Session API stubFor(post(urlEqualTo("/api/session?realmName=" + fusionRealm)).willReturn(aResponse().withStatus(200))); } badPathEndpoint = "http://localhost:" + wireMockRulePort + badPath; unauthPathEndpoint = "http://localhost:" + wireMockRulePort + unauthPath; notAnEndpoint = "http://localhost:" + wireMockRulePort + "/not_an_endpoint/api"; fusionEndpoints = useWireMockRule ? fusionUrl + "," + notAnEndpoint + "," + badPathEndpoint + "," + unauthPathEndpoint : fusionUrl; } @Test(expected = UnsupportedOperationException.class) public void testPostBatchToPipeline() throws Exception { final QueryPipelineClient pipelineClient = new QueryPipelineClient(Reporter.NULL, fusionEndpoints, fusionUser, fusionPass, fusionRealm, null); pipelineClient.postBatchToPipeline(buildDocs(1)); } @Test(expected = UnsupportedOperationException.class) public void testGetBatchMultipleEndpoints() throws Exception { final QueryPipelineClient pipelineClient = new QueryPipelineClient(Reporter.NULL, fusionEndpoints, fusionUser, fusionPass, fusionRealm, null); pipelineClient.getBatchFromStartPointWithRetry(0, 100); } @Test(expected = HttpResponseException.class) public void testGetBatchBadEndpoint() throws Exception { final QueryPipelineClient pipelineClient = new QueryPipelineClient(Reporter.NULL, badPathEndpoint, fusionUser, fusionPass, fusionRealm, null); pipelineClient.getBatchFromStartPointWithRetry(0, 100); } @Test(expected = HttpResponseException.class) public void testGetBatchUnauthPathEndpoint() throws Exception { final QueryPipelineClient pipelineClient = new QueryPipelineClient(Reporter.NULL, unauthPathEndpoint, fusionUser, fusionPass, fusionRealm, null); pipelineClient.getBatchFromStartPointWithRetry(0, 100); } @Test(expected = SolrException.class) public void testGetBatchNotanEndpoint() throws Exception { final QueryPipelineClient pipelineClient = new QueryPipelineClient(Reporter.NULL, notAnEndpoint, fusionUser, fusionPass, fusionRealm, null); pipelineClient.getBatchFromStartPointWithRetry(0, 100); } }
apache-2.0
DariusX/camel
core/camel-endpointdsl/src/generated/java/org/apache/camel/builder/endpoint/dsl/ElsqlEndpointBuilderFactory.java
95666
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.camel.builder.endpoint.dsl; import java.util.Map; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.TimeUnit; import javax.annotation.Generated; import org.apache.camel.ExchangePattern; import org.apache.camel.LoggingLevel; import org.apache.camel.builder.EndpointConsumerBuilder; import org.apache.camel.builder.EndpointProducerBuilder; import org.apache.camel.builder.endpoint.AbstractEndpointBuilder; import org.apache.camel.spi.ExceptionHandler; import org.apache.camel.spi.PollingConsumerPollStrategy; /** * Use ElSql to define SQL queries. Extends the SQL Component. * * Generated by camel build tools - do NOT edit this file! */ @Generated("org.apache.camel.maven.packaging.EndpointDslMojo") public interface ElsqlEndpointBuilderFactory { /** * Builder for endpoint consumers for the ElSQL component. */ public interface ElsqlEndpointConsumerBuilder extends EndpointConsumerBuilder { default AdvancedElsqlEndpointConsumerBuilder advanced() { return (AdvancedElsqlEndpointConsumerBuilder) this; } /** * Whether to allow using named parameters in the queries. * * The option is a: <code>boolean</code> type. * * Default: true * Group: common */ default ElsqlEndpointConsumerBuilder allowNamedParameters( boolean allowNamedParameters) { doSetProperty("allowNamedParameters", allowNamedParameters); return this; } /** * Whether to allow using named parameters in the queries. * * The option will be converted to a <code>boolean</code> type. * * Default: true * Group: common */ default ElsqlEndpointConsumerBuilder allowNamedParameters( String allowNamedParameters) { doSetProperty("allowNamedParameters", allowNamedParameters); return this; } /** * To use a vendor specific com.opengamma.elsql.ElSqlConfig. * * The option is a: * <code>org.apache.camel.component.elsql.ElSqlDatabaseVendor</code> * type. * * Group: common */ default ElsqlEndpointConsumerBuilder databaseVendor( ElSqlDatabaseVendor databaseVendor) { doSetProperty("databaseVendor", databaseVendor); return this; } /** * To use a vendor specific com.opengamma.elsql.ElSqlConfig. * * The option will be converted to a * <code>org.apache.camel.component.elsql.ElSqlDatabaseVendor</code> * type. * * Group: common */ default ElsqlEndpointConsumerBuilder databaseVendor( String databaseVendor) { doSetProperty("databaseVendor", databaseVendor); return this; } /** * Sets the DataSource to use to communicate with the database. * * The option is a: <code>javax.sql.DataSource</code> type. * * Group: common */ default ElsqlEndpointConsumerBuilder dataSource(Object dataSource) { doSetProperty("dataSource", dataSource); return this; } /** * Sets the DataSource to use to communicate with the database. * * The option will be converted to a <code>javax.sql.DataSource</code> * type. * * Group: common */ default ElsqlEndpointConsumerBuilder dataSource(String dataSource) { doSetProperty("dataSource", dataSource); return this; } /** * Sets the reference to a DataSource to lookup from the registry, to * use for communicating with the database. * * The option is a: <code>java.lang.String</code> type. * * Group: common */ @Deprecated default ElsqlEndpointConsumerBuilder dataSourceRef(String dataSourceRef) { doSetProperty("dataSourceRef", dataSourceRef); return this; } /** * Specify the full package and class name to use as conversion when * outputType=SelectOne. * * The option is a: <code>java.lang.String</code> type. * * Group: common */ default ElsqlEndpointConsumerBuilder outputClass(String outputClass) { doSetProperty("outputClass", outputClass); return this; } /** * Store the query result in a header instead of the message body. By * default, outputHeader == null and the query result is stored in the * message body, any existing content in the message body is discarded. * If outputHeader is set, the value is used as the name of the header * to store the query result and the original message body is preserved. * * The option is a: <code>java.lang.String</code> type. * * Group: common */ default ElsqlEndpointConsumerBuilder outputHeader(String outputHeader) { doSetProperty("outputHeader", outputHeader); return this; } /** * Make the output of consumer or producer to SelectList as List of Map, * or SelectOne as single Java object in the following way: a) If the * query has only single column, then that JDBC Column object is * returned. (such as SELECT COUNT( ) FROM PROJECT will return a Long * object. b) If the query has more than one column, then it will return * a Map of that result. c) If the outputClass is set, then it will * convert the query result into an Java bean object by calling all the * setters that match the column names. It will assume your class has a * default constructor to create instance with. d) If the query resulted * in more than one rows, it throws an non-unique result exception. * StreamList streams the result of the query using an Iterator. This * can be used with the Splitter EIP in streaming mode to process the * ResultSet in streaming fashion. * * The option is a: * <code>org.apache.camel.component.sql.SqlOutputType</code> type. * * Default: SelectList * Group: common */ default ElsqlEndpointConsumerBuilder outputType(SqlOutputType outputType) { doSetProperty("outputType", outputType); return this; } /** * Make the output of consumer or producer to SelectList as List of Map, * or SelectOne as single Java object in the following way: a) If the * query has only single column, then that JDBC Column object is * returned. (such as SELECT COUNT( ) FROM PROJECT will return a Long * object. b) If the query has more than one column, then it will return * a Map of that result. c) If the outputClass is set, then it will * convert the query result into an Java bean object by calling all the * setters that match the column names. It will assume your class has a * default constructor to create instance with. d) If the query resulted * in more than one rows, it throws an non-unique result exception. * StreamList streams the result of the query using an Iterator. This * can be used with the Splitter EIP in streaming mode to process the * ResultSet in streaming fashion. * * The option will be converted to a * <code>org.apache.camel.component.sql.SqlOutputType</code> type. * * Default: SelectList * Group: common */ default ElsqlEndpointConsumerBuilder outputType(String outputType) { doSetProperty("outputType", outputType); return this; } /** * The separator to use when parameter values is taken from message body * (if the body is a String type), to be inserted at # placeholders. * Notice if you use named parameters, then a Map type is used instead. * The default value is comma. * * The option is a: <code>char</code> type. * * Default: , * Group: common */ default ElsqlEndpointConsumerBuilder separator(char separator) { doSetProperty("separator", separator); return this; } /** * The separator to use when parameter values is taken from message body * (if the body is a String type), to be inserted at # placeholders. * Notice if you use named parameters, then a Map type is used instead. * The default value is comma. * * The option will be converted to a <code>char</code> type. * * Default: , * Group: common */ default ElsqlEndpointConsumerBuilder separator(String separator) { doSetProperty("separator", separator); return this; } /** * Sets whether to break batch if onConsume failed. * * The option is a: <code>boolean</code> type. * * Default: false * Group: consumer */ default ElsqlEndpointConsumerBuilder breakBatchOnConsumeFail( boolean breakBatchOnConsumeFail) { doSetProperty("breakBatchOnConsumeFail", breakBatchOnConsumeFail); return this; } /** * Sets whether to break batch if onConsume failed. * * The option will be converted to a <code>boolean</code> type. * * Default: false * Group: consumer */ default ElsqlEndpointConsumerBuilder breakBatchOnConsumeFail( String breakBatchOnConsumeFail) { doSetProperty("breakBatchOnConsumeFail", breakBatchOnConsumeFail); return this; } /** * Allows for bridging the consumer to the Camel routing Error Handler, * which mean any exceptions occurred while the consumer is trying to * pickup incoming messages, or the likes, will now be processed as a * message and handled by the routing Error Handler. By default the * consumer will use the org.apache.camel.spi.ExceptionHandler to deal * with exceptions, that will be logged at WARN or ERROR level and * ignored. * * The option is a: <code>boolean</code> type. * * Default: false * Group: consumer */ default ElsqlEndpointConsumerBuilder bridgeErrorHandler( boolean bridgeErrorHandler) { doSetProperty("bridgeErrorHandler", bridgeErrorHandler); return this; } /** * Allows for bridging the consumer to the Camel routing Error Handler, * which mean any exceptions occurred while the consumer is trying to * pickup incoming messages, or the likes, will now be processed as a * message and handled by the routing Error Handler. By default the * consumer will use the org.apache.camel.spi.ExceptionHandler to deal * with exceptions, that will be logged at WARN or ERROR level and * ignored. * * The option will be converted to a <code>boolean</code> type. * * Default: false * Group: consumer */ default ElsqlEndpointConsumerBuilder bridgeErrorHandler( String bridgeErrorHandler) { doSetProperty("bridgeErrorHandler", bridgeErrorHandler); return this; } /** * Sets an expected update count to validate when using onConsume. * * The option is a: <code>int</code> type. * * Default: -1 * Group: consumer */ default ElsqlEndpointConsumerBuilder expectedUpdateCount( int expectedUpdateCount) { doSetProperty("expectedUpdateCount", expectedUpdateCount); return this; } /** * Sets an expected update count to validate when using onConsume. * * The option will be converted to a <code>int</code> type. * * Default: -1 * Group: consumer */ default ElsqlEndpointConsumerBuilder expectedUpdateCount( String expectedUpdateCount) { doSetProperty("expectedUpdateCount", expectedUpdateCount); return this; } /** * Sets the maximum number of messages to poll. * * The option is a: <code>int</code> type. * * Group: consumer */ default ElsqlEndpointConsumerBuilder maxMessagesPerPoll( int maxMessagesPerPoll) { doSetProperty("maxMessagesPerPoll", maxMessagesPerPoll); return this; } /** * Sets the maximum number of messages to poll. * * The option will be converted to a <code>int</code> type. * * Group: consumer */ default ElsqlEndpointConsumerBuilder maxMessagesPerPoll( String maxMessagesPerPoll) { doSetProperty("maxMessagesPerPoll", maxMessagesPerPoll); return this; } /** * After processing each row then this query can be executed, if the * Exchange was processed successfully, for example to mark the row as * processed. The query can have parameter. * * The option is a: <code>java.lang.String</code> type. * * Group: consumer */ default ElsqlEndpointConsumerBuilder onConsume(String onConsume) { doSetProperty("onConsume", onConsume); return this; } /** * After processing the entire batch, this query can be executed to bulk * update rows etc. The query cannot have parameters. * * The option is a: <code>java.lang.String</code> type. * * Group: consumer */ default ElsqlEndpointConsumerBuilder onConsumeBatchComplete( String onConsumeBatchComplete) { doSetProperty("onConsumeBatchComplete", onConsumeBatchComplete); return this; } /** * After processing each row then this query can be executed, if the * Exchange failed, for example to mark the row as failed. The query can * have parameter. * * The option is a: <code>java.lang.String</code> type. * * Group: consumer */ default ElsqlEndpointConsumerBuilder onConsumeFailed( String onConsumeFailed) { doSetProperty("onConsumeFailed", onConsumeFailed); return this; } /** * Sets whether empty resultset should be allowed to be sent to the next * hop. Defaults to false. So the empty resultset will be filtered out. * * The option is a: <code>boolean</code> type. * * Default: false * Group: consumer */ default ElsqlEndpointConsumerBuilder routeEmptyResultSet( boolean routeEmptyResultSet) { doSetProperty("routeEmptyResultSet", routeEmptyResultSet); return this; } /** * Sets whether empty resultset should be allowed to be sent to the next * hop. Defaults to false. So the empty resultset will be filtered out. * * The option will be converted to a <code>boolean</code> type. * * Default: false * Group: consumer */ default ElsqlEndpointConsumerBuilder routeEmptyResultSet( String routeEmptyResultSet) { doSetProperty("routeEmptyResultSet", routeEmptyResultSet); return this; } /** * If the polling consumer did not poll any files, you can enable this * option to send an empty message (no body) instead. * * The option is a: <code>boolean</code> type. * * Default: false * Group: consumer */ default ElsqlEndpointConsumerBuilder sendEmptyMessageWhenIdle( boolean sendEmptyMessageWhenIdle) { doSetProperty("sendEmptyMessageWhenIdle", sendEmptyMessageWhenIdle); return this; } /** * If the polling consumer did not poll any files, you can enable this * option to send an empty message (no body) instead. * * The option will be converted to a <code>boolean</code> type. * * Default: false * Group: consumer */ default ElsqlEndpointConsumerBuilder sendEmptyMessageWhenIdle( String sendEmptyMessageWhenIdle) { doSetProperty("sendEmptyMessageWhenIdle", sendEmptyMessageWhenIdle); return this; } /** * Enables or disables transaction. If enabled then if processing an * exchange failed then the consumer breaks out processing any further * exchanges to cause a rollback eager. * * The option is a: <code>boolean</code> type. * * Default: false * Group: consumer */ default ElsqlEndpointConsumerBuilder transacted(boolean transacted) { doSetProperty("transacted", transacted); return this; } /** * Enables or disables transaction. If enabled then if processing an * exchange failed then the consumer breaks out processing any further * exchanges to cause a rollback eager. * * The option will be converted to a <code>boolean</code> type. * * Default: false * Group: consumer */ default ElsqlEndpointConsumerBuilder transacted(String transacted) { doSetProperty("transacted", transacted); return this; } /** * Sets how resultset should be delivered to route. Indicates delivery * as either a list or individual object. defaults to true. * * The option is a: <code>boolean</code> type. * * Default: true * Group: consumer */ default ElsqlEndpointConsumerBuilder useIterator(boolean useIterator) { doSetProperty("useIterator", useIterator); return this; } /** * Sets how resultset should be delivered to route. Indicates delivery * as either a list or individual object. defaults to true. * * The option will be converted to a <code>boolean</code> type. * * Default: true * Group: consumer */ default ElsqlEndpointConsumerBuilder useIterator(String useIterator) { doSetProperty("useIterator", useIterator); return this; } /** * The number of subsequent error polls (failed due some error) that * should happen before the backoffMultipler should kick-in. * * The option is a: <code>int</code> type. * * Group: scheduler */ default ElsqlEndpointConsumerBuilder backoffErrorThreshold( int backoffErrorThreshold) { doSetProperty("backoffErrorThreshold", backoffErrorThreshold); return this; } /** * The number of subsequent error polls (failed due some error) that * should happen before the backoffMultipler should kick-in. * * The option will be converted to a <code>int</code> type. * * Group: scheduler */ default ElsqlEndpointConsumerBuilder backoffErrorThreshold( String backoffErrorThreshold) { doSetProperty("backoffErrorThreshold", backoffErrorThreshold); return this; } /** * The number of subsequent idle polls that should happen before the * backoffMultipler should kick-in. * * The option is a: <code>int</code> type. * * Group: scheduler */ default ElsqlEndpointConsumerBuilder backoffIdleThreshold( int backoffIdleThreshold) { doSetProperty("backoffIdleThreshold", backoffIdleThreshold); return this; } /** * The number of subsequent idle polls that should happen before the * backoffMultipler should kick-in. * * The option will be converted to a <code>int</code> type. * * Group: scheduler */ default ElsqlEndpointConsumerBuilder backoffIdleThreshold( String backoffIdleThreshold) { doSetProperty("backoffIdleThreshold", backoffIdleThreshold); return this; } /** * To let the scheduled polling consumer backoff if there has been a * number of subsequent idles/errors in a row. The multiplier is then * the number of polls that will be skipped before the next actual * attempt is happening again. When this option is in use then * backoffIdleThreshold and/or backoffErrorThreshold must also be * configured. * * The option is a: <code>int</code> type. * * Group: scheduler */ default ElsqlEndpointConsumerBuilder backoffMultiplier( int backoffMultiplier) { doSetProperty("backoffMultiplier", backoffMultiplier); return this; } /** * To let the scheduled polling consumer backoff if there has been a * number of subsequent idles/errors in a row. The multiplier is then * the number of polls that will be skipped before the next actual * attempt is happening again. When this option is in use then * backoffIdleThreshold and/or backoffErrorThreshold must also be * configured. * * The option will be converted to a <code>int</code> type. * * Group: scheduler */ default ElsqlEndpointConsumerBuilder backoffMultiplier( String backoffMultiplier) { doSetProperty("backoffMultiplier", backoffMultiplier); return this; } /** * Milliseconds before the next poll. * * The option is a: <code>long</code> type. * * Default: 500 * Group: scheduler */ default ElsqlEndpointConsumerBuilder delay(long delay) { doSetProperty("delay", delay); return this; } /** * Milliseconds before the next poll. * * The option will be converted to a <code>long</code> type. * * Default: 500 * Group: scheduler */ default ElsqlEndpointConsumerBuilder delay(String delay) { doSetProperty("delay", delay); return this; } /** * If greedy is enabled, then the ScheduledPollConsumer will run * immediately again, if the previous run polled 1 or more messages. * * The option is a: <code>boolean</code> type. * * Default: false * Group: scheduler */ default ElsqlEndpointConsumerBuilder greedy(boolean greedy) { doSetProperty("greedy", greedy); return this; } /** * If greedy is enabled, then the ScheduledPollConsumer will run * immediately again, if the previous run polled 1 or more messages. * * The option will be converted to a <code>boolean</code> type. * * Default: false * Group: scheduler */ default ElsqlEndpointConsumerBuilder greedy(String greedy) { doSetProperty("greedy", greedy); return this; } /** * Milliseconds before the first poll starts. * * The option is a: <code>long</code> type. * * Default: 1000 * Group: scheduler */ default ElsqlEndpointConsumerBuilder initialDelay(long initialDelay) { doSetProperty("initialDelay", initialDelay); return this; } /** * Milliseconds before the first poll starts. * * The option will be converted to a <code>long</code> type. * * Default: 1000 * Group: scheduler */ default ElsqlEndpointConsumerBuilder initialDelay(String initialDelay) { doSetProperty("initialDelay", initialDelay); return this; } /** * Specifies a maximum limit of number of fires. So if you set it to 1, * the scheduler will only fire once. If you set it to 5, it will only * fire five times. A value of zero or negative means fire forever. * * The option is a: <code>long</code> type. * * Default: 0 * Group: scheduler */ default ElsqlEndpointConsumerBuilder repeatCount(long repeatCount) { doSetProperty("repeatCount", repeatCount); return this; } /** * Specifies a maximum limit of number of fires. So if you set it to 1, * the scheduler will only fire once. If you set it to 5, it will only * fire five times. A value of zero or negative means fire forever. * * The option will be converted to a <code>long</code> type. * * Default: 0 * Group: scheduler */ default ElsqlEndpointConsumerBuilder repeatCount(String repeatCount) { doSetProperty("repeatCount", repeatCount); return this; } /** * The consumer logs a start/complete log line when it polls. This * option allows you to configure the logging level for that. * * The option is a: <code>org.apache.camel.LoggingLevel</code> type. * * Default: TRACE * Group: scheduler */ default ElsqlEndpointConsumerBuilder runLoggingLevel( LoggingLevel runLoggingLevel) { doSetProperty("runLoggingLevel", runLoggingLevel); return this; } /** * The consumer logs a start/complete log line when it polls. This * option allows you to configure the logging level for that. * * The option will be converted to a * <code>org.apache.camel.LoggingLevel</code> type. * * Default: TRACE * Group: scheduler */ default ElsqlEndpointConsumerBuilder runLoggingLevel( String runLoggingLevel) { doSetProperty("runLoggingLevel", runLoggingLevel); return this; } /** * Allows for configuring a custom/shared thread pool to use for the * consumer. By default each consumer has its own single threaded thread * pool. * * The option is a: * <code>java.util.concurrent.ScheduledExecutorService</code> type. * * Group: scheduler */ default ElsqlEndpointConsumerBuilder scheduledExecutorService( ScheduledExecutorService scheduledExecutorService) { doSetProperty("scheduledExecutorService", scheduledExecutorService); return this; } /** * Allows for configuring a custom/shared thread pool to use for the * consumer. By default each consumer has its own single threaded thread * pool. * * The option will be converted to a * <code>java.util.concurrent.ScheduledExecutorService</code> type. * * Group: scheduler */ default ElsqlEndpointConsumerBuilder scheduledExecutorService( String scheduledExecutorService) { doSetProperty("scheduledExecutorService", scheduledExecutorService); return this; } /** * To use a cron scheduler from either camel-spring or camel-quartz * component. * * The option is a: <code>java.lang.String</code> type. * * Default: none * Group: scheduler */ default ElsqlEndpointConsumerBuilder scheduler(String scheduler) { doSetProperty("scheduler", scheduler); return this; } /** * To configure additional properties when using a custom scheduler or * any of the Quartz, Spring based scheduler. * * The option is a: <code>java.util.Map&lt;java.lang.String, * java.lang.Object&gt;</code> type. * The option is multivalued, and you can use the * schedulerProperties(String, Object) method to add a value (call the * method multiple times to set more values). * * Group: scheduler */ default ElsqlEndpointConsumerBuilder schedulerProperties( String key, Object value) { doSetMultiValueProperty("schedulerProperties", "scheduler." + key, value); return this; } /** * To configure additional properties when using a custom scheduler or * any of the Quartz, Spring based scheduler. * * The option is a: <code>java.util.Map&lt;java.lang.String, * java.lang.Object&gt;</code> type. * The option is multivalued, and you can use the * schedulerProperties(String, Object) method to add a value (call the * method multiple times to set more values). * * Group: scheduler */ default ElsqlEndpointConsumerBuilder schedulerProperties(Map values) { doSetMultiValueProperties("schedulerProperties", "scheduler.", values); return this; } /** * Whether the scheduler should be auto started. * * The option is a: <code>boolean</code> type. * * Default: true * Group: scheduler */ default ElsqlEndpointConsumerBuilder startScheduler( boolean startScheduler) { doSetProperty("startScheduler", startScheduler); return this; } /** * Whether the scheduler should be auto started. * * The option will be converted to a <code>boolean</code> type. * * Default: true * Group: scheduler */ default ElsqlEndpointConsumerBuilder startScheduler( String startScheduler) { doSetProperty("startScheduler", startScheduler); return this; } /** * Time unit for initialDelay and delay options. * * The option is a: <code>java.util.concurrent.TimeUnit</code> type. * * Default: MILLISECONDS * Group: scheduler */ default ElsqlEndpointConsumerBuilder timeUnit(TimeUnit timeUnit) { doSetProperty("timeUnit", timeUnit); return this; } /** * Time unit for initialDelay and delay options. * * The option will be converted to a * <code>java.util.concurrent.TimeUnit</code> type. * * Default: MILLISECONDS * Group: scheduler */ default ElsqlEndpointConsumerBuilder timeUnit(String timeUnit) { doSetProperty("timeUnit", timeUnit); return this; } /** * Controls if fixed delay or fixed rate is used. See * ScheduledExecutorService in JDK for details. * * The option is a: <code>boolean</code> type. * * Default: true * Group: scheduler */ default ElsqlEndpointConsumerBuilder useFixedDelay(boolean useFixedDelay) { doSetProperty("useFixedDelay", useFixedDelay); return this; } /** * Controls if fixed delay or fixed rate is used. See * ScheduledExecutorService in JDK for details. * * The option will be converted to a <code>boolean</code> type. * * Default: true * Group: scheduler */ default ElsqlEndpointConsumerBuilder useFixedDelay(String useFixedDelay) { doSetProperty("useFixedDelay", useFixedDelay); return this; } } /** * Advanced builder for endpoint consumers for the ElSQL component. */ public interface AdvancedElsqlEndpointConsumerBuilder extends EndpointConsumerBuilder { default ElsqlEndpointConsumerBuilder basic() { return (ElsqlEndpointConsumerBuilder) this; } /** * To let the consumer use a custom ExceptionHandler. Notice if the * option bridgeErrorHandler is enabled then this option is not in use. * By default the consumer will deal with exceptions, that will be * logged at WARN or ERROR level and ignored. * * The option is a: <code>org.apache.camel.spi.ExceptionHandler</code> * type. * * Group: consumer (advanced) */ default AdvancedElsqlEndpointConsumerBuilder exceptionHandler( ExceptionHandler exceptionHandler) { doSetProperty("exceptionHandler", exceptionHandler); return this; } /** * To let the consumer use a custom ExceptionHandler. Notice if the * option bridgeErrorHandler is enabled then this option is not in use. * By default the consumer will deal with exceptions, that will be * logged at WARN or ERROR level and ignored. * * The option will be converted to a * <code>org.apache.camel.spi.ExceptionHandler</code> type. * * Group: consumer (advanced) */ default AdvancedElsqlEndpointConsumerBuilder exceptionHandler( String exceptionHandler) { doSetProperty("exceptionHandler", exceptionHandler); return this; } /** * Sets the exchange pattern when the consumer creates an exchange. * * The option is a: <code>org.apache.camel.ExchangePattern</code> type. * * Group: consumer (advanced) */ default AdvancedElsqlEndpointConsumerBuilder exchangePattern( ExchangePattern exchangePattern) { doSetProperty("exchangePattern", exchangePattern); return this; } /** * Sets the exchange pattern when the consumer creates an exchange. * * The option will be converted to a * <code>org.apache.camel.ExchangePattern</code> type. * * Group: consumer (advanced) */ default AdvancedElsqlEndpointConsumerBuilder exchangePattern( String exchangePattern) { doSetProperty("exchangePattern", exchangePattern); return this; } /** * A pluggable org.apache.camel.PollingConsumerPollingStrategy allowing * you to provide your custom implementation to control error handling * usually occurred during the poll operation before an Exchange have * been created and being routed in Camel. * * The option is a: * <code>org.apache.camel.spi.PollingConsumerPollStrategy</code> type. * * Group: consumer (advanced) */ default AdvancedElsqlEndpointConsumerBuilder pollStrategy( PollingConsumerPollStrategy pollStrategy) { doSetProperty("pollStrategy", pollStrategy); return this; } /** * A pluggable org.apache.camel.PollingConsumerPollingStrategy allowing * you to provide your custom implementation to control error handling * usually occurred during the poll operation before an Exchange have * been created and being routed in Camel. * * The option will be converted to a * <code>org.apache.camel.spi.PollingConsumerPollStrategy</code> type. * * Group: consumer (advanced) */ default AdvancedElsqlEndpointConsumerBuilder pollStrategy( String pollStrategy) { doSetProperty("pollStrategy", pollStrategy); return this; } /** * Allows to plugin to use a custom * org.apache.camel.component.sql.SqlProcessingStrategy to execute * queries when the consumer has processed the rows/batch. * * The option is a: * <code>org.apache.camel.component.sql.SqlProcessingStrategy</code> * type. * * Group: consumer (advanced) */ default AdvancedElsqlEndpointConsumerBuilder processingStrategy( Object processingStrategy) { doSetProperty("processingStrategy", processingStrategy); return this; } /** * Allows to plugin to use a custom * org.apache.camel.component.sql.SqlProcessingStrategy to execute * queries when the consumer has processed the rows/batch. * * The option will be converted to a * <code>org.apache.camel.component.sql.SqlProcessingStrategy</code> * type. * * Group: consumer (advanced) */ default AdvancedElsqlEndpointConsumerBuilder processingStrategy( String processingStrategy) { doSetProperty("processingStrategy", processingStrategy); return this; } /** * If enabled then the populateStatement method from * org.apache.camel.component.sql.SqlPrepareStatementStrategy is always * invoked, also if there is no expected parameters to be prepared. When * this is false then the populateStatement is only invoked if there is * 1 or more expected parameters to be set; for example this avoids * reading the message body/headers for SQL queries with no parameters. * * The option is a: <code>boolean</code> type. * * Default: false * Group: advanced */ default AdvancedElsqlEndpointConsumerBuilder alwaysPopulateStatement( boolean alwaysPopulateStatement) { doSetProperty("alwaysPopulateStatement", alwaysPopulateStatement); return this; } /** * If enabled then the populateStatement method from * org.apache.camel.component.sql.SqlPrepareStatementStrategy is always * invoked, also if there is no expected parameters to be prepared. When * this is false then the populateStatement is only invoked if there is * 1 or more expected parameters to be set; for example this avoids * reading the message body/headers for SQL queries with no parameters. * * The option will be converted to a <code>boolean</code> type. * * Default: false * Group: advanced */ default AdvancedElsqlEndpointConsumerBuilder alwaysPopulateStatement( String alwaysPopulateStatement) { doSetProperty("alwaysPopulateStatement", alwaysPopulateStatement); return this; } /** * Whether the endpoint should use basic property binding (Camel 2.x) or * the newer property binding with additional capabilities. * * The option is a: <code>boolean</code> type. * * Default: false * Group: advanced */ default AdvancedElsqlEndpointConsumerBuilder basicPropertyBinding( boolean basicPropertyBinding) { doSetProperty("basicPropertyBinding", basicPropertyBinding); return this; } /** * Whether the endpoint should use basic property binding (Camel 2.x) or * the newer property binding with additional capabilities. * * The option will be converted to a <code>boolean</code> type. * * Default: false * Group: advanced */ default AdvancedElsqlEndpointConsumerBuilder basicPropertyBinding( String basicPropertyBinding) { doSetProperty("basicPropertyBinding", basicPropertyBinding); return this; } /** * To use a specific configured ElSqlConfig. It may be better to use the * databaseVendor option instead. * * The option is a: <code>com.opengamma.elsql.ElSqlConfig</code> type. * * Group: advanced */ default AdvancedElsqlEndpointConsumerBuilder elSqlConfig( Object elSqlConfig) { doSetProperty("elSqlConfig", elSqlConfig); return this; } /** * To use a specific configured ElSqlConfig. It may be better to use the * databaseVendor option instead. * * The option will be converted to a * <code>com.opengamma.elsql.ElSqlConfig</code> type. * * Group: advanced */ default AdvancedElsqlEndpointConsumerBuilder elSqlConfig( String elSqlConfig) { doSetProperty("elSqlConfig", elSqlConfig); return this; } /** * If set greater than zero, then Camel will use this count value of * parameters to replace instead of querying via JDBC metadata API. This * is useful if the JDBC vendor could not return correct parameters * count, then user may override instead. * * The option is a: <code>int</code> type. * * Group: advanced */ default AdvancedElsqlEndpointConsumerBuilder parametersCount( int parametersCount) { doSetProperty("parametersCount", parametersCount); return this; } /** * If set greater than zero, then Camel will use this count value of * parameters to replace instead of querying via JDBC metadata API. This * is useful if the JDBC vendor could not return correct parameters * count, then user may override instead. * * The option will be converted to a <code>int</code> type. * * Group: advanced */ default AdvancedElsqlEndpointConsumerBuilder parametersCount( String parametersCount) { doSetProperty("parametersCount", parametersCount); return this; } /** * Specifies a character that will be replaced to in SQL query. Notice, * that it is simple String.replaceAll() operation and no SQL parsing is * involved (quoted strings will also change). * * The option is a: <code>java.lang.String</code> type. * * Default: # * Group: advanced */ default AdvancedElsqlEndpointConsumerBuilder placeholder( String placeholder) { doSetProperty("placeholder", placeholder); return this; } /** * Allows to plugin to use a custom * org.apache.camel.component.sql.SqlPrepareStatementStrategy to control * preparation of the query and prepared statement. * * The option is a: * <code>org.apache.camel.component.sql.SqlPrepareStatementStrategy</code> type. * * Group: advanced */ default AdvancedElsqlEndpointConsumerBuilder prepareStatementStrategy( Object prepareStatementStrategy) { doSetProperty("prepareStatementStrategy", prepareStatementStrategy); return this; } /** * Allows to plugin to use a custom * org.apache.camel.component.sql.SqlPrepareStatementStrategy to control * preparation of the query and prepared statement. * * The option will be converted to a * <code>org.apache.camel.component.sql.SqlPrepareStatementStrategy</code> type. * * Group: advanced */ default AdvancedElsqlEndpointConsumerBuilder prepareStatementStrategy( String prepareStatementStrategy) { doSetProperty("prepareStatementStrategy", prepareStatementStrategy); return this; } /** * Sets whether synchronous processing should be strictly used, or Camel * is allowed to use asynchronous processing (if supported). * * The option is a: <code>boolean</code> type. * * Default: false * Group: advanced */ default AdvancedElsqlEndpointConsumerBuilder synchronous( boolean synchronous) { doSetProperty("synchronous", synchronous); return this; } /** * Sets whether synchronous processing should be strictly used, or Camel * is allowed to use asynchronous processing (if supported). * * The option will be converted to a <code>boolean</code> type. * * Default: false * Group: advanced */ default AdvancedElsqlEndpointConsumerBuilder synchronous( String synchronous) { doSetProperty("synchronous", synchronous); return this; } /** * Configures the Spring JdbcTemplate with the key/values from the Map. * * The option is a: <code>java.util.Map&lt;java.lang.String, * java.lang.Object&gt;</code> type. * The option is multivalued, and you can use the * templateOptions(String, Object) method to add a value (call the * method multiple times to set more values). * * Group: advanced */ default AdvancedElsqlEndpointConsumerBuilder templateOptions( String key, Object value) { doSetMultiValueProperty("templateOptions", "template." + key, value); return this; } /** * Configures the Spring JdbcTemplate with the key/values from the Map. * * The option is a: <code>java.util.Map&lt;java.lang.String, * java.lang.Object&gt;</code> type. * The option is multivalued, and you can use the * templateOptions(String, Object) method to add a value (call the * method multiple times to set more values). * * Group: advanced */ default AdvancedElsqlEndpointConsumerBuilder templateOptions(Map values) { doSetMultiValueProperties("templateOptions", "template.", values); return this; } /** * Sets whether to use placeholder and replace all placeholder * characters with sign in the SQL queries. * * The option is a: <code>boolean</code> type. * * Default: true * Group: advanced */ default AdvancedElsqlEndpointConsumerBuilder usePlaceholder( boolean usePlaceholder) { doSetProperty("usePlaceholder", usePlaceholder); return this; } /** * Sets whether to use placeholder and replace all placeholder * characters with sign in the SQL queries. * * The option will be converted to a <code>boolean</code> type. * * Default: true * Group: advanced */ default AdvancedElsqlEndpointConsumerBuilder usePlaceholder( String usePlaceholder) { doSetProperty("usePlaceholder", usePlaceholder); return this; } } /** * Builder for endpoint producers for the ElSQL component. */ public interface ElsqlEndpointProducerBuilder extends EndpointProducerBuilder { default AdvancedElsqlEndpointProducerBuilder advanced() { return (AdvancedElsqlEndpointProducerBuilder) this; } /** * Whether to allow using named parameters in the queries. * * The option is a: <code>boolean</code> type. * * Default: true * Group: common */ default ElsqlEndpointProducerBuilder allowNamedParameters( boolean allowNamedParameters) { doSetProperty("allowNamedParameters", allowNamedParameters); return this; } /** * Whether to allow using named parameters in the queries. * * The option will be converted to a <code>boolean</code> type. * * Default: true * Group: common */ default ElsqlEndpointProducerBuilder allowNamedParameters( String allowNamedParameters) { doSetProperty("allowNamedParameters", allowNamedParameters); return this; } /** * To use a vendor specific com.opengamma.elsql.ElSqlConfig. * * The option is a: * <code>org.apache.camel.component.elsql.ElSqlDatabaseVendor</code> * type. * * Group: common */ default ElsqlEndpointProducerBuilder databaseVendor( ElSqlDatabaseVendor databaseVendor) { doSetProperty("databaseVendor", databaseVendor); return this; } /** * To use a vendor specific com.opengamma.elsql.ElSqlConfig. * * The option will be converted to a * <code>org.apache.camel.component.elsql.ElSqlDatabaseVendor</code> * type. * * Group: common */ default ElsqlEndpointProducerBuilder databaseVendor( String databaseVendor) { doSetProperty("databaseVendor", databaseVendor); return this; } /** * Sets the DataSource to use to communicate with the database. * * The option is a: <code>javax.sql.DataSource</code> type. * * Group: common */ default ElsqlEndpointProducerBuilder dataSource(Object dataSource) { doSetProperty("dataSource", dataSource); return this; } /** * Sets the DataSource to use to communicate with the database. * * The option will be converted to a <code>javax.sql.DataSource</code> * type. * * Group: common */ default ElsqlEndpointProducerBuilder dataSource(String dataSource) { doSetProperty("dataSource", dataSource); return this; } /** * Sets the reference to a DataSource to lookup from the registry, to * use for communicating with the database. * * The option is a: <code>java.lang.String</code> type. * * Group: common */ @Deprecated default ElsqlEndpointProducerBuilder dataSourceRef(String dataSourceRef) { doSetProperty("dataSourceRef", dataSourceRef); return this; } /** * Specify the full package and class name to use as conversion when * outputType=SelectOne. * * The option is a: <code>java.lang.String</code> type. * * Group: common */ default ElsqlEndpointProducerBuilder outputClass(String outputClass) { doSetProperty("outputClass", outputClass); return this; } /** * Store the query result in a header instead of the message body. By * default, outputHeader == null and the query result is stored in the * message body, any existing content in the message body is discarded. * If outputHeader is set, the value is used as the name of the header * to store the query result and the original message body is preserved. * * The option is a: <code>java.lang.String</code> type. * * Group: common */ default ElsqlEndpointProducerBuilder outputHeader(String outputHeader) { doSetProperty("outputHeader", outputHeader); return this; } /** * Make the output of consumer or producer to SelectList as List of Map, * or SelectOne as single Java object in the following way: a) If the * query has only single column, then that JDBC Column object is * returned. (such as SELECT COUNT( ) FROM PROJECT will return a Long * object. b) If the query has more than one column, then it will return * a Map of that result. c) If the outputClass is set, then it will * convert the query result into an Java bean object by calling all the * setters that match the column names. It will assume your class has a * default constructor to create instance with. d) If the query resulted * in more than one rows, it throws an non-unique result exception. * StreamList streams the result of the query using an Iterator. This * can be used with the Splitter EIP in streaming mode to process the * ResultSet in streaming fashion. * * The option is a: * <code>org.apache.camel.component.sql.SqlOutputType</code> type. * * Default: SelectList * Group: common */ default ElsqlEndpointProducerBuilder outputType(SqlOutputType outputType) { doSetProperty("outputType", outputType); return this; } /** * Make the output of consumer or producer to SelectList as List of Map, * or SelectOne as single Java object in the following way: a) If the * query has only single column, then that JDBC Column object is * returned. (such as SELECT COUNT( ) FROM PROJECT will return a Long * object. b) If the query has more than one column, then it will return * a Map of that result. c) If the outputClass is set, then it will * convert the query result into an Java bean object by calling all the * setters that match the column names. It will assume your class has a * default constructor to create instance with. d) If the query resulted * in more than one rows, it throws an non-unique result exception. * StreamList streams the result of the query using an Iterator. This * can be used with the Splitter EIP in streaming mode to process the * ResultSet in streaming fashion. * * The option will be converted to a * <code>org.apache.camel.component.sql.SqlOutputType</code> type. * * Default: SelectList * Group: common */ default ElsqlEndpointProducerBuilder outputType(String outputType) { doSetProperty("outputType", outputType); return this; } /** * The separator to use when parameter values is taken from message body * (if the body is a String type), to be inserted at # placeholders. * Notice if you use named parameters, then a Map type is used instead. * The default value is comma. * * The option is a: <code>char</code> type. * * Default: , * Group: common */ default ElsqlEndpointProducerBuilder separator(char separator) { doSetProperty("separator", separator); return this; } /** * The separator to use when parameter values is taken from message body * (if the body is a String type), to be inserted at # placeholders. * Notice if you use named parameters, then a Map type is used instead. * The default value is comma. * * The option will be converted to a <code>char</code> type. * * Default: , * Group: common */ default ElsqlEndpointProducerBuilder separator(String separator) { doSetProperty("separator", separator); return this; } /** * Enables or disables batch mode. * * The option is a: <code>boolean</code> type. * * Default: false * Group: producer */ default ElsqlEndpointProducerBuilder batch(boolean batch) { doSetProperty("batch", batch); return this; } /** * Enables or disables batch mode. * * The option will be converted to a <code>boolean</code> type. * * Default: false * Group: producer */ default ElsqlEndpointProducerBuilder batch(String batch) { doSetProperty("batch", batch); return this; } /** * Whether the producer should be started lazy (on the first message). * By starting lazy you can use this to allow CamelContext and routes to * startup in situations where a producer may otherwise fail during * starting and cause the route to fail being started. By deferring this * startup to be lazy then the startup failure can be handled during * routing messages via Camel's routing error handlers. Beware that when * the first message is processed then creating and starting the * producer may take a little time and prolong the total processing time * of the processing. * * The option is a: <code>boolean</code> type. * * Default: false * Group: producer */ default ElsqlEndpointProducerBuilder lazyStartProducer( boolean lazyStartProducer) { doSetProperty("lazyStartProducer", lazyStartProducer); return this; } /** * Whether the producer should be started lazy (on the first message). * By starting lazy you can use this to allow CamelContext and routes to * startup in situations where a producer may otherwise fail during * starting and cause the route to fail being started. By deferring this * startup to be lazy then the startup failure can be handled during * routing messages via Camel's routing error handlers. Beware that when * the first message is processed then creating and starting the * producer may take a little time and prolong the total processing time * of the processing. * * The option will be converted to a <code>boolean</code> type. * * Default: false * Group: producer */ default ElsqlEndpointProducerBuilder lazyStartProducer( String lazyStartProducer) { doSetProperty("lazyStartProducer", lazyStartProducer); return this; } /** * If set, will ignore the results of the SQL query and use the existing * IN message as the OUT message for the continuation of processing. * * The option is a: <code>boolean</code> type. * * Default: false * Group: producer */ default ElsqlEndpointProducerBuilder noop(boolean noop) { doSetProperty("noop", noop); return this; } /** * If set, will ignore the results of the SQL query and use the existing * IN message as the OUT message for the continuation of processing. * * The option will be converted to a <code>boolean</code> type. * * Default: false * Group: producer */ default ElsqlEndpointProducerBuilder noop(String noop) { doSetProperty("noop", noop); return this; } /** * Whether to use the message body as the SQL and then headers for * parameters. If this option is enabled then the SQL in the uri is not * used. Note that query parameters in the message body are represented * by a question mark instead of a # symbol. * * The option is a: <code>boolean</code> type. * * Default: false * Group: producer */ default ElsqlEndpointProducerBuilder useMessageBodyForSql( boolean useMessageBodyForSql) { doSetProperty("useMessageBodyForSql", useMessageBodyForSql); return this; } /** * Whether to use the message body as the SQL and then headers for * parameters. If this option is enabled then the SQL in the uri is not * used. Note that query parameters in the message body are represented * by a question mark instead of a # symbol. * * The option will be converted to a <code>boolean</code> type. * * Default: false * Group: producer */ default ElsqlEndpointProducerBuilder useMessageBodyForSql( String useMessageBodyForSql) { doSetProperty("useMessageBodyForSql", useMessageBodyForSql); return this; } } /** * Advanced builder for endpoint producers for the ElSQL component. */ public interface AdvancedElsqlEndpointProducerBuilder extends EndpointProducerBuilder { default ElsqlEndpointProducerBuilder basic() { return (ElsqlEndpointProducerBuilder) this; } /** * If enabled then the populateStatement method from * org.apache.camel.component.sql.SqlPrepareStatementStrategy is always * invoked, also if there is no expected parameters to be prepared. When * this is false then the populateStatement is only invoked if there is * 1 or more expected parameters to be set; for example this avoids * reading the message body/headers for SQL queries with no parameters. * * The option is a: <code>boolean</code> type. * * Default: false * Group: advanced */ default AdvancedElsqlEndpointProducerBuilder alwaysPopulateStatement( boolean alwaysPopulateStatement) { doSetProperty("alwaysPopulateStatement", alwaysPopulateStatement); return this; } /** * If enabled then the populateStatement method from * org.apache.camel.component.sql.SqlPrepareStatementStrategy is always * invoked, also if there is no expected parameters to be prepared. When * this is false then the populateStatement is only invoked if there is * 1 or more expected parameters to be set; for example this avoids * reading the message body/headers for SQL queries with no parameters. * * The option will be converted to a <code>boolean</code> type. * * Default: false * Group: advanced */ default AdvancedElsqlEndpointProducerBuilder alwaysPopulateStatement( String alwaysPopulateStatement) { doSetProperty("alwaysPopulateStatement", alwaysPopulateStatement); return this; } /** * Whether the endpoint should use basic property binding (Camel 2.x) or * the newer property binding with additional capabilities. * * The option is a: <code>boolean</code> type. * * Default: false * Group: advanced */ default AdvancedElsqlEndpointProducerBuilder basicPropertyBinding( boolean basicPropertyBinding) { doSetProperty("basicPropertyBinding", basicPropertyBinding); return this; } /** * Whether the endpoint should use basic property binding (Camel 2.x) or * the newer property binding with additional capabilities. * * The option will be converted to a <code>boolean</code> type. * * Default: false * Group: advanced */ default AdvancedElsqlEndpointProducerBuilder basicPropertyBinding( String basicPropertyBinding) { doSetProperty("basicPropertyBinding", basicPropertyBinding); return this; } /** * To use a specific configured ElSqlConfig. It may be better to use the * databaseVendor option instead. * * The option is a: <code>com.opengamma.elsql.ElSqlConfig</code> type. * * Group: advanced */ default AdvancedElsqlEndpointProducerBuilder elSqlConfig( Object elSqlConfig) { doSetProperty("elSqlConfig", elSqlConfig); return this; } /** * To use a specific configured ElSqlConfig. It may be better to use the * databaseVendor option instead. * * The option will be converted to a * <code>com.opengamma.elsql.ElSqlConfig</code> type. * * Group: advanced */ default AdvancedElsqlEndpointProducerBuilder elSqlConfig( String elSqlConfig) { doSetProperty("elSqlConfig", elSqlConfig); return this; } /** * If set greater than zero, then Camel will use this count value of * parameters to replace instead of querying via JDBC metadata API. This * is useful if the JDBC vendor could not return correct parameters * count, then user may override instead. * * The option is a: <code>int</code> type. * * Group: advanced */ default AdvancedElsqlEndpointProducerBuilder parametersCount( int parametersCount) { doSetProperty("parametersCount", parametersCount); return this; } /** * If set greater than zero, then Camel will use this count value of * parameters to replace instead of querying via JDBC metadata API. This * is useful if the JDBC vendor could not return correct parameters * count, then user may override instead. * * The option will be converted to a <code>int</code> type. * * Group: advanced */ default AdvancedElsqlEndpointProducerBuilder parametersCount( String parametersCount) { doSetProperty("parametersCount", parametersCount); return this; } /** * Specifies a character that will be replaced to in SQL query. Notice, * that it is simple String.replaceAll() operation and no SQL parsing is * involved (quoted strings will also change). * * The option is a: <code>java.lang.String</code> type. * * Default: # * Group: advanced */ default AdvancedElsqlEndpointProducerBuilder placeholder( String placeholder) { doSetProperty("placeholder", placeholder); return this; } /** * Allows to plugin to use a custom * org.apache.camel.component.sql.SqlPrepareStatementStrategy to control * preparation of the query and prepared statement. * * The option is a: * <code>org.apache.camel.component.sql.SqlPrepareStatementStrategy</code> type. * * Group: advanced */ default AdvancedElsqlEndpointProducerBuilder prepareStatementStrategy( Object prepareStatementStrategy) { doSetProperty("prepareStatementStrategy", prepareStatementStrategy); return this; } /** * Allows to plugin to use a custom * org.apache.camel.component.sql.SqlPrepareStatementStrategy to control * preparation of the query and prepared statement. * * The option will be converted to a * <code>org.apache.camel.component.sql.SqlPrepareStatementStrategy</code> type. * * Group: advanced */ default AdvancedElsqlEndpointProducerBuilder prepareStatementStrategy( String prepareStatementStrategy) { doSetProperty("prepareStatementStrategy", prepareStatementStrategy); return this; } /** * Sets whether synchronous processing should be strictly used, or Camel * is allowed to use asynchronous processing (if supported). * * The option is a: <code>boolean</code> type. * * Default: false * Group: advanced */ default AdvancedElsqlEndpointProducerBuilder synchronous( boolean synchronous) { doSetProperty("synchronous", synchronous); return this; } /** * Sets whether synchronous processing should be strictly used, or Camel * is allowed to use asynchronous processing (if supported). * * The option will be converted to a <code>boolean</code> type. * * Default: false * Group: advanced */ default AdvancedElsqlEndpointProducerBuilder synchronous( String synchronous) { doSetProperty("synchronous", synchronous); return this; } /** * Configures the Spring JdbcTemplate with the key/values from the Map. * * The option is a: <code>java.util.Map&lt;java.lang.String, * java.lang.Object&gt;</code> type. * The option is multivalued, and you can use the * templateOptions(String, Object) method to add a value (call the * method multiple times to set more values). * * Group: advanced */ default AdvancedElsqlEndpointProducerBuilder templateOptions( String key, Object value) { doSetMultiValueProperty("templateOptions", "template." + key, value); return this; } /** * Configures the Spring JdbcTemplate with the key/values from the Map. * * The option is a: <code>java.util.Map&lt;java.lang.String, * java.lang.Object&gt;</code> type. * The option is multivalued, and you can use the * templateOptions(String, Object) method to add a value (call the * method multiple times to set more values). * * Group: advanced */ default AdvancedElsqlEndpointProducerBuilder templateOptions(Map values) { doSetMultiValueProperties("templateOptions", "template.", values); return this; } /** * Sets whether to use placeholder and replace all placeholder * characters with sign in the SQL queries. * * The option is a: <code>boolean</code> type. * * Default: true * Group: advanced */ default AdvancedElsqlEndpointProducerBuilder usePlaceholder( boolean usePlaceholder) { doSetProperty("usePlaceholder", usePlaceholder); return this; } /** * Sets whether to use placeholder and replace all placeholder * characters with sign in the SQL queries. * * The option will be converted to a <code>boolean</code> type. * * Default: true * Group: advanced */ default AdvancedElsqlEndpointProducerBuilder usePlaceholder( String usePlaceholder) { doSetProperty("usePlaceholder", usePlaceholder); return this; } } /** * Builder for endpoint for the ElSQL component. */ public interface ElsqlEndpointBuilder extends ElsqlEndpointConsumerBuilder, ElsqlEndpointProducerBuilder { default AdvancedElsqlEndpointBuilder advanced() { return (AdvancedElsqlEndpointBuilder) this; } /** * Whether to allow using named parameters in the queries. * * The option is a: <code>boolean</code> type. * * Default: true * Group: common */ default ElsqlEndpointBuilder allowNamedParameters( boolean allowNamedParameters) { doSetProperty("allowNamedParameters", allowNamedParameters); return this; } /** * Whether to allow using named parameters in the queries. * * The option will be converted to a <code>boolean</code> type. * * Default: true * Group: common */ default ElsqlEndpointBuilder allowNamedParameters( String allowNamedParameters) { doSetProperty("allowNamedParameters", allowNamedParameters); return this; } /** * To use a vendor specific com.opengamma.elsql.ElSqlConfig. * * The option is a: * <code>org.apache.camel.component.elsql.ElSqlDatabaseVendor</code> * type. * * Group: common */ default ElsqlEndpointBuilder databaseVendor( ElSqlDatabaseVendor databaseVendor) { doSetProperty("databaseVendor", databaseVendor); return this; } /** * To use a vendor specific com.opengamma.elsql.ElSqlConfig. * * The option will be converted to a * <code>org.apache.camel.component.elsql.ElSqlDatabaseVendor</code> * type. * * Group: common */ default ElsqlEndpointBuilder databaseVendor(String databaseVendor) { doSetProperty("databaseVendor", databaseVendor); return this; } /** * Sets the DataSource to use to communicate with the database. * * The option is a: <code>javax.sql.DataSource</code> type. * * Group: common */ default ElsqlEndpointBuilder dataSource(Object dataSource) { doSetProperty("dataSource", dataSource); return this; } /** * Sets the DataSource to use to communicate with the database. * * The option will be converted to a <code>javax.sql.DataSource</code> * type. * * Group: common */ default ElsqlEndpointBuilder dataSource(String dataSource) { doSetProperty("dataSource", dataSource); return this; } /** * Sets the reference to a DataSource to lookup from the registry, to * use for communicating with the database. * * The option is a: <code>java.lang.String</code> type. * * Group: common */ @Deprecated default ElsqlEndpointBuilder dataSourceRef(String dataSourceRef) { doSetProperty("dataSourceRef", dataSourceRef); return this; } /** * Specify the full package and class name to use as conversion when * outputType=SelectOne. * * The option is a: <code>java.lang.String</code> type. * * Group: common */ default ElsqlEndpointBuilder outputClass(String outputClass) { doSetProperty("outputClass", outputClass); return this; } /** * Store the query result in a header instead of the message body. By * default, outputHeader == null and the query result is stored in the * message body, any existing content in the message body is discarded. * If outputHeader is set, the value is used as the name of the header * to store the query result and the original message body is preserved. * * The option is a: <code>java.lang.String</code> type. * * Group: common */ default ElsqlEndpointBuilder outputHeader(String outputHeader) { doSetProperty("outputHeader", outputHeader); return this; } /** * Make the output of consumer or producer to SelectList as List of Map, * or SelectOne as single Java object in the following way: a) If the * query has only single column, then that JDBC Column object is * returned. (such as SELECT COUNT( ) FROM PROJECT will return a Long * object. b) If the query has more than one column, then it will return * a Map of that result. c) If the outputClass is set, then it will * convert the query result into an Java bean object by calling all the * setters that match the column names. It will assume your class has a * default constructor to create instance with. d) If the query resulted * in more than one rows, it throws an non-unique result exception. * StreamList streams the result of the query using an Iterator. This * can be used with the Splitter EIP in streaming mode to process the * ResultSet in streaming fashion. * * The option is a: * <code>org.apache.camel.component.sql.SqlOutputType</code> type. * * Default: SelectList * Group: common */ default ElsqlEndpointBuilder outputType(SqlOutputType outputType) { doSetProperty("outputType", outputType); return this; } /** * Make the output of consumer or producer to SelectList as List of Map, * or SelectOne as single Java object in the following way: a) If the * query has only single column, then that JDBC Column object is * returned. (such as SELECT COUNT( ) FROM PROJECT will return a Long * object. b) If the query has more than one column, then it will return * a Map of that result. c) If the outputClass is set, then it will * convert the query result into an Java bean object by calling all the * setters that match the column names. It will assume your class has a * default constructor to create instance with. d) If the query resulted * in more than one rows, it throws an non-unique result exception. * StreamList streams the result of the query using an Iterator. This * can be used with the Splitter EIP in streaming mode to process the * ResultSet in streaming fashion. * * The option will be converted to a * <code>org.apache.camel.component.sql.SqlOutputType</code> type. * * Default: SelectList * Group: common */ default ElsqlEndpointBuilder outputType(String outputType) { doSetProperty("outputType", outputType); return this; } /** * The separator to use when parameter values is taken from message body * (if the body is a String type), to be inserted at # placeholders. * Notice if you use named parameters, then a Map type is used instead. * The default value is comma. * * The option is a: <code>char</code> type. * * Default: , * Group: common */ default ElsqlEndpointBuilder separator(char separator) { doSetProperty("separator", separator); return this; } /** * The separator to use when parameter values is taken from message body * (if the body is a String type), to be inserted at # placeholders. * Notice if you use named parameters, then a Map type is used instead. * The default value is comma. * * The option will be converted to a <code>char</code> type. * * Default: , * Group: common */ default ElsqlEndpointBuilder separator(String separator) { doSetProperty("separator", separator); return this; } } /** * Advanced builder for endpoint for the ElSQL component. */ public interface AdvancedElsqlEndpointBuilder extends AdvancedElsqlEndpointConsumerBuilder, AdvancedElsqlEndpointProducerBuilder { default ElsqlEndpointBuilder basic() { return (ElsqlEndpointBuilder) this; } /** * If enabled then the populateStatement method from * org.apache.camel.component.sql.SqlPrepareStatementStrategy is always * invoked, also if there is no expected parameters to be prepared. When * this is false then the populateStatement is only invoked if there is * 1 or more expected parameters to be set; for example this avoids * reading the message body/headers for SQL queries with no parameters. * * The option is a: <code>boolean</code> type. * * Default: false * Group: advanced */ default AdvancedElsqlEndpointBuilder alwaysPopulateStatement( boolean alwaysPopulateStatement) { doSetProperty("alwaysPopulateStatement", alwaysPopulateStatement); return this; } /** * If enabled then the populateStatement method from * org.apache.camel.component.sql.SqlPrepareStatementStrategy is always * invoked, also if there is no expected parameters to be prepared. When * this is false then the populateStatement is only invoked if there is * 1 or more expected parameters to be set; for example this avoids * reading the message body/headers for SQL queries with no parameters. * * The option will be converted to a <code>boolean</code> type. * * Default: false * Group: advanced */ default AdvancedElsqlEndpointBuilder alwaysPopulateStatement( String alwaysPopulateStatement) { doSetProperty("alwaysPopulateStatement", alwaysPopulateStatement); return this; } /** * Whether the endpoint should use basic property binding (Camel 2.x) or * the newer property binding with additional capabilities. * * The option is a: <code>boolean</code> type. * * Default: false * Group: advanced */ default AdvancedElsqlEndpointBuilder basicPropertyBinding( boolean basicPropertyBinding) { doSetProperty("basicPropertyBinding", basicPropertyBinding); return this; } /** * Whether the endpoint should use basic property binding (Camel 2.x) or * the newer property binding with additional capabilities. * * The option will be converted to a <code>boolean</code> type. * * Default: false * Group: advanced */ default AdvancedElsqlEndpointBuilder basicPropertyBinding( String basicPropertyBinding) { doSetProperty("basicPropertyBinding", basicPropertyBinding); return this; } /** * To use a specific configured ElSqlConfig. It may be better to use the * databaseVendor option instead. * * The option is a: <code>com.opengamma.elsql.ElSqlConfig</code> type. * * Group: advanced */ default AdvancedElsqlEndpointBuilder elSqlConfig(Object elSqlConfig) { doSetProperty("elSqlConfig", elSqlConfig); return this; } /** * To use a specific configured ElSqlConfig. It may be better to use the * databaseVendor option instead. * * The option will be converted to a * <code>com.opengamma.elsql.ElSqlConfig</code> type. * * Group: advanced */ default AdvancedElsqlEndpointBuilder elSqlConfig(String elSqlConfig) { doSetProperty("elSqlConfig", elSqlConfig); return this; } /** * If set greater than zero, then Camel will use this count value of * parameters to replace instead of querying via JDBC metadata API. This * is useful if the JDBC vendor could not return correct parameters * count, then user may override instead. * * The option is a: <code>int</code> type. * * Group: advanced */ default AdvancedElsqlEndpointBuilder parametersCount(int parametersCount) { doSetProperty("parametersCount", parametersCount); return this; } /** * If set greater than zero, then Camel will use this count value of * parameters to replace instead of querying via JDBC metadata API. This * is useful if the JDBC vendor could not return correct parameters * count, then user may override instead. * * The option will be converted to a <code>int</code> type. * * Group: advanced */ default AdvancedElsqlEndpointBuilder parametersCount( String parametersCount) { doSetProperty("parametersCount", parametersCount); return this; } /** * Specifies a character that will be replaced to in SQL query. Notice, * that it is simple String.replaceAll() operation and no SQL parsing is * involved (quoted strings will also change). * * The option is a: <code>java.lang.String</code> type. * * Default: # * Group: advanced */ default AdvancedElsqlEndpointBuilder placeholder(String placeholder) { doSetProperty("placeholder", placeholder); return this; } /** * Allows to plugin to use a custom * org.apache.camel.component.sql.SqlPrepareStatementStrategy to control * preparation of the query and prepared statement. * * The option is a: * <code>org.apache.camel.component.sql.SqlPrepareStatementStrategy</code> type. * * Group: advanced */ default AdvancedElsqlEndpointBuilder prepareStatementStrategy( Object prepareStatementStrategy) { doSetProperty("prepareStatementStrategy", prepareStatementStrategy); return this; } /** * Allows to plugin to use a custom * org.apache.camel.component.sql.SqlPrepareStatementStrategy to control * preparation of the query and prepared statement. * * The option will be converted to a * <code>org.apache.camel.component.sql.SqlPrepareStatementStrategy</code> type. * * Group: advanced */ default AdvancedElsqlEndpointBuilder prepareStatementStrategy( String prepareStatementStrategy) { doSetProperty("prepareStatementStrategy", prepareStatementStrategy); return this; } /** * Sets whether synchronous processing should be strictly used, or Camel * is allowed to use asynchronous processing (if supported). * * The option is a: <code>boolean</code> type. * * Default: false * Group: advanced */ default AdvancedElsqlEndpointBuilder synchronous(boolean synchronous) { doSetProperty("synchronous", synchronous); return this; } /** * Sets whether synchronous processing should be strictly used, or Camel * is allowed to use asynchronous processing (if supported). * * The option will be converted to a <code>boolean</code> type. * * Default: false * Group: advanced */ default AdvancedElsqlEndpointBuilder synchronous(String synchronous) { doSetProperty("synchronous", synchronous); return this; } /** * Configures the Spring JdbcTemplate with the key/values from the Map. * * The option is a: <code>java.util.Map&lt;java.lang.String, * java.lang.Object&gt;</code> type. * The option is multivalued, and you can use the * templateOptions(String, Object) method to add a value (call the * method multiple times to set more values). * * Group: advanced */ default AdvancedElsqlEndpointBuilder templateOptions( String key, Object value) { doSetMultiValueProperty("templateOptions", "template." + key, value); return this; } /** * Configures the Spring JdbcTemplate with the key/values from the Map. * * The option is a: <code>java.util.Map&lt;java.lang.String, * java.lang.Object&gt;</code> type. * The option is multivalued, and you can use the * templateOptions(String, Object) method to add a value (call the * method multiple times to set more values). * * Group: advanced */ default AdvancedElsqlEndpointBuilder templateOptions(Map values) { doSetMultiValueProperties("templateOptions", "template.", values); return this; } /** * Sets whether to use placeholder and replace all placeholder * characters with sign in the SQL queries. * * The option is a: <code>boolean</code> type. * * Default: true * Group: advanced */ default AdvancedElsqlEndpointBuilder usePlaceholder( boolean usePlaceholder) { doSetProperty("usePlaceholder", usePlaceholder); return this; } /** * Sets whether to use placeholder and replace all placeholder * characters with sign in the SQL queries. * * The option will be converted to a <code>boolean</code> type. * * Default: true * Group: advanced */ default AdvancedElsqlEndpointBuilder usePlaceholder( String usePlaceholder) { doSetProperty("usePlaceholder", usePlaceholder); return this; } } /** * Proxy enum for * <code>org.apache.camel.component.elsql.ElSqlDatabaseVendor</code> enum. */ enum ElSqlDatabaseVendor { Default, Postgres, HSql, MySql, Oracle, SqlServer2008, Veritca; } /** * Proxy enum for <code>org.apache.camel.component.sql.SqlOutputType</code> * enum. */ enum SqlOutputType { SelectOne, SelectList, StreamList; } public interface ElsqlBuilders { /** * ElSQL (camel-elsql) * Use ElSql to define SQL queries. Extends the SQL Component. * * Category: database,sql * Since: 2.16 * Maven coordinates: org.apache.camel:camel-elsql * * Syntax: <code>elsql:elsqlName:resourceUri</code> * * Path parameter: elsqlName (required) * The name of the elsql to use (is NAMED in the elsql file) * * Path parameter: resourceUri * The resource file which contains the elsql SQL statements to use. You * can specify multiple resources separated by comma. The resources are * loaded on the classpath by default, you can prefix with file: to load * from file system. Notice you can set this option on the component and * then you do not have to configure this on the endpoint. * * @param path elsqlName:resourceUri */ default ElsqlEndpointBuilder elsql(String path) { return ElsqlEndpointBuilderFactory.endpointBuilder("elsql", path); } /** * ElSQL (camel-elsql) * Use ElSql to define SQL queries. Extends the SQL Component. * * Category: database,sql * Since: 2.16 * Maven coordinates: org.apache.camel:camel-elsql * * Syntax: <code>elsql:elsqlName:resourceUri</code> * * Path parameter: elsqlName (required) * The name of the elsql to use (is NAMED in the elsql file) * * Path parameter: resourceUri * The resource file which contains the elsql SQL statements to use. You * can specify multiple resources separated by comma. The resources are * loaded on the classpath by default, you can prefix with file: to load * from file system. Notice you can set this option on the component and * then you do not have to configure this on the endpoint. * * @param componentName to use a custom component name for the endpoint * instead of the default name * @param path elsqlName:resourceUri */ default ElsqlEndpointBuilder elsql(String componentName, String path) { return ElsqlEndpointBuilderFactory.endpointBuilder(componentName, path); } } static ElsqlEndpointBuilder endpointBuilder( String componentName, String path) { class ElsqlEndpointBuilderImpl extends AbstractEndpointBuilder implements ElsqlEndpointBuilder, AdvancedElsqlEndpointBuilder { public ElsqlEndpointBuilderImpl(String path) { super(componentName, path); } } return new ElsqlEndpointBuilderImpl(path); } }
apache-2.0
sourcerebels/simple-dpi-calculator
app/src/main/java/com/sourcerebels/simpledpicalculator/model/ScreenDensity.java
494
package com.sourcerebels.simpledpicalculator.model; /** * Densities enumeration. */ public enum ScreenDensity { LDPI(0.75f), MDPI(1.0f), HDPI(1.5f), XHDPI(2.0f), XXHDPI(3.0f), XXXHDPI(4.0f); private float mFactor; private ScreenDensity(float factor) { mFactor = factor; } public float getFactor() { return mFactor; } public boolean greaterThan(ScreenDensity other) { return ordinal() > other.ordinal(); } }
apache-2.0
hristobakalov/BeFriendy
app/src/main/java/com/example/LoginActivity.java
8584
package com.example; import android.content.Context; import android.content.Intent; import android.net.ConnectivityManager; import android.net.NetworkInfo; import android.os.AsyncTask; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.text.TextUtils; import android.util.Log; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.Toast; import com.example.EssentialClasses.DatabaseUser; import com.example.EssentialClasses.Player; import com.google.firebase.database.ChildEventListener; import com.google.firebase.database.DataSnapshot; import com.google.firebase.database.DatabaseError; import com.google.firebase.database.DatabaseReference; import com.google.firebase.database.FirebaseDatabase; import java.io.IOException; import java.net.HttpURLConnection; import java.net.URL; import java.util.concurrent.ExecutionException; public class LoginActivity extends AppCompatActivity { private static final String TAG = "AUTH"; EditText emailLogin; EditText passwordLogin; Button buttonLogin; Button buttonCreateAcc; Button buttonForgotPass; private DatabaseReference mDatabase; private final static boolean isValidEmail(CharSequence target) { return !TextUtils.isEmpty(target) && android.util.Patterns.EMAIL_ADDRESS.matcher(target).matches(); } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_login); //initialization of firebase reference mDatabase = FirebaseDatabase.getInstance().getReference(); } @Override protected void onStart() { super.onStart(); //field initialization emailLogin = (EditText) findViewById(R.id.loginEmail); passwordLogin = (EditText) findViewById(R.id.loginPassword); buttonLogin = (Button) findViewById(R.id.loginButton); buttonCreateAcc = (Button) findViewById(R.id.createAccountButton); buttonForgotPass = (Button) findViewById(R.id.forgotPasswordButton); Player.get().getUsers().clear(); mDatabase.child("users").addChildEventListener(new ChildEventListener() { // Retrieve all users as they are in the database @Override public void onChildAdded(DataSnapshot snapshot, String previousChildKey) { DatabaseUser user = snapshot.getValue(DatabaseUser.class); //this is how you parse information from firebase boolean userAlreadyAdded = Player.get().getUser(user.getUserId()) != null; if (!userAlreadyAdded) { Player.get().getUsers().add(user); // add registered user in Reg.Users list } } @Override public void onChildChanged(DataSnapshot dataSnapshot, String s) { } @Override public void onChildRemoved(DataSnapshot dataSnapshot) { } @Override public void onChildMoved(DataSnapshot dataSnapshot, String s) { } @Override public void onCancelled(DatabaseError databaseError) { } }); buttonLogin.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { String typedEmail = emailLogin.getText().toString(); String typedPassword = passwordLogin.getText().toString(); NetworkTesting networkTesting = new NetworkTesting(); try { if (networkTesting.execute().get() == true) { //TODO: Internet connection check by pinging google! //Fields Validation if (typedEmail.isEmpty() || typedPassword.isEmpty()) { //For testing purposes if the fieldImageViews are empty it would log you with test@test.com typedEmail = "test@test.com"; typedPassword = "test"; SignInUser(typedEmail, typedPassword); Toast.makeText(getApplicationContext(), "Logged in with test@test.com", Toast.LENGTH_SHORT).show(); // Toast.makeText(getApplicationContext(), "Please fill in both email and password!", Toast.LENGTH_LONG).show(); } else if (!isValidEmail(typedEmail)) { Toast.makeText(getApplicationContext(), "The email is not valid!", Toast.LENGTH_SHORT).show(); }/* else if (typedPassword.length() < 6) { Toast.makeText(getApplicationContext(), "This password is too short", Toast.LENGTH_LONG).show(); }*/ //so it is easier to develop else if (typedPassword.length() > 19) { Toast.makeText(getApplicationContext(), "This password is too long", Toast.LENGTH_SHORT).show(); } else { //check if the user is registered or not SignInUser(typedEmail, typedPassword); } } else { Toast.makeText(LoginActivity.this, "Your device does not have an internet connection", Toast.LENGTH_LONG).show(); } } catch (InterruptedException e) { e.printStackTrace(); } catch (ExecutionException e) { e.printStackTrace(); } } }); buttonCreateAcc.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent ii = new Intent(getApplicationContext(), RegistrationActivity.class); startActivity(ii); } }); } private void SignInUser(String typedEmail, String typedPassword) { boolean userExists = false; for (DatabaseUser currUser : Player.get().getUsers()) { if (typedEmail.equals(currUser.getEmail()) && typedPassword.equals(currUser.getPassword())) { Player.get().setUserId(currUser.getUserId()); // User initialized from database user-data Player.get().setUserName(currUser.getUserName()); Player.get().setEmailAddress(currUser.getEmail()); Player.get().setUsergameListIds(currUser.getUserGames()); // Player.get().setPassword(currUser.getPassword()); //START SERVICE FOR GAME INFO AND USER INFO startService(new Intent(getApplicationContext(), RetrieveInfoFromDatabase.class)); userExists = true; //Intent intent = new Intent(getApplicationContext(), GameActivity.class); Intent intent = new Intent(getApplicationContext(), GameListActivity.class); startActivity(intent); finish(); break; } } if (!userExists) { Toast.makeText(getApplicationContext(), "Email or password incorrect", Toast.LENGTH_SHORT).show(); } } class NetworkTesting extends AsyncTask<String, Void, Boolean> { private Exception exception; protected Boolean doInBackground(String... xyz) { if (isNetworkAvailable()) { try { HttpURLConnection urlc = (HttpURLConnection) (new URL("http://www.google.com").openConnection()); urlc.setRequestProperty("User-Agent", "Test"); urlc.setRequestProperty("Connection", "close"); urlc.setConnectTimeout(1500); urlc.connect(); return (urlc.getResponseCode() == 200); } catch (IOException e) { Log.e("LoginActivity", "Error checking internet connection", e); } } else { Log.d("LoginActivity", "No network available!"); } return false; } private boolean isNetworkAvailable() { ConnectivityManager connectivityManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE); NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo(); return activeNetworkInfo != null; } } }
apache-2.0
pliskowski/ECJ-2015
cevo-experiments/src/main/java/put/ci/cevo/experiments/ipd/IPDPopulationFactory.java
572
package put.ci.cevo.experiments.ipd; import put.ci.cevo.framework.factories.IndividualFactory; import put.ci.cevo.framework.factories.UniformRandomPopulationFactory; import put.ci.cevo.util.annotations.AccessedViaReflection; public class IPDPopulationFactory extends UniformRandomPopulationFactory<IPDVector> { @AccessedViaReflection public IPDPopulationFactory(IndividualFactory<IPDVector> individualFactory) { super(individualFactory); } @AccessedViaReflection public IPDPopulationFactory(int choices) { super(new IPDVectorIndividualFactory(choices)); } }
apache-2.0
Winis04/STUPS-Toolbox-2.0
src/main/java/GrammarSimulator/Rule.java
2448
package GrammarSimulator; import org.apache.commons.lang.builder.EqualsBuilder; import org.apache.commons.lang.builder.HashCodeBuilder; import java.util.ArrayList; import java.util.Collections; import java.util.List; /** * this class describes a production rule of a formal {@link Grammar}. * Every rule contains a {@link Nonterminal} on the left side, and a list of {@link Symbol}s on the right side. * That means, the toolbox is only capable of describing context free grammars //TODO * @author isabel * @since 22.12.16 */ public final class Rule { private final Nonterminal comingFrom; private final List<Symbol> rightSide; /** * the constructor for the rule * @param comingFrom the left side of the rule * @param rightSide the right side of the rule */ public Rule(Nonterminal comingFrom, List<Symbol> rightSide) { this.comingFrom = comingFrom; this.rightSide = rightSide; } /** * Getter-Method for {@link #comingFrom} * @return a {@link Nonterminal}, the left side of the rule */ public Nonterminal getComingFrom() { return comingFrom; } /** * Getter-Method for {@link #rightSide} * @return a {@link List} of {@link Symbol}s, the right side of the rule. */ public List<Symbol> getRightSide() { return Collections.unmodifiableList(new ArrayList<>(rightSide)); } /** * copy-method * @return a copy of this rule */ public Rule copy() { return new Rule(this.comingFrom,this.rightSide); } @Override public boolean equals(Object obj) { if (obj == null) { return false; } if (obj == this) { return true; } if (obj.getClass() != getClass()) { return false; } Rule rhs = (Rule) obj; if(rhs.rightSide.size() != this.rightSide.size()) { return false; } EqualsBuilder builder = new EqualsBuilder(); builder.append(rhs.comingFrom,this.comingFrom); for(int i=0;i<this.rightSide.size();i++) { builder.append(rhs.rightSide.get(i),this.rightSide.get(i)); } return builder.isEquals(); } @Override public int hashCode() { HashCodeBuilder builder = new HashCodeBuilder(17,31); builder.append(this.comingFrom); this.rightSide.forEach(builder::append); return builder.toHashCode(); } }
apache-2.0
seven332/Stage
demo/src/main/java/com/hippo/stage/demo/scene/ChildDirectorScene.java
1664
/* * Copyright 2017 Hippo Seven * * 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.hippo.stage.demo.scene; /* * Created by Hippo on 5/2/2017. */ import android.support.annotation.NonNull; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import com.hippo.stage.Director; import com.hippo.stage.Stage; import com.hippo.stage.demo.R; public class ChildDirectorScene extends DebugScene { @NonNull @Override protected View onCreateView(@NonNull LayoutInflater inflater, @NonNull ViewGroup container) { final View view = inflater.inflate(R.layout.scene_child_director, container, false); ViewGroup container1 = (ViewGroup) view.findViewById(R.id.stage_layout1); ViewGroup container2 = (ViewGroup) view.findViewById(R.id.stage_layout2); Director director = hireChildDirector(); Stage stage1 = director.direct(container1); if (stage1.getSceneCount() == 0) { stage1.pushScene(new HomeScene()); } Stage stage2 = director.direct(container2); if (stage2.getSceneCount() == 0) { stage2.pushScene(new HomeScene()); } return view; } }
apache-2.0
blackcathacker/kc.preclean
coeus-code/src/main/java/org/kuali/coeus/common/notification/impl/KcNotificationAuthorizationServiceImpl.java
2032
/* * Copyright 2005-2014 The Kuali Foundation * * Licensed under the Educational Community License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.opensource.org/licenses/ecl1.php * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.kuali.coeus.common.notification.impl; import org.kuali.coeus.common.framework.person.KcPerson; import org.kuali.coeus.common.framework.person.KcPersonService; import org.kuali.coeus.sys.framework.auth.UnitAuthorizationService; import org.kuali.rice.krad.util.GlobalVariables; public class KcNotificationAuthorizationServiceImpl implements KcNotificationAuthorizationService { private UnitAuthorizationService unitAuthorizationService; private KcPersonService kcPersonService; @Override public boolean hasPermission(String permissionName){ KcPerson person = kcPersonService.getKcPersonByUserName(getUserName()); return unitAuthorizationService.hasPermission(person.getPersonId(), "KC-NTFCN", permissionName); } protected String getUserName() { return GlobalVariables.getUserSession().getPerson().getPrincipalName(); } /** * * This method inject UnitAuthorizationService * @param unitAuthorizationService */ public void setUnitAuthorizationService(UnitAuthorizationService unitAuthorizationService) { this.unitAuthorizationService = unitAuthorizationService; } /** * * This method inject KcPersonService * @param kcPersonService */ public void setKcPersonService(KcPersonService kcPersonService) { this.kcPersonService = kcPersonService; } }
apache-2.0
andreasaronsson/kataromannumerals
src/test/java/nu/aron/kataromannumerals/RegistryTest.java
686
package nu.aron.kataromannumerals; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; class RegistryTest { Registry registry; @BeforeEach void setUp() { // registry = new Registry(empty()); } @Test void test() { System.err.println("One"); Registry.get().stdout(); Registry.add("first"); System.err.println("Two"); Registry.get().stdout(); Registry.add("second"); Registry.add("third"); System.err.println("Three"); Registry.get().stdout(); Registry.remove("second"); System.err.println("Four"); Registry.get().stdout(); } }
apache-2.0
CloudCIX/cloudcix-java
cloudcix-java/UsageSample/src/HelloWorld.java
4956
/** * Runs through some samples on how to use CloudCIX JAVA SDK. */ import java.util.Map; import java.util.HashMap; import org.json.simple.JSONObject; import cloudcix.base.CloudCIXAuth; import cloudcix.base.Response; import cloudcix.base.Utilities; import cloudcix.api.Auth; import cloudcix.api.Membership; /** * @author CloudCIX developers * */ public class HelloWorld { public static void main(String[] args) { System.out.println("Starting hello world sample."); System.out.println("Getting admin token."); Utilities utilities = new Utilities(); String admin_token = utilities.get_admin_token(); System.out.println("Admin token: " + admin_token); System.out.println("Getting user token."); String user_token = ""; Auth auth_client = new Auth(); CloudCIXAuth credentials = new CloudCIXAuth("user@mail.com", "super53cr3t", "yourIdMember", null); Response response = auth_client.keystone.create(credentials); if (response.code != 201) { System.out.println(response.body.toJSONString()); System.exit(1); } else { user_token = response.headers.get("X-Subject-Token").get(0); } System.out.println("User token: " + user_token); System.out.println("Validate the token."); response = auth_client.keystone.read(admin_token, user_token); if (response.code != 200) { System.out.println(response.body.toJSONString()); System.exit(1); } System.out.println("Token validated."); System.out.println("Read the address."); JSONObject token_data = (JSONObject) response.body.get("token"); JSONObject user_data = (JSONObject) token_data.get("user"); String idAddress = user_data.get("idAddress").toString(); Membership membership_client = new Membership(); response = membership_client.address.read(user_token, idAddress, null, null, null, null); if (response.code != 200) { System.out.println(response.body.toJSONString()); System.exit(1); } System.out.println("Address data: " + response.body.toJSONString()); System.out.println("Create a department."); String idMember = user_data.get("idMember").toString(); JSONObject request = new JSONObject(); request.put("name", "test_create_department"); Map<String, String> path_params = new HashMap<String, String>(); path_params.put("idMember", idMember); response = membership_client.department.create(user_token, request, null, path_params, null); if (response.code != 201) { System.out.println(response.body.toJSONString()); System.exit(1); } System.out.println("Department data: " + response.body.toJSONString()); System.out.println("Update a department."); JSONObject content = (JSONObject) response.body.get("content"); String idDepartment = content.get("idDepartment").toString(); request = new JSONObject(); request.put("name", "test_update_department."); response = membership_client.department.update(user_token, idDepartment, request, null, path_params, null); if (response.code != 200 && response.code != 204) { System.out.println(response.body.toJSONString()); System.exit(1); } if (response.code != 204) System.out.println("Department data: " + response.body.toJSONString()); System.out.println("Read a department."); response = membership_client.department.read(user_token, idDepartment, null, null, path_params, null); if (response.code != 200) { System.out.println(response.body.toJSONString()); System.exit(1); } System.out.println("Department data: " + response.body.toJSONString()); System.out.println("List departments."); response = membership_client.department.list(user_token, null, null, path_params, null); if (response.code != 200) { System.out.println(response.body.toJSONString()); System.exit(1); } System.out.println("Departments data: " + response.body.toJSONString()); System.out.println("Delete department."); response = membership_client.department.delete(user_token, idDepartment, null, null, path_params, null); if (response.code != 204) { System.out.println(response.body.toJSONString()); System.exit(1); } System.out.println("Checking it was deleted."); response = membership_client.department.read(user_token, idDepartment, null, null, path_params, null); if (response.code != 404) { System.out.println(response.body.toJSONString()); System.exit(1); } System.out.println("Response:" + response.body.toJSONString()); System.out.println("Delete user token."); response = auth_client.keystone.delete(admin_token, user_token); if (response.code != 204) { System.out.println(response.body.toJSONString()); System.exit(1); } System.out.println("Checking it was deleted."); response = auth_client.keystone.read(admin_token, user_token); if (response.code != 404) { System.out.println(response.body.toJSONString()); System.exit(1); } System.out.println("Token was deleted."); System.out.println("Hello world sample finished."); } }
apache-2.0
sentinelweb/LanTV
net/src/test/java/co/uk/sentinelweb/lantv/net/smb/SmbShareListInteractorTest.java
2759
package co.uk.sentinelweb.lantv.net.smb; import org.junit.Before; import org.junit.Test; import java.util.List; import co.uk.sentinelweb.lantv.domain.Media; import co.uk.sentinelweb.lantv.net.smb.url.SmbLocationParser; /** * Created by robert on 12/02/2017. */ public class SmbShareListInteractorTest { static { jcifs.Config.registerSmbURLHandler(); } @Before public void setUp() throws Exception { } @Test public void getList() throws Exception { final List<Media> list = new SmbShareListInteractor().getList(TestData.IP_ADDR, TestData.SHARE, TestData.PATH, TestData.USER, TestData.PASS ); if (list != null) { for (final Media m : list) { System.out.println(m.toString()); } } } @Test public void getShareList() throws Exception { final List<Media> list = new SmbShareListInteractor().getList(TestData.IP_ADDR, null, null, TestData.USER, TestData.PASS ); if (list != null) { for (final Media m : list) { System.out.println(m.toString()); } } } @Test public void getNetworkList() throws Exception { final List<Media> list = new SmbShareListInteractor().getList(null, null, null, null, null ); if (list != null) { for (final Media m : list) { System.out.println(m.toString()); } } } @Test public void getWorkgroupList() throws Exception { final List<Media> list = new SmbShareListInteractor().getList("WORKGROUP", null, null, null, null ); if (list != null) { for (final Media m : list) { System.out.println(m.toString()); } } } @Test public void getComputerList() throws Exception { final List<Media> list = new SmbShareListInteractor().getList(new SmbLocationParser().parse("smb://robert:satori@TIGER/")); if (list != null) { for (final Media m : list) { System.out.println(m.toString()); } } } // @Test // public void getFileData() throws Exception { // final SmbLocation location = new SmbLocation("192.168.0.13", "Drobo", "video/movies/superhero/", "dark_knight.iso.mp4",TestData.USER, TestData.PASS);// // final Media m = new SmbShareListInteractor().getList(location ); // System.out.println(m.toString()); // } }
apache-2.0
zhangdaiscott/jeecg-boot
jeecg-boot/jeecg-boot-base/jeecg-boot-base-core/src/main/java/org/jeecg/common/api/dto/FileDownDTO.java
750
package org.jeecg.common.api.dto; import lombok.Data; import javax.servlet.http.HttpServletResponse; import java.io.Serializable; /** * 文件下载 * cloud api 用到的接口传输对象 */ @Data public class FileDownDTO implements Serializable { private static final long serialVersionUID = 6749126258686446019L; private String filePath; private String uploadpath; private String uploadType; private HttpServletResponse response; public FileDownDTO(){} public FileDownDTO(String filePath, String uploadpath, String uploadType,HttpServletResponse response){ this.filePath = filePath; this.uploadpath = uploadpath; this.uploadType = uploadType; this.response = response; } }
apache-2.0
stanioanmihail/PDSDPracticalTest01
OtherExamples/PracticalTest02/src/ro/cs/pub/ro/practicaltest02/PracticalTest02MainActivity.java
3884
package ro.cs.pub.ro.practicaltest02; import android.app.Activity; import android.content.Intent; import android.os.Bundle; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; import android.widget.CheckBox; import android.widget.CompoundButton; import android.widget.CompoundButton.OnCheckedChangeListener; import android.widget.EditText; import android.widget.Toast; public class PracticalTest02MainActivity extends Activity { int number_of_checks; int REQ_CODE_S = 2; EditText numberOfChecks; CheckBox check1, check2, check3; Button navigate; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_practical_test02_main); numberOfChecks = (EditText) findViewById(R.id.edit_text); check1 = (CheckBox) findViewById(R.id.checkbox1); check2 = (CheckBox) findViewById(R.id.checkbox2); check3 = (CheckBox) findViewById(R.id.checkbox3); navigate = (Button) findViewById(R.id.nav_button); if(savedInstanceState != null){ } number_of_checks = 0; numberOfChecks.setText(Integer.toString(number_of_checks)); check1.setOnCheckedChangeListener(new OnCheckedChangeListener() { @Override public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { // TODO Auto-generated method stub if(buttonView.isChecked()){ number_of_checks++; numberOfChecks.setText(Integer.toString(number_of_checks)); }else{ number_of_checks--; numberOfChecks.setText(Integer.toString(number_of_checks)); } } }); check2.setOnCheckedChangeListener(new OnCheckedChangeListener() { @Override public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { // TODO Auto-generated method stub if(buttonView.isChecked()){ number_of_checks++; numberOfChecks.setText(Integer.toString(number_of_checks)); }else{ number_of_checks--; numberOfChecks.setText(Integer.toString(number_of_checks)); } } }); check3.setOnCheckedChangeListener(new OnCheckedChangeListener() { @Override public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { // TODO Auto-generated method stub if(buttonView.isChecked()){ number_of_checks++; numberOfChecks.setText(Integer.toString(number_of_checks)); }else{ number_of_checks--; numberOfChecks.setText(Integer.toString(number_of_checks)); } } }); navigate.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { // TODO Auto-generated method stub String toSend = new String(""); if(check1.isChecked()){ toSend = toSend + "Check1"; } if(check2.isChecked()){ toSend = toSend + "Check2"; } if(check3.isChecked()){ toSend = toSend + "Check3"; } Intent i = new Intent("ro.cs.pub.ro.SECONDARY"); i.putExtra("CheckString", toSend); startActivityForResult(i,REQ_CODE_S); } }); } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.practical_test02_main, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { // Handle action bar item clicks here. The action bar will // automatically handle clicks on the Home/Up button, so long // as you specify a parent activity in AndroidManifest.xml. int id = item.getItemId(); if (id == R.id.action_settings) { return true; } return super.onOptionsItemSelected(item); } @Override protected void onActivityResult(int reqCode, int resultCode, Intent intent){ Toast.makeText(this, "The activity returned with result "+ resultCode, Toast.LENGTH_LONG).show(); } }
apache-2.0
SSEHUB/EASyProducer
Plugins/IVML/de.uni-hildesheim.sse.ivml.comments/src/de/uni_hildesheim/sse/ivml/comments/editor/CommentsEditor.java
555
package de.uni_hildesheim.sse.ivml.comments.editor; import org.eclipse.ui.editors.text.TextEditor; /** * A simple editor for IVML comments. * Currently, this editor does not provide any further capabilities then * editing plain text. * * Implementation based on http://www.ccs.neu.edu/home/lieber/courses/csu670/f05/project/pluginDevExample.pdf * * @author kroeher * */ public class CommentsEditor extends TextEditor { /** * Empty constructor of the comments editor. */ public CommentsEditor() { //super(); } }
apache-2.0
arquillian/arquillian-extension-warp
ftest/src/test/java/org/jboss/arquillian/warp/ftest/commandBus/EnrichTestCase.java
1355
/* * JBoss, Home of Professional Open Source * Copyright 2012, Red Hat Middleware LLC, and individual contributors * by the @authors tag. See the copyright.txt in the distribution for a * full listing of individual contributors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.jboss.arquillian.warp.ftest.commandBus; import static java.lang.annotation.RetentionPolicy.RUNTIME; import java.lang.annotation.Documented; import java.lang.annotation.ElementType; import java.lang.annotation.Inherited; import java.lang.annotation.Retention; import java.lang.annotation.Target; /** * Annotated classes should be enriched by Arquillian dependency injection using {@link TestCaseEnricher} * * @author Lukas Fryc */ @Inherited @Documented @Retention(RUNTIME) @Target({ElementType.TYPE, ElementType.METHOD}) @interface EnrichTestCase { }
apache-2.0
xperimental/garanbot
src/net/sourcewalker/garanbot/account/LoginActivity.java
7931
// // Copyright 2011 Thomas Gumprecht, Robert Jacob, Thomas Pieronczyk // // 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.sourcewalker.garanbot.account; import net.sourcewalker.garanbot.R; import net.sourcewalker.garanbot.api.AuthenticationException; import net.sourcewalker.garanbot.api.ClientException; import net.sourcewalker.garanbot.api.GaranboClient; import net.sourcewalker.garanbot.api.User; import net.sourcewalker.garanbot.data.GaranbotDBMetaData; import android.accounts.Account; import android.accounts.AccountAuthenticatorActivity; import android.accounts.AccountManager; import android.content.ContentResolver; import android.content.Intent; import android.os.AsyncTask; import android.os.Bundle; import android.util.Log; import android.view.View; import android.view.View.OnClickListener; import android.view.Window; import android.widget.Button; import android.widget.EditText; import android.widget.Toast; /** * This activity presents a simple login screen to the user. When he clicks * Login the entered data is validated and if it is correct the next activity is * displayed. If the login was successful this activity should not be reachable * using the back button. This activity will be launched from the * {@link AccountManager} once the account management has been implemented. * * @author Xperimental */ public class LoginActivity extends AccountAuthenticatorActivity implements OnClickListener { public static final String ACTION_ERROR = LoginActivity.class.getName() + ".ERROR"; public static final String TAG = "LoginActivity"; private String accountType; private AccountManager accountManager; private Button loginButton; private Button cancelButton; private Button registerButton; private EditText usernameField; private EditText passwordField; /* * (non-Javadoc) * @see android.app.Activity#onCreate(android.os.Bundle) */ @Override protected void onCreate(final Bundle savedInstanceState) { super.onCreate(savedInstanceState); requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS); setContentView(R.layout.activity_login); accountType = getString(R.string.account_type); accountManager = AccountManager.get(this); loginButton = (Button) findViewById(R.id.login_ok); loginButton.setOnClickListener(this); cancelButton = (Button) findViewById(R.id.login_cancel); cancelButton.setOnClickListener(this); registerButton = (Button) findViewById(R.id.login_register); registerButton.setOnClickListener(this); usernameField = (EditText) findViewById(R.id.login_username); passwordField = (EditText) findViewById(R.id.login_password); if (ACTION_ERROR.equals(getIntent().getAction())) { final Bundle extras = getIntent().getExtras(); if (extras != null) { final String message = extras .getString(AccountManager.KEY_ERROR_MESSAGE); Toast.makeText(this, message, Toast.LENGTH_LONG).show(); } finish(); } } /** * Enable or disable interactive GUI elements in activity. * * @param enabled * If true, elements will be enabled. */ protected void enableGui(final boolean enabled) { loginButton.setEnabled(enabled); cancelButton.setEnabled(enabled); registerButton.setEnabled(enabled); usernameField.setEnabled(enabled); passwordField.setEnabled(enabled); } /** * Create the account in the account manager. * * @param username * Username of new account. * @param password * Password of new account. */ public void createAccount(final String username, final String password) { final Account account = new Account(username, accountType); final boolean created = accountManager.addAccountExplicitly(account, password, null); if (created) { final Bundle result = new Bundle(); result.putString(AccountManager.KEY_ACCOUNT_NAME, username); result.putString(AccountManager.KEY_ACCOUNT_TYPE, accountType); setAccountAuthenticatorResult(result); ContentResolver.setSyncAutomatically(account, GaranbotDBMetaData.AUTHORITY, true); finish(); } else { Toast.makeText(this, R.string.toast_account_createfailed, Toast.LENGTH_LONG).show(); } } /* * (non-Javadoc) * @see android.view.View.OnClickListener#onClick(android.view.View) */ public void onClick(final View v) { switch (v.getId()) { case R.id.login_ok: final String username = usernameField.getText().toString(); final String password = passwordField.getText().toString(); final CredentialsTestTask task = new CredentialsTestTask(); task.execute(username, password); break; case R.id.login_cancel: finish(); break; case R.id.login_register: final Intent registerActivity = new Intent(this, RegisterActivity.class); startActivity(registerActivity); break; default: throw new IllegalArgumentException("Unknown view clicked: " + v); } } private class CredentialsTestTask extends AsyncTask<String, Void, LoginParcel> { /* * (non-Javadoc) * @see android.os.AsyncTask#onPreExecute() */ @Override protected void onPreExecute() { setProgressBarIndeterminateVisibility(true); enableGui(false); } /* * (non-Javadoc) * @see android.os.AsyncTask#doInBackground(Params[]) */ @Override protected LoginParcel doInBackground(final String... params) { final String username = params[0]; final String password = params[1]; final GaranboClient client = new GaranboClient(username, password); Boolean result; try { final User serverUser = client.user().get(); result = username.equalsIgnoreCase(serverUser.getUsername()); } catch (final AuthenticationException e) { // Wrong password etc. result = false; } catch (final ClientException e) { // Other reason for failing (e.g. network). Log.e(TAG, "Error while logging in: " + e.getMessage()); result = false; } return new LoginParcel(username, password, result); } /* * (non-Javadoc) * @see android.os.AsyncTask#onPostExecute(java.lang.Object) */ @Override protected void onPostExecute(final LoginParcel result) { setProgressBarIndeterminateVisibility(false); enableGui(true); if (result.successful) { createAccount(result.username, result.password); } else { Toast.makeText(LoginActivity.this, R.string.toast_loginfailed, Toast.LENGTH_LONG).show(); } } } }
apache-2.0
ubluer/XiangOA
src/main/java/com/thinkgem/jeesite/modules/sys/security/FormAuthenticationFilter.java
4562
/** * Copyright &copy; 2012-2016 <a href="https://github.com/thinkgem/jeesite">JeeSite</a> All rights reserved. */ package com.thinkgem.jeesite.modules.sys.security; import com.thinkgem.jeesite.common.utils.StringUtils; import org.apache.shiro.authc.AuthenticationException; import org.apache.shiro.authc.AuthenticationToken; import org.apache.shiro.authc.IncorrectCredentialsException; import org.apache.shiro.authc.UnknownAccountException; import org.apache.shiro.web.util.WebUtils; import org.springframework.stereotype.Service; import javax.servlet.ServletRequest; import javax.servlet.ServletResponse; import javax.servlet.http.HttpServletRequest; /** * 表单验证(包含验证码)过滤类 * @author ThinkGem * @version 2014-5-19 */ @Service public class FormAuthenticationFilter extends org.apache.shiro.web.filter.authc.FormAuthenticationFilter { public static final String DEFAULT_CAPTCHA_PARAM = "validateCode"; public static final String DEFAULT_MOBILE_PARAM = "mobileLogin"; public static final String DEFAULT_MESSAGE_PARAM = "message"; private String captchaParam = DEFAULT_CAPTCHA_PARAM; private String mobileLoginParam = DEFAULT_MOBILE_PARAM; private String messageParam = DEFAULT_MESSAGE_PARAM; public AuthenticationToken createToken(ServletRequest request, ServletResponse response) { String username = getUsername(request); String password = getPassword(request); if (password==null){ password = ""; } boolean rememberMe = isRememberMe(request); String host = StringUtils.getRemoteAddr((HttpServletRequest)request); String captcha = getCaptcha(request); boolean mobile = isMobileLogin(request); return new UsernamePasswordToken(username, password.toCharArray(), rememberMe, host, captcha, mobile); } /** * 获取登录用户名 */ protected String getUsername(ServletRequest request, ServletResponse response) { String username = super.getUsername(request); if (StringUtils.isBlank(username)){ username = StringUtils.toString(request.getAttribute(getUsernameParam()), StringUtils.EMPTY); } return username; } /** * 获取登录密码 */ @Override protected String getPassword(ServletRequest request) { String password = super.getPassword(request); if (StringUtils.isBlank(password)){ password = StringUtils.toString(request.getAttribute(getPasswordParam()), StringUtils.EMPTY); } return password; } /** * 获取记住我 */ @Override protected boolean isRememberMe(ServletRequest request) { String isRememberMe = WebUtils.getCleanParam(request, getRememberMeParam()); if (StringUtils.isBlank(isRememberMe)){ isRememberMe = StringUtils.toString(request.getAttribute(getRememberMeParam()), StringUtils.EMPTY); } return StringUtils.toBoolean(isRememberMe); } public String getCaptchaParam() { return captchaParam; } protected String getCaptcha(ServletRequest request) { return WebUtils.getCleanParam(request, getCaptchaParam()); } public String getMobileLoginParam() { return mobileLoginParam; } protected boolean isMobileLogin(ServletRequest request) { return WebUtils.isTrue(request, getMobileLoginParam()); } public String getMessageParam() { return messageParam; } /** * 登录成功之后跳转URL */ public String getSuccessUrl() { return super.getSuccessUrl(); } @Override protected void issueSuccessRedirect(ServletRequest request, ServletResponse response) throws Exception { // Principal p = UserUtils.getPrincipal(); // if (p != null && !p.isMobileLogin()){ WebUtils.issueRedirect(request, response, getSuccessUrl(), null, true); // }else{ // super.issueSuccessRedirect(request, response); // } } /** * 登录失败调用事件 */ @Override protected boolean onLoginFailure(AuthenticationToken token, AuthenticationException e, ServletRequest request, ServletResponse response) { String className = e.getClass().getName(), message = ""; if (IncorrectCredentialsException.class.getName().equals(className) || UnknownAccountException.class.getName().equals(className)){ message = "用户或密码错误, 请重试."; } else if (e.getMessage() != null && StringUtils.startsWith(e.getMessage(), "msg:")){ message = StringUtils.replace(e.getMessage(), "msg:", ""); } else{ message = "系统出现点问题,请稍后再试!"; e.printStackTrace(); // 输出到控制台 } request.setAttribute(getFailureKeyAttribute(), className); request.setAttribute(getMessageParam(), message); return true; } }
apache-2.0
Yoyun/MvpDouBan
app/src/main/java/com/soulin/mvpdouban/data/DataManager.java
1591
package com.soulin.mvpdouban.data; import com.soulin.mvpdouban.data.local.DatabaseHelper; import com.soulin.mvpdouban.data.local.PreferencesHelper; import com.soulin.mvpdouban.data.model.Movie; import com.soulin.mvpdouban.data.model.MovieList; import com.soulin.mvpdouban.data.remote.MoviesService; import java.util.List; import javax.inject.Inject; import javax.inject.Singleton; import rx.Observable; import rx.functions.Func1; /** * Created by Soulin on 2017/1/18. */ @Singleton public class DataManager { private final MoviesService mMoviesService; private final DatabaseHelper mDatabaseHelper; private final PreferencesHelper mPreferencesHelper; @Inject public DataManager(MoviesService mMoviesService, DatabaseHelper mDatabaseHelper, PreferencesHelper mPreferencesHelper) { this.mMoviesService = mMoviesService; this.mDatabaseHelper = mDatabaseHelper; this.mPreferencesHelper = mPreferencesHelper; } public PreferencesHelper getmPreferencesHelper() { return mPreferencesHelper; } public Observable<Movie> syncMovies() { return mMoviesService.getMovies(0, 66) .concatMap(new Func1<MovieList, Observable<Movie>>() { @Override public Observable<Movie> call(MovieList movieList) { return mDatabaseHelper.setMovies(movieList.subjects()); } }); } public Observable<List<Movie>> getMovies() { return mDatabaseHelper.getMovies().distinct(); } }
apache-2.0
apparentlymart/shindig
java/gadgets/src/test/java/org/apache/shindig/gadgets/parse/caja/VanillaCajaHtmlSerializerTest.java
2679
/** * 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.shindig.gadgets.parse.caja; import org.junit.Before; import org.junit.Test; import org.w3c.dom.DOMImplementation; import org.w3c.dom.bootstrap.DOMImplementationRegistry; import static org.junit.Assert.assertEquals; /** * Tests for VanillaCajaHtmlSerializer. */ public class VanillaCajaHtmlSerializerTest { private VanillaCajaHtmlParser parser; private VanillaCajaHtmlSerializer serializer; @Before public void setUp() throws Exception { DOMImplementationRegistry registry = DOMImplementationRegistry.newInstance(); // Require the traversal API DOMImplementation domImpl = registry.getDOMImplementation("XML 1.0 Traversal 2.0"); parser = new VanillaCajaHtmlParser(domImpl, true); serializer = new VanillaCajaHtmlSerializer(); } @Test public void testParseAndSerializeNonASCIINotEscaped() throws Exception { String html = "<html><head><script src=\"1.js\"></script></head>" + "<body><a href=\"hello\">\\u200E\\u200F\\u2010\\u0410</a>" + "</body></html>"; assertEquals(html, serializer.serialize(parser.parseDom(html))); } @Test public void testParseAndSerializeCommentsNotRemoved() throws Exception { String html = "<html><head><script src=\"1.js\"></script></head>" + "<body><div>before <!-- Test Data --> after \n" + "<!-- [if IE ]>" + "<link href=\"iecss.css\" rel=\"stylesheet\" type=\"text/css\">" + "<![endif]-->" + "</div></body></html>"; // If we run the serializer with wantsComments set to false, all comments are removed from the // serialized html and the output is: // "<html><head><script src=\"1.js\"></script></head>" // + "<body><div>" // + "</div></body></html>" assertEquals(html, serializer.serialize(parser.parseDom(html))); } }
apache-2.0
talent518/zxing
src/com/google/zxing/aztec/AztecDetectorResult.java
1317
/* * Copyright 2010 ZXing authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.zxing.aztec; import com.google.zxing.ResultPoint; import com.google.zxing.common.BitMatrix; import com.google.zxing.common.DetectorResult; public final class AztecDetectorResult extends DetectorResult { private final boolean compact; private final int nbDatablocks; private final int nbLayers; public AztecDetectorResult(BitMatrix bits, ResultPoint[] points, boolean compact, int nbDatablocks, int nbLayers) { super(bits, points); this.compact = compact; this.nbDatablocks = nbDatablocks; this.nbLayers = nbLayers; } public int getNbLayers() { return nbLayers; } public int getNbDatablocks() { return nbDatablocks; } public boolean isCompact() { return compact; } }
apache-2.0
zhangchuanchuan/coolweather
src/com/coolweather/app/db/CoolWeatherDB.java
2935
package com.coolweather.app.db; import java.util.ArrayList; import java.util.List; import android.content.ContentValues; import android.content.Context; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import com.coolweather.app.model.City; import com.coolweather.app.model.Province; public class CoolWeatherDB { /** * Êý¾ÝÃû£¬Ãû³ÆÎª£ºcool_weather */ public static final String DB_NAME = "cool_weather"; /** * Êý¾Ý¿â°æ±¾£¬µ±Ç°°æ±¾ÊÇ1 */ public static final int VERSION = 1; private static CoolWeatherDB coolWeatherDB; private SQLiteDatabase db; /** * ½«¹¹Ôì˽Óл¯ */ private CoolWeatherDB(Context context){ CoolWeatherOpenHelper dbHelper = new CoolWeatherOpenHelper(context, DB_NAME, null, VERSION); db = dbHelper.getWritableDatabase(); } /** * µ¥Àýģʽ£¬»ñÈ¡CoolWeatherDBʵÀý */ public synchronized static CoolWeatherDB getInstance(Context context){ if(coolWeatherDB==null){ coolWeatherDB = new CoolWeatherDB(context); } return coolWeatherDB; } /** * ½«ProvinceʵÀý´æ´¢µ½Êý¾Ý¿â */ public void saveProvince(Province province){ if(province!=null){ ContentValues values = new ContentValues(); values.put("province_name", province.getProvinceName()); values.put("province_code", province.getProvinceCode()); db.insert("Province", null, values); } } /** * ´ÓÊý¾Ý¿âÖжÁȡʡ·ÝÐÅÏ¢ */ public List<Province> loadProvinces(){ List<Province> list = new ArrayList<Province>(); Cursor cursor = db.query("Province", null, null, null, null, null, null); while(cursor.moveToNext()){ Province province = new Province(); province.setId(cursor.getInt(cursor.getColumnIndex("id"))); province.setProvinceName(cursor.getString(cursor.getColumnIndex("province_name"))); province.setProvinceCode(cursor.getString(cursor.getColumnIndex("province_code"))); list.add(province); } if(cursor!=null){ cursor.close(); } return list; } /** * ½«CityʵÀý´æ´¢µ½Êý¾Ý¿â */ public void saveCity(City city){ if(city!=null){ ContentValues values = new ContentValues(); values.put("city_name", city.getCityName()); values.put("city_code", city.getCityCode()); values.put("province_id", city.getProvinceId()); db.insert("City", null, values); } } /** * ¶Áȡij¸öÊ¡·ÝµÄËùÓгÇÊÐÐÅÏ¢ */ public List<City> loadCities(int provinceId){ List<City> list = new ArrayList<City>(); Cursor cursor = db.query("City", null, "province_id=?", new String[]{String.valueOf(provinceId)}, null, null, null); while(cursor.moveToNext()){ City city = new City(); city.setId(cursor.getInt(cursor.getColumnIndex("id"))); city.setCityName(cursor.getString(cursor.getColumnIndex("city_name"))); city.setCityCode(cursor.getString(cursor.getColumnIndex("city_code"))); city.setProvinceId(provinceId); list.add(city); } if(cursor!=null){ cursor.close(); } return list; } }
apache-2.0
DeadManPoe/AFOSpaceProject
src/main/java/server/SocketThread.java
2029
package server; import java.io.IOException; import java.lang.reflect.InvocationTargetException; import java.net.Socket; import java.util.logging.Level; /** * Represents a thread that handles a request by a client in the logic of the * client server pattern * * @author Andrea Sessa * @author Giorgio Pea * @version 1.0 */ public class SocketThread extends Thread { // The server this thread refers to private MainServer server; // The socket used to handle the client's request private Socket socket; /** * Constructs a thread that handles a request by a client in the logic of * the client server pattern. This thread is constructed from a server and a * socket that represents the client itself and that will be used to handle * the client's request * * @param server * the server this thread refers to * @param socket * the socket this thread uses to handle the client's request and * that represents the client itself */ public SocketThread(MainServer server, Socket socket) { this.server = server; this.socket = socket; } /** * Runs the thread. The thread handles the client's request by receiving the * client data, processing it and invoking on the client a remote method, * all is done through a {@link SocketRemoteDataExchange} * * @see SocketRemoteDataExchange */ public void run() { SocketRemoteDataExchange dataExchange; try { // Client's request handling dataExchange = new SocketRemoteDataExchange(server, socket); server.setSocketDataExchange(dataExchange); dataExchange.receiveData(); } catch (ClassNotFoundException | IllegalAccessException | IllegalArgumentException | InvocationTargetException | NoSuchMethodException | SecurityException e) { ServerLogger.getLogger().log(Level.SEVERE, "Could not perform action | SocketThread", e); } catch (IOException e) { ServerLogger.getLogger().log(Level.SEVERE, "Could not communicate with the client | SocketThread", e); } } }
apache-2.0
quarkusio/quarkus
independent-projects/resteasy-reactive/client/runtime/src/main/java/org/jboss/resteasy/reactive/client/impl/DefaultClientContext.java
1815
package org.jboss.resteasy.reactive.client.impl; import io.vertx.core.Vertx; import java.util.Collections; import java.util.Map; import java.util.function.Supplier; import javax.ws.rs.RuntimeType; import org.jboss.resteasy.reactive.client.spi.ClientContext; import org.jboss.resteasy.reactive.client.spi.ClientContextResolver; import org.jboss.resteasy.reactive.client.spi.MultipartResponseData; import org.jboss.resteasy.reactive.common.core.GenericTypeMapping; public class DefaultClientContext implements ClientContext { public static DefaultClientContext INSTANCE = new DefaultClientContext(); public static final ClientContextResolver RESOLVER = new ClientContextResolver() { @Override public ClientContext resolve(ClassLoader classLoader) { return INSTANCE; } }; final GenericTypeMapping genericTypeMapping; final ClientSerialisers serialisers; final ClientProxies clientProxies; public DefaultClientContext() { serialisers = new ClientSerialisers(); serialisers.registerBuiltins(RuntimeType.CLIENT); clientProxies = new ClientProxies(Collections.emptyMap(), Collections.emptyMap()); genericTypeMapping = new GenericTypeMapping(); } @Override public ClientSerialisers getSerialisers() { return serialisers; } @Override public GenericTypeMapping getGenericTypeMapping() { return genericTypeMapping; } @Override public Supplier<Vertx> getVertx() { return null; } @Override public ClientProxies getClientProxies() { return clientProxies; } @Override public Map<Class<?>, MultipartResponseData> getMultipartResponsesData() { return Collections.emptyMap(); // supported in quarkus only at the moment } }
apache-2.0
mmberg/nadia
src/net/mmberg/nadia/processor/dialogmodel/aqd/AQDContext.java
312
package net.mmberg.nadia.processor.dialogmodel.aqd; import net.mmberg.nadia.dialogmodel.definition.aqd.AQDContextModel; public class AQDContext extends AQDContextModel{ public AQDContext(){ super(); } public AQDContext(String specification, String reference){ super(specification, reference); } }
apache-2.0
sequenceiq/cloudbreak
core/src/main/java/com/sequenceiq/cloudbreak/service/stack/repair/StackRepairService.java
4618
package com.sequenceiq.cloudbreak.service.stack.repair; import java.util.Set; import java.util.concurrent.ExecutorService; import javax.inject.Inject; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.stereotype.Component; import com.sequenceiq.cloudbreak.api.model.Status; import com.sequenceiq.cloudbreak.controller.FlowsAlreadyRunningException; import com.sequenceiq.cloudbreak.core.flow2.service.ReactorFlowManager; import com.sequenceiq.cloudbreak.core.flow2.stack.FlowMessageService; import com.sequenceiq.cloudbreak.core.flow2.stack.Msg; import com.sequenceiq.cloudbreak.domain.HostMetadata; import com.sequenceiq.cloudbreak.domain.InstanceMetaData; import com.sequenceiq.cloudbreak.domain.Stack; import com.sequenceiq.cloudbreak.repository.HostMetadataRepository; import com.sequenceiq.cloudbreak.repository.InstanceMetaDataRepository; @Component public class StackRepairService { private static final Logger LOGGER = LoggerFactory.getLogger(StackRepairService.class); @Inject private FlowMessageService flowMessageService; @Inject private InstanceMetaDataRepository instanceMetaDataRepository; @Inject private HostMetadataRepository hostMetadataRepository; @Inject private ReactorFlowManager reactorFlowManager; @Inject private ExecutorService executorService; public void add(Stack stack, Set<String> unhealthyInstanceIds) { if (unhealthyInstanceIds.isEmpty()) { LOGGER.warn("No instances are unhealthy, returning..."); flowMessageService.fireEventAndLog(stack.getId(), Msg.STACK_REPAIR_COMPLETE_CLEAN, Status.AVAILABLE.name()); return; } UnhealthyInstances unhealthyInstances = groupInstancesByHostGroups(stack, unhealthyInstanceIds); StackRepairFlowSubmitter stackRepairFlowSubmitter = new StackRepairFlowSubmitter(stack.getId(), unhealthyInstances); flowMessageService.fireEventAndLog(stack.getId(), Msg.STACK_REPAIR_ATTEMPTING, Status.UPDATE_IN_PROGRESS.name()); executorService.submit(stackRepairFlowSubmitter); } private UnhealthyInstances groupInstancesByHostGroups(Stack stack, Set<String> unhealthyInstanceIds) { UnhealthyInstances unhealthyInstances = new UnhealthyInstances(); for (String instanceId : unhealthyInstanceIds) { InstanceMetaData instanceMetaData = instanceMetaDataRepository.findByInstanceId(stack.getId(), instanceId); HostMetadata hostMetadata = hostMetadataRepository.findHostInClusterByName(stack.getCluster().getId(), instanceMetaData.getDiscoveryFQDN()); String hostGroupName = hostMetadata.getHostGroup().getName(); unhealthyInstances.addInstance(instanceId, hostGroupName); } return unhealthyInstances; } class StackRepairFlowSubmitter implements Runnable { private static final int RETRIES = 10; private static final int SLEEP_TIME_MS = 1000; private final Long stackId; private final UnhealthyInstances unhealthyInstances; StackRepairFlowSubmitter(Long stackId, UnhealthyInstances unhealthyInstances) { this.stackId = stackId; this.unhealthyInstances = unhealthyInstances; } public Long getStackId() { return stackId; } public UnhealthyInstances getUnhealthyInstances() { return unhealthyInstances; } @Override public void run() { boolean submitted = false; int trials = 0; while (!submitted) { try { reactorFlowManager.triggerStackRepairFlow(stackId, unhealthyInstances); flowMessageService.fireEventAndLog(stackId, Msg.STACK_REPAIR_TRIGGERED, Status.UPDATE_IN_PROGRESS.name()); submitted = true; } catch (FlowsAlreadyRunningException fare) { trials++; if (trials == RETRIES) { LOGGER.error("Could not submit because other flows are running for stack " + stackId); return; } LOGGER.info("Waiting for other flows of stack " + stackId + " to complete."); try { Thread.sleep(SLEEP_TIME_MS); } catch (InterruptedException e) { LOGGER.error("Interrupted while waiting for other flows to finish.", e); return; } } } } } }
apache-2.0
jenkinsci/google-cloud-backup-plugin
src/main/java/com/google/jenkins/plugins/cloudbackup/initiation/NoActionInitiationStrategy.java
1402
/* * Copyright 2015 Google 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.google.jenkins.plugins.cloudbackup.initiation; import java.io.IOException; import java.nio.file.Path; import java.util.logging.Logger; /** * No-op initiation strategy. */ public class NoActionInitiationStrategy implements InitiationStrategy { private static final Logger logger = Logger.getLogger(NoActionInitiationStrategy.class.getName()); @Override public void initializeNewEnvironment(Path jenkinsHome) throws IOException { logger.fine("Initializing new environment (taking no action)."); } @Override public void initializeRestoredEnvironment(Path jenkinsHome, String lastBackupId) throws IOException { logger.fine("Last backup id: " + lastBackupId); logger.fine("Initializing restored environment (taking no action)."); } }
apache-2.0
nelenkov/wwwjdic
wwwjdic/src/org/nick/wwwjdic/client/GzipStringResponseHandler.java
1897
/** * */ package org.nick.wwwjdic.client; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.util.zip.GZIPInputStream; import org.apache.http.Header; import org.apache.http.HttpEntity; import org.apache.http.HttpResponse; import org.apache.http.HttpStatus; import org.apache.http.client.ClientProtocolException; import org.apache.http.client.ResponseHandler; import org.apache.http.util.EntityUtils; public class GzipStringResponseHandler implements ResponseHandler<String> { public String handleResponse(HttpResponse response) throws ClientProtocolException, IOException { HttpEntity entity = response.getEntity(); if (response.getStatusLine().getStatusCode() != HttpStatus.SC_OK) { if (entity != null) { entity.consumeContent(); } throw new RuntimeException("Server error: " + response.getStatusLine()); } Header contentEncoding = response.getFirstHeader("Content-Encoding"); String responseStr = null; if (contentEncoding != null && contentEncoding.getValue().equalsIgnoreCase("gzip")) { GZIPInputStream is = new GZIPInputStream(entity.getContent()); try { ByteArrayOutputStream arr = new ByteArrayOutputStream(); byte[] buff = new byte[1024]; int len; while ((len = is.read(buff)) > 0) { arr.write(buff, 0, len); } responseStr = new String(arr.toByteArray(), "UTF-8"); } finally { is.close(); } } else { if (entity != null) { responseStr = EntityUtils.toString(entity); } } return responseStr; } }
apache-2.0
sigmoidanalytics/spork-streaming
src/org/apache/pig/backend/hadoop/executionengine/spark_streaming/converter/FilterConverter.java
2409
package org.apache.pig.backend.hadoop.executionengine.spark_streaming.converter; import java.io.Serializable; import java.util.List; import org.apache.pig.backend.executionengine.ExecException; import org.apache.pig.backend.hadoop.executionengine.physicalLayer.POStatus; import org.apache.pig.backend.hadoop.executionengine.physicalLayer.Result; import org.apache.pig.backend.hadoop.executionengine.physicalLayer.relationalOperators.POFilter; import org.apache.pig.backend.hadoop.executionengine.spark_streaming.SparkUtil; import org.apache.pig.data.Tuple; import scala.runtime.AbstractFunction1; import org.apache.spark.rdd.RDD; import org.apache.spark.streaming.api.java.JavaDStream; /** * Converter that converts an RDD to a filtered RRD using POFilter * @author billg */ @SuppressWarnings({ "serial"}) public class FilterConverter implements POConverter<Tuple, Tuple, POFilter> { @Override public JavaDStream<Tuple> convert(List<JavaDStream<Tuple>> predecessors, POFilter physicalOperator) { SparkUtil.assertPredecessorSize(predecessors, physicalOperator, 1); JavaDStream<Tuple> rdd = predecessors.get(0); FilterFunction filterFunction = new FilterFunction(physicalOperator); return new JavaDStream<Tuple>(rdd.dstream().filter(filterFunction),SparkUtil.getManifest(Tuple.class)); } private static class FilterFunction extends AbstractFunction1<Tuple, Object> implements Serializable { private POFilter poFilter; private FilterFunction(POFilter poFilter) { this.poFilter = poFilter; } @Override public Boolean apply(Tuple v1) { Result result; try { poFilter.setInputs(null); poFilter.attachInput(v1); result = poFilter.getNextTuple(); } catch (ExecException e) { throw new RuntimeException("Couldn't filter tuple", e); } if (result == null) { return false; } switch (result.returnStatus) { case POStatus.STATUS_OK: return true; case POStatus.STATUS_EOP: // TODO: probably also ok for EOS, END_OF_BATCH return false; default: throw new RuntimeException("Unexpected response code from filter: " + result); } } } }
apache-2.0
Jeson2016/ocr-ball
OcrBall/app/src/main/java/com/android/ocrball/OcrBallService.java
2016
package com.android.ocrball; import android.app.Service; import android.content.Context; import android.content.Intent; import android.graphics.PixelFormat; import android.os.IBinder; import android.util.Log; import android.view.Gravity; import android.view.LayoutInflater; import android.view.MotionEvent; import android.view.View; import android.view.ViewConfiguration; import android.view.WindowManager; import android.widget.FrameLayout; import com.android.ocrball.manager.MyWindowManager; import com.android.ocrball.view.OcrBallView; import java.lang.ref.SoftReference; /** * This service is use to support ocr ball running background * Created by admin on 2016/12/07 . */ public class OcrBallService extends Service{ private static final String TAG = "OcrBallService"; private static final boolean DEBUG = true || Log.isLoggable(TAG, Log.DEBUG); @Override public IBinder onBind(Intent intent) { if(DEBUG) Log.i(TAG,"onBind"); return mBinder; } @Override public int onStartCommand(Intent intent, int flags, int startId) { if(DEBUG) Log.i(TAG,"onStartCommand"); createView(); return super.onStartCommand(intent, flags, startId); } @Override public void onCreate() { super.onCreate(); if(DEBUG) Log.i(TAG,"onCreate"); } private void createView(){ if(DEBUG) Log.i(TAG,"createView"); MyWindowManager.createFloatBallView(getApplicationContext()); } private final IBinder mBinder = new ServiceStub(this); static class ServiceStub extends IOcrBallService.Stub{ //changing weak ref to softref to prevent media playercrash SoftReference<OcrBallService> mService; ServiceStub(OcrBallService service) { mService = new SoftReference<OcrBallService>(service); } public void createView(){ mService.get().createView(); } } }
apache-2.0
lumeng689/luapp
practise/src/main/java/org/luapp/practise/mqtt/HelloMqtt.java
1915
package org.luapp.practise.mqtt; import org.fusesource.mqtt.client.*; import java.net.URISyntaxException; import java.util.concurrent.TimeUnit; /** * Created by lum on 2015/7/1. */ public class HelloMqtt { public static void main(String[] args) throws Exception { new Thread(new Runnable() { @Override public void run() { try { MQTT mqtt = new MQTT(); mqtt.setHost("localhost", 1883); BlockingConnection connection = mqtt.blockingConnection(); connection.connect(); Topic[] topics = {new Topic("topic", QoS.AT_LEAST_ONCE)}; byte[] qoses = connection.subscribe(topics); while (true) { System.out.println("......"); TimeUnit.SECONDS.sleep(3); Message message = connection.receive(); System.out.println("received topic: " + message.getTopic()); byte[] payload = message.getPayload(); System.out.println("received content: " + new String(payload, "utf-8")); message.ack(); } } catch (Exception e) { e.printStackTrace(); } finally { } } }).start(); MQTT mqtt = new MQTT(); mqtt.setHost("localhost", 1883); BlockingConnection connection = mqtt.blockingConnection(); connection.connect(); int i = 0; while(true) { System.out.println("publish......"); connection.publish("topic", ("hello" + i++).getBytes(), QoS.AT_LEAST_ONCE, false); TimeUnit.SECONDS.sleep(3); } // connection.disconnect(); // Thread.currentThread().join(); } }
apache-2.0
lvweiwolf/poi-3.16
src/testcases/org/apache/poi/ss/formula/EvaluationListener.java
2276
/* ==================================================================== 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.poi.ss.formula; import org.apache.poi.ss.formula.eval.ValueEval; /** * Tests should extend this class if they need to track the internal working of the {@link WorkbookEvaluator}.<br/> * * Default method implementations all do nothing * * @author Josh Micich */ public abstract class EvaluationListener implements IEvaluationListener { @Override public void onCacheHit(int sheetIndex, int rowIndex, int columnIndex, ValueEval result) { // do nothing } @Override public void onReadPlainValue(int sheetIndex, int rowIndex, int columnIndex, ICacheEntry entry) { // do nothing } @Override public void onStartEvaluate(EvaluationCell cell, ICacheEntry entry) { // do nothing } @Override public void onEndEvaluate(ICacheEntry entry, ValueEval result) { // do nothing } @Override public void onClearWholeCache() { // do nothing } @Override public void onClearCachedValue(ICacheEntry entry) { // do nothing } @Override public void onChangeFromBlankValue(int sheetIndex, int rowIndex, int columnIndex, EvaluationCell cell, ICacheEntry entry) { // do nothing } @Override public void sortDependentCachedValues(ICacheEntry[] entries) { // do nothing } @Override public void onClearDependentCachedValue(ICacheEntry entry, int depth) { // do nothing } }
apache-2.0
MarekMatejkaKCL/Events
app/src/main/java/mm/events/FBListEventDetailActivity.java
2718
package mm.events; import android.content.Intent; import android.os.Bundle; import android.app.Activity; import android.support.v7.app.ActionBarActivity; import android.view.MenuItem; /** * An activity representing a single FBListEvent detail screen. This * activity is only used on handset devices. On tablet-size devices, * item details are presented side-by-side with a list of items * in a {@link FBListEventListActivity}. * <p/> * This activity is mostly just a 'shell' activity containing nothing * more than a {@link FBListEventDetailFragment}. */ public class FBListEventDetailActivity extends ActionBarActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_fblistevent_detail); // Show the Up button in the action bar. getSupportActionBar().setDisplayHomeAsUpEnabled(true); // savedInstanceState is non-null when there is fragment state // saved from previous configurations of this activity // (e.g. when rotating the screen from portrait to landscape). // In this case, the fragment will automatically be re-added // to its container so we don't need to manually add it. // For more information, see the Fragments API guide at: // // http://developer.android.com/guide/components/fragments.html // if (savedInstanceState == null) { // Create the detail fragment and add it to the activity // using a fragment transaction. Bundle arguments = new Bundle(); arguments.putString(FBListEventDetailFragment.ARG_ITEM_ID, getIntent().getStringExtra(FBListEventDetailFragment.ARG_ITEM_ID)); FBListEventDetailFragment fragment = new FBListEventDetailFragment(); fragment.setArguments(arguments); getFragmentManager().beginTransaction() .add(R.id.fblistevent_detail_container, fragment) .commit(); } } @Override public boolean onOptionsItemSelected(MenuItem item) { int id = item.getItemId(); if (id == android.R.id.home) { // This ID represents the Home or Up button. In the case of this // activity, the Up button is shown. For // more details, see the Navigation pattern on Android Design: // // http://developer.android.com/design/patterns/navigation.html#up-vs-back // navigateUpTo(new Intent(this, FBListEventListActivity.class)); return true; } return super.onOptionsItemSelected(item); } }
apache-2.0
songshu198907/LeetPractise
src/main/java/algorithm/leet_370_end/Find_the_Difference_389.java
449
package algorithm.leet_370_end; /** * Created by shu on 2016/9/27. */ public class Find_the_Difference_389 { public char findTheDifference(String s, String t) { int[] arr = new int[26]; for (int i = 0; i < s.length(); i++) { arr[s.charAt(i) - 'a']++; } for (int i = 0; i < t.length(); i++) { if (arr[t.charAt(i) - 'a']-- == 0) return t.charAt(i); } return ' '; } }
apache-2.0
PlanetWaves/clockworkengine
trunk/jme3-core/src/main/java/com/jme3/scene/debug/SkeletonInterBoneWire.java
4908
/* * Copyright (c) 2009-2012 jMonkeyEngine * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * * Neither the name of 'jMonkeyEngine' nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package com.jme3.scene.debug; import java.nio.FloatBuffer; import java.util.Map; import com.jme3.animation.Bone; import com.jme3.animation.Skeleton; import com.jme3.math.Vector3f; import com.jme3.scene.Mesh; import com.jme3.scene.VertexBuffer; import com.jme3.scene.VertexBuffer.Format; import com.jme3.scene.VertexBuffer.Type; import com.jme3.scene.VertexBuffer.Usage; import com.jme3.util.BufferUtils; /** * A class that displays a dotted line between a bone tail and its childrens' heads. * * @author Marcin Roguski (Kaelthas) */ public class SkeletonInterBoneWire extends Mesh { private static final int POINT_AMOUNT = 10; /** The amount of connections between bones. */ private int connectionsAmount; /** The skeleton that will be showed. */ private Skeleton skeleton; /** The map between the bone index and its length. */ private Map<Integer, Float> boneLengths; /** * Creates buffers for points. Each line has POINT_AMOUNT of points. * @param skeleton * the skeleton that will be showed * @param boneLengths * the lengths of the bones */ public SkeletonInterBoneWire(Skeleton skeleton, Map<Integer, Float> boneLengths) { this.skeleton = skeleton; for (Bone bone : skeleton.getRoots()) { this.countConnections(bone); } this.setMode(Mode.Points); this.setPointSize(1); this.boneLengths = boneLengths; VertexBuffer pb = new VertexBuffer(Type.Position); FloatBuffer fpb = BufferUtils.createFloatBuffer(POINT_AMOUNT * connectionsAmount * 3); pb.setupData(Usage.Stream, 3, Format.Float, fpb); this.setBuffer(pb); this.updateCounts(); } /** * The method updates the geometry according to the poitions of the bones. */ public void updateGeometry() { VertexBuffer vb = this.getBuffer(Type.Position); FloatBuffer posBuf = this.getFloatBuffer(Type.Position); posBuf.clear(); for (int i = 0; i < skeleton.getBoneCount(); ++i) { Bone bone = skeleton.getBone(i); Vector3f parentTail = bone.getModelSpacePosition().add(bone.getModelSpaceRotation().mult(Vector3f.UNIT_Y.mult(boneLengths.get(i)))); for (Bone child : bone.getChildren()) { Vector3f childHead = child.getModelSpacePosition(); Vector3f v = childHead.subtract(parentTail); float pointDelta = v.length() / POINT_AMOUNT; v.normalizeLocal().multLocal(pointDelta); Vector3f pointPosition = parentTail.clone(); for (int j = 0; j < POINT_AMOUNT; ++j) { posBuf.put(pointPosition.getX()).put(pointPosition.getY()).put(pointPosition.getZ()); pointPosition.addLocal(v); } } } posBuf.flip(); vb.updateData(posBuf); this.updateBound(); } /** * Th method couns the connections between bones. * @param bone * the bone where counting starts */ private void countConnections(Bone bone) { for (Bone child : bone.getChildren()) { ++connectionsAmount; this.countConnections(child); } } }
apache-2.0
akarnokd/rxjava2-backport
src/test/java/hu/akarnokd/rxjava2/internal/operators/nbp/NbpOperatorDistinctUntilChangedTest.java
4981
/** * Copyright 2015 David Karnok and Netflix, 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 hu.akarnokd.rxjava2.internal.operators.nbp; import static org.mockito.Matchers.*; import static org.mockito.Mockito.*; import org.junit.*; import org.mockito.InOrder; import hu.akarnokd.rxjava2.*; import hu.akarnokd.rxjava2.NbpObservable.NbpSubscriber; import hu.akarnokd.rxjava2.functions.Function; public class NbpOperatorDistinctUntilChangedTest { NbpSubscriber<String> w; NbpSubscriber<String> w2; // nulls lead to exceptions final Function<String, String> TO_UPPER_WITH_EXCEPTION = new Function<String, String>() { @Override public String apply(String s) { if (s.equals("x")) { return "xx"; } return s.toUpperCase(); } }; @Before public void before() { w = TestHelper.mockNbpSubscriber(); w2 = TestHelper.mockNbpSubscriber(); } @Test public void testDistinctUntilChangedOfNone() { NbpObservable<String> src = NbpObservable.empty(); src.distinctUntilChanged().subscribe(w); verify(w, never()).onNext(anyString()); verify(w, never()).onError(any(Throwable.class)); verify(w, times(1)).onComplete(); } @Test public void testDistinctUntilChangedOfNoneWithKeySelector() { NbpObservable<String> src = NbpObservable.empty(); src.distinctUntilChanged(TO_UPPER_WITH_EXCEPTION).subscribe(w); verify(w, never()).onNext(anyString()); verify(w, never()).onError(any(Throwable.class)); verify(w, times(1)).onComplete(); } @Test public void testDistinctUntilChangedOfNormalSource() { NbpObservable<String> src = NbpObservable.just("a", "b", "c", "c", "c", "b", "b", "a", "e"); src.distinctUntilChanged().subscribe(w); InOrder inOrder = inOrder(w); inOrder.verify(w, times(1)).onNext("a"); inOrder.verify(w, times(1)).onNext("b"); inOrder.verify(w, times(1)).onNext("c"); inOrder.verify(w, times(1)).onNext("b"); inOrder.verify(w, times(1)).onNext("a"); inOrder.verify(w, times(1)).onNext("e"); inOrder.verify(w, times(1)).onComplete(); inOrder.verify(w, never()).onNext(anyString()); verify(w, never()).onError(any(Throwable.class)); } @Test public void testDistinctUntilChangedOfNormalSourceWithKeySelector() { NbpObservable<String> src = NbpObservable.just("a", "b", "c", "C", "c", "B", "b", "a", "e"); src.distinctUntilChanged(TO_UPPER_WITH_EXCEPTION).subscribe(w); InOrder inOrder = inOrder(w); inOrder.verify(w, times(1)).onNext("a"); inOrder.verify(w, times(1)).onNext("b"); inOrder.verify(w, times(1)).onNext("c"); inOrder.verify(w, times(1)).onNext("B"); inOrder.verify(w, times(1)).onNext("a"); inOrder.verify(w, times(1)).onNext("e"); inOrder.verify(w, times(1)).onComplete(); inOrder.verify(w, never()).onNext(anyString()); verify(w, never()).onError(any(Throwable.class)); } @Test @Ignore("Null values no longer allowed") public void testDistinctUntilChangedOfSourceWithNulls() { NbpObservable<String> src = NbpObservable.just(null, "a", "a", null, null, "b", null, null); src.distinctUntilChanged().subscribe(w); InOrder inOrder = inOrder(w); inOrder.verify(w, times(1)).onNext(null); inOrder.verify(w, times(1)).onNext("a"); inOrder.verify(w, times(1)).onNext(null); inOrder.verify(w, times(1)).onNext("b"); inOrder.verify(w, times(1)).onNext(null); inOrder.verify(w, times(1)).onComplete(); inOrder.verify(w, never()).onNext(anyString()); verify(w, never()).onError(any(Throwable.class)); } @Test @Ignore("Null values no longer allowed") public void testDistinctUntilChangedOfSourceWithExceptionsFromKeySelector() { NbpObservable<String> src = NbpObservable.just("a", "b", null, "c"); src.distinctUntilChanged(TO_UPPER_WITH_EXCEPTION).subscribe(w); InOrder inOrder = inOrder(w); inOrder.verify(w, times(1)).onNext("a"); inOrder.verify(w, times(1)).onNext("b"); verify(w, times(1)).onError(any(NullPointerException.class)); inOrder.verify(w, never()).onNext(anyString()); inOrder.verify(w, never()).onComplete(); } }
apache-2.0
karimgarza/StatsAgg
src/main/java/com/pearson/statsagg/webui/api/NotificationGroupDetails.java
4377
/* * Copyright 2015 prashant kumar (prashant4nov). * * 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.pearson.statsagg.webui.api; import com.pearson.statsagg.database_objects.notifications.NotificationGroupsDao; import com.pearson.statsagg.database_objects.notifications.NotificationGroup; import com.pearson.statsagg.utilities.StackTrace; import java.io.PrintWriter; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.json.simple.JSONObject; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * * @author prashant kumar (prashant4nov) */ @WebServlet(name="API_NotificationGroupDetails", urlPatterns={"/api/notification-group-details"}) public class NotificationGroupDetails extends HttpServlet { private static final Logger logger = LoggerFactory.getLogger(NotificationGroupDetails.class.getName()); public static final String PAGE_NAME = "API_NotificationGroupDetails"; /** * Returns a short description of the servlet. * * @return a String containing servlet description */ @Override public String getServletInfo() { return PAGE_NAME; } /** * Handles the HTTP <code>GET</code> method. * * @param request servlet request * @param response servlet response */ @Override protected void doGet(HttpServletRequest request, HttpServletResponse response) { logger.debug("doGet"); try { JSONObject json = getNotificationGroup(request, new NotificationGroupsDao()); PrintWriter out = null; response.setContentType("application/json"); out = response.getWriter(); out.println(json); } catch (Exception e) { logger.error(e.toString() + System.lineSeparator() + StackTrace.getStringFromStackTrace(e)); } } /** * Returns a json object containing the details of the requested notification group. * * @param request servlet request * @param notificationGroupsDao NotificationGroupsDao object * @return details of the requested notification group */ JSONObject getNotificationGroup(HttpServletRequest request, NotificationGroupsDao notificationGroupsDao) { logger.debug("getNotificationGroup"); logger.debug(PAGE_NAME); JSONObject notificationGroupDetails = new JSONObject(); int notificationGroupId = 0; try { if (request.getParameter(Helper.id) != null) { notificationGroupId = Integer.parseInt(request.getParameter(Helper.id)); } NotificationGroup notificationGroup = notificationGroupsDao.getNotificationGroup(notificationGroupId); if (notificationGroup != null) { if (notificationGroup.getId() != null) { notificationGroupDetails.put("id", notificationGroup.getId()); } if (notificationGroup.getName() != null) { notificationGroupDetails.put("name", notificationGroup.getName()); } if (notificationGroup.getEmailAddresses() != null) { notificationGroupDetails.put("email_addresses", notificationGroup.getEmailAddresses()); } } else { notificationGroupDetails.put(Helper.error, Helper.noResult); } } catch (Exception e) { logger.error(e.toString() + System.lineSeparator() + StackTrace.getStringFromStackTrace(e)); notificationGroupDetails.put(Helper.error, Helper.errorMsg); } return notificationGroupDetails; } }
apache-2.0
springfox/springfox
springfox-spring-web/src/main/java/springfox/documentation/spring/web/plugins/JacksonSerializerConvention.java
4104
/* * * Copyright 2017-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * 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 springfox.documentation.spring.web.plugins; import com.fasterxml.classmate.TypeResolver; import com.fasterxml.jackson.databind.annotation.JsonDeserialize; import com.fasterxml.jackson.databind.annotation.JsonSerialize; import io.github.classgraph.ClassGraph; import io.github.classgraph.ScanResult; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.core.Ordered; import org.springframework.http.ResponseEntity; import springfox.documentation.schema.AlternateTypeRule; import springfox.documentation.schema.AlternateTypeRuleConvention; import java.lang.reflect.Type; import java.util.ArrayList; import java.util.List; import java.util.Optional; import java.util.function.Function; import java.util.stream.Stream; import static java.util.Optional.*; import static springfox.documentation.schema.AlternateTypeRules.*; /** * Class to automatically detect type substitutions given the jackson serialize/deserialize annotations */ public class JacksonSerializerConvention implements AlternateTypeRuleConvention { private static final Logger LOGGER = LoggerFactory.getLogger(JacksonSerializerConvention.class); private static final int IMMUTABLES_CONVENTION_ORDER = Ordered.HIGHEST_PRECEDENCE + 4000; private final TypeResolver resolver; private final String packagePrefix; public JacksonSerializerConvention(TypeResolver resolver, String packagePrefix) { this.resolver = resolver; this.packagePrefix = packagePrefix; } @Override public List<AlternateTypeRule> rules() { ScanResult scanResults = new ClassGraph() .whitelistPackages(packagePrefix) .enableAnnotationInfo() .scan(); List<Class<?>> serialized = scanResults.getClassesWithAnnotation(JsonSerialize.class.getCanonicalName()) .loadClasses(); List<Class<?>> deserialized = scanResults.getClassesWithAnnotation(JsonDeserialize.class.getCanonicalName()) .loadClasses(); List<AlternateTypeRule> rules = new ArrayList<>(); Stream.concat(serialized.stream(), deserialized.stream()) .forEachOrdered(type -> { findAlternate(type).ifPresent(alternative -> { rules.add(newRule( resolver.resolve(type), resolver.resolve(alternative), getOrder())); rules.add(newRule( resolver.resolve(ResponseEntity.class, type), resolver.resolve(alternative), getOrder())); }); }); return rules; } private Optional<Type> findAlternate(Class<?> type) { Class serializer = ofNullable(type.getAnnotation(JsonSerialize.class)) .map((Function<JsonSerialize, Class>) JsonSerialize::as) .orElse(Void.class); Class deserializer = ofNullable(type.getAnnotation(JsonDeserialize.class)) .map((Function<JsonDeserialize, Class>) JsonDeserialize::as) .orElse(Void.class); Type toUse; if (serializer != deserializer) { LOGGER.warn("The serializer {} and deserializer {} . Picking the serializer by default", serializer.getName(), deserializer.getName()); } if (serializer == Void.class && deserializer == Void.class) { toUse = null; } else if (serializer != Void.class) { toUse = serializer; } else { toUse = deserializer; } return ofNullable(toUse); } @Override public int getOrder() { return IMMUTABLES_CONVENTION_ORDER; } }
apache-2.0
StreamReduce/streamreduce-core
analytics/src/test/java/com/streamreduce/storm/spouts/ConnectionSpoutTest.java
2419
/* * Copyright 2012 Nodeable 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.streamreduce.storm.spouts; import com.mongodb.BasicDBObject; import com.streamreduce.storm.MongoClient; import org.apache.log4j.Logger; import org.junit.Before; import org.junit.Test; import org.springframework.test.util.ReflectionTestUtils; import java.util.List; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNull; import static org.junit.Assert.fail; import static org.mockito.Matchers.anyString; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; public class ConnectionSpoutTest { ConnectionSpout connectionSpout; @Before public void setUp() throws Exception { MongoClient mockMongoClient = mock(MongoClient.class); when(mockMongoClient.getConnections()).thenThrow(new RuntimeException("mongo failure")); when(mockMongoClient.getConnection(anyString())).thenThrow(new RuntimeException("mongo failure")); Logger mockLogger = mock(Logger.class); connectionSpout = new ConnectionSpout(); ReflectionTestUtils.setField(connectionSpout, "mongoClient", mockMongoClient); ReflectionTestUtils.setField(connectionSpout, "logger", mockLogger); } @Test public void testGetDBEntries() throws Exception { try { List<BasicDBObject> dbObjects = connectionSpout.getDBEntries(); assertEquals(0, dbObjects.size()); } catch (Exception e) { fail("Did not catch unexpected exception."); } } @Test public void testGetDBEntry() throws Exception { try { BasicDBObject dbObject = connectionSpout.getDBEntry("blah"); assertNull(dbObject); } catch (Exception e) { fail("Did not catch unexpected exception."); } } }
apache-2.0
metaborg/spoofax-eclipse
org.metaborg.spoofax.eclipse/src/main/java/org/metaborg/spoofax/eclipse/editor/IEclipseEditorRegistryInternal.java
118
package org.metaborg.spoofax.eclipse.editor; public interface IEclipseEditorRegistryInternal { void register(); }
apache-2.0
vespa-engine/vespa
vdslib/src/main/java/com/yahoo/vdslib/state/ClusterState.java
20549
// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root. package com.yahoo.vdslib.state; import com.yahoo.text.StringUtilities; import java.text.ParseException; import java.util.BitSet; import java.util.HashMap; import java.util.HashSet; import java.util.Map; import java.util.Objects; import java.util.Set; import java.util.StringTokenizer; /** * Be careful about changing this class, as it mirrors the ClusterState in C++. * Please update both if you need to change anything. */ public class ClusterState implements Cloneable { private static final NodeState DEFAULT_STORAGE_UP_NODE_STATE = new NodeState(NodeType.STORAGE, State.UP); private static final NodeState DEFAULT_DISTRIBUTOR_UP_NODE_STATE = new NodeState(NodeType.DISTRIBUTOR, State.UP); private static final NodeState DEFAULT_STORAGE_DOWN_NODE_STATE = new NodeState(NodeType.STORAGE, State.DOWN); private static final NodeState DEFAULT_DISTRIBUTOR_DOWN_NODE_STATE = new NodeState(NodeType.DISTRIBUTOR, State.DOWN); /** * Maintains a bitset where all non-down nodes have a bit set. All nodes that differs from defaultUp * and defaultDown are store explicit in a hash map. */ private static class Nodes { private int logicalNodeCount; private final NodeType type; private final BitSet upNodes; private final Map<Integer, NodeState> nodeStates = new HashMap<>(); Nodes(NodeType type) { this.type = type; upNodes = new BitSet(); } Nodes(Nodes b) { logicalNodeCount = b.logicalNodeCount; type = b.type; upNodes = (BitSet) b.upNodes.clone(); b.nodeStates.forEach((key, value) -> nodeStates.put(key, value.clone())); } void updateMaxIndex(int index) { if (index > logicalNodeCount) { upNodes.set(logicalNodeCount, index); logicalNodeCount = index; } } int getLogicalNodeCount() { return logicalNodeCount; } NodeState getNodeState(int index) { NodeState ns = nodeStates.get(index); if (ns != null) return ns; return (index >= getLogicalNodeCount() || ! upNodes.get(index)) ? new NodeState(type, State.DOWN) : new NodeState(type, State.UP); } private void validateInput(Node node, NodeState ns) { ns.verifyValidInSystemState(node.getType()); if (node.getType() != type) { throw new IllegalArgumentException("NodeType '" + node.getType() + "' differs from '" + type + "'"); } } void setNodeState(Node node, NodeState ns) { validateInput(node, ns); int index = node.getIndex(); if (index >= logicalNodeCount) { logicalNodeCount = index + 1; } setNodeStateInternal(index, ns); } void addNodeState(Node node, NodeState ns) { validateInput(node, ns); int index = node.getIndex(); updateMaxIndex(index + 1); setNodeStateInternal(index, ns); } private static boolean equalsWithDescription(NodeState a, NodeState b) { // This is due to NodeState.equals considers semantic equality, and description is not part of that. return a.equals(b) && ((a.getState() != State.DOWN) || a.getDescription().equals(b.getDescription())); } private void setNodeStateInternal(int index, NodeState ns) { nodeStates.remove(index); if (ns.getState() == State.DOWN) { upNodes.clear(index); if ( ! equalsWithDescription(defaultDown(), ns)) { nodeStates.put(index, ns); } } else { upNodes.set(index); if ( ! equalsWithDescription(defaultUp(), ns)) { nodeStates.put(index, ns); } } } boolean similarToImpl(Nodes other, final NodeStateCmp nodeStateCmp) { // TODO verify behavior of C++ impl against this if (logicalNodeCount != other.logicalNodeCount) return false; if (type != other.type) return false; if ( ! upNodes.equals(other.upNodes)) return false; for (Integer node : unionNodeSetWith(other.nodeStates.keySet())) { final NodeState lhs = nodeStates.get(node); final NodeState rhs = other.nodeStates.get(node); if (!nodeStateCmp.similar(type, lhs, rhs)) { return false; } } return true; } private Set<Integer> unionNodeSetWith(final Set<Integer> otherNodes) { final Set<Integer> unionNodeSet = new HashSet<>(nodeStates.keySet()); unionNodeSet.addAll(otherNodes); return unionNodeSet; } @Override public String toString() { return toString(false); } String toString(boolean verbose) { StringBuilder sb = new StringBuilder(); int nodeCount = verbose ? getLogicalNodeCount() : upNodes.length(); if ( nodeCount > 0 ) { sb.append(type == NodeType.DISTRIBUTOR ? " distributor:" : " storage:").append(nodeCount); for (int i = 0; i < nodeCount; i++) { String nodeState = getNodeState(i).serialize(i, verbose); if (!nodeState.isEmpty()) { sb.append(' ').append(nodeState); } } } return sb.toString(); } @Override public boolean equals(Object obj) { if (! (obj instanceof Nodes)) return false; Nodes b = (Nodes) obj; if (logicalNodeCount != b.logicalNodeCount) return false; if (type != b.type) return false; if (!upNodes.equals(b.upNodes)) return false; if (!nodeStates.equals(b.nodeStates)) return false; return true; } @Override public int hashCode() { return Objects.hash(logicalNodeCount, type, nodeStates, upNodes); } private NodeState defaultDown() { return type == NodeType.STORAGE ? DEFAULT_STORAGE_DOWN_NODE_STATE : DEFAULT_DISTRIBUTOR_DOWN_NODE_STATE; } private NodeState defaultUp() { return defaultUpNodeState(type); } } private int version = 0; private State state = State.DOWN; private String description = ""; private int distributionBits = 16; private final Nodes distributorNodes; private final Nodes storageNodes; public ClusterState(String serialized) throws ParseException { distributorNodes = new Nodes(NodeType.DISTRIBUTOR); storageNodes = new Nodes(NodeType.STORAGE); deserialize(serialized); } public ClusterState(ClusterState b) { version = b.version; state = b.state; description = b.description; distributionBits = b.distributionBits; distributorNodes = new Nodes(b.distributorNodes); storageNodes = new Nodes(b.storageNodes); } private Nodes getNodes(NodeType type) { return (type == NodeType.STORAGE) ? storageNodes : (type == NodeType.DISTRIBUTOR) ? distributorNodes : null; } /** * Parse a given cluster state string into a returned ClusterState instance, wrapping any * parse exceptions in a RuntimeException. */ public static ClusterState stateFromString(final String stateStr) { try { return new ClusterState(stateStr); } catch (Exception e) { throw new RuntimeException(e); } } public static ClusterState emptyState() { return stateFromString(""); } public ClusterState clone() { return new ClusterState(this); } @Override public boolean equals(Object o) { if (!(o instanceof ClusterState)) { return false; } ClusterState other = (ClusterState) o; if (version != other.version || !state.equals(other.state) || distributionBits != other.distributionBits || !distributorNodes.equals(other.distributorNodes) || !storageNodes.equals(other.storageNodes)) { return false; } return true; } @Override public int hashCode() { return java.util.Objects.hash(version, state, distributionBits, distributorNodes, storageNodes); } @FunctionalInterface private interface NodeStateCmp { boolean similar(NodeType nodeType, NodeState lhs, NodeState rhs); } public boolean similarTo(Object o) { if (!(o instanceof ClusterState)) { return false; } final ClusterState other = (ClusterState) o; return similarToImpl(other, this::normalizedNodeStateSimilarTo); } public boolean similarToIgnoringInitProgress(final ClusterState other) { return similarToImpl(other, this::normalizedNodeStateSimilarToIgnoringInitProgress); } private boolean similarToImpl(ClusterState other, final NodeStateCmp nodeStateCmp) { if (other == this) { return true; // We're definitely similar to ourselves. } // Two cluster states are considered similar if they are both down. When clusters // are down, their individual node states do not matter to ideal state computations // and content nodes therefore do not need to observe them. if (state.equals(State.DOWN) && other.state.equals(State.DOWN)) { return true; } if (!metaInformationSimilarTo(other)) { return false; } if ( !distributorNodes.similarToImpl(other.distributorNodes, nodeStateCmp)) return false; if ( !storageNodes.similarToImpl(other.storageNodes, nodeStateCmp)) return false; return true; } private boolean metaInformationSimilarTo(final ClusterState other) { if (version != other.version || !state.equals(other.state)) { return false; } if (distributionBits != other.distributionBits) { return false; } return true; } private boolean normalizedNodeStateSimilarTo(final NodeType nodeType, final NodeState lhs, final NodeState rhs) { final NodeState lhsNormalized = (lhs != null ? lhs : defaultUpNodeState(nodeType)); final NodeState rhsNormalized = (rhs != null ? rhs : defaultUpNodeState(nodeType)); return lhsNormalized.similarTo(rhsNormalized); } private boolean normalizedNodeStateSimilarToIgnoringInitProgress( final NodeType nodeType, final NodeState lhs, final NodeState rhs) { final NodeState lhsNormalized = (lhs != null ? lhs : defaultUpNodeState(nodeType)); final NodeState rhsNormalized = (rhs != null ? rhs : defaultUpNodeState(nodeType)); return lhsNormalized.similarToIgnoringInitProgress(rhsNormalized); } private static NodeState defaultUpNodeState(final NodeType nodeType) { return nodeType == NodeType.STORAGE ? DEFAULT_STORAGE_UP_NODE_STATE : DEFAULT_DISTRIBUTOR_UP_NODE_STATE; } /** Used during deserialization */ private class NodeData { boolean empty = true; Node node = new Node(NodeType.STORAGE, 0); StringBuilder sb = new StringBuilder(); void addNodeState() throws ParseException { if (!empty) { NodeState ns = NodeState.deserialize(node.getType(), sb.toString()); getNodes(node.getType()).addNodeState(node, ns); } empty = true; sb = new StringBuilder(); } } private void deserialize(String serialized) throws ParseException { StringTokenizer st = new StringTokenizer(serialized, " \t\n\f\r", false); NodeData nodeData = new NodeData(); String lastAbsolutePath = ""; state = State.UP; while (st.hasMoreTokens()) { String token = st.nextToken(); int index = token.indexOf(':'); if (index < 0) { throw new ParseException("Token " + token + " does not contain ':': " + serialized, 0); } String key = token.substring(0, index); String value = token.substring(index + 1); if (key.length() > 0 && key.charAt(0) == '.') { if (lastAbsolutePath.equals("")) { throw new ParseException("The first path in system state string needs to be absolute, in state: " + serialized, 0); } key = lastAbsolutePath + key; } else { lastAbsolutePath = key; } if (key.length() > 0) switch (key.charAt(0)) { case 'c': if (key.equals("cluster")) { setClusterState(State.get(value)); continue; } break; case 'b': if (key.equals("bits")) { distributionBits = Integer.parseInt(value); continue; } break; case 'v': if (key.equals("version")) { try{ setVersion(Integer.valueOf(value)); } catch (Exception e) { throw new ParseException("Illegal version '" + value + "'. Must be an integer, in state: " + serialized, 0); } continue; } break; case 'm': if (key.length() > 1) break; setDescription(StringUtilities.unescape(value)); continue; case 'd': case 's': NodeType nodeType = null; int dot = key.indexOf('.'); String type = (dot < 0 ? key : key.substring(0, dot)); if (type.equals("storage")) { nodeType = NodeType.STORAGE; } else if (type.equals("distributor")) { nodeType = NodeType.DISTRIBUTOR; } if (nodeType == null) break; if (dot < 0) { int nodeCount; try{ nodeCount = Integer.valueOf(value); } catch (Exception e) { throw new ParseException("Illegal node count '" + value + "' in state: " + serialized, 0); } getNodes(nodeType).updateMaxIndex(nodeCount); continue; } int dot2 = key.indexOf('.', dot + 1); Node node; if (dot2 < 0) { node = new Node(nodeType, Integer.valueOf(key.substring(dot + 1))); } else { node = new Node(nodeType, Integer.valueOf(key.substring(dot + 1, dot2))); } if (node.getIndex() >= getNodeCount(nodeType)) { throw new ParseException("Cannot index " + nodeType + " node " + node.getIndex() + " of " + getNodeCount(nodeType) + " in state: " + serialized, 0); } if (!nodeData.node.equals(node)) { nodeData.addNodeState(); } if (dot2 < 0) { break; // No default key for nodeStates. } else { nodeData.sb.append(' ').append(key.substring(dot2 + 1)).append(':').append(value); } nodeData.node = node; nodeData.empty = false; continue; default: break; } // Ignore unknown nodeStates } nodeData.addNodeState(); } public String getTextualDifference(ClusterState other) { return getDiff(other).toString(); } public String getHtmlDifference(ClusterState other) { return getDiff(other).toHtml(); } private Diff getDiff(ClusterState other) { Diff diff = new Diff(); if (version != other.version) { diff.add(new Diff.Entry("version", version, other.version)); } if (!state.equals(other.state)) { diff.add(new Diff.Entry("cluster", state, other.state)); } if (distributionBits != other.distributionBits) { diff.add(new Diff.Entry("bits", distributionBits, other.distributionBits)); } for (NodeType type : NodeType.getTypes()) { Diff typeDiff = new Diff(); int maxCount = Math.max(getNodeCount(type), other.getNodeCount(type)); for (int i = 0; i < maxCount; i++) { Node n = new Node(type, i); Diff d = getNodeState(n).getDiff(other.getNodeState(n)); if (d.differs()) { typeDiff.add(new Diff.Entry(i, d)); } } if (typeDiff.differs()) { diff.add(new Diff.Entry(type, typeDiff).splitLine()); } } return diff; } public int getVersion() { return version; } public void setVersion(int version) { this.version = version; } public int getDistributionBitCount() { return distributionBits; } public void setDistributionBits(int bits) { distributionBits = bits; } /** * Returns the state of this cluster state. In particular, it does not return the cluster state, * no matter what the function name says. */ public State getClusterState() { return state; } /** * Sets the state of this cluster state. In particular, it does not set the cluster state, * no matter what the function name says. */ public void setClusterState(State s) { if (!s.validClusterState()) { throw new IllegalArgumentException("Illegal cluster state " + s); } state = s; } /** * Take the distributor nodes as an example. Let X be the highest index of * the distributor nodes added through setNodeState(). Let Y be the number * of suffix nodes for which the state is down and without description. * E.g. if node X is down and without description, but nodex X-1 is up, then Y is 1. * The node count for distributors is then X + 1 - Y. */ public int getNodeCount(NodeType type) { return getNodes(type).getLogicalNodeCount(); } /** * Returns the state of a node. * If the node is not known this returns a node in the state UP (never null) if it has lower index than the max * and DOWN otherwise. */ public NodeState getNodeState(Node node) { return getNodes(node.getType()).getNodeState(node.getIndex()); } /** * Set the node state of the given node. * * Automatically adjusts number of nodes of that given type if out of range of current nodes seen. */ public void setNodeState(Node node, NodeState newState) { newState.verifyValidInSystemState(node.getType()); getNodes(node.getType()).setNodeState(node, newState); } public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } /** Returns the serialized form of this cluster state */ // TODO: Don't rely on toString for that @Override public String toString() { return toString(false); } public String toString(boolean verbose) { StringBuilder sb = new StringBuilder(); if (version != 0) { sb.append(" version:").append(version); } if (!state.equals(State.UP)) { sb.append(" cluster:").append(state.serialize()); } if (distributionBits != 16) { sb.append(" bits:").append(distributionBits); } sb.append(distributorNodes.toString(verbose)); sb.append(storageNodes.toString(verbose)); if (sb.length() > 0) { // Remove first space if not empty sb.deleteCharAt(0); } return sb.toString(); } }
apache-2.0
inferred/FreeBuilder
src/test/java/org/inferred/freebuilder/processor/property/ListPropertyTest.java
38015
/* * Copyright 2016 Google 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 org.inferred.freebuilder.processor.property; import static org.inferred.freebuilder.processor.property.ElementFactory.INTEGERS; import static org.inferred.freebuilder.processor.property.ElementFactory.TYPES; import static org.inferred.freebuilder.processor.source.feature.GuavaLibrary.GUAVA; import static org.junit.Assume.assumeTrue; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.annotation.JsonDeserialize; import com.google.common.collect.ImmutableList; import com.google.common.collect.Lists; import com.google.common.testing.EqualsTester; import org.inferred.freebuilder.FreeBuilder; import org.inferred.freebuilder.processor.FeatureSets; import org.inferred.freebuilder.processor.NamingConvention; import org.inferred.freebuilder.processor.Processor; import org.inferred.freebuilder.processor.source.SourceBuilder; import org.inferred.freebuilder.processor.source.feature.FeatureSet; import org.inferred.freebuilder.processor.source.testing.BehaviorTester; import org.inferred.freebuilder.processor.source.testing.ParameterizedBehaviorTestFactory; import org.inferred.freebuilder.processor.source.testing.ParameterizedBehaviorTestFactory.Shared; import org.inferred.freebuilder.processor.source.testing.TestBuilder; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.junit.rules.ExpectedException; import org.junit.runner.RunWith; import org.junit.runners.Parameterized; import org.junit.runners.Parameterized.Parameters; import org.junit.runners.Parameterized.UseParametersRunnerFactory; import java.util.Arrays; import java.util.Collection; import java.util.Iterator; import java.util.List; import java.util.stream.IntStream; import java.util.stream.Stream; /** Behavioral tests for {@code List<?>} properties. */ @RunWith(Parameterized.class) @UseParametersRunnerFactory(ParameterizedBehaviorTestFactory.class) public class ListPropertyTest { @SuppressWarnings("unchecked") @Parameters(name = "List<{0}>, {1}, {2}") public static Iterable<Object[]> parameters() { List<NamingConvention> conventions = Arrays.asList(NamingConvention.values()); List<FeatureSet> features = FeatureSets.ALL; return () -> Lists .cartesianProduct(TYPES, conventions, features) .stream() .map(List::toArray) .iterator(); } @Rule public final ExpectedException thrown = ExpectedException.none(); @Shared public BehaviorTester behaviorTester; private final ElementFactory elements; private final NamingConvention convention; private final FeatureSet features; private final SourceBuilder listPropertyType; private final SourceBuilder validatedType; public ListPropertyTest( ElementFactory elements, NamingConvention convention, FeatureSet features) { this.elements = elements; this.convention = convention; this.features = features; listPropertyType = SourceBuilder.forTesting() .addLine("package com.example;") .addLine("@%s", FreeBuilder.class) .addLine("public abstract class DataType {") .addLine(" public abstract %s<%s> %s;", List.class, elements.type(), convention.get()) .addLine("") .addLine(" public static class Builder extends DataType_Builder {}") .addLine(" public abstract Builder toBuilder();") .addLine("}"); validatedType = SourceBuilder.forTesting() .addLine("package com.example;") .addLine("@%s", FreeBuilder.class) .addLine("public abstract class DataType {") .addLine(" public abstract %s<%s> %s;", List.class, elements.type(), convention.get()) .addLine("") .addLine(" public static class Builder extends DataType_Builder {") .addLine(" @Override public Builder addItems(%s element) {", elements.unwrappedType()) .addLine(" if (!(%s)) {", elements.validation()) .addLine(" throw new IllegalArgumentException(\"%s\");", elements.errorMessage()) .addLine(" }") .addLine(" return super.addItems(element);") .addLine(" }") .addLine(" }") .addLine("}"); } @Before public void setUp() { behaviorTester.withPermittedPackage(elements.type().getPackage()); } @Test public void testDefaultEmpty() { behaviorTester .with(new Processor(features)) .with(listPropertyType) .with(testBuilder() .addLine("DataType value = new DataType.Builder().build();") .addLine("assertThat(value.%s).isEmpty();", convention.get()) .build()) .runTest(); } @Test public void testAddSingleElement() { behaviorTester .with(new Processor(features)) .with(listPropertyType) .with(testBuilder() .addLine("DataType value = new DataType.Builder()") .addLine(" .addItems(%s)", elements.example(0)) .addLine(" .addItems(%s)", elements.example(1)) .addLine(" .build();") .addLine("assertThat(value.%s).containsExactly(%s).inOrder();", convention.get(), elements.examples(0, 1)) .build()) .runTest(); } @Test public void testAddSingleElement_null() { thrown.expect(NullPointerException.class); behaviorTester .with(new Processor(features)) .with(listPropertyType) .with(testBuilder() .addLine("new DataType.Builder()") .addLine(" .addItems((%s) null);", elements.type()) .build()) .runTest(); } @Test public void testAddVarargs() { behaviorTester .with(new Processor(features)) .with(listPropertyType) .with(testBuilder() .addLine("DataType value = new DataType.Builder()") .addLine(" .addItems(%s)", elements.examples(0, 1)) .addLine(" .build();") .addLine("assertThat(value.%s).containsExactly(%s).inOrder();", convention.get(), elements.examples(0, 1)) .build()) .runTest(); } @Test public void testAddVarargs_null() { thrown.expect(NullPointerException.class); behaviorTester .with(new Processor(features)) .with(listPropertyType) .with(testBuilder() .addLine("new DataType.Builder()") .addLine(" .addItems(%s, (%s) null);", elements.example(0), elements.type()) .build()) .runTest(); } @Test public void testAddAllSpliterator() { behaviorTester .with(new Processor(features)) .with(listPropertyType) .with(testBuilder() .addLine("DataType value = new DataType.Builder()") .addLine(" .addAllItems(Stream.of(%s).spliterator())", elements.examples(0, 1)) .addLine(" .build();") .addLine("assertThat(value.%s).containsExactly(%s).inOrder();", convention.get(), elements.examples(0, 1)) .build()) .runTest(); } @Test public void testAddAllSpliterator_null() { thrown.expect(NullPointerException.class); behaviorTester .with(new Processor(features)) .with(listPropertyType) .with(testBuilder() .addLine("new DataType.Builder()") .addLine(" .addAllItems(Stream.of(%s, (%s) null).spliterator());", elements.example(0), elements.type()) .build()) .runTest(); } @Test public void testAddAllStream() { behaviorTester .with(new Processor(features)) .with(listPropertyType) .with(testBuilder() .addLine("DataType value = new DataType.Builder()") .addLine(" .addAllItems(Stream.of(%s))", elements.examples(0, 1)) .addLine(" .build();") .addLine("assertThat(value.%s).containsExactly(%s).inOrder();", convention.get(), elements.examples(0, 1)) .build()) .runTest(); } @Test public void testAddAllStream_null() { thrown.expect(NullPointerException.class); behaviorTester .with(new Processor(features)) .with(listPropertyType) .with(testBuilder() .addLine("new DataType.Builder()") .addLine(" .addAllItems(Stream.of(%s, (%s) null));", elements.example(0), elements.type()) .build()) .runTest(); } @Test public void testAddAllIntStream() { assumeTrue(elements == INTEGERS); behaviorTester .with(new Processor(features)) .with(listPropertyType) .with(testBuilder() .addLine("DataType value = new DataType.Builder()") .addLine(" .addAllItems(%s.of(1, 2))", IntStream.class) .addLine(" .build();") .addLine("assertThat(value.%s).containsExactly(1, 2).inOrder();", convention.get()) .build()) .runTest(); } @Test public void testAddAllIterable() { behaviorTester .with(new Processor(features)) .with(listPropertyType) .with(testBuilder() .addLine("DataType value = new DataType.Builder()") .addLine(" .addAllItems(%s.of(%s))", ImmutableList.class, elements.examples(0, 1)) .addLine(" .build();") .addLine("assertThat(value.%s).containsExactly(%s).inOrder();", convention.get(), elements.examples(0, 1)) .build()) .runTest(); } @Test public void testAddAllIterable_onlyIteratesOnce() { behaviorTester .with(new Processor(features)) .with(listPropertyType) .with(testBuilder() .addLine("DataType value = new DataType.Builder()") .addLine(" .addAllItems(new %s<%s>(%s))", DodgySingleIterable.class, elements.type(), elements.examples(0, 1)) .addLine(" .build();") .addLine("assertThat(value.%s).containsExactly(%s).inOrder();", convention.get(), elements.examples(0, 1)) .build()) .runTest(); } /** Throws a {@link NullPointerException} on second call to {@link #iterator()}. */ public static class DodgySingleIterable<T> implements Iterable<T> { private ImmutableList<T> values; @SafeVarargs public DodgySingleIterable(T... values) { this.values = ImmutableList.copyOf(values); } @Override public Iterator<T> iterator() { try { return values.iterator(); } finally { values = null; } } } @Test public void testClear() { behaviorTester .with(new Processor(features)) .with(listPropertyType) .with(testBuilder() .addLine("DataType value = new DataType.Builder()") .addLine(" .addItems(%s)", elements.examples(0, 1)) .addLine(" .clearItems()") .addLine(" .addItems(%s)", elements.examples(2, 3)) .addLine(" .build();") .addLine("assertThat(value.%s).containsExactly(%s).inOrder();", convention.get(), elements.examples(2, 3)) .build()) .runTest(); } @Test public void testClear_emptyList() { behaviorTester .with(new Processor(features)) .with(listPropertyType) .with(testBuilder() .addLine("DataType value = new DataType.Builder()") .addLine(" .clearItems()") .addLine(" .addItems(%s)", elements.examples(2, 3)) .addLine(" .build();") .addLine("assertThat(value.%s).containsExactly(%s).inOrder();", convention.get(), elements.examples(2, 3)) .build()) .runTest(); } @Test public void testGetter_returnsLiveView() { behaviorTester .with(new Processor(features)) .with(listPropertyType) .with(testBuilder() .addLine("DataType.Builder builder = new DataType.Builder();") .addLine("%s<%s> itemsView = builder.%s;", List.class, elements.type(), convention.get()) .addLine("assertThat(itemsView).isEmpty();") .addLine("builder.addItems(%s);", elements.examples(0, 1)) .addLine("assertThat(itemsView).containsExactly(%s).inOrder();", elements.examples(0, 1)) .addLine("builder.clearItems();") .addLine("assertThat(itemsView).isEmpty();") .addLine("builder.addItems(%s);", elements.examples(2, 3)) .addLine("assertThat(itemsView).containsExactly(%s).inOrder();", elements.examples(2, 3)) .build()) .runTest(); } @Test public void testGetter_returnsUnmodifiableList() { thrown.expect(UnsupportedOperationException.class); behaviorTester .with(new Processor(features)) .with(listPropertyType) .with(testBuilder() .addLine("DataType.Builder builder = new DataType.Builder();") .addLine("%s<%s> itemsView = builder.%s;", List.class, elements.type(), convention.get()) .addLine("itemsView.add(%s);", elements.example(0)) .build()) .runTest(); } @Test public void testMergeFrom_valueInstance() { behaviorTester .with(new Processor(features)) .with(listPropertyType) .with(testBuilder() .addLine("DataType value = new DataType.Builder()") .addLine(" .addItems(%s)", elements.examples(0, 1)) .addLine(" .build();") .addLine("DataType.Builder builder = new DataType.Builder()") .addLine(" .mergeFrom(value);") .addLine("assertThat(builder.%s).containsExactly(%s).inOrder();", convention.get(), elements.examples(0, 1)) .build()) .runTest(); } @Test public void testMergeFrom_builder() { behaviorTester .with(new Processor(features)) .with(listPropertyType) .with(testBuilder() .addLine("DataType.Builder template = new DataType.Builder()") .addLine(" .addItems(%s);", elements.examples(0, 1)) .addLine("DataType.Builder builder = new DataType.Builder()") .addLine(" .mergeFrom(template);") .addLine("assertThat(builder.%s).containsExactly(%s).inOrder();", convention.get(), elements.examples(0, 1)) .build()) .runTest(); } @Test public void testToBuilder_fromPartial() { behaviorTester .with(new Processor(features)) .with(listPropertyType) .with(testBuilder() .addLine("DataType value1 = new DataType.Builder()") .addLine(" .addItems(%s)", elements.examples(0, 1)) .addLine(" .buildPartial();") .addLine("DataType value2 = value1.toBuilder()") .addLine(" .addItems(%s)", elements.example(2)) .addLine(" .build();") .addLine("assertThat(value2.%s)", convention.get()) .addLine(" .containsExactly(%s)", elements.examples(0, 1, 2)) .addLine(" .inOrder();") .build()) .runTest(); } @Test public void testBuilderClear() { behaviorTester .with(new Processor(features)) .with(listPropertyType) .with(testBuilder() .addLine("DataType value = new DataType.Builder()") .addLine(" .addItems(%s)", elements.examples(0, 1)) .addLine(" .clear()") .addLine(" .addItems(%s)", elements.examples(2, 3)) .addLine(" .build();") .addLine("assertThat(value.%s).containsExactly(%s).inOrder();", convention.get(), elements.examples(2, 3)) .build()) .runTest(); } @Test public void testBuilderClear_noBuilderFactory() { behaviorTester .with(new Processor(features)) .with(SourceBuilder.forTesting() .addLine("package com.example;") .addLine("@%s", FreeBuilder.class) .addLine("public abstract class DataType {") .addLine(" public abstract %s<%s> %s;", List.class, elements.type(), convention.get()) .addLine("") .addLine(" public static class Builder extends DataType_Builder {") .addLine(" private Builder() { }") .addLine(" }") .addLine(" public static Builder builder(%s... items) {", elements.unwrappedType()) .addLine(" return new Builder().addItems(items);") .addLine(" }") .addLine("}")) .with(testBuilder() .addLine("DataType value = DataType.builder(%s)", elements.examples(0, 1)) .addLine(" .clear()") .addLine(" .addItems(%s)", elements.examples(2, 3)) .addLine(" .build();") .addLine("assertThat(value.%s).containsExactly(%s).inOrder();", convention.get(), elements.examples(2, 3)) .build()) .runTest(); } @Test public void testEquality() { behaviorTester .with(new Processor(features)) .with(listPropertyType) .with(testBuilder() .addLine("new %s()", EqualsTester.class) .addLine(" .addEqualityGroup(") .addLine(" new DataType.Builder().build(),") .addLine(" new DataType.Builder().build())") .addLine(" .addEqualityGroup(") .addLine(" new DataType.Builder()") .addLine(" .addItems(%s)", elements.examples(0, 1)) .addLine(" .build(),") .addLine(" new DataType.Builder()") .addLine(" .addItems(%s)", elements.examples(0, 1)) .addLine(" .build())") .addLine(" .addEqualityGroup(") .addLine(" new DataType.Builder()") .addLine(" .addItems(%s)", elements.example(0)) .addLine(" .build(),") .addLine(" new DataType.Builder()") .addLine(" .addItems(%s)", elements.example(0)) .addLine(" .build())") .addLine(" .testEquals();") .build()) .runTest(); } @Test public void testInstanceReuse() { assumeGuavaAvailable(); behaviorTester .with(new Processor(features)) .with(listPropertyType) .with(testBuilder() .addLine("DataType value = new DataType.Builder()") .addLine(" .addItems(%s)", elements.example(0)) .addLine(" .build();") .addLine("DataType copy = DataType.Builder.from(value).build();") .addLine("assertThat(value.%1$s).isSameAs(copy.%1$s);", convention.get()) .build()) .runTest(); } @Test public void testFromReusesImmutableListInstance() { assumeGuavaAvailable(); behaviorTester .with(new Processor(features)) .with(listPropertyType) .with(new TestBuilder() .addImport("com.example.DataType") .addLine("DataType value = new DataType.Builder()") .addLine(" .addItems(%s)", elements.example(0)) .addLine(" .addItems(%s)", elements.example(1)) .addLine(" .build();") .addLine("DataType copy = DataType.Builder.from(value).build();") .addLine("assertThat(copy.%1$s).isSameAs(value.%1$s);", convention.get()) .build()) .runTest(); } @Test public void testMergeFromReusesImmutableListInstance() { assumeGuavaAvailable(); behaviorTester .with(new Processor(features)) .with(listPropertyType) .with(new TestBuilder() .addImport("com.example.DataType") .addLine("DataType value = new DataType.Builder()") .addLine(" .addItems(%s)", elements.example(0)) .addLine(" .addItems(%s)", elements.example(1)) .addLine(" .build();") .addLine("DataType copy = new DataType.Builder().mergeFrom(value).build();") .addLine("assertThat(copy.%1$s).isSameAs(value.%1$s);", convention.get()) .build()) .runTest(); } @Test public void testMergeFromEmptyListDoesNotPreventReuseOfImmutableListInstance() { assumeGuavaAvailable(); behaviorTester .with(new Processor(features)) .with(listPropertyType) .with(new TestBuilder() .addImport("com.example.DataType") .addLine("DataType value = new DataType.Builder()") .addLine(" .addItems(%s)", elements.example(0)) .addLine(" .addItems(%s)", elements.example(1)) .addLine(" .build();") .addLine("DataType copy = new DataType.Builder()") .addLine(" .from(value)") .addLine(" .mergeFrom(new DataType.Builder())") .addLine(" .build();") .addLine("assertThat(copy.%1$s).isSameAs(value.%1$s);", convention.get()) .build()) .runTest(); } @Test public void testPropertyClearAfterMergeFromValue() { behaviorTester .with(new Processor(features)) .with(listPropertyType) .with(testBuilder() .addLine("DataType value = new DataType.Builder()") .addLine(" .addItems(%s)", elements.examples(0, 1)) .addLine(" .build();") .addLine("DataType copy = DataType.Builder") .addLine(" .from(value)") .addLine(" .clearItems()") .addLine(" .build();") .addLine("assertThat(copy.%s).isEmpty();", convention.get()) .build()) .runTest(); } @Test public void testBuilderClearAfterMergeFromValue() { behaviorTester .with(new Processor(features)) .with(listPropertyType) .with(testBuilder() .addLine("DataType value = new DataType.Builder()") .addLine(" .addItems(%s)", elements.examples(0, 1)) .addLine(" .build();") .addLine("DataType copy = DataType.Builder") .addLine(" .from(value)") .addLine(" .clear()") .addLine(" .build();") .addLine("assertThat(copy.%s).isEmpty();", convention.get()) .build()) .runTest(); } @Test public void testCollectionProperty() { // See also https://github.com/google/FreeBuilder/issues/227 behaviorTester .with(new Processor(features)) .with(SourceBuilder.forTesting() .addLine("package com.example;") .addLine("@%s", FreeBuilder.class) .addLine("public abstract class DataType {") .addLine(" public abstract %s<%s> %s;", Collection.class, elements.type(), convention.get()) .addLine("") .addLine(" public static class Builder extends DataType_Builder {}") .addLine("}")) .with(testBuilder() .addLine("DataType value = new DataType.Builder()") .addLine(" .addItems(%s)", elements.example(0)) .addLine(" .addItems(%s)", elements.example(1)) .addLine(" .build();") .addLine("assertThat(value.%s).containsExactly(%s).inOrder();", convention.get(), elements.examples(0, 1)) .build()) .runTest(); } @Test public void testCollectionProperty_withWildcard() { behaviorTester .with(new Processor(features)) .with(SourceBuilder.forTesting() .addLine("package com.example;") .addLine("@%s", FreeBuilder.class) .addLine("public abstract class DataType {") .addLine(" public abstract %s<? extends %s> %s;", Collection.class, elements.supertype(), convention.get()) .addLine("") .addLine(" public static class Builder extends DataType_Builder {}") .addLine("}")) .with(testBuilder() .addLine("DataType value = new DataType.Builder()") .addLine(" .addItems(%s)", elements.example(0)) .addLine(" .addItems(%s)", elements.supertypeExample()) .addLine(" .build();") .addLine("assertThat(value.%s).containsExactly(%s, %s).inOrder();", convention.get(), elements.example(0), elements.supertypeExample()) .build()) .runTest(); } @Test public void testListOfParameters() { // See also // - https://github.com/google/FreeBuilder/issues/178 // - https://github.com/google/FreeBuilder/issues/229 behaviorTester .with(new Processor(features)) .with(SourceBuilder.forTesting() .addLine("package com.example;") .addLine("@%s", FreeBuilder.class) .addLine("public abstract class DataType<E> {") .addLine(" public abstract %s<E> %s;", List.class, convention.get()) .addLine("") .addLine(" public static class Builder<E> extends DataType_Builder<E> {}") .addLine("}")) .with(testBuilder() .addLine("DataType<%1$s> value = new DataType.Builder<%1$s>()", elements.type()) .addLine(" .addItems(%s)", elements.example(0)) .addLine(" .addItems(%s)", elements.example(1)) .addLine(" .build();") .addLine("assertThat(value.%s).containsExactly(%s).inOrder();", convention.get(), elements.examples(0, 1)) .build()) .runTest(); } @Test public void testListOfParameterWildcards() { behaviorTester .with(new Processor(features)) .with(SourceBuilder.forTesting() .addLine("package com.example;") .addLine("@%s", FreeBuilder.class) .addLine("public abstract class DataType<E> {") .addLine(" public abstract %s<? extends E> %s;", List.class, convention.get()) .addLine("") .addLine(" public static class Builder<E> extends DataType_Builder<E> {}") .addLine("}")) .with(testBuilder() .addLine("DataType<%1$s> value = new DataType.Builder<%1$s>()", elements.supertype()) .addLine(" .addItems(%s)", elements.example(0)) .addLine(" .addItems(%s)", elements.supertypeExample()) .addLine(" .build();") .addLine("assertThat(value.%s).containsExactly(%s, %s).inOrder();", convention.get(), elements.example(0), elements.supertypeExample()) .build()) .runTest(); } @Test public void testImmutableListProperty() { assumeGuavaAvailable(); behaviorTester .with(new Processor(features)) .with(SourceBuilder.forTesting() .addLine("package com.example;") .addLine("@%s", FreeBuilder.class) .addLine("public abstract class DataType {") .addLine(" public abstract %s<%s> %s;", ImmutableList.class, elements.type(), convention.get()) .addLine("") .addLine(" public static class Builder extends DataType_Builder {}") .addLine("}")) .with(testBuilder() .addLine("DataType value = new DataType.Builder()") .addLine(" .addItems(%s)", elements.example(0)) .addLine(" .addItems(%s)", elements.example(1)) .addLine(" .build();") .addLine("assertThat(value.%s).containsExactly(%s).inOrder();", convention.get(), elements.examples(0, 1)) .build()) .runTest(); } @Test public void testImmutableListProperty_withWildcard() { assumeGuavaAvailable(); behaviorTester .with(new Processor(features)) .with(SourceBuilder.forTesting() .addLine("package com.example;") .addLine("@%s", FreeBuilder.class) .addLine("public abstract class DataType {") .addLine(" public abstract %s<? extends %s> %s;", ImmutableList.class, elements.supertype(), convention.get()) .addLine("") .addLine(" public static class Builder extends DataType_Builder {}") .addLine("}")) .with(testBuilder() .addLine("DataType value = new DataType.Builder()") .addLine(" .addItems(%s)", elements.example(0)) .addLine(" .addItems(%s)", elements.supertypeExample()) .addLine(" .build();") .addLine("assertThat(value.%s).containsExactly(%s, %s).inOrder();", convention.get(), elements.example(0), elements.supertypeExample()) .build()) .runTest(); } @Test public void testValidation_varargsAdd() { thrown.expectMessage(elements.errorMessage()); behaviorTester .with(new Processor(features)) .with(validatedType) .with(testBuilder() .addLine("new DataType.Builder().addItems(%s, %s);", elements.example(0), elements.invalidExample()) .build()) .runTest(); } @Test public void testValidation_addAllSpliterator() { thrown.expectMessage(elements.errorMessage()); behaviorTester .with(new Processor(features)) .with(validatedType) .with(testBuilder() .addLine("new DataType.Builder().addAllItems(Stream.of(%s, %s).spliterator());", elements.example(0), elements.invalidExample()) .build()) .runTest(); } @Test public void testValidation_addAllStream() { thrown.expectMessage(elements.errorMessage()); behaviorTester .with(new Processor(features)) .with(validatedType) .with(testBuilder() .addLine("new DataType.Builder().addAllItems(Stream.of(%s, %s));", elements.example(0), elements.invalidExample()) .build()) .runTest(); } @Test public void testValidation_addAllIterable() { thrown.expectMessage(elements.errorMessage()); behaviorTester .with(new Processor(features)) .with(validatedType) .with(testBuilder() .addLine("new DataType.Builder().addAllItems(%s.of(%s, %s));", ImmutableList.class, elements.example(0), elements.invalidExample()) .build()) .runTest(); } @Test public void testJacksonInteroperability() { // See also https://github.com/google/FreeBuilder/issues/68 behaviorTester .with(new Processor(features)) .with(SourceBuilder.forTesting() .addLine("package com.example;") .addLine("import " + JsonProperty.class.getName() + ";") .addLine("@%s", FreeBuilder.class) .addLine("@%s(builder = DataType.Builder.class)", JsonDeserialize.class) .addLine("public interface DataType {") .addLine(" @JsonProperty(\"stuff\") %s<%s> %s;", List.class, elements.type(), convention.get()) .addLine("") .addLine(" class Builder extends DataType_Builder {}") .addLine("}")) .with(testBuilder() .addLine("DataType value = new DataType.Builder()") .addLine(" .addItems(%s)", elements.example(0)) .addLine(" .addItems(%s)", elements.example(1)) .addLine(" .build();") .addLine("%1$s mapper = new %1$s();", ObjectMapper.class) .addLine("String json = mapper.writeValueAsString(value);") .addLine("DataType clone = mapper.readValue(json, DataType.class);") .addLine("assertThat(clone.%s).containsExactly(%s).inOrder();", convention.get(), elements.examples(0, 1)) .build()) .runTest(); } @Test public void testCompilesWithoutWarnings() { behaviorTester .with(new Processor(features)) .with(listPropertyType) .compiles() .withNoWarnings(); } @Test public void testCanNamePropertyElements() { // See also https://github.com/google/FreeBuilder/issues/258 behaviorTester .with(new Processor(features)) .with(SourceBuilder.forTesting() .addLine("package com.example;") .addLine("@%s", FreeBuilder.class) .addLine("public abstract class DataType {") .addLine(" public abstract %s<%s> %s;", List.class, elements.type(), convention.get("elements")) .addLine("") .addLine(" public static class Builder extends DataType_Builder {}") .addLine("}")) .with(testBuilder() .addLine("DataType value = new DataType.Builder()") .addLine(" .addElements(%s)", elements.examples(0, 1)) .addLine(" .build();") .addLine("assertThat(value.%s).containsExactly(%s).inOrder();", convention.get("elements"), elements.examples(0, 1)) .build()) .runTest(); } @Test public void testGenericFieldCompilesWithoutHeapPollutionWarnings() { behaviorTester .with(new Processor(features)) .with(SourceBuilder.forTesting() .addLine("package com.example;") .addLine("@%s", FreeBuilder.class) .addLine("public abstract class DataType {") .addLine(" public abstract %1$s<%1$s<%2$s>> %3$s;", List.class, elements.type(), convention.get()) .addLine("") .addLine(" public static class Builder extends DataType_Builder {}") .addLine("}")) .with(testBuilder() .addLine("new DataType.Builder().addItems(") .addLine(" ImmutableList.of(%s),", elements.examples(0, 1)) .addLine(" ImmutableList.of(%s));", elements.examples(2, 3)) .build()) .compiles() .withNoWarnings(); } @Test public void testGenericBuildableTypeCompilesWithoutHeapPollutionWarnings() { behaviorTester .with(new Processor(features)) .with(SourceBuilder.forTesting() .addLine("package com.example;") .addLine("@%s", FreeBuilder.class) .addLine("public abstract class DataType<T> {") .addLine(" public abstract %s<T> %s;", List.class, convention.get()) .addLine("") .addLine(" public static class Builder<T> extends DataType_Builder<T> {}") .addLine("}")) .with(testBuilder() .addLine("new DataType.Builder<%s>().addItems(%s).build();", elements.type(), elements.examples(0, 1)) .build()) .compiles() .withNoWarnings(); } @Test public void testCanOverrideGenericFieldVarargsAdder() { // Ensure we remove the final annotation needed to apply @SafeVarargs. behaviorTester .with(new Processor(features)) .with(SourceBuilder.forTesting() .addLine("package com.example;") .addLine("@%s", FreeBuilder.class) .addLine("public abstract class DataType {") .addLine(" public abstract %1$s<%1$s<%2$s>> %3$s;", List.class, elements.type(), convention.get()) .addLine("") .addLine(" public static class Builder extends DataType_Builder {") .addLine(" @%s", Override.class) .addLine(" @%s", SafeVarargs.class) .addLine(" @%s(\"varargs\")", SuppressWarnings.class) .addLine(" public final Builder addItems(%s<%s>... items) {", List.class, elements.type()) .addLine(" return super.addItems(items);") .addLine(" }") .addLine(" }") .addLine("}")) .compiles() .withNoWarnings(); } @Test public void testCanOverrideGenericBuildableVarargsAdder() { // Ensure we remove the final annotation needed to apply @SafeVarargs. behaviorTester .with(new Processor(features)) .with(SourceBuilder.forTesting() .addLine("package com.example;") .addLine("@%s", FreeBuilder.class) .addLine("public abstract class DataType<T> {") .addLine(" public abstract %s<T> %s;", List.class, convention.get()) .addLine("") .addLine(" public static class Builder<T> extends DataType_Builder<T> {") .addLine(" @%s", Override.class) .addLine(" @%s", SafeVarargs.class) .addLine(" @%s(\"varargs\")", SuppressWarnings.class) .addLine(" public final Builder<T> addItems(T... items) {") .addLine(" return super.addItems(items);") .addLine(" }") .addLine(" }") .addLine("}")) .compiles() .withNoWarnings(); } private void assumeGuavaAvailable() { assumeTrue("Guava available", features.get(GUAVA).isAvailable()); } private static TestBuilder testBuilder() { return new TestBuilder() .addImport("com.example.DataType") .addImport(ImmutableList.class) .addImport(Stream.class); } }
apache-2.0
PublicTransitAnalytics/ScoreGenerator
src/main/java/com/publictransitanalytics/scoregenerator/distance/ForwardPointSequencer.java
1666
/* * Copyright 2018 Public Transit Analytics. * * 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.publictransitanalytics.scoregenerator.distance; import com.google.common.collect.ImmutableList; import com.publictransitanalytics.scoregenerator.location.PointLocation; import java.util.Collections; import java.util.List; import java.util.Set; import java.util.stream.Collectors; import java.util.stream.IntStream; import lombok.RequiredArgsConstructor; /** * * @author Public Transit Analytics */ @RequiredArgsConstructor public class ForwardPointSequencer implements PointSequencer { final PointLocation origin; final Set<PointLocation> destinations; @Override public List<PointLocation> getSequence() { return ImmutableList.<PointLocation>builder().addAll(destinations) .add(origin).build(); } @Override public Set<Integer> getOrigins() { return Collections.singleton(destinations.size()); } @Override public Set<Integer> getDestinations() { return IntStream.range(0, destinations.size()).boxed().collect( Collectors.toSet()); } }
apache-2.0
gosu-lang/old-gosu-repo
gosu-core-api/src/main/java/gw/lang/parser/IStackProvider.java
538
/* * Copyright 2013 Guidewire Software, Inc. */ package gw.lang.parser; public interface IStackProvider { int THIS_POS = 0; int SUPER_POS = 1; int START_POS = 2; /** * For compile-time assignment of stack indexes. */ public int getNextStackIndex(); /** * For compile-time assignment of stack indexes at a particular scope. */ public int getNextStackIndexForScope( IScope scope ); /** * For compile-time use. Returns true iff an isolated scope is visible. */ public boolean hasIsolatedScope(); }
apache-2.0
Sunshine747/task_1
addressbook-web-tests/src/test/java/ru/stqa/addressbook/tests/ContactDeletionFromGroupTest.java
1793
package ru.stqa.addressbook.tests; import org.testng.annotations.BeforeMethod; import org.testng.annotations.Test; import ru.stqa.addressbook.model.ContactData; import ru.stqa.addressbook.model.Contacts; import ru.stqa.addressbook.model.GroupData; import ru.stqa.addressbook.model.Groups; import static org.hamcrest.CoreMatchers.equalTo; import static org.hamcrest.MatcherAssert.assertThat; /** * Created by Администратор on 25.12.2016. */ public class ContactDeletionFromGroupTest extends TestBase { @BeforeMethod public void ensurePrecondition() { Contacts allContacts = app.db().contacts(); Groups groups = app.db().groups(); if (app.db().contacts().size() == 0) { app.goTo().homePage(); app.goTo().addNewContact(); app.contact().create(new ContactData().withFirstName("contact_first_name")); } if (groups.size() == 0) { app.goTo().groupPage(); app.group().create(new GroupData().withName("group_name")); } if (app.db().contactsInGroups(allContacts).size() == 0) { app.goTo().homePage(); app.contact().addToGroup(app.db().contacts().stream().iterator().next(), app.db().groups().stream().iterator().next()); } } @Test public void testAddContactToGroup() { Contacts contacts = app.db().contactsInGroups(app.db().contacts()); ContactData contact = contacts.stream().iterator().next(); app.goTo().homePage(); GroupData group = contact.getGroups().iterator().next(); app.contact().deleteFromGroup(contact, group); ContactData contactForEq = app.db().contacts().stream() .filter(s -> s.getId() == contact.getId()).iterator().next(); app.goTo().homePage(); assertThat(contactForEq.getGroups().contains(group), equalTo(false)); } }
apache-2.0
knetikmedia/knetikcloud-java-client
src/main/java/com/knetikcloud/model/PageResourceUserLevelingResource.java
7677
/* * Knetik Platform API Documentation latest * This is the spec for the Knetik API. Use this in conjunction with the documentation found at https://knetikcloud.com. * * OpenAPI spec version: latest * Contact: support@knetik.com * * NOTE: This class is auto generated by the swagger code generator program. * https://github.com/swagger-api/swagger-codegen.git * Do not edit the class manually. */ package com.knetikcloud.model; import java.util.Objects; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonValue; import com.knetikcloud.model.Order; import com.knetikcloud.model.UserLevelingResource; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; import java.util.ArrayList; import java.util.List; /** * PageResourceUserLevelingResource */ @javax.annotation.Generated(value = "io.swagger.codegen.languages.JavaClientCodegen", date = "2018-03-14T12:03:43.231-04:00") public class PageResourceUserLevelingResource { @JsonProperty("content") private List<UserLevelingResource> content = null; @JsonProperty("first") private Boolean first = null; @JsonProperty("last") private Boolean last = null; @JsonProperty("number") private Integer number = null; @JsonProperty("number_of_elements") private Integer numberOfElements = null; @JsonProperty("size") private Integer size = null; @JsonProperty("sort") private List<Order> sort = null; @JsonProperty("total_elements") private Long totalElements = null; @JsonProperty("total_pages") private Integer totalPages = null; public PageResourceUserLevelingResource content(List<UserLevelingResource> content) { this.content = content; return this; } public PageResourceUserLevelingResource addContentItem(UserLevelingResource contentItem) { if (this.content == null) { this.content = new ArrayList<UserLevelingResource>(); } this.content.add(contentItem); return this; } /** * Get content * @return content **/ @ApiModelProperty(value = "") public List<UserLevelingResource> getContent() { return content; } public void setContent(List<UserLevelingResource> content) { this.content = content; } public PageResourceUserLevelingResource first(Boolean first) { this.first = first; return this; } /** * Get first * @return first **/ @ApiModelProperty(value = "") public Boolean isFirst() { return first; } public void setFirst(Boolean first) { this.first = first; } public PageResourceUserLevelingResource last(Boolean last) { this.last = last; return this; } /** * Get last * @return last **/ @ApiModelProperty(value = "") public Boolean isLast() { return last; } public void setLast(Boolean last) { this.last = last; } public PageResourceUserLevelingResource number(Integer number) { this.number = number; return this; } /** * Get number * @return number **/ @ApiModelProperty(value = "") public Integer getNumber() { return number; } public void setNumber(Integer number) { this.number = number; } public PageResourceUserLevelingResource numberOfElements(Integer numberOfElements) { this.numberOfElements = numberOfElements; return this; } /** * Get numberOfElements * @return numberOfElements **/ @ApiModelProperty(value = "") public Integer getNumberOfElements() { return numberOfElements; } public void setNumberOfElements(Integer numberOfElements) { this.numberOfElements = numberOfElements; } public PageResourceUserLevelingResource size(Integer size) { this.size = size; return this; } /** * Get size * @return size **/ @ApiModelProperty(value = "") public Integer getSize() { return size; } public void setSize(Integer size) { this.size = size; } public PageResourceUserLevelingResource sort(List<Order> sort) { this.sort = sort; return this; } public PageResourceUserLevelingResource addSortItem(Order sortItem) { if (this.sort == null) { this.sort = new ArrayList<Order>(); } this.sort.add(sortItem); return this; } /** * Get sort * @return sort **/ @ApiModelProperty(value = "") public List<Order> getSort() { return sort; } public void setSort(List<Order> sort) { this.sort = sort; } public PageResourceUserLevelingResource totalElements(Long totalElements) { this.totalElements = totalElements; return this; } /** * Get totalElements * @return totalElements **/ @ApiModelProperty(value = "") public Long getTotalElements() { return totalElements; } public void setTotalElements(Long totalElements) { this.totalElements = totalElements; } public PageResourceUserLevelingResource totalPages(Integer totalPages) { this.totalPages = totalPages; return this; } /** * Get totalPages * @return totalPages **/ @ApiModelProperty(value = "") public Integer getTotalPages() { return totalPages; } public void setTotalPages(Integer totalPages) { this.totalPages = totalPages; } @Override public boolean equals(java.lang.Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } PageResourceUserLevelingResource pageResourceUserLevelingResource = (PageResourceUserLevelingResource) o; return Objects.equals(this.content, pageResourceUserLevelingResource.content) && Objects.equals(this.first, pageResourceUserLevelingResource.first) && Objects.equals(this.last, pageResourceUserLevelingResource.last) && Objects.equals(this.number, pageResourceUserLevelingResource.number) && Objects.equals(this.numberOfElements, pageResourceUserLevelingResource.numberOfElements) && Objects.equals(this.size, pageResourceUserLevelingResource.size) && Objects.equals(this.sort, pageResourceUserLevelingResource.sort) && Objects.equals(this.totalElements, pageResourceUserLevelingResource.totalElements) && Objects.equals(this.totalPages, pageResourceUserLevelingResource.totalPages); } @Override public int hashCode() { return Objects.hash(content, first, last, number, numberOfElements, size, sort, totalElements, totalPages); } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("class PageResourceUserLevelingResource {\n"); sb.append(" content: ").append(toIndentedString(content)).append("\n"); sb.append(" first: ").append(toIndentedString(first)).append("\n"); sb.append(" last: ").append(toIndentedString(last)).append("\n"); sb.append(" number: ").append(toIndentedString(number)).append("\n"); sb.append(" numberOfElements: ").append(toIndentedString(numberOfElements)).append("\n"); sb.append(" size: ").append(toIndentedString(size)).append("\n"); sb.append(" sort: ").append(toIndentedString(sort)).append("\n"); sb.append(" totalElements: ").append(toIndentedString(totalElements)).append("\n"); sb.append(" totalPages: ").append(toIndentedString(totalPages)).append("\n"); sb.append("}"); return sb.toString(); } /** * Convert the given object to string with each line indented by 4 spaces * (except the first line). */ private String toIndentedString(java.lang.Object o) { if (o == null) { return "null"; } return o.toString().replace("\n", "\n "); } }
apache-2.0
yuanhuan2005/idm-java-sdk
src/main/java/com/tcl/idm/util/ThreadedStreamHandler.java
3693
package com.tcl.idm.util; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStream; import java.io.PrintWriter; /** * This class is intended to be used with the SystemCommandExecutor class to let * users execute system commands from Java applications. * * This class is based on work that was shared in a JavaWorld article named * "When System.exec() won't". That article is available at this url: * * http://www.javaworld.com/javaworld/jw-12-2000/jw-1229-traps.html * * Documentation for this class is available at this URL: * * http://devdaily.com/java/java-processbuilder-process-system-exec * * * Copyright 2010 alvin j. alexander, devdaily.com. * * This program is free software: you can redistribute it and/or modify it under * the terms of the GNU Lesser Public License as published by the Free Software * Foundation, either version 3 of the License, or (at your option) any later * version. * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU Lesser Public License for more details. * * You should have received a copy of the GNU Lesser Public License along with * this program. If not, see <http://www.gnu.org/licenses/>. * * Please ee the following page for the LGPL license: * http://www.gnu.org/licenses/lgpl.txt * */ class ThreadedStreamHandler extends Thread { InputStream inputStream; String adminPassword; OutputStream outputStream; PrintWriter printWriter; StringBuilder outputBuffer = new StringBuilder(); private boolean sudoIsRequested = false; /** * A simple constructor for when the sudo command is not necessary. This * constructor will just run the command you provide, without running sudo * before the command, and without expecting a password. * * @param inputStream * @param streamType */ ThreadedStreamHandler(InputStream inputStream) { this.inputStream = inputStream; } /** * Use this constructor when you want to invoke the 'sudo' command. The * outputStream must not be null. If it is, you'll regret it. :) * * command is wrong. * * @param inputStream * @param streamType * @param outputStream * @param adminPassword */ ThreadedStreamHandler(InputStream inputStream, OutputStream outputStream, String adminPassword) { this.inputStream = inputStream; this.outputStream = outputStream; printWriter = new PrintWriter(outputStream); this.adminPassword = adminPassword; sudoIsRequested = true; } @Override public void run() { // on mac os x 10.5.x, when i run a 'sudo' command, i need to write // the admin password out immediately; that's why this code is // here. if (sudoIsRequested) { // doSleep(500); printWriter.println(adminPassword); printWriter.flush(); } BufferedReader bufferedReader = null; try { bufferedReader = new BufferedReader(new InputStreamReader(inputStream)); String line = null; while ((line = bufferedReader.readLine()) != null) { outputBuffer.append(line + "\n"); } } catch (IOException ioe) { } catch (Throwable t) { } finally { try { if (null != bufferedReader) { bufferedReader.close(); } } catch (IOException e) { // ignore this one } } } @SuppressWarnings("unused") private void doSleep(long millis) { try { Thread.sleep(millis); } catch (InterruptedException e) { // ignore } } public StringBuilder getOutputBuffer() { return outputBuffer; } }
apache-2.0
lusparioTT/fks
src/org/nutz/plugins/view/freemarker/FreemarkerView.java
6705
package org.nutz.plugins.view.freemarker; import java.util.Enumeration; import java.util.HashMap; import java.util.Map; import javax.servlet.GenericServlet; import javax.servlet.ServletContext; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import org.nutz.lang.Files; import org.nutz.lang.Lang; import org.nutz.lang.Strings; import org.nutz.mvc.Mvcs; import org.nutz.mvc.view.AbstractPathView; import freemarker.ext.jsp.TaglibFactory; import freemarker.ext.servlet.HttpRequestHashModel; import freemarker.ext.servlet.HttpRequestParametersHashModel; import freemarker.ext.servlet.HttpSessionHashModel; import freemarker.ext.servlet.ServletContextHashModel; import freemarker.template.Configuration; import freemarker.template.ObjectWrapper; import freemarker.template.Template; import freemarker.template.TemplateModel; public class FreemarkerView extends AbstractPathView { private FreeMarkerConfigurer freeMarkerConfigurer; private static final String ATTR_APPLICATION_MODEL = ".freemarker.Application"; private static final String ATTR_JSP_TAGLIBS_MODEL = ".freemarker.JspTaglibs"; private static final String ATTR_REQUEST_MODEL = ".freemarker.Request"; private static final String ATTR_REQUEST_PARAMETERS_MODEL = ".freemarker.RequestParameters"; private static final String KEY_APPLICATION = "Application"; private static final String KEY_REQUEST_MODEL = "Request"; private static final String KEY_SESSION_MODEL = "Session"; private static final String KEY_REQUEST_PARAMETER_MODEL = "Parameters"; private static final String KEY_EXCEPTION = "exception"; private static final String OBJ = "obj"; private static final String REQUEST = "request"; private static final String RESPONSE = "response"; private static final String SESSION = "session"; private static final String APPLICATION = "application"; private static final String KEY_JSP_TAGLIBS = "JspTaglibs"; public static final String PATH_BASE = "base"; public FreemarkerView(FreeMarkerConfigurer freeMarkerConfigurer, String path) { super(path); this.freeMarkerConfigurer = freeMarkerConfigurer; } public void render(HttpServletRequest request, HttpServletResponse response, Object value) throws Throwable { String $temp = evalPath(request, value); String path = getPath($temp); ServletContext sc = request.getSession().getServletContext(); Configuration cfg = freeMarkerConfigurer.getConfiguration(); Map<String, Object> root = new HashMap<String, Object>(); root.put(OBJ, value); root.put(REQUEST, request); root.put(RESPONSE, response); HttpSession session = request.getSession(); root.put(SESSION, session); root.put(APPLICATION, sc); root.put("props", System.getProperties());// .get("java.version") Map<String, String> msgs = Mvcs.getMessages(request); root.put("mvcs", msgs); Enumeration<?> reqs = request.getAttributeNames(); while (reqs.hasMoreElements()) { String strKey = (String) reqs.nextElement(); //测试 查看属性名称 //System.out.println(strKey); root.put(strKey, request.getAttribute(strKey)); } jspTaglibs(sc, request, response, root, cfg.getObjectWrapper()); try { Template template = cfg.getTemplate(path); response.setContentType("text/html; charset=" + template.getEncoding()); template.process(root, response.getWriter()); //测试一下模板引擎提供的数据模型 //System.out.println("data-model - " + root); //System.out.println("base === " + root.get("base")); } catch (Exception e) { throw Lang.wrapThrow(e); } } /** * 子类可以覆盖这个方法,给出自己特殊的后缀 * * @return 后缀 */ protected String getExt() { return freeMarkerConfigurer.getSuffix(); } private String getPath(String path) { StringBuffer sb = new StringBuffer(); // 空路径,采用默认规则 if (Strings.isBlank(path)) { sb.append(Mvcs.getServletContext().getRealPath(freeMarkerConfigurer.getPrefix())); sb.append((path.startsWith("/") ? "" : "/")); sb.append(Files.renameSuffix(path, getExt())); } // 绝对路径 : 以 '/' 开头的路径不增加 '/WEB-INF' else if (path.charAt(0) == '/') { String ext = getExt(); sb.append(path); if (!path.toLowerCase().endsWith(ext)) sb.append(ext); } // 包名形式的路径 else { sb.append(path.replace('.', '/')); sb.append(getExt()); } return sb.toString(); } protected void jspTaglibs(ServletContext servletContext, HttpServletRequest request, HttpServletResponse response, Map<String, Object> model, ObjectWrapper wrapper) { synchronized (servletContext) { ServletContextHashModel servletContextModel = (ServletContextHashModel) servletContext.getAttribute(ATTR_APPLICATION_MODEL); if (Lang.isEmpty(servletContextModel)) { GenericServlet servlet = JspSupportServlet.jspSupportServlet; if (!Lang.isEmpty(servlet)) { servletContextModel = new ServletContextHashModel(servlet, wrapper); servletContext.setAttribute(ATTR_APPLICATION_MODEL, servletContextModel); TaglibFactory taglibs = new TaglibFactory(servletContext); servletContext.setAttribute(ATTR_JSP_TAGLIBS_MODEL, taglibs); } } model.put(KEY_APPLICATION, servletContextModel); TemplateModel tempModel = (TemplateModel) servletContext.getAttribute(ATTR_JSP_TAGLIBS_MODEL); model.put(KEY_JSP_TAGLIBS, tempModel); } HttpSession session = request.getSession(false); if (!Lang.isEmpty(session)) { model.put(KEY_SESSION_MODEL, new HttpSessionHashModel(session, wrapper)); } HttpRequestHashModel requestModel = (HttpRequestHashModel) request.getAttribute(ATTR_REQUEST_MODEL); if (Lang.isEmpty(requestModel) || !Lang.equals(requestModel.getRequest(), request)) { requestModel = new HttpRequestHashModel(request, response, wrapper); request.setAttribute(ATTR_REQUEST_MODEL, requestModel); } model.put(KEY_REQUEST_MODEL, requestModel); HttpRequestParametersHashModel reqParametersModel = (HttpRequestParametersHashModel) request.getAttribute(ATTR_REQUEST_PARAMETERS_MODEL); if (Lang.isEmpty(reqParametersModel) || !Lang.equals(requestModel.getRequest(), request)) { reqParametersModel = new HttpRequestParametersHashModel(request); request.setAttribute(ATTR_REQUEST_PARAMETERS_MODEL, reqParametersModel); } model.put(KEY_REQUEST_PARAMETER_MODEL, reqParametersModel); Throwable exception = (Throwable) request.getAttribute("javax.servlet.error.exception"); if (Lang.isEmpty(exception)) { exception = (Throwable) request.getAttribute("javax.servlet.error.JspException"); } if (!Lang.isEmpty(exception)) { model.put(KEY_EXCEPTION, exception); } } }
apache-2.0
talsma-ict/umldoclet
src/plantuml-asl/src/net/sourceforge/plantuml/windowsdot/WindowsDotArchive.java
3464
/* ======================================================================== * PlantUML : a free UML diagram generator * ======================================================================== * * (C) Copyright 2009-2020, Arnaud Roques * * Project Info: https://plantuml.com * * If you like this project or if you find it useful, you can support us at: * * https://plantuml.com/patreon (only 1$ per month!) * https://plantuml.com/paypal * * This file is part of PlantUML. * * 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. * * * Original Author: Arnaud Roques */ package net.sourceforge.plantuml.windowsdot; import java.io.BufferedOutputStream; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import net.sourceforge.plantuml.brotli.BrotliInputStream; public final class WindowsDotArchive { private static WindowsDotArchive singleton = null; private Boolean isThereArchive; private File exe; private WindowsDotArchive() { } public final synchronized static WindowsDotArchive getInstance() { if (singleton == null) { singleton = new WindowsDotArchive(); } return singleton; } final static public String readString(InputStream is) throws IOException { int len = readByte(is); final StringBuilder sb = new StringBuilder(len); for (int i = 0; i < len; i++) { sb.append((char) readByte(is)); } return sb.toString(); } final static public int readNumber(InputStream is) throws IOException { int result = readByte(is); result = result * 256 + readByte(is); result = result * 256 + readByte(is); return result; } private static int readByte(InputStream is) throws IOException { return is.read(); } private static void extract(File dir) throws IOException { final InputStream raw = WindowsDotArchive.class.getResourceAsStream("graphviz.dat"); try (final BrotliInputStream is = new BrotliInputStream(raw)) { while (true) { final String name = readString(is); if (name.length() == 0) break; final int size = readNumber(is); try (final OutputStream fos = new BufferedOutputStream(new FileOutputStream(new File(dir, name)))) { for (int i = 0; i < size; i++) { fos.write(is.read()); } } } } } public synchronized boolean isThereArchive() { if (isThereArchive == null) try (InputStream raw = WindowsDotArchive.class.getResourceAsStream("graphviz.dat")) { isThereArchive = raw != null; } catch (Exception e) { isThereArchive = false; } return isThereArchive; } public synchronized File getWindowsExeLite() { if (isThereArchive() == false) { return null; } if (exe == null) try { final File tmp = new File(System.getProperty("java.io.tmpdir"), "_graphviz"); tmp.mkdirs(); extract(tmp); exe = new File(tmp, "dot.exe"); } catch (IOException e) { e.printStackTrace(); } return exe; } }
apache-2.0
googlearchive/science-journal
OpenScienceJournal/whistlepunk_library/src/main/java/com/google/android/apps/forscience/whistlepunk/ReusableFormatter.java
1207
/* * Copyright 2017 Google 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.google.android.apps.forscience.whistlepunk; import java.util.Formatter; /** * A re-usable formatter class to use as an alternative to String.format, which creates a new * Formatter behind the scenes for each use. */ public class ReusableFormatter { private Formatter formatter; private StringBuilder builder; public ReusableFormatter() { builder = new StringBuilder(); formatter = new Formatter(builder); } public Formatter format(String format, Object... params) { builder.setLength(0); return formatter.format(format, params); } }
apache-2.0
support-project/knowledge
src/main/java/org/support/project/knowledge/bat/DataTransferBat.java
3706
package org.support.project.knowledge.bat; import org.apache.commons.lang.ClassUtils; import org.h2.tools.Server; import org.support.project.common.config.ConfigLoader; import org.support.project.common.log.Log; import org.support.project.common.log.LogFactory; import org.support.project.knowledge.logic.DataTransferLogic; import org.support.project.ormapping.config.ConnectionConfig; import org.support.project.web.config.AppConfig; import org.support.project.web.logic.DBConnenctionLogic; public class DataTransferBat extends AbstractBat implements Runnable { /** ログ */ private static final Log LOG = LogFactory.getLog(DataTransferBat.class); private boolean runing = false; private boolean serverStarted = false; public static void main(String[] args) throws Exception { try { initLogName("DataTransferBat.log"); configInit(ClassUtils.getShortClassName(DataTransferBat.class)); DataTransferLogic.get().requestTransfer(); DataTransferBat bat = new DataTransferBat(); bat.dbInit(); bat.start(); } catch (Exception e) { LOG.error("any error", e); throw e; } } @Override public void run() { // データ取得元の組み込みDBを起動(既に起動している場合起動しない) runing = true; try { AppConfig appConfig = ConfigLoader.load(AppConfig.APP_CONFIG, AppConfig.class); String[] parms = { "-tcp", "-baseDir", appConfig.getDatabasePath() }; LOG.info("start h2 database"); Server server = Server.createTcpServer(parms); server.start(); // System.out.println("Database start..."); serverStarted = true; while (runing) { Thread.sleep(1000); } server.stop(); } catch (Exception e) { LOG.error(e); } LOG.info("Database stop."); } /** * * @throws Exception */ private void start() throws Exception { if (DataTransferLogic.get().isTransferRequested() || DataTransferLogic.get().isTransferBackRequested()) { // 多重起動チェック if (DataTransferLogic.get().isTransferStarted()) { LOG.info("ALL Ready started."); return; } // DBを起動 Thread thread = new Thread(this); thread.start(); try { // サーバーが起動するまで待機 while (!serverStarted) { Thread.sleep(1000); } // コネクションの設定を読み込み ConnectionConfig defaultConnection = DBConnenctionLogic.get().getDefaultConnectionConfig(); ConnectionConfig customConnection = DBConnenctionLogic.get().getCustomConnectionConfig(); // データ移行を実行(すごく時間がかかる可能性あり) if (DataTransferLogic.get().isTransferBackRequested()) { DataTransferLogic.get().transferData(customConnection, defaultConnection); } else { DataTransferLogic.get().transferData(defaultConnection, customConnection); } } catch (Exception e) { LOG.error("ERROR", e); } finally { // データ移行終了 DataTransferLogic.get().finishTransfer(); // DBを停止 runing = false; thread.join(); } } } }
apache-2.0
tijoparacka/nifi
nifi-nar-bundles/nifi-scripting-bundle/nifi-scripting-processors/src/main/java/org/apache/nifi/record/script/ScriptedRecordSetWriter.java
7624
/* * 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.nifi.record.script; import org.apache.nifi.annotation.behavior.Restricted; import org.apache.nifi.annotation.behavior.Restriction; import org.apache.nifi.annotation.documentation.CapabilityDescription; import org.apache.nifi.annotation.documentation.Tags; import org.apache.nifi.annotation.lifecycle.OnEnabled; import org.apache.nifi.components.RequiredPermission; import org.apache.nifi.components.ValidationResult; import org.apache.nifi.controller.ConfigurationContext; import org.apache.nifi.logging.ComponentLog; import org.apache.nifi.processors.script.ScriptEngineConfigurator; import org.apache.nifi.schema.access.SchemaNotFoundException; import org.apache.nifi.serialization.RecordSetWriter; import org.apache.nifi.serialization.RecordSetWriterFactory; import org.apache.nifi.serialization.record.RecordSchema; import javax.script.Invocable; import javax.script.ScriptException; import java.io.IOException; import java.io.OutputStream; import java.lang.reflect.UndeclaredThrowableException; import java.util.Collection; import java.util.HashSet; import java.util.Map; /** * A RecordSetWriter implementation that allows the user to script the RecordWriter instance */ @Tags({"record", "writer", "script", "invoke", "groovy", "python", "jython", "jruby", "ruby", "javascript", "js", "lua", "luaj", "restricted"}) @CapabilityDescription("Allows the user to provide a scripted RecordSetWriterFactory instance in order to write records to an outgoing flow file.") @Restricted( restrictions = { @Restriction( requiredPermission = RequiredPermission.EXECUTE_CODE, explanation = "Provides operator the ability to execute arbitrary code assuming all permissions that NiFi has.") } ) public class ScriptedRecordSetWriter extends AbstractScriptedRecordFactory<RecordSetWriterFactory> implements RecordSetWriterFactory { @Override @OnEnabled public void onEnabled(final ConfigurationContext context) { super.onEnabled(context); } @Override public RecordSetWriter createWriter(ComponentLog logger, RecordSchema schema, OutputStream out) throws SchemaNotFoundException, IOException { if (recordFactory.get() != null) { try { return recordFactory.get().createWriter(logger, schema, out); } catch (UndeclaredThrowableException ute) { throw new IOException(ute.getCause()); } } return null; } /** * Reloads the script RecordSetWriterFactory. This must be called within the lock. * * @param scriptBody An input stream associated with the script content * @return Whether the script was successfully reloaded */ @Override protected boolean reloadScript(final String scriptBody) { // note we are starting here with a fresh listing of validation // results since we are (re)loading a new/updated script. any // existing validation results are not relevant final Collection<ValidationResult> results = new HashSet<>(); try { // get the engine and ensure its invocable if (scriptEngine instanceof Invocable) { final Invocable invocable = (Invocable) scriptEngine; // Find a custom configurator and invoke their eval() method ScriptEngineConfigurator configurator = scriptingComponentHelper.scriptEngineConfiguratorMap.get(scriptingComponentHelper.getScriptEngineName().toLowerCase()); if (configurator != null) { configurator.eval(scriptEngine, scriptBody, scriptingComponentHelper.getModules()); } else { // evaluate the script scriptEngine.eval(scriptBody); } // get configured processor from the script (if it exists) final Object obj = scriptEngine.get("writer"); if (obj != null) { final ComponentLog logger = getLogger(); try { // set the logger if the processor wants it invocable.invokeMethod(obj, "setLogger", logger); } catch (final NoSuchMethodException nsme) { if (logger.isDebugEnabled()) { logger.debug("Configured script RecordSetWriterFactory does not contain a setLogger method."); } } if (configurationContext != null) { try { // set the logger if the processor wants it invocable.invokeMethod(obj, "setConfigurationContext", configurationContext); } catch (final NoSuchMethodException nsme) { if (logger.isDebugEnabled()) { logger.debug("Configured script RecordSetWriterFactory does not contain a setConfigurationContext method."); } } } // record the processor for use later final RecordSetWriterFactory scriptedWriter = invocable.getInterface(obj, RecordSetWriterFactory.class); recordFactory.set(scriptedWriter); } else { throw new ScriptException("No RecordSetWriterFactory was defined by the script."); } } } catch (final Exception ex) { final ComponentLog logger = getLogger(); final String message = "Unable to load script: " + ex.getLocalizedMessage(); logger.error(message, ex); results.add(new ValidationResult.Builder() .subject("ScriptValidation") .valid(false) .explanation("Unable to load script due to " + ex.getLocalizedMessage()) .input(scriptingComponentHelper.getScriptPath()) .build()); } // store the updated validation results validationResults.set(results); // return whether there was any issues loading the configured script return results.isEmpty(); } @Override public RecordSchema getSchema(Map<String, String> variables, RecordSchema readSchema) throws SchemaNotFoundException, IOException { final RecordSetWriterFactory writerFactory = recordFactory.get(); if (writerFactory == null) { return null; } try { return writerFactory.getSchema(variables, readSchema); } catch (UndeclaredThrowableException ute) { throw new IOException(ute.getCause()); } } }
apache-2.0
spring-cloud/spring-cloud-zookeeper
spring-cloud-zookeeper-core/src/main/java/org/springframework/cloud/zookeeper/ZookeeperHealthAutoConfiguration.java
2290
/* * Copyright 2015-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.cloud.zookeeper; import org.apache.curator.framework.CuratorFramework; import org.springframework.boot.actuate.autoconfigure.health.ConditionalOnEnabledHealthIndicator; import org.springframework.boot.actuate.endpoint.annotation.Endpoint; import org.springframework.boot.autoconfigure.AutoConfigureAfter; import org.springframework.boot.autoconfigure.condition.ConditionalOnBean; import org.springframework.boot.autoconfigure.condition.ConditionalOnClass; import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; /** * Auto {@link Configuration} for adding a Zookeeper health endpoint to actuator if * required. * * @author Tom Gianos * @since 2.0.1 */ @Configuration(proxyBeanMethods = false) @ConditionalOnZookeeperEnabled @ConditionalOnClass(Endpoint.class) @AutoConfigureAfter({ ZookeeperAutoConfiguration.class }) public class ZookeeperHealthAutoConfiguration { /** * If there is an active curator, if the zookeeper health endpoint is enabled and if a * health indicator hasn't already been added by a user add one. * @param curator The curator connection to zookeeper to use * @return An instance of {@link ZookeeperHealthIndicator} to add to actuator health * report */ @Bean @ConditionalOnMissingBean(ZookeeperHealthIndicator.class) @ConditionalOnBean(CuratorFramework.class) @ConditionalOnEnabledHealthIndicator("zookeeper") public ZookeeperHealthIndicator zookeeperHealthIndicator(CuratorFramework curator) { return new ZookeeperHealthIndicator(curator); } }
apache-2.0
recommenders/rival
rival-evaluate/src/test/java/net/recommenders/rival/evaluation/metric/NDCGTest.java
7401
/* * Copyright 2015 recommenders.net. * * 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.recommenders.rival.evaluation.metric; import net.recommenders.rival.core.DataModelIF; import net.recommenders.rival.evaluation.metric.ranking.NDCG; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; import java.util.Map; import net.recommenders.rival.core.DataModelFactory; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNull; /** * Tests for {@link NDCG}. * * @author <a href="http://github.com/alansaid">Alan</a>. */ @RunWith(JUnit4.class) public class NDCGTest { @Test public void testSameGroundtruthAsPredictions() { DataModelIF<Long, Long> predictions = DataModelFactory.getDefaultModel(); DataModelIF<Long, Long> test = DataModelFactory.getDefaultModel(); for (long i = 1L; i < 20; i++) { for (long j = 1L; j < 15; j++) { test.addPreference(i, j, i * j % 5 + 1.0); predictions.addPreference(i, j, i * j % 5 + 1.0); } } NDCG<Long, Long> ndcgBasic = new NDCG<Long, Long>(predictions, test); assertNotNull(ndcgBasic); NDCG<Long, Long> ndcg = new NDCG<Long, Long>(predictions, test, new int[]{5, 10, 20}); ndcg.compute(); assertEquals(1.0, ndcg.getValue(), 0.0); assertEquals(1.0, ndcg.getValueAt(5), 0.0); assertEquals(1.0, ndcg.getValueAt(10), 0.0); Map<Long, Double> ndcgPerUser = ndcg.getValuePerUser(); for (Map.Entry<Long, Double> e : ndcgPerUser.entrySet()) { long user = e.getKey(); double value = e.getValue(); assertEquals(1.0, value, 0.0); } } @Test public void testOrderOneUserTrecevalStrategy() { // groundtruth: 0 1 1 1 // predictions: 0 1 1 1 DataModelIF<Long, Long> test = DataModelFactory.getDefaultModel(); DataModelIF<Long, Long> predictions = DataModelFactory.getDefaultModel(); test.addPreference(1L, 1L, 0.0); test.addPreference(1L, 2L, 1.0); test.addPreference(1L, 3L, 1.0); test.addPreference(1L, 4L, 1.0); predictions.addPreference(1L, 3L, 1.0); predictions.addPreference(1L, 2L, 1.0); predictions.addPreference(1L, 4L, 1.0); predictions.addPreference(1L, 1L, 0.0); NDCG<Long, Long> ndcg = new NDCG<Long, Long>(predictions, test, 1.0, new int[]{1, 2, 3, 4, 5}, NDCG.TYPE.TREC_EVAL); ndcg.compute(); assertEquals(1.0, ndcg.getValue(), 0.001); // change the order of the predictions: // groundtruth: 0 0 1 1 // predictions: 0 1 1 1 test = DataModelFactory.getDefaultModel(); predictions = DataModelFactory.getDefaultModel(); test.addPreference(1L, 1L, 0.0); test.addPreference(1L, 2L, 0.0); test.addPreference(1L, 3L, 1.0); test.addPreference(1L, 4L, 1.0); predictions.addPreference(1L, 4L, 1.0); predictions.addPreference(1L, 3L, 1.0); predictions.addPreference(1L, 2L, 1.0); predictions.addPreference(1L, 1L, 0.0); ndcg = new NDCG<Long, Long>(predictions, test, 1.0, new int[]{1, 2, 3, 4, 5}, NDCG.TYPE.TREC_EVAL); ndcg.compute(); assertEquals(1.0, ndcg.getValue(), 0.001); // groundtruth: 0 1 1 0 // predictions: 0 1 1 1 test = DataModelFactory.getDefaultModel(); predictions = DataModelFactory.getDefaultModel(); test.addPreference(1L, 1L, 0.0); test.addPreference(1L, 20L, 0.0); test.addPreference(1L, 3L, 1.0); test.addPreference(1L, 4L, 1.0); predictions.addPreference(1L, 20L, 1.0); predictions.addPreference(1L, 4L, 1.0); predictions.addPreference(1L, 3L, 1.0); predictions.addPreference(1L, 1L, 0.0); ndcg = new NDCG<Long, Long>(predictions, test, 1.0, new int[]{1, 2, 3, 4, 5}, NDCG.TYPE.TREC_EVAL); ndcg.compute(); assertEquals(0.693, ndcg.getValue(), 0.001); } @Test public void testOneUserTrecevalStrategySingleRelevance() { // groundtruth: ? 0 1 1 // predictions: 3 4 5 1 DataModelIF<Long, Long> test = DataModelFactory.getDefaultModel(); DataModelIF<Long, Long> predictions = DataModelFactory.getDefaultModel(); test.addPreference(1L, 2L, 0.0); test.addPreference(1L, 3L, 1.0); test.addPreference(1L, 4L, 1.0); predictions.addPreference(1L, 1L, 3.0); predictions.addPreference(1L, 2L, 4.0); predictions.addPreference(1L, 3L, 5.0); predictions.addPreference(1L, 4L, 1.0); NDCG<Long, Long> ndcg = new NDCG<Long, Long>(predictions, test, 1.0, new int[]{1, 2, 3, 4, 5}, NDCG.TYPE.TREC_EVAL); ndcg.compute(); assertEquals(0.8772, ndcg.getValue(), 0.001); assertEquals(1.0, ndcg.getValueAt(1), 0.001); assertEquals(0.6131, ndcg.getValueAt(2), 0.001); assertEquals(0.6131, ndcg.getValueAt(3), 0.001); assertEquals(0.8772, ndcg.getValueAt(4), 0.001); assertEquals(0.8772, ndcg.getValueAt(5), 0.001); Map<Long, Double> ndcgPerUser = ndcg.getValuePerUser(); for (Map.Entry<Long, Double> e : ndcgPerUser.entrySet()) { long user = e.getKey(); double value = e.getValue(); assertEquals(0.8772, value, 0.001); } } @Test public void testOneUserTrecevalStrategyMultipleRelevance() { // groundtruth: ? 0 1 2 // predictions: 3 4 5 1 DataModelIF<Long, Long> test = DataModelFactory.getDefaultModel(); DataModelIF<Long, Long> predictions = DataModelFactory.getDefaultModel(); test.addPreference(1L, 2L, 0.0); test.addPreference(1L, 3L, 1.0); test.addPreference(1L, 4L, 2.0); predictions.addPreference(1L, 1L, 3.0); predictions.addPreference(1L, 2L, 4.0); predictions.addPreference(1L, 3L, 5.0); predictions.addPreference(1L, 4L, 1.0); NDCG<Long, Long> ndcg = new NDCG<Long, Long>(predictions, test, 1.0, new int[]{1, 2, 3, 4, 5}, NDCG.TYPE.TREC_EVAL); ndcg.compute(); assertEquals(0.7075, ndcg.getValue(), 0.001); assertEquals(0.5, ndcg.getValueAt(1), 0.001); assertEquals(0.3801, ndcg.getValueAt(2), 0.001); assertEquals(0.3801, ndcg.getValueAt(3), 0.001); assertEquals(0.7075, ndcg.getValueAt(4), 0.001); assertEquals(0.7075, ndcg.getValueAt(5), 0.001); Map<Long, Double> ndcgPerUser = ndcg.getValuePerUser(); for (Map.Entry<Long, Double> e : ndcgPerUser.entrySet()) { long user = e.getKey(); double value = e.getValue(); assertEquals(0.7075, value, 0.001); } } }
apache-2.0
keetip/versio
core/src/main/java/com/keetip/versio/domain/Project.java
2561
/* * Copyright (c) 2014 Keetip * * 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 product may include a number of subcomponents with separate copyright notices and * license terms. Your use of the source code for the these subcomponents is subject to * the terms and conditions of the subcomponent's license, as noted in the LICENSE file. */ package com.keetip.versio.domain; import java.util.Date; import java.util.UUID; import org.apache.commons.lang.Validate; import org.apache.commons.lang.builder.EqualsBuilder; import org.apache.commons.lang.builder.HashCodeBuilder; import com.keetip.ddd.domain.Entity; /** * @author keetip * */ public class Project implements Entity<Project>{ private final UUID mUuid; private final String mName; private String mDescription; private Date mCreationDate; /** * Construct a new persisted Project entity * * @param uuid */ public Project(UUID uuid, String name){ Validate.notNull(uuid, "Project id is required"); Validate.notNull(name, "Project name is required"); mUuid = uuid; mName = name; } /** * Construct a new transient Project entity * * @return */ public static Project newProject(String name){ return new Project(UUID.randomUUID(), name); } public UUID getUuid() { return mUuid; } public String getName() { return mName; } public String getDescription() { return mDescription; } public void setDescription(String description) { mDescription = description; } public Date getCreationDate() { return mCreationDate; } public void setCreationDate(Date creationDate) { mCreationDate = creationDate; } @Override public int hashCode() { return new HashCodeBuilder() .append(mUuid) .hashCode(); } @Override public boolean equals(Object obj) { if(!(obj instanceof Project)){ return false; } Project other = (Project)obj; return sameIdentityAs(other); } public boolean sameIdentityAs(Project other) { return new EqualsBuilder() .append(mUuid, other.getUuid()) .isEquals(); } }
apache-2.0
whiskeysierra/tracer
tracer-okhttp/src/test/java/org/zalando/tracer/okhttp/FlowInterceptorTest.java
2347
package org.zalando.tracer.okhttp; import com.github.restdriver.clientdriver.ClientDriver; import com.github.restdriver.clientdriver.ClientDriverFactory; import io.opentracing.Scope; import io.opentracing.Span; import io.opentracing.mock.MockTracer; import okhttp3.OkHttpClient; import okhttp3.Request; import okhttp3.Response; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.Test; import org.zalando.tracer.Flow; import java.io.IOException; import static com.github.restdriver.clientdriver.RestClientDriver.giveResponse; import static com.github.restdriver.clientdriver.RestClientDriver.onRequestTo; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.is; final class FlowInterceptorTest { private final ClientDriver server = new ClientDriverFactory().createClientDriver(); private final MockTracer tracer = new MockTracer(); private final Flow flow = Flow.create(tracer); private final OkHttpClient client = new OkHttpClient.Builder() .addNetworkInterceptor(new FlowInterceptor(flow)) .build(); @AfterEach void shutdownServer() { server.shutdownQuietly(); } @Test void shouldAddHeaderFromTraceId() throws IOException { final Span span = tracer.buildSpan("test").start(); server.addExpectation(onRequestTo("/") .withHeader("X-Flow-ID", span.context().toTraceId()), giveResponse("Hello, world!", "text/plain")); execute(span); } @Test void shouldAddHeaderFromBaggage() throws IOException { server.addExpectation(onRequestTo("/") .withHeader("X-Flow-ID", "REcCvlqMSReeo7adheiYFA"), giveResponse("Hello, world!", "text/plain")); execute(tracer.buildSpan("test").start() .setBaggageItem("flow_id", "REcCvlqMSReeo7adheiYFA")); } private void execute(final Span span) throws IOException { try (final Scope ignored = tracer.activateSpan(span)) { final Response response = client.newCall(new Request.Builder() .url(server.getBaseUrl()) .build()).execute(); assertThat(response.code(), is(200)); assertThat(response.body().string(), is("Hello, world!")); } } }
apache-2.0
ow2-xlcloud/openstack-sdk
openstack-climate-sdk/src/main/java/org/xlcloud/openstack/model/climate/Lease.java
4900
/* * Copyright 2012 AMG.lab, a Bull Group Company * * 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.xlcloud.openstack.model.climate; import java.util.ArrayList; import java.util.Date; import java.util.List; import org.xlcloud.openstack.model.climate.json.OpenStackDateDeserializer; import org.xlcloud.openstack.model.climate.json.OpenStackDateSerializer; import com.fasterxml.jackson.annotation.JsonIgnore; import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.annotation.JsonInclude.Include; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.databind.annotation.JsonDeserialize; import com.fasterxml.jackson.databind.annotation.JsonSerialize; /** * Entity enables to create basic reservation of physical resources * * @author Michał Kamiński, AMG.net */ public class Lease { @JsonProperty( "id" ) private String id; @JsonProperty( "user_id" ) private String userId; @JsonProperty( "name" ) private String name; @JsonProperty( "start_date" ) @JsonSerialize( using = OpenStackDateSerializer.class ) @JsonDeserialize( using = OpenStackDateDeserializer.class ) @JsonInclude( Include.NON_NULL ) private Date startDate; @JsonProperty( "end_date" ) @JsonSerialize( using = OpenStackDateSerializer.class ) @JsonDeserialize( using = OpenStackDateDeserializer.class ) @JsonInclude( Include.NON_NULL ) private Date endDate; @JsonProperty( "created_at" ) @JsonSerialize( using = OpenStackDateSerializer.class ) @JsonDeserialize( using = OpenStackDateDeserializer.class ) @JsonInclude( Include.NON_NULL ) private Date createdAt; @JsonProperty( "updated_at" ) @JsonSerialize( using = OpenStackDateSerializer.class ) @JsonDeserialize( using = OpenStackDateDeserializer.class ) @JsonInclude( Include.NON_NULL ) private Date updatedAt; @JsonProperty( "reservations" ) List<Reservation> reservations; @JsonProperty( "events" ) List<Event> events; @JsonProperty( "tenant_id" ) private String tenantId; @JsonProperty( "trust_id" ) private String trustId; public String getId() { return id; } public void setId(String id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public Date getStartDate() { return startDate; } public void setStartDate(Date startDate) { this.startDate = startDate; } public Date getEndDate() { return endDate; } public void setEndDate(Date endDate) { this.endDate = endDate; } public List<Reservation> getReservations() { if (reservations == null) { reservations = new ArrayList<Reservation>(); } return reservations; } public void setReservations(List<Reservation> reservations) { this.reservations = reservations; } public List<Event> getEvents() { if (events == null) { events = new ArrayList<Event>(); } return events; } public String getTenantId() { return tenantId; } public void setTenantId(String tenantId) { this.tenantId = tenantId; } public String getUserId() { return userId; } public void setUserId(String userId) { this.userId = userId; } public Date getCreatedAt() { return createdAt; } public void setCreatedAt(Date createdAt) { this.createdAt = createdAt; } public Date getUpdatedAt() { return updatedAt; } public void setUpdatedAt(Date updatedAt) { this.updatedAt = updatedAt; } public String getTrustId() { return trustId; } public void setTrustId(String trustId) { this.trustId = trustId; } @JsonIgnore public Event getStartEvent() { return getEventByType(EventType.START); } @JsonIgnore public Event getEndEvent() { return getEventByType(EventType.END); } @JsonIgnore private Event getEventByType(EventType type) { for (Event event : getEvents()) { if (type.equals(event.getEventType())) { return event; } } return null; } }
apache-2.0
jentfoo/aws-sdk-java
aws-java-sdk-medialive/src/main/java/com/amazonaws/services/medialive/model/transform/Scte27SourceSettingsJsonUnmarshaller.java
2791
/* * 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.medialive.model.transform; import java.math.*; import javax.annotation.Generated; import com.amazonaws.services.medialive.model.*; import com.amazonaws.transform.SimpleTypeJsonUnmarshallers.*; import com.amazonaws.transform.*; import com.fasterxml.jackson.core.JsonToken; import static com.fasterxml.jackson.core.JsonToken.*; /** * Scte27SourceSettings JSON Unmarshaller */ @Generated("com.amazonaws:aws-java-sdk-code-generator") public class Scte27SourceSettingsJsonUnmarshaller implements Unmarshaller<Scte27SourceSettings, JsonUnmarshallerContext> { public Scte27SourceSettings unmarshall(JsonUnmarshallerContext context) throws Exception { Scte27SourceSettings scte27SourceSettings = new Scte27SourceSettings(); int originalDepth = context.getCurrentDepth(); String currentParentElement = context.getCurrentParentElement(); int targetDepth = originalDepth + 1; JsonToken token = context.getCurrentToken(); if (token == null) token = context.nextToken(); if (token == VALUE_NULL) { return null; } while (true) { if (token == null) break; if (token == FIELD_NAME || token == START_OBJECT) { if (context.testExpression("pid", targetDepth)) { context.nextToken(); scte27SourceSettings.setPid(context.getUnmarshaller(Integer.class).unmarshall(context)); } } else if (token == END_ARRAY || token == END_OBJECT) { if (context.getLastParsedParentElement() == null || context.getLastParsedParentElement().equals(currentParentElement)) { if (context.getCurrentDepth() <= originalDepth) break; } } token = context.nextToken(); } return scte27SourceSettings; } private static Scte27SourceSettingsJsonUnmarshaller instance; public static Scte27SourceSettingsJsonUnmarshaller getInstance() { if (instance == null) instance = new Scte27SourceSettingsJsonUnmarshaller(); return instance; } }
apache-2.0
OdessaAlexSV/java_forTester
mantis-tests/src/test/java/ru/stqa/pft/mantis/appmanager/RegistrationHelper.java
750
package ru.stqa.pft.mantis.appmanager; import org.openqa.selenium.By; /** * Created by asviderskiy on 11.04.2016. */ public class RegistrationHelper extends HelperBase { public RegistrationHelper(ApplicationManager app) { super(app); } public void start(String username, String email) { wd.get(app.getProperty("web.baseUrl") + "/signup_page.php"); type(By.name("username"), username); type(By.name("email"), email); click(By.cssSelector("input[value='Signup']")); } public void finish(String confirmationLink, String password) { wd.get(confirmationLink); type(By.name("password"), password); type(By.name("password_confirm"), password); click(By.cssSelector("input[value='Update User']")); } }
apache-2.0
raducotescu/publick-sling-blog
src/main/java/com/nateyolles/sling/publick/sightly/WCMUse.java
5429
package com.nateyolles.sling.publick.sightly; import java.net.URI; import java.net.URISyntaxException; import javax.jcr.RepositoryException; import javax.jcr.Session; import javax.script.Bindings; import org.apache.commons.lang.StringUtils; import org.apache.jackrabbit.api.JackrabbitSession; import org.apache.jackrabbit.api.security.user.Group; import org.apache.jackrabbit.api.security.user.User; import org.apache.sling.api.SlingHttpServletRequest; import org.apache.sling.api.SlingHttpServletResponse; import org.apache.sling.api.resource.Resource; import org.apache.sling.api.resource.ResourceResolver; import org.apache.sling.api.resource.ValueMap; import org.apache.sling.api.scripting.SlingBindings; import org.apache.sling.api.scripting.SlingScriptHelper; import org.apache.sling.scripting.sightly.pojo.Use; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.nateyolles.sling.publick.PublickConstants; /** * The base class that all Sightly components should extend * from. Any sightly component extending this class should * simply override the #activate() method. Instead of using * Sling Bindings, the classes can use the provided helper * methods. */ public class WCMUse implements Use { /** * File extension for HTML files, used in getting page paths. */ private static final String HTML_EXTENSION = ".html"; /** * Logger instance to log and debug errors. */ private static final Logger LOGGER = LoggerFactory.getLogger(WCMUse.class); /** * Global bindings populated by the init method. */ private Bindings bindings; /** * Sightly component initialization. * * @param bindings The current execution context. */ @Override public void init(Bindings bindings) { this.bindings = bindings; activate(); } /** * The activate method is meant to be overridden as it's the * entry point to the extended class. */ public void activate() { } /** * Get the current resource. * * @return The current resource. */ public Resource getResource() { return (Resource)bindings.get(SlingBindings.RESOURCE); } /** * Get the resource resolver backed by the current resource. * * @return The current resource resolver. */ public ResourceResolver getResourceResolver() { return getResource().getResourceResolver(); } /** * Get the current resource properties. * * @return The current resource properties. */ public ValueMap getProperties() { return getResource().adaptTo(ValueMap.class); } /** * Get the current Sling Script Helper. * * @return The current Sling Script Helper. */ public SlingScriptHelper getSlingScriptHelper() { return (SlingScriptHelper)bindings.get(SlingBindings.SLING); } /** * Get the current request. * * @return The current Sling HTTP Servlet Request. */ public SlingHttpServletRequest getRequest() { return (SlingHttpServletRequest)bindings.get(SlingBindings.REQUEST); } /** * Get the current response. * * @return The current Sling HTTP Servlet Response. */ public SlingHttpServletResponse getResponse() { return (SlingHttpServletResponse)bindings.get(SlingBindings.RESPONSE); } /** * Get the current JCR session. * * @return The current JCR session. */ public Session getSession() { return getResourceResolver().adaptTo(Session.class); } /** * Get the authorable status of the current user. * TODO: remove and use UserService * * @return true if the current user is an admin or author. */ public boolean isAuthorable() { boolean authorable = false; JackrabbitSession js = (JackrabbitSession)getSession(); try { Group authors = (Group)js.getUserManager().getAuthorizable(PublickConstants.GROUP_ID_AUTHORS); User user = (User)js.getUserManager().getAuthorizable(js.getUserID()); authorable = user.isAdmin() || authors.isMember(user); } catch (RepositoryException e) { LOGGER.error("Could not determine group membership", e); } return authorable; } /** * Generate the absolute resource path from the relative path. * * @return The absolute blog post display path. */ public String getAbsolutePath(final String relativePath) { String displayPath = null; String newRelativePath = relativePath; if (StringUtils.isNotBlank(newRelativePath)) { try { URI uri = new URI(getRequest().getRequestURL().toString()); if (relativePath.startsWith("/content/")) { newRelativePath = StringUtils.removeStart(newRelativePath, "/content"); } newRelativePath = StringUtils.removeEnd(newRelativePath, "/"); displayPath = new URI(uri.getScheme(), uri.getUserInfo(), uri.getHost(), uri.getPort(), newRelativePath, uri.getQuery(), uri.getFragment()).toString(); } catch (URISyntaxException e) { LOGGER.error("Could not get create absolute path from Request URL", e); } } return displayPath; } }
apache-2.0
tesshucom/subsonic-fx-player
subsonic-fx-player-api/src/main/java/com/tesshu/subsonic/client/fx/view/browsing/id3/IndexRow.java
928
/** * Copyright © 2017 tesshu.com (webmaster@tesshu.com) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.tesshu.subsonic.client.fx.view.browsing.id3; public interface IndexRow extends BrowsingID3Row { default ArtistID3Wrapper getArtist() { return null; }; default boolean isAnalized() { return false; }; default void setAnalized(boolean isAnalized) { // to be none }; }
apache-2.0
datazuul/com.datazuul.webapps--netcms
src/main/java/de/javapro/netcms/frontend/wicket/ImageResource.java
1153
package de.javapro.netcms.frontend.wicket; import org.apache.wicket.markup.html.DynamicWebResource; import org.apache.wicket.util.string.StringValueConversionException; import org.apache.wicket.util.value.ValueMap; import com.datazuul.commons.cms.backend.NetCMSRepository; import com.datazuul.commons.cms.domain.DomainName; import com.datazuul.commons.cms.domain.Image; public class ImageResource extends DynamicWebResource { @Override protected ResourceState getResourceState() { long id = -1; final ValueMap params = getParameters(); if (params != null) { if (params.containsKey("id")) { try { id = params.getLong("id"); } catch (final StringValueConversionException e) { // invalid id show error message // TODO } final String imageSize = params.getString("size"); final NetCMSRepository repository = NetCMSRepository.getInstance(); final DomainName dn = ((NetCMSApplication) NetCMSApplication.get()).getDomainName(); final Image image = repository.getImageById(dn, id); final ImageResourceState state = new ImageResourceState(image, imageSize); return state; } } return null; } }
apache-2.0
lbendig/gobblin
gobblin-runtime/src/main/java/gobblin/runtime/mapreduce/MRTask.java
4672
/* * 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 gobblin.runtime.mapreduce; import com.google.common.collect.Maps; import gobblin.configuration.State; import gobblin.configuration.WorkUnitState; import gobblin.metrics.event.EventSubmitter; import gobblin.runtime.TaskContext; import gobblin.runtime.task.BaseAbstractTask; import java.io.IOException; import java.util.Map; import lombok.extern.slf4j.Slf4j; import org.apache.commons.lang.exception.ExceptionUtils; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.mapreduce.Job; /** * A task that runs an MR job. * * Usage: * TaskUtils.setTaskFactoryClass(workUnit, MRTaskFactory.class); * MRTask.serializeJobToState(workUnit, myJob); * * Subclasses can override {@link #createJob()} to customize the way the MR job is prepared. */ @Slf4j public class MRTask extends BaseAbstractTask { private static final String JOB_CONFIGURATION_PREFIX = "MRTask.jobConfiguration."; public static class Events { public static final String MR_JOB_STARTED_EVENT = "MRJobStarted"; public static final String MR_JOB_SUCCESSFUL = "MRJobSuccessful"; public static final String MR_JOB_FAILED = "MRJobFailed"; public static final String JOB_URL = "jobTrackingUrl"; public static final String FAILURE_CONTEXT = "failureContext"; } public static void serializeJobToState(State state, Job job) { for (Map.Entry<String, String> entry : job.getConfiguration()) { state.setProp(JOB_CONFIGURATION_PREFIX + entry.getKey(), entry.getValue()); } } private final TaskContext taskContext; private final EventSubmitter eventSubmitter; public MRTask(TaskContext taskContext) { super(taskContext); this.taskContext = taskContext; this.eventSubmitter = new EventSubmitter.Builder(this.metricContext, "gobblin.MRTask") .addMetadata(additionalEventMetadata()).build(); } public void onMRTaskComplete (boolean isSuccess, Throwable t) throws RuntimeException { if (isSuccess) { this.workingState = WorkUnitState.WorkingState.SUCCESSFUL; } else if (t == null) { this.workingState = WorkUnitState.WorkingState.FAILED; } else { log.error ("Failed to run MR job with exception {}", ExceptionUtils.getStackTrace(t)); this.workingState = WorkUnitState.WorkingState.FAILED; } } @Override public void commit() { log.debug ("State is set to {} inside onMRTaskComplete.", this.workingState); } @Override public void run() { try { Job job = createJob(); job.submit(); this.eventSubmitter.submit(Events.MR_JOB_STARTED_EVENT, Events.JOB_URL, job.getTrackingURL()); job.waitForCompletion(false); if (job.isSuccessful()) { this.eventSubmitter.submit(Events.MR_JOB_SUCCESSFUL, Events.JOB_URL, job.getTrackingURL()); this.onMRTaskComplete(true, null); } else { this.eventSubmitter.submit(Events.MR_JOB_FAILED, Events.JOB_URL, job.getTrackingURL()); this.onMRTaskComplete (false, new IOException("MR Job is not successful")); } } catch (Throwable t) { log.error("Failed to run MR job.", t); this.eventSubmitter.submit(Events.MR_JOB_FAILED, Events.FAILURE_CONTEXT, t.getMessage()); this.onMRTaskComplete (false, t); } } protected Map<String, String> additionalEventMetadata() { return Maps.newHashMap(); } protected Job createJob() throws IOException { Job job = Job.getInstance(new Configuration()); for (Map.Entry<Object, Object> entry : this.taskContext.getTaskState().getProperties().entrySet()) { if (entry.getKey() instanceof String && ((String) entry.getKey()).startsWith(JOB_CONFIGURATION_PREFIX)) { String actualKey = ((String) entry.getKey()).substring(JOB_CONFIGURATION_PREFIX.length()); job.getConfiguration().set(actualKey, (String) entry.getValue()); } } return job; } }
apache-2.0
sankoudai/java-knowledge-center
java-knowledge-basics/src/main/java/com/sankoudai/java/basics/topics/TestParameter.java
543
package com.sankoudai.java.basics.topics; import junit.framework.TestCase; import java.util.Arrays; /** * @author : sankoudai * @version : created at 2015/8/11 */ public class TestParameter extends TestCase { public void testVarargs(){ varargsMethod("jim", "Lilei"); varargsMethod(null, "hi"); } private void varargsMethod(Object ... params){ System.out.println(params.getClass()); System.out.println(params instanceof Object[]); System.out.println(Arrays.toString(params)); } }
apache-2.0
onesummers/fogweather
app/src/main/java/com/fogweather/android/gson/Now.java
362
package com.fogweather.android.gson; import com.google.gson.annotations.SerializedName; /** * Created by Administrator on 2017/9/19. */ public class Now { @SerializedName("tmp") public String temperature ; @SerializedName("cond") public More more ; public class More{ @SerializedName("txt") public String info ; } }
apache-2.0
xjtu3c/GranuleJ
GOP/GranuleJIDE/src/AST/VariableArityParameterDeclaration.java
7777
package AST; import java.util.HashSet; import java.util.LinkedHashSet; import java.io.File; import java.util.*; import beaver.*; import java.util.ArrayList; import java.util.zip.*; import java.io.*; import java.util.Stack; import java.util.regex.Pattern; import java.io.FileOutputStream; import java.io.IOException; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import javax.xml.transform.stream.StreamResult; import javax.xml.transform.dom.DOMSource; import javax.xml.transform.TransformerFactory; import javax.xml.transform.Transformer; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import org.w3c.dom.Element; import org.w3c.dom.Document; import java.util.HashMap; import java.util.Map.Entry; import javax.xml.transform.TransformerException; import javax.xml.parsers.ParserConfigurationException; import java.util.Collection; /** * @ast node * @declaredat VariableArityParameters.ast:1 */ public class VariableArityParameterDeclaration extends ParameterDeclaration implements Cloneable { /** * @apilvl low-level */ public void flushCache() { super.flushCache(); type_computed = false; type_value = null; } /** * @apilvl internal */ public void flushCollectionCache() { super.flushCollectionCache(); } /** * @apilvl internal */ @SuppressWarnings({"unchecked", "cast"}) public VariableArityParameterDeclaration clone() throws CloneNotSupportedException { VariableArityParameterDeclaration node = (VariableArityParameterDeclaration)super.clone(); node.type_computed = false; node.type_value = null; node.in$Circle(false); node.is$Final(false); return node; } /** * @apilvl internal */ @SuppressWarnings({"unchecked", "cast"}) public VariableArityParameterDeclaration copy() { try { VariableArityParameterDeclaration node = (VariableArityParameterDeclaration)clone(); if(children != null) node.children = (ASTNode[])children.clone(); return node; } catch (CloneNotSupportedException e) { } System.err.println("Error: Could not clone node of type " + getClass().getName() + "!"); return null; } /** * @apilvl low-level */ @SuppressWarnings({"unchecked", "cast"}) public VariableArityParameterDeclaration fullCopy() { VariableArityParameterDeclaration res = (VariableArityParameterDeclaration)copy(); for(int i = 0; i < getNumChildNoTransform(); i++) { ASTNode node = getChildNoTransform(i); if(node != null) node = node.fullCopy(); res.setChild(node, i); } return res; } /** * @ast method * @aspect VariableArityParameters * @declaredat D:\zhh\JastAddJ\Java1.5Frontend\VariableArityParameters.jrag:15 */ public void nameCheck() { super.nameCheck(); if(!variableArityValid()) error("only the last formal paramater may be of variable arity"); } /** * @ast method * @aspect VariableArityParameters * @declaredat D:\zhh\JastAddJ\Java1.5Frontend\VariableArityParameters.jrag:101 */ public void toString(StringBuffer s) { getModifiers().toString(s); getTypeAccess().toString(s); s.append(" ... " + name()); } /** * @ast method * @declaredat VariableArityParameters.ast:1 */ public VariableArityParameterDeclaration() { super(); } /** * @ast method * @declaredat VariableArityParameters.ast:7 */ public VariableArityParameterDeclaration(Modifiers p0, Access p1, String p2) { setChild(p0, 0); setChild(p1, 1); setID(p2); } /** * @ast method * @declaredat VariableArityParameters.ast:12 */ public VariableArityParameterDeclaration(Modifiers p0, Access p1, beaver.Symbol p2) { setChild(p0, 0); setChild(p1, 1); setID(p2); } /** * @apilvl low-level * @ast method * @declaredat VariableArityParameters.ast:20 */ protected int numChildren() { return 2; } /** * @apilvl internal * @ast method * @declaredat VariableArityParameters.ast:26 */ public boolean mayHaveRewrite() { return false; } /** * Setter for Modifiers * @apilvl high-level * @ast method * @declaredat java.ast:5 */ public void setModifiers(Modifiers node) { setChild(node, 0); } /** * Getter for Modifiers * @apilvl high-level * @ast method * @declaredat java.ast:12 */ public Modifiers getModifiers() { return (Modifiers)getChild(0); } /** * @apilvl low-level * @ast method * @declaredat java.ast:18 */ public Modifiers getModifiersNoTransform() { return (Modifiers)getChildNoTransform(0); } /** * Setter for TypeAccess * @apilvl high-level * @ast method * @declaredat java.ast:5 */ public void setTypeAccess(Access node) { setChild(node, 1); } /** * Getter for TypeAccess * @apilvl high-level * @ast method * @declaredat java.ast:12 */ public Access getTypeAccess() { return (Access)getChild(1); } /** * @apilvl low-level * @ast method * @declaredat java.ast:18 */ public Access getTypeAccessNoTransform() { return (Access)getChildNoTransform(1); } /** * Setter for lexeme ID * @apilvl high-level * @ast method * @declaredat java.ast:5 */ public void setID(String value) { tokenString_ID = value; } /** * @ast method * @declaredat java.ast:8 */ public void setID(beaver.Symbol symbol) { if(symbol.value != null && !(symbol.value instanceof String)) throw new UnsupportedOperationException("setID is only valid for String lexemes"); tokenString_ID = (String)symbol.value; IDstart = symbol.getStart(); IDend = symbol.getEnd(); } /** * Getter for lexeme ID * @apilvl high-level * @ast method * @declaredat java.ast:19 */ public String getID() { return tokenString_ID != null ? tokenString_ID : ""; } /* If the last formal parameter is a variable arity parameter of type T, it is considered to define a formal parameter of type T[].* @attribute syn * @aspect VariableArityParameters * @declaredat D:\zhh\JastAddJ\Java1.5Frontend\VariableArityParameters.jrag:30 */ @SuppressWarnings({"unchecked", "cast"}) public TypeDecl type() { if(type_computed) { return type_value; } ASTNode$State state = state(); int num = state.boundariesCrossed; boolean isFinal = this.is$Final(); type_value = type_compute(); if(isFinal && num == state().boundariesCrossed) type_computed = true; return type_value; } /** * @apilvl internal */ private TypeDecl type_compute() { return super.type().arrayType(); } /** * @attribute syn * @aspect VariableArityParameters * @declaredat D:\zhh\JastAddJ\Java1.5Frontend\VariableArityParameters.jrag:36 */ @SuppressWarnings({"unchecked", "cast"}) public boolean isVariableArity() { ASTNode$State state = state(); boolean isVariableArity_value = isVariableArity_compute(); return isVariableArity_value; } /** * @apilvl internal */ private boolean isVariableArity_compute() { return true; } /** * @attribute inh * @aspect VariableArityParameters * @declaredat D:\zhh\JastAddJ\Java1.5Frontend\VariableArityParameters.jrag:26 */ @SuppressWarnings({"unchecked", "cast"}) public boolean variableArityValid() { ASTNode$State state = state(); boolean variableArityValid_value = getParent().Define_boolean_variableArityValid(this, null); return variableArityValid_value; } /** * @apilvl internal */ public ASTNode rewriteTo() { return super.rewriteTo(); } }
apache-2.0
creswick/StreamingQR
development/qrlib/src/main/java/com/galois/qrstream/qrpipe/IProgress.java
792
/** * Copyright 2014 Galois, 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.galois.qrstream.qrpipe; import com.galois.qrstream.qrpipe.DecodeState; public interface IProgress { void changeState(DecodeState state); void drawFinderPoints(float[] pts); }
apache-2.0
datanucleus/tests
jakarta/rdbms/src/java/org/datanucleus/samples/annotations/embedded/collection/EmbeddedCollElement.java
2303
/********************************************************************** Copyright (c) 2016 Andy Jefferson and others. 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. Contributors: ... **********************************************************************/ package org.datanucleus.samples.annotations.embedded.collection; import jakarta.persistence.Column; import jakarta.persistence.Embeddable; /** * Element embedded in a collection. */ @Embeddable public class EmbeddedCollElement { @Column(name="NAME") String name; @Column(name="VALUE") long value; public EmbeddedCollElement(String name, long val) { this.name = name; this.value = val; } public String getName() { return name; } public long getValue() { return value; } /* (non-Javadoc) * @see java.lang.Object#hashCode() */ @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((name == null) ? 0 : name.hashCode()); result = prime * result + (int) (value ^ (value >>> 32)); return result; } /* (non-Javadoc) * @see java.lang.Object#equals(java.lang.Object) */ @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; EmbeddedCollElement other = (EmbeddedCollElement) obj; if (name == null) { if (other.name != null) return false; } else if (!name.equals(other.name)) return false; if (value != other.value) return false; return true; } }
apache-2.0
play2-maven-plugin/play2-maven-test-projects
play24/java/computer-database/app/models/Company.java
948
package models; import java.util.*; import javax.persistence.*; //import play.db.ebean.*; import play.data.validation.*; import com.avaje.ebean.*; /** * Company entity managed by Ebean */ @Entity public class Company extends Model { private static final long serialVersionUID = 1L; @Id public Long id; @Constraints.Required public String name; /** * Generic query helper for entity Company with id Long */ public static Model.Find<Long,Company> find = new Model.Find<Long,Company>(){}; //public static Model.Finder<Long,Company> find = new Model.Finder<Long,Company>(Long.class, Company.class); public static Map<String,String> options() { LinkedHashMap<String,String> options = new LinkedHashMap<String,String>(); for(Company c: Company.find.orderBy("name").findList()) { options.put(c.id.toString(), c.name); } return options; } }
apache-2.0
johnythomas/JavaAlgorithms
src/main/java/johny/javaalgorithms/algorithms/QuickSort.java
3451
package johny.javaalgorithms.algorithms; public class QuickSort { /** * does quicksort on the array passed as the input * * @param array - the array to be sorted * @param left - the left index from which the sorting is to be done * @param right - the right index to which the sorting will be done */ public void quickSort(int[] array, int left, int right) { /*left index will be less than the right index if sorting has to be done otherwise sorting cannot be done*/ if (left >= right) { return; } /*we will choose the middle element as the pivot*/ int pivot = array[(left + right) / 2]; /* * calling the partition method which will rearrange the array based on the pivot. * It returns the partitionIndex based on which the array will be divided into 2 and quicksort will be done on both the arrays */ int partitionIndex = partition(array, left, right, pivot); /* * calling the quicksort recursively. * This will do the same steps in the left array till partitionIndex - 1 */ quickSort(array, left, partitionIndex - 1); /* * calling the quicksort recursively. * This will do the same steps in the right array from partitionIndex */ quickSort(array, partitionIndex, right); } /** * This method is the core of the quicksort * This method will find the partition index based on which the array will be partitioned and quicksort will be done again recursively * @param array - the array which has to be partitioned * @param left - partitioning will be done from this index * @param right - partitioning will be done till this index * @param pivot - the pivot value will decide the movement of the left and the right index * @return will return the partitioning index */ private int partition(int[] array, int left, int right, int pivot) { /* nothing to be done if left is less than right */ while (left < right) { /* increment the left till there is an element which is greater than the pivot */ while (array[left] < pivot) { left++; } /* decrement the right till there is an element which is less than the pivot */ while (array[right] > pivot) { right--; } /* check if left is less than right if the left and right has not crossed and it is stuck */ if (left <= right) { /* swap the left with the right element */ swap(array, left, right); /* move both left and right */ left++; right--; } } /* the partitionIndex will be the left index */ return left; } /** * This method will swap 2 elements in an array passed * @param array - the array in which the swapping has to be done * @param left - the index which need to be swapped * @param right - the second index which needs to be swapped */ private void swap(int[] array, int left, int right) { /* swapping the values using a temp */ int temp = array[left]; array[left] = array[right]; array[right] = temp; } }
apache-2.0
vam-google/google-cloud-java
google-api-grpc/proto-google-cloud-container-v1/src/main/java/com/google/container/v1/ClientCertificateConfigOrBuilder.java
526
// Generated by the protocol buffer compiler. DO NOT EDIT! // source: google/container/v1/cluster_service.proto package com.google.container.v1; public interface ClientCertificateConfigOrBuilder extends // @@protoc_insertion_point(interface_extends:google.container.v1.ClientCertificateConfig) com.google.protobuf.MessageOrBuilder { /** * * * <pre> * Issue a client certificate. * </pre> * * <code>bool issue_client_certificate = 1;</code> */ boolean getIssueClientCertificate(); }
apache-2.0
lmenezes/elasticsearch
src/main/java/org/elasticsearch/search/facet/terms/strings/HashedAggregator.java
9993
/* * Licensed to ElasticSearch and Shay Banon under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. ElasticSearch licenses this * file to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.elasticsearch.search.facet.terms.strings; import com.carrotsearch.hppc.ObjectIntOpenHashMap; import com.google.common.collect.ImmutableList; import org.apache.lucene.util.ArrayUtil; import org.apache.lucene.util.BytesRef; import org.apache.lucene.util.BytesRefHash; import org.elasticsearch.common.collect.BoundedTreeSet; import org.elasticsearch.common.lucene.HashedBytesRef; import org.elasticsearch.index.fielddata.BytesValues; import org.elasticsearch.index.fielddata.BytesValues.Iter; import org.elasticsearch.search.facet.InternalFacet; import org.elasticsearch.search.facet.terms.TermsFacet; import org.elasticsearch.search.facet.terms.support.EntryPriorityQueue; import java.util.Arrays; public class HashedAggregator { private int missing; private int total; private final HashCount hash; private final HashCount assertHash = getAssertHash(); public HashedAggregator() { hash = new BytesRefHashHashCount(new BytesRefHash()); } public void onDoc(int docId, BytesValues values) { if (values.hasValue(docId)) { final Iter iter = values.getIter(docId); while (iter.hasNext()) { onValue(docId, iter.next(), iter.hash(), values); total++; } } else { missing++; } } public void addValue(BytesRef value, int hashCode, BytesValues values) { final boolean added = hash.addNoCount(value, hashCode, values); assert assertHash.addNoCount(value, hashCode, values) == added : "asserting counter diverged from current counter - value: " + value + " hash: " + hashCode; } protected void onValue(int docId, BytesRef value, int hashCode, BytesValues values) { final boolean added = hash.add(value, hashCode, values); // note: we must do a deep copy here the incoming value could have been // modified by a script or so assert assertHash.add(BytesRef.deepCopyOf(value), hashCode, values) == added : "asserting counter diverged from current counter - value: " + value + " hash: " + hashCode; } public final int missing() { return missing; } public final int total() { return total; } public final boolean isEmpty() { return hash.size() == 0; } public BytesRefCountIterator getIter() { assert hash.size() == assertHash.size(); return hash.iter(); } public void release() { hash.release(); } public static interface BytesRefCountIterator { public BytesRef next(); BytesRef makeSafe(); public int count(); public boolean shared(); } public static InternalFacet buildFacet(String facetName, int size, int shardSize, long missing, long total, TermsFacet.ComparatorType comparatorType, HashedAggregator aggregator) { if (aggregator.isEmpty()) { return new InternalStringTermsFacet(facetName, comparatorType, size, ImmutableList.<InternalStringTermsFacet.TermEntry>of(), missing, total); } else { if (shardSize < EntryPriorityQueue.LIMIT) { EntryPriorityQueue ordered = new EntryPriorityQueue(shardSize, comparatorType.comparator()); BytesRefCountIterator iter = aggregator.getIter(); while (iter.next() != null) { ordered.insertWithOverflow(new InternalStringTermsFacet.TermEntry(iter.makeSafe(), iter.count())); // maybe we can survive with a 0-copy here if we keep the // bytes ref hash around? } InternalStringTermsFacet.TermEntry[] list = new InternalStringTermsFacet.TermEntry[ordered.size()]; for (int i = ordered.size() - 1; i >= 0; i--) { list[i] = ((InternalStringTermsFacet.TermEntry) ordered.pop()); } return new InternalStringTermsFacet(facetName, comparatorType, size, Arrays.asList(list), missing, total); } else { BoundedTreeSet<InternalStringTermsFacet.TermEntry> ordered = new BoundedTreeSet<InternalStringTermsFacet.TermEntry>(comparatorType.comparator(), shardSize); BytesRefCountIterator iter = aggregator.getIter(); while (iter.next() != null) { ordered.add(new InternalStringTermsFacet.TermEntry(iter.makeSafe(), iter.count())); // maybe we can survive with a 0-copy here if we keep the // bytes ref hash around? } return new InternalStringTermsFacet(facetName, comparatorType, size, ordered, missing, total); } } } private HashCount getAssertHash() { HashCount count = null; assert (count = new AssertingHashCount()) != null; return count; } private static interface HashCount { public boolean add(BytesRef value, int hashCode, BytesValues values); public boolean addNoCount(BytesRef value, int hashCode, BytesValues values); public void release(); public int size(); public BytesRefCountIterator iter(); } private static final class BytesRefHashHashCount implements HashCount { private final BytesRefHash hash; private int[] counts = new int[10]; public BytesRefHashHashCount(BytesRefHash hash) { this.hash = hash; } @Override public boolean add(BytesRef value, int hashCode, BytesValues values) { int key = hash.add(value, hashCode); if (key < 0) { key = ((-key) - 1); } else if (key >= counts.length) { counts = ArrayUtil.grow(counts, key + 1); } return (counts[key]++) == 0; } public boolean addNoCount(BytesRef value, int hashCode, BytesValues values) { int key = hash.add(value, hashCode); final boolean added = key >= 0; if (key < 0) { key = ((-key) - 1); } else if (key >= counts.length) { counts = ArrayUtil.grow(counts, key + 1); } return added; } @Override public BytesRefCountIterator iter() { return new BytesRefCountIteratorImpl(); } public final class BytesRefCountIteratorImpl implements BytesRefCountIterator { final BytesRef spare = new BytesRef(); private final int size; private int current = 0; private int currentCount = -1; BytesRefCountIteratorImpl() { this.size = hash.size(); } public BytesRef next() { if (current < size) { currentCount = counts[current]; hash.get(current++, spare); return spare; } currentCount = -1; return null; } @Override public BytesRef makeSafe() { return BytesRef.deepCopyOf(spare); } public int count() { return currentCount; } @Override public boolean shared() { return true; } } @Override public int size() { return hash.size(); } @Override public void release() { hash.close(); } } private static final class AssertingHashCount implements HashCount { // simple // implemenation // for // assertions private final ObjectIntOpenHashMap<HashedBytesRef> valuesAndCount = new ObjectIntOpenHashMap<HashedBytesRef>(); private HashedBytesRef spare = new HashedBytesRef(); @Override public boolean add(BytesRef value, int hashCode, BytesValues values) { int adjustedValue = valuesAndCount.addTo(spare.reset(value, hashCode), 1); assert adjustedValue >= 1; if (adjustedValue == 1) { // only if we added the spare we create a // new instance spare.bytes = values.makeSafe(spare.bytes); spare = new HashedBytesRef(); return true; } return false; } @Override public int size() { return valuesAndCount.size(); } @Override public BytesRefCountIterator iter() { throw new UnsupportedOperationException(); } @Override public void release() { } @Override public boolean addNoCount(BytesRef value, int hashCode, BytesValues values) { if (!valuesAndCount.containsKey(spare.reset(value, hashCode))) { valuesAndCount.addTo(spare.reset(value, hashCode), 0); spare.bytes = values.makeSafe(spare.bytes); spare = new HashedBytesRef(); return true; } return false; } } }
apache-2.0
chris115379/Recipr
data/src/main/java/de/androidbytes/recipr/data/provider/category/CategoryColumns.java
1444
package de.androidbytes.recipr.data.provider.category; import android.net.Uri; import android.provider.BaseColumns; import de.androidbytes.recipr.data.provider.ReciprProvider; import de.androidbytes.recipr.data.provider.user.UserColumns; /** * A category is used to group various favoriteRecipes. */ public class CategoryColumns implements BaseColumns { public static final String TABLE_NAME = "category"; public static final Uri CONTENT_URI = Uri.parse(ReciprProvider.CONTENT_URI_BASE + "/" + TABLE_NAME); /** * Primary key. */ public static final String _ID = BaseColumns._ID; public static final String USER_ID = "category__user_id"; /** * Name of the CategoryEntity. */ public static final String NAME = "category__name"; public static final String DEFAULT_ORDER = TABLE_NAME + "." +_ID; // @formatter:off public static final String[] ALL_COLUMNS = new String[] { _ID, USER_ID, NAME }; // @formatter:on public static boolean hasColumns(String[] projection) { if (projection == null) return true; for (String c : projection) { if (c.equals(USER_ID) || c.contains("." + USER_ID)) return true; if (c.equals(NAME) || c.contains("." + NAME)) return true; } return false; } public static final String PREFIX_USER = TABLE_NAME + "__" + UserColumns.TABLE_NAME; }
apache-2.0
ctripcorp/x-pipe
redis/redis-console/src/main/java/com/ctrip/xpipe/redis/console/spring/CheckerContextConfig.java
9426
package com.ctrip.xpipe.redis.console.spring; import com.ctrip.xpipe.api.foundation.FoundationService; import com.ctrip.xpipe.redis.checker.*; import com.ctrip.xpipe.redis.checker.alert.AlertManager; import com.ctrip.xpipe.redis.checker.cluster.AllCheckerLeaderElector; import com.ctrip.xpipe.redis.checker.cluster.GroupCheckerLeaderElector; import com.ctrip.xpipe.redis.checker.config.CheckerConfig; import com.ctrip.xpipe.redis.checker.config.CheckerDbConfig; import com.ctrip.xpipe.redis.checker.config.impl.DefaultCheckerDbConfig; import com.ctrip.xpipe.redis.checker.healthcheck.actions.interaction.HealthStateService; import com.ctrip.xpipe.redis.checker.healthcheck.actions.ping.DefaultPingService; import com.ctrip.xpipe.redis.checker.healthcheck.actions.ping.PingService; import com.ctrip.xpipe.redis.checker.healthcheck.allleader.SentinelMonitorsCheckCrossDc; import com.ctrip.xpipe.redis.checker.healthcheck.allleader.SentinelShardBind; import com.ctrip.xpipe.redis.checker.impl.*; import com.ctrip.xpipe.redis.checker.spring.ConsoleServerMode; import com.ctrip.xpipe.redis.checker.spring.ConsoleServerModeCondition; import com.ctrip.xpipe.redis.console.config.ConsoleConfig; import com.ctrip.xpipe.redis.console.config.impl.DefaultConsoleConfig; import com.ctrip.xpipe.redis.console.dao.MigrationClusterDao; import com.ctrip.xpipe.redis.console.dao.MigrationEventDao; import com.ctrip.xpipe.redis.console.dao.MigrationShardDao; import com.ctrip.xpipe.redis.console.healthcheck.meta.DcIgnoredConfigChangeListener; import com.ctrip.xpipe.redis.console.migration.auto.DefaultBeaconManager; import com.ctrip.xpipe.redis.console.migration.auto.DefaultMonitorServiceManager; import com.ctrip.xpipe.redis.console.migration.auto.MonitorServiceManager; import com.ctrip.xpipe.redis.console.redis.DefaultSentinelManager; import com.ctrip.xpipe.redis.console.resources.CheckerAllMetaCache; import com.ctrip.xpipe.redis.console.resources.CheckerMetaCache; import com.ctrip.xpipe.redis.console.resources.CheckerPersistenceCache; import com.ctrip.xpipe.redis.console.service.DcClusterShardService; import com.ctrip.xpipe.redis.console.service.impl.AlertEventService; import com.ctrip.xpipe.redis.console.service.impl.DcClusterShardServiceImpl; import com.ctrip.xpipe.redis.console.service.meta.BeaconMetaService; import com.ctrip.xpipe.redis.console.service.meta.impl.BeaconMetaServiceImpl; import com.ctrip.xpipe.redis.console.util.DefaultMetaServerConsoleServiceManagerWrapper; import com.ctrip.xpipe.redis.core.meta.MetaCache; import com.ctrip.xpipe.spring.AbstractProfile; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.beans.factory.annotation.Value; import org.springframework.context.annotation.*; import java.util.concurrent.ExecutorService; import static com.ctrip.xpipe.spring.AbstractSpringConfigContext.GLOBAL_EXECUTOR; /** * @author lishanglin * date 2021/3/8 */ @Configuration @ComponentScan(excludeFilters = { @ComponentScan.Filter(type = FilterType.ASSIGNABLE_TYPE, value = {MigrationEventDao.class, MigrationClusterDao.class, MigrationShardDao.class}) }, basePackages = { "com.ctrip.xpipe.redis.console.dao", "com.ctrip.xpipe.redis.checker" }) @ConsoleServerMode(ConsoleServerModeCondition.SERVER_MODE.CHECKER) public class CheckerContextConfig { @Bean public DcClusterShardService dcClusterShardService() { return new DcClusterShardServiceImpl(); } @Bean public PersistenceCache persistenceCache(CheckerConfig checkerConfig, CheckerConsoleService checkerConsoleService) { return new CheckerPersistenceCache(checkerConfig, checkerConsoleService); } @Bean @Profile(AbstractProfile.PROFILE_NAME_PRODUCTION) public MetaCache metaCache(CheckerConfig checkerConfig, CheckerConsoleService checkerConsoleService) { return new CheckerMetaCache(checkerConfig, checkerConsoleService); } @Bean public CheckerAllMetaCache checkerAllMetaCache() { return new CheckerAllMetaCache(); } @Bean @Profile(AbstractProfile.PROFILE_NAME_TEST) public MetaCache testMetaCache() { return new TestMetaCache(); } @Bean public ProxyManager proxyManager(GroupCheckerLeaderElector clusterServer, CheckerConfig checkerConfig, CheckerConsoleService checkerConsoleService) { return new CheckerProxyManager(clusterServer, checkerConfig, checkerConsoleService); } @Bean public DefaultConsoleConfig consoleConfig() { return new DefaultConsoleConfig(); } @Bean public CheckerDbConfig checkerDbConfig(PersistenceCache persistenceCache) { return new DefaultCheckerDbConfig(persistenceCache); } @Bean public DcIgnoredConfigChangeListener dcIgnoredConfigChangeListener() { return new DcIgnoredConfigChangeListener(); } @Bean public MetaServerManager metaServerManager() { return new DefaultMetaServerConsoleServiceManagerWrapper(); } @Bean @Profile(AbstractProfile.PROFILE_NAME_PRODUCTION) public GroupCheckerLeaderElector checkerLeaderElector(FoundationService foundationService) { return new GroupCheckerLeaderElector(foundationService.getGroupId()); } @Bean public CheckerRedisDelayManager redisDelayManager() { return new CheckerRedisDelayManager(); } @Bean public CheckerRedisInfoManager redisInfoManager() { return new CheckerRedisInfoManager(); } @Bean public DefaultPingService pingService() { return new DefaultPingService(); } @Bean public ClusterHealthManager clusterHealthManager(@Qualifier(GLOBAL_EXECUTOR) ExecutorService executorService) { return new CheckerClusterHealthManager(executorService); } @Bean public MonitorServiceManager monitorServiceManager(ConsoleConfig config) { return new DefaultMonitorServiceManager(config); } @Bean public BeaconMetaService beaconMetaService(MetaCache metaCache) { return new BeaconMetaServiceImpl(metaCache); } @Bean public BeaconManager beaconManager(MonitorServiceManager monitorServiceManager, BeaconMetaService beaconMetaService) { return new DefaultBeaconManager(monitorServiceManager, beaconMetaService); } @Bean public CheckerCrossMasterDelayManager checkerCrossMasterDelayManager(FoundationService foundationService) { return new CheckerCrossMasterDelayManager(foundationService.getDataCenter()); } @Bean public RemoteCheckerManager remoteCheckerManager(CheckerConfig checkerConfig) { return new DefaultRemoteCheckerManager(checkerConfig); } @Bean public AlertEventService alertEventService() { return new AlertEventService(); } @Bean @Lazy public SentinelManager sentinelManager() { return new DefaultSentinelManager(); } @Bean @Profile(AbstractProfile.PROFILE_NAME_PRODUCTION) public HealthCheckReporter healthCheckReporter(CheckerConfig checkerConfig, CheckerConsoleService checkerConsoleService, GroupCheckerLeaderElector clusterServer, AllCheckerLeaderElector allCheckerLeaderElector, RedisDelayManager redisDelayManager, CrossMasterDelayManager crossMasterDelayManager, PingService pingService, ClusterHealthManager clusterHealthManager, HealthStateService healthStateService, @Value("${server.port}") int serverPort) { return new HealthCheckReporter(healthStateService, checkerConfig, checkerConsoleService, clusterServer, allCheckerLeaderElector, redisDelayManager, crossMasterDelayManager, pingService, clusterHealthManager, serverPort); } @Bean(name = "ALLCHECKER") @Profile(AbstractProfile.PROFILE_NAME_PRODUCTION) public AllCheckerLeaderElector allCheckerLeaderElector(FoundationService foundationService) { return new AllCheckerLeaderElector(foundationService.getDataCenter()); } @Bean public FoundationService foundationService() { return FoundationService.DEFAULT; } @Bean public SentinelMonitorsCheckCrossDc sentinelMonitorsCheckCrossDc(CheckerAllMetaCache metaCache, PersistenceCache persistenceCache, CheckerConfig config, FoundationService foundationService, SentinelManager manager, AlertManager alertManager ) { return new SentinelMonitorsCheckCrossDc(metaCache, persistenceCache, config, foundationService.getDataCenter(), manager, alertManager); } @Bean public SentinelShardBind sentinelShardBind(CheckerAllMetaCache metaCache, CheckerConfig checkerConfig, SentinelManager sentinelManager, @Qualifier(GLOBAL_EXECUTOR) ExecutorService executor, CheckerConsoleService checkerConsoleService) { return new SentinelShardBind(metaCache, checkerConfig, sentinelManager, executor, checkerConsoleService); } }
apache-2.0
youdonghai/intellij-community
platform/lang-impl/src/com/intellij/codeInsight/navigation/BackgroundUpdaterTask.java
5089
/* * Copyright 2000-2016 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.codeInsight.navigation; import com.intellij.openapi.application.ApplicationManager; import com.intellij.openapi.application.ModalityState; import com.intellij.openapi.progress.PerformInBackgroundOption; import com.intellij.openapi.progress.ProgressIndicator; import com.intellij.openapi.progress.Task; import com.intellij.openapi.project.Project; import com.intellij.openapi.util.Ref; import com.intellij.psi.PsiElement; import com.intellij.ui.popup.AbstractPopup; import com.intellij.usageView.UsageInfo; import com.intellij.usages.UsageInfo2UsageAdapter; import com.intellij.usages.UsageView; import com.intellij.usages.impl.UsageViewImpl; import com.intellij.util.Alarm; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import javax.swing.*; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.List; /** * User: anna */ public abstract class BackgroundUpdaterTask<T> extends Task.Backgroundable { protected AbstractPopup myPopup; protected T myComponent; private Ref<UsageView> myUsageView; private final List<PsiElement> myData = new ArrayList<>(); private final Alarm myAlarm = new Alarm(Alarm.ThreadToUse.SWING_THREAD); private final Object lock = new Object(); private volatile boolean myCanceled; private volatile boolean myFinished; private volatile ProgressIndicator myIndicator; public BackgroundUpdaterTask(Project project, String title, boolean canBeCancelled) { super(project, title, canBeCancelled); } public BackgroundUpdaterTask(Project project, String title) { super(project, title); } public BackgroundUpdaterTask(Project project, String title, boolean canBeCancelled, PerformInBackgroundOption backgroundOption) { super(project, title, canBeCancelled, backgroundOption); } public void init(@NotNull AbstractPopup popup, @NotNull T component, @NotNull Ref<UsageView> usageView) { myPopup = popup; myComponent = component; myUsageView = usageView; } public abstract String getCaption(int size); protected abstract void replaceModel(@NotNull List<PsiElement> data); protected abstract void paintBusy(boolean paintBusy); public boolean setCanceled() { boolean canceled = myCanceled; myCanceled = true; return canceled; } public boolean isCanceled() { return myCanceled; } public boolean updateComponent(final PsiElement element, @Nullable final Comparator comparator) { final UsageView view = myUsageView.get(); if (view != null && !((UsageViewImpl)view).isDisposed()) { ApplicationManager.getApplication().runReadAction(() -> view.appendUsage(new UsageInfo2UsageAdapter(new UsageInfo(element)))); return true; } if (myCanceled) return false; final JComponent content = myPopup.getContent(); if (content == null || myPopup.isDisposed()) return false; synchronized (lock) { if (myData.contains(element)) return true; myData.add(element); } myAlarm.addRequest(() -> { myAlarm.cancelAllRequests(); if (myCanceled) return; if (myPopup.isDisposed()) return; ArrayList<PsiElement> data = new ArrayList<>(); synchronized (lock) { if (comparator != null) { Collections.sort(myData, comparator); } data.addAll(myData); } replaceModel(data); myPopup.setCaption(getCaption(getCurrentSize())); myPopup.pack(true, true); }, 200, ModalityState.stateForComponent(content)); return true; } public int getCurrentSize() { synchronized (lock) { return myData.size(); } } @Override public void run(@NotNull ProgressIndicator indicator) { paintBusy(true); myIndicator = indicator; } @Override public void onSuccess() { myPopup.setCaption(getCaption(getCurrentSize())); paintBusy(false); } @Override public void onFinished() { myFinished = true; } @Nullable protected PsiElement getTheOnlyOneElement() { synchronized (lock) { if (myData.size() == 1) { return myData.get(0); } } return null; } public boolean isFinished() { return myFinished; } public boolean cancelTask() { ProgressIndicator indicator = myIndicator; if (indicator != null) { indicator.cancel(); } return setCanceled(); } }
apache-2.0
bendraaisma/gnuob-soap
src/main/java/br/com/netbrasoft/gnuob/generic/AbstractType.java
3491
/* * Copyright 2016 Netbrasoft * * 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 br.com.netbrasoft.gnuob.generic; import static br.com.netbrasoft.gnuob.generic.NetbrasoftSoapConstants.CREATION_COLUMN_NAME; import static br.com.netbrasoft.gnuob.generic.NetbrasoftSoapConstants.ID_COLUMN_NAME; import static br.com.netbrasoft.gnuob.generic.NetbrasoftSoapConstants.MODIFICATION_COLUMN_NAME; import static br.com.netbrasoft.gnuob.generic.NetbrasoftSoapConstants.VERSION_COLUMN_NAME; import static br.com.netbrasoft.gnuob.generic.NetbrasoftSoapConstants.ZERO; import static java.lang.System.currentTimeMillis; import static javax.persistence.GenerationType.IDENTITY; import static org.apache.commons.lang3.builder.ToStringStyle.SHORT_PREFIX_STYLE; import java.io.Serializable; import java.sql.Timestamp; import javax.persistence.Cacheable; import javax.persistence.Column; import javax.persistence.GeneratedValue; import javax.persistence.Id; import javax.persistence.MappedSuperclass; import javax.persistence.PrePersist; import javax.persistence.PreUpdate; import javax.persistence.Transient; import javax.persistence.Version; import javax.xml.bind.annotation.XmlAttribute; import javax.xml.bind.annotation.XmlTransient; import static org.apache.commons.lang3.builder.ToStringBuilder.reflectionToString; @Cacheable(value = false) @MappedSuperclass public abstract class AbstractType implements Serializable, ICallback { private static final long serialVersionUID = 7895247154381678321L; private Timestamp creation; private long id; private Timestamp modification; private int version; @Transient public abstract boolean isDetached(); @PrePersist protected void prePersistType() { creation = new Timestamp(currentTimeMillis()); modification = new Timestamp(currentTimeMillis()); prePersist(); } @PreUpdate protected void preUpdateType() { modification = new Timestamp(currentTimeMillis()); preUpdate(); } @XmlTransient @Column(name = CREATION_COLUMN_NAME) public Timestamp getCreation() { return creation; } @XmlAttribute @Id @GeneratedValue(strategy = IDENTITY) @Column(name = ID_COLUMN_NAME) public long getId() { return id; } @XmlTransient @Column(name = MODIFICATION_COLUMN_NAME) public Timestamp getModification() { return modification; } @XmlAttribute @Version @Column(name = VERSION_COLUMN_NAME) public int getVersion() { return version; } @Transient public boolean isAbstractTypeDetached() { return id > ZERO; } public void setCreation(final Timestamp creation) { this.creation = creation; } public void setId(final long id) { this.id = id; } public void setModification(final Timestamp modification) { this.modification = modification; } public void setVersion(final int version) { this.version = version; } @Override public String toString() { return reflectionToString(this, SHORT_PREFIX_STYLE); } }
apache-2.0
vimaier/conqat
org.conqat.engine.graph/src/org/conqat/engine/graph/concentrate/GraphConcentrator.java
7454
/*-------------------------------------------------------------------------+ | | | Copyright 2005-2011 The ConQAT 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 org.conqat.engine.graph.concentrate; import java.util.ArrayList; import org.conqat.lib.commons.assessment.Assessment; import org.conqat.lib.commons.collections.TwoDimHashMap; import org.conqat.engine.commons.ConQATParamDoc; import org.conqat.engine.commons.ConQATPipelineProcessorBase; import org.conqat.engine.commons.node.NodeUtils; import org.conqat.engine.core.core.AConQATAttribute; import org.conqat.engine.core.core.AConQATParameter; import org.conqat.engine.core.core.AConQATProcessor; import org.conqat.engine.core.core.ConQATException; import org.conqat.engine.graph.nodes.ConQATGraph; import org.conqat.engine.graph.nodes.ConQATGraphInnerNode; import org.conqat.engine.graph.nodes.ConQATVertex; import org.conqat.engine.graph.nodes.DeepCloneCopyAction; import edu.uci.ics.jung.graph.impl.DirectedSparseEdge; /** * This processor concentrates a graph, i.e. it collapses leaves and infers * edges for the collapsed graph. * * @author Benjamin Hummel * @author $Author: deissenb $ * @version $Rev: 35147 $ * @ConQAT.Rating GREEN Hash: D9A952F89E9B24594A88691F425D54C1 */ @AConQATProcessor(description = "This processor concentrates a ConQATGraph by folding all vertices " + "of an inner node into a single vertex and combining edges accordingly. Optionally an " + "assessment which is present at the edges can be combined for the new edge.") public class GraphConcentrator extends ConQATPipelineProcessorBase<ConQATGraph> { /** Extension used to prolong the id. */ private static final String EXT = "_"; /** The key to read the assessment from. */ private String assessmentKey = null; /** Storage for the new edges (with assessment). */ private final TwoDimHashMap<String, String, Assessment> newEdgeAssessments = new TwoDimHashMap<String, String, Assessment>(); /** Flag for loop filtering. */ private boolean loopsFilter = true; /** Set the assessment key. */ @AConQATParameter(name = "assessment", maxOccurrences = 1, description = "" + "The key to read the assessment from. If not key is given, no assessment is created for the edges.") public void setAssessmentKey( @AConQATAttribute(name = ConQATParamDoc.READKEY_KEY_NAME, description = ConQATParamDoc.READKEY_KEY_DESC) String key) { assessmentKey = key; } /** Set the assessment key. */ @AConQATParameter(name = "loops", maxOccurrences = 1, description = "" + "Filter self-loops [true]") public void setLoopsFilter( @AConQATAttribute(name = "filter", description = "Enable/disable loop filter") boolean loopsFilter) { this.loopsFilter = loopsFilter; } /** {@inheritDoc} */ @Override protected void processInput(ConQATGraph graph) throws ConQATException { calculateNewEdges(graph); discardEmptyInnerNodes(graph); createRepresentativeNodes(graph, graph); insertNewEdges(graph); getLogger().info( "Concentrated graph has " + graph.getVertices().size() + " vertices and " + graph.getEdges().size() + " edges."); } /** Calculates the new edges for the graph. */ private void calculateNewEdges(ConQATGraph graph) { for (DirectedSparseEdge edge : graph.getEdges()) { ConQATVertex source = (ConQATVertex) edge.getSource(); ConQATVertex dest = (ConQATVertex) edge.getDest(); insertEdge(source.getParent().getId(), dest.getParent().getId(), edge); } } /** * Inserts an edge between the given nodes (if it does not already exist) * and handles merging the assessment (if required). */ private void insertEdge(String sourceID, String targetID, DirectedSparseEdge originalEdge) { if (loopsFilter && sourceID.equals(targetID)) { return; } // deal with assessment if (assessmentKey == null) { newEdgeAssessments.putValue(sourceID, targetID, null); } else { Assessment origAssessment = (Assessment) originalEdge .getUserDatum(assessmentKey); if (origAssessment == null) { origAssessment = new Assessment(); } Assessment newAssessment = newEdgeAssessments.getValue(sourceID, targetID); if (newAssessment == null) { newEdgeAssessments.putValue(sourceID, targetID, origAssessment); } else { newAssessment.add(origAssessment); } } } /** Removes all empty inner nodes. */ private void discardEmptyInnerNodes(ConQATGraphInnerNode node) { if (!node.hasChildren()) { node.remove(); } else { for (ConQATGraphInnerNode child : new ArrayList<ConQATGraphInnerNode>( node.getInnerNodes())) { discardEmptyInnerNodes(child); } } } /** Creates the representative nodes for all graphs having vertices. */ private void createRepresentativeNodes(ConQATGraphInnerNode node, ConQATGraph graph) throws ConQATException { // erase child vertices boolean createRep = !node.getChildVertices().isEmpty(); for (ConQATVertex vertex : new ArrayList<ConQATVertex>(node .getChildVertices())) { vertex.remove(); } // handle children for (ConQATGraphInnerNode child : new ArrayList<ConQATGraphInnerNode>( node.getInnerNodes())) { createRepresentativeNodes(child, graph); } // create representative if needed if (createRep) { ConQATGraphInnerNode parent = node.getParent(); ConQATVertex vertex = null; if (node.hasChildren() || parent == null) { vertex = graph.createVertex(extendedName(node.getId()), extendedName(node.getName()), node); } else { node.remove(); vertex = graph.createVertex(extendedName(node.getId()), node .getName(), parent); } NodeUtils.copyValues(NodeUtils.getDisplayList(graph), node, vertex); } } /** Inserts all new edges into the graph. */ private void insertNewEdges(ConQATGraph graph) { for (String source : newEdgeAssessments.getFirstKeys()) { for (String target : newEdgeAssessments.getSecondKeys(source)) { DirectedSparseEdge edge = graph.addEdge(graph .getVertexByID(extendedName(source)), graph .getVertexByID(extendedName(target))); if (assessmentKey != null) { edge.addUserDatum(assessmentKey, newEdgeAssessments .getValue(source, target), DeepCloneCopyAction .getInstance()); } } } } /** Create extended name for a vertex name */ private static String extendedName(String name) { return name + EXT; } }
apache-2.0
lesaint/experimenting-annotation-processing
experimenting-rounds/massive-count-of-annotated-classes/src/main/java/fr/javatronic/blog/massive/annotation1/Class_667.java
145
package fr.javatronic.blog.massive.annotation1; import fr.javatronic.blog.processor.Annotation_001; @Annotation_001 public class Class_667 { }
apache-2.0
LorenzReinhart/ONOSnew
incubator/net/src/test/java/org/onosproject/incubator/net/virtual/impl/VirtualNetworkTopologyManagerTest.java
28674
/* * Copyright 2016-present Open Networking Laboratory * * 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.onosproject.incubator.net.virtual.impl; import org.junit.After; import org.junit.Before; import org.junit.Test; import org.onlab.junit.TestUtils; import org.onlab.osgi.TestServiceDirectory; import org.onlab.rest.BaseResource; import org.onosproject.common.event.impl.TestEventDispatcher; import org.onosproject.core.ApplicationId; import org.onosproject.core.CoreService; import org.onosproject.core.CoreServiceAdapter; import org.onosproject.core.DefaultApplicationId; import org.onosproject.core.IdGenerator; import org.onosproject.incubator.net.virtual.NetworkId; import org.onosproject.incubator.net.virtual.TenantId; import org.onosproject.incubator.net.virtual.VirtualDevice; import org.onosproject.incubator.net.virtual.VirtualLink; import org.onosproject.incubator.net.virtual.VirtualNetwork; import org.onosproject.incubator.store.virtual.impl.DistributedVirtualNetworkStore; import org.onosproject.net.ConnectPoint; import org.onosproject.net.DeviceId; import org.onosproject.net.DisjointPath; import org.onosproject.net.Link; import org.onosproject.net.NetTestTools; import org.onosproject.net.Path; import org.onosproject.net.PortNumber; import org.onosproject.net.TestDeviceParams; import org.onosproject.net.topology.LinkWeigher; import org.onosproject.net.topology.LinkWeight; import org.onosproject.net.topology.Topology; import org.onosproject.net.topology.TopologyCluster; import org.onosproject.net.topology.TopologyService; import org.onosproject.store.service.TestStorageService; import java.util.Map; import java.util.Optional; import java.util.Set; import java.util.concurrent.atomic.AtomicLong; import static junit.framework.TestCase.assertTrue; import static org.junit.Assert.*; /** * Junit tests for VirtualNetworkTopologyService. */ public class VirtualNetworkTopologyManagerTest extends TestDeviceParams { private final String tenantIdValue1 = "TENANT_ID1"; private VirtualNetworkManager manager; private DistributedVirtualNetworkStore virtualNetworkManagerStore; private CoreService coreService; private TestServiceDirectory testDirectory; @Before public void setUp() throws Exception { virtualNetworkManagerStore = new DistributedVirtualNetworkStore(); coreService = new VirtualNetworkTopologyManagerTest.TestCoreService(); TestUtils.setField(virtualNetworkManagerStore, "coreService", coreService); TestUtils.setField(virtualNetworkManagerStore, "storageService", new TestStorageService()); virtualNetworkManagerStore.activate(); BaseResource.setServiceDirectory(testDirectory); manager = new VirtualNetworkManager(); manager.store = virtualNetworkManagerStore; manager.coreService = coreService; NetTestTools.injectEventDispatcher(manager, new TestEventDispatcher()); testDirectory = new TestServiceDirectory(); TestUtils.setField(manager, "serviceDirectory", testDirectory); manager.activate(); } @After public void tearDown() { virtualNetworkManagerStore.deactivate(); manager.deactivate(); NetTestTools.injectEventDispatcher(manager, null); } /** * Method to create the virtual network for further testing. * * @return virtual network */ private VirtualNetwork setupVirtualNetworkTopology() { manager.registerTenantId(TenantId.tenantId(tenantIdValue1)); VirtualNetwork virtualNetwork = manager.createVirtualNetwork(TenantId.tenantId(tenantIdValue1)); VirtualDevice virtualDevice1 = manager.createVirtualDevice(virtualNetwork.id(), DID1); VirtualDevice virtualDevice2 = manager.createVirtualDevice(virtualNetwork.id(), DID2); VirtualDevice virtualDevice3 = manager.createVirtualDevice(virtualNetwork.id(), DID3); VirtualDevice virtualDevice4 = manager.createVirtualDevice(virtualNetwork.id(), DID4); ConnectPoint cp1 = new ConnectPoint(virtualDevice1.id(), PortNumber.portNumber(1)); manager.createVirtualPort(virtualNetwork.id(), cp1.deviceId(), cp1.port(), cp1); ConnectPoint cp2 = new ConnectPoint(virtualDevice1.id(), PortNumber.portNumber(2)); manager.createVirtualPort(virtualNetwork.id(), cp2.deviceId(), cp2.port(), cp2); ConnectPoint cp3 = new ConnectPoint(virtualDevice2.id(), PortNumber.portNumber(3)); manager.createVirtualPort(virtualNetwork.id(), cp3.deviceId(), cp3.port(), cp3); ConnectPoint cp4 = new ConnectPoint(virtualDevice2.id(), PortNumber.portNumber(4)); manager.createVirtualPort(virtualNetwork.id(), cp4.deviceId(), cp4.port(), cp4); ConnectPoint cp5 = new ConnectPoint(virtualDevice3.id(), PortNumber.portNumber(5)); manager.createVirtualPort(virtualNetwork.id(), cp5.deviceId(), cp5.port(), cp5); ConnectPoint cp6 = new ConnectPoint(virtualDevice3.id(), PortNumber.portNumber(6)); manager.createVirtualPort(virtualNetwork.id(), cp6.deviceId(), cp6.port(), cp6); VirtualLink link1 = manager.createVirtualLink(virtualNetwork.id(), cp1, cp3); virtualNetworkManagerStore.updateLink(link1, link1.tunnelId(), Link.State.ACTIVE); VirtualLink link2 = manager.createVirtualLink(virtualNetwork.id(), cp3, cp1); virtualNetworkManagerStore.updateLink(link2, link2.tunnelId(), Link.State.ACTIVE); VirtualLink link3 = manager.createVirtualLink(virtualNetwork.id(), cp4, cp5); virtualNetworkManagerStore.updateLink(link3, link3.tunnelId(), Link.State.ACTIVE); VirtualLink link4 = manager.createVirtualLink(virtualNetwork.id(), cp5, cp4); virtualNetworkManagerStore.updateLink(link4, link4.tunnelId(), Link.State.ACTIVE); VirtualLink link5 = manager.createVirtualLink(virtualNetwork.id(), cp2, cp6); virtualNetworkManagerStore.updateLink(link5, link5.tunnelId(), Link.State.ACTIVE); VirtualLink link6 = manager.createVirtualLink(virtualNetwork.id(), cp6, cp2); virtualNetworkManagerStore.updateLink(link6, link6.tunnelId(), Link.State.ACTIVE); return virtualNetwork; } /** * Tests the currentTopology() method. */ @Test public void testCurrentTopology() { VirtualNetwork virtualNetwork = setupVirtualNetworkTopology(); TopologyService topologyService = manager.get(virtualNetwork.id(), TopologyService.class); Topology topology = topologyService.currentTopology(); assertNotNull("The topology should not be null.", topology); } /** * Test isLatest() method using a null topology. */ @Test(expected = NullPointerException.class) public void testIsLatestByNullTopology() { manager.registerTenantId(TenantId.tenantId(tenantIdValue1)); VirtualNetwork virtualNetwork = manager.createVirtualNetwork(TenantId.tenantId(tenantIdValue1)); TopologyService topologyService = manager.get(virtualNetwork.id(), TopologyService.class); // test the isLatest() method with a null topology. topologyService.isLatest(null); } /** * Test isLatest() method. */ @Test public void testIsLatest() { manager.registerTenantId(TenantId.tenantId(tenantIdValue1)); VirtualNetwork virtualNetwork = manager.createVirtualNetwork(TenantId.tenantId(tenantIdValue1)); TopologyService topologyService = manager.get(virtualNetwork.id(), TopologyService.class); Topology topology = topologyService.currentTopology(); // test the isLatest() method. assertTrue("This should be latest topology", topologyService.isLatest(topology)); VirtualDevice srcVirtualDevice = manager.createVirtualDevice(virtualNetwork.id(), DID1); VirtualDevice dstVirtualDevice = manager.createVirtualDevice(virtualNetwork.id(), DID2); // test the isLatest() method where a new device has been added to the current topology. assertFalse("This should not be latest topology", topologyService.isLatest(topology)); topology = topologyService.currentTopology(); ConnectPoint src = new ConnectPoint(srcVirtualDevice.id(), PortNumber.portNumber(1)); manager.createVirtualPort(virtualNetwork.id(), src.deviceId(), src.port(), new ConnectPoint(srcVirtualDevice.id(), src.port())); ConnectPoint dst = new ConnectPoint(dstVirtualDevice.id(), PortNumber.portNumber(2)); manager.createVirtualPort(virtualNetwork.id(), dst.deviceId(), dst.port(), new ConnectPoint(dstVirtualDevice.id(), dst.port())); VirtualLink link1 = manager.createVirtualLink(virtualNetwork.id(), src, dst); // test the isLatest() method where a new link has been added to the current topology. assertFalse("This should not be latest topology", topologyService.isLatest(topology)); } /** * Test getGraph() method. */ @Test public void testGetGraph() { manager.registerTenantId(TenantId.tenantId(tenantIdValue1)); VirtualNetwork virtualNetwork = manager.createVirtualNetwork(TenantId.tenantId(tenantIdValue1)); TopologyService topologyService = manager.get(virtualNetwork.id(), TopologyService.class); Topology topology = topologyService.currentTopology(); // test the getGraph() method. assertNotNull("The graph should not be null.", topologyService.getGraph(topology)); } /** * Test getClusters() method. */ @Test public void testGetClusters() { VirtualNetwork virtualNetwork = setupVirtualNetworkTopology(); TopologyService topologyService = manager.get(virtualNetwork.id(), TopologyService.class); Topology topology = topologyService.currentTopology(); // test the getClusters() method. assertNotNull("The clusters should not be null.", topologyService.getClusters(topology)); assertEquals("The clusters size did not match.", 2, topologyService.getClusters(topology).size()); } /** * Test getCluster() method using a null cluster identifier. */ @Test(expected = NullPointerException.class) public void testGetClusterUsingNullClusterId() { VirtualNetwork virtualNetwork = setupVirtualNetworkTopology(); TopologyService topologyService = manager.get(virtualNetwork.id(), TopologyService.class); Topology topology = topologyService.currentTopology(); Set<TopologyCluster> clusters = topologyService.getClusters(topology); TopologyCluster cluster = clusters.stream().findFirst().get(); // test the getCluster() method with a null cluster identifier TopologyCluster cluster1 = topologyService.getCluster(topology, null); } /** * Test getCluster() method. */ @Test public void testGetCluster() { VirtualNetwork virtualNetwork = setupVirtualNetworkTopology(); TopologyService topologyService = manager.get(virtualNetwork.id(), TopologyService.class); Topology topology = topologyService.currentTopology(); Set<TopologyCluster> clusters = topologyService.getClusters(topology); assertNotNull("The clusters should not be null.", clusters); assertEquals("The clusters size did not match.", 2, clusters.size()); // test the getCluster() method. TopologyCluster cluster = clusters.stream().findFirst().get(); assertNotNull("The cluster should not be null.", cluster); TopologyCluster cluster1 = topologyService.getCluster(topology, cluster.id()); assertNotNull("The cluster should not be null.", cluster1); assertEquals("The cluster ID did not match.", cluster.id(), cluster1.id()); } /** * Test getClusterDevices() methods with a null cluster. */ @Test(expected = NullPointerException.class) public void testGetClusterDevicesUsingNullCluster() { VirtualNetwork virtualNetwork = setupVirtualNetworkTopology(); TopologyService topologyService = manager.get(virtualNetwork.id(), TopologyService.class); Topology topology = topologyService.currentTopology(); Set<TopologyCluster> clusters = topologyService.getClusters(topology); // test the getClusterDevices() method using a null cluster. Object[] objects = clusters.stream().toArray(); assertNotNull("The cluster should not be null.", objects); Set<DeviceId> clusterDevices = topologyService.getClusterDevices(topology, null); } /** * Test getClusterLinks() methods with a null cluster. */ @Test(expected = NullPointerException.class) public void testGetClusterLinksUsingNullCluster() { VirtualNetwork virtualNetwork = setupVirtualNetworkTopology(); TopologyService topologyService = manager.get(virtualNetwork.id(), TopologyService.class); Topology topology = topologyService.currentTopology(); Set<TopologyCluster> clusters = topologyService.getClusters(topology); // test the getClusterLinks() method using a null cluster. Object[] objects = clusters.stream().toArray(); assertNotNull("The cluster should not be null.", objects); Set<Link> clusterLinks = topologyService.getClusterLinks(topology, null); } /** * Test getClusterDevices() and getClusterLinks() methods. */ @Test public void testGetClusterDevicesLinks() { VirtualNetwork virtualNetwork = setupVirtualNetworkTopology(); TopologyService topologyService = manager.get(virtualNetwork.id(), TopologyService.class); Topology topology = topologyService.currentTopology(); Set<TopologyCluster> clusters = topologyService.getClusters(topology); assertNotNull("The clusters should not be null.", clusters); assertEquals("The clusters size did not match.", 2, clusters.size()); // test the getClusterDevices() method. Object[] objects = clusters.stream().toArray(); assertNotNull("The cluster should not be null.", objects); Set<DeviceId> clusterDevices = topologyService.getClusterDevices(topology, (TopologyCluster) objects[0]); assertNotNull("The devices should not be null.", clusterDevices); assertEquals("The devices size did not match.", 3, clusterDevices.size()); Set<DeviceId> clusterDevices1 = topologyService.getClusterDevices(topology, (TopologyCluster) objects[1]); assertNotNull("The devices should not be null.", clusterDevices1); assertEquals("The devices size did not match.", 1, clusterDevices1.size()); // test the getClusterLinks() method. Set<Link> clusterLinks = topologyService.getClusterLinks(topology, (TopologyCluster) objects[0]); assertNotNull("The links should not be null.", clusterLinks); assertEquals("The links size did not match.", 6, clusterLinks.size()); Set<Link> clusterLinks1 = topologyService.getClusterLinks(topology, (TopologyCluster) objects[1]); assertNotNull("The links should not be null.", clusterLinks1); assertEquals("The links size did not match.", 0, clusterLinks1.size()); } /** * Test getPaths() method using a null src device identifier. */ @Test(expected = NullPointerException.class) public void testGetPathsUsingNullSrcDeviceId() { VirtualNetwork virtualNetwork = setupVirtualNetworkTopology(); TopologyService topologyService = manager.get(virtualNetwork.id(), TopologyService.class); Topology topology = topologyService.currentTopology(); VirtualDevice srcVirtualDevice = getVirtualDevice(virtualNetwork.id(), DID1); VirtualDevice dstVirtualDevice = getVirtualDevice(virtualNetwork.id(), DID2); // test the getPaths() method using a null src device identifier. Set<Path> paths = topologyService.getPaths(topology, null, dstVirtualDevice.id()); } /** * Test getPaths() method using a null dst device identifier. */ @Test(expected = NullPointerException.class) public void testGetPathsUsingNullDstDeviceId() { VirtualNetwork virtualNetwork = setupVirtualNetworkTopology(); TopologyService topologyService = manager.get(virtualNetwork.id(), TopologyService.class); Topology topology = topologyService.currentTopology(); VirtualDevice srcVirtualDevice = getVirtualDevice(virtualNetwork.id(), DID1); VirtualDevice dstVirtualDevice = getVirtualDevice(virtualNetwork.id(), DID2); // test the getPaths() method using a null dst device identifier. Set<Path> paths = topologyService.getPaths(topology, srcVirtualDevice.id(), null); } /** * Test getPaths() method using a null weight. */ @Test(expected = NullPointerException.class) public void testGetPathsUsingNullWeight() { VirtualNetwork virtualNetwork = setupVirtualNetworkTopology(); TopologyService topologyService = manager.get(virtualNetwork.id(), TopologyService.class); Topology topology = topologyService.currentTopology(); VirtualDevice srcVirtualDevice = getVirtualDevice(virtualNetwork.id(), DID1); VirtualDevice dstVirtualDevice = getVirtualDevice(virtualNetwork.id(), DID2); // test the getPaths() method using a null weight. Set<Path> paths = topologyService.getPaths(topology, srcVirtualDevice.id(), dstVirtualDevice.id(), (LinkWeigher) null); } /** * Test getPaths() and getPaths() by weight methods. */ @Test public void testGetPaths() { VirtualNetwork virtualNetwork = setupVirtualNetworkTopology(); TopologyService topologyService = manager.get(virtualNetwork.id(), TopologyService.class); Topology topology = topologyService.currentTopology(); VirtualDevice srcVirtualDevice = getVirtualDevice(virtualNetwork.id(), DID1); VirtualDevice dstVirtualDevice = getVirtualDevice(virtualNetwork.id(), DID2); // test the getPaths() method. Set<Path> paths = topologyService.getPaths(topology, srcVirtualDevice.id(), dstVirtualDevice.id()); assertNotNull("The paths should not be null.", paths); assertEquals("The paths size did not match.", 1, paths.size()); // test the getPaths() by weight method. LinkWeight weight = edge -> 1.0; Set<Path> paths1 = topologyService.getPaths(topology, srcVirtualDevice.id(), dstVirtualDevice.id(), weight); assertNotNull("The paths should not be null.", paths1); assertEquals("The paths size did not match.", 1, paths1.size()); Path path = paths1.iterator().next(); assertEquals("wrong path length", 1, path.links().size()); assertEquals("wrong path cost", 1.0, path.cost(), 0.01); } /** * Test getDisjointPaths() methods using a null src device identifier. */ @Test(expected = NullPointerException.class) public void testGetDisjointPathsUsingNullSrcDeviceId() { VirtualNetwork virtualNetwork = setupVirtualNetworkTopology(); TopologyService topologyService = manager.get(virtualNetwork.id(), TopologyService.class); Topology topology = topologyService.currentTopology(); VirtualDevice srcVirtualDevice = getVirtualDevice(virtualNetwork.id(), DID1); VirtualDevice dstVirtualDevice = getVirtualDevice(virtualNetwork.id(), DID2); // test the getDisjointPaths() method using a null src device identifier. Set<DisjointPath> paths = topologyService.getDisjointPaths(topology, null, dstVirtualDevice.id()); } /** * Test getDisjointPaths() methods using a null dst device identifier. */ @Test(expected = NullPointerException.class) public void testGetDisjointPathsUsingNullDstDeviceId() { VirtualNetwork virtualNetwork = setupVirtualNetworkTopology(); TopologyService topologyService = manager.get(virtualNetwork.id(), TopologyService.class); Topology topology = topologyService.currentTopology(); VirtualDevice srcVirtualDevice = getVirtualDevice(virtualNetwork.id(), DID1); VirtualDevice dstVirtualDevice = getVirtualDevice(virtualNetwork.id(), DID2); // test the getDisjointPaths() method using a null dst device identifier. Set<DisjointPath> paths = topologyService.getDisjointPaths(topology, srcVirtualDevice.id(), null); } /** * Test getDisjointPaths() methods using a null weight. */ @Test(expected = NullPointerException.class) public void testGetDisjointPathsUsingNullWeight() { VirtualNetwork virtualNetwork = setupVirtualNetworkTopology(); TopologyService topologyService = manager.get(virtualNetwork.id(), TopologyService.class); Topology topology = topologyService.currentTopology(); VirtualDevice srcVirtualDevice = getVirtualDevice(virtualNetwork.id(), DID1); VirtualDevice dstVirtualDevice = getVirtualDevice(virtualNetwork.id(), DID2); // test the getDisjointPaths() method using a null weight. Set<DisjointPath> paths = topologyService.getDisjointPaths(topology, srcVirtualDevice.id(), dstVirtualDevice.id(), (LinkWeight) null); } /** * Test getDisjointPaths() methods using a null risk profile. */ @Test(expected = NullPointerException.class) public void testGetDisjointPathsUsingNullRiskProfile() { VirtualNetwork virtualNetwork = setupVirtualNetworkTopology(); TopologyService topologyService = manager.get(virtualNetwork.id(), TopologyService.class); Topology topology = topologyService.currentTopology(); VirtualDevice srcVirtualDevice = getVirtualDevice(virtualNetwork.id(), DID1); VirtualDevice dstVirtualDevice = getVirtualDevice(virtualNetwork.id(), DID2); // test the getDisjointPaths() method using a null risk profile. Set<DisjointPath> paths = topologyService.getDisjointPaths(topology, srcVirtualDevice.id(), dstVirtualDevice.id(), (Map<Link, Object>) null); } /** * Test getDisjointPaths() methods. */ @Test public void testGetDisjointPaths() { VirtualNetwork virtualNetwork = setupVirtualNetworkTopology(); TopologyService topologyService = manager.get(virtualNetwork.id(), TopologyService.class); Topology topology = topologyService.currentTopology(); VirtualDevice srcVirtualDevice = getVirtualDevice(virtualNetwork.id(), DID1); VirtualDevice dstVirtualDevice = getVirtualDevice(virtualNetwork.id(), DID2); // test the getDisjointPaths() method. Set<DisjointPath> paths = topologyService.getDisjointPaths(topology, srcVirtualDevice.id(), dstVirtualDevice.id()); assertNotNull("The paths should not be null.", paths); assertEquals("The paths size did not match.", 1, paths.size()); // test the getDisjointPaths() method using a weight. LinkWeight weight = edge -> 1.0; Set<DisjointPath> paths1 = topologyService.getDisjointPaths(topology, srcVirtualDevice.id(), dstVirtualDevice.id(), weight); assertNotNull("The paths should not be null.", paths1); assertEquals("The paths size did not match.", 1, paths1.size()); } /** * Test isInfrastructure() method using a null connect point. */ @Test(expected = NullPointerException.class) public void testIsInfrastructureUsingNullConnectPoint() { VirtualNetwork virtualNetwork = setupVirtualNetworkTopology(); TopologyService topologyService = manager.get(virtualNetwork.id(), TopologyService.class); Topology topology = topologyService.currentTopology(); // test the isInfrastructure() method using a null connect point. Boolean isInfrastructure = topologyService.isInfrastructure(topology, null); } /** * Test isInfrastructure() method. */ @Test public void testIsInfrastructure() { VirtualNetwork virtualNetwork = setupVirtualNetworkTopology(); TopologyService topologyService = manager.get(virtualNetwork.id(), TopologyService.class); Topology topology = topologyService.currentTopology(); VirtualDevice srcVirtualDevice = getVirtualDevice(virtualNetwork.id(), DID1); VirtualDevice dstVirtualDevice = getVirtualDevice(virtualNetwork.id(), DID4); ConnectPoint cp1 = new ConnectPoint(srcVirtualDevice.id(), PortNumber.portNumber(1)); ConnectPoint cp2 = new ConnectPoint(dstVirtualDevice.id(), PortNumber.portNumber(2)); // test the isInfrastructure() method. Boolean isInfrastructure = topologyService.isInfrastructure(topology, cp1); assertTrue("The connect point should be infrastructure.", isInfrastructure); isInfrastructure = topologyService.isInfrastructure(topology, cp2); assertFalse("The connect point should not be infrastructure.", isInfrastructure); } /** * Test isBroadcastPoint() method using a null connect point. */ @Test(expected = NullPointerException.class) public void testIsBroadcastUsingNullConnectPoint() { VirtualNetwork virtualNetwork = setupVirtualNetworkTopology(); TopologyService topologyService = manager.get(virtualNetwork.id(), TopologyService.class); Topology topology = topologyService.currentTopology(); // test the isInfrastructure() method using a null connect point. Boolean isInfrastructure = topologyService.isBroadcastPoint(topology, null); } /** * Test isBroadcastPoint() method. */ @Test public void testIsBroadcastPoint() { VirtualNetwork virtualNetwork = setupVirtualNetworkTopology(); TopologyService topologyService = manager.get(virtualNetwork.id(), TopologyService.class); Topology topology = topologyService.currentTopology(); VirtualDevice srcVirtualDevice = getVirtualDevice(virtualNetwork.id(), DID1); ConnectPoint cp = new ConnectPoint(srcVirtualDevice.id(), PortNumber.portNumber(1)); // test the isBroadcastPoint() method. Boolean isBroadcastPoint = topologyService.isBroadcastPoint(topology, cp); assertTrue("The connect point should be a broadcast point.", isBroadcastPoint); } /** * Return the virtual device matching the device identifier. * * @param networkId virtual network identifier * @param deviceId device identifier * @return virtual device */ private VirtualDevice getVirtualDevice(NetworkId networkId, DeviceId deviceId) { Optional<VirtualDevice> foundDevice = manager.getVirtualDevices(networkId) .stream() .filter(device -> deviceId.equals(device.id())) .findFirst(); if (foundDevice.isPresent()) { return foundDevice.get(); } return null; } /** * Core service test class. */ private class TestCoreService extends CoreServiceAdapter { ApplicationId appId; @Override public IdGenerator getIdGenerator(String topic) { return new IdGenerator() { private AtomicLong counter = new AtomicLong(0); @Override public long getNewId() { return counter.getAndIncrement(); } }; } @Override public ApplicationId registerApplication(String name) { appId = new DefaultApplicationId(1, name); return appId; } @Override public ApplicationId getAppId(String name) { return appId; } } }
apache-2.0
jenniferzheng/gobblin
gobblin-data-management/src/test/java/org/apache/gobblin/data/management/conversion/hive/converter/HiveAvroToOrcConverterTest.java
13128
/* * 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.gobblin.data.management.conversion.hive.converter; import java.io.IOException; import java.util.List; import org.apache.avro.Schema; import org.apache.commons.lang.StringUtils; import org.apache.hadoop.hive.metastore.api.FieldSchema; import org.apache.hadoop.hive.metastore.api.Partition; import org.apache.hadoop.hive.metastore.api.Table; import org.testng.Assert; import org.testng.annotations.Test; import com.google.common.base.Optional; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableMap; import com.google.common.collect.Lists; import com.typesafe.config.Config; import com.typesafe.config.ConfigFactory; import org.apache.gobblin.configuration.WorkUnitState; import org.apache.gobblin.data.management.ConversionHiveTestUtils; import org.apache.gobblin.data.management.conversion.hive.LocalHiveMetastoreTestUtils; import org.apache.gobblin.data.management.conversion.hive.dataset.ConvertibleHiveDataset; import org.apache.gobblin.data.management.conversion.hive.dataset.ConvertibleHiveDatasetTest; import org.apache.gobblin.data.management.conversion.hive.entities.QueryBasedHiveConversionEntity; import org.apache.gobblin.data.management.conversion.hive.entities.SchemaAwareHivePartition; import org.apache.gobblin.data.management.conversion.hive.entities.SchemaAwareHiveTable; import org.apache.gobblin.data.management.copy.hive.WhitelistBlacklist; @Test(groups = { "gobblin.data.management.conversion" }) public class HiveAvroToOrcConverterTest { private static String resourceDir = "hiveConverterTest"; private LocalHiveMetastoreTestUtils hiveMetastoreTestUtils; public HiveAvroToOrcConverterTest() { this.hiveMetastoreTestUtils = LocalHiveMetastoreTestUtils.getInstance(); } /*** * Test flattened DDL and DML generation * @throws IOException */ @Test public void testFlattenSchemaDDLandDML() throws Exception { String dbName = "testdb"; String tableName = "testtable"; String tableSdLoc = "/tmp/testtable"; this.hiveMetastoreTestUtils.getLocalMetastoreClient().dropDatabase(dbName, false, true, true); Table table = this.hiveMetastoreTestUtils.createTestTable(dbName, tableName, tableSdLoc, Optional.<String> absent()); Schema schema = ConversionHiveTestUtils.readSchemaFromJsonFile(resourceDir, "recordWithinRecordWithinRecord_nested.json"); WorkUnitState wus = ConversionHiveTestUtils.createWus(dbName, tableName, 0); try (HiveAvroToFlattenedOrcConverter converter = new HiveAvroToFlattenedOrcConverter();) { Config config = ConfigFactory.parseMap( ImmutableMap.<String, String>builder().put("destinationFormats", "flattenedOrc") .put("flattenedOrc.destination.dbName", dbName) .put("flattenedOrc.destination.tableName", tableName + "_orc") .put("flattenedOrc.destination.dataPath", "file:" + tableSdLoc + "_orc").build()); ConvertibleHiveDataset cd = ConvertibleHiveDatasetTest.createTestConvertibleDataset(config); List<QueryBasedHiveConversionEntity> conversionEntities = Lists.newArrayList(converter.convertRecord(converter.convertSchema(schema, wus), new QueryBasedHiveConversionEntity(cd, new SchemaAwareHiveTable(table, schema)), wus)); Assert.assertEquals(conversionEntities.size(), 1, "Only one query entity should be returned"); QueryBasedHiveConversionEntity queryBasedHiveConversionEntity = conversionEntities.get(0); List<String> queries = queryBasedHiveConversionEntity.getQueries(); Assert.assertEquals(queries.size(), 4, "4 DDL and one DML query should be returned"); // Ignoring part before first bracket in DDL and 'select' clause in DML because staging table has // .. a random name component String actualDDLQuery = StringUtils.substringAfter("(", queries.get(0).trim()); String actualDMLQuery = StringUtils.substringAfter("SELECT", queries.get(0).trim()); String expectedDDLQuery = StringUtils.substringAfter("(", ConversionHiveTestUtils.readQueryFromFile(resourceDir, "recordWithinRecordWithinRecord_flattened.ddl")); String expectedDMLQuery = StringUtils.substringAfter("SELECT", ConversionHiveTestUtils.readQueryFromFile(resourceDir, "recordWithinRecordWithinRecord_flattened.dml")); Assert.assertEquals(actualDDLQuery, expectedDDLQuery); Assert.assertEquals(actualDMLQuery, expectedDMLQuery); } } /*** * Test nested DDL and DML generation * @throws IOException */ @Test public void testNestedSchemaDDLandDML() throws Exception { String dbName = "testdb"; String tableName = "testtable"; String tableSdLoc = "/tmp/testtable"; this.hiveMetastoreTestUtils.getLocalMetastoreClient().dropDatabase(dbName, false, true, true); Table table = this.hiveMetastoreTestUtils.createTestTable(dbName, tableName, tableSdLoc, Optional.<String> absent()); Schema schema = ConversionHiveTestUtils.readSchemaFromJsonFile(resourceDir, "recordWithinRecordWithinRecord_nested.json"); WorkUnitState wus = ConversionHiveTestUtils.createWus(dbName, tableName, 0); wus.getJobState().setProp("orc.table.flatten.schema", "false"); try (HiveAvroToNestedOrcConverter converter = new HiveAvroToNestedOrcConverter();) { Config config = ConfigFactory.parseMap(ImmutableMap.<String, String> builder() .put("destinationFormats", "nestedOrc") .put("nestedOrc.destination.tableName","testtable_orc_nested") .put("nestedOrc.destination.dbName",dbName) .put("nestedOrc.destination.dataPath","file:/tmp/testtable_orc_nested") .build()); ConvertibleHiveDataset cd = ConvertibleHiveDatasetTest.createTestConvertibleDataset(config); List<QueryBasedHiveConversionEntity> conversionEntities = Lists.newArrayList(converter.convertRecord(converter.convertSchema(schema, wus), new QueryBasedHiveConversionEntity(cd , new SchemaAwareHiveTable(table, schema)), wus)); Assert.assertEquals(conversionEntities.size(), 1, "Only one query entity should be returned"); QueryBasedHiveConversionEntity queryBasedHiveConversionEntity = conversionEntities.get(0); List<String> queries = queryBasedHiveConversionEntity.getQueries(); Assert.assertEquals(queries.size(), 4, "4 DDL and one DML query should be returned"); // Ignoring part before first bracket in DDL and 'select' clause in DML because staging table has // .. a random name component String actualDDLQuery = StringUtils.substringAfter("(", queries.get(0).trim()); String actualDMLQuery = StringUtils.substringAfter("SELECT", queries.get(0).trim()); String expectedDDLQuery = StringUtils.substringAfter("(", ConversionHiveTestUtils.readQueryFromFile(resourceDir, "recordWithinRecordWithinRecord_nested.ddl")); String expectedDMLQuery = StringUtils.substringAfter("SELECT", ConversionHiveTestUtils.readQueryFromFile(resourceDir, "recordWithinRecordWithinRecord_nested.dml")); Assert.assertEquals(actualDDLQuery, expectedDDLQuery); Assert.assertEquals(actualDMLQuery, expectedDMLQuery); } } @Test public void dropReplacedPartitionsTest() throws Exception { Table table = ConvertibleHiveDatasetTest.getTestTable("dbName", "tableName"); table.setTableType("VIRTUAL_VIEW"); table.setPartitionKeys(ImmutableList.of(new FieldSchema("year", "string", ""), new FieldSchema("month", "string", ""))); Partition part = new Partition(); part.setParameters(ImmutableMap.of("gobblin.replaced.partitions", "2015,12|2016,01")); SchemaAwareHiveTable hiveTable = new SchemaAwareHiveTable(table, null); SchemaAwareHivePartition partition = new SchemaAwareHivePartition(table, part, null); QueryBasedHiveConversionEntity conversionEntity = new QueryBasedHiveConversionEntity(null, hiveTable, Optional.of(partition)); List<ImmutableMap<String, String>> expected = ImmutableList.of(ImmutableMap.of("year", "2015", "month", "12"), ImmutableMap.of("year", "2016", "month", "01")); Assert.assertEquals(AbstractAvroToOrcConverter.getDropPartitionsDDLInfo(conversionEntity), expected); // Make sure that a partition itself is not dropped Partition replacedSelf = new Partition(); replacedSelf.setParameters(ImmutableMap.of("gobblin.replaced.partitions", "2015,12|2016,01|2016,02")); replacedSelf.setValues(ImmutableList.of("2016", "02")); conversionEntity = new QueryBasedHiveConversionEntity(null, hiveTable, Optional.of(new SchemaAwareHivePartition(table, replacedSelf, null))); Assert.assertEquals(AbstractAvroToOrcConverter.getDropPartitionsDDLInfo(conversionEntity), expected); } @Test /*** * More comprehensive tests for WhiteBlackList are in: {@link org.apache.gobblin.data.management.copy.hive.WhitelistBlacklistTest} */ public void hiveViewRegistrationWhiteBlackListTest() throws Exception { WorkUnitState wus = ConversionHiveTestUtils.createWus("dbName", "tableName", 0); Optional<WhitelistBlacklist> optionalWhitelistBlacklist = AbstractAvroToOrcConverter.getViewWhiteBackListFromWorkUnit(wus); Assert.assertTrue(!optionalWhitelistBlacklist.isPresent(), "No whitelist blacklist specified in WUS, WhiteListBlackList object should be absent"); wus.setProp(AbstractAvroToOrcConverter.HIVE_CONVERSION_VIEW_REGISTRATION_WHITELIST, ""); wus.setProp(AbstractAvroToOrcConverter.HIVE_CONVERSION_VIEW_REGISTRATION_BLACKLIST, ""); optionalWhitelistBlacklist = AbstractAvroToOrcConverter.getViewWhiteBackListFromWorkUnit(wus); Assert.assertTrue(optionalWhitelistBlacklist.isPresent(), "Whitelist blacklist specified in WUS, WhiteListBlackList object should be present"); Assert.assertTrue(optionalWhitelistBlacklist.get().acceptDb("mydb")); Assert.assertTrue(optionalWhitelistBlacklist.get().acceptTable("mydb", "mytable")); wus.setProp(AbstractAvroToOrcConverter.HIVE_CONVERSION_VIEW_REGISTRATION_WHITELIST, "yourdb"); wus.setProp(AbstractAvroToOrcConverter.HIVE_CONVERSION_VIEW_REGISTRATION_BLACKLIST, ""); optionalWhitelistBlacklist = AbstractAvroToOrcConverter.getViewWhiteBackListFromWorkUnit(wus); Assert.assertTrue(optionalWhitelistBlacklist.isPresent(), "Whitelist blacklist specified in WUS, WhiteListBlackList object should be present"); Assert.assertTrue(!optionalWhitelistBlacklist.get().acceptDb("mydb")); Assert.assertTrue(!optionalWhitelistBlacklist.get().acceptTable("mydb", "mytable")); Assert.assertTrue(optionalWhitelistBlacklist.get().acceptDb("yourdb")); Assert.assertTrue(optionalWhitelistBlacklist.get().acceptTable("yourdb", "mytable")); wus.setProp(AbstractAvroToOrcConverter.HIVE_CONVERSION_VIEW_REGISTRATION_WHITELIST, "yourdb.yourtable"); wus.setProp(AbstractAvroToOrcConverter.HIVE_CONVERSION_VIEW_REGISTRATION_BLACKLIST, ""); optionalWhitelistBlacklist = AbstractAvroToOrcConverter.getViewWhiteBackListFromWorkUnit(wus); Assert.assertTrue(optionalWhitelistBlacklist.isPresent(), "Whitelist blacklist specified in WUS, WhiteListBlackList object should be present"); Assert.assertTrue(!optionalWhitelistBlacklist.get().acceptDb("mydb")); Assert.assertTrue(!optionalWhitelistBlacklist.get().acceptTable("yourdb", "mytable")); Assert.assertTrue(optionalWhitelistBlacklist.get().acceptDb("yourdb")); Assert.assertTrue(optionalWhitelistBlacklist.get().acceptTable("yourdb", "yourtable")); wus.setProp(AbstractAvroToOrcConverter.HIVE_CONVERSION_VIEW_REGISTRATION_WHITELIST, ""); wus.setProp(AbstractAvroToOrcConverter.HIVE_CONVERSION_VIEW_REGISTRATION_BLACKLIST, "yourdb.yourtable"); optionalWhitelistBlacklist = AbstractAvroToOrcConverter.getViewWhiteBackListFromWorkUnit(wus); Assert.assertTrue(optionalWhitelistBlacklist.isPresent(), "Whitelist blacklist specified in WUS, WhiteListBlackList object should be present"); Assert.assertTrue(optionalWhitelistBlacklist.get().acceptDb("mydb")); Assert.assertTrue(optionalWhitelistBlacklist.get().acceptTable("yourdb", "mytable")); Assert.assertTrue(optionalWhitelistBlacklist.get().acceptDb("yourdb")); Assert.assertTrue(!optionalWhitelistBlacklist.get().acceptTable("yourdb", "yourtable")); } }
apache-2.0
andremanuelbarbosa/image-uploader
src/main/java/com/andremanuelbarbosa/imageuploader/dao/ImageUploaderImageDao.java
217
package com.andremanuelbarbosa.imageuploader.dao; import com.andremanuelbarbosa.imageuploader.domain.ImageUploaderImage; public interface ImageUploaderImageDao { public void addImage(ImageUploaderImage image); }
apache-2.0
gchq/stroom
stroom-util-shared/src/main/java/stroom/util/shared/validation/ValidFilePathValidator.java
287
package stroom.util.shared.validation; import javax.validation.ConstraintValidator; public interface ValidFilePathValidator extends ConstraintValidator<ValidFilePath, String> { // De-couples the use of the constraint annotation from the implementation of // that constraint. }
apache-2.0
epam/DLab
services/dlab-model/src/main/java/com/epam/dlab/dto/keyload/KeyLoadStatus.java
1894
/*************************************************************************** Copyright (c) 2016, EPAM SYSTEMS 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.epam.dlab.dto.keyload; import javax.ws.rs.core.Response; import java.util.Arrays; public enum KeyLoadStatus { NONE("none", null, Response.Status.NOT_FOUND), NEW("new", null, Response.Status.ACCEPTED), SUCCESS("success", "ok", Response.Status.OK), ERROR("error", "err", Response.Status.INTERNAL_SERVER_ERROR); private String status; private String value; private Response.Status httpStatus; KeyLoadStatus(String status, String value, Response.Status httpStatus) { this.status = status; this.value = value; this.httpStatus = httpStatus; } public String getStatus() { return status; } public Response.Status getHttpStatus() { return httpStatus; } public static boolean isSuccess(String value) { return SUCCESS.value.equals(value); } public static String getStatus(boolean successed) { return successed ? SUCCESS.status : ERROR.status; } public static KeyLoadStatus findByStatus(String status) { return Arrays.stream(values()).reduce(NONE, (result, next) -> next.status.equalsIgnoreCase(status) ? next : result); } }
apache-2.0
bytegriffin/Get4J
get4j-core/src/main/java/com/bytegriffin/get4j/download/DownloadFile.java
2540
package com.bytegriffin.get4j.download; import java.util.List; import java.util.Map; import com.bytegriffin.get4j.net.http.OkHttpClientEngine; import com.google.common.collect.Lists; import com.google.common.collect.Maps; public class DownloadFile { private String fileName; private byte[] content; private long contentLength; private String seedName; private String url; // 待下载的大文件列表 key:seedName value: download file list private static Map<String, List<DownloadFile>> download_big_file_list = Maps.newHashMap(); /** * 先将要下载的大文件地址加入到待下载列表中 * * @param seedName 种子名称 * @param downloadFile 下载文件对象 */ public static void add(String seedName, DownloadFile downloadFile) { List<DownloadFile> list = download_big_file_list.get(seedName); if (list != null && list.isEmpty()) { list.add(downloadFile); } else { list = Lists.newArrayList(); list.add(downloadFile); download_big_file_list.put(seedName, list); } } /** * 是否有大文件需要下载 * * @param seedName 种子名称 * @return 如果有大文件需要下载返回true,否则返回false */ public static boolean isExist(String seedName) { List<DownloadFile> list = download_big_file_list.get(seedName); if (list == null || list.isEmpty()) { return false; } return true; } /** * 下载大文件 * @param seedName String */ public static void downloadBigFile(String seedName) { if (isExist(seedName)) { List<DownloadFile> downlist = download_big_file_list.get(seedName); for (DownloadFile file : downlist) { OkHttpClientEngine.downloadBigFile(seedName, file.getUrl(), file.getContentLength()); } download_big_file_list.get(seedName).clear(); } } public String getFileName() { return fileName; } public DownloadFile setFileName(String fileName) { this.fileName = fileName; return this; } public byte[] getContent() { return content; } public DownloadFile setContent(byte[] content) { this.content = content; return this; } public long getContentLength() { return contentLength; } public DownloadFile setContentLength(long contentLength) { this.contentLength = contentLength; return this; } public DownloadFile setSeedName(String seedName) { this.seedName = seedName; return this; } public String getSeedName() { return seedName; } public String getUrl() { return url; } public DownloadFile setUrl(String url) { this.url = url; return this; } }
apache-2.0
romainmoreau/gas-sensor
gas-sensor-web/src/main/java/fr/romainmoreau/gassensor/web/jserialcomm/JSerialCommProperties.java
345
package fr.romainmoreau.gassensor.web.jserialcomm; import java.util.List; public class JSerialCommProperties { private List<JSerialCommGasSensor> gasSensors; public List<JSerialCommGasSensor> getGasSensors() { return gasSensors; } public void setGasSensors(List<JSerialCommGasSensor> gasSensors) { this.gasSensors = gasSensors; } }
apache-2.0
epam/DLab
services/security-service/src/main/java/com/epam/dlab/auth/dao/SearchRequestBuilder.java
830
/*************************************************************************** Copyright (c) 2016, EPAM SYSTEMS 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.epam.dlab.auth.dao; public class SearchRequestBuilder { public SearchRequestBuilder() { } }
apache-2.0
MartinMReed/signingserver-bb
signingserver-bb/src/main/java/net/hardisonbrewing/signingserver/service/icon/SVGService.java
3052
/** * Copyright (c) 2011 Martin M Reed * * 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.hardisonbrewing.signingserver.service.icon; import java.io.InputStream; import javax.microedition.m2g.SVGImage; import javax.microedition.m2g.ScalableGraphics; import net.rim.device.api.system.Bitmap; import net.rim.device.api.system.EncodedImage; import net.rim.device.api.system.PNGEncodedImage; import net.rim.device.api.ui.Graphics; import net.rim.device.api.ui.XYDimension; import net.rim.device.api.ui.XYEdges; import org.metova.mobile.util.io.IOUtility; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.w3c.dom.svg.SVGSVGElement; public class SVGService { private static final Logger log = LoggerFactory.getLogger( SVGService.class ); public static SVGImage getImage( String name ) { InputStream inputStream = null; try { inputStream = SVGService.class.getResourceAsStream( name ); return (SVGImage) SVGImage.createImage( inputStream, null ); } catch (Exception e) { log.error( "Execption loading SVG image", e ); return null; } finally { IOUtility.safeClose( inputStream ); } } public static EncodedImage convert( SVGImage svgImage, XYDimension image, XYEdges padding ) { int paddingTop = padding == null ? 0 : padding.top; int paddingRight = padding == null ? 0 : padding.right; int paddingBottom = padding == null ? 0 : padding.bottom; int paddingLeft = padding == null ? 0 : padding.left; svgImage.setViewportWidth( image.width - ( paddingLeft + paddingRight ) ); svgImage.setViewportHeight( image.height - ( paddingTop + paddingBottom ) ); SVGSVGElement svgElement = (SVGSVGElement) svgImage.getDocument().getDocumentElement(); svgElement.setFloatTrait( "width", svgImage.getViewportWidth() ); svgElement.setFloatTrait( "height", svgImage.getViewportHeight() ); Bitmap bitmap = new Bitmap( image.width, image.height ); bitmap.setARGB( new int[image.width * image.height], 0, image.width, 0, 0, image.width, image.height ); Graphics graphics = Graphics.create( bitmap ); ScalableGraphics scalableGraphics = ScalableGraphics.createInstance(); scalableGraphics.bindTarget( graphics ); scalableGraphics.render( paddingLeft, paddingTop, svgImage ); scalableGraphics.releaseTarget(); return PNGEncodedImage.encode( bitmap ); } }
apache-2.0
tzou24/abins
abins/src/main/java/org/abins/platform/core/service/impl/APermissionServiceImpl.java
3633
package org.abins.platform.core.service.impl; import java.util.List; import java.util.Map; import org.abins.platform.core.dao.IAPermissionDao; import org.abins.platform.core.dao.cache.IRedisDao; import org.abins.platform.core.entity.APermission; import org.abins.platform.core.exception.APermissionException; import org.abins.platform.core.service.IAPermissionService; import org.abins.platform.utils.ProtostuffUtil; import org.abins.platform.utils.RedisUtil; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import redis.clients.jedis.Jedis; import com.dyuproject.protostuff.ProtostuffIOUtil; import com.dyuproject.protostuff.runtime.RuntimeSchema; /** * 功能描述:资源权限业务层 * * @author : yaobin 2016-10-10 * @modify : yaobin 2016-10-10 <描述修改内容> */ @Service public class APermissionServiceImpl implements IAPermissionService { private Logger logger = LoggerFactory.getLogger(this.getClass()); @Autowired private IAPermissionDao permissionDao; //@Autowired //private IRedisDao<APermission> redisDao; private final String REDIS_KEY = "permission_redis_key"; private Jedis jedis = RedisUtil.getJedis(); @Override public int save(APermission permission) { int result = permissionDao.addPermission(permission); return result; } @Override public int update(APermission t) { return 0; } @Override public int delete(APermission permission) { int result = permissionDao.deleteById(permission.getPermissionId()); return result; } @Override public APermission findById(String permissionId) throws APermissionException { byte[] bytes = jedis.get(permissionId.getBytes()); APermission permission = null; if(bytes == null){ permission = permissionDao.findById(permissionId); byte[] serializer = ProtostuffUtil.serializer(permission); jedis.set(permission.getPermissionId().getBytes(), serializer); }else{ permission = ProtostuffUtil.deserializer(bytes, APermission.class); } if(permission == null){ logger.error("未找到该资源"); throw new APermissionException("未找到该资源"); }else{ return permission; } } @Override public List<APermission> queryAll(Map<String, Object> params) throws APermissionException { Jedis jedis = RedisUtil.getJedis(); try { byte[] bytes = jedis.get(REDIS_KEY.getBytes()); if(bytes != null){ APermission permission = ProtostuffUtil.deserializer(bytes, APermission.class); return null; } return null; } catch (Exception e) { return null; } //使用缓存 // List<APermission> redisCache = redisDao.getRedis(REDIS_KEY); // if(redisCache != null){ // // params == null // return redisCache; // }else{ // List<APermission> permissions = permissionDao.queryAll(params); // redisDao.addRedis(REDIS_KEY, permissions); // return permissions; // } } @Override public List<APermission> findByUserRole(String roleId) throws APermissionException { return null; } }
apache-2.0
JeanRev/TeamcityDockerCloudPlugin
server/src/test/java/run/var/teamcity/cloud/docker/util/ResourcesTest.java
5116
package run.var.teamcity.cloud.docker.util; import org.junit.Test; import run.var.teamcity.cloud.docker.TestResourceBundle; import java.util.MissingResourceException; import java.util.ResourceBundle; import static org.assertj.core.api.Assertions.*; public class ResourcesTest { @Test public void invalidConstructorInput() { assertThatExceptionOfType(NullPointerException.class).isThrownBy(() -> new Resources((ResourceBundle[]) null)); assertThatExceptionOfType(IllegalArgumentException.class).isThrownBy(Resources::new); } @Test public void text() { TestResourceBundle bundle = new TestResourceBundle(); bundle.getResourcesMap().put("test.key", "{0,number,#} {1,number} {3} '{4}' {5}"); Resources resources = new Resources(bundle); assertThat(resources.text("test.key", 1000, 1000, 1000, null)).isEqualTo("1000 1,000 null {4} {5}"); } @Test public void textMultipleBundles() { TestResourceBundle bundle1 = new TestResourceBundle(); TestResourceBundle bundle2 = new TestResourceBundle(); TestResourceBundle bundle3 = new TestResourceBundle(); bundle1.getResourcesMap().put("A", "1"); bundle2.getResourcesMap().put("A", "2"); bundle3.getResourcesMap().put("A", "3"); bundle2.getResourcesMap().put("B", "2"); bundle3.getResourcesMap().put("B", "3"); Resources resources = new Resources(bundle1, bundle2, bundle3); assertThat(resources.text("A", new Object[0])).isEqualTo("1"); assertThat(resources.text("B", new Object[0])).isEqualTo("2"); } @Test public void textNoArg() { TestResourceBundle bundle = new TestResourceBundle(); bundle.getResourcesMap().put("test.key", "'foo'"); Resources resources = new Resources(bundle); assertThat(resources.text("test.key")).isEqualTo("foo"); } @Test public void textNoArgMultipleBundles() { TestResourceBundle bundle1 = new TestResourceBundle(); TestResourceBundle bundle2 = new TestResourceBundle(); TestResourceBundle bundle3 = new TestResourceBundle(); bundle1.getResourcesMap().put("A", "1"); bundle2.getResourcesMap().put("A", "2"); bundle3.getResourcesMap().put("A", "3"); bundle2.getResourcesMap().put("B", "2"); bundle3.getResourcesMap().put("B", "3"); Resources resources = new Resources(bundle1, bundle2, bundle3); assertThat(resources.text("A")).isEqualTo("1"); assertThat(resources.text("B")).isEqualTo("2"); } @Test public void textInvalidInput() { TestResourceBundle bundle = new TestResourceBundle(); bundle.getResourcesMap().put("test.key", "foo"); Resources resources = new Resources(bundle); assertThatExceptionOfType(NullPointerException.class).isThrownBy(() -> resources.text(null, new Object[0])); assertThatExceptionOfType(NullPointerException.class).isThrownBy(() -> resources.text("missing.key", (Object[]) null)); assertThatExceptionOfType(MissingResourceException.class).isThrownBy(() -> resources.text("missing.key", new Object[0])); } @Test public void textNoArgInvalidInput() { TestResourceBundle bundle = new TestResourceBundle(); bundle.getResourcesMap().put("test.key", "foo"); Resources resources = new Resources(bundle); assertThatExceptionOfType(NullPointerException.class).isThrownBy(() -> resources.text(null)); assertThatExceptionOfType(MissingResourceException.class).isThrownBy(() -> resources.text("missing.key")); } @Test public void string() { TestResourceBundle bundle = new TestResourceBundle(); bundle.getResourcesMap().put("test.key", "'foo'"); Resources resources = new Resources(bundle); assertThat(resources.string("test.key")).isEqualTo("'foo'"); } @Test public void stringMultipleBundles() { TestResourceBundle bundle1 = new TestResourceBundle(); TestResourceBundle bundle2 = new TestResourceBundle(); TestResourceBundle bundle3 = new TestResourceBundle(); bundle1.getResourcesMap().put("A", "1"); bundle2.getResourcesMap().put("A", "2"); bundle3.getResourcesMap().put("A", "3"); bundle2.getResourcesMap().put("B", "2"); bundle3.getResourcesMap().put("B", "3"); Resources resources = new Resources(bundle1, bundle2, bundle3); assertThat(resources.string("A")).isEqualTo("1"); assertThat(resources.string("B")).isEqualTo("2"); } @Test public void stringInvalidInput() { TestResourceBundle bundle = new TestResourceBundle(); bundle.getResourcesMap().put("test.key", "'foo'"); Resources resources = new Resources(bundle); assertThatExceptionOfType(NullPointerException.class).isThrownBy(() -> resources.string(null)); assertThatExceptionOfType(MissingResourceException.class).isThrownBy(() -> resources.string("missing.key")); } }
apache-2.0
elhoim/gdata-client-java
java/src/com/google/gdata/model/gd/Organization.java
9983
/* Copyright (c) 2008 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.gdata.model.gd; import com.google.gdata.model.AttributeKey; import com.google.gdata.model.Element; import com.google.gdata.model.ElementCreator; import com.google.gdata.model.ElementKey; import com.google.gdata.model.MetadataRegistry; import com.google.gdata.model.QName; import com.google.gdata.util.Namespaces; /** * Describes an organization (like Company). * * */ public class Organization extends Element { /** Organization type. */ public static final class Rel { /** Other organization. */ public static final String OTHER = Namespaces.gPrefix + "other"; /** Work organization. */ public static final String WORK = Namespaces.gPrefix + "work"; /** Array containing all available values. */ private static final String[] ALL_VALUES = { OTHER, WORK}; /** Returns an array of all values defined in this class. */ public static String[] values() { return ALL_VALUES; } private Rel() {} } /** * The key for this element. */ public static final ElementKey<Void, Organization> KEY = ElementKey.of(new QName(Namespaces.gNs, "organization"), Void.class, Organization.class); /** * Label. */ public static final AttributeKey<String> LABEL = AttributeKey.of(new QName(null, "label"), String.class); /** * Whether this is the primary organization. */ public static final AttributeKey<Boolean> PRIMARY = AttributeKey.of(new QName(null, "primary"), Boolean.class); /** * Organization type. */ public static final AttributeKey<String> REL = AttributeKey.of(new QName(null, "rel"), String.class); /** * Registers the metadata for this element. */ public static void registerMetadata(MetadataRegistry registry) { if (registry.isRegistered(KEY)) { return; } // The builder for this element ElementCreator builder = registry.build(KEY); // Local properties builder.addAttribute(LABEL); builder.addAttribute(PRIMARY); builder.addAttribute(REL); builder.addElement(OrgDepartment.KEY); builder.addElement(OrgJobDescription.KEY); builder.addElement(OrgName.KEY); builder.addElement(OrgSymbol.KEY); builder.addElement(OrgTitle.KEY); builder.addElement(Where.KEY); } /** * Constructs an instance using the default key. */ public Organization() { super(KEY); } /** * Subclass constructor, allows subclasses to supply their own element key. */ protected Organization(ElementKey<?, ? extends Organization> key) { super(key); } /** * Constructs a new instance by doing a shallow copy of data from an existing * {@link Element} instance. Will use the given {@link ElementKey} as the key * for the element. This constructor is used when adapting from one element * key to another. You cannot call this constructor directly, instead use * {@link Element#createElement(ElementKey, Element)}. * * @param key The key to use for this element. * @param source source element */ protected Organization(ElementKey<?, ? extends Organization> key, Element source) { super(key, source); } @Override public Organization lock() { return (Organization) super.lock(); } /** * Returns the label. * * @return label */ public String getLabel() { return super.getAttributeValue(LABEL); } /** * Sets the label. * * @param label label or {@code null} to reset * @return this to enable chaining setters */ public Organization setLabel(String label) { super.setAttributeValue(LABEL, label); return this; } /** * Returns whether it has the label. * * @return whether it has the label */ public boolean hasLabel() { return getLabel() != null; } /** * Returns the department name in organization. * * @return department name in organization */ public OrgDepartment getOrgDepartment() { return super.getElement(OrgDepartment.KEY); } /** * Sets the department name in organization. * * @param orgDepartment department name in organization or {@code null} to * reset * @return this to enable chaining setters */ public Organization setOrgDepartment(OrgDepartment orgDepartment) { super.setElement(OrgDepartment.KEY, orgDepartment); return this; } /** * Returns whether it has the department name in organization. * * @return whether it has the department name in organization */ public boolean hasOrgDepartment() { return super.hasElement(OrgDepartment.KEY); } /** * Returns the job description. * * @return job description */ public OrgJobDescription getOrgJobDescription() { return super.getElement(OrgJobDescription.KEY); } /** * Sets the job description. * * @param orgJobDescription job description or {@code null} to reset * @return this to enable chaining setters */ public Organization setOrgJobDescription(OrgJobDescription orgJobDescription) { super.setElement(OrgJobDescription.KEY, orgJobDescription); return this; } /** * Returns whether it has the job description. * * @return whether it has the job description */ public boolean hasOrgJobDescription() { return super.hasElement(OrgJobDescription.KEY); } /** * Returns the name of organization. * * @return name of organization */ public OrgName getOrgName() { return super.getElement(OrgName.KEY); } /** * Sets the name of organization. * * @param orgName name of organization or {@code null} to reset * @return this to enable chaining setters */ public Organization setOrgName(OrgName orgName) { super.setElement(OrgName.KEY, orgName); return this; } /** * Returns whether it has the name of organization. * * @return whether it has the name of organization */ public boolean hasOrgName() { return super.hasElement(OrgName.KEY); } /** * Returns the organization symbol/ticker. * * @return organization symbol/ticker */ public OrgSymbol getOrgSymbol() { return super.getElement(OrgSymbol.KEY); } /** * Sets the organization symbol/ticker. * * @param orgSymbol organization symbol/ticker or {@code null} to reset * @return this to enable chaining setters */ public Organization setOrgSymbol(OrgSymbol orgSymbol) { super.setElement(OrgSymbol.KEY, orgSymbol); return this; } /** * Returns whether it has the organization symbol/ticker. * * @return whether it has the organization symbol/ticker */ public boolean hasOrgSymbol() { return super.hasElement(OrgSymbol.KEY); } /** * Returns the position in organization. * * @return position in organization */ public OrgTitle getOrgTitle() { return super.getElement(OrgTitle.KEY); } /** * Sets the position in organization. * * @param orgTitle position in organization or {@code null} to reset * @return this to enable chaining setters */ public Organization setOrgTitle(OrgTitle orgTitle) { super.setElement(OrgTitle.KEY, orgTitle); return this; } /** * Returns whether it has the position in organization. * * @return whether it has the position in organization */ public boolean hasOrgTitle() { return super.hasElement(OrgTitle.KEY); } /** * Returns the whether this is the primary organization. * * @return whether this is the primary organization */ public Boolean getPrimary() { return super.getAttributeValue(PRIMARY); } /** * Sets the whether this is the primary organization. * * @param primary whether this is the primary organization or {@code null} to * reset * @return this to enable chaining setters */ public Organization setPrimary(Boolean primary) { super.setAttributeValue(PRIMARY, primary); return this; } /** * Returns whether it has the whether this is the primary organization. * * @return whether it has the whether this is the primary organization */ public boolean hasPrimary() { return getPrimary() != null; } /** * Returns the organization type. * * @return organization type */ public String getRel() { return super.getAttributeValue(REL); } /** * Sets the organization type. * * @param rel organization type or {@code null} to reset * @return this to enable chaining setters */ public Organization setRel(String rel) { super.setAttributeValue(REL, rel); return this; } /** * Returns whether it has the organization type. * * @return whether it has the organization type */ public boolean hasRel() { return getRel() != null; } /** * Returns the office location. * * @return office location */ public Where getWhere() { return super.getElement(Where.KEY); } /** * Sets the office location. * * @param where office location or {@code null} to reset * @return this to enable chaining setters */ public Organization setWhere(Where where) { super.setElement(Where.KEY, where); return this; } /** * Returns whether it has the office location. * * @return whether it has the office location */ public boolean hasWhere() { return super.hasElement(Where.KEY); } }
apache-2.0
torrances/swtk-commons
commons-dict-wiktionary/src/main/java/org/swtk/commons/dict/wiktionary/generated/y/t/t/WiktionaryYTT000.java
2089
package org.swtk.commons.dict.wiktionary.generated.y.t.t; import java.util.Collection; import java.util.HashMap; import java.util.Map; import org.swtk.common.dict.dto.wiktionary.Entry; import com.trimc.blogger.commons.utils.GsonUtils; public class WiktionaryYTT000 { private static Map<String, Entry> map = new HashMap<String, Entry>(); static { add("ytterbia", "{\"term\":\"ytterbia\", \"etymology\":{\"influencers\":[], \"languages\":[], \"text\":\"\"}, \"definitions\":{\"list\":[{\"upperType\":\"NOUN\", \"text\":\"ytterbium oxid\", \"priority\":1},{\"upperType\":\"NOUN\", \"text\":\"Ytterbium oxide\", \"priority\":2}]}, \"synonyms\":{}}"); add("yttrium", "{\"term\":\"yttrium\", \"etymology\":{\"influencers\":[], \"languages\":[], \"text\":\"From w:Ytterby|Ytterby, (literally, \u0026quot;outer village\u0026quot;) a town in Sweden.\"}, \"definitions\":{\"list\":[{\"upperType\":\"NOUN\", \"text\":\"A metallic chemical element (\u0027symbol\u0027 Y) with an atomic number of 39\", \"priority\":1},{\"upperType\":\"NOUN\", \"text\":\"A single atom of this element\", \"priority\":2}]}, \"synonyms\":{}}"); add("yttrotantalite", "{\"term\":\"yttrotantalite\", \"etymology\":{\"influencers\":[], \"languages\":[], \"text\":\"{{prefix|yttro|tantalite|lang\u003den}}\"}, \"definitions\":{\"list\":[{\"upperType\":\"NOUN\", \"text\":\"A brown or black tantalate of uranium, yttrium, and calcium\", \"priority\":1}]}, \"synonyms\":{}}"); add("yttrotitanite", "{\"term\":\"yttrotitanite\", \"etymology\":{\"influencers\":[], \"languages\":[], \"text\":\"{{prefix|yttro|titanite|lang\u003den}}\"}, \"definitions\":{\"list\":[{\"upperType\":\"NOUN\", \"text\":\"A brownish-black variety of titanite\", \"priority\":1}]}, \"synonyms\":{}}"); } private static void add(String term, String json) { map.put(term, GsonUtils.toObject(json, Entry.class)); } public static Entry get(String term) { return map.get(term); } public static boolean has(String term) { return null != get(term); } public static Collection<String> terms() { return map.keySet(); } }
apache-2.0