hexsha
stringlengths
40
40
size
int64
8
1.04M
content
stringlengths
8
1.04M
avg_line_length
float64
2.24
100
max_line_length
int64
4
1k
alphanum_fraction
float64
0.25
0.97
eb1ec72e543398ab46c66b54812ed09d00337a2d
3,515
package com.micmiu.hadoop.mr.demo; import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.JSONObject; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.conf.Configured; import org.apache.hadoop.fs.Path; import org.apache.hadoop.io.IntWritable; import org.apache.hadoop.io.LongWritable; import org.apache.hadoop.io.Text; import org.apache.hadoop.mapreduce.Job; import org.apache.hadoop.mapreduce.Mapper; import org.apache.hadoop.mapreduce.Reducer; import org.apache.hadoop.mapreduce.lib.input.FileInputFormat; import org.apache.hadoop.mapreduce.lib.input.TextInputFormat; import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat; import org.apache.hadoop.mapreduce.lib.output.TextOutputFormat; import org.apache.hadoop.util.Tool; import org.apache.hadoop.util.ToolRunner; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.IOException; import java.util.StringTokenizer; /** * hadoop jar xx.jar MainClass -libjars a.jar,b.jar arg0 arg1 .... * libjars 文件是需要放在hadoop当前所在文件系统中,不能是hdfs、s3n/s3或者其他系统 * 这些第三方jar包 都被加载到当前classloader的子loader中,不是当前classloader中 * User: <a href="http://micmiu.com">micmiu</a> * Date: 2/17/2015 * Time: 16:20 */ public class MRUseLibjarsDemo extends Configured implements Tool { private static final Logger LOGGER = LoggerFactory.getLogger(MRUseLibjarsDemo.class); public static class MyJsonMap extends Mapper<LongWritable, Text, Text, IntWritable> { private final IntWritable one = new IntWritable(1); private Text name = new Text(); @Override protected void setup(Context context) throws IOException, InterruptedException { super.setup(context); LOGGER.info(">>>> libjars(tmpjars) ... " + context.getConfiguration().get("tmpjars")); } public void map(LongWritable key, Text value, Context context) throws IOException, InterruptedException { //"{\"name\":\"Michael\",\"blog\":\"micmiu.com\"}" String line = value.toString(); LOGGER.info(">>>> log mapper line = " + line); try { JSONObject jsonObj = JSON.parseObject(line); if (jsonObj.containsKey("name")) { name.set(jsonObj.getString("name")); context.write(name, one); } } catch (Exception e) { LOGGER.error("map error", e); } } } public static class MyReduce extends Reducer<Text, IntWritable, Text, IntWritable> { public void reduce(Text key, Iterable<IntWritable> values, Context context) throws IOException, InterruptedException { int sum = 0; for (IntWritable val : values) { sum += val.get(); } LOGGER.info("reduce log >>>> " + key + " = " + sum); context.write(key, new IntWritable(sum)); } } public int run(String[] args) throws Exception { Configuration conf = getConf(); Job job = Job.getInstance(conf, MRUseLibjarsDemo.class.getSimpleName()); job.setJarByClass(MRUseLibjarsDemo.class); job.setOutputKeyClass(Text.class); job.setOutputValueClass(IntWritable.class); job.setMapperClass(MyJsonMap.class); job.setReducerClass(MyReduce.class); job.setInputFormatClass(TextInputFormat.class); job.setOutputFormatClass(TextOutputFormat.class); FileInputFormat.addInputPath(job, new Path(args[0])); FileOutputFormat.setOutputPath(job, new Path(args[1])); return (job.waitForCompletion(true) ? 0 : -1); } public static void main(String[] args) throws Exception { int res = ToolRunner.run(new MRUseLibjarsDemo(), args); LOGGER.info("MR <MRUseLibjarsDemo> run with toolrunner result = {}", res); System.exit(res); } }
31.666667
107
0.737411
b6cb23723fe942bcffca2660fad8b3f96724aa66
3,126
package com.twitter.hraven; import org.junit.Test; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; /** */ public class TestFlow { private static final String CLUSTER = "cluster@dc"; private static final String USER = "testuser"; private static final String APP_ID = "testapp"; private static final String QUEUE1 = "queue1"; @Test public void testJobAggregation() { long runId = System.currentTimeMillis(); JobDetails job1 = new JobDetails(new JobKey(CLUSTER, USER, APP_ID, runId, "job_20120101000000_0001")); job1.setTotalMaps(100); job1.setTotalReduces(10); job1.setSubmitTime(runId); job1.setQueue(QUEUE1); CounterMap counters1 = new CounterMap(); counters1.add(new Counter("group1", "key1", 100)); counters1.add(new Counter("group2", "key1", 1000)); job1.setCounters(counters1); JobDetails job2 = new JobDetails(new JobKey(CLUSTER, USER, APP_ID, runId, "job_20120101000000_0002")); job2.setTotalMaps(10); job2.setTotalReduces(1); job2.setQueue(QUEUE1 + "2"); job2.setSubmitTime(runId + 3600000L); CounterMap counters2 = new CounterMap(); counters2.add(new Counter("group2", "key2", 1)); job2.setCounters(counters2); JobDetails job3 = new JobDetails(new JobKey(CLUSTER, USER, APP_ID, runId, "job_20120101000000_0003")); job3.setTotalMaps(1000); job3.setTotalReduces(10); job3.setSubmitTime(runId + 4800000L); job3.setQueue(QUEUE1+ "3"); CounterMap counters3 = new CounterMap(); counters3.add(new Counter("group1", "key1", 50)); counters3.add(new Counter("group2", "key1", 100)); job3.setCounters(counters3); job3.setMapCounters(counters3); job3.setReduceCounters(counters3); Flow flow = new Flow(new FlowKey(CLUSTER, USER, APP_ID, runId)); flow.addJob(job1); flow.addJob(job2); flow.addJob(job3); assertEquals(3, flow.getJobCount()); // totalMaps = 100 + 10 + 1000 assertEquals(1110, flow.getTotalMaps()); // totalReduces = 10 + 1 + 10 assertEquals(21, flow.getTotalReduces()); // ensure the queue for the first job in the flow is set as queue for the flow assertTrue(QUEUE1.equals(flow.getQueue())); // total counters: group1, key1 = 100 + 50 assertEquals(150, flow.getCounters().getCounter("group1", "key1").getValue()); // total counters: group2, key1 = 1000 + 100 assertEquals(1100, flow.getCounters().getCounter("group2", "key1").getValue()); // total counters: group2, key2 = 1 assertEquals(1, flow.getCounters().getCounter("group2", "key2").getValue()); // map counters: group1, key1 = 50 assertEquals(50, flow.getMapCounters().getCounter("group1", "key1").getValue()); // map counters: group2, key1 = 100 assertEquals(100, flow.getMapCounters().getCounter("group2", "key1").getValue()); // reduce counters: group1, key1 = 50 assertEquals(50, flow.getReduceCounters().getCounter("group1", "key1").getValue()); // reduce counters: group2, key1 = 100 assertEquals(100, flow.getReduceCounters().getCounter("group2", "key1").getValue()); } }
40.076923
106
0.690339
53bfbe400549968125fcf772669cb911dce8aba0
5,914
package com.ensoftcorp.open.commons.ui.views.smart; import java.util.HashSet; import java.util.Set; import com.ensoftcorp.atlas.core.indexing.IIndexListener; import com.ensoftcorp.atlas.core.indexing.IndexingUtil; import com.ensoftcorp.open.commons.ui.log.Log; import com.ensoftcorp.atlas.core.query.Q; import com.ensoftcorp.atlas.core.script.FrontierStyledResult; import com.ensoftcorp.atlas.core.script.StyledResult; import com.ensoftcorp.atlas.ui.scripts.selections.FilteringAtlasSmartViewScript; import com.ensoftcorp.atlas.ui.scripts.selections.IExplorableScript; import com.ensoftcorp.atlas.ui.scripts.selections.IResizableScript; import com.ensoftcorp.atlas.ui.scripts.util.SimpleScriptUtil; import com.ensoftcorp.atlas.ui.selection.event.FrontierEdgeExploreEvent; import com.ensoftcorp.atlas.ui.selection.event.IAtlasSelectionEvent; import com.ensoftcorp.open.commons.codepainter.CodePainter; import com.ensoftcorp.open.commons.codepainter.ColorPalette; public final class CodePainterSmartView extends FilteringAtlasSmartViewScript implements IResizableScript, IExplorableScript { private static CodePainter codePainter = null; private static Set<CodePainterSmartViewEventListener> listeners = new HashSet<CodePainterSmartViewEventListener>(); private static IIndexListener indexListener = null; public CodePainterSmartView(){ if(indexListener == null){ // index listener disables selection listener on index change indexListener = new IIndexListener(){ @Override public void indexOperationCancelled(IndexOperation op) {} @Override public void indexOperationComplete(IndexOperation op) {} @Override public void indexOperationError(IndexOperation op, Throwable error) {} @Override public void indexOperationScheduled(IndexOperation op) {} @Override public void indexOperationStarted(IndexOperation op) { synchronized (CodePainter.class){ if(codePainter != null){ for(ColorPalette colorPalette : codePainter.getColorPalettes()){ try { colorPalette.clearCanvas(); } catch (Exception e){ Log.warning("Error clearing current code painter color palette canvas [" + colorPalette.getName() + "]", e); } } } } } }; // add the index listener IndexingUtil.addListener(indexListener); } } /** * A listener class to handle callbacks for smart view events */ public static interface CodePainterSmartViewEventListener { public void selectionChanged(IAtlasSelectionEvent event, int reverse, int forward); public void codePainterChanged(CodePainter codePainter); } public static void addListener(CodePainterSmartViewEventListener listener){ listeners.add(listener); } public static void removeListener(CodePainterSmartViewEventListener listener){ listeners.remove(listener); } /** * Sets the active code painter. Setting code painter to null effectively * disables code painter smart view. * * @param codePainter */ public static final synchronized boolean setCodePainter(CodePainter codePainter){ synchronized (CodePainterSmartView.class){ if(codePainter == null){ // assigning null again CodePainterSmartView.codePainter = null; notifyListenersCodePainterChanged(); return true; } else if(CodePainterSmartView.codePainter == null){ // first non-null assignment CodePainterSmartView.codePainter = codePainter; notifyListenersCodePainterChanged(); return true; } else if(!CodePainterSmartView.codePainter.equals(codePainter)){ // new non-equal assignment (code painter change) CodePainterSmartView.codePainter = codePainter; notifyListenersCodePainterChanged(); return true; } // no change return false; } } private static void notifyListenersCodePainterChanged() { for(CodePainterSmartViewEventListener listener : listeners){ try { listener.codePainterChanged(CodePainterSmartView.codePainter); } catch (Throwable t){ Log.error("Error notifying code painter changed listeners", t); } } } /** * Returns the active code painter * @return */ public static final synchronized CodePainter getCodePainter(){ synchronized (CodePainterSmartView.class){ return codePainter; } } @Override public final String getTitle() { return "Code Painter"; } @Override protected final String[] getSupportedNodeTags() { return EVERYTHING; } @Override protected final String[] getSupportedEdgeTags() { return EVERYTHING; } @Override public final synchronized int getDefaultStepTop() { synchronized (CodePainterSmartView.class){ if(codePainter != null){ return codePainter.getDefaultStepReverse(); } } return 1; } @Override public final synchronized int getDefaultStepBottom() { synchronized (CodePainterSmartView.class){ if(codePainter != null){ return codePainter.getDefaultStepForward(); } } return 1; } @Override public final synchronized FrontierStyledResult explore(FrontierEdgeExploreEvent event, FrontierStyledResult oldResult) { synchronized (CodePainterSmartView.class){ if(codePainter != null){ return codePainter.explore(event, oldResult); } } return SimpleScriptUtil.explore(this, event, oldResult); } @Override public final synchronized FrontierStyledResult evaluate(IAtlasSelectionEvent event, int reverse, int forward) { FrontierStyledResult result = null; synchronized (CodePainterSmartView.class){ if(codePainter != null){ result = codePainter.evaluate(event, reverse, forward); } } for(CodePainterSmartViewEventListener listener : listeners){ listener.selectionChanged(event, reverse, forward); } return result; } @Override protected final StyledResult selectionChanged(IAtlasSelectionEvent event, Q filteredSelection) { // this is dead code, just here to satisfy interfaces return null; } }
30.173469
126
0.757355
d65224c7f61ff8b6440aec7ae4d640bb12bcaaf3
1,855
package com.unascribed.fabrication.mixin.e_mechanics.obsidian_tears; import java.util.Optional; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.injection.At; import org.spongepowered.asm.mixin.injection.Inject; import org.spongepowered.asm.mixin.injection.callback.CallbackInfoReturnable; import com.unascribed.fabrication.support.EligibleIf; import com.unascribed.fabrication.support.MixinConfigPlugin; import net.minecraft.block.Block; import net.minecraft.block.BlockState; import net.minecraft.block.Blocks; import net.minecraft.block.RespawnAnchorBlock; import net.minecraft.entity.EntityType; import net.minecraft.entity.player.PlayerEntity; import net.minecraft.server.world.ServerWorld; import net.minecraft.util.math.BlockPos; import net.minecraft.util.math.Vec3d; @Mixin(PlayerEntity.class) @EligibleIf(configAvailable="*.obsidian_tears") public class MixinPlayerEntity { @Inject(at=@At("HEAD"), method="findRespawnPosition(Lnet/minecraft/server/world/ServerWorld;Lnet/minecraft/util/math/BlockPos;FZZ)Ljava/util/Optional;", cancellable=true) private static void findRespawnPosition(ServerWorld world, BlockPos pos, float f, boolean b, boolean b2, CallbackInfoReturnable<Optional<Vec3d>> ci) { if (!MixinConfigPlugin.isEnabled("*.obsidian_tears")) return; BlockState state = world.getBlockState(pos); Block bl = state.getBlock(); if (bl == Blocks.CRYING_OBSIDIAN) { if (world.getBlockState(pos.up()).getBlock().canMobSpawnInside() && world.getBlockState(pos.up().up()).getBlock().canMobSpawnInside()) { ci.setReturnValue(Optional.of(new Vec3d(pos.getX()+0.5, pos.getY()+1, pos.getZ()+0.5))); } else { Optional<Vec3d> attempt = RespawnAnchorBlock.findRespawnPosition(EntityType.PLAYER, world, pos); if (attempt.isPresent()) { ci.setReturnValue(attempt); } } } } }
41.222222
153
0.78221
3e42b13b33bc76e42e910526691f449a9c4ca9db
1,717
package io.kpow.secure; import clojure.java.api.Clojure; import clojure.lang.IFn; import java.util.Properties; public class Decoder { /** * Decode payload > text with key taken from environment variable KPOW_SECURE_KEY **/ public static String text(String payload) { IFn require = Clojure.var("clojure.core", "require"); require.invoke(Clojure.read("kpow.secure")); return (String) Clojure.var("kpow.secure", "decrypted").invoke(payload); } /** * Decode payload > text with key provided **/ public static String text(String key, String payload) { IFn require = Clojure.var("clojure.core", "require"); require.invoke(Clojure.read("kpow.secure")); return (String) Clojure.var("kpow.secure", "decrypted").invoke(key, payload); } /** * Decode payload > properties with key taken from environment variable KPOW_SECURE_KEY **/ public static Properties properties(String payload) { IFn require = Clojure.var("clojure.core", "require"); require.invoke(Clojure.read("kpow.secure")); String text = (String) Clojure.var("kpow.secure", "decrypted").invoke(payload); return (Properties) Clojure.var("kpow.secure", "->props").invoke(text); } /** * Decode payload > properties with key provided **/ public static Properties properties(String key, String payload) { IFn require = Clojure.var("clojure.core", "require"); require.invoke(Clojure.read("kpow.secure")); String text = (String) Clojure.var("kpow.secure", "decrypted").invoke(key, payload); return (Properties) Clojure.var("kpow.secure", "->props").invoke(text); } }
35.770833
92
0.649971
361622fb666511f5e781b7f513ea26228a5091e3
351
package com.nattguld.tasker.util; /** * * @author randqm * */ public class Misc { /** * Makes the current thread sleep for a given amount of time. * * @param ms The milliseconds to sleep. */ public static void sleep(long ms) { try { Thread.sleep(ms); } catch (InterruptedException e) { //e.printStackTrace(); } } }
13.5
62
0.615385
8d9cbfe1e7343dcafeafe2c8a493bb1115f54ff0
3,768
/* * Copyright 2021 - 2022 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.sbm.project.openrewrite; import org.springframework.sbm.engine.context.ProjectContext; import org.springframework.sbm.project.resource.RewriteSourceFileHolder; import org.springframework.sbm.project.resource.TestProjectContext; import org.junit.jupiter.api.Test; import org.openrewrite.java.tree.J; import java.nio.file.Path; import static org.assertj.core.api.Assertions.assertThat; class RewriteSourceFileHolderTest { public static final Path PROJECT_DIR = TestProjectContext.getDefaultProjectRoot(); public static final String SOURCE_CODE = "package com.foo.bar; class Foo{}"; private ProjectContext projectContext = TestProjectContext.buildProjectContext() .withJavaSource("src/main/java", SOURCE_CODE) .build(); private RewriteSourceFileHolder<J.CompilationUnit> sut = projectContext .getProjectJavaSources() .list() .get(0) .getResource(); @Test void replaceWithShouldMarkAsChanged_whenContentDiffers() { J.CompilationUnit newSourceFile = TestProjectContext.buildProjectContext() .withJavaSource("src/main/java", "package com.foo.bar; class Bar{}") .build() .getProjectJavaSources() .list() .get(0) .getResource() .getSourceFile(); sut.replaceWith(newSourceFile); assertThat(sut.hasChanges()).isTrue(); assertThat(sut.getSourceFile()).isSameAs(newSourceFile); } @Test void replaceWithShouldNotMarkAsChanged_WhenContentEquals() { String sourceCode = "class Foo{}"; J.CompilationUnit newSourceFile = TestProjectContext.buildProjectContext() .withJavaSource("src/main/java", SOURCE_CODE) .build() .getProjectJavaSources() .list() .get(0) .getResource() .getSourceFile(); sut.replaceWith(newSourceFile); assertThat(sut.hasChanges()).isFalse(); assertThat(sut.getSourceFile()).isSameAs(newSourceFile); } @Test void testSourcePath() { Path sourcePath = sut.getSourcePath(); assertThat(sourcePath).isEqualTo(Path.of("src/main/java/com/foo/bar/Foo.java")); } @Test void testGetAbsolutePath() { Path absolutePath = sut.getAbsolutePath(); assertThat(absolutePath).isEqualTo(PROJECT_DIR.resolve("src/main/java/com/foo/bar/Foo.java")); } @Test void testMoveTo_withRelativePath() { sut.moveTo(Path.of("foo/Bar.java")); assertThat(sut.getAbsolutePath()).isEqualTo(PROJECT_DIR.resolve("foo/Bar.java")); assertThat(sut.print()).isEqualTo(SOURCE_CODE); assertThat(sut.hasChanges()).isTrue(); } @Test void testMoveTo_withAbsolutePath() { sut.moveTo(PROJECT_DIR.resolve("foo/Foo.java")); assertThat(sut.getAbsolutePath()).isEqualTo(PROJECT_DIR.resolve("foo/Foo.java")); assertThat(sut.print()).isEqualTo(SOURCE_CODE); assertThat(sut.hasChanges()).isTrue(); } }
35.885714
102
0.667728
b251ddd6017508323ac333a43a126552cf2b0eb3
665
package io.gomint.server.inventory.item; import io.gomint.inventory.item.ItemType; import io.gomint.server.registry.RegisterInfo; import io.gomint.world.block.data.BlockColor; /** * @author geNAZt * @version 1.0 */ @RegisterInfo(sId = "minecraft:wool", id = 35) public class ItemWool extends ItemStack implements io.gomint.inventory.item.ItemWool { @Override public ItemType getItemType() { return ItemType.WOOL; } @Override public BlockColor getColor() { return BlockColor.values()[this.getData()]; } @Override public void setColor(BlockColor color) { this.setData((short) color.ordinal()); } }
22.166667
86
0.690226
b3928fa8dbbdeea0a0d6cb4d4399173de9605acd
3,565
package com.tajkun.ad.search.index; import com.alibaba.fastjson.JSON; import com.tajkun.ad.binlogrel.constant.OpType; import com.tajkun.ad.common.export.ExportConstant; import com.tajkun.ad.common.export.table.*; import com.tajkun.ad.search.handler.LevelDataHandler; import org.springframework.context.annotation.DependsOn; import org.springframework.stereotype.Component; import javax.annotation.PostConstruct; import java.io.BufferedReader; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Paths; import java.util.List; import java.util.stream.Collectors; /** * @program: tajkun-ad * @description: 读取文件全量索引 * @author: Jiakun * @create: 2020-04-25 13:17 **/ @Component @DependsOn("dataTable") public class IndexFileLoader { // 全量索引加载,检索系统启动时执行,即IndexFileLoader加载到spring容器时就执行 @PostConstruct public void init() { // 顺序2 3 4 List<String> planStrings = loadExportData( String.format("%s%s", ExportConstant.DATA_ROOT_DIR, ExportConstant.PROMOTION_PLAN)); planStrings.forEach(plan -> LevelDataHandler.handleLevel2( JSON.parseObject(plan, PlanTable.class), OpType.ADD )); List<String> creativeStrings = loadExportData( String.format("%s%s", ExportConstant.DATA_ROOT_DIR, ExportConstant.CREATIVE)); creativeStrings.forEach(creative -> LevelDataHandler.handleLevel2( JSON.parseObject(creative, CreativeTable.class), OpType.ADD )); List<String> unitStrings = loadExportData( String.format("%s%s", ExportConstant.DATA_ROOT_DIR, ExportConstant.PROMOTION_UNIT)); unitStrings.forEach(unit -> LevelDataHandler.handleLevel3( JSON.parseObject(unit, UnitTable.class), OpType.ADD )); List<String> creativeUnitStrings = loadExportData( String.format("%s%s", ExportConstant.DATA_ROOT_DIR, ExportConstant.CREATIVE_UNIT)); creativeUnitStrings.forEach(cu -> LevelDataHandler.handleLevel3( JSON.parseObject(cu, CreativeUnitTable.class), OpType.ADD )); List<String> unitDistrictStrings = loadExportData( String.format("%s%s", ExportConstant.DATA_ROOT_DIR, ExportConstant.UNIT_DISTRICT)); unitDistrictStrings.forEach(district -> LevelDataHandler.handleLevel4( JSON.parseObject(district, UnitDistrictTable.class), OpType.ADD )); List<String> unitInterestStrings = loadExportData( String.format("%s%s", ExportConstant.DATA_ROOT_DIR, ExportConstant.UNIT_INTEREST)); unitInterestStrings.forEach(interest -> LevelDataHandler.handleLevel4( JSON.parseObject(interest, UnitInterestTable.class), OpType.ADD )); List<String> unitKeywordStrings = loadExportData( String.format("%s%s", ExportConstant.DATA_ROOT_DIR, ExportConstant.UNIT_KEYWORD)); unitKeywordStrings.forEach(keyword -> LevelDataHandler.handleLevel4( JSON.parseObject(keyword, UnitKeywordTable.class), OpType.ADD )); } // 读取数据文件到List<String> private List<String> loadExportData(String fileName) { try (BufferedReader reader = Files.newBufferedReader(Paths.get(fileName))){ return reader.lines().collect(Collectors.toList()); } catch (IOException e) { throw new RuntimeException(e.getMessage()); } } }
38.75
100
0.670407
167d8d1ad9477cceca3b2d200017f41baa3a1f44
1,706
package com.fr.swift.cloud.config.entity.key; import javax.persistence.Column; import javax.persistence.Embeddable; import java.io.Serializable; /** * @author yee * @date 2018/7/3 */ @Embeddable public class SwiftSegLocationEntityId implements Serializable { private static final long serialVersionUID = 2145513184016170123L; @Column(name = "clusterId") private String clusterId; @Column(name = "segmentId") private String segmentId; public SwiftSegLocationEntityId(String clusterId, String segmentId) { this.clusterId = clusterId; this.segmentId = segmentId; } public SwiftSegLocationEntityId() { } public String getClusterId() { return clusterId; } public void setClusterId(String clusterId) { this.clusterId = clusterId; } public String getSegmentId() { return segmentId; } public void setSegmentId(String segmentId) { this.segmentId = segmentId; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } SwiftSegLocationEntityId that = (SwiftSegLocationEntityId) o; if (clusterId != null ? !clusterId.equals(that.clusterId) : that.clusterId != null) { return false; } return segmentId != null ? segmentId.equals(that.segmentId) : that.segmentId == null; } @Override public int hashCode() { int result = clusterId != null ? clusterId.hashCode() : 0; result = 31 * result + (segmentId != null ? segmentId.hashCode() : 0); return result; } }
25.088235
93
0.628957
83d5453dc643066a8a23e1ad6627ee220df2888e
2,293
/** * Copyright (C) 2014-2015 LinkedIn Corp. (pinot-core@linkedin.com) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.linkedin.pinot.core.segment.creator.impl.fwd; import java.io.Closeable; import java.io.File; import java.util.Arrays; import org.apache.commons.io.FileUtils; import com.linkedin.pinot.common.data.FieldSpec; import com.linkedin.pinot.core.index.writer.impl.FixedBitSkipListSCMVWriter; import com.linkedin.pinot.core.segment.creator.ForwardIndexCreator; import com.linkedin.pinot.core.segment.creator.impl.V1Constants; public class MultiValueUnsortedForwardIndexCreator implements ForwardIndexCreator, Closeable { private final File forwardIndexFile; private final FieldSpec spec; private int maxNumberOfBits = 0; private FixedBitSkipListSCMVWriter mVWriter; public MultiValueUnsortedForwardIndexCreator(FieldSpec spec, File baseIndexDir, int cardinality, int numDocs, int totalNumberOfValues, boolean hasNulls) throws Exception { forwardIndexFile = new File(baseIndexDir, spec.getName() + V1Constants.Indexes.UN_SORTED_MV_FWD_IDX_FILE_EXTENTION); this.spec = spec; FileUtils.touch(forwardIndexFile); maxNumberOfBits = SingleValueUnsortedForwardIndexCreator.getNumOfBits(cardinality); mVWriter = new FixedBitSkipListSCMVWriter(forwardIndexFile, numDocs, totalNumberOfValues, maxNumberOfBits); } @Override public void index(int docId, Object e) { final Object[] entryArr = ((Object[]) e); Arrays.sort(entryArr); final int[] entries = new int[entryArr.length]; for (int i = 0; i < entryArr.length; i++) { entries[i] = ((Integer) entryArr[i]).intValue(); } mVWriter.setIntArray(docId, entries); } @Override public void close() { mVWriter.close(); } }
34.742424
120
0.756651
561181d98e39b7de3387c6bf34337f48ce35b9de
5,974
begin_unit|revision:0.9.5;language:Java;cregit-version:0.0.1 begin_comment comment|/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ end_comment begin_package DECL|package|org.apache.camel.component.file.remote package|package name|org operator|. name|apache operator|. name|camel operator|. name|component operator|. name|file operator|. name|remote package|; end_package begin_import import|import name|java operator|. name|io operator|. name|File import|; end_import begin_import import|import name|java operator|. name|text operator|. name|SimpleDateFormat import|; end_import begin_import import|import name|java operator|. name|util operator|. name|Date import|; end_import begin_import import|import name|org operator|. name|apache operator|. name|camel operator|. name|BindToRegistry import|; end_import begin_import import|import name|org operator|. name|apache operator|. name|camel operator|. name|builder operator|. name|RouteBuilder import|; end_import begin_import import|import name|org operator|. name|apache operator|. name|camel operator|. name|component operator|. name|mock operator|. name|MockEndpoint import|; end_import begin_import import|import name|org operator|. name|junit operator|. name|jupiter operator|. name|api operator|. name|BeforeEach import|; end_import begin_import import|import name|org operator|. name|junit operator|. name|jupiter operator|. name|api operator|. name|Test import|; end_import begin_import import|import static name|org operator|. name|apache operator|. name|camel operator|. name|test operator|. name|junit5 operator|. name|TestSupport operator|. name|deleteDirectory import|; end_import begin_import import|import static name|org operator|. name|junit operator|. name|jupiter operator|. name|api operator|. name|Assertions operator|. name|assertTrue import|; end_import begin_comment comment|/** * Unit test for FTP using expression (file language) */ end_comment begin_class DECL|class|FtpConsumerMoveExpressionTest specifier|public class|class name|FtpConsumerMoveExpressionTest extends|extends name|FtpServerTestSupport block|{ annotation|@ name|BindToRegistry argument_list|( literal|"myguidgenerator" argument_list|) DECL|field|guid specifier|private name|MyGuidGenerator name|guid init|= operator|new name|MyGuidGenerator argument_list|() decl_stmt|; DECL|method|getFtpUrl () specifier|private name|String name|getFtpUrl parameter_list|() block|{ return|return literal|"ftp://admin@localhost:" operator|+ name|getPort argument_list|() operator|+ literal|"/filelanguage?password=admin&delay=5000" return|; block|} annotation|@ name|Override annotation|@ name|BeforeEach DECL|method|setUp () specifier|public name|void name|setUp parameter_list|() throws|throws name|Exception block|{ name|super operator|. name|setUp argument_list|() expr_stmt|; name|deleteDirectory argument_list|( literal|"target/filelanguage" argument_list|) expr_stmt|; block|} annotation|@ name|Test DECL|method|testMoveUsingExpression () specifier|public name|void name|testMoveUsingExpression parameter_list|() throws|throws name|Exception block|{ name|MockEndpoint name|mock init|= name|getMockEndpoint argument_list|( literal|"mock:result" argument_list|) decl_stmt|; name|mock operator|. name|expectedBodiesReceived argument_list|( literal|"Reports" argument_list|) expr_stmt|; name|sendFile argument_list|( name|getFtpUrl argument_list|() argument_list|, literal|"Reports" argument_list|, literal|"report2.txt" argument_list|) expr_stmt|; name|assertMockEndpointsSatisfied argument_list|() expr_stmt|; comment|// give time for consumer to rename file name|Thread operator|. name|sleep argument_list|( literal|1000 argument_list|) expr_stmt|; name|String name|now init|= operator|new name|SimpleDateFormat argument_list|( literal|"yyyyMMdd" argument_list|) operator|. name|format argument_list|( operator|new name|Date argument_list|() argument_list|) decl_stmt|; name|File name|file init|= operator|new name|File argument_list|( name|FTP_ROOT_DIR operator|+ literal|"/filelanguage/backup/" operator|+ name|now operator|+ literal|"/123-report2.bak" argument_list|) decl_stmt|; name|assertTrue argument_list|( name|file operator|. name|exists argument_list|() argument_list|, literal|"File should have been renamed" argument_list|) expr_stmt|; block|} annotation|@ name|Override DECL|method|createRouteBuilder () specifier|protected name|RouteBuilder name|createRouteBuilder parameter_list|() throws|throws name|Exception block|{ return|return operator|new name|RouteBuilder argument_list|() block|{ specifier|public name|void name|configure parameter_list|() throws|throws name|Exception block|{ name|from argument_list|( name|getFtpUrl argument_list|() operator|+ literal|"&move=backup/${date:now:yyyyMMdd}/${bean:myguidgenerator}" operator|+ literal|"-${file:name.noext}.bak" argument_list|) operator|. name|to argument_list|( literal|"mock:result" argument_list|) expr_stmt|; block|} block|} return|; block|} DECL|class|MyGuidGenerator specifier|public class|class name|MyGuidGenerator block|{ DECL|method|guid () specifier|public name|String name|guid parameter_list|() block|{ return|return literal|"123" return|; block|} block|} block|} end_class end_unit
16.102426
810
0.798795
8ada1eb364e2afa3c082984b9125518e0a81525b
2,296
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.jackrabbit.core.observation; import java.util.Collection; /** * The <code>DispatchAction</code> class is a simple struct that defines what * <code>EventState</code>s should be dispatched to which * <code>EventConsumer</code>s. */ class DispatchAction { /** * The collection of <code>EventState</code>s */ private final EventStateCollection eventStates; /** * <code>EventStates</code> are dispatched to these * <code>EventConsumer</code>s. */ private final Collection<EventConsumer> eventConsumers; /** * Creates a new <code>DispatchAction</code> struct with * <code>eventStates</code> and <code>eventConsumers</code>. */ DispatchAction(EventStateCollection eventStates, Collection<EventConsumer> eventConsumers) { this.eventStates = eventStates; this.eventConsumers = eventConsumers; } /** * Returns a collection of {@link EventState}s to dispatch. * * @return a collection of {@link EventState}s to dispatch. */ EventStateCollection getEventStates() { return eventStates; } /** * Returns a <code>Collection</code> of {@link EventConsumer}s where * the events should be dispatched to. * * @return a <code>Collection</code> of {@link EventConsumer}s. */ Collection<EventConsumer> getEventConsumers() { return eventConsumers; } }
34.268657
97
0.6777
673dc1a3cf3b8c0df5cdcdcc4f13eaa39733f83c
126
package cn.skyui.practice.bytecode; public class ByteDemo { private int a = 1; protected void testMethod() { } }
15.75
35
0.666667
be3bf1c3f5b247eea6573cc79c9c1c84dd57eb4d
176
package ingredients.cobertura; public class Cebola implements Cobertura { @Override public String getNome() { // TODO Auto-generated method stub return "Cebola"; } }
14.666667
42
0.732955
ae2d7a58848726c7dc92ae39bbbb582caf6bdb89
1,332
/* * Copyright 2007-2021, CIIC Guanaitong, Co., Ltd. * All rights reserved. */ package com.ciicgat.api.core.model; /** * Created by August.Zhou on 2017/7/31 10:36. */ public class TestBean { String text; int integer; public TestBean(String text, int integer) { this.text = text; this.integer = integer; } public TestBean() { } public String getText() { return text; } public void setText(String text) { this.text = text; } public int getInteger() { return integer; } public void setInteger(int integer) { this.integer = integer; } @Override public boolean equals(Object o) { if (this == o) return true; if (!(o instanceof TestBean)) return false; TestBean testBean = (TestBean) o; if (integer != testBean.integer) return false; return text != null ? text.equals(testBean.text) : testBean.text == null; } @Override public int hashCode() { int result = text != null ? text.hashCode() : 0; result = 31 * result + integer; return result; } @Override public String toString() { return "TestBean{" + "text='" + text + '\'' + ", integer=" + integer + '}'; } }
20.181818
81
0.545045
0d37d0725ecfc730876f7786b7697d87e6d42f03
2,145
package se.fnord.jamon.internal; import java.util.ArrayDeque; import java.util.Collection; import java.util.Deque; import java.util.Iterator; import se.fnord.jamon.Node; import se.fnord.jamon.Path; public class PathStack { private static final Holder EMPTY = new Holder(null, new ArrayDeque<Node>(0)); private static final class Holder { public final Path parent; public final Deque<Node> children; public Holder(Path parent, Deque<Node> children) { this.parent = parent; this.children = children; } public void buildString(StringBuilder sb) { sb.append("["); Iterator<Node> iterator = children.iterator(); Node n; if (iterator.hasNext()) { n = iterator.next(); sb.append(parent.forChild(n).toString()); while (iterator.hasNext()) { n = iterator.next(); sb.append(", ").append(parent.forChild(n).toString()); } } sb.append("]"); } } private final Deque<Holder> queue = new ArrayDeque<>(); private Holder current = EMPTY; public void prepend(Path parent, Collection<Node> children) { if (!children.isEmpty()) { if (!current.children.isEmpty()) queue.addFirst(current); current = new Holder(parent, new ArrayDeque<>(children)); } } public void append(Path parent, Collection<Node> children) { if (!children.isEmpty()) { if (queue.isEmpty() && current.children.isEmpty()) current = new Holder(parent, new ArrayDeque<>(children)); else queue.addLast(new Holder(parent, new ArrayDeque<>(children))); } } public Path poll() { Node c = current.children.poll(); if (c != null) return current.parent.forChild(c); Holder next = queue.poll(); if (next == null) { current = EMPTY; return null; } current = next; c = current.children.poll(); return current.parent.forChild(c); } public boolean isEmpty() { return current.children.isEmpty() && queue.isEmpty(); } @Override public String toString() { StringBuilder b = new StringBuilder(); b.append("PathStack["); current.buildString(b); for (Holder h : queue) { b.append(", "); h.buildString(b); } b.append("]"); return b.toString(); } }
23.833333
79
0.664336
0ae671085d1621f3aadf470d4c8c90f3217f40ef
1,328
package com.binlee.design.flyweight; /** * @author binli sleticalboy@gmail.com * created by IDEA 2020/11/16 */ public final class SharedBike { private static final int MAX_SIZE = 10; private static final SharedBike[] POOL = new SharedBike[MAX_SIZE]; private boolean inUse = false; public String qrCode; private SharedBike() { } public static SharedBike obtain() { synchronized (POOL) { for (int i = MAX_SIZE - 1; i >= 0; i--) { final SharedBike bike = POOL[i]; if (bike != null && !bike.inUse) { bike.inUse = true; POOL[i] = null; return bike; } } return new SharedBike(); } } public void recycle() { synchronized (POOL) { for (int i = 0; i < MAX_SIZE; i++) { final SharedBike bike = POOL[i]; if (bike == null) { inUse = false; qrCode = null; POOL[i] = this; } } } } @Override public String toString() { return "SharedBike{@" + hashCode() + ", inUse=" + inUse + ", qrCode='" + qrCode + '\'' + '}'; } }
25.056604
70
0.448795
2cd846ecc85f2cfd73b99c04cf373370affe0112
1,492
package leetcode.weekly_contests.weekly_197; public class P_1515 { private static final int[][] DIRS = { { 0, 1 }, { 0, -1 }, { 1, 0 }, { -1, 0 } }; double lowerLimit = 1e-5; public double getMinDistSum(int[][] positions) { final int n = positions.length; final double[] curr = { 0.0, 0.0 }; for (int[] position : positions) { curr[0] += position[0]; curr[1] += position[1]; } curr[0] /= n; curr[1] /= n; double minDist = distSum(curr, positions, n); double testDistance = 1; outer: while (testDistance > lowerLimit) { for (int[] dir : DIRS) { final double[] newPoint = { curr[0] + testDistance * dir[0], curr[1] + testDistance * dir[1] }; final double newD = distSum(newPoint, positions, n); if (newD < minDist) { minDist = newD; curr[0] = newPoint[0]; curr[1] = newPoint[1]; continue outer; } } testDistance /= 2; } return minDist; } private static double distSum(double[] p, int[][] positions, int n) { double sum = 0; for (int[] pos : positions) { final double distx = Math.abs(pos[0] - p[0]); final double disty = Math.abs(pos[1] - p[1]); sum += Math.hypot(distx, disty); } return sum; } }
31.744681
111
0.474531
776741067369cb40b146846d4f2790b6ce514bd4
479
package com.xiao.aop.advisor; import org.aopalliance.aop.Advice; import org.springframework.aop.Pointcut; import org.springframework.aop.PointcutAdvisor; public class MyBeforeAdvisor implements PointcutAdvisor { @Override public Pointcut getPointcut() { //自定义切点 return null; } @Override public Advice getAdvice() { //自定义增强器 return null; } @Override public boolean isPerInstance() { return true; } }
19.16
57
0.663883
e824421dc99134a8849faa4f59c3b0239101f53c
303
package wy.rest.addons.zcgl.cpncata.dao; import com.baomidou.mybatisplus.mapper.BaseMapper; import wy.rest.addons.zcgl.cpncata.model.Xyd_cpn_cata; /** * 入驻企业Mapper接口 * * @author wyframe * @Date 2017-09-06 18:41:54 */ public interface Xyd_cpn_cataMapper extends BaseMapper<Xyd_cpn_cata> { }
18.9375
71
0.752475
d439987e8c6ce825c5c800b0977ee309a74965db
2,549
/* * Copyright 2019 Miroslav Pokorny (github.com/mP1) * * 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 walkingkooka.net; /** * A problem that occurred while parsing and validating a {@link HostAddress host address}. */ abstract public class HostAddressProblem { /** * {@see HostAddressIncompleteProblem} */ public static HostAddressProblem incomplete() { return HostAddressIncompleteProblem.INSTANCE; } /** * {@see HostAddressInvalidCharacterProblem} */ public static HostAddressProblem invalidCharacter(final int at) { return HostAddressInvalidCharacterProblem.with(at); } /** * {@see HostAddressInvalidLengthProblem} */ public static HostAddressProblem invalidLength(final int at) { return HostAddressInvalidLengthProblem.with(at); } /** * {@see HostAddressInvalidValueProblem} */ public static HostAddressProblem invalidValue(final int at) { return HostAddressInvalidValueProblem.with(at); } /** * {@see HostAddressProbablyIp4Problem} */ public static HostAddressProblem probablyIp4() { return HostAddressProbablyIp4Problem.INSTANCE; } /** * {@see HostAddressProbablyIp6Problem} */ public static HostAddressProblem probablyIp6() { return HostAddressProbablyIp6Problem.INSTANCE; } /** * Package private to limit sub classing. */ HostAddressProblem() { super(); } /** * Reports by throwing an exception. */ abstract void report(final String message); /** * Builds a message using the address. */ abstract public String message(final String address); /** * When true do not try the next parse method. */ abstract boolean stopTrying(); /** * Returns the relative priority of this problem. */ abstract int priority(); /** * Force sub classes to implement. */ @Override abstract public String toString(); }
25.49
91
0.666928
0ec1fb869dda6413878d148653085e2c7d76af92
371
package myproject; public class Average { public static void main(String[] args) { long n; int i; double res=0; n=args.length; for (i=0; i<n; i++) { res = res + Integer.parseInt(args[i]); } System.out.println("Average of ("); for (i=0; i<n-1; i++) { System.out.println(args[i]+ ","); } System.out.println(args[i]+")" +res/n); } }
15.458333
41
0.560647
69c2a28ae02d6c391c8de0851f7fd5143e09aa03
633
package June2021AppleLeetcode; import java.util.Arrays; public class _0239SlidingWindowMaximum { public static void main(String[] args) { System.out.println(Arrays.toString(maxSlidingWindow(new int[] { 1, 3, -1, -3, 5, 3, 6, 7 }, 3))); System.out.println(Arrays.toString(maxSlidingWindow(new int[] { 1 }, 1))); System.out.println(Arrays.toString(maxSlidingWindow(new int[] { 1, -1 }, 1))); System.out.println(Arrays.toString(maxSlidingWindow(new int[] { 9, 11 }, 2))); System.out.println(Arrays.toString(maxSlidingWindow(new int[] { 4, -2 }, 2))); } public static int[] maxSlidingWindow(int[] nums, int k) { } }
30.142857
99
0.690363
4fa9d726c461c6a53d44e3abbaa7f9037c7e2dfe
1,239
package playstudios.security.filters; import com.auth0.jwt.JWT; import com.auth0.jwt.algorithms.Algorithm; import org.springframework.security.authentication.AuthenticationManager; import org.springframework.security.core.Authentication; import org.springframework.security.web.authentication.www.BasicAuthenticationFilter; import playstudios.models.internal.User; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.util.Date; import static playstudios.security.SecurityConstants.*; public class JWTAuthenticationFilter extends BasicAuthenticationFilter { public JWTAuthenticationFilter(AuthenticationManager authenticationManager) { super(authenticationManager); } @Override protected void onSuccessfulAuthentication(HttpServletRequest request, HttpServletResponse response, Authentication authResult) { String jwtToken = JWT.create() .withSubject(((User) authResult.getPrincipal()).getName()) .withExpiresAt(new Date(System.currentTimeMillis() + EXPIRATION_TIME_MS)) .sign(Algorithm.HMAC512(SECRET.getBytes())); response.addHeader(AUTHORIZATION_HEADER, TOKEN_PREFIX + jwtToken); } }
37.545455
132
0.782889
67b6730d9b1548d19df531999cb7a3e1a6f2a420
6,368
/** * Copyright (C) 2014 Telenor Digital AS * * 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.comoyo.commons.logging.context; import java.io.UnsupportedEncodingException; import java.util.Map; import java.util.MissingResourceException; import java.util.ResourceBundle; import java.util.logging.ErrorManager; import java.util.logging.Filter; import java.util.logging.Formatter; import java.util.logging.Handler; import java.util.logging.Level; import java.util.logging.LogRecord; import java.util.logging.Logger; /** * Wrapper class that will enrich log messages passing through wrapped * {@link Handler}s with context information available through the * {@link LoggingContext} interface. * */ public class ContextAddingHandler extends Handler { private final Handler wrapped; private ContextAddingHandler(final Handler wrapped) { this.wrapped = wrapped; } /** * Enrich messages passing through a single handler with context information. * * @param handler the underlying logging handler * @return a version of the given handler that also logs context information */ public static Handler wrapHandler(final Handler handler) { return new ContextAddingHandler(handler); } /** * Enrich messages passing through all {@link Handler}s of a given * logger with context information. This modifies the set of * handlers for the given logger. Handlers added after this * function has been called are not affected. Calling this * function multiple times is supported, and will not affect * already modified handlers in this logger's handler set. * * @param logger the logger to modify */ public static void wrapAllHandlers(final Logger logger) { final Handler[] handlers = logger.getHandlers(); for (final Handler handler : handlers) { if (!(handler instanceof ContextAddingHandler)) { logger.removeHandler(handler); logger.addHandler(wrapHandler(handler)); } } } private static String escapeString(final String string) { return string.replace("\\", "\\\\").replace("\n", "\\n").replace("\"", "\\\""); } private static LogRecord addContextToRecord(final LogRecord original) { final Map<String, String> context = original.getThrown() == null ? LoggingContext.getContext() : LoggingContext.getLastEnteredContext(); if (context == null) { return original; } final ResourceBundle bundle = original.getResourceBundle(); final String message = original.getMessage(); String localized = message; if (message == null) { localized = ""; } else { if (bundle != null) { try { localized = bundle.getString(message); } catch (MissingResourceException e) { localized = message; } } else { localized = message; } } final StringBuilder sb = new StringBuilder(localized); sb.append(" | context: {"); boolean first = true; for (Map.Entry<String, String> entry : context.entrySet()) { if (!first) { sb.append(", "); } sb.append("\"") .append(escapeString(entry.getKey())) .append("\": \"") .append(escapeString(entry.getValue())) .append("\""); first = false; } sb.append("}"); final LogRecord record = new LogRecord(original.getLevel(), sb.toString()); record.setLevel(original.getLevel()); record.setLoggerName(original.getLoggerName()); record.setMillis(original.getMillis()); record.setParameters(original.getParameters()); record.setSequenceNumber(original.getSequenceNumber()); record.setSourceClassName(original.getSourceClassName()); record.setSourceMethodName(original.getSourceMethodName()); record.setThreadID(original.getThreadID()); record.setThrown(original.getThrown()); return record; } @Override public void publish(final LogRecord record) { wrapped.publish(addContextToRecord(record)); } @Override public void close() { wrapped.close(); } @Override public void flush() { wrapped.flush(); } @Override public String getEncoding() { return wrapped.getEncoding(); } @Override public ErrorManager getErrorManager() { return wrapped.getErrorManager(); } @Override public Filter getFilter() { return wrapped.getFilter(); } @Override public Formatter getFormatter() { return wrapped.getFormatter(); } @Override public Level getLevel() { return wrapped.getLevel(); } @Override public boolean isLoggable(final LogRecord record) { return wrapped.isLoggable(record); } @Override public void setEncoding(final String encoding) throws UnsupportedEncodingException { wrapped.setEncoding(encoding); } @Override public void setErrorManager(final ErrorManager em) { wrapped.setErrorManager(em); } @Override public void setFilter(final Filter newFilter) { wrapped.setFilter(newFilter); } @Override public void setFormatter(final Formatter newFormatter) { wrapped.setFormatter(newFormatter); } @Override public void setLevel(final Level newLevel) { wrapped.setLevel(newLevel); } }
27.929825
87
0.62343
e759a55bbc7b8981aa9222fdc6e140c5aec4245e
2,618
package org.karlsland.m3g; public class AnimationTrack extends Object3D { public final static int ALPHA = 256; public final static int AMBIENT_COLOR = 257; public final static int COLOR = 258; public final static int CROP = 259; public final static int DENSITY = 260; public final static int DIFFUSE_COLOR = 261; public final static int EMISSIVE_COLOR = 262; public final static int FAR_DISTANCE = 263; public final static int FIELD_OF_VIEW = 264; public final static int INTENSITY = 265; public final static int MORPH_WEIGHTS = 266; public final static int NEAR_DISTANCE = 267; public final static int ORIENTATION = 268; public final static int PICKABILITY = 269; public final static int SCALE = 270; public final static int SHININESS = 271; public final static int SPECULAR_COLOR = 272; public final static int SPOT_ANGLE = 273; public final static int SPOT_EXPONENT = 274; public final static int TRANSLATION = 275; public final static int VISIBILITY = 276; native private void jni_initialize (KeyframeSequence keyframeSequence, int property); native private void jni_finalize (); native private AnimationController jni_getController (); native private KeyframeSequence jni_getKeyframeSequence (); native private int jni_getTargetProperty (); native private void jni_setController (AnimationController controller); native private String jni_print (); private KeyframeSequence keyframeSequence; private AnimationController animationController; public AnimationTrack (KeyframeSequence keyframeSequence, int property) { this.keyframeSequence = keyframeSequence; this.animationController = null; jni_initialize (keyframeSequence, property); } @Override protected void finalize () { jni_finalize (); } public AnimationController getController () { return jni_getController (); } public KeyframeSequence getKeyframeSequence () { return jni_getKeyframeSequence (); } public int getTargetProperty () { return jni_getTargetProperty (); } public void setController (AnimationController controller) { jni_setController (controller); this.animationController = controller; } @Override public String toString () { return jni_print (); } }
36.873239
113
0.65699
c577ec74209ee3b9bfb50a38a7224618f9568fd2
362
package com.leeseojune53.citylife.Exceptions; import org.springframework.http.HttpStatus; import org.springframework.web.bind.annotation.ResponseStatus; @ResponseStatus(value = HttpStatus.CONFLICT, reason = "Overlap") public class UserAlreadySignupExceptions extends RuntimeException{ public UserAlreadySignupExceptions(){ super("아이디중복."); } }
30.166667
66
0.792818
d0d5910ca81dfa4e70aa8cb6532ac6b852e668ff
181
package com.smatechnologies.opcon.commons.serializer; /** * @author Pierre PINON */ public interface ISerializer<T> { String serialize(T value) throws SerializeException; }
18.1
56
0.751381
3558050109cce3f66bdef899f3589d379e1a62bc
933
package com.richer.thirteenwater.Activity; import android.content.Intent; import androidx.appcompat.app.AppCompatActivity; import android.os.Bundle; import android.view.View; import android.widget.Button; import android.widget.TextView; import com.richer.thirteenwater.R; public class RuleActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_rule); Intent intent = getIntent(); String name = intent.getStringExtra("name"); TextView tv_name = findViewById(R.id.message_rule); tv_name.setText(name); Button returnButton = findViewById(R.id.return_rule); returnButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { finish(); } }); } }
26.657143
68
0.687031
9f63500fc8535a2608fb8729f6d18a59f6bbea5c
4,196
/* * Copyright (C) 2009 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package android.view; /** * Constants to be used to perform haptic feedback effects via * {@link View#performHapticFeedback(int)} */ public class HapticFeedbackConstants { private HapticFeedbackConstants() {} /** * The user has performed a long press on an object that is resulting * in an action being performed. */ public static final int LONG_PRESS = 0; /** * The user has pressed on a virtual on-screen key. */ public static final int VIRTUAL_KEY = 1; /** * The user has pressed a soft keyboard key. */ public static final int KEYBOARD_TAP = 3; /** * The user has pressed either an hour or minute tick of a Clock. */ public static final int CLOCK_TICK = 4; /** * The user has pressed either a day or month or year date of a Calendar. * @hide */ public static final int CALENDAR_DATE = 5; /** * The user has performed a context click on an object. */ public static final int CONTEXT_CLICK = 6; /** * The user has pressed a virtual or software keyboard key. */ public static final int KEYBOARD_PRESS = KEYBOARD_TAP; /** * The user has released a virtual keyboard key. */ public static final int KEYBOARD_RELEASE = 7; /** * The user has released a virtual key. */ public static final int VIRTUAL_KEY_RELEASE = 8; /** * The user has performed a selection/insertion handle move on text field. */ public static final int TEXT_HANDLE_MOVE = 9; /** * The user unlocked the device * @hide */ public static final int ENTRY_BUMP = 10; /** * The user has moved the dragged object within a droppable area. * @hide */ public static final int DRAG_CROSSING = 11; /** * The user has started a gesture (e.g. on the soft keyboard). */ public static final int GESTURE_START = 12; /** * The user has finished a gesture (e.g. on the soft keyboard). */ public static final int GESTURE_END = 13; /** * The user's squeeze crossed the gesture's initiation threshold. * @hide */ public static final int EDGE_SQUEEZE = 14; /** * The user's squeeze crossed the gesture's release threshold. * @hide */ public static final int EDGE_RELEASE = 15; /** * A haptic effect to signal the confirmation or successful completion of a user * interaction. */ public static final int CONFIRM = 16; /** * A haptic effect to signal the rejection or failure of a user interaction. */ public static final int REJECT = 17; /** * The phone has booted with safe mode enabled. * This is a private constant. Feel free to renumber as desired. * @hide */ public static final int SAFE_MODE_ENABLED = 10001; /** * Invocation of the voice assistant via hardware button. * @hide */ public static final int ASSISTANT_BUTTON = 10002; /** * Flag for {@link View#performHapticFeedback(int, int) * View.performHapticFeedback(int, int)}: Ignore the setting in the * view for whether to perform haptic feedback, do it always. */ public static final int FLAG_IGNORE_VIEW_SETTING = 0x0001; /** * Flag for {@link View#performHapticFeedback(int, int) * View.performHapticFeedback(int, int)}: Ignore the global setting * for whether to perform haptic feedback, do it always. */ public static final int FLAG_IGNORE_GLOBAL_SETTING = 0x0002; }
27.788079
84
0.649666
e9ca02abb4d39b46af08caef68d673b4cc969abd
473
package com.quorum.tessera.p2p; import static org.mockito.Mockito.mock; import com.quorum.tessera.config.Config; import com.quorum.tessera.core.api.ServiceFactory; import com.quorum.tessera.transaction.TransactionManager; public class MockServiceFactory implements ServiceFactory { @Override public TransactionManager transactionManager() { return mock(TransactionManager.class); } @Override public Config config() { return mock(Config.class); } }
22.52381
59
0.782241
9f6bf46331fdf4bbece8de5a22c1368fcd652631
14,934
package com.example.ownclient; import androidx.annotation.NonNull; import androidx.appcompat.app.AppCompatActivity; import android.annotation.SuppressLint; import android.app.AlertDialog; import android.app.ProgressDialog; import android.content.DialogInterface; import android.graphics.Point; import android.net.ConnectivityManager; import android.net.NetworkInfo; import android.os.AsyncTask; import android.os.Bundle; import android.os.Handler; import android.os.Looper; import android.os.Message; import android.sax.StartElementListener; import android.view.MotionEvent; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.TextView; import android.widget.Toast; import com.erz.joysticklibrary.JoyStick; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.IOException; import java.net.InetSocketAddress; import java.net.Socket; import java.net.SocketAddress; import java.net.SocketException; import java.net.SocketTimeoutException; import java.util.Timer; import java.util.TimerTask; public class MainActivity extends AppCompatActivity { private TextView mtv_status; private Button mbtn_connect; private Button mbtn_quit; private Button mbtn_showMsg; private Button mbtn_leftClick; private Button mbtn_rightClick; private Button mbtn_scrollUp; private Button mbtn_scrollDown; private EditText sMsg; private ProgressDialog pro; private Socket socket = null; private ConnectivityManager cm; private DisplayHandler h; private Timer tm; private int PORT = 9000; private int Delay = 3000; private int rx; private int ry; private final Point pt = new Point(0, 0); private String IP = "10.0.2.2"; /*-------------------- LOCAL IP --------------------*/ private boolean isConnected = false; private boolean isWifi = false; private boolean dialogShow = false; //SEND final static int CON=0x01; final static int MOUSE_REQ=0x02; final static int SEVER_EXIT=0x04; final static int SHOW_MESSAGE=0x08; final static int LEFT_CLICK=0x16; final static int RIGHT_CLICK=0x32; final static int SCROLL_UP=0x64; final static int SCROLL_DOWN=0x128; //RECV final static int MOUSE_POS=0x01; public void confirmDialog(final String msg) { Handler mHandler = new Handler(Looper.getMainLooper()); mHandler.postDelayed(new Runnable() { @Override public void run() { AlertDialog.Builder alert = new AlertDialog.Builder(MainActivity.this); alert.setPositiveButton("확인", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { dialog.dismiss(); dialogShow = false; } }); alert.setMessage(msg); alert.show(); dialogShow = true; } }, 0); } class DisplayHandler extends Handler{ @Override public void handleMessage(@NonNull Message msg) { super.handleMessage(msg); if(msg.what==0){ pro.cancel(); } } } class NetworkThread extends Thread { @Override public void run() { super.run(); SocketAddress socketAddress = new InetSocketAddress(IP, PORT); socket = new Socket(); try { socket.setSoTimeout(Delay); socket.connect(socketAddress, Delay); tm = new Timer(); tm.schedule(new MouseTimer(), 0, 100); h.sendEmptyMessage(0); } catch (SocketTimeoutException e) { pro.dismiss(); if (!dialogShow) { confirmDialog("Connection Failed as TimeOut"); return; } } catch (SocketException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } } class MoveMouseThread extends Thread { @Override public void run() { super.run(); try { DataOutputStream dos = new DataOutputStream(socket.getOutputStream()); dos.writeInt(MOUSE_REQ); dos.writeInt(pt.x); dos.writeInt(pt.y); } catch (IOException e) { e.printStackTrace(); } } } class SendDialog extends Thread { String m_Text; @Override public void run() { super.run(); try { DataOutputStream dos = new DataOutputStream(socket.getOutputStream()); dos.writeInt(SHOW_MESSAGE); dos.writeUTF(sMsg.getText().toString()); } catch (IOException e) { e.printStackTrace(); } } } class LeftClick extends Thread { @Override public void run() { super.run(); try { DataOutputStream dos = new DataOutputStream(socket.getOutputStream()); dos.writeInt(LEFT_CLICK); } catch (IOException e) { e.printStackTrace(); } } } class RightClick extends Thread { @Override public void run() { super.run(); try { DataOutputStream dos = new DataOutputStream(socket.getOutputStream()); dos.writeInt(RIGHT_CLICK); } catch (IOException e) { e.printStackTrace(); } } } class ScrollUp extends Thread { @Override public void run() { super.run(); try { DataOutputStream dos = new DataOutputStream(socket.getOutputStream()); dos.writeInt(SCROLL_UP); } catch (IOException e) { e.printStackTrace(); } } } class ScrollDown extends Thread { @Override public void run() { super.run(); try { DataOutputStream dos = new DataOutputStream(socket.getOutputStream()); dos.writeInt(SCROLL_DOWN); } catch (IOException e) { e.printStackTrace(); } } } class MouseTimer extends TimerTask { @Override public void run() { if (socket != null) { try { DataInputStream dis = new DataInputStream(socket.getInputStream()); DataOutputStream dos = new DataOutputStream(socket.getOutputStream()); dos.writeInt(CON); // SendOpcode int opcode = dis.readInt(); // ReadOpcode if (opcode == MOUSE_POS) { rx = dis.readInt(); ry = dis.readInt(); } Handler mHandler = new Handler(Looper.getMainLooper()); mHandler.postDelayed(new Runnable() { @Override public void run() { mtv_status.setText(new String("Status: " + isConnected + ", " + "Wifi:" + isWifi + ", x:" + rx + ", y:" + ry)); } }, 0); } catch (IOException e) { e.printStackTrace(); } } } } class ServerExitThread extends Thread { @Override public void run() { super.run(); tm.cancel(); try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } DataOutputStream dos = null; try { dos = new DataOutputStream(socket.getOutputStream()); dos.writeInt(SEVER_EXIT); socket.close(); } catch (IOException e) { e.printStackTrace(); } } } @SuppressLint("ClickableViewAccessibility") @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); mtv_status = findViewById(R.id.textView); mbtn_connect = findViewById(R.id.button); mbtn_quit = findViewById(R.id.button2); mbtn_showMsg = findViewById(R.id.button5); mbtn_leftClick = findViewById(R.id.button3); mbtn_rightClick = findViewById(R.id.button4); mbtn_scrollUp = findViewById(R.id.button6); mbtn_scrollDown = findViewById(R.id.button7); sMsg = findViewById(R.id.editText3); mbtn_connect.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { pro = ProgressDialog.show(MainActivity.this,null,"Connecting.."); NetworkThread thread = new NetworkThread(); thread.start(); } }); mbtn_quit.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if (!dialogShow) { if (socket == null) { confirmDialog("Connect First"); return; } } else return; ServerExitThread thread = new ServerExitThread(); thread.start(); } }); mbtn_showMsg.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if (!dialogShow) { if (socket == null) { confirmDialog("Connect First"); return; } } else return; SendDialog thread = new SendDialog(); thread.start(); } }); mbtn_leftClick.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if (!dialogShow) { if (socket == null) { confirmDialog("Connect First"); return; } } else return; LeftClick thread = new LeftClick(); thread.start(); } }); mbtn_rightClick.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if (!dialogShow) { if (socket == null) { confirmDialog("Connect First"); return; } } else return; RightClick thread = new RightClick(); thread.start(); } }); mbtn_scrollUp.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if (!dialogShow) { if (socket == null) { confirmDialog("Connect First"); return; } } else return; ScrollUp thread = new ScrollUp(); thread.start(); } }); mbtn_scrollDown.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if (!dialogShow) { if (socket == null) { confirmDialog("Connect First"); return; } } else return; ScrollDown thread = new ScrollDown(); thread.start(); } }); JoyStick joyStick = (JoyStick) findViewById(R.id.joy1); JoyStick.JoyStickListener jl = new JoyStick.JoyStickListener() { @Override public void onMove(JoyStick joyStick, double angle, double power, int direction) { if (!dialogShow) { if (socket == null) { confirmDialog("Connect First"); return; } } else return; switch(direction) { case JoyStick.DIRECTION_CENTER: break; case JoyStick.DIRECTION_LEFT: { pt.x--; break; } case JoyStick.DIRECTION_LEFT_UP: { pt.x--; pt.y--; break; } case JoyStick.DIRECTION_UP: { pt.y--; break; } case JoyStick.DIRECTION_UP_RIGHT: { pt.x++; pt.y--; break; } case JoyStick.DIRECTION_RIGHT: { pt.x++; break; } case JoyStick.DIRECTION_RIGHT_DOWN: { pt.x++; pt.y++; break; } case JoyStick.DIRECTION_DOWN: { pt.y++; break; } case JoyStick.DIRECTION_DOWN_LEFT: { pt.x--; pt.y++; break; } } MoveMouseThread thread = new MoveMouseThread(); thread.start(); return; } @Override public void onTap() { } @Override public void onDoubleTap() { } }; joyStick.setListener(jl); joyStick.setOnTouchListener(new JoyStick.OnTouchListener() { @Override public boolean onTouch(View v, MotionEvent event) { int action = event.getAction(); if (action == MotionEvent.ACTION_UP) pt.set(0, 0); return false; } }); cm = (ConnectivityManager)getSystemService(CONNECTIVITY_SERVICE); NetworkInfo activeNetwork = cm.getActiveNetworkInfo(); isConnected = activeNetwork != null && activeNetwork.isConnectedOrConnecting(); isWifi = activeNetwork.getType() == ConnectivityManager.TYPE_WIFI; mtv_status.setText("Status: "+isConnected+", "+"Wifi:"+isWifi); h = new DisplayHandler(); } }
33.78733
140
0.496987
8da9ee615ebea33341cdebe7b335fd2b6b1f5e5d
5,089
/* * Copyright (c) 2012 Jan Kotek * * 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.mapdb.store.legacy; import org.mapdb.CC; import org.mapdb.io.DataOutput2ByteArray; import org.mapdb.ser.Serializer; import org.mapdb.ser.Serializers; import org.mapdb.store.Store; import java.io.IOException; import java.nio.ByteBuffer; import java.util.Arrays; import java.util.Iterator; import java.util.List; import java.util.concurrent.CopyOnWriteArrayList; import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReentrantLock; import java.util.concurrent.locks.ReentrantReadWriteLock; import java.util.logging.Logger; /** * Low level record store. */ public abstract class Store2 implements Store { protected static final Logger LOG = Logger.getLogger(Store.class.getName()); public static final int VOLUME_CHUNK_SHIFT = 20; // 1 MB protected final static int CHECKSUM_FLAG_MASK = 1; protected final static int COMPRESS_FLAG_MASK = 1<<2; protected final static int ENCRYPT_FLAG_MASK = 1<<3; protected static final int CHUNK_SIZE = 1<< VOLUME_CHUNK_SHIFT; protected static final int CHUNK_SIZE_MOD_MASK = CHUNK_SIZE -1; public abstract long getMaxRecid(); public abstract ByteBuffer getRaw(long recid); public abstract Iterator<Long> getFreeRecids(); public abstract void updateRaw(long recid, ByteBuffer data); /** returns maximal store size or `0` if there is no limit */ public abstract long getSizeLimit(); /** returns current size occupied by physical store (does not include index). It means file allocated by physical file */ public abstract long getCurrSize(); /** returns free size in physical store (does not include index). */ public abstract long getFreeSize(); /** get some statistics about store. This may require traversing entire store, so it can take some time.*/ public abstract String calculateStatistics(); public void printStatistics(){ System.out.println(calculateStatistics()); } protected Lock serializerPojoInitLock = new ReentrantLock(); protected final ReentrantLock structuralLock = new ReentrantLock(); protected final ReentrantReadWriteLock newRecidLock = new ReentrantReadWriteLock(); protected final ReentrantReadWriteLock locks = new ReentrantReadWriteLock(); protected void lockAllWrite() { newRecidLock.writeLock().lock(); locks.writeLock().lock(); structuralLock.lock(); } protected void unlockAllWrite() { structuralLock.unlock(); locks.writeLock().unlock(); newRecidLock.writeLock().unlock(); } protected <A> DataOutput2ByteArray serialize(A value, Serializer<A> serializer){ if(value==null) return null; DataOutput2ByteArray out = newDataOut2(); serializer.serialize(out,value); if(out.pos>0){ if(CC.PARANOID)try{ //check that array is the same after deserialization DataInput2Exposed inp = new DataInput2Exposed(ByteBuffer.wrap(Arrays.copyOf(out.buf,out.pos))); byte[] decompress = deserialize(Serializers.BYTE_ARRAY_NOSIZE,out.pos,inp); DataOutput2ByteArray expected = newDataOut2(); serializer.serialize(expected,value); byte[] expected2 = Arrays.copyOf(expected.buf, expected.pos); //check arrays equals assert(Arrays.equals(expected2,decompress)); }catch(Exception e){ throw new RuntimeException(e); } } return out; } protected DataOutput2ByteArray newDataOut2() { return new DataOutput2ByteArray(); } protected <A> A deserialize(Serializer<A> serializer, int size, DataInput2Exposed di) throws IOException { int start = di.pos; A ret = serializer.deserialize(di); if(size+start>di.pos) throw new AssertionError("data were not fully read, check your serializer "); if(size+start<di.pos) throw new AssertionError("data were read beyond record size, check your serializer"); return ret; } protected int expectedMasks(){ return 0; } List<Runnable> closeListeners = new CopyOnWriteArrayList<Runnable>(); public void closeListenerRegister(Runnable closeListener) { closeListeners.add(closeListener); } public void closeListenerUnregister(Runnable closeListener) { closeListeners.remove(closeListener); } }
32.414013
125
0.693653
b08d58d1b481f446d70759df100e015e3a61e4c1
1,886
/* ---------------------------------------------------------------------------- * This file was automatically generated by SWIG (http://www.swig.org). * Version 3.0.10 * * Do not make changes to this file unless you know what you are doing--modify * the SWIG interface file instead. * ----------------------------------------------------------------------------- */ package com.google.ortools.constraintsolver; public class SolutionPool extends BaseObject { private transient long swigCPtr; protected SolutionPool(long cPtr, boolean cMemoryOwn) { super(operations_research_constraint_solverJNI.SolutionPool_SWIGUpcast(cPtr), cMemoryOwn); swigCPtr = cPtr; } protected static long getCPtr(SolutionPool obj) { return (obj == null) ? 0 : obj.swigCPtr; } protected void finalize() { delete(); } public synchronized void delete() { if (swigCPtr != 0) { if (swigCMemOwn) { swigCMemOwn = false; operations_research_constraint_solverJNI.delete_SolutionPool(swigCPtr); } swigCPtr = 0; } super.delete(); } public void Initialize(Assignment assignment) { operations_research_constraint_solverJNI.SolutionPool_Initialize(swigCPtr, this, Assignment.getCPtr(assignment), assignment); } public void RegisterNewSolution(Assignment assignment) { operations_research_constraint_solverJNI.SolutionPool_RegisterNewSolution(swigCPtr, this, Assignment.getCPtr(assignment), assignment); } public void GetNextSolution(Assignment assignment) { operations_research_constraint_solverJNI.SolutionPool_GetNextSolution(swigCPtr, this, Assignment.getCPtr(assignment), assignment); } public boolean SyncNeeded(Assignment local_assignment) { return operations_research_constraint_solverJNI.SolutionPool_SyncNeeded(swigCPtr, this, Assignment.getCPtr(local_assignment), local_assignment); } }
34.290909
148
0.694062
46b0241a8c79973d12370ac6f057ba3c688d0c4e
11,188
package org.zky.zky.widget.surfaceview; import android.content.Context; import android.content.res.TypedArray; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.Paint; import android.graphics.Point; import android.graphics.PorterDuff; import android.graphics.PorterDuffXfermode; import android.graphics.Rect; import android.util.AttributeSet; import android.util.Log; import android.view.MotionEvent; import android.view.SurfaceView; import android.view.SurfaceHolder; import org.zky.zky.R; import org.zky.zky.utils.ScreenUtils; /** * rocker * //TODO 摇杆的回调 * Created by zhan9 on 2016/12/16. */ public class RockerView extends SurfaceView implements SurfaceHolder.Callback, Runnable { private static final String TAG = "RockerView"; //绘制间隔 private static int DEFAULT_INTERVAL = 30; //默认宽高 private static int DEFAULT_WIDTH = 200; private static int DEFAULT_HEIGHT = 200; //默认按钮宽高 private static int DEFAULT_BUTTON_WIDTH = 36; //状态 public static int STATUS_DEFAULT = 0; public static int STATUS_UP = 1; public static int STATUS_DOWN = 2; public static int STATUS_LEFT = 3; public static int STATUS_RIGHT = 4; private Point mStartPoint; private Point mEndPoint; private Point mCenterPoint; private Point mCurrentPoint; private int width; private int height; private int mCurrentStatus = STATUS_DEFAULT; private boolean mIsDrawing; private Context mContext; private SurfaceHolder mHolder; private Canvas mCanvas; private Paint mPaint; private int id_button; private int id_background; private int color_background = Color.WHITE; private float buttonWidth; private float buttonHeight; private Bitmap bm_button; private Bitmap bm_background; private boolean mIsRocking = false; private RockerOnStatusChangeListener mListener; public RockerView(Context context) { super(context); mContext = context; init(); } public RockerView(Context context, AttributeSet attrs) { this(context, attrs, 0); } public RockerView(Context context, AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); mContext = context; initAttrs(attrs); init(); } private void initAttrs(AttributeSet attrs) { TypedArray array = mContext.obtainStyledAttributes(attrs, R.styleable.RockerView); id_button = array.getResourceId(R.styleable.RockerView_button, 0); id_background = array.getResourceId(R.styleable.RockerView_mBackground, 0); if (id_background == 0) color_background = array.getColor(R.styleable.RockerView_mBackground, Color.WHITE); buttonWidth = array.getDimension(R.styleable.RockerView_buttonWidth, ScreenUtils.dip2px(mContext, DEFAULT_BUTTON_WIDTH)); buttonHeight = array.getDimension(R.styleable.RockerView_buttonHeight, ScreenUtils.dip2px(mContext, DEFAULT_BUTTON_WIDTH)); array.recycle(); } private void init() { if (id_button != 0) { bm_button = BitmapFactory.decodeResource(mContext.getResources(), id_button); if (bm_button != null) bm_button = ScreenUtils.zoomImg(bm_button, buttonWidth, buttonHeight); } if (id_background != 0) { bm_background = BitmapFactory.decodeResource(mContext.getResources(), id_background); } mHolder = getHolder(); mHolder.addCallback(this); setFocusable(true); setFocusableInTouchMode(true); mStartPoint = new Point(0, 0); mEndPoint = new Point(0, 0); mCenterPoint = new Point(0, 0); mCurrentPoint = new Point(0, 0); mPaint = new Paint(); mPaint.setColor(Color.RED); mPaint.setStyle(Paint.Style.STROKE); mPaint.setAntiAlias(true); } @Override public void surfaceCreated(SurfaceHolder holder) { mIsDrawing = true; new Thread(this).start(); } @Override public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) { } @Override public void surfaceDestroyed(SurfaceHolder holder) { mIsDrawing = false; } @Override public void run() { while (mIsDrawing) { long start = System.currentTimeMillis(); drawButton(); long end = System.currentTimeMillis(); if (end - start < DEFAULT_INTERVAL) { try { Thread.sleep(DEFAULT_INTERVAL - (end - start)); } catch (Exception e) { e.printStackTrace(); } } } } private void drawButton() { try { mCanvas = mHolder.lockCanvas(); if (bm_background != null) { if (bm_background.getWidth() != width) bm_background = ScreenUtils.zoomImg(bm_background, width, height); mCanvas.drawBitmap(bm_background, 0, 0, null); } else { mCanvas.drawColor(color_background); } if (bm_button != null) { //TODO 暂时解决闪回中心的问题,没有找到为什么- - if (mIsRocking&&mCurrentPoint.x == width/2&& mCurrentPoint.y == height/2){ Log.e(TAG, "drawButton: 又闪回了"); }else { mCanvas.drawBitmap(bm_button, mCurrentPoint.x - buttonWidth / 2, mCurrentPoint.y - buttonHeight / 2, mPaint); } } else { mCanvas.drawCircle(mCurrentPoint.x, mCurrentPoint.y, ScreenUtils.dip2px(mContext, DEFAULT_BUTTON_WIDTH), mPaint); } } catch (Exception e) { e.printStackTrace(); } finally { if (mCanvas != null) mHolder.unlockCanvasAndPost(mCanvas); } } @Override public boolean onTouchEvent(MotionEvent event) { int action = event.getAction(); switch (action) { case MotionEvent.ACTION_DOWN: mStartPoint.x = (int) event.getX(); mStartPoint.y = (int) event.getY(); break; case MotionEvent.ACTION_MOVE: mIsRocking = true ; mEndPoint.x = (int) event.getX(); mEndPoint.y = (int) event.getY(); mCurrentPoint.x = mCenterPoint.x + (mEndPoint.x - mStartPoint.x); mCurrentPoint.y = mCenterPoint.y + (mEndPoint.y - mStartPoint.y); //判断有效区域 mCurrentPoint.x = (int) Math.max(mCurrentPoint.x, buttonWidth / 2); mCurrentPoint.x = (int) Math.min(mCurrentPoint.x, width - buttonWidth / 2); mCurrentPoint.y = (int) Math.max(mCurrentPoint.y, buttonHeight / 2); mCurrentPoint.y = (int) Math.min(mCurrentPoint.y, height - buttonHeight / 2); if (mCurrentPoint.x == width / 2) Log.e(TAG, "drawButton: point(" + mCurrentPoint.x + "," + mCurrentPoint.y + ")"); Log.i(TAG, "drawButton: start(" + mStartPoint.x + "," + mStartPoint.y + ") end(" + mEndPoint.x + "," + mEndPoint.y + ")" + ",current(" + mCurrentPoint.x + "," + mCurrentPoint.y + ") , center(" + mCenterPoint.x + "," + mCenterPoint.y + ")"); if (mCurrentPoint.x * height / width - mCurrentPoint.y > 0) { if (mCurrentPoint.x * height / width + mCurrentPoint.y - height > 0) { //right if (mCurrentStatus != STATUS_RIGHT && mListener != null) { mCurrentStatus = STATUS_RIGHT; mListener.change(mCurrentStatus); } } else { //up if (mCurrentStatus != STATUS_UP && mListener != null) { mCurrentStatus = STATUS_UP; mListener.change(mCurrentStatus); } } } else { if (mCurrentPoint.x * height / width + mCurrentPoint.y - height > 0) { //down if (mCurrentStatus != STATUS_DOWN && mListener != null) { mCurrentStatus = STATUS_DOWN; mListener.change(mCurrentStatus); } } else { //left if (mCurrentStatus != STATUS_LEFT && mListener != null) { mCurrentStatus = STATUS_LEFT; mListener.change(mCurrentStatus); } } } break; case MotionEvent.ACTION_UP: mIsRocking = false; mCurrentPoint.x = width / 2; mCurrentPoint.y = height / 2; if (mCurrentStatus != STATUS_DEFAULT && mListener != null) { mCurrentStatus = STATUS_DEFAULT; mListener.change(mCurrentStatus); } break; } return true; } @Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { width = measureWidth(widthMeasureSpec); height = measureHeight(heightMeasureSpec); mCenterPoint.x = width / 2; mCenterPoint.y = height / 2; mCurrentPoint.x = width / 2; mCurrentPoint.y = height / 2; setMeasuredDimension(width, height); } private int measureHeight(int heightMeasureSpec) { int result; int mode = MeasureSpec.getMode(heightMeasureSpec); int size = MeasureSpec.getSize(heightMeasureSpec); if (mode == MeasureSpec.EXACTLY) { result = size; } else { if (bm_background != null) { result = bm_background.getHeight(); } else { result = ScreenUtils.dip2px(mContext, DEFAULT_HEIGHT); } if (mode == MeasureSpec.AT_MOST) { result = Math.min(result, size); } } return result; } private int measureWidth(int widthMeasureSpec) { int result; int mode = MeasureSpec.getMode(widthMeasureSpec); int size = MeasureSpec.getSize(widthMeasureSpec); if (mode == MeasureSpec.EXACTLY) { result = size; } else { if (bm_background != null) { result = bm_background.getWidth(); } else { result = ScreenUtils.dip2px(mContext, DEFAULT_HEIGHT); } if (mode == MeasureSpec.AT_MOST) { result = Math.min(result, size); } } return result; } public void setRockerListener(RockerOnStatusChangeListener listener) { this.mListener = listener; } public interface RockerOnStatusChangeListener { void change(int newStatus); } }
33.698795
256
0.571416
fc03d1d1bddcaab53214db97566f627d738a2cd4
730
package type; /** * Represents a user-defined class in the OXi type system. */ public class ClassType extends FieldType { private String id; public ClassType(String id) { this.id = id; } public String getID() { return new String(id); } @Override public boolean isClass() { return true; } @Override public boolean equals(Object o) { if (!(o instanceof ClassType)) return false; ClassType c = (ClassType) o; return c.id.equals(id); } @Override public int hashCode() { return id.hashCode(); } @Override public String toString() { return "o" + id.length() + id.replaceAll("_", "__"); } }
18.25
60
0.565753
02de55be9866af21357995f4964a04482f78707a
247
package com.github.thriveframework.thrive.example.stats; import lombok.Data; @Data public class Stats { private long total = 0; private long count = 0; public void addItem(long size){ total += size; count++; } }
16.466667
56
0.639676
d4cbcc16f4c56a663f72e0f771c2ffa7cd6d73fa
1,367
package org.jivesoftware.openfire.trustcircle; import java.io.File; import java.security.cert.X509Certificate; import java.util.Collections; import org.apache.commons.io.IOUtils; import org.directtruststandards.timplus.common.cert.CertUtils; import org.directtruststandards.timplus.common.cert.Thumbprint; import org.jivesoftware.SpringDataBaseTest; import org.jivesoftware.openfire.trustbundle.TrustBundle; import org.junit.Before; public abstract class TrustCircleBaseTest extends SpringDataBaseTest { protected X509Certificate testAnchor; protected TrustCircle testCircle; @Before public void setUp() throws Exception { super.setUp(); final File bundleLocation = new File("./src/test/resources/bundles/providerTestBundle.p7b"); final TrustBundle bundle = new TrustBundle(); bundle.setBundleName("JUnit Bundle"); bundle.setBundleURL(filePrefix + bundleLocation.getAbsolutePath()); bundle.setRefreshInterval(24); trustBundleProv.addTrustBundle(bundle); testAnchor = CertUtils.toX509Certificate(IOUtils.resourceToByteArray("/certs/direct.securehealthemail.com.cer")); trustAnchorProv.addTrustAnchor(testAnchor); testCircle = trustCircleProv.addTrustCircle("TestCircle", Collections.singleton(Thumbprint.toThumbprint(testAnchor).toString())); trustCircleProv.addTrustBundleToCircle("TestCircle", "JUnit Bundle"); } }
32.547619
131
0.807608
d1a7c61f5b224022c384e8e584dafac1efe698b8
3,026
package com.yusys.bione.frame.message.entity; import java.io.Serializable; import javax.persistence.*; import java.sql.Timestamp; /** * The persistent class for the BIONE_MSG_NOTICE_INFO database table. * */ @Entity @Table(name="BIONE_MSG_NOTICE_INFO") public class BioneMsgNoticeInfo implements Serializable { private static final long serialVersionUID = 1L; @Id @Column(name="ANNOUNCEMENT_ID") private String announcementId; @Column(name="ANNOUNCEMENT_DETAIL") private String announcementDetail; @Column(name="ANNOUNCEMENT_STS") private String announcementSts; @Column(name="ANNOUNCEMENT_TITLE") private String announcementTitle; @Column(name="ANNOUNCEMENT_TYPE") private String announcementType; @Column(name="EFFECTIVE__DATE") private Timestamp effectiveDate; @Column(name="EXPIRE_DATE") private Timestamp expireDate; @Column(name="LAST_UPDATE_TIME") private Timestamp lastUpdateTime; @Column(name="LAST_UPDATE_USER") private String lastUpdateUser; @Column(name="LOGIC_SYS_NO") private String logicSysNo; @Column(name="CREATE_USER") private String createUser; public BioneMsgNoticeInfo() { } public String getAnnouncementId() { return this.announcementId; } public void setAnnouncementId(String announcementId) { this.announcementId = announcementId; } public String getAnnouncementDetail() { return this.announcementDetail; } public void setAnnouncementDetail(String announcementDetail) { this.announcementDetail = announcementDetail; } public String getAnnouncementSts() { return this.announcementSts; } public void setAnnouncementSts(String announcementSts) { this.announcementSts = announcementSts; } public String getAnnouncementTitle() { return this.announcementTitle; } public void setAnnouncementTitle(String announcementTitle) { this.announcementTitle = announcementTitle; } public String getAnnouncementType() { return this.announcementType; } public void setAnnouncementType(String announcementType) { this.announcementType = announcementType; } public Timestamp getEffectiveDate() { return this.effectiveDate; } public void setEffectiveDate(Timestamp effectiveDate) { this.effectiveDate = effectiveDate; } public Timestamp getExpireDate() { return this.expireDate; } public void setExpireDate(Timestamp expireDate) { this.expireDate = expireDate; } public Timestamp getLastUpdateTime() { return this.lastUpdateTime; } public void setLastUpdateTime(Timestamp lastUpdateTime) { this.lastUpdateTime = lastUpdateTime; } public String getLastUpdateUser() { return this.lastUpdateUser; } public void setLastUpdateUser(String lastUpdateUser) { this.lastUpdateUser = lastUpdateUser; } public String getLogicSysNo() { return this.logicSysNo; } public void setLogicSysNo(String logicSysNo) { this.logicSysNo = logicSysNo; } public String getCreateUser() { return createUser; } public void setCreateUser(String createUser) { this.createUser = createUser; } }
21.309859
69
0.77462
2a793a98215244c0f959e75edf958b35f2671b4a
597
package com.github.byference.tinyrpc.core.annotation; import com.github.byference.tinyrpc.core.listener.RpcApplicationContextListener; import com.github.byference.tinyrpc.core.spring.TinyRpcScannerConfigurer; import org.springframework.context.annotation.Import; import java.lang.annotation.*; /** * enable rpc client. * * @see RpcApplicationContextListener * @see TinyRpcScannerConfigurer * @author byference * @since 2019/04/13 */ @Target(ElementType.TYPE) @Retention(RetentionPolicy.RUNTIME) @Documented @Import({TinyRpcScannerConfigurer.class}) public @interface EnableRpcClient { }
25.956522
80
0.809045
e98b3f34151cb650ae64e71a191b5166ba57ad9f
582
package com.tramchester.integration.testSupport; import com.tramchester.config.GraphDBConfig; import java.nio.file.Path; public class GraphDBTestConfig implements GraphDBConfig { private final Path fullpath; public GraphDBTestConfig(String subFolderForDB, String dbFilename) { Path containingFolder = Path.of("databases", subFolderForDB); this.fullpath = containingFolder.resolve(dbFilename); } public Path getDbPath() { return fullpath; } @Override public String getNeo4jPagecacheMemory() { return "100m"; } }
23.28
72
0.716495
99b95ead2bd9b62466ff4573e5c26095f882f504
2,267
package org.wx.sdk.card.request; import org.wx.sdk.base.Request; import org.wx.sdk.card.respone.CardPayCellSetRespone; import java.util.HashMap; import java.util.Map; /** * <p>设置买单接口请求对象 * <p>创建卡券之后,开发者可以通过设置微信买单接口设置该card_id支持微信买单功能。 * 值得开发者注意的是,设置买单的card_id必须已经配置了门店,否则会报错。 * <p>注意事项: * <p>1.设置快速买单的卡券须支持至少一家有核销员门店,否则无法设置成功; * <p>2.若该卡券设置了center_url(居中使用跳转链接),须先将该设置更新为空后再设置自快速买单方可生效。 * @author Rocye * @version 2017.12.22 */ public class CardPayCellSetRequest implements Request<CardPayCellSetRespone> { /** 微信公众平台唯一接口凭证 */ private String accessToken; /** 请求参数的Map */ private Map<String, Object> wxHashMap = new HashMap<String, Object>(); /** 卡券ID */ private String card_id; /** 是否开启买单功能 */ private Boolean is_open; /** * 构造器 * @param cardId 卡券ID * @param isOpen 是否开启买单功能 */ public CardPayCellSetRequest(String cardId, Boolean isOpen) { this.card_id = cardId; this.is_open = isOpen; } /** * 获取接口请求地址 */ public String getApiUrl(){ String url = "https://api.weixin.qq.com/card/paycell/set?access_token="+ this.accessToken; return url; } /** * 获取返回对象类 */ public Class<CardPayCellSetRespone> getResponseClass(){ return CardPayCellSetRespone.class; } /** * 获取请求参数的HashMap */ public Map<String, Object> getWxHashMap(){ wxHashMap.put("card_id", this.card_id); wxHashMap.put("is_open", this.is_open); return wxHashMap; } /** * 请求类型:1-普通Get 2-下载GET 3-普通POST 4-下载POST 5-无参上传 6-有参上传 */ public int getReqType(){ return 3; } /** * 请求参数格式(kv,json,xml) */ public String getParamFormat(){ return "json"; } /** * 设置AccessToken */ public void setAccessToken(String accessToken){ this.accessToken = accessToken; } public String getCard_id() { return card_id; } public void setCard_id(String card_id) { this.card_id = card_id; } public Boolean getIs_open() { return is_open; } public void setIs_open(Boolean is_open) { this.is_open = is_open; } }
22.445545
99
0.601676
95a0ae905166917ac391f3500022dab77ea6583b
3,601
/* * Copyright 2015 SATO taichi * * 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 ninja.siden.okite.compiler.internal; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; import io.gige.CompilationResult; import io.gige.CompilerContext; import io.gige.Compilers; import io.gige.junit.CompilerRunner; import java.util.List; import java.util.Set; import javax.annotation.Generated; import javax.annotation.processing.RoundEnvironment; import javax.lang.model.element.AnnotationMirror; import javax.lang.model.element.TypeElement; import ninja.siden.okite.annotation.AnnotateWith.AnnotationTarget; import ninja.siden.okite.compiler.BaseProcessor; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; /** * @author taichi */ @RunWith(CompilerRunner.class) public class ValidationInfoTest { @Compilers CompilerContext context; @Before public void setUp() throws Exception { this.context.setSourcePath("src/test/java").set( diag -> System.out.println(diag)); } @Test public void validation() throws Exception { CompilationResult result = this.context.set(new BaseProcessor() { @Override public boolean process(Set<? extends TypeElement> annotations, RoundEnvironment roundEnv) { if (roundEnv.processingOver()) { return false; } TypeElement type = env.elemUtils.getTypeElement(Val.class) .get(); List<? extends AnnotationMirror> list = type .getAnnotationMirrors(); AnnotationMirror am = list.get(0); ValidationInfo info = ValidationInfo.from(env, type, am); assertEquals("pref", info.prefix); assertEquals("suff", info.suffix); assertTrue(info.cascading); assertEquals(2, info.with.size()); AnnotateWithInfo awi = info.with.get(0); assertEquals(Generated.class.getName(), awi.annotation); assertEquals(AnnotationTarget.TYPE, awi.target); assertEquals("aaa=bbb", awi.attributes); return false; } }).setUnits(Val.class).compile(); assertTrue(result.success()); } @Test public void metaValidation() throws Exception { CompilationResult result = this.context.set(new BaseProcessor() { @Override public boolean process(Set<? extends TypeElement> annotations, RoundEnvironment roundEnv) { if (roundEnv.processingOver()) { return false; } TypeElement type = env.elemUtils.getTypeElement(MetaVal.class) .get(); List<? extends AnnotationMirror> list = type .getAnnotationMirrors(); AnnotationMirror am = list.get(0); ValidationInfo info = ValidationInfo.fromMeta(env, type, am); assertEquals("pref", info.prefix); assertEquals("suff", info.suffix); assertTrue(info.cascading); assertEquals(1, info.with.size()); AnnotateWithInfo awi = info.with.get(0); assertEquals(Override.class.getName(), awi.annotation); assertEquals(AnnotationTarget.CONSTRUCTOR, awi.target); assertEquals("ccc=dddd", awi.attributes); return false; } }).setUnits(MetaVal.class).compile(); assertTrue(result.success()); } }
29.760331
76
0.72952
b80be72a21d5e28d125f70402107ea885c98210d
611
/* * 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 br.com.petshop.dao; import java.util.List; import org.hibernate.HibernateException; import org.hibernate.Session; import br.com.petshop.entidade.Dono; /** * * @author Silvio */ public interface DonoDao extends BaseDao<Dono, Long> { Dono pesquisarPorCpfDono(String cpf, Session sessao) throws HibernateException; List<Dono> pesquisarPorNome(String nome, Session sessao) throws HibernateException; }
25.458333
87
0.759411
722de4e64286d3b98cb161f16a326545a8ea7dee
7,955
package org.bch.c3pro.server.external; import com.amazonaws.services.sqs.model.MessageAttributeValue; import org.apache.commons.codec.binary.Base64; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.bch.c3pro.server.config.AppConfig; import org.bch.c3pro.server.exception.C3PROException; import com.amazonaws.auth.AWSCredentials; import com.amazonaws.auth.profile.ProfileCredentialsProvider; import com.amazonaws.regions.Region; import com.amazonaws.regions.Regions; import com.amazonaws.services.sqs.AmazonSQS; import com.amazonaws.services.sqs.AmazonSQSClient; import com.amazonaws.services.sqs.model.SendMessageRequest; import javax.crypto.Cipher; import javax.crypto.KeyGenerator; import javax.crypto.SecretKey; import javax.crypto.spec.IvParameterSpec; import java.io.UnsupportedEncodingException; import java.security.InvalidKeyException; import java.security.PublicKey; import java.security.SecureRandom; /** * Implements the access to a Amazon SQS queue * @author CHIP-IHL */ public class SQSAccess implements Queue { private AmazonSQS sqs = null; Log log = LogFactory.getLog(SQSAccess.class); /** * Sends a message to the SQS * @param resource The payload * @throws C3PROException In case access to SQS is not possible */ @Override public void sendMessage(String resource) throws C3PROException { setCredentials(); this.sqs.sendMessage(new SendMessageRequest(AppConfig.getProp(AppConfig.AWS_SQS_URL), resource)); } /** * Sends an encrypted message to the SQS (See documentation) * @param resource The resource * @param publicKey The public key used to encrypt the symetric key * @param UUIDKey the if of the key * @param version The version * @throws C3PROException In case access to SQS is not possible */ @Override public void sendMessageEncrypted(String resource, PublicKey publicKey, String UUIDKey, String version) throws C3PROException { setCredentials(); // Generate the symetric private key to encrypt the message SecretKey symetricKey = generateSecretKey(); byte []encKeyToSend = null; byte []encResource = null; Cipher cipher; try { // We encrypt the symetric key using the public available key int size = Integer.parseInt(AppConfig.getProp(AppConfig.SECURITY_PRIVATEKEY_SIZE)); //SecureRandom random = new SecureRandom(); //IvParameterSpec iv = new IvParameterSpec(random.generateSeed(16)); encKeyToSend = encryptRSA(publicKey, symetricKey.getEncoded()); // We encrypt the message cipher = Cipher.getInstance(AppConfig.getProp(AppConfig.SECURITY_PRIVATEKEY_ALG)); //cipher.init(Cipher.ENCRYPT_MODE, symmetricKey, iv); cipher.init(Cipher.ENCRYPT_MODE, symetricKey, new IvParameterSpec(new byte[size])); encResource = cipher.doFinal(resource.getBytes(AppConfig.UTF)); } catch (UnsupportedEncodingException e) { throw new C3PROException(e.getMessage(), e); } catch (InvalidKeyException e) { throw new C3PROException(e.getMessage(), e); } catch (Exception e) { throw new C3PROException(e.getMessage(), e); } pushMessage(Base64.encodeBase64String(encResource), Base64.encodeBase64String(encKeyToSend), UUIDKey, version); } private void pushMessage(String msg, String key, String uuid, String version) throws C3PROException{ setCredentials(); // We send the encrypted message to the Queue. We Base64 encode it SendMessageRequest mse = new SendMessageRequest(AppConfig.getProp(AppConfig.AWS_SQS_URL), msg); System.out.println(AppConfig.getProp(AppConfig.AWS_SQS_URL)); // Add SQS Elem metadata: encrypted symmetric key MessageAttributeValue atr = new MessageAttributeValue(); atr.setStringValue(key); atr.setDataType("String"); mse.addMessageAttributesEntry(AppConfig.getProp(AppConfig.SECURITY_METADATAKEY), atr); // Add SQS Elem metadata: public key uuid atr = new MessageAttributeValue(); atr.setStringValue(uuid); atr.setDataType("String"); mse.addMessageAttributesEntry(AppConfig.getProp(AppConfig.SECURITY_METADATAKEYID), atr); atr = new MessageAttributeValue(); atr.setStringValue(version); atr.setDataType("String"); mse.addMessageAttributesEntry(AppConfig.getProp(AppConfig.FHIR_METADATA_VERSION), atr); try { this.sqs.sendMessage(mse); } catch (Exception e) { e.printStackTrace(); throw new C3PROException(e.getMessage(), e); } } /** * Generates a secret symmetric key * @return The generated key * @throws C3PROException In case an error occurs during the generation */ public SecretKey generateSecretKey() throws C3PROException { SecretKey key = null; try { KeyGenerator generator = KeyGenerator.getInstance(AppConfig.getProp(AppConfig.SECURITY_PRIVATEKEY_BASEALG)); int size = Integer.parseInt(AppConfig.getProp(AppConfig.SECURITY_PRIVATEKEY_SIZE)); SecureRandom random = new SecureRandom(); generator.init(size*8, random); key = generator.generateKey(); } catch (Exception e) { throw new C3PROException(e.getMessage(), e); } return key; } /** * Encrypts the given byte array using the provided public key using RSA * @param key The public key * @param text The message to encrypt * @return The encrypted message * @throws C3PROException In case an error occurs during the encryption */ public byte[] encryptRSA(PublicKey key, byte[] text) throws C3PROException { Cipher cipher = null; byte [] out = null; try { cipher = Cipher.getInstance(AppConfig.getProp(AppConfig.SECURITY_PUBLICKEY_ALG)); cipher.init(Cipher.ENCRYPT_MODE, key); out = cipher.doFinal(text); } catch (Exception e) { throw new C3PROException(e.getMessage(), e); } return out; } /** * Sends an ALREADY encrypted message to the SQS (See documentation) * @param resource The resource * @param UUIDKey the if of the key * @param version The version * @throws C3PROException In case access to SQS is not possible */ public void sendMessageAlreadyEncrypted(String resource, String key, String UUIDKey, String version) throws C3PROException { pushMessage(resource, key, UUIDKey, version); } private void setCredentials() throws C3PROException { if (this.sqs == null) { AWSCredentials credentials = null; try { System.setProperty("aws.profile", AppConfig.getProp(AppConfig.AWS_SQS_PROFILE)); System.out.println(AppConfig.getProp(AppConfig.AWS_SQS_PROFILE)); credentials = new ProfileCredentialsProvider().getCredentials(); } catch (Exception e) { e.printStackTrace(); throw new C3PROException( "Cannot load the credentials from the credential profiles file. " + "Please make sure that the credentials file is at the correct " + "location (~/.aws/credentials), and is in valid format.", e); } this.sqs = new AmazonSQSClient(credentials); System.out.println(AppConfig.getProp(AppConfig.AWS_SQS_REGION)); Region usWest2 = Region.getRegion(Regions.fromName(AppConfig.getProp(AppConfig.AWS_SQS_REGION))); sqs.setRegion(usWest2); } } }
40.380711
120
0.666248
339a455e2680900f68547d4c65ccc1b656b0931d
1,579
package com.minhtetoo.PADCMMNEWS.data.model; import com.minhtetoo.PADCMMNEWS.Utils.AppConstants; import com.minhtetoo.PADCMMNEWS.data.VO.NewsVO; import com.minhtetoo.PADCMMNEWS.events.RestApiEvents; import com.minhtetoo.PADCMMNEWS.network.MMNewsDataAgentImpl; import org.greenrobot.eventbus.EventBus; import org.greenrobot.eventbus.Subscribe; import java.util.ArrayList; import java.util.List; /** * Created by min on 12/3/2017. */ public class NewsModel { private static NewsModel objInstance; private List<NewsVO> mNews; int mmNewsPageIndex=1; private NewsModel() { EventBus.getDefault().register(this); mNews = new ArrayList<>(); } public static NewsModel getObjInstance(){ if(objInstance == null){ objInstance = new NewsModel(); } return objInstance; } public void startloadingMMNews(){ MMNewsDataAgentImpl.getObjInstance().loadMMNews(AppConstants.ACESS_TOKEN, mmNewsPageIndex); } public List<NewsVO> getmNews(){ return mNews; } public void loadMoreNews() { MMNewsDataAgentImpl.getObjInstance().loadMMNews(AppConstants.ACESS_TOKEN, mmNewsPageIndex); } @Subscribe public void onNewsDataLoaded(RestApiEvents.NewsDataLoadedEvent event){ mNews.addAll(event.getLoadNews()); mmNewsPageIndex = event.getLoadedPageIndex() + 1; } public void forceRefreshNews() { mNews = new ArrayList<>(); mmNewsPageIndex = 1; startloadingMMNews(); } }
19.987342
81
0.676377
dbd7c3e8eab49e0e5b6396af71a7d05fa8e38479
149
package org.wavecraft.ui.events; public enum UiEventMenu implements UiEvent { QUIT, START_NEW_GAME, NAV_MENU_OPTIONS, NAV_MENU_MAIN, RESUME_GAME }
24.833333
67
0.825503
465728c61f10dc12d16a71c01d5e9019b2566d7a
5,476
/** * The contents of this file are subject to the license and copyright * detailed in the LICENSE and NOTICE files at the root of the source * tree and available online at * * http://www.dspace.org/license/ */ package org.dspace.services.sessions.model; import java.util.Enumeration; import java.util.Set; import java.util.UUID; import java.util.concurrent.ConcurrentHashMap; import javax.servlet.ServletContext; import javax.servlet.http.HttpSession; import javax.servlet.http.HttpSessionContext; /** * This is a special HTTP session object that stands in for a real one * when sessions are not initiated or associated by HTTP requests. * * @author Aaron Zeckoski (azeckoski @ gmail.com) */ @SuppressWarnings("deprecation") public final class InternalHttpSession implements HttpSession { private final String id; private long lastAccessedTime = System.currentTimeMillis(); private long creationTime = System.currentTimeMillis(); private int maxInactiveInternal = 1800; private boolean invalidated = false; private ConcurrentHashMap<String, Object> attributes = null; private ConcurrentHashMap<String, Object> getAttributes() { if (this.attributes == null) { this.attributes = new ConcurrentHashMap<String, Object>(); } return this.attributes; } public InternalHttpSession() { this.id = UUID.randomUUID().toString(); } private void checkInvalidated() { if (invalidated) { throw new IllegalStateException("This session is no longer valid"); } } @Override public String toString() { return "internalSession:" + this.id + ":" + this.creationTime + ":" + this.invalidated + ":" + super.toString(); } /* (non-Javadoc) * @see javax.servlet.http.HttpSession#getAttribute(java.lang.String) */ public Object getAttribute(String name) { checkInvalidated(); return getAttributes().get(name); } /* (non-Javadoc) * @see javax.servlet.http.HttpSession#getAttributeNames() */ @SuppressWarnings("unchecked") public Enumeration getAttributeNames() { checkInvalidated(); return getAttributes().keys(); } /* (non-Javadoc) * @see javax.servlet.http.HttpSession#getCreationTime() */ public long getCreationTime() { checkInvalidated(); return creationTime; } /* (non-Javadoc) * @see javax.servlet.http.HttpSession#getId() */ public String getId() { checkInvalidated(); return id; } /* (non-Javadoc) * @see javax.servlet.http.HttpSession#getLastAccessedTime() */ public long getLastAccessedTime() { checkInvalidated(); return lastAccessedTime; } /* (non-Javadoc) * @see javax.servlet.http.HttpSession#getMaxInactiveInterval() */ public int getMaxInactiveInterval() { checkInvalidated(); return maxInactiveInternal; } /* (non-Javadoc) * @see javax.servlet.http.HttpSession#getServletContext() */ public ServletContext getServletContext() { checkInvalidated(); return null; } /* (non-Javadoc) * @see javax.servlet.http.HttpSession#getSessionContext() */ public HttpSessionContext getSessionContext() { checkInvalidated(); return null; } /* (non-Javadoc) * @see javax.servlet.http.HttpSession#getValue(java.lang.String) */ public Object getValue(String name) { checkInvalidated(); return getAttributes().get(name); } /* (non-Javadoc) * @see javax.servlet.http.HttpSession#getValueNames() */ public String[] getValueNames() { checkInvalidated(); Set<String> names = getAttributes().keySet(); return names.toArray(new String[names.size()]); } /* (non-Javadoc) * @see javax.servlet.http.HttpSession#invalidate() */ public void invalidate() { invalidated = true; if (this.attributes != null) { this.attributes.clear(); this.attributes = null; } } /* (non-Javadoc) * @see javax.servlet.http.HttpSession#isNew() */ public boolean isNew() { return false; } /* (non-Javadoc) * @see javax.servlet.http.HttpSession#putValue(java.lang.String, java.lang.Object) */ public void putValue(String name, Object value) { checkInvalidated(); getAttributes().put(name, value); } /* (non-Javadoc) * @see javax.servlet.http.HttpSession#removeAttribute(java.lang.String) */ public void removeAttribute(String name) { checkInvalidated(); getAttributes().remove(name); } /* (non-Javadoc) * @see javax.servlet.http.HttpSession#removeValue(java.lang.String) */ public void removeValue(String name) { checkInvalidated(); getAttributes().remove(name); } /* (non-Javadoc) * @see javax.servlet.http.HttpSession#setAttribute(java.lang.String, java.lang.Object) */ public void setAttribute(String name, Object value) { checkInvalidated(); getAttributes().put(name, value); } /* (non-Javadoc) * @see javax.servlet.http.HttpSession#setMaxInactiveInterval(int) */ public void setMaxInactiveInterval(int interval) { checkInvalidated(); this.maxInactiveInternal = interval; } }
27.517588
120
0.639701
ec9264d5da38b3fd10d017819111b6206184b60b
2,445
package cmps252.HW4_2.UnitTesting; import static org.junit.jupiter.api.Assertions.*; import java.io.FileNotFoundException; import java.util.List; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.Tag; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; import cmps252.HW4_2.Customer; import cmps252.HW4_2.FileParser; @Tag("38") class Record_534 { private static List<Customer> customers; @BeforeAll public static void init() throws FileNotFoundException { customers = FileParser.getCustomers(Configuration.CSV_File); } @Test @DisplayName("Record 534: FirstName is Lindsey") void FirstNameOfRecord534() { assertEquals("Lindsey", customers.get(533).getFirstName()); } @Test @DisplayName("Record 534: LastName is Michocki") void LastNameOfRecord534() { assertEquals("Michocki", customers.get(533).getLastName()); } @Test @DisplayName("Record 534: Company is Ink Spot Printing Med Svc Inc") void CompanyOfRecord534() { assertEquals("Ink Spot Printing Med Svc Inc", customers.get(533).getCompany()); } @Test @DisplayName("Record 534: Address is 1691 Los Angeles Ave") void AddressOfRecord534() { assertEquals("1691 Los Angeles Ave", customers.get(533).getAddress()); } @Test @DisplayName("Record 534: City is Ventura") void CityOfRecord534() { assertEquals("Ventura", customers.get(533).getCity()); } @Test @DisplayName("Record 534: County is Ventura") void CountyOfRecord534() { assertEquals("Ventura", customers.get(533).getCounty()); } @Test @DisplayName("Record 534: State is CA") void StateOfRecord534() { assertEquals("CA", customers.get(533).getState()); } @Test @DisplayName("Record 534: ZIP is 93004") void ZIPOfRecord534() { assertEquals("93004", customers.get(533).getZIP()); } @Test @DisplayName("Record 534: Phone is 805-659-3697") void PhoneOfRecord534() { assertEquals("805-659-3697", customers.get(533).getPhone()); } @Test @DisplayName("Record 534: Fax is 805-659-8553") void FaxOfRecord534() { assertEquals("805-659-8553", customers.get(533).getFax()); } @Test @DisplayName("Record 534: Email is lindsey@michocki.com") void EmailOfRecord534() { assertEquals("lindsey@michocki.com", customers.get(533).getEmail()); } @Test @DisplayName("Record 534: Web is http://www.lindseymichocki.com") void WebOfRecord534() { assertEquals("http://www.lindseymichocki.com", customers.get(533).getWeb()); } }
25.46875
81
0.730879
8e43095a1a28e377ab03b5bb4d36523bf85c3ea0
1,301
package com.gitee.passerr.leetcode.problem.algorithm.page1; import java.util.Arrays; /** * 假设按照升序排序的数组在预先未知的某个点上进行了旋转。 * ( 例如,数组 [0,1,2,4,5,6,7] 可能变为 [4,5,6,7,0,1,2] )。 * 搜索一个给定的目标值,如果数组中存在这个目标值,则返回它的索引,否则返回 -1 。 * 你可以假设数组中不存在重复的元素。 * <p> * 你的算法时间复杂度必须是 O(log n) 级别。 * 示例 1: * 输入: nums = [4,5,6,7,0,1,2], target = 0 * 输出: 4 * <p> * 示例 2: * 输入: nums = [4,5,6,7,0,1,2], target = 3 * 输出: -1 * @author xiehai * @date 2019/07/05 15:21 * @Copyright(c) tellyes tech. inc. co.,ltd */ public class Solution33 { public int search(int[] nums, int target) { int middle = -1, length = nums.length; // 找到中位数索引 for (int i = 1; i < length; i++) { if (nums[i] < nums[i - 1]) { // 中位数为较大的数字索引 middle = i - 1; break; } } // 本身是旋转过的 排序 if (middle >= 0) { Arrays.sort(nums); } // 二分查找 int index = Arrays.binarySearch(nums, target); // 若本身就是有序 直接返回结果 if (middle < 0) { return index > -1 ? index : -1; } // 旋转节点右边元素数量 int offset = length - middle - 1; // 最后位置大于旋转位置 则元素应该在排序前左边 否则在右边 return index > -1 ? (index < offset ? index + middle + 1 : index - offset) : -1; } }
24.092593
88
0.50269
9fe31e0d5f059bfa6be9d6ae14728b52b7f93885
3,709
package com.atolcd.alfresco.filer.core.test.content; import static org.assertj.core.api.Assertions.assertThat; import static org.junit.platform.engine.discovery.DiscoverySelectors.selectClass; import static org.junit.platform.launcher.core.LauncherDiscoveryRequestBuilder.request; import java.util.Optional; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.junit.jupiter.engine.JupiterTestEngine; import org.junit.platform.engine.DiscoverySelector; import org.junit.platform.engine.TestExecutionResult; import org.junit.platform.launcher.LauncherDiscoveryRequest; import org.junit.platform.testkit.engine.EngineExecutionResults; import org.junit.platform.testkit.engine.EngineTestKit; import org.junit.platform.testkit.engine.Events; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit.jupiter.SpringExtension; import com.atolcd.alfresco.filer.core.model.FilerException; import com.atolcd.alfresco.filer.core.test.framework.PostgreSQLExtension; public class DisableDefaultModelStartupTest { private static final Logger LOGGER = LoggerFactory.getLogger(DisableDefaultModelStartupTest.class); private final JupiterTestEngine engine = new JupiterTestEngine(); @Test public void modelDisabled() { Events testEvents = executeTestsForClass(DisableDefaultModelStartupConfiguration.class).testEvents(); logTestFailures(testEvents); assertThat(testEvents.started().count()).isEqualTo(1); assertThat(testEvents.succeeded().count()).isEqualTo(0); assertThat(testEvents.skipped().count()).isEqualTo(0); assertThat(testEvents.aborted().count()).isEqualTo(0); assertThat(testEvents.failed().count()).isEqualTo(1); Throwable error = testEvents.finished().failed().stream().findFirst() .map(event -> event.getPayload(TestExecutionResult.class)) .map(Optional::get) // Event of type FINISHED cannot have empty payload .map(TestExecutionResult::getThrowable) .map(Optional::get) // Throwable is always present on failed test .get(); assertThat(error) .isInstanceOf(IllegalStateException.class) .hasCauseInstanceOf(FilerException.class); assertThat(error.getCause()) .hasMessage("Could not find aspect: {http://www.atolcd.com/model/filer/1.0}fileable"); } @ExtendWith(PostgreSQLExtension.class) @ExtendWith(SpringExtension.class) @ContextConfiguration({ "classpath:alfresco/application-context.xml", "classpath:context/security-context.xml", "classpath:alfresco/module/filer/disable/model-context.xml" }) public static class DisableDefaultModelStartupConfiguration { @Test public void check() { // no-op - context is loaded by SpringExtension } } private EngineExecutionResults executeTestsForClass(final Class<?> testClass) { DiscoverySelector selectors = selectClass(testClass); LauncherDiscoveryRequest request = request().selectors(selectors).build(); return EngineTestKit.execute(this.engine, request); } private static void logTestFailures(final Events testEvents) { testEvents.finished().failed().stream() .map(event -> event.getPayload(TestExecutionResult.class)) .map(Optional::get) // Event of type FINISHED cannot have empty payload .map(TestExecutionResult::getThrowable) .map(Optional::get) // Throwable is always present on failed test // TODO wait for https://github.com/pmd/pmd/issues/2255 .forEach(thrown -> LOGGER.error("Extension test error", thrown)); // NOPMD InvalidLogMessageFormat false positive } }
42.147727
121
0.765705
e79294b888c4fc747cff55130dd9400ae7cbca2b
3,000
// Copyright (c), 2013, adopus consulting GmbH Switzerland, all rights reserved. package com.purej.vminspect.http.server; import java.lang.management.ManagementFactory; import javax.management.ObjectName; import org.eclipse.jetty.server.Server; import org.eclipse.jetty.servlet.ServletContextHandler; import org.eclipse.jetty.servlet.ServletHolder; import com.purej.vminspect.data.MySample; import com.purej.vminspect.http.servlet.VmInspectionServlet; /** * Starts the VmInspectServlet in a embedded jetty server for testing with a * web-browser. * * @author Stefan Mueller */ public final class JettyServerTest { private JettyServerTest() { } /** * The java main method. */ public static void main(String[] args) throws Exception { // Config from cmd or default: int port = args.length > 0 ? Integer.parseInt(args[0]) : 8080; int frequencyMs = args.length > 1 ? Integer.parseInt(args[1]) : 60000; String storageDir = args.length > 2 ? args[2] : null; Server server = new Server(port); // Init 1: Direct init // VmInspectionServlet servlet = new VmInspectionServlet(); // servlet.init(new CustomMBeanAccessControlFactory(), // Integer.parseInt(args[1]), args.length > 2 ? args[2] : null); // ServletHolder servletHolder = new ServletHolder(servlet); // Init 2: servlet parameters ServletHolder servletHolder = new ServletHolder(VmInspectionServlet.class); servletHolder.setInitParameter("vminspect.mbeans.readonly", "false"); servletHolder.setInitParameter("vminspect.mbeans.writeConfirmation", "true"); // servletHolder.setInitParameter("vminspect.mbeans.accessControlFactory", // CustomMBeanAccessControlFactory.class.getName()); servletHolder.setInitParameter("vminspect.statistics.collection.frequencyMs", String.valueOf(frequencyMs)); servletHolder.setInitParameter("vminspect.statistics.storage.dir", storageDir); ServletContextHandler handler = new ServletContextHandler(); handler.setContextPath("/inspect"); handler.addServlet(servletHolder, "/*"); server.setHandler(handler); server.start(); ManagementFactory.getPlatformMBeanServer().registerMBean(new MySample(false), new ObjectName("purej.vminspect", "id", "1")); ManagementFactory.getPlatformMBeanServer().registerMBean(new MySample(true), new ObjectName("purej.vminspect", "id", "2")); ManagementFactory.getPlatformMBeanServer().registerMBean(new MySample(true), new ObjectName("purej.vminspect:type=my Type,id=12")); ManagementFactory.getPlatformMBeanServer().registerMBean(new MySample(true), new ObjectName("purej.vminspect:type=myType,spaces=a b c")); ManagementFactory.getPlatformMBeanServer().registerMBean(new MySample(true), new ObjectName("purej.vminspect:type=myType,sonderzeichen='äöü';")); System.out.println("Jetty-Server started and VmInspection deployed, check-out http://localhost:" + port + "/inspect"); } }
46.875
150
0.734667
c9e9bba87a8186107c698cd854dd9d13cd92badb
215
package com.jegarn.jegarn.packet.base; public class Notification extends HasSubTypePacket{ public static final String TYPE = "notification"; public Notification(){ this.type = TYPE; } }
23.888889
54
0.683721
41ad493a448b34a88cfbca07a3933496fc7ff399
1,672
/* * Copyright 2017 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.github.i49.cascade.core.matchers.simple; import org.w3c.dom.Attr; import org.w3c.dom.Element; import org.w3c.dom.NamedNodeMap; import io.github.i49.cascade.core.matchers.Matcher; import io.github.i49.cascade.core.matchers.MatcherType; /** * */ public class IdentifierMatcher implements Matcher { private final String identifier; public IdentifierMatcher(String identifier) { this.identifier = identifier; } @Override public MatcherType getType() { return MatcherType.IDENTIFIER; } @Override public boolean matches(Element element) { NamedNodeMap map = element.getAttributes(); for (int i = 0; i < map.getLength(); i++) { Attr a = (Attr)map.item(i); if (a.isId() && this.identifier.equals(a.getValue())) { return true; } } return false; } @Override public String toString() { return "#" + this.identifier; } public String getIdentifier() { return identifier; } }
26.539683
75
0.66567
83689b253a2535f08defbca7bd90c12049c30484
696
package com.taotao.cloud.file.propeties; import lombok.Data; import org.springframework.boot.context.properties.ConfigurationProperties; import org.springframework.cloud.context.config.annotation.RefreshScope; /** * 七牛云文件服务Properties * * @author dengtao * @date 2020/10/26 09:39 * @since v1.0 */ @Data @RefreshScope @ConfigurationProperties(prefix = "taotao.cloud.file.qiniu") public class QiniuProperties { /** * 七牛绑定的域名 */ private String domain; /** * 七牛ACCESS_KEY */ private String accessKey; /** * 七牛SECRET_KEY */ private String secretKey; /** * 七牛存储空间名 */ private String bucketName; private String zone; }
18.810811
75
0.672414
907887d51fb23613d130fa790aea8aad0a49195b
384
package ftw.strategy.applicator; import ftw.simulation.model.SimulationResult; import ftw.stock.ExchangeRate; import ftw.stock.data.reader.DataUnit; import ftw.strategy.model.Strategy; import java.math.BigDecimal; import java.util.Collection; import java.util.List; public interface IStrategyApplicator { void applyStrategies(); SimulationResult getSimulationResult(); }
21.333333
45
0.807292
afaf585bd8d71a590be43eca55c2e5738f7e97d0
397
package cn.alphahub.mall.order.feign; import cn.alphahub.common.constant.AppConstant; import cn.alphahub.mall.ware.api.WareSkuApi; import org.springframework.cloud.openfeign.FeignClient; /** * sku库存 * * @author liuwenjing * @version 1.0 * @date 2021/05/07 */ @FeignClient(value = AppConstant.WARE_SERVICE, contextId = "wareSkuClient") public interface WareSkuClient extends WareSkuApi { }
23.352941
75
0.770781
6c06ef81f6cefac29672e075cd574378e52a2032
2,302
/* Copyright (c) 2002, 2014, Oracle and/or its affiliates. All rights reserved. The MySQL Connector/J is licensed under the terms of the GPLv2 <http://www.gnu.org/licenses/old-licenses/gpl-2.0.html>, like most MySQL Connectors. There are special exceptions to the terms and conditions of the GPLv2 as it is applied to this software, see the FOSS License Exception <http://www.mysql.com/about/legal/licensing/foss-exception.html>. 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; version 2 of the License. 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, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ package testsuite.simple; import java.sql.SQLException; import java.sql.Savepoint; import java.util.Properties; import com.mysql.jdbc.ConnectionLifecycleInterceptor; public class TestLifecycleInterceptor implements ConnectionLifecycleInterceptor { static int transactionsBegun = 0; static int transactionsCompleted = 0; public void close() throws SQLException { } public boolean commit() throws SQLException { return true; } public boolean rollback() throws SQLException { return true; } public boolean rollback(Savepoint s) throws SQLException { return true; } public boolean setAutoCommit(boolean flag) throws SQLException { return true; } public boolean setCatalog(String catalog) throws SQLException { return true; } public boolean transactionBegun() throws SQLException { transactionsBegun++; return true; } public boolean transactionCompleted() throws SQLException { transactionsCompleted++; return true; } public void destroy() { } public void init(com.mysql.jdbc.Connection conn, Properties props) throws SQLException { } }
30.693333
92
0.728497
ca0e849459e9e8562fef70359ae10037d9e26953
22,411
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.falcon.regression; import org.apache.falcon.entity.v0.EntityType; import org.apache.falcon.entity.v0.Frequency.TimeUnit; import org.apache.falcon.entity.v0.process.Properties; import org.apache.falcon.entity.v0.process.Property; import org.apache.falcon.regression.core.bundle.Bundle; import org.apache.falcon.regression.core.enumsAndConstants.ResponseErrors; import org.apache.falcon.regression.core.helpers.ColoHelper; import org.apache.falcon.regression.core.util.BundleUtil; import org.apache.falcon.regression.core.util.HadoopUtil; import org.apache.falcon.regression.core.util.InstanceUtil; import org.apache.falcon.regression.core.util.OSUtil; import org.apache.falcon.regression.core.util.OozieUtil; import org.apache.falcon.regression.core.util.TimeUtil; import org.apache.falcon.regression.core.util.Util; import org.apache.falcon.regression.testHelper.BaseTestClass; import org.apache.falcon.resource.InstancesResult; import org.apache.hadoop.fs.FileSystem; import org.apache.log4j.Logger; import org.apache.oozie.client.CoordinatorAction; import org.apache.oozie.client.OozieClient; import org.apache.oozie.client.WorkflowJob.Status; import org.testng.Assert; import org.testng.annotations.AfterMethod; import org.testng.annotations.BeforeClass; import org.testng.annotations.BeforeMethod; import org.testng.annotations.Test; import java.util.List; /** * Test Suite for instance rerun. */ @Test(groups = { "distributed", "embedded", "sanity" }) public class ProcessInstanceRerunTest extends BaseTestClass { private boolean restartRequired; private String baseTestDir = cleanAndGetTestDir(); private String aggregateWorkflowDir = baseTestDir + "/aggregator"; private String feedInputPath = baseTestDir + "/input" + MINUTE_DATE_PATTERN; private String feedOutputPath = baseTestDir + "/output-data" + MINUTE_DATE_PATTERN; private String feedInputTimedOutPath = baseTestDir + "/timedout" + MINUTE_DATE_PATTERN; private ColoHelper cluster = servers.get(0); private FileSystem clusterFS = serverFS.get(0); private OozieClient clusterOC = serverOC.get(0); private static final Logger LOGGER = Logger.getLogger(ProcessInstanceRerunTest.class); private static final double TIMEOUT = 10; private String processName; private String start = "?start=2010-01-02T01:00Z"; @BeforeClass(alwaysRun = true) public void createTestData() throws Exception { LOGGER.info("in @BeforeClass"); HadoopUtil.uploadDir(clusterFS, aggregateWorkflowDir, OSUtil.RESOURCES_OOZIE); } @BeforeMethod(alwaysRun = true) public void setup() throws Exception { bundles[0] = BundleUtil.readELBundle(); bundles[0] = new Bundle(bundles[0], cluster); bundles[0].generateUniqueBundle(this); bundles[0].setInputFeedDataPath(feedInputPath); bundles[0].setProcessWorkflow(aggregateWorkflowDir); bundles[0].setProcessPeriodicity(5, TimeUnit.minutes); bundles[0].setOutputFeedPeriodicity(5, TimeUnit.minutes); processName = bundles[0].getProcessName(); } @AfterMethod(alwaysRun = true) public void tearDown() { removeTestClassEntities(); } /** * Schedule process. Kill some instances. Rerun some of that killed. Check that * instances were rerun correctly and other are still killed. * * @throws Exception */ @Test(groups = {"singleCluster"}) public void testProcessInstanceRerunSomeKilled02() throws Exception { bundles[0].setProcessValidity("2010-01-02T01:00Z", "2010-01-02T01:26Z"); bundles[0].setOutputFeedLocationData(feedOutputPath); bundles[0].setProcessConcurrency(5); bundles[0].submitFeedsScheduleProcess(prism); InstanceUtil.waitTillInstancesAreCreated(clusterOC, bundles[0].getProcessData(), 0); OozieUtil.createMissingDependencies(cluster, EntityType.PROCESS, processName, 0); InstanceUtil.waitTillInstanceReachState(clusterOC, processName, 5, CoordinatorAction.Status.RUNNING, EntityType.PROCESS, 5); InstancesResult r = prism.getProcessHelper().getProcessInstanceKill(processName, start + "&end=2010-01-02T01:16Z"); InstanceUtil.validateResponse(r, 4, 0, 0, 0, 4); List<String> wfIDs = InstanceUtil.getWorkflows(clusterOC, processName); prism.getProcessHelper().getProcessInstanceRerun(processName, start + "&end=2010-01-02T01:11Z"); InstanceUtil.areWorkflowsRunning(clusterOC, wfIDs, 6, 5, 1, 0); } /** * Schedule process. Kill some instances. Rerun some of these killed without using -start or * -end parameters. Should fail. * * @throws Exception */ @Test(groups = {"singleCluster"}) public void testProcessInstanceRerunKilledWOParams() throws Exception { bundles[0].setProcessValidity("2010-01-02T01:00Z", "2010-01-02T01:26Z"); bundles[0].setOutputFeedLocationData(feedOutputPath); bundles[0].setProcessConcurrency(5); bundles[0].submitFeedsScheduleProcess(prism); InstanceUtil.waitTillInstancesAreCreated(clusterOC, bundles[0].getProcessData(), 0); OozieUtil.createMissingDependencies(cluster, EntityType.PROCESS, processName, 0); InstanceUtil.waitTillInstanceReachState(clusterOC, processName, 5, CoordinatorAction.Status.RUNNING, EntityType.PROCESS, 5); InstancesResult r = prism.getProcessHelper().getProcessInstanceKill(processName, start + "&end=2010-01-02T01:16Z"); InstanceUtil.validateResponse(r, 4, 0, 0, 0, 4); r = prism.getProcessHelper().getProcessInstanceRerun(processName, null); InstanceUtil.validateError(r, ResponseErrors.UNPARSEABLE_DATE); } /** * Schedule process. Kill some instances. Rerun some of these killed using only * -end parameter. Should fail. * * @throws Exception */ @Test(groups = {"singleCluster"}) public void testProcessInstanceRerunKilledWOStartParam() throws Exception { bundles[0].setProcessValidity("2010-01-02T01:00Z", "2010-01-02T01:26Z"); bundles[0].setOutputFeedLocationData(feedOutputPath); bundles[0].setProcessConcurrency(5); bundles[0].submitFeedsScheduleProcess(prism); InstanceUtil.waitTillInstancesAreCreated(clusterOC, bundles[0].getProcessData(), 0); OozieUtil.createMissingDependencies(cluster, EntityType.PROCESS, processName, 0); InstanceUtil.waitTillInstanceReachState(clusterOC, processName, 5, CoordinatorAction.Status.RUNNING, EntityType.PROCESS, 5); InstancesResult r = prism.getProcessHelper().getProcessInstanceKill(processName, start + "&end=2010-01-02T01:16Z"); InstanceUtil.validateResponse(r, 4, 0, 0, 0, 4); r = prism.getProcessHelper().getProcessInstanceRerun(processName, "?end=2010-01-02T01:11Z"); InstanceUtil.validateError(r, ResponseErrors.UNPARSEABLE_DATE); } /** * Schedule process. Kill some instances. Rerun some of these killed using only * -start parameter. Should fail. * * @throws Exception */ @Test(groups = {"singleCluster"}) public void testProcessInstanceRerunKilledWOEndParam() throws Exception { bundles[0].setProcessValidity("2010-01-02T01:00Z", "2010-01-02T01:26Z"); bundles[0].setOutputFeedLocationData(feedOutputPath); bundles[0].setProcessConcurrency(5); bundles[0].submitFeedsScheduleProcess(prism); InstanceUtil.waitTillInstancesAreCreated(clusterOC, bundles[0].getProcessData(), 0); OozieUtil.createMissingDependencies(cluster, EntityType.PROCESS, processName, 0); InstanceUtil.waitTillInstanceReachState(clusterOC, processName, 5, CoordinatorAction.Status.RUNNING, EntityType.PROCESS, 5); InstancesResult r = prism.getProcessHelper().getProcessInstanceKill(processName, start + "&end=2010-01-02T01:16Z"); InstanceUtil.validateResponse(r, 4, 0, 0, 0, 4); r = prism.getProcessHelper().getProcessInstanceRerun(processName, start); InstanceUtil.validateError(r, ResponseErrors.UNPARSEABLE_DATE); } /** * Schedule process. Kill all instances. Rerun them. Check that they were rerun. * * @throws Exception */ @Test(groups = {"singleCluster"}) public void testProcessInstanceRerunMultipleKilled() throws Exception { bundles[0].setProcessValidity("2010-01-02T01:00Z", "2010-01-02T01:11Z"); bundles[0].setOutputFeedLocationData(feedOutputPath); bundles[0].setProcessConcurrency(5); String process = bundles[0].getProcessData(); LOGGER.info("process: " + Util.prettyPrintXml(process)); bundles[0].submitFeedsScheduleProcess(prism); InstanceUtil.waitTillInstancesAreCreated(clusterOC, bundles[0].getProcessData(), 0); OozieUtil.createMissingDependencies(cluster, EntityType.PROCESS, processName, 0); InstanceUtil.waitTillInstanceReachState(clusterOC, processName, 3, CoordinatorAction.Status.RUNNING, EntityType.PROCESS, 5); InstancesResult r = prism.getProcessHelper() .getProcessInstanceKill(processName, start + "&end=2010-01-02T01:11Z"); InstanceUtil.validateResponse(r, 3, 0, 0, 0, 3); List<String> wfIDs = InstanceUtil.getWorkflows(clusterOC, processName); prism.getProcessHelper(). getProcessInstanceRerun(processName, start + "&end=2010-01-02T01:11Z"); InstanceUtil.areWorkflowsRunning(clusterOC, wfIDs, 3, 3, 0, 0); } /** * Schedule process. Kill some instances. Rerun them. Check that there are no killed * instances left. * * @throws Exception */ @Test(groups = {"singleCluster"}) public void testProcessInstanceRerunSomeKilled01() throws Exception { bundles[0].setProcessValidity("2010-01-02T01:00Z", "2010-01-02T01:26Z"); bundles[0].setOutputFeedLocationData(feedOutputPath); bundles[0].setProcessConcurrency(6); bundles[0].submitFeedsScheduleProcess(prism); InstanceUtil.waitTillInstancesAreCreated(clusterOC, bundles[0].getProcessData(), 0); OozieUtil.createMissingDependencies(cluster, EntityType.PROCESS, processName, 0); InstanceUtil.waitTillInstanceReachState(clusterOC, processName, 6, CoordinatorAction.Status.RUNNING, EntityType.PROCESS, 5); InstancesResult r = prism.getProcessHelper() .getProcessInstanceKill(processName, start + "&end=2010-01-02T01:11Z"); InstanceUtil.validateResponse(r, 3, 0, 0, 0, 3); List<String> wfIDs = InstanceUtil.getWorkflows(clusterOC, processName); prism.getProcessHelper().getProcessInstanceRerun(processName, start + "&end=2010-01-02T01:11Z"); TimeUtil.sleepSeconds(TIMEOUT); InstanceUtil.areWorkflowsRunning(clusterOC, wfIDs, 6, 6, 0, 0); } /** * Schedule process. Kill single instance. Rerun it. Check it was rerun. * * @throws Exception */ @Test(groups = {"singleCluster"}) public void testProcessInstanceRerunSingleKilled() throws Exception { bundles[0].setProcessValidity("2010-01-02T01:00Z", "2010-01-02T01:04Z"); bundles[0].setOutputFeedLocationData(feedOutputPath); bundles[0].setProcessConcurrency(1); bundles[0].submitFeedsScheduleProcess(prism); InstanceUtil.waitTillInstancesAreCreated(clusterOC, bundles[0].getProcessData(), 0); OozieUtil.createMissingDependencies(cluster, EntityType.PROCESS, processName, 0); InstanceUtil.waitTillInstanceReachState(clusterOC, processName, 1, CoordinatorAction.Status.RUNNING, EntityType.PROCESS, 5); prism.getProcessHelper().getProcessInstanceKill(processName, start + "&end=2010-01-02T01:01Z"); String wfID = InstanceUtil.getWorkflows(clusterOC, processName, Status.KILLED).get(0); prism.getProcessHelper().getProcessInstanceRerun(processName, start + "&end=2010-01-02T01:01Z"); Assert.assertTrue(InstanceUtil.isWorkflowRunning(clusterOC, wfID)); } /** * Schedule process. Wait till it got succeeded. Rerun first succeeded instance. Check if it * is running. * * @throws Exception */ @Test(groups = {"singleCluster"}) public void testProcessInstanceRerunSingleSucceeded() throws Exception { bundles[0].setProcessValidity("2010-01-02T01:00Z", "2010-01-02T01:04Z"); bundles[0].setOutputFeedLocationData(feedOutputPath); bundles[0].setProcessConcurrency(6); bundles[0].submitFeedsScheduleProcess(prism); String process = bundles[0].getProcessData(); InstanceUtil.waitTillInstancesAreCreated(clusterOC, process, 0); OozieUtil.createMissingDependencies(cluster, EntityType.PROCESS, processName, 0); InstanceUtil.waitTillInstanceReachState(clusterOC, processName, 1, CoordinatorAction.Status.RUNNING, EntityType.PROCESS, 5); String wfID = InstanceUtil.getWorkflows(clusterOC, processName, Status.RUNNING, Status.SUCCEEDED).get(0); InstanceUtil.waitTillInstanceReachState(clusterOC, processName, 0, CoordinatorAction .Status.SUCCEEDED, EntityType.PROCESS); prism.getProcessHelper().getProcessInstanceRerun(processName, start + "&end=2010-01-02T01:01Z&force=true"); Assert.assertTrue(InstanceUtil.isWorkflowRunning(clusterOC, wfID)); } /** * Schedule process. Suspend its instances. Try to rerun them. Check that instances weren't * rerun and are still suspended. * * @throws Exception */ @Test(groups = {"singleCluster"}) public void testProcessInstanceRerunSingleSuspended() throws Exception { bundles[0].setProcessValidity("2010-01-02T01:00Z", "2010-01-02T01:06Z"); bundles[0].setOutputFeedLocationData(feedOutputPath); bundles[0].setProcessConcurrency(2); bundles[0].submitFeedsScheduleProcess(prism); InstanceUtil.waitTillInstancesAreCreated(clusterOC, bundles[0].getProcessData(), 0); OozieUtil.createMissingDependencies(cluster, EntityType.PROCESS, processName, 0); InstanceUtil.waitTillInstanceReachState(clusterOC, processName, 2, CoordinatorAction.Status.RUNNING, EntityType.PROCESS, 5); prism.getProcessHelper().getProcessInstanceSuspend(processName, start + "&end=2010-01-02T01:06Z"); prism.getProcessHelper().getProcessInstanceRerun(processName, start + "&end=2010-01-02T01:06Z"); Assert.assertEquals(InstanceUtil.getInstanceStatus(clusterOC, processName, 0, 1), CoordinatorAction.Status.SUSPENDED); } /** * Schedule process. Wait till its instances succeed. Rerun them all. Check they are running. * * @throws Exception */ @Test(groups = {"singleCluster"}) public void testProcessInstanceRerunMultipleSucceeded() throws Exception { bundles[0].setProcessValidity("2010-01-02T01:00Z", "2010-01-02T01:08Z"); bundles[0].setOutputFeedLocationData(feedOutputPath); bundles[0].setProcessConcurrency(2); bundles[0].submitFeedsScheduleProcess(prism); InstanceUtil.waitTillInstancesAreCreated(clusterOC, bundles[0].getProcessData(), 0); OozieUtil.createMissingDependencies(cluster, EntityType.PROCESS, processName, 0); InstanceUtil.waitTillInstanceReachState(clusterOC, processName, 2, CoordinatorAction.Status.SUCCEEDED, EntityType.PROCESS); List<String> wfIDs = InstanceUtil.getWorkflows(clusterOC, processName); prism.getProcessHelper().getProcessInstanceRerun(processName, start + "&end=2010-01-02T01:11Z&force=true"); InstanceUtil.areWorkflowsRunning(clusterOC, wfIDs, 2, 2, 0, 0); } /** * Schedule process with invalid input feed data path. Wait till process got timed-out. Rerun * it's instances. Check that they were rerun and are waiting (wait for input data). * * @throws Exception */ @Test(groups = {"singleCluster"}) public void testProcessInstanceRerunTimedOut() throws Exception { bundles[0].setInputFeedDataPath(feedInputTimedOutPath); bundles[0].setProcessValidity("2010-01-02T01:00Z", "2010-01-02T01:11Z"); bundles[0].setProcessTimeOut(2, TimeUnit.minutes); bundles[0].setOutputFeedLocationData(feedOutputPath); bundles[0].setProcessConcurrency(3); bundles[0].submitFeedsScheduleProcess(prism); CoordinatorAction.Status s; InstanceUtil.waitTillInstanceReachState(clusterOC, processName, 1, CoordinatorAction.Status.TIMEDOUT, EntityType.PROCESS); prism.getProcessHelper().getProcessInstanceRerun(processName, start + "&end=2010-01-02T01:11Z"); s = InstanceUtil.getInstanceStatus(clusterOC, processName, 0, 0); Assert.assertEquals(s, CoordinatorAction.Status.WAITING, "instance should have been in WAITING state"); } @Test(groups = {"singleCluster"}, timeOut = 1200000) public void testProcessInstanceRerunFailedPostProcessing() throws Exception { restartRequired=true; bundles[0].setProcessValidity("2015-01-02T01:00Z", "2015-01-02T01:04Z"); bundles[0].setOutputFeedLocationData(feedOutputPath); bundles[0].setProcessConcurrency(1); bundles[0].submitFeedsScheduleProcess(prism); String bundleId = OozieUtil.getLatestBundleID(clusterOC, bundles[0].getProcessName(), EntityType.PROCESS); InstanceUtil.waitTillInstancesAreCreated(clusterOC, bundles[0].getProcessData(), 0); //bring down Server1 colo Util.shutDownService(cluster.getClusterHelper()); OozieUtil.createMissingDependencies(cluster, EntityType.PROCESS, processName, 0); //wait for instance to go in killing state InstanceUtil.waitTillInstanceReachState(clusterOC, processName, 1, CoordinatorAction.Status.KILLED, EntityType.PROCESS, 5); Assert.assertEquals(OozieUtil.getWorkflowActionStatus(clusterOC, bundleId, "post-processing") .contains("KILLED"), true); Assert.assertEquals(OozieUtil.getWorkflowActionStatus(clusterOC, bundleId, "user-action") .contains("SUCCEEDED"), true); //start Server1 colo Util.startService(cluster.getClusterHelper()); TimeUtil.sleepSeconds(10); prism.getProcessHelper().getProcessInstanceRerun(processName, "?start=2015-01-02T01:00Z&end=2015-01-02T01:04Z"); while (!OozieUtil.getWorkflowActionStatus(clusterOC, bundleId, "post-processing").contains("SUCCEEDED")) { TimeUtil.sleepSeconds(10); } } @Test(groups = {"singleCluster"}, timeOut = 1200000) public void testProcessInstanceRerunFailedWorkflowAction() throws Exception { // Defining path to be used in pig script String propPath = cleanAndGetTestDir() + "/rerun"; org.apache.falcon.entity.v0.process.Process processElement = bundles[0].getProcessObject(); Properties properties = new Properties(); Property propertyInput = new Property(); propertyInput.setName("inputPath"); propertyInput.setValue(propPath); Property propertyOutput = new Property(); propertyOutput.setName("outputPath"); propertyOutput.setValue(propPath + "/output"); properties.getProperties().add(propertyInput); properties.getProperties().add(propertyOutput); processElement.setProperties(properties); bundles[0].setProcessData(processElement.toString()); HadoopUtil.uploadDir(clusterFS, aggregateWorkflowDir, OSUtil.MULTIPLE_ACTION_WORKFLOW); HadoopUtil.copyDataToFolder(clusterFS, aggregateWorkflowDir, OSUtil.concat(OSUtil.PIG_DIR, "id.pig")); bundles[0].setProcessValidity("2015-01-02T01:00Z", "2015-01-02T01:04Z"); bundles[0].setOutputFeedLocationData(feedOutputPath); bundles[0].setProcessConcurrency(1); bundles[0].submitFeedsScheduleProcess(prism); String bundleId = OozieUtil.getLatestBundleID(clusterOC, bundles[0].getProcessName(), EntityType.PROCESS); InstanceUtil.waitTillInstancesAreCreated(clusterOC, bundles[0].getProcessData(), 0); OozieUtil.createMissingDependencies(cluster, EntityType.PROCESS, processName, 0); //wait for instance to get killed InstanceUtil.waitTillInstanceReachState(clusterOC, processName, 1, CoordinatorAction.Status.KILLED, EntityType.PROCESS, 5); Assert.assertEquals(OozieUtil.getWorkflowActionStatus(clusterOC, bundleId, "user-action") .contains("KILLED"), true); Assert.assertEquals(OozieUtil.getSubWorkflowActionStatus(clusterOC, bundleId, "user-action", "pig") .contains("KILLED"), true); Assert.assertEquals(OozieUtil.getSubWorkflowActionStatus(clusterOC, bundleId, "user-action", "aggregator") .contains("SUCCEEDED"), true); HadoopUtil.uploadDir(clusterFS, propPath, OSUtil.MULTIPLE_ACTION_WORKFLOW); prism.getProcessHelper().getProcessInstanceRerun(processName, "?start=2015-01-02T01:00Z&end=2015-01-02T01:04Z"); while (!OozieUtil.getSubWorkflowActionStatus(clusterOC, bundleId, "user-action", "pig").contains("SUCCEEDED")) { TimeUtil.sleepSeconds(10); } } }
49.802222
120
0.709339
9d8f7e734627d148c5a1420d6a1461d7533f4c40
1,320
package com.kkb.solr.demo; import org.apache.solr.client.solrj.SolrQuery; import org.apache.solr.client.solrj.impl.HttpSolrServer; import org.apache.solr.client.solrj.response.QueryResponse; import org.apache.solr.common.SolrDocument; import org.apache.solr.common.SolrDocumentList; import org.junit.Before; import org.junit.Test; public class SearchDemo { private HttpSolrServer httpSolrServer; // 提取HttpSolrServer创建 @Before public void init() { // 1. 创建HttpSolrServer对象 // 设置solr服务接口,浏览器客户端地址http://127.0.0.1:8081/solr/#/ String baseURL = "http://solr8080:8080/solr"; this.httpSolrServer = new HttpSolrServer(baseURL); } @Test public void searchTest() throws Exception{ // 创建搜索对象 SolrQuery query = new SolrQuery(); // 设置搜索条件 query.setQuery("*:*"); // query.set("q", "*:*"); // 发起搜索请求 QueryResponse response = this.httpSolrServer.query(query); // 处理搜索结果 SolrDocumentList results = response.getResults(); System.out.println("搜索到的结果总数:" + results.getNumFound()); // 遍历搜索结果 for (SolrDocument solrDocument : results) { System.out.println("----------------------------------------------------"); System.out.println("id:" + solrDocument.get("id")); System.out.println("content" + solrDocument.get("content")); } } }
26.4
78
0.665152
2d17168ba67c2074b880159075c5ac173aa4db3a
3,592
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.syncope.core.provisioning.java.data; import org.apache.syncope.core.persistence.api.entity.EntityFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import org.apache.syncope.common.lib.to.SAML2IdPMetadataTO; import org.apache.syncope.core.persistence.api.entity.auth.SAML2IdPMetadata; import org.apache.syncope.core.provisioning.api.data.SAML2IdPMetadataDataBinder; @Component public class SAML2IdPMetadataDataBinderImpl implements SAML2IdPMetadataDataBinder { @Autowired private EntityFactory entityFactory; private SAML2IdPMetadata getSAML2IdPMetadata( final SAML2IdPMetadata saml2IdPMetadata, final SAML2IdPMetadataTO saml2IdPMetadataTO) { SAML2IdPMetadata saml2IdPMetadataResult = saml2IdPMetadata; if (saml2IdPMetadataResult == null) { saml2IdPMetadataResult = entityFactory.newEntity(SAML2IdPMetadata.class); } saml2IdPMetadataResult.setEncryptionCertificate(saml2IdPMetadataTO.getEncryptionCertificate()); saml2IdPMetadataResult.setEncryptionKey(saml2IdPMetadataTO.getEncryptionKey()); saml2IdPMetadataResult.setMetadata(saml2IdPMetadataTO.getMetadata()); saml2IdPMetadataResult.setSigningCertificate(saml2IdPMetadataTO.getSigningCertificate()); saml2IdPMetadataResult.setSigningKey(saml2IdPMetadataTO.getSigningKey()); saml2IdPMetadataResult.setAppliesTo(saml2IdPMetadataTO.getAppliesTo()); return saml2IdPMetadataResult; } @Override public SAML2IdPMetadata create(final SAML2IdPMetadataTO saml2IdPMetadataTO) { return update(entityFactory.newEntity(SAML2IdPMetadata.class), saml2IdPMetadataTO); } @Override public SAML2IdPMetadata update( final SAML2IdPMetadata saml2IdPMetadata, final SAML2IdPMetadataTO saml2IdPMetadataTO) { return getSAML2IdPMetadata(saml2IdPMetadata, saml2IdPMetadataTO); } @Override public SAML2IdPMetadataTO getSAML2IdPMetadataTO(final SAML2IdPMetadata saml2IdPMetadata) { SAML2IdPMetadataTO saml2IdPMetadataTO = new SAML2IdPMetadataTO(); saml2IdPMetadataTO.setKey(saml2IdPMetadata.getKey()); saml2IdPMetadataTO.setMetadata(saml2IdPMetadata.getMetadata()); saml2IdPMetadataTO.setEncryptionCertificate(saml2IdPMetadata.getEncryptionCertificate()); saml2IdPMetadataTO.setEncryptionKey(saml2IdPMetadata.getEncryptionKey()); saml2IdPMetadataTO.setSigningCertificate(saml2IdPMetadata.getSigningCertificate()); saml2IdPMetadataTO.setSigningKey(saml2IdPMetadata.getSigningKey()); saml2IdPMetadataTO.setAppliesTo(saml2IdPMetadata.getAppliesTo()); return saml2IdPMetadataTO; } }
44.345679
103
0.77784
556ccc831859aed0b9aa9312ffb97c139557fc33
8,047
/* * Copyright 2018 Benjamin Martin * * 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 test.warppoint.commands; import me.kangarko.ui.menu.menues.MenuPagged; import me.kangarko.ui.model.ItemCreator; import net.lapismc.lapiscore.LapisCoreCommand; import net.lapismc.warppoint.WarpPoint; import org.bukkit.DyeColor; import org.bukkit.Material; import org.bukkit.OfflinePlayer; import org.bukkit.command.CommandSender; import org.bukkit.entity.Player; import org.bukkit.event.inventory.ClickType; import org.bukkit.inventory.ItemStack; import test.warppoint.playerdata.Warp; import test.warppoint.playerdata.WarpPointPlayer; public class WarpPointWarpList extends LapisCoreCommand { private final WarpPoint plugin; public WarpPointWarpList(WarpPoint p) { super(p, "warplist", "shows the warps a player has access to", new ArrayList<>(Arrays.asList("warpslist", "listwarp", "listwarps"))); plugin = p; } @Override public void onCommand(CommandSender sender, String[] args) { if (!(sender instanceof Player)) { sender.sendMessage(plugin.config.getMessage("NotAPlayer")); return; } Player p = (Player) sender; if (args.length == 0) { Set<Warp> warps2 = plugin.WPWarps.getAllPublicWarps(); p.sendMessage(plugin.config.getMessage("WarpList.public")); if (warps2.isEmpty()) { p.sendMessage(plugin.config.getMessage("NoWarpsInList")); } else { String warpsString2 = plugin.SecondaryColor + warps2.toString().replace("[", "").replace("]", ""); p.sendMessage(warpsString2); } List<Warp> warps1 = plugin.WPWarps.getPrivateWarps(p.getUniqueId()); p.sendMessage(plugin.config.getMessage("WarpList.private")); if (warps1.isEmpty()) { p.sendMessage(plugin.config.getMessage("NoWarpsInList")); } else { String warpsString1 = plugin.SecondaryColor + warps1.toString().replace("[", "").replace("]", ""); p.sendMessage(warpsString1); } if (plugin.factions) { List<Warp> warps0 = plugin.WPFactions.getFactionWarps(p.getUniqueId()); p.sendMessage(plugin.config.getMessage("WarpList.faction")); if (warps0.isEmpty()) { p.sendMessage(plugin.config.getMessage("NoWarpsInList")); } else { String warpsString0 = plugin.SecondaryColor + warps0.toString().replace("[", "").replace("]", ""); p.sendMessage(warpsString0); } } } else { String typeString = args[0].toLowerCase(); WarpPointPlayer player = new WarpPointPlayer(plugin, p.getUniqueId()); switch (typeString) { case "faction": if (plugin.factions) { List<Warp> warps0 = plugin.WPFactions.getFactionWarps(p.getUniqueId()); if (warps0.isEmpty()) { p.sendMessage(plugin.config.getMessage("NoWarpsInList")); } else { if (plugin.getConfig().getBoolean("WarpListGUI")) { new WarpsListUI(player, warps0, WarpPoint.WarpType.Faction).displayTo(p); } else { p.sendMessage(plugin.config.getMessage("WarpList.faction")); String warpsString0 = plugin.SecondaryColor + warps0.toString().replace("[", "").replace("]", ""); p.sendMessage(warpsString0); } } } else { p.sendMessage(plugin.config.getMessage("FactionsDisabled")); } break; case "private": List<Warp> warps1 = plugin.WPWarps.getPrivateWarps(p.getUniqueId()); if (warps1.isEmpty()) { p.sendMessage(plugin.config.getMessage("NoWarpsInList")); } else { if (plugin.getConfig().getBoolean("WarpListGUI")) { new WarpsListUI(player, warps1, WarpPoint.WarpType.Private).displayTo(p); } else { p.sendMessage(plugin.config.getMessage("WarpList.private")); String warpsString1 = plugin.SecondaryColor + warps1.toString().replace("[", "").replace("]", ""); p.sendMessage(warpsString1); } } break; case "public": Set<Warp> warps2 = plugin.WPWarps.getAllPublicWarps(); if (warps2.isEmpty()) { p.sendMessage(plugin.config.getMessage("NoWarpsInList")); } else { if (plugin.getConfig().getBoolean("WarpListGUI")) { new WarpsListUI(player, warps2, WarpPoint.WarpType.Public).displayTo(p); } else { p.sendMessage(plugin.config.getMessage("WarpList.public")); String warpsString2 = plugin.SecondaryColor + warps2.toString().replace("[", "").replace("]", ""); p.sendMessage(warpsString2); } } break; default: String types; if (plugin.factions) { types = "private/public/faction"; } else { types = "private/public"; } p.sendMessage(plugin.config.getMessage("InvalidType")); p.sendMessage(plugin.config.getMessage("Help.warpList").replace("%types", types)); break; } } } private class WarpsListUI extends MenuPagged<Warp> { final Random r = new Random(System.currentTimeMillis()); final OfflinePlayer op; final WarpPoint.WarpType type; WarpsListUI(WarpPointPlayer p, Iterable<Warp> warps, WarpPoint.WarpType warpType) { super(9 * 2, null, warps); op = p.getPlayer(); type = warpType; setTitle(getMenuTitle()); } @Override protected String getMenuTitle() { return type == null ? "" : "Your " + type.toString() + " warps"; } @Override protected ItemStack convertToItemStack(Warp warp) { return ItemCreator.of(Material.WOOL).color(DyeColor.values()[(r.nextInt(DyeColor.values().length))]) .name(warp.getName()).build().make(); } @Override protected void onMenuClickPaged(Player player, Warp warp, ClickType clickType) { if (clickType.isLeftClick()) { player.closeInventory(); warp.teleportPlayer(player); } } @Override protected boolean updateButtonOnClick() { return false; } @Override protected String[] getInfo() { return new String[]{ "This is a list of your current homes", "", "Left click to teleport!" }; } } }
43.032086
130
0.538586
cf9cc5646f8ecc77c1b42d09e4e6abc3ba377519
213
package org.sagebionetworks.web.client.widget.entity.controller; public interface URLProvEntryView extends ProvenanceEntry { String getURL(); void configure(String title, String url); String getTitle(); }
17.75
64
0.788732
42fb83ea22568bf1f516f3dbee58c497164f27e1
2,538
package com.github.mictaege.lenientfun; import org.junit.Before; import org.junit.Test; import org.mockito.Mock; import java.util.List; import java.util.function.ToIntBiFunction; import static com.github.mictaege.lenientfun.LenientAdapter.toIntBiFunc; import static org.mockito.Mockito.verify; import static org.mockito.MockitoAnnotations.initMocks; public class LenientToIntBiFunctionTest { @Mock private List value0; @Mock private List value1; @Before public void before() { initMocks(this); } @Test public void shouldAcceptToIntBiFunction() { feedLenientToIntBiFunction(value0, value1, (v0, v1) -> v0.size() + v1.size()); verify(value0).size(); verify(value1).size(); } @Test(expected = FunctionalRuntimeException.class) public void shouldHandleRaisedException() { feedLenientToIntBiFunction(value0, value1, (v0, v1) -> { throw new Exception(); }); } @Test public void shouldUseLenientToIntBiFunctionInJava() { final LenientToIntBiFunction<List, List> lenient = (v0, v1) -> v0.size() + v1.size(); feedJavaToIntBiFunction(value0, value1, lenient); verify(value0).size(); verify(value1).size(); } @Test(expected = FunctionalRuntimeException.class) public void shouldUseThrowingLenientToIntBiFunctionInJava() { final LenientToIntBiFunction<List, List> lenient = (v0, v1) -> { throw new Exception(); }; feedJavaToIntBiFunction(value0, value1, lenient); } @Test public void shouldAdaptLenientToIntBiFunction() { feedJavaToIntBiFunction(value0, value1, toIntBiFunc((v0, v1) -> v0.size() + v1.size())); verify(value0).size(); verify(value1).size(); } @Test(expected = FunctionalRuntimeException.class) public void shouldAdaptThrowingLenientToIntBiFunction() { feedJavaToIntBiFunction(value0, value1, toIntBiFunc((v0, v1) -> { throw new Exception(); })); } private <T, U> int feedLenientToIntBiFunction(final T value0, final U value1, final LenientToIntBiFunction<T, U> function) { try { return function.applyAsInt(value0, value1); } catch (final Exception e) { throw new FunctionalRuntimeException(e); } } private <T, U> int feedJavaToIntBiFunction(final T value0, final U value1, final ToIntBiFunction<T, U> function) { return function.applyAsInt(value0, value1); } }
29.511628
128
0.662333
8fe472e65e237bd7287cd6753a84ef182ffa87ea
1,404
package persistencia; import java.sql.Connection; import java.sql.DriverManager; import java.sql.SQLException; /** * @author Maikel Maciel Rönnau * @version 1.0 * @since 06/01/2015 */ public class ConexaoBanco { /*** Atributos estáticos com os dados da conexão com o banco de dados *****/ //Endereço do banco de dados: private static final String URL = "jdbc:mysql://localhost:3306/epti"; //Usuário para autenticação: private static final String USUARIO = "root"; //Senha do usuário para autenticação: private static final String SENHA = "root"; /*** Fim dos atributos da conexão com o banco de dados ********************/ public static Connection getConnection() throws SQLException { //Criando objeto para receber a conexão; Connection c; try { //Atribuindo conexão ao objeto criado: c = DriverManager.getConnection(URL, USUARIO, SENHA); } catch (Exception e) { //Lançando erro: throw new SQLException("Não foi possível estabelecer conexão com o banco de dados, " + "contate o admistrador para resolver este problema. " + e.getMessage()); }//Fecha catch. //Retornando objeto com a conexão: return c; }//Fecha método getConnection. }//Fecha classe.
29.25
96
0.606125
854f73d6a161cafc5ab2e182af23692309196b0c
67,546
begin_unit|revision:0.9.5;language:Java;cregit-version:0.0.1 begin_comment comment|/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ end_comment begin_package package|package name|org operator|. name|apache operator|. name|jackrabbit operator|. name|oak operator|. name|query operator|. name|ast package|; end_package begin_import import|import static name|com operator|. name|google operator|. name|common operator|. name|base operator|. name|Preconditions operator|. name|checkNotNull import|; end_import begin_import import|import static name|com operator|. name|google operator|. name|common operator|. name|collect operator|. name|Lists operator|. name|newArrayList import|; end_import begin_import import|import static name|org operator|. name|apache operator|. name|jackrabbit operator|. name|JcrConstants operator|. name|NT_BASE import|; end_import begin_import import|import name|java operator|. name|util operator|. name|ArrayList import|; end_import begin_import import|import name|java operator|. name|util operator|. name|List import|; end_import begin_import import|import name|java operator|. name|util operator|. name|Set import|; end_import begin_import import|import name|java operator|. name|util operator|. name|concurrent operator|. name|TimeUnit import|; end_import begin_import import|import name|org operator|. name|apache operator|. name|jackrabbit operator|. name|oak operator|. name|api operator|. name|PropertyState import|; end_import begin_import import|import name|org operator|. name|apache operator|. name|jackrabbit operator|. name|oak operator|. name|api operator|. name|PropertyValue import|; end_import begin_import import|import name|org operator|. name|apache operator|. name|jackrabbit operator|. name|oak operator|. name|api operator|. name|Result operator|. name|SizePrecision import|; end_import begin_import import|import name|org operator|. name|apache operator|. name|jackrabbit operator|. name|oak operator|. name|api operator|. name|Tree import|; end_import begin_import import|import name|org operator|. name|apache operator|. name|jackrabbit operator|. name|oak operator|. name|api operator|. name|Type import|; end_import begin_import import|import name|org operator|. name|apache operator|. name|jackrabbit operator|. name|oak operator|. name|commons operator|. name|LazyValue import|; end_import begin_import import|import name|org operator|. name|apache operator|. name|jackrabbit operator|. name|oak operator|. name|commons operator|. name|PathUtils import|; end_import begin_import import|import name|org operator|. name|apache operator|. name|jackrabbit operator|. name|oak operator|. name|core operator|. name|ImmutableRoot import|; end_import begin_import import|import name|org operator|. name|apache operator|. name|jackrabbit operator|. name|oak operator|. name|plugins operator|. name|memory operator|. name|PropertyBuilder import|; end_import begin_import import|import name|org operator|. name|apache operator|. name|jackrabbit operator|. name|oak operator|. name|plugins operator|. name|tree operator|. name|TreeUtil import|; end_import begin_import import|import name|org operator|. name|apache operator|. name|jackrabbit operator|. name|oak operator|. name|query operator|. name|ExecutionContext import|; end_import begin_import import|import name|org operator|. name|apache operator|. name|jackrabbit operator|. name|oak operator|. name|query operator|. name|QueryEngineSettings import|; end_import begin_import import|import name|org operator|. name|apache operator|. name|jackrabbit operator|. name|oak operator|. name|query operator|. name|QueryImpl import|; end_import begin_import import|import name|org operator|. name|apache operator|. name|jackrabbit operator|. name|oak operator|. name|query operator|. name|QueryOptions import|; end_import begin_import import|import name|org operator|. name|apache operator|. name|jackrabbit operator|. name|oak operator|. name|query operator|. name|RuntimeNodeTraversalException import|; end_import begin_import import|import name|org operator|. name|apache operator|. name|jackrabbit operator|. name|oak operator|. name|spi operator|. name|query operator|. name|fulltext operator|. name|FullTextExpression import|; end_import begin_import import|import name|org operator|. name|apache operator|. name|jackrabbit operator|. name|oak operator|. name|query operator|. name|index operator|. name|FilterImpl import|; end_import begin_import import|import name|org operator|. name|apache operator|. name|jackrabbit operator|. name|oak operator|. name|query operator|. name|plan operator|. name|ExecutionPlan import|; end_import begin_import import|import name|org operator|. name|apache operator|. name|jackrabbit operator|. name|oak operator|. name|query operator|. name|plan operator|. name|SelectorExecutionPlan import|; end_import begin_import import|import name|org operator|. name|apache operator|. name|jackrabbit operator|. name|oak operator|. name|spi operator|. name|query operator|. name|Cursor import|; end_import begin_import import|import name|org operator|. name|apache operator|. name|jackrabbit operator|. name|oak operator|. name|plugins operator|. name|index operator|. name|Cursors import|; end_import begin_import import|import name|org operator|. name|apache operator|. name|jackrabbit operator|. name|oak operator|. name|plugins operator|. name|index operator|. name|IndexConstants import|; end_import begin_import import|import name|org operator|. name|apache operator|. name|jackrabbit operator|. name|oak operator|. name|spi operator|. name|query operator|. name|IndexRow import|; end_import begin_import import|import name|org operator|. name|apache operator|. name|jackrabbit operator|. name|oak operator|. name|plugins operator|. name|memory operator|. name|PropertyValues import|; end_import begin_import import|import name|org operator|. name|apache operator|. name|jackrabbit operator|. name|oak operator|. name|spi operator|. name|query operator|. name|QueryConstants import|; end_import begin_import import|import name|org operator|. name|apache operator|. name|jackrabbit operator|. name|oak operator|. name|spi operator|. name|query operator|. name|QueryIndex import|; end_import begin_import import|import name|org operator|. name|apache operator|. name|jackrabbit operator|. name|oak operator|. name|spi operator|. name|query operator|. name|QueryIndex operator|. name|AdvancedQueryIndex import|; end_import begin_import import|import name|org operator|. name|apache operator|. name|jackrabbit operator|. name|oak operator|. name|spi operator|. name|query operator|. name|QueryIndex operator|. name|IndexPlan import|; end_import begin_import import|import name|org operator|. name|apache operator|. name|jackrabbit operator|. name|oak operator|. name|spi operator|. name|state operator|. name|NodeState import|; end_import begin_import import|import name|org operator|. name|apache operator|. name|jackrabbit operator|. name|oak operator|. name|stats operator|. name|StatsOptions import|; end_import begin_import import|import name|org operator|. name|apache operator|. name|jackrabbit operator|. name|oak operator|. name|stats operator|. name|TimerStats import|; end_import begin_import import|import name|org operator|. name|apache operator|. name|jackrabbit operator|. name|oak operator|. name|stats operator|. name|CounterStats import|; end_import begin_import import|import name|org operator|. name|apache operator|. name|jackrabbit operator|. name|oak operator|. name|stats operator|. name|HistogramStats import|; end_import begin_import import|import name|org operator|. name|jetbrains operator|. name|annotations operator|. name|NotNull import|; end_import begin_import import|import name|org operator|. name|jetbrains operator|. name|annotations operator|. name|Nullable import|; end_import begin_import import|import name|org operator|. name|slf4j operator|. name|Logger import|; end_import begin_import import|import name|org operator|. name|slf4j operator|. name|LoggerFactory import|; end_import begin_import import|import name|com operator|. name|google operator|. name|common operator|. name|collect operator|. name|ImmutableSet import|; end_import begin_import import|import name|com operator|. name|google operator|. name|common operator|. name|collect operator|. name|Iterables import|; end_import begin_comment comment|/** * A selector within a query. */ end_comment begin_class specifier|public class|class name|SelectorImpl extends|extends name|SourceImpl block|{ specifier|private specifier|static specifier|final name|Logger name|LOG init|= name|LoggerFactory operator|. name|getLogger argument_list|( name|SelectorImpl operator|. name|class argument_list|) decl_stmt|; specifier|private specifier|static specifier|final name|Boolean name|TIMER_DISABLED init|= name|Boolean operator|. name|getBoolean argument_list|( literal|"oak.query.timerDisabled" argument_list|) decl_stmt|; comment|// The sample rate. Must be a power of 2. specifier|private specifier|static specifier|final name|Long name|TIMER_SAMPLE_RATE init|= name|Long operator|. name|getLong argument_list|( literal|"oak.query.timerSampleRate" argument_list|, literal|0x100 argument_list|) decl_stmt|; specifier|private specifier|static specifier|final name|long name|SLOW_QUERY_HISTOGRAM init|= literal|1 decl_stmt|; specifier|private specifier|static specifier|final name|long name|TOTAL_QUERY_HISTOGRAM init|= literal|0 decl_stmt|; specifier|private specifier|static specifier|final name|String name|SLOW_QUERY_PERCENTILE_METRICS_NAME init|= literal|"SLOW_QUERY_PERCENTILE_METRICS" decl_stmt|; specifier|private specifier|static specifier|final name|String name|SLOW_QUERY_COUNT_NAME init|= literal|"SLOW_QUERY_COUNT" decl_stmt|; specifier|private specifier|static name|long name|timerSampleCounter decl_stmt|; comment|// TODO possibly support using multiple indexes (using index intersection / index merge) specifier|private name|SelectorExecutionPlan name|plan decl_stmt|; comment|/** * The WHERE clause of the query. */ specifier|private name|ConstraintImpl name|queryConstraint decl_stmt|; comment|/** * The join condition of this selector that can be evaluated at execution * time. For the query "select * from nt:base as a inner join nt:base as b * on a.x = b.x", the join condition "a.x = b.x" is only set for the * selector b, as selector a can't evaluate it if it is executed first * (until b is executed). */ specifier|private name|JoinConditionImpl name|joinCondition decl_stmt|; comment|/** * The node type associated with the {@link #nodeTypeName} */ specifier|private specifier|final name|NodeTypeInfo name|nodeTypeInfo decl_stmt|; specifier|private specifier|final name|String name|selectorName decl_stmt|; specifier|private specifier|final name|String name|nodeTypeName decl_stmt|; specifier|private specifier|final name|boolean name|matchesAllTypes decl_stmt|; comment|/** * All of the matching supertypes, or empty if the {@link #matchesAllTypes} * flag is set */ specifier|private specifier|final name|Set argument_list|< name|String argument_list|> name|supertypes decl_stmt|; comment|/** * All of the matching primary subtypes, or empty if the * {@link #matchesAllTypes} flag is set */ specifier|private specifier|final name|Set argument_list|< name|String argument_list|> name|primaryTypes decl_stmt|; comment|/** * All of the matching mixin types, or empty if the {@link #matchesAllTypes} * flag is set */ specifier|private specifier|final name|Set argument_list|< name|String argument_list|> name|mixinTypes decl_stmt|; comment|/** * Whether this selector is the parent of a descendent or parent-child join. * Access rights don't need to be checked in such selectors (unless there * are conditions on the selector). */ specifier|private name|boolean name|isParent decl_stmt|; comment|/** * Whether this selector is the left hand side of a left outer join. * Right outer joins are converted to left outer join. */ specifier|private name|boolean name|outerJoinLeftHandSide decl_stmt|; comment|/** * Whether this selector is the right hand side of a left outer join. * Right outer joins are converted to left outer join. */ specifier|private name|boolean name|outerJoinRightHandSide decl_stmt|; comment|/** * The list of all join conditions this selector is involved. For the query * "select * from nt:base as a inner join nt:base as b on a.x = * b.x", the join condition "a.x = b.x" is set for both selectors a and b, * so both can check if the property x is set. * The join conditions are added during the init phase. */ specifier|private name|ArrayList argument_list|< name|JoinConditionImpl argument_list|> name|allJoinConditions init|= operator|new name|ArrayList argument_list|< name|JoinConditionImpl argument_list|> argument_list|() decl_stmt|; comment|/** * The selector constraints can be evaluated when the given selector is * evaluated. For example, for the query * "select * from nt:base a inner join nt:base b where a.x = 1 and b.y = 2", * the condition "a.x = 1" can be evaluated when evaluating selector a. The * other part of the condition can't be evaluated until b is available. * These constraints are collected during the prepare phase. */ specifier|private specifier|final name|List argument_list|< name|ConstraintImpl argument_list|> name|selectorConstraints init|= name|newArrayList argument_list|() decl_stmt|; specifier|private name|Cursor name|cursor decl_stmt|; specifier|private name|IndexRow name|currentRow decl_stmt|; specifier|private name|int name|scanCount decl_stmt|; specifier|private name|String name|planIndexName decl_stmt|; specifier|private name|TimerStats name|timerDuration decl_stmt|; specifier|private name|CachedTree name|cachedTree decl_stmt|; specifier|private name|boolean name|updateTotalQueryHistogram init|= literal|true decl_stmt|; specifier|public name|SelectorImpl parameter_list|( name|NodeTypeInfo name|nodeTypeInfo parameter_list|, name|String name|selectorName parameter_list|) block|{ name|this operator|. name|nodeTypeInfo operator|= name|checkNotNull argument_list|( name|nodeTypeInfo argument_list|) expr_stmt|; name|this operator|. name|selectorName operator|= name|checkNotNull argument_list|( name|selectorName argument_list|) expr_stmt|; name|this operator|. name|nodeTypeName operator|= name|nodeTypeInfo operator|. name|getNodeTypeName argument_list|() expr_stmt|; name|this operator|. name|matchesAllTypes operator|= name|NT_BASE operator|. name|equals argument_list|( name|nodeTypeName argument_list|) expr_stmt|; if|if condition|( operator|! name|this operator|. name|matchesAllTypes condition|) block|{ name|this operator|. name|supertypes operator|= name|nodeTypeInfo operator|. name|getSuperTypes argument_list|() expr_stmt|; name|supertypes operator|. name|add argument_list|( name|nodeTypeName argument_list|) expr_stmt|; name|this operator|. name|primaryTypes operator|= name|nodeTypeInfo operator|. name|getPrimarySubTypes argument_list|() expr_stmt|; name|this operator|. name|mixinTypes operator|= name|nodeTypeInfo operator|. name|getMixinSubTypes argument_list|() expr_stmt|; if|if condition|( name|nodeTypeInfo operator|. name|isMixin argument_list|() condition|) block|{ name|mixinTypes operator|. name|add argument_list|( name|nodeTypeName argument_list|) expr_stmt|; block|} else|else block|{ name|primaryTypes operator|. name|add argument_list|( name|nodeTypeName argument_list|) expr_stmt|; block|} block|} else|else block|{ name|this operator|. name|supertypes operator|= name|ImmutableSet operator|. name|of argument_list|() expr_stmt|; name|this operator|. name|primaryTypes operator|= name|ImmutableSet operator|. name|of argument_list|() expr_stmt|; name|this operator|. name|mixinTypes operator|= name|ImmutableSet operator|. name|of argument_list|() expr_stmt|; block|} block|} specifier|public name|String name|getSelectorName parameter_list|() block|{ return|return name|selectorName return|; block|} specifier|public name|String name|getNodeType parameter_list|() block|{ return|return name|nodeTypeName return|; block|} specifier|public name|boolean name|matchesAllTypes parameter_list|() block|{ return|return name|matchesAllTypes return|; block|} comment|/** * @return all of the matching supertypes, or empty if the * {@link #matchesAllTypes} flag is set */ annotation|@ name|NotNull specifier|public name|Set argument_list|< name|String argument_list|> name|getSupertypes parameter_list|() block|{ return|return name|supertypes return|; block|} comment|/** * @return all of the matching primary subtypes, or empty if the * {@link #matchesAllTypes} flag is set */ annotation|@ name|NotNull specifier|public name|Set argument_list|< name|String argument_list|> name|getPrimaryTypes parameter_list|() block|{ return|return name|primaryTypes return|; block|} comment|/** * @return all of the matching mixin types, or empty if the * {@link #matchesAllTypes} flag is set */ annotation|@ name|NotNull specifier|public name|Set argument_list|< name|String argument_list|> name|getMixinTypes parameter_list|() block|{ return|return name|mixinTypes return|; block|} specifier|public name|Iterable argument_list|< name|String argument_list|> name|getWildcardColumns parameter_list|() block|{ return|return name|nodeTypeInfo operator|. name|getNamesSingleValuesProperties argument_list|() return|; block|} annotation|@ name|Override name|boolean name|accept parameter_list|( name|AstVisitor name|v parameter_list|) block|{ return|return name|v operator|. name|visit argument_list|( name|this argument_list|) return|; block|} annotation|@ name|Override specifier|public name|String name|toString parameter_list|() block|{ return|return name|quote argument_list|( name|nodeTypeName argument_list|) operator|+ literal|" as " operator|+ name|quote argument_list|( name|selectorName argument_list|) return|; block|} specifier|public name|boolean name|isPrepared parameter_list|() block|{ return|return name|plan operator|!= literal|null return|; block|} annotation|@ name|Override specifier|public name|void name|unprepare parameter_list|() block|{ name|plan operator|= literal|null expr_stmt|; name|planIndexName operator|= literal|null expr_stmt|; name|timerDuration operator|= literal|null expr_stmt|; name|selectorConstraints operator|. name|clear argument_list|() expr_stmt|; name|isParent operator|= literal|false expr_stmt|; name|joinCondition operator|= literal|null expr_stmt|; name|allJoinConditions operator|. name|clear argument_list|() expr_stmt|; block|} annotation|@ name|Override specifier|public name|void name|prepare parameter_list|( name|ExecutionPlan name|p parameter_list|) block|{ if|if condition|( operator|! operator|( name|p operator|instanceof name|SelectorExecutionPlan operator|) condition|) block|{ throw|throw operator|new name|IllegalArgumentException argument_list|( literal|"Not a selector plan" argument_list|) throw|; block|} name|SelectorExecutionPlan name|selectorPlan init|= operator|( name|SelectorExecutionPlan operator|) name|p decl_stmt|; if|if condition|( name|selectorPlan operator|. name|getSelector argument_list|() operator|!= name|this condition|) block|{ throw|throw operator|new name|IllegalArgumentException argument_list|( literal|"Not a plan for this selector" argument_list|) throw|; block|} name|pushDown argument_list|() expr_stmt|; name|this operator|. name|plan operator|= name|selectorPlan expr_stmt|; block|} specifier|private name|void name|pushDown parameter_list|() block|{ if|if condition|( name|queryConstraint operator|!= literal|null condition|) block|{ name|queryConstraint operator|. name|restrictPushDown argument_list|( name|this argument_list|) expr_stmt|; block|} if|if condition|( operator|! name|outerJoinLeftHandSide operator|&& operator|! name|outerJoinRightHandSide condition|) block|{ for|for control|( name|JoinConditionImpl name|c range|: name|allJoinConditions control|) block|{ name|c operator|. name|restrictPushDown argument_list|( name|this argument_list|) expr_stmt|; block|} block|} block|} annotation|@ name|Override specifier|public name|ExecutionPlan name|prepare parameter_list|() block|{ if|if condition|( name|plan operator|!= literal|null condition|) block|{ return|return name|plan return|; block|} name|pushDown argument_list|() expr_stmt|; name|plan operator|= name|query operator|. name|getBestSelectorExecutionPlan argument_list|( name|createFilter argument_list|( literal|true argument_list|) argument_list|) expr_stmt|; return|return name|plan return|; block|} specifier|public name|SelectorExecutionPlan name|getExecutionPlan parameter_list|() block|{ return|return name|plan return|; block|} annotation|@ name|Override specifier|public name|void name|setQueryConstraint parameter_list|( name|ConstraintImpl name|queryConstraint parameter_list|) block|{ name|this operator|. name|queryConstraint operator|= name|queryConstraint expr_stmt|; block|} annotation|@ name|Override specifier|public name|void name|setOuterJoin parameter_list|( name|boolean name|outerJoinLeftHandSide parameter_list|, name|boolean name|outerJoinRightHandSide parameter_list|) block|{ name|this operator|. name|outerJoinLeftHandSide operator|= name|outerJoinLeftHandSide expr_stmt|; name|this operator|. name|outerJoinRightHandSide operator|= name|outerJoinRightHandSide expr_stmt|; block|} annotation|@ name|Override specifier|public name|void name|addJoinCondition parameter_list|( name|JoinConditionImpl name|joinCondition parameter_list|, name|boolean name|forThisSelector parameter_list|) block|{ if|if condition|( name|forThisSelector condition|) block|{ name|this operator|. name|joinCondition operator|= name|joinCondition expr_stmt|; block|} name|allJoinConditions operator|. name|add argument_list|( name|joinCondition argument_list|) expr_stmt|; if|if condition|( name|joinCondition operator|. name|isParent argument_list|( name|this argument_list|) condition|) block|{ name|isParent operator|= literal|true expr_stmt|; block|} block|} annotation|@ name|Override specifier|public name|void name|execute parameter_list|( name|NodeState name|rootState parameter_list|) block|{ name|long name|start init|= name|startTimer argument_list|() decl_stmt|; try|try block|{ name|executeInternal argument_list|( name|rootState argument_list|) expr_stmt|; block|} finally|finally block|{ name|stopTimer argument_list|( name|start argument_list|, literal|true argument_list|) expr_stmt|; block|} block|} specifier|private name|void name|executeInternal parameter_list|( name|NodeState name|rootState parameter_list|) block|{ name|QueryIndex name|index init|= name|plan operator|. name|getIndex argument_list|() decl_stmt|; name|timerDuration operator|= literal|null expr_stmt|; if|if condition|( name|index operator|== literal|null condition|) block|{ name|cursor operator|= name|Cursors operator|. name|newPathCursor argument_list|( operator|new name|ArrayList argument_list|< name|String argument_list|> argument_list|() argument_list|, name|query operator|. name|getSettings argument_list|() argument_list|) expr_stmt|; name|planIndexName operator|= literal|"traverse" expr_stmt|; return|return; block|} name|IndexPlan name|p init|= name|plan operator|. name|getIndexPlan argument_list|() decl_stmt|; if|if condition|( name|p operator|!= literal|null condition|) block|{ name|planIndexName operator|= name|p operator|. name|getPlanName argument_list|() expr_stmt|; name|p operator|. name|setFilter argument_list|( name|createFilter argument_list|( literal|false argument_list|) argument_list|) expr_stmt|; name|AdvancedQueryIndex name|adv init|= operator|( name|AdvancedQueryIndex operator|) name|index decl_stmt|; name|cursor operator|= name|adv operator|. name|query argument_list|( name|p argument_list|, name|rootState argument_list|) expr_stmt|; block|} else|else block|{ name|FilterImpl name|f init|= name|createFilter argument_list|( literal|false argument_list|) decl_stmt|; name|planIndexName operator|= name|index operator|. name|getIndexName argument_list|( name|f argument_list|, name|rootState argument_list|) expr_stmt|; name|cursor operator|= name|index operator|. name|query argument_list|( name|f argument_list|, name|rootState argument_list|) expr_stmt|; block|} block|} specifier|private name|long name|startTimer parameter_list|() block|{ if|if condition|( name|TIMER_DISABLED condition|) block|{ return|return operator|- literal|1 return|; block|} return|return name|System operator|. name|nanoTime argument_list|() return|; block|} specifier|private name|void name|stopTimer parameter_list|( name|long name|start parameter_list|, name|boolean name|execute parameter_list|) block|{ if|if condition|( name|start operator|== operator|- literal|1 condition|) block|{ return|return; block|} name|long name|timeNanos init|= name|System operator|. name|nanoTime argument_list|() operator|- name|start decl_stmt|; if|if condition|( name|timeNanos operator|> literal|1000000 condition|) block|{ comment|// always measure slow events (slower than 1 ms) name|measure argument_list|( name|timeNanos argument_list|) expr_stmt|; block|} elseif|else if|if condition|( operator|( name|timerSampleCounter operator|++ operator|& operator|( name|TIMER_SAMPLE_RATE operator|- literal|1 operator|) operator|) operator|== literal|0 condition|) block|{ comment|// only measure each xth fast event, but multiply by x, so on comment|// average measured times are correct name|measure argument_list|( name|timeNanos operator|* name|TIMER_SAMPLE_RATE argument_list|) expr_stmt|; block|} block|} specifier|private name|void name|measure parameter_list|( name|long name|timeNanos parameter_list|) block|{ name|TimerStats name|t init|= name|timerDuration decl_stmt|; if|if condition|( name|t operator|== literal|null condition|) block|{ comment|// reuse the timer (in the normal case) name|t operator|= name|timerDuration operator|= name|query operator|. name|getSettings argument_list|() operator|. name|getStatisticsProvider argument_list|() operator|. name|getTimer argument_list|( literal|"QUERY_DURATION_" operator|+ name|planIndexName argument_list|, name|StatsOptions operator|. name|METRICS_ONLY argument_list|) expr_stmt|; block|} name|t operator|. name|update argument_list|( name|timeNanos argument_list|, name|TimeUnit operator|. name|NANOSECONDS argument_list|) expr_stmt|; block|} annotation|@ name|Override specifier|public name|String name|getPlan parameter_list|( name|NodeState name|rootState parameter_list|) block|{ name|StringBuilder name|buff init|= operator|new name|StringBuilder argument_list|() decl_stmt|; name|buff operator|. name|append argument_list|( name|toString argument_list|() argument_list|) expr_stmt|; name|buff operator|. name|append argument_list|( literal|" /* " argument_list|) expr_stmt|; name|QueryIndex name|index init|= name|getIndex argument_list|() decl_stmt|; if|if condition|( name|index operator|!= literal|null condition|) block|{ if|if condition|( name|index operator|instanceof name|AdvancedQueryIndex condition|) block|{ name|AdvancedQueryIndex name|adv init|= operator|( name|AdvancedQueryIndex operator|) name|index decl_stmt|; name|IndexPlan name|p init|= name|plan operator|. name|getIndexPlan argument_list|() decl_stmt|; name|buff operator|. name|append argument_list|( name|adv operator|. name|getPlanDescription argument_list|( name|p argument_list|, name|rootState argument_list|) argument_list|) expr_stmt|; block|} else|else block|{ name|buff operator|. name|append argument_list|( name|index operator|. name|getPlan argument_list|( name|createFilter argument_list|( literal|true argument_list|) argument_list|, name|rootState argument_list|) argument_list|) expr_stmt|; block|} block|} else|else block|{ name|buff operator|. name|append argument_list|( literal|"no-index" argument_list|) expr_stmt|; block|} if|if condition|( operator|! name|selectorConstraints operator|. name|isEmpty argument_list|() condition|) block|{ name|buff operator|. name|append argument_list|( literal|" where " argument_list|) operator|. name|append argument_list|( operator|new name|AndImpl argument_list|( name|selectorConstraints argument_list|) operator|. name|toString argument_list|() argument_list|) expr_stmt|; block|} name|buff operator|. name|append argument_list|( literal|" */" argument_list|) expr_stmt|; return|return name|buff operator|. name|toString argument_list|() return|; block|} annotation|@ name|Override specifier|public name|String name|getIndexCostInfo parameter_list|( name|NodeState name|rootState parameter_list|) block|{ name|StringBuilder name|buff init|= operator|new name|StringBuilder argument_list|() decl_stmt|; name|buff operator|. name|append argument_list|( name|quoteJson argument_list|( name|selectorName argument_list|) argument_list|) operator|. name|append argument_list|( literal|": " argument_list|) expr_stmt|; name|QueryIndex name|index init|= name|getIndex argument_list|() decl_stmt|; if|if condition|( name|index operator|!= literal|null condition|) block|{ if|if condition|( name|index operator|instanceof name|AdvancedQueryIndex condition|) block|{ name|IndexPlan name|p init|= name|plan operator|. name|getIndexPlan argument_list|() decl_stmt|; name|buff operator|. name|append argument_list|( literal|"{ perEntry: " argument_list|) operator|. name|append argument_list|( name|p operator|. name|getCostPerEntry argument_list|() argument_list|) expr_stmt|; name|buff operator|. name|append argument_list|( literal|", perExecution: " argument_list|) operator|. name|append argument_list|( name|p operator|. name|getCostPerExecution argument_list|() argument_list|) expr_stmt|; name|buff operator|. name|append argument_list|( literal|", count: " argument_list|) operator|. name|append argument_list|( name|p operator|. name|getEstimatedEntryCount argument_list|() argument_list|) expr_stmt|; name|buff operator|. name|append argument_list|( literal|" }" argument_list|) expr_stmt|; block|} else|else block|{ name|buff operator|. name|append argument_list|( name|index operator|. name|getCost argument_list|( name|createFilter argument_list|( literal|true argument_list|) argument_list|, name|rootState argument_list|) argument_list|) expr_stmt|; block|} block|} return|return name|buff operator|. name|toString argument_list|() return|; block|} comment|/** * Create the filter condition for planning or execution. * * @param preparing whether a filter for the prepare phase should be made * @return the filter */ annotation|@ name|Override specifier|public name|FilterImpl name|createFilter parameter_list|( name|boolean name|preparing parameter_list|) block|{ name|FilterImpl name|f init|= operator|new name|FilterImpl argument_list|( name|this argument_list|, name|query operator|. name|getStatement argument_list|() argument_list|, name|query operator|. name|getSettings argument_list|() argument_list|) decl_stmt|; name|f operator|. name|setPreparing argument_list|( name|preparing argument_list|) expr_stmt|; if|if condition|( name|joinCondition operator|!= literal|null condition|) block|{ name|joinCondition operator|. name|restrict argument_list|( name|f argument_list|) expr_stmt|; block|} comment|// rep:excerpt handling: create a (fake) restriction comment|// "rep:excerpt is not null" to let the index know that comment|// we will need the excerpt for|for control|( name|ColumnImpl name|c range|: name|query operator|. name|getColumns argument_list|() control|) block|{ if|if condition|( name|c operator|. name|getSelector argument_list|() operator|. name|equals argument_list|( name|this argument_list|) condition|) block|{ name|String name|columnName init|= name|c operator|. name|getColumnName argument_list|() decl_stmt|; if|if condition|( name|columnName operator|. name|equals argument_list|( name|QueryConstants operator|. name|OAK_SCORE_EXPLANATION argument_list|) condition|) block|{ name|f operator|. name|restrictProperty argument_list|( name|columnName argument_list|, name|Operator operator|. name|NOT_EQUAL argument_list|, literal|null argument_list|) expr_stmt|; block|} elseif|else if|if condition|( name|columnName operator|. name|startsWith argument_list|( name|QueryConstants operator|. name|REP_EXCERPT argument_list|) condition|) block|{ name|f operator|. name|restrictProperty argument_list|( name|QueryConstants operator|. name|REP_EXCERPT argument_list|, name|Operator operator|. name|EQUAL argument_list|, name|PropertyValues operator|. name|newString argument_list|( name|columnName argument_list|) argument_list|) expr_stmt|; block|} elseif|else if|if condition|( name|columnName operator|. name|startsWith argument_list|( name|QueryConstants operator|. name|REP_FACET argument_list|) condition|) block|{ name|f operator|. name|restrictProperty argument_list|( name|QueryConstants operator|. name|REP_FACET argument_list|, name|Operator operator|. name|EQUAL argument_list|, name|PropertyValues operator|. name|newString argument_list|( name|columnName argument_list|) argument_list|) expr_stmt|; block|} block|} block|} comment|// all conditions can be pushed to the selectors - comment|// except in some cases to "outer joined" selectors, comment|// but the exceptions are handled in the condition comment|// itself. comment|// An example where it *is* a problem: comment|// "select * from a left outer join b on a.x = b.y comment|// where b.y is null" - in this case the selector b comment|// must not use an index condition on "y is null" comment|// (".. is null" must be written as "not .. is not null"). if|if condition|( name|queryConstraint operator|!= literal|null condition|) block|{ name|queryConstraint operator|. name|restrict argument_list|( name|f argument_list|) expr_stmt|; name|FullTextExpression name|ft init|= name|queryConstraint operator|. name|getFullTextConstraint argument_list|( name|this argument_list|) decl_stmt|; name|f operator|. name|setFullTextConstraint argument_list|( name|ft argument_list|) expr_stmt|; block|} for|for control|( name|ConstraintImpl name|constraint range|: name|selectorConstraints control|) block|{ name|constraint operator|. name|restrict argument_list|( name|f argument_list|) expr_stmt|; block|} name|QueryOptions name|options init|= name|query operator|. name|getQueryOptions argument_list|() decl_stmt|; if|if condition|( name|options operator|!= literal|null condition|) block|{ if|if condition|( name|options operator|. name|indexName operator|!= literal|null condition|) block|{ name|f operator|. name|restrictProperty argument_list|( name|IndexConstants operator|. name|INDEX_NAME_OPTION argument_list|, name|Operator operator|. name|EQUAL argument_list|, name|PropertyValues operator|. name|newString argument_list|( name|options operator|. name|indexName argument_list|) argument_list|) expr_stmt|; block|} if|if condition|( name|options operator|. name|indexTag operator|!= literal|null condition|) block|{ name|f operator|. name|restrictProperty argument_list|( name|IndexConstants operator|. name|INDEX_TAG_OPTION argument_list|, name|Operator operator|. name|EQUAL argument_list|, name|PropertyValues operator|. name|newString argument_list|( name|options operator|. name|indexTag argument_list|) argument_list|) expr_stmt|; block|} block|} return|return name|f return|; block|} annotation|@ name|Override specifier|public name|boolean name|next parameter_list|() block|{ name|long name|start init|= name|startTimer argument_list|() decl_stmt|; try|try block|{ return|return name|nextInternal argument_list|() return|; block|} finally|finally block|{ name|stopTimer argument_list|( name|start argument_list|, literal|true argument_list|) expr_stmt|; block|} block|} specifier|private name|boolean name|nextInternal parameter_list|() block|{ while|while condition|( name|cursor operator|!= literal|null operator|&& name|cursor operator|. name|hasNext argument_list|() condition|) block|{ name|scanCount operator|++ expr_stmt|; name|query operator|. name|getQueryExecutionStats argument_list|() operator|. name|scan argument_list|( literal|1 argument_list|, name|scanCount argument_list|) expr_stmt|; try|try block|{ name|totalQueryStats argument_list|( name|query operator|. name|getSettings argument_list|() argument_list|) expr_stmt|; name|currentRow operator|= name|cursor operator|. name|next argument_list|() expr_stmt|; block|} catch|catch parameter_list|( name|RuntimeNodeTraversalException name|e parameter_list|) block|{ name|addSlowQueryStats argument_list|( name|query operator|. name|getSettings argument_list|() argument_list|) expr_stmt|; name|LOG operator|. name|warn argument_list|( name|e operator|. name|getMessage argument_list|() operator|+ literal|" for query " operator|+ name|query operator|. name|getStatement argument_list|() argument_list|) expr_stmt|; throw|throw name|e throw|; block|} if|if condition|( name|isParent condition|) block|{ comment|// we must not check whether the _parent_ is readable comment|// for joins of type comment|// "select [b].[jcr:primaryType] comment|// from [nt:base] as [a] comment|// inner join [nt:base] as [b] comment|// on isdescendantnode([b], [a]) comment|// where [b].[jcr:path] = $path" comment|// because if we did, we would filter out comment|// correct results block|} elseif|else if|if condition|( name|currentRow operator|. name|isVirtualRow argument_list|() condition|) block|{ comment|// this is a virtual row and should be selected as is return|return literal|true return|; block|} else|else block|{ comment|// we must check whether the _child_ is readable comment|// (even if no properties are read) for joins of type comment|// "select [a].[jcr:primaryType] comment|// from [nt:base] as [a] comment|// inner join [nt:base] as [b] comment|// on isdescendantnode([b], [a]) comment|// where [a].[jcr:path] = $path" comment|// because not checking would reveal existence comment|// of the child node if|if condition|( operator|! name|getCachedTree argument_list|( name|currentRow operator|. name|getPath argument_list|() argument_list|) operator|. name|exists argument_list|() condition|) block|{ continue|continue; block|} block|} if|if condition|( name|evaluateCurrentRow argument_list|() condition|) block|{ return|return literal|true return|; block|} block|} name|cursor operator|= literal|null expr_stmt|; name|currentRow operator|= literal|null expr_stmt|; return|return literal|false return|; block|} specifier|private name|void name|totalQueryStats parameter_list|( name|QueryEngineSettings name|queryEngineSettings parameter_list|) block|{ if|if condition|( name|updateTotalQueryHistogram condition|) block|{ name|updateTotalQueryHistogram operator|= literal|false expr_stmt|; name|HistogramStats name|histogramStats init|= name|queryEngineSettings operator|. name|getStatisticsProvider argument_list|() operator|. name|getHistogram argument_list|( name|SLOW_QUERY_PERCENTILE_METRICS_NAME argument_list|, name|StatsOptions operator|. name|METRICS_ONLY argument_list|) decl_stmt|; name|histogramStats operator|. name|update argument_list|( name|TOTAL_QUERY_HISTOGRAM argument_list|) expr_stmt|; block|} block|} specifier|private name|void name|addSlowQueryStats parameter_list|( name|QueryEngineSettings name|queryEngineSettings parameter_list|) block|{ name|HistogramStats name|histogramStats init|= name|queryEngineSettings operator|. name|getStatisticsProvider argument_list|() operator|. name|getHistogram argument_list|( name|SLOW_QUERY_PERCENTILE_METRICS_NAME argument_list|, name|StatsOptions operator|. name|METRICS_ONLY argument_list|) decl_stmt|; name|histogramStats operator|. name|update argument_list|( name|SLOW_QUERY_HISTOGRAM argument_list|) expr_stmt|; name|CounterStats name|slowQueryCounter init|= name|queryEngineSettings operator|. name|getStatisticsProvider argument_list|() operator|. name|getCounterStats argument_list|( name|SLOW_QUERY_COUNT_NAME argument_list|, name|StatsOptions operator|. name|METRICS_ONLY argument_list|) decl_stmt|; name|slowQueryCounter operator|. name|inc argument_list|() expr_stmt|; block|} specifier|private name|boolean name|evaluateCurrentRow parameter_list|() block|{ if|if condition|( name|currentRow operator|. name|isVirtualRow argument_list|() condition|) block|{ comment|//null path implies that all checks are already done -- we just need to pass it through return|return literal|true return|; block|} if|if condition|( operator|! name|matchesAllTypes operator|&& operator|! name|evaluateTypeMatch argument_list|() condition|) block|{ return|return literal|false return|; block|} for|for control|( name|ConstraintImpl name|constraint range|: name|selectorConstraints control|) block|{ if|if condition|( operator|! name|constraint operator|. name|evaluate argument_list|() condition|) block|{ if|if condition|( name|constraint operator|. name|evaluateStop argument_list|() condition|) block|{ comment|// stop processing from now on name|cursor operator|= literal|null expr_stmt|; block|} return|return literal|false return|; block|} block|} if|if condition|( name|joinCondition operator|!= literal|null operator|&& operator|! name|joinCondition operator|. name|evaluate argument_list|() condition|) block|{ return|return literal|false return|; block|} return|return literal|true return|; block|} specifier|private name|boolean name|evaluateTypeMatch parameter_list|() block|{ name|CachedTree name|ct init|= name|getCachedTree argument_list|( name|currentRow operator|. name|getPath argument_list|() argument_list|) decl_stmt|; if|if condition|( operator|! name|ct operator|. name|exists argument_list|() condition|) block|{ return|return literal|false return|; block|} name|Tree name|t init|= name|ct operator|. name|getTree argument_list|() decl_stmt|; name|LazyValue argument_list|< name|Tree argument_list|> name|readOnly init|= name|ct operator|. name|getReadOnlyTree argument_list|() decl_stmt|; name|String name|primaryTypeName init|= name|TreeUtil operator|. name|getPrimaryTypeName argument_list|( name|t argument_list|, name|readOnly argument_list|) decl_stmt|; if|if condition|( name|primaryTypeName operator|!= literal|null operator|&& name|primaryTypes operator|. name|contains argument_list|( name|primaryTypeName argument_list|) condition|) block|{ return|return literal|true return|; block|} for|for control|( name|String name|mixinName range|: name|TreeUtil operator|. name|getMixinTypeNames argument_list|( name|t argument_list|, name|readOnly argument_list|) control|) block|{ if|if condition|( name|mixinTypes operator|. name|contains argument_list|( name|mixinName argument_list|) condition|) block|{ return|return literal|true return|; block|} block|} comment|// no matches found return|return literal|false return|; block|} comment|/** * Get the current absolute Oak path (normalized). * * @return the path */ specifier|public name|String name|currentPath parameter_list|() block|{ return|return name|cursor operator|== literal|null condition|? literal|null else|: name|currentRow operator|. name|getPath argument_list|() return|; block|} comment|/** * Get the tree at the current path. * * @return the current tree, or null */ annotation|@ name|Nullable specifier|public name|Tree name|currentTree parameter_list|() block|{ name|String name|path init|= name|currentPath argument_list|() decl_stmt|; if|if condition|( name|path operator|== literal|null condition|) block|{ return|return literal|null return|; block|} return|return name|getTree argument_list|( name|path argument_list|) return|; block|} annotation|@ name|Nullable name|Tree name|getTree parameter_list|( annotation|@ name|NotNull name|String name|path parameter_list|) block|{ return|return name|getCachedTree argument_list|( name|path argument_list|) operator|. name|getTree argument_list|() return|; block|} comment|/** * Get the tree at the given path. * * @param path the path * @return the tree, or null */ annotation|@ name|NotNull specifier|private name|CachedTree name|getCachedTree parameter_list|( annotation|@ name|NotNull name|String name|path parameter_list|) block|{ if|if condition|( name|cachedTree operator|== literal|null operator||| operator|! name|cachedTree operator|. name|denotes argument_list|( name|path argument_list|) condition|) block|{ name|cachedTree operator|= operator|new name|CachedTree argument_list|( name|path argument_list|, name|query argument_list|) expr_stmt|; block|} return|return name|cachedTree return|; block|} comment|/** * The value for the given selector for the current node. * * @param propertyName the JCR (not normalized) property name * @return the property value */ specifier|public name|PropertyValue name|currentProperty parameter_list|( name|String name|propertyName parameter_list|) block|{ name|String name|pn init|= name|normalizePropertyName argument_list|( name|propertyName argument_list|) decl_stmt|; return|return name|currentOakProperty argument_list|( name|pn argument_list|) return|; block|} comment|/** * The value for the given selector for the current node, filtered by * property type. * * @param propertyName the JCR (not normalized) property name * @param propertyType only include properties of this type * @return the property value (possibly null) */ specifier|public name|PropertyValue name|currentProperty parameter_list|( name|String name|propertyName parameter_list|, name|int name|propertyType parameter_list|) block|{ name|String name|pn init|= name|normalizePropertyName argument_list|( name|propertyName argument_list|) decl_stmt|; return|return name|currentOakProperty argument_list|( name|pn argument_list|, name|propertyType argument_list|) return|; block|} comment|/** * Get the property value. The property name may be relative. The special * property names "jcr:path", "jcr:score" and "rep:excerpt" are supported. * * @param oakPropertyName (must already be normalized) * @return the property value or null if not found */ specifier|public name|PropertyValue name|currentOakProperty parameter_list|( name|String name|oakPropertyName parameter_list|) block|{ return|return name|currentOakProperty argument_list|( name|oakPropertyName argument_list|, literal|null argument_list|) return|; block|} specifier|private name|PropertyValue name|currentOakProperty parameter_list|( name|String name|oakPropertyName parameter_list|, name|Integer name|propertyType parameter_list|) block|{ name|boolean name|asterisk init|= name|oakPropertyName operator|. name|indexOf argument_list|( literal|'*' argument_list|) operator|>= literal|0 decl_stmt|; if|if condition|( name|asterisk condition|) block|{ name|Tree name|t init|= name|currentTree argument_list|() decl_stmt|; if|if condition|( name|t operator|!= literal|null condition|) block|{ name|LOG operator|. name|trace argument_list|( literal|"currentOakProperty() - '*' case. looking for '{}' in '{}'" argument_list|, name|oakPropertyName argument_list|, name|t operator|. name|getPath argument_list|() argument_list|) expr_stmt|; block|} name|ArrayList argument_list|< name|PropertyValue argument_list|> name|list init|= operator|new name|ArrayList argument_list|< name|PropertyValue argument_list|> argument_list|() decl_stmt|; name|readOakProperties argument_list|( name|list argument_list|, name|t argument_list|, name|oakPropertyName argument_list|, name|propertyType argument_list|) expr_stmt|; if|if condition|( name|list operator|. name|size argument_list|() operator|== literal|0 condition|) block|{ return|return literal|null return|; block|} elseif|else if|if condition|( name|list operator|. name|size argument_list|() operator|== literal|1 condition|) block|{ return|return name|list operator|. name|get argument_list|( literal|0 argument_list|) return|; block|} name|Type argument_list|< name|? argument_list|> name|type init|= name|list operator|. name|get argument_list|( literal|0 argument_list|) operator|. name|getType argument_list|() decl_stmt|; for|for control|( name|int name|i init|= literal|1 init|; name|i operator|< name|list operator|. name|size argument_list|() condition|; name|i operator|++ control|) block|{ name|Type argument_list|< name|? argument_list|> name|t2 init|= name|list operator|. name|get argument_list|( name|i argument_list|) operator|. name|getType argument_list|() decl_stmt|; if|if condition|( name|t2 operator|!= name|type condition|) block|{ comment|// types don't match name|type operator|= name|Type operator|. name|STRING expr_stmt|; break|break; block|} block|} if|if condition|( name|type operator|== name|Type operator|. name|STRING condition|) block|{ name|ArrayList argument_list|< name|String argument_list|> name|strings init|= operator|new name|ArrayList argument_list|< name|String argument_list|> argument_list|() decl_stmt|; for|for control|( name|PropertyValue name|p range|: name|list control|) block|{ name|Iterables operator|. name|addAll argument_list|( name|strings argument_list|, name|p operator|. name|getValue argument_list|( name|Type operator|. name|STRINGS argument_list|) argument_list|) expr_stmt|; block|} return|return name|PropertyValues operator|. name|newString argument_list|( name|strings argument_list|) return|; block|} name|Type argument_list|< name|? argument_list|> name|baseType init|= name|type operator|. name|isArray argument_list|() condition|? name|type operator|. name|getBaseType argument_list|() else|: name|type decl_stmt|; annotation|@ name|SuppressWarnings argument_list|( literal|"unchecked" argument_list|) name|PropertyBuilder argument_list|< name|Object argument_list|> name|builder init|= operator|( name|PropertyBuilder argument_list|< name|Object argument_list|> operator|) name|PropertyBuilder operator|. name|array argument_list|( name|baseType argument_list|) decl_stmt|; name|builder operator|. name|setName argument_list|( literal|"" argument_list|) expr_stmt|; for|for control|( name|PropertyValue name|v range|: name|list control|) block|{ if|if condition|( name|type operator|. name|isArray argument_list|() condition|) block|{ for|for control|( name|Object name|value range|: operator|( name|Iterable argument_list|< name|? argument_list|> operator|) name|v operator|. name|getValue argument_list|( name|type argument_list|) control|) block|{ name|builder operator|. name|addValue argument_list|( name|value argument_list|) expr_stmt|; block|} block|} else|else block|{ name|builder operator|. name|addValue argument_list|( name|v operator|. name|getValue argument_list|( name|type argument_list|) argument_list|) expr_stmt|; block|} block|} name|PropertyState name|s init|= name|builder operator|. name|getPropertyState argument_list|() decl_stmt|; return|return name|PropertyValues operator|. name|create argument_list|( name|s argument_list|) return|; block|} name|boolean name|relative init|= operator|! name|oakPropertyName operator|. name|startsWith argument_list|( name|QueryConstants operator|. name|REP_FACET operator|+ literal|"(" argument_list|) operator|&& operator|! name|oakPropertyName operator|. name|startsWith argument_list|( name|QueryConstants operator|. name|REP_EXCERPT operator|+ literal|"(" argument_list|) operator|&& name|oakPropertyName operator|. name|indexOf argument_list|( literal|'/' argument_list|) operator|>= literal|0 decl_stmt|; name|Tree name|t init|= name|currentTree argument_list|() decl_stmt|; if|if condition|( name|relative condition|) block|{ for|for control|( name|String name|p range|: name|PathUtils operator|. name|elements argument_list|( name|PathUtils operator|. name|getParentPath argument_list|( name|oakPropertyName argument_list|) argument_list|) control|) block|{ if|if condition|( name|t operator|== literal|null condition|) block|{ return|return literal|null return|; block|} if|if condition|( name|p operator|. name|equals argument_list|( literal|".." argument_list|) condition|) block|{ name|t operator|= name|t operator|. name|isRoot argument_list|() condition|? literal|null else|: name|t operator|. name|getParent argument_list|() expr_stmt|; block|} elseif|else if|if condition|( name|p operator|. name|equals argument_list|( literal|"." argument_list|) condition|) block|{ comment|// same node block|} else|else block|{ name|t operator|= name|t operator|. name|getChild argument_list|( name|p argument_list|) expr_stmt|; block|} block|} name|oakPropertyName operator|= name|PathUtils operator|. name|getName argument_list|( name|oakPropertyName argument_list|) expr_stmt|; block|} return|return name|currentOakProperty argument_list|( name|t argument_list|, name|oakPropertyName argument_list|, name|propertyType argument_list|) return|; block|} specifier|private name|PropertyValue name|currentOakProperty parameter_list|( name|Tree name|t parameter_list|, name|String name|oakPropertyName parameter_list|, name|Integer name|propertyType parameter_list|) block|{ name|PropertyValue name|result decl_stmt|; if|if condition|( operator|( name|t operator|== literal|null operator||| operator|! name|t operator|. name|exists argument_list|() operator|) operator|&& operator|( name|currentRow operator|== literal|null operator||| operator|! name|currentRow operator|. name|isVirtualRow argument_list|() operator|) condition|) block|{ return|return literal|null return|; block|} if|if condition|( name|oakPropertyName operator|. name|equals argument_list|( name|QueryConstants operator|. name|JCR_PATH argument_list|) condition|) block|{ name|String name|path init|= name|currentPath argument_list|() decl_stmt|; name|String name|local init|= name|getLocalPath argument_list|( name|path argument_list|) decl_stmt|; if|if condition|( name|local operator|== literal|null condition|) block|{ comment|// not a local path return|return literal|null return|; block|} name|result operator|= name|PropertyValues operator|. name|newString argument_list|( name|local argument_list|) expr_stmt|; block|} elseif|else if|if condition|( name|oakPropertyName operator|. name|equals argument_list|( name|QueryConstants operator|. name|JCR_SCORE argument_list|) condition|) block|{ name|result operator|= name|currentRow operator|. name|getValue argument_list|( name|QueryConstants operator|. name|JCR_SCORE argument_list|) expr_stmt|; block|} elseif|else if|if condition|( name|oakPropertyName operator|. name|equals argument_list|( name|QueryConstants operator|. name|REP_EXCERPT argument_list|) operator||| name|oakPropertyName operator|. name|startsWith argument_list|( name|QueryConstants operator|. name|REP_EXCERPT operator|+ literal|"(" argument_list|) condition|) block|{ name|result operator|= name|currentRow operator|. name|getValue argument_list|( name|oakPropertyName argument_list|) expr_stmt|; block|} elseif|else if|if condition|( name|oakPropertyName operator|. name|equals argument_list|( name|QueryConstants operator|. name|OAK_SCORE_EXPLANATION argument_list|) condition|) block|{ name|result operator|= name|currentRow operator|. name|getValue argument_list|( name|QueryConstants operator|. name|OAK_SCORE_EXPLANATION argument_list|) expr_stmt|; block|} elseif|else if|if condition|( name|oakPropertyName operator|. name|equals argument_list|( name|QueryConstants operator|. name|REP_SPELLCHECK argument_list|) condition|) block|{ name|result operator|= name|currentRow operator|. name|getValue argument_list|( name|QueryConstants operator|. name|REP_SPELLCHECK argument_list|) expr_stmt|; block|} elseif|else if|if condition|( name|oakPropertyName operator|. name|equals argument_list|( name|QueryConstants operator|. name|REP_SUGGEST argument_list|) condition|) block|{ name|result operator|= name|currentRow operator|. name|getValue argument_list|( name|QueryConstants operator|. name|REP_SUGGEST argument_list|) expr_stmt|; block|} elseif|else if|if condition|( name|oakPropertyName operator|. name|startsWith argument_list|( name|QueryConstants operator|. name|REP_FACET operator|+ literal|"(" argument_list|) condition|) block|{ name|result operator|= name|currentRow operator|. name|getValue argument_list|( name|oakPropertyName argument_list|) expr_stmt|; block|} else|else block|{ name|result operator|= name|PropertyValues operator|. name|create argument_list|( name|t operator|. name|getProperty argument_list|( name|oakPropertyName argument_list|) argument_list|) expr_stmt|; block|} if|if condition|( name|result operator|== literal|null condition|) block|{ return|return literal|null return|; block|} if|if condition|( name|propertyType operator|!= literal|null operator|&& name|result operator|. name|getType argument_list|() operator|. name|tag argument_list|() operator|!= name|propertyType condition|) block|{ return|return literal|null return|; block|} return|return name|result return|; block|} specifier|private name|void name|readOakProperties parameter_list|( name|ArrayList argument_list|< name|PropertyValue argument_list|> name|target parameter_list|, name|Tree name|t parameter_list|, name|String name|oakPropertyName parameter_list|, name|Integer name|propertyType parameter_list|) block|{ name|boolean name|skipCurrentNode init|= literal|false decl_stmt|; while|while condition|( operator|! name|skipCurrentNode condition|) block|{ if|if condition|( name|t operator|== literal|null operator||| operator|! name|t operator|. name|exists argument_list|() condition|) block|{ return|return; block|} name|LOG operator|. name|trace argument_list|( literal|"readOakProperties() - reading '{}' for '{}'" argument_list|, name|t operator|. name|getPath argument_list|() argument_list|, name|oakPropertyName argument_list|) expr_stmt|; name|int name|slash init|= name|oakPropertyName operator|. name|indexOf argument_list|( literal|'/' argument_list|) decl_stmt|; if|if condition|( name|slash operator|< literal|0 condition|) block|{ break|break; block|} name|String name|parent init|= name|oakPropertyName operator|. name|substring argument_list|( literal|0 argument_list|, name|slash argument_list|) decl_stmt|; name|oakPropertyName operator|= name|oakPropertyName operator|. name|substring argument_list|( name|slash operator|+ literal|1 argument_list|) expr_stmt|; if|if condition|( name|parent operator|. name|equals argument_list|( literal|".." argument_list|) condition|) block|{ name|t operator|= name|t operator|. name|isRoot argument_list|() condition|? literal|null else|: name|t operator|. name|getParent argument_list|() expr_stmt|; block|} elseif|else if|if condition|( name|parent operator|. name|equals argument_list|( literal|"." argument_list|) condition|) block|{ comment|// same node block|} elseif|else if|if condition|( name|parent operator|. name|equals argument_list|( literal|"*" argument_list|) condition|) block|{ for|for control|( name|Tree name|child range|: name|t operator|. name|getChildren argument_list|() control|) block|{ name|readOakProperties argument_list|( name|target argument_list|, name|child argument_list|, name|oakPropertyName argument_list|, name|propertyType argument_list|) expr_stmt|; block|} name|skipCurrentNode operator|= literal|true expr_stmt|; block|} else|else block|{ name|t operator|= name|t operator|. name|getChild argument_list|( name|parent argument_list|) expr_stmt|; block|} block|} if|if condition|( name|skipCurrentNode condition|) block|{ return|return; block|} if|if condition|( operator|! literal|"*" operator|. name|equals argument_list|( name|oakPropertyName argument_list|) condition|) block|{ name|PropertyValue name|value init|= name|currentOakProperty argument_list|( name|t argument_list|, name|oakPropertyName argument_list|, name|propertyType argument_list|) decl_stmt|; if|if condition|( name|value operator|!= literal|null condition|) block|{ name|LOG operator|. name|trace argument_list|( literal|"readOakProperties() - adding: '{}' from '{}'" argument_list|, name|value argument_list|, name|t operator|. name|getPath argument_list|() argument_list|) expr_stmt|; name|target operator|. name|add argument_list|( name|value argument_list|) expr_stmt|; block|} return|return; block|} for|for control|( name|PropertyState name|p range|: name|t operator|. name|getProperties argument_list|() control|) block|{ if|if condition|( name|propertyType operator|== literal|null operator||| name|p operator|. name|getType argument_list|() operator|. name|tag argument_list|() operator|== name|propertyType condition|) block|{ name|PropertyValue name|v init|= name|PropertyValues operator|. name|create argument_list|( name|p argument_list|) decl_stmt|; name|target operator|. name|add argument_list|( name|v argument_list|) expr_stmt|; block|} block|} block|} specifier|public name|boolean name|isVirtualRow parameter_list|() block|{ return|return name|currentRow operator|!= literal|null operator|&& name|currentRow operator|. name|isVirtualRow argument_list|() return|; block|} annotation|@ name|Override specifier|public name|SelectorImpl name|getSelector parameter_list|( name|String name|selectorName parameter_list|) block|{ if|if condition|( name|selectorName operator|. name|equals argument_list|( name|this operator|. name|selectorName argument_list|) condition|) block|{ return|return name|this return|; block|} return|return literal|null return|; block|} specifier|public name|long name|getScanCount parameter_list|() block|{ return|return name|scanCount return|; block|} specifier|public name|void name|restrictSelector parameter_list|( name|ConstraintImpl name|constraint parameter_list|) block|{ name|selectorConstraints operator|. name|add argument_list|( name|constraint argument_list|) expr_stmt|; block|} specifier|public name|List argument_list|< name|ConstraintImpl argument_list|> name|getSelectorConstraints parameter_list|() block|{ return|return name|selectorConstraints return|; block|} annotation|@ name|Override specifier|public name|boolean name|equals parameter_list|( name|Object name|other parameter_list|) block|{ if|if condition|( name|this operator|== name|other condition|) block|{ return|return literal|true return|; block|} elseif|else if|if condition|( operator|! operator|( name|other operator|instanceof name|SelectorImpl operator|) condition|) block|{ return|return literal|false return|; block|} return|return name|selectorName operator|. name|equals argument_list|( operator|( operator|( name|SelectorImpl operator|) name|other operator|) operator|. name|selectorName argument_list|) return|; block|} annotation|@ name|Override specifier|public name|int name|hashCode parameter_list|() block|{ return|return name|selectorName operator|. name|hashCode argument_list|() return|; block|} name|QueryIndex name|getIndex parameter_list|() block|{ return|return name|plan operator|== literal|null condition|? literal|null else|: name|plan operator|. name|getIndex argument_list|() return|; block|} annotation|@ name|Override specifier|public name|ArrayList argument_list|< name|SourceImpl argument_list|> name|getInnerJoinSelectors parameter_list|() block|{ name|ArrayList argument_list|< name|SourceImpl argument_list|> name|list init|= operator|new name|ArrayList argument_list|< name|SourceImpl argument_list|> argument_list|() decl_stmt|; name|list operator|. name|add argument_list|( name|this argument_list|) expr_stmt|; return|return name|list return|; block|} annotation|@ name|Override specifier|public name|boolean name|isOuterJoinRightHandSide parameter_list|() block|{ return|return name|this operator|. name|outerJoinRightHandSide return|; block|} specifier|public name|QueryImpl name|getQuery parameter_list|() block|{ return|return name|query return|; block|} annotation|@ name|Override specifier|public name|long name|getSize parameter_list|( name|NodeState name|rootState parameter_list|, name|SizePrecision name|precision parameter_list|, name|long name|max parameter_list|) block|{ if|if condition|( name|cursor operator|== literal|null condition|) block|{ name|execute argument_list|( name|rootState argument_list|) expr_stmt|; block|} return|return name|cursor operator|. name|getSize argument_list|( name|precision argument_list|, name|max argument_list|) return|; block|} annotation|@ name|Override specifier|public name|SourceImpl name|copyOf parameter_list|() block|{ return|return operator|new name|SelectorImpl argument_list|( name|nodeTypeInfo argument_list|, name|selectorName argument_list|) return|; block|} specifier|private specifier|static specifier|final class|class name|CachedTree block|{ specifier|private specifier|final name|String name|path decl_stmt|; specifier|private specifier|final name|Tree name|tree decl_stmt|; specifier|private specifier|final name|ExecutionContext name|ctx decl_stmt|; specifier|private specifier|final name|LazyValue argument_list|< name|Tree argument_list|> name|readOnlyTree decl_stmt|; specifier|private name|CachedTree parameter_list|( annotation|@ name|NotNull name|String name|path parameter_list|, annotation|@ name|NotNull name|QueryImpl name|query parameter_list|) block|{ name|this operator|. name|path operator|= name|path expr_stmt|; name|this operator|. name|tree operator|= name|query operator|. name|getTree argument_list|( name|path argument_list|) expr_stmt|; name|this operator|. name|ctx operator|= name|query operator|. name|getExecutionContext argument_list|() expr_stmt|; name|this operator|. name|readOnlyTree operator|= operator|new name|LazyValue argument_list|< name|Tree argument_list|> argument_list|() block|{ annotation|@ name|Override specifier|protected name|Tree name|createValue parameter_list|() block|{ return|return operator|new name|ImmutableRoot argument_list|( name|ctx operator|. name|getBaseState argument_list|() argument_list|) operator|. name|getTree argument_list|( name|path argument_list|) return|; block|} block|} expr_stmt|; block|} specifier|private name|boolean name|denotes parameter_list|( annotation|@ name|NotNull name|String name|path parameter_list|) block|{ return|return name|this operator|. name|path operator|. name|equals argument_list|( name|path argument_list|) return|; block|} specifier|private name|boolean name|exists parameter_list|() block|{ return|return name|tree operator|!= literal|null operator|&& name|tree operator|. name|exists argument_list|() return|; block|} annotation|@ name|Nullable specifier|private name|Tree name|getTree parameter_list|() block|{ return|return name|tree return|; block|} annotation|@ name|NotNull specifier|private name|LazyValue argument_list|< name|Tree argument_list|> name|getReadOnlyTree parameter_list|() block|{ return|return name|readOnlyTree return|; block|} block|} block|} end_class end_unit
14.217217
815
0.789151
3e4390c16f3ac7a4c2fc8a6cb363eb043ca34847
7,953
/* Soot - a J*va Optimization Framework * Copyright (C) 2002 Sable Research Group * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the * Free Software Foundation, Inc., 59 Temple Place - Suite 330, * Boston, MA 02111-1307, USA. */ /* * Modified by the Sable Research Group and others 1997-1999. * See the 'credits' file distributed with Soot for the complete list of * contributors. (Soot is distributed at http://www.sable.mcgill.ca/soot) */ package soot.util; import java.util.*; public class IterableMap implements Map { private HashMap<Object, Object> content_map, back_map; private HashChain key_chain, value_chain; public IterableMap() { this( 7, 0.7f); } public IterableMap( int initialCapacity) { this( initialCapacity, 0.7f); } public IterableMap( int initialCapacity, float loadFactor) { content_map = new HashMap<Object, Object>( initialCapacity, loadFactor); back_map = new HashMap<Object, Object>( initialCapacity, loadFactor); key_chain = new HashChain(); value_chain = new HashChain(); } public void clear() { Iterator kcit = key_chain.iterator(); while (kcit.hasNext()) content_map.remove( kcit.next()); Iterator vcit = value_chain.iterator(); while (vcit.hasNext()) back_map.remove( vcit.next()); key_chain.clear(); value_chain.clear(); } public Iterator iterator() { return key_chain.iterator(); } public boolean containsKey(Object key) { return key_chain.contains( key); } public boolean containsValue(Object value) { return value_chain.contains( value); } public Set entrySet() { return content_map.entrySet(); } public boolean equals( Object o) { if (o == this) return true; if ((o instanceof IterableMap) == false) return false; IterableMap other = (IterableMap) o; if (key_chain.equals( other.key_chain) == false) return false; // check that the other has our mapping Iterator kcit = key_chain.iterator(); while (kcit.hasNext()) { Object ko = kcit.next(); if (other.content_map.get( ko) != content_map.get( ko)) return false; } return true; } public Object get( Object key) { return content_map.get( key); } public int hashCode() { return content_map.hashCode(); } public boolean isEmpty() { return key_chain.isEmpty(); } private transient Set<Object> keySet = null; private transient Set<Object> valueSet = null; private transient Collection<Object> values = null; public Set<Object> keySet() { if (keySet == null) { keySet = new AbstractSet() { public Iterator iterator() { return key_chain.iterator(); } public int size() { return key_chain.size(); } public boolean contains(Object o) { return key_chain.contains(o); } public boolean remove(Object o) { if (key_chain.contains(o) == false) { return false; } if (IterableMap.this.content_map.get( o) == null) { IterableMap.this.remove(o); return true; } return (IterableMap.this.remove(o) != null); } public void clear() { IterableMap.this.clear(); } }; } return keySet; } public Set<Object> valueSet() { if (valueSet == null) { valueSet = new AbstractSet() { public Iterator iterator() { return value_chain.iterator(); } public int size() { return value_chain.size(); } public boolean contains(Object o) { return value_chain.contains(o); } public boolean remove(Object o) { if (value_chain.contains( o) == false) { return false; } HashChain c = (HashChain) IterableMap.this.back_map.get( o); Iterator it = c.snapshotIterator(); while (it.hasNext()) { Object ko = it.next(); if (IterableMap.this.content_map.get( o) == null) { IterableMap.this.remove(ko); } else if (IterableMap.this.remove( ko) == null) { return false; } } return true; } public void clear() { IterableMap.this.clear(); } }; } return valueSet; } public Object put( Object key, Object value) { if (key_chain.contains( key)) { Object old_value = content_map.get( key); if (old_value == value) return value; HashChain kc = (HashChain) back_map.get( old_value); kc.remove( key); if (kc.isEmpty()) { value_chain.remove( old_value); back_map.remove( old_value); } kc = (HashChain) back_map.get( value); if (kc == null) { kc = new HashChain(); back_map.put( value, kc); value_chain.add( value); } kc.add( key); return old_value; } else { key_chain.add(key); content_map.put( key, value); HashChain kc = (HashChain) back_map.get( value); if (kc == null) { kc = new HashChain(); back_map.put( value, kc); value_chain.add( value); } kc.add( key); return null; } } public void putAll( Map t) { Iterator kit = (t instanceof IterableMap) ? ((IterableMap) t).key_chain.iterator() : t.keySet().iterator(); while (kit.hasNext()) { Object key = kit.next(); put( key, t.get( key)); } } public Object remove( Object key) { if (key_chain.contains( key) == false) return null; key_chain.remove( key); Object value = content_map.remove( key); HashChain c = (HashChain) back_map.get( value); c.remove( key); if (c.size() == 0) back_map.remove( value); return value; } public int size() { return key_chain.size(); } public Collection<Object> values() { if (values==null) { values = new AbstractCollection() { public Iterator iterator() { return new Mapping_Iterator( IterableMap.this.key_chain, IterableMap.this.content_map); } public int size() { return key_chain.size(); } public boolean contains(Object o) { return value_chain.contains(o); } public void clear() { IterableMap.this.clear(); } }; } return values; } public class Mapping_Iterator implements Iterator { private final Iterator it; private HashMap<Object, Object> m; public Mapping_Iterator( HashChain c, HashMap<Object, Object> m) { it = c.iterator(); this.m = m; } public boolean hasNext() { return it.hasNext(); } public Object next() throws NoSuchElementException { return m.get( it.next()); } public void remove() throws UnsupportedOperationException { throw new UnsupportedOperationException("You cannot remove from an Iterator on the values() for an IterableMap."); } } }
24.02719
119
0.582422
c0ac7562345de10e77fb2f6c41ff2a4a9aee5791
28,516
package org.apache.xalan.processor; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.util.StringTokenizer; import java.util.Vector; import javax.xml.transform.TransformerException; import org.apache.xalan.res.XSLMessages; import org.apache.xalan.templates.AVT; import org.apache.xalan.templates.ElemTemplateElement; import org.apache.xml.utils.QName; import org.apache.xml.utils.StringToIntTable; import org.apache.xml.utils.StringVector; import org.apache.xml.utils.XMLChar; import org.apache.xpath.XPath; import org.xml.sax.SAXException; public class XSLTAttributeDef { static final int FATAL = 0; static final int ERROR = 1; static final int WARNING = 2; static final int T_CDATA = 1; static final int T_URL = 2; static final int T_AVT = 3; static final int T_PATTERN = 4; static final int T_EXPR = 5; static final int T_CHAR = 6; static final int T_NUMBER = 7; static final int T_YESNO = 8; static final int T_QNAME = 9; static final int T_QNAMES = 10; static final int T_ENUM = 11; static final int T_SIMPLEPATTERNLIST = 12; static final int T_NMTOKEN = 13; static final int T_STRINGLIST = 14; static final int T_PREFIX_URLLIST = 15; static final int T_ENUM_OR_PQNAME = 16; static final int T_NCNAME = 17; static final int T_AVT_QNAME = 18; static final int T_QNAMES_RESOLVE_NULL = 19; static final int T_PREFIXLIST = 20; static XSLTAttributeDef m_foreignAttr = new XSLTAttributeDef("*", "*", 1, false, false, 2); static String S_FOREIGNATTR_SETTER = "setForeignAttr"; private String m_namespace; private String m_name; private int m_type; private StringToIntTable m_enums; private String m_default; private boolean m_required; private boolean m_supportsAVT; int m_errorType = 2; String m_setterString = null; // $FF: synthetic field static Class class$org$apache$xpath$XPath; // $FF: synthetic field static Class class$java$lang$Double; // $FF: synthetic field static Class class$java$lang$Float; // $FF: synthetic field static Class class$java$lang$Boolean; // $FF: synthetic field static Class class$java$lang$Byte; // $FF: synthetic field static Class class$java$lang$Character; // $FF: synthetic field static Class class$java$lang$Short; // $FF: synthetic field static Class class$java$lang$Integer; // $FF: synthetic field static Class class$java$lang$Long; XSLTAttributeDef(String namespace, String name, int type, boolean required, boolean supportsAVT, int errorType) { this.m_namespace = namespace; this.m_name = name; this.m_type = type; this.m_required = required; this.m_supportsAVT = supportsAVT; this.m_errorType = errorType; } XSLTAttributeDef(String namespace, String name, int type, boolean supportsAVT, int errorType, String defaultVal) { this.m_namespace = namespace; this.m_name = name; this.m_type = type; this.m_required = false; this.m_supportsAVT = supportsAVT; this.m_errorType = errorType; this.m_default = defaultVal; } XSLTAttributeDef(String namespace, String name, boolean required, boolean supportsAVT, boolean prefixedQNameValAllowed, int errorType, String k1, int v1, String k2, int v2) { this.m_namespace = namespace; this.m_name = name; this.m_type = prefixedQNameValAllowed ? 16 : 11; this.m_required = required; this.m_supportsAVT = supportsAVT; this.m_errorType = errorType; this.m_enums = new StringToIntTable(2); this.m_enums.put(k1, v1); this.m_enums.put(k2, v2); } XSLTAttributeDef(String namespace, String name, boolean required, boolean supportsAVT, boolean prefixedQNameValAllowed, int errorType, String k1, int v1, String k2, int v2, String k3, int v3) { this.m_namespace = namespace; this.m_name = name; this.m_type = prefixedQNameValAllowed ? 16 : 11; this.m_required = required; this.m_supportsAVT = supportsAVT; this.m_errorType = errorType; this.m_enums = new StringToIntTable(3); this.m_enums.put(k1, v1); this.m_enums.put(k2, v2); this.m_enums.put(k3, v3); } XSLTAttributeDef(String namespace, String name, boolean required, boolean supportsAVT, boolean prefixedQNameValAllowed, int errorType, String k1, int v1, String k2, int v2, String k3, int v3, String k4, int v4) { this.m_namespace = namespace; this.m_name = name; this.m_type = prefixedQNameValAllowed ? 16 : 11; this.m_required = required; this.m_supportsAVT = supportsAVT; this.m_errorType = errorType; this.m_enums = new StringToIntTable(4); this.m_enums.put(k1, v1); this.m_enums.put(k2, v2); this.m_enums.put(k3, v3); this.m_enums.put(k4, v4); } String getNamespace() { return this.m_namespace; } String getName() { return this.m_name; } int getType() { return this.m_type; } private int getEnum(String key) { return this.m_enums.get(key); } private String[] getEnumNames() { return this.m_enums.keys(); } String getDefault() { return this.m_default; } void setDefault(String def) { this.m_default = def; } boolean getRequired() { return this.m_required; } boolean getSupportsAVT() { return this.m_supportsAVT; } int getErrorType() { return this.m_errorType; } public String getSetterMethodName() { if (null == this.m_setterString) { if (m_foreignAttr == this) { return S_FOREIGNATTR_SETTER; } if (this.m_name.equals("*")) { this.m_setterString = "addLiteralResultAttribute"; return this.m_setterString; } StringBuffer outBuf = new StringBuffer(); outBuf.append("set"); if (this.m_namespace != null && this.m_namespace.equals("http://www.w3.org/XML/1998/namespace")) { outBuf.append("Xml"); } int n = this.m_name.length(); for(int i = 0; i < n; ++i) { char c = this.m_name.charAt(i); if ('-' == c) { ++i; c = this.m_name.charAt(i); c = Character.toUpperCase(c); } else if (0 == i) { c = Character.toUpperCase(c); } outBuf.append(c); } this.m_setterString = outBuf.toString(); } return this.m_setterString; } AVT processAVT(StylesheetHandler handler, String uri, String name, String rawName, String value, ElemTemplateElement owner) throws SAXException { try { AVT avt = new AVT(handler, uri, name, rawName, value, owner); return avt; } catch (TransformerException var8) { throw new SAXException(var8); } } Object processCDATA(StylesheetHandler handler, String uri, String name, String rawName, String value, ElemTemplateElement owner) throws SAXException { if (this.getSupportsAVT()) { try { AVT avt = new AVT(handler, uri, name, rawName, value, owner); return avt; } catch (TransformerException var8) { throw new SAXException(var8); } } else { return value; } } Object processCHAR(StylesheetHandler handler, String uri, String name, String rawName, String value, ElemTemplateElement owner) throws SAXException { if (this.getSupportsAVT()) { try { AVT avt = new AVT(handler, uri, name, rawName, value, owner); if (avt.isSimple() && value.length() != 1) { this.handleError(handler, "INVALID_TCHAR", new Object[]{name, value}, (Exception)null); return null; } else { return avt; } } catch (TransformerException var8) { throw new SAXException(var8); } } else if (value.length() != 1) { this.handleError(handler, "INVALID_TCHAR", new Object[]{name, value}, (Exception)null); return null; } else { return new Character(value.charAt(0)); } } Object processENUM(StylesheetHandler handler, String uri, String name, String rawName, String value, ElemTemplateElement owner) throws SAXException { AVT avt = null; if (this.getSupportsAVT()) { try { avt = new AVT(handler, uri, name, rawName, value, owner); if (!avt.isSimple()) { return avt; } } catch (TransformerException var10) { throw new SAXException(var10); } } int retVal = this.getEnum(value); if (retVal == -10000) { StringBuffer enumNamesList = this.getListOfEnums(); this.handleError(handler, "INVALID_ENUM", new Object[]{name, value, enumNamesList.toString()}, (Exception)null); return null; } else { return this.getSupportsAVT() ? avt : new Integer(retVal); } } Object processENUM_OR_PQNAME(StylesheetHandler handler, String uri, String name, String rawName, String value, ElemTemplateElement owner) throws SAXException { Object objToReturn = null; if (this.getSupportsAVT()) { try { AVT avt = new AVT(handler, uri, name, rawName, value, owner); if (!avt.isSimple()) { return avt; } objToReturn = avt; } catch (TransformerException var14) { throw new SAXException(var14); } } int key = this.getEnum(value); if (key != -10000) { if (objToReturn == null) { objToReturn = new Integer(key); } } else { StringBuffer enumNamesList; try { QName qname = new QName(value, handler, true); if (objToReturn == null) { objToReturn = qname; } if (qname.getPrefix() == null) { enumNamesList = this.getListOfEnums(); enumNamesList.append(" <qname-but-not-ncname>"); this.handleError(handler, "INVALID_ENUM", new Object[]{name, value, enumNamesList.toString()}, (Exception)null); return null; } } catch (IllegalArgumentException var12) { enumNamesList = this.getListOfEnums(); enumNamesList.append(" <qname-but-not-ncname>"); this.handleError(handler, "INVALID_ENUM", new Object[]{name, value, enumNamesList.toString()}, var12); return null; } catch (RuntimeException var13) { StringBuffer enumNamesList = this.getListOfEnums(); enumNamesList.append(" <qname-but-not-ncname>"); this.handleError(handler, "INVALID_ENUM", new Object[]{name, value, enumNamesList.toString()}, var13); return null; } } return objToReturn; } Object processEXPR(StylesheetHandler handler, String uri, String name, String rawName, String value, ElemTemplateElement owner) throws SAXException { try { XPath expr = handler.createXPath(value, owner); return expr; } catch (TransformerException var9) { new SAXException(var9); throw new SAXException(var9); } } Object processNMTOKEN(StylesheetHandler handler, String uri, String name, String rawName, String value, ElemTemplateElement owner) throws SAXException { if (this.getSupportsAVT()) { try { AVT avt = new AVT(handler, uri, name, rawName, value, owner); if (avt.isSimple() && !XMLChar.isValidNmtoken(value)) { this.handleError(handler, "INVALID_NMTOKEN", new Object[]{name, value}, (Exception)null); return null; } else { return avt; } } catch (TransformerException var8) { throw new SAXException(var8); } } else if (!XMLChar.isValidNmtoken(value)) { this.handleError(handler, "INVALID_NMTOKEN", new Object[]{name, value}, (Exception)null); return null; } else { return value; } } Object processPATTERN(StylesheetHandler handler, String uri, String name, String rawName, String value, ElemTemplateElement owner) throws SAXException { try { XPath pattern = handler.createMatchPatternXPath(value, owner); return pattern; } catch (TransformerException var8) { throw new SAXException(var8); } } Object processNUMBER(StylesheetHandler handler, String uri, String name, String rawName, String value, ElemTemplateElement owner) throws SAXException { if (this.getSupportsAVT()) { AVT avt = null; try { avt = new AVT(handler, uri, name, rawName, value, owner); if (avt.isSimple()) { Double var7 = Double.valueOf(value); } return avt; } catch (TransformerException var11) { throw new SAXException(var11); } catch (NumberFormatException var12) { this.handleError(handler, "INVALID_NUMBER", new Object[]{name, value}, var12); return null; } } else { try { return Double.valueOf(value); } catch (NumberFormatException var13) { this.handleError(handler, "INVALID_NUMBER", new Object[]{name, value}, var13); return null; } } } Object processQNAME(StylesheetHandler handler, String uri, String name, String rawName, String value, ElemTemplateElement owner) throws SAXException { try { QName qname = new QName(value, handler, true); return qname; } catch (IllegalArgumentException var9) { this.handleError(handler, "INVALID_QNAME", new Object[]{name, value}, var9); return null; } catch (RuntimeException var10) { this.handleError(handler, "INVALID_QNAME", new Object[]{name, value}, var10); return null; } } Object processAVT_QNAME(StylesheetHandler handler, String uri, String name, String rawName, String value, ElemTemplateElement owner) throws SAXException { AVT avt = null; try { avt = new AVT(handler, uri, name, rawName, value, owner); if (avt.isSimple()) { int indexOfNSSep = value.indexOf(58); String localName; if (indexOfNSSep >= 0) { localName = value.substring(0, indexOfNSSep); if (!XMLChar.isValidNCName(localName)) { this.handleError(handler, "INVALID_QNAME", new Object[]{name, value}, (Exception)null); return null; } } localName = indexOfNSSep < 0 ? value : value.substring(indexOfNSSep + 1); if (localName == null || localName.length() == 0 || !XMLChar.isValidNCName(localName)) { this.handleError(handler, "INVALID_QNAME", new Object[]{name, value}, (Exception)null); return null; } } return avt; } catch (TransformerException var10) { throw new SAXException(var10); } } Object processNCNAME(StylesheetHandler handler, String uri, String name, String rawName, String value, ElemTemplateElement owner) throws SAXException { if (this.getSupportsAVT()) { AVT avt = null; try { avt = new AVT(handler, uri, name, rawName, value, owner); if (avt.isSimple() && !XMLChar.isValidNCName(value)) { this.handleError(handler, "INVALID_NCNAME", new Object[]{name, value}, (Exception)null); return null; } else { return avt; } } catch (TransformerException var9) { throw new SAXException(var9); } } else if (!XMLChar.isValidNCName(value)) { this.handleError(handler, "INVALID_NCNAME", new Object[]{name, value}, (Exception)null); return null; } else { return value; } } Vector processQNAMES(StylesheetHandler handler, String uri, String name, String rawName, String value) throws SAXException { StringTokenizer tokenizer = new StringTokenizer(value, " \t\n\r\f"); int nQNames = tokenizer.countTokens(); Vector qnames = new Vector(nQNames); for(int i = 0; i < nQNames; ++i) { qnames.addElement(new QName(tokenizer.nextToken(), handler)); } return qnames; } final Vector processQNAMESRNU(StylesheetHandler handler, String uri, String name, String rawName, String value) throws SAXException { StringTokenizer tokenizer = new StringTokenizer(value, " \t\n\r\f"); int nQNames = tokenizer.countTokens(); Vector qnames = new Vector(nQNames); String defaultURI = handler.getNamespaceForPrefix(""); for(int i = 0; i < nQNames; ++i) { String tok = tokenizer.nextToken(); if (tok.indexOf(58) == -1) { qnames.addElement(new QName(defaultURI, tok)); } else { qnames.addElement(new QName(tok, handler)); } } return qnames; } Vector processSIMPLEPATTERNLIST(StylesheetHandler handler, String uri, String name, String rawName, String value, ElemTemplateElement owner) throws SAXException { try { StringTokenizer tokenizer = new StringTokenizer(value, " \t\n\r\f"); int nPatterns = tokenizer.countTokens(); Vector patterns = new Vector(nPatterns); for(int i = 0; i < nPatterns; ++i) { XPath pattern = handler.createMatchPatternXPath(tokenizer.nextToken(), owner); patterns.addElement(pattern); } return patterns; } catch (TransformerException var12) { throw new SAXException(var12); } } StringVector processSTRINGLIST(StylesheetHandler handler, String uri, String name, String rawName, String value) { StringTokenizer tokenizer = new StringTokenizer(value, " \t\n\r\f"); int nStrings = tokenizer.countTokens(); StringVector strings = new StringVector(nStrings); for(int i = 0; i < nStrings; ++i) { strings.addElement(tokenizer.nextToken()); } return strings; } StringVector processPREFIX_URLLIST(StylesheetHandler handler, String uri, String name, String rawName, String value) throws SAXException { StringTokenizer tokenizer = new StringTokenizer(value, " \t\n\r\f"); int nStrings = tokenizer.countTokens(); StringVector strings = new StringVector(nStrings); for(int i = 0; i < nStrings; ++i) { String prefix = tokenizer.nextToken(); String url = handler.getNamespaceForPrefix(prefix); if (url == null) { throw new SAXException(XSLMessages.createMessage("ER_CANT_RESOLVE_NSPREFIX", new Object[]{prefix})); } strings.addElement(url); } return strings; } StringVector processPREFIX_LIST(StylesheetHandler handler, String uri, String name, String rawName, String value) throws SAXException { StringTokenizer tokenizer = new StringTokenizer(value, " \t\n\r\f"); int nStrings = tokenizer.countTokens(); StringVector strings = new StringVector(nStrings); for(int i = 0; i < nStrings; ++i) { String prefix = tokenizer.nextToken(); String url = handler.getNamespaceForPrefix(prefix); if (!prefix.equals("#default") && url == null) { throw new SAXException(XSLMessages.createMessage("ER_CANT_RESOLVE_NSPREFIX", new Object[]{prefix})); } strings.addElement(prefix); } return strings; } Object processURL(StylesheetHandler handler, String uri, String name, String rawName, String value, ElemTemplateElement owner) throws SAXException { if (this.getSupportsAVT()) { try { AVT avt = new AVT(handler, uri, name, rawName, value, owner); return avt; } catch (TransformerException var8) { throw new SAXException(var8); } } else { return value; } } private Boolean processYESNO(StylesheetHandler handler, String uri, String name, String rawName, String value) throws SAXException { if (!value.equals("yes") && !value.equals("no")) { this.handleError(handler, "INVALID_BOOLEAN", new Object[]{name, value}, (Exception)null); return null; } else { return new Boolean(value.equals("yes")); } } Object processValue(StylesheetHandler handler, String uri, String name, String rawName, String value, ElemTemplateElement owner) throws SAXException { int type = this.getType(); Object processedValue = null; switch(type) { case 1: processedValue = this.processCDATA(handler, uri, name, rawName, value, owner); break; case 2: processedValue = this.processURL(handler, uri, name, rawName, value, owner); break; case 3: processedValue = this.processAVT(handler, uri, name, rawName, value, owner); break; case 4: processedValue = this.processPATTERN(handler, uri, name, rawName, value, owner); break; case 5: processedValue = this.processEXPR(handler, uri, name, rawName, value, owner); break; case 6: processedValue = this.processCHAR(handler, uri, name, rawName, value, owner); break; case 7: processedValue = this.processNUMBER(handler, uri, name, rawName, value, owner); break; case 8: processedValue = this.processYESNO(handler, uri, name, rawName, value); break; case 9: processedValue = this.processQNAME(handler, uri, name, rawName, value, owner); break; case 10: processedValue = this.processQNAMES(handler, uri, name, rawName, value); break; case 11: processedValue = this.processENUM(handler, uri, name, rawName, value, owner); break; case 12: processedValue = this.processSIMPLEPATTERNLIST(handler, uri, name, rawName, value, owner); break; case 13: processedValue = this.processNMTOKEN(handler, uri, name, rawName, value, owner); break; case 14: processedValue = this.processSTRINGLIST(handler, uri, name, rawName, value); break; case 15: processedValue = this.processPREFIX_URLLIST(handler, uri, name, rawName, value); break; case 16: processedValue = this.processENUM_OR_PQNAME(handler, uri, name, rawName, value, owner); break; case 17: processedValue = this.processNCNAME(handler, uri, name, rawName, value, owner); break; case 18: processedValue = this.processAVT_QNAME(handler, uri, name, rawName, value, owner); break; case 19: processedValue = this.processQNAMESRNU(handler, uri, name, rawName, value); break; case 20: processedValue = this.processPREFIX_LIST(handler, uri, name, rawName, value); } return processedValue; } void setDefAttrValue(StylesheetHandler handler, ElemTemplateElement elem) throws SAXException { this.setAttrValue(handler, this.getNamespace(), this.getName(), this.getName(), this.getDefault(), elem); } private Class getPrimativeClass(Object obj) { if (obj instanceof XPath) { return class$org$apache$xpath$XPath == null ? (class$org$apache$xpath$XPath = class$("org.apache.xpath.XPath")) : class$org$apache$xpath$XPath; } else { Class cl = obj.getClass(); if (cl == (class$java$lang$Double == null ? (class$java$lang$Double = class$("java.lang.Double")) : class$java$lang$Double)) { cl = Double.TYPE; } if (cl == (class$java$lang$Float == null ? (class$java$lang$Float = class$("java.lang.Float")) : class$java$lang$Float)) { cl = Float.TYPE; } else if (cl == (class$java$lang$Boolean == null ? (class$java$lang$Boolean = class$("java.lang.Boolean")) : class$java$lang$Boolean)) { cl = Boolean.TYPE; } else if (cl == (class$java$lang$Byte == null ? (class$java$lang$Byte = class$("java.lang.Byte")) : class$java$lang$Byte)) { cl = Byte.TYPE; } else if (cl == (class$java$lang$Character == null ? (class$java$lang$Character = class$("java.lang.Character")) : class$java$lang$Character)) { cl = Character.TYPE; } else if (cl == (class$java$lang$Short == null ? (class$java$lang$Short = class$("java.lang.Short")) : class$java$lang$Short)) { cl = Short.TYPE; } else if (cl == (class$java$lang$Integer == null ? (class$java$lang$Integer = class$("java.lang.Integer")) : class$java$lang$Integer)) { cl = Integer.TYPE; } else if (cl == (class$java$lang$Long == null ? (class$java$lang$Long = class$("java.lang.Long")) : class$java$lang$Long)) { cl = Long.TYPE; } return cl; } } private StringBuffer getListOfEnums() { StringBuffer enumNamesList = new StringBuffer(); String[] enumValues = this.getEnumNames(); for(int i = 0; i < enumValues.length; ++i) { if (i > 0) { enumNamesList.append(' '); } enumNamesList.append(enumValues[i]); } return enumNamesList; } boolean setAttrValue(StylesheetHandler handler, String attrUri, String attrLocalName, String attrRawName, String attrValue, ElemTemplateElement elem) throws SAXException { if (!attrRawName.equals("xmlns") && !attrRawName.startsWith("xmlns:")) { String setterString = this.getSetterMethodName(); if (null != setterString) { try { Method meth; Object[] args; Class[] argTypes; if (setterString.equals(S_FOREIGNATTR_SETTER)) { if (attrUri == null) { attrUri = ""; } Class sclass = attrUri.getClass(); argTypes = new Class[]{sclass, sclass, sclass, sclass}; meth = elem.getClass().getMethod(setterString, argTypes); args = new Object[]{attrUri, attrLocalName, attrRawName, attrValue}; } else { Object value = this.processValue(handler, attrUri, attrLocalName, attrRawName, attrValue, elem); if (null == value) { return false; } argTypes = new Class[]{this.getPrimativeClass(value)}; try { meth = elem.getClass().getMethod(setterString, argTypes); } catch (NoSuchMethodException var14) { Class cl = value.getClass(); argTypes[0] = cl; meth = elem.getClass().getMethod(setterString, argTypes); } args = new Object[]{value}; } meth.invoke(elem, args); } catch (NoSuchMethodException var15) { if (!setterString.equals(S_FOREIGNATTR_SETTER)) { handler.error("ER_FAILED_CALLING_METHOD", new Object[]{setterString}, var15); return false; } } catch (IllegalAccessException var16) { handler.error("ER_FAILED_CALLING_METHOD", new Object[]{setterString}, var16); return false; } catch (InvocationTargetException var17) { this.handleError(handler, "WG_ILLEGAL_ATTRIBUTE_VALUE", new Object[]{"name", this.getName()}, var17); return false; } } return true; } else { return true; } } private void handleError(StylesheetHandler handler, String msg, Object[] args, Exception exc) throws SAXException { switch(this.getErrorType()) { case 0: case 1: handler.error(msg, args, exc); break; case 2: handler.warn(msg, args); } } // $FF: synthetic method static Class class$(String x0) { try { return Class.forName(x0); } catch (ClassNotFoundException var2) { throw new NoClassDefFoundError(var2.getMessage()); } } }
37.178618
215
0.610043
714d378cac7a92be85bba2b5053dade17f3061b0
593
package com.laioffer.twitch.service; import com.laioffer.twitch.dao.RegisterDao; import com.laioffer.twitch.entity.db.User; import com.laioffer.twitch.util.Util; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import java.io.IOException; @Service public class RegisterService { @Autowired private RegisterDao registerDao; public boolean register(User user) throws IOException { user.setPassword(Util.encryptPassword(user.getUserId(), user.getPassword())); return registerDao.register(user); } }
28.238095
85
0.777403
29f9a10cd594ec6b77e90efc082e23d7422f13ee
3,153
package org.dump2csv; import org.apache.commons.csv.CSVFormat; import org.apache.commons.csv.CSVPrinter; import org.h2.jdbcx.JdbcDataSource; import org.junit.After; import org.junit.Before; import org.junit.Test; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.PrintStream; import java.sql.Connection; import java.sql.ResultSet; import java.sql.ResultSetMetaData; import java.sql.SQLException; import java.util.ArrayList; import static org.dump2csv.ResourceHelpers.getURL; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertThat; /*** * Module for exploring H2 DB database (mostly in-memory related features) */ public class H2FakeDSTest { private Connection conn = null; private final ByteArrayOutputStream outContent = new ByteArrayOutputStream(); private final ByteArrayOutputStream errContent = new ByteArrayOutputStream(); @Before public void before() throws SQLException { JdbcDataSource ds = new JdbcDataSource(); ds.setURL("jdbc:h2:mem:db1"); ds.setUser("sa"); ds.setPassword("sa"); conn = ds.getConnection(); conn.createStatement().execute("CREATE TABLE TESTCSV AS SELECT * FROM CSVREAD('"+ getURL("test01.csv") +"');"); System.setOut(new PrintStream(outContent)); System.setErr(new PrintStream(errContent)); } @After public void after() throws SQLException { System.setOut(null); System.setErr(null); conn.close(); } @Test public void createAndLoadATableFromCSV() throws SQLException { JdbcDataSource ds = new JdbcDataSource(); ds.setURL("jdbc:h2:mem:db1"); ds.setUser("sa"); ds.setPassword("sa"); Connection conn = ds.getConnection(); ResultSet rs = conn.createStatement().executeQuery("SELECT * FROM TESTCSV;"); while (rs.next()) { System.out.println(rs.getString(1)); System.out.println(rs.getString(2)); } rs.close(); conn.close(); assertEquals("1\nHello\n2\nWorld!\n3\nAgain!\n", outContent.toString()); } @Test public void printCSV() throws SQLException, IOException { JdbcDataSource ds = new JdbcDataSource(); ds.setURL("jdbc:h2:mem:db1"); ds.setUser("sa"); ds.setPassword("sa"); Connection conn = ds.getConnection(); ResultSet rs = conn.createStatement().executeQuery("SELECT * FROM TESTCSV;"); final CSVPrinter printer = CSVFormat.DEFAULT.withHeader(rs).print(new PrintStream(outContent)); ResultSetMetaData md = rs.getMetaData(); int columnCount = md.getColumnCount(); while (rs.next()) { ArrayList<Object> l = new ArrayList<>(columnCount); for(int i = 1; i <= columnCount; i++){ l.add(rs.getObject(i)); } printer.printRecord(l); } rs.close(); conn.close(); assertThat( outContent.toString(), RegexMatcher.matches("NUM,TEXT\\s+1,Hello\\s+2,World!\\s+3,Again!\\s+")); } }
32.173469
116
0.640977
74c08111f8c75941bcc459ffda1ee01034662763
2,060
package seedu.address.logic.parser; import static java.util.Objects.requireNonNull; import static seedu.address.logic.parser.CliSyntax.PREFIX_EMAIL; import static seedu.address.logic.parser.CliSyntax.PREFIX_NAME; import static seedu.address.logic.parser.CliSyntax.PREFIX_PHONE; import seedu.address.logic.commands.EditBorrowerCommand; import seedu.address.logic.commands.exceptions.CommandException; import seedu.address.logic.parser.exceptions.ParseException; /** * Parses input arguments and creates a new EditBorrowerCommand object */ public class EditCommandParser implements Parser<EditBorrowerCommand> { /** * Parses the given {@code String} of arguments in the context of the EditBorrowerCommand * and returns an EditBorrowerCommand object for execution. * * @throws ParseException if the user input does not conform the expected format */ public EditBorrowerCommand parse(String args) throws ParseException, CommandException { requireNonNull(args); ArgumentMultimap argMultimap = ArgumentTokenizer.tokenize(args, PREFIX_NAME, PREFIX_PHONE, PREFIX_EMAIL); EditBorrowerCommand.EditBorrowerDescriptor editBorrowerDescriptor = new EditBorrowerCommand.EditBorrowerDescriptor(); if (argMultimap.getValue(PREFIX_NAME).isPresent()) { editBorrowerDescriptor.setName(ParserUtil.parseName(argMultimap.getValue(PREFIX_NAME).get())); } if (argMultimap.getValue(PREFIX_PHONE).isPresent()) { editBorrowerDescriptor.setPhone(ParserUtil.parsePhone(argMultimap.getValue(PREFIX_PHONE) .get())); } if (argMultimap.getValue(PREFIX_EMAIL).isPresent()) { editBorrowerDescriptor.setEmail(ParserUtil.parseEmail(argMultimap.getValue(PREFIX_EMAIL).get())); } if (!editBorrowerDescriptor.isAnyFieldEdited()) { throw new ParseException(EditBorrowerCommand.MESSAGE_NOT_EDITED); } return new EditBorrowerCommand(editBorrowerDescriptor); } }
42.916667
109
0.737864
05ee8072868819971ef445b56e64dcb57087740d
392
package jp.co.canon.rss.logmanager.scheduler; import jp.co.canon.rss.logmanager.exception.ConvertException; import jp.co.canon.rss.logmanager.vo.job.StepEntity; import java.io.IOException; public interface SchedulerStrategy { void runStep(StepEntity stepEntity, boolean manual) throws ConvertException, IOException; void stopStep(int jobId) throws ConvertException, IOException; }
32.666667
93
0.813776
7029390ddd0e3f8b89b8c7a78c6844cda97df05e
134
package cn.printf.springbootboilerplate.usercontext.domain; public interface PasswordEncoder { String encode(String password); }
22.333333
59
0.813433
ca07ee6bea992c900fb8f11df2c6cf61086c05a3
1,465
package cryodex.modules.mus; import cryodex.CryodexController; import cryodex.modules.Tournament; import cryodex.xml.XMLObject; import cryodex.xml.XMLUtils; import cryodex.xml.XMLUtils.Element; public class MusOptions implements XMLObject { boolean showKillPoints = true; boolean enterOnlyPoints = true; public MusOptions() { } public MusOptions(Element e) { if (e != null) { showKillPoints = e.getBooleanFromChild("SHOWKILLPOINTS", true); enterOnlyPoints = e.getBooleanFromChild("ENTERONLYPOINTS", true); } } public boolean isShowKillPoints() { return showKillPoints; } public void setShowKillPoints(boolean showKillPoints) { this.showKillPoints = showKillPoints; updateTournamentVisuals(); } public boolean isEnterOnlyPoints() { return enterOnlyPoints; } public void setEnterOnlyPoints(boolean enterOnlyPoints) { this.enterOnlyPoints = enterOnlyPoints; updateTournamentVisuals(); } private void updateTournamentVisuals() { if (CryodexController.isLoading == false && CryodexController.getAllTournaments() != null) { for (Tournament t : CryodexController.getAllTournaments()) { if (t instanceof MusTournament) { t.updateVisualOptions(); } } } CryodexController.saveData(); } @Override public StringBuilder appendXML(StringBuilder sb) { XMLUtils.appendObject(sb, "SHOWKILLPOINTS", showKillPoints); XMLUtils.appendObject(sb, "ENTERONLYPOINTS", enterOnlyPoints); return sb; } }
23.253968
68
0.752901
6e455dd39636e850c8f0e4709869f613f0738f99
1,497
package com.sappsoftwaresolutions.OOMenu; public class Main { public static void main(String[] args){ //create main menu leaves MenuItemComponent leaf1 = new MenuItemLeaf("Leaf1"); MenuItemComponent leaf2 = new MenuItemLeaf("Leaf2"); MenuItemComponent leaf3 = new MenuItemLeaf("Leaf3"); MenuItemComponent leaf4 = new MenuItemLeaf("Leaf4"); //create submenu1 and 4 leaves MenuItemComponent sub1leaf1 = new MenuItemLeaf("Sub1Leaf1"); MenuItemComponent sub1leaf2 = new MenuItemLeaf("Sub1Leaf2"); MenuItemComponent sub1leaf3 = new MenuItemLeaf("Sub1Leaf3"); MenuItemComponent sub1leaf4 = new MenuItemLeaf("Sub1Leaf4"); MenuItemComponent submenu1 = new MenuItemComposite("SubMenu1",sub1leaf1,sub1leaf2,sub1leaf3,sub1leaf4); //create submenu2 and 4 leaves MenuItemComponent sub2leaf1 = new MenuItemLeaf("Sub2Leaf1"); MenuItemComponent sub2leaf2 = new MenuItemLeaf("Sub2Leaf2"); MenuItemComponent sub2leaf3 = new MenuItemLeaf("Sub2Leaf3"); MenuItemComponent sub2leaf4 = new MenuItemLeaf("Sub2Leaf4"); MenuItemComponent submenu2 = new MenuItemComposite("SubMenu1",sub2leaf1,sub2leaf2,sub2leaf3,sub2leaf4); //create MainMenu with all leaves and submenus MenuItemComponent MainMenu = new MenuItemComposite("MainMenu", leaf1, leaf2, leaf3, leaf4,submenu1,submenu2); //create Visitor VisitorDisplayInterface display = new VisitorDisplayPrint(); VisitorInputInterface input = new VisitorInputKeyboard(); MainMenu.runMenuOption(display,input); } }
41.583333
111
0.781563
2fa0854c9324e37883cddb4ae9b7bf3c52cc5c14
8,663
package rhomobile.bluetooth; import java.io.IOException; import net.rim.device.api.bluetooth.BluetoothSerialPort; import net.rim.device.api.bluetooth.BluetoothSerialPortInfo; import net.rim.device.api.bluetooth.BluetoothSerialPortListener; import net.rim.device.api.ui.component.Status; import net.rim.device.api.util.DataBuffer; public class BluetoothPort implements BluetoothSerialPortListener { public interface BluetoothPortListener { public void onBluetoothPortDisconnect(); public void onBluetoothPortError(); public void onBluetoothPortDataReceived(); public void onBluetoothPortConnected(boolean success); } private BluetoothSerialPort mPort; private static boolean mIsDataSent = true; private DataBuffer mWritedData; private DataBuffer mReadedData; private BluetoothPortListener mListener = null; private byte[] _receiveBuffer = new byte[1024]; private String mConnectedDeviceName = ""; private ConnectionListenThread mListenThread = null; private class ConnectionListenThread extends Thread { private BluetoothPort Port; private byte[] data; public ConnectionListenThread(BluetoothPort port) { Port = port; data = new byte[1]; } public void run() { while (true) { try { sleep(50); } catch (Exception e) { } try { if (Port.mPort != null) { int readed = Port.mPort.read(data, 0, 1); if (readed > 0) { mReadedData.writeByteArray(data, 0, 1); } // ok Port.deviceConnected(true); Port.mListenThread = null; BluetoothManager.getInstance().closeBluetoothScreenSilent(); interrupt(); } } catch (Exception e) { // port not ready } } } } public void disconnect() { BluetoothManager.rhoLogInfo("BluetoothPort.disconnect()"); if (mPort != null) { mPort.disconnect(); mPort.close(); //mListener.onBluetoothPortDisconnect(); } else { mListener.onBluetoothPortError(); } if (mListenThread != null) { mListenThread.interrupt(); mListenThread = null; } } public int getStatus() { return mReadedData.getArrayLength(); } public byte[] readData() { byte[] data = null; synchronized(mReadedData) { data = mReadedData.toArray(); mReadedData.reset(); } return data; } public void writeData(byte[] data) { synchronized(mWritedData) { mWritedData.write(data, 0, data.length); } // Call sendData to send the data. sendData(); } public String getConnectedDeviceName() { return mConnectedDeviceName; } public void startListenThread() { //mListenThread = new ConnectionListenThread(this); //mListenThread.start(); //deviceConnected(true); } public BluetoothPort(BluetoothSerialPortInfo info, BluetoothPortListener listener) { // Fill a 1k array with the a character. //Arrays.fill(_receiveBuffer, (byte)'a'); // Initialize the buffers. //_data = new StringBuffer(); mReadedData = new DataBuffer(); mWritedData = new DataBuffer(); mListener = listener; try { if(info == null) { BluetoothManager.rhoLogInfo("BluetoothPort.BluetoothPort() server init"); // Open a port to listen for incoming connections. mPort = new BluetoothSerialPort(BluetoothSerialPort.DEFAULT_UUID, "btspp", BluetoothSerialPort.BAUD_9600, BluetoothSerialPort.DATA_FORMAT_PARITY_NONE | BluetoothSerialPort.DATA_FORMAT_STOP_BITS_1 | BluetoothSerialPort.DATA_FORMAT_DATA_BITS_8, BluetoothSerialPort.FLOW_CONTROL_NONE, 1024, 1024, this); mConnectedDeviceName = "unknown";//mPort.toString(); } else { // Connect to the selected device. BluetoothManager.rhoLogInfo("BluetoothPort.BluetoothPort() client init"); mPort = new BluetoothSerialPort(info, BluetoothSerialPort.BAUD_9600, BluetoothSerialPort.DATA_FORMAT_PARITY_NONE | BluetoothSerialPort.DATA_FORMAT_STOP_BITS_1 | BluetoothSerialPort.DATA_FORMAT_DATA_BITS_8, BluetoothSerialPort.FLOW_CONTROL_NONE, 1024, 1024, this); mConnectedDeviceName = info.getDeviceName(); } } catch(IOException ex) { BluetoothManager.rhoLogInfo("BluetoothPort.BluetoothPort() ERROR!"); mListener.onBluetoothPortError(); //Status.show("Error: " + ex.getMessage()); } } // Invoked when a connection is established. public void deviceConnected(boolean success) { BluetoothManager.rhoLogInfo("BluetoothPort.deviceConnected("+String.valueOf(success)+")"); if (success) { } mListener.onBluetoothPortConnected(success); } // Invoked when a connection is closed. public void deviceDisconnected() { BluetoothManager.rhoLogInfo("BluetoothPort.deviceDisconnected()"); mListener.onBluetoothPortDisconnect(); } // Invoked when the drt state changes. public void dtrStateChange(boolean high) { BluetoothManager.rhoLogInfo("BluetoothPort.dtrStateChange("+String.valueOf(high)+")"); //Status.show("DTR: " + high); } // Invoked when data has been received. public void dataReceived(int length) { BluetoothManager.rhoLogInfo("BluetoothPort.dataReceived("+String.valueOf(length)+")"); int len; try { // Read the data that arrived. if((len = mPort.read(_receiveBuffer, 0, length == -1 ? _receiveBuffer.length : length)) != 0) { // If loopback is enabled write the data back. if(len == 1 && _receiveBuffer[0] == '\r') { _receiveBuffer[1] = '\n'; ++len; } // Update the screen with the new data that arrived. synchronized (mReadedData) { mReadedData.writeByteArray(_receiveBuffer, 0, len); } mListener.onBluetoothPortDataReceived(); } } catch(IOException ioex) { // Catch and re-throw the exception. // throw new RuntimeException(ioex.toString()); mListener.onBluetoothPortError(); } } // Invoked after all data in the buffer has been sent. public void dataSent() { BluetoothManager.rhoLogInfo("BluetoothPort.dataSent()"); // Set the _dataSent flag to true to allow more data to be written. mIsDataSent = true; // Call sendData in case there is data waiting to be sent. sendData(); } // Sends the data currently in the DataBuffer. private void sendData() { BluetoothManager.rhoLogInfo("BluetoothPort.sendData()"); // Ensure we have data to send. synchronized (mWritedData) { if (mWritedData.getArrayLength() > 0) { // Ensure the last write call has resulted in the sending of the data // prior to calling write again. Calling write in sequence without waiting // for the data to be sent can overwrite existing requests and result in // data loss. if (mIsDataSent) { try { // Set the _dataSent flag to false so we don't send any more // data until it has been verified that this data was sent. mIsDataSent = false; // Write out the data in the DataBuffer and reset the DataBuffer. mPort.write(mWritedData.getArray(), 0, mWritedData.getArrayLength()); mWritedData.reset(); BluetoothManager.rhoLogInfo("BluetoothPort.sendData() data was sended"); } catch (IOException ioex) { // Reset _dataSent to true so we can attempt another data write. mIsDataSent = true; //System.out.println("Failed to write data. Exception: " + ioex.toString()); BluetoothManager.rhoLogError("BluetoothPort.sendData() ERROR during send data"); mListener.onBluetoothPortError(); } } else { BluetoothManager.rhoLogInfo("BluetoothPort.sendData() data can not send now - wait"); //System.out.println("Can't send data right now, data will be sent after dataSent notify call."); } } } } }
30.719858
316
0.617338
e42369b8da41e71389021f84e7f856d27776535b
375
package com.atguigu.gmall.sms.mapper; import com.atguigu.gmall.sms.entity.SkuLadderEntity; import com.baomidou.mybatisplus.core.mapper.BaseMapper; import org.apache.ibatis.annotations.Mapper; /** * 商品阶梯价格 * * @author guiban * @email guiban@atguigu.com * @date 2020-10-28 17:11:25 */ @Mapper public interface SkuLadderMapper extends BaseMapper<SkuLadderEntity> { }
20.833333
70
0.765333
a3d54c36b3d07b8cafd40af214f03af067b4a9b7
166
package com.atguigu.ioc.component.base; public class BaseRepository<T> { public void save() { System.out.println("saved by base repository..."); } }
16.6
53
0.662651
70fbba005a8abba4e25bf9fe824040d6591447be
994
/* * Copyright 2019 Immutables Authors and Contributors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.immutables.criteria.backend; /** * Allows to name things like {@code Path}, {@code Container} etc. * @param <T> type of the instance to name */ public interface NamingStrategy<T> { /** * Give a generic or specific name to an entity * @param toName instance to name * @return string representation of {@code toName} */ String name(T toName); }
30.121212
75
0.721328
c2479df6490b65d6ebcbafc5b7d64de6f44567b4
5,339
package com.skytala.eCommerce.domain.shipment.relations.picklist.control.item; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Set; import javax.servlet.http.HttpServletRequest; import org.springframework.http.HttpStatus; import org.springframework.http.MediaType; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.*; import com.google.common.base.Splitter; import com.skytala.eCommerce.domain.shipment.relations.picklist.command.item.AddPicklistItem; import com.skytala.eCommerce.domain.shipment.relations.picklist.command.item.DeletePicklistItem; import com.skytala.eCommerce.domain.shipment.relations.picklist.command.item.UpdatePicklistItem; import com.skytala.eCommerce.domain.shipment.relations.picklist.event.item.PicklistItemAdded; import com.skytala.eCommerce.domain.shipment.relations.picklist.event.item.PicklistItemDeleted; import com.skytala.eCommerce.domain.shipment.relations.picklist.event.item.PicklistItemFound; import com.skytala.eCommerce.domain.shipment.relations.picklist.event.item.PicklistItemUpdated; import com.skytala.eCommerce.domain.shipment.relations.picklist.mapper.item.PicklistItemMapper; import com.skytala.eCommerce.domain.shipment.relations.picklist.model.item.PicklistItem; import com.skytala.eCommerce.domain.shipment.relations.picklist.query.item.FindPicklistItemsBy; import com.skytala.eCommerce.framework.exceptions.RecordNotFoundException; import com.skytala.eCommerce.framework.pubsub.Scheduler; import static com.skytala.eCommerce.framework.pubsub.ResponseUtil.*; @RestController @RequestMapping("/shipment/picklist/picklistItems") public class PicklistItemController { private static Map<String, RequestMethod> validRequests = new HashMap<>(); public PicklistItemController() { validRequests.put("find", RequestMethod.GET); validRequests.put("add", RequestMethod.POST); validRequests.put("update", RequestMethod.PUT); validRequests.put("removeById", RequestMethod.DELETE); } /** * * @param allRequestParams * all params by which you want to find a PicklistItem * @return a List with the PicklistItems * @throws Exception */ @GetMapping("/find") public ResponseEntity<List<PicklistItem>> findPicklistItemsBy(@RequestParam(required = false) Map<String, String> allRequestParams) throws Exception { FindPicklistItemsBy query = new FindPicklistItemsBy(allRequestParams); if (allRequestParams == null) { query.setFilter(new HashMap<>()); } List<PicklistItem> picklistItems =((PicklistItemFound) Scheduler.execute(query).data()).getPicklistItems(); return ResponseEntity.ok().body(picklistItems); } /** * creates a new PicklistItem entry in the ofbiz database * * @param picklistItemToBeAdded * the PicklistItem thats to be added * @return true on success; false on fail */ @RequestMapping(method = RequestMethod.POST, value = "/add", consumes = MediaType.APPLICATION_JSON_UTF8_VALUE) public ResponseEntity<PicklistItem> createPicklistItem(@RequestBody PicklistItem picklistItemToBeAdded) throws Exception { AddPicklistItem command = new AddPicklistItem(picklistItemToBeAdded); PicklistItem picklistItem = ((PicklistItemAdded) Scheduler.execute(command).data()).getAddedPicklistItem(); if (picklistItem != null) return successful(picklistItem); else return conflict(null); } /** * Updates the PicklistItem with the specific Id * * @param picklistItemToBeUpdated * the PicklistItem thats to be updated * @return true on success, false on fail * @throws Exception */ @RequestMapping(method = RequestMethod.PUT, value = "/{nullVal}", consumes = MediaType.APPLICATION_JSON_UTF8_VALUE) public ResponseEntity<String> updatePicklistItem(@RequestBody PicklistItem picklistItemToBeUpdated, @PathVariable String nullVal) throws Exception { // picklistItemToBeUpdated.setnull(null); UpdatePicklistItem command = new UpdatePicklistItem(picklistItemToBeUpdated); try { if(((PicklistItemUpdated) Scheduler.execute(command).data()).isSuccess()) return noContent(); } catch (RecordNotFoundException e) { return notFound(); } return conflict(); } @GetMapping("/{picklistItemId}") public ResponseEntity<PicklistItem> findById(@PathVariable String picklistItemId) throws Exception { HashMap<String, String> requestParams = new HashMap<String, String>(); requestParams.put("picklistItemId", picklistItemId); try { List<PicklistItem> foundPicklistItem = findPicklistItemsBy(requestParams).getBody(); if(foundPicklistItem.size()==1){ return successful(foundPicklistItem.get(0)); }else{ return notFound(); } } catch (RecordNotFoundException e) { return notFound(); } } @DeleteMapping("/{picklistItemId}") public ResponseEntity<String> deletePicklistItemByIdUpdated(@PathVariable String picklistItemId) throws Exception { DeletePicklistItem command = new DeletePicklistItem(picklistItemId); try { if (((PicklistItemDeleted) Scheduler.execute(command).data()).isSuccess()) return noContent(); } catch (RecordNotFoundException e) { return notFound(); } return conflict(); } }
35.832215
151
0.779547
dd68f23839e9c2125d5b20dfa50f5a08246b7883
1,053
package CEform.P; import java.util.ArrayList; import parsing.ParseException; import parsing.Token; import parsing.Tokenizer; import Lustre.Logic; import Lustre.Lustre; import Lustre.Node; import QDDC.QDDC; import QDDC.G.G; public class Rising extends P{ P p; public int parse(ArrayList<Token> tokens, int cnt) throws ParseException { if (tokens.get(cnt).is("rising")) cnt++; else throw new ParseException("rising expected: " + Tokenizer.debugShow(tokens, cnt)); ArrayList<Token> subtokens = Tokenizer.startingEnding(cnt, "(", ")", tokens); cnt += subtokens.size()+2; p = new P(); int cnt2 = p.parse(subtokens, 0); if (cnt2 == subtokens.size()) return cnt; else throw new ParseException("Unreached end of statement: " + Tokenizer.debugShow(subtokens, cnt2)); } public String toString() { return "rising (" + p + ")"; } public PEA.Bool toPEABool() { try{ throw new Exception("undefined!"); }catch(Exception ex){ex.printStackTrace();} return null; } }
22.891304
100
0.660019
46d45bf70a7fa21747dbe3ec19c7ecb7f4be20f4
310
package cn.javava.live.repository; import cn.javava.live.entity.Stream; import org.springframework.data.jpa.repository.JpaSpecificationExecutor; import org.springframework.data.repository.Repository; public interface StreamRepository extends Repository<Stream, String>, JpaSpecificationExecutor<Stream> { }
31
104
0.845161
b3332916224352743de4447b8878016c3a7c4c9a
874
package scraper.image; import java.awt.Component; import javax.swing.DefaultListCellRenderer; import javax.swing.ImageIcon; import javax.swing.JLabel; import javax.swing.JList; import statics.ImageUtils; /** * @author Daniel J. Rivers * 2014 * * Created: Apr 30, 2014, 11:54:49 PM */ public class URLImageCellRenderer extends DefaultListCellRenderer { private static final long serialVersionUID = 1L; @Override public Component getListCellRendererComponent(JList<?> list, Object value, int index, boolean isSelected, boolean cellHasFocus ) { JLabel c = (JLabel)super.getListCellRendererComponent( list, value, index, isSelected, cellHasFocus ); c.setText( "Image " + ( index + 1 ) ); URLImage i = (URLImage)value; c.setIcon( new ImageIcon( ImageUtils.getScaledImage( i.getImage(), 200, 150 ) ) ); return c; } }
29.133333
132
0.712815
87417b4e550a99934408965fcb8f70811aebb381
2,553
package de.fxdiagram.pde; import com.google.common.collect.Iterators; import de.fxdiagram.eclipse.selection.ISelectionExtractor; import org.eclipse.core.resources.IProject; import org.eclipse.core.runtime.IAdaptable; import org.eclipse.jface.viewers.ISelection; import org.eclipse.jface.viewers.IStructuredSelection; import org.eclipse.osgi.service.resolver.BundleDescription; import org.eclipse.pde.core.plugin.IPluginModelBase; import org.eclipse.pde.core.plugin.PluginRegistry; import org.eclipse.ui.IWorkbenchPart; import org.eclipse.xtext.xbase.lib.Functions.Function1; import org.eclipse.xtext.xbase.lib.Functions.Function2; import org.eclipse.xtext.xbase.lib.IterableExtensions; import org.eclipse.xtext.xbase.lib.IteratorExtensions; @SuppressWarnings("all") public class BundleSelectionExtractor implements ISelectionExtractor { @Override public boolean addSelectedElement(final IWorkbenchPart activePart, final ISelectionExtractor.Acceptor acceptor) { final ISelection selection = activePart.getSite().getSelectionProvider().getSelection(); if ((selection instanceof IStructuredSelection)) { final Function1<IAdaptable, BundleDescription> _function = (IAdaptable it) -> { IProject _adapter = it.<IProject>getAdapter(IProject.class); IPluginModelBase _findModel = null; if (((IProject) _adapter)!=null) { IProject _adapter_1 = it.<IProject>getAdapter(IProject.class); _findModel=PluginRegistry.findModel(((IProject) _adapter_1)); } BundleDescription _bundleDescription = null; if (_findModel!=null) { _bundleDescription=_findModel.getBundleDescription(); } return _bundleDescription; }; final Function1<BundleDescription, Boolean> _function_1 = (BundleDescription it) -> { return Boolean.valueOf(acceptor.accept(it)); }; final Iterable<Boolean> booleans = IterableExtensions.<BundleDescription, Boolean>map(IteratorExtensions.<BundleDescription>toSet(IteratorExtensions.<BundleDescription>filterNull(IteratorExtensions.<IAdaptable, BundleDescription>map(Iterators.<IAdaptable>filter(((IStructuredSelection)selection).iterator(), IAdaptable.class), _function))), _function_1); final Function2<Boolean, Boolean, Boolean> _function_2 = (Boolean $0, Boolean $1) -> { return Boolean.valueOf((($0).booleanValue() || ($1).booleanValue())); }; return (boolean) IterableExtensions.<Boolean, Boolean>fold(booleans, Boolean.valueOf(false), _function_2); } return false; } }
52.102041
360
0.75989
5e3c9cb7f16a364d01340a19d2684f51fd8ba443
1,850
package com.example.demo1.validate; import com.example.demo1.BaseWebTest; import org.junit.jupiter.api.Test; import org.springframework.core.io.DefaultResourceLoader; import org.springframework.core.io.ResourceLoader; import org.springframework.mock.web.MockMultipartFile; import java.io.File; import java.io.FileInputStream; import static org.hamcrest.Matchers.containsString; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; public class ValidateTest extends BaseWebTest { private static final ResourceLoader resourceLoader = new DefaultResourceLoader(); @Test public void fileTest() throws Exception { String fileName = "application.properties"; File file = resourceLoader.getResource(fileName).getFile(); MockMultipartFile mockFile = new MockMultipartFile("uploadFile", fileName, "text/plain", new FileInputStream(file)); uploadFile("/validate/file/2", mockFile) .andExpect(status().isOk()) .andExpect(content().string(containsString("{\"code\":\"0\",\"msg\":\"success\",\"data\":\"application.properties\"}"))); } @Test public void fileTestFail() throws Exception { String fileName = "application.properties"; File file = resourceLoader.getResource(fileName).getFile(); MockMultipartFile mockFile = new MockMultipartFile("uploadFile", fileName, "text/plain", new FileInputStream(file)); uploadFile("/validate/file/1", mockFile) .andExpect(status().isBadRequest()) .andExpect(content().string(containsString("{\"code\":\"0x0000013a\",\"msg\":\"shoulder.validate.input.mimeType.illegal\",\"data\":[\"uploadFile\"]}"))); } }
44.047619
169
0.705946
ece154598e4bc87822b31eb0bbe26200e375a7a7
1,124
/* * Copyright (C) 2017-2019 Dremio Corporation * * 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.dremio.service.coordinator; import com.dremio.exec.proto.CoordinationProtos.NodeEndpoint; /** * Provider to {@code com.dremio.exec.proto.CoordinationProtos.NodeEndpoint} */ public interface ServiceSet extends ListenableSet { /** * Register an endpoint for the given service * * @param endpoint the endpoint to register * @return a handle to the registration * @throws NullPointerException if endpoint is {@code null} */ RegistrationHandle register(NodeEndpoint endpoint); }
33.058824
76
0.745552
1579910e233d14f55cbc1c234886573428349252
3,601
/** * Copyright 2009 - 2011 Sergio Bossa (sergio.bossa@gmail.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 terrastore.client; import terrastore.client.connection.Connection; /** * @author Sven Johansson * @author Sergio Bossa * */ public class BackupOperation extends AbstractOperation { private final String bucket; // private volatile String file; private volatile String secretKey; /** * Sets up a {@link BackupOperation} for a specific bucket and * {@link Connection}. * * @param bucket The parent {@link BucketOperation} * @param connection The Terrastore server {@link Connection} */ BackupOperation(Connection connection, String bucket) { super(connection); this.bucket = bucket; } BackupOperation(BackupOperation other) { super(other.connection); this.bucket = other.bucket; this.file = other.file; this.secretKey = other.secretKey; } /** * Specifies the source or destination file name for the backup operation. * * @param file The name of the server side file to read/write from. */ public BackupOperation file(String file) { BackupOperation newInstance = new BackupOperation(this); newInstance.file = file; return newInstance; } /** * Specifies the "secret key" used to validate/authenticate the backup * operation. * The secret key serves as a safety-mechanism to guard against accidental * execution of backup operations. * * @param secretKey The "secret key" to be used in server communication. */ public BackupOperation secretKey(String secretKey) { BackupOperation newInstance = new BackupOperation(this); newInstance.secretKey = secretKey; return newInstance; } /** * Executes an export of the buckets contents to the specified file. * * @throws TerrastoreClientException If server communication fails, or the * request is not valid - i.e, the secret key is rejected. * * @see #file(String) * @see #secretKey() */ public void executeExport() throws TerrastoreClientException { connection.exportBackup(new Context()); } /** * Executes an import of bucket contents from the specified file on the * Terrastore server. * * @throws TerrastoreClientException If server communication fails, or the * request is not valid - i.e, the secret key is rejected. */ public void executeImport() throws TerrastoreClientException { connection.importBackup(new Context()); } public class Context { public String getBucket() { return bucket; } public String getFile() { return file; } public String getSecretKey() { return secretKey; } } }
31.313043
79
0.628437
c73b1d1d8247c9ba2bb648450537d0cc79ec6aff
1,195
package com.spreadst.devtools.editors.mainentry; import com.intellij.openapi.fileEditor.FileEditor; import com.intellij.openapi.fileEditor.FileEditorPolicy; import com.intellij.openapi.fileEditor.FileEditorProvider; import com.intellij.openapi.project.Project; import com.intellij.openapi.vfs.VirtualFile; import org.jetbrains.annotations.NotNull; public class MainEntryEditorProvider implements FileEditorProvider { private static final String ID = "st-main-entry-editor"; private static final String sSuffix = MainEntryFileType.DOT_EXT_MAIN_ENTRY; @Override public boolean accept(@NotNull Project project, @NotNull VirtualFile file) { String path = file.getPath(); return path.regionMatches(true, path.length() - sSuffix.length(), sSuffix, 0, sSuffix.length()); } @NotNull @Override public FileEditor createEditor(@NotNull Project project, @NotNull VirtualFile file) { return new MainEntryViewEditor(); } @NotNull @Override public String getEditorTypeId() { return ID; } @NotNull @Override public FileEditorPolicy getPolicy() { return FileEditorPolicy.HIDE_DEFAULT_EDITOR; } }
29.875
104
0.739749
5fd2ceb39390f5872afe03ada95d384940f9bdf9
6,189
package seedu.address; import java.io.IOException; import java.nio.file.Path; import java.util.function.Supplier; import javafx.stage.Screen; import javafx.stage.Stage; import seedu.address.commons.core.Config; import seedu.address.commons.core.GuiSettings; import seedu.address.commons.exceptions.DataConversionException; import seedu.address.model.Model; import seedu.address.model.ModelManager; import seedu.address.model.ReadOnlyRestOrRant; import seedu.address.model.RestOrRant; import seedu.address.model.UserPrefs; import seedu.address.storage.JsonMenuStorage; import seedu.address.storage.JsonOrdersStorage; import seedu.address.storage.JsonStatisticsStorage; import seedu.address.storage.JsonTablesStorage; import seedu.address.storage.UserPrefsStorage; import seedu.address.testutil.TestUtil; import systemtests.ModelHelper; /** * This class is meant to override some properties of MainApp so that it will be suited for * testing */ public class TestApp extends MainApp { public static final Path TABLES_FOR_TESTING = TestUtil.getFilePathInSandboxFolder("sampleTables.json"); public static final Path ORDERS_FOR_TESTING = TestUtil.getFilePathInSandboxFolder("sampleOrders.json"); public static final Path MENU_FOR_TESTING = TestUtil.getFilePathInSandboxFolder("sampleMenu.json"); public static final Path STATS_FOR_TESTING = TestUtil.getFilePathInSandboxFolder("sampleStats.json"); protected static final Path DEFAULT_PREF_FILE_LOCATION_FOR_TESTING = TestUtil.getFilePathInSandboxFolder("pref_testing.json"); protected Supplier<ReadOnlyRestOrRant> initialDataSupplier = () -> null; protected Path tablesFileLocation = TABLES_FOR_TESTING; protected Path ordersFileLocation = ORDERS_FOR_TESTING; protected Path menuFileLocation = MENU_FOR_TESTING; protected Path statsFileLocation = STATS_FOR_TESTING; public TestApp() { } public TestApp(Supplier<ReadOnlyRestOrRant> initialDataSupplier, Path tablesFileLocation, Path ordersFileLocation, Path menuFileLocation, Path statsFileLocation) { super(); this.initialDataSupplier = initialDataSupplier; this.tablesFileLocation = tablesFileLocation; this.ordersFileLocation = ordersFileLocation; this.menuFileLocation = menuFileLocation; this.statsFileLocation = statsFileLocation; // If some initial local data has been provided, write those to the file if (initialDataSupplier.get() != null) { JsonTablesStorage jsonTablesStorage = new JsonTablesStorage(tablesFileLocation); JsonOrdersStorage jsonOrdersStorage = new JsonOrdersStorage(ordersFileLocation); JsonMenuStorage jsonMenuStorage = new JsonMenuStorage(menuFileLocation); JsonStatisticsStorage jsonStatsStorage = new JsonStatisticsStorage(statsFileLocation); try { ReadOnlyRestOrRant restOrRant = initialDataSupplier.get(); jsonTablesStorage.saveTables(restOrRant.getTables()); jsonOrdersStorage.saveOrders(restOrRant.getOrders()); jsonMenuStorage.saveMenu(restOrRant.getMenu()); jsonStatsStorage.saveStatistics(restOrRant.getStatistics()); } catch (IOException ioe) { throw new AssertionError(ioe); } } } @Override protected Config initConfig(Path configFilePath) { Config config = super.initConfig(configFilePath); config.setUserPrefsFilePath(DEFAULT_PREF_FILE_LOCATION_FOR_TESTING); return config; } @Override protected UserPrefs initPrefs(UserPrefsStorage storage) { UserPrefs userPrefs = super.initPrefs(storage); double x = Screen.getPrimary().getVisualBounds().getMinX(); double y = Screen.getPrimary().getVisualBounds().getMinY(); userPrefs.setGuiSettings(new GuiSettings(600.0, 600.0, (int) x, (int) y)); userPrefs.setTablesFilePath(tablesFileLocation); userPrefs.setOrdersFilePath(ordersFileLocation); userPrefs.setMenuFilePath(menuFileLocation); userPrefs.setStatisticsFilePath(statsFileLocation); return userPrefs; } /** * Returns a defensive copy of the RestOrRant data stored inside the storage files. */ public RestOrRant readStorageRestOrRant() { try { return new RestOrRant(storage.readOrders().get(), storage.readMenu().get(), storage.readTables().get(), storage.readStatistics().get()); } catch (DataConversionException dce) { throw new AssertionError("Data is not in the RestOrRant format.", dce); } catch (IOException ioe) { throw new AssertionError("Storage file cannot be found.", ioe); } } /** * Returns the file path of the tables storage file. */ public Path getTableStorageLocation() { return storage.getTableFilePath(); } /** * Returns the file path of the orders storage file. */ public Path getOrdersStorageLocation() { return storage.getOrdersFilePath(); } /** * Returns the file path of the menu storage file. */ public Path getMenuStorageLocation() { return storage.getMenuFilePath(); } /** * Returns the file path of the statistics storage file. */ public Path getStatisticsStorageLocation() { return storage.getStatisticsFilePath(); } /** * Returns a defensive copy of the model. */ public Model getModel() { Model copy = new ModelManager((model.getRestOrRant()), new UserPrefs()); ModelHelper.setOrderItemFilteredList(copy, model.getFilteredOrderItemList()); ModelHelper.setMenuItemFilteredList(copy, model.getFilteredMenuItemList()); ModelHelper.setTableFilteredList(copy, model.getFilteredTableList()); ModelHelper.setRevenueFilteredList(copy, model.getFilteredRevenueList()); return copy; } @Override public void start(Stage primaryStage) { ui.start(primaryStage); } public static void main(String[] args) { launch(args); } }
39.170886
107
0.709969
421bb968c4f4e586da1825a275ce40a3446d433c
9,019
package com.example.administrator.biaozhunban.greendao; import android.database.Cursor; import android.database.sqlite.SQLiteStatement; import org.greenrobot.greendao.AbstractDao; import org.greenrobot.greendao.Property; import org.greenrobot.greendao.internal.DaoConfig; import org.greenrobot.greendao.database.Database; import org.greenrobot.greendao.database.DatabaseStatement; import com.example.administrator.biaozhunban.greendao.entity.Agency; // THIS CODE IS GENERATED BY greenDAO, DO NOT EDIT. /** * DAO for table "AGENCY". */ public class AgencyDao extends AbstractDao<Agency, Long> { public static final String TABLENAME = "AGENCY"; /** * Properties of entity Agency.<br/> * Can be used for QueryBuilder and for referencing column names. */ public static class Properties { public final static Property Id = new Property(0, Long.class, "id", true, "_id"); public final static Property Agency_id = new Property(1, String.class, "agency_id", false, "AGENCY_ID"); public final static Property Agency_name = new Property(2, String.class, "agency_name", false, "AGENCY_NAME"); public final static Property Agency_tel = new Property(3, String.class, "agency_tel", false, "AGENCY_TEL"); public final static Property Agency_address = new Property(4, String.class, "agency_address", false, "AGENCY_ADDRESS"); public final static Property Province_code = new Property(5, String.class, "province_code", false, "PROVINCE_CODE"); public final static Property City_code = new Property(6, String.class, "city_code", false, "CITY_CODE"); public final static Property Area_code = new Property(7, String.class, "area_code", false, "AREA_CODE"); public final static Property Note = new Property(8, String.class, "note", false, "NOTE"); public final static Property CreateDate = new Property(9, String.class, "createDate", false, "CREATE_DATE"); } public AgencyDao(DaoConfig config) { super(config); } public AgencyDao(DaoConfig config, DaoSession daoSession) { super(config, daoSession); } /** Creates the underlying database table. */ public static void createTable(Database db, boolean ifNotExists) { String constraint = ifNotExists? "IF NOT EXISTS ": ""; db.execSQL("CREATE TABLE " + constraint + "\"AGENCY\" (" + // "\"_id\" INTEGER PRIMARY KEY AUTOINCREMENT ," + // 0: id "\"AGENCY_ID\" TEXT," + // 1: agency_id "\"AGENCY_NAME\" TEXT," + // 2: agency_name "\"AGENCY_TEL\" TEXT," + // 3: agency_tel "\"AGENCY_ADDRESS\" TEXT," + // 4: agency_address "\"PROVINCE_CODE\" TEXT," + // 5: province_code "\"CITY_CODE\" TEXT," + // 6: city_code "\"AREA_CODE\" TEXT," + // 7: area_code "\"NOTE\" TEXT," + // 8: note "\"CREATE_DATE\" TEXT);"); // 9: createDate } /** Drops the underlying database table. */ public static void dropTable(Database db, boolean ifExists) { String sql = "DROP TABLE " + (ifExists ? "IF EXISTS " : "") + "\"AGENCY\""; db.execSQL(sql); } @Override protected final void bindValues(DatabaseStatement stmt, Agency entity) { stmt.clearBindings(); Long id = entity.getId(); if (id != null) { stmt.bindLong(1, id); } String agency_id = entity.getAgency_id(); if (agency_id != null) { stmt.bindString(2, agency_id); } String agency_name = entity.getAgency_name(); if (agency_name != null) { stmt.bindString(3, agency_name); } String agency_tel = entity.getAgency_tel(); if (agency_tel != null) { stmt.bindString(4, agency_tel); } String agency_address = entity.getAgency_address(); if (agency_address != null) { stmt.bindString(5, agency_address); } String province_code = entity.getProvince_code(); if (province_code != null) { stmt.bindString(6, province_code); } String city_code = entity.getCity_code(); if (city_code != null) { stmt.bindString(7, city_code); } String area_code = entity.getArea_code(); if (area_code != null) { stmt.bindString(8, area_code); } String note = entity.getNote(); if (note != null) { stmt.bindString(9, note); } String createDate = entity.getCreateDate(); if (createDate != null) { stmt.bindString(10, createDate); } } @Override protected final void bindValues(SQLiteStatement stmt, Agency entity) { stmt.clearBindings(); Long id = entity.getId(); if (id != null) { stmt.bindLong(1, id); } String agency_id = entity.getAgency_id(); if (agency_id != null) { stmt.bindString(2, agency_id); } String agency_name = entity.getAgency_name(); if (agency_name != null) { stmt.bindString(3, agency_name); } String agency_tel = entity.getAgency_tel(); if (agency_tel != null) { stmt.bindString(4, agency_tel); } String agency_address = entity.getAgency_address(); if (agency_address != null) { stmt.bindString(5, agency_address); } String province_code = entity.getProvince_code(); if (province_code != null) { stmt.bindString(6, province_code); } String city_code = entity.getCity_code(); if (city_code != null) { stmt.bindString(7, city_code); } String area_code = entity.getArea_code(); if (area_code != null) { stmt.bindString(8, area_code); } String note = entity.getNote(); if (note != null) { stmt.bindString(9, note); } String createDate = entity.getCreateDate(); if (createDate != null) { stmt.bindString(10, createDate); } } @Override public Long readKey(Cursor cursor, int offset) { return cursor.isNull(offset + 0) ? null : cursor.getLong(offset + 0); } @Override public Agency readEntity(Cursor cursor, int offset) { Agency entity = new Agency( // cursor.isNull(offset + 0) ? null : cursor.getLong(offset + 0), // id cursor.isNull(offset + 1) ? null : cursor.getString(offset + 1), // agency_id cursor.isNull(offset + 2) ? null : cursor.getString(offset + 2), // agency_name cursor.isNull(offset + 3) ? null : cursor.getString(offset + 3), // agency_tel cursor.isNull(offset + 4) ? null : cursor.getString(offset + 4), // agency_address cursor.isNull(offset + 5) ? null : cursor.getString(offset + 5), // province_code cursor.isNull(offset + 6) ? null : cursor.getString(offset + 6), // city_code cursor.isNull(offset + 7) ? null : cursor.getString(offset + 7), // area_code cursor.isNull(offset + 8) ? null : cursor.getString(offset + 8), // note cursor.isNull(offset + 9) ? null : cursor.getString(offset + 9) // createDate ); return entity; } @Override public void readEntity(Cursor cursor, Agency entity, int offset) { entity.setId(cursor.isNull(offset + 0) ? null : cursor.getLong(offset + 0)); entity.setAgency_id(cursor.isNull(offset + 1) ? null : cursor.getString(offset + 1)); entity.setAgency_name(cursor.isNull(offset + 2) ? null : cursor.getString(offset + 2)); entity.setAgency_tel(cursor.isNull(offset + 3) ? null : cursor.getString(offset + 3)); entity.setAgency_address(cursor.isNull(offset + 4) ? null : cursor.getString(offset + 4)); entity.setProvince_code(cursor.isNull(offset + 5) ? null : cursor.getString(offset + 5)); entity.setCity_code(cursor.isNull(offset + 6) ? null : cursor.getString(offset + 6)); entity.setArea_code(cursor.isNull(offset + 7) ? null : cursor.getString(offset + 7)); entity.setNote(cursor.isNull(offset + 8) ? null : cursor.getString(offset + 8)); entity.setCreateDate(cursor.isNull(offset + 9) ? null : cursor.getString(offset + 9)); } @Override protected final Long updateKeyAfterInsert(Agency entity, long rowId) { entity.setId(rowId); return rowId; } @Override public Long getKey(Agency entity) { if(entity != null) { return entity.getId(); } else { return null; } } @Override public boolean hasKey(Agency entity) { return entity.getId() != null; } @Override protected final boolean isEntityUpdateable() { return true; } }
37.268595
127
0.600399
f8fb10ad779abf008cf5819c8e20bf6727c0ef80
298
package com.example.redisspringboot.repository; import com.example.redisspringboot.domain.Person; import org.springframework.data.repository.CrudRepository; import org.springframework.stereotype.Repository; @Repository public interface PersonRepository extends CrudRepository<Person, String> { }
29.8
74
0.855705
294108d211bd2ed55b4a854f75dffb5afba88ce7
1,297
package com.xuegao.netty_chat_room_server.tomcat2; import io.netty.buffer.Unpooled; import io.netty.channel.ChannelHandlerContext; import io.netty.handler.codec.http.*; public class WuzzResponse { //SocketChannel的封装 private ChannelHandlerContext ctx; private HttpRequest req; public WuzzResponse(ChannelHandlerContext ctx, HttpRequest req) { this.ctx = ctx; this.req = req; } public void write(String out) throws Exception { try { if (out == null || out.length() == 0) { return; } // 设置 http协议及请求头信息 FullHttpResponse response = new DefaultFullHttpResponse( // 设置http版本为1.1 HttpVersion.HTTP_1_1, // 设置响应状态码 HttpResponseStatus.OK, // 将输出值写出 编码为UTF-8 Unpooled.wrappedBuffer(out.getBytes("UTF-8"))); response.headers().set("Content-Type", "text/html;"); // 当前是否支持长连接 // if (HttpUtil.isKeepAlive(r)) { // // 设置连接内容为长连接 // response.headers().set(CONNECTION, HttpHeaderValues.KEEP_ALIVE); // } ctx.write(response); } finally { ctx.flush(); ctx.close(); } } }
29.477273
82
0.552814
b81f2553b4a12bef500076d85b809e97b90c3a0c
1,544
/* * Hibernate, Relational Persistence for Idiomatic Java * * License: GNU Lesser General Public License (LGPL), version 2.1 or later * See the lgpl.txt file in the root directory or http://www.gnu.org/licenses/lgpl-2.1.html */ package org.hibernate.orm.type.descriptor.java.internal; import org.hibernate.orm.type.descriptor.java.spi.AbstractBasicTypeDescriptor; import org.hibernate.orm.type.descriptor.spi.JdbcRecommendedSqlTypeMappingContext; import org.hibernate.orm.type.descriptor.spi.WrapperOptions; import org.hibernate.orm.type.descriptor.sql.spi.SqlTypeDescriptor; import org.hibernate.query.sqm.domain.type.SqmDomainTypeBasic; /** * @author Steve Ebersole */ public class NonStandardBasicJavaTypeDescriptor<T> extends AbstractBasicTypeDescriptor<T> implements SqmDomainTypeBasic { public NonStandardBasicJavaTypeDescriptor(Class<T> type) { super( type ); } @Override public SqlTypeDescriptor getJdbcRecommendedSqlType(JdbcRecommendedSqlTypeMappingContext context) { // none return null; } @Override public String toString(T value) { return null; } @Override public T fromString(String string) { return null; } @Override public <X> X unwrap(T value, Class<X> type, WrapperOptions options) { return null; } @Override public <X> T wrap(X value, WrapperOptions options) { return null; } @Override public String asLoggableText() { return "{non-standard-basic-type(" + getJavaType().getName() + "}"; } @Override public SqmDomainTypeBasic getExportedDomainType() { return this; } }
26.169492
121
0.766192
da6058926246da9bd4322066c81f121b3ef92742
5,644
package org.adoptopenjdk.jheappo.io; import org.adoptopenjdk.jheappo.objects.*; /* ROOT UNKNOWN | 0xFF | ID | object ID ROOT JNI GLOBAL | 0x01 | ID | object ID | ID | JNI global ref ID ROOT JNI LOCAL | 0x02 | ID | object ID | u4 | thread serial number | u4 | frame number in stack trace (-1 for empty) ROOT JAVA FRAME | 0x03 | ID | object ID | u4 | thread serial number | u4 | frame number in stack trace (-1 for empty) ROOT NATIVE STACK | 0x04 | ID | object ID | u4 | thread serial number ROOT STICKY CLASS | 0x05 | ID | object ID ROOT THREAD BLOCK | 0x06 | ID | object ID | u4 | thread serial number ROOT MONITOR USED | 0x07 | ID | object ID ROOT THREAD OBJECT | 0x08 | ID | thread object ID | u4 | thread serial number | u4 | stack trace serial number CLASS DUMP | 0x20 | ID | class object ID | u4 | stack trace serial number | ID | super class object ID | ID | class loader object ID | ID | signers object ID | ID | protection domain object ID | ID | reserved | ID | reserved | u4 | instance size (in bytes) | u2 | size of constant pool and number of records that follow: | u2 | constant pool index | u1 | type of entry: (See Basic Type) | value | value of entry (u1, u2, u4, or u8 based on type of entry) | u2 | Number of static fields: | ID | static field name string ID | u1 | type of field: (See Basic Type) | value | value of entry (u1, u2, u4, or u8 based on type of field) | u2 | Number of instance fields (not including super class's) | ID | field name string ID | u1 | type of field: (See Basic Type) INSTANCE DUMP | 0x21 | ID | object ID | u4 | stack trace serial number | ID | class object ID | u4 | number of bytes that follow |[value]* | instance field values (this class, followed by super class, etc) OBJECT ARRAY DUMP | 0x22 | ID | array object ID | u4 | stack trace serial number | u4 | number of elements | ID | array class object ID | [ID]* | elements PRIMITIVE ARRAY DUMP | 0x23 | ID | array object ID | u4 | stack trace serial number | u4 | number of elements | u1 | element type (See Basic Type) | [u1]* | elements (packed array) Basic Types 2 | object 4 | boolean 5 | char 6 | float 7 | double 8 | byte 9 | short 10 | int 11 | long */ public class HeapDumpSegment extends HeapProfileRecord { public static final int TAG1 = 0x0C; public static final int TAG2 = 0x1C; private final EncodedChunk body; public HeapDumpSegment(EncodedChunk body) { this.body = body; } public boolean hasNext() { return body.endOfBuffer(); } public HeapObject next() { int typeCode = body.extractU1(); switch (typeCode) { case RootUnknown.TAG: return new RootUnknown(body); case RootJNIGlobal.TAG: return new RootJNIGlobal(body); case RootJNILocal.TAG: return new RootJNILocal(body); case RootJavaFrame.TAG: return new RootJavaFrame(body); case RootNativeStack.TAG: return new RootNativeStack(body); case RootStickyClass.TAG: return new RootStickyClass(body); case RootThreadBlock.TAG: return new RootThreadBlock(body); case RootMonitorUsed.TAG: return new RootMonitorUsed(body); case RootThreadObject.TAG: return new RootThreadObject(body); case ClassObject.TAG: return new ClassObject(body); case InstanceObject.TAG: return new InstanceObject(body); case ObjectArray.TAG: return new ObjectArray(body); case PrimitiveArray.TAG: return new PrimitiveArray(body); default: System.out.println(typeCode + " not recognized... @index=" + body.getIndex()); return null; } } }
40.898551
110
0.435507
b833d542410835c133307f2bef67674235c5d44d
628
package com.wixpress.petri.experiments.domain; import com.fasterxml.jackson.databind.JavaType; import org.junit.Test; import static org.junit.Assert.assertTrue; /** * Created with IntelliJ IDEA. * User: uri * Date: 4/23/14 * Time: 5:10 PM * To change this template use File | Settings | File Templates. */ public class FilterTypeIdResolverTest { @Test public void createsUnrecognizedFilterWhenResolvingUnrecognizedId() throws Exception { JavaType filterFromUnknown = new FilterTypeIdResolver().typeFromId("UNKNOWN"); assertTrue(filterFromUnknown.hasRawClass(UnrecognizedFilter.class)); } }
27.304348
89
0.753185
a0f466c1087c41608618ae4b54e3b29542fce9e3
1,003
/** * http://practice.geeksforgeeks.org/problems/number-of-ways/0 * Medium * Given a tile of size 1 x 4, how many ways you can construct a grid of size N x 4. Input: The first line of input contains an integer T denoting the number of test cases. The first line of each test case is N. Output: Print number of possible ways. Constraints: 1 ≤ T ≤ 50 1 ≤ N ≤ 80 Example: Input: 3 1 4 5 Output: 1 2 3 0 1 2 3 4 5 6 7 8 9 0 1 1 1 2 3 4 5 7 9 */ package jacoblo.algorithm.DynamicProgramming; public class NumberOfWaysForTies { public static void main(String[] args0 ) { int n = 79; long result = numOfWaysForTies( n) ; System.out.println(result); } public static long numOfWaysForTies(int n) { if (n <= 0 ) return 0; long[] result = new long[n+1]; result[1] = 1; if (n >= 2) { result[2] = 1; } if (n >= 3) { result[3] = 1; } if (n >= 4) { result[4] = 2; } for (int i = 5 ; i <= n ; i++ ) { result[i] = result[i-1] + result[i-4]; } return result[n]; } }
16.442623
84
0.62014
92a8ea8fc7385a55a9ce988183d9d3e346ef26ce
1,262
package invisibleinktoolkit.algorithms.gui; import java.awt.Dimension; import java.awt.event.ActionListener; import javax.swing.BoxLayout; import javax.swing.JCheckBox; import javax.swing.JPanel; import javax.swing.border.TitledBorder; public class LSBMatchPanel extends JPanel{ //VARIABLES /** * Generated Serialisation ID. */ private static final long serialVersionUID = -5347327864521430768L; /** * Whether to match LSB or not. */ private JCheckBox mShouldMatch; //CONSTRUCTORS /** * Creates a new LSB Matching Panel. * * @param listener The listener for check box change events. * @param match Whether match should be set by default. */ public LSBMatchPanel(ActionListener listener, boolean match){ super(); this.setLayout(new BoxLayout(this, BoxLayout.X_AXIS)); this.setBorder(new TitledBorder("Should this algorithm use LSB Matching?")); this.setPreferredSize(new Dimension(600,50)); mShouldMatch = new JCheckBox("Use LSB Matching?", match); JPanel spacer = new JPanel(); this.add(mShouldMatch); this.add(spacer); mShouldMatch.addActionListener(listener); } //FUNCTIONS /** * Whether we should match LSB or not. */ public boolean shouldMatch(){ return mShouldMatch.isSelected(); } }
22.945455
78
0.734548
da15a5cdd2a5fb3f41118d8adfe46d26f700c587
6,131
/* * 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 com.angularjs.bankapp.config; import java.util.Arrays; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.security.authentication.AuthenticationManager; import org.springframework.security.authentication.AuthenticationTrustResolver; import org.springframework.security.authentication.AuthenticationTrustResolverImpl; import org.springframework.security.authentication.ProviderManager; import org.springframework.security.authentication.dao.DaoAuthenticationProvider; import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder; import org.springframework.security.config.annotation.web.builders.HttpSecurity; import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; import org.springframework.security.core.userdetails.UserDetailsService; import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; import org.springframework.security.web.authentication.rememberme.PersistentTokenBasedRememberMeServices; import org.springframework.security.web.authentication.rememberme.PersistentTokenRepository; import org.springframework.security.web.util.matcher.AntPathRequestMatcher; /** * * @author ravindra.palli */ @Configuration @EnableWebSecurity public class WebSecurityConfig extends WebSecurityConfigurerAdapter { @Autowired private UserDetailsService userDetailsService; @Autowired @Qualifier("tokenRepository") private PersistentTokenRepository tokenRepository; @Autowired private RestAuthenticationEntryPoint restAuthenticationEntryPoint; @Autowired private AuthenticationSuccessHandler authenticationSuccessHandler; @Autowired private AuthenticationFailureHandler authenticationFailureHandler; @Autowired private CustomLogoutSuccessHandler customLogoutSuccessHandler; @Bean public BCryptPasswordEncoder passwordEncoder() { return new BCryptPasswordEncoder(); }; @Autowired public void configureGlobalSecurity(AuthenticationManagerBuilder auth) throws Exception { auth.authenticationProvider(authenticationProvider()); } @Override public AuthenticationManager authenticationManager() throws Exception { return new ProviderManager(Arrays.asList(authenticationProvider())); } @Bean public DaoAuthenticationProvider authenticationProvider() { DaoAuthenticationProvider authenticationProvider = new DaoAuthenticationProvider(); authenticationProvider.setUserDetailsService(userDetailsService); authenticationProvider.setPasswordEncoder(passwordEncoder()); return authenticationProvider; } @Bean public PersistentTokenBasedRememberMeServices getPersistentTokenBasedRememberMeServices() { PersistentTokenBasedRememberMeServices tokenBasedservice = new PersistentTokenBasedRememberMeServices( "rememberMe", userDetailsService, tokenRepository); tokenBasedservice.setTokenValiditySeconds(86400); tokenBasedservice.setParameter("rememberMe"); return tokenBasedservice; } @Bean public AuthenticationTrustResolver getAuthenticationTrustResolver() { return new AuthenticationTrustResolverImpl(); } @Override protected void configure(HttpSecurity http) throws Exception { // http.authorizeRequests() // .anyRequest().hasAnyRole("ADMIN", "USER") // .and() // .authorizeRequests().antMatchers("/admin/**").hasRole("ADMIN") // .and() // .authorizeRequests().antMatchers("/", "/login**").permitAll() // .and() // .formLogin().loginPage("/login").loginProcessingUrl("/login").permitAll() // .and() // .logout().logoutSuccessUrl("/login").permitAll() // .and() // .rememberMe().rememberMeParameter("remember-me").tokenRepository(tokenRepository) // .tokenValiditySeconds(86400) // .and() // .csrf() // .and() // .exceptionHandling().accessDeniedPage("/Access_Denied"); http .csrf().disable() .authorizeRequests() .anyRequest().authenticated() .and() .addFilterBefore( authenticationFilter(), CustomAuthenticationFilter.class) .logout().logoutUrl("/logout") .logoutSuccessHandler(customLogoutSuccessHandler) .and() .exceptionHandling() .authenticationEntryPoint(restAuthenticationEntryPoint); } @Bean public CustomAuthenticationFilter authenticationFilter() throws Exception { CustomAuthenticationFilter customAuthenticationFilter = new CustomAuthenticationFilter(); customAuthenticationFilter .setAuthenticationSuccessHandler(authenticationSuccessHandler); customAuthenticationFilter .setAuthenticationFailureHandler(authenticationFailureHandler); customAuthenticationFilter .setRequiresAuthenticationRequestMatcher( new AntPathRequestMatcher("/login", "POST") ); customAuthenticationFilter.setRememberMeServices( getPersistentTokenBasedRememberMeServices() ); customAuthenticationFilter .setAuthenticationManager(authenticationManager()); return customAuthenticationFilter; } }
41.707483
111
0.715381
0a0c0bb199894b20d9cd434a31035ed65cfd807f
7,201
/** * Copyright 2015 LinkedIn Corp. 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. */ package wherehows.dao.table; import java.util.ArrayList; import java.util.List; import java.util.Map; import javax.persistence.EntityManager; import javax.persistence.EntityManagerFactory; import javax.persistence.Query; import javax.persistence.criteria.CriteriaBuilder; import javax.persistence.criteria.CriteriaQuery; import javax.persistence.criteria.Predicate; import javax.persistence.criteria.Root; import lombok.SneakyThrows; public class BaseDao { protected final EntityManagerFactory entityManagerFactory; public BaseDao(EntityManagerFactory factory) { this.entityManagerFactory = factory; } /** * Find an entity by primary key * @param entityClass T.class the entity class type * @param primaryKey Object * @param <T> Entity type to find * @return An entity */ @SneakyThrows @SuppressWarnings("unchecked") public <T> T find(Class<T> entityClass, Object primaryKey) { EntityManager entityManager = entityManagerFactory.createEntityManager(); try { return (T) entityManager.find(entityClass, primaryKey); } finally { entityManager.close(); } } /** * Find an entity by a single criteria, e.g. id, urn. * @param entityClass T.class the entity class type * @param criteriaKey String * @param criteriaValue Object * @param <T> Entity type to find * @return An entity */ @SneakyThrows @SuppressWarnings("unchecked") public <T> T findBy(Class<T> entityClass, String criteriaKey, Object criteriaValue) { EntityManager entityManager = entityManagerFactory.createEntityManager(); CriteriaBuilder cb = entityManager.getCriteriaBuilder(); CriteriaQuery<T> criteria = cb.createQuery(entityClass); Root<T> entityRoot = criteria.from(entityClass); criteria.select(entityRoot); criteria.where(cb.equal(entityRoot.get(criteriaKey), criteriaValue)); try { return entityManager.createQuery(criteria).getSingleResult(); } finally { entityManager.close(); } } /** * Find a list of entities by a single criteria, e.g. id, urn. * @param entityClass T.class the entity class type * @param criteriaKey String * @param criteriaValue Object * @param <T> Entity type to find * @return List of entities */ @SneakyThrows @SuppressWarnings("unchecked") public <T> List<T> findListBy(Class<T> entityClass, String criteriaKey, Object criteriaValue) { EntityManager entityManager = entityManagerFactory.createEntityManager(); CriteriaBuilder cb = entityManager.getCriteriaBuilder(); CriteriaQuery<T> criteria = cb.createQuery(entityClass); Root<T> entityRoot = criteria.from(entityClass); criteria.select(entityRoot); criteria.where(cb.equal(entityRoot.get(criteriaKey), criteriaValue)); try { return entityManager.createQuery(criteria).getResultList(); } finally { entityManager.close(); } } /** * Find a list of entities by a parameter map * @param entityClass T.class the entity class type * @param params Map<String, Object> * @param <T> Entity type to find * @return List of entities */ @SneakyThrows @SuppressWarnings("unchecked") public <T> List<T> findListBy(Class<T> entityClass, Map<String, ? extends Object> params) { EntityManager entityManager = entityManagerFactory.createEntityManager(); CriteriaBuilder cb = entityManager.getCriteriaBuilder(); CriteriaQuery<T> criteria = cb.createQuery(entityClass); Root<T> entityRoot = criteria.from(entityClass); //Constructing list of parameters List<Predicate> predicates = new ArrayList<Predicate>(); for (Map.Entry<String, ? extends Object> entry : params.entrySet()) { predicates.add(cb.equal(entityRoot.get(entry.getKey()), entry.getValue())); } criteria.select(entityRoot); criteria.where(predicates.toArray(new Predicate[]{})); try { return entityManager.createQuery(criteria).getResultList(); } finally { entityManager.close(); } } /** * Merge (update or create) an entity record. * @param record an entity object * @return the persisted / managed record */ @SneakyThrows public Object update(Object record) { EntityManager entityManager = entityManagerFactory.createEntityManager(); entityManager.getTransaction().begin(); try { record = entityManager.merge(record); entityManager.getTransaction().commit(); return record; } finally { entityManager.close(); } } /** * Update/merge a list of entity records. * @param records a list of entity objects */ @SneakyThrows public void updateList(List<? extends Object> records) { EntityManager entityManager = entityManagerFactory.createEntityManager(); entityManager.getTransaction().begin(); try { for (Object record : records) { entityManager.merge(record); entityManager.flush(); } entityManager.getTransaction().commit(); } finally { entityManager.close(); } } /** * Remove an entity record. If it's detached, try to attach it first. * @param record an entity object */ @SneakyThrows public void remove(Object record) { EntityManager entityManager = entityManagerFactory.createEntityManager(); entityManager.getTransaction().begin(); try { entityManager.remove(entityManager.contains(record) ? record : entityManager.merge(record)); entityManager.getTransaction().commit(); } finally { entityManager.close(); } } /** * Remove a list of entity record. * @param records a list of entity object */ @SneakyThrows public void removeList(List<? extends Object> records) { EntityManager entityManager = entityManagerFactory.createEntityManager(); entityManager.getTransaction().begin(); try { for (Object record : records) { entityManager.remove(entityManager.contains(record) ? record : entityManager.merge(record)); entityManager.flush(); } entityManager.getTransaction().commit(); } finally { entityManager.close(); } } /** * Execute an update or delete query String. * @param queryStr String * @param params Parameters */ @SneakyThrows public void executeUpdate(String queryStr, Map<String, Object> params) { EntityManager entityManager = entityManagerFactory.createEntityManager(); try { Query query = entityManager.createQuery(queryStr); for (Map.Entry<String, Object> param : params.entrySet()) { query.setParameter(param.getKey(), param.getValue()); } query.executeUpdate(); } finally { entityManager.close(); } } }
32.004444
100
0.700458