code
stringlengths
5
1.04M
repo_name
stringlengths
7
108
path
stringlengths
6
299
language
stringclasses
1 value
license
stringclasses
15 values
size
int64
5
1.04M
/* * Copyright 2011 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 io.rover.shaded.zxing.com.google.zxing.maxicode; import io.rover.shaded.zxing.com.google.zxing.BarcodeFormat; import io.rover.shaded.zxing.com.google.zxing.BinaryBitmap; import io.rover.shaded.zxing.com.google.zxing.ChecksumException; import io.rover.shaded.zxing.com.google.zxing.DecodeHintType; import io.rover.shaded.zxing.com.google.zxing.FormatException; import io.rover.shaded.zxing.com.google.zxing.NotFoundException; import io.rover.shaded.zxing.com.google.zxing.Reader; import io.rover.shaded.zxing.com.google.zxing.Result; import io.rover.shaded.zxing.com.google.zxing.ResultMetadataType; import io.rover.shaded.zxing.com.google.zxing.ResultPoint; import io.rover.shaded.zxing.com.google.zxing.common.BitMatrix; import io.rover.shaded.zxing.com.google.zxing.common.DecoderResult; import io.rover.shaded.zxing.com.google.zxing.maxicode.decoder.Decoder; import java.util.Map; /** * This implementation can detect and decode a MaxiCode in an image. */ public final class MaxiCodeReader implements Reader { private static final ResultPoint[] NO_POINTS = new ResultPoint[0]; private static final int MATRIX_WIDTH = 30; private static final int MATRIX_HEIGHT = 33; private final Decoder decoder = new Decoder(); /* Decoder getDecoder() { return decoder; } */ /** * Locates and decodes a MaxiCode in an image. * * @return a String representing the content encoded by the MaxiCode * @throws NotFoundException if a MaxiCode cannot be found * @throws FormatException if a MaxiCode cannot be decoded * @throws ChecksumException if error correction fails */ @Override public Result decode(BinaryBitmap image) throws NotFoundException, ChecksumException, FormatException { return decode(image, null); } @Override public Result decode(BinaryBitmap image, Map<DecodeHintType,?> hints) throws NotFoundException, ChecksumException, FormatException { DecoderResult decoderResult; if (hints != null && hints.containsKey(DecodeHintType.PURE_BARCODE)) { BitMatrix bits = extractPureBits(image.getBlackMatrix()); decoderResult = decoder.decode(bits, hints); } else { throw NotFoundException.getNotFoundInstance(); } Result result = new Result(decoderResult.getText(), decoderResult.getRawBytes(), NO_POINTS, BarcodeFormat.MAXICODE); String ecLevel = decoderResult.getECLevel(); if (ecLevel != null) { result.putMetadata(ResultMetadataType.ERROR_CORRECTION_LEVEL, ecLevel); } return result; } @Override public void reset() { // do nothing } /** * This method detects a code in a "pure" image -- that is, pure monochrome image * which contains only an unrotated, unskewed, image of a code, with some white border * around it. This is a specialized method that works exceptionally fast in this special * case. * * @see io.rover.shaded.zxing.com.google.zxing.datamatrix.DataMatrixReader#extractPureBits(BitMatrix) * @see io.rover.shaded.zxing.com.google.zxing.qrcode.QRCodeReader#extractPureBits(BitMatrix) */ private static BitMatrix extractPureBits(BitMatrix image) throws NotFoundException { int[] enclosingRectangle = image.getEnclosingRectangle(); if (enclosingRectangle == null) { throw NotFoundException.getNotFoundInstance(); } int left = enclosingRectangle[0]; int top = enclosingRectangle[1]; int width = enclosingRectangle[2]; int height = enclosingRectangle[3]; // Now just read off the bits BitMatrix bits = new BitMatrix(MATRIX_WIDTH, MATRIX_HEIGHT); for (int y = 0; y < MATRIX_HEIGHT; y++) { int iy = top + (y * height + height / 2) / MATRIX_HEIGHT; for (int x = 0; x < MATRIX_WIDTH; x++) { int ix = left + (x * width + width / 2 + (y & 0x01) * width / 2) / MATRIX_WIDTH; if (image.get(ix, iy)) { bits.set(x, y); } } } return bits; } }
RoverPlatform/rover-android
sdk/src/main/java/io/rover/shaded/zxing/com/google/zxing/maxicode/MaxiCodeReader.java
Java
apache-2.0
4,533
import java.io.IOException; import java.util.Random; import java.lang.Thread; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.fs.FileSystem; import org.apache.hadoop.fs.FSDataInputStream; import org.apache.hadoop.fs.FSDataOutputStream; import org.apache.hadoop.fs.Path; import org.apache.hadoop.fs.Seekable; import org.apache.hadoop.fs.FileStatus; import org.apache.hadoop.ipc.RemoteException; public class MultipleFileThroughput { public static void main(String[] args) { if (args.length == 0) { System.out.println("Usage: hadoop jar RW_Exp.jar {setup, run}) [args]\n\n"+ "Example 1: To create a 2 MB file of random bytes called example.txt:\n\t" + "hadoop jar RW_Exp.jar setup 2 example.txt\n"+ "Example 1: To time 3000 read/write requests to/from example.txt of size 32KB with 75% reads:\n\t" + "hadoop jar RW_Exp.jar run 3000 32 0.75 example.txt\n"); } else if (args[0].equals("setup")) { if (args.length < 3) { System.out.println("Not Enough Arguments\n" + "Usage: hadoop jar RW_Exp.jar setup <File Size in MB> <File Name>" ); return; } setup(Integer.parseInt(args[1]), args[2]); } else if (args[0].equals("run")) { if (args.length < 5) { System.out.println("Not Enough Arguments\n" + "Usage: hadoop jar RW_Exp.jar run <Number of Requests>"+ " <Request Size (KB)>" + " <Read/Write Ratio>" + " <File Name>" ); return; } run(Integer.parseInt(args[1]), Integer.parseInt(args[2]), Double.parseDouble(args[3]), args[4]); } } public static void run(int N_REQUESTS, int REQUEST_SIZE, double READ_RATIO, String filename) { try { Configuration conf = new Configuration(); FileSystem fs = FileSystem.get(conf); //File to write to Path file = new Path(filename); Random rand = new Random(System.currentTimeMillis()); //32 kilobytes of random data byte[] randBuf = new byte[REQUEST_SIZE * 1024]; rand.nextBytes(randBuf); FileStatus fileStat = fs.getFileStatus(file); //Length of the file int FILE_SIZE = (int) fileStat.getLen(); //Open reader and writer FSDataInputStream reader = fs.open(file); FSDataOutputStream writer = fs.append(file); long startTime = System.currentTimeMillis(); for (int i=0; i < N_REQUESTS; i++) { int newIndex = rand.nextInt(FILE_SIZE - randBuf.length); if (rand.nextFloat() < READ_RATIO) { //Read 32 KB reader.seek(newIndex); reader.read(randBuf); } else { //Write 32 KB writer.seek(newIndex); writer.write(randBuf); rand.nextBytes(randBuf); } } System.out.println(System.currentTimeMillis() - startTime); writer.close(); reader.close(); } catch (Exception e) { System.out.println(e); e.printStackTrace(); } } public static void setup(int FILE_SIZE, String filename) { try { Configuration conf = new Configuration(); FileSystem fs = FileSystem.get(conf); //File to write to Path file = new Path(filename); FSDataOutputStream out = fs.create(file); //Create a random byte array Random rand = new Random(System.currentTimeMillis()); //1 MB byte[] mbBuffer = new byte[1048576]; //Write 1GB to file for (int i=0; i<FILE_SIZE; i++) { rand.nextBytes(mbBuffer); out.write(mbBuffer); if (i % 100 == 0) { System.out.println( "Wrote " + ((double) i / 1000.0) + " GB"); } } out.close(); } catch (Exception e) { System.out.println(e); e.printStackTrace(); } } }
songweijia/hdfsrs
experiments/stephen/MultipleFileThroughputExperiments/MultipleFileThroughput.java
Java
apache-2.0
3,862
package com.jukusoft.renderer2d.prototyp.engine.math; /** * Created by Justin on 23.08.2016. */ public class Vector2f implements Cloneable { /** * vector coordinates */ protected volatile float x = 0; protected volatile float y = 0; /** * default constructor * * @param x x coordinate of vector * @param y y coordinate of vector */ public Vector2f (float x, float y) { this.x = x; this.y = y; } /** * default constructor */ public Vector2f () { // } public float getX () { return x; } public float getY () { return y; } public void setX(float x) { this.x = x; } public void setY(float y) { this.y = y; } @Override public Vector2f clone () { return new Vector2f(this.x, this.y); } }
JuKu/java-2drenderer-prototyp
prototyp-game-engine/src/main/java/com/jukusoft/renderer2d/prototyp/engine/math/Vector2f.java
Java
apache-2.0
883
/* * Copyright The OpenTelemetry Authors * SPDX-License-Identifier: Apache-2.0 */ package io.opentelemetry.testing; import static org.assertj.core.api.Assertions.assertThat; import io.opentelemetry.sdk.metrics.common.InstrumentType; import io.opentelemetry.sdk.metrics.common.InstrumentValueType; import io.opentelemetry.sdk.metrics.internal.debug.SourceInfo; import io.opentelemetry.sdk.metrics.internal.descriptor.InstrumentDescriptor; import io.opentelemetry.sdk.metrics.internal.descriptor.MetricDescriptor; import io.opentelemetry.sdk.metrics.internal.state.DebugUtils; import io.opentelemetry.sdk.metrics.internal.view.ImmutableView; import io.opentelemetry.sdk.metrics.view.View; import org.junit.jupiter.api.Test; // Note: This class MUST be outside the io.opentelemetry.metrics package to work correctly. class SourceInfoTest { // Note: The line numbers for these statics are used as part of the test. private static final SourceInfo info = SourceInfo.fromCurrentStack(); @Test void sourceInfoFindsStackTrace() { assertThat(info.shortDebugString()).isEqualTo("SourceInfoTest.java:23"); assertThat(info.multiLineDebugString()) .startsWith( "\tat io.opentelemetry.testing.SourceInfoTest.<clinit>(SourceInfoTest.java:23)\n"); } @Test void testDuplicateExceptionMessage_pureInstruments() { MetricDescriptor simple = MetricDescriptor.create( View.builder().build(), InstrumentDescriptor.create( "name", "description", "unit", InstrumentType.OBSERVABLE_COUNTER, InstrumentValueType.DOUBLE)); MetricDescriptor simpleWithNewDescription = MetricDescriptor.create( View.builder().build(), InstrumentDescriptor.create( "name", "description2", "unit2", InstrumentType.COUNTER, InstrumentValueType.LONG)); assertThat(DebugUtils.duplicateMetricErrorMessage(simple, simpleWithNewDescription)) .contains("Found duplicate metric definition: name") .contains("- Unit [unit2] does not match [unit]") .contains("- Description [description2] does not match [description]") .contains("- InstrumentType [COUNTER] does not match [OBSERVABLE_COUNTER]") .contains("- InstrumentValueType [LONG] does not match [DOUBLE]") .contains(simple.getSourceInstrument().getSourceInfo().multiLineDebugString()) .contains("Original instrument registered with same name but is incompatible.") .contains( simpleWithNewDescription.getSourceInstrument().getSourceInfo().multiLineDebugString()); } @Test void testDuplicateExceptionMessage_viewBasedConflict() { View problemView = View.builder().setName("name2").build(); MetricDescriptor simple = MetricDescriptor.create( problemView, InstrumentDescriptor.create( "name", "description", "unit", InstrumentType.HISTOGRAM, InstrumentValueType.DOUBLE)); MetricDescriptor simpleWithNewDescription = MetricDescriptor.create( View.builder().build(), InstrumentDescriptor.create( "name2", "description2", "unit", InstrumentType.HISTOGRAM, InstrumentValueType.DOUBLE)); assertThat(DebugUtils.duplicateMetricErrorMessage(simple, simpleWithNewDescription)) .contains("Found duplicate metric definition: name2") .contains(simple.getSourceInstrument().getSourceInfo().multiLineDebugString()) .contains("- Description [description2] does not match [description]") .contains("Conflicting view registered") .contains(ImmutableView.getSourceInfo(problemView).multiLineDebugString()) .contains("FROM instrument name") .contains( simpleWithNewDescription.getSourceInstrument().getSourceInfo().multiLineDebugString()); } @Test void testDuplicateExceptionMessage_viewBasedConflict2() { View problemView = View.builder().setName("name").build(); MetricDescriptor simple = MetricDescriptor.create( View.builder().build(), InstrumentDescriptor.create( "name", "description", "unit2", InstrumentType.HISTOGRAM, InstrumentValueType.DOUBLE)); MetricDescriptor simpleWithNewDescription = MetricDescriptor.create( problemView, InstrumentDescriptor.create( "name2", "description", "unit", InstrumentType.HISTOGRAM, InstrumentValueType.DOUBLE)); assertThat(DebugUtils.duplicateMetricErrorMessage(simple, simpleWithNewDescription)) .contains("Found duplicate metric definition: name") .contains("VIEW defined") .contains(ImmutableView.getSourceInfo(problemView).multiLineDebugString()) .contains("FROM instrument name2") .contains(simple.getSourceInstrument().getSourceInfo().multiLineDebugString()) .contains("- Unit [unit] does not match [unit2]") .contains("Original instrument registered with same name but is incompatible.") .contains( simpleWithNewDescription.getSourceInstrument().getSourceInfo().multiLineDebugString()); } }
open-telemetry/opentelemetry-java
sdk/metrics/src/debugEnabledTest/java/io/opentelemetry/testing/SourceInfoTest.java
Java
apache-2.0
5,456
package org.apereo.cas.services; import org.apereo.cas.support.events.service.CasRegisteredServiceLoadedEvent; import lombok.ToString; import lombok.val; import org.springframework.context.ConfigurableApplicationContext; import java.util.ArrayList; import java.util.Collection; import java.util.Comparator; import java.util.List; import java.util.Objects; import java.util.stream.Stream; /** * Default In Memory Service Registry Dao for test/demonstration purposes. * * @author Scott Battaglia * @since 3.1 */ @ToString public class InMemoryServiceRegistry extends AbstractServiceRegistry { private final List<RegisteredService> registeredServices; public InMemoryServiceRegistry(final ConfigurableApplicationContext applicationContext) { this(applicationContext, new ArrayList<>(0), new ArrayList<>(0)); } public InMemoryServiceRegistry(final ConfigurableApplicationContext applicationContext, final List<RegisteredService> registeredServices, final Collection<ServiceRegistryListener> serviceRegistryListeners) { super(applicationContext, serviceRegistryListeners); this.registeredServices = registeredServices; } @Override public boolean delete(final RegisteredService registeredService) { return this.registeredServices.remove(registeredService); } @Override public RegisteredService findServiceById(final long id) { return this.registeredServices.stream().filter(r -> r.getId() == id).findFirst().orElse(null); } @Override public Collection<RegisteredService> load() { val services = new ArrayList<RegisteredService>(registeredServices.size()); registeredServices .stream() .map(this::invokeServiceRegistryListenerPostLoad) .filter(Objects::nonNull) .forEach(s -> { publishEvent(new CasRegisteredServiceLoadedEvent(this, s)); services.add(s); }); return services; } @Override public RegisteredService save(final RegisteredService registeredService) { if (registeredService.getId() == RegisteredService.INITIAL_IDENTIFIER_VALUE) { registeredService.setId(findHighestId() + 1); } invokeServiceRegistryListenerPreSave(registeredService); val svc = findServiceById(registeredService.getId()); if (svc != null) { this.registeredServices.remove(svc); } this.registeredServices.add(registeredService); return registeredService; } /** * This isn't super-fast but we don't expect thousands of services. * * @return the highest service id in the list of registered services */ private long findHighestId() { return this.registeredServices.stream().map(RegisteredService::getId).max(Comparator.naturalOrder()).orElse(0L); } @Override public long size() { return registeredServices.size(); } @Override public Stream<? extends RegisteredService> getServicesStream() { return this.registeredServices.stream(); } }
pdrados/cas
core/cas-server-core-services-registry/src/main/java/org/apereo/cas/services/InMemoryServiceRegistry.java
Java
apache-2.0
3,186
/* * 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.syncope.client.search; import org.syncope.client.AbstractBaseBean; /** * Search condition to be applied when comparing attribute values. */ public class AttributeCond extends AbstractBaseBean { private static final long serialVersionUID = 3275277728404021417L; public enum Type { LIKE, EQ, GT, LT, GE, LE, ISNULL, ISNOTNULL } private Type type; private String schema; private String expression; public AttributeCond() { super(); } public AttributeCond(final Type conditionType) { super(); this.type = conditionType; } public final String getExpression() { return expression; } public final void setExpression(final String conditionExpression) { this.expression = conditionExpression; } public final String getSchema() { return schema; } public final void setSchema(final String conditionSchema) { this.schema = conditionSchema; } public final Type getType() { return type; } public final void setType(final Type conditionType) { this.type = conditionType; } public final boolean checkValidity() { return type != null && schema != null && (type == Type.ISNULL || type == Type.ISNOTNULL || expression != null); } }
ilgrosso/oldSyncopeIdM
client/src/main/java/org/syncope/client/search/AttributeCond.java
Java
apache-2.0
2,225
package com.sys1yagi.android_roughly_java8.tools; import org.apache.commons.io.FileUtils; import android.content.Context; import java.io.File; import java.io.IOException; import javax.inject.Inject; import javax.inject.Singleton; import rx.Observable; @Singleton public class FileManager { Context context; @Inject GsonHolder gsonHolder; @Inject public FileManager(Context context) { this.context = context; } public File getFileDir() { return context.getFilesDir(); } public File saveJsonToFileDir(Object object, String name) { File dir = getFileDir(); File file = new File(dir, name); try { FileUtils.writeStringToFile(file, gsonHolder.getGson().toJson(object)); } catch (IOException e) { e.printStackTrace(); return null; } return file; } public boolean removeFromFileDir(String name) { File dir = getFileDir(); File file = new File(dir, name); return file.delete(); } public <T> T loadJsonFromFileDir(String name, Class<T> clazz) { File dir = getFileDir(); File file = new File(dir, name); if (!file.exists()) { return null; } try { String string = FileUtils.readFileToString(file); return gsonHolder.getGson().fromJson(string, clazz); } catch (IOException e) { return null; } } public Observable<File> getFileDirFiles() { return files(getFileDir()); } public Observable<File> files(File f) { if (f == null) { return Observable.empty(); } if (f.isDirectory()) { return Observable.from(f.listFiles()).flatMap(this::files); } else { return Observable.just(f); } } }
sys1yagi/android-roughly-java8
app/src/main/java/com/sys1yagi/android_roughly_java8/tools/FileManager.java
Java
apache-2.0
1,868
package service; import java.util.List; import model.Person; public interface IPersonService { public List<Person> loadPersons(); }
Chaos777/ssm
src/main/java/service/IPersonService.java
Java
apache-2.0
139
/* * Copyright 2013 Cloud4SOA, www.cloud4soa.eu * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package eu.cloud4soa.adapter.rest.conversion; /** * This factory is only proof of concept * I do not know if the properties i use are correct! * I need clarification about c4s datamodels! * * @author Denis Neuling (dn@cloudcontrol.de) */ public class RequestFactory { // public static MonitorDetailRequest createMonitorDetailRequest(IMonitoringJob monitoringJob){ // MonitorDetailRequest monitorDetailRequest = new MonitorDetailRequest(); // monitorDetailRequest.setBaseUrl(monitoringJob.getCheckUrl()); // // return monitorDetailRequest; // } // // public static ExtendedMonitorRequest createExtendedMonitorRequest(IMonitoringJob monitoringJob, String ApplicationURL){ // ExtendedMonitorRequest extendedMonitorRequest = new ExtendedMonitorRequest(); // extendedMonitorRequest.setBaseUrl(monitoringJob.getCheckUrl()); // extendedMonitorRequest.setApplicationUrl(ApplicationURL); // // return extendedMonitorRequest; // } // // public static DeleteDeploymentRequest createDeleteDeploymentRequest(ApplicationInstance applicationInstance){ // DeleteDeploymentRequest deleteDeploymentRequest = new DeleteDeploymentRequest(); // // deleteDeploymentRequest.setBaseUrl(applicationInstance.getDeploymentIP()); // deleteDeploymentRequest.setApplicationName(applicationInstance.getTitle()); // deleteDeploymentRequest.setDeploymentName(applicationInstance.getApplication().getDeployment().getUriId()); // // return deleteDeploymentRequest; // } }
SeaCloudsEU/paas-unified-library
adapter-REST/src/main/java/eu/cloud4soa/adapter/rest/conversion/RequestFactory.java
Java
apache-2.0
2,119
package allow.simulator.knowledge; import java.util.ArrayList; import java.util.List; import java.util.concurrent.Callable; import java.util.concurrent.CountDownLatch; import allow.simulator.entity.Entity; import allow.simulator.knowledge.crf.DBConnector; import allow.simulator.mobility.planner.Itinerary; import allow.simulator.mobility.planner.Leg; import allow.simulator.mobility.planner.TType; import allow.simulator.world.Street; import allow.simulator.world.StreetSegment; import allow.simulator.world.Weather; public class Worker implements Callable<List<Itinerary>> { // Requests to send to the planner. public List<Itinerary> toUpdate; public Entity entity; // Latch to count down for thread synchronization. public CountDownLatch latch; public void prepare(Entity entity, List<Itinerary> toUpdate, CountDownLatch latch) { this.entity = entity; this.toUpdate = toUpdate; this.latch = latch; } public void reset() { toUpdate = null; latch = null; entity = null; } @Override public List<Itinerary> call() throws Exception { for (Itinerary it : toUpdate) { List<Experience> ex = itineraryToTravelExperience(entity, it); try { DBConnector.getPredictedItinerary(entity, ex); /*it.priorSegmentation = new ArrayList<TravelExperience>(ex.size()); for (TravelExperience e : ex) { it.priorSegmentation.add(e.clone()); }*/ updateItineraryFromTravelExperience(it, ex); } catch (Exception e) { e.printStackTrace(); } } latch.countDown(); return toUpdate; } private static List<Experience> itineraryToTravelExperience(Entity e, Itinerary it) { List<Experience> ret = new ArrayList<Experience>(); Weather.State currentWeather = e.getContext().getWeather().getCurrentState(); for (Leg l : it.legs) { long tStart = l.startTime; long tEnd = 0; if (l.streets.size() == 0) { double v = (l.mode == TType.WALK) ? StreetSegment.WALKING_SPEED : ((l.mode == TType.BICYCLE || l.mode == TType.SHARED_BICYCLE) ? StreetSegment.CYCLING_SPEED : StreetSegment.DEFAULT_DRIVING_SPEED); tEnd = (long) (tStart + l.distance / v); ret.add(new Experience(tEnd - tStart, 0.0, l.mode, tStart, tEnd, -1, -1, null, currentWeather)); continue; } for (Street street : l.streets) { double v = (l.mode == TType.WALK) ? street.getSubSegments() .get(0).getWalkingSpeed() : ((l.mode == TType.BICYCLE || l.mode == TType.SHARED_BICYCLE) ? street.getSubSegments() .get(0).getCyclingSpeed() : street .getSubSegments().get(0).getMaxSpeed()); double travelTime = street.getLength() / v; double costs = l.costs * (street.getLength() / l.distance); tEnd = (long) (tStart + travelTime * 1000); Experience t = new Experience(street, travelTime, costs, l.mode, tStart, tEnd, -1, -1, l.tripId, currentWeather); ret.add(t); tStart = tEnd; } } return ret; } private static void updateItineraryFromTravelExperience(Itinerary it, List<Experience> ex) { if (ex.size() == 0) { return; } it.waitingTime = 0; int exIndex = 0; long legStartTime = 0; long legEndTime = 0; boolean first = true; for (Leg l : it.legs) { if (first || l.mode == TType.BUS || l.mode == TType.CABLE_CAR) { legStartTime = l.startTime; legEndTime = legStartTime; } else { legStartTime = legEndTime; } int added = 0; for (int i = exIndex; i < ex.size(); i++) { Experience e = ex.get(i); if (e.isTransient()) break; // In case transportation means changes. if ((e.getTransportationMean() != l.mode)) { break; } // In case these is an intermediate bus change. if ((l.mode == TType.BUS || l.mode == TType.CABLE_CAR) && !l.tripId.equals(e.getPublicTransportationTripId())) { break; } double duration = e.getTravelTime() * 1000; it.maxFillingLevel = Math.max(e.getPublicTransportationFillingLevel(), it.maxFillingLevel); legEndTime += duration; added++; } exIndex += added; if (added == 0) { legEndTime += ex.get(exIndex++).getTravelTime() * 1000; } first = false; l.startTime = legStartTime; l.endTime = legEndTime; } // Update itinerary time. it.startTime = it.legs.get(0).startTime; it.endTime = it.startTime; for (Leg l : it.legs) { long duration = (l.endTime - l.startTime); it.endTime += duration; } it.duration = ((it.endTime - it.startTime) / 1000); // Compute waiting time. for (int i = 0; i < it.legs.size() - 1; i++) { it.waitingTime += ((it.legs.get(i + 1).startTime - it.legs.get(i).endTime) / 1000); } it.duration += (it.waitingTime / 1000); } }
poxrucker/collaborative-learning-simulation
Simulator/src/allow/simulator/knowledge/Worker.java
Java
apache-2.0
4,724
/* * Copyright 2000-2011 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.util.indexing; import com.intellij.openapi.fileTypes.FileType; import com.intellij.openapi.project.Project; import consulo.util.dataholder.UserDataHolder; import com.intellij.openapi.vfs.VirtualFile; import com.intellij.psi.PsiFile; import javax.annotation.Nonnull; import javax.annotation.Nullable; /** * @author Eugene Zhuravlev * Date: Mar 28, 2008 */ public interface FileContent extends UserDataHolder { @Nonnull FileType getFileType(); @Nonnull VirtualFile getFile(); @Nonnull String getFileName(); byte[] getContent(); @Nonnull CharSequence getContentAsText(); @Nullable Project getProject(); @Nonnull PsiFile getPsiFile(); }
consulo/consulo
modules/base/core-api/src/main/java/com/intellij/util/indexing/FileContent.java
Java
apache-2.0
1,301
package com.suscipio_solutions.consecro_mud.Abilities.Spells; import java.util.Vector; import com.suscipio_solutions.consecro_mud.Abilities.interfaces.Ability; import com.suscipio_solutions.consecro_mud.Common.interfaces.CMMsg; import com.suscipio_solutions.consecro_mud.Common.interfaces.PhyStats; import com.suscipio_solutions.consecro_mud.Exits.interfaces.Exit; import com.suscipio_solutions.consecro_mud.Locales.interfaces.Room; import com.suscipio_solutions.consecro_mud.MOBS.interfaces.MOB; import com.suscipio_solutions.consecro_mud.core.CMClass; import com.suscipio_solutions.consecro_mud.core.CMLib; import com.suscipio_solutions.consecro_mud.core.CMParms; import com.suscipio_solutions.consecro_mud.core.Directions; import com.suscipio_solutions.consecro_mud.core.interfaces.Physical; @SuppressWarnings("rawtypes") public class Spell_IllusoryWall extends Spell { @Override public String ID() { return "Spell_IllusoryWall"; } private final static String localizedName = CMLib.lang().L("Illusory Wall"); @Override public String name() { return localizedName; } @Override protected int canAffectCode(){return CAN_EXITS;} @Override protected int canTargetCode(){return CAN_EXITS;} @Override public int classificationCode(){ return Ability.ACODE_SPELL|Ability.DOMAIN_ILLUSION;} @Override public int abstractQuality(){ return Ability.QUALITY_INDIFFERENT;} @Override public void affectPhyStats(Physical affected, PhyStats affectableStats) { super.affectPhyStats(affected,affectableStats); // when this spell is on a MOBs Affected list, // it should consistantly put the mob into // a sleeping state, so that nothing they do // can get them out of it. affectableStats.setDisposition(affectableStats.disposition()|PhyStats.IS_INVISIBLE); } @Override public boolean invoke(MOB mob, Vector commands, Physical givenTarget, boolean auto, int asLevel) { final String whatToOpen=CMParms.combine(commands,0); final int dirCode=Directions.getGoodDirectionCode(whatToOpen); if(dirCode<0) { mob.tell(L("Cast which direction?!")); return false; } final Exit exit=mob.location().getExitInDir(dirCode); final Room room=mob.location().getRoomInDir(dirCode); if((exit==null)||(room==null)||(!CMLib.flags().canBeSeenBy(exit,mob))) { mob.tell(L("That way is already closed.")); return false; } if(!super.invoke(mob,commands,givenTarget,auto,asLevel)) return false; final boolean success=proficiencyCheck(mob,0,auto); if(!success) beneficialVisualFizzle(mob,null,L("<S-NAME> whisper(s) @x1, but nothing happens.",Directions.getDirectionName(dirCode))); else { final CMMsg msg=CMClass.getMsg(mob,exit,this,verbalCastCode(mob,exit,auto),auto?"":L("^S<S-NAME> whisper(s) @x1.^?",Directions.getDirectionName(dirCode))); if(mob.location().okMessage(mob,msg)) { mob.location().send(mob,msg); beneficialAffect(mob,exit,asLevel,0); } } return success; } }
ConsecroMUD/ConsecroMUD
com/suscipio_solutions/consecro_mud/Abilities/Spells/Spell_IllusoryWall.java
Java
apache-2.0
2,943
package com.linxcool.andbase.ui.swipeback; import android.os.Bundle; import android.preference.PreferenceActivity; import android.view.View; public class SwipeBackPreferenceActivity extends PreferenceActivity implements SwipeBackActivityBase { private SwipeBackActivityHelper mHelper; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); mHelper = new SwipeBackActivityHelper(this); mHelper.onActivityCreate(); } @Override protected void onPostCreate(Bundle savedInstanceState) { super.onPostCreate(savedInstanceState); mHelper.onPostCreate(); } @Override public View findViewById(int id) { View v = super.findViewById(id); if (v == null && mHelper != null) return mHelper.findViewById(id); return v; } @Override public SwipeBackLayout getSwipeBackLayout() { return mHelper.getSwipeBackLayout(); } @Override public void setSwipeBackEnable(boolean enable) { getSwipeBackLayout().setEnableGesture(enable); } @Override public void scrollToFinishActivity() { getSwipeBackLayout().scrollToFinishActivity(); } }
linxcool/wechoice
library/src/main/java/com/linxcool/andbase/ui/swipeback/SwipeBackPreferenceActivity.java
Java
apache-2.0
1,240
package com.tagmycode.plugin; import com.j256.ormlite.dao.Dao; import com.j256.ormlite.dao.GenericRawResults; import com.tagmycode.plugin.filter.FilterLanguages; import com.tagmycode.sdk.DbService; import com.tagmycode.sdk.model.Language; import com.tagmycode.sdk.model.LanguagesCollection; import com.tagmycode.sdk.model.Snippet; import java.sql.SQLException; public class FilterLanguagesLoader { private Data data; public FilterLanguagesLoader(Data data) { this.data = data; } public FilterLanguages load() { DbService dbService = data.getStorageEngine().getDbService(); Dao<Snippet, String> snippetDao = dbService.snippetDao(); GenericRawResults<String[]> query; FilterLanguages filterLanguages = new FilterLanguages(); try { LanguagesCollection languages = data.getLanguages(); query = snippetDao.queryRaw( "SELECT languages.code, count(*) AS total FROM languages" + " INNER JOIN snippets ON snippets.language_id = languages.id" + " GROUP BY name ORDER BY total DESC"); for (String[] language : query) { Language foundLanguage = languages.findByCode(language[0]); if (foundLanguage == null) { Framework.LOGGER.error("Language " + language[0] + " not found in Language list"); } else { filterLanguages.add(foundLanguage, Integer.valueOf(language[1])); } } } catch (SQLException e) { e.printStackTrace(); } return filterLanguages; } }
massimozappino/tagmycode-java-plugin-framework
src/main/java/com/tagmycode/plugin/FilterLanguagesLoader.java
Java
apache-2.0
1,676
package cn.itweet.modules.admin.article.service.tag; import cn.itweet.ItweetBootApplication; import cn.itweet.common.exception.SystemException; import cn.itweet.modules.admin.article.entity.Tag; import org.junit.Assert; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.data.domain.Page; import org.springframework.data.domain.PageRequest; import org.springframework.test.context.junit4.SpringRunner; import java.util.Date; /** * Created by whoami on 20/04/2017. */ @RunWith(SpringRunner.class) @SpringBootTest(classes = ItweetBootApplication.class) public class TagServiceTests { @Autowired private TagService tagService; @Test public void test() throws SystemException { // addTagTest(); //getTagByNameTest(); //listTest(); //updateTest(); //deleteByIdTest(); } private void deleteByIdTest() { tagService.deleteById(tagService.getTagByName("spark").getId()); } private void updateTest() throws SystemException { Tag tag = tagService.getTagByName("impala"); tag.setName("spark"); tagService.update(tag); } private void listTest() { Page<Tag> tags = tagService.list(0); Assert.assertEquals(1,tags.getContent().size()); } private void getTagByNameTest() { Assert.assertNotNull(tagService.getTagByName("impala")); } private void addTagTest() throws SystemException { Tag t = tagService.addTag(new Tag("impala",new Date())); // tagService.addTag(new Tag("hawq",new Date())); // tagService.addTag(new Tag("drill",new Date())); // tagService.addTag(new Tag("DeepGreen",new Date())); // tagService.addTag(new Tag("Itweet",new Date())); // tagService.addTag(new Tag("BlueData",new Date())); Assert.assertEquals("impala",t.getName()); } }
itweet/itweet-boot
src/test/java/cn/itweet/modules/admin/article/service/tag/TagServiceTests.java
Java
apache-2.0
2,011
/* * 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.cassandra.distributed.test; import java.io.IOException; import org.junit.AfterClass; import org.junit.BeforeClass; import org.junit.Test; import org.apache.cassandra.distributed.Cluster; import org.apache.cassandra.distributed.api.NodeToolResult; import static org.junit.Assert.assertEquals; public class NodeToolTest extends TestBaseImpl { private static Cluster CLUSTER; @BeforeClass public static void before() throws IOException { CLUSTER = init(Cluster.build().withNodes(1).start()); } @AfterClass public static void after() { if (CLUSTER != null) CLUSTER.close(); } @Test public void testCommands() throws Throwable { assertEquals(0, CLUSTER.get(1).nodetool("help")); assertEquals(0, CLUSTER.get(1).nodetool("flush")); assertEquals(1, CLUSTER.get(1).nodetool("not_a_legal_command")); } @Test public void testCaptureConsoleOutput() throws Throwable { NodeToolResult ringResult = CLUSTER.get(1).nodetoolResult("ring"); ringResult.asserts().stdoutContains("Datacenter: datacenter0"); ringResult.asserts().stdoutContains("127.0.0.1 rack0 Up Normal"); assertEquals("Non-empty error output", "", ringResult.getStderr()); } @Test public void testNodetoolSystemExit() { // Verify currently calls System.exit, this test uses that knowlege to test System.exit behavior in jvm-dtest CLUSTER.get(1).nodetoolResult("verify", "--check-tokens") .asserts() .failure() .stdoutContains("Token verification requires --extended-verify"); } }
blerer/cassandra
test/distributed/org/apache/cassandra/distributed/test/NodeToolTest.java
Java
apache-2.0
2,504
/* * Copyright (c) 2013 Noveo Group * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * Except as contained in this notice, the name(s) of the above copyright holders * shall not be used in advertising or otherwise to promote the sale, use or * other dealings in this Software without prior written authorization. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package com.noveogroup.android.log; /** * Simple implementation of {@link Logger} that prints all messages * using {@link Handler} interface. */ public class SimpleLogger extends AbstractLogger { private final Handler handler; /** * Creates new {@link SimpleLogger} instance. * * @param name the name of the logger. * @param handler the handler to log messages. */ public SimpleLogger(String name, Handler handler) { super(name); this.handler = handler; } @Override public boolean isEnabled(Level level) { return handler != null && handler.isEnabled(level); } @Override public void print(Level level, String message, Throwable throwable) { if (handler != null) { handler.print(getName(), level, throwable, message); } } @Override public void print(Level level, Throwable throwable, String messageFormat, Object... args) { if (handler != null) { handler.print(getName(), level, throwable, messageFormat, args); } } }
MACEPA/EpiSample
androidCommon/src/main/java/com/noveogroup/android/log/SimpleLogger.java
Java
apache-2.0
2,437
package edu.umass.cs.runner.system.generators; import edu.umass.cs.runner.Record; import edu.umass.cs.runner.Runner; import edu.umass.cs.runner.system.backend.AbstractLibrary; import edu.umass.cs.runner.system.backend.IHTML; import edu.umass.cs.runner.utils.Slurpie; import edu.umass.cs.surveyman.input.AbstractLexer; import edu.umass.cs.surveyman.input.AbstractParser; import edu.umass.cs.surveyman.input.csv.CSVLexer; import edu.umass.cs.surveyman.survey.HTMLDatum; import edu.umass.cs.surveyman.survey.StringDatum; import edu.umass.cs.surveyman.survey.Survey; import edu.umass.cs.surveyman.survey.SurveyDatum; import edu.umass.cs.surveyman.survey.exceptions.SurveyException; import org.jsoup.Jsoup; import org.jsoup.nodes.Document; import org.jsoup.nodes.Element; import java.io.BufferedWriter; import java.io.FileWriter; import java.io.IOException; import java.net.MalformedURLException; public class HTML { public static final String REMOTE_REFERENCE = jsReference("https://surveyman.github.io/surveyman.js/surveyman.main.js"); public static final String LOCAL_REFERENCE = jsReference("surveyman.main.js"); private static String jsReference(String src) { return String.format("<script type=\"text/javascript\" src=\"%s\"></script>\n", src); } private static String stringify() throws SurveyException, MalformedURLException { return "<div name=\"question\" hidden>" + "<p class=\"question\"></p>" + "<p class=\"answer\"></p>" + "</div>"; } private static String stringifyPreview(SurveyDatum c) throws SurveyException { String baseString = SurveyDatum.html(c); return String.format("<div id=\"preview\" hidden>%s</div>" , ((c instanceof StringDatum) ? CSVLexer.htmlChars2XML(baseString) : "")); } public static void spitHTMLToFile( String html, Survey survey) throws IOException, SurveyException, InstantiationException, IllegalAccessException { String htmlFileName = Record.getHtmlFileName(survey); Runner.LOGGER.info(String.format("Source html found at %s", htmlFileName)); BufferedWriter bw = new BufferedWriter(new FileWriter(htmlFileName)); bw.write(html); bw.close(); } private static String cleanedPreview(Record record) { String preview = record.library.props.getProperty("splashpage", ""); Document doc = Jsoup.parse(preview); Element body = doc.body(); return body.html(); } public static String getHTMLString( Record record, IHTML backendHTML) throws SurveyException { String html = ""; try { assert record!=null; assert(record.library!=null); assert(record.library.props!=null); String strPreview = cleanedPreview(record); String breakoffMessage = record.breakoffMessage; SurveyDatum preview = AbstractParser.parseComponent( HTMLDatum.isHTMLComponent(strPreview) ? AbstractLexer.xmlChars2HTML(strPreview) : strPreview, -1, -1, -1); html = String.format(Slurpie.slurp(AbstractLibrary.HTMLSKELETON) , record.survey.encoding , JS.getJSString(record.backendType, record.survey, preview, breakoffMessage) , stringifyPreview(preview) , stringify() , backendHTML.getActionForm(record) , record.survey.source , record.outputFileName , backendHTML.getHTMLString() , Slurpie.slurp(AbstractLibrary.CUSTOMCSS, true) ); } catch (IOException ex) { Runner.LOGGER.fatal(ex); System.exit(-1); } try{ spitHTMLToFile(html, record.survey); } catch (IOException io) { Runner.LOGGER.warn(io); } catch (InstantiationException e) { e.printStackTrace(); } catch (IllegalAccessException e) { e.printStackTrace(); } return html; // return (new HtmlCompressor()).compress(html); } }
SurveyMan/Runner
src/main/java/edu/umass/cs/runner/system/generators/HTML.java
Java
apache-2.0
4,343
/* JAI-Ext - OpenSource Java Advanced Image Extensions Library * http://www.geo-solutions.it/ * Copyright 2014 GeoSolutions * 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 it.geosolutions.jaiext.scale; import java.awt.Point; import java.awt.Rectangle; import java.awt.RenderingHints; import java.awt.geom.Point2D; import java.awt.image.Raster; import java.awt.image.RenderedImage; import java.awt.image.WritableRaster; import java.awt.image.renderable.ParameterBlock; import java.util.Map; import javax.media.jai.BorderExtender; import javax.media.jai.GeometricOpImage; import javax.media.jai.ImageLayout; import javax.media.jai.IntegerSequence; import javax.media.jai.Interpolation; import javax.media.jai.JAI; import javax.media.jai.OpImage; import javax.media.jai.PlanarImage; import javax.media.jai.ROI; import javax.media.jai.RenderedOp; import javax.media.jai.WarpOpImage; import com.sun.media.jai.util.ImageUtil; import com.sun.media.jai.util.Rational; import it.geosolutions.jaiext.interpolators.InterpolationBicubic; import it.geosolutions.jaiext.interpolators.InterpolationBilinear; import it.geosolutions.jaiext.interpolators.InterpolationNearest; import it.geosolutions.jaiext.range.Range; /** * A class extending <code>WarpOpImage</code> for use by further extension classes that perform image scaling. Image scaling operations require * rectilinear backwards mapping and padding by the resampling filter dimensions. * * <p> * When applying scale factors of scaleX, scaleY to a source image with the upper left pixel at (srcMinX, srcMinY) and width of srcWidth and height of * srcHeight, the resulting image is defined to have the following bounds: * * <code> * dstMinX = ceil(A), where A = srcMinX * scaleX - 0.5 + transX, * dstMinY = ceil(B), where B = srcMinY * scaleY - 0.5 + transY, * dstMaxX = ceil(C), where C = (srcMaxX + 1) * scaleX - 1.5 + transX * and srcMaxX = srcMinX + srcWidth - 1 * dstMaxY = ceil(D), where D = (srcMaxY + 1) * scaleY - 1.5 + transY * and srcMaxY = srcMinY + srcHeight - 1 * dstWidth = dstMaxX - dstMinX + 1 * dstHeight = dstMaxY - dstMinY + 1 * </code> * * <p> * In the case where source's upper left pixel is located is (0, 0), the formulae simplify to * * <code> * dstMinX = 0 * dstMinY = 0 * dstWidth = ceil (srcWidth * scaleX - 0.5 + transX) * dstHeight = ceil (srcHeight * scaleY - 0.5 + transY) * </code> * * <p> * In the case where the source's upper left pixel is located at (0, 0) and the scaling factors are integers, the formulae further simplify to * * <code> * dstMinX = 0 * dstMinY = 0 * dstWidth = ceil (srcWidth * scaleX + transX) * dstWidth = ceil (srcHeight * scaleY + transY) * </code> * * <p> * When interpolations which require padding the source such as Bilinear or Bicubic interpolation are specified, the source needs to be extended such * that it has the extra pixels needed to compute all the destination pixels. This extension is performed via the <code>BorderExtender</code> class. * The type of border extension can be specified as a <code>RenderingHint</code> to the <code>JAI.create</code> method. * * <p> * If no <code>BorderExtender</code> is specified, the source will not be extended. The scaled image size is still calculated according to the formula * specified above. However since there is not enough source to compute all the destination pixels, only that subset of the destination image's pixels * which can be computed, will be written in the destination. The rest of the destination will be set to zeros. * * <p> * It may be noted that the minX, minY, width and height hints as specified through the <code>JAI.KEY_IMAGE_LAYOUT</code> hint in the * <code>RenderingHints</code> object are not honored, as this operator calculates the destination image bounds itself. The other * <code>ImageLayout</code> hints, like tileWidth and tileHeight, however are honored. * * It should be noted that the superclass <code>GeometricOpImage</code> automatically adds a value of <code>Boolean.TRUE</code> for the * <code>JAI.KEY_REPLACE_INDEX_COLOR_MODEL</code> to the given <code>configuration</code> and passes it up to its superclass constructor so that * geometric operations are performed on the pixel values instead of being performed on the indices into the color map for those operations whose * source(s) have an <code>IndexColorModel</code>. This addition will take place only if a value for the * <code>JAI.KEY_REPLACE_INDEX_COLOR_MODEL</code> has not already been provided by the user. Note that the <code>configuration</code> Map is cloned * before the new hint is added to it. Regarding the value for the <code>JAI.KEY_REPLACE_INDEX_COLOR_MODEL</code> <code>RenderingHints</code>, the * operator itself can be smart based on the parameters, i.e. while the default value for the <code>JAI.KEY_REPLACE_INDEX_COLOR_MODEL</code> is * <code>Boolean.TRUE</code> for operations that extend this class, in some cases the operator could set the default. * * @see WarpOpImage * @see OpImage * */ public abstract class ScaleOpImage extends GeometricOpImage { /** The horizontal scale factor. */ protected float scaleX; /** The vertical scale factor. */ protected float scaleY; /** Thee horizontal translation factor */ protected float transX; /** The vertical translation factor */ protected float transY; /*** Rational representations */ protected Rational scaleXRational, scaleYRational; protected long scaleXRationalNum, scaleXRationalDenom; protected long scaleYRationalNum, scaleYRationalDenom; protected Rational invScaleXRational, invScaleYRational; protected long invScaleXRationalNum, invScaleXRationalDenom; protected long invScaleYRationalNum, invScaleYRationalDenom; protected Rational transXRational, transYRational; protected long transXRationalNum, transXRationalDenom; protected long transYRationalNum, transYRationalDenom; protected static float rationalTolerance = 0.000001F; // Padding private int lpad, rpad, tpad, bpad; /** Source ROI */ protected final ROI srcROI; /** ROI image */ protected final PlanarImage srcROIImage; /** Boolean indicating if a ROI object is used */ protected final boolean hasROI; /** Rectangle containing ROI bounds */ protected final Rectangle roiBounds; /** Value indicating if roi RasterAccessor should be used on computations */ protected boolean useRoiAccessor; /** Inverse scale value X */ protected long invScaleXInt; /** Inverse scale fractional value X */ protected long invScaleXFrac; /** Inverse scale value Y */ protected long invScaleYInt; /** Inverse scale fractional value Y */ protected long invScaleYFrac; /** Interpolator provided to the Scale operator */ protected Interpolation interpolator = null; /** Boolean for checking if the image is binary or not */ protected boolean isBinary; /** Subsample bits used for binary and bicubic interpolation */ protected int subsampleBits; /** Value used for calculating the fractional part of the y position */ protected int one; /** Interpolation kernel width */ protected int interp_width; /** Interpolation kernel heigth */ protected int interp_height; /** Interpolation kernel left padding */ protected int interp_left; /** Interpolation kernel top padding */ protected int interp_top; /** Value used for calculating the bilinear interpolation for integer dataTypes */ protected int shift; /** Value used for calculating the bilinear interpolation */ protected int shift2; /** The value of 0.5 scaled by 2^subsampleBits */ protected int round2; /** Precision bits used for bicubic interpolation */ protected int precisionBits; /** The value of 0.5 scaled by 2^precisionBits */ protected int round; /** Image dataType */ protected int dataType; /** No Data Range */ protected Range noData; /** Boolean for checking if no data range is present */ protected boolean hasNoData = false; /** Destination value for No Data byte */ protected byte[] destinationNoDataByte; /** Destination value for No Data ushort */ protected short[] destinationNoDataUShort; /** Destination value for No Data short */ protected short[] destinationNoDataShort; /** Destination value for No Data int */ protected int[] destinationNoDataInt; /** Destination value for No Data float */ protected float[] destinationNoDataFloat; /** Destination value for No Data double */ protected double[] destinationNoDataDouble; /** Boolean for checking if the no data is negative infinity */ protected boolean isNegativeInf = false; /** Boolean for checking if the no data is positive infinity */ protected boolean isPositiveInf = false; /** Boolean for checking if the no data is NaN */ protected boolean isRangeNaN = false; /** Boolean for checking if the interpolator is Nearest */ protected boolean isNearestNew = false; /** Boolean for checking if the interpolator is Bilinear */ protected boolean isBilinearNew = false; /** Boolean for checking if the interpolator is Bicubic */ protected boolean isBicubicNew = false; /** Boolean indicating if No Data and ROI are not used */ protected boolean caseA; /** Boolean indicating if only the ROI is used */ protected boolean caseB; /** Boolean indicating if only the No Data are used */ protected boolean caseC; /** Extended ROI image*/ protected RenderedOp srcROIImgExt; /** Extended source Image*/ protected RenderedOp extendedIMG; /** The extended bounds used by the roi iterator */ protected Rectangle roiRect; /** ROI Border Extender */ final static BorderExtender roiExtender = BorderExtender .createInstance(BorderExtender.BORDER_ZERO); // FORMULAE FOR FORWARD MAP are derived as follows // Nearest // Minimum: // srcMin = floor ((dstMin + 0.5 - trans) / scale) // srcMin <= (dstMin + 0.5 - trans) / scale < srcMin + 1 // srcMin*scale <= dstMin + 0.5 - trans < (srcMin + 1)*scale // srcMin*scale - 0.5 + trans // <= dstMin < (srcMin + 1)*scale - 0.5 + trans // Let A = srcMin*scale - 0.5 + trans, // Let B = (srcMin + 1)*scale - 0.5 + trans // // dstMin = ceil(A) // // Maximum: // Note that srcMax is defined to be srcMin + dimension - 1 // srcMax = floor ((dstMax + 0.5 - trans) / scale) // srcMax <= (dstMax + 0.5 - trans) / scale < srcMax + 1 // srcMax*scale <= dstMax + 0.5 - trans < (srcMax + 1)*scale // srcMax*scale - 0.5 + trans // <= dstMax < (srcMax+1) * scale - 0.5 + trans // Let float A = (srcMax + 1) * scale - 0.5 + trans // // dstMax = floor(A), if floor(A) < A, else // dstMax = floor(A) - 1 // OR dstMax = ceil(A - 1) // // Other interpolations // // First the source should be shrunk by the padding that is // required for the particular interpolation. Then the // shrunk source should be forward mapped as follows: // // Minimum: // srcMin = floor (((dstMin + 0.5 - trans)/scale) - 0.5) // srcMin <= ((dstMin + 0.5 - trans)/scale) - 0.5 < srcMin+1 // (srcMin+0.5)*scale <= dstMin+0.5-trans < // (srcMin+1.5)*scale // (srcMin+0.5)*scale - 0.5 + trans // <= dstMin < (srcMin+1.5)*scale - 0.5 + trans // Let A = (srcMin+0.5)*scale - 0.5 + trans, // Let B = (srcMin+1.5)*scale - 0.5 + trans // // dstMin = ceil(A) // // Maximum: // srcMax is defined as srcMin + dimension - 1 // srcMax = floor (((dstMax + 0.5 - trans) / scale) - 0.5) // srcMax <= ((dstMax + 0.5 - trans)/scale) - 0.5 < srcMax+1 // (srcMax+0.5)*scale <= dstMax + 0.5 - trans < // (srcMax+1.5)*scale // (srcMax+0.5)*scale - 0.5 + trans // <= dstMax < (srcMax+1.5)*scale - 0.5 + trans // Let float A = (srcMax+1.5)*scale - 0.5 + trans // // dstMax = floor(A), if floor(A) < A, else // dstMax = floor(A) - 1 // OR dstMax = ceil(A - 1) // private static ImageLayout layoutHelper(RenderedImage source, float scaleX, float scaleY, float transX, float transY, Interpolation interp, ImageLayout il) { // Represent the scale factors as Rational numbers. // Since a value of 1.2 is represented as 1.200001 which // throws the forward/backward mapping in certain situations. // Convert the scale and translation factors to Rational numbers Rational scaleXRational = Rational.approximate(scaleX, rationalTolerance); Rational scaleYRational = Rational.approximate(scaleY, rationalTolerance); long scaleXRationalNum = (long) scaleXRational.num; long scaleXRationalDenom = (long) scaleXRational.denom; long scaleYRationalNum = (long) scaleYRational.num; long scaleYRationalDenom = (long) scaleYRational.denom; Rational transXRational = Rational.approximate(transX, rationalTolerance); Rational transYRational = Rational.approximate(transY, rationalTolerance); long transXRationalNum = (long) transXRational.num; long transXRationalDenom = (long) transXRational.denom; long transYRationalNum = (long) transYRational.num; long transYRationalDenom = (long) transYRational.denom; ImageLayout layout = (il == null) ? new ImageLayout() : (ImageLayout) il.clone(); int x0 = source.getMinX(); int y0 = source.getMinY(); int w = source.getWidth(); int h = source.getHeight(); // Variables to store the calculated destination upper left coordinate long dx0Num, dx0Denom, dy0Num, dy0Denom; // Variables to store the calculated destination bottom right // coordinate long dx1Num, dx1Denom, dy1Num, dy1Denom; // Start calculations for destination dx0Num = x0; dx0Denom = 1; dy0Num = y0; dy0Denom = 1; // Formula requires srcMaxX + 1 = (x0 + w - 1) + 1 = x0 + w dx1Num = x0 + w; dx1Denom = 1; // Formula requires srcMaxY + 1 = (y0 + h - 1) + 1 = y0 + h dy1Num = y0 + h; dy1Denom = 1; dx0Num *= scaleXRationalNum; dx0Denom *= scaleXRationalDenom; dy0Num *= scaleYRationalNum; dy0Denom *= scaleYRationalDenom; dx1Num *= scaleXRationalNum; dx1Denom *= scaleXRationalDenom; dy1Num *= scaleYRationalNum; dy1Denom *= scaleYRationalDenom; // Equivalent to subtracting 0.5 dx0Num = 2 * dx0Num - dx0Denom; dx0Denom *= 2; dy0Num = 2 * dy0Num - dy0Denom; dy0Denom *= 2; // Equivalent to subtracting 1.5 dx1Num = 2 * dx1Num - 3 * dx1Denom; dx1Denom *= 2; dy1Num = 2 * dy1Num - 3 * dy1Denom; dy1Denom *= 2; // Adding translation factors // Equivalent to float dx0 += transX dx0Num = dx0Num * transXRationalDenom + transXRationalNum * dx0Denom; dx0Denom *= transXRationalDenom; // Equivalent to float dy0 += transY dy0Num = dy0Num * transYRationalDenom + transYRationalNum * dy0Denom; dy0Denom *= transYRationalDenom; // Equivalent to float dx1 += transX dx1Num = dx1Num * transXRationalDenom + transXRationalNum * dx1Denom; dx1Denom *= transXRationalDenom; // Equivalent to float dy1 += transY dy1Num = dy1Num * transYRationalDenom + transYRationalNum * dy1Denom; dy1Denom *= transYRationalDenom; // Get the integral coordinates int l_x0, l_y0, l_x1, l_y1; l_x0 = Rational.ceil(dx0Num, dx0Denom); l_y0 = Rational.ceil(dy0Num, dy0Denom); l_x1 = Rational.ceil(dx1Num, dx1Denom); l_y1 = Rational.ceil(dy1Num, dy1Denom); // Set the top left coordinate of the destination layout.setMinX(l_x0); layout.setMinY(l_y0); int width = l_x1 - l_x0 + 1; int height = l_y1 - l_y0 + 1; if (width < 1) width = 1; if (height < 1) height = 1; // Width and height layout.setWidth(width); layout.setHeight(height); return layout; } // This method precompute the integer and fractional position of every pixel protected final void preComputePositionsInt(Rectangle destRect, int srcRectX, int srcRectY, int srcPixelStride, int srcScanlineStride, int xpos[], int ypos[], int[] xfracvalues, int[] yfracvalues, int roiScanlineStride, int[] yposRoi) { // Destination Rectangle position final int dwidth = destRect.width; final int dheight = destRect.height; // Loop variables based on the destination rectangle to be calculated. final int dx = destRect.x; final int dy = destRect.y; // Initially the y source value is calculated by the destination value and then performing the inverse // scale operation on it. long syNum = dy, syDenom = 1; // Subtract the X translation factor sy -= transY syNum = syNum * transYRationalDenom - transYRationalNum * syDenom; syDenom *= transYRationalDenom; // Add 0.5 syNum = 2 * syNum + syDenom; syDenom *= 2; // Multply by invScaleX syNum *= invScaleYRationalNum; syDenom *= invScaleYRationalDenom; if (isBilinearNew || isBicubicNew) { // Subtract 0.5 syNum = 2 * syNum - syDenom; syDenom *= 2; } // Separate the y source coordinate into integer and fractional part int srcYInt = Rational.floor(syNum, syDenom); long srcYFrac = syNum % syDenom; if (srcYInt < 0) { srcYFrac = syDenom + srcYFrac; } // Normalize - Get a common denominator for the fracs of // src and invScaleY final long commonYDenom = syDenom * invScaleYRationalDenom; srcYFrac *= invScaleYRationalDenom; final long newInvScaleYFrac = invScaleYFrac * syDenom; // Initially the x source value is calculated by the destination value and then performing the inverse // scale operation on it. long sxNum = dx, sxDenom = 1; // Subtract the X translation factor sx -= transX sxNum = sxNum * transXRationalDenom - transXRationalNum * sxDenom; sxDenom *= transXRationalDenom; // Add 0.5 sxNum = 2 * sxNum + sxDenom; sxDenom *= 2; // Multply by invScaleX sxNum *= invScaleXRationalNum; sxDenom *= invScaleXRationalDenom; if (isBilinearNew || isBicubicNew) { // Subtract 0.5 sxNum = 2 * sxNum - sxDenom; sxDenom *= 2; } // Separate the x source coordinate into integer and fractional part int srcXInt = Rational.floor(sxNum, sxDenom); long srcXFrac = sxNum % sxDenom; if (srcXInt < 0) { srcXFrac = sxDenom + srcXFrac; } // Normalize - Get a common denominator for the fracs of // src and invScaleX final long commonXDenom = sxDenom * invScaleXRationalDenom; srcXFrac *= invScaleXRationalDenom; final long newInvScaleXFrac = invScaleXFrac * sxDenom; // Store of the x positions for (int i = 0; i < dwidth; i++) { if (isBinary) { xpos[i] = srcXInt; } else { xpos[i] = (srcXInt - srcRectX) * srcPixelStride; } // Calculate the yfrac value if (isBilinearNew || isBicubicNew) { xfracvalues[i] = (int) (((1.0f * srcXFrac) / commonXDenom) * one); } // Move onto the next source pixel. // Add the integral part of invScaleX to the integral part // of srcX srcXInt += invScaleXInt; // Add the fractional part of invScaleX to the fractional part // of srcX srcXFrac += newInvScaleXFrac; // If the fractional part is now greater than equal to the // denominator, divide so as to reduce the numerator to be less // than the denominator and add the overflow to the integral part. if (srcXFrac >= commonXDenom) { srcXInt += 1; srcXFrac -= commonXDenom; } } // Store of the y positions for (int i = 0; i < dheight; i++) { // Calculate the source position in the source data array. if (isBinary) { ypos[i] = srcYInt; } else { ypos[i] = (srcYInt - srcRectY) * srcScanlineStride; } // If roi is present, the y position roi value is calculated if (useRoiAccessor) { if (isBinary) { yposRoi[i] = srcYInt; } else { yposRoi[i] = (srcYInt - srcRectY) * roiScanlineStride; } } // Calculate the yfrac value if (isBilinearNew || isBicubicNew) { yfracvalues[i] = (int) ((1.0f * srcYFrac / commonYDenom) * one); } // yfracvalues[i] = (int) ((1.0f *srcYFrac / commonYDenom) * one); // Move onto the next source pixel. // Add the integral part of invScaleY to the integral part // of srcY srcYInt += invScaleYInt; // Add the fractional part of invScaleY to the fractional part // of srcY srcYFrac += newInvScaleYFrac; // If the fractional part is now greater than equal to the // denominator, divide so as to reduce the numerator to be less // than the denominator and add the overflow to the integral part. if (srcYFrac >= commonYDenom) { srcYInt += 1; srcYFrac -= commonYDenom; } } } protected final void preComputePositionsFloat(Rectangle destRect, int srcRectX, int srcRectY, int srcPixelStride, int srcScanlineStride, int xpos[], int ypos[], float[] xfracvalues, float[] yfracvalues, int roiScanlineStride, int[] yposRoi) { // Destination Rectangle position final int dwidth = destRect.width; final int dheight = destRect.height; // Loop variables based on the destination rectangle to be calculated. final int dx = destRect.x; final int dy = destRect.y; // Initially the y source value is calculated by the destination value and then performing the inverse // scale operation on it. long syNum = dy, syDenom = 1; // Subtract the X translation factor sy -= transY syNum = syNum * transYRationalDenom - transYRationalNum * syDenom; syDenom *= transYRationalDenom; // Add 0.5 syNum = 2 * syNum + syDenom; syDenom *= 2; // Multply by invScaleX syNum *= invScaleYRationalNum; syDenom *= invScaleYRationalDenom; if (isBilinearNew || isBicubicNew) { // Subtract 0.5 syNum = 2 * syNum - syDenom; syDenom *= 2; } // Separate the y source coordinate into integer and fractional part int srcYInt = Rational.floor(syNum, syDenom); long srcYFrac = syNum % syDenom; if (srcYInt < 0) { srcYFrac = syDenom + srcYFrac; } // Normalize - Get a common denominator for the fracs of // src and invScaleY final long commonYDenom = syDenom * invScaleYRationalDenom; srcYFrac *= invScaleYRationalDenom; final long newInvScaleYFrac = invScaleYFrac * syDenom; // Initially the x source value is calculated by the destination value and then performing the inverse // scale operation on it. long sxNum = dx, sxDenom = 1; // Subtract the X translation factor sx -= transX sxNum = sxNum * transXRationalDenom - transXRationalNum * sxDenom; sxDenom *= transXRationalDenom; // Add 0.5 sxNum = 2 * sxNum + sxDenom; sxDenom *= 2; // Multply by invScaleX sxNum *= invScaleXRationalNum; sxDenom *= invScaleXRationalDenom; if (isBilinearNew || isBicubicNew) { // Subtract 0.5 sxNum = 2 * sxNum - sxDenom; sxDenom *= 2; } // Separate the x source coordinate into integer and fractional part int srcXInt = Rational.floor(sxNum, sxDenom); long srcXFrac = sxNum % sxDenom; if (srcXInt < 0) { srcXFrac = sxDenom + srcXFrac; } // Normalize - Get a common denominator for the fracs of // src and invScaleX final long commonXDenom = sxDenom * invScaleXRationalDenom; srcXFrac *= invScaleXRationalDenom; final long newInvScaleXFrac = invScaleXFrac * sxDenom; // Store of the x positions for (int i = 0; i < dwidth; i++) { xpos[i] = (srcXInt - srcRectX) * srcPixelStride; // Calculate the yfrac value if (isBilinearNew || isBicubicNew) { xfracvalues[i] = (1.0f * srcXFrac) / commonXDenom; } // xfracvalues[i] = (1.0f * srcXFrac) / commonXDenom; // Move onto the next source pixel. // Add the integral part of invScaleX to the integral part // of srcX srcXInt += invScaleXInt; // Add the fractional part of invScaleX to the fractional part // of srcX srcXFrac += newInvScaleXFrac; // If the fractional part is now greater than equal to the // denominator, divide so as to reduce the numerator to be less // than the denominator and add the overflow to the integral part. if (srcXFrac >= commonXDenom) { srcXInt += 1; srcXFrac -= commonXDenom; } } // Store of the y positions for (int i = 0; i < dheight; i++) { // Calculate the source position in the source data array. ypos[i] = (srcYInt - srcRectY) * srcScanlineStride; // If roi is present, the y position roi value is calculated if (useRoiAccessor) { yposRoi[i] = (srcYInt - srcRectY) * roiScanlineStride; } // Calculate the yfrac value if (isBilinearNew || isBicubicNew) { yfracvalues[i] = 1.0f * srcYFrac / commonYDenom; } // yfracvalues[i] = (float) srcYFrac / (float) commonYDenom; // Move onto the next source pixel. // Add the integral part of invScaleY to the integral part // of srcY srcYInt += invScaleYInt; // Add the fractional part of invScaleY to the fractional part // of srcY srcYFrac += newInvScaleYFrac; // If the fractional part is now greater than equal to the // denominator, divide so as to reduce the numerator to be less // than the denominator and add the overflow to the integral part. if (srcYFrac >= commonYDenom) { srcYInt += 1; srcYFrac -= commonYDenom; } } } private static Map<Object, Object> configHelper(RenderedImage source, Map<Object, Object> configuration, Interpolation interp) { Map<Object, Object> config = configuration; // If source image is binary and the interpolation is either nearest // or bilinear, do not expand if (ImageUtil.isBinary(source.getSampleModel()) && (interp == null || interp instanceof InterpolationNearest || interp instanceof InterpolationBilinear)) { // Set to false if (configuration == null) { config = new RenderingHints(JAI.KEY_REPLACE_INDEX_COLOR_MODEL, Boolean.FALSE); } else { // If the user specified a value for this hint, we don't // want to change that if (!config.containsKey(JAI.KEY_REPLACE_INDEX_COLOR_MODEL)) { RenderingHints hints = new RenderingHints(null); // This is effectively a clone of configuration hints.putAll(configuration); config = hints; config.put(JAI.KEY_REPLACE_INDEX_COLOR_MODEL, Boolean.TRUE); } } } return config; } /** * Constructs a <code>ScaleOpImage</code> from a <code>RenderedImage</code> source, an optional <code>BorderExtender</code>, x and y scale and * translation factors, and an <code>Interpolation</code> object. The image dimensions are determined by forward-mapping the source bounds, and * are passed to the superclass constructor by means of the <code>layout</code> parameter. Other fields of the layout are passed through * unchanged. If <code>layout</code> is <code>null</code>, a new <code>ImageLayout</code> will be constructor to hold the bounds information. * * Note that the scale factors are represented internally as Rational numbers in order to workaround inexact device specific representation of * floating point numbers. For instance the floating point number 1.2 is internally represented as 1.200001, which can throw the calculations off * during a forward/backward map. * * <p> * The Rational approximation is valid upto the sixth decimal place. * * @param layout an <code>ImageLayout</code> optionally containing the tile grid layout, <code>SampleModel</code>, and <code>ColorModel</code>, or * <code>null</code>. * @param source a <code>RenderedImage</code>. * @param configuration Configurable attributes of the image including configuration variables indexed by <code>RenderingHints.Key</code>s and * image properties indexed by <code>String</code>s or <code>CaselessStringKey</code>s. This is simply forwarded to the superclass * constructor. * @param cobbleSources a boolean indicating whether <code>computeRect</code> expects contiguous sources. * @param extender a <code>BorderExtender</code>, or <code>null</code>. * @param interp an <code>Interpolation</code> object to use for resampling. * @param scaleX scale factor along x axis. * @param scaleY scale factor along y axis. * @param transX translation factor along x axis. * @param transY translation factor along y axis. * * @throws IllegalArgumentException if <code>source</code> is <code>null</code>. * @throws IllegalArgumentException if combining the source bounds with the layout parameter results in negative output width or height. * * @since JAI 1.1 */ public ScaleOpImage(RenderedImage source, ImageLayout layout, Map configuration, boolean cobbleSources, BorderExtender extender, Interpolation interp, float scaleX, float scaleY, float transX, float transY, boolean useRoiAccessor, double[] backgroundValues) { super(vectorize(source), // vectorize() checks for null source. layoutHelper(source, scaleX, scaleY, transX, transY, interp, layout), configHelper( source, configuration, interp), cobbleSources, extender, interp, backgroundValues); this.scaleX = scaleX; this.scaleY = scaleY; this.transX = transX; this.transY = transY; // Represent the scale factors as Rational numbers. // Since a value of 1.2 is represented as 1.200001 which // throws the forward/backward mapping in certain situations. // Convert the scale and translation factors to Rational numbers this.scaleXRational = Rational.approximate(scaleX, rationalTolerance); this.scaleYRational = Rational.approximate(scaleY, rationalTolerance); this.scaleXRationalNum = (long) this.scaleXRational.num; this.scaleXRationalDenom = (long) this.scaleXRational.denom; this.scaleYRationalNum = (long) this.scaleYRational.num; this.scaleYRationalDenom = (long) this.scaleYRational.denom; this.transXRational = Rational.approximate(transX, rationalTolerance); this.transYRational = Rational.approximate(transY, rationalTolerance); this.transXRationalNum = (long) this.transXRational.num; this.transXRationalDenom = (long) this.transXRational.denom; this.transYRationalNum = (long) this.transYRational.num; this.transYRationalDenom = (long) this.transYRational.denom; // Inverse scale factors as Rationals invScaleXRational = new Rational(scaleXRational); invScaleXRational.invert(); invScaleYRational = new Rational(scaleYRational); invScaleYRational.invert(); invScaleXRationalNum = invScaleXRational.num; invScaleXRationalDenom = invScaleXRational.denom; invScaleYRationalNum = invScaleYRational.num; invScaleYRationalDenom = invScaleYRational.denom; lpad = interp.getLeftPadding(); rpad = interp.getRightPadding(); tpad = interp.getTopPadding(); bpad = interp.getBottomPadding(); if (extender == null) { // Get the source dimensions int x0 = source.getMinX(); int y0 = source.getMinY(); int w = source.getWidth(); int h = source.getHeight(); // The first source pixel (x0, y0) long dx0Num, dx0Denom, dy0Num, dy0Denom; // The first pixel (x1, y1) that is just outside the source long dx1Num, dx1Denom, dy1Num, dy1Denom; if (interp instanceof InterpolationNearest) { // First point inside the source dx0Num = x0; dx0Denom = 1; dy0Num = y0; dy0Denom = 1; // First point outside source // for nearest, x1 = x0 + w, y1 = y0 + h // since anything >= a but < (a+1) maps to a for nearest // Equivalent to float d_x1 = x0 + w dx1Num = x0 + w; dx1Denom = 1; // Equivalent to float d_y1 = y0 + h dy1Num = y0 + h; dy1Denom = 1; } else { // First point inside the source dx0Num = 2 * x0 + 1; // x0 + 0.5 dx0Denom = 2; dy0Num = 2 * y0 + 1; // y0 + 0.5 dy0Denom = 2; // for other interpolations, x1 = x0+w+0.5, y1 = y0+h+0.5 // as derived in the formulae derivation above. dx1Num = 2 * x0 + 2 * w + 1; dx1Denom = 2; dy1Num = 2 * y0 + 2 * h + 1; dy1Denom = 2; // Equivalent to x0 += lpad; dx0Num += dx0Denom * lpad; // Equivalent to y0 += tpad; dy0Num += dy0Denom * tpad; // Equivalent to x1 -= rpad; dx1Num -= dx1Denom * rpad; // Equivalent to y1 += bpad; dy1Num -= dy1Denom * bpad; } // Forward map the first and last source points // Equivalent to float d_x0 = x0 * scaleX; dx0Num *= scaleXRationalNum; dx0Denom *= scaleXRationalDenom; // Add the X translation factor d_x0 += transX dx0Num = dx0Num * transXRationalDenom + transXRationalNum * dx0Denom; dx0Denom *= transXRationalDenom; // Equivalent to float d_y0 = y0 * scaleY; dy0Num *= scaleYRationalNum; dy0Denom *= scaleYRationalDenom; // Add the Y translation factor, float d_y0 += transY dy0Num = dy0Num * transYRationalDenom + transYRationalNum * dy0Denom; dy0Denom *= transYRationalDenom; // Equivalent to float d_x1 = x1 * scaleX; dx1Num *= scaleXRationalNum; dx1Denom *= scaleXRationalDenom; // Add the X translation factor d_x1 += transX dx1Num = dx1Num * transXRationalDenom + transXRationalNum * dx1Denom; dx1Denom *= transXRationalDenom; // Equivalent to float d_y1 = y1 * scaleY; dy1Num *= scaleYRationalNum; dy1Denom *= scaleYRationalDenom; // Add the Y translation factor, float d_y1 += transY dy1Num = dy1Num * transYRationalDenom + transYRationalNum * dy1Denom; dy1Denom *= transYRationalDenom; // Get the integral coordinates int l_x0, l_y0, l_x1, l_y1; // Subtract 0.5 from dx0, dy0 dx0Num = 2 * dx0Num - dx0Denom; dx0Denom *= 2; dy0Num = 2 * dy0Num - dy0Denom; dy0Denom *= 2; l_x0 = Rational.ceil(dx0Num, dx0Denom); l_y0 = Rational.ceil(dy0Num, dy0Denom); // Subtract 0.5 from dx1, dy1 dx1Num = 2 * dx1Num - dx1Denom; dx1Denom *= 2; dy1Num = 2 * dy1Num - dy1Denom; dy1Denom *= 2; l_x1 = (int) Rational.floor(dx1Num, dx1Denom); // l_x1 must be less than but not equal to (dx1Num/dx1Denom) if ((l_x1 * dx1Denom) == dx1Num) { l_x1 -= 1; } l_y1 = (int) Rational.floor(dy1Num, dy1Denom); if (l_y1 * dy1Denom == dy1Num) { l_y1 -= 1; } computableBounds = new Rectangle(l_x0, l_y0, (l_x1 - l_x0 + 1), (l_y1 - l_y0 + 1)); } else { // If extender is present we can write the entire destination. computableBounds = getBounds(); // Padding of the input image in order to avoid the call of the getExtendedData() method. // Extend the Source image ParameterBlock pb = new ParameterBlock(); pb.setSource(source, 0); int leftPadding = lpad; int topPadding = tpad; if (interp instanceof InterpolationBilinear || interp instanceof InterpolationBicubic) { // add an extrapixel for left and top padding since the border extender will fill them // with zero otherwise leftPadding++; topPadding++; } pb.set(leftPadding, 0); pb.set(rpad, 1); pb.set(topPadding, 2); pb.set(bpad, 3); pb.set(extender, 4); extendedIMG = JAI.create("border", pb); } // SG Retrieve the rendered source image and its ROI. Object property = source.getProperty("ROI"); if (property instanceof ROI) { srcROI = (ROI) property; srcROIImage = srcROI.getAsImage(); // FIXME can we use smaller bounds here? roiRect = new Rectangle(srcROIImage.getMinX() - lpad, srcROIImage.getMinY() - tpad, srcROIImage.getWidth() + lpad + rpad, srcROIImage.getHeight() + tpad + bpad); // Padding of the input ROI image in order to avoid the call of the getExtendedData() method // Calculate the padding between the ROI and the source image padded roiBounds = srcROIImage.getBounds(); Rectangle srcRect = new Rectangle(source.getMinX() - lpad , source.getMinY() - tpad, source.getWidth() + lpad + rpad, source.getHeight() + tpad + bpad); int deltaX0 = (roiBounds.x - srcRect.x); int leftP = deltaX0 > 0 ? deltaX0 : 0; int deltaY0 = (roiBounds.y - srcRect.y); int topP = deltaY0 > 0 ? deltaY0 : 0; int deltaX1 = (srcRect.x + srcRect.width - roiBounds.x - roiBounds.width); int rightP = deltaX1 > 0 ? deltaX1 : 0; int deltaY1 = (srcRect.y + srcRect.height - roiBounds.y - roiBounds.height); int bottomP = deltaY1 > 0 ? deltaY1 : 0; // Extend the ROI image ParameterBlock pb = new ParameterBlock(); pb.setSource(srcROIImage, 0); pb.set(leftP, 0); pb.set(rightP, 1); pb.set(topP, 2); pb.set(bottomP, 3); pb.set(roiExtender, 4); srcROIImgExt = JAI.create("border", pb); hasROI = true; this.useRoiAccessor = useRoiAccessor; } else { srcROI = null; srcROIImage = null; roiBounds = null; hasROI = false; } } /** * Computes the position in the specified source that best matches the supplied destination image position. * * <p> * The implementation in this class returns the value of <code>pt</code> in the following code snippet: * * <pre> * Point2D pt = (Point2D) destPt.clone(); * pt.setLocation((destPt.getX() - transX + 0.5) / scaleX - 0.5, (destPt.getY() - transY + 0.5) * / scaleY - 0.5); * </pre> * * Subclasses requiring different behavior should override this method. * </p> * * @param destPt the position in destination image coordinates to map to source image coordinates. * @param sourceIndex the index of the source image. * * @return a <code>Point2D</code> of the same class as <code>destPt</code>. * * @throws IllegalArgumentException if <code>destPt</code> is <code>null</code>. * @throws IndexOutOfBoundsException if <code>sourceIndex</code> is non-zero. * * @since JAI 1.1.2 */ public Point2D mapDestPoint(Point2D destPt, int sourceIndex) { if (destPt == null) { throw new IllegalArgumentException(JaiI18N.getString("Generic0")); } else if (sourceIndex != 0) { throw new IndexOutOfBoundsException(JaiI18N.getString("Generic1")); } Point2D pt = (Point2D) destPt.clone(); pt.setLocation((destPt.getX() - transX + 0.5) / scaleX - 0.5, (destPt.getY() - transY + 0.5) / scaleY - 0.5); return pt; } /** * Computes the position in the destination that best matches the supplied source image position. * * <p> * The implementation in this class returns the value of <code>pt</code> in the following code snippet: * * <pre> * Point2D pt = (Point2D) sourcePt.clone(); * pt.setLocation(scaleX * (sourcePt.getX() + 0.5) + transX - 0.5, scaleY * (sourcePt.getY() + 0.5) * + transY - 0.5); * </pre> * * Subclasses requiring different behavior should override this method. * </p> * * @param sourcePt the position in source image coordinates to map to destination image coordinates. * @param sourceIndex the index of the source image. * * @return a <code>Point2D</code> of the same class as <code>sourcePt</code>. * * @throws IllegalArgumentException if <code>sourcePt</code> is <code>null</code>. * @throws IndexOutOfBoundsException if <code>sourceIndex</code> is non-zero. * * @since JAI 1.1.2 */ public Point2D mapSourcePoint(Point2D sourcePt, int sourceIndex) { if (sourcePt == null) { throw new IllegalArgumentException(JaiI18N.getString("Generic0")); } else if (sourceIndex != 0) { throw new IndexOutOfBoundsException(JaiI18N.getString("Generic1")); } Point2D pt = (Point2D) sourcePt.clone(); pt.setLocation(scaleX * (sourcePt.getX() + 0.5) + transX - 0.5, scaleY * (sourcePt.getY() + 0.5) + transY - 0.5); return pt; } /** * Returns the minimum bounding box of the region of the destination to which a particular <code>Rectangle</code> of the specified source will be * mapped. * * @param sourceRect the <code>Rectangle</code> in source coordinates. * @param sourceIndex the index of the source image. * * @return a <code>Rectangle</code> indicating the destination bounding box, or <code>null</code> if the bounding box is unknown. * * @throws IllegalArgumentException if <code>sourceIndex</code> is negative or greater than the index of the last source. * @throws IllegalArgumentException if <code>sourceRect</code> is <code>null</code>. * * @since JAI 1.1 */ protected Rectangle forwardMapRect(Rectangle sourceRect, int sourceIndex) { if (sourceRect == null) { throw new IllegalArgumentException(JaiI18N.getString("Generic0")); } if (sourceIndex != 0) { throw new IllegalArgumentException(JaiI18N.getString("Generic1")); } // Get the source dimensions int x0 = sourceRect.x; int y0 = sourceRect.y; int w = sourceRect.width; int h = sourceRect.height; // Variables to represent the first pixel inside the destination. long dx0Num, dx0Denom, dy0Num, dy0Denom; // Variables to represent the last destination pixel. long dx1Num, dx1Denom, dy1Num, dy1Denom; if (interp instanceof InterpolationNearest) { // First point inside the source dx0Num = x0; dx0Denom = 1; dy0Num = y0; dy0Denom = 1; // First point outside source // for nearest, x1 = x0 + w, y1 = y0 + h // since anything >= a and < a+1 maps to a for nearest, since // we use floor to calculate the integral source position // Equivalent to float d_x1 = x0 + w dx1Num = x0 + w; dx1Denom = 1; // Equivalent to float d_y1 = y0 + h dy1Num = y0 + h; dy1Denom = 1; } else { // First point inside the source (x0 + 0.5, y0 + 0.5) dx0Num = 2 * x0 + 1; dx0Denom = 2; dy0Num = 2 * y0 + 1; dy0Denom = 2; // for other interpolations, x1 = x0 + w + 0.5, y1 = y0 + h + 0.5 // as derived in the formulae derivation above. dx1Num = 2 * x0 + 2 * w + 1; dx1Denom = 2; dy1Num = 2 * y0 + 2 * h + 1; dy1Denom = 2; } // Forward map first and last source positions // Equivalent to float d_x0 = x0 * scaleX; dx0Num = dx0Num * scaleXRationalNum; dx0Denom *= scaleXRationalDenom; // Equivalent to float d_y0 = y0 * scaleY; dy0Num = dy0Num * scaleYRationalNum; dy0Denom *= scaleYRationalDenom; // Equivalent to float d_x1 = x1 * scaleX; dx1Num = dx1Num * scaleXRationalNum; dx1Denom *= scaleXRationalDenom; // Equivalent to float d_y1 = y1 * scaleY; dy1Num = dy1Num * scaleYRationalNum; dy1Denom *= scaleYRationalDenom; // Add the translation factors. // Equivalent to float d_x0 += transX dx0Num = dx0Num * transXRationalDenom + transXRationalNum * dx0Denom; dx0Denom *= transXRationalDenom; // Equivalent to float d_y0 += transY dy0Num = dy0Num * transYRationalDenom + transYRationalNum * dy0Denom; dy0Denom *= transYRationalDenom; // Equivalent to float d_x1 += transX dx1Num = dx1Num * transXRationalDenom + transXRationalNum * dx1Denom; dx1Denom *= transXRationalDenom; // Equivalent to float d_y1 += transY dy1Num = dy1Num * transYRationalDenom + transYRationalNum * dy1Denom; dy1Denom *= transYRationalDenom; // Get the integral coordinates int l_x0, l_y0, l_x1, l_y1; // Subtract 0.5 from dx0, dy0 dx0Num = 2 * dx0Num - dx0Denom; dx0Denom *= 2; dy0Num = 2 * dy0Num - dy0Denom; dy0Denom *= 2; l_x0 = Rational.ceil(dx0Num, dx0Denom); l_y0 = Rational.ceil(dy0Num, dy0Denom); // Subtract 0.5 from dx1, dy1 dx1Num = 2 * dx1Num - dx1Denom; dx1Denom *= 2; dy1Num = 2 * dy1Num - dy1Denom; dy1Denom *= 2; l_x1 = (int) Rational.floor(dx1Num, dx1Denom); if ((l_x1 * dx1Denom) == dx1Num) { l_x1 -= 1; } l_y1 = (int) Rational.floor(dy1Num, dy1Denom); if ((l_y1 * dy1Denom) == dy1Num) { l_y1 -= 1; } return new Rectangle(l_x0, l_y0, (l_x1 - l_x0 + 1), (l_y1 - l_y0 + 1)); } /** * Returns the minimum bounding box of the region of the specified source to which a particular <code>Rectangle</code> of the destination will be * mapped. * * @param destRect the <code>Rectangle</code> in destination coordinates. * @param sourceIndex the index of the source image. * * @return a <code>Rectangle</code> indicating the source bounding box, or <code>null</code> if the bounding box is unknown. * * @throws IllegalArgumentException if <code>sourceIndex</code> is negative or greater than the index of the last source. * @throws IllegalArgumentException if <code>destRect</code> is <code>null</code>. * * @since JAI 1.1 */ protected Rectangle backwardMapRect(Rectangle destRect, int sourceIndex) { if (destRect == null) { throw new IllegalArgumentException(JaiI18N.getString("Generic0")); } if (sourceIndex != 0) { throw new IllegalArgumentException(JaiI18N.getString("Generic1")); } // Get the destination rectangle coordinates and dimensions int x0 = destRect.x; int y0 = destRect.y; int w = destRect.width; int h = destRect.height; // Variables that will eventually hold the source pixel // positions which are the result of the backward map long sx0Num, sx0Denom, sy0Num, sy0Denom; // First destination point that will be backward mapped // will be dx0 + 0.5, dy0 + 0.5 sx0Num = (x0 * 2 + 1); sx0Denom = 2; sy0Num = (y0 * 2 + 1); sy0Denom = 2; // The last destination pixel to be backward mapped will be // dx0 + w - 1 + 0.5, dy0 + h - 1 + 0.5 i.e. // dx0 + w - 0.5, dy0 + h - 0.5 long sx1Num, sx1Denom, sy1Num, sy1Denom; // Equivalent to float sx1 = dx0 + dw - 0.5; sx1Num = 2 * x0 + 2 * w - 1; sx1Denom = 2; // Equivalent to float sy1 = dy0 + dh - 0.5; sy1Num = 2 * y0 + 2 * h - 1; sy1Denom = 2; // Subtract the translation factors. sx0Num = sx0Num * transXRationalDenom - transXRationalNum * sx0Denom; sx0Denom *= transXRationalDenom; sy0Num = sy0Num * transYRationalDenom - transYRationalNum * sy0Denom; sy0Denom *= transYRationalDenom; sx1Num = sx1Num * transXRationalDenom - transXRationalNum * sx1Denom; sx1Denom *= transXRationalDenom; sy1Num = sy1Num * transYRationalDenom - transYRationalNum * sy1Denom; sy1Denom *= transYRationalDenom; // Backward map both the destination positions // Equivalent to float sx0 = x0 / scaleX; sx0Num *= invScaleXRationalNum; sx0Denom *= invScaleXRationalDenom; sy0Num *= invScaleYRationalNum; sy0Denom *= invScaleYRationalDenom; sx1Num *= invScaleXRationalNum; sx1Denom *= invScaleXRationalDenom; sy1Num *= invScaleYRationalNum; sy1Denom *= invScaleYRationalDenom; int s_x0 = 0, s_y0 = 0, s_x1 = 0, s_y1 = 0; if (interp instanceof InterpolationNearest) { // Floor sx0, sy0 s_x0 = Rational.floor(sx0Num, sx0Denom); s_y0 = Rational.floor(sy0Num, sy0Denom); // Equivalent to (int)Math.floor(sx1) s_x1 = Rational.floor(sx1Num, sx1Denom); // Equivalent to (int)Math.floor(sy1) s_y1 = Rational.floor(sy1Num, sy1Denom); } else { // For all other interpolations // Equivalent to (int) Math.floor(sx0 - 0.5) s_x0 = Rational.floor(2 * sx0Num - sx0Denom, 2 * sx0Denom); // Equivalent to (int) Math.floor(sy0 - 0.5) s_y0 = Rational.floor(2 * sy0Num - sy0Denom, 2 * sy0Denom); // Calculate the last source point s_x1 = Rational.floor(2 * sx1Num - sx1Denom, 2 * sx1Denom); // Equivalent to (int)Math.ceil(sy1 - 0.5) s_y1 = Rational.floor(2 * sy1Num - sy1Denom, 2 * sy1Denom); } return new Rectangle(s_x0, s_y0, (s_x1 - s_x0 + 1), (s_y1 - s_y0 + 1)); } /** * Computes a tile. If source cobbling was requested at construction time, the source tile boundaries are overlayed onto the destination, cobbling * is performed for areas that intersect multiple source tiles, and <code>computeRect(Raster[], WritableRaster, Rectangle)</code> is called for * each of the resulting regions. Otherwise, <code>computeRect(PlanarImage[], WritableRaster, * Rectangle)</code> is called once to compute the entire active area of the tile. * * <p> * The image bounds may be larger than the bounds of the source image. In this case, samples for which there are no corresponding sources are set * to zero. * * <p> * The following steps are performed in order to compute the tile: * <ul> * <li>The destination tile is backward mapped to compute the needed source. * <li>This source is then split on tile boundaries to produce rectangles that do not cross tile boundaries. * <li>These source rectangles are then forward mapped to produce destination rectangles, and the computeRect method is called for each * corresponding pair of source and destination rectangles. * <li>For higher order interpolations, some source cobbling across tile boundaries does occur. * </ul> * * @param tileX The X index of the tile. * @param tileY The Y index of the tile. * * @return The tile as a <code>Raster</code>. */ public Raster computeTile(int tileX, int tileY) { if (!cobbleSources) { return super.computeTile(tileX, tileY); } // X and Y coordinate of the pixel pixel of the tile. int orgX = tileXToX(tileX); int orgY = tileYToY(tileY); // Create a new WritableRaster to represent this tile. WritableRaster dest = createWritableRaster(sampleModel, new Point(orgX, orgY)); Rectangle rect = new Rectangle(orgX, orgY, tileWidth, tileHeight); // Clip dest rectangle against the part of the destination // rectangle that can be written. Rectangle destRect = rect.intersection(computableBounds); if ((destRect.width <= 0) || (destRect.height <= 0)) { // If empty rectangle, return empty tile. return dest; } // Get the source rectangle required to compute the destRect Rectangle srcRect = mapDestRect(destRect, 0); Raster[] sources = new Raster[1]; // Split the source on tile boundaries. // Get the new pairs of src & dest Rectangles // The tileWidth and tileHeight of the source image // may differ from this tileWidth and tileHeight. PlanarImage source0 = getSourceImage(0); IntegerSequence srcXSplits = new IntegerSequence(); IntegerSequence srcYSplits = new IntegerSequence(); source0.getSplits(srcXSplits, srcYSplits, srcRect); // Note that the getExtendedData() method is not called because the input images are padded. // For each image there is a check if the rectangle is contained inside the source image; // if this not happen, the data is taken from the padded image. if (srcXSplits.getNumElements() == 1 && srcYSplits.getNumElements() == 1) { // If the source is fully contained within // a tile there is no need to split it any further. if (extender == null) { sources[0] = source0.getData(srcRect); } else { if(source0.getBounds().contains(srcRect)){ sources[0] = source0.getData(srcRect); }else{ sources[0] = extendedIMG.getData(srcRect); } } // Compute the destination tile. computeRect(sources, dest, destRect); } else { // Source Rect straddles 2 or more tiles // Get Source Tilewidth & height int srcTileWidth = source0.getTileWidth(); int srcTileHeight = source0.getTileHeight(); srcYSplits.startEnumeration(); while (srcYSplits.hasMoreElements()) { // Along Y TileBoundaries int ysplit = srcYSplits.nextElement(); srcXSplits.startEnumeration(); while (srcXSplits.hasMoreElements()) { // Along X TileBoundaries int xsplit = srcXSplits.nextElement(); // Construct a pseudo tile for intersection purposes Rectangle srcTile = new Rectangle(xsplit, ysplit, srcTileWidth, srcTileHeight); // Intersect the tile with the source Rectangle Rectangle newSrcRect = srcRect.intersection(srcTile); // // The new source rect could be of size less than or equal // to the interpolation kernel dimensions. In which case // the forward map produces null destination rectangles. // Hence we need to deal with these cases in the manner // implemented below (grow the source before the map. This // would result in source cobbling). Not an issue for // Nearest-Neighbour. // if (!(interp instanceof InterpolationNearest)) { if (newSrcRect.width <= interp.getWidth()) { // // Need to forward map this source rectangle. // Since we need a minimum of 2 * (lpad + rpad + 1) // in order to process, we contsruct a source // rectangle of that size, forward map and then // process the resulting destination rectangle. // Rectangle wSrcRect = new Rectangle(); Rectangle wDestRect; wSrcRect.x = newSrcRect.x; wSrcRect.y = newSrcRect.y - tpad - 1; wSrcRect.width = 2 * (lpad + rpad + 1); wSrcRect.height = newSrcRect.height + bpad + tpad + 2; wSrcRect = wSrcRect.intersection(source0.getBounds()); wDestRect = mapSourceRect(wSrcRect, 0); // // Make sure this destination rectangle is // within the bounds of our original writable // destination rectangle // wDestRect = wDestRect.intersection(destRect); if ((wDestRect.width > 0) && (wDestRect.height > 0)) { // Do the operations with these new rectangles if (extender == null) { sources[0] = source0.getData(wSrcRect); } else { if(source0.getBounds().contains(srcRect)){ sources[0] = source0.getData(srcRect); } else { sources[0] = extendedIMG.getData(srcRect); } } // Compute the destination tile. computeRect(sources, dest, wDestRect); } } if (newSrcRect.height <= interp.getHeight()) { // // Need to forward map this source rectangle. // Since we need a minimum of 2 * (tpad + bpad + 1) // in order to process, we create a source // rectangle of that size, forward map and then // process the resulting destinaltion rectangle // Rectangle hSrcRect = new Rectangle(); Rectangle hDestRect; hSrcRect.x = newSrcRect.x - lpad - 1; hSrcRect.y = newSrcRect.y; hSrcRect.width = newSrcRect.width + lpad + rpad + 2; hSrcRect.height = 2 * (tpad + bpad + 1); hSrcRect = hSrcRect.intersection(source0.getBounds()); hDestRect = mapSourceRect(hSrcRect, 0); // // Make sure this destination rectangle is // within the bounds of our original writable // destination rectangle // hDestRect = hDestRect.intersection(destRect); if ((hDestRect.width > 0) && (hDestRect.height > 0)) { // Do the operations with these new rectangles if (extender == null) { sources[0] = source0.getData(hSrcRect); } else { if(source0.getBounds().contains(srcRect)){ sources[0] = source0.getData(srcRect); }else{ sources[0] = extendedIMG.getData(srcRect); } } // Compute the destination tile. computeRect(sources, dest, hDestRect); } } } // Process source rectangle if ((newSrcRect.width > 0) && (newSrcRect.height > 0)) { // Forward map this source rectangle // to get the destination rectangle Rectangle newDestRect = mapSourceRect(newSrcRect, 0); // Make sure this destination rectangle is // within the bounds of our original writable // destination rectangle newDestRect = newDestRect.intersection(destRect); if ((newDestRect.width > 0) && (newDestRect.height > 0)) { // Do the operations with these new rectangles if (extender == null) { sources[0] = source0.getData(newSrcRect); } else { if(source0.getBounds().contains(srcRect)){ sources[0] = source0.getData(srcRect); }else{ sources[0] = extendedIMG.getData(srcRect); } } // Compute the destination tile. computeRect(sources, dest, newDestRect); } // // Since mapSourceRect (forward map) shrinks the // source rectangle before the map, there are areas // of this rectangle which never get mapped. // // These occur at the tile boundaries between // rectangles. The following algorithm handles // these edge conditions. // // The cases : // Right edge // Bottom edge // Lower Right Corner // if (!(interp instanceof InterpolationNearest)) { Rectangle RTSrcRect = new Rectangle(); Rectangle RTDestRect; // Right Edge RTSrcRect.x = newSrcRect.x + newSrcRect.width - 1 - rpad - lpad; RTSrcRect.y = newSrcRect.y; // // The amount of src not used from the end of // the first tile is rpad + 0.5. The amount // not used from the beginning of the next tile // is lpad + 0.5. Since we cannot start mapping // at 0.5, we need to get the area of the half // pixel on both sides. So we get another 0,5 // from both sides. In total (rpad + 0.5 + // 0.5) + (lpad + 0.5 + 0.5) // Since mapSourceRect subtracts rpad + 0.5 and // lpad + 0.5 from the source before the // forward map, we need to add that in. // RTSrcRect.width = 2 * (lpad + rpad + 1); RTSrcRect.height = newSrcRect.height; RTDestRect = mapSourceRect(RTSrcRect, 0); // Clip this against the whole destrect RTDestRect = RTDestRect.intersection(destRect); // RTSrcRect may be out of image bounds; // map one more time RTSrcRect = mapDestRect(RTDestRect, 0); if (RTDestRect.width > 0 && RTDestRect.height > 0) { // Do the operations with these new rectangles if (extender == null) { sources[0] = source0.getData(RTSrcRect); } else { if(source0.getBounds().contains(srcRect)){ sources[0] = source0.getData(srcRect); }else{ sources[0] = extendedIMG.getData(srcRect); } } // Compute the destination tile. computeRect(sources, dest, RTDestRect); } // Bottom Edge Rectangle BTSrcRect = new Rectangle(); Rectangle BTDestRect; BTSrcRect.x = newSrcRect.x; BTSrcRect.y = newSrcRect.y + newSrcRect.height - 1 - bpad - tpad; // // The amount of src not used from the end of // the first tile is tpad + 0.5. The amount // not used from the beginning of the next tile // is bpad + 0.5. Since we cannot start mapping // at 0.5, we need to get the area of the half // pixel on both sides. So we get another 0,5 // from both sides. In total (tpad + 0.5 + // 0.5) + (bpad + 0.5 + 0.5) // Since mapSourceRect subtracts tpad + 0.5 and // bpad + 0.5 from the source before the // forward map, we need to add that in. // BTSrcRect.width = newSrcRect.width; BTSrcRect.height = 2 * (tpad + bpad + 1); BTDestRect = mapSourceRect(BTSrcRect, 0); // Clip this against the whole destrect BTDestRect = BTDestRect.intersection(destRect); // BTSrcRect maybe out of bounds // map one more time BTSrcRect = mapDestRect(BTDestRect, 0); // end if (BTDestRect.width > 0 && BTDestRect.height > 0) { // Do the operations with these new rectangles if (extender == null) { sources[0] = source0.getData(BTSrcRect); } else { if(source0.getBounds().contains(srcRect)){ sources[0] = source0.getData(srcRect); }else{ sources[0] = extendedIMG.getData(srcRect); } } // Compute the destination tile. computeRect(sources, dest, BTDestRect); } // Lower Right Area Rectangle LRTSrcRect = new Rectangle(); Rectangle LRTDestRect; LRTSrcRect.x = newSrcRect.x + newSrcRect.width - 1 - rpad - lpad; LRTSrcRect.y = newSrcRect.y + newSrcRect.height - 1 - bpad - tpad; // Comment forthcoming LRTSrcRect.width = 2 * (rpad + lpad + 1); LRTSrcRect.height = 2 * (tpad + bpad + 1); LRTDestRect = mapSourceRect(LRTSrcRect, 0); // Clip this against the whole destrect LRTDestRect = LRTDestRect.intersection(destRect); // LRTSrcRect may still be out of bounds LRTSrcRect = mapDestRect(LRTDestRect, 0); if (LRTDestRect.width > 0 && LRTDestRect.height > 0) { // Do the operations with these new rectangles if (extender == null) { sources[0] = source0.getData(LRTSrcRect); } else { if(source0.getBounds().contains(srcRect)){ sources[0] = source0.getData(srcRect); }else{ sources[0] = extendedIMG.getData(srcRect); } } // Compute the destination tile. computeRect(sources, dest, LRTDestRect); } } } } } } // Return the written destination raster return dest; } @Override public synchronized void dispose() { if (srcROIImage != null) { srcROIImage.dispose(); } if(srcROIImgExt != null) { srcROIImgExt.dispose(); } super.dispose(); } }
geosolutions-it/jai-ext
jt-scale/src/main/java/it/geosolutions/jaiext/scale/ScaleOpImage.java
Java
apache-2.0
73,146
/* * 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.sejda.sambox.encryption; import static java.util.Objects.nonNull; import static org.bouncycastle.util.Arrays.copyOf; import java.io.InputStream; import org.bouncycastle.crypto.BufferedBlockCipher; import org.bouncycastle.crypto.DataLengthException; import org.bouncycastle.crypto.InvalidCipherTextException; import org.bouncycastle.crypto.engines.AESFastEngine; import org.bouncycastle.crypto.io.CipherInputStream; import org.bouncycastle.crypto.modes.CBCBlockCipher; import org.bouncycastle.crypto.params.KeyParameter; import org.bouncycastle.crypto.params.ParametersWithIV; /** * AES implementation of a {@link EncryptionAlgorithmEngine} with no pudding * * @author Andrea Vacondio * */ class AESEngineNoPadding implements AESEncryptionAlgorithmEngine { private BufferedBlockCipher cipher; AESEngineNoPadding(BufferedBlockCipher cipher) { this.cipher = cipher; } @Override public InputStream encryptStream(InputStream data, byte[] key, byte[] iv) { init(key, iv); return new CipherInputStream(data, cipher); } @Override public InputStream encryptStream(InputStream data, byte[] key) { return encryptStream(data, key, null); } @Override public byte[] encryptBytes(byte[] data, byte[] key, byte[] iv) { init(key, iv); try { byte[] buf = new byte[cipher.getOutputSize(data.length)]; int len = cipher.processBytes(data, 0, data.length, buf, 0); len += cipher.doFinal(buf, len); return copyOf(buf, len); } catch (DataLengthException | IllegalStateException | InvalidCipherTextException e) { throw new EncryptionException(e); } } @Override public byte[] encryptBytes(byte[] data, byte[] key) { return encryptBytes(data, key, null); } private void init(byte[] key, byte[] iv) { cipher.reset(); if (nonNull(iv)) { cipher.init(true, new ParametersWithIV(new KeyParameter(key), iv)); } else { cipher.init(true, new KeyParameter(key)); } } /** * @return and instance of EncryptionAlgorithmEngine AES/CBC/NoPadding and no initialization vector */ static AESEngineNoPadding cbc() { return new AESEngineNoPadding( new BufferedBlockCipher(new CBCBlockCipher(new AESFastEngine()))); } /** * @return and instance of EncryptionAlgorithmEngine AES/ECB/NoPadding and no initialization vector */ static AESEngineNoPadding ecb() { return new AESEngineNoPadding(new BufferedBlockCipher(new AESFastEngine())); } }
torakiki/sambox
src/main/java/org/sejda/sambox/encryption/AESEngineNoPadding.java
Java
apache-2.0
3,537
package org.androidpn.laumanager; import android.net.Uri; public final class DBCONSTANTS { public static final String TYPE = ""; public final static String APP_TABLE = "AppInfo"; public final static String VIDEO_TABLE = "VideoInfo"; public final static String PIC_TABLE = "PicInfo"; public final static String TV_TABLE = "TVInfo"; public static final String DB_Name= "TVLauncherDB"; public static final String[] TABLES = new String[]{APP_TABLE, VIDEO_TABLE, PIC_TABLE, TV_TABLE}; public static final String APP_TYPE = "vnd.android.cursor.dir/" + APP_TABLE; public static final String APP_ITEM_TYPE = "vnd.android.cursor.item/" + APP_TABLE; public static final String VIDEO_TYPE = "vnd.android.cursor.dir/" + VIDEO_TABLE; public static final String VIDEO_ITEM_TYPE = "vnd.android.cursor.item/" + VIDEO_TABLE; public static final String TV_TYPE = "vnd.android.cursor.dir/" + TV_TABLE; public static final String TV_ITEM_TYPE = "vnd.android.cursor.item/" + TV_TABLE; public static final String PIC_TYPE = "vnd.android.cursor.dir/" + PIC_TABLE; public static final String PIC_ITEM_TYPE = "vnd.android.cursor.item/" + PIC_TABLE; public static final String AUTHORITY = "org.androidpn.laumanager.dbprovider"; public static final int APKS = 1; public static final int APK = 2; public static final int VIDEOS = 3; public static final int VIDEO = 4; public static final int TVS = 5; public static final int TV = 6; public static final int PICS = 7; public static final int PIC = 8; public static final Uri APK_NOIFY_URI = Uri.parse("content://" + DBCONSTANTS.AUTHORITY + "/" + DBCONSTANTS.APP_TABLE); public static final Uri VIDEO_NOIFY_URI = Uri.parse("content://" + DBCONSTANTS.AUTHORITY + "/" + DBCONSTANTS.VIDEO_TABLE); public static final Uri TV_NOIFY_URI = Uri.parse("content://" + DBCONSTANTS.AUTHORITY + "/" + DBCONSTANTS.TV_TABLE); public static final Uri PIC_NOIFY_URI = Uri.parse("content://" + DBCONSTANTS.AUTHORITY + "/" + DBCONSTANTS.PIC_TABLE); }
JackieFlower/androidpn-client1.2.1test
src/org/androidpn/laumanager/DBCONSTANTS.java
Java
apache-2.0
2,111
package cn.databird.dao; import cn.databird.base.BaseDao; /** * Created by 言溪 on 2016/10/28. */ public interface LoginDao extends BaseDao { }
beihua/DataBird
DataBird-JavaWeb/src/main/java/cn/databird/dao/LoginDao.java
Java
apache-2.0
151
package example.repo; import example.model.Customer1708; import java.util.List; import org.springframework.data.repository.CrudRepository; public interface Customer1708Repository extends CrudRepository<Customer1708, Long> { List<Customer1708> findByLastName(String lastName); }
spring-projects/spring-data-examples
jpa/deferred/src/main/java/example/repo/Customer1708Repository.java
Java
apache-2.0
284
/* * JFork Project * * 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 jfork.nproperty; import jfork.typecaster.TypeCaster; import jfork.typecaster.exception.IllegalTypeException; import java.io.*; import java.lang.reflect.*; import java.util.*; import java.util.regex.Matcher; import java.util.regex.Pattern; /** * Configuration parser parses given configuration file(s) and fills given object fields. * * It can be used like this:<br /><br /> * <pre> * {@literal @}Cfg * class ConfigMain * { * public static int SOME_CONFIGURATION_OPTION = 0; * * public ConfigMain() * { * ConfigParser.parse(this, "main.ini"); * } * }</pre> * * @author Nikita Sankov */ public class ConfigParser { private final static Pattern parametersPattern = Pattern.compile("\\$\\{([^}]*)\\}"); /** * Parses property set with using of NProperty annotations and string path to property source. * * @param object NProperty annotated object, that represents Java property storage. * @param path Path to properties file. * @throws InvocationTargetException Failed invoke some annotated method. * @throws NoSuchMethodException Appears on adding splitter properties to lists. * @throws InstantiationException When failed to create instance of an custom object. Such exception can appered when property field is of custom type. * @throws IllegalAccessException If NProperty tries access inaccessible entities in annotated object. * @throws IOException If configuration file does not exists or due to system IO errors. */ public static Properties parse(Object object, String path) throws InvocationTargetException, NoSuchMethodException, InstantiationException, IllegalAccessException, IOException { return parse(object, new File(path)); } /** * Parses XML property set with using of nProperty annotations and string path to property XML source. * Author - PointerRage. * * @param object NProperty annotated object, that represents Java property storage. * @param path Path to properties file. * @throws InvocationTargetException Failed invoke some annotated method. * @throws NoSuchMethodException Appears on adding splitter properties to lists. * @throws InstantiationException When failed to create instance of an custom object. Such exception can appered when property field is of custom type. * @throws IllegalAccessException If NProperty tries access inaccessible entities in annotated object. * @throws IOException If configuration file does not exists or due to system IO errors. */ public static Properties parseXml(Object object, String path) throws InvocationTargetException, NoSuchMethodException, InstantiationException, IllegalAccessException, IOException { return parseXml(object, new File(path)); } /** * Parses property set with using of NProperty annotations and File object referenced to property source. * * @param object NProperty annotated object, that represents Java property storage. * @param file File to read properties from. * @throws InvocationTargetException Failed invoke some annotated method. * @throws NoSuchMethodException Appears on adding splitter properties to lists. * @throws InstantiationException When failed to create instance of an custom object. Such exception can appered when property field is of custom type. * @throws IllegalAccessException If NProperty tries access inaccessible entities in annotated object. * @throws IOException If configuration file does not exists or due to system IO errors. */ public static Properties parse(Object object, File file) throws IOException, InvocationTargetException, NoSuchMethodException, InstantiationException, IllegalAccessException { Properties props; try (FileInputStream stream = new FileInputStream(file)) { props = parse(object, stream, file.getPath()); } return props; } /** * Parses XML property set with using of nProperty annotations and XML File object referenced to property source. * Author - PointerRage. * * @param object nProperty annotated object, that represents Java property storage. * @param file File to read properties from. * @throws InvocationTargetException Failed invoke some annotated method. * @throws NoSuchMethodException Appears on adding splitter properties to lists. * @throws InstantiationException When failed to create instance of an custom object. Such exception can appered when property field is of custom type. * @throws IllegalAccessException If NProperty tries access inaccessible entities in annotated object. * @throws IOException If configuration file does not exists or due to system IO errors. */ public static Properties parseXml(Object object, File file) throws IOException, InvocationTargetException, NoSuchMethodException, InstantiationException, IllegalAccessException { Properties props; try (FileInputStream stream = new FileInputStream(file)) { props = parseXml(object, stream, file.getPath()); } return props; } /** * Parses property set with using of NProperty annotations and using abstract input io stream (it can be a file, network or any other thing Java can provide within io streams). * * @param object NProperty annotated object, that represents Java property storage. * @param stream IO stream from properties will be read. * @param streamName Name of stream (this will be used instead of file name, because of using IO stream we cannot retrieve file name). * @throws InvocationTargetException Failed invoke some annotated method. * @throws NoSuchMethodException Appears on adding splitter properties to lists. * @throws InstantiationException When failed to create instance of an custom object. Such exception can appered when property field is of custom type. * @throws IllegalAccessException If NProperty tries access inaccessible entities in annotated object. * @throws IOException If configuration file does not exists or due to system IO errors. */ public static Properties parse(Object object, InputStream stream, String streamName) throws InvocationTargetException, NoSuchMethodException, InstantiationException, IllegalAccessException, IOException { Properties props = new Properties(); props.load(stream); return parse0(object, props, streamName); } /** * Parses XML property set with using of nProperty annotations and using abstract input XML io stream (it can be a file, network or any other thing Java can provide within io streams). * Author - PointerRage. * * @param object nProperty annotated object, that represents Java property storage. * @param stream IO stream from properties will be read. * @param streamName Name of stream (this will be used instead of file name, because of using IO stream we cannot retrieve file name). * @throws InvocationTargetException Failed invoke some annotated method. * @throws NoSuchMethodException Appears on adding splitter properties to lists. * @throws InstantiationException When failed to create instance of an custom object. Such exception can appered when property field is of custom type. * @throws IllegalAccessException If NProperty tries access inaccessible entities in annotated object. * @throws IOException If configuration file does not exists or due to system IO errors. */ public static Properties parseXml(Object object, InputStream stream, String streamName) throws InvocationTargetException, NoSuchMethodException, InstantiationException, IllegalAccessException, IOException { Properties props = new Properties(); props.loadFromXML(stream); return parse0(object, props, streamName); } /** * Parses property set with using of NProperty annotations and using abstract input io stream reader (it can be a file, network or any other thing Java can provide within io streams). * * @param object NProperty annotated object, that represents Java property storage. * @param reader IO stream reader. * @param streamName Name of stream (this will be used instead of file name, because of using IO stream we cannot retrieve file name). * @throws InvocationTargetException Failed invoke some annotated method. * @throws NoSuchMethodException Appears on adding splitter properties to lists. * @throws InstantiationException When failed to create instance of an custom object. Such exception can appered when property field is of custom type. * @throws IllegalAccessException If NProperty tries access inaccessible entities in annotated object. * @throws IOException If configuration file does not exists or due to system IO errors. */ public static Properties parse(Object object, Reader reader, String streamName) throws InvocationTargetException, NoSuchMethodException, InstantiationException, IllegalAccessException, IOException { Properties props = new Properties(); props.load(reader); return parse0(object, props, streamName); } /** * Parses property set with using of NProperty annotations. * * @param object NProperty annotated object, that represents Java property storage. * @param path Path to configuration file. * @throws IOException If configuration file does not exists or due to system IO errors. * @throws IllegalAccessException If NProperty tries access inaccessible entities in annotated object. * @throws InstantiationException When failed to create instance of an custom object. Such exception can appered when property field is of custom type. * @throws NoSuchMethodException Appears on adding splitter properties to lists. * @throws InvocationTargetException Failed invoke some annotated method. */ @SuppressWarnings("unchecked") private static Properties parse0(Object object, Properties props, String path) throws IOException, IllegalAccessException, InstantiationException, NoSuchMethodException, InvocationTargetException { boolean callEvents = object instanceof IPropertyListener; if (callEvents) ((IPropertyListener)object).onStart(path); boolean isClass = (object instanceof Class); boolean classAnnotationPresent; String prefix = null; boolean classAllowParameters = false; if (isClass) { classAnnotationPresent = ((Class)object).isAnnotationPresent(Cfg.class); if (classAnnotationPresent) { prefix = ((Cfg)((Class)object).getAnnotation(Cfg.class)).prefix(); classAllowParameters = ((Cfg)((Class)object).getAnnotation(Cfg.class)).parametrize(); } } else { classAnnotationPresent = object.getClass().isAnnotationPresent(Cfg.class); if (classAnnotationPresent) { prefix = object.getClass().getAnnotation(Cfg.class).prefix(); classAllowParameters = object.getClass().getAnnotation(Cfg.class).parametrize(); } } Field[] fields = (object instanceof Class) ? ((Class) object).getDeclaredFields() : object.getClass().getDeclaredFields(); for (Field field : fields) { // Find property name String name; boolean allowParameters = classAllowParameters; if (isClass && !Modifier.isStatic(field.getModifiers())) continue; if (field.isAnnotationPresent(Cfg.class)) { if (field.getAnnotation(Cfg.class).ignore()) continue; name = field.getAnnotation(Cfg.class).value(); if (!allowParameters) allowParameters = field.getAnnotation(Cfg.class).parametrize(); // If name is empty, we should try to take field name as property name if (name.isEmpty()) name = field.getName(); } else if (classAnnotationPresent) name = field.getName(); else continue; // Adding prefix if needed if (prefix != null && !prefix.isEmpty()) name = prefix.concat(name); boolean oldAccess = field.isAccessible(); field.setAccessible(true); if (props.containsKey(name)) { String propValue = props.getProperty(name); if (allowParameters) { boolean replacePlaceholders = false; while (true) { // Check for parameters in property value Matcher parametersMatcher = parametersPattern.matcher(propValue); boolean exit = true; while (parametersMatcher.find()) { String parameterPropertyName = parametersMatcher.group(1); if (!parameterPropertyName.isEmpty()) { exit = false; String parameterPropertyValue = props.containsKey(parameterPropertyName) ? props.getProperty(parameterPropertyName) : ""; propValue = propValue.replace(parametersMatcher.group(), parameterPropertyValue); } else if (!replacePlaceholders) { replacePlaceholders = true; } } if (exit) break; } if (replacePlaceholders) { propValue = propValue.replace("${}", "$"); } } // Native arrays if (field.getType().isArray()) { Class baseType = field.getType().getComponentType(); if (propValue != null) { String[] values = propValue.split(field.isAnnotationPresent(Cfg.class) ? field.getAnnotation(Cfg.class).splitter() : ";"); Object array = Array.newInstance(baseType, values.length); field.set(object, array); int index = 0; for (String value : values) { try { Array.set(array, index, TypeCaster.cast(baseType, value)); } catch (IllegalTypeException | NumberFormatException e) { if (callEvents) ((IPropertyListener)object).onInvalidPropertyCast(name, value); } ++index; } field.set(object, array); } } // Lists else if (field.getType().isAssignableFrom(List.class)) { if (field.get(object) == null) throw new NullPointerException("Cannot use null-object for parsing List splitter."); Class genericType = (Class)((ParameterizedType)field.getGenericType()).getActualTypeArguments()[0]; if (propValue != null) { String[] values = propValue.split(field.isAnnotationPresent(Cfg.class) ? field.getAnnotation(Cfg.class).splitter() : ";"); for (String value : values) { try { ((List<Object>)field.get(object)).add(TypeCaster.cast(genericType, value)); } catch (IllegalTypeException | NumberFormatException e) { if (callEvents) ((IPropertyListener)object).onInvalidPropertyCast(name, value); } } } } // Primary & standard types else { if (propValue != null) { // If it is known type - just cast it, else - create new instance of class is possible if (TypeCaster.isCastable(field)) { try { TypeCaster.cast(object, field, propValue); } catch (IllegalTypeException | NumberFormatException e) { if (callEvents) ((IPropertyListener)object).onInvalidPropertyCast(name, propValue); } } // Custom classes else { Constructor construct = field.getType().getDeclaredConstructor(String.class); boolean oldConstructAccess = construct.isAccessible(); construct.setAccessible(true); field.set(object, construct.newInstance(propValue)); construct.setAccessible(oldConstructAccess); } } } } else { if (object instanceof IPropertyListener) { ((IPropertyListener)object).onPropertyMiss(name); } } field.setAccessible(oldAccess); } // Methods Method[] methods = (object instanceof Class) ? ((Class) object).getDeclaredMethods() : object.getClass().getDeclaredMethods(); for (Method method : methods) { // Accumulate annotation info if (method.isAnnotationPresent(Cfg.class)) { String propName = method.getAnnotation(Cfg.class).value(); if (propName.isEmpty()) propName = method.getName(); if (!props.containsKey(propName)) { if (object instanceof IPropertyListener) { ((IPropertyListener)object).onPropertyMiss(propName); } continue; } if (method.getParameterTypes().length == 1) { String propValue = props.getProperty(propName); boolean oldAccess = method.isAccessible(); method.setAccessible(true); if (propValue != null) { try { method.invoke(object, TypeCaster.cast(method.getParameterTypes()[0], propValue)); } catch (IllegalTypeException | NumberFormatException | InvocationTargetException e) { if (callEvents) ((IPropertyListener)object).onInvalidPropertyCast(propName, propValue); } } else method.invoke(object, method.getParameterTypes()[0] == String.class ? propValue : (TypeCaster.cast(method.getParameterTypes()[0], propValue))); method.setAccessible(oldAccess); } } } if (callEvents) ((IPropertyListener)object).onDone(path); return props; } /** * Stores configuration fields to file with given path. * * @param object Object to get fields from. * @param path Path to file write to. * @throws IOException If any I/O error occurs. * @throws IllegalAccessException When failed to access objects' data. */ public static void store(Object object, String path) throws IOException, IllegalAccessException { store(object, new File(path)); } /** * Stores configuration fields in XML format to file with given path. * Author - PointerRage. * * @param object Object to get fields from. * @param path Path to file write to. * @throws IOException If any I/O error occurs. * @throws IllegalAccessException When failed to access objects' data. */ public static void storeXml(Object object, String path) throws IOException, IllegalAccessException { storeXml(object, new File(path)); } /** * Stores configuration fields to given file. * * @param object Object to get fields from. * @param file File descriptor to write to. * @throws IOException If any I/O error occurs. * @throws IllegalAccessException When failed to access objects' data. */ public static void store(Object object, File file) throws IOException, IllegalAccessException { try (OutputStream stream = new FileOutputStream(file)) { store(object, stream); } } /** * Stores configuration fields in XML format to given file. * Author - PointerRage. * * @param object Object to get fields from. * @param file File descriptor to write to. * @throws IOException If any I/O error occurs. * @throws IllegalAccessException When failed to access objects' data. */ public static void storeXml(Object object, File file) throws IOException, IllegalAccessException { try (OutputStream stream = new FileOutputStream(file)) { storeXml(object, stream); } } /** * Stores configuration fields to stream. * * @param object Object to get fields from. * @param stream Output stream to write to. * @throws IOException If any I/O error occurs. * @throws IllegalAccessException When failed to access objects' data. */ public static void store(Object object, OutputStream stream) throws IOException, IllegalAccessException { ConfigStoreFormatterIni formatter = new ConfigStoreFormatterIni(); store0(object, formatter); stream.write(formatter.generate().getBytes()); } /** * Stores configuration fields to stream in XML format. * Author - PointerRage. * * @param object Object to get fields from. * @param stream Output stream to write to. * @throws IOException If any I/O error occurs. * @throws IllegalAccessException When failed to access objects' data. */ public static void storeXml(Object object, OutputStream stream) throws IOException, IllegalAccessException { ConfigStoreFormatterXml formatter = new ConfigStoreFormatterXml(); store0(object, formatter); stream.write(formatter.generate().getBytes()); } /** * Stores configuration fields to stream. * * @param object Object to get fields from. * @param writer Writer interface to write to. * @throws IOException If any I/O error occurs. * @throws IllegalAccessException When failed to access objects' data. */ public static void store(Object object, Writer writer) throws IOException, IllegalAccessException { ConfigStoreFormatterIni formatter = new ConfigStoreFormatterIni(); store0(object, formatter); writer.write(formatter.generate()); } /** * Stores configuration fields to stream in XML format. * * @param object Object to get fields from. * @param writer Writer interface to write to. * @throws IOException If any I/O error occurs. * @throws IllegalAccessException When failed to access objects' data. */ public static void storeXml(Object object, Writer writer) throws IOException, IllegalAccessException { ConfigStoreFormatterXml formatter = new ConfigStoreFormatterXml(); store0(object, formatter); writer.write(formatter.generate()); } /** * Stores configuration fields to stream. * * @param object Object to get fields from. * @throws IOException If any I/O error occurs. * @throws IllegalAccessException When failed to access objects' data. */ private static void store0(Object object, IConfigStoreFormatter formatter) throws IOException, IllegalAccessException { boolean isClass = (object instanceof Class); boolean classAnnotationPresent; String prefix = null; if (isClass) { classAnnotationPresent = ((Class)object).isAnnotationPresent(Cfg.class); if (classAnnotationPresent) { prefix = ((Cfg)((Class)object).getAnnotation(Cfg.class)).prefix(); } } else { classAnnotationPresent = object.getClass().isAnnotationPresent(Cfg.class); if (classAnnotationPresent) { prefix = object.getClass().getAnnotation(Cfg.class).prefix(); } } Field[] fields = (object instanceof Class) ? ((Class) object).getDeclaredFields() : object.getClass().getDeclaredFields(); for (Field field : fields) { // Find property name String name, value; String splitter = ";"; if (isClass && !Modifier.isStatic(field.getModifiers())) continue; if (field.isAnnotationPresent(Cfg.class)) { if (field.getAnnotation(Cfg.class).ignore()) continue; name = field.getAnnotation(Cfg.class).value(); splitter = field.getAnnotation(Cfg.class).splitter(); // If name is empty, we should try to take field name as property name if (name.isEmpty()) name = field.getName(); } else if (classAnnotationPresent) name = field.getName(); else continue; // Adding prefix if needed if (prefix != null && !prefix.isEmpty()) name = prefix.concat(name); boolean oldAccess = field.isAccessible(); field.setAccessible(true); Object fieldValue = field.get(object); if (fieldValue != null && field.getType().isArray()) { StringBuilder builder = new StringBuilder(); for (int i = 0, j = Array.getLength(fieldValue); i < j; ++i) { builder.append(Array.get(fieldValue, i)); if (i < j - 1) builder.append(splitter); } value = builder.toString(); } else if (fieldValue != null && field.getType().isAssignableFrom(List.class)) { StringBuilder builder = new StringBuilder(); boolean isFirst = true; for (Object val : (List<?>)fieldValue) { if (isFirst) isFirst = false; else builder.append(splitter); builder.append(val); } value = builder.toString(); } else { value = String.valueOf(fieldValue); } formatter.addPair(name, value); field.setAccessible(oldAccess); } } }
Snarov/jfork
nProperty/src/jfork/nproperty/ConfigParser.java
Java
apache-2.0
24,863
/* * 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 brooklyn.util.internal.ssh.process; import static org.testng.Assert.assertTrue; import java.util.Arrays; import java.util.Map; import org.testng.Assert; import org.testng.annotations.Test; import brooklyn.util.config.ConfigBag; import brooklyn.util.internal.ssh.ShellToolAbstractTest; /** * Test the operation of the {@link ProcessTool} utility class. */ public class ProcessToolIntegrationTest extends ShellToolAbstractTest { @Override protected ProcessTool newUnregisteredTool(Map<String,?> flags) { return new ProcessTool(flags); } // ones here included as *non*-integration tests. must run on windows and linux. // (also includes integration tests from parent) @Test(groups="UNIX") public void testPortableCommand() throws Exception { String out = execScript("echo hello world"); assertTrue(out.contains("hello world"), "out="+out); } @Test(groups="Integration") public void testLoginShell() { // this detection scheme only works for commands; can't test whether it works for scripts without // requiring stuff in bash_profile / profile / etc, which gets hard to make portable; // it is nearly the same code path on the impl so this is probably enough final String LOGIN_SHELL_CHECK = "shopt -q login_shell && echo 'yes, login shell' || echo 'no, not login shell'"; ConfigBag config = ConfigBag.newInstance().configure(ProcessTool.PROP_NO_EXTRA_OUTPUT, true); String out; out = execCommands(config, Arrays.asList(LOGIN_SHELL_CHECK), null); Assert.assertEquals(out.trim(), "no, not login shell", "out = "+out); config.configure(ProcessTool.PROP_LOGIN_SHELL, true); out = execCommands(config, Arrays.asList(LOGIN_SHELL_CHECK), null); Assert.assertEquals(out.trim(), "yes, login shell", "out = "+out); } }
neykov/incubator-brooklyn
core/src/test/java/brooklyn/util/internal/ssh/process/ProcessToolIntegrationTest.java
Java
apache-2.0
2,726
/* * Copyright (C) 2014 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.android.settings.sim; import com.android.internal.telephony.IccCardConstants; import com.android.internal.telephony.TelephonyIntents; import com.android.settings.R; import com.android.settings.Settings.SimSettingsActivity; import com.mediatek.settings.UtilsExt; import com.mediatek.settings.cdma.CdmaUtils; import com.mediatek.settings.ext.ISettingsMiscExt; import android.app.NotificationManager; import android.app.PendingIntent; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.content.res.Resources; import android.provider.Settings; import android.support.v4.app.NotificationCompat; import android.telephony.SubscriptionInfo; import android.telephony.SubscriptionManager; import android.telephony.TelephonyManager; import android.util.Log; /// M: Add for CT 6M. import com.mediatek.settings.FeatureOption; import java.util.List; public class SimSelectNotification extends BroadcastReceiver { private static final String TAG = "SimSelectNotification"; private static final int NOTIFICATION_ID = 1; @Override public void onReceive(Context context, Intent intent) { /// M: add for auto sanity if (UtilsExt.shouldDisableForAutoSanity()) { return; } /// @} /// M: for [C2K 2 SIM Warning] @{ // can not listen to SIM_STATE_CHANGED because it happened even when SIM switch // (switch default data), in which case should not show the C2K 2 SIM warning // SIM_STATE_CHANGED is not exact, maybe ICC is ready or absent, // but SubscriptionController is not ready. List<SubscriptionInfo> subs = SubscriptionManager.from(context) .getActiveSubscriptionInfoList(); final int detectedType = intent.getIntExtra( SubscriptionManager.INTENT_KEY_DETECT_STATUS, 0); Log.d(TAG, "sub info update, subs = " + subs + ", type = " + detectedType); if (detectedType == SubscriptionManager.EXTRA_VALUE_NOCHANGE) { return; } if (subs != null && subs.size() > 1) { CdmaUtils.checkCdmaSimStatus(context, subs.size()); } /// @} final TelephonyManager telephonyManager = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE); final SubscriptionManager subscriptionManager = SubscriptionManager.from(context); final int numSlots = telephonyManager.getSimCount(); final boolean isInProvisioning = Settings.Global.getInt(context.getContentResolver(), Settings.Global.DEVICE_PROVISIONED, 0) == 0; // Do not create notifications on single SIM devices or when provisiong i.e. Setup Wizard. if (numSlots < 2 || isInProvisioning) { return; } // Cancel any previous notifications cancelNotification(context); // If sim state is not ABSENT or LOADED then ignore String simStatus = intent.getStringExtra(IccCardConstants.INTENT_KEY_ICC_STATE); if (!(IccCardConstants.INTENT_VALUE_ICC_ABSENT.equals(simStatus) || IccCardConstants.INTENT_VALUE_ICC_LOADED.equals(simStatus))) { Log.d(TAG, "sim state is not Absent or Loaded"); /// M: maybe ACTION_SUBINFO_RECORD_UPDATED is received, @{ // but ICC card don't loaded or absent /* return; */ /// @} } else { Log.d(TAG, "simstatus = " + simStatus); } int state; for (int i = 0; i < numSlots; i++) { state = telephonyManager.getSimState(i); if (!(state == TelephonyManager.SIM_STATE_ABSENT || state == TelephonyManager.SIM_STATE_READY || state == TelephonyManager.SIM_STATE_UNKNOWN)) { Log.d(TAG, "All sims not in valid state yet"); /// M: maybe ACTION_SUBINFO_RECORD_UPDATED is received, @{ // but ICC card don't loaded or absent /* return; */ /// @} } } List<SubscriptionInfo> sil = subscriptionManager.getActiveSubscriptionInfoList(); if (sil == null || sil.size() < 1) { Log.d(TAG, "Subscription list is empty"); return; } // Clear defaults for any subscriptions which no longer exist subscriptionManager.clearDefaultsForInactiveSubIds(); boolean dataSelected = SubscriptionManager.isUsableSubIdValue( SubscriptionManager.getDefaultDataSubId()); boolean smsSelected = SubscriptionManager.isUsableSubIdValue( SubscriptionManager.getDefaultSmsSubId()); // If data and sms defaults are selected, dont show notification (Calls default is optional) if (dataSelected && smsSelected) { Log.d(TAG, "Data & SMS default sims are selected. No notification"); return; } // Create a notification to tell the user that some defaults are missing createNotification(context); /// M: for plug-in and CT 6M if (!isSimDialogNeeded(context)) { return; } if (sil.size() == 1) { // If there is only one subscription, ask if user wants to use if for everything Intent newIntent = new Intent(context, SimDialogActivity.class); newIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); newIntent.putExtra(SimDialogActivity.DIALOG_TYPE_KEY, SimDialogActivity.PREFERRED_PICK); newIntent.putExtra(SimDialogActivity.PREFERRED_SIM, sil.get(0).getSimSlotIndex()); context.startActivity(newIntent); } else if (!dataSelected) { // If there are mulitple, ensure they pick default data Intent newIntent = new Intent(context, SimDialogActivity.class); newIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); newIntent.putExtra(SimDialogActivity.DIALOG_TYPE_KEY, SimDialogActivity.DATA_PICK); context.startActivity(newIntent); } } private void createNotification(Context context){ final Resources resources = context.getResources(); NotificationCompat.Builder builder = new NotificationCompat.Builder(context) .setSmallIcon(R.drawable.ic_sim_card_alert_white_48dp) .setColor(context.getColor(R.color.sim_noitification)) .setContentTitle(resources.getString(R.string.sim_notification_title)) .setContentText(resources.getString(R.string.sim_notification_summary)); /// M: for plug-in customizeSimDisplay(context, builder); Intent resultIntent = new Intent(context, SimSettingsActivity.class); resultIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); PendingIntent resultPendingIntent = PendingIntent.getActivity(context, 0, resultIntent, PendingIntent.FLAG_CANCEL_CURRENT); builder.setContentIntent(resultPendingIntent); NotificationManager notificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE); notificationManager.notify(NOTIFICATION_ID, builder.build()); } public static void cancelNotification(Context context) { NotificationManager notificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE); notificationManager.cancel(NOTIFICATION_ID); } ///---------------------------------------MTK------------------------------------------------- /** * only for plug-in, change "SIM" to "UIM/SIM". * @param context the context. * @param builder the notification builder. */ private void customizeSimDisplay( Context context, NotificationCompat.Builder builder) { Resources resources = context.getResources(); String title = resources.getString(R.string.sim_notification_title); String text = resources.getString(R.string.sim_notification_summary); ISettingsMiscExt miscExt = UtilsExt.getMiscPlugin(context); title = miscExt.customizeSimDisplayString( title, SubscriptionManager.INVALID_SUBSCRIPTION_ID); text = miscExt.customizeSimDisplayString( text, SubscriptionManager.INVALID_SUBSCRIPTION_ID); builder.setContentTitle(title); builder.setContentText(text); } /** * add for plug-in and CT 6M. * whether allowed show data pick dailog and preferred sim dialog. */ private boolean isSimDialogNeeded(Context context) { boolean isNeeded = false; if (!FeatureOption.MTK_CT6M_SUPPORT) { isNeeded = UtilsExt.getSimManagmentExtPlugin(context).isSimDialogNeeded(); } return isNeeded; } }
miswenwen/My_bird_work
Bird_work/我的项目/Settings/src/com/android/settings/sim/SimSelectNotification.java
Java
apache-2.0
9,698
package org.apache.helix; /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.Map; import org.apache.helix.mock.MockBaseDataAccessor; import org.apache.helix.model.LiveInstance; import org.apache.helix.model.MaintenanceSignal; import org.apache.helix.model.Message; import org.apache.helix.model.PauseSignal; import org.apache.helix.model.StateModelDefinition; import org.apache.helix.zookeeper.datamodel.ZNRecord; import org.apache.helix.zookeeper.datamodel.ZNRecordUpdater; import org.apache.helix.zookeeper.zkclient.DataUpdater; import org.apache.helix.zookeeper.zkclient.exception.ZkNoNodeException; import org.apache.zookeeper.data.Stat; public class MockAccessor implements HelixDataAccessor { private final String _clusterName; //Map<String, ZNRecord> data = new HashMap<String, ZNRecord>(); private final PropertyKey.Builder _propertyKeyBuilder; private BaseDataAccessor _baseDataAccessor = new MockBaseDataAccessor(); public MockAccessor() { this("testCluster-" + Math.random() * 10000 % 999); } public MockAccessor(String clusterName) { _clusterName = clusterName; _propertyKeyBuilder = new PropertyKey.Builder(_clusterName); } @Override public boolean createStateModelDef(StateModelDefinition stateModelDef) { return false; } @Override public boolean createControllerMessage(Message message) { return false; } @Override public boolean createControllerLeader(LiveInstance leader) { return false; } @Override public boolean createPause(PauseSignal pauseSignal) { return false; } @Override public boolean createMaintenance(MaintenanceSignal maintenanceSignal) { return false; } @Override public boolean setProperty(PropertyKey key, HelixProperty value) { String path = key.getPath(); _baseDataAccessor.set(path, value.getRecord(), AccessOption.PERSISTENT); return true; } @Override public <T extends HelixProperty> boolean updateProperty(PropertyKey key, T value) { return updateProperty(key, new ZNRecordUpdater(value.getRecord()), value); } @Override public <T extends HelixProperty> boolean updateProperty(PropertyKey key, DataUpdater<ZNRecord> updater, T value) { String path = key.getPath(); PropertyType type = key.getType(); if (type.updateOnlyOnExists) { if (_baseDataAccessor.exists(path, 0)) { if (type.mergeOnUpdate) { ZNRecord znRecord = new ZNRecord((ZNRecord) _baseDataAccessor.get(path, null, 0)); ZNRecord newZNRecord = updater.update(znRecord); if (newZNRecord != null) { _baseDataAccessor.set(path, newZNRecord, 0); } } else { _baseDataAccessor.set(path, value.getRecord(), 0); } } } else { if (type.mergeOnUpdate) { if (_baseDataAccessor.exists(path, 0)) { ZNRecord znRecord = new ZNRecord((ZNRecord) _baseDataAccessor.get(path, null, 0)); ZNRecord newZNRecord = updater.update(znRecord); if (newZNRecord != null) { _baseDataAccessor.set(path, newZNRecord, 0); } } else { _baseDataAccessor.set(path, value.getRecord(), 0); } } else { _baseDataAccessor.set(path, value.getRecord(), 0); } } return true; } @SuppressWarnings("unchecked") @Override public <T extends HelixProperty> T getProperty(PropertyKey key) { String path = key.getPath(); Stat stat = new Stat(); return (T) HelixProperty.convertToTypedInstance(key.getTypeClass(), (ZNRecord) _baseDataAccessor.get(path, stat, 0)); } @Override public boolean removeProperty(PropertyKey key) { String path = key.getPath(); // PropertyPathConfig.getPath(type, // _clusterName, keys); _baseDataAccessor.remove(path, 0); return true; } @Override public HelixProperty.Stat getPropertyStat(PropertyKey key) { PropertyType type = key.getType(); String path = key.getPath(); try { Stat stat = _baseDataAccessor.getStat(path, 0); if (stat != null) { return new HelixProperty.Stat(stat.getVersion(), stat.getCtime(), stat.getMtime(), stat.getEphemeralOwner()); } } catch (ZkNoNodeException e) { } return null; } @Override public List<HelixProperty.Stat> getPropertyStats(List<PropertyKey> keys) { if (keys == null || keys.size() == 0) { return Collections.emptyList(); } List<HelixProperty.Stat> propertyStats = new ArrayList<>(keys.size()); List<String> paths = new ArrayList<>(keys.size()); for (PropertyKey key : keys) { paths.add(key.getPath()); } Stat[] zkStats = _baseDataAccessor.getStats(paths, 0); for (int i = 0; i < keys.size(); i++) { Stat zkStat = zkStats[i]; HelixProperty.Stat propertyStat = null; if (zkStat != null) { propertyStat = new HelixProperty.Stat(zkStat.getVersion(), zkStat.getCtime(), zkStat.getMtime(), zkStat.getEphemeralOwner()); } propertyStats.add(propertyStat); } return propertyStats; } @Override public List<String> getChildNames(PropertyKey propertyKey) { String path = propertyKey.getPath(); return _baseDataAccessor.getChildNames(path, 0); } @SuppressWarnings("unchecked") @Deprecated @Override public <T extends HelixProperty> List<T> getChildValues(PropertyKey propertyKey) { return getChildValues(propertyKey, false); } @Override public <T extends HelixProperty> List<T> getChildValues(PropertyKey key, boolean throwException) { String path = key.getPath(); // PropertyPathConfig.getPath(type, List<ZNRecord> children = _baseDataAccessor.getChildren(path, null, 0, 0, 0); return (List<T>) HelixProperty.convertToTypedList(key.getTypeClass(), children); } @Deprecated @Override public <T extends HelixProperty> Map<String, T> getChildValuesMap(PropertyKey key) { return getChildValuesMap(key, false); } @Override public <T extends HelixProperty> Map<String, T> getChildValuesMap(PropertyKey key, boolean throwException) { List<T> list = getChildValues(key, throwException); return HelixProperty.convertListToMap(list); } @Override public <T extends HelixProperty> boolean[] createChildren(List<PropertyKey> keys, List<T> children) { return setChildren(keys, children); } @Override public <T extends HelixProperty> boolean[] setChildren(List<PropertyKey> keys, List<T> children) { boolean[] results = new boolean[keys.size()]; for (int i = 0; i < keys.size(); i++) { results[i] = setProperty(keys.get(i), children.get(i)); } return results; } @Override public PropertyKey.Builder keyBuilder() { return _propertyKeyBuilder; } @Override public BaseDataAccessor getBaseDataAccessor() { return _baseDataAccessor; } @Override public <T extends HelixProperty> boolean[] updateChildren(List<String> paths, List<DataUpdater<ZNRecord>> updaters, int options) { return _baseDataAccessor.updateChildren(paths, updaters, options); } @Deprecated @Override public <T extends HelixProperty> List<T> getProperty(List<PropertyKey> keys) { return getProperty(keys, false); } @Override public <T extends HelixProperty> List<T> getProperty(List<PropertyKey> keys, boolean throwException) { List<T> list = new ArrayList<T>(); for (PropertyKey key : keys) { @SuppressWarnings("unchecked") T t = (T) getProperty(key); list.add(t); } return list; } }
lei-xia/helix
helix-core/src/test/java/org/apache/helix/MockAccessor.java
Java
apache-2.0
8,435
package demo.catalog.coursera.org.courserademoapp.network; import retrofit.http.GET; import rx.Observable; public interface CatalogAPIService { @GET("/api/catalog.v1/courses?fields=smallIcon") Observable<JSCourseResponse> getCourses(); }
richk/CourseraDemoApp
app/src/main/java/demo/catalog/coursera/org/courserademoapp/network/CatalogAPIService.java
Java
apache-2.0
248
/* * 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.pig.newplan.logical.relational; import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.Set; import org.apache.pig.impl.logicalLayer.FrontendException; import org.apache.pig.impl.util.Pair; import org.apache.pig.newplan.Operator; import org.apache.pig.newplan.OperatorPlan; import org.apache.pig.newplan.PlanVisitor; import org.apache.pig.newplan.logical.expression.LogicalExpression; public class LOUnion extends LogicalRelationalOperator { // uid mapping from output uid to input uid private List<Pair<Long, Long>> uidMapping = new ArrayList<Pair<Long, Long>>(); public LOUnion(OperatorPlan plan) { super("LOUnion", plan); } @Override public LogicalSchema getSchema() throws FrontendException { if (schema != null) { return schema; } List<Operator> inputs = null; inputs = plan.getPredecessors(this); // If any predecessor's schema is null, then the schema for union is null for (Operator input : inputs) { LogicalRelationalOperator op = (LogicalRelationalOperator)input; if (op.getSchema()==null) return null; } LogicalSchema s0 = ((LogicalRelationalOperator)inputs.get(0)).getSchema(); if (inputs.size()==1) return s0; LogicalSchema s1 = ((LogicalRelationalOperator)inputs.get(1)).getSchema(); LogicalSchema mergedSchema = LogicalSchema.merge(s0, s1); // Merge schema for (int i=2;i<inputs.size();i++) { LogicalSchema otherSchema = ((LogicalRelationalOperator)inputs.get(i)).getSchema(); if (mergedSchema==null || otherSchema==null) return null; mergedSchema = LogicalSchema.merge(mergedSchema, otherSchema); if (mergedSchema == null) return null; } // Bring back cached uid if any; otherwise, cache uid generated for (int i=0;i<s0.size();i++) { LogicalSchema.LogicalFieldSchema fs = mergedSchema.getField(i); long uid = -1; for (Pair<Long, Long> pair : uidMapping) { if (pair.second==s0.getField(i).uid) { uid = pair.first; break; } } if (uid==-1) { uid = LogicalExpression.getNextUid(); for (Operator input : inputs) { long inputUid = ((LogicalRelationalOperator)input).getSchema().getField(i).uid; uidMapping.add(new Pair<Long, Long>(uid, inputUid)); } } fs.uid = uid; } schema = mergedSchema; return schema; } @Override public void accept(PlanVisitor v) throws FrontendException { if (!(v instanceof LogicalRelationalNodesVisitor)) { throw new FrontendException("Expected LogicalPlanVisitor", 2223); } ((LogicalRelationalNodesVisitor)v).visit(this); } @Override public boolean isEqual(Operator other) throws FrontendException { if (other != null && other instanceof LOUnion) { return checkEquality((LOUnion)other); } else { return false; } } // Get input uids mapping to the output uid public Set<Long> getInputUids(long uid) { Set<Long> result = new HashSet<Long>(); for (Pair<Long, Long> pair : uidMapping) { if (pair.first==uid) result.add(pair.second); } return result; } @Override public void resetUid() { uidMapping = new ArrayList<Pair<Long, Long>>(); } }
simplegeo/hadoop-pig
src/org/apache/pig/newplan/logical/relational/LOUnion.java
Java
apache-2.0
4,578
/* * Copyright 2015 Austin Keener, Michael Ritter, Florian Spieß, and the JDA 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 net.dv8tion.jda.internal.handle; import net.dv8tion.jda.api.entities.Guild; import net.dv8tion.jda.api.entities.GuildChannel; import net.dv8tion.jda.api.entities.Invite; import net.dv8tion.jda.api.entities.User; import net.dv8tion.jda.api.events.guild.invite.GuildInviteCreateEvent; import net.dv8tion.jda.api.utils.data.DataObject; import net.dv8tion.jda.internal.JDAImpl; import net.dv8tion.jda.internal.entities.InviteImpl; import java.time.OffsetDateTime; import java.util.Optional; public class InviteCreateHandler extends SocketHandler { public InviteCreateHandler(JDAImpl api) { super(api); } @Override protected Long handleInternally(DataObject content) { long guildId = content.getUnsignedLong("guild_id"); if (getJDA().getGuildSetupController().isLocked(guildId)) return guildId; Guild realGuild = getJDA().getGuildById(guildId); if (realGuild == null) { EventCache.LOG.debug("Caching INVITE_CREATE for unknown guild with id {}", guildId); getJDA().getEventCache().cache(EventCache.Type.GUILD, guildId, responseNumber, allContent, this::handle); return null; } long channelId = content.getUnsignedLong("channel_id"); GuildChannel realChannel = realGuild.getGuildChannelById(channelId); if (realChannel == null) { EventCache.LOG.debug("Caching INVITE_CREATE for unknown channel with id {} in guild with id {}", channelId, guildId); getJDA().getEventCache().cache(EventCache.Type.CHANNEL, channelId, responseNumber, allContent, this::handle); return null; } String code = content.getString("code"); boolean temporary = content.getBoolean("temporary"); int maxAge = content.getInt("max_age", -1); int maxUses = content.getInt("max_uses", -1); OffsetDateTime creationTime = content.opt("created_at") .map(String::valueOf) .map(OffsetDateTime::parse) .orElse(null); Optional<DataObject> inviterJson = content.optObject("inviter"); boolean expanded = maxUses != -1; User inviter = inviterJson.map(json -> getJDA().getEntityBuilder().createUser(json)).orElse(null); InviteImpl.ChannelImpl channel = new InviteImpl.ChannelImpl(realChannel); InviteImpl.GuildImpl guild = new InviteImpl.GuildImpl(realGuild); final Invite.TargetType targetType = Invite.TargetType.fromId(content.getInt("target_type", 0)); final Invite.InviteTarget target; switch (targetType) { case STREAM: DataObject targetUserObject = content.getObject("target_user"); target = new InviteImpl.InviteTargetImpl(targetType, null, getJDA().getEntityBuilder().createUser(targetUserObject)); break; case EMBEDDED_APPLICATION: DataObject applicationObject = content.getObject("target_application"); Invite.EmbeddedApplication application = new InviteImpl.EmbeddedApplicationImpl( applicationObject.getString("icon", null), applicationObject.getString("name"), applicationObject.getString("description"), applicationObject.getString("summary"), applicationObject.getLong("id"), applicationObject.getInt("max_participants", -1) ); target = new InviteImpl.InviteTargetImpl(targetType, application, null); break; case NONE: target = null; break; default: target = new InviteImpl.InviteTargetImpl(targetType, null, null); } Invite invite = new InviteImpl(getJDA(), code, expanded, inviter, maxAge, maxUses, temporary, creationTime, 0, channel, guild, null, target, Invite.InviteType.GUILD); getJDA().handleEvent( new GuildInviteCreateEvent( getJDA(), responseNumber, invite, realChannel)); return null; } }
DV8FromTheWorld/JDA
src/main/java/net/dv8tion/jda/internal/handle/InviteCreateHandler.java
Java
apache-2.0
4,765
/* =================================================== * Copyright 2015 Alex Muthmann * * 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 de.dev.eth0.rssreader.app.util.html.rewriter.impl; import android.content.Context; import android.os.Bundle; import android.support.v4.app.FragmentActivity; import android.text.style.ClickableSpan; import android.view.View; import de.dev.eth0.rssreader.app.data.database.tables.FeedEntryTable; import de.dev.eth0.rssreader.app.ui.dialog.ImageOverlayDialog; import de.dev.eth0.rssreader.app.util.html.rewriter.AbstractRewriter; import de.dev.eth0.rssreader.core.Constants; import timber.log.Timber; public class ImageRewriterImpl extends AbstractRewriter { private final Context context; public ImageRewriterImpl(Context context) { this.context = context; } @Override public boolean accepts(String url) { return Constants.PATTERN_IMAGES.matcher(url).matches(); } @Override public Object rewrite(final String url) { Timber.d("Setup Overlay for Image %s", url); return new ClickableSpan() { @Override public void onClick(View view) { if (context instanceof FragmentActivity) { FragmentActivity activity = (FragmentActivity)context; ImageOverlayDialog dialog = new ImageOverlayDialog(); Bundle bundle = new Bundle(); bundle.putString(FeedEntryTable.COLUMN_LINK, url); dialog.setArguments(bundle); dialog.show(activity.getSupportFragmentManager(), dialog.getClass().getSimpleName()); } } }; } }
deveth0/Android-RSSReader
app/src/main/java/de/dev/eth0/rssreader/app/util/html/rewriter/impl/ImageRewriterImpl.java
Java
apache-2.0
2,143
/* * Copyright 2013-2015 must-be.org * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package consulo.java.refactoring; import org.jetbrains.annotations.PropertyKey; import com.intellij.AbstractBundle; /** * @author VISTALL * @since 15.08.2015 */ public class JavaRefactoringBundle extends AbstractBundle { private static final JavaRefactoringBundle ourInstance = new JavaRefactoringBundle(); private JavaRefactoringBundle() { super("messages.JavaRefactoringBundle"); } public static String message(@PropertyKey(resourceBundle = "messages.JavaRefactoringBundle") String key) { return ourInstance.getMessage(key); } public static String message(@PropertyKey(resourceBundle = "messages.JavaRefactoringBundle") String key, Object... params) { return ourInstance.getMessage(key, params); } }
consulo/consulo-java
java-impl/src/main/java/consulo/java/refactoring/JavaRefactoringBundle.java
Java
apache-2.0
1,323
/* * Copyright 2000-2009 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.template.macro; import javax.annotation.Nonnull; import com.intellij.codeInsight.template.*; import com.intellij.psi.PsiElement; import com.intellij.psi.PsiMethod; /** * @author yole */ public class MethodReturnTypeMacro extends Macro { @Override public String getName() { return "methodReturnType"; } @Override public String getPresentableName() { return "methodReturnType()"; } @Override @Nonnull public String getDefaultValue() { return "a"; } @Override public Result calculateResult(@Nonnull final Expression[] params, final ExpressionContext context) { PsiElement place = context.getPsiElementAtStartOffset(); while(place != null){ if (place instanceof PsiMethod){ return new PsiTypeResult(((PsiMethod)place).getReturnType(), place.getProject()); } place = place.getParent(); } return null; } @Override public boolean isAcceptableInContext(TemplateContextType context) { return context instanceof JavaCodeContextType; } }
consulo/consulo-java
java-impl/src/main/java/com/intellij/codeInsight/template/macro/MethodReturnTypeMacro.java
Java
apache-2.0
1,662
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package nettyhttpserver.response; import nettyhttpserver.response.watcher.Info; import io.netty.handler.codec.http.DefaultFullHttpResponse; import io.netty.handler.codec.http.FullHttpResponse; import static io.netty.handler.codec.http.HttpHeaders.Names.*; import io.netty.handler.codec.http.HttpResponseStatus; import io.netty.handler.codec.http.HttpVersion; import io.netty.handler.codec.http.QueryStringDecoder; import java.util.List; /** * * @author Roman */ class RedirectHttpResponse { public FullHttpResponse getResponse(QueryStringDecoder qsd) { List<String> url = qsd.parameters().get("url"); Info.redirectCount(url.get(0)); FullHttpResponse response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.MOVED_PERMANENTLY); response.headers().set(LOCATION, url.get(0)); return response; } }
sentinalll/netty_server
src/nettyhttpserver/response/RedirectHttpResponse.java
Java
apache-2.0
971
/* * Copyright 2017 Open Language for Internet of Things (Oliot) * * 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.oliot.heroku.tsd.models.schema; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlType; import java.util.ArrayList; import java.util.List; /** * <p>Java class for TSD_AttributeValuePairListType complex type. * * <p>The following schema fragment specifies the expected content contained within this class. * * <pre> * &lt;complexType name="TSD_AttributeValuePairListType"> * &lt;complexContent> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType"> * &lt;sequence> * &lt;element name="stringAVP" type="{urn:gs1:tsd:tsd_common:xsd:1}TSD_StringAttributeValuePairType" maxOccurs="unbounded"/> * &lt;/sequence> * &lt;/restriction> * &lt;/complexContent> * &lt;/complexType> * </pre> * * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "TSD_AttributeValuePairListType", namespace = "urn:gs1:tsd:tsd_common:xsd:1", propOrder = { "stringAVP" }) public class TSDAttributeValuePairListType { @XmlElement(required = true) protected List<TSDStringAttributeValuePairType> stringAVP; /** * Gets the value of the stringAVP property. * * <p> * This accessor method returns a reference to the live list, * not a snapshot. Therefore any modification you make to the * returned list will be present inside the JAXB object. * This is why there is not a <CODE>set</CODE> method for the stringAVP property. * * <p> * For example, to add a new item, do as follows: * <pre> * getStringAVP().add(newItem); * </pre> * * * <p> * Objects of the following type(s) are allowed in the list * {@link TSDStringAttributeValuePairType } * * */ public List<TSDStringAttributeValuePairType> getStringAVP() { if (stringAVP == null) { stringAVP = new ArrayList<TSDStringAttributeValuePairType>(); } return this.stringAVP; } }
oliot-tsd/tsd-heroku
src/main/java/org/oliot/heroku/tsd/models/schema/TSDAttributeValuePairListType.java
Java
apache-2.0
2,715
/** * Copyright (c) 2015 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 io.jmnarloch.spring.cloud.zuul.store; import com.datastax.driver.core.Cluster; import org.cassandraunit.spring.CassandraDataSet; import org.cassandraunit.spring.CassandraUnitTestExecutionListener; import org.cassandraunit.spring.EmbeddedCassandra; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.cloud.netflix.zuul.filters.ZuulProperties; import org.springframework.context.annotation.Configuration; import org.springframework.data.cassandra.core.CassandraTemplate; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.TestExecutionListeners; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import java.net.InetAddress; import java.util.HashMap; import java.util.List; import java.util.Map; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; import static org.springframework.test.context.TestExecutionListeners.MergeMode.MERGE_WITH_DEFAULTS; /** * Tests the {@link CassandraZuulRouteStore} class. * * @author Jakub Narloch */ @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration @TestExecutionListeners( value = { CassandraUnitTestExecutionListener.class }, mergeMode = MERGE_WITH_DEFAULTS) @CassandraDataSet(value = { "schema/cassandra.cql" }) @EmbeddedCassandra public class CassandraZuulRouteStoreTest { private CassandraZuulRouteStore instance; private CassandraTemplate cassandraTemplate; @Before public void setUp() throws Exception { final Cluster cluster = Cluster.builder() .addContactPoints(InetAddress.getLoopbackAddress()) .withPort(9142) .build(); cassandraTemplate = new CassandraTemplate(cluster.connect("zuul")); instance = new CassandraZuulRouteStore(cassandraTemplate); } @Test public void shouldRetrieveEmptyRouteList() { // given cassandraTemplate.truncate("zuul_routes"); // when final List<ZuulProperties.ZuulRoute> routes = instance.findAll(); // then assertTrue(routes.isEmpty()); } @Test public void shouldRetrieveConfiguredRoutes() { // when final List<ZuulProperties.ZuulRoute> routes = instance.findAll(); // then assertFalse(routes.isEmpty()); assertEquals(2, routes.size()); final Map<String, ZuulProperties.ZuulRoute> routeMap = asMap(routes); assertEquals("resource", routeMap.get("resource").getId()); assertEquals("/api/**", routeMap.get("resource").getPath()); assertEquals("rest-service", routeMap.get("resource").getServiceId()); } private Map<String, ZuulProperties.ZuulRoute> asMap(List<ZuulProperties.ZuulRoute> routes) { final Map<String, ZuulProperties.ZuulRoute> map = new HashMap<String, ZuulProperties.ZuulRoute>(); for(ZuulProperties.ZuulRoute route : routes) { map.put(route.getId(), route); } return map; } @Configuration public static class Config { } }
jmnarloch/zuul-route-cassandra-spring-cloud-starter
src/test/java/io/jmnarloch/spring/cloud/zuul/store/CassandraZuulRouteStoreTest.java
Java
apache-2.0
3,791
package com.alexsadliak.textanalyzer.ui.finderInfo; import javafx.scene.Scene; import javafx.stage.Modality; import javafx.stage.Stage; public final class FinderInfoService { public void showFinderInfoView(final String text) { Stage finderInfoStage = new Stage(); finderInfoStage.setTitle("Text Analyzer: Find Information"); finderInfoStage.setResizable(false); finderInfoStage.initModality(Modality.APPLICATION_MODAL); FinderInfoView finderInfoView = new FinderInfoView(); finderInfoStage.setScene(new Scene(finderInfoView.getView())); FinderInfoPresenter finderInfoPresenter = (FinderInfoPresenter) finderInfoView.getPresenter(); finderInfoPresenter.find(text); finderInfoPresenter.setFinderInfoStage(finderInfoStage); finderInfoStage.showAndWait(); } }
alexsadliak/text-analyzer
src/main/java/com/alexsadliak/textanalyzer/ui/finderInfo/FinderInfoService.java
Java
apache-2.0
866
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package ufo.lucene4; import java.text.DecimalFormat; import java.text.DecimalFormatSymbols; import java.util.Date; import java.util.Locale; import org.junit.After; import org.junit.AfterClass; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Rule; import org.junit.rules.TestName; import org.junit.runner.RunWith; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.ApplicationContext; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import ufo.lucene4.config.Constants; import ufo.lucene4.config.SpringConfig; /** * * @author ufo */ @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(classes = SpringConfig.class) public class Lucene4BaseTest { private final static DecimalFormat TIME_FORMAT = new DecimalFormat("####,###.###", new DecimalFormatSymbols(Locale.US)); private final Logger logger = LoggerFactory.getLogger(getClass()); @BeforeClass public static void setUpBeforeClass() { if (System.getProperty(Constants.FILESYSTEM_RESOURCES_PATH_VARIABLE)==null) { System.setProperty(Constants.FILESYSTEM_RESOURCES_PATH_VARIABLE, "."); } } @AfterClass public static void tearDownAfterClass() { // Do nothing } @Rule public TestName name = new TestName(); @Autowired protected ApplicationContext context; private Date testStartDate; @Before public void setUpBeforeTest() { testStartDate = new Date(); logger.info("==================================================================="); logger.info("BEGIN TEST " + name.getMethodName()); logger.info("==================================================================="); } @After public void tearDownAfterTest() { long executionTime = new Date().getTime() - testStartDate.getTime(); logger.info("==================================================================="); logger.info("END TEST " + name.getMethodName()); logger.info("execution time: " + TIME_FORMAT.format(executionTime) + " ms"); logger.info("==================================================================="); } public Logger getLogger() { return logger; } }
ufoscout/java-sample-projects
skeletons/skeleton-spring4-jar/src/test/java/ufo/lucene4/Lucene4BaseTest.java
Java
apache-2.0
2,597
package de.hshannover.f4.trust.irondetect.policy.publisher.model.identifier.handler; import org.w3c.dom.Document; import org.w3c.dom.Element; import de.hshannover.f4.trust.ifmapj.exception.MarshalException; import de.hshannover.f4.trust.ifmapj.identifier.Identifier; import de.hshannover.f4.trust.ifmapj.identifier.Identifiers.Helpers; import de.hshannover.f4.trust.irondetect.policy.publisher.model.identifier.Rule; import de.hshannover.f4.trust.irondetect.policy.publisher.util.PolicyStrings; public class RuleHandler extends ExtendetIdentifierHandler<Rule> { @Override public Element toExtendetElement(Identifier i, Document doc) throws MarshalException { Helpers.checkIdentifierType(i, this); Rule rule = (Rule) i; String id = rule.getID(); if (id == null) { throw new MarshalException("No id set"); } Element policyElement = doc.createElementNS(PolicyStrings.POLICY_IDENTIFIER_NS_URI, PolicyStrings.RULE_EL_NAME); Element idElement = doc.createElementNS(null, PolicyStrings.ID_EL_NAME); idElement.setTextContent(id); policyElement.appendChild(idElement); Helpers.addAdministrativeDomain(policyElement, rule); return policyElement; } @Override public Class<Rule> handles() { return Rule.class; } }
MReichenbach/irondetect
src/main/java/de/hshannover/f4/trust/irondetect/policy/publisher/model/identifier/handler/RuleHandler.java
Java
apache-2.0
1,252
/* * 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.kms.model; import javax.annotation.Generated; /** * <p> * The request was rejected because the specified <code>KeySpec</code> value is not valid. * </p> */ @Generated("com.amazonaws:aws-java-sdk-code-generator") public class InvalidKeyUsageException extends com.amazonaws.services.kms.model.AWSKMSException { private static final long serialVersionUID = 1L; /** * Constructs a new InvalidKeyUsageException with the specified error message. * * @param message * Describes the error encountered. */ public InvalidKeyUsageException(String message) { super(message); } }
jentfoo/aws-sdk-java
aws-java-sdk-kms/src/main/java/com/amazonaws/services/kms/model/InvalidKeyUsageException.java
Java
apache-2.0
1,243
/* * 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.rds.model; import java.io.Serializable; import javax.annotation.Generated; import com.amazonaws.AmazonWebServiceRequest; /** * <p/> * * @see <a href="http://docs.aws.amazon.com/goto/WebAPI/rds-2014-10-31/DescribeDBClusters" target="_top">AWS API * Documentation</a> */ @Generated("com.amazonaws:aws-java-sdk-code-generator") public class DescribeDBClustersRequest extends com.amazonaws.AmazonWebServiceRequest implements Serializable, Cloneable { /** * <p> * The user-supplied DB cluster identifier. If this parameter is specified, information from only the specific DB * cluster is returned. This parameter isn't case-sensitive. * </p> * <p> * Constraints: * </p> * <ul> * <li> * <p> * If supplied, must match an existing DBClusterIdentifier. * </p> * </li> * </ul> */ private String dBClusterIdentifier; /** * <p> * A filter that specifies one or more DB clusters to describe. * </p> * <p> * Supported filters: * </p> * <ul> * <li> * <p> * <code>db-cluster-id</code> - Accepts DB cluster identifiers and DB cluster Amazon Resource Names (ARNs). The * results list will only include information about the DB clusters identified by these ARNs. * </p> * </li> * </ul> */ private com.amazonaws.internal.SdkInternalList<Filter> filters; /** * <p> * The maximum number of records to include in the response. If more records exist than the specified * <code>MaxRecords</code> value, a pagination token called a marker is included in the response so that the * remaining results can be retrieved. * </p> * <p> * Default: 100 * </p> * <p> * Constraints: Minimum 20, maximum 100. * </p> */ private Integer maxRecords; /** * <p> * An optional pagination token provided by a previous <code>DescribeDBClusters</code> request. If this parameter is * specified, the response includes only records beyond the marker, up to the value specified by * <code>MaxRecords</code>. * </p> */ private String marker; /** * <p> * Optional Boolean parameter that specifies whether the output includes information about clusters shared from * other AWS accounts. * </p> */ private Boolean includeShared; /** * <p> * The user-supplied DB cluster identifier. If this parameter is specified, information from only the specific DB * cluster is returned. This parameter isn't case-sensitive. * </p> * <p> * Constraints: * </p> * <ul> * <li> * <p> * If supplied, must match an existing DBClusterIdentifier. * </p> * </li> * </ul> * * @param dBClusterIdentifier * The user-supplied DB cluster identifier. If this parameter is specified, information from only the * specific DB cluster is returned. This parameter isn't case-sensitive.</p> * <p> * Constraints: * </p> * <ul> * <li> * <p> * If supplied, must match an existing DBClusterIdentifier. * </p> * </li> */ public void setDBClusterIdentifier(String dBClusterIdentifier) { this.dBClusterIdentifier = dBClusterIdentifier; } /** * <p> * The user-supplied DB cluster identifier. If this parameter is specified, information from only the specific DB * cluster is returned. This parameter isn't case-sensitive. * </p> * <p> * Constraints: * </p> * <ul> * <li> * <p> * If supplied, must match an existing DBClusterIdentifier. * </p> * </li> * </ul> * * @return The user-supplied DB cluster identifier. If this parameter is specified, information from only the * specific DB cluster is returned. This parameter isn't case-sensitive.</p> * <p> * Constraints: * </p> * <ul> * <li> * <p> * If supplied, must match an existing DBClusterIdentifier. * </p> * </li> */ public String getDBClusterIdentifier() { return this.dBClusterIdentifier; } /** * <p> * The user-supplied DB cluster identifier. If this parameter is specified, information from only the specific DB * cluster is returned. This parameter isn't case-sensitive. * </p> * <p> * Constraints: * </p> * <ul> * <li> * <p> * If supplied, must match an existing DBClusterIdentifier. * </p> * </li> * </ul> * * @param dBClusterIdentifier * The user-supplied DB cluster identifier. If this parameter is specified, information from only the * specific DB cluster is returned. This parameter isn't case-sensitive.</p> * <p> * Constraints: * </p> * <ul> * <li> * <p> * If supplied, must match an existing DBClusterIdentifier. * </p> * </li> * @return Returns a reference to this object so that method calls can be chained together. */ public DescribeDBClustersRequest withDBClusterIdentifier(String dBClusterIdentifier) { setDBClusterIdentifier(dBClusterIdentifier); return this; } /** * <p> * A filter that specifies one or more DB clusters to describe. * </p> * <p> * Supported filters: * </p> * <ul> * <li> * <p> * <code>db-cluster-id</code> - Accepts DB cluster identifiers and DB cluster Amazon Resource Names (ARNs). The * results list will only include information about the DB clusters identified by these ARNs. * </p> * </li> * </ul> * * @return A filter that specifies one or more DB clusters to describe.</p> * <p> * Supported filters: * </p> * <ul> * <li> * <p> * <code>db-cluster-id</code> - Accepts DB cluster identifiers and DB cluster Amazon Resource Names (ARNs). * The results list will only include information about the DB clusters identified by these ARNs. * </p> * </li> */ public java.util.List<Filter> getFilters() { if (filters == null) { filters = new com.amazonaws.internal.SdkInternalList<Filter>(); } return filters; } /** * <p> * A filter that specifies one or more DB clusters to describe. * </p> * <p> * Supported filters: * </p> * <ul> * <li> * <p> * <code>db-cluster-id</code> - Accepts DB cluster identifiers and DB cluster Amazon Resource Names (ARNs). The * results list will only include information about the DB clusters identified by these ARNs. * </p> * </li> * </ul> * * @param filters * A filter that specifies one or more DB clusters to describe.</p> * <p> * Supported filters: * </p> * <ul> * <li> * <p> * <code>db-cluster-id</code> - Accepts DB cluster identifiers and DB cluster Amazon Resource Names (ARNs). * The results list will only include information about the DB clusters identified by these ARNs. * </p> * </li> */ public void setFilters(java.util.Collection<Filter> filters) { if (filters == null) { this.filters = null; return; } this.filters = new com.amazonaws.internal.SdkInternalList<Filter>(filters); } /** * <p> * A filter that specifies one or more DB clusters to describe. * </p> * <p> * Supported filters: * </p> * <ul> * <li> * <p> * <code>db-cluster-id</code> - Accepts DB cluster identifiers and DB cluster Amazon Resource Names (ARNs). The * results list will only include information about the DB clusters identified by these ARNs. * </p> * </li> * </ul> * <p> * <b>NOTE:</b> This method appends the values to the existing list (if any). Use * {@link #setFilters(java.util.Collection)} or {@link #withFilters(java.util.Collection)} if you want to override * the existing values. * </p> * * @param filters * A filter that specifies one or more DB clusters to describe.</p> * <p> * Supported filters: * </p> * <ul> * <li> * <p> * <code>db-cluster-id</code> - Accepts DB cluster identifiers and DB cluster Amazon Resource Names (ARNs). * The results list will only include information about the DB clusters identified by these ARNs. * </p> * </li> * @return Returns a reference to this object so that method calls can be chained together. */ public DescribeDBClustersRequest withFilters(Filter... filters) { if (this.filters == null) { setFilters(new com.amazonaws.internal.SdkInternalList<Filter>(filters.length)); } for (Filter ele : filters) { this.filters.add(ele); } return this; } /** * <p> * A filter that specifies one or more DB clusters to describe. * </p> * <p> * Supported filters: * </p> * <ul> * <li> * <p> * <code>db-cluster-id</code> - Accepts DB cluster identifiers and DB cluster Amazon Resource Names (ARNs). The * results list will only include information about the DB clusters identified by these ARNs. * </p> * </li> * </ul> * * @param filters * A filter that specifies one or more DB clusters to describe.</p> * <p> * Supported filters: * </p> * <ul> * <li> * <p> * <code>db-cluster-id</code> - Accepts DB cluster identifiers and DB cluster Amazon Resource Names (ARNs). * The results list will only include information about the DB clusters identified by these ARNs. * </p> * </li> * @return Returns a reference to this object so that method calls can be chained together. */ public DescribeDBClustersRequest withFilters(java.util.Collection<Filter> filters) { setFilters(filters); return this; } /** * <p> * The maximum number of records to include in the response. If more records exist than the specified * <code>MaxRecords</code> value, a pagination token called a marker is included in the response so that the * remaining results can be retrieved. * </p> * <p> * Default: 100 * </p> * <p> * Constraints: Minimum 20, maximum 100. * </p> * * @param maxRecords * The maximum number of records to include in the response. If more records exist than the specified * <code>MaxRecords</code> value, a pagination token called a marker is included in the response so that the * remaining results can be retrieved. </p> * <p> * Default: 100 * </p> * <p> * Constraints: Minimum 20, maximum 100. */ public void setMaxRecords(Integer maxRecords) { this.maxRecords = maxRecords; } /** * <p> * The maximum number of records to include in the response. If more records exist than the specified * <code>MaxRecords</code> value, a pagination token called a marker is included in the response so that the * remaining results can be retrieved. * </p> * <p> * Default: 100 * </p> * <p> * Constraints: Minimum 20, maximum 100. * </p> * * @return The maximum number of records to include in the response. If more records exist than the specified * <code>MaxRecords</code> value, a pagination token called a marker is included in the response so that the * remaining results can be retrieved. </p> * <p> * Default: 100 * </p> * <p> * Constraints: Minimum 20, maximum 100. */ public Integer getMaxRecords() { return this.maxRecords; } /** * <p> * The maximum number of records to include in the response. If more records exist than the specified * <code>MaxRecords</code> value, a pagination token called a marker is included in the response so that the * remaining results can be retrieved. * </p> * <p> * Default: 100 * </p> * <p> * Constraints: Minimum 20, maximum 100. * </p> * * @param maxRecords * The maximum number of records to include in the response. If more records exist than the specified * <code>MaxRecords</code> value, a pagination token called a marker is included in the response so that the * remaining results can be retrieved. </p> * <p> * Default: 100 * </p> * <p> * Constraints: Minimum 20, maximum 100. * @return Returns a reference to this object so that method calls can be chained together. */ public DescribeDBClustersRequest withMaxRecords(Integer maxRecords) { setMaxRecords(maxRecords); return this; } /** * <p> * An optional pagination token provided by a previous <code>DescribeDBClusters</code> request. If this parameter is * specified, the response includes only records beyond the marker, up to the value specified by * <code>MaxRecords</code>. * </p> * * @param marker * An optional pagination token provided by a previous <code>DescribeDBClusters</code> request. If this * parameter is specified, the response includes only records beyond the marker, up to the value specified by * <code>MaxRecords</code>. */ public void setMarker(String marker) { this.marker = marker; } /** * <p> * An optional pagination token provided by a previous <code>DescribeDBClusters</code> request. If this parameter is * specified, the response includes only records beyond the marker, up to the value specified by * <code>MaxRecords</code>. * </p> * * @return An optional pagination token provided by a previous <code>DescribeDBClusters</code> request. If this * parameter is specified, the response includes only records beyond the marker, up to the value specified * by <code>MaxRecords</code>. */ public String getMarker() { return this.marker; } /** * <p> * An optional pagination token provided by a previous <code>DescribeDBClusters</code> request. If this parameter is * specified, the response includes only records beyond the marker, up to the value specified by * <code>MaxRecords</code>. * </p> * * @param marker * An optional pagination token provided by a previous <code>DescribeDBClusters</code> request. If this * parameter is specified, the response includes only records beyond the marker, up to the value specified by * <code>MaxRecords</code>. * @return Returns a reference to this object so that method calls can be chained together. */ public DescribeDBClustersRequest withMarker(String marker) { setMarker(marker); return this; } /** * <p> * Optional Boolean parameter that specifies whether the output includes information about clusters shared from * other AWS accounts. * </p> * * @param includeShared * Optional Boolean parameter that specifies whether the output includes information about clusters shared * from other AWS accounts. */ public void setIncludeShared(Boolean includeShared) { this.includeShared = includeShared; } /** * <p> * Optional Boolean parameter that specifies whether the output includes information about clusters shared from * other AWS accounts. * </p> * * @return Optional Boolean parameter that specifies whether the output includes information about clusters shared * from other AWS accounts. */ public Boolean getIncludeShared() { return this.includeShared; } /** * <p> * Optional Boolean parameter that specifies whether the output includes information about clusters shared from * other AWS accounts. * </p> * * @param includeShared * Optional Boolean parameter that specifies whether the output includes information about clusters shared * from other AWS accounts. * @return Returns a reference to this object so that method calls can be chained together. */ public DescribeDBClustersRequest withIncludeShared(Boolean includeShared) { setIncludeShared(includeShared); return this; } /** * <p> * Optional Boolean parameter that specifies whether the output includes information about clusters shared from * other AWS accounts. * </p> * * @return Optional Boolean parameter that specifies whether the output includes information about clusters shared * from other AWS accounts. */ public Boolean isIncludeShared() { return this.includeShared; } /** * Returns a string representation of this object. This is useful for testing and debugging. Sensitive data will be * redacted from this string using a placeholder value. * * @return A string representation of this object. * * @see java.lang.Object#toString() */ @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("{"); if (getDBClusterIdentifier() != null) sb.append("DBClusterIdentifier: ").append(getDBClusterIdentifier()).append(","); if (getFilters() != null) sb.append("Filters: ").append(getFilters()).append(","); if (getMaxRecords() != null) sb.append("MaxRecords: ").append(getMaxRecords()).append(","); if (getMarker() != null) sb.append("Marker: ").append(getMarker()).append(","); if (getIncludeShared() != null) sb.append("IncludeShared: ").append(getIncludeShared()); sb.append("}"); return sb.toString(); } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (obj instanceof DescribeDBClustersRequest == false) return false; DescribeDBClustersRequest other = (DescribeDBClustersRequest) obj; if (other.getDBClusterIdentifier() == null ^ this.getDBClusterIdentifier() == null) return false; if (other.getDBClusterIdentifier() != null && other.getDBClusterIdentifier().equals(this.getDBClusterIdentifier()) == false) return false; if (other.getFilters() == null ^ this.getFilters() == null) return false; if (other.getFilters() != null && other.getFilters().equals(this.getFilters()) == false) return false; if (other.getMaxRecords() == null ^ this.getMaxRecords() == null) return false; if (other.getMaxRecords() != null && other.getMaxRecords().equals(this.getMaxRecords()) == false) return false; if (other.getMarker() == null ^ this.getMarker() == null) return false; if (other.getMarker() != null && other.getMarker().equals(this.getMarker()) == false) return false; if (other.getIncludeShared() == null ^ this.getIncludeShared() == null) return false; if (other.getIncludeShared() != null && other.getIncludeShared().equals(this.getIncludeShared()) == false) return false; return true; } @Override public int hashCode() { final int prime = 31; int hashCode = 1; hashCode = prime * hashCode + ((getDBClusterIdentifier() == null) ? 0 : getDBClusterIdentifier().hashCode()); hashCode = prime * hashCode + ((getFilters() == null) ? 0 : getFilters().hashCode()); hashCode = prime * hashCode + ((getMaxRecords() == null) ? 0 : getMaxRecords().hashCode()); hashCode = prime * hashCode + ((getMarker() == null) ? 0 : getMarker().hashCode()); hashCode = prime * hashCode + ((getIncludeShared() == null) ? 0 : getIncludeShared().hashCode()); return hashCode; } @Override public DescribeDBClustersRequest clone() { return (DescribeDBClustersRequest) super.clone(); } }
jentfoo/aws-sdk-java
aws-java-sdk-rds/src/main/java/com/amazonaws/services/rds/model/DescribeDBClustersRequest.java
Java
apache-2.0
21,691
/* * Copyright 2014 Simone Filice and Giuseppe Castellucci and Danilo Croce and Roberto Basili * 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 it.uniroma2.sag.kelp.kernel.tree; import it.uniroma2.sag.kelp.data.representation.tree.TreeRepresentation; import it.uniroma2.sag.kelp.data.representation.tree.node.TreeNode; import it.uniroma2.sag.kelp.data.representation.tree.node.TreeNodePairs; import it.uniroma2.sag.kelp.kernel.DirectKernel; import it.uniroma2.sag.kelp.kernel.tree.deltamatrix.DeltaMatrix; import it.uniroma2.sag.kelp.kernel.tree.deltamatrix.StaticDeltaMatrix; import java.util.ArrayList; import java.util.List; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.fasterxml.jackson.annotation.JsonIgnore; import com.fasterxml.jackson.annotation.JsonTypeName; /** * Partial Tree Kernel implementation. * * A Partial Tree Kernel is a convolution kernel that evaluates the tree * fragments shared between two trees. The considered fragments are are partial * trees, i.e. a node and its partial descendancy (the descendancy can be * incomplete, i.e. a partial production is allowed). The kernel function is * defined as: </br> * * \(K(T_1,T_2) = \sum_{n_1 \in N_{T_1}} \sum_{n_2 \in N_{T_2}} * \Delta(n_1,n_2)\) * * </br> where \(\Delta(n_1,n_2)=\sum^{|F|}_i=1 I_i(n_1) I_i(n_2)\), that is the * number of common fragments rooted at the n1 and n2. It can be computed as: * </br> - if the node labels of \(n_1\) and \(n_2\) are different then * \(\Delta(n_1,n_2)=0\) </br> - else \(\Delta(n_1,n_2)= \mu(\lambda^2 + * \sum_{J_1, J_2, l(J_1)=l(J_2)} \lambda^{d(J_1)+d(J_2)} \prod_{i=1}^{l(J_1)} * \Delta(c_{n_1}[J_{1i}], c_{n_2}[J_{2i}])\) * * </br></br> Fore details see [Moschitti, EACL2006] Alessandro Moschitti. * Efficient convolution kernels for dependency and constituent syntactic trees. * In ECML 2006, Berlin, Germany. * * @author Danilo Croce, Giuseppe Castellucci */ @JsonTypeName("ptk") public class PartialTreeKernel extends DirectKernel<TreeRepresentation> { private Logger logger = LoggerFactory.getLogger(PartialTreeKernel.class); private int MAX_CHILDREN = 50; private int MAX_RECURSION = 20; /** * Vertical Decay Factor */ private float mu; /** * Horizontal Decay factor */ private float lambda; /** * Horizontal Decay factor, pow 2 */ @JsonIgnore private float lambda2; /** * Multiplicative factor to scale up/down the leaves contribution */ private float terminalFactor = 1; /** * Maximum length of common subsequences considered in the recursion. It * reflects the maximum branching factor allowed to the tree fragments. */ private int maxSubseqLeng = Integer.MAX_VALUE; //TODO //REMOVE THE DYNAMIC DELTA MATRIX /** * The delta matrix, used to cache the delta functions applied to subtrees */ @JsonIgnore private DeltaMatrix deltaMatrix = StaticDeltaMatrix.getInstance(); private int recursion_id = 0; private float[][] kernel_mat_buffer = new float[MAX_RECURSION][MAX_CHILDREN]; private float[][][] DPS_buffer = new float[MAX_RECURSION][MAX_CHILDREN + 1][MAX_CHILDREN + 1]; private float[][][] DP_buffer = new float[MAX_RECURSION][MAX_CHILDREN + 1][MAX_CHILDREN + 1]; /** * Default constructor. It should be used only for json * serialization/deserialization purposes This constructor by default uses * lambda=0.4, mu=0.4, terminalFactor=1 and it forces to operate to the * represenatation whose identifier is "0". * * Please use the PartialTreeKernel(String) or * PartialTreeKernel(float,float,float,String) to use a Partial Tree Kernel * in your application. */ public PartialTreeKernel() { this(0.4f, 0.4f, 1f, "0"); } /** * A Constructor for the Partial Tree Kernel in which parameters can be set * manually. * * @param LAMBDA * lambda value in the PTK formula * @param MU * mu value of the PTK formula * @param terminalFactor * terminal factor * @param representationIdentifier * the representation on which operate */ public PartialTreeKernel(float LAMBDA, float MU, float terminalFactor, String representationIdentifier) { super(representationIdentifier); this.lambda = LAMBDA; this.lambda2 = LAMBDA * LAMBDA; this.mu = MU; this.terminalFactor = terminalFactor; // this.deltaMatrix = new StaticDeltaMatrix(); } /** * This constructor by default uses lambda=0.4, mu=0.4, terminalFactor=1 */ public PartialTreeKernel(String representationIdentifier) { this(0.4f, 0.4f, 1f, representationIdentifier); } /** * Determine the subtrees (from the two trees) whose root have the same * label. This optimization has been proposed in [Moschitti, EACL 2006]. * * @param a * First Tree * @param b * Second Tree * @return The node pairs having the same label */ private ArrayList<TreeNodePairs> determineSubList(TreeRepresentation a, TreeRepresentation b) { ArrayList<TreeNodePairs> intersect = new ArrayList<TreeNodePairs>(); int i = 0, j = 0, j_old, j_final; int cfr; List<TreeNode> nodesA = a.getOrderedNodeSetByLabel(); List<TreeNode> nodesB = b.getOrderedNodeSetByLabel(); int n_a = nodesA.size(); int n_b = nodesB.size(); while (i < n_a && j < n_b) { if ((cfr = (nodesA.get(i).getContent().getTextFromData() .compareTo(nodesB.get(j).getContent().getTextFromData()))) > 0) j++; else if (cfr < 0) i++; else { j_old = j; do { do { intersect.add(new TreeNodePairs(nodesA.get(i), nodesB .get(j))); deltaMatrix.add(nodesA.get(i).getId(), nodesB.get(j) .getId(), DeltaMatrix.NO_RESPONSE); j++; } while (j < n_b && (nodesA.get(i).getContent().getTextFromData() .equals(nodesB.get(j).getContent() .getTextFromData()))); i++; j_final = j; j = j_old; } while (i < n_a && (nodesA.get(i).getContent().getTextFromData() .equals(nodesB.get(j).getContent() .getTextFromData()))); j = j_final; } } return intersect; } /** * Evaluate the Partial Tree Kernel * * @param a * First tree * @param b * Second Tree * @return Kernel value */ public float evaluateKernelNotNormalize(TreeRepresentation a, TreeRepresentation b) { /* * TODO CHECK FOR MULTITHREADING WITH SIMONE FILICE AND/OR DANILO CROCE * * In order to avoid collisions in the DeltaMatrix when multiple threads * call the kernel at the same time, a specific DeltaMatrix for each * thread should be initialized */ // Initialize the delta function cache deltaMatrix.clear(); /* * Check the size of caching matrices */ int maxBranchingFactor = Math.max(a.getBranchingFactor(), b.getBranchingFactor()); int maxHeight = Math.max(a.getHeight(), b.getHeight()); if (kernel_mat_buffer[0].length < maxBranchingFactor + 1 || DP_buffer.length < maxHeight) { if (maxBranchingFactor >= MAX_CHILDREN) { MAX_CHILDREN = maxBranchingFactor + 1; } if (maxHeight > MAX_RECURSION) MAX_RECURSION = maxHeight; logger.warn("Increasing the size of cache matrices to host trees with height=" + MAX_RECURSION + " and maxBranchingFactor=" + MAX_CHILDREN + ""); kernel_mat_buffer = new float[MAX_RECURSION][MAX_CHILDREN]; DPS_buffer = new float[MAX_RECURSION][MAX_CHILDREN][MAX_CHILDREN]; DP_buffer = new float[MAX_RECURSION][MAX_CHILDREN][MAX_CHILDREN]; } /* * End of the check */ ArrayList<TreeNodePairs> pairs = determineSubList(a, b); float k = 0; for (int i = 0; i < pairs.size(); i++) { k += ptkDeltaFunction(pairs.get(i).getNx(), pairs.get(i).getNz()); } return k; } @JsonIgnore public DeltaMatrix getDeltaMatrix() { return deltaMatrix; } /** * Get the Vertical Decay factor * * @return Vertical Decay factor */ public float getLambda() { return lambda; } /** * Get the Horizontal Decay factor * * @return Horizontal Decay factor */ public float getMu() { return mu; } /** * Get the Terminal Factor * * @return */ public float getTerminalFactor() { return terminalFactor; } @Override public float kernelComputation(TreeRepresentation repA, TreeRepresentation repB) { return (float) evaluateKernelNotNormalize((TreeRepresentation) repA, (TreeRepresentation) repB); } /** * Partial Tree Kernel Delta Function * * @param Nx * root of the first tree * @param Nz * root of the second tree * @return */ private float ptkDeltaFunction(TreeNode Nx, TreeNode Nz) { float sum = 0; if (deltaMatrix.get(Nx.getId(), Nz.getId()) != DeltaMatrix.NO_RESPONSE) return deltaMatrix.get(Nx.getId(), Nz.getId()); // already there if (!Nx.getContent().getTextFromData() .equals(Nz.getContent().getTextFromData())) { deltaMatrix.add(Nx.getId(), Nz.getId(), 0); return 0; } else if (Nx.getNoOfChildren() == 0 || Nz.getNoOfChildren() == 0) { deltaMatrix.add(Nx.getId(), Nz.getId(), mu * lambda2 * terminalFactor); return mu * lambda2 * terminalFactor; } else { float delta_sk = stringKernelDeltaFunction(Nx.getChildren(), Nz.getChildren()); sum = mu * (lambda2 + delta_sk); deltaMatrix.add(Nx.getId(), Nz.getId(), sum); return sum; } } /** * Sets the delta matrix. This method should not be used, as the new KeLP versions * are optimized to automatically set the proper delta matrix * * @param deltaMatrix */ @Deprecated @JsonIgnore public void setDeltaMatrix(DeltaMatrix deltaMatrix) { this.deltaMatrix = deltaMatrix; } public void setLambda(float lambda) { this.lambda = lambda; this.lambda2 = this.lambda * this.lambda; } public void setMu(float mu) { this.mu = mu; } public void setTerminalFactor(float terminalFactor) { this.terminalFactor = terminalFactor; } /** * The String Kernel formulation, that recursively estimates the partial * overlap between children sequences. * * @param Sx * children of the first subtree * @param Sz * children of the second subtree * * @return string kernel score */ private float stringKernelDeltaFunction(ArrayList<TreeNode> Sx, ArrayList<TreeNode> Sz) { int n = Sx.size(); int m = Sz.size(); float[][] DPS = DPS_buffer[recursion_id]; float[][] DP = DP_buffer[recursion_id]; float[] kernel_mat = kernel_mat_buffer[recursion_id]; recursion_id++; int i, j, l, p; float K; p = n; if (m < n) p = m; if (p > maxSubseqLeng) p = maxSubseqLeng; kernel_mat[0] = 0; for (i = 1; i <= n; i++) { for (j = 1; j <= m; j++) { if ((Sx.get(i - 1).getContent().getTextFromData().equals(Sz .get(j - 1).getContent().getTextFromData()))) { DPS[i][j] = ptkDeltaFunction(Sx.get(i - 1), Sz.get(j - 1)); kernel_mat[0] += DPS[i][j]; } else DPS[i][j] = 0; } } for (l = 1; l < p; l++) { kernel_mat[l] = 0; for (j = 0; j <= m; j++) DP[l - 1][j] = 0.0f; for (i = 0; i <= n; i++) DP[i][l - 1] = 0.f; for (i = l; i <= n; i++) for (j = l; j <= m; j++) { DP[i][j] = DPS[i][j] + lambda * DP[i - 1][j] + lambda * DP[i][j - 1] - lambda2 * DP[i - 1][j - 1]; if (Sx.get(i - 1) .getContent() .getTextFromData() .equals(Sz.get(j - 1).getContent() .getTextFromData())) { DPS[i][j] = ptkDeltaFunction(Sx.get(i - 1), Sz.get(j - 1)) * DP[i - 1][j - 1]; kernel_mat[l] += DPS[i][j]; } } } K = 0; for (l = 0; l < p; l++) { K += kernel_mat[l]; } recursion_id--; return K; } /** * @return The maximum length of common subsequences considered in the * recursion. It reflects the maximum branching factor allowed to * the tree fragments. */ public int getMaxSubseqLeng() { return maxSubseqLeng; } /** * @param maxSubseqLeng * The maximum length of common subsequences considered in the * recursion. It reflects the maximum branching factor allowed to * the tree fragments. */ public void setMaxSubseqLeng(int maxSubseqLeng) { this.maxSubseqLeng = maxSubseqLeng; } }
SAG-KeLP/kelp-additional-kernels
src/main/java/it/uniroma2/sag/kelp/kernel/tree/PartialTreeKernel.java
Java
apache-2.0
12,750
package com.vav.Common.Hashing; /** * Created by Vaibhav on 4/14/17. */ public class DirectAddressTable { int [] table; public DirectAddressTable(){ for(int i =0;i<table.length;i++) table[i]=0; table = new int [1000]; } public void insert(int value){ table[value]=value; } public boolean search(int value){ if(table[value]==value){ return true; } return false; } public void delete(int value){ table[value] = 0; } }
vav8085/WarPlan
src/com/vav/Common/Hashing/DirectAddressTable.java
Java
apache-2.0
536
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package io.fares.maven.plugins.design.builder.flattener; import io.fares.maven.plugins.utils.AetherUtil; import org.apache.maven.execution.*; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import static org.junit.Assert.*; import org.junit.Rule; import org.junit.Test; import java.io.File; import java.util.Arrays; import org.apache.maven.plugin.MojoExecution; import org.apache.maven.plugin.testing.MojoRule; import org.apache.maven.plugin.testing.resources.TestResources; import org.apache.maven.plugin.testing.stubs.StubArtifactRepository; import org.apache.maven.project.MavenProject; import org.apache.maven.project.ProjectBuilder; import org.apache.maven.project.ProjectBuildingRequest; import org.apache.maven.project.ProjectBuildingResult; import org.codehaus.plexus.PlexusContainer; import org.eclipse.aether.DefaultRepositorySystemSession; import org.eclipse.aether.internal.impl.DefaultRepositorySystem; import org.eclipse.aether.repository.*; public class FlattenImportPathMojoTest { protected final Logger log = LoggerFactory.getLogger(FlattenImportPathMojoTest.class); @Rule public MojoRule rule = new MojoRule(); @Rule public TestResources resources = new TestResources("src/test/resources/unit", "target/ut/"); /** * @throws Exception if any */ @org.junit.Ignore("Needs more work to make the mocking behave. See the MavenProjectStub") @Test public void testDependencyResolver() throws Exception { File baseDir = resources.getBasedir("flatten/test-dependency-resolver-config"); File pomFile = new File(baseDir, "pom.xml"); PlexusContainer container = rule.getContainer(); // see if we can get localrepo manager from system and add to session DefaultRepositorySystemSession systemSession = new DefaultRepositorySystemSession(); LocalRepository lr = new LocalRepository(new File(baseDir, "repo")); DefaultRepositorySystem system = container.lookup(DefaultRepositorySystem.class); LocalRepositoryManager lrm = system.newLocalRepositoryManager(systemSession, lr); systemSession.setLocalRepositoryManager(lrm); systemSession.setProxySelector(AetherUtil.newProxySelector(baseDir)); MavenExecutionRequest request = new DefaultMavenExecutionRequest(); request.setBaseDirectory(baseDir); request.setLocalRepositoryPath(new File(baseDir, ".m2")); request.setLocalRepository(new StubArtifactRepository(new File(baseDir, ".m2").getCanonicalPath())); ProjectBuildingRequest configuration = request.getProjectBuildingRequest(); configuration.setResolveDependencies(true); configuration.setRepositorySession(systemSession); ProjectBuilder projectBuilder = rule.lookup(ProjectBuilder.class); ProjectBuildingResult projectBuildingResult = projectBuilder.build(pomFile, configuration); MavenProject project = projectBuildingResult.getProject(); MavenExecutionResult result = new DefaultMavenExecutionResult(); MavenSession session = new MavenSession(container, systemSession, request, result); session.setCurrentProject(project); session.setProjects(Arrays.asList(project)); MojoExecution exec = rule.newMojoExecution("flatten"); FlattenImportPathMojo mojo = (FlattenImportPathMojo) rule.lookupConfiguredMojo(session, exec); // set sources dir rule.setVariableValueToObject(mojo, "sourceDirectory", new File(baseDir, "src")); rule.setVariableValueToObject(mojo, "outputDirectory", new File(baseDir, "target")); mojo.execute(); assertNotNull(pomFile); assertTrue(pomFile.exists()); } }
fareliner/design-builder
maven-plugin/src/test/java/io/fares/maven/plugins/design/builder/flattener/FlattenImportPathMojoTest.java
Java
apache-2.0
4,375
package com.mana.innovative.dto.common.payload; import com.mana.innovative.dto.common.CalendarEvent; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlElementWrapper; import java.util.List; /** * Created by IntelliJ IDEA. * * @author Bloom Date: 1/2/13 Time: 4:24 PM * @email arkoghosh @hotmail.com, meankur1@gmail.com * @Copyright * @since: jdk 1.7 */ public class CalendarEventsPayload { /** * The Calendar events. */ private List< CalendarEvent > calendarEvents; /** * The Total count. */ private int totalCount; /** * Gets calendar events. * * @return the calendar events */ @XmlElementWrapper( name = "calendar_events" ) @XmlElement( name = "calendar_event" ) public List< CalendarEvent > getCalendarEvents( ) { return calendarEvents; } /** * Sets calendar events. * * @param calendarEvents the calendar events */ public void setCalendarEvents( final List< CalendarEvent > calendarEvents ) { this.calendarEvents = calendarEvents; } /** * Gets total count. * * @return the total count */ public int getTotalCount( ) { return totalCount; } /** * Sets total count. * * @param totalCount the total count */ public void setTotalCount( final int totalCount ) { this.totalCount = totalCount; } }
arkoghosh11/bloom-test
bloom-dto/src/main/java/com/mana/innovative/dto/common/payload/CalendarEventsPayload.java
Java
apache-2.0
1,444
/* * 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.wrmsr.neurosis.util; public class Box<T> { public final T value; public Box(T value) { this.value = value; } public T getValue() { return value; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; Box box = (Box) o; if (value != null ? !value.equals(box.value) : box.value != null) return false; return true; } @Override public int hashCode() { return value != null ? value.hashCode() : 0; } @Override public String toString() { return getClass().getSimpleName() + "{value=" + value + '}'; } }
wrmsr/neurosis
neurosis-utils/src/main/java/com/wrmsr/neurosis/util/Box.java
Java
apache-2.0
1,287
package com.timefleeting.app; import android.app.ActivityManager; import android.content.Context; import android.content.Intent; import android.util.Log; import java.util.List; public class SystemUtils { public static boolean isAppAlive(Context context, String packageName){ ActivityManager activityManager = (ActivityManager)context.getSystemService(Context.ACTIVITY_SERVICE); List<ActivityManager.RunningAppProcessInfo> processInfos = activityManager.getRunningAppProcesses(); for(int i = 0; i < processInfos.size(); i++){ if(processInfos.get(i).processName.equals(packageName)){ Log.i("NotificationLaunch", String.format("the %s is running, isAppAlive return true", packageName)); return true; } } Log.i("NotificationLaunch", String.format("the %s is not running, isAppAlive return false", packageName)); return false; } }
Nightonke/TimeFleeting
src/com/timefleeting/app/SystemUtils.java
Java
apache-2.0
1,015
/** * 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.component.stax; import org.xml.sax.ContentHandler; import org.apache.camel.CamelContext; import org.apache.camel.Processor; import org.apache.camel.impl.ProcessorEndpoint; import org.apache.camel.spi.Metadata; import org.apache.camel.spi.UriEndpoint; import org.apache.camel.spi.UriPath; import org.apache.camel.util.EndpointHelper; @UriEndpoint(scheme = "stax", syntax = "stax:contentHandlerClass", producerOnly = true, label = "transformation") public class StAXEndpoint extends ProcessorEndpoint { @UriPath @Metadata(required = "true") private String contentHandlerClass; public StAXEndpoint(String endpointUri, CamelContext context) { super(endpointUri, context, null); } public String getContentHandlerClass() { return contentHandlerClass; } public void setContentHandlerClass(String contentHandlerClass) { this.contentHandlerClass = contentHandlerClass; } @Override protected void doStart() throws Exception { super.doStart(); Processor target; if (EndpointHelper.isReferenceParameter(contentHandlerClass)) { ContentHandler handler = EndpointHelper.resolveReferenceParameter(getCamelContext(), contentHandlerClass.substring(1), ContentHandler.class, true); target = new StAXProcessor(handler); } else { Class<ContentHandler> clazz = getCamelContext().getClassResolver().resolveMandatoryClass(contentHandlerClass, ContentHandler.class); target = new StAXProcessor(clazz); } setProcessor(target); } }
ramonmaruko/camel
components/camel-stax/src/main/java/org/apache/camel/component/stax/StAXEndpoint.java
Java
apache-2.0
2,409
/** * 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.processor.async; import org.apache.camel.ContextTestSupport; import org.apache.camel.Exchange; import org.apache.camel.Processor; import org.apache.camel.builder.RouteBuilder; /** * @version */ public class AsyncEndpointFilterTest extends ContextTestSupport { private static String beforeThreadName; private static String afterThreadName; public void testAsyncEndpoint() throws Exception { getMockEndpoint("mock:before").expectedBodiesReceived("Hello Camel"); getMockEndpoint("mock:after").expectedBodiesReceived("Bye Camel"); getMockEndpoint("mock:result").expectedBodiesReceived("Bye Camel"); String reply = template.requestBody("direct:start", "Hello Camel", String.class); assertEquals("Bye Camel", reply); assertMockEndpointsSatisfied(); assertFalse("Should use different threads", beforeThreadName.equalsIgnoreCase(afterThreadName)); } @Override protected RouteBuilder createRouteBuilder() throws Exception { return new RouteBuilder() { @Override public void configure() throws Exception { context.addComponent("async", new MyAsyncComponent()); from("direct:start") .to("mock:before") .to("log:before") .filter(body().contains("Camel")) .process(new Processor() { public void process(Exchange exchange) throws Exception { beforeThreadName = Thread.currentThread().getName(); } }) .to("async:Bye Camel") .process(new Processor() { public void process(Exchange exchange) throws Exception { afterThreadName = Thread.currentThread().getName(); } }) .to("log:after") .to("mock:after") .end() .to("mock:result"); } }; } }
everttigchelaar/camel-svn
camel-core/src/test/java/org/apache/camel/processor/async/AsyncEndpointFilterTest.java
Java
apache-2.0
3,121
package io.jooby.i2413; public class B2413 { private String id; private String name; public B2413(String id, String name) { this.id = id; this.name = name; } 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; } }
jooby-project/jooby
tests/src/test/java/io/jooby/i2413/B2413.java
Java
apache-2.0
395
/* * Copyright (C) 2013 The Rythm Engine project * Gelin Luo <greenlaw110(at)gmail.com> * * 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.rythmengine.resource; import org.rythmengine.extension.ITemplateResourceLoader; import org.rythmengine.utils.IO; import java.net.URL; /** * Created by IntelliJ IDEA. * User: luog * Date: 20/01/12 * Time: 11:25 PM * To change this template use File | Settings | File Templates. */ public class ClasspathTemplateResource extends TemplateResourceBase implements ITemplateResource { private URL url; private String key; public ClasspathTemplateResource(String path) { this(path, null); } public ClasspathTemplateResource(String path, ITemplateResourceLoader loader) { super(loader); ClassLoader cl = loader.getEngine().classLoader(); // strip leading slash so path will work with classes in a JAR file while (path.startsWith("/")) path = path.substring(1); url = cl.getResource(path); if( !isValid() ) { url = cl.getResource( loader.getResourceLoaderRoot() + "/" + path ); } key = path; } @Override public String getKey() { return key; } @Override public String reload() { return IO.readContentAsString(url); } @Override protected long lastModified() { if (getEngine().isProdMode()) return 0; String fileName; if ("file".equals(url.getProtocol())) { fileName = url.getFile(); } else if ("jar".equals(url.getProtocol())) { try { java.net.JarURLConnection jarUrl = (java.net.JarURLConnection) url.openConnection(); fileName = jarUrl.getJarFile().getName(); } catch (Exception e) { return System.currentTimeMillis() + 1; } } else { return System.currentTimeMillis() + 1; } java.io.File file = new java.io.File(fileName); return file.lastModified(); } @Override public boolean isValid() { return null != url; } @Override public boolean equals(Object obj) { if (obj == this) return true; if (obj instanceof ClasspathTemplateResource) { ClasspathTemplateResource that = (ClasspathTemplateResource) obj; return that.getKey().equals(this.getKey()); } return false; } @Override protected long defCheckInterval() { return -1; } @Override protected Long userCheckInterval() { return Long.valueOf(1000 * 5); } @Override public String getSuggestedClassName() { return path2CN(key); } }
alfishe/Rythm
src/main/java/org/rythmengine/resource/ClasspathTemplateResource.java
Java
apache-2.0
3,483
package com.saulpower.GreenWireTest.database; import java.util.List; import de.greenrobot.dao.DaoEnum; import java.util.Map; import java.util.HashMap; import de.greenrobot.dao.DaoException; // THIS CODE IS GENERATED BY greenDAO, DO NOT EDIT. Enable "keep" sections if you want to edit. /** * Entity mapped to table IDENTIFICATION. */ public class Identification extends SyncBase { private transient long personPersonId; private String externalID; private String expiration; private String verifiedByID; private String guid; private String name; private String issuedBy; private String dateVerified; private transient long identificationStudentId; private String tagString; private String dateIssued; private Long tenantID; private transient long saveResultSaveResultId; private String dateLastModified; private String number; private transient long identificationGuardianId; private transient Long syncBaseId; private Boolean isDeleted; private Integer version; private transient long identificationPersonId; private Long id; private String dateCreated; private IdentificationType type; /** Used to resolve relations */ private transient DaoSession daoSession; /** Used for active entity operations. */ private transient IdentificationDao myDao; private Person person; private Long person__resolvedKey; private SaveResult saveResult; private Long saveResult__resolvedKey; private List<Attachment> attachments; private List<CustomValue> customValues; public Identification() { } public Identification(Long id) { this.id = id; setDerivedEntityType(getClass().getCanonicalName()); } Identification(long personPersonId, String externalID, String expiration, String verifiedByID, String guid, String name, String issuedBy, String dateVerified, long identificationStudentId, String tagString, String dateIssued, Long tenantID, long saveResultSaveResultId, String dateLastModified, String number, long identificationGuardianId, Long syncBaseId, Boolean isDeleted, Integer version, long identificationPersonId, Long id, String dateCreated, IdentificationType type) { this.personPersonId = personPersonId; this.externalID = externalID; this.expiration = expiration; this.verifiedByID = verifiedByID; this.guid = guid; this.name = name; this.issuedBy = issuedBy; this.dateVerified = dateVerified; this.identificationStudentId = identificationStudentId; this.tagString = tagString; this.dateIssued = dateIssued; this.tenantID = tenantID; this.saveResultSaveResultId = saveResultSaveResultId; this.dateLastModified = dateLastModified; this.number = number; this.identificationGuardianId = identificationGuardianId; this.syncBaseId = syncBaseId; this.isDeleted = isDeleted; this.version = version; this.identificationPersonId = identificationPersonId; this.id = id; this.dateCreated = dateCreated; this.type = type; } public Identification(long personPersonId, String externalID, String expiration, String verifiedByID, String guid, String name, String issuedBy, String dateVerified, long identificationStudentId, String tagString, String dateIssued, Long tenantID, long saveResultSaveResultId, String dateLastModified, String number, long identificationGuardianId, Boolean isDeleted, Integer version, long identificationPersonId, Long id, String dateCreated, IdentificationType type) { this.personPersonId = personPersonId; this.externalID = externalID; this.expiration = expiration; this.verifiedByID = verifiedByID; this.guid = guid; this.name = name; this.issuedBy = issuedBy; this.dateVerified = dateVerified; this.identificationStudentId = identificationStudentId; this.tagString = tagString; this.dateIssued = dateIssued; this.tenantID = tenantID; this.saveResultSaveResultId = saveResultSaveResultId; this.dateLastModified = dateLastModified; this.number = number; this.identificationGuardianId = identificationGuardianId; this.isDeleted = isDeleted; this.version = version; this.identificationPersonId = identificationPersonId; this.id = id; this.dateCreated = dateCreated; this.type = type; setDerivedEntityType(getClass().getCanonicalName()); } /** called by internal mechanisms, do not call yourself. */ @Override public void __setDaoSession(DaoSession daoSession) { super.__setDaoSession(daoSession); this.daoSession = daoSession; myDao = daoSession != null ? daoSession.getIdentificationDao() : null; } public long getPersonPersonId() { return personPersonId; } public void setPersonPersonId(long personPersonId) { this.personPersonId = personPersonId; } public String getExternalID() { return externalID; } public void setExternalID(String externalID) { this.externalID = externalID; } public String getExpiration() { return expiration; } public void setExpiration(String expiration) { this.expiration = expiration; } public String getVerifiedByID() { return verifiedByID; } public void setVerifiedByID(String verifiedByID) { this.verifiedByID = verifiedByID; } public String getGuid() { return guid; } public void setGuid(String guid) { this.guid = guid; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getIssuedBy() { return issuedBy; } public void setIssuedBy(String issuedBy) { this.issuedBy = issuedBy; } public String getDateVerified() { return dateVerified; } public void setDateVerified(String dateVerified) { this.dateVerified = dateVerified; } public long getIdentificationStudentId() { return identificationStudentId; } public void setIdentificationStudentId(long identificationStudentId) { this.identificationStudentId = identificationStudentId; } public String getTagString() { return tagString; } public void setTagString(String tagString) { this.tagString = tagString; } public String getDateIssued() { return dateIssued; } public void setDateIssued(String dateIssued) { this.dateIssued = dateIssued; } public Long getTenantID() { return tenantID; } public void setTenantID(Long tenantID) { this.tenantID = tenantID; } public long getSaveResultSaveResultId() { return saveResultSaveResultId; } public void setSaveResultSaveResultId(long saveResultSaveResultId) { this.saveResultSaveResultId = saveResultSaveResultId; } public String getDateLastModified() { return dateLastModified; } public void setDateLastModified(String dateLastModified) { this.dateLastModified = dateLastModified; } public String getNumber() { return number; } public void setNumber(String number) { this.number = number; } public long getIdentificationGuardianId() { return identificationGuardianId; } public void setIdentificationGuardianId(long identificationGuardianId) { this.identificationGuardianId = identificationGuardianId; } public Long getSyncBaseId() { return syncBaseId; } public void setSyncBaseId(Long syncBaseId) { this.syncBaseId = syncBaseId; } public Boolean getIsDeleted() { return isDeleted; } public void setIsDeleted(Boolean isDeleted) { this.isDeleted = isDeleted; } public Integer getVersion() { return version; } public void setVersion(Integer version) { this.version = version; } public long getIdentificationPersonId() { return identificationPersonId; } public void setIdentificationPersonId(long identificationPersonId) { this.identificationPersonId = identificationPersonId; } public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getDateCreated() { return dateCreated; } public void setDateCreated(String dateCreated) { this.dateCreated = dateCreated; } public IdentificationType getType() { return type; } public void setType(IdentificationType type) { this.type = type; } public enum IdentificationType implements DaoEnum { DRIVERLICENSE(0), BIRTHCERTIFICATE(1), PASSPORT(2), MILITARYID(3), OTHER(4); private static final Map<Long, IdentificationType> intToTypeMap = new HashMap<Long, IdentificationType>(); static { for (IdentificationType type : IdentificationType.values()) { intToTypeMap.put(type.value, type); } } public static IdentificationType fromInt(long i) { IdentificationType type = intToTypeMap.get(Long.valueOf(i)); return type; } private final long value; private IdentificationType(long value) { this.value = value; } @Override public long getValue() { return value; } } /** To-one relationship, resolved on first access. */ public Person getPerson() { long __key = this.personPersonId; if (person__resolvedKey == null || !person__resolvedKey.equals(__key)) { if (daoSession == null) { throw new DaoException("Entity is detached from DAO context"); } PersonDao targetDao = daoSession.getPersonDao(); Person personNew = targetDao.load(__key); synchronized (this) { person = personNew; person__resolvedKey = __key; } } return person; } public void setPerson(Person person) { if (person == null) { throw new DaoException("To-one property 'personPersonId' has not-null constraint; cannot set to-one to null"); } synchronized (this) { this.person = person; personPersonId = person.getId(); person__resolvedKey = personPersonId; } } /** To-one relationship, resolved on first access. */ public SaveResult getSaveResult() { long __key = this.saveResultSaveResultId; if (saveResult__resolvedKey == null || !saveResult__resolvedKey.equals(__key)) { if (daoSession == null) { throw new DaoException("Entity is detached from DAO context"); } SaveResultDao targetDao = daoSession.getSaveResultDao(); SaveResult saveResultNew = targetDao.load(__key); synchronized (this) { saveResult = saveResultNew; saveResult__resolvedKey = __key; } } return saveResult; } public void setSaveResult(SaveResult saveResult) { if (saveResult == null) { throw new DaoException("To-one property 'saveResultSaveResultId' has not-null constraint; cannot set to-one to null"); } synchronized (this) { this.saveResult = saveResult; saveResultSaveResultId = saveResult.getId(); saveResult__resolvedKey = saveResultSaveResultId; } } /** To-many relationship, resolved on first access (and after reset). Changes to to-many relations are not persisted, make changes to the target entity. */ public List<Attachment> getAttachments() { if (attachments == null) { if (daoSession == null) { throw new DaoException("Entity is detached from DAO context"); } AttachmentDao targetDao = daoSession.getAttachmentDao(); List<Attachment> attachmentsNew = targetDao._queryIdentification_Attachments(id); synchronized (this) { if(attachments == null) { attachments = attachmentsNew; } } } return attachments; } /** Resets a to-many relationship, making the next get call to query for a fresh result. */ public synchronized void resetAttachments() { attachments = null; } /** To-many relationship, resolved on first access (and after reset). Changes to to-many relations are not persisted, make changes to the target entity. */ public List<CustomValue> getCustomValues() { if (customValues == null) { if (daoSession == null) { throw new DaoException("Entity is detached from DAO context"); } CustomValueDao targetDao = daoSession.getCustomValueDao(); List<CustomValue> customValuesNew = targetDao._queryIdentification_CustomValues(id); synchronized (this) { if(customValues == null) { customValues = customValuesNew; } } } return customValues; } /** Resets a to-many relationship, making the next get call to query for a fresh result. */ public synchronized void resetCustomValues() { customValues = null; } /** Convenient call for {@link AbstractDao#delete(Object)}. Entity must attached to an entity context. */ public void delete() { if (myDao == null) { throw new DaoException("Entity is detached from DAO context"); } myDao.delete(this); } /** Convenient call for {@link AbstractDao#update(Object)}. Entity must attached to an entity context. */ public void update() { if (myDao == null) { throw new DaoException("Entity is detached from DAO context"); } myDao.update(this); } /** Convenient call for {@link AbstractDao#refresh(Object)}. Entity must attached to an entity context. */ public void refresh() { if (myDao == null) { throw new DaoException("Entity is detached from DAO context"); } myDao.refresh(this); } }
saulpower/greendaoprotobuf
GreenWireTest/src/main/java/com/saulpower/GreenWireTest/database/Identification.java
Java
apache-2.0
14,585
/** * Licensed to Apereo under one or more contributor license agreements. See the NOTICE file * distributed with this work for additional information regarding copyright ownership. Apereo * 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 the * following location: * * <p>http://www.apache.org/licenses/LICENSE-2.0 * * <p>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.apereo.portal.events.aggr.dao.jpa; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNull; import java.util.Collections; import java.util.List; import org.apereo.portal.concurrency.CallableWithoutResult; import org.apereo.portal.events.aggr.DateDimension; import org.apereo.portal.events.aggr.dao.DateDimensionDao; import org.apereo.portal.events.aggr.dao.TimeDimensionDao; import org.apereo.portal.test.BaseAggrEventsJpaDaoTest; import org.joda.time.DateMidnight; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; /** */ @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(locations = "classpath:jpaAggrEventsTestContext.xml") public class JpaDateTimeDimensionDaoTest extends BaseAggrEventsJpaDaoTest { @Autowired private DateDimensionDao dateDimensionDao; @Autowired private TimeDimensionDao timeDimensionDao; @Test public void testGetMinMaxDateDimension() { this.execute( new CallableWithoutResult() { @Override protected void callWithoutResult() { final DateDimension newestDateDimension = dateDimensionDao.getNewestDateDimension(); assertNull(newestDateDimension); } }); this.execute( new CallableWithoutResult() { @Override protected void callWithoutResult() { final List<DateDimension> dateDimensions = dateDimensionDao.getDateDimensions(); assertEquals(Collections.EMPTY_LIST, dateDimensions); } }); this.executeInTransaction( new CallableWithoutResult() { @Override protected void callWithoutResult() { DateMidnight date = new DateMidnight(2012, 1, 1); for (int i = 0; i < 7; i++) { dateDimensionDao.createDateDimension(date, 0, null); date = date.plusDays(1); } } }); this.execute( new CallableWithoutResult() { @Override protected void callWithoutResult() { DateMidnight date = new DateMidnight(2012, 1, 1); final DateDimension dateDimension = dateDimensionDao.getDateDimensionByDate(date); assertNotNull(dateDimension); } }); this.execute( new CallableWithoutResult() { @Override protected void callWithoutResult() { final List<DateDimension> dateDimensions = dateDimensionDao.getDateDimensions(); assertEquals(7, dateDimensions.size()); } }); this.execute( new CallableWithoutResult() { @Override protected void callWithoutResult() { final DateMidnight start = new DateMidnight(2012, 1, 2); final DateMidnight end = new DateMidnight(2012, 1, 6); final List<DateDimension> dateDimensions = dateDimensionDao.getDateDimensionsBetween(start, end); assertEquals(4, dateDimensions.size()); } }); this.execute( new CallableWithoutResult() { @Override protected void callWithoutResult() { final DateDimension oldestDateDimension = dateDimensionDao.getOldestDateDimension(); assertEquals(2012, oldestDateDimension.getYear()); assertEquals(1, oldestDateDimension.getMonth()); assertEquals(1, oldestDateDimension.getDay()); } }); this.execute( new CallableWithoutResult() { @Override protected void callWithoutResult() { final DateDimension newestDateDimension = dateDimensionDao.getNewestDateDimension(); assertEquals(2012, newestDateDimension.getYear()); assertEquals(1, newestDateDimension.getMonth()); assertEquals(7, newestDateDimension.getDay()); } }); } }
jhelmer-unicon/uPortal
uportal-war/src/test/java/org/apereo/portal/events/aggr/dao/jpa/JpaDateTimeDimensionDaoTest.java
Java
apache-2.0
5,852
package com.example.coolweather.gson; import com.google.gson.annotations.SerializedName; import java.util.List; /** * Created by Wiggins on 2017/6/17. */ public class Weather { public String status; public Basic basic; public Aqi aqi; public Now now; public Suggestion suggestion; @SerializedName("daily_forecast") public List<Forecast> forecastList; }
WigginsW/coolweather
app/src/main/java/com/example/coolweather/gson/Weather.java
Java
apache-2.0
388
/* * 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.kylin.rest.security; import java.io.IOException; import java.sql.SQLException; import org.apache.kylin.common.KylinConfig; import org.apache.kylin.common.util.LocalFileMetadataTestCase; import org.apache.kylin.metadata.MetadataConstants; import org.apache.kylin.metadata.acl.TableACLManager; import org.apache.kylin.query.security.AccessDeniedException; import org.apache.kylin.query.security.QueryACLTestUtil; import org.hamcrest.CoreMatchers; import org.junit.After; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.junit.rules.ExpectedException; import org.springframework.security.authentication.TestingAuthenticationToken; import org.springframework.security.core.context.SecurityContextHolder; public class QueryWithTableACLTest extends LocalFileMetadataTestCase { private static final String PROJECT = "DEFAULT"; private static final String ADMIN = "ADMIN"; private static final String MODELER = "MODELER"; private static final String STREAMING_TABLE = "DEFAULT.STREAMING_TABLE"; @Rule public ExpectedException thrown = ExpectedException.none(); @Before public void setUp() { SecurityContextHolder.getContext().setAuthentication(new TestingAuthenticationToken(false, null)); this.createTestMetadata(); } @Test public void testNormalQuery() throws SQLException { QueryACLTestUtil.setUser(ADMIN); QueryACLTestUtil.mockQuery(PROJECT, "select * from STREAMING_TABLE"); } @Test public void testFailQuery() throws SQLException, IOException { QueryACLTestUtil.setUser(MODELER); QueryACLTestUtil.mockQuery(PROJECT, "select * from STREAMING_TABLE"); QueryACLTestUtil.setUser(ADMIN); TableACLManager.getInstance(KylinConfig.getInstanceFromEnv()).addTableACL(PROJECT, "ADMIN", STREAMING_TABLE, MetadataConstants.TYPE_USER); thrown.expectCause(CoreMatchers.isA(AccessDeniedException.class)); thrown.expectMessage(CoreMatchers.containsString("Query failed.Access table:DEFAULT.STREAMING_TABLE denied")); QueryACLTestUtil.mockQuery(PROJECT, "select * from STREAMING_TABLE"); } @Test public void testFailQueryWithCountStar() throws SQLException, IOException { QueryACLTestUtil.setUser(MODELER); QueryACLTestUtil.mockQuery(PROJECT, "select count(*) from STREAMING_TABLE"); QueryACLTestUtil.setUser(ADMIN); TableACLManager.getInstance(KylinConfig.getInstanceFromEnv()).addTableACL(PROJECT, "ADMIN", STREAMING_TABLE, MetadataConstants.TYPE_USER); thrown.expectCause(CoreMatchers.isA(AccessDeniedException.class)); thrown.expectMessage(CoreMatchers.containsString("Query failed.Access table:DEFAULT.STREAMING_TABLE denied")); QueryACLTestUtil.mockQuery(PROJECT, "select count(*) from STREAMING_TABLE"); } @After public void after() throws Exception { SecurityContextHolder.getContext().setAuthentication(null); this.cleanupTestMetadata(); } }
apache/incubator-kylin
server/src/test/java/org/apache/kylin/rest/security/QueryWithTableACLTest.java
Java
apache-2.0
3,845
/* * Copyright 2017-2022 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with * the License. A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR * CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions * and limitations under the License. */ package com.amazonaws.services.savingsplans.model.transform; import java.math.*; import javax.annotation.Generated; import com.amazonaws.services.savingsplans.model.*; import com.amazonaws.transform.SimpleTypeJsonUnmarshallers.*; import com.amazonaws.transform.*; import com.fasterxml.jackson.core.JsonToken; import static com.fasterxml.jackson.core.JsonToken.*; /** * ListTagsForResourceResult JSON Unmarshaller */ @Generated("com.amazonaws:aws-java-sdk-code-generator") public class ListTagsForResourceResultJsonUnmarshaller implements Unmarshaller<ListTagsForResourceResult, JsonUnmarshallerContext> { public ListTagsForResourceResult unmarshall(JsonUnmarshallerContext context) throws Exception { ListTagsForResourceResult listTagsForResourceResult = new ListTagsForResourceResult(); 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 listTagsForResourceResult; } while (true) { if (token == null) break; if (token == FIELD_NAME || token == START_OBJECT) { if (context.testExpression("tags", targetDepth)) { context.nextToken(); listTagsForResourceResult.setTags(new MapUnmarshaller<String, String>(context.getUnmarshaller(String.class), context .getUnmarshaller(String.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 listTagsForResourceResult; } private static ListTagsForResourceResultJsonUnmarshaller instance; public static ListTagsForResourceResultJsonUnmarshaller getInstance() { if (instance == null) instance = new ListTagsForResourceResultJsonUnmarshaller(); return instance; } }
aws/aws-sdk-java
aws-java-sdk-savingsplans/src/main/java/com/amazonaws/services/savingsplans/model/transform/ListTagsForResourceResultJsonUnmarshaller.java
Java
apache-2.0
2,984
package edu.byui.cs246.scandroid; import java.text.SimpleDateFormat; import java.util.Calendar; /** * Created by admin on 11/2/16. */ //class for storing a single scan public class Scan { private String symbology = ""; //type of barcode, if available private String data = ""; //the actual data represented by the barcode private String timestamp = ""; //a timestamp indicating when the barcode was scanned //init the scan setting only the timestamp public Scan() {setTimestamp();} //init the scan using a string for data and generate a timestamp public Scan(String data) { this.data = data; setTimestamp(); } //constructor - scan is used here as a noun //init the scan using strings for data and symbology and generate a timestamp public Scan(String data, String symbology) { this.data = data; this.symbology = symbology; setTimestamp(); } //getters for data, symbology and timestamp public String getData() { return data; } public String getSymbology() { return symbology; } public String getTimestamp() { return timestamp; } //private setter for timestamp private void setTimestamp() { this.timestamp = new SimpleDateFormat("yyyyMMdd.HHmmss").format(Calendar.getInstance().getTime()); } }
scanalyzer/ScAndroid
app/src/main/java/edu/byui/cs246/scandroid/Scan.java
Java
apache-2.0
1,333
/* * (C) Copyright 2016 Kurento (http://kurento.org/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package org.kurento.test.browser; import static java.lang.System.currentTimeMillis; import static java.lang.Thread.sleep; import static java.util.concurrent.TimeUnit.SECONDS; import static org.kurento.commons.PropertiesManager.getProperty; import static org.kurento.test.config.TestConfiguration.DOCKER_NODE_CHROME_IMAGE_DEFAULT; import static org.kurento.test.config.TestConfiguration.DOCKER_NODE_CHROME_IMAGE_PROPERTY; import static org.kurento.test.config.TestConfiguration.DOCKER_NODE_FIREFOX_IMAGE_DEFAULT; import static org.kurento.test.config.TestConfiguration.DOCKER_NODE_FIREFOX_IMAGE_PROPERTY; import static org.kurento.test.config.TestConfiguration.SELENIUM_MAX_DRIVER_ERROR_DEFAULT; import static org.kurento.test.config.TestConfiguration.SELENIUM_MAX_DRIVER_ERROR_PROPERTY; import static org.kurento.test.config.TestConfiguration.SELENIUM_RECORD_DEFAULT; import static org.kurento.test.config.TestConfiguration.SELENIUM_RECORD_PROPERTY; import static org.kurento.test.config.TestConfiguration.TEST_SELENIUM_DNAT; import static org.kurento.test.config.TestConfiguration.TEST_SELENIUM_DNAT_DEFAULT; import java.io.File; import java.io.IOException; import java.net.ConnectException; import java.net.HttpURLConnection; import java.net.URL; import java.nio.file.Files; import java.nio.file.Path; import java.util.Random; import java.util.concurrent.Callable; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; import java.util.concurrent.ExecutionException; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.Future; import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeoutException; import org.kurento.commons.exception.KurentoException; import org.kurento.test.base.KurentoTest; import org.kurento.test.docker.Docker; import org.openqa.selenium.remote.DesiredCapabilities; import org.openqa.selenium.remote.RemoteWebDriver; import org.openqa.selenium.remote.SessionId; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class DockerBrowserManager { public static final int REMOTE_WEB_DRIVER_CREATION_MAX_RETRIES = 3; private static final int REMOTE_WEB_DRIVER_CREATION_TIMEOUT_S = 300; private static final int WAIT_URL_POLL_TIME_MS = 200; private static final int WAIT_URL_TIMEOUT_SEC = 10; private static Logger log = LoggerFactory.getLogger(DockerBrowserManager.class); private class DockerBrowser { private String id; private String browserContainerName; private String browserContainerIp; private DesiredCapabilities capabilities; private RemoteWebDriver driver; public DockerBrowser(String id, DesiredCapabilities capabilities) { this.id = id; this.capabilities = capabilities; calculateContainerNames(); } private void calculateContainerNames() { browserContainerName = id; if (docker.isRunningInContainer()) { String containerName = docker.getContainerName(); browserContainerName = containerName + "-" + browserContainerName + "-" + KurentoTest.getTestClassName() + "-" + new Random().nextInt(1000); } } public void create() { String nodeImageId = calculateBrowserImageName(capabilities); BrowserType type = BrowserType.valueOf(capabilities.getBrowserName().toUpperCase()); int numRetries = 0; do { try { Boolean kmsSelenium = false; if (getProperty(TEST_SELENIUM_DNAT) != null && getProperty(TEST_SELENIUM_DNAT, TEST_SELENIUM_DNAT_DEFAULT)) { kmsSelenium = true; } if (kmsSelenium) { browserContainerIp = docker.generateIpAddressForContainer(); docker.startAndWaitNode(browserContainerName, type, browserContainerName, nodeImageId, record, browserContainerIp); } else { docker.startAndWaitNode(browserContainerName, type, browserContainerName, nodeImageId, record); browserContainerIp = docker.inspectContainer(browserContainerName).getNetworkSettings().getNetworks() .values().iterator().next().getIpAddress(); } String driverUrl = String.format("http://%s:4444/wd/hub", browserContainerIp); waitForUrl(driverUrl); createAndWaitRemoteDriver(driverUrl, capabilities); } catch (TimeoutException e) { if (numRetries == REMOTE_WEB_DRIVER_CREATION_MAX_RETRIES) { throw new KurentoException("Timeout of " + REMOTE_WEB_DRIVER_CREATION_TIMEOUT_S * REMOTE_WEB_DRIVER_CREATION_MAX_RETRIES + " seconds trying to create a RemoteWebDriver after" + REMOTE_WEB_DRIVER_CREATION_MAX_RETRIES + "retries"); } log.warn("Timeout of {} seconds creating RemoteWebDriver. Retrying {}...", REMOTE_WEB_DRIVER_CREATION_TIMEOUT_S, numRetries); docker.stopAndRemoveContainer(browserContainerName, record); browserContainerName += "r"; capabilities.setCapability("applicationName", browserContainerName); numRetries++; } } while (driver == null); log.debug("RemoteWebDriver for browser {} created (Version={}, Capabilities={})", id, driver.getCapabilities().getVersion(), driver.getCapabilities()); } public void waitForUrl(String url) { boolean urlAvailable = false; long timeoutMs = currentTimeMillis() + SECONDS.toMillis(WAIT_URL_TIMEOUT_SEC); do { try { if (currentTimeMillis() > timeoutMs) { throw new KurentoException("Timeout of " + WAIT_URL_TIMEOUT_SEC + " seconds waiting for URL " + url); } HttpURLConnection connection = (HttpURLConnection) new URL(url).openConnection(); connection.setRequestMethod("HEAD"); int responseCode = connection.getResponseCode(); urlAvailable = responseCode >= 200 && responseCode < 500; if (!urlAvailable) { log.debug("URL {} is not still available (response {}) ... waiting {} ms", url, responseCode, WAIT_URL_POLL_TIME_MS); sleep(WAIT_URL_POLL_TIME_MS); } } catch (ConnectException e) { log.trace("{} is not yet available", url); } catch (IOException | InterruptedException e) { log.error("Exception waiting for url {}", url, e); } } while (!urlAvailable); } private void createAndWaitRemoteDriver(final String driverUrl, final DesiredCapabilities capabilities) throws TimeoutException { log.debug("Creating remote driver for browser {} in hub {}", id, driverUrl); int timeoutSeconds = getProperty(SELENIUM_MAX_DRIVER_ERROR_PROPERTY, SELENIUM_MAX_DRIVER_ERROR_DEFAULT); long timeoutMs = System.currentTimeMillis() + TimeUnit.SECONDS.toMillis(timeoutSeconds); do { Future<RemoteWebDriver> driverFuture = null; try { driverFuture = exec.submit(new Callable<RemoteWebDriver>() { @Override public RemoteWebDriver call() throws Exception { return new RemoteWebDriver(new URL(driverUrl), capabilities); } }); RemoteWebDriver remoteDriver; remoteDriver = driverFuture.get(REMOTE_WEB_DRIVER_CREATION_TIMEOUT_S, TimeUnit.SECONDS); SessionId sessionId = remoteDriver.getSessionId(); log.debug("Created selenium session {} for browser {}", sessionId, id); driver = remoteDriver; } catch (TimeoutException e) { driverFuture.cancel(true); throw e; } catch (InterruptedException e) { throw new RuntimeException("Interrupted exception waiting for RemoteWebDriver", e); } catch (ExecutionException e) { log.warn("Exception creating RemoveWebDriver", e); // Check timeout if (System.currentTimeMillis() > timeoutMs) { throw new KurentoException( "Timeout of " + timeoutSeconds + " seconds waiting to create a RemoteWebDriver", e.getCause()); } log.debug("Exception creating RemoteWebDriver for browser \"{}\". Retrying...", id, e.getCause()); // Poll time try { Thread.sleep(500); } catch (InterruptedException t) { Thread.currentThread().interrupt(); return; } } } while (driver == null); } public RemoteWebDriver getRemoteWebDriver() { return driver; } public void close() { downloadLogsForContainer(browserContainerName, id); docker.stopAndRemoveContainer(browserContainerName, record); } } private Docker docker = Docker.getSingleton(); private ExecutorService exec = Executors.newFixedThreadPool(10); private ConcurrentMap<String, DockerBrowser> browsers = new ConcurrentHashMap<>(); private boolean record; private Path downloadLogsPath; public DockerBrowserManager() { docker = Docker.getSingleton(); record = getProperty(SELENIUM_RECORD_PROPERTY, SELENIUM_RECORD_DEFAULT); } public void setDownloadLogsPath(Path path) { this.downloadLogsPath = path; } public RemoteWebDriver createDockerDriver(String id, DesiredCapabilities capabilities) { DockerBrowser browser = new DockerBrowser(id, capabilities); if (browsers.putIfAbsent(id, browser) != null) { throw new KurentoException("Browser with id " + id + " already exists"); } browser.create(); return browser.getRemoteWebDriver(); } public void closeDriver(String id) { DockerBrowser browser = browsers.remove(id); if (browser == null) { log.warn("Browser " + id + " does not exists"); return; } browser.close(); } private String calculateBrowserImageName(DesiredCapabilities capabilities) { String browserName = capabilities.getBrowserName(); if (browserName.equals(DesiredCapabilities.chrome().getBrowserName())) { // Chrome return getProperty(DOCKER_NODE_CHROME_IMAGE_PROPERTY, DOCKER_NODE_CHROME_IMAGE_DEFAULT); } else if (browserName.equals(DesiredCapabilities.firefox().getBrowserName())) { // Firefox return getProperty(DOCKER_NODE_FIREFOX_IMAGE_PROPERTY, DOCKER_NODE_FIREFOX_IMAGE_DEFAULT); } else { throw new RuntimeException( "Browser " + browserName + " is not supported currently for Docker scope"); } } private void downloadLogsForContainer(String container, String logName) { if (downloadLogsPath != null) { try { String logFileName = new File(KurentoTest.getDefaultOutputFile("-" + logName + "-container.log")) .getAbsolutePath(); Path logFile = downloadLogsPath.resolve(logFileName); if (Files.exists(logFile.getParent())) { Files.createDirectories(logFile.getParent()); } log.debug("Downloading log for container {} in file {}", container, logFile.toAbsolutePath()); docker.downloadLog(container, logFile); } catch (IOException e) { log.warn("Exception writing logs for container {}", container, e); } } } }
Kurento/kurento-java
kurento-integration-tests/kurento-test/src/main/java/org/kurento/test/browser/DockerBrowserManager.java
Java
apache-2.0
12,001
/* * Copyright (C) 2018 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License */ package com.android.tools.build.bundletool.splitters; import static com.android.tools.build.bundletool.model.BundleModule.DEX_DIRECTORY; import static com.android.tools.build.bundletool.model.utils.TargetingProtoUtils.sdkVersionFrom; import static com.android.tools.build.bundletool.model.utils.TargetingProtoUtils.sdkVersionTargeting; import static com.android.tools.build.bundletool.model.utils.TargetingProtoUtils.variantTargeting; import static com.android.tools.build.bundletool.model.utils.Versions.ANDROID_Q_API_VERSION; import static com.google.common.collect.ImmutableSet.toImmutableSet; import com.android.bundle.Targeting.VariantTargeting; import com.android.tools.build.bundletool.model.BundleModule; import com.android.tools.build.bundletool.model.ModuleEntry; import com.google.common.collect.ImmutableSet; import java.util.stream.Stream; /** Generates variant targetings based on compression of dex files. */ public final class DexCompressionVariantGenerator implements BundleModuleVariantGenerator { private final ApkGenerationConfiguration apkGenerationConfiguration; public DexCompressionVariantGenerator(ApkGenerationConfiguration apkGenerationConfiguration) { this.apkGenerationConfiguration = apkGenerationConfiguration; } @Override public Stream<VariantTargeting> generate(BundleModule module) { if (!apkGenerationConfiguration.getEnableDexCompressionSplitter() || apkGenerationConfiguration.isForInstantAppVariants()) { return Stream.of(); } ImmutableSet<ModuleEntry> dexEntries = module.getEntries().stream() .filter(entry -> entry.getPath().startsWith(DEX_DIRECTORY)) .collect(toImmutableSet()); if (dexEntries.isEmpty()) { return Stream.of(); } // Uncompressed dex are supported starting from Android P, but only starting from Android Q the // performance impact is negligible compared to a compressed dex. return Stream.of(variantTargeting(sdkVersionTargeting(sdkVersionFrom(ANDROID_Q_API_VERSION)))); } }
google/bundletool
src/main/java/com/android/tools/build/bundletool/splitters/DexCompressionVariantGenerator.java
Java
apache-2.0
2,661
package io.datakernel.http; import io.datakernel.eventloop.Eventloop; import io.datakernel.promise.Promises; import io.datakernel.test.TestUtils; import io.datakernel.test.rules.ByteBufRule; import io.datakernel.test.rules.EventloopRule; import org.junit.Before; import org.junit.ClassRule; import org.junit.Test; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.IOException; import static io.datakernel.promise.TestUtils.await; import static java.nio.charset.StandardCharsets.UTF_8; public class AsyncHttpServerClientBreakConnectionTest { private final Logger logger = LoggerFactory.getLogger(AsyncHttpServerClientBreakConnectionTest.class); private final int FREE_PORT = TestUtils.getFreePort(); @ClassRule public static final EventloopRule eventloopRule = new EventloopRule(); @ClassRule public static final ByteBufRule bufRule = new ByteBufRule(); private AsyncHttpServer server; private AsyncHttpClient client; private Eventloop eventloop = Eventloop.getCurrentEventloop(); @Before public void init() throws IOException { server = AsyncHttpServer.create(eventloop, request -> { logger.info("Closing server..."); eventloop.post(() -> server.close().whenComplete(() -> logger.info("Server Closed"))); return Promises.delay(100L, HttpResponse.ok200() .withBody("Hello World".getBytes()) ); }) .withListenPort(FREE_PORT) .withAcceptOnce(); client = AsyncHttpClient.create(eventloop); server.listen(); } @Test public void testBreakConnection() { await(client.request( HttpRequest.post("http://127.0.0.1:" + FREE_PORT) .withBody("Hello World".getBytes())) .map(response -> response.loadBody() .map(body -> body.getString(UTF_8)))); } }
softindex/datakernel
core-http/src/test/java/io/datakernel/http/AsyncHttpServerClientBreakConnectionTest.java
Java
apache-2.0
1,778
package com.kailash.tutorial.swing.ch22; public interface StringListener { void textEmitted(String text); }
kvasani/JavaGUI
src/main/java/com/kailash/tutorial/swing/ch22/StringListener.java
Java
apache-2.0
113
/* * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one * or more contributor license agreements. Licensed under the Elastic License; * you may not use this file except in compliance with the Elastic License. */ package org.elasticsearch.xpack.runtimefields.mapper; import org.apache.lucene.document.StoredField; import org.apache.lucene.index.DirectoryReader; import org.apache.lucene.index.LeafReaderContext; import org.apache.lucene.index.RandomIndexWriter; import org.apache.lucene.search.Collector; import org.apache.lucene.search.IndexSearcher; import org.apache.lucene.search.LeafCollector; import org.apache.lucene.search.MatchAllDocsQuery; import org.apache.lucene.search.Query; import org.apache.lucene.search.Scorable; import org.apache.lucene.search.ScoreMode; import org.apache.lucene.search.Sort; import org.apache.lucene.search.SortField; import org.apache.lucene.search.TopFieldDocs; import org.apache.lucene.store.Directory; import org.apache.lucene.util.BytesRef; import org.elasticsearch.Version; import org.elasticsearch.common.lucene.search.function.ScriptScoreQuery; import org.elasticsearch.common.settings.Settings; import org.elasticsearch.index.fielddata.ScriptDocValues; import org.elasticsearch.index.fielddata.SortedNumericDoubleValues; import org.elasticsearch.index.mapper.MappedFieldType; import org.elasticsearch.index.query.SearchExecutionContext; import org.elasticsearch.plugins.ScriptPlugin; import org.elasticsearch.script.ScoreScript; import org.elasticsearch.script.Script; import org.elasticsearch.script.ScriptContext; import org.elasticsearch.script.ScriptEngine; import org.elasticsearch.script.ScriptModule; import org.elasticsearch.script.ScriptService; import org.elasticsearch.script.ScriptType; import org.elasticsearch.search.MultiValueMode; import org.elasticsearch.xpack.runtimefields.RuntimeFields; import org.elasticsearch.xpack.runtimefields.fielddata.DoubleScriptFieldData; import java.io.IOException; import java.util.ArrayList; import java.util.Collection; import java.util.List; import java.util.Map; import java.util.Set; import static java.util.Collections.emptyMap; import static org.hamcrest.Matchers.equalTo; public class DoubleScriptFieldTypeTests extends AbstractNonTextScriptFieldTypeTestCase { public void testFormat() throws IOException { assertThat(simpleMappedFieldType().docValueFormat("#.0", null).format(1), equalTo("1.0")); assertThat(simpleMappedFieldType().docValueFormat("#.0", null).format(1.2), equalTo("1.2")); assertThat(simpleMappedFieldType().docValueFormat("#,##0.##", null).format(11), equalTo("11")); assertThat(simpleMappedFieldType().docValueFormat("#,##0.##", null).format(1123), equalTo("1,123")); assertThat(simpleMappedFieldType().docValueFormat("#,##0.00", null).format(1123), equalTo("1,123.00")); assertThat(simpleMappedFieldType().docValueFormat("#,##0.00", null).format(1123.1), equalTo("1,123.10")); } @Override public void testDocValues() throws IOException { try (Directory directory = newDirectory(); RandomIndexWriter iw = new RandomIndexWriter(random(), directory)) { iw.addDocument(List.of(new StoredField("_source", new BytesRef("{\"foo\": [1.0]}")))); iw.addDocument(List.of(new StoredField("_source", new BytesRef("{\"foo\": [3.14, 1.4]}")))); List<Double> results = new ArrayList<>(); try (DirectoryReader reader = iw.getReader()) { IndexSearcher searcher = newSearcher(reader); DoubleScriptFieldType ft = build("add_param", Map.of("param", 1)); DoubleScriptFieldData ifd = ft.fielddataBuilder("test", mockContext()::lookup).build(null, null); searcher.search(new MatchAllDocsQuery(), new Collector() { @Override public ScoreMode scoreMode() { return ScoreMode.COMPLETE_NO_SCORES; } @Override public LeafCollector getLeafCollector(LeafReaderContext context) { SortedNumericDoubleValues dv = ifd.load(context).getDoubleValues(); return new LeafCollector() { @Override public void setScorer(Scorable scorer) {} @Override public void collect(int doc) throws IOException { if (dv.advanceExact(doc)) { for (int i = 0; i < dv.docValueCount(); i++) { results.add(dv.nextValue()); } } } }; } }); assertThat(results, equalTo(List.of(2.0, 2.4, 4.140000000000001))); } } } @Override public void testSort() throws IOException { try (Directory directory = newDirectory(); RandomIndexWriter iw = new RandomIndexWriter(random(), directory)) { iw.addDocument(List.of(new StoredField("_source", new BytesRef("{\"foo\": [1.1]}")))); iw.addDocument(List.of(new StoredField("_source", new BytesRef("{\"foo\": [4.2]}")))); iw.addDocument(List.of(new StoredField("_source", new BytesRef("{\"foo\": [2.1]}")))); try (DirectoryReader reader = iw.getReader()) { IndexSearcher searcher = newSearcher(reader); DoubleScriptFieldData ifd = simpleMappedFieldType().fielddataBuilder("test", mockContext()::lookup).build(null, null); SortField sf = ifd.sortField(null, MultiValueMode.MIN, null, false); TopFieldDocs docs = searcher.search(new MatchAllDocsQuery(), 3, new Sort(sf)); assertThat(reader.document(docs.scoreDocs[0].doc).getBinaryValue("_source").utf8ToString(), equalTo("{\"foo\": [1.1]}")); assertThat(reader.document(docs.scoreDocs[1].doc).getBinaryValue("_source").utf8ToString(), equalTo("{\"foo\": [2.1]}")); assertThat(reader.document(docs.scoreDocs[2].doc).getBinaryValue("_source").utf8ToString(), equalTo("{\"foo\": [4.2]}")); } } } @Override public void testUsedInScript() throws IOException { try (Directory directory = newDirectory(); RandomIndexWriter iw = new RandomIndexWriter(random(), directory)) { iw.addDocument(List.of(new StoredField("_source", new BytesRef("{\"foo\": [1.1]}")))); iw.addDocument(List.of(new StoredField("_source", new BytesRef("{\"foo\": [4.2]}")))); iw.addDocument(List.of(new StoredField("_source", new BytesRef("{\"foo\": [2.1]}")))); try (DirectoryReader reader = iw.getReader()) { IndexSearcher searcher = newSearcher(reader); SearchExecutionContext searchContext = mockContext(true, simpleMappedFieldType()); assertThat(searcher.count(new ScriptScoreQuery(new MatchAllDocsQuery(), new Script("test"), new ScoreScript.LeafFactory() { @Override public boolean needs_score() { return false; } @Override public ScoreScript newInstance(LeafReaderContext ctx) { return new ScoreScript(Map.of(), searchContext.lookup(), ctx) { @Override public double execute(ExplanationHolder explanation) { ScriptDocValues.Doubles doubles = (ScriptDocValues.Doubles) getDoc().get("test"); return doubles.get(0); } }; } }, 2.5f, "test", 0, Version.CURRENT)), equalTo(1)); } } } @Override public void testExistsQuery() throws IOException { try (Directory directory = newDirectory(); RandomIndexWriter iw = new RandomIndexWriter(random(), directory)) { iw.addDocument(List.of(new StoredField("_source", new BytesRef("{\"foo\": [1]}")))); iw.addDocument(List.of(new StoredField("_source", new BytesRef("{\"foo\": []}")))); try (DirectoryReader reader = iw.getReader()) { IndexSearcher searcher = newSearcher(reader); assertThat(searcher.count(simpleMappedFieldType().existsQuery(mockContext())), equalTo(1)); } } } @Override public void testRangeQuery() throws IOException { try (Directory directory = newDirectory(); RandomIndexWriter iw = new RandomIndexWriter(random(), directory)) { iw.addDocument(List.of(new StoredField("_source", new BytesRef("{\"foo\": [1]}")))); iw.addDocument(List.of(new StoredField("_source", new BytesRef("{\"foo\": [2]}")))); iw.addDocument(List.of(new StoredField("_source", new BytesRef("{\"foo\": [2.5]}")))); try (DirectoryReader reader = iw.getReader()) { IndexSearcher searcher = newSearcher(reader); MappedFieldType ft = simpleMappedFieldType(); assertThat(searcher.count(ft.rangeQuery("2", "3", true, true, null, null, null, mockContext())), equalTo(2)); assertThat(searcher.count(ft.rangeQuery(2, 3, true, true, null, null, null, mockContext())), equalTo(2)); assertThat(searcher.count(ft.rangeQuery(1.1, 3, true, true, null, null, null, mockContext())), equalTo(2)); assertThat(searcher.count(ft.rangeQuery(1.1, 3, false, true, null, null, null, mockContext())), equalTo(2)); assertThat(searcher.count(ft.rangeQuery(2, 3, false, true, null, null, null, mockContext())), equalTo(1)); assertThat(searcher.count(ft.rangeQuery(2.5, 3, true, true, null, null, null, mockContext())), equalTo(1)); assertThat(searcher.count(ft.rangeQuery(2.5, 3, false, true, null, null, null, mockContext())), equalTo(0)); } } } @Override protected Query randomRangeQuery(MappedFieldType ft, SearchExecutionContext ctx) { return ft.rangeQuery(randomLong(), randomLong(), randomBoolean(), randomBoolean(), null, null, null, ctx); } @Override public void testTermQuery() throws IOException { try (Directory directory = newDirectory(); RandomIndexWriter iw = new RandomIndexWriter(random(), directory)) { iw.addDocument(List.of(new StoredField("_source", new BytesRef("{\"foo\": [1]}")))); iw.addDocument(List.of(new StoredField("_source", new BytesRef("{\"foo\": [2]}")))); try (DirectoryReader reader = iw.getReader()) { IndexSearcher searcher = newSearcher(reader); assertThat(searcher.count(simpleMappedFieldType().termQuery("1", mockContext())), equalTo(1)); assertThat(searcher.count(simpleMappedFieldType().termQuery(1, mockContext())), equalTo(1)); assertThat(searcher.count(simpleMappedFieldType().termQuery(1.1, mockContext())), equalTo(0)); assertThat(searcher.count(build("add_param", Map.of("param", 1)).termQuery(2, mockContext())), equalTo(1)); } } } @Override protected Query randomTermQuery(MappedFieldType ft, SearchExecutionContext ctx) { return ft.termQuery(randomLong(), ctx); } @Override public void testTermsQuery() throws IOException { try (Directory directory = newDirectory(); RandomIndexWriter iw = new RandomIndexWriter(random(), directory)) { iw.addDocument(List.of(new StoredField("_source", new BytesRef("{\"foo\": [1]}")))); iw.addDocument(List.of(new StoredField("_source", new BytesRef("{\"foo\": [2.1]}")))); try (DirectoryReader reader = iw.getReader()) { IndexSearcher searcher = newSearcher(reader); assertThat(searcher.count(simpleMappedFieldType().termsQuery(List.of("1"), mockContext())), equalTo(1)); assertThat(searcher.count(simpleMappedFieldType().termsQuery(List.of(1), mockContext())), equalTo(1)); assertThat(searcher.count(simpleMappedFieldType().termsQuery(List.of(1.1), mockContext())), equalTo(0)); assertThat(searcher.count(simpleMappedFieldType().termsQuery(List.of(1.1, 2.1), mockContext())), equalTo(1)); assertThat(searcher.count(simpleMappedFieldType().termsQuery(List.of(2.1, 1), mockContext())), equalTo(2)); } } } @Override protected Query randomTermsQuery(MappedFieldType ft, SearchExecutionContext ctx) { return ft.termsQuery(List.of(randomLong()), ctx); } @Override protected DoubleScriptFieldType simpleMappedFieldType() throws IOException { return build("read_foo", Map.of()); } @Override protected MappedFieldType loopFieldType() throws IOException { return build("loop", Map.of()); } @Override protected String typeName() { return "double"; } private static DoubleScriptFieldType build(String code, Map<String, Object> params) throws IOException { return build(new Script(ScriptType.INLINE, "test", code, params)); } private static DoubleScriptFieldType build(Script script) throws IOException { ScriptPlugin scriptPlugin = new ScriptPlugin() { @Override public ScriptEngine getScriptEngine(Settings settings, Collection<ScriptContext<?>> contexts) { return new ScriptEngine() { @Override public String getType() { return "test"; } @Override public Set<ScriptContext<?>> getSupportedContexts() { return Set.of(DoubleFieldScript.CONTEXT); } @Override public <FactoryType> FactoryType compile( String name, String code, ScriptContext<FactoryType> context, Map<String, String> params ) { @SuppressWarnings("unchecked") FactoryType factory = (FactoryType) factory(code); return factory; } private DoubleFieldScript.Factory factory(String code) { switch (code) { case "read_foo": return (fieldName, params, lookup) -> (ctx) -> new DoubleFieldScript(fieldName, params, lookup, ctx) { @Override public void execute() { for (Object foo : (List<?>) lookup.source().get("foo")) { emit(((Number) foo).doubleValue()); } } }; case "add_param": return (fieldName, params, lookup) -> (ctx) -> new DoubleFieldScript(fieldName, params, lookup, ctx) { @Override public void execute() { for (Object foo : (List<?>) lookup.source().get("foo")) { emit(((Number) foo).doubleValue() + ((Number) getParams().get("param")).doubleValue()); } } }; case "loop": return (fieldName, params, lookup) -> { // Indicate that this script wants the field call "test", which *is* the name of this field lookup.forkAndTrackFieldReferences("test"); throw new IllegalStateException("shoud have thrown on the line above"); }; default: throw new IllegalArgumentException("unsupported script [" + code + "]"); } } }; } }; ScriptModule scriptModule = new ScriptModule(Settings.EMPTY, List.of(scriptPlugin, new RuntimeFields())); try (ScriptService scriptService = new ScriptService(Settings.EMPTY, scriptModule.engines, scriptModule.contexts)) { DoubleFieldScript.Factory factory = scriptService.compile(script, DoubleFieldScript.CONTEXT); return new DoubleScriptFieldType("test", factory, script, emptyMap(), (b, d) -> {}); } } }
nknize/elasticsearch
x-pack/plugin/runtime-fields/src/test/java/org/elasticsearch/xpack/runtimefields/mapper/DoubleScriptFieldTypeTests.java
Java
apache-2.0
17,055
/* * Created on Sep 16, 2009 * * 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. * * Copyright @2009-2013 the original author or authors. */ package org.fest.assertions; /** * Test case for implementations of {@code contains}. * * @author Alex Ruiz */ public interface GroupAssert_contains_TestCase { void should_pass_if_actual_contains_given_value(); void should_pass_if_actual_contains_given_values(); void should_fail_if_actual_is_null(); void should_fail_and_display_description_if_actual_is_null(); void should_throw_error_if_expected_is_null(); void should_fail_if_actual_does_not_contain_given_values(); void should_fail_and_display_description_if_actual_does_not_contain_given_values(); void should_fail_with_custom_message_if_actual_does_not_contain_given_values(); void should_fail_with_custom_message_ignoring_description_if_actual_does_not_contain_given_values(); }
alexruiz/fest-assert-1.x
src/test/java/org/fest/assertions/GroupAssert_contains_TestCase.java
Java
apache-2.0
1,409
package strategy.compare; import filecomparator.helper.FileHelper; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import java.util.Comparator; /** * * @author panagiotis */ public class DefaultCompareStrategyImpl extends AbstractCompareStrategy{ @Override public void compare(FileHelper fileHelper) throws IOException{ Comparator<String> comparator = new Comparator<String>() { @Override public int compare(String r1, String r2){ return r1.compareTo(r2);}}; File smallerFile = fileHelper.getSmallerSortedFile(); File largerFile = fileHelper.getLargerSortedFile(); File outputFile = fileHelper.getOutputFile(); outputFile.getParentFile().mkdirs(); outputFile.createNewFile(); OutputStreamWriter outputWriter = new OutputStreamWriter(new FileOutputStream(outputFile, true), "UTF-8"); BufferedWriter fbw = new BufferedWriter(outputWriter); //Splitting files according to size and keeping in memory indexing would be better? //TODO test split files and indexing BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(smallerFile), "UTF8")); String line; while ((line = br.readLine()) != null) { if(line.trim().isEmpty()) continue; BufferedReader br1 = new BufferedReader(new InputStreamReader(new FileInputStream(largerFile), "UTF8")); String line1; while ((line1 = br1.readLine()) != null) { int comparisonResult = comparator.compare(line,line1); if( comparisonResult == 0){ fbw.append(line); fbw.newLine(); br1.close(); break; }else if( comparisonResult > 0){ continue; }else{ br1.close(); break; } //if(br1.)br1.close(); } } fbw.close(); br.close(); } }
psofiadis/filecomparator
filecomparator/src/strategy/compare/DefaultCompareStrategyImpl.java
Java
apache-2.0
2,356
package com.orionplatform.admin.usermanagement.userdetails.tasks; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import com.orionplatform.calendar.CalendarService; import com.orionplatform.calendar.datetime.DateTime; import com.orionplatform.core.abstraction.Orion; import com.orionplatform.data.data_access.user.authentication.OrionUserLoginsDAO; public class GetUserLoginDatesAndNumberOfLoginsForDateTask extends Orion { public static synchronized List<List<Long>> run(String userID, List<DateTime> loginDateTimes) { List<DateTime> sortedLoginDateTimes = CalendarService.sortDateTimes(loginDateTimes); List<List<Long>> loginDatesToNumberOfLogins = new ArrayList<List<Long>>(); for(DateTime datetime : sortedLoginDateTimes) { long numberOfLoginsForDate = OrionUserLoginsDAO.getNumberOfUserLoginsByUserIDAndDate(userID, datetime.getDate().getDateStringSplitByHyphensYearFirst()); loginDatesToNumberOfLogins.add(Arrays.asList(CalendarService.convertDateTimeToEpochMilliseconds(datetime), numberOfLoginsForDate)); } return loginDatesToNumberOfLogins; } }
orioncode/orionplatform
orion_admin/src/main/java/com/orionplatform/admin/usermanagement/userdetails/tasks/GetUserLoginDatesAndNumberOfLoginsForDateTask.java
Java
apache-2.0
1,185
package com.elven.danmaku.sample.stage01; import static org.lwjgl.opengl.GL11.*; import java.awt.Color; import java.awt.Font; import com.elven.danmaku.core.frame.GameView; import com.elven.danmaku.core.graphics.texture.TextTextureSource; import com.elven.danmaku.core.graphics.texture.Texture; import com.elven.danmaku.core.graphics.texture.TextureLoader; public class Stage01Menu implements GameView { private final Texture textTexture; public Stage01Menu(TextureLoader loader) { textTexture = loader.getTexture(new TextTextureSource("Press Z to start", "pressztostart", Font.getFont("Arial"), Color.BLACK)); } @Override public void render() { glDisable(GL_TEXTURE_2D); glBegin(GL_QUADS); glColor3f(1, 1, 1); glVertex2i(0, 0); glVertex2i(0, 480); glVertex2i(640, 480); glVertex2i(640, 0); glEnd(); glEnable(GL_TEXTURE_2D); textTexture.bind(); glBegin(GL_QUADS); glTexCoord2f(0, 0); glVertex2i(270, 10); glTexCoord2f(0, textTexture.getHeight()); glVertex2i(270, 10 + textTexture.getImageHeight()); glTexCoord2f(textTexture.getWidth(), textTexture.getHeight()); glVertex2i(270 + textTexture.getImageWidth(), 10 + textTexture.getImageHeight()); glTexCoord2f(textTexture.getWidth(), 0); glVertex2i(270 + textTexture.getImageWidth(), 10); glEnd(); } @Override public void destroy() { // TODO Auto-generated method stub } }
AlanSchaeffer/Danmaku
Danmaku/src/com/elven/danmaku/sample/stage01/Stage01Menu.java
Java
apache-2.0
1,453
// Copyright 2021 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package com.google.api.ads.admanager.jaxws.v202108; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlRootElement; import javax.xml.bind.annotation.XmlType; /** * * Creates a new {@link CreativeSet}. * * @param creativeSet the creative set to create * @return the creative set with its ID filled in * * * <p>Java class for createCreativeSet element declaration. * * <p>The following schema fragment specifies the expected content contained within this class. * * <pre> * &lt;element name="createCreativeSet"> * &lt;complexType> * &lt;complexContent> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType"> * &lt;sequence> * &lt;element name="creativeSet" type="{https://www.google.com/apis/ads/publisher/v202108}CreativeSet" minOccurs="0"/> * &lt;/sequence> * &lt;/restriction> * &lt;/complexContent> * &lt;/complexType> * &lt;/element> * </pre> * * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "", propOrder = { "creativeSet" }) @XmlRootElement(name = "createCreativeSet") public class CreativeSetServiceInterfacecreateCreativeSet { protected CreativeSet creativeSet; /** * Gets the value of the creativeSet property. * * @return * possible object is * {@link CreativeSet } * */ public CreativeSet getCreativeSet() { return creativeSet; } /** * Sets the value of the creativeSet property. * * @param value * allowed object is * {@link CreativeSet } * */ public void setCreativeSet(CreativeSet value) { this.creativeSet = value; } }
googleads/googleads-java-lib
modules/dfp_appengine/src/main/java/com/google/api/ads/admanager/jaxws/v202108/CreativeSetServiceInterfacecreateCreativeSet.java
Java
apache-2.0
2,422
/** * Copyright 2014 Microsoft Open Technologies Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.microsoftopentechnologies.intellij.helpers.azure; import com.google.common.util.concurrent.ListenableFuture; import com.intellij.ide.util.PropertiesComponent; import com.microsoftopentechnologies.intellij.components.MSOpenTechTools; import com.microsoftopentechnologies.intellij.components.PluginSettings; import com.microsoftopentechnologies.intellij.helpers.NoSubscriptionException; import com.microsoftopentechnologies.intellij.helpers.OpenSSLHelper; import com.microsoftopentechnologies.intellij.helpers.StringHelper; import com.microsoftopentechnologies.intellij.helpers.aadauth.AuthenticationContext; import com.microsoftopentechnologies.intellij.helpers.aadauth.AuthenticationResult; import com.microsoftopentechnologies.intellij.helpers.aadauth.PromptValue; import com.microsoftopentechnologies.intellij.model.Subscription; import org.apache.xerces.dom.DeferredElementImpl; import org.jetbrains.annotations.Nullable; import org.w3c.dom.Document; import org.w3c.dom.Node; import org.w3c.dom.NodeList; import org.xml.sax.InputSource; import org.xml.sax.SAXException; import sun.misc.BASE64Decoder; import javax.net.ssl.HttpsURLConnection; import javax.net.ssl.KeyManagerFactory; import javax.net.ssl.SSLContext; import javax.xml.namespace.QName; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.ParserConfigurationException; import javax.xml.transform.Transformer; import javax.xml.transform.TransformerException; import javax.xml.transform.TransformerFactory; import javax.xml.transform.dom.DOMSource; import javax.xml.transform.stream.StreamResult; import javax.xml.xpath.*; import java.io.*; import java.net.HttpURLConnection; import java.net.URL; import java.security.*; import java.security.cert.CertificateException; import java.util.concurrent.ExecutionException; public class AzureRestAPIHelper { public static final String AZURE_API_VERSION = "2014-06-01"; public static final String USER_AGENT_HEADER = "User-Agent"; public static final String TELEMETRY_HEADER = "X-ClientService-ClientTag"; public static final String X_MS_VERSION_HEADER = "x-ms-version"; public static final String AUTHORIZATION_HEADER = "Authorization"; public static final String ACCEPT_HEADER = "Accept"; public static final String CONTENT_TYPE_HEADER = "Content-Type"; public static void removeSubscription(String subscriptionId) throws SAXException, ParserConfigurationException, XPathExpressionException, IOException, TransformerException { String existingXml = PropertiesComponent.getInstance().getValue(MSOpenTechTools.AppSettingsNames.SUBSCRIPTION_FILE); NodeList subscriptionList = (NodeList) getXMLValue(existingXml, "//Subscription", XPathConstants.NODESET); for (int i = 0; i < subscriptionList.getLength(); i++) { String id = getAttributeValue(subscriptionList.item(i), "Id"); if (id.equals(subscriptionId)) subscriptionList.item(i).getParentNode().removeChild(subscriptionList.item(i)); } TransformerFactory tf = TransformerFactory.newInstance(); Transformer transformer = tf.newTransformer(); StringWriter writer = new StringWriter(); transformer.transform(new DOMSource(subscriptionList.item(0).getOwnerDocument()), new StreamResult(writer)); PropertiesComponent.getInstance().setValue(MSOpenTechTools.AppSettingsNames.SUBSCRIPTION_FILE, writer.getBuffer().toString()); } public static void importSubscription(File publishSettingsFile) throws AzureCmdException { try { BufferedReader isfile = new BufferedReader(new InputStreamReader(new FileInputStream(publishSettingsFile))); String line = isfile.readLine(); String publishInfo = ""; while (line != null) { publishInfo = publishInfo + line; line = isfile.readLine(); } String xml = OpenSSLHelper.processCertificate(publishInfo); if (!PropertiesComponent.getInstance().getValue(MSOpenTechTools.AppSettingsNames.SUBSCRIPTION_FILE, "").trim().isEmpty()) { String existingXml = PropertiesComponent.getInstance().getValue(MSOpenTechTools.AppSettingsNames.SUBSCRIPTION_FILE); NodeList subscriptionList = (NodeList) getXMLValue(existingXml, "//Subscription", XPathConstants.NODESET); Node newSubscription = ((NodeList) getXMLValue(xml, "//Subscription", XPathConstants.NODESET)).item(0); if (subscriptionList.getLength() == 0) { PropertiesComponent.getInstance().setValue(MSOpenTechTools.AppSettingsNames.SUBSCRIPTION_FILE, xml); } else { Document ownerDocument = subscriptionList.item(0).getOwnerDocument(); Node parentNode = subscriptionList.item(0).getParentNode(); for (int i = 0; i < subscriptionList.getLength(); i++) { String newId = getAttributeValue(newSubscription, "Id"); String id = getAttributeValue(subscriptionList.item(i), "Id"); if (id.equals(newId)) subscriptionList.item(i).getParentNode().removeChild(subscriptionList.item(i)); } Node newNode = ownerDocument.importNode(newSubscription, true); Node node = parentNode.appendChild(newNode); TransformerFactory tf = TransformerFactory.newInstance(); Transformer transformer = tf.newTransformer(); StringWriter writer = new StringWriter(); transformer.transform(new DOMSource(node.getOwnerDocument()), new StreamResult(writer)); PropertiesComponent.getInstance().setValue(MSOpenTechTools.AppSettingsNames.SUBSCRIPTION_FILE, writer.getBuffer().toString()); } } else { PropertiesComponent.getInstance().setValue(MSOpenTechTools.AppSettingsNames.SUBSCRIPTION_FILE, xml); } } catch (AzureCmdException ex) { throw ex; } catch (Exception ex) { throw new AzureCmdException("Error importing subscription", ex); } } public static Object getXMLValue(String xml, String xQuery, QName resultType) throws XPathExpressionException, IOException, SAXException, ParserConfigurationException { DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); DocumentBuilder db = dbf.newDocumentBuilder(); Document doc = db.parse(new InputSource(new StringReader(xml))); XPathFactory xPathfactory = XPathFactory.newInstance(); XPath xPath = xPathfactory.newXPath(); XPathExpression xPathExpression = xPath.compile(xQuery); return xPathExpression.evaluate(doc, resultType); } public static String getAttributeValue(Node node, String attributeName) { Node n = node.getAttributes().getNamedItem(attributeName); return (n == null) ? null : n.getNodeValue(); } public static String getChildNodeValue(Node node, String elementName) { return ((DeferredElementImpl) node).getElementsByTagName(elementName).item(0).getTextContent(); } public static String getRestApiCommand(String path, String subscriptionId) throws IOException, SAXException, ParserConfigurationException, XPathExpressionException, NoSuchAlgorithmException, KeyStoreException, CertificateException, UnrecoverableKeyException, KeyManagementException, NoSubscriptionException, AzureCmdException, ExecutionException, InterruptedException { AzureRestCallbackAdapter<String> callback = new AzureRestCallbackAdapter<String>() { @Override public int apply(HttpsURLConnection sslConnection) throws IOException { int response = sslConnection.getResponseCode(); if (sslConnection.getResponseCode() < 400) { setResult(readStream(sslConnection.getInputStream(), true)); } return response; } }; runWithSSLConnection(path, true, subscriptionId, callback); if (!callback.isOk()) { throw callback.getError(); } return callback.getResult(); } public static String postRestApiCommand(String path, String postData, String subscriptionId, String asyncUrl, boolean jsonContent) throws IOException, CertificateException, NoSuchAlgorithmException, UnrecoverableKeyException, ParserConfigurationException, SAXException, KeyStoreException, XPathExpressionException, KeyManagementException, AzureCmdException, InterruptedException, NoSubscriptionException, ExecutionException { return restApiCommand("POST", path, postData, subscriptionId, asyncUrl, jsonContent); } public static String putRestApiCommand(String path, String postData, String subscriptionId, String asyncUrl, boolean jsonContent) throws IOException, CertificateException, NoSuchAlgorithmException, UnrecoverableKeyException, ParserConfigurationException, SAXException, KeyStoreException, XPathExpressionException, KeyManagementException, AzureCmdException, InterruptedException, NoSubscriptionException, ExecutionException { return restApiCommand("PUT", path, postData, subscriptionId, asyncUrl, jsonContent); } public static String deleteRestApiCommand(String path, String subscriptionId, String asyncUrl, boolean jsonContent) throws IOException, CertificateException, NoSuchAlgorithmException, UnrecoverableKeyException, ParserConfigurationException, SAXException, KeyStoreException, XPathExpressionException, KeyManagementException, AzureCmdException, InterruptedException, NoSubscriptionException, ExecutionException { return restApiCommand("DELETE", path, null, subscriptionId, asyncUrl, jsonContent); } private static String restApiCommand( final String method, final String path, final String postData, final String subscriptionId, final String asyncUrl, final boolean jsonContent) throws IOException, CertificateException, NoSuchAlgorithmException, UnrecoverableKeyException, ParserConfigurationException, SAXException, KeyStoreException, XPathExpressionException, KeyManagementException, AzureCmdException, InterruptedException, NoSubscriptionException, ExecutionException { // This is a callback method that is invoked in a loop below after the request has been // sent. The purpose of this method is to check the status of the pending operation and check // if it is complete. final AzureRestCallbackAdapter<Boolean> requestStatusCallback = new AzureRestCallbackAdapter<Boolean>() { @Override public int apply(HttpsURLConnection sslConnection) throws IOException { setResult(false); try { int responseCode = sslConnection.getResponseCode(); if (responseCode < 200 && responseCode > 299) { setError(new AzureCmdException("Operation interrupted", "Http error code: " + String.valueOf(responseCode))); } else { String pollres = readStream(sslConnection.getInputStream()); NodeList nl = ((NodeList) getXMLValue(pollres, "//Status", XPathConstants.NODESET)); if (nl.getLength() > 0) { if (nl.item(0).getTextContent().equals("Succeeded")) { setResult(true); } } } return responseCode; } catch (Exception e) { setError(new AzureCmdException(e.getMessage(), e)); return HttpURLConnection.HTTP_INTERNAL_ERROR; } } }; AzureRestCallbackAdapter<String> callback = new AzureRestCallbackAdapter<String>() { @Override public int apply(HttpsURLConnection sslConnection) throws IOException { setError(null); sslConnection.setRequestMethod(method); sslConnection.setDoOutput(postData != null); sslConnection.setRequestProperty("Accept", ""); if (postData != null) { DataOutputStream wr = new DataOutputStream(sslConnection.getOutputStream()); wr.writeBytes(postData); wr.flush(); wr.close(); } int responseCode = sslConnection.getResponseCode(); if (responseCode >= 200 && responseCode < 300) { String response = readStream(sslConnection.getInputStream()); if (responseCode == 202 && asyncUrl != null) { String operationURL = asyncUrl + sslConnection.getHeaderField("x-ms-request-id"); sslConnection.disconnect(); boolean succeed = false; while (!succeed) { try { runWithSSLConnection(operationURL, false, subscriptionId, requestStatusCallback); if (!requestStatusCallback.isOk()) { setError(requestStatusCallback.getError()); // NOTE: setting "succeed" to false below means that the loop for // checking the status of the request will continue running; the hope is // that the error that occurred while checking for status is transient // and won't occur again; // TODO: A better approach might be to retry a few times and then bail. succeed = false; } else { succeed = requestStatusCallback.getResult(); } if (!succeed) { // wait for a while otherwise Azure complains with a // "too many requests received" error // TODO: This is a bit hacky. See if we can do better. Thread.sleep(2000); } } catch (Exception e) { setError(new AzureCmdException(e.getMessage(), e)); return responseCode; } } } setResult(response); } else { String err = readStream(sslConnection.getErrorStream(), true); setError(new AzureCmdException("Error uploading script: ", err)); } return responseCode; } }; runWithSSLConnection(path, jsonContent, subscriptionId, callback); if (!callback.isOk()) { throw callback.getError(); } return callback.getResult(); } interface AzureRestCallback<T> { @Nullable int apply(HttpsURLConnection sslConnection) throws IOException; T getResult(); void setResult(T result); AzureCmdException getError(); void setError(AzureCmdException throwable); boolean isOk(); @Override boolean equals(@Nullable java.lang.Object o); } abstract static class AzureRestCallbackAdapter<T> implements AzureRestCallback<T> { private T result; private AzureCmdException azureError = null; @Override public T getResult() { return result; } @Override public void setResult(T result) { this.result = result; } @Override public AzureCmdException getError() { return azureError; } @Override public void setError(AzureCmdException throwable) { this.azureError = throwable; } @Override public boolean isOk() { return azureError == null; } } public static <T> void runWithSSLConnection( String path, boolean jsonContent, String subscriptionId, AzureRestCallback<T> callback) throws IOException, CertificateException, NoSuchAlgorithmException, UnrecoverableKeyException, ParserConfigurationException, SAXException, KeyStoreException, XPathExpressionException, KeyManagementException, ExecutionException, InterruptedException, AzureCmdException, NoSubscriptionException { AzureManager apiManager = AzureRestAPIManager.getManager(); AzureAuthenticationMode authMode = apiManager.getAuthenticationMode(); if (authMode == AzureAuthenticationMode.ActiveDirectory) { runWithSSLConnectionFromToken(path, jsonContent, subscriptionId, callback, apiManager); } else if (authMode == AzureAuthenticationMode.SubscriptionSettings) { runWithSSLConnectionFromCert(path, jsonContent, subscriptionId, callback); } else { throw new NoSubscriptionException("A valid Azure subscription has not been configured yet."); } } private static <T> void runWithSSLConnectionFromCert( String path, boolean jsonContent, String subscriptionId, AzureRestCallback<T> callback) throws IOException, KeyManagementException, NoSuchAlgorithmException, UnrecoverableKeyException, KeyStoreException, CertificateException, ParserConfigurationException, XPathExpressionException, SAXException, AzureCmdException { HttpsURLConnection sslConnection = getSSLConnectionFromCert(path, jsonContent, subscriptionId); int response = callback.apply(sslConnection); if (response < 200 || response > 299) { throw new AzureCmdException("Error connecting to service", readStream(sslConnection.getErrorStream())); } } private static <T> void runWithSSLConnectionFromToken( String path, boolean jsonContent, String subscriptionId, AzureRestCallback<T> callback, AzureManager apiManager) throws IOException, KeyManagementException, NoSuchAlgorithmException, UnrecoverableKeyException, KeyStoreException, CertificateException, ParserConfigurationException, XPathExpressionException, SAXException, InterruptedException, ExecutionException, AzureCmdException, NoSubscriptionException { HttpsURLConnection sslConnection;// there should already be a valid auth token by this time boolean isForSubscription = !StringHelper.isNullOrWhiteSpace(subscriptionId); if (!isForSubscription && apiManager.getAuthenticationToken() == null) { throw new UnsupportedOperationException("The authentication mode has been set to use AD " + "but no valid access token found. Please sign in to your account."); } // if this call is for a specific subscription and we don't have an authentication token for // that subscription then acquire one if (isForSubscription && apiManager.getAuthenticationTokenForSubscription(subscriptionId) == null) { // perform interactive authentication acquireTokenInteractive(subscriptionId, apiManager); } sslConnection = getSSLConnectionFromAccessToken(path, jsonContent, subscriptionId, false); int response = callback.apply(sslConnection); if (response == HttpURLConnection.HTTP_UNAUTHORIZED) { // retry with refresh token sslConnection = getSSLConnectionFromAccessToken(path, jsonContent, subscriptionId, true); // sslConnection will be null if we don't have a refresh token; in which // we fall through to the next "if" check where we attempt interactive auth if (sslConnection != null) { response = callback.apply(sslConnection); } if (response == HttpURLConnection.HTTP_UNAUTHORIZED) { // perform interactive authentication acquireTokenInteractive(subscriptionId, apiManager); // third time lucky? sslConnection = getSSLConnectionFromAccessToken(path, jsonContent, subscriptionId, false); response = callback.apply(sslConnection); if (response < 200 || response > 299) { // clear the auth token apiManager.setAuthenticationToken(null); throw new AzureCmdException("Error connecting to service", readStream(sslConnection.getErrorStream())); } } else if (response < 200 || response > 299) { throw new AzureCmdException("Error connecting to service", readStream(sslConnection.getErrorStream())); } } else if (response < 200 || response > 299) { throw new AzureCmdException("Error connecting to service", readStream(sslConnection.getErrorStream())); } } private static AuthenticationResult acquireTokenInteractive( String subscriptionId, AzureManager apiManager) throws IOException, CertificateException, NoSuchAlgorithmException, UnrecoverableKeyException, ExecutionException, ParserConfigurationException, InterruptedException, XPathExpressionException, SAXException, KeyManagementException, KeyStoreException, AzureCmdException, NoSubscriptionException { PluginSettings settings = MSOpenTechTools.getCurrent().getSettings(); AuthenticationContext context = null; AuthenticationResult token = null; boolean isForSubscription = !StringHelper.isNullOrWhiteSpace(subscriptionId); try { context = new AuthenticationContext(settings.getAdAuthority()); String windowTitle = isForSubscription ? "Sign in: " + apiManager.getSubscriptionFromId(subscriptionId).getName() : "Sign in to your Microsoft account"; ListenableFuture<AuthenticationResult> future = context.acquireTokenInteractiveAsync( getTenantName(subscriptionId), settings.getAzureServiceManagementUri(), settings.getClientId(), settings.getRedirectUri(), null, windowTitle, (isForSubscription) ? PromptValue.attemptNone : PromptValue.login); token = future.get(); // save the token if (isForSubscription) { apiManager.setAuthenticationTokenForSubscription(subscriptionId, token); } else { apiManager.setAuthenticationToken(token); } } finally { if (context != null) { context.dispose(); } } return token; } private static HttpsURLConnection getSSLConnectionFromAccessToken( String path, boolean jsonContent, String subscriptionId, boolean useRefreshToken) throws IOException, KeyManagementException, NoSuchAlgorithmException, UnrecoverableKeyException, KeyStoreException, CertificateException, ParserConfigurationException, XPathExpressionException, SAXException, InterruptedException, ExecutionException, AzureCmdException, NoSubscriptionException { PluginSettings settings = MSOpenTechTools.getCurrent().getSettings(); AzureManager apiManager = AzureRestAPIManager.getManager(); // get the default token if there is no subscription ID; otherwise fetch // the token for the subscription boolean isForSubscription = !StringHelper.isNullOrWhiteSpace(subscriptionId); AuthenticationResult token = isForSubscription ? apiManager.getAuthenticationTokenForSubscription(subscriptionId) : apiManager.getAuthenticationToken(); // get a new access token if "useRefreshToken" is true if (useRefreshToken) { // check if we have a refresh token to redeem if (StringHelper.isNullOrWhiteSpace(token.getRefreshToken())) { return null; } AuthenticationContext context = new AuthenticationContext(settings.getAdAuthority()); try { token = context.acquireTokenByRefreshToken( token, getTenantName(subscriptionId), settings.getAzureServiceManagementUri(), settings.getClientId()); } finally { context.dispose(); } if (isForSubscription) { apiManager.setAuthenticationTokenForSubscription(subscriptionId, token); } else { apiManager.setAuthenticationToken(token); } } String url = settings.getAzureServiceManagementUri(); URL myUrl = new URL(new URL(url), path); // Uncomment following two lines to capture traffic in Fiddler. You'll need to // import the Fiddler cert as a trusted root cert in the JRE first though. //Proxy proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress("127.0.0.1", 8888)); //HttpsURLConnection conn = (HttpsURLConnection) myUrl.openConnection(proxy); HttpsURLConnection conn = (HttpsURLConnection) myUrl.openConnection(); conn.addRequestProperty(USER_AGENT_HEADER, getPlatformUserAgent()); conn.addRequestProperty(TELEMETRY_HEADER, getPlatformUserAgent()); conn.addRequestProperty(X_MS_VERSION_HEADER, AZURE_API_VERSION); if (jsonContent) { conn.addRequestProperty(ACCEPT_HEADER, "application/json"); conn.addRequestProperty(CONTENT_TYPE_HEADER, "application/json"); } else { conn.addRequestProperty(ACCEPT_HEADER, "application/xml"); conn.addRequestProperty(CONTENT_TYPE_HEADER, "application/xml"); } // set access token conn.addRequestProperty(AUTHORIZATION_HEADER, "Bearer " + token.getAccessToken()); return conn; } private static String getPlatformUserAgent() { String version = MSOpenTechTools.getCurrent().getSettings().getPluginVersion(); return String.format( "%s/%s (lang=%s; os=%s; version=%s)", MSOpenTechTools.PLUGIN_ID, version, "Java", System.getProperty("os.name"), version); } private static String getTenantName(String subscriptionId) throws IOException, CertificateException, NoSuchAlgorithmException, UnrecoverableKeyException, ExecutionException, ParserConfigurationException, InterruptedException, SAXException, AzureCmdException, NoSubscriptionException, KeyStoreException, XPathExpressionException, KeyManagementException { // get tenant id from subscription if this request is for an // azure subscription String tenantName = MSOpenTechTools.getCurrent().getSettings().getTenantName(); if (!StringHelper.isNullOrWhiteSpace(subscriptionId)) { Subscription subscription = AzureRestAPIManager.getManager().getSubscriptionFromId(subscriptionId); if (subscription != null) { tenantName = subscription.getTenantId(); } } return tenantName; } private static HttpsURLConnection getSSLConnectionFromCert( String path, boolean jsonContent, String subscriptionId) throws IOException, KeyManagementException, NoSuchAlgorithmException, UnrecoverableKeyException, KeyStoreException, CertificateException, ParserConfigurationException, XPathExpressionException, SAXException { String publishSettings = PropertiesComponent.getInstance().getValue(MSOpenTechTools.AppSettingsNames.SUBSCRIPTION_FILE, ""); if (publishSettings.isEmpty()) return null; Node node = null; NodeList subslist = (NodeList) getXMLValue( publishSettings, "//PublishData/PublishProfile/Subscription", XPathConstants.NODESET); for (int i = 0; i < subslist.getLength(); i++) { String id = getAttributeValue(subslist.item(i), "Id"); if (id.equals(subscriptionId)) node = subslist.item(i); } if (node == null) return null; String pfx = getAttributeValue(node, "ManagementCertificate"); String url = getAttributeValue(node, "ServiceManagementUrl"); byte[] decodeBuffer = new BASE64Decoder().decodeBuffer(pfx); KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance("SunX509"); InputStream is = new ByteArrayInputStream(decodeBuffer); KeyStore ks = KeyStore.getInstance("PKCS12"); ks.load(is, OpenSSLHelper.PASSWORD.toCharArray()); keyManagerFactory.init(ks, OpenSSLHelper.PASSWORD.toCharArray()); SSLContext sslContext = SSLContext.getInstance("TLS"); sslContext.init(keyManagerFactory.getKeyManagers(), null, new SecureRandom()); URL myUrl = new URL(url + path); HttpsURLConnection conn = (HttpsURLConnection) myUrl.openConnection(); conn.setSSLSocketFactory(sslContext.getSocketFactory()); conn.addRequestProperty(USER_AGENT_HEADER, getPlatformUserAgent()); conn.addRequestProperty(TELEMETRY_HEADER, getPlatformUserAgent()); conn.addRequestProperty(X_MS_VERSION_HEADER, AZURE_API_VERSION); if (jsonContent) { conn.addRequestProperty(ACCEPT_HEADER, "application/json"); conn.addRequestProperty(CONTENT_TYPE_HEADER, "application/json"); } else { conn.addRequestProperty(ACCEPT_HEADER, "application/xml"); conn.addRequestProperty(CONTENT_TYPE_HEADER, "application/xml"); } return conn; } private static String readStream(InputStream is) throws IOException { return readStream(is, false); } private static String readStream(InputStream is, boolean keepLines) throws IOException { BufferedReader in = null; try { in = new BufferedReader( new InputStreamReader(is)); String inputLine; String separator = System.getProperty("line.separator"); StringBuilder response = new StringBuilder(); while ((inputLine = in.readLine()) != null) { response.append(inputLine); if (keepLines) { response.append(separator); } } in.close(); in = null; return response.toString(); } finally { if (in != null) { in.close(); } } } public static void uploadScript(final String path, final String filePath, final String subscriptionId) throws IOException, CertificateException, NoSuchAlgorithmException, UnrecoverableKeyException, ParserConfigurationException, SAXException, KeyStoreException, XPathExpressionException, KeyManagementException, AzureCmdException, InterruptedException, NoSubscriptionException, ExecutionException { runWithSSLConnection(path, true, subscriptionId, new AzureRestCallbackAdapter<Void>() { @Override public int apply(HttpsURLConnection sslConnection) throws IOException { String script = readStream(new FileInputStream(filePath), true); sslConnection.setRequestMethod("PUT"); sslConnection.setDoOutput(true); sslConnection.setRequestProperty("Accept", ""); sslConnection.setRequestProperty("Content-Type", "text/plain"); DataOutputStream wr = new DataOutputStream(sslConnection.getOutputStream()); wr.writeBytes(script); wr.flush(); wr.close(); return sslConnection.getResponseCode(); } }); } public static boolean existsMobileService(String name) { try { URL myUrl = new URL("https://" + name + ".azure-mobile.net"); HttpsURLConnection conn = (HttpsURLConnection) myUrl.openConnection(); int responseCode = conn.getResponseCode(); return (responseCode >= 200 && responseCode < 300); } catch (Exception e) { return false; } } }
nandhanurrevanth/msopentech-tools-for-intellij
src/android/com/microsoftopentechnologies/intellij/helpers/azure/AzureRestAPIHelper.java
Java
apache-2.0
34,380
/* * Copyright 2017-2022 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with * the License. A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR * CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions * and limitations under the License. */ package com.amazonaws.services.iotfleethub.model; import java.io.Serializable; import javax.annotation.Generated; /** * * @see <a href="http://docs.aws.amazon.com/goto/WebAPI/iotfleethub-2020-11-03/CreateApplication" target="_top">AWS API * Documentation</a> */ @Generated("com.amazonaws:aws-java-sdk-code-generator") public class CreateApplicationResult extends com.amazonaws.AmazonWebServiceResult<com.amazonaws.ResponseMetadata> implements Serializable, Cloneable { /** * <p> * The unique Id of the web application. * </p> */ private String applicationId; /** * <p> * The ARN of the web application. * </p> */ private String applicationArn; /** * <p> * The unique Id of the web application. * </p> * * @param applicationId * The unique Id of the web application. */ public void setApplicationId(String applicationId) { this.applicationId = applicationId; } /** * <p> * The unique Id of the web application. * </p> * * @return The unique Id of the web application. */ public String getApplicationId() { return this.applicationId; } /** * <p> * The unique Id of the web application. * </p> * * @param applicationId * The unique Id of the web application. * @return Returns a reference to this object so that method calls can be chained together. */ public CreateApplicationResult withApplicationId(String applicationId) { setApplicationId(applicationId); return this; } /** * <p> * The ARN of the web application. * </p> * * @param applicationArn * The ARN of the web application. */ public void setApplicationArn(String applicationArn) { this.applicationArn = applicationArn; } /** * <p> * The ARN of the web application. * </p> * * @return The ARN of the web application. */ public String getApplicationArn() { return this.applicationArn; } /** * <p> * The ARN of the web application. * </p> * * @param applicationArn * The ARN of the web application. * @return Returns a reference to this object so that method calls can be chained together. */ public CreateApplicationResult withApplicationArn(String applicationArn) { setApplicationArn(applicationArn); return this; } /** * Returns a string representation of this object. This is useful for testing and debugging. Sensitive data will be * redacted from this string using a placeholder value. * * @return A string representation of this object. * * @see java.lang.Object#toString() */ @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("{"); if (getApplicationId() != null) sb.append("ApplicationId: ").append(getApplicationId()).append(","); if (getApplicationArn() != null) sb.append("ApplicationArn: ").append(getApplicationArn()); sb.append("}"); return sb.toString(); } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (obj instanceof CreateApplicationResult == false) return false; CreateApplicationResult other = (CreateApplicationResult) obj; if (other.getApplicationId() == null ^ this.getApplicationId() == null) return false; if (other.getApplicationId() != null && other.getApplicationId().equals(this.getApplicationId()) == false) return false; if (other.getApplicationArn() == null ^ this.getApplicationArn() == null) return false; if (other.getApplicationArn() != null && other.getApplicationArn().equals(this.getApplicationArn()) == false) return false; return true; } @Override public int hashCode() { final int prime = 31; int hashCode = 1; hashCode = prime * hashCode + ((getApplicationId() == null) ? 0 : getApplicationId().hashCode()); hashCode = prime * hashCode + ((getApplicationArn() == null) ? 0 : getApplicationArn().hashCode()); return hashCode; } @Override public CreateApplicationResult clone() { try { return (CreateApplicationResult) super.clone(); } catch (CloneNotSupportedException e) { throw new IllegalStateException("Got a CloneNotSupportedException from Object.clone() " + "even though we're Cloneable!", e); } } }
aws/aws-sdk-java
aws-java-sdk-iotfleethub/src/main/java/com/amazonaws/services/iotfleethub/model/CreateApplicationResult.java
Java
apache-2.0
5,358
/**************************************************************** * Licensed to the AOS Community (AOS) under one or more * * contributor license agreements. See the NOTICE file * * distributed with this work for additional information * * regarding copyright ownership. The AOS licenses this file * * to you under the Apache License, Version 2.0 (the * * "License"); you may not use this file except in compliance * * with the License. You may obtain a copy of the License at * * * * http://www.apache.org/licenses/LICENSE-2.0 * * * * Unless required by applicable law or agreed to in writing, * * software distributed under the License is distributed on an * * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * * KIND, either express or implied. See the License for the * * specific language governing permissions and limitations * * under the License. * ****************************************************************/ package io.datalayer.data.map; import io.datalayer.data.iterable.EmptyIterator; import io.datalayer.data.iterator.AosIterator; /** * A {@link Map} that is always empty. * */ public final class EmptyMap implements Map { /** The single instance of the class. */ public static final EmptyMap INSTANCE = new EmptyMap(); /** * Constructor marked private to prevent instantiation. */ private EmptyMap() { } public Object get(Object key) { return null; } public Object set(Object key, Object value) { throw new UnsupportedOperationException(); } public Object delete(Object key) { throw new UnsupportedOperationException(); } public boolean contains(Object key) { return false; } public void clear() { } public int size() { return 0; } public boolean isEmpty() { return true; } public AosIterator iterator() { return EmptyIterator.INSTANCE; } }
echalkpad/t4f-data
structure/core/src/main/java/io/datalayer/data/map/EmptyMap.java
Java
apache-2.0
2,191
/* Copyright 2019 Volker Berlin (i-net software) 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 de.inetsoftware.jwebassembly.javascript; import java.util.function.Function; import java.util.function.Supplier; import de.inetsoftware.jwebassembly.module.ArraySyntheticFunctionName; import de.inetsoftware.jwebassembly.wasm.AnyType; /** * Synthetic JavaScript import function. * * @author Volker Berlin * */ public class JavaScriptSyntheticFunctionName extends ArraySyntheticFunctionName { private final Supplier<String> js; /** * Create a synthetic function which based on imported, dynamic generated JavaScript. * * @param module * the module name * @param functionName * the name of the function * @param js * the dynamic JavaScript as a lambda expression * @param signature * the types of the signature */ public JavaScriptSyntheticFunctionName( String module, String functionName, Supplier<String> js, AnyType... signature ) { super( module, functionName, signature ); this.js = js; } /** * {@inheritDoc} */ @Override protected boolean hasWasmCode() { return false; } /** * {@inheritDoc} */ @Override protected Function<String, Object> getAnnotation() { return ( key ) -> { switch( key ) { case JavaScriptWriter.JAVA_SCRIPT_CONTENT: return js.get(); default: } return null; }; } }
i-net-software/JWebAssembly
src/de/inetsoftware/jwebassembly/javascript/JavaScriptSyntheticFunctionName.java
Java
apache-2.0
2,112
package com.greensnow25; import org.junit.Test; import java.io.File; import java.io.IOException; import java.io.RandomAccessFile; import static org.hamcrest.core.Is.is; import static org.junit.Assert.assertThat; /** * public testClass SortLargeFileTest . * * @author grensnow25. * @version 1. * @since 28.02.17. */ public class SortLargeFileTest { /** * test array. */ private String[] testo = new String[]{"999999999", "1", "55555", "333", "4444", "333", "666666"}; /** * system didectory. */ private final String userDir = System.getProperty("user.dir"); /** * path to the file. */ private String path = "\\src\\main\\java\\com\\greensnow25\\"; /** * metod sort file. */ @Test public void whenSortFileIsSuccessfulThenReturnTrue() { SortLargeFile sort = new SortLargeFile(); String separator = System.getProperty("line.separator"); boolean result = true; String temp; String lastLine = ""; File sourse = new File(userDir + path + "test.txt"); File dest = new File(userDir + path + "dest.txt"); try (RandomAccessFile write = new RandomAccessFile(sourse, "rw"); RandomAccessFile read = new RandomAccessFile(dest, "rw")) { for (String line : testo) { write.writeBytes(line); write.writeBytes(separator); } sort.sortFile(sourse, dest); while ((temp = read.readLine()) != null) { if (lastLine.length() > temp.length()) { result = false; } lastLine = temp; } } catch (IOException ex) { ex.printStackTrace(); } assertThat(result, is(true)); } }
greensnow25/javaaz
chapter3/Input_Output/src/test/java/com/greensnow25/SortLargeFileTest.java
Java
apache-2.0
1,805
/* * Copyright (C) 2015 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.cloud.dataflow.sdk.runners.worker; import com.google.cloud.dataflow.sdk.util.Weighted; import com.google.cloud.dataflow.sdk.util.state.State; import com.google.cloud.dataflow.sdk.util.state.StateNamespace; import com.google.cloud.dataflow.sdk.util.state.StateTag; import com.google.common.cache.Cache; import com.google.common.cache.CacheBuilder; import com.google.common.cache.RemovalCause; import com.google.common.cache.RemovalListener; import com.google.common.cache.RemovalNotification; import com.google.common.cache.Weigher; import com.google.protobuf.ByteString; import java.io.PrintWriter; import java.util.HashMap; import java.util.Map; import java.util.Objects; /** * Process-wide cache of per-key state. */ public class WindmillStateCache { private Cache<StateId, StateCacheEntry> stateCache; private int weight = 0; private static class CacheWeigher implements Weigher<Weighted, Weighted> { @Override public int weigh(Weighted key, Weighted value) { return (int) Math.max(key.getWeight() + value.getWeight(), Integer.MAX_VALUE); } } public WindmillStateCache() { final Weigher<Weighted, Weighted> weigher = Weighers.weightedKeysAndValues(); stateCache = CacheBuilder.newBuilder() .maximumWeight(100000000 /* 100 MB */) .recordStats() .weigher(weigher) .removalListener(new RemovalListener<StateId, StateCacheEntry>() { @Override public void onRemoval(RemovalNotification<StateId, StateCacheEntry> removal) { if (removal.getCause() != RemovalCause.REPLACED) { weight -= weigher.weigh(removal.getKey(), removal.getValue()); } } }) .build(); } public long getWeight() { return weight; } /** * Per-computation view of the state cache. */ public class ForComputation { private final String computation; private ForComputation(String computation) { this.computation = computation; } /** * Returns a per-computation, per-key view of the state cache. */ public ForKey forKey(ByteString key, String stateFamily, long cacheToken) { return new ForKey(computation, key, stateFamily, cacheToken); } } /** * Per-computation, per-key view of the state cache. */ public class ForKey { private final String computation; private final ByteString key; private final String stateFamily; private final long cacheToken; private ForKey(String computation, ByteString key, String stateFamily, long cacheToken) { this.computation = computation; this.key = key; this.stateFamily = stateFamily; this.cacheToken = cacheToken; } public <T extends State> T get(StateNamespace namespace, StateTag<T> address) { return WindmillStateCache.this.get( computation, key, stateFamily, cacheToken, namespace, address); } public <T extends State> void put( StateNamespace namespace, StateTag<T> address, T value, long weight) { WindmillStateCache.this.put( computation, key, stateFamily, cacheToken, namespace, address, value, weight); } } /** * Returns a per-computation view of the state cache. */ public ForComputation forComputation(String computation) { return new ForComputation(computation); } private <T extends State> T get(String computation, ByteString processingKey, String stateFamily, long token, StateNamespace namespace, StateTag<T> address) { StateId id = new StateId(computation, processingKey, stateFamily, namespace); StateCacheEntry entry = stateCache.getIfPresent(id); if (entry == null) { return null; } if (entry.getToken() != token) { stateCache.invalidate(id); return null; } return entry.get(namespace, address); } private <T extends State> void put(String computation, ByteString processingKey, String stateFamily, long token, StateNamespace namespace, StateTag<T> address, T value, long weight) { StateId id = new StateId(computation, processingKey, stateFamily, namespace); StateCacheEntry entry = stateCache.getIfPresent(id); if (entry == null || entry.getToken() != token) { entry = new StateCacheEntry(token); this.weight += id.getWeight(); } this.weight += entry.put(namespace, address, value, weight); // Always add back to the cache to update the weight. stateCache.put(id, entry); } /** * Struct identifying a cache entry that contains all data for a key and namespace. */ private static class StateId implements Weighted { public final String computation; public final ByteString processingKey; public final String stateFamily; public final Object namespaceKey; public StateId(String computation, ByteString processingKey, String stateFamily, StateNamespace namespace) { this.computation = computation; this.processingKey = processingKey; this.stateFamily = stateFamily; this.namespaceKey = namespace.getCacheKey(); } @Override public boolean equals(Object other) { if (other instanceof StateId) { StateId otherId = (StateId) other; return computation.equals(otherId.computation) && processingKey.equals(otherId.processingKey) && stateFamily.equals(otherId.stateFamily) && namespaceKey.equals(otherId.namespaceKey); } return false; } @Override public int hashCode() { return Objects.hash(computation, processingKey, namespaceKey); } @Override public long getWeight() { return processingKey.size(); } } /** * Entry in the state cache that stores a map of values and a token representing the * validity of the values. */ private static class StateCacheEntry implements Weighted { private final long token; private final Map<NamespacedTag<?>, WeightedValue<?>> values; private long weight; public StateCacheEntry(long token) { this.values = new HashMap<>(); this.token = token; this.weight = 0; } @SuppressWarnings("unchecked") public <T extends State> T get(StateNamespace namespace, StateTag<T> tag) { WeightedValue<T> weightedValue = (WeightedValue<T>) values.get(new NamespacedTag(namespace, tag)); return weightedValue == null ? null : weightedValue.value; } public <T extends State> long put( StateNamespace namespace, StateTag<T> tag, T value, long weight) { WeightedValue<T> weightedValue = (WeightedValue<T>) values.get(new NamespacedTag(namespace, tag)); long weightDelta = 0; if (weightedValue == null) { weightedValue = new WeightedValue<T>(); } else { weightDelta -= weightedValue.weight; } weightedValue.value = value; weightedValue.weight = weight; weightDelta += weight; this.weight += weightDelta; values.put(new NamespacedTag(namespace, tag), weightedValue); return weightDelta; } @Override public long getWeight() { return weight; } public long getToken() { return token; } private static class NamespacedTag<T extends State> { private final StateNamespace namespace; private final StateTag<T> tag; NamespacedTag(StateNamespace namespace, StateTag<T> tag) { this.namespace = namespace; this.tag = tag; } @Override public boolean equals(Object other) { if (!(other instanceof NamespacedTag)) { return false; } NamespacedTag<?> that = (NamespacedTag<?>) other; return namespace.equals(that.namespace) && tag.equals(that.tag); } @Override public int hashCode() { return Objects.hash(namespace, tag); } } private static class WeightedValue<T> { public long weight = 0; public T value = null; } } /** * Print summary statistics of the cache to the given {@link PrintWriter}. */ public void printSummaryHtml(PrintWriter response) { response.println("Cache Stats: <br><table border=0>"); response.println( "<tr><th>Hit Ratio</th><th>Evictions</th><th>Size</th><th>Weight</th></tr><tr>"); response.println("<th>" + stateCache.stats().hitRate() + "</th>"); response.println("<th>" + stateCache.stats().evictionCount() + "</th>"); response.println("<th>" + stateCache.size() + "</th>"); response.println("<th>" + getWeight() + "</th>"); response.println("</tr></table><br>"); } /** * Print detailed information about the cache to the given {@link PrintWriter}. */ public void printDetailedHtml(PrintWriter response) { response.println("<h1>Cache Information</h1>"); printSummaryHtml(response); } }
Test-Betta-Inc/musical-umbrella
sdk/src/main/java/com/google/cloud/dataflow/sdk/runners/worker/WindmillStateCache.java
Java
apache-2.0
9,500
/* ### * IP: GHIDRA * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package agent.gdb.model.impl; import java.util.*; import java.util.concurrent.CompletableFuture; import java.util.stream.Collectors; import agent.gdb.manager.breakpoint.*; import ghidra.async.AsyncUtils; import ghidra.dbg.agent.DefaultTargetObject; import ghidra.dbg.target.TargetBreakpointSpec; import ghidra.dbg.target.TargetBreakpointSpecContainer.TargetBreakpointKindSet; import ghidra.dbg.target.TargetDeletable; import ghidra.dbg.target.schema.TargetAttributeType; import ghidra.dbg.target.schema.TargetObjectSchemaInfo; import ghidra.dbg.util.PathUtils; import ghidra.util.Msg; import ghidra.util.datastruct.ListenerSet; import ghidra.util.datastruct.WeakValueHashMap; @TargetObjectSchemaInfo( name = "BreakpointSpec", attributes = { @TargetAttributeType(type = Void.class) }, canonicalContainer = true) public class GdbModelTargetBreakpointSpec extends DefaultTargetObject<GdbModelTargetBreakpointLocation, GdbModelTargetBreakpointContainer> implements TargetBreakpointSpec, TargetDeletable { protected static String indexBreakpoint(GdbBreakpointInfo info) { return PathUtils.makeIndex(info.getNumber()); } protected static String keyBreakpoint(GdbBreakpointInfo info) { return PathUtils.makeKey(indexBreakpoint(info)); } protected final GdbModelImpl impl; protected final long number; protected GdbBreakpointInfo info; protected boolean enabled; protected String expression; protected String display; protected TargetBreakpointKindSet kinds; protected final Map<Long, GdbModelTargetBreakpointLocation> breaksBySub = new WeakValueHashMap<>(); protected final ListenerSet<TargetBreakpointAction> actions = new ListenerSet<>(TargetBreakpointAction.class) { // Use strong references on actions protected Map<TargetBreakpointAction, TargetBreakpointAction> createMap() { return Collections.synchronizedMap(new LinkedHashMap<>()); }; }; public GdbModelTargetBreakpointSpec(GdbModelTargetBreakpointContainer breakpoints, GdbBreakpointInfo info) { super(breakpoints.impl, breakpoints, keyBreakpoint(info), "BreakpointSpec"); this.impl = breakpoints.impl; this.number = info.getNumber(); this.info = info; impl.addModelObject(info, this); changeAttributes(List.of(), Map.of(CONTAINER_ATTRIBUTE_NAME, breakpoints), "Initialized"); } protected CompletableFuture<Void> init() { return updateInfo(info, info, "Created").exceptionally(ex -> { Msg.info(this, "Initial breakpoint info update failed", ex); return null; }); } @Override public CompletableFuture<Void> delete() { return impl.gateFuture(impl.gdb.deleteBreakpoints(number)); } @Override public boolean isEnabled() { return enabled; } @Override public String getExpression() { return expression; } protected TargetBreakpointKindSet computeKinds(GdbBreakpointInfo from) { switch (from.getType()) { case BREAKPOINT: return TargetBreakpointKindSet.of(TargetBreakpointKind.SW_EXECUTE); case HW_BREAKPOINT: return TargetBreakpointKindSet.of(TargetBreakpointKind.HW_EXECUTE); case HW_WATCHPOINT: return TargetBreakpointKindSet.of(TargetBreakpointKind.WRITE); case READ_WATCHPOINT: return TargetBreakpointKindSet.of(TargetBreakpointKind.READ); case ACCESS_WATCHPOINT: return TargetBreakpointKindSet.of(TargetBreakpointKind.READ, TargetBreakpointKind.WRITE); default: return TargetBreakpointKindSet.of(); } } @Override public TargetBreakpointKindSet getKinds() { return kinds; } @Override public void addAction(TargetBreakpointAction action) { actions.add(action); } @Override public void removeAction(TargetBreakpointAction action) { actions.remove(action); } protected CompletableFuture<GdbBreakpointInfo> getInfo(boolean refresh) { if (!refresh) { return CompletableFuture.completedFuture(impl.gdb.getKnownBreakpoints().get(number)); } return impl.gdb.listBreakpoints() .thenApply(__ -> impl.gdb.getKnownBreakpoints().get(number)); } @Override public CompletableFuture<Void> requestElements(boolean refresh) { return getInfo(refresh).thenCompose(i -> { return updateInfo(info, i, "Refreshed"); }); } @Override public CompletableFuture<Void> disable() { return impl.gateFuture(impl.gdb.disableBreakpoints(number)); } @Override public CompletableFuture<Void> enable() { return impl.gateFuture(impl.gdb.enableBreakpoints(number)); } protected CompletableFuture<Void> updateInfo(GdbBreakpointInfo oldInfo, GdbBreakpointInfo newInfo, String reason) { if (newInfo.getType().isWatchpoint()) { return updateWptInfo(oldInfo, newInfo, reason); } else { return updateBktpInfo(oldInfo, newInfo, reason); } } protected void updateAttributesFromInfo(String reason) { changeAttributes(List.of(), Map.of( ENABLED_ATTRIBUTE_NAME, enabled = info.isEnabled(), EXPRESSION_ATTRIBUTE_NAME, expression = info.getType() == GdbBreakpointType.CATCHPOINT ? info.getCatchType() : info.getOriginalLocation(), KINDS_ATTRIBUTE_NAME, kinds = computeKinds(info), DISPLAY_ATTRIBUTE_NAME, display = computeDisplay()), reason); } protected synchronized List<GdbModelTargetBreakpointLocation> setInfoAndComputeLocations( GdbBreakpointInfo oldInfo, GdbBreakpointInfo newInfo) { if (oldInfo != this.info) { Msg.error(this, "Manager and model breakpoint info was/is out of sync!"); } this.info = newInfo; List<GdbModelTargetBreakpointLocation> effectives = newInfo.getLocations() .stream() .filter(l -> !"<PENDING>".equals(l.getAddr())) .map(this::getTargetBreakpointLocation) .collect(Collectors.toList()); breaksBySub.keySet() .retainAll( effectives.stream().map(e -> e.loc.getSub()).collect(Collectors.toSet())); return effectives; } protected CompletableFuture<Void> updateBktpInfo(GdbBreakpointInfo oldInfo, GdbBreakpointInfo newInfo, String reason) { List<GdbModelTargetBreakpointLocation> locs = setInfoAndComputeLocations(oldInfo, newInfo); updateAttributesFromInfo(reason); setElements(locs, reason); return AsyncUtils.NIL; } protected CompletableFuture<Void> updateWptInfo(GdbBreakpointInfo oldInfo, GdbBreakpointInfo newInfo, String reason) { List<GdbModelTargetBreakpointLocation> locs = setInfoAndComputeLocations(oldInfo, newInfo); updateAttributesFromInfo(reason); assert locs.size() == 1; return locs.get(0).initWpt().thenAccept(__ -> { setElements(locs, reason); }); } protected GdbModelTargetBreakpointLocation findLocation(GdbModelTargetStackFrame frame) { for (GdbModelTargetBreakpointLocation bp : breaksBySub.values()) { // TODO: Is this necessary? /*if (bp.range.contains(frame.pc)) { continue; }*/ if (!bp.loc.getInferiorIds().contains(frame.inferior.inferior.getId())) { continue; } return bp; } return null; } protected void breakpointHit(GdbModelTargetStackFrame frame, GdbModelTargetBreakpointLocation eb) { actions.fire.breakpointHit(this, frame.thread, frame, eb); } public synchronized GdbModelTargetBreakpointLocation getTargetBreakpointLocation( GdbBreakpointLocation loc) { return breaksBySub.computeIfAbsent(loc.getSub(), i -> new GdbModelTargetBreakpointLocation(this, loc)); } protected String addressFromInfo() { if (info.getAddress() != null) { return info.getAddress(); } List<GdbBreakpointLocation> locs = info.getLocations(); if (locs.isEmpty()) { return "<PENDING>"; } if (locs.size() == 1) { String addr = locs.get(0).getAddr(); if (addr == null) { return "<PENDING>"; } return addr; } return "<MULTIPLE>"; } protected String computeDisplay() { Object enb = info.isEnabled() ? "y" : "n"; String addr = addressFromInfo(); String what = info.getWhat() == null ? "" : info.getWhat(); switch (info.getType()) { case ACCESS_WATCHPOINT: case HW_WATCHPOINT: case READ_WATCHPOINT: case BREAKPOINT: case HW_BREAKPOINT: case OTHER: return String.format("%d %s %s %s %s %s", info.getNumber(), info.getTypeName(), info.getDisp(), enb, addr, what).trim(); case CATCHPOINT: return String.format("%d %s %s %s %s", info.getNumber(), info.getTypeName(), info.getDisp(), enb, what).trim(); case DPRINTF: // TODO: script? return String.format("%d %s %s %s %s %s", info.getNumber(), info.getTypeName(), info.getDisp(), enb, addr, what).trim(); } throw new AssertionError(); } @Override public String getDisplay() { return display; } @Override public GdbModelTargetBreakpointContainer getContainer() { return parent; } }
NationalSecurityAgency/ghidra
Ghidra/Debug/Debugger-agent-gdb/src/main/java/agent/gdb/model/impl/GdbModelTargetBreakpointSpec.java
Java
apache-2.0
9,156
package e2e.org.rockm.blink; import org.apache.http.client.HttpClient; import org.apache.http.impl.client.HttpClientBuilder; import org.junit.Before; import org.rockm.blink.BlinkServer; import static e2e.org.rockm.blink.support.HttpUtil.PORT; public class BlinkServerTest { protected static BlinkServer blinkServer; protected final HttpClient httpClient = HttpClientBuilder.create().build(); @Before public void setUp() throws Exception { if(blinkServer == null) { blinkServer = new BlinkServer(PORT); } blinkServer.reset(); } }
rockem/blink-java
src/test/java/e2e/org/rockm/blink/BlinkServerTest.java
Java
apache-2.0
591
package org.hua.ds; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; /** * Marker interface used by implementations to indicate that an operation takes * O(n) time where n is the size of the input. The primary purpose of this * interface is to allow generic algorithms to alter their behavior to provide * good performance. */ @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.METHOD) public @interface LinearTime { /** * Whether the running time is amortized or worst-case. * * @return {@code true} if amortized, {@code false} if worst-case */ public boolean amortized() default false; }
d-michail/hds
src/main/java/org/hua/ds/LinearTime.java
Java
apache-2.0
744
package com.googlecode.blaisemath.json; /*- * #%L * blaise-json * -- * Copyright (C) 2019 - 2021 Elisha Peterson * -- * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * #L% */ import com.fasterxml.jackson.core.JsonGenerator; import com.fasterxml.jackson.databind.JsonSerializer; import com.fasterxml.jackson.databind.SerializerProvider; import com.googlecode.blaisemath.encode.FontCoder; import java.awt.*; import java.io.IOException; /** * Serializes fonts as json strings/ * @author Elisha Peterson */ public class FontSerializer extends JsonSerializer<Font> { @Override public void serialize(Font value, JsonGenerator gen, SerializerProvider serializers) throws IOException { gen.writeString(new FontCoder().encode(value)); } }
triathematician/blaisemath
blaise-json/src/main/java/com/googlecode/blaisemath/json/FontSerializer.java
Java
apache-2.0
1,276
/* * DBeaver - Universal Database Manager * Copyright (C) 2010-2021 DBeaver Corp and others * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.jkiss.dbeaver.ext.mysql.model; import org.jkiss.code.NotNull; import org.jkiss.code.Nullable; import org.jkiss.dbeaver.DBException; import org.jkiss.dbeaver.ext.mysql.MySQLConstants; import org.jkiss.dbeaver.model.DBPEvaluationContext; import org.jkiss.dbeaver.model.DBUtils; import org.jkiss.dbeaver.model.exec.jdbc.JDBCPreparedStatement; import org.jkiss.dbeaver.model.exec.jdbc.JDBCResultSet; import org.jkiss.dbeaver.model.exec.jdbc.JDBCSession; import org.jkiss.dbeaver.model.impl.jdbc.JDBCDataSource; import org.jkiss.dbeaver.model.impl.jdbc.JDBCStructureAssistant; import org.jkiss.dbeaver.model.impl.jdbc.JDBCUtils; import org.jkiss.dbeaver.model.impl.struct.AbstractObjectReference; import org.jkiss.dbeaver.model.impl.struct.RelationalObjectType; import org.jkiss.dbeaver.model.runtime.DBRProgressMonitor; import org.jkiss.dbeaver.model.struct.DBSObject; import org.jkiss.dbeaver.model.struct.DBSObjectReference; import org.jkiss.dbeaver.model.struct.DBSObjectType; import java.sql.SQLException; import java.util.List; import java.util.Locale; /** * MySQLStructureAssistant */ public class MySQLStructureAssistant extends JDBCStructureAssistant<MySQLExecutionContext> { private final MySQLDataSource dataSource; public MySQLStructureAssistant(MySQLDataSource dataSource) { this.dataSource = dataSource; } @Override protected JDBCDataSource getDataSource() { return dataSource; } @Override public DBSObjectType[] getSupportedObjectTypes() { return new DBSObjectType[] { RelationalObjectType.TYPE_TABLE, RelationalObjectType.TYPE_CONSTRAINT, RelationalObjectType.TYPE_PROCEDURE, RelationalObjectType.TYPE_TABLE_COLUMN, }; } @Override public DBSObjectType[] getHyperlinkObjectTypes() { return new DBSObjectType[] { RelationalObjectType.TYPE_TABLE, RelationalObjectType.TYPE_PROCEDURE }; } @Override public DBSObjectType[] getAutoCompleteObjectTypes() { return new DBSObjectType[] { RelationalObjectType.TYPE_TABLE, RelationalObjectType.TYPE_PROCEDURE, }; } @Override protected void findObjectsByMask(@NotNull MySQLExecutionContext executionContext, @NotNull JDBCSession session, @NotNull DBSObjectType objectType, @NotNull ObjectsSearchParams params, @NotNull List<DBSObjectReference> references) throws SQLException { MySQLCatalog catalog = params.getParentObject() instanceof MySQLCatalog ? (MySQLCatalog) params.getParentObject() : null; if (catalog == null && !params.isGlobalSearch()) { catalog = executionContext.getContextDefaults().getDefaultCatalog(); } if (objectType == RelationalObjectType.TYPE_TABLE) { findTablesByMask(session, catalog, params, references); } else if (objectType == RelationalObjectType.TYPE_CONSTRAINT) { findConstraintsByMask(session, catalog, params, references); } else if (objectType == RelationalObjectType.TYPE_PROCEDURE) { findProceduresByMask(session, catalog, params, references); } else if (objectType == RelationalObjectType.TYPE_TABLE_COLUMN) { findTableColumnsByMask(session, catalog, params, references); } } private void findTablesByMask(JDBCSession session, @Nullable final MySQLCatalog catalog, @NotNull ObjectsSearchParams params, List<DBSObjectReference> objects) throws SQLException { DBRProgressMonitor monitor = session.getProgressMonitor(); QueryParams queryParams = new QueryParams( MySQLConstants.COL_TABLE_NAME, MySQLConstants.COL_TABLE_SCHEMA + "," + MySQLConstants.COL_TABLE_NAME, MySQLConstants.META_TABLE_TABLES ); if (params.isSearchInComments()) { queryParams.setCommentColumnName("TABLE_COMMENT"); } if (catalog != null) { queryParams.setSchemaColumnName(MySQLConstants.COL_TABLE_SCHEMA); } queryParams.setMaxResults(params.getMaxResults() - objects.size()); String sql = generateQuery(queryParams); // Load tables try (JDBCPreparedStatement dbStat = session.prepareStatement(sql)) { fillParameters(dbStat, params, catalog, true, false); try (JDBCResultSet dbResult = dbStat.executeQuery()) { while (!monitor.isCanceled() && dbResult.next()) { final String catalogName = JDBCUtils.safeGetString(dbResult, MySQLConstants.COL_TABLE_SCHEMA); final String tableName = JDBCUtils.safeGetString(dbResult, MySQLConstants.COL_TABLE_NAME); objects.add(new AbstractObjectReference(tableName, dataSource.getCatalog(catalogName), null, MySQLTableBase.class, RelationalObjectType.TYPE_TABLE) { @Override public DBSObject resolveObject(DBRProgressMonitor monitor) throws DBException { MySQLCatalog tableCatalog = catalog != null ? catalog : dataSource.getCatalog(catalogName); if (tableCatalog == null) { throw new DBException("Table catalog '" + catalogName + "' not found"); } MySQLTableBase table = tableCatalog.getTableCache().getObject(monitor, tableCatalog, tableName); if (table == null) { throw new DBException("Table '" + tableName + "' not found in catalog '" + catalogName + "'"); } return table; } }); } } } } private void findProceduresByMask(JDBCSession session, @Nullable final MySQLCatalog catalog, @NotNull ObjectsSearchParams params, List<DBSObjectReference> objects) throws SQLException { DBRProgressMonitor monitor = session.getProgressMonitor(); QueryParams queryParams = new QueryParams( MySQLConstants.COL_ROUTINE_NAME, MySQLConstants.COL_ROUTINE_SCHEMA + "," + MySQLConstants.COL_ROUTINE_NAME, MySQLConstants.META_TABLE_ROUTINES ); if (params.isSearchInComments()) { queryParams.setCommentColumnName("ROUTINE_COMMENT"); } if (catalog != null) { queryParams.setSchemaColumnName(MySQLConstants.COL_ROUTINE_SCHEMA); } queryParams.setMaxResults(params.getMaxResults() - objects.size()); if (params.isSearchInDefinitions()) { queryParams.setDefinitionColumnName(MySQLConstants.COL_ROUTINE_DEFINITION); } String sql = generateQuery(queryParams); // Load procedures try (JDBCPreparedStatement dbStat = session.prepareStatement(sql)) { fillParameters(dbStat, params, catalog, true, true); try (JDBCResultSet dbResult = dbStat.executeQuery()) { while (!monitor.isCanceled() && dbResult.next()) { final String catalogName = JDBCUtils.safeGetString(dbResult, MySQLConstants.COL_ROUTINE_SCHEMA); final String procName = JDBCUtils.safeGetString(dbResult, MySQLConstants.COL_ROUTINE_NAME); objects.add(new AbstractObjectReference(procName, dataSource.getCatalog(catalogName), null, MySQLProcedure.class, RelationalObjectType.TYPE_PROCEDURE) { @Override public DBSObject resolveObject(DBRProgressMonitor monitor) throws DBException { MySQLCatalog procCatalog = catalog != null ? catalog : dataSource.getCatalog(catalogName); if (procCatalog == null) { throw new DBException("Procedure catalog '" + catalogName + "' not found"); } MySQLProcedure procedure = procCatalog.getProcedure(monitor, procName); if (procedure == null) { throw new DBException("Procedure '" + procName + "' not found in catalog '" + procCatalog.getName() + "'"); } return procedure; } }); } } } } private void findConstraintsByMask(JDBCSession session, @Nullable final MySQLCatalog catalog, @NotNull ObjectsSearchParams params, List<DBSObjectReference> objects) throws SQLException { DBRProgressMonitor monitor = session.getProgressMonitor(); QueryParams queryParams = new QueryParams( MySQLConstants.COL_CONSTRAINT_NAME, MySQLConstants.COL_TABLE_SCHEMA + "," + MySQLConstants.COL_TABLE_NAME + "," + MySQLConstants.COL_CONSTRAINT_NAME + "," + MySQLConstants.COL_CONSTRAINT_TYPE, MySQLConstants.META_TABLE_TABLE_CONSTRAINTS ); if (catalog != null) { queryParams.setSchemaColumnName(MySQLConstants.COL_TABLE_SCHEMA); } queryParams.setMaxResults(params.getMaxResults() - objects.size()); String sql = generateQuery(queryParams); // Load constraints try (JDBCPreparedStatement dbStat = session.prepareStatement(sql)) { fillParameters(dbStat, params, catalog, false, false); try (JDBCResultSet dbResult = dbStat.executeQuery()) { while (!monitor.isCanceled() && dbResult.next()) { final String catalogName = JDBCUtils.safeGetString(dbResult, MySQLConstants.COL_TABLE_SCHEMA); final String tableName = JDBCUtils.safeGetString(dbResult, MySQLConstants.COL_TABLE_NAME); final String constrName = JDBCUtils.safeGetString(dbResult, MySQLConstants.COL_CONSTRAINT_NAME); final String constrType = JDBCUtils.safeGetString(dbResult, MySQLConstants.COL_CONSTRAINT_TYPE); final boolean isFK = MySQLConstants.CONSTRAINT_FOREIGN_KEY.equals(constrType); final boolean isCheck = MySQLConstants.CONSTRAINT_CHECK.equals(constrType); objects.add(new AbstractObjectReference(constrName, dataSource.getCatalog(catalogName), null, isFK ? MySQLTableForeignKey.class : MySQLTableConstraint.class, RelationalObjectType.TYPE_CONSTRAINT) { @Override public DBSObject resolveObject(DBRProgressMonitor monitor) throws DBException { MySQLCatalog tableCatalog = catalog != null ? catalog : dataSource.getCatalog(catalogName); if (tableCatalog == null) { throw new DBException("Constraint catalog '" + catalogName + "' not found"); } MySQLTable table = tableCatalog.getTable(monitor, tableName); if (table == null) { throw new DBException("Constraint table '" + tableName + "' not found in catalog '" + tableCatalog.getName() + "'"); } DBSObject constraint; if (isFK) { constraint = table.getAssociation(monitor, constrName); } else if (isCheck) { constraint = table.getCheckConstraint(monitor, constrName); } else { constraint = table.getUniqueKey(monitor, constrName); } if (constraint == null) { throw new DBException("Constraint '" + constrName + "' not found in table '" + table.getFullyQualifiedName(DBPEvaluationContext.DDL) + "'"); } return constraint; } }); } } } } private void findTableColumnsByMask(JDBCSession session, @Nullable final MySQLCatalog catalog, @NotNull ObjectsSearchParams params, List<DBSObjectReference> objects) throws SQLException { DBRProgressMonitor monitor = session.getProgressMonitor(); QueryParams queryParams = new QueryParams( MySQLConstants.COL_COLUMN_NAME, MySQLConstants.COL_TABLE_SCHEMA + "," + MySQLConstants.COL_TABLE_NAME + "," + MySQLConstants.COL_COLUMN_NAME, MySQLConstants.META_TABLE_COLUMNS ); if (params.isSearchInComments()) { queryParams.setCommentColumnName("COLUMN_COMMENT"); } if (catalog != null) { queryParams.setSchemaColumnName(MySQLConstants.COL_TABLE_SCHEMA); } queryParams.setMaxResults(params.getMaxResults() - objects.size()); if (params.isSearchInDefinitions()) { queryParams.setDefinitionColumnName(MySQLConstants.COL_COLUMN_GENERATION_EXPRESSION); } String sql = generateQuery(queryParams); // Load columns try (JDBCPreparedStatement dbStat = session.prepareStatement(sql)) { fillParameters(dbStat, params, catalog, true, true); try (JDBCResultSet dbResult = dbStat.executeQuery()) { while (!monitor.isCanceled() && dbResult.next()) { final String catalogName = JDBCUtils.safeGetString(dbResult, MySQLConstants.COL_TABLE_SCHEMA); final String tableName = JDBCUtils.safeGetString(dbResult, MySQLConstants.COL_TABLE_NAME); final String columnName = JDBCUtils.safeGetString(dbResult, MySQLConstants.COL_COLUMN_NAME); objects.add(new AbstractObjectReference(columnName, dataSource.getCatalog(catalogName), null, MySQLTableColumn.class, RelationalObjectType.TYPE_TABLE_COLUMN) { @NotNull @Override public String getFullyQualifiedName(DBPEvaluationContext context) { return DBUtils.getQuotedIdentifier(dataSource, catalogName) + '.' + DBUtils.getQuotedIdentifier(dataSource, tableName) + '.' + DBUtils.getQuotedIdentifier(dataSource, columnName); } @Override public DBSObject resolveObject(DBRProgressMonitor monitor) throws DBException { MySQLCatalog tableCatalog = catalog != null ? catalog : dataSource.getCatalog(catalogName); if (tableCatalog == null) { throw new DBException("Column catalog '" + catalogName + "' not found"); } MySQLTableBase table = tableCatalog.getTableCache().getObject(monitor, tableCatalog, tableName); if (table == null) { throw new DBException("Column table '" + tableName + "' not found in catalog '" + tableCatalog.getName() + "'"); } MySQLTableColumn column = table.getAttribute(monitor, columnName); if (column == null) { throw new DBException("Column '" + columnName + "' not found in table '" + table.getFullyQualifiedName(DBPEvaluationContext.DDL) + "'"); } return column; } }); } } } } private static String generateQuery(@NotNull QueryParams params) { StringBuilder sql = new StringBuilder("SELECT ").append(params.getSelect()).append(" FROM ").append(params.getFrom()).append(" WHERE "); boolean addParentheses = params.getCommentColumnName() != null || params.getDefinitionColumnName() != null; if (addParentheses) { sql.append("("); } sql.append(params.getObjectNameColumn()).append(" LIKE ? "); if (params.getCommentColumnName() != null) { sql.append("OR ").append(params.getCommentColumnName()).append(" LIKE ?"); } if (params.getDefinitionColumnName() != null) { sql.append(" OR ").append(params.getDefinitionColumnName()).append(" LIKE ?"); } if (addParentheses) { sql.append(") "); } if (params.getSchemaColumnName() != null) { sql.append("AND ").append(params.getSchemaColumnName()).append(" = ? "); } sql.append("ORDER BY ").append(params.getObjectNameColumn()).append(" LIMIT ").append(params.getMaxResults()); return sql.toString(); } private static void fillParameters(@NotNull JDBCPreparedStatement statement, @NotNull ObjectsSearchParams params, @Nullable MySQLCatalog catalog, boolean hasCommentColumn, boolean hasDefinitionColumn) throws SQLException { String mask = params.getMask().toLowerCase(Locale.ENGLISH); statement.setString(1, mask); int idx = 2; if (params.isSearchInComments() && hasCommentColumn) { statement.setString(idx, mask); idx++; } if (params.isSearchInDefinitions() && hasDefinitionColumn) { statement.setString(idx, mask); idx++; } if (catalog != null) { statement.setString(idx, catalog.getName()); } } private static final class QueryParams { @NotNull private final String objectNameColumn; @Nullable private String commentColumnName; @Nullable private String schemaColumnName; @NotNull private final String select; @NotNull private final String from; private int maxResults; @Nullable private String definitionColumnName; private QueryParams(@NotNull String objectNameColumn, @NotNull String select, @NotNull String from) { this.objectNameColumn = objectNameColumn; this.select = select; this.from = from; } @NotNull private String getObjectNameColumn() { return objectNameColumn; } @Nullable private String getCommentColumnName() { return commentColumnName; } private void setCommentColumnName(@Nullable String commentColumnName) { this.commentColumnName = commentColumnName; } @Nullable private String getSchemaColumnName() { return schemaColumnName; } private void setSchemaColumnName(@Nullable String schemaColumnName) { this.schemaColumnName = schemaColumnName; } @NotNull public String getSelect() { return select; } @NotNull public String getFrom() { return from; } @Nullable private String getDefinitionColumnName() { return definitionColumnName; } private void setDefinitionColumnName(@Nullable String definitionColumnName) { this.definitionColumnName = definitionColumnName; } private int getMaxResults() { return maxResults; } private void setMaxResults(int maxResults) { this.maxResults = maxResults; } } @Override public boolean supportsSearchInCommentsFor(@NotNull DBSObjectType objectType) { return objectType == RelationalObjectType.TYPE_TABLE || objectType == RelationalObjectType.TYPE_PROCEDURE || objectType == RelationalObjectType.TYPE_TABLE_COLUMN; } @Override public boolean supportsSearchInDefinitionsFor(@NotNull DBSObjectType objectType) { return objectType == RelationalObjectType.TYPE_PROCEDURE || objectType == RelationalObjectType.TYPE_TABLE_COLUMN; } }
Sargul/dbeaver
plugins/org.jkiss.dbeaver.ext.mysql/src/org/jkiss/dbeaver/ext/mysql/model/MySQLStructureAssistant.java
Java
apache-2.0
21,155
/******************************************************************************* * Copyright 2016, 2018 elasql.org 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.elasql.procedure.calvin; import java.util.logging.Level; import java.util.logging.Logger; import org.elasql.cache.CachedRecord; import org.elasql.remote.groupcomm.TupleSet; import org.elasql.schedule.calvin.ExecutionPlan; import org.elasql.schedule.calvin.ExecutionPlan.ParticipantRole; import org.elasql.schedule.calvin.ReadWriteSetAnalyzer; import org.elasql.server.Elasql; import org.elasql.sql.PrimaryKey; import org.elasql.storage.metadata.NotificationPartitionPlan; import org.vanilladb.core.sql.Constant; import org.vanilladb.core.sql.IntegerConstant; import org.vanilladb.core.sql.storedprocedure.StoredProcedureParamHelper; /** * A stored procedure that executes its logic on all the machines. * * @author SLMT * * @param <H> the type of parameter helpers for this stored procedure */ public abstract class AllExecuteProcedure<H extends StoredProcedureParamHelper> extends CalvinStoredProcedure<H> { private static Logger logger = Logger.getLogger(AllExecuteProcedure.class.getName()); private static final String KEY_FINISH = "finish"; private static final int MASTER_NODE = 0; private int localNodeId = Elasql.serverId(); private int numOfParts; public AllExecuteProcedure(long txNum, H paramHelper) { super(txNum, paramHelper); numOfParts = Elasql.partitionMetaMgr().getCurrentNumOfParts(); } @Override protected ExecutionPlan analyzeParameters(Object[] pars) { ExecutionPlan plan = super.analyzeParameters(pars); return alterExecutionPlan(plan); } @Override public boolean willResponseToClients() { // The master node is the only one that will response to the clients. return localNodeId == MASTER_NODE; } @Override public boolean isReadOnly() { return false; } @Override protected void prepareKeys(ReadWriteSetAnalyzer analyzer) { // default: do nothing } private ExecutionPlan alterExecutionPlan(ExecutionPlan plan) { if (localNodeId == MASTER_NODE) { for (int nodeId = 0; nodeId < numOfParts; nodeId++) plan.addRemoteReadKey(NotificationPartitionPlan.createRecordKey(nodeId, MASTER_NODE)); } plan.setParticipantRole(ParticipantRole.ACTIVE); plan.setForceReadWriteTx(); return plan; } @Override protected void executeTransactionLogic() { executeSql(null); // Notification for finish if (localNodeId == MASTER_NODE) { if (logger.isLoggable(Level.INFO)) logger.info("Waiting for other servers..."); // Master: Wait for notification from other nodes waitForNotification(); if (logger.isLoggable(Level.INFO)) logger.info("Other servers completion comfirmed."); } else { // Salve: Send notification to the master sendNotification(); } } private void waitForNotification() { // Wait for notification from other nodes for (int nodeId = 0; nodeId < numOfParts; nodeId++) if (nodeId != MASTER_NODE) { if (logger.isLoggable(Level.FINE)) logger.fine("Waiting for the notification from node no." + nodeId); PrimaryKey notKey = NotificationPartitionPlan.createRecordKey(nodeId, MASTER_NODE); CachedRecord rec = cacheMgr.readFromRemote(notKey); Constant con = rec.getVal(KEY_FINISH); int value = (int) con.asJavaVal(); if (value != 1) throw new RuntimeException("Notification value error, node no." + nodeId + " sent " + value); if (logger.isLoggable(Level.FINE)) logger.fine("Receive notification from node no." + nodeId); } } private void sendNotification() { // Create a key value set PrimaryKey notKey = NotificationPartitionPlan.createRecordKey(Elasql.serverId(), MASTER_NODE); CachedRecord notVal = NotificationPartitionPlan.createRecord(Elasql.serverId(), MASTER_NODE, txNum); notVal.addFldVal(KEY_FINISH, new IntegerConstant(1)); TupleSet ts = new TupleSet(-1); // Use node id as source tx number ts.addTuple(notKey, txNum, txNum, notVal); Elasql.connectionMgr().pushTupleSet(0, ts); if (logger.isLoggable(Level.FINE)) logger.fine("The notification is sent to the master by tx." + txNum); } }
elasql/elasql
src/main/java/org/elasql/procedure/calvin/AllExecuteProcedure.java
Java
apache-2.0
4,927
/* * $Header: /var/chroot/cvs/cvs/factsheetDesigner/extern/jakarta-slide-server-src-2.1-iPlus Edit/src/share/org/apache/slide/search/basic/expression/MergeExpression.java,v 1.2 2006-01-22 22:49:05 peter-cvs Exp $ * $Revision: 1.2 $ * $Date: 2006-01-22 22:49:05 $ * * ==================================================================== * * Copyright 1999-2002 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package org.apache.slide.search.basic.expression; import java.util.Collection; import java.util.Iterator; import org.apache.slide.search.InvalidQueryException; import org.apache.slide.search.SearchException; import org.apache.slide.search.basic.IBasicExpression; import org.apache.slide.search.basic.IBasicResultSet; import org.jdom.a.Element; /** * Abstract base class for merge expressions (AND, OR). * * @version $Revision: 1.2 $ */ public abstract class MergeExpression extends GenericBasicExpression { /** all nested expressions */ private Collection expressionsToMerge = null; /** * Creates a merge expression according to Element e * * @param e jdom element, that describes the expression * @param expressionsToMerge a Collection of IBasicExpressions to merge. */ MergeExpression (Element e, Collection expressionsToMerge) throws InvalidQueryException { super (e); this.expressionsToMerge = expressionsToMerge; if (expressionsToMerge.size() == 0) { throw new InvalidQueryException(getMustHaveMergeExpressionsMessage(e.getName())); } } /** * Executes the expression. * * @return a Set of RequestedResource objects * * @throws SearchException */ public IBasicResultSet execute () throws SearchException { Iterator iterator = expressionsToMerge.iterator(); if (iterator.hasNext()) { resultSet = ((IBasicExpression)iterator.next()).execute(); } while (iterator.hasNext()) { IBasicExpression expression = (IBasicExpression)iterator.next(); merge(expression.execute()); } return resultSet; } /** * Merges the given <code>set</code> into the result Set of this expression. * * @param set the Set to merge. */ protected abstract void merge (IBasicResultSet set); /** * String representation for debugging purposes. * * @return this expression as String */ protected String toString (String op) { StringBuffer sb = new StringBuffer(); Iterator it = expressionsToMerge.iterator(); while (it.hasNext()) { sb.append (((IBasicExpression) it.next()).toString()); if (it.hasNext()) sb.append (" ").append (op).append (" "); } return sb.toString(); } /** * Returns the message of the InvalidQueryException that is thrown by the * constructor the <code>expressionsToMerge</code> set is empty. * * @param operationName the name of the operation (e.g. <code>and</code>) * * @return the message of the InvalidQueryException. */ private static String getMustHaveMergeExpressionsMessage(String operationName) { return "<" + operationName + "> must have at least on nested expression."; } }
integrated/jakarta-slide-server
src/share/org/apache/slide/search/basic/expression/MergeExpression.java
Java
apache-2.0
3,917
package org.intellij.plugins.intelliLang.inject; import java.util.ArrayList; import java.util.List; import javax.annotation.Nonnull; import consulo.psi.injection.AbstractLanguageInjectionSupport; import consulo.psi.injection.LanguageInjectionSupport; import org.intellij.plugins.intelliLang.inject.config.BaseInjection; import com.intellij.lang.injection.MultiHostInjector; import com.intellij.lang.injection.MultiHostRegistrar; import com.intellij.psi.PsiComment; import com.intellij.psi.PsiElement; import com.intellij.psi.PsiLanguageInjectionHost; import com.intellij.util.ArrayUtil; /** * @author gregsh */ public class CommentLanguageInjector implements MultiHostInjector { private final LanguageInjectionSupport[] mySupports; private final LanguageInjectionSupport myInjectorSupport = new AbstractLanguageInjectionSupport() { @Nonnull @Override public String getId() { return "comment"; } @Override public boolean isApplicableTo(PsiLanguageInjectionHost host) { return true; } @Nonnull @Override public Class[] getPatternClasses() { return ArrayUtil.EMPTY_CLASS_ARRAY; } }; public CommentLanguageInjector() { List<LanguageInjectionSupport> supports = new ArrayList<LanguageInjectionSupport>(InjectorUtils.getActiveInjectionSupports()); supports.add(myInjectorSupport); mySupports = ArrayUtil.toObjectArray(supports, LanguageInjectionSupport.class); } public void injectLanguages(@Nonnull final MultiHostRegistrar registrar, @Nonnull final PsiElement context) { if (!(context instanceof PsiLanguageInjectionHost) || context instanceof PsiComment) return; if (!((PsiLanguageInjectionHost)context).isValidHost()) return; PsiLanguageInjectionHost host = (PsiLanguageInjectionHost)context; boolean applicableFound = false; for (LanguageInjectionSupport support : mySupports) { if (!support.isApplicableTo(host)) continue; if (support == myInjectorSupport && applicableFound) continue; applicableFound = true; BaseInjection injection = support.findCommentInjection(host, null); if (injection == null) continue; if (!InjectorUtils.registerInjectionSimple(host, injection, support, registrar)) continue; return; } } }
consulo/consulo
modules/base/lang-injecting-impl/src/main/java/org/intellij/plugins/intelliLang/inject/CommentLanguageInjector.java
Java
apache-2.0
2,284
package com.yuzhouwan.step; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import org.junit.Before; import org.junit.Test; public class MyStep { private static int stepNum; private static int[] init = { 0, 1, 2, 4 }; @Before public void init() throws IOException { BufferedReader reader = new BufferedReader(new InputStreamReader( System.in)); stepNum = Integer.parseInt(reader.readLine()); } @Test public void test() { System.out.println(step(stepNum)); } /** * 0 0 * 1 1 * 2 2 * 3 4(111, 12, 21, 3) * 4 7(1111, 211, 121, 112, 31, 13, 22) * * f(n) f(n-1) + f(n-2) + f(n-3) * * @return */ private static int step(int step) { if (step < 4) return init[step]; return step(step - 1) + step(step - 2) + step(step - 3); } }
MasteringJava/Arithmetic
递归/跳台阶/MyStep.java
Java
apache-2.0
835
package com.baozi.admin.modules.sys.dao; import com.baozi.admin.common.BaseDao; import com.baozi.admin.common.annotation.MybatisDao; import com.baozi.admin.modules.sys.entity.Role; import java.util.List; /** * Created by baozi on 2017/6/11. */ @MybatisDao public interface RoleDao extends BaseDao<Role> { List<Role> findListByUserId(String userId); void deleteRoleMenu(Role role); void insertRoleMenu(Role role); List<String> findMenuIdList(Role role); }
Eyre-zz/baozi_admin
src/main/java/com/baozi/admin/modules/sys/dao/RoleDao.java
Java
apache-2.0
500
// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root. package ai.vespa.rankingexpression.importer.operations; import ai.vespa.rankingexpression.importer.DimensionRenamer; import ai.vespa.rankingexpression.importer.IntermediateGraph; import ai.vespa.rankingexpression.importer.OrderedTensorType; import com.yahoo.searchlib.rankingexpression.Reference; import com.yahoo.searchlib.rankingexpression.evaluation.Context; import com.yahoo.searchlib.rankingexpression.evaluation.DoubleValue; import com.yahoo.searchlib.rankingexpression.evaluation.MapContext; import com.yahoo.searchlib.rankingexpression.evaluation.TensorValue; import com.yahoo.searchlib.rankingexpression.evaluation.Value; import com.yahoo.searchlib.rankingexpression.rule.ExpressionNode; import com.yahoo.searchlib.rankingexpression.rule.ReferenceNode; import com.yahoo.searchlib.rankingexpression.rule.TensorFunctionNode; import com.yahoo.tensor.Tensor; import com.yahoo.tensor.TensorType; import com.yahoo.tensor.evaluation.VariableTensor; import com.yahoo.tensor.functions.TensorFunction; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.Optional; import java.util.function.Function; import java.util.stream.Collectors; /** * Wraps an imported operation node and produces the respective Vespa tensor * operation. During import, a graph of these operations are constructed. Then, * the types are used to deduce sensible dimension names using the * DimensionRenamer. After the types have been renamed, the proper Vespa * expressions can be extracted. * * @author lesters */ public abstract class IntermediateOperation { public final static String FUNCTION_PREFIX = "imported_ml_function_"; protected final String name; protected final String modelName; protected final List<IntermediateOperation> inputs; protected final List<IntermediateOperation> outputs = new ArrayList<>(); protected OrderedTensorType type; protected TensorFunction<Reference> function; protected TensorFunction<Reference> rankingExpressionFunction = null; protected boolean exportAsRankingFunction = false; private boolean hasRenamedDimensions = false; private final List<String> importWarnings = new ArrayList<>(); private Value constantValue = null; private List<IntermediateOperation> controlInputs = Collections.emptyList(); protected Function<OrderedTensorType, Value> constantValueFunction = null; IntermediateOperation(String modelName, String name, List<IntermediateOperation> inputs) { this.name = name; this.modelName = ensureValidAsDimensionName(modelName); this.inputs = new ArrayList<>(inputs); this.inputs.forEach(i -> i.outputs.add(this)); } protected abstract OrderedTensorType lazyGetType(); protected abstract TensorFunction<Reference> lazyGetFunction(); public String modelName() { return modelName; } /** Returns the Vespa tensor type of this operation if it exists */ public Optional<OrderedTensorType> type() { if (type == null) { type = lazyGetType(); } return Optional.ofNullable(type); } /** Returns the Vespa tensor function implementing all operations from this node with inputs */ public Optional<TensorFunction<Reference>> function() { if (function == null) { if (isConstant()) { ExpressionNode constant = new ReferenceNode(Reference.simple("constant", vespaName())); function = new TensorFunctionNode.ExpressionTensorFunction(constant); } else if (outputs.size() > 1 || exportAsRankingFunction) { rankingExpressionFunction = lazyGetFunction(); function = new VariableTensor<Reference>(rankingExpressionFunctionName(), type.type()); } else { function = lazyGetFunction(); } } return Optional.ofNullable(function); } /** Returns original name of this operation node */ public String name() { return name; } /** Return unmodifiable list of inputs */ public List<IntermediateOperation> inputs() { return inputs; } /** Return unmodifiable list of outputs. If a node has multiple outputs, consider adding a function. */ public List<IntermediateOperation> outputs() { return Collections.unmodifiableList(outputs); } /** Returns a function that should be added as a ranking expression function */ public Optional<TensorFunction<Reference>> rankingExpressionFunction() { return Optional.ofNullable(rankingExpressionFunction); } /** Add dimension name constraints for this operation */ public void addDimensionNameConstraints(DimensionRenamer renamer) { } /** Convenience method to adds dimensions and constraints of the given tensor type */ protected void addConstraintsFrom(OrderedTensorType type, DimensionRenamer renamer) { for (int i = 0; i < type.dimensions().size(); i++) { renamer.addDimension(type.dimensions().get(i).name()); // Each dimension is distinct and ordered correctly: for (int j = i + 1; j < type.dimensions().size(); j++) { renamer.addConstraint(type.dimensions().get(i).name(), type.dimensions().get(j).name(), DimensionRenamer.Constraint.notEqual(false), this); } } } /** Performs dimension rename for this operation */ public void renameDimensions(DimensionRenamer renamer) { type = type.rename(renamer); hasRenamedDimensions = true; } /** Return true for operations that are inputs to the model itself (as opposed to inputs to the operation) */ public boolean isInput() { return false; } /** Return true if this node is constant */ public boolean isConstant() { return inputs.stream().allMatch(IntermediateOperation::isConstant); } /** Sets the constant value */ public void setConstantValue(Value value) { constantValue = value; } /** Gets the constant value if it exists */ public Optional<Value> getConstantValue() { if (constantValue != null) { return Optional.of(constantValue); } if (constantValueFunction != null) { return Optional.of(constantValueFunction.apply(type().orElse(null))); } return Optional.empty(); } /** Set the constant value function */ public void setConstantValueFunction(Function<OrderedTensorType, Value> func) { this.constantValueFunction = func; } /** Sets the external control inputs */ public void setControlInputs(List<IntermediateOperation> inputs) { this.controlInputs = inputs; } /** Retrieve the control inputs for this operation */ public List<IntermediateOperation> getControlInputs() { return Collections.unmodifiableList(this.controlInputs); } /** Retrieve the valid Vespa name of this node */ public String vespaName() { if (isConstant()) return modelName + "_" + vespaName(name); return vespaName(name); } public static String vespaName(String name) { return name != null ? namePartOf(name).replace('/', '_').replace('.', '_') : null; } /** Retrieve the valid Vespa name of this node if it is a ranking expression function */ public String rankingExpressionFunctionName() { String vespaName = vespaName(); if (vespaName == null) { return null; } return isConstant() ? "constant(" + vespaName + ")" : FUNCTION_PREFIX + modelName + "_" + vespaName; } /** Retrieve the list of warnings produced during its lifetime */ public List<String> warnings() { return Collections.unmodifiableList(importWarnings); } /** Set an input warning */ public void warning(String warning) { importWarnings.add(warning); } boolean verifyInputs(int expected, Function<IntermediateOperation, Optional<?>> func) { if (inputs.size() != expected) { throw new IllegalArgumentException("Expected " + expected + " inputs for '" + name + "', got " + inputs.size()); } return inputs.stream().map(func).allMatch(Optional::isPresent); } boolean allInputTypesPresent(int expected) { return verifyInputs(expected, IntermediateOperation::type); } boolean allInputFunctionsPresent(int expected) { return verifyInputs(expected, IntermediateOperation::function); } /** Recursively evaluates this operation's constant value to avoid doing it run-time. */ public Value evaluateAsConstant(OrderedTensorType type) { if ( ! isConstant() ) { throw new IllegalArgumentException("Attempted to evaluate non-constant operation as a constant."); } Value val = evaluableCopy().evaluateAsConstant(new MapContext(DoubleValue.NaN)); if (type == null) { return val; } Tensor tensor = val.asTensor(); checkIfRenameableTo(tensor, type); setConstantValueFunction(t -> new TensorValue(tensor.withType(t.type()))); // so we don't have to re-evaluate return new TensorValue(tensor.withType(type.type())); } private void checkIfRenameableTo(Tensor tensor, OrderedTensorType type) { if ( ! tensor.type().isRenamableTo(type.type()) ) { throw new IllegalArgumentException("Constant evaluation in " + name + " resulted in wrong type. " + "Expected: " + type.type() + " Got: " + tensor.type()); } } private IntermediateOperation evaluableCopy() { if (hasRenamedDimensions) { return this; } IntermediateOperation copy = copyTree(); // Must have performed dimension renaming to properly evaluate as constant IntermediateGraph graph = new IntermediateGraph(modelName); graph.put(name, copy); graph.outputs(graph.defaultSignature()).put(name, name); graph.optimize(); return copy; } private IntermediateOperation copyTree() { List<IntermediateOperation> in = new ArrayList<>(); if (constantValue != null) { IntermediateOperation constant = new Constant(modelName, name, type); constant.setConstantValueFunction(t -> new TensorValue(constantValue.asTensor().withType(t.type()))); return constant; } inputs.forEach(i -> in.add(i.copyTree())); IntermediateOperation copy = withInputs(in); if (constantValueFunction != null) { copy.constantValueFunction = constantValueFunction; } return copy; } private Value evaluateAsConstant(Context context) { String constantName = "constant(" + vespaName() + ")"; Value result = context.get(constantName); if (result == DoubleValue.NaN) { if (constantValue != null) { result = constantValue; } else if (inputs.size() == 0) { if (getConstantValue().isEmpty()) { throw new IllegalArgumentException("Error in evaluating constant for " + name); } result = getConstantValue().get(); } else { inputs.forEach(i -> i.evaluateAsConstant(context)); result = new TensorValue(lazyGetFunction().evaluate(context)); } context.put(constantName, result); if (outputs.size() > 1 || exportAsRankingFunction) { context.put(rankingExpressionFunctionName(), result); } } return result; } /** Insert an operation between an input and this one */ public void insert(IntermediateOperation operationToInsert, int inputNumber) { if ( operationToInsert.inputs.size() > 0 ) { throw new IllegalArgumentException("Operation to insert to '" + name + "' has " + "existing inputs which is not supported."); } IntermediateOperation previousInputOperation = inputs.get(inputNumber); int outputNumber = findOutputNumber(previousInputOperation, this); if (outputNumber == -1) { throw new IllegalArgumentException("Input '" + previousInputOperation.name + "' to '" + name + "' does not have '" + name + "' as output."); } previousInputOperation.outputs.set(outputNumber, operationToInsert); operationToInsert.inputs.add(previousInputOperation); operationToInsert.outputs.add(this); inputs.set(inputNumber, operationToInsert); } /** Remove an operation between an input and this one */ public void uninsert(int inputNumber) { IntermediateOperation operationToRemove = inputs.get(inputNumber); IntermediateOperation newInputOperation = operationToRemove.inputs.get(0); int outputNumber = findOutputNumber(newInputOperation, operationToRemove); newInputOperation.outputs.set(outputNumber, this); inputs.set(inputNumber, newInputOperation); } private int findOutputNumber(IntermediateOperation output, IntermediateOperation op) { for (int i = 0; i < output.outputs.size(); ++i) { if (output.outputs.get(i).equals(op)) { return i; } } return -1; } /** Removes outputs if they point to the same operation */ public void removeDuplicateOutputsTo(IntermediateOperation op) { int last, first = outputs.indexOf(op); while (first >= 0 && (last = outputs.lastIndexOf(op)) > first) { outputs.remove(last); } } /** * Returns the largest value type among the input value types. * This should only be called after it has been verified that input types are available. * * @throws IllegalArgumentException if a type cannot be uniquely determined * @throws RuntimeException if called when input types are not available */ TensorType.Value resultValueType() { return TensorType.Value.largestOf(inputs.stream() .map(input -> input.type().get().type().valueType()) .collect(Collectors.toList())); } public abstract IntermediateOperation withInputs(List<IntermediateOperation> inputs); String asString(Optional<OrderedTensorType> type) { return type.map(t -> t.toString()).orElse("(unknown)"); } /** * A method signature input and output has the form name:index. * This returns the name part without the index. */ public static String namePartOf(String name) { name = name.startsWith("^") ? name.substring(1) : name; return name.split(":")[0]; } /** * This return the output index part. Indexes are used for nodes with * multiple outputs. */ public static int indexPartOf(String name) { int i = name.indexOf(":"); return i < 0 ? 0 : Integer.parseInt(name.substring(i + 1)); } public abstract String operationName(); /** Required due to tensor dimension name restrictions */ private static String ensureValidAsDimensionName(String modelName) { return modelName.replaceAll("[^\\w\\d\\$@_]", "_"); } @Override public String toString() { return operationName() + "(" + inputs().stream().map(input -> asString(input.type())).collect(Collectors.joining(", ")) + ")"; } public String toFullString() { return "\t" + type + ":\t" + operationName() + "(" + inputs().stream().map(input -> input.toFullString()).collect(Collectors.joining(", ")) + ")"; } /** * An interface mapping operation attributes to Vespa Values. * Adapter for differences in different model types. */ public interface AttributeMap { Optional<Value> get(String key); Optional<Value> get(String key, OrderedTensorType type); Optional<List<Value>> getList(String key); } }
vespa-engine/vespa
model-integration/src/main/java/ai/vespa/rankingexpression/importer/operations/IntermediateOperation.java
Java
apache-2.0
16,261
package ru.rodionovsasha.shoppinglist.dto; import lombok.AllArgsConstructor; import lombok.Getter; @Getter @AllArgsConstructor class FieldErrorDto { private String field; private String message; }
rodionovsasha/ShoppingList
src/main/java/ru/rodionovsasha/shoppinglist/dto/FieldErrorDto.java
Java
apache-2.0
207
/* * Copyright 2011 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.gwt.testing.easygwtmock.client.internal; import java.util.HashMap; import java.util.Map; /** * An object that represents a method that can be called on a mock object. * * @author Michael Goderbauer */ public class Method { private final String name; private final Class<?> returnType; private final Class<?>[] declaredThrowables; private final Class<?>[] argumentTypes; private static Map<Class<?>, Object> defaultReturnValues = new HashMap<Class<?>, Object>(); static { defaultReturnValues.put(byte.class, (byte) 0); defaultReturnValues.put(short.class, (short) 0); defaultReturnValues.put(int.class, 0); defaultReturnValues.put(long.class, (long) 0); defaultReturnValues.put(float.class, (float) 0); defaultReturnValues.put(double.class, (double) 0); defaultReturnValues.put(boolean.class, false); defaultReturnValues.put(char.class, (char) 0); } public Method(String name, Class<?> returnType, Class<?>[] argumentTypes, Class<?>[] declaredThrowables) { this.name = name; this.returnType = returnType; this.declaredThrowables = declaredThrowables; this.argumentTypes = argumentTypes; } public String getName() { return this.name; } public Object getDefaultReturnValue() { return defaultReturnValues.get(this.returnType); } public boolean isReturnValueVoid() { return this.returnType.equals(void.class); } public boolean isReturnValuePrimitive() { return this.returnType.isPrimitive(); } public boolean canThrow(Throwable throwable) { if (throwable instanceof RuntimeException) { return true; } if (throwable instanceof Error) { return true; } Class<?> throwableClass = throwable.getClass(); for (Class<?> declaredThrowable : this.declaredThrowables) { if (Utils.isSubclass(throwableClass, declaredThrowable)) { return true; } } return false; } public Class<?>[] getArgumentTypes() { return this.argumentTypes; } @Override public String toString() { StringBuilder result = new StringBuilder(this.name); result.append("("); for (Class<?> argument : this.argumentTypes) { result.append(Utils.cutPackage(argument.getName())).append(", "); } if (this.argumentTypes.length > 0) { result.setLength(result.length() - 2); } result.append(")"); return result.toString(); } }
google/easy-gwt-mock
java/com/google/gwt/testing/easygwtmock/client/internal/Method.java
Java
apache-2.0
3,055
/* * Copyright 2015 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.amqp.tutorials.tut6; import org.springframework.amqp.rabbit.annotation.RabbitListener; /** * @author Gary Russell * @author Scott Deeg */ public class Tut6Server { @RabbitListener(queues = "tut.rpc.requests") // @SendTo("tut.rpc.replies") used when the client doesn't set replyTo. public int fibonacci(int n) { System.out.println(" [x] Received request for " + n); int result = fib(n); System.out.println(" [.] Returned " + result); return result; } public int fib(int n) { return n == 0 ? 0 : n == 1 ? 1 : (fib(n - 1) + fib(n - 2)); } }
rabbitmq/rabbitmq-tutorials
spring-amqp/src/main/java/org/springframework/amqp/tutorials/tut6/Tut6Server.java
Java
apache-2.0
1,207
package com.bupt.paragon.wechatchoosen.fragment; import android.app.Fragment; /** * Created by Paragon on 2016/5/29. */ public interface SetCurrentListener { void setCurrentFragment(Fragment fragment); }
newbeginningxzm/WeChatChoosen
app/src/main/java/com/bupt/paragon/wechatchoosen/fragment/SetCurrentListener.java
Java
apache-2.0
212
/* * Copyright 2014-2015 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.net.intent; import com.google.common.base.MoreObjects; import org.onosproject.core.ApplicationId; import org.onosproject.net.ConnectPoint; import org.onosproject.net.OduSignalType; import java.util.Collections; import static com.google.common.base.Preconditions.checkNotNull; /** * An optical layer intent for connectivity between two OCh ports. * No traffic selector or traffic treatment are needed. */ public final class OpticalConnectivityIntent extends Intent { private final ConnectPoint src; private final ConnectPoint dst; private final OduSignalType signalType; private final boolean isBidirectional; /** * Creates an optical connectivity intent between the specified * connection points. * * @param appId application identification * @param key intent key * @param src the source transponder port * @param dst the destination transponder port * @param signalType signal type * @param isBidirectional indicates if intent is unidirectional * @param priority priority to use for flows from this intent */ protected OpticalConnectivityIntent(ApplicationId appId, Key key, ConnectPoint src, ConnectPoint dst, OduSignalType signalType, boolean isBidirectional, int priority) { super(appId, key, Collections.emptyList(), priority); this.src = checkNotNull(src); this.dst = checkNotNull(dst); this.signalType = checkNotNull(signalType); this.isBidirectional = isBidirectional; } /** * Returns a new optical connectivity intent builder. * * @return host to host intent builder */ public static Builder builder() { return new Builder(); } /** * Builder for optical connectivity intents. */ public static class Builder extends Intent.Builder { private ConnectPoint src; private ConnectPoint dst; private OduSignalType signalType; private boolean isBidirectional; @Override public Builder appId(ApplicationId appId) { return (Builder) super.appId(appId); } @Override public Builder key(Key key) { return (Builder) super.key(key); } @Override public Builder priority(int priority) { return (Builder) super.priority(priority); } /** * Sets the source for the intent that will be built. * * @param src source to use for built intent * @return this builder */ public Builder src(ConnectPoint src) { this.src = src; return this; } /** * Sets the destination for the intent that will be built. * * @param dst dest to use for built intent * @return this builder */ public Builder dst(ConnectPoint dst) { this.dst = dst; return this; } /** * Sets the ODU signal type for the intent that will be built. * * @param signalType ODU signal type * @return this builder */ public Builder signalType(OduSignalType signalType) { this.signalType = signalType; return this; } /** * Sets the directionality of the intent. * * @param isBidirectional true if bidirectional, false if unidirectional * @return this builder */ public Builder bidirectional(boolean isBidirectional) { this.isBidirectional = isBidirectional; return this; } /** * Builds an optical connectivity intent from the accumulated parameters. * * @return point to point intent */ public OpticalConnectivityIntent build() { return new OpticalConnectivityIntent( appId, key, src, dst, signalType, isBidirectional, priority ); } } /** * Constructor for serializer. */ protected OpticalConnectivityIntent() { super(); this.src = null; this.dst = null; this.signalType = null; this.isBidirectional = false; } /** * Returns the source transponder port. * * @return source transponder port */ public ConnectPoint getSrc() { return src; } /** * Returns the destination transponder port. * * @return source transponder port */ public ConnectPoint getDst() { return dst; } /** * Returns the ODU signal type. * * @return ODU signal type */ public OduSignalType getSignalType() { return signalType; } /** * Returns the directionality of the intent. * * @return true if bidirectional, false if unidirectional */ public boolean isBidirectional() { return isBidirectional; } @Override public String toString() { return MoreObjects.toStringHelper(this) .add("id", id()) .add("key", key()) .add("appId", appId()) .add("priority", priority()) .add("resources", resources()) .add("src", src) .add("dst", dst) .add("signalType", signalType) .add("isBidirectional", isBidirectional) .toString(); } }
maxkondr/onos-porta
core/api/src/main/java/org/onosproject/net/intent/OpticalConnectivityIntent.java
Java
apache-2.0
6,451
package gov.va.med.imaging.core.router.commands.dicom.importer; import gov.va.med.imaging.core.interfaces.exceptions.ConnectionException; import gov.va.med.imaging.core.interfaces.exceptions.MethodException; import gov.va.med.imaging.core.interfaces.exceptions.SecurityCredentialsExpiredException; import gov.va.med.imaging.datasource.DicomImporterDataSourceSpi; import gov.va.med.imaging.exchange.business.dicom.importer.Order; import gov.va.med.imaging.exchange.business.dicom.importer.OrderingLocation; import gov.va.med.imaging.exchange.business.dicom.importer.OrderingProvider; import gov.va.med.imaging.exchange.business.dicom.importer.Procedure; import java.util.List; public class GetOrderingProviderListCommandImpl extends AbstractDicomImporterDataSourceCommandImpl<List<OrderingProvider>> { private final String siteId; private final String searchString; private static final long serialVersionUID = 1L; private static final String SPI_METHOD_NAME = "getOrderingProviderList"; public GetOrderingProviderListCommandImpl(String siteId, String searchString) { this.siteId = siteId; this.searchString = searchString; } @Override protected Class<?>[] getSpiMethodParameterTypes() { return new Class<?>[]{String.class, String.class}; } @Override protected Object[] getSpiMethodParameters() { return new Object[]{getSiteId(), getSearchString()} ; } @Override protected String parameterToString() { // TODO Auto-generated method stub return null; } /* (non-Javadoc) * @see gov.va.med.imaging.core.router.AbstractDataSourceCommandImpl#getCommandResult(gov.va.med.imaging.datasource.VersionableDataSourceSpi) */ @Override protected List<OrderingProvider> getCommandResult( DicomImporterDataSourceSpi spi) throws ConnectionException, MethodException, SecurityCredentialsExpiredException { return spi.getOrderingProviderList(getSiteId(), getSearchString()); } /* (non-Javadoc) * @see gov.va.med.imaging.core.router.AbstractDataSourceCommandImpl#getSpiMethodName() */ @Override protected String getSpiMethodName() { return SPI_METHOD_NAME; } public String getSiteId() { return siteId; } public String getSearchString() { return searchString; } }
VHAINNOVATIONS/Telepathology
Source/Java/CoreRouter/main/src/java/gov/va/med/imaging/core/router/commands/dicom/importer/GetOrderingProviderListCommandImpl.java
Java
apache-2.0
2,224
package net.minidev.json.test; import junit.framework.TestCase; import net.minidev.json.JSONObject; import net.minidev.json.JSONStyle; import net.minidev.json.JSONValue; /** * Test all Compression Styles * * @author Uriel Chemouni <uchemouni@gmail.com> * */ public class TestCompressorFlags extends TestCase { public void testProtect() throws Exception { String compressed = "{k:value}"; String nCompress = "{\"k\":\"value\"}"; JSONObject obj = (JSONObject) JSONValue.parse(nCompress); // test MAX_COMPRESS String r = obj.toJSONString(JSONStyle.MAX_COMPRESS); assertEquals(compressed, r); // test LT_COMPRESS r = obj.toJSONString(JSONStyle.LT_COMPRESS); assertEquals(nCompress, r); // test NO_COMPRESS r = obj.toJSONString(JSONStyle.NO_COMPRESS); assertEquals(nCompress, r); // only keys values JSONStyle style = new JSONStyle(-1 & JSONStyle.FLAG_PROTECT_KEYS); r = obj.toJSONString(style); assertEquals("{k:\"value\"}", r); // only protect values style = new JSONStyle(-1 & JSONStyle.FLAG_PROTECT_VALUES); r = obj.toJSONString(style); assertEquals("{\"k\":value}", r); } public void testAggresive() throws Exception { String r; JSONStyle style; String NProtectValue = "{\"a b\":\"c d\"}"; JSONObject obj = (JSONObject) JSONValue.parse(NProtectValue); /** * Test Without Agressive */ style = new JSONStyle(-1 & JSONStyle.FLAG_PROTECT_KEYS); r = obj.toJSONString(style); assertEquals(NProtectValue, r); style = new JSONStyle(-1 & JSONStyle.FLAG_PROTECT_VALUES); r = obj.toJSONString(style); assertEquals(NProtectValue, r); /** * Test With Agressive */ style = new JSONStyle(-1 & (JSONStyle.FLAG_PROTECT_VALUES | JSONStyle.FLAG_AGRESSIVE)); r = obj.toJSONString(style); assertEquals("{\"a b\":c d}", r); style = new JSONStyle(-1 & (JSONStyle.FLAG_PROTECT_KEYS | JSONStyle.FLAG_AGRESSIVE)); r = obj.toJSONString(style); assertEquals("{a b:\"c d\"}", r); style = JSONStyle.MAX_COMPRESS; r = obj.toJSONString(style); assertEquals("{a b:c d}", r); } public void test4Web() throws Exception { String NProtectValue = "{\"k\":\"http:\\/\\/url\"}"; JSONObject obj = (JSONObject) JSONValue.parse(NProtectValue); String r = obj.toJSONString(JSONStyle.MAX_COMPRESS); assertEquals("{k:\"http://url\"}", r); r = obj.toJSONString(JSONStyle.LT_COMPRESS); assertEquals("{\"k\":\"http://url\"}", r); r = obj.toJSONString(JSONStyle.NO_COMPRESS); assertEquals("{\"k\":\"http:\\/\\/url\"}", r); } }
netplex/json-smart-v1
json-smart/src/test/java/net/minidev/json/test/TestCompressorFlags.java
Java
apache-2.0
2,527
/** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with this * work for additional information regarding copyright ownership. The ASF * licenses this file to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package org.apache.hadoop.ozone.container.common.helpers; import com.google.common.collect.Maps; import org.apache.hadoop.hdds.protocol.proto .StorageContainerDatanodeProtocolProtos.DeletedBlocksTransaction; import java.util.List; import java.util.Map; import java.util.stream.Collectors; /** * A helper class to wrap the info about under deletion container blocks. */ public final class DeletedContainerBlocksSummary { private final List<DeletedBlocksTransaction> blocks; // key : txID // value : times of this tx has been processed private final Map<Long, Integer> txSummary; // key : container name // value : the number of blocks need to be deleted in this container // if the message contains multiple entries for same block, // blocks will be merged private final Map<String, Integer> blockSummary; // total number of blocks in this message private int numOfBlocks; private DeletedContainerBlocksSummary(List<DeletedBlocksTransaction> blocks) { this.blocks = blocks; txSummary = Maps.newHashMap(); blockSummary = Maps.newHashMap(); blocks.forEach(entry -> { txSummary.put(entry.getTxID(), entry.getCount()); if (blockSummary.containsKey(entry.getContainerName())) { blockSummary.put(entry.getContainerName(), blockSummary.get(entry.getContainerName()) + entry.getBlockIDCount()); } else { blockSummary.put(entry.getContainerName(), entry.getBlockIDCount()); } numOfBlocks += entry.getBlockIDCount(); }); } public static DeletedContainerBlocksSummary getFrom( List<DeletedBlocksTransaction> blocks) { return new DeletedContainerBlocksSummary(blocks); } public int getNumOfBlocks() { return numOfBlocks; } public int getNumOfContainers() { return blockSummary.size(); } public String getTXIDs() { return String.join(",", txSummary.keySet() .stream().map(String::valueOf).collect(Collectors.toList())); } public String getTxIDSummary() { List<String> txSummaryEntry = txSummary.entrySet().stream() .map(entry -> entry.getKey() + "(" + entry.getValue() + ")") .collect(Collectors.toList()); return "[" + String.join(",", txSummaryEntry) + "]"; } @Override public String toString() { StringBuffer sb = new StringBuffer(); for (DeletedBlocksTransaction blks : blocks) { sb.append(" ") .append("TXID=") .append(blks.getTxID()) .append(", ") .append("TimesProceed=") .append(blks.getCount()) .append(", ") .append(blks.getContainerName()) .append(" : [") .append(String.join(",", blks.getBlockIDList())).append("]") .append("\n"); } return sb.toString(); } }
ChetnaChaudhari/hadoop
hadoop-hdds/container-service/src/main/java/org/apache/hadoop/ozone/container/common/helpers/DeletedContainerBlocksSummary.java
Java
apache-2.0
3,593
/* * Copyright 2014 SeaClouds * Contact: SeaClouds * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package eu.seaclouds.platform.dashboard.rest; import eu.atos.sla.parser.data.GuaranteeTermsStatus; import eu.atos.sla.parser.data.Penalty; import eu.atos.sla.parser.data.Violation; import eu.atos.sla.parser.data.wsag.Agreement; import eu.atos.sla.parser.data.wsag.GuaranteeTerm; import eu.seaclouds.platform.dashboard.model.SeaCloudsApplicationData; import eu.seaclouds.platform.dashboard.model.SeaCloudsApplicationDataStorage; import org.testng.annotations.BeforeMethod; import org.testng.annotations.Test; import java.util.List; import static org.testng.Assert.assertNotNull; public class SlaResourceTest extends AbstractResourceTest<SlaResource>{ SlaResource resource = new SlaResource(getSlaProxy()); SeaCloudsApplicationData applicationData; @Override @BeforeMethod public void setUpMethod() throws Exception { super.setUpMethod(); applicationData = new SeaCloudsApplicationData(getDam()); applicationData.setAgreementId(getAgreement()); SeaCloudsApplicationDataStorage.getInstance().addSeaCloudsApplicationData(applicationData); } @Test public void testGetAgreement() throws Exception { Agreement agreement = (Agreement) resource.getAgreement(applicationData.getSeaCloudsApplicationId()).getEntity(); assertNotNull(agreement); } @Test public void testGetAgreementStatus() throws Exception { GuaranteeTermsStatus entity = (GuaranteeTermsStatus) resource.getAgreementStatus(applicationData.getSeaCloudsApplicationId()).getEntity(); assertNotNull(entity); } @Test public void testGetViolations() throws Exception { Agreement agreement = (Agreement) resource.getAgreement(applicationData.getSeaCloudsApplicationId()).getEntity(); for(GuaranteeTerm term : agreement.getTerms().getAllTerms().getGuaranteeTerms()){ List<Violation> entity = (List<Violation>) resource.getViolations(applicationData.getSeaCloudsApplicationId(), term.getName()).getEntity(); assertNotNull(entity); } } @Test public void testGetPenalties() throws Exception { Agreement agreement = (Agreement) resource.getAgreement(applicationData.getSeaCloudsApplicationId()) .getEntity(); for(GuaranteeTerm term : agreement.getTerms().getAllTerms().getGuaranteeTerms()){ List<Penalty> entity = (List<Penalty>) resource.getPenalties(applicationData.getSeaCloudsApplicationId(), term.getName()) .getEntity(); assertNotNull(entity); for (Penalty p : entity) { assertNotNull(p); } } } }
SeaCloudsEU/SeaCloudsPlatform
dashboard/src/test/java/eu/seaclouds/platform/dashboard/rest/SlaResourceTest.java
Java
apache-2.0
3,353
package tianma.swing.example.events; import java.awt.Container; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.ItemEvent; import java.awt.event.ItemListener; import javax.swing.GroupLayout; import javax.swing.JButton; import javax.swing.JCheckBox; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.SwingUtilities; /** * It is possible to remove the registered listener with the * removeActionListener() method * */ @SuppressWarnings("serial") public class RemoveListenerSample extends JFrame { private JLabel label; private JButton addButton; private JCheckBox activeBox; private ButtonClickListener listener; private int count = 0; public RemoveListenerSample() { initUI(); } private void initUI() { Container pane = getContentPane(); GroupLayout groupLayout = new GroupLayout(pane); pane.setLayout(groupLayout); addButton = new JButton("+"); listener = new ButtonClickListener(); activeBox = new JCheckBox("Active listener"); activeBox.addItemListener(new ItemListener() { @Override public void itemStateChanged(ItemEvent e) { if (activeBox.isSelected()) { addButton.addActionListener(listener); } else { addButton.removeActionListener(listener); } } }); label = new JLabel("0"); groupLayout.setAutoCreateContainerGaps(true); groupLayout.setHorizontalGroup(groupLayout .createSequentialGroup() .addGroup( groupLayout.createParallelGroup() .addComponent(addButton).addComponent(label)) .addGap(30).addComponent(activeBox)); groupLayout.setVerticalGroup(groupLayout .createSequentialGroup() .addGroup( groupLayout.createParallelGroup() .addComponent(addButton) .addComponent(activeBox)).addGap(30) .addComponent(label)); pack(); setTitle("Remove Listener Sample"); setDefaultCloseOperation(EXIT_ON_CLOSE); setLocationRelativeTo(null); } private class ButtonClickListener implements ActionListener { @Override public void actionPerformed(ActionEvent e) { label.setText("" + (++count)); } } public static void main(String[] args) { SwingUtilities.invokeLater(new Runnable() { @Override public void run() { RemoveListenerSample sample = new RemoveListenerSample(); sample.setVisible(true); } }); } }
tianma8023/SwingExample
src/tianma/swing/example/events/RemoveListenerSample.java
Java
apache-2.0
2,463
package ru.agolovin; import java.util.Random; /** * @author agolovin (agolovin@list.ru) * @version $Id$ * @since 0.1 */ public class Bomberman { /** * Game marker. */ private static volatile boolean stop; /** * Game board. */ private final Cell[][] board; /** * Game board size [size][size]. */ private final int size; /** * Number of warriors. */ private final int bots; /** * Number of blocks on board. */ private final int blocks; /** * Warriors array. */ private Figure[] warriors; /** * For Random number. */ private Random random; /** * Player thread. */ private Thread player; /** * Constructor. * * @param size int * @param bots int * @param blocks int */ private Bomberman(int size, int bots, int blocks) { this.size = size; this.board = new Cell[size][size]; this.bots = bots; this.blocks = blocks; stop = false; this.random = new Random(); } /** * Get game marker. * * @return boolean result. */ public synchronized static boolean isStop() { return stop; } /** * Change game marker. * * @param stop boolean */ public static void setStop(boolean stop) { Bomberman.stop = stop; } /** * Main method. * * @param args String[] */ public static void main(String[] args) { new Bomberman(3, 3, 1).init(); } /** * Initialization. */ private void init() { prepareBoard(); setUpBlockCell(); setUpWarriors(); createThreads(); try { player.join(); System.out.println("Game over"); } catch (InterruptedException e) { e.printStackTrace(); } } /** * Prepare board. */ private void prepareBoard() { for (int i = 0; i < this.size; i++) { for (int j = 0; j < this.size; j++) { this.board[i][j] = new Cell(i, j); } } } /** * Set blocks on board. */ private void setUpBlockCell() { int count = this.blocks; while (count != 0) { int x = getRandomNumber(); int y = getRandomNumber(); if (this.board[x][y].getIsStop()) { this.board[x][y].setIsStop(true); System.out.println( String.format( "Block setUp in %s, %s", this.board[x][y].getXCell(), this.board[x][y].getYCell())); count--; } } } /** * Initialize warriors. */ private void setUpWarriors() { this.warriors = new Warrior[this.bots]; Warrior warrior; int count = 0; while (count != this.bots) { int x = getRandomNumber(); int y = getRandomNumber(); if (this.board[x][y].getIsStop() && this.board[x][y].getFigure() == null) { warrior = new Warrior(String.valueOf(count), this.board, this.board[x][y]); this.warriors[count] = warrior; count++; } } } /** * Prepare player figure. * * @return Player player. */ private Player createBomberman() { Player player = null; boolean result = false; while (!result) { int x = getRandomNumber(); int y = getRandomNumber(); if (this.board[x][y].getIsStop() && this.board[x][y].getFigure() == null) { player = new Player("0", this.board, this.board[x][y]); System.out.println( String.format("Bomberman %s start game in %d %d", player.type(), this.board[x][y].getXCell(), this.board[x][y].getYCell()) ); result = true; } } return player; } /** * get random number in allowed range. * * @return int result */ private int getRandomNumber() { return random.nextInt(this.size); } /** * Create threads. */ private void createThreads() { this.player = new Thread(this.createBomberman()); this.player.start(); for (Figure warrior : this.warriors) { new Thread(warrior).start(); } } }
MorpG/Java-course
package_2/multithreading/bomberman/src/main/java/ru/agolovin/Bomberman.java
Java
apache-2.0
4,565
/* * 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.rapidpm.proxybuilder.objectadapter.annotations.dynamicobjectadapter; import java.lang.reflect.InvocationHandler; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.util.HashMap; import java.util.Map; public abstract class ExtendedInvocationHandler<T> implements InvocationHandler { private final Map<MethodIdentifier, Method> adaptedMethods = new HashMap<>(); private final Map<MethodIdentifier, Object> adapters = new HashMap<>(); private T original; public void setOriginal(T original) { this.original = original; } public void addAdapter(Object adapter) { final Class<?> adapterClass = adapter.getClass(); Method[] methods = adapterClass.getDeclaredMethods(); for (Method m : methods) { final MethodIdentifier key = new MethodIdentifier(m); adaptedMethods.put(key, m); adapters.put(key, adapter); } } @Override public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { try { final MethodIdentifier key = new MethodIdentifier(method); Method other = adaptedMethods.get(key); if (other != null) { other.setAccessible(true); //Lambdas... final Object result = other.invoke(adapters.get(key), args); other.setAccessible(false); return result; } else { return method.invoke(original, args); } } catch (InvocationTargetException e) { throw e.getTargetException(); } } }
tfeiner/proxybuilder
modules/objectadapter/generator/annotations/src/main/java/org/rapidpm/proxybuilder/objectadapter/annotations/dynamicobjectadapter/ExtendedInvocationHandler.java
Java
apache-2.0
2,312
package io.crowdcode.flaschenhals.stock.resource; import lombok.AllArgsConstructor; import lombok.EqualsAndHashCode; import lombok.Getter; import lombok.NoArgsConstructor; import lombok.Setter; import lombok.ToString; import lombok.experimental.Accessors; @Getter @Setter @ToString @EqualsAndHashCode @Accessors(chain = true) @AllArgsConstructor @NoArgsConstructor public class StockEntryRequest { private Long productId; private Long quantity; }
crowdcode-de/spring-cloud-performance-tuning
domain-services/stock-api/src/main/java/io/crowdcode/flaschenhals/stock/resource/StockEntryRequest.java
Java
apache-2.0
460
/* * * * Copyright 2010-2016 OrientDB LTD (http://orientdb.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. * * * * For more information: http://orientdb.com * */ package com.orientechnologies.orient.core.command; public interface OCommandRequestAsynch { public OCommandResultListener getResultListener(); public void setResultListener(OCommandResultListener iListener); public boolean isAsynchronous(); }
orientechnologies/orientdb
core/src/main/java/com/orientechnologies/orient/core/command/OCommandRequestAsynch.java
Java
apache-2.0
985
/** * Copyright &copy; 2012-2014 <a href="https://github.com/thinkgem/jeesite">JeeSite</a> All rights reserved. */ package com.tp.ems.modules.waterexpertdb.service; import com.github.abel533.echarts.json.GsonOption; import com.tp.ems.common.persistence.Page; import com.tp.ems.common.service.CrudService; import com.tp.ems.modules.waterexpertdb.dao.ContrastDataDao; import com.tp.ems.modules.waterexpertdb.entity.ContrastData; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.*; /** * 专家数据库(对比分析)Service * @author 张丽 * @version 2016-11-07 */ @Service @Transactional(readOnly = true) public class ContrastDataService extends CrudService<ContrastDataDao, ContrastData> { @Autowired private ContrastDataDao contrastDataAmountDao; @Autowired private WaterCompareUtils utils; public ContrastData get(String id) { return super.get(id); } public List<ContrastData> findList(ContrastData contrastDataAmount) { return super.findList(contrastDataAmount); } public Page<ContrastData> findPage(Page<ContrastData> page, ContrastData contrastDataAmount) { return super.findPage(page, contrastDataAmount); } @Transactional(readOnly = false) public void save(ContrastData contrastDataAmount) { super.save(contrastDataAmount); } @Transactional(readOnly = false) public void delete(ContrastData contrastDataAmount) { super.delete(contrastDataAmount); } //不同监测点同一时间段 对比分析 /** * type:1 负荷 折线图 2 电量 柱状图 * @param dataAmountList * @param type * @return */ public GsonOption diffDeviceAnalysis(List<ContrastData> dataAmountList,String type){ GsonOption option = new GsonOption(); Map<String,List<ContrastData>> map = new HashMap(); for(int i =0;i<dataAmountList.size();i++){ List<ContrastData> contrastDataAmounts = contrastDataAmountDao.getIntervalData(dataAmountList.get(i)); map.put(String.valueOf(i),contrastDataAmounts); } int flag = 0; for(int j=0;j<map.size();j++){ if(map.get(String.valueOf(j)).size()==0){ flag++; } } if(flag>1){ return null; } option = utils.barChart(map,type); return option; } //同一监测点同比 如:13年3月和14年4月 // 环比 :相邻时间段 如13年3月和13年2月 /** * type:1 负荷 折线图 2 电量 柱状图 * compareType 1:同比 2 : 环比 * @param dataAmount * @return * @throws java.text.ParseException */ public GsonOption sameDeviceDiffTime(ContrastData dataAmount) throws ParseException { GsonOption option = new GsonOption(); Map map = new HashMap(); String compareType = dataAmount.getCompareType(); //选中时间下 List<ContrastData> contrastDataAmounts = contrastDataAmountDao.getIntervalData(dataAmount); map.put("0",contrastDataAmounts); Date startTime = dataAmount.getStartTime(); Date endTime = dataAmount.getEndTime(); // 同比 、环比 Date startTime_basis = convertDateBasis(startTime,compareType); Date endTime_basis = convertDateBasis(endTime,compareType); dataAmount.setStartTime(startTime_basis); dataAmount.setEndTime(endTime_basis); List<ContrastData> contrastDataAmounts_basis = contrastDataAmountDao.getIntervalData(dataAmount); map.put("1",contrastDataAmounts_basis); if(contrastDataAmounts.size()<=0 && contrastDataAmounts_basis.size()<=0){ return null; } option = utils.barChart(map,dataAmount.getType()); return option; } /** * 转化同比/环比时间 type:1 同比 type : 2 环比 * @param date * @param compareType * @return */ public Date convertDateBasis(Date date,String compareType){ Calendar cal = Calendar.getInstance(); cal.setTime(date); if(compareType.equals("1")){ cal.add(Calendar.YEAR, -1); }else if(compareType.equals("2")){ cal.add(Calendar.MONTH,-1); } SimpleDateFormat sdf = new SimpleDateFormat( "yyyy-MM-dd"); String date_convert =sdf.format(cal.getTime()); try { Date indate = sdf.parse(date_convert); return indate; } catch (ParseException e) { e.printStackTrace(); } return null; } /** * type:1 1 JLJLL 净累计流量 2 SSLL 瞬时流量 * @param dataAmount * @param type * @return */ public GsonOption sameDeviceTwoTimeInterval(ContrastData dataAmount,String type){ GsonOption option = new GsonOption(); List<ContrastData> contrastDataAmounts = new ArrayList<>(); contrastDataAmounts = contrastDataAmountDao.getIntervalData(dataAmount); if(contrastDataAmounts.size()<=0){ return null; } option = utils.barOneDeviceTwoInterval(contrastDataAmounts, type); return option; } }
347184068/gmenergy
src/main/java/com/tp/ems/modules/waterexpertdb/service/ContrastDataService.java
Java
apache-2.0
4,820
package org.baade.eel.tools.conf; import javax.xml.bind.annotation.XmlType; /** * 消息的配置 * @author <a href="http://eel.baade.org">Baade Eel Project</a> * 2017/4/1. */ @XmlType(propOrder = { "protocFilePath", "protosFileDir", "msgFileJavaOutPath" }) public class MessageConfig { private String protocFilePath; private String protosFileDir; private String msgFileJavaOutPath; public String getProtocFilePath() { return protocFilePath; } public void setProtocFilePath(String protocFilePath) { this.protocFilePath = protocFilePath; } public String getProtosFileDir() { return protosFileDir; } public void setProtosFileDir(String protosFileDir) { this.protosFileDir = protosFileDir; } public String getMsgFileJavaOutPath() { return msgFileJavaOutPath; } public void setMsgFileJavaOutPath(String msgFileJavaOutPath) { this.msgFileJavaOutPath = msgFileJavaOutPath; } }
baade-org/eel
eel-tools/src/main/java/org/baade/eel/tools/conf/MessageConfig.java
Java
apache-2.0
1,029