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
7756bb4fb7eb066ead9df2809f090f53b3de8608
683
/** * Create with IntelliJ IDEA * Project name : final * Package name : org.wukm.service * Author : Wukunmeng * User : wukm * Date : 18-6-7 * Time : 上午11:19 * --------------------------------- */ package org.wukm.service; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * Create with IntelliJ IDEA * Project name : final * Package name : org.wukm.service * Author : Wukunmeng * User : wukm * Date : 18-6-7 * Time : 上午11:19 * --------------------------------- * To change this template use File | Settings | File and Code Templates. */ public abstract class CommonService { protected Logger logger = LoggerFactory.getLogger(this.getClass()); }
21.34375
73
0.612006
6fd37430e804756071b5dadb4ae1e82bee82be3f
18,565
package vserver.impl; import vjson.JSON; import vproxybase.connection.NetEventLoop; import vproxybase.connection.ServerSock; import vproxybase.http.HttpContext; import vproxybase.http.HttpProtocolHandler; import vproxybase.processor.http1.entity.Chunk; import vproxybase.processor.http1.entity.Header; import vproxybase.processor.http1.entity.Request; import vproxybase.processor.http1.entity.Response; import vproxybase.protocol.ProtocolHandlerContext; import vproxybase.protocol.ProtocolServerConfig; import vproxybase.protocol.ProtocolServerHandler; import vproxybase.util.*; import vserver.*; import vserver.route.WildcardSubPath; import java.io.IOException; import java.util.*; import java.util.stream.Collectors; import static vserver.HttpMethod.ALL_METHODS; public class Http1ServerImpl extends AbstractServer implements HttpServer { private boolean started = false; private final Map<HttpMethod, Tree<SubPath, RoutingHandler>> routes = new HashMap<>(HttpMethod.values().length) {{ for (HttpMethod m : HttpMethod.values()) { put(m, new Tree<>()); } }}; public Http1ServerImpl() { } public Http1ServerImpl(NetEventLoop loop) { super(loop); } @Override protected String threadname() { return "http-1-server"; } private void record(Tree<SubPath, RoutingHandler> tree, SubPath subpath, RoutingHandler handler) { // null means this sub-path is '/' which is the end of this route if (subpath == null) { tree.leaf(handler); return; } // check the last branch // note: here we only check the LAST branch because we need to preserve the handling order // consider this situation: // 1. handle(..., /a/b, ...) registers /a/b // 2. handle(..., /a/:x, ...) registers /a/:x // 3. handle(..., /a/b, ...) registers /a/b // we must NOT add the 3rd path to the branch of the 1st path because if so we will get order 1st,3rd,2nd // instead of the expected order 1st,2nd,3rd var last = tree.lastBranch(); if (last != null && last.data.currentSame(subpath)) { // can use the last node record(last, subpath.next(), handler); return; } // must be new route var br = tree.branch(subpath); record(br, subpath.next(), handler); } private void record(HttpMethod[] methods, SubPath route, RoutingHandler handler) { for (HttpMethod m : methods) { record(routes.get(m), route, handler); } } @Override public HttpServer handle(HttpMethod[] methods, SubPath route, RoutingHandler handler) { if (started) { throw new IllegalStateException("This http server is already started"); } record(methods, route, handler); return this; } private void preListen() { if (started) { throw new IllegalStateException("This http server is already started"); } started = true; record(ALL_METHODS, SubPath.create("/*"), this::handle404); } public void listen(ServerSock server) throws IOException { if (loop == null) { throw new IllegalStateException("loop not specified but listen(ServerSock) is called"); } preListen(); ProtocolServerHandler.apply(loop, server, new ProtocolServerConfig().setInBufferSize(4096).setOutBufferSize(4096), new HttpProtocolHandler(true) { @Override protected void request(ProtocolHandlerContext<HttpContext> ctx) { handle(ctx); } }); } private void handle404(RoutingContext ctx) { ctx.response() .status(404) .end(ByteArray.from(("Cannot " + ctx.method() + " " + ctx.uri() + "\r\n").getBytes())); } private void sendResponse(ProtocolHandlerContext<HttpContext> _pctx, Response response) { if (response.headers == null) { response.headers = new ArrayList<>(2); // may add // x-powered-by // content-length } boolean needAddServerId = true; for (Header h : response.headers) { if (h.key.equalsIgnoreCase("x-powered-by")) { needAddServerId = false; break; } } if (needAddServerId) { response.headers.add(new Header("X-Powered-By", "vproxy/" + Version.VERSION)); } // fill in default values if (response.version == null) { response.version = "HTTP/1.1"; } if (response.statusCode == 0) { response.statusCode = 200; response.reason = "OK"; } boolean chunked = false; for (Header h : response.headers) { if (h.key.equalsIgnoreCase("transfer-encoding")) { if (h.value.equalsIgnoreCase("chunked")) { chunked = true; break; } } } if (!chunked) { if (response.body == null) { response.headers.add(new Header("Content-Length", "0")); } else { response.headers.add(new Header("Content-Length", Integer.toString(response.body.length()))); } } _pctx.write(response.toByteArray().toJavaArray()); } private void handle(ProtocolHandlerContext<HttpContext> _pctx) { Request request = _pctx.data.result; RoutingContext[] ctx = new RoutingContext[1]; { final HttpMethod method; final Map<String, String> headers = new HashMap<>(); final String uri = unescape(request.uri); final Map<String, String> query = new HashMap<>(); final ByteArray body; final HttpResponse response; final HandlerChain chain; final List<String> paths; { // paths and query if (uri == null) { Response resp = new Response(); resp.statusCode = 400; resp.reason = "Bad Request"; resp.body = ByteArray.from("Bad Request: invalid uri\r\n".getBytes()); sendResponse(_pctx, resp); return; } String path = uri; String queryPart = ""; if (path.contains("?")) { queryPart = path.substring(path.indexOf('?') + 1); path = path.substring(0, path.indexOf('?')); } paths = Arrays.stream(path.split("/")).map(String::trim).filter(s -> !s.isEmpty()).collect(Collectors.toList()); var queryList = Arrays.stream(queryPart.split("&")).filter(s -> !s.isBlank()).collect(Collectors.toList()); for (var qkv : queryList) { if (qkv.indexOf('=') == -1) { query.put(qkv, ""); } else { int idx = qkv.indexOf('='); query.put(qkv.substring(0, idx), qkv.substring(idx + 1)); } } } { // method try { method = HttpMethod.valueOf(request.method); } catch (RuntimeException e) { Response resp = new Response(); resp.statusCode = 400; resp.reason = "Bad Request"; resp.body = ByteArray.from("Bad Request: invalid method\r\n".getBytes()); sendResponse(_pctx, resp); return; } } { // uri if (!uri.startsWith("/")) { Response resp = new Response(); resp.statusCode = 400; resp.reason = "Bad Request"; resp.body = ByteArray.from("Bad Request: invalid uri\r\n".getBytes()); sendResponse(_pctx, resp); return; } } { // headers if (request.headers != null) { for (Header h : request.headers) { headers.put(h.key.toLowerCase(), h.value); } } if (request.trailers != null) { for (Header h : request.trailers) { headers.put(h.key.toLowerCase(), h.value); } } } { // body if (request.body != null) { body = request.body; } else if (request.chunks != null) { ByteArray foo = null; for (Chunk c : request.chunks) { if (foo == null) { foo = c.content; } else { foo = foo.concat(c.content); } } body = foo; } else { body = null; } } { // response response = new HttpResponse() { final Response response = new Response(); boolean isEnd = false; boolean headersSent = false; boolean allowChunked = false; @Override public HttpResponse status(int code, String msg) { if (isEnd) { throw new IllegalStateException("This response is already ended"); } if (headersSent) { throw new IllegalStateException("Headers of this response is already sent"); } response.statusCode = code; response.reason = msg; return this; } @Override public HttpResponse header(String key, String value) { if (isEnd) { throw new IllegalStateException("This response is already ended"); } if (headersSent) { throw new IllegalStateException("Headers of this response is already sent"); } if (response.headers == null) { response.headers = new LinkedList<>(); } response.headers.add(new Header(key, value)); return this; } @Override public HttpResponse sendHeadersWithChunked() { if (headersSent) { throw new IllegalStateException("Headers of this response is already sent"); } if (response.headers == null) { response.headers = new LinkedList<>(); } boolean hasTransferEncoding = false; String transferEncoding = "chunked"; for (Header h : response.headers) { if (h.key.toLowerCase().equals("transfer-encoding")) { hasTransferEncoding = true; transferEncoding = h.value; break; } } if (!transferEncoding.equals("chunked")) { throw new IllegalStateException("The response has Transfer-Encoding set to " + transferEncoding + ", cannot run in chunked mode"); } if (!hasTransferEncoding) { response.headers.add(new Header("Transfer-Encoding", transferEncoding)); } headersSent = true; allowChunked = true; sendResponse(_pctx, response); return this; } @Override public void end(@SuppressWarnings("rawtypes") JSON.Instance inst) { header("Content-Type", "application/json"); String ua = headers.get("user-agent"); if (ua != null && ua.startsWith("curl/")) { // use pretty end(inst.pretty() + "\r\n"); } else { end(inst.stringify()); } } @Override public void end(ByteArray body) { if (isEnd) { throw new IllegalStateException("This response is already ended"); } isEnd = true; response.body = body; sendResponse(_pctx, response); } @Override public HttpResponse sendChunk(ByteArray chunk) { if (!allowChunked) { throw new IllegalStateException("You have to call sendHeadersWithChunked() first"); } Chunk c = new Chunk(); c.size = chunk.length(); c.content = chunk; _pctx.write(c.toByteArray().toJavaArray()); return this; } }; } { // chain var list = buildHandlerChain(routes.get(method), paths).iterator(); chain = () -> { var tup = list.next(); tup.left.forEach(pre -> pre.accept(ctx[0])); // pre process tup.right.accept(ctx[0]); }; } // build ctx ctx[0] = new RoutingContext(_pctx.connection.remote, _pctx.connection.getLocal(), method, uri, query, headers, body, response, chain); } ctx[0].next(); } private static String unescape(String uri) { byte[] input = uri.getBytes(); int idx = 0; byte[] result = Utils.allocateByteArray(input.length); int state = 0; // 0 -> normal, 1 -> %[x]x, 2 -> %x[x] int a = 0; for (byte b : input) { char c = (char) b; // safe if (state == 0) { if (c == '%') { state = 1; } else { result[idx++] = b; } } else { int n; try { n = Integer.parseInt("" + c, 16); } catch (NumberFormatException ignore) { assert Logger.lowLevelDebug("escaped uri part not number: " + c); return null; } if (state == 1) { a = n; state = 2; } else { n = a * 16 + n; result[idx++] = (byte) n; state = 0; } } } if (state == 0) { return new String(result, 0, idx); } else { return null; } } // return: list<tuple<list<preHandlers>, actualHandler>> // the preHandlers are constructed in this method, and actualHandlers are user defined private List<Tuple<List<RoutingHandler>, RoutingHandler>> buildHandlerChain(Tree<SubPath, RoutingHandler> tree, List<String> paths) { var ret = new LinkedList<Tuple<List<RoutingHandler>, RoutingHandler>>(); var pre = Collections.<RoutingHandler>emptyList(); if (paths.isEmpty()) { // special handling for paths.isEmpty condition // paths.isEmpty means the request path is `/` // we need this special handling because // the method buildHandlerChain(...) is iterated over paths list // if the list is empty, the chain won't be built // adding more modifications to method buildHandlerChain(...) // will make things complex. we simply check paths.isEmpty here // as the entry condition, things will be a lot easier. for (var h : tree.leafData()) { // definitely no data to fill, so preHandlers can be empty ret.add(new Tuple<>(Collections.emptyList(), h)); } // also 404 should be added ret.add(new Tuple<>(Collections.emptyList(), this::handle404)); } else { buildHandlerChain(ret, pre, tree, paths, 0); } assert !ret.isEmpty(); // 404 handler would had already been added return ret; } private void buildHandlerChain(List<Tuple<List<RoutingHandler>, RoutingHandler>> ret, List<RoutingHandler> preHandlers, Tree<SubPath, RoutingHandler> tree, List<String> paths, final int pathIdx) { if (pathIdx >= paths.size()) { return; // iteration finishes } String path = paths.get(pathIdx); boolean isLast = pathIdx + 1 == paths.size(); for (var br : tree.branches()) { if (br.data.match(path)) { // may need to handle because sub-path matches RoutingHandler preHandler = rctx -> br.data.fill(rctx, path); var newPreHandlers = new AppendingList<>(preHandlers, preHandler); buildHandlerChain(ret, newPreHandlers, br, paths, pathIdx + 1); if (isLast || br.data instanceof WildcardSubPath) { // isLast means in this branch until this tree node, data on these traversed nodes matched // so all leaf/leaves on current tree node should be added to the handler chain for (var h : br.leafData()) { ret.add(new Tuple<>(newPreHandlers, h)); } } } } } }
40.27115
158
0.478966
02c79cde91d055620474591e58a6c0c1aaf23be1
247
package me.ederign.decorator; public class InternacionalTaxes extends ItemExtras { public InternacionalTaxes( Item item ) { super( item ); } @Override public int getPrice() { return 50 + super.getPrice(); } }
19
52
0.639676
08e683cb1ecd7dde5c69a7b4bde6304c96334360
548
package CoreJava.LabBook.Lab2; import java.util.Arrays; public class DuplicateSort { public int modifyArray(int[] a) { int j = 0; for (int i = 0; i < a.length-1; i++) { if (a[i] != a[i+1]) { a[j] = a[i]; j++; } } a[j++]=a[a.length-1]; Arrays.sort(a); return j; } public static void main(String[] args) { int[] a = { 1, 4, 5, 1 }; DuplicateSort ref = new DuplicateSort(); Arrays.sort(a); int len = ref.modifyArray(a); for (int i = len-1; i >= 0; i--) { System.out.print(a[i]+" "); } } }
15.657143
42
0.529197
1d41e7e68690d64d79d6e585ebd749f4ac7a29bf
469
package p005cm.aptoide.accountmanager; import p026rx.p027b.C0132p; /* renamed from: cm.aptoide.accountmanager.v */ /* compiled from: lambda */ public final /* synthetic */ class C1339v implements C0132p { /* renamed from: a */ public static final /* synthetic */ C1339v f4236a = new C1339v(); private /* synthetic */ C1339v() { } public final Object call(Object obj) { return Boolean.valueOf(((SignUpAdapter) obj).isEnabled()); } }
24.684211
69
0.667377
b1e16e2bbecbcf24d66bad20de9a4a170ed37df1
9,206
package uk.gov.companieshouse.service; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.junit.jupiter.MockitoExtension; import uk.gov.companieshouse.client.CompanyOfficersClient; import uk.gov.companieshouse.model.dto.companyofficers.CompanyOfficer; import uk.gov.companieshouse.model.dto.dissolution.DirectorRequest; import uk.gov.companieshouse.model.enums.OfficerRole; import uk.gov.companieshouse.service.dissolution.validator.CompanyOfficerValidator; import java.time.LocalDateTime; import java.util.Arrays; import java.util.Collections; import java.util.List; import java.util.Map; import java.util.Optional; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNull; import static org.junit.jupiter.api.Assertions.assertTrue; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; import static uk.gov.companieshouse.fixtures.CompanyOfficerFixtures.generateCompanyOfficer; import static uk.gov.companieshouse.fixtures.CompanyOfficerFixtures.generateCompanyOfficerLinks; import static uk.gov.companieshouse.fixtures.DissolutionFixtures.generateDirectorRequest; @ExtendWith(MockitoExtension.class) public class CompanyOfficerServiceTest { @InjectMocks private CompanyOfficerService service; @Mock private CompanyOfficersClient client; @Mock private CompanyOfficerValidator validator; public static final String COMPANY_NUMBER = "12345678"; @Test public void getActiveDirectorsForCompany_shouldFetchOfficers_AndIndexUsingOfficerId() { CompanyOfficer activeDirector1 = generateCompanyOfficer(); activeDirector1.setResignedOn(null); activeDirector1.setOfficerRole(OfficerRole.DIRECTOR.getValue()); activeDirector1.setLinks(generateCompanyOfficerLinks("123abc")); CompanyOfficer activeDirector2 = generateCompanyOfficer(); activeDirector2.setResignedOn(null); activeDirector2.setOfficerRole(OfficerRole.DIRECTOR.getValue()); activeDirector2.setLinks(generateCompanyOfficerLinks("456def")); when(client.getCompanyOfficers(COMPANY_NUMBER)).thenReturn(Arrays.asList(activeDirector1, activeDirector2)); final Map<String, CompanyOfficer> result = service.getActiveDirectorsForCompany(COMPANY_NUMBER); verify(client).getCompanyOfficers(COMPANY_NUMBER); assertEquals(2, result.size()); assertEquals(activeDirector1, result.get("123abc")); assertEquals(activeDirector2, result.get("456def")); } @Test public void getActiveDirectorsForCompany_shouldFetchOfficers_filterOutResignedOfficers() { CompanyOfficer activeDirector1 = generateCompanyOfficer(); activeDirector1.setResignedOn(null); activeDirector1.setOfficerRole(OfficerRole.DIRECTOR.getValue()); activeDirector1.setLinks(generateCompanyOfficerLinks("123abc")); CompanyOfficer activeDirector2 = generateCompanyOfficer(); activeDirector2.setResignedOn(null); activeDirector2.setOfficerRole(OfficerRole.DIRECTOR.getValue()); activeDirector2.setLinks(generateCompanyOfficerLinks("456def")); CompanyOfficer resignedDirector = generateCompanyOfficer(); resignedDirector.setResignedOn(LocalDateTime.now().toString()); resignedDirector.setOfficerRole(OfficerRole.DIRECTOR.getValue()); resignedDirector.setLinks(generateCompanyOfficerLinks("789ghi")); when(client.getCompanyOfficers(COMPANY_NUMBER)).thenReturn(Arrays.asList(activeDirector1, activeDirector2, resignedDirector)); final Map<String, CompanyOfficer> result = service.getActiveDirectorsForCompany(COMPANY_NUMBER); assertEquals(2, result.size()); assertEquals(activeDirector1, result.get("123abc")); assertEquals(activeDirector2, result.get("456def")); assertNull(result.get("789ghi")); } @Test public void getActiveDirectorsForCompany_shouldFetchOfficers_filterOutNonDirectorsAndNonMembers() { CompanyOfficer activeDirector = generateCompanyOfficer(); activeDirector.setResignedOn(null); activeDirector.setOfficerRole(OfficerRole.DIRECTOR.getValue()); activeDirector.setLinks(generateCompanyOfficerLinks("123abc")); CompanyOfficer activeCorporateDirector = generateCompanyOfficer(); activeCorporateDirector.setResignedOn(null); activeCorporateDirector.setOfficerRole(OfficerRole.CORPORATE_DIRECTOR.getValue()); activeCorporateDirector.setLinks(generateCompanyOfficerLinks("321abc")); CompanyOfficer activeCorporateNomineeDirector = generateCompanyOfficer(); activeCorporateNomineeDirector.setResignedOn(null); activeCorporateNomineeDirector.setOfficerRole(OfficerRole.CORPORATE_NOMINEE_DIRECTOR.getValue()); activeCorporateNomineeDirector.setLinks(generateCompanyOfficerLinks("321cba")); CompanyOfficer activeJudicialFactor = generateCompanyOfficer(); activeJudicialFactor.setResignedOn(null); activeJudicialFactor.setOfficerRole(OfficerRole.JUDICIAL_FACTOR.getValue()); activeJudicialFactor.setLinks(generateCompanyOfficerLinks("abc123")); CompanyOfficer activeSecretary = generateCompanyOfficer(); activeSecretary.setResignedOn(null); activeSecretary.setOfficerRole(OfficerRole.SECRETARY.getValue()); activeSecretary.setLinks(generateCompanyOfficerLinks("456def")); CompanyOfficer activeMember = generateCompanyOfficer(); activeMember.setResignedOn(null); activeMember.setOfficerRole(OfficerRole.LLP_MEMBER.getValue()); activeMember.setLinks(generateCompanyOfficerLinks("789ghi")); CompanyOfficer activeDesignatedMember = generateCompanyOfficer(); activeDesignatedMember.setResignedOn(null); activeDesignatedMember.setOfficerRole(OfficerRole.LLP_DESIGNATED_MEMBER.getValue()); activeDesignatedMember.setLinks(generateCompanyOfficerLinks("987ghi")); CompanyOfficer activeCorporateMember = generateCompanyOfficer(); activeCorporateMember.setResignedOn(null); activeCorporateMember.setOfficerRole(OfficerRole.CORPORATE_LLP_MEMBER.getValue()); activeCorporateMember.setLinks(generateCompanyOfficerLinks("987ihg")); CompanyOfficer activeCorporateDesignatedMember = generateCompanyOfficer(); activeCorporateDesignatedMember.setResignedOn(null); activeCorporateDesignatedMember.setOfficerRole(OfficerRole.CORPORATE_LLP_DESIGNATED_MEMBER.getValue()); activeCorporateDesignatedMember.setLinks(generateCompanyOfficerLinks("ghi789")); when(client.getCompanyOfficers(COMPANY_NUMBER)).thenReturn(Arrays.asList( activeDirector, activeCorporateDirector, activeCorporateNomineeDirector, activeJudicialFactor, activeSecretary, activeMember, activeDesignatedMember, activeCorporateMember, activeCorporateDesignatedMember )); final Map<String, CompanyOfficer> result = service.getActiveDirectorsForCompany(COMPANY_NUMBER); assertEquals(8, result.size()); assertEquals(activeDirector, result.get("123abc")); assertEquals(activeCorporateDirector, result.get("321abc")); assertEquals(activeCorporateNomineeDirector, result.get("321cba")); assertEquals(activeJudicialFactor, result.get("abc123")); assertNull(result.get("456def")); assertEquals(activeMember, result.get("789ghi")); assertEquals(activeDesignatedMember, result.get("987ghi")); assertEquals(activeCorporateMember, result.get("987ihg")); assertEquals(activeCorporateDesignatedMember, result.get("ghi789")); } @Test public void areSelectedDirectorsValid_shouldReturnError_ifSelectedDirectorsAreNotValid() { final String error = "Some invalid director error"; final Map<String, CompanyOfficer> companyDirectors = Map.of("123abc", generateCompanyOfficer()); final List<DirectorRequest> selectedDirectors = Collections.singletonList(generateDirectorRequest()); when(validator.areSelectedDirectorsValid(companyDirectors, selectedDirectors)).thenReturn(Optional.of(error)); final Optional<String> result = service.areSelectedDirectorsValid(companyDirectors, selectedDirectors); assertEquals(error, result.get()); } @Test public void areSelectedDirectorsValid_shouldReturnNoError_ifSelectedDirectorsAreValid() { final Map<String, CompanyOfficer> companyDirectors = Map.of("123abc", generateCompanyOfficer()); final List<DirectorRequest> selectedDirectors = Collections.singletonList(generateDirectorRequest()); when(validator.areSelectedDirectorsValid(companyDirectors, selectedDirectors)).thenReturn(Optional.empty()); final Optional<String> result = service.areSelectedDirectorsValid(companyDirectors, selectedDirectors); assertTrue(result.isEmpty()); } }
47.699482
134
0.764719
d37d9f5157039a13990f016598d69e24cbff364f
5,537
package com.github.ocraft.s2client.protocol.game.raw; /*- * #%L * ocraft-s2client-protocol * %% * Copyright (C) 2017 - 2018 Ocraft Project * %% * 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. * #L% */ import SC2APIProtocol.Raw; import com.github.ocraft.s2client.protocol.Strings; import com.github.ocraft.s2client.protocol.observation.spatial.ImageData; import com.github.ocraft.s2client.protocol.spatial.Point2d; import com.github.ocraft.s2client.protocol.spatial.RectangleI; import com.github.ocraft.s2client.protocol.spatial.Size2dI; import java.io.Serializable; import java.util.Collections; import java.util.Set; import static com.github.ocraft.s2client.protocol.DataExtractor.tryGet; import static com.github.ocraft.s2client.protocol.Errors.required; import static com.github.ocraft.s2client.protocol.Preconditions.require; import static java.util.stream.Collectors.collectingAndThen; import static java.util.stream.Collectors.toSet; public final class StartRaw implements Serializable { private static final long serialVersionUID = -281483860654181069L; private final Size2dI mapSize; /** Width and height of the map. */ private final ImageData pathingGrid; /** 1 bit bitmap of the pathing grid. */ private final ImageData terrainHeight; /** 1 byte bitmap of the terrain height. */ private final ImageData placementGrid; /** 1 bit bitmap of the building placement grid. */ private final RectangleI playableArea; /** The playable cells. */ private final Set<Point2d> startLocations; /** Possible start locations for enemy players (not self start location). */ private StartRaw(Raw.StartRaw sc2ApiStartRaw) { mapSize = tryGet(Raw.StartRaw::getMapSize, Raw.StartRaw::hasMapSize) .apply(sc2ApiStartRaw).map(Size2dI::from).orElseThrow(required("map size")); pathingGrid = tryGet(Raw.StartRaw::getPathingGrid, Raw.StartRaw::hasPathingGrid) .apply(sc2ApiStartRaw).map(ImageData::from).orElseThrow(required("pathing grid")); terrainHeight = tryGet(Raw.StartRaw::getTerrainHeight, Raw.StartRaw::hasTerrainHeight) .apply(sc2ApiStartRaw).map(ImageData::from).orElseThrow(required("terrain height")); placementGrid = tryGet(Raw.StartRaw::getPlacementGrid, Raw.StartRaw::hasPlacementGrid) .apply(sc2ApiStartRaw).map(ImageData::from).orElseThrow(required("placement grid")); playableArea = tryGet(Raw.StartRaw::getPlayableArea, Raw.StartRaw::hasPlayableArea) .apply(sc2ApiStartRaw).map(RectangleI::from).orElseThrow(required("playable area")); startLocations = sc2ApiStartRaw.getStartLocationsList().stream().map(Point2d::from) .collect(collectingAndThen(toSet(), Collections::unmodifiableSet)); } public static StartRaw from(Raw.StartRaw sc2ApiStartRaw) { require("sc2api start raw", sc2ApiStartRaw); return new StartRaw(sc2ApiStartRaw); } public Size2dI getMapSize() { return mapSize; } public ImageData getPathingGrid() { return pathingGrid; } public ImageData getTerrainHeight() { return terrainHeight; } public ImageData getPlacementGrid() { return placementGrid; } public RectangleI getPlayableArea() { return playableArea; } public Set<Point2d> getStartLocations() { return startLocations; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; StartRaw startRaw = (StartRaw) o; return mapSize.equals(startRaw.mapSize) && pathingGrid.equals(startRaw.pathingGrid) && terrainHeight.equals(startRaw.terrainHeight) && placementGrid.equals(startRaw.placementGrid) && playableArea.equals(startRaw.playableArea) && startLocations.equals(startRaw.startLocations); } @Override public int hashCode() { int result = mapSize.hashCode(); result = 31 * result + pathingGrid.hashCode(); result = 31 * result + terrainHeight.hashCode(); result = 31 * result + placementGrid.hashCode(); result = 31 * result + playableArea.hashCode(); result = 31 * result + startLocations.hashCode(); return result; } @Override public String toString() { return Strings.toJson(this); } }
40.416058
124
0.702908
699c018f41dfcefe879dfe3186237fbc3f787f20
1,311
package io.rivmt.keyboard.openwnn.KOKR; public class ComposingWord { private StringBuilder composingWord = new StringBuilder(); private String composingChar = ""; private String fixedWord; public void composeChar(String composingChar) { this.composingChar = composingChar; } public void commitComposingChar() { composingWord.append(composingChar); composingChar = ""; } public String commitComposingWord() { commitComposingChar(); String result = composingWord.toString(); composingWord = new StringBuilder(); composingChar = ""; return result; } public boolean backspace() { if(composingWord.length() == 0) return false; else composingWord.deleteCharAt(composingWord.length()-1); return true; } public String getComposingChar() { return composingChar; } public String getComposingWord() { return composingWord.toString(); } public void setComposingWord(String composingWord) { this.composingWord = new StringBuilder(composingWord); } public String getEntireWord() { return composingWord.toString() + composingChar; } public int length() { return composingWord.length() + (composingChar.isEmpty() ? 0 : 1); } public String getFixedWord() { return fixedWord; } public void setFixedWord(String fixedWord) { this.fixedWord = fixedWord; } }
21.85
68
0.737605
4ca9bb627688db8b740c1e628db44b996c672315
2,138
package de.dhbw.studientag.tours; import java.util.ArrayList; import java.util.List; import android.content.Context; import android.util.Pair; import android.view.LayoutInflater; import android.view.View; import android.view.View.OnClickListener; import android.view.ViewGroup; import android.view.ViewManager; import android.widget.ArrayAdapter; import android.widget.ImageButton; import android.widget.TextView; import de.dhbw.studientag.OnBinClicked; import de.dhbw.studientag.R; import de.dhbw.studientag.model.Tour; public class SelectTourDialogAdapter extends ArrayAdapter<Tour> { private final Context context; private final List<Pair<Boolean,Tour>> tourList; private OnBinClicked mBinClicked; public SelectTourDialogAdapter(Context context,List<Pair<Boolean,Tour>> tourList) { super(context, R.layout.dialog_list, extractTour(tourList) ); this.context = context; this.tourList = tourList; } @Override public View getView(final int position, View convertView, ViewGroup parent) { LayoutInflater inflater = (LayoutInflater) context .getSystemService(Context.LAYOUT_INFLATER_SERVICE); View row = inflater.inflate(R.layout.dialog_list, parent, false); TextView tourName = (TextView) row.findViewById(R.id.dialogListTourName); tourName.setText((CharSequence) tourList.get(position).second.getName()); ImageButton delete = (ImageButton) row.findViewById(R.id.dialogListDelete); if (tourList.get(position).first) { delete.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { mBinClicked.binClicked(position); //remove bin icon ((ViewManager)v.getParent()).removeView(v); } }); } else { //no bin icon if company not in tour ((ViewManager) delete.getParent()).removeView(delete); } return row; } public void setOnBinClickListener(OnBinClicked binClicked) { this.mBinClicked = binClicked; } private static List<Tour> extractTour(List<Pair<Boolean,Tour>> pTourList){ List<Tour> tourList = new ArrayList<Tour>(); for(Pair<Boolean,Tour> pair : pTourList){ tourList.add(pair.second); } return tourList; } }
29.694444
84
0.760524
fad89c62ef391f246a4f406050a390ecc7b7d5a0
15,534
/* * Licensed to Elasticsearch under one or more contributor * license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright * ownership. Elasticsearch licenses this file to you under * the Apache License, Version 2.0 (the "License"); you may * not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.elasticsearch.index.mapper.ip; import com.google.common.net.InetAddresses; import org.apache.lucene.analysis.NumericTokenStream; import org.apache.lucene.document.Field; import org.apache.lucene.index.IndexOptions; import org.apache.lucene.search.NumericRangeQuery; import org.apache.lucene.search.Query; import org.apache.lucene.util.BytesRef; import org.apache.lucene.util.BytesRefBuilder; import org.apache.lucene.util.NumericUtils; import org.elasticsearch.common.Explicit; import org.elasticsearch.common.Nullable; import org.elasticsearch.common.Numbers; import org.elasticsearch.common.Strings; import org.elasticsearch.common.settings.Settings; import org.elasticsearch.common.unit.Fuzziness; import org.elasticsearch.common.xcontent.XContentBuilder; import org.elasticsearch.common.xcontent.XContentParser; import org.elasticsearch.index.analysis.NamedAnalyzer; import org.elasticsearch.index.analysis.NumericAnalyzer; import org.elasticsearch.index.analysis.NumericTokenizer; import org.elasticsearch.index.fielddata.FieldDataType; import org.elasticsearch.index.mapper.MappedFieldType; import org.elasticsearch.index.mapper.Mapper; import org.elasticsearch.index.mapper.MapperParsingException; import org.elasticsearch.index.mapper.ParseContext; import org.elasticsearch.index.mapper.core.LongFieldMapper; import org.elasticsearch.index.mapper.core.LongFieldMapper.CustomLongNumericField; import org.elasticsearch.index.mapper.core.NumberFieldMapper; import org.elasticsearch.index.query.QueryParseContext; import java.io.IOException; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.regex.Matcher; import java.util.regex.Pattern; import static org.elasticsearch.index.mapper.MapperBuilders.ipField; import static org.elasticsearch.index.mapper.core.TypeParsers.parseNumberField; /** * */ public class IpFieldMapper extends NumberFieldMapper { public static final String CONTENT_TYPE = "ip"; public static final long MAX_IP = 4294967296l; public static String longToIp(long longIp) { int octet3 = (int) ((longIp >> 24) % 256); int octet2 = (int) ((longIp >> 16) % 256); int octet1 = (int) ((longIp >> 8) % 256); int octet0 = (int) ((longIp) % 256); return octet3 + "." + octet2 + "." + octet1 + "." + octet0; } private static final Pattern pattern = Pattern.compile("\\."); private static final Pattern MASK_PATTERN = Pattern.compile("(\\d{1,3})\\.(\\d{1,3})\\.(\\d{1,3})\\.(\\d{1,3})/(\\d{1,3})"); public static long ipToLong(String ip) { try { if (!InetAddresses.isInetAddress(ip)) { throw new IllegalArgumentException("failed to parse ip [" + ip + "], not a valid ip address"); } String[] octets = pattern.split(ip); if (octets.length != 4) { throw new IllegalArgumentException("failed to parse ip [" + ip + "], not a valid ipv4 address (4 dots)"); } return (Long.parseLong(octets[0]) << 24) + (Integer.parseInt(octets[1]) << 16) + (Integer.parseInt(octets[2]) << 8) + Integer.parseInt(octets[3]); } catch (Exception e) { if (e instanceof IllegalArgumentException) { throw (IllegalArgumentException) e; } throw new IllegalArgumentException("failed to parse ip [" + ip + "]", e); } } /** * Computes the min &amp; max ip addresses (represented as long values - * same way as stored in index) represented by the given CIDR mask * expression. The returned array has the length of 2, where the first entry * represents the {@code min} address and the second the {@code max}. A * {@code -1} value for either the {@code min} or the {@code max}, * represents an unbounded end. In other words: * * <p> * {@code min == -1 == "0.0.0.0" } * </p> * * and * * <p> * {@code max == -1 == "255.255.255.255" } * </p> */ public static long[] cidrMaskToMinMax(String cidr) { Matcher matcher = MASK_PATTERN.matcher(cidr); if (!matcher.matches()) { return null; } int addr = ((Integer.parseInt(matcher.group(1)) << 24) & 0xFF000000) | ((Integer.parseInt(matcher.group(2)) << 16) & 0xFF0000) | ((Integer.parseInt(matcher.group(3)) << 8) & 0xFF00) | (Integer.parseInt(matcher.group(4)) & 0xFF); int mask = (-1) << (32 - Integer.parseInt(matcher.group(5))); if (Integer.parseInt(matcher.group(5)) == 0) { mask = 0 << 32; } int from = addr & mask; long longFrom = intIpToLongIp(from); if (longFrom == 0) { longFrom = -1; } int to = from + (~mask); long longTo = intIpToLongIp(to) + 1; // we have to +1 here as the range // is non-inclusive on the "to" // side if (longTo == MAX_IP) { longTo = -1; } return new long[] { longFrom, longTo }; } private static long intIpToLongIp(int i) { long p1 = ((long) ((i >> 24) & 0xFF)) << 24; int p2 = ((i >> 16) & 0xFF) << 16; int p3 = ((i >> 8) & 0xFF) << 8; int p4 = i & 0xFF; return p1 + p2 + p3 + p4; } public static class Defaults extends NumberFieldMapper.Defaults { public static final String NULL_VALUE = null; public static final MappedFieldType FIELD_TYPE = new IpFieldType(); static { FIELD_TYPE.freeze(); } } public static class Builder extends NumberFieldMapper.Builder<Builder, IpFieldMapper> { protected String nullValue = Defaults.NULL_VALUE; public Builder(String name) { super(name, Defaults.FIELD_TYPE, Defaults.PRECISION_STEP_64_BIT); builder = this; } @Override public IpFieldMapper build(BuilderContext context) { setupFieldType(context); IpFieldMapper fieldMapper = new IpFieldMapper(name, fieldType, defaultFieldType, ignoreMalformed(context), coerce(context), context.indexSettings(), multiFieldsBuilder.build(this, context), copyTo); return (IpFieldMapper) fieldMapper.includeInAll(includeInAll); } @Override protected NamedAnalyzer makeNumberAnalyzer(int precisionStep) { String name = precisionStep == Integer.MAX_VALUE ? "_ip/max" : ("_ip/" + precisionStep); return new NamedAnalyzer(name, new NumericIpAnalyzer(precisionStep)); } @Override protected int maxPrecisionStep() { return 64; } } public static class TypeParser implements Mapper.TypeParser { @Override public Mapper.Builder parse(String name, Map<String, Object> node, ParserContext parserContext) throws MapperParsingException { IpFieldMapper.Builder builder = ipField(name); parseNumberField(builder, name, node, parserContext); for (Iterator<Map.Entry<String, Object>> iterator = node.entrySet().iterator(); iterator.hasNext();) { Map.Entry<String, Object> entry = iterator.next(); String propName = Strings.toUnderscoreCase(entry.getKey()); Object propNode = entry.getValue(); if (propName.equals("null_value")) { if (propNode == null) { throw new MapperParsingException("Property [null_value] cannot be null."); } builder.nullValue(propNode.toString()); iterator.remove(); } } return builder; } } public static final class IpFieldType extends LongFieldMapper.LongFieldType { public IpFieldType() { setFieldDataType(new FieldDataType("long")); } protected IpFieldType(IpFieldType ref) { super(ref); } @Override public NumberFieldType clone() { return new IpFieldType(this); } @Override public String typeName() { return CONTENT_TYPE; } @Override public Long value(Object value) { if (value == null) { return null; } if (value instanceof Number) { return ((Number) value).longValue(); } if (value instanceof BytesRef) { return Numbers.bytesToLong((BytesRef) value); } return ipToLong(value.toString()); } /** * IPs should return as a string. */ @Override public Object valueForSearch(Object value) { Long val = value(value); if (val == null) { return null; } return longToIp(val); } @Override public BytesRef indexedValueForSearch(Object value) { BytesRefBuilder bytesRef = new BytesRefBuilder(); NumericUtils.longToPrefixCoded(parseValue(value), 0, bytesRef); // 0 because of exact match return bytesRef.get(); } @Override public Query termQuery(Object value, @Nullable QueryParseContext context) { if (value != null) { long[] fromTo; if (value instanceof BytesRef) { fromTo = cidrMaskToMinMax(((BytesRef) value).utf8ToString()); } else { fromTo = cidrMaskToMinMax(value.toString()); } if (fromTo != null) { return rangeQuery(fromTo[0] < 0 ? null : fromTo[0], fromTo[1] < 0 ? null : fromTo[1], true, false); } } return super.termQuery(value, context); } @Override public Query rangeQuery(Object lowerTerm, Object upperTerm, boolean includeLower, boolean includeUpper) { return NumericRangeQuery.newLongRange(names().indexName(), numericPrecisionStep(), lowerTerm == null ? null : parseValue(lowerTerm), upperTerm == null ? null : parseValue(upperTerm), includeLower, includeUpper); } @Override public Query fuzzyQuery(Object value, Fuzziness fuzziness, int prefixLength, int maxExpansions, boolean transpositions) { long iValue = parseValue(value); long iSim; try { iSim = ipToLong(fuzziness.asString()); } catch (IllegalArgumentException e) { iSim = fuzziness.asLong(); } return NumericRangeQuery.newLongRange(names().indexName(), numericPrecisionStep(), iValue - iSim, iValue + iSim, true, true); } } protected IpFieldMapper(String simpleName, MappedFieldType fieldType, MappedFieldType defaultFieldType, Explicit<Boolean> ignoreMalformed, Explicit<Boolean> coerce, Settings indexSettings, MultiFields multiFields, CopyTo copyTo) { super(simpleName, fieldType, defaultFieldType, ignoreMalformed, coerce, indexSettings, multiFields, copyTo); } private static long parseValue(Object value) { if (value instanceof Number) { return ((Number) value).longValue(); } if (value instanceof BytesRef) { return ipToLong(((BytesRef) value).utf8ToString()); } return ipToLong(value.toString()); } @Override protected void innerParseCreateField(ParseContext context, List<Field> fields) throws IOException { String ipAsString; if (context.externalValueSet()) { ipAsString = (String) context.externalValue(); if (ipAsString == null) { ipAsString = fieldType().nullValueAsString(); } } else { if (context.parser().currentToken() == XContentParser.Token.VALUE_NULL) { ipAsString = fieldType().nullValueAsString(); } else { ipAsString = context.parser().text(); } } if (ipAsString == null) { return; } if (context.includeInAll(includeInAll, this)) { context.allEntries().addText(fieldType().names().fullName(), ipAsString, fieldType().boost()); } final long value = ipToLong(ipAsString); if (fieldType().indexOptions() != IndexOptions.NONE || fieldType().stored()) { CustomLongNumericField field = new CustomLongNumericField(value, fieldType()); field.setBoost(fieldType().boost()); fields.add(field); } if (fieldType().hasDocValues()) { addDocValue(context, fields, value); } } @Override protected String contentType() { return CONTENT_TYPE; } @Override protected void doXContentBody(XContentBuilder builder, boolean includeDefaults, Params params) throws IOException { super.doXContentBody(builder, includeDefaults, params); if (includeDefaults || fieldType().numericPrecisionStep() != Defaults.PRECISION_STEP_64_BIT) { builder.field("precision_step", fieldType().numericPrecisionStep()); } if (includeDefaults || fieldType().nullValueAsString() != null) { builder.field("null_value", fieldType().nullValueAsString()); } if (includeInAll != null) { builder.field("include_in_all", includeInAll); } else if (includeDefaults) { builder.field("include_in_all", false); } } public static class NumericIpAnalyzer extends NumericAnalyzer<NumericIpTokenizer> { private final int precisionStep; public NumericIpAnalyzer(int precisionStep) { this.precisionStep = precisionStep; } @Override protected NumericIpTokenizer createNumericTokenizer(char[] buffer) throws IOException { return new NumericIpTokenizer(precisionStep, buffer); } } public static class NumericIpTokenizer extends NumericTokenizer { public NumericIpTokenizer(int precisionStep, char[] buffer) throws IOException { super(new NumericTokenStream(precisionStep), buffer, null); } @Override protected void setValue(NumericTokenStream tokenStream, String value) { tokenStream.setLongValue(ipToLong(value)); } } }
37.79562
135
0.609952
eb1d683012f3fa3ea23774f44690070ce22b2467
662
package com.codepreplabs.bean; public class Engineer { private String name; private String stream; private String employeeType; private String country; public String getName() { return name; } public void setName(String name) { this.name = name; } public String getStream() { return stream; } public void setStream(String stream) { this.stream = stream; } public String getEmployeeType() { return employeeType; } public void setEmployeeType(String employeeType) { this.employeeType = employeeType; } public String getCountry() { return country; } public void setCountry(String country) { this.country = country; } }
15.761905
51
0.719033
20807f76f92be76deae117e2c57f086fdf41a07e
734
/** * Class Salmon contains information about a Cheese, including the manufacturer, name, price, minimum age, weight */ public class Salmon extends Grocery{ /** * Constructs a new Salmon, based upon all of the provided input parameters. * * @param manufacturer - the manufacturer of this Salmon * @param name - the name of this Salmon * @param price - the price of this Salmon * @param minimumAge - the minimum age limit to buy this Salmon * @param weight - the weight of this Salmon * @return - object Salmon */ public Salmon(String manufacturer, String name, Double price, int minimumAge, Double weight) { super(manufacturer, name, price, minimumAge, weight); } }
36.7
113
0.681199
28cf56b59163de294de8ea7564e29aedc70228ef
227
package com.desertkun.brainout.content; import com.desertkun.brainout.reflection.Reflect; import com.desertkun.brainout.reflection.ReflectAlias; @Reflect("content.SpawnTarget") public enum SpawnTarget { normal, flag }
20.636364
54
0.797357
2157e6922ab6f6729a0e157f6ae755ea6b61d425
3,325
/* * 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.samza.util; import java.util.HashMap; import java.util.Map; import java.util.Set; import org.apache.samza.Partition; import org.apache.samza.SamzaException; import org.apache.samza.system.SystemAdmin; import org.apache.samza.system.SystemStreamMetadata; import org.apache.samza.system.SystemStreamMetadata.SystemStreamPartitionMetadata; import org.apache.samza.system.SystemStreamPartition; /** * A simple helper admin class that defines a single partition (partition 0) for * a given system. The metadata uses null for all offsets, which means that the * stream doesn't support offsets, and will be treated as empty. This class * should be used when a system has no concept of partitioning or offsets, since * Samza needs at least one partition for an input stream, in order to read it. */ public class SinglePartitionWithoutOffsetsSystemAdmin implements SystemAdmin { private static final Map<Partition, SystemStreamPartitionMetadata> FAKE_PARTITION_METADATA = new HashMap<Partition, SystemStreamPartitionMetadata>(); static { FAKE_PARTITION_METADATA.put(new Partition(0), new SystemStreamPartitionMetadata(null, null, null)); } @Override public Map<String, SystemStreamMetadata> getSystemStreamMetadata(Set<String> streamNames) { Map<String, SystemStreamMetadata> metadata = new HashMap<String, SystemStreamMetadata>(); for (String streamName : streamNames) { metadata.put(streamName, new SystemStreamMetadata(streamName, FAKE_PARTITION_METADATA)); } return metadata; } @Override public void createChangelogStream(String streamName, int numOfPartitions) { throw new SamzaException("Method not implemented"); } @Override public void validateChangelogStream(String streamName, int numOfPartitions) { throw new SamzaException("Method not implemented"); } @Override public Map<SystemStreamPartition, String> getOffsetsAfter(Map<SystemStreamPartition, String> offsets) { Map<SystemStreamPartition, String> offsetsAfter = new HashMap<SystemStreamPartition, String>(); for (SystemStreamPartition systemStreamPartition : offsets.keySet()) { offsetsAfter.put(systemStreamPartition, null); } return offsetsAfter; } @Override public void createCoordinatorStream(String streamName) { throw new UnsupportedOperationException("Single partition admin can't create coordinator streams."); } @Override public Integer offsetComparator(String offset1, String offset2) { return null; } }
37.359551
151
0.772632
0a788c6f56fb17e06f5bd064efba43453b764c5f
224
package com.andrewclam.ch1fundamentals.section03.bag; /** * API for a {@link Bag} * @param <Item> type of {@link Item} to store */ public interface Bag<Item> { void add(Item item); boolean isEmpty(); int size(); }
18.666667
53
0.665179
720f4581f3dbbf38768ebdfd0d3d96b2d2fda624
216
package game.engine.gameHandlers.operation; import game.util.MutableCell; import java.util.List; public class Nothing implements Operation { @Override public void execute(List<MutableCell> currCells) { } }
16.615385
52
0.773148
4cb1f5969dd292c8b7f10f1257995c090da54043
1,452
package org.openehealth.ipf.platform.camel.core.reifier; import org.apache.camel.CamelContext; import org.apache.camel.model.DataFormatDefinition; import org.apache.camel.reifier.dataformat.DataFormatReifier; import org.apache.camel.spi.DataFormat; import org.openehealth.ipf.commons.core.modules.api.Parser; import org.openehealth.ipf.commons.core.modules.api.Renderer; import org.openehealth.ipf.platform.camel.core.adapter.DataFormatAdapter; import org.openehealth.ipf.platform.camel.core.model.DataFormatAdapterDefinition; import java.util.Map; /** * @author Christian Ohr */ public class DataFormatAdapterReifier extends DataFormatReifier<DataFormatAdapterDefinition> { public DataFormatAdapterReifier(CamelContext camelContext, DataFormatDefinition definition) { super(camelContext, (DataFormatAdapterDefinition) definition); } @Override protected DataFormat doCreateDataFormat() { if (definition.getParserBeanName() != null) { return new DataFormatAdapter(camelContext.getRegistry() .lookupByNameAndType(definition.getParserBeanName(), Parser.class)); } else { return new DataFormatAdapter(camelContext.getRegistry() .lookupByNameAndType(definition.getRendererBeanName(), Renderer.class)); } } @Override protected void prepareDataFormatConfig(Map<String, Object> properties) { } }
38.210526
97
0.741047
5b9e8ba9eb521d59b328ba45d507ba618853a3c9
1,488
/* * Copyright 2013-2017 Indiana University * * 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 edu.iu.wdamds; public class MDSConstants { public static final String NUM_MAPS = "num_maps"; public static final String X_FILE_PATH = "x_file_path"; public static final String X_OUT_FILE_PATH = "x_out_file_path"; public static final String IDS_FILE = "ids_file"; public static final String LABELS_FILE = "labels_file"; public static final String THRESHOLD = "threshold"; public static final String D = "d"; public static final String ALPHA = "alpha"; public static final String N = "n"; public static final String CG_ITER = "cg_iter"; public static final String NUM_THREADS = "num_threads"; public static final int MAX_ITER = 10000; public static final int BLOCK_SIZE = 64; public static final String ROWS_TAG = "#ROWS"; public static final String FILES_TAG = "#FILES"; }
35.428571
76
0.709005
378c4113c4f395bdedd83c796f60748683eef7b7
1,052
package com.ziroom.ziroomcustomer.bestgoods.model; import java.util.List; public class ah { private List<a> a; public List<a> getList() { return this.a; } public void setList(List<a> paramList) { this.a = paramList; } public class a { private String b; private String c; private boolean d; public a() {} public String getCode() { return this.c; } public String getShowName() { return this.b; } public boolean isSelected() { return this.d; } public void setCode(String paramString) { this.c = paramString; } public void setSelected(boolean paramBoolean) { this.d = paramBoolean; } public void setShowName(String paramString) { this.b = paramString; } } } /* Location: /Users/gaoht/Downloads/zirom/classes2-dex2jar.jar!/com/ziroom/ziroomcustomer/bestgoods/model/ah.class * Java compiler version: 6 (50.0) * JD-Core Version: 0.7.1 */
16.698413
127
0.585551
617171dee95b804515eb14bbce779bcbdbdd9ead
656
package hudson.remoting; import org.jenkinsci.remoting.CallableDecorator; /** * Decorator on {@code Callable.call()} to filter the execution. * * @author Kohsuke Kawaguchi * @deprecated * Use {@link CallableDecorator} */ @Deprecated public interface CallableFilter { /** * This implementation should normally look something like this: * * <pre> * V call(Callable c) { * doSomePrep(); * try { * return c.call(); * } finally { * doSomeCleanUp(); * } * } * </pre> */ <V> V call(java.util.concurrent.Callable<V> callable) throws Exception; }
21.866667
75
0.577744
52bfe0c60fe233ed28ff817e8bb30fbb779d9282
2,855
package com.realm.annotations; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.List; public class RealmDataClass { public HashMap package_tables; public HashMap<String, HashMap<String, DynamicProperty.storage_mode>> package_json_storagemode; public HashMap table_columns; public String[] tables; public String[][][] table_column_json; public String[] getDynamicClassPaths() { return new String[]{}; } public String[] getDynamicSyncClassPaths() { return new String[]{}; } public List<sync_service_description> getSyncDescription() { return new ArrayList<>(); } public HashMap<String, sync_service_description> getHashedSyncDescriptions() { return null; } public List<sync_service_description> getSyncDescription(Object obj) { return null; } public String getPackageTable(String package_name) { return ""; } public HashMap<String, String> getTableColumns(String table_name) { return new HashMap<>(); } public String getTableCreateSttment(String table_name, Boolean copy) { return ""; } public String getTableCreateIndexSttment(String table_name) { return ""; } public String getDeleteRecordSttment(String table_name, String sid) { return ""; } /** * Returns true if the json does not have the active key defined in db_class or if the json has the key and the value is true */ public Boolean jsonHasActiveKey(JSONObject json) { return false; } // // /** // * Returns true if the json does not have the active key defined in db_class or if the json has the key and the value is true // */ public Object getContentValuesFromJson(JSONObject json, String table_name) { Object cv = new Object(); return cv; } // public String[][][] getTableColumnJson() { return new String[][][]{{{}}}; } // public String[] getTables() { return new String[]{}; } public Object getObjectFromCursor(Object c, String package_name) { return null; } // public JSONObject getJsonFromCursor(Object c, String package_name) throws JSONException { return null; } // // /** // * Returns most efficient direct insert queries as per sqlite 3.7 /nAdjust database compound Limit for optimization // */ public String[][] getInsertStatementsFromJson(JSONArray array, String package_name) throws JSONException { return null; } public List<String> getFilePathFields(String package_name, List<String> available_keys) { return new ArrayList<>(); } }
23.991597
131
0.658144
4c74fdc2f911fb7fdef3a555166cee8541f949ed
9,880
/** * Copyright © 2016-2021 The Thingsboard Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.thingsboard.edge.rpc; import com.google.common.io.Resources; import io.grpc.ManagedChannel; import io.grpc.netty.GrpcSslContexts; import io.grpc.netty.NettyChannelBuilder; import io.grpc.stub.StreamObserver; import lombok.extern.slf4j.Slf4j; import org.springframework.beans.factory.annotation.Value; import org.springframework.stereotype.Service; import org.thingsboard.edge.exception.EdgeConnectionException; import org.thingsboard.server.common.data.ResourceUtils; import org.thingsboard.server.gen.edge.v1.ConnectRequestMsg; import org.thingsboard.server.gen.edge.v1.ConnectResponseCode; import org.thingsboard.server.gen.edge.v1.ConnectResponseMsg; import org.thingsboard.server.gen.edge.v1.DownlinkMsg; import org.thingsboard.server.gen.edge.v1.DownlinkResponseMsg; import org.thingsboard.server.gen.edge.v1.EdgeConfiguration; import org.thingsboard.server.gen.edge.v1.EdgeRpcServiceGrpc; import org.thingsboard.server.gen.edge.v1.RequestMsg; import org.thingsboard.server.gen.edge.v1.RequestMsgType; import org.thingsboard.server.gen.edge.v1.ResponseMsg; import org.thingsboard.server.gen.edge.v1.SyncRequestMsg; import org.thingsboard.server.gen.edge.v1.UplinkMsg; import org.thingsboard.server.gen.edge.v1.UplinkResponseMsg; import javax.net.ssl.SSLException; import java.io.File; import java.net.URISyntaxException; import java.util.concurrent.ExecutionException; import java.util.concurrent.TimeUnit; import java.util.concurrent.locks.ReentrantLock; import java.util.function.Consumer; @Service @Slf4j public class EdgeGrpcClient implements EdgeRpcClient { @Value("${cloud.rpc.host}") private String rpcHost; @Value("${cloud.rpc.port}") private int rpcPort; @Value("${cloud.rpc.timeout}") private int timeoutSecs; @Value("${cloud.rpc.keep_alive_time_sec}") private int keepAliveTimeSec; @Value("${cloud.rpc.ssl.enabled}") private boolean sslEnabled; @Value("${cloud.rpc.ssl.cert}") private String certResource; private ManagedChannel channel; private StreamObserver<RequestMsg> inputStream; private static final ReentrantLock uplinkMsgLock = new ReentrantLock(); @Override public void connect(String edgeKey, String edgeSecret, Consumer<UplinkResponseMsg> onUplinkResponse, Consumer<EdgeConfiguration> onEdgeUpdate, Consumer<DownlinkMsg> onDownlink, Consumer<Exception> onError) { NettyChannelBuilder builder = NettyChannelBuilder.forAddress(rpcHost, rpcPort) .keepAliveTime(keepAliveTimeSec, TimeUnit.SECONDS); if (sslEnabled) { try { builder.sslContext(GrpcSslContexts.forClient().trustManager(ResourceUtils.getInputStream(this, certResource)).build()); } catch (SSLException e) { log.error("Failed to initialize channel!", e); throw new RuntimeException(e); } } else { builder.usePlaintext(); } channel = builder.build(); EdgeRpcServiceGrpc.EdgeRpcServiceStub stub = EdgeRpcServiceGrpc.newStub(channel); log.info("[{}] Sending a connect request to the TB!", edgeKey); this.inputStream = stub.handleMsgs(initOutputStream(edgeKey, onUplinkResponse, onEdgeUpdate, onDownlink, onError)); this.inputStream.onNext(RequestMsg.newBuilder() .setMsgType(RequestMsgType.CONNECT_RPC_MESSAGE) .setConnectRequestMsg(ConnectRequestMsg.newBuilder().setEdgeRoutingKey(edgeKey).setEdgeSecret(edgeSecret).build()) .build()); } private StreamObserver<ResponseMsg> initOutputStream(String edgeKey, Consumer<UplinkResponseMsg> onUplinkResponse, Consumer<EdgeConfiguration> onEdgeUpdate, Consumer<DownlinkMsg> onDownlink, Consumer<Exception> onError) { return new StreamObserver<>() { @Override public void onNext(ResponseMsg responseMsg) { if (responseMsg.hasConnectResponseMsg()) { ConnectResponseMsg connectResponseMsg = responseMsg.getConnectResponseMsg(); if (connectResponseMsg.getResponseCode().equals(ConnectResponseCode.ACCEPTED)) { log.info("[{}] Configuration received: {}", edgeKey, connectResponseMsg.getConfiguration()); onEdgeUpdate.accept(connectResponseMsg.getConfiguration()); } else { log.error("[{}] Failed to establish the connection! Code: {}. Error message: {}.", edgeKey, connectResponseMsg.getResponseCode(), connectResponseMsg.getErrorMsg()); try { EdgeGrpcClient.this.disconnect(true); } catch (InterruptedException e) { log.error("[{}] Got interruption during disconnect!", edgeKey, e); } onError.accept(new EdgeConnectionException("Failed to establish the connection! Response code: " + connectResponseMsg.getResponseCode().name())); } } else if (responseMsg.hasEdgeUpdateMsg()) { log.debug("[{}] Edge update message received {}", edgeKey, responseMsg.getEdgeUpdateMsg()); onEdgeUpdate.accept(responseMsg.getEdgeUpdateMsg().getConfiguration()); } else if (responseMsg.hasUplinkResponseMsg()) { log.debug("[{}] Uplink response message received {}", edgeKey, responseMsg.getUplinkResponseMsg()); onUplinkResponse.accept(responseMsg.getUplinkResponseMsg()); } else if (responseMsg.hasDownlinkMsg()) { log.debug("[{}] Downlink message received {}", edgeKey, responseMsg.getDownlinkMsg()); onDownlink.accept(responseMsg.getDownlinkMsg()); } } @Override public void onError(Throwable t) { log.debug("[{}] The rpc session received an error!", edgeKey, t); try { EdgeGrpcClient.this.disconnect(true); } catch (InterruptedException e) { log.error("[{}] Got interruption during disconnect!", edgeKey, e); } onError.accept(new RuntimeException(t)); } @Override public void onCompleted() { log.debug("[{}] The rpc session was closed!", edgeKey); } }; } @Override public void disconnect(boolean onError) throws InterruptedException { if (!onError) { try { inputStream.onCompleted(); } catch (Exception e) { log.error("Exception during onCompleted", e); } } if (channel != null) { channel.shutdown(); int attempt = 0; do { try { channel.awaitTermination(timeoutSecs, TimeUnit.SECONDS); } catch (Exception e) { log.error("Channel await termination was interrupted", e); } if (attempt > 5) { log.warn("We had reached maximum of termination attempts. Force closing channel"); try { channel.shutdownNow(); } catch (Exception e) { log.error("Exception during shutdownNow", e); } break; } attempt++; } while (!channel.isTerminated()); } } @Override public void sendUplinkMsg(UplinkMsg msg) { uplinkMsgLock.lock(); try { this.inputStream.onNext(RequestMsg.newBuilder() .setMsgType(RequestMsgType.UPLINK_RPC_MESSAGE) .setUplinkMsg(msg) .build()); } finally { uplinkMsgLock.unlock(); } } @Override public void sendSyncRequestMsg(boolean syncRequired) { uplinkMsgLock.lock(); try { SyncRequestMsg syncRequestMsg = SyncRequestMsg.newBuilder().setSyncRequired(syncRequired).build(); this.inputStream.onNext(RequestMsg.newBuilder() .setMsgType(RequestMsgType.SYNC_REQUEST_RPC_MESSAGE) .setSyncRequestMsg(syncRequestMsg) .build()); } finally { uplinkMsgLock.unlock(); } } @Override public void sendDownlinkResponseMsg(DownlinkResponseMsg downlinkResponseMsg) { uplinkMsgLock.lock(); try { this.inputStream.onNext(RequestMsg.newBuilder() .setMsgType(RequestMsgType.UPLINK_RPC_MESSAGE) .setDownlinkResponseMsg(downlinkResponseMsg) .build()); } finally { uplinkMsgLock.unlock(); } } }
43.716814
188
0.608907
87fbb937a26a819ca6f295b75c693ac8efe0a2b4
9,328
/******************************************************************************* * Copyright 2013 SAP AG * * 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.sap.core.odata.core.ep.producer; import static org.custommonkey.xmlunit.XMLAssert.assertXpathEvaluatesTo; import static org.custommonkey.xmlunit.XMLAssert.assertXpathExists; import static org.custommonkey.xmlunit.XMLAssert.assertXpathNotExists; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import java.io.IOException; import java.io.InputStream; import java.util.HashMap; import java.util.Locale; import java.util.Map; import org.custommonkey.xmlunit.SimpleNamespaceContext; import org.custommonkey.xmlunit.XMLUnit; import org.junit.BeforeClass; import org.junit.Test; import com.sap.core.odata.api.ODataServiceVersion; import com.sap.core.odata.api.commons.HttpStatusCodes; import com.sap.core.odata.api.commons.ODataHttpHeaders; import com.sap.core.odata.api.edm.Edm; import com.sap.core.odata.api.ep.EntityProvider; import com.sap.core.odata.api.processor.ODataErrorContext; import com.sap.core.odata.api.processor.ODataResponse; import com.sap.core.odata.core.commons.ContentType; import com.sap.core.odata.core.ep.AbstractXmlProducerTestHelper; import com.sap.core.odata.core.ep.AtomEntityProvider; import com.sap.core.odata.core.ep.ProviderFacadeImpl; import com.sap.core.odata.testutil.helper.StringHelper; /** * @author SAP AG */ public class XmlErrorProducerTest extends AbstractXmlProducerTestHelper { private static final String contentType = ContentType.APPLICATION_XML.toContentTypeString(); private static final HttpStatusCodes expectedStatus = HttpStatusCodes.INTERNAL_SERVER_ERROR; public XmlErrorProducerTest(final StreamWriterImplType type) { super(type); } @BeforeClass public static void setup() throws Exception { Map<String, String> prefixMap = new HashMap<String, String>(); prefixMap.put("a", Edm.NAMESPACE_M_2007_08); XMLUnit.setXpathNamespaceContext(new SimpleNamespaceContext(prefixMap)); } @Test public void viaRuntimeDelegate() throws Exception { ODataErrorContext context = new ODataErrorContext(); context.setContentType(contentType); context.setHttpStatus(expectedStatus); context.setErrorCode(null); context.setMessage(null); context.setLocale(null); context.setInnerError(null); ODataResponse response = EntityProvider.writeErrorDocument(context); String errorXml = verifyResponse(response); verifyXml(null, null, null, null, errorXml); context.setErrorCode("a"); context.setMessage("a"); context.setLocale(Locale.GERMAN); context.setInnerError("a"); response = EntityProvider.writeErrorDocument(context); errorXml = verifyResponse(response); verifyXml("a", "a", Locale.GERMAN, "a", errorXml); context.setErrorCode(null); context.setInnerError(null); response = EntityProvider.writeErrorDocument(context); errorXml = verifyResponse(response); verifyXml(null, "a", Locale.GERMAN, null, errorXml); } @Test public void viaProviderFacadeImpl() throws Exception { String errorCode = null; String message = null; Locale locale = null; String innerError = null; ODataErrorContext ctx = new ODataErrorContext(); ctx.setContentType(contentType); ctx.setErrorCode(errorCode); ctx.setHttpStatus(expectedStatus); ctx.setLocale(locale); ctx.setMessage(message); ODataResponse response = new ProviderFacadeImpl().writeErrorDocument(ctx); String errorXml = verifyResponse(response); verifyXml(errorCode, message, locale, innerError, errorXml); errorCode = "a"; message = "a"; locale = Locale.GERMAN; innerError = "a"; ctx = new ODataErrorContext(); ctx.setContentType(contentType); ctx.setErrorCode(errorCode); ctx.setHttpStatus(expectedStatus); ctx.setLocale(locale); ctx.setMessage(message); ctx.setInnerError(innerError); response = new ProviderFacadeImpl().writeErrorDocument(ctx); errorXml = verifyResponse(response); verifyXml(errorCode, message, locale, innerError, errorXml); errorCode = null; message = "a"; locale = Locale.GERMAN; innerError = null; ctx = new ODataErrorContext(); ctx.setContentType(contentType); ctx.setErrorCode(errorCode); ctx.setHttpStatus(expectedStatus); ctx.setLocale(locale); ctx.setMessage(message); ctx.setInnerError(innerError); response = new ProviderFacadeImpl().writeErrorDocument(ctx); errorXml = verifyResponse(response); verifyXml(errorCode, message, locale, innerError, errorXml); } @Test public void normal() throws Exception { serializeError(null, "Message", null, Locale.GERMAN); serializeError(null, "Message", null, Locale.ENGLISH); serializeError(null, "Message", null, Locale.CANADA); serializeError(null, "Message", null, Locale.FRANCE); serializeError(null, "Message", null, Locale.CHINA); } @Test public void none() throws Exception { serializeError(null, null, null, null); } @Test public void onlyErrorCode() throws Exception { serializeError("ErrorCode", null, null, null); } @Test public void onlyMessage() throws Exception { serializeError(null, "message", null, null); } @Test public void onlyInnerError() throws Exception { serializeError(null, null, "InnerError", null); } @Test public void onlyLocale() throws Exception { serializeError(null, null, null, Locale.GERMANY); } @Test public void withoutMessage() throws Exception { serializeError("ErrorCode", null, null, Locale.GERMAN); } @Test public void normalWithErrorCodeVariation() throws Exception { serializeError("", "Message", null, Locale.GERMAN); serializeError(" ", "Message", null, Locale.GERMAN); } @Test public void normalWithInnerErrorVariation() throws Exception { serializeError(null, "Message", "", Locale.GERMAN); serializeError(null, "Message", " ", Locale.GERMAN); } @Test public void all() throws Exception { serializeError("ErrorCode", "Message", "InnerError", Locale.GERMAN); serializeError("ErrorCode", "Message", "InnerError", Locale.ENGLISH); serializeError("ErrorCode", "Message", "InnerError", Locale.CANADA); serializeError("ErrorCode", "Message", "InnerError", Locale.FRANCE); serializeError("ErrorCode", "Message", "InnerError", Locale.CHINA); } private String getLang(final Locale locale) { if (locale == null) { return ""; } if (locale.getCountry().isEmpty()) { return locale.getLanguage(); } else { return locale.getLanguage() + "-" + locale.getCountry(); } } private void serializeError(final String errorCode, final String message, final String innerError, final Locale locale) throws Exception { ODataResponse response = new AtomEntityProvider().writeErrorDocument(expectedStatus, errorCode, message, locale, innerError); String errorXml = verifyResponse(response); verifyXml(errorCode, message, locale, innerError, errorXml); } private String verifyResponse(final ODataResponse response) throws IOException { assertNotNull(response); assertNotNull(response.getEntity()); assertEquals(ContentType.APPLICATION_XML.toContentTypeString(), response.getContentHeader()); assertEquals(expectedStatus, response.getStatus()); assertNotNull(response.getHeader(ODataHttpHeaders.DATASERVICEVERSION)); assertEquals(ODataServiceVersion.V10, response.getHeader(ODataHttpHeaders.DATASERVICEVERSION)); String xmlString = StringHelper.inputStreamToString((InputStream) response.getEntity()); return xmlString; } private void verifyXml(final String errorCode, final String message, final Locale locale, final String innerError, final String errorXml) throws Exception { assertXpathExists("/a:error", errorXml); if (errorCode != null) { assertXpathEvaluatesTo(errorCode, "/a:error/a:code", errorXml); } else { assertXpathExists("/a:error/a:code", errorXml); } if (message != null) { assertXpathEvaluatesTo(message, "/a:error/a:message", errorXml); assertXpathExists("/a:error/a:message[@xml:lang=\"" + getLang(locale) + "\"]", errorXml); } else { if (locale == null) { assertXpathExists("/a:error/a:message[@xml:lang='']", errorXml); } else { assertXpathExists("/a:error/a:message[@xml:lang=\"" + getLang(locale) + "\"]", errorXml); } } if (innerError == null) { assertXpathNotExists("/a:error/a:innererror", errorXml); } else { assertXpathExists("/a:error/a:innererror", errorXml); } } }
35.333333
158
0.714944
2fe4fa226eb90a109d9ba08601cebef89955dc88
2,208
package ch.jjoller.mcaixictw; import java.util.ArrayList; import java.util.List; public class Util { public static int bool2Int(boolean b) { return b ? 1 : 0; } public static String toString(List<Boolean> symlist) { String s = ""; for (boolean b : symlist) { String one = b ? "1" : "0"; s += one; } return s; } /** * Return a random integer between [0, end) * * @param range * @return */ public static int randRange(int end) { return ((int) Math.round(Math.random() * end)) % end; } public static boolean randSym() { return Math.random() < 0.5 ? true : false; } /** * Decodes the value encoded on the end of a list of symbols * * @param symlist * @return */ public static int decode(List<Boolean> symlist) { int value = 0; for (int i = 0; i < symlist.size(); i++) { int k = symlist.get(i) ? 1 : 0; value = 2 * value + k; } return value; } /** * Encodes a value onto the end of a symbol list using "bits" symbols. the * most significant bit is at position 0 of the list. * * @param value * @param bits * @return */ public static List<Boolean> encode(int value, int bits) { List<Boolean> symlist = new ArrayList<Boolean>(); for (int i = 0; i < bits; i++, value /= 2) { boolean sym = (value & 1) == 1 ? true : false; symlist.add(0, sym); } return symlist; } /** * decrease the resolution of the given value to a number with the given * number of bits. the given value should be a number between 0 and 1. for * example if the number of bits is 3 then 1 would be encoded as 7 (111). * * @param val * @param bits * @return */ public static int decreaseResolution(double val, int bits) { assert (val <= 1.0 && val >= 0.0); // maximal possible value, all bits set to 1. int max = (1 << bits) - 1; return (int) Math.round(val * max); } /** * returns the number of bits needed to encode the given amount of states. * * @param states * @return */ public static int bitsNeeded(int states) { assert (states > 1); int i, c; for (i = 1, c = 1; i < states; i *= 2, c++) { } assert (c - 1 > 0); return c - 1; } public static boolean DebugOutput = false; }
21.647059
75
0.607337
291b22edcbf8ee2fe840ec206955b8d441e9193d
256
package com.wyq.firehelper.developkit.dagger; import dagger.Component; @ActivityScope @Component(dependencies = {AppComponent.class},modules = {ActivityModule.class}) public interface ActivityComponent { void inject(DaggerActivity daggerActivity); }
25.6
80
0.808594
1d1356152a49341b2c398d1e56ae149b714e064e
738
package br.com.centralit.citcorpore.negocio; import java.util.List; import br.com.centralit.citcorpore.bean.TipoMovimFinanceiraViagemDTO; import br.com.citframework.service.CrudService; /** * @author ronnie.lopes * */ public interface TipoMovimFinanceiraViagemService extends CrudService { public List<TipoMovimFinanceiraViagemDTO> listByClassificacao(String classificacao) throws Exception; public TipoMovimFinanceiraViagemDTO findByMovimentacao(Long idtipoMovimFinanceiraViagem) throws Exception; public TipoMovimFinanceiraViagemDTO findByMovimentacaoEstadoAdiantamento(Long idtipoMovimFinanceiraViagem, String adiantamento) throws Exception; public List<TipoMovimFinanceiraViagemDTO> recuperaTipoAtivos() throws Exception; }
41
146
0.860434
6c7bd69527c3fc8cecff6f98ae98f5fbb5702f2d
1,322
package leetcode.editor.cn; import java.util.Stack; /** * Created with IntelliJ IDEA. * <p> * Date: 2019-01-08 * Time: 22:22 * ### [20\. Valid Parentheses](https://leetcode-cn.com/problems/valid-parentheses/) * <p> * <p> * Given a string containing just the characters `'('`, `')'`, `'{'`, `'}'`, `'['` and `']'`, determine if the input string is valid. * <p> * An input string is valid if: * <p> * Note that an empty string is also considered valid. * <p> * **Example 1:** * <p> * **Example 2:** * <p> * **Example 3:** * <p> * **Example 4:** * <p> * **Example 5:** * <p> * ``` * Input: "()" * Output: true * Input: "()[]{}" * Output: true * Input: "(]" * Output: false * Input: "([)]" * Output: false * Input: "{[]}" * Output: true */ public class ValidParentheses{ /** * cost 13ms */ public boolean isValid(String s){ Stack<Character> stack = new Stack<>(); for(int i=0;i<s.length();i++){ char ch = s.charAt(i); if(ch=='('||ch=='['||ch=='{'){ stack.push(ch); }else { if(stack.isEmpty()){ return false; } char topChar = stack.pop(); if(topChar=='('&&ch!=')'){ return false; }else if(topChar=='['&&ch!=']'){ return false; }else if(topChar=='{'&&ch!='}'){ return false; } } } return stack.isEmpty(); } }
19.441176
133
0.521936
5cee4e6ad554bb8f4f6e7a3fd4888b71db5368c6
4,117
// // This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.4-2 // See <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a> // Any modifications to this file will be lost upon recompilation of the source schema. // Generated on: 2015.05.18 at 05:13:02 PM MST // package eml.ecoinformatics_org.spatialraster_2_1; import javax.xml.bind.JAXBElement; import javax.xml.bind.annotation.XmlElementDecl; import javax.xml.bind.annotation.XmlRegistry; import javax.xml.namespace.QName; /** * This object contains factory methods for each * Java content interface and Java element interface * generated in the eml.ecoinformatics_org.spatialraster_2_1 package. * <p>An ObjectFactory allows you to programatically * construct new instances of the Java representation * for XML content. The Java representation of XML * content can consist of schema derived interfaces * and classes representing the binding of schema * type definitions, element declarations and model * groups. Factory methods for each of these are * provided in this class. * */ @XmlRegistry public class ObjectFactory { private final static QName _SpatialRaster_QNAME = new QName("eml://ecoinformatics.org/spatialRaster-2.1.1", "spatialRaster"); /** * Create a new ObjectFactory that can be used to create new instances of schema derived classes for package: eml.ecoinformatics_org.spatialraster_2_1 * */ public ObjectFactory() { } /** * Create an instance of {@link DataQuality } * */ public DataQuality createDataQuality() { return new DataQuality(); } /** * Create an instance of {@link SpatialRasterType } * */ public SpatialRasterType createSpatialRasterType() { return new SpatialRasterType(); } /** * Create an instance of {@link SpatialRasterType.GeoreferenceInfo } * */ public SpatialRasterType.GeoreferenceInfo createSpatialRasterTypeGeoreferenceInfo() { return new SpatialRasterType.GeoreferenceInfo(); } /** * Create an instance of {@link BandType } * */ public BandType createBandType() { return new BandType(); } /** * Create an instance of {@link DataQuality.QuantitativeAccuracyReport } * */ public DataQuality.QuantitativeAccuracyReport createDataQualityQuantitativeAccuracyReport() { return new DataQuality.QuantitativeAccuracyReport(); } /** * Create an instance of {@link SpatialRasterType.ImageDescription } * */ public SpatialRasterType.ImageDescription createSpatialRasterTypeImageDescription() { return new SpatialRasterType.ImageDescription(); } /** * Create an instance of {@link SpatialRasterType.GeoreferenceInfo.CornerPoint } * */ public SpatialRasterType.GeoreferenceInfo.CornerPoint createSpatialRasterTypeGeoreferenceInfoCornerPoint() { return new SpatialRasterType.GeoreferenceInfo.CornerPoint(); } /** * Create an instance of {@link SpatialRasterType.GeoreferenceInfo.ControlPoint } * */ public SpatialRasterType.GeoreferenceInfo.ControlPoint createSpatialRasterTypeGeoreferenceInfoControlPoint() { return new SpatialRasterType.GeoreferenceInfo.ControlPoint(); } /** * Create an instance of {@link SpatialRasterType.GeoreferenceInfo.BilinearFit } * */ public SpatialRasterType.GeoreferenceInfo.BilinearFit createSpatialRasterTypeGeoreferenceInfoBilinearFit() { return new SpatialRasterType.GeoreferenceInfo.BilinearFit(); } /** * Create an instance of {@link JAXBElement }{@code <}{@link SpatialRasterType }{@code >}} * */ @XmlElementDecl(namespace = "eml://ecoinformatics.org/spatialRaster-2.1.1", name = "spatialRaster") public JAXBElement<SpatialRasterType> createSpatialRaster(SpatialRasterType value) { return new JAXBElement<SpatialRasterType>(_SpatialRaster_QNAME, SpatialRasterType.class, null, value); } }
32.936
154
0.710712
71ef7a1ead9907f0d9b41ed9b92db66193d063ae
224
package spaces; import static org.junit.jupiter.api.Assertions.*; import org.junit.jupiter.api.*; class SpacesTests { @Test void moduleSpaces() { assertEquals("spaces", Spaces.class.getModule().getName()); } }
16
63
0.705357
1792f7fae2c485d04f4f7fc905081eaa3e7fe2d6
539
import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertTrue; import org.junit.jupiter.api.Test; class SolutionTest { @Test void sample() { assertTrue(Solution.isAllPossibilities(new int[]{0, 1, 2, 3})); assertFalse(Solution.isAllPossibilities(new int[]{1, 2, 3, 4})); assertFalse(Solution.isAllPossibilities(new int[]{6, 0, 4})); assertFalse(Solution.isAllPossibilities(new int[]{0, 2, 2, 3})); assertFalse(Solution.isAllPossibilities(new int[0])); } }
33.6875
68
0.723562
80d3bfceb38c2b27ef72d588aebb1a4059a5dd72
1,809
package no.nav.foreldrepenger.regler.uttak.fastsetteperiode.grunnlag; import java.time.LocalDate; public final class Datoer { private LocalDate omsorgsovertakelse; private LocalDate termin; private LocalDate fødsel; private Dødsdatoer dødsdatoer; //Ikke sleng inn flere datoer her uten å prøve å plassere i andre mer passende klasser private Datoer() { } public LocalDate getFamiliehendelse() { if (getOmsorgsovertakelse() != null) { return getOmsorgsovertakelse(); } if (getFødsel() != null) { return getFødsel(); } if (getTermin() != null) { return getTermin(); } throw new IllegalStateException("Ingen familiehendelse"); } public LocalDate getTermin() { return termin; } public LocalDate getFødsel() { return fødsel; } public LocalDate getOmsorgsovertakelse() { return omsorgsovertakelse; } public Dødsdatoer getDødsdatoer() { return dødsdatoer; } public static class Builder { private final Datoer kladd = new Datoer(); public Builder fødsel(LocalDate fødsel) { kladd.fødsel = fødsel; return this; } public Builder termin(LocalDate termin) { kladd.termin = termin; return this; } public Builder omsorgsovertakelse(LocalDate omsorgsovertakelse) { kladd.omsorgsovertakelse = omsorgsovertakelse; return this; } public Builder dødsdatoer(Dødsdatoer.Builder dødsdatoer) { kladd.dødsdatoer = dødsdatoer == null ? null : dødsdatoer.build(); return this; } public Datoer build() { return kladd; } } }
24.445946
90
0.60199
b15360f1fda8eef27c99b2c3a54147db312a2c69
942
package tu.bp21.passwortmanager.db.entities; import androidx.annotation.NonNull; import androidx.room.Entity; import androidx.room.ForeignKey; @Entity( primaryKeys = {"username", "websiteName", "webAddress"}, foreignKeys = { @ForeignKey( entity = Website.class, parentColumns = {"username", "websiteName"}, childColumns = {"username", "websiteName"}, onDelete = ForeignKey.CASCADE, onUpdate = ForeignKey.CASCADE) }) public class Url { @NonNull public String websiteName; @NonNull public String username; @NonNull public String webAddress; public Url(@NonNull String username, @NonNull String websiteName, @NonNull String webAddress) { this.username = username; this.websiteName = websiteName; this.webAddress = webAddress; } // adapted for simple json delivery @Override public String toString() { return "\"" + webAddress + "\""; } }
26.914286
97
0.677282
cb9a38a4a4fc878b85d4d06dd6c5617567187c93
658
package rnr.home.panicreducer.controller; import io.micrometer.core.annotation.Timed; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RestController; import java.io.IOException; @RestController @Timed public class TestController { @RequestMapping(value = "/one", method = RequestMethod.GET) public String one() throws InterruptedException{ Thread.sleep(10000);return "Method One"; } @RequestMapping(value = "/two", method = RequestMethod.GET) public String two() { return "Method Two"; } }
28.608696
63
0.75076
0506277683e4f28e898c1ec9d3cd7ba2b48f0c07
6,224
package com.malalaoshi.android.fragments.schoolpicker; import android.content.Intent; import android.os.Bundle; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.AdapterView; import android.widget.ListView; import android.widget.RelativeLayout; import android.widget.TextView; import com.malalaoshi.android.R; import com.malalaoshi.android.activitys.schoolpicker.CityPickerActivity; import com.malalaoshi.android.adapters.SchoolPickerAdapter; import com.malalaoshi.android.network.api.SchoolListApi; import com.malalaoshi.android.core.base.BaseFragment; import com.malalaoshi.android.core.network.api.ApiExecutor; import com.malalaoshi.android.core.network.api.BaseApiContext; import com.malalaoshi.android.entity.City; import com.malalaoshi.android.entity.School; import com.malalaoshi.android.network.result.SchoolListResult; import com.malalaoshi.android.utils.MiscUtil; import java.util.List; import butterknife.Bind; import butterknife.ButterKnife; import butterknife.OnClick; /** * Created by kang on 16/8/16. */ public class SchoolPickerFragment extends BaseFragment implements AdapterView.OnItemClickListener { public static String ARGS_CITY = "city"; public static String EXTRA_IS_INIT_SCHOOL = "isInitSchool"; @Bind(R.id.ll_city) protected RelativeLayout rlCity; @Bind(R.id.tv_picker_tiptext) protected TextView tvPickerTiptext; @Bind(R.id.tv_city) protected TextView tvCity; @Bind(R.id.gv_all_schools) protected ListView gvAllSchools; protected SchoolPickerAdapter schoolPickerAdapter; public boolean isInitSchool = true; private City city; private List<School> schools; private OnSchoolClick onSchoolClick; public static SchoolPickerFragment newInstance(City city,boolean isInitSchool) { SchoolPickerFragment schoolPickerFragment = new SchoolPickerFragment(); Bundle bundle = new Bundle(); bundle.putParcelable(ARGS_CITY,city); bundle.putBoolean(EXTRA_IS_INIT_SCHOOL,isInitSchool); schoolPickerFragment.setArguments(bundle); return schoolPickerFragment; } @Nullable @Override public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { View view = inflater.inflate(R.layout.fragment_school_picker, container, false); ButterKnife.bind(this, view); init(); initData(); initView(); setEvent(); return view; } private void init() { Bundle bundle = getArguments(); if (bundle!=null){ city = bundle.getParcelable(ARGS_CITY); isInitSchool = bundle.getBoolean(EXTRA_IS_INIT_SCHOOL); } } private void initView() { if (isInitSchool){ rlCity.setVisibility(View.GONE); tvPickerTiptext.setVisibility(View.GONE); }else{ tvCity.setText(city.getName()); } } private void setEvent() { gvAllSchools.setOnItemClickListener(this); } private void initData() { schoolPickerAdapter = new SchoolPickerAdapter(getContext()); gvAllSchools.setAdapter(schoolPickerAdapter); loadData(); } private void loadData() { ApiExecutor.exec(new FetchSchoolListRequest(this,city.getId())); } public void setOnSchoolClick(OnSchoolClick onSchoolClick) { this.onSchoolClick = onSchoolClick; } @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { if (onSchoolClick!=null){ onSchoolClick.onSchoolClick(city, schools.get(position)); } } private static final class FetchSchoolListRequest extends BaseApiContext<SchoolPickerFragment, SchoolListResult> { private Long cityId; @Override public void onApiStarted() { get().startProcessDialog("加载中..."); super.onApiStarted(); } public FetchSchoolListRequest(SchoolPickerFragment cityPickerFragment, Long cityId) { super(cityPickerFragment); this.cityId = cityId; } @Override public SchoolListResult request() throws Exception { return new SchoolListApi().getSchoolsByCityId(cityId); } @Override public void onApiSuccess(@NonNull SchoolListResult response) { get().onLoadSuccess(response); } @Override public void onApiFailure(Exception exception) { get().onLoadFailed(); } @Override public void onApiFinished() { super.onApiFinished(); get().stopProcessDialog(); } } private void onLoadFailed() { MiscUtil.toast("加载失败,请检查网络"); } private void onLoadSuccess(SchoolListResult response) { if (response == null) { onLoadFailed(); } schools = response.getResults(); if (schools!=null){ Log.e("school","schools:"+schools.size()); schoolPickerAdapter.clear(); schoolPickerAdapter.addAll(schools); schoolPickerAdapter.notifyDataSetChanged(); } } public interface OnSchoolClick { void onSchoolClick(City city, School school); } @OnClick(R.id.ll_city) void onClickPickerCity(View view){ CityPickerActivity.openForResult(this,CityPickerActivity.RESULT_CODE_CITY); } @Override public void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); if (CityPickerActivity.RESULT_CODE_CITY==resultCode&&data!=null){ //更新老师列表数据 city = data.getParcelableExtra(CityPickerActivity.EXTRA_CITY); tvCity.setText(city.getName()); schoolPickerAdapter.clear(); schoolPickerAdapter.notifyDataSetChanged(); loadData(); } } @Override public String getStatName() { return "城市选择"; } }
29.923077
123
0.679467
ef3b6ae10cd785e775e20439e6c64f9b8e614d03
2,131
package fri.util.database.jpa.tree.examples.closuretable.temporal; import java.util.Date; import javax.persistence.Entity; import javax.persistence.Id; import javax.persistence.IdClass; import javax.persistence.JoinColumn; import javax.persistence.ManyToOne; import javax.persistence.Temporal; import javax.persistence.TemporalType; import fri.util.database.jpa.tree.closuretable.ClosureTableTreeNode; import fri.util.database.jpa.tree.closuretable.TemporalTreePath; import fri.util.database.jpa.tree.examples.closuretable.CompositePersonTreePathId; import fri.util.database.jpa.tree.examples.closuretable.PersonAbstractTreePath; import fri.util.database.jpa.tree.examples.closuretable.PersonCtt; /** Example for temporal TreePath implementation. */ @Entity @IdClass(CompositePersonTreePathId.class) // has a composite primary key public class PersonTemporalTreePath extends PersonAbstractTreePath implements TemporalTreePath { @Id @ManyToOne(targetEntity = PersonCtt.class) @JoinColumn(name = "ancestor", nullable = false) // the name of the database foreign key column private ClosureTableTreeNode ancestor; @Id @ManyToOne(targetEntity = PersonCtt.class) @JoinColumn(name = "descendant", nullable = false) // the name of the database foreign key column private ClosureTableTreeNode descendant; @Temporal(TemporalType.TIMESTAMP) private Date validFrom; @Temporal(TemporalType.TIMESTAMP) private Date validTo; @Override public ClosureTableTreeNode getAncestor() { return ancestor; } @Override public void setAncestor(ClosureTableTreeNode ancestor) { this.ancestor = ancestor; } @Override public ClosureTableTreeNode getDescendant() { return descendant; } @Override public void setDescendant(ClosureTableTreeNode descendant) { this.descendant = descendant; } // interface Temporal @Override public Date getValidTo() { return validTo; } @Override public void setValidTo(Date validTo) { this.validTo = validTo; } @Override public Date getValidFrom() { return validFrom; } @Override public void setValidFrom(Date validFrom) { this.validFrom = validFrom; } }
27.675325
98
0.792116
04acc856cbe9dcfdcd43da589ec8b7c36be1fa2f
355
package controller; public class GraphicsEngine { private static GraphicsEngine instance = null; protected GraphicsEngine() {} // Exists only to defeat instantiation. public static GraphicsEngine getInstance() { if(instance == null) { instance = new GraphicsEngine(); } return instance; } }
22.1875
73
0.633803
7221bc796440bd931eeb19c5d92c618e0408f514
6,669
package com.google.code.siren4j.converter; import java.net.URL; import java.util.Collection; import java.util.HashMap; import java.util.HashSet; import java.util.Map; import java.util.Set; import org.apache.commons.collections.MapUtils; import org.apache.commons.lang3.StringUtils; import org.reflections.Reflections; import org.reflections.util.ClasspathHelper; import org.reflections.util.ConfigurationBuilder; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.google.code.siren4j.annotations.Siren4JEntity; import com.google.code.siren4j.error.Siren4JException; /** * The resource registry keeps a list of all Siren4J Resources as defined by their * {@link Siren4JEntity} annotation. The name is used as the classname. The names therefore must be * unique on the classpath. If two of the same named resources are found then an exception will be thrown during * classpath scanning. This is required for the * {@link ReflectingConverter#toObject(com.google.code.siren4j.component.Entity)} method so * it can figure out which classes to reconstitute. */ public class ResourceRegistryImpl implements ResourceRegistry { private Map<String, Class<?>> entries = new HashMap<String, Class<?>>(); private static Logger LOG = LoggerFactory.getLogger(ResourceRegistryImpl.class); private ResourceRegistryImpl(String... packages) throws Siren4JException { init(packages); } /** * Retrieve a new resource registry instance. * * @param packages array of package pattern strings that will be searched * for resources. * @return the instance, never <code>null</code>. * @throws Siren4JException */ public static ResourceRegistry newInstance(String... packages) throws Siren4JException { return new ResourceRegistryImpl(packages); } /* (non-Javadoc) * @see com.google.code.siren4j.converter.ResourceRegistry#getClassByEntityName(java.lang.String) */ public Class<?> getClassByEntityName(String name) { if (StringUtils.isBlank(name)) { throw new IllegalArgumentException("name cannot be null or empty."); } return entries.get(name); } /* (non-Javadoc) * @see com.google.code.siren4j.converter.ResourceRegistry#getAllEntries() */ @SuppressWarnings("unchecked") public Map<String, Class<?>> getAllEntries() { return (Map<String, Class<?>>) MapUtils.unmodifiableMap(entries); } /* (non-Javadoc) * @see com.google.code.siren4j.converter.ResourceRegistry#containsEntityEntry(java.lang.String) */ public boolean containsEntityEntry(String entityName) { if (StringUtils.isBlank(entityName)) { throw new IllegalArgumentException("entityName cannot be null or empty."); } return entries.containsKey(entityName); } /* (non-Javadoc) * @see com.google.code.siren4j.converter.ResourceRegistry#containsClassEntry(java.lang.Class) */ public boolean containsClassEntry(Class<?> clazz) { if (clazz == null) { throw new IllegalArgumentException("clazz cannot be null."); } return entries.containsValue(clazz); } /* (non-Javadoc) * @see com.google.code.siren4j.converter.ResourceRegistry#putEntry(java.lang.String, java.lang.Class, boolean) */ public void putEntry(String entityName, Class<?> clazz, boolean overwrite) throws Siren4JException { if (StringUtils.isBlank(entityName)) { throw new IllegalArgumentException("entityName cannot be null or empty."); } if (clazz == null) { throw new IllegalArgumentException("clazz cannot be null."); } if (!overwrite && containsEntityEntry(entityName)) { String newline = "\n"; StringBuilder msg = new StringBuilder("Attempted to add a resource with duplicate name to the registry: "); msg.append(newline); msg.append("Entity Name: "); msg.append(entityName); msg.append(newline); msg.append("Existing class: "); msg.append(getClassByEntityName(entityName).getName()); msg.append(newline); msg.append("Other class: "); msg.append(clazz.getName()); LOG.error(msg.toString()); throw new Siren4JException(msg.toString()); } LOG.info("Found Siren4J resource: [name: " + entityName + "] [class: " + clazz.getName() + "]"); entries.put(entityName, clazz); } /** * Scans the classpath for resources. * * @param packages * @throws Siren4JException */ @SuppressWarnings("deprecation") private void init(String... packages) throws Siren4JException { LOG.info("Siren4J scanning classpath for resource entries..."); Reflections reflections = null; ConfigurationBuilder builder = new ConfigurationBuilder(); Collection<URL> urls = new HashSet<URL>(); if (packages != null && packages.length > 0) { //limit scan to packages for (String pkg : packages) { urls.addAll(ClasspathHelper.forPackage(pkg)); } } else { urls.addAll(ClasspathHelper.forPackage("com.")); urls.addAll(ClasspathHelper.forPackage("org.")); urls.addAll(ClasspathHelper.forPackage("net.")); } //Always add Siren4J Resources by default, this will add the collection resource //and what ever other resource gets added to this package and has the entity annotation. urls.addAll(ClasspathHelper.forPackage("com.google.code.siren4j.resource")); builder.setUrls(urls); reflections = new Reflections(builder); Set<Class<?>> types = reflections.getTypesAnnotatedWith(Siren4JEntity.class); for (Class<?> c : types) { Siren4JEntity anno = c.getAnnotation(Siren4JEntity.class); String name = StringUtils .defaultIfBlank(anno.name(), anno.entityClass().length > 0 ? anno.entityClass()[0] : c.getName()); putEntry(StringUtils.defaultIfEmpty(name, c.getName()), c, false); // Always add the class name as an entry in the index if it does not already exist. if (!containsEntityEntry(c.getName())) { putEntry(StringUtils.defaultIfEmpty(c.getName(), c.getName()), c, false); } } } }
41.166667
120
0.641775
df33f48b87c3fe424df1f9780e21a7b695d67854
2,300
/******************************************************************************* * Copyright 2012 Apigee Corporation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ package org.usergrid.persistence.cassandra; import java.util.UUID; import org.usergrid.persistence.ConnectedEntityRef; import org.usergrid.persistence.EntityRef; import org.usergrid.persistence.SimpleEntityRef; public class ConnectedEntityRefImpl extends SimpleEntityRef implements ConnectedEntityRef { final String connectionType; public ConnectedEntityRefImpl() { super(null, null); connectionType = null; } public ConnectedEntityRefImpl(UUID entityId) { super(null, entityId); connectionType = null; } public ConnectedEntityRefImpl(EntityRef ref) { super(ref); connectionType = null; } public ConnectedEntityRefImpl(String connectionType, EntityRef connectedEntity) { super(connectedEntity.getType(), connectedEntity.getUuid()); this.connectionType = connectionType; } public ConnectedEntityRefImpl(String connectionType, String entityType, UUID entityId) { super(entityType, entityId); this.connectionType = connectionType; } @Override public String getConnectionType() { return connectionType; } public static String getConnectionType(ConnectedEntityRef connection) { if (connection == null) { return null; } return connection.getConnectionType(); } public static UUID getConnectedEntityId(ConnectedEntityRef connection) { if (connection == null) { return null; } return connection.getUuid(); } public static String getConnectedEntityType(ConnectedEntityRef connection) { if (connection == null) { return null; } return connection.getType(); } }
27.710843
80
0.708261
76af0b27f0a0fdff4297d38125b859d1293e6cf5
2,004
/* * Copyright 2018 Vorlonsoft LLC * * Licensed under The MIT License (MIT) */ package com.vorlonsoft.android.rate; import android.content.Intent; import android.net.Uri; import static com.vorlonsoft.android.rate.StoreType.APPLE; import static com.vorlonsoft.android.rate.StoreType.BLACKBERRY; import static com.vorlonsoft.android.rate.StoreType.GOOGLEPLAY; import static com.vorlonsoft.android.rate.StoreType.INTENT; import static com.vorlonsoft.android.rate.StoreType.OTHER; final class StoreOptions { private int storeType = GOOGLEPLAY; private String applicationId = null; private Intent[] intents = null; StoreOptions() { } String getApplicationId() { return applicationId; } @SuppressWarnings("WeakerAccess") void setApplicationId(String applicationId) { this.applicationId = applicationId; } Intent[] getIntents() { return intents; } @SuppressWarnings("WeakerAccess") void setIntents(Intent[] intents) { this.intents = intents; } int getStoreType() { return storeType; } void setStoreType(final int storeType, final String[] stringParam, final Intent[] intentParaam) { this.storeType = storeType; switch (storeType) { case APPLE: case BLACKBERRY: setApplicationId(stringParam[0]); break; case INTENT: setIntents(intentParaam); break; case OTHER: final Intent[] intents; if (stringParam == null) { intents = null; } else { int length = stringParam.length; intents = new Intent[length]; for (int i = 0; i < length; i++) { intents[i] = new Intent(Intent.ACTION_VIEW, Uri.parse(stringParam[i])); } } setIntents(intents); } } }
26.368421
101
0.589321
e87263a98ea3d410d33d3f3952933f091ee90590
9,760
/** * * Process Editor - Core Package * * (C) 2008,2009 Frank Puhlmann * * http://frapu.net * */ package net.frapu.code.visualization.tracking; import java.awt.Point; import net.frapu.code.visualization.*; import java.util.LinkedList; import java.util.List; import javax.swing.JTextField; /** * * This class tracks the actions of the ProcessModel and the ProcessNodes * contained in a ProcessEditor. * * @todo: Add support for resizement of nodes! * @todo: Add support for multiple selections! * * @author frank */ public class ProcessEditorActionTracker implements ProcessModelListener, ProcessObjectListener, ProcessEditorListener { private ProcessModel currentModel = null; private List<ProcessEditorActionRecord> actionTrack = new LinkedList<ProcessEditorActionRecord>(); private int actionPointer = -1; private boolean tracking = true; public ProcessEditorActionTracker(ProcessEditor editor) { editor.addListener(this); modelChanged(editor.getModel()); log("New ProcessEditorActionTracker created."); } /** * @param text */ protected void log(String text) { //System.out.println(this.hashCode()+": "+text); } public boolean undoLastAction() { ProcessEditorActionRecord lastRecord = popAction(); log("UNDO: "+lastRecord); if (lastRecord!=null) { if (lastRecord instanceof ProcessEditorDragableMovedAction) { ProcessEditorDragableMovedAction action = (ProcessEditorDragableMovedAction)lastRecord; // Return Dragable to last position Dragable o = action.getDragable(); setTracking(false); o.setPos(new Point(action.getOldX(), action.getOldY())); setTracking(true); return true; } if (lastRecord instanceof ProcessEditorPropertyChangedAction) { ProcessEditorPropertyChangedAction action = (ProcessEditorPropertyChangedAction)lastRecord; // Undo property change ProcessObject o = action.getProcessObject(); setTracking(false); o.setProperty(action.getKey(), action.getOldValue()); // Check if Cluster // if (true) { // // Walk back until no more of the same action is to be found // boolean check = true; // while (check) { // ProcessEditorActionRecord prevRecord = getAction(); // if (prevRecord instanceof ProcessEditorPropertyChangedAction) { // ProcessEditorPropertyChangedAction prevAction = // (ProcessEditorPropertyChangedAction) prevRecord; // // Still the same object // if (prevAction.getProcessObject() == action.getProcessObject()) { // if (prevAction.getKey().equals(action.getKey())) { // // Indeed the same // prevAction.getProcessObject().setProperty(prevAction.getKey(), prevAction.getOldValue()); // System.out.println("XY"); // popAction(); // } // } // } else { // check = false; // } // } // } setTracking(true); return true; } if (lastRecord instanceof ProcessEditorObjectCreatedAction) { ProcessEditorObjectCreatedAction action = (ProcessEditorObjectCreatedAction)lastRecord; // Delete object setTracking(false); // Check nodes if (action.getProcessObject() instanceof ProcessNode) currentModel.removeNode((ProcessNode)action.getProcessObject()); // Check edges if (action.getProcessObject() instanceof ProcessEdge) currentModel.removeEdge((ProcessEdge)action.getProcessObject()); setTracking(true); return true; } if (lastRecord instanceof ProcessEditorObjectDeletedAction) { ProcessEditorObjectDeletedAction action = (ProcessEditorObjectDeletedAction)lastRecord; // Create object setTracking(false); if (action.getProcessObject() instanceof ProcessNode) currentModel.addNode((ProcessNode)action.getProcessObject()); if (action.getProcessObject() instanceof ProcessEdge) currentModel.addEdge((ProcessEdge)action.getProcessObject()); setTracking(true); return true; } } return false; } private ProcessEditorActionRecord popAction() { if (actionPointer<0) return null; actionPointer--; return actionTrack.get(actionPointer+1); } @SuppressWarnings("unused") private ProcessEditorActionRecord getAction() { if (actionPointer<0) return null; return actionTrack.get(actionPointer+1); } private void pushAction(ProcessEditorActionRecord record) { if (!isTracking()) return; // Check if pointer != size if (actionPointer!=actionTrack.size()-1) { // Remove everything after the pointer for (int i=actionPointer+1; i<actionTrack.size(); i++) { actionTrack.remove(i); } } // Add action to record actionTrack.add(record); // Log log("RECORD: "+record); // Set actionPointer actionPointer = actionTrack.size()-1; } protected void setTracking(boolean b) { tracking = b; } public boolean isTracking() { return tracking; } // // // ProcessEditor Listener // // @Override public void processObjectClicked(ProcessObject o) { // Ignore } @Override public void processObjectDoubleClicked(ProcessObject o) { // Ignore } @Override public void modelChanged(ProcessModel m) { if (currentModel!=null) { currentModel.removeListener(this); // Remove all ProcessObjectListeners from the old Nodes for (ProcessNode n: currentModel.getNodes()) { n.removeListener(this); } for (ProcessEdge e: currentModel.getEdges()) { e.removeListener(this); } } // Attach ProcessObject listeners to all nodes/edge of the new model for (ProcessNode n: m.getNodes()) { n.addListener(this); } for (ProcessEdge e: m.getEdges()) { e.addListener(this); } m.addListener(this); currentModel = m; // Clear recorded tracks actionTrack.clear(); } @Override public void processObjectDragged(Dragable o, int oldX, int oldY) { ProcessEditorDragableMovedAction record = new ProcessEditorDragableMovedAction(o, oldX, oldY, o.getPos().x, o.getPos().y); // Add action to record pushAction(record); } // // ProcessModel Listener // @Override public void processNodeAdded(ProcessNode newNode) { if (newNode==null) return; newNode.addListener(this); ProcessEditorObjectCreatedAction record = new ProcessEditorObjectCreatedAction(newNode); pushAction(record); } @Override public void processNodeRemoved(ProcessNode remNode) { if (remNode==null) return; remNode.removeListener(this); ProcessEditorObjectDeletedAction record = new ProcessEditorObjectDeletedAction(remNode); pushAction(record); } @Override public void processEdgeAdded(ProcessEdge edge) { if (edge==null) return; edge.addListener(this); ProcessEditorObjectCreatedAction record = new ProcessEditorObjectCreatedAction(edge); pushAction(record); } @Override public void processEdgeRemoved(ProcessEdge edge) { if (edge==null) return; edge.removeListener(this); ProcessEditorObjectDeletedAction record = new ProcessEditorObjectDeletedAction(edge); pushAction(record); } @Override public void processObjectPropertyChange(ProcessObject obj, String name, String oldValue, String newValue) { // ignore } // // ProcessObjectListener // @Override public void propertyChanged(ProcessObject o, String key, String oldValue, String newValue) { // Ignore x, y, width, height (tracked via ProcessEditorListener) if (key.equals(ProcessNode.PROP_XPOS) | key.equals(ProcessNode.PROP_YPOS) | key.equals(ProcessNode.PROP_WIDTH) | key.equals(ProcessNode.PROP_HEIGHT)) return; // Track property changes here!!! ProcessEditorPropertyChangedAction record = new ProcessEditorPropertyChangedAction(o, key, oldValue, newValue); // Add action to record pushAction(record); } @Override public void processNodeEditingFinished(ProcessNode o) { } @Override public void processNodeEditingStarted(ProcessNode o, JTextField textfield) { } }
32
127
0.579508
6d32c166a20bd3517dd156f9e09c399af1083896
1,679
package com.sell.liqihao.sellsystem.base; import android.os.Bundle; import android.support.annotation.Nullable; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.Toolbar; import android.util.Log; import com.sell.liqihao.sellsystem.R; /** * Activity的基类 * Created by wangwenzhang on 2017/11/9. */ public abstract class BaseActivity <P extends BasePresenter>extends AppCompatActivity implements BaseView<P> { protected P presenter; protected String TAG = getClass().getSimpleName(); @Override protected void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(getLayout()); setPresenter(presenter); if (presenter != null) { this.presenter.attachView(this); } else { Log.e("test","presenter is empty"); } initView(); getData(); } /** * 初始化布局 */ public abstract void initView(); /** * 获取数据 */ public abstract void getData(); /** * 设置布局文件id * @return */ public abstract int getLayout(); /** * 布局销毁 调用presenter置空view,防止内存溢出 */ @Override protected void onDestroy() { super.onDestroy(); if (presenter!=null){ presenter.detachView(); } } protected void initToolBar(Toolbar toolbar, boolean homeAsUpEnable, String title) { toolbar.setTitle(title); toolbar.setTitleTextColor(this.getResources().getColor(R.color.topMoney)); setSupportActionBar(toolbar); getSupportActionBar().setDisplayHomeAsUpEnabled(homeAsUpEnable); } }
22.386667
110
0.642049
a36175a34a81f7cd1d41b3e0128f1e288c3f6f2a
2,248
package br.com.dgas.especificidade.ui.activity; import android.content.Intent; import android.os.Bundle; import android.os.Handler; import android.support.v7.app.ActionBarActivity; import android.view.Menu; import android.view.MenuItem; import br.com.dgas.especificidade.R; import br.com.dgas.especificidade.os.task.SinglePlayerDatabaseCheckTask; public class LoadingActivity extends ActionBarActivity implements SinglePlayerDatabaseCheckTask.OnTaskResultListener { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_loading); this.displayMainScreen(); finish(); //this.startSinglePlayerTask(3000); } @SuppressWarnings("unused") private void startSinglePlayerTask(int delay) { final SinglePlayerDatabaseCheckTask singlePlayerTask = new SinglePlayerDatabaseCheckTask(this); final String singlePlayerUrl = getString(R.string.url_singleplayer_version_checker); if (delay > 0) { Handler handler = new Handler(); Runnable runnable = new Runnable() { @Override public void run() { singlePlayerTask.execute(singlePlayerUrl); } }; handler.postDelayed(runnable, delay); } else { singlePlayerTask.execute(singlePlayerUrl); } } private void displayMainScreen() { startActivity(new Intent(this, MainActivity.class)); } @Override public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.menu_loading, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { int id = item.getItemId(); //noinspection SimplifiableIfStatement if (id == R.id.action_settings) { return true; } return super.onOptionsItemSelected(item); } @Override public void onTaskCancelled() { finish(); } @Override public void onTaskComplete() { if (!isFinishing()) { finish(); this.displayMainScreen(); } } }
27.414634
92
0.644128
1ace139f50fd0304f61b2a308a58027879d70cd5
691
package lista.string.pkg1.questao.pkg1; import java.util.Scanner; public class ListaString1Questao1 { public static void main(String[] args) { String frase; int tam; int cont = 0; Scanner in = new Scanner (System.in); System.out.println("Digite a frase: "); frase = in.nextLine(); tam = frase.length(); for(int i = 0; i < tam; i++){ if( frase.charAt(i) == 'a' || frase.charAt(i) == 'e' ||frase.charAt(i) == 'i' || frase.charAt(i) == 'o' ||frase.charAt(i) == 'u'){ cont++; } } System.out.println("Na frase há " + cont + " vogais."); } }
19.194444
142
0.496382
0879dded47973e3ea5d6cd45ce085ca3537a0442
3,859
package grammarPack; import java.io.*; import java.util.*; /* * Asks the user for a text file that has the grammar specifications * it then asks the user for a symbol from the grammar they'd like to generate * e.g. a sentence, and how many of them they'd like * it then goes through and displays */ public class Main { public static void main(String[] args) throws FileNotFoundException { //introduction System.out.println("Welcome to our sentence generator!"); System.out.println(); // open grammar file System.out.print("What is the name of the grammar file? "); Scanner console = new Scanner(System.in); String fileName = console.nextLine(); List<String> lines; try { lines = readLines(fileName); } catch(Exception e) { System.out.println("Sorry that's not a valid file name"); return; } // construct grammar solver and begin user input loop Generator solver = new Generator(Collections.unmodifiableList(lines)); // repeatedly prompt for symbols to generate, and generate them String symbol = getSymbol(console, solver); while (symbol.length() > 0) { if (solver.contains(symbol)) { doGenerate(console, solver, symbol); } else { System.out.println("Illegal symbol."); } symbol = getSymbol(console, solver); } } /* * Displays all non-terminal symbols, * prompts for a symbol to generate, * and returns the symbol as a string. */ public static String getSymbol(Scanner console, Generator solver) { System.out.println(); System.out.println("Available symbols to generate are:"); Set<String> symbols = solver.getSymbols(); System.out.println(symbols); System.out.print("What do you want to generate (Enter to quit)? "); String target = console.nextLine().trim(); return target; } /* * Generates some number of instances of the given symbol. */ public static void doGenerate(Scanner console, Generator solver, String symbol) { System.out.print("How many do you want me to generate? "); if (console.hasNextInt()) { int number = console.nextInt(); if (number < 0) { System.out.println("No negatives allowed."); } else { System.out.println(); for (int i = 0; i < number; i++) { String result = solver.generate(symbol); System.out.println(result); } } } else { System.out.println("That is not a valid integer."); } console.nextLine(); // to position to next line } /* * Reads the text from the file with the given name and returns it all * as one big string. Strips empty lines and trims leading/trailing * whitespace from each line. Throws a FileNotFoundException if the * file with the given name is not found. */ public static List<String> readLines(String fileName) throws FileNotFoundException { List<String> lines = new ArrayList<String>(); Scanner input = new Scanner(new File("files/" + fileName)); while (input.hasNextLine()) { String line = input.nextLine().trim(); if (line.length() > 0) { lines.add(line); } } return lines; } }
29.458015
87
0.540036
6b7b0a6c3d31b4fe1dbd670ce396687ed3717adc
195
package com.itingchunyu.m.data; /** * @author liyanxi * @date 2018/8/10 * Copyright (c) 2018 www.itingchunyu.com. All rights reserved. */ public enum Status { SUCCESS, ERROR, LOADING }
16.25
63
0.682051
0de0ef8c4186422117f8a78297a255eae8134dc2
23,249
package org.aksw.simba.lsq.vocab; import org.apache.jena.rdf.model.Property; import org.apache.jena.rdf.model.Resource; import org.apache.jena.rdf.model.ResourceFactory; /** * LSQ vocabulary * * @author Claus Stadler * */ public class LSQ { public static final String NS = "http://lsq.aksw.org/vocab#"; public static class Terms { public static final String Query = NS + "Query"; public static final String text = NS + "text"; public static final String hash = NS + "hash"; public static final String resultCount = NS + "resultCount"; public static final String isDistinct = NS + "isDistinct"; // Error reporting duing benchmarking upon exceeding thresholds during counting and/or retrieval public static final String exceededMaxByteSizeForCounting = NS + "exceededMaxByteSizeForCounting"; public static final String exceededMaxResultCountForCounting = NS + "exceededMaxResultCountForCounting"; public static final String exceededMaxByteSizeForSerialization = NS + "exceededMaxByteSizeForSerialization"; public static final String exceededMaxResultCountForSerialization = NS + "exceededMaxResultCountForSerialization"; // public static final String exceededMaxCount = NS + "exceededMaxCount"; public static final String serializedResult = NS + "serializedResult"; // Vocab for benchmark configuration // Note: In a future LSQ version we could allow configuration of thresholds separately for // primary queries (the queries from the log) and secondary ones (those derived from bgp and tps) // (However, secondary queries may occurr also occur as primary ones, so more management would be needed) public static final String benchmarkSecondaryQueries = NS + "benchmarkSecondaryQueries"; public static final String maxCount = NS + "maxCount"; public static final String maxCountAffectsTp = NS + "maxCountAffectsTp"; public static final String maxResultCountForRetrieval = NS + "maxResultCountForRetrieval"; public static final String maxByteSizeForRetrieval = NS + "maxByteSizeForRetrieval"; public static final String maxResultCountForSerialization = NS + "maxResultCountForSerialization"; public static final String maxByteSizeForSerialization = NS + "maxByteSizeForSerialization"; public static final String retrievalDuration = NS + "retrievalDuration"; public static final String countingDuration = NS + "countingDuration"; public static final String evalDuration = NS + "evalDuration"; // public static final String distinctResultSize = ns + "distinctResultSize"; public static final String hasStructuralFeatures = NS + "hasStructuralFeatures"; public static final String hasSpin = NS + "hasSpin"; public static final String hasTp = NS + "hasTp"; public static final String hasTpInBgp = NS + "hasTpInBgp"; public static final String hasBgp = NS + "hasBgp"; public static final String hasSubBgp = NS + "hasSubBgp"; public static final String extensionQuery = NS + "extensionQuery"; // Link to the resource that corresponds to the query SELECT COUNT(DISTINCT joinVar) WHERE subBgp public static final String joinExtensionQuery = NS + "joinExtensionQuery"; //public static final String tpText = ns + "tpText"; //public static final String triplePatternResultSize = ns + "triplePatternResultSize"; public static final String headers = NS + "headers"; // Vocab for benchmark statistics (TODO group with the other error reporting (threshold exceeded) predicates above) public static final String execStatus = NS + "execStatus"; public static final String execError = NS + "execError"; public static final String processingError = NS + "processingError"; public static final String parseError = NS + "parseError"; public static final String runTimeMs = NS + "runTimeMs"; public static final String retrievalError = NS + "retrievalError"; public static final String countingError = NS + "countingError"; public static final String benchmarkRun = NS + "benchmarkRun"; public static final String hasExec = NS + "hasExec"; public static final String hasElementExec = NS + "hasElementExec"; public static final String hasLocalExec = NS + "hasLocalExec"; public static final String hasQueryExec = NS + "hasQueryExec"; public static final String hasRemoteExec = NS + "hasRemoteExec"; public static final String hasBgpExec = NS + "hasBgpExec"; public static final String hasTpExec = NS + "hasTpExec"; public static final String hasJoinVarExec = NS + "hasJoinVarExec"; public static final String hasTpInBgpExec = NS + "hasTpInBgpExec"; public static final String hasSubBgpExec = NS + "hasSubBgpExec"; public static final String usesFeature = "usesFeature"; public static final String feature = "feature"; public static final String count = NS + "count"; public static final String Vertex = NS + "Vertex"; public static final String Edge = NS + "Edge"; public static final String hasEdge = NS + "hasEdge"; public static final String in = NS + "in"; public static final String out = NS + "out"; // Indicates that a resource represents an RDF term or a variable // (we cannot have those in the subject position so we need a "proxy" resource) public static final String proxyFor = NS + "proxyFor"; // Join vertex type (used as an attribute, hence lower camel case spelling) public static final String star = NS + "star"; public static final String sink = NS + "sink"; public static final String path = NS + "path"; public static final String hybrid = NS + "hybrid"; public static final String joinVertex = NS + "joinVertex"; public static final String joinVertexType = NS + "joinVertexType"; public static final String joinVertexDegree = NS + "joinVertexDegree"; public static final String bgpCount = NS + "bgpCount"; public static final String tpCount = NS + "tpCount"; public static final String tpInBgpCountMin = NS + "tpInBgpCountMin"; public static final String tpInBgpCountMax = NS + "tpInBgpCountMax"; public static final String tpInBgpCountMean = NS + "tpInBgpCountMean"; public static final String tpInBgpCountMedian = NS + "tpInBgpCountMedian"; public static final String joinVertexCount = NS + "joinVertexCount"; public static final String projectVarCount = NS + "projectVarCount"; //public static final String avgJoinVerticesDegree = ns + "avgJoinVerticesDegree"; public static final String joinVertexDegreeMean = NS + "joinVertexDegreeMean"; public static final String joinVertexDegreeMedian = NS + "joinVertexDegreeMedian"; public static final String hasBgpNode = NS + "hasBgpNode"; public static final String mentionsSubject = NS + "mentionsSubject"; public static final String mentionsPredicate = NS + "mentionsPredicate"; public static final String mentionsObject = NS + "mentionsObject"; public static final String mentionsTuple = NS + "mentionsTuple"; public static final String sequenceId = NS + "sequenceId"; public static final String host = NS + "host"; public static final String hostHash = NS + "hostHash"; public static final String atTime = PROV.NS + "atTime"; public static final String endpoint = NS + "endpoint"; public static final String userAgent = NS + "userAgent"; public static final String config = NS + "config"; public static final String requestDelay = NS + "requestDelay"; public static final String connectionTimeoutForRetrieval = NS + "connectionTimeoutForRetrieval"; public static final String executionTimeoutForRetrieval = NS + "executionTimeoutForRetrieval"; public static final String connectionTimeoutForCounting = NS + "connectionTimeoutForCounting"; public static final String executionTimeoutForCounting = NS + "executionTimeoutForCounting"; // public static final String resultSetSizeThreshold = ns + "resultSetSizeThreshold"; public static final String datasetSize = NS + "datasetSize"; public static final String datasetLabel = NS + "datasetLabel"; public static final String datasetIri = NS + "datasetIri"; public static final String baseIri = NS + "baseIri"; public static final String tpToGraphRatio = NS + "tpToGraphRatio"; // Selectivity of a triple pattern in regard to the BGP in which it occurrs public static final String tpSelBGPRestricted = NS +"bgpRestrictedTpSel"; public static final String tpToBgpRatio = NS +"tpToBgpRatio"; // Selectivity of a triple pattern in regard to a variable that participates in a join with other TPs public static final String tpSelJoinVarRestricted = NS + "tpSelJoinVarRestricted"; } public static Resource resource(String local) { return ResourceFactory.createResource(NS + local); } public static Property property(String local) { return ResourceFactory.createProperty(NS + local); } public static final Property config = ResourceFactory.createProperty(Terms.config); // Used internally for the hypergraph representation - not part of the public vocab public static final Resource Vertex = ResourceFactory.createResource(Terms.Vertex); public static final Resource Edge = ResourceFactory.createResource(Terms.Edge); public static final Property in = ResourceFactory.createProperty(Terms.in); public static final Property out = ResourceFactory.createProperty(Terms.out); // Indicates that a resource represents an RDF term or a variable // (we cannot have those in the subject position so we need a "proxy" resource) public static final Property proxyFor = property("proxyFor"); public static final Resource star = ResourceFactory.createResource(Terms.star); public static final Resource sink = ResourceFactory.createResource(Terms.sink); public static final Resource path = ResourceFactory.createResource(Terms.path); public static final Resource hybrid = ResourceFactory.createResource(Terms.hybrid); public static final Property joinVertex = ResourceFactory.createProperty(Terms.joinVertex); public static final Property joinVertexType = ResourceFactory.createProperty(Terms.joinVertexType); public static final Property joinVertexDegree = ResourceFactory.createProperty(Terms.joinVertexDegree); public static final Property bgps = ResourceFactory.createProperty(Terms.bgpCount); public static final Property tps = ResourceFactory.createProperty(Terms.tpCount); public static final Property minBgpTriples = ResourceFactory.createProperty(Terms.tpInBgpCountMin); public static final Property maxBgpTriples = ResourceFactory.createProperty(Terms.tpInBgpCountMax); public static final Property joinVertices = ResourceFactory.createProperty(Terms.joinVertexCount); public static final Property projectVars = ResourceFactory.createProperty(Terms.projectVarCount); //public static final Property avgJoinVerticesDegree = property("avgJoinVerticesDegree"); public static final Property meanJoinVertexDegree = property("meanJoinVertexDegree"); public static final Property medianJoinVertexsDegree = property("medianJoinVertexDegree"); public static final Property mentionsSubject = property("mentionsSubject"); public static final Property mentionsPredicate = property("mentionsPredicate"); public static final Property mentionsObject = property("mentionsObject"); public static final Property mentionsTuple = property("mentionsTuple"); // stats = stats + getMentionsTuple(predicates); // subjects and objects // These attributes are part of SPIN - no need to duplicate them // public static final Resource Select = resource("Select"); // public static final Resource Construct = resource(""); // public static final Resource Ask = resource(""); // public static final Resource Describe = resource(org.topbraid.spin.vocabulary.SP)); // Type so that all triple pattern executions in a query can be retrieved //public static final Resource TPExec = resource("TPExec"); // An LSQ Query. It is different from SPIN::Query. // TODO Sort out the exact semantic relation - but its roughly: // A SPIN query represents a query itself, whereas a LSQ query represents a record about it // More concretely, an LSQ record holds information about at which time a certain query was fired based on which log file, etc. public static final Resource Query = ResourceFactory.createResource(Terms.Query); public static final Property text = ResourceFactory.createProperty(Terms.text); public static final Property resultCount = ResourceFactory.createProperty(Terms.resultCount); public static final Property hasStructuralFeatures = ResourceFactory.createProperty(Terms.hasStructuralFeatures); public static final Property hasSpin = ResourceFactory.createProperty(Terms.hasSpin); public static final Property hasTp = ResourceFactory.createProperty(Terms.hasTp); public static final Property hasBGP = ResourceFactory.createProperty(Terms.hasBgp); public static final Property hasBGPNode = ResourceFactory.createProperty(Terms.hasBgpNode); //public static final Property tpText = property("tpText"); //public static final Property triplePatternResultSize = property("triplePatternResultSize"); public static final Property execError = ResourceFactory.createProperty(Terms.execError); public static final Property processingError = ResourceFactory.createProperty(Terms.processingError); public static final Property parseError = ResourceFactory.createProperty(Terms.parseError); public static final Property runTimeMs = ResourceFactory.createProperty(Terms.runTimeMs); public static final Property benchmarkRun = ResourceFactory.createProperty(Terms.benchmarkRun); public static final Property hasExec = ResourceFactory.createProperty(Terms.hasExec); public static final Property hasLocalExec = ResourceFactory.createProperty(Terms.hasLocalExec); public static final Property hasRemoteExec = ResourceFactory.createProperty(Terms.hasRemoteExec); public static final Property hasBgpExec = ResourceFactory.createProperty(Terms.hasBgpExec); public static final Property hasTpExec = ResourceFactory.createProperty(Terms.hasTpExec); public static final Property hasJoinVarExec = ResourceFactory.createProperty(Terms.hasJoinVarExec); // Execution // Selectivity of a triple pattern in regard to the whole data set // TODO Rename to tpSelectivity(GraphRestricted) public static final Property tpSel = ResourceFactory.createProperty(Terms.tpToGraphRatio); // Selectivity of a triple pattern in regard to the BGP in which it occurrs public static final Property tpSelBGPRestricted = ResourceFactory.createProperty(Terms.tpSelBGPRestricted); // Selectivity of a triple pattern in regard to a variable that participates in a join with other TPs public static final Property tpSelJoinVarRestricted = ResourceFactory.createProperty(Terms.tpSelJoinVarRestricted); // Similar to tpSelectivity, but considering immediate filters present on it // (maybe only those filters for which indexes can be used) //public static final Property fTpSelectivityBgpRestricted = property("fTpSelectivityBgpRestricted"); public static final Property meanTPSelectivity = property("meanTPSelectivity"); // TODO This is PROV vocab //public static final Property wasAssociatedWith = property("wasAssociatedWith"); public static final Property usesFeature = property(Terms.usesFeature); public static final Property triplePath = property("triplePath"); // TODO Not sure if the following metadata really belongs here ~ Claus // TODO This is covered by the MEX ontology public static final Property engine = property("engine"); public static final Property vendor = property("vendor"); public static final Property version = property("version"); public static final Property processor = property("processor"); public static final Property ram = property("ram"); public static final Property dataset = property("dataset"); public static final Property endpoint = ResourceFactory.createProperty(Terms.endpoint); public static final Property userAgent = ResourceFactory.createProperty(Terms.userAgent); // TODO This is actually the vocab for apache log parsing - move it elsewhere public static final Resource WebAccessLogFormat = resource("WebAccessLogFormat"); public static final Resource CsvLogFormat = resource("CsvLogFormat"); public static final Property pattern = property("pattern"); public static final Property sequenceId = ResourceFactory.createProperty(Terms.sequenceId); /** * logRecord: String representation of the original log entry - usually a line */ public static final Property logRecord = property("logRecord"); public static final Property host = ResourceFactory.createProperty(Terms.host); public static final Property hostHash = ResourceFactory.createProperty(Terms.hostHash); //public static final Property timestamp = ResourceFactory.createProperty(Strs.timestamp); public static final Property user = property("user"); public static final Property request = property("request"); public static final Property query = property("query"); public static final Property requestPath = property("uri"); public static final Property queryString = property("queryString"); public static final Property protocol = property("protocol"); public static final Property headers = property(Terms.headers); public static final Property verb = property("verb"); public static final Property parsed = property("parsed"); // Whether a log entry could be parsed public static final Property statusCode = property("statusCode"); public static final Property execStatus = ResourceFactory.createProperty(Terms.execStatus); public static final Property numResponseBytes = property("numResponseBytes"); // Query / Graph Pattern Features // None indicates the absence of features; must not appear with any other features public static final Resource None = resource("None"); // TODO These terms can be found in SP instead of SPIN public static final Resource Select = resource("Select"); public static final Resource Construct = resource("Construct"); public static final Resource Describe = resource("Describe"); public static final Resource Ask = resource("Ask"); public static final Resource Unknown = resource("Unknown"); public static final Resource TriplePattern = resource("TriplePattern"); public static final Resource TriplePath = resource("TriplePath"); public static final Resource Triple = resource("Triples"); public static final Resource Group = resource("Group"); public static final Resource Assign = resource("Assign"); public static final Resource Dataset = resource("Dataset"); public static final Resource SubQuery = resource("SubQuery"); public static final Resource Filter = resource("Filter"); public static final Resource Values = resource("Values"); public static final Resource Bind = resource("Bind"); public static final Resource Service = resource("Service"); public static final Resource Exists = resource("Exists"); public static final Resource NotExists = resource("NotExists"); public static final Resource Minus = resource("Minus"); public static final Resource NamedGraph = resource("NamedGraph"); public static final Resource Union = resource("Union"); public static final Resource Optional = resource("Optional"); public static final Resource Reduced = resource("Reduced"); public static final Resource Find = resource("Find"); public static final Resource Distinct = resource("Distinct"); public static final Resource OrderBy = resource("OrderBy"); public static final Resource GroupBy = resource("GroupBy"); public static final Resource Aggregators = resource("Aggregators"); public static final Resource Functions = resource("Functions"); public static final Resource Offset = resource("Offset"); public static final Resource Limit = resource("Limit"); // Path Features public static final Resource LinkPath = resource("LinkPath"); public static final Resource ReverseLinkPath = resource("ReverseLinkPath"); public static final Resource NegPropSetPath = resource("NegPropSetPath"); public static final Resource InversePath = resource("InversePath"); public static final Resource ModPath = resource("ModPath"); public static final Resource FixedLengthPath = resource("FixedLengthPath"); public static final Resource DistinctPath = resource("DistinctPath"); public static final Resource MultiPath = resource("MultiPath"); public static final Resource ShortestPath = resource("ShortestPath"); public static final Resource ZeroOrOnePath = resource("ZeroOrOnePath"); // NOTE: We do not reflect syntactic differences of path expressions such as // fooPath{1,} and fooPath+ in the vocab public static final Resource ZeroOrMore1Path = resource("ZeroOrMorePath"); public static final Resource ZeroOrMoreNPath = resource("ZeroOrMorePath"); public static final Resource OneOrMore1Path = resource("oneOrMorePath"); public static final Resource OneOrMoreNPath = resource("oneOrMorePath"); public static final Resource AltPath = resource("AltPath"); public static final Resource SeqPath = resource("SeqPath"); public static final Property usesService = property("usesService"); public static final String defaultLsqrNs = "http://lsq.aksw.org/res/"; public static final Property hasVar = property("hasVar"); public static final Property hasVarExec = property("hasVarExec"); // Temporary id attributes - used to craft final IRIs public static final Property queryId = property("queryId"); public static final Property bgpId = property("bgpId"); public static final Property bgpVarId = property("bgpVarId"); public static final Property tpId = property("tpId"); public static final Property tpVarId = property("tpVarId"); //public static final Property //lsqv:resultSize //lsqv:runTimeMs //lsqv:hasLocalExecution //lsqv:structuralFeatures //lsqv:runtimeError //lsqv:resultSize //lsqv:meanTriplePatternSelectivity //lsqv:joinVertexDegree 2 ; lsqv:joinVertexType lsqv:Star //lsqv:hasRemoteExecution //lsqv:endpoint --> maybe supersede by dataset distribution vocab (i think dcat has something) // }
51.895089
131
0.738957
0f871e5022dacdbc7033d04cde3f0b07d1ea720f
2,517
// Generated by the protocol buffer compiler. DO NOT EDIT! // source: com/api/igdb/igdbproto.proto package proto; public interface MultiplayerModeOrBuilder extends // @@protoc_insertion_point(interface_extends:proto.MultiplayerMode) com.google.protobuf.MessageOrBuilder { /** * <code>uint64 id = 1;</code> * @return The id. */ long getId(); /** * <code>bool campaigncoop = 2;</code> * @return The campaigncoop. */ boolean getCampaigncoop(); /** * <code>bool dropin = 3;</code> * @return The dropin. */ boolean getDropin(); /** * <code>.proto.Game game = 4;</code> * @return Whether the game field is set. */ boolean hasGame(); /** * <code>.proto.Game game = 4;</code> * @return The game. */ proto.Game getGame(); /** * <code>.proto.Game game = 4;</code> */ proto.GameOrBuilder getGameOrBuilder(); /** * <code>bool lancoop = 5;</code> * @return The lancoop. */ boolean getLancoop(); /** * <code>bool offlinecoop = 6;</code> * @return The offlinecoop. */ boolean getOfflinecoop(); /** * <code>int32 offlinecoopmax = 7;</code> * @return The offlinecoopmax. */ int getOfflinecoopmax(); /** * <code>int32 offlinemax = 8;</code> * @return The offlinemax. */ int getOfflinemax(); /** * <code>bool onlinecoop = 9;</code> * @return The onlinecoop. */ boolean getOnlinecoop(); /** * <code>int32 onlinecoopmax = 10;</code> * @return The onlinecoopmax. */ int getOnlinecoopmax(); /** * <code>int32 onlinemax = 11;</code> * @return The onlinemax. */ int getOnlinemax(); /** * <code>.proto.Platform platform = 12;</code> * @return Whether the platform field is set. */ boolean hasPlatform(); /** * <code>.proto.Platform platform = 12;</code> * @return The platform. */ proto.Platform getPlatform(); /** * <code>.proto.Platform platform = 12;</code> */ proto.PlatformOrBuilder getPlatformOrBuilder(); /** * <code>bool splitscreen = 13;</code> * @return The splitscreen. */ boolean getSplitscreen(); /** * <code>bool splitscreenonline = 14;</code> * @return The splitscreenonline. */ boolean getSplitscreenonline(); /** * <code>string checksum = 15;</code> * @return The checksum. */ java.lang.String getChecksum(); /** * <code>string checksum = 15;</code> * @return The bytes for checksum. */ com.google.protobuf.ByteString getChecksumBytes(); }
20.298387
72
0.60588
b044089459673cc0cd1b407d127e100a1d6981b6
19,720
/* * 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.sis.parameter; import java.util.Collections; import java.util.Map; import javax.measure.unit.SI; import javax.measure.unit.Unit; import org.opengis.parameter.ParameterValue; import org.opengis.parameter.ParameterDescriptor; import org.opengis.parameter.ParameterNotFoundException; import org.apache.sis.referencing.NamedIdentifier; import org.apache.sis.internal.referencing.Formulas; import org.apache.sis.internal.util.Constants; import org.apache.sis.measure.MeasurementRange; import org.apache.sis.util.resources.Errors; import org.apache.sis.util.ArraysExt; import static org.opengis.referencing.IdentifiedObject.NAME_KEY; import static org.apache.sis.metadata.iso.citation.Citations.NETCDF; // Branch-specific imports import org.apache.sis.internal.jdk7.Objects; /** * Map projection parameters, with special processing for alternative ways to express the ellipsoid axis length * and the standard parallels. See {@link MapProjectionDescriptor} for more information about those non-standard * parameters. * * @author Martin Desruisseaux (Geomatys) * @since 0.6 * @version 0.6 * @module */ final class MapProjectionParameters extends DefaultParameterValueGroup { /** * For cross-version compatibility. */ private static final long serialVersionUID = -6801091012335717139L; /** * The {@link EarthRadius} parameter instance, created when first needed. * This is an "invisible" parameter, never shown in the {@link #values()} list. */ private transient ParameterValue<Double> earthRadius; /** * The {@link InverseFlattening} parameter instance, created when first needed. * This is an "invisible" parameter, never shown in the {@link #values()} list. */ private transient InverseFlattening inverseFlattening; /** * The {@link StandardParallel} parameter instance, created when first needed. * This is an "invisible" parameter, never shown in the {@link #values()} list. */ private transient ParameterValue<double[]> standardParallel; /** * The {@link IsIvfDefinitive} parameter instance, created when first needed. * This is an "invisible" parameter, never shown in the {@link #values()} list. */ private transient ParameterValue<Boolean> isIvfDefinitive; /** * Creates a new parameter value group. An instance of {@link MapProjectionDescriptor} * is mandatory, because some method in this class will need to cast the descriptor. */ MapProjectionParameters(final MapProjectionDescriptor descriptor) { super(descriptor); } /** * Returns {@code true} since the {@link #parameterIfExist(String)} method below is compatible with * {@link #parameter(String)}. Note that we would need to revisit this condition if this class was * no longer final. */ @Override boolean isKnownImplementation() { return true; } /** * Returns the value in this group for the specified name. If the given name is one of the * "invisible" parameters, returns a dynamic parameter view without adding it to the list * of real parameter values. * * @param name The case insensitive name of the parameter to search for. * @return The parameter value for the given name. * @throws ParameterNotFoundException if there is no parameter value for the given name. */ @Override ParameterValue<?> parameterIfExist(final String name) throws ParameterNotFoundException { if (MapProjectionDescriptor.isHeuristicMatchForName(name, Constants.EARTH_RADIUS)) { if (earthRadius == null) { earthRadius = new EarthRadius(parameter(Constants.SEMI_MAJOR), parameter(Constants.SEMI_MINOR)); } return earthRadius; } if (MapProjectionDescriptor.isHeuristicMatchForName(name, Constants.INVERSE_FLATTENING)) { return getInverseFlattening(); } if (MapProjectionDescriptor.isHeuristicMatchForName(name, Constants.IS_IVF_DEFINITIVE)) { if (isIvfDefinitive == null) { isIvfDefinitive = new IsIvfDefinitive(getInverseFlattening()); } return isIvfDefinitive; } if (((MapProjectionDescriptor) getDescriptor()).hasStandardParallels) { if (MapProjectionDescriptor.isHeuristicMatchForName(name, Constants.STANDARD_PARALLEL)) { if (standardParallel == null) { standardParallel = new StandardParallel(parameter(Constants.STANDARD_PARALLEL_1), parameter(Constants.STANDARD_PARALLEL_2)); } return standardParallel; } } return super.parameterIfExist(name); } /** * Returns the {@link InverseFlattening} instance, creating it when first needed. * This parameter is used also by {@link IsIvfDefinitive}. */ private InverseFlattening getInverseFlattening() { if (inverseFlattening == null) { inverseFlattening = new InverseFlattening(parameter(Constants.SEMI_MAJOR), parameter(Constants.SEMI_MINOR)); } return inverseFlattening; } /** * The earth radius parameter. This parameter is computed automatically from the {@code "semi_major"} * and {@code "semi_minor"} parameters. When explicitely set, this parameter value is also assigned * to the {@code "semi_major"} and {@code "semi_minor"} axis lengths. * * @see org.apache.sis.referencing.datum.DefaultEllipsoid#getAuthalicRadius() */ static final class EarthRadius extends DefaultParameterValue<Double> { /** * For cross-version compatibility. Actually instances of this class * are not expected to be serialized, but we try to be a bit safer here. */ private static final long serialVersionUID = 5848432458976184182L; /** * All names known to Apache SIS for the Earth radius parameter. * This is used in some NetCDF files instead of {@code SEMI_MAJOR} and {@code SEMI_MINOR}. * This is not a standard parameter. */ static final ParameterDescriptor<Double> DESCRIPTOR = new DefaultParameterDescriptor<Double>( InverseFlattening.toMap(Constants.EARTH_RADIUS), 0, 1, Double.class, MeasurementRange.createGreaterThan(0.0, SI.METRE), null, null); /** * The parameters for the semi-major and semi-minor axis length. */ private final ParameterValue<?> semiMajor, semiMinor; /** * Creates a new parameter. */ EarthRadius(final ParameterValue<?> semiMajor, final ParameterValue<?> semiMinor) { super(DESCRIPTOR); this.semiMajor = semiMajor; this.semiMinor = semiMinor; } /** * Invoked when a new parameter value is set. This method sets both axis length to the given radius. */ @Override protected void setValue(final Object value, final Unit<?> unit) { super.setValue(value, unit); // Perform argument check. final double r = (Double) value; // At this point, can not be anything else than Double. semiMajor.setValue(r, unit); semiMinor.setValue(r, unit); } /** * Invoked when the parameter value is requested. Unconditionally computes the authalic radius. * If an Earth radius has been explicitely specified, the result will be the same unless the user * overwrote it with explicit semi-major or semi-minor axis length. */ @Override public double doubleValue() { double r = semiMajor.doubleValue(); if (semiMinor.getValue() != null) { // Compute in unit of the semi-major axis. r = Formulas.getAuthalicRadius(r, semiMinor.doubleValue(semiMajor.getUnit())); } return r; } /** * Unconditionally returns the unit of the semi-major axis, which is the unit * in which {@link #doubleValue()} performs its computation. */ @Override public Unit<?> getUnit() { return semiMajor.getUnit(); } /** * Getters other than the above {@code doubleValue()} delegate to this method. */ @Override public Double getValue() { return doubleValue(); } } /** * The inverse flattening parameter. This parameter is computed automatically from the {@code "semi_major"} * and {@code "semi_minor"} parameters. When explicitly set, this parameter value is used for computing the * semi-minor axis length. * * @see org.apache.sis.referencing.datum.DefaultEllipsoid#getInverseFlattening() */ static final class InverseFlattening extends DefaultParameterValue<Double> { /** * For cross-version compatibility. Actually instances of this class * are not expected to be serialized, but we try to be a bit safer here. */ private static final long serialVersionUID = 4490056024453509851L; /** * All names known to Apache SIS for the inverse flattening parameter. * This is used in some NetCDF files instead of {@code SEMI_MINOR}. * This is not a standard parameter. */ static final ParameterDescriptor<Double> DESCRIPTOR = new DefaultParameterDescriptor<Double>( toMap(Constants.INVERSE_FLATTENING), 0, 1, Double.class, MeasurementRange.createGreaterThan(0.0, Unit.ONE), null, null); /** * Helper method for {@link #DESCRIPTOR} constructions. */ static Map<String,?> toMap(final String name) { return Collections.singletonMap(NAME_KEY, new NamedIdentifier(NETCDF, name)); } /** * The parameters for the semi-major and semi-minor axis length. */ private final ParameterValue<?> semiMajor, semiMinor; /** * The declared inverse flattening values, together with a snapshot of axis lengths * at the time the inverse flattening has been set. */ private double inverseFlattening, a, b; /** * Creates a new parameter. */ InverseFlattening(final ParameterValue<?> semiMajor, final ParameterValue<?> semiMinor) { super(DESCRIPTOR); this.semiMajor = semiMajor; this.semiMinor = semiMinor; invalidate(); } /** * Declares that the inverse flattening factor is not definitive. * We use the fact that the {@code ==} operator gives {@code false} if a value is NaN. */ void invalidate() { a = b = Double.NaN; } /** * Returns {@code true} if the inverse flattening factor has been explicitely specified * and seems to still valid. */ boolean isIvfDefinitive() { if (inverseFlattening > 0) { final Number ca = (Number) semiMajor.getValue(); if (ca != null && ca.doubleValue() == a) { final Number cb = (Number) semiMinor.getValue(); if (cb != null && cb.doubleValue() == b) { return Objects.equals(semiMajor.getUnit(), semiMinor.getUnit()); } } } return false; } /** * Invoked when a new parameter value is set. * This method computes the semi-minor axis length from the given value. */ @Override protected void setValue(final Object value, final Unit<?> unit) { super.setValue(value, unit); // Perform argument check. final double ivf = (Double) value; // At this point, can not be anything else than Double. final Number ca = (Number) semiMajor.getValue(); if (ca != null) { a = ca.doubleValue(); b = Formulas.getSemiMinor(a, ivf); semiMinor.setValue(b, semiMajor.getUnit()); } else { invalidate(); } inverseFlattening = ivf; } /** * Invoked when the parameter value is requested. Computes the inverse flattening factor * from the axis lengths if the currently stored value does not seem to be valid anymore. */ @Override public double doubleValue() { final double ca = semiMajor.doubleValue(); final double cb = semiMinor.doubleValue(semiMajor.getUnit()); if (ca == a && cb == b && inverseFlattening > 0) { return inverseFlattening; } return Formulas.getInverseFlattening(ca, cb); } /** * Getters other than the above {@code doubleValue()} delegate to this method. */ @Override public Double getValue() { return doubleValue(); } } /** * Whether the inverse flattening parameter is definitive. * * @see org.apache.sis.referencing.datum.DefaultEllipsoid#isIvfDefinitive() */ static final class IsIvfDefinitive extends DefaultParameterValue<Boolean> { /** * For cross-version compatibility. Actually instances of this class * are not expected to be serialized, but we try to be a bit safer here. */ private static final long serialVersionUID = 5988883252321358629L; /** * All names known to Apache SIS for the "is IVF definitive" parameter. * This is not a standard parameter. */ static final ParameterDescriptor<Boolean> DESCRIPTOR = new DefaultParameterDescriptor<Boolean>( InverseFlattening.toMap(Constants.IS_IVF_DEFINITIVE), 0, 1, Boolean.class, null, null, Boolean.FALSE); /** * The parameters for the inverse flattening factor. */ private final InverseFlattening inverseFlattening; /** * Creates a new parameter. */ IsIvfDefinitive(final InverseFlattening inverseFlattening) { super(DESCRIPTOR); this.inverseFlattening = inverseFlattening; } /** * Invoked when a new parameter value is set. */ @Override protected void setValue(final Object value, final Unit<?> unit) { super.setValue(value, unit); // Perform argument check. if (!(Boolean) value) { inverseFlattening.invalidate(); } } /** * Invoked when the parameter value is requested. */ @Override public boolean booleanValue() { return inverseFlattening.isIvfDefinitive(); } /** * Getters other than the above {@code booleanValue()} delegate to this method. */ @Override public Boolean getValue() { return booleanValue(); } } /** * The standard parallels parameter as an array of {@code double}. This parameter is computed automatically * from the {@code "standard_parallel_1"} and {@code "standard_parallel_1"} standard parameters. When this * non-standard parameter is explicitely set, the array elements are given to the above-cited standard parameters. */ static final class StandardParallel extends DefaultParameterValue<double[]> { /** * For cross-version compatibility. Actually instances of this class * are not expected to be serialized, but we try to be a bit safer here. */ private static final long serialVersionUID = -1379566730374843040L; /** * All names known to Apache SIS for the standard parallels parameter, as an array of 1 or 2 elements. * This is used in some NetCDF files instead of {@link #STANDARD_PARALLEL_1} and * {@link #STANDARD_PARALLEL_2}. This is not a standard parameter. */ static final ParameterDescriptor<double[]> DESCRIPTOR = new DefaultParameterDescriptor<double[]>( InverseFlattening.toMap(Constants.STANDARD_PARALLEL), 0, 1, double[].class, null, null, null); /** * The parameters for the standard parallels. */ private final ParameterValue<?> standardParallel1, standardParallel2; /** * Creates a new parameter. */ StandardParallel(final ParameterValue<?> standardParallel1, final ParameterValue<?> standardParallel2) { super(DESCRIPTOR); this.standardParallel1 = standardParallel1; this.standardParallel2 = standardParallel2; } /** * Invoked when a new parameter value is set. This method assign the array elements * to {@code "standard_parallel_1"} and {@code "standard_parallel_1"} parameters. */ @Override @SuppressWarnings("fallthrough") protected void setValue(final Object value, final Unit<?> unit) { super.setValue(value, unit); // Perform argument check. double p1 = Double.NaN; double p2 = Double.NaN; if (value != null) { final double[] values = (double[]) value; switch (values.length) { default: { throw new IllegalArgumentException(Errors.format( Errors.Keys.UnexpectedArrayLength_2, 2, values.length)); } case 2: p2 = values[1]; // Fallthrough case 1: p1 = values[0]; // Fallthrough case 0: break; } } standardParallel1.setValue(p1, unit); standardParallel2.setValue(p2, unit); } /** * Invoked when the parameter value is requested. Unconditionally computes the array * from the {@code "standard_parallel_1"} and {@code "standard_parallel_1"} parameters. */ @Override public double[] getValue() { final Number p1 = (Number) standardParallel1.getValue(); final Number p2 = (Number) standardParallel2.getValue(); if (p2 == null) { if (p1 == null) { return ArraysExt.EMPTY_DOUBLE; } return new double[] {p1.doubleValue()}; } return new double[] {(p1 != null) ? p1.doubleValue() : Double.NaN, p2.doubleValue()}; } } }
39.519038
118
0.616329
d4602c313a4378f70811179baff73bb3ae71494f
2,315
/** * */ package com.my.model; /** * @author SU360282 * */ public class SubExpression implements Comparable<SubExpression> { private int priority; private String expression; private int operandPosition; private char operand; private int startIndx; private int endIndx; private long firstVal; public long getFirstVal() { return firstVal; } public void setFirstVal(long firstVal) { this.firstVal = firstVal; } public long getSecondVal() { return secondVal; } public void setSecondVal(long secondVal) { this.secondVal = secondVal; } private long secondVal; public int getStartIndx() { return startIndx; } public void setStartIndx(int startIndx) { this.startIndx = startIndx; } public int getEndIndx() { return endIndx; } public void setEndIndx(int endIndx) { this.endIndx = endIndx; } public char getOperand() { return operand; } public void setOperand(char operand) { this.operand = operand; } public int getOperandPosition() { return operandPosition; } public void setOperandPosition(int operandPosition) { this.operandPosition = operandPosition; } private long total; public int getPriority() { return priority; } public void setPriority(int priority) { this.priority = priority; } public String getExpression() { return expression; } public void setExpression(String expression) { this.expression = expression; } public long getTotal() { return total; } public void setTotal(long total) { this.total = total; } @Override public int compareTo(SubExpression subExpr) { return subExpr.priority-this.priority; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + priority+startIndx+endIndx; return result; } @Override public boolean equals(Object obj) { if (this == obj) { return true; } if (obj == null) { return false; } if (getClass() != obj.getClass()) { return false; } SubExpression other = (SubExpression) obj; if (startIndx!=other.startIndx || endIndx!=other.endIndx) { return false; } if (priority != other.priority) { return false; } return true; } @Override public String toString() { return String.format("%d: %d", startIndx, priority); } }
19.291667
65
0.679914
c02fbc615fa172023dc4baa604f3e1d4cef09650
3,685
// Copyright © Microsoft Open Technologies, 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 // // THIS CODE IS PROVIDED *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS // OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION // ANY IMPLIED WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A // PARTICULAR PURPOSE, MERCHANTABILITY OR NON-INFRINGEMENT. // // See the Apache License, Version 2.0 for the specific language // governing permissions and limitations under the License. package com.microsoft.aad.adal; import java.net.URL; import java.util.HashMap; import java.util.UUID; import android.os.Build; import com.microsoft.aad.adal.AuthenticationConstants.AAD; /** * It uses one time async task. WebRequest are wrapped here to prevent multiple * reuses for same tasks. Each request returns a handler for cancel action. Call * this from UI thread to correctly create async task and execute. */ public class WebRequestHandler implements IWebRequestHandler { private static final String TAG = "WebRequestHandler"; /** * Header for accept. */ public static final String HEADER_ACCEPT = "Accept"; /** * Header for json type. */ public static final String HEADER_ACCEPT_JSON = "application/json"; private UUID mRequestCorrelationId = null; /** * Creates http request. */ public WebRequestHandler() { } @Override public HttpWebResponse sendGet(URL url, HashMap<String, String> headers) { Logger.d(TAG, "WebRequestHandler thread" + android.os.Process.myTid()); HttpWebRequest request = new HttpWebRequest(url); request.setRequestMethod(HttpWebRequest.REQUEST_METHOD_GET); headers = updateHeaders(headers); addHeadersToRequest(headers, request); return request.send(); } @Override public HttpWebResponse sendPost(URL url, HashMap<String, String> headers, byte[] content, String contentType) { Logger.d(TAG, "WebRequestHandler thread" + android.os.Process.myTid()); HttpWebRequest request = new HttpWebRequest(url); request.setRequestMethod(HttpWebRequest.REQUEST_METHOD_POST); request.setRequestContentType(contentType); request.setRequestContent(content); headers = updateHeaders(headers); addHeadersToRequest(headers, request); return request.send(); } private void addHeadersToRequest(HashMap<String, String> headers, HttpWebRequest request) { if (headers != null && !headers.isEmpty()) { request.getRequestHeaders().putAll(headers); } } private HashMap<String, String> updateHeaders(HashMap<String, String> headers) { if (headers == null) { headers = new HashMap<String, String>(); } if (mRequestCorrelationId != null) { headers.put(AAD.CLIENT_REQUEST_ID, mRequestCorrelationId.toString()); } headers.put(AAD.ADAL_ID_PLATFORM, "Android"); headers.put(AAD.ADAL_ID_VERSION, AuthenticationContext.getVersionName()); headers.put(AAD.ADAL_ID_OS_VER, "" + Build.VERSION.SDK_INT); headers.put(AAD.ADAL_ID_DM, android.os.Build.MODEL); return headers; } /** * Sets correlationId. * * @param requestCorrelationId {@link UUID} */ public void setRequestCorrelationId(UUID requestCorrelationId) { this.mRequestCorrelationId = requestCorrelationId; } }
32.043478
95
0.689824
c41242412c5a6226c3d3e91c2ee26a46ec23470b
1,456
package com.spreetail.dictionary; public class Dictionary { private MultiValueMap<String, String> multiValueMap = new MultiValueMap<>(); public void addEntry(String key, String value) { if (multiValueMap.put(key, value)) { ConsoleUtilities.printToConsole("Added"); } else { ConsoleUtilities.printToConsole("ERROR, value already exists"); } } public void removeValueFromKey(String key, String value) { if (!isKeyPresent(key)) { ConsoleUtilities.printToConsole("ERROR, key does not exist."); return; } if (!isKeyValuePresent(key, value)) { ConsoleUtilities.printToConsole("ERROR, value does not exist."); return; } if (multiValueMap.remove(key, value)) { ConsoleUtilities.printToConsole("Removed"); if (multiValueMap.get(key).isEmpty()) { multiValueMap.remove(key); } } } public void removeKey(String key) { if (!isKeyPresent(key)) { ConsoleUtilities.printToConsole("ERROR, key does not exist"); return; } if (multiValueMap.remove(key)) { ConsoleUtilities.printToConsole("Removed"); } } public void clear() { if (multiValueMap.clear()) { ConsoleUtilities.printToConsole("Cleared"); } } public boolean isKeyPresent(String key) { return multiValueMap.contains(key); } public MultiValueMap<String, String> getDictionary() { return multiValueMap; } public boolean isKeyValuePresent(String key, String value) { return multiValueMap.contains(key, value); } }
23.868852
77
0.710852
9970163265e89e5070ff411c75805ae614f47b91
177
package my.com.codeplay.training.network_demo.model; public class Weather { public int id; public String main; public String description; public String icon; }
19.666667
52
0.728814
a88ccb23540005cc34d3fb78f0e7500e8357c2d8
219
public class SassoCartaForbiceMain { public static void main(String[] args) { Giocatore g = new Giocatore(); Giocatore CPU = new Giocatore(); Partita p = new Partita(); while (true) p.Start(g, CPU); } }
16.846154
41
0.6621
bd0e42a5c3e0cdbc650260ec685bbf933dd3c691
1,611
package MediaVetorThread; import java.util.logging.Level; import java.util.logging.Logger; //Cria-se um classe e implementa os metodos public class MediaVetor { private int soma ; private int media ; // metodo synchronized serve para que apenas uma Thread cesa esse metódo por vez public synchronized int somaArray(int[] array) { soma = 0; media = 0; for (int i = 0; i < array.length; i++) { soma += array[i]; System.out.println("Executando a soma " + Thread.currentThread().getName() + " somando o valor " + array[i] + " com total de " + soma); try { // a Thread dorme por meio milesegundo para executar o for novamente Thread.sleep(500); } catch (InterruptedException ex) { Logger.getLogger(MediaVetor.class.getName()).log(Level.SEVERE, null, ex); } } //media+=array.length; //System.out.println("A media do vetor é " + media); return soma; //return media; } public synchronized int mediaArray(int[] array) { soma = 0; media = 0; for (int i = 0; i < array.length; i++) { soma += array[i]; } media= soma/array.length; try { Thread.sleep(100); } catch (InterruptedException ex) { Logger.getLogger(MediaVetor.class.getName()).log(Level.SEVERE, null, ex); } return media; //return media; } }
29.833333
90
0.52576
7646b782b5a10f41680ca5b679cbb08ac7a6e69a
5,145
package com.sunyard.unionpay; import com.sunyard.sdk.AcpService; import com.sunyard.sdk.LogUtil; import com.sunyard.sdk.SDKConfig; import javax.servlet.ServletConfig; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; import java.util.HashMap; import java.util.List; import java.util.Map; /** * 重要:联调测试时请仔细阅读注释! * * 产品:代付产品<br> * 交易:文件传输类接口:后台获取对账文件交易,只有同步应答 <br> * 日期: 2015-09<br> * 版本: 1.0.0 * 版权: 中国银联<br> * 声明:以下代码只是为了方便商户测试而提供的样例代码,商户可以根据自己需要,按照技术文档编写。该代码仅供参考,不提供编码,性能,规范性等方面的保障<br> * 该接口参考文档位置:open.unionpay.com帮助中心 下载 产品接口规范 《代付产品接口规范》<br> * 《平台接入接口规范-第5部分-附录》(内包含应答码接口规范)<br> * 《全渠道平台接入接口规范 第3部分 文件接口》(对账文件格式说明)<br> * 测试过程中的如果遇到疑问或问题您可以:1)优先在open平台中查找答案: * 调试过程中的问题或其他问题请在 https://open.unionpay.com/ajweb/help/faq/list 帮助中心 FAQ 搜索解决方案 * 测试过程中产生的7位应答码问题疑问请在https://open.unionpay.com/ajweb/help/respCode/respCodeList 输入应答码搜索解决方案 * 2) 咨询在线人工支持: open.unionpay.com注册一个用户并登陆在右上角点击“在线客服”,咨询人工QQ测试支持。 * 交易说明: 对账文件的格式请参考《全渠道平台接入接口规范 第3部分 文件接口》 * 对账文件示例见目录file下的802310048993424_20150905.zip * 解析落地后的对账文件可以参考BaseDemo.java中的parseZMFile();parseZMEFile();方法 * */ public class Form10_7_FileTransfer extends HttpServlet { @Override public void init(ServletConfig config) throws ServletException { /** * 请求银联接入地址,获取证书文件,证书路径等相关参数初始化到SDKConfig类中 * 在java main 方式运行时必须每次都执行加载 * 如果是在web应用开发里,这个方法可使用监听的方式写入缓存,无须在这出现 */ //这里已经将加载属性文件的方法挪到了web/AutoLoadServlet.java中 //SDKConfig.getConfig().loadPropertiesFromSrc(); //从classpath加载acp_sdk.properties文件 super.init(); } @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { String merId = req.getParameter("merId"); String settleDate = req.getParameter("settleDate"); Map<String, String> data = new HashMap<String, String>(); /***银联全渠道系统,产品参数,除了encoding自行选择外其他不需修改***/ data.put("version", DemoBase.version); //版本号 全渠道默认值 data.put("encoding", DemoBase.encoding); //字符集编码 可以使用UTF-8,GBK两种方式 data.put("signMethod", SDKConfig.getConfig().getSignMethod()); //签名方法 data.put("txnType", "76"); //交易类型 76-对账文件下载 data.put("txnSubType", "01"); //交易子类型 01-对账文件下载 data.put("bizType", "000000"); //业务类型,固定 /***商户接入参数***/ data.put("accessType", "0"); //接入类型,商户接入填0,不需修改 data.put("merId", merId); //商户代码,请替换正式商户号测试,如使用的是自助化平台注册的777开头的商户号,该商户号没有权限测文件下载接口的,请使用测试参数里写的文件下载的商户号和日期测。如需777商户号的真实交易的对账文件,请使用自助化平台下载文件。 data.put("settleDate", settleDate); //清算日期,如果使用正式商户号测试则要修改成自己想要获取对账文件的日期, 测试环境如果使用700000000000001商户号则固定填写0119 data.put("txnTime",DemoBase.getCurrentTime()); //订单发送时间,取系统时间,格式为YYYYMMDDhhmmss,必须取当前时间,否则会报txnTime无效 data.put("fileType", "00"); //文件类型,一般商户填写00即可 /**请求参数设置完毕,以下对请求参数进行签名并发送http post请求,接收同步应答报文------------->**/ Map<String, String> reqData = AcpService.sign(data,DemoBase.encoding);//报文中certId,signature的值是在signData方法中获取并自动赋值的,只要证书配置正确即可。 String url = SDKConfig.getConfig().getFileTransUrl();//获取请求银联的前台地址:对应属性文件acp_sdk.properties文件中的acpsdk.fileTransUrl Map<String, String> rspData = AcpService.post(reqData,url,DemoBase.encoding); /**对应答码的处理,请根据您的业务逻辑来编写程序,以下应答码处理逻辑仅供参考------------->**/ //应答码规范参考open.unionpay.com帮助中心 下载 产品接口规范 《平台接入接口规范-第5部分-附录》 String fileContentDispaly = ""; if(!rspData.isEmpty()){ if(AcpService.validate(rspData, DemoBase.encoding)){ LogUtil.writeLog("验证签名成功"); String respCode = rspData.get("respCode"); if("00".equals(respCode)){ String outPutDirectory ="d:\\"; // 交易成功,解析返回报文中的fileContent并落地 String zipFilePath = AcpService.deCodeFileContent(rspData,outPutDirectory,DemoBase.encoding); //对落地的zip文件解压缩并解析 List<String> fileList = DemoBase.unzip(zipFilePath, outPutDirectory); //解析ZM,ZME文件 fileContentDispaly ="<br>获取到商户对账文件,并落地到"+outPutDirectory+",并解压缩 <br>"; for(String file : fileList){ if(file.indexOf("ZM_")!=-1){ List<Map> ZmDataList = DemoBase.parseZMFile(file); fileContentDispaly = fileContentDispaly+DemoBase.getFileContentTable(ZmDataList,file); }else if(file.indexOf("ZME_")!=-1){ DemoBase.parseZMEFile(file); } } //TODO }else{ //其他应答码为失败请排查原因 //TODO } }else{ LogUtil.writeErrorLog("验证签名失败"); //TODO 检查验证签名失败的原因 } }else{ //未返回正确的http状态 LogUtil.writeErrorLog("未获取到返回报文或返回http状态码非200"); } String reqMessage = DemoBase.genHtmlResult(reqData); String rspMessage = DemoBase.genHtmlResult(rspData); resp.getWriter().write("</br>请求报文:<br/>"+reqMessage+"<br/>" + "应答报文:</br>"+rspMessage+fileContentDispaly); } @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { doPost(req, resp); } }
39.576923
166
0.689602
7e43c7c946ffa9790f999627320c9f63293a9a7a
923
package com.elex.oa.service.project; import com.elex.oa.entity.Page; import com.elex.oa.entity.project.*; import com.github.pagehelper.PageInfo; import java.util.List; import java.util.Map; public interface WeeklyPlanService { //数据列表查询 PageInfo queryList(WeeklyPlanQuery weeklyPlanQuery, Page page); //根据关联id查询计划 List<WeeklyPlan> queryPlansById(String related); //根据姓名查询项目信息 PageInfo<ApprovalList> queryCodeByName(String name, Page page); //根据code 查询详情 Map<String,String> queryDetailByCode(String code); //添加周计划 String addPlans(WeeklyPlan weeklyPlan); //审批周计划 String approvalPlans(WeeklyPlan weeklyPlan); //查询项目信息 PageInfo<ProjectInfor> queryProjectName(OperationQuery operationQuery, Page page); //修改周计划 String amendPlans(WeeklyPlan weeklyPlan); //删除周计划 String deleteWeek(int id); //查询某项目的里程碑计划 List<String> queryMileStone(String code); }
28.84375
86
0.739978
bfb37b34e9157ebf3431c5868fee93750fd49660
1,588
package bdd.dao; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Calendar; import java.util.HashMap; import java.util.Map; import bdd.BDD; import bdd.table.VenteGroup; public class VenteDAO { public static final SimpleDateFormat formatter = new SimpleDateFormat("dd/MM/yy"); public static final SimpleDateFormat formatter2 = new SimpleDateFormat("MMMM yyyy"); /** * Renvoi les vente du mois mentionné * * @param month * @return */ public static Map<String, VenteGroup> getByMonth(final String month) { final Map<String, Map<String, VenteGroup>> ventes = BDD.getInstance().getVentes(); Map<String, VenteGroup> listVente = ventes.get(month); if (listVente == null) { listVente = new HashMap<>(); ventes.put(month, listVente); } return listVente; } /** * Transorme une date en mois + annee (exemple Juin 2016) * * @param date * @return */ public static String dateToMonth(final String date) { try { final Calendar calendar = Calendar.getInstance(); calendar.setTime(formatter.parse(date)); return formatter2.format(calendar.getTime()); } catch (final ParseException e) { System.out.println("ERROR : Impossible de parser la date"); } return null; } /** * Renvoi le premier id disponible * * @param newGroup * @return */ public static String nextId(final VenteGroup newGroup) { int id = 0; while (newGroup.getListVente().containsKey(String.valueOf(id))) { id++; } return String.valueOf(id); } }
24.8125
86
0.672544
bd2cf691f5dbe413c29fb735c2d5b519c7959386
19,111
/* * 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.cayenne.modeler.dialog.db; import java.awt.Component; import java.io.File; import java.io.FileWriter; import java.io.IOException; import java.io.PrintWriter; import java.util.Iterator; import java.util.List; import javax.sql.DataSource; import javax.swing.JFileChooser; import javax.swing.JOptionPane; import javax.swing.WindowConstants; import javax.swing.event.ChangeEvent; import javax.swing.event.ChangeListener; import org.apache.cayenne.access.loader.DbLoaderConfiguration; import org.apache.cayenne.access.loader.filters.TableFilter; import org.apache.cayenne.access.loader.filters.FiltersConfig; import org.apache.cayenne.access.loader.filters.PatternFilter; import org.apache.cayenne.configuration.DataChannelDescriptor; import org.apache.cayenne.configuration.DataNodeDescriptor; import org.apache.cayenne.dba.JdbcAdapter; import org.apache.cayenne.map.DataMap; import org.apache.cayenne.map.DbAttribute; import org.apache.cayenne.map.DbEntity; import org.apache.cayenne.map.DbRelationship; import org.apache.cayenne.map.ObjAttribute; import org.apache.cayenne.map.ObjEntity; import org.apache.cayenne.map.ObjRelationship; import org.apache.cayenne.map.event.EntityEvent; import org.apache.cayenne.map.event.MapEvent; import org.apache.cayenne.merge.AbstractToDbToken; import org.apache.cayenne.merge.DbMerger; import org.apache.cayenne.merge.ExecutingMergerContext; import org.apache.cayenne.merge.MergeDirection; import org.apache.cayenne.merge.MergerContext; import org.apache.cayenne.merge.MergerToken; import org.apache.cayenne.merge.ModelMergeDelegate; import org.apache.cayenne.modeler.ProjectController; import org.apache.cayenne.modeler.dialog.ValidationResultBrowser; import org.apache.cayenne.modeler.event.AttributeDisplayEvent; import org.apache.cayenne.modeler.event.EntityDisplayEvent; import org.apache.cayenne.modeler.event.RelationshipDisplayEvent; import org.apache.cayenne.modeler.pref.DBConnectionInfo; import org.apache.cayenne.modeler.util.CayenneController; import org.apache.cayenne.project.Project; import org.apache.cayenne.resource.Resource; import org.apache.cayenne.swing.BindingBuilder; import org.apache.cayenne.swing.ObjectBinding; import org.apache.cayenne.tools.dbimport.config.FiltersConfigBuilder; import org.apache.cayenne.tools.dbimport.config.ReverseEngineering; import org.apache.cayenne.tools.dbimport.config.Schema; import org.apache.cayenne.validation.ValidationResult; public class MergerOptions extends CayenneController { protected MergerOptionsView view; // protected ObjectBinding[] optionBindings; protected ObjectBinding sqlBinding; protected DBConnectionInfo connectionInfo; protected DataMap dataMap; protected JdbcAdapter adapter; protected String textForSQL; protected DbMerger merger; protected MergerTokenSelectorController tokens; protected String defaultSchema; public MergerOptions(ProjectController parent, String title, DBConnectionInfo connectionInfo, DataMap dataMap, String defaultSchema) { super(parent); this.dataMap = dataMap; this.tokens = new MergerTokenSelectorController(parent); this.view = new MergerOptionsView(tokens.getView()); this.connectionInfo = connectionInfo; this.defaultSchema = defaultSchema; /* * TODO:? this.generatorDefaults = (DBGeneratorDefaults) parent * .getPreferenceDomainForProject() .getDetail("DbGenerator", * DBGeneratorDefaults.class, true); */ this.view.setTitle(title); initController(); // tables.updateTables(dataMap); prepareMigrator(); // generatorDefaults.configureGenerator(generator); createSQL(); refreshView(); } public Component getView() { return view; } /* * public DBGeneratorDefaults getGeneratorDefaults() { return generatorDefaults; } */ public String getTextForSQL() { return textForSQL; } protected void initController() { BindingBuilder builder = new BindingBuilder( getApplication().getBindingFactory(), this); sqlBinding = builder.bindToTextArea(view.getSql(), "textForSQL"); /* * optionBindings = new ObjectBinding[5]; optionBindings[0] = * builder.bindToStateChangeAndAction(view.getCreateFK(), * "generatorDefaults.createFK", "refreshSQLAction()"); optionBindings[1] = * builder.bindToStateChangeAndAction(view.getCreatePK(), * "generatorDefaults.createPK", "refreshSQLAction()"); optionBindings[2] = * builder.bindToStateChangeAndAction(view.getCreateTables(), * "generatorDefaults.createTables", "refreshSQLAction()"); optionBindings[3] = * builder.bindToStateChangeAndAction(view.getDropPK(), * "generatorDefaults.dropPK", "refreshSQLAction()"); optionBindings[4] = * builder.bindToStateChangeAndAction(view.getDropTables(), * "generatorDefaults.dropTables", "refreshSQLAction()"); */ builder.bindToAction(view.getGenerateButton(), "generateSchemaAction()"); builder.bindToAction(view.getSaveSqlButton(), "storeSQLAction()"); builder.bindToAction(view.getCancelButton(), "closeAction()"); // refresh SQL if different tables were selected view.getTabs().addChangeListener(new ChangeListener() { public void stateChanged(ChangeEvent e) { if (view.getTabs().getSelectedIndex() == 1) { // this assumes that some tables where checked/unchecked... not very // efficient refreshGeneratorAction(); } } }); } /** * check database and create the {@link List} of {@link MergerToken}s */ protected void prepareMigrator() { try { adapter = (JdbcAdapter) connectionInfo.makeAdapter(getApplication().getClassLoadingService()); tokens.setMergerFactory(adapter.mergerFactory()); merger = new DbMerger(adapter.mergerFactory()); DbLoaderConfiguration config = new DbLoaderConfiguration(); config.setFiltersConfig(FiltersConfig.create(null, defaultSchema, TableFilter.everything(), PatternFilter.INCLUDE_NOTHING)); List<MergerToken> mergerTokens = merger.createMergeTokens( connectionInfo.makeDataSource(getApplication().getClassLoadingService()), adapter, dataMap, config); tokens.setTokens(mergerTokens); } catch (Exception ex) { reportError("Error loading adapter", ex); } } /** * Returns SQL statements generated for selected schema generation options. */ protected void createSQL() { // convert them to string representation for display StringBuilder buf = new StringBuilder(); Iterator<MergerToken> it = tokens.getSelectedTokens().iterator(); String batchTerminator = adapter.getBatchTerminator(); String lineEnd = batchTerminator != null ? "\n" + batchTerminator + "\n\n" : "\n\n"; while (it.hasNext()) { MergerToken token = it.next(); if (token instanceof AbstractToDbToken) { AbstractToDbToken tdb = (AbstractToDbToken) token; for (String sql : tdb.createSql(adapter)) { buf.append(sql); buf.append(lineEnd); } } } textForSQL = buf.toString(); } protected void refreshView() { /* * for (int i = 0; i < optionBindings.length; i++) { * optionBindings[i].updateView(); } */ sqlBinding.updateView(); } // =============== // Actions // =============== /** * Starts options dialog. */ public void startupAction() { view.pack(); view.setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE); view.setModal(true); makeCloseableOnEscape(); centerView(); view.setVisible(true); } public void refreshGeneratorAction() { // prepareMigrator(); refreshSQLAction(); } /** * Updates a text area showing generated SQL. */ public void refreshSQLAction() { // sync generator with defaults, make SQL, then sync the view... // generatorDefaults.configureGenerator(generator); createSQL(); sqlBinding.updateView(); } /** * Performs configured schema operations via DbGenerator. */ public void generateSchemaAction() { refreshGeneratorAction(); // sanity check... List<MergerToken> tokensToMigrate = tokens.getSelectedTokens(); if (tokensToMigrate.isEmpty()) { JOptionPane.showMessageDialog(getView(), "Nothing to migrate."); return; } final ProjectController c = getProjectController(); final Object src = this; final DataChannelDescriptor domain = (DataChannelDescriptor) getProjectController() .getProject() .getRootNode(); final DataNodeDescriptor node = getProjectController().getCurrentDataNode(); ModelMergeDelegate delegate = new ModelMergeDelegate() { public void dbAttributeAdded(DbAttribute att) { if (c.getCurrentDbEntity() == att.getEntity()) { c.fireDbAttributeDisplayEvent(new AttributeDisplayEvent(src, att, att .getEntity(), dataMap, domain)); } } public void dbAttributeModified(DbAttribute att) { if (c.getCurrentDbEntity() == att.getEntity()) { c.fireDbAttributeDisplayEvent(new AttributeDisplayEvent(src, att, att .getEntity(), dataMap, domain)); } } public void dbAttributeRemoved(DbAttribute att) { if (c.getCurrentDbEntity() == att.getEntity()) { c.fireDbAttributeDisplayEvent(new AttributeDisplayEvent(src, att, att .getEntity(), dataMap, domain)); } } public void dbEntityAdded(DbEntity ent) { c.fireDbEntityEvent(new EntityEvent(src, ent, MapEvent.ADD)); c.fireDbEntityDisplayEvent(new EntityDisplayEvent( src, ent, dataMap, node, domain)); } public void dbEntityRemoved(DbEntity ent) { c.fireDbEntityEvent(new EntityEvent(src, ent, MapEvent.REMOVE)); c.fireDbEntityDisplayEvent(new EntityDisplayEvent( src, ent, dataMap, node, domain)); } public void dbRelationshipAdded(DbRelationship rel) { if (c.getCurrentDbEntity() == rel.getSourceEntity()) { c.fireDbRelationshipDisplayEvent(new RelationshipDisplayEvent( src, rel, rel.getSourceEntity(), dataMap, domain)); } } public void dbRelationshipRemoved(DbRelationship rel) { if (c.getCurrentDbEntity() == rel.getSourceEntity()) { c.fireDbRelationshipDisplayEvent(new RelationshipDisplayEvent( src, rel, rel.getSourceEntity(), dataMap, domain)); } } public void objAttributeAdded(ObjAttribute att) { if (c.getCurrentObjEntity() == att.getEntity()) { c.fireObjAttributeDisplayEvent(new AttributeDisplayEvent( src, att, att.getEntity(), dataMap, domain)); } } public void objAttributeModified(ObjAttribute att) { if (c.getCurrentObjEntity() == att.getEntity()) { c.fireObjAttributeDisplayEvent(new AttributeDisplayEvent( src, att, att.getEntity(), dataMap, domain)); } } public void objAttributeRemoved(ObjAttribute att) { if (c.getCurrentObjEntity() == att.getEntity()) { c.fireObjAttributeDisplayEvent(new AttributeDisplayEvent( src, att, att.getEntity(), dataMap, domain)); } } public void objEntityAdded(ObjEntity ent) { c.fireObjEntityEvent(new EntityEvent(src, ent, MapEvent.ADD)); c.fireObjEntityDisplayEvent(new EntityDisplayEvent( src, ent, dataMap, node, domain)); } public void objEntityRemoved(ObjEntity ent) { c.fireObjEntityEvent(new EntityEvent(src, ent, MapEvent.REMOVE)); c.fireObjEntityDisplayEvent(new EntityDisplayEvent( src, ent, dataMap, node, domain)); } public void objRelationshipAdded(ObjRelationship rel) { if (c.getCurrentObjEntity() == rel.getSourceEntity()) { c.fireObjRelationshipDisplayEvent(new RelationshipDisplayEvent( src, rel, rel.getSourceEntity(), dataMap, domain)); } } public void objRelationshipRemoved(ObjRelationship rel) { if (c.getCurrentObjEntity() == rel.getSourceEntity()) { c.fireObjRelationshipDisplayEvent(new RelationshipDisplayEvent( src, rel, rel.getSourceEntity(), dataMap, domain)); } } }; try { DataSource dataSource = connectionInfo.makeDataSource(getApplication() .getClassLoadingService()); // generator.runGenerator(dataSource); MergerContext mergerContext = new ExecutingMergerContext( dataMap, dataSource, adapter, delegate); boolean modelChanged = false; for (MergerToken tok : tokensToMigrate) { int numOfFailuresBefore = mergerContext .getValidationResult() .getFailures() .size(); tok.execute(mergerContext); if (!modelChanged && tok.getDirection().equals(MergeDirection.TO_MODEL)) { modelChanged = true; } if (numOfFailuresBefore == mergerContext .getValidationResult() .getFailures() .size()) { // looks like the token executed without failures tokens.removeToken(tok); } } if (modelChanged) { // mark the model as unsaved Project project = getApplication().getProject(); project.setModified(true); ProjectController projectController = getApplication() .getFrameController() .getProjectController(); projectController.setDirty(true); } ValidationResult failures = mergerContext.getValidationResult(); if (failures == null || !failures.hasFailures()) { JOptionPane.showMessageDialog(getView(), "Migration Complete."); } else { new ValidationResultBrowser(this).startupAction( "Migration Complete", "Migration finished. The following problem(s) were ignored.", failures); } } catch (Throwable th) { reportError("Migration Error", th); } } /** * Allows user to save generated SQL in a file. */ public void storeSQLAction() { JFileChooser fc = new JFileChooser(); fc.setDialogType(JFileChooser.SAVE_DIALOG); fc.setDialogTitle("Save SQL Script"); Resource projectDir = getApplication().getProject().getConfigurationResource(); if (projectDir != null) { fc.setCurrentDirectory(new File(projectDir.getURL().getPath())); } if (fc.showSaveDialog(getView()) == JFileChooser.APPROVE_OPTION) { refreshGeneratorAction(); try { File file = fc.getSelectedFile(); FileWriter fw = new FileWriter(file); PrintWriter pw = new PrintWriter(fw); pw.print(textForSQL); pw.flush(); pw.close(); } catch (IOException ex) { reportError("Error Saving SQL", ex); } } } private ProjectController getProjectController() { return getApplication().getFrameController().getProjectController(); } public void closeAction() { view.dispose(); } }
37.108738
136
0.577259
f5239cffe03785454bf804cf4237bb7dcd039484
5,881
begin_unit|revision:0.9.5;language:Java;cregit-version:0.0.1 begin_comment comment|/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ end_comment begin_package package|package name|org operator|. name|apache operator|. name|karaf operator|. name|event operator|. name|command package|; end_package begin_import import|import static name|org operator|. name|hamcrest operator|. name|CoreMatchers operator|. name|equalTo import|; end_import begin_import import|import static name|org operator|. name|junit operator|. name|Assert operator|. name|assertThat import|; end_import begin_import import|import name|java operator|. name|io operator|. name|ByteArrayOutputStream import|; end_import begin_import import|import name|java operator|. name|io operator|. name|PrintStream import|; end_import begin_import import|import name|java operator|. name|io operator|. name|UnsupportedEncodingException import|; end_import begin_import import|import name|java operator|. name|text operator|. name|DateFormat import|; end_import begin_import import|import name|java operator|. name|text operator|. name|ParseException import|; end_import begin_import import|import name|java operator|. name|text operator|. name|SimpleDateFormat import|; end_import begin_import import|import name|java operator|. name|util operator|. name|Date import|; end_import begin_import import|import name|java operator|. name|util operator|. name|HashMap import|; end_import begin_import import|import name|org operator|. name|apache operator|. name|karaf operator|. name|event operator|. name|command operator|. name|EventPrinter import|; end_import begin_import import|import name|org operator|. name|junit operator|. name|Test import|; end_import begin_import import|import name|org operator|. name|osgi operator|. name|service operator|. name|event operator|. name|Event import|; end_import begin_class specifier|public class|class name|EventPrinterTest block|{ name|DateFormat name|df init|= operator|new name|SimpleDateFormat argument_list|( literal|"yyyy-MM-dd HH:mm" argument_list|) decl_stmt|; annotation|@ name|Test specifier|public name|void name|testPrint parameter_list|() throws|throws name|UnsupportedEncodingException block|{ name|ByteArrayOutputStream name|baos init|= operator|new name|ByteArrayOutputStream argument_list|() decl_stmt|; name|PrintStream name|out init|= operator|new name|PrintStream argument_list|( name|baos argument_list|) decl_stmt|; operator|new name|EventPrinter argument_list|( name|out argument_list|, literal|false argument_list|) operator|. name|accept argument_list|( name|event argument_list|() argument_list|) expr_stmt|; name|String name|result init|= name|baos operator|. name|toString argument_list|( literal|"utf-8" argument_list|) decl_stmt|; name|assertThat argument_list|( name|result argument_list|, name|equalTo argument_list|( literal|"2016-01-01 12:00:00 - myTopic\n" argument_list|) argument_list|) expr_stmt|; block|} annotation|@ name|Test specifier|public name|void name|testPrintVerbose parameter_list|() throws|throws name|UnsupportedEncodingException block|{ name|ByteArrayOutputStream name|baos init|= operator|new name|ByteArrayOutputStream argument_list|() decl_stmt|; name|PrintStream name|out init|= operator|new name|PrintStream argument_list|( name|baos argument_list|) decl_stmt|; operator|new name|EventPrinter argument_list|( name|out argument_list|, literal|true argument_list|) operator|. name|accept argument_list|( name|event argument_list|() argument_list|) expr_stmt|; name|String name|result init|= name|baos operator|. name|toString argument_list|( literal|"utf-8" argument_list|) decl_stmt|; name|assertThat argument_list|( name|result argument_list|, name|equalTo argument_list|( literal|"2016-01-01 12:00:00 - myTopic\n" operator|+ literal|"a: b\n" operator|+ literal|"c: [d, e]\n\n" argument_list|) argument_list|) expr_stmt|; block|} specifier|private name|Event name|event parameter_list|() block|{ name|HashMap argument_list|< name|String argument_list|, name|Object argument_list|> name|props init|= operator|new name|HashMap argument_list|<> argument_list|() decl_stmt|; name|props operator|. name|put argument_list|( literal|"a" argument_list|, literal|"b" argument_list|) expr_stmt|; name|props operator|. name|put argument_list|( literal|"c" argument_list|, operator|new name|String index|[] block|{ literal|"d" block|, literal|"e" block|} argument_list|) expr_stmt|; name|Date name|date decl_stmt|; try|try block|{ name|date operator|= name|df operator|. name|parse argument_list|( literal|"2016-01-01 12:00:00" argument_list|) expr_stmt|; block|} catch|catch parameter_list|( name|ParseException name|e parameter_list|) block|{ throw|throw operator|new name|RuntimeException argument_list|( name|e argument_list|) throw|; block|} name|props operator|. name|put argument_list|( literal|"timestamp" argument_list|, name|date operator|. name|getTime argument_list|() argument_list|) expr_stmt|; return|return operator|new name|Event argument_list|( literal|"myTopic" argument_list|, name|props argument_list|) return|; block|} block|} end_class end_unit
14.665835
810
0.794763
1013aeb2909ce9263ab40165585238d9e6122a35
23,141
package org.galatea.kafka.starter.testing; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; import static org.unitils.reflectionassert.ReflectionAssert.assertReflectionEquals; import java.io.Closeable; import java.io.File; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.Optional; import java.util.Properties; import java.util.Set; import java.util.concurrent.Callable; import java.util.function.Function; import lombok.Getter; import lombok.extern.slf4j.Slf4j; import org.apache.kafka.common.serialization.Serde; import org.apache.kafka.streams.KafkaStreams; import org.apache.kafka.streams.KeyValue; import org.apache.kafka.streams.MockCluster; import org.apache.kafka.streams.StreamsConfig; import org.apache.kafka.streams.TestInputTopic; import org.apache.kafka.streams.TestOutputTopic; import org.apache.kafka.streams.Topology; import org.apache.kafka.streams.TopologyTestDriver; import org.apache.kafka.streams.state.KeyValueIterator; import org.apache.kafka.streams.state.KeyValueStore; import org.apache.kafka.streams.state.QueryableStoreType; import org.galatea.kafka.starter.messaging.Topic; import org.galatea.kafka.starter.testing.alias.AliasHelper; import org.galatea.kafka.starter.testing.avro.RecordPostProcessor; import org.galatea.kafka.starter.testing.conversion.ConversionService; import org.springframework.util.FileSystemUtils; import org.unitils.reflectionassert.ReflectionComparatorMode; @Slf4j public class TopologyTester implements Closeable { @Getter private final TopologyTestDriver driver; private final Map<String, TopicConfig<?, ?>> inputTopicConfig = new HashMap<>(); private final Map<String, TopicConfig<?, ?>> outputTopicConfig = new HashMap<>(); private final Map<String, TopicConfig<?, ?>> storeConfig = new HashMap<>(); private final Set<Class<?>> beanClasses = new HashSet<>(); @Getter private final ConversionService typeConversionService = new ConversionService(); private final Map<Class<?>, RecordPostProcessor<?>> postProcessors = new HashMap<>(); /** * Use this KafkaStreams object for calling any code that needs to retrieve stores from the * KafkaStreams object */ public KafkaStreams mockStreams() { KafkaStreams mockStreams = mock(KafkaStreams.class); when(mockStreams.store(any(String.class), any(QueryableStoreType.class))) .thenAnswer(invocationOnMock -> driver.getKeyValueStore(invocationOnMock.getArgument(0))); return mockStreams; } public <T> void registerPostProcessor(Class<T> forClass, RecordPostProcessor<T> processor) { postProcessors.put(forClass, processor); } public TopologyTester(Topology topology, Properties streamProperties) { String stateDir = streamProperties.getProperty(StreamsConfig.STATE_DIR_CONFIG) + "/" + streamProperties .getProperty(StreamsConfig.APPLICATION_ID_CONFIG); File dirFile = new File(stateDir); if (dirFile.exists() && !FileSystemUtils.deleteRecursively(dirFile)) { log.error("Was unable to delete state dir before tests: {}", stateDir); } driver = new TopologyTestDriver(topology, streamProperties, MockCluster.empty()); log.info("Initiated new TopologyTester with application ID: {}", streamProperties.getProperty(StreamsConfig.APPLICATION_ID_CONFIG)); } /** * Register class/interface to be treated as a bean. If not registered, the class will be created * using the string constructor if it exists. */ public void registerBeanClass(Class<?> beanClassOrInterface) { beanClasses.add(beanClassOrInterface); } public void beforeTest() { outputTopicConfig.forEach((topicName, topicConfig) -> readOutput(topicConfig)); driver.getAllStateStores().values().stream().flatMap(Collection::stream) .map(s -> (KeyValueStore<Object, ?>) s) .forEach(kvStore -> { try (KeyValueIterator<Object, ?> iter = kvStore.all()) { while (iter.hasNext()) { KeyValue<Object, ?> entry = iter.next(); log.info("Deleting entry in store: {}", entry); kvStore.delete(entry.key); } kvStore.flush(); } }); } public <K, V> void purgeMessagesInOutput(Topic<K, V> topic) { readOutput(outputTopicConfig(topic)); } @SuppressWarnings("unchecked") public <K, V> TopicConfig<K, V> getInputConfig(Topic<K, V> topic) { return (TopicConfig<K, V>) inputTopicConfig.get(topic.getName()); } @SuppressWarnings("unchecked") public <K, V> TopicConfig<K, V> getOutputConfig(Topic<K, V> topic) { return (TopicConfig<K, V>) outputTopicConfig.get(topic.getName()); } @SuppressWarnings("unchecked") public <K, V> TopicConfig<K, V> getStoreConfig(String storeName) { return (TopicConfig<K, V>) storeConfig.get(storeName); } public <K, V> TopicConfig<K, V> configureInputTopic(Topic<K, V> topic, Callable<K> createEmptyKey, Callable<V> createEmptyValue) { if (inputTopicConfig.containsKey(topic.getName())) { throw new IllegalStateException( String.format("Input topic %s cannot be configured more than once", topic.getName())); } inputTopicConfig.put(topic.getName(), new TopicConfig<>(topic.getName(), topic.getKeySerde(), topic.getValueSerde(), createEmptyKey, createEmptyValue, testInputTopic(topic))); return inputTopicConfig(topic); } private <K, V> TestInputTopic<K, V> testInputTopic(Topic<K, V> topic) { return driver.createInputTopic(topic.getName(), topic.getKeySerde().serializer(), topic.getValueSerde().serializer()); } private <K, V> TestOutputTopic<K, V> testOutputTopic(Topic<K, V> topic) { return driver.createOutputTopic(topic.getName(), topic.getKeySerde().deserializer(), topic.getValueSerde().deserializer()); } public <K, V> TopicConfig<K, V> configureOutputTopic(Topic<K, V> topic, Callable<K> createEmptyKey, Callable<V> createEmptyValue) { if (outputTopicConfig.containsKey(topic.getName())) { throw new IllegalStateException( String.format("Output topic %s cannot be configured more than once", topic.getName())); } outputTopicConfig.put(topic.getName(), new TopicConfig<>(topic.getName(), topic.getKeySerde(), topic.getValueSerde(), createEmptyKey, createEmptyValue, testOutputTopic(topic))); return outputTopicConfig(topic); } public <K, V> TopicConfig<K, V> configureStore(String storeName, Serde<K> keySerde, Serde<V> valueSerde, Callable<K> createEmptyKey, Callable<V> createEmptyValue) { if (storeConfig.containsKey(storeName)) { throw new IllegalStateException( String.format("Store %s cannot be configured more than once", storeName)); } storeConfig.put(storeName, new TopicConfig<>(storeName, keySerde, valueSerde, createEmptyKey, createEmptyValue)); return storeConfig(storeName); } public <K, V> void pipeInput(Topic<K, V> topic, List<Map<String, String>> records) throws Exception { pipeInput(topic, records, null); } public <K, V> void pipeInput(Topic<K, V> topic, List<Map<String, String>> records, Function<KeyValue<K, V>, KeyValue<K, V>> recordCreationCallback) throws Exception { for (Map<String, String> record : records) { pipeInput(topic, record, recordCreationCallback); } } public <K, V> void pipeInput(Topic<K, V> topic, Map<String, String> fieldMap) throws Exception { pipeInput(topic, fieldMap, null); } public <K, V> void pipeInput(Topic<K, V> topic, Map<String, String> fieldMap, Function<KeyValue<K, V>, KeyValue<K, V>> recordCreationCallback) throws Exception { TopicConfig<K, V> topicConfig = inputTopicConfig(topic); KeyValue<K, V> record = createRecordWithProcessing(fieldMap, topicConfig); if (recordCreationCallback != null) { record = recordCreationCallback.apply(record); } log.info("{} Piping record into topology on topic {}: {}", TopologyTester.class.getSimpleName(), topic.getName(), record); topicConfig.getConfiguredInput().pipeInput(record.key, record.value); } private <V, K> boolean keyIsBean(TopicConfig<K, V> topicConfig) throws Exception { Class<?> keyClass = topicConfig.createKey().getClass(); return beanClasses.contains(keyClass) || collectionContainsAny(beanClasses, Arrays.asList(keyClass.getInterfaces())); } private <V, K> boolean valueIsBean(TopicConfig<K, V> topicConfig) throws Exception { Class<?> valueClass = topicConfig.createValue().getClass(); return beanClasses.contains(valueClass) || collectionContainsAny(beanClasses, Arrays.asList(valueClass.getInterfaces())); } public static <T> boolean collectionContainsAny(Set<T> set, Collection<T> contains) { for (T contain : contains) { if (set.contains(contain)) { return true; } } return false; } public <K, V> void assertOutputList(Topic<K, V> topic, List<Map<String, String>> expectedRecords, boolean lenientOrder) throws Exception { assertOutputList(topic, expectedRecords, lenientOrder, Collections.emptySet()); } /** * maps within list of expected records may NOT have different key sets */ public <K, V> void assertOutputList(Topic<K, V> topic, List<Map<String, String>> expectedRecords, boolean lenientOrder, Set<String> extraFieldsToCompareWithDefaults) throws Exception { TopicConfig<K, V> topicConfig = outputTopicConfig(topic); List<KeyValue<K, V>> output = readOutput(topicConfig); if (expectedRecords.isEmpty() && output.isEmpty()) { return; } if (!output.isEmpty()) { assertFalse("output is not empty but expectedOutput is. At least 1 record is required " + "in 'expectedRecords' for in-depth comparison", expectedRecords.isEmpty()); } Set<String> expectedFields = AliasHelper .expandAliasKeys(expectedRecords.get(0).keySet(), topicConfig.getAliases()); expectedFields.addAll( AliasHelper.expandAliasKeys(extraFieldsToCompareWithDefaults, topicConfig.getAliases())); // comparableActualOutput has only necessary fields populated, as defined by 'expectedFields' List<KeyValue<K, V>> comparableActualOutput = stripUnnecessaryFields(output, expectedFields, topicConfig); List<KeyValue<K, V>> expectedOutput = new ArrayList<>( expectedRecordsFromMaps(topicConfig, expectedRecords, extraFieldsToCompareWithDefaults)); assertListEquals(expectedOutput, comparableActualOutput, lenientOrder); } protected <V, K> Collection<KeyValue<K, V>> expectedRecordsFromMaps(TopicConfig<K, V> topicConfig, Collection<Map<String, String>> expectedRecordMaps, Set<String> extraFieldsToDefault) throws Exception { List<KeyValue<K, V>> expectedOutput = new ArrayList<>(); if (expectedRecordMaps.isEmpty()) { return expectedOutput; } Set<String> expectedFields = expectedRecordMaps.stream().findFirst().map(Map::keySet) .orElse(new HashSet<>()); // verify that all maps in expectedRecordMaps have the same set of fields for (Map<String, String> expectedRecordMap : expectedRecordMaps) { if (!expectedRecordMap.keySet().equals(expectedFields)) { throw new IllegalArgumentException(String.format("Expected records (as maps) have " + "differing key sets.\n\tExpected: %s\n\tActual: %s", expectedFields, expectedRecordMap.keySet())); } } Set<String> fieldsToMakeDefault = AliasHelper .expandAliasKeys(extraFieldsToDefault, topicConfig.getAliases()); Map<String, String> topicDefaultValues = AliasHelper .expandAliasKeys(topicConfig.getDefaultValues(), topicConfig.getAliases()); for (Map<String, String> expectedRecordMap : expectedRecordMaps) { expectedRecordMap = AliasHelper.expandAliasKeys(expectedRecordMap, topicConfig.getAliases()); // add default values to expectedRecordMap if the field doesn't exist already for (String fieldToDefault : fieldsToMakeDefault) { expectedRecordMap.computeIfAbsent(fieldToDefault, key -> Optional.ofNullable(topicDefaultValues.get(key)).orElseThrow( () -> new IllegalArgumentException(String.format( "Cannot do an explicit compare on field '%s' because default value is not set", fieldToDefault)))); } expectedOutput.add(createRecordWithProcessing(expectedRecordMap, topicConfig)); } return expectedOutput; } public void assertStoreContain(String storeName, Collection<Map<String, String>> expected) throws Exception { assertStoreContain(storeName, expected, Collections.emptySet()); } public void assertStoreContain(String storeName, Collection<Map<String, String>> expected, Set<String> extraFieldsToDefault) throws Exception { TopicConfig<Object, Object> storeConfig = storeConfig(storeName); if (expected.isEmpty()) { return; } KeyValueStore<Object, Object> store = driver.getKeyValueStore(storeName); Collection<KeyValue<Object, Object>> expectedRecords = expectedRecordsFromMaps(storeConfig, expected, extraFieldsToDefault); Set<String> expectedFields = expected.iterator().next().keySet(); expectedFields = AliasHelper.expandAliasKeys(expectedFields, storeConfig.getAliases()); expectedFields .addAll(AliasHelper.expandAliasKeys(extraFieldsToDefault, storeConfig.getAliases())); List<KeyValue<Object, Object>> storeContentsStripped = new ArrayList<>(); try (KeyValueIterator<Object, Object> iter = store.all()) { while (iter.hasNext()) { storeContentsStripped.add(stripUnnecessaryFields(iter.next(), expectedFields, storeConfig)); } } for (KeyValue<Object, Object> expectedRecord : expectedRecords) { assertTrue(String.format("Store does not contain record with matching fields %s; values: %s", expectedFields.toString(), expectedRecord), storeContentsStripped.contains(expectedRecord)); } } public void assertStoreNotContain(String storeName, Collection<Map<String, String>> unexpected) throws Exception { assertStoreNotContain(storeName, unexpected, Collections.emptySet()); } public void assertStoreNotContain(String storeName, Collection<Map<String, String>> unexpected, Set<String> extraFieldsToDefault) throws Exception { TopicConfig<Object, Object> storeConfig = storeConfig(storeName); if (unexpected.isEmpty()) { return; } KeyValueStore<Object, Object> store = driver.getKeyValueStore(storeName); Collection<KeyValue<Object, Object>> unexpectedRecords = expectedRecordsFromMaps(storeConfig, unexpected, extraFieldsToDefault); Set<String> expectedFields = unexpected.iterator().next().keySet(); expectedFields = AliasHelper.expandAliasKeys(expectedFields, storeConfig.getAliases()); expectedFields .addAll(AliasHelper.expandAliasKeys(extraFieldsToDefault, storeConfig.getAliases())); List<KeyValue<Object, Object>> storeContentsStripped = new ArrayList<>(); try (KeyValueIterator<Object, Object> iter = store.all()) { while (iter.hasNext()) { storeContentsStripped.add(stripUnnecessaryFields(iter.next(), expectedFields, storeConfig)); } } for (KeyValue<Object, Object> unexpectedRecord : unexpectedRecords) { assertFalse(String.format("Store does not contain record with matching fields %s; values: %s", expectedFields.toString(), unexpectedRecord), storeContentsStripped.contains(unexpectedRecord)); } } // TODO: raw types aliasing, conversions, defaults private <K, V> KeyValue<K, V> createRecordWithProcessing(Map<String, String> expectedEntryMap, TopicConfig<K, V> topicConfig) throws Exception { boolean keyIsBean = keyIsBean(topicConfig); boolean valueIsBean = valueIsBean(topicConfig); KeyValue<K, V> record = RecordBeanHelper .createRecord(typeConversionService, expectedEntryMap, topicConfig, keyIsBean, valueIsBean); return postProcessRecord(record); } private <V, K> KeyValue<K, V> postProcessRecord(KeyValue<K, V> record) throws Exception { K processedKey = null; V processedValue = null; for (Entry<Class<?>, RecordPostProcessor<?>> entry : postProcessors.entrySet()) { Class<?> forClass = entry.getKey(); RecordPostProcessor<?> processor = entry.getValue(); if (processedKey == null && forClass.isInstance(record.key)) { log.debug("Post-processing key {}", record.key); processedKey = useProcessor((RecordPostProcessor<K>) processor, record.key); log.debug("Processed key: {}", processedKey); } if (processedValue == null && forClass.isInstance(record.value)) { log.debug("Post-processing key {}", record.value); processedValue = useProcessor((RecordPostProcessor<V>) processor, record.value); log.debug("Processed value: {}", processedValue); } if (processedKey != null && processedValue != null) { break; } } processedKey = Optional.ofNullable(processedKey).orElse(record.key); processedValue = Optional.ofNullable(processedValue).orElse(record.value); return KeyValue.pair(processedKey, processedValue); } private <K> K useProcessor(RecordPostProcessor<K> processor, K key) throws Exception { return processor.process(key); } public <K, V> void assertOutputMap(Topic<K, V> topic, Collection<Map<String, String>> expectedRecords) throws Exception { assertOutputMap(topic, expectedRecords, Collections.emptySet()); } public <K, V> void assertOutputMap(Topic<K, V> topic, Collection<Map<String, String>> expectedRecords, Set<String> extraFieldsToCompareWithDefaults) throws Exception { TopicConfig<K, V> topicConfig = outputTopicConfig(topic); List<KeyValue<K, V>> output = readOutput(topicConfig); if (output.isEmpty() && expectedRecords.isEmpty()) { // both empty, no need to do anything else return; } Map<K, V> outputMap = new HashMap<>(); for (KeyValue<K, V> outputRecord : output) { outputMap.put(outputRecord.key, outputRecord.value); } List<KeyValue<K, V>> reducedOutput = new ArrayList<>(); outputMap.forEach((key, value) -> reducedOutput.add(new KeyValue<>(key, value))); if (!output.isEmpty()) { assertFalse("output is not empty but expectedOutput is. At least 1 record is required " + "in 'expectedRecords' for in-depth comparison", expectedRecords.isEmpty()); } Set<String> expectedFields = AliasHelper .expandAliasKeys(expectedRecords.iterator().next().keySet(), topicConfig.getAliases()); expectedFields.addAll( AliasHelper.expandAliasKeys(extraFieldsToCompareWithDefaults, topicConfig.getAliases())); List<KeyValue<K, V>> comparableOutput = stripUnnecessaryFields(reducedOutput, expectedFields, topicConfig); Collection<KeyValue<K, V>> expectedOutput = expectedRecordsFromMaps(topicConfig, expectedRecords, extraFieldsToCompareWithDefaults); assertListEquals(expectedOutput, comparableOutput, true); } private <K, V> List<KeyValue<K, V>> stripUnnecessaryFields(List<KeyValue<K, V>> records, Set<String> necessaryFields, TopicConfig<K, V> topicConfig) throws Exception { // strippedRecords will contain the same records as input, but with only necessary fields populated List<KeyValue<K, V>> strippedRecords = new ArrayList<>(); for (KeyValue<K, V> originalRecord : records) { strippedRecords.add(stripUnnecessaryFields(originalRecord, necessaryFields, topicConfig)); } return strippedRecords; } private <K, V> KeyValue<K, V> stripUnnecessaryFields(KeyValue<K, V> record, Set<String> necessaryFields, TopicConfig<K, V> topicConfig) throws Exception { boolean keyIsBean = keyIsBean(topicConfig); boolean valueIsBean = valueIsBean(topicConfig); KeyValue<K, V> strippedRecord = RecordBeanHelper .copyRecordPropertiesIntoNew(necessaryFields, record, topicConfig, keyIsBean, valueIsBean); return postProcessRecord(strippedRecord); } private void assertListEquals(Collection<?> expected, Collection<?> actual, boolean lenientOrder) { try { if (lenientOrder) { assertReflectionEquals(expected, actual, ReflectionComparatorMode.LENIENT_ORDER); } else { assertReflectionEquals(expected, actual); } } catch (IllegalStateException e) { if (!lenientOrder) { throw e; // believe the IllegalStateException will only occur with LENIENT_ORDER enabled } List<?> actualWithoutExpected = new ArrayList<>(actual); StringBuilder sb = new StringBuilder("Expected and Actual lists do no match:"); for (Object expectedEntry : expected) { if (actualWithoutExpected.contains(expectedEntry)) { actualWithoutExpected.remove(expectedEntry); } else { sb.append("\n\tExpected but not received: ").append(expectedEntry.toString()); } } for (Object receivedButNotExpected : actualWithoutExpected) { sb.append("\n\tReceived but not expected: ").append(receivedButNotExpected.toString()); } fail(sb.toString()); } } private <K, V> List<KeyValue<K, V>> readOutput(TopicConfig<K, V> config) { return config.getConfiguredOutput().readKeyValuesToList(); } @SuppressWarnings("unchecked") private <K, V> TopicConfig<K, V> inputTopicConfig(Topic<K, V> topic) { TopicConfig<?, ?> topicConfig = inputTopicConfig.get(topic.getName()); if (topicConfig == null) { throw new IllegalStateException( String.format("Input topic %s is not configured", topic.getName())); } return (TopicConfig<K, V>) topicConfig; } @SuppressWarnings("unchecked") private <K, V> TopicConfig<K, V> outputTopicConfig(Topic<K, V> topic) { TopicConfig<?, ?> topicConfig = outputTopicConfig.get(topic.getName()); if (topicConfig == null) { throw new IllegalStateException( String.format("Output topic %s is not configured", topic.getName())); } return (TopicConfig<K, V>) topicConfig; } @SuppressWarnings("unchecked") private <K, V> TopicConfig<K, V> storeConfig(String storeName) { TopicConfig<?, ?> topicConfig = storeConfig.get(storeName); if (topicConfig == null) { throw new IllegalStateException( String.format("Store %s is not configured", storeName)); } return (TopicConfig<K, V>) topicConfig; } @Override public void close() { driver.close(); } }
40.957522
103
0.710341
fb305e7c5a2008de172042869515866ca9c3e215
22,120
package gov.nih.nci.evs.testUtil.ui; import gov.nih.nci.evs.browser.common.*; import gov.nih.nci.evs.browser.utils.*; import java.io.*; import java.net.*; import java.util.*; import org.LexGrid.LexBIG.DataModel.Core.ResolvedConceptReference; import org.LexGrid.LexBIG.LexBIGService.LexBIGService; import org.LexGrid.LexBIG.Utility.Iterators.*; import org.LexGrid.LexBIG.Utility.Iterators.ResolvedConceptReferencesIterator; /** * <!-- LICENSE_TEXT_START --> * Copyright 2008-2015 NGIT. This software was developed in conjunction * with the National Cancer Institute, and so to the extent government * employees are co-authors, any rights in such works shall be subject * to Title 17 of the United States Code, section 105. * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the disclaimer of Article 3, * below. 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. * 2. The end-user documentation included with the redistribution, * if any, must include the following acknowledgment: * "This product includes software developed by NGIT and the National * Cancer Institute." If no such end-user documentation is to be * included, this acknowledgment shall appear in the software itself, * wherever such third-party acknowledgments normally appear. * 3. The names "The National Cancer Institute", "NCI" and "NGIT" must * not be used to endorse or promote products derived from this software. * 4. This license does not authorize the incorporation of this software * into any third party proprietary programs. This license does not * authorize the recipient to use any trademarks owned by either NCI * or NGIT * 5. THIS SOFTWARE IS PROVIDED "AS IS," AND ANY EXPRESSED OR IMPLIED * WARRANTIES, (INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE) ARE * DISCLAIMED. IN NO EVENT SHALL THE NATIONAL CANCER INSTITUTE, * NGIT, OR THEIR AFFILIATES 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. * <!-- LICENSE_TEXT_END --> */ /** * @author EVS Team * @version 1.0 * * Modification history: * Initial implementation kim.ong@ngc.com * */ public class TestCaseValidator { // Variable declaration private LexBIGService lbSvc = null; private ResolvedConceptReferencesIterator rcr_iterator = null; private ResolvedConceptReference rcref = null; // Default constructor public TestCaseValidator(LexBIGService lbSvc) { this.lbSvc = lbSvc; } /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // Simple search /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// //name or code search public ResolvedConceptReference validate(String scheme, String version, String matchText, String target, String algorithm) { ResolvedConceptReferencesIterator iterator = search(scheme, version, matchText, target, algorithm); if (iterator == null) return null; ResolvedConceptReference rcref = null; try { while(iterator.hasNext()) { rcref = iterator.next(); return rcref; } } catch (Exception ex) { ex.printStackTrace(); } return null; } public ResolvedConceptReferencesIterator search(String scheme, String version, String matchText, String target, String algorithm) { ResolvedConceptReferencesIterator rcr_iterator = null; try { rcr_iterator = new SimpleSearchUtils(lbSvc).search(scheme, version, matchText, target, algorithm); return rcr_iterator; } catch (Exception ex) { ex.printStackTrace(); return null; } } public ResolvedConceptReference validatePropertySearch( String scheme, String version, String matchText, String source, String matchAlgorithm, boolean excludeDesignation, boolean ranking, int maxToReturn) { ResolvedConceptReferencesIterator iterator = searchByProperties( scheme, version, matchText, source, matchAlgorithm, excludeDesignation, ranking, maxToReturn); if (iterator == null) return null; ResolvedConceptReference rcref = null; try { while(iterator.hasNext()) { rcref = iterator.next(); return rcref; } } catch (Exception ex) { ex.printStackTrace(); } return null; } // property search public ResolvedConceptReferencesIterator search( String scheme, String version, String matchText, String[] property_types, String[] property_names, String source, String matchAlgorithm, boolean excludeDesignation, boolean ranking, int maxToReturn) { ResolvedConceptReferencesIterator rcr_iterator = null; try { ResolvedConceptReferencesIteratorWrapper wrapper = new SearchUtils(lbSvc).searchByProperties( scheme, version, matchText, property_types, property_names, source, matchAlgorithm, excludeDesignation, ranking, maxToReturn); if (wrapper != null) { rcr_iterator = wrapper.getIterator(); return rcr_iterator; } } catch (Exception ex) { ex.printStackTrace(); return null; } return null; } public ResolvedConceptReferencesIterator searchByProperties( String scheme, String version, String matchText, String source, String matchAlgorithm, boolean excludeDesignation, boolean ranking, int maxToReturn) { Vector schemes = new Vector(); Vector versions = new Vector(); schemes.add(scheme); versions.add(version); return searchByProperties( schemes, versions, matchText, source, matchAlgorithm, excludeDesignation, ranking, maxToReturn); } public ResolvedConceptReferencesIterator searchByProperties( Vector schemes, Vector versions, String matchText, String source, String matchAlgorithm, boolean excludeDesignation, boolean ranking, int maxToReturn) { ResolvedConceptReferencesIterator rcr_iterator = null; try { ResolvedConceptReferencesIteratorWrapper wrapper = new SearchUtils(lbSvc).searchByProperties( schemes, versions, matchText, source, matchAlgorithm, excludeDesignation, ranking, maxToReturn); if (wrapper != null) { rcr_iterator = wrapper.getIterator(); return rcr_iterator; } } catch (Exception ex) { ex.printStackTrace(); } return null; } //relationship search public ResolvedConceptReference validate(String scheme, String version, String matchText, String[] associationsToNavigate, String[] association_qualifier_names, String[] association_qualifier_values, int search_direction, String source, String matchAlgorithm, boolean designationOnly, boolean ranking, int maxToReturn ) { ResolvedConceptReferencesIterator iterator = search(scheme, version, matchText, associationsToNavigate, association_qualifier_names, association_qualifier_values, search_direction, source, matchAlgorithm, designationOnly, ranking, maxToReturn); if (iterator == null) return null; ResolvedConceptReference rcref = null; try { while(iterator.hasNext()) { rcref = iterator.next(); return rcref; } } catch (Exception ex) { ex.printStackTrace(); } return null; } public ResolvedConceptReferencesIterator search(String scheme, String version, String matchText, String[] associationsToNavigate, String[] association_qualifier_names, String[] association_qualifier_values, int search_direction, String source, String matchAlgorithm, boolean designationOnly, boolean ranking, int maxToReturn ) { ResolvedConceptReferencesIterator rcr_iterator = null; try { ResolvedConceptReferencesIteratorWrapper wrapper = new SearchUtils(lbSvc).searchByAssociations( scheme, version, matchText, associationsToNavigate, association_qualifier_names, association_qualifier_values, search_direction, source, matchAlgorithm, designationOnly, ranking, maxToReturn); if (wrapper != null) { rcr_iterator = wrapper.getIterator(); return rcr_iterator; } } catch (Exception ex) { ex.printStackTrace(); } return null; } /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // Mapping search /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// //validate mapping search public ResolvedConceptReference validateMappingSearch( String scheme, String version, String matchText, String target, String matchAlgorithm, int maxToReturn ) { ResolvedConceptReferencesIterator iterator = searchMapping( scheme, version, matchText, target, matchAlgorithm, maxToReturn); if (iterator == null) return null; ResolvedConceptReference rcref = null; try { while(iterator.hasNext()) { rcref = iterator.next(); return rcref; } } catch (Exception ex) { ex.printStackTrace(); } return null; } // mapping search public ResolvedConceptReferencesIterator searchMapping( String scheme, String version, String matchText, String target, String matchAlgorithm, int maxToReturn ) { return new MappingSearchUtils(lbSvc).searchMapping( scheme, version, matchText, target, matchAlgorithm, maxToReturn); } /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // Resolved value set search /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// //resolved value set search public ResolvedConceptReference validateValueSetSearch( String scheme, String version, String matchText, String target, String matchAlgorithm, int maxToReturn ) { ResolvedConceptReferencesIterator iterator = searchValueSet( scheme, version, matchText, target, matchAlgorithm, maxToReturn); if (iterator == null) return null; ResolvedConceptReference rcref = null; try { while(iterator.hasNext()) { rcref = iterator.next(); return rcref; } } catch (Exception ex) { ex.printStackTrace(); } return null; } public ResolvedConceptReferencesIterator searchValueSet( String scheme, String version, String matchText, String target, String matchAlgorithm, int maxToReturn ) { if (target.compareTo("Code") == 0 || target.compareTo("codes") == 0) { return new ValueSetSearchUtils().searchByCode( scheme, matchText, maxToReturn); } else if (target.compareTo("Name") == 0 || target.compareTo("names") == 0) { return new ValueSetSearchUtils().searchByName( scheme, matchText, matchAlgorithm, maxToReturn); } return null; } /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // Multiple search /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// public ResolvedConceptReference validateMultipleSearch( Vector schemes, Vector versions, String matchText, String target, String matchAlgorithm, int maxToReturn ) { ResolvedConceptReferencesIterator iterator = multipleSearch( schemes, versions, matchText, target, matchAlgorithm, maxToReturn); if (iterator == null) return null; ResolvedConceptReference rcref = null; try { while(iterator.hasNext()) { rcref = iterator.next(); return rcref; } } catch (Exception ex) { ex.printStackTrace(); } return null; } public ResolvedConceptReferencesIterator multipleSearch( Vector schemes, Vector versions, String matchText, String target, String matchAlgorithm, int maxToReturn ) { ResolvedConceptReferencesIterator iterator = null; ResolvedConceptReferencesIteratorWrapper wrapper = null; String source = "ALL"; boolean designationOnly = false; boolean ranking = true; boolean excludeDesignation = true; try { if (target.compareTo("Name") == 0 || target.compareTo("names") == 0) { return new SimpleSearchUtils(lbSvc).search(schemes, versions, matchText, SimpleSearchUtils.BY_NAME, matchAlgorithm); } else if (target.compareTo("Code") == 0 || target.compareTo("codes") == 0) { wrapper = new CodeSearchUtils(lbSvc).searchByCode(schemes, versions, matchText, source, matchAlgorithm, ranking, maxToReturn); if (wrapper != null) { iterator = wrapper.getIterator(); } return iterator; } else if (target.compareTo("Property") == 0 || target.compareTo("properties") == 0) { wrapper = new SearchUtils(lbSvc).searchByProperties(schemes, versions, matchText, source, matchAlgorithm, excludeDesignation, ranking, maxToReturn); if (wrapper != null) { iterator = wrapper.getIterator(); } } else if (target.compareTo("Property") == 0 || target.compareTo("properties") == 0) { wrapper = new SearchUtils(lbSvc).searchByAssociations(schemes, versions, matchText, source, matchAlgorithm, designationOnly, ranking, maxToReturn); if (wrapper != null) { iterator = wrapper.getIterator(); return iterator; } } } catch (Exception ex) { ex.printStackTrace(); } return null; } /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // Advanced search /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// public ResolvedConceptReference validateAdvancedSearch( String scheme, String version, String matchText, String target, String matchAlgorithm, int maxToReturn, String source, String property_name, String rel_search_association, String rel_search_rela, String direction ) { ResolvedConceptReferencesIterator iterator = advancedSearch( scheme, version, matchText, target, matchAlgorithm, maxToReturn, source, property_name, rel_search_association, rel_search_rela, direction); if (iterator == null) return null; ResolvedConceptReference rcref = null; try { while(iterator.hasNext()) { rcref = iterator.next(); return rcref; } } catch (Exception ex) { ex.printStackTrace(); } return null; } public ResolvedConceptReferencesIterator advancedSearch( String scheme, String version, String matchText, String target, String matchAlgorithm, int maxToReturn, String source, String property_name, String rel_search_association, String rel_search_rela, String direction ) { ResolvedConceptReferencesIterator iterator = null; ResolvedConceptReferencesIteratorWrapper wrapper = null; //String source = "ALL"; boolean designationOnly = false; boolean ranking = true; boolean excludeDesignation = true; String property_type = null; try { if (target.compareTo("Name") == 0 || target.compareTo("names") == 0) { return new SimpleSearchUtils(lbSvc).search(scheme, version, matchText, SimpleSearchUtils.BY_NAME, matchAlgorithm); } else if (target.compareTo("Code") == 0 || target.compareTo("codes") == 0) { Vector schemes = new Vector(); schemes.add(scheme); Vector versions = new Vector(); versions.add(version); wrapper = new CodeSearchUtils(lbSvc).searchByCode(schemes, versions, matchText, source, matchAlgorithm, ranking, maxToReturn); if (wrapper != null) { iterator = wrapper.getIterator(); } return iterator; } else if (target.compareTo("Property") == 0 || target.compareTo("properties") == 0) { String[] property_types = null; if (property_type != null) { property_types = new String[] { property_type }; } String[] property_names = null; if (property_name != null) { property_names = new String[] { property_name }; } excludeDesignation = false; wrapper = new SearchUtils(lbSvc).searchByProperties(scheme, version, matchText, property_types, property_names, source, matchAlgorithm, excludeDesignation, ranking, maxToReturn); if (wrapper != null) { iterator = wrapper.getIterator(); } } else if (target.compareTo("Relationship") == 0 || target.compareTo("relationships") == 0) { if (rel_search_association != null && rel_search_association.compareTo("ALL") == 0) { rel_search_association = null; } if (rel_search_rela != null) { rel_search_rela = rel_search_rela.trim(); if (rel_search_rela.length() == 0) rel_search_rela = null; } int search_direction = Constants.SEARCH_SOURCE; if (direction != null && direction.compareToIgnoreCase("source") == 0) { search_direction = Constants.SEARCH_TARGET; } String[] associationsToNavigate = null; String[] association_qualifier_names = null; String[] association_qualifier_values = null; if (rel_search_association != null) { String assocName = rel_search_association; associationsToNavigate = new String[] { assocName }; } if (rel_search_rela != null) { association_qualifier_names = new String[] { "rela" }; association_qualifier_values = new String[] { rel_search_rela }; if (associationsToNavigate == null) { Vector w = new CodingSchemeDataUtils(lbSvc).getSupportedAssociationNames(scheme, null); if (w == null || w.size() == 0) { } else { associationsToNavigate = new String[w.size()]; for (int i = 0; i < w.size(); i++) { String nm = (String) w.elementAt(i); associationsToNavigate[i] = nm; } } } } wrapper = new SearchUtils(lbSvc).searchByAssociations(scheme, version, matchText, associationsToNavigate, association_qualifier_names, association_qualifier_values, search_direction, source, matchAlgorithm, excludeDesignation, ranking, maxToReturn); if (wrapper != null) { iterator = wrapper.getIterator(); return iterator; } } } catch (Exception ex) { ex.printStackTrace(); } return null; } }
37.555178
135
0.570479
2fc54df55c3d787317aaf6c008ef074b62116c3a
699
/* * 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 gr.ics.forth.rdfvisualizer.api.core.properties; import com.thoughtworks.xstream.annotations.XStreamAlias; import com.thoughtworks.xstream.annotations.XStreamImplicit; import java.util.ArrayList; import java.util.List; /** * * @author minadakn */ @XStreamAlias("xproperties") public class Xproperties { @XStreamAlias("virtuoso_host") // private String virtuoso_host; @XStreamImplicit(itemFieldName = "preference") public List preferences = new ArrayList(); }
26.884615
79
0.731044
5ad6623b574a3b15dd73e02cc42d9744b2c080be
32,013
begin_unit|revision:0.9.5;language:Java;cregit-version:0.0.1 begin_comment comment|/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ end_comment begin_package DECL|package|org.apache.camel.component.rabbitmq package|package name|org operator|. name|apache operator|. name|camel operator|. name|component operator|. name|rabbitmq package|; end_package begin_import import|import name|java operator|. name|io operator|. name|IOException import|; end_import begin_import import|import name|java operator|. name|util operator|. name|concurrent operator|. name|ExecutorService import|; end_import begin_import import|import name|java operator|. name|util operator|. name|concurrent operator|. name|RejectedExecutionException import|; end_import begin_import import|import name|java operator|. name|util operator|. name|concurrent operator|. name|ScheduledExecutorService import|; end_import begin_import import|import name|java operator|. name|util operator|. name|concurrent operator|. name|atomic operator|. name|AtomicBoolean import|; end_import begin_import import|import name|com operator|. name|rabbitmq operator|. name|client operator|. name|AMQP import|; end_import begin_import import|import name|com operator|. name|rabbitmq operator|. name|client operator|. name|Channel import|; end_import begin_import import|import name|com operator|. name|rabbitmq operator|. name|client operator|. name|Connection import|; end_import begin_import import|import name|org operator|. name|apache operator|. name|camel operator|. name|AsyncCallback import|; end_import begin_import import|import name|org operator|. name|apache operator|. name|camel operator|. name|Exchange import|; end_import begin_import import|import name|org operator|. name|apache operator|. name|camel operator|. name|FailedToCreateProducerException import|; end_import begin_import import|import name|org operator|. name|apache operator|. name|camel operator|. name|RuntimeCamelException import|; end_import begin_import import|import name|org operator|. name|apache operator|. name|camel operator|. name|component operator|. name|rabbitmq operator|. name|pool operator|. name|PoolableChannelFactory import|; end_import begin_import import|import name|org operator|. name|apache operator|. name|camel operator|. name|component operator|. name|rabbitmq operator|. name|reply operator|. name|ReplyManager import|; end_import begin_import import|import name|org operator|. name|apache operator|. name|camel operator|. name|component operator|. name|rabbitmq operator|. name|reply operator|. name|TemporaryQueueReplyManager import|; end_import begin_import import|import name|org operator|. name|apache operator|. name|camel operator|. name|support operator|. name|DefaultAsyncProducer import|; end_import begin_import import|import name|org operator|. name|apache operator|. name|camel operator|. name|support operator|. name|service operator|. name|ServiceHelper import|; end_import begin_import import|import name|org operator|. name|apache operator|. name|camel operator|. name|util operator|. name|ObjectHelper import|; end_import begin_import import|import name|org operator|. name|apache operator|. name|commons operator|. name|pool operator|. name|ObjectPool import|; end_import begin_import import|import name|org operator|. name|apache operator|. name|commons operator|. name|pool operator|. name|impl operator|. name|GenericObjectPool import|; end_import begin_class DECL|class|RabbitMQProducer specifier|public class|class name|RabbitMQProducer extends|extends name|DefaultAsyncProducer block|{ DECL|field|GENERATED_CORRELATION_ID_PREFIX specifier|private specifier|static specifier|final name|String name|GENERATED_CORRELATION_ID_PREFIX init|= literal|"Camel-" decl_stmt|; DECL|field|conn specifier|private name|Connection name|conn decl_stmt|; DECL|field|channelPool specifier|private name|ObjectPool argument_list|< name|Channel argument_list|> name|channelPool decl_stmt|; DECL|field|executorService specifier|private name|ExecutorService name|executorService decl_stmt|; DECL|field|closeTimeout specifier|private name|int name|closeTimeout init|= literal|30 operator|* literal|1000 decl_stmt|; DECL|field|started specifier|private specifier|final name|AtomicBoolean name|started init|= operator|new name|AtomicBoolean argument_list|( literal|false argument_list|) decl_stmt|; DECL|field|replyManager specifier|private name|ReplyManager name|replyManager decl_stmt|; DECL|method|RabbitMQProducer (RabbitMQEndpoint endpoint) specifier|public name|RabbitMQProducer parameter_list|( name|RabbitMQEndpoint name|endpoint parameter_list|) throws|throws name|IOException block|{ name|super argument_list|( name|endpoint argument_list|) expr_stmt|; block|} annotation|@ name|Override DECL|method|getEndpoint () specifier|public name|RabbitMQEndpoint name|getEndpoint parameter_list|() block|{ return|return operator|( name|RabbitMQEndpoint operator|) name|super operator|. name|getEndpoint argument_list|() return|; block|} comment|/** * Channel callback (similar to Spring JDBC ConnectionCallback) */ DECL|interface|ChannelCallback specifier|private interface|interface name|ChannelCallback parameter_list|< name|T parameter_list|> block|{ DECL|method|doWithChannel (Channel channel) name|T name|doWithChannel parameter_list|( name|Channel name|channel parameter_list|) throws|throws name|Exception function_decl|; block|} comment|/** * Do something with a pooled channel (similar to Spring JDBC TransactionTemplate#execute) */ DECL|method|execute (ChannelCallback<T> callback) specifier|private parameter_list|< name|T parameter_list|> name|T name|execute parameter_list|( name|ChannelCallback argument_list|< name|T argument_list|> name|callback parameter_list|) throws|throws name|Exception block|{ name|Channel name|channel decl_stmt|; try|try block|{ name|channel operator|= name|channelPool operator|. name|borrowObject argument_list|() expr_stmt|; block|} catch|catch parameter_list|( name|IllegalStateException name|e parameter_list|) block|{ comment|// Since this method is not synchronized its possible the comment|// channelPool has been cleared by another thread name|checkConnectionAndChannelPool argument_list|() expr_stmt|; name|channel operator|= name|channelPool operator|. name|borrowObject argument_list|() expr_stmt|; block|} if|if condition|( operator|! name|channel operator|. name|isOpen argument_list|() condition|) block|{ name|log operator|. name|warn argument_list|( literal|"Got a closed channel from the pool. Invalidating and borrowing a new one from the pool." argument_list|) expr_stmt|; name|channelPool operator|. name|invalidateObject argument_list|( name|channel argument_list|) expr_stmt|; comment|// Reconnect if another thread hasn't yet name|checkConnectionAndChannelPool argument_list|() expr_stmt|; name|attemptDeclaration argument_list|() expr_stmt|; name|channel operator|= name|channelPool operator|. name|borrowObject argument_list|() expr_stmt|; block|} try|try block|{ return|return name|callback operator|. name|doWithChannel argument_list|( name|channel argument_list|) return|; block|} finally|finally block|{ name|channelPool operator|. name|returnObject argument_list|( name|channel argument_list|) expr_stmt|; block|} block|} comment|/** * Open connection and initialize channel pool * @throws Exception */ DECL|method|openConnectionAndChannelPool () specifier|private specifier|synchronized name|void name|openConnectionAndChannelPool parameter_list|() throws|throws name|Exception block|{ name|log operator|. name|trace argument_list|( literal|"Creating connection..." argument_list|) expr_stmt|; name|this operator|. name|conn operator|= name|getEndpoint argument_list|() operator|. name|connect argument_list|( name|executorService argument_list|) expr_stmt|; name|log operator|. name|debug argument_list|( literal|"Created connection: {}" argument_list|, name|conn argument_list|) expr_stmt|; name|log operator|. name|trace argument_list|( literal|"Creating channel pool..." argument_list|) expr_stmt|; name|channelPool operator|= operator|new name|GenericObjectPool argument_list|<> argument_list|( operator|new name|PoolableChannelFactory argument_list|( name|this operator|. name|conn argument_list|) argument_list|, name|getEndpoint argument_list|() operator|. name|getChannelPoolMaxSize argument_list|() argument_list|, name|GenericObjectPool operator|. name|WHEN_EXHAUSTED_BLOCK argument_list|, name|getEndpoint argument_list|() operator|. name|getChannelPoolMaxWait argument_list|() argument_list|) expr_stmt|; name|attemptDeclaration argument_list|() expr_stmt|; block|} DECL|method|attemptDeclaration () specifier|private specifier|synchronized name|void name|attemptDeclaration parameter_list|() throws|throws name|Exception block|{ if|if condition|( name|getEndpoint argument_list|() operator|. name|isDeclare argument_list|() condition|) block|{ name|execute argument_list|( operator|new name|ChannelCallback argument_list|< name|Void argument_list|> argument_list|() block|{ annotation|@ name|Override specifier|public name|Void name|doWithChannel parameter_list|( name|Channel name|channel parameter_list|) throws|throws name|Exception block|{ name|getEndpoint argument_list|() operator|. name|declareExchangeAndQueue argument_list|( name|channel argument_list|) expr_stmt|; return|return literal|null return|; block|} block|} argument_list|) expr_stmt|; block|} block|} comment|/** * This will reconnect only if the connection is closed. * @throws Exception */ DECL|method|checkConnectionAndChannelPool () specifier|private specifier|synchronized name|void name|checkConnectionAndChannelPool parameter_list|() throws|throws name|Exception block|{ if|if condition|( name|this operator|. name|conn operator|== literal|null operator||| operator|! name|this operator|. name|conn operator|. name|isOpen argument_list|() condition|) block|{ name|log operator|. name|info argument_list|( literal|"Reconnecting to RabbitMQ" argument_list|) expr_stmt|; try|try block|{ name|closeConnectionAndChannel argument_list|() expr_stmt|; block|} catch|catch parameter_list|( name|Exception name|e parameter_list|) block|{ comment|// no op block|} name|openConnectionAndChannelPool argument_list|() expr_stmt|; block|} block|} annotation|@ name|Override DECL|method|doStart () specifier|protected name|void name|doStart parameter_list|() throws|throws name|Exception block|{ name|this operator|. name|executorService operator|= name|getEndpoint argument_list|() operator|. name|getCamelContext argument_list|() operator|. name|getExecutorServiceManager argument_list|() operator|. name|newSingleThreadExecutor argument_list|( name|this argument_list|, literal|"CamelRabbitMQProducer[" operator|+ name|getEndpoint argument_list|() operator|. name|getQueue argument_list|() operator|+ literal|"]" argument_list|) expr_stmt|; try|try block|{ name|openConnectionAndChannelPool argument_list|() expr_stmt|; block|} catch|catch parameter_list|( name|IOException name|e parameter_list|) block|{ name|log operator|. name|warn argument_list|( literal|"Failed to create connection. It will attempt to connect again when publishing a message." argument_list|, name|e argument_list|) expr_stmt|; block|} block|} comment|/** * If needed, close Connection and Channel * @throws IOException */ DECL|method|closeConnectionAndChannel () specifier|private specifier|synchronized name|void name|closeConnectionAndChannel parameter_list|() throws|throws name|IOException block|{ if|if condition|( name|channelPool operator|!= literal|null condition|) block|{ try|try block|{ name|channelPool operator|. name|close argument_list|() expr_stmt|; name|channelPool operator|= literal|null expr_stmt|; block|} catch|catch parameter_list|( name|Exception name|e parameter_list|) block|{ throw|throw operator|new name|IOException argument_list|( literal|"Error closing channelPool" argument_list|, name|e argument_list|) throw|; block|} block|} if|if condition|( name|conn operator|!= literal|null condition|) block|{ name|log operator|. name|debug argument_list|( literal|"Closing connection: {} with timeout: {} ms." argument_list|, name|conn argument_list|, name|closeTimeout argument_list|) expr_stmt|; name|conn operator|. name|close argument_list|( name|closeTimeout argument_list|) expr_stmt|; name|conn operator|= literal|null expr_stmt|; block|} block|} annotation|@ name|Override DECL|method|doStop () specifier|protected name|void name|doStop parameter_list|() throws|throws name|Exception block|{ name|unInitReplyManager argument_list|() expr_stmt|; name|closeConnectionAndChannel argument_list|() expr_stmt|; if|if condition|( name|executorService operator|!= literal|null condition|) block|{ name|getEndpoint argument_list|() operator|. name|getCamelContext argument_list|() operator|. name|getExecutorServiceManager argument_list|() operator|. name|shutdownNow argument_list|( name|executorService argument_list|) expr_stmt|; name|executorService operator|= literal|null expr_stmt|; block|} block|} annotation|@ name|Override DECL|method|process (Exchange exchange, AsyncCallback callback) specifier|public name|boolean name|process parameter_list|( name|Exchange name|exchange parameter_list|, name|AsyncCallback name|callback parameter_list|) block|{ comment|// deny processing if we are not started if|if condition|( operator|! name|isRunAllowed argument_list|() condition|) block|{ if|if condition|( name|exchange operator|. name|getException argument_list|() operator|== literal|null condition|) block|{ name|exchange operator|. name|setException argument_list|( operator|new name|RejectedExecutionException argument_list|() argument_list|) expr_stmt|; block|} comment|// we cannot process so invoke callback name|callback operator|. name|done argument_list|( literal|true argument_list|) expr_stmt|; return|return literal|true return|; block|} try|try block|{ if|if condition|( name|exchange operator|. name|getPattern argument_list|() operator|. name|isOutCapable argument_list|() condition|) block|{ comment|// in out requires a bit more work than in only return|return name|processInOut argument_list|( name|exchange argument_list|, name|callback argument_list|) return|; block|} else|else block|{ comment|// in only return|return name|processInOnly argument_list|( name|exchange argument_list|, name|callback argument_list|) return|; block|} block|} catch|catch parameter_list|( name|Throwable name|e parameter_list|) block|{ comment|// must catch exception to ensure callback is invoked as expected comment|// to let Camel error handling deal with this name|exchange operator|. name|setException argument_list|( name|e argument_list|) expr_stmt|; name|callback operator|. name|done argument_list|( literal|true argument_list|) expr_stmt|; return|return literal|true return|; block|} block|} DECL|method|processInOut (final Exchange exchange, final AsyncCallback callback) specifier|protected name|boolean name|processInOut parameter_list|( specifier|final name|Exchange name|exchange parameter_list|, specifier|final name|AsyncCallback name|callback parameter_list|) throws|throws name|Exception block|{ specifier|final name|org operator|. name|apache operator|. name|camel operator|. name|Message name|in init|= name|exchange operator|. name|getIn argument_list|() decl_stmt|; name|initReplyManager argument_list|() expr_stmt|; comment|// the request timeout can be overruled by a header otherwise the endpoint configured value is used specifier|final name|long name|timeout init|= name|exchange operator|. name|getIn argument_list|() operator|. name|getHeader argument_list|( name|RabbitMQConstants operator|. name|REQUEST_TIMEOUT argument_list|, name|getEndpoint argument_list|() operator|. name|getRequestTimeout argument_list|() argument_list|, name|long operator|. name|class argument_list|) decl_stmt|; specifier|final name|String name|originalCorrelationId init|= name|in operator|. name|getHeader argument_list|( name|RabbitMQConstants operator|. name|CORRELATIONID argument_list|, name|String operator|. name|class argument_list|) decl_stmt|; comment|// we append the 'Camel-' prefix to know it was generated by us name|String name|correlationId init|= name|GENERATED_CORRELATION_ID_PREFIX operator|+ name|getEndpoint argument_list|() operator|. name|getCamelContext argument_list|() operator|. name|getUuidGenerator argument_list|() operator|. name|generateUuid argument_list|() decl_stmt|; name|in operator|. name|setHeader argument_list|( name|RabbitMQConstants operator|. name|CORRELATIONID argument_list|, name|correlationId argument_list|) expr_stmt|; name|in operator|. name|setHeader argument_list|( name|RabbitMQConstants operator|. name|REPLY_TO argument_list|, name|replyManager operator|. name|getReplyTo argument_list|() argument_list|) expr_stmt|; name|String name|exchangeName init|= operator|( name|String operator|) name|exchange operator|. name|getIn argument_list|() operator|. name|getHeader argument_list|( name|RabbitMQConstants operator|. name|EXCHANGE_OVERRIDE_NAME argument_list|) decl_stmt|; comment|// If it is BridgeEndpoint we should ignore the message header of EXCHANGE_OVERRIDE_NAME if|if condition|( name|exchangeName operator|== literal|null operator||| name|getEndpoint argument_list|() operator|. name|isBridgeEndpoint argument_list|() condition|) block|{ name|exchangeName operator|= name|getEndpoint argument_list|() operator|. name|getExchangeName argument_list|() expr_stmt|; block|} else|else block|{ name|log operator|. name|debug argument_list|( literal|"Overriding header: {} detected sending message to exchange: {}" argument_list|, name|RabbitMQConstants operator|. name|EXCHANGE_OVERRIDE_NAME argument_list|, name|exchangeName argument_list|) expr_stmt|; block|} name|String name|key init|= name|in operator|. name|getHeader argument_list|( name|RabbitMQConstants operator|. name|ROUTING_KEY argument_list|, name|String operator|. name|class argument_list|) decl_stmt|; comment|// we just need to make sure RoutingKey option take effect if it is not BridgeEndpoint if|if condition|( name|key operator|== literal|null operator||| name|getEndpoint argument_list|() operator|. name|isBridgeEndpoint argument_list|() condition|) block|{ name|key operator|= name|getEndpoint argument_list|() operator|. name|getRoutingKey argument_list|() operator|== literal|null condition|? literal|"" else|: name|getEndpoint argument_list|() operator|. name|getRoutingKey argument_list|() expr_stmt|; block|} if|if condition|( name|ObjectHelper operator|. name|isEmpty argument_list|( name|key argument_list|) operator|&& name|ObjectHelper operator|. name|isEmpty argument_list|( name|exchangeName argument_list|) condition|) block|{ throw|throw operator|new name|IllegalArgumentException argument_list|( literal|"ExchangeName and RoutingKey is not provided in the endpoint: " operator|+ name|getEndpoint argument_list|() argument_list|) throw|; block|} name|log operator|. name|debug argument_list|( literal|"Registering reply for {}" argument_list|, name|correlationId argument_list|) expr_stmt|; name|replyManager operator|. name|registerReply argument_list|( name|replyManager argument_list|, name|exchange argument_list|, name|callback argument_list|, name|originalCorrelationId argument_list|, name|correlationId argument_list|, name|timeout argument_list|) expr_stmt|; try|try block|{ name|basicPublish argument_list|( name|exchange argument_list|, name|exchangeName argument_list|, name|key argument_list|) expr_stmt|; block|} catch|catch parameter_list|( name|Exception name|e parameter_list|) block|{ name|replyManager operator|. name|cancelCorrelationId argument_list|( name|correlationId argument_list|) expr_stmt|; name|exchange operator|. name|setException argument_list|( name|e argument_list|) expr_stmt|; return|return literal|true return|; block|} comment|// continue routing asynchronously (reply will be processed async when its received) return|return literal|false return|; block|} DECL|method|processInOnly (Exchange exchange, AsyncCallback callback) specifier|private name|boolean name|processInOnly parameter_list|( name|Exchange name|exchange parameter_list|, name|AsyncCallback name|callback parameter_list|) throws|throws name|Exception block|{ name|String name|exchangeName init|= operator|( name|String operator|) name|exchange operator|. name|getIn argument_list|() operator|. name|getHeader argument_list|( name|RabbitMQConstants operator|. name|EXCHANGE_OVERRIDE_NAME argument_list|) decl_stmt|; comment|// If it is BridgeEndpoint we should ignore the message header of EXCHANGE_OVERRIDE_NAME if|if condition|( name|exchangeName operator|== literal|null operator||| name|getEndpoint argument_list|() operator|. name|isBridgeEndpoint argument_list|() condition|) block|{ name|exchangeName operator|= name|getEndpoint argument_list|() operator|. name|getExchangeName argument_list|() expr_stmt|; block|} else|else block|{ name|log operator|. name|debug argument_list|( literal|"Overriding header: {} detected sending message to exchange: {}" argument_list|, name|RabbitMQConstants operator|. name|EXCHANGE_OVERRIDE_NAME argument_list|, name|exchangeName argument_list|) expr_stmt|; block|} name|String name|key init|= name|exchange operator|. name|getIn argument_list|() operator|. name|getHeader argument_list|( name|RabbitMQConstants operator|. name|ROUTING_KEY argument_list|, name|String operator|. name|class argument_list|) decl_stmt|; comment|// we just need to make sure RoutingKey option take effect if it is not BridgeEndpoint if|if condition|( name|key operator|== literal|null operator||| name|getEndpoint argument_list|() operator|. name|isBridgeEndpoint argument_list|() condition|) block|{ name|key operator|= name|getEndpoint argument_list|() operator|. name|getRoutingKey argument_list|() operator|== literal|null condition|? literal|"" else|: name|getEndpoint argument_list|() operator|. name|getRoutingKey argument_list|() expr_stmt|; block|} if|if condition|( name|ObjectHelper operator|. name|isEmpty argument_list|( name|key argument_list|) operator|&& name|ObjectHelper operator|. name|isEmpty argument_list|( name|exchangeName argument_list|) condition|) block|{ throw|throw operator|new name|IllegalArgumentException argument_list|( literal|"ExchangeName and RoutingKey is not provided in the endpoint: " operator|+ name|getEndpoint argument_list|() argument_list|) throw|; block|} name|basicPublish argument_list|( name|exchange argument_list|, name|exchangeName argument_list|, name|key argument_list|) expr_stmt|; name|callback operator|. name|done argument_list|( literal|true argument_list|) expr_stmt|; return|return literal|true return|; block|} comment|/** * Send a message borrowing a channel from the pool. */ DECL|method|basicPublish (final Exchange camelExchange, final String rabbitExchange, final String routingKey) specifier|private name|void name|basicPublish parameter_list|( specifier|final name|Exchange name|camelExchange parameter_list|, specifier|final name|String name|rabbitExchange parameter_list|, specifier|final name|String name|routingKey parameter_list|) throws|throws name|Exception block|{ if|if condition|( name|channelPool operator|== literal|null condition|) block|{ comment|// Open connection and channel lazily if another thread hasn't name|checkConnectionAndChannelPool argument_list|() expr_stmt|; block|} name|execute argument_list|( operator|new name|ChannelCallback argument_list|< name|Void argument_list|> argument_list|() block|{ annotation|@ name|Override specifier|public name|Void name|doWithChannel parameter_list|( name|Channel name|channel parameter_list|) throws|throws name|Exception block|{ name|getEndpoint argument_list|() operator|. name|publishExchangeToChannel argument_list|( name|camelExchange argument_list|, name|channel argument_list|, name|routingKey argument_list|) expr_stmt|; return|return literal|null return|; block|} block|} argument_list|) expr_stmt|; block|} DECL|method|buildProperties (Exchange exchange) name|AMQP operator|. name|BasicProperties operator|. name|Builder name|buildProperties parameter_list|( name|Exchange name|exchange parameter_list|) block|{ return|return name|getEndpoint argument_list|() operator|. name|getMessageConverter argument_list|() operator|. name|buildProperties argument_list|( name|exchange argument_list|) return|; block|} DECL|method|getCloseTimeout () specifier|public name|int name|getCloseTimeout parameter_list|() block|{ return|return name|closeTimeout return|; block|} DECL|method|setCloseTimeout (int closeTimeout) specifier|public name|void name|setCloseTimeout parameter_list|( name|int name|closeTimeout parameter_list|) block|{ name|this operator|. name|closeTimeout operator|= name|closeTimeout expr_stmt|; block|} DECL|method|initReplyManager () specifier|protected name|void name|initReplyManager parameter_list|() block|{ if|if condition|( operator|! name|started operator|. name|get argument_list|() condition|) block|{ synchronized|synchronized init|( name|this init|) block|{ if|if condition|( name|started operator|. name|get argument_list|() condition|) block|{ return|return; block|} name|log operator|. name|debug argument_list|( literal|"Starting reply manager" argument_list|) expr_stmt|; comment|// must use the classloader from the application context when creating reply manager, comment|// as it should inherit the classloader from app context and not the current which may be comment|// a different classloader name|ClassLoader name|current init|= name|Thread operator|. name|currentThread argument_list|() operator|. name|getContextClassLoader argument_list|() decl_stmt|; name|ClassLoader name|ac init|= name|getEndpoint argument_list|() operator|. name|getCamelContext argument_list|() operator|. name|getApplicationContextClassLoader argument_list|() decl_stmt|; try|try block|{ if|if condition|( name|ac operator|!= literal|null condition|) block|{ name|Thread operator|. name|currentThread argument_list|() operator|. name|setContextClassLoader argument_list|( name|ac argument_list|) expr_stmt|; block|} comment|// validate that replyToType and replyTo is configured accordingly if|if condition|( name|getEndpoint argument_list|() operator|. name|getReplyToType argument_list|() operator|!= literal|null condition|) block|{ comment|// setting temporary with a fixed replyTo is not supported if|if condition|( name|getEndpoint argument_list|() operator|. name|getReplyTo argument_list|() operator|!= literal|null operator|&& name|getEndpoint argument_list|() operator|. name|getReplyToType argument_list|() operator|. name|equals argument_list|( name|ReplyToType operator|. name|Temporary operator|. name|name argument_list|() argument_list|) condition|) block|{ throw|throw operator|new name|IllegalArgumentException argument_list|( literal|"ReplyToType " operator|+ name|ReplyToType operator|. name|Temporary operator|+ literal|" is not supported when replyTo " operator|+ name|getEndpoint argument_list|() operator|. name|getReplyTo argument_list|() operator|+ literal|" is also configured." argument_list|) throw|; block|} block|} if|if condition|( name|getEndpoint argument_list|() operator|. name|getReplyTo argument_list|() operator|!= literal|null condition|) block|{ comment|// specifying reply queues is not currently supported throw|throw operator|new name|IllegalArgumentException argument_list|( literal|"Specifying replyTo " operator|+ name|getEndpoint argument_list|() operator|. name|getReplyTo argument_list|() operator|+ literal|" is currently not supported." argument_list|) throw|; block|} else|else block|{ name|replyManager operator|= name|createReplyManager argument_list|() expr_stmt|; name|log operator|. name|debug argument_list|( literal|"Using RabbitMQReplyManager: {} to process replies from temporary queue" argument_list|, name|replyManager argument_list|) expr_stmt|; block|} block|} catch|catch parameter_list|( name|Exception name|e parameter_list|) block|{ throw|throw operator|new name|FailedToCreateProducerException argument_list|( name|getEndpoint argument_list|() argument_list|, name|e argument_list|) throw|; block|} finally|finally block|{ name|Thread operator|. name|currentThread argument_list|() operator|. name|setContextClassLoader argument_list|( name|current argument_list|) expr_stmt|; block|} name|started operator|. name|set argument_list|( literal|true argument_list|) expr_stmt|; block|} block|} block|} DECL|method|unInitReplyManager () specifier|protected name|void name|unInitReplyManager parameter_list|() block|{ try|try block|{ if|if condition|( name|replyManager operator|!= literal|null condition|) block|{ if|if condition|( name|log operator|. name|isDebugEnabled argument_list|() condition|) block|{ name|log operator|. name|debug argument_list|( literal|"Stopping RabbitMQReplyManager: {} from processing replies from: {}" argument_list|, name|replyManager argument_list|, name|getEndpoint argument_list|() operator|. name|getReplyTo argument_list|() operator|!= literal|null condition|? name|getEndpoint argument_list|() operator|. name|getReplyTo argument_list|() else|: literal|"temporary queue" argument_list|) expr_stmt|; block|} name|ServiceHelper operator|. name|stopService argument_list|( name|replyManager argument_list|) expr_stmt|; block|} block|} catch|catch parameter_list|( name|Exception name|e parameter_list|) block|{ throw|throw name|RuntimeCamelException operator|. name|wrapRuntimeCamelException argument_list|( name|e argument_list|) throw|; block|} finally|finally block|{ name|started operator|. name|set argument_list|( literal|false argument_list|) expr_stmt|; block|} block|} DECL|method|createReplyManager () specifier|protected name|ReplyManager name|createReplyManager parameter_list|() throws|throws name|Exception block|{ comment|// use a temporary queue name|ReplyManager name|replyManager init|= operator|new name|TemporaryQueueReplyManager argument_list|( name|getEndpoint argument_list|() operator|. name|getCamelContext argument_list|() argument_list|) decl_stmt|; name|replyManager operator|. name|setEndpoint argument_list|( name|getEndpoint argument_list|() argument_list|) expr_stmt|; name|String name|name init|= literal|"RabbitMQReplyManagerTimeoutChecker[" operator|+ name|getEndpoint argument_list|() operator|. name|getExchangeName argument_list|() operator|+ literal|"]" decl_stmt|; name|ScheduledExecutorService name|replyManagerExecutorService init|= name|getEndpoint argument_list|() operator|. name|getCamelContext argument_list|() operator|. name|getExecutorServiceManager argument_list|() operator|. name|newSingleThreadScheduledExecutor argument_list|( name|name argument_list|, name|name argument_list|) decl_stmt|; name|replyManager operator|. name|setScheduledExecutorService argument_list|( name|replyManagerExecutorService argument_list|) expr_stmt|; name|log operator|. name|debug argument_list|( literal|"Staring ReplyManager: {}" argument_list|, name|name argument_list|) expr_stmt|; name|ServiceHelper operator|. name|startService argument_list|( name|replyManager argument_list|) expr_stmt|; return|return name|replyManager return|; block|} block|} end_class end_unit
15.74668
810
0.806235
a9bbce5b45b7e3ae5ec6e39b829730f6bde500c2
4,314
package ceylon.language; import static ceylon.language.parseInteger_.parseInteger; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNull; import static org.junit.Assert.fail; import org.junit.Test; public class IntegerTest { private void assertParseInteger(Long expect, java.lang.String str) { Integer parsed = parseInteger(str); if (expect != null) { if (parsed == null) { fail(str + " didn't parse as an Integer"); } assertEquals("parseInteger(" + str + ")" + parsed.longValue(), expect.longValue(), parsed.longValue()); } else { assertNull("parseInteger(" + str + ") returned a result " + parsed, parsed); } } @Test public void testParseInteger() { assertParseInteger(0L, "0"); assertParseInteger(1000L, "1_000"); assertParseInteger(1000L, "1000"); assertParseInteger(1000L, "1k"); assertParseInteger(1000L, "+1_000"); assertParseInteger(1000L, "+1000"); assertParseInteger(1000L, "+1k"); assertParseInteger(-1000L, "-1_000"); assertParseInteger(-1000L, "-1000"); assertParseInteger(-1000L, "-1k"); assertParseInteger(0L, "0"); assertParseInteger(0L, "00"); assertParseInteger(0L, "0_000"); assertParseInteger(0L, "-00"); assertParseInteger(0L, "+00"); assertParseInteger(0L, "0k"); assertParseInteger(1L, "1"); assertParseInteger(1L, "01"); assertParseInteger(1L, "0_001"); assertParseInteger(1L, "+1"); assertParseInteger(1L, "+01"); assertParseInteger(1L, "+0_001"); assertParseInteger(-1L, "-1"); assertParseInteger(-1L, "-01"); assertParseInteger(-1L, "-0_001"); assertParseInteger(1000L, "1k"); assertParseInteger(1000000L, "1M"); assertParseInteger(1000000000L, "1G"); assertParseInteger(1000000000000L, "1T"); assertParseInteger(1000000000000000L, "1P"); assertParseInteger(-1000L, "-1k"); assertParseInteger(-1000000L, "-1M"); assertParseInteger(-1000000000L, "-1G"); assertParseInteger(-1000000000000L, "-1T"); assertParseInteger(-1000000000000000L, "-1P"); assertParseInteger(9223372036854775807L, "9223372036854775807"); assertParseInteger(9223372036854775807L, "9_223_372_036_854_775_807"); assertParseInteger(-9223372036854775808L, "-9223372036854775808"); assertParseInteger(-9223372036854775808L, "-9_223_372_036_854_775_808"); assertParseInteger(null, ""); assertParseInteger(null, "_"); assertParseInteger(null, "+"); assertParseInteger(null, "+_"); assertParseInteger(null, "-"); assertParseInteger(null, "-_"); assertParseInteger(null, "foo"); assertParseInteger(null, " 0"); assertParseInteger(null, "0 "); assertParseInteger(null, "0+0"); assertParseInteger(null, "0-0"); assertParseInteger(null, "0+"); assertParseInteger(null, "0-"); assertParseInteger(null, "k"); assertParseInteger(null, "k1"); assertParseInteger(null, "+k"); assertParseInteger(null, "-k"); assertParseInteger(null, "1kk"); assertParseInteger(null, "0_"); assertParseInteger(null, "_0"); assertParseInteger(null, "0_0"); assertParseInteger(null, "0_00"); assertParseInteger(null, "0_0000"); assertParseInteger(null, "0_000_0"); assertParseInteger(null, "0000_000"); assertParseInteger(null, "1_0"); assertParseInteger(null, "!_00"); assertParseInteger(null, "1_0000"); assertParseInteger(null, "1_000_0"); assertParseInteger(null, "1000_000"); assertParseInteger(null, "9223372036854775808"); assertParseInteger(null, "-9223372036854775809"); } @Test public void testConversionToInteger() { assertEquals(0.0, Integer.instance(0).getFloat(), 0.0); assertEquals(1.0, Integer.instance(1).getFloat(), 1.0); assertEquals(9007199254740991.0, Integer.instance(9007199254740991L).getFloat(), 0.0); assertEquals(-9007199254740991.0, Integer.instance(-9007199254740991L).getFloat(), 0.0); try { Integer.instance(9007199254740992L).getFloat(); fail("OverflowException expected"); } catch (OverflowException e) { // Checking that this is thrown } try { Integer.instance(-9007199254740992L).getFloat(); fail("OverflowException expected"); } catch (OverflowException e) { // Checking that this is thrown } } }
32.931298
96
0.690542
9f06476474d3480f7c03b3d8d5138c2caf740b71
3,155
/* * Copyright 2017 Red Hat, Inc. and/or its affiliates. * * 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.optaplanner.workbench.screens.solver.client.editor; import java.util.List; import javax.enterprise.context.Dependent; import javax.inject.Inject; import com.google.gwt.event.dom.client.ChangeEvent; import com.google.gwt.event.dom.client.ClickEvent; import org.jboss.errai.common.client.dom.Button; import org.jboss.errai.common.client.dom.Div; import org.jboss.errai.common.client.dom.Document; import org.jboss.errai.common.client.dom.HTMLElement; import org.jboss.errai.common.client.dom.Option; import org.jboss.errai.common.client.dom.Select; import org.jboss.errai.ui.shared.api.annotations.DataField; import org.jboss.errai.ui.shared.api.annotations.EventHandler; import org.jboss.errai.ui.shared.api.annotations.Templated; import org.uberfire.commons.data.Pair; @Dependent @Templated public class LocalSearchFormViewImpl implements LocalSearchFormView { @Inject Document document; @DataField("view") @Inject Div view; @DataField("localSearchTypeSelect") Select localSearchTypeSelect; @DataField("removeLocalSearch") @Inject Button removeLocalSearch; private LocalSearchForm presenter; @Inject public LocalSearchFormViewImpl(final Select localSearchTypeSelect) { this.localSearchTypeSelect = localSearchTypeSelect; } @Override public void setPresenter(final LocalSearchForm presenter) { this.presenter = presenter; } @EventHandler("localSearchTypeSelect") public void onLocalSearchTypeSelected(final ChangeEvent event) { presenter.onLocalSearchTypeSelected(localSearchTypeSelect.getValue()); } @EventHandler("removeLocalSearch") public void onRemoveLocalSearchClicked(final ClickEvent event) { presenter.onLocalSearchRemoved(); } @Override public void initLocalSearchTypeSelectOptions(final List<Pair<String, String>> optionPairs) { for (Pair<String, String> optionPair : optionPairs) { localSearchTypeSelect.add(createOption(optionPair)); } } @Override public void setSelectedLocalSearchType(final String localSearchType) { localSearchTypeSelect.setValue(localSearchType); } private Option createOption(final Pair<String, String> optionPair) { Option option = (Option) document.createElement("option"); option.setText(optionPair.getK1()); option.setValue(optionPair.getK2()); return option; } @Override public HTMLElement getElement() { return view; } }
31.868687
96
0.740412
e174421356a13116d4dbcbb178158ed81bf217cf
455
package com.slimgears.rxrepo.mongodb.adapter; import com.slimgears.rxrepo.encoding.MetaReader; import com.slimgears.rxrepo.encoding.MetaWriter; import org.bson.BsonReader; import org.bson.BsonWriter; class BsonAdapter { static MetaReader forReader(BsonReader reader) { return BsonReaderAdapter.forBsonReader(reader); } static MetaWriter forWriter(BsonWriter writer) { return BsonWriterAdapter.forBsonWriter(writer); } }
26.764706
55
0.771429
475d21337c76d78263bcea0ebd69c9bdded75aee
2,098
package com.culabs.nfvo.model.db; public class DBNsdVnfdKey { /** * This field was generated by MyBatis Generator. * This field corresponds to the database column templ_nsd_nfvd.template_id * * @mbggenerated Sat Apr 25 15:02:04 CST 2015 */ private String template_id; /** * This field was generated by MyBatis Generator. * This field corresponds to the database column templ_nsd_nfvd.vnfd_id * * @mbggenerated Sat Apr 25 15:02:04 CST 2015 */ private String vnfd_id; /** * This method was generated by MyBatis Generator. * This method returns the value of the database column templ_nsd_nfvd.template_id * * @return the value of templ_nsd_nfvd.template_id * * @mbggenerated Sat Apr 25 15:02:04 CST 2015 */ public String getTemplate_id() { return template_id; } /** * This method was generated by MyBatis Generator. * This method sets the value of the database column templ_nsd_nfvd.template_id * * @param template_id the value for templ_nsd_nfvd.template_id * * @mbggenerated Sat Apr 25 15:02:04 CST 2015 */ public void setTemplate_id(String template_id) { this.template_id = template_id; } /** * This method was generated by MyBatis Generator. * This method returns the value of the database column templ_nsd_nfvd.vnfd_id * * @return the value of templ_nsd_nfvd.vnfd_id * * @mbggenerated Sat Apr 25 15:02:04 CST 2015 */ public String getVnfd_id() { return vnfd_id; } /** * This method was generated by MyBatis Generator. * This method sets the value of the database column templ_nsd_nfvd.vnfd_id * * @param vnfd_id the value for templ_nsd_nfvd.vnfd_id * * @mbggenerated Sat Apr 25 15:02:04 CST 2015 */ public void setVnfd_id(String vnfd_id) { this.vnfd_id = vnfd_id; } @Override public String toString() { return "DBNsdVnfdKey [template_id=" + template_id + ", vnfd_id=" + vnfd_id + "]"; } }
27.973333
86
0.65205
e053ef67c3d2ea57e4631b96c1d25c47fcc7d88d
2,531
package europeana.rnd.dataprocessing.dates.edtf; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.io.Serializable; public class Interval extends TemporalEntity implements Serializable { Instant start; Instant end; public Interval(Instant start, Instant end) { super(); this.start = start; this.end = end; } @Override public boolean isTimeOnly() { return (start==null || start.isTimeOnly() ) && (end==null || end.isTimeOnly() ); } public Instant getStart() { return start; } public void setStart(Instant start) { this.start = start; } public Instant getEnd() { return end; } public void setEnd(Instant end) { this.end = end; } @Override public void setApproximate(boolean approx) { if(start!=null && start.date!=null) start.date.setApproximate(approx); if(end!=null && end.date!=null) end.date.setApproximate(approx); } @Override public void setUncertain(boolean uncertain) { if(start!=null && start.date!=null) start.date.setUncertain(uncertain); if(end!=null && end.date!=null) end.date.setUncertain(uncertain); } @Override public boolean isApproximate() { return (start!=null && start.isApproximate()) || (end!=null && end.isApproximate()); } @Override public boolean isUncertain() { return (start!=null && start.isUncertain()) || (end!=null && end.isUncertain()); } @Override public void switchDayMonth() { if (start!=null) start.switchDayMonth(); if (end!=null) end.switchDayMonth(); } @Override public TemporalEntity copy() { try { ByteArrayOutputStream bytes = new ByteArrayOutputStream(); ObjectOutputStream out=new ObjectOutputStream(bytes); out.writeObject(this); out.close(); ObjectInputStream in=new ObjectInputStream(new ByteArrayInputStream(bytes.toByteArray())); Interval copy=(Interval)in.readObject(); return copy; } catch (ClassNotFoundException | IOException e) { throw new RuntimeException(e.getMessage(), e); } } @Override public Instant getFirstDay() { return start==null ? null : start.getFirstDay(); } @Override public Instant getLastDay() { return end==null ? null : end.getLastDay(); } @Override public void removeTime() { if(start!=null) start.removeTime(); if(end!=null) end.removeTime(); } }
23.009091
94
0.669696
36ecfbb7556a162c7d4ad4593e1899b3697fd9a0
4,105
package com.miz.service; import java.io.File; import java.io.IOException; import com.miz.functions.MizLib; import com.miz.mizuu.R; import com.miz.mizuu.SplashScreen; import android.app.IntentService; import android.app.Notification; import android.app.NotificationManager; import android.content.Context; import android.content.Intent; import android.graphics.BitmapFactory; import android.support.v4.app.NotificationCompat; public class MoveFilesService extends IntentService { public MoveFilesService() { super("MoveFilesService"); } @Override protected void onHandleIntent(Intent intent) { // Setup up notification NotificationCompat.Builder builder = new NotificationCompat.Builder(getApplicationContext()); builder.setSmallIcon(R.drawable.refresh); builder.setTicker(getString(R.string.movingDataFiles)); builder.setContentTitle(getString(R.string.movingDataFiles)); builder.setContentText(getString(R.string.movingDataFilesDescription)); builder.setOngoing(true); builder.setOnlyAlertOnce(true); builder.setLargeIcon(BitmapFactory.decodeResource(getResources(), R.drawable.refresh)); // Build notification Notification updateNotification = builder.build(); // Show the notification NotificationManager mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE); mNotificationManager.notify(5, updateNotification); // Tell the system that this is an ongoing notification, so it shouldn't be killed startForeground(5, updateNotification); File[] listFiles; String name = ""; File oldDataFolder = MizLib.getOldDataFolder(); if (oldDataFolder.listFiles() != null) { listFiles = oldDataFolder.listFiles(); int count = listFiles.length; for (int i = 0; i < count; i++) { name = listFiles[i].getName(); if (!listFiles[i].isDirectory()) { if (name.endsWith("_bg.jpg")) { // Movie backdrop movieBackdrop(listFiles[i]); } else if (name.endsWith("_tvbg.jpg")) { // TV show backdrop tvShowBackdrop(listFiles[i]); } else if (name.contains("_S") && name.contains("E") && name.endsWith(".jpg")) { // Episode photo episodePhoto(listFiles[i]); } else { // Collection cover art movieThumb(listFiles[i]); } listFiles[i].delete(); } } } File oldMovieThumbs = new File(MizLib.getOldDataFolder() + "/movie-thumbs"); if (oldMovieThumbs.exists() && oldMovieThumbs.listFiles() != null) { listFiles = oldMovieThumbs.listFiles(); int count = listFiles.length; for (int i = 0; i < count; i++) { movieThumb(listFiles[i]); listFiles[i].delete(); } } File oldTvShowThumbs = new File(MizLib.getOldDataFolder() + "/tvshows-thumbs"); if (oldTvShowThumbs.exists() && oldTvShowThumbs.listFiles() != null) { listFiles = oldTvShowThumbs.listFiles(); int count = listFiles.length; for (int i = 0; i < count; i++) { tvShowThumb(listFiles[i]); listFiles[i].delete(); } } // Delete the old data folder MizLib.deleteRecursive(oldDataFolder); Intent i = new Intent(this, SplashScreen.class); i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP|Intent.FLAG_ACTIVITY_NEW_TASK|Intent.FLAG_ACTIVITY_CLEAR_TASK); startActivity(i); } private void movieBackdrop(File backdrop) { try { MizLib.copyFile(backdrop, new File(MizLib.getMovieBackdropFolder(this), backdrop.getName())); } catch (IOException e) {} } private void tvShowBackdrop(File backdrop) { try { MizLib.copyFile(backdrop, new File(MizLib.getTvShowBackdropFolder(this), backdrop.getName())); } catch (IOException e) {} } private void episodePhoto(File episode) { try { MizLib.copyFile(episode, new File(MizLib.getTvShowEpisodeFolder(this), episode.getName())); } catch (IOException e) {} } private void movieThumb(File thumb) { try { MizLib.copyFile(thumb, new File(MizLib.getMovieThumbFolder(this), thumb.getName())); } catch (IOException e) {} } private void tvShowThumb(File thumb) { try { MizLib.copyFile(thumb, new File(MizLib.getTvShowThumbFolder(this), thumb.getName())); } catch (IOException e) {} } }
31.821705
114
0.721803
2c8cc839f849713f1d613d94a9c80fa6ca0023bf
2,977
package org.adaptlab.chpir.android.survey.questionfragments; import android.view.View; import android.view.ViewGroup; import android.widget.EditText; import android.widget.LinearLayout; import android.widget.RadioButton; import android.widget.RadioGroup; import android.widget.RadioGroup.OnCheckedChangeListener; import org.adaptlab.chpir.android.survey.R; import org.adaptlab.chpir.android.survey.models.Response; public class SelectOneWriteOtherQuestionFragment extends SelectOneQuestionFragment { protected EditText otherText = null; @Override protected void beforeAddViewHook(ViewGroup questionComponent) { RadioButton radioButton = new RadioButton(getActivity()); otherText = new EditText(getActivity()); radioButton.setTextColor(getResources().getColorStateList(R.color.states)); radioButton.setText(R.string.other_specify); radioButton.setTypeface(getInstrument().getTypeFace( getActivity().getApplicationContext())); final int otherId = getOptions().size(); radioButton.setId(otherId); radioButton.setLayoutParams(new RadioGroup.LayoutParams( LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT)); radioButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if (mSpecialResponses != null) { mSpecialResponses.clearCheck(); } } }); getRadioGroup().setOnCheckedChangeListener(new OnCheckedChangeListener() { public void onCheckedChanged(RadioGroup group, int checkedId) { if (checkedId != -1) { if (checkedId == otherId) { otherText.setEnabled(true); } else { otherText.setEnabled(false); otherText.getText().clear(); } setResponseIndex(checkedId); } } }); for (int i = 0; i < getRadioGroup().getChildCount(); i++) { getRadioGroup().getChildAt(i).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if (mSpecialResponses != null) { mSpecialResponses.clearCheck(); } } }); } getRadioGroup().addView(radioButton, otherId); addOtherResponseView(otherText); questionComponent.addView(otherText); } @Override protected void unSetResponse() { if (getRadioGroup() != null) { getRadioGroup().clearCheck(); } if (otherText.getText().length() > 0) { otherText.setText(Response.BLANK); otherText.setEnabled(false); } setResponseTextBlank(); } }
37.2125
89
0.600941
863f18a53d1f3165ee81bb50323ee4cec6b018d7
560
package crazypants.enderio.base.block.darksteel.anvil; import net.minecraft.client.gui.GuiRepair; import net.minecraft.entity.player.InventoryPlayer; import net.minecraft.world.World; //This class is almost a complete copy / paste of GuiRepair with the container changed to ContainerDarkSteelAnvil and the //hard coded check for a max anvil level of 40 replaced to a call to EnderCoreMethods public class GuiDarkSteelAnvil extends GuiRepair { public GuiDarkSteelAnvil(InventoryPlayer inventoryIn, World worldIn) { super(inventoryIn, worldIn); } }
35
122
0.807143
a37aa712bdc1bea4223ab352600e746cd7833d95
580
package com.omnicrola.panoptes.export; import java.text.SimpleDateFormat; import java.util.Date; public class TimesheetDate { private final static SimpleDateFormat SHORT_DATE_FORMAT = new SimpleDateFormat("yyyy-MM-dd"); private final Date date; private TimesheetDate() { this.date = new Date(); } public TimesheetDate(Date date) { this.date = date; } public Date getDate() { return (Date) this.date.clone(); } @Override public String toString() { return SHORT_DATE_FORMAT.format(this.date); } }
19.333333
97
0.658621
d275ac26b99125eb26e3229c5ef2c175929e253a
1,623
package it.vige.school.dto; import java.io.Serializable; public class User implements Serializable { private static final long serialVersionUID = -6713889813860348323L; private String id; private String name; private String surname; private int income; private String room; private String school; private boolean present; public String getId() { return id; } public void setId(String id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getSurname() { return surname; } public void setSurname(String surname) { this.surname = surname; } public int getIncome() { return income; } public void setIncome(int income) { this.income = income; } public String getRoom() { return room; } public void setRoom(String room) { this.room = room; } public String getSchool() { return school; } public void setSchool(String school) { this.school = school; } public boolean isPresent() { return present; } public void setPresent(boolean present) { this.present = present; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((id == null) ? 0 : id.hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; User other = (User) obj; if (id == null) { if (other.id != null) return false; } else if (!id.equals(other.id)) return false; return true; } }
15.605769
68
0.664202
d2c889b5f431ef23c1e2a33e1c0bfc5a20c0dcf5
2,557
package cc.ryanc.halo.service; import cc.ryanc.halo.model.domain.Comment; import cc.ryanc.halo.model.domain.Post; import org.springframework.data.domain.Page; import org.springframework.data.domain.Pageable; import java.util.List; import java.util.Optional; /** * <pre> * 评论业务逻辑接口 * </pre> * * @author : HJY * @date : 2018/1/22 */ public interface CommentService { /** * 新增评论 * * @param comment comment */ void save(Comment comment); /** * 删除评论 * * @param commentId commentId * @return Optional */ Optional<Comment> remove(Long commentId); /** * 查询所有的评论,用于后台管理 * * @param status status * @param pageable pageable * @return Page */ Page<Comment> findAll(Integer status, Pageable pageable); /** * 根据评论状态查询评论 * * @param status 评论状态 * @return List */ List<Comment> findAll(Integer status); /** * 查询所有评论,不分页 * * @return List */ List<Comment> findAll(); /** * 更改评论的状态 * * @param commentId commentId * @param status status * @return Comment */ Comment updateCommentStatus(Long commentId, Integer status); /** * 根据评论编号查询评论 * * @param commentId commentId * @return Optional */ Optional<Comment> findCommentById(Long commentId); /** * 根据文章查询评论 * * @param post post * @param pageable pageable * @return Page */ Page<Comment> findCommentsByPost(Post post, Pageable pageable); /** * 根据文章和评论状态查询评论 分页 * * @param post post * @param pageable pageable * @param status status * @return Page */ Page<Comment> findCommentsByPostAndCommentStatus(Post post, Pageable pageable, Integer status); /** * 根据文章和评论状态查询评论 不分页 * * @param post post * @param status status * @return List */ List<Comment> findCommentsByPostAndCommentStatus(Post post, Integer status); /** * 根据文章和评论状态(为不查询的)查询评论 不分页 * * @param post post * @param status status * @return List */ List<Comment> findCommentsByPostAndCommentStatusNot(Post post, Integer status); /** * 查询最新的前五条评论 * * @return List */ List<Comment> findCommentsLatest(); /** * 根据评论状态查询数量 * * @param status 评论状态 * @return 评论数量 */ Integer getCountByStatus(Integer status); /** * 查询评论总数 * * @return Long */ Long getCount(); }
18.801471
99
0.575284
2d3194b08c7b8c26c80efac0769232246eec4618
2,116
package de.rdnp.chartplot.plotting; import static org.junit.Assert.assertEquals; import java.awt.image.BufferedImage; import java.io.File; import java.util.ArrayList; import java.util.Collections; import java.util.List; import org.junit.Test; import de.rdnp.chartplot.io.ConfigurationProvider; import de.rdnp.chartplot.io.FlightRadarParser; import de.rdnp.chartplot.model.GeoContent; import de.rdnp.chartplot.model.GeoPoint; public class PlottingWorkflowTest { @Test public void plotLayeredChart_ValidInput_ChartPlotted() { String sampleCsv = "csvPath,color,type,minLatitude,maxLatitude,minLongitude,maxLongitude,outputWidth\r\n" + "./exists.csv,#ff0000,points,41,43,8,9,540\r\n" + "./exists.csv,#0000ff,path"; ConfigurationProvider config = ConfigurationProvider.loadFromCsv(sampleCsv); List<String> plottedLayers = new ArrayList<>(); PlottingWorkflow workflow = mockPlotter(config, plottedLayers); workflow.plotAllLayers(); assertEquals(2, plottedLayers.size()); assertEquals("540:1453:java.awt.Color[r=255,g=0,b=0]:1",plottedLayers.get(0)); assertEquals("540:1453:java.awt.Color[r=0,g=0,b=255]:1",plottedLayers.get(1)); } private PlottingWorkflow mockPlotter(ConfigurationProvider config, final List<String> plottedLayers) { FlightRadarParser mockLayerParser = new FlightRadarParser() { @Override public GeoContent parse(String input) { return new GeoContent(Collections.singletonList(new GeoPoint(42, 8.5, "mockPoint"))); } }; return new PlottingWorkflow(config, mockLayerParser) { @Override protected ChartPlotter createPlotter() { return new ChartPlotter(config.getChartConfiguration().getOutputWidth(), config.getChartConfiguration().getOutputHeight()) { @Override public BufferedImage plotChart(Chart chart) { plottedLayers.add(this.width+":"+this.height+":"+this.plotColor+":"+chart.getChartPoints().size()); return null; } }; } @Override protected String readCsv(File layerCsv) { return layerCsv.getName(); } }; } }
34.688525
129
0.723535
82a07ff4e0cfb5f4b09f5120fc95db2aa0a42ad8
5,604
/* * Copyright 2021 Shulie Technology, Co.Ltd * Email: shulie@shulie.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, * See the License for the specific language governing permissions and * limitations under the License. */ package io.shulie.tro.cloud.biz.output.scenemanage; import java.io.Serializable; import java.math.BigDecimal; import java.util.Date; import java.util.List; import javax.validation.constraints.NotNull; import io.shulie.tro.cloud.common.bean.RuleBean; import io.shulie.tro.cloud.common.bean.TimeBean; import io.shulie.tro.cloud.common.bean.scenemanage.SceneBusinessActivityRefBean; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; import lombok.Data; /** * @ClassName SceneManageWrapperOutput * @Description * @Author qianshui * @Date 2020/4/17 下午5:55 */ @Data @ApiModel(description = "场景详情出参") public class SceneManageWrapperOutput implements Serializable { private static final long serialVersionUID = 7324148443733465383L; @ApiModelProperty(value = "压测场景ID") private Long id; @ApiModelProperty(value = "客户ID") private Long customId; @ApiModelProperty(value = "场景负责人") private Long managerId; @ApiModelProperty(value = "压测场景名称") private String pressureTestSceneName; @ApiModelProperty(value = "业务活动配置") private List<SceneBusinessActivityRefOutput> businessActivityConfig; @ApiModelProperty(value = "施压类型,0:并发,1:tps,2:自定义;不填默认为0") private Integer pressureType; @ApiModelProperty(value = "并发数量") private Integer concurrenceNum; @ApiModelProperty(value = "指定IP数") private Integer ipNum; @ApiModelProperty(value = "压测时长(秒)") private Long pressureTestSecond; @ApiModelProperty(value = "压测时长") private TimeBean pressureTestTime; @ApiModelProperty(value = "施压模式") @NotNull(message = "施压模式不能为空") private Integer pressureMode; @ApiModelProperty(value = "递增时长(秒)") private Long increasingSecond; @ApiModelProperty(value = "递增时长") private TimeBean increasingTime; @ApiModelProperty(value = "阶梯层数") private Integer step; @ApiModelProperty(value = "预计消耗流量") private BigDecimal estimateFlow; @ApiModelProperty(name = "scriptType", value = "脚本类型") private Integer scriptType; @ApiModelProperty(name = "uploadFile", value = "压测脚本/文件") private List<SceneScriptRefOutput> uploadFile; @ApiModelProperty(name = "stopCondition", value = "SLA终止配置") private List<SceneSlaRefOutput> stopCondition; @ApiModelProperty(name = "warningCondition", value = "SLA警告配置") private List<SceneSlaRefOutput> warningCondition; @ApiModelProperty(name = "status", value = "压测状态") private Integer status; @ApiModelProperty(value = "总测试时长(压测时长+预热时长)") private transient Long totalTestTime; private transient String updateTime; private transient String lastPtTime; private String features; private Integer configType; private Long scriptId; private Long businessFlowId ; private Integer scheduleInterval; private List<Long> enginePluginIds; /** * 压测类型,默认为0,默认不展示到页面 */ private Integer type; @Data public static class SceneBusinessActivityRefOutput extends SceneBusinessActivityRefBean { private static final long serialVersionUID = -6384484202725660595L; @ApiModelProperty(value = "ID") private Long id; @ApiModelProperty(value = "绑定关系") private String bindRef; @ApiModelProperty(value = "应用IDS") private String applicationIds; private Long scriptId ; private String businessFlowId; /** * 是否包含压测头 */ private Boolean hasPT; } @Data public static class SceneSlaRefOutput implements Serializable { private static final long serialVersionUID = 5117439939447730586L; @ApiModelProperty(value = "ID") private Long id; @ApiModelProperty(value = "规则名称") private String ruleName; @ApiModelProperty(value = "适用对象") private String[] businessActivity; @ApiModelProperty(value = "规则") private RuleBean rule; @ApiModelProperty(value = "状态") private Integer status; @ApiModelProperty(value = "触发事件") private String event; } @Data public static class SceneScriptRefOutput implements Serializable { private static final long serialVersionUID = -1038145286303661484L; @ApiModelProperty(value = "ID") private Long id; @ApiModelProperty(value = "文件名称") private String fileName; @ApiModelProperty(value = "文件类型") private Integer fileType; @ApiModelProperty(value = "文件大小") private String fileSize; @ApiModelProperty(value = "上传时间") private String uploadTime; @ApiModelProperty(value = "上传路径") private String uploadPath; @ApiModelProperty(value = "是否删除") private Integer isDeleted; @ApiModelProperty(value = "上传数据量") private Long uploadedData; @ApiModelProperty(value = "是否拆分") private Integer isSplit; @ApiModelProperty(value = "Topic") private String topic; } }
26.186916
93
0.691649
18f800d71df624d93bf6cbff498656073896f51c
1,534
package com.quinn.framework.component.intercept; import com.quinn.framework.api.EntityServiceInterceptor; import com.quinn.framework.api.entityflag.ParameterAble; import com.quinn.framework.api.methodflag.MethodFlag; import com.quinn.framework.api.methodflag.ReadFlag; import com.quinn.framework.component.EntityServiceInterceptorChain; import com.quinn.framework.service.ParameterAbleService; import com.quinn.util.base.model.BaseResult; import javax.annotation.Resource; import org.springframework.stereotype.Component; /** * 缓存读过滤器 * * @author Qunhua.Liao * @since 2020-03-20 */ @Component public class ParameterAbleReadEntityServiceInterceptor implements EntityServiceInterceptor { @Resource private ParameterAbleService parameterAbleService; @Override public Class<? extends MethodFlag>[] interceptBean() { return new Class[]{ParameterAble.class}; } @Override public Class<? extends MethodFlag>[] interceptMethod() { return new Class[]{ReadFlag.class}; } @Override public <T> void after(EntityServiceInterceptorChain chain, T t, BaseResult result) { Object object = result.getData(); if (object instanceof ParameterAble) { ParameterAble parameterAble = (ParameterAble) object; BaseResult<ParameterAble> res = parameterAbleService.selectByKey(parameterAble.cacheKey()); if (res.isSuccess()) { parameterAble.setCoDbParamValue(res.getData().getCoDbParamValue()); } } } }
31.306122
103
0.730769
7e4ee5a47c2d19bcb36b54e5214a39bf14a1a8ce
1,662
package me.eli.mathutils.fraction.graphing; import java.util.ArrayList; import java.util.List; public class Plane { private final int dimensions; private final List<GraphComponent> pairs; { pairs = new ArrayList<GraphComponent>(); } public Plane(int dimensions) { this.dimensions = dimensions; } public int getDimensions() { return dimensions; } public void verify(GraphComponent p) { if(p.getDimensions() != getDimensions()) throw new IllegalArgumentException("Attempted to place invalid pair in dimension"); } public boolean contains(GraphComponent p) { loop: for(GraphComponent m : pairs) { if(!m.getClass().isAssignableFrom(p.getClass()) || !p.getClass().isAssignableFrom(m.getClass())) continue; for(int i = 0; i < m.getDimensions(); i++) { if(m.getPoints()[i] != p.getPoints()[i]) continue loop; } return true; } return false; } public boolean add(GraphComponent p) { verify(p); if(contains(p)) return false; return pairs.add(p); } public boolean remove(GraphComponent p) { verify(p); loop: for(GraphComponent m : pairs) { for(int i = 0; i < m.getDimensions(); i++) { if(m.getPoints()[i] != p.getPoints()[i]) continue loop; } pairs.remove(m); return true; } return false; } public GraphComponent[] getComponents() { return pairs.toArray(new GraphComponent[pairs.size()]); } public int getComponentsAmount() { return getComponents().length; } @Override public String toString() { String s = ""; for(GraphComponent p : pairs) s += ", " + p.toString(); return getDimensions() + "DPlane:[" + s.substring(2) + "]"; } }
21.307692
99
0.657641
8b4598e87a3800c85727d763d2118a8b5d66182b
724
package com.zsun.java.nowcoder.jianzhioffer; /** * Created by zsun. * DateTime: 2019/05/19 20:35 */ /** * 一只青蛙一次可以跳上1级台阶,也可以跳上2级......它也可以跳上n级。 * 求该青蛙跳上一个n级的台阶总共有多少种跳法。 */ public class JumpFloor2 { public int jump2(int target) { if (target <= 0) { return -1; } return (int) new Power().power(2, target - 1); // if (target <= 2) { // return target; // } // // int[] jumps = new int[target + 1]; // jumps[0] = 1; // int i; // int j; // for (i = 1; i <= target; i++) { // for (j = 0; j < i; j++) { // jumps[i] += jumps[j]; // } // } // return jumps[target]; } }
20.111111
54
0.439227
2817341dff029aae8e56fd6d0ac13b5d9c3e1613
929
package no.nav.folketrygdloven.skjæringstidspunkt.regel.ytelse.k9; import no.nav.folketrygdloven.skjæringstidspunkt.regel.FastsettSkjæringstidspunktLikOpptjening; import no.nav.folketrygdloven.skjæringstidspunkt.regelmodell.AktivitetStatusModell; import no.nav.fpsak.nare.RuleService; import no.nav.fpsak.nare.evaluation.Evaluation; import no.nav.fpsak.nare.specification.Specification; /** * Fastsetter sjæringstidspunkt for beregning lik skjæringstidspunkt for opptjening for alle k9 ytelser. */ public class RegelFastsettSkjæringstidspunktK9 implements RuleService<AktivitetStatusModell> { @Override public Evaluation evaluer(AktivitetStatusModell regelmodell) { return getSpecification().evaluate(regelmodell); } @SuppressWarnings("unchecked") @Override public Specification<AktivitetStatusModell> getSpecification() { return new FastsettSkjæringstidspunktLikOpptjening(); } }
35.730769
104
0.812702
be81debee4bd6edd1993f252da2feeb4d59082f2
2,872
/* * Copyright 2018 iserge. * * 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.cesiumjs.cs.datasources.properties; import jsinterop.annotations.JsConstructor; import jsinterop.annotations.JsProperty; import jsinterop.annotations.JsType; import org.cesiumjs.cs.collections.TimeIntervalCollection; import org.cesiumjs.cs.core.Event; import org.cesiumjs.cs.core.enums.ReferenceFrame; /** * A {@link TimeIntervalCollectionProperty} which is also a * {@link PositionProperty}. * * @author Serge Silaev aka iSergio */ @JsType(isNative = true, namespace = "Cesium", name = "TimeIntervalCollectionPositionProperty") public class TimeIntervalCollectionPositionProperty extends PositionProperty { /** * Gets the interval collection. */ @JsProperty public TimeIntervalCollection intervals; /** * Gets the reference frame in which the position is defined. Default: * {@link ReferenceFrame#FIXED()} */ @JsProperty public ReferenceFrame referenceFrame; /** * A {@link TimeIntervalCollectionProperty} which is also a * {@link PositionProperty}. */ @JsConstructor public TimeIntervalCollectionPositionProperty() { } /** * A {@link TimeIntervalCollectionProperty} which is also a * {@link PositionProperty}. * * @param referenceFrame The reference frame in which the position is defined. */ @JsConstructor public TimeIntervalCollectionPositionProperty(ReferenceFrame referenceFrame) { } /** * Gets the event that is raised whenever the definition of this property * changes. The definition is considered to have changed if a call to getValue * would return a different result for the same time. */ @JsProperty public native Event definitionChanged(); /** * Gets a value indicating if this property is constant. A property is * considered constant if getValue always returns the same result for the * current definition. */ @JsProperty public native boolean isConstant(); /** * Compares this property to the provided property and returns true if they are * equal, false otherwise. * * @param other The other property. * @return true if left and right are equal, false otherwise. */ public native boolean equals(Property other); }
32.269663
95
0.71344
79160f59ca96cc34cecb91f2c3f14ba72d89d58c
1,651
package com.kerk12.smartcityassistant; import java.util.ArrayList; import java.util.List; /** * Class used for managing the order. Used in EOrder. */ public class Order { private static List<Dish> basket = new ArrayList<Dish>(); public enum PaymentMethod{CREDIT_CARD,CASH} private PaymentMethod paymentMethod; /** * Returns the final price of the order. * @return The final price. */ public static double getFinalPrice(){ double sum = 0; for (Dish d:basket){ sum +=d.getPrice(); } return sum; } public PaymentMethod getPaymentMethod() { return paymentMethod; } public void setPaymentMethod(PaymentMethod paymentMethod) { this.paymentMethod = paymentMethod; } public static List<Dish> getBasket() { return basket; } public static void setBasket(List<Dish> basket) { Order.basket = basket; } /** * Clears the order basket. */ public static void ClearOrder(){ basket = new ArrayList<Dish>(); } /** * Add a dish to the order basket. * @param dish The dish to be added. */ public static void AddDish(Dish dish){ basket.add(dish); } /** * Returns the number of items in the basket. * @return The number of items in the basket. */ public static int getOrderItemCount(){ return basket.size(); } /** * Remove an item from the basket, at the given index. * @param index The index of the item. */ public static void RemoveItem(int index){ basket.remove(index); } }
22.013333
63
0.603876
4c16f802962dbf71a290f03a2953a00e9c0c7cb7
307
package net.collaud.fablab.manager.dao; import net.collaud.fablab.manager.data.MachineTypeEO; import org.springframework.data.jpa.repository.JpaRepository; /** * * @author Gaetan Collaud <gaetancollaud@gmail.com> */ public interface MachineTypeRepository extends JpaRepository<MachineTypeEO, Long>{ }
25.583333
82
0.801303
6d571270ca82ea13440afdc79a4dcd821c2607a8
1,989
package com.yimao11.widgets.ss; import android.text.TextUtils; import java.util.regex.Pattern; /** * author : 颜洪毅 * e-mail : yhyzgn@gmail.com * time : 2018-02-02 15:29 * version: 1.0.0 * desc : 正则工具类 */ public class RegexUtils { // 数字 private final static String REG_NUMBER = "^\\d+$"; // 手机号码 private final static String REG_MOBILE = "^1[3,4,5,6,7,8,9]\\d{9}$"; // 邮箱 private final static String REG_EMAIL = "^(\\w+)(\\.\\w+)*@(\\w{2,8}\\.){1,3}\\w{2,8}$"; // 网址 private final static String REG_URL = "^https?://(\\w+)+(\\.\\w+)+(/\\w+)*/?$"; private RegexUtils() { throw new UnsupportedOperationException("Can not instantiate utils class."); } /** * 检查是否是数字 * * @param text 待检查文本 * @return 是否是数字 */ public static boolean isNumber(String text) { return match(text, REG_NUMBER); } /** * 检查是否是手机号码 * * @param text 待检查文本 * @return 是否是手机号码 */ public static boolean isMobile(String text) { return match(text, REG_MOBILE); } /** * 检查是否是邮箱地址 * * @param text 待检查文本 * @return 是否是邮箱地址 */ public static boolean isEmail(String text) { return match(text, REG_EMAIL); } /** * 检查是否是url * * @param text 待检查文本 * @return 是否是url */ public static boolean isUrl(String text) { return match(text, REG_URL); } /** * 检查字符串是否匹配 * * @param text 待检查字符串 * @param reg 匹配正则表达式 * @return 是否匹配 */ public static boolean match(String text, String reg) { return !TextUtils.isEmpty(text) && Pattern.compile(reg).matcher(text).matches(); } /** * 隐藏手机号中间四位 * * @param mobile 手机号码 * @return 结果 */ public static String hideMobile(String mobile) { if (isMobile(mobile)) { return mobile.replaceAll("(\\d{3})\\d{4}(\\d{4})", "$1****$2"); } return mobile; } }
21.619565
92
0.540473
4ead6eead92e97b7ab86ad23f377a9771c8eb3c6
903
/* * Geometry.java * * Created on 8. februar 2007, 10:00 * * To change this template, choose Tools | Template Manager * and open the template in the editor. */ package com.rometools.modules.georss.geometries; import java.io.Serializable; /** * Abstract base class for geometries. * * @author runaas */ public abstract class AbstractGeometry implements Cloneable, Serializable { /** * */ private static final long serialVersionUID = 1L; /** Creates a new instance of Geometry */ public AbstractGeometry() { } /** * Make a deep copy of the geometric object * * @return A copy of the object */ @Override public Object clone() throws CloneNotSupportedException { return super.clone(); } @Override public boolean equals(final Object obj) { return obj != null && obj.getClass() == getClass(); } }
20.066667
75
0.640089
a590e7c6279b7cdd6e5b5bb95b90201e7132b6e1
1,638
/* * Copyright Hyperledger Besu Contributors * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on * an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the * specific language governing permissions and limitations under the License. * * SPDX-License-Identifier: Apache-2.0 */ package org.hyperledger.besu.evm.internal; import static org.assertj.core.api.Assertions.assertThat; import org.hyperledger.besu.datatypes.Hash; import org.hyperledger.besu.evm.Code; import org.hyperledger.besu.evm.operation.JumpDestOperation; import org.apache.tuweni.bytes.Bytes; import org.junit.Test; public class JumpDestCacheTest { private final String op = Bytes.of(JumpDestOperation.OPCODE).toUnprefixedHexString(); @Test public void testScale() { Bytes contractBytes = Bytes.fromHexString("0xDEAD" + op + "BEEF" + op + "B0B0" + op + "C0DE" + op + "FACE"); // 3rd bit, 6th bit, 9th bit, 12th bit long[] jumpDests = {4 + 32 + 256 + 2048}; CodeScale scale = new CodeScale(); Code contractCode = new Code(contractBytes, Hash.hash(contractBytes), jumpDests); int weight = scale.weigh(contractCode.getCodeHash(), contractCode.getValidJumpDestinations()); assertThat(weight).isEqualTo(contractCode.getCodeHash().size() + jumpDests.length * 8); } }
38.093023
118
0.738706
f9b412ae1f8694d4eb7f61a289fb2ff77a112f18
1,497
/* * 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.axis2.rest; import java.util.HashMap; import java.util.Map; public class StockService { private static Map<String, Stock> map = new HashMap<String, Stock>(); public float getStockValue(String name) { float value = 0; try { value = map.get(name).getValue(); } catch (Exception e) { } return value; } public String addStock(String name, float value) { Stock stock = new Stock(); stock.setName(name); stock.setValue(value); map.put(name, stock); return name+ " stock added with value : "+value; } public void removeStock(String name) { map.remove(name); } }
28.245283
73
0.685371
bcf95d0fd0ef8f6ef03f1addae2df2592a46b419
2,715
package com.victorlh.spotify.spotifyapiclienttest.controllers; import com.neovisionaries.i18n.CountryCode; import com.victorlh.spotify.apiclient.models.objects.AudioFeaturesObject; import com.victorlh.spotify.apiclient.models.lists.ListAudiosFeaturesObject; import com.victorlh.spotify.apiclient.models.lists.ListTracksObject; import com.victorlh.spotify.apiclient.models.objects.TrackObject; import com.victorlh.spotify.apiclient.services.tracks.models.AudioFeaturesMultipleTracksRequest; import com.victorlh.spotify.apiclient.services.tracks.models.AudioFeaturesTrackRequest; import com.victorlh.spotify.apiclient.services.tracks.models.MultipleTracksRequest; import com.victorlh.spotify.apiclient.services.tracks.models.TrackRequest; import com.victorlh.spotify.spotifyapiclienttest.services.TracksService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; import java.util.List; @RestController public class TracksController { private final TracksService tracksService; @Autowired public TracksController(TracksService tracksService) { this.tracksService = tracksService; } @GetMapping({"/tracks", "/tracks/"}) public ListTracksObject getListTracks(@RequestParam("ids") List<String> ids, @RequestParam(value = "market", required = false) String market) { MultipleTracksRequest request = MultipleTracksRequest.builder().ids(ids).market(market != null ? CountryCode.getByAlpha2Code(market) : null).build(); return this.tracksService.getMultipleTracks(request); } @GetMapping("/tracks/{id}") public TrackObject getTrack(@PathVariable("id") String showId, @RequestParam(value = "market", required = false) String market) { TrackRequest request = TrackRequest.builder().id(showId).market(market != null ? CountryCode.getByAlpha2Code(market) : null).build(); return this.tracksService.getTrack(request); } @GetMapping({"/audio-features", "/audio-features/"}) public ListAudiosFeaturesObject getAudioFeaturesMultipleTracks(@RequestParam("ids") List<String> ids) { AudioFeaturesMultipleTracksRequest request = AudioFeaturesMultipleTracksRequest.builder().ids(ids).build(); return this.tracksService.getAudioFeaturesMultipleTracks(request); } @GetMapping("/audio-features/{id}") public AudioFeaturesObject getAudioFeaturesTrack(@PathVariable("id") String showId) { AudioFeaturesTrackRequest request = AudioFeaturesTrackRequest.builder().id(showId).build(); return this.tracksService.getAudioFeaturesTrack(request); } }
48.482143
151
0.818785
aeb879e9421df78404f3687b661f9ea9629d19a8
1,396
/* * 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 autoclicker; /** * * @author akash */ import java.awt.AWTException; import java.awt.Robot; import java.awt.event.MouseEvent; public class Main { /** * @param args the command line arguments * @throws java.lang.InterruptedException * @throws java.awt.AWTException */ public static void main(String[] args) throws InterruptedException, AWTException { // TODO code application logic here // Scanner scanner = new Scanner(System.in); // System.out.println("---AutoClicker---"); // System.out.print("how much clicks would you like: "); int a = 10;//scanner.nextInt(); // System.out.print("how much delay would you like: "); int del = 500;//scanner.nextInt(); // System.out.println("the program will start at 3 seconds."); Thread.sleep(3000); Robot robot = new Robot(); robot.setAutoDelay(del); for (int i = 0; i < a; i++) { robot.mousePress(MouseEvent.BUTTON1_MASK); robot.mouseRelease(MouseEvent.BUTTON1_MASK); } System.out.println("AutoClicker Finished"); } }
26.339623
86
0.600287
3b5c7056acf94cc25dbadde0762222c5f76bd0d8
2,051
package org.e792a8.acme.utils; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileWriter; import java.io.IOException; public class FileSystem { private static final int TEMP_DIR_ATTEMPTS = 4096; // https://www.cnblogs.com/longronglang/p/7458027.html public static String read(File file, int length) { // String encoding = "UTF-8"; Long filelength = file.length(); byte[] filecontent = new byte[filelength.intValue()]; try { FileInputStream in = new FileInputStream(file); in.read(filecontent); in.close(); } catch (FileNotFoundException e) { e.printStackTrace(); return null; } catch (IOException e) { e.printStackTrace(); return null; } // try { // return new String(filecontent, encoding); // } catch (UnsupportedEncodingException e) { // System.err.println("The OS does not support " + encoding); // e.printStackTrace(); // return null; // } return new String(filecontent); } // https://www.cnblogs.com/longronglang/p/7458027.html public static boolean write(File file, String content) { FileWriter writer = null; try { writer = new FileWriter(file); writer.write(content); } catch (IOException e) { e.printStackTrace(); return false; } finally { try { writer.close(); } catch (IOException e) { e.printStackTrace(); return false; } } return true; } public static File createTempDir() { File baseDir = new File(System.getProperty("java.io.tmpdir")); String baseName = System.currentTimeMillis() + "-"; for (int counter = 0; counter < TEMP_DIR_ATTEMPTS; counter++) { File tempDir = new File(baseDir, baseName + counter); if (tempDir.mkdir()) { return tempDir; } } return null; } public static void rmDir(File file) { if (file.exists()) { if (file.isDirectory()) { for (File f : file.listFiles()) { rmDir(f); } } } file.delete(); } public static String safePathName(String s) { return s.replaceAll("[/\\\\:*?.,|\"<> ]", "_"); } }
24.129412
65
0.660653
8b300ee4ec5432d7735ace1a97edfa5bf02b621b
69
package it.vige.school.web; public enum ReportType { MONTH, YEAR }
11.5
27
0.73913
426b5ee599364521821dec7f569edf713245a2c4
2,289
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.gobblin.metrics.kafka; import com.google.common.base.Optional; import com.typesafe.config.Config; import org.apache.gobblin.util.reflection.GobblinConstructorUtils; public class PusherUtils { public static final String METRICS_REPORTING_KAFKA_CONFIG_PREFIX = "metrics.reporting.kafka.config"; public static final String KAFKA_PUSHER_CLASS_NAME_KEY = "metrics.reporting.kafkaPusherClass"; public static final String KAFKA_PUSHER_CLASS_NAME_KEY_FOR_EVENTS = "metrics.reporting.events.kafkaPusherClass"; public static final String DEFAULT_KAFKA_PUSHER_CLASS_NAME = "org.apache.gobblin.metrics.kafka.KafkaPusher"; public static final String DEFAULT_KEY_VALUE_PUSHER_CLASS_NAME = "org.apache.gobblin.metrics.kafka.LoggingPusher"; /** * Create a {@link Pusher} * @param pusherClassName the {@link Pusher} class to instantiate * @param brokers brokers to connect to * @param topic the topic to write to * @param config additional configuration for configuring the {@link Pusher} * @return a {@link Pusher} */ public static Pusher getPusher(String pusherClassName, String brokers, String topic, Optional<Config> config) { try { Class<?> pusherClass = Class.forName(pusherClassName); return (Pusher) GobblinConstructorUtils.invokeLongestConstructor(pusherClass, brokers, topic, config); } catch (ReflectiveOperationException e) { throw new RuntimeException("Could not instantiate kafka pusher", e); } } }
45.78
116
0.770205
09f9a62823bb1eacfcc246786801b913dd96f14d
581
package com.zhu2chu.all.taxonomy.jdk.inherit; public class Son extends Parent { private String parent = null; public void appson() { System.out.println(this.parent); } /** * 无论如何,this都是Son的实例,只是看调用的方法在哪定义的,它所指向的变量就不一样。 * 如app方法在子类可以访问,是在父类定义的,所以this.parent指向的是父类中定义的那个变量 * 在子类中调用时,this.parent指向的则是子类中定义的变量。 * 继承并非是将父类的东西变成自己的(跟在自己内部定义一样的效果),而是实例一个父类对象,将其括起来而已 * 总之,访问修饰符控制的只是成员能被访问的位置,它原来属于谁,依旧属于谁。 */ /*public static void main(String[] args) { Son s = new Son(); s.app(); s.appson(); }*/ }
24.208333
57
0.645439
585228d00ed394e0844b0219e6e26822645eb569
1,984
/*- * Copyright (C) 2008 Erik Larsson * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package io.takari.jdkget.osx.storage.ps.container; import io.takari.jdkget.osx.storage.fs.FileSystemMajorType; import io.takari.jdkget.osx.storage.ps.PartitionSystemType; /** * @author <a href="http://www.catacombae.org/" target="_top">Erik Larsson</a> */ public abstract class ContainerHandler { /** Returns true if the container contains a file system. */ public abstract boolean containsFileSystem(); /** Returns true if the container contains a partition system. */ public abstract boolean containsPartitionSystem(); /** Returns true if the container contains another container. */ public abstract boolean containsContainer(); /** * Probes for the file system type contained within this container. Returns * null if the file system type could not be determined. */ public abstract FileSystemMajorType detectFileSystemType(); /** * Probes for the partition system type contained within this container. * Returns null if the partition system type could not be determined. */ public abstract PartitionSystemType detectPartitionSystemType(); /** * Probes for the container type contained within this container. * Returns null if the container type could not be determined. */ public abstract ContainerType detectContainerType(); }
36.740741
78
0.74748
8e66aabe2389cc32f077aaf6af82237e38e63c85
3,512
package com.dz.dao; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.util.ArrayList; import java.util.List; import com.dz.domain.Category; import com.dz.utils.DBUtil; public class CategoryDao { static Connection connection = null; static PreparedStatement pstmt = null; static ResultSet rs = null; //查找所有种类 public List<Category> findAllCategory() { List<Category> categoryList = new ArrayList<Category>(); try { connection = DBUtil.getConnection(); String sql = "select * from category"; pstmt = connection.prepareStatement(sql); rs = pstmt.executeQuery(); while (rs.next()) { Category category = new Category(); category.setCategory_id(rs.getInt("category_id")); category.setCategory_name(rs.getString("category_name")); categoryList.add(category); } return categoryList; } catch (SQLException e) { e.printStackTrace(); return categoryList; } } //增加种类 public boolean addCategory(Category category) { try { connection = DBUtil.getConnection(); String sql = "insert into category(Category_id,Category_name) values(?,?)"; pstmt = connection.prepareStatement(sql); pstmt.setInt(1,category.getCategory_id()); pstmt.setString(2, category.getCategory_name()); pstmt.execute(); return true; } catch (SQLException e) { e.printStackTrace(); return false; } } //删除种类 public boolean delCategory(Category category) { try { connection = DBUtil.getConnection(); String sql = " delete from category where category_id = ? "; pstmt = connection.prepareStatement(sql); pstmt.setInt(1, category.getCategory_id()); pstmt.executeUpdate(); return true; } catch (SQLException e) { e.printStackTrace(); return false; } } //通过种类id查找种类 public Category findCategoryByCategory_id(Integer category_id) { try { connection = DBUtil.getConnection(); String sql = " select * from category where category_id = ? "; pstmt = connection.prepareStatement(sql); pstmt.setInt(1, category_id); rs = pstmt.executeQuery(); if (rs.next()) { Category category = new Category(); category.setCategory_id(rs.getInt("category_id")); category.setCategory_name(rs.getString("category_name")); return category; } else { return null; } } catch (SQLException e) { e.printStackTrace(); return null; } } //更新种类 public boolean updateCategory(Category category) { try { connection = DBUtil.getConnection(); String sql = " update category set category_name = ? where category_id = ? "; pstmt = connection.prepareStatement(sql); pstmt.setString(1, category.getCategory_name()); pstmt.setInt(2, category.getCategory_id()); pstmt.executeUpdate(); return true; } catch (SQLException e) { e.printStackTrace(); return false; } } //按种类id升序排列查找所有种类(查找导航种类) public List<Category> findNaviCategory() { List<Category> categoryList = new ArrayList<Category>(); try { connection = DBUtil.getConnection(); String sql = "select * from category"; pstmt = connection.prepareStatement(sql); rs = pstmt.executeQuery(); while (rs.next()) { Category category = new Category(); category.setCategory_id(rs.getInt("category_id")); category.setCategory_name(rs.getString("category_name")); categoryList.add(category); } return categoryList; } catch (SQLException e) { e.printStackTrace(); return categoryList; } } }
26.406015
80
0.697323
fee11152dc94751a542c74077e8f38837e6f14e0
4,316
package dev.nick.app.screencast.tools; import android.content.ContentValues; import android.content.Context; import android.content.Intent; import android.database.Cursor; import android.net.Uri; import android.os.Build; import android.provider.MediaStore; import java.io.File; public abstract class MediaTools { public static Intent buildSharedIntent(Context context, File imageFile) { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) { Intent sharingIntent = new Intent(Intent.ACTION_SEND); sharingIntent.setType("video/mp4"); Uri uri; String filePath = imageFile.getAbsolutePath(); Cursor cursor = context.getContentResolver().query( MediaStore.Images.Media.EXTERNAL_CONTENT_URI, new String[]{MediaStore.Images.Media._ID}, MediaStore.Images.Media.DATA + "=? ", new String[]{filePath}, null); try { if (cursor != null && cursor.moveToFirst()) { int id = cursor.getInt(cursor .getColumnIndex(MediaStore.MediaColumns._ID)); Uri baseUri = Uri.parse("content://media/external/images/media"); uri = Uri.withAppendedPath(baseUri, "" + id); } else { if (imageFile.exists()) { ContentValues values = new ContentValues(); values.put(MediaStore.Images.Media.DATA, filePath); uri = context.getContentResolver().insert( MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values); } else { return null; } } sharingIntent.putExtra(Intent.EXTRA_STREAM, uri); return sharingIntent; } finally { if (cursor != null) { cursor.close(); } } } else { Intent sharingIntent = new Intent(Intent.ACTION_SEND); sharingIntent.setType("video/mp4"); Uri uri = Uri.parse("file://" + imageFile.getAbsolutePath()); sharingIntent.putExtra(Intent.EXTRA_STREAM, uri); sharingIntent.putExtra(Intent.EXTRA_SUBJECT, imageFile.getName()); return sharingIntent; } } public static Intent buildOpenIntent(Context context, File imageFile) { Intent open = new Intent(Intent.ACTION_VIEW); Uri uri; if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) { String filePath = imageFile.getAbsolutePath(); Cursor cursor = context.getContentResolver().query( MediaStore.Images.Media.EXTERNAL_CONTENT_URI, new String[]{MediaStore.Images.Media._ID}, MediaStore.Images.Media.DATA + "=? ", new String[]{filePath}, null); try { if (cursor != null && cursor.moveToFirst()) { int id = cursor.getInt(cursor .getColumnIndex(MediaStore.MediaColumns._ID)); Uri baseUri = Uri.parse("content://media/external/images/media"); uri = Uri.withAppendedPath(baseUri, "" + id); } else { if (imageFile.exists()) { ContentValues values = new ContentValues(); values.put(MediaStore.Images.Media.DATA, filePath); uri = context.getContentResolver().insert( MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values); } else { return null; } } return open; } finally { if (cursor != null) { cursor.close(); } } } else { uri = Uri.parse("file://" + imageFile.getAbsolutePath()); } open.setDataAndType(uri, "video/mp4"); open.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); return open; } }
41.104762
87
0.511121
9d8c1adc42bee97a609d9acebe32d2a8f4529ca6
7,355
package com.smartcodeltd.jenkinsci.plugins.buildmonitor.viewmodel.syntacticsugar; import com.google.common.base.Supplier; import com.google.common.collect.Lists; import com.sonyericsson.jenkins.plugins.bfa.model.FailureCauseBuildAction; import com.sonyericsson.jenkins.plugins.bfa.model.FoundFailureCause; import hudson.model.AbstractBuild; import hudson.model.AbstractProject; import hudson.model.Result; import hudson.model.User; import hudson.plugins.claim.ClaimBuildAction; import hudson.scm.ChangeLogSet; import jenkins.model.CauseOfInterruption; import jenkins.model.InterruptedBuildAction; import org.powermock.api.mockito.PowerMockito; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Calendar; import java.util.Iterator; import java.util.List; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; import static org.powermock.api.mockito.PowerMockito.mockStatic; /** * @author Jan Molak */ public class BuildStateRecipe implements Supplier<AbstractBuild<?, ?>> { private AbstractBuild<?, ?> build; public BuildStateRecipe() { build = mock(AbstractBuild.class); AbstractProject parent = mock(AbstractProject.class); when(build.getParent()).thenReturn(parent); } public BuildStateRecipe hasNumber(int number) { when(build.getNumber()).thenReturn(number); // see hudson.model.Run::getDisplayName return hasName("#" + number); } public BuildStateRecipe hasName(String name) { when(build.getDisplayName()).thenReturn(name); return this; } public BuildStateRecipe whichNumberIs(int number) { return hasNumber(number); } public BuildStateRecipe finishedWith(Result result) { when(build.getResult()).thenReturn(result); return this; } public BuildStateRecipe withChangesFrom(String... authors) { ChangeLogSet changeSet = changeSetBasedOn(entriesBy(authors)); when(build.getChangeSet()).thenReturn(changeSet); // any methods that use getChangeSet as their source of data should be called normally // (build is a partial mock in this case) when(build.getCulprits()).thenCallRealMethod(); return this; } public BuildStateRecipe succeededThanksTo(String... authors) { finishedWith(Result.SUCCESS); withChangesFrom(authors); return this; } public BuildStateRecipe wasBrokenBy(String... culprits) { finishedWith(Result.FAILURE); withChangesFrom(culprits); return this; } public BuildStateRecipe hasntStartedYet() { when(build.hasntStartedYet()).thenReturn(true); return this; } public BuildStateRecipe isStillBuilding() { when(build.isBuilding()).thenReturn(true); return this; } public BuildStateRecipe isStillUpdatingTheLog() { when(build.isLogUpdated()).thenReturn(true); return this; } public BuildStateRecipe startedAt(String time) throws Exception { long startedAt = new SimpleDateFormat("H:m:s").parse(time).getTime(); Calendar timestamp = mock(Calendar.class); when(build.getTimestamp()).thenReturn(timestamp); when(timestamp.getTimeInMillis()).thenReturn(startedAt); return this; } public BuildStateRecipe took(int minutes) throws Exception{ long duration = (long) minutes * 60 * 1000; when(build.getDuration()).thenReturn(duration); return this; } public BuildStateRecipe usuallyTakes(int minutes) throws Exception{ long duration = (long) minutes * 60 * 1000; when(build.getEstimatedDuration()).thenReturn(duration); return this; } public BuildStateRecipe wasClaimedBy(String aPotentialHero, String reason) { final ClaimBuildAction action = claimBuildAction(aPotentialHero, reason); when(build.getAction(ClaimBuildAction.class)).thenReturn(action); return this; } private ClaimBuildAction claimBuildAction(String author, String reason) { ClaimBuildAction action = mock(ClaimBuildAction.class); when(action.isClaimed()).thenReturn(true); when(action.getClaimedByName()).thenReturn(author); when(action.getReason()).thenReturn(reason); return action; } public BuildStateRecipe wasAbortedBy(String username) { User user = userCalled(username); mockStatic(User.class); PowerMockito.when(User.get(user.getId())).thenReturn(user); final InterruptedBuildAction action = interruptedBuildAction(user); when(build.getAction(InterruptedBuildAction.class)).thenReturn(action); finishedWith(Result.ABORTED); return this; } private InterruptedBuildAction interruptedBuildAction(User user) { List<CauseOfInterruption> causes = Lists.<CauseOfInterruption>newArrayList( new CauseOfInterruption.UserInterruption(user) ); InterruptedBuildAction action = mock(InterruptedBuildAction.class); when(action.getCauses()).thenReturn(causes); return action; } public BuildStateRecipe knownProblems(String... failures) { final FailureCauseBuildAction action = failureCauseBuildAction(failures); when(build.getAction(FailureCauseBuildAction.class)).thenReturn(action); return this; } private FailureCauseBuildAction failureCauseBuildAction(String... FailureNames) { FailureCauseBuildAction action = mock(FailureCauseBuildAction.class); List<FoundFailureCause> items = new ArrayList<FoundFailureCause>(); for( String name : FailureNames ) { items.add(failure(name)); } when(action.getFoundFailureCauses()).thenReturn(items); return action; } private FoundFailureCause failure(String name) { FoundFailureCause failure = mock(FoundFailureCause.class); when(failure.getDescription()).thenReturn(name); return failure; } public BuildStateRecipe and() { return this; } @Override public AbstractBuild get() { return build; } // todo: replace mock user with userCalled private List<ChangeLogSet.Entry> entriesBy(String... authors) { List<ChangeLogSet.Entry> entries = new ArrayList<ChangeLogSet.Entry>(); for (String name : authors) { User author = mock(User.class); ChangeLogSet.Entry entry = mock(ChangeLogSet.Entry.class); when(author.getFullName()).thenReturn(name); when(entry.getAuthor()).thenReturn(author); entries.add(entry); } return entries; } private User userCalled(String name) { User user = mock(User.class); when(user.getId()).thenReturn(name.toLowerCase()); when(user.getFullName()).thenReturn(name); return user; } private ChangeLogSet changeSetBasedOn(final List<ChangeLogSet.Entry> entries) { return new ChangeLogSet<ChangeLogSet.Entry>(null) { @Override public boolean isEmptySet() { return false; } public Iterator<Entry> iterator() { return entries.iterator(); } }; } }
30.143443
94
0.679402
d7986df9e9602ac71b247a0191021cedd98d9521
741
package com.solucionamos.bmcmanager.connection; import org.xml.sax.SAXException; import org.xml.sax.helpers.DefaultHandler; public class HttpsConnectionSaxHandler extends DefaultHandler { public static final int AUTH_OK = 0; private int authResult = -1; private String content = null; public int getAuthResult() { return authResult; } public void endElement(String uri, String localName, String qName) throws SAXException { if (localName.equals("authResult")) { authResult = Integer.valueOf(content); } } public void characters(char[] ch, int start, int length) { content = String.copyValueOf(ch, start, length); } }
27.444444
71
0.653171
40b4546f5f4c90fada46719839933595e9af9085
6,569
/* * File created on Mar 3, 2014 * * Copyright (c) 2014 Virginia Polytechnic Institute and State University * * 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.soulwing.credo.repository; import java.util.ArrayList; import java.util.Collection; import java.util.Date; import java.util.List; import javax.enterprise.context.ApplicationScoped; import javax.persistence.EntityManager; import javax.persistence.NoResultException; import javax.persistence.PersistenceContext; import javax.persistence.Query; import javax.persistence.TypedQuery; import org.apache.commons.lang.Validate; import org.soulwing.credo.UserGroup; import org.soulwing.credo.UserGroupMember; import org.soulwing.credo.domain.UserGroupMemberEntity; /** * A {@link UserGroupMemberRepository} that is implemented using JPA. * * @author Carl Harris */ @ApplicationScoped public class JpaUserGroupMemberRepository implements UserGroupMemberRepository { @PersistenceContext protected EntityManager entityManager; /** * {@inheritDoc} */ @Override public void add(UserGroupMember groupMember) { if (!(groupMember instanceof UserGroupMemberEntity)) { throw new IllegalArgumentException("unrecognized member type: " + groupMember.getClass().getName()); } ((UserGroupMemberEntity) groupMember).setDateCreated(new Date()); entityManager.persist(groupMember); } @Override public void remove(UserGroupMember groupMember) { entityManager.remove(groupMember); } /** * {@inheritDoc} */ @Override public boolean remove(Long id) { UserGroupMember groupMember = entityManager.find( UserGroupMemberEntity.class, id); boolean found = groupMember != null; if (found) { entityManager.remove(groupMember); } return found; } /** * {@inheritDoc} */ @Override public UserGroupMember findByGroupAndProfileId(String groupName, Long profileId) { TypedQuery<UserGroupMember> query = entityManager.createNamedQuery( "findGroupMemberWithGroupAndProfileId", UserGroupMember.class); query.setParameter("groupName", groupName); query.setParameter("profileId", profileId); try { return query.getSingleResult(); } catch (NoResultException ex) { return null; } } /** * {@inheritDoc} */ @Override public UserGroupMember findByGroupNameAndLoginName(String groupName, String loginName) { if (UserGroup.SELF_GROUP_NAME.equals(groupName)) { groupName = null; } String queryName = groupName != null ? "findGroupMemberWithGroupNameAndLoginName" : "findGroupMemberSelf"; TypedQuery<UserGroupMember> query = entityManager.createNamedQuery(queryName, UserGroupMember.class); if (groupName != null) { query.setParameter("groupName", groupName); } query.setParameter("loginName", loginName); try { return query.getSingleResult(); } catch (NoResultException ex) { return null; } } /** * {@inheritDoc} */ @Override @SuppressWarnings("unchecked") public Collection<UserGroupMember> findAllMembers(String groupName) { Validate.notEmpty(groupName, "groupName is required"); Validate.isTrue(!UserGroup.SELF_GROUP_NAME.equals(groupName)); // We can't use a typed query here because we have more than one // item in the select clause, in order to allow sorting. Query query = entityManager.createNamedQuery("findAllGroupMembers"); query.setParameter("groupName", groupName); return (Collection<UserGroupMember>) query.getResultList(); } /** * {@inheritDoc} */ @Override @SuppressWarnings("unchecked") public Collection<UserGroupMember> findByLoginName(String loginName) { // We can't use a typed query here because we have more than one // item in the select clause, in order to allow sorting. Query query = entityManager.createNamedQuery( "findGroupsAndMembersByLoginName"); query.setParameter("loginName", loginName); return (Collection<UserGroupMember>) query.getResultList(); } /** * {@inheritDoc} */ @Override @SuppressWarnings("unchecked") public Collection<UserGroupMember> findByGroupIdAndLoginName( Long groupId, String loginName) { // We can't use a typed query here because we have more than one // item in the select clause, in order to allow sorting. Query query = entityManager.createNamedQuery( "findMembersByGroupIdAndLoginName"); query.setParameter("groupId", groupId); query.setParameter("loginName", loginName); return (Collection<UserGroupMember>) query.getResultList(); } /** * {@inheritDoc} */ @Override public UserGroupMember findByGroupAndLoginName(UserGroup group, String loginName) { // We can't use a typed query here because we have more than one // item in the select clause, in order to allow sorting. Query query = null; if (group.getOwner() == null) { query = entityManager.createNamedQuery( "findGroupMemberWithGroupAndLoginName"); } else { query = entityManager.createNamedQuery( "findGroupMemberWithGroupAndLoginNameIncludingAncestors"); query.setParameter("ancestors", makeAncestorList(group)); } query.setParameter("groupId", group.getId()); query.setParameter("loginName", loginName); List results = query.getResultList(); if (results.isEmpty()) return null; if (group.getOwner() == null) { return (UserGroupMember) results.get(0); } Object[] row = (Object[]) results.get(0); return (UserGroupMember) row[0]; } private List<Long> makeAncestorList(UserGroup group) { List<Long> ancestors = new ArrayList<>(); String path = group.getAncestryPath(); String[] ids = path.length() < 2 ? new String[0] : path.substring(1, path.length() - 1).split("/"); for (String id : ids) { ancestors.add(Long.valueOf(id)); } return ancestors; } }
28.314655
75
0.698736
79e6052787f438984b1c6b7568d951a975f09f69
1,444
package com.valtech.aem.saas.core.http.request; import org.apache.http.client.methods.HttpUriRequest; import org.hamcrest.core.IsInstanceOf; import org.junit.jupiter.api.Test; import javax.servlet.http.HttpServletResponse; import java.util.List; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.core.Is.is; import static org.junit.jupiter.api.Assertions.assertThrows; class SearchRequestGetTest { @Test void testConstructor() { assertThrows(NullPointerException.class, () -> new SearchRequestGet(null)); } @Test void getRequest() { SearchRequestGet emptySearchRequestGet = new SearchRequestGet(""); assertThrows(IllegalArgumentException.class, emptySearchRequestGet::getRequest); SearchRequestGet incorrectUriSyntaxSearchRequestGet = new SearchRequestGet("$%^&*"); assertThrows(IllegalArgumentException.class, incorrectUriSyntaxSearchRequestGet::getRequest); assertThat(new SearchRequestGet("https://wknd.site/us/en/adventures/bali-surf-camp.html").getRequest(), IsInstanceOf.instanceOf( HttpUriRequest.class)); } @Test void getSuccessStatusCodes() { List<Integer> statusCodes = new SearchRequestGet("").getSuccessStatusCodes(); assertThat(statusCodes.size(), is(1)); assertThat(statusCodes.get(0), is( HttpServletResponse.SC_OK)); } }
36.1
111
0.716759