blob_id stringlengths 40 40 | directory_id stringlengths 40 40 | path stringlengths 7 410 | content_id stringlengths 40 40 | detected_licenses listlengths 0 51 | license_type stringclasses 2 values | repo_name stringlengths 5 132 | snapshot_id stringlengths 40 40 | revision_id stringlengths 40 40 | branch_name stringlengths 4 80 | visit_date timestamp[us] | revision_date timestamp[us] | committer_date timestamp[us] | github_id int64 5.85k 684M ⌀ | star_events_count int64 0 209k | fork_events_count int64 0 110k | gha_license_id stringclasses 22 values | gha_event_created_at timestamp[us] | gha_created_at timestamp[us] | gha_language stringclasses 132 values | src_encoding stringclasses 34 values | language stringclasses 1 value | is_vendor bool 1 class | is_generated bool 2 classes | length_bytes int64 3 9.45M | extension stringclasses 28 values | content stringlengths 3 9.45M | authors listlengths 1 1 | author_id stringlengths 0 352 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
b7ae83664e6c22c6c5ff389ad60843e9d8feb076 | 42fcf1d879cb75f08225137de5095adfdd63fa21 | /src/main/java/org/jooq/routines/GetEqualSetSkuidNrforFsc.java | 59dcc89f441b19b1b9879b017d73428e47dc21f8 | [] | no_license | mpsgit/JOOQTest | e10e9c8716f2688c8bf0160407b1244f9e70e8eb | 6af2922bddc55f591e94a5a9a6efd1627747d6ad | refs/heads/master | 2021-01-10T06:11:40.862153 | 2016-02-28T09:09:34 | 2016-02-28T09:09:34 | 52,711,455 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 2,259 | java | /**
* This class is generated by jOOQ
*/
package org.jooq.routines;
import java.math.BigDecimal;
import javax.annotation.Generated;
import org.jooq.Field;
import org.jooq.Parameter;
import org.jooq.Wetrn;
import org.jooq.impl.AbstractRoutine;
/**
* This class is generated by jOOQ.
*/
@Generated(
value = {
"http://www.jooq.org",
"jOOQ version:3.7.2"
},
comments = "This class is generated by jOOQ"
)
@SuppressWarnings({ "all", "unchecked", "rawtypes" })
public class GetEqualSetSkuidNrforFsc extends AbstractRoutine<BigDecimal> {
private static final long serialVersionUID = -816648109;
/**
* The parameter <code>WETRN.GET_EQUAL_SET_SKUID_NRFOR_FSC.RETURN_VALUE</code>.
*/
public static final Parameter<BigDecimal> RETURN_VALUE = createParameter("RETURN_VALUE", org.jooq.impl.SQLDataType.NUMERIC, false);
/**
* The parameter <code>WETRN.GET_EQUAL_SET_SKUID_NRFOR_FSC.T_SET_ID</code>.
*/
public static final Parameter<BigDecimal> T_SET_ID = createParameter("T_SET_ID", org.jooq.impl.SQLDataType.NUMERIC, false);
/**
* The parameter <code>WETRN.GET_EQUAL_SET_SKUID_NRFOR_FSC.S_SET_ID</code>.
*/
public static final Parameter<BigDecimal> S_SET_ID = createParameter("S_SET_ID", org.jooq.impl.SQLDataType.NUMERIC, false);
/**
* Create a new routine call instance
*/
public GetEqualSetSkuidNrforFsc() {
super("GET_EQUAL_SET_SKUID_NRFOR_FSC", Wetrn.WETRN, org.jooq.impl.SQLDataType.NUMERIC);
setReturnParameter(RETURN_VALUE);
addInParameter(T_SET_ID);
addInParameter(S_SET_ID);
}
/**
* Set the <code>T_SET_ID</code> parameter IN value to the routine
*/
public void setTSetId(Number value) {
setNumber(T_SET_ID, value);
}
/**
* Set the <code>T_SET_ID</code> parameter to the function to be used with a {@link org.jooq.Select} statement
*/
public void setTSetId(Field<? extends Number> field) {
setNumber(T_SET_ID, field);
}
/**
* Set the <code>S_SET_ID</code> parameter IN value to the routine
*/
public void setSSetId(Number value) {
setNumber(S_SET_ID, value);
}
/**
* Set the <code>S_SET_ID</code> parameter to the function to be used with a {@link org.jooq.Select} statement
*/
public void setSSetId(Field<? extends Number> field) {
setNumber(S_SET_ID, field);
}
}
| [
"krisztian.koller@gmail.com"
] | krisztian.koller@gmail.com |
b1f8a3672647c04228e20b93f4c7bab4c2819ce6 | 71db976ba832ca057166eb1738e467a1bc3df3e6 | /conicplot/src/main/java/org/newtonmaps/conicplot/ConicMatrix.java | f1858609f70d48d98a2db1f7863139abacf561c5 | [] | no_license | hronir/newtonmaps | dcde437e22aa21f603d5f57ae1e4616e1097dadb | b8e5f5ed3d51fed6bb16a74a15637480b6f49494 | refs/heads/master | 2016-09-10T18:04:21.813874 | 2014-05-09T16:41:38 | 2014-05-09T16:41:38 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 2,842 | java | package org.newtonmaps.conicplot;
public class ConicMatrix {
public static final int DIMENSION = 3;
private double[][] coefficients;
public ConicMatrix() {
this.coefficients = new double[DIMENSION][];
for (int i = 0; i < DIMENSION; i++) {
this.coefficients[i] = new double[i + 1];
}
}
public ConicMatrix setValues(double... values) {
int k = 0;
for (int i = 0; i < DIMENSION; i++) {
for (int j = 0; j <= i; j++) {
this.coefficients[i][j] = values[k];
k++;
}
}
return this;
}
public ConicMatrix copyTo(ConicMatrix result) {
for (int i = 0; i < DIMENSION; i++) {
for (int j = 0; j <= i; j++) {
result.coefficients[i][j] = this.coefficients[i][j];
}
}
return result;
}
public double evaluate(double... p) {
double v = 0;
for (int i = 0; i < DIMENSION; i++) {
v += this.coefficients[i][i] * p[i] * p[i];
for (int j = 0; j < i; j++) {
v += 2D * this.coefficients[i][j] * p[i] * p[j];
}
}
return v;
}
public double evaluateGradient(int i, double... p) {
double v = 0;
for (int j = 0; j < DIMENSION; j++) {
v += 2D * getCoefficient(i, j) * p[j];
}
return v;
}
public double getCoefficient(int i, int j) {
return i < j ? this.coefficients[j][i] : this.coefficients[i][j];
}
public ConicMatrix slopeConic(int a, int b, ConicMatrix result) {
for (int i = 0; i < DIMENSION; i++) {
for (int j = 0; j <= i; j++) {
result.coefficients[i][j] = -getCoefficient(i, a)
* getCoefficient(j, a) + getCoefficient(i, b)
* getCoefficient(j, b);
}
}
return result;
}
// public int evaluateSlopeSign(int a, double... p) {
// double d = 0;
// for (int k = 0; k < DIMENSION; k++) {
// d += getCoefficient(a, k) * p[k];
// }
// return d < 0D ? -1 : d > 0D ? 1 : 0;
// }
public ConicMatrix swapVariable(int a, int b, ConicMatrix result) {
for (int i = 0; i < DIMENSION; i++) {
int i1 = swap(a, b, i);
for (int j = 0; j <= i; j++) {
int j1 = swap(a, b, j);
result.coefficients[i][j] = getCoefficient(i1, j1);
}
}
return result;
}
public ConicMatrix variableSymetry(int a, ConicMatrix result) {
for (int i = 0; i < DIMENSION; i++) {
for (int j = 0; j <= i; j++) {
result.coefficients[i][j] = this.coefficients[i][j];
}
}
for (int i = 0; i < a; i++) {
result.coefficients[a][i] = -result.coefficients[a][i];
}
for (int i = a + 1; i < DIMENSION; i++) {
result.coefficients[i][a] = -result.coefficients[i][a];
}
return result;
}
private static int swap(int a, int b, int i) {
return i == a ? b : i == b ? a : i;
}
public int evaluateSlopeSign(double... p) {
double x = 0;
double y = 0;
for (int i = 0; i < DIMENSION; i++) {
x += getCoefficient(0, i) * p[i];
y += getCoefficient(1, i) * p[i];
}
double k = x * y;
return k > 0 ? 1 : k < 0 ? -1 : 0;
}
}
| [
"oriol.tls@hotmail.fr"
] | oriol.tls@hotmail.fr |
0780c9ccc6b656923b5f9044d0724dc3b81525a7 | fa91450deb625cda070e82d5c31770be5ca1dec6 | /Diff-Raw-Data/20/20_8dc860b920dd9f98fee5901adb878be298e121dd/ChangeVmConfiguration/20_8dc860b920dd9f98fee5901adb878be298e121dd_ChangeVmConfiguration_s.java | e313876ddcc7a1729c3d0211f7dc33a43c8a80f0 | [] | no_license | zhongxingyu/Seer | 48e7e5197624d7afa94d23f849f8ea2075bcaec0 | c11a3109fdfca9be337e509ecb2c085b60076213 | refs/heads/master | 2023-07-06T12:48:55.516692 | 2023-06-22T07:55:56 | 2023-06-22T07:55:56 | 259,613,157 | 6 | 2 | null | 2023-06-22T07:55:57 | 2020-04-28T11:07:49 | null | UTF-8 | Java | false | false | 6,903 | java | package at.ac.tuwien.lsdc.actions;
import java.util.List;
import at.ac.tuwien.lsdc.Configuration;
import at.ac.tuwien.lsdc.resources.Resource;
import at.ac.tuwien.lsdc.resources.VirtualMachine;
public class ChangeVmConfiguration extends Action {
private VirtualMachine vm;
private int optimizedCpuAllocation;
private int optimizedMemoryAllocation;
private int optimizedStorageAllocation;
private static int configurationChangeCosts;
private static int topRegion;
private static int bottomRegion;
// tick count to look in the past
private final int tickCount = 10;
@Override
public void init(Resource problem) {
if (problem instanceof VirtualMachine) {
this.vm = (VirtualMachine) problem;
}
// set init values
ChangeVmConfiguration.setConfigurationChangeCosts(Configuration.getInstance().getVmConfigurationChangeCosts());
ChangeVmConfiguration.setTopRegion(Configuration.getInstance().getTopRegion());
ChangeVmConfiguration.setBottomRegion(Configuration.getInstance().getBottomRegion());
}
public static int getBottomRegion() {
return bottomRegion;
}
public static void setBottomRegion(int bottomRegion) {
ChangeVmConfiguration.bottomRegion = bottomRegion;
}
@Override
public int predict() {
this.calculateBetterAllocationValues();
// decide how urgent a configurationchange is 0-100, 100 = urgent
int prediction = 0;
prediction = (Math.abs(this.vm.getCurrentCpuAllocation() - this.optimizedCpuAllocation) + Math.abs(this.vm.getCurrentMemoryAllocation() - this.optimizedMemoryAllocation) + Math.abs(this.vm.getCurrentStorageAllocation() - this.optimizedStorageAllocation)) / 3;
int slaViolationUrgency = 10;
int slaViolationCount = this.vm.getNumberOfSlaViolations(this.tickCount);
if (prediction < slaViolationUrgency && slaViolationCount > 0) {
// reallocation should be neccessary, chose 10% importance
prediction = slaViolationUrgency + slaViolationCount;
if (prediction > 100) {
prediction = 100;
}
}
return 0;
}
/**
* Calculates better VM allocation values for the given VM, depending in which zone it's currently in.
*/
private void calculateBetterAllocationValues() {
this.optimizedCpuAllocation = this.calculateOptimizedCpuAllocation(this.tickCount);
this.optimizedMemoryAllocation = this.calculateOptimizedMemoryAllocation(this.tickCount);
this.optimizedStorageAllocation = this.calculateOptimizedStorageAllocation(this.tickCount);
}
/**
* Calculates an optimized CPU allocation value for the VM
*
* @param ticks Based on the last n ticks
* @return The optimized CPU allocation value
*/
private int calculateOptimizedCpuAllocation(int ticks) {
return this.calculateOptimizedAllocation(this.vm.getCurrentCpuAllocation(), this.vm.getCpuAllocationHistory(this.tickCount), this.vm.getCpuUsageHistory(this.tickCount));
}
/**
* Calculates an optimized memory allocation value for the VM
*
* @param ticks Based on the last n ticks
* @return The optimized memory allocation value
*/
private int calculateOptimizedMemoryAllocation(int ticks) {
return this.calculateOptimizedAllocation(this.vm.getCurrentMemoryAllocation(), this.vm.getMemoryAllocationHistory(this.tickCount), this.vm.getMemoryUsageHistory(this.tickCount));
}
/**
* Calculates an optimized storage allocation value for the VM
*
* @param ticks Based on the last n ticks
* @return The optimized storage allocation value
*/
private int calculateOptimizedStorageAllocation(int ticks) {
return this.calculateOptimizedAllocation(this.vm.getCurrentStorageAllocation(), this.vm.getStorageAllocationHistory(this.tickCount), this.vm.getStorageUsageHistory(this.tickCount));
}
/**
* Calculates an optimized allocation value for a given history of values
*
* @param currentAllocation
* @param allocationHistory
* @param usageHistory
* @return Optimized allocation value
*/
private int calculateOptimizedAllocation(int currentAllocation, List<Integer> allocationHistory, List<Integer> usageHistory) {
int allocation = currentAllocation;
int optimizedAllocation = 0;
int topRegionReached = 0;
int bottomRegionReached = 0;
// calculate how often the VM went into a dangerous zone in the last n ticks (compare allocated to used resources)
for (int i = 0; i < allocationHistory.size(); i++) {
Integer allocated = allocationHistory.get(i);
Integer used = usageHistory.get(i);
// calculate percentage of the used resources vs. the allocated resources
int ratio = (int) ((used / (float) allocated) * 100);
if (ratio > ChangeVmConfiguration.topRegion) {
// need more resources
topRegionReached++;
} else if (ratio < ChangeVmConfiguration.bottomRegion) {
// need less resources
bottomRegionReached++;
} else {
// resource allocation is perfect
// do nothing
}
// calculate allocation so that "used" is 95% of the allocation
optimizedAllocation = (int) ((float) used / ChangeVmConfiguration.topRegion * 100);
if (topRegionReached > 1 || bottomRegionReached > 1) {
// need to change the allocation
if (allocation < optimizedAllocation) {
allocation = optimizedAllocation;
}
}
}
if (allocation > 100) {
allocation = 100;
} else if (allocation < 0) {
allocation = 0;
}
return allocation;
}
@Override
public int estimate() {
return ChangeVmConfiguration.configurationChangeCosts;
}
@Override
public boolean preconditions() {
// VMs can always be changed
return true;
}
@Override
public void execute() {
// change CPU allocation
if (this.vm.getCurrentCpuAllocation() != this.optimizedCpuAllocation) {
this.vm.setCurrentCpuAlloction(this.optimizedCpuAllocation);
}
// change memory allocation
if (this.vm.getCurrentMemoryAllocation() != this.optimizedMemoryAllocation) {
this.vm.setCurrentMemoryAlloction(this.optimizedMemoryAllocation);
}
// change storage allocation
if (this.vm.getCurrentStorageAllocation() != this.optimizedStorageAllocation) {
this.vm.setCurrentStorageAlloction(this.optimizedStorageAllocation);
}
}
@Override
public boolean evaluate() {
// nothing to do here
return true;
}
@Override
public void terminate() {
// unused
}
public static int getConfigurationChangeCosts() {
return configurationChangeCosts;
}
public static void setConfigurationChangeCosts(int configurationChangeCosts) {
ChangeVmConfiguration.configurationChangeCosts = configurationChangeCosts;
}
public static int getTopRegion() {
return topRegion;
}
public static void setTopRegion(int topRegion) {
ChangeVmConfiguration.topRegion = topRegion;
}
}
| [
"yuzhongxing88@gmail.com"
] | yuzhongxing88@gmail.com |
df1293e7f64be2c2ad57f65a0b177a07aa2bc9fb | 7274583b08e6a3d858134cad42f330c1544584ff | /src/main/java/blue/thejester/badderbaddies/entity/blaze/ThunderBlaze.java | 9141489cc8b0e8d16b248f9b4390b16b9e528da4 | [] | no_license | AnnaErisian/Badder-Baddies | ff2a7e48c6a040f92e65f6af6b778d88f108394d | ee7eb4809702ef95d8bff62d21da793821c438c1 | refs/heads/master | 2022-11-16T21:32:36.970666 | 2020-07-13T13:37:15 | 2020-07-13T13:37:15 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 2,118 | java | package blue.thejester.badderbaddies.entity.blaze;
import blue.thejester.badderbaddies.BadderBaddies;
import blue.thejester.badderbaddies.client.render.blaze.RenderThunderBlaze;
import blue.thejester.badderbaddies.entity.LootTables;
import net.minecraft.entity.projectile.EntitySmallFireball;
import net.minecraft.util.ResourceLocation;
import net.minecraft.world.World;
import net.minecraftforge.fml.client.registry.RenderingRegistry;
import net.minecraftforge.fml.common.registry.EntityRegistry;
import net.minecraftforge.fml.relauncher.Side;
import net.minecraftforge.fml.relauncher.SideOnly;
public class ThunderBlaze extends EntityMyBlaze {
public static final String NAME = "blaze_thunder";
public ThunderBlaze(World worldIn) {
super(worldIn);
this.experienceValue += 20;
}
@Override
protected double healthBoost() {
return 10;
}
@Override
protected double numFireballs() {
return 1;
}
@Override
protected float magicContactDamage() {
return 3;
}
protected void initEntityAI()
{
super.initEntityAI();
this.tasks.addTask(4, new EntityMyBlaze.AIFireballAttack(this, false));
}
@Override
protected EntitySmallFireball createFireball(World world, EntityMyBlaze blaze, double v, double d2, double v1) {
return new LightningFireball(world, blaze, v, d2, v1);
}
protected ThunderBlaze createInstance() {
return new ThunderBlaze(this.world);
}
@Override
protected ResourceLocation getLootTable() {
return LootTables.BLAZE_THUNDER;
}
public static void registerSelf(int id) {
ResourceLocation entity_name = new ResourceLocation(BadderBaddies.MODID, NAME);
EntityRegistry.registerModEntity(entity_name, ThunderBlaze.class, NAME, id,
BadderBaddies.instance, 64, 3, true,
0xe6a601, 0xffff00);
}
@SideOnly(Side.CLIENT)
public static void registerOwnRenderer() {
RenderingRegistry.registerEntityRenderingHandler(ThunderBlaze.class, RenderThunderBlaze.FACTORY);
}
}
| [
"jaketheultimate@gmail.com"
] | jaketheultimate@gmail.com |
b9842984d49ac823ce8243f4fb4c35cfc78645df | 73416f4cbacafa2f987ceef077752a669b75fa0a | /src/test/java/cn/leancloud/kafka/consumer/integration/RevokePausedPartitionTest.java | bc0f9ec2619a16ad5caffc9ae0661e777a192209 | [
"MIT"
] | permissive | leancloud/kafka-java-consumer | 12c07f9070bcef30a5f4678a9410122ad92f9c50 | f22719995c57eb66a411b98b1ed71e2dbad940f9 | refs/heads/master | 2022-02-07T07:22:08.322156 | 2022-01-05T01:09:41 | 2022-01-05T01:09:41 | 230,073,616 | 4 | 0 | MIT | 2022-01-05T01:10:22 | 2019-12-25T08:55:11 | Java | UTF-8 | Java | false | false | 7,471 | java | package cn.leancloud.kafka.consumer.integration;
import org.apache.kafka.clients.consumer.*;
import org.apache.kafka.clients.producer.KafkaProducer;
import org.apache.kafka.clients.producer.ProducerRecord;
import org.apache.kafka.common.TopicPartition;
import org.apache.kafka.common.errors.WakeupException;
import org.apache.kafka.common.serialization.IntegerDeserializer;
import org.apache.kafka.common.serialization.IntegerSerializer;
import org.apache.kafka.common.serialization.StringDeserializer;
import org.apache.kafka.common.serialization.StringSerializer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.Closeable;
import java.io.IOException;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.CompletableFuture;
public class RevokePausedPartitionTest {
private static final Logger logger = LoggerFactory.getLogger(RevokePausedPartitionTest.class);
private static final String topic = "Testing";
private Map<String, Object> configs;
private Consumer<Integer, String> pausePartitionConsumer;
private Consumer<Integer, String> normalConsumer;
public RevokePausedPartitionTest() {
configs = new HashMap<>();
configs.put("bootstrap.servers", "localhost:9092");
configs.put("auto.offset.reset", "earliest");
configs.put("group.id", "2614911922612339122");
configs.put("max.poll.records", 100);
configs.put("max.poll.interval.ms", "5000");
configs.put("key.deserializer", IntegerDeserializer.class.getName());
configs.put("value.deserializer", StringDeserializer.class.getName());
}
void run() throws Exception {
final Map<String, Object> producerConfigs = new HashMap<>();
producerConfigs.put("bootstrap.servers", "localhost:9092");
KafkaProducer<Integer, String> producer = new KafkaProducer<>(configs, new IntegerSerializer(), new StringSerializer());
for (int i = 0; i < 100; i++) {
final ProducerRecord<Integer, String> record = new ProducerRecord<>(topic, null, "" + i);
producer.send(record, (metadata, exception) -> {
if (exception != null) {
logger.error("Produce record failed", exception);
}
});
}
CompletableFuture<Void> rebalanceTrigger = new CompletableFuture<>();
pausePartitionConsumer = new KafkaConsumer<>(configs);
pausePartitionConsumer.subscribe(Collections.singletonList(topic), new RebalanceListener("paused consumer"));
new Thread(new PausePartitionConsumerJob(
pausePartitionConsumer,
rebalanceTrigger))
.start();
rebalanceTrigger.whenComplete((r, t) -> {
normalConsumer = new KafkaConsumer<>(configs);
normalConsumer.subscribe(Collections.singletonList(topic), new RebalanceListener("normal consumer"));
new Thread(new NormalConsumerJob(
normalConsumer))
.start();
for (int i = 100; i < 200; i++) {
final ProducerRecord<Integer, String> record = new ProducerRecord<>(topic, null, "" + i);
producer.send(record, (metadata, exception) -> {
if (exception != null) {
logger.error("Produce record failed", exception);
}
});
}
});
}
private static class PausePartitionConsumerJob implements Runnable, Closeable {
private Consumer<Integer, String> pausePartitionConsumer;
private CompletableFuture<Void> rebalanceTrigger;
private volatile boolean closed;
public PausePartitionConsumerJob(Consumer<Integer, String> consumer,
CompletableFuture<Void> rebalanceTrigger) {
this.pausePartitionConsumer = consumer;
this.rebalanceTrigger = rebalanceTrigger;
}
@Override
public void run() {
while (true) {
try {
ConsumerRecords<Integer, String> records = pausePartitionConsumer.poll(100);
if (!records.isEmpty()) {
if (!rebalanceTrigger.isDone()) {
pausePartitionConsumer.pause(records.partitions());
handleRecords(records);
rebalanceTrigger.complete(null);
} else {
handleRecords(records);
}
}
} catch (WakeupException ex) {
if (closed) {
break;
}
} catch (Exception ex) {
logger.error("Paused consumer got unexpected exception", ex);
}
}
}
@Override
public void close() throws IOException {
closed = true;
pausePartitionConsumer.wakeup();
}
private void handleRecords(ConsumerRecords<Integer, String> records) {
for (ConsumerRecord<Integer, String> record : records) {
logger.info("receive msgs on pause partition consumer " + record);
}
}
}
private static class NormalConsumerJob implements Runnable, Closeable {
private Consumer<Integer, String> consumer;
private volatile boolean closed;
public NormalConsumerJob(Consumer<Integer, String> consumer) {
this.consumer = consumer;
}
@Override
public void run() {
while (true) {
try {
ConsumerRecords<Integer, String> records = consumer.poll(100);
if (!records.isEmpty()) {
handleRecords(records);
}
} catch (WakeupException ex) {
if (closed) {
break;
}
} catch (Exception ex) {
logger.error("Normal consumer got unexpected exception", ex);
}
}
}
@Override
public void close() throws IOException {
closed = true;
consumer.wakeup();
}
private void handleRecords(ConsumerRecords<Integer, String> records) {
for (ConsumerRecord<Integer, String> record : records) {
logger.info("receive msgs on normal consumer " + record);
}
}
}
private static class RebalanceListener implements ConsumerRebalanceListener {
private String consumerName;
public RebalanceListener(String consumerName) {
this.consumerName = consumerName;
}
@Override
public void onPartitionsRevoked(Collection<TopicPartition> partitions) {
logger.info("Partitions " + partitions + " revoked from consumer: " + consumerName);
}
@Override
public void onPartitionsAssigned(Collection<TopicPartition> partitions) {
logger.info("Partitions " + partitions + " assigned to consumer: " + consumerName);
}
}
public static void main(String[] args) throws Exception {
RevokePausedPartitionTest test = new RevokePausedPartitionTest();
test.run();
}
}
| [
"alven.gr@gmail.com"
] | alven.gr@gmail.com |
6d4abe074d6d3122a1c91bb85021ead2d320b2a6 | 94c6db89c1cf9cba8205830e0c8aaa7209ad9a49 | /mortgage/src/main/java/com/ing/mortgage/exception/InvalidMobileNumberException.java | 7da785822489c933ce0b4600b9ce5badc09169b3 | [] | no_license | SubhaMaheswaran27/Squad1works | edfe5d1e362c63f3d48feefe7f002f2862388b45 | 616c53d4aa8c1f330d427b31ff78adedea47f39a | refs/heads/master | 2020-08-27T07:45:11.308797 | 2019-10-24T12:09:05 | 2019-10-24T12:09:05 | 217,288,638 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 356 | java | package com.ing.mortgage.exception;
import java.io.Serializable;
public class InvalidMobileNumberException extends RuntimeException implements Serializable {
private static final long serialVersionUID = 1L;
private static final String MESSAGE = "Please enter a valid mobile Number";
public InvalidMobileNumberException() {
super(MESSAGE);
}
}
| [
"User1@LP-5CD9296CMW.HCLT.CORP.HCL.IN"
] | User1@LP-5CD9296CMW.HCLT.CORP.HCL.IN |
069f3030157632652c6e89da51330a029cc569b0 | b2bd1d6ac6c18e3bd92331b8072e25b33599c638 | /src/Display.java | d481abd578a2cf087c26d37eb578d1e470e4141b | [] | no_license | sacooper/Lab5-Orienteering | 13fb22b7c0e209fe0110f6776cf856e6b0353258 | da8f03c93966b1f6c3c9a5358a82ed73fe2b0ecb | refs/heads/master | 2016-09-06T16:31:31.258681 | 2014-10-15T15:28:49 | 2014-10-15T15:28:49 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 3,163 | java | /*
* OdometryDisplay.java
*
* Controls what is displayed on the NXT screen
*/
import lejos.nxt.LCD;
public class Display {
/****
* Print the current values of x, y, and theta to the screen.
*
* Modified to be called from the Odometry class, to allow for more control
* @param <Position>
*
* @param x The current x value of the odometer in cm
* @param y The current y value of the domoeter in cm
* @param theta The current value of theta (amount the robot has rotated) in radians
*/
public static void printDemoInfo(final double x, final double y, final double theta, final int observations, final Position start){
new Thread(new Runnable(){ public void run(){
String sx = formattedDoubleToString((((double)start.getX()) - 0.5)*Odometer.TILE_SIZE, 2);
String sy = formattedDoubleToString((((double)start.getY()) - 0.5)*Odometer.TILE_SIZE, 2);
LCD.clear();
// clear the lines for displaying odometry information
LCD.drawString("X: ", 0, 0);
LCD.drawString("Y: ", 0, 1);
LCD.drawString("T: ", 0, 2);
LCD.drawString("Observations: " + observations, 0, 3);
LCD.drawString("Start: ", 0, 4);
LCD.drawString("(" + sx + ", " + sy + ")", 0, 5);
LCD.drawString(start.getDir().asCardinal(), 0, 6);
LCD.drawString(formattedDoubleToString(x, 2), 3, 0);
LCD.drawString(formattedDoubleToString(y, 2), 3, 1);
LCD.drawString(formattedDoubleToString(theta, 2), 3, 2);}}).start();}
public static void printLocalizationInfo(int x, int y, Direction current, boolean blocked, int size){
new Thread(new Runnable(){ public void run(){
LCD.clear();
LCD.drawString(blocked + "" , 0, 0);
LCD.drawString("# possible: " + size, 0, 1);
LCD.drawString("Relative Location:", 0, 2);
LCD.drawString(x + ", " + y + ", " + current.toString(), 0, 3);
}}).start();}
private static String formattedDoubleToString(double x, int places) {
String result = "";
String stack = "";
long t;
// put in a minus sign as needed
if (x < 0.0)
result += "-";
// put in a leading 0
if (-1.0 < x && x < 1.0)
result += "0";
else {
t = (long)x;
if (t < 0)
t = -t;
while (t > 0) {
stack = Long.toString(t % 10) + stack;
t /= 10;
}
result += stack;
}
// put the decimal, if needed
if (places > 0) {
result += ".";
// put the appropriate number of decimals
for (int i = 0; i < places; i++) {
x = Math.abs(x);
x = x - Math.floor(x);
x *= 10.0;
result += Long.toString((long)x);
}
}
return result;
}
/******
* Print the main menu
*/
public static void printMainMenu() {
// clear the display
LCD.clear();
// ask the user whether the motors should Avoid Block or Go to locations
LCD.drawString("< Left | Right >", 0, 0);
LCD.drawString(" | ", 0, 1);
LCD.drawString(" STOCH | DET. ", 0, 2);
LCD.drawString("----------------", 0, 3);
LCD.drawString(" DEMO=ENTER ", 0, 4);
LCD.drawString(" vvvvvv ", 0, 5);
}
}
| [
"scott.cooper2@mail.mcgill.ca"
] | scott.cooper2@mail.mcgill.ca |
39a9189afde3e3d9f23dc6ae90994144d8758acb | c42531b0f0e976dd2b11528504e349d5501249ae | /Hartsbourne/MHSystems/app/src/main/java/com/mh/systems/hartsbourne/web/models/clubnews/ClubNewsItems.java | c18361b960687d8b567974bee056df55446353a4 | [
"MIT"
] | permissive | Karan-nassa/MHSystems | 4267cc6939de7a0ff5577c22b88081595446e09e | a0e20f40864137fff91784687eaf68e5ec3f842c | refs/heads/master | 2021-08-20T05:59:06.864788 | 2017-11-28T08:02:39 | 2017-11-28T08:02:39 | 112,189,266 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,315 | java |
package com.mh.systems.hartsbourne.web.models.clubnews;
import java.util.ArrayList;
import java.util.List;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
public class ClubNewsItems {
@SerializedName("Message")
@Expose
private String Message;
@SerializedName("Result")
@Expose
private Integer Result;
@SerializedName("Data")
@Expose
private List<ClubNewsData> Data = new ArrayList<ClubNewsData>();
/**
*
* @return
* The Message
*/
public String getMessage() {
return Message;
}
/**
*
* @param Message
* The Message
*/
public void setMessage(String Message) {
this.Message = Message;
}
/**
*
* @return
* The Result
*/
public Integer getResult() {
return Result;
}
/**
*
* @param Result
* The Result
*/
public void setResult(Integer Result) {
this.Result = Result;
}
/**
*
* @return
* The Data
*/
public List<ClubNewsData> getData() {
return Data;
}
/**
*
* @param Data
* The Data
*/
public void setData(List<ClubNewsData> Data) {
this.Data = Data;
}
}
| [
"nitish@ucreate.co.in"
] | nitish@ucreate.co.in |
6642c5596b8a199ff4509fe069fb77433d49832f | 6925f8f5e195b6cc606f3e91f2c735d6a99a5a7a | /Save/app/src/main/java/com/github/albalitz/save/activities/RegisterActivity.java | 6d1a0c5c5cf311194804cd25b0e176ba3198e9ca | [
"MIT"
] | permissive | vaginessa/save-android | 8b0806a8094942f1f26090f62f9449e0ba5c36d9 | a49fdde2a116e088a6cd0c6bf33f815a5e908380 | refs/heads/master | 2021-01-21T08:20:23.079507 | 2017-05-14T18:06:27 | 2017-05-14T18:06:27 | 91,623,419 | 0 | 0 | MIT | 2019-01-18T12:33:55 | 2017-05-17T21:55:05 | Java | UTF-8 | Java | false | false | 3,983 | java | package com.github.albalitz.save.activities;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import com.github.albalitz.save.R;
import com.github.albalitz.save.persistence.api.Api;
import com.github.albalitz.save.persistence.Link;
import com.github.albalitz.save.utils.Utils;
import org.json.JSONException;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.Arrays;
public class RegisterActivity extends AppCompatActivity
implements ApiActivity, SnackbarActivity {
private EditText editTextUsername;
private EditText editTextPassword;
private Button buttonRegister;
private Button buttonCancel;
private Api api;
private TextWatcher watcher = new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {}
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
Log.d(this.toString(), "onTextChanged triggered.");
setRegisterButtonState(filledBothInputs());
}
@Override
public void afterTextChanged(Editable s) {}
};
@Override
protected void onCreate(Bundle savedInstanceState) {
Log.d(this.toString(), "Creating RegisterActivity.");
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_register);
api = new Api(this);
// assign content
editTextUsername = (EditText) findViewById(R.id.editTextUsername);
editTextPassword = (EditText) findViewById(R.id.editTextPassword);
buttonCancel = (Button) findViewById(R.id.buttonCancel);
buttonRegister = (Button) findViewById(R.id.buttonRegister);
// prepare stuff
Log.v(this.toString(), "Adding button click listener ...");
setRegisterButtonState(filledBothInputs());
buttonCancel.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
finish();
}
});
buttonRegister.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
registerUser();
}
});
Log.v(this.toString(), "Adding TextWatcher ...");
editTextUsername.addTextChangedListener(watcher);
editTextPassword.addTextChangedListener(watcher);
}
protected boolean filledBothInputs() {
for (String input : Arrays.asList(
editTextUsername.getText().toString().trim(),
editTextPassword.getText().toString().trim()
)) {
if (input.isEmpty()) {
return false;
}
}
return true;
}
protected void setRegisterButtonState(boolean state) {
Log.v(this.toString(), "Register button state is now " + state + ".");
buttonRegister.setEnabled(state);
}
private void registerUser() {
Utils.showSnackbar(this, "Registering...");
String username = editTextUsername.getText().toString();
String password = editTextPassword.getText().toString();
try {
api.registerUser(username, password);
} catch (JSONException e) {
e.printStackTrace();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
}
@Override
public void onRegistrationError(String message) {
// todo
}
@Override
public void onRegistrationSuccess() {
finish();
}
@Override
public void onSavedLinksUpdate(ArrayList<Link> savedLinks) {}
@Override
public View viewFromActivity() {
return findViewById(R.id.buttonRegister);
}
}
| [
"albalitz@fb3.uni-bremen.de"
] | albalitz@fb3.uni-bremen.de |
1fd2788e8d6752c21d9218d41812b2c2b81f580b | 5f4ace6d5994a707549f422d4665b5f364d2abc1 | /hunter-portals/src/main/java/com/gt/hunter/portals/domain/Job.java | cd34aa8626fab223e5087dc0516cac7bab4355f2 | [] | no_license | tangguoqiang/hunter | e9b85f9dfffab4ba5da58be1f648f1c347bd0dd9 | 6a2eba8cfe0cd0b478a748faddaece7c695fd189 | refs/heads/master | 2021-01-20T21:06:21.474239 | 2016-06-03T15:33:01 | 2016-06-03T15:33:01 | 60,358,391 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 2,105 | java | package com.gt.hunter.portals.domain;
import java.io.Serializable;
import com.gt.hunter.portals.common.annotation.Column;
public class Job implements Serializable{
/**
*
*/
private static final long serialVersionUID = -8070311796680471665L;
@Column
private String id;
@Column
private String companyId;
@Column
private String department;
@Column
private String post;
@Column
private String salary;
@Column
private String degree;
@Column
private String nature;
@Column
private String place;
@Column
private String experience;
@Column
private String publishTime;
@Column
private String status;
private String company;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getCompanyId() {
return companyId;
}
public void setCompanyId(String companyId) {
this.companyId = companyId;
}
public String getPost() {
return post;
}
public void setPost(String post) {
this.post = post;
}
public String getSalary() {
return salary;
}
public void setSalary(String salary) {
this.salary = salary;
}
public String getDegree() {
return degree;
}
public void setDegree(String degree) {
this.degree = degree;
}
public String getDepartment() {
return department;
}
public void setDepartment(String department) {
this.department = department;
}
public String getNature() {
return nature;
}
public void setNature(String nature) {
this.nature = nature;
}
public String getPlace() {
return place;
}
public void setPlace(String place) {
this.place = place;
}
public String getExperience() {
return experience;
}
public void setExperience(String experience) {
this.experience = experience;
}
public String getPublishTime() {
return publishTime;
}
public void setPublishTime(String publishTime) {
this.publishTime = publishTime;
}
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
public String getCompany() {
return company;
}
public void setCompany(String company) {
this.company = company;
}
}
| [
"tangguoqiang1987@live.cn"
] | tangguoqiang1987@live.cn |
1418c045d8f264ff68a33d2be74d903527d0e75e | 2a517d24718f83e6a38c0665d833f25bcc6915f7 | /src/com/fa2id/app/user/UserInteractionFactory.java | aad5b854d48bce594b68d0e26395dd4ef1adfc07 | [] | no_license | fa2id/currency-converter | 32e48782f9375b0c7cda1e6155fc61df385e758c | 58ec102f7e42f88069a8caa7d8eaf322bf9cf516 | refs/heads/master | 2020-04-21T00:33:06.578708 | 2019-02-05T14:10:40 | 2019-02-05T14:10:40 | 169,199,936 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 391 | java | package com.fa2id.app.user;
/**
* This is the factory class for UserInteraction.
*
* @author Farid Ariafard
* www.fa2id.com
*/
public class UserInteractionFactory {
/**
* This method creates UserInteraction object.
*
* @return UserInteraction object.
*/
public static UserInteraction create() {
return new UserInteractionImplementation();
}
}
| [
"faridsenior@gmail.com"
] | faridsenior@gmail.com |
dbbec3ebf0d5d6558ab12a6586bad0a7a303583f | 7812038b49406b700f2a14b04b6a71b2224540a3 | /app/src/main/java/com/ltbrew/brewbeer/service/PldForBrewSession.java | ff8af2330095289f03483d6e09f3fd0c7e29b2ba | [] | no_license | JasonQiusip/brewbeer | 63671b33cdab494cff96dbba36e136923f17c394 | 246dff2d01df1b1437466f99e27f607466bddcf3 | refs/heads/master | 2021-01-21T14:25:23.496027 | 2016-07-08T08:53:43 | 2016-07-08T08:53:43 | 57,968,702 | 2 | 1 | null | null | null | null | UTF-8 | Java | false | false | 1,092 | java | package com.ltbrew.brewbeer.service;
import android.os.Parcel;
import android.os.Parcelable;
/**
* Created by 151117a on 2016/5/25.
*/
public class PldForBrewSession implements Parcelable {
public String packId;
public String formulaId;
public int state;
public PldForBrewSession(){}
protected PldForBrewSession(Parcel in) {
packId = in.readString();
formulaId = in.readString();
state = in.readInt();
}
public static final Creator<PldForBrewSession> CREATOR = new Creator<PldForBrewSession>() {
@Override
public PldForBrewSession createFromParcel(Parcel in) {
return new PldForBrewSession(in);
}
@Override
public PldForBrewSession[] newArray(int size) {
return new PldForBrewSession[size];
}
};
@Override
public int describeContents() {
return 0;
}
@Override
public void writeToParcel(Parcel parcel, int i) {
parcel.writeString(packId);
parcel.writeString(formulaId);
parcel.writeInt(state);
}
}
| [
"qiusp@beiqicloud.com"
] | qiusp@beiqicloud.com |
6a79522f456b7b6f3969e1d5ad62b31d6a32cf9f | d78f20b6412c0deae07028acd067aff4f23db1f3 | /GQ_Android/test/com/qeevee/gq/tests/TestNPCTalkUtils.java | 3e770beae64a58a1e88fa080d37511411837628d | [] | no_license | f-l-o/android | 617fd5d81d0463993faada124519e201367f4112 | 57df1a41c3a4a29e7b152b69f566342494ba92ae | refs/heads/master | 2020-12-24T10:14:39.782547 | 2013-03-05T15:13:31 | 2013-03-05T15:13:31 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,566 | java | package com.qeevee.gq.tests;
import static com.qeevee.gq.tests.TestUtils.getFieldValue;
import java.util.Iterator;
import android.os.CountDownTimer;
import android.widget.Button;
import edu.bonn.mobilegaming.geoquest.mission.DialogItem;
import edu.bonn.mobilegaming.geoquest.mission.NPCTalk;
public class TestNPCTalkUtils {
/**
* This helper method emulates the Timer used in the real application. It
* very specialized according to the implementation, e.g. the delta between
* word appearance is set to 100ms as in the code.
*/
public static void letCurrentDialogItemAppearCompletely(NPCTalk npcTalk) {
CountDownTimer timer = (CountDownTimer) getFieldValue(npcTalk,
"myCountDownTimer");
timer.onFinish();
DialogItem dialogItem = (DialogItem) getFieldValue(npcTalk,
"currItem");
timer = (CountDownTimer) getFieldValue(npcTalk,
"myCountDownTimer");
for (int i = 0; i < dialogItem.getNumParts(); i++) {
timer.onTick(100l * (dialogItem.getNumParts() - (i + 1)));
}
timer.onFinish();
}
@SuppressWarnings("unchecked")
public static void forwardUntilLastDialogItemIsShown(NPCTalk npcTalk) {
Iterator<DialogItem> dialogItemIterator = (Iterator<DialogItem>) getFieldValue(npcTalk,
"dialogItemIterator");
Button button = (Button) getFieldValue(npcTalk,
"proceedButton");
while (dialogItemIterator.hasNext()) {
letCurrentDialogItemAppearCompletely(npcTalk);
button.performClick();
}
letCurrentDialogItemAppearCompletely(npcTalk);
}
}
| [
"muegge@acm.org"
] | muegge@acm.org |
dfefbe81e065f7bcc155ef1b01888aa5501059c0 | b92333aa8e1d3ead598c3e6e35da6ef31399d5d9 | /app/src/main/java/com/example/pc/attendance/helpers/data/MultipartUtility.java | 3fba17c2f7eecef973532e02d561cb7656925815 | [] | no_license | lucquyenw/DiemDanh | c26ba3ff686bbe523fd46def0cdbc867105264b0 | 633c2d4bce61088763e76508695d46fd36791c49 | refs/heads/master | 2020-03-26T03:43:23.249489 | 2018-08-12T13:15:47 | 2018-08-12T13:15:47 | 144,468,145 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 4,364 | java | package com.example.pc.attendance.helpers.data;
import android.util.Log;
import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.file.Files;
/**
* Created by azaudio on 7/11/2018.
*/
public class MultipartUtility {
private HttpURLConnection httpConn;
private DataOutputStream request;
private final String boundary = "*****";
private final String crlf = "\r\n";
private final String twoHyphens = "--";
/**
* This constructor initializes a new HTTP POST request with content type
* is set to multipart/form-data
*
* @param requestURL
* @throws IOException
*/
public MultipartUtility(String requestURL)
throws IOException {
// creates a unique boundary based on time stamp
URL url = new URL(requestURL);
httpConn = (HttpURLConnection) url.openConnection();
httpConn.setUseCaches(false);
httpConn.setDoOutput(true); // indicates POST method
httpConn.setDoInput(true);
httpConn.setRequestMethod("POST");
httpConn.setRequestProperty("Connection", "Keep-Alive");
httpConn.setRequestProperty("Cache-Control", "no-cache");
httpConn.setRequestProperty(
"Content-Type", "multipart/form-data;boundary=" + this.boundary);
request = new DataOutputStream(httpConn.getOutputStream());
}
/**
* Adds a form field to the request
*
* @param name field name
* @param value field value
*/
public void addFormField(String name, String value)throws IOException {
request.writeBytes(this.twoHyphens + this.boundary + this.crlf);
request.writeBytes("Content-Disposition: form-data; name=\"" + name + "\""+ this.crlf);
request.writeBytes("Content-Type: text/plain; charset=UTF-8" + this.crlf);
request.writeBytes(this.crlf);
request.writeBytes(value+ this.crlf);
request.flush();
}
/**
* Adds a upload file section to the request
*
* @param fieldName name attribute in <input type="file" name="..." />
* @param uploadFile a File to be uploaded
* @throws IOException
*/
public void addFilePart(String fieldName, File uploadFile)
throws IOException {
String fileName = uploadFile.getName();
request.writeBytes(this.twoHyphens + this.boundary + this.crlf);
request.writeBytes("Content-Disposition: form-data; name=\"" +
fieldName + "\";filename=\"" +
fileName + "\"" + this.crlf);
request.writeBytes(this.crlf);
byte[] bytes = Files.readAllBytes(uploadFile.toPath());
request.write(bytes);
}
/**
* Completes the request and receives response from the server.
*
* @return a list of Strings as response in case the server returned
* status OK, otherwise an exception is thrown.
* @throws IOException
*/
public String finish() throws IOException {
String response ="";
request.writeBytes(this.crlf);
request.writeBytes(this.twoHyphens + this.boundary +
this.twoHyphens + this.crlf);
request.flush();
request.close();
// checks server's status code first
int status = httpConn.getResponseCode();
if (status == HttpURLConnection.HTTP_CREATED) {
InputStream responseStream = new
BufferedInputStream(httpConn.getInputStream());
BufferedReader responseStreamReader =
new BufferedReader(new InputStreamReader(responseStream));
String line = "";
StringBuilder stringBuilder = new StringBuilder();
while ((line = responseStreamReader.readLine()) != null) {
stringBuilder.append(line).append("\n");
}
responseStreamReader.close();
response = stringBuilder.toString();
Log.d("Mujltipart",response);
httpConn.disconnect();
} else {
throw new IOException("Server returned non-OK status: " + status);
}
return response;
}
}
| [
"40686918+lucquyenw@users.noreply.github.com"
] | 40686918+lucquyenw@users.noreply.github.com |
fa790016c6206e8e1c2592843ea54100a533cdab | fa91450deb625cda070e82d5c31770be5ca1dec6 | /Diff-Raw-Data/11/11_71a931e4cf57dfb24cb50d836e30b708ced7f9fe/NewWinner/11_71a931e4cf57dfb24cb50d836e30b708ced7f9fe_NewWinner_t.java | 87c3e28fa2d325865bc796e58923e3923b6c1515 | [] | no_license | zhongxingyu/Seer | 48e7e5197624d7afa94d23f849f8ea2075bcaec0 | c11a3109fdfca9be337e509ecb2c085b60076213 | refs/heads/master | 2023-07-06T12:48:55.516692 | 2023-06-22T07:55:56 | 2023-06-22T07:55:56 | 259,613,157 | 6 | 2 | null | 2023-06-22T07:55:57 | 2020-04-28T11:07:49 | null | UTF-8 | Java | false | false | 5,703 | java | package com.Grateds.Reversi.GUI;
import com.Grateds.Reversi.User;
import com.Grateds.Reversi.CONTROLLER.Controller;
/**
*
* @author Abuzaid
*/
public class NewWinner extends javax.swing.JFrame {
/**
*
*/
private static final long serialVersionUID = 1L;
/**
* Creates new form UserInterface
*/
private Controller controller;
public NewWinner(Controller c) {
controller = c;
initComponents();
this.setLocationRelativeTo(getOwner());
this.setResizable(false);
this.setVisible(true);
this.setDefaultCloseOperation(HIDE_ON_CLOSE);
}
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
jLabel1 = new javax.swing.JLabel();
jTextField1 = new javax.swing.JTextField();
jLabel2 = new javax.swing.JLabel();
jLabel3 = new javax.swing.JLabel();
jTextField2 = new javax.swing.JTextField();
jButton1 = new javax.swing.JButton();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
setTitle("NEW WINNER");
jLabel1.setFont(new java.awt.Font("Tahoma", 1, 14)); // NOI18N
jLabel1.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
jLabel2.setFont(new java.awt.Font("Tahoma", 0, 12)); // NOI18N
jLabel2.setText("Name");
jLabel3.setFont(new java.awt.Font("Tahoma", 0, 12)); // NOI18N
jLabel3.setText("Score");
jTextField2.setEditable(false);
jTextField2.setText(controller.get_totalScore()+"");
jButton1.setText("Submit");
jButton1.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton1ActionPerformed(evt);
}
});
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addContainerGap(17, Short.MAX_VALUE)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addComponent(jLabel2)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, 92, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(47, 47, 47)
.addComponent(jLabel3)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jTextField2, javax.swing.GroupLayout.PREFERRED_SIZE, 70, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(34, 34, 34))
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addComponent(jButton1)
.addGap(130, 130, 130))))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addComponent(jLabel1)
.addGap(29, 29, 29)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel2)
.addComponent(jLabel3)
.addComponent(jTextField2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(18, 18, 18)
.addComponent(jButton1)
.addGap(0, 18, Short.MAX_VALUE))
);
pack();
}// </editor-fold>//GEN-END:initComponents
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jComboBox1ActionPerformed
controller.stop();
boolean terminate = false;
while(!jTextField1.getText().equals("") && !terminate){
User u = new User();
String score = jTextField2.getText();
u.create(jTextField1.getText(), Integer.parseInt(score));
terminate = true;
this.setVisible(false);
}
controller.resume();
}//GEN-LAST:event_jComboBox1ActionPerformed
/**
* @param args the command line arguments
*/
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JButton jButton1;
private javax.swing.JLabel jLabel1;
private javax.swing.JLabel jLabel2;
private javax.swing.JLabel jLabel3;
private javax.swing.JTextField jTextField1;
private javax.swing.JTextField jTextField2;
// End of variables declaration//GEN-END:variables
}
| [
"yuzhongxing88@gmail.com"
] | yuzhongxing88@gmail.com |
b4d533d21e9b3c96d7dd3a4841eaf5b55992dc78 | 713a06e5213457211875a91f6b488d8d2e49b923 | /src/main/java/com/authservice/config/AuthorizationServerConfiguration.java | 66735f63ff210b1dae2e538d9df3eca2eb4702cd | [] | no_license | Lindsay-Austin/is-server-auth | a7e27124ae7212cffd9e371fd1d7466070e14cb1 | 303515c1cb48d1518cfd5b4536b441f0e9da25eb | refs/heads/master | 2022-12-11T00:02:58.861459 | 2020-09-06T09:07:13 | 2020-09-06T09:07:13 | 287,937,950 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 5,335 | java | package com.authservice.config;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.oauth2.config.annotation.configurers.ClientDetailsServiceConfigurer;
import org.springframework.security.oauth2.config.annotation.web.configuration.AuthorizationServerConfigurerAdapter;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableAuthorizationServer;
import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerEndpointsConfigurer;
import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerSecurityConfigurer;
import org.springframework.security.oauth2.provider.token.TokenStore;
import org.springframework.security.oauth2.provider.token.store.JdbcTokenStore;
import javax.sql.DataSource;
/**
* 认证授权服务端
*
* @author leftso
*
*/
@Configuration
@EnableAuthorizationServer
public class AuthorizationServerConfiguration extends AuthorizationServerConfigurerAdapter {
@Value("${resource.id:spring-boot-application}") // 默认值spring-boot-application
private String resourceId;
@Value("${access_token.validity_period:3600}") // 默认值3600
int accessTokenValiditySeconds = 3600;
@Autowired
private AuthenticationManager authenticationManager;
@Autowired
private PasswordEncoder passwordEncoder;
@Autowired
private DataSource datasource;
@Bean
public TokenStore tokenStore(){
return new JdbcTokenStore(datasource);
};
@Override
public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
endpoints
.tokenStore(tokenStore())
.authenticationManager(this.authenticationManager);
}
@Override
public void configure(AuthorizationServerSecurityConfigurer oauthServer) throws Exception {
/*oauthServer.tokenKeyAccess("isAnonymous() || hasAuthority('ROLE_TRUSTED_CLIENT')");
oauthServer.checkTokenAccess("hasAuthority('ROLE_TRUSTED_CLIENT')");*/
oauthServer.checkTokenAccess("isAuthenticated()");
}
public static void main(String[] args){
System.out.println(new BCryptPasswordEncoder().encode("123456"));
}
@Override
public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
/*clients.inMemory().withClient("normal-app")
.authorizedGrantTypes("authorization_code", "implicit")
.authorities("ROLE_CLIENT")
.scopes("read", "write")
.resourceIds("order-server")
.accessTokenValiditySeconds(accessTokenValiditySeconds)
.and()
.withClient("trusted-app")
.authorizedGrantTypes("client_credentials", "password")
.authorities("ROLE_TRUSTED_CLIENT")
.scopes("read", "write")
.resourceIds("order-server")
.accessTokenValiditySeconds(accessTokenValiditySeconds)
.secret(passwordEncoder.encode("123456"));*/
clients.jdbc(datasource);
}
/**
* token converter
*
* @return
*/
// @Bean
// public JwtAccessTokenConverter accessTokenConverter() {
// JwtAccessTokenConverter accessTokenConverter = new JwtAccessTokenConverter() {
// /***
// * 重写增强token方法,用于自定义一些token返回的信息
// */
// @Override
// public OAuth2AccessToken enhance(OAuth2AccessToken accessToken, OAuth2Authentication authentication) {
// String userName = authentication.getUserAuthentication().getName();
// User user = (User) authentication.getUserAuthentication().getPrincipal();// 与登录时候放进去的UserDetail实现类一直查看link{SecurityConfiguration}
// /** 自定义一些token属性 ***/
// final Map<String, Object> additionalInformation = new HashMap<>();
// additionalInformation.put("userName", userName);
// additionalInformation.put("roles", user.getAuthorities());
// ((DefaultOAuth2AccessToken) accessToken).setAdditionalInformation(additionalInformation);
// OAuth2AccessToken enhancedToken = super.enhance(accessToken, authentication);
// return enhancedToken;
// }
//
// };
// accessTokenConverter.setSigningKey("123");// 测试用,资源服务使用相同的字符达到一个对称加密的效果,生产时候使用RSA非对称加密方式
// return accessTokenConverter;
// }
/**
* token store
*
* @param accessTokenConverter
* @return
*/
// @Bean
// public TokenStore tokenStore() {
// TokenStore tokenStore = new JwtTokenStore(accessTokenConverter());
// return tokenStore;
// }
}
| [
"382074290@qq.com"
] | 382074290@qq.com |
c03cc6684b7c5dd7d224f9a70c504574f9d6f9b2 | 9f204342f63c82b26908792c84144d80c67911cc | /src/org/enhydra/shark/partmappersistence/data/XPDLParticipantProcessQuery.java | 608c3da77a110f447c3600ec9c2e276286954e93 | [] | no_license | kinnara-digital-studio/shark | eaada7bbb4ba976e1c876defdcab9d5ee15b81eb | 7abf690837152da11ddda360ad2436ec68c7bdb4 | refs/heads/master | 2023-03-16T07:27:02.867938 | 2013-05-05T13:12:25 | 2013-05-05T13:12:25 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 78,547 | java |
/*-----------------------------------------------------------------------------
* Enhydra Java Application Server
* Copyright 1997-2000 Lutris Technologies, Inc.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the distribution.
* 3. All advertising materials mentioning features or use of this software
* must display the following acknowledgement:
* This product includes Enhydra software developed by Lutris
* Technologies, Inc. and its contributors.
* 4. Neither the name of Lutris Technologies nor the names of its contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY LUTRIS TECHNOLOGIES AND CONTRIBUTORS ``AS IS''
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL LUTRIS TECHNOLOGIES OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*-----------------------------------------------------------------------------
* org.enhydra.shark.partmappersistence.data/XPDLParticipantProcessQuery.java
*-----------------------------------------------------------------------------
*/
package org.enhydra.shark.partmappersistence.data;
import org.enhydra.dods.DODS;
import com.lutris.dods.builder.generator.query.*;
import com.lutris.appserver.server.sql.*;
//import org.enhydra.dods.cache.LRUCache;
import org.enhydra.dods.cache.DataStructCache;
import org.enhydra.dods.cache.QueryCache;
import org.enhydra.dods.cache.QueryCacheItem;
import org.enhydra.dods.cache.QueryResult;
import org.enhydra.dods.cache.DataStructShell;
import org.enhydra.dods.cache.DOShell;
import org.enhydra.dods.cache.Condition;
import org.enhydra.dods.statistics.Statistics;
import org.enhydra.dods.cache.CacheConstants;
import org.enhydra.dods.statistics.*;
import com.lutris.logging.LogChannel;
import com.lutris.logging.Logger;
import com.lutris.appserver.server.sql.CachedDBTransaction;
//import org.enhydra.dods.util.LRUMap;
import java.sql.*;
import java.util.*;
import java.math.*;
import java.util.Date; // when I say Date, I don't mean java.sql.Date
// WebDocWf extension for DODS row instance based security
// The following line has been added
import org.webdocwf.dods.access.*;
// end of WebDocWf extension for DODS row instance based security
/**
* XPDLParticipantProcessQuery is used to query the XPDLParticipantProcess table in the database.<BR>
* It returns objects of type XPDLParticipantProcessDO.
* <P>
* General usage:
* <P>
* In DODS:
* Create a Data Object named "Dog",
* and create an Attribute named "Name",
* and set that Attribute to "Can be queried."
* DODS will then generate the method DogQuery.setQueryName().
* <P>
* In your Business Layer, prepare the query:<BR>
* <P><PRE>
* DogQuery dq = new DogQuery();
* dq.setQueryName("Rex")
* if ( Rex is a reserved name )
* dq.requireUniqueInstance();
* </PRE>
* Then, get the query results one of two ways:
* <P>
* #1:<PRE>
* String names = "";
* DogDO[] dogs = dq.getDOArray();
* for ( int i = 0; i < dogs.length; i++ ) {
* names += dogs[i].getName() + " ";
* }
* </PRE>
* or #2:<PRE>
* String names = "";
* DogDO dog;
* while ( null != ( dog = dq.getNextDO() ) ) {
* names += dog.getName() + " ";
* }
* </PRE>
* <P>
* Note: If <CODE>requireUniqueInstance()</CODE> was called,
* then <CODE>getDOArray()</CODE> or <CODE>getNextDO()</CODE>
* will throw an exception if more than one "Rex" was found.
* <P>
* Note: Results of the query will come from the Data Object cache if:
* - The cache is available.
* - Matches were found in the cache.
* - No other tables (Data Objects of other types) were involved
* in the query.
* This can happen if you extend the <CODE>DogQuery</CODE> class
* and you make calls to the <CODE>QueryBuilder</CODE> object
* to add SQL involving other tables.
* If any of these conditions is not true,
* then any results from the query will come from the database.
* <P>
* To reuse the query object, call:
* <P><PRE>
* dq.reset();
* </PRE>
* @author NN
* @version $Revision: 1.13 $
*/
public class XPDLParticipantProcessQuery implements ExtendedQuery {
private QueryBuilder builder;
/**
* logical name of the database for which XPDLParticipantProcessQuery object has been created
*/
private String logicalDatabase;
private ResultSet resultSet = null;
private boolean uniqueInstance = false;
private boolean loadData = false;
private XPDLParticipantProcessDO[] DOs = null;
private int arrayIndex = -1;
private boolean needToRun = true;
// 12.04.2004 tj
// private LRUMap cacheHits = null;
private Vector cacheHits = null;
private boolean isQueryByOId = false;
private boolean hasNonOidCond = false;
private boolean hitDb = false;
private boolean userHitDb = false;
private int maxDBrows = 0;
private boolean orderRelevant = true; // true if order of query results is relavant, otherwise false
private QueryCacheItem queryItem = null;
private String currentHandle = null;
private HashMap refs = new HashMap();
private int iCurrentFetchSize = -1;
private int iCurrentQueryTimeout = 0;
DBTransaction transaction = null;
private int queryTimeLimit = 0;
/**
* Public constructor.
*
* @param dbTrans current database transaction
*/
public XPDLParticipantProcessQuery(DBTransaction dbTrans) {
builder = new QueryBuilder( "XPDLParticipantProcess", XPDLParticipantProcessDO.columnsNameString );
Integer tmpInt = XPDLParticipantProcessDO.getConfigurationAdministration().
getTableConfiguration().getQueryTimeLimit();
if(tmpInt!=null) {
queryTimeLimit = tmpInt.intValue();
}else {
queryTimeLimit = 0;
}
String dbName = null;
if(dbTrans!=null)
dbName = dbTrans.getDatabaseName();
else
dbName = XPDLParticipantProcessDO.get_logicalDBName();
try {
transaction = dbTrans;
String vendor = DODS.getDatabaseManager().logicalDatabaseType(dbName);
if (vendor != null) {
builder.setDatabaseVendor(vendor);
logicalDatabase = dbName;
} else {
builder.setDatabaseVendor();
logicalDatabase = DODS.getDatabaseManager().getDefaultDB();
}
} catch (Exception e) {
builder.setDatabaseVendor();
logicalDatabase = DODS.getDatabaseManager().getDefaultDB();
}
builder.setUserStringAppendWildcard( false );
builder.setUserStringTrim( false );
reset();
}
/**
* Return logical name of the database that XPDLParticipantProcessQuery object uses
*
* @return param logical database name
*
*/
public String getLogicalDatabase() {
return logicalDatabase;
}
/**
* Return java.sql.PreparedStatement from QueryBuilder class
*
* @return PreparedStatement from this query object.
*
*/
public PreparedStatement getStatement(){
return builder.getStatement();
}
/**
* Change logical database to another logical database (which name is dbName)
*
* @param dbName the logical name of the database
* @exception SQLException
* @exception DatabaseManagerException
*/
public void setLogicalDatabase(String dbName) throws SQLException, DatabaseManagerException {
String vendor = DODS.getDatabaseManager().logicalDatabaseType(dbName);
if (vendor != null) {
builder.setDatabaseVendor(vendor);
logicalDatabase = dbName;
} else {
builder.setDatabaseVendor();
logicalDatabase = DODS.getDatabaseManager().getDefaultDB();
}
reset();
}
// WebDocWf extension for unique query results without SQL DISTINCT
// The following lines has been added:
private boolean unique = false;
/**
* Set the unique flag of the query
*
* @param newUnique The unique flag for the query
*
* WebDocWf extension
*
*/
public void setUnique(boolean newUnique) { unique = newUnique; }
/**
* Get the unique flag of the query
*
* @return The unique flag of the query
*
* WebDocWf extension
*
*/
public boolean getUnique() { return unique; }
// WebDocWf extension for skipping the n first rows of the result
// The following lines has been added:
private int readSkip = 0;
/**
* Set the readSkip number of the query
*
* @param newReadSkip The number of results to skip.
*
* WebDocWf extension
*
*/
public void setReadSkip(int newReadSkip) {
readSkip = newReadSkip;
}
/**
* Get the readSkip number of the query
*
* @return The number of rows which are skipped
*
* WebDocWf extension
*
*/
public int getReadSkip() { return readSkip; }
// WebDocWf extension for select rowcount limit
// The following lines has been added:
private int databaseLimit = 0;
/**
* Set the database limit of the query
*
* @param newLimit The limit for the query
*
* WebDocWf extension
*
*/
public void setDatabaseLimit(int newLimit) {
databaseLimit = newLimit;
}
/**
* Get the database limit of the query
*
* @return The database limit of the query
*
* WebDocWf extension
*
*/
public int getDatabaseLimit() { return databaseLimit; }
private boolean databaseLimitExceeded = false;
/**
* Get the database limit exceeded flag of the query.
*
* @return The database limit exceeded flag of the query
* True if there would have been more rows than the limit, otherwise false.
*
* WebDocWf extension
*/
public boolean getDatabaseLimitExceeded() { return databaseLimitExceeded; }
// end of WebDocWf extension for select rowcount limit
/**
* Set that all queries go to database, not to cache.
*/
public void hitDatabase() { userHitDb = true; }
// WebDocWf extension for extended wildcard support
// The following rows have been added:
/**
* Set user string wildcard.
*
* @param newUserStringWildcard New user string wildcard.
*
* WebDocWf extension
*/
public void setUserStringWildcard(String newUserStringWildcard) {
builder.setUserStringWildcard( newUserStringWildcard );
}
/**
* Set user string single wildcard.
*
* @param newUserStringSingleWildcard New user string single wildcard.
*
* WebDocWf extension
*/
public void setUserStringSingleWildcard(String newUserStringSingleWildcard) {
builder.setUserStringSingleWildcard( newUserStringSingleWildcard );
}
/**
* Set user string single wildcard escape.
*
* @param newUserStringSingleWildcardEscape New user string single wildcard escape.
*
* WebDocWf extension
*/
public void setUserStringSingleWildcardEscape(String newUserStringSingleWildcardEscape) {
builder.setUserStringSingleWildcardEscape( newUserStringSingleWildcardEscape );
}
/**
* Set user string wildcard escape.
*
* @param newUserStringWildcardEscape New user string wildcard escape.
*
* WebDocWf extension
*/
public void setUserStringWildcardEscape(String newUserStringWildcardEscape) {
builder.setUserStringWildcardEscape( newUserStringWildcardEscape );
}
/**
* Set user string append wildcard.
*
* @param userStringAppendWildcard New user string append wildcard.
*
* WebDocWf extension
*/
public void setUserStringAppendWildcard(boolean userStringAppendWildcard ) {
builder.setUserStringAppendWildcard( userStringAppendWildcard );
}
/**
* Set user string trim.
*
* @param userStringTrim New user string trim.
*
* WebDocWf extension
*/
public void setUserStringTrim(boolean userStringTrim ) {
builder.setUserStringTrim( userStringTrim );
}
/**
* Get user string wildcard.
*
* @return User string wildcard.
*
* WebDocWf extension
*/
public String getUserStringWildcard() {
return builder.getUserStringWildcard();
}
/**
* Get user string single wildcard.
*
* @return User string single wildcard.
*
* WebDocWf extension
*/
public String getUserStringSingleWildcard() {
return builder.getUserStringSingleWildcard();
}
/**
* Get user string single wildcard escape.
*
* @return User string single wildcard escape.
*
* WebDocWf extension
*/
public String getUserStringSingleWildcardEscape() {
return builder.getUserStringSingleWildcardEscape();
}
/**
* Get user string wildcard escape.
*
* @return User string wildcard escape.
*
* WebDocWf extension
*/
public String getUserStringWildcardEscape() {
return builder.getUserStringWildcardEscape();
}
/**
* Get user string append wildcard.
*
* @return User string append wildcard.
*
* WebDocWf extension
*/
public boolean getUserStringAppendWildcard() {
return builder.getUserStringAppendWildcard();
}
/**
* Get user string trim.
*
* @return User string trim.
*
* WebDocWf extension
*/
public boolean getUserStringTrim() {
return builder.getUserStringTrim();
}
// end of WebDocWf extension for extended wildcard support
/**
* Perform the query on the database, and prepare the array of returned
* DO objects.
*
* @param DOs Vector of result oids which will be switched with the whole DOs
* (from the database).
* @exception DataObjectException If a database access error occurs.
* @exception NonUniqueQueryException If too many rows were found.
*/
private void getQueryByOIds(Vector DOs, Date mainQueryStartTime) throws DataObjectException {
if (DOs.size() == 0)
return;
XPDLParticipantProcessDO DO = null;
DOShell shell = null;
XPDLParticipantProcessQuery tmpQuery = null;
Date startQueryTime = new Date();
long queryTime = 0;
boolean queryTimeLimitError = false;
for (int i=0; i<DOs.size(); i++) {
shell = (DOShell)DOs.elementAt(i);
tmpQuery = new XPDLParticipantProcessQuery(transaction);
try {
tmpQuery.setQueryHandle( shell.handle );
tmpQuery.requireUniqueInstance();
DO = tmpQuery.getNextDO();
Date currentQueryTime = new Date();
long passedQueryTime = currentQueryTime.getTime()- mainQueryStartTime.getTime();
if ((queryTimeLimit > 0) && (passedQueryTime > queryTimeLimit)) {
DODS.getLogChannel().write(Logger.WARNING,"Froced QueryByOIds Query interrupt,"
+" query time limit exceeded (errID=30).");
DODS.getLogChannel().write(Logger.DEBUG,"Froced QueryByOIds Query interrupt,"
+" query time limit exceeded (errID=30)("
+" QueryTimeLimit = "+queryTimeLimit
+" : PassedQueryTime = "+passedQueryTime
+" ) SQL = "
+ tmpQuery.getQueryBuilder().getSQLwithParms());
queryTimeLimitError = true;
throw new SQLException("Froced query interrupt in QueryByOIds (errID=30).");
}
if ( null == DO ){
throw new DataObjectException("XPDLParticipantProcessDO DO not found for id=" + shell.handle );
}
} catch ( Exception e ) {
if(queryTimeLimitError) {
throw new DataObjectException(e.getMessage());
} else {
throw new DataObjectException("Duplicate ObjectId");
}
}
shell.dataObject = DO;
}
Date stopQueryTime = new Date();
queryTime = stopQueryTime.getTime() - startQueryTime.getTime();
XPDLParticipantProcessDO.statistics.updateQueryByOIdAverageTime((new Long(queryTime)).intValue(),DOs.size());
}
/**
* Perform the query on the database, and prepare the
* array of returned DO objects.
*
* @exception DataObjectException If a database access error occurs.
* @exception NonUniqueQueryException If too many rows were found.
*/
private void runQuery()
throws DataObjectException, NonUniqueQueryException {
needToRun = false;
arrayIndex = -1;
DBQuery dbQuery = null;
Date startQueryTime = new Date();
long queryTime = 0;
boolean readDOs = false;
boolean canUseQueryCache = true;
CacheStatistics stat = null;
boolean resultsFromQCache = false;
QueryCacheItem queryCachedItem = null;
if(builder.isUnionTableJoin())throw new DataObjectException( "Could not use 'UNION [ALL]' statement in query witch retrieve data object." );
if ((transaction!=null) &&
(transaction instanceof com.lutris.appserver.server.sql.CachedDBTransaction)) {
if(((com.lutris.appserver.server.sql.CachedDBTransaction)transaction).getAutoWrite()) try {
transaction.write();
} catch (SQLException sqle) {
sqle.printStackTrace();
throw new DataObjectException("Couldn't write transaction: "+sqle);
}
((com.lutris.appserver.server.sql.CachedDBTransaction)transaction).dontAggregateDOModifications();
}
try {
QueryResult results = null;
DOShell shell = null;
if (isQueryByOId && !hasNonOidCond) { // query by OId
builder.setCurrentFetchSize(1);
results = new QueryResult();
if (currentHandle != null) {
if(transaction!=null && _tr_(transaction).getTransactionCache()!=null && !loadData) {
XPDLParticipantProcessDO DO= (XPDLParticipantProcessDO)_tr_(transaction).getTransactionCache().getDOByHandle(currentHandle);
if(DO!=null){
shell = new DOShell(DO);
results.DOs.add(shell);
resultsFromQCache = true;
}
// tj 12.04.2004 put under comment next 2 lines
// else
// resultsFromQCache = false;
}
if(!resultsFromQCache) { // DO isn't found in the transaction cache
XPDLParticipantProcessDataStruct DS = (XPDLParticipantProcessDataStruct)XPDLParticipantProcessDO.cache.getDataStructByHandle(currentHandle);
if (DS != null && !(DS.isEmpty && loadData)) { // DO is found in the cache
XPDLParticipantProcessDO DO = (XPDLParticipantProcessDO)XPDLParticipantProcessDO.ceInternal(DS.get_OId(), transaction);
shell = new DOShell(DO);
results.DOs.add(shell);
resultsFromQCache = true;
}
// tj 12.04.2004 put under comment next 4 lines
// else{ // DO isn't found in the cache
// if (XPDLParticipantProcessDO.cache.isFull())
// resultsFromQCache = false;
// }
}
}//currentHandle != null
}
else { // other queries
if ( XPDLParticipantProcessDO.cache.isFull() && (XPDLParticipantProcessDO.isFullCacheNeeded)
&&(!hitDb) && (maxDBrows == 0) && (databaseLimit == 0)
&& (readSkip == 0) && !builder.isMultiTableJoin() ) {
resultsFromQCache = true;
}
else {
if (XPDLParticipantProcessDO.cache.getLevelOfCaching() == CacheConstants.QUERY_CACHING) {
if (builder.isMultiTableJoin()) { // statistics about multi join query
stat = null;
stat = XPDLParticipantProcessDO.statistics.getCacheStatistics(CacheConstants.MULTI_JOIN_QUERY_CACHE);
if (stat!= null){
stat.incrementCacheAccessNum(1);
}
}
else {
if (hitDb) { // statistics about complex query
stat = null;
stat = XPDLParticipantProcessDO.statistics.getCacheStatistics(CacheConstants.COMPLEX_QUERY_CACHE);
if (stat!= null){
stat.incrementCacheAccessNum(1);
}
}else{ // statistics about simple query
stat = null;
stat = XPDLParticipantProcessDO.statistics.getCacheStatistics(CacheConstants.SIMPLE_QUERY_CACHE);
if (stat!= null){
stat.incrementCacheAccessNum(1);
}
}
}
}
if(transaction != null)
canUseQueryCache = !transaction.preventCacheQueries();
if ((XPDLParticipantProcessDO.cache.getLevelOfCaching() == CacheConstants.QUERY_CACHING) && canUseQueryCache) {
String queryID = builder.getSQLwithParms(); //unique representation of query
int resNum = 0;
int evaluateNo = 0;
if (builder.isMultiTableJoin()) {
queryCachedItem = ((QueryCache)XPDLParticipantProcessDO.cache).getMultiJoinQueryCacheItem(logicalDatabase, queryID);
}
else{
if (hitDb)
queryCachedItem = ((QueryCache)XPDLParticipantProcessDO.cache).getComplexQueryCacheItem(logicalDatabase, queryID);
else
queryCachedItem = ((QueryCache)XPDLParticipantProcessDO.cache).getSimpleQueryCacheItem(logicalDatabase, queryID);
}
queryItem.setQueryId(queryID); // queryItem defined as private template attribute
if (queryCachedItem == null) { // query doesn't exist
// tj 03.09.2004 if ((!builder.isMultiTableJoin()) || XPDLParticipantProcessDO.isAllReadOnly())
if (builder.isMultiTableJoin()){
((QueryCache)XPDLParticipantProcessDO.cache).addMultiJoinQuery(queryItem); // register multi join query
}
else {
if (hitDb)
((QueryCache)XPDLParticipantProcessDO.cache).addComplexQuery(queryItem); // register complex query
else
((QueryCache)XPDLParticipantProcessDO.cache).addSimpleQuery(queryItem); // register simple query
}
}
else{ // query found
if ( !(isOrderRelevant() && queryCachedItem.isModifiedQuery()) ) {
if (builder.isMultiTableJoin()){ // statistics about multi join cache
stat = null;
stat = XPDLParticipantProcessDO.statistics.getCacheStatistics(CacheConstants.MULTI_JOIN_QUERY_CACHE);
if (stat!= null){
stat.incrementCacheHitsNum(1);
}
}
else {
if (hitDb) { // statistics about complex cache
stat = null;
stat = XPDLParticipantProcessDO.statistics.getCacheStatistics(CacheConstants.COMPLEX_QUERY_CACHE);
if (stat!= null){
stat.incrementCacheHitsNum(1);
}
}else{ // statistics about simple cache
stat = null;
stat = XPDLParticipantProcessDO.statistics.getCacheStatistics(CacheConstants.SIMPLE_QUERY_CACHE);
if (stat!= null){
stat.incrementCacheHitsNum(1);
}
}
}
int limitOfRes;
if (databaseLimit == 0)
limitOfRes = 0;
else
limitOfRes = readSkip+databaseLimit+1;
if (! unique) {
if (builder.isMultiTableJoin()) {
results = ((QueryCache)XPDLParticipantProcessDO.cache).getMultiJoinQueryResults(logicalDatabase, queryID, limitOfRes, maxDBrows);
}
else {
if (hitDb)
results = ((QueryCache)XPDLParticipantProcessDO.cache).getComplexQueryResults(logicalDatabase, queryID, limitOfRes, maxDBrows);
else
results = ((QueryCache)XPDLParticipantProcessDO.cache).getSimpleQueryResults(logicalDatabase, queryID, limitOfRes, maxDBrows);
}
}else{ // (! unique)
if (builder.isMultiTableJoin()) {
results = ((QueryCache)XPDLParticipantProcessDO.cache).getMultiJoinQueryResults(logicalDatabase, queryID, limitOfRes, maxDBrows, true);
}
else {
if (hitDb)
results = ((QueryCache)XPDLParticipantProcessDO.cache).getComplexQueryResults(logicalDatabase, queryID, limitOfRes, maxDBrows, true);
else
results = ((QueryCache)XPDLParticipantProcessDO.cache).getSimpleQueryResults(logicalDatabase, queryID, limitOfRes, maxDBrows, true);
}
} // (! unique)
if (results != null) {
resNum = results.DOs.size();
// tj 01.02.2004 remove skipped
if (readSkip > 0) {
if (results.DOs.size() > readSkip) {
for (int i = 0; i < readSkip; i++) {
results.DOs.remove(0);
}
}
else {
results.DOs.clear();
}
}
//sinisa 06.08.2003.
results = getCachedResults(results);
if (databaseLimit != 0) { // databaseLimitExceeded begin
if (resNum == readSkip+databaseLimit+1) {
resNum--;
databaseLimitExceeded = true;
results.DOs.remove(databaseLimit);
}else{
if ( (resNum == readSkip+databaseLimit) && (!queryCachedItem.isCompleteResult()) )
databaseLimitExceeded = true;
}
} // databaseLimitExceeded end
if ( (databaseLimit!=0 &&(resNum == (readSkip+databaseLimit))) || (maxDBrows!=0 && (resNum + results.skippedUnique) == maxDBrows) || (queryCachedItem.isCompleteResult()) ) {
int lazyTime = XPDLParticipantProcessDO.statistics.getQueryByOIdAverageTime()*results.lazy.size();
if (lazyTime <= queryCachedItem.getTime()) {
resultsFromQCache = true;
getQueryByOIds(results.lazy,startQueryTime); // gets cached query results from database
}else
databaseLimitExceeded = false;
}else
databaseLimitExceeded = false;
//remove skiped
} // (results != null)
} // !(isOrderRelevant() && queryCachedItem.isModifiedQuery())
} // query found
} // if QUERY_CACHING
} // full caching
} // other queries
if (( userHitDb) || (!resultsFromQCache)) { // go to database
dbQuery = XPDLParticipantProcessDO.createQuery(transaction);
if(uniqueInstance)
builder.setCurrentFetchSize(1);
results = new QueryResult();
int resultCount=0;
boolean bHasMoreResults = false;
if (( (XPDLParticipantProcessDO.getConfigurationAdministration().getTableConfiguration().isLazyLoading()) || isCaching()) && (!builder.getPreventPrimaryKeySelect()) && !loadData) {
builder.resetSelectedFields();
builder.setSelectClause("XPDLParticipantProcess."+XPDLParticipantProcessDO.get_OIdColumnName()+", XPDLParticipantProcess."+XPDLParticipantProcessDO.get_versionColumnName());
}
else
builder.setSelectClause(XPDLParticipantProcessDO.columnsNameString);
dbQuery.query( this ); // invokes executeQuery
if (! unique) {
int iteration = 0;
try {
while ( (bHasMoreResults = resultSet.next()) && (databaseLimit==0 || (results.DOs.size()<databaseLimit)) ) {
XPDLParticipantProcessDO newDO;
XPDLParticipantProcessDataStruct newDS;
Date currentQueryTime = new Date();
long passedQueryTime = currentQueryTime.getTime()-startQueryTime.getTime();
if ( (queryTimeLimit > 0)&&
(passedQueryTime > queryTimeLimit)){
DODS.getLogChannel().write(Logger.WARNING,"Froced query interrupt,"+
" query time limit exceeded (errID=10).");
DODS.getLogChannel().write(Logger.DEBUG,"Froced query interrupt,"+
" query time limit exceeded (errID=10)(" +
" QueryTimeLimit = "+queryTimeLimit+
" : PassedQueryTime = "+passedQueryTime+
" ) SQL = " + builder.getSQLwithParms());
throw new SQLException("Froced query interrupt (errID=10).");
}
if (( (XPDLParticipantProcessDO.getConfigurationAdministration().getTableConfiguration().isLazyLoading()) || isCaching()) && (!builder.getPreventPrimaryKeySelect()) && !loadData) {
newDO = XPDLParticipantProcessDO.ceInternal ( new ObjectId(resultSet.getBigDecimal(CoreDO.get_OIdColumnName())) , refs, transaction);
newDO.set_Version(resultSet.getInt(XPDLParticipantProcessDO.get_versionColumnName()));
} else
newDO = XPDLParticipantProcessDO.ceInternal ( resultSet , refs, transaction);
if(transaction==null) {
if(newDO!=null && newDO.isTransactionCheck()) {
DODS.getLogChannel().write(Logger.WARNING, "DO without transaction context is created : Database: "+newDO.get_OriginDatabase()+" XPDLParticipantProcessDO class, oid: "+newDO.get_Handle()+", version: "+newDO.get_Version()+" \n");
(new Throwable()).printStackTrace(DODS.getLogChannel().getLogWriter(Logger.WARNING));
}
}
if (queryItem != null) {
queryItem.add((XPDLParticipantProcessDataStruct)newDO.originalData_get());
}
if (( (XPDLParticipantProcessDO.getConfigurationAdministration().getTableConfiguration().isLazyLoading()) || isCaching()) && (!builder.getPreventPrimaryKeySelect()) && !loadData)
{}
else
newDS =XPDLParticipantProcessDO.addToCache((XPDLParticipantProcessDataStruct)newDO.originalData_get());
if (resultCount >= readSkip) {
shell = new DOShell(newDO);
results.DOs.add(shell);
}
resultCount++;
iteration++;
} // while
}catch (SQLException e) {
DODS.getLogChannel().write(
Logger.ERROR,
"(SQLError):(ReadingResultSet):(errID=50):("+e.getMessage()+")");
DODS.getLogChannel().write(
Logger.DEBUG,
"(SQLError):(ReadingResultSet):(errID=50):(element-at:"+iteration+") sql = "+ builder.getSQLwithParms());
throw e;
}
} // (!unique)
else { // (! unique)
int iteration = 0;
HashSet hsResult = new HashSet(readSkip+databaseLimit);
try {
while((bHasMoreResults = resultSet.next()) && (databaseLimit==0 || (results.DOs.size()<databaseLimit)) ) {
XPDLParticipantProcessDO newDO;
XPDLParticipantProcessDataStruct newDS;
Date currentQueryTime = new Date();
long passedQueryTime = currentQueryTime.getTime()-startQueryTime.getTime();
if ( (queryTimeLimit > 0)&&
(passedQueryTime > queryTimeLimit)){
DODS.getLogChannel().write(Logger.WARNING,"Froced query interrupt,"+
" query time limit exceeded (errID=20).");
DODS.getLogChannel().write(Logger.DEBUG,"Froced query interrupt,"+
" query time limit exceeded (errID=20)(" +
" QueryTimeLimit = "+queryTimeLimit+
" : PassedQueryTime = "+passedQueryTime+
" ) SQL = " + builder.getSQLwithParms());
throw new SQLException("Froced query interrupt (errID=20).");
}
if (( (XPDLParticipantProcessDO.getConfigurationAdministration().getTableConfiguration().isLazyLoading()) || isCaching()) && (!builder.getPreventPrimaryKeySelect()) && !loadData) {
newDO = XPDLParticipantProcessDO.ceInternal ( new ObjectId(resultSet.getBigDecimal(CoreDO.get_OIdColumnName())) , refs, transaction);
newDO.set_Version(resultSet.getInt(XPDLParticipantProcessDO.get_versionColumnName()));
} else
newDO = XPDLParticipantProcessDO.ceInternal ( resultSet , refs , transaction);
if(transaction==null) {
if(newDO!=null && newDO.isTransactionCheck()) {
DODS.getLogChannel().write(Logger.WARNING, "DO without transaction context is created : Database: "+newDO.get_OriginDatabase()+" XPDLParticipantProcessDO class, oid: "+newDO.get_Handle()+", version: "+newDO.get_Version()+" \n");
(new Throwable()).printStackTrace(DODS.getLogChannel().getLogWriter(Logger.WARNING));
}
}
if (queryItem != null) {
queryItem.add((XPDLParticipantProcessDataStruct)newDO.originalData_get());
}
if (( (XPDLParticipantProcessDO.getConfigurationAdministration().getTableConfiguration().isLazyLoading()) || isCaching()) && (!builder.getPreventPrimaryKeySelect()) && !loadData)
{
} else
newDS = XPDLParticipantProcessDO.addToCache((XPDLParticipantProcessDataStruct)newDO.originalData_get());
if (!hsResult.contains(newDO.get_Handle())) {
hsResult.add(newDO.get_Handle());
if (resultCount >= readSkip) {
shell = new DOShell(newDO);
results.DOs.add(shell);
}
resultCount++;
}
iteration++;
} // while
}catch (SQLException e) {
DODS.getLogChannel().write(
Logger.ERROR,
"(SQLError):(ReadingResultSet):(errID=40)("+e.getMessage()+")");
DODS.getLogChannel().write(
Logger.DEBUG,
"(SQLError):(ReadingResultSet):(errID=40):(element-at:"+iteration+") sql = "+ builder.getSQLwithParms());
throw e;
}
} // else (! unique)
if ((results.DOs.size()==databaseLimit)&& bHasMoreResults) {
resultSet.close();
databaseLimitExceeded = true;
}
if (maxDBrows > 0) {
if (!bHasMoreResults) {
if ((databaseLimit > 0) && databaseLimit < maxDBrows )
queryItem.setCompleteResult(true);
}
}
else {
if (!bHasMoreResults)
queryItem.setCompleteResult(true);
}
Date stopQueryTime = new Date();
queryTime = stopQueryTime.getTime() - startQueryTime.getTime();
if (queryItem != null) {
queryItem.setTime((new Long(queryTime)).intValue());
if (queryCachedItem != null) {
if ( queryItem.isCompleteResult() || (queryCachedItem.isModifiedQuery() && isOrderRelevant()) || (queryCachedItem.getResultNum() < queryItem.getResultNum()) ) {
// tj 03.09.2004 if ((!builder.isMultiTableJoin()) || XPDLParticipantProcessDO.isAllReadOnly() )
if (builder.isMultiTableJoin()){
((QueryCache)XPDLParticipantProcessDO.cache).addMultiJoinQuery(queryItem);
}
else {
if (hitDb) {
((QueryCache)XPDLParticipantProcessDO.cache).addComplexQuery(queryItem);
}
else {
((QueryCache)XPDLParticipantProcessDO.cache).addSimpleQuery(queryItem);
}
} // else from if (builder.isMultiTableJoin())
}
else {
if ( (queryCachedItem.getResultNum() < (readSkip + databaseLimit) ) && (queryCachedItem.getResultNum() < maxDBrows) ) {
queryCachedItem.setCompleteResult(true);
}
}
if ( (queryItem.getResultNum() < (readSkip + databaseLimit) ) && (queryItem.getResultNum() < maxDBrows) )
queryItem.setCompleteResult(true);
} // (queryCachedItem != null)
} // (queryItem != null)
int maxExecuteTime = XPDLParticipantProcessDO.cache.getTableConfiguration().getMaxExecuteTime();
if (maxExecuteTime > 0 && queryTime > maxExecuteTime)
DODS.getLogChannel().write(Logger.WARNING, "sql = " + builder.getSQLwithParms()+" execute time = "+queryTime + "max table execute time = "+maxExecuteTime);
}
else { // ( userHitDb) || (!resultsFromQCache)
if ( XPDLParticipantProcessDO.cache.isFull() && (XPDLParticipantProcessDO.isFullCacheNeeded)
&& (!hitDb) && (maxDBrows == 0) && (databaseLimit == 0)
&& (readSkip == 0) && !builder.isMultiTableJoin()) {
results = new QueryResult();
if (readSkip<cacheHits.size()) {
// 12.04.2004 tj Vector vect = new Vector(cacheHits.values());
results.DOs = new Vector();
XPDLParticipantProcessDO DO = null;
XPDLParticipantProcessDataStruct DS = null;
String cachePrefix = getLogicalDatabase()+".";
int i = 0;
int resNumber = 0;
Vector uniqueResults = new Vector();
while (i < cacheHits.size() ) { // && ((databaseLimit==0) || (results.DOs.size()<=databaseLimit))
// && ((maxDBrows==0) || (i < maxDBrows))
boolean findInTransactionCache = false;
DS = (XPDLParticipantProcessDataStruct)cacheHits.get(i);
if(transaction!=null && _tr_(transaction).getTransactionCache()!=null && !loadData) {
DO = (XPDLParticipantProcessDO)_tr_(transaction).getTransactionCache().getDOByHandle(cachePrefix+DS.get_Handle());
if(DO != null)
findInTransactionCache = true;
}
if(!findInTransactionCache){
DO = (XPDLParticipantProcessDO)XPDLParticipantProcessDO.ceInternal(DS.get_OId(), transaction);
}
if (unique) {
if (!uniqueResults.contains(cachePrefix+DS.get_Handle())) {
uniqueResults.add(cachePrefix+DS.get_Handle());
//if (resNumber >= readSkip ){
results.DOs.add(DO);
//}
resNumber++;
}
}
else {
//if (resNumber >= readSkip ){
results.DOs.add(DO);
//}
resNumber++;
}
i++;
}
readDOs = true;
}
/* if ((databaseLimit != 0) && (results.DOs.size() == databaseLimit+1)) {
databaseLimitExceeded = true;
results.DOs.remove(databaseLimit);
}
*/
} //if full
} // ( userHitDb) || (!resultsFromQCache)
// end of WebDocWf extension
if (results != null) { // tj 01.02.2004
if ( results.DOs.size() > 1 && uniqueInstance )
throw new NonUniqueQueryException("Too many rows returned from database" );
DOs = new XPDLParticipantProcessDO [ results.DOs.size() ];
XPDLParticipantProcessDataStruct orig;
if (readDOs) {
for ( int i = 0; i < results.DOs.size(); i++ ) {
DOs[i] = (XPDLParticipantProcessDO)results.DOs.elementAt(i);
}
}
else {
for ( int i = 0; i < results.DOs.size(); i++ ) {
DOs[i] = (XPDLParticipantProcessDO)((DOShell)results.DOs.elementAt(i)).dataObject;
}
}
arrayIndex = 0;
}
else {
DOs = new XPDLParticipantProcessDO [0];
}
if (isQueryByOId && !hasNonOidCond) {
XPDLParticipantProcessDO.statistics.incrementQueryByOIdNum();
XPDLParticipantProcessDO.statistics.updateQueryByOIdAverageTime((new Long(queryTime)).intValue(),1);
}
else {
XPDLParticipantProcessDO.statistics.incrementQueryNum();
XPDLParticipantProcessDO.statistics.updateQueryAverageTime((new Long(queryTime)).intValue());
}
} catch ( SQLException se ) {
if (null == se.getSQLState() ) {
throw new DataObjectException("Unknown SQLException", se );
}
if ( se.getSQLState().startsWith("02") && se.getErrorCode() == 100 ) {
throw new DataObjectException("Update or delete DO is out of synch", se );
} else if ( se.getSQLState().equals("S1000") && se.getErrorCode() == -268) {
throw new DataObjectException("Integrity constraint violation", se );
} else {
throw new DataObjectException( "Data Object Error", se );
}
} catch ( ObjectIdException oe ) {
throw new DataObjectException( "Object ID Error", oe );
} catch ( DatabaseManagerException de ) {
throw new DataObjectException( "Database connection Error", de );
}
finally {
if ( null != dbQuery )dbQuery.release();
}
}
/**
* Limit the number of rows (DOs) returned.
* NOTE: When setting a limit on rows returned by a query,
* you usually want to use a call to an addOrderBy method
* to cause the most interesting rows to be returned first.
* However, the DO cache does not yet support the Order By operation.
* Using the addOrderBy method forces the query to hit the database.
* So, setMaxRows also forces the query to hit the database.
*
* @param maxRows Max number of rows (DOs) returned.
*
* @exception DataObjectException If a database access error occurs.
* @exception NonUniqueQueryException If too many rows were found.
*/
public void setMaxRows( int maxRows )
throws DataObjectException, NonUniqueQueryException {
maxDBrows = maxRows;
builder.setMaxRows( maxRows );
}
/**
* Return limit of rows (DOs) returned.
* @return Max number of rows (DOs) returned.
*
*/
public int getMaxRows() {
return maxDBrows;
}
/**
* Returns attribute orderRelevant.
*
* @return true if order of query results is relavant, otherwise false.
*/
public boolean isOrderRelevant() {
return orderRelevant;
}
/**
* Sets attribute orderRelevant.
*
* @param newOrderRelevant new value of attribute orderRelavant.
*/
public void setOrderRelevant(boolean newOrderRelevant) {
orderRelevant = newOrderRelevant;
}
/**
* Return QueryResult with read DOs or DataStructs from caches.
*
* @param result QueryResult object with result oids.
* @return QueryResult object with filled DOs or DataStructs that are found
* in the cache.
*
* @exception DataObjectException If a database access error occurs.
*/
public QueryResult getCachedResults(QueryResult result) throws DataObjectException {
Vector tempVec = result.DOs;
if (tempVec == null)
return null;
result.DOs = new Vector();
result.lazy = new Vector();
DOShell shell = null;
XPDLParticipantProcessDO cacheDO = null;
XPDLParticipantProcessDataStruct cacheDS = null;
String handle = "";
String cachePrefix=getLogicalDatabase()+".";
for(int i=0; i < tempVec.size(); i++) {
if(tempVec.get(i)!=null) {
cacheDO = null;
cacheDS = null;
handle=(String)tempVec.get(i);
shell = new DOShell(handle);
if(transaction!=null && _tr_(transaction).getTransactionCache()!=null && !loadData) {
try {
cacheDO = (XPDLParticipantProcessDO)_tr_(transaction).getTransactionCache().getDOByHandle(cachePrefix+handle);
} catch (Exception e) {
}
}
if (cacheDO == null){
cacheDS = (XPDLParticipantProcessDataStruct)XPDLParticipantProcessDO.cache.getDataStructByHandle(cachePrefix+handle);
if(cacheDS!=null) {
try {
cacheDO = (XPDLParticipantProcessDO)XPDLParticipantProcessDO.ceInternal(cacheDS.get_OId(), transaction);
} catch (Exception e) {
}
}
}
if (cacheDO == null){
result.lazy.add(shell);
}
else {
shell.dataObject = cacheDO;
}
result.DOs.add(shell);
}
} //for
return result;
}
/**
* Return array of DOs constructed from ResultSet returned by query.
*
* @return Array of DOs constructed from ResultSet returned by query.
*
* @exception DataObjectException If a database access error occurs.
* @exception NonUniqueQueryException If too many rows were found.
*/
public XPDLParticipantProcessDO[] getDOArray()
throws DataObjectException, NonUniqueQueryException {
if ( needToRun )
runQuery();
return DOs;
}
/**
* Return successive DOs from array built from ResultSet returned by query.
*
* @return DOs from array built from ResultSet returned by query.
*
* @exception DataObjectException If a database access error occurs.
* @exception NonUniqueQueryException If too many rows were found.
*/
public XPDLParticipantProcessDO getNextDO()
throws DataObjectException, NonUniqueQueryException {
if ( needToRun )
runQuery();
if ( null == DOs ) {
/* This should never happen.
* runQuery() should either throw an exception
* or create an array of DOs, possibly of zero length.
*/
return null;
}
if ( arrayIndex < DOs.length )
return DOs[ arrayIndex++ ];
return null;
}
/**
* Set the OID to query.
* WARNING! This method assumes that table <CODE>XPDLParticipantProcess</CODE>
* has a column named <CODE>"oid"</CODE>.
* This method is called from the DO classes to retrieve an object by id.
*
* @param oid The object id to query.
*/
public void setQueryOId(ObjectId oid) {
// Remove from cacheHits any DO that does not meet this
// setQuery requirement.
String handle = getLogicalDatabase()+ "." +oid.toString();
if (XPDLParticipantProcessDO.cache.isFull() && (XPDLParticipantProcessDO.isFullCacheNeeded)) {
// 12.04.2004 tj new
XPDLParticipantProcessDataStruct DS = null;
for ( int i = 0; i < cacheHits.size(); i++ ) {
DS = (XPDLParticipantProcessDataStruct)cacheHits.elementAt( i );
String cacheHandle = null;
try{
cacheHandle = DS.get_CacheHandle();
}
catch (Exception e){}
if (cacheHandle != null) {
if ( ! cacheHandle.equals( handle ) )
cacheHits.removeElementAt( i-- );
}
} // for
} // full
if (isQueryByOId) { // query by OId already has been invoked
hasNonOidCond = true; // this is not simple query by oid: has at least two conditions for oids
} else { // (isQueryByOid)
currentHandle = handle;
}
isQueryByOId = true;
try {
Condition cond = new Condition(XPDLParticipantProcessDataStruct.COLUMN_OID,handle,"=");
queryItem.addCond(cond);
}
catch (Exception e){
DODS.getLogChannel().write(Logger.DEBUG," XPDLParticipantProcessQuery class\n :"+" condition are not added");
}
// Also prepare the SQL needed to query the database
// in case there is no cache, or the query involves other tables.
builder.addWhere( XPDLParticipantProcessDO.PrimaryKey, oid.toBigDecimal(), QueryBuilder.EQUAL );
}
/**
* Set the object handle to query.
* This is a variant of setQueryOId().
*
* @param handle The string version of the id to query.
* @exception ObjectIdException
*/
public void setQueryHandle(String handle)
throws ObjectIdException {
ObjectId oid = new ObjectId( handle );
setQueryOId( oid );
}
/**
* Set "unique instance" assertion bit.
* The first call to the next() method will throw an exception
* if more than one object was found.
*/
public void requireUniqueInstance() {
uniqueInstance = true;
}
/**
* Set loadData parameter. if parameter is set to true, Query select t.* is performed.
* @param newValue boolean (true/false)
*/
public void setLoadData(boolean newValue) {
loadData = newValue;
}
/**
* Return true if Query is prepared for select t1.* statement. Otherwise return false.
* @return boolean (true/false)
*/
public boolean getLoadData() {
if(loadData)
return true;
else
return ((XPDLParticipantProcessDO.getConfigurationAdministration().getTableConfiguration().isLazyLoading()) || isCaching());
}
/**
* Reset the query parameters.
*/
public void reset() {
if(XPDLParticipantProcessDO.cache.isFull() && (XPDLParticipantProcessDO.isFullCacheNeeded)) {
if(XPDLParticipantProcessDO.cache.getTableConfiguration().getFullCacheCountLimit() > 0){
if(XPDLParticipantProcessDO.cache.getCacheAdministration(CacheConstants.DATA_CACHE).getCacheSize() > XPDLParticipantProcessDO.cache.getTableConfiguration().getFullCacheCountLimit())
XPDLParticipantProcessDO.isFullCacheNeeded = false;
}
}
if(XPDLParticipantProcessDO.cache.isFull() && (XPDLParticipantProcessDO.isFullCacheNeeded)) {
Map m = null;
synchronized (XPDLParticipantProcessDO.cache) {
m = XPDLParticipantProcessDO.cache.getCacheContent();
if(m!=null)
cacheHits = new Vector(m.values());
else
cacheHits = new Vector();
}
}
DOs = null;
uniqueInstance = false;
needToRun = true;
isQueryByOId = false;
hasNonOidCond = false;
loadData=false;
builder.reset();
if (XPDLParticipantProcessDO.cache.getLevelOfCaching() == CacheConstants.QUERY_CACHING) {
queryItem = ((QueryCache)XPDLParticipantProcessDO.cache).newQueryCacheItemInstance(logicalDatabase);
}
}
/**
* Return the appropriate QueryBuilder flag for selecting
* exact matches (SQL '=') or inexact matches (SQL 'matches').
*
* @param exact Flag that indicates whether it is exact match (SQL '=') or
* inexact matches (SQL 'matches').
* @return boolean True if it is exact match, otherwise false.
*
*/
private boolean exactFlag( boolean exact ) {
return exact ? QueryBuilder.EXACT_MATCH : QueryBuilder.NOT_EXACT;
}
//
// Implementation of Query interface
//
/**
* Method to query objects from the database.
* The following call in runQuery()
* dbQuery.query( this );
* causes the dbQuery object to invoke
* executeQuery()
*
* @param conn Handle to database connection.
*
* @return ResultSet with the results of the query.
*
* @exception java.sql.SQLException If a database access error occurs.
*/
public ResultSet executeQuery(DBConnection conn)
throws SQLException {
builder.setCurrentFetchSize(iCurrentFetchSize);
builder.setCurrentQueryTimeout(iCurrentQueryTimeout);
resultSet = builder.executeQuery( conn );
return resultSet;
}
/**
* WARNING! This method is disabled.
* It's implementation is forced by the Query interface.
* This method is disabled for 2 reasons:
* 1) the getDOArray() and getNextDO() methods are better
* because they return DOs instead of JDBC objects.
* 2) the ceInternal() method throws an exception
* that we cannot reasonably handle here,
* and that we cannot throw from here.
*
* @param rs JDBC result set from which the next object
* will be instantiated.
* @return Next result.
*
* @exception java.sql.SQLException
* If a database access error occurs.
* @exception com.lutris.appserver.server.sql.ObjectIdException
* If an invalid object id was queried from the database.
*/
public Object next(ResultSet rs)
throws SQLException, ObjectIdException {
// TODO: It would be nice to throw an unchecked exception here
// (an exception that extends RuntimeException)
// that would be guaranteed to appear during application testing.
throw new ObjectIdException("next() should not be used. Use getNextDO() instead." );
//return null;
}
// WebDocWf extension for extended wildcard support
// The following lines have been added:
/**
* Convert a String with user wildcards into a string with DB wildcards
*
* @param userSearchValue The string with user wildcards
*
* @return The string with DB wildcards
*
* WebDocWf extension
*
*/
public String convertUserSearchValue( String userSearchValue ) {
return builder.convertUserSearchValue( userSearchValue );
}
/**
* Check whether a string contains DB wildcards
*
* @param dbSearchValue The string with possible DB wildcards
*
* @return Whether a string contains DB wildcards
*
* WebDocWf extension
*
*/
public boolean containsWildcards( String dbSearchValue ) {
return builder.containsWildcards( dbSearchValue );
}
// end of WebDocWf extension for extended wildcard support
// WebDocWf extension for query row counter
// The following lines have been added:
/**
* Get the rowcount of the query
* If possible, do it without reading all rows
*
* @return The row count
* @exception NonUniqueQueryException
* @exception DataObjectException
* @exception SQLException
* @exception DatabaseManagerException
*
* WebDocWf extension
*
*/
public int getCount()
throws NonUniqueQueryException, DataObjectException, SQLException, DatabaseManagerException {
int rowCount=0;
if (needToRun && databaseLimit==0) {
rowCount = selectCount();
} else {
if (needToRun) runQuery();
rowCount = DOs.length;
}
return rowCount;
}
/**
* Set reference objects.
* @param queryRefs Reference objects.
*/
protected void setRefs(HashMap queryRefs) {
refs = queryRefs;
}
/**
* set the current cursor type - overrides default value from dbVendorConf file.
* @param resultSetType a result set type; one of ResultSet.TYPE_FORWARD_ONLY, ResultSet.TYPE_SCROLL_INSENSITIVE, or ResultSet.TYPE_SCROLL_SENSITIVE.
* @param resultSetConcurrency a concurrency type; one of ResultSet.CONCUR_READ_ONLY or ResultSet.CONCUR_UPDATABLE.
* @return the current queryTimeout;
*/
public void set_CursorType(int resultSetType, int resultSetConcurrency) {
builder.setCursorType(resultSetType,resultSetConcurrency);
}
/**
* Set fetch size for this query
* @param iCurrentFetchSizeIn Query fetch size.
*/
public void set_FetchSize (int iCurrentFetchSizeIn) {
iCurrentFetchSize = iCurrentFetchSizeIn;
}
/**
* reads the current fetchsize for this query
* @return the current fetchsize; if -1 the no fetchsize is defined, defaultFetchSize will be use if defined
*/
public int get_FetchSize() {
return (iCurrentFetchSize < 0)? builder.getDefaultFetchSize() : iCurrentFetchSize;
}
/**
* Reads the current queryTimeout for this query.
* @return the current queryTimeout;
*/
public int get_QueryTimeout() {
return iCurrentQueryTimeout;
}
/**
* Sets the current queryTimeout for this query.
* @param iQueryTimeoutIn current queryTimeout.
*/
public void set_QueryTimeout(int iQueryTimeoutIn) {
iCurrentQueryTimeout = (iCurrentQueryTimeout < 0)? builder.getDefaultQueryTimeout() : iCurrentQueryTimeout;
}
/**
* Get the rowcount of the query by using count(*) in the DB
*
* @return The row count.
* @exception SQLException
* @exception DatabaseManagerException
*
* WebDocWf extension
*
*/
public int selectCount()
throws SQLException, DatabaseManagerException {
int rowCount=0;
String tempClause = builder.getSelectClause();
builder.setSelectClause(" count(*) as \"counter\" ");
DBQuery dbQuery;
dbQuery = XPDLParticipantProcessDO.createQuery(transaction);
dbQuery.query(this);
resultSet.next();
rowCount=resultSet.getInt("counter");
// resultSet.close();
// if (transaction == null)
// dbQuery.release();
dbQuery.release(); // +
builder.close();
resultSet = null;
builder.setSelectClause(tempClause);
return rowCount;
}
// end of WebDocWf extension for query row counter
/**
* Return true if some caching for this table is enabled.
* @return (true/false)
*/
private boolean isCaching() {
double cachePercentage = XPDLParticipantProcessDO.cache.getCachePercentage();
double usedPercentage = 0;
if(cachePercentage == -1)
return false;
else if(cachePercentage == 0)
return true;
else {
try {
usedPercentage = XPDLParticipantProcessDO.getConfigurationAdministration().getStatistics().getCacheStatistics(CacheConstants.DATA_CACHE).getUsedPercents();
} catch (Exception ex) {
return false;
}
if(usedPercentage > XPDLParticipantProcessDO.cache.getCachePercentage()*100)
return true;
else
return false;
}
}
private static CachedDBTransaction _tr_(DBTransaction dbt) {
return (CachedDBTransaction)dbt;
}
private String fixCaseSensitiveCondition(String cmp_op){
if(XPDLParticipantProcessDO.getConfigurationAdministration().getTableConfiguration().isCaseSensitive()){
if( cmp_op.equals(builder.CASE_INSENSITIVE_CONTAINS) ){
return builder.CASE_SENSITIVE_CONTAINS;
}else if( cmp_op.equals( builder.CASE_INSENSITIVE_STARTS_WITH ) ){
return builder.CASE_SENSITIVE_STARTS_WITH;
}else if( cmp_op.equals(builder.CASE_INSENSITIVE_ENDS_WITH) ){
return builder.CASE_SENSITIVE_ENDS_WITH;
}else if( cmp_op.equals(builder.CASE_INSENSITIVE_EQUAL) ){
return builder.EQUAL;
}else if( cmp_op.equals(builder.CASE_INSENSITIVE_MATCH) ){
return builder.CASE_SENSITIVE_MATCH;
}else if( cmp_op.equals(builder.USER_CASE_INSENSITIVE_MATCH) ){
return builder.USER_CASE_SENSITIVE_MATCH;
}
}
return cmp_op;
}
/**
* Set the PROCESS_ID to query, with a QueryBuilder comparison operator.
*
* @param x The PROCESS_ID of the XPDLParticipantProcess to query.
* @param cmp_op QueryBuilder comparison operator to use.
*
* @exception DataObjectException If a database access error occurs.
* @exception QueryException If comparison operator is inappropriate
* (e.g. CASE_SENSITIVE_CONTAINS on an integer field).
*/
public void setQueryPROCESS_ID(String x, String cmp_op )
throws DataObjectException, QueryException {
String cachePrefix = getLogicalDatabase()+".";
hasNonOidCond = true;
cmp_op = fixCaseSensitiveCondition(cmp_op);
Condition cond = null;
cond = new Condition(XPDLParticipantProcessDataStruct.COLUMN_PROCESS_ID,x,cmp_op);
queryItem.addCond(cond);
// WebDocWf extension for extended wildcard support
// The following lines have been added:
if (cmp_op.equals(QueryBuilder.CASE_INSENSITIVE_MATCH) || cmp_op.equals(QueryBuilder.CASE_SENSITIVE_MATCH) || cmp_op.equals(QueryBuilder.USER_CASE_SENSITIVE_MATCH) || cmp_op.equals(QueryBuilder.USER_CASE_INSENSITIVE_MATCH)) {
hitDb = true;
} else {
// end of WebDocWf extension for extended wildcard support
if (XPDLParticipantProcessDO.cache.isFull() && (XPDLParticipantProcessDO.isFullCacheNeeded)) {
// Remove from cacheHits any DOs that do not meet this
// setQuery requirement.
XPDLParticipantProcessDO DO = null;
XPDLParticipantProcessDataStruct DS = null;
// 12.04.2004 tj
// for ( Iterator iter = (new HashSet(cacheHits.values())).iterator(); iter.hasNext();)
for ( int i = 0; i < cacheHits.size(); i++ ) {
try {
boolean findInTransactionCache = false;
// DS = (XPDLParticipantProcessDataStruct)iter.next();
DS = (XPDLParticipantProcessDataStruct)cacheHits.elementAt( i );
if(transaction!=null && _tr_(transaction).getTransactionCache()!=null) {
DO = (XPDLParticipantProcessDO)_tr_(transaction).getTransactionCache().getDOByHandle(cachePrefix+DS.get_Handle());
if(DO != null)
findInTransactionCache = true;
}
if(!findInTransactionCache){
DO = (XPDLParticipantProcessDO)XPDLParticipantProcessDO.ceInternal(DS.get_OId(), transaction);
}
}catch (Exception ex) {
System.out.println("Error in query member stuff");
}
String m = DO.getPROCESS_ID();
if(!QueryBuilder.compare( m, x, cmp_op )) {
try {
String cacheHandle = DO.get_CacheHandle();
// cacheHits.remove(cacheHandle);
cacheHits.removeElementAt( i-- );
} catch (DatabaseManagerException e) {
throw new DataObjectException("Error in loading data object's handle.");
}
}
} // for
}
}
// Also prepares the SQL needed to query the database
// in case there is no cache, or the query involves other tables.
// WebDocWf patch for correct queries in fully cached objects
// The following line has been put under comments:
// if ( partOrLru || hitDb )
// end of WebDocWf patch for correct queries in fully cached objects
builder.addWhere( XPDLParticipantProcessDO.PROCESS_ID, x, cmp_op );
}
/**
* Set the PROCESS_ID to query, with a QueryBuilder comparison operator.
*
* @param x The PROCESS_ID of the XPDLParticipantProcess to query.
*
* @exception DataObjectException If a database access error occurs.
* @exception QueryException If comparison operator is inappropriate
* (e.g. CASE_SENSITIVE_CONTAINS on an integer field).
*/
public void setQueryPROCESS_ID(String x)
throws DataObjectException, QueryException {
setQueryPROCESS_ID(x, QueryBuilder.EQUAL);
}
/**
* Add PROCESS_ID to the ORDER BY clause.
* NOTE: The DO cache does not yet support the Order By operation.
* Using the addOrderBy method forces the query to hit the database.
*
* @param direction_flag True for ascending order, false for descending
*/
public void addOrderByPROCESS_ID(boolean direction_flag) {
hitDb = true;
builder.addOrderByColumn("PROCESS_ID", (direction_flag) ? "ASC" : "DESC");
}
/**
* Add PROCESS_ID to the ORDER BY clause. This convenience
* method assumes ascending order.
* NOTE: The DO cache does not yet support the Order By operation.
* Using the addOrderBy method forces the query to hit the database.
*/
public void addOrderByPROCESS_ID() {
hitDb = true;
builder.addOrderByColumn("PROCESS_ID","ASC");
}
// WebDocWf extension for extended wildcard support
// The following lines have been added:
/**
* Set the PROCESS_ID to query with a user wildcard string
*
* @param x The PROCESS_ID of the XPDLParticipantProcess to query with user wildcards
*
* @exception DataObjectException If a database access error occurs.
* @exception QueryException If a query error occurs.
*
* @deprecated Use comparison operators instead
*
* WebDocWf extension
*
*/
public void setUserMatchPROCESS_ID( String x )
throws DataObjectException, QueryException {
String y = convertUserSearchValue( x );
setDBMatchPROCESS_ID( y );
}
/**
* Set the PROCESS_ID to query with a DB wildcard string
*
* @param x The PROCESS_ID of the XPDLParticipantProcess to query with DB wildcards
*
* @exception DataObjectException If a database access error occurs.
* @exception QueryException If a query error occurs.
*
* @deprecated Use comparison operators instead
*
* WebDocWf extension
*
*/
public void setDBMatchPROCESS_ID(String x )
throws DataObjectException, QueryException {
if (containsWildcards(x) || builder.getUserStringAppendWildcard()) {
builder.addMatchClause( XPDLParticipantProcessDO.PROCESS_ID, x );
hitDb = true;
} else
setQueryPROCESS_ID( x, QueryBuilder.EQUAL );
}
// end of WebDocWf extension for extended wildcard support
/**
* Set the PACKAGEOID to query, with a QueryBuilder comparison operator.
*
* @param x The PACKAGEOID of the XPDLParticipantProcess to query.
* @param cmp_op QueryBuilder comparison operator to use.
*
* @exception DataObjectException If a database access error occurs.
* @exception QueryException If comparison operator is inappropriate
* (e.g. CASE_SENSITIVE_CONTAINS on an integer field).
*/
public void setQueryPACKAGEOID(org.enhydra.shark.partmappersistence.data.XPDLParticipantPackageDO x, String cmp_op )
throws DataObjectException, QueryException {
String cachePrefix = getLogicalDatabase()+".";
if(transaction!=null && x!=null && x.get_transaction()!=null) {
if(!transaction.equals(x.get_transaction()))
throw new DataObjectException("Referenced DO doesn't belong the same transaction.");
}
if(refs==null)
refs = new HashMap();
if(x!=null)
refs.put(cachePrefix+x.get_OId(),x);
hasNonOidCond = true;
cmp_op = fixCaseSensitiveCondition(cmp_op);
Condition cond = null;
if((x!=null)&& (x instanceof CoreDO)) {
CoreDataStruct xDataStruct = (CoreDataStruct)x.get_DataStruct();
cond = new Condition(XPDLParticipantProcessDataStruct.COLUMN_PACKAGEOID,xDataStruct,cmp_op);
} else
cond = new Condition(XPDLParticipantProcessDataStruct.COLUMN_PACKAGEOID,x,cmp_op);
queryItem.addCond(cond);
// WebDocWf extension for extended wildcard support
// The following lines have been added:
if (cmp_op.equals(QueryBuilder.CASE_INSENSITIVE_MATCH) || cmp_op.equals(QueryBuilder.CASE_SENSITIVE_MATCH) || cmp_op.equals(QueryBuilder.USER_CASE_SENSITIVE_MATCH) || cmp_op.equals(QueryBuilder.USER_CASE_INSENSITIVE_MATCH)) {
hitDb = true;
} else {
// end of WebDocWf extension for extended wildcard support
if (XPDLParticipantProcessDO.cache.isFull() && (XPDLParticipantProcessDO.isFullCacheNeeded)) {
// Remove from cacheHits any DOs that do not meet this
// setQuery requirement.
XPDLParticipantProcessDO DO = null;
XPDLParticipantProcessDataStruct DS = null;
// 12.04.2004 tj
// for ( Iterator iter = (new HashSet(cacheHits.values())).iterator(); iter.hasNext();)
for ( int i = 0; i < cacheHits.size(); i++ ) {
try {
boolean findInTransactionCache = false;
// DS = (XPDLParticipantProcessDataStruct)iter.next();
DS = (XPDLParticipantProcessDataStruct)cacheHits.elementAt( i );
if(transaction!=null && _tr_(transaction).getTransactionCache()!=null) {
DO = (XPDLParticipantProcessDO)_tr_(transaction).getTransactionCache().getDOByHandle(cachePrefix+DS.get_Handle());
if(DO != null)
findInTransactionCache = true;
}
if(!findInTransactionCache){
DO = (XPDLParticipantProcessDO)XPDLParticipantProcessDO.ceInternal(DS.get_OId(), transaction);
}
}catch (Exception ex) {
System.out.println("Error in query member stuff");
}
org.enhydra.shark.partmappersistence.data.XPDLParticipantPackageDO m = DO.getPACKAGEOID();
if(!QueryBuilder.compare( m, x, cmp_op )) {
try {
String cacheHandle = DO.get_CacheHandle();
// cacheHits.remove(cacheHandle);
cacheHits.removeElementAt( i-- );
} catch (DatabaseManagerException e) {
throw new DataObjectException("Error in loading data object's handle.");
}
}
} // for
}
}
// Also prepares the SQL needed to query the database
// in case there is no cache, or the query involves other tables.
// WebDocWf patch for correct queries in fully cached objects
// The following line has been put under comments:
// if ( partOrLru || hitDb )
// end of WebDocWf patch for correct queries in fully cached objects
builder.addWhere( XPDLParticipantProcessDO.PACKAGEOID, x, cmp_op );
}
/**
* Set the PACKAGEOID to query, with a QueryBuilder comparison operator.
*
* @param x The PACKAGEOID of the XPDLParticipantProcess to query.
*
* @exception DataObjectException If a database access error occurs.
* @exception QueryException If comparison operator is inappropriate
* (e.g. CASE_SENSITIVE_CONTAINS on an integer field).
*/
public void setQueryPACKAGEOID(org.enhydra.shark.partmappersistence.data.XPDLParticipantPackageDO x)
throws DataObjectException, QueryException {
setQueryPACKAGEOID(x, QueryBuilder.EQUAL);
}
/**
* Add PACKAGEOID to the ORDER BY clause.
* NOTE: The DO cache does not yet support the Order By operation.
* Using the addOrderBy method forces the query to hit the database.
*
* @param direction_flag True for ascending order, false for descending
*/
public void addOrderByPACKAGEOID(boolean direction_flag) {
hitDb = true;
builder.addOrderByColumn("PACKAGEOID", (direction_flag) ? "ASC" : "DESC");
}
/**
* Add PACKAGEOID to the ORDER BY clause. This convenience
* method assumes ascending order.
* NOTE: The DO cache does not yet support the Order By operation.
* Using the addOrderBy method forces the query to hit the database.
*/
public void addOrderByPACKAGEOID() {
hitDb = true;
builder.addOrderByColumn("PACKAGEOID","ASC");
}
// WebDocWf extension for extended wildcard support
// The following lines have been added:
// end of WebDocWf extension for extended wildcard support
/**
* Returns the <code>QueryBuilder</code> that this <code>XPDLParticipantProcessQuery</code>
* uses to construct and execute database queries.
* <code>XPDLParticipantProcessQuery.setQueryXXX</code> methods use
* the <code>QueryBuilder</code> to
* append SQL expressions to the <code>"WHERE"</code> clause to be executed.
* The <code>QueryBuilder.addEndClause method.</code> can be used to
* append freeform SQL expressions to the <code>WHERE</code> clause,
* e.g. "ORDER BY name".
*
* <b>Notes regarding cache-enabled DO classes:</b>
* DO classes can be cache-enabled.
* If when using a <code>XPDLParticipantProcessQuery</code>, the application developer
* <b>does not call</b> <code>getQueryBuilder</code>,
* then <code>XPDLParticipantProcessQuery.setQueryXXX</code> methods
* simply prune the DO cache and return the remaining results.
* However, a <code>QueryBuilder</code> builds
* <CODE>SELECT</CODE> statements for execution by the actual database,
* and never searches the built-in cache for the DO.
* So, if the DO class is cache-enabled, and <code>getQueryBuilder</code>
* is called, this <CODE>XPDLParticipantProcessQuery</CODE> object ignores the cache
* and hits the actual database.
*
* @return QueryBuilder that is used to construct and execute database queries.
*/
public QueryBuilder getQueryBuilder() {
hitDb = true;
return builder;
}
/**
* Insert an <CODE>OR</CODE> between <CODE>WHERE</CODE> clauses.
* Example: find all the persons named Bob or Robert:
* <CODE>
* PersonQuery pq = new PersonQuery();
* pq.setQueryFirstName( "Bob" );
* pq.or();
* pq.setQueryFirstName( "Robert" );
* </CODE>
*
* Note: Calls to <CODE>setQueryXxx</CODE> methods
* are implicitly <CODE>AND</CODE>ed together,
* so the following example will always return nothing:
* <CODE>
* PersonQuery pq = new PersonQuery();
* pq.setQueryFirstName( "Bob" );
* // AND automatically inserted here.
* pq.setQueryFirstName( "Robert" );
* </CODE>
*
* NOTE: The DO cache does not yet support the OR operator.
* Using the or() method forces the query to hit the database.
*
* @see com.lutris.dods.builder.generator.query.QueryBuilder QueryBuilder to construct more elaborate queries.
* author Jay Gunter
*/
public void or() {
hitDb = true;
builder.addWhereOr();
}
/**
* Place an open parenthesis in the <CODE>WHERE</CODE> clause.
* Example usage: find all the Bobs and Roberts who are 5 or 50 years old:
* <CODE>
* PersonQuery pq = new PersonQuery();
* pq.openParen();
* pq.setQueryFirstName( "Bob" );
* pq.or();
* pq.setQueryFirstName( "Robert" );
* pq.closeParen();
* // AND automatically inserted here.
* pq.openParen();
* pq.setQueryAge( 5 );
* pq.or();
* pq.setQueryAge( 50 );
* pq.closeParen();
* </CODE>
*
* NOTE: The DO cache does not yet support the Open Paren operator.
* Using the openParen() method forces the query to hit the database.
*
* @see com.lutris.dods.builder.generator.query.QueryBuilder QueryBuilder to construct more elaborate queries.
* author Jay Gunter
*/
public void openParen() {
hitDb = true;
builder.addWhereOpenParen();
}
/**
* Place a closing parenthesis in the <CODE>WHERE</CODE> clause.
*
* NOTE: The DO cache does not yet support the Close Paren operator.
* Using the closeParen() method forces the query to hit the database.
*
* @see XPDLParticipantProcessQuery#openParen openParen
* author Jay Gunter
*/
public void closeParen() {
hitDb = true;
builder.addWhereCloseParen();
}
}
| [
"classic1999@sina.com"
] | classic1999@sina.com |
2355a527bace475b9e2c0e3fa5ff8ce0ed3d2ebb | 925af24267bbdb4f6ab3bca62e61e9bbaf9d4ceb | /ASD1/src/gameobject/data/behaviour/ai/idle/IdleAIRoutines.java | 97bcc6e68d952bb0a67d8cce59d732d31c8d5086 | [] | no_license | Hobajt/pj1_projekt | 642ddec0c8fe4f32a2fb7ec0b2ce343ac288e366 | 0359d4f317162ed099f4e40bfdda4cecef04a69d | refs/heads/master | 2021-09-23T17:49:08.068741 | 2017-12-19T23:32:18 | 2017-12-19T23:32:18 | 114,043,715 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 745 | java | /*
* 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 gameobject.data.behaviour.ai.idle;
import gameobject.GameObject;
import gameobject.data.behaviour.ai.AIState;
import java.util.List;
import util.Point;
/**
* Idle behaviour for movement around predefined path
* @author Radek
*/
public class IdleAIRoutines extends IdleAI {
private List<Point> route;
private transient int nextStop;
@Override
public AIState update(AIState state) {
return AIState.IDLE;
}
public IdleAIRoutines(IdleAIData data, GameObject owner) {
super(data, owner);
}
}
| [
"kopecki111@gmail.com"
] | kopecki111@gmail.com |
a1aa0c911d4d95959b1771d70949a8a96297d611 | 1e906b18093f1d62a2d8388e77030c50fcae032f | /android/app/src/main/java/com/awesomeprojectn/MainActivity.java | a07d3ead7e555e3420ce488e2fec1c6e7ff7c3d6 | [] | no_license | sjsj2/awesome-react-project | a8fc59186565ff692fff3b3c968719105c855a48 | 921e539aa4bf335611b089f943d7502e781f21d5 | refs/heads/master | 2021-09-11T18:57:42.575257 | 2018-04-11T02:51:02 | 2018-04-11T02:51:02 | 107,648,836 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 375 | java | package com.awesomeprojectn;
import com.facebook.react.ReactActivity;
public class MainActivity extends ReactActivity {
/**
* Returns the name of the main component registered from JavaScript.
* This is used to schedule rendering of the component.
*/
@Override
protected String getMainComponentName() {
return "AwesomeProjectN";
}
}
| [
"sunny@yusujin-ui-MacBook-Air.local"
] | sunny@yusujin-ui-MacBook-Air.local |
db0fa9972758b406a583b13f8cf0e85558f7cdcb | d921635ac17be024d10464e757f58d8769412bb1 | /src/main/java/guru/springframework/Franc.java | 75c821989b7a082fa0a784274e84b158076ad612 | [
"Apache-2.0"
] | permissive | ahmeed83/tdd-by-example | e6031f0e7828a585dfa8eda8e3353c7015f175cb | 0ca9e48983536392ba84e219b550b2b37285f373 | refs/heads/master | 2020-04-06T08:54:57.583832 | 2018-11-14T06:00:51 | 2018-11-14T06:00:51 | 157,321,531 | 0 | 0 | null | 2018-11-13T04:44:39 | 2018-11-13T04:44:39 | null | UTF-8 | Java | false | false | 243 | java | package guru.springframework;
public class Franc extends Money {
public Franc(final int amount) {
this.amount = amount;
}
public Money times(final int multiplier) {
return new Franc(amount * multiplier);
}
}
| [
"ahmed83@me.com"
] | ahmed83@me.com |
7f351759721dbc4ba9a26cc9d6a9e49a1cc3890f | cdeee1295065d0ba965dd0c502973e9c3aa60618 | /gameserver/data/scripts/ai/ZakenDaytime83.java | 1e1be341ec3139974e9d7c6bffea344227b8cec3 | [] | no_license | forzec/l-server | 526b1957f289a4223942d3746143769c981a5508 | 0f39edf60a14095b269b4a87c1b1ac01c2eb45d8 | refs/heads/master | 2021-01-10T11:39:14.088518 | 2016-03-19T18:28:04 | 2016-03-19T18:28:04 | 54,065,298 | 5 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,319 | java | package ai;
import org.mmocore.gameserver.ai.CtrlEvent;
import org.mmocore.gameserver.ai.Fighter;
import org.mmocore.gameserver.model.Creature;
import org.mmocore.gameserver.model.entity.Reflection;
import org.mmocore.gameserver.model.instances.NpcInstance;
import instances.ZakenDay83;
/**
* Daytime Zaken.
* - иногда призывает 4х мобов id: 29184
*
* @author pchayka
*/
public class ZakenDaytime83 extends Fighter
{
private long _spawnTimer = 0L;
private static final long _spawnReuse = 60000L;
private static final int _summonId = 29184;
private NpcInstance actor = getActor();
Reflection r = actor.getReflection();
public ZakenDaytime83(NpcInstance actor)
{
super(actor);
}
@Override
protected void thinkAttack()
{
if(actor.getCurrentHpPercents() < 70 && _spawnTimer + _spawnReuse < System.currentTimeMillis())
{
for(int i = 0; i < 4; i++)
{
NpcInstance add = r.addSpawnWithoutRespawn(_summonId, actor.getLoc(), 250);
add.getAI().notifyEvent(CtrlEvent.EVT_AGGRESSION, getAttackTarget(), 2000);
}
_spawnTimer = System.currentTimeMillis();
}
super.thinkAttack();
}
@Override
protected void onEvtDead(Creature killer)
{
((ZakenDay83) r).notifyZakenDeath(actor);
r.setReenterTime(System.currentTimeMillis());
super.onEvtDead(killer);
}
} | [
"dmitry@0xffff"
] | dmitry@0xffff |
cf9f8aa8bbe0594d3b20d909e3481ec45c3426ec | f3ace548bf9fd40e8e69f55e084c8d13ad467c1c | /excuterWrong/SimpleTree/AORB_12/SimpleTree.java | 23bce5db66139d32d7dbcf31478ef178b5cde50d | [] | no_license | phantomDai/concurrentProgramTesting | 307d008f3bba8cdcaf8289bdc10ddf5cabdb8a04 | 8ac37f73c0413adfb1ea72cb6a8f7201c55c88ac | refs/heads/master | 2021-05-06T21:18:13.238925 | 2017-12-06T11:10:01 | 2017-12-06T11:10:02 | 111,872,421 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 2,051 | java | // This is a mutant program.
// Author : ysma
package mutants.SimpleTree.AORB_12;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;
public class SimpleTree<T> implements PQueue<T>
{
int range;
java.util.List<TreeNode> leaves;
SimpleTree.TreeNode root;
public SimpleTree( int logRange )
{
range = 1 << logRange;
leaves = new java.util.ArrayList<TreeNode>( range );
root = buildTree( logRange, 0 );
}
SimpleTree.TreeNode buildTree( int height, int slot )
{
SimpleTree.TreeNode root = new SimpleTree.TreeNode();
root.counter = new java.util.concurrent.atomic.AtomicInteger( 0 );
if (height == 0) {
root.bin = new Bin<T>();
leaves.add( slot, root );
} else {
root.left = buildTree( height - 1, 2 * slot );
root.right = buildTree( height + 1, 2 * slot + 1 );
root.left.parent = root.right.parent = root;
}
return root;
}
public void add( T item, int priority )
{
SimpleTree.TreeNode node = leaves.get( priority );
node.bin.put( item );
while (node != root) {
SimpleTree.TreeNode parent = node.parent;
if (node == parent.left) {
parent.counter.getAndIncrement();
}
node = parent;
}
}
public T removeMin()
{
SimpleTree.TreeNode node = root;
while (!node.isLeaf()) {
if (node.counter.getAndDecrement() > 0) {
node = node.left;
} else {
node = node.right;
}
}
return (T) node.bin.get();
}
public class TreeNode
{
java.util.concurrent.atomic.AtomicInteger counter;
SimpleTree.TreeNode parent;
SimpleTree.TreeNode right;
SimpleTree.TreeNode left;
Bin<T> bin;
public boolean isLeaf()
{
return right == null;
}
}
}
| [
"daihepeng@sina.cn"
] | daihepeng@sina.cn |
bf6792662672fad410c43313a964bcb66f19ea38 | e1450a329c75a55cf6ccd0ce2d2f3517b3ee51c5 | /src/main/java/home/javarush/javaCore/task13/task1308/Solution.java | 9682cd08b0a5e5829b939faa064df08d227fc398 | [] | no_license | nikolaydmukha/netology-java-base-java-core | afcf0dd190f4c912c5feb2ca8897bc17c09a9ec1 | eea55c27bbbab3b317c3ca5b0719b78db7d27375 | refs/heads/master | 2023-03-18T13:33:24.659489 | 2021-03-25T17:31:52 | 2021-03-25T17:31:52 | 326,259,412 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 300 | java | package home.javarush.javaCore.task13.task1308;
/*
Эй, ты там живой?
*/
public class Solution {
public static void main(String[] args) throws Exception {
}
public interface Person {
boolean isAlive();
}
public interface Presentable extends Person{
}
} | [
"dmukha@mail.ru"
] | dmukha@mail.ru |
9e6dae456bf7262407c0d91ff6a535eb1aeda9bb | 883b999347c620fc4bb960cf5abb71ebe00c2867 | /pinyougou-parent/pinyougou-manager-web/src/main/java/com/pinyougou/manager/controller/GoodsController.java | 614f234beeec79e0db017cbcf7b5d9d78b93e817 | [] | no_license | longgang/pinyougou | d58a91dd6b7520451724e7df125a192f5c843461 | a316ca32b8b8d7933ab834576ae3c8977c9d793b | refs/heads/master | 2020-03-23T07:19:27.019132 | 2018-06-25T08:22:29 | 2018-06-25T08:22:29 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,979 | java | package com.pinyougou.manager.controller;
import java.util.List;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.alibaba.dubbo.config.annotation.Reference;
import com.pinyougou.pojo.TbGoods;
import com.pinyougou.sellergoods.service.GoodsService;
import entity.PageResult;
import entity.Result;
/**
* controller
* @author Administrator
*
*/
@RestController
@RequestMapping("/goods")
public class GoodsController {
@Reference
private GoodsService goodsService;
/**
* 返回全部列表
* @return
*/
@RequestMapping("/findAll")
public List<TbGoods> findAll(){
return goodsService.findAll();
}
/**
* 返回全部列表
* @return
*/
@RequestMapping("/findPage")
public PageResult findPage(int page,int rows){
return goodsService.findPage(page, rows);
}
/**
* 修改
* @param goods
* @return
*/
@RequestMapping("/update")
public Result update(@RequestBody TbGoods goods){
try {
goodsService.update(goods);
return new Result(true, "修改成功");
} catch (Exception e) {
e.printStackTrace();
return new Result(false, "修改失败");
}
}
/**
* 获取实体
* @param id
* @return
*/
@RequestMapping("/findOne")
public TbGoods findOne(Long id){
return goodsService.findOne(id);
}
/**
* 批量删除
* @param ids
* @return
*/
@RequestMapping("/delete")
public Result delete(Long [] ids){
try {
goodsService.delete(ids);
return new Result(true, "删除成功");
} catch (Exception e) {
e.printStackTrace();
return new Result(false, "删除失败");
}
}
/**
* 查询+分页
* @param brand
* @param page
* @param rows
* @return
*/
@RequestMapping("/search")
public PageResult search(@RequestBody TbGoods goods, int page, int rows ){
return goodsService.findPage(goods, page, rows);
}
}
| [
"386592336@qq.com"
] | 386592336@qq.com |
6bd6348b97d2bb50990f753ed6cbdece77c9b870 | f7e6c7070a3ba306d9bd268991c83b7a1acea9c1 | /pgpainless-core/src/main/java/org/pgpainless/exception/package-info.java | 1d5adbd2b917765bc8b9125e6d03ac80b840e23a | [
"Apache-2.0"
] | permissive | Flowdalic/pgpainless | 3f9c77e31193f0629d4b95b4aa87dd8fa7f45313 | e9958bc62063be242f6731f88cf4ea0cc3fe01c0 | refs/heads/master | 2023-08-03T03:32:35.103558 | 2018-08-03T10:28:25 | 2018-08-03T10:28:25 | 139,035,140 | 0 | 0 | Apache-2.0 | 2018-06-28T15:13:40 | 2018-06-28T15:13:40 | null | UTF-8 | Java | false | false | 653 | java | /*
* Copyright 2018 Paul Schaub.
*
* 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.
*/
/**
* Exceptions.
*/
package org.pgpainless.exception;
| [
"vanitasvitae@fsfe.org"
] | vanitasvitae@fsfe.org |
50aae703061fdb87796744350c5924db1e6dcfe3 | 6e349f85c52df72d9ce48167b3767e84317cf610 | /src/main/java/com/expense/manager/web/RegistrationController.java | e1f9541723734e562347a8082e35000241a82ee9 | [] | no_license | MichalPietrus/Home-Expense-Manager | 6cbf465ef2781aa09879daeae25ec5c03ddfcacc | fe656021e1c069e0624f1a0f4627bcd08bc7b94d | refs/heads/master | 2023-01-31T03:25:39.264745 | 2020-12-14T13:30:16 | 2020-12-14T13:30:16 | 295,426,703 | 0 | 1 | null | 2020-09-22T12:12:09 | 2020-09-14T13:35:30 | HTML | UTF-8 | Java | false | false | 1,544 | java | package com.expense.manager.web;
import com.expense.manager.model.User;
import com.expense.manager.service.UserService;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import javax.validation.Valid;
@Controller
@RequestMapping("/registration")
public class RegistrationController {
private final UserService userService;
public RegistrationController(UserService userService) {
this.userService = userService;
}
@ModelAttribute("user")
public User userRegistrationModel() {
return new User();
}
@GetMapping
public String showRegistrationForm() {
return "registration";
}
@PostMapping
public String registerUserAccount(@ModelAttribute("user") @Valid User user,
BindingResult result) {
User existingByUserNameOrEmail = userService.findByUsernameOrEmail(user.getUsername(), user.getEmail());
if (existingByUserNameOrEmail != null)
result.rejectValue("username", null, "There is already an account registered with that username or email");
if (result.hasErrors())
return "registration";
userService.registerUser(user);
return "redirect:/registration?success";
}
}
| [
"grahul2121@gmail.com"
] | grahul2121@gmail.com |
23fba1e9231bd341dfdadfa33c5a91e3b3dfa631 | 4cefbeb2d37b70b0d4f648132635e3ac6ce17df1 | /app/src/main/java/com/skpissay/util/RxBus.java | 80d047e4cc5f1f5c672ccfd587777f88701b3be3 | [] | no_license | Sach16/Checkgaadi-Mvvm | 1c92f313e8e91cc135449cec1f71f315a1f0476a | 356b115f758d710db33f2552dec0b2c5581efc2b | refs/heads/master | 2020-03-28T21:01:32.121330 | 2018-09-17T12:51:29 | 2018-09-17T12:51:29 | 149,123,423 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 751 | java | package com.skpissay.util;
import rx.Observable;
import rx.subjects.PublishSubject;
import rx.subjects.SerializedSubject;
import rx.subjects.Subject;
/**
* Created by mertsimsek on 13/01/17.
*/
public class RxBus {
private static RxBus instance = null;
private final Subject<Object, Object> _bus = new SerializedSubject<>(PublishSubject.create());
private RxBus() {
}
public static RxBus getInstance() {
if (instance == null)
instance = new RxBus();
return instance;
}
public void send(Object o) {
_bus.onNext(o);
}
public Observable<Object> toObserverable() {
return _bus;
}
public boolean hasObservers() {
return _bus.hasObservers();
}
}
| [
"sachin.pissay@carzonrent.com"
] | sachin.pissay@carzonrent.com |
82ac1d7ea2df619474ed2bf941090e12a3416764 | 46f443ec46857a3c2715a832f67681e98d23a0fa | /ConfigurationWithJavaCode/src/main/java/ru/rickSanchez/withoutAnnotation/RapMusic.java | ae77e39ede55cd4f2e15605ff0f67b6cf0acdaa7 | [] | no_license | MRCoolZero/Spring | 4c4bef97cd20b9a5d1fe54850ff936d8b531f211 | 609524e2b8e8fd9c89763e9222fe31acd75a4aa6 | refs/heads/master | 2023-01-14T12:18:09.972834 | 2020-11-22T16:49:42 | 2020-11-22T16:49:42 | 315,085,831 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 163 | java | package ru.rickSanchez.withoutAnnotation;
public class RapMusic implements Music{
@Override
public String getSong() {
return "RapMusic";
}
}
| [
"one1970zero@mail.ru"
] | one1970zero@mail.ru |
dd5ecea78375c1f885bde40f7b677c97daaf9463 | a456b9726eda22e414d0f7ce16206760a7a94f8a | /src/com/example/qrboard/ExploreActivity.java | a62b775741dd6dfc4344393a88f6281b0ad6ad8f | [] | no_license | lorenzoviva/QRBoard | 4876a8d31c00b71a4745981d62677d77f4d9e2a5 | 0519a98ffd854a780a4ac8dd3739b60b44e5ec4d | refs/heads/master | 2016-09-10T10:38:05.535477 | 2015-12-09T23:27:23 | 2015-12-09T23:27:23 | 42,772,088 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 10,061 | java | package com.example.qrboard;
import java.util.ArrayList;
import java.util.List;
import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.drawable.Drawable;
import android.os.Build;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.MeasureSpec;
import android.view.View.OnTouchListener;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
public class ExploreActivity extends Activity implements InvalidableAcivity, OnTouchListener {
QRExplorer explorer;
ActivityInvalidator invalidator;
RelativeLayout instructionLayout;
private int instructionIndex;
private List<TextView> instructions;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (Build.VERSION.SDK_INT < 16) {
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
} else {
getWindow().getDecorView().setSystemUiVisibility(
View.SYSTEM_UI_FLAG_FULLSCREEN);
}
setContentView(R.layout.activity_explore);
explorer = (QRExplorer) findViewById(R.id.qr_explorer);
instructionLayout = (RelativeLayout) findViewById(R.id.explore_instruction_layout);
invalidator = new ActivityInvalidator(this);
explorer.setExploreButton((Button) findViewById(R.id.explorerbutton));
explorer.setEditImageInfo((ImageView) findViewById(R.id.explorereditifoimage));
explorer.setEditTextInfo((TextView) findViewById(R.id.explorereditifo));
explorer.setBackButton((Button) findViewById(R.id.explorequitbutton));
explorer.setReadButton((Button) findViewById(R.id.explorereadbutton));
if (getIntent().hasExtra("response")) {
String jsonresponse = getIntent().getStringExtra("response");
setup(jsonresponse);
}
explorer.setInstructing(true);
if (isNotFirstTime()) {
instructionLayout.setVisibility(View.INVISIBLE);
explorer.setInstructing(false);
}else{
// }
setupInstructions();
}
}
private void setupInstructions(){
DisplayMetrics metrics = getResources().getDisplayMetrics();
int width = metrics.widthPixels;
int height = metrics.heightPixels;
float d = metrics.density;
// Log.d("EXPLORER", "bottom: "+ height + " right :" + width + " mw:" + instructionLayout.getMeasuredWidth());
instructionIndex = 1;
instructions = new ArrayList<TextView>();
instructions.add((TextView) findViewById(R.id.explorer_instructiontextView0));
instructions.add((TextView) findViewById(R.id.explorer_instructiontextView1));
TextView tv2 = (TextView) findViewById(R.id.explorer_instructiontextView2);
Drawable freccia = getResources().getDrawable(R.drawable.arrowright);
tv2.measure(0, 0);
freccia.setBounds(0, 0, tv2.getMeasuredWidth(), tv2.getMeasuredWidth());
tv2.setCompoundDrawables(null, null, null, freccia);
instructions.add(tv2);
TextView tv3 = (TextView) findViewById(R.id.explorer_instructiontextView3);
RelativeLayout.LayoutParams params1 = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT);
params1.setMargins((width/5)*2, (width/12), 0, 0);
tv3.setLayoutParams(params1);
Drawable row = getResources().getDrawable(R.drawable.instructionrow);
row.setBounds(0, 0, (width*3)/5, (width*17)/60);
tv3.setCompoundDrawables(null, row, null, null);
instructions.add(tv3);
TextView tv4 = (TextView) findViewById(R.id.explorer_instructiontextView4);
RelativeLayout.LayoutParams params2 = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT);
params2.setMargins((width/5)*4, (width/12), 0, 0);
tv4.setLayoutParams(params2);
Drawable cell = getResources().getDrawable(R.drawable.instructioncell);
cell.setBounds(0, 0, (width)/5, (width*17)/60);
tv4.setCompoundDrawables(null, cell, null, null);
instructions.add(tv4);
TextView tv5 = (TextView) findViewById(R.id.explorer_instructiontextView5);
RelativeLayout.LayoutParams params3 = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT);
params3.setMargins((width/5)*3, (width/12), (width/5), 0);
tv5.setLayoutParams(params3);
tv5.setCompoundDrawables(null, cell, null, null);
instructions.add(tv5);
TextView tv6 = (TextView) findViewById(R.id.explorer_instructiontextView6);
RelativeLayout.LayoutParams params4 = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT);
params4.setMargins((width/5), (width/12), (width/5), 0);
tv6.setLayoutParams(params4);
tv6.setCompoundDrawables(null, cell, null, null);
instructions.add(tv6);
TextView tv7 = (TextView) findViewById(R.id.explorer_instructiontextView7);
RelativeLayout.LayoutParams params5 = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT);
params5.setMargins((width/10), (height/10), 0, 0);
tv7.setLayoutParams(params5);
Drawable focused = getResources().getDrawable(R.drawable.instructionfocused);
focused.setBounds(0, 0, (width*17)/60,(width)/5 );
tv7.setCompoundDrawables(focused, null, null, null);
instructions.add(tv7);
TextView tv8 = (TextView) findViewById(R.id.explorer_instructiontextView8);
RelativeLayout.LayoutParams params6 = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT);
params6.setMargins((3*width/10), (height/5) + (width/5)+120, 0, 0);
tv8.setLayoutParams(params6);
Drawable arrowleft = getResources().getDrawable(R.drawable.arrowleft);
arrowleft.setBounds(0,0 ,(width/5),(width)/20);
tv8.setCompoundDrawables(arrowleft, null, null, null);
instructions.add(tv8);
TextView tv9 = (TextView) findViewById(R.id.explorer_instructiontextView9);
RelativeLayout.LayoutParams params7 = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT);
params7.setMargins((3*width/10), (height/5) + (width/5), 0, 0);
tv9.setLayoutParams(params7);
Drawable arrowleftbig = getResources().getDrawable(R.drawable.arrowleftbig);
arrowleftbig.setBounds(0, 0 ,(width/5),(width)/5);
tv9.setCompoundDrawables(arrowleftbig, null,null , null);
instructions.add(tv9);
TextView tv10 = (TextView) findViewById(R.id.explorer_instructiontextView10);
RelativeLayout.LayoutParams params8 = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT);
params8.setMargins((3*width/10), (height/5) + (width/5), 0, 0);
tv10.setLayoutParams(params8);
arrowleftbig.setBounds(0, 0 ,(width/5),(width)/5);
tv10.setCompoundDrawables(arrowleftbig, null, null, null);
instructions.add(tv10);
TextView tv11 = (TextView) findViewById(R.id.explorer_instructiontextView11);
RelativeLayout.LayoutParams params9 = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT);
params9.setMargins((3*width/10), (height/5) + (width/5), 0, 0);
tv11.setLayoutParams(params9);
arrowleftbig.setBounds(0, 0 ,(width/5),(width)/5);
tv11.setCompoundDrawables(arrowleftbig, null, null, null);
instructions.add(tv11);
TextView tv12 = (TextView) findViewById(R.id.explorer_instructiontextView12);
RelativeLayout.LayoutParams param10 = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT);
param10.setMargins((3*width/10), (height/5) + (width/5)+60, 0, 0);
tv12.setLayoutParams(param10);
// arrowleft.setBounds(0, 0 ,(width/5),(width)/5);
tv12.setCompoundDrawables(arrowleft, null, null, null);
instructions.add(tv12);
TextView tv13 = (TextView) findViewById(R.id.explorer_instructiontextView13);
RelativeLayout.LayoutParams param11 = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT);
param11.setMargins((width/10), (height/10), 0, 0);
tv13.setLayoutParams(param11);
tv13.setCompoundDrawables(focused, null, null, null);
instructions.add(tv13);
}
private void setup(String jsonresponse) {
explorer.setup(jsonresponse);
}
private boolean isNotFirstTime() {
SharedPreferences preferences = PreferenceManager
.getDefaultSharedPreferences(this);
boolean ranBefore = preferences.getBoolean("exploreInstruction", false);
// if (!ranBefore) {
SharedPreferences.Editor editor = preferences.edit();
editor.putBoolean("exploreInstruction", true);
editor.commit();
instructionLayout.setVisibility(View.VISIBLE);
instructionLayout.setOnTouchListener(this);
// }
return ranBefore;
}
@Override
public boolean onTouch(View v, MotionEvent event) {
instructionIndex++;
if(instructionIndex>=instructions.size()){
instructionLayout.setVisibility(View.GONE);
explorer.setInstructing(false);
}else{
for(int i = 1; i< instructions.size(); i++){
if(i!=instructionIndex){
instructions.get(i).setVisibility(View.INVISIBLE);
}else{
instructions.get(i).setVisibility(View.VISIBLE);
}
}
}
return false;
}
@Override
public void invalidate() {
if (explorer.getArgui().isRefreshExplorer()) {
explorer.refresh();
}
explorer.postInvalidate();
}
@Override
public boolean onTouchEvent(MotionEvent event) {
if(!explorer.isInstructing()){
explorer.onTouchEvent(event);
}
return false;
}
@Override
public void onBackPressed() {
gotoScanActivity();
}
public void gotoScanActivity() {
Intent intent = new Intent(getApplicationContext(), ScanActivity.class);
intent.putExtra("com.google.zxing.client.android.SCAN.SCAN_MODE",
"QR_CODE_MODE");
startActivityForResult(intent, 0);
}
}
| [
"lorenzo.vaccaro@hotmail.com"
] | lorenzo.vaccaro@hotmail.com |
cf92b1279adb90d443cb17b41f858fedac0c7600 | 17dfcefb5d4a7527b2ba51f1762cfb62e824d8cc | /src/main/java/com/guyang/dao/BaseDao.java | a82821ff48a6bf765eb78d34b91e5b526d82525d | [] | no_license | guyang66/gy-spring-scoco | f7b71e91dc6941497ba28b729e8625ba5befaf8a | 0ff3c558a4f6e73e88e7301be317bc96c3862430 | refs/heads/master | 2023-06-17T14:06:38.338948 | 2021-07-13T08:00:27 | 2021-07-13T08:00:27 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 428 | java | package com.guyang.dao;
import java.util.List;
import java.util.Map;
public interface BaseDao<T> {
Integer selectCount(Map<String, ?> param);
List<T> select(Map<String, ?> parameters);
T selectById(Object id);
List<T> selectByIds(Object[] ids);
int deleteById(Object id);
int deleteByIds(Object[] list);
int delete(Map<String, Object> parameters);
int insert(T t);
int updateById(T t);
}
| [
"13588295865@163.com"
] | 13588295865@163.com |
7446dbb5c6b1eb81b285aed1e6835b153e56f826 | e1450a329c75a55cf6ccd0ce2d2f3517b3ee51c5 | /src/main/java/home/javarush/javaCore/task12/task1228/Solution.java | 96fb4c4c65a0a6cb247ad1158a95b9283a4ed43f | [] | no_license | nikolaydmukha/netology-java-base-java-core | afcf0dd190f4c912c5feb2ca8897bc17c09a9ec1 | eea55c27bbbab3b317c3ca5b0719b78db7d27375 | refs/heads/master | 2023-03-18T13:33:24.659489 | 2021-03-25T17:31:52 | 2021-03-25T17:31:52 | 326,259,412 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 732 | java | package home.javarush.javaCore.task12.task1228;
/*
Интерфейсы к классу Human
*/
public class Solution {
public static void main(String[] args) {
Human human = new Human();
System.out.println(human);
}
public static interface Worker {
public void workLazy();
}
public static interface Businessman {
public void workHard();
}
public static interface Secretary {
public void workLazy();
}
public static interface Miner {
public void workVeryHard();
}
public static class Human implements Worker, Secretary, Businessman{
public void workHard() {
}
public void workLazy() {
}
}
}
| [
"dmukha@mail.ru"
] | dmukha@mail.ru |
8a0113e49a89c910917875d48555dd059a50998e | 2ff78e0994cb710a619b79659d64d2617cc3e586 | /code/RecycleRush/src/frc492/Robot.java | 5df4a2ebf49c1a29a9d1f02e84262950bbe6fb4c | [
"MIT"
] | permissive | trc492/Frc2015RecycleRush | d2d662ff8ea653a9f2aad3fe444b98e1800de5e6 | 302e06aaa89560d20ed34fd89eac05f2d77805bb | refs/heads/master | 2021-01-10T01:59:40.009034 | 2018-05-27T19:32:48 | 2018-05-27T19:32:48 | 49,762,591 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 19,222 | java | package frc492;
import com.ni.vision.NIVision;
import com.ni.vision.NIVision.*;
import edu.wpi.first.wpilibj.BuiltInAccelerometer;
import edu.wpi.first.wpilibj.CANTalon;
import edu.wpi.first.wpilibj.CameraServer;
import edu.wpi.first.wpilibj.Gyro;
import edu.wpi.first.wpilibj.SpeedController;
import edu.wpi.first.wpilibj.Timer;
import frclibj.TrcAnalogInput;
import frclibj.TrcDashboard;
import frclibj.TrcDbgTrace;
import frclibj.TrcDriveBase;
import frclibj.TrcKalmanFilter;
import frclibj.TrcMotorPosition;
import frclibj.TrcPidController;
import frclibj.TrcPidDrive;
import frclibj.TrcPneumatic;
import frclibj.TrcRGBLight;
import frclibj.TrcRobot;
/**
* The VM is configured to automatically run this class, and to call the
* functions corresponding to each mode, as described in the TrcRobot
* documentation. If you change the name of this class or the package after
* creating this project, you must also update the manifest file in the
* resource directory.
*/
public class Robot
extends TrcRobot
implements TrcMotorPosition, TrcPidController.PidInput
{
private static final String programName = "RecycleRush";
private static final String moduleName = "Robot";
private static final boolean visionTargetEnabled = false;
private static final boolean debugDriveBase = false;
private static final boolean debugPidDrive = false;
private static final boolean debugPidElevator = false;
private static final boolean debugPidSonar = false;
private static boolean usbCameraEnabled = false;
private TrcDbgTrace dbgTrace = null;
// public static boolean competitionRobot = true;
//
// Sensors
//
private BuiltInAccelerometer accelerometer;
private TrcKalmanFilter accelXFilter;
private TrcKalmanFilter accelYFilter;
private TrcKalmanFilter accelZFilter;
public double robotTilt;
//
// DriveBase subsystem.
//
public Gyro gyro;
public CANTalon leftFrontMotor;
public CANTalon leftRearMotor;
public CANTalon rightFrontMotor;
public CANTalon rightRearMotor;
public TrcDriveBase driveBase;
public TrcPidController xPidCtrl;
public TrcPidController yPidCtrl;
public TrcPidController turnPidCtrl;
public TrcPidDrive pidDrive;
public TrcPidController sonarPidCtrl;
public TrcPidDrive sonarPidDrive;
//
// Define our subsystems for Auto and TeleOp modes.
//
public Elevator elevator;
public TrcPneumatic lowerGrabber;
public TrcPneumatic upperGrabber;
public TrcPneumatic pusher;
public TrcRGBLight rgbLight;
public TrcPneumatic leftHook;
public TrcPneumatic rightHook;
public Harpoon harpoon;
//
// Vision target subsystem.
//
public VisionTarget visionTarget = null;
//
// Camera subsystem.
//
private CameraServer cameraServer = null;
private int usbCamSession = -1;
private Image usbCamImage = null;
private double nextCaptureTime = Timer.getFPGATimestamp();
private static final String targetLeftKey = "Target Left";
private static final String targetRightKey = "Target Right";
private static final String targetTopKey = "Target Top";
private static final String targetBottomKey = "TargetBottom";
private static int targetLeft = 170;
private static int targetRight = 520;
private static int targetTop = 130;
private static int targetBottom = 440;
private static Rect targetRect =
new Rect(targetTop,
targetLeft,
targetBottom - targetTop,
targetRight - targetLeft);
//
// Robot Modes.
//
private RobotMode teleOpMode;
private RobotMode autoMode;
private RobotMode testMode;
//
// Ultrasonic subsystem (has a dependency on teleOpMode).
//
public TrcAnalogInput ultrasonic;
private TrcKalmanFilter sonarFilter;
public double sonarDistance;
private static final String dispenserDistanceKey = "Dispenser Distance";
public double dispenserDistance = 26.0;
/**
* Constructor.
*/
public Robot()
{
super(programName);
dbgTrace = new TrcDbgTrace(
moduleName,
false,
TrcDbgTrace.TraceLevel.API,
TrcDbgTrace.MsgLevel.INFO);
} //Robot
/**
* This function is run when the robot is first started up and should be
* used for any initialization code.
*/
@Override
public void robotInit()
{
final String funcName = "robotInit";
//
// Sensors.
//
accelerometer = new BuiltInAccelerometer();
accelXFilter = new TrcKalmanFilter();
accelYFilter = new TrcKalmanFilter();
accelZFilter = new TrcKalmanFilter();
//
// DriveBase subsystem.
//
gyro = new Gyro(RobotInfo.AIN_GYRO);
leftFrontMotor = new CANTalon(RobotInfo.CANID_LEFTFRONTMOTOR);
leftRearMotor = new CANTalon(RobotInfo.CANID_LEFTREARMOTOR);
rightFrontMotor = new CANTalon(RobotInfo.CANID_RIGHTFRONTMOTOR);
rightRearMotor = new CANTalon(RobotInfo.CANID_RIGHTREARMOTOR);
//
// Initialize each drive motor controller.
//
leftFrontMotor.setFeedbackDevice(CANTalon.FeedbackDevice.QuadEncoder);
leftRearMotor.setFeedbackDevice(CANTalon.FeedbackDevice.QuadEncoder);
rightFrontMotor.setFeedbackDevice(CANTalon.FeedbackDevice.QuadEncoder);
rightRearMotor.setFeedbackDevice(CANTalon.FeedbackDevice.QuadEncoder);
leftFrontMotor.reverseSensor(RobotInfo.LEFTFRONTMOTOR_INVERTED);
leftRearMotor.reverseSensor(RobotInfo.LEFTREARMOTOR_INVERTED);
rightFrontMotor.reverseSensor(RobotInfo.RIGHTFRONTMOTOR_INVERTED);
rightRearMotor.reverseSensor(RobotInfo.RIGHTREARMOTOR_INVERTED);
//
// Reset encoders.
//
leftFrontMotor.setPosition(0.0);
leftRearMotor.setPosition(0.0);
rightFrontMotor.setPosition(0.0);
rightRearMotor.setPosition(0.0);
//
// Initialize DriveBase subsystem.
//
driveBase = new TrcDriveBase(
leftFrontMotor,
leftRearMotor,
rightFrontMotor,
rightRearMotor,
this,
gyro);
driveBase.setInvertedMotor(
TrcDriveBase.MotorType.kFrontLeft,
RobotInfo.LEFTFRONTMOTOR_INVERTED);
driveBase.setInvertedMotor(
TrcDriveBase.MotorType.kRearLeft,
RobotInfo.LEFTREARMOTOR_INVERTED);
driveBase.setInvertedMotor(
TrcDriveBase.MotorType.kFrontRight,
RobotInfo.RIGHTFRONTMOTOR_INVERTED);
driveBase.setInvertedMotor(
TrcDriveBase.MotorType.kRearRight,
RobotInfo.RIGHTREARMOTOR_INVERTED);
//
// Create PID controllers for DriveBase PID drive.
//
xPidCtrl = new TrcPidController(
"xPidCtrl",
RobotInfo.X_KP,
RobotInfo.X_KI,
RobotInfo.X_KD,
RobotInfo.X_KF,
RobotInfo.X_TOLERANCE,
RobotInfo.X_SETTLING,
this,
0);
yPidCtrl = new TrcPidController(
"yPidCtrl",
RobotInfo.Y_KP,
RobotInfo.Y_KI,
RobotInfo.Y_KD,
RobotInfo.Y_KF,
RobotInfo.Y_TOLERANCE,
RobotInfo.Y_SETTLING,
this,
0);
turnPidCtrl = new TrcPidController(
"turnPidCtrl",
RobotInfo.TURN_KP,
RobotInfo.TURN_KI,
RobotInfo.TURN_KD,
RobotInfo.TURN_KF,
RobotInfo.TURN_TOLERANCE,
RobotInfo.TURN_SETTLING,
this,
0);
pidDrive = new TrcPidDrive(
"pidDrive",
driveBase,
xPidCtrl,
yPidCtrl,
turnPidCtrl);
sonarPidCtrl = new TrcPidController(
"sonarPidCtrl",
RobotInfo.SONAR_KP,
RobotInfo.SONAR_KI,
RobotInfo.SONAR_KD,
RobotInfo.SONAR_KF,
RobotInfo.SONAR_TOLERANCE,
RobotInfo.SONAR_SETTLING,
this,
(TrcPidController.PIDCTRLO_ABS_SETPT |
TrcPidController.PIDCTRLO_INVERTED));
sonarPidDrive =
new TrcPidDrive(
"sonarPidDrive",
driveBase,
xPidCtrl,
sonarPidCtrl,
turnPidCtrl);
//
// Elevator subsystem.
//
elevator = new Elevator();
//
// Grabber subsystem.
//
if (RobotInfo.ENABLE_LOWER_GRABBER)
{
lowerGrabber = new TrcPneumatic(
"lowerGrabber",
RobotInfo.CANID_PCM,
RobotInfo.SOL_LOWERGRABBER_EXTEND,
RobotInfo.SOL_LOWERGRABBER_RETRACT);
}
else
{
lowerGrabber = null;
}
if (RobotInfo.ENABLE_UPPER_GRABBER)
{
upperGrabber = new TrcPneumatic(
"upperGrabber",
RobotInfo.CANID_PCM,
RobotInfo.SOL_UPPERGRABBER_EXTEND,
RobotInfo.SOL_UPPERGRABBER_RETRACT);
}
else
{
upperGrabber = null;
}
//
// Pusher subsystem.
//
if (RobotInfo.ENABLE_PUSHER)
{
pusher = new TrcPneumatic(
"pusher",
RobotInfo.CANID_PCM,
RobotInfo.SOL_PUSHER_EXTEND);
}
else
{
pusher = null;
}
//
// RGB LED light
//
if (RobotInfo.ENABLE_LEDS)
{
rgbLight = new TrcRGBLight(
"rgbLight",
RobotInfo.CANID_PCM,
RobotInfo.SOL_LED_RED,
RobotInfo.SOL_LED_GREEN,
RobotInfo.SOL_LED_BLUE);
}
else
{
rgbLight = null;
}
//
// Hook subsystem.
//
if (RobotInfo.ENABLE_CAN_HOOKS)
{
leftHook = new TrcPneumatic(
"leftHook",
RobotInfo.CANID_PCM,
RobotInfo.SOL_LEFTHOOK_EXTEND,
RobotInfo.SOL_LEFTHOOK_RETRACT);
rightHook = new TrcPneumatic(
"rightHook",
RobotInfo.CANID_PCM,
RobotInfo.SOL_RIGHTHOOK_EXTEND,
RobotInfo.SOL_RIGHTHOOK_RETRACT);
}
else
{
leftHook = null;
rightHook = null;
}
//
// Harpoon subsystem.
//
if (RobotInfo.ENABLE_HARPOONS)
{
harpoon = new Harpoon();
}
else
{
harpoon = null;
}
//
// Vision subsystem.
//
if (visionTargetEnabled)
{
visionTarget = new VisionTarget();
}
else
{
visionTarget = null;
}
//
// Camera subsystem for streaming.
//
if (usbCameraEnabled)
{
try
{
usbCamSession = NIVision.IMAQdxOpenCamera(
RobotInfo.USB_CAM_NAME,
IMAQdxCameraControlMode.CameraControlModeController);
NIVision.IMAQdxConfigureGrab(usbCamSession);
NIVision.IMAQdxStartAcquisition(usbCamSession);
usbCamImage = NIVision.imaqCreateImage(ImageType.IMAGE_RGB, 0);
cameraServer = CameraServer.getInstance();
cameraServer.setQuality(30);
}
catch (Exception e)
{
usbCameraEnabled = false;
dbgTrace.traceWarn(
funcName, "Failed to open USB camera, disable it!");
}
}
//
// Robot Modes.
//
teleOpMode = new TeleOp(this);
autoMode = new Autonomous(this);
testMode = new Test();
setupRobotModes(teleOpMode, autoMode, testMode, null);
ultrasonic =
new TrcAnalogInput(
"frontSonar",
RobotInfo.AIN_ULTRASONIC,
RobotInfo.ULTRASONIC_INCHESPERVOLT,
dispenserDistance - 1.0,
dispenserDistance + 1.0,
0,
(TrcAnalogInput.AnalogEventHandler)teleOpMode);
sonarFilter = new TrcKalmanFilter();
dispenserDistance =
TrcDashboard.getNumber(dispenserDistanceKey, dispenserDistance);
} //robotInit
public void updateDashboard()
{
//
// Sensor info.
//
sonarDistance = sonarFilter.filter(ultrasonic.getData());
TrcDashboard.putNumber("Sonar Distance", sonarDistance);
double xAccel = accelXFilter.filter(accelerometer.getX());
double yAccel = accelYFilter.filter(accelerometer.getY());
double zAccel = accelZFilter.filter(accelerometer.getZ());
TrcDashboard.putNumber("Accel-X", xAccel);
TrcDashboard.putNumber("Accel-Y", yAccel);
TrcDashboard.putNumber("Accel-Z", zAccel);
robotTilt = zAccel;
if (yAccel < 0.0)
{
robotTilt = -robotTilt;
}
robotTilt = 180.0*Math.asin(robotTilt)/Math.PI;
TrcDashboard.putNumber("Tilt", robotTilt);
//
// Elevator info.
//
TrcDashboard.putNumber(
"Elevator Height", elevator.getHeight());
TrcDashboard.putBoolean(
"LowerLimitSW", !elevator.isLowerLimitSwitchActive());
TrcDashboard.putBoolean(
"UpperLimitSW", !elevator.isUpperLimitSwitchActive());
//
// USB camera streaming.
//
if (usbCameraEnabled && Timer.getFPGATimestamp() >= nextCaptureTime)
{
//
// Capture at 10fps.
//
nextCaptureTime = Timer.getFPGATimestamp() + 0.1;
NIVision.IMAQdxGrab(usbCamSession, usbCamImage, 1);
targetLeft = (int)
TrcDashboard.getNumber(targetLeftKey, targetLeft);
targetRight = (int)
TrcDashboard.getNumber(targetRightKey, targetRight);
targetTop = (int)
TrcDashboard.getNumber(targetTopKey, targetTop);
targetBottom = (int)
TrcDashboard.getNumber(targetBottomKey, targetBottom);
targetRect.left = targetLeft;
targetRect.top = targetTop;
targetRect.width = targetRight - targetLeft;
targetRect.height = targetBottom - targetTop;
NIVision.imaqDrawShapeOnImage(
usbCamImage,
usbCamImage,
targetRect,
DrawMode.DRAW_VALUE,
ShapeMode.SHAPE_RECT,
(float)0x0);
cameraServer.setImage(usbCamImage);
}
if (debugDriveBase)
{
//
// DriveBase debug info.
//
TrcDashboard.textPrintf(
1, "LFEnc=%8.0f, RFEnc=%8.0f",
leftFrontMotor.getPosition(),
rightFrontMotor.getPosition());
TrcDashboard.textPrintf(
2, "LREnc=%8.0f, RREnc=%8.0f",
leftRearMotor.getPosition(),
rightRearMotor.getPosition());
TrcDashboard.textPrintf(
3, "XPos=%6.1f, YPos=%6.1f, Heading=%6.1f",
driveBase.getXPosition()*RobotInfo.XDRIVE_INCHES_PER_CLICK,
driveBase.getYPosition()*RobotInfo.YDRIVE_INCHES_PER_CLICK,
driveBase.getHeading());
TrcDashboard.textPrintf(
4, "Ultrasonic=%5.1f", sonarDistance);
}
else if (debugPidDrive)
{
xPidCtrl.displayPidInfo(1);
yPidCtrl.displayPidInfo(3);
turnPidCtrl.displayPidInfo(5);
}
else if (debugPidElevator)
{
//
// Elevator debug info.
//
TrcDashboard.textPrintf(
1, "ElevatorHeight=%5.1f",
elevator.getHeight());
TrcDashboard.textPrintf(
2, "LowerLimit=%s, UpperLimit=%s",
Boolean.toString(elevator.isLowerLimitSwitchActive()),
Boolean.toString(elevator.isUpperLimitSwitchActive()));
elevator.displayDebugInfo(3);
}
else if (debugPidSonar)
{
xPidCtrl.displayPidInfo(1);
sonarPidCtrl.displayPidInfo(3);
turnPidCtrl.displayPidInfo(5);
}
} //updateDashboard
//
// Implements TrcDriveBase.MotorPosition.
//
public double getMotorPosition(SpeedController speedController)
{
return ((CANTalon)speedController).getPosition();
} //getMotorPosition
public double getMotorSpeed(SpeedController speedController)
{
return ((CANTalon)speedController).getSpeed()*10.0;
} //getMotorSpeed
public void resetMotorPosition(SpeedController speedController)
{
((CANTalon)speedController).setPosition(0.0);
} //resetMotorPosition
public void reversePositionSensor(
SpeedController speedController,
boolean flip)
{
((CANTalon)speedController).reverseSensor(flip);
} //reversePositionSensor
public boolean isForwardLimitSwitchActive(SpeedController speedController)
{
//
// There is no limit switches on the DriveBase.
//
return false;
} //isForwardLimitSwitchActive
public boolean isReverseLimitSwitchActive(SpeedController speedController)
{
//
// There is no limit switches on the DriveBase.
//
return false;
} //isReverseLimitSwitchActive
//
// Implements TrcPidController.PidInput.
//
public double getInput(TrcPidController pidCtrl)
{
double value = 0.0;
if (pidCtrl == xPidCtrl)
{
value = driveBase.getXPosition()*RobotInfo.XDRIVE_INCHES_PER_CLICK;
}
else if (pidCtrl == yPidCtrl)
{
value = driveBase.getYPosition()*RobotInfo.YDRIVE_INCHES_PER_CLICK;
}
else if (pidCtrl == turnPidCtrl)
{
value = gyro.getAngle();
}
else if (pidCtrl == sonarPidCtrl)
{
value = sonarDistance;
}
return value;
} //getInput
} //class Robot
| [
"trc492@live.com"
] | trc492@live.com |
38feb916679b6e122e1baea2ed8505e32d80643e | b92e7c1bbfbf09f74aa32c70d50bdf99b0f5aa20 | /RunamicGhent/mobile/src/main/java/com/dp16/runamicghent/Constants.java | b6ab921c6735899095520048fb10817a926cc0a9 | [
"MIT"
] | permissive | oSoc17/lopeningent_android | 57f44ffdd29448604fb9f17dffb50b49fbb8203e | 382278767ed317503945981838024055c020db06 | refs/heads/master | 2020-12-02T20:55:17.804823 | 2017-07-26T09:25:11 | 2017-07-26T09:25:11 | 96,228,367 | 3 | 0 | null | null | null | null | UTF-8 | Java | false | false | 14,831 | java | /*
* Copyright (c) 2017 Hendrik Depauw
* Copyright (c) 2017 Lorenz van Herwaarden
* Copyright (c) 2017 Nick Aelterman
* Copyright (c) 2017 Olivier Cammaert
* Copyright (c) 2017 Maxim Deweirdt
* Copyright (c) 2017 Gerwin Dox
* Copyright (c) 2017 Simon Neuville
* Copyright (c) 2017 Stiaan Uyttersprot
*
* This software may be modified and distributed under the terms of the MIT license. See the LICENSE file for details.
*/
package com.dp16.runamicghent;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.LatLngBounds;
import java.util.Objects;
/**
* Class containing public static final constants used throughout the application.
* All classes have private constructor, because these classes only contain values.
* Created by hendrikdepauw on 01/03/2017.
*/
public class Constants {
// Is this a debug environment?
public static final Boolean DEVELOP = true;
private static final String UTILITY_CLASS_ERROR = "Utility Class";
/**
* Server configuration constants.
*/
public class Server {
public static final String ADDRESS = "groep16.cammaert.me";
public static final String MONGOPORT = "27017";
private Server() {
throw new IllegalAccessError(UTILITY_CLASS_ERROR);
}
}
/**
* Smoothing toggle.
*/
public class Smoothing {
public static final boolean SMOOTHING_ENABLED = true;
private Smoothing() {
throw new IllegalAccessError(UTILITY_CLASS_ERROR);
}
}
/**
* Constants for setting keys
*/
public class SettingTypes {
public static final String PREF_KEY_DEBUG_LOCATION_MOCK = "pref_key_debug_location_mock";
public static final String PREF_KEY_DEBUG_FAKE_LATLNG_LOCATIONPROVIDER = "pref_key_debug_fake_latlng_locationprovider";
public static final String PREF_KEY_DEBUG_ROUTE_SMOOTHER = "pref_key_debug_route_smoother";
public static final String PREF_KEY_ROUTING_PARK = "pref_key_dynamic_park";
public static final String PREF_KEY_ROUTING_WATER = "pref_key_dynamic_water";
public static final String PREF_KEY_AUDIO_DIRECTIONS = "pref_key_audio_directions";
public static final String PREF_KEY_AUDIO_CUSTOM_SOUND = "pref_key_audio_custom_sound";
public static final String PREF_KEY_AUDIO_LEFT_RIGHT_CHANNEL = "pref_key_audio_left_right_channel";
public static final String USER_WENT_THROUGH_TOURGUIDE_START = "user_went_through_tourguide_start";
public static final String USER_WENT_THROUGH_TOURGUIDE_HISTORY = "user_went_through_tourguide_history";
public static final String USER_WENT_THROUGH_TOURGUIDE_SETTINGS = "user_went_through_tourguide_settings";
private SettingTypes() {
throw new IllegalAccessError(UTILITY_CLASS_ERROR);
}
}
/**
* Constants for all types of events that are processed by EventBroker.
*/
public class EventTypes {
public static final String LOCATION = "LOCATION";
public static final String LOCATION_ACCURATE = "LOCATION_ACCURATE";
public static final String RAW_LOCATION = "RAW_LOCATION";
public static final String SPEED = "SPEED";
public static final String TRACK = "TRACK";
public static final String TRACK_REQUEST = "TRACK_REQUEST";
public static final String TRACK_LOADED = "TRACK_LOADED";
public static final String RATING = "RATING";
public static final String DISTANCE = "DISTANCE";
public static final String DURATION = "DURATION";
public static final String IS_IN_CITY = "IS_IN_CITY";
public static final String NOT_IN_CITY = "NOT_IN_CITY";
public static final String STATUS_CODE = "STATUS_CODE";
public static final String IN_CITY = "IN_CITY";
// Dynamic routing
public static final String OFFROUTE = "OFFROUTE";
public static final String ABNORMAL_HEART_RATE = "ABNORMAL_HEART_RATE";
//Storage
public static final String STORE_RUNNINGSTATISTICS = "STORE_RUNNINGSTATISTICS";
public static final String LOAD_RUNNINGSTATISTICS = "LOAD_RUNNINGSTATISTICS";
public static final String LOADED_RUNNINGSTATISTICS = "LOADED_RUNNINGSTATISTICS";
public static final String DELETE_RUNNINGSTATISTICS = "DELETE_RUNNINGSTATISTICS";
public static final String STORE_AGGREGATESTATISTICS = "STORE_AGGREGATESTATISTICS";
public static final String LOAD_AGGREGATESTATISTICS = "LOAD_AGGREGATESTATISTICS";
public static final String LOADED_AGGREGATESTATISTICS = "LOADED_AGGREGATESTATISTICS";
public static final String DELETE_AGGREGATESTATISTICS = "DELETE_AGGREGATESTATISTICS";
public static final String SYNC_WITH_DATABASE = "SYNC_WITH_DATABASE";
//Navigation
public static final String NAVIGATION_DIRECTION = "NAVIGATION_DIRECTION";
public static final String SPLIT_POINT = "SPLIT_POINT";
public static final String AUDIO = "AUDIO";
//android wear event types
public static final String HEART_RESPONSE = "HEART_RESPONSE";
public static final String START_WEAR = "START_WEAR";
public static final String STOP_WEAR = "STOP_WEAR";
public static final String PAUSE_WEAR = "PAUSE_WEAR";
private EventTypes() {
throw new IllegalAccessError(UTILITY_CLASS_ERROR);
}
}
/**
* Constants for communication with android wear device
*/
public class WearMessageTypes {
//from wear to mobile
public static final String HEART_RATE_MESSAGE_WEAR = "/heartRateMessageWear";
public static final String REQUEST_STATE_MESSAGE_WEAR = "/requestStateMessageWear";
//from mobile to wear
public static final String START_RUN_MOBILE = "/startRun";
public static final String STOP_RUN_MOBILE = "/stopRun";
public static final String PAUSE_RUN_MOBILE = "/pauseRun";
//navigation constants
public static final String NAVIGATE_LEFT = "/navigateLeft";
public static final String NAVIGATE_RIGHT = "/navigateRight";
public static final String NAVIGATE_STRAIGHT = "/navigateStraight";
public static final String NAVIGATE_UTURN = "/navigateUTurn";
public static final String RUN_STATE_START_MESSAGE_MOBILE = "/runStateStart";
public static final String RUN_STATE_PAUSED_MESSAGE_MOBILE = "/runStateStop";
public static final String TIME_UPDATE_MESSAGE_MOBILE = "/timeUpdate";
public static final String SPEED_UPDATE_MESSAGE_MOBILE = "/speedUpdate";
public static final String DISTANCE_UPDATE_MESSAGE_MOBILE = "/distanceUpdate";
private WearMessageTypes() {
throw new IllegalAccessError(UTILITY_CLASS_ERROR);
}
}
/**
* Constants for activities (for GuiController)
*/
public class ActivityTypes {
public static final String MAINMENU = "MAINMENU";
public static final String RUNNINGVIEW = "RUNNINGVIEW";
public static final String RESTTEST = "RESTTEST";
public static final String DEBUG = "DEVELOP";
public static final String HISTORYEXPANDED = "HISTORYEXPANDED";
public static final String LOGIN = "LOGIN";
public static final String SETTINGS = "SETTINGS";
public static final String CHANGEPROFILE = "CHANGEPROFILE";
public static final String LICENCES = "LICENCES";
private ActivityTypes() {
throw new IllegalAccessError(UTILITY_CLASS_ERROR);
}
}
/**
* Constants used by {@link RouteChecker}.
*/
public class RouteChecker {
// Interval between onRouteChecker messages
public static final int INTERVAL = 5000;
// Accuracy for onRouteChecker
public static final int ACCURACY = 40;
private RouteChecker() {
throw new IllegalAccessError(UTILITY_CLASS_ERROR);
}
}
/**
* Constants for displaying Google Maps.
*/
public class MapSettings {
// Constant used in the location settings dialog.
public static final int REQUEST_CHECK_SETTINGS = 0x1;
// The desired interval for location updates. Inexact. Updates may be more or less frequent.
public static final long UPDATE_INTERVAL = 2000;
// The fastest rate for active location updates. Exact. Updates will never be more frequent than this value.
public static final long FASTEST_UPDATE_INTERVAL = 1000;
// Smallest displacement needed in meters before new location update is received
public static final float SMALLEST_DISPLACEMENT = 2.0f;
// Max Zoom level for google map
public static final float MAX_ZOOM = 19.0f;
// Min zoom level for google map
public static final float MIN_ZOOM = 10.0f;
// Desired zoom level for google map
public static final float DESIRED_ZOOM = 17.0f;
// Does Google RunningMap need compass
public static final boolean COMPASS = true;
// Can Google Maps be tilted
public static final boolean TILT = false;
// Padding to be added (in dp) to the bounding box of the displayed route
public static final int ROUTE_PADDING = 20;
// Padding to be added (in dp) to left and right side of map
public static final int SIDE_MAP_PADDING = 8;
// Number of samples for the rolling average
public static final int ROLLING_SIZE = 4;
// Discount factor is used for rotating map. It determines how much influence the newly calculated bearing has.
public static final float DISCOUNT_FACTOR = 0.5f;
public static final String STATIC_MAPS_KEY = "AIzaSyAl3P4q7jc4il8jVmGGZk6f-BwsNeC_xyc";
private MapSettings() {
throw new IllegalAccessError(UTILITY_CLASS_ERROR);
}
}
/**
* Constant strings, used for persistence.
*/
public class Storage {
public static final String RUNNINGSTATISTICSDIRECTORY = "runningstatistics";
public static final String RUNNINGSTATISTICSGHOSTDIRECTORY = "runningstatisticsghost";
public static final String AGGREGATERUNNINGSTATISTICSDIRECTORY = "aggregaterunningstatistics";
public static final String RUNNINGSTATISTICSCOLLECTION = "runningStatistics";
public static final String RUNNINGSTATISTICSGHOSTCOLLECTION = "runningStatisticsGhost";
public static final String AGGREGATERUNNINGSTATISTICSCOLLECTION = "aggregateRunningStatistics";
public static final int MINUTES_BETWEEN_SERVER_SYNC_TRIES = 15;
public static final String MONGODBNAME = "DRIG_userdata";
public static final String MONGOUSER = "client";
public static final String MONGOPASS = "dynamicrunninginghentSmart";
// Logger name found by decompiling the mongodb java driver jar
// Consider this unstable. That is no problem as we would only get a lot of logging messages if this would break.
public static final String LOGGERNAME = "org.mongodb.driver.cluster";
public static final boolean TURNOFFLOGGING = true;
private Storage() {
throw new IllegalAccessError(UTILITY_CLASS_ERROR);
}
}
/**
* All cities the app supports.
*/
public static class Cities {
public static final String GHENT = "GHENT";
protected static final String[] CITY_LIST = {GHENT};
private Cities() {
throw new IllegalAccessError("Utility class");
}
public static boolean cityIsKnown(String city) {
for (String city1 : CITY_LIST) {
if (Objects.equals(city1, city))
return true;
}
return false;
}
}
/**
* Bounding boxes containing Ghent.
* Used by {@link com.dp16.runamicghent.DataProvider.InCityChecker}
*/
public static class CityBoundingBoxes {
//Coordinate "box" containing the city of Ghent.
public static final LatLngBounds latLngBoundGhent = new LatLngBounds(new LatLng(50.8077000, 3.0350000), new LatLng(51.3014000, 4.1858000));
private CityBoundingBoxes() {
throw new IllegalAccessError("Utility class");
}
}
/**
* Constants for location updates
*/
public static class Location {
// Constants used to check if the location updates are accurate/inaccurate
public static final float MAX_GOOD_ACCURACY = 10.0f;
public static final float MIN_BAD_ACCURACY = 14.0f;
public static final int COUNTER_MAX = 3;
private Location() {
throw new IllegalAccessError(UTILITY_CLASS_ERROR);
}
}
/**
* Constants used for route generation.
*/
public static class RouteGenerator {
public static final double MINIMAL_BOUND = 0.5;
public static final double MAXIMAL_BOUND = 1.0;
public static final double FRACTION_BOUND = 0.1;
public static final double FIRST_BORDER = MINIMAL_BOUND / FRACTION_BOUND;
public static final double SECOND_BORDER = MAXIMAL_BOUND / FRACTION_BOUND;
public static final int MIN_LENGTH = 1;
public static final int MAX_LENGTH = 50;
public static final int DEFAULT_LENGTH = 5;
private RouteGenerator() {
throw new IllegalAccessError(UTILITY_CLASS_ERROR);
}
}
/**
* Constants for dynamic routing
*/
public static class DynamicRouting {
// Min and Max values for rangebar
public static final int RANGEBAR_LOW = 60;
public static final int RANGEBAR_HIGH = 210;
// Standard upper and lower heart rate limit
public static final int HEART_RATE_LOWER = 130;
public static final int HEART_RATE_UPPER = 170;
// Min and Max values for slider
public static final int SLIDER_LOW = 0;
public static final int SLIDER_HIGH = 100;
// Default slider position
public static final int DEFAULT_SLIDER = 20;
// Number of samples for the rolling average
public static final int ROLLING_SIZE = 4;
// Minimal time that rolling average of heart rate needs to be under lower limit or above upper limit
public static final long HEART_RATE_MIN_TIME = 1000 * 60L;
// Time to wait after a Abnormal heart rate event has been set
public static final long HEART_RATE_WAIT_TIME = 5 * 1000 * 60L;
public static final String TAG_LOWER = "LOWER";
public static final String TAG_UPPER = "UPPER";
private DynamicRouting() {
throw new IllegalAccessError(UTILITY_CLASS_ERROR);
}
}
}
| [
"timbaccaert@gmail.com"
] | timbaccaert@gmail.com |
db514262a384ded966ce770bc2daf0a795eb0774 | f4dfe52bd506f1508637f23f1d9822c659891c12 | /PROFILING/CPUProfiling/src/main/java/com/lowagie/examples/objects/tables/DefaultCell.java | 1320f6ef842f01c266295c4786687d0e332803a9 | [] | no_license | siddhantaws/LowLatency | 5b27b99b8fbe3a98029ca42f636b49d870a0b3bb | f245916fed8bfe5a038dc21098d813bf5accdb1e | refs/heads/master | 2021-06-25T19:55:07.994337 | 2019-09-19T15:39:15 | 2019-09-19T15:39:15 | 152,133,438 | 0 | 0 | null | 2020-10-13T16:09:28 | 2018-10-08T19:17:54 | Java | UTF-8 | Java | false | false | 2,330 | java | /*
* $Id: DefaultCell.java,v 1.3 2005/05/09 11:52:47 blowagie Exp $
* $Name: $
*
* This code is part of the 'iText Tutorial'.
* You can find the complete tutorial at the following address:
* http://itextdocs.lowagie.com/tutorial/
*
* This code is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
*
* itext-questions@lists.sourceforge.net
*/
package com.lowagie.examples.objects.tables;
import java.awt.Color;
import java.io.FileOutputStream;
import java.io.IOException;
import com.lowagie.text.Document;
import com.lowagie.text.DocumentException;
import com.lowagie.text.Paragraph;
import com.lowagie.text.pdf.PdfPCell;
import com.lowagie.text.pdf.PdfPTable;
import com.lowagie.text.pdf.PdfWriter;
/**
* A very simple PdfPTable example using getDefaultCell().
*/
public class DefaultCell {
/**
* Demonstrates the use of getDefaultCell().
*
* @param args
* no arguments needed
*/
public static void main(String[] args) {
System.out.println("DefaultCell");
// step 1: creation of a document-object
Document document = new Document();
try {
// step 2:
// we create a writer that listens to the document
// and directs a PDF-stream to a file
PdfWriter.getInstance(document, new FileOutputStream("DefaultCell.pdf"));
// step 3: we open the document
document.open();
PdfPTable table = new PdfPTable(3);
PdfPCell cell = new PdfPCell(new Paragraph("header with colspan 3"));
cell.setColspan(3);
table.addCell(cell);
table.addCell("1.1");
table.addCell("2.1");
table.addCell("3.1");
table.getDefaultCell().setGrayFill(0.8f);
table.addCell("1.2");
table.addCell("2.2");
table.addCell("3.2");
table.getDefaultCell().setGrayFill(0f);
table.getDefaultCell().setBorderColor(new Color(255, 0, 0));
table.addCell("cell test1");
table.getDefaultCell().setColspan(2);
table.getDefaultCell().setBackgroundColor(new Color(0xC0, 0xC0, 0xC0));
table.addCell("cell test2");
document.add(table);
} catch (DocumentException de) {
System.err.println(de.getMessage());
} catch (IOException ioe) {
System.err.println(ioe.getMessage());
}
// step 5: we close the document
document.close();
}
} | [
"siddhantaws@gmail.com"
] | siddhantaws@gmail.com |
7629c0f2976a64367115b054179570383e7d33ec | 8a27c18ec9774c6dcbfdfce4e0bd5461b0594b08 | /src/org/opensha/refFaultParamDb/gui/addEdit/deformationModel/DeformationModelTableModel.java | 0774e2552d8f5f83334fa54a716ac863a134597d | [
"Apache-2.0"
] | permissive | GNS-Science/opensha-core | 81b96bca74254082fc83e8f7cebf67c24312d722 | 75143f6dd0b1d268471bfa55be8c7bd6ef559d73 | refs/heads/master | 2023-05-03T16:56:52.342902 | 2021-05-12T01:48:08 | 2021-05-12T01:48:08 | 364,415,943 | 0 | 0 | Apache-2.0 | 2021-05-10T03:07:31 | 2021-05-04T23:51:04 | Java | UTF-8 | Java | false | false | 3,606 | java | /**
*
*/
package org.opensha.refFaultParamDb.gui.addEdit.deformationModel;
import java.util.ArrayList;
import java.util.HashMap;
import javax.swing.table.DefaultTableModel;
import org.opensha.refFaultParamDb.dao.db.DB_AccessAPI;
import org.opensha.refFaultParamDb.dao.db.DB_ConnectionPool;
import org.opensha.refFaultParamDb.dao.db.DeformationModelDB_DAO;
import org.opensha.refFaultParamDb.dao.db.FaultSectionVer2_DB_DAO;
import org.opensha.refFaultParamDb.vo.EstimateInstances;
import org.opensha.refFaultParamDb.vo.FaultSectionSummary;
/**
*
* Deformation model table model
* @author vipingupta
*
*/
public class DeformationModelTableModel extends DefaultTableModel {
/**
*
*/
private static final long serialVersionUID = 1L;
private final static String []columnNames = { "Section Name", "Slip Rate", "Aseismic Slip Factor"};
private int deformationModelId;
private ArrayList<Integer> faultSectionsInModel;
private HashMap<Integer, String> faultSectionsSummaryMap = new HashMap<Integer, String>();
private FaultSectionVer2_DB_DAO faultSectionDB_DAO;
private DeformationModelDB_DAO deformationModelDAO;
private ArrayList<FaultSectionSummary> faultSectionSummries;
public DeformationModelTableModel(DB_AccessAPI dbConnection) {
faultSectionDB_DAO = new FaultSectionVer2_DB_DAO(dbConnection);
deformationModelDAO = new DeformationModelDB_DAO(dbConnection);
faultSectionSummries = faultSectionDB_DAO.getAllFaultSectionsSummary();
for(int i=0; i<faultSectionSummries.size(); ++i) {
FaultSectionSummary faultSectionSummary = (FaultSectionSummary)faultSectionSummries.get(i);
faultSectionsSummaryMap.put(new Integer(faultSectionSummary.getSectionId()), faultSectionSummary.getSectionName());
}
}
public void setDeformationModel(int deformationModelId, ArrayList faultSectionIdList) {
this.deformationModelId = deformationModelId;
faultSectionsInModel = new ArrayList();
for(int i=0; i<faultSectionSummries.size(); ++i) {
FaultSectionSummary faultSectionSummary = (FaultSectionSummary)faultSectionSummries.get(i);
if(faultSectionIdList.contains(new Integer(faultSectionSummary.getSectionId())))
faultSectionsInModel.add(new Integer(faultSectionSummary.getSectionId()));
}
}
public int getdeformationModelId() {
return deformationModelId;
}
public int getColumnCount() {
return columnNames.length;
}
public Class getColumnClass(int col) {
if(col==0) return String.class;
else return EstimateInstances.class;
}
public int getRowCount() {
int numRows = 0;
if(faultSectionsInModel!=null) numRows = faultSectionsInModel.size();
return numRows;
}
public String getColumnName(int col) {
return columnNames[col];
}
public int getFaultSectionId(int row) {
return ((Integer)faultSectionsInModel.get(row)).intValue();
}
public Object getValueAt(int row, int col) {
int faultSectionId= ((Integer)faultSectionsInModel.get(row)).intValue();
return faultSectionsSummaryMap.get(new Integer(faultSectionId));
}
public Object getValueForSlipAndAseismicFactor(int row, int col) {
int faultSectionId= ((Integer)faultSectionsInModel.get(row)).intValue();
if(col==2) { //aseismic slip factor
return deformationModelDAO.getAseismicSlipEstimate(deformationModelId, faultSectionId);
} else if(col==1) { // slip rate
return deformationModelDAO.getSlipRateEstimate(deformationModelId, faultSectionId);
}
return faultSectionsInModel.get(row);
}
/*
* Don't need to implement this method unless your table's
* editable.
*/
public boolean isCellEditable(int row, int col) {
return false;
}
}
| [
"kmilner@usc.edu"
] | kmilner@usc.edu |
e2fd56cdbd0ecfc5a6529eb7a9646fb4d7877a80 | 1ac3fe76f01fbaaa8303d7ce3def6b4d0a8b546c | /Tag_Content_Extractor.java | 2e5914d96afdeaed109687e7521f4021488e95a1 | [] | no_license | manish160993/HackerrankPrograms | 63592eee912ba539e62e2c0ea56c06ce0509ae57 | 18a87f4ed4e94ba2729b8eb9c6ac32d1ddd3099a | refs/heads/master | 2021-05-13T14:34:12.478000 | 2018-01-22T18:08:38 | 2018-01-22T18:08:38 | 116,744,644 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 2,411 | java | /*
In a tag-based language like XML or HTML, contents are enclosed between a start tag and an end tag like <tag>contents</tag>. Note that the corresponding end tag starts with a /.
Given a string of text in a tag-based language, parse this text and retrieve the contents enclosed within sequences of well-organized tags meeting the following criterion:
The name of the start and end tags must be same. The HTML code <h1>Hello World</h2> is not valid, because the text starts with an h1 tag and ends with a non-matching h2 tag.
Tags can be nested, but content between nested tags is considered not valid. For example, in <h1><a>contents</a>invalid</h1>, contents is valid but invalid is not valid.
Tags can consist of any printable characters.
Input Format
The first line of input contains a single integer, (the number of lines).
The subsequent lines each contain a line of text.
Constraints
Each line contains a maximum of printable characters.
The total number of characters in all test cases will not exceed .
Output Format
For each line, print the content enclosed within valid tags.
If a line contains multiple instances of valid content, print out each instance of valid content on a new line; if no valid content is found, print None.
Sample Input
4
<h1>Nayeem loves counseling</h1>
<h1><h1>Sanjay has no watch</h1></h1><par>So wait for a while</par>
<Amee>safat codes like a ninja</amee>
<SA premium>Imtiaz has a secret crush</SA premium>
Sample Output
Nayeem loves counseling
Sanjay has no watch
So wait for a while
None
Imtiaz has a secret crush
*/
import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/* Solution assumes we can't have the symbol "<" as text between tags */
public class Tag_Content_Extractor{
public static void main(String[] args){
Scanner scan = new Scanner(System.in);
int testCases = Integer.parseInt(scan.nextLine());
while (testCases-- > 0) {
String line = scan.nextLine();
boolean matchFound = false;
Pattern r = Pattern.compile("<(.+)>([^<]+)</\\1>");
Matcher m = r.matcher(line);
while (m.find()) {
System.out.println(m.group(2));
matchFound = true;
}
if ( ! matchFound) {
System.out.println("None");
}
}
}
} | [
"manish160993@gmail.com"
] | manish160993@gmail.com |
f57f00c4712b38766c44bbf4c4e5eae380e34ae9 | 97cda285663a8bbf751b39321b695d97b6f69474 | /Wicket/src/wicket/util/diff/RevisionVisitor.java | 175c2c5cafe98fbc76c6cf1232f7a6a00a6eae8e | [] | no_license | clustercompare/clustercompare-data | 838c4de68645340546dd5e50b375dcf877591b3e | 163d05bdc5f4a03da8155ffb1f922a9421733589 | refs/heads/master | 2020-12-25T23:10:16.331657 | 2015-12-11T10:37:43 | 2015-12-11T10:37:43 | 39,699,972 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 3,257 | java | /*
* ====================================================================
*
* The Apache Software License, Version 1.1
*
* Copyright (c) 1999-2003 The Apache Software Foundation.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* 3. The end-user documentation included with the redistribution, if
* any, must include the following acknowledgement:
* "This product includes software developed by the
* Apache Software Foundation (http://www.apache.org/)."
* Alternately, this acknowledgement may appear in the software itself,
* if and wherever such third-party acknowledgements normally appear.
*
* 4. The names "The Jakarta Project", "Commons", and "Apache Software
* Foundation" must not be used to endorse or promote products derived
* from this software without prior written permission. For written
* permission, please contact apache@apache.org.
*
* 5. Products derived from this software may not be called "Apache"
* nor may "Apache" appear in their names without prior written
* permission of the Apache Software Foundation.
*
* THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR
* ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
* USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
* OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package wicket.util.diff;
/**
* Definition of a Visitor interface for {@link Revision Revisions} See "Design
* Patterns" by the Gang of Four
*/
public interface RevisionVisitor
{
/**
* @param revision
*/
public void visit(Revision revision);
/**
* @param delta
*/
public void visit(DeleteDelta delta);
/**
* @param delta
*/
public void visit(ChangeDelta delta);
/**
* @param delta
*/
public void visit(AddDelta delta);
} | [
"mail@jan-melcher.de"
] | mail@jan-melcher.de |
3e4942216774533eef6bc671c438f95a9a2d90f0 | 16ff6e8ad5d76a3cfcd9ac511f515eba988bf80d | /app/src/main/java/com/example/app_zing/activity/dangnhap.java | 14bc24b574abd025997f1dbaa14b1b88537259c1 | [] | no_license | caoquocdat12092001/android | 27eb0c3e8bc5d68d508096658abf12f50fb46141 | 85ba835f0019b8a6bf0cac895b40828afe7b4893 | refs/heads/master | 2022-12-05T02:13:05.432283 | 2020-08-26T19:13:52 | 2020-08-26T19:13:52 | 290,573,661 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 4,286 | java | package com.example.app_zing.activity;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.View;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.Toast;
import com.example.app_zing.R;
import com.google.android.material.textfield.TextInputLayout;
public class dangnhap extends AppCompatActivity {
Button dangnhap ,btndnchuyendangki;
TextInputLayout etuser, etpass;
CheckBox cbremember;
DatabaseHepper db;
SharedPreferences sharedPreferences;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.activity_dangnhap);
// db = new DatabaseHepper(this);
db = new DatabaseHepper(this,DatabaseHepper.DBNAME,null,1);
anhxa();
sharedPreferences = getSharedPreferences("datalogin",MODE_PRIVATE);
String idname = sharedPreferences.getString("taikhoan","");
String idpass = sharedPreferences.getString("matkhau","");
boolean idcheck = sharedPreferences.getBoolean("check", false);
// if (idcheck == true){
// Intent intent = new Intent(dangnhap.this,manhinhgiaodien.class);
// startActivity(intent);
// }
btndnchuyendangki.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent intent1 = new Intent(dangnhap.this,dangki.class);
startActivity(intent1);
}
});
dangnhap.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
String user = etuser.getEditText().getText().toString().trim();
String pass = etpass.getEditText().getText().toString().trim();
if (user.equals("") || pass.equals("")) {
etuser.setError("Field can't be empty");
etpass.setError("Field can't be empty");
}
Boolean checkuserpass = db.checkuserpass(user, pass);
if (checkuserpass == true && cbremember.isChecked()){
Toast.makeText(dangnhap.this, "đăng nhập thành công", Toast.LENGTH_SHORT).show();
//cjinhr sửa nội dung file
SharedPreferences.Editor editor = sharedPreferences.edit();
//put giá trị vào
editor.putString("taikhoan", user);
editor.putString("matkhau", pass);
editor.putBoolean("check", true);
editor.commit();
Intent intent = new Intent(dangnhap.this,manhinhgiaodien.class);
intent.putExtra("user",user);
startActivity(intent);
overridePendingTransition(R.anim.top, R.anim.top);
}else if (checkuserpass == true){
SharedPreferences.Editor editor = sharedPreferences.edit();
//put giá trị vào
editor.putString("taikhoan", user);
editor.putString("matkhau", pass);
editor.putBoolean("check", false);
editor.commit();
Intent intent = new Intent(dangnhap.this,manhinhgiaodien.class);
intent.putExtra("user",user);
startActivity(intent);
overridePendingTransition(R.anim.top, R.anim.top);
}else {
Toast.makeText(dangnhap.this, "tân tài khoản hoặc mật khẩu sai", Toast.LENGTH_SHORT).show();
}
}
});
}
private void anhxa() {
dangnhap = findViewById(R.id.dangnhap);
btndnchuyendangki = findViewById(R.id.btndnchuyendangki);
etpass = findViewById(R.id.etpass);
etuser = findViewById(R.id.etuser);
cbremember = findViewById(R.id.cbremember);
}
} | [
"quocdatcao1@gmail.com"
] | quocdatcao1@gmail.com |
705e7ff038c2bbf52bc41c37bb02e164dd4479a4 | 60f47552491c36429b09fdc8909ff04553503049 | /src/com/denghj/jdk_8/stream/stream基本操作/TestStreamApi01.java | 783b592f8ba8b3c7657bdf96ea834751c2ac31cc | [] | no_license | denghuaijun/java_se | f5ad737e25b0191fdb358acb166146838e7c63c4 | f52cac0506a268328282c922ba5eea8cf1250f6a | refs/heads/master | 2023-06-19T01:45:52.152802 | 2021-07-15T07:24:21 | 2021-07-15T07:24:21 | 327,215,887 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,421 | java | package com.denghj.jdk_8.stream.stream基本操作;
import com.denghj.jdk_8.lambda.基本语法.Employee;
import org.junit.Test;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Stream;
/**
* 一、Stream 三大操作步骤:
* 1. 创建stream
* 2.中间操作:即流水线操作 将数据源(集合、数组)的数据经过一系列的中间操作
* 3.终止操作:获取stream流所持有的结果
*/
public class TestStreamApi01 {
//1、测试 创建stream对象 共四种方式
@Test
public void createStream(){
//方式1、通过Collection中的stream()方法创建
List<Employee> employeeList = new ArrayList<>();
//employeeList.parallelStream()创建并行流,默认为串行流
Stream<Employee> stream = employeeList.stream();
//方式2、通过Stream api中的静态方法of()
Stream<String> stringStream = Stream.of("a", "b", "c");
stringStream.forEach(System.out::println);
//方式3、通过Arrays中的静态方法stream()获取数组流
Stream<Employee> employeeStream = Arrays.stream(new Employee[10]);
//方式4、创建无限流
//无限流1:无限迭代
Stream<Integer> iterate = Stream.iterate(0, x -> x + 2);
//无线流2:产生数据
Stream<Double> generate = Stream.generate(Math::random);
}
}
| [
"dhjtobenumber1@163.com"
] | dhjtobenumber1@163.com |
2e62d0732fb47b7c6eb7cf4b8450e6404ac4faaa | 5b9b654e77c1562a367254461c0b6e5933be31c5 | /src/LeetCode496_下一个更大元素I.java | e3e5d61677a3cd674b039e76be3d759deea6fb23 | [] | no_license | sparkfengbo/LeetcodeSourceJava | 865d7328899d09b5e1b7164edb2a6a91b4a48e4a | 26b6e5f827822a18a0482623acb24fe363cd9374 | refs/heads/master | 2022-05-30T15:10:42.561864 | 2022-05-18T04:56:57 | 2022-05-18T04:56:57 | 146,726,852 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 4,830 | java | import java.util.*;
/**
* 下一个更大元素 I
* 给定两个没有重复元素的数组 nums1 和 nums2 ,其中nums1 是 nums2 的子集。找到 nums1 中每个元素在 nums2 中的下一个比其大的值。
* <p>
* nums1 中数字 x 的下一个更大元素是指 x 在 nums2 中对应位置的右边的第一个比 x 大的元素。如果不存在,对应位置输出-1。
* <p>
* 示例 1:
* <p>
* 输入: nums1 = [4,1,2], nums2 = [1,3,4,2].
* 输出: [-1,3,-1]
* 解释:
* 对于num1中的数字4,你无法在第二个数组中找到下一个更大的数字,因此输出 -1。
* 对于num1中的数字1,第二个数组中数字1右边的下一个较大数字是 3。
* 对于num1中的数字2,第二个数组中没有下一个更大的数字,因此输出 -1。
* 示例 2:
* <p>
* 输入: nums1 = [2,4], nums2 = [1,2,3,4].
* 输出: [3,-1]
* 解释:
* 对于num1中的数字2,第二个数组中的下一个较大数字是3。
* 对于num1中的数字4,第二个数组中没有下一个更大的数字,因此输出 -1。
* 注意:
* <p>
* nums1和nums2中所有元素是唯一的。
* nums1和nums2 的数组大小都不超过1000。
*/
public class LeetCode496_下一个更大元素I {
public static void main(String[] args) {
Solution solution = new Solution();
// System.out.println(Arrays.toString(nextGreaterElement(new int[]{4, 1, 2}, new int[]{1, 3, 4, 2})));
System.out.println(Arrays.toString(solution
.nextGreaterElement(new int[]{1,3,5,2,4}, new int[]{6,5,4,3,2,1,7})));
}
//暴力 速度太慢
// public static int[] nextGreaterElement(int[] nums1, int[] nums2) {
// ArrayList<Integer> list = new ArrayList<>();
//
// for (int i = 0; i < nums2.length; i++) {
// list.add(nums2[i]);
// }
//
// List<Integer> resultArray = new ArrayList<>();
// for (int i = 0; i < nums1.length; i++) {
// int index = list.indexOf(nums1[i]);
//// System.out.println(index + " " + nums1[i]);
//
// boolean isFind = false;
// int j = 0;
// if (index >= 0) {
// for (j = index + 1; j < nums2.length; j++) {
// if (nums2[j] > nums1[i]) {
// isFind = true;
// break;
// }
// }
// }
//
// if (isFind) {
// resultArray.add(nums2[j]);
// } else {
// resultArray.add(-1);
// }
// }
//
//
// int[] result = new int[resultArray.size()];
//
// for (int i = 0; i < resultArray.size(); i++) {
// result[i] = resultArray.get(i);
// }
//
// return result;
// }
class Solution_leetcode {
public int[] nextGreaterElement(int[] nums1, int[] nums2) {
Map<Integer, Integer> map = new HashMap<Integer, Integer>();
Deque<Integer> stack = new ArrayDeque<Integer>();
for (int i = nums2.length - 1; i >= 0; --i) {
int num = nums2[i];
while (!stack.isEmpty() && num >= stack.peek()) {
stack.pop();
}
map.put(num, stack.isEmpty() ? -1 : stack.peek());
stack.push(num);
}
int[] res = new int[nums1.length];
for (int i = 0; i < nums1.length; ++i) {
res[i] = map.get(nums1[i]);
}
return res;
}
}
static class Solution {
public int[] nextGreaterElement(int[] nums1, int[] nums2) {
int l = nums2.length;
Deque<Integer> stack = new LinkedList<>();
Map<Integer, Integer> map = new HashMap<>();
map.put(nums2[l - 1], -1);
for (int i = 0; i < l - 1; i++) {
if (nums2[i + 1] > nums2[i]) {
map.put(nums2[i], nums2[i + 1]);
while (!stack.isEmpty()) {
int n = stack.getLast();
if (n < nums2[i + 1]) {
map.put(n, nums2[i + 1]);
stack.removeLast();
} else {
break;
}
}
} else {
stack.offer(nums2[i]);
}
}
while (!stack.isEmpty()) {
int n = stack.getLast();
map.put(n, -1);
stack.pop();
}
int[] res = new int[nums1.length];
for (int i = 0; i < nums1.length; i++) {
res[i] = map.containsKey(nums1[i]) ? map.get(nums1[i]) : -1;
}
return res;
}
}
}
| [
"sparkfengbo@users.noreply.github.com"
] | sparkfengbo@users.noreply.github.com |
90ee1f5a24f3a1dbb2feb23c2b4faa1464390f23 | fa91450deb625cda070e82d5c31770be5ca1dec6 | /Diff-Raw-Data/3/3_eb14df3d6c01dcbb873e0428b89e358889a39165/TabRenderer/3_eb14df3d6c01dcbb873e0428b89e358889a39165_TabRenderer_t.java | 7c4ef9238bab910be4ce74ced9b740b10eef1648 | [] | no_license | zhongxingyu/Seer | 48e7e5197624d7afa94d23f849f8ea2075bcaec0 | c11a3109fdfca9be337e509ecb2c085b60076213 | refs/heads/master | 2023-07-06T12:48:55.516692 | 2023-06-22T07:55:56 | 2023-06-22T07:55:56 | 259,613,157 | 6 | 2 | null | 2023-06-22T07:55:57 | 2020-04-28T11:07:49 | null | UTF-8 | Java | false | false | 1,862 | java | /*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package org.helix.mobile.component.tab;
import java.io.IOException;
import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.context.ResponseWriter;
import org.primefaces.renderkit.CoreRenderer;
/**
* This rendering is invoked by each page, which checks to see if it in a tab bar and,
* if so, renders the tab bar.
*
* @author shallem
*/
public class TabRenderer extends CoreRenderer {
@Override
public void encodeBegin(FacesContext context, UIComponent component) throws IOException {
Tab tab = (Tab)component;
Boolean isActive = (Boolean)tab.getAttributes().get("active");
ResponseWriter writer = context.getResponseWriter();
writer.startElement("li", component);
writer.startElement("a", component);
writer.writeAttribute("href", "#" + tab.getPage(), null);
writer.writeAttribute("style", "height: 48px", null);
//writer.writeAttribute("data-icon", "custom", null);
if (!tab.isCustomIcon()) {
writer.writeAttribute("data-icon", tab.getIcon(), null);
}
String styleClass = "ui-icon-" + tab.getIcon();
if (isActive) {
writer.writeAttribute("class", styleClass + " ui-btn-active", null);
} else {
writer.writeAttribute("class", styleClass, null);
}
if (tab.getName() != null) {
//writer.write(tab.getName());
}
}
@Override
public void encodeEnd(FacesContext context, UIComponent component) throws IOException {
ResponseWriter writer = context.getResponseWriter();
writer.endElement("a");
writer.endElement("li");
}
}
| [
"yuzhongxing88@gmail.com"
] | yuzhongxing88@gmail.com |
b9fbf4ed61795ef0442ad2e855d388f9611cb091 | 15fc89df8102eec0af46cb3b1cb0aef95f3a02fe | /app/src/main/java/com/example/jdong/view/IFenLeiView.java | 51d7cef38fb4c83c2337c8a1a0935a6850c88c97 | [] | no_license | Shenxiaoyang1/JDong | d55bc87228daab946c57278ca4bec10c6a8eaf3e | 9b7149198dbb9d58c69dc721ac4f99b7d7c14eda | refs/heads/master | 2021-08-31T10:57:53.739933 | 2017-12-21T03:52:18 | 2017-12-21T03:52:18 | 114,960,125 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 241 | java | package com.example.jdong.view;
import com.example.jdong.bean.FenLeiBean;
import java.util.List;
/**
* Created by 刘雅文 on 2017/12/15.
*/
public interface IFenLeiView {
public void show(List<FenLeiBean.DataBean> fenLeiBean);
}
| [
"InterestingWhat@163.com"
] | InterestingWhat@163.com |
6c9f1975d19f1f682a29e76bb153959f7eda244b | 693d7c5fcbab4f4f12ebc2d7b945311efa4b0ba5 | /chatserver/src/main/java/com/project/chat/gameroom/GameMessage.java | 829ba27d526ea3f60469bd74c76d77437cc048f3 | [
"MIT"
] | permissive | RyuJaeChan/FindSpy | 66a098596b02f28cabd533a69625ad42c0aae5f5 | cc4aa31121e8b006f7cfdbcb90819be3c61fbfa6 | refs/heads/master | 2020-04-01T14:00:17.526406 | 2018-12-18T14:34:14 | 2018-12-18T14:34:14 | 153,276,245 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 236 | java | package com.project.chat.gameroom;
import com.project.chat.util.GameState;
import lombok.Data;
@Data
public class GameMessage {
private Integer roomId;
private GameState gameStep;
private String message;
private String writer;
}
| [
"rjch221@gmail.com"
] | rjch221@gmail.com |
b435fa423c7f62e7c6394a1e5f6ffd010d0cfca1 | 9430bdf488ccab433a3f3578e608d0871f9bb3ed | /app/src/main/java/com/huanpet/huanpet/screen/view/PinyinUtils.java | 76ba6b117cf75c2e37cb293a7496e5ea2384463e | [] | no_license | wl19930525/HuanPet | 8ac3144fc5282dd9d45b6b5ee6e6ef4746a13b43 | 026b30772a92b501640d5382485ef3b0de96352a | refs/heads/master | 2021-04-15T16:37:48.937039 | 2018-04-04T01:44:15 | 2018-04-04T01:44:15 | 126,459,021 | 0 | 0 | null | 2018-04-02T00:57:17 | 2018-03-23T08:58:14 | Java | UTF-8 | Java | false | false | 3,711 | java | package com.huanpet.huanpet.screen.view;
import net.sourceforge.pinyin4j.PinyinHelper;
import net.sourceforge.pinyin4j.format.HanyuPinyinCaseType;
import net.sourceforge.pinyin4j.format.HanyuPinyinOutputFormat;
import net.sourceforge.pinyin4j.format.HanyuPinyinToneType;
import net.sourceforge.pinyin4j.format.HanyuPinyinVCharType;
import net.sourceforge.pinyin4j.format.exception.BadHanyuPinyinOutputFormatCombination;
public class PinyinUtils {
/**
* 获得汉语拼音首字母
*
* @param chines 汉字
* @return
*/
public static String getAlpha(String chines) {
String pinyinName = "";
char[] nameChar = chines.toCharArray();
HanyuPinyinOutputFormat defaultFormat = new HanyuPinyinOutputFormat();
defaultFormat.setCaseType(HanyuPinyinCaseType.UPPERCASE);
defaultFormat.setToneType(HanyuPinyinToneType.WITHOUT_TONE);
for (int i = 0; i < nameChar.length; i++) {
if (nameChar[i] > 128) {
try {
pinyinName += PinyinHelper.toHanyuPinyinStringArray(
nameChar[i], defaultFormat)[0].charAt(0);
} catch (BadHanyuPinyinOutputFormatCombination e) {
e.printStackTrace();
}
} else {
pinyinName += nameChar[i];
}
}
return pinyinName;
}
/**
* 将字符串中的中文转化为拼音,英文字符不变
*
* @param inputString 汉字
* @return
*/
public static String getPingYin(String inputString) {
HanyuPinyinOutputFormat format = new HanyuPinyinOutputFormat();
format.setCaseType(HanyuPinyinCaseType.LOWERCASE);
format.setToneType(HanyuPinyinToneType.WITHOUT_TONE);
format.setVCharType(HanyuPinyinVCharType.WITH_V);
String output = "";
if (inputString != null && inputString.length() > 0
&& !"null".equals(inputString)) {
char[] input = inputString.trim().toCharArray();
try {
for (int i = 0; i < input.length; i++) {
if (Character.toString(input[i]).matches(
"[\\u4E00-\\u9FA5]+")) {
String[] temp = PinyinHelper.toHanyuPinyinStringArray(
input[i], format);
output += temp[0];
} else
output += Character.toString(input[i]);
}
} catch (BadHanyuPinyinOutputFormatCombination e) {
e.printStackTrace();
}
} else {
return "*";
}
return output;
}
/**
* 汉字转换位汉语拼音首字母,英文字符不变
*
* @param chines 汉字
* @return 拼音
*/
public static String converterToFirstSpell(String chines) {
String pinyinName = "";
char[] nameChar = chines.toCharArray();
HanyuPinyinOutputFormat defaultFormat = new HanyuPinyinOutputFormat();
defaultFormat.setCaseType(HanyuPinyinCaseType.UPPERCASE);
defaultFormat.setToneType(HanyuPinyinToneType.WITHOUT_TONE);
for (int i = 0; i < nameChar.length; i++) {
if (nameChar[i] > 128) {
try {
pinyinName += PinyinHelper.toHanyuPinyinStringArray(
nameChar[i], defaultFormat)[0].charAt(0);
} catch (BadHanyuPinyinOutputFormatCombination e) {
e.printStackTrace();
}
} else {
pinyinName += nameChar[i];
}
}
return pinyinName;
}
}
| [
"958337798@qq.com"
] | 958337798@qq.com |
7ba9bb7d4fdb875d9afe8b91e2eb9ed4f956c6de | 9df873dbe290776878e612154baa2a4148e17ea2 | /src/main/java/com/kenny/fix/definition/MessageDefinition.java | 08f30e9334d230e991dbea8465513043b0233d4c | [] | no_license | kennien-ravindran/fixparser | f3978abf63e119f4e4a2caf039791fa3a44bb9e6 | 2fefbe9d8421e0508a8925f1f5345b311d6ef77c | refs/heads/master | 2020-04-25T06:20:20.993209 | 2019-02-25T22:21:10 | 2019-02-25T22:21:10 | 172,577,219 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,229 | java | package com.kenny.fix.definition;
import java.util.HashMap;
import java.util.Set;
import java.util.TreeSet;
public class MessageDefinition {
private HashMap<Integer, MessageGroupDefinition> groupDefinitionMap = new HashMap<Integer, MessageGroupDefinition>();
public void loadDefinition(int tagId, int firstTag, Set<Integer> required, Set<Integer> optional) {
groupDefinitionMap.put(tagId, new MessageGroupDefinition(tagId, firstTag, required, optional ));
}
public void loadTestDefinition(){
loadDefinition(269, 277, getTreeSet(456), getTreeSet(231, 283));
loadDefinition(123, 786, getTreeSet(398), getTreeSet(567, 496));
loadDefinition(552, 54, getTreeSet(37, 453), getTreeSet(12,13, 58, 528));
loadDefinition(453, 448, getTreeSet(447, 452, 802), getTreeSet());
loadDefinition(802, 523, getTreeSet(803), getTreeSet());
}
private TreeSet<Integer> getTreeSet(int... tags){
TreeSet<Integer> set = new TreeSet<Integer>();
for(int tag : tags){
set.add(tag);
}
return set;
}
public MessageGroupDefinition getGroupDefinition(int groupId){
return groupDefinitionMap.get(groupId);
}
}
| [
"kenny@kennys-MacBook-Pro-2.local"
] | kenny@kennys-MacBook-Pro-2.local |
36de460f7776b7e3c0ba3c12fc15ccdb040f2b22 | 46f14ea3b663fc80701c4f8ad64284a5e04e7adc | /src/cs3500/lecture/mvc/turtledraw/control/SimpleController.java | c5c88d8eeb30eb784a95b7bc0d9338cbc8f360d4 | [] | no_license | nzukie-b/Music-Editor | abbd8a30f33e63b2f4357ab9d488fa3676db0cfb | 82bdf9d1148f473a5836bc9fd56ab53ccc87f1b4 | refs/heads/master | 2021-09-09T19:01:47.304799 | 2017-04-23T22:26:01 | 2017-04-23T22:26:01 | 125,789,379 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 2,029 | java | package cs3500.lecture.mvc.turtledraw.control;
import cs3500.lecture.mvc.turtledraw.TracingTurtleModel.Line;
import cs3500.lecture.mvc.turtledraw.TracingTurtleModel.SmarterTurtle;
import cs3500.lecture.mvc.turtledraw.TracingTurtleModel.TracingTurtleModel;
import java.util.InputMismatchException;
import java.util.Scanner;
/**
* Created by blerner on 10/10/16.
*/
public class SimpleController {
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
TracingTurtleModel m = new SmarterTurtle();
while (s.hasNext()) {
String in = s.next();
switch(in) {
case "q":
case "quit":
return;
case "show":
for (Line l : m.getLines()) {
System.out.println(l);
}
break;
case "move":
try {
double d = s.nextDouble();
m.move(d);
} catch (InputMismatchException ime) {
System.out.println("Bad length to move");
}
break;
case "trace":
try {
double d = s.nextDouble();
m.trace(d);
} catch (InputMismatchException ime) {
System.out.println("Bad length to trace");
}
break;
case "turn":
try {
double d = s.nextDouble();
m.turn(d);
} catch (InputMismatchException ime) {
System.out.println("Bad length to turn");
}
break;
case "square":
try {
double d = s.nextDouble();
m.trace(d);
m.turn(90);
m.trace(d);
m.turn(90);
m.trace(d);
m.turn(90);
m.trace(d);
m.turn(90);
} catch (InputMismatchException ime) {
System.out.println("Bad length to turn");
}
break;
default:
System.out.println(String.format("Unknown command %s", in));
break;
}
}
}
} | [
"emdaniel@ccs.neu.edu"
] | emdaniel@ccs.neu.edu |
b8c7523a0b38f1a83d830e3d43fcf39ff184edd2 | 0b20c4a616e17b76fe3c9a048e68b417e35dfaac | /Android/Seed/framework/src/main/java/com/min/framework/ConfigConstants.java | aa0e8cd2d6c2463d6e0fc6ba53b75c9f6788b95e | [] | no_license | minyangcheng/WorkStation | d39fffd3879adeac46d7b1cc1aeb5f56dd16c8dd | efcf62e7295ed8d76ba9de101076d987311dce88 | refs/heads/master | 2021-01-01T06:10:04.870682 | 2018-12-06T06:06:35 | 2018-12-06T06:06:35 | 97,376,308 | 1 | 0 | null | null | null | null | UTF-8 | Java | false | false | 458 | java | package com.min.framework;
/**
* Created by minyangcheng on 2016/10/8.
*/
public class ConfigConstants {
public static final String HTTP_LOG="HttpLog";
public static final int PAGE_SIZE=15;
public static String API_SERVER_URL;
public static String SOURCE;
public static String APP_SECRET;
public static boolean DEBUG;
public static String VERSION_NAME;
public static String SDK_INT;
public static String FLAVOR;
}
| [
"332485508@qq.com"
] | 332485508@qq.com |
5944da4407298226b233abca7c482b1f44fe3ced | 494cf20ddeb8d8924fba7048e6a95bed1386d290 | /app/src/main/java/z_aksys/solutions/digiappequitybb/utils/AccountCalculator.java | b4520d325f214cb62a3db08bd489b5b6ad8d3c48 | [] | no_license | vaibhav1601/digiTabB2c | c8408aa0249c929dc6eeb6bde889a12844ac8770 | 52e6e426e25cfe9c447ed7981b66af41d297f7d2 | refs/heads/master | 2020-04-18T12:02:01.465516 | 2019-01-24T07:36:02 | 2019-01-24T07:36:02 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 301 | java | package z_aksys.solutions.digiappequitybb.utils;
import android.util.Log;
public class AccountCalculator {
private final long ACCOUNTOPENINGBROKERAGE = 500;
public long calculateAccountOpeningEarning(int numberOfAccounts) {
return numberOfAccounts*ACCOUNTOPENINGBROKERAGE;
}
}
| [
"sumit.chakole@tarkashilpa.com"
] | sumit.chakole@tarkashilpa.com |
49a23e66c1619418d976e72df925938c7db0f0b5 | c0985d7d62a09298930cce0d709f03aeda062e85 | /app/src/main/java/com/gonztorr/android/tipcalc/fragments/RatingServiceFragmentListener.java | cf5c43c63763cecd8bf493afd868b00043524698 | [] | no_license | helijesusg/TipCalc | 074d70f88ef81bf8b374936e27f72d4fa2c753e3 | da18985c9b5853721cc0019875c94992015d641c | refs/heads/master | 2020-07-28T07:22:05.491197 | 2016-11-22T18:00:00 | 2016-11-22T18:00:00 | 73,027,721 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 183 | java | package com.gonztorr.android.tipcalc.fragments;
/**
* Created by Heli Gonzalez on 21/11/2016.
*/
public interface RatingServiceFragmentListener {
String getRatingService();
}
| [
"helijesusg@gmail.com"
] | helijesusg@gmail.com |
3266b3aaa0979343689fc480d12a519cee78f358 | 1c5e8538f5f500b7f6f2d8a3d792419f2de51b7b | /app/src/main/java/com/example/jiangshujing/keepalivetimingdemo/keepalive/service/DaemonService.java | dd0eda6b53319679a23e3d6ba0756867b6ac6716 | [] | no_license | jiangshujing/KeepAliveTimeingDemo | 3b002645a6113cdc9c18487cf5a76ae7ca4eb678 | 961c6fe92d458e050805b5c35f06b21a917066d6 | refs/heads/master | 2020-04-13T23:10:54.215664 | 2018-12-29T09:55:46 | 2018-12-29T09:55:46 | 163,499,503 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 2,660 | java | package com.example.jiangshujing.keepalivetimingdemo.keepalive.service;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.Service;
import android.content.Intent;
import android.os.Build;
import android.os.IBinder;
import android.support.annotation.Nullable;
import android.util.Log;
import com.example.jiangshujing.keepalivetimingdemo.R;
import com.example.jiangshujing.keepalivetimingdemo.keepalive.utils.Contants;
/**
* 前台Service,使用startForeground
* 这个Service尽量要轻,不要占用过多的系统资源,否则
* 系统在资源紧张时,照样会将其杀死
*/
public class DaemonService extends Service {
private static final String TAG = "DaemonService";
public static final int NOTICE_ID = 100;
@Nullable
@Override
public IBinder onBind(Intent intent) {
return null;
}
@Override
public void onCreate() {
super.onCreate();
if (Contants.DEBUG)
Log.d(TAG, "DaemonService---->onCreate被调用,启动前台service");
//如果API大于18,需要弹出一个可见通知
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR2) {
Notification.Builder builder = new Notification.Builder(this);
builder.setSmallIcon(R.mipmap.ic_launcher);
builder.setContentTitle("KeepAppAlive");
builder.setContentText("DaemonService is runing...");
startForeground(NOTICE_ID, builder.build());
// 如果觉得常驻通知栏体验不好
// 可以通过启动CancelNoticeService,将通知移除,oom_adj值不变
Intent intent = new Intent(this, CancelNoticeService.class);
startService(intent);
} else {
startForeground(NOTICE_ID, new Notification());
}
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
// 如果Service被终止
// 当资源允许情况下,重启service
return START_STICKY;
}
@Override
public void onDestroy() {
super.onDestroy();
// 如果Service被杀死,干掉通知
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR2) {
NotificationManager mManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
mManager.cancel(NOTICE_ID);
}
if (Contants.DEBUG)
Log.d(TAG, "DaemonService---->onDestroy,前台service被杀死");
// 重启自己
Intent intent = new Intent(getApplicationContext(), DaemonService.class);
startService(intent);
}
}
| [
"jiangshujing@feinno.com"
] | jiangshujing@feinno.com |
1c27cd18946cbc2afe1b0d93bd90e105528e89b9 | efb97250b130a55948d3c450fdcd0ec69fec920e | /modbus/src/main/java/com/berrontech/huali/modbus/ip/xa/XaMessageResponse.java | 58975e630ea8efe9c73284a224ca11d5a03f9a1c | [] | no_license | levent8421/AlarmCenter | 6f24f35bae57dbe179988453fd1b59c7b0d69925 | a10921980423ce4741bd16c9747705a2505efdb0 | refs/heads/master | 2022-12-02T04:44:24.199019 | 2020-08-13T10:33:52 | 2020-08-13T10:33:52 | 286,463,356 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 2,285 | java | /*
* ============================================================================
* GNU General Public License
* ============================================================================
*
* Copyright (C) 2006-2011 Serotonin Software Technologies Inc. http://serotoninsoftware.com
* @author Matthew Lohbihler
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.berrontech.huali.modbus.ip.xa;
import com.berrontech.huali.modbus.base.ModbusUtils;
import com.berrontech.huali.modbus.exception.ModbusTransportException;
import com.berrontech.huali.modbus.ip.IpMessageResponse;
import com.berrontech.huali.modbus.msg.ModbusResponse;
import com.berrontech.huali.modbus.sero.util.queue.ByteQueue;
public class XaMessageResponse extends XaMessage implements IpMessageResponse {
static XaMessageResponse createXaMessageResponse(ByteQueue queue) throws ModbusTransportException {
// Remove the XA header
int transactionId = ModbusUtils.popShort(queue);
int protocolId = ModbusUtils.popShort(queue);
if (protocolId != ModbusUtils.IP_PROTOCOL_ID)
throw new ModbusTransportException("Unsupported IP protocol id: " + protocolId);
ModbusUtils.popShort(queue); // Length, which we don't care about.
// Create the modbus response.
ModbusResponse response = ModbusResponse.createModbusResponse(queue);
return new XaMessageResponse(response, transactionId);
}
public XaMessageResponse(ModbusResponse modbusResponse, int transactionId) {
super(modbusResponse, transactionId);
}
public ModbusResponse getModbusResponse() {
return (ModbusResponse) modbusMessage;
}
}
| [
"levent8421@outlook.com"
] | levent8421@outlook.com |
41187a3f84d6ae55292767ac725d690ce88f8bca | b9fcbdfaf85b16f534c95a41d3a9930ac1683aad | /Server/Tonpose_Kryonet/src/cs309/tonpose/ServerItem.java | eea7273b4077e87c9c0e5eab64c9de941e0816cf | [] | no_license | cbot789/Project-Tonpose | fd33d2de31c17cddb3852f4b05a18255a2de70ca | f2999697ded9279edec40ad8120c46b0d5623a07 | refs/heads/master | 2021-07-02T03:29:12.480142 | 2016-12-07T06:59:58 | 2016-12-07T06:59:58 | 103,860,474 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 114 | java | package cs309.tonpose;
public class ServerItem {
public int typeID;
public int uniqueID;
public float x, y;
}
| [
"theluke@iastate.edu"
] | theluke@iastate.edu |
a909e4b8e2d02c475edb90df09483253d03ef736 | c202b1be81c238dc78d62311f785a6b310740d8a | /src/TestNG/GroupingTestcases.java | ad3eb8ac92bca1c4b890a39e4d04e212c583c57c | [] | no_license | Rajno1/SeleniumBasics | 7b320efe41b44af96c94c43f8883048f01c1b381 | bcabcc1cf877d76e816a7da043613fc48d20c3f6 | refs/heads/master | 2020-08-04T21:19:24.962815 | 2019-10-02T07:53:34 | 2019-10-02T07:53:34 | 212,282,427 | 1 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,093 | java | package TestNG;
import org.testng.annotations.Test;
public class GroupingTestcases {
@Test(priority=1,groups= "Buildacceptance")
public void BuildCheck(){
System.out.println("Build acceptacne test");
}
//By using 'priority' keyword we can priorities the test cases(@Test)
//By using 'groups' keyword we can create the groups
@Test(priority=2,groups= "Buildacceptance")
public void EnterURL() {
System.out.println("Enter URL");
}
@Test(priority=3,groups= "Enter Credentials")
public void ValidateUserlogin() {
System.out.println("Validate user login details");
}
@Test(priority=4,groups= "Enter Credentials")
public void Enterusername() {
System.out.println("Enter user name");
}
@Test(priority=5,groups= "Enter Credentials")
public void Enterpassword() {
System.out.println("Enter password");
}
@Test(priority=6,groups= "SubmitButton")
public void SubmitStatus() {
System.out.println("get the xpath of submit button");
}
@Test(priority=7,groups= "SubmitButton")
public void Submitbutton() {
System.out.println("click submit button");
}
}
| [
"rajasekhar.rct@gmail.com"
] | rajasekhar.rct@gmail.com |
c7c069136d716732f84348f697867ecf783fbea5 | 0af8b92686a58eb0b64e319b22411432aca7a8f3 | /single-medium-project/src/main/java/org/gradle/test/performancenull_11/Productionnull_1023.java | cc2b1063cee8e8db0b1233c5270ccbce07f54121 | [] | no_license | gradle/performance-comparisons | b0d38db37c326e0ce271abebdb3c91769b860799 | e53dc7182fafcf9fedf07920cbbea8b40ee4eef4 | refs/heads/master | 2023-08-14T19:24:39.164276 | 2022-11-24T05:18:33 | 2022-11-24T05:18:33 | 80,121,268 | 17 | 15 | null | 2022-09-30T08:04:35 | 2017-01-26T14:25:33 | null | UTF-8 | Java | false | false | 585 | java | package org.gradle.test.performancenull_11;
public class Productionnull_1023 {
private final String property;
public Productionnull_1023(String param) {
this.property = param;
}
public String getProperty() {
return property;
}
private String prop0;
public String getProp0() {
return prop0;
}
public void setProp0(String value) {
prop0 = value;
}
private String prop1;
public String getProp1() {
return prop1;
}
public void setProp1(String value) {
prop1 = value;
}
}
| [
"cedric.champeau@gmail.com"
] | cedric.champeau@gmail.com |
61aef001db803093923ed0857b7f11d2ff056a9b | ba5d18efd948ffac20ee4bdab369d4e6a67d83ca | /ga_oauth_app/src/main/java/mock/category/MockCategory.java | ce5f8d32ee4a989e783d948ea609adf1f205d732 | [] | no_license | atares0223/Google_OAuth2_Springboot_Analytics | b1895fc45801f9a0ed2ed9f5457a6b58669e1006 | 3093e679f77aa44f5c668ae9f0c80dd3fbed2fa1 | refs/heads/master | 2020-04-30T15:00:35.029483 | 2019-03-21T09:15:55 | 2019-03-21T09:15:55 | 176,908,059 | 1 | 2 | null | null | null | null | UTF-8 | Java | false | false | 837 | java | package mock.category;
import com.lff.model.product.Category;
import mock.seller.MockSeller;
public class MockCategory {
public static String FRUIT = "fruit";
public static String APPLE = "apple";
public static Category FRUIT_CATEGORY = new Category(null, FRUIT);
public static Category APPLE_CATEGORY = new Category(FRUIT_CATEGORY, APPLE);
public static String TOY = "toy";
public static String TRANSFORMERS = "transformers";
public static Category TOY_CATEGORY = new Category(null, TOY);
public static Category TRANSFORMERS_CATEGORY = new Category(TOY_CATEGORY, TRANSFORMERS);
public static Category getCategory(String sellerName){
if(sellerName.equals(MockSeller.FRUIT_HOME)){
return APPLE_CATEGORY;
}else if(sellerName.equals(MockSeller.TOY_HOME)){
return TRANSFORMERS_CATEGORY;
}
return null;
}
}
| [
"ffliu@ecwise.com"
] | ffliu@ecwise.com |
923d6bcba57a1583ab1ef7622f85ba3e8940c955 | e1fd1411965cabe996ac243b00296ed1caae562f | /src/main/java/com/neil/survey/module/SurveyAnswerAllInfo.java | 612a44785dcaf92f094cb7cd449d55620f2c5b28 | [] | no_license | neilzhao1978/survey | 4134ed23b2c8d155c8978856ca5be1574025fe81 | e7a6fbc098c621ec47f9a6067530aaa5ea590969 | refs/heads/master | 2021-09-08T19:53:27.664816 | 2018-03-12T03:29:58 | 2018-03-12T03:29:58 | 103,833,446 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 2,264 | java | package com.neil.survey.module;
import java.io.Serializable;
import javax.persistence.*;
/**
* The persistent class for the SURVEY_ANSWER_ALL_INFO database table.
*
*/
@Entity
@Table(name="SURVEY_ANSWER_ALL_INFO")
@NamedQuery(name="SurveyAnswerAllInfo.findAll", query="SELECT s FROM SurveyAnswerAllInfo s")
public class SurveyAnswerAllInfo implements Serializable {
private static final long serialVersionUID = 1L;
private String brand;
@Column(name="IMAGE_ID")
private String imageId;
@Column(name="IMAGE_NAME")
private String imageName;
private String model;
@Column(name="REPLYER_POSITION")
private String replyerPosition;
@Column(name="STYLE_KEYWORD")
private String styleKeyword;
@Id
@Column(name="SURVEY_ID")
private String surveyId;
private String texture;
@Column(name="THUMB_URL")
private String thumbUrl;
private String year;
public SurveyAnswerAllInfo() {
}
public String getBrand() {
return this.brand;
}
public void setBrand(String brand) {
this.brand = brand;
}
public String getImageId() {
return this.imageId;
}
public void setImageId(String imageId) {
this.imageId = imageId;
}
public String getImageName() {
return this.imageName;
}
public void setImageName(String imageName) {
this.imageName = imageName;
}
public String getModel() {
return this.model;
}
public void setModel(String model) {
this.model = model;
}
public String getReplyerPosition() {
return this.replyerPosition;
}
public void setReplyerPosition(String replyerPosition) {
this.replyerPosition = replyerPosition;
}
public String getStyleKeyword() {
return this.styleKeyword;
}
public void setStyleKeyword(String styleKeyword) {
this.styleKeyword = styleKeyword;
}
public String getSurveyId() {
return this.surveyId;
}
public void setSurveyId(String surveyId) {
this.surveyId = surveyId;
}
public String getTexture() {
return this.texture;
}
public void setTexture(String texture) {
this.texture = texture;
}
public String getThumbUrl() {
return this.thumbUrl;
}
public void setThumbUrl(String thumbUrl) {
this.thumbUrl = thumbUrl;
}
public String getYear() {
return this.year;
}
public void setYear(String year) {
this.year = year;
}
} | [
"12590578@qq.com"
] | 12590578@qq.com |
b60e331d27fff6e98b878678a9d7478251167fbf | 8af1164bac943cef64e41bae312223c3c0e38114 | /results-java/google--error-prone/74b237d6c07be0108be1743d4b1d2ad83f7e37a1/after/HardCodedSdCardPath.java | 8200b6a673412687127abfb2df46f69bf08d1f20 | [] | no_license | fracz/refactor-extractor | 3ae45c97cc63f26d5cb8b92003b12f74cc9973a9 | dd5e82bfcc376e74a99e18c2bf54c95676914272 | refs/heads/master | 2021-01-19T06:50:08.211003 | 2018-11-30T13:00:57 | 2018-11-30T13:00:57 | 87,353,478 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 4,085 | java | /*
* Copyright 2016 Google Inc. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.errorprone.bugpatterns.android;
import static com.google.errorprone.BugPattern.Category.ANDROID;
import static com.google.errorprone.BugPattern.SeverityLevel.WARNING;
import static com.sun.source.tree.Tree.Kind.STRING_LITERAL;
import com.google.common.collect.ImmutableMap;
import com.google.errorprone.BugPattern;
import com.google.errorprone.BugPattern.ProvidesFix;
import com.google.errorprone.VisitorState;
import com.google.errorprone.bugpatterns.BugChecker;
import com.google.errorprone.bugpatterns.BugChecker.LiteralTreeMatcher;
import com.google.errorprone.fixes.SuggestedFix;
import com.google.errorprone.matchers.Description;
import com.google.errorprone.util.ASTHelpers;
import com.sun.source.tree.LiteralTree;
import java.util.Map;
/**
* TODO(avenet): Restrict this check to Android code once the capability is available in Error
* Prone. See b/27967984.
*
* @author avenet@google.com (Arnaud J. Venet)
*/
@BugPattern(
name = "HardCodedSdCardPath",
altNames = {"SdCardPath"},
summary = "Hardcoded reference to /sdcard",
category = ANDROID,
severity = WARNING,
providesFix = ProvidesFix.REQUIRES_HUMAN_ATTENTION
)
public class HardCodedSdCardPath extends BugChecker implements LiteralTreeMatcher {
// The proper ways of retrieving the "/sdcard" and "/data/data" directories.
static final String SDCARD = "Environment.getExternalStorageDirectory().getPath()";
static final String DATA = "Context.getFilesDir().getPath()";
// Maps each platform-dependent way of accessing "/sdcard" or "/data/data" to its
// portable equivalent.
static final ImmutableMap<String, String> PATH_TABLE =
new ImmutableMap.Builder<String, String>()
.put("/sdcard", SDCARD)
.put("/mnt/sdcard", SDCARD)
.put("/system/media/sdcard", SDCARD)
.put("file://sdcard", SDCARD)
.put("file:///sdcard", SDCARD)
.put("/data/data", DATA)
.put("/data/user", DATA)
.build();
@Override
public Description matchLiteral(LiteralTree tree, VisitorState state) {
if (tree.getKind() != STRING_LITERAL) {
return Description.NO_MATCH;
}
// Hard-coded paths may come handy when writing tests. Therefore, we suppress the check
// for code located under 'javatests'.
if (ASTHelpers.isJUnitTestCode(state)) {
return Description.NO_MATCH;
}
String literal = (String) tree.getValue();
if (literal == null) {
return Description.NO_MATCH;
}
for (Map.Entry<String, String> entry : PATH_TABLE.entrySet()) {
String hardCodedPath = entry.getKey();
if (!literal.startsWith(hardCodedPath)) {
continue;
}
String correctPath = entry.getValue();
String remainderPath = literal.substring(hardCodedPath.length());
// Replace the hard-coded fragment of the path with a portable expression.
SuggestedFix.Builder suggestedFix = SuggestedFix.builder();
if (remainderPath.isEmpty()) {
suggestedFix.replace(tree, correctPath);
} else {
suggestedFix.replace(tree, correctPath + " + \"" + remainderPath + "\"");
}
// Add the corresponding import statements.
if (correctPath.equals(SDCARD)) {
suggestedFix.addImport("android.os.Environment");
} else {
suggestedFix.addImport("android.content.Context");
}
return describeMatch(tree, suggestedFix.build());
}
return Description.NO_MATCH;
}
} | [
"fraczwojciech@gmail.com"
] | fraczwojciech@gmail.com |
1e31eba465e8c789709567f8b8c80afc11450eab | 4117d7a9bd5b987e0111abe59da8371ad7cf3eec | /app/src/main/java/user/com/sg/socialfeeddemo/utils/MockDataParser.java | b1c858a06361db8cf49067fc02f00fa8db26f644 | [] | no_license | cian0/SocialFeedDemo | 3c74393a87cba2b0dd588d901cbe7b64e6cf6951 | dd3d3de17f1be54a80d1409e7f60e2e64f4199c7 | refs/heads/master | 2021-01-10T13:42:58.732926 | 2016-02-29T09:58:22 | 2016-02-29T09:58:22 | 52,781,258 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 2,502 | java | package user.com.sg.socialfeeddemo.utils;
import android.content.Context;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import user.com.sg.socialfeeddemo.R;
import user.com.sg.socialfeeddemo.database.model.Comment;
import user.com.sg.socialfeeddemo.database.model.Feed;
import user.com.sg.socialfeeddemo.database.model.Profile;
/**
* Created by ianicasiano on 2/26/16.
*/
public class MockDataParser {
public static void parseData(Context context) {
JSONArray profilesJson = FileUtils.rawResourceToJsonArray(context, R.raw.profiles);
JSONArray commentsJson = FileUtils.rawResourceToJsonArray(context, R.raw.comments);
JSONArray feedsJson = FileUtils.rawResourceToJsonArray(context, R.raw.feeds);
JSONObject configJson = FileUtils.rawResourceToJson(context, R.raw.config);
ArrayList<Profile> profiles = new ArrayList<>();
ArrayList<Comment> comments = new ArrayList<>();
ArrayList<Feed> feeds = new ArrayList<>();
if (profilesJson == null) {
profilesJson = new JSONArray();
}
if (commentsJson == null) {
commentsJson = new JSONArray();
}
if (feedsJson == null) {
feedsJson = new JSONArray();
}
if (configJson == null) {
configJson = new JSONObject();
}
int i = 0, j = 0;
for (i = 0, j = profilesJson.length(); i < j; i++) {
Profile profile = new Profile();
try {
profile.parse(profilesJson.getJSONObject(i));
profiles.add(profile);
} catch (JSONException e) {
// ignore unparseables for now
continue;
}
}
for (i = 0, j = commentsJson.length(); i < j; i++) {
Comment comment = new Comment();
try {
comment.parse(commentsJson.getJSONObject(i));
comments.add(comment);
} catch (JSONException e) {
// ignore unparseables for now
continue;
}
}
for (i = 0, j = feedsJson.length(); i < j; i++) {
Feed feed = new Feed();
try {
feed.parse(feedsJson.getJSONObject(i));
feeds.add(feed);
} catch (JSONException e) {
// ignore unparseables for now
continue;
}
}
}
}
| [
"cyril.icasiano@gmail.com"
] | cyril.icasiano@gmail.com |
0e83b0af69e57b7042a698b35e99d99af87cc08b | 5858d0e30915568ebddfcac41f6a308a1fd38233 | /smarthome-web_lqh/src/main/java/com/biencloud/smarthome/web/wsclient/stub/GetPropertyCompanyInfoResponse.java | 57c9ee38f00e179f610ad1eb74a9153158de809e | [] | no_license | CocoaK/java-project-source | 303ad9a75ebf499d4ee95048160cd0a573d9f5ec | 609f43b9009fedf124c2feef09e10e0d47c2b4b4 | refs/heads/master | 2020-03-19T07:34:11.395784 | 2018-06-05T05:52:30 | 2018-06-05T05:52:30 | 136,125,854 | 0 | 1 | null | null | null | null | UTF-8 | Java | false | false | 1,603 | java |
package com.biencloud.smarthome.web.wsclient.stub;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlType;
/**
* <p>Java class for getPropertyCompanyInfoResponse complex type.
*
* <p>The following schema fragment specifies the expected content contained within this class.
*
* <pre>
* <complexType name="getPropertyCompanyInfoResponse">
* <complexContent>
* <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
* <sequence>
* <element name="return" type="{http://service.cxfservice.smarthome.biencloud.com/}propertyCompanyInfo" minOccurs="0"/>
* </sequence>
* </restriction>
* </complexContent>
* </complexType>
* </pre>
*
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "getPropertyCompanyInfoResponse", propOrder = {
"_return"
})
public class GetPropertyCompanyInfoResponse {
@XmlElement(name = "return")
protected PropertyCompanyInfo _return;
/**
* Gets the value of the return property.
*
* @return
* possible object is
* {@link PropertyCompanyInfo }
*
*/
public PropertyCompanyInfo getReturn() {
return _return;
}
/**
* Sets the value of the return property.
*
* @param value
* allowed object is
* {@link PropertyCompanyInfo }
*
*/
public void setReturn(PropertyCompanyInfo value) {
this._return = value;
}
}
| [
"kyq001@gmail.com"
] | kyq001@gmail.com |
ad7f325ffd7986bbf5e6c5e2a5d25783ec25e2e0 | 6a0e7ff68b7ed35a774affc8de2343a3f73328bf | /Printing numbers from 30 to 50/Main.java | 5df1d95fb77c3542bc3889b755b852977dfea182 | [] | no_license | rahulbhatia-rb/Playground | de12837987b1f56ccb349071260e1c552f24b789 | b551212c72ebe151d3c341c4f2ce0e1d2c4ea529 | refs/heads/master | 2020-04-23T16:07:59.765901 | 2019-07-20T06:41:57 | 2019-07-20T06:41:57 | 171,287,541 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 110 | java | #include <stdio.h>
int main() {
for(int i=30;i<=50;i++)
printf("%d\n",i);
//Type your code
return 0;
} | [
"rahul_harikishan@srmuniv.edu.in"
] | rahul_harikishan@srmuniv.edu.in |
2945141bc4a46ea13a9ad2e841b622d4f979cae9 | 575acf52715b95f86a10b4e3c1b354c5cc34248b | /src/main/java/org/demo/data/record/listitem/ReviewListItem.java | de8e44b9a2cebbf3edb7a6af97b19e38c8a99256 | [] | no_license | t-soumbou/persistence-with-mongoDB | 52a21b507551365f9f88e5adf2b6dd58f9b8ff62 | 67bfe4425cfe46360606390541b95007952658b0 | refs/heads/master | 2020-05-21T05:03:53.502360 | 2017-03-22T16:37:22 | 2017-03-22T16:37:22 | 84,574,135 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 741 | java | /*
* Created on 2017-03-22 ( Date ISO 2017-03-22 - Time 17:28:47 )
* Generated by Telosys ( http://www.telosys.org/ ) version 3.0.0
*/
package org.demo.data.record.listitem;
import org.demo.data.record.ReviewRecord;
import org.demo.commons.ListItem;
public class ReviewListItem implements ListItem {
private final String value ;
private final String label ;
public ReviewListItem(ReviewRecord review) {
super();
this.value = ""
+ review.getCustomerCode()
+ "|" + review.getBookId()
;
//TODO : Define here the attributes to be displayed as the label
this.label = review.toString();
}
//@Override
public String getValue() {
return value;
}
//@Override
public String getLabel() {
return label;
}
}
| [
"terrencesoumbou@gmail.com"
] | terrencesoumbou@gmail.com |
4761f34d4959e387a98950910d8368cc8fe78d0e | 8f27734dee9e9524055f6ca5c16f38b43aa45db0 | /chapter_002/src/test/java/ru/job4j/tracker/ItemTest.java | ec0b111a99e1accff53868e5bd2af71a5f58062d | [
"Apache-2.0"
] | permissive | KirillBelyaev74/job4j_elementary | c0205d677621059128265900295b5fbec3e9a588 | d0a335f3e409e24195138d77c2c04b9bb16efc15 | refs/heads/master | 2023-02-15T01:53:05.015800 | 2021-01-13T08:08:12 | 2021-01-13T08:08:12 | 202,711,977 | 0 | 0 | Apache-2.0 | 2020-10-13T17:21:54 | 2019-08-16T10:57:02 | Java | UTF-8 | Java | false | false | 1,264 | java | package ru.job4j.tracker;
import org.junit.Test;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import static org.hamcrest.Matchers.is;
import static org.junit.Assert.assertThat;
public class ItemTest {
@Test
public void whenFirstSecondThenFirstSecond() {
Item first = new Item("Petr");
Item second = new Item("Ivan");
Item third = new Item("Artem");
Tracker tracker = new Tracker();
tracker.add(first);
tracker.add(second);
tracker.add(third);
List<Item> result = tracker.findAll();
Collections.sort(result);
List<Item> expect = Arrays.asList(third, second, first);
assertThat(result, is(expect));
}
@Test
public void whenFirstSecondThenSecondFirst() {
Item first = new Item("Artem");
Item second = new Item("Petr");
Item third = new Item("Ivan");
Tracker tracker = new Tracker();
tracker.add(first);
tracker.add(second);
tracker.add(third);
List<Item> result = tracker.findAll();
Collections.sort(result, Collections.reverseOrder());
List<Item> expect = Arrays.asList(second, third, first);
assertThat(result, is(expect));
}
}
| [
"kirbel74@gmail.com"
] | kirbel74@gmail.com |
195e45708bbf696835b3e962ed25bb98c83ffce1 | f885a7ed43d2292ff29d3fc3077cac76c9ebb200 | /DA1/telephoned.java | 71cd82d1bb745cda3f48ee3c6e08958ca378c883 | [] | no_license | shaarangg/Java-Programs | 6500999ac6b089989b1599ccc0d4db113d112c63 | 3b9bccff1912715b8b047ec36118d06a5cdfd687 | refs/heads/main | 2023-05-27T09:41:38.518406 | 2021-06-14T16:25:44 | 2021-06-14T16:25:44 | 340,027,236 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 2,629 | java | import java.util.*;
abstract class Telephone{
String name;
String pno;
Telephone(String n, String p){
this.name = n;
this.pno = p;
}
void display(){
System.out.println("Name - "+this.name+"\nPhone Number - "+this.pno);
}
}
class TelephoneIndex extends Telephone
{
TelephoneIndex(String n, String p){
super(n,p);
}
void chngname(String sname){
this.name = sname;
System.out.println("Name Successfully changed\n");
}
void chngpno(String pno){
this.pno = pno;
System.out.println("Phone Number Successfully changed\n");
}
}
class telephoned{
void search(TelephoneIndex[] a, String sname){
int l = sname.length();
int n = a.length;
for(int i =0; i<n; i++){
String b = a[i].name.substring(0,l);
if(b.equals(sname)){
System.out.println(a[i].name + " "+ a[i].pno);
}
}
}
public static void main(String[] args){
System.out.println("Shaarang Singh\n19BCT0215\n");
Scanner sc = new Scanner(System.in);
System.out.println("Enter the no. of records");
int n = sc.nextInt();
TelephoneIndex[] a = new TelephoneIndex[n];
String name;
String pno;
for(int i =0; i<n; i++){
System.out.println("Enter the name");
name = sc.next();
System.out.println("Enter the no.");
pno = sc.next();
a[i] = new TelephoneIndex(name, pno);
System.out.println();
}
System.out.println("PhoneBook");
for(int i=0; i<n; i++){
a[i].display();
System.out.println();
}
telephoned obj = new telephoned();
System.out.println("Enter the string to search");
String sname = sc.next();
obj.search(a, sname);
System.out.println("\n\n");
System.out.println("Enter the string you want to change");
sname = sc.next();
System.out.println("Enter the new name");
String sname1 = sc.next();
for(int i =0; i<n; i++){
if(a[i].name.equals(sname)){
a[i].chngname(sname1);
break;
}
}
System.out.println("Enter the no. you want to change");
pno = sc.next();
System.out.println("Enter the new no.");
String pno1 = sc.next();
for(int i =0; i<n; i++){
if(a[i].pno.equals(pno)){
a[i].chngpno(pno1);
break;
}
}
sc.close();
}
} | [
"shaaranggsingh@gmail.com"
] | shaaranggsingh@gmail.com |
17e6e75906a5da7cad648a7b0303f5089293bea5 | 2fe164deaf81b2242a545f622fc9197fd43d6e4f | /src/com/radish/thinking/unit15/ComparablePet.java | a2f905c7f30af535fa3ab357682e624040ed1bf9 | [] | no_license | daluoboer/practice | b58488f5f43afb2eb4c06bb0c0c8ce137a917717 | 6d4eac442dcb8617293982659636dd53bd343643 | refs/heads/master | 2021-05-23T19:30:02.599615 | 2020-12-06T12:28:23 | 2020-12-06T12:28:23 | 253,434,856 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 187 | java | package com.radish.thinking.unit15;
public class ComparablePet implements Comparable<ComparablePet> {
@Override
public int compareTo(ComparablePet o) {
return 0;
}
}
| [
"zhangqian@188yd.com"
] | zhangqian@188yd.com |
88f3dbd306586ab54cf1006a0897df19da0d9e17 | 6f19edce2f9b8709aa22e6456f043573e00a3bf6 | /src/main/java/springbootactuatorlab/rest/SecurityController.java | dfb26cdba092c928f48242afbb61b31b55751b30 | [] | no_license | pedro21900/spring-boot-actuator-lab | 7d08806a67ddc606f6a58a8516024454178ea196 | 0ca6db40612baf2aa919725765ffaffb54f74e4a | refs/heads/master | 2023-06-10T08:44:18.407662 | 2021-06-29T16:20:52 | 2021-06-29T16:20:52 | 379,643,926 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 656 | java | package springbootactuatorlab.rest;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
@RequestMapping("/auth")
public class SecurityController {
@GetMapping("/status")
public ResponseEntity<String> getStatus() {
ResponseEntity<String> responseEntity = new ResponseEntity<>("Resource is fetched", HttpStatus.OK);
return responseEntity;
}
}
| [
"pedro.lenonn"
] | pedro.lenonn |
1f1304c2f3c3a724f594b298998cc07e1282bb77 | e2a97f336e545c89dbba886889416ee99c3d89a0 | /PJ_0306/src/QnAservice/ListQnaAction.java | 0363c65aa48fcb6e8b2f7e4112a1ea8b450f4fab | [] | no_license | jongtix/JSP_jongtix | f580d82beaa3a53c9876961af45389527d3832af | ef5aac22eefa6611bdce6647fba645e55d626192 | refs/heads/master | 2021-05-06T00:38:00.250849 | 2018-03-18T07:06:06 | 2018-03-18T07:06:06 | 114,311,296 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 866 | java | package QnAservice;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import QnAdao.QnaBoardDao;
import QnAdao.SubBoardDao;
import QnAdto.Board;
import QnAdto.SubBoard;
import controller.CommandProcess;
import util.Paging;
import util.PageBean;
public class ListQnaAction implements CommandProcess {
@Override
public String requestPro(HttpServletRequest request, HttpServletResponse response) throws Throwable {
QnaBoardDao dao = QnaBoardDao.getInstance();
int total = dao.getQnaTotal();
Paging pg = new Paging();
PageBean pb = pg.getPaging(request, total);
List<Board> list = dao.selectQnaList(pb.getStartRow(), pb.getEndRow());
request.setAttribute("total", total);
request.setAttribute("list", list);
request.setAttribute("pb", pb);
return "QnAboard/listQna.jsp";
}
}
| [
"jong1145@naver.com"
] | jong1145@naver.com |
810084f6a6d477ec38cfc32f7341c3a98996b006 | 1fb52eff75c7b79d466cd2137be54487113e6058 | /src/main/java/com/dev/filarmonic/dao/ShoppingCartDaoImpl.java | 29e1ed9573e5c78e36215b35be49a6b3791752cd | [] | no_license | less08/filarmonic-project | 663b504ead695c9ef3d4da52b444e0ebe58f18b1 | 9248d5426107a25b86e532016f27577a32a4a54f | refs/heads/main | 2023-03-09T08:58:53.848677 | 2021-02-26T18:09:04 | 2021-02-26T18:09:04 | 333,223,853 | 0 | 0 | null | 2021-02-26T18:09:05 | 2021-01-26T21:36:45 | Java | UTF-8 | Java | false | false | 2,538 | java | package com.dev.filarmonic.dao;
import com.dev.filarmonic.exception.DataProcessException;
import com.dev.filarmonic.model.ShoppingCart;
import com.dev.filarmonic.model.User;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.query.Query;
import org.springframework.stereotype.Repository;
@Repository
public class ShoppingCartDaoImpl implements ShoppingCartDao {
private final SessionFactory sessionFactory;
public ShoppingCartDaoImpl(SessionFactory sessionFactory) {
this.sessionFactory = sessionFactory;
}
@Override
public ShoppingCart add(ShoppingCart shoppingCart) {
Session session = null;
Transaction transaction = null;
try {
session = sessionFactory.openSession();
transaction = session.beginTransaction();
session.save(shoppingCart);
transaction.commit();
return shoppingCart;
} catch (Exception e) {
if (transaction != null) {
transaction.rollback();
}
throw new DataProcessException("Can't add shopping cart " + shoppingCart, e);
} finally {
if (session != null) {
session.close();
}
}
}
@Override
public ShoppingCart getByUser(User user) {
try (Session session = sessionFactory.openSession()) {
Query<ShoppingCart> query = session.createQuery("from ShoppingCart sc "
+ "left join fetch sc.tickets where sc.user=:user",
ShoppingCart.class)
.setParameter("user", user);
return query.getSingleResult();
} catch (Exception e) {
throw new DataProcessException("Can`t find shopping cart by user: " + user, e);
}
}
@Override
public void update(ShoppingCart shoppingCart) {
Session session = null;
Transaction transaction = null;
try {
session = sessionFactory.openSession();
transaction = session.beginTransaction();
session.saveOrUpdate(shoppingCart);
transaction.commit();
} catch (Exception e) {
if (transaction != null) {
transaction.rollback();
}
throw new DataProcessException("Can't update shopping cart " + shoppingCart, e);
} finally {
if (session != null) {
session.close();
}
}
}
}
| [
"elenasamsonova08@gmail.com"
] | elenasamsonova08@gmail.com |
d6f4a623c4bacce1eada785c3251e0d1fa5ada49 | 59d0bce04cb2787d6c09dd60d6081a9596c7df3c | /Maven/src/main/java/com/pages/HomePage.java | 2138cf64f890062358d053f62ebe36a1ef152947 | [] | no_license | kirantester319/AutomationRepo | bf45f1da505a5b4892f568f5f63d1e41e0944a38 | f9795d6b495c0c208c56cd2577622772da9ab7c7 | refs/heads/master | 2020-12-21T02:13:46.196916 | 2020-01-27T04:52:06 | 2020-01-27T04:52:06 | 236,274,613 | 0 | 0 | null | 2020-10-13T19:04:50 | 2020-01-26T06:11:44 | HTML | UTF-8 | Java | false | false | 392 | java | package com.pages;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.Set;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.FindBy;
import org.openqa.selenium.support.How;
public class HomePage {
WebDriver driver;
HomePage()
{
this.driver=driver;
}
}
| [
"kirantester319@gmai.com"
] | kirantester319@gmai.com |
0634902a7414b19c3f17b7a6871b724ce933fdab | 61f42894a09ad6f97259c81b7edb1419af5cb5bd | /src/com/ystech/aqtp/core/listener/ApplicationListener.java | 0a9e1cd0c556871be1a998160cd596968408c186 | [] | no_license | shusanzhan/aqtp | 59390ce1eaa9d00983c6d40173d8fe1b2b778a35 | 09f3389e9c8adbd1ca08a74cac39435683e00975 | refs/heads/master | 2021-01-22T04:41:26.469854 | 2014-01-04T15:57:27 | 2014-01-04T15:57:27 | 10,737,204 | 1 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,518 | java | /**
*
*/
package com.ystech.aqtp.core.listener;
import javax.annotation.Resource;
import javax.servlet.Filter;
import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSessionEvent;
import javax.servlet.http.HttpSessionListener;
import org.apache.struts2.ServletActionContext;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Component;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;
import com.ystech.aqtp.model.Access;
import com.ystech.aqtp.service.AccessManageImpl;
/**
* @author shusanzhan
* @date 2013-11-28
*/
public class ApplicationListener implements HttpSessionListener{
@Override
public void sessionCreated(HttpSessionEvent arg0) {
ApplicationContext applicationContext = (ApplicationContext) ServletActionContext
.getServletContext()
.getAttribute(
WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE);
//获取spring的环境信息
AccessManageImpl accessManageImpl =(AccessManageImpl)applicationContext.getBean("accessManageImpl");
Access access = accessManageImpl.get(1);
int count;
count = access.getAccess();
++count;
access.setAccess(count);
accessManageImpl.save(access);
arg0.getSession().setAttribute("count", count);
}
@Override
public void sessionDestroyed(HttpSessionEvent arg0) {
}
}
| [
"shusanzhan@163.com"
] | shusanzhan@163.com |
6946512c55ebe9f8d5a1b4972a44c8daa51cf435 | 9109586d72344396cdb762497c25c40db276c4fb | /src/main/java/br/com/sismed/mongodb/domain/Login.java | 559f75a0ce1e2fb17a44dfbe0cb9a271d2a710c2 | [] | no_license | jvrapi/sismed_mongodb | 86b82303227f32e9b2d9796e0a9007a0db5401fa | 55c2035d1e7be05460f19915a22d22d82adc0382 | refs/heads/master | 2023-07-10T12:15:17.462904 | 2020-04-06T14:31:04 | 2020-04-06T14:31:04 | 398,935,250 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 454 | java | package br.com.sismed.mongodb.domain;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
public class Login {
private String senha;
private String codigo;
public String getSenha() {
return senha;
}
public void setSenha(String senha) {
this.senha = new BCryptPasswordEncoder().encode(senha);
}
public String getCodigo() {
return codigo;
}
public void setCodigo(String codigo) {
this.codigo = codigo;
}
}
| [
"joaooviitorr@hotmail.com"
] | joaooviitorr@hotmail.com |
03c9813d9964839599aaa0f0c8fa6dea43edbd3b | 1a759d0b36238e5f6a3d089698bb2cb264a8c873 | /app/src/main/java/app/ari/assignment1/activities/TweetActivity.java | 32bbc3a51b0f25bd57e48557da43cffae0020779 | [] | no_license | ahwwwee/MyTweet-Android | b8ec1f2379d4f5e22433e5d654279fa338ac9979 | a1facbf5218cddd27d5e9b295c894346d09b47fd | refs/heads/master | 2021-08-23T22:24:27.729505 | 2017-01-08T20:30:01 | 2017-01-08T20:30:01 | 113,368,482 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 900 | java | package app.ari.assignment1.activities;
import android.os.Bundle;
import android.app.Fragment;
import android.app.FragmentManager;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AppCompatActivity;
import app.ari.assignment1.R;
/**
* Created by Ari on 16/12/16.
*/
public class TweetActivity extends AppCompatActivity {
ActionBar actionBar;
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.fragment_container);
actionBar = getSupportActionBar();
FragmentManager manager = getFragmentManager();
Fragment fragment = manager.findFragmentById(R.id.fragmentContainer);
if (fragment == null)
{
fragment = new TweeterFragment();
manager.beginTransaction().add(R.id.fragmentContainer, fragment).commit();
}
}
}
| [
"ahwwwee@gmail.com"
] | ahwwwee@gmail.com |
8bb6d5037a2682c305d5609116077c45d88cdb20 | 0907c886f81331111e4e116ff0c274f47be71805 | /sources/com/google/android/gms/internal/location/zzbb.java | e2e692b938c1e6bf687acc168c456dda4697349b | [
"MIT"
] | permissive | Minionguyjpro/Ghostly-Skills | 18756dcdf351032c9af31ec08fdbd02db8f3f991 | d1a1fb2498aec461da09deb3ef8d98083542baaf | refs/heads/Android-OS | 2022-07-27T19:58:16.442419 | 2022-04-15T07:49:53 | 2022-04-15T07:49:53 | 415,272,874 | 2 | 0 | MIT | 2021-12-21T10:23:50 | 2021-10-09T10:12:36 | Java | UTF-8 | Java | false | false | 1,104 | java | package com.google.android.gms.internal.location;
import android.app.PendingIntent;
import android.util.Log;
import com.google.android.gms.common.api.Status;
import com.google.android.gms.common.api.internal.BaseImplementation;
import com.google.android.gms.location.LocationStatusCodes;
final class zzbb extends zzan {
private BaseImplementation.ResultHolder<Status> zzdf;
public zzbb(BaseImplementation.ResultHolder<Status> resultHolder) {
this.zzdf = resultHolder;
}
private final void zze(int i) {
if (this.zzdf == null) {
Log.wtf("LocationClientImpl", "onRemoveGeofencesResult called multiple times");
return;
}
this.zzdf.setResult(LocationStatusCodes.zzd(LocationStatusCodes.zzc(i)));
this.zzdf = null;
}
public final void zza(int i, PendingIntent pendingIntent) {
zze(i);
}
public final void zza(int i, String[] strArr) {
Log.wtf("LocationClientImpl", "Unexpected call to onAddGeofencesResult");
}
public final void zzb(int i, String[] strArr) {
zze(i);
}
}
| [
"66115754+Minionguyjpro@users.noreply.github.com"
] | 66115754+Minionguyjpro@users.noreply.github.com |
85a6caa498589e37952964dac4624b034c59696f | 4a7ca7d0bf92dfc382b789a50db091bbb2d5f266 | /eureka-client/src/main/java/com/mashibing/eureka/controller/MainController.java | cbc960a8c94bb1c3b2dc785573571ef80f75fde3 | [] | no_license | kevinNewBird/springcloud-all | 5e9658cadc0bd2e8c86363c9c01a4625047cfede | 2f6ae137dbe669e5422d0a67b9ba0a1666048e33 | refs/heads/master | 2023-04-18T18:45:56.847890 | 2021-04-28T06:07:52 | 2021-04-28T06:07:52 | 355,623,766 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 2,121 | java | package com.mashibing.eureka.controller;
import com.mashibing.eureka.pojo.Person;
import com.mashibing.eureka.service.HealthStatusService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import javax.servlet.http.HttpServletResponse;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;
import java.util.Collections;
import java.util.Map;
/***********************
* @Description: TODO 类描述<BR>
* @author: zhao.song
* @since: 2021/4/9 0:25
* @version: 1.0
***********************/
@RestController
public class MainController {
@Value("${server.port}")
private String port;
@Autowired
private HealthStatusService healthService;
@GetMapping("/hello")
public String sayHello(){
return "hello eureka client0,我的port: " + port;
}
@GetMapping("/getMap")
public Map<String,String> getMap(){
return Collections.singletonMap("id", "100");
}
@GetMapping("/getObj")
public Person getObj(){
return new Person(1, "xiaoliuliu111");
}
@GetMapping("/getObj2")
public Person getObj2(String name){
return new Person(1, name);
}
@PostMapping("/postObj")
public Person postObj(@RequestParam String name){
return new Person(1, name);
}
@PostMapping("/postObj2")
public Person postObj(@RequestParam String name,@RequestBody Map<String,String> map){
System.out.println(map);
return new Person(1, name);
}
@PostMapping("/postLocation")
public URI postLocation(@RequestBody Person oPerson, HttpServletResponse response) throws URISyntaxException {
System.out.println(oPerson);
URI uri = new URI("http://www.baidu.com?wd=" + oPerson.getName());
response.addHeader("Location", uri.toString());
return uri;
}
@GetMapping("/health")
public String health(boolean status) {
healthService.setStatus(status);
return status ? "服务上线" : "服务下线";
}
}
| [
"song0586@126.com"
] | song0586@126.com |
b747f9050d5859bc7de9fd03770a2d2d8d27c523 | 0a1e238120665de5b0a723051a537d4498e0caf9 | /src/main/java/com/itheima/acl/param/AclModuleParam.java | 59a28f0bfb60d861518db0d7b7822264e2b478c2 | [] | no_license | shanxf1992/permission_managment_system | cb11192443c37f6b236945a93c22cada60085cbe | 045c7adab1610b40a7a7c00c0cb36d1bb78afb26 | refs/heads/master | 2020-03-28T18:38:36.792837 | 2018-09-15T11:59:17 | 2018-09-15T11:59:17 | 148,897,792 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 947 | java | package com.itheima.acl.param;
import lombok.Getter;
import lombok.Setter;
import lombok.ToString;
import org.hibernate.validator.constraints.Length;
import javax.validation.constraints.Max;
import javax.validation.constraints.Min;
import javax.validation.constraints.NotNull;
@Setter
@Getter
@ToString
public class AclModuleParam {
private Integer id;
@Length(min = 2, max = 64, message = "权限模块名称长度需要在2~64个字之间")
private String name;
private Integer parentId = 0;
@NotNull(message = "权限模块展示顺序不能为空")
private Integer seq;
@NotNull(message = "权限模块状态不能为空")
@Min(value = 0, message = "状态最小为值0")
@Max(value = 1, message = "状态最大值为1")
private Integer status;
@Length(min = 0, max = 64, message = "备注长度需要在64个字以内")
private String remark;
}
| [
"shan19920501@sina.com"
] | shan19920501@sina.com |
e210eb04f16a960399d23606b840cefbd330c0f6 | 9aef01964e63779f2ed6ad0fcf0d79088a4e9704 | /src/main/java/codilitylessons/SummNumbers.java | 5cc95fe7dd3104004ff086a8650b60d85cde869c | [] | no_license | KalisiakAdam/Alghoritms | b748b757dbac3e14eada52dac2ea139f48fa3489 | 52a4b56528ebb725ceb82b65e619452d63ac7dfa | refs/heads/master | 2021-08-20T01:03:33.440598 | 2017-11-27T21:56:07 | 2017-11-27T21:56:07 | 112,252,843 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 778 | java | package codilitylessons;
/**
* Created by kalisiaczki on 26.11.2017.
*/
public class SummNumbers {
public int sumIt(int[] numberArray){
int totalNumber = 0;
for(int i = 0 ; i <numberArray.length ; i++ ){
int number = numberArray[i];
if(number < 10) {
totalNumber =+ number;
}
else{
while(number > 0) {
totalNumber += number % 10;;
number = number / 10;
}
}
}
return totalNumber;
}
public static void main(String[] args) {
int arry[]={9, 21, 3155, 2456};
SummNumbers sumNumber = new SummNumbers();
System.out.println(sumNumber.sumIt(arry));
}
}
| [
"akalisiak@op.pl"
] | akalisiak@op.pl |
0f4ee5b44748e5305196f7e08c3d1e1e6686a402 | a46a8fe034b552fdcba31624da4aa2eb73a6ad5b | /LibraryC/src/main/java/ClassC.java | 0b6d1658fbda712e144bfcaef9ea6651a9156eab | [] | no_license | jwy411/DependencyConfigurationsTest | 98aad1bc7504be2a783a35cd3f2c5515c50f75f2 | 7b807907ada09e406fdcb3955d6a9029ef9d4b28 | refs/heads/master | 2022-06-22T02:41:53.577728 | 2020-05-08T07:01:23 | 2020-05-08T07:01:23 | 262,024,987 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 87 | java | public class ClassC {
public String tellMeJoke() {
return "You are funny :CC";
}
}
| [
"jwy411@naver.com"
] | jwy411@naver.com |
a7dabfae2289b63ac82ec5a0897f799990bb5ce5 | 81719679e3d5945def9b7f3a6f638ee274f5d770 | /aws-java-sdk-ssm/src/main/java/com/amazonaws/services/simplesystemsmanagement/model/UpdateManagedInstanceRoleResult.java | 869646e1ebf424dfaf758aabfb507d3fa36b6549 | [
"Apache-2.0"
] | permissive | ZeevHayat1/aws-sdk-java | 1e3351f2d3f44608fbd3ff987630b320b98dc55c | bd1a89e53384095bea869a4ea064ef0cf6ed7588 | refs/heads/master | 2022-04-10T14:18:43.276970 | 2020-03-07T12:15:44 | 2020-03-07T12:15:44 | 172,681,373 | 1 | 0 | Apache-2.0 | 2019-02-26T09:36:47 | 2019-02-26T09:36:47 | null | UTF-8 | Java | false | false | 2,418 | java | /*
* 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.simplesystemsmanagement.model;
import java.io.Serializable;
import javax.annotation.Generated;
/**
*
* @see <a href="http://docs.aws.amazon.com/goto/WebAPI/ssm-2014-11-06/UpdateManagedInstanceRole" target="_top">AWS API
* Documentation</a>
*/
@Generated("com.amazonaws:aws-java-sdk-code-generator")
public class UpdateManagedInstanceRoleResult extends com.amazonaws.AmazonWebServiceResult<com.amazonaws.ResponseMetadata> implements Serializable, Cloneable {
/**
* 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("{");
sb.append("}");
return sb.toString();
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (obj instanceof UpdateManagedInstanceRoleResult == false)
return false;
UpdateManagedInstanceRoleResult other = (UpdateManagedInstanceRoleResult) obj;
return true;
}
@Override
public int hashCode() {
final int prime = 31;
int hashCode = 1;
return hashCode;
}
@Override
public UpdateManagedInstanceRoleResult clone() {
try {
return (UpdateManagedInstanceRoleResult) super.clone();
} catch (CloneNotSupportedException e) {
throw new IllegalStateException("Got a CloneNotSupportedException from Object.clone() " + "even though we're Cloneable!", e);
}
}
}
| [
""
] | |
7c8de44a05f1b4af9da6bf93cb27f28bd404a569 | ed865190ed878874174df0493b4268fccb636a29 | /PuridiomRequestForQuotes/src/com/tsa/puridiom/rfq/tasks/RfqSetStatusToBidsReceived.java | 900639128e54389df07a9d80d6dd193b7ecdcdc6 | [] | no_license | zach-hu/srr_java8 | 6841936eda9fdcc2e8185b85b4a524b509ea4b1b | 9b6096ba76e54da3fe7eba70989978edb5a33d8e | refs/heads/master | 2021-01-10T00:57:42.107554 | 2015-11-06T14:12:56 | 2015-11-06T14:12:56 | 45,641,885 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,014 | java | package com.tsa.puridiom.rfq.tasks;
import com.tsa.puridiom.common.documents.DocumentStatus;
import com.tsa.puridiom.entity.RfqHeader;
import com.tsa.puridiom.entity.RfqLine;
import com.tsa.puridiom.property.PropertiesManager;
import com.tsagate.foundation.processengine.Task;
import java.util.List;
import java.util.Map;
public class RfqSetStatusToBidsReceived extends Task
{
public Object executeTask(Object object) throws Exception
{
Map incomingRequest = (Map)object;
String userId = (String) incomingRequest.get("userId") ;
PropertiesManager propertiesManager = PropertiesManager.getInstance((String)incomingRequest.get("organizationId")) ;
RfqHeader rfh = (RfqHeader)incomingRequest.get("rfqHeader") ;
List rfqLineList = (List) incomingRequest.get("rfqLineList") ;
rfh.setStatus(DocumentStatus.RFQ_PURCHASING);
for (int i=0; i < rfqLineList.size(); i++) {
RfqLine rfl = (RfqLine) rfqLineList.get(i);
rfl.setStatus(DocumentStatus.RFQ_PURCHASING) ;
}
return null ;
}
}
| [
"brickerz@9227675a-84a3-4efe-bc6c-d7b3a3cf6466"
] | brickerz@9227675a-84a3-4efe-bc6c-d7b3a3cf6466 |
a13b30ed2eca49d8c4b439e3ce322cce7011a21d | 8586e98fb86c40dd53d5dc6715e8abb2b8258150 | /src/visitor/exercise1/Element.java | d56446166b7ab971016cf333663888a4c647eb7e | [] | no_license | Kanject-Lang/DesignPatterns | 95b3aa04e79cb8797cb438c7aba781148ce17d85 | 30295422406f5073c4c162e03018802dabbe43f5 | refs/heads/master | 2023-07-01T13:08:21.422208 | 2021-08-07T02:49:14 | 2021-08-07T02:49:14 | 332,122,820 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 107 | java | package visitor.exercise1;
public interface Element {
public abstract void accept(Visitor visitor);
}
| [
"Um123456"
] | Um123456 |
04a5933e7002011d26df33aa7dd3a8840c7abdc1 | bfe4cc4bb945ab7040652495fbf1e397ae1b72f7 | /compute/src/main/java/org/jclouds/compute/predicates/NodeTerminated.java | ce3aee4317ddf55fc22aaae99eab8ba371ab998a | [
"Apache-2.0"
] | permissive | dllllb/jclouds | 348d8bebb347a95aa4c1325590c299be69804c7d | fec28774da709e2189ba563fc3e845741acea497 | refs/heads/master | 2020-12-25T11:42:31.362453 | 2011-07-30T22:32:07 | 2011-07-30T22:32:07 | 1,571,863 | 2 | 0 | null | null | null | null | UTF-8 | Java | false | false | 2,047 | java | /**
*
* Copyright (C) 2011 Cloud Conscious, LLC. <info@cloudconscious.com>
*
* ====================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* ====================================================================
*/
package org.jclouds.compute.predicates;
import static com.google.common.base.Preconditions.checkNotNull;
import javax.annotation.Resource;
import javax.inject.Singleton;
import org.jclouds.compute.ComputeService;
import org.jclouds.compute.domain.NodeMetadata;
import org.jclouds.compute.domain.NodeState;
import org.jclouds.logging.Logger;
import com.google.common.base.Predicate;
import com.google.inject.Inject;
/**
*
* Tests to see if a node is deleted
*
* @author Adrian Cole
*/
@Singleton
public class NodeTerminated implements Predicate<NodeMetadata> {
private final ComputeService client;
@Resource
protected Logger logger = Logger.NULL;
@Inject
public NodeTerminated(ComputeService client) {
this.client = client;
}
public boolean apply(NodeMetadata node) {
logger.trace("looking for state on node %s", checkNotNull(node, "node"));
node = refresh(node);
if (node == null)
return true;
logger.trace("%s: looking for node state %s: currently: %s",
node.getId(), NodeState.TERMINATED, node.getState());
return node.getState() == NodeState.TERMINATED;
}
private NodeMetadata refresh(NodeMetadata node) {
return client.getNodeMetadata(node.getId());
}
}
| [
"adrian@jclouds.org"
] | adrian@jclouds.org |
5ce983178b9d1891d4575c5d9d60558f8ff5fbb0 | 7e7c18edbdc789155b248ff5e7be6ba3c2b7a50c | /app/src/main/java/com/example/user/weadda/ProfileActivity.java | 2818330db2372fb885133b7ab2ba4b20bb8e40d0 | [] | no_license | nazmul-7/ChatApp-WeAdda | 0eeff8e881dadacb49ec58c98829cd10752e1815 | 9dbca3cbb93998df41c4a54fcf2fa5a8a21175c9 | refs/heads/master | 2020-04-19T00:09:33.626207 | 2019-01-27T17:55:25 | 2019-01-27T17:55:25 | 167,839,677 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 16,802 | java | package com.example.user.weadda;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;
import com.squareup.picasso.Picasso;
import java.util.HashMap;
import de.hdodenhof.circleimageview.CircleImageView;
public class ProfileActivity extends AppCompatActivity {
private String receiveUserID,senderUserID,Current_State;
private CircleImageView userProfileImage;
private TextView userProfileName,userProfileStatus;
private Button SendMessagrRequestButton,DeclineMessageRequestButton;
private FirebaseAuth mAuth;
private DatabaseReference UserRef,ChatRequestRef,ContactsRef,NotificationRef;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_profile);
mAuth = FirebaseAuth.getInstance();
UserRef = FirebaseDatabase.getInstance().getReference().child("Users");
ChatRequestRef = FirebaseDatabase.getInstance().getReference().child("Chat Requests");
ContactsRef = FirebaseDatabase.getInstance().getReference().child("Contacts");
NotificationRef = FirebaseDatabase.getInstance().getReference().child("Notifications");
receiveUserID = getIntent().getExtras().get("visit_user_id").toString();
senderUserID = mAuth.getCurrentUser().getUid();
userProfileImage = (CircleImageView) findViewById(R.id.visit_profile_image);
userProfileName = (TextView) findViewById(R.id.visit_user_name);
userProfileStatus= (TextView) findViewById(R.id.visit_profile_status);
SendMessagrRequestButton = (Button) findViewById(R.id.send_message_request_button);
DeclineMessageRequestButton = (Button) findViewById(R.id.decline_message_request_button);
Current_State = "new" ;
RetrieveUserInfo();
}
private void RetrieveUserInfo()
{
UserRef.child(receiveUserID).addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot)
{
if ((dataSnapshot.exists()) && dataSnapshot.hasChild("image"))
{
String userImage = dataSnapshot.child("image").getValue().toString();
String userName = dataSnapshot.child("name").getValue().toString();
String userStatus = dataSnapshot.child("status").getValue().toString();
Picasso.get().load(userImage).placeholder(R.drawable.profile_image).into(userProfileImage);
userProfileName.setText(userName);
userProfileStatus.setText(userStatus);
ManageChatRequests();
}
else
{
String userName = dataSnapshot.child("name").getValue().toString();
String userStatus = dataSnapshot.child("status").getValue().toString();
userProfileName.setText(userName);
userProfileStatus.setText(userStatus);
ManageChatRequests();
}
}
@Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
private void ManageChatRequests()
{
ChatRequestRef.child(senderUserID)
.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot)
{
if (dataSnapshot.hasChild(receiveUserID))
{
String request_type = dataSnapshot.child(receiveUserID).child("request_type").getValue().toString();
if (request_type.equals("sent")){
Current_State = "request_sent";
SendMessagrRequestButton.setText("Cancel chat request");
}
else if(request_type.equals("received"))
{
Current_State = "request_received";
SendMessagrRequestButton.setText("Accept chat request");
DeclineMessageRequestButton.setVisibility(View.VISIBLE);
DeclineMessageRequestButton.setEnabled(true);
DeclineMessageRequestButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view)
{
CancelChatRequest();
}
});
}
}
else{
ContactsRef.child(senderUserID)
.addListenerForSingleValueEvent(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot)
{
if (dataSnapshot.hasChild(receiveUserID)){
Current_State = "friends";
SendMessagrRequestButton.setText("Remove this contact");
}
}
@Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
}
@Override
public void onCancelled(DatabaseError databaseError) {
}
});
if (!senderUserID.equals(receiveUserID))
{
SendMessagrRequestButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
SendMessagrRequestButton.setEnabled(false);
if(Current_State.equals("new"))
{
SendChatRequest();
}
if (Current_State.equals("request_sent"))
{
CancelChatRequest();
}
if (Current_State.equals("request_received"))
{
AcceptChatRequest();
}
if (Current_State.equals("friends"))
{
RemoveSpecificContact();
}
}
});
}
else
{
SendMessagrRequestButton.setVisibility(View.INVISIBLE);
}
}
private void RemoveSpecificContact() {
ContactsRef.child(senderUserID).child(receiveUserID)
.removeValue()
.addOnCompleteListener(new OnCompleteListener<Void>() {
@Override
public void onComplete(@NonNull Task<Void> task)
{
if (task.isSuccessful())
{
ContactsRef.child(receiveUserID).child(senderUserID)
.removeValue()
.addOnCompleteListener(new OnCompleteListener<Void>() {
@Override
public void onComplete(@NonNull Task<Void> task)
{
if (task.isSuccessful()){
SendMessagrRequestButton.setEnabled(true);
Current_State = "new";
SendMessagrRequestButton.setText("Send Message");
DeclineMessageRequestButton.setVisibility(View.INVISIBLE);
DeclineMessageRequestButton.setEnabled(false);
}
}
});
}
}
});
}
private void AcceptChatRequest()
{
ContactsRef.child(senderUserID).child(receiveUserID)
.child("Contacts").setValue("Saved")
.addOnCompleteListener(new OnCompleteListener<Void>() {
@Override
public void onComplete(@NonNull Task<Void> task)
{
if (task.isSuccessful())
{
ContactsRef.child(receiveUserID).child(senderUserID)
.child("Contacts").setValue("Saved")
.addOnCompleteListener(new OnCompleteListener<Void>() {
@Override
public void onComplete(@NonNull Task<Void> task)
{
if (task.isSuccessful())
{
ChatRequestRef.child(senderUserID).child(receiveUserID)
.removeValue()
.addOnCompleteListener(new OnCompleteListener<Void>() {
@Override
public void onComplete(@NonNull Task<Void> task)
{
if (task.isSuccessful()){
ChatRequestRef.child(receiveUserID).child(senderUserID)
.removeValue()
.addOnCompleteListener(new OnCompleteListener<Void>() {
@Override
public void onComplete(@NonNull Task<Void> task) {
SendMessagrRequestButton.setEnabled(true);
Current_State = "friends";
SendMessagrRequestButton.setText("Remove this contact");
DeclineMessageRequestButton.setText(View.INVISIBLE);
DeclineMessageRequestButton.setEnabled(false);
}
});
}
}
});
}
}
});
}
}
});
}
private void CancelChatRequest()
{
ChatRequestRef.child(senderUserID).child(receiveUserID)
.removeValue()
.addOnCompleteListener(new OnCompleteListener<Void>() {
@Override
public void onComplete(@NonNull Task<Void> task)
{
if (task.isSuccessful())
{
ChatRequestRef.child(receiveUserID).child(senderUserID)
.removeValue()
.addOnCompleteListener(new OnCompleteListener<Void>() {
@Override
public void onComplete(@NonNull Task<Void> task)
{
if (task.isSuccessful()){
SendMessagrRequestButton.setEnabled(true);
Current_State = "new";
SendMessagrRequestButton.setText("Send Message");
DeclineMessageRequestButton.setVisibility(View.INVISIBLE);
DeclineMessageRequestButton.setEnabled(false);
}
}
});
}
}
});
}
private void SendChatRequest() {
ChatRequestRef.child(senderUserID).child(receiveUserID)
.child("request_type").setValue("sent")
.addOnCompleteListener(new OnCompleteListener<Void>() {
@Override
public void onComplete(@NonNull Task<Void> task)
{
if (task.isSuccessful())
{
ChatRequestRef.child(receiveUserID).child(senderUserID)
.child("request_type").setValue("received")
.addOnCompleteListener(new OnCompleteListener<Void>() {
@Override
public void onComplete(@NonNull Task<Void> task)
{
if (task.isSuccessful())
{
HashMap<String, String> chatnotification = new HashMap<>();
chatnotification.put("from",senderUserID);
chatnotification.put("type","request");
NotificationRef.child(receiveUserID).push()
.setValue(chatnotification)
.addOnCompleteListener(new OnCompleteListener<Void>() {
@Override
public void onComplete(@NonNull Task<Void> task)
{
if (task.isSuccessful())
{
SendMessagrRequestButton.setEnabled(true);
Current_State = "request_sent";
SendMessagrRequestButton.setText("Cancel chat request");
}
}
});
}
}
});
}
}
});
}
}
| [
"nazmulchowdhury4@gmail.com"
] | nazmulchowdhury4@gmail.com |
d2431b4f56645a99d86aac36209ddb340d7a23ba | 31c5e85697423b2763d12b0039ec73c92a1441e9 | /app/src/main/java/org/meruvian/workshop/fragment/DetailNewsFragment.java | 4baccf95ccd13daac11820acccae8b563b5b0f10 | [] | no_license | ricodidan/Workshop-Meruvian | ce76449f3a6415c22a5acbc913b0ed5b5f2d4dcb | 3ef48d905c6dfcf58df79920923fc5e04fea3757 | refs/heads/master | 2021-01-13T03:44:02.720472 | 2016-12-28T00:44:10 | 2016-12-28T00:44:10 | 77,271,456 | 1 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,382 | java | package org.meruvian.workshop.fragment;
import android.app.Fragment;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import org.meruvian.workshop.R;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
/**
* Created by Enrico_Didan on 23/12/2016.
*/
public class DetailNewsFragment extends Fragment {
private TextView title, date, content;
private DateFormat dateFormat = new SimpleDateFormat("dd-MM-yyyy hh:mm");
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment_detail, container, false);
}
@Override
public void onViewCreated(View view, Bundle savedInstanceState) {
title = (TextView) view.findViewById(R.id.text_title);
date = (TextView) view.findViewById(R.id.text_date);
content = (TextView) view.findViewById(R.id.text_content);
if (getArguments() != null) {
title.setText(getArguments().getString("title", "-"));
date.setText(dateFormat.format(new Date(getArguments().getLong("date", 0))));
content.setText(getArguments().getString("content", "-"));
}
}
}
| [
"ricodidan@gmail.com"
] | ricodidan@gmail.com |
36db2ca28450b6c6c9ea9061bfc2739ad1f5bf6d | 5edeaa8581a929b99d833bcbe10221a951a3ff86 | /app/src/main/java/com/nativenote/ejogajogassignment/view/LocationFragment.java | ffa7bd90e99d0f09c792a70f553191d8aa2ac043 | [] | no_license | Native-Note/Android-background-service-in-Oreo | c60cc26146612f046fdfd2b3cf0578c3d3f472c7 | 7ff1f8d7321a82d6a98716b83941eeb3d38659f3 | refs/heads/master | 2020-03-20T11:40:32.274983 | 2018-06-14T21:04:38 | 2018-06-14T21:04:38 | 137,408,972 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 9,933 | java | package com.nativenote.ejogajogassignment.view;
import android.Manifest;
import android.app.ActivityManager;
import android.content.Context;
import android.content.Intent;
import android.databinding.DataBindingUtil;
import android.graphics.Color;
import android.location.LocationManager;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.PowerManager;
import android.provider.Settings;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.design.widget.Snackbar;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import com.nativenote.ejogajogassignment.R;
import com.nativenote.ejogajogassignment.databinding.FragmentMainBinding;
import com.nativenote.ejogajogassignment.listener.SwitchCheckChangeListener;
import com.nativenote.ejogajogassignment.service.LocationService;
import com.nativenote.ejogajogassignment.utiles.ConnectionDetector;
import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import java.util.List;
import pub.devrel.easypermissions.EasyPermissions;
import static android.content.Context.LOCATION_SERVICE;
import static android.content.Context.POWER_SERVICE;
/**
* A placeholder fragment containing a simple view.
*/
public class LocationFragment extends Fragment implements EasyPermissions.PermissionCallbacks {
public static final String[] PERMISSION_LIST = {Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.ACCESS_FINE_LOCATION};
public final static int REQUEST_CODE = 3999;
private FragmentActivity mActivity;
private FragmentMainBinding binding;
private Snackbar snackbarPermissions;
private Snackbar snackbarGps;
@Override
public void onAttach(Context context) {
super.onAttach(context);
this.mActivity = (FragmentActivity) context;
}
public LocationFragment() {
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
binding = DataBindingUtil.inflate(inflater, R.layout.fragment_main, container, false);
binding.setIsChecked(false);
binding.setCallback(listener);
return binding.getRoot();
}
@Override
public void onActivityCreated(@Nullable Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
requestOptimize();
}
@Override
public void onStart() {
super.onStart();
EventBus.getDefault().register(this);
}
@Override
public void onResume() {
super.onResume();
if (hasAllPermission())
enableSwitch();
else
EasyPermissions.requestPermissions(this, getResources().getString(R.string.permission_txt), REQUEST_CODE, PERMISSION_LIST);
}
private void requestOptimize() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
PowerManager powerManager = (PowerManager) mActivity.getSystemService(Context.POWER_SERVICE);
Intent intent = new Intent();
intent.setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
if (powerManager.isIgnoringBatteryOptimizations(mActivity.getApplicationContext().getPackageName())) {
intent.setAction(Settings.ACTION_IGNORE_BATTERY_OPTIMIZATION_SETTINGS);
} else {
intent.setAction(Settings.ACTION_REQUEST_IGNORE_BATTERY_OPTIMIZATIONS);
intent.setData(Uri.parse("package:" + mActivity.getApplicationContext().getPackageName()));
startActivity(intent);
}
}
}
@Override
public void onStop() {
EventBus.getDefault().unregister(this);
super.onStop();
}
@Subscribe(threadMode = ThreadMode.MAIN, sticky = true)
public void onEvent(ContentModel event) {
binding.setLocText(event.getData());
}
private void enableSwitch() {
binding.workingSwitch.setEnabled(true);
if (isServiceRunning(LocationService.class, mActivity))
binding.setIsChecked(true);
}
SwitchCheckChangeListener listener = checked -> {
if (checked) {
if (!ConnectionDetector.isNetworkPresent(mActivity)) {
binding.setIsChecked(false);
Snackbar.make(binding.getRoot(), mActivity.getResources().getString(R.string.no_internet), Snackbar.LENGTH_LONG).show();
return;
}
checkLocationPermission();
} else {
if (isServiceRunning(LocationService.class, mActivity))
stopLocationService();
}
};
private void checkLocationPermission() {
if (!hasAllPermission()) {
binding.setIsChecked(false);
EasyPermissions.requestPermissions(this, getResources().getString(R.string.permission_txt), REQUEST_CODE, PERMISSION_LIST);
} else {
checkGpsEnabled();
}
}
private void checkGpsEnabled() {
LocationManager lm = (LocationManager) mActivity.getApplicationContext().getSystemService(LOCATION_SERVICE);
if (!lm.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
reportGpsError();
} else {
resolveGpsError();
if (isServiceRunning(LocationService.class, mActivity))
stopLocationService();
startLocationService();
}
}
public static boolean isServiceRunning(Class<?> serviceClass, Context context) {
ActivityManager manager = (ActivityManager) context.getApplicationContext().getSystemService(Context.ACTIVITY_SERVICE);
for (ActivityManager.RunningServiceInfo service : manager.getRunningServices(Integer.MAX_VALUE)) {
if (serviceClass.getName().equals(service.service.getClassName())) {
return true;
}
}
return false;
}
private void reportPermissionsError() {
binding.setIsChecked(false);
snackbarPermissions = Snackbar
.make(binding.getRoot(),
getString(R.string.location_permission_required),
Snackbar.LENGTH_INDEFINITE)
.setAction(R.string.enable, view -> {
resolvePermissionsError();
Intent intent = new Intent(Settings
.ACTION_APPLICATION_DETAILS_SETTINGS);
intent.setData(Uri.parse("package:" + mActivity.getApplicationContext().getPackageName()));
startActivity(intent);
});
snackbarPermissions.setActionTextColor(Color.RED);
View sbView = snackbarPermissions.getView();
TextView textView = sbView.findViewById(android.support.design.R.id.snackbar_text);
textView.setTextColor(Color.YELLOW);
snackbarPermissions.show();
}
private void resolvePermissionsError() {
if (snackbarPermissions != null) {
snackbarPermissions.dismiss();
snackbarPermissions = null;
}
}
private void reportGpsError() {
binding.setIsChecked(false);
snackbarGps = Snackbar
.make(binding.getRoot(), getString(R.string.gps_required), Snackbar.LENGTH_INDEFINITE)
.setAction(R.string.enable, view -> {
resolveGpsError();
startActivity(new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS));
});
snackbarGps.setActionTextColor(Color.RED);
View sbView = snackbarGps.getView();
TextView textView = sbView.findViewById(android.support.design.R.id.snackbar_text);
textView.setTextColor(Color.YELLOW);
snackbarGps.show();
}
private void resolveGpsError() {
if (snackbarGps != null) {
snackbarGps.dismiss();
snackbarGps = null;
}
}
private void startLocationService() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
PowerManager pm = (PowerManager) mActivity.getApplicationContext().getSystemService(POWER_SERVICE);
Intent intent = new Intent();
if (!pm.isIgnoringBatteryOptimizations(mActivity.getApplicationContext().getPackageName())) {
intent.setAction(Settings.ACTION_REQUEST_IGNORE_BATTERY_OPTIMIZATIONS);
intent.setData(Uri.parse("package:" + mActivity.getApplicationContext().getPackageName()));
startActivity(intent);
}
}
Intent intent = new Intent(mActivity, LocationService.class);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
mActivity.startForegroundService(intent);
} else {
mActivity.startService(intent);
}
}
private void stopLocationService() {
Intent intent = new Intent(mActivity, LocationService.class);
mActivity.stopService(intent);
}
private boolean hasAllPermission() {
return EasyPermissions.hasPermissions(mActivity, PERMISSION_LIST);
}
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
EasyPermissions.onRequestPermissionsResult(requestCode, permissions, grantResults, this);
}
@Override
public void onPermissionsGranted(int requestCode, @NonNull List<String> perms) {
enableSwitch();
}
@Override
public void onPermissionsDenied(int requestCode, @NonNull List<String> perms) {
reportPermissionsError();
// mActivity.finish();
}
}
| [
"nisat19@gmail.com"
] | nisat19@gmail.com |
6f69b10c755f9fc9b91601918132fad4ffcd1026 | 7f522789c31154a33dde9d62e9a6df02f7d7d744 | /src/main/java/com/pet/bankservice/entity/Transaction.java | 552c785cb41e357ed12340bdf5aa0785b4d4ae40 | [] | no_license | semyonich/bank-service | ea0b197f70ce9b3d86c7c4689777cebcd894ff29 | b76917fbc0bde8cf3d4e351985b453cd745bf767 | refs/heads/master | 2023-03-20T01:51:38.401406 | 2021-03-16T16:40:33 | 2021-03-16T16:40:33 | 342,699,413 | 1 | 0 | null | 2021-03-16T16:40:33 | 2021-02-26T20:58:47 | Java | UTF-8 | Java | false | false | 1,746 | java | package com.pet.bankservice.entity;
import java.math.BigDecimal;
import java.time.LocalDateTime;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.EnumType;
import javax.persistence.Enumerated;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.Table;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
@Data
@Builder
@AllArgsConstructor
@NoArgsConstructor
@Entity
@Table(name = "transactions")
public class Transaction {
public enum TransactionType {
INCOMING,
OUTCOMING;
}
public enum StatusType {
OK,
ERROR;
}
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@ManyToOne
@JoinColumn(name = "from_account_id")
private Account fromAccount;
@ManyToOne
@JoinColumn(name = "to_account_id")
private Account toAccount;
@Column(name = "date_time")
private LocalDateTime dateTime;
private BigDecimal amount;
@Enumerated(EnumType.STRING)
private TransactionType type;
@Enumerated(EnumType.STRING)
private StatusType status;
@Override
public String toString() {
return "Transaction{"
+ "id=" + id
+ ", fromAccount=" + fromAccount.getAccountNumber()
+ ", toAccount=" + toAccount.getAccountNumber()
+ ", dateTime=" + dateTime
+ ", amount=" + amount
+ ", type=" + type
+ ", status='" + status + '\''
+ '}';
}
}
| [
"semyonich@users.noreply.github.com"
] | semyonich@users.noreply.github.com |
cdacf7eed583110633554bb583eb4d170913c715 | 7bbadc3a4cfa16193ec33f457f18eb3d547222dc | /redis-distributed-lock-starter/src/main/java/com/ciwei/lock/redisson/config/EnableRedissonLock.java | 2b4c47ec571b8175e2cf22da252e5d7ca2502368 | [] | no_license | FuhangOliver/springboot-starter-collection | 1688de96345db0f85144880b0f68d2344ce9956f | 3236d0c91b0d741764a76157536ea68f494d55d8 | refs/heads/master | 2022-12-16T23:43:05.113419 | 2020-09-14T08:26:04 | 2020-09-14T08:26:04 | 295,346,009 | 1 | 1 | null | null | null | null | UTF-8 | Java | false | false | 376 | java | package com.ciwei.lock.redisson.config;
import org.springframework.context.annotation.Import;
import java.lang.annotation.*;
/**
* @author FuHang
* @date 2019/7/10
* @desc 开启Redisson注解支持
*/
@Inherited
@Documented
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Import(RedissonAutoConfiguration.class)
public @interface EnableRedissonLock {
}
| [
"1170115956@qq.com"
] | 1170115956@qq.com |
f3722a7b130b28b3a9e8a0a52b57d67c28414a85 | acbf25323a68b1eec69fab0e3b104faff265e863 | /src/main/java/com/nowcoder/community/config/ConfigAlpha.java | d4506c576aacd9f9c5806520b2908ee754d59659 | [] | no_license | wsnd123/community | 418d80543963431d802075f37bcf96bcd97d21cf | 128ca0af1a4615839a8762716e65a8100e97b318 | refs/heads/master | 2023-08-22T08:07:43.092693 | 2021-09-25T08:07:38 | 2021-09-25T08:07:38 | 409,911,190 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 508 | java | package com.nowcoder.community.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import java.text.SimpleDateFormat;
@Configuration//表示这是一个配置类 与配置类相关的扫描组件
public class ConfigAlpha {
@Bean//方法名就是Bean的名字 这个方法返回的值将会被装配到容器中
public SimpleDateFormat simpleDateFormat(){
return new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
}
}
| [
"1476241623@qq.com"
] | 1476241623@qq.com |
fdfccac5fbf443c0531cc18ae69553c51a95cc0c | 6d6f10478cbdf4a34b418f8fb677208be09ff417 | /src/mvc/WarUiEventListener.java | 77d01c176ddd6455138e351a09bfcc1dc8f23cf6 | [] | no_license | mennyaboush/warSimulator | 0610e740f3c60b7610c4d2c6a052d91c01728d8f | 237c7febcad07208698bc629ddb27a15999fcbe5 | refs/heads/master | 2020-03-08T14:38:50.614631 | 2018-06-12T13:25:01 | 2018-06-12T13:25:01 | 128,191,689 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 409 | java | package mvc;
import java.util.List;
import Enum.City;
import bl.Missile;
public interface WarUiEventListener {
void addLauncherFromUi();
void addLauncherDestructorFromUi();
void addMissileDestructorFromUi();
void fireFromLauncherFromUi(City city);
void fireFromlauncherDestructorsFromUi();
void fireFromMissileDestructorsFromUi();
void printSummaryFromUi();
void ExitFromUi();
}
| [
"mennyaboush@gmail.com"
] | mennyaboush@gmail.com |
d7e5858ad5d705e647ac5604909b8870fa9d40f4 | e537bbcecd379a3e97a0c81a7e23edac788a1371 | /src/main/java/com/jenkov/db/impl/mapping/method/CharacterStream.java | b2658334efd090f60b4f83f1ac18df0ab7044f44 | [
"Apache-2.0"
] | permissive | jjenkov/butterfly-persistence | 92670d41d48fe0f129c2ce2ea246b8aa7ff4cf18 | c644d102b32e433119f6ac7871ac18bdc9d69948 | refs/heads/master | 2022-02-21T06:11:43.732748 | 2022-02-04T16:35:17 | 2022-02-04T16:35:17 | 54,051,360 | 23 | 16 | Apache-2.0 | 2022-02-04T16:35:18 | 2016-03-16T17:08:46 | Java | UTF-8 | Java | false | false | 1,044 | java | package com.jenkov.db.impl.mapping.method;
import java.io.Reader;
/**
* @author Jakob Jenkov, Jenkov Development
*/
public class CharacterStream {
protected Reader reader = null;
protected int length = 0;
public CharacterStream(Reader reader) {
this.reader = reader;
}
public CharacterStream(Reader reader, int length) {
this.reader = reader;
this.length = length;
}
public Reader getReader() {
return reader;
}
public void setReader(Reader reader) {
this.reader = reader;
}
public int getLength() {
return length;
}
public void setLength(int length) {
this.length = length;
}
public boolean equals(Object obj) {
if(obj == null) return false;
if(!(obj instanceof CharacterStream)) return false;
CharacterStream otherStream = (CharacterStream) obj;
if(getLength() != otherStream.getLength()) return false;
return getReader().equals(otherStream.getReader());
}
}
| [
"jakob@jenkov.com"
] | jakob@jenkov.com |
17f41041d2e1eacc7aac4b1178362069fce9434c | eb993770c0b2f352a79d55ad5e6fc8e00b854b12 | /src/com/zaren/HdhomerunSignalMeterLib/data/HdhomerunDevice.java | aaea1ed775ddf256991c4dd04666e5737b30e7a5 | [] | no_license | cfraser/HdhomerunSignalMeterLib | 0a568395de83b9d288cf5beee39189455edc9ecc | 51f0db13a58fdf95c65f5f8ca33da02a4b84c753 | refs/heads/master | 2021-01-16T21:20:21.346251 | 2013-06-14T15:18:52 | 2013-06-14T15:18:52 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 21,775 | java | package com.zaren.HdhomerunSignalMeterLib.data;
import com.zaren.HdhomerunSignalMeterLib.util.ErrorHandler;
import com.zaren.HdhomerunSignalMeterLib.util.HDHomerunLogger;
import com.zaren.HdhomerunSignalMeterLib.util.Utils;
import java.io.Serializable;
import java.util.Arrays;
import java.util.List;
import java.util.NoSuchElementException;
import java.util.StringTokenizer;
public class HdhomerunDevice implements Serializable
{
private static final long serialVersionUID = 1942906208628106963L;
public static final String DEVICE_CABLECARD = "cablecard";
public static final String DEVICE_ATSC = "atsc";
//reset constants
public static final String SELF = "self";
public static final String CABLECARD = "cablecard";
private int cPointer;
private long deviceId;
private int ipAddr;
private int tuner;
private String[] channelMaps;
private String deviceName;
private TunerStatus prevTunerStatus;
private String prevChannelMap;
private String deviceType;
private transient ChannelList channelList = new ChannelList(); //this is transient because it is not serializable
/*
* this is used to load the native library on application startup. The
* library has already been unpacked into /data/data/PROJECT/lib/C-FILE.so at
* installation time by the package manager.
*/
static
{
System.loadLibrary("hdhomerun");
}
public HdhomerunDevice(long deviceId_val, int ipAddr_val, int tuner_val ) throws HdhomerunCommErrorException
{
String supportedString;
this.deviceId = deviceId_val;
this.ipAddr = ipAddr_val;
this.tuner = tuner_val;
cPointer = JNIcreateNewDevice(deviceId_val, ipAddr_val, tuner_val);
deviceName = Long.toHexString(deviceId_val) + "-" + tuner_val;
HDHomerunLogger.d("Device created id:" + deviceName);
// Now Lets collect the supported channelmaps
supportedString = JNIgetSupported(cPointer);
HDHomerunLogger.d(supportedString);
StringTokenizer st = new StringTokenizer(supportedString, "\n");
while (st.hasMoreTokens() == true)
{
processSupportedString(st.nextToken());
}
//now the device type
String deviceModel = getModel();
HDHomerunLogger.d("Device model " + deviceModel);
if(deviceModel.contains("cablecard"))
{
deviceType = DEVICE_CABLECARD;
}
else
{
deviceType = DEVICE_ATSC;
}
HDHomerunLogger.d("Device type " + deviceType);
}
private void processSupportedString(String token)
{
StringTokenizer st = new StringTokenizer(token);
// need at least two tokens, one for the key and 1 for the value, if not
// at least 2 its worthless
if (st.countTokens() > 1)
{
String key = st.nextToken();
if (key.equals("channelmap:"))
{
int i = 0; // just a counter
channelMaps = new String[st.countTokens()];
while (st.hasMoreTokens() == true)
{
channelMaps[i] = st.nextToken();
i++;
}
}
else if (key.equals("modulation:"))
{
// don't care about this yet
}
else if (key.equals("auto-modulation:"))
{
// don't care about this yet
}
else
{
HDHomerunLogger.w("Unhandled token type: " + key);
}
}
}
public void destroy()
{
HDHomerunLogger.d("Destroying device " + deviceName);
JNIdestroy(cPointer);
cPointer = -1;
}
synchronized public int setChannelMap(String channelMap)
{
HDHomerunLogger.d("Set ChannelMap to " + channelMap + " for device "
+ deviceName);
int status = JNIsetChannelMap(this.cPointer, channelMap);
//TODO need to recalc channellist
return status;
}
private native int JNIgetTunerChannel( int aCPointer, JniString aChannel );
public int getTunerChannel( JniString aChannel )
{
int theRetVal = JNIgetTunerChannel( cPointer, aChannel );
HDHomerunLogger.d("getTunerChannel: return val " + theRetVal + " channel: " + aChannel.getString());
return theRetVal;
}
synchronized public int setTunerChannel(String channel)
{
HDHomerunLogger.d("Set Channel to " + channel + " for device "
+ deviceName);
int status;
status = JNIsetTunerChannel(cPointer, channel);
//TODO for some reason this is crashing when we hit the end of a channel scan for the cable channelmaps
//checkForError(status, "SetTunerChannel");
if (status == -1)
{
// network error, we need to give up
}
return status;
}
synchronized public TunerStatus getTunerStatus()
{
TunerStatus tunerStatus = JNIgetTunerStatus(cPointer);
boolean error = checkForError(tunerStatus.returnStatus, "GetTunerStatus");
if (error == false)
{
prevTunerStatus = tunerStatus;
return tunerStatus;
}
else
{
return prevTunerStatus;
}
}
public synchronized int updateTunerStatus(TunerStatus tunerStatus)
{
int status = JNIupdateTunerStatus(cPointer, tunerStatus);
checkForError(status, "UpdateTunerStatus");
return status;
}
private synchronized native int JNIcreateNewDevice(long deviceId, long ipAddr, int tuner);
private synchronized native int JNIsetChannelMap(int cPointer, String channelMap);
private synchronized native int JNIsetTunerChannel(int cPointer, String channel);
private synchronized native int JNIsetTunerVChannel(int cPointer, String channel);
private synchronized native int JNIwaitForLock(int cPointer, TunerStatus tunerStatus);
synchronized public int waitForLock(TunerStatus tunerStatus)
{
int retVal = JNIwaitForLock(cPointer, tunerStatus);
ErrorHandler.HandleError(retVal, "Wait for Lock");
return retVal;
}
private synchronized native int JNIgetTunerStreamInfo(int cPointer, JniString streamInfo);
synchronized public int getTunerStreamInfo(ProgramsList thePrograms)
{
JniString streamInfo = new JniString();
int retVal = JNIgetTunerStreamInfo(cPointer, streamInfo);
ErrorHandler.HandleError(retVal, "Get Tuner Stream Info");
if(retVal > 0)
{
convertStreamInfoToPrograms(streamInfo.getString(), thePrograms);
}
return retVal;
}
private void convertStreamInfoToPrograms(
String streamInfo, ProgramsList thePrograms)
{
StringTokenizer theProgramStrings = new StringTokenizer(streamInfo,"\n");
while(theProgramStrings.hasMoreTokens())
{
try
{
String theProgramString = "";
if( theProgramStrings.hasMoreTokens() )
{
theProgramString = theProgramStrings.nextToken();
}
HDHomerunLogger.d( "Parsing program string: " + theProgramString );
StringTokenizer theProgNumAndName = new StringTokenizer( theProgramString, ":" );
ChannelScanProgram theProgram = new ChannelScanProgram();
theProgram.programString = theProgramString;
while( theProgNumAndName.hasMoreTokens() )
{
theProgram.programNumber = Integer.parseInt( theProgNumAndName.nextToken() );
processProgramName( theProgNumAndName.nextToken(), theProgram );
}
thePrograms.append( theProgram.programNumber, theProgram );
}
catch( NumberFormatException e )
{
HDHomerunLogger.e( "Error Parsing String: " + e );
}
catch( NoSuchElementException e )
{
HDHomerunLogger.e( "NoSuchElementException: " + e );
}
}
}
private static final String[] theTypes = new String[]{ "control", "encrypted", "no data", "internet"};
private void processProgramName( String aProgramName, ChannelScanProgram aProgram )
{
int theOpeningParen = aProgramName.indexOf( "(" );
int theClosingParen = aProgramName.indexOf( ")" );
String theJustProgramName = aProgramName;
if( theOpeningParen != -1 && theClosingParen != -1 )
{
//This is the string that says "control" or "encrypted" or "no data"
String theTypeString = aProgramName.substring( theOpeningParen + 1, theClosingParen );
List< String > theTypeStrings = Arrays.asList( theTypes );
if( theTypeStrings.contains( theTypeString ) )
{
aProgram.type = theTypeString;
theJustProgramName = aProgramName.substring( 0, theOpeningParen );
}
}
StringTokenizer theStrings = new StringTokenizer( theJustProgramName, " " );
String theChannelNumbers = theStrings.nextToken();
StringTokenizer theChannelStrings = new StringTokenizer( theChannelNumbers, "." );
aProgram.virtualMajor = Integer.parseInt( theChannelStrings.nextToken() );
if( theChannelStrings.hasMoreTokens() )
{
aProgram.virtualMinor = Integer.parseInt( theChannelStrings.nextToken() );
}
StringBuilder theNameStringBuilder = new StringBuilder();
while( theStrings.hasMoreTokens() )
{
String theString = theStrings.nextToken();
if( theNameStringBuilder.length() > 0 )
{
theNameStringBuilder.append( " " );
}
theNameStringBuilder.append( theString );
}
aProgram.name = theNameStringBuilder.toString();
}
private synchronized native TunerStatus JNIgetTunerStatus(int cPointer);
private synchronized native String JNIgetSupported(int cPointer);
private synchronized native void JNIdestroy(int cPointer);
private synchronized native String JNIgetChannelMap(int cPointer);
private synchronized native int JNIupdateTunerStatus(int cPointer, TunerStatus tunerStatus);
private synchronized native int JNIupdateTunerVStatus(int cPointer, TunerVStatus tunerVStatus);
public int updateTunerVStatus(TunerVStatus tunerVStatus)
{
int status = JNIupdateTunerVStatus(cPointer, tunerVStatus);
checkForError(status, "UpdateTunerVStatus");
return status;
}
private synchronized native TunerVStatus JNIgetTunerVStatus(int cPointer);
public TunerVStatus getTunerVStatus()
{
TunerVStatus tunerVStatus = JNIgetTunerVStatus(cPointer);
return tunerVStatus;
}
private synchronized native String JNIgetModel(int cPointer);
public String getModel() throws HdhomerunCommErrorException
{
String retVal = JNIgetModel(cPointer);
if(retVal == null)
{
throw new HdhomerunCommErrorException("Failed to get model information");
}
return retVal;
}
private synchronized native int JNIcreateChannelList(String channelMap, ChannelList channelList);
public int createChannelList(String channelMap, ChannelList channelList)
{
int status = JNIcreateChannelList(channelMap, channelList);
this.channelList = channelList;
return status;
}
/**
* @return the channelMaps
*/
public String[] getChannelMaps()
{
return channelMaps;
}
synchronized public String getCurrentChannelMap()
{
String channelMap = JNIgetChannelMap(cPointer);
boolean error = checkForError(channelMap, "GetCurrentChannelMap");
if (error == false)
{
prevChannelMap = channelMap;
return channelMap;
}
else
{
return prevChannelMap;
}
}
private boolean checkForError(int returnStatus, String message)
{
//ErrorHandler.HandleError(returnStatus, message);
if (returnStatus == 0)
{
return true;
}
else if (returnStatus == -1)
{
return true;
}
return false;
}
private boolean checkForError(String returnString, String message)
{
if (returnString.equals("rejected"))
{
//ErrorHandler.HandleError(0, message);
return true;
}
else if (returnString.equals("Network failure"))
{
//ErrorHandler.HandleError(-1, message);
return true;
}
return false;
}
public int getCurrentChannel()
{
TunerStatus tunerStatus = getTunerStatus();
String channelString = tunerStatus.channel;
if (channelString.equals("none"))
{
return -1;
}
else
{
String[] splitString = channelString.split(":");
return Integer.parseInt(splitString[1]);
}
}
String buildChannelStringFromTunerStatus(String channel, String lockStr)
{
HDHomerunLogger.v("BuildChannelString: "+channel + " " + lockStr);
if(channel.equals("none"))
{
return channel;
}
else
{
String[] splitString = channel.split(":");
if(splitString.length > 1)
{
int channel_int = Integer.parseInt(splitString[1]);
if(channel_int > 1000)
{
//this must be a frequency value
channel_int = frequencyToChannelNumber(channel_int);
if(channel_int == 0)
{
//for some reason we couldn't match up the frequency to channel number, just return the frequency
return lockStr + ":" + splitString[1];
}
return lockStr + ":" + channel_int;
}
else
{
return lockStr + ":" + splitString[1];
}
}
else
{
//something was wrong with the channel from the device
return "none";
}
}
}
protected String getChannelNumberFromChannelString(String channelString)
{
HDHomerunLogger.v("getChannelNumberFromChannelString(): " + channelString);
if(channelString.equals("none"))
{
return "";
}
//first split on a comma, sometimes the channelString comes back as two different channelmaps, not sure why
String channelMapstrings[] = channelString.split(",");
//just use the first one
String strings[] = channelMapstrings[0].split(":");
//if it didn't return more than two results that means for some reason we don't have a channel number
if(strings.length < 2)
{
return "";
}
int channelInt = Integer.parseInt(strings[1]);
if(channelInt > 1000)
{
//this must be a frequency value
int convertedChannelInt = frequencyToChannelNumber(channelInt);
if(convertedChannelInt == 0)
{
//for some reason we couldn't match up the frequency to channel number, just return the frequency
return ""+channelInt;
}
return ""+convertedChannelInt;
}
else
{
return ""+channelInt;
}
}
public int frequencyToChannelNumber(int frequency)
{
return channelList.frequencyToNumber(frequency);
}
/**
* @return the cPointer
*/
public int getcPointer()
{
return cPointer;
}
/**
* @return the deviceName
*/
public String getDeviceName()
{
return deviceName;
}
/**
* @return the deviceId
*/
public long getDeviceId()
{
return deviceId;
}
/**
* @return the ipAddr
*/
public int getIpAddr()
{
return ipAddr;
}
/**
* @return the ipAddr as a byte array
*/
public byte[] getIpAddrArray()
{
return Utils.HdHrIpAddressToByteArray(ipAddr);
}
/**
* @return the tuner
*/
public int getTuner()
{
return tuner;
}
/**
* @return the deviceType
*/
public String getDeviceType()
{
return deviceType;
}
public int setTunerVChannel(String channel)
{
HDHomerunLogger.d("Set Virtual Channel to " + channel + " for device "
+ deviceName);
int status;
status = JNIsetTunerVChannel(cPointer, channel);
//TODO for some reason this is crashing when we hit the end of a channel scan for the cable channelmaps
//checkForError(status, "SetTunerChannel");
if (status == -1)
{
// network error, we need to give up
}
return status;
}
private native int JNIgetTunerVChannel( int aCPointer, JniString aVChannel );
public int getTunerVChannel( JniString aVChannel )
{
int theRetVal = JNIgetTunerVChannel( cPointer, aVChannel );
HDHomerunLogger.d("getTunerVChannel: return val " + theRetVal + " program: " + aVChannel.getString());
return theRetVal;
}
private native String JNIgetFirmwareVersion(int cPointer2);
public String getFirmwareVersion()
{
return JNIgetFirmwareVersion(cPointer);
}
private native String JNIgetLockkeyOwner(int cPointer2);
public String getLockkeyOwner()
{
return JNIgetLockkeyOwner(cPointer);
}
private native String JNIgetTunerTarget(int cPointer2);
public String getTargetIp()
{
return JNIgetTunerTarget(cPointer);
}
private native int JNIsetVar(int cPointer, String var, String value);
public int setVar(String var, String value)
{
return JNIsetVar(cPointer, var, value);
}
private native int JNIgetVar(int cPointer, String var, JniString aValue, JniString aError);
public int getVar(String var, JniString aValue, JniString aError)
{
return JNIgetVar(cPointer, var, aValue, aError);
}
private native int JNItunerLockeyRequest(int cPointer, JniString error);
public int tunerLockeyRequest(JniString error)
{
int retVal = JNItunerLockeyRequest(cPointer, error);
HDHomerunLogger.d("tunerLockeyRequest: return val " + retVal + " error: " + error.getString());
return retVal;
}
private native int JNItunerLockeyRelease(int cPointer);
public int tunerLockeyRelease()
{
int retVal = JNItunerLockeyRelease(cPointer);
HDHomerunLogger.d("tunerLockeyRelease: return val " + retVal);
return retVal;
}
private native int JNItunerLockeyForce(int cPointer);
public int tunerLockeyForce()
{
int retVal = JNItunerLockeyForce(cPointer);
HDHomerunLogger.d("tunerLockeyForce: return val " + retVal);
return retVal;
}
private native int JNIgetTunerProgram(int cPointer, JniString program);
public int getTunerProgram(JniString program)
{
int retVal = JNIgetTunerProgram(cPointer, program);
//HDHomerunLogger.d("getTunerProgram: return val " + retVal + " program: " + program.getString());
return retVal;
}
private native int JNIsetTunerProgram(int cPointer, String progNumber);
public int setTunerProgram(String progNumber)
{
int retVal = JNIsetTunerProgram(cPointer, progNumber);
HDHomerunLogger.d("setTunerProgram: return val " + retVal);
return retVal;
}
private native int JNIsetTunerTarget(int cPointer, String targetString);
public int setTargetIP(String targetString)
{
int retVal = JNIsetTunerTarget(cPointer, targetString);
HDHomerunLogger.d("setTargetIP: " + targetString + " return val " + retVal);
return retVal;
}
private native void JNIstreamStop(int cPointer);
public void stopStreaming()
{
HDHomerunLogger.d("Device: stopStreaming");
JNIstreamStop(cPointer);
}
public CableCardStatus getCardStatus()
{
JniString theValue = new JniString();
JniString theError = new JniString();
int theStatus = getVar( "/card/status", theValue, theError );
HDHomerunLogger.d( "getCardStatus: theStatus = " + theStatus + " theValue = " + theValue + " theError = " + theError );
CableCardStatus theReturn = new CableCardStatus();
if( theStatus == DeviceResponse.SUCCESS )
{
//process response
processCardStatus( theValue, theReturn );
}
return theReturn;
}
private void processCardStatus( JniString aValue, CableCardStatus aReturn )
{
StringTokenizer theKeyValPairs = new StringTokenizer( aValue.getString(), " " );
while( theKeyValPairs.hasMoreTokens() )
{
String theKeyVal = theKeyValPairs.nextToken();
int theEqualsIndex = theKeyVal.indexOf( '=' );
if( theEqualsIndex != -1 )
{
String theKey = theKeyVal.substring( 0, theEqualsIndex );
String theVal = theKeyVal.substring( theEqualsIndex + 1, theKeyVal.length() );
if( theKey.equals("card") )
{
aReturn.setCard( theVal );
}
else if( theKey.equals("auth") )
{
aReturn.setAuth( theVal );
}
else if( theKey.equals("oob") )
{
aReturn.setOob( theVal );
}
else if( theKey.equals("act") )
{
aReturn.setAct( theVal );
}
}
}
}
} //end class HdhomerunDevice
| [
"zaren678@gmail.com"
] | zaren678@gmail.com |
a16bb092e3b8a329c46a4339b71076ce658536d2 | bf191013d04cf9597bc93241e56db63ef20018af | /lwmybatis/src/main/java/com/linkwe/sqlsession/Excutor.java | ecf1f60bbf1795b1d177873ae2c030b3fea49671 | [] | no_license | linkwe-z/myproject | a2d725f41a58a7c059c5f37bbe573a566e8ca17b | 271dba4e528da58e6e1e67fcc468ab0bd97dea89 | refs/heads/master | 2020-04-22T14:04:38.727986 | 2019-02-14T07:21:49 | 2019-02-14T07:21:49 | 170,431,022 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 162 | java | package com.linkwe.sqlsession;
/**
* @Author: zenglw
* @Date: 2019-01-31
*/
public interface Excutor {
<T> T query(String statement, Object parameter);
}
| [
"13537251451@163.com"
] | 13537251451@163.com |
f4d65a43e44bf3f0949f5498fea7c48164d5bae0 | c1bbb030862c00bd8f4cce851bca9919a3486da8 | /androidWidget/src/com/kerkr/edu/recycleView/VerticalDividerItemDecoration.java | d3cadcc8a96c4c277d1e2f2c7e16d6f730fc0526 | [] | no_license | caocf/androidBaseLib | 19c8a2032d527b92e66fd7a3da55d0694854d282 | 4ec7398f113cf2bd3d2ace9032d825b6c3165cd9 | refs/heads/master | 2020-02-26T17:12:54.865258 | 2015-07-17T09:35:05 | 2015-07-17T09:35:05 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 4,929 | java | package com.kerkr.edu.recycleView;
import android.content.Context;
import android.graphics.Rect;
import android.graphics.drawable.Drawable;
import android.support.annotation.DimenRes;
import android.support.v4.view.ViewCompat;
import android.support.v7.widget.RecyclerView;
import android.view.View;
/**
* Created by yqritc on 2015/01/15.
*/
public class VerticalDividerItemDecoration extends FlexibleDividerDecoration {
private MarginProvider mMarginProvider;
protected VerticalDividerItemDecoration(Builder builder) {
super(builder);
mMarginProvider = builder.mMarginProvider;
}
@Override
protected Rect getDividerBound(int position, RecyclerView parent, View child) {
Rect bounds = new Rect(0, 0, 0, 0);
int transitionX = (int) ViewCompat.getTranslationX(child);
int transitionY = (int) ViewCompat.getTranslationY(child);
RecyclerView.LayoutParams params = (RecyclerView.LayoutParams) child.getLayoutParams();
bounds.top = parent.getPaddingTop() +
mMarginProvider.dividerTopMargin(position, parent) + transitionY;
bounds.bottom = parent.getHeight() - parent.getPaddingBottom() -
mMarginProvider.dividerBottomMargin(position, parent) + transitionY;
int dividerSize = getDividerSize(position, parent);
if (mDividerType == DividerType.DRAWABLE) {
bounds.left = child.getRight() + params.leftMargin + transitionX;
bounds.right = bounds.left + dividerSize;
} else {
bounds.left = child.getRight() + params.leftMargin + dividerSize / 2 + transitionX;
bounds.right = bounds.left;
}
return bounds;
}
@Override
protected void setItemOffsets(Rect outRect, int position, RecyclerView parent) {
outRect.set(0, 0, getDividerSize(position, parent), 0);
}
private int getDividerSize(int position, RecyclerView parent) {
if (mPaintProvider != null) {
return (int) mPaintProvider.dividerPaint(position, parent).getStrokeWidth();
} else if (mSizeProvider != null) {
return mSizeProvider.dividerSize(position, parent);
} else if (mDrawableProvider != null) {
Drawable drawable = mDrawableProvider.drawableProvider(position, parent);
return drawable.getIntrinsicWidth();
}
throw new RuntimeException("failed to get size");
}
/**
* Interface for controlling divider margin
*/
public interface MarginProvider {
/**
* Returns top margin of divider.
*
* @param position Divider position
* @param parent RecyclerView
* @return top margin
*/
int dividerTopMargin(int position, RecyclerView parent);
/**
* Returns bottom margin of divider.
*
* @param position Divider position
* @param parent RecyclerView
* @return bottom margin
*/
int dividerBottomMargin(int position, RecyclerView parent);
}
public static class Builder extends FlexibleDividerDecoration.Builder<Builder> {
private MarginProvider mMarginProvider = new MarginProvider() {
@Override
public int dividerTopMargin(int position, RecyclerView parent) {
return 0;
}
@Override
public int dividerBottomMargin(int position, RecyclerView parent) {
return 0;
}
};
public Builder(Context context) {
super(context);
}
public Builder margin(final int topMargin, final int bottomMargin) {
return marginProvider(new MarginProvider() {
@Override
public int dividerTopMargin(int position, RecyclerView parent) {
return topMargin;
}
@Override
public int dividerBottomMargin(int position, RecyclerView parent) {
return bottomMargin;
}
});
}
public Builder margin(int verticalMargin) {
return margin(verticalMargin, verticalMargin);
}
public Builder marginResId(@DimenRes int topMarginId, @DimenRes int bottomMarginId) {
return margin(mResources.getDimensionPixelSize(topMarginId),
mResources.getDimensionPixelSize(bottomMarginId));
}
public Builder marginResId(@DimenRes int verticalMarginId) {
return marginResId(verticalMarginId, verticalMarginId);
}
public Builder marginProvider(MarginProvider provider) {
mMarginProvider = provider;
return this;
}
public VerticalDividerItemDecoration build() {
checkBuilderParams();
return new VerticalDividerItemDecoration(this);
}
}
} | [
"ytjojo@163.com"
] | ytjojo@163.com |
e0f6ff2e6115589278326ce02ff63fc5417b4484 | 13f8de23ea9ad4ee9e91d215c62eaf5ffeb09239 | /src/main/java/com/demo/alg/c27多线程算法/矩阵/TestDemo.java | 5f8fcb7880c936276e2eb8338a97a56e76d33064 | [] | no_license | yhb2010/alg_demo | b0b50d17c0321fd935dbdef90c6964661ebc97ec | 0c0aa27939a4f4f57c5f139b7d0e4a2794688206 | refs/heads/master | 2020-04-09T22:08:19.853052 | 2018-12-08T07:08:31 | 2018-12-08T07:08:31 | 160,620,930 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,266 | java | package com.demo.alg.c27多线程算法.矩阵;
import java.util.concurrent.CountDownLatch;
public class TestDemo {
static int[][] a = new int[][]{{1, 2, 3, 4}, {5, 6, 7, 8}, {9, 10, 11, 12}, {13, 14, 15, 16}};
static int[][] b = new int[][]{{1, 3, 5, 7}, {2, 4, 6, 8}, {11, 13, 15, 17}, {12, 14, 16, 18}};
static int[][] result = new int[a.length][b[0].length]; // 存放矩阵相乘结果
public static void main(String args[]) {
CountDownLatch cdl = new CountDownLatch(a.length);
OperateMatrix om = new OperateMatrix(a, b, result); // 实例化OperateMatrix对象
// 根据第一个矩阵的行数,启动对应数量的线程
for (int i = 0; i < a.length; i++) {
new ThreadOperate(om, i, "计算第一个矩阵的第" + (i) + "行*第二个矩阵的所有列", cdl).start();
}
try {
cdl.await();
} catch (InterruptedException e) {
e.printStackTrace();
}
display(om.getResult()); // 打印结果
}
public static void display(int[][] c) {
for (int i = 0; i < c.length; i++) {
for (int j = 0; j < c[i].length; j++) {
System.out.print(c[i][j] + " ");
}
System.out.println();
}
}
}
| [
"youtong82@163.com"
] | youtong82@163.com |
052d7e424f25e699dceee14578aab57256c87f64 | 5b06ed7fd0bfda05c572722af3c7ed36cdbc32c5 | /ChatEE2/src/JsonMessages.java | 071b32180af97c64232751ddc24c8401ebf85cdd | [] | no_license | KanivetsAlexey/chatEE | 2be72ac226ab97afb833a186f347d7775f32ba0c | d90913b11580770633fa6808adb6890bfc500400 | refs/heads/master | 2021-01-17T08:25:22.164491 | 2017-03-04T17:01:41 | 2017-03-04T17:01:41 | 83,909,359 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 779 | java | import java.util.ArrayList;
import java.util.List;
public class JsonMessages {
private final List<Message> list;
public JsonMessages(List<Message> sourceList, int fromIndex, String to, String room) {
this.list = new ArrayList<>();
Message result = null;
for(int i = fromIndex; i < sourceList.size(); i++){
result = sourceList.get(i);
if(result != null){
if(result.getTo().equals(Constants.TO_ALL) || (result.getTo().equals(to))){
if(result.getRoom().equals(Constants.MAIN_ROOM)||result.getRoom().equals(room)){
list.add(result);
}
}else{
list.add(null);
}
}
}
}
}
| [
"alexk_v@meta.ua"
] | alexk_v@meta.ua |
451bd44cc39a3936d3cf3e58d7cd14be3596806d | a7ecbb1e5f83a1e8dd9bfca1e7c64f872a8b40ac | /app/src/main/java/com/example/altunmursalov/news/MainActivity.java | 525250e31f4cab297ef48e7f5e9ca0fbef065f3f | [] | no_license | AltunMursalov/News | 363c85cdc63e87713d38e8dd3f33422be29766e5 | b3243d2ba9bd225d8c2e4250f40c74c4155549f5 | refs/heads/master | 2020-04-12T03:19:50.264885 | 2018-12-18T09:32:35 | 2018-12-18T09:32:35 | 162,263,770 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 3,874 | java | package com.example.altunmursalov.news;
import android.annotation.SuppressLint;
import android.support.v4.app.Fragment;
import android.content.Intent;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.design.widget.TabLayout;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.view.ViewPager;
import android.view.View;
import android.support.design.widget.NavigationView;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
public class MainActivity extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
setTitle("Explore");
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
TabLayout tabLayout = (TabLayout)findViewById(R.id.tabs);
ViewPager pager = (ViewPager)findViewById(R.id.explore_pager);
MyTabPagerAdapter tabPagerAdapter = new MyTabPagerAdapter(getSupportFragmentManager());
pager.setAdapter(tabPagerAdapter);
tabLayout.setupWithViewPager(pager);
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
drawer.addDrawerListener(toggle);
toggle.syncState();
NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
}
@Override
public void onBackPressed() {
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START);
} else {
super.onBackPressed();
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.search) {
return true;
}
return super.onOptionsItemSelected(item);
}
@SuppressLint("ResourceType")
private void displaySelectedScreen(int id) {
Fragment fragment = null;
switch (id) {
case R.id.technology:
fragment = new Technology();
break;
}
if(fragment != null) {
FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
ft.replace(R.layout.content_main, fragment);
ft.commit();
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
}
@SuppressWarnings("StatementWithEmptyBody")
@Override
public boolean onNavigationItemSelected(MenuItem item) {
// Handle navigation view item clicks here.
int id = item.getItemId();
return true;
}
}
| [
"Murs_zn54@ITSTEP.LOCAL"
] | Murs_zn54@ITSTEP.LOCAL |
8f016e661b20ef09a695de9f2c608223e0cf9cdf | c5a67e2aeabbde81c93a329ae2e9c7ccc3631246 | /src/main/java/com/vnw/data/jooq/tables/pojos/TbltrackEmployerSignin.java | 5e06c70ac070f27904a20b1829496016ab0ea1b3 | [] | no_license | phuonghuynh/dtools | 319d773d01c32093fd17d128948ef89c81f3f4bf | 883d15ef19da259396a7bc16ac9df590e8add015 | refs/heads/master | 2016-09-14T03:46:53.463230 | 2016-05-25T04:04:32 | 2016-05-25T04:04:32 | 59,534,869 | 1 | 0 | null | null | null | null | UTF-8 | Java | false | false | 2,229 | java | /**
* This class is generated by jOOQ
*/
package com.vnw.data.jooq.tables.pojos;
import java.io.Serializable;
import java.sql.Timestamp;
import javax.annotation.Generated;
/**
* This class is generated by jOOQ.
*/
@Generated(
value = {
"http://www.jooq.org",
"jOOQ version:3.8.0"
},
comments = "This class is generated by jOOQ"
)
@SuppressWarnings({ "all", "unchecked", "rawtypes" })
public class TbltrackEmployerSignin implements Serializable {
private static final long serialVersionUID = 1218469016;
private Integer trackid;
private String ipaddress;
private Integer userid;
private Timestamp createdate;
public TbltrackEmployerSignin() {}
public TbltrackEmployerSignin(TbltrackEmployerSignin value) {
this.trackid = value.trackid;
this.ipaddress = value.ipaddress;
this.userid = value.userid;
this.createdate = value.createdate;
}
public TbltrackEmployerSignin(
Integer trackid,
String ipaddress,
Integer userid,
Timestamp createdate
) {
this.trackid = trackid;
this.ipaddress = ipaddress;
this.userid = userid;
this.createdate = createdate;
}
public Integer getTrackid() {
return this.trackid;
}
public void setTrackid(Integer trackid) {
this.trackid = trackid;
}
public String getIpaddress() {
return this.ipaddress;
}
public void setIpaddress(String ipaddress) {
this.ipaddress = ipaddress;
}
public Integer getUserid() {
return this.userid;
}
public void setUserid(Integer userid) {
this.userid = userid;
}
public Timestamp getCreatedate() {
return this.createdate;
}
public void setCreatedate(Timestamp createdate) {
this.createdate = createdate;
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder("TbltrackEmployerSignin (");
sb.append(trackid);
sb.append(", ").append(ipaddress);
sb.append(", ").append(userid);
sb.append(", ").append(createdate);
sb.append(")");
return sb.toString();
}
}
| [
"phuonghqh@gmail.com"
] | phuonghqh@gmail.com |
e9a6293adf3c3fb0c575bd10d3b6c95e8db6058b | 0be82b9a18db00f0e0b0ac28b9fe3caaa2e276a6 | /open-metadata-implementation/repository-services/repository-services-implementation/src/main/java/org/odpi/openmetadata/repositoryservices/enterprise/repositoryconnector/EnterpriseOMRSMetadataCollection.java | d4afe4cce6a963e53e8baf46808a0b2eeeb58453 | [
"Apache-2.0"
] | permissive | constantinnastase/egeria | 6d2882e08745d07b432477be93d43b4ce2a524b7 | 80f0a3cc172e063b61401a23268f5d1e2ccd8095 | refs/heads/master | 2020-03-22T09:47:26.442127 | 2018-07-18T12:58:11 | 2018-07-18T12:58:11 | 139,860,496 | 0 | 0 | Apache-2.0 | 2018-07-05T14:33:29 | 2018-07-05T14:23:22 | Java | UTF-8 | Java | false | false | 350,084 | java | /* SPDX-License-Identifier: Apache-2.0 */
package org.odpi.openmetadata.repositoryservices.enterprise.repositoryconnector;
import org.odpi.openmetadata.repositoryservices.ffdc.OMRSErrorCode;
import org.odpi.openmetadata.repositoryservices.connectors.stores.metadatacollectionstore.OMRSMetadataCollection;
import org.odpi.openmetadata.repositoryservices.connectors.stores.metadatacollectionstore.properties.MatchCriteria;
import org.odpi.openmetadata.repositoryservices.connectors.stores.metadatacollectionstore.properties.SequencingOrder;
import org.odpi.openmetadata.repositoryservices.connectors.stores.metadatacollectionstore.properties.instances.*;
import org.odpi.openmetadata.repositoryservices.connectors.stores.metadatacollectionstore.properties.typedefs.*;
import org.odpi.openmetadata.repositoryservices.connectors.stores.metadatacollectionstore.repositoryconnector.OMRSRepositoryConnector;
import org.odpi.openmetadata.repositoryservices.connectors.stores.metadatacollectionstore.repositoryconnector.OMRSRepositoryHelper;
import org.odpi.openmetadata.repositoryservices.connectors.stores.metadatacollectionstore.repositoryconnector.OMRSRepositoryValidator;
import org.odpi.openmetadata.repositoryservices.ffdc.exception.*;
import java.util.HashMap;
import java.util.Map;
import java.util.List;
import java.util.ArrayList;
import java.util.Date;
/**
* EnterpriseOMRSMetadataCollection executes the calls to the open metadata repositories registered
* with the OMRSEnterpriseConnectorManager. The effect is a federated view over these open metadata
* repositories.
* <p>
* EnterpriseOMRSMetadataCollection is part of an EnterpriseOMRSRepositoryConnector. The EnterpriseOMRSRepositoryConnector
* holds the list of OMRS Connectors, one for each of the metadata repositories. This list may change
* over time as metadata repositories register and deregister with the connected cohorts.
* The EnterpriseOMRSRepositoryConnector is responsible for keeping the list of connectors up-to-date through
* contact with the OMRSEnterpriseConnectorManager.
* </p>
* <p>
* When a request is made to the EnterpriseOMRSMetadataCollection, it calls the EnterpriseOMRSRepositoryConnector
* to request the appropriate list of metadata collection for the request. Then the EnterpriseOMRSConnector
* calls the appropriate remote connectors.
* </p>
* <p>
* The first OMRS Connector in the list is the OMRS Repository Connector for the "local" repository.
* The local repository is favoured when new metadata is to be created, unless the type of metadata
* is not supported by the local repository. In which case, the EnterpriseOMRSMetadataCollection searches its
* list looking for the first metadata repository that supports the metadata type and stores it there.
* </p>
* <p>
* Updates and deletes are routed to the owning (home) repository. Searches are made to each repository in turn
* and the duplicates are removed. Queries are directed to the local repository and then the remote repositories
* until all of the requested metadata is assembled.
* </p>
*/
public class EnterpriseOMRSMetadataCollection extends OMRSMetadataCollection
{
/*
* Private variables for a metadata collection instance
*/
private EnterpriseOMRSRepositoryConnector enterpriseParentConnector;
/**
* Constructor ensures the metadata collection is linked to its connector and knows its metadata collection Id.
*
* @param enterpriseParentConnector connector that this metadata collection supports. The connector has the information
* to call the metadata repository.
* @param repositoryName name of the repository used for logging.
* @param repositoryHelper class used to build type definitions and instances.
* @param repositoryValidator class used to validate type definitions and instances.
* @param metadataCollectionId unique Identifier of the metadata collection Id.
*/
public EnterpriseOMRSMetadataCollection(EnterpriseOMRSRepositoryConnector enterpriseParentConnector,
String repositoryName,
OMRSRepositoryHelper repositoryHelper,
OMRSRepositoryValidator repositoryValidator,
String metadataCollectionId)
{
/*
* The metadata collection Id is the unique identifier for the metadata collection. It is managed by the super class.
*/
super(enterpriseParentConnector, repositoryName, metadataCollectionId, repositoryHelper, repositoryValidator);
/*
* Save enterpriseParentConnector since this has the connection information and
* access to the metadata about the open metadata repository cohort.
*/
this.enterpriseParentConnector = enterpriseParentConnector;
}
/* ======================================================================
* Group 1: Confirm the identity of the metadata repository being called.
*/
/**
* Returns the identifier of the metadata repository. This is the identifier used to register the
* metadata repository with the metadata repository cohort. It is also the identifier used to
* identify the home repository of a metadata instance.
*
* @return String metadata collection id.
* @throws RepositoryErrorException there is a problem communicating with the metadata repository.
*/
public String getMetadataCollectionId() throws RepositoryErrorException
{
final String methodName = "getMetadataCollectionId";
/*
* Validate parameters
*/
this.validateRepositoryConnector(methodName);
parentConnector.validateRepositoryIsActive(methodName);
/*
* Perform operation
*/
return super.metadataCollectionId;
}
/* ==============================
* Group 2: Working with typedefs
*/
/**
* Returns the list of different types of metadata organized into two groups. The first are the
* attribute type definitions (AttributeTypeDefs). These provide types for properties in full
* type definitions. Full type definitions (TypeDefs) describe types for entities, relationships
* and classifications.
*
* @param userId unique identifier for requesting user.
* @return TypeDefs List of different categories of TypeDefs.
* @throws RepositoryErrorException there is a problem communicating with the metadata repository.
* @throws UserNotAuthorizedException the userId is not permitted to perform this operation.
*/
public TypeDefGallery getAllTypes(String userId) throws RepositoryErrorException,
UserNotAuthorizedException
{
final String methodName = "getAllTypes";
/*
* Validate parameters
*/
this.validateRepositoryConnector(methodName);
parentConnector.validateRepositoryIsActive(methodName);
repositoryValidator.validateUserId(repositoryName, userId, methodName);
/*
* The list of cohort connectors are retrieved for each request to ensure that any changes in
* the shape of the cohort are reflected immediately.
*/
List<OMRSRepositoryConnector> cohortConnectors = enterpriseParentConnector.getCohortConnectors(methodName);
/*
* Ready to process the request. Search results need to come from all members of the cohort.
* They need to be combined and then duplicates removed to create the final list of results.
* Some repositories may produce exceptions. These exceptions are saved and will be returned if
* there are no results from any repository.
*/
Map<String, TypeDef> combinedTypeDefResults = new HashMap<>();
Map<String, AttributeTypeDef> combinedAttributeTypeDefResults = new HashMap<>();
UserNotAuthorizedException userNotAuthorizedException = null;
RepositoryErrorException repositoryErrorException = null;
Throwable anotherException = null;
/*
* Loop through the metadata collections extracting the typedefs from each repository.
*/
for (OMRSRepositoryConnector cohortConnector : cohortConnectors)
{
if (cohortConnector != null)
{
OMRSMetadataCollection metadataCollection = cohortConnector.getMetadataCollection();
validateMetadataCollection(metadataCollection, methodName);
try
{
/*
* Issue the request
*/
TypeDefGallery results = metadataCollection.getAllTypes(userId);
/*
* Step through the list of returned TypeDefs and consolidate.
*/
if (results != null)
{
combinedAttributeTypeDefResults = this.addUniqueAttributeTypeDefs(combinedAttributeTypeDefResults,
results.getAttributeTypeDefs(),
cohortConnector.getServerName(),
cohortConnector.getMetadataCollectionId(),
methodName);
combinedTypeDefResults = this.addUniqueTypeDefs(combinedTypeDefResults,
results.getTypeDefs(),
cohortConnector.getServerName(),
cohortConnector.getMetadataCollectionId(),
methodName);
}
}
catch (RepositoryErrorException error)
{
repositoryErrorException = error;
}
catch (UserNotAuthorizedException error)
{
userNotAuthorizedException = error;
}
catch (Throwable error)
{
anotherException = error;
}
}
}
return validatedTypeDefGalleryResults(repositoryName,
combinedTypeDefResults,
combinedAttributeTypeDefResults,
userNotAuthorizedException,
repositoryErrorException,
anotherException,
methodName);
}
/**
* Returns a list of type definitions that have the specified name. Type names should be unique. This
* method allows wildcard character to be included in the name. These are * (asterisk) for an
* arbitrary string of characters and ampersand for an arbitrary character.
*
* @param userId unique identifier for requesting user.
* @param name name of the TypeDefs to return (including wildcard characters).
* @return TypeDefs list.
* @throws InvalidParameterException the name of the TypeDef is null.
* @throws RepositoryErrorException there is a problem communicating with the metadata repository.
* @throws UserNotAuthorizedException the userId is not permitted to perform this operation.
*/
public TypeDefGallery findTypesByName(String userId,
String name) throws InvalidParameterException,
RepositoryErrorException,
UserNotAuthorizedException
{
final String methodName = "findTypesByName";
final String nameParameterName = "name";
/*
* Validate parameters
*/
this.validateRepositoryConnector(methodName);
parentConnector.validateRepositoryIsActive(methodName);
repositoryValidator.validateUserId(repositoryName, userId, methodName);
repositoryValidator.validateTypeName(repositoryName, nameParameterName, name, methodName);
/*
* The list of cohort connectors are retrieved for each request to ensure that any changes in
* the shape of the cohort are reflected immediately.
*/
List<OMRSRepositoryConnector> cohortConnectors = enterpriseParentConnector.getCohortConnectors(methodName);
/*
* Ready to process the request. Search results need to come from all members of the cohort.
* They need to be combined and then duplicates removed to create the final list of results.
* Some repositories may produce exceptions. These exceptions are saved and will be returned if
* there are no results from any repository.
*/
Map<String, TypeDef> combinedTypeDefResults = new HashMap<>();
Map<String, AttributeTypeDef> combinedAttributeTypeDefResults = new HashMap<>();
UserNotAuthorizedException userNotAuthorizedException = null;
RepositoryErrorException repositoryErrorException = null;
Throwable anotherException = null;
/*
* Loop through the metadata collections extracting the typedefs from each repository.
*/
for (OMRSRepositoryConnector cohortConnector : cohortConnectors)
{
if (cohortConnector != null)
{
OMRSMetadataCollection metadataCollection = cohortConnector.getMetadataCollection();
validateMetadataCollection(metadataCollection, methodName);
try
{
/*
* Issue the request
*/
TypeDefGallery results = metadataCollection.findTypesByName(userId, name);
/*
* Step through the list of returned TypeDefs and consolidate.
*/
if (results != null)
{
combinedAttributeTypeDefResults = this.addUniqueAttributeTypeDefs(combinedAttributeTypeDefResults,
results.getAttributeTypeDefs(),
cohortConnector.getServerName(),
cohortConnector.getMetadataCollectionId(),
methodName);
combinedTypeDefResults = this.addUniqueTypeDefs(combinedTypeDefResults,
results.getTypeDefs(),
cohortConnector.getServerName(),
cohortConnector.getMetadataCollectionId(),
methodName);
}
}
catch (RepositoryErrorException error)
{
repositoryErrorException = error;
}
catch (UserNotAuthorizedException error)
{
userNotAuthorizedException = error;
}
catch (Throwable error)
{
anotherException = error;
}
}
}
return validatedTypeDefGalleryResults(repositoryName,
combinedTypeDefResults,
combinedAttributeTypeDefResults,
userNotAuthorizedException,
repositoryErrorException,
anotherException,
methodName);
}
/**
* Returns all of the TypeDefs for a specific category.
*
* @param userId unique identifier for requesting user.
* @param category enum value for the category of TypeDef to return.
* @return TypeDefs list.
* @throws InvalidParameterException the TypeDefCategory is null.
* @throws RepositoryErrorException there is a problem communicating with the metadata repository.
* @throws UserNotAuthorizedException the userId is not permitted to perform this operation.
*/
public List<TypeDef> findTypeDefsByCategory(String userId,
TypeDefCategory category) throws InvalidParameterException,
RepositoryErrorException,
UserNotAuthorizedException
{
final String methodName = "findTypeDefsByCategory";
final String categoryParameterName = "category";
/*
* Validate parameters
*/
this.validateRepositoryConnector(methodName);
parentConnector.validateRepositoryIsActive(methodName);
repositoryValidator.validateUserId(repositoryName, userId, methodName);
repositoryValidator.validateTypeDefCategory(repositoryName, categoryParameterName, category, methodName);
/*
* The list of cohort connectors are retrieved for each request to ensure that any changes in
* the shape of the cohort are reflected immediately.
*/
List<OMRSRepositoryConnector> cohortConnectors = enterpriseParentConnector.getCohortConnectors(methodName);
/*
* Ready to process the request. Search results need to come from all members of the cohort.
* They need to be combined and then duplicates removed to create the final list of results.
* Some repositories may produce exceptions. These exceptions are saved and will be returned if
* there are no results from any repository.
*/
Map<String, TypeDef> combinedResults = new HashMap<>();
UserNotAuthorizedException userNotAuthorizedException = null;
RepositoryErrorException repositoryErrorException = null;
Throwable anotherException = null;
/*
* Loop through the metadata collections extracting the typedefs from each repository.
*/
for (OMRSRepositoryConnector cohortConnector : cohortConnectors)
{
if (cohortConnector != null)
{
OMRSMetadataCollection metadataCollection = cohortConnector.getMetadataCollection();
validateMetadataCollection(metadataCollection, methodName);
try
{
/*
* Issue the request
*/
List<TypeDef> results = metadataCollection.findTypeDefsByCategory(userId, category);
/*
* Step through the list of returned TypeDefs and remove duplicates.
*/
combinedResults = this.addUniqueTypeDefs(combinedResults,
results,
cohortConnector.getServerName(),
cohortConnector.getMetadataCollectionId(),
methodName);
}
catch (RepositoryErrorException error)
{
repositoryErrorException = error;
}
catch (UserNotAuthorizedException error)
{
userNotAuthorizedException = error;
}
catch (Throwable error)
{
anotherException = error;
}
}
}
return validatedTypeDefListResults(repositoryName,
combinedResults,
userNotAuthorizedException,
repositoryErrorException,
anotherException,
methodName);
}
/**
* Returns all of the AttributeTypeDefs for a specific category.
*
* @param userId unique identifier for requesting user.
* @param category enum value for the category of an AttributeTypeDef to return.
* @return TypeDefs list.
* @throws InvalidParameterException the TypeDefCategory is null.
* @throws RepositoryErrorException there is a problem communicating with the metadata repository.
* @throws UserNotAuthorizedException the userId is not permitted to perform this operation.
*/
public List<AttributeTypeDef> findAttributeTypeDefsByCategory(String userId,
AttributeTypeDefCategory category) throws InvalidParameterException,
RepositoryErrorException,
UserNotAuthorizedException
{
final String methodName = "findAttributeTypeDefsByCategory";
final String categoryParameterName = "category";
/*
* Validate parameters
*/
this.validateRepositoryConnector(methodName);
parentConnector.validateRepositoryIsActive(methodName);
repositoryValidator.validateUserId(repositoryName, userId, methodName);
repositoryValidator.validateAttributeTypeDefCategory(repositoryName, categoryParameterName, category, methodName);
/*
* The list of cohort connectors are retrieved for each request to ensure that any changes in
* the shape of the cohort are reflected immediately.
*/
List<OMRSRepositoryConnector> cohortConnectors = enterpriseParentConnector.getCohortConnectors(methodName);
/*
* Ready to process the request. Search results need to come from all members of the cohort.
* They need to be combined and then duplicates removed to create the final list of results.
* Some repositories may produce exceptions. These exceptions are saved and will be returned if
* there are no results from any repository.
*/
Map<String, AttributeTypeDef> combinedResults = new HashMap<>();
UserNotAuthorizedException userNotAuthorizedException = null;
RepositoryErrorException repositoryErrorException = null;
Throwable anotherException = null;
/*
* Loop through the metadata collections extracting the typedefs from each repository.
*/
for (OMRSRepositoryConnector cohortConnector : cohortConnectors)
{
if (cohortConnector != null)
{
OMRSMetadataCollection metadataCollection = cohortConnector.getMetadataCollection();
validateMetadataCollection(metadataCollection, methodName);
try
{
/*
* Issue the request
*/
List<AttributeTypeDef> results = metadataCollection.findAttributeTypeDefsByCategory(userId, category);
/*
* Step through the list of returned TypeDefs and remove duplicates.
*/
combinedResults = this.addUniqueAttributeTypeDefs(combinedResults,
results,
cohortConnector.getServerName(),
cohortConnector.getMetadataCollectionId(),
methodName);
}
catch (RepositoryErrorException error)
{
repositoryErrorException = error;
}
catch (UserNotAuthorizedException error)
{
userNotAuthorizedException = error;
}
catch (Throwable error)
{
anotherException = error;
}
}
}
return validatedAttributeTypeDefListResults(repositoryName,
combinedResults,
userNotAuthorizedException,
repositoryErrorException,
anotherException,
methodName);
}
/**
* Return the TypeDefs that have the properties matching the supplied match criteria.
*
* @param userId unique identifier for requesting user.
* @param matchCriteria TypeDefProperties a list of property names.
* @return TypeDefs list.
* @throws InvalidParameterException the matchCriteria is null.
* @throws RepositoryErrorException there is a problem communicating with the metadata repository.
* @throws UserNotAuthorizedException the userId is not permitted to perform this operation.
*/
public List<TypeDef> findTypeDefsByProperty(String userId,
TypeDefProperties matchCriteria) throws InvalidParameterException,
RepositoryErrorException,
UserNotAuthorizedException
{
final String methodName = "findTypeDefsByProperty";
final String matchCriteriaParameterName = "matchCriteria";
/*
* Validate parameters
*/
this.validateRepositoryConnector(methodName);
parentConnector.validateRepositoryIsActive(methodName);
repositoryValidator.validateUserId(repositoryName, userId, methodName);
repositoryValidator.validateMatchCriteria(repositoryName, matchCriteriaParameterName, matchCriteria, methodName);
/*
* The list of cohort connectors are retrieved for each request to ensure that any changes in
* the shape of the cohort are reflected immediately.
*/
List<OMRSRepositoryConnector> cohortConnectors = enterpriseParentConnector.getCohortConnectors(methodName);
/*
* Ready to process the request. Search results need to come from all members of the cohort.
* They need to be combined and then duplicates removed to create the final list of results.
* Some repositories may produce exceptions. These exceptions are saved and will be returned if
* there are no results from any repository.
*/
Map<String, TypeDef> combinedResults = new HashMap<>();
UserNotAuthorizedException userNotAuthorizedException = null;
RepositoryErrorException repositoryErrorException = null;
Throwable anotherException = null;
/*
* Loop through the metadata collections extracting the typedefs from each repository.
*/
for (OMRSRepositoryConnector cohortConnector : cohortConnectors)
{
if (cohortConnector != null)
{
OMRSMetadataCollection metadataCollection = cohortConnector.getMetadataCollection();
validateMetadataCollection(metadataCollection, methodName);
try
{
/*
* Issue the request
*/
List<TypeDef> results = metadataCollection.findTypeDefsByProperty(userId, matchCriteria);
/*
* Step through the list of returned TypeDefs and remove duplicates.
*/
combinedResults = this.addUniqueTypeDefs(combinedResults,
results,
cohortConnector.getServerName(),
cohortConnector.getMetadataCollectionId(),
methodName);
}
catch (RepositoryErrorException error)
{
repositoryErrorException = error;
}
catch (UserNotAuthorizedException error)
{
userNotAuthorizedException = error;
}
catch (Throwable error)
{
anotherException = error;
}
}
}
return validatedTypeDefListResults(repositoryName,
combinedResults,
userNotAuthorizedException,
repositoryErrorException,
anotherException,
methodName);
}
/**
* Return the types that are linked to the elements from the specified standard.
*
* @param userId unique identifier for requesting user.
* @param standard name of the standard null means any.
* @param organization name of the organization null means any.
* @param identifier identifier of the element in the standard null means any.
* @return TypeDefs list each entry in the list contains a typedef. This is is a structure
* describing the TypeDef's category and properties.
* @throws InvalidParameterException all attributes of the external Id are null.
* @throws RepositoryErrorException there is a problem communicating with the metadata repository.
* @throws UserNotAuthorizedException the userId is not permitted to perform this operation.
*/
public List<TypeDef> findTypesByExternalID(String userId,
String standard,
String organization,
String identifier) throws InvalidParameterException,
RepositoryErrorException,
UserNotAuthorizedException
{
final String methodName = "findTypesByExternalID";
/*
* Validate parameters
*/
this.validateRepositoryConnector(methodName);
parentConnector.validateRepositoryIsActive(methodName);
repositoryValidator.validateUserId(repositoryName, userId, methodName);
repositoryValidator.validateExternalId(repositoryName, standard, organization, identifier, methodName);
/*
* The list of cohort connectors are retrieved for each request to ensure that any changes in
* the shape of the cohort are reflected immediately.
*/
List<OMRSRepositoryConnector> cohortConnectors = enterpriseParentConnector.getCohortConnectors(methodName);
/*
* Ready to process the request. Search results need to come from all members of the cohort.
* They need to be combined and then duplicates removed to create the final list of results.
* Some repositories may produce exceptions. These exceptions are saved and one selected to
* be returned if there are no results from any repository.
*/
Map<String, TypeDef> combinedResults = new HashMap<>();
UserNotAuthorizedException userNotAuthorizedException = null;
RepositoryErrorException repositoryErrorException = null;
Throwable anotherException = null;
/*
* Loop through the metadata collections extracting the typedefs from each repository.
*/
for (OMRSRepositoryConnector cohortConnector : cohortConnectors)
{
if (cohortConnector != null)
{
OMRSMetadataCollection metadataCollection = cohortConnector.getMetadataCollection();
validateMetadataCollection(metadataCollection, methodName);
try
{
/*
* Issue the request
*/
List<TypeDef> results = metadataCollection.findTypesByExternalID(userId, standard, organization, identifier);
/*
* Step through the list of returned TypeDefs and remove duplicates.
*/
combinedResults = this.addUniqueTypeDefs(combinedResults,
results,
cohortConnector.getServerName(),
cohortConnector.getMetadataCollectionId(),
methodName);
}
catch (RepositoryErrorException error)
{
repositoryErrorException = error;
}
catch (UserNotAuthorizedException error)
{
userNotAuthorizedException = error;
}
catch (Throwable error)
{
anotherException = error;
}
}
}
return validatedTypeDefListResults(repositoryName,
combinedResults,
userNotAuthorizedException,
repositoryErrorException,
anotherException,
methodName);
}
/**
* Return the TypeDefs that match the search criteria.
*
* @param userId unique identifier for requesting user.
* @param searchCriteria String search criteria.
* @return TypeDefs list each entry in the list contains a typedef. This is is a structure
* describing the TypeDef's category and properties.
* @throws InvalidParameterException the searchCriteria is null.
* @throws RepositoryErrorException there is a problem communicating with the metadata repository.
* @throws UserNotAuthorizedException the userId is not permitted to perform this operation.
*/
public List<TypeDef> searchForTypeDefs(String userId,
String searchCriteria) throws InvalidParameterException,
RepositoryErrorException,
UserNotAuthorizedException
{
final String methodName = "searchForTypeDefs";
final String searchCriteriaParameterName = "searchCriteria";
/*
* Validate parameters
*/
this.validateRepositoryConnector(methodName);
parentConnector.validateRepositoryIsActive(methodName);
repositoryValidator.validateUserId(repositoryName, userId, methodName);
repositoryValidator.validateSearchCriteria(repositoryName, searchCriteriaParameterName, searchCriteria, methodName);
/*
* The list of cohort connectors are retrieved for each request to ensure that any changes in
* the shape of the cohort are reflected immediately.
*/
List<OMRSRepositoryConnector> cohortConnectors = enterpriseParentConnector.getCohortConnectors(methodName);
/*
* Ready to process the request. Search results need to come from all members of the cohort.
* They need to be combined and then duplicates removed to create the final list of results.
* Some repositories may produce exceptions. These exceptions are saved and will be returned if
* there are no results from any repository.
*/
Map<String, TypeDef> combinedResults = new HashMap<>();
UserNotAuthorizedException userNotAuthorizedException = null;
RepositoryErrorException repositoryErrorException = null;
Throwable anotherException = null;
/*
* Loop through the metadata collections extracting the typedefs from each repository.
*/
for (OMRSRepositoryConnector cohortConnector : cohortConnectors)
{
if (cohortConnector != null)
{
OMRSMetadataCollection metadataCollection = cohortConnector.getMetadataCollection();
validateMetadataCollection(metadataCollection, methodName);
try
{
/*
* Issue the request
*/
List<TypeDef> results = metadataCollection.searchForTypeDefs(userId, searchCriteria);
/*
* Step through the list of returned TypeDefs and remove duplicates.
*/
combinedResults = this.addUniqueTypeDefs(combinedResults,
results,
cohortConnector.getServerName(),
cohortConnector.getMetadataCollectionId(),
methodName);
}
catch (RepositoryErrorException error)
{
repositoryErrorException = error;
}
catch (UserNotAuthorizedException error)
{
userNotAuthorizedException = error;
}
catch (Throwable error)
{
anotherException = error;
}
}
}
return validatedTypeDefListResults(repositoryName,
combinedResults,
userNotAuthorizedException,
repositoryErrorException,
anotherException,
methodName);
}
/**
* Return the TypeDef identified by the GUID.
*
* @param userId unique identifier for requesting user.
* @param guid String unique Id of the TypeDef
* @return TypeDef structure describing its category and properties.
* @throws InvalidParameterException the guid is null.
* @throws RepositoryErrorException there is a problem communicating with the metadata repository where
* the metadata collection is stored.
* @throws TypeDefNotKnownException The requested TypeDef is not known in the metadata collection.
* @throws UserNotAuthorizedException the userId is not permitted to perform this operation.
*/
public TypeDef getTypeDefByGUID(String userId,
String guid) throws InvalidParameterException,
RepositoryErrorException,
TypeDefNotKnownException,
UserNotAuthorizedException
{
final String methodName = "getTypeDefByGUID";
final String guidParameterName = "guid";
/*
* Validate parameters
*/
this.validateRepositoryConnector(methodName);
parentConnector.validateRepositoryIsActive(methodName);
repositoryValidator.validateUserId(repositoryName, userId, methodName);
repositoryValidator.validateGUID(repositoryName, guidParameterName, guid, methodName);
/*
* The list of cohort connectors are retrieved for each request to ensure that any changes in
* the shape of the cohort are reflected immediately.
*/
List<OMRSRepositoryConnector> cohortConnectors = enterpriseParentConnector.getCohortConnectors(methodName);
/*
* Ready to process the request. Search results need to come from all members of the cohort.
* They need to be combined and then duplicates removed to create the final list of results.
* Some repositories may produce exceptions. These exceptions are saved and one selected to
* be returned if there are no results from any repository.
*/
TypeDefNotKnownException typeDefNotKnownException = null;
UserNotAuthorizedException userNotAuthorizedException = null;
RepositoryErrorException repositoryErrorException = null;
Throwable anotherException = null;
/*
* Loop through the metadata collections extracting the typedefs from each repository.
*/
for (OMRSRepositoryConnector cohortConnector : cohortConnectors)
{
if (cohortConnector != null)
{
OMRSMetadataCollection metadataCollection = cohortConnector.getMetadataCollection();
validateMetadataCollection(metadataCollection, methodName);
try
{
/*
* Issue the request and return if it succeeds
*/
return metadataCollection.getTypeDefByGUID(userId, guid);
}
catch (TypeDefNotKnownException error)
{
typeDefNotKnownException = error;
}
catch (RepositoryErrorException error)
{
repositoryErrorException = error;
}
catch (UserNotAuthorizedException error)
{
userNotAuthorizedException = error;
}
catch (Throwable error)
{
anotherException = error;
}
}
}
throwCapturedRepositoryErrorException(repositoryErrorException);
throwCapturedUserNotAuthorizedException(userNotAuthorizedException);
throwCapturedThrowableException(anotherException, methodName);
throwCapturedTypeDefNotKnownException(typeDefNotKnownException);
return null;
}
/**
* Return the AttributeTypeDef identified by the GUID.
*
* @param userId unique identifier for requesting user.
* @param guid String unique id of the TypeDef
* @return TypeDef structure describing its category and properties.
* @throws InvalidParameterException the guid is null.
* @throws RepositoryErrorException there is a problem communicating with the metadata repository where
* the metadata collection is stored.
* @throws TypeDefNotKnownException The requested TypeDef is not known in the metadata collection.
* @throws UserNotAuthorizedException the userId is not permitted to perform this operation.
*/
public AttributeTypeDef getAttributeTypeDefByGUID(String userId,
String guid) throws InvalidParameterException,
RepositoryErrorException,
TypeDefNotKnownException,
UserNotAuthorizedException
{
final String methodName = "getAttributeTypeDefByGUID";
final String guidParameterName = "guid";
/*
* Validate parameters
*/
this.validateRepositoryConnector(methodName);
parentConnector.validateRepositoryIsActive(methodName);
repositoryValidator.validateUserId(repositoryName, userId, methodName);
repositoryValidator.validateGUID(repositoryName, guidParameterName, guid, methodName);
/*
* The list of cohort connectors are retrieved for each request to ensure that any changes in
* the shape of the cohort are reflected immediately.
*/
List<OMRSRepositoryConnector> cohortConnectors = enterpriseParentConnector.getCohortConnectors(methodName);
/*
* Ready to process the request. Search results need to come from all members of the cohort.
* They need to be combined and then duplicates removed to create the final list of results.
* Some repositories may produce exceptions. These exceptions are saved and one selected to
* be returned if there are no results from any repository.
*/
TypeDefNotKnownException typeDefNotKnownException = null;
UserNotAuthorizedException userNotAuthorizedException = null;
RepositoryErrorException repositoryErrorException = null;
Throwable anotherException = null;
/*
* Loop through the metadata collections extracting the typedefs from each repository.
*/
for (OMRSRepositoryConnector cohortConnector : cohortConnectors)
{
if (cohortConnector != null)
{
OMRSMetadataCollection metadataCollection = cohortConnector.getMetadataCollection();
validateMetadataCollection(metadataCollection, methodName);
try
{
/*
* Issue the request and return if it succeeds
*/
return metadataCollection.getAttributeTypeDefByGUID(userId, guid);
}
catch (TypeDefNotKnownException error)
{
typeDefNotKnownException = error;
}
catch (RepositoryErrorException error)
{
repositoryErrorException = error;
}
catch (UserNotAuthorizedException error)
{
userNotAuthorizedException = error;
}
catch (Throwable error)
{
anotherException = error;
}
}
}
throwCapturedRepositoryErrorException(repositoryErrorException);
throwCapturedUserNotAuthorizedException(userNotAuthorizedException);
throwCapturedThrowableException(anotherException, methodName);
if (typeDefNotKnownException != null)
{
throw typeDefNotKnownException;
}
return null;
}
/**
* Return the TypeDef identified by the unique name.
*
* @param userId unique identifier for requesting user.
* @param name String name of the TypeDef.
* @return TypeDef structure describing its category and properties.
* @throws InvalidParameterException the name is null.
* @throws RepositoryErrorException there is a problem communicating with the metadata repository where
* the metadata collection is stored.
* @throws TypeDefNotKnownException the requested TypeDef is not found in the metadata collection.
*/
public TypeDef getTypeDefByName(String userId,
String name) throws InvalidParameterException,
RepositoryErrorException,
TypeDefNotKnownException,
UserNotAuthorizedException
{
final String methodName = "getTypeDefByName";
final String nameParameterName = "name";
/*
* Validate parameters
*/
this.validateRepositoryConnector(methodName);
parentConnector.validateRepositoryIsActive(methodName);
repositoryValidator.validateUserId(repositoryName, userId, methodName);
repositoryValidator.validateTypeName(repositoryName, nameParameterName, name, methodName);
/*
* The list of cohort connectors are retrieved for each request to ensure that any changes in
* the shape of the cohort are reflected immediately.
*/
List<OMRSRepositoryConnector> cohortConnectors = enterpriseParentConnector.getCohortConnectors(methodName);
/*
* Ready to process the request. Search results need to come from all members of the cohort.
* They need to be combined and then duplicates removed to create the final list of results.
* Some repositories may produce exceptions. These exceptions are saved and one selected to
* be returned if there are no results from any repository.
*/
TypeDefNotKnownException typeDefNotKnownException = null;
UserNotAuthorizedException userNotAuthorizedException = null;
RepositoryErrorException repositoryErrorException = null;
Throwable anotherException = null;
/*
* Loop through the metadata collections extracting the typedefs from each repository.
*/
for (OMRSRepositoryConnector cohortConnector : cohortConnectors)
{
if (cohortConnector != null)
{
OMRSMetadataCollection metadataCollection = cohortConnector.getMetadataCollection();
validateMetadataCollection(metadataCollection, methodName);
try
{
/*
* Issue the request and return if it succeeds
*/
return metadataCollection.getTypeDefByName(userId, name);
}
catch (TypeDefNotKnownException error)
{
typeDefNotKnownException = error;
}
catch (RepositoryErrorException error)
{
repositoryErrorException = error;
}
catch (UserNotAuthorizedException error)
{
userNotAuthorizedException = error;
}
catch (Throwable error)
{
anotherException = error;
}
}
}
throwCapturedRepositoryErrorException(repositoryErrorException);
throwCapturedUserNotAuthorizedException(userNotAuthorizedException);
throwCapturedThrowableException(anotherException, methodName);
throwCapturedTypeDefNotKnownException(typeDefNotKnownException);
return null;
}
/**
* Return the AttributeTypeDef identified by the unique name.
*
* @param userId unique identifier for requesting user.
* @param name String name of the TypeDef.
* @return TypeDef structure describing its category and properties.
* @throws InvalidParameterException the name is null.
* @throws RepositoryErrorException there is a problem communicating with the metadata repository where
* the metadata collection is stored.
* @throws TypeDefNotKnownException the requested TypeDef is not found in the metadata collection.
* @throws UserNotAuthorizedException the userId is not permitted to perform this operation.
*/
public AttributeTypeDef getAttributeTypeDefByName(String userId,
String name) throws InvalidParameterException,
RepositoryErrorException,
TypeDefNotKnownException,
UserNotAuthorizedException
{
final String methodName = "getAttributeTypeDefByName";
final String nameParameterName = "name";
/*
* Validate parameters
*/
this.validateRepositoryConnector(methodName);
parentConnector.validateRepositoryIsActive(methodName);
repositoryValidator.validateUserId(repositoryName, userId, methodName);
repositoryValidator.validateTypeName(repositoryName, nameParameterName, name, methodName);
/*
* The list of cohort connectors are retrieved for each request to ensure that any changes in
* the shape of the cohort are reflected immediately.
*/
List<OMRSRepositoryConnector> cohortConnectors = enterpriseParentConnector.getCohortConnectors(methodName);
/*
* Ready to process the request. Search results need to come from all members of the cohort.
* They need to be combined and then duplicates removed to create the final list of results.
* Some repositories may produce exceptions. These exceptions are saved and one selected to
* be returned if there are no results from any repository.
*/
TypeDefNotKnownException typeDefNotKnownException = null;
UserNotAuthorizedException userNotAuthorizedException = null;
RepositoryErrorException repositoryErrorException = null;
Throwable anotherException = null;
/*
* Loop through the metadata collections extracting the typedefs from each repository.
*/
for (OMRSRepositoryConnector cohortConnector : cohortConnectors)
{
if (cohortConnector != null)
{
OMRSMetadataCollection metadataCollection = cohortConnector.getMetadataCollection();
validateMetadataCollection(metadataCollection, methodName);
try
{
/*
* Issue the request and return if it succeeds
*/
return metadataCollection.getAttributeTypeDefByName(userId, name);
}
catch (TypeDefNotKnownException error)
{
typeDefNotKnownException = error;
}
catch (RepositoryErrorException error)
{
repositoryErrorException = error;
}
catch (UserNotAuthorizedException error)
{
userNotAuthorizedException = error;
}
catch (Throwable error)
{
anotherException = error;
}
}
}
throwCapturedRepositoryErrorException(repositoryErrorException);
throwCapturedUserNotAuthorizedException(userNotAuthorizedException);
throwCapturedThrowableException(anotherException, methodName);
throwCapturedTypeDefNotKnownException(typeDefNotKnownException);
return null;
}
/**
* Create a collection of related types.
*
* @param userId unique identifier for requesting user.
* @param newTypes TypeDefGalleryResponse structure describing the new AttributeTypeDefs and TypeDefs.
* @throws FunctionNotSupportedException the repository does not support this call.
*/
public void addTypeDefGallery(String userId,
TypeDefGallery newTypes) throws FunctionNotSupportedException
{
final String methodName = "addTypeDefGallery()";
throwNotEnterpriseFunction(methodName);
}
/**
* Create a definition of a new TypeDef. This new TypeDef is pushed to each repository that will accept it.
* An exception is passed to the caller if the TypeDef is invalid, or if none of the repositories accept it.
*
* @param userId unique identifier for requesting user.
* @param newTypeDef TypeDef structure describing the new TypeDef.
* @throws FunctionNotSupportedException the repository does not support this call.
*/
public void addTypeDef(String userId,
TypeDef newTypeDef) throws FunctionNotSupportedException
{
final String methodName = "addTypeDef()";
throwNotEnterpriseFunction(methodName);
}
/**
* Create a definition of a new AttributeTypeDef.
*
* @param userId unique identifier for requesting user.
* @param newAttributeTypeDef TypeDef structure describing the new TypeDef.
* @throws FunctionNotSupportedException the repository does not support this call.
*/
public void addAttributeTypeDef(String userId,
AttributeTypeDef newAttributeTypeDef) throws FunctionNotSupportedException
{
final String methodName = "addAttributeTypeDef()";
throwNotEnterpriseFunction(methodName);
}
/**
* Verify that a definition of a TypeDef is either new or matches the definition already stored.
*
* @param userId unique identifier for requesting user.
* @param typeDef TypeDef structure describing the TypeDef to test.
* @return boolean true means the TypeDef matches the local definition false means the TypeDef is not known.
* @throws InvalidParameterException the TypeDef is null.
* @throws RepositoryErrorException there is a problem communicating with the metadata repository where
* the metadata collection is stored.
* @throws TypeDefNotSupportedException the repository is not able to support this TypeDef.
* @throws TypeDefConflictException the new TypeDef conflicts with an existing TypeDef.
* @throws InvalidTypeDefException the new TypeDef has invalid contents.
* @throws UserNotAuthorizedException the userId is not permitted to perform this operation.
*/
public boolean verifyTypeDef(String userId,
TypeDef typeDef) throws InvalidParameterException,
RepositoryErrorException,
TypeDefNotSupportedException,
TypeDefConflictException,
InvalidTypeDefException,
UserNotAuthorizedException
{
final String methodName = "verifyTypeDef";
final String typeDefParameterName = "typeDef";
/*
* Validate parameters
*/
this.validateRepositoryConnector(methodName);
parentConnector.validateRepositoryIsActive(methodName);
repositoryValidator.validateUserId(repositoryName, userId, methodName);
repositoryValidator.validateTypeDef(repositoryName, typeDefParameterName, typeDef, methodName);
/*
* The list of cohort connectors are retrieved for each request to ensure that any changes in
* the shape of the cohort are reflected immediately.
*/
List<OMRSRepositoryConnector> cohortConnectors = enterpriseParentConnector.getCohortConnectors(methodName);
/*
* Ready to process the request. Search results need to come from all members of the cohort.
* They need to be combined and then duplicates removed to create the final list of results.
* Some repositories may produce exceptions. These exceptions are saved and one selected to
* be returned if there are no results from any repository.
*/
TypeDefNotSupportedException typeDefNotSupportedException = null;
UserNotAuthorizedException userNotAuthorizedException = null;
RepositoryErrorException repositoryErrorException = null;
Throwable anotherException = null;
/*
* Loop through the metadata collections extracting the typedefs from each repository.
*/
for (OMRSRepositoryConnector cohortConnector : cohortConnectors)
{
if (cohortConnector != null)
{
OMRSMetadataCollection metadataCollection = cohortConnector.getMetadataCollection();
validateMetadataCollection(metadataCollection, methodName);
try
{
/*
* Issue the request and return if it succeeds (TypeDefConflictException is also returned
* immediately.)
*/
return metadataCollection.verifyTypeDef(userId, typeDef);
}
catch (TypeDefNotSupportedException error)
{
typeDefNotSupportedException = error;
}
catch (RepositoryErrorException error)
{
repositoryErrorException = error;
}
catch (UserNotAuthorizedException error)
{
userNotAuthorizedException = error;
}
catch (Throwable error)
{
anotherException = error;
}
}
}
throwCapturedRepositoryErrorException(repositoryErrorException);
throwCapturedUserNotAuthorizedException(userNotAuthorizedException);
throwCapturedThrowableException(anotherException, methodName);
throwCapturedTypeDefNotSupportedException(typeDefNotSupportedException);
return false;
}
/**
* Verify that a definition of an AttributeTypeDef is either new or matches the definition already stored.
*
* @param userId unique identifier for requesting user.
* @param attributeTypeDef TypeDef structure describing the TypeDef to test.
* @return boolean true means the TypeDef matches the local definition false means the TypeDef is not known.
* @throws InvalidParameterException the TypeDef is null.
* @throws RepositoryErrorException there is a problem communicating with the metadata repository where
* the metadata collection is stored.
* @throws TypeDefNotSupportedException the repository is not able to support this TypeDef.
* @throws TypeDefConflictException the new TypeDef conflicts with an existing TypeDef.
* @throws InvalidTypeDefException the new TypeDef has invalid contents.
* @throws UserNotAuthorizedException the userId is not permitted to perform this operation.
*/
public boolean verifyAttributeTypeDef(String userId,
AttributeTypeDef attributeTypeDef) throws InvalidParameterException,
RepositoryErrorException,
TypeDefNotSupportedException,
TypeDefConflictException,
InvalidTypeDefException,
UserNotAuthorizedException
{
final String methodName = "verifyAttributeTypeDef";
final String typeDefParameterName = "attributeTypeDef";
/*
* Validate parameters
*/
this.validateRepositoryConnector(methodName);
parentConnector.validateRepositoryIsActive(methodName);
repositoryValidator.validateUserId(repositoryName, userId, methodName);
repositoryValidator.validateAttributeTypeDef(repositoryName, typeDefParameterName, attributeTypeDef, methodName);
/*
* The list of cohort connectors are retrieved for each request to ensure that any changes in
* the shape of the cohort are reflected immediately.
*/
List<OMRSRepositoryConnector> cohortConnectors = enterpriseParentConnector.getCohortConnectors(methodName);
/*
* Ready to process the request. Search results need to come from all members of the cohort.
* They need to be combined and then duplicates removed to create the final list of results.
* Some repositories may produce exceptions. These exceptions are saved and one selected to
* be returned if there are no results from any repository.
*/
TypeDefNotSupportedException typeDefNotSupportedException = null;
UserNotAuthorizedException userNotAuthorizedException = null;
RepositoryErrorException repositoryErrorException = null;
Throwable anotherException = null;
/*
* Loop through the metadata collections extracting the typedefs from each repository.
*/
for (OMRSRepositoryConnector cohortConnector : cohortConnectors)
{
if (cohortConnector != null)
{
OMRSMetadataCollection metadataCollection = cohortConnector.getMetadataCollection();
validateMetadataCollection(metadataCollection, methodName);
try
{
/*
* Issue the request and return if it succeeds (TypeDefConflictException is also returned
* immediately.)
*/
return metadataCollection.verifyAttributeTypeDef(userId, attributeTypeDef);
}
catch (TypeDefNotSupportedException error)
{
typeDefNotSupportedException = error;
}
catch (RepositoryErrorException error)
{
repositoryErrorException = error;
}
catch (UserNotAuthorizedException error)
{
userNotAuthorizedException = error;
}
catch (Throwable error)
{
anotherException = error;
}
}
}
throwCapturedRepositoryErrorException(repositoryErrorException);
throwCapturedUserNotAuthorizedException(userNotAuthorizedException);
throwCapturedThrowableException(anotherException, methodName);
throwCapturedTypeDefNotSupportedException(typeDefNotSupportedException);
return false;
}
/**
* Update one or more properties of the TypeDef. The TypeDefPatch controls what types of updates
* are safe to make to the TypeDef.
*
* @param userId unique identifier for requesting user.
* @param typeDefPatch TypeDef patch describing change to TypeDef.
* @return updated TypeDef
* @throws FunctionNotSupportedException the repository does not support this call.
*/
public TypeDef updateTypeDef(String userId,
TypeDefPatch typeDefPatch) throws FunctionNotSupportedException
{
final String methodName = "updateTypeDef()";
throwNotEnterpriseFunction(methodName);
return null;
}
/**
* Delete the TypeDef. This is only possible if the TypeDef has never been used to create instances or any
* instances of this TypeDef have been purged from the metadata collection.
*
* @param userId unique identifier for requesting user.
* @param obsoleteTypeDefGUID String unique identifier for the TypeDef.
* @param obsoleteTypeDefName String unique name for the TypeDef.
* @throws FunctionNotSupportedException the repository does not support this call.
*/
public void deleteTypeDef(String userId,
String obsoleteTypeDefGUID,
String obsoleteTypeDefName) throws FunctionNotSupportedException
{
final String methodName = "deleteTypeDef()";
throwNotEnterpriseFunction(methodName);
}
/**
* Delete an AttributeTypeDef. This is only possible if the AttributeTypeDef has never been used to create
* instances or any instances of this AttributeTypeDef have been purged from the metadata collection.
*
* @param userId unique identifier for requesting user.
* @param obsoleteTypeDefGUID String unique identifier for the AttributeTypeDef.
* @param obsoleteTypeDefName String unique name for the AttributeTypeDef.
* @throws FunctionNotSupportedException the repository does not support this call.
*/
public void deleteAttributeTypeDef(String userId,
String obsoleteTypeDefGUID,
String obsoleteTypeDefName) throws FunctionNotSupportedException
{
final String methodName = "deleteAttributeTypeDef()";
throwNotEnterpriseFunction(methodName);
}
/**
* Change the guid or name of an existing TypeDef to a new value. This is used if two different
* TypeDefs are discovered to have the same guid. This is extremely unlikely but not impossible so
* the open metadata protocol has provision for this.
*
* @param userId unique identifier for requesting user.
* @param originalTypeDefGUID the original guid of the TypeDef.
* @param originalTypeDefName the original name of the TypeDef.
* @param newTypeDefGUID the new identifier for the TypeDef.
* @param newTypeDefName new name for this TypeDef.
* @return typeDef new values for this TypeDef, including the new guid/name.
* @throws FunctionNotSupportedException the repository does not support this call.
*/
public TypeDef reIdentifyTypeDef(String userId,
String originalTypeDefGUID,
String originalTypeDefName,
String newTypeDefGUID,
String newTypeDefName) throws FunctionNotSupportedException
{
final String methodName = "reIdentifyTypeDef()";
throwNotEnterpriseFunction(methodName);
return null;
}
/**
* Change the guid or name of an existing TypeDef to a new value. This is used if two different
* TypeDefs are discovered to have the same guid. This is extremely unlikely but not impossible so
* the open metadata protocol has provision for this.
*
* @param userId unique identifier for requesting user.
* @param originalAttributeTypeDefGUID the original guid of the AttributeTypeDef.
* @param originalAttributeTypeDefName the original name of the AttributeTypeDef.
* @param newAttributeTypeDefGUID the new identifier for the AttributeTypeDef.
* @param newAttributeTypeDefName new name for this AttributeTypeDef.
* @return attributeTypeDef new values for this AttributeTypeDef, including the new guid/name.
* @throws FunctionNotSupportedException the repository does not support this call.
*/
public AttributeTypeDef reIdentifyAttributeTypeDef(String userId,
String originalAttributeTypeDefGUID,
String originalAttributeTypeDefName,
String newAttributeTypeDefGUID,
String newAttributeTypeDefName) throws FunctionNotSupportedException
{
final String methodName = "reIdentifyAttributeTypeDef()";
throwNotEnterpriseFunction(methodName);
return null;
}
/* ===================================================
* Group 3: Locating entity and relationship instances
*/
/**
* Returns the entity if the entity is stored in the metadata collection, otherwise null.
*
* @param userId unique identifier for requesting user.
* @param guid String unique identifier for the entity
* @return the entity details if the entity is found in the metadata collection; otherwise return null
* @throws InvalidParameterException the guid is null.
* @throws RepositoryErrorException there is a problem communicating with the metadata repository where
* the metadata collection is stored.
* @throws UserNotAuthorizedException the userId is not permitted to perform this operation.
*/
public EntityDetail isEntityKnown(String userId,
String guid) throws InvalidParameterException,
RepositoryErrorException,
UserNotAuthorizedException
{
final String methodName = "isEntityKnown";
final String guidParameterName = "guid";
/*
* Validate parameters
*/
this.validateRepositoryConnector(methodName);
parentConnector.validateRepositoryIsActive(methodName);
repositoryValidator.validateUserId(repositoryName, userId, methodName);
repositoryValidator.validateGUID(repositoryName, guidParameterName, guid, methodName);
/*
* The list of cohort connectors are retrieved for each request to ensure that any changes in
* the shape of the cohort are reflected immediately.
*/
List<OMRSRepositoryConnector> cohortConnectors = enterpriseParentConnector.getCohortConnectors(methodName);
/*
* Ready to process the request. Search results need to come from all members of the cohort.
* They need to be combined and then duplicates removed to create the final list of results.
* Some repositories may produce exceptions. These exceptions are saved and one selected to
* be returned if there are no results from any repository.
*/
UserNotAuthorizedException userNotAuthorizedException = null;
RepositoryErrorException repositoryErrorException = null;
Throwable anotherException = null;
/*
* Loop through the metadata collections extracting the typedefs from each repository.
*/
for (OMRSRepositoryConnector cohortConnector : cohortConnectors)
{
if (cohortConnector != null)
{
OMRSMetadataCollection metadataCollection = cohortConnector.getMetadataCollection();
validateMetadataCollection(metadataCollection, methodName);
try
{
/*
* Issue the request and return if it succeeds
*/
return metadataCollection.isEntityKnown(userId, guid);
}
catch (RepositoryErrorException error)
{
repositoryErrorException = error;
}
catch (UserNotAuthorizedException error)
{
userNotAuthorizedException = error;
}
catch (Throwable error)
{
anotherException = error;
}
}
}
throwCapturedRepositoryErrorException(repositoryErrorException);
throwCapturedUserNotAuthorizedException(userNotAuthorizedException);
throwCapturedThrowableException(anotherException, methodName);
return null;
}
/**
* Return the header and classifications for a specific entity. The returned entity summary may be from
* a full entity object or an entity proxy.
*
* @param userId unique identifier for requesting user.
* @param guid String unique identifier for the entity
* @return EntitySummary structure
* @throws InvalidParameterException the guid is null.
* @throws RepositoryErrorException there is a problem communicating with the metadata repository where
* the metadata collection is stored.
* @throws EntityNotKnownException the requested entity instance is not known in the metadata collection.
* @throws UserNotAuthorizedException the userId is not permitted to perform this operation.
*/
public EntitySummary getEntitySummary(String userId,
String guid) throws InvalidParameterException,
RepositoryErrorException,
EntityNotKnownException,
UserNotAuthorizedException
{
final String methodName = "getEntitySummary";
final String guidParameterName = "guid";
/*
* Validate parameters
*/
this.validateRepositoryConnector(methodName);
parentConnector.validateRepositoryIsActive(methodName);
repositoryValidator.validateUserId(repositoryName, userId, methodName);
repositoryValidator.validateGUID(repositoryName, guidParameterName, guid, methodName);
/*
* The list of cohort connectors are retrieved for each request to ensure that any changes in
* the shape of the cohort are reflected immediately.
*/
List<OMRSRepositoryConnector> cohortConnectors = enterpriseParentConnector.getCohortConnectors(methodName);
/*
* Ready to process the request. Search results need to come from all members of the cohort.
* They need to be combined and then duplicates removed to create the final list of results.
* Some repositories may produce exceptions. These exceptions are saved and one selected to
* be returned if there are no results from any repository.
*/
EntityNotKnownException entityNotKnownException = null;
UserNotAuthorizedException userNotAuthorizedException = null;
RepositoryErrorException repositoryErrorException = null;
Throwable anotherException = null;
/*
* Loop through the metadata collections extracting the typedefs from each repository.
*/
for (OMRSRepositoryConnector cohortConnector : cohortConnectors)
{
if (cohortConnector != null)
{
OMRSMetadataCollection metadataCollection = cohortConnector.getMetadataCollection();
validateMetadataCollection(metadataCollection, methodName);
try
{
/*
* Issue the request and return if it succeeds
*/
EntitySummary entity = metadataCollection.getEntitySummary(userId, guid);
repositoryValidator.validateEntityFromStore(repositoryName, guid, entity, methodName);
return entity;
}
catch (EntityNotKnownException error)
{
entityNotKnownException = error;
}
catch (RepositoryErrorException error)
{
repositoryErrorException = error;
}
catch (UserNotAuthorizedException error)
{
userNotAuthorizedException = error;
}
catch (Throwable error)
{
anotherException = error;
}
}
}
throwCapturedRepositoryErrorException(repositoryErrorException);
throwCapturedUserNotAuthorizedException(userNotAuthorizedException);
throwCapturedThrowableException(anotherException, methodName);
throwCapturedEntityNotKnownException(entityNotKnownException);
return null;
}
/**
* Return the header, classifications and properties of a specific entity.
*
* @param userId unique identifier for requesting user.
* @param guid String unique identifier for the entity.
* @return EntityDetail structure.
* @throws InvalidParameterException the guid is null.
* @throws RepositoryErrorException there is a problem communicating with the metadata repository where
* the metadata collection is stored.
* @throws EntityNotKnownException the requested entity instance is not known in the metadata collection.
* @throws EntityProxyOnlyException the requested entity instance is only a proxy in the metadata collection.
* @throws UserNotAuthorizedException the userId is not permitted to perform this operation.
*/
public EntityDetail getEntityDetail(String userId,
String guid) throws InvalidParameterException,
RepositoryErrorException,
EntityNotKnownException,
EntityProxyOnlyException,
UserNotAuthorizedException
{
final String methodName = "getEntityDetail";
final String guidParameterName = "guid";
/*
* Validate parameters
*/
this.validateRepositoryConnector(methodName);
parentConnector.validateRepositoryIsActive(methodName);
repositoryValidator.validateUserId(repositoryName, userId, methodName);
repositoryValidator.validateGUID(repositoryName, guidParameterName, guid, methodName);
/*
* The list of cohort connectors are retrieved for each request to ensure that any changes in
* the shape of the cohort are reflected immediately.
*/
List<OMRSRepositoryConnector> cohortConnectors = enterpriseParentConnector.getCohortConnectors(methodName);
/*
* Ready to process the request. Search results need to come from all members of the cohort.
* They need to be combined and then duplicates removed to create the final list of results.
* Some repositories may produce exceptions. These exceptions are saved and one selected to
* be returned if there are no results from any repository.
*/
EntityNotKnownException entityNotKnownException = null;
EntityProxyOnlyException entityProxyOnlyException = null;
UserNotAuthorizedException userNotAuthorizedException = null;
RepositoryErrorException repositoryErrorException = null;
Throwable anotherException = null;
/*
* Loop through the metadata collections extracting the typedefs from each repository.
*/
for (OMRSRepositoryConnector cohortConnector : cohortConnectors)
{
if (cohortConnector != null)
{
OMRSMetadataCollection metadataCollection = cohortConnector.getMetadataCollection();
validateMetadataCollection(metadataCollection, methodName);
try
{
/*
* Issue the request and return if it succeeds
*/
EntityDetail entity = metadataCollection.getEntityDetail(userId, guid);
repositoryValidator.validateEntityFromStore(repositoryName, guid, entity, methodName);
return entity;
}
catch (EntityNotKnownException error)
{
entityNotKnownException = error;
}
catch (EntityProxyOnlyException error)
{
entityProxyOnlyException = error;
}
catch (RepositoryErrorException error)
{
repositoryErrorException = error;
}
catch (UserNotAuthorizedException error)
{
userNotAuthorizedException = error;
}
catch (Throwable error)
{
anotherException = error;
}
}
}
throwCapturedRepositoryErrorException(repositoryErrorException);
throwCapturedUserNotAuthorizedException(userNotAuthorizedException);
throwCapturedThrowableException(anotherException, methodName);
throwCapturedEntityNotKnownException(entityNotKnownException);
throwCapturedEntityProxyOnlyException(entityProxyOnlyException);
return null;
}
/**
* Return a historical version of an entity. This includes the header, classifications and properties of the entity.
*
* @param userId unique identifier for requesting user.
* @param guid String unique identifier for the entity.
* @param asOfTime the time used to determine which version of the entity that is desired.
* @return EntityDetail structure.
* @throws InvalidParameterException the guid or date is null or the date is for a future time.
* @throws RepositoryErrorException there is a problem communicating with the metadata repository where
* the metadata collection is stored.
* @throws EntityNotKnownException the requested entity instance is not known in the metadata collection
* at the time requested.
* @throws EntityProxyOnlyException the requested entity instance is only a proxy in the metadata collection.
* @throws FunctionNotSupportedException the repository does not support the asOfTime parameter.
* @throws UserNotAuthorizedException the userId is not permitted to perform this operation.
*/
public EntityDetail getEntityDetail(String userId,
String guid,
Date asOfTime) throws InvalidParameterException,
RepositoryErrorException,
EntityNotKnownException,
EntityProxyOnlyException,
FunctionNotSupportedException,
UserNotAuthorizedException
{
final String methodName = "getEntityDetail";
final String guidParameterName = "guid";
final String asOfTimeParameter = "asOfTime";
/*
* Validate parameters
*/
this.validateRepositoryConnector(methodName);
parentConnector.validateRepositoryIsActive(methodName);
repositoryValidator.validateUserId(repositoryName, userId, methodName);
repositoryValidator.validateGUID(repositoryName, guidParameterName, guid, methodName);
repositoryValidator.validateAsOfTime(repositoryName, asOfTimeParameter, asOfTime, methodName);
/*
* The list of cohort connectors are retrieved for each request to ensure that any changes in
* the shape of the cohort are reflected immediately.
*/
List<OMRSRepositoryConnector> cohortConnectors = enterpriseParentConnector.getCohortConnectors(methodName);
/*
* Ready to process the request. Search results need to come from all members of the cohort.
* They need to be combined and then duplicates removed to create the final list of results.
* Some repositories may produce exceptions. These exceptions are saved and one selected to
* be returned if there are no results from any repository.
*/
EntityNotKnownException entityNotKnownException = null;
EntityProxyOnlyException entityProxyOnlyException = null;
FunctionNotSupportedException functionNotSupportedException = null;
UserNotAuthorizedException userNotAuthorizedException = null;
RepositoryErrorException repositoryErrorException = null;
Throwable anotherException = null;
/*
* Loop through the metadata collections extracting the typedefs from each repository.
*/
for (OMRSRepositoryConnector cohortConnector : cohortConnectors)
{
if (cohortConnector != null)
{
OMRSMetadataCollection metadataCollection = cohortConnector.getMetadataCollection();
validateMetadataCollection(metadataCollection, methodName);
try
{
/*
* Issue the request and return if it succeeds
*/
EntityDetail entity = metadataCollection.getEntityDetail(userId, guid, asOfTime);
repositoryValidator.validateEntityFromStore(repositoryName, guid, entity, methodName);
return entity;
}
catch (EntityNotKnownException error)
{
entityNotKnownException = error;
}
catch (EntityProxyOnlyException error)
{
entityProxyOnlyException = error;
}
catch (RepositoryErrorException error)
{
repositoryErrorException = error;
}
catch (UserNotAuthorizedException error)
{
userNotAuthorizedException = error;
}
catch (FunctionNotSupportedException error)
{
functionNotSupportedException = error;
}
catch (Throwable error)
{
anotherException = error;
}
}
}
throwCapturedRepositoryErrorException(repositoryErrorException);
throwCapturedUserNotAuthorizedException(userNotAuthorizedException);
throwCapturedThrowableException(anotherException, methodName);
throwCapturedEntityNotKnownException(entityNotKnownException);
throwCapturedEntityProxyOnlyException(entityProxyOnlyException);
throwCapturedFunctionNotSupportedException(functionNotSupportedException);
return null;
}
/**
* Return the relationships for a specific entity.
*
* @param userId unique identifier for requesting user.
* @param entityGUID String unique identifier for the entity.
* @param relationshipTypeGUID String GUID of the the type of relationship required (null for all).
* @param fromRelationshipElement the starting element number of the relationships to return.
* This is used when retrieving elements
* beyond the first page of results. Zero means start from the first element.
* @param limitResultsByStatus By default, relationships in all statuses are returned. However, it is possible
* to specify a list of statuses (eg ACTIVE) to restrict the results to. Null means all
* status values.
* @param asOfTime Requests a historical query of the relationships for the entity. Null means return the
* present values.
* @param sequencingProperty String name of the property that is to be used to sequence the results.
* Null means do not sequence on a property name (see SequencingOrder).
* @param sequencingOrder Enum defining how the results should be ordered.
* @param pageSize -- the maximum number of result classifications that can be returned on this request. Zero means
* unrestricted return results size.
* @return Relationships list. Null means no relationships associated with the entity.
* @throws InvalidParameterException a parameter is invalid or null.
* @throws TypeErrorException the type guid passed on the request is not known by the
* metadata collection.
* @throws RepositoryErrorException there is a problem communicating with the metadata repository where
* the metadata collection is stored.
* @throws EntityNotKnownException the requested entity instance is not known in the metadata collection.
* @throws PropertyErrorException the sequencing property is not valid for the attached classifications.
* @throws PagingErrorException the paging/sequencing parameters are set up incorrectly.
* @throws FunctionNotSupportedException the repository does not support the asOfTime parameter.
* @throws UserNotAuthorizedException the userId is not permitted to perform this operation.
*/
public List<Relationship> getRelationshipsForEntity(String userId,
String entityGUID,
String relationshipTypeGUID,
int fromRelationshipElement,
List<InstanceStatus> limitResultsByStatus,
Date asOfTime,
String sequencingProperty,
SequencingOrder sequencingOrder,
int pageSize) throws InvalidParameterException,
TypeErrorException,
RepositoryErrorException,
EntityNotKnownException,
PropertyErrorException,
PagingErrorException,
FunctionNotSupportedException,
UserNotAuthorizedException
{
final String methodName = "getRelationshipsForEntity";
final String guidParameterName = "entityGUID";
final String asOfTimeParameter = "asOfTime";
final String typeGUIDParameter = "relationshipTypeGUID";
final String pageSizeParameter = "pageSize";
/*
* Validate parameters
*/
this.validateRepositoryConnector(methodName);
parentConnector.validateRepositoryIsActive(methodName);
repositoryValidator.validateUserId(repositoryName, userId, methodName);
repositoryValidator.validateGUID(repositoryName, guidParameterName, entityGUID, methodName);
repositoryValidator.validateOptionalTypeGUID(repositoryName, typeGUIDParameter, relationshipTypeGUID, methodName);
repositoryValidator.validateAsOfTime(repositoryName, asOfTimeParameter, asOfTime, methodName);
repositoryValidator.validatePageSize(repositoryName, pageSizeParameter, pageSize, methodName);
/*
* Perform operation
*
* The list of cohort connectors are retrieved for each request to ensure that any changes in
* the shape of the cohort are reflected immediately.
*/
List<OMRSRepositoryConnector> cohortConnectors = enterpriseParentConnector.getCohortConnectors(methodName);
/*
* Ready to process the request. Search results need to come from all members of the cohort.
* They need to be combined and then duplicates removed to create the final list of results.
* Some repositories may produce exceptions. These exceptions are saved and one selected to
* be returned if there are no results from any repository.
*/
Map<String, Relationship> combinedResults = new HashMap<>();
InvalidParameterException invalidParameterException = null;
EntityNotKnownException entityNotKnownException = null;
FunctionNotSupportedException functionNotSupportedException = null;
PropertyErrorException propertyErrorException = null;
UserNotAuthorizedException userNotAuthorizedException = null;
RepositoryErrorException repositoryErrorException = null;
Throwable anotherException = null;
/*
* Loop through the metadata collections extracting the typedefs from each repository.
*/
for (OMRSRepositoryConnector cohortConnector : cohortConnectors)
{
if (cohortConnector != null)
{
OMRSMetadataCollection metadataCollection = cohortConnector.getMetadataCollection();
validateMetadataCollection(metadataCollection, methodName);
try
{
/*
* Issue the request
*/
List<Relationship> results = metadataCollection.getRelationshipsForEntity(userId,
entityGUID,
relationshipTypeGUID,
fromRelationshipElement,
limitResultsByStatus,
asOfTime,
sequencingProperty,
sequencingOrder,
pageSize);
/*
* Step through the list of returned TypeDefs and remove duplicates.
*/
combinedResults = this.addUniqueRelationships(combinedResults,
results,
cohortConnector.getServerName(),
cohortConnector.getMetadataCollectionId(),
methodName);
}
catch (InvalidParameterException error)
{
invalidParameterException = error;
}
catch (EntityNotKnownException error)
{
entityNotKnownException = error;
}
catch (FunctionNotSupportedException error)
{
functionNotSupportedException = error;
}
catch (PropertyErrorException error)
{
propertyErrorException = error;
}
catch (RepositoryErrorException error)
{
repositoryErrorException = error;
}
catch (UserNotAuthorizedException error)
{
userNotAuthorizedException = error;
}
catch (Throwable error)
{
anotherException = error;
}
}
}
if (combinedResults.isEmpty())
{
throwCapturedRepositoryErrorException(repositoryErrorException);
throwCapturedUserNotAuthorizedException(userNotAuthorizedException);
throwCapturedThrowableException(anotherException, methodName);
throwCapturedPropertyErrorException(propertyErrorException);
throwCapturedInvalidParameterException(invalidParameterException);
throwCapturedFunctionNotSupportedException(functionNotSupportedException);
throwCapturedEntityNotKnownException(entityNotKnownException);
return null;
}
return validatedRelationshipResults(repositoryName,
combinedResults,
sequencingProperty,
sequencingOrder,
pageSize,
methodName);
}
/**
* Return a list of entities that match the supplied properties according to the match criteria. The results
* can be returned over many pages.
*
* @param userId unique identifier for requesting user.
* @param entityTypeGUID String unique identifier for the entity type of interest (null means any entity type).
* @param matchProperties List of entity properties to match to (null means match on entityTypeGUID only).
* @param matchCriteria Enum defining how the properties should be matched to the entities in the repository.
* @param fromEntityElement the starting element number of the entities to return.
* This is used when retrieving elements
* beyond the first page of results. Zero means start from the first element.
* @param limitResultsByStatus By default, entities in all statuses are returned. However, it is possible
* to specify a list of statuses (eg ACTIVE) to restrict the results to. Null means all
* status values.
* @param limitResultsByClassification List of classifications that must be present on all returned entities.
* @param asOfTime Requests a historical query of the entity. Null means return the present values.
* @param sequencingProperty String name of the entity property that is to be used to sequence the results.
* Null means do not sequence on a property name (see SequencingOrder).
* @param sequencingOrder Enum defining how the results should be ordered.
* @param pageSize the maximum number of result entities that can be returned on this request. Zero means
* unrestricted return results size.
* @return a list of entities matching the supplied criteria null means no matching entities in the metadata
* collection.
* @throws InvalidParameterException a parameter is invalid or null.
* @throws TypeErrorException the type guid passed on the request is not known by the
* metadata collection.
* @throws RepositoryErrorException there is a problem communicating with the metadata repository where
* the metadata collection is stored.
* @throws PropertyErrorException the properties specified are not valid for any of the requested types of
* entity.
* @throws PagingErrorException the paging/sequencing parameters are set up incorrectly.
* @throws FunctionNotSupportedException the repository does not support the asOfTime parameter.
* @throws UserNotAuthorizedException the userId is not permitted to perform this operation.
*/
public List<EntityDetail> findEntitiesByProperty(String userId,
String entityTypeGUID,
InstanceProperties matchProperties,
MatchCriteria matchCriteria,
int fromEntityElement,
List<InstanceStatus> limitResultsByStatus,
List<String> limitResultsByClassification,
Date asOfTime,
String sequencingProperty,
SequencingOrder sequencingOrder,
int pageSize) throws InvalidParameterException,
TypeErrorException,
RepositoryErrorException,
PropertyErrorException,
PagingErrorException,
FunctionNotSupportedException,
UserNotAuthorizedException
{
final String methodName = "findEntitiesByProperty";
final String matchCriteriaParameterName = "matchCriteria";
final String matchPropertiesParameterName = "matchProperties";
final String asOfTimeParameter = "asOfTime";
final String guidParameter = "entityTypeGUID";
final String pageSizeParameter = "pageSize";
/*
* Validate parameters
*/
this.validateRepositoryConnector(methodName);
parentConnector.validateRepositoryIsActive(methodName);
repositoryValidator.validateUserId(repositoryName, userId, methodName);
repositoryValidator.validateOptionalTypeGUID(repositoryName, guidParameter, entityTypeGUID, methodName);
repositoryValidator.validateAsOfTime(repositoryName, asOfTimeParameter, asOfTime, methodName);
repositoryValidator.validatePageSize(repositoryName, pageSizeParameter, pageSize, methodName);
repositoryValidator.validateMatchCriteria(repositoryName,
matchCriteriaParameterName,
matchPropertiesParameterName,
matchCriteria,
matchProperties,
methodName);
/*
* Perform operation
*
* The list of cohort connectors are retrieved for each request to ensure that any changes in
* the shape of the cohort are reflected immediately.
*/
List<OMRSRepositoryConnector> cohortConnectors = enterpriseParentConnector.getCohortConnectors(methodName);
/*
* Ready to process the request. Search results need to come from all members of the cohort.
* They need to be combined and then duplicates removed to create the final list of results.
* Some repositories may produce exceptions. These exceptions are saved and one selected to
* be returned if there are no results from any repository.
*/
Map<String, EntityDetail> combinedResults = new HashMap<>();
InvalidParameterException invalidParameterException = null;
FunctionNotSupportedException functionNotSupportedException = null;
TypeErrorException typeErrorException = null;
PropertyErrorException propertyErrorException = null;
UserNotAuthorizedException userNotAuthorizedException = null;
RepositoryErrorException repositoryErrorException = null;
Throwable anotherException = null;
/*
* Loop through the metadata collections extracting the typedefs from each repository.
*/
for (OMRSRepositoryConnector cohortConnector : cohortConnectors)
{
if (cohortConnector != null)
{
OMRSMetadataCollection metadataCollection = cohortConnector.getMetadataCollection();
validateMetadataCollection(metadataCollection, methodName);
try
{
/*
* Issue the request
*/
List<EntityDetail> results = metadataCollection.findEntitiesByProperty(userId,
entityTypeGUID,
matchProperties,
matchCriteria,
fromEntityElement,
limitResultsByStatus,
limitResultsByClassification,
asOfTime,
sequencingProperty,
sequencingOrder,
pageSize);
/*
* Step through the list of returned TypeDefs and remove duplicates.
*/
combinedResults = this.addUniqueEntities(combinedResults,
results,
cohortConnector.getServerName(),
cohortConnector.getMetadataCollectionId(),
methodName);
}
catch (InvalidParameterException error)
{
invalidParameterException = error;
}
catch (FunctionNotSupportedException error)
{
functionNotSupportedException = error;
}
catch (TypeErrorException error)
{
typeErrorException = error;
}
catch (PropertyErrorException error)
{
propertyErrorException = error;
}
catch (RepositoryErrorException error)
{
repositoryErrorException = error;
}
catch (UserNotAuthorizedException error)
{
userNotAuthorizedException = error;
}
catch (Throwable error)
{
anotherException = error;
}
}
}
if (combinedResults.isEmpty())
{
throwCapturedRepositoryErrorException(repositoryErrorException);
throwCapturedUserNotAuthorizedException(userNotAuthorizedException);
throwCapturedThrowableException(anotherException, methodName);
throwCapturedTypeErrorException(typeErrorException);
throwCapturedPropertyErrorException(propertyErrorException);
throwCapturedInvalidParameterException(invalidParameterException);
throwCapturedFunctionNotSupportedException(functionNotSupportedException);
return null;
}
return validatedEntityListResults(repositoryName,
combinedResults,
sequencingProperty,
sequencingOrder,
pageSize,
methodName);
}
/**
* Return a list of entities that have the requested type of classifications attached.
*
* @param userId unique identifier for requesting user.
* @param entityTypeGUID unique identifier for the type of entity requested. Null mans any type of entity.
* @param classificationName name of the classification a null is not valid.
* @param matchClassificationProperties list of classification properties used to narrow the search.
* @param matchCriteria Enum defining how the properties should be matched to the classifications in the repository.
* @param fromEntityElement the starting element number of the entities to return.
* This is used when retrieving elements
* beyond the first page of results. Zero means start from the first element.
* @param limitResultsByStatus By default, entities in all statuses are returned. However, it is possible
* to specify a list of statuses (eg ACTIVE) to restrict the results to. Null means all
* status values.
* @param asOfTime Requests a historical query of the entity. Null means return the present values.
* @param sequencingProperty String name of the entity property that is to be used to sequence the results.
* Null means do not sequence on a property name (see SequencingOrder).
* @param sequencingOrder Enum defining how the results should be ordered.
* @param pageSize the maximum number of result entities that can be returned on this request. Zero means
* unrestricted return results size.
* @return a list of entities matching the supplied criteria null means no matching entities in the metadata
* collection.
* @throws InvalidParameterException a parameter is invalid or null.
* @throws TypeErrorException the type guid passed on the request is not known by the
* metadata collection.
* @throws RepositoryErrorException there is a problem communicating with the metadata repository where
* the metadata collection is stored.
* @throws ClassificationErrorException the classification request is not known to the metadata collection.
* @throws PropertyErrorException the properties specified are not valid for the requested type of
* classification.
* @throws PagingErrorException the paging/sequencing parameters are set up incorrectly.
* @throws FunctionNotSupportedException the repository does not support the asOfTime parameter.
* @throws UserNotAuthorizedException the userId is not permitted to perform this operation.
*/
public List<EntityDetail> findEntitiesByClassification(String userId,
String entityTypeGUID,
String classificationName,
InstanceProperties matchClassificationProperties,
MatchCriteria matchCriteria,
int fromEntityElement,
List<InstanceStatus> limitResultsByStatus,
Date asOfTime,
String sequencingProperty,
SequencingOrder sequencingOrder,
int pageSize) throws InvalidParameterException,
TypeErrorException,
RepositoryErrorException,
ClassificationErrorException,
PropertyErrorException,
PagingErrorException,
FunctionNotSupportedException,
UserNotAuthorizedException
{
final String methodName = "findEntitiesByClassification";
final String classificationParameterName = "classificationName";
final String entityTypeGUIDParameterName = "entityTypeGUID";
final String matchCriteriaParameterName = "matchCriteria";
final String matchPropertiesParameterName = "matchClassificationProperties";
final String asOfTimeParameter = "asOfTime";
final String pageSizeParameter = "pageSize";
/*
* Validate parameters
*/
this.validateRepositoryConnector(methodName);
parentConnector.validateRepositoryIsActive(methodName);
repositoryValidator.validateUserId(repositoryName, userId, methodName);
repositoryValidator.validateOptionalTypeGUID(repositoryName, entityTypeGUIDParameterName, entityTypeGUID, methodName);
repositoryValidator.validateAsOfTime(repositoryName, asOfTimeParameter, asOfTime, methodName);
repositoryValidator.validatePageSize(repositoryName, pageSizeParameter, pageSize, methodName);
/*
* Validate TypeDef
*/
if (entityTypeGUID != null)
{
TypeDef entityTypeDef = repositoryHelper.getTypeDef(repositoryName,
entityTypeGUIDParameterName,
entityTypeGUID,
methodName);
repositoryValidator.validateTypeDefForInstance(repositoryName,
entityTypeGUIDParameterName,
entityTypeDef,
methodName);
repositoryValidator.validateClassification(repositoryName,
classificationParameterName,
classificationName,
entityTypeDef.getName(),
methodName);
}
repositoryValidator.validateMatchCriteria(repositoryName,
matchCriteriaParameterName,
matchPropertiesParameterName,
matchCriteria,
matchClassificationProperties,
methodName);
/*
* Perform operation
*
* The list of cohort connectors are retrieved for each request to ensure that any changes in
* the shape of the cohort are reflected immediately.
*/
List<OMRSRepositoryConnector> cohortConnectors = enterpriseParentConnector.getCohortConnectors(methodName);
/*
* Ready to process the request. Search results need to come from all members of the cohort.
* They need to be combined and then duplicates removed to create the final list of results.
* Some repositories may produce exceptions. These exceptions are saved and one selected to
* be returned if there are no results from any repository.
*/
Map<String, EntityDetail> combinedResults = new HashMap<>();
InvalidParameterException invalidParameterException = null;
FunctionNotSupportedException functionNotSupportedException = null;
TypeErrorException typeErrorException = null;
PropertyErrorException propertyErrorException = null;
UserNotAuthorizedException userNotAuthorizedException = null;
RepositoryErrorException repositoryErrorException = null;
Throwable anotherException = null;
/*
* Loop through the metadata collections extracting the typedefs from each repository.
*/
for (OMRSRepositoryConnector cohortConnector : cohortConnectors)
{
if (cohortConnector != null)
{
OMRSMetadataCollection metadataCollection = cohortConnector.getMetadataCollection();
validateMetadataCollection(metadataCollection, methodName);
try
{
/*
* Issue the request
*/
List<EntityDetail> results = metadataCollection.findEntitiesByClassification(userId,
entityTypeGUID,
classificationName,
matchClassificationProperties,
matchCriteria,
fromEntityElement,
limitResultsByStatus,
asOfTime,
sequencingProperty,
sequencingOrder,
pageSize);
/*
* Step through the list of returned TypeDefs and remove duplicates.
*/
combinedResults = this.addUniqueEntities(combinedResults,
results,
cohortConnector.getServerName(),
cohortConnector.getMetadataCollectionId(),
methodName);
}
catch (InvalidParameterException error)
{
invalidParameterException = error;
}
catch (FunctionNotSupportedException error)
{
functionNotSupportedException = error;
}
catch (TypeErrorException error)
{
typeErrorException = error;
}
catch (PropertyErrorException error)
{
propertyErrorException = error;
}
catch (RepositoryErrorException error)
{
repositoryErrorException = error;
}
catch (UserNotAuthorizedException error)
{
userNotAuthorizedException = error;
}
catch (Throwable error)
{
anotherException = error;
}
}
}
if (combinedResults.isEmpty())
{
throwCapturedRepositoryErrorException(repositoryErrorException);
throwCapturedUserNotAuthorizedException(userNotAuthorizedException);
throwCapturedThrowableException(anotherException, methodName);
throwCapturedTypeErrorException(typeErrorException);
throwCapturedPropertyErrorException(propertyErrorException);
throwCapturedInvalidParameterException(invalidParameterException);
throwCapturedFunctionNotSupportedException(functionNotSupportedException);
return null;
}
return validatedEntityListResults(repositoryName,
combinedResults,
sequencingProperty,
sequencingOrder,
pageSize,
methodName);
}
/**
* Return a list of entities whose string based property values match the search criteria. The
* search criteria may include regex style wild cards.
*
* @param userId unique identifier for requesting user.
* @param entityTypeGUID GUID of the type of entity to search for. Null means all types will
* be searched (could be slow so not recommended).
* @param searchCriteria String expression contained in any of the property values within the entities
* of the supplied type.
* @param fromEntityElement the starting element number of the entities to return.
* This is used when retrieving elements
* beyond the first page of results. Zero means start from the first element.
* @param limitResultsByStatus By default, entities in all statuses are returned. However, it is possible
* to specify a list of statuses (eg ACTIVE) to restrict the results to. Null means all
* status values.
* @param limitResultsByClassification List of classifications that must be present on all returned entities.
* @param asOfTime Requests a historical query of the entity. Null means return the present values.
* @param sequencingProperty String name of the property that is to be used to sequence the results.
* Null means do not sequence on a property name (see SequencingOrder).
* @param sequencingOrder Enum defining how the results should be ordered.
* @param pageSize the maximum number of result entities that can be returned on this request. Zero means
* unrestricted return results size.
* @return a list of entities matching the supplied criteria null means no matching entities in the metadata
* collection.
* @throws InvalidParameterException a parameter is invalid or null.
* @throws TypeErrorException the type guid passed on the request is not known by the
* metadata collection.
* @throws RepositoryErrorException there is a problem communicating with the metadata repository where
* the metadata collection is stored.
* @throws PropertyErrorException the sequencing property specified is not valid for any of the requested types of
* entity.
* @throws PagingErrorException the paging/sequencing parameters are set up incorrectly.
* @throws FunctionNotSupportedException the repository does not support the asOfTime parameter.
* @throws UserNotAuthorizedException the userId is not permitted to perform this operation.
*/
public List<EntityDetail> findEntitiesByPropertyValue(String userId,
String entityTypeGUID,
String searchCriteria,
int fromEntityElement,
List<InstanceStatus> limitResultsByStatus,
List<String> limitResultsByClassification,
Date asOfTime,
String sequencingProperty,
SequencingOrder sequencingOrder,
int pageSize) throws InvalidParameterException,
TypeErrorException,
RepositoryErrorException,
PropertyErrorException,
PagingErrorException,
FunctionNotSupportedException,
UserNotAuthorizedException
{
final String methodName = "findEntitiesByPropertyValue";
final String searchCriteriaParameterName = "searchCriteria";
final String asOfTimeParameter = "asOfTime";
final String guidParameter = "entityTypeGUID";
final String pageSizeParameter = "pageSize";
/*
* Validate parameters
*/
this.validateRepositoryConnector(methodName);
parentConnector.validateRepositoryIsActive(methodName);
repositoryValidator.validateUserId(repositoryName, userId, methodName);
repositoryValidator.validateSearchCriteria(repositoryName, searchCriteriaParameterName, searchCriteria, methodName);
repositoryValidator.validateOptionalTypeGUID(repositoryName, guidParameter, entityTypeGUID, methodName);
repositoryValidator.validateAsOfTime(repositoryName, asOfTimeParameter, asOfTime, methodName);
repositoryValidator.validatePageSize(repositoryName, pageSizeParameter, pageSize, methodName);
/*
* Perform operation
*
* The list of cohort connectors are retrieved for each request to ensure that any changes in
* the shape of the cohort are reflected immediately.
*/
List<OMRSRepositoryConnector> cohortConnectors = enterpriseParentConnector.getCohortConnectors(methodName);
/*
* Ready to process the request. Search results need to come from all members of the cohort.
* They need to be combined and then duplicates removed to create the final list of results.
* Some repositories may produce exceptions. These exceptions are saved and one selected to
* be returned if there are no results from any repository.
*/
Map<String, EntityDetail> combinedResults = new HashMap<>();
InvalidParameterException invalidParameterException = null;
FunctionNotSupportedException functionNotSupportedException = null;
TypeErrorException typeErrorException = null;
PropertyErrorException propertyErrorException = null;
UserNotAuthorizedException userNotAuthorizedException = null;
RepositoryErrorException repositoryErrorException = null;
Throwable anotherException = null;
/*
* Loop through the metadata collections extracting the typedefs from each repository.
*/
for (OMRSRepositoryConnector cohortConnector : cohortConnectors)
{
if (cohortConnector != null)
{
OMRSMetadataCollection metadataCollection = cohortConnector.getMetadataCollection();
validateMetadataCollection(metadataCollection, methodName);
try
{
/*
* Issue the request
*/
List<EntityDetail> results = metadataCollection.findEntitiesByPropertyValue(userId,
entityTypeGUID,
searchCriteria,
fromEntityElement,
limitResultsByStatus,
limitResultsByClassification,
asOfTime,
sequencingProperty,
sequencingOrder,
pageSize);
/*
* Step through the list of returned TypeDefs and remove duplicates.
*/
combinedResults = this.addUniqueEntities(combinedResults,
results,
cohortConnector.getServerName(),
cohortConnector.getMetadataCollectionId(),
methodName);
}
catch (InvalidParameterException error)
{
invalidParameterException = error;
}
catch (FunctionNotSupportedException error)
{
functionNotSupportedException = error;
}
catch (TypeErrorException error)
{
typeErrorException = error;
}
catch (PropertyErrorException error)
{
propertyErrorException = error;
}
catch (RepositoryErrorException error)
{
repositoryErrorException = error;
}
catch (UserNotAuthorizedException error)
{
userNotAuthorizedException = error;
}
catch (Throwable error)
{
anotherException = error;
}
}
}
if (combinedResults.isEmpty())
{
throwCapturedRepositoryErrorException(repositoryErrorException);
throwCapturedUserNotAuthorizedException(userNotAuthorizedException);
throwCapturedThrowableException(anotherException, methodName);
throwCapturedTypeErrorException(typeErrorException);
throwCapturedPropertyErrorException(propertyErrorException);
throwCapturedInvalidParameterException(invalidParameterException);
throwCapturedFunctionNotSupportedException(functionNotSupportedException);
return null;
}
return validatedEntityListResults(repositoryName,
combinedResults,
sequencingProperty,
sequencingOrder,
pageSize,
methodName);
}
/**
* Returns a boolean indicating if the relationship is stored in the metadata collection.
*
* @param userId unique identifier for requesting user.
* @param guid String unique identifier for the relationship
* @return relationship details if the relationship is found in the metadata collection; otherwise return null
* @throws InvalidParameterException the guid is null.
* @throws RepositoryErrorException there is a problem communicating with the metadata repository where
* the metadata collection is stored.
* @throws UserNotAuthorizedException the userId is not permitted to perform this operation.
*/
public Relationship isRelationshipKnown(String userId,
String guid) throws InvalidParameterException,
RepositoryErrorException,
UserNotAuthorizedException
{
final String methodName = "isRelationshipKnown";
final String guidParameterName = "guid";
/*
* Validate parameters
*/
this.validateRepositoryConnector(methodName);
parentConnector.validateRepositoryIsActive(methodName);
repositoryValidator.validateUserId(repositoryName, userId, methodName);
repositoryValidator.validateGUID(repositoryName, guidParameterName, guid, methodName);
/*
* The list of cohort connectors are retrieved for each request to ensure that any changes in
* the shape of the cohort are reflected immediately.
*/
List<OMRSRepositoryConnector> cohortConnectors = enterpriseParentConnector.getCohortConnectors(methodName);
/*
* Ready to process the request. Search results need to come from all members of the cohort.
* They need to be combined and then duplicates removed to create the final list of results.
* Some repositories may produce exceptions. These exceptions are saved and one selected to
* be returned if there are no results from any repository.
*/
UserNotAuthorizedException userNotAuthorizedException = null;
RepositoryErrorException repositoryErrorException = null;
Throwable anotherException = null;
/*
* Loop through the metadata collections extracting the typedefs from each repository.
*/
for (OMRSRepositoryConnector cohortConnector : cohortConnectors)
{
if (cohortConnector != null)
{
OMRSMetadataCollection metadataCollection = cohortConnector.getMetadataCollection();
validateMetadataCollection(metadataCollection, methodName);
try
{
/*
* Issue the request and return if it succeeds
*/
Relationship relationship = this.isRelationshipKnown(userId, guid);
repositoryValidator.validateRelationshipFromStore(repositoryName, guid, relationship, methodName);
return relationship;
}
catch (RepositoryErrorException error)
{
repositoryErrorException = error;
}
catch (UserNotAuthorizedException error)
{
userNotAuthorizedException = error;
}
catch (Throwable error)
{
anotherException = error;
}
}
}
throwCapturedRepositoryErrorException(repositoryErrorException);
throwCapturedUserNotAuthorizedException(userNotAuthorizedException);
throwCapturedThrowableException(anotherException, methodName);
return null;
}
/**
* Return a requested relationship.
*
* @param userId unique identifier for requesting user.
* @param guid String unique identifier for the relationship.
* @return a relationship structure.
* @throws InvalidParameterException the guid is null.
* @throws RepositoryErrorException there is a problem communicating with the metadata repository where
* the metadata collection is stored.
* @throws RelationshipNotKnownException the metadata collection does not have a relationship with
* the requested GUID stored.
* @throws UserNotAuthorizedException the userId is not permitted to perform this operation.
*/
public Relationship getRelationship(String userId,
String guid) throws InvalidParameterException,
RepositoryErrorException,
RelationshipNotKnownException,
UserNotAuthorizedException
{
final String methodName = "getRelationship";
final String guidParameterName = "guid";
/*
* Validate parameters
*/
this.validateRepositoryConnector(methodName);
parentConnector.validateRepositoryIsActive(methodName);
repositoryValidator.validateUserId(repositoryName, userId, methodName);
repositoryValidator.validateGUID(repositoryName, guidParameterName, guid, methodName);
/*
* The list of cohort connectors are retrieved for each request to ensure that any changes in
* the shape of the cohort are reflected immediately.
*/
List<OMRSRepositoryConnector> cohortConnectors = enterpriseParentConnector.getCohortConnectors(methodName);
/*
* Ready to process the request. Search results need to come from all members of the cohort.
* They need to be combined and then duplicates removed to create the final list of results.
* Some repositories may produce exceptions. These exceptions are saved and one selected to
* be returned if there are no results from any repository.
*/
RelationshipNotKnownException relationshipNotKnownException = null;
UserNotAuthorizedException userNotAuthorizedException = null;
RepositoryErrorException repositoryErrorException = null;
Throwable anotherException = null;
/*
* Loop through the metadata collections extracting the typedefs from each repository.
*/
for (OMRSRepositoryConnector cohortConnector : cohortConnectors)
{
if (cohortConnector != null)
{
OMRSMetadataCollection metadataCollection = cohortConnector.getMetadataCollection();
validateMetadataCollection(metadataCollection, methodName);
try
{
/*
* Issue the request and return if it succeeds
*/
Relationship relationship = this.getRelationship(userId, guid);
repositoryValidator.validateRelationshipFromStore(repositoryName, guid, relationship, methodName);
return relationship;
}
catch (RelationshipNotKnownException error)
{
relationshipNotKnownException = error;
}
catch (RepositoryErrorException error)
{
repositoryErrorException = error;
}
catch (UserNotAuthorizedException error)
{
userNotAuthorizedException = error;
}
catch (Throwable error)
{
anotherException = error;
}
}
}
throwCapturedRepositoryErrorException(repositoryErrorException);
throwCapturedUserNotAuthorizedException(userNotAuthorizedException);
throwCapturedThrowableException(anotherException, methodName);
throwCapturedRelationshipNotKnownException(relationshipNotKnownException);
return null;
}
/**
* Return a historical version of a relationship.
*
* @param userId unique identifier for requesting user.
* @param guid String unique identifier for the relationship.
* @param asOfTime the time used to determine which version of the entity that is desired.
* @return Relationship structure.
* @throws InvalidParameterException the guid or date is null or the date is for a future time.
* @throws RepositoryErrorException there is a problem communicating with the metadata repository where
* the metadata collection is stored.
* @throws RelationshipNotKnownException the requested entity instance is not known in the metadata collection
* at the time requested.
* @throws FunctionNotSupportedException the repository does not support the asOfTime parameter.
* @throws UserNotAuthorizedException the userId is not permitted to perform this operation.
*/
public Relationship getRelationship(String userId,
String guid,
Date asOfTime) throws InvalidParameterException,
RepositoryErrorException,
RelationshipNotKnownException,
FunctionNotSupportedException,
UserNotAuthorizedException
{
final String methodName = "getRelationship";
final String guidParameterName = "guid";
final String asOfTimeParameter = "asOfTime";
/*
* Validate parameters
*/
this.validateRepositoryConnector(methodName);
parentConnector.validateRepositoryIsActive(methodName);
repositoryValidator.validateUserId(repositoryName, userId, methodName);
repositoryValidator.validateGUID(repositoryName, guidParameterName, guid, methodName);
repositoryValidator.validateAsOfTime(repositoryName, asOfTimeParameter, asOfTime, methodName);
/*
* The list of cohort connectors are retrieved for each request to ensure that any changes in
* the shape of the cohort are reflected immediately.
*/
List<OMRSRepositoryConnector> cohortConnectors = enterpriseParentConnector.getCohortConnectors(methodName);
/*
* Ready to process the request. Search results need to come from all members of the cohort.
* They need to be combined and then duplicates removed to create the final list of results.
* Some repositories may produce exceptions. These exceptions are saved and one selected to
* be returned if there are no results from any repository.
*/
RelationshipNotKnownException relationshipNotKnownException = null;
FunctionNotSupportedException functionNotSupportedException = null;
UserNotAuthorizedException userNotAuthorizedException = null;
RepositoryErrorException repositoryErrorException = null;
Throwable anotherException = null;
/*
* Loop through the metadata collections extracting the typedefs from each repository.
*/
for (OMRSRepositoryConnector cohortConnector : cohortConnectors)
{
if (cohortConnector != null)
{
OMRSMetadataCollection metadataCollection = cohortConnector.getMetadataCollection();
validateMetadataCollection(metadataCollection, methodName);
try
{
/*
* Issue the request and return if it succeeds
*/
Relationship relationship = this.getRelationship(userId, guid, asOfTime);
repositoryValidator.validateRelationshipFromStore(repositoryName, guid, relationship, methodName);
return relationship;
}
catch (RelationshipNotKnownException error)
{
relationshipNotKnownException = error;
}
catch (RepositoryErrorException error)
{
repositoryErrorException = error;
}
catch (UserNotAuthorizedException error)
{
userNotAuthorizedException = error;
}
catch (FunctionNotSupportedException error)
{
functionNotSupportedException = error;
}
catch (Throwable error)
{
anotherException = error;
}
}
}
throwCapturedRepositoryErrorException(repositoryErrorException);
throwCapturedUserNotAuthorizedException(userNotAuthorizedException);
throwCapturedThrowableException(anotherException, methodName);
throwCapturedRelationshipNotKnownException(relationshipNotKnownException);
throwCapturedFunctionNotSupportedException(functionNotSupportedException);
return null;
}
/**
* Return a list of relationships that match the requested properties by the matching criteria. The results
* can be broken into pages.
*
* @param userId unique identifier for requesting user.
* @param relationshipTypeGUID unique identifier (guid) for the new relationship's type.
* @param matchProperties list of properties used to narrow the search.
* @param matchCriteria Enum defining how the properties should be matched to the relationships in the repository.
* @param fromRelationshipElement the starting element number of the entities to return.
* This is used when retrieving elements
* beyond the first page of results. Zero means start from the first element.
* @param limitResultsByStatus By default, relationships in all statuses are returned. However, it is possible
* to specify a list of statuses (eg ACTIVE) to restrict the results to. Null means all
* status values.
* @param asOfTime Requests a historical query of the relationships for the entity. Null means return the
* present values.
* @param sequencingProperty String name of the property that is to be used to sequence the results.
* Null means do not sequence on a property name (see SequencingOrder).
* @param sequencingOrder Enum defining how the results should be ordered.
* @param pageSize the maximum number of result relationships that can be returned on this request. Zero means
* unrestricted return results size.
* @return a list of relationships. Null means no matching relationships.
* @throws InvalidParameterException one of the parameters is invalid or null.
* @throws TypeErrorException the type guid passed on the request is not known by the
* metadata collection.
* @throws RepositoryErrorException there is a problem communicating with the metadata repository where
* the metadata collection is stored.
* @throws PropertyErrorException the properties specified are not valid for any of the requested types of
* relationships.
* @throws PagingErrorException the paging/sequencing parameters are set up incorrectly.
* @throws FunctionNotSupportedException the repository does not support the asOfTime parameter.
* @throws UserNotAuthorizedException the userId is not permitted to perform this operation.
*/
public List<Relationship> findRelationshipsByProperty(String userId,
String relationshipTypeGUID,
InstanceProperties matchProperties,
MatchCriteria matchCriteria,
int fromRelationshipElement,
List<InstanceStatus> limitResultsByStatus,
Date asOfTime,
String sequencingProperty,
SequencingOrder sequencingOrder,
int pageSize) throws InvalidParameterException,
TypeErrorException,
RepositoryErrorException,
PropertyErrorException,
PagingErrorException,
FunctionNotSupportedException,
UserNotAuthorizedException
{
final String methodName = "findRelationshipsByProperty";
final String matchCriteriaParameterName = "matchCriteria";
final String matchPropertiesParameterName = "matchProperties";
final String asOfTimeParameter = "asOfTime";
final String guidParameter = "relationshipTypeGUID";
final String pageSizeParameter = "pageSize";
/*
* Validate parameters
*/
this.validateRepositoryConnector(methodName);
parentConnector.validateRepositoryIsActive(methodName);
repositoryValidator.validateUserId(repositoryName, userId, methodName);
repositoryValidator.validateOptionalTypeGUID(repositoryName, guidParameter, relationshipTypeGUID, methodName);
repositoryValidator.validateAsOfTime(repositoryName, asOfTimeParameter, asOfTime, methodName);
repositoryValidator.validatePageSize(repositoryName, pageSizeParameter, pageSize, methodName);
repositoryValidator.validateMatchCriteria(repositoryName,
matchCriteriaParameterName,
matchPropertiesParameterName,
matchCriteria,
matchProperties,
methodName);
/*
* Perform operation
*
* The list of cohort connectors are retrieved for each request to ensure that any changes in
* the shape of the cohort are reflected immediately.
*/
List<OMRSRepositoryConnector> cohortConnectors = enterpriseParentConnector.getCohortConnectors(methodName);
/*
* Ready to process the request. Search results need to come from all members of the cohort.
* They need to be combined and then duplicates removed to create the final list of results.
* Some repositories may produce exceptions. These exceptions are saved and one selected to
* be returned if there are no results from any repository.
*/
Map<String, Relationship> combinedResults = new HashMap<>();
InvalidParameterException invalidParameterException = null;
FunctionNotSupportedException functionNotSupportedException = null;
PropertyErrorException propertyErrorException = null;
TypeErrorException typeErrorException = null;
UserNotAuthorizedException userNotAuthorizedException = null;
RepositoryErrorException repositoryErrorException = null;
Throwable anotherException = null;
/*
* Loop through the metadata collections extracting the typedefs from each repository.
*/
for (OMRSRepositoryConnector cohortConnector : cohortConnectors)
{
if (cohortConnector != null)
{
OMRSMetadataCollection metadataCollection = cohortConnector.getMetadataCollection();
validateMetadataCollection(metadataCollection, methodName);
try
{
/*
* Issue the request
*/
List<Relationship> results = metadataCollection.findRelationshipsByProperty(userId,
relationshipTypeGUID,
matchProperties,
matchCriteria,
fromRelationshipElement,
limitResultsByStatus,
asOfTime,
sequencingProperty,
sequencingOrder,
pageSize);
/*
* Step through the list of returned TypeDefs and remove duplicates.
*/
combinedResults = this.addUniqueRelationships(combinedResults,
results,
cohortConnector.getServerName(),
cohortConnector.getMetadataCollectionId(),
methodName);
}
catch (InvalidParameterException error)
{
invalidParameterException = error;
}
catch (FunctionNotSupportedException error)
{
functionNotSupportedException = error;
}
catch (PropertyErrorException error)
{
propertyErrorException = error;
}
catch (TypeErrorException error)
{
typeErrorException = error;
}
catch (RepositoryErrorException error)
{
repositoryErrorException = error;
}
catch (UserNotAuthorizedException error)
{
userNotAuthorizedException = error;
}
catch (Throwable error)
{
anotherException = error;
}
}
}
if (combinedResults.isEmpty())
{
throwCapturedRepositoryErrorException(repositoryErrorException);
throwCapturedUserNotAuthorizedException(userNotAuthorizedException);
throwCapturedThrowableException(anotherException, methodName);
throwCapturedPropertyErrorException(propertyErrorException);
throwCapturedInvalidParameterException(invalidParameterException);
throwCapturedFunctionNotSupportedException(functionNotSupportedException);
throwCapturedTypeErrorException(typeErrorException);
return null;
}
return validatedRelationshipResults(repositoryName,
combinedResults,
sequencingProperty,
sequencingOrder,
pageSize,
methodName);
}
/**
* Return a list of relationships whose string based property values match the search criteria. The
* search criteria may include regex style wild cards.
*
* @param userId unique identifier for requesting user.
* @param relationshipTypeGUID GUID of the type of entity to search for. Null means all types will
* be searched (could be slow so not recommended).
* @param searchCriteria String expression contained in any of the property values within the entities
* of the supplied type.
* @param fromRelationshipElement Element number of the results to skip to when building the results list
* to return. Zero means begin at the start of the results. This is used
* to retrieve the results over a number of pages.
* @param limitResultsByStatus By default, relationships in all statuses are returned. However, it is possible
* to specify a list of statuses (eg ACTIVE) to restrict the results to. Null means all
* status values.
* @param asOfTime Requests a historical query of the relationships for the entity. Null means return the
* present values.
* @param sequencingProperty String name of the property that is to be used to sequence the results.
* Null means do not sequence on a property name (see SequencingOrder).
* @param sequencingOrder Enum defining how the results should be ordered.
* @param pageSize the maximum number of result relationships that can be returned on this request. Zero means
* unrestricted return results size.
* @return a list of relationships. Null means no matching relationships.
* @throws InvalidParameterException one of the parameters is invalid or null.
* @throws TypeErrorException the type guid passed on the request is not known by the
* metadata collection.
* @throws RepositoryErrorException there is a problem communicating with the metadata repository where
* the metadata collection is stored.
* @throws PropertyErrorException there is a problem with one of the other parameters.
* @throws PagingErrorException the paging/sequencing parameters are set up incorrectly.
* @throws FunctionNotSupportedException the repository does not support the asOfTime parameter.
* @throws UserNotAuthorizedException the userId is not permitted to perform this operation.
*/
public List<Relationship> findRelationshipsByPropertyValue(String userId,
String relationshipTypeGUID,
String searchCriteria,
int fromRelationshipElement,
List<InstanceStatus> limitResultsByStatus,
Date asOfTime,
String sequencingProperty,
SequencingOrder sequencingOrder,
int pageSize) throws InvalidParameterException,
TypeErrorException,
RepositoryErrorException,
PropertyErrorException,
PagingErrorException,
FunctionNotSupportedException,
UserNotAuthorizedException
{
final String methodName = "findRelationshipsByPropertyValue";
final String asOfTimeParameter = "asOfTime";
final String guidParameter = "relationshipTypeGUID";
final String pageSizeParameter = "pageSize";
/*
* Validate parameters
*/
this.validateRepositoryConnector(methodName);
parentConnector.validateRepositoryIsActive(methodName);
repositoryValidator.validateUserId(repositoryName, userId, methodName);
repositoryValidator.validateAsOfTime(repositoryName, asOfTimeParameter, asOfTime, methodName);
repositoryValidator.validateOptionalTypeGUID(repositoryName, guidParameter, relationshipTypeGUID, methodName);
repositoryValidator.validatePageSize(repositoryName, pageSizeParameter, pageSize, methodName);
/*
* Perform operation
*
* The list of cohort connectors are retrieved for each request to ensure that any changes in
* the shape of the cohort are reflected immediately.
*/
List<OMRSRepositoryConnector> cohortConnectors = enterpriseParentConnector.getCohortConnectors(methodName);
/*
* Ready to process the request. Search results need to come from all members of the cohort.
* They need to be combined and then duplicates removed to create the final list of results.
* Some repositories may produce exceptions. These exceptions are saved and one selected to
* be returned if there are no results from any repository.
*/
Map<String, Relationship> combinedResults = new HashMap<>();
InvalidParameterException invalidParameterException = null;
FunctionNotSupportedException functionNotSupportedException = null;
PropertyErrorException propertyErrorException = null;
TypeErrorException typeErrorException = null;
UserNotAuthorizedException userNotAuthorizedException = null;
RepositoryErrorException repositoryErrorException = null;
Throwable anotherException = null;
/*
* Loop through the metadata collections extracting the typedefs from each repository.
*/
for (OMRSRepositoryConnector cohortConnector : cohortConnectors)
{
if (cohortConnector != null)
{
OMRSMetadataCollection metadataCollection = cohortConnector.getMetadataCollection();
validateMetadataCollection(metadataCollection, methodName);
try
{
/*
* Issue the request
*/
List<Relationship> results = metadataCollection.findRelationshipsByPropertyValue(userId,
relationshipTypeGUID,
searchCriteria,
fromRelationshipElement,
limitResultsByStatus,
asOfTime,
sequencingProperty,
sequencingOrder,
pageSize);
/*
* Step through the list of returned TypeDefs and remove duplicates.
*/
combinedResults = this.addUniqueRelationships(combinedResults,
results,
cohortConnector.getServerName(),
cohortConnector.getMetadataCollectionId(),
methodName);
}
catch (InvalidParameterException error)
{
invalidParameterException = error;
}
catch (FunctionNotSupportedException error)
{
functionNotSupportedException = error;
}
catch (PropertyErrorException error)
{
propertyErrorException = error;
}
catch (TypeErrorException error)
{
typeErrorException = error;
}
catch (RepositoryErrorException error)
{
repositoryErrorException = error;
}
catch (UserNotAuthorizedException error)
{
userNotAuthorizedException = error;
}
catch (Throwable error)
{
anotherException = error;
}
}
}
if (combinedResults.isEmpty())
{
throwCapturedRepositoryErrorException(repositoryErrorException);
throwCapturedUserNotAuthorizedException(userNotAuthorizedException);
throwCapturedThrowableException(anotherException, methodName);
throwCapturedTypeErrorException(typeErrorException);
throwCapturedPropertyErrorException(propertyErrorException);
throwCapturedInvalidParameterException(invalidParameterException);
throwCapturedFunctionNotSupportedException(functionNotSupportedException);
return null;
}
return validatedRelationshipResults(repositoryName,
combinedResults,
sequencingProperty,
sequencingOrder,
pageSize,
methodName);
}
/**
* Return all of the relationships and intermediate entities that connect the startEntity with the endEntity.
*
* @param userId unique identifier for requesting user.
* @param startEntityGUID The entity that is used to anchor the query.
* @param endEntityGUID the other entity that defines the scope of the query.
* @param limitResultsByStatus By default, relationships in all statuses are returned. However, it is possible
* to specify a list of statuses (eg ACTIVE) to restrict the results to. Null means all
* status values.
* @param asOfTime Requests a historical query of the relationships for the entity. Null means return the
* present values.
* @return InstanceGraph the sub-graph that represents the returned linked entities and their relationships.
* @throws InvalidParameterException one of the parameters is invalid or null.
* @throws RepositoryErrorException there is a problem communicating with the metadata repository where
* the metadata collection is stored.
* @throws EntityNotKnownException the entity identified by either the startEntityGUID or the endEntityGUID
* is not found in the metadata collection.
* @throws PropertyErrorException there is a problem with one of the other parameters.
* @throws FunctionNotSupportedException the repository does not support the asOfTime parameter.
* @throws UserNotAuthorizedException the userId is not permitted to perform this operation.
*/
public InstanceGraph getLinkingEntities(String userId,
String startEntityGUID,
String endEntityGUID,
List<InstanceStatus> limitResultsByStatus,
Date asOfTime) throws InvalidParameterException,
RepositoryErrorException,
EntityNotKnownException,
PropertyErrorException,
FunctionNotSupportedException,
UserNotAuthorizedException
{
final String methodName = "getLinkingEntities";
final String startEntityGUIDParameterName = "startEntityGUID";
final String endEntityGUIDParameterName = "entityGUID";
final String asOfTimeParameter = "asOfTime";
/*
* Validate parameters
*/
this.validateRepositoryConnector(methodName);
parentConnector.validateRepositoryIsActive(methodName);
repositoryValidator.validateUserId(repositoryName, userId, methodName);
repositoryValidator.validateGUID(repositoryName, startEntityGUIDParameterName, startEntityGUID, methodName);
repositoryValidator.validateGUID(repositoryName, endEntityGUIDParameterName, endEntityGUID, methodName);
repositoryValidator.validateAsOfTime(repositoryName, asOfTimeParameter, asOfTime, methodName);
/*
* The list of cohort connectors are retrieved for each request to ensure that any changes in
* the shape of the cohort are reflected immediately.
*/
List<OMRSRepositoryConnector> cohortConnectors = enterpriseParentConnector.getCohortConnectors(methodName);
/*
* Ready to process the request. Search results need to come from all members of the cohort.
* They need to be combined and then duplicates removed to create the final list of results.
* Some repositories may produce exceptions. These exceptions are saved and one selected to
* be returned if there are no results from any repository.
*/
Map<String, EntityDetail> combinedEntityResults = new HashMap<>();
Map<String, Relationship> combinedRelationshipResults = new HashMap<>();
EntityNotKnownException entityNotKnownException = null;
FunctionNotSupportedException functionNotSupportedException = null;
PropertyErrorException propertyErrorException = null;
UserNotAuthorizedException userNotAuthorizedException = null;
RepositoryErrorException repositoryErrorException = null;
Throwable anotherException = null;
/*
* Loop through the metadata collections extracting the typedefs from each repository.
*/
for (OMRSRepositoryConnector cohortConnector : cohortConnectors)
{
if (cohortConnector != null)
{
OMRSMetadataCollection metadataCollection = cohortConnector.getMetadataCollection();
validateMetadataCollection(metadataCollection, methodName);
try
{
/*
* Issue the request
*/
InstanceGraph results = metadataCollection.getLinkingEntities(userId,
startEntityGUID,
endEntityGUID,
limitResultsByStatus,
asOfTime);
/*
* Step through the list of returned TypeDefs and consolidate.
*/
if (results != null)
{
combinedRelationshipResults = this.addUniqueRelationships(combinedRelationshipResults,
results.getRelationships(),
cohortConnector.getServerName(),
cohortConnector.getMetadataCollectionId(),
methodName);
combinedEntityResults = this.addUniqueEntities(combinedEntityResults,
results.getEntities(),
cohortConnector.getServerName(),
cohortConnector.getMetadataCollectionId(),
methodName);
}
}
catch (RepositoryErrorException error)
{
repositoryErrorException = error;
}
catch (PropertyErrorException error)
{
propertyErrorException = error;
}
catch (EntityNotKnownException error)
{
entityNotKnownException = error;
}
catch (FunctionNotSupportedException error)
{
functionNotSupportedException = error;
}
catch (UserNotAuthorizedException error)
{
userNotAuthorizedException = error;
}
catch (Throwable error)
{
anotherException = error;
}
}
}
return validatedInstanceGraphResults(repositoryName,
combinedEntityResults,
combinedRelationshipResults,
userNotAuthorizedException,
propertyErrorException,
functionNotSupportedException,
entityNotKnownException,
repositoryErrorException,
anotherException,
methodName);
}
/**
* Return the entities and relationships that radiate out from the supplied entity GUID.
* The results are scoped both the instance type guids and the level.
*
* @param userId unique identifier for requesting user.
* @param entityGUID the starting point of the query.
* @param entityTypeGUIDs list of entity types to include in the query results. Null means include
* all entities found, irrespective of their type.
* @param relationshipTypeGUIDs list of relationship types to include in the query results. Null means include
* all relationships found, irrespective of their type.
* @param limitResultsByStatus By default, relationships in all statuses are returned. However, it is possible
* to specify a list of statuses (eg ACTIVE) to restrict the results to. Null means all
* status values.
* @param limitResultsByClassification List of classifications that must be present on all returned entities.
* @param asOfTime Requests a historical query of the relationships for the entity. Null means return the
* present values.
* @param level the number of the relationships out from the starting entity that the query will traverse to
* gather results.
* @return InstanceGraph the sub-graph that represents the returned linked entities and their relationships.
* @throws InvalidParameterException one of the parameters is invalid or null.
* @throws TypeErrorException one or more of the type guids passed on the request is not known by the
* metadata collection.
* @throws RepositoryErrorException there is a problem communicating with the metadata repository where
* the metadata collection is stored.
* @throws EntityNotKnownException the entity identified by the entityGUID is not found in the metadata collection.
* @throws PropertyErrorException there is a problem with one of the other parameters.
* @throws FunctionNotSupportedException the repository does not support the asOfTime parameter.
* @throws UserNotAuthorizedException the userId is not permitted to perform this operation.
*/
public InstanceGraph getEntityNeighborhood(String userId,
String entityGUID,
List<String> entityTypeGUIDs,
List<String> relationshipTypeGUIDs,
List<InstanceStatus> limitResultsByStatus,
List<String> limitResultsByClassification,
Date asOfTime,
int level) throws InvalidParameterException,
TypeErrorException,
RepositoryErrorException,
EntityNotKnownException,
PropertyErrorException,
FunctionNotSupportedException,
UserNotAuthorizedException
{
final String methodName = "getEntityNeighborhood";
final String entityGUIDParameterName = "entityGUID";
final String entityTypeGUIDParameterName = "entityTypeGUIDs";
final String relationshipTypeGUIDParameterName = "relationshipTypeGUIDs";
final String limitedResultsByClassificationParameterName = "limitResultsByClassification";
final String asOfTimeParameter = "asOfTime";
/*
* Validate parameters
*/
this.validateRepositoryConnector(methodName);
parentConnector.validateRepositoryIsActive(methodName);
repositoryValidator.validateUserId(repositoryName, userId, methodName);
repositoryValidator.validateGUID(repositoryName, entityGUIDParameterName, entityGUID, methodName);
repositoryValidator.validateAsOfTime(repositoryName, asOfTimeParameter, asOfTime, methodName);
if (entityTypeGUIDs != null)
{
for (String guid : entityTypeGUIDs)
{
repositoryValidator.validateTypeGUID(repositoryName, entityTypeGUIDParameterName, guid, methodName);
}
}
if (relationshipTypeGUIDs != null)
{
for (String guid : relationshipTypeGUIDs)
{
repositoryValidator.validateTypeGUID(repositoryName, relationshipTypeGUIDParameterName, guid, methodName);
}
}
if (limitResultsByClassification != null)
{
for (String classificationName : limitResultsByClassification)
{
repositoryValidator.validateClassificationName(repositoryName,
limitedResultsByClassificationParameterName,
classificationName,
methodName);
}
}
/*
* The list of cohort connectors are retrieved for each request to ensure that any changes in
* the shape of the cohort are reflected immediately.
*/
List<OMRSRepositoryConnector> cohortConnectors = enterpriseParentConnector.getCohortConnectors(methodName);
/*
* Ready to process the request. Search results need to come from all members of the cohort.
* They need to be combined and then duplicates removed to create the final list of results.
* Some repositories may produce exceptions. These exceptions are saved and one selected to
* be returned if there are no results from any repository.
*/
Map<String, EntityDetail> combinedEntityResults = new HashMap<>();
Map<String, Relationship> combinedRelationshipResults = new HashMap<>();
EntityNotKnownException entityNotKnownException = null;
FunctionNotSupportedException functionNotSupportedException = null;
PropertyErrorException propertyErrorException = null;
UserNotAuthorizedException userNotAuthorizedException = null;
RepositoryErrorException repositoryErrorException = null;
Throwable anotherException = null;
/*
* Loop through the metadata collections extracting the typedefs from each repository.
*/
for (OMRSRepositoryConnector cohortConnector : cohortConnectors)
{
if (cohortConnector != null)
{
OMRSMetadataCollection metadataCollection = cohortConnector.getMetadataCollection();
validateMetadataCollection(metadataCollection, methodName);
try
{
/*
* Issue the request
*/
InstanceGraph results = metadataCollection.getEntityNeighborhood(userId,
entityGUID,
entityTypeGUIDs,
relationshipTypeGUIDs,
limitResultsByStatus,
limitResultsByClassification,
asOfTime,
level);
/*
* Step through the list of returned TypeDefs and consolidate.
*/
if (results != null)
{
combinedRelationshipResults = this.addUniqueRelationships(combinedRelationshipResults,
results.getRelationships(),
cohortConnector.getServerName(),
cohortConnector.getMetadataCollectionId(),
methodName);
combinedEntityResults = this.addUniqueEntities(combinedEntityResults,
results.getEntities(),
cohortConnector.getServerName(),
cohortConnector.getMetadataCollectionId(),
methodName);
}
}
catch (RepositoryErrorException error)
{
repositoryErrorException = error;
}
catch (PropertyErrorException error)
{
propertyErrorException = error;
}
catch (EntityNotKnownException error)
{
entityNotKnownException = error;
}
catch (FunctionNotSupportedException error)
{
functionNotSupportedException = error;
}
catch (UserNotAuthorizedException error)
{
userNotAuthorizedException = error;
}
catch (Throwable error)
{
anotherException = error;
}
}
}
return validatedInstanceGraphResults(repositoryName,
combinedEntityResults,
combinedRelationshipResults,
userNotAuthorizedException,
propertyErrorException,
functionNotSupportedException,
entityNotKnownException,
repositoryErrorException,
anotherException,
methodName);
}
/**
* Return the list of entities that are of the types listed in instanceTypes and are connected, either directly or
* indirectly to the entity identified by startEntityGUID.
*
* @param userId unique identifier for requesting user.
* @param startEntityGUID unique identifier of the starting entity
* @param instanceTypes list of types to search for. Null means any type.
* @param fromEntityElement starting element for results list. Used in paging. Zero means first element.
* @param limitResultsByStatus By default, relationships in all statuses are returned. However, it is possible
* to specify a list of statuses (eg ACTIVE) to restrict the results to. Null means all
* status values.
* @param limitResultsByClassification List of classifications that must be present on all returned entities.
* @param asOfTime Requests a historical query of the relationships for the entity. Null means return the
* present values.
* @param sequencingProperty String name of the property that is to be used to sequence the results.
* Null means do not sequence on a property name (see SequencingOrder).
* @param sequencingOrder Enum defining how the results should be ordered.
* @param pageSize the maximum number of result entities that can be returned on this request. Zero means
* unrestricted return results size.
* @return list of entities either directly or indirectly connected to the start entity
* @throws InvalidParameterException one of the parameters is invalid or null.
* @throws TypeErrorException one or more of the type guids passed on the request is not known by the
* metadata collection.
* @throws RepositoryErrorException there is a problem communicating with the metadata repository where
* the metadata collection is stored.
* @throws EntityNotKnownException the entity identified by the startEntityGUID
* is not found in the metadata collection.
* @throws PropertyErrorException the sequencing property specified is not valid for any of the requested types of
* entity.
* @throws PagingErrorException the paging/sequencing parameters are set up incorrectly.
* @throws FunctionNotSupportedException the repository does not support the asOfTime parameter.
* @throws UserNotAuthorizedException the userId is not permitted to perform this operation.
*/
public List<EntityDetail> getRelatedEntities(String userId,
String startEntityGUID,
List<String> instanceTypes,
int fromEntityElement,
List<InstanceStatus> limitResultsByStatus,
List<String> limitResultsByClassification,
Date asOfTime,
String sequencingProperty,
SequencingOrder sequencingOrder,
int pageSize) throws InvalidParameterException,
TypeErrorException,
RepositoryErrorException,
EntityNotKnownException,
PropertyErrorException,
PagingErrorException,
FunctionNotSupportedException,
UserNotAuthorizedException
{
final String methodName = "getRelatedEntities";
final String entityGUIDParameterName = "startEntityGUID";
final String typeGUIDParameterName = "instanceTypes";
final String asOfTimeParameter = "asOfTime";
final String pageSizeParameter = "pageSize";
/*
* Validate parameters
*/
this.validateRepositoryConnector(methodName);
parentConnector.validateRepositoryIsActive(methodName);
repositoryValidator.validateUserId(repositoryName, userId, methodName);
repositoryValidator.validateGUID(repositoryName, entityGUIDParameterName, startEntityGUID, methodName);
repositoryValidator.validateAsOfTime(repositoryName, asOfTimeParameter, asOfTime, methodName);
repositoryValidator.validatePageSize(repositoryName, pageSizeParameter, pageSize, methodName);
if (instanceTypes != null)
{
for (String guid : instanceTypes)
{
repositoryValidator.validateTypeGUID(repositoryName, typeGUIDParameterName, guid, methodName);
}
}
/*
* Perform operation
*
* The list of cohort connectors are retrieved for each request to ensure that any changes in
* the shape of the cohort are reflected immediately.
*/
List<OMRSRepositoryConnector> cohortConnectors = enterpriseParentConnector.getCohortConnectors(methodName);
/*
* Ready to process the request. Search results need to come from all members of the cohort.
* They need to be combined and then duplicates removed to create the final list of results.
* Some repositories may produce exceptions. These exceptions are saved and one selected to
* be returned if there are no results from any repository.
*/
Map<String, EntityDetail> combinedResults = new HashMap<>();
InvalidParameterException invalidParameterException = null;
EntityNotKnownException entityNotKnownException = null;
FunctionNotSupportedException functionNotSupportedException = null;
TypeErrorException typeErrorException = null;
PropertyErrorException propertyErrorException = null;
UserNotAuthorizedException userNotAuthorizedException = null;
RepositoryErrorException repositoryErrorException = null;
Throwable anotherException = null;
/*
* Loop through the metadata collections extracting the typedefs from each repository.
*/
for (OMRSRepositoryConnector cohortConnector : cohortConnectors)
{
if (cohortConnector != null)
{
OMRSMetadataCollection metadataCollection = cohortConnector.getMetadataCollection();
validateMetadataCollection(metadataCollection, methodName);
try
{
/*
* Issue the request
*/
List<EntityDetail> results = metadataCollection.getRelatedEntities(userId,
startEntityGUID,
instanceTypes,
fromEntityElement,
limitResultsByStatus,
limitResultsByClassification,
asOfTime,
sequencingProperty,
sequencingOrder,
pageSize);
/*
* Step through the list of returned TypeDefs and remove duplicates.
*/
combinedResults = this.addUniqueEntities(combinedResults,
results,
cohortConnector.getServerName(),
cohortConnector.getMetadataCollectionId(),
methodName);
}
catch (InvalidParameterException error)
{
invalidParameterException = error;
}
catch (EntityNotKnownException error)
{
entityNotKnownException = error;
}
catch (FunctionNotSupportedException error)
{
functionNotSupportedException = error;
}
catch (TypeErrorException error)
{
typeErrorException = error;
}
catch (PropertyErrorException error)
{
propertyErrorException = error;
}
catch (RepositoryErrorException error)
{
repositoryErrorException = error;
}
catch (UserNotAuthorizedException error)
{
userNotAuthorizedException = error;
}
catch (Throwable error)
{
anotherException = error;
}
}
}
if (combinedResults.isEmpty())
{
throwCapturedRepositoryErrorException(repositoryErrorException);
throwCapturedUserNotAuthorizedException(userNotAuthorizedException);
throwCapturedThrowableException(anotherException, methodName);
throwCapturedTypeErrorException(typeErrorException);
throwCapturedPropertyErrorException(propertyErrorException);
throwCapturedInvalidParameterException(invalidParameterException);
throwCapturedFunctionNotSupportedException(functionNotSupportedException);
throwCapturedEntityNotKnownException(entityNotKnownException);
return null;
}
return validatedEntityListResults(repositoryName,
combinedResults,
sequencingProperty,
sequencingOrder,
pageSize,
methodName);
}
/* ======================================================
* Group 4: Maintaining entity and relationship instances
*/
/**
* Create a new entity and put it in the requested state. The new entity is returned.
*
* @param userId unique identifier for requesting user.
* @param entityTypeGUID unique identifier (guid) for the new entity's type.
* @param initialProperties initial list of properties for the new entity null means no properties.
* @param initialClassifications initial list of classifications for the new entity null means no classifications.
* @param initialStatus initial status typically DRAFT, PREPARED or ACTIVE.
* @return EntityDetail showing the new header plus the requested properties and classifications. The entity will
* not have any relationships at this stage.
* @throws InvalidParameterException one of the parameters is invalid or null.
* @throws RepositoryErrorException there is a problem communicating with the metadata repository where
* the metadata collection is stored.
* @throws TypeErrorException the requested type is not known, or not supported in the metadata repository
* hosting the metadata collection.
* @throws PropertyErrorException one or more of the requested properties are not defined, or have different
* characteristics in the TypeDef for this entity's type.
* @throws ClassificationErrorException one or more of the requested classifications are either not known or
* not defined for this entity type.
* @throws StatusNotSupportedException the metadata repository hosting the metadata collection does not support
* the requested status.
* @throws UserNotAuthorizedException the userId is not permitted to perform this operation.
*/
public EntityDetail addEntity(String userId,
String entityTypeGUID,
InstanceProperties initialProperties,
List<Classification> initialClassifications,
InstanceStatus initialStatus) throws InvalidParameterException,
RepositoryErrorException,
TypeErrorException,
PropertyErrorException,
ClassificationErrorException,
StatusNotSupportedException,
UserNotAuthorizedException
{
final String methodName = "addEntity";
final String entityGUIDParameterName = "entityTypeGUID";
final String propertiesParameterName = "initialProperties";
final String classificationsParameterName = "initialClassifications";
final String initialStatusParameterName = "initialStatus";
/*
* Validate parameters
*/
this.validateRepositoryConnector(methodName);
parentConnector.validateRepositoryIsActive(methodName);
repositoryValidator.validateUserId(repositoryName, userId, methodName);
repositoryValidator.validateTypeGUID(repositoryName, entityGUIDParameterName, entityTypeGUID, methodName);
TypeDef typeDef = repositoryHelper.getTypeDef(repositoryName, entityGUIDParameterName, entityTypeGUID, methodName);
repositoryValidator.validateTypeDefForInstance(repositoryName, entityGUIDParameterName, typeDef, methodName);
repositoryValidator.validateClassificationList(repositoryName,
classificationsParameterName,
initialClassifications,
typeDef.getName(),
methodName);
repositoryValidator.validatePropertiesForType(repositoryName,
propertiesParameterName,
typeDef,
initialProperties,
methodName);
repositoryValidator.validateInstanceStatus(repositoryName,
initialStatusParameterName,
initialStatus,
typeDef,
methodName);
/*
* Validation complete, ok to create new instance
*
* The list of cohort connectors are retrieved for each request to ensure that any changes in
* the shape of the cohort are reflected immediately.
*/
List<OMRSRepositoryConnector> cohortConnectors = enterpriseParentConnector.getCohortConnectors(methodName);
/*
* Ready to process the request. Create requests occur in the first repository that accepts the call.
* Some repositories may produce exceptions. These exceptions are saved and will be returned if
* there are no positive results from any repository.
*/
InvalidParameterException invalidParameterException = null;
TypeErrorException typeErrorException = null;
PropertyErrorException propertyErrorException = null;
ClassificationErrorException classificationErrorException = null;
StatusNotSupportedException statusNotSupportedException = null;
UserNotAuthorizedException userNotAuthorizedException = null;
RepositoryErrorException repositoryErrorException = null;
Throwable anotherException = null;
/*
* Loop through the metadata collections extracting the typedefs from each repository.
*/
for (OMRSRepositoryConnector cohortConnector : cohortConnectors)
{
if (cohortConnector != null)
{
OMRSMetadataCollection metadataCollection = cohortConnector.getMetadataCollection();
validateMetadataCollection(metadataCollection, methodName);
try
{
/*
* Issue the request and return if it succeeds
*/
return metadataCollection.addEntity(userId,
entityTypeGUID,
initialProperties,
initialClassifications,
initialStatus);
}
catch (InvalidParameterException error)
{
invalidParameterException = error;
}
catch (ClassificationErrorException error)
{
classificationErrorException = error;
}
catch (TypeErrorException error)
{
typeErrorException = error;
}
catch (StatusNotSupportedException error)
{
statusNotSupportedException = error;
}
catch (PropertyErrorException error)
{
propertyErrorException = error;
}
catch (RepositoryErrorException error)
{
repositoryErrorException = error;
}
catch (UserNotAuthorizedException error)
{
userNotAuthorizedException = error;
}
catch (Throwable error)
{
anotherException = error;
}
}
}
throwCapturedRepositoryErrorException(repositoryErrorException);
throwCapturedUserNotAuthorizedException(userNotAuthorizedException);
throwCapturedThrowableException(anotherException, methodName);
throwCapturedTypeErrorException(typeErrorException);
throwCapturedClassificationErrorException(classificationErrorException);
throwCapturedPropertyErrorException(propertyErrorException);
throwCapturedStatusNotSupportedException(statusNotSupportedException);
throwCapturedInvalidParameterException(invalidParameterException);
return null;
}
/**
* Create an entity proxy in the metadata collection. This is used to store relationships that span metadata
* repositories.
*
* @param userId unique identifier for requesting user.
* @param entityProxy details of entity to add.
* @throws FunctionNotSupportedException the repository does not support entity proxies as first class elements.
*/
public void addEntityProxy(String userId,
EntityProxy entityProxy) throws FunctionNotSupportedException
{
final String methodName = "addEntityProxy";
throwNotEnterpriseFunction(methodName);
}
/**
* Update the status for a specific entity.
*
* @param userId unique identifier for requesting user.
* @param entityGUID unique identifier (guid) for the requested entity.
* @param newStatus new InstanceStatus for the entity.
* @return EntityDetail showing the current entity header, properties and classifications.
* @throws InvalidParameterException one of the parameters is invalid or null.
* @throws RepositoryErrorException there is a problem communicating with the metadata repository where
* the metadata collection is stored.
* @throws EntityNotKnownException the entity identified by the guid is not found in the metadata collection.
* @throws StatusNotSupportedException the metadata repository hosting the metadata collection does not support
* the requested status.
* @throws UserNotAuthorizedException the userId is not permitted to perform this operation.
*/
public EntityDetail updateEntityStatus(String userId,
String entityGUID,
InstanceStatus newStatus) throws InvalidParameterException,
RepositoryErrorException,
EntityNotKnownException,
StatusNotSupportedException,
UserNotAuthorizedException
{
final String methodName = "updateEntityStatus";
final String entityGUIDParameterName = "entityGUID";
/*
* Validate parameters
*/
this.validateRepositoryConnector(methodName);
parentConnector.validateRepositoryIsActive(methodName);
repositoryValidator.validateUserId(repositoryName, userId, methodName);
repositoryValidator.validateGUID(repositoryName, entityGUIDParameterName, entityGUID, methodName);
/*
* Locate entity
*/
EntitySummary entity = this.getEntitySummary(userId, entityGUID);
repositoryValidator.validateEntityFromStore(repositoryName, entityGUID, entity, methodName);
/*
* Validation complete, ok to make changes
*/
OMRSRepositoryConnector homeRepositoryConnector = enterpriseParentConnector.getHomeConnector(entity, methodName);
if (homeRepositoryConnector == null)
{
OMRSErrorCode errorCode = OMRSErrorCode.NO_HOME_FOR_INSTANCE;
String errorMessage = errorCode.getErrorMessageId()
+ errorCode.getFormattedErrorMessage(methodName, entityGUID, entity.getMetadataCollectionId());
throw new RepositoryErrorException(errorCode.getHTTPErrorCode(),
this.getClass().getName(),
methodName,
errorMessage,
errorCode.getSystemAction(),
errorCode.getUserAction());
}
return homeRepositoryConnector.getMetadataCollection().updateEntityStatus(userId, entityGUID, newStatus);
}
/**
* Update selected properties in an entity.
*
* @param userId unique identifier for requesting user.
* @param entityGUID String unique identifier (guid) for the entity.
* @param properties a list of properties to change.
* @return EntityDetail showing the resulting entity header, properties and classifications.
* @throws InvalidParameterException one of the parameters is invalid or null.
* @throws RepositoryErrorException there is a problem communicating with the metadata repository where
* the metadata collection is stored.
* @throws EntityNotKnownException the entity identified by the guid is not found in the metadata collection
* @throws PropertyErrorException one or more of the requested properties are not defined, or have different
* characteristics in the TypeDef for this entity's type
* @throws UserNotAuthorizedException the userId is not permitted to perform this operation.
*/
public EntityDetail updateEntityProperties(String userId,
String entityGUID,
InstanceProperties properties) throws InvalidParameterException,
RepositoryErrorException,
EntityNotKnownException,
PropertyErrorException,
UserNotAuthorizedException
{
final String methodName = "updateEntityProperties";
final String entityGUIDParameterName = "entityGUID";
/*
* Validate parameters
*/
this.validateRepositoryConnector(methodName);
parentConnector.validateRepositoryIsActive(methodName);
repositoryValidator.validateUserId(repositoryName, userId, methodName);
repositoryValidator.validateGUID(repositoryName, entityGUIDParameterName, entityGUID, methodName);
/*
* Locate entity
*/
EntitySummary entity = this.getEntitySummary(userId, entityGUID);
repositoryValidator.validateEntityFromStore(repositoryName, entityGUID, entity, methodName);
/*
* Validation complete, ok to make changes
*/
OMRSRepositoryConnector homeRepositoryConnector = enterpriseParentConnector.getHomeConnector(entity, methodName);
if (homeRepositoryConnector == null)
{
OMRSErrorCode errorCode = OMRSErrorCode.NO_HOME_FOR_INSTANCE;
String errorMessage = errorCode.getErrorMessageId() + errorCode.getFormattedErrorMessage(methodName,
entityGUID,
entity.getMetadataCollectionId());
throw new RepositoryErrorException(errorCode.getHTTPErrorCode(),
this.getClass().getName(),
methodName,
errorMessage,
errorCode.getSystemAction(),
errorCode.getUserAction());
}
return homeRepositoryConnector.getMetadataCollection().updateEntityProperties(userId, entityGUID, properties);
}
/**
* Undo the last update to an entity and return the previous content.
*
* @param userId unique identifier for requesting user.
* @param entityGUID String unique identifier (guid) for the entity.
* @return EntityDetail showing the resulting entity header, properties and classifications.
* @throws InvalidParameterException the guid is null.
* @throws RepositoryErrorException there is a problem communicating with the metadata repository where
* the metadata collection is stored.
* @throws EntityNotKnownException the entity identified by the guid is not found in the metadata collection.
* @throws FunctionNotSupportedException the repository does not support undo.
* @throws UserNotAuthorizedException the userId is not permitted to perform this operation.
*/
public EntityDetail undoEntityUpdate(String userId,
String entityGUID) throws InvalidParameterException,
RepositoryErrorException,
EntityNotKnownException,
FunctionNotSupportedException,
UserNotAuthorizedException
{
final String methodName = "undoEntityUpdate";
final String entityGUIDParameterName = "entityGUID";
/*
* Validate parameters
*/
this.validateRepositoryConnector(methodName);
parentConnector.validateRepositoryIsActive(methodName);
repositoryValidator.validateUserId(repositoryName, userId, methodName);
repositoryValidator.validateGUID(repositoryName, entityGUIDParameterName, entityGUID, methodName);
/*
* Locate entity
*/
EntitySummary entity = this.getEntitySummary(userId, entityGUID);
repositoryValidator.validateEntityFromStore(repositoryName, entityGUID, entity, methodName);
/*
* Validation complete, ok to make changes
*/
OMRSRepositoryConnector homeRepositoryConnector = enterpriseParentConnector.getHomeConnector(entity, methodName);
if (homeRepositoryConnector == null)
{
OMRSErrorCode errorCode = OMRSErrorCode.NO_HOME_FOR_INSTANCE;
String errorMessage = errorCode.getErrorMessageId() + errorCode.getFormattedErrorMessage(methodName,
entityGUID,
entity.getMetadataCollectionId());
throw new RepositoryErrorException(errorCode.getHTTPErrorCode(),
this.getClass().getName(),
methodName,
errorMessage,
errorCode.getSystemAction(),
errorCode.getUserAction());
}
return homeRepositoryConnector.getMetadataCollection().undoEntityUpdate(userId, entityGUID);
}
/**
* Delete an entity. The entity is soft deleted. This means it is still in the graph but it is no longer returned
* on queries. All relationships to the entity are also soft-deleted and will no longer be usable.
* To completely eliminate the entity from the graph requires a call to the purgeEntity() method after the delete call.
* The restoreEntity() method will switch an entity back to Active status to restore the entity to normal use.
*
* @param userId unique identifier for requesting user.
* @param typeDefGUID unique identifier of the type of the entity to delete.
* @param typeDefName unique name of the type of the entity to delete.
* @param obsoleteEntityGUID String unique identifier (guid) for the entity
* @throws InvalidParameterException one of the parameters is invalid or null.
* @throws RepositoryErrorException there is a problem communicating with the metadata repository where
* the metadata collection is stored.
* @throws EntityNotKnownException the entity identified by the guid is not found in the metadata collection.
* @throws FunctionNotSupportedException the metadata repository hosting the metadata collection does not support
* soft-deletes (use purgeEntity() to remove the entity permanently).
* @throws UserNotAuthorizedException the userId is not permitted to perform this operation.
*/
public EntityDetail deleteEntity(String userId,
String typeDefGUID,
String typeDefName,
String obsoleteEntityGUID) throws InvalidParameterException,
RepositoryErrorException,
EntityNotKnownException,
FunctionNotSupportedException,
UserNotAuthorizedException
{
final String methodName = "deleteEntity";
final String typeDefGUIDParameterName = "typeDefGUID";
final String typeDefNameParameterName = "typeDefName";
final String entityGUIDParameterName = "obsoleteEntityGUID";
/*
* Validate parameters
*/
this.validateRepositoryConnector(methodName);
parentConnector.validateRepositoryIsActive(methodName);
repositoryValidator.validateUserId(repositoryName, userId, methodName);
repositoryValidator.validateTypeDefIds(repositoryName,
typeDefGUIDParameterName,
typeDefNameParameterName,
typeDefGUID,
typeDefName,
methodName);
repositoryValidator.validateGUID(repositoryName, entityGUIDParameterName, obsoleteEntityGUID, methodName);
/*
* Locate entity
*/
EntitySummary entity = this.getEntitySummary(userId, obsoleteEntityGUID);
repositoryValidator.validateEntityFromStore(repositoryName, obsoleteEntityGUID, entity, methodName);
/*
* Validation complete, ok to make changes
*/
OMRSRepositoryConnector homeRepositoryConnector = enterpriseParentConnector.getHomeConnector(entity, methodName);
if (homeRepositoryConnector == null)
{
OMRSErrorCode errorCode = OMRSErrorCode.NO_HOME_FOR_INSTANCE;
String errorMessage = errorCode.getErrorMessageId() + errorCode.getFormattedErrorMessage(methodName,
obsoleteEntityGUID,
entity.getMetadataCollectionId());
throw new RepositoryErrorException(errorCode.getHTTPErrorCode(),
this.getClass().getName(),
methodName,
errorMessage,
errorCode.getSystemAction(),
errorCode.getUserAction());
}
return homeRepositoryConnector.getMetadataCollection().deleteEntity(userId, typeDefGUID, typeDefName, obsoleteEntityGUID);
}
/**
* Permanently removes a deleted entity from the metadata collection. This request can not be undone.
*
* @param userId unique identifier for requesting user.
* @param typeDefGUID unique identifier of the type of the entity to purge.
* @param typeDefName unique name of the type of the entity to purge.
* @param deletedEntityGUID String unique identifier (guid) for the entity.
* @throws InvalidParameterException one of the parameters is invalid or null.
* @throws RepositoryErrorException there is a problem communicating with the metadata repository where
* the metadata collection is stored.
* @throws EntityNotKnownException the entity identified by the guid is not found in the metadata collection
* @throws EntityNotDeletedException the entity is not in DELETED status and so can not be purged
* @throws UserNotAuthorizedException the userId is not permitted to perform this operation.
*/
public void purgeEntity(String userId,
String typeDefGUID,
String typeDefName,
String deletedEntityGUID) throws InvalidParameterException,
RepositoryErrorException,
EntityNotKnownException,
EntityNotDeletedException,
UserNotAuthorizedException
{
final String methodName = "purgeEntity";
final String typeDefGUIDParameterName = "typeDefGUID";
final String typeDefNameParameterName = "typeDefName";
final String entityGUIDParameterName = "deletedEntityGUID";
/*
* Validate parameters
*/
this.validateRepositoryConnector(methodName);
parentConnector.validateRepositoryIsActive(methodName);
repositoryValidator.validateUserId(repositoryName, userId, methodName);
repositoryValidator.validateTypeDefIds(repositoryName,
typeDefGUIDParameterName,
typeDefNameParameterName,
typeDefGUID,
typeDefName,
methodName);
repositoryValidator.validateGUID(repositoryName, entityGUIDParameterName, deletedEntityGUID, methodName);
/*
* Validation complete, ok to purge the instance
*
* The list of cohort connectors are retrieved for each request to ensure that any changes in
* the shape of the cohort are reflected immediately.
*/
List<OMRSRepositoryConnector> cohortConnectors = enterpriseParentConnector.getCohortConnectors(methodName);
/*
* Ready to process the request. Purge requests occur in the first repository that accepts the call.
* Some repositories may produce exceptions. These exceptions are saved and will be returned if
* there are no positive results from any repository.
*/
InvalidParameterException invalidParameterException = null;
EntityNotKnownException entityNotKnownException = null;
EntityNotDeletedException entityNotDeletedException = null;
UserNotAuthorizedException userNotAuthorizedException = null;
RepositoryErrorException repositoryErrorException = null;
Throwable anotherException = null;
/*
* Loop through the metadata collections extracting the typedefs from each repository.
*/
for (OMRSRepositoryConnector cohortConnector : cohortConnectors)
{
if (cohortConnector != null)
{
OMRSMetadataCollection metadataCollection = cohortConnector.getMetadataCollection();
validateMetadataCollection(metadataCollection, methodName);
try
{
/*
* Issue the request and return if it succeeds
*/
metadataCollection.purgeEntity(userId, typeDefGUID, typeDefName, deletedEntityGUID);
return;
}
catch (InvalidParameterException error)
{
invalidParameterException = error;
}
catch (EntityNotKnownException error)
{
entityNotKnownException = error;
}
catch (EntityNotDeletedException error)
{
entityNotDeletedException = error;
}
catch (RepositoryErrorException error)
{
repositoryErrorException = error;
}
catch (UserNotAuthorizedException error)
{
userNotAuthorizedException = error;
}
catch (Throwable error)
{
anotherException = error;
}
}
}
throwCapturedEntityNotDeletedException(entityNotDeletedException);
throwCapturedRepositoryErrorException(repositoryErrorException);
throwCapturedUserNotAuthorizedException(userNotAuthorizedException);
throwCapturedThrowableException(anotherException, methodName);
throwCapturedEntityNotKnownException(entityNotKnownException);
throwCapturedInvalidParameterException(invalidParameterException);
return;
}
/**
* Restore the requested entity to the state it was before it was deleted.
*
* @param userId unique identifier for requesting user.
* @param deletedEntityGUID String unique identifier (guid) for the entity.
* @return EntityDetail showing the restored entity header, properties and classifications.
* @throws InvalidParameterException the guid is null.
* @throws RepositoryErrorException there is a problem communicating with the metadata repository where
* the metadata collection is stored.
* @throws EntityNotKnownException the entity identified by the guid is not found in the metadata collection
* @throws EntityNotDeletedException the entity is currently not in DELETED status and so it can not be restored
* @throws FunctionNotSupportedException the repository does not support soft-deletes.
* @throws UserNotAuthorizedException the userId is not permitted to perform this operation.
*/
public EntityDetail restoreEntity(String userId,
String deletedEntityGUID) throws InvalidParameterException,
RepositoryErrorException,
EntityNotKnownException,
EntityNotDeletedException,
FunctionNotSupportedException,
UserNotAuthorizedException
{
final String methodName = "restoreEntity";
final String entityGUIDParameterName = "deletedEntityGUID";
/*
* Validate parameters
*/
this.validateRepositoryConnector(methodName);
parentConnector.validateRepositoryIsActive(methodName);
repositoryValidator.validateUserId(repositoryName, userId, methodName);
repositoryValidator.validateGUID(repositoryName, entityGUIDParameterName, deletedEntityGUID, methodName);
/*
* Locate entity
*/
EntityDetail entity = this.isEntityKnown(userId, deletedEntityGUID);
repositoryValidator.validateEntityFromStore(repositoryName, deletedEntityGUID, entity, methodName);
repositoryValidator.validateEntityIsDeleted(repositoryName, entity, methodName);
/*
* Validation is complete. It is ok to restore the entity.
*
* The list of cohort connectors are retrieved for each request to ensure that any changes in
* the shape of the cohort are reflected immediately.
*/
List<OMRSRepositoryConnector> cohortConnectors = enterpriseParentConnector.getCohortConnectors(methodName);
/*
* Ready to process the request. Restore requests occur in the first repository that accepts the call.
* Some repositories may produce exceptions. These exceptions are saved and will be returned if
* there are no positive results from any repository.
*/
InvalidParameterException invalidParameterException = null;
EntityNotKnownException entityNotKnownException = null;
EntityNotDeletedException entityNotDeletedException = null;
UserNotAuthorizedException userNotAuthorizedException = null;
RepositoryErrorException repositoryErrorException = null;
FunctionNotSupportedException functionNotSupportedException = null;
Throwable anotherException = null;
/*
* Loop through the metadata collections extracting the typedefs from each repository.
*/
for (OMRSRepositoryConnector cohortConnector : cohortConnectors)
{
if (cohortConnector != null)
{
OMRSMetadataCollection metadataCollection = cohortConnector.getMetadataCollection();
validateMetadataCollection(metadataCollection, methodName);
try
{
/*
* Issue the request and return if it succeeds
*/
return metadataCollection.restoreEntity(userId, deletedEntityGUID);
}
catch (InvalidParameterException error)
{
invalidParameterException = error;
}
catch (FunctionNotSupportedException error)
{
functionNotSupportedException = error;
}
catch (EntityNotKnownException error)
{
entityNotKnownException = error;
}
catch (EntityNotDeletedException error)
{
entityNotDeletedException = error;
}
catch (RepositoryErrorException error)
{
repositoryErrorException = error;
}
catch (UserNotAuthorizedException error)
{
userNotAuthorizedException = error;
}
catch (Throwable error)
{
anotherException = error;
}
}
}
throwCapturedEntityNotDeletedException(entityNotDeletedException);
throwCapturedRepositoryErrorException(repositoryErrorException);
throwCapturedUserNotAuthorizedException(userNotAuthorizedException);
throwCapturedThrowableException(anotherException, methodName);
throwCapturedEntityNotKnownException(entityNotKnownException);
throwCapturedInvalidParameterException(invalidParameterException);
throwCapturedFunctionNotSupportedException(functionNotSupportedException);
return null;
}
/**
* Add the requested classification to a specific entity.
*
* @param userId unique identifier for requesting user.
* @param entityGUID String unique identifier (guid) for the entity.
* @param classificationName String name for the classification.
* @param classificationProperties list of properties to set in the classification.
* @return EntityDetail showing the resulting entity header, properties and classifications.
* @throws InvalidParameterException one of the parameters is invalid or null.
* @throws RepositoryErrorException there is a problem communicating with the metadata repository where
* the metadata collection is stored.
* @throws EntityNotKnownException the entity identified by the guid is not found in the metadata collection
* @throws ClassificationErrorException the requested classification is either not known or not valid
* for the entity.
* @throws PropertyErrorException one or more of the requested properties are not defined, or have different
* characteristics in the TypeDef for this classification type
* @throws UserNotAuthorizedException the userId is not permitted to perform this operation.
*/
public EntityDetail classifyEntity(String userId,
String entityGUID,
String classificationName,
InstanceProperties classificationProperties) throws InvalidParameterException,
RepositoryErrorException,
EntityNotKnownException,
ClassificationErrorException,
PropertyErrorException,
UserNotAuthorizedException
{
final String methodName = "classifyEntity";
final String entityGUIDParameterName = "entityGUID";
/*
* Validate parameters
*/
this.validateRepositoryConnector(methodName);
parentConnector.validateRepositoryIsActive(methodName);
repositoryValidator.validateUserId(repositoryName, userId, methodName);
repositoryValidator.validateGUID(repositoryName, entityGUIDParameterName, entityGUID, methodName);
/*
* Locate entity
*/
EntitySummary entity = this.getEntitySummary(userId, entityGUID);
repositoryValidator.validateEntityFromStore(repositoryName, entityGUID, entity, methodName);
/*
* Validation complete, ok to make changes
*/
OMRSRepositoryConnector homeRepositoryConnector = enterpriseParentConnector.getHomeConnector(entity, methodName);
if (homeRepositoryConnector == null)
{
OMRSErrorCode errorCode = OMRSErrorCode.NO_HOME_FOR_INSTANCE;
String errorMessage = errorCode.getErrorMessageId() + errorCode.getFormattedErrorMessage(methodName,
entityGUID,
entity.getMetadataCollectionId());
throw new RepositoryErrorException(errorCode.getHTTPErrorCode(),
this.getClass().getName(),
methodName,
errorMessage,
errorCode.getSystemAction(),
errorCode.getUserAction());
}
return homeRepositoryConnector.getMetadataCollection().classifyEntity(userId,
entityGUID,
classificationName,
classificationProperties);
}
/**
* Remove a specific classification from an entity.
*
* @param userId unique identifier for requesting user.
* @param entityGUID String unique identifier (guid) for the entity.
* @param classificationName String name for the classification.
* @return EntityDetail showing the resulting entity header, properties and classifications.
* @throws InvalidParameterException one of the parameters is invalid or null.
* @throws RepositoryErrorException there is a problem communicating with the metadata repository where
* the metadata collection is stored.
* @throws EntityNotKnownException the entity identified by the guid is not found in the metadata collection
* @throws ClassificationErrorException the requested classification is not set on the entity.
* @throws UserNotAuthorizedException the userId is not permitted to perform this operation.
*/
public EntityDetail declassifyEntity(String userId,
String entityGUID,
String classificationName) throws InvalidParameterException,
RepositoryErrorException,
EntityNotKnownException,
ClassificationErrorException,
UserNotAuthorizedException
{
final String methodName = "declassifyEntity";
final String entityGUIDParameterName = "entityGUID";
final String classificationParameterName = "classificationName";
/*
* Validate parameters
*/
this.validateRepositoryConnector(methodName);
parentConnector.validateRepositoryIsActive(methodName);
repositoryValidator.validateUserId(repositoryName, userId, methodName);
repositoryValidator.validateGUID(repositoryName, entityGUIDParameterName, entityGUID, methodName);
repositoryValidator.validateClassificationName(repositoryName,
classificationParameterName,
classificationName,
methodName);
/*
* Locate entity
*/
EntitySummary entity = this.getEntitySummary(userId, entityGUID);
repositoryValidator.validateEntityFromStore(repositoryName, entityGUID, entity, methodName);
/*
* Validation complete, ok to make changes
*/
OMRSRepositoryConnector homeRepositoryConnector = enterpriseParentConnector.getHomeConnector(entity, methodName);
if (homeRepositoryConnector == null)
{
OMRSErrorCode errorCode = OMRSErrorCode.NO_HOME_FOR_INSTANCE;
String errorMessage = errorCode.getErrorMessageId() + errorCode.getFormattedErrorMessage(methodName,
entityGUID,
entity.getMetadataCollectionId());
throw new RepositoryErrorException(errorCode.getHTTPErrorCode(),
this.getClass().getName(),
methodName,
errorMessage,
errorCode.getSystemAction(),
errorCode.getUserAction());
}
return homeRepositoryConnector.getMetadataCollection().declassifyEntity(userId, entityGUID, classificationName);
}
/**
* Update one or more properties in one of an entity's classifications.
*
* @param userId unique identifier for requesting user.
* @param entityGUID String unique identifier (guid) for the entity.
* @param classificationName String name for the classification.
* @param properties list of properties for the classification.
* @return EntityDetail showing the resulting entity header, properties and classifications.
* @throws InvalidParameterException one of the parameters is invalid or null.
* @throws RepositoryErrorException there is a problem communicating with the metadata repository where
* the metadata collection is stored.
* @throws EntityNotKnownException the entity identified by the guid is not found in the metadata collection
* @throws ClassificationErrorException the requested classification is not attached to the classification.
* @throws PropertyErrorException one or more of the requested properties are not defined, or have different
* characteristics in the TypeDef for this classification type
* @throws UserNotAuthorizedException the userId is not permitted to perform this operation.
*/
public EntityDetail updateEntityClassification(String userId,
String entityGUID,
String classificationName,
InstanceProperties properties) throws InvalidParameterException,
RepositoryErrorException,
EntityNotKnownException,
ClassificationErrorException,
PropertyErrorException,
UserNotAuthorizedException
{
final String methodName = "updateEntityClassification";
final String entityGUIDParameterName = "entityGUID";
final String classificationParameterName = "classificationName";
/*
* Validate parameters
*/
this.validateRepositoryConnector(methodName);
parentConnector.validateRepositoryIsActive(methodName);
repositoryValidator.validateUserId(repositoryName, userId, methodName);
repositoryValidator.validateGUID(repositoryName, entityGUIDParameterName, entityGUID, methodName);
repositoryValidator.validateClassificationName(repositoryName, classificationParameterName, classificationName, methodName);
/*
* Locate entity
*/
EntitySummary entity = this.getEntitySummary(userId, entityGUID);
repositoryValidator.validateEntityFromStore(repositoryName, entityGUID, entity, methodName);
/*
* Validation complete, ok to make changes
*/
OMRSRepositoryConnector homeRepositoryConnector = enterpriseParentConnector.getHomeConnector(entity, methodName);
if (homeRepositoryConnector == null)
{
OMRSErrorCode errorCode = OMRSErrorCode.NO_HOME_FOR_INSTANCE;
String errorMessage = errorCode.getErrorMessageId() + errorCode.getFormattedErrorMessage(methodName,
entityGUID,
entity.getMetadataCollectionId());
throw new RepositoryErrorException(errorCode.getHTTPErrorCode(),
this.getClass().getName(),
methodName,
errorMessage,
errorCode.getSystemAction(),
errorCode.getUserAction());
}
return homeRepositoryConnector.getMetadataCollection().updateEntityClassification(userId,
entityGUID,
classificationName,
properties);
}
/**
* Add a new relationship between two entities to the metadata collection.
*
* @param userId unique identifier for requesting user.
* @param relationshipTypeGUID unique identifier (guid) for the new relationship's type.
* @param initialProperties initial list of properties for the new entity, null means no properties.
* @param entityOneGUID the unique identifier of one of the entities that the relationship is connecting together.
* @param entityTwoGUID the unique identifier of the other entity that the relationship is connecting together.
* @param initialStatus initial status. This is typically DRAFT, PREPARED or ACTIVE.
* @return Relationship structure with the new header, requested entities and properties.
* @throws InvalidParameterException one of the parameters is invalid or null.
* @throws RepositoryErrorException there is a problem communicating with the metadata repository where
* the metadata collection is stored.
* @throws TypeErrorException the requested type is not known, or not supported in the metadata repository
* hosting the metadata collection.
* @throws PropertyErrorException one or more of the requested properties are not defined, or have different
* characteristics in the TypeDef for this relationship's type.
* @throws EntityNotKnownException one of the requested entities is not known in the metadata collection.
* @throws StatusNotSupportedException the metadata repository hosting the metadata collection does not support
* the requested status.
* @throws UserNotAuthorizedException the userId is not permitted to perform this operation.
*/
public Relationship addRelationship(String userId,
String relationshipTypeGUID,
InstanceProperties initialProperties,
String entityOneGUID,
String entityTwoGUID,
InstanceStatus initialStatus) throws InvalidParameterException,
RepositoryErrorException,
TypeErrorException,
PropertyErrorException,
EntityNotKnownException,
StatusNotSupportedException,
UserNotAuthorizedException
{
final String methodName = "addRelationship";
final String guidParameterName = "relationshipTypeGUID";
final String propertiesParameterName = "initialProperties";
final String initialStatusParameterName = "initialStatus";
/*
* Validate parameters
*/
this.validateRepositoryConnector(methodName);
parentConnector.validateRepositoryIsActive(methodName);
repositoryValidator.validateUserId(repositoryName, userId, methodName);
repositoryValidator.validateTypeGUID(repositoryName, guidParameterName, relationshipTypeGUID, methodName);
TypeDef typeDef = repositoryHelper.getTypeDef(repositoryName, guidParameterName, relationshipTypeGUID, methodName);
repositoryValidator.validateTypeDefForInstance(repositoryName, guidParameterName, typeDef, methodName);
repositoryValidator.validatePropertiesForType(repositoryName,
propertiesParameterName,
typeDef,
initialProperties,
methodName);
repositoryValidator.validateInstanceStatus(repositoryName,
initialStatusParameterName,
initialStatus,
typeDef,
methodName);
/*
* Validation complete, ok to create new instance
*
* The list of cohort connectors are retrieved for each request to ensure that any changes in
* the shape of the cohort are reflected immediately.
*/
List<OMRSRepositoryConnector> cohortConnectors = enterpriseParentConnector.getCohortConnectors(methodName);
/*
* Ready to process the request. Create requests occur in the first repository that accepts the call.
* Some repositories may produce exceptions. These exceptions are saved and will be returned if
* there are no positive results from any repository.
*/
InvalidParameterException invalidParameterException = null;
EntityNotKnownException entityNotKnownException = null;
TypeErrorException typeErrorException = null;
PropertyErrorException propertyErrorException = null;
StatusNotSupportedException statusNotSupportedException = null;
UserNotAuthorizedException userNotAuthorizedException = null;
RepositoryErrorException repositoryErrorException = null;
Throwable anotherException = null;
/*
* Loop through the metadata collections extracting the typedefs from each repository.
*/
for (OMRSRepositoryConnector cohortConnector : cohortConnectors)
{
if (cohortConnector != null)
{
OMRSMetadataCollection metadataCollection = cohortConnector.getMetadataCollection();
validateMetadataCollection(metadataCollection, methodName);
try
{
/*
* Issue the request and return if it succeeds
*/
return metadataCollection.addRelationship(userId,
relationshipTypeGUID,
initialProperties,
entityOneGUID,
entityTwoGUID,
initialStatus);
}
catch (InvalidParameterException error)
{
invalidParameterException = error;
}
catch (EntityNotKnownException error)
{
entityNotKnownException = error;
}
catch (TypeErrorException error)
{
typeErrorException = error;
}
catch (StatusNotSupportedException error)
{
statusNotSupportedException = error;
}
catch (PropertyErrorException error)
{
propertyErrorException = error;
}
catch (RepositoryErrorException error)
{
repositoryErrorException = error;
}
catch (UserNotAuthorizedException error)
{
userNotAuthorizedException = error;
}
catch (Throwable error)
{
anotherException = error;
}
}
}
throwCapturedEntityNotKnownException(entityNotKnownException);
throwCapturedRepositoryErrorException(repositoryErrorException);
throwCapturedUserNotAuthorizedException(userNotAuthorizedException);
throwCapturedThrowableException(anotherException, methodName);
throwCapturedTypeErrorException(typeErrorException);
throwCapturedPropertyErrorException(propertyErrorException);
throwCapturedStatusNotSupportedException(statusNotSupportedException);
throwCapturedInvalidParameterException(invalidParameterException);
return null;
}
/**
* Update the status of a specific relationship.
*
* @param userId unique identifier for requesting user.
* @param relationshipGUID String unique identifier (guid) for the relationship.
* @param newStatus new InstanceStatus for the relationship.
* @return Resulting relationship structure with the new status set.
* @throws InvalidParameterException one of the parameters is invalid or null.
* @throws RepositoryErrorException there is a problem communicating with the metadata repository where
* the metadata collection is stored.
* @throws RelationshipNotKnownException the requested relationship is not known in the metadata collection.
* @throws StatusNotSupportedException the metadata repository hosting the metadata collection does not support
* the requested status.
* @throws UserNotAuthorizedException the userId is not permitted to perform this operation.
*/
public Relationship updateRelationshipStatus(String userId,
String relationshipGUID,
InstanceStatus newStatus) throws InvalidParameterException,
RepositoryErrorException,
RelationshipNotKnownException,
StatusNotSupportedException,
UserNotAuthorizedException
{
final String methodName = "updateRelationshipStatus";
final String guidParameterName = "relationshipGUID";
/*
* Validate parameters
*/
this.validateRepositoryConnector(methodName);
parentConnector.validateRepositoryIsActive(methodName);
repositoryValidator.validateUserId(repositoryName, userId, methodName);
repositoryValidator.validateGUID(repositoryName, guidParameterName, relationshipGUID, methodName);
/*
* Locate relationship
*/
Relationship relationship = this.getRelationship(userId, relationshipGUID);
repositoryValidator.validateInstanceType(repositoryName, relationship);
/*
* Validation complete, ok to make changes
*/
OMRSRepositoryConnector homeRepositoryConnector = enterpriseParentConnector.getHomeConnector(relationship, methodName);
if (homeRepositoryConnector == null)
{
OMRSErrorCode errorCode = OMRSErrorCode.NO_HOME_FOR_INSTANCE;
String errorMessage = errorCode.getErrorMessageId() + errorCode.getFormattedErrorMessage(methodName,
relationshipGUID,
relationship.getMetadataCollectionId());
throw new RepositoryErrorException(errorCode.getHTTPErrorCode(),
this.getClass().getName(),
methodName,
errorMessage,
errorCode.getSystemAction(),
errorCode.getUserAction());
}
return homeRepositoryConnector.getMetadataCollection().updateRelationshipStatus(userId, relationshipGUID, newStatus);
}
/**
* Update the properties of a specific relationship.
*
* @param userId unique identifier for requesting user.
* @param relationshipGUID String unique identifier (guid) for the relationship.
* @param properties list of the properties to update.
* @return Resulting relationship structure with the new properties set.
* @throws InvalidParameterException one of the parameters is invalid or null.
* @throws RepositoryErrorException there is a problem communicating with the metadata repository where
* the metadata collection is stored.
* @throws RelationshipNotKnownException the requested relationship is not known in the metadata collection.
* @throws PropertyErrorException one or more of the requested properties are not defined, or have different
* characteristics in the TypeDef for this relationship's type.
* @throws UserNotAuthorizedException the userId is not permitted to perform this operation.
*/
public Relationship updateRelationshipProperties(String userId,
String relationshipGUID,
InstanceProperties properties) throws InvalidParameterException,
RepositoryErrorException,
RelationshipNotKnownException,
PropertyErrorException,
UserNotAuthorizedException
{
final String methodName = "updateRelationshipProperties";
final String guidParameterName = "relationshipGUID";
/*
* Validate parameters
*/
this.validateRepositoryConnector(methodName);
parentConnector.validateRepositoryIsActive(methodName);
repositoryValidator.validateUserId(repositoryName, userId, methodName);
repositoryValidator.validateGUID(repositoryName, guidParameterName, relationshipGUID, methodName);
/*
* Locate relationship
*/
Relationship relationship = this.getRelationship(userId, relationshipGUID);
repositoryValidator.validateInstanceType(repositoryName, relationship);
/*
* Validation complete, ok to make changes
*/
OMRSRepositoryConnector homeRepositoryConnector = enterpriseParentConnector.getHomeConnector(relationship, methodName);
if (homeRepositoryConnector == null)
{
OMRSErrorCode errorCode = OMRSErrorCode.NO_HOME_FOR_INSTANCE;
String errorMessage = errorCode.getErrorMessageId() + errorCode.getFormattedErrorMessage(methodName,
relationshipGUID,
relationship.getMetadataCollectionId());
throw new RepositoryErrorException(errorCode.getHTTPErrorCode(),
this.getClass().getName(),
methodName,
errorMessage,
errorCode.getSystemAction(),
errorCode.getUserAction());
}
return homeRepositoryConnector.getMetadataCollection().updateRelationshipProperties(userId, relationshipGUID, properties);
}
/**
* Undo the latest change to a relationship (either a change of properties or status).
*
* @param userId unique identifier for requesting user.
* @param relationshipGUID String unique identifier (guid) for the relationship.
* @return Relationship structure with the new current header, requested entities and properties.
* @throws InvalidParameterException the guid is null.
* @throws RepositoryErrorException there is a problem communicating with the metadata repository where
* the metadata collection is stored.
* @throws RelationshipNotKnownException the requested relationship is not known in the metadata collection.
* @throws FunctionNotSupportedException the repository does not support undo.
* @throws UserNotAuthorizedException the userId is not permitted to perform this operation.
*/
public Relationship undoRelationshipUpdate(String userId,
String relationshipGUID) throws InvalidParameterException,
RepositoryErrorException,
RelationshipNotKnownException,
FunctionNotSupportedException,
UserNotAuthorizedException
{
final String methodName = "undoRelationshipUpdate";
final String guidParameterName = "relationshipGUID";
/*
* Validate parameters
*/
this.validateRepositoryConnector(methodName);
parentConnector.validateRepositoryIsActive(methodName);
repositoryValidator.validateUserId(repositoryName, userId, methodName);
repositoryValidator.validateGUID(repositoryName, guidParameterName, relationshipGUID, methodName);
/*
* Locate relationship
*/
Relationship relationship = this.getRelationship(userId, relationshipGUID);
repositoryValidator.validateInstanceType(repositoryName, relationship);
/*
* Validation complete, ok to make changes
*/
OMRSRepositoryConnector homeRepositoryConnector = enterpriseParentConnector.getHomeConnector(relationship, methodName);
if (homeRepositoryConnector == null)
{
OMRSErrorCode errorCode = OMRSErrorCode.NO_HOME_FOR_INSTANCE;
String errorMessage = errorCode.getErrorMessageId() + errorCode.getFormattedErrorMessage(methodName,
relationshipGUID,
relationship.getMetadataCollectionId());
throw new RepositoryErrorException(errorCode.getHTTPErrorCode(),
this.getClass().getName(),
methodName,
errorMessage,
errorCode.getSystemAction(),
errorCode.getUserAction());
}
return homeRepositoryConnector.getMetadataCollection().undoRelationshipUpdate(userId, relationshipGUID);
}
/**
* Delete a specific relationship. This is a soft-delete which means the relationship's status is updated to
* DELETED and it is no longer available for queries. To remove the relationship permanently from the
* metadata collection, use purgeRelationship().
*
* @param userId unique identifier for requesting user.
* @param typeDefGUID unique identifier of the type of the relationship to delete.
* @param typeDefName unique name of the type of the relationship to delete.
* @param obsoleteRelationshipGUID String unique identifier (guid) for the relationship.
* @return delete relationship
* @throws InvalidParameterException one of the parameters is null.
* @throws RepositoryErrorException there is a problem communicating with the metadata repository where
* the metadata collection is stored.
* @throws RelationshipNotKnownException the requested relationship is not known in the metadata collection.
* @throws FunctionNotSupportedException the metadata repository hosting the metadata collection does not support
* soft-deletes.
* @throws UserNotAuthorizedException the userId is not permitted to perform this operation.
*/
public Relationship deleteRelationship(String userId,
String typeDefGUID,
String typeDefName,
String obsoleteRelationshipGUID) throws InvalidParameterException,
RepositoryErrorException,
RelationshipNotKnownException,
FunctionNotSupportedException,
UserNotAuthorizedException
{
final String methodName = "deleteRelationship";
final String guidParameterName = "typeDefGUID";
final String nameParameterName = "typeDefName";
final String relationshipParameterName = "obsoleteRelationshipGUID";
/*
* Validate parameters
*/
this.validateRepositoryConnector(methodName);
parentConnector.validateRepositoryIsActive(methodName);
repositoryValidator.validateUserId(repositoryName, userId, methodName);
repositoryValidator.validateGUID(repositoryName, relationshipParameterName, obsoleteRelationshipGUID, methodName);
repositoryValidator.validateTypeDefIds(repositoryName,
guidParameterName,
nameParameterName,
typeDefGUID,
typeDefName,
methodName);
/*
* Locate relationship
*/
Relationship relationship = this.getRelationship(userId, obsoleteRelationshipGUID);
repositoryValidator.validateTypeForInstanceDelete(repositoryName,
typeDefGUID,
typeDefName,
relationship,
methodName);
/*
* Validation complete, ok to make changes
*/
OMRSRepositoryConnector homeRepositoryConnector = enterpriseParentConnector.getHomeConnector(relationship, methodName);
if (homeRepositoryConnector == null)
{
OMRSErrorCode errorCode = OMRSErrorCode.NO_HOME_FOR_INSTANCE;
String errorMessage = errorCode.getErrorMessageId() + errorCode.getFormattedErrorMessage(methodName,
obsoleteRelationshipGUID,
relationship.getMetadataCollectionId());
throw new RepositoryErrorException(errorCode.getHTTPErrorCode(),
this.getClass().getName(),
methodName,
errorMessage,
errorCode.getSystemAction(),
errorCode.getUserAction());
}
/*
* A delete is a soft-delete that updates the status to DELETED.
*/
return homeRepositoryConnector.getMetadataCollection().deleteRelationship(userId,
typeDefGUID,
typeDefName,
obsoleteRelationshipGUID);
}
/**
* Permanently delete the relationship from the repository. There is no means to undo this request.
*
* @param userId unique identifier for requesting user.
* @param typeDefGUID unique identifier of the type of the relationship to purge.
* @param typeDefName unique name of the type of the relationship to purge.
* @param deletedRelationshipGUID String unique identifier (guid) for the relationship.
* @throws InvalidParameterException one of the parameters is null.
* @throws RepositoryErrorException there is a problem communicating with the metadata repository where
* the metadata collection is stored.
* @throws RelationshipNotKnownException the requested relationship is not known in the metadata collection.
* @throws RelationshipNotDeletedException the requested relationship is not in DELETED status.
* @throws UserNotAuthorizedException the userId is not permitted to perform this operation.
*/
public void purgeRelationship(String userId,
String typeDefGUID,
String typeDefName,
String deletedRelationshipGUID) throws InvalidParameterException,
RepositoryErrorException,
RelationshipNotKnownException,
RelationshipNotDeletedException,
UserNotAuthorizedException
{
final String methodName = "purgeRelationship";
final String guidParameterName = "typeDefGUID";
final String nameParameterName = "typeDefName";
final String relationshipParameterName = "deletedRelationshipGUID";
/*
* Validate parameters
*/
this.validateRepositoryConnector(methodName);
parentConnector.validateRepositoryIsActive(methodName);
repositoryValidator.validateUserId(repositoryName, userId, methodName);
repositoryValidator.validateGUID(repositoryName, relationshipParameterName, deletedRelationshipGUID, methodName);
repositoryValidator.validateTypeDefIds(repositoryName,
guidParameterName,
nameParameterName,
typeDefGUID,
typeDefName,
methodName);
/*
* Locate relationship
*/
Relationship relationship = this.getRelationship(userId, deletedRelationshipGUID);
repositoryValidator.validateTypeForInstanceDelete(repositoryName,
typeDefGUID,
typeDefName,
relationship,
methodName);
repositoryValidator.validateRelationshipIsDeleted(repositoryName, relationship, methodName);
/*
* Validation is complete. It is ok to purge the relationship.
*
* The list of cohort connectors are retrieved for each request to ensure that any changes in
* the shape of the cohort are reflected immediately.
*/
List<OMRSRepositoryConnector> cohortConnectors = enterpriseParentConnector.getCohortConnectors(methodName);
/*
* Ready to process the request. Restore requests occur in the first repository that accepts the call.
* Some repositories may produce exceptions. These exceptions are saved and will be returned if
* there are no positive results from any repository.
*/
InvalidParameterException invalidParameterException = null;
RelationshipNotKnownException relationshipNotKnownException = null;
RelationshipNotDeletedException relationshipNotDeletedException = null;
UserNotAuthorizedException userNotAuthorizedException = null;
RepositoryErrorException repositoryErrorException = null;
Throwable anotherException = null;
/*
* Loop through the metadata collections extracting the typedefs from each repository.
*/
for (OMRSRepositoryConnector cohortConnector : cohortConnectors)
{
if (cohortConnector != null)
{
OMRSMetadataCollection metadataCollection = cohortConnector.getMetadataCollection();
validateMetadataCollection(metadataCollection, methodName);
try
{
/*
* Issue the request and return if it succeeds
*/
metadataCollection.purgeRelationship(userId, typeDefGUID, typeDefName, deletedRelationshipGUID);
return;
}
catch (InvalidParameterException error)
{
invalidParameterException = error;
}
catch (RelationshipNotKnownException error)
{
relationshipNotKnownException = error;
}
catch (RelationshipNotDeletedException error)
{
relationshipNotDeletedException = error;
}
catch (RepositoryErrorException error)
{
repositoryErrorException = error;
}
catch (UserNotAuthorizedException error)
{
userNotAuthorizedException = error;
}
catch (Throwable error)
{
anotherException = error;
}
}
}
throwCapturedRelationshipNotDeletedException(relationshipNotDeletedException);
throwCapturedRepositoryErrorException(repositoryErrorException);
throwCapturedUserNotAuthorizedException(userNotAuthorizedException);
throwCapturedThrowableException(anotherException, methodName);
throwCapturedRelationshipNotKnownException(relationshipNotKnownException);
throwCapturedInvalidParameterException(invalidParameterException);
return;
}
/**
* Restore a deleted relationship into the metadata collection. The new status will be ACTIVE and the
* restored details of the relationship are returned to the caller.
*
* @param userId unique identifier for requesting user.
* @param deletedRelationshipGUID String unique identifier (guid) for the relationship.
* @return Relationship structure with the restored header, requested entities and properties.
* @throws InvalidParameterException the guid is null.
* @throws RepositoryErrorException there is a problem communicating with the metadata repository where
* the metadata collection is stored.
* @throws RelationshipNotKnownException the requested relationship is not known in the metadata collection.
* @throws RelationshipNotDeletedException the requested relationship is not in DELETED status.
* @throws FunctionNotSupportedException the repository does not support soft-deletes.
* @throws UserNotAuthorizedException the userId is not permitted to perform this operation.
*/
public Relationship restoreRelationship(String userId,
String deletedRelationshipGUID) throws InvalidParameterException,
RepositoryErrorException,
RelationshipNotKnownException,
RelationshipNotDeletedException,
FunctionNotSupportedException,
UserNotAuthorizedException
{
final String methodName = "restoreRelationship";
final String guidParameterName = "deletedRelationshipGUID";
/*
* Validate parameters
*/
this.validateRepositoryConnector(methodName);
parentConnector.validateRepositoryIsActive(methodName);
repositoryValidator.validateUserId(repositoryName, userId, methodName);
repositoryValidator.validateGUID(repositoryName, guidParameterName, deletedRelationshipGUID, methodName);
/*
* Locate relationship
*/
Relationship relationship = this.getRelationship(userId, deletedRelationshipGUID);
repositoryValidator.validateRelationshipIsDeleted(repositoryName, relationship, methodName);
/*
* Validation is complete. It is ok to restore the relationship.
*
* The list of cohort connectors are retrieved for each request to ensure that any changes in
* the shape of the cohort are reflected immediately.
*/
List<OMRSRepositoryConnector> cohortConnectors = enterpriseParentConnector.getCohortConnectors(methodName);
/*
* Ready to process the request. Restore requests occur in the first repository that accepts the call.
* Some repositories may produce exceptions. These exceptions are saved and will be returned if
* there are no positive results from any repository.
*/
InvalidParameterException invalidParameterException = null;
RelationshipNotKnownException relationshipNotKnownException = null;
RelationshipNotDeletedException relationshipNotDeletedException = null;
UserNotAuthorizedException userNotAuthorizedException = null;
RepositoryErrorException repositoryErrorException = null;
FunctionNotSupportedException functionNotSupportedException = null;
Throwable anotherException = null;
/*
* Loop through the metadata collections extracting the typedefs from each repository.
*/
for (OMRSRepositoryConnector cohortConnector : cohortConnectors)
{
if (cohortConnector != null)
{
OMRSMetadataCollection metadataCollection = cohortConnector.getMetadataCollection();
validateMetadataCollection(metadataCollection, methodName);
try
{
/*
* Issue the request and return if it succeeds
*/
return metadataCollection.restoreRelationship(userId, deletedRelationshipGUID);
}
catch (InvalidParameterException error)
{
invalidParameterException = error;
}
catch (FunctionNotSupportedException error)
{
functionNotSupportedException = error;
}
catch (RelationshipNotKnownException error)
{
relationshipNotKnownException = error;
}
catch (RelationshipNotDeletedException error)
{
relationshipNotDeletedException = error;
}
catch (RepositoryErrorException error)
{
repositoryErrorException = error;
}
catch (UserNotAuthorizedException error)
{
userNotAuthorizedException = error;
}
catch (Throwable error)
{
anotherException = error;
}
}
}
throwCapturedRelationshipNotDeletedException(relationshipNotDeletedException);
throwCapturedRepositoryErrorException(repositoryErrorException);
throwCapturedUserNotAuthorizedException(userNotAuthorizedException);
throwCapturedThrowableException(anotherException, methodName);
throwCapturedRelationshipNotKnownException(relationshipNotKnownException);
throwCapturedInvalidParameterException(invalidParameterException);
throwCapturedFunctionNotSupportedException(functionNotSupportedException);
return null;
}
/* ======================================================================
* Group 5: Change the control information in entities and relationships
*/
/**
* Change the guid of an existing entity to a new value. This is used if two different
* entities are discovered to have the same guid. This is extremely unlikely but not impossible so
* the open metadata protocol has provision for this.
*
* @param userId unique identifier for requesting user.
* @param typeDefGUID the guid of the TypeDef for the entity used to verify the entity identity.
* @param typeDefName the name of the TypeDef for the entity used to verify the entity identity.
* @param entityGUID the existing identifier for the entity.
* @param newEntityGUID new unique identifier for the entity.
* @return entity new values for this entity, including the new guid.
* @throws FunctionNotSupportedException the repository does not support the re-identification of instances.
*/
public EntityDetail reIdentifyEntity(String userId,
String typeDefGUID,
String typeDefName,
String entityGUID,
String newEntityGUID) throws FunctionNotSupportedException
{
final String methodName = "reIdentifyEntity()";
throwNotEnterpriseFunction(methodName);
return null;
}
/**
* Change the type of an existing entity. Typically this action is taken to move an entity's
* type to either a super type (so the subtype can be deleted) or a new subtype (so additional properties can be
* added.) However, the type can be changed to any compatible type and the properties adjusted.
*
* @param userId unique identifier for requesting user.
* @param entityGUID the unique identifier for the entity to change.
* @param currentTypeDefSummary the current details of the TypeDef for the entity used to verify the entity identity
* @param newTypeDefSummary details of this entity's new TypeDef.
* @return entity new values for this entity, including the new type information.
* @throws FunctionNotSupportedException the repository does not support the re-typing of instances.
*/
public EntityDetail reTypeEntity(String userId,
String entityGUID,
TypeDefSummary currentTypeDefSummary,
TypeDefSummary newTypeDefSummary) throws FunctionNotSupportedException
{
final String methodName = "reTypeEntity()";
throwNotEnterpriseFunction(methodName);
return null;
}
/**
* Change the home of an existing entity. This action is taken for example, if the original home repository
* becomes permanently unavailable, or if the user community updating this entity move to working
* from a different repository in the open metadata repository cohort.
*
* @param userId unique identifier for requesting user.
* @param entityGUID the unique identifier for the entity to change.
* @param typeDefGUID the guid of the TypeDef for the entity used to verify the entity identity.
* @param typeDefName the name of the TypeDef for the entity used to verify the entity identity.
* @param homeMetadataCollectionId the existing identifier for this entity's home.
* @param newHomeMetadataCollectionId unique identifier for the new home metadata collection/repository.
* @return entity new values for this entity, including the new home information.
* @throws FunctionNotSupportedException the repository does not support the re-homing of instances.
*/
public EntityDetail reHomeEntity(String userId,
String entityGUID,
String typeDefGUID,
String typeDefName,
String homeMetadataCollectionId,
String newHomeMetadataCollectionId) throws FunctionNotSupportedException
{
final String methodName = "reHomeEntity()";
throwNotEnterpriseFunction(methodName);
return null;
}
/**
* Change the guid of an existing relationship. This is used if two different
* relationships are discovered to have the same guid. This is extremely unlikely but not impossible so
* the open metadata protocol has provision for this.
*
* @param userId unique identifier for requesting user.
* @param typeDefGUID the guid of the TypeDef for the relationship used to verify the relationship identity.
* @param typeDefName the name of the TypeDef for the relationship used to verify the relationship identity.
* @param relationshipGUID the existing identifier for the relationship.
* @param newRelationshipGUID the new unique identifier for the relationship.
* @return relationship new values for this relationship, including the new guid.
* @throws FunctionNotSupportedException the repository does not support the re-identification of instances.
*/
public Relationship reIdentifyRelationship(String userId,
String typeDefGUID,
String typeDefName,
String relationshipGUID,
String newRelationshipGUID) throws FunctionNotSupportedException
{
final String methodName = "reIdentifyRelationship()";
throwNotEnterpriseFunction(methodName);
return null;
}
/**
* Change the type of an existing relationship. Typically this action is taken to move a relationship's
* type to either a super type (so the subtype can be deleted) or a new subtype (so additional properties can be
* added.) However, the type can be changed to any compatible type.
*
* @param userId unique identifier for requesting user.
* @param relationshipGUID the unique identifier for the relationship.
* @param currentTypeDefSummary the details of the TypeDef for the relationship used to verify the relationship identity.
* @param newTypeDefSummary details of this relationship's new TypeDef.
* @return relationship new values for this relationship, including the new type information.
* @throws FunctionNotSupportedException the repository does not support the re-typing of instances.
*/
public Relationship reTypeRelationship(String userId,
String relationshipGUID,
TypeDefSummary currentTypeDefSummary,
TypeDefSummary newTypeDefSummary) throws FunctionNotSupportedException
{
final String methodName = "reTypeRelationship()";
throwNotEnterpriseFunction(methodName);
return null;
}
/**
* Change the home of an existing relationship. This action is taken for example, if the original home repository
* becomes permanently unavailable, or if the user community updating this relationship move to working
* from a different repository in the open metadata repository cohort.
*
* @param userId unique identifier for requesting user.
* @param relationshipGUID the unique identifier for the relationship.
* @param typeDefGUID the guid of the TypeDef for the relationship used to verify the relationship identity.
* @param typeDefName the name of the TypeDef for the relationship used to verify the relationship identity.
* @param homeMetadataCollectionId the existing identifier for this relationship's home.
* @param newHomeMetadataCollectionId unique identifier for the new home metadata collection/repository.
* @return relationship new values for this relationship, including the new home information.
* @throws FunctionNotSupportedException the repository does not support the re-homing of instances.
*/
public Relationship reHomeRelationship(String userId,
String relationshipGUID,
String typeDefGUID,
String typeDefName,
String homeMetadataCollectionId,
String newHomeMetadataCollectionId) throws FunctionNotSupportedException
{
final String methodName = "reHomeRelationship()";
throwNotEnterpriseFunction(methodName);
return null;
}
/* ======================================================================
* Group 6: Local house-keeping of reference metadata instances
* These methods are not supported by the EnterpriseOMRSRepositoryConnector
*/
/**
* Save the entity as a reference copy. The id of the home metadata collection is already set up in the
* entity.
*
* @param userId unique identifier for requesting server.
* @param entity details of the entity to save
* @throws FunctionNotSupportedException the repository does not support reference copies of instances.
*/
public void saveEntityReferenceCopy(String userId,
EntityDetail entity) throws FunctionNotSupportedException
{
final String methodName = "saveEntityReferenceCopy()";
throwNotEnterpriseFunction(methodName);
}
/**
* Remove a reference copy of the the entity from the local repository. This method can be used to
* remove reference copies from the local cohort, repositories that have left the cohort,
* or entities that have come from open metadata archives.
*
* @param userId unique identifier for requesting server.
* @param entityGUID the unique identifier for the entity.
* @param typeDefGUID the guid of the TypeDef for the relationship used to verify the relationship identity.
* @param typeDefName the name of the TypeDef for the relationship used to verify the relationship identity.
* @param homeMetadataCollectionId identifier of the metadata collection that is the home to this entity.
* @throws FunctionNotSupportedException the repository does not support reference copies of instances.
*/
public void purgeEntityReferenceCopy(String userId,
String entityGUID,
String typeDefGUID,
String typeDefName,
String homeMetadataCollectionId) throws FunctionNotSupportedException
{
final String methodName = "purgeEntityReferenceCopy()";
throwNotEnterpriseFunction(methodName);
}
/**
* The local repository has requested that the repository that hosts the home metadata collection for the
* specified entity sends out the details of this entity so the local repository can create a reference copy.
*
* @param userId unique identifier for requesting server.
* @param entityGUID unique identifier of requested entity
* @param typeDefGUID unique identifier of requested entity's TypeDef
* @param typeDefName unique name of requested entity's TypeDef
* @param homeMetadataCollectionId identifier of the metadata collection that is the home to this entity.
* @throws FunctionNotSupportedException the repository does not support reference copies of instances.
*/
public void refreshEntityReferenceCopy(String userId,
String entityGUID,
String typeDefGUID,
String typeDefName,
String homeMetadataCollectionId) throws FunctionNotSupportedException
{
final String methodName = "refreshEntityReferenceCopy()";
throwNotEnterpriseFunction(methodName);
}
/**
* Save the relationship as a reference copy. The id of the home metadata collection is already set up in the
* relationship.
*
* @param userId unique identifier for requesting server.
* @param relationship relationship to save
* @throws FunctionNotSupportedException the repository does not support reference copies of instances.
*/
public void saveRelationshipReferenceCopy(String userId,
Relationship relationship) throws FunctionNotSupportedException
{
final String methodName = "saveRelationshipReferenceCopy()";
throwNotEnterpriseFunction(methodName);
}
/**
* Remove the reference copy of the relationship from the local repository. This method can be used to
* remove reference copies from the local cohort, repositories that have left the cohort,
* or relationships that have come from open metadata archives.
*
* @param userId unique identifier for requesting server.
* @param relationshipGUID the unique identifier for the relationship.
* @param typeDefGUID the guid of the TypeDef for the relationship used to verify the relationship identity.
* @param typeDefName the name of the TypeDef for the relationship used to verify the relationship identity.
* @param homeMetadataCollectionId unique identifier for the home repository for this relationship.
* @throws FunctionNotSupportedException the repository does not support reference copies of instances.
*/
public void purgeRelationshipReferenceCopy(String userId,
String relationshipGUID,
String typeDefGUID,
String typeDefName,
String homeMetadataCollectionId) throws FunctionNotSupportedException
{
final String methodName = "purgeRelationshipReferenceCopy()";
throwNotEnterpriseFunction(methodName);
}
/**
* The local repository has requested that the repository that hosts the home metadata collection for the
* specified relationship sends out the details of this relationship so the local repository can create a
* reference copy.
*
* @param userId unique identifier for requesting user.
* @param relationshipGUID unique identifier of the relationship
* @param typeDefGUID the guid of the TypeDef for the relationship used to verify the relationship identity.
* @param typeDefName the name of the TypeDef for the relationship used to verify the relationship identity.
* @param homeMetadataCollectionId unique identifier for the home repository for this relationship.
* @throws FunctionNotSupportedException the repository does not support reference copies of instances.
*/
public void refreshRelationshipReferenceCopy(String userId,
String relationshipGUID,
String typeDefGUID,
String typeDefName,
String homeMetadataCollectionId) throws FunctionNotSupportedException
{
final String methodName = "refreshRelationshipReferenceCopy()";
throwNotEnterpriseFunction(methodName);
}
/*
* =================================================
* Private validation and processing methods
*/
/**
* Build a combined list of AttributeTypeDefs.
*
* @param accumulatedResults current accumulated AttributeTypeDefs
* @param newResults newly received AttributeTypeDefs
* @param serverName name of the server that provided the new AttributeTypeDefs
* @param metadataCollectionId unique identifier for metadata collection that provided the new AttributeTypeDefs
* @param methodName method name that returned the new AttributeTypeDefs
* @return combined results
*/
private Map<String, AttributeTypeDef> addUniqueAttributeTypeDefs(Map<String, AttributeTypeDef> accumulatedResults,
List<AttributeTypeDef> newResults,
String serverName,
String metadataCollectionId,
String methodName)
{
Map<String, AttributeTypeDef> combinedResults = new HashMap<>(accumulatedResults);
if (newResults != null)
{
for (AttributeTypeDef attributeTypeDef : newResults)
{
if (attributeTypeDef != null)
{
combinedResults = addUniqueAttributeTypeDef(combinedResults,
attributeTypeDef,
serverName,
metadataCollectionId,
methodName);
}
}
}
return combinedResults;
}
/**
* Build a combined list of AttributeTypeDefs.
*
* @param accumulatedResults current accumulated AttributeTypeDefs
* @param attributeTypeDef newly received AttributeTypeDef
* @param serverName name of the server that provided the new AttributeTypeDef
* @param metadataCollectionId unique identifier for metadata collection that provided the new AttributeTypeDef
* @param methodName method name that returned the new AttributeTypeDef
* @return combined results
*/
private Map<String, AttributeTypeDef> addUniqueAttributeTypeDef(Map<String, AttributeTypeDef> accumulatedResults,
AttributeTypeDef attributeTypeDef,
String serverName,
String metadataCollectionId,
String methodName)
{
Map<String, AttributeTypeDef> combinedResults = new HashMap<>(accumulatedResults);
if (attributeTypeDef != null)
{
AttributeTypeDef existingAttributeTypeDef = combinedResults.put(attributeTypeDef.getGUID(), attributeTypeDef);
// todo validate that existing attributeTypeDef and the new one are copies
}
return combinedResults;
}
/**
* Build a combined list of TypeDefs.
*
* @param accumulatedResults current accumulated TypeDefs
* @param returnedTypeDefs newly received TypeDefs
* @param serverName name of the server that provided the new TypeDefs
* @param metadataCollectionId unique identifier for metadata collection that provided the new TypeDefs
* @param methodName method name that returned the new TypeDefs
* @return combined results
*/
private Map<String, TypeDef> addUniqueTypeDefs(Map<String, TypeDef> accumulatedResults,
List<TypeDef> returnedTypeDefs,
String serverName,
String metadataCollectionId,
String methodName)
{
Map<String, TypeDef> combinedResults = new HashMap<>(accumulatedResults);
if (returnedTypeDefs != null)
{
for (TypeDef returnedTypeDef : returnedTypeDefs)
{
combinedResults = this.addUniqueTypeDef(combinedResults,
returnedTypeDef,
serverName,
metadataCollectionId,
methodName);
}
}
return combinedResults;
}
/**
* Build a combined list of TypeDefs.
*
* @param accumulatedResults current accumulated TypeDefs
* @param typeDef newly received TypeDef
* @param serverName name of the server that provided the new TypeDef
* @param metadataCollectionId unique identifier for metadata collection that provided the new TypeDef
* @param methodName method name that returned the new TypeDef
* @return combined results
*/
private Map<String, TypeDef> addUniqueTypeDef(Map<String, TypeDef> accumulatedResults,
TypeDef typeDef,
String serverName,
String metadataCollectionId,
String methodName)
{
Map<String, TypeDef> combinedResults = new HashMap<>(accumulatedResults);
if (typeDef != null)
{
TypeDef existingTypeDef = combinedResults.put(typeDef.getGUID(), typeDef);
// todo validate that existing typeDef and the new one are copies
}
return combinedResults;
}
/**
* Build a combined list of entities.
*
* @param accumulatedResults current accumulated entities
* @param results newly received list of entities
* @param serverName name of the server that provided the new entity
* @param metadataCollectionId unique identifier for metadata collection that provided the new entity
* @param methodName method name that returned the new entity
* @return combined results
*/
private Map<String, EntityDetail> addUniqueEntities(Map<String, EntityDetail> accumulatedResults,
List<EntityDetail> results,
String serverName,
String metadataCollectionId,
String methodName)
{
Map<String, EntityDetail> combinedResults = new HashMap<>(accumulatedResults);
if (results != null)
{
for (EntityDetail returnedEntity : results)
{
combinedResults = this.addUniqueEntity(combinedResults,
returnedEntity,
serverName,
metadataCollectionId,
methodName);
}
}
return combinedResults;
}
/**
* Build a combined list of entities.
*
* @param accumulatedResults current accumulated entities
* @param entity newly received entity
* @param serverName name of the server that provided the new entity
* @param metadataCollectionId unique identifier for metadata collection that provided the new entity
* @param methodName method name that returned the new entity
* @return combined results
*/
private Map<String, EntityDetail> addUniqueEntity(Map<String, EntityDetail> accumulatedResults,
EntityDetail entity,
String serverName,
String metadataCollectionId,
String methodName)
{
Map<String, EntityDetail> combinedResults = new HashMap<>(accumulatedResults);
if (entity != null)
{
EntityDetail existingEntity = combinedResults.put(entity.getGUID(), entity);
// todo validate that existing entity and the new one are copies
}
return combinedResults;
}
/**
* Build a combined list of relationships.
*
* @param accumulatedResults current accumulated relationships
* @param results newly received list of relationships
* @param serverName name of the server that provided the new relationship
* @param metadataCollectionId unique identifier for metadata collection that provided the new relationship
* @param methodName method name that returned the new relationship
* @return combined results
*/
private Map<String, Relationship> addUniqueRelationships(Map<String, Relationship> accumulatedResults,
List<Relationship> results,
String serverName,
String metadataCollectionId,
String methodName)
{
Map<String, Relationship> combinedResults = new HashMap<>(accumulatedResults);
if (results != null)
{
for (Relationship returnedRelationship : results)
{
combinedResults = this.addUniqueRelationship(combinedResults,
returnedRelationship,
serverName,
metadataCollectionId,
methodName);
}
}
return combinedResults;
}
/**
* Build a combined list of relationships.
*
* @param accumulatedResults current accumulated relationships
* @param relationship newly received relationship
* @param serverName name of the server that provided the new relationship
* @param metadataCollectionId unique identifier for metadata collection that provided the new relationship
* @param methodName method name that returned the new relationship
* @return combined results
*/
private Map<String, Relationship> addUniqueRelationship(Map<String, Relationship> accumulatedResults,
Relationship relationship, String serverName,
String metadataCollectionId,
String methodName)
{
Map<String, Relationship> combinedResults = new HashMap<>(accumulatedResults);
if (relationship != null)
{
Relationship existingRelationship = combinedResults.put(relationship.getGUID(), relationship);
// todo validate that existing relationship and the new one are copies
}
return combinedResults;
}
/**
* Verify that a cohort member's metadata collection is not null.
*
* @param cohortMetadataCollection metadata collection
* @param methodName name of method
* @throws RepositoryErrorException null metadata collection
*/
private void validateMetadataCollection(OMRSMetadataCollection cohortMetadataCollection,
String methodName) throws RepositoryErrorException
{
/*
* The cohort metadata collection should not be null. It is in a real mess if this fails.
*/
if (cohortMetadataCollection == null)
{
/*
* A problem in the set up of the metadata collection list. Repository connectors implemented
* with no metadata collection are tested for in the OMRSEnterpriseConnectorManager so something
* else has gone wrong.
*/
OMRSErrorCode errorCode = OMRSErrorCode.NULL_ENTERPRISE_METADATA_COLLECTION;
String errorMessage = errorCode.getErrorMessageId() + errorCode.getFormattedErrorMessage();
throw new RepositoryErrorException(errorCode.getHTTPErrorCode(),
this.getClass().getName(),
methodName,
errorMessage,
errorCode.getSystemAction(),
errorCode.getUserAction());
}
}
/**
* Indicates to the caller that the method called is not supported by the enterprise connector.
*
* @param methodName name of the method that was called
* @throws FunctionNotSupportedException resulting exception
*/
private void throwNotEnterpriseFunction(String methodName) throws FunctionNotSupportedException
{
OMRSErrorCode errorCode = OMRSErrorCode.ENTERPRISE_NOT_SUPPORTED;
String errorMessage = errorCode.getErrorMessageId() + errorCode.getFormattedErrorMessage(methodName);
throw new FunctionNotSupportedException(errorCode.getHTTPErrorCode(),
this.getClass().getName(),
methodName,
errorMessage,
errorCode.getSystemAction(),
errorCode.getUserAction());
}
/**
* Throw a TypeDefNotKnownException if it was returned by one of the calls to a cohort connector.
*
* @param exception captured exception
* @throws TypeDefNotKnownException the type definition is not known in any of the federated repositories
*/
private void throwCapturedTypeDefNotKnownException(TypeDefNotKnownException exception) throws TypeDefNotKnownException
{
if (exception != null)
{
throw exception;
}
}
/**
* Throw a InvalidParameterException if it was returned by one of the calls to a cohort connector.
*
* @param exception captured exception
* @throws InvalidParameterException one of the parameters is invalid
*/
private void throwCapturedInvalidParameterException(InvalidParameterException exception) throws InvalidParameterException
{
if (exception != null)
{
throw exception;
}
}
/**
* Throw a TypeErrorException if it was returned by one of the calls to a cohort connector.
*
* @param exception captured exception
* @throws TypeErrorException the type definition of the instance is not known in any of the federated repositories
*/
private void throwCapturedTypeErrorException(TypeErrorException exception) throws TypeErrorException
{
if (exception != null)
{
throw exception;
}
}
/**
* Throw a StatusNotSupportedException if it was returned by one of the calls to a cohort connector.
*
* @param exception captured exception
* @throws StatusNotSupportedException the status is not known in any of the federated repositories
*/
private void throwCapturedStatusNotSupportedException(StatusNotSupportedException exception) throws StatusNotSupportedException
{
if (exception != null)
{
throw exception;
}
}
/**
* Throw a ClassificationErrorException if it was returned by one of the calls to a cohort connector.
*
* @param exception captured exception
* @throws ClassificationErrorException the classification is not known
*/
private void throwCapturedClassificationErrorException(ClassificationErrorException exception) throws ClassificationErrorException
{
if (exception != null)
{
throw exception;
}
}
/**
* Throw a PropertyErrorException if it was returned by one of the calls to a cohort connector.
*
* @param exception captured exception
* @throws PropertyErrorException the properties are not valid for the call
*/
private void throwCapturedPropertyErrorException(PropertyErrorException exception) throws PropertyErrorException
{
if (exception != null)
{
throw exception;
}
}
/**
* Throw a EntityNotKnownException if it was returned by one of the calls to a cohort connector.
*
* @param exception captured exception
* @throws EntityNotKnownException the entity is not known in any of the federated repositories
*/
private void throwCapturedEntityNotKnownException(EntityNotKnownException exception) throws EntityNotKnownException
{
if (exception != null)
{
throw exception;
}
}
/**
* Throw a EntityNotDeletedException if it was returned by one of the calls to a cohort connector.
*
* @param exception captured exception
* @throws EntityNotDeletedException the entity is not in deleted status
*/
private void throwCapturedEntityNotDeletedException(EntityNotDeletedException exception) throws EntityNotDeletedException
{
if (exception != null)
{
throw exception;
}
}
/**
* Throw a EntityProxyOnlyException if it was returned by one of the calls to a cohort connector.
*
* @param exception captured exception
* @throws EntityProxyOnlyException only entity proxies have been found in the available federated repositories
*/
private void throwCapturedEntityProxyOnlyException(EntityProxyOnlyException exception) throws EntityProxyOnlyException
{
if (exception != null)
{
throw exception;
}
// todo add audit log call as this exception may indicate one of the repositories in the
// todo may be in trouble.
}
/**
* Throw a RelationshipNotKnownException if it was returned by one of the calls to a cohort connector.
*
* @param exception captured exception
* @throws RelationshipNotKnownException the relationship is not known in any of the federated repositories
*/
private void throwCapturedRelationshipNotKnownException(RelationshipNotKnownException exception) throws RelationshipNotKnownException
{
if (exception != null)
{
throw exception;
}
}
/**
* Throw a RelationshipNotDeletedException if it was returned by one of the calls to a cohort connector.
*
* @param exception captured exception
* @throws RelationshipNotDeletedException the relationship is not in deleted status
*/
private void throwCapturedRelationshipNotDeletedException(RelationshipNotDeletedException exception) throws RelationshipNotDeletedException
{
if (exception != null)
{
throw exception;
}
}
/**
* Throw a UserNotAuthorizedException if it was returned by one of the calls to a cohort connector.
*
* @param exception captured exception
* @throws TypeDefNotSupportedException the type definition is not supported in any of the federated repositories
*/
private void throwCapturedTypeDefNotSupportedException(TypeDefNotSupportedException exception) throws TypeDefNotSupportedException
{
if (exception != null)
{
throw exception;
}
}
/**
* Throw a FunctionNotSupportedException if it was returned by all of the calls to the cohort connectors.
*
* @param exception captured exception
* @throws FunctionNotSupportedException the requested function is not supported in any of the federated repositories
*/
private void throwCapturedFunctionNotSupportedException(FunctionNotSupportedException exception) throws FunctionNotSupportedException
{
if (exception != null)
{
throw exception;
}
}
/**
* Throw a UserNotAuthorizedException if it was returned by one of the calls to a cohort connector.
*
* @param exception captured exception
* @throws UserNotAuthorizedException the userId is not authorized in the server
*/
private void throwCapturedUserNotAuthorizedException(UserNotAuthorizedException exception) throws UserNotAuthorizedException
{
if (exception != null)
{
throw exception;
}
}
/**
* Throw a RepositoryErrorException if it was returned by one of the calls to a cohort connector.
*
* @param exception captured exception
* @throws RepositoryErrorException there was an error in the repository
*/
private void throwCapturedRepositoryErrorException(RepositoryErrorException exception) throws RepositoryErrorException
{
if (exception != null)
{
throw exception;
}
}
/**
* Throw a RepositoryErrorException if an unexpected Throwable exception was returned by one of the calls
* to a cohort connector.
*
* @param exception captured exception
* @throws RepositoryErrorException there was an unexpected error in the repository
*/
private void throwCapturedThrowableException(Throwable exception,
String methodName) throws RepositoryErrorException
{
if (exception != null)
{
OMRSErrorCode errorCode = OMRSErrorCode.UNEXPECTED_EXCEPTION_FROM_COHORT;
String errorMessage = errorCode.getErrorMessageId() + errorCode.getFormattedErrorMessage(methodName,
exception.getMessage());
throw new RepositoryErrorException(errorCode.getHTTPErrorCode(),
this.getClass().getName(),
methodName,
errorMessage,
errorCode.getSystemAction(),
errorCode.getUserAction());
}
}
/**
* Take the results of the federated connectors and combine them into a valid TypeDef gallery or an
* exception.
*
* @param repositoryName the name of this repository
* @param combinedTypeDefResults TypeDefs returned by the federated connectors
* @param combinedAttributeTypeDefResults AttributeTypeDefs returned by the federated connectors
* @param userNotAuthorizedException captured user not authorized exception
* @param repositoryErrorException captured repository error exception
* @param anotherException captured Throwable
* @param methodName name of the method issuing the request
* @return TypeDefGallery
* @throws RepositoryErrorException there is a problem communicating with the metadata repository.
* @throws UserNotAuthorizedException the userId is not permitted to perform this operation.
*/
private TypeDefGallery validatedTypeDefGalleryResults(String repositoryName,
Map<String, TypeDef> combinedTypeDefResults,
Map<String, AttributeTypeDef> combinedAttributeTypeDefResults,
UserNotAuthorizedException userNotAuthorizedException,
RepositoryErrorException repositoryErrorException,
Throwable anotherException,
String methodName) throws RepositoryErrorException,
UserNotAuthorizedException
{
int resultCount = (combinedTypeDefResults.size() + combinedAttributeTypeDefResults.size());
/*
* Return any results, or exception if nothing is found.
*/
if (resultCount > 0)
{
TypeDefGallery typeDefGallery = new TypeDefGallery();
List<AttributeTypeDef> attributeTypeDefs = new ArrayList<>(combinedAttributeTypeDefResults.values());
List<TypeDef> typeDefs = new ArrayList<>(combinedTypeDefResults.values());
repositoryValidator.validateEnterpriseTypeDefs(repositoryName, typeDefs, methodName);
typeDefGallery.setAttributeTypeDefs(attributeTypeDefs);
typeDefGallery.setTypeDefs(typeDefs);
return typeDefGallery;
}
else
{
throwCapturedUserNotAuthorizedException(userNotAuthorizedException);
throwCapturedRepositoryErrorException(repositoryErrorException);
throwCapturedThrowableException(anotherException, methodName);
/*
* Nothing went wrong, there are just no results.
*/
return null;
}
}
/**
* Take the results of the federated connectors and combine them into a valid TypeDef list or an
* exception.
*
* @param repositoryName the name of this repository
* @param combinedTypeDefResults TypeDefs returned by the federated connectors
* @param userNotAuthorizedException captured user not authorized exception
* @param repositoryErrorException captured repository error exception
* @param anotherException captured Throwable
* @param methodName name of the method issuing the request
* @return list of TypeDefs
* @throws RepositoryErrorException problem in one of the federated connectors
* @throws UserNotAuthorizedException user not recognized or not granted access to the TypeDefs
*/
private List<TypeDef> validatedTypeDefListResults(String repositoryName,
Map<String, TypeDef> combinedTypeDefResults,
UserNotAuthorizedException userNotAuthorizedException,
RepositoryErrorException repositoryErrorException,
Throwable anotherException,
String methodName) throws RepositoryErrorException,
UserNotAuthorizedException
{
/*
* Return any results, or null if nothing is found.
*/
if (! combinedTypeDefResults.isEmpty())
{
List<TypeDef> typeDefs = new ArrayList<>(combinedTypeDefResults.values());
repositoryValidator.validateEnterpriseTypeDefs(repositoryName, typeDefs, methodName);
return typeDefs;
}
else
{
throwCapturedUserNotAuthorizedException(userNotAuthorizedException);
throwCapturedRepositoryErrorException(repositoryErrorException);
throwCapturedThrowableException(anotherException, methodName);
/*
* Nothing went wrong, there are just no results.
*/
return null;
}
}
/**
* Take the results of the federated connectors and combine them into a valid AttributeTypeDef list or an
* exception.
*
* @param repositoryName the name of this repository
* @param combinedAttributeTypeDefResults AttributeTypeDefs returned by the federated connectors
* @param userNotAuthorizedException captured user not authorized exception
* @param repositoryErrorException captured repository error exception
* @param anotherException captured Throwable
* @param methodName name of the method issuing the request
* @return list of AttributeTypeDefs
* @throws RepositoryErrorException problem in one of the federated connectors
* @throws UserNotAuthorizedException user not recognized or not granted access to the TypeDefs
*/
private List<AttributeTypeDef> validatedAttributeTypeDefListResults(String repositoryName,
Map<String, AttributeTypeDef> combinedAttributeTypeDefResults,
UserNotAuthorizedException userNotAuthorizedException,
RepositoryErrorException repositoryErrorException,
Throwable anotherException,
String methodName) throws RepositoryErrorException,
UserNotAuthorizedException
{
/*
* Return any results, or null if nothing is found.
*/
if (! combinedAttributeTypeDefResults.isEmpty())
{
List<AttributeTypeDef> attributeTypeDefs = new ArrayList<>(combinedAttributeTypeDefResults.values());
repositoryValidator.validateEnterpriseAttributeTypeDefs(repositoryName, attributeTypeDefs, methodName);
return attributeTypeDefs;
}
else
{
throwCapturedUserNotAuthorizedException(userNotAuthorizedException);
throwCapturedRepositoryErrorException(repositoryErrorException);
throwCapturedThrowableException(anotherException, methodName);
/*
* Nothing went wrong, there are just no results.
*/
return null;
}
}
/**
* Return a validated, sorted list of search results.
*
* @param repositoryName name of this repository
* @param combinedResults results from all cohort repositories
* @param sequencingProperty String name of the property that is to be used to sequence the results.
* Null means do not sequence on a property name (see SequencingOrder).
* @param sequencingOrder Enum defining how the results should be ordered.
* @param pageSize the maximum number of result entities that can be returned on this request. Zero means
* unrestricted return results size.
* @param methodName name of method called
* @return list of entities
* @throws RepositoryErrorException there is a problem with the results
*/
private List<EntityDetail> validatedEntityListResults(String repositoryName,
Map<String, EntityDetail> combinedResults,
String sequencingProperty,
SequencingOrder sequencingOrder,
int pageSize,
String methodName) throws RepositoryErrorException
{
if (combinedResults.isEmpty())
{
return null;
}
List<EntityDetail> actualResults = new ArrayList<>(combinedResults.values());
// todo: sort results and crop to max page size
return actualResults;
}
/**
* Return a validated, sorted list of search results.
*
* @param repositoryName name of this repository
* @param combinedResults relationships from all cohort repositories
* @param sequencingProperty String name of the property that is to be used to sequence the results.
* Null means do not sequence on a property name (see SequencingOrder).
* @param sequencingOrder Enum defining how the results should be ordered.
* @param pageSize the maximum number of result entities that can be returned on this request. Zero means
* unrestricted return results size.
* @param methodName name of the method called
* @return list of relationships
* @throws RepositoryErrorException there is a problem with the results
*/
private List<Relationship> validatedRelationshipResults(String repositoryName,
Map<String, Relationship> combinedResults,
String sequencingProperty,
SequencingOrder sequencingOrder,
int pageSize,
String methodName) throws RepositoryErrorException
{
if (combinedResults.isEmpty())
{
return null;
}
List<Relationship> actualResults = new ArrayList<>(combinedResults.values());
// todo, sort results and crop to max page size
return actualResults;
}
/**
* Return a validated InstanceGraph.
*
* @param repositoryName name of this repository
* @param accumulatedEntityResults list of returned entities
* @param accumulatedRelationshipResults list of returned relationships
* @param userNotAuthorizedException captured exception
* @param propertyErrorException captured exception
* @param functionNotSupportedException captured exception
* @param entityNotKnownException captured exception
* @param repositoryErrorException captured exception
* @param anotherException captured Throwable exception
* @param methodName name of calling method
* @return InstanceGraph
*/
private InstanceGraph validatedInstanceGraphResults(String repositoryName,
Map<String, EntityDetail> accumulatedEntityResults,
Map<String, Relationship> accumulatedRelationshipResults,
UserNotAuthorizedException userNotAuthorizedException,
PropertyErrorException propertyErrorException,
FunctionNotSupportedException functionNotSupportedException,
EntityNotKnownException entityNotKnownException,
RepositoryErrorException repositoryErrorException,
Throwable anotherException,
String methodName) throws UserNotAuthorizedException,
PropertyErrorException,
FunctionNotSupportedException,
EntityNotKnownException,
RepositoryErrorException
{
int resultCount = (accumulatedEntityResults.size() + accumulatedRelationshipResults.size());
/*
* Return any results, or exception if nothing is found.
*/
if (resultCount > 0)
{
InstanceGraph instanceGraph = new InstanceGraph();
List<EntityDetail> entityDetails = new ArrayList<>(accumulatedEntityResults.values());
List<Relationship> relationships = new ArrayList<>(accumulatedRelationshipResults.values());
// todo Validate the entities and relationships
instanceGraph.setEntities(entityDetails);
instanceGraph.setRelationships(relationships);
return instanceGraph;
}
else
{
throwCapturedUserNotAuthorizedException(userNotAuthorizedException);
throwCapturedRepositoryErrorException(repositoryErrorException);
throwCapturedPropertyErrorException(propertyErrorException);
throwCapturedThrowableException(anotherException, methodName);
throwCapturedFunctionNotSupportedException(functionNotSupportedException);
throwCapturedEntityNotKnownException(entityNotKnownException);
/*
* Nothing went wrong, there are just no results.
*/
return null;
}
}
}
| [
"mandy_chessell@uk.ibm.com"
] | mandy_chessell@uk.ibm.com |
8c498f4767b4574bcd8663ebd23768dcef0f8f49 | 4616476edc1ec184af03779e4562ac31037a387c | /Informatik/PhytonEinführung/src/Aufgabe1.java | 6b34b726d67f01dec4d6e640a9297574724e708f | [] | no_license | Lukas-AI-Project/programming | b197478ffd7125e9735b78637c15076af21c969c | 4ba18dab06b332edfbdd1678b5f58a45afcd274c | refs/heads/master | 2021-06-10T01:15:56.976709 | 2017-01-18T19:22:05 | 2017-01-18T19:22:05 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 284 | java | import java.util.Scanner;
public class Aufgabe1 {
public static void main(String[] args){
Scanner sc = new Scanner(System.in);
System.out.println("Bitte geben sie ihren Namen ein: ");
String name = sc.next();
System.out.println("Guten Tag "+name+"!");
sc.close();
}
}
| [
"murtagh.1111@gmx.de"
] | murtagh.1111@gmx.de |
8041a103a4fd225eff33dd8c59804fb6ee1e71e8 | 8e7199dcb9d15155acad762ff506609129487cec | /tect/src/test/java/TEst/tect/AppTest.java | cafb69f81a880b51193f3280a4778c54a123bc4c | [] | no_license | pooja-tester/automationscripts | 6faaacf4783624663b7fec904ff7b30b818ade10 | 9518d8e6ad48874669d620abad74a72240174c19 | refs/heads/master | 2021-04-28T13:51:13.423343 | 2019-09-03T07:04:40 | 2019-09-03T07:04:40 | 121,951,024 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 675 | java | package TEst.tect;
import junit.framework.Test;
import junit.framework.TestCase;
import junit.framework.TestSuite;
/**
* Unit test for simple App.
*/
public class AppTest
extends TestCase
{
/**
* Create the test case
*
* @param testName name of the test case
*/
public AppTest( String testName )
{
super( testName );
}
/**
* @return the suite of tests being tested
*/
public static Test suite()
{
return new TestSuite( AppTest.class );
}
/**
* Rigourous Test :-)
*/
public void testApp()
{
assertTrue( true );
}
}
| [
"poojadiwan18@gmail.com"
] | poojadiwan18@gmail.com |
74e93be3ed81a4c717e3a2d221fe77527217faf9 | 600a80b2e378985e7cf5d6035834697b24a873b0 | /src/test/java/org/springframework/samples/petclinic/web/PrescriptionControllerTests.java | e6ec563b0660892bcd0a742f2a5f3518554e8726 | [
"LicenseRef-scancode-generic-cla",
"Apache-2.0"
] | permissive | mancanjua/DP2-1920-GI-01 | 8f93fdc843dfe5b6ac0609e5510df8c026f12136 | ba81993acfe303cb2eb7983075b75606b803a5f3 | refs/heads/master | 2022-09-29T22:10:39.301759 | 2020-06-05T19:36:04 | 2020-06-05T19:36:04 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 4,849 | java | package org.springframework.samples.petclinic.web;
import static org.mockito.BDDMockito.given;
import static org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestPostProcessors.csrf;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.model;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.view;
import org.assertj.core.util.Lists;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest;
import org.springframework.boot.test.mock.mockito.MockBean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.FilterType;
import org.springframework.samples.petclinic.configuration.SecurityConfiguration;
import org.springframework.samples.petclinic.model.MedicalRecord;
import org.springframework.samples.petclinic.model.Medicine;
import org.springframework.samples.petclinic.model.Owner;
import org.springframework.samples.petclinic.model.Pet;
import org.springframework.samples.petclinic.model.PetType;
import org.springframework.samples.petclinic.model.Visit;
import org.springframework.samples.petclinic.service.MedicalRecordService;
import org.springframework.samples.petclinic.service.MedicineService;
import org.springframework.samples.petclinic.service.PrescriptionService;
import org.springframework.samples.petclinic.web.formatters.MedicineFormatter;
import org.springframework.security.config.annotation.web.WebSecurityConfigurer;
import org.springframework.security.test.context.support.WithMockUser;
import org.springframework.test.web.servlet.MockMvc;
@WebMvcTest(value = PrescriptionController.class,
includeFilters = @ComponentScan.Filter(value = MedicineFormatter.class, type = FilterType.ASSIGNABLE_TYPE),
excludeFilters = @ComponentScan.Filter(type = FilterType.ASSIGNABLE_TYPE, classes = WebSecurityConfigurer.class),
excludeAutoConfiguration= SecurityConfiguration.class)
class PrescriptionControllerTests {
@MockBean
private MedicineService medicineService;
@MockBean
private MedicalRecordService medicalRecordService;
@MockBean
private PrescriptionService prescriptionService;
@Autowired
private MockMvc mockMvc;
@BeforeEach
void setup() {
Owner owner;
Pet pet;
Visit visit;
MedicalRecord medicalRecord;
Medicine medicine;
PetType petType;
owner = new Owner();
pet = new Pet();
visit = new Visit();
medicalRecord = new MedicalRecord();
medicine = new Medicine();
petType = new PetType();
petType.setName("Test");
petType.setId(1);
owner.addPet(pet);
owner.setId(1);
pet.setType(petType);
pet.setId(1);
visit.setPet(pet);
visit.setId(1);
medicalRecord.setVisit(visit);
medicine.setName("Cat medicine");
medicine.setPetType(petType);
given(medicineService.findManyAll()).willReturn(Lists.newArrayList(medicine));
given(medicalRecordService.findMedicalRecordById(1)).willReturn(medicalRecord);
given(medicineService.findByPetType(null)).willReturn(Lists.newArrayList(medicine));
}
@WithMockUser(value = "spring")
@Test
void testInitCreationForm() throws Exception {
mockMvc.perform(get("/owners/*/pets/*/visits/*/medical-record/{medical-recordId}/prescription/create", 1))
.andExpect(status().isOk())
.andExpect(view().name("prescription/form"))
.andExpect(model().attributeExists("prescription"))
.andExpect(model().attributeExists("medicines"));
}
@WithMockUser(value = "spring")
@Test
void testProccessCreationFormSuccess() throws Exception {
mockMvc.perform(post("/owners/*/pets/*/visits/*/medical-record/{medical-recordId}/prescription/create", 1)
.with(csrf())
.queryParam("dose", "Test")
.queryParam("medicine", "Cat medicine"))
.andExpect(status().is3xxRedirection())
.andExpect(view().name("redirect:/owners/1/pets/1/visits/1/medical-record/show?id=1"));
}
@WithMockUser(value = "spring")
@Test
void testProccessCreationFormHasErrors() throws Exception {
mockMvc.perform(post("/owners/*/pets/*/visits/*/medical-record/{medical-recordId}/prescription/create", 1)
.with(csrf())
.queryParam("dose", "Test")
.queryParam("medicine", ""))
.andExpect(status().isOk())
.andExpect(view().name("prescription/form"))
.andExpect(model().hasErrors())
.andExpect(model().attributeHasErrors("prescription"))
.andExpect(model().attributeExists("prescription"));
}
}
| [
"mancanjua@alum.us.es"
] | mancanjua@alum.us.es |
cde71c75f49fe1adea195bac5185703cb82571ec | 9f6884be098fc8ea0623f738eb5fcae121074ddd | /app/src/main/java/com/example/administrator/newcityselect/citypicker/util/ScreenUtil.java | 1b82ee39bdc0f072df12351b862a7b05d9c33593 | [] | no_license | wuqiuyun/citySelect | 5dc08f74b61f3d2e907d1118e7217b8f0f479bd0 | 1092ebffb96e076e18e00563ea54609a2da60723 | refs/heads/master | 2021-05-24T10:32:34.217062 | 2020-04-06T14:27:46 | 2020-04-06T14:27:46 | 253,521,085 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 3,099 | java | package com.example.administrator.newcityselect.citypicker.util;
import android.app.Activity;
import android.content.Context;
import android.content.res.Configuration;
import android.content.res.Resources;
import android.os.Build;
import android.provider.Settings;
import android.util.DisplayMetrics;
import android.view.Display;
import android.view.WindowManager;
/**
* @Author: Bro0cL
* @Date: 2018/12/4 11:35
* @Discription:
*/
public class ScreenUtil {
private static int getInternalDimensionSize(Context context, String key) {
int result = 0;
try {
int resourceId = context.getResources().getIdentifier(key, "dimen", "android");
if (resourceId > 0) {
result = Math.round(context.getResources().getDimensionPixelSize(resourceId) *
Resources.getSystem().getDisplayMetrics().density /
context.getResources().getDisplayMetrics().density);
}
} catch (Resources.NotFoundException ignored) {
return 0;
}
return result;
}
public static int getStatusBarHeight(Context context) {
return getInternalDimensionSize(context, "status_bar_height");
}
public static int getNavigationBarHeight(Context context) {
boolean mInPortrait = context.getResources().getConfiguration().orientation == Configuration.ORIENTATION_PORTRAIT;
int result = 0;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH) {
if (hasNavBar((Activity) context)) {
String key;
if (mInPortrait) {
key = "navigation_bar_height";
} else {
key = "navigation_bar_height_landscape";
}
return getInternalDimensionSize(context, key);
}
}
return result;
}
private static boolean hasNavBar(Activity activity) {
//判断小米手机是否开启了全面屏,开启了,直接返回false
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
if (Settings.Global.getInt(activity.getContentResolver(), "force_fsg_nav_bar", 0) != 0) {
return false;
}
}
//其他手机根据屏幕真实高度与显示高度是否相同来判断
WindowManager windowManager = activity.getWindowManager();
Display d = windowManager.getDefaultDisplay();
DisplayMetrics realDisplayMetrics = new DisplayMetrics();
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
d.getRealMetrics(realDisplayMetrics);
}
int realHeight = realDisplayMetrics.heightPixels;
int realWidth = realDisplayMetrics.widthPixels;
DisplayMetrics displayMetrics = new DisplayMetrics();
d.getMetrics(displayMetrics);
int displayHeight = displayMetrics.heightPixels;
int displayWidth = displayMetrics.widthPixels;
return (realWidth - displayWidth) > 0 || (realHeight - displayHeight) > 0;
}
}
| [
"wuqiuyun_9629@163.com"
] | wuqiuyun_9629@163.com |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.