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
|
|---|---|---|---|---|---|
9aaa930a2c9aff1c47e4234038b1d928b3e496fd
| 3,920
|
package soundcom.scorelab.org.soundcom_lib;
import android.content.Context;
import android.widget.ImageView;
import soundcom.scorelab.org.soundcom_lib.FSK_Modulator;
import soundcom.scorelab.org.soundcom_lib.AudioHandler;
import soundcom.scorelab.org.soundcom_lib.ImageHandler;
import soundcom.scorelab.org.soundcom_lib.StringHanlder;
import java.util.ArrayList;
public class Transmitter {
private static String modulation;
private static ImageView image;
private static String src;
private static double sample_rate;
private static double symbol_size;
private static int [] data;
private static double sample_period;
private static int number_of_carriers;
private static ArrayList<Double> modulated;
private static ImageHandler image_handler;
private static FSK_Modulator fsk_modulator;
private static AudioHandler audio_handler;
private static StringHanlder string_handler;
private static Context context;
public Transmitter() {
}
public Transmitter(String modulation,ImageView image, double sample_rate, double symbol_size, double sample_period, int number_of_carriers,Context context) { //Contructor for image
this.modulation = modulation;
this.image = image;
this.sample_rate = sample_rate;
this.symbol_size = symbol_size;
this.sample_period = sample_period;
this.number_of_carriers = number_of_carriers;
this.context = context;
initImage();
initString();
initModulator();
}
public Transmitter(String modulation,String src, double sample_rate, double symbol_size, double sample_period, int number_of_carriers,Context context) {//Constructore for String
this.modulation = modulation;
this.src = src;
this.sample_rate = sample_rate;
this.symbol_size = symbol_size;
this.sample_period = sample_period;
this.number_of_carriers = number_of_carriers;
this.context = context;
long startTime = System.nanoTime();
initString();
initModulator();
long endTime = System.nanoTime();
long duration = (endTime - startTime)/1000000;
System.out.println("Time taken for modulation: " + duration + "ms") ;
}
public void initImage(){
image_handler = new ImageHandler(image);
System.out.println("This is the length of Data : " + image_handler.getData_size());
data = new int [image_handler.getData_size()];
data = image_handler.getBitImage();
}
public void initString(){
string_handler = new StringHanlder(src);
System.out.println("This is the length of Data : " + string_handler.getB().length);
data = new int [string_handler.getB().length];
data = string_handler.getB();
}
public void initModulator (){
if (modulation.equals("FSK")) {
fsk_modulator = new FSK_Modulator(data, sample_rate, symbol_size, number_of_carriers);
fsk_modulator.modulate();
modulated = fsk_modulator.getModulated();
System.out.println("This is the length of modulated : " + modulated.size());
}
}
public void writeAudio (){
audio_handler = new AudioHandler(castToDouble(modulated),context,"FSK.wav");
audio_handler.writeFile();
audio_handler.close();
}
public Double [] castToDouble(ArrayList<Double> in ){
Double [] r = new Double[in.size()];
for (int i = 0; i <in.size() ; i++) {
r[i] = (Double) in.get(i);
}
return r;
}
}
| 36.296296
| 184
| 0.621939
|
45205172948b2aa043887fb03ee2b3a746223757
| 980
|
package me.ByteCoder.Core.Command.Commands;
import me.ByteCoder.Core.Command.Command;
import me.ByteCoder.Core.Command.CommandSender;
import me.ByteCoder.Core.Logger.Logger;
import me.ByteCoder.Core.Logger.Logger.LoggType;
import me.ByteCoder.Core.Utils.ServerUtils;
import me.ByteCoder.Core.Utils.StringUtils;
public class Restart extends Command {
@Override
public void exec(CommandSender sender, String in, String[] args) {
if(args.length == 1){
loadShutdownListener();
Logger.println("Restarting...", LoggType.INFO);
System.exit(0);
}
}
@Override
public String getCommand() {
return "restart";
}
@Override
public String getDescription() {
return "Restart core system";
}
private static void loadShutdownListener() {
Runtime.getRuntime().addShutdownHook(new Thread() {
@Override
public void run() {
ServerUtils.run("cmd /C java -jar " + StringUtils.getJarFile().getName());
}
});
}
}
| 23.902439
| 79
| 0.696939
|
2244e40ed74bc546963f7cb01c9f6af5a5ec3c58
| 755
|
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See License.txt in the repository root.
package com.microsoft.tfs.core.clients.serverstatus.exceptions;
import com.microsoft.tfs.core.exceptions.TEClientException;
/**
* Base class for server status client exceptions.
*
* @since TEE-SDK-10.1
*/
public class ServerStatusException extends TEClientException {
public ServerStatusException() {
super();
}
public ServerStatusException(final String message, final Throwable cause) {
super(message, cause);
}
public ServerStatusException(final String message) {
super(message);
}
public ServerStatusException(final Throwable cause) {
super(cause);
}
}
| 24.354839
| 79
| 0.711258
|
c80c76874f0522bb64199066be7c6c80bdf656b2
| 66
|
import org.openqa.selenium.WebDriver;
public class StartMain{
}
| 11
| 37
| 0.787879
|
4ba81082fa0d3aaffcec5cb2dcab33593a947893
| 3,114
|
/*******************************************************************************
* Copyright © 2019 by California Community Colleges Chancellor's Office
*
* 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.cccnext.tesuto.content.assembler.competency;
import org.cccnext.tesuto.content.dto.competency.CompetencyMapDto;
import org.cccnext.tesuto.content.model.competency.CompetencyMap;
import org.cccnext.tesuto.content.model.competency.CompetencyRef;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import static org.junit.Assert.assertEquals;
/**
* Created by jasonbrown on 6/17/16.
*/
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = { "classpath:/testApplicationContext.xml" })
public class CompetencyMapDtoAssemblerImplTest {
@Autowired
CompetencyMapDtoAssembler competencyMapDtoAssembler;
public CompetencyMap getCompetencyMap(){
CompetencyMap competencyMap = new CompetencyMap();
competencyMap.setVersion(4);
competencyMap.setIdentifier("Identifier");
competencyMap.setCompetencyRefs(generateCompetencyRefs(Arrays.asList("id-TEST-0001", "id-TEST-0002", "id-TEST-0003")));
competencyMap.setDiscipline("MATH");
competencyMap.setTitle("TEST | TITLE");
return competencyMap;
}
@Test
public void testAssembleDisassemble(){
CompetencyMap competencyMap = getCompetencyMap();
CompetencyMapDto competencyMapDto = competencyMapDtoAssembler.assembleDto(competencyMap);
CompetencyMap competencyMapDisassembled = competencyMapDtoAssembler.disassembleDto(competencyMapDto);
assertEquals("CompetencyMap incorrectly assembled, dissassembled", competencyMap, competencyMapDisassembled);
}
public static List<CompetencyRef> generateCompetencyRefs(List<String> identifiers) {
List<CompetencyRef> competenceRefs = new ArrayList<CompetencyRef>();
for(String identifier:identifiers) {
CompetencyRef ref = new CompetencyRef();
ref.setCompetencyIdentifier(identifier);
ref.setVersion(1);
ref.setDiscipline("discipline");
competenceRefs.add(ref);
}
return competenceRefs;
}
}
| 40.441558
| 127
| 0.708414
|
dd65043ed73e83c97787039acf45644409c91def
| 179
|
package net.adrianlehmann.swt_revision.patterns.variation_patterns.factory_method;
/**
* Created by adrianlehmann on 09.07.17.
*/
public class uPhone implements Smartphone {
}
| 22.375
| 82
| 0.793296
|
a3ce5150cedd8dd9e60b91e58c283adec18fcc0e
| 4,725
|
/*
* Copyright 2018 NAVER Corp.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.navercorp.pinpoint.test;
import com.navercorp.pinpoint.common.util.Assert;
import com.navercorp.pinpoint.profiler.context.AsyncSpanChunk;
import com.navercorp.pinpoint.profiler.context.LocalAsyncId;
import com.navercorp.pinpoint.profiler.context.id.TraceRoot;
/**
* @author Woonduk Kang(emeroad)
*/
public class Item implements Comparable<Item> {
private final Object value;
private final long time;
private final long spanId;
private final int sequence;
private final TraceRoot traceRoot;
private final LocalAsyncId localAsyncId;
// public Item(Object value, long time, TraceRoot traceRoot, int sequence) {
// this(value, time, traceRoot, sequence, OrderedSpanRecorder.ASYNC_ID_NOT_SET, OrderedSpanRecorder.ASYNC_SEQUENCE_NOT_SET);
// }
public Item(Object value, long time, TraceRoot traceRoot, int sequence) {
this.value = value;
this.time = time;
this.traceRoot = Assert.requireNonNull(traceRoot, "traceRoot");
this.spanId = traceRoot.getTraceId().getSpanId();
this.sequence = sequence;
if (value instanceof AsyncSpanChunk) {
final AsyncSpanChunk spanChunk = (AsyncSpanChunk) value;
this.localAsyncId = spanChunk.getLocalAsyncId();
} else {
this.localAsyncId = null;
}
}
public Object getValue() {
return value;
}
public long getSpanId() {
return spanId;
}
public TraceRoot getTraceRoot() {
return traceRoot;
}
@Override
public int compareTo(Item o) {
if (this.localAsyncId == null && o.localAsyncId == null) {
return compareItems(this, o);
} else if (this.localAsyncId != null && o.localAsyncId != null) {
return compareAsyncItems(this, o);
} else {
if (this.localAsyncId == null) {
return -1;
} else {
return 1;
}
}
}
private static int compareItems(Item lhs, Item rhs) {
if (lhs.time < rhs.time) {
return -1;
} else if (lhs.time > rhs.time) {
return 1;
} else {
if (lhs.spanId < rhs.spanId) {
return -1;
} else if (lhs.spanId > rhs.spanId) {
return 1;
} else {
if (lhs.sequence < rhs.sequence) {
return -1;
} else if (lhs.sequence > rhs.sequence) {
return 1;
} else {
return compareHashes(lhs, rhs);
}
}
}
}
private static int compareAsyncItems(Item lhs, Item rhs) {
final LocalAsyncId localAsyncId1 = lhs.localAsyncId;
final LocalAsyncId localAsyncId2 = rhs.localAsyncId;
if (localAsyncId1.getAsyncId() < localAsyncId2.getAsyncId()) {
return -1;
} else if (localAsyncId1.getAsyncId() > localAsyncId2.getAsyncId()) {
return 1;
} else {
if (localAsyncId1.getSequence() < localAsyncId2.getSequence()) {
return -1;
} else if (localAsyncId1.getSequence() > localAsyncId2.getSequence()) {
return 1;
} else {
if (lhs.sequence < rhs.sequence) {
return -1;
} else if (lhs.sequence > rhs.sequence) {
return 1;
} else {
return compareHashes(lhs, rhs);
}
}
}
}
private static int compareHashes(Item lhs, Item rhs) {
int h1 = System.identityHashCode(lhs.value);
int h2 = System.identityHashCode(rhs.value);
return h1 < h2 ? -1 : (h1 > h2 ? 1 : 0);
}
@Override
public String toString() {
return "Item{" +
"value=" + value +
", time=" + time +
", spanId=" + spanId +
", sequence=" + sequence +
", traceRoot=" + traceRoot +
", localAsyncId=" + localAsyncId +
'}';
}
}
| 31.925676
| 131
| 0.567196
|
8863945d3108edaf7475a34ea042ea26b4b85496
| 29,716
|
package org.batfish.question.routes;
import static org.batfish.datamodel.Prefix.MAX_PREFIX_LENGTH;
import static org.batfish.datamodel.matchers.RowMatchers.hasColumn;
import static org.batfish.question.routes.RoutesAnswerer.COL_ADMIN_DISTANCE;
import static org.batfish.question.routes.RoutesAnswerer.COL_AS_PATH;
import static org.batfish.question.routes.RoutesAnswerer.COL_COMMUNITIES;
import static org.batfish.question.routes.RoutesAnswerer.COL_LOCAL_PREF;
import static org.batfish.question.routes.RoutesAnswerer.COL_METRIC;
import static org.batfish.question.routes.RoutesAnswerer.COL_NETWORK;
import static org.batfish.question.routes.RoutesAnswerer.COL_NEXT_HOP;
import static org.batfish.question.routes.RoutesAnswerer.COL_NEXT_HOP_INTERFACE;
import static org.batfish.question.routes.RoutesAnswerer.COL_NEXT_HOP_IP;
import static org.batfish.question.routes.RoutesAnswerer.COL_NODE;
import static org.batfish.question.routes.RoutesAnswerer.COL_ORIGIN_PROTOCOL;
import static org.batfish.question.routes.RoutesAnswerer.COL_PROTOCOL;
import static org.batfish.question.routes.RoutesAnswerer.COL_ROUTE_ENTRY_PRESENCE;
import static org.batfish.question.routes.RoutesAnswerer.COL_TAG;
import static org.batfish.question.routes.RoutesAnswerer.COL_VRF_NAME;
import static org.batfish.question.routes.RoutesAnswererUtil.alignRouteRowAttributes;
import static org.batfish.question.routes.RoutesAnswererUtil.computeNextHopNode;
import static org.batfish.question.routes.RoutesAnswererUtil.getAbstractRouteRowsDiff;
import static org.batfish.question.routes.RoutesAnswererUtil.getBgpRibRoutes;
import static org.batfish.question.routes.RoutesAnswererUtil.getBgpRouteRowsDiff;
import static org.batfish.question.routes.RoutesAnswererUtil.getMainRibRoutes;
import static org.batfish.question.routes.RoutesAnswererUtil.getRoutesDiff;
import static org.batfish.question.routes.RoutesAnswererUtil.groupBgpRoutes;
import static org.batfish.question.routes.RoutesAnswererUtil.groupRoutes;
import static org.hamcrest.Matchers.allOf;
import static org.hamcrest.Matchers.contains;
import static org.hamcrest.Matchers.containsInAnyOrder;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.hasSize;
import static org.hamcrest.Matchers.nullValue;
import static org.junit.Assert.assertThat;
import com.google.common.collect.HashBasedTable;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.ImmutableSortedMap;
import com.google.common.collect.ImmutableSortedSet;
import com.google.common.collect.Lists;
import com.google.common.collect.Multiset;
import com.google.common.collect.Table;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.SortedMap;
import java.util.SortedSet;
import org.batfish.datamodel.AbstractRoute;
import org.batfish.datamodel.AsPath;
import org.batfish.datamodel.Bgpv4Route;
import org.batfish.datamodel.Bgpv4Route.Builder;
import org.batfish.datamodel.Configuration;
import org.batfish.datamodel.GenericRib;
import org.batfish.datamodel.Ip;
import org.batfish.datamodel.OriginType;
import org.batfish.datamodel.OspfExternalType2Route;
import org.batfish.datamodel.Prefix;
import org.batfish.datamodel.RoutingProtocol;
import org.batfish.datamodel.answers.Schema;
import org.batfish.datamodel.bgp.community.StandardCommunity;
import org.batfish.datamodel.ospf.OspfMetricType;
import org.batfish.datamodel.pojo.Node;
import org.batfish.datamodel.table.Row;
import org.batfish.question.routes.DiffRoutesOutput.KeyPresenceStatus;
import org.batfish.question.routes.RoutesAnswererTest.MockRib;
import org.batfish.question.routes.RoutesAnswererUtil.RouteEntryPresenceStatus;
import org.batfish.question.routes.RoutesQuestion.RibProtocol;
import org.batfish.specifier.RoutingProtocolSpecifier;
import org.hamcrest.Matcher;
import org.junit.Test;
/** Tests for {@link RoutesAnswererUtil} */
public class RoutesAnswererUtilTest {
@Test
public void testAlignRtRowAttrs() {
RouteRowAttribute rra1 = RouteRowAttribute.builder().setNextHop("node1").build();
RouteRowAttribute rra3 = RouteRowAttribute.builder().setNextHop("node3").build();
RouteRowAttribute rra5 = RouteRowAttribute.builder().setNextHop("node5").build();
RouteRowAttribute rra2 = RouteRowAttribute.builder().setNextHop("node2").build();
RouteRowAttribute rra4 = RouteRowAttribute.builder().setNextHop("node4").build();
List<List<RouteRowAttribute>> alignedRouteRowattrs =
alignRouteRowAttributes(
ImmutableList.of(rra1, rra3, rra5), ImmutableList.of(rra2, rra4, rra5));
// expected result after merging the two lists
List<List<RouteRowAttribute>> expectedOutput =
ImmutableList.of(
Lists.newArrayList(rra1, null),
Lists.newArrayList(null, rra2),
Lists.newArrayList(rra3, null),
Lists.newArrayList(null, rra4),
Lists.newArrayList(rra5, rra5));
assertThat(alignedRouteRowattrs, equalTo(expectedOutput));
}
@Test
public void testAlignRtRowAttrsTrailingNulls1() {
RouteRowAttribute rra1 = RouteRowAttribute.builder().setNextHop("node1").build();
RouteRowAttribute rra2 = RouteRowAttribute.builder().setNextHop("node2").build();
RouteRowAttribute rra3 = RouteRowAttribute.builder().setNextHop("node3").build();
List<List<RouteRowAttribute>> alignedRouteRowattrs =
alignRouteRowAttributes(ImmutableList.of(rra1, rra2, rra3), ImmutableList.of(rra1));
// null trails for non-matching attributes
List<List<RouteRowAttribute>> expectedOutput =
ImmutableList.of(
Lists.newArrayList(rra1, rra1),
Lists.newArrayList(rra2, null),
Lists.newArrayList(rra3, null));
assertThat(alignedRouteRowattrs, equalTo(expectedOutput));
}
@Test
public void testAlignRtRowAttrsTrailingNulls2() {
RouteRowAttribute rra1 = RouteRowAttribute.builder().setNextHop("node1").build();
RouteRowAttribute rra2 = RouteRowAttribute.builder().setNextHop("node2").build();
RouteRowAttribute rra3 = RouteRowAttribute.builder().setNextHop("node3").build();
List<List<RouteRowAttribute>> alignedRouteRowattrs =
alignRouteRowAttributes(ImmutableList.of(rra1), ImmutableList.of(rra1, rra2, rra3));
// null trails for non-matching attributes
List<List<RouteRowAttribute>> expectedOutput =
ImmutableList.of(
Lists.newArrayList(rra1, rra1),
Lists.newArrayList(null, rra2),
Lists.newArrayList(null, rra3));
assertThat(alignedRouteRowattrs, equalTo(expectedOutput));
}
@Test
public void testAlignRtRowAttrsLeadingNulls() {
RouteRowAttribute rra1 = RouteRowAttribute.builder().setNextHop("node1").build();
RouteRowAttribute rra2 = RouteRowAttribute.builder().setNextHop("node2").build();
RouteRowAttribute rra3 = RouteRowAttribute.builder().setNextHop("node3").build();
List<List<RouteRowAttribute>> alignedRouteRowattrs =
alignRouteRowAttributes(ImmutableList.of(rra3), ImmutableList.of(rra1, rra2, rra3));
// trailing nulls for non-matching attributes
List<List<RouteRowAttribute>> expectedOutput =
ImmutableList.of(
Lists.newArrayList(null, rra1),
Lists.newArrayList(null, rra2),
Lists.newArrayList(rra3, rra3));
assertThat(alignedRouteRowattrs, equalTo(expectedOutput));
}
@Test
public void testMainRibColumnsValue() {
SortedMap<String, SortedMap<String, GenericRib<AbstractRoute>>> ribs =
ImmutableSortedMap.of(
"n1",
ImmutableSortedMap.of(
Configuration.DEFAULT_VRF_NAME,
new MockRib<>(
ImmutableSet.of(
OspfExternalType2Route.builder()
.setNetwork(Prefix.parse("1.1.1.0/24"))
.setNextHopIp(Ip.parse("1.1.1.2"))
.setAdmin(10)
.setMetric(30L)
.setLsaMetric(2)
.setCostToAdvertiser(2)
.setArea(1L)
.setAdvertiser("n2")
.setOspfMetricType(OspfMetricType.E2)
.build()))));
Multiset<Row> actual =
getMainRibRoutes(
ribs,
ImmutableSet.of("n1"),
null,
RoutingProtocolSpecifier.ALL_PROTOCOLS_SPECIFIER,
".*",
null);
assertThat(
actual,
contains(
allOf(
hasColumn(COL_NODE, new Node("n1"), Schema.NODE),
hasColumn(COL_VRF_NAME, Configuration.DEFAULT_VRF_NAME, Schema.STRING),
hasColumn(COL_NETWORK, Prefix.parse("1.1.1.0/24"), Schema.PREFIX),
hasColumn(COL_NEXT_HOP_IP, Ip.parse("1.1.1.2"), Schema.IP),
hasColumn(COL_NEXT_HOP_INTERFACE, "dynamic", Schema.STRING),
hasColumn(COL_NEXT_HOP, nullValue(), Schema.STRING),
hasColumn(COL_PROTOCOL, "ospfE2", Schema.STRING),
hasColumn(COL_TAG, nullValue(), Schema.INTEGER),
hasColumn(COL_ADMIN_DISTANCE, equalTo(10), Schema.INTEGER),
hasColumn(COL_METRIC, equalTo(30L), Schema.LONG))));
}
@Test
public void testBgpRibRouteColumnsValue() {
// Create two BGP routes: one standard route and one from a BGP unnumbered session
Ip ip = Ip.parse("1.1.1.1");
Prefix prefix = Prefix.create(ip, MAX_PREFIX_LENGTH);
Ip bgpUnnumIp = Ip.parse("169.254.0.1");
Bgpv4Route.Builder rb =
Bgpv4Route.builder()
.setNetwork(prefix)
.setOriginType(OriginType.IGP)
.setCommunities(ImmutableSortedSet.of(StandardCommunity.of(65537L)))
.setProtocol(RoutingProtocol.BGP)
.setOriginatorIp(Ip.parse("1.1.1.2"))
.setAsPath(AsPath.ofSingletonAsSets(ImmutableList.of(1L, 2L)));
Bgpv4Route standardRoute = rb.setNextHopIp(ip).build();
Bgpv4Route unnumRoute = rb.setNextHopIp(bgpUnnumIp).setNextHopInterface("iface").build();
Table<String, String, Set<Bgpv4Route>> bgpRouteTable = HashBasedTable.create();
bgpRouteTable.put("node", "vrf", ImmutableSet.of(standardRoute, unnumRoute));
Multiset<Row> rows =
getBgpRibRoutes(
bgpRouteTable,
RibProtocol.BGP,
ImmutableSet.of("node"),
null,
RoutingProtocolSpecifier.ALL_PROTOCOLS_SPECIFIER,
".*");
// Both routes should have the same values for these columns
Matcher<Row> commonMatcher =
allOf(
hasColumn(COL_NODE, new Node("node"), Schema.NODE),
hasColumn(COL_VRF_NAME, "vrf", Schema.STRING),
hasColumn(COL_NETWORK, prefix, Schema.PREFIX),
hasColumn(COL_PROTOCOL, "bgp", Schema.STRING),
hasColumn(COL_AS_PATH, "1 2", Schema.STRING),
hasColumn(COL_METRIC, 0, Schema.INTEGER),
hasColumn(COL_LOCAL_PREF, 0L, Schema.LONG),
hasColumn(COL_COMMUNITIES, ImmutableList.of("1:1"), Schema.list(Schema.STRING)),
hasColumn(COL_ORIGIN_PROTOCOL, nullValue(), Schema.STRING),
hasColumn(COL_TAG, nullValue(), Schema.INTEGER));
assertThat(
rows,
containsInAnyOrder(
// Standard route
allOf(
commonMatcher,
hasColumn(COL_NEXT_HOP_IP, ip, Schema.IP),
hasColumn(COL_NEXT_HOP_INTERFACE, "dynamic", Schema.STRING)),
// Route from BGP unnumbered session
allOf(
commonMatcher,
hasColumn(COL_NEXT_HOP_IP, nullValue(), Schema.IP),
hasColumn(COL_NEXT_HOP_INTERFACE, "iface", Schema.STRING))));
}
@Test
public void testGetBgpRoutesCommunities() {
Ip ip = Ip.parse("1.1.1.1");
Table<String, String, Set<Bgpv4Route>> bgpRouteTable = HashBasedTable.create();
bgpRouteTable.put(
"node",
"vrf",
ImmutableSet.of(
new Builder()
.setNetwork(Prefix.create(ip, MAX_PREFIX_LENGTH))
.setOriginType(OriginType.IGP)
.setOriginatorIp(ip)
.setReceivedFromIp(ip)
.setCommunities(ImmutableSortedSet.of(StandardCommunity.of(65537L)))
.setProtocol(RoutingProtocol.BGP)
.build()));
Multiset<Row> rows =
getBgpRibRoutes(
bgpRouteTable,
RibProtocol.BGP,
ImmutableSet.of("node"),
null,
RoutingProtocolSpecifier.ALL_PROTOCOLS_SPECIFIER,
".*");
assertThat(
rows.iterator().next().get(COL_COMMUNITIES, Schema.list(Schema.STRING)),
equalTo(ImmutableList.of("1:1")));
}
@Test
public void testComputeNextHopNode() {
assertThat(computeNextHopNode(null, ImmutableMap.of()), nullValue());
assertThat(computeNextHopNode(Ip.parse("1.1.1.1"), null), nullValue());
assertThat(computeNextHopNode(Ip.parse("1.1.1.1"), ImmutableMap.of()), nullValue());
assertThat(
computeNextHopNode(
Ip.parse("1.1.1.1"), ImmutableMap.of(Ip.parse("1.1.1.1"), ImmutableSet.of("n1"))),
equalTo("n1"));
assertThat(
computeNextHopNode(
Ip.parse("1.1.1.1"), ImmutableMap.of(Ip.parse("1.1.1.2"), ImmutableSet.of("n1"))),
nullValue());
}
@Test
public void testBgpRoutesRowDiff() {
RouteRowAttribute.Builder routeRowAttrBuilder =
RouteRowAttribute.builder()
.setAdminDistance(200)
.setMetric(2L)
.setOriginProtocol("bgp")
.setAsPath(AsPath.ofSingletonAsSets(ImmutableList.of(1L, 2L)))
.setLocalPreference(1L);
List<List<RouteRowAttribute>> diffMatrix = new ArrayList<>();
diffMatrix.add(Lists.newArrayList(routeRowAttrBuilder.build(), routeRowAttrBuilder.build()));
List<List<RouteRowAttribute>> diffMatrixChanged = new ArrayList<>();
diffMatrix.add(
Lists.newArrayList(routeRowAttrBuilder.build(), routeRowAttrBuilder.setMetric(1L).build()));
List<List<RouteRowAttribute>> diffMatrixMissingRefs = new ArrayList<>();
diffMatrixMissingRefs.add(Lists.newArrayList(routeRowAttrBuilder.build(), null));
List<List<RouteRowAttribute>> diffMatrixMissingBase = new ArrayList<>();
diffMatrixMissingBase.add(Lists.newArrayList(null, routeRowAttrBuilder.build()));
List<DiffRoutesOutput> diff =
ImmutableList.of(
new DiffRoutesOutput(
new RouteRowKey("node", "vrf", Prefix.parse("1.1.1.1/24")),
new RouteRowSecondaryKey(Ip.parse("1.1.1.2"), "bgp"),
KeyPresenceStatus.IN_BOTH,
diffMatrix,
KeyPresenceStatus.IN_BOTH),
new DiffRoutesOutput(
new RouteRowKey("node", "vrf", Prefix.parse("1.1.1.1/24")),
new RouteRowSecondaryKey(Ip.parse("1.1.1.2"), "bgp"),
KeyPresenceStatus.IN_BOTH,
diffMatrixChanged,
KeyPresenceStatus.IN_BOTH),
new DiffRoutesOutput(
new RouteRowKey("node", "vrf", Prefix.parse("1.1.1.1/24")),
new RouteRowSecondaryKey(Ip.parse("1.1.1.2"), "bgp"),
KeyPresenceStatus.ONLY_IN_SNAPSHOT,
diffMatrixMissingRefs,
KeyPresenceStatus.IN_BOTH),
new DiffRoutesOutput(
new RouteRowKey("node", "vrf", Prefix.parse("1.1.1.1/24")),
new RouteRowSecondaryKey(Ip.parse("1.1.1.2"), "bgp"),
KeyPresenceStatus.ONLY_IN_REFERENCE,
diffMatrixMissingBase,
KeyPresenceStatus.IN_BOTH),
new DiffRoutesOutput(
new RouteRowKey("node", "vrf", Prefix.parse("1.1.1.1/24")),
new RouteRowSecondaryKey(Ip.parse("1.1.1.2"), "bgp"),
KeyPresenceStatus.IN_BOTH,
diffMatrixMissingRefs,
KeyPresenceStatus.IN_BOTH),
new DiffRoutesOutput(
new RouteRowKey("node", "vrf", Prefix.parse("1.1.1.1/24")),
new RouteRowSecondaryKey(Ip.parse("1.1.1.2"), "bgp"),
KeyPresenceStatus.IN_BOTH,
diffMatrixMissingBase,
KeyPresenceStatus.IN_BOTH));
Multiset<Row> rows = getBgpRouteRowsDiff(diff, RibProtocol.BGP);
assertThat(
rows,
containsInAnyOrder(
ImmutableList.of(
hasColumn(
COL_ROUTE_ENTRY_PRESENCE,
equalTo(RouteEntryPresenceStatus.UNCHANGED.routeEntryPresenceName()),
Schema.STRING),
hasColumn(
COL_ROUTE_ENTRY_PRESENCE,
equalTo(RouteEntryPresenceStatus.CHANGED.routeEntryPresenceName()),
Schema.STRING),
hasColumn(
COL_ROUTE_ENTRY_PRESENCE,
equalTo(RouteEntryPresenceStatus.ONLY_IN_SNAPSHOT.routeEntryPresenceName()),
Schema.STRING),
hasColumn(
COL_ROUTE_ENTRY_PRESENCE,
equalTo(RouteEntryPresenceStatus.ONLY_IN_REFERENCE.routeEntryPresenceName()),
Schema.STRING),
hasColumn(
COL_ROUTE_ENTRY_PRESENCE,
equalTo(RouteEntryPresenceStatus.ONLY_IN_SNAPSHOT.routeEntryPresenceName()),
Schema.STRING),
hasColumn(
COL_ROUTE_ENTRY_PRESENCE,
equalTo(RouteEntryPresenceStatus.ONLY_IN_REFERENCE.routeEntryPresenceName()),
Schema.STRING))));
}
@Test
public void testGroupMatchingRoutesByPrefix() {
SortedMap<String, SortedMap<String, GenericRib<AbstractRoute>>> ribs =
ImmutableSortedMap.of(
"n1",
ImmutableSortedMap.of(
Configuration.DEFAULT_VRF_NAME,
new MockRib<>(
ImmutableSet.of(
OspfExternalType2Route.builder()
.setNetwork(Prefix.parse("1.1.1.0/24"))
.setNextHopIp(Ip.parse("1.1.1.2"))
.setAdmin(10)
.setMetric(30L)
.setLsaMetric(2)
.setCostToAdvertiser(2)
.setArea(1L)
.setAdvertiser("n2")
.setOspfMetricType(OspfMetricType.E2)
.build(),
OspfExternalType2Route.builder()
.setNetwork(Prefix.parse("1.1.1.0/24"))
.setNextHopIp(Ip.parse("1.1.1.3"))
.setAdmin(10)
.setMetric(20L)
.setLsaMetric(2)
.setCostToAdvertiser(2)
.setArea(1L)
.setAdvertiser("n2")
.setOspfMetricType(OspfMetricType.E2)
.build()))));
Map<RouteRowKey, Map<RouteRowSecondaryKey, SortedSet<RouteRowAttribute>>> grouped =
groupRoutes(
ribs,
ImmutableSet.of("n1"),
null,
".*",
RoutingProtocolSpecifier.ALL_PROTOCOLS_SPECIFIER,
null);
assertThat(grouped.keySet(), hasSize(1));
RouteRowKey expectedKey =
new RouteRowKey("n1", Configuration.DEFAULT_VRF_NAME, Prefix.parse("1.1.1.0/24"));
assertThat(grouped.keySet().iterator().next(), equalTo(expectedKey));
Map<RouteRowSecondaryKey, SortedSet<RouteRowAttribute>> innerGroup = grouped.get(expectedKey);
// checking equality of inner group
Map<RouteRowSecondaryKey, SortedSet<RouteRowAttribute>> expectedInnerMap =
ImmutableMap.of(
new RouteRowSecondaryKey(Ip.parse("1.1.1.2"), "ospfE2"),
ImmutableSortedSet.of(
RouteRowAttribute.builder().setAdminDistance(10).setMetric(30L).build()),
new RouteRowSecondaryKey(Ip.parse("1.1.1.3"), "ospfE2"),
ImmutableSortedSet.of(
RouteRowAttribute.builder().setAdminDistance(10).setMetric(20L).build()));
// matching the secondary key
assertThat(innerGroup, equalTo(expectedInnerMap));
}
@Test
public void testGroupMatchingBgpRoutesByPrefix() {
Bgpv4Route bgpv4Route1 =
Bgpv4Route.builder()
.setNetwork(Prefix.parse("1.1.1.0/24"))
.setNextHopIp(Ip.parse("1.1.1.2"))
.setOriginType(OriginType.IGP)
.setOriginatorIp(Ip.parse("1.1.1.2"))
.setProtocol(RoutingProtocol.BGP)
.setLocalPreference(1L)
.setAdmin(10)
.setMetric(30L)
.setAsPath(AsPath.ofSingletonAsSets(ImmutableList.of(1L, 2L)))
.build();
Bgpv4Route bgpv4Route2 =
Bgpv4Route.builder()
.setNetwork(Prefix.parse("1.1.1.0/24"))
.setNextHopIp(Ip.parse("1.1.1.3"))
.setAdmin(10)
.setMetric(20L)
.setOriginType(OriginType.IGP)
.setOriginatorIp(Ip.parse("1.1.1.2"))
.setProtocol(RoutingProtocol.BGP)
.setLocalPreference(1L)
.setAsPath(AsPath.ofSingletonAsSets(ImmutableList.of(1L, 2L)))
.build();
Table<String, String, Set<Bgpv4Route>> bgpTable = HashBasedTable.create();
bgpTable.row("node").put(Configuration.DEFAULT_VRF_NAME, new HashSet<>());
bgpTable.row("node").get(Configuration.DEFAULT_VRF_NAME).add(bgpv4Route1);
bgpTable.row("node").get(Configuration.DEFAULT_VRF_NAME).add(bgpv4Route2);
Map<RouteRowKey, Map<RouteRowSecondaryKey, SortedSet<RouteRowAttribute>>> grouped =
groupBgpRoutes(bgpTable, ImmutableSet.of("node"), ".*", null, ".*");
assertThat(grouped.keySet(), hasSize(1));
RouteRowKey expectedKey =
new RouteRowKey("node", Configuration.DEFAULT_VRF_NAME, Prefix.parse("1.1.1.0/24"));
assertThat(grouped.keySet().iterator().next(), equalTo(expectedKey));
Map<RouteRowSecondaryKey, SortedSet<RouteRowAttribute>> innerGroup = grouped.get(expectedKey);
// checking equality of inner group
Map<RouteRowSecondaryKey, SortedSet<RouteRowAttribute>> expectedInnerMap =
ImmutableMap.of(
new RouteRowSecondaryKey(Ip.parse("1.1.1.2"), "bgp"),
ImmutableSortedSet.of(
RouteRowAttribute.builder()
.setAdminDistance(10)
.setMetric(30L)
.setAsPath(AsPath.ofSingletonAsSets(ImmutableList.of(1L, 2L)))
.setLocalPreference(1L)
.build()),
new RouteRowSecondaryKey(Ip.parse("1.1.1.3"), "bgp"),
ImmutableSortedSet.of(
RouteRowAttribute.builder()
.setAdminDistance(10)
.setMetric(20L)
.setLocalPreference(1L)
.setAsPath(AsPath.ofSingletonAsSets(ImmutableList.of(1L, 2L)))
.build()));
// matching the secondary key
assertThat(innerGroup, equalTo(expectedInnerMap));
}
@Test
public void testGetRoutesDiffCommonKey() {
RouteRowKey routeRowKey = new RouteRowKey("node", "vrf", Prefix.parse("2.2.2.2/24"));
RouteRowSecondaryKey rrsk1 = new RouteRowSecondaryKey(Ip.parse("1.1.1.1"), "bgp");
RouteRowSecondaryKey rrsk2 = new RouteRowSecondaryKey(Ip.parse("1.1.1.2"), "bgp");
RouteRowSecondaryKey rrsk3 = new RouteRowSecondaryKey(Ip.parse("1.1.1.3"), "bgp");
RouteRowSecondaryKey rrsk4 = new RouteRowSecondaryKey(Ip.parse("1.1.1.4"), "bgp");
RouteRowAttribute rra1 = RouteRowAttribute.builder().setNextHop("node1").build();
RouteRowAttribute rra2 = RouteRowAttribute.builder().setNextHop("node2").build();
RouteRowAttribute rra3 = RouteRowAttribute.builder().setNextHop("node3").build();
RouteRowAttribute rra4 = RouteRowAttribute.builder().setNextHop("node4").build();
RouteRowAttribute rra5 = RouteRowAttribute.builder().setNextHop("node5").build();
ImmutableMap.Builder<RouteRowSecondaryKey, SortedSet<RouteRowAttribute>>
immutablelMapBuilderBase = ImmutableMap.builder();
ImmutableMap.Builder<RouteRowSecondaryKey, SortedSet<RouteRowAttribute>>
immutablelMapBuilderRef = ImmutableMap.builder();
Map<RouteRowSecondaryKey, SortedSet<RouteRowAttribute>> innerGroupsInBase =
immutablelMapBuilderBase
.put(rrsk1, ImmutableSortedSet.of(rra1))
.put(rrsk2, ImmutableSortedSet.of(rra1, rra2))
.put(rrsk3, ImmutableSortedSet.of(rra4))
.build();
Map<RouteRowSecondaryKey, SortedSet<RouteRowAttribute>> innerGroupsInRef =
immutablelMapBuilderRef
.put(rrsk1, ImmutableSortedSet.of(rra2))
.put(rrsk2, ImmutableSortedSet.of(rra1, rra3))
.put(rrsk4, ImmutableSortedSet.of(rra5))
.build();
List<DiffRoutesOutput> diffRoutesOutputs =
getRoutesDiff(
ImmutableMap.of(routeRowKey, innerGroupsInBase),
ImmutableMap.of(routeRowKey, innerGroupsInRef));
assertThat(
diffRoutesOutputs,
containsInAnyOrder(
new DiffRoutesOutput(
routeRowKey,
rrsk1,
KeyPresenceStatus.IN_BOTH,
ImmutableList.of(Lists.newArrayList(rra1, rra2)),
KeyPresenceStatus.IN_BOTH),
new DiffRoutesOutput(
routeRowKey,
rrsk2,
KeyPresenceStatus.IN_BOTH,
ImmutableList.of(
Lists.newArrayList(rra1, rra1),
Lists.newArrayList(rra2, null),
Lists.newArrayList(null, rra3)),
KeyPresenceStatus.IN_BOTH),
new DiffRoutesOutput(
routeRowKey,
rrsk3,
KeyPresenceStatus.ONLY_IN_SNAPSHOT,
ImmutableList.of(Lists.newArrayList(rra4, null)),
KeyPresenceStatus.IN_BOTH),
new DiffRoutesOutput(
routeRowKey,
rrsk4,
KeyPresenceStatus.ONLY_IN_REFERENCE,
ImmutableList.of(Lists.newArrayList(null, rra5)),
KeyPresenceStatus.IN_BOTH)));
}
@Test
public void testGetRoutesDiffNonCommonKey() {
RouteRowKey routeRowKey1 = new RouteRowKey("node1", "vrf", Prefix.parse("1.1.1.1/24"));
RouteRowKey routeRowKey2 = new RouteRowKey("node2", "vrf", Prefix.parse("1.1.1.2/24"));
RouteRowSecondaryKey rrsk1 = new RouteRowSecondaryKey(Ip.parse("1.1.1.1"), "bgp");
RouteRowSecondaryKey rrsk2 = new RouteRowSecondaryKey(Ip.parse("1.1.1.2"), "bgp");
RouteRowAttribute rra1 = RouteRowAttribute.builder().setNextHop("node11").build();
RouteRowAttribute rra2 = RouteRowAttribute.builder().setNextHop("node22").build();
ImmutableMap.Builder<RouteRowSecondaryKey, SortedSet<RouteRowAttribute>>
immutablelMapBuilderBase = ImmutableMap.builder();
ImmutableMap.Builder<RouteRowSecondaryKey, SortedSet<RouteRowAttribute>>
immutablelMapBuilderRef = ImmutableMap.builder();
Map<RouteRowSecondaryKey, SortedSet<RouteRowAttribute>> innerGroupsInBase =
immutablelMapBuilderBase.put(rrsk1, ImmutableSortedSet.of(rra1)).build();
Map<RouteRowSecondaryKey, SortedSet<RouteRowAttribute>> innerGroupsInRef =
immutablelMapBuilderRef.put(rrsk2, ImmutableSortedSet.of(rra2)).build();
List<DiffRoutesOutput> diffRoutesOutputs =
getRoutesDiff(
ImmutableMap.of(routeRowKey1, innerGroupsInBase),
ImmutableMap.of(routeRowKey2, innerGroupsInRef));
assertThat(
diffRoutesOutputs,
containsInAnyOrder(
new DiffRoutesOutput(
routeRowKey1,
rrsk1,
KeyPresenceStatus.ONLY_IN_SNAPSHOT,
ImmutableList.of(Lists.newArrayList(rra1, null)),
KeyPresenceStatus.ONLY_IN_SNAPSHOT),
new DiffRoutesOutput(
routeRowKey2,
rrsk2,
KeyPresenceStatus.ONLY_IN_REFERENCE,
ImmutableList.of(Lists.newArrayList(null, rra2)),
KeyPresenceStatus.ONLY_IN_REFERENCE)));
}
@Test
public void testAbstractRoutesRowDiff() {
RouteRowAttribute.Builder routeRowAttrBuilder =
RouteRowAttribute.builder().setAdminDistance(200).setMetric(2L).setNextHop("node1");
List<List<RouteRowAttribute>> diffMatrix = new ArrayList<>();
diffMatrix.add(Lists.newArrayList(routeRowAttrBuilder.build(), routeRowAttrBuilder.build()));
List<DiffRoutesOutput> diff =
ImmutableList.of(
new DiffRoutesOutput(
new RouteRowKey("node", "vrf", Prefix.parse("1.1.1.1/24")),
new RouteRowSecondaryKey(Ip.parse("1.1.1.2"), "bgp"),
KeyPresenceStatus.IN_BOTH,
diffMatrix,
KeyPresenceStatus.IN_BOTH));
Multiset<Row> rows = getAbstractRouteRowsDiff(diff);
assertThat(
rows,
containsInAnyOrder(
ImmutableList.of(
hasColumn(
COL_ROUTE_ENTRY_PRESENCE,
equalTo(RouteEntryPresenceStatus.UNCHANGED.routeEntryPresenceName()),
Schema.STRING))));
}
}
| 44.220238
| 100
| 0.645006
|
f984b8708ccb50ac85f7726ee9543b0381e3ee33
| 1,462
|
package ru.job4j.model.dao;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import ru.job4j.model.entities.Address;
import static org.junit.Assert.*;
public class DAddressTest {
private Address address;
private DAddress addr = DAddress.getInstance();
/**
* Before.
*/
@Before
public void before() {
address = new Address("Kiev");
addr.add(address);
}
/**
* After.
*/
@After
public void after() {
addr.delete(address.getId());
}
/**
* Test add.
*/
@Test
public void add() {
Address result = addr.getById(address.getId());
assertEquals(address, result);
}
/**
* Test update.
*/
@Test
public void update() {
String name = "Paris";
address.setName(name);
addr.update(address);
Address result = addr.getById(address.getId());
assertEquals(name, result.getName());
}
/**
* Test delete.
*/
@Test
public void delete() {
Address temp = new Address("LA");
addr.add(temp);
int size = addr.getAll().size();
addr.delete(temp.getId());
int result = addr.getAll().size();
assertEquals(size - 1, result);
}
/**
* Test getById.
*/
@Test
public void getById() {
Address temp = addr.getById(address.getId());
assertEquals(address, temp);
}
}
| 20.305556
| 55
| 0.546512
|
741dd3b0da3925ed6a2e4e06b67a3c461f569a52
| 330
|
package com.atlassian.opsgenie.user.model;
import com.fasterxml.jackson.annotation.JsonProperty;
import lombok.Data;
@Data
public class AddUserRequest{
@JsonProperty("fullName")
private String fullname;
private String username;
private String locale;
private String timezone;
private UserRole role;
}
| 18.333333
| 53
| 0.754545
|
eecbc0e90163a4e431442141644f58da9a74ddb4
| 1,469
|
/**
*
* Copyright 2020 paolo mococci
*
* 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 following 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 local.example.warehouse.view.route;
import org.springframework.beans.factory.annotation.Autowired;
import com.vaadin.flow.component.applayout.AppLayout;
import com.vaadin.flow.component.button.Button;
import com.vaadin.flow.component.icon.VaadinIcon;
import com.vaadin.flow.router.Route;
import com.vaadin.flow.router.RouteAlias;
import com.vaadin.flow.router.RouterLayout;
import com.vaadin.flow.server.PWA;
@Route("")
@RouteAlias("warehouse")
@PWA(name = "Warehouse", shortName = "Warehouse", enableInstallPrompt = false)
public class MainRoute
extends AppLayout
implements RouterLayout {
private static final long serialVersionUID = -1899543193616113831L;
@SuppressWarnings("unused")
private final Button logout;
@Autowired
public MainRoute() {
super();
this.logout = new Button("logout", VaadinIcon.SIGN_OUT.create());
}
}
| 29.979592
| 78
| 0.762423
|
fdfcce01774d110ca58dd5dbf2a97f031b265188
| 964
|
package com.example.swagger.demo.service;
import com.example.swagger.demo.model.Book;
import lombok.NoArgsConstructor;
import org.springframework.stereotype.Service;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.time.LocalDateTime;
import java.util.List;
import java.util.UUID;
@Service
public class BookService {
public List<Book> getBooks(){
return List.of(
new Book(UUID.randomUUID().toString(), "Clean Arquitecture", "Robert Martin", LocalDateTime.now(), new BigDecimal("150.50").setScale(2, RoundingMode.HALF_DOWN)),
new Book(UUID.randomUUID().toString(), "Mastering Microservices with Java", "Sourabh Sharma", LocalDateTime.now(), new BigDecimal("375.25").setScale(2, RoundingMode.HALF_DOWN)),
new Book(UUID.randomUUID().toString(), "Spring in Action", "Craig Walls", LocalDateTime.now(), new BigDecimal("311.75").setScale(2, RoundingMode.HALF_DOWN))
);
}
}
| 43.818182
| 193
| 0.717842
|
bdc4b3205fb1433998df72f61bbc5fe9e4512728
| 1,839
|
/*
* Copyright (c) 2008-2020, Hazelcast, Inc. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.hazelcast.sql.impl.calcite.opt.physical.visitor;
import com.hazelcast.sql.impl.QueryException;
import com.hazelcast.sql.impl.expression.Expression;
import com.hazelcast.sql.impl.expression.predicate.IsNullPredicate;
import org.apache.calcite.rex.RexCall;
import org.apache.calcite.sql.SqlOperator;
/**
* Utility methods for REX to Hazelcast expression conversion.
*/
public final class RexToExpression {
private RexToExpression() {
// No-op.
}
/**
* Converts a {@link RexCall} to {@link Expression}.
*
* @param call the call to convert.
* @return the resulting expression.
* @throws QueryException if the given {@link RexCall} can't be
* converted.
*/
@SuppressWarnings("SwitchStatementWithTooFewBranches")
public static Expression<?> convertCall(RexCall call, Expression<?>[] operands) {
SqlOperator operator = call.getOperator();
switch (operator.getKind()) {
case IS_NULL:
return IsNullPredicate.create(operands[0]);
default:
break;
}
throw QueryException.error("Unsupported operator: " + operator);
}
}
| 32.839286
| 85
| 0.681892
|
7ce140c4e698f83da86fb2fc8de2ffd4d9b052cf
| 2,896
|
/*
* Copyright Ningbo Qishan Technology Co., Ltd
*
* 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.mds.group.purchase.utils;
import net.sourceforge.pinyin4j.PinyinHelper;
import net.sourceforge.pinyin4j.format.HanyuPinyinCaseType;
import net.sourceforge.pinyin4j.format.HanyuPinyinOutputFormat;
import net.sourceforge.pinyin4j.format.exception.BadHanyuPinyinOutputFormatCombination;
/**
* 拼音工具
*
* @author shuke
*/
public class PinYinUtil {
/**
* 获取中文字符串首字母缩写
*
* @param str 中文字符串
* @return 首字母缩写 ping yin
* @throws BadHanyuPinyinOutputFormatCombination 拼音转换错误
*/
public static String getPingYin(String str) throws BadHanyuPinyinOutputFormatCombination {
HanyuPinyinOutputFormat defaultFormat = new HanyuPinyinOutputFormat();
// 设置大小写格式
defaultFormat.setCaseType(HanyuPinyinCaseType.UPPERCASE);
char[] charArray = str.toCharArray();
StringBuilder pinyin = new StringBuilder();
for (char aCharArray : charArray) {
//匹配中文,非中文转换会转换成null
if (Character.toString(aCharArray).matches("[\\u4E00-\\u9FA5]+")) {
String[] hanyuPinyinStringArray = PinyinHelper.toHanyuPinyinStringArray(aCharArray, defaultFormat);
if (hanyuPinyinStringArray != null) {
pinyin.append(hanyuPinyinStringArray[0].charAt(0));
}
}
}
return pinyin.toString();
}
/**
* 获取中文字符串首字母
*
* @param str 中文字符串
* @return 首字母 ping yin first
* @throws BadHanyuPinyinOutputFormatCombination 拼音转换错误
*/
public static String getPingYinFirst(String str) throws BadHanyuPinyinOutputFormatCombination {
HanyuPinyinOutputFormat defaultFormat = new HanyuPinyinOutputFormat();
// 设置大小写格式
defaultFormat.setCaseType(HanyuPinyinCaseType.UPPERCASE);
char[] charArray = str.toCharArray();
StringBuilder pinyin = new StringBuilder();
//匹配中文,非中文转换会转换成null
if (Character.toString(charArray[0]).matches("[\\u4E00-\\u9FA5]+")) {
String[] hanyuPinyinStringArray = PinyinHelper.toHanyuPinyinStringArray(charArray[0], defaultFormat);
if (hanyuPinyinStringArray != null) {
pinyin.append(hanyuPinyinStringArray[0].charAt(0));
}
}
return pinyin.toString();
}
}
| 36.658228
| 115
| 0.680594
|
843cc83fdd7a4ee80bd6f4719db0667985dac1d2
| 3,954
|
package io.voucherify.android.client.model;
import com.google.gson.annotations.SerializedName;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
public class Customer implements Querable {
private String id;
@SerializedName("source_id")
private String sourceId;
private String name;
private String email;
private String description;
@SerializedName("created_at")
private Date createdAt;
private Map<String, Object> metadata;
private String object;
public void setId(String id) {
this.id = id;
}
public void setSourceId(String sourceId) {
this.sourceId = sourceId;
}
public void setName(String name) {
this.name = name;
}
public void setEmail(String email) {
this.email = email;
}
public void setDescription(String description) {
this.description = description;
}
public void setCreatedAt(Date createdAt) {
this.createdAt = createdAt;
}
public void setMetadata(Map<String, Object> metadata) {
this.metadata = metadata;
}
public void setObject(String object) {
this.object = object;
}
public String getId() {
return id;
}
public String getSourceId() {
return sourceId;
}
public String getName() {
return name;
}
public String getEmail() {
return email;
}
public String getDescription() {
return description;
}
public Date getCreatedAt() {
return createdAt;
}
public Map<String, Object> getMetadata() {
return metadata;
}
public String getObject() {
return object;
}
@Override
public void createQuery(Map<String, String> map) {
map.put("customer[id]", id);
map.put("customer[source_id]", sourceId);
map.put("customer[name]", name);
map.put("customer[email]", email);
if (createdAt != null) {
map.put("customer[created_at]", createdAt.toString());
}
map.put("customer[object]", object);
if (metadata != null) {
for (Map.Entry<String, Object> ob : metadata.entrySet()) {
map.put("customer[metadata][" + ob.getKey() + "]", ob.getValue().toString());
}
}
}
public static class Builder {
private String id;
private String sourceId;
private String name;
private String email;
private String description;
private Map<String, Object> metadata;
public Builder withId(String id) {
this.id = id;
return this;
}
public Builder withSourceId(String sourceId) {
this.sourceId = sourceId;
return this;
}
public Builder withName(String name) {
this.name = name;
return this;
}
public Builder withEmail(String email) {
this.email = email;
return this;
}
public Builder withDescription(String description) {
this.description = description;
return this;
}
public Builder withMetadata(Map<String, Object> metadata) {
this.metadata = metadata;
return this;
}
public Builder addMetadata(String key, Object value) {
if (metadata == null) {
metadata = new HashMap<>();
}
metadata.put(key, value);
return this;
}
public Customer build() {
Customer customer = new Customer();
customer.id = id;
customer.sourceId = sourceId;
customer.name = name;
customer.email = email;
customer.description = description;
customer.metadata = metadata;
customer.object = "customer";
return customer;
}
}
}
| 22.724138
| 93
| 0.566262
|
851c7ed65fb94aaaff3aa67dc3ab67c50bbdf8f6
| 1,063
|
package com.genymobile.scrcpy;
import android.graphics.Rect;
public class Options {
private int maxSize;
private int bitRate;
private boolean tunnelForward;
private Rect crop;
private boolean sendFrameMeta; // send PTS so that the client may record properly
public int getMaxSize() {
return maxSize;
}
public void setMaxSize(int maxSize) {
this.maxSize = maxSize;
}
public int getBitRate() {
return bitRate;
}
public void setBitRate(int bitRate) {
this.bitRate = bitRate;
}
public boolean isTunnelForward() {
return tunnelForward;
}
public void setTunnelForward(boolean tunnelForward) {
this.tunnelForward = tunnelForward;
}
public Rect getCrop() {
return crop;
}
public void setCrop(Rect crop) {
this.crop = crop;
}
public boolean getSendFrameMeta() {
return sendFrameMeta;
}
public void setSendFrameMeta(boolean sendFrameMeta) {
this.sendFrameMeta = sendFrameMeta;
}
}
| 20.442308
| 85
| 0.64158
|
ceb4d9091c86c5bfa380b92a311c94b9fb67b73a
| 5,455
|
package com.quootta.mdate.ui.activity;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import com.quootta.mdate.R;
import com.quootta.mdate.base.BaseActivity;
import com.quootta.mdate.base.BaseApp;
import com.quootta.mdate.engine.account.AlterUserPasMesRequest;
import com.quootta.mdate.engine.account.AlterUserPasRequest;
import com.quootta.mdate.helper.CountDownButtonHelper;
import com.quootta.mdate.myListener.VolleyListener;
import com.quootta.mdate.utils.LogUtil;
import com.quootta.mdate.utils.SecretUtil;
import com.quootta.mdate.utils.ToastUtil;
import com.android.volley.RequestQueue;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.HashMap;
import java.util.Map;
import butterknife.Bind;
import butterknife.OnClick;
/**
* Created by Ryon on 2016/9/22/0022.
*/
public class AlterUserPasActivity extends BaseActivity {
@Bind(R.id.account_title)
TextView accountTitle;
@Bind(R.id.rel_title_bar)
RelativeLayout relTitleBar;
@Bind(R.id.account_alter_user_src)
ImageView accountAlterUserSrc;
@Bind(R.id.account_alter_user_text)
EditText accountAlterUserText;
@Bind(R.id.account_alter_get_code)
Button accountAlterGetCode;
@Bind(R.id.account_alter_mes_src)
ImageView accountAlterMesSrc;
@Bind(R.id.account_alter_mes_text)
EditText accountAlterMesText;
@Bind(R.id.account_alter_pas_src)
ImageView accountAlterPasSrc;
@Bind(R.id.account_alter_pas_text)
EditText accountAlterPasText;
@Bind(R.id.account_alter_bind)
RelativeLayout accountAlterBind;
// @Bind(R.id.account_alter_back)
// ImageView accountAlterBack;
// @Bind(R.id.account_title)
// TextView accountTitle;
// @Bind(R.id.rel_title_bar)
// RelativeLayout relTitleBar;
// @Bind(R.id.account_alter_user_src)
// ImageView accountAlterUserSrc;
// @Bind(R.id.account_alter_user_text)
// EditText accountAlterUserText;
// @Bind(R.id.account_alter_get_code)
// Button accountAlterGetCode;
// @Bind(R.id.account_alter_mes_src)
// ImageView accountAlterMesSrc;
// @Bind(R.id.account_alter_mes_text)
// EditText accountAlterMesText;
// @Bind(R.id.account_alter_pas_src)
// ImageView accountAlterPasSrc;
// @Bind(R.id.account_alter_pas_text)
// EditText accountAlterPasText;
// @Bind(R.id.account_alter_bind)
// RelativeLayout accountAlterBind;
private RequestQueue requestQueue;
@Override
protected void init() {
requestQueue = BaseApp.getRequestQueue();
}
@Override
protected int getRootView() {
return R.layout.activity_alte_userpas;
}
@Override
protected void initData() {
}
@Override
protected void setListener() {
}
//获取验证码
private void requestVerification() {
Map<String, String> paramsMap = new HashMap<>();
paramsMap.put("mobile", accountAlterUserText.getText().toString().trim());
AlterUserPasMesRequest alterUserPasMesRequest = new AlterUserPasMesRequest(paramsMap,
new VolleyListener() {
@Override
protected void onSuccess(JSONObject response) {
LogUtil.d("AlterUserPasActivity", "Response:" + response);
try {
ToastUtil.showToast(response.getString("msg").toString());
setCountDownTimer();
} catch (JSONException e) {
e.printStackTrace();
}
}
});
requestQueue.add(alterUserPasMesRequest);
}
private void setCountDownTimer() {
CountDownButtonHelper countDownButtonHelper = new CountDownButtonHelper(accountAlterGetCode,
getString(R.string.get_verification_code), 30, 1);
countDownButtonHelper.start();
}
//修改密码
private void alterUserPas() {
Map<String, String> alterPasMap = new HashMap<>();
alterPasMap.put("password", SecretUtil.bytesToMD5(accountAlterPasText.getText().toString()));
alterPasMap.put("mobile", accountAlterUserText.getText().toString());
alterPasMap.put("verify_code", accountAlterMesText.getText().toString());
AlterUserPasRequest alterUserPasRequest = new AlterUserPasRequest(alterPasMap, new VolleyListener() {
@Override
protected void onSuccess(JSONObject response) {
ToastUtil.showToast(getString(R.string.app_tips_text21));
finish();
}
});
requestQueue.add(alterUserPasRequest);
}
@OnClick({R.id.account_alter_back, R.id.account_alter_get_code, R.id.account_alter_bind})
public void onClick(View view) {
switch (view.getId()) {
case R.id.account_alter_back:
finish();
break;
case R.id.account_alter_get_code:
if (accountAlterPasText.getText().toString().trim() != null) {
requestVerification();
} else {
ToastUtil.showToast(getString(R.string.app_tips_text22));
}
break;
case R.id.account_alter_bind:
alterUserPas();
break;
}
}
}
| 32.470238
| 109
| 0.661778
|
6c07be0b112beb0b495f90a35c0d9c78618bc89a
| 986
|
package edu.century.FinalProject.old;
import java.math.BigDecimal;
public class SavingsAccount extends Account {
private final BigDecimal MIN_BALANCE = new BigDecimal("100.00");
public SavingsAccount(){
super();
}
public SavingsAccount(String amount, String accountNumber) {
super(amount, accountNumber);
}
public void makeWithdrawal(String amount) {
BigDecimal withdrawalAmount = new BigDecimal(amount);
int withdrawalStatus = this.getBalance().subtract(withdrawalAmount).compareTo(MIN_BALANCE);
if(withdrawalStatus == 0 || withdrawalStatus == 1) {
withdraw(withdrawalAmount);
}else
System.out.println("Cannot complete withdrawal - insufficient funds!");
}
public void makeDeposit(String amount) {
BigDecimal depositAmount = new BigDecimal(amount);
deposit(depositAmount);
}
public BigDecimal getMinBalance() {
return MIN_BALANCE;
}
public String toString(){
return super.toString();
}
}
| 22.930233
| 94
| 0.71501
|
c4267d68190b3472b8049ddb23c030f197ef4eec
| 2,185
|
/**
* Copyright (C) ${project.inceptionYear} ${owner} (hello@graylog.com)
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.graylog.plugins.backup.strategy;
import org.apache.commons.lang.SystemUtils;
import org.graylog.plugins.backup.model.BackupStruct;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;
public abstract class AbstractMongoBackupStrategy implements BackupStrategy
{
private static final Logger LOG = LoggerFactory.getLogger(AbstractMongoBackupStrategy.class);
protected BackupStruct backupStruct;
protected abstract void pack() throws Exception;
protected String osShellPath()
{
if (SystemUtils.IS_OS_UNIX)
{
return "/bin/sh";
}
throw new IllegalArgumentException("At the moment your system is not supported");
}
protected synchronized void processCommand(List<String> command) throws Exception
{
//need to find a a smart way to manage processBuilder
ProcessBuilder pb = new ProcessBuilder(command);
pb.redirectErrorStream(true);
Process p = pb.start( );
Timer timeOut = new Timer( );
timeOut.schedule(new TimerTask( )
{
@Override
public void run()
{
if(p.isAlive())
{
LOG.warn("restore process take more than 15 sec I'll destroy it");
p.destroy( );
}
}
//this parameter need to be configurable
}, 15000);
p.waitFor( );
timeOut.cancel( );
}
}
| 26.975309
| 97
| 0.655835
|
7b9a5d8ce5ac1ea2a476f341a074f0c64ce95c05
| 1,679
|
import java.util.Scanner;
public class SPIRALDISPLAY {
public static void Display(int [][] a)
{
for (int i = 0; i < a.length; i++) {
for (int j = 0; j < a[0].length; j++) {
System.out.print(a[i][j]+" ");
}
System.out.println();
}
}
public static void main(String[] args) {
Scanner scn = new Scanner(System.in);
int row = scn.nextInt();
int coloumn = scn.nextInt();
int [][] spiralArray = new int[row][coloumn];
for (int i = 0; i < spiralArray.length; i++) {
for (int j = 0; j < spiralArray[0].length; j++) {
spiralArray[i][j] = scn.nextInt();
}
}
int minr = 0;
int minc = 0;
int maxr = spiralArray.length-1;
int maxc = spiralArray[0].length-1;
int tne = row * coloumn;
int cnt = 0;
// Display(spiralArray);
while(cnt < tne)
{
// LEFT WALL
for(int i = minr , j=minc ; i <= maxr && cnt < tne; i++ )
{
System.out.println(spiralArray[i][j]);
cnt++;
}
minc++;
// BOTTOM WALL
for(int i = maxr , j=minc ; j <= maxc && cnt < tne; j++ )
{
System.out.println(spiralArray[i][j]);
cnt++;
}
maxr--;
for(int i = maxr , j=maxc ; i >= minr && cnt < tne; i-- )
{
System.out.println(spiralArray[i][j]);
cnt++;
}
maxc--;
for(int i = minr , j=maxc ; j >= minc && cnt < tne; j-- )
{
System.out.println(spiralArray[i][j]);
cnt++;
}
minr++;
}
}
}
//11
//21
//31
//32
//33
//34
//35
//25
//15
//14
//13
//12
//22
//23
//24
| 15.263636
| 63
| 0.455628
|
77b2880e9156642d10bf4b5830b9c6662be77d61
| 1,987
|
/*
* 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 battleship;
import java.util.Scanner;
import battleship.Exceptions.*;
import java.io.IOException;
/**
*
* @author Nacho Verdón
*
* El clásico juego de mesa 'Hundir la flota'.
*
* Esta clase se encarga de manejar la interacción con el jugador.
*/
public final class Battleship {
private static Grid grid;
// Objeto para manejar la entrada de datos.
private static final Scanner SC = new Scanner(System.in);;
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
try {
grid = new Grid();
showGrids();
grid.attackPlayerCell(2);
showGrids();
askForInput(grid);
} catch (Exception err) {
System.out.println(err.getMessage());
}
}
private static void clearScreen() {
System.out.print("\033[H\033[2J");
System.out.flush();
}
private static void showGrids() throws IOException {
clearScreen();
System.out.println(Text.PLAYER_GRID);
System.out.println(grid.getPlayerGrid());
System.out.println(Text.CPU_GRID);
System.out.println(grid.getCPUGrid());
}
/**
* Espera la entrada de datos del usuario y realiza acciones según los datos
* introducidos.
*
* @param grid Tablero sobre el cual se desarrollará la acción.
*/
private static void askForInput(Grid grid) {
System.out.println("Gimme int: ");
try {
int num = SC.nextInt();
} catch (IndexOutOfBoundsException e) {
System.out.println("Te pasaste, muyayo. But...");
} catch (Exception e) {
System.out.println("Not an int. But...");
}
System.out.println("It's OK, dude :)");
}
}
| 26.144737
| 80
| 0.603926
|
ce9d828e9b409f16b91d6f667f0c5288a4fb39dd
| 27,882
|
package gjavac.test.java;
import gjavac.lib.Contract;
import gjavac.lib.Offline;
import gjavac.lib.*;
import static gjavac.lib.UvmCoreLibs.*;
@Contract(storage = Storage.class)
class DemoContract extends UvmContract<Storage> {
@Override
public void init() {
this.getStorage().name = "";
this.getStorage().symbol = "";
this.getStorage().supply = ""; // int64 含精度 整数
this.getStorage().precision = 0L; // int64 精度 10的幂
this.getStorage().state = "NOT_INITED";
this.getStorage().admin = caller_address();
this.getStorage().allowLock = false;
this.getStorage().lockedAmounts = UvmMap.<String>create(); //users balance
this.getStorage().allowed = UvmMap.<String>create(); //users balance
this.getStorage().users = UvmMap.<String>create(); //users balance
}
@Offline
public String state(String arg){
return this.getStorage().state;
}
@Offline
public String tokenName(String arg){
return this.getStorage().name;
}
@Offline
public Long precision(String arg){
return this.getStorage().precision;
}
@Offline
public String admin(String arg){
return this.getStorage().admin;
}
@Offline
public Boolean allowLock(String arg){ return this.getStorage().allowLock; }
@Offline
public String supply(String arg){
return this.getStorage().supply;
}
@Offline
public String tokenSymbol(String arg){
return this.getStorage().symbol;
}
///////////////////////////
public void init_token( String arg) {
Utils utils = new Utils();
UvmJsonModule json = (UvmJsonModule)UvmCoreLibs.importModule(UvmJsonModule.class, "json");
utils.checkAdmin(this);
utils.checkCallerFrameValid((UvmContract)this);
Storage storage = (Storage)this.getStorage();
if (storage.state!=utils.NOT_INITED()) {
UvmCoreLibs.error("this token contract inited before");
} else {
UvmArray parsed = utils.parseAtLeastArgs(arg, 4, "argument format error, need format: name,symbol,supply,precision");
UvmMap info = UvmMap.create();
String name = (String)parsed.get(1);
String symbol = (String)parsed.get(2);
String supplystr = (String)parsed.get(3);
long precision = UvmCoreLibs.tointeger(parsed.get(4));
info.set("name", name);
info.set("symbol", symbol);
info.set("supply", supplystr);
info.set("precision", precision);
if (name != null && name.length() >= 1) {
storage.setName(name);
if (symbol != null && symbol.length() >= 1) {
storage.setSymbol(symbol);
UvmSafeMathModule safemathModule = (UvmSafeMathModule)UvmCoreLibs.importModule(UvmSafeMathModule.class, "safemath");
UvmBigInt bigintSupply = safemathModule.bigint(supplystr);
UvmBigInt bigint0 = safemathModule.bigint(0);
if (supplystr == null || safemathModule.le(bigintSupply, bigint0)) {
UvmCoreLibs.error("invalid supply:" + supplystr);
}
storage.setSupply(supplystr);
String fromAddress = utils.getFromAddress();
if (fromAddress == null) {
fromAddress = "null";
}
String callerAddr = UvmCoreLibs.caller_address();
if (fromAddress!=callerAddr) {
UvmCoreLibs.error("init_token can't be called from other contract:" + fromAddress);
} else {
UvmCoreLibs.fast_map_set("users", callerAddr, supplystr);
if (precision < 1L) {
UvmCoreLibs.error("precision must be positive integer");
} else {
UvmArray allowedPrecisions = UvmArray.create();
allowedPrecisions.add(1L);
allowedPrecisions.add(10L);
allowedPrecisions.add(100L);
allowedPrecisions.add(1000L);
allowedPrecisions.add(10000L);
allowedPrecisions.add(100000L);
allowedPrecisions.add(1000000L);
allowedPrecisions.add(10000000L);
allowedPrecisions.add(100000000L);
if (!utils.arrayContains(allowedPrecisions, precision)) {
UvmCoreLibs.error("precision can only be positive integer in " + json.dumps(allowedPrecisions));
} else {
storage.setPrecision(precision);
storage.setState(utils.COMMON());
UvmCoreLibs.emit("Inited", supplystr);
}
}
}
} else {
UvmCoreLibs.error("symbol needed");
}
} else {
UvmCoreLibs.error("name needed");
}
}
}
public void openAllowLock( String arg) {
Utils utils = new Utils();
utils.checkAdmin(this);
utils.checkState(this);
utils.checkCallerFrameValid((UvmContract)this);
Storage storage = (Storage)this.getStorage();
if (storage.getAllowLock()) {
UvmCoreLibs.error("this contract had been opened allowLock before");
} else {
storage.setAllowLock(true);
UvmCoreLibs.emit("AllowedLock", "");
}
}
@Offline
public String balanceOf( String owner) {
Utils utils = new Utils();
utils.checkStateInited(this);
utils.checkAddress(owner);
String amountStr = utils.getBalanceOfUser(this, owner);
return amountStr;
}
public void transfer( String arg) {
Utils utils = new Utils();
utils.checkState(this);
utils.checkCallerFrameValid((UvmContract)this);
if ((Storage)this.getStorage() != null) {
UvmArray parsed = utils.parseAtLeastArgs(arg, 2, "argument format error, need format is to_address,integer_amount[,memo]");
String to = UvmCoreLibs.tostring(parsed.get(1));
String amountStr = (String)parsed.get(2);
utils.checkAddress(to);
UvmSafeMathModule safemathModule = (UvmSafeMathModule)UvmCoreLibs.importModule(UvmSafeMathModule.class, "safemath");
UvmBigInt bigintAmount = safemathModule.bigint(amountStr);
UvmBigInt bigint0 = safemathModule.bigint(0);
if (amountStr == null || safemathModule.le(bigintAmount, bigint0)) {
UvmCoreLibs.error("invalid amount:" + amountStr);
return;
}
String fromAddress = utils.getFromAddress();
if(fromAddress == to){
UvmCoreLibs.error("fromAddress and toAddress is same:" + fromAddress);
return;
}
Object temp = UvmCoreLibs.fast_map_get("users", fromAddress);
if (temp == null) {
temp = "0";
}
UvmBigInt fromBalance = safemathModule.bigint(temp);
temp = UvmCoreLibs.fast_map_get("users", to);
if (temp == null) {
temp = "0";
}
UvmBigInt toBalance = safemathModule.bigint(temp);
if (safemathModule.lt(fromBalance, bigintAmount)) {
UvmCoreLibs.error("insufficient balance:" + safemathModule.tostring(fromBalance));
}
fromBalance = safemathModule.sub(fromBalance, bigintAmount);
toBalance = safemathModule.add(toBalance, bigintAmount);
String frombalanceStr = safemathModule.tostring(fromBalance);
if (frombalanceStr== "0") {
UvmCoreLibs.fast_map_set("users", fromAddress, (Object)null);
} else {
UvmCoreLibs.fast_map_set("users", fromAddress, frombalanceStr);
}
UvmCoreLibs.fast_map_set("users", to, safemathModule.tostring(toBalance));
if (UvmCoreLibs.is_valid_contract_address(to)) {
MultiOwnedContractSimpleInterface multiOwnedContract = (MultiOwnedContractSimpleInterface)UvmCoreLibs.importContractFromAddress(MultiOwnedContractSimpleInterface.class, to);
if (multiOwnedContract != null && multiOwnedContract.getOn_deposit_contract_token() != null) {
multiOwnedContract.on_deposit_contract_token(amountStr);
}
}
UvmMap eventArg = UvmMap.create();
eventArg.set("from", fromAddress);
eventArg.set("to", to);
eventArg.set("amount", amountStr);
String eventArgStr = UvmCoreLibs.tojsonstring(eventArg);
UvmCoreLibs.emit("Transfer", eventArgStr);
}
}
public void transferFrom( String arg) {
Utils utils = new Utils();
utils.checkState(this);
utils.checkCallerFrameValid((UvmContract)this);
if ((Storage)this.getStorage() != null) {
UvmArray parsed = utils.parseAtLeastArgs(arg, 3, "argument format error, need format is fromAddress,toAddress,amount(with precision)");
String fromAddress = UvmCoreLibs.tostring(parsed.get(1));
String toAddress = UvmCoreLibs.tostring(parsed.get(2));
String amountStr = UvmCoreLibs.tostring(parsed.get(3));
utils.checkAddress(fromAddress);
utils.checkAddress(toAddress);
if(fromAddress == toAddress){
UvmCoreLibs.error("fromAddress and toAddress is same:" + fromAddress);
return;
}
UvmSafeMathModule safemathModule = (UvmSafeMathModule)UvmCoreLibs.importModule(UvmSafeMathModule.class, "safemath");
UvmBigInt bigintAmount = safemathModule.bigint(amountStr);
UvmBigInt bigint0 = safemathModule.bigint(0);
if (amountStr == null || safemathModule.le(bigintAmount, bigint0)) {
UvmCoreLibs.error("invalid amount:" + amountStr);
}
Object temp = UvmCoreLibs.fast_map_get("users", fromAddress);
if (temp == null) {
temp = "0";
}
UvmBigInt bigintFromBalance = safemathModule.bigint(temp);
Object temp2 = UvmCoreLibs.fast_map_get("users", toAddress);
if (temp2 == null) {
temp2 = "0";
}
UvmBigInt bigintToBalance = safemathModule.bigint(temp2);
if (safemathModule.lt(bigintFromBalance, bigintAmount)) {
UvmCoreLibs.error("insufficient balance :" + safemathModule.tostring(bigintFromBalance));
}
Object allowedDataStr = UvmCoreLibs.fast_map_get("allowed", fromAddress);
if (allowedDataStr == null) {
UvmCoreLibs.error("not enough approved amount to withdraw");
} else {
UvmJsonModule jsonModule = (UvmJsonModule)UvmCoreLibs.importModule(UvmJsonModule.class, "json");
UvmMap allowedData = (UvmMap)UvmCoreLibs.totable(jsonModule.loads(UvmCoreLibs.tostring(allowedDataStr)));
String contractCaller = utils.getFromAddress();
if (allowedData == null) {
UvmCoreLibs.error("not enough approved amount to withdraw");
} else {
String approvedAmountStr = (String)allowedData.get(contractCaller);
if (approvedAmountStr == null) {
UvmCoreLibs.error("no approved amount to withdraw");
}
UvmBigInt bigintApprovedAmount = safemathModule.bigint(approvedAmountStr);
if (bigintApprovedAmount != null && !safemathModule.gt(bigintAmount, bigintApprovedAmount)) {
bigintFromBalance = safemathModule.sub(bigintFromBalance, bigintAmount);
String bigintFromBalanceStr = safemathModule.tostring(bigintFromBalance);
if (bigintFromBalanceStr=="0") {
bigintFromBalance = null;
}
bigintToBalance = safemathModule.add(bigintToBalance, bigintAmount);
String bigintToBalanceStr = safemathModule.tostring(bigintToBalance);
if (bigintToBalanceStr=="0") {
bigintToBalanceStr = null;
}
bigintApprovedAmount = safemathModule.sub(bigintApprovedAmount, bigintAmount);
UvmCoreLibs.fast_map_set("users", fromAddress, bigintFromBalanceStr);
UvmCoreLibs.fast_map_set("users", toAddress, bigintToBalanceStr);
if (safemathModule.tostring(bigintApprovedAmount)=="0") {
allowedData.set(contractCaller, null);
} else {
allowedData.set(contractCaller, safemathModule.tostring(bigintApprovedAmount));
}
allowedDataStr = UvmCoreLibs.tojsonstring(allowedData);
UvmCoreLibs.fast_map_set("allowed", fromAddress, allowedDataStr);
if (UvmCoreLibs.is_valid_contract_address(toAddress)) {
MultiOwnedContractSimpleInterface multiOwnedContract = (MultiOwnedContractSimpleInterface)UvmCoreLibs.importContractFromAddress(MultiOwnedContractSimpleInterface.class, toAddress);
if (multiOwnedContract != null && multiOwnedContract.getOn_deposit_contract_token() != null) {
multiOwnedContract.on_deposit_contract_token(amountStr);
}
}
UvmMap eventArg = UvmMap.create();
eventArg.set("from", fromAddress);
eventArg.set("to", toAddress);
eventArg.set("amount", amountStr);
String eventArgStr = UvmCoreLibs.tojsonstring(eventArg);
UvmCoreLibs.emit("Transfer", eventArgStr);
} else {
UvmCoreLibs.error("not enough approved amount to withdraw");
}
}
}
}
}
public void approve( String arg) {
Utils utils = new Utils();
utils.checkState(this);
utils.checkCallerFrameValid((UvmContract)this);
if ((Storage)this.getStorage() != null) {
UvmArray parsed = utils.parseAtLeastArgs(arg, 2, "argument format error, need format is spenderAddress,amount(with precision)");
String spender = UvmCoreLibs.tostring(parsed.get(1));
utils.checkAddress(spender);
String amountStr = UvmCoreLibs.tostring(parsed.get(2));
UvmSafeMathModule safemathModule = (UvmSafeMathModule)UvmCoreLibs.importModule(UvmSafeMathModule.class, "safemath");
UvmBigInt bigintAmount = safemathModule.bigint(amountStr);
UvmBigInt bigint0 = safemathModule.bigint(0);
if (amountStr == null || safemathModule.lt(bigintAmount, bigint0)) {
UvmCoreLibs.error("amount must be non-negative integer");
}
String contractCaller = utils.getFromAddress();
UvmJsonModule jsonModule = (UvmJsonModule)UvmCoreLibs.importModule(UvmJsonModule.class, "json");
UvmMap allowedDataTable = (UvmMap)null;
Object allowedDataStr = UvmCoreLibs.fast_map_get("allowed", contractCaller);
if (allowedDataStr == null) {
allowedDataTable = UvmMap.create();
} else {
allowedDataTable = (UvmMap)UvmCoreLibs.totable(jsonModule.loads(UvmCoreLibs.tostring(allowedDataStr)));
if (allowedDataTable == null) {
UvmCoreLibs.error("allowed storage data error");
return;
}
}
if(safemathModule.eq(bigintAmount,bigint0)){
allowedDataTable.set(spender,null);
}else{
allowedDataTable.set(spender, amountStr);
}
UvmCoreLibs.fast_map_set("allowed", contractCaller, UvmCoreLibs.tojsonstring(allowedDataTable));
UvmMap eventArg = UvmMap.create();
eventArg.set("from", contractCaller);
eventArg.set("spender", spender);
eventArg.set("amount", amountStr);
String eventArgStr = UvmCoreLibs.tojsonstring(eventArg);
UvmCoreLibs.emit("Approved", eventArgStr);
}
}
@Offline
public String approvedBalanceFrom( String arg) {
if ((Storage)this.getStorage() != null) {
Utils utils = new Utils();
UvmArray parsed = utils.parseAtLeastArgs(arg, 2, "argument format error, need format is spenderAddress,authorizerAddress");
String spender = UvmCoreLibs.tostring(parsed.get(1));
String authorizer = UvmCoreLibs.tostring(parsed.get(2));
utils.checkAddress(spender);
utils.checkAddress(authorizer);
Object allowedDataStr = UvmCoreLibs.fast_map_get("allowed", authorizer);
if (allowedDataStr == null) {
return "0";
} else {
UvmJsonModule jsonModule = (UvmJsonModule)UvmCoreLibs.importModule(UvmJsonModule.class, "json");
UvmMap allowedDataTable = (UvmMap)UvmCoreLibs.totable(jsonModule.loads(UvmCoreLibs.tostring(allowedDataStr)));
if (allowedDataTable == null) {
return "0";
} else {
String allowedAmount = (String)allowedDataTable.get(spender);
return allowedAmount == null ? "0" : allowedAmount;
}
}
} else {
return "";
}
}
@Offline
public String allApprovedFromUser( String arg) {
if ((Storage)this.getStorage() != null) {
Utils utils = new Utils();
utils.checkAddress(arg);
Object allowedDataStr = UvmCoreLibs.fast_map_get("allowed", "authorizer");
if (allowedDataStr == null) {
return "{}";
} else {
return UvmCoreLibs.tostring(allowedDataStr);
}
} else {
return "";
}
}
public void pause( String arg) {
Utils utils = new Utils();
utils.checkCallerFrameValid((UvmContract)this);
Storage var10000 = (Storage)this.getStorage();
if (var10000 != null) {
Storage storage = var10000;
String state = storage.getState();
if (state==utils.STOPPED()) {
UvmCoreLibs.error("this contract stopped now, can't pause");
} else if (state==utils.PAUSED()) {
UvmCoreLibs.error("this contract paused now, can't pause");
} else {
utils.checkAdmin(this);
storage.setState(utils.PAUSED());
UvmCoreLibs.emit("Paused", "");
}
}
}
public void resume( String arg) {
Utils utils = new Utils();
utils.checkCallerFrameValid((UvmContract)this);
Storage var10000 = (Storage)this.getStorage();
if (var10000 != null) {
Storage storage = var10000;
String state = storage.getState();
if (state!=utils.PAUSED()) {
UvmCoreLibs.error("this contract not paused now, can't resume");
} else {
utils.checkAdmin(this);
storage.setState(utils.COMMON());
UvmCoreLibs.emit("Resumed", "");
}
}
}
public void stop( String arg) {
Utils utils = new Utils();
utils.checkCallerFrameValid((UvmContract)this);
Storage var10000 = (Storage)this.getStorage();
if (var10000 != null) {
Storage storage = var10000;
String state = storage.getState();
if (state==utils.STOPPED()) {
UvmCoreLibs.error("this contract stopped now, can't stop");
} else if (state==utils.PAUSED()) {
UvmCoreLibs.error("this contract paused now, can't stop");
} else {
utils.checkAdmin(this);
storage.setState(utils.STOPPED());
UvmCoreLibs.emit("Stopped", "");
}
}
}
public void lock( String arg) {
Utils utils = new Utils();
utils.checkState(this);
utils.checkCallerFrameValid((UvmContract)this);
Storage var10000 = (Storage)this.getStorage();
if (var10000 != null) {
Storage storage = var10000;
if (!storage.getAllowLock()) {
UvmCoreLibs.error("this token contract not allow lock balance");
} else {
UvmArray parsed = utils.parseAtLeastArgs(arg, 2, "arg format error, need format is integer_amount,unlockBlockNumber");
String toLockAmount = (String)parsed.get(1);
long unlockBlockNumber = UvmCoreLibs.tointeger(parsed.get(2));
UvmSafeMathModule safemathModule = (UvmSafeMathModule)UvmCoreLibs.importModule(UvmSafeMathModule.class, "safemath");
UvmBigInt bigintToLockAmount = safemathModule.bigint(toLockAmount);
UvmBigInt bigint0 = safemathModule.bigint(0L);
if (toLockAmount != null && !safemathModule.le(bigintToLockAmount, bigint0)) {
if (unlockBlockNumber < UvmCoreLibs.get_header_block_num()) {
UvmCoreLibs.error("to unlock block number can't be earlier than current block number " + UvmCoreLibs.tostring(UvmCoreLibs.get_header_block_num()));
} else {
String fromAddress = utils.getFromAddress();
if (fromAddress!=UvmCoreLibs.caller_address()) {
UvmCoreLibs.error("only common user account can lock balance");
} else {
Object temp = UvmCoreLibs.fast_map_get("users", fromAddress);
if (temp == null) {
UvmCoreLibs.error("your balance is 0");
} else {
UvmBigInt bigintFromBalance = safemathModule.bigint(temp);
if (safemathModule.gt(bigintToLockAmount, bigintFromBalance)) {
UvmCoreLibs.error("you have not enough balance to lock");
} else {
Object lockedAmount = UvmCoreLibs.fast_map_get("lockedAmounts", fromAddress);
if (lockedAmount == null) {
UvmCoreLibs.fast_map_set("lockedAmounts", fromAddress, UvmCoreLibs.tostring(toLockAmount) + "," + UvmCoreLibs.tostring(unlockBlockNumber));
bigintFromBalance = safemathModule.sub(bigintFromBalance, bigintToLockAmount);
UvmCoreLibs.fast_map_set("users", fromAddress, safemathModule.tostring(bigintFromBalance));
UvmCoreLibs.emit("Locked", UvmCoreLibs.tostring(toLockAmount));
} else {
UvmCoreLibs.error("you have locked balance now, before lock again, you need unlock them or use other address to lock");
}
}
}
}
}
} else {
UvmCoreLibs.error("to unlock amount must be positive integer");
}
}
}
}
public void unlock( String arg) {
Utils utils = new Utils();
String fromAddress = utils.getFromAddress();
forceUnlock(fromAddress);
}
public void forceUnlock( String unlockAddress) {
Utils utils = new Utils();
utils.checkState(this);
utils.checkCallerFrameValid((UvmContract)this);
if (this.getStorage().getAllowLock()==false) {
UvmCoreLibs.error("this token contract not allow lock balance");
} else {
Object lockedStr = UvmCoreLibs.fast_map_get("lockedAmounts", unlockAddress);
if (lockedStr == null) {
UvmCoreLibs.error("you have not locked balance");
} else {
UvmArray lockedInfoParsed = utils.parseAtLeastArgs(UvmCoreLibs.tostring(lockedStr), 2, "locked amount info format error");
String lockedAmountStr = UvmCoreLibs.tostring(lockedInfoParsed.get(1));
long canUnlockBlockNumber = UvmCoreLibs.tointeger(lockedInfoParsed.get(2));
if (UvmCoreLibs.get_header_block_num() < canUnlockBlockNumber) {
UvmCoreLibs.error("your locked balance only can be unlock after block #" + UvmCoreLibs.tostring(canUnlockBlockNumber));
return;
}
UvmCoreLibs.fast_map_set("lockedAmounts", unlockAddress, (Object)null);
Object temp = UvmCoreLibs.fast_map_get("users", unlockAddress);
if (temp == null) {
temp = "0";
}
UvmSafeMathModule safemathModule = (UvmSafeMathModule)UvmCoreLibs.importModule(UvmSafeMathModule.class, "safemath");
UvmBigInt bigintFromBalance = safemathModule.bigint(temp);
UvmBigInt bigintLockedAmount = safemathModule.bigint(UvmCoreLibs.tostring(lockedAmountStr));
bigintFromBalance = safemathModule.add(bigintFromBalance, bigintLockedAmount);
UvmCoreLibs.fast_map_set("users", unlockAddress, safemathModule.tostring(bigintFromBalance));
String tempevent = unlockAddress + "," + UvmCoreLibs.tostring(lockedStr);
UvmCoreLibs.emit("Unlocked", tempevent);
}
}
}
@Offline
public String lockedBalanceOf( String owner) {
if ((Storage)this.getStorage() != null) {
Object lockedAmount = UvmCoreLibs.fast_map_get("lockedAmounts", owner);
if (lockedAmount == null) {
return "0,0";
} else {
return UvmCoreLibs.tostring(lockedAmount);
}
} else {
return "";
}
}
}
| 48.744755
| 209
| 0.546051
|
2a2dd76586b0f82bb2802e4a6722a101509383f4
| 11,004
|
/*******************************************************************************
* Copyright (c) 1998, 2013 Oracle and/or its affiliates. All rights reserved.
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License v1.0 and Eclipse Distribution License v. 1.0
* which accompanies this distribution.
* The Eclipse Public License is available at http://www.eclipse.org/legal/epl-v10.html
* and the Eclipse Distribution License is available at
* http://www.eclipse.org/org/documents/edl-v10.php.
*
* Contributors:
* Oracle - initial API and implementation from Oracle TopLink
******************************************************************************/
package org.eclipse.persistence.testing.tests.queries;
import java.util.Vector;
import org.eclipse.persistence.queries.*;
import org.eclipse.persistence.expressions.*;
import org.eclipse.persistence.mappings.*;
import org.eclipse.persistence.testing.framework.*;
import org.eclipse.persistence.testing.models.employee.domain.*;
/**
* <b>Purpose</b>: Test for bug 2782991: Find by Primary Key with
* conforming does Linear Search.
* <b>Responsibilities</b>:
* <ul><li>Find a way to tell if a cache check takes constant or linear time
* relative to the size of the cache.
* <li>For most reads by primary key the cache check should take constant time.
* </ul>
* <p>Cases:
* <ul><li>Existing Object: Should take constant time.
* <li>New Object (new objects not cached): Should take time relative to the
* size of the new objects cache only.
* <li>New Object (new objects cached): Not tested. Should take constant
* time.
* <li>Deleted Object: Should take constant time. Even though the query should
* return null, the cache hit should succeed.
* <li>Not Existing Object: Should take constant time, for if can't find by
* exact primary key the object is not there.
* </ul>
* In the case of find by inexact primary key, the new and not existing cases
* take a linear number of extra calls.
* <p><b>Future testing:</b>
* <ul><li>Set conforming on the descriptor also (regression).
* <li>Set conforming on the descriptor only (regression).
* <li>Test all the other non conforming options, such as check cache by exact
* primary key.
* <li>Test case where no selection criteria is specified, and the first object
* returned happens to be deleted.
* <li>Test case where selection object is specified. (See {@link ConformResultsWithSelectionObjectTest}).
* <li>A true not existing case: the object does not exist on the database either.
* </ul>
* @author Stephen McRitchie
* @since 9.0.4.0
*/
public class ConformResultsWithPrimaryKeyExpressionTest extends ConformResultsInUnitOfWorkTest {
public static final int CASE_NEW = 0;
public static final int CASE_DELETED = 1;
public static final int CASE_EXISTING = 2;
public static final int CASE_NOTEXISTING = 3;
public final int testCase;
public final boolean checkCacheByExactPrimaryKey;
public int expectedGetIdCallCount;
public int actualGetIdCallCount;
Employee selectionObject;
AttributeAccessor overwrittenAccessor;
public ConformResultsWithPrimaryKeyExpressionTest(int testCase, boolean checkCacheByExactPrimaryKey) {
this.testCase = testCase;
this.checkCacheByExactPrimaryKey = checkCacheByExactPrimaryKey;
String modifier = null;
switch (testCase) {
case CASE_NEW:
modifier = "NEW";
break;
case CASE_DELETED:
modifier = "DELETED";
break;
case CASE_EXISTING:
modifier = "EXISTING";
break;
case CASE_NOTEXISTING:
modifier = "NOTEXISTING";
break;
}
if (shouldCheckCacheByExactPrimaryKey()) {
setName("ConformResultsWithExactPrimaryKeyExpressionTest:" + modifier);
} else {
setName("ConformResultsWithInexactPrimaryKeyExpressionTest:" + modifier);
}
}
public void buildConformQuery() {
conformedQuery = new ReadObjectQuery(Employee.class);
ExpressionBuilder emp = new ExpressionBuilder();
Expression exactPrimaryKeyExpression = null;
if (!getSession().getPlatform().isOracle()) {
exactPrimaryKeyExpression = emp.get("id").equal(selectionObject.getId());
} else {
exactPrimaryKeyExpression = emp.get("id").equal("" + selectionObject.getId());
}
if (shouldCheckCacheByExactPrimaryKey()) {
((ReadObjectQuery)conformedQuery).setSelectionCriteria(exactPrimaryKeyExpression);
} else {
Expression inexactPrimaryKeyExpression = exactPrimaryKeyExpression.and(emp.get("firstName").equal(selectionObject.getFirstName()));
((ReadObjectQuery)conformedQuery).setSelectionCriteria(inexactPrimaryKeyExpression);
}
conformedQuery.conformResultsInUnitOfWork();
}
public static Vector buildTests() {
Vector tests = new Vector(4);
tests.add(new ConformResultsWithPrimaryKeyExpressionTest(CASE_DELETED, true));
tests.add(new ConformResultsWithPrimaryKeyExpressionTest(CASE_EXISTING, true));
tests.add(new ConformResultsWithPrimaryKeyExpressionTest(CASE_NEW, true));
tests.add(new ConformResultsWithPrimaryKeyExpressionTest(CASE_NOTEXISTING, true));
tests.add(new ConformResultsWithPrimaryKeyExpressionTest(CASE_DELETED, false));
tests.add(new ConformResultsWithPrimaryKeyExpressionTest(CASE_EXISTING, false));
tests.add(new ConformResultsWithPrimaryKeyExpressionTest(CASE_NEW, false));
tests.add(new ConformResultsWithPrimaryKeyExpressionTest(CASE_NOTEXISTING, false));
return tests;
}
protected Employee findWorstCaseEmployee() {
Vector searchOrder = unitOfWork.getIdentityMapAccessor().getAllFromIdentityMap(null, Employee.class, null, null);
return (Employee)searchOrder.lastElement();
}
/**
* prepareTest method comment.
*/
public void prepareTest() {
ReadAllQuery query = new ReadAllQuery(Employee.class);
Vector employees = (Vector)getSession().executeQuery(query);
for (int i = 0; i < (employees.size() - 1); i++) {
unitOfWork.registerExistingObject(employees.elementAt(i));
}
Employee unregisteredEmployee = (Employee)employees.elementAt(employees.size() - 1);
// Further tests the not exists case when the query goes to the session.
getSession().getIdentityMapAccessor().removeFromIdentityMap(unregisteredEmployee);
int n = employees.size() - 1;
Employee newEmployee = new Employee();
newEmployee.setFirstName("Bobert");
newEmployee.setLastName("Schmit");
newEmployee.setId(new java.math.BigDecimal(45));
unitOfWork.registerNewObject(newEmployee);
Employee registeredEmployee = findWorstCaseEmployee();
switch (testCase) {
case CASE_NEW: {
selectionObject = newEmployee;
if (shouldCheckCacheByExactPrimaryKey()) {
expectedGetIdCallCount = 1;
} else {
expectedGetIdCallCount = n + 1;
}
break;
}
case CASE_DELETED: {
selectionObject = registeredEmployee;
unitOfWork.deleteObject(selectionObject);
if (shouldCheckCacheByExactPrimaryKey()) {
expectedGetIdCallCount = 0;
} else {
// S.M changed from 3 - 4 from session read refactoring. In the
// old code, we would not go to the database if we got a
// cache hit on the session cache. Now we do. Gray area
expectedGetIdCallCount = 3;
}
break;
}
case CASE_EXISTING: {
selectionObject = registeredEmployee;
if (shouldCheckCacheByExactPrimaryKey()) {
expectedGetIdCallCount = 0;
} else {
expectedGetIdCallCount = 1;
}
break;
}
case CASE_NOTEXISTING: {
selectionObject = unregisteredEmployee;
if (shouldCheckCacheByExactPrimaryKey()) {
// S.M. This went from 5 calls to 4, which is good.
// When checking the one new object + registration +
// building clone + building backup clone.
expectedGetIdCallCount = 3;
} else {
expectedGetIdCallCount = n + 4;
}
break;
}
}
}
public void setup() {
// Change how the primary key attribute 'id' in Employee is accessed.
// Now everytime TopLink extracts the primary key from an Employee object it
// will call Employee.getId() reflectively, which will update a count.
DatabaseMapping mapping = getSession().getDescriptor(Employee.class).getMappingForAttributeName("id");
overwrittenAccessor = mapping.getAttributeAccessor();
mapping.setGetMethodName("getId");
mapping.setSetMethodName("setId");
mapping.getAttributeAccessor().initializeAttributes(Employee.class);
super.setup();
}
public void reset() {
DatabaseMapping mapping = getSession().getDescriptor(Employee.class).getMappingForAttributeName("id");
mapping.setAttributeAccessor(overwrittenAccessor);
super.reset();
}
/**
* Override test to count the calls to Employee.getId just for the query.
*/
public void test() {
int initialCount = Employee.getGetIdCallCount();
result = unitOfWork.executeQuery(conformedQuery);
actualGetIdCallCount = Employee.getGetIdCallCount() - initialCount;
unitOfWork.release();
}
/**
* verify method comment.
*/
public void verify() {
if ((result == null) && (testCase != CASE_DELETED)) {
throw new TestErrorException("object existed in unit of work but not returned in query.");
}
if ((result != null) && (testCase == CASE_DELETED)) {
throw new TestErrorException("object was deleted in unit of work but returned in query.");
}
if (actualGetIdCallCount != expectedGetIdCallCount) {
throw new TestErrorException("The performance of find by primary key has changed. Expected calls to getId: " + expectedGetIdCallCount + ". Actual calls: " + actualGetIdCallCount + ". As long as the algorithmic complexity does not change (linear/constant) this should be ok.");
}
}
public boolean shouldCheckCacheByExactPrimaryKey() {
return checkCacheByExactPrimaryKey;
}
}
| 44.550607
| 292
| 0.643402
|
adf259efa5d84a831ff481d0e734e841d7aa91b4
| 2,057
|
package net.minecraft.command.server;
import com.google.gson.JsonParseException;
import java.util.List;
import net.minecraft.command.CommandBase;
import net.minecraft.command.CommandException;
import net.minecraft.command.ICommandSender;
import net.minecraft.command.SyntaxErrorException;
import net.minecraft.command.WrongUsageException;
import net.minecraft.entity.player.EntityPlayerMP;
import net.minecraft.server.MinecraftServer;
import net.minecraft.util.BlockPos;
import net.minecraft.util.ChatComponentProcessor;
import net.minecraft.util.IChatComponent;
import org.apache.commons.lang3.exception.ExceptionUtils;
public class CommandMessageRaw extends CommandBase {
private static final String __OBFID = "CL_00000667";
public boolean isUsernameIndex(String[] var1, int var2) {
return var2 == 0;
}
public String getCommandUsage(ICommandSender var1) {
return "commands.tellraw.usage";
}
public String getCommandName() {
return "tellraw";
}
public int getRequiredPermissionLevel() {
return 2;
}
public void processCommand(ICommandSender var1, String[] var2) throws CommandException {
if (var2.length < 2) {
throw new WrongUsageException("commands.tellraw.usage", new Object[0]);
} else {
EntityPlayerMP var3 = getPlayer(var1, var2[0]);
String var4 = func_180529_a(var2, 1);
try {
IChatComponent var5 = IChatComponent.Serializer.jsonToComponent(var4);
var3.addChatMessage(ChatComponentProcessor.func_179985_a(var1, var5, var3));
} catch (JsonParseException var7) {
Throwable var6 = ExceptionUtils.getRootCause(var7);
throw new SyntaxErrorException("commands.tellraw.jsonException", new Object[]{var6 == null ? "" : var6.getMessage()});
}
}
}
public List addTabCompletionOptions(ICommandSender var1, String[] var2, BlockPos var3) {
return var2.length == 1 ? getListOfStringsMatchingLastWord(var2, MinecraftServer.getServer().getAllUsernames()) : null;
}
}
| 36.087719
| 130
| 0.728245
|
f61f13816a3e16dddbc8c2b8b29c1863782d410a
| 1,033
|
package im.puglisi.simplelist;
import org.bukkit.plugin.Plugin;
import org.bukkit.plugin.PluginManager;
import org.bukkit.plugin.java.JavaPlugin;
/**@author Jason Puglisi
* @version 1.3.0
*/
public class SimpleList extends JavaPlugin {
public static Plugin pex;
public static Plugin sc;
// Plugin enable
public void onEnable() {
PluginManager pm = getServer().getPluginManager();
getLogger().info("v" + getDescription().getVersion() + " enabled");
getCommand("who").setExecutor(new List(this));
getCommand("list").setExecutor(new List(this));
getCommand("players").setExecutor(new List(this));
getCommand("online").setExecutor(new List(this));
pex = pm.getPlugin("PermissionsEx");
sc = pm.getPlugin("SupaChat");
}
// Plugin disable
public void onDisable() {
getLogger().info("v" + getDescription().getVersion() + " disabled");
}
// PermissionsEx Enabled
public static boolean pexEnabled() {
return pex != null;
}
// SupaChat Enabled
public static boolean scEnabled() {
return sc != null;
}
}
| 27.184211
| 70
| 0.71152
|
c9ceaa9a5f85ebb02e350069b26a34803f8fc1b4
| 4,667
|
/*
Copyright 2019 Evan Saulpaugh
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.esaulpaugh.headlong.abi;
import com.esaulpaugh.headlong.abi.util.Utils;
import java.io.Serializable;
import java.nio.ByteBuffer;
import static com.esaulpaugh.headlong.abi.UnitType.UNIT_LENGTH_BYTES;
/**
* Represents a Contract ABI type such as uint256 or decimal. Used to validate, encode, and decode data.
*
* @param <J> this {@link ABIType}'s corresponding Java type
*/
public abstract class ABIType<J> implements Serializable {
static final int TYPE_CODE_BOOLEAN = 0;
static final int TYPE_CODE_BYTE = 1;
static final int TYPE_CODE_INT = 2;
static final int TYPE_CODE_LONG = 3;
static final int TYPE_CODE_BIG_INTEGER = 4;
static final int TYPE_CODE_BIG_DECIMAL = 5;
static final int TYPE_CODE_ARRAY = 6;
static final int TYPE_CODE_TUPLE = 7;
public static final ABIType<?>[] EMPTY_TYPE_ARRAY = new ABIType<?>[0];
final String canonicalType;
final Class<J> clazz;
final boolean dynamic;
private String name = null;
ABIType(String canonicalType, Class<J> clazz, boolean dynamic) {
this.canonicalType = canonicalType; // .intern() to save memory and allow == comparison?
this.clazz = clazz;
this.dynamic = dynamic;
}
public final String getCanonicalType() {
return canonicalType;
}
public final Class<J> clazz() {
return clazz;
}
public final boolean isDynamic() {
return dynamic;
}
public final String getName() {
return name;
}
/* don't expose this; cached (nameless) instances are shared and must be immutable */
final ABIType<J> setName(String name) {
this.name = name;
return this;
}
abstract String arrayClassName();
abstract int typeCode();
abstract int byteLength(Object value);
abstract int byteLengthPacked(Object value);
public abstract int validate(Object value);
abstract void encodeHead(Object value, ByteBuffer dest, int[] offset);
abstract void encodeTail(Object value, ByteBuffer dest);
/**
* Decodes the data at the buffer's current position according to this {@link ABIType}.
*
* @param buffer the buffer containing the encoded data
* @param unitBuffer a buffer of length {@link UnitType#UNIT_LENGTH_BYTES} in which to store intermediate values
* @return the decoded value
*/
abstract J decode(ByteBuffer buffer, byte[] unitBuffer);
public abstract J parseArgument(String s);
void validateClass(Object value) {
// may throw NPE
if(clazz != value.getClass() && !clazz.isAssignableFrom(value.getClass())) {
throw new IllegalArgumentException("class mismatch: "
+ value.getClass().getName()
+ " not assignable to "
+ clazz.getName()
+ " (" + Utils.friendlyClassName(value.getClass()) + " not instanceof " + Utils.friendlyClassName(clazz) + "/" + canonicalType + ")");
}
}
static byte[] newUnitBuffer() {
return new byte[UNIT_LENGTH_BYTES];
}
@Override
public final int hashCode() {
return canonicalType.hashCode();
}
@Override
public final boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
return canonicalType.equals(((ABIType<?>) o).canonicalType);
}
@Override
public final String toString() {
return canonicalType;
}
final void toString(StringBuilder sb) {
switch (typeCode()) {
case TYPE_CODE_ARRAY:
sb.append('[');
((ArrayType<?, ?>) this).elementType.toString(sb);
sb.append(']');
break;
case TYPE_CODE_TUPLE:
sb.append('(');
for(ABIType<?> e : (TupleType) this) {
e.toString(sb);
}
sb.append(')');
break;
default:
sb.append(this);
}
sb.append(' ').append(getName()).append(',');
}
}
| 30.109677
| 154
| 0.636383
|
57d94f03c322c1c4292c630031558f8c1b00fe0f
| 3,795
|
/*
* Copyright 2018 Ryos.io.
*
* 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.ryos.rhino.sdk.users.source;
import static org.hamcrest.CoreMatchers.equalTo;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.core.IsNull.notNullValue;
import io.ryos.rhino.sdk.exceptions.ConfigurationNotFoundException;
import io.ryos.rhino.sdk.exceptions.NoUserFoundException;
import io.ryos.rhino.sdk.users.repositories.Regions;
import java.util.UUID;
import org.junit.Test;
public class FileBasedUserSourceTest {
private static final String CSV_EMPTY_FILE = "classpath:///test_users_empty.csv";
private static final String CSV_FILE = "classpath:///test_users.csv";
private static final int EXPECTED_NUM_USERS = 2;
@Test
public void testGetUsers() {
var fileBasedUserSource = new FileBasedUserSourceImpl(CSV_FILE);
var users = fileBasedUserSource.getUsers();
assertThat(users, notNullValue());
assertThat(users.isEmpty(), equalTo(false));
assertThat(users.size(), equalTo(EXPECTED_NUM_USERS));
}
@Test
public void testGetSingleUserForRegionAndCount() {
var fileBasedUserSource = new FileBasedUserSourceImpl(CSV_FILE);
var users = fileBasedUserSource.getUsers(1, Regions.US);
assertThat(users, notNullValue());
assertThat(users.isEmpty(), equalTo(false));
assertThat(users.size(), equalTo(1));
}
@Test
public void testGetMultipleUserForEUAndExceedingCount() {
var fileBasedUserSource = new FileBasedUserSourceImpl(CSV_FILE);
var users = fileBasedUserSource.getUsers(4, Regions.EU);
assertThat(users, notNullValue());
assertThat(users.isEmpty(), equalTo(false));
assertThat(users.size(), equalTo(1));
}
@Test
public void testGetSingleUserForNonExistingRegion() {
var fileBasedUserSource = new FileBasedUserSourceImpl(CSV_FILE);
var users = fileBasedUserSource.getUsers(1, Regions.AP);
assertThat(users, notNullValue());
assertThat(users.isEmpty(), equalTo(true));
}
@Test(expected = IllegalArgumentException.class)
public void testGetSingleUserForInvalidNumber() {
var fileBasedUserSource = new FileBasedUserSourceImpl(CSV_FILE);
var users = fileBasedUserSource.getUsers(-1, Regions.AP);
assertThat(users, notNullValue());
assertThat(users.isEmpty(), equalTo(true));
}
@Test(expected = NoUserFoundException.class)
public void testGetUsersFromEmptyFile() {
var fileBasedUserSource = new FileBasedUserSourceImpl(CSV_EMPTY_FILE);
fileBasedUserSource.getUsers();
}
@Test(expected = IllegalArgumentException.class)
public void testGetUsersWithInvalidPath() {
var fileBasedUserSource = new FileBasedUserSourceImpl(UUID.randomUUID().toString());
fileBasedUserSource.getUsers();
}
@Test(expected = IllegalArgumentException.class)
public void testGetUsersWithInvalidScheme() {
var fileBasedUserSource =
new FileBasedUserSourceImpl("invalid:///" + UUID.randomUUID().toString());
fileBasedUserSource.getUsers();
}
@Test(expected = ConfigurationNotFoundException.class)
public void testGetUsersWithNonexistingFile() {
var fileBasedUserSource =
new FileBasedUserSourceImpl("file:///" + UUID.randomUUID().toString());
fileBasedUserSource.getUsers();
}
}
| 34.816514
| 88
| 0.751779
|
25168eee66a0f89f48c249a79f872f46ca6c250c
| 675
|
package com.hlogi.wappclone.web;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import com.hlogi.wappclone.databinding.ActivityWappWebBinding;
//TODO: Implement signing in to WApp Web using QR code
public class WAppWebActivity extends AppCompatActivity {
private ActivityWappWebBinding binding;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
binding = ActivityWappWebBinding.inflate(getLayoutInflater());
setContentView(binding.getRoot());
}
@Override
protected void onDestroy() {
super.onDestroy();
binding = null;
}
}
| 25
| 70
| 0.733333
|
c7d1a3659396a2754693b03909e06b7016dfc12f
| 746
|
package com.C4theBomb.datastructures.treesandgraphs;
import java.util.ArrayList;
import java.util.List;
public class MinimalTree {
Node<Integer> root;
public MinimalTree(ArrayList<Integer> list) {
this.root = createMinimalTree(list, 0, list.size() - 1);
}
public Node<Integer> createMinimalTree(List<Integer> list, int startIndex, int endIndex) {
if (endIndex < startIndex) {
return null;
}
int middle = (startIndex + endIndex) / 2;
Node<Integer> root = new Node<>(list.get(middle));
root.conn.put("left", createMinimalTree(list, startIndex, middle - 1));
root.conn.put("right", createMinimalTree(list, middle + 1, endIndex));
return root;
}
}
| 28.692308
| 94
| 0.646113
|
8bc26c78fff7562430f157f4f5ee001decd5633b
| 558
|
package org.example.com.streamDemo;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;
public class FlatMapDemo {
public static void main(String[] args) {
methodTest();
}
static void methodTest() {
List<String> strs = Arrays.asList("Hello", "world", "benny jane");
List<String> res = strs.stream().map(s -> s.split("")).flatMap(Arrays::stream).distinct().collect(Collectors.toList());
System.out.println(res);
}
}
| 27.9
| 127
| 0.673835
|
8c1bce54c1565b8ce92c8914d820b632e4b40d4d
| 2,852
|
/*
* 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 uk.co.objectconnexions.expressiveobjects.viewer.scimpi.dispatcher.view.simple;
import uk.co.objectconnexions.expressiveobjects.viewer.scimpi.dispatcher.AbstractElementProcessor;
import uk.co.objectconnexions.expressiveobjects.viewer.scimpi.dispatcher.context.RequestContext;
import uk.co.objectconnexions.expressiveobjects.viewer.scimpi.dispatcher.context.RequestContext.Scope;
import uk.co.objectconnexions.expressiveobjects.viewer.scimpi.dispatcher.processor.Request;
public class Variable extends AbstractElementProcessor {
@Override
public void process(final Request request) {
final String name = request.getOptionalProperty(NAME);
final String value = request.getOptionalProperty(VALUE);
final String defaultTo = request.getOptionalProperty(DEFAULT);
final String scopeName = request.getOptionalProperty(SCOPE);
final boolean isClear = request.getOptionalProperty("action", "set").equals("clear");
final Scope scope = RequestContext.scope(scopeName, isClear ? Scope.SESSION : Scope.REQUEST);
process(request, name, value, defaultTo, isClear, scope);
}
protected void process(final Request request, final String name, final String value, final String defaultTo, final boolean isClear, final Scope scope) {
request.pushNewBuffer();
request.processUtilCloseTag();
String source = request.popBuffer();
if (isClear) {
request.appendDebug("variable: " + name + " (cleared)");
request.getContext().clearVariable(name, scope);
} else {
if (source.length() == 0 && value != null) {
source = value;
}
if (source.length() == 0) {
source = defaultTo;
}
request.appendDebug(" " + name + " (" + scope + ") set to " + source);
request.getContext().addVariable(name, source, scope);
}
}
@Override
public String getName() {
return "variable";
}
}
| 43.876923
| 156
| 0.693198
|
36db99796a77622ea7d60da381e5efbcc0a8ef02
| 23,105
|
// Copyright 2018 The Bazel Authors. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package build.buildfarm.instance.memory;
import static build.bazel.remote.execution.v2.ExecutionStage.Value.CACHE_CHECK;
import static build.bazel.remote.execution.v2.ExecutionStage.Value.COMPLETED;
import static build.bazel.remote.execution.v2.ExecutionStage.Value.EXECUTING;
import static build.bazel.remote.execution.v2.ExecutionStage.Value.QUEUED;
import static build.bazel.remote.execution.v2.ExecutionStage.Value.UNKNOWN;
import static build.buildfarm.cas.ContentAddressableStorages.casMapDecorator;
import static build.buildfarm.common.Actions.invalidActionVerboseMessage;
import static build.buildfarm.common.Errors.VIOLATION_TYPE_INVALID;
import static build.buildfarm.common.Errors.VIOLATION_TYPE_MISSING;
import static build.buildfarm.instance.AbstractServerInstance.MISSING_ACTION;
import static build.buildfarm.instance.memory.MemoryInstance.TIMEOUT_OUT_OF_BOUNDS;
import static com.google.common.collect.Multimaps.synchronizedSetMultimap;
import static com.google.common.truth.Truth.assertThat;
import static com.google.common.util.concurrent.MoreExecutors.newDirectExecutorService;
import static java.util.concurrent.TimeUnit.NANOSECONDS;
import static org.mockito.Mockito.any;
import static org.mockito.Mockito.atLeastOnce;
import static org.mockito.Mockito.doAnswer;
import static org.mockito.Mockito.doThrow;
import static org.mockito.Mockito.eq;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.verifyZeroInteractions;
import static org.mockito.Mockito.when;
import build.bazel.remote.execution.v2.Action;
import build.bazel.remote.execution.v2.ActionResult;
import build.bazel.remote.execution.v2.Command;
import build.bazel.remote.execution.v2.Digest;
import build.bazel.remote.execution.v2.Directory;
import build.bazel.remote.execution.v2.ExecuteOperationMetadata;
import build.bazel.remote.execution.v2.ExecuteResponse;
import build.bazel.remote.execution.v2.ExecutionPolicy;
import build.bazel.remote.execution.v2.ExecutionStage;
import build.bazel.remote.execution.v2.Platform;
import build.bazel.remote.execution.v2.RequestMetadata;
import build.bazel.remote.execution.v2.ResultsCachePolicy;
import build.buildfarm.common.DigestUtil;
import build.buildfarm.common.Watchdog;
import build.buildfarm.common.Watcher;
import build.buildfarm.instance.Instance.MatchListener;
import build.buildfarm.instance.OperationsMap;
import build.buildfarm.instance.WatchFuture;
import build.buildfarm.v1test.ActionCacheConfig;
import build.buildfarm.v1test.CompletedOperationMetadata;
import build.buildfarm.v1test.DelegateCASConfig;
import build.buildfarm.v1test.MemoryInstanceConfig;
import build.buildfarm.v1test.QueueEntry;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.Iterables;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.google.common.collect.MultimapBuilder;
import com.google.common.collect.SetMultimap;
import com.google.common.util.concurrent.ListenableFuture;
import com.google.longrunning.Operation;
import com.google.protobuf.Any;
import com.google.protobuf.ByteString;
import com.google.protobuf.Duration;
import com.google.protobuf.InvalidProtocolBufferException;
import com.google.protobuf.util.Durations;
import com.google.rpc.Code;
import com.google.rpc.PreconditionFailure;
import com.google.rpc.PreconditionFailure.Violation;
import com.google.rpc.Status;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
import org.mockito.ArgumentCaptor;
import org.mockito.invocation.InvocationOnMock;
import org.mockito.stubbing.Answer;
@RunWith(JUnit4.class)
public class MemoryInstanceTest {
private final DigestUtil DIGEST_UTIL = new DigestUtil(DigestUtil.HashFunction.SHA256);
private final Command simpleCommand = Command.newBuilder().addArguments("true").build();
private final Digest simpleCommandDigest = DIGEST_UTIL.compute(simpleCommand);
private final Action simpleAction =
Action.newBuilder().setCommandDigest(simpleCommandDigest).build();
private final Digest simpleActionDigest = DIGEST_UTIL.compute(simpleAction);
private final Duration MAXIMUM_ACTION_TIMEOUT = Durations.fromSeconds(3600);
private MemoryInstance instance;
private OperationsMap outstandingOperations;
private SetMultimap<String, WatchFuture> watchers;
private ExecutorService watcherService;
private Map<Digest, ByteString> storage;
private List<Worker> workers;
private Map<String, Watchdog> requeuers;
private Map<String, Watchdog> operationTimeoutDelays;
@Before
public void setUp() throws Exception {
outstandingOperations = new MemoryInstance.OutstandingOperations();
watchers =
synchronizedSetMultimap(
MultimapBuilder.hashKeys().hashSetValues(/* expectedValuesPerKey=*/ 1).build());
watcherService = newDirectExecutorService();
MemoryInstanceConfig memoryInstanceConfig =
MemoryInstanceConfig.newBuilder()
.setListOperationsDefaultPageSize(1024)
.setListOperationsMaxPageSize(16384)
.setTreeDefaultPageSize(1024)
.setTreeMaxPageSize(16384)
.setOperationPollTimeout(Durations.fromSeconds(10))
.setOperationCompletedDelay(Durations.fromSeconds(10))
.setDefaultActionTimeout(Durations.fromSeconds(600))
.setMaximumActionTimeout(MAXIMUM_ACTION_TIMEOUT)
.setActionCacheConfig(
ActionCacheConfig.newBuilder()
.setDelegateCas(DelegateCASConfig.getDefaultInstance())
.build())
.build();
storage = Maps.newHashMap();
workers = Lists.newArrayList();
requeuers = Maps.newHashMap();
operationTimeoutDelays = Maps.newHashMap();
instance =
new MemoryInstance(
"memory",
DIGEST_UTIL,
memoryInstanceConfig,
casMapDecorator(storage),
watchers,
watcherService,
outstandingOperations,
workers,
requeuers,
operationTimeoutDelays);
}
@After
public void tearDown() throws Exception {
watcherService.shutdown();
watcherService.awaitTermination(Long.MAX_VALUE, NANOSECONDS);
}
@Test
public void listOperationsForEmptyOutstanding() {
ImmutableList.Builder<Operation> operations = new ImmutableList.Builder<>();
String nextToken =
instance.listOperations(/* pageSize=*/ 1, /* pageToken=*/ "", /* filter=*/ "", operations);
assertThat(nextToken).isEqualTo("");
assertThat(operations.build()).isEmpty();
}
@Test
public void listOperationsForOutstandingOperations() throws InterruptedException {
Operation operation = Operation.newBuilder().setName("test-operation").build();
outstandingOperations.put(operation.getName(), operation);
ImmutableList.Builder<Operation> operations = new ImmutableList.Builder<>();
String nextToken =
instance.listOperations(/* pageSize=*/ 1, /* pageToken=*/ "", /* filter=*/ "", operations);
// we should have reached the end of list
assertThat(nextToken).isEqualTo("");
assertThat(operations.build()).containsExactly(operation);
}
@Test
public void listOperationsLimitsPages() throws InterruptedException {
Operation testOperation1 = Operation.newBuilder().setName("test-operation1").build();
Operation testOperation2 = Operation.newBuilder().setName("test-operation2").build();
outstandingOperations.put(testOperation1.getName(), testOperation1);
outstandingOperations.put(testOperation2.getName(), testOperation2);
ImmutableList.Builder<Operation> operations = new ImmutableList.Builder<>();
String nextToken =
instance.listOperations(/* pageSize=*/ 1, /* pageToken=*/ "", /* filter=*/ "", operations);
// we should not be at the end
assertThat(nextToken).isNotEqualTo("");
assertThat(operations.build().size()).isEqualTo(1);
nextToken =
instance.listOperations(
/* pageSize=*/ 1, /* pageToken=*/ nextToken, /* filter=*/ "", operations);
// we should have reached the end
assertThat(nextToken).isEqualTo("");
assertThat(operations.build()).containsExactly(testOperation1, testOperation2);
}
@Test
public void actionCacheMissResult() throws Exception {
Action action = Action.getDefaultInstance();
assertThat(
instance
.getActionResult(
instance.getDigestUtil().computeActionKey(action),
RequestMetadata.getDefaultInstance())
.get())
.isNull();
}
@Test
public void actionCacheRetrievableByActionKey() throws Exception {
ActionResult result = ActionResult.getDefaultInstance();
storage.put(DIGEST_UTIL.compute(result), result.toByteString());
Action action = Action.getDefaultInstance();
instance.putActionResult(instance.getDigestUtil().computeActionKey(action), result);
assertThat(
instance
.getActionResult(
instance.getDigestUtil().computeActionKey(action),
RequestMetadata.getDefaultInstance())
.get())
.isEqualTo(result);
}
@Test
public void missingOperationIsNotFound() throws InterruptedException {
Watcher watcher = mock(Watcher.class);
doThrow(io.grpc.Status.NOT_FOUND.asRuntimeException()).when(watcher).observe(eq(null));
boolean caughtNotFoundException = false;
try {
instance.watchOperation("does-not-exist", watcher).get();
} catch (ExecutionException e) {
io.grpc.Status status = io.grpc.Status.fromThrowable(e);
if (status.getCode() == io.grpc.Status.Code.NOT_FOUND) {
caughtNotFoundException = true;
}
}
assertThat(caughtNotFoundException).isTrue();
verify(watcher, times(1)).observe(eq(null));
}
@Test
public void watchOperationAddsWatcher() throws InterruptedException {
Operation operation = Operation.newBuilder().setName("my-watched-operation").build();
outstandingOperations.put(operation.getName(), operation);
Watcher watcher = mock(Watcher.class);
instance.watchOperation(operation.getName(), watcher);
verify(watcher, times(1)).observe(eq(operation));
WatchFuture watchFuture = Iterables.getOnlyElement(watchers.get(operation.getName()));
watchFuture.observe(operation);
verify(watcher, times(2)).observe(eq(operation));
}
@Test
public void watchOpRaceLossInvertsTestOnInitial()
throws ExecutionException, InterruptedException {
Operation operation = Operation.newBuilder().setName("my-watched-operation").build();
Operation doneOperation = operation.toBuilder().setDone(true).build();
// as a result of the initial verified test, change the operation to done
Answer<Void> initialAnswer =
new Answer<Void>() {
@Override
public Void answer(InvocationOnMock invocation) throws Throwable {
outstandingOperations.put(operation.getName(), doneOperation);
return null;
}
};
Watcher watcher = mock(Watcher.class);
doAnswer(initialAnswer).when(watcher).observe(eq(operation));
// set for each verification
outstandingOperations.put(operation.getName(), operation);
instance.watchOperation(operation.getName(), watcher).get();
verify(watcher, times(1)).observe(eq(operation));
verify(watcher, times(1)).observe(eq(doneOperation));
}
private class UnwatchFuture extends WatchFuture {
private final String operationName;
UnwatchFuture(String operationName, Watcher observer) {
super(observer);
this.operationName = operationName;
}
@Override
public void unwatch() {
watchers.remove(operationName, this);
}
}
@Test
public void requeueFailOnInvalid() throws InterruptedException, InvalidProtocolBufferException {
// These new operations are invalid as they're missing actions.
Operation queuedOperation = createOperation("missing-action-queued-operation", QUEUED);
outstandingOperations.put(queuedOperation.getName(), queuedOperation);
Watcher watcher = mock(Watcher.class);
watchers.put(queuedOperation.getName(), new UnwatchFuture(queuedOperation.getName(), watcher));
assertThat(instance.requeueOperation(queuedOperation)).isFalse();
ArgumentCaptor<Operation> operationCaptor = ArgumentCaptor.forClass(Operation.class);
verify(watcher, times(1)).observe(operationCaptor.capture());
Operation operation = operationCaptor.getValue();
assertThat(operation.getName()).isEqualTo(queuedOperation.getName());
}
@Test
public void requeueSucceedsOnQueued()
throws InterruptedException, InvalidProtocolBufferException {
storage.put(simpleActionDigest, simpleAction.toByteString());
storage.put(simpleCommandDigest, simpleCommand.toByteString());
Operation queuedOperation = createOperation("my-queued-operation", QUEUED);
outstandingOperations.put(queuedOperation.getName(), queuedOperation);
Watcher watcher = mock(Watcher.class);
watchers.put(queuedOperation.getName(), new UnwatchFuture(queuedOperation.getName(), watcher));
assertThat(instance.requeueOperation(queuedOperation)).isTrue();
verifyZeroInteractions(watcher);
}
@Test
public void requeueFailureNotifiesWatchers() throws Exception {
ExecuteOperationMetadata metadata =
ExecuteOperationMetadata.newBuilder()
.setActionDigest(simpleActionDigest)
.setStage(QUEUED)
.build();
Operation queuedOperation = createOperation("missing-action-operation", metadata);
outstandingOperations.put(queuedOperation.getName(), queuedOperation);
Watcher watcher = mock(Watcher.class);
ListenableFuture<Void> watchFuture =
instance.watchOperation(queuedOperation.getName(), watcher);
assertThat(instance.requeueOperation(queuedOperation)).isFalse();
watchFuture.get();
ArgumentCaptor<Operation> operationCaptor = ArgumentCaptor.forClass(Operation.class);
verify(watcher, atLeastOnce()).observe(operationCaptor.capture());
List<Operation> operations = operationCaptor.getAllValues();
Operation erroredOperation = operations.get(operations.size() - 1);
assertThat(erroredOperation.getDone()).isTrue();
CompletedOperationMetadata completedMetadata =
erroredOperation.getMetadata().unpack(CompletedOperationMetadata.class);
assertThat(completedMetadata.getExecuteOperationMetadata().getStage()).isEqualTo(COMPLETED);
PreconditionFailure preconditionFailure =
PreconditionFailure.newBuilder()
.addViolations(
Violation.newBuilder()
.setType(VIOLATION_TYPE_MISSING)
.setSubject("blobs/" + DigestUtil.toString(simpleActionDigest))
.setDescription(MISSING_ACTION))
.build();
ExecuteResponse executeResponse =
ExecuteResponse.newBuilder()
.setStatus(
Status.newBuilder()
.setCode(Code.FAILED_PRECONDITION.getNumber())
.setMessage(
invalidActionVerboseMessage(simpleActionDigest, preconditionFailure))
.addDetails(Any.pack(preconditionFailure)))
.build();
assertThat(erroredOperation.getResponse().unpack(ExecuteResponse.class))
.isEqualTo(executeResponse);
}
private Operation createOperation(String name, ExecuteOperationMetadata metadata) {
return Operation.newBuilder().setName(name).setMetadata(Any.pack(metadata)).build();
}
private Operation createOperation(String name, ExecutionStage.Value stage) {
return createOperation(
name,
ExecuteOperationMetadata.newBuilder()
.setActionDigest(simpleActionDigest)
.setStage(stage)
.build());
}
private boolean putNovelOperation(ExecutionStage.Value stage) throws InterruptedException {
storage.put(simpleActionDigest, simpleAction.toByteString());
storage.put(simpleCommandDigest, simpleCommand.toByteString());
return instance.putOperation(createOperation("does-not-exist", stage));
}
@Test
public void novelPutUnknownOperationReturnsTrue() throws InterruptedException {
assertThat(putNovelOperation(UNKNOWN)).isTrue();
}
@Test
public void novelPutCacheCheckOperationReturnsTrue() throws InterruptedException {
assertThat(putNovelOperation(CACHE_CHECK)).isTrue();
}
@Test
public void novelPutQueuedOperationReturnsTrue() throws InterruptedException {
assertThat(putNovelOperation(QUEUED)).isTrue();
}
@Test
public void novelPutExecutingOperationReturnsFalse() throws InterruptedException {
assertThat(putNovelOperation(EXECUTING)).isFalse();
}
@Test
public void novelPutCompletedOperationReturnsTrue() throws InterruptedException {
assertThat(putNovelOperation(COMPLETED)).isTrue();
}
private Digest createAction(Action.Builder actionBuilder) {
Command command = Command.newBuilder().addArguments("echo").build();
ByteString commandBlob = command.toByteString();
Digest commandDigest = DIGEST_UTIL.compute(commandBlob);
storage.put(commandDigest, commandBlob);
Directory root = Directory.getDefaultInstance();
Digest rootDigest = DIGEST_UTIL.compute(root);
Action action =
actionBuilder.setCommandDigest(commandDigest).setInputRootDigest(rootDigest).build();
ByteString actionBlob = action.toByteString();
Digest actionDigest = DIGEST_UTIL.compute(actionBlob);
storage.put(actionDigest, actionBlob);
return actionDigest;
}
@Test
public void actionWithExcessiveTimeoutFailsValidation()
throws InterruptedException, InvalidProtocolBufferException {
Duration timeout = Durations.fromSeconds(9000);
Digest actionDigestWithExcessiveTimeout = createAction(Action.newBuilder().setTimeout(timeout));
Watcher watcher = mock(Watcher.class);
IllegalStateException timeoutInvalid = null;
instance.execute(
actionDigestWithExcessiveTimeout,
/* skipCacheLookup=*/ true,
ExecutionPolicy.getDefaultInstance(),
ResultsCachePolicy.getDefaultInstance(),
RequestMetadata.getDefaultInstance(),
watcher);
ArgumentCaptor<Operation> watchCaptor = ArgumentCaptor.forClass(Operation.class);
verify(watcher, times(1)).observe(watchCaptor.capture());
Operation watchOperation = watchCaptor.getValue();
assertThat(watchOperation.getResponse().is(ExecuteResponse.class)).isTrue();
Status status = watchOperation.getResponse().unpack(ExecuteResponse.class).getStatus();
assertThat(status.getCode()).isEqualTo(Code.FAILED_PRECONDITION.getNumber());
assertThat(status.getDetailsCount()).isEqualTo(1);
assertThat(status.getDetails(0).is(PreconditionFailure.class)).isTrue();
PreconditionFailure preconditionFailure =
status.getDetails(0).unpack(PreconditionFailure.class);
assertThat(preconditionFailure.getViolationsList())
.contains(
Violation.newBuilder()
.setType(VIOLATION_TYPE_INVALID)
.setSubject(
Durations.toString(timeout)
+ " > "
+ Durations.toString(MAXIMUM_ACTION_TIMEOUT))
.setDescription(TIMEOUT_OUT_OF_BOUNDS)
.build());
}
@Test
public void actionWithMaximumTimeoutIsValid() throws InterruptedException {
Digest actionDigestWithExcessiveTimeout =
createAction(Action.newBuilder().setTimeout(MAXIMUM_ACTION_TIMEOUT));
Watcher watcher = mock(Watcher.class);
instance.execute(
actionDigestWithExcessiveTimeout,
/* skipCacheLookup=*/ true,
ExecutionPolicy.getDefaultInstance(),
ResultsCachePolicy.getDefaultInstance(),
RequestMetadata.getDefaultInstance(),
watcher);
verify(watcher, atLeastOnce()).observe(any(Operation.class));
}
@Test
public void pollFailsWithNullRequeuer() throws InterruptedException {
Operation operation =
Operation.newBuilder()
.setName("test-operation")
.setMetadata(
Any.pack(ExecuteOperationMetadata.newBuilder().setStage(EXECUTING).build()))
.build();
outstandingOperations.put(operation.getName(), operation);
assertThat(instance.pollOperation(operation.getName(), EXECUTING)).isFalse();
}
@Test
public void matchCancelRemovesFromWorkers() throws InterruptedException {
MatchListener listener = mock(MatchListener.class);
instance.match(Platform.getDefaultInstance(), listener);
ArgumentCaptor<Runnable> onCancelHandlerCaptor = ArgumentCaptor.forClass(Runnable.class);
verify(listener, times(1)).setOnCancelHandler(onCancelHandlerCaptor.capture());
onCancelHandlerCaptor.getValue().run();
assertThat(workers).isEmpty();
}
@Test
public void requeueRemovesRequeuers() throws InterruptedException {
Digest actionDigest = createAction(Action.newBuilder());
instance.execute(
actionDigest,
/* skipCacheLookup=*/ true,
ExecutionPolicy.getDefaultInstance(),
ResultsCachePolicy.getDefaultInstance(),
RequestMetadata.getDefaultInstance(),
(operation) -> {});
MatchListener listener = mock(MatchListener.class);
when(listener.onEntry(any(QueueEntry.class))).thenReturn(true);
instance.match(Platform.getDefaultInstance(), listener);
ArgumentCaptor<QueueEntry> queueEntryCaptor = ArgumentCaptor.forClass(QueueEntry.class);
verify(listener, times(1)).onEntry(queueEntryCaptor.capture());
QueueEntry queueEntry = queueEntryCaptor.getValue();
assertThat(queueEntry).isNotNull();
String operationName = queueEntry.getExecuteEntry().getOperationName();
assertThat(requeuers).isNotEmpty();
Operation queuedOperation = outstandingOperations.get(operationName);
assertThat(instance.isQueued(queuedOperation)).isTrue();
instance.putOperation(queuedOperation); // requeue
assertThat(requeuers).isEmpty();
assertThat(outstandingOperations.get(operationName)).isEqualTo(queuedOperation);
}
}
| 41.932849
| 100
| 0.737676
|
5ac12fd633ad202f8e3c812ca21d05e148318c40
| 1,496
|
package se.fnord.graph.orientdb;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
public class TestOrientURL {
@Test
public void remoteHappyCase() {
final OrientURL remote = OrientURL.create("remote:ap.se:3434/fnord");
assertEquals(new OrientURL("remote", "ap.se:3434", "/", "fnord"), remote);
assertEquals("remote:ap.se:3434/fnord", remote.toString());
}
@Test
public void remoteWithEmptyDbNameShouldBeNull() {
final OrientURL remote = OrientURL.create("remote:ap.se:3434/");
assertEquals(new OrientURL("remote", "ap.se:3434", "/", null), remote);
assertEquals("remote:ap.se:3434/", remote.toString());
}
@Test
public void remoteShouldAddTrailingSlashPath() {
final OrientURL remote = OrientURL.create("remote:ap.se:3434");
assertEquals(new OrientURL("remote", "ap.se:3434", "/", null), remote);
assertEquals("remote:ap.se:3434/", remote.toString());
}
@Test
public void plocalHappyCase() {
final OrientURL remote = OrientURL.create("plocal:/fnord");
assertEquals(new OrientURL("plocal", null, "/", "fnord"), remote);
assertEquals("plocal:/fnord", remote.toString());
}
@Test
public void memoryHappyCase() {
final OrientURL url = OrientURL.create("memory:/fnord");
assertEquals(new OrientURL("memory", null, null, "/fnord"), url);
assertEquals("memory:/fnord", url.toString());
}
}
| 29.92
| 82
| 0.641711
|
9e09570541698e4b4cfc3e9617ef697071ac6363
| 4,464
|
package doWork.file;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;
import java.util.Map.Entry;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.hbase.KeyValue;
import org.apache.hadoop.hbase.regionserver.Store;
import org.apache.hadoop.hbase.regionserver.StoreFile;
import org.apache.hadoop.hbase.regionserver.TimeRangeTracker;
import org.apache.hadoop.hbase.util.Bytes;
import doWork.LCCIndexConstant;
import doWork.LCCIndexGenerator;
import doWork.LCStatInfo;
public class LCIndexWriter {
private final Path basePath;
private TreeMap<byte[], StoreFile.Writer> indexWriters = new TreeMap<byte[], StoreFile.Writer>(
Bytes.BYTES_COMPARATOR);
private List<LCStatInfo> rangeInfoList;
// raw pathName is: /hbase/AAA/xxx/.tmp/BBB,
// writerBaseDir = /hbase/lcc/AAA/.tmp/BBB.lccindex
// file /hbase/lcc/AAA/.tmp/BBB.lccindex/Q1-Q4 indicates a index file for qualifier Q1/Q4
public LCIndexWriter(Store store, Path rawHFile, Map<byte[], Integer> statistic,
List<LCStatInfo> rangeInfoList, TimeRangeTracker tracker) throws IOException {
this.rangeInfoList = rangeInfoList;
if (store.localfs != null) {
basePath = store.getLocalBaseDirByFileName(rawHFile);
if (!store.localfs.exists(basePath)) { // create dir
store.localfs.mkdirs(basePath);
}
} else {
basePath = store.mWinterGetLCCIndexFilePathFromHFilePathInTmp(rawHFile);
}
for (Entry<byte[], Integer> entry : statistic.entrySet()) {
if (entry.getValue() > 0) {
// targetPath = /hbase/lcc/AAA/.tmp/BBB.lccindex/Q1-Q4
Path targetPath = new Path(basePath, Bytes.toString(entry.getKey()));
StoreFile.Writer writer = null;
if (store.localfs != null) {
writer =
store.mWinterCreateWriterInLocalTmp(entry.getValue(), store.family.getCompression(),
false, true, targetPath);
writeStatInfo(store.localfs, basePath, Bytes.toString(entry.getKey()));
} else {
writer =
store.mWinterCreateWriterInTmp(entry.getValue(), store.family.getCompression(),
false, true, targetPath);
writeStatInfo(store.fs, basePath, Bytes.toString(entry.getKey()));
}
if (tracker != null) {
writer.setTimeRangeTracker(tracker);
}
indexWriters.put(entry.getKey(), writer);
} else {
System.out.println("winter ignore cf: " + Bytes.toString(entry.getKey())
+ " bacause it contains " + entry.getValue() + " rows");
}
}
}
private void writeStatInfo(FileSystem fs, Path basePath, String qualifierName) throws IOException {
for (LCStatInfo stat : rangeInfoList) {
if (stat.getName().equals(qualifierName)) {
Path pt = new Path(basePath, qualifierName + LCCIndexConstant.LC_STAT_FILE_SUFFIX);
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(fs.create(pt, true)));
if (stat.isSet()) {
for (long l : stat.getSetValues()) {
bw.write(l + "\n");
}
} else {
for (long l : stat.getCounts()) {
bw.write(l + "\n");
}
}
bw.close();
return;
}
}
}
public Path getBaseDirPath() {
return this.basePath;
}
public void append(KeyValue kv) throws IOException {
byte[] rawQualifier =
Bytes.toBytes(LCCIndexGenerator.mWinterRecoverLCCQualifier_Str(Bytes.toString(kv
.getFamily())));
if (!indexWriters.containsKey(rawQualifier)) {
System.out.println("winter error, try to write indexed value but writer not exists");
} else {
indexWriters.get(rawQualifier).append(kv);
}
}
public void close() throws IOException {
close(false);
}
public void close(boolean print) throws IOException {
for (Entry<byte[], StoreFile.Writer> entry : indexWriters.entrySet()) {
entry.getValue().close();
if (print) {
System.out.println("winter flushing memstore to file: " + entry.getValue().getPath());
}
}
}
// /home/winter/temp/data/lccindex/tpch_lcc/.lctmp/d6c3f4e4ad5149aa8f98ce2bae815460.lccindex/priority
// to
// /home/winter/temp/data/lccindex/tpch_lcc/207525d39bf02b403759fbc13af3c0ab/f/.lccindex/priority/d6c3f4e4ad5149aa8f98ce2bae815460
}
| 36.590164
| 132
| 0.670027
|
8371c51bfa4e56d220eb57cf0444e0aab94714e8
| 1,157
|
private void sendData(HttpServletResponse response, MediaBean mediaBean) throws IOException {
if (logger.isInfoEnabled()) logger.info("sendData[" + mediaBean + "]");
response.setContentLength(mediaBean.getContentLength());
response.setContentType(mediaBean.getContentType());
response.addHeader("Last-Modified", mediaBean.getLastMod());
response.addHeader("Cache-Control", "must-revalidate");
response.addHeader("content-disposition", "attachment, filename=" + (new Date()).getTime() + "_" + mediaBean.getFileName());
byte[] content = mediaBean.getContent();
InputStream is = null;
OutputStream os = null;
try {
os = response.getOutputStream();
is = new ByteArrayInputStream(content);
IOUtils.copy(is, os);
} catch (IOException e) {
logger.error(e, e);
} finally {
if (is != null) try {
is.close();
} catch (IOException e) {
}
if (os != null) try {
os.close();
} catch (IOException e) {
}
}
}
| 41.321429
| 132
| 0.560933
|
55ae7387199dc82f422f69c424418ef01c0e562f
| 2,607
|
package com.fasterxml.jackson.annotation;
import java.util.Arrays;
import java.util.Collections;
import java.util.LinkedHashSet;
import java.util.Set;
/**
* Tests to verify that it is possibly to merge {@link JsonIncludeProperties.Value}
* instances for overrides
*/
public class JsonIncludePropertiesTest extends TestBase
{
@JsonIncludeProperties(value = {"foo", "bar"})
private final static class Bogus
{
}
private final JsonIncludeProperties.Value ALL = JsonIncludeProperties.Value.all();
public void testAll()
{
assertSame(ALL, JsonIncludeProperties.Value.from(null));
assertNull(ALL.getIncluded());
assertEquals(ALL, ALL);
assertEquals("JsonIncludeProperties.Value(included=null)", ALL.toString());
assertEquals(0, ALL.hashCode());
}
public void testFromAnnotation()
{
JsonIncludeProperties.Value v = JsonIncludeProperties.Value.from(Bogus.class.getAnnotation(JsonIncludeProperties.class));
assertNotNull(v);
Set<String> included = v.getIncluded();
assertEquals(2, v.getIncluded().size());
assertEquals(_set("foo", "bar"), included);
assertEquals("JsonIncludeProperties.Value(included=[bar, foo])", v.toString());
assertEquals(v, JsonIncludeProperties.Value.from(Bogus.class.getAnnotation(JsonIncludeProperties.class)));
}
public void testWithOverridesAll() {
JsonIncludeProperties.Value v = JsonIncludeProperties.Value.from(Bogus.class.getAnnotation(JsonIncludeProperties.class));
v = v.withOverrides(ALL);
Set<String> included = v.getIncluded();
assertEquals(2, included.size());
assertEquals(_set("foo", "bar"), included);
}
public void testWithOverridesEmpty() {
JsonIncludeProperties.Value v = JsonIncludeProperties.Value.from(Bogus.class.getAnnotation(JsonIncludeProperties.class));
v = v.withOverrides(new JsonIncludeProperties.Value(Collections.<String>emptySet()));
Set<String> included = v.getIncluded();
assertEquals(0, included.size());
}
public void testWithOverridesMerge() {
JsonIncludeProperties.Value v = JsonIncludeProperties.Value.from(Bogus.class.getAnnotation(JsonIncludeProperties.class));
v = v.withOverrides(new JsonIncludeProperties.Value(_set("foo")));
Set<String> included = v.getIncluded();
assertEquals(1, included.size());
assertEquals(_set("foo"), included);
}
private Set<String> _set(String... args)
{
return new LinkedHashSet<String>(Arrays.asList(args));
}
}
| 37.782609
| 129
| 0.696586
|
75f423b4aee4e800756327ff8145c04dc84afc7f
| 4,532
|
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
package com.azure.resourcemanager.network.implementation;
import com.azure.core.management.exception.ManagementException;
import com.azure.core.management.SubResource;
import com.azure.resourcemanager.network.LoadBalancer;
import com.azure.resourcemanager.network.LoadBalancerBackend;
import com.azure.resourcemanager.network.LoadBalancingRule;
import com.azure.resourcemanager.network.NetworkInterface;
import com.azure.resourcemanager.network.models.BackendAddressPoolInner;
import com.azure.resourcemanager.network.models.HasNetworkInterfaces;
import com.azure.resourcemanager.network.models.NetworkInterfaceIpConfigurationInner;
import com.azure.resourcemanager.resources.fluentcore.arm.ResourceUtils;
import com.azure.resourcemanager.resources.fluentcore.arm.models.implementation.ChildResourceImpl;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import java.util.TreeMap;
/** Implementation for LoadBalancerBackend. */
class LoadBalancerBackendImpl extends ChildResourceImpl<BackendAddressPoolInner, LoadBalancerImpl, LoadBalancer>
implements LoadBalancerBackend,
LoadBalancerBackend.Definition<LoadBalancer.DefinitionStages.WithCreate>,
LoadBalancerBackend.UpdateDefinition<LoadBalancer.Update>,
LoadBalancerBackend.Update {
LoadBalancerBackendImpl(BackendAddressPoolInner inner, LoadBalancerImpl parent) {
super(inner, parent);
}
// Getters
@Override
public Map<String, String> backendNicIPConfigurationNames() {
// This assumes a NIC can only have one IP config associated with the backend of an LB,
// which is correct at the time of this implementation and seems unlikely to ever change
final Map<String, String> ipConfigNames = new TreeMap<>();
if (this.inner().backendIpConfigurations() != null) {
for (NetworkInterfaceIpConfigurationInner inner : this.inner().backendIpConfigurations()) {
String nicId = ResourceUtils.parentResourceIdFromResourceId(inner.id());
String ipConfigName = ResourceUtils.nameFromResourceId(inner.id());
ipConfigNames.put(nicId, ipConfigName);
}
}
return Collections.unmodifiableMap(ipConfigNames);
}
@Override
public Map<String, LoadBalancingRule> loadBalancingRules() {
final Map<String, LoadBalancingRule> rules = new TreeMap<>();
if (this.inner().loadBalancingRules() != null) {
for (SubResource inner : this.inner().loadBalancingRules()) {
String name = ResourceUtils.nameFromResourceId(inner.id());
LoadBalancingRule rule = this.parent().loadBalancingRules().get(name);
if (rule != null) {
rules.put(name, rule);
}
}
}
return Collections.unmodifiableMap(rules);
}
@Override
public String name() {
return this.inner().name();
}
@Override
public Set<String> getVirtualMachineIds() {
Set<String> vmIds = new HashSet<>();
Map<String, String> nicConfigs = this.backendNicIPConfigurationNames();
for (String nicId : nicConfigs.keySet()) {
try {
NetworkInterface nic = this.parent().manager().networkInterfaces().getById(nicId);
if (nic == null || nic.virtualMachineId() == null) {
continue;
} else {
vmIds.add(nic.virtualMachineId());
}
} catch (ManagementException | IllegalArgumentException e) {
continue;
}
}
return vmIds;
}
// Verbs
@Override
public LoadBalancerImpl attach() {
this.parent().withBackend(this);
return this.parent();
}
// Withers
@Override
public LoadBalancerBackendImpl withExistingVirtualMachines(HasNetworkInterfaces... vms) {
return (vms != null) ? this.withExistingVirtualMachines(Arrays.asList(vms)) : this;
}
@Override
public LoadBalancerBackendImpl withExistingVirtualMachines(Collection<HasNetworkInterfaces> vms) {
if (vms != null) {
for (HasNetworkInterfaces vm : vms) {
this.parent().withExistingVirtualMachine(vm, this.name());
}
}
return this;
}
}
| 38.40678
| 112
| 0.677846
|
6135179cbee60eb3859cdaed166f16f6a50a85e0
| 6,085
|
/**************************************************************************
FileSystem.java is part of Titanium4j Mobile 3.0. Copyright 2012 Emitrom LLC
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
**************************************************************************/
package com.emitrom.ti4j.mobile.client.filesystem;
import com.emitrom.ti4j.mobile.client.core.TiFactory;
import com.emitrom.ti4j.mobile.client.core.TiModule;
/**
* The top level filesystem module. the filesystem module is used for reading
* and saving files and directories on the device.
*/
public class FileSystem extends TiModule {
public static final int MODE_APPEND = MODE_APPEND();
public static final int MODE_READ = MODE_READ();
public static final int MODE_WRITE = MODE_WRITE();
private static FileSystem instance = null;
public static FileSystem get() {
if (instance == null) {
instance = new FileSystem();
}
return instance;
}
private FileSystem() {
createPeer();
}
/**
* @return Readonly constant where your application data directory is
* located. this directory should be used to place
* applications-specific files. on iphone, this directory is also
* backed up.
*/
public native String getApplicationDataDirectory() /*-{
var jso = this.@com.emitrom.ti4j.core.client.ProxyObject::getJsObj()();
return jso.applicationDataDirectory;
}-*/;
/**
* @return Readonly constant where your application is located
*/
public native String getApplicationDirectory() /*-{
var jso = this.@com.emitrom.ti4j.core.client.ProxyObject::getJsObj()();
return jso.applicationDirectory;
}-*/;
/**
* @return Readonly platform specific line ending constant
*/
public native String getLineEnding() /*-{
var jso = this.@com.emitrom.ti4j.core.client.ProxyObject::getJsObj()();
return jso.lineEnding;
}-*/;
/**
* @return Readonly constant where your application resources are located
*/
public native String getResourcesDirectory() /*-{
var jso = this.@com.emitrom.ti4j.core.client.ProxyObject::getJsObj()();
return jso.resourcesDirectory;
}-*/;
/**
* @return Readonly path separator constant
*/
public native String getSeparator() /*-{
var jso = this.@com.emitrom.ti4j.core.client.ProxyObject::getJsObj()();
return jso.separator;
}-*/;
/**
* @return Readonly constant where your application can place temporary
* files
*/
public native String getTempDirectory() /*-{
var jso = this.@com.emitrom.ti4j.core.client.ProxyObject::getJsObj()();
return jso.tempDirectory;
}-*/;
public static native File createFile() /*-{
var jso = this.@com.emitrom.ti4j.core.client.ProxyObject::getJsObj()();
var obj = jso.createFile();
var toReturn = @com.emitrom.ti4j.mobile.client.filesystem.File::new(Lcom/google/gwt/core/client/JavaScriptObject;)(obj);
return toReturn;
}-*/;
public native FileStream createFileStream() /*-{
var jso = this.@com.emitrom.ti4j.core.client.ProxyObject::getJsObj()();
var obj = jso.createFileStream();
var toReturn = @com.emitrom.ti4j.mobile.client.filesystem.FileStream::new(Lcom/google/gwt/core/client/JavaScriptObject;)(obj);
return toReturn;
}-*/;
/**
* Create temp file and return a
* {@link com.emitrom.ti4j.mobile.client.filesystem.File}
*/
public native File createTempDirectory() /*-{
var jso = this.@com.emitrom.ti4j.core.client.ProxyObject::getJsObj()();
var obj = jso.createTempDirectory();
var toReturn = @com.emitrom.ti4j.mobile.client.filesystem.File::new(Lcom/google/gwt/core/client/JavaScriptObject;)(obj);
return toReturn;
}-*/;
/**
* Create a temp file and return a
* {@link com.emitrom.ti4j.mobile.client.filesystem.File}
*/
public native File createTempFile() /*-{
var jso = this.@com.emitrom.ti4j.core.client.ProxyObject::getJsObj()();
var obj = jso.createTempFile();
var toReturn = @com.emitrom.ti4j.mobile.client.filesystem.File::new(Lcom/google/gwt/core/client/JavaScriptObject;)(obj);
return toReturn;
}-*/;
/**
* Return a fully formed file path as a
* {@link com.emitrom.ti4j.mobile.client.filesystem.File} object
*
* @param path
* one or more path arguments to form the full path joined
* together with the platform specific path separator. if a
* relative path is passed, the full path will be relative to the
* application resource folder.
*/
public native File getFile(String path) /*-{
var jso = this.@com.emitrom.ti4j.core.client.ProxyObject::getJsObj()();
var obj = jso.getFile(path);
var toReturn = @com.emitrom.ti4j.mobile.client.filesystem.File::new(Lcom/google/gwt/core/client/JavaScriptObject;)(obj);
return toReturn;
}-*/;
public static native boolean isExternalStoragePresent() /*-{
var jso = this.@com.emitrom.ti4j.core.client.ProxyObject::getJsObj()();
return jso.isExternalStoragePresent();
}-*/;
private static native final int MODE_APPEND() /*-{
return Titanium.Filesystem.MODE_APPEND;
}-*/;
private static native final int MODE_READ() /*-{
return Titanium.Filesystem.MODE_READ;
}-*/;
private static native final int MODE_WRITE() /*-{
return Titanium.Filesystem.MODE_WRITE;
}-*/;
@Override
public void createPeer() {
jsObj = TiFactory.createNativeFileSystemModule();
}
}
| 35.377907
| 128
| 0.660477
|
47d4ee2adceddf7d63754b1f457800a0e7b030c8
| 3,146
|
/*
* Copyright (C) 2013 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package interactivespaces.service.comm.serial.xbee.internal;
import interactivespaces.service.comm.serial.xbee.RxIoSampleXBeeFrame;
import interactivespaces.service.comm.serial.xbee.XBeeAddress16;
import interactivespaces.service.comm.serial.xbee.XBeeAddress64;
import java.util.List;
/**
* A response frame for an XBee RX IO Sample.
*
* @author Keith M. Hughes
*/
public class RxIoSampleXBeeFrameImpl implements RxIoSampleXBeeFrame {
/**
* The 64 bit address for the remote radio
*/
private XBeeAddress64 address64;
/**
* The 16 bit address for the remote radio
*/
private XBeeAddress16 address16;
/**
* The receive options.
*/
private int receiveOptions;
/**
* Mask for the digital IO channels.
*/
private int digitalchannelMask;
/**
* Mask for the analog IO channels.
*/
private int analogChannelMask;
/**
* The digital samples.
*/
private int digitalSamples;
/**
* All analog samples that were taken.
*/
private List<Integer> analogSamples;
public RxIoSampleXBeeFrameImpl(XBeeAddress64 address64, XBeeAddress16 address16,
int receiveOptions, int digitalchannelMask, int analogChannelMask, int digitalSamples,
List<Integer> analogSamples) {
this.address64 = address64;
this.address16 = address16;
this.digitalchannelMask = digitalchannelMask;
this.analogChannelMask = analogChannelMask;
this.digitalSamples = digitalSamples;
this.analogSamples = analogSamples;
}
@Override
public XBeeAddress64 getAddress64() {
return address64;
}
@Override
public XBeeAddress16 getAddress16() {
return address16;
}
@Override
public int getReceiveOptions() {
return receiveOptions;
}
@Override
public int getDigitalChannelMask() {
return digitalchannelMask;
}
@Override
public int getAnalogChannelMask() {
return analogChannelMask;
}
@Override
public int getDigitalSamples() {
return digitalSamples;
}
@Override
public boolean getDigitalSample(int sample) {
return (digitalSamples & sample) != 0;
}
@Override
public List<Integer> getAnalogSamples() {
return analogSamples;
}
@Override
public String toString() {
return "RxIoSampleXBeeFrameImpl [address64=" + address64 + ", address16=" + address16
+ ", receiveOptions=" + receiveOptions + ", digitalchannelMask=" + digitalchannelMask
+ ", digitalSamples=" + digitalSamples + ", analogChannelMask=" + analogChannelMask
+ ", analogSamples=" + analogSamples + "]";
}
}
| 24.968254
| 93
| 0.713605
|
e17dadcf3c1b91033c9564fc8e0ad43523d2938a
| 671
|
/* Generated By:JavaCC: Do not edit this line. CanonicalTermParserTreeConstants.java Version 5.0 */
package org.cs3.prolog.connector.internal.cterm.parser;
public interface CanonicalTermParserTreeConstants
{
public int JJTVOID = 0;
public int JJTATOM = 1;
public int JJTNIL = 2;
public int JJTVARIABLE = 3;
public int JJTCOMPOUND = 4;
public int JJTINTEGER = 5;
public int JJTFLOAT = 6;
public int JJTSTRING = 7;
public String[] jjtNodeName = {
"void",
"Atom",
"Nil",
"Variable",
"Compound",
"Integer",
"Float",
"String",
};
}
/* JavaCC - OriginalChecksum=64039172a0cfffc49e33fd5a6f497e92 (do not edit this line) */
| 23.964286
| 99
| 0.687034
|
1ea6e87a538edfa2041e7adbe14be44875be25a8
| 3,443
|
package com.github.javarushcommunity.jrtb.command;
import com.github.javarushcommunity.jrtb.javarushclient.JavaRushGroupClient;
import com.github.javarushcommunity.jrtb.javarushclient.dto.GroupDiscussionInfo;
import com.github.javarushcommunity.jrtb.javarushclient.dto.GroupRequestArgs;
import com.github.javarushcommunity.jrtb.repository.GroupSubService;
import com.github.javarushcommunity.jrtb.repository.entity.GroupSub;
import com.github.javarushcommunity.jrtb.service.SendBotMessageService;
import org.telegram.telegrambots.meta.api.objects.Update;
import java.util.stream.Collectors;
import static com.github.javarushcommunity.jrtb.command.CommandName.ADD_GROUP_SUB;
import static com.github.javarushcommunity.jrtb.command.CommandUtils.getChatId;
import static com.github.javarushcommunity.jrtb.command.CommandUtils.getMessage;
import static java.util.Objects.isNull;
import static org.apache.commons.lang3.StringUtils.SPACE;
import static org.apache.commons.lang3.StringUtils.isNumeric;
/**
* Add Group subscription {@link Command}.
*/
//todo add unit test for the command logic.
public class AddGroupSubCommand implements Command {
private final SendBotMessageService sendBotMessageService;
private final JavaRushGroupClient javaRushGroupClient;
private final GroupSubService groupSubService;
public AddGroupSubCommand(SendBotMessageService sendBotMessageService, JavaRushGroupClient javaRushGroupClient,
GroupSubService groupSubService) {
this.sendBotMessageService = sendBotMessageService;
this.javaRushGroupClient = javaRushGroupClient;
this.groupSubService = groupSubService;
}
@Override
public void execute(Update update) {
if (getMessage(update).equalsIgnoreCase(ADD_GROUP_SUB.getCommandName())) {
sendGroupIdList(getChatId(update));
return;
}
String groupId = getMessage(update).split(SPACE)[1];
String chatId = getChatId(update);
if (isNumeric(groupId)) {
GroupDiscussionInfo groupById = javaRushGroupClient.getGroupById(Integer.parseInt(groupId));
if (isNull(groupById.getId())) {
sendGroupNotFound(chatId, groupId);
}
GroupSub savedGroupSub = groupSubService.save(chatId, groupById);
sendBotMessageService.sendMessage(chatId, "Подписал на группу " + savedGroupSub.getTitle());
} else {
sendGroupNotFound(chatId, groupId);
}
}
private void sendGroupNotFound(String chatId, String groupId) {
String groupNotFoundMessage = "Нет группы с ID = \"%s\"";
sendBotMessageService.sendMessage(chatId, String.format(groupNotFoundMessage, groupId));
}
private void sendGroupIdList(String chatId) {
String groupIds = javaRushGroupClient.getGroupList(GroupRequestArgs.builder().build()).stream()
.map(group -> String.format("%s - %s \n", group.getTitle(), group.getId()))
.collect(Collectors.joining());
String message = "Чтобы подписаться на группу - передай комадну вместе с ID группы. \n" +
"Например: /addGroupSub 16. \n\n" +
"я подготовил список всех групп - выберай какую хочешь :) \n\n" +
"имя группы - ID группы \n\n" +
"%s";
sendBotMessageService.sendMessage(chatId, String.format(message, groupIds));
}
}
| 42.506173
| 115
| 0.717979
|
347caf98d6f6c56cd97e3ee704ebad34ce468e80
| 11,271
|
/*
* 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.
*/
/*
* Created on 15.03.2005
* Last modification G.Seryakova
* Last modified on 15.03.2005
*
* This test parse string byte numbers.
*
* scenario
*/
package org.apache.harmony.test.func.api.java.lang.F_NumberStringParsingTest_02;
import org.apache.harmony.test.func.share.ScenarioTest;
import org.apache.harmony.share.Result;
import java.util.StringTokenizer;
/**
* This test parse string of byte numbers.
*
*/
public class F_NumberStringParsingTest_02 extends ScenarioTest {
private Byte rightByteResult[] = new Byte[10];
private String decNumbers = new String(
"123,85,-56,-34,0,-64,128,-129,-128,127");
private String binaryNumbers = new String(
"1111011,1010101,-111000,-100010,0,-1000000,10000000,-10000001,-10000000,1111111");
private String mixNumbers = new String(
"123,#55,-56,-0x22,0,-0X40,0X80,-129,-0200,0177");
public static void main(String[] args) {
System.exit(new F_NumberStringParsingTest_02().test(args));
}
public F_NumberStringParsingTest_02() {
rightByteResult[0] = new Byte("123");
rightByteResult[1] = new Byte("85");
rightByteResult[2] = new Byte("-56");
rightByteResult[3] = new Byte("-34");
rightByteResult[4] = new Byte("0");
rightByteResult[5] = new Byte("-64");
rightByteResult[8] = new Byte("-128");
rightByteResult[9] = new Byte("127");
}
public int parseDecByteString1() {
Object resultArr[] = new Object[10];
StringBuffer resultString = new StringBuffer();
String next;
StringTokenizer strToken = new StringTokenizer(decNumbers, ",");
int num = 0;
while (strToken.hasMoreTokens()) {
next = strToken.nextToken();
try {
resultArr[num] = new Byte(Byte.parseByte(next));
if (num == 6 || num == 7) {
return fail(num + " byte element failed(must be Exception).");
}
} catch (NumberFormatException e) {
if (num < 6 || num > 7) {
return fail(num + " byte element failed.");
}
resultArr[num] = next.trim();
}
num++;
}
for (int i = 0; i < 10; i++) {
if (i < 6 || i > 7) {
if (!resultArr[i].equals(rightByteResult[i])) {
return fail(i + " byte element failed.");
}
}
}
Byte tmp;
for (int i = 0; i < 10; i++) {
if (Byte.class.isAssignableFrom(resultArr[i].getClass())) {
tmp = (Byte) resultArr[i];
resultString.append(tmp.byteValue());
} else {
resultString.append(resultArr[i]);
}
resultString.append(",");
}
resultString.deleteCharAt(resultString.length() - 1);
if (!decNumbers.equals(resultString.toString())) {
return fail("Strings (int) not equal. Must be " + decNumbers
+ ", but is" + resultString.toString());
}
return Result.PASS;
}
public int parseDecByteString2() {
Object resultArr[] = new Object[10];
StringBuffer resultString = new StringBuffer();
String next;
StringTokenizer strToken = new StringTokenizer(decNumbers, ",");
int num = 0;
while (strToken.hasMoreTokens()) {
next = strToken.nextToken();
try {
resultArr[num] = Byte.valueOf(next);
if (num == 6 || num == 7) {
return fail(num + " byte element failed(must be Exception).");
}
} catch (NumberFormatException e) {
resultArr[num] = next.trim();
if (num < 6 || num > 7) {
return fail(num + " byte element failed.");
}
}
num++;
}
Byte tmp;
for (int i = 0; i < 10; i++) {
if (i < 6 || i > 7) {
tmp = (Byte) resultArr[i];
if (tmp.compareTo(rightByteResult[i]) != 0) {
return fail(i + " byte element failed.");
}
}
}
for (int i = 0; i < 10; i++) {
if (Byte.class.isAssignableFrom(resultArr[i].getClass())) {
tmp = (Byte) resultArr[i];
resultString.append(tmp.intValue());
} else {
resultString.append(resultArr[i]);
}
resultString.append(",");
}
resultString.deleteCharAt(resultString.length() - 1);
if (!decNumbers.equals(resultString.toString())) {
return fail("Strings (int) not equal. Must be " + decNumbers
+ ", but is" + resultString.toString());
}
return Result.PASS;
}
public int parseBinaryByteString1() {
Object resultArr[] = new Object[10];
StringBuffer resultString = new StringBuffer();
String next;
StringTokenizer strToken = new StringTokenizer(binaryNumbers, ",");
int num = 0;
while (strToken.hasMoreTokens()) {
next = strToken.nextToken();
try {
resultArr[num] = new Byte(Byte.parseByte(next, 2));
if (num == 6 || num == 7) {
return fail(num + " byte element failed(must be Exception).");
}
} catch (NumberFormatException e) {
if (num < 6 || num > 7) {
return fail(num + " byte element failed.");
}
resultArr[num] = Integer.valueOf(next, 2).toString();
}
num++;
}
for (int i = 0; i < 10; i++) {
if (i < 6 || i > 7) {
if (!resultArr[i].equals(rightByteResult[i])) {
return fail(i + " byte element failed.");
}
}
}
Byte tmp;
for (int i = 0; i < 10; i++) {
if (Byte.class.isAssignableFrom(resultArr[i].getClass())) {
tmp = (Byte) resultArr[i];
resultString.append(tmp.toString());
} else {
resultString.append(resultArr[i]);
}
resultString.append(",");
}
resultString.deleteCharAt(resultString.length() - 1);
if (!decNumbers.equals(resultString.toString())) {
return fail("Strings (int) not equal. Must be " + decNumbers
+ ", but is" + resultString.toString());
}
return Result.PASS;
}
public int parseBinaryByteString2() {
Object resultArr[] = new Object[10];
StringBuffer resultString = new StringBuffer();
String next;
StringTokenizer strToken = new StringTokenizer(binaryNumbers, ",");
int num = 0;
while (strToken.hasMoreTokens()) {
next = strToken.nextToken();
try {
resultArr[num] = Byte.valueOf(next, 2);
if (num == 6 || num == 7) {
return fail(num + " byte element failed(must be Exception).");
}
} catch (NumberFormatException e) {
resultArr[num] = Integer.valueOf(next, 2).toString();
if (num < 6 || num > 7) {
return fail(num + " byte element failed.");
}
}
num++;
}
for (int i = 0; i < 10; i++) {
if (i < 6 || i > 7) {
if (rightByteResult[i].compareTo(resultArr[i]) != 0) {
return fail(i + " byte element failed.");
}
}
}
Byte tmp;
for (int i = 0; i < 10; i++) {
if (Byte.class.isAssignableFrom(resultArr[i].getClass())) {
tmp = (Byte) resultArr[i];
resultString.append(Byte.toString(tmp.byteValue()));
} else {
resultString.append(resultArr[i]);
}
resultString.append(",");
}
resultString.deleteCharAt(resultString.length() - 1);
if (!decNumbers.equals(resultString.toString())) {
return fail("Strings (int) not equal. Must be " + decNumbers
+ ", but is" + resultString.toString());
}
return Result.PASS;
}
public int parseMixByteString() {
StringBuffer resultString = new StringBuffer();
String next;
StringTokenizer strToken = new StringTokenizer(mixNumbers, ",");
int num = 0;
while (strToken.hasMoreTokens()) {
next = strToken.nextToken();
try {
resultString.append(Byte.decode(next));
if (num == 6 || num == 7) {
return fail(num + " byte element failed(must be Exception).");
}
} catch (NumberFormatException e) {
if (num < 6 || num > 7) {
return fail(num + " byte element failed.");
}
resultString.append(Integer.decode(next));
}
resultString.append(",");
num++;
}
resultString.deleteCharAt(resultString.length() - 1);
if (!decNumbers.equals(resultString.toString())) {
return fail("Strings (int) not equal. Must be " + decNumbers
+ ", but is" + resultString.toString());
}
return Result.PASS;
}
public int test() {
int ind = 0;
if (parseDecByteString1() != Result.PASS) {
fail("parseDecByteString1() failed.");
ind++;
}
if (parseDecByteString2() != Result.PASS) {
fail("parseDecByteString2() failed.");
ind++;
}
if (parseBinaryByteString1() != Result.PASS) {
fail("parseBinaryByteString1() failed.");
ind++;
}
if (parseBinaryByteString2() != Result.PASS) {
fail("parseBinaryByteString2() failed.");
ind++;
}
if (parseMixByteString() != Result.PASS) {
fail("parseMixByteString() failed.");
ind++;
}
if (ind == 0) {
return pass();
} else {
return fail("");
}
}
}
| 33.445104
| 95
| 0.50936
|
0d249f83c1a5001a2144fd98ef0eaaaf2f3910b8
| 2,181
|
package com.gempukku.swccgo.logic.effects;
import com.gempukku.swccgo.game.SwccgGame;
import com.gempukku.swccgo.logic.timing.AbstractStandardEffect;
import com.gempukku.swccgo.logic.timing.Action;
/**
* This class is used as the effect that is responded when a top-level or response action occurs.
* Setting a RespondableEffect via the allowResponses method of AbstractRespondableAction
* is required if any targeting was done by the card. If there is nothing that would ever respond to that action, then
* the child class UnrespondableEffect can set instead with the allowResponses method to avoid unnecessary triggers, etc.
*/
public abstract class RespondableEffect extends AbstractStandardEffect {
private Action _targetingAction;
/**
* Creates a respondable effect
* @param action the action performing this effect
*/
protected RespondableEffect(Action action) {
this(action, action);
}
/**
* Creates a respondable effect
* @param action the action performing this effect
* @param targetingAction the action with the targeting information
*/
protected RespondableEffect(Action action, Action targetingAction) {
super(action);
_targetingAction = targetingAction;
}
@Override
public Type getType() {
return Type.RESPONDABLE_EFFECT;
}
@Override
public String getText(SwccgGame game) {
return _targetingAction.getText();
}
@Override
public boolean isPlayableInFull(SwccgGame game) {
return true;
}
@Override
protected FullEffectResult playEffectReturningResult(SwccgGame game) {
performActionResults(_targetingAction);
return new FullEffectResult(true);
}
/**
* Gets the targeting action.
* @return the targeting action
*/
public Action getTargetingAction() {
return _targetingAction;
}
/**
* This method is called to perform the results part of the action if the action was not canceled.
* @param targetingAction the action with the targeting information
*/
protected abstract void performActionResults(Action targetingAction);
}
| 31.608696
| 121
| 0.715727
|
1e0176aa2964b9f5c6363ce8e6a9eb506d32c101
| 519
|
/*
* This file is part of the constraint solver ACE (AbsCon Essence).
*
* Copyright (c) 2021. All rights reserved.
* Christophe Lecoutre, CRIL, Univ. Artois and CNRS.
*
* Licensed under the MIT License.
* See LICENSE file in the project root for full license information.
*/
import main.Head;
/**
* This is the main class of the constraint solver <code>ACE (AbsCon Essence)</code>
*
* @author Christophe Lecoutre
*/
public class ace {
public static void main(String[] args) {
Head.main(args);
}
}
| 21.625
| 84
| 0.691715
|
da3688c419e9ddc6185e4a7ee069d4aceb8ea16e
| 529
|
package demoa001.model;
import org.noear.solon.validation.annotation.NotBlank;
public class Model {
/**
* 用户名
* @since 1.0
*/
@NotBlank
String name;
/**
* nick name
* @required
* @since 1.0
*/
String nick;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getNick() {
return nick;
}
public void setNick(String nick) {
this.nick = nick;
}
}
| 13.564103
| 54
| 0.529301
|
64affc1b4c173d517031ec7cf08b40571039961e
| 816
|
package sql;
import config.SqlExecuteConfig;
import org.apache.flink.table.api.TableResult;
import org.apache.flink.table.api.bridge.java.StreamTableEnvironment;
public class SqlExecute {
private TableResult tableResult;
private SqlExecuteConfig sqlConfig;
private SqlExecute(SqlExecuteConfig sqlConfig) {
this.sqlConfig = sqlConfig;
this.tableResult = null;
}
public static SqlExecute submit(StreamTableEnvironment tEnv, SqlExecuteConfig sqlConfig) {
SqlExecute executeSql = new SqlExecute(sqlConfig);
executeSql.tableResult = tEnv.executeSql(sqlConfig.sql);
return executeSql;
}
public TableResult getTableResult() {
return this.tableResult;
}
public SqlExecuteConfig getSqlConfig() {
return this.sqlConfig;
}
}
| 27.2
| 94
| 0.724265
|
b3caf8c32bc5d690045d7e69de4a745a514473a4
| 632
|
package com.feitianzhu.fu700.model;
import com.google.gson.annotations.SerializedName;
/**
* Created by dicallc on 2017/9/28 0028.
*/
public class WXModel {
/**
* sign : 8006c15bb9695f7da257de66d8921726
* timestamp : 1506518784
* noncestr : 1wpl1n1q8ekdksbpckpqmh9ftqm7dsld
* partnerid : 1244914402
* prepayid : 1111111111222222222222222223
* package : Sign=WXPay
* appid : wxffd14b94d7649d25
*/
public String sign;
public int timestamp;
public String noncestr;
public String partnerid;
public String prepayid;
@SerializedName("package") public String packageX;
public String appid;
}
| 21.793103
| 52
| 0.732595
|
502c791f3668c1978e3630e066ba9543f4fab75f
| 1,367
|
package net.buildtheearth.terraminusminus.substitutes.net.minecraft.util.math;
public class ChunkPos {
public final int x, z;
public ChunkPos(int x, int z) {
this.x = x;
this.z = z;
}
public ChunkPos(BlockPos block) {
this(blockToCube(block.x), blockToCube(block.z));
}
public int getPosX() {
return this.x;
}
public int getPosZ() {
return this.z;
}
public int getMinBlockX() {
return cubeToMinBlock(this.x);
}
public int getMinBlockZ() {
return cubeToMinBlock(this.z);
}
public int getMaxBlockX() {
return cubeToMaxBlock(this.x);
}
public int getMaxBlockZ() {
return cubeToMaxBlock(this.z);
}
public static int blockToCube(int val) {
return val >> 4;
}
public static int cubeToMinBlock(int val) {
return val << 4;
}
public static int cubeToMaxBlock(int val) {
return cubeToMinBlock(val) + 15;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + x;
result = prime * result + z;
return result;
}
@Override
public boolean equals(Object other) {
if (this == other) return true;
if (other == null) return false;
if(!(other instanceof ChunkPos)) return false;
ChunkPos otherChunkPos = (ChunkPos) other;
if (x != otherChunkPos.x || z != otherChunkPos.z) return false;
return true;
}
}
| 18.472973
| 78
| 0.651061
|
0e441561b7b2dc350d23f7bd4781d2013be406a2
| 6,995
|
package com.github.skjolber.xmlfilter.test;
import java.io.File;
import java.io.FilenameFilter;
import java.io.IOException;
import java.io.StringReader;
import java.net.URL;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Properties;
import javax.xml.parsers.SAXParserFactory;
import org.apache.commons.io.IOUtils;
import org.apache.xerces.jaxp.SAXParserFactoryImpl;
import org.xml.sax.InputSource;
import org.xml.sax.XMLReader;
import org.xmlunit.builder.DiffBuilder;
import org.xmlunit.diff.Diff;
import com.github.skjolber.ddom.stream.sax.XMLConformanceEntityResolver;
import com.github.skjolber.xmlfilter.XmlFilter;
public class XmlFilterRunner {
private XmlFilterPropertiesFactory xmlFilterPropertiesFactory;
private XmlFilterOutputDirectoriesFactory xmlOutputDirectoriesFactory;
private File directory;
private List<XmlFilterOutputDirectory> outputDirectory;
private boolean literal = true;;
public XmlFilterRunner(List<?> nullable, File directory, XmlFilterPropertiesFactory xmlFilterPropertiesFactory, boolean literal) throws Exception {
this.directory = directory;
this.xmlOutputDirectoriesFactory = new XmlFilterOutputDirectoriesFactory(nullable);
this.outputDirectory = xmlOutputDirectoriesFactory.create(directory);
this.xmlFilterPropertiesFactory = xmlFilterPropertiesFactory;
this.literal = literal;
}
public List<File> process(XmlFilter xmlFilter) throws Exception {
List<File> directories = new ArrayList<>();
XmlFilterProperties properties = xmlFilterPropertiesFactory.createInstance(xmlFilter);
if(!properties.isNoop()) {
for(XmlFilterOutputDirectory xmlOutputDirectory : outputDirectory) {
for (XmlFilterInputDirectory xmlInputDirectory : xmlOutputDirectory.getSourceDirectories()) {
if(xmlInputDirectory.matches(properties)) {
processInputOutput(xmlInputDirectory, xmlOutputDirectory, xmlFilter);
directories.add(xmlInputDirectory.getDirectory());
}
}
}
} else {
processDirectories(directory, xmlFilter, directories);
}
return directories;
}
private void processDirectories(File directory, XmlFilter xmlFilter, List<File> directories) {
File[] files = XmlFilterInputDirectory.getFiles(directory);
if(files != null && files.length > 0) {
for(int i = 0; i < files.length; i++) {
String from;
try {
from = IOUtils.toString(files[i].toURI().toURL(), "UTF-8");
} catch (IOException e) {
throw new RuntimeException(e);
}
StringBuilder output = new StringBuilder(1024);
if(!xmlFilter.process(from, output)) {
System.out.println(from);
throw new IllegalArgumentException("Unable to process " + files[i] + " using " + xmlFilter);
}
String to = output.toString();
if(!new String(from).equals(to)) {
printDiff(xmlFilter, XmlFilterPropertiesFactory.noopProperties, files[i], files[i], from, to, from);
throw new IllegalArgumentException("Unexpected noop result for " + files[i]);
}
}
directories.add(directory);
}
File[] subdirectories = directory.listFiles(new FilenameFilter() {
@Override
public boolean accept(File dir, String name) {
return new File(dir, name).isDirectory();
}
});
if(subdirectories != null) {
Arrays.sort(subdirectories);
for(File subdirectory : subdirectories) {
processDirectories(subdirectory, xmlFilter, directories);
}
}
}
protected void processInputOutput(XmlFilterInputDirectory inputDirectory, XmlFilterOutputDirectory outputDirectory, XmlFilter xmlFilter) throws Exception {
File[] filteredFiles = outputDirectory.getFiles();
File[] sourceFiles = inputDirectory.getFiles();
for(int i = 0; i < filteredFiles.length; i++) {
if(!filteredFiles[i].getName().equals(sourceFiles[i].getName())) {
throw new IllegalArgumentException();
}
String from = IOUtils.toString(sourceFiles[i].toURI().toURL(), "UTF-8");
StringBuilder output = new StringBuilder(1024);
if(!xmlFilter.process(from, output)) {
throw new IllegalArgumentException("Unable to process " + sourceFiles[i] + " using " + xmlFilter);
}
String to = output.toString();
String expected = IOUtils.toString(filteredFiles[i].toURI().toURL(), "UTF-8");
if(Character.isWhitespace(to.charAt(0))) {
// assume indent
to = to.substring(1);
}
if(isWellformed(to) != isWellformed(expected)) {
printDiff(xmlFilter, inputDirectory.getProperties(), filteredFiles[i], sourceFiles[i], from, to, expected);
throw new IllegalArgumentException("Unexpected result for " + sourceFiles[i]);
}
if(literal) {
if(!new String(expected).equals(to)) {
printDiff(xmlFilter, inputDirectory.getProperties(), filteredFiles[i], sourceFiles[i], from, to, expected);
throw new IllegalArgumentException("Unexpected result for " + sourceFiles[i]);
}
} else {
Diff d = DiffBuilder.compare(expected).withTest(to).build();
if(d.hasDifferences()) {
printDiff(xmlFilter, inputDirectory.getProperties(), filteredFiles[i], sourceFiles[i], from, to, expected);
throw new IllegalArgumentException("Unexpected result for " + sourceFiles[i]);
}
}
}
}
protected void printDiff(XmlFilter filter, Properties properties, File expectedFile, File original, String from, String to, String expected) {
System.out.println("Processing using: " + filter);
System.out.println("Properties: " + properties);
System.out.println("File input: " + original);
System.out.println("File expected output: " + expectedFile);
System.out.println("From: \n" + from);
System.out.println("Expected:\n" + expected);
System.out.println("Actual:\n" + to);
System.out.println("(size " + expected.length() + " vs " + to.length() + ")");
for(int k = 0; k < Math.min(expected.length(), to.length()); k++) {
if(expected.charAt(k) != to.charAt(k)) {
System.out.println("Diff at " + k + ": " + expected.charAt(k) + " vs + " + to.charAt(k));
break;
}
}
}
public static boolean hasXMLDeclaration(String out) {
return out.startsWith("<?xml ");
}
public static boolean isWellformed(String out) {
SAXParserFactory saxFactory = new SAXParserFactoryImpl();
saxFactory.setNamespaceAware(false);
try {
XMLReader xmlReader = saxFactory.newSAXParser().getXMLReader();
xmlReader.parse(new InputSource(new StringReader(out)));
} catch(Exception e) {
return false;
}
return true;
}
public static boolean isWellformed(final URL base) {
SAXParserFactory saxFactory = new SAXParserFactoryImpl();
saxFactory.setNamespaceAware(false);
try {
XMLReader xmlReader = saxFactory.newSAXParser().getXMLReader();
if(base != null) {
xmlReader.setEntityResolver(new XMLConformanceEntityResolver(base));
}
xmlReader.parse(base.toExternalForm());
} catch(Exception e) {
return false;
}
return true;
}
}
| 34.121951
| 156
| 0.710365
|
6a474d86bfc8132e49c4a3792457365788f54882
| 5,719
|
/*
* Copyright 2014-2017 Rudy De Busscher (www.c4j.be)
*
* 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 be.c4j.ee.security.sso.server.servlet;
import be.c4j.ee.security.config.Debug;
import be.c4j.ee.security.config.OctopusConfig;
import be.c4j.ee.security.exception.OctopusUnexpectedException;
import be.c4j.ee.security.sso.OctopusSSOUser;
import be.c4j.ee.security.sso.server.SSOProducerBean;
import be.c4j.ee.security.sso.server.config.SSOServerConfiguration;
import be.c4j.ee.security.sso.server.servlet.helper.OIDCTokenHelper;
import be.c4j.ee.security.sso.server.store.OIDCStoreData;
import be.c4j.ee.security.sso.server.store.SSOTokenStore;
import com.nimbusds.jwt.SignedJWT;
import com.nimbusds.oauth2.sdk.AbstractRequest;
import com.nimbusds.oauth2.sdk.AuthorizationCode;
import com.nimbusds.oauth2.sdk.ResponseMode;
import com.nimbusds.oauth2.sdk.id.State;
import com.nimbusds.oauth2.sdk.token.AccessToken;
import com.nimbusds.oauth2.sdk.token.BearerAccessToken;
import com.nimbusds.openid.connect.sdk.AuthenticationRequest;
import com.nimbusds.openid.connect.sdk.AuthenticationSuccessResponse;
import com.nimbusds.openid.connect.sdk.claims.IDTokenClaimsSet;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.inject.Inject;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
/**
*
*/
@WebServlet("/octopus/sso/authenticate")
public class AuthenticationServlet extends HttpServlet {
private static final Logger LOGGER = LoggerFactory.getLogger(AuthenticationServlet.class);
@Inject
private SSOServerConfiguration ssoServerConfiguration;
@Inject
private SSOProducerBean ssoProducerBean;
@Inject
private SSOTokenStore tokenStore;
@Inject
private OctopusConfig octopusConfig;
@Inject
private OIDCTokenHelper oidcTokenHelper;
@Override
protected void doGet(HttpServletRequest httpServletRequest, HttpServletResponse response) throws ServletException, IOException {
// We can't inject the OctopusSSOUSer because we then get a Proxy which is stored.
// Bad things will happen ....
OctopusSSOUser ssoUser = ssoProducerBean.getOctopusSSOUser();
AuthenticationRequest request = (AuthenticationRequest) httpServletRequest.getAttribute(AbstractRequest.class.getName());
String clientId = request.getClientID().getValue();
IDTokenClaimsSet claimsSet = oidcTokenHelper.defineIDToken(httpServletRequest, ssoUser, request, clientId);
OIDCStoreData oidcStoreData = new OIDCStoreData(new BearerAccessToken(ssoServerConfiguration.getOIDCTokenLength()
, ssoServerConfiguration.getSSOAccessTokenTimeToLive(), request.getScope()));
AuthorizationCode authorizationCode = null;
AccessToken accessToken = null;
SignedJWT idToken = null;
if (request.getResponseType().impliesCodeFlow()) {
authorizationCode = new AuthorizationCode(ssoServerConfiguration.getOIDCTokenLength());
oidcStoreData.setAuthorizationCode(authorizationCode);
// implicit -> idToken immediately transferred
// code flow -> first code, then exchanged to accessToken/idToken
} else {
if (request.getResponseType().contains("token")) {
// Set the variable so that the Access code is send in this response.
accessToken = oidcStoreData.getAccessToken();
}
idToken = oidcTokenHelper.signIdToken(clientId, claimsSet);
}
oidcStoreData.setIdTokenClaimsSet(claimsSet);
oidcStoreData.setClientId(request.getClientID());
oidcStoreData.setScope(request.getScope());
String userAgent = httpServletRequest.getHeader("User-Agent");
String remoteHost = httpServletRequest.getRemoteAddr();
tokenStore.addLoginFromClient(ssoUser, ssoUser.getCookieToken(), userAgent, remoteHost, oidcStoreData);
State state = request.getState();
AuthenticationSuccessResponse successResponse = new AuthenticationSuccessResponse(request.getRedirectionURI()
, authorizationCode, idToken, accessToken, state, null, ResponseMode.QUERY);
try {
String callback = successResponse.toURI().toString();
showDebugInfo(ssoUser);
response.sendRedirect(callback);
//SecurityUtils.getSubject().logout();// Do not use logout of subject, it wil remove the cookie which we need !
} catch (IOException e) {
// OWASP A6 : Sensitive Data Exposure
throw new OctopusUnexpectedException(e);
} finally {
httpServletRequest.getSession().invalidate(); // Don't keep the session on the SSO server
}
}
private void showDebugInfo(OctopusSSOUser user) {
if (octopusConfig.showDebugFor().contains(Debug.SSO_FLOW)) {
LOGGER.info(String.format("(SSO Server) User %s is authenticated and cookie written if needed.", user.getFullName()));
}
}
}
| 40.274648
| 132
| 0.735094
|
51e7514efb544056a7d1f7f42af31caa7101e6ea
| 2,214
|
/*******************************************************************************
* Copyright 2021 Konexios, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy
* of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
******************************************************************************/
package com.konexios.acn.client.model;
import java.io.Serializable;
import java.util.HashSet;
import java.util.Set;
public class SoftwareReleaseScheduleAutomationModel implements Serializable {
private static final long serialVersionUID = 650773309220706022L;
private AcnDeviceCategory deviceCategory;
private Set<String> objectHids = new HashSet<String>();
private String softwareReleaseHid;
private String userHid;
private Long timeToExpireSeconds;
private String jobName;
public AcnDeviceCategory getDeviceCategory() {
return deviceCategory;
}
public void setDeviceCategory(AcnDeviceCategory deviceCategory) {
this.deviceCategory = deviceCategory;
}
public Set<String> getObjectHids() {
return objectHids;
}
public void setObjectHids(Set<String> objectHids) {
this.objectHids = objectHids;
}
public String getSoftwareReleaseHid() {
return softwareReleaseHid;
}
public void setSoftwareReleaseHid(String softwareReleaseHid) {
this.softwareReleaseHid = softwareReleaseHid;
}
public String getUserHid() {
return userHid;
}
public void setUserHid(String userHid) {
this.userHid = userHid;
}
public Long getTimeToExpireSeconds() {
return timeToExpireSeconds;
}
public void setTimeToExpireSeconds(Long timeToExpireSeconds) {
this.timeToExpireSeconds = timeToExpireSeconds;
}
public String getJobName() {
return jobName;
}
public void setJobName(String jobName) {
this.jobName = jobName;
}
}
| 27.333333
| 80
| 0.714092
|
ac26f8a9438e525464c7b3f582ff2a27895eb8bf
| 886
|
package pruebas;
import dto.Productos;
import java.util.List;
import mybatis.SessionFactory;
import mybatis.mapper.ProductosMapper;
import org.apache.ibatis.session.SqlSession;
public class PruebaQry {
public static void main(String[] args) {
List<Productos> list;
try (SqlSession session = SessionFactory.getSqlSessionFactory().openSession()) {
ProductosMapper mapper = session.getMapper(ProductosMapper.class);
list = mapper.productosQry();//Para obtener la lista
}
if (list != null) {
for (Productos p : list) {
System.out.println(String.format("%-4d%-40s%-10s%8.2f",
p.getIdproducto(), p.getTitulo(),
p.getTipo(), p.getPrecio()));
}
} else {
System.out.println("consulta sin resultados...");
}
}
}
| 30.551724
| 88
| 0.594808
|
2f789730d04fc85fd7bd3e9c71080069bc397c40
| 4,027
|
/*
* 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.calcite.rel.core;
import org.apache.calcite.config.CalciteSystemProperty;
import org.apache.calcite.plan.RelOptCluster;
import org.apache.calcite.plan.RelTraitSet;
import org.apache.calcite.rel.RelNode;
import org.apache.calcite.rel.RelWriter;
import org.apache.calcite.rel.SingleRel;
import org.apache.calcite.rel.type.RelDataType;
import org.apache.calcite.rex.RexNode;
import org.apache.calcite.rex.RexShuttle;
import org.apache.calcite.sql.type.SqlTypeName;
import org.apache.calcite.util.Litmus;
import com.google.common.collect.ImmutableList;
import java.util.List;
import java.util.Objects;
/**
* Relational expression that returns the contents of a relation expression as
* it was at a given time in the past.
*
* <p>For example, if {@code Products} is a temporal table, and
* {@link TableScan}(Products) is a relational operator that returns all
* versions of the contents of the table, then
* {@link Snapshot}(TableScan(Products)) is a relational operator that only
* returns the contents whose versions that overlap with the given specific
* period (i.e. those that started before given period and ended after it).
*/
public abstract class Snapshot extends SingleRel {
//~ Instance fields --------------------------------------------------------
private final RexNode period;
//~ Constructors -----------------------------------------------------------
/**
* Creates a Snapshot.
*
* @param cluster Cluster that this relational expression belongs to
* @param traitSet The traits of this relational expression
* @param input Input relational expression
* @param period Timestamp expression which as the table was at the given
* time in the past
*/
protected Snapshot(RelOptCluster cluster, RelTraitSet traitSet, RelNode input,
RexNode period) {
super(cluster, traitSet, input);
this.period = Objects.requireNonNull(period);
// Too expensive for everyday use:
assert !CalciteSystemProperty.DEBUG.value() || isValid(Litmus.THROW, null);
}
//~ Methods ----------------------------------------------------------------
@Override public final RelNode copy(RelTraitSet traitSet, List<RelNode> inputs) {
return copy(traitSet, sole(inputs), getPeriod());
}
public abstract Snapshot copy(RelTraitSet traitSet, RelNode input, RexNode period);
@Override public List<RexNode> getChildExps() {
return ImmutableList.of(period);
}
public RelNode accept(RexShuttle shuttle) {
RexNode condition = shuttle.apply(this.period);
if (this.period == condition) {
return this;
}
return copy(traitSet, getInput(), condition);
}
@Override public RelWriter explainTerms(RelWriter pw) {
return super.explainTerms(pw)
.item("period", period);
}
public RexNode getPeriod() {
return period;
}
@Override public boolean isValid(Litmus litmus, Context context) {
RelDataType dataType = period.getType();
if (dataType.getSqlTypeName() != SqlTypeName.TIMESTAMP) {
return litmus.fail("The system time period specification expects Timestamp type but is '"
+ dataType.getSqlTypeName() + "'");
}
return litmus.succeed();
}
}
| 36.944954
| 95
| 0.700273
|
bd302556e58fdbdcbe72a441e231617c9185b0b0
| 712
|
package com.tz.redismanager.config.sdk.domain.dto;
import com.tz.redismanager.config.sdk.enm.ConfigTypeEnum;
import lombok.Getter;
import lombok.Setter;
import lombok.ToString;
/**
* <p>配置Context</p>
*
* @author tuanzuo
* @version 1.7.0
* @time 2021-08-07 19:16
**/
@Getter
@Setter
@ToString
public class ConfigContext {
/**
* 主键
*/
private Long id;
/**
* 服务名
*/
private String serviceName;
/**
* 配置类型
* {@link ConfigTypeEnum}
*/
private Integer configType;
/**
* 配置key
*/
private String configKey;
/**
* 配置key名称
*/
private String keyName;
/**
* 配置内容JSON
*/
private String content;
}
| 13.692308
| 57
| 0.577247
|
9a1213e15a677415c9516c6cf44c47e26aec1ac4
| 1,282
|
package jp.gr.java_conf.daisy.ajax_mutator.detector.dom_manipulation_detector;
import java.util.List;
import jp.gr.java_conf.daisy.ajax_mutator.detector.AbstractDetector;
import jp.gr.java_conf.daisy.ajax_mutator.mutatable.DOMCreation;
import org.mozilla.javascript.ast.AstNode;
import org.mozilla.javascript.ast.FunctionCall;
import org.mozilla.javascript.ast.PropertyGet;
/**
* Detector to detect dom creation like document.createElement("tagName")
*
* @author Kazuki Nishiura
*/
public class CreateElementDetector extends AbstractDetector<DOMCreation> {
private static String CREATE_ELEMENT_IDENTIFIER = "createElement";
@Override
public DOMCreation detect(AstNode node) {
return detectFromFunctionCall(node, true);
}
@Override
protected DOMCreation detectFromFunctionCall(FunctionCall functionCall,
AstNode target, List<AstNode> arguments) {
if (functionCall.getTarget() instanceof PropertyGet) {
PropertyGet propertyGet = (PropertyGet) functionCall.getTarget();
if (CREATE_ELEMENT_IDENTIFIER.equals(
propertyGet.getProperty().getIdentifier())) {
return new DOMCreation(functionCall, arguments.get(0));
}
}
return null;
}
}
| 33.736842
| 78
| 0.724649
|
5227bf0b45d33030ebf1e24f9e8c2c64d327b46a
| 1,061
|
package com.unascribed.fabrication.mixin.a_fixes.better_pause_freezing;
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.CallbackInfo;
import com.unascribed.fabrication.client.AtlasViewerScreen;
import com.unascribed.fabrication.support.EligibleIf;
import com.unascribed.fabrication.support.Env;
import com.unascribed.fabrication.support.MixinConfigPlugin;
import net.minecraft.client.MinecraftClient;
import net.minecraft.client.texture.TextureManager;
@Mixin(TextureManager.class)
@EligibleIf(configAvailable="*.better_pause_freezing", envMatches=Env.CLIENT)
public class MixinTextureManager {
@Inject(at=@At("HEAD"), method="tick()V", cancellable=true)
public void tick(CallbackInfo ci) {
if (MixinConfigPlugin.isEnabled("*.better_pause_freezing") && MinecraftClient.getInstance().isPaused() && !(MinecraftClient.getInstance().currentScreen instanceof AtlasViewerScreen)) {
ci.cancel();
}
}
}
| 39.296296
| 186
| 0.816211
|
680a3472339991b40383de051b6e5221c96a0975
| 6,213
|
/**
*/
package edu.kit.ipd.sdq.kamp4aps.model.aPS.StructureRepository.impl;
import edu.kit.ipd.sdq.kamp4aps.model.aPS.ComponentRepository.ComponentRepositoryPackage;
import edu.kit.ipd.sdq.kamp4aps.model.aPS.ComponentRepository.Controller;
import edu.kit.ipd.sdq.kamp4aps.model.aPS.StructureRepository.ControlCabinet;
import edu.kit.ipd.sdq.kamp4aps.model.aPS.StructureRepository.StructureRepositoryPackage;
import org.eclipse.emf.common.notify.Notification;
import org.eclipse.emf.common.notify.NotificationChain;
import org.eclipse.emf.ecore.EClass;
import org.eclipse.emf.ecore.InternalEObject;
import org.eclipse.emf.ecore.impl.ENotificationImpl;
/**
* <!-- begin-user-doc -->
* An implementation of the model object '<em><b>Control Cabinet</b></em>'.
* <!-- end-user-doc -->
* <p>
* The following features are implemented:
* </p>
* <ul>
* <li>{@link edu.kit.ipd.sdq.kamp4aps.model.aPS.StructureRepository.impl.ControlCabinetImpl#getController <em>Controller</em>}</li>
* </ul>
*
* @generated
*/
public class ControlCabinetImpl extends StructureImpl implements ControlCabinet {
/**
* The cached value of the '{@link #getController() <em>Controller</em>}' reference.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #getController()
* @generated
* @ordered
*/
protected Controller controller;
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
protected ControlCabinetImpl() {
super();
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
protected EClass eStaticClass() {
return StructureRepositoryPackage.Literals.CONTROL_CABINET;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public Controller getController() {
if (controller != null && controller.eIsProxy()) {
InternalEObject oldController = (InternalEObject)controller;
controller = (Controller)eResolveProxy(oldController);
if (controller != oldController) {
if (eNotificationRequired())
eNotify(new ENotificationImpl(this, Notification.RESOLVE, StructureRepositoryPackage.CONTROL_CABINET__CONTROLLER, oldController, controller));
}
}
return controller;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public Controller basicGetController() {
return controller;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public NotificationChain basicSetController(Controller newController, NotificationChain msgs) {
Controller oldController = controller;
controller = newController;
if (eNotificationRequired()) {
ENotificationImpl notification = new ENotificationImpl(this, Notification.SET, StructureRepositoryPackage.CONTROL_CABINET__CONTROLLER, oldController, newController);
if (msgs == null) msgs = notification; else msgs.add(notification);
}
return msgs;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public void setController(Controller newController) {
if (newController != controller) {
NotificationChain msgs = null;
if (controller != null)
msgs = ((InternalEObject)controller).eInverseRemove(this, ComponentRepositoryPackage.CONTROLLER__CONTROLLER_OF, Controller.class, msgs);
if (newController != null)
msgs = ((InternalEObject)newController).eInverseAdd(this, ComponentRepositoryPackage.CONTROLLER__CONTROLLER_OF, Controller.class, msgs);
msgs = basicSetController(newController, msgs);
if (msgs != null) msgs.dispatch();
}
else if (eNotificationRequired())
eNotify(new ENotificationImpl(this, Notification.SET, StructureRepositoryPackage.CONTROL_CABINET__CONTROLLER, newController, newController));
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public NotificationChain eInverseAdd(InternalEObject otherEnd, int featureID, NotificationChain msgs) {
switch (featureID) {
case StructureRepositoryPackage.CONTROL_CABINET__CONTROLLER:
if (controller != null)
msgs = ((InternalEObject)controller).eInverseRemove(this, ComponentRepositoryPackage.CONTROLLER__CONTROLLER_OF, Controller.class, msgs);
return basicSetController((Controller)otherEnd, msgs);
}
return super.eInverseAdd(otherEnd, featureID, msgs);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public NotificationChain eInverseRemove(InternalEObject otherEnd, int featureID, NotificationChain msgs) {
switch (featureID) {
case StructureRepositoryPackage.CONTROL_CABINET__CONTROLLER:
return basicSetController(null, msgs);
}
return super.eInverseRemove(otherEnd, featureID, msgs);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public Object eGet(int featureID, boolean resolve, boolean coreType) {
switch (featureID) {
case StructureRepositoryPackage.CONTROL_CABINET__CONTROLLER:
if (resolve) return getController();
return basicGetController();
}
return super.eGet(featureID, resolve, coreType);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public void eSet(int featureID, Object newValue) {
switch (featureID) {
case StructureRepositoryPackage.CONTROL_CABINET__CONTROLLER:
setController((Controller)newValue);
return;
}
super.eSet(featureID, newValue);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public void eUnset(int featureID) {
switch (featureID) {
case StructureRepositoryPackage.CONTROL_CABINET__CONTROLLER:
setController((Controller)null);
return;
}
super.eUnset(featureID);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public boolean eIsSet(int featureID) {
switch (featureID) {
case StructureRepositoryPackage.CONTROL_CABINET__CONTROLLER:
return controller != null;
}
return super.eIsSet(featureID);
}
} //ControlCabinetImpl
| 29.306604
| 169
| 0.680348
|
8fc3c8fd7bc38826eae4ad3dc901689a111b330e
| 3,511
|
package org.jboss.resteasy.test.providers.jaxb.regression;
import org.jboss.resteasy.client.ClientRequest;
import org.jboss.resteasy.client.ClientResponse;
import org.jboss.resteasy.core.Dispatcher;
import org.jboss.resteasy.plugins.providers.jaxb.JAXBContextWrapper;
import org.jboss.resteasy.test.EmbeddedContainer;
import org.junit.AfterClass;
import org.junit.Assert;
import org.junit.BeforeClass;
import org.junit.Test;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.xml.bind.JAXBContext;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import static org.jboss.resteasy.test.TestPortProvider.generateURL;
/**
* @author <a href="mailto:bill@burkecentral.com">Bill Burke</a>
* @version $Revision: 1 $
*/
public class AbstractJAXBClassTest
{
private static Dispatcher dispatcher;
@BeforeClass
public static void before() throws Exception
{
dispatcher = EmbeddedContainer.start().getDispatcher();
dispatcher.getRegistry().addPerRequestResource(SimpleResource.class);
}
@AfterClass
public static void after() throws Exception
{
EmbeddedContainer.stop();
}
@Path("/")
public static class SimpleResource
{
@POST
public void post(Person person)
{
System.out.println("******** HERE ******** " + person.getName() + " " + person.getId());
}
@POST
@Path("kunde")
public void postKunde(Kunde kunde)
{
System.out.println("HERE KUNDE!!!!" + kunde.getNachname());
}
}
private static final String kundeXml = "<?xml version=\"1.0\"?>\n"
+ "<privatkunde>\n"
+ "<nachname>Test</nachname>\n"
+ "<vorname>Theo</vorname>\n"
+ "<seit>2001-01-31T00:00:00+01:00</seit>\n"
+ "<adresse><plz>76133</plz><ort>Karlsruhe</ort><strasse>Moltkestrasse</strasse><hausnr>31</hausnr></adresse>\n"
+ "</privatkunde>";
@Test
public void testSeeAlso() throws Exception
{
JAXBContext ctx = new JAXBContextWrapper(null, Kunde.class);
Kunde kunde = (Kunde) ctx.createUnmarshaller().unmarshal(
new ByteArrayInputStream(kundeXml.getBytes()));
System.out.println("HERE KUNDE!!!!" + kunde.getNachname());
}
/**
* Test for RESTEASY-126
*
* @throws Exception
*/
@Test
public void testPost() throws Exception
{
{
try
{
ClientRequest request = new ClientRequest(generateURL(""));
String s = "<?xml version=\"1.0\"?><person><name>bill</name></person>";
request.body("application/xml", s);
ClientResponse<?> response = request.post();
Assert.assertEquals(204, response.getStatus());
response.releaseConnection();
}
catch (IOException e)
{
throw new RuntimeException(e);
}
{
try
{
ClientRequest request = new ClientRequest(generateURL("/kunde"));
request.body("application/xml", kundeXml);
ClientResponse<?> response = request.post();
Assert.assertEquals(204, response.getStatus());
response.releaseConnection();
}
catch (IOException e)
{
throw new RuntimeException(e);
}
}
}
}
}
| 29.504202
| 124
| 0.588152
|
98693d33606cd90378474b168d8d0c4288a85648
| 8,847
|
/*
* 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.directory.shared.client.api.operations;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
import java.util.UUID;
import java.util.concurrent.TimeUnit;
import org.apache.directory.api.ldap.model.constants.SchemaConstants;
import org.apache.directory.api.ldap.model.csn.CsnFactory;
import org.apache.directory.api.ldap.model.entry.Attribute;
import org.apache.directory.api.ldap.model.entry.DefaultEntry;
import org.apache.directory.api.ldap.model.entry.Entry;
import org.apache.directory.api.ldap.model.entry.ModificationOperation;
import org.apache.directory.api.ldap.model.message.ModifyRequest;
import org.apache.directory.api.ldap.model.message.ModifyRequestImpl;
import org.apache.directory.api.ldap.model.message.ModifyResponse;
import org.apache.directory.api.ldap.model.message.ResultCodeEnum;
import org.apache.directory.api.ldap.model.name.Dn;
import org.apache.directory.api.util.DateUtils;
import org.apache.directory.api.util.Network;
import org.apache.directory.ldap.client.api.LdapNetworkConnection;
import org.apache.directory.ldap.client.api.future.ModifyFuture;
import org.apache.directory.server.annotations.CreateLdapServer;
import org.apache.directory.server.annotations.CreateTransport;
import org.apache.directory.server.core.annotations.ApplyLdifs;
import org.apache.directory.server.core.api.CoreSession;
import org.apache.directory.server.core.integ.AbstractLdapTestUnit;
import org.apache.directory.server.core.integ.FrameworkRunner;
import org.apache.directory.shared.client.api.LdapApiIntegrationUtils;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
/**
* Tests the modify operation
*
* @author <a href="mailto:dev@directory.apache.org">Apache Directory Project</a>
*/
@RunWith(FrameworkRunner.class)
@CreateLdapServer(transports =
{ @CreateTransport(protocol = "LDAP"), @CreateTransport(protocol = "LDAPS") })
@ApplyLdifs(
{
"dn: uid=billyd,ou=users,ou=system",
"objectClass: person",
"objectClass: organizationalPerson",
"objectClass: inetOrgPerson",
"uid: billyd",
"userPassword: secret",
"sn: billyd",
"cn: billyd"
})
public class ClientModifyRequestTest extends AbstractLdapTestUnit
{
private LdapNetworkConnection connection;
private CoreSession session;
@Before
public void setup() throws Exception
{
connection = (LdapNetworkConnection)LdapApiIntegrationUtils.getPooledAdminConnection( getLdapServer() );
session = getLdapServer().getDirectoryService().getAdminSession();
}
@After
public void shutdown() throws Exception
{
LdapApiIntegrationUtils.releasePooledAdminConnection( connection, getLdapServer() );
}
@Test
public void testModify() throws Exception
{
Dn dn = new Dn( "uid=admin,ou=system" );
String expected = String.valueOf( System.currentTimeMillis() );
ModifyRequest modRequest = new ModifyRequestImpl();
modRequest.setName( dn );
modRequest.replace( SchemaConstants.SN_AT, expected );
connection.modify( modRequest );
Entry entry = session.lookup( dn );
String actual = entry.get( SchemaConstants.SN_AT ).getString();
assertEquals( expected, actual );
}
@Test
public void testModifyWithEntry() throws Exception
{
Dn dn = new Dn( "uid=admin,ou=system" );
Entry entry = new DefaultEntry( dn );
String expectedSn = String.valueOf( System.currentTimeMillis() );
String expectedCn = String.valueOf( System.currentTimeMillis() );
entry.add( SchemaConstants.SN_AT, expectedSn );
entry.add( SchemaConstants.CN_AT, expectedCn );
connection.modify( entry, ModificationOperation.REPLACE_ATTRIBUTE );
Entry lookupEntry = session.lookup( dn );
String actualSn = lookupEntry.get( SchemaConstants.SN_AT ).getString();
assertEquals( expectedSn, actualSn );
String actualCn = lookupEntry.get( SchemaConstants.CN_AT ).getString();
assertEquals( expectedCn, actualCn );
}
@Test
public void testModifyReplaceRemove() throws Exception
{
Dn dn = new Dn( "uid=admin,ou=system" );
Entry entry = new DefaultEntry( dn );
entry.add( "givenName", "test" );
connection.modify( entry, ModificationOperation.REPLACE_ATTRIBUTE );
Entry lookupEntry = session.lookup( dn );
String gn = lookupEntry.get( "givenName" ).getString();
assertEquals( "test", gn );
// Now, replace the givenName
ModifyRequest modifyRequest = new ModifyRequestImpl();
modifyRequest.setName( dn );
modifyRequest.replace( "givenName" );
connection.modify( modifyRequest );
lookupEntry = session.lookup( dn );
Attribute giveName = lookupEntry.get( "givenName" );
assertNull( giveName );
}
@Test
public void modifyAsync() throws Exception
{
Dn dn = new Dn( "uid=admin,ou=system" );
String expected = String.valueOf( System.currentTimeMillis() );
ModifyRequest modifyRequest = new ModifyRequestImpl();
modifyRequest.setName( dn );
modifyRequest.replace( SchemaConstants.SN_AT, expected );
assertTrue( session.exists( dn ) );
ModifyFuture modifyFuture = connection.modifyAsync( modifyRequest );
ModifyResponse response = modifyFuture.get( 1000, TimeUnit.MILLISECONDS );
assertNotNull( response );
Entry entry = session.lookup( dn );
String actual = entry.get( SchemaConstants.SN_AT ).getString();
assertEquals( expected, actual );
assertTrue( connection.isAuthenticated() );
assertTrue( session.exists( dn ) );
}
/**
* ApacheDS doesn't allow modifying entryUUID and entryCSN AT
*/
@Test
public void testModifyEntryUUIDAndEntryCSN() throws Exception
{
Dn dn = new Dn( "uid=admin,ou=system" );
ModifyRequest modifyRequest = new ModifyRequestImpl();
modifyRequest.setName( dn );
modifyRequest.replace( SchemaConstants.ENTRY_UUID_AT, UUID.randomUUID().toString() );
ModifyResponse modResp = connection.modify( modifyRequest );
assertEquals( ResultCodeEnum.INSUFFICIENT_ACCESS_RIGHTS, modResp.getLdapResult().getResultCode() );
modifyRequest = new ModifyRequestImpl();
modifyRequest.setName( dn );
modifyRequest.replace( SchemaConstants.ENTRY_CSN_AT, new CsnFactory( 0 ).newInstance().toString() );
// admin can modify the entryCsn
modResp = connection.modify( modifyRequest );
assertEquals( ResultCodeEnum.SUCCESS, modResp.getLdapResult().getResultCode() );
LdapNetworkConnection nonAdminConnection = new LdapNetworkConnection( Network.LOOPBACK_HOSTNAME, getLdapServer().getPort() );
Dn bindDn = new Dn( "uid=billyd,ou=users,ou=system" );
nonAdminConnection.bind( bindDn.getName(), "secret" );
// non-admin user cannot modify entryCSN
modResp = nonAdminConnection.modify( modifyRequest );
assertEquals( ResultCodeEnum.INSUFFICIENT_ACCESS_RIGHTS, modResp.getLdapResult().getResultCode() );
nonAdminConnection.close();
}
/**
* ApacheDS allows modifying the modifiersName and modifyTimestamp operational AT
*/
@Test
public void testModifyModifierNameAndModifyTimestamp() throws Exception
{
Dn dn = new Dn( "uid=admin,ou=system" );
String modifierName = "uid=x,ou=system";
String modifiedTime = DateUtils.getGeneralizedTime();
ModifyRequest modifyRequest = new ModifyRequestImpl();
modifyRequest.setName( dn );
modifyRequest.replace( SchemaConstants.MODIFIERS_NAME_AT, modifierName );
modifyRequest.replace( SchemaConstants.MODIFY_TIMESTAMP_AT, modifiedTime );
ModifyResponse modResp = connection.modify( modifyRequest );
assertEquals( ResultCodeEnum.SUCCESS, modResp.getLdapResult().getResultCode() );
Entry loadedEntry = connection.lookup( dn.getName(), "+" );
assertEquals( modifierName, loadedEntry.get( SchemaConstants.MODIFIERS_NAME_AT ).getString() );
assertEquals( modifiedTime, loadedEntry.get( SchemaConstants.MODIFY_TIMESTAMP_AT ).getString() );
}
}
| 33.511364
| 129
| 0.74805
|
bf38a0a9ae96f4a87a05aac6432ceee9e23ab622
| 203
|
package ch.uzh.ifi.hase.soprafs22.rest.dto;
import lombok.Getter;
import lombok.Setter;
@Getter
@Setter
public class LobbyStartDTO {
private String hostToken;
private Boolean roundStarted;
}
| 14.5
| 43
| 0.763547
|
4dea438460192b3fd8f47f8877a4a1180f7e2516
| 7,733
|
package it.unibz.inf.ontop.test.sparql11;
import com.google.common.collect.ImmutableSet;
import it.unibz.inf.ontop.test.sparql.ManifestTestUtils;
import it.unibz.inf.ontop.test.sparql.MemoryOntopTestCase;
import org.eclipse.rdf4j.query.Dataset;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;
import java.util.Collection;
/**
* Test of SPARQL 1.1 compliance
*/
@RunWith(Parameterized.class)
public class MemorySPARQL11QueryTest extends MemoryOntopTestCase {
/* List of UNSUPPORTED QUERIES */
private static final String aggregatesManifest = "http://www.w3.org/2009/sparql/docs/tests/data-sparql11/aggregates/manifest#";
private static final String bindManifest = "http://www.w3.org/2009/sparql/docs/tests/data-sparql11/bind/manifest#";
private static final String bindingsManifest = "http://www.w3.org/2009/sparql/docs/tests/data-sparql11/bindings/manifest#";
private static final String functionsManifest = "http://www.w3.org/2009/sparql/docs/tests/data-sparql11/functions/manifest#";
private static final String constructManifest = "http://www.w3.org/2009/sparql/docs/tests/data-sparql11/construct/manifest#";
private static final String csvTscResManifest = "http://www.w3.org/2009/sparql/docs/tests/data-sparql11/csv-tsv-res/manifest#";
private static final String groupingManifest = "http://www.w3.org/2009/sparql/docs/tests/data-sparql11/grouping/manifest#";
private static final String negationManifest = "http://www.w3.org/2009/sparql/docs/tests/data-sparql11/negation/manifest#";
private static final String existsManifest = "http://www.w3.org/2009/sparql/docs/tests/data-sparql11/exists/manifest#";
private static final String projectExpressionManifest = "http://www.w3.org/2009/sparql/docs/tests/data-sparql11/project-expression/manifest#";
private static final String propertyPathManifest = "http://www.w3.org/2009/sparql/docs/tests/data-sparql11/property-path/manifest#";
private static final String subqueryManifest = "http://www.w3.org/2009/sparql/docs/tests/data-sparql11/subquery/manifest#";
private static final String serviceManifest = "http://www.w3.org/2009/sparql/docs/tests/data-sparql11/service/manifest#";
private static ImmutableSet<String> IGNORE = ImmutableSet.of(
/* AGGREGATES */
// TODO: support GROUP_CONCAT
aggregatesManifest + "agg-groupconcat-01",
aggregatesManifest + "agg-groupconcat-02",
aggregatesManifest + "agg-groupconcat-03",
// TODO: support IF
aggregatesManifest + "agg-err-02",
/* BINDINGS
*/
// TODO: fix it (UNDEF involves the notion of COMPATIBILITY when joining)
bindingsManifest + "values8",
// TODO: fix it (UNDEF involves the notion of COMPATIBILITY when joining)
bindingsManifest + "values5",
/* FUNCTIONS*/
//bnode not supported in SPARQL transformation
functionsManifest + "bnode01",
functionsManifest + "bnode02",
// the SI does not preserve the original timezone
functionsManifest + "hours",
// the SI does not preserve the original timezone
functionsManifest + "day",
//not supported in SPARQL transformation
functionsManifest + "if01",
functionsManifest + "if02",
functionsManifest + "in01",
functionsManifest + "in02",
functionsManifest + "iri01",
//not supported in H2 transformation
functionsManifest + "md5-01",
functionsManifest + "md5-02",
//The SI does not support IRIs as ORDER BY conditions
functionsManifest + "plus-1",
//The SI does not support IRIs as ORDER BY conditions
functionsManifest + "plus-2",
//SHA1 is not supported in H2
functionsManifest + "sha1-01",
functionsManifest + "sha1-02",
//SHA512 is not supported in H2
functionsManifest + "sha512-01",
functionsManifest + "sha512-02",
//TODO: fix it
functionsManifest + "strafter02",
//TODO: fix it
functionsManifest + "strbefore02",
//not supported in SPARQL transformation
functionsManifest + "strdt01",
functionsManifest + "strdt02",
functionsManifest + "strdt03",
functionsManifest + "strlang01",
functionsManifest + "strlang02",
functionsManifest + "strlang03",
//not supported in SPARQL transformation
functionsManifest + "timezone",
//TZ is not supported in H2
functionsManifest + "tz",
/* CONSTRUCT not supported yet*/
//Projection cannot be cast to Reduced in rdf4j
constructManifest + "constructwhere01",
constructManifest + "constructwhere02",
constructManifest + "constructwhere03",
//problem importing dataset
constructManifest + "constructwhere04",
/* CSV */
// Sorting by IRI is not supported by the SI
csvTscResManifest + "tsv01",
// Sorting by IRI is not supported by the SI
csvTscResManifest + "tsv02",
//different format for number and not supported custom datatype
csvTscResManifest + "tsv03",
/* GROUPING */
// TODO: fix
groupingManifest + "group01",
// Multi-typed COALESCE as grouping condition TODO: support it
groupingManifest + "group04",
// TODO: fix
groupingManifest + "group05",
/* NEGATION
not supported yet */
negationManifest + "subset-by-exclusion-nex-1",
negationManifest + "temporal-proximity-by-exclusion-nex-1",
negationManifest + "subset-01",
negationManifest + "subset-02",
negationManifest + "set-equals-1",
negationManifest + "subset-03",
negationManifest + "exists-01",
negationManifest + "exists-02",
/* EXISTS
not supported yet */
existsManifest + "exists01",
existsManifest + "exists02",
existsManifest + "exists03",
existsManifest + "exists04",
existsManifest + "exists05",
/* PROPERTY PATH*/
// Not supported: ArbitraryLengthPath
propertyPathManifest + "pp02",
//wrong result, unexpected binding
propertyPathManifest + "pp06",
// Not supported: ArbitraryLengthPath
propertyPathManifest + "pp12",
propertyPathManifest + "pp14",
propertyPathManifest + "pp16",
propertyPathManifest + "pp21",
propertyPathManifest + "pp23",
propertyPathManifest + "pp25",
//Not supported: ZeroLengthPath
propertyPathManifest + "pp28a",
// Not supported: ArbitraryLengthPath
propertyPathManifest + "pp34",
propertyPathManifest + "pp35",
propertyPathManifest + "pp36",
propertyPathManifest + "pp37",
/* SERVICE
not supported yet */
serviceManifest + "service1",
//no loading of the dataset
serviceManifest + "service2",
serviceManifest + "service3",
serviceManifest + "service4a",
serviceManifest + "service5",
//no loading of the dataset
serviceManifest + "service6",
serviceManifest + "service7",
/* SUBQUERY
*/
//Quad translated as a triple. TODO: fix it
subqueryManifest + "subquery02",
//Quad translated as a triple. TODO: fix it
subqueryManifest + "subquery04",
// EXISTS is not supported yet
subqueryManifest + "subquery10",
//ORDER BY IRI (for supported by the SI)
subqueryManifest + "subquery11",
//unbound variable: Var TODO: fix it
subqueryManifest + "subquery12",
//ORDER BY IRI (for supported by the SI)
subqueryManifest + "subquery13",
//missing results (TODO: fix)
subqueryManifest + "subquery14"
);
public MemorySPARQL11QueryTest(String testIRI, String name, String queryFileURL, String resultFileURL, Dataset dataSet,
boolean laxCardinality, boolean checkOrder, ImmutableSet<String> ignoredTests) {
super(testIRI, name, queryFileURL, resultFileURL, dataSet, laxCardinality, checkOrder, ignoredTests);
}
@Parameterized.Parameters(name="{1}")
public static Collection<Object[]> parameters() throws Exception {
return ManifestTestUtils.parametersFromSuperManifest(
"/testcases-dawg-sparql-1.1/manifest-all.ttl",
IGNORE);
}
}
| 34.522321
| 143
| 0.726626
|
7953beaf6659151b5d0760f73562425f8116d67c
| 282
|
package com.gitee.qdbp.jdbc.test.model;
import com.gitee.qdbp.able.model.reusable.ExtraData;
/**
* 选项
*
* @author zhh
* @version 180514
*/
public class RoleOptions extends ExtraData {
/** 版本序列号 **/
private static final long serialVersionUID = 1L;
}
| 16.588235
| 53
| 0.648936
|
3e8abb22e53bca5539c351ddf01f31c033709f4c
| 6,973
|
/*
* The MIT License
*
* Copyright 2017 Leif Lindbäck <leifl@kth.se>.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package se.kth.iv1351.bankjdbc.view;
import java.util.List;
import java.util.Scanner;
import se.kth.iv1351.bankjdbc.controller.Controller;
import se.kth.iv1351.bankjdbc.model.Instrument;
import se.kth.iv1351.bankjdbc.model.InstrumentDTO;
/**
* Reads and interprets user commands. This command interpreter is blocking, the user
* interface does not react to user input while a command is being executed.
*/
public class BlockingInterpreter {
private static final String PROMPT = "> ";
private final Scanner console = new Scanner(System.in);
private Controller ctrl;
private boolean keepReceivingCmds = false;
/**
* Creates a new instance that will use the specified controller for all operations.
*
* @param ctrl The controller used by this instance.
*/
public BlockingInterpreter(Controller ctrl) {
this.ctrl = ctrl;
}
/**
* Stops the commend interpreter.
*/
public void stop() {
keepReceivingCmds = false;
}
/**
* Interprets and performs user commands. This method will not return until the
* UI has been stopped. The UI is stopped either when the user gives the
* "quit" command, or when the method <code>stop()</code> is called.
*/
public void handleCmds() {
keepReceivingCmds = true;
while (keepReceivingCmds) {
try {
CmdLine cmdLine = new CmdLine(readNextLine());
switch (cmdLine.getCmd()) {
case HELP:
for (Command command : Command.values()) {
if (command == Command.ILLEGAL_COMMAND) {
continue;
}
System.out.println(command.toString().toLowerCase());
}
break;
case QUIT:
keepReceivingCmds = false;
break;
case LIST:
List<? extends InstrumentDTO> allInstruments = null;
if (cmdLine.getParameter(0).equals(""))
allInstruments = ctrl.getAllInstruments();
for (InstrumentDTO instrument : allInstruments) {
System.out.println("type: " + instrument.getType() + ", "
+ "brand: " + instrument.getBrand() + ", "
+ "cost/month: " + instrument.getMonthlyPrice()
);
}
break;
case RENT:
ctrl.rent(Integer.parseInt(cmdLine.getParameter(0)),
cmdLine.getParameter(1).toUpperCase(), cmdLine.getParameter(2).toUpperCase());
break;
case RETURN:
List<? extends Instrument> studentInstruments = null;
int studentId = -1;
if (cmdLine.getParameter(0).equals("")) {
System.out.println("ERROR\tSPECIFY STUDENT USING STUDENT ID AFTER 'RETURN'");
} else {
studentId = Integer.parseInt(cmdLine.getParameter(0));
studentInstruments = ctrl.getInstrumentsForStudent(studentId);
}
int counter = 1;
for (Instrument instrument : studentInstruments) {
System.out.println("[" + counter + "]\t" + instrument.getType()
+ ",\t" + instrument.getBrand()
+ ",\t" + instrument.getMonthlyPrice()
);
counter++;
}
if(counter == 1){
System.out.println("STUDENT DOES NOT HAVE ANY RENTALS CURRENTLY");
break;
}
int choice = 0;
System.out.println("[" + counter + "]\tNone");
try { choice = Integer.parseInt(console.nextLine()); }
catch(Exception e) {
System.out.println("INVALID INPUT");
}
switch(choice){
case 1:
ctrl.returnInstrument(studentId, studentInstruments.get(0));
studentInstruments.remove(0);
break;
case 2:
if(counter == 2){
break;
} else {
ctrl.returnInstrument(studentId, studentInstruments.get(1));
studentInstruments.remove(1);
}
break;
default:
System.out.println("NO INSTRUMENT RETURNED");
}
break;
default:
System.out.println("illegal command");
}
} catch (Exception e) {
System.out.println("Operation failed");
System.out.println(e.getMessage());
e.printStackTrace();
}
}
}
private String readNextLine() {
System.out.print(PROMPT);
return console.nextLine();
}
}
| 42.779141
| 115
| 0.492041
|
0a6f5fcc4893730c355042b58589115323c6700b
| 431
|
package br.com.armange.codeless.reflection.klass;
public class ClassValue {
private final Class<?> value;
private final Exception exception;
public ClassValue(final Class<?> value, final Exception exception) {
this.value = value;
this.exception = exception;
}
public Object getValue() {
return value;
}
public Exception getException() {
return exception;
}
}
| 21.55
| 72
| 0.645012
|
a86881a4166cdcfc13fe54330aaec2eecc6f4180
| 4,025
|
/**
* @author krvsingh
*/
package connectors.qc.notifier.restclient.model;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.net.URISyntaxException;
import java.util.Properties;
import java.util.logging.Level;
import java.util.logging.Logger;
import connectors.qc.notifier.restclient.commons.ClassUtils;
import connectors.qc.notifier.restclient.commons.StringUtils;
public class ConnectionEntity {
private static final Logger LOG = Logger.getLogger(ConnectionEntity.class
.getName());
private String url = "";
private String domain = "";
private String project = "";
private String username = "";
private String password = "";
public ConnectionEntity() {
// load from properties file
loadGlobals();
// override by system ENV
loadLocals();
}
public ConnectionEntity(String propFilePath) {
// load from properties file
getPropertiesFromFile(propFilePath);
// override by system ENV
loadLocals();
}
private void loadGlobals() {
String file = null;
try {
file = ClassUtils.getJarDir(this.getClass()) + "/"
+ ConnectionConstants.DEFAULT_TD_PROPERTY_FILE;
} catch (URISyntaxException e1) {
LOG.log(Level.WARNING,
"Error Loading Global Connection Property File : ", e1);
file = null;
}
getPropertiesFromFile(file);
}
private void loadLocals() {
LOG.fine("Attempting to read System Properties ..");
// set URL
String urlstr = "";
try {
urlstr = System.getProperty(ConnectionConstants.PROPERTY_TD_URL);
} catch (Exception e) {
LOG.log(Level.WARNING, "Property : "
+ ConnectionConstants.PROPERTY_TD_URL
+ " Undefined or Null. System Defaults will be used.");
}
if (StringUtils.isDefined(urlstr)) {
url = urlstr;
} else {
if (StringUtils.isNotDefined(url)) {
url = ConnectionConstants.DEFAULT_TD_URL;
}
}
// set domain
String domainstr = System
.getProperty(ConnectionConstants.PROPERTY_TD_DOMAIN);
if (StringUtils.isDefined(domainstr)) {
domain = domainstr;
}
// set Project
String projectstr = System
.getProperty(ConnectionConstants.PROPERTY_TD_PROJECT);
if (StringUtils.isDefined(projectstr)) {
project = projectstr;
}
// set Username
String user = System.getProperty(ConnectionConstants.PROPERTY_TD_USER);
if (StringUtils.isDefined(user)) {
username = user;
}
// set Password
String pwd = System
.getProperty(ConnectionConstants.PROPERTY_TD_PASSWORD);
if (StringUtils.isDefined(pwd)) {
password = pwd;
}
}
private void getPropertiesFromFile(String file) {
if (file != null) {
Properties properties = new Properties();
try {
FileInputStream inputStream = new FileInputStream(
new File(file));
LOG.fine(String.format(
"Reading Global connection Properties File : %s", file));
properties.load(inputStream);
inputStream.close();
} catch (IOException e) {
LOG.warning(String
.format("Connection Properties File \"%s\" NOT FOUND. Will read connection parameters from System",
file));
return;
}
try {
setProperties(properties);
} catch (Exception e) {
LOG.log(Level.WARNING, "", e);
}
}
}
private void setProperties(Properties properties) {
url = properties.getProperty(ConnectionConstants.PROPERTY_TD_URL);
domain = properties.getProperty(ConnectionConstants.PROPERTY_TD_DOMAIN);
project = properties
.getProperty(ConnectionConstants.PROPERTY_TD_PROJECT);
username = properties.getProperty(ConnectionConstants.PROPERTY_TD_USER);
password = properties
.getProperty(ConnectionConstants.PROPERTY_TD_PASSWORD);
// export System user to environment if read from file
System.setProperty(ConnectionConstants.PROPERTY_TD_USER, username);
}
public String getUrl() {
return url;
}
public String getDomain() {
return domain;
}
public String getProject() {
return project;
}
public String getUsername() {
return username;
}
public String getPassword() {
return password;
}
}
| 23.265896
| 105
| 0.712795
|
9dcf94ba881928a85f3cece34f6401eced7e6066
| 11,182
|
/*
*
* 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.bookkeeper.util;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.SortedSet;
import java.util.TreeSet;
import org.apache.zookeeper.KeeperException;
import org.apache.zookeeper.KeeperException.NoNodeException;
import org.apache.zookeeper.WatchedEvent;
import org.apache.zookeeper.Watcher;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
/**
* Test the subtree cache.
*/
public class SubTreeCacheTest {
class TestTreeProvider implements SubTreeCache.TreeProvider {
class Node {
Watcher watcher = null;
public Map<String, Node> children = new HashMap<>();
}
final Node root = new Node();
Node getNode(String path) throws KeeperException {
String[] pathSegments = path.split("/");
Node cur = root;
for (String segment : pathSegments) {
if (segment.length() == 0) {
continue; // ignore leading empty one for leading /
}
if (cur.children.containsKey(segment)) {
cur = cur.children.get(segment);
} else {
throw KeeperException.create(KeeperException.Code.NONODE);
}
}
return cur;
}
@Override
public List<String> getChildren(
String path, Watcher watcher) throws InterruptedException, KeeperException {
Node node = getNode(path);
/* Enforce only one live watch per node */
Assert.assertTrue(null == node.watcher);
node.watcher = watcher;
return new ArrayList<String>(node.children.keySet());
}
public void createNode(String path) throws KeeperException {
String[] segments = path.split("/");
if (segments.length == 0) {
throw KeeperException.create(KeeperException.Code.NONODE);
}
String child = segments[segments.length - 1];
String[] parentSegments = Arrays.copyOfRange(segments, 0, segments.length - 1);
Node parent = getNode(String.join("/", parentSegments));
if (parent.children.containsKey(child)) {
throw KeeperException.create(KeeperException.Code.NODEEXISTS);
} else {
parent.children.put(child, new Node());
if (null != parent.watcher) {
parent.watcher.process(
new WatchedEvent(
Watcher.Event.EventType.NodeCreated,
Watcher.Event.KeeperState.SyncConnected,
path));
parent.watcher = null;
}
}
}
public void removeNode(String path) throws KeeperException {
String[] segments = path.split("/");
if (segments.length == 0) {
throw KeeperException.create(KeeperException.Code.NONODE);
}
String child = segments[segments.length - 1];
String[] parentSegments = Arrays.copyOfRange(segments, 0, segments.length - 1);
String parentPath = String.join("/", parentSegments);
Node parent = getNode(parentPath);
if (!parent.children.containsKey(child)) {
throw KeeperException.create(KeeperException.Code.NONODE);
} else {
Node cNode = parent.children.get(child);
if (!cNode.children.isEmpty()) {
throw KeeperException.create(KeeperException.Code.NOTEMPTY);
} else {
if (null != cNode.watcher) {
cNode.watcher.process(
new WatchedEvent(
Watcher.Event.EventType.NodeChildrenChanged,
Watcher.Event.KeeperState.SyncConnected,
path));
cNode.watcher = null;
}
if (null != parent.watcher) {
parent.watcher.process(
new WatchedEvent(
Watcher.Event.EventType.NodeDeleted,
Watcher.Event.KeeperState.SyncConnected,
parentPath));
parent.watcher = null;
}
parent.children.remove(child);
}
}
}
}
TestTreeProvider tree = new TestTreeProvider();
SubTreeCache cache = new SubTreeCache(tree);
class TestWatch implements Watcher {
boolean fired = false;
@Override
public void process(WatchedEvent event) {
fired = true;
}
public boolean getFired() {
return fired;
}
}
TestWatch setWatch() {
TestWatch watch = new TestWatch();
cache.registerWatcher(watch);
return watch;
}
void assertFired(TestWatch watch) {
Assert.assertTrue(watch.getFired());
}
void assertNotFired(TestWatch watch) {
Assert.assertFalse(watch.getFired());
}
class TestWatchGuard extends TestWatch implements AutoCloseable {
SubTreeCache.WatchGuard guard;
void setGuard(SubTreeCache.WatchGuard guard) {
this.guard = guard;
}
@Override
public void close() throws Exception {
guard.close();
}
}
TestWatchGuard setWatchWithGuard() {
TestWatchGuard watch = new TestWatchGuard();
watch.setGuard(cache.registerWatcherWithGuard(watch));
return watch;
}
void readAssertChildren(String path, String[] children) throws KeeperException, InterruptedException {
SortedSet<String> shouldBe = new TreeSet<String>(Arrays.asList(children));
List<String> returned = cache.getChildren(path);
SortedSet<String> is = new TreeSet<String>(returned);
returned.clear(); // trip up implementations which return an internal reference
Assert.assertEquals(shouldBe, is);
}
@Before
public void setUp() throws Exception {
String[] preCreate =
{"/a"
, "/a/a"
, "/a/a/a"
, "/a/a/b"
, "/a/b"
, "/a/c"
, "/b"
, "/b/a"
};
for (String path : preCreate) {
tree.createNode(path);
}
}
//@Test
public void testNoUpdate() throws Exception {
TestWatch watch = setWatch();
readAssertChildren("/a/a", new String[]{"a", "b"});
assertNotFired(watch);
}
//@Test
public void testSingleCreate() throws Exception {
TestWatch watch = setWatch();
readAssertChildren("/a/a", new String[]{"a", "b"});
tree.createNode("/a/a/c");
assertFired(watch);
}
//@Test
public void testSingleRemoval() throws Exception {
TestWatch watch = setWatch();
readAssertChildren("/a/a", new String[]{"a", "b"});
tree.removeNode("/a/a/b");
assertFired(watch);
}
//@Test
public void testCancelation() throws Exception {
TestWatch watch = setWatch();
readAssertChildren("/a/a", new String[]{"a", "b"});
cache.cancelWatcher(watch);
tree.createNode("/a/a/c");
assertNotFired(watch);
}
//@Test
public void testGuardCancelation() throws Exception {
TestWatch watch;
try (TestWatchGuard guard = setWatchWithGuard()) {
readAssertChildren("/a/a", new String[]{"a", "b"});
watch = guard;
}
tree.createNode("/a/a/c");
assertNotFired(watch);
}
//@Test
public void testGuardCancelationExceptional() throws Exception {
TestWatch watch = null;
try (TestWatchGuard guard = setWatchWithGuard()) {
watch = guard;
readAssertChildren("/z/a", new String[]{});
} catch (Exception e) {
}
tree.createNode("/a/a/c");
assertNotFired(watch);
}
//@Test
public void testDuplicateWatch() throws Exception {
try (TestWatchGuard watch = setWatchWithGuard()) {
readAssertChildren("/a/a", new String[]{"a", "b"});
}
try (TestWatchGuard watch = setWatchWithGuard()) {
readAssertChildren("/a/a", new String[]{"a", "b"});
assertNotFired(watch);
tree.createNode("/a/a/e");
assertFired(watch);
}
}
//@Test(expected = NoNodeException.class)
public void testNoNode() throws Exception {
try (TestWatchGuard watch = setWatchWithGuard()) {
readAssertChildren("/z/a", new String[]{});
}
}
//@Test
public void testRemoveEmptyNode() throws Exception {
try (TestWatchGuard watch = setWatchWithGuard()) {
readAssertChildren("/a/a/a", new String[]{});
tree.removeNode("/a/a/a");
assertFired(watch);
}
}
//@Test
public void doubleWatch() throws Exception {
try (TestWatchGuard watch1 = setWatchWithGuard()) {
readAssertChildren("/a/a", new String[]{"a", "b"});
try (TestWatchGuard watch2 = setWatchWithGuard()) {
tree.createNode("/a/a/e");
assertFired(watch1);
readAssertChildren("/a/b", new String[]{});
tree.createNode("/a/b/e");
assertFired(watch2);
}
}
}
//@Test
public void sequentialWatch() throws Exception {
try (TestWatchGuard watch = setWatchWithGuard()) {
readAssertChildren("/a/a", new String[]{"a", "b"});
tree.removeNode("/a/a/a");
assertFired(watch);
}
try (TestWatchGuard watch = setWatchWithGuard()) {
readAssertChildren("/a/a", new String[]{"b"});
tree.removeNode("/a/a/b");
assertFired(watch);
}
}
}
| 34.195719
| 106
| 0.549812
|
208626d13baabb1d02e65822b70376f3b6d2fbaf
| 6,354
|
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package erp.mod;
import erp.mod.cfg.db.SDbCompanyBranchEntity;
import erp.mod.cfg.db.SDbCountry;
import erp.mod.cfg.db.SDbCurrency;
import erp.mod.cfg.db.SDbFunctionalArea;
import erp.mod.cfg.db.SDbLanguage;
import erp.mod.cfg.db.SDbShift;
import erp.mod.cfg.form.SFormFunctionalArea;
import erp.mod.cfg.view.SViewFunctionalArea;
import javax.swing.JMenu;
import sa.lib.SLibConsts;
import sa.lib.db.SDbConsts;
import sa.lib.db.SDbRegistry;
import sa.lib.grid.SGridPaneView;
import sa.lib.gui.SGuiCatalogueSettings;
import sa.lib.gui.SGuiClient;
import sa.lib.gui.SGuiForm;
import sa.lib.gui.SGuiModule;
import sa.lib.gui.SGuiOptionPicker;
import sa.lib.gui.SGuiParams;
import sa.lib.gui.SGuiReport;
/**
*
* @author Juan Barajas, Claudio Peña, Sergio Flores
*/
public class SModuleCfg extends SGuiModule {
private SFormFunctionalArea moFunctionalsAreas;
public SModuleCfg(SGuiClient client) {
super(client, SModConsts.MOD_CFG_N, SLibConsts.UNDEFINED);
moModuleIcon = miClient.getImageIcon(mnModuleType);
}
@Override
public JMenu[] getMenus() {
throw new UnsupportedOperationException("Not supported yet.");
}
@Override
public SDbRegistry getRegistry(final int type, final SGuiParams params) {
SDbRegistry registry = null;
switch (type) {
case SModConsts.CFGU_CUR:
registry = new SDbCurrency();
break;
case SModConsts.CFGU_LAN:
registry = new SDbLanguage();
break;
case SModConsts.CFGU_COB_ENT:
registry = new SDbCompanyBranchEntity();
break;
case SModConsts.CFGU_FUNC:
registry = new SDbFunctionalArea();
break;
case SModConsts.CFGU_SHIFT:
registry = new SDbShift();
break;
case SModConsts.LOCU_CTY:
registry = new SDbCountry();
break;
default:
miClient.showMsgBoxError(SLibConsts.ERR_MSG_OPTION_UNKNOWN);
}
return registry;
}
@Override
public SGuiCatalogueSettings getCatalogueSettings(final int type, final int subtype, final SGuiParams params) {
String sql = "";
SGuiCatalogueSettings settings = null;
switch (type) {
case SModConsts.CFGU_COB_ENT:
/* Use of other parameters:
* subtype = Filter: Entity category ID. Can be 'SLibConsts.UNDEFINED' meaning that all categories are requested.
*/
settings = new SGuiCatalogueSettings("Entidad", 2, 1);
sql = "SELECT id_cob AS " + SDbConsts.FIELD_ID + "1, id_ent AS " + SDbConsts.FIELD_ID + "2, ent AS " + SDbConsts.FIELD_ITEM + ", " +
"id_cob AS " + SDbConsts.FIELD_FK + "1 " +
"FROM " + SModConsts.TablesMap.get(type) + " " +
"WHERE b_del = 0 " + (subtype == SLibConsts.UNDEFINED ? "" : "AND fid_ct_ent = " + subtype) + " " +
"ORDER BY id_cob, id_ent, ent ";
break;
case SModConsts.CFGU_CUR:
settings = new SGuiCatalogueSettings("Moneda", 1, 1, SLibConsts.DATA_TYPE_TEXT);
sql = "SELECT id_cur AS " + SDbConsts.FIELD_ID + "1, 1 AS " + SDbConsts.FIELD_FK + "1, cur AS " + SDbConsts.FIELD_ITEM + ", cur_key AS " + SDbConsts.FIELD_COMP + " " +
"FROM erp.cfgu_cur " +
"WHERE b_del = 0 " +
"ORDER BY cur, id_cur ";
break;
case SModConsts.CFGS_TP_MMS:
settings = new SGuiCatalogueSettings("Configuración", 1, 1, SLibConsts.DATA_TYPE_TEXT);
sql = "SELECT id_tp_mms AS " + SDbConsts.FIELD_ID + "1, 1 AS " + SDbConsts.FIELD_FK + "1, name AS " + SDbConsts.FIELD_ITEM + ", code AS " + SDbConsts.FIELD_COMP + " " +
"FROM erp.cfgs_tp_mms " +
"WHERE b_del = 0 " +
"ORDER BY name, id_tp_mms ";
break;
case SModConsts.CFGU_FUNC:
settings = new SGuiCatalogueSettings("Área funcional", 1, 1, SLibConsts.DATA_TYPE_TEXT);
sql = "SELECT id_func AS " + SDbConsts.FIELD_ID + "1, 1 AS " + SDbConsts.FIELD_FK + "1, name AS " + SDbConsts.FIELD_ITEM + ", code AS " + SDbConsts.FIELD_COMP + " " +
"FROM " + SModConsts.TablesMap.get(type) + " " +
"WHERE b_del = 0 " +
"ORDER BY name, id_func ";
break;
default:
miClient.showMsgBoxError(SLibConsts.ERR_MSG_OPTION_UNKNOWN);
}
if (settings != null) {
settings.setSql(sql);
}
return settings;
}
@Override
public SGridPaneView getView(final int type, final int subtype, final SGuiParams params) {
SGridPaneView view = null;
switch (type) {
case SModConsts.CFGU_FUNC:
view = new SViewFunctionalArea(miClient, "Áreas funcionales");
break;
default:
miClient.showMsgBoxError(SLibConsts.ERR_MSG_OPTION_UNKNOWN);
}
return view;
}
@Override
public SGuiOptionPicker getOptionPicker(final int type, final int subtype, final SGuiParams params) {
throw new UnsupportedOperationException("Not supported yet.");
}
@Override
public SGuiForm getForm(final int type, final int subtype, final SGuiParams params) {
SGuiForm form = null;
switch (type) {
case SModConsts.CFGU_FUNC:
if (moFunctionalsAreas == null) moFunctionalsAreas = new SFormFunctionalArea(miClient, "Área funcional");
form = moFunctionalsAreas;
break;
default:
miClient.showMsgBoxError(SLibConsts.ERR_MSG_OPTION_UNKNOWN);
}
return form;
}
@Override
public SGuiReport getReport(final int type, final int subtype, final SGuiParams params) {
throw new UnsupportedOperationException("Not supported yet.");
}
}
| 38.047904
| 184
| 0.587819
|
8116c772e7bc5c9cfc09443134a4849828bc34a6
| 2,942
|
package cn.e3mall.controller;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import cn.e3mall.common.pojo.EasyUIDataGridResult;
import cn.e3mall.common.utils.E3Result;
import cn.e3mall.pojo.TbItem;
import cn.e3mall.pojo.TbItemDesc;
import cn.e3mall.service.ItemService;
/**
* 商品管理Controller
* <p>Title: ItemController</p>
* <p>Description: </p>
* <p>Company: www.itcast.cn</p>
* @version 1.0
*/
@Controller
public class ItemController {
@Autowired
private ItemService itemService;
@RequestMapping("/item/{itemId}")
@ResponseBody
public TbItem getItemById(@PathVariable Long itemId) {
TbItem tbItem = itemService.getItemById(itemId);
return tbItem;
}
@RequestMapping("/item/list")
@ResponseBody
public EasyUIDataGridResult getItemList(Integer page, Integer rows) {
//调用服务查询商品列表
EasyUIDataGridResult result = itemService.getItemList(page, rows);
return result;
}
/**
* 商品添加功能
*/
@RequestMapping(value="/item/save", method=RequestMethod.POST)
@ResponseBody
public E3Result addItem(TbItem item, String desc) {
E3Result result = itemService.addItem(item, desc);
return result;
}
/**
* 商品编辑功能
*/
@RequestMapping(value="/rest/item/update", method=RequestMethod.POST)
@ResponseBody
public E3Result editItem(TbItem item, String desc) {
E3Result result = itemService.updateItem(item, desc);
return result;
}
@RequestMapping(value="/rest/item/query/item/desc/{id}", method=RequestMethod.GET)
@ResponseBody
public E3Result editItem1(@PathVariable Long id) {
TbItemDesc tbItemDesc = itemService.getItemDescById(id);
return E3Result.ok(tbItemDesc);
}
@RequestMapping(value="/rest/item/param/item/query/{id}", method=RequestMethod.GET)
@ResponseBody
public E3Result editItem2(@PathVariable Long id) {
TbItem tbItem = itemService.getItemById(id);
return E3Result.ok(tbItem);
}
/**
* 商品删除功能
*/
@RequestMapping(value="/rest/item/delete", method=RequestMethod.POST)
@ResponseBody
public E3Result delItem(@RequestBody String params) {
E3Result result = itemService.delItem(params);
return result;
}
/**
* 商品上架功能
*/
@RequestMapping(value="/rest/item/reshelf", method=RequestMethod.POST)
@ResponseBody
public E3Result reshelfItem(@RequestBody String params) {
E3Result result = itemService.reshelfItem(params);
return result;
}
/**
* 商品下架功能
*/
@RequestMapping(value="/rest/item/instock", method=RequestMethod.POST)
@ResponseBody
public E3Result instockItem(@RequestBody String params) {
E3Result result = itemService.instockItem(params);
return result;
}
}
| 26.504505
| 84
| 0.756968
|
3f2712af484105aceb5c6f5426bf1b74933fa9c5
| 105
|
package com.piesat.excel.excel;
public interface ReadExcelResultCallback<T> {
void onResult(T t);
}
| 17.5
| 45
| 0.752381
|
be0b080880366f6545e430d5f73468ca2e001936
| 1,305
|
package io.geekidea.springbootplus.example;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.Resource;
import org.springframework.jdbc.datasource.init.DataSourceInitializer;
import org.springframework.jdbc.datasource.init.DatabasePopulator;
import org.springframework.jdbc.datasource.init.ResourceDatabasePopulator;
import javax.sql.DataSource;
@Configuration
public class BatchTaskDataSourceInitializer {
/**
* 构建Resource对象
*/
@Value("classpath:test.sql")
private Resource businessScript;
/**
* 自定义Bean实现业务的特殊需求
* @param dataSource
* @return
*/
@Bean
public DataSourceInitializer dataSourceInitializer(final DataSource dataSource) {
final DataSourceInitializer initializer = new DataSourceInitializer();
// 设置数据源
initializer.setDataSource(dataSource);
initializer.setDatabasePopulator(databasePopulator());
return initializer;
}
private DatabasePopulator databasePopulator() {
final ResourceDatabasePopulator populator = new ResourceDatabasePopulator();
populator.addScripts(businessScript);
return populator;
}
}
| 34.342105
| 85
| 0.758621
|
ad29a239dba312750f4bff0583ad28c698414e33
| 1,088
|
package com.omertdemirel.rentacar.business.abstracts;
import java.util.List;
import org.springframework.data.domain.Sort;
import com.omertdemirel.rentacar.business.dtos.CreditCardDto;
import com.omertdemirel.rentacar.business.dtos.ListCreditCardDto;
import com.omertdemirel.rentacar.business.request.CreateCreditCardRequest;
import com.omertdemirel.rentacar.business.request.UpdateCreditCardRequest;
import com.omertdemirel.rentacar.core.utilities.results.DataResult;
import com.omertdemirel.rentacar.core.utilities.results.Result;
public interface CreditCardService {
Result update(UpdateCreditCardRequest updateCreditCardRequest);
Result create(CreateCreditCardRequest createCreditCardRequest);
Result delete(int creditCardId);
DataResult<List<ListCreditCardDto>> listAll();
DataResult<CreditCardDto> getById(int creditCardId);
DataResult<CreditCardDto> getByCreditCardNumber(String creditCardNumber);
DataResult<List<ListCreditCardDto>> getAllSorted(Sort.Direction direction);
DataResult<List<ListCreditCardDto>> getAllPaged(int pageNo, int pageSize);
}
| 32
| 76
| 0.840074
|
6b42aac7b0251d76a1018dd5e62ded9256e85dd3
| 6,676
|
package brokenlib.common.notification;
import brokenlib.BrokenLib;
import brokenlib.common.network.BrokenLibNetwork;
import brokenlib.common.notification.packet.CSPacketNotification;
import brokenlib.common.notification.packet.SPacketRemoveNotification;
import io.netty.util.collection.IntObjectHashMap;
import net.minecraft.entity.player.EntityPlayerMP;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.nbt.NBTTagList;
import net.minecraftforge.common.MinecraftForge;
import net.minecraftforge.common.util.Constants;
import net.minecraftforge.fml.common.FMLCommonHandler;
import net.minecraftforge.fml.common.eventhandler.EventPriority;
import net.minecraftforge.fml.common.eventhandler.SubscribeEvent;
import net.minecraftforge.fml.common.gameevent.PlayerEvent;
import net.minecraftforge.fml.relauncher.Side;
import java.util.BitSet;
import java.util.Collections;
import java.util.Map;
import java.util.UUID;
public class ServerNotificationManager {
private static volatile ServerNotificationManager instance = null;
public static ServerNotificationManager instance() {
if (instance == null) {
synchronized (ServerNotificationManager.class) {
if (instance == null)
instance = new ServerNotificationManager();
}
}
return instance;
}
private BitSet ids;
private IntObjectHashMap<LinkedNotification> notifications;
private BrokenLibNetwork network;
private ServerNotificationManager() {
this.ids = new BitSet();
this.notifications = new IntObjectHashMap<>();
this.network = NotificationManager.instance().getNetwork();
MinecraftForge.EVENT_BUS.register(this);
}
public void initSaver() {
BrokenLib.proxy.getDataWrapper().getData().addSubData("notification_manager", this::saveToNBT, this::loadFromNBT);
}
/**
* Adds the specified notification to the notifications stack. This will be sent to the player with the specified
* UUID as soon as he's connected.
* @param target The UUID of the targeted player
* @param notification The notification to be sent to the player
*/
public void addNotification(UUID target, Notification notification) {
notification.setIimestamp(System.currentTimeMillis());
LinkedNotification linkedNotification = new LinkedNotification(target, notification);
int id = getNextAvailableId();
notifications.put(id, linkedNotification);
BrokenLib.proxy.getDataWrapper().markDirty();
EntityPlayerMP player = FMLCommonHandler.instance().getMinecraftServerInstance().getPlayerList().getPlayerByUUID(target);
if (player != null) {
new CSPacketNotification(id, linkedNotification.notification, Side.SERVER).sendUsing(network).to(player);
}
}
/**
* Called when the client reply is received on the server. Checks if the notification id is available, if the player
* targeted by the notification is the same player who sent the packet.
* @param player The player replying
* @param pck the packet received from the client
*/
public void receivedNotificationPacket(EntityPlayerMP player, CSPacketNotification pck) {
if (!this.notifications.containsKey(pck.getNotificationId())) return;
LinkedNotification linkedNotification = notifications.get(pck.getNotificationId());
if (!linkedNotification.target.equals(player.getUniqueID())) return;
linkedNotification.notification.fromNBT(pck.getNBT(), Side.SERVER);
if (linkedNotification.notification.receivedOnServer(player)) {
linkedNotification.notification.onRemove(Side.SERVER);
this.notifications.remove(pck.getNotificationId());
freeId(pck.getNotificationId());
new SPacketRemoveNotification(pck.getNotificationId()).sendUsing(network).to(player);
}
BrokenLib.proxy.getDataWrapper().markDirty();
}
public boolean removeNotification(int id) {
LinkedNotification notification = this.notifications.remove(id);
if(notification == null)
return false;
freeId(id);
EntityPlayerMP player = FMLCommonHandler.instance().getMinecraftServerInstance().getPlayerList().getPlayerByUUID(notification.target);
if(player != null)
new SPacketRemoveNotification(id).sendUsing(this.network).to(player);
return true;
}
/**
* Sends to the player all the notifications related to him.
* @param player The player who requires the notifications
*/
private void clientConnection(EntityPlayerMP player) {
this.notifications.entrySet().stream()
.filter(e -> e.getValue().target.equals(player.getUniqueID()))
.forEach(e -> new CSPacketNotification(e.getKey(), e.getValue().notification, Side.SERVER)
.sendUsing(network).to(player)
);
}
@SubscribeEvent(priority = EventPriority.LOWEST)
public void onClientConnect(PlayerEvent.PlayerLoggedInEvent event) {
if (!event.player.world.isRemote)
clientConnection((EntityPlayerMP) event.player);
}
/**
* Used to data persistence. It saves all the notifications in a NBTTagCompound.
* @return the serialized manager
*/
public NBTTagCompound saveToNBT() {
NBTTagCompound nbt = new NBTTagCompound();
NBTTagList list = new NBTTagList();
this.notifications.values().forEach(n -> list.appendTag(n.toNBT()));
nbt.setTag("notifications", list);
return nbt;
}
/**
* Used to data persistence. It loads all the notifications from a NBTTagCompound.
* @param nbt The serialized manager
*/
public void loadFromNBT(NBTTagCompound nbt) {
this.notifications.clear();
this.ids.clear();
NBTTagList list = nbt.getTagList("notifications", Constants.NBT.TAG_COMPOUND);
for (int i = 0; i < list.tagCount(); i++) {
NBTTagCompound n = list.getCompoundTagAt(i);
LinkedNotification notification = new LinkedNotification(n);
if (!notification.hasToBeRemoved)
this.notifications.put(getNextAvailableId(), notification);
}
}
private int getNextAvailableId() {
int id = ids.nextClearBit(0);
ids.set(id);
return id;
}
private void freeId(int id) {
ids.clear(id);
}
public Map<Integer, LinkedNotification> getNotifications() {
return Collections.unmodifiableMap(this.notifications);
}
}
| 39.738095
| 142
| 0.691282
|
0edd32529c8f82781392a6d69803d3f8d813c22b
| 3,941
|
package cn.com.tsjx.sys.impl;
import java.io.IOException;
import javax.annotation.Resource;
import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import org.apache.commons.lang3.StringUtils;
import org.springframework.core.task.TaskExecutor;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.JavaMailSenderImpl;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Service;
import com.sun.xml.internal.messaging.saaj.packaging.mime.internet.MimeUtility;
import cn.com.tsjx.common.config.MailConfig;
import cn.com.tsjx.sys.MailService;
@Service("mailService")
public class MailServiceImpl implements MailService {
@Resource
private JavaMailSender javaMailSender;
@Resource
private TaskExecutor taskExecutor;
public boolean isMailConfigComplete() {
if (StringUtils.isEmpty(MailConfig.FORMMAIL) || StringUtils.isEmpty(MailConfig.HOST) || MailConfig.PORT == null
|| StringUtils.isEmpty(MailConfig.USERNAME) || StringUtils.isEmpty(MailConfig.PASSWORD)) {
return false;
} else {
return true;
}
}
// 增加邮件发送任务
public void addSendMailTask(final MimeMessage mimeMessage) {
try {
taskExecutor.execute(new Runnable() {
public void run() {
javaMailSender.send(mimeMessage);
}
});
} catch (Exception e) {
e.printStackTrace();
}
}
public void sendMail(String toMail, String subject, String content, String siteName) {
try {
JavaMailSenderImpl javaMailSenderImpl = (JavaMailSenderImpl) javaMailSender;
javaMailSenderImpl.setHost(MailConfig.HOST);
javaMailSenderImpl.setPort(MailConfig.PORT);
javaMailSenderImpl.setUsername(MailConfig.USERNAME);
javaMailSenderImpl.setPassword(MailConfig.PASSWORD);
MimeMessage mimeMessage = javaMailSenderImpl.createMimeMessage();
MimeMessageHelper mimeMessageHelper = new MimeMessageHelper(mimeMessage, false, "utf-8");
mimeMessageHelper.setFrom(MimeUtility.encodeWord(siteName) + " <" + MailConfig.FORMMAIL + ">");
mimeMessageHelper.setTo(toMail);
mimeMessageHelper.setSubject(subject);
mimeMessageHelper.setText(content, true);
// 异步发送
// addSendMailTask(mimeMessage);
javaMailSender.send(mimeMessage);
} catch (Exception e) {
e.printStackTrace();
}
}
public void sendMailTest(String smtpFromMail, String smtpHost, Integer smtpPort, String smtpUsername,
String smtpPassword, String toMail) {
try {
JavaMailSenderImpl javaMailSenderImpl = (JavaMailSenderImpl) javaMailSender;
javaMailSenderImpl.setHost(smtpHost);
javaMailSenderImpl.setPort(smtpPort);
javaMailSenderImpl.setUsername(smtpUsername);
javaMailSenderImpl.setPassword(smtpPassword);
MimeMessage mimeMessage = javaMailSenderImpl.createMimeMessage();
MimeMessageHelper mimeMessageHelper;
try {
mimeMessageHelper = new MimeMessageHelper(mimeMessage, false, "utf-8");
mimeMessageHelper.setFrom(MimeUtility.encodeWord("测试") + " <" + smtpFromMail + ">");
mimeMessageHelper.setTo(toMail);
mimeMessageHelper.setSubject("测试主题");
mimeMessageHelper.setText("测试内容", true);
javaMailSender.send(mimeMessage);
} catch (javax.mail.MessagingException e) {
e.printStackTrace();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
| 38.637255
| 120
| 0.643745
|
3a0e5b1ca0b2fe4d5ab67a40e87e48514a3e8320
| 4,653
|
/*
* Copyright (C) 2011 Everit Kft. (http://everit.org)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.everit.osgi.dev.maven;
import java.io.File;
import java.io.FileFilter;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import org.apache.commons.io.filefilter.TrueFileFilter;
import org.apache.maven.plugin.MojoExecutionException;
import org.apache.maven.plugin.MojoFailureException;
import org.apache.maven.plugins.annotations.Mojo;
import org.apache.maven.plugins.annotations.Parameter;
import org.everit.osgi.dev.maven.configuration.EnvironmentConfiguration;
import org.everit.osgi.dev.maven.util.FileManager;
/**
* Synchronizes back the configured directories.
*/
@Mojo(name = "sync-back", requiresProject = true)
public class SyncBackMojo extends AbstractEOSGiMojo {
/**
* Path to folder where the distribution will be generated. The content of this folder will be
* overridden if the files with same name already exist.
*
*/
@Parameter(property = "eosgi.distFolder", defaultValue = "${project.build.directory}/eosgi/dist")
protected String distFolder;
/**
* The directory where there may be additional files to create the distribution package
* (optional).
*/
@Parameter(property = "eosgi.sourceDistFolder", defaultValue = "${basedir}/src/dist/")
protected String sourceDistFolder;
/**
* List of relative folder paths that should be synchronized back to the source distribution
* folder when this goal is called.
*/
@Parameter
protected Map<String, String> syncBackFolders;
private boolean cleanNonTouchedFilesInFolderRecurse(final File file,
final Set<File> touchedFiles) {
if (file.isDirectory()) {
File[] folderContents = file.listFiles((FileFilter) TrueFileFilter.INSTANCE);
boolean clean = true;
for (File content : folderContents) {
clean = cleanNonTouchedFilesInFolderRecurse(content, touchedFiles) && clean;
}
if (clean && !touchedFiles.contains(file)) {
file.delete();
return true;
} else {
return false;
}
} else {
if (!touchedFiles.contains(file)) {
file.delete();
return true;
} else {
return false;
}
}
}
@Override
protected void doExecute() throws MojoExecutionException, MojoFailureException {
if (syncBackFolders == null || syncBackFolders.size() == 0) {
getLog().info("No folders are configured to sync back.");
return;
}
EnvironmentConfiguration[] environments = getEnvironmentsToProcess();
if (environments.length != 1) {
throw new MojoExecutionException(
"Select exactly one environment to synchronize its folders back to the source"
+ " distribution folder! You can select an environment with the "
+ "'eosgi.environmentId' system property or 'environmentIdsToProcess' plugin"
+ " configuration.");
}
EnvironmentConfiguration environmentConfiguration = environments[0];
File sourceDistFolderFile = new File(sourceDistFolder);
File globalDistFolderFile = new File(distFolder);
String environmentId = environmentConfiguration.getId();
File environmentRootFolder = new File(globalDistFolderFile, environmentId);
FileManager fileManager = new FileManager();
for (Entry<String, String> syncBackFolder : syncBackFolders.entrySet()) {
String relativeFolderPath = syncBackFolder.getValue();
File envornmentDistSyncFolder = new File(environmentRootFolder, relativeFolderPath);
File sourceSyncFolder = new File(sourceDistFolderFile, relativeFolderPath);
sourceSyncFolder.mkdirs();
getLog()
.info("Syncing back '" + syncBackFolder.getKey() + "', from folder '"
+ envornmentDistSyncFolder + "' to folder '" + sourceSyncFolder + "'");
fileManager.copyDirectory(envornmentDistSyncFolder, sourceSyncFolder);
Set<File> touchedFiles = fileManager.getTouchedFiles();
touchedFiles.add(sourceSyncFolder);
cleanNonTouchedFilesInFolderRecurse(sourceSyncFolder, touchedFiles);
}
}
}
| 37.224
| 99
| 0.712229
|
ef35f23e3b2d975271d978930f59c5f84bd06679
| 3,577
|
/*
* 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.flink.runtime.io.network.partition;
import java.io.File;
import java.io.IOException;
/**
* The type of the BoundedBlockingSubpartition. Also doubles as the factory.
*/
public enum BoundedBlockingSubpartitionType {
/**
* A BoundedBlockingSubpartition type that simply stores the partition data in a file.
* Data is eagerly spilled (written to disk) and readers directly read from the file.
*/
FILE {
@Override
public BoundedBlockingSubpartition create(int index, BoundedBlockingResultPartition parent, File tempFile, int readBufferSize) throws IOException {
return BoundedBlockingSubpartition.createWithFileChannel(index, parent, tempFile, readBufferSize);
}
},
/**
* A BoundedBlockingSubpartition type that stores the partition data in memory mapped file.
* Data is written to and read from the mapped memory region.
* Disk spilling happens lazily, when the OS swaps out the pages from the memory mapped file.
*/
MMAP {
@Override
public BoundedBlockingSubpartition create(int index, BoundedBlockingResultPartition parent, File tempFile, int readBufferSize) throws IOException {
return BoundedBlockingSubpartition.createWithMemoryMappedFile(index, parent, tempFile);
}
},
/**
* Creates a BoundedBlockingSubpartition that stores the partition data in a file and
* memory maps that file for reading.
* Data is eagerly spilled (written to disk) and then mapped into memory. The main
* difference to the {@link BoundedBlockingSubpartitionType#MMAP} variant
* is that no I/O is necessary when pages from the memory mapped file are evicted.
*/
FILE_MMAP {
@Override
public BoundedBlockingSubpartition create(int index, BoundedBlockingResultPartition parent, File tempFile, int readBufferSize) throws IOException {
return BoundedBlockingSubpartition.createWithFileAndMemoryMappedReader(index, parent, tempFile);
}
},
/**
* Selects the BoundedBlockingSubpartition type based on the current memory architecture. If 64-bit,
* the type of {@link BoundedBlockingSubpartitionType#FILE_MMAP} is recommended. Otherwise, the type
* of {@link BoundedBlockingSubpartitionType#FILE} is by default.
*/
AUTO {
@Override
public BoundedBlockingSubpartition create(int index, BoundedBlockingResultPartition parent, File tempFile, int readBufferSize) throws IOException {
return ResultPartitionFactory.getBoundedBlockingType().create(index, parent, tempFile, readBufferSize);
}
};
// ------------------------------------------------------------------------
/**
* Creates BoundedBlockingSubpartition of this type.
*/
public abstract BoundedBlockingSubpartition create(int index, BoundedBlockingResultPartition parent, File tempFile, int readBufferSize) throws IOException;
}
| 40.191011
| 156
| 0.760973
|
3356bb2a75ddb8794dbc68d28e0b6dc0423921c4
| 4,255
|
/*
Copyright (c) since 2015, Tel Aviv University and Software Modeling Lab
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
* Neither the name of Tel Aviv University and Software Modeling Lab nor the
names of its contributors may be used to endorse or promote products
derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL Tel Aviv University and Software Modeling Lab
BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package tau.smlab.syntech.richcontrollerwalker;
import java.util.ArrayDeque;
import java.util.Deque;
import java.util.List;
import java.util.Objects;
import net.sf.javabdd.BDD;
import tau.smlab.syntech.jtlv.Env;
import tau.smlab.syntech.richcontrollerwalker.Engine.FullState;
import tau.smlab.syntech.richcontrollerwalker.util.Mode;
import tau.smlab.syntech.richcontrollerwalker.util.Mod;
public final class History {
private final Deque<HistoryItem> stack = new ArrayDeque<>();
boolean canStepBack() {
return !stack.isEmpty();
}
Mode getModeOfLastItem() {
return stack.getLast().getMode();
}
void save(final FullState fullState, Mod nextTurn) {
stack.addLast(new FreeItem(fullState, nextTurn));
}
void save(final List<BDD> route, Mode mode) {
stack.addLast(new RouteItem(route, mode));
}
void reset() {
for (HistoryItem historyItem : stack) {
historyItem.clear();
}
stack.clear();
}
HistoryItem popPreviousItem() {
if (!canStepBack()) {
throw new IllegalStateException("cannot get previous step when step history is empty.");
}
return stack.removeLast();
}
boolean isPrevFree() {
return stack.getLast().getMode().equals(Mode.FREE);
}
abstract static class HistoryItem {
private final Mode mode;
public HistoryItem(Mode mode) {
this.mode = mode;
}
public Mode getMode() {
return mode;
}
abstract void clear();
}
static class FreeItem extends HistoryItem {
private final FullState fullState;
private final Mod nextTurn;
public FreeItem(FullState fullState, Mod nextTurn) {
super(Mode.FREE);
Objects.requireNonNull(fullState);
if (Objects.isNull(fullState.getState()) || Objects.isNull(fullState.getSuccessors())
|| fullState.getState().isFree() || fullState.getSuccessors().isFree()) {
throw new IllegalStateException("cannot save full state with bull or free BDDs");
}
this.fullState = fullState;
this.nextTurn = nextTurn;
}
FullState getFullState() {
return fullState;
}
Mod getTurn() {
return nextTurn;
}
@Override
void clear() {
fullState.reset();
}
}
static class RouteItem extends HistoryItem {
private List<BDD> route;
public RouteItem(List<BDD> route, Mode mode) {
super(ensureGuidedMode(mode));
this.route = route;
}
private static Mode ensureGuidedMode(Mode mode) {
if (mode.isFree()) {
throw new IllegalArgumentException("route history item cannot be associated with FREE mode.");
}
return mode;
}
List<BDD> getRoute() {
return route;
}
@Override
void clear() {
if (Objects.nonNull(route)) {
Env.free(route);
route = null;
}
}
}
}
| 27.993421
| 98
| 0.73537
|
ddb8084c28c606d01f357ad83b548942afaede8d
| 486
|
package be.kdg.repaircafe.backend.persistence.api;
import be.kdg.repaircafe.backend.dom.repairs.Repair;
import be.kdg.repaircafe.backend.dom.users.roles.Client;
import java.util.List;
/**
* Extra interface to support customization of Spring's Data interfaces
*/
public interface RepairRepositoryCustom
{
// https://programmeren3-repaircafe.rhcloud.com/repair-cafe-applicatie/repair-cafe-backend/backend-persistence-layer/
List<Repair> getRepairsByClient(Client client);
}
| 28.588235
| 121
| 0.794239
|
e2456464e4833c1cb89581a511d2b7928c1e3b83
| 1,229
|
/*
* 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.test.annotations.cid.keymanytoone;
import java.io.Serializable;
import java.util.HashSet;
import java.util.Set;
import javax.persistence.CascadeType;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.Id;
import javax.persistence.OneToMany;
/**
* TODO : javadoc
*
* @author Steve Ebersole
*/
@Entity
public class Card implements Serializable {
@Id
private String id;
@OneToMany(cascade = CascadeType.ALL, fetch = FetchType.EAGER, mappedBy = "primaryKey.card")
private Set<CardField> fields;
public Card(String id) {
this();
this.id = id;
}
Card() {
fields = new HashSet<CardField>();
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public void addField(Card card, Key key) {
fields.add(new CardField(card, key));
}
public Set<CardField> getFields() {
return fields;
}
public void setFields(Set<CardField> fields) {
this.fields = fields;
}
}
| 20.483333
| 94
| 0.716843
|
0e198a05dc1ef0539837659a1917843df7be3937
| 3,117
|
/***************************************************************************
* Copyright 2017 Kieker Project (http://kieker-monitoring.net)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
***************************************************************************/
package kieker.tools.logReplayer;
import kieker.analysis.IAnalysisController;
import kieker.analysis.plugin.reader.AbstractReaderPlugin;
import kieker.analysis.plugin.reader.jms.JmsReader;
import kieker.common.configuration.Configuration;
/**
* An implementation of the {@link AbstractLogReplayer}, using the {@link JmsReader} to replay {@link kieker.common.record.IMonitoringRecord}s from a JMS queue.
*
* @author Andre van Hoorn
*
* @since 1.3
*/
public class JMSLogReplayer extends AbstractLogReplayer {
private final String jmsProviderUrl;
private final String jmsDestination;
private final String jmsFactoryLookupName;
/**
* Creates a new JMS log replayer.
*
* @param jmsProviderUrl
* = for instance "tcp://127.0.0.1:3035/"
* @param jmsDestination
* = for instance "queue1"
* @param jmsFactoryLookupName
* = for instance "org.exolab.jms.jndi.InitialContextFactory" (OpenJMS)
* @param monitoringConfigurationFile
* The path of the monitoring.properties file.
*/
public JMSLogReplayer(final String monitoringConfigurationFile, final String jmsProviderUrl, final String jmsDestination, final String jmsFactoryLookupName) {
super(monitoringConfigurationFile,
false, // realtimeMode
1.0, // realtimeAccelerationFactor: any value will do because realtimeMode = false
true, // keepOriginalLoggingTimestamps
1, // numRealtimeWorkerThreads: any value will do because realtimeMode = false
Long.MIN_VALUE,
Long.MAX_VALUE);
this.jmsProviderUrl = jmsProviderUrl;
this.jmsDestination = jmsDestination;
this.jmsFactoryLookupName = jmsFactoryLookupName;
}
/**
* {@inheritDoc}
*/
@Override
protected AbstractReaderPlugin createReader(final IAnalysisController analysisController) {
final Configuration configuration = new Configuration();
configuration.setProperty(JmsReader.CONFIG_PROPERTY_NAME_PROVIDERURL, this.jmsProviderUrl);
configuration.setProperty(JmsReader.CONFIG_PROPERTY_NAME_DESTINATION, this.jmsDestination);
configuration.setProperty(JmsReader.CONFIG_PROPERTY_NAME_FACTORYLOOKUP, this.jmsFactoryLookupName);
return new JmsReader(configuration, analysisController);
}
/**
* {@inheritDoc}
*/
@Override
protected String readerOutputPortName() {
return JmsReader.OUTPUT_PORT_NAME_RECORDS;
}
}
| 38.012195
| 160
| 0.725056
|
84106db3305a99b9a792ac442a80281109d5c066
| 1,675
|
package algorithms;
public class LCS {
public static void main(String[] args){
String a=new String("fa");
String b=new String("fa");
System.out.print(a==b);
String d = "44";
int aa3= 1;
// String X = "ak46deetyyxaz";
// String Y = "k6dcbtacbzeg";
// char[] x = X.toCharArray();
// char[] y = Y.toCharArray();
// int[][] doubleArray = length(x, y);
// StringBuilder longCommonSubstring = new StringBuilder();
// longCommonSubstring = lcs(doubleArray, x, y, x.length, y.length, longCommonSubstring);
// System.out.println(longCommonSubstring.toString());
}
public static int[][] length(char[] x,char[] y){
int[][] doubleArray = new int[x.length+1][y.length+1];
for(int i = 1; i <= x.length; i++){
for(int j = 1;j <= y.length; j++){
if(x[i-1] == y[j-1]) {
doubleArray[i][j] = doubleArray[i-1][j-1] + 1;
}else if(doubleArray[i-1][j] > doubleArray[i][j-1]){
doubleArray[i][j] = doubleArray[i-1][j];
}else{
doubleArray[i][j] = doubleArray[i][j-1];
}
}
}
return doubleArray;
}
public static StringBuilder lcs(int[][] doubleArray, char[] x, char[] y, int xLength, int yLength, StringBuilder longCommonSubstring){
if(xLength == 0 || yLength == 0){
return longCommonSubstring;
}
if(x[xLength - 1] == y[yLength - 1]){
longCommonSubstring.append(x[xLength - 1]);
lcs(doubleArray, x, y, xLength - 1, yLength - 1, longCommonSubstring);
}else if(doubleArray[xLength][yLength-1] > doubleArray[xLength-1][yLength]){
lcs(doubleArray, x, y, xLength, yLength - 1, longCommonSubstring);
}else{
lcs(doubleArray, x, y, xLength - 1, yLength, longCommonSubstring);
}
return longCommonSubstring;
}
}
| 32.843137
| 135
| 0.638209
|
c9601d78c8bedad418e029f8b476e227789f0940
| 1,019
|
package net.modificationstation.stationapi.api.common.recipe;
import net.modificationstation.stationapi.api.common.StationAPI;
import net.modificationstation.stationapi.api.common.event.recipe.RecipeRegisterEvent;
import net.modificationstation.stationapi.api.common.registry.Identifier;
import net.modificationstation.stationapi.api.common.registry.Registry;
import java.net.*;
import java.util.function.*;
/**
* The JSON recipe parser registry that holds all JSON recipe parsers to automatically run when {@link RecipeRegisterEvent} event is called with a proper identifier.
* @author mine_diver
*/
public final class JsonRecipeParserRegistry extends Registry<Consumer<URL>> {
private JsonRecipeParserRegistry(Identifier identifier) {
super(identifier);
}
@Override
public int getRegistrySize() {
return Integer.MAX_VALUE;
}
public static final JsonRecipeParserRegistry INSTANCE = new JsonRecipeParserRegistry(Identifier.of(StationAPI.MODID, "json_recipe_parsers"));
}
| 37.740741
| 165
| 0.794897
|
e98c84f7637d27d97b47854b74d02e9c25d460e9
| 2,044
|
package acceptance;
import acceptance.pageobject.ListBookPage;
import org.junit.Before;
import org.junit.Test;
import org.openqa.selenium.WebDriver;
import static org.assertj.core.api.Assertions.assertThat;
public class ITSearchBooks extends BaseAcceptance {
private ListBookPage listBookPage;
private static WebDriver driver = getDriver();
@Before
public void setup() throws InterruptedException {
driver.get(baseUrl);
login();
listBookPage = new ListBookPage(driver);
listBookPage.clickOnBooksDropdownButton();
sleepABit(500);
listBookPage.clickOnListAllButton();
sleepABit(500);
}
@Test
public void whenSearchBookByTitle_TheBookListIsUpdatedWithTheCorrectResults() throws InterruptedException {
listBookPage.selectFilter("Title");
listBookPage.setValueForFilter("The Pragmatic Programmer");
sleepABit(500);
assertThat(listBookPage.getListOfBooks().size()).isEqualTo(1);
}
@Test
public void whenSearchBookByTitle_TheUrlIsUpdatedCorrectly() throws InterruptedException {
listBookPage.selectFilter("Title");
listBookPage.setValueForFilter("The Pragmatic Programmer");
sleepABit(500);
assertThat(driver.getCurrentUrl()).contains("title=The%20Pragmatic%20Programmer");
}
@Test
public void whenSearchBookByIsbn_TheBookListIsUpdatedWithTheCorrectResults() throws InterruptedException {
listBookPage.selectFilter("ISBN");
sleepABit(500);
listBookPage.setValueForFilter("978-0-201-48567-7");
sleepABit(500);
assertThat(listBookPage.getListOfBooks().size()).isEqualTo(1);
}
@Test
public void whenSearchBookByIsbn_TheUrlIsUpdatedCorrectly() throws InterruptedException {
listBookPage.selectFilter("ISBN");
sleepABit(500);
listBookPage.setValueForFilter("978-0-201-48567-7");
sleepABit(500);
assertThat(driver.getCurrentUrl()).contains("isbn=978-0-201-48567-7");
}
}
| 29.623188
| 111
| 0.710372
|
6f2185076a9d900d5822b5dbcf0c6dd4314fa5b3
| 1,645
|
package me.monkeykiller.customblocks.commands;
import me.monkeykiller.customblocks.CustomBlocksPlugin;
import org.bukkit.command.Command;
import org.bukkit.command.CommandSender;
import org.bukkit.command.PluginCommand;
import org.bukkit.command.TabExecutor;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.util.ArrayList;
import java.util.List;
@SuppressWarnings("unused")
public class BaseCommand implements TabExecutor {
public static List<BaseCommand> REGISTRY = new ArrayList<>();
public String name;
public List<String> aliases;
public BaseCommand(@NotNull String name, @Nullable List<String> aliases) {
this.name = name;
this.aliases = aliases;
PluginCommand cmd = CustomBlocksPlugin.plugin.getCommand(name);
assert cmd != null;
cmd.setExecutor(this);
cmd.setTabCompleter(this);
}
@Override
public boolean onCommand(@NotNull CommandSender sender, @NotNull Command command, @NotNull String label, @NotNull String[] args) {
return false;
}
@Nullable
public List<String> onTabComplete(@NotNull CommandSender sender, @NotNull Command command, @NotNull String alias, @NotNull String[] args) {
return null;
}
public PluginCommand parseCommand() {
return CustomBlocksPlugin.plugin.getCommand(name);
}
public static BaseCommand getCommand(String cmd) {
for (BaseCommand command : REGISTRY)
if (cmd.equalsIgnoreCase(command.name) || command.aliases.contains(cmd.toLowerCase()))
return command;
return null;
}
}
| 31.037736
| 143
| 0.71307
|
d822de8a34b3489813fd5e41a3fe9f70cec8edb9
| 2,200
|
/*
* Copyright (C) 2016 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.android.apps.common.testing.ui.multiprocess.testapp.idling;
import android.os.Handler;
import androidx.annotation.Nullable;
import androidx.test.espresso.IdlingResource;
/**
* Takes a String and passes it back after a while via a callback.
* <p>
* This executes a long-running operation on a different thread that results in problems with
* Espresso if an {@link IdlingResource} is not implemented and registered.
*/
public class MessageDelayer {
private static final int DELAY_MILLIS = 3000;
/**
* Callback interface for clients to use.
*/
public interface DelayerCallback {
void onDone(String text);
}
/**
* Takes a String and returns it after {@link #DELAY_MILLIS} via a {@link DelayerCallback}.
*
* @param message the string that will be returned via the callback
* @param callback used to notify the caller asynchronously
*/
public static void processMessage(
final String message,
final DelayerCallback callback,
@Nullable final SimpleIdlingResource idlingResource) {
// The IdlingResource is null in production.
if (idlingResource != null) {
idlingResource.setIdleState(false);
}
// Delay the execution, return message via callback.
Handler handler = new Handler();
handler.postDelayed(new Runnable() {
@Override
public void run() {
if (callback != null) {
callback.onDone(message);
if (idlingResource != null) {
idlingResource.setIdleState(true);
}
}
}
}, DELAY_MILLIS);
}
}
| 31.428571
| 93
| 0.699091
|
23e6efb9d98bf8bcd7722cc89fd9fc59b43d88fa
| 14,102
|
package ch.poole.openinghoursfragment;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.test.platform.app.InstrumentationRegistry;
import androidx.test.uiautomator.By;
import androidx.test.uiautomator.BySelector;
import androidx.test.uiautomator.Configurator;
import androidx.test.uiautomator.UiDevice;
import androidx.test.uiautomator.UiObject;
import androidx.test.uiautomator.UiObject2;
import androidx.test.uiautomator.UiObjectNotFoundException;
import androidx.test.uiautomator.UiScrollable;
import androidx.test.uiautomator.UiSelector;
import androidx.test.uiautomator.Until;
import org.junit.Assert;
import android.util.Log;
/**
* Various methods to support testing
*
* @author Simon Poole
*
*/
public class TestUtils {
private static final String DEBUG_TAG = "TestUtils";
/**
* Click the overflow button in a menu bar
*
* @return true if successful
*/
public static boolean clickOverflowButton() {
return clickMenuButton("More options", false, true);
}
/**
* Click a menu bar button
*
* @param description the description of the button
* @param longClick if true perform a long click
* @param waitForNewWindow if true wait for a new window
* @return true if successful
*/
public static boolean clickMenuButton(String description, boolean longClick, boolean waitForNewWindow) {
// Note: contrary to "text", "textStartsWith" is case insensitive
BySelector bySelector = By.clickable(true).descStartsWith(description);
UiSelector uiSelector = new UiSelector().clickable(true).descriptionStartsWith(description);
UiDevice device = UiDevice.getInstance(InstrumentationRegistry.getInstrumentation());
device.wait(Until.findObject(bySelector), 500);
UiObject button = device.findObject(uiSelector);
if (button.exists()) {
try {
if (longClick) {
button.longClick();
} else if (waitForNewWindow) {
button.clickAndWaitForNewWindow();
} else {
button.click();
}
return true; // the button clicks don't seem to reliably return a true
} catch (UiObjectNotFoundException e) {
Log.e(DEBUG_TAG, "Object vanished.");
return false;
}
} else {
Log.e(DEBUG_TAG, "Object not found");
return false;
}
}
/**
* Click on a button
*
* @param resId resource id
* @param waitForNewWindow if true wait for a new window after clicking
* @return true if the button was found and clicked
* @throws UiObjectNotFoundException
*/
public static boolean clickButton(String resId, boolean waitForNewWindow) {
try {
UiDevice device = UiDevice.getInstance(InstrumentationRegistry.getInstrumentation());
UiSelector uiSelector = new UiSelector().clickable(true).resourceId(resId);
UiObject button = device.findObject(uiSelector);
if (waitForNewWindow) {
return button.clickAndWaitForNewWindow();
} else {
return button.click();
}
} catch (UiObjectNotFoundException e) {
System.out.println(e.getMessage() + " " + resId);
return false;
}
}
/**
* Execute a drag
*
* @param startX start screen X coordinate
* @param startY start screen Y coordinate
* @param endX end screen X coordinate
* @param endY end screen Y coordinate
* @param steps number of 5ms steps
*/
public static void drag(float startX, float startY, float endX, float endY, int steps) {
UiDevice device = UiDevice.getInstance(InstrumentationRegistry.getInstrumentation());
device.swipe((int) startX, (int) startY, (int) endX, (int) endY, steps);
}
/**
* Click a text on screen (case insensitive, start of a string)
*
* @param device UiDevice object
* @param clickable clickable if true the search will be restricted to clickable objects
* @param text text to search (case insensitive, uses textStartsWith)
* @param waitForNewWindow set the wait for new window flag if true
* @return true if successful
*/
public static boolean clickText(UiDevice device, boolean clickable, String text, boolean waitForNewWindow) {
Log.w(DEBUG_TAG, "Searching for object with " + text);
// Note: contrary to "text", "textStartsWith" is case insensitive
BySelector bySelector = null;
UiSelector uiSelector = null;
// NOTE order of the selector terms is significant
if (clickable) {
bySelector = By.clickable(true).textStartsWith(text);
uiSelector = new UiSelector().clickable(true).textStartsWith(text);
} else {
bySelector = By.textStartsWith(text);
uiSelector = new UiSelector().textStartsWith(text);
}
device.wait(Until.findObject(bySelector), 500);
UiObject button = device.findObject(uiSelector);
if (button.exists()) {
try {
if (waitForNewWindow) {
button.clickAndWaitForNewWindow();
} else {
button.click();
Log.e(DEBUG_TAG, ".... clicked");
}
return true;
} catch (UiObjectNotFoundException e) {
Log.e(DEBUG_TAG, "Object vanished.");
return false;
}
} else {
Log.e(DEBUG_TAG, "Object not found");
return false;
}
}
/**
* Click a text on screen (exact)
*
* @param device UiDevice object
* @param clickable clickable if true the search will be restricted to clickable objects
* @param text text to search (case insensitive, uses textStartsWith)
* @param waitForNewWindow set the wait for new window flag if true
* @return true if successful
*/
public static boolean clickTextExact(UiDevice device, boolean clickable, String text, boolean waitForNewWindow) {
Log.w(DEBUG_TAG, "Searching for object with " + text);
// Note: contrary to "text", "textStartsWith" is case insensitive
BySelector bySelector = null;
UiSelector uiSelector = null;
// NOTE order of the selector terms is significant
if (clickable) {
bySelector = By.clickable(true).text(text);
uiSelector = new UiSelector().clickable(true).text(text);
} else {
bySelector = By.text(text);
uiSelector = new UiSelector().text(text);
}
device.wait(Until.findObject(bySelector), 500);
UiObject button = device.findObject(uiSelector);
if (button.exists()) {
try {
if (waitForNewWindow) {
button.clickAndWaitForNewWindow();
} else {
button.click();
Log.e(DEBUG_TAG, ".... clicked");
}
return true;
} catch (UiObjectNotFoundException e) {
Log.e(DEBUG_TAG, "Object vanished.");
return false;
}
} else {
Log.e(DEBUG_TAG, "Object not found");
return false;
}
}
/**
* Click a text on screen (case sensitive, any position in a string)
*
* @param device UiDevice object
* @param clickable clickable if true the search will be restricted to clickable objects
* @param text text to search (case sensitive, uses textContains)
* @param waitForNewWindow set the wait for new window flag if true
* @return true if successful
*/
public static boolean clickTextContains(UiDevice device, boolean clickable, String text, boolean waitForNewWindow) {
Log.w(DEBUG_TAG, "Searching for object with " + text);
//
BySelector bySelector = null;
UiSelector uiSelector = null;
// NOTE order of the selector terms is significant
if (clickable) {
bySelector = By.clickable(true).textContains(text);
uiSelector = new UiSelector().clickable(true).textContains(text);
} else {
bySelector = By.textContains(text);
uiSelector = new UiSelector().textContains(text);
}
device.wait(Until.findObject(bySelector), 500);
UiObject button = device.findObject(uiSelector);
if (button.exists()) {
try {
if (waitForNewWindow) {
button.clickAndWaitForNewWindow();
} else {
button.click();
Log.e(DEBUG_TAG, ".... clicked");
}
return true;
} catch (UiObjectNotFoundException e) {
Log.e(DEBUG_TAG, "Object vanished.");
return false;
}
} else {
Log.e(DEBUG_TAG, "Object not found");
return false;
}
}
/**
* Find text on screen (case insensitive)
*
* @param device UiDevice object
* @param clickable if true the search will be restricted to clickable objects
* @param text the text to find
* @return an UiObject2 or null
*/
@Nullable
public static UiObject2 findText(@NonNull UiDevice device, boolean clickable, @NonNull String text) {
return findText(device, clickable, text, 500);
}
/**
* Find text on screen (case insensitive)
*
* @param device UiDevice object
* @param clickable if true the search will be restricted to clickable objects
* @param text the text to find
* @param waot ms to wait for text to appear
* @return an UiObject2 or null
*/
@Nullable
public static UiObject2 findText(@NonNull UiDevice device, boolean clickable, @NonNull String text, int wait) {
Log.w(DEBUG_TAG, "Searching for object with " + text);
// Note: contrary to "text", "textStartsWith" is case insensitive
BySelector bySelector = null;
if (clickable) {
bySelector = By.clickable(true).textStartsWith(text);
} else {
bySelector = By.textStartsWith(text);
}
return device.wait(Until.findObject(bySelector), wait);
}
/**
* Find text on screen (case sensitive)
*
* @param device UiDevice object
* @param clickable if true the search will be restricted to clickable objects
* @param text the text to find
* @return an UiObject2 or null
*/
@Nullable
public static UiObject2 findTextContains(@NonNull UiDevice device, boolean clickable, @NonNull String text) {
Log.w(DEBUG_TAG, "Searching for object with " + text);
BySelector bySelector = null;
if (clickable) {
bySelector = By.clickable(true).textContains(text);
} else {
bySelector = By.textContains(text);
}
return device.wait(Until.findObject(bySelector), 500);
}
/**
* Click on an object
*
* @param device UiDevice object
* @param clickable if true the search will be restricted to clickable objects
* @param resourceId resource id of the object
* @param waitForNewWindow set the wait for new window flag if true
* @return true if successful
*/
public static boolean clickResource(UiDevice device, boolean clickable, String resourceId, boolean waitForNewWindow) {
Log.w(DEBUG_TAG, "Searching for object with " + resourceId);
// Note: contrary to "text", "textStartsWith" is case insensitive
BySelector bySelector = null;
UiSelector uiSelector = null;
// NOTE order of the selector terms is significant
if (clickable) {
bySelector = By.clickable(true).res(resourceId);
uiSelector = new UiSelector().clickable(true).resourceId(resourceId);
} else {
bySelector = By.res(resourceId);
uiSelector = new UiSelector().resourceId(resourceId);
}
device.wait(Until.findObject(bySelector), 500);
UiObject button = device.findObject(uiSelector);
if (button.exists()) {
try {
if (waitForNewWindow) {
button.clickAndWaitForNewWindow();
} else {
button.click();
Log.e(DEBUG_TAG, ".... clicked");
}
return true;
} catch (UiObjectNotFoundException e) {
Log.e(DEBUG_TAG, "Object vanished.");
return false;
}
} else {
Log.e(DEBUG_TAG, "Object not found");
return false;
}
}
/**
* Double click at an object
*
* @param device the UiDevice
* @param object the object
*/
public static void doubleClick(@NonNull UiDevice device, @NonNull UiObject2 object) {
Configurator cc = Configurator.getInstance();
long defaultAckTimeout = cc.getActionAcknowledgmentTimeout();
cc.setActionAcknowledgmentTimeout(0);
object.click();
try {
Thread.sleep(50); // NOSONAR
} catch (InterruptedException e) {
}
object.click();
cc.setActionAcknowledgmentTimeout(defaultAckTimeout);
}
/**
* Scroll to a specific text
*
* @param text the text
* @throws UiObjectNotFoundException if the UiScrollable couldn't be found
*/
public static void scrollTo(@NonNull String text) {
UiScrollable scrollable = new UiScrollable(new UiSelector().scrollable(true));
try {
scrollable.scrollIntoView(new UiSelector().textStartsWith(text));
} catch (UiObjectNotFoundException e) {
// Assert.fail(text + " not found"); seems to fail if text already in view ....
}
}
}
| 37.806971
| 122
| 0.604595
|
d606fa0756945850814dd16efacefbe7ae76876b
| 449
|
package org.softspiders.pairs;
import java.util.Collections;
import java.util.HashSet;
import java.util.Set;
public class Pairs {
private Set<Pair> pairs = new HashSet<Pair>();
public void addPair(Pair pair) {
pairs.add(pair);
}
public void removePair(Pair pair) {
pairs.remove(pair);
}
public Set<Pair> getPairs() {
return Collections.unmodifiableSet(pairs);
}
public void setPairs(Set<Pair> pairs) {
this.pairs = pairs;
}
}
| 17.269231
| 47
| 0.712695
|
b130d3321b933a1223970a500aa3832a332eee88
| 6,775
|
package tw.osthm;
import android.os.Environment;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.reflect.TypeToken;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
public class osthmManager {
public static final String externalDir = Environment.getExternalStorageDirectory().getAbsolutePath();
public static final String themes_folder = externalDir + "/.os-thm/themes/";
public static final String config_file = externalDir + "/.os-thm/conf";
public static final String exported_themes_folder = externalDir + "/os-thm/";
// Initialize
public static void init() {
// Initialize
// Check if os-thm folder exist
if (!StorageUtil.isDirectoryExists(exported_themes_folder))
StorageUtil.createDirectory(exported_themes_folder);
// Check if .os-thm folder exist
if (!StorageUtil.isDirectoryExists(themes_folder) ||
!StorageUtil.isFileExist(config_file)) {
// Initialize the folder structure
// Create the folder .osthm and .osthm/themes
StorageUtil.createDirectory(themes_folder);
// Create the config file
StorageUtil.createFile(config_file, "{}");
} else {
// Check if the config file is valid or not
try {
if (!isJSONValid(StorageUtil.readFile(config_file)))
StorageUtil.createFile(config_file, "{}");
} catch (IOException ignored) {
}
// Check if the themes are valid or not
List<File> files = StorageUtil.getFiles(themes_folder);
for (File file : files) {
// If the theme is invalid, then delete it
try {
if (!isJSONValid(StorageUtil.readFile(file.getAbsolutePath())))
StorageUtil.deleteFile(file.getAbsolutePath());
else {
// Detect if there are any filename that doesn't matches the UUID, then fix it
HashMap<String, Object> thm = new Gson().fromJson(StorageUtil
.readFile(file.getAbsolutePath()),
new TypeToken<HashMap<String, Object>>() {
}.getType());
if (!(thm.get("uuid").toString() + ".os-thm").equals(file.getName()))
StorageUtil.rename(file.getAbsolutePath(), themes_folder +
thm.get("uuid").toString() + ".os-thm");
}
} catch (IOException ignored) {
}
}
}
}
public static void setConf(String key, String value) {
HashMap<String, String> data = loadConfJson();
data.put(key, value);
StorageUtil.createFile(config_file, new Gson().toJson(data));
}
public static String getConf(String key, String defaultValue) {
HashMap<String, String> data = loadConfJson();
return data.containsKey(key) ? data.get(key) : defaultValue;
}
public static boolean containsConf(String key) {
HashMap<String, String> data = loadConfJson();
return data.containsKey(key);
}
public static void removeConf(String key) throws IOException {
HashMap<String, String> data = loadConfJson();
if (data.containsKey(key)) {
data.remove(key);
StorageUtil.createFile(config_file, new Gson().toJson(data));
}
}
public static void clearConf() {
StorageUtil.createFile(config_file, "{}");
}
public static void setTheme(HashMap<String, Object> theme) {
StorageUtil.createFile(themes_folder + theme.get("uuid").toString() + ".os-thm",
new Gson().toJson(theme));
}
public static ArrayList<HashMap<String, Object>> getThemes() {
List<File> files = StorageUtil.getFiles(themes_folder);
ArrayList<HashMap<String, Object>> themes = new ArrayList<>();
GsonBuilder gsonBuilder = new GsonBuilder();
gsonBuilder.registerTypeAdapter(new TypeToken<HashMap<String, Object>>() {
}.getType(),
new HashMapDeserializerFix());
Gson gson = gsonBuilder.create();
for (File file : files) {
try {
themes.add((HashMap<String, Object>) gson.fromJson(StorageUtil
.readFile(file.getAbsolutePath()),
new TypeToken<HashMap<String, Object>>() {
}.getType()));
} catch (IOException ignored) {
}
}
return themes;
}
public static void removeTheme(String uuid) {
if (StorageUtil.isFileExist(themes_folder + uuid + ".os-thm"))
StorageUtil.deleteFile(themes_folder + uuid + ".os-thm");
}
public static void clearThemes() {
List<File> files = StorageUtil.getFiles(themes_folder);
for (File file : files)
StorageUtil.deleteFile(file.getAbsolutePath());
}
public static boolean containsTheme(String uuid) {
List<File> files = StorageUtil.getFiles(themes_folder);
for (File file : files) {
if (file.getName().equals(uuid + ".os-thm")) {
return true;
}
}
return false;
}
public static String exportThemeFile(String json) {
int fileNum = 0;
while (true) {
if (StorageUtil.isFileExist(exported_themes_folder + "theme_" + Integer.toString(fileNum) + ".os-thm"))
fileNum++;
else {
StorageUtil.createFile(exported_themes_folder + "theme_" + Integer.toString(fileNum) + ".os-thm", json);
return exported_themes_folder + "theme_" + Integer.toString(fileNum) + ".os-thm";
}
}
}
// Utilities ===================================================================================
// Load config file into HashMap
private static HashMap<String, String> loadConfJson() {
try {
return new Gson().fromJson(StorageUtil.readFile(config_file),
new TypeToken<HashMap<String, String>>() {
}.getType());
} catch (IOException e) {
return null;
}
}
// Check if the JSON is valid or not
private static boolean isJSONValid(String test) {
try {
new JSONObject(test);
} catch (JSONException ex) {
return false;
}
return true;
}
}
| 36.820652
| 120
| 0.569004
|
93050441443a4fe13789bed1589a61cfd97cbf85
| 908
|
package reflectx.annotations;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* Catch exceptions that might occur in the proxy interface implementation class method,
* return the default value if the method has a return value or {@code null}.
*
* @author zpp0196
*/
@Retention(RetentionPolicy.SOURCE)
@Target(ElementType.METHOD)
public @interface RunWithCatch {
byte byteValue() default Byte.MAX_VALUE;
short shortValue() default Short.MIN_VALUE;
int intValue() default Integer.MIN_VALUE;
long longValue() default Long.MIN_VALUE;
float floatValue() default Float.MIN_VALUE;
double doubleValue() default Double.MIN_VALUE;
boolean booleanValue() default false;
char charValue() default Character.MIN_VALUE;
String stringValue() default "";
}
| 25.942857
| 88
| 0.759912
|
f77c9d8324c1d86c1c1e2084e8ca5498c99b3b90
| 8,099
|
package com.github.yamill.orientation;
import android.app.Activity;
import android.content.pm.ActivityInfo;
import android.graphics.Point;
import android.hardware.SensorManager;
import android.provider.Settings;
import android.view.Display;
import android.view.OrientationEventListener;
import java.util.HashMap;
import java.util.Map;
import javax.annotation.Nullable;
import com.facebook.react.bridge.Arguments;
import com.facebook.react.bridge.Callback;
import com.facebook.react.bridge.LifecycleEventListener;
import com.facebook.react.bridge.ReactApplicationContext;
import com.facebook.react.bridge.ReactContextBaseJavaModule;
import com.facebook.react.bridge.ReactMethod;
import com.facebook.react.bridge.WritableMap;
import com.facebook.react.modules.core.DeviceEventManagerModule;
public class OrientationModule extends ReactContextBaseJavaModule implements LifecycleEventListener {
final OrientationEventListener mOrientationEventListener;
private Integer mOrientationValue;
private String mOrientation;
private String mSpecificOrientation;
final private String[] mOrientations;
private boolean mHostActive = false;
public static final String LANDSCAPE = "LANDSCAPE";
public static final String LANDSCAPE_LEFT = "LANDSCAPE-LEFT";
public static final String LANDSCAPE_RIGHT = "LANDSCAPE-RIGHT";
public static final String PORTRAIT = "PORTRAIT";
public static final String PORTRAIT_UPSIDEDOWN = "PORTRAITUPSIDEDOWN";
public static final String ORIENTATION_UNKNOWN = "UNKNOWN";
private static final int ACTIVE_SECTOR_SIZE = 45;
private final String[] ORIENTATIONS_PORTRAIT_DEVICE = {PORTRAIT, LANDSCAPE_RIGHT, PORTRAIT_UPSIDEDOWN, LANDSCAPE_LEFT};
private final String[] ORIENTATIONS_LANDSCAPE_DEVICE = {LANDSCAPE_LEFT, PORTRAIT, LANDSCAPE_RIGHT, PORTRAIT_UPSIDEDOWN};
public OrientationModule(ReactApplicationContext reactContext) {
super(reactContext);
final ReactApplicationContext ctx = reactContext;
mOrientations = isLandscapeDevice() ? ORIENTATIONS_LANDSCAPE_DEVICE : ORIENTATIONS_PORTRAIT_DEVICE;
mOrientationEventListener = new OrientationEventListener(reactContext,
SensorManager.SENSOR_DELAY_NORMAL) {
@Override
public void onOrientationChanged(int orientationValue) {
if (!mHostActive || isDeviceOrientationLocked() || !ctx.hasActiveCatalystInstance())
return;
mOrientationValue = orientationValue;
if (mOrientation != null && mSpecificOrientation != null) {
final int halfSector = ACTIVE_SECTOR_SIZE / 2;
if ((orientationValue % 90) > halfSector
&& (orientationValue % 90) < (90 - halfSector)) {
return;
}
}
final String orientation = getOrientationString(orientationValue);
final String specificOrientation = getSpecificOrientationString(orientationValue);
final DeviceEventManagerModule.RCTDeviceEventEmitter deviceEventEmitter = ctx.getJSModule(DeviceEventManagerModule.RCTDeviceEventEmitter.class);
if (!orientation.equals(mOrientation)) {
mOrientation = orientation;
WritableMap params = Arguments.createMap();
params.putString("orientation", orientation);
deviceEventEmitter.emit("orientationDidChange", params);
}
if (!specificOrientation.equals(mSpecificOrientation)) {
mSpecificOrientation = specificOrientation;
WritableMap params = Arguments.createMap();
params.putString("specificOrientation", specificOrientation);
deviceEventEmitter.emit("specificOrientationDidChange", params);
}
}
};
ctx.addLifecycleEventListener(this);
if (mOrientationEventListener.canDetectOrientation()) {
mOrientationEventListener.enable();
}
}
@ReactMethod
public void isOrientationLockedBySystem(Callback callback) {
try {
if (Settings.System.getInt(
getReactApplicationContext().getContentResolver(), Settings.System.ACCELEROMETER_ROTATION
) == 1) {
callback.invoke(null, false);
} else {
callback.invoke(null, true);
};
} catch (Settings.SettingNotFoundException e) {
callback.invoke(e, null);
}
}
@Override
public String getName() {
return "Orientation";
}
@ReactMethod
public void getOrientation(Callback callback) {
callback.invoke(null, mOrientation);
}
@ReactMethod
public void lockToPortrait() {
final Activity activity = getCurrentActivity();
if (activity == null) {
return;
}
activity.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
}
@ReactMethod
public void lockToLandscape() {
final Activity activity = getCurrentActivity();
if (activity == null) {
return;
}
activity.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_SENSOR_LANDSCAPE);
}
@ReactMethod
public void lockToLandscapeLeft() {
final Activity activity = getCurrentActivity();
if (activity == null) {
return;
}
activity.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
}
@ReactMethod
public void lockToLandscapeRight() {
final Activity activity = getCurrentActivity();
if (activity == null) {
return;
}
activity.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_REVERSE_LANDSCAPE);
}
@ReactMethod
public void unlockAllOrientations() {
final Activity activity = getCurrentActivity();
if (activity == null) {
return;
}
activity.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED);
}
@Override
public
@Nullable
Map<String, Object> getConstants() {
HashMap<String, Object> constants = new HashMap<String, Object>();
constants.put("initialOrientation", mOrientation);
return constants;
}
private boolean isDeviceOrientationLocked() {
final Activity activity = getCurrentActivity();
if (activity == null) {
return false;
}
return Settings.System.getInt(
activity.getContentResolver(),
Settings.System.ACCELEROMETER_ROTATION, 0
) == 0;
}
private boolean isLandscapeDevice() {
final Activity activity = getCurrentActivity();
if (activity == null) {
return false;
}
Display display = activity.getWindowManager().getDefaultDisplay();
Point size = new Point();
display.getSize(size);
return size.x > size.y;
}
private String getSpecificOrientationString(int orientationValue) {
if (orientationValue < 0) return ORIENTATION_UNKNOWN;
final int index = (int) ((float) orientationValue / 90.0 + 0.5) % 4;
return mOrientations[index];
}
private String getOrientationString(int orientationValue) {
final String specificOrientation = getSpecificOrientationString(orientationValue);
switch (specificOrientation) {
case LANDSCAPE_LEFT:
case LANDSCAPE_RIGHT:
return LANDSCAPE;
case PORTRAIT:
case PORTRAIT_UPSIDEDOWN:
return PORTRAIT;
default:
return ORIENTATION_UNKNOWN;
}
}
@Override
public void onHostResume() {
mHostActive = true;
}
@Override
public void onHostPause() {
mHostActive = false;
}
@Override
public void onHostDestroy() {
mHostActive = false;
}
}
| 35.213043
| 160
| 0.654155
|
2ceee8686c8774c55dc4c06b35198348236d57bb
| 1,355
|
package ch.wisv.toornament.model;
import ch.wisv.toornament.model.enums.MatchStatus;
import com.fasterxml.jackson.annotation.JsonAnyGetter;
import com.fasterxml.jackson.annotation.JsonAnySetter;
import com.fasterxml.jackson.annotation.JsonFormat;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class Game {
private int number;
private MatchStatus status;
private List<Opponent> opponents;
private Map<String, Object[]> disciplineFields = new HashMap<>();
public int getNumber() {
return number;
}
public void setNumber(int number) {
this.number = number;
}
public MatchStatus getStatus() {
return status;
}
public void setStatus(MatchStatus status) {
this.status = status;
}
public List<Opponent> getOpponents() {
return opponents;
}
public void setOpponents(List<Opponent> opponents) {
this.opponents = opponents;
}
// Capture all other fields that Jackson do not match other members
@JsonAnyGetter
public Map<String, Object[]> otherFields() {
return disciplineFields;
}
@JsonAnySetter
@JsonFormat(with = JsonFormat.Feature.ACCEPT_SINGLE_VALUE_AS_ARRAY)
public void setOtherField(String name, Object[] value) {
disciplineFields.put(name, value);
}
}
| 24.196429
| 71
| 0.692251
|
4270d7d2388beaaa2f9b432a7c19930748aa99cd
| 170
|
class A {
static {
Runnable runnable = new Runnable() {
public void run() {
}
};
System.out.println(runnable);
}
}
| 18.888889
| 44
| 0.447059
|
3def1ea8d7e4e87fe84b5ff8817e3531ca386415
| 1,528
|
package io.perfeccionista.framework.pagefactory.factory.proxy;
import io.perfeccionista.framework.exceptions.ElementMethodNotImplemented;
import io.perfeccionista.framework.exceptions.attachments.MobileElementAttachmentEntry;
import io.perfeccionista.framework.pagefactory.elements.base.MobileChildElement;
import io.perfeccionista.framework.pagefactory.elements.base.MobileParentElement;
import net.sf.cglib.proxy.InvocationHandler;
import java.lang.reflect.Method;
import static io.perfeccionista.framework.exceptions.messages.PageFactoryApiMessages.ELEMENT_METHOD_NOT_IMPLEMENTED;
public class MobileParentElementInvocationHandler implements InvocationHandler {
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
MobileParentElement element = ((MobileParentElement) proxy);
if (isElementMethod(method)) {
return element.getElementRegistry()
.getRequiredElementByMethod(method);
}
// TODO: Добавить в сообщение об ошибке имя класса в котором вызывается метод
throw ElementMethodNotImplemented.exception(ELEMENT_METHOD_NOT_IMPLEMENTED.getMessage(method.getName()))
.addLastAttachmentEntry(MobileElementAttachmentEntry.of(element));
}
/**
* Проверяем, что метод возвращает элемент
* @param method
* @return
*/
private boolean isElementMethod(Method method) {
return MobileChildElement.class.isAssignableFrom(method.getReturnType());
}
}
| 40.210526
| 116
| 0.768979
|
e8a3ca203a43f7f529384d2b7a0e4043e684c01e
| 8,991
|
/*************************************************************************
* *
* Open Dynamics Engine, Copyright (C) 2001,2002 Russell L. Smith. *
* All rights reserved. Email: russ@q12.org Web: www.q12.org *
* Open Dynamics Engine 4J, Copyright (C) 2009-2014 Tilmann Zaeschke *
* All rights reserved. Email: ode4j@gmx.de Web: www.ode4j.org *
* *
* This library is free software; you can redistribute it and/or *
* modify it under the terms of EITHER: *
* (1) 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. The text of the GNU Lesser *
* General Public License is included with this library in the *
* file LICENSE.TXT. *
* (2) The BSD-style license that is included with this library in *
* the file ODE-LICENSE-BSD.TXT and ODE4J-LICENSE-BSD.TXT. *
* *
* 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 files *
* LICENSE.TXT, ODE-LICENSE-BSD.TXT and ODE4J-LICENSE-BSD.TXT for more *
* details. *
* *
*************************************************************************/
package org.ode4j.ode;
import org.ode4j.math.DVector3;
import org.ode4j.math.DVector3C;
/**
* ****************************************************************************<br>
* Piston <br>
* <br>
* ****************************************************************************<br>
* Component of a Piston joint
* <PRE>
* |- Anchor point
* Body_1 | Body_2
* +---------------+ V +------------------+
* / /| / /|
* / / + |-- ______ / / +
* / x /./........x.......(_____()..../ x /.......> axis
* +---------------+ / |-- +------------------+ /
* | |/ | |/
* +---------------+ +------------------+
* | |
* | |
* |------------------> <----------------------------|
* anchor1 anchor2
*
*
* </PRE>
*
* When the prismatic joint as been elongated (i.e. dJointGetPistonPosition)
* return a value > 0
* <PRE>
* |- Anchor point
* Body_1 | Body_2
* +---------------+ V +------------------+
* / /| / /|
* / / + |-- ______ / / +
* / x /./........_____x.......(_____()..../ x /.......> axis
* +---------------+ / |-- +------------------+ /
* | |/ | |/
* +---------------+ +------------------+
* | |
* | |
* |----------------.> <----------------------------|
* anchor1 |----| anchor2
* ^
* |-- This is what dJointGetPistonPosition will
* return
* </PRE>
* ****************************************************************************
*/
public interface DPistonJoint extends DJoint {
/**
* Set the joint anchor.
* @param x x
* @param y y
* @param z z
*/
void setAnchor (double x, double y, double z);
/**
* Set the joint anchor.
* @param a a
*/
void setAnchor (DVector3C a);
/**
* Get the joint anchor.
* <p>
* This returns the point on body 1. If the joint is perfectly satisfied,
* this will be the same as the point on body 2 in direction perpendicular
* to the prismatic axis.
* @param result Object that returns the result after calling this method
*/
void getAnchor (DVector3 result);
/**
* Get the joint anchor wrt body 2.
* <p>
* This returns the point on body 2. You can think of a Piston
* joint as trying to keep the result of dJointGetPistonAnchor() and
* dJointGetPistonAnchor2() the same in the direction perpendicular to the
* prismatic axis. If the joint is perfectly satisfied,
* this function will return the same value as dJointGetPistonAnchor() to
* within roundoff errors. dJointGetPistonAnchor2() can be used, along with
* dJointGetPistonAnchor(), to see how far the joint has come apart.
* @param result Object that returns the result after calling this method
*/
void getAnchor2 (DVector3 result);
/**
* Set the Piston anchor as if the 2 bodies were already at [dx,dy, dz] apart.
* <p>
* This function initialize the anchor and the relative position of each body
* as if the position between body1 and body2 was already the projection of [dx, dy, dz]
* along the Piston axis. (i.e as if the body1 was at its current position - [dx,dy,dy] when the
* axis is set).
* Ex: <br>
* <code>
* double offset = 3; <br>
* dVector3 axis; <br>
* dJointGetPistonAxis(jId, axis); <br>
* dJointSetPistonAnchor(jId, 0, 0, 0); <br>
* // If you request the position you will have: dJointGetPistonPosition(jId) == 0 <br>
* dJointSetPistonAnchorOffset(jId, 0, 0, 0, axis[X]*offset, axis[Y]*offset, axis[Z]*offset); <br>
* // If you request the position you will have: dJointGetPistonPosition(jId) == offset <br>
* </code>
*
* @param xyz The X, Y and Z position of the anchor point in world frame
* @param dx A delta to be substracted to the X position as if the anchor was set
* when body1 was at current_position[X] - dx
* @param dy A delta to be substracted to the Y position as if the anchor was set
* when body1 was at current_position[Y] - dy
* @param dz A delta to be substracted to the Z position as if the anchor was set
* when body1 was at current_position[Z] - dz
*/
void setAnchorOffset(DVector3C xyz, double dx, double dy, double dz);
/**
* Set the joint axis.
* @param x x
* @param y y
* @param z z
*/
void setAxis (double x, double y, double z);
/**
* Set the joint axis.
* @param a a
*/
void setAxis (DVector3C a);
/**
* Get the prismatic axis (This is also the rotoide axis.
* @param result Object that returns the result after calling this method
*/
void getAxis (DVector3 result);
/**
* Get the Piston linear position (i.e. the piston's extension).
* <p>
* When the axis is set, the current position of the attached bodies is
* examined and that position will be the zero position.
* @return position
*/
double getPosition();
/**
* Get the piston linear position's time derivative.
* @return rate
*/
double getPositionRate();
/**
* Applies the given force in the slider's direction.
* <p>
* That is, it applies a force with specified magnitude, in the direction of
* prismatic's axis, to body1, and with the same magnitude but opposite
* direction to body2. This function is just a wrapper for dBodyAddForce().
* @param force force
*/
void addForce (double force);
double getParamLoStop2();
double getParamHiStop2();
void setParamLoStop2(double d);
void setParamHiStop2(double d);
/**
* Get the Piston angular position (i.e. the twist between the 2 bodies).
* <p>
* When the axis is set, the current position of the attached bodies is
* examined and that position will be the zero position.
* @return angle
*/
double getAngle();
/**
* Get the piston angular position's time derivative.
* @return angle
*/
double getAngleRate();
/**
* Set joint parameter.
*/
@Override
void setParam (PARAM_N parameter, double value);
/**
* Get joint parameter.
*/
@Override
double getParam (PARAM_N parameter);
}
| 38.423077
| 100
| 0.467245
|
c7d118c0ef3e8feef2987e889903e0394e9ee159
| 664
|
package neuronet.copy;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
public class EMFProvider {
private static final EMFProvider singleton = new EMFProvider();
private EntityManagerFactory emf;
private EMFProvider() {
}
public static EMFProvider getInstance() {
return singleton;
}
public EntityManagerFactory getEntityManagerFactory(String persistenceUnitName) {
if (emf == null) {
emf = Persistence.createEntityManagerFactory(persistenceUnitName);
}
return emf;
}
public void closeEntityManagerFactory() {
if (emf != null) {
emf.close();
}
emf = null;
}
}
| 20.75
| 83
| 0.715361
|
27d1170d9ed3315fcd7d2a95c52e5be4d40726c1
| 2,919
|
package org.motechproject.security.authentication;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.ArgumentCaptor;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.runners.MockitoJUnitRunner;
import org.motechproject.security.domain.MotechUser;
import org.motechproject.security.helper.SessionHandler;
import org.motechproject.security.config.SettingService;
import org.motechproject.security.repository.AllMotechUsers;
import org.springframework.security.core.Authentication;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import static org.junit.Assert.assertEquals;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
@RunWith(MockitoJUnitRunner.class)
public class MotechLoginSuccessHandlerTest {
@InjectMocks
private MotechLoginSuccessHandler motechLoginSuccessHandler = new MotechLoginSuccessHandler();
@Mock
AllMotechUsers allMotechUsers;
@Mock
private SettingService settingService;
@Mock
private SessionHandler sessionHandler;
@Mock
private HttpSession session;
@Mock
private HttpServletRequest request;
@Mock
private HttpServletResponse response;
@Mock
private Authentication authentication;
ArgumentCaptor<MotechUser> userCaptor = ArgumentCaptor.forClass(MotechUser.class);
@Test
public void shouldSetSessionTimeoutAndStore() throws ServletException, IOException {
MotechUser user = new MotechUser();
user.setUserName("testUser");
user.setFailureLoginCounter(3);
when(authentication.getName()).thenReturn("testUser");
when(allMotechUsers.findByUserName("testUser")).thenReturn(user);
when(request.getSession()).thenReturn(session);
when(settingService.getSessionTimeout()).thenReturn(500);
motechLoginSuccessHandler.onAuthenticationSuccess(request, response, authentication);
verify(session).setMaxInactiveInterval(500);
verify(sessionHandler).addSession(session);
}
@Test
public void shouldResetFailureLoginCounter() throws ServletException, IOException {
MotechUser user = new MotechUser();
user.setUserName("testUser");
user.setFailureLoginCounter(3);
when(authentication.getName()).thenReturn("testUser");
when(allMotechUsers.findByUserName("testUser")).thenReturn(user);
when(request.getSession()).thenReturn(session);
when(settingService.getSessionTimeout()).thenReturn(500);
motechLoginSuccessHandler.onAuthenticationSuccess(request, response, authentication);
verify(allMotechUsers).update(userCaptor.capture());
assertEquals((Integer)0, userCaptor.getValue().getFailureLoginCounter());
}
}
| 33.170455
| 98
| 0.764303
|
15458cf5fe10f594533cb400a6733afe637ca57a
| 807
|
package io.boodskap.iot.spi.storage.jpa;
import io.boodskap.iot.StorageException;
import io.boodskap.iot.dao.RawDataDAO;
import io.boodskap.iot.model.jpa.RawData;
import io.boodskap.iot.spi.storage.IRawStorage;
import io.boodskap.iot.spi.storage.jpa.dao.RawDataDAOImpl;
public class JPARawStorage implements IRawStorage {
protected JPARawStorage() {
}
@Override
public boolean isPaginationSupported() {
return true;
}
@Override
public boolean isSearchSupported() {
return true;
}
@Override
public String getVendorInfo() {
return "JPA (Java Persistence Architecture)";
}
@Override
public String getVersion() {
return "2.1.1";
}
@SuppressWarnings("unchecked")
@Override
public RawDataDAO<RawData> getRawDataDAO() throws StorageException {
return RawDataDAOImpl.get();
}
}
| 19.682927
| 69
| 0.758364
|
541a947c1e766686c23b3e47a0e1eb8114d7a2b1
| 4,872
|
/*
* The MIT License
*
* Copyright 2018 d471061c.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.d471061c.dungeonviz.logic;
import com.d471061c.dungeonviz.domain.Dungeon;
import com.d471061c.dungeonviz.domain.Edge;
import com.d471061c.dungeonviz.domain.PrimObject;
import com.d471061c.dungeonviz.domain.Room;
import com.d471061c.dungeonviz.domain.datastructures.PrimObjectHeap;
/**
* Dungeon generator
*
* @author d471061c
*/
public class DungeonGenerator {
private final int INFINITY = 999999;
private RoomFactory roomFactory;
private DungeonVisualizer visualizer;
/**
* Dungeon Generator
*
* @param roomFactory Factory that provides the rooms
* @see RoomFactory
*/
public DungeonGenerator(RoomFactory roomFactory) {
this.roomFactory = roomFactory;
this.visualizer = new DungeonVisualizer();
}
public DungeonGenerator() {
this(new RoomFactory());
}
/**
*
* Get minimum spanning tree with Prim's algorithm
*
* @param rooms Rooms which to be connected
* @return Minimum spanning tree represented as edges
*/
private Edge[] primAlgorithm(Room rooms[]) {
// Generate the graph from given rooms
// ID of each room is the index in which the room is located at.
int rootIndex = 0;
PrimObjectHeap heap = new PrimObjectHeap(rooms.length);
PrimObject objects[] = new PrimObject[rooms.length];
Room parent[] = new Room[rooms.length];
// Initialize all objects
for (int i = 0; i < rooms.length; i++) {
parent[i] = null;
objects[i] = new PrimObject(rooms[i], this.INFINITY, i);
}
objects[rootIndex].setValue(0);
// Insert all prim objects to heap
for (PrimObject object : objects) {
heap.insert(object);
}
// Edges between rooms
Edge edges[] = new Edge[rooms.length - 1];
int edgePointer = 0;
// Actual Prim's Algorithm
while (!heap.isEmpty()) {
// Delete the minimum
PrimObject currentObject = heap.deleteMin();
// Add edge
if (parent[currentObject.getIndex()] != null) {
Edge edge = new Edge(currentObject.getRoom(), parent[currentObject.getIndex()]);
edges[edgePointer] = edge;
edgePointer++;
}
// Go through all the rooms
for (int i = 0; i < objects.length; i++) {
// No paths to self
if (currentObject.getIndex() != i) {
double distance = currentObject.getRoom().distance(objects[i].getRoom());
if (distance < objects[i].getValue() && heap.contains(objects[i])) {
parent[i] = currentObject.getRoom();
objects[i].setValue(distance);
heap.update(objects[i]);
}
}
}
}
return edges;
}
/**
* Generate a dungeon with given number of rooms.
*
* @param rooms Amount of rooms
* @return Generated dungeon
*/
public Dungeon generateDungeon(int rooms) {
Room dungeonRooms[] = new Room[rooms];
for (int i = 0; i < rooms; i++) {
Room room = this.roomFactory.produceRoom();
dungeonRooms[i] = room;
}
// Calculate the edges between the rooms
Edge edges[] = primAlgorithm(dungeonRooms);
char[][] map = visualizer.createMap(dungeonRooms, edges);
return new Dungeon(dungeonRooms, map);
}
}
| 34.309859
| 97
| 0.597906
|
6303fec36fbde34f99fa7ca089553d4696bd74a3
| 572
|
package com.networkedassets.git4c.infrastructure.database.ao;
import net.java.ao.Entity;
import net.java.ao.Preload;
import net.java.ao.schema.Table;
@Table("RepositoryUsages")
@Preload
public interface RepositoryUsageEntity extends Entity {
String getUuid();
void setUuid(String uuid);
String getUsername();
void setUsername(String name);
String getRepository();
void setRepository(String repositoryUuid);
String getRepositoryName();
void setRepositoryName(String repositoryUuid);
Long getDate();
void setDate(Long date);
}
| 22
| 61
| 0.744755
|
bd2903bffae1b041582af6c9369f6e2212150fe2
| 214
|
package br.com.gabriel.logica;
import br.com.gabriel.poo.Funcionario;
public class FuncionarioExterno {
public static void main(String[] args) {
Funcionario f = new Funcionario();
f.nome = "Roberto";
}
}
| 17.833333
| 41
| 0.719626
|
33675f2f462df5049c4beadbc21415b26ba8a480
| 1,992
|
/*
* Copyright 2011 DTO Solutions, Inc. (http://dtosolutions.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.
*/
/*
* TestPoliciesYaml.java
*
* User: Greg Schueler <a href="mailto:greg@dtosolutions.com">greg@dtosolutions.com</a>
* Created: 8/25/11 10:18 AM
*
*/
package com.dtolabs.rundeck.core.authorization.providers;
import junit.framework.TestCase;
import java.io.File;
import java.util.*;
/**
* TestPoliciesYaml is ...
*
* @author Greg Schueler <a href="mailto:greg@dtosolutions.com">greg@dtosolutions.com</a>
*/
public class TestPoliciesYaml extends TestCase {
File testdir;
File test1;
File test2;
public void setUp() throws Exception {
testdir = new File("src/test/com/dtolabs/rundeck/core/authorization/providers");
test1 = new File(testdir, "test1.yaml");
test2 = new File(testdir, "test2.yaml");
}
public void tearDown() throws Exception {
}
public void testCountPolicies() throws Exception {
PoliciesYaml policies = new PoliciesYaml(test1);
assertEquals(2, policies.countPolicies());
}
public void testGroupNames() throws Exception {
PoliciesYaml policies = new PoliciesYaml(test1);
final Collection<String> strings = policies.groupNames();
assertEquals(3, strings.size());
assertTrue(strings.contains("qa_group"));
assertTrue(strings.contains("prod_group"));
assertTrue(strings.contains("dev_group"));
}
}
| 30.181818
| 89
| 0.693775
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.