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
e9da3a7a4ae6e599f21cc2ab9a46a8ef1910a5a7
5,952
// Copyright (C) 2014 The Android Open Source Project // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package com.google.gitiles; import static com.google.common.collect.Iterables.getOnlyElement; import static java.nio.charset.StandardCharsets.UTF_8; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; import com.google.common.collect.ImmutableList; import com.google.common.io.BaseEncoding; import org.eclipse.jgit.diff.DiffEntry; import org.eclipse.jgit.diff.DiffEntry.ChangeType; import org.eclipse.jgit.diff.DiffEntry.Side; import org.eclipse.jgit.diff.Edit; import org.eclipse.jgit.diff.Edit.Type; import org.eclipse.jgit.diff.RawText; import org.eclipse.jgit.internal.storage.dfs.DfsRepository; import org.eclipse.jgit.internal.storage.dfs.DfsRepositoryDescription; import org.eclipse.jgit.internal.storage.dfs.InMemoryRepository; import org.eclipse.jgit.junit.TestRepository; import org.eclipse.jgit.patch.FileHeader; import org.eclipse.jgit.patch.Patch; import org.eclipse.jgit.revwalk.RevCommit; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; @RunWith(JUnit4.class) public class DiffServletTest { private TestRepository<DfsRepository> repo; private GitilesServlet servlet; @Before public void setUp() throws Exception { DfsRepository r = new InMemoryRepository(new DfsRepositoryDescription("test")); repo = new TestRepository<>(r); servlet = TestGitilesServlet.create(repo); } @Test public void diffFileOneParentHtml() throws Exception { String contents1 = "foo\n"; String contents2 = "foo\ncontents\n"; RevCommit c1 = repo.update("master", repo.commit().add("foo", contents1)); RevCommit c2 = repo.update("master", repo.commit().parent(c1).add("foo", contents2)); FakeHttpServletRequest req = FakeHttpServletRequest.newRequest(); req.setPathInfo("/test/+diff/" + c2.name() + "^!/foo"); FakeHttpServletResponse res = new FakeHttpServletResponse(); servlet.service(req, res); String diffHeader = String.format( "diff --git <a href=\"/b/test/+/%s/foo\">a/foo</a> <a href=\"/b/test/+/%s/foo\">b/foo</a>", c1.name(), c2.name()); String actual = res.getActualBodyString(); assertTrue(String.format("Expected diff body to contain [%s]:\n%s", diffHeader, actual), actual.contains(diffHeader)); } @Test public void diffFileNoParentsText() throws Exception { String contents = "foo\ncontents\n"; RevCommit c = repo.update("master", repo.commit().add("foo", contents)); FakeHttpServletRequest req = FakeHttpServletRequest.newRequest(); req.setPathInfo("/test/+diff/" + c.name() + "^!/foo"); req.setQueryString("format=TEXT"); FakeHttpServletResponse res = new FakeHttpServletResponse(); servlet.service(req, res); Patch p = parsePatch(res.getActualBody()); FileHeader f = getOnlyElement(p.getFiles()); assertEquals(ChangeType.ADD, f.getChangeType()); assertEquals(DiffEntry.DEV_NULL, f.getPath(Side.OLD)); assertEquals("foo", f.getPath(Side.NEW)); RawText rt = new RawText(contents.getBytes(UTF_8)); Edit e = getOnlyElement(getOnlyElement(f.getHunks()).toEditList()); assertEquals(Type.INSERT, e.getType()); assertEquals(contents, rt.getString(e.getBeginB(), e.getEndB(), false)); } @Test public void diffFileOneParentText() throws Exception { String contents1 = "foo\n"; String contents2 = "foo\ncontents\n"; RevCommit c1 = repo.update("master", repo.commit().add("foo", contents1)); RevCommit c2 = repo.update("master", repo.commit().parent(c1).add("foo", contents2)); FakeHttpServletRequest req = FakeHttpServletRequest.newRequest(); req.setPathInfo("/test/+diff/" + c2.name() + "^!/foo"); req.setQueryString("format=TEXT"); FakeHttpServletResponse res = new FakeHttpServletResponse(); servlet.service(req, res); Patch p = parsePatch(res.getActualBody()); FileHeader f = getOnlyElement(p.getFiles()); assertEquals(ChangeType.MODIFY, f.getChangeType()); assertEquals("foo", f.getPath(Side.OLD)); assertEquals("foo", f.getPath(Side.NEW)); RawText rt2 = new RawText(contents2.getBytes(UTF_8)); Edit e = getOnlyElement(getOnlyElement(f.getHunks()).toEditList()); assertEquals(Type.INSERT, e.getType()); assertEquals("contents\n", rt2.getString(e.getBeginB(), e.getEndB(), false)); } @Test public void diffDirectoryText() throws Exception { String contents = "contents\n"; RevCommit c = repo.update("master", repo.commit() .add("dir/foo", contents) .add("dir/bar", contents) .add("baz", contents)); FakeHttpServletRequest req = FakeHttpServletRequest.newRequest(); req.setPathInfo("/test/+diff/" + c.name() + "^!/dir"); req.setQueryString("format=TEXT"); FakeHttpServletResponse res = new FakeHttpServletResponse(); servlet.service(req, res); Patch p = parsePatch(res.getActualBody()); assertEquals(2, p.getFiles().size()); assertEquals("dir/bar", p.getFiles().get(0).getPath(Side.NEW)); assertEquals("dir/foo", p.getFiles().get(1).getPath(Side.NEW)); } private static Patch parsePatch(byte[] enc) { byte[] buf = BaseEncoding.base64().decode(new String(enc, UTF_8)); Patch p = new Patch(); p.parse(buf, 0, buf.length); assertEquals(ImmutableList.of(), p.getErrors()); return p; } }
39.417219
99
0.713206
31f98b109884d54e41bea124832ef2e16c8ba781
1,605
package com.appbestsmile.voicelikeme.db; import java.util.List; import io.reactivex.Single; import io.reactivex.schedulers.Schedulers; public class ScheduleItemDataSource { private ScheduleItemDao scheduleItemDao; public ScheduleItemDataSource(ScheduleItemDao scheduleItemDao) { this.scheduleItemDao = scheduleItemDao; } public Single<List<ScheduleItem>> getAllSchedules() { return Single.fromCallable(() -> scheduleItemDao.getAllSchedules()).subscribeOn(Schedulers.io()); } public Single<Boolean> insertNewScheduleItemAsync(ScheduleItem scheduleItem) { return Single.fromCallable(() -> scheduleItemDao.insertNewScheduleItem(scheduleItem) > 1) .subscribeOn(Schedulers.io()); } public long insertNewScheduleItem(ScheduleItem scheduleItem) { return scheduleItemDao.insertNewScheduleItem(scheduleItem); } public Single<Boolean> deleteRecordItemAsync(ScheduleItem scheduleItem) { return Single.fromCallable(() -> scheduleItemDao.deleteScheduleItem(scheduleItem) > 1) .subscribeOn(Schedulers.io()); } public int deleteRecordItem(ScheduleItem scheduleItem) { return scheduleItemDao.deleteScheduleItem(scheduleItem); } public Single<Boolean> updateRecordItemAsync(ScheduleItem scheduleItem) { return Single.fromCallable(() -> scheduleItemDao.updateScheduleItem(scheduleItem) > 1) .subscribeOn(Schedulers.io()); } public int updateRecordItem(ScheduleItem scheduleItem) { return scheduleItemDao.updateScheduleItem(scheduleItem); } public int getRecordingsCount() { return scheduleItemDao.getCount(); } }
32.1
101
0.771963
dacbc64a81834274d8658d5847dc337eadc2436c
1,335
package ru.stqa.training.selenium.adminLiteCart; import org.junit.Test; import org.openqa.selenium.By; import org.openqa.selenium.WebElement; import java.util.List; import static junit.framework.TestCase.assertTrue; public class Task7MoveToAllSectionsTest extends TestBase { @Test public void testMoveToAllSection() { // логин в панель администратора реализован в фикстуре в классе TestBase int numberOfWebElementsFromLeftPanel = driver.findElements(By.cssSelector("li#app-")).size(); for (int i = 0; i < numberOfWebElementsFromLeftPanel; i++) { List<WebElement> arrayOfWebElements = driver.findElements(By.cssSelector("Li#app-")); arrayOfWebElements.get(i).click(); assertTrue(isElementsPresent(By.cssSelector("h1"))); int numberOfIncludingWebElements = driver.findElements(By.cssSelector("[id ^= doc-]")).size(); if (numberOfIncludingWebElements != 0) { for (int j = 1; j < numberOfIncludingWebElements; j++) { List<WebElement> arrayOfIncludingWebElements = driver.findElements(By.cssSelector("[id ^= doc-]")); arrayOfIncludingWebElements.get(j).click(); assertTrue(isElementsPresent(By.cssSelector("h1"))); } } } } }
39.264706
119
0.655431
0e01ec595204b57ce9ef5f2dda6cd831b760d68b
2,293
/* * BSD 3-Clause License * * Copyright (c) 2022, CGATechnologies * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * 3. Neither the name of the copyright holder nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package org.cga.sctp.api.targeting.community; import org.cga.sctp.targeting.TargetedHouseholdStatus; import javax.validation.Valid; import javax.validation.constraints.NotNull; import javax.validation.constraints.Size; import java.util.List; public class TargetedHouseholdUpdateRequest { @NotNull(message = "List is required") @Size(min = 1, max = 100, message = "List must not exceed {max} items") private List<@NotNull @Valid TargetedHouseholdStatus> statuses; public List<TargetedHouseholdStatus> getStatuses() { return statuses; } public void setStatuses(List<TargetedHouseholdStatus> statuses) { this.statuses = statuses; } }
40.946429
81
0.759267
1df6a2e28e171b8f8bd589bd2bb9338bba5f5b85
620
package co.edu.sena.programming.lesson05; public class Ejemplo02 { public static void main(String[] args) { System.out.println(EstadosComputador.APAGADO); System.out.println(EstadoComputador2.APAGADO); System.out.println(EstadosComputador.APAGADO.ordinal()); System.out.println(EstadosComputador.PRENDIDO.ordinal()); System.out.println(EstadosComputador.SUSPENDIDO.ordinal()); System.out.println(EstadosComputador.APAGADO.name()); System.out.println(EstadosComputador.PRENDIDO.name()); System.out.println(EstadosComputador.SUSPENDIDO.name()); } }
41.333333
67
0.719355
7bbf7f43f2927f6542e576032825acbb5535ef5b
2,329
package seedu.address.logic.commands; import static seedu.address.logic.commands.CommandTestUtil.assertCommandFailure; import static seedu.address.logic.commands.CommandTestUtil.assertCommandSuccess; import static seedu.address.testutil.TypicalAssignments.getTypicalProductiveNus; import static seedu.address.testutil.TypicalIndexes.INDEX_FIRST_ASSIGNMENT; import java.util.ArrayList; import java.util.List; import org.junit.jupiter.api.Test; import seedu.address.commons.core.Messages; import seedu.address.commons.core.index.Index; import seedu.address.logic.commands.exceptions.CommandException; import seedu.address.model.Model; import seedu.address.model.ModelManager; import seedu.address.model.UserPrefs; public class UndoCommandTest { private Model model = new ModelManager(getTypicalProductiveNus(), new UserPrefs(), null); @Test public void execute_noPreviousCommand_fail() { assertCommandFailure(new UndoCommand("undo"), model, UndoCommand.MESSAGE_UNDO_FAIL); } @Test public void execute_haveSuccessfulPreviousCommand_success() throws CommandException { List<Index> indexesToMarkDone = new ArrayList<>(); indexesToMarkDone.add(INDEX_FIRST_ASSIGNMENT); DoneCommand doneCommand = new DoneCommand(indexesToMarkDone); model.preUpdateModel(); doneCommand.execute(model); String expectedMessage = UndoCommand.MESSAGE_UNDO_SUCCESS; Model expectedModel = new ModelManager(getTypicalProductiveNus(), new UserPrefs(), null); UndoCommand undoCommand = new UndoCommand("undo"); assertCommandSuccess(undoCommand, model, expectedMessage, expectedModel); } @Test public void execute_haveUnsuccessfulPreviousCommand_fail() { UndoneCommand undoneCommand = new UndoneCommand(INDEX_FIRST_ASSIGNMENT); try { undoneCommand.execute(model); } catch (CommandException ignored) { UndoCommand undoCommand = new UndoCommand("undo"); assertCommandFailure(undoCommand, model, UndoCommand.MESSAGE_UNDO_FAIL); } } @Test public void execute_wrongCommandFormat_fail() { assertCommandFailure(new UndoCommand("undo 3"), model, String.format(Messages.MESSAGE_INVALID_COMMAND_FORMAT, UndoCommand.MESSAGE_USAGE)); } }
36.968254
99
0.753542
b72e0951308301d2ab37bc19928f925d310d87d4
5,268
package com.zzx.cicd.cdk; import software.amazon.awscdk.core.Aws; import software.amazon.awscdk.core.Construct; import software.amazon.awscdk.core.SecretValue; import software.amazon.awscdk.core.SecretsManagerSecretOptions; import software.amazon.awscdk.core.Stack; import software.amazon.awscdk.core.StackProps; import software.amazon.awscdk.services.codebuild.BuildEnvironment; import software.amazon.awscdk.services.codebuild.BuildEnvironmentVariable; import software.amazon.awscdk.services.codebuild.BuildEnvironmentVariableType; import software.amazon.awscdk.services.codebuild.BuildSpec; import software.amazon.awscdk.services.codebuild.ComputeType; import software.amazon.awscdk.services.codebuild.LinuxBuildImage; import software.amazon.awscdk.services.codebuild.PipelineProject; import software.amazon.awscdk.services.codebuild.PipelineProjectProps; import software.amazon.awscdk.services.codepipeline.Artifact; import software.amazon.awscdk.services.codepipeline.IAction; import software.amazon.awscdk.services.codepipeline.Pipeline; import software.amazon.awscdk.services.codepipeline.PipelineProps; import software.amazon.awscdk.services.codepipeline.StageProps; import software.amazon.awscdk.services.codepipeline.actions.CodeBuildAction; import software.amazon.awscdk.services.codepipeline.actions.CodeBuildActionProps; import software.amazon.awscdk.services.codepipeline.actions.GitHubSourceAction; import software.amazon.awscdk.services.codepipeline.actions.GitHubSourceActionProps; import software.amazon.awscdk.services.iam.AccountPrincipal; import software.amazon.awscdk.services.iam.ManagedPolicy; import software.amazon.awscdk.services.iam.Role; import software.amazon.awscdk.services.iam.RoleProps; import software.amazon.awscdk.services.iam.ServicePrincipal; import java.util.Arrays; import java.util.Collections; import java.util.HashMap; public class CicdStack extends Stack { public CicdStack(Construct parent, String id, StackProps props) { super(parent, id, props); init(); } private void init() { createCodeBuildProject(); } // CI/CD system for deploying the project to the target domain private void createCodeBuildProject() { IAction githubSourceAction = new GitHubSourceAction(GitHubSourceActionProps.builder() .actionName("Source") .owner("jokyjang") .repo("ZhangZhaoxiBe") .branch("master") .oauthToken(SecretValue.secretsManager("jokyjang.github.oauth", SecretsManagerSecretOptions.builder() .jsonField("zhang.zhaoxi.be.oauth.token") .build())) .output(Artifact.artifact("Source")) .build()); StageProps sourceStage = StageProps.builder() .stageName("Source") .actions(Collections.singletonList(githubSourceAction)) .build(); // Love Project actions and stage. IAction codeBuildAction = new CodeBuildAction(CodeBuildActionProps.builder() .actionName("LoveBuild") .input(Artifact.artifact("Source")) .project(new PipelineProject(this, "LoveProject", PipelineProjectProps.builder() .buildSpec(BuildSpec.fromSourceFilename("./love/buildspec.yml")) .projectName("LoveProjectBuild") .environment(BuildEnvironment.builder() .computeType(ComputeType.SMALL) .buildImage(LinuxBuildImage.STANDARD_2_0) .environmentVariables(new HashMap<String, BuildEnvironmentVariable>() {{ put("LOVA_BUCKET_NAME", BuildEnvironmentVariable.builder() .type(BuildEnvironmentVariableType.PLAINTEXT) // TODO Move these values to CloudFormation exported value .value("love.zhangzhaoxi.be") .build() ); }}) .build()) .role(new Role(this, "LoveProjectRole", RoleProps.builder() .roleName("LoveProjectRole") .assumedBy(new ServicePrincipal("codebuild.amazonaws.com")) .managedPolicies(Collections.singletonList(ManagedPolicy.fromAwsManagedPolicyName("AmazonS3FullAccess"))) .build())) .build())) .role(new Role(this, "LoveBuildActionRole", RoleProps.builder() .roleName("LoveBuildActionRole") .assumedBy(new AccountPrincipal(Aws.ACCOUNT_ID)) .build())) .build()); StageProps buildStage = StageProps.builder() .stageName("Build") .actions(Collections.singletonList(codeBuildAction)) .build(); new Pipeline(this, "ZhangZhaoxiBePipeline", PipelineProps.builder() .pipelineName("ZhangZhaoxiBe") .stages(Arrays.asList(sourceStage, buildStage)) .role(new Role(this, "ZhangZhaoxiBePipelineRole", RoleProps.builder() .roleName("ZhangZhaoxiBePipelineRole") .assumedBy(new ServicePrincipal("codepipeline.amazonaws.com")) .build())) .build() ); } }
47.459459
125
0.679954
d6da1a256c143de85968d0c1ed22e848b9281ab9
565
package com.nirvanaxp.types.entities.user; import com.nirvanaxp.types.entities.POSNirvanaBaseClass_; import javax.annotation.Generated; import javax.persistence.metamodel.SingularAttribute; import javax.persistence.metamodel.StaticMetamodel; @Generated(value="Dali", date="2019-03-22T13:53:23.373+0530") @StaticMetamodel(UsersToLocation.class) public class UsersToLocation_ extends POSNirvanaBaseClass_ { public static volatile SingularAttribute<UsersToLocation, String> locationsId; public static volatile SingularAttribute<UsersToLocation, String> usersId; }
40.357143
79
0.846018
fd115feff0f001e0c57c4f360253a76f05c01a2d
14,366
package org.fcrepo.server.security.xacml.pdp.data; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.net.URI; import java.net.URISyntaxException; import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Set; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.ParserConfigurationException; import com.sun.xacml.EvaluationCtx; import com.sun.xacml.attr.AttributeDesignator; import com.sun.xacml.attr.AttributeValue; import com.sun.xacml.attr.BagAttribute; import com.sun.xacml.cond.EvaluationResult; import org.w3c.dom.Document; import org.w3c.dom.Node; import org.w3c.dom.NodeList; import org.xml.sax.SAXException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.fcrepo.server.security.xacml.pdp.MelcoePDP; import org.fcrepo.server.security.xacml.util.AttributeBean; /** * Base abstract class for all PolicyIndex implementations. * * Gets the index configuration common to all implementations. * * @author Stephen Bayliss * @version $Id$ */ public abstract class PolicyIndexBase implements PolicyIndex { // used in testing - indicates if the implementation returns indexed results // or if false indicates that all policies are returned irrespective of the request public boolean indexed = true; protected Map<String, Map<String, String>> indexMap = null; private static final Logger log = LoggerFactory.getLogger(PolicyIndexBase.class.getName()); protected static final String METADATA_POLICY_NS = "metadata"; // FIXME: migrate to Spring-based configuration // this path is relative to the pdp directory private static final String CONFIG_FILE = "/conf/config-policy-index.xml"; // xacml namespaces and prefixes public static final Map<String, String> namespaces = new HashMap<String, String>(); static { namespaces.put("p", XACML20_POLICY_NS); namespaces.put("m", METADATA_POLICY_NS); // appears to dbxml specific and probably not used } protected PolicyIndexBase() throws PolicyIndexException { initConfig(); } /** * read index configuration from config file * configuration is a list of policy target attributes to index * @throws PolicyIndexException */ private void initConfig() throws PolicyIndexException { String home = MelcoePDP.PDP_HOME.getAbsolutePath(); String filename = home + CONFIG_FILE; File f = new File(filename); log.info("Loading config file: " + f.getAbsolutePath()); Document doc = null; try { DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); DocumentBuilder docBuilder = factory.newDocumentBuilder(); doc = docBuilder.parse(new FileInputStream(f)); } catch (ParserConfigurationException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (FileNotFoundException e) { throw new PolicyIndexException("Configuration file " + filename + " not found.", e); } catch (SAXException e) { throw new PolicyIndexException("Error parsing config file + " + filename, e); } catch (IOException e) { throw new PolicyIndexException("Error reading config file " + filename, e); } NodeList nodes = null; // get index map information String[] indexMapElements = {"subjectAttributes", "resourceAttributes", "actionAttributes", "environmentAttributes"}; indexMap = new HashMap<String, Map<String, String>>(); for (String s : indexMapElements) { indexMap.put(s, new HashMap<String, String>()); } nodes = doc.getElementsByTagName("indexMap").item(0) .getChildNodes(); for (int x = 0; x < nodes.getLength(); x++) { Node node = nodes.item(x); if (node.getNodeType() == Node.ELEMENT_NODE) { if (log.isDebugEnabled()) { log.debug("Node name: " + node.getNodeName()); } NodeList attrs = node.getChildNodes(); for (int y = 0; y < attrs.getLength(); y++) { Node attr = attrs.item(y); if (attr.getNodeType() == Node.ELEMENT_NODE) { String name = attr.getAttributes().getNamedItem("name") .getNodeValue(); String type = attr.getAttributes().getNamedItem("type") .getNodeValue(); indexMap.get(node.getNodeName()).put(name, type); } } } } } /** * This method extracts the attributes listed in the indexMap from the given * evaluation context. * * @param eval * the Evaluation Context from which to extract Attributes * @return a Map of Attributes for each category (Subject, Resource, Action, * Environment) * @throws URISyntaxException */ @SuppressWarnings("unchecked") protected Map<String, Set<AttributeBean>> getAttributeMap(EvaluationCtx eval) throws URISyntaxException { URI defaultCategoryURI = new URI(AttributeDesignator.SUBJECT_CATEGORY_DEFAULT); Map<String, String> im = null; Map<String, Set<AttributeBean>> attributeMap = new HashMap<String, Set<AttributeBean>>(); Map<String, AttributeBean> attributeBeans = null; im = indexMap.get("subjectAttributes"); attributeBeans = new HashMap<String, AttributeBean>(); for (String attributeId : im.keySet()) { EvaluationResult result = eval.getSubjectAttribute(new URI(im.get(attributeId)), new URI(attributeId), defaultCategoryURI); if (result.getStatus() == null && !result.indeterminate()) { AttributeValue attr = result.getAttributeValue(); if (attr.returnsBag()) { Iterator<AttributeValue> i = ((BagAttribute) attr).iterator(); if (i.hasNext()) { while (i.hasNext()) { AttributeValue value = i.next(); String attributeType = im.get(attributeId); AttributeBean ab = attributeBeans.get(attributeId); if (ab == null) { ab = new AttributeBean(); ab.setId(attributeId); ab.setType(attributeType); attributeBeans.put(attributeId, ab); } ab.addValue(value.encode()); } } } } } attributeMap.put("subjectAttributes", new HashSet(attributeBeans .values())); im = indexMap.get("resourceAttributes"); attributeBeans = new HashMap<String, AttributeBean>(); for (String attributeId : im.keySet()) { EvaluationResult result = eval.getResourceAttribute(new URI(im.get(attributeId)), new URI(attributeId), null); if (result.getStatus() == null && !result.indeterminate()) { AttributeValue attr = result.getAttributeValue(); if (attr.returnsBag()) { Iterator<AttributeValue> i = ((BagAttribute) attr).iterator(); if (i.hasNext()) { while (i.hasNext()) { AttributeValue value = i.next(); String attributeType = im.get(attributeId); AttributeBean ab = attributeBeans.get(attributeId); if (ab == null) { ab = new AttributeBean(); ab.setId(attributeId); ab.setType(attributeType); attributeBeans.put(attributeId, ab); } if (attributeId.equals(XACML_RESOURCE_ID) && value.encode().startsWith("/")) { String[] components = makeComponents(value.encode()); if (components != null && components.length > 0) { for (String c : components) { ab.addValue(c); } } else { ab.addValue(value.encode()); } } else { ab.addValue(value.encode()); } } } } } } attributeMap.put("resourceAttributes", new HashSet(attributeBeans .values())); im = indexMap.get("actionAttributes"); attributeBeans = new HashMap<String, AttributeBean>(); for (String attributeId : im.keySet()) { EvaluationResult result = eval.getActionAttribute(new URI(im.get(attributeId)), new URI(attributeId), null); if (result.getStatus() == null && !result.indeterminate()) { AttributeValue attr = result.getAttributeValue(); if (attr.returnsBag()) { Iterator<AttributeValue> i = ((BagAttribute) attr).iterator(); if (i.hasNext()) { while (i.hasNext()) { AttributeValue value = i.next(); String attributeType = im.get(attributeId); AttributeBean ab = attributeBeans.get(attributeId); if (ab == null) { ab = new AttributeBean(); ab.setId(attributeId); ab.setType(attributeType); attributeBeans.put(attributeId, ab); } ab.addValue(value.encode()); } } } } } attributeMap.put("actionAttributes", new HashSet(attributeBeans .values())); im = indexMap.get("environmentAttributes"); attributeBeans = new HashMap<String, AttributeBean>(); for (String attributeId : im.keySet()) { URI imAttrId = new URI(im.get(attributeId)); URI attrId = new URI(attributeId); EvaluationResult result = eval.getEnvironmentAttribute(imAttrId, attrId, null); if (result.getStatus() == null && !result.indeterminate()) { AttributeValue attr = result.getAttributeValue(); if (attr.returnsBag()) { Iterator<AttributeValue> i = ((BagAttribute) attr).iterator(); if (i.hasNext()) { while (i.hasNext()) { AttributeValue value = i.next(); String attributeType = im.get(attributeId); AttributeBean ab = attributeBeans.get(attributeId); if (ab == null) { ab = new AttributeBean(); ab.setId(attributeId); ab.setType(attributeType); attributeBeans.put(attributeId, ab); } ab.addValue(value.encode()); } } } } } attributeMap.put("environmentAttributes", new HashSet(attributeBeans .values())); return attributeMap; } /** * Splits a XACML hierarchical resource-id value into a set of resource-id values * that can be matched against a policy. * * Eg an incoming request for /res1/res2/res3/.* should match * /res1/.* * /res1/res2/.* * /res1/res2/res3/.* * * in policies. * * @param resourceId XACML hierarchical resource-id value * @return array of individual resource-id values that can be used to match against policies */ protected static String[] makeComponents(String resourceId) { if (resourceId == null || resourceId.equals("") || !resourceId.startsWith("/")) { return null; } List<String> components = new ArrayList<String>(); String[] parts = resourceId.split("\\/"); for (int x = 1; x < parts.length; x++) { StringBuilder sb = new StringBuilder(); for (int y = 0; y < x; y++) { sb.append("/"); sb.append(parts[y + 1]); } components.add(sb.toString()); if (x != parts.length - 1) { components.add(sb.toString() + "/.*"); } else { components.add(sb.toString() + "$"); } } return components.toArray(new String[components.size()]); } }
38.106101
109
0.505429
a93fb7e07524dce858799b51019b8dc81b2dc6fe
1,267
package org.kendar.servers.utils.models; public class RegexpData { private String regexp; private String matcherString; private boolean caseInsensitive; private boolean literal; private boolean unicodeCase; private boolean multiline; public String getRegexp() { return regexp; } public void setRegexp(String regexp) { this.regexp = regexp; } public String getMatcherString() { return matcherString; } public void setMatcherString(String matcherString) { this.matcherString = matcherString; } public boolean isCaseInsensitive() { return caseInsensitive; } public void setCaseInsensitive(boolean caseInsensitive) { this.caseInsensitive = caseInsensitive; } public boolean isLiteral() { return literal; } public void setLiteral(boolean literal) { this.literal = literal; } public boolean isUnicodeCase() { return unicodeCase; } public void setUnicodeCase(boolean unicodeCase) { this.unicodeCase = unicodeCase; } public boolean isMultiline() { return multiline; } public void setMultiline(boolean multiline) { this.multiline = multiline; } }
21.474576
61
0.656669
1064586880f0b44a0ae1aa049df88dbaee309de1
17,904
package com.github.yellowstonegames; import com.badlogic.gdx.Application; import com.badlogic.gdx.ApplicationAdapter; import com.badlogic.gdx.Gdx; import com.badlogic.gdx.InputAdapter; import com.badlogic.gdx.graphics.Camera; import com.badlogic.gdx.graphics.GL20; import com.badlogic.gdx.graphics.g2d.SpriteBatch; import com.badlogic.gdx.math.MathUtils; import com.badlogic.gdx.math.Vector2; import com.badlogic.gdx.utils.TimeUtils; import com.github.tommyettinger.ds.ObjectList; import com.github.tommyettinger.ds.support.EnhancedRandom; import com.github.tommyettinger.ds.support.FourWheelRandom; import com.github.tommyettinger.textra.Font; import com.github.yellowstonegames.core.ArrayTools; import com.github.yellowstonegames.core.TrigTools; import com.github.yellowstonegames.glyph.GlidingGlyph; import com.github.yellowstonegames.glyph.GlyphMap; import com.github.yellowstonegames.glyph.KnownFonts; import com.github.yellowstonegames.grid.*; import com.github.yellowstonegames.path.DijkstraMap; import com.github.yellowstonegames.place.DungeonProcessor; import com.github.yellowstonegames.smooth.CoordGlider; import com.github.yellowstonegames.smooth.Director; import com.github.yellowstonegames.smooth.VectorSequenceGlider; import static com.badlogic.gdx.Gdx.input; import static com.badlogic.gdx.Input.Keys.*; import static com.github.yellowstonegames.core.DescriptiveColor.*; import static com.github.yellowstonegames.core.MathTools.swayRandomized; public class DungeonDemo extends ApplicationAdapter { private SpriteBatch batch; private GlyphMap gm; private DungeonProcessor dungeonProcessor; private char[][] bare, dungeon, prunedDungeon; private float[][] res, light; private Region seen, inView, blockage; private final Noise waves = new Noise(123, 0.5f, Noise.FOAM, 1); private Director<GlidingGlyph> director, directorSmall; private ObjectList<GlidingGlyph> glyphs; private DijkstraMap playerToCursor; private final ObjectList<Coord> toCursor = new ObjectList<>(100); private final ObjectList<Coord> awaitedMoves = new ObjectList<>(50); private Coord cursor = Coord.get(-1, -1); private final Vector2 pos = new Vector2(); public static final int GRID_WIDTH = 100; public static final int GRID_HEIGHT = 32; private static final int DEEP_OKLAB = describeOklab("dark dull cobalt"); private static final int SHALLOW_OKLAB = describeOklab("dull denim"); private static final int STONE_OKLAB = describeOklab("darkmost gray dullest bronze"); private static final long deepText = toRGBA8888(offsetLightness(DEEP_OKLAB)); private static final long shallowText = toRGBA8888(offsetLightness(SHALLOW_OKLAB)); private static final long stoneText = toRGBA8888(describeOklab("gray dullmost butter bronze")); @Override public void create() { Gdx.app.setLogLevel(Application.LOG_INFO); long seed = TimeUtils.millis() >>> 21; Gdx.app.log("SEED", "Initial seed is " + seed); EnhancedRandom random = new FourWheelRandom(seed); batch = new SpriteBatch(); // Font font = KnownFonts.getInconsolataLGC().scaleTo(20f, 20f); // font = KnownFonts.getCascadiaMono().scale(0.5f, 0.5f); // font = KnownFonts.getIosevka().scale(0.75f, 0.75f); // font = KnownFonts.getIosevkaSlab().scale(0.75f, 0.75f); // font = KnownFonts.getDejaVuSansMono().scale(0.75f, 0.75f); Font font = KnownFonts.getCozette(); // Font font = KnownFonts.getAStarry(); gm = new GlyphMap(font, GRID_WIDTH, GRID_HEIGHT); GlidingGlyph playerGlyph = new GlidingGlyph('@', describe("red orange"), Coord.get(1, 1)); playerGlyph.getLocation().setCompleteRunner(() -> { seen.or(inView.refill(FOV.reuseFOV(res, light, playerGlyph.getLocation().getEnd().x, playerGlyph.getLocation().getEnd().y, 6.5f, Radius.CIRCLE), 0.001f, 2f)); blockage.remake(seen).not().fringe8way(); LineTools.pruneLines(dungeon, seen, prunedDungeon); }); glyphs = ObjectList.with(playerGlyph); director = new Director<>(GlidingGlyph::getLocation, glyphs, 150L); directorSmall = new Director<>(GlidingGlyph::getSmallMotion, glyphs, 300L); dungeonProcessor = new DungeonProcessor(GRID_WIDTH, GRID_HEIGHT, random); dungeonProcessor.addWater(DungeonProcessor.ALL, 40); waves.setFractalType(Noise.RIDGED_MULTI); light = new float[GRID_WIDTH][GRID_HEIGHT]; seen = new Region(GRID_WIDTH, GRID_HEIGHT); blockage = new Region(GRID_WIDTH, GRID_HEIGHT); prunedDungeon = new char[GRID_WIDTH][GRID_HEIGHT]; inView = new Region(GRID_WIDTH, GRID_HEIGHT); input.setInputProcessor(new InputAdapter(){ @Override public boolean keyDown(int keycode) { switch (keycode){ case ESCAPE: case Q: Gdx.app.exit(); break; case R: regenerate(); break; default: return false; } return true; } // if the user clicks and mouseMoved hasn't already assigned a path to toCursor, then we call mouseMoved // ourselves and copy toCursor over to awaitedMoves. @Override public boolean touchUp(int screenX, int screenY, int pointer, int button) { pos.set(screenX, screenY); gm.viewport.unproject(pos); if (onGrid(MathUtils.floor(pos.x), MathUtils.floor(pos.y))) { mouseMoved(screenX, screenY); awaitedMoves.addAll(toCursor); return true; } return false; } @Override public boolean touchDragged(int screenX, int screenY, int pointer) { return mouseMoved(screenX, screenY); } // causes the path to the mouse position to become highlighted (toCursor contains a list of Coords that // receive highlighting). Uses DijkstraMap.findPathPreScanned() to find the path, which is rather fast. @Override public boolean mouseMoved(int screenX, int screenY) { if(!awaitedMoves.isEmpty()) return false; pos.set(screenX, screenY); gm.viewport.unproject(pos); if (onGrid(screenX = MathUtils.floor(pos.x), screenY = MathUtils.floor(pos.y))) { // we also need to check if screenX or screenY is the same cell. if (cursor.x == screenX && cursor.y == screenY) { return false; } cursor = Coord.get(screenX, screenY); // This uses DijkstraMap.findPathPreScannned() to get a path as a List of Coord from the current // player position to the position the user clicked on. The "PreScanned" part is an optimization // that's special to DijkstraMap; because the part of the map that is viable to move into has // already been fully analyzed by the DijkstraMap.partialScan() method at the start of the // program, and re-calculated whenever the player moves, we only need to do a fraction of the // work to find the best path with that info. toCursor.clear(); playerToCursor.findPathPreScanned(toCursor, cursor); // findPathPreScanned includes the current cell (goal) by default, which is helpful when // you're finding a path to a monster or loot, and want to bump into it, but here can be // confusing because you would "move into yourself" as your first move without this. if (!toCursor.isEmpty()) { toCursor.remove(0); } } return false; } }); regenerate(); } public void move(Direction way){ final CoordGlider cg = glyphs.first().getLocation(); // this prevents movements from restarting while a slide is already in progress. if(cg.getChange() != 0f && cg.getChange() != 1f) return; final Coord next = cg.getStart().translate(way); if(next.isWithin(GRID_WIDTH, GRID_HEIGHT) && bare[next.x][next.y] == '.') { cg.setEnd(next); director.play(); } else{ VectorSequenceGlider small = VectorSequenceGlider.BUMPS.getOrDefault(way, glyphs.first().ownEmptyMotion).copy(); small.setCompleteRunner(() -> glyphs.first().setSmallMotion(glyphs.first().ownEmptyMotion)); glyphs.first().setSmallMotion(small); directorSmall.play(); } } public void regenerate(){ dungeonProcessor.setPlaceGrid(dungeon = LineTools.hashesToLines(dungeonProcessor.generate(), true)); bare = dungeonProcessor.getBarePlaceGrid(); ArrayTools.insert(dungeon, prunedDungeon, 0, 0); res = FOV.generateSimpleResistances(bare); Coord player = new Region(bare, '.').singleRandom(dungeonProcessor.rng); glyphs.first().getLocation().setStart(player); glyphs.first().getLocation().setEnd(player); seen.remake(inView.refill(FOV.reuseFOV(res, light, player.x, player.y, 6.5f, Radius.CIRCLE), 0.001f, 2f)); blockage.remake(seen).not().fringe8way(); LineTools.pruneLines(dungeon, seen, prunedDungeon); gm.backgrounds = new int[GRID_WIDTH][GRID_HEIGHT]; gm.map.clear(); if(playerToCursor == null) playerToCursor = new DijkstraMap(bare, Measurement.EUCLIDEAN); else playerToCursor.initialize(bare); playerToCursor.setGoal(player); playerToCursor.partialScan(13, blockage); } public void recolor(){ Coord player = glyphs.first().location.getStart(); float modifiedTime = (TimeUtils.millis() & 0xFFFFFL) * 0x1p-9f; int rainbow = toRGBA8888( limitToGamut(100, (int) (TrigTools.sin_(modifiedTime * 0.2f) * 40f) + 128, (int) (TrigTools.cos_(modifiedTime * 0.2f) * 40f) + 128, 255)); FOV.reuseFOV(res, light, player.x, player.y, swayRandomized(12345, modifiedTime) * 2.5f + 4f, Radius.CIRCLE); for (int y = 0; y < GRID_HEIGHT; y++) { for (int x = 0; x < GRID_WIDTH; x++) { if (inView.contains(x, y)) { if(toCursor.contains(Coord.get(x, y))){ gm.backgrounds[x][y] = rainbow; gm.put(x, y, stoneText << 32 | prunedDungeon[x][y]); } else { switch (prunedDungeon[x][y]) { case '~': gm.backgrounds[x][y] = toRGBA8888(lighten(DEEP_OKLAB, 0.6f * Math.min(1.2f, Math.max(0, light[x][y] + waves.getConfiguredNoise(x, y, modifiedTime))))); gm.put(x, y, deepText << 32 | prunedDungeon[x][y]); break; case ',': gm.backgrounds[x][y] = toRGBA8888(lighten(SHALLOW_OKLAB, 0.6f * Math.min(1.2f, Math.max(0, light[x][y] + waves.getConfiguredNoise(x, y, modifiedTime))))); gm.put(x, y, shallowText << 32 | prunedDungeon[x][y]); break; case ' ': gm.backgrounds[x][y] = 0; break; default: gm.backgrounds[x][y] = toRGBA8888(lighten(STONE_OKLAB, 0.6f * light[x][y])); gm.put(x, y, stoneText << 32 | prunedDungeon[x][y]); } } } else if (seen.contains(x, y)) { switch (prunedDungeon[x][y]) { case '~': gm.backgrounds[x][y] = toRGBA8888(edit(DEEP_OKLAB, 0f, 0f, 0f, 0f, 0.7f, 0f, 0f, 1f)); gm.put(x, y, deepText << 32 | prunedDungeon[x][y]); break; case ',': gm.backgrounds[x][y] = toRGBA8888(edit(SHALLOW_OKLAB, 0f, 0f, 0f, 0f, 0.7f, 0f, 0f, 1f)); gm.put(x, y, shallowText << 32 | prunedDungeon[x][y]); break; case ' ': gm.backgrounds[x][y] = 0; break; default: gm.backgrounds[x][y] = toRGBA8888(edit(STONE_OKLAB, 0f, 0f, 0f, 0f, 0.7f, 0f, 0f, 1f)); gm.put(x, y, stoneText << 32 | prunedDungeon[x][y]); } } else { gm.backgrounds[x][y] = 0; } } } } /** * Supports WASD, vi-keys (hjklyubn), arrow keys, and numpad for movement, plus '.' or numpad 5 to stay still. */ public void handleHeldKeys() { if(input.isKeyPressed(A) || input.isKeyPressed(H) || input.isKeyPressed(LEFT) || input.isKeyPressed(NUMPAD_4)) move(Direction.LEFT); else if(input.isKeyPressed(S) || input.isKeyPressed(J) || input.isKeyPressed(DOWN) || input.isKeyPressed(NUMPAD_2)) move(Direction.DOWN); else if(input.isKeyPressed(W) || input.isKeyPressed(K) || input.isKeyPressed(UP) || input.isKeyPressed(NUMPAD_8)) move(Direction.UP); else if(input.isKeyPressed(D) || input.isKeyPressed(L) || input.isKeyPressed(RIGHT) || input.isKeyPressed(NUMPAD_6)) move(Direction.RIGHT); else if(input.isKeyPressed(Y) || input.isKeyPressed(NUMPAD_7)) move(Direction.UP_LEFT); else if(input.isKeyPressed(U) || input.isKeyPressed(NUMPAD_9)) move(Direction.UP_RIGHT); else if(input.isKeyPressed(B) || input.isKeyPressed(NUMPAD_1)) move(Direction.DOWN_LEFT); else if(input.isKeyPressed(N) || input.isKeyPressed(NUMPAD_3)) move(Direction.DOWN_RIGHT); else if(input.isKeyPressed(PERIOD) || input.isKeyPressed(NUMPAD_5) || input.isKeyPressed(NUMPAD_DOT)) move(Direction.NONE); } @Override public void render() { recolor(); director.step(); directorSmall.step(); handleHeldKeys(); if(!director.isPlaying() && !directorSmall.isPlaying() && !awaitedMoves.isEmpty()) { Coord m = awaitedMoves.remove(0); if (!toCursor.isEmpty()) toCursor.remove(0); move(glyphs.first().getLocation().getStart().toGoTo(m)); } else { if (!director.isPlaying() && !directorSmall.isPlaying()) { // postMove(); // this only happens if we just removed the last Coord from awaitedMoves, and it's only then that we need to // re-calculate the distances from all cells to the player. We don't need to calculate this information on // each part of a many-cell move (just the end), nor do we need to calculate it whenever the mouse moves. if (awaitedMoves.isEmpty()) { // the next two lines remove any lingering data needed for earlier paths playerToCursor.clearGoals(); playerToCursor.resetMap(); // the next line marks the player as a "goal" cell, which seems counter-intuitive, but it works because all // cells will try to find the distance between themselves and the nearest goal, and once this is found, the // distances don't change as long as the goals don't change. Since the mouse will move and new paths will be // found, but the player doesn't move until a cell is clicked, the "goal" is the non-changing cell, so the // player's position, and the "target" of a pathfinding method like DijkstraMap.findPathPreScanned() is the // currently-moused-over cell, which we only need to set where the mouse is being handled. playerToCursor.setGoal(glyphs.first().location.getStart()); // DijkstraMap.partialScan only finds the distance to get to a cell if that distance is less than some limit, // which is 13 here. It also won't try to find distances through an impassable cell, which here is the blockage // GreasedRegion that contains the cells just past the edge of the player's FOV area. playerToCursor.partialScan(13, blockage); } } } Gdx.gl.glClearColor(0, 0, 0, 1); Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT); Camera camera = gm.viewport.getCamera(); camera.position.set(gm.getGridWidth() * 0.5f, gm.getGridHeight() * 0.5f, 0f); camera.update(); gm.viewport.apply(false); batch.setProjectionMatrix(camera.combined); batch.begin(); gm.draw(batch, 0, 0); glyphs.first().draw(batch, gm.getFont()); batch.end(); Gdx.graphics.setTitle(Gdx.graphics.getFramesPerSecond() + " FPS"); } @Override public void resize(int width, int height) { super.resize(width, height); gm.resize(width, height); } private boolean onGrid(int screenX, int screenY) { return screenX >= 0 && screenX < GRID_WIDTH && screenY >= 0 && screenY < GRID_HEIGHT; } }
51.30086
186
0.591823
368a21ae6285783edfe0fa6cfc5c98074e6e01e5
2,237
package com.elmakers.mine.bukkit.protection; import org.bukkit.Location; import org.bukkit.block.Block; import org.bukkit.entity.Player; import org.bukkit.plugin.Plugin; import com.elmakers.mine.bukkit.api.protection.BlockBreakManager; import com.elmakers.mine.bukkit.api.protection.BlockBuildManager; import com.elmakers.mine.bukkit.api.protection.PVPManager; public class GriefPreventionManager implements BlockBuildManager, BlockBreakManager, PVPManager { private boolean enabled = false; private GriefPreventionAPI api = null; public void setEnabled(boolean enabled) { this.enabled = enabled; } public boolean isEnabled() { return enabled && api != null; } public void initialize(Plugin plugin) { if (enabled) { try { Plugin griefPlugin = plugin.getServer().getPluginManager().getPlugin("GriefPrevention"); if (griefPlugin != null) { api = new GriefPreventionAPI(griefPlugin); } } catch (Throwable ignored) { } if (api == null) { plugin.getLogger().info("GriefPrevention not found, claim protection will not be used."); } else { plugin.getLogger().info("GriefPrevention found, will respect claim build permissions for construction spells"); } } else { plugin.getLogger().info("GriefPrevention manager disabled, claim protection will not be used."); api = null; } } @Override public boolean hasBuildPermission(Player player, Block block) { if (enabled && block != null && api != null) { return api.hasBuildPermission(player, block); } return true; } @Override public boolean hasBreakPermission(Player player, Block block) { if (enabled && block != null && api != null) { return api.hasBreakPermission(player, block); } return true; } @Override public boolean isPVPAllowed(Player player, Location location) { if (enabled && location != null && api != null) { return api.isPVPAllowed(location); } return true; } }
32.42029
127
0.621815
339a5ea279d59470ff7852038beedc993c19b721
7,971
package io.github.flarroca.liferay.util; import java.util.Map; import javax.portlet.PortletPreferences; import com.liferay.portal.kernel.exception.SystemException; import com.liferay.portal.model.ResourceConstants; import com.liferay.portal.service.PortletPreferencesLocalService; import com.liferay.portal.service.PortletPreferencesLocalServiceUtil; import com.liferay.portal.theme.ThemeDisplay; public class RenderPreferencesUtil { public static final String TABLE_CLASS_DEFAULT = "table table-striped table-bordered table-condensed text-overflow"; public static String getHTMLTable(ThemeDisplay themeDisplay) { return(getHTMLTable(themeDisplay.getCompanyId(), themeDisplay.getScopeGroupId(), themeDisplay.getSiteGroupId(), themeDisplay.getPlid(), themeDisplay.getUserId(), themeDisplay.getPortletDisplay().getId())); } public static String getHTMLTable(long companyId, long scopeGroupId, long groupId, long plid, long userId, String portletId) { StringBuilder html = new StringBuilder(); try { PortletPreferencesLocalService service = PortletPreferencesLocalServiceUtil.getService(); PortletPreferences p1 = null; PortletPreferences p2 = null; PortletPreferences p3 = null; PortletPreferences p4 = null; p1 = service.getPreferences(companyId,0 ,ResourceConstants.SCOPE_COMPANY , 0,portletId); p2 = service.getPreferences(companyId,0 ,ResourceConstants.SCOPE_GROUP_TEMPLATE, 0,portletId); p3 = service.getPreferences(companyId,0 ,ResourceConstants.SCOPE_GROUP , 0,portletId); p4 = service.getPreferences(companyId,0 ,ResourceConstants.SCOPE_INDIVIDUAL , 0,portletId); if ((p1.getMap().size()>0)||(p2.getMap().size()>0)||(p3.getMap().size()>0)||(p4.getMap().size()>0)) { html.append("<h4>Global owner without page</h4>"); html.append(getHTMLTable("<h5>Company</h5>",p1)); html.append(getHTMLTable("<h5>Scope</h5>",p2)); html.append(getHTMLTable("<h5>Group</h5>",p3)); html.append(getHTMLTable("<h5>Individual</h5>",p4)); } p1 = service.getPreferences(companyId,0 ,ResourceConstants.SCOPE_COMPANY , 0,portletId); p2 = service.getPreferences(companyId,0 ,ResourceConstants.SCOPE_GROUP_TEMPLATE, 0,portletId); p3 = service.getPreferences(companyId,0 ,ResourceConstants.SCOPE_GROUP , 0,portletId); p4 = service.getPreferences(companyId,0 ,ResourceConstants.SCOPE_INDIVIDUAL , 0,portletId); if ((p1.getMap().size()>0)||(p2.getMap().size()>0)||(p3.getMap().size()>0)||(p4.getMap().size()>0)) { html.append("<h4>Global owner without page</h4>"); html.append(getHTMLTable("<h5>Company</h5>",p1)); html.append(getHTMLTable("<h5>Scope</h5>",p2)); html.append(getHTMLTable("<h5>Group</h5>",p3)); html.append(getHTMLTable("<h5>Individual</h5>",p4)); } p1 = service.getPreferences(companyId,companyId ,ResourceConstants.SCOPE_COMPANY , 0,portletId); p2 = service.getPreferences(companyId,scopeGroupId ,ResourceConstants.SCOPE_GROUP_TEMPLATE, 0,portletId); p3 = service.getPreferences(companyId,groupId ,ResourceConstants.SCOPE_GROUP , 0,portletId); p4 = service.getPreferences(companyId,userId ,ResourceConstants.SCOPE_INDIVIDUAL , 0,portletId); if ((p1.getMap().size()>0)||(p2.getMap().size()>0)||(p3.getMap().size()>0)||(p4.getMap().size()>0)) { html.append("<h4>Without page</h4>"); html.append(getHTMLTable("<h5>Company</h5>",p1)); html.append(getHTMLTable("<h5>Scope</h5>",p2)); html.append(getHTMLTable("<h5>Group</h5>",p3)); html.append(getHTMLTable("<h5>Individual</h5>",p4)); } p1 = service.getPreferences(companyId,0 ,ResourceConstants.SCOPE_COMPANY ,plid,portletId); p2 = service.getPreferences(companyId,0 ,ResourceConstants.SCOPE_GROUP_TEMPLATE,plid,portletId); p3 = service.getPreferences(companyId,0 ,ResourceConstants.SCOPE_GROUP ,plid,portletId); p4 = service.getPreferences(companyId,0 ,ResourceConstants.SCOPE_INDIVIDUAL ,plid,portletId); if ((p1.getMap().size()>0)||(p2.getMap().size()>0)||(p3.getMap().size()>0)||(p4.getMap().size()>0)) { html.append("<h4>Global for page ").append(plid).append("</h4>"); html.append(getHTMLTable("<h5>Company</h5>",p1)); html.append(getHTMLTable("<h5>Scope</h5>",p2)); html.append(getHTMLTable("<h5>Group</h5>",p3)); html.append(getHTMLTable("<h5>Individual</h5>",p4)); } p1 = service.getPreferences(companyId,companyId ,ResourceConstants.SCOPE_COMPANY ,plid,portletId); p2 = service.getPreferences(companyId,scopeGroupId ,ResourceConstants.SCOPE_GROUP_TEMPLATE,plid,portletId); p3 = service.getPreferences(companyId,groupId ,ResourceConstants.SCOPE_GROUP ,plid,portletId); p4 = service.getPreferences(companyId,userId ,ResourceConstants.SCOPE_INDIVIDUAL ,plid,portletId); if ((p1.getMap().size()>0)||(p2.getMap().size()>0)||(p3.getMap().size()>0)||(p4.getMap().size()>0)) { html.append("<h4>For page ").append(plid).append("</h4>"); html.append(getHTMLTable("<h5>Company</h5>",p1)); html.append(getHTMLTable("<h5>Scope</h5>",p2)); html.append(getHTMLTable("<h5>Group</h5>",p3)); html.append(getHTMLTable("<h5>Individual</h5>",p4)); } html.append("<h4>Scope</h4>"); html.append("<ul>"); html.append(" <li>Company: " ).append(companyId ).append("</li>"); html.append(" <li>scopeGroupId: ").append(scopeGroupId).append("</li>"); html.append(" <li>groupId: " ).append(groupId ).append("</li>"); html.append(" <li>plid: " ).append(plid ).append("</li>"); html.append(" <li>userId: " ).append(userId ).append("</li>"); html.append(" <li>portletId: " ).append(portletId ).append("</li>"); html.append("</ul>"); } catch (SystemException e) { html.append(e.getMessage()); } return(html.toString()); } public static String getHTMLTable(String title, PortletPreferences preferences) { return(((preferences!=null)&&(preferences.getMap().size()>0)?title:"")+getHTMLTable(preferences, TABLE_CLASS_DEFAULT)); } public static String getHTMLTable(PortletPreferences preferences) { return(getHTMLTable(preferences, TABLE_CLASS_DEFAULT)); } public static String getHTMLTable(PortletPreferences preferences,String tableClass) { Map<String, String[]> map = preferences.getMap(); if (map.size()>0) { StringBuilder builder = new StringBuilder(); builder.append("<table class='"+tableClass+"'>"); builder.append(" <thead>"); builder.append(" <tr><th>key</th><th>value</th><th></th></tr>"); builder.append(" </thead>"); builder.append(" <tbody>"); for (Map.Entry<String, String[]> entry: map.entrySet()) { String key=entry.getKey(); String[] value=entry.getValue(); for (int i = 0; i < value.length; i++) { builder.append("<tr><td>").append(key).append("</td><td>").append(value[i]).append("</td><td>").append(i).append("</td></tr>"); } } builder.append(" </tbody>"); builder.append("</table>"); return builder.toString(); } return(""); } }
56.133803
211
0.612094
6b87c8b9a7cc5091a5999cade1dcb76262e52742
27,878
package mage.sets; import mage.cards.ExpansionSet; import mage.constants.Rarity; import mage.constants.SetType; /** * @author JayDi85 */ public final class Masters25 extends ExpansionSet { private static final Masters25 instance = new Masters25(); public static Masters25 getInstance() { return instance; } private Masters25() { super("Masters 25", "A25", ExpansionSet.buildDate(2018, 3, 16), SetType.SUPPLEMENTAL); this.blockName = "Reprint"; this.hasBasicLands = false; this.hasBoosters = true; this.numBoosterLands = 0; this.numBoosterCommon = 11; this.numBoosterUncommon = 3; this.numBoosterRare = 1; this.ratioBoosterMythic = 8; cards.add(new SetCardInfo("Act of Heroism", 1, Rarity.COMMON, mage.cards.a.ActOfHeroism.class)); cards.add(new SetCardInfo("Akroma, Angel of Wrath", 2, Rarity.MYTHIC, mage.cards.a.AkromaAngelOfWrath.class)); cards.add(new SetCardInfo("Akroma's Vengeance", 3, Rarity.RARE, mage.cards.a.AkromasVengeance.class)); cards.add(new SetCardInfo("Angelic Page", 4, Rarity.UNCOMMON, mage.cards.a.AngelicPage.class)); cards.add(new SetCardInfo("Armageddon", 5, Rarity.MYTHIC, mage.cards.a.Armageddon.class)); cards.add(new SetCardInfo("Auramancer", 6, Rarity.COMMON, mage.cards.a.Auramancer.class)); cards.add(new SetCardInfo("Cloudshift", 7, Rarity.COMMON, mage.cards.c.Cloudshift.class)); cards.add(new SetCardInfo("Congregate", 8, Rarity.UNCOMMON, mage.cards.c.Congregate.class)); cards.add(new SetCardInfo("Darien, King of Kjeldor", 9, Rarity.RARE, mage.cards.d.DarienKingOfKjeldor.class)); cards.add(new SetCardInfo("Dauntless Cathar", 10, Rarity.COMMON, mage.cards.d.DauntlessCathar.class)); cards.add(new SetCardInfo("Decree of Justice", 11, Rarity.RARE, mage.cards.d.DecreeOfJustice.class)); cards.add(new SetCardInfo("Disenchant", 12, Rarity.COMMON, mage.cards.d.Disenchant.class)); cards.add(new SetCardInfo("Fencing Ace", 13, Rarity.COMMON, mage.cards.f.FencingAce.class)); cards.add(new SetCardInfo("Fiend Hunter", 14, Rarity.UNCOMMON, mage.cards.f.FiendHunter.class)); cards.add(new SetCardInfo("Geist of the Moors", 15, Rarity.COMMON, mage.cards.g.GeistOfTheMoors.class)); cards.add(new SetCardInfo("Gods Willing", 16, Rarity.COMMON, mage.cards.g.GodsWilling.class)); cards.add(new SetCardInfo("Griffin Protector", 17, Rarity.COMMON, mage.cards.g.GriffinProtector.class)); cards.add(new SetCardInfo("Karona's Zealot", 18, Rarity.UNCOMMON, mage.cards.k.KaronasZealot.class)); cards.add(new SetCardInfo("Knight of the Skyward Eye", 19, Rarity.COMMON, mage.cards.k.KnightOfTheSkywardEye.class)); cards.add(new SetCardInfo("Kongming, 'Sleeping Dragon'", 20, Rarity.UNCOMMON, mage.cards.k.KongmingSleepingDragon.class)); cards.add(new SetCardInfo("Kor Firewalker", 21, Rarity.UNCOMMON, mage.cards.k.KorFirewalker.class)); cards.add(new SetCardInfo("Loyal Sentry", 22, Rarity.COMMON, mage.cards.l.LoyalSentry.class)); cards.add(new SetCardInfo("Luminarch Ascension", 23, Rarity.RARE, mage.cards.l.LuminarchAscension.class)); cards.add(new SetCardInfo("Lunarch Mantle", 24, Rarity.COMMON, mage.cards.l.LunarchMantle.class)); cards.add(new SetCardInfo("Noble Templar", 25, Rarity.COMMON, mage.cards.n.NobleTemplar.class)); cards.add(new SetCardInfo("Nyx-Fleece Ram", 26, Rarity.UNCOMMON, mage.cards.n.NyxFleeceRam.class)); cards.add(new SetCardInfo("Ordeal of Heliod", 27, Rarity.UNCOMMON, mage.cards.o.OrdealOfHeliod.class)); cards.add(new SetCardInfo("Pacifism", 28, Rarity.COMMON, mage.cards.p.Pacifism.class)); cards.add(new SetCardInfo("Path of Peace", 29, Rarity.COMMON, mage.cards.p.PathOfPeace.class)); cards.add(new SetCardInfo("Promise of Bunrei", 30, Rarity.UNCOMMON, mage.cards.p.PromiseOfBunrei.class)); cards.add(new SetCardInfo("Renewed Faith", 31, Rarity.COMMON, mage.cards.r.RenewedFaith.class)); cards.add(new SetCardInfo("Rest in Peace", 32, Rarity.RARE, mage.cards.r.RestInPeace.class)); cards.add(new SetCardInfo("Savannah Lions", 33, Rarity.COMMON, mage.cards.s.SavannahLions.class)); cards.add(new SetCardInfo("Squadron Hawk", 34, Rarity.COMMON, mage.cards.s.SquadronHawk.class)); cards.add(new SetCardInfo("Swords to Plowshares", 35, Rarity.UNCOMMON, mage.cards.s.SwordsToPlowshares.class)); cards.add(new SetCardInfo("Thalia, Guardian of Thraben", 36, Rarity.RARE, mage.cards.t.ThaliaGuardianOfThraben.class)); cards.add(new SetCardInfo("Urbis Protector", 37, Rarity.UNCOMMON, mage.cards.u.UrbisProtector.class)); cards.add(new SetCardInfo("Valor in Akros", 38, Rarity.UNCOMMON, mage.cards.v.ValorInAkros.class)); cards.add(new SetCardInfo("Whitemane Lion", 39, Rarity.COMMON, mage.cards.w.WhitemaneLion.class)); cards.add(new SetCardInfo("Accumulated Knowledge", 40, Rarity.COMMON, mage.cards.a.AccumulatedKnowledge.class)); cards.add(new SetCardInfo("Arcane Denial", 41, Rarity.COMMON, mage.cards.a.ArcaneDenial.class)); cards.add(new SetCardInfo("Bident of Thassa", 42, Rarity.RARE, mage.cards.b.BidentOfThassa.class)); cards.add(new SetCardInfo("Blue Elemental Blast", 43, Rarity.UNCOMMON, mage.cards.b.BlueElementalBlast.class)); cards.add(new SetCardInfo("Blue Sun's Zenith", 44, Rarity.RARE, mage.cards.b.BlueSunsZenith.class)); cards.add(new SetCardInfo("Borrowing 100,000 Arrows", 45, Rarity.COMMON, mage.cards.b.Borrowing100000Arrows.class)); cards.add(new SetCardInfo("Brainstorm", 46, Rarity.COMMON, mage.cards.b.Brainstorm.class)); cards.add(new SetCardInfo("Brine Elemental", 47, Rarity.UNCOMMON, mage.cards.b.BrineElemental.class)); cards.add(new SetCardInfo("Choking Tethers", 48, Rarity.COMMON, mage.cards.c.ChokingTethers.class)); cards.add(new SetCardInfo("Coralhelm Guide", 49, Rarity.COMMON, mage.cards.c.CoralhelmGuide.class)); cards.add(new SetCardInfo("Counterspell", 50, Rarity.COMMON, mage.cards.c.Counterspell.class)); cards.add(new SetCardInfo("Court Hussar", 51, Rarity.COMMON, mage.cards.c.CourtHussar.class)); cards.add(new SetCardInfo("Curiosity", 52, Rarity.UNCOMMON, mage.cards.c.Curiosity.class)); cards.add(new SetCardInfo("Cursecatcher", 53, Rarity.UNCOMMON, mage.cards.c.Cursecatcher.class)); cards.add(new SetCardInfo("Dragon's Eye Savants", 54, Rarity.COMMON, mage.cards.d.DragonsEyeSavants.class)); cards.add(new SetCardInfo("Exclude", 55, Rarity.UNCOMMON, mage.cards.e.Exclude.class)); cards.add(new SetCardInfo("Fathom Seer", 56, Rarity.COMMON, mage.cards.f.FathomSeer.class)); cards.add(new SetCardInfo("Flash", 57, Rarity.RARE, mage.cards.f.Flash.class)); cards.add(new SetCardInfo("Freed from the Real", 58, Rarity.UNCOMMON, mage.cards.f.FreedFromTheReal.class)); cards.add(new SetCardInfo("Genju of the Falls", 59, Rarity.UNCOMMON, mage.cards.g.GenjuOfTheFalls.class)); cards.add(new SetCardInfo("Ghost Ship", 60, Rarity.COMMON, mage.cards.g.GhostShip.class)); cards.add(new SetCardInfo("Horseshoe Crab", 61, Rarity.COMMON, mage.cards.h.HorseshoeCrab.class)); cards.add(new SetCardInfo("Jace, the Mind Sculptor", 62, Rarity.MYTHIC, mage.cards.j.JaceTheMindSculptor.class)); cards.add(new SetCardInfo("Jalira, Master Polymorphist", 63, Rarity.UNCOMMON, mage.cards.j.JaliraMasterPolymorphist.class)); cards.add(new SetCardInfo("Man-o'-War", 64, Rarity.COMMON, mage.cards.m.ManOWar.class)); cards.add(new SetCardInfo("Merfolk Looter", 65, Rarity.UNCOMMON, mage.cards.m.MerfolkLooter.class)); cards.add(new SetCardInfo("Murder of Crows", 66, Rarity.UNCOMMON, mage.cards.m.MurderOfCrows.class)); cards.add(new SetCardInfo("Mystic of the Hidden Way", 67, Rarity.COMMON, mage.cards.m.MysticOfTheHiddenWay.class)); cards.add(new SetCardInfo("Pact of Negation", 68, Rarity.RARE, mage.cards.p.PactOfNegation.class)); cards.add(new SetCardInfo("Phantasmal Bear", 69, Rarity.COMMON, mage.cards.p.PhantasmalBear.class)); cards.add(new SetCardInfo("Reef Worm", 70, Rarity.RARE, mage.cards.r.ReefWorm.class)); cards.add(new SetCardInfo("Retraction Helix", 71, Rarity.COMMON, mage.cards.r.RetractionHelix.class)); cards.add(new SetCardInfo("Shoreline Ranger", 72, Rarity.COMMON, mage.cards.s.ShorelineRanger.class)); cards.add(new SetCardInfo("Sift", 73, Rarity.COMMON, mage.cards.s.Sift.class)); cards.add(new SetCardInfo("Totally Lost", 74, Rarity.COMMON, mage.cards.t.TotallyLost.class)); cards.add(new SetCardInfo("Twisted Image", 75, Rarity.UNCOMMON, mage.cards.t.TwistedImage.class)); cards.add(new SetCardInfo("Vendilion Clique", 76, Rarity.MYTHIC, mage.cards.v.VendilionClique.class)); cards.add(new SetCardInfo("Vesuvan Shapeshifter", 77, Rarity.RARE, mage.cards.v.VesuvanShapeshifter.class)); cards.add(new SetCardInfo("Willbender", 78, Rarity.UNCOMMON, mage.cards.w.Willbender.class)); cards.add(new SetCardInfo("Ancient Craving", 79, Rarity.UNCOMMON, mage.cards.a.AncientCraving.class)); cards.add(new SetCardInfo("Bloodhunter Bat", 80, Rarity.COMMON, mage.cards.b.BloodhunterBat.class)); cards.add(new SetCardInfo("Caustic Tar", 81, Rarity.UNCOMMON, mage.cards.c.CausticTar.class)); cards.add(new SetCardInfo("Dark Ritual", 82, Rarity.COMMON, mage.cards.d.DarkRitual.class)); cards.add(new SetCardInfo("Deadly Designs", 83, Rarity.UNCOMMON, mage.cards.d.DeadlyDesigns.class)); cards.add(new SetCardInfo("Death's-Head Buzzard", 84, Rarity.COMMON, mage.cards.d.DeathsHeadBuzzard.class)); cards.add(new SetCardInfo("Diabolic Edict", 85, Rarity.COMMON, mage.cards.d.DiabolicEdict.class)); cards.add(new SetCardInfo("Dirge of Dread", 86, Rarity.COMMON, mage.cards.d.DirgeOfDread.class)); cards.add(new SetCardInfo("Disfigure", 87, Rarity.COMMON, mage.cards.d.Disfigure.class)); cards.add(new SetCardInfo("Doomsday", 88, Rarity.MYTHIC, mage.cards.d.Doomsday.class)); cards.add(new SetCardInfo("Dusk Legion Zealot", 89, Rarity.COMMON, mage.cards.d.DuskLegionZealot.class)); cards.add(new SetCardInfo("Erg Raiders", 90, Rarity.COMMON, mage.cards.e.ErgRaiders.class)); cards.add(new SetCardInfo("Fallen Angel", 91, Rarity.UNCOMMON, mage.cards.f.FallenAngel.class)); cards.add(new SetCardInfo("Hell's Caretaker", 92, Rarity.RARE, mage.cards.h.HellsCaretaker.class)); cards.add(new SetCardInfo("Horror of the Broken Lands", 93, Rarity.COMMON, mage.cards.h.HorrorOfTheBrokenLands.class)); cards.add(new SetCardInfo("Ihsan's Shade", 94, Rarity.UNCOMMON, mage.cards.i.IhsansShade.class)); cards.add(new SetCardInfo("Laquatus's Champion", 95, Rarity.RARE, mage.cards.l.LaquatussChampion.class)); cards.add(new SetCardInfo("Living Death", 96, Rarity.RARE, mage.cards.l.LivingDeath.class)); cards.add(new SetCardInfo("Mesmeric Fiend", 97, Rarity.UNCOMMON, mage.cards.m.MesmericFiend.class)); cards.add(new SetCardInfo("Murder", 98, Rarity.COMMON, mage.cards.m.Murder.class)); cards.add(new SetCardInfo("Nezumi Cutthroat", 99, Rarity.COMMON, mage.cards.n.NezumiCutthroat.class)); cards.add(new SetCardInfo("Phyrexian Ghoul", 100, Rarity.COMMON, mage.cards.p.PhyrexianGhoul.class)); cards.add(new SetCardInfo("Phyrexian Obliterator", 101, Rarity.MYTHIC, mage.cards.p.PhyrexianObliterator.class)); cards.add(new SetCardInfo("Plague Wind", 102, Rarity.RARE, mage.cards.p.PlagueWind.class)); cards.add(new SetCardInfo("Ratcatcher", 103, Rarity.RARE, mage.cards.r.Ratcatcher.class)); cards.add(new SetCardInfo("Ravenous Chupacabra", 104, Rarity.UNCOMMON, mage.cards.r.RavenousChupacabra.class)); cards.add(new SetCardInfo("Relentless Rats", 105, Rarity.COMMON, mage.cards.r.RelentlessRats.class)); cards.add(new SetCardInfo("Returned Phalanx", 106, Rarity.COMMON, mage.cards.r.ReturnedPhalanx.class)); cards.add(new SetCardInfo("Ruthless Ripper", 107, Rarity.COMMON, mage.cards.r.RuthlessRipper.class)); cards.add(new SetCardInfo("Street Wraith", 108, Rarity.UNCOMMON, mage.cards.s.StreetWraith.class)); cards.add(new SetCardInfo("Supernatural Stamina", 109, Rarity.COMMON, mage.cards.s.SupernaturalStamina.class)); cards.add(new SetCardInfo("Triskaidekaphobia", 110, Rarity.RARE, mage.cards.t.Triskaidekaphobia.class)); cards.add(new SetCardInfo("Twisted Abomination", 111, Rarity.COMMON, mage.cards.t.TwistedAbomination.class)); cards.add(new SetCardInfo("Undead Gladiator", 112, Rarity.UNCOMMON, mage.cards.u.UndeadGladiator.class)); cards.add(new SetCardInfo("Unearth", 113, Rarity.COMMON, mage.cards.u.Unearth.class)); cards.add(new SetCardInfo("Vampire Lacerator", 114, Rarity.COMMON, mage.cards.v.VampireLacerator.class)); cards.add(new SetCardInfo("Will-o'-the-Wisp", 115, Rarity.UNCOMMON, mage.cards.w.WillOTheWisp.class)); cards.add(new SetCardInfo("Zombify", 116, Rarity.UNCOMMON, mage.cards.z.Zombify.class)); cards.add(new SetCardInfo("Zulaport Cutthroat", 117, Rarity.UNCOMMON, mage.cards.z.ZulaportCutthroat.class)); cards.add(new SetCardInfo("Act of Treason", 118, Rarity.COMMON, mage.cards.a.ActOfTreason.class)); cards.add(new SetCardInfo("Akroma, Angel of Fury", 119, Rarity.MYTHIC, mage.cards.a.AkromaAngelOfFury.class)); cards.add(new SetCardInfo("Balduvian Horde", 120, Rarity.COMMON, mage.cards.b.BalduvianHorde.class)); cards.add(new SetCardInfo("Ball Lightning", 121, Rarity.RARE, mage.cards.b.BallLightning.class)); cards.add(new SetCardInfo("Blood Moon", 122, Rarity.RARE, mage.cards.b.BloodMoon.class)); cards.add(new SetCardInfo("Browbeat", 123, Rarity.UNCOMMON, mage.cards.b.Browbeat.class)); cards.add(new SetCardInfo("Chandra's Outrage", 124, Rarity.COMMON, mage.cards.c.ChandrasOutrage.class)); cards.add(new SetCardInfo("Chartooth Cougar", 125, Rarity.COMMON, mage.cards.c.ChartoothCougar.class)); cards.add(new SetCardInfo("Cinder Storm", 126, Rarity.COMMON, mage.cards.c.CinderStorm.class)); cards.add(new SetCardInfo("Crimson Mage", 127, Rarity.COMMON, mage.cards.c.CrimsonMage.class)); cards.add(new SetCardInfo("Eidolon of the Great Revel", 128, Rarity.RARE, mage.cards.e.EidolonOfTheGreatRevel.class)); cards.add(new SetCardInfo("Enthralling Victor", 129, Rarity.UNCOMMON, mage.cards.e.EnthrallingVictor.class)); cards.add(new SetCardInfo("Fortune Thief", 130, Rarity.RARE, mage.cards.f.FortuneThief.class)); cards.add(new SetCardInfo("Frenzied Goblin", 131, Rarity.COMMON, mage.cards.f.FrenziedGoblin.class)); cards.add(new SetCardInfo("Genju of the Spires", 132, Rarity.UNCOMMON, mage.cards.g.GenjuOfTheSpires.class)); cards.add(new SetCardInfo("Goblin War Drums", 133, Rarity.UNCOMMON, mage.cards.g.GoblinWarDrums.class)); cards.add(new SetCardInfo("Hordeling Outburst", 134, Rarity.COMMON, mage.cards.h.HordelingOutburst.class)); cards.add(new SetCardInfo("Humble Defector", 135, Rarity.UNCOMMON, mage.cards.h.HumbleDefector.class)); cards.add(new SetCardInfo("Imperial Recruiter", 136, Rarity.MYTHIC, mage.cards.i.ImperialRecruiter.class)); cards.add(new SetCardInfo("Ire Shaman", 137, Rarity.UNCOMMON, mage.cards.i.IreShaman.class)); cards.add(new SetCardInfo("Izzet Chemister", 138, Rarity.RARE, mage.cards.i.IzzetChemister.class)); cards.add(new SetCardInfo("Jackal Pup", 139, Rarity.COMMON, mage.cards.j.JackalPup.class)); cards.add(new SetCardInfo("Kindle", 140, Rarity.COMMON, mage.cards.k.Kindle.class)); cards.add(new SetCardInfo("Lightning Bolt", 141, Rarity.UNCOMMON, mage.cards.l.LightningBolt.class)); cards.add(new SetCardInfo("Magus of the Wheel", 142, Rarity.RARE, mage.cards.m.MagusOfTheWheel.class)); cards.add(new SetCardInfo("Mogg Flunkies", 143, Rarity.COMMON, mage.cards.m.MoggFlunkies.class)); cards.add(new SetCardInfo("Pillage", 144, Rarity.COMMON, mage.cards.p.Pillage.class)); cards.add(new SetCardInfo("Pyre Hound", 145, Rarity.COMMON, mage.cards.p.PyreHound.class)); cards.add(new SetCardInfo("Pyroclasm", 146, Rarity.UNCOMMON, mage.cards.p.Pyroclasm.class)); cards.add(new SetCardInfo("Red Elemental Blast", 147, Rarity.UNCOMMON, mage.cards.r.RedElementalBlast.class)); cards.add(new SetCardInfo("Simian Spirit Guide", 148, Rarity.UNCOMMON, mage.cards.s.SimianSpiritGuide.class)); cards.add(new SetCardInfo("Skeletonize", 149, Rarity.COMMON, mage.cards.s.Skeletonize.class)); cards.add(new SetCardInfo("Skirk Commando", 150, Rarity.COMMON, mage.cards.s.SkirkCommando.class)); cards.add(new SetCardInfo("Soulbright Flamekin", 151, Rarity.COMMON, mage.cards.s.SoulbrightFlamekin.class)); cards.add(new SetCardInfo("Spikeshot Goblin", 152, Rarity.UNCOMMON, mage.cards.s.SpikeshotGoblin.class)); cards.add(new SetCardInfo("Thresher Lizard", 153, Rarity.COMMON, mage.cards.t.ThresherLizard.class)); cards.add(new SetCardInfo("Trumpet Blast", 154, Rarity.COMMON, mage.cards.t.TrumpetBlast.class)); cards.add(new SetCardInfo("Uncaged Fury", 155, Rarity.COMMON, mage.cards.u.UncagedFury.class)); cards.add(new SetCardInfo("Zada, Hedron Grinder", 156, Rarity.UNCOMMON, mage.cards.z.ZadaHedronGrinder.class)); cards.add(new SetCardInfo("Ainok Survivalist", 157, Rarity.COMMON, mage.cards.a.AinokSurvivalist.class)); cards.add(new SetCardInfo("Ambassador Oak", 158, Rarity.COMMON, mage.cards.a.AmbassadorOak.class)); cards.add(new SetCardInfo("Ancient Stirrings", 159, Rarity.UNCOMMON, mage.cards.a.AncientStirrings.class)); cards.add(new SetCardInfo("Arbor Elf", 160, Rarity.COMMON, mage.cards.a.ArborElf.class)); cards.add(new SetCardInfo("Azusa, Lost but Seeking", 161, Rarity.RARE, mage.cards.a.AzusaLostButSeeking.class)); cards.add(new SetCardInfo("Broodhatch Nantuko", 162, Rarity.UNCOMMON, mage.cards.b.BroodhatchNantuko.class)); cards.add(new SetCardInfo("Colossal Dreadmaw", 163, Rarity.COMMON, mage.cards.c.ColossalDreadmaw.class)); cards.add(new SetCardInfo("Courser of Kruphix", 164, Rarity.RARE, mage.cards.c.CourserOfKruphix.class)); cards.add(new SetCardInfo("Cultivate", 165, Rarity.COMMON, mage.cards.c.Cultivate.class)); cards.add(new SetCardInfo("Echoing Courage", 166, Rarity.COMMON, mage.cards.e.EchoingCourage.class)); cards.add(new SetCardInfo("Elvish Aberration", 167, Rarity.COMMON, mage.cards.e.ElvishAberration.class)); cards.add(new SetCardInfo("Elvish Piper", 168, Rarity.RARE, mage.cards.e.ElvishPiper.class)); cards.add(new SetCardInfo("Ember Weaver", 169, Rarity.COMMON, mage.cards.e.EmberWeaver.class)); cards.add(new SetCardInfo("Epic Confrontation", 170, Rarity.COMMON, mage.cards.e.EpicConfrontation.class)); cards.add(new SetCardInfo("Fierce Empath", 171, Rarity.UNCOMMON, mage.cards.f.FierceEmpath.class)); cards.add(new SetCardInfo("Giant Growth", 172, Rarity.COMMON, mage.cards.g.GiantGrowth.class)); cards.add(new SetCardInfo("Invigorate", 173, Rarity.UNCOMMON, mage.cards.i.Invigorate.class)); cards.add(new SetCardInfo("Iwamori of the Open Fist", 174, Rarity.UNCOMMON, mage.cards.i.IwamoriOfTheOpenFist.class)); cards.add(new SetCardInfo("Kavu Climber", 175, Rarity.COMMON, mage.cards.k.KavuClimber.class)); cards.add(new SetCardInfo("Kavu Predator", 176, Rarity.UNCOMMON, mage.cards.k.KavuPredator.class)); cards.add(new SetCardInfo("Krosan Colossus", 177, Rarity.UNCOMMON, mage.cards.k.KrosanColossus.class)); cards.add(new SetCardInfo("Krosan Tusker", 178, Rarity.UNCOMMON, mage.cards.k.KrosanTusker.class)); cards.add(new SetCardInfo("Living Wish", 179, Rarity.RARE, mage.cards.l.LivingWish.class)); cards.add(new SetCardInfo("Lull", 180, Rarity.COMMON, mage.cards.l.Lull.class)); cards.add(new SetCardInfo("Master of the Wild Hunt", 181, Rarity.MYTHIC, mage.cards.m.MasterOfTheWildHunt.class)); cards.add(new SetCardInfo("Nettle Sentinel", 182, Rarity.COMMON, mage.cards.n.NettleSentinel.class)); cards.add(new SetCardInfo("Plummet", 183, Rarity.COMMON, mage.cards.p.Plummet.class)); cards.add(new SetCardInfo("Presence of Gond", 184, Rarity.COMMON, mage.cards.p.PresenceOfGond.class)); cards.add(new SetCardInfo("Protean Hulk", 185, Rarity.RARE, mage.cards.p.ProteanHulk.class)); cards.add(new SetCardInfo("Rancor", 186, Rarity.UNCOMMON, mage.cards.r.Rancor.class)); cards.add(new SetCardInfo("Regrowth", 187, Rarity.UNCOMMON, mage.cards.r.Regrowth.class)); cards.add(new SetCardInfo("Stampede Driver", 188, Rarity.UNCOMMON, mage.cards.s.StampedeDriver.class)); cards.add(new SetCardInfo("Summoner's Pact", 189, Rarity.RARE, mage.cards.s.SummonersPact.class)); cards.add(new SetCardInfo("Timberpack Wolf", 190, Rarity.COMMON, mage.cards.t.TimberpackWolf.class)); cards.add(new SetCardInfo("Tree of Redemption", 191, Rarity.MYTHIC, mage.cards.t.TreeOfRedemption.class)); cards.add(new SetCardInfo("Utopia Sprawl", 192, Rarity.UNCOMMON, mage.cards.u.UtopiaSprawl.class)); cards.add(new SetCardInfo("Vessel of Nascency", 193, Rarity.COMMON, mage.cards.v.VesselOfNascency.class)); cards.add(new SetCardInfo("Wildheart Invoker", 194, Rarity.COMMON, mage.cards.w.WildheartInvoker.class)); cards.add(new SetCardInfo("Woolly Loxodon", 195, Rarity.COMMON, mage.cards.w.WoollyLoxodon.class)); cards.add(new SetCardInfo("Animar, Soul of Elements", 196, Rarity.MYTHIC, mage.cards.a.AnimarSoulOfElements.class)); cards.add(new SetCardInfo("Baloth Null", 197, Rarity.UNCOMMON, mage.cards.b.BalothNull.class)); cards.add(new SetCardInfo("Blightning", 198, Rarity.UNCOMMON, mage.cards.b.Blightning.class)); cards.add(new SetCardInfo("Boros Charm", 199, Rarity.UNCOMMON, mage.cards.b.BorosCharm.class)); cards.add(new SetCardInfo("Brion Stoutarm", 200, Rarity.RARE, mage.cards.b.BrionStoutarm.class)); cards.add(new SetCardInfo("Cloudblazer", 201, Rarity.UNCOMMON, mage.cards.c.Cloudblazer.class)); cards.add(new SetCardInfo("Conflux", 202, Rarity.RARE, mage.cards.c.Conflux.class)); cards.add(new SetCardInfo("Eladamri's Call", 203, Rarity.RARE, mage.cards.e.EladamrisCall.class)); cards.add(new SetCardInfo("Gisela, Blade of Goldnight", 204, Rarity.MYTHIC, mage.cards.g.GiselaBladeOfGoldnight.class)); cards.add(new SetCardInfo("Grenzo, Dungeon Warden", 205, Rarity.RARE, mage.cards.g.GrenzoDungeonWarden.class)); cards.add(new SetCardInfo("Hanna, Ship's Navigator", 206, Rarity.RARE, mage.cards.h.HannaShipsNavigator.class)); cards.add(new SetCardInfo("Lorescale Coatl", 207, Rarity.UNCOMMON, mage.cards.l.LorescaleCoatl.class)); cards.add(new SetCardInfo("Mystic Snake", 208, Rarity.RARE, mage.cards.m.MysticSnake.class)); cards.add(new SetCardInfo("Nicol Bolas", 209, Rarity.RARE, mage.cards.n.NicolBolas.class)); cards.add(new SetCardInfo("Niv-Mizzet, the Firemind", 210, Rarity.RARE, mage.cards.n.NivMizzetTheFiremind.class)); cards.add(new SetCardInfo("Notion Thief", 211, Rarity.RARE, mage.cards.n.NotionThief.class)); cards.add(new SetCardInfo("Pernicious Deed", 212, Rarity.RARE, mage.cards.p.PerniciousDeed.class)); cards.add(new SetCardInfo("Pillory of the Sleepless", 213, Rarity.UNCOMMON, mage.cards.p.PilloryOfTheSleepless.class)); cards.add(new SetCardInfo("Prossh, Skyraider of Kher", 214, Rarity.MYTHIC, mage.cards.p.ProsshSkyraiderOfKher.class)); cards.add(new SetCardInfo("Quicksilver Dagger", 215, Rarity.UNCOMMON, mage.cards.q.QuicksilverDagger.class)); cards.add(new SetCardInfo("Ruric Thar, the Unbowed", 216, Rarity.RARE, mage.cards.r.RuricTharTheUnbowed.class)); cards.add(new SetCardInfo("Shadowmage Infiltrator", 217, Rarity.UNCOMMON, mage.cards.s.ShadowmageInfiltrator.class)); cards.add(new SetCardInfo("Stangg", 218, Rarity.UNCOMMON, mage.cards.s.Stangg.class)); cards.add(new SetCardInfo("Vindicate", 219, Rarity.RARE, mage.cards.v.Vindicate.class)); cards.add(new SetCardInfo("Watchwolf", 220, Rarity.UNCOMMON, mage.cards.w.Watchwolf.class)); cards.add(new SetCardInfo("Assembly-Worker", 221, Rarity.COMMON, mage.cards.a.AssemblyWorker.class)); cards.add(new SetCardInfo("Chalice of the Void", 222, Rarity.MYTHIC, mage.cards.c.ChaliceOfTheVoid.class)); cards.add(new SetCardInfo("Coalition Relic", 223, Rarity.RARE, mage.cards.c.CoalitionRelic.class)); cards.add(new SetCardInfo("Ensnaring Bridge", 224, Rarity.MYTHIC, mage.cards.e.EnsnaringBridge.class)); cards.add(new SetCardInfo("Heavy Arbalest", 225, Rarity.UNCOMMON, mage.cards.h.HeavyArbalest.class)); cards.add(new SetCardInfo("Nihil Spellbomb", 226, Rarity.COMMON, mage.cards.n.NihilSpellbomb.class)); cards.add(new SetCardInfo("Perilous Myr", 227, Rarity.UNCOMMON, mage.cards.p.PerilousMyr.class)); cards.add(new SetCardInfo("Primal Clay", 228, Rarity.COMMON, mage.cards.p.PrimalClay.class)); cards.add(new SetCardInfo("Prophetic Prism", 229, Rarity.COMMON, mage.cards.p.PropheticPrism.class)); cards.add(new SetCardInfo("Sai of the Shinobi", 230, Rarity.UNCOMMON, mage.cards.s.SaiOfTheShinobi.class)); cards.add(new SetCardInfo("Self-Assembler", 231, Rarity.COMMON, mage.cards.s.SelfAssembler.class)); cards.add(new SetCardInfo("Strionic Resonator", 232, Rarity.RARE, mage.cards.s.StrionicResonator.class)); cards.add(new SetCardInfo("Sundering Titan", 233, Rarity.RARE, mage.cards.s.SunderingTitan.class)); cards.add(new SetCardInfo("Swiftfoot Boots", 234, Rarity.UNCOMMON, mage.cards.s.SwiftfootBoots.class)); cards.add(new SetCardInfo("Treasure Keeper", 235, Rarity.UNCOMMON, mage.cards.t.TreasureKeeper.class)); cards.add(new SetCardInfo("Ash Barrens", 236, Rarity.UNCOMMON, mage.cards.a.AshBarrens.class)); cards.add(new SetCardInfo("Cascade Bluffs", 237, Rarity.RARE, mage.cards.c.CascadeBluffs.class)); cards.add(new SetCardInfo("Fetid Heath", 238, Rarity.RARE, mage.cards.f.FetidHeath.class)); cards.add(new SetCardInfo("Flooded Grove", 239, Rarity.RARE, mage.cards.f.FloodedGrove.class)); cards.add(new SetCardInfo("Haunted Fengraf", 240, Rarity.COMMON, mage.cards.h.HauntedFengraf.class)); cards.add(new SetCardInfo("Mikokoro, Center of the Sea", 241, Rarity.RARE, mage.cards.m.MikokoroCenterOfTheSea.class)); cards.add(new SetCardInfo("Mishra's Factory", 242, Rarity.UNCOMMON, mage.cards.m.MishrasFactory.class)); cards.add(new SetCardInfo("Myriad Landscape", 243, Rarity.UNCOMMON, mage.cards.m.MyriadLandscape.class)); cards.add(new SetCardInfo("Pendelhaven", 244, Rarity.RARE, mage.cards.p.Pendelhaven.class)); cards.add(new SetCardInfo("Quicksand", 245, Rarity.UNCOMMON, mage.cards.q.Quicksand.class)); cards.add(new SetCardInfo("Rishadan Port", 246, Rarity.RARE, mage.cards.r.RishadanPort.class)); cards.add(new SetCardInfo("Rugged Prairie", 247, Rarity.RARE, mage.cards.r.RuggedPrairie.class)); cards.add(new SetCardInfo("Twilight Mire", 248, Rarity.RARE, mage.cards.t.TwilightMire.class)); cards.add(new SetCardInfo("Zoetic Cavern", 249, Rarity.UNCOMMON, mage.cards.z.ZoeticCavern.class)); } }
99.209964
132
0.719671
d5e8298e5f931267b47593fd4b6d81f8818245a2
128
/** * This package provides functionality for outputting data to Yaml format. */ package com.fortify.cli.common.output.yaml;
21.333333
74
0.757813
bc6eee9aa0cfb5fbb4b482fe31340845be7bf455
56
package com.jmsoftware.maf.osscenter.read.service.impl;
28
55
0.839286
61403fe78c3410d77bf21f6452d6a4a856f44f5f
6,108
/* * MIT License * * Copyright (c) derrop and derklaro * Copyright (c) contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package com.github.phantompowered.proxy.protocol.play.server.entity.spawn; import com.github.phantompowered.proxy.api.connection.ProtocolDirection; import com.github.phantompowered.proxy.api.network.util.PositionedPacket; import com.github.phantompowered.proxy.api.network.wrapper.ProtoBuf; import com.github.phantompowered.proxy.protocol.ProtocolIds; import com.github.phantompowered.proxy.protocol.play.server.entity.EntityPacket; import org.jetbrains.annotations.NotNull; public class PacketPlayServerSpawnEntity implements PositionedPacket, EntityPacket { private int entityId; private int x; private int y; private int z; private int speedX; private int speedY; private int speedZ; private byte pitch; private byte yaw; private int type; private int extraData; public PacketPlayServerSpawnEntity(int entityId, int x, int y, int z, int speedX, int speedY, int speedZ, byte pitch, byte yaw, int type, int extraData) { this.entityId = entityId; this.x = x; this.y = y; this.z = z; this.speedX = speedX; this.speedY = speedY; this.speedZ = speedZ; this.pitch = pitch; this.yaw = yaw; this.type = type; this.extraData = extraData; } public PacketPlayServerSpawnEntity() { } @Override public int getId() { return ProtocolIds.ToClient.Play.SPAWN_ENTITY; } @Override public int getEntityId() { return this.entityId; } @Override public void setEntityId(int entityId) { this.entityId = entityId; } @Override public int getX() { return this.x; } @Override public void setX(int x) { this.x = x; } @Override public int getY() { return this.y; } @Override public void setY(int y) { this.y = y; } @Override public int getZ() { return this.z; } @Override public void setZ(int z) { this.z = z; } public int getSpeedX() { return this.speedX; } public void setSpeedX(int speedX) { this.speedX = speedX; } public int getSpeedY() { return this.speedY; } public void setSpeedY(int speedY) { this.speedY = speedY; } public int getSpeedZ() { return this.speedZ; } public void setSpeedZ(int speedZ) { this.speedZ = speedZ; } @Override public byte getPitch() { return this.pitch; } @Override public void setPitch(byte pitch) { this.pitch = pitch; } @Override public byte getYaw() { return this.yaw; } @Override public void setYaw(byte yaw) { this.yaw = yaw; } public int getType() { return this.type; } public void setType(int type) { this.type = type; } public int getExtraData() { return this.extraData; } public void setExtraData(int extraData) { this.extraData = extraData; } @Override public void read(@NotNull ProtoBuf protoBuf, @NotNull ProtocolDirection direction, int protocolVersion) { this.entityId = protoBuf.readVarInt(); this.type = protoBuf.readByte(); this.x = protoBuf.readInt(); this.y = protoBuf.readInt(); this.z = protoBuf.readInt(); this.pitch = protoBuf.readByte(); this.yaw = protoBuf.readByte(); this.extraData = protoBuf.readInt(); if (this.extraData > 0) { this.speedX = protoBuf.readShort(); this.speedY = protoBuf.readShort(); this.speedZ = protoBuf.readShort(); } } @Override public void write(@NotNull ProtoBuf protoBuf, @NotNull ProtocolDirection direction, int protocolVersion) { protoBuf.writeVarInt(this.entityId); protoBuf.writeByte(this.type); protoBuf.writeInt(this.x); protoBuf.writeInt(this.y); protoBuf.writeInt(this.z); protoBuf.writeByte(this.pitch); protoBuf.writeByte(this.yaw); protoBuf.writeInt(this.extraData); if (this.extraData > 0) { protoBuf.writeShort(this.speedX); protoBuf.writeShort(this.speedY); protoBuf.writeShort(this.speedZ); } } public String toString() { return "PacketPlayServerSpawnEntity(entityId=" + this.getEntityId() + ", x=" + this.getX() + ", y=" + this.getY() + ", z=" + this.getZ() + ", speedX=" + this.getSpeedX() + ", speedY=" + this.getSpeedY() + ", speedZ=" + this.getSpeedZ() + ", pitch=" + this.getPitch() + ", yaw=" + this.getYaw() + ", type=" + this.getType() + ", trackedEntityId=" + this.getExtraData() + ")"; } }
27.513514
158
0.616732
f22e374db388fc82309940a806d53cdc3f598a66
357
package com.monoya.my.cake.web.api.web.dto; import lombok.Data; import java.io.Serializable; /** * 商品数据传输对象 */ @Data public class CakeDTO implements Serializable { private Long id; private String cakeName; private String cakeTaste; private String pic; private String url; private Integer price; private String cakeDetail; }
17.85
46
0.717087
8b8c44dc43375812a1a3e1aa44b94c32366940fb
5,040
package com.jokers.pojo.bo; /** * <p>AmapBo class.</p> * * @author yuton * @version 1.0 * 高德API消息接收 * @since 2017/4/17 11:22 */ public class AmapBo { /** * status : 1 * info : OK * infocode : 10000 * result : {"type":"4","location":"113.9434017,22.5496889","radius":"550","desc":"广东省 深圳市 南山区 高新中一道 靠近招商银行(科兴科学园社区支行)","country":"中国","province":"广东省","city":"深圳市","citycode":"0755","adcode":"440305","road":"高新中一道","street":"高新中一道","poi":"招商银行(科兴科学园社区支行)"} */ private String status; private String info; private String infocode; private ResultBean result; /** * <p>Getter for the field <code>status</code>.</p> * * @return a {@link java.lang.String} object. */ public String getStatus() { return status; } /** * <p>Setter for the field <code>status</code>.</p> * * @param status a {@link java.lang.String} object. */ public void setStatus(String status) { this.status = status; } /** * <p>Getter for the field <code>info</code>.</p> * * @return a {@link java.lang.String} object. */ public String getInfo() { return info; } /** * <p>Setter for the field <code>info</code>.</p> * * @param info a {@link java.lang.String} object. */ public void setInfo(String info) { this.info = info; } /** * <p>Getter for the field <code>infocode</code>.</p> * * @return a {@link java.lang.String} object. */ public String getInfocode() { return infocode; } /** * <p>Setter for the field <code>infocode</code>.</p> * * @param infocode a {@link java.lang.String} object. */ public void setInfocode(String infocode) { this.infocode = infocode; } /** * <p>Getter for the field <code>result</code>.</p> * * @return a {@link com.jokers.pojo.bo.AmapBo.ResultBean} object. */ public ResultBean getResult() { return result; } /** * <p>Setter for the field <code>result</code>.</p> * * @param result a {@link com.jokers.pojo.bo.AmapBo.ResultBean} object. */ public void setResult(ResultBean result) { this.result = result; } public static class ResultBean { /** * type : 4 * location : 113.9434017,22.5496889 * radius : 550 * desc : 广东省 深圳市 南山区 高新中一道 靠近招商银行(科兴科学园社区支行) * country : 中国 * province : 广东省 * city : 深圳市 * citycode : 0755 * adcode : 440305 * road : 高新中一道 * street : 高新中一道 * poi : 招商银行(科兴科学园社区支行) */ private String type; private String location; private String radius; private String desc; private String country; private String province; private String city; private String citycode; private String adcode; private String road; private String street; private String poi; public String getType() { return type; } public void setType(String type) { this.type = type; } public String getLocation() { return location; } public void setLocation(String location) { this.location = location; } public String getRadius() { return radius; } public void setRadius(String radius) { this.radius = radius; } public String getDesc() { return desc; } public void setDesc(String desc) { this.desc = desc; } public String getCountry() { return country; } public void setCountry(String country) { this.country = country; } public String getProvince() { return province; } public void setProvince(String province) { this.province = province; } public String getCity() { return city; } public void setCity(String city) { this.city = city; } public String getCitycode() { return citycode; } public void setCitycode(String citycode) { this.citycode = citycode; } public String getAdcode() { return adcode; } public void setAdcode(String adcode) { this.adcode = adcode; } public String getRoad() { return road; } public void setRoad(String road) { this.road = road; } public String getStreet() { return street; } public void setStreet(String street) { this.street = street; } public String getPoi() { return poi; } public void setPoi(String poi) { this.poi = poi; } } }
22.702703
261
0.518254
53303e02cbfc98c5fb930ebf2b6dc739558385fe
1,739
package array; /** * 63. Unique Paths II * * A robot is located at the top-left corner of a m x n grid (marked 'Start' in the diagram below). * The robot can only move either down or right at any point in time. The robot is trying to reach * the bottom-right corner of the grid (marked 'Finish' in the diagram below). * Now consider if some obstacles are added to the grids. How many unique paths would there be? * * Note: m and n will be at most 100. * Example 1: * Input: * [ * [0,0,0], * [0,1,0], * [0,0,0] * ] * Output: 2 * Explanation: * There is one obstacle in the middle of the 3x3 grid above. * There are two ways to reach the bottom-right corner: * 1. Right -> Right -> Down -> Down * 2. Down -> Down -> Right -> Right * * Created by zjm on 2019/6/7. */ public class UniquePathsII { //just like UniquePaths, only need consider the vlue of obstacleGrid[i][j] is 1 or not. public int uniquePathsWithObstacles(int[][] obstacleGrid) { if(obstacleGrid.length < 1) { return 0; } int r = obstacleGrid.length; int c = obstacleGrid[0].length; int[][] res = new int[r][c]; for(int i = 0; i < r; i++) { if(obstacleGrid[i][0] == 1) { break; } res[i][0] = 1; } for(int i = 0; i < c; i++) { if(obstacleGrid[0][i] == 1) { break; } res[0][i] = 1; } for(int i = 1; i < r; i++) { for(int j = 1; j < c; j++) { if(obstacleGrid[i][j] != 1) { res[i][j] = res[i - 1][j] + res[i][j - 1]; } } } return res[r-1][c-1]; } }
28.983333
99
0.510063
2bc93500ade358db1c8268680e4ff642a0db7311
1,467
/* * Jitsi, the OpenSource Java VoIP and Instant Messaging client. * * Copyright @ 2015 Atlassian Pty Ltd * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.jitsi.android.gui.call; import android.os.*; import org.jitsi.impl.neomedia.device.util.*; /** * Video handler fragment for API18 and above. Provides OpenGL context for * displaying local preview in direct surface encoding mode. * * @author Pawel Domas */ public class VideoHandlerFragmentAPI18 extends VideoHandlerFragment { @Override public void onActivityCreated(Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); CameraUtils.localPreviewCtxProvider = new OpenGlCtxProvider(getActivity(), localPreviewContainer); } @Override public void onDestroy() { super.onDestroy(); // This provider is no longer valid CameraUtils.localPreviewCtxProvider = null; } }
28.211538
75
0.718473
fa72c1ce095b9ef4ee3cf955b61298a89fc1bb0b
14,904
/* * Copyright (C) 2010-2021 Evolveum and contributors * * This work is dual-licensed under the Apache License 2.0 * and European Union Public License. See LICENSE file for details. */ package com.evolveum.midpoint.repo.common.activity.run.buckets.segmentation; import com.evolveum.midpoint.repo.common.activity.run.buckets.BaseBucketContentFactory; import com.evolveum.midpoint.util.logging.Trace; import com.evolveum.midpoint.util.logging.TraceManager; import com.evolveum.midpoint.xml.ns._public.common.common_3.*; import org.jetbrains.annotations.NotNull; import java.util.*; import java.util.stream.Collectors; import static com.evolveum.midpoint.util.MiscUtil.argCheck; import static com.evolveum.midpoint.xml.ns._public.common.common_3.StringWorkBucketsBoundaryMarkingType.INTERVAL; import static java.util.Collections.emptyList; import static java.util.Collections.singletonList; import static org.apache.commons.lang3.ObjectUtils.defaultIfNull; /** * Creates content of string-based buckets (defined by {@link StringWorkSegmentationType} and its subtypes). */ public class StringBucketContentFactory extends BaseBucketContentFactory<StringWorkSegmentationType> { private static final Trace LOGGER = TraceManager.getTrace(StringBucketContentFactory.class); @NotNull private final StringWorkBucketsBoundaryMarkingType marking; @NotNull private final List<String> boundaries; private static final String OID_BOUNDARIES = "0-9a-f"; StringBucketContentFactory(@NotNull StringWorkSegmentationType segmentationConfig) { super(segmentationConfig); this.marking = defaultIfNull(segmentationConfig.getComparisonMethod(), INTERVAL); this.boundaries = processBoundaries(); } /** * This is to allow instantiation even for subtypes of {@link StringWorkSegmentationType}. * It is a price we pay for using simple {@link Class#getConstructor(Class[])} to look for * the applicable constructor. */ StringBucketContentFactory(@NotNull OidWorkSegmentationType segmentationConfig) { this((StringWorkSegmentationType) segmentationConfig); } @Override public AbstractWorkBucketContentType createNextBucketContent(AbstractWorkBucketContentType lastBucketContent, Integer lastBucketSequentialNumber) { switch (marking) { case INTERVAL: return createAdditionalIntervalBucket(lastBucketContent, lastBucketSequentialNumber); case PREFIX: return createAdditionalPrefixBucket(lastBucketContent, lastBucketSequentialNumber); case EXACT_MATCH: return createAdditionalExactMatchBucket(lastBucketContent, lastBucketSequentialNumber); default: throw new AssertionError("unsupported marking: " + marking); } } private AbstractWorkBucketContentType createAdditionalIntervalBucket(AbstractWorkBucketContentType lastBucketContent, Integer lastBucketSequentialNumber) { String lastBoundary; if (lastBucketSequentialNumber != null) { if (!(lastBucketContent instanceof StringIntervalWorkBucketContentType)) { throw new IllegalStateException("Null or unsupported bucket content: " + lastBucketContent); } StringIntervalWorkBucketContentType lastContent = (StringIntervalWorkBucketContentType) lastBucketContent; if (lastContent.getTo() == null) { return null; } lastBoundary = lastContent.getTo(); } else { lastBoundary = null; } return new StringIntervalWorkBucketContentType() .from(lastBoundary) .to(computeNextBoundary(lastBoundary)); } private AbstractWorkBucketContentType createAdditionalPrefixBucket(AbstractWorkBucketContentType lastBucketContent, Integer lastBucketSequentialNumber) { String lastBoundary; if (lastBucketSequentialNumber != null) { if (!(lastBucketContent instanceof StringPrefixWorkBucketContentType)) { throw new IllegalStateException("Null or unsupported bucket content: " + lastBucketContent); } StringPrefixWorkBucketContentType lastContent = (StringPrefixWorkBucketContentType) lastBucketContent; if (lastContent.getPrefix().size() > 1) { throw new IllegalStateException("Multiple prefixes are not supported now: " + lastContent); } else if (lastContent.getPrefix().isEmpty()) { return null; } else { lastBoundary = lastContent.getPrefix().get(0); } } else { lastBoundary = null; } String nextBoundary = computeNextBoundary(lastBoundary); if (nextBoundary != null) { return new StringPrefixWorkBucketContentType() .prefix(nextBoundary); } else { return null; } } private AbstractWorkBucketContentType createAdditionalExactMatchBucket(AbstractWorkBucketContentType lastBucketContent, Integer lastBucketSequentialNumber) { String lastBoundary; if (lastBucketSequentialNumber != null) { if (!(lastBucketContent instanceof StringValueWorkBucketContentType)) { throw new IllegalStateException("Null or unsupported bucket content: " + lastBucketContent); } StringValueWorkBucketContentType lastContent = (StringValueWorkBucketContentType) lastBucketContent; if (lastContent.getValue().size() > 1) { throw new IllegalStateException("Multiple values are not supported now: " + lastContent); } else if (lastContent.getValue().isEmpty()) { return null; } else { lastBoundary = lastContent.getValue().get(0); } } else { lastBoundary = null; } String nextBoundary = computeNextBoundary(lastBoundary); if (nextBoundary != null) { return new StringValueWorkBucketContentType() .value(nextBoundary); } else { return null; } } private String computeNextBoundary(String lastBoundary) { List<Integer> currentIndices = stringToIndices(lastBoundary); if (incrementIndices(currentIndices)) { return indicesToString(currentIndices); } else { return null; } } @NotNull private List<Integer> stringToIndices(String lastBoundary) { List<Integer> currentIndices = new ArrayList<>(); if (lastBoundary == null) { for (int i = 0; i < boundaries.size(); i++) { if (i < boundaries.size() - 1) { currentIndices.add(0); } else { currentIndices.add(-1); } } } else { if (lastBoundary.length() != boundaries.size()) { throw new IllegalStateException("Unexpected length of lastBoundary ('" + lastBoundary + "'): " + lastBoundary.length() + ", expected " + boundaries.size()); } for (int i = 0; i < lastBoundary.length(); i++) { int index = boundaries.get(i).indexOf(lastBoundary.charAt(i)); if (index < 0) { throw new IllegalStateException("Illegal character at position " + (i+1) + " of lastBoundary (" + lastBoundary + "): expected one of '" + boundaries.get(i) + "'"); } currentIndices.add(index); } } return currentIndices; } // true if the new state is a valid one private boolean incrementIndices(List<Integer> currentIndices) { assert boundaries.size() == currentIndices.size(); for (int i = currentIndices.size() - 1; i >= 0; i--) { int nextValue = currentIndices.get(i) + 1; if (nextValue < boundaries.get(i).length()) { currentIndices.set(i, nextValue); return true; } else { currentIndices.set(i, 0); } } return false; } private String indicesToString(List<Integer> currentIndices) { assert boundaries.size() == currentIndices.size(); StringBuilder sb = new StringBuilder(); for (int i = 0; i < currentIndices.size(); i++) { sb.append(boundaries.get(i).charAt(currentIndices.get(i))); } return sb.toString(); } @Override public Integer estimateNumberOfBuckets() { int combinations = 1; for (String boundary : boundaries) { combinations *= boundary.length(); } return marking == INTERVAL ? combinations+1 : combinations; } private List<String> processBoundaries() { List<String> expanded = getConfiguredBoundaries().stream() .map(this::expand) .collect(Collectors.toList()); int depth = defaultIfNull(segmentationConfig.getDepth(), 1); List<String> rv = new ArrayList<>(expanded.size() * depth); for (int i = 0; i < depth; i++) { rv.addAll(expanded); } return rv; } private List<String> getConfiguredBoundaries() { if (!segmentationConfig.getBoundary().isEmpty()) { return new Boundaries(segmentationConfig.getBoundary()) .getConfiguredBoundaries(); } else if (!segmentationConfig.getBoundaryCharacters().isEmpty()) { return segmentationConfig.getBoundaryCharacters(); } else if (segmentationConfig instanceof OidWorkSegmentationType) { return singletonList(OID_BOUNDARIES); } else { return emptyList(); } } private static class Scanner { private final String string; private int index; private Scanner(String string) { this.string = string; } private boolean hasNext() { return index < string.length(); } // @pre hasNext() private boolean isDash() { return string.charAt(index) == '-'; } // @pre hasNext() public char next() { char c = string.charAt(index++); if (c != '\\') { return c; } else if (index != string.length()) { return string.charAt(index++); } else { throw new IllegalArgumentException("Boundary specification cannot end with '\\': " + string); } } } private String expand(String s) { StringBuilder sb = new StringBuilder(); Scanner scanner = new Scanner(s); while (scanner.hasNext()) { if (scanner.isDash()) { if (sb.length() == 0) { throw new IllegalArgumentException("Boundary specification cannot start with '-': " + s); } else { scanner.next(); if (!scanner.hasNext()) { throw new IllegalArgumentException("Boundary specification cannot end with '-': " + s); } else { appendFromTo(sb, sb.charAt(sb.length()-1), scanner.next()); } } } else { sb.append(scanner.next()); } } String expanded = sb.toString(); if (marking == INTERVAL) { checkBoundary(expanded); } return expanded; } // this is a bit tricky: we do not know what matching rule will be used to execute the comparisons // but let's assume it will be consistent with the default ordering private void checkBoundary(String boundary) { for (int i = 1; i < boundary.length(); i++) { char before = boundary.charAt(i - 1); char after = boundary.charAt(i); if (before >= after) { LOGGER.warn("Boundary characters are not sorted in ascending order ({}); comparing '{}' and '{}'", boundary, before, after); } } } private void appendFromTo(StringBuilder sb, char fromExclusive, char toInclusive) { for (char c = (char) (fromExclusive+1); c <= toInclusive; c++) { sb.append(c); } } // just for testing @NotNull public List<String> getBoundaries() { return boundaries; } private static class Boundaries { private final List<BoundarySpecificationType> specifications; private final List<String> configuredBoundaries = new ArrayList<>(); private Boundaries(List<BoundarySpecificationType> specifications) { this.specifications = specifications; } public List<String> getConfiguredBoundaries() { for (BoundarySpecificationType specification : specifications) { process(specification); } checkConsistency(); return configuredBoundaries; } private void process(BoundarySpecificationType specification) { if (specification.getPosition().isEmpty()) { configuredBoundaries.add(specification.getCharacters()); return; } for (Integer position : specification.getPosition()) { argCheck(position != null, "Position is null in %s", specification); extendIfNeeded(position); set(position, specification.getCharacters()); } } /** * @param position User-visible position, i.e. starts at 1 (not at zero)! */ private void extendIfNeeded(int position) { int index = position - 1; while (configuredBoundaries.size() <= index) { configuredBoundaries.add(null); } } /** * @param position User-visible position, i.e. starts at 1 (not at zero)! */ private void set(int position, String characters) { int index = position - 1; assert configuredBoundaries.size() > index; argCheck(configuredBoundaries.get(index) == null, "Boundary characters for position %d defined more than once: %s", position, configuredBoundaries); configuredBoundaries.set(index, characters); } private void checkConsistency() { for (int i = 0; i < configuredBoundaries.size(); i++) { String configuredBoundary = configuredBoundaries.get(i); argCheck(configuredBoundary != null, "Boundary characters for position %s are not defined: %s", i, configuredBoundaries); } } } }
39.638298
123
0.605408
c1e64165c9f25c7daf5ef500e4595d6f7a685a48
13,981
/* * File: MutableIntegerTest.java * Authors: Justin Basilico * Company: Sandia National Laboratories * Project: Cognitive Foundry * * Copyright June 14, 2011, Sandia Corporation. * Under the terms of Contract DE-AC04-94AL85000, there is a non-exclusive * license for use of this work by or on behalf of the U.S. Government. Export * of this program may require a license from the United States Government. * See CopyrightHistory.txt for complete details. * */ package gov.sandia.cognition.math; import gov.sandia.cognition.math.matrix.DimensionalityMismatchException; import gov.sandia.cognition.math.matrix.Vector; import gov.sandia.cognition.math.matrix.VectorFactory; import gov.sandia.cognition.math.matrix.mtj.Vector1; import gov.sandia.cognition.math.matrix.mtj.Vector2; /** * Unit tests for class MutableInteger. * * @author Justin Basilico * @since 3.1.2 */ public class MutableIntegerTest extends EuclideanRingTestHarness<MutableInteger> { /** * Creates a new test. * * @param testName The test name. */ public MutableIntegerTest( final String testName) { super(testName); } protected int randomInt() { final int range = (int) this.RANGE + 1; return 2 * this.RANDOM.nextInt(range) - range; } @Override protected MutableInteger createRandom() { return new MutableInteger(this.randomInt()); } protected int[] getGoodValues() { return new int[] { 1, 2, 3, 4, 5, 10, -1, -2, -3, -4, -10, Integer.MIN_VALUE, Integer.MAX_VALUE, 0, this.randomInt() }; } /** * Test of constructors of class MutableInteger. */ public void testConstructors() { int value = 0; MutableInteger instance = new MutableInteger(); assertEquals(value, instance.getValue()); value = this.randomInt(); instance = new MutableInteger(value); assertEquals(value, instance.getValue()); instance = new MutableInteger(instance); assertEquals(value, instance.getValue()); } /** * Test of equals method, of class MutableInteger. */ public void testEquals() { int[] values = this.getGoodValues(); for (int xValue : values) { MutableInteger x = new MutableInteger(xValue); assertTrue(x.equals(x)); for (int yValue : values) { MutableInteger y = new MutableInteger(yValue); assertEquals(xValue == yValue, x.equals(y)); assertEquals(new Integer(xValue).equals(new Integer(yValue)), x.equals(y)); } } } /** * Test of compareTo method, of class MutableInteger. */ public void testCompareTo() { int[] values = this.getGoodValues(); for (int xValue : values) { MutableInteger x = new MutableInteger(xValue); assertEquals(0, x.compareTo(x)); for (int yValue : values) { MutableInteger y = new MutableInteger(yValue); assertEquals(new Integer(xValue).compareTo(new Integer(yValue)), x.compareTo(y)); } } } /** * Test of hashCode method, of class MutableInteger. */ public void testHashCode() { MutableInteger instance = new MutableInteger(); assertEquals(0, instance.hashCode()); for (int value : this.getGoodValues()) { instance.setValue(value); int expected = new Integer(value).hashCode(); assertEquals(expected, instance.hashCode()); assertEquals(expected, instance.hashCode()); assertEquals(expected, new MutableInteger(value).hashCode()); } } /** * Test of intValue method, of class MutableInteger. */ public void testIntValue() { int value = 0; MutableInteger instance = new MutableInteger(); int expected = value; assertEquals(expected, instance.intValue()); for (int goodValue : this.getGoodValues()) { value = goodValue; instance.setValue(value); expected = value; assertEquals(expected, instance.intValue()); } } /** * Test of longValue method, of class MutableInteger. */ public void testLongValue() { int value = 0; MutableInteger instance = new MutableInteger(); long expected = (long) value; assertEquals(expected, instance.longValue()); for (int goodValue : this.getGoodValues()) { value = goodValue; instance.setValue(value); expected = (long) value; assertEquals(expected, instance.longValue()); } } /** * Test of floatValue method, of class MutableInteger. */ public void testFloatValue() { int value = 0; MutableInteger instance = new MutableInteger(); float expected = (float) value; assertEquals(expected, instance.floatValue()); for (int goodValue : this.getGoodValues()) { value = goodValue; instance.setValue(value); expected = (float) value; assertEquals(expected, instance.floatValue()); } } /** * Test of doubleValue method, of class MutableInteger. */ public void testDoubleValue() { int value = 0; MutableInteger instance = new MutableInteger(); double expected = (double) value; assertEquals(expected, instance.doubleValue()); for (int goodValue : this.getGoodValues()) { value = goodValue; instance.setValue(value); expected = (double) value; assertEquals(expected, instance.doubleValue()); } } /** * Test of getValue method, of class MutableInteger. */ public void testGetValue() { this.testSetValue(); } /** * Test of setValue method, of class MutableInteger. */ public void testSetValue() { int value = 0; MutableInteger instance = new MutableInteger(); assertEquals(value, instance.value); assertEquals(value, instance.getValue()); for (int goodValue : this.getGoodValues()) { value = goodValue; instance.setValue(value); assertEquals(value, instance.value); assertEquals(value, instance.getValue()); } } /** * Test of toString method, of class MutableInteger. */ public void testToString() { String expected = "0"; MutableInteger instance = new MutableInteger(); assertEquals(expected, instance.toString()); for (int value : this.getGoodValues()) { instance.setValue(value); expected = new Integer(value).toString(); assertEquals(expected, instance.toString()); } } /** * Test of convertToVector method, of class MutableInteger. */ public void testConvertToVector() { MutableInteger instance = new MutableInteger(); Vector1 result = instance.convertToVector(); assertEquals(0, (int) result.getX()); int value = this.randomInt(); instance.setValue(value); assertEquals(0, (int) result.getX()); result = instance.convertToVector(); assertEquals(value, (int) result.getX()); result.setX(this.randomInt()); assertEquals(value, instance.getValue()); } /** * Test of convertFromVector method, of class MutableInteger. */ public void testConvertFromVector() { MutableInteger instance = new MutableInteger(); Vector vector = VectorFactory.getDefault().createVector(1); int value = 0; instance.convertFromVector(vector); assertEquals(value, instance.getValue()); value = this.randomInt(); vector.setElement(0, value); instance.convertFromVector(vector); assertEquals(value, instance.getValue()); boolean exceptionThrown = false; try { instance.convertFromVector(new Vector2()); } catch (DimensionalityMismatchException e) { exceptionThrown = true; } finally { assertTrue(exceptionThrown); } } @Override public void testScaleEquals() { int value = 0; int scale = this.randomInt(); int expected = 0; MutableInteger instance = new MutableInteger(); expected = value * scale; instance.scaleEquals(scale); assertEquals(expected, instance.getValue()); value = this.randomInt(); scale = this.randomInt(); instance.setValue(value); expected = value * scale; instance.scaleEquals(scale); assertEquals(expected, instance.getValue()); for (int i = 0; i < 1 + RANDOM.nextInt(10); i++) { scale = this.randomInt(); expected *= scale; instance.scaleEquals(scale); assertEquals(expected, instance.getValue()); } } @Override public void testPlusEquals() { int value = 0; int otherValue = this.randomInt(); int expected = 0; MutableInteger instance = new MutableInteger(); expected = value + otherValue; instance.plusEquals(new MutableInteger(otherValue)); assertEquals(expected, instance.getValue()); value = this.randomInt(); otherValue = this.randomInt(); instance.setValue(value); expected = value + otherValue; instance.plusEquals(new MutableInteger(otherValue)); assertEquals(expected, instance.getValue()); for (int i = 0; i < 1 + RANDOM.nextInt(10); i++) { otherValue = this.randomInt(); MutableInteger other = new MutableInteger(otherValue); expected += otherValue; instance.plusEquals(other); assertEquals(expected, instance.getValue()); assertEquals(otherValue, other.getValue()); } } @Override public void testTimesEquals() { int value = 0; int otherValue = this.randomInt(); int expected = 0; MutableInteger instance = new MutableInteger(); expected = value * otherValue; instance.timesEquals(new MutableInteger(otherValue)); assertEquals(expected, instance.getValue()); value = this.randomInt(); otherValue = this.randomInt(); instance.setValue(value); expected = value * otherValue; instance.timesEquals(new MutableInteger(otherValue)); assertEquals(expected, instance.getValue()); for (int i = 0; i < 1 + RANDOM.nextInt(10); i++) { otherValue = this.randomInt(); MutableInteger other = new MutableInteger(otherValue); expected *= otherValue; instance.timesEquals(other); assertEquals(expected, instance.getValue()); assertEquals(otherValue, other.getValue()); } } @Override public void testDivideEquals() { int value = 0; int otherValue = this.randomInt(); int expected = 0; MutableInteger instance = new MutableInteger(); expected = value / otherValue; instance.divideEquals(new MutableInteger(otherValue)); assertEquals(expected, instance.getValue()); value = this.randomInt(); otherValue = this.randomInt(); instance.setValue(value); expected = value / otherValue; instance.divideEquals(new MutableInteger(otherValue)); assertEquals(expected, instance.getValue()); for (int i = 0; i < 1 + RANDOM.nextInt(10); i++) { otherValue = this.randomInt(); MutableInteger other = new MutableInteger(otherValue); if (otherValue != 0) { expected /= otherValue; instance.divideEquals(other); assertEquals(expected, instance.getValue()); assertEquals(otherValue, other.getValue()); } else { boolean exceptionThrown = false; try { instance.divideEquals(other); } catch (ArithmeticException e) { exceptionThrown = true; } finally { assertTrue(exceptionThrown); } } } } @Override public void testDotTimesEquals() { int value = 0; int otherValue = this.randomInt(); int expected = 0; MutableInteger instance = new MutableInteger(); expected = value * otherValue; instance.dotTimesEquals(new MutableInteger(otherValue)); assertEquals(expected, instance.getValue()); value = this.randomInt(); otherValue = this.randomInt(); instance.setValue(value); expected = value * otherValue; instance.dotTimesEquals(new MutableInteger(otherValue)); assertEquals(expected, instance.getValue()); for (int i = 0; i < 1 + RANDOM.nextInt(10); i++) { otherValue = this.randomInt(); MutableInteger other = new MutableInteger(otherValue); expected *= otherValue; instance.dotTimesEquals(other); assertEquals(expected, instance.getValue()); assertEquals(otherValue, other.getValue()); } } }
29.187891
80
0.573636
b51eb5f5d86712b4efc9404f3e0f8238568ecf95
2,800
/* * Copyright 2015-2021 Alejandro Sánchez <[email protected]> * * 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.nexttypes.datatypes; import java.awt.Color; import java.awt.Graphics2D; import java.awt.image.BufferedImage; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.util.Hashtable; import javax.imageio.ImageIO; import org.apache.commons.codec.binary.Base64; import com.google.zxing.BarcodeFormat; import com.google.zxing.EncodeHintType; import com.google.zxing.WriterException; import com.google.zxing.common.BitMatrix; import com.google.zxing.qrcode.QRCodeWriter; import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel; import com.nexttypes.exceptions.NXException; import com.nexttypes.system.Constants; public class QRCode { protected BufferedImage qrcode; public QRCode(String text, int size, ErrorCorrectionLevel errorCorrectionLevel) { Hashtable<EncodeHintType, Object> hintMap = new Hashtable<EncodeHintType, Object>(); hintMap.put(EncodeHintType.ERROR_CORRECTION, errorCorrectionLevel); hintMap.put(EncodeHintType.CHARACTER_SET, Constants.UTF_8_CHARSET); hintMap.put(EncodeHintType.MARGIN, 1); QRCodeWriter qrcodeWriter = new QRCodeWriter(); BitMatrix bitMatrix = null; try { bitMatrix = qrcodeWriter.encode(text, BarcodeFormat.QR_CODE, size, size, hintMap); } catch (WriterException e) { throw new NXException(e); } int imageSize = bitMatrix.getWidth(); qrcode = new BufferedImage(imageSize, imageSize, BufferedImage.TYPE_INT_RGB); qrcode.createGraphics(); Graphics2D graphics = (Graphics2D) qrcode.getGraphics(); graphics.setColor(Color.WHITE); graphics.fillRect(0, 0, imageSize, imageSize); graphics.setColor(Color.BLACK); for (int x = 0; x < imageSize; x++) { for (int y = 0; y < imageSize; y++) { if (bitMatrix.get(x, y)) { graphics.fillRect(x, y, 1, 1); } } } } public byte[] getBytes() { byte[] bytes = null; try (ByteArrayOutputStream stream = new ByteArrayOutputStream()) { ImageIO.write(qrcode, "png", stream); bytes = stream.toByteArray(); } catch (IOException e) { throw new NXException(e); } return bytes; } public String getBase64() { return "data:image/png;base64," + Base64.encodeBase64String(getBytes()); } }
31.818182
86
0.746786
a283af6a7cf905d3f1bc3190c5e0e6eb3b12aab4
2,916
package com.workhub.z.servicechat.dao; import com.workhub.z.servicechat.VO.FileMonitoringVo; import com.workhub.z.servicechat.VO.GroupFileVo; import com.workhub.z.servicechat.entity.group.ZzGroupFile; import org.apache.ibatis.annotations.Param; import tk.mybatis.mapper.common.Mapper; import java.util.List; import java.util.Map; /** * 群文件(ZzGroupFile)表数据库访问层 * * @author 忠 * @since 2019-05-13 10:59:08 */ public interface ZzGroupFileDao extends Mapper<ZzGroupFile> { /** * 通过ID查询单条数据 * * @param fileId 主键 * @return 实例对象 */ ZzGroupFile queryById(String fileId); /** * 查询指定行数据 * * @param offset 查询起始位置 * @param limit 查询条数 * @return 对象列表 */ List<ZzGroupFile> queryAllByLimit(@Param("offset") int offset, @Param("limit") int limit); /** * 通过实体作为筛选条件查询 * * @param zzGroupFile 实例对象 * @return 对象列表 */ List<ZzGroupFile> queryAll(ZzGroupFile zzGroupFile); /** * 新增数据 * * @param zzGroupFile 实例对象 * @return 影响行数 */ @Override int insert(ZzGroupFile zzGroupFile); /** * 修改数据 * * @param zzGroupFile 实例对象 * @return 影响行数 */ int update(ZzGroupFile zzGroupFile); /** * 通过主键删除数据 * * @param fileId 主键 * @return 影响行数 */ int deleteById(String fileId); //List<GroupInfoVo> groupFileList(@Param("id") String id, @Param("start") Integer start, @Param("end") Integer end); Long groupFileListTotal(@Param("id")String id); List<GroupFileVo> groupFileList(@Param("id") String id,@Param("userId") String userId,@Param("query") String query); List<GroupFileVo> groupFileList(@Param("id") String id,@Param("query") String query); List<GroupFileVo> groupFileListByMe(@Param("groupId") String groupId,@Param("userId") String userId); List<GroupFileVo> groupFileListByOwner(@Param("groupId") String groupId,@Param("userId") String userId); List<GroupFileVo> groupFileListByPass(@Param("groupId") String groupId); //查询附件大小 double queryFileSize(@Param("dateFmat") String dateFmat,@Param("date") String date,@Param("unit") long unit ); //查询附件大小(日期范围) List<Map> queryFileSizeRange(@Param("dateFmat") String dateFmat, @Param("dateBegin") String dateBegin, @Param("dateEnd") String dateEnd, @Param("unit") long unit ); //上传文件记录 int fileRecord(@Param("param") ZzGroupFile zzUploadFile); //文件信息补全 int fileUpdate(@Param("param") ZzGroupFile zzUploadFile); List<FileMonitoringVo> fileMonitoring(@Param("params") Map<String,Object> param); int setFileApproveFLg(@Param("params") List<Map<String,String>> params); /** * 查询文件信息列表 * @param params page、size页码页数 ;groupId接收人id ;userId 上传人id ;isGroup文件类型0私聊1群文件905会议文件 * @return * @throws Exception */ List<GroupFileVo> getGroupFileList(@Param("params") Map<String,String> params); }
28.038462
168
0.664609
3a275b0686be71839348dafbad3d0085d08328ad
4,001
/* * DBeaver - Universal Database Manager * Copyright (C) 2010-2021 DBeaver Corp and others * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.jkiss.dbeaver.model.text.parser.rules; import org.jkiss.code.NotNull; import org.jkiss.dbeaver.model.text.parser.TPCharacterScanner; import org.jkiss.dbeaver.model.text.parser.TPRule; import org.jkiss.dbeaver.model.text.parser.TPToken; import org.jkiss.dbeaver.model.text.parser.TPTokenAbstract; import org.jkiss.utils.CommonUtils; /** * An implementation of <code>IRule</code> detecting a numerical value * with optional decimal part, scientific notation (<code>10e-3</code>) * and support for the hexadecimal base (16). */ public class NumberRule implements TPRule { public static final int RADIX_DECIMAL = 10; public static final int RADIX_HEXADECIMAL = 16; /** * The token to be returned when this rule is successful */ protected TPToken fToken; /** * Creates a rule which will return the specified * token when a numerical sequence is detected. * * @param token the token to be returned */ public NumberRule(@NotNull TPToken token) { fToken = token; } @Override public TPToken evaluate(TPCharacterScanner scanner) { int ch = scanner.read(); int chCount = 1; if (!CommonUtils.isDigit(ch, RADIX_DECIMAL)) { return undefined(scanner, 1); } boolean seenDecimalSeparator = false; boolean seenScientificNotation = false; int radix = RADIX_DECIMAL; if (ch == '0') { int ch1 = scanner.read(); if (ch1 == 'x' || ch1 == 'X') { ch1 = scanner.read(); if (CommonUtils.isDigit(ch1, RADIX_HEXADECIMAL)) { radix = RADIX_HEXADECIMAL; } else { return undefined(scanner, 3); } } else { scanner.unread(); } } while (true) { if (radix == RADIX_DECIMAL && ch == '.') { if (seenDecimalSeparator) { return undefined(scanner, chCount); } ch = scanner.read(); chCount++; if (ch < '0' || ch > '9') { return undefined(scanner, chCount); } seenDecimalSeparator = true; continue; } if (radix == RADIX_DECIMAL && (ch == 'e' || ch == 'E')) { if (seenScientificNotation) { return undefined(scanner, chCount); } ch = scanner.read(); chCount++; if (ch == '+' || ch == '-') { ch = scanner.read(); chCount++; } if (ch < '0' || ch > '9') { return undefined(scanner, chCount); } seenScientificNotation = true; continue; } if (!CommonUtils.isDigit(ch, radix)) { scanner.unread(); return fToken; } ch = scanner.read(); chCount++; } } private static TPToken undefined(TPCharacterScanner scanner, int readCount) { while (readCount > 0) { readCount--; scanner.unread(); } return TPTokenAbstract.UNDEFINED; } }
31.257813
81
0.547863
341c4301c2a32e114682e1faab25e1f6f83e768d
5,765
/* * 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.gridgain.demo.azurefunction.compute; import java.util.HashMap; import java.util.List; import java.util.Map; import javax.cache.Cache; import org.apache.ignite.Ignite; import org.apache.ignite.IgniteCache; import org.apache.ignite.IgniteException; import org.apache.ignite.binary.BinaryObject; import org.apache.ignite.cache.affinity.Affinity; import org.apache.ignite.cache.query.QueryCursor; import org.apache.ignite.cache.query.ScanQuery; import org.apache.ignite.cluster.ClusterNode; import org.apache.ignite.compute.ComputeJob; import org.apache.ignite.compute.ComputeJobResult; import org.apache.ignite.compute.ComputeJobResultPolicy; import org.apache.ignite.compute.ComputeTask; import org.apache.ignite.lang.IgniteBiPredicate; import org.apache.ignite.resources.IgniteInstanceResource; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; /** * Compute task that calculate average population across all the cities of a given country. A destination node that * stores a primary copy of the partition with the cities is calculated during the map phase. After that, a job is sent * for the execution to that only avoiding a broadcast or cluster-wide full-scan operation. */ public class AvgCalculationTask implements ComputeTask<String, String> { @IgniteInstanceResource private Ignite ignite; private int partition; private ClusterNode node; @Override public @NotNull Map<? extends ComputeJob, ClusterNode> map(List<ClusterNode> subgrid, @Nullable String countryCode) throws IgniteException { //Getting a cluster node and a partition that store a primary copy of all the cities with 'countryCode'. Affinity<String> affinity = ignite.affinity("Country"); node = affinity.mapKeyToNode(countryCode); partition = affinity.partition(countryCode); //Scheduling the task for calculation on that primary node only. HashMap<AvgCalculationJob, ClusterNode> executionMap = new HashMap<>(); executionMap.put(new AvgCalculationJob(countryCode, partition), node); return executionMap; } @Override public ComputeJobResultPolicy result(ComputeJobResult res, List<ComputeJobResult> rcvd) throws IgniteException { return ComputeJobResultPolicy.WAIT; } @Nullable @Override public String reduce(List<ComputeJobResult> results) throws IgniteException { //Reducing calculation results - only one result is possible int[] result = results.get(0).getData(); if (result == null) return "Wrong country code, no cities found"; return "Calculation Result [avgPopulation=" + result[0] + ", citiesCount=" + result[1] + ", partition=" + partition + ", nodeId=" + node.id() + ", nodeAddresses=" + node.addresses() + "]"; } /** * Compute job that calculates average population across all the cities of a given country. * The job iterates only over a single data partition. */ private static class AvgCalculationJob implements ComputeJob { @IgniteInstanceResource private Ignite ignite; private String countryCode; private int partition; public AvgCalculationJob(String countryCode, int partition) { this.partition = partition; this.countryCode = countryCode; } @Override public Object execute() throws IgniteException { //Accessing object records with BinaryObject interface that avoids a need of deserialization and doesn't //require to keep models' classes on the server nodes. IgniteCache<BinaryObject, BinaryObject> cities = ignite.cache("City").withKeepBinary(); ScanQuery<BinaryObject, BinaryObject> scanQuery = new ScanQuery<>(partition, new IgniteBiPredicate<BinaryObject, BinaryObject>() { @Override public boolean apply(BinaryObject key, BinaryObject object) { //Filtering out cities of other countries that stored in the same partition. return key.field("CountryCode").equals(countryCode); } }); //Extra hint to Ignite that the data is available locally. scanQuery.setLocal(true); //Calculation average population across the cities. QueryCursor<Cache.Entry<BinaryObject, BinaryObject>> cursor = cities.query(scanQuery); long totalPopulation = 0; int citiesNumber = 0; for (Cache.Entry<BinaryObject, BinaryObject> entry: cursor) { totalPopulation += (int)entry.getValue().field("Population"); citiesNumber++; } return citiesNumber == 0 ? null : new int[] {(int)(totalPopulation/citiesNumber), citiesNumber}; } @Override public void cancel() { System.out.println("Task is cancelled"); } } }
40.598592
119
0.703036
8bfe584e8af4297e777b7e44338fa74e3977218c
490
package com.dnastack.ga4gh.dataconnect.adapter.security; import org.springframework.boot.autoconfigure.condition.ConditionalOnExpression; import org.springframework.context.annotation.Configuration; import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity; @Configuration @ConditionalOnExpression("${app.auth.global-method-security.enabled:true}") @EnableGlobalMethodSecurity(prePostEnabled = true) public class GlobalMethodSecurityConfig { }
40.833333
102
0.865306
0e0963d4faf2ceee0c6c48c2c14e55e853c9196b
47,395
/* *AVISO LEGAL © Copyright *Este programa esta protegido por la ley de derechos de autor. *La reproduccion o distribucion ilicita de este programa o de cualquiera de *sus partes esta penado por la ley con severas sanciones civiles y penales, *y seran objeto de todas las sanciones legales que correspondan. *Su contenido no puede copiarse para fines comerciales o de otras, *ni puede mostrarse, incluso en una version modificada, en otros sitios Web. Solo esta permitido colocar hipervinculos al sitio web. */ package com.bydan.erp.nomina.util; import org.apache.log4j.Logger; import java.sql.Time; import java.sql.Timestamp; import org.apache.poi.ss.usermodel.Workbook; import org.apache.poi.ss.usermodel.Sheet; import org.apache.poi.ss.usermodel.Row; import org.apache.poi.ss.usermodel.Cell; import org.apache.poi.ss.usermodel.CellStyle; import org.apache.poi.ss.usermodel.IndexedColors; import org.apache.poi.ss.util.CellRangeAddress; import javax.swing.border.Border; import java.io.InputStream; import java.util.Scanner; import java.util.List; import java.util.ArrayList; import java.util.Set; import java.util.Date; //import java.util.ArrayList; import com.bydan.framework.erp.business.entity.GeneralEntity; import com.bydan.framework.erp.business.entity.GeneralEntityReturnGeneral; import com.bydan.framework.erp.business.entity.GeneralEntityParameterGeneral; import com.bydan.framework.erp.business.entity.DatoGeneral; import com.bydan.framework.erp.business.entity.OrderBy; import com.bydan.framework.erp.business.entity.Classe; import com.bydan.framework.erp.business.entity.Reporte; import com.bydan.framework.erp.util.ConstantesJsp; import com.bydan.framework.erp.business.dataaccess.ConstantesSql; import com.bydan.erp.nomina.util.CargoGrupoConstantesFunciones; import com.bydan.erp.nomina.util.CargoGrupoParameterReturnGeneral; //import com.bydan.erp.nomina.util.CargoGrupoParameterGeneral; import com.bydan.framework.erp.business.logic.DatosCliente; import com.bydan.framework.erp.util.*; import com.bydan.erp.nomina.business.entity.*; import com.bydan.erp.seguridad.business.entity.*; import com.bydan.erp.contabilidad.business.entity.*; import com.bydan.erp.tesoreria.business.entity.*; import com.bydan.erp.cartera.business.entity.*; import com.bydan.erp.seguridad.util.*; import com.bydan.erp.contabilidad.util.*; import com.bydan.erp.tesoreria.util.*; import com.bydan.erp.cartera.util.*; //import com.bydan.framework.erp.util.*; //import com.bydan.framework.erp.business.logic.*; //import com.bydan.erp.nomina.business.dataaccess.*; //import com.bydan.erp.nomina.business.logic.*; //import java.sql.SQLException; //CONTROL_INCLUDE import com.bydan.erp.seguridad.business.entity.*; @SuppressWarnings("unused") final public class CargoGrupoConstantesFunciones extends CargoGrupoConstantesFuncionesAdditional { public static String S_TIPOREPORTE_EXTRA=""; //USADO MAS EN RELACIONADO PARA MANTENIMIENTO MAESTRO-DETALLE public static Integer TAMANIO_ALTO_MAXIMO_TABLADATOS=Constantes.ISWING_TAMANIOMAXIMO_TABLADATOS; public static Integer TAMANIO_ALTO_MINIMO_TABLADATOS=Constantes.ISWING_TAMANIOMINIMO_TABLADATOS; //PARA TABLA RELACIONES(DESCRIPCION HEIGHTPE_REL_TAB) public static Integer ALTO_TABPANE_RELACIONES=Constantes.ISWING_ALTO_TABPANE + Funciones2.getValorProporcion(Constantes.ISWING_ALTO_TABPANE,0); //PARA TABLA RELACIONADO(DESCRIPTION HEIGHTPE_REL) public static Integer TAMANIO_ALTO_MAXIMO_TABLADATOSREL=Constantes.ISWING_TAMANIOMAXIMO_TABLADATOSREL + Funciones2.getValorProporcion(Constantes.ISWING_TAMANIOMAXIMO_TABLADATOSREL,0); public static Integer TAMANIO_ALTO_MINIMO_TABLADATOSREL=Constantes.ISWING_TAMANIOMINIMO_TABLADATOSREL + Funciones2.getValorProporcion(Constantes.ISWING_TAMANIOMINIMO_TABLADATOSREL,0); //PARA CAMBIAR TODO--> SE CAMBIA EN TABLA RELACIONES Y TABLAS RELACIONADOS /* PARA MANEJAR EL TAB RELACIONES CON TABLA DE DATOS SE DEBE MODIFICAR Y VERIFICAR LOS VALORES CONTANTES: final public static Integer ISWING_TAMANIOMAXIMO_TABLADATOSREL=240;//230;350; final public static Integer ISWING_TAMANIOMINIMO_TABLADATOSREL=240;//230;260 final public static Integer ISWING_ALTO_TABPANE=375;//375;400;260; CASO CONTRARIO, ESTOS VALORES SERIAN PARA CADA CASO (NO CONSTANTES) NOTA: * LA ALINEACION HORIZONTAL,FALTA */ public static final String SFINALQUERY=Constantes.SFINALQUERY; public static final String SNOMBREOPCION="CargoGrupo"; public static final String SPATHOPCION="Nomina"; public static final String SPATHMODULO="nomina/"; public static final String SPERSISTENCECONTEXTNAME=""; public static final String SPERSISTENCENAME="CargoGrupo"+CargoGrupoConstantesFunciones.SPERSISTENCECONTEXTNAME+Constantes.SPERSISTENCECONTEXTNAME; public static final String SEJBNAME="CargoGrupoHomeRemote"; public static final String SEJBNAME_ADDITIONAL="CargoGrupoHomeRemoteAdditional"; //RMI public static final String SLOCALEJBNAME_RMI=CargoGrupoConstantesFunciones.SCHEMA+"_"+CargoGrupoConstantesFunciones.SEJBNAME+"_"+Constantes.SEJBLOCAL;//"erp/CargoGrupoHomeRemote/local" public static final String SREMOTEEJBNAME_RMI=CargoGrupoConstantesFunciones.SCHEMA+"_"+CargoGrupoConstantesFunciones.SEJBNAME+"_"+Constantes.SEJBREMOTE;//remote public static final String SLOCALEJBNAMEADDITIONAL_RMI=CargoGrupoConstantesFunciones.SCHEMA+"_"+CargoGrupoConstantesFunciones.SEJBNAME+Constantes.SEJBADDITIONAL+"_"+Constantes.SEJBLOCAL;//"erp/CargoGrupoHomeRemote/local" public static final String SREMOTEEJBNAMEADDITIONAL_RMI=CargoGrupoConstantesFunciones.SCHEMA+"_"+CargoGrupoConstantesFunciones.SEJBNAME+Constantes.SEJBADDITIONAL+"_"+Constantes.SEJBREMOTE;//remote //RMI //JBOSS5.1 public static final String SLOCALEJBNAME=Constantes.SEJBPACKAGE+Constantes.SEJBSEPARATOR+CargoGrupoConstantesFunciones.SEJBNAME+Constantes.SEJBSEPARATOR+Constantes.SEJBLOCAL;//"erp/CargoGrupoHomeRemote/local" public static final String SREMOTEEJBNAME=Constantes.SEJBPACKAGE+Constantes.SEJBSEPARATOR+CargoGrupoConstantesFunciones.SEJBNAME+Constantes.SEJBSEPARATOR+Constantes.SEJBREMOTE;//remote public static final String SLOCALEJBNAMEADDITIONAL=Constantes.SEJBPACKAGE+Constantes.SEJBSEPARATOR+CargoGrupoConstantesFunciones.SEJBNAME+Constantes.SEJBADDITIONAL+Constantes.SEJBSEPARATOR+Constantes.SEJBLOCAL;//"erp/CargoGrupoHomeRemote/local" public static final String SREMOTEEJBNAMEADDITIONAL=Constantes.SEJBPACKAGE+Constantes.SEJBSEPARATOR+CargoGrupoConstantesFunciones.SEJBNAME+Constantes.SEJBADDITIONAL+Constantes.SEJBSEPARATOR+Constantes.SEJBREMOTE;//remote //JBOSS5.1 public static final String SSESSIONNAME=CargoGrupoConstantesFunciones.OBJECTNAME + Constantes.SSESSIONBEAN; public static final String SSESSIONNAME_FACE=Constantes.SFACE_INI+CargoGrupoConstantesFunciones.SSESSIONNAME + Constantes.SFACE_FIN; public static final String SREQUESTNAME=CargoGrupoConstantesFunciones.OBJECTNAME + Constantes.SREQUESTBEAN; public static final String SREQUESTNAME_FACE=Constantes.SFACE_INI+CargoGrupoConstantesFunciones.SREQUESTNAME + Constantes.SFACE_FIN; public static final String SCLASSNAMETITULOREPORTES="Cargo Grupos"; public static final String SRELATIVEPATH="../../../"; public static final String SCLASSPLURAL="s"; public static final String SCLASSWEBTITULO="Cargo Grupo"; public static final String SCLASSWEBTITULO_LOWER="Cargo Grupo"; public static Integer INUMEROPAGINACION=10; public static Integer ITAMANIOFILATABLA=Constantes.ISWING_ALTO_FILA; public static Boolean ES_DEBUG=false; public static Boolean CON_DESCRIPCION_DETALLADO=false; public static final String CLASSNAME="CargoGrupo"; public static final String OBJECTNAME="cargogrupo"; //PARA FORMAR QUERYS public static final String SCHEMA=Constantes.SCHEMA_NOMINA; public static final String TABLENAME="cargo_grupo"; public static final String SQL_SECUENCIAL=SCHEMA+"."+TABLENAME+"_id_seq"; public static String QUERYSELECT="select cargogrupo from "+CargoGrupoConstantesFunciones.SPERSISTENCENAME+" cargogrupo"; public static String QUERYSELECTNATIVE="select "+CargoGrupoConstantesFunciones.SCHEMA+"."+CargoGrupoConstantesFunciones.TABLENAME+".id,"+CargoGrupoConstantesFunciones.SCHEMA+"."+CargoGrupoConstantesFunciones.TABLENAME+".version_row,"+CargoGrupoConstantesFunciones.SCHEMA+"."+CargoGrupoConstantesFunciones.TABLENAME+".id_empresa,"+CargoGrupoConstantesFunciones.SCHEMA+"."+CargoGrupoConstantesFunciones.TABLENAME+".codigo,"+CargoGrupoConstantesFunciones.SCHEMA+"."+CargoGrupoConstantesFunciones.TABLENAME+".nombre from "+CargoGrupoConstantesFunciones.SCHEMA+"."+CargoGrupoConstantesFunciones.TABLENAME;//+" as "+CargoGrupoConstantesFunciones.TABLENAME; //AUDITORIA public static Boolean ISCONAUDITORIA=false; public static Boolean ISCONAUDITORIADETALLE=true; //GUARDAR SOLO MAESTRO DETALLE FUNCIONALIDAD public static Boolean ISGUARDARREL=false; protected CargoGrupoConstantesFuncionesAdditional cargogrupoConstantesFuncionesAdditional=null; public CargoGrupoConstantesFuncionesAdditional getCargoGrupoConstantesFuncionesAdditional() { return this.cargogrupoConstantesFuncionesAdditional; } public void setCargoGrupoConstantesFuncionesAdditional(CargoGrupoConstantesFuncionesAdditional cargogrupoConstantesFuncionesAdditional) { try { this.cargogrupoConstantesFuncionesAdditional=cargogrupoConstantesFuncionesAdditional; } catch(Exception e) { ; } } public static final String ID=ConstantesSql.ID; public static final String VERSIONROW=ConstantesSql.VERSIONROW; public static final String IDEMPRESA= "id_empresa"; public static final String CODIGO= "codigo"; public static final String NOMBRE= "nombre"; //TITULO CAMPO public static final String LABEL_ID= "Id"; public static final String LABEL_ID_LOWER= "id"; public static final String LABEL_VERSIONROW= "Versionrow"; public static final String LABEL_VERSIONROW_LOWER= "version Row"; public static final String LABEL_IDEMPRESA= "Empresa"; public static final String LABEL_IDEMPRESA_LOWER= "Empresa"; public static final String LABEL_CODIGO= "Codigo"; public static final String LABEL_CODIGO_LOWER= "Codigo"; public static final String LABEL_NOMBRE= "Nombre"; public static final String LABEL_NOMBRE_LOWER= "Nombre"; public static final String SREGEXCODIGO=ConstantesValidacion.SREGEXCADENA; public static final String SMENSAJEREGEXCODIGO=ConstantesValidacion.SVALIDACIONCADENA; public static final String SREGEXNOMBRE=ConstantesValidacion.SREGEXCADENA; public static final String SMENSAJEREGEXNOMBRE=ConstantesValidacion.SVALIDACIONCADENA; public static String getCargoGrupoLabelDesdeNombre(String sNombreColumna) { String sLabelColumna=""; if(sNombreColumna.equals(CargoGrupoConstantesFunciones.IDEMPRESA)) {sLabelColumna=CargoGrupoConstantesFunciones.LABEL_IDEMPRESA;} if(sNombreColumna.equals(CargoGrupoConstantesFunciones.CODIGO)) {sLabelColumna=CargoGrupoConstantesFunciones.LABEL_CODIGO;} if(sNombreColumna.equals(CargoGrupoConstantesFunciones.NOMBRE)) {sLabelColumna=CargoGrupoConstantesFunciones.LABEL_NOMBRE;} if(sLabelColumna.equals("")) { sLabelColumna=sNombreColumna; } return sLabelColumna; } public static String getNombreEjb_JBoss81(String sAplicacion,String sModule,String sClaseEjb,String sInterfaceEjb) throws Exception { String sDescripcion=""; sDescripcion="ejb:"+sAplicacion+"/"+sModule+"/"+sClaseEjb+"!" + sInterfaceEjb; return sDescripcion; } public static String getCargoGrupoDescripcion(CargoGrupo cargogrupo) { String sDescripcion=Constantes.SCAMPONONE; if(cargogrupo !=null/* && cargogrupo.getId()!=0*/) { sDescripcion=cargogrupo.getcodigo();//cargogrupocargogrupo.getcodigo().trim(); } return sDescripcion; } public static String getCargoGrupoDescripcionDetallado(CargoGrupo cargogrupo) { String sDescripcion=""; sDescripcion+=CargoGrupoConstantesFunciones.ID+"="; sDescripcion+=cargogrupo.getId().toString()+","; sDescripcion+=CargoGrupoConstantesFunciones.VERSIONROW+"="; sDescripcion+=cargogrupo.getVersionRow().toString()+","; sDescripcion+=CargoGrupoConstantesFunciones.IDEMPRESA+"="; sDescripcion+=cargogrupo.getid_empresa().toString()+","; sDescripcion+=CargoGrupoConstantesFunciones.CODIGO+"="; sDescripcion+=cargogrupo.getcodigo()+","; sDescripcion+=CargoGrupoConstantesFunciones.NOMBRE+"="; sDescripcion+=cargogrupo.getnombre()+","; return sDescripcion; } public static void setCargoGrupoDescripcion(CargoGrupo cargogrupo,String sValor) throws Exception { if(cargogrupo !=null) { cargogrupo.setcodigo(sValor);;//cargogrupocargogrupo.getcodigo().trim(); } } public static String getEmpresaDescripcion(Empresa empresa) { String sDescripcion=Constantes.SCAMPONONE; if(empresa!=null/*&&empresa.getId()>0*/) { sDescripcion=EmpresaConstantesFunciones.getEmpresaDescripcion(empresa); } return sDescripcion; } public static String getNombreIndice(String sNombreIndice) { if(sNombreIndice.equals("Todos")) { sNombreIndice="Tipo=Todos"; } else if(sNombreIndice.equals("PorId")) { sNombreIndice="Tipo=Por Id"; } else if(sNombreIndice.equals("FK_IdEmpresa")) { sNombreIndice="Tipo= Por Empresa"; } return sNombreIndice; } public static String getDetalleIndicePorId(Long id) { return "Parametros->Porid="+id.toString(); } public static String getDetalleIndiceFK_IdEmpresa(Long id_empresa) { String sDetalleIndice=" Parametros->"; if(id_empresa!=null) {sDetalleIndice+=" Codigo Unico De Empresa="+id_empresa.toString();} return sDetalleIndice; } public static void quitarEspaciosCargoGrupo(CargoGrupo cargogrupo,ArrayList<DatoGeneral> arrDatoGeneral) throws Exception { cargogrupo.setcodigo(cargogrupo.getcodigo().trim()); cargogrupo.setnombre(cargogrupo.getnombre().trim()); } public static void quitarEspaciosCargoGrupos(List<CargoGrupo> cargogrupos,ArrayList<DatoGeneral> arrDatoGeneral) throws Exception { for(CargoGrupo cargogrupo: cargogrupos) { cargogrupo.setcodigo(cargogrupo.getcodigo().trim()); cargogrupo.setnombre(cargogrupo.getnombre().trim()); } } public static void InicializarGeneralEntityAuxiliaresCargoGrupo(CargoGrupo cargogrupo,Boolean conAsignarBase,Boolean conInicializarAuxiliar) throws Exception { if(conAsignarBase && cargogrupo.getConCambioAuxiliar()) { cargogrupo.setIsDeleted(cargogrupo.getIsDeletedAuxiliar()); cargogrupo.setIsNew(cargogrupo.getIsNewAuxiliar()); cargogrupo.setIsChanged(cargogrupo.getIsChangedAuxiliar()); //YA RESTAURO, NO DEBERIA HACERLO NUEVAMENTE AL MENOS NO HASTA GUARDAR OTRA VEZ cargogrupo.setConCambioAuxiliar(false); } if(conInicializarAuxiliar) { cargogrupo.setIsDeletedAuxiliar(false); cargogrupo.setIsNewAuxiliar(false); cargogrupo.setIsChangedAuxiliar(false); cargogrupo.setConCambioAuxiliar(false); } } public static void InicializarGeneralEntityAuxiliaresCargoGrupos(List<CargoGrupo> cargogrupos,Boolean conAsignarBase,Boolean conInicializarAuxiliar) throws Exception { for(CargoGrupo cargogrupo : cargogrupos) { if(conAsignarBase && cargogrupo.getConCambioAuxiliar()) { cargogrupo.setIsDeleted(cargogrupo.getIsDeletedAuxiliar()); cargogrupo.setIsNew(cargogrupo.getIsNewAuxiliar()); cargogrupo.setIsChanged(cargogrupo.getIsChangedAuxiliar()); //YA RESTAURO, NO DEBERIA HACERLO NUEVAMENTE AL MENOS NO HASTA GUARDAR OTRA VEZ cargogrupo.setConCambioAuxiliar(false); } if(conInicializarAuxiliar) { cargogrupo.setIsDeletedAuxiliar(false); cargogrupo.setIsNewAuxiliar(false); cargogrupo.setIsChangedAuxiliar(false); cargogrupo.setConCambioAuxiliar(false); } } } public static void InicializarValoresCargoGrupo(CargoGrupo cargogrupo,Boolean conEnteros) throws Exception { if(conEnteros) { Short ish_value=0; } } public static void InicializarValoresCargoGrupos(List<CargoGrupo> cargogrupos,Boolean conEnteros) throws Exception { for(CargoGrupo cargogrupo: cargogrupos) { if(conEnteros) { Short ish_value=0; } } } public static void TotalizarValoresFilaCargoGrupo(List<CargoGrupo> cargogrupos,CargoGrupo cargogrupoAux) throws Exception { CargoGrupoConstantesFunciones.InicializarValoresCargoGrupo(cargogrupoAux,true); for(CargoGrupo cargogrupo: cargogrupos) { if(cargogrupo.getsType().equals(Constantes2.S_TOTALES)) { continue; } } } public static ArrayList<String> getArrayColumnasGlobalesCargoGrupo(ArrayList<DatoGeneral> arrDatoGeneral) throws Exception { ArrayList<String> arrColumnasGlobales=new ArrayList<String>(); arrColumnasGlobales=CargoGrupoConstantesFunciones.getArrayColumnasGlobalesCargoGrupo(arrDatoGeneral,new ArrayList<String>()); return arrColumnasGlobales; } public static ArrayList<String> getArrayColumnasGlobalesCargoGrupo(ArrayList<DatoGeneral> arrDatoGeneral,ArrayList<String> arrColumnasGlobalesNo) throws Exception { ArrayList<String> arrColumnasGlobales=new ArrayList<String>(); Boolean noExiste=false; noExiste=false; for(String sColumnaGlobalNo:arrColumnasGlobalesNo) { if(sColumnaGlobalNo.equals(CargoGrupoConstantesFunciones.IDEMPRESA)) { noExiste=true; } } if(!noExiste) { arrColumnasGlobales.add(CargoGrupoConstantesFunciones.IDEMPRESA); } return arrColumnasGlobales; } public static ArrayList<String> getArrayColumnasGlobalesNoCargoGrupo(ArrayList<DatoGeneral> arrDatoGeneral) throws Exception { ArrayList<String> arrColumnasGlobales=new ArrayList<String>(); return arrColumnasGlobales; } public static Boolean ExisteEnLista(List<CargoGrupo> cargogrupos,CargoGrupo cargogrupo,Boolean conIdNulo) throws Exception { Boolean existe=false; for(CargoGrupo cargogrupoAux: cargogrupos) { if(cargogrupoAux!=null && cargogrupo!=null) { if((cargogrupoAux.getId()==null && cargogrupo.getId()==null) && conIdNulo) { existe=true; break; } else if(cargogrupoAux.getId()!=null && cargogrupo.getId()!=null){ if(cargogrupoAux.getId().equals(cargogrupo.getId())) { existe=true; break; } } } } return existe; } public static ArrayList<DatoGeneral> getTotalesListaCargoGrupo(List<CargoGrupo> cargogrupos) throws Exception { ArrayList<DatoGeneral> arrTotalesDatoGeneral=new ArrayList<DatoGeneral>(); DatoGeneral datoGeneral=new DatoGeneral(); for(CargoGrupo cargogrupo: cargogrupos) { if(cargogrupo.getsType().equals(Constantes2.S_TOTALES)) { continue; } } return arrTotalesDatoGeneral; } public static ArrayList<OrderBy> getOrderByListaCargoGrupo() throws Exception { ArrayList<OrderBy> arrOrderBy=new ArrayList<OrderBy>(); OrderBy orderBy=new OrderBy(); orderBy=new OrderBy(false,CargoGrupoConstantesFunciones.LABEL_ID, CargoGrupoConstantesFunciones.ID,false,""); arrOrderBy.add(orderBy); orderBy=new OrderBy(false,CargoGrupoConstantesFunciones.LABEL_VERSIONROW, CargoGrupoConstantesFunciones.VERSIONROW,false,""); arrOrderBy.add(orderBy); orderBy=new OrderBy(false,CargoGrupoConstantesFunciones.LABEL_IDEMPRESA, CargoGrupoConstantesFunciones.IDEMPRESA,false,""); arrOrderBy.add(orderBy); orderBy=new OrderBy(false,CargoGrupoConstantesFunciones.LABEL_CODIGO, CargoGrupoConstantesFunciones.CODIGO,false,""); arrOrderBy.add(orderBy); orderBy=new OrderBy(false,CargoGrupoConstantesFunciones.LABEL_NOMBRE, CargoGrupoConstantesFunciones.NOMBRE,false,""); arrOrderBy.add(orderBy); return arrOrderBy; } public static List<String> getTodosTiposColumnasCargoGrupo() throws Exception { List<String> arrTiposColumnas=new ArrayList<String>(); String sTipoColumna=new String(); sTipoColumna=new String(); sTipoColumna=CargoGrupoConstantesFunciones.ID; arrTiposColumnas.add(sTipoColumna); sTipoColumna=new String(); sTipoColumna=CargoGrupoConstantesFunciones.VERSIONROW; arrTiposColumnas.add(sTipoColumna); sTipoColumna=new String(); sTipoColumna=CargoGrupoConstantesFunciones.IDEMPRESA; arrTiposColumnas.add(sTipoColumna); sTipoColumna=new String(); sTipoColumna=CargoGrupoConstantesFunciones.CODIGO; arrTiposColumnas.add(sTipoColumna); sTipoColumna=new String(); sTipoColumna=CargoGrupoConstantesFunciones.NOMBRE; arrTiposColumnas.add(sTipoColumna); return arrTiposColumnas; } public static ArrayList<Reporte> getTiposSeleccionarCargoGrupo() throws Exception { return CargoGrupoConstantesFunciones.getTiposSeleccionarCargoGrupo(false,true,true,true,true); } public static ArrayList<Reporte> getTiposSeleccionarCargoGrupo(Boolean conFk) throws Exception { return CargoGrupoConstantesFunciones.getTiposSeleccionarCargoGrupo(conFk,true,true,true,true); } public static ArrayList<Reporte> getTiposSeleccionarCargoGrupo(Boolean conFk,Boolean conStringColumn,Boolean conValorColumn,Boolean conFechaColumn,Boolean conBitColumn) throws Exception { ArrayList<Reporte> arrTiposSeleccionarTodos=new ArrayList<Reporte>(); Reporte reporte=new Reporte(); if(conFk) { reporte=new Reporte(); reporte.setsCodigo(CargoGrupoConstantesFunciones.LABEL_IDEMPRESA); reporte.setsDescripcion(CargoGrupoConstantesFunciones.LABEL_IDEMPRESA); arrTiposSeleccionarTodos.add(reporte); } if(conStringColumn) { reporte=new Reporte(); reporte.setsCodigo(CargoGrupoConstantesFunciones.LABEL_CODIGO); reporte.setsDescripcion(CargoGrupoConstantesFunciones.LABEL_CODIGO); arrTiposSeleccionarTodos.add(reporte); } if(conStringColumn) { reporte=new Reporte(); reporte.setsCodigo(CargoGrupoConstantesFunciones.LABEL_NOMBRE); reporte.setsDescripcion(CargoGrupoConstantesFunciones.LABEL_NOMBRE); arrTiposSeleccionarTodos.add(reporte); } return arrTiposSeleccionarTodos; } public static ArrayList<Reporte> getTiposRelacionesCargoGrupo(Boolean conEspecial) throws Exception { ArrayList<Reporte> arrTiposRelacionesTodos=new ArrayList<Reporte>(); Reporte reporte=new Reporte(); //ESTO ESTA EN CONTROLLER return arrTiposRelacionesTodos; } public static void refrescarForeignKeysDescripcionesCargoGrupo(CargoGrupo cargogrupoAux) throws Exception { cargogrupoAux.setempresa_descripcion(EmpresaConstantesFunciones.getEmpresaDescripcion(cargogrupoAux.getEmpresa())); } public static void refrescarForeignKeysDescripcionesCargoGrupo(List<CargoGrupo> cargogruposTemp) throws Exception { for(CargoGrupo cargogrupoAux:cargogruposTemp) { cargogrupoAux.setempresa_descripcion(EmpresaConstantesFunciones.getEmpresaDescripcion(cargogrupoAux.getEmpresa())); } } public static ArrayList<Classe> getClassesForeignKeysOfCargoGrupo(ArrayList<Classe> classesP,DeepLoadType deepLoadType)throws Exception { try { ArrayList<Classe> classes=new ArrayList<Classe>(); if(deepLoadType.equals(DeepLoadType.NONE)) { classes.add(new Classe(Empresa.class)); } else if(deepLoadType.equals(DeepLoadType.INCLUDE)) { for(Classe clas:classesP) { if(clas.clas.equals(Empresa.class)) { classes.add(new Classe(Empresa.class)); } } } else if(deepLoadType.equals(DeepLoadType.EXCLUDE)) { } return classes; } catch(Exception e) { //Funciones.manageException(logger,e); throw e; } } public static ArrayList<Classe> getClassesForeignKeysFromStringsOfCargoGrupo(ArrayList<String> arrClasses,DeepLoadType deepLoadType)throws Exception { try { ArrayList<Classe> classes=new ArrayList<Classe>(); if(deepLoadType.equals(DeepLoadType.NONE)) { for(String sClasse:arrClasses) { if(Empresa.class.getSimpleName().equals(sClasse)) { classes.add(new Classe(Empresa.class)); continue; } } } else if(deepLoadType.equals(DeepLoadType.INCLUDE)) { for(String sClasse:arrClasses) { if(Empresa.class.getSimpleName().equals(sClasse)) { classes.add(new Classe(Empresa.class)); continue; } } } else if(deepLoadType.equals(DeepLoadType.EXCLUDE)) { } return classes; } catch(Exception e) { //Funciones.manageException(logger,e); throw e; } } public static ArrayList<Classe> getClassesRelationshipsOfCargoGrupo(ArrayList<Classe> classesP,DeepLoadType deepLoadType)throws Exception { try { return CargoGrupoConstantesFunciones.getClassesRelationshipsOfCargoGrupo(classesP,deepLoadType,true); } catch(Exception e) { //Funciones.manageException(logger,e); throw e; } } public static ArrayList<Classe> getClassesRelationshipsOfCargoGrupo(ArrayList<Classe> classesP,DeepLoadType deepLoadType,Boolean conMuchosAMuchos)throws Exception { try { ArrayList<Classe> classes=new ArrayList<Classe>(); if(deepLoadType.equals(DeepLoadType.NONE)) { classes.add(new Classe(Cargo.class)); } else if(deepLoadType.equals(DeepLoadType.INCLUDE)) { for(Classe clas:classesP) { if(clas.clas.equals(Cargo.class)) { classes.add(new Classe(Cargo.class)); break; } } } else if(deepLoadType.equals(DeepLoadType.EXCLUDE)) { } return classes; } catch(Exception e) { //Funciones.manageException(logger,e); throw e; } } public static ArrayList<Classe> getClassesRelationshipsFromStringsOfCargoGrupo(ArrayList<String> arrClasses,DeepLoadType deepLoadType)throws Exception { try { return CargoGrupoConstantesFunciones.getClassesRelationshipsFromStringsOfCargoGrupo(arrClasses,deepLoadType,true); } catch(Exception e) { //Funciones.manageException(logger,e); throw e; } } public static ArrayList<Classe> getClassesRelationshipsFromStringsOfCargoGrupo(ArrayList<String> arrClasses,DeepLoadType deepLoadType,Boolean conMuchosAMuchos)throws Exception { try { ArrayList<Classe> classes=new ArrayList<Classe>(); if(deepLoadType.equals(DeepLoadType.NONE)) { for(String sClasse:arrClasses) { if(Cargo.class.getSimpleName().equals(sClasse)) { classes.add(new Classe(Cargo.class)); continue; } } } else if(deepLoadType.equals(DeepLoadType.INCLUDE)) { for(String sClasse:arrClasses) { if(Cargo.class.getSimpleName().equals(sClasse)) { classes.add(new Classe(Cargo.class)); continue; } } } else if(deepLoadType.equals(DeepLoadType.EXCLUDE)) { } return classes; } catch(Exception e) { //Funciones.manageException(logger,e); throw e; } } //FUNCIONES CONTROLLER public static void actualizarLista(CargoGrupo cargogrupo,List<CargoGrupo> cargogrupos,Boolean permiteQuitar) throws Exception { try { Boolean existe=false; CargoGrupo cargogrupoEncontrado=null; for(CargoGrupo cargogrupoLocal:cargogrupos) { if(cargogrupoLocal.getId().equals(cargogrupo.getId())) { cargogrupoEncontrado=cargogrupoLocal; cargogrupoLocal.setIsChanged(cargogrupo.getIsChanged()); cargogrupoLocal.setIsNew(cargogrupo.getIsNew()); cargogrupoLocal.setIsDeleted(cargogrupo.getIsDeleted()); cargogrupoLocal.setGeneralEntityOriginal(cargogrupo.getGeneralEntityOriginal()); cargogrupoLocal.setId(cargogrupo.getId()); cargogrupoLocal.setVersionRow(cargogrupo.getVersionRow()); cargogrupoLocal.setid_empresa(cargogrupo.getid_empresa()); cargogrupoLocal.setcodigo(cargogrupo.getcodigo()); cargogrupoLocal.setnombre(cargogrupo.getnombre()); cargogrupoLocal.setCargos(cargogrupo.getCargos()); existe=true; break; } } if(!cargogrupo.getIsDeleted()) { if(!existe) { cargogrupos.add(cargogrupo); } } else { if(cargogrupoEncontrado!=null && permiteQuitar) { cargogrupos.remove(cargogrupoEncontrado); } } } catch(Exception e) { throw e; } } public static void actualizarSelectedLista(CargoGrupo cargogrupo,List<CargoGrupo> cargogrupos) throws Exception { try { for(CargoGrupo cargogrupoLocal:cargogrupos) { if(cargogrupoLocal.getId().equals(cargogrupo.getId())) { cargogrupoLocal.setIsSelected(cargogrupo.getIsSelected()); break; } } } catch(Exception e) { throw e; } } public static void setEstadosInicialesCargoGrupo(List<CargoGrupo> cargogruposAux) throws Exception { //this.cargogruposAux=cargogruposAux; for(CargoGrupo cargogrupoAux:cargogruposAux) { if(cargogrupoAux.getIsChanged()) { cargogrupoAux.setIsChanged(false); } if(cargogrupoAux.getIsNew()) { cargogrupoAux.setIsNew(false); } if(cargogrupoAux.getIsDeleted()) { cargogrupoAux.setIsDeleted(false); } } } public static void setEstadosInicialesCargoGrupo(CargoGrupo cargogrupoAux) throws Exception { //this.cargogrupoAux=cargogrupoAux; if(cargogrupoAux.getIsChanged()) { cargogrupoAux.setIsChanged(false); } if(cargogrupoAux.getIsNew()) { cargogrupoAux.setIsNew(false); } if(cargogrupoAux.getIsDeleted()) { cargogrupoAux.setIsDeleted(false); } } public static void seleccionarAsignar(CargoGrupo cargogrupoAsignar,CargoGrupo cargogrupo) throws Exception { cargogrupoAsignar.setId(cargogrupo.getId()); cargogrupoAsignar.setVersionRow(cargogrupo.getVersionRow()); cargogrupoAsignar.setid_empresa(cargogrupo.getid_empresa()); cargogrupoAsignar.setempresa_descripcion(cargogrupo.getempresa_descripcion()); cargogrupoAsignar.setcodigo(cargogrupo.getcodigo()); cargogrupoAsignar.setnombre(cargogrupo.getnombre()); } public static void inicializarCargoGrupo(CargoGrupo cargogrupo) throws Exception { try { cargogrupo.setId(0L); cargogrupo.setid_empresa(-1L); cargogrupo.setcodigo(""); cargogrupo.setnombre(""); } catch(Exception e) { throw e; } } public static void generarExcelReporteHeaderCargoGrupo(String sTipo,Row row,Workbook workbook) { Cell cell=null; int iCell=0; CellStyle cellStyle = Funciones2.getStyleTitulo(workbook,"PRINCIPAL"); if(sTipo.equals("RELACIONADO")) { iCell++; } cell = row.createCell(iCell++); cell.setCellValue(CargoGrupoConstantesFunciones.LABEL_IDEMPRESA); cell.setCellStyle(cellStyle); cell = row.createCell(iCell++); cell.setCellValue(CargoGrupoConstantesFunciones.LABEL_CODIGO); cell.setCellStyle(cellStyle); cell = row.createCell(iCell++); cell.setCellValue(CargoGrupoConstantesFunciones.LABEL_NOMBRE); cell.setCellStyle(cellStyle); } public static void generarExcelReporteDataCargoGrupo(String sTipo,Row row,Workbook workbook,CargoGrupo cargogrupo,CellStyle cellStyle) throws Exception { Cell cell=null; int iCell=0; if(sTipo.equals("RELACIONADO")) { iCell++; } cell = row.createCell(iCell++); cell.setCellValue(cargogrupo.getempresa_descripcion()); if(cellStyle!=null) { cell.setCellStyle(cellStyle); } cell = row.createCell(iCell++); cell.setCellValue(cargogrupo.getcodigo()); if(cellStyle!=null) { cell.setCellStyle(cellStyle); } cell = row.createCell(iCell++); cell.setCellValue(cargogrupo.getnombre()); if(cellStyle!=null) { cell.setCellStyle(cellStyle); } } //FUNCIONES CONTROLLER public String sFinalQueryCargoGrupo=Constantes.SFINALQUERY; public String getsFinalQueryCargoGrupo() { return this.sFinalQueryCargoGrupo; } public void setsFinalQueryCargoGrupo(String sFinalQueryCargoGrupo) { this.sFinalQueryCargoGrupo= sFinalQueryCargoGrupo; } public Border resaltarSeleccionarCargoGrupo=null; public Border setResaltarSeleccionarCargoGrupo(ParametroGeneralUsuario parametroGeneralUsuario/*CargoGrupoBeanSwingJInternalFrame cargogrupoBeanSwingJInternalFrame*/) { Border borderResaltar=Funciones2.getBorderResaltar(parametroGeneralUsuario,"COLUMNA"); //cargogrupoBeanSwingJInternalFrame.jTtoolBarCargoGrupo.setBorder(borderResaltar); this.resaltarSeleccionarCargoGrupo= borderResaltar; return borderResaltar; } public Border getResaltarSeleccionarCargoGrupo() { return this.resaltarSeleccionarCargoGrupo; } public void setResaltarSeleccionarCargoGrupo(Border borderResaltarSeleccionarCargoGrupo) { this.resaltarSeleccionarCargoGrupo= borderResaltarSeleccionarCargoGrupo; } //RESALTAR,VISIBILIDAD,HABILITAR COLUMNA public Border resaltaridCargoGrupo=null; public Boolean mostraridCargoGrupo=true; public Boolean activaridCargoGrupo=true; public Border resaltarid_empresaCargoGrupo=null; public Boolean mostrarid_empresaCargoGrupo=true; public Boolean activarid_empresaCargoGrupo=true; public Boolean cargarid_empresaCargoGrupo=true;//ConNoLoadForeignKeyColumnOTable=false public Boolean event_dependid_empresaCargoGrupo=false;//ConEventDepend=true public Border resaltarcodigoCargoGrupo=null; public Boolean mostrarcodigoCargoGrupo=true; public Boolean activarcodigoCargoGrupo=true; public Border resaltarnombreCargoGrupo=null; public Boolean mostrarnombreCargoGrupo=true; public Boolean activarnombreCargoGrupo=true; public Border setResaltaridCargoGrupo(ParametroGeneralUsuario parametroGeneralUsuario/*CargoGrupoBeanSwingJInternalFrame cargogrupoBeanSwingJInternalFrame*/) { Border borderResaltar=Funciones2.getBorderResaltar(parametroGeneralUsuario,"COLUMNA"); //cargogrupoBeanSwingJInternalFrame.jTtoolBarCargoGrupo.setBorder(borderResaltar); this.resaltaridCargoGrupo= borderResaltar; return borderResaltar; } public Border getresaltaridCargoGrupo() { return this.resaltaridCargoGrupo; } public void setResaltaridCargoGrupo(Border borderResaltar) { this.resaltaridCargoGrupo= borderResaltar; } public Boolean getMostraridCargoGrupo() { return this.mostraridCargoGrupo; } public void setMostraridCargoGrupo(Boolean mostraridCargoGrupo) { this.mostraridCargoGrupo= mostraridCargoGrupo; } public Boolean getActivaridCargoGrupo() { return this.activaridCargoGrupo; } public void setActivaridCargoGrupo(Boolean activaridCargoGrupo) { this.activaridCargoGrupo= activaridCargoGrupo; } public Border setResaltarid_empresaCargoGrupo(ParametroGeneralUsuario parametroGeneralUsuario/*CargoGrupoBeanSwingJInternalFrame cargogrupoBeanSwingJInternalFrame*/) { Border borderResaltar=Funciones2.getBorderResaltar(parametroGeneralUsuario,"COLUMNA"); //cargogrupoBeanSwingJInternalFrame.jTtoolBarCargoGrupo.setBorder(borderResaltar); this.resaltarid_empresaCargoGrupo= borderResaltar; return borderResaltar; } public Border getresaltarid_empresaCargoGrupo() { return this.resaltarid_empresaCargoGrupo; } public void setResaltarid_empresaCargoGrupo(Border borderResaltar) { this.resaltarid_empresaCargoGrupo= borderResaltar; } public Boolean getMostrarid_empresaCargoGrupo() { return this.mostrarid_empresaCargoGrupo; } public void setMostrarid_empresaCargoGrupo(Boolean mostrarid_empresaCargoGrupo) { this.mostrarid_empresaCargoGrupo= mostrarid_empresaCargoGrupo; } public Boolean getActivarid_empresaCargoGrupo() { return this.activarid_empresaCargoGrupo; } public void setActivarid_empresaCargoGrupo(Boolean activarid_empresaCargoGrupo) { this.activarid_empresaCargoGrupo= activarid_empresaCargoGrupo; } public Boolean getCargarid_empresaCargoGrupo() { return this.cargarid_empresaCargoGrupo; } public void setCargarid_empresaCargoGrupo(Boolean cargarid_empresaCargoGrupo) { this.cargarid_empresaCargoGrupo= cargarid_empresaCargoGrupo; } public Border setResaltarcodigoCargoGrupo(ParametroGeneralUsuario parametroGeneralUsuario/*CargoGrupoBeanSwingJInternalFrame cargogrupoBeanSwingJInternalFrame*/) { Border borderResaltar=Funciones2.getBorderResaltar(parametroGeneralUsuario,"COLUMNA"); //cargogrupoBeanSwingJInternalFrame.jTtoolBarCargoGrupo.setBorder(borderResaltar); this.resaltarcodigoCargoGrupo= borderResaltar; return borderResaltar; } public Border getresaltarcodigoCargoGrupo() { return this.resaltarcodigoCargoGrupo; } public void setResaltarcodigoCargoGrupo(Border borderResaltar) { this.resaltarcodigoCargoGrupo= borderResaltar; } public Boolean getMostrarcodigoCargoGrupo() { return this.mostrarcodigoCargoGrupo; } public void setMostrarcodigoCargoGrupo(Boolean mostrarcodigoCargoGrupo) { this.mostrarcodigoCargoGrupo= mostrarcodigoCargoGrupo; } public Boolean getActivarcodigoCargoGrupo() { return this.activarcodigoCargoGrupo; } public void setActivarcodigoCargoGrupo(Boolean activarcodigoCargoGrupo) { this.activarcodigoCargoGrupo= activarcodigoCargoGrupo; } public Border setResaltarnombreCargoGrupo(ParametroGeneralUsuario parametroGeneralUsuario/*CargoGrupoBeanSwingJInternalFrame cargogrupoBeanSwingJInternalFrame*/) { Border borderResaltar=Funciones2.getBorderResaltar(parametroGeneralUsuario,"COLUMNA"); //cargogrupoBeanSwingJInternalFrame.jTtoolBarCargoGrupo.setBorder(borderResaltar); this.resaltarnombreCargoGrupo= borderResaltar; return borderResaltar; } public Border getresaltarnombreCargoGrupo() { return this.resaltarnombreCargoGrupo; } public void setResaltarnombreCargoGrupo(Border borderResaltar) { this.resaltarnombreCargoGrupo= borderResaltar; } public Boolean getMostrarnombreCargoGrupo() { return this.mostrarnombreCargoGrupo; } public void setMostrarnombreCargoGrupo(Boolean mostrarnombreCargoGrupo) { this.mostrarnombreCargoGrupo= mostrarnombreCargoGrupo; } public Boolean getActivarnombreCargoGrupo() { return this.activarnombreCargoGrupo; } public void setActivarnombreCargoGrupo(Boolean activarnombreCargoGrupo) { this.activarnombreCargoGrupo= activarnombreCargoGrupo; } public void setMostrarCampos(DeepLoadType deepLoadType,ArrayList<Classe> campos)throws Exception { Boolean esInicial=false; Boolean esAsigna=false; if(deepLoadType.equals(DeepLoadType.INCLUDE) || deepLoadType.equals(DeepLoadType.NONE)) { esInicial=false; esAsigna=true; } else if(deepLoadType.equals(DeepLoadType.EXCLUDE)) { esInicial=true; esAsigna=false; } this.setMostraridCargoGrupo(esInicial); this.setMostrarid_empresaCargoGrupo(esInicial); this.setMostrarcodigoCargoGrupo(esInicial); this.setMostrarnombreCargoGrupo(esInicial); for(Classe campo:campos) { if(campo.clase.equals(CargoGrupoConstantesFunciones.ID)) { this.setMostraridCargoGrupo(esAsigna); continue; } if(campo.clase.equals(CargoGrupoConstantesFunciones.IDEMPRESA)) { this.setMostrarid_empresaCargoGrupo(esAsigna); continue; } if(campo.clase.equals(CargoGrupoConstantesFunciones.CODIGO)) { this.setMostrarcodigoCargoGrupo(esAsigna); continue; } if(campo.clase.equals(CargoGrupoConstantesFunciones.NOMBRE)) { this.setMostrarnombreCargoGrupo(esAsigna); continue; } } } public void setActivarCampos(DeepLoadType deepLoadType,ArrayList<Classe> campos)throws Exception { Boolean esInicial=false; Boolean esAsigna=false; if(deepLoadType.equals(DeepLoadType.INCLUDE) || deepLoadType.equals(DeepLoadType.NONE)) { esInicial=false; esAsigna=true; } else if(deepLoadType.equals(DeepLoadType.EXCLUDE)) { esInicial=true; esAsigna=false; } this.setActivaridCargoGrupo(esInicial); this.setActivarid_empresaCargoGrupo(esInicial); this.setActivarcodigoCargoGrupo(esInicial); this.setActivarnombreCargoGrupo(esInicial); for(Classe campo:campos) { if(campo.clase.equals(CargoGrupoConstantesFunciones.ID)) { this.setActivaridCargoGrupo(esAsigna); continue; } if(campo.clase.equals(CargoGrupoConstantesFunciones.IDEMPRESA)) { this.setActivarid_empresaCargoGrupo(esAsigna); continue; } if(campo.clase.equals(CargoGrupoConstantesFunciones.CODIGO)) { this.setActivarcodigoCargoGrupo(esAsigna); continue; } if(campo.clase.equals(CargoGrupoConstantesFunciones.NOMBRE)) { this.setActivarnombreCargoGrupo(esAsigna); continue; } } } public void setResaltarCampos(DeepLoadType deepLoadType,ArrayList<Classe> campos,ParametroGeneralUsuario parametroGeneralUsuario/*,CargoGrupoBeanSwingJInternalFrame cargogrupoBeanSwingJInternalFrame*/)throws Exception { Border esInicial=null; Border esAsigna=null; if(deepLoadType.equals(DeepLoadType.INCLUDE) || deepLoadType.equals(DeepLoadType.NONE)) { esInicial=null; esAsigna=Funciones2.getBorderResaltar(parametroGeneralUsuario,"COLUMNA"); } else if(deepLoadType.equals(DeepLoadType.EXCLUDE)) { esInicial=Funciones2.getBorderResaltar(parametroGeneralUsuario,"COLUMNA"); esAsigna=null; } this.setResaltaridCargoGrupo(esInicial); this.setResaltarid_empresaCargoGrupo(esInicial); this.setResaltarcodigoCargoGrupo(esInicial); this.setResaltarnombreCargoGrupo(esInicial); for(Classe campo:campos) { if(campo.clase.equals(CargoGrupoConstantesFunciones.ID)) { this.setResaltaridCargoGrupo(esAsigna); continue; } if(campo.clase.equals(CargoGrupoConstantesFunciones.IDEMPRESA)) { this.setResaltarid_empresaCargoGrupo(esAsigna); continue; } if(campo.clase.equals(CargoGrupoConstantesFunciones.CODIGO)) { this.setResaltarcodigoCargoGrupo(esAsigna); continue; } if(campo.clase.equals(CargoGrupoConstantesFunciones.NOMBRE)) { this.setResaltarnombreCargoGrupo(esAsigna); continue; } } } public Border resaltarCargoCargoGrupo=null; public Border getResaltarCargoCargoGrupo() { return this.resaltarCargoCargoGrupo; } public void setResaltarCargoCargoGrupo(Border borderResaltarCargo) { if(borderResaltarCargo!=null) { this.resaltarCargoCargoGrupo= borderResaltarCargo; } } public Border setResaltarCargoCargoGrupo(ParametroGeneralUsuario parametroGeneralUsuario/*CargoGrupoBeanSwingJInternalFrame cargogrupoBeanSwingJInternalFrame*/) { Border borderResaltarCargo=Funciones2.getBorderResaltar(parametroGeneralUsuario,"COLUMNA"); //cargogrupoBeanSwingJInternalFrame.jTtoolBarCargoGrupo.setBorder(borderResaltarCargo); this.resaltarCargoCargoGrupo= borderResaltarCargo; return borderResaltarCargo; } public Boolean mostrarCargoCargoGrupo=true; public Boolean getMostrarCargoCargoGrupo() { return this.mostrarCargoCargoGrupo; } public void setMostrarCargoCargoGrupo(Boolean visibilidadResaltarCargo) { this.mostrarCargoCargoGrupo= visibilidadResaltarCargo; } public Boolean activarCargoCargoGrupo=true; public Boolean gethabilitarResaltarCargoCargoGrupo() { return this.activarCargoCargoGrupo; } public void setActivarCargoCargoGrupo(Boolean habilitarResaltarCargo) { this.activarCargoCargoGrupo= habilitarResaltarCargo; } public void setMostrarRelaciones(DeepLoadType deepLoadType,ArrayList<Classe> clases)throws Exception { Boolean esInicial=false; Boolean esAsigna=false; if(deepLoadType.equals(DeepLoadType.INCLUDE) || deepLoadType.equals(DeepLoadType.NONE)) { esInicial=false; esAsigna=true; } else if(deepLoadType.equals(DeepLoadType.EXCLUDE)) { esInicial=true; esAsigna=false; } this.setMostrarCargoCargoGrupo(esInicial); for(Classe clase:clases) { if(clase.clas.equals(Cargo.class)) { this.setMostrarCargoCargoGrupo(esAsigna); continue; } } } public void setActivarRelaciones(DeepLoadType deepLoadType,ArrayList<Classe> clases)throws Exception { Boolean esInicial=false; Boolean esAsigna=false; if(deepLoadType.equals(DeepLoadType.INCLUDE) || deepLoadType.equals(DeepLoadType.NONE)) { esInicial=false; esAsigna=true; } else if(deepLoadType.equals(DeepLoadType.EXCLUDE)) { esInicial=true; esAsigna=false; } this.setActivarCargoCargoGrupo(esInicial); for(Classe clase:clases) { if(clase.clas.equals(Cargo.class)) { this.setActivarCargoCargoGrupo(esAsigna); continue; } } } public void setResaltarRelaciones(DeepLoadType deepLoadType,ArrayList<Classe> clases,ParametroGeneralUsuario parametroGeneralUsuario/*,CargoGrupoBeanSwingJInternalFrame cargogrupoBeanSwingJInternalFrame*/)throws Exception { Border esInicial=null; Border esAsigna=null; if(deepLoadType.equals(DeepLoadType.INCLUDE) || deepLoadType.equals(DeepLoadType.NONE)) { esInicial=null; esAsigna=Funciones2.getBorderResaltar(parametroGeneralUsuario,"COLUMNA"); } else if(deepLoadType.equals(DeepLoadType.EXCLUDE)) { esInicial=Funciones2.getBorderResaltar(parametroGeneralUsuario,"COLUMNA"); esAsigna=null; } this.setResaltarCargoCargoGrupo(esInicial); for(Classe clase:clases) { if(clase.clas.equals(Cargo.class)) { this.setResaltarCargoCargoGrupo(esAsigna); continue; } } } public Boolean mostrarFK_IdEmpresaCargoGrupo=true; public Boolean getMostrarFK_IdEmpresaCargoGrupo() { return this.mostrarFK_IdEmpresaCargoGrupo; } public void setMostrarFK_IdEmpresaCargoGrupo(Boolean visibilidadResaltar) { this.mostrarFK_IdEmpresaCargoGrupo= visibilidadResaltar; } public Boolean activarFK_IdEmpresaCargoGrupo=true; public Boolean getActivarFK_IdEmpresaCargoGrupo() { return this.activarFK_IdEmpresaCargoGrupo; } public void setActivarFK_IdEmpresaCargoGrupo(Boolean habilitarResaltar) { this.activarFK_IdEmpresaCargoGrupo= habilitarResaltar; } public Border resaltarFK_IdEmpresaCargoGrupo=null; public Border getResaltarFK_IdEmpresaCargoGrupo() { return this.resaltarFK_IdEmpresaCargoGrupo; } public void setResaltarFK_IdEmpresaCargoGrupo(Border borderResaltar) { this.resaltarFK_IdEmpresaCargoGrupo= borderResaltar; } public void setResaltarFK_IdEmpresaCargoGrupo(ParametroGeneralUsuario parametroGeneralUsuario/*CargoGrupoBeanSwingJInternalFrame cargogrupoBeanSwingJInternalFrame*/) { Border borderResaltar=Funciones2.getBorderResaltar(parametroGeneralUsuario,"TAB"); this.resaltarFK_IdEmpresaCargoGrupo= borderResaltar; } //CONTROL_FUNCION2 }
33.805278
652
0.763562
7020f9b98f2d483ae273d63bac49c58427e2b9d8
3,203
package org.kohsuke.github; import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; import java.io.IOException; import java.net.URL; import java.util.Date; /** * A comment attached to a commit (or a specific line in a specific file of a commit.) * * @author Kohsuke Kawaguchi * @see GHRepository#listCommitComments() * @see GHCommit#listComments() * @see GHCommit#createComment(String, String, Integer, Integer) */ @SuppressFBWarnings(value = {"UWF_UNWRITTEN_PUBLIC_OR_PROTECTED_FIELD", "UWF_UNWRITTEN_FIELD", "NP_UNWRITTEN_FIELD"}, justification = "JSON API") public class GHCommitComment extends GHObject { private GHRepository owner; String body, html_url, commit_id; Integer line; String path; User user; static class User { // TODO: what if someone who doesn't have an account on GitHub makes a commit? @SuppressFBWarnings(value = "UUF_UNUSED_FIELD", justification = "We don't provide it in API now") String url,avatar_url,gravatar_id; @SuppressFBWarnings(value = "UUF_UNUSED_FIELD", justification = "We don't provide it in API now") int id; String login; } public GHRepository getOwner() { return owner; } /** * URL like 'https://github.com/kohsuke/sandbox-ant/commit/8ae38db0ea5837313ab5f39d43a6f73de3bd9000#commitcomment-1252827' to * show this commit comment in a browser. */ public URL getHtmlUrl() { return GitHub.parseURL(html_url); } public String getSHA1() { return commit_id; } /** * Commit comment in the GitHub flavored markdown format. */ public String getBody() { return body; } /** * A commit comment can be on a specific line of a specific file, if so, this field points to a file. * Otherwise null. */ public String getPath() { return path; } /** * A commit comment can be on a specific line of a specific file, if so, this field points to the line number in the file. * Otherwise -1. */ public int getLine() { return line!=null ? line : -1; } /** * Gets the user who put this comment. */ public GHUser getUser() throws IOException { return owner.root.getUser(user.login); } /** * Gets the commit to which this comment is associated with. */ public GHCommit getCommit() throws IOException { return getOwner().getCommit(getSHA1()); } /** * Updates the body of the commit message. */ public void update(String body) throws IOException { new Requester(owner.root) .with("body", body) .method("PATCH").to(getApiTail(), GHCommitComment.class); this.body = body; } /** * Deletes this comment. */ public void delete() throws IOException { new Requester(owner.root).method("DELETE").to(getApiTail()); } private String getApiTail() { return String.format("/repos/%s/%s/comments/%s",owner.getOwnerName(),owner.getName(),id); } GHCommitComment wrap(GHRepository owner) { this.owner = owner; return this; } }
27.612069
129
0.635654
f6525c97edce1dfa794d6cc5a41164c2013ca0f6
2,625
/* * * * */ package com.cms.template.directive; import java.util.HashMap; import java.util.Map; import org.apache.commons.beanutils.ConvertUtilsBean; import org.apache.commons.lang.ArrayUtils; import com.jfinal.template.Directive; import com.jfinal.template.expr.ast.Assign; import com.jfinal.template.expr.ast.Expr; import com.jfinal.template.expr.ast.ExprList; import com.jfinal.template.stat.Scope; /** * 模板指令 - 基类 * * * */ public abstract class BaseDirective extends Directive { private static final ConvertUtilsBean CONVERT_UTILS = new ConvertUtilsBean(); /** "起始数量"参数名称 */ private static final String START_PARAMETER_NAME = "start"; /** "数量"参数名称 */ private static final String COUNT_PARAMETER_NAME = "count"; /** "排序"参数名称 */ private static final String ORDER_BY_PARAMETER_NAME = "orderBy"; protected Map<String,Expr> params = new HashMap<>(); /** * 设置参数 */ @Override public void setExprList(ExprList exprList) { // TODO Auto-generated method stub super.setExprList(exprList); Expr[] exprArray = exprList.getExprArray(); if(ArrayUtils.isNotEmpty(exprArray)){ for(Expr expr : exprArray){ Assign assign = (Assign)expr; params.put(assign.getId(), expr); } } } /** * 获取参数 * * @param name * 名称 * @param type * 类型 * @return 参数,若不存在则返回null */ @SuppressWarnings("unchecked") protected <T> T getParameter(String name,Class<T> type,Scope scope){ Expr expr = params.get(name); if(expr!=null){ Object value = expr.eval(scope); return (T)CONVERT_UTILS.convert(value, type); } return null; } /** * 获取起始数量 * * @param params * 参数 * @return 起始数量 */ protected Integer getStart(Scope scope){ Expr expr = params.get(START_PARAMETER_NAME); if(expr!=null){ return (Integer)expr.eval(scope); } return null; } /** * 获取数量 * * @param params * 参数 * @return 数量 */ protected Integer getCount(Scope scope){ Expr expr = params.get(COUNT_PARAMETER_NAME); if(expr!=null){ return (Integer)expr.eval(scope); } return null; } /** * 获取排序 * * @param params * 参数 * @return 数量 */ protected String getOrderBy(Scope scope){ Expr expr = params.get(ORDER_BY_PARAMETER_NAME); if(expr!=null){ return (String)expr.eval(scope); } return null; } }
21.694215
81
0.586667
35745b23aa0be43de23cd442b7cd8350d9b31973
460
package ENCAPSULATION.example2.fix; import java.math.BigDecimal; import java.util.Currency; public class Amount { private final BigDecimal value; private final Currency currency; /* For the Love of Immutability */ public Amount(BigDecimal value, Currency currency) { this.value = value; this.currency = currency; } public BigDecimal getValue() { return value; } public Currency getCurrency() { return currency; } }
17.037037
54
0.704348
68f57638d71bc72a0b917c6058029b16f77a4a5f
3,498
/* * Copyright 2015-2017 Emmanuel Keller / QWAZR * <p> * 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 * <p> * http://www.apache.org/licenses/LICENSE-2.0 * <p> * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.qwazr.database; import com.qwazr.cluster.ClusterManager; import com.qwazr.cluster.ClusterServiceInterface; import com.qwazr.server.ApplicationBuilder; import com.qwazr.server.BaseServer; import com.qwazr.server.GenericServer; import com.qwazr.server.GenericServerBuilder; import com.qwazr.server.RestApplication; import com.qwazr.server.WelcomeShutdownService; import com.qwazr.server.configuration.ServerConfiguration; import javax.management.JMException; import javax.servlet.ServletException; import java.io.IOException; import java.net.URISyntaxException; import java.util.HashSet; import java.util.Set; import java.util.concurrent.ExecutorService; public class TableServer implements BaseServer { private final GenericServer server; private final TableServiceBuilder serviceBuilder; public TableServer(final ServerConfiguration serverConfiguration) throws IOException { final TableSingleton tableSingleton = new TableSingleton(serverConfiguration.dataDirectory, null); final ExecutorService executorService = tableSingleton.getExecutorService(); final GenericServerBuilder builder = GenericServer.of(serverConfiguration, executorService); final ApplicationBuilder webServices = ApplicationBuilder.of("/*").classes(RestApplication.JSON_CLASSES). singletons(new WelcomeShutdownService()); final Set<String> services = new HashSet<>(); services.add(ClusterServiceInterface.SERVICE_NAME); services.add(TableServiceInterface.SERVICE_NAME); final ClusterManager clusterManager = new ClusterManager(executorService, serverConfiguration).registerProtocolListener(builder, services); webServices.singletons(clusterManager.getService()); final TableManager tableManager = tableSingleton.getTableManager(); webServices.singletons(tableManager.getService()); serviceBuilder = new TableServiceBuilder(clusterManager, tableManager); builder.getWebServiceContext().jaxrs(webServices); builder.shutdownListener(server -> tableSingleton.close()); server = builder.build(); } public TableServiceBuilder getServiceBuilder() { return serviceBuilder; } public GenericServer getServer() { return server; } private static volatile TableServer INSTANCE; public static synchronized TableServer getInstance() { return INSTANCE; } public static synchronized void main(final String... args) throws IOException, ServletException, JMException { if (INSTANCE != null) shutdown(); INSTANCE = new TableServer(new ServerConfiguration(args)); INSTANCE.start(); } public static synchronized void shutdown() { if (INSTANCE != null) INSTANCE.stop(); INSTANCE = null; } }
37.212766
117
0.739851
b59646a6ddb9aa0e0e57d8ecff412218bd729762
838
package com.jdroid.android.dialog; import android.support.v4.app.FragmentActivity; import com.jdroid.android.R; import com.jdroid.android.utils.ExternalAppsUtils; public class AppInfoDialogFragment extends AlertDialogFragment { public static void show(FragmentActivity fragmentActivity, int titleResId, int messageResId, String permission) { String screenViewName = AppInfoDialogFragment.class.getSimpleName() + "-" + permission; show(fragmentActivity, new AppInfoDialogFragment(), null, fragmentActivity.getString(titleResId), fragmentActivity.getString(messageResId), fragmentActivity.getString(R.string.jdroid_cancel), null, fragmentActivity.getString(R.string.jdroid_deviceSettings), true, screenViewName, null); } @Override protected void onPositiveClick() { ExternalAppsUtils.openAppInfo(getActivity()); } }
38.090909
141
0.810263
857bd4b12d62bdebb4bfa9861dca6e9d0b8794cb
2,509
package com.taoswork.tallycheck.descriptor.metadata.processor.handler.fields.basics; import com.taoswork.tallycheck.datadomain.base.presentation.FieldType; import com.taoswork.tallycheck.datadomain.base.presentation.typed.DateCellMode; import com.taoswork.tallycheck.datadomain.base.presentation.typed.DateMode; import com.taoswork.tallycheck.datadomain.base.presentation.typed.PresentationDate; import com.taoswork.tallycheck.descriptor.metadata.fieldmetadata.FieldMetaMediate; import com.taoswork.tallycheck.descriptor.metadata.fieldmetadata.basic.DateFieldMeta; import com.taoswork.tallycheck.descriptor.metadata.processor.ProcessResult; import com.taoswork.tallycheck.descriptor.metadata.processor.handler.basic.BaseFieldHandler; import java.lang.reflect.Field; import java.util.Date; /** * Created by Gao Yuan on 2015/5/25. */ class _DateFieldHandler extends BaseFieldHandler { private boolean fits(Field field, FieldMetaMediate metaMediate) { boolean firstCheck = false; if (FieldType.DATE.equals(metaMediate.getBasicFieldMetaObject().getFieldType())) { firstCheck = true; } if (field.isAnnotationPresent(PresentationDate.class)) { firstCheck = true; } if (firstCheck) { Class fieldJavaType = field.getType(); if (Date.class.equals(fieldJavaType) || Long.class.equals(fieldJavaType)) { return true; } else { return false; } } return false; } @Override protected boolean canProcess(Field field, FieldMetaMediate metaMediate) { return fits(field, metaMediate); } @Override protected ProcessResult doProcess(Field field, FieldMetaMediate metaMediate) { DateFieldMeta.Seed dateFieldSeed = null; PresentationDate presentationBoolean = field.getDeclaredAnnotation(PresentationDate.class); boolean useJavaDate = Date.class.equals(field.getType()); DateMode model = DateMode.DateTime; DateCellMode cellModel = DateCellMode.DateAndTime; if (presentationBoolean != null) { model = presentationBoolean.mode(); cellModel = presentationBoolean.cellMode(); } dateFieldSeed = new DateFieldMeta.Seed(model, cellModel, useJavaDate); if (dateFieldSeed != null) { metaMediate.setMetaSeed(dateFieldSeed); return ProcessResult.HANDLED; } return ProcessResult.FAILED; } }
39.203125
99
0.706656
c4cb39a6e8fc8526225f1fe7106763f189cba96c
1,356
package io.github.scottleedavis.mattermost.slashjira.io; import com.atlassian.jira.rest.client.api.JiraRestClient; import com.atlassian.jira.rest.client.api.domain.Issue; import com.atlassian.jira.rest.client.internal.async.AsynchronousJiraRestClientFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.stereotype.Service; import java.net.URI; @Service public class JiraService { private String username; private String password; private String url; private JiraRestClient jiraRestClient; @Autowired public JiraService(@Value("${jira.username}") String username, @Value("${jira.password}") String password, @Value("${jira.url}") String url) { this.username = username; this.password = password; this.url = url; this.jiraRestClient = getJiraRestClient(); } public Issue getIssue(String key) { return jiraRestClient.getIssueClient().getIssue(key).claim(); } private JiraRestClient getJiraRestClient() { return new AsynchronousJiraRestClientFactory().createWithBasicHttpAuthentication(getJiraUri(), this.username, this.password); } private URI getJiraUri() { return URI.create(this.url); } }
32.285714
133
0.713864
be35f733bd8a0a183dadea6a527ae58f696042ef
1,626
/* * 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 co.edu.uniandes.csw.maratones.entities; import java.io.Serializable; import java.util.Date; import javax.persistence.CascadeType; import javax.persistence.Entity; import javax.persistence.ManyToOne; import javax.persistence.Temporal; import javax.persistence.TemporalType; import uk.co.jemos.podam.common.PodamExclude; /** * * @author c.mendez11 */ @Entity public class PublicacionEntity extends BaseEntity implements Serializable{ @Temporal(TemporalType.DATE) private Date fecha; private String texto; @PodamExclude @ManyToOne(cascade = CascadeType.PERSIST) private BlogEntity blog; public PublicacionEntity(){ } /** * @return the fecha */ public Date getFecha() { return fecha; } /** * @param fecha the fecha to set */ public void setFecha(Date fecha) { this.fecha = fecha; } /** * @return the texto */ public String getTexto() { return texto; } /** * @param texto the texto to set */ public void setTexto(String texto) { this.texto = texto; } /** * @return the blog */ public BlogEntity getBlog() { return blog; } /** * @param blog the blog to set */ public void setBlog(BlogEntity blog) { this.blog = blog; } }
21.116883
80
0.600861
41cb94a17a98acec74952942f50f14676d5f1836
645
package com.DesignPattern.VisitorPattern.demo1; /** * Demo 1: 不使用 Visitor Pattern 访问者模式 */ public class Demo1 { public static void main(String[] args) { Goods clothes = new Clothes("Green", 22.3); Goods pc = new Pc("Black", 3333.33); System.out.println("Demo1: 不使用 Visitor Pattern 访问者模式"); System.out.println("\n-------------- Test 1 --------------"); People man = new Man(); man.visit(clothes); man.visit(pc); System.out.println("\n-------------- Test 2 --------------"); People woman = new Woman(); woman.visit(clothes); woman.visit(pc); } }
28.043478
69
0.531783
f3f86591a08c0e4a6530c68b66218ba5e6c0e2ee
513
package org.reasm.commons.messages; import org.reasm.AssemblyErrorMessage; /** * An error message that is generated during an assembly when there is a syntax error in an effective address. * * @author Francis Gagné */ public class SyntaxErrorInEffectiveAddressErrorMessage extends AssemblyErrorMessage { /** * Initializes a new SyntaxErrorInEffectiveAddressErrorMessage. */ public SyntaxErrorInEffectiveAddressErrorMessage() { super("Syntax error in effective address"); } }
25.65
110
0.752437
3efd28207e16a1d240d045c3db69d513a4258a10
531
package org.sorcerers.asm; import java.io.DataInputStream; import java.io.FileInputStream; import java.io.IOException; public class BytecodeVersionChecker { public static int checkClassVersion(String filename) throws IOException { DataInputStream in = new DataInputStream(new FileInputStream(filename)); int magic = in.readInt(); if (magic != 0xcafebabe) { System.out.println(filename + " is not a valid class!"); } in.readUnsignedShort(); int major = in.readUnsignedShort(); in.close(); return major; } }
24.136364
74
0.741996
a8d8cae1278b0cccec38afeec3078ffe5f4396d0
3,971
package com.github.TKnudsen.ComplexDataObject.model.processors.features.mixedData; import java.util.ArrayList; import java.util.HashMap; import java.util.LinkedHashSet; import java.util.List; import java.util.Map; import java.util.Set; import com.github.TKnudsen.ComplexDataObject.data.features.Feature; import com.github.TKnudsen.ComplexDataObject.data.features.FeatureType; import com.github.TKnudsen.ComplexDataObject.data.features.Features; import com.github.TKnudsen.ComplexDataObject.data.features.mixedData.MixedDataFeatureContainer; import com.github.TKnudsen.ComplexDataObject.data.features.mixedData.MixedDataFeatureTools; import com.github.TKnudsen.ComplexDataObject.data.features.mixedData.MixedDataFeatureVector; import com.github.TKnudsen.ComplexDataObject.model.processors.complexDataObject.DataProcessingCategory; /** * <p> * Title: Feature * </p> * * <p> * Description: two goals: * * (1) achieve equal size of all featureVectors * * (2) guarantee same order * </p> * * <p> * Copyright: Copyright (c) 2017 * </p> * * @author Juergen Bernard * @version 1.01 */ public class IdenticalFeaturesProvider implements IMixedDataFeatureVectorProcessor { @Override public void process(List<MixedDataFeatureVector> data) { Set<String> featureNames = new LinkedHashSet<>(); Map<String, FeatureType> featureTypes = new HashMap<>(); for (MixedDataFeatureVector fv : data) for (Feature<?> f : fv.getVectorRepresentation()) featureNames.add(f.getFeatureName()); for (String featureName : featureNames) featureTypes.put(featureName, guessFeatureType(featureName, data)); List<String> names = new ArrayList<>(featureNames); for (MixedDataFeatureVector fv : data) { for (int i = 0; i < names.size(); i++) { String featureName = names.get(i); FeatureType featureType = featureTypes.get(featureName); if (fv.sizeOfFeatures() <= i) fv.addFeature( MixedDataFeatureTools.convert(Features.createDefaultFeature(featureName, featureType))); else if (fv.getFeature(i) == null || fv.getFeature(i).getFeatureName() == null) { fv.removeFeature(i); fv.setFeature(i, MixedDataFeatureTools.convert(Features.createDefaultFeature(featureName, featureType))); } else if (!fv.getFeature(i).getFeatureName().equals(featureName)) { Feature<?> feature = fv.getFeature(featureName); if (feature == null) fv.setFeature(i, MixedDataFeatureTools.convert(Features.createDefaultFeature(featureName, featureType))); else fv.setFeature(i, fv.removeFeature(featureName)); } } } } @Override public void process(MixedDataFeatureContainer container) { process(new ArrayList<>(container.values())); } /** * guesses the type of a feature, according to the number of occurrences in a * list of featureVectors. * * @param featureName * @param featureVectors * @return */ private FeatureType guessFeatureType(String featureName, List<MixedDataFeatureVector> featureVectors) { Map<FeatureType, Integer> counts = new HashMap<>(); for (MixedDataFeatureVector fv : featureVectors) if (fv.getFeature(featureName) != null && fv.getFeature(featureName).getFeatureType() != null) if (counts.get(fv.getFeature(featureName).getFeatureType()) == null) counts.put(fv.getFeature(featureName).getFeatureType(), new Integer(0)); else counts.put(fv.getFeature(featureName).getFeatureType(), counts.get(fv.getFeature(featureName).getFeatureType()) + 1); FeatureType ret = null; Integer maxCount = 0; for (FeatureType featureType : counts.keySet()) if (counts.get(featureType) > maxCount) { maxCount = counts.get(featureType); ret = featureType; } return ret; } @Override public DataProcessingCategory getPreprocessingCategory() { return DataProcessingCategory.DATA_CLEANING; } }
34.530435
105
0.716444
8ab3d0a266e1930e3ae6964c19858beb9a2a7c2b
692
package es.upm.miw.apaw_practice.domain.models.vet_clinic; public class VetLeaf implements VetComponent { private final Vet vet; public VetLeaf(Vet vet) { this.vet = vet; } public Vet getVet() { return this.vet; } @Override public boolean isComposite() { return false; } @Override public void add(VetComponent vetTree) { throw new UnsupportedOperationException("Unsupported operation: can not 'add' anything to a 'Leaf'."); } @Override public void remove(VetComponent vetTree) { //do nothing because it is a leaf } @Override public int numberOfNodes() { return 1; } }
19.771429
110
0.627168
1ac563202e47d3f461b6de4aba788f3773328bb6
8,915
// Copyright 2009 Google Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package com.google.gwtorm.protobuf; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertSame; import static org.junit.Assert.assertTrue; import com.google.gwtorm.client.Column; import com.google.gwtorm.data.Address; import com.google.gwtorm.data.Person; import com.google.protobuf.CodedInputStream; import com.google.protobuf.CodedOutputStream; import org.junit.Test; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.UnsupportedEncodingException; import java.nio.ByteBuffer; import java.util.ArrayList; import java.util.List; import java.util.SortedSet; import java.util.TreeSet; public class ProtobufEncoderTest { private static final byte[] testingBin = new byte[] { // // name 0x0a, 0x09, // name.name 0x0a, 0x07, 0x74, 0x65, 0x73, 0x74, 0x69, 0x6e, 0x67, // // age 0x10, (byte) 75, // // registered (true) 0x18, 0x01 // // }; @SuppressWarnings("cast") @Test public void testPerson() throws UnsupportedEncodingException { final ProtobufCodec<Person> e = CodecFactory.encoder(Person.class); Person p = e.decode(testingBin); assertNotNull(p); assertTrue(p instanceof Person); assertEquals("testing", p.name()); assertEquals(75, p.age()); assertTrue(p.isRegistered()); final byte[] out = e.encodeToByteArray(p); assertEquals(asString(testingBin), asString(out)); assertEquals(testingBin.length, e.sizeof(p)); } @Test public void testAddress() { final ProtobufCodec<Address> e = CodecFactory.encoder(Address.class); Address a = e.decode(new byte[0]); assertNotNull(a); assertNull(a.location()); Person.Key k = new Person.Key("bob"); Person p = new Person(k, 42); Address b = new Address(new Address.Key(k, "ny"), "ny"); byte[] act = e.encodeToByteArray(b); Address c = e.decode(act); assertEquals(c.location(), b.location()); assertEquals(c.city(), b.city()); assertEquals(c.key(), b.key()); } @Test public void testDecodeEmptiesByteBuffer() { ProtobufCodec<Person> e = CodecFactory.encoder(Person.class); ByteBuffer buf = ByteBuffer.wrap(testingBin); Person p = e.decode(buf); assertEquals(0, buf.remaining()); assertEquals(testingBin.length, buf.position()); } @Test public void testEncodeFillsByteBuffer() throws UnsupportedEncodingException { ProtobufCodec<Person> e = CodecFactory.encoder(Person.class); Person p = new Person(new Person.Key("testing"), 75); p.register(); int sz = e.sizeof(p); assertEquals(testingBin.length, sz); ByteBuffer buf = ByteBuffer.allocate(sz); e.encode(p, buf); assertEquals(0, buf.remaining()); assertEquals(sz, buf.position()); buf.flip(); byte[] act = new byte[sz]; buf.get(act); assertEquals(asString(testingBin), asString(act)); } @Test public void testEncodeNonArrayByteBuffer() throws UnsupportedEncodingException { ProtobufCodec<Person> e = CodecFactory.encoder(Person.class); Person p = new Person(new Person.Key("testing"), 75); p.register(); int sz = e.sizeof(p); assertEquals(testingBin.length, sz); ByteBuffer buf = ByteBuffer.allocateDirect(sz); assertFalse("direct ByteBuffer has no array", buf.hasArray()); e.encode(p, buf); assertEquals(0, buf.remaining()); assertEquals(sz, buf.position()); buf.flip(); byte[] act = new byte[sz]; buf.get(act); assertEquals(asString(testingBin), asString(act)); } @Test public void testStringList() throws UnsupportedEncodingException { ProtobufCodec<StringList> e = CodecFactory.encoder(StringList.class); StringList list = new StringList(); list.list = new ArrayList<String>(); list.list.add("moe"); list.list.add("larry"); byte[] act = e.encodeToByteArray(list); StringList other = e.decode(act); assertNotNull(other.list); assertEquals(list.list, other.list); assertEquals(asString(new byte[] { // // 0x12, 0x03, 'm', 'o', 'e', // 0x12, 0x05, 'l', 'a', 'r', 'r', 'y' // }), asString(act)); } @Test public void testStringSet() throws UnsupportedEncodingException { ProtobufCodec<StringSet> e = CodecFactory.encoder(StringSet.class); StringSet list = new StringSet(); list.list = new TreeSet<String>(); list.list.add("larry"); list.list.add("moe"); byte[] act = e.encodeToByteArray(list); StringSet other = e.decode(act); assertNotNull(other.list); assertEquals(list.list, other.list); assertEquals(asString(new byte[] { // // 0x0a, 0x05, 'l', 'a', 'r', 'r', 'y', // 0x0a, 0x03, 'm', 'o', 'e' // }), asString(act)); } @Test public void testPersonList() { ProtobufCodec<PersonList> e = CodecFactory.encoder(PersonList.class); PersonList list = new PersonList(); list.people = new ArrayList<Person>(); list.people.add(new Person(new Person.Key("larry"), 1 << 16)); list.people.add(new Person(new Person.Key("curly"), 1)); list.people.add(new Person(new Person.Key("moe"), -1)); PersonList other = e.decode(e.encodeToByteArray(list)); assertNotNull(other.people); assertEquals(list.people, other.people); } @Test public void testCustomEncoderList() { ProtobufCodec<ItemList> e = CodecFactory.encoder(ItemList.class); ItemList list = new ItemList(); list.list = new ArrayList<Item>(); list.list.add(new Item()); list.list.add(new Item()); ItemList other = e.decode(e.encodeToByteArray(list)); assertNotNull(other.list); assertEquals(2, other.list.size()); } @Test public void testEnumEncoder() throws UnsupportedEncodingException { assertEquals(1, ThingWithEnum.Type.B.ordinal()); assertSame(ThingWithEnum.Type.B, ThingWithEnum.Type.values()[1]); ProtobufCodec<ThingWithEnum> e = CodecFactory.encoder(ThingWithEnum.class); ThingWithEnum thing = new ThingWithEnum(); thing.type = ThingWithEnum.Type.B; ThingWithEnum other = e.decode(e.encodeToByteArray(thing)); assertNotNull(other.type); assertSame(thing.type, other.type); byte[] act = e.encodeToByteArray(thing); byte[] exp = {0x08, 0x01}; assertEquals(asString(exp), asString(act)); } @Test public void testEncodeToStream()throws IOException { ProtobufCodec<ThingWithEnum> e = CodecFactory.encoder(ThingWithEnum.class); ThingWithEnum thing = new ThingWithEnum(); thing.type = ThingWithEnum.Type.B; ByteArrayOutputStream out = new ByteArrayOutputStream(); e.encodeWithSize(thing, out); byte[] exp = {0x02, 0x08, 0x01}; assertEquals(asString(exp), asString(out.toByteArray())); byte[] exp2 = {0x02, 0x08, 0x01, '\n'}; ByteArrayInputStream in = new ByteArrayInputStream(exp2); ThingWithEnum other = e.decodeWithSize(in); assertTrue('\n' == in.read()); assertTrue(-1 == in.read()); assertNotNull(other.type); assertSame(thing.type, other.type); } private static String asString(byte[] bin) throws UnsupportedEncodingException { return new String(bin, "ISO-8859-1"); } static class PersonList { @Column(id = 5) public List<Person> people; } static class StringList { @Column(id = 2) List<String> list; } static class StringSet { @Column(id = 1) SortedSet<String> list; } static class Item { } static class ItemCodec extends ProtobufCodec<Item> { @Override public void encode(Item obj, CodedOutputStream out) throws IOException { out.writeBoolNoTag(true); } @Override public void mergeFrom(CodedInputStream in, Item obj) throws IOException { in.readBool(); } @Override public Item newInstance() { return new Item(); } @Override public int sizeof(Item obj) { return 1; } } static class ItemList { @Column(id = 2) @CustomCodec(ItemCodec.class) List<Item> list; } static class ThingWithEnum { static enum Type { A, B; } @Column(id = 1) Type type; } }
28.034591
79
0.671116
553396b1e80164fc52827879d4fb672a724f1d2c
21,701
package com.cactusteam.money.sync; import com.cactusteam.money.sync.changes.ChangeItem; import com.cactusteam.money.sync.changes.ChangesApplier; import com.cactusteam.money.sync.changes.ChangesList; import com.cactusteam.money.sync.changes.ChangesListProvider; import com.cactusteam.money.sync.changes.IChangesStorage; import com.cactusteam.money.sync.changes.ObjectWrapper; import com.cactusteam.money.sync.model.SyncAccount; import com.cactusteam.money.sync.model.SyncBudget; import com.cactusteam.money.sync.model.SyncCategory; import com.cactusteam.money.sync.model.SyncDebt; import com.cactusteam.money.sync.model.SyncDebtNote; import com.cactusteam.money.sync.model.SyncObject; import com.cactusteam.money.sync.model.SyncPattern; import com.cactusteam.money.sync.model.SyncSubcategory; import com.cactusteam.money.sync.model.SyncTransaction; import java.util.ArrayList; import java.util.HashMap; import java.util.Iterator; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.UUID; /** * @author vpotapenko */ public class SyncJobsExecutor { private static final int LOCK_TRIES = 10; private static final int TIMEOUT_MILLIS = 5000; private final Map<Integer, ChangesListProvider> listProviders = new HashMap<>(); private final IProxyDatabase proxyDatabase; private final ILogger logger; private String deviceId; private ChangesApplier changesApplier; public SyncJobsExecutor(IProxyDatabase proxyDatabase, IChangesStorage logStorage, ILogger logger, String deviceId) { this.proxyDatabase = proxyDatabase; this.logger = logger; this.deviceId = deviceId; listProviders.put(SyncConstants.ACCOUNT_TYPE, new ChangesListProvider("accounts", logStorage)); listProviders.put(SyncConstants.CATEGORY_TYPE, new ChangesListProvider("categories", logStorage)); listProviders.put(SyncConstants.SUBCATEGORY_TYPE, new ChangesListProvider("subcategories", logStorage)); listProviders.put(SyncConstants.DEBT_TYPE, new ChangesListProvider("debts", logStorage)); listProviders.put(SyncConstants.DEBT_NOTE_TYPE, new ChangesListProvider("debt_notes", logStorage)); listProviders.put(SyncConstants.TRANSACTION_TYPE, new ChangesListProvider("transactions", logStorage)); listProviders.put(SyncConstants.PATTERN_TYPE, new ChangesListProvider("patterns", logStorage)); listProviders.put(SyncConstants.BUDGET_TYPE, new ChangesListProvider("budgets", logStorage)); } public List<SyncJob<Boolean>> createCheckJobs() { List<SyncJob<Boolean>> jobs = new LinkedList<>(); jobs.add(new SyncJob<Boolean>() { @Override protected Boolean doJob() throws Exception { return proxyDatabase.hasDirtyAccounts() || checkListItems(SyncConstants.ACCOUNT_TYPE); } }); jobs.add(new SyncJob<Boolean>() { @Override protected Boolean doJob() throws Exception { return proxyDatabase.hasDirtyCategories() || checkListItems(SyncConstants.CATEGORY_TYPE); } }); jobs.add(new SyncJob<Boolean>() { @Override protected Boolean doJob() throws Exception { return proxyDatabase.hasDirtySubcategories() || checkListItems(SyncConstants.SUBCATEGORY_TYPE); } }); jobs.add(new SyncJob<Boolean>() { @Override protected Boolean doJob() throws Exception { return proxyDatabase.hasDirtyDebts() || checkListItems(SyncConstants.DEBT_TYPE); } }); jobs.add(new SyncJob<Boolean>() { @Override protected Boolean doJob() throws Exception { return proxyDatabase.hasDirtyDebtNotes() || checkListItems(SyncConstants.DEBT_NOTE_TYPE); } }); jobs.add(new SyncJob<Boolean>() { @Override protected Boolean doJob() throws Exception { return proxyDatabase.hasDirtyTransactions() || checkListItems(SyncConstants.TRANSACTION_TYPE); } }); jobs.add(new SyncJob<Boolean>() { @Override protected Boolean doJob() throws Exception { return proxyDatabase.hasDirtyPatterns() || checkListItems(SyncConstants.PATTERN_TYPE); } }); jobs.add(new SyncJob<Boolean>() { @Override protected Boolean doJob() throws Exception { return proxyDatabase.hasDirtyBudgets() || checkListItems(SyncConstants.BUDGET_TYPE); } }); return jobs; } public List<SyncJob<Object>> createSyncJobs() { // order is important, sync objects have dependencies List<SyncJob<Object>> jobs = new LinkedList<>(); jobs.add(new SyncJob<Object>() { @Override protected Object doJob() throws Exception { syncAccounts(); return null; } }); jobs.add(new SyncJob<Object>() { @Override protected Object doJob() throws Exception { syncCategories(); return null; } }); jobs.add(new SyncJob<Object>() { @Override protected Object doJob() throws Exception { syncSubcategories(); return null; } }); jobs.add(new SyncJob<Object>() { @Override protected Object doJob() throws Exception { syncDebts(); return null; } }); jobs.add(new SyncJob<Object>() { @Override protected Object doJob() throws Exception { syncDebtNotes(); return null; } }); jobs.add(new SyncJob<Object>() { @Override protected Object doJob() throws Exception { syncBudgets(); return null; } }); jobs.add(new SyncJob<Object>() { @Override protected Object doJob() throws Exception { syncTransactions(); return null; } }); jobs.add(new SyncJob<Object>() { @Override protected Object doJob() throws Exception { syncPatterns(); return null; } }); return jobs; } private boolean checkListItems(int type) throws Exception { ChangesListProvider changesListProvider = listProviders.get(type); String lockId = generateLockId(); boolean locked = changesListProvider.lock(lockId); for (int i = 0; i < LOCK_TRIES && !locked; i++) { Thread.sleep(TIMEOUT_MILLIS); locked = changesListProvider.lock(lockId); } try { ChangesList log = changesListProvider.getCurrentList(); if (log == null) return false; for (ChangeItem item : log.items) { if (!proxyDatabase.alreadyApplied(type, item.id)) return true; } } finally { changesListProvider.unlock(lockId); } return false; } void syncBudgets() throws Exception { int type = SyncConstants.BUDGET_TYPE; ChangesListProvider changesListProvider = listProviders.get(type); String lockId = lockJournal(type, changesListProvider); try { downloadBudgets(); uploadBudgets(); } finally { changesListProvider.unlock(lockId); } } void uploadBudgets() throws Exception { ChangesListProvider changesListProvider = listProviders.get(SyncConstants.BUDGET_TYPE); ChangesList currentList = changesListProvider.getCurrentList(); List<SyncBudget> dirtyBudgets = proxyDatabase.getDirtyBudgets(currentList); if (dirtyBudgets.isEmpty()) return; uploadDirtyObjects(dirtyBudgets, SyncConstants.BUDGET_TYPE, currentList, "budgets"); } void downloadBudgets() throws Exception { ChangesListProvider changesListProvider = listProviders.get(SyncConstants.BUDGET_TYPE); List<ChangeItem> items = downloadItems(changesListProvider, "budgets"); getChangesApplier().execute(proxyDatabase, items); } void syncPatterns() throws Exception { int type = SyncConstants.PATTERN_TYPE; ChangesListProvider changesListProvider = listProviders.get(type); String lockId = lockJournal(type, changesListProvider); try { downloadPatterns(); uploadPatterns(); } finally { changesListProvider.unlock(lockId); } } void uploadPatterns() throws Exception { List<SyncPattern> dirtyPatterns = proxyDatabase.getDirtyPatterns(); if (dirtyPatterns.isEmpty()) return; ChangesListProvider changesListProvider = listProviders.get(SyncConstants.PATTERN_TYPE); ChangesList list = changesListProvider.getCurrentList(); uploadDirtyObjects(dirtyPatterns, SyncConstants.PATTERN_TYPE, list, "patterns"); } void downloadPatterns() throws Exception { ChangesListProvider changesListProvider = listProviders.get(SyncConstants.PATTERN_TYPE); List<ChangeItem> items = downloadItems(changesListProvider, "patterns"); getChangesApplier().execute(proxyDatabase, items); } void syncDebts() throws Exception { int type = SyncConstants.DEBT_TYPE; ChangesListProvider changesListProvider = listProviders.get(type); String lockId = lockJournal(type, changesListProvider); try { downloadDebts(); uploadDebts(); } finally { changesListProvider.unlock(lockId); } } void uploadDebts() throws Exception { List<SyncDebt> dirtyDebts = proxyDatabase.getDirtyDebts(); if (dirtyDebts.isEmpty()) return; ChangesListProvider changesListProvider = listProviders.get(SyncConstants.DEBT_TYPE); ChangesList list = changesListProvider.getCurrentList(); uploadDirtyObjects(dirtyDebts, SyncConstants.DEBT_TYPE, list, "debts"); } void downloadDebts() throws Exception { ChangesListProvider changesListProvider = listProviders.get(SyncConstants.DEBT_TYPE); List<ChangeItem> items = downloadItems(changesListProvider, "debts"); getChangesApplier().execute(proxyDatabase, items); } void syncDebtNotes() throws Exception { int type = SyncConstants.DEBT_NOTE_TYPE; ChangesListProvider changesListProvider = listProviders.get(type); String lockId = lockJournal(type, changesListProvider); try { downloadDebtNotes(); uploadDebtNotes(); } finally { changesListProvider.unlock(lockId); } } void uploadDebtNotes() throws Exception { List<SyncDebtNote> dirtyDebtNotes = proxyDatabase.getDirtyDebtNotes(); if (dirtyDebtNotes.isEmpty()) return; ChangesListProvider changesListProvider = listProviders.get(SyncConstants.DEBT_NOTE_TYPE); ChangesList list = changesListProvider.getCurrentList(); uploadDirtyObjects(dirtyDebtNotes, SyncConstants.DEBT_NOTE_TYPE, list, "debt_notes"); } void downloadDebtNotes() throws Exception { ChangesListProvider changesListProvider = listProviders.get(SyncConstants.DEBT_NOTE_TYPE); List<ChangeItem> items = downloadItems(changesListProvider, "debt_notes"); getChangesApplier().execute(proxyDatabase, items); } private ChangesApplier getChangesApplier() { if (changesApplier == null) { changesApplier = new ChangesApplier(deviceId); } return changesApplier; } private void syncTransactions() throws Exception { int type = SyncConstants.TRANSACTION_TYPE; ChangesListProvider changesListProvider = listProviders.get(type); String lockId = lockJournal(type, changesListProvider); try { downloadTransactions(); uploadTransactions(); } finally { changesListProvider.unlock(lockId); } } void uploadTransactions() throws Exception { List<SyncTransaction> dirtyTransactions = proxyDatabase.getDirtyTransactions(); if (dirtyTransactions.isEmpty()) return; ChangesListProvider changesListProvider = listProviders.get(SyncConstants.TRANSACTION_TYPE); ChangesList list = changesListProvider.getCurrentList(); uploadDirtyObjects(dirtyTransactions, SyncConstants.TRANSACTION_TYPE, list, "transactions"); } void downloadTransactions() throws Exception { ChangesListProvider changesListProvider = listProviders.get(SyncConstants.TRANSACTION_TYPE); List<ChangeItem> items = downloadItems(changesListProvider, "transactions"); getChangesApplier().execute(proxyDatabase, items); } private void syncSubcategories() throws Exception { int type = SyncConstants.SUBCATEGORY_TYPE; ChangesListProvider changesListProvider = listProviders.get(type); String lockId = lockJournal(type, changesListProvider); try { downloadSubcategories(); uploadSubcategories(); } finally { changesListProvider.unlock(lockId); } } void uploadSubcategories() throws Exception { List<SyncSubcategory> dirtySubcategories = proxyDatabase.getDirtySubcategories(); if (dirtySubcategories.isEmpty()) return; ChangesListProvider changesListProvider = listProviders.get(SyncConstants.SUBCATEGORY_TYPE); ChangesList list = changesListProvider.getCurrentList(); uploadDirtyObjects(dirtySubcategories, SyncConstants.SUBCATEGORY_TYPE, list, "subcategories"); } void downloadSubcategories() throws Exception { ChangesListProvider changesListProvider = listProviders.get(SyncConstants.SUBCATEGORY_TYPE); List<ChangeItem> items = downloadItems(changesListProvider, "subcategories"); getChangesApplier().execute(proxyDatabase, items); } private void syncCategories() throws Exception { int type = SyncConstants.CATEGORY_TYPE; ChangesListProvider changesListProvider = listProviders.get(type); String lockId = lockJournal(type, changesListProvider); try { downloadCategories(); uploadCategories(); } finally { changesListProvider.unlock(lockId); } } void uploadCategories() throws Exception { List<SyncCategory> dirtyCategories = proxyDatabase.getDirtyCategories(); if (dirtyCategories.isEmpty()) return; ChangesListProvider changesListProvider = listProviders.get(SyncConstants.CATEGORY_TYPE); ChangesList list = changesListProvider.getCurrentList(); uploadDirtyObjects(dirtyCategories, SyncConstants.CATEGORY_TYPE, list, "categories"); } void downloadCategories() throws Exception { ChangesListProvider changesListProvider = listProviders.get(SyncConstants.CATEGORY_TYPE); List<ChangeItem> items = downloadItems(changesListProvider, "categories"); getChangesApplier().execute(proxyDatabase, items); } private void syncAccounts() throws Exception { int type = SyncConstants.ACCOUNT_TYPE; ChangesListProvider changesListProvider = listProviders.get(type); String lockId = lockJournal(type, changesListProvider); try { downloadAccounts(); uploadAccounts(); } finally { changesListProvider.unlock(lockId); } } private String lockJournal(int type, ChangesListProvider changesListProvider) throws Exception { String lockId = generateLockId(); boolean locked = changesListProvider.lock(lockId); for (int i = 0; i < LOCK_TRIES && !locked; i++) { String remoteLock = changesListProvider.getLockId(); if (proxyDatabase.isOutdatedLock(remoteLock, type)) { changesListProvider.unlock(remoteLock); } else { Thread.sleep(TIMEOUT_MILLIS); } locked = changesListProvider.lock(lockId); } if (!locked) { String remoteLock = changesListProvider.getLockId(); proxyDatabase.saveLock(remoteLock, type); switch (type) { case SyncConstants.ACCOUNT_TYPE: throw new SyncException("Accounts journal is locked by another session. Try later."); case SyncConstants.CATEGORY_TYPE: throw new SyncException("Categories journal is locked by another session. Try later."); case SyncConstants.SUBCATEGORY_TYPE: throw new SyncException("Subcategories journal is locked by another session. Try later."); case SyncConstants.DEBT_TYPE: throw new SyncException("Debts journal is locked by another session. Try later."); case SyncConstants.DEBT_NOTE_TYPE: throw new SyncException("Debt notes journal is locked by another session. Try later."); case SyncConstants.TRANSACTION_TYPE: throw new SyncException("Transactions journal is locked by another session. Try later."); case SyncConstants.PATTERN_TYPE: throw new SyncException("Patterns journal is locked by another session. Try later."); case SyncConstants.BUDGET_TYPE: throw new SyncException("Budgets journal is locked by another session. Try later."); } } return lockId; } void downloadAccounts() throws Exception { ChangesListProvider changesListProvider = listProviders.get(SyncConstants.ACCOUNT_TYPE); List<ChangeItem> items = downloadItems(changesListProvider, "accounts"); getChangesApplier().execute(proxyDatabase, items); } private List<ChangeItem> downloadItems(ChangesListProvider changesListProvider, String logSuffix) throws Exception { logger.print("Downloading " + logSuffix); List<ChangeItem> result = new LinkedList<>(); ChangesList log = changesListProvider.getCurrentList(); while (log != null) { result.addAll(0, log.items); boolean hasOldItems = false; for (Iterator<ChangeItem> it = result.iterator(); it.hasNext(); ) { ChangeItem item = it.next(); if (proxyDatabase.alreadyApplied(item.objectWrapper.type, item.id)) { it.remove(); hasOldItems = true; } else { break; } } if (!hasOldItems) { log = changesListProvider.getPreviousLog(log.previousVersion); } else { log = null; } } return result; } void uploadAccounts() throws Exception { List<SyncAccount> dirtyAccounts = proxyDatabase.getDirtyAccounts(); if (dirtyAccounts.isEmpty()) return; ChangesListProvider changesListProvider = listProviders.get(SyncConstants.ACCOUNT_TYPE); ChangesList list = changesListProvider.getCurrentList(); uploadDirtyObjects(dirtyAccounts, SyncConstants.ACCOUNT_TYPE, list, "accounts"); } private <T extends SyncObject> void uploadDirtyObjects(List<T> dirtyObjects, int type, ChangesList list, String logSuffix) throws Exception { logger.print("Uploading " + logSuffix); final List<ChangeItem> newItems = new ArrayList<>(); for (T obj : dirtyObjects) { ChangeItem item; if (obj.removed) { item = new ChangeItem( list.nextCommandId(), SyncConstants.DELETE_ACTION, new ObjectWrapper(type, obj) ); } else if (obj.globalId >= 0) { item = new ChangeItem( list.nextCommandId(), SyncConstants.UPDATE_ACTION, new ObjectWrapper(type, obj) ); } else { obj.globalId = obj.preparedGlobalId != null ? obj.preparedGlobalId : list.nextGlobalId(); item = new ChangeItem( list.nextCommandId(), SyncConstants.CREATE_ACTION, new ObjectWrapper(type, obj) ); item.sourceId = obj.localId; item.sourceDeviceId = deviceId; } newItems.add(item); list.items.add(item); } listProviders.get(type).putLog(list); proxyDatabase.runInTx(new Runnable() { @Override public void run() { proxyDatabase.clearDirties(newItems); } }); } private String generateLockId() { return UUID.randomUUID().toString(); } /** * For tests purposes * * @param deviceId deviceId */ void setDeviceId(String deviceId) { this.deviceId = deviceId; } }
38.890681
145
0.627805
18ac84ca3a18d3c69162916994f74f62b43b5d36
3,479
package uk.gov.companieshouse.api.accounts.interceptor; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.TestInstance; import org.junit.jupiter.api.TestInstance.Lifecycle; 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.api.model.transaction.Transaction; import uk.gov.companieshouse.api.model.transaction.TransactionStatus; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertTrue; import static org.mockito.ArgumentMatchers.anyString; import static org.mockito.Mockito.when; @ExtendWith(MockitoExtension.class) @TestInstance(Lifecycle.PER_CLASS) class OpenTransactionInterceptorTest { @InjectMocks private OpenTransactionInterceptor transactionInterceptor; @Mock private HttpServletRequest httpServletRequestMock; @Mock private HttpServletResponse httpServletResponseMock; @Test @DisplayName("Tests the interceptor with an existing transaction that is open - happy path") void testPreHandleWithOpenTransaction() { when(httpServletRequestMock.getAttribute(anyString())) .thenReturn(createDummyTransaction(true)); when(httpServletRequestMock.getMethod()).thenReturn("POST"); assertTrue(transactionInterceptor .preHandle(httpServletRequestMock, httpServletResponseMock, new Object())); } @Test @DisplayName("Tests the interceptor failure when transaction is closed and not a GET") void testPreHandleWithClosedTransaction() { when(httpServletRequestMock.getAttribute(anyString())) .thenReturn(createDummyTransaction(false)); when(httpServletRequestMock.getMethod()).thenReturn("POST"); assertFalse(transactionInterceptor .preHandle(httpServletRequestMock, httpServletResponseMock, new Object())); } @Test @DisplayName("Tests the interceptor with a GET request when transaction is closed") void testPreHandleWithGetClosedTransaction() { when(httpServletRequestMock.getAttribute(anyString())) .thenReturn(createDummyTransaction(false)); when(httpServletRequestMock.getMethod()).thenReturn("GET"); assertTrue(transactionInterceptor .preHandle(httpServletRequestMock, httpServletResponseMock, new Object())); } @Test @DisplayName("Tests the interceptor failure when transaction has not been set") void testPreHandleWithTransactionNotBeingSet() { when(httpServletRequestMock.getAttribute(anyString())) .thenReturn(null); assertFalse(transactionInterceptor .preHandle(httpServletRequestMock, httpServletResponseMock, new Object())); } /** * creates an open or closed dummy transaction depending on the boolean passed into method * * @param isOpen - true = open, false - closed * @return {@link Transaction} with the desired transaction status */ private Transaction createDummyTransaction(boolean isOpen) { Transaction transaction = new Transaction(); transaction.setStatus( isOpen ? TransactionStatus.OPEN : TransactionStatus.CLOSED); return transaction; } }
35.5
96
0.745329
4f66e616db132ee1e4214c13fe07615b562f7465
6,168
package water.fvec; import static org.junit.Assert.*; import org.junit.BeforeClass; import org.junit.*; import water.*; public class NewVectorTest extends TestUtil { @BeforeClass() public static void setup() { stall_till_cloudsize(1); } static final double EPSILON = 1e-6; private void testImpl( long[] ls, int[] xs, Class C, boolean hasFloat ) { int [] id = new int[xs.length]; for(int i = 0; i < xs.length; ++i)id[i] = i; testImpl(ls,xs,id,C,hasFloat); } private void testImpl( long[] ls, int[] xs, int [] id, Class C, boolean hasFloat ) { Vec vec = null; try { AppendableVec av = new AppendableVec(Vec.newKey(), Vec.T_NUM); NewChunk nv = new NewChunk(av,0, ls, xs, id, null); Chunk bv = nv.compress(); Futures fs = new Futures(); vec = bv._vec = av.layout_and_close(fs); fs.blockForPending(); // Compression returns the expected compressed-type: assertTrue( "Found chunk class "+bv.getClass()+" but expected "+C, C.isInstance(bv) ); // Also, we can decompress correctly for( int i=0; i<ls.length; i++ ) assertEquals(bv.atd(i), water.util.PrettyPrint.pow10(ls[i],xs[i]), Math.abs(bv.atd(i))*EPSILON); } finally { if( vec != null ) vec.remove(); } } // Test that various collections of parsed numbers compress as expected. @Test public void testCompression() { // A simple no-compress testImpl(new long[] {120, 12,120}, new int [] { 0, 1, 0}, C0LChunk.class,false); // A simple no-compress testImpl(new long[] {122, 3,44}, new int [] { 0, 0, 0}, C1NChunk.class,false); // A simple compressed boolean vector testImpl(new long[] {1, 0, 1}, new int [] {0, 0, 0}, CBSChunk.class,false); // Scaled-byte compression testImpl(new long[] {122,-3,44}, // 12.2, -3.0, 4.4 ==> 122e-1, -30e-1, 44e-1 new int [] { -1, 0,-1}, C1SChunk.class, true); // Positive-scale byte compression testImpl(new long[] {1000,200,30}, // 1000, 2000, 3000 ==> 1e3, 2e3, 3e3 new int [] { 0, 1, 2}, C1SChunk.class,false); // A simple no-compress short testImpl(new long[] {1000,200,32767, -32767,32}, new int [] { 0, 1, 0, 0, 3}, C2Chunk.class,false); // Scaled-byte compression testImpl(new long[] {50100,50101,50123,49999}, // 50100, 50101, 50123, 49999 new int [] { 0, 0, 0, 0}, C1SChunk.class,false); // Scaled-byte compression testImpl(new long[] {51000,50101,50123,49999}, // 51000, 50101, 50123, 49999 new int [] { 0, 0, 0, 0}, C2SChunk.class,false); // Scaled-short compression testImpl(new long[] {501000,501001,50123,49999}, // 50100.0, 50100.1, 50123, 49999 new int [] { -1, -1, 0, 0}, C2SChunk.class, true); // Integers testImpl(new long[] {123456,2345678,34567890}, new int [] { 0, 0, 0}, C4Chunk.class,false); // // Floats testImpl(new long[] {1234,2345,314}, new int [] { -1, -5, -2}, C4SChunk.class, true); // Doubles testImpl(new long[] {1234,2345678,31415}, new int [] { 40, 10, -40}, C8DChunk.class, true); testImpl(new long[] {-581504,-477862,342349}, new int[] {-5,-18,-5}, C8DChunk.class,true); } // Testing writes to an existing Chunk causing inflation @Test public void testWrites() { Vec vec = null; try { Futures fs = new Futures(); AppendableVec av = new AppendableVec(Vec.newKey(), Vec.T_NUM); long ls[] = new long[]{0,0,0,0}; // A 4-row chunk int xs[] = new int[]{0,0,0,0}; // A 4-row chunk NewChunk nv = new NewChunk(av,0,ls,xs,null,null); nv.close(0,fs); vec = av.layout_and_close(fs); fs.blockForPending(); assertEquals(nv._len, vec.length()); // Compression returns the expected constant-compression-type: Chunk c0 = vec.chunkForChunkIdx(0); assertTrue( "Found chunk class "+c0.getClass()+" but expected C0LChunk", c0 instanceof C0LChunk ); // Also, we can decompress correctly for( int i=0; i<ls.length; i++ ) assertEquals(0, c0.atd(i), c0.atd(i)*EPSILON); // Now write a zero into slot 0 vec.set(0,0); assertEquals(vec.at8(0),0); Chunk c1 = vec.chunkForChunkIdx(0); assertTrue( "Found chunk class "+c1.getClass()+" but expected C0LChunk", c1 instanceof C0LChunk ); // Now write a one into slot 1; chunk should inflate into boolean vector. vec.set(1, 1); assertEquals(vec.at8(1),1); // Immediate visibility in current thread Chunk c2 = vec.chunkForChunkIdx(0); // Look again at the installed chunk assertTrue( "Found chunk class "+c2.getClass()+" but expected CBSChunk", c2 instanceof CBSChunk ); // Now write a two into slot 2; chunk should inflate into byte vector vec.set(2, 2); assertEquals(vec.at8(2),2); // Immediate visibility in current thread Chunk c3 = vec.chunkForChunkIdx(0); // Look again at the installed chunk assertTrue( "Found chunk class "+c3.getClass()+" but expected C1NChunk", c3 instanceof C1NChunk ); vec.set(3, 3); assertEquals(vec.at8(3),3); // Immediate visibility in current thread Chunk c4 = vec.chunkForChunkIdx(0); // Look again at the installed chunk assertTrue("Found chunk class " + c4.getClass() + " but expected C1NChunk", c4 instanceof C1NChunk); // Now doing the same for multiple writes, close() only at the end for better speed try (Vec.Writer vw = vec.open()) { vw.set(1, 4); vw.set(2, 5); vw.set(3, 6); // Updates will be immediately visible on the writing node } // now, after vw.close(), numbers are consistent across the H2O cloud assertEquals(vec.at8(1),4); assertEquals(vec.at8(2),5); assertEquals(vec.at8(3),6); } finally { if( vec != null ) vec.remove(); } } }
40.847682
106
0.584955
1cb33bf66da7998ae32794e92068a0b52fd07ef2
1,225
package com.sdl.ecommerce.api.model.impl; import com.sdl.ecommerce.api.model.ProductAttribute; import com.sdl.ecommerce.api.model.ProductPrice; import com.sdl.ecommerce.api.model.ProductVariant; import java.util.List; /** * Generic Product Variant * * @author nic */ public class GenericProductVariant implements ProductVariant { private String id; private ProductPrice price; private List<ProductAttribute> attributes; public GenericProductVariant(String id, ProductPrice price, List<ProductAttribute> attributes) { this.id = id; this.price = price; this.attributes = attributes; } @Override public String getId() { return this.id; } @Override public ProductPrice getPrice() { return this.price; } @Override public List<ProductAttribute> getAttributes() { return this.attributes; } public ProductAttribute getAttribute(String id) { if ( this.attributes != null ) { for ( ProductAttribute attribute : this.attributes ) { if ( attribute.getId().equals(id) ) { return attribute; } } } return null; } }
23.557692
100
0.634286
dafc8c623b0113a28b02d45a814f25551e5735b5
4,810
package me.tatiyanupanwong.supasin.android.libraries.kits.location.internal.huawei.model; import android.app.Activity; import android.content.Context; import android.location.Location; import android.os.Looper; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import androidx.annotation.RequiresPermission; import androidx.annotation.RestrictTo; import me.tatiyanupanwong.supasin.android.libraries.kits.internal.huawei.tasks.HuaweiTask; import me.tatiyanupanwong.supasin.android.libraries.kits.location.internal.interceptors.LocationResultInterceptor; import me.tatiyanupanwong.supasin.android.libraries.kits.location.internal.interceptors.VoidResultInterceptor; import me.tatiyanupanwong.supasin.android.libraries.kits.location.model.FusedLocationProviderClient; import me.tatiyanupanwong.supasin.android.libraries.kits.location.model.LocationCallback; import me.tatiyanupanwong.supasin.android.libraries.kits.location.model.LocationListener; import me.tatiyanupanwong.supasin.android.libraries.kits.location.model.LocationRequest; import me.tatiyanupanwong.supasin.android.libraries.kits.tasks.Task; import static android.Manifest.permission.ACCESS_COARSE_LOCATION; import static android.Manifest.permission.ACCESS_FINE_LOCATION; import static androidx.annotation.RestrictTo.Scope.LIBRARY; @RestrictTo(LIBRARY) public final class HuaweiFusedLocationProviderClient implements FusedLocationProviderClient { private final com.huawei.hms.location.FusedLocationProviderClient mDelegate; private final HuaweiLocationCallbacksHolder mLocationCallbacksHolder = new HuaweiLocationCallbacksHolder(); private final HuaweiLocationListenersHolder mLocationListenersHolder = new HuaweiLocationListenersHolder(); public HuaweiFusedLocationProviderClient(@NonNull Context context) { mDelegate = com.huawei.hms.location.LocationServices .getFusedLocationProviderClient(context); } public HuaweiFusedLocationProviderClient(@NonNull Activity activity) { mDelegate = com.huawei.hms.location.LocationServices .getFusedLocationProviderClient(activity); } @Override @RequiresPermission(anyOf = { ACCESS_FINE_LOCATION, ACCESS_COARSE_LOCATION }) public @NonNull Task<Location> getLastLocation() { return new HuaweiTask<>( mDelegate.getLastLocation(), LocationResultInterceptor.INSTANCE ); } @Override @RequiresPermission(anyOf = { ACCESS_FINE_LOCATION, ACCESS_COARSE_LOCATION }) public @NonNull Task<Void> requestLocationUpdates(@NonNull LocationRequest request, @NonNull LocationCallback callback) { return requestLocationUpdates(request, callback, null); } @Override @RequiresPermission(anyOf = { ACCESS_FINE_LOCATION, ACCESS_COARSE_LOCATION }) public @NonNull Task<Void> requestLocationUpdates(@NonNull LocationRequest request, @NonNull LocationListener listener) { return requestLocationUpdates(request, listener, null); } @Override @RequiresPermission(anyOf = { ACCESS_FINE_LOCATION, ACCESS_COARSE_LOCATION }) public @NonNull Task<Void> requestLocationUpdates(@NonNull LocationRequest request, final @NonNull LocationCallback callback, @Nullable Looper looper) { return new HuaweiTask<>( mDelegate.requestLocationUpdates( HuaweiLocationRequest.unwrap(request), mLocationCallbacksHolder.put(callback), looper), VoidResultInterceptor.INSTANCE ); } @Override @RequiresPermission(anyOf = { ACCESS_FINE_LOCATION, ACCESS_COARSE_LOCATION }) public @NonNull Task<Void> requestLocationUpdates(@NonNull LocationRequest request, @NonNull LocationListener listener, @Nullable Looper looper) { return new HuaweiTask<>( mDelegate.requestLocationUpdates( HuaweiLocationRequest.unwrap(request), mLocationListenersHolder.put(listener), looper), VoidResultInterceptor.INSTANCE ); } @Override public @NonNull Task<Void> removeLocationUpdates(@NonNull LocationCallback callback) { return new HuaweiTask<>( mDelegate.removeLocationUpdates(mLocationCallbacksHolder.remove(callback)), VoidResultInterceptor.INSTANCE ); } @Override public @NonNull Task<Void> removeLocationUpdates(@NonNull LocationListener listener) { return new HuaweiTask<>( mDelegate.removeLocationUpdates(mLocationListenersHolder.remove(listener)), VoidResultInterceptor.INSTANCE ); } }
42.566372
114
0.735551
e2655a13f0c42cfa69eaa335b7566eb7e8799f94
1,083
package com.common.util; import java.util.LinkedList; import java.util.Queue; import com.leetcode.struct.TreeNode; public class TreeUtils { public static TreeNode toTree(Integer[] nums) { if (nums.length == 0) return null; TreeNode head = new TreeNode(nums[0]); Queue<TreeNode> queue = new LinkedList<>(); queue.offer(head); int index = 1; // 当前的数组下标 while (index < nums.length) { TreeNode cur = queue.poll(); if (nums[index] != null) { // 第一个节点不为null则放到左节点并入队 TreeNode temp = new TreeNode(nums[index]); cur.left = temp; queue.offer(temp); } if (index++ >= nums.length) break; if ((index < nums.length) && (nums[index] != null)) { // 第一个节点不为null则放到左节点并入队 TreeNode temp = new TreeNode(nums[index]); cur.right = temp; queue.offer(temp); } index++; } return head; } }
30.083333
67
0.498615
de55c7221d233ba54e5a4f4a2087a082a226b164
1,024
package com.jannchie.word.config; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.web.servlet.config.annotation.CorsRegistry; import org.springframework.web.servlet.config.annotation.InterceptorRegistry; import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; /** * 配置跨域 * * @author jannchie */ @Configuration public class ConfigService { @Bean public WebMvcConfigurer myConfigure() { return new WebMvcConfigurer() { @Override public void addCorsMappings(CorsRegistry registry) { registry .addMapping("/**") .allowedOrigins("*") .allowedMethods("*") .allowedHeaders("*") .allowCredentials(true) .maxAge(3600); } }; } }
30.117647
77
0.624023
0f0825a9120dce28e163a975f9650fb13ea84b77
9,268
package com.ltv.aerospike.management.form; import java.awt.BorderLayout; import java.awt.Component; import java.awt.Dimension; import java.awt.Frame; import java.awt.GridLayout; import java.awt.Toolkit; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import javax.swing.BorderFactory; import javax.swing.JButton; import javax.swing.JComboBox; import javax.swing.JComponent; import javax.swing.JDialog; import javax.swing.JLabel; import javax.swing.JList; import javax.swing.JPanel; import javax.swing.JPopupMenu; import javax.swing.JTextField; import javax.swing.SwingConstants; import javax.swing.SwingUtilities; import javax.swing.plaf.basic.BasicComboBoxRenderer; import javax.swing.table.DefaultTableModel; import com.ltv.aerospike.api.proto.QueryServices.QueryResponse; import com.ltv.aerospike.management.component.DefaultFont; import com.ltv.aerospike.management.component.EditableTable; import com.ltv.aerospike.management.config.AppConstant; import com.ltv.aerospike.management.config.TableCommand; import com.ltv.aerospike.management.event.NamespaceEvent; import io.grpc.stub.StreamObserver; public class NamespaceDialog extends JDialog { public JTextField txtNamespace = new JTextField(); public JLabel txtOldNamespace = new JLabel(); public JComboBox cboUser = new JComboBox(); public JComboBox cboRole = new JComboBox(new String[]{AppConstant.ROLE_OWNER,AppConstant.ROLE_DDL,AppConstant.ROLE_DQL,AppConstant.ROLE_DML,AppConstant.ROLE_DCL}); public JButton btnAdd = new JButton(AppConstant.ADD); public JButton btnSave = new JButton(AppConstant.SAVE); public EditableTable tblRole; public List<List> lstRole = new ArrayList(); public NamespaceEvent namespaceEvent = new NamespaceEvent(); public NamespaceDialog(Frame owner, String title, boolean modal) { super(owner, title, modal); JPanel namespacePanel = new JPanel(); namespacePanel.setBorder(BorderFactory.createEmptyBorder(20, 20, 20, 20)); getContentPane().add(namespacePanel); namespacePanel.setLayout(new BorderLayout(5, 5)); JPanel namePanel = new JPanel(); JPanel rolePanel = new JPanel(); namespacePanel.add(namePanel, BorderLayout.NORTH); namespacePanel.add(rolePanel, BorderLayout.CENTER); namespacePanel.add(btnSave, BorderLayout.SOUTH); namePanel.setLayout(new BorderLayout(5,5)); namePanel.add(new JLabel(AppConstant.NAMESPACE), BorderLayout.WEST); namePanel.add(txtNamespace, BorderLayout.CENTER); txtOldNamespace.setVisible(false); namePanel.add(txtOldNamespace, BorderLayout.EAST); JPanel searchUserPanel = new JPanel(); searchUserPanel.setLayout(new GridLayout(1,5)); searchUserPanel.add(new JLabel(AppConstant.USER_NAME, SwingConstants.RIGHT)); cboUser.setRenderer(new ItemRenderer()); searchUserPanel.add(cboUser); searchUserPanel.add(new JLabel(AppConstant.ROLE, SwingConstants.RIGHT)); searchUserPanel.add(cboRole); searchUserPanel.add(btnAdd, BorderLayout.EAST); rolePanel.setLayout(new BorderLayout(5,5)); rolePanel.add(searchUserPanel, BorderLayout.NORTH); tblRole = new EditableTable() { @Override public void buildPopupMenu() { JPopupMenu popup = new JPopupMenu(); popup.add(buildMenu(AppConstant.DELETE, TableCommand.DELETE.getValue())); addMouseListener(new MouseAdapter() { public void mouseReleased(MouseEvent e) { if (SwingUtilities.isRightMouseButton(e)) { popup.show((JComponent) e.getSource(), e.getX(), e.getY()); } } }); getTableHeader().addMouseListener(new MouseAdapter() { @Override public void mouseReleased(MouseEvent e) { if (SwingUtilities.isRightMouseButton(e)) { popup.show((JComponent) e.getSource(), e.getX(), e.getY()); } } }); DefaultFont.setFont(popup); } @Override public void actionPerformed(ActionEvent actionEvent) { switch (actionEvent.getActionCommand()) { case TableCommand.DELETE_VALUE: HashMap mapUser = new HashMap(); for(int i = 0; i < cboUser.getItemCount(); i++) { Item item = (Item) cboUser.getItemAt(i); mapUser.put(item.getId(), item.getDescription()); } for(List row : lstRole) { if(mapUser.get(row.get(0)).equals(tblRole.getValueAt(tblRole.getSelectedRow(), 0)) && row.get(1).equals(tblRole.getValueAt(tblRole.getSelectedRow(), 1)) ) { lstRole.remove(row); break; } } tblRole.removeSelectedRows(); break; } } }; rolePanel.add(tblRole, BorderLayout.CENTER); String[] header = {"User","Role"}; tblRole.setModel(new DefaultTableModel(header, 0)); rolePanel.setBorder(BorderFactory.createTitledBorder(AppConstant.PERMISSION)); setSize(new Dimension(600, 400)); setLocation((Toolkit.getDefaultToolkit().getScreenSize().width) / 2 - 300, (Toolkit.getDefaultToolkit().getScreenSize().height) / 2 - 200); setResizable(false); btnAdd.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { namespaceEvent.addRoleButtonClick(e); } }); btnSave.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { if(txtNamespace.getText().trim().isEmpty()) { MainForm.getInstance().lblStatus.setText("Namespace is required"); return; } if(!txtOldNamespace.getText().trim().isEmpty()) { namespaceEvent.renameNamespace(txtOldNamespace.getText(), txtNamespace.getText()); } namespaceEvent.saveNamespaceButtonClick(e); } }); } public void loadNamespaceForm() { List<Map<String, Object>> lstUser = new ArrayList(); MainForm.getInstance().aeClient.query(new StreamObserver<QueryResponse>() { @Override public void onNext(QueryResponse queryResponse) { Map user = MainForm.getInstance().aeClient.parseRecord(queryResponse); if(user.get(AppConstant.KEY) != null) lstUser.add(user); } @Override public void onError(Throwable throwable) { MainForm.getInstance().lblStatus.setText("Namespace data loaded failed"); } @Override public void onCompleted() { SwingUtilities.invokeLater(new Runnable() { @Override public void run() { if(lstUser.isEmpty()) return; Map<String, String> mapUser = new HashMap(); for(Map<String, Object> record : lstUser) { MainForm.getInstance().namespaceDialog.cboUser.addItem(new Item((String)record.get(AppConstant.KEY), (String)record.get("name"))); mapUser.put(record.get(AppConstant.KEY).toString(), record.get("name").toString()); } namespaceEvent.loadTblRole(mapUser); MainForm.getInstance().namespaceDialog.setVisible(true); } }); } }, "aerospike", "user"); } class ItemRenderer extends BasicComboBoxRenderer { public Component getListCellRendererComponent( JList list, Object value, int index, boolean isSelected, boolean cellHasFocus) { super.getListCellRendererComponent(list, value, index, isSelected, cellHasFocus); if (value != null) { Item item = (Item)value; setText( item.getDescription() ); } return this; } } public class Item { private String id; private String description; public Item(String id, String description) { this.id = id; this.description = description; } public String getId() { return id; } public String getDescription() { return description; } public String toString() { return description; } } }
40.121212
167
0.597324
4f22053424db573e6fe23256cba50ed057ab70d9
158
package Exercise_01_12; public class Exercise_01_12 { public static void main(String[]args) { System.out.println(24*60*60/(100*60+35)*1.6); } }
14.363636
48
0.677215
4d9d6ecc648e6be716722d4ab97c58f7fb5d7ef1
225
class dis { public static void main(String args[]) { float sp=960; float lp=4; float cp,p; cp=100/(100-lp)*sp; float nsp=1160; p=nsp-cp; System.out.println("cost price="+cp); System.out.println("profit"+p); } }
15
39
0.64
552b8507f960b030cf20abc250840643e00ecf98
1,038
package org.jetbrains.android.util; import org.jetbrains.annotations.NotNull; public class WaitingStrategies { public static abstract class Strategy { private Strategy() { } } public static class DoNotWait extends Strategy { private static final DoNotWait INSTANCE = new DoNotWait(); private DoNotWait() { } @NotNull public static DoNotWait getInstance() { return INSTANCE; } } public static class WaitForTime extends Strategy { private final int myTimeMs; private WaitForTime(int timeMs) { assert timeMs > 0; myTimeMs = timeMs; } @NotNull public static WaitForTime getInstance(int timeMs) { return new WaitForTime(timeMs); } public int getTimeMs() { return myTimeMs; } } public static class WaitForever extends Strategy { private static final WaitForever INSTANCE = new WaitForever(); private WaitForever() { } @NotNull public static WaitForever getInstance() { return INSTANCE; } } }
19.584906
66
0.668593
736304be197c177f0c5a0a5474cacc7f70159dec
9,193
package whelk.history; import whelk.JsonLd; import java.util.*; public class History { private final HashMap<List<Object>, Ownership> m_pathOwnership; // The last version added to this history, needed for diffing the next one against. private DocumentVersion m_lastVersion; private final JsonLd m_jsonLd; /** * Reconstruct a records history given a (backwards chronologically ordered "DESC") * list of versions of said record */ public History(List<DocumentVersion> versions, JsonLd jsonLd) { m_jsonLd = jsonLd; m_pathOwnership = new HashMap<>(); // The list we get is sorted chronologically, oldest first. for (DocumentVersion version : versions) { addVersion(version); } } public void addVersion(DocumentVersion version) { if (m_lastVersion == null) { m_pathOwnership.put( new ArrayList<>(), new Ownership(version, null) ); } else { examineDiff(new ArrayList<>(), version, version.doc.data, m_lastVersion.doc.data, null); } m_lastVersion = version; } public Ownership getOwnership(List<Object> path) { List<Object> temp = new ArrayList<>(path); while (!temp.isEmpty()) { Ownership value = m_pathOwnership.get(temp); if (value != null) return value; temp.remove(temp.size()-1); } return m_pathOwnership.get(new ArrayList<>()); // The root (first) owner } /** * Get the set of owners for path and everything under it. */ public Set<Ownership> getSubtreeOwnerships(List<Object> path) { Set<Ownership> owners = new HashSet<>(); for (Object keyObject : m_pathOwnership.keySet()) { List<Object> key = (List<Object>) keyObject; if (key.size() >= path.size() && key.subList(0, path.size()).equals(path)) { // A path below (more specific) than 'path' owners.add(m_pathOwnership.get(key)); } } return owners; } /** * Examine differences between (what would presumably be) the same entity * in two versions of a record. * * 'version' is the new version (whole Record), * 'previousVersion' is the old one (whole Record), * 'path' is where in the record(s) we are, * 'examining' is the object (entity?) being compared, * 'correspondingPrevious' is the "same" object in the old version * 'compositePath' is null or a (shorter/higher) path to the latest * found enclosing "composite object", such as for example a Title, * which is considered _one value_ even though it is structured and * has subcomponents. The point of this is that changing (for example) * a subTitle should result in ownership of the whole title (not just * the subtitle). */ private void examineDiff(List<Object> path, DocumentVersion version, Object examining, Object correspondingPrevious, List<Object> compositePath) { if (examining instanceof Map) { if (! (correspondingPrevious instanceof Map) ) { setOwnership(path, compositePath, version); return; } Set k1 = ((Map) examining).keySet(); Set k2 = ((Map) correspondingPrevious).keySet(); // Is this a composite object ? Object type = ((Map)examining).get("@type"); if ( type instanceof String && ( m_jsonLd.isSubClassOf( (String) type, "StructuredValue") || m_jsonLd.isSubClassOf( (String) type, "QualifiedRole") ) ) { compositePath = new ArrayList<>(path); } // Key added! if (!k2.containsAll(k1)) { Set newKeys = new HashSet(k1); newKeys.removeAll(k2); for (Object key : newKeys) { List<Object> newPath = new ArrayList(path); newPath.add(key); setOwnership(newPath, compositePath, version); } } } if (examining instanceof List) { if (! (correspondingPrevious instanceof List) ) { setOwnership(path, compositePath, version); return; } } if (examining instanceof String || examining instanceof Float || examining instanceof Boolean) { if (!examining.equals(correspondingPrevious)) { setOwnership(path, compositePath, version); return; } } // Keep scanning if (examining instanceof List) { // Create copies of the two lists (so that they can be manipulated) // and remove from them any elements that _have an identical copy_ in the // other list. // This way, only elements that differ somehow remain to be checked, and // they remain in their relative order to one another. // Without this, removal or addition of a list element results in every // _following_ element being compared with the wrong element in the other list. List tempNew = new LinkedList((List) examining); List tempOld = new LinkedList((List) correspondingPrevious); for (int i = 0; i < tempNew.size(); ++i) { for (int j = 0; j < tempOld.size(); ++j) { if (tempNew.get(i).equals(tempOld.get(j))) { // Equals will recursively check the entire subtree! tempNew.remove(i); tempOld.remove(j); --i; --j; break; } } } for (int i = 0; i < tempNew.size(); ++i) { List<Object> childPath = new ArrayList(path); if ( tempOld.size() > i ) { childPath.add(Integer.valueOf(i)); examineDiff(childPath, version, tempNew.get(i), tempOld.get(i), compositePath); } } } else if (examining instanceof Map) { for (Object key : ((Map) examining).keySet() ) { List<Object> childPath = new ArrayList(path); if ( ((Map)correspondingPrevious).get(key) != null ) { childPath.add(key); examineDiff(childPath, version, ((Map) examining).get(key), ((Map) correspondingPrevious).get(key), compositePath); } } } } private void setOwnership(List<Object> newPath, List<Object> compositePath, DocumentVersion version) { List<Object> path; if (compositePath != null) { path = compositePath; } else { path = newPath; } m_pathOwnership.put( path, new Ownership(version, m_pathOwnership.get(path)) ); } // DEBUG CODE BELOW THIS POINT public String toString() { StringBuilder b = new StringBuilder(); toString(b, m_lastVersion.doc.data, 0, new ArrayList<>()); return b.toString(); } private void toString(StringBuilder b, Object current, int indent, List<Object> path) { if (current instanceof List) { for (int i = 0; i < ((List) current).size(); ++i) { beginLine(b, indent, path); b.append("[\n"); List<Object> childPath = new ArrayList(path); childPath.add(Integer.valueOf(i)); toString(b, ((List)current).get(i), indent + 1, childPath); b.setLength(b.length()-1); // drop newline b.append(",\n"); beginLine(b, indent, path); b.append("]\n"); } } else if (current instanceof Map) { beginLine(b, indent, path); b.append("{\n"); for (Object key : ((Map) current).keySet() ) { List<Object> childPath = new ArrayList(path); childPath.add(key); beginLine(b, indent+1, childPath); b.append( "\"" + key + "\"" + " : \n"); toString(b, ((Map) current).get(key), indent + 1, childPath); b.setLength(b.length()-1); // drop newline b.append(",\n"); } beginLine(b, indent, path); b.append("}\n"); } else { // Bool, string, number beginLine(b, indent, path); b.append("\""); b.append(current.toString()); b.append("\""); } } private void beginLine(StringBuilder b, int indent, List<Object> path) { Formatter formatter = new Formatter(b); formatter.format("%1$-50s| ", getOwnership(path)); for (int i = 0; i < indent; ++i) { b.append(" "); } } }
38.95339
132
0.528663
eee5a2ff7f7cf4d73cbd9b10404c75dc7a7ef420
749
package com.sva.test.dao; import java.util.List; import javax.annotation.Resource; import org.junit.Assert; import org.junit.Test; import com.sva.dao.PhoneDao; import com.sva.model.PhoneModel; public class PhoneDaoTest extends BasicDaoTest{ @Resource PhoneDao dao; @Test public void getAllDataTest(){ List<PhoneModel> lis = dao.getAllData(); Assert.assertNotEquals("result not 0",0,lis.size()); } @Test public void savePhoneTest(){ PhoneModel model = new PhoneModel(); model.setIp("0.0.0.0"); model.setPhoneNumber("123123123"); model.setTimestamp(12312313L); int result = dao.savePhone(model); Assert.assertEquals("result 1",1,result); } }
24.16129
60
0.659546
d9ea2f745846cb7df95ac605007c170260d55778
5,138
package com.mt.access.infrastructure.oauth2; import com.mt.access.application.ApplicationServiceRegistry; import com.mt.access.domain.DomainRegistry; import com.mt.access.domain.model.client.Client; import com.mt.access.domain.model.client.ClientId; import com.mt.access.domain.model.permission.PermissionId; import com.mt.access.domain.model.project.ProjectId; import com.mt.access.domain.model.role.Role; import com.mt.access.domain.model.role.RoleId; import com.mt.access.domain.model.user.UserId; import com.mt.access.domain.model.user_relation.UserRelation; import com.mt.access.infrastructure.AppConstant; import com.mt.common.domain.model.domainId.DomainId; import org.springframework.security.oauth2.common.DefaultOAuth2AccessToken; import org.springframework.security.oauth2.common.OAuth2AccessToken; import org.springframework.security.oauth2.provider.OAuth2Authentication; import org.springframework.security.oauth2.provider.token.TokenEnhancer; import org.springframework.stereotype.Component; import java.time.Instant; import java.util.HashMap; import java.util.Map; import java.util.Optional; import java.util.Set; import java.util.stream.Collectors; /** * capture issued at time to enable token revocation feature, * use user id instead of username to enhance security */ @Component public class CustomTokenEnhancer implements TokenEnhancer { private static final String NOT_USED = "not_used"; @Override public OAuth2AccessToken enhance(OAuth2AccessToken accessToken, OAuth2Authentication authentication) { Map<String, Object> info = new HashMap<>(); info.put("iat", Instant.now().getEpochSecond()); if (!authentication.isClientOnly()) { UserId userId = new UserId(authentication.getName()); info.put("uid", userId.getDomainId()); //for user Set<String> scope = authentication.getOAuth2Request().getScope(); if (scope != null && scope.size() > 0 && !NOT_USED.equals(scope.stream().findFirst().get())) { //only one projectId allowed //get tenant project permission Optional<String> first = scope.stream().findFirst(); ProjectId projectId = new ProjectId(first.get()); Optional<UserRelation> userRelation = ApplicationServiceRegistry.getUserRelationApplicationService().getUserRelation(userId,projectId ); if (userRelation.isEmpty()) { //auto assign default user role for target project UserRelation newRelation = ApplicationServiceRegistry.getUserRelationApplicationService().onboardUserToTenant(userId, projectId); Set<PermissionId> compute = DomainRegistry.getComputePermissionService().compute(newRelation); info.put("permissionIds", compute.stream().map(DomainId::getDomainId).collect(Collectors.toSet())); info.put("projectId", newRelation.getProjectId().getDomainId()); } else { Set<PermissionId> compute = DomainRegistry.getComputePermissionService().compute(userRelation.get()); info.put("permissionIds", compute.stream().map(DomainId::getDomainId).collect(Collectors.toSet())); info.put("projectId", userRelation.get().getProjectId().getDomainId()); } } else { //get auth project permission and user tenant projects Optional<UserRelation> userRelation = ApplicationServiceRegistry.getUserRelationApplicationService().getUserRelation(userId, new ProjectId(AppConstant.MT_AUTH_PROJECT_ID)); userRelation.ifPresent(relation -> { Set<PermissionId> compute = DomainRegistry.getComputePermissionService().compute(relation); info.put("permissionIds", compute.stream().map(DomainId::getDomainId).collect(Collectors.toSet())); info.put("projectId", relation.getProjectId().getDomainId()); if (relation.getTenantIds() != null) { info.put("tenantId", relation.getTenantIds().stream().map(DomainId::getDomainId).collect(Collectors.toSet())); } }); } } else { //for client ClientId clientId = new ClientId(authentication.getName()); Optional<Client> client = ApplicationServiceRegistry.getClientApplicationService().internalQuery(clientId); client.ifPresent(client1 -> { RoleId roleId = client1.getRoleId(); Optional<Role> byId = ApplicationServiceRegistry.getRoleApplicationService().internalGetById(roleId); byId.ifPresent(role -> { info.put("projectId", client1.getProjectId().getDomainId()); info.put("permissionIds", role.getTotalPermissionIds().stream().map(DomainId::getDomainId).collect(Collectors.toSet())); }); }); } ((DefaultOAuth2AccessToken) accessToken).setAdditionalInformation(info); return accessToken; } }
55.847826
188
0.678279
1a6d3597646e7defc53c10536a84232a191a7b62
2,057
/* * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. * * This program and the accompanying materials are made available under the * terms of the Eclipse Distribution License v. 1.0, which is available at * http://www.eclipse.org/org/documents/edl-v10.php. * * SPDX-License-Identifier: BSD-3-Clause */ package com.sun.xml.ws.tx.at.internal; import java.io.Externalizable; import java.io.IOException; import java.io.ObjectInput; import java.io.ObjectOutput; import java.util.Arrays; import javax.transaction.xa.Xid; /** * Xid implementation used for persisting branch state. * Wrapper over XidImpl to override semantics of hashCode and equals */ public class BranchXidImpl implements Xid, Externalizable { private Xid delegate; public BranchXidImpl() { } public BranchXidImpl(Xid xid) { this.delegate = xid; } public byte[] getBranchQualifier() { return delegate.getBranchQualifier(); } public int getFormatId() { return delegate.getFormatId(); } public byte[] getGlobalTransactionId() { return delegate.getGlobalTransactionId(); } public Xid getDelegate() { return delegate; } // // Object // public boolean equals(Object o) { if (!(o instanceof Xid)) return false; Xid that = (Xid) o; final boolean formatId = getFormatId() == that.getFormatId(); final boolean txid = Arrays.equals(getGlobalTransactionId(), that.getGlobalTransactionId()); final boolean bqual = Arrays.equals(getBranchQualifier(), that.getBranchQualifier()); return formatId && txid && bqual; } public int hashCode() { return delegate.hashCode(); } public String toString() { return "BranchXidImpl:" + delegate.toString(); } // // Externalizable // public void readExternal(ObjectInput in) throws IOException, ClassNotFoundException { delegate = (Xid) in.readObject(); } public void writeExternal(ObjectOutput out) throws IOException { out.writeObject(delegate); } }
23.375
100
0.691298
986ad02132ffebc286a42a556964bf1b927a7709
1,661
package com.destiny.squirrel.utils; import com.google.common.collect.Lists; import org.junit.Test; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Spliterator; import java.util.concurrent.ConcurrentHashMap; import java.util.function.Consumer; import java.util.function.Function; import java.util.stream.Collectors; public class LambdaJavaTest { @Test public void test001(){ Function<String,Integer> function = node -> Integer.valueOf(node); System.out.println(function.apply("45")); Consumer<String> consumer = (node) -> System.out.println("consumer -> " + node); consumer.andThen(consumer).accept("45"); List<String> list = new ArrayList<>(); list.add("2"); list.add("3"); list.add("4"); list.add("5"); list.add("6"); list.add("7"); list.add("8"); Spliterator<String> spliterator = list.spliterator(); // 计数器 int cnt = 0; // concurrency parallel print element while (spliterator.tryAdvance(System.out::println)) { System.out.println("cnt = " + ++cnt); } list.parallelStream().forEach(System.out::println); String computeStr = list.parallelStream().collect(Collectors.joining("-")); System.out.println(computeStr); Map<String,String> map = new HashMap<>(3,1.3f); map.put("dd","45"); ConcurrentHashMap<String,String> chm = new ConcurrentHashMap<>(23,4.0f,3); chm.put("34","rt"); } @Test public void test002(){ List<String> list = Lists.newArrayList("2","5","6"); String s = list.stream().filter(node -> node.equals("5")).findAny().orElse(null); System.out.println(s); } }
24.426471
83
0.686936
0c9e8db862a7e368e343cb7c8db66d88afd25e44
4,035
package io.jenkins.plugins.analysis.core.util; import java.util.Map; import java.util.NoSuchElementException; import org.junit.jupiter.api.Test; import edu.hm.hafner.analysis.Severity; import edu.hm.hafner.util.SerializableTest; import io.jenkins.plugins.analysis.core.util.IssuesStatistics.StatisticProperties; import static io.jenkins.plugins.analysis.core.testutil.Assertions.*; /** * Tests the class {@link IssuesStatistics}. * * @author Ullrich Hafner */ class IssuesStatisticsTest extends SerializableTest<IssuesStatistics> { @Test void shouldCreateStatistics() { IssuesStatistics statistics = createSerializable(); assertThat(StatisticProperties.TOTAL.get(statistics)).isEqualTo(1 + 2 + 3 + 4); assertThat(StatisticProperties.TOTAL_ERROR.get(statistics)).isEqualTo(1); assertThat(StatisticProperties.TOTAL_HIGH.get(statistics)).isEqualTo(2); assertThat(StatisticProperties.TOTAL_NORMAL.get(statistics)).isEqualTo(3); assertThat(StatisticProperties.TOTAL_LOW.get(statistics)).isEqualTo(4); assertThat(statistics.getTotalSizeOf(Severity.ERROR)).isEqualTo(1); assertThat(statistics.getTotalSizeOf(Severity.WARNING_HIGH)).isEqualTo(2); assertThat(statistics.getTotalSizeOf(Severity.WARNING_NORMAL)).isEqualTo(3); assertThat(statistics.getTotalSizeOf(Severity.WARNING_LOW)).isEqualTo(4); assertThat(StatisticProperties.NEW.get(statistics)).isEqualTo(5 + 6 + 7 + 8); assertThat(StatisticProperties.NEW_ERROR.get(statistics)).isEqualTo(5); assertThat(StatisticProperties.NEW_HIGH.get(statistics)).isEqualTo(6); assertThat(StatisticProperties.NEW_NORMAL.get(statistics)).isEqualTo(7); assertThat(StatisticProperties.NEW_LOW.get(statistics)).isEqualTo(8); assertThat(statistics.getNewSizeOf(Severity.ERROR)).isEqualTo(5); assertThat(statistics.getNewSizeOf(Severity.WARNING_HIGH)).isEqualTo(6); assertThat(statistics.getNewSizeOf(Severity.WARNING_NORMAL)).isEqualTo(7); assertThat(statistics.getNewSizeOf(Severity.WARNING_LOW)).isEqualTo(8); assertThat(StatisticProperties.DELTA.get(statistics)).isEqualTo(9 + 10 + 11 + 12); assertThat(StatisticProperties.DELTA_ERROR.get(statistics)).isEqualTo(9); assertThat(StatisticProperties.DELTA_HIGH.get(statistics)).isEqualTo(10); assertThat(StatisticProperties.DELTA_NORMAL.get(statistics)).isEqualTo(11); assertThat(StatisticProperties.DELTA_LOW.get(statistics)).isEqualTo(12); assertThat(StatisticProperties.FIXED.get(statistics)).isEqualTo(13); assertThat((Map<Severity, Integer>) statistics.getTotalSizePerSeverity().toMap()).contains( entry(Severity.ERROR, 1), entry(Severity.WARNING_HIGH, 2), entry(Severity.WARNING_NORMAL, 3), entry(Severity.WARNING_LOW, 4)); } @Test void shouldRejectUnsupportedSeverities() { IssuesStatistics statistics = createSerializable(); assertThatExceptionOfType(NoSuchElementException.class).isThrownBy( () -> statistics.getNewSizeOf(null)).withMessageContaining("null"); assertThatExceptionOfType(NoSuchElementException.class).isThrownBy( () -> statistics.getNewSizeOf(new Severity("other"))).withMessageContaining("other"); } @Override protected IssuesStatistics createSerializable() { IssuesStatisticsBuilder builder = new IssuesStatisticsBuilder(); builder.setTotalErrorSize(1) .setTotalHighSize(2) .setTotalNormalSize(3) .setTotalLowSize(4) .setNewErrorSize(5) .setNewHighSize(6) .setNewNormalSize(7) .setNewLowSize(8) .setDeltaErrorSize(9) .setDeltaHighSize(10) .setDeltaNormalSize(11) .setDeltaLowSize(12) .setFixedSize(13); return builder.build(); } }
44.340659
101
0.702354
6cf7a185d7ea5f8410812a8997154b0bebe141a7
3,841
package net.sf.javagimmicks.collections8.decorators; import java.io.Serializable; import java.util.Collection; import java.util.Map; import java.util.Set; import java.util.function.BiConsumer; import java.util.function.BiFunction; import java.util.function.Function; /** * A basic class for {@link Map} decorators that simply forwards all calls to an * internal delegate instance. */ public abstract class AbstractMapDecorator<K, V> implements Map<K, V>, Serializable { private static final long serialVersionUID = 7755485389940064486L; protected final Map<K, V> _decorated; protected AbstractMapDecorator(final Map<K, V> decorated) { _decorated = decorated; } @Override public void clear() { getDecorated().clear(); } @Override public boolean containsKey(final Object key) { return getDecorated().containsKey(key); } @Override public boolean containsValue(final Object value) { return getDecorated().containsValue(value); } @Override public Set<Map.Entry<K, V>> entrySet() { return getDecorated().entrySet(); } @Override public V get(final Object key) { return getDecorated().get(key); } @Override public boolean isEmpty() { return getDecorated().isEmpty(); } @Override public Set<K> keySet() { return getDecorated().keySet(); } @Override public V put(final K key, final V value) { return getDecorated().put(key, value); } @Override public void putAll(final Map<? extends K, ? extends V> m) { getDecorated().putAll(m); } @Override public V remove(final Object key) { return getDecorated().remove(key); } @Override public int size() { return getDecorated().size(); } @Override public Collection<V> values() { return getDecorated().values(); } @Override public String toString() { return getDecorated().toString(); } @Override public V getOrDefault(final Object key, final V defaultValue) { return getDecorated().getOrDefault(key, defaultValue); } @Override public void forEach(final BiConsumer<? super K, ? super V> action) { getDecorated().forEach(action); } @Override public void replaceAll(final BiFunction<? super K, ? super V, ? extends V> function) { getDecorated().replaceAll(function); } @Override public V putIfAbsent(final K key, final V value) { return getDecorated().putIfAbsent(key, value); } @Override public boolean remove(final Object key, final Object value) { return getDecorated().remove(key, value); } @Override public boolean replace(final K key, final V oldValue, final V newValue) { return getDecorated().replace(key, oldValue, newValue); } @Override public V replace(final K key, final V value) { return getDecorated().replace(key, value); } @Override public V computeIfAbsent(final K key, final Function<? super K, ? extends V> mappingFunction) { return getDecorated().computeIfAbsent(key, mappingFunction); } @Override public V computeIfPresent(final K key, final BiFunction<? super K, ? super V, ? extends V> remappingFunction) { return getDecorated().computeIfPresent(key, remappingFunction); } @Override public V compute(final K key, final BiFunction<? super K, ? super V, ? extends V> remappingFunction) { return getDecorated().compute(key, remappingFunction); } @Override public V merge(final K key, final V value, final BiFunction<? super V, ? super V, ? extends V> remappingFunction) { return getDecorated().merge(key, value, remappingFunction); } protected Map<K, V> getDecorated() { return _decorated; } }
21.948571
116
0.659203
d6e9b9681117dcbab46539a22a7459800e7c03a1
9,397
/* * Copyright 2002-2020 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.context.support; import org.springframework.beans.BeansException; import org.springframework.beans.factory.config.ConfigurableListableBeanFactory; import org.springframework.beans.factory.support.DefaultListableBeanFactory; import org.springframework.context.ApplicationContext; import org.springframework.context.ApplicationContextException; import org.springframework.lang.Nullable; import java.io.IOException; /** * {@link org.springframework.context.ApplicationContext}的一个实现基类。 * <p> * 该类支持对{@link #refresh()}多次调用, 每次调用都将创建一个新的内部beanFactory实例,典型的模板模式。 * <p> * 子类唯一需要实现的方法是{@link #loadBeanDefinitions},每次调用{@link #refresh()}刷新时都会调用该方法。 * <p> * {@link #loadBeanDefinitions}其具体的实现逻辑应该是将beanDefinitions加载到给定的{@link org.springframework.beans.factory.support.DefaultListableBeanFactory}中,通常委托给一个或多个特定的beanDefinition读取器,典型的委派模式。 * <p> * 注意,WebApplicationContexts有一个类似的基类。 * {@link org.springframework.web.context.support.AbstractRefreshableWebApplicationContext}提供了相同的子类化策略, * 但是还预实现了Web环境的所有上下文功能。 * 还有一种预定义的方式来接收Web上下文的配置位置。 * <p> * 读取beanDefinition的两种方式一种是xml方式,该方式提供了通用的{@link AbstractXmlApplicationContext}基类,从基类根据不同读取方式派生出 * {@link ClassPathXmlApplicationContext}和{@link FileSystemXmlApplicationContext}。 * <p> * 另一种 * {@link org.springframework.context.annotation.AnnotationConfigApplicationContext}支持{@code @Configuration}注解的类作为beanDefinition的源 * <p> * * @author Juergen Hoeller * @author Chris Beams * @see #loadBeanDefinitions * @see org.springframework.beans.factory.support.DefaultListableBeanFactory * @see org.springframework.web.context.support.AbstractRefreshableWebApplicationContext * @see AbstractXmlApplicationContext * @see ClassPathXmlApplicationContext * @see FileSystemXmlApplicationContext * @see org.springframework.context.annotation.AnnotationConfigApplicationContext * @since 1.1.3 */ public abstract class AbstractRefreshableApplicationContext extends AbstractApplicationContext { @Nullable private Boolean allowBeanDefinitionOverriding; @Nullable private Boolean allowCircularReferences; /** * 该上下文的beanFactory */ // TODO 为什么要用volatile来修饰 @Nullable private volatile DefaultListableBeanFactory beanFactory; /** * Create a new AbstractRefreshableApplicationContext with no parent. */ public AbstractRefreshableApplicationContext() { } /** * Create a new AbstractRefreshableApplicationContext with the given parent context. * * @param parent the parent context */ public AbstractRefreshableApplicationContext(@Nullable ApplicationContext parent) { super(parent); } /** * 设置是否允许覆盖beanDefinition,默认值为{@code true} * <p> * 允许覆盖:注册具有相同名称的另一个定义将自动替换前一个定义。 * 不允许覆盖:将引发异常。 * <p> * 实际是将该属性通过{@linkplain #customizeBeanFactory(DefaultListableBeanFactory) "customizeBeanFactory"}设置给了 * {@linkplain org.springframework.beans.factory.support.DefaultListableBeanFactory} * * @param allowBeanDefinitionOverriding * @see org.springframework.beans.factory.support.DefaultListableBeanFactory#setAllowBeanDefinitionOverriding */ public void setAllowBeanDefinitionOverriding(boolean allowBeanDefinitionOverriding) { this.allowBeanDefinitionOverriding = allowBeanDefinitionOverriding; } /** * 设置是否允许bean之间的循环引用,并自动尝试解决它们,默认值为{@code true} * <p> * 允许循环引用:会自动尝试解决它们 * 不允许循环引用:用引发异常 * <p> * 实际是将该属性通过{@linkplain #customizeBeanFactory(DefaultListableBeanFactory) "customizeBeanFactory"}设置给了 * {@linkplain org.springframework.beans.factory.support.DefaultListableBeanFactory} * * @param allowCircularReferences * @see org.springframework.beans.factory.support.DefaultListableBeanFactory#setAllowCircularReferences */ // TODO 并不清楚循环引用怎么自动解决 public void setAllowCircularReferences(boolean allowCircularReferences) { this.allowCircularReferences = allowCircularReferences; } /** * 该类最重要的方法 * <p> * 实现对该上下文的beanFactory进行刷新 * <p> * 如果已经有一个beanFactory则关闭,为该上下文初始化一个新的beanFactory * * @throws BeansException */ @Override protected final void refreshBeanFactory() throws BeansException { // 1、第一步判断是否有beanFactory,如果有则关闭beanFactory if (hasBeanFactory()) { // TODO 如何释放掉bean destroyBeans(); // TODO 关闭bean工厂,为什么只是清理了实例变量,里面逻辑没看懂 closeBeanFactory(); } try { // 2、第二部创建一个新的beanFactory // TODO 如何创建一个 新的factory DefaultListableBeanFactory beanFactory = createBeanFactory(); // TODO beanFactory里的ID有什么特殊用途 beanFactory.setSerializationId(getId()); // 定制beanFactory属性,override和circularReferences属性 customizeBeanFactory(beanFactory); // 重点方法*****: 加载beanDefinitions loadBeanDefinitions(beanFactory); this.beanFactory = beanFactory; } catch (IOException ex) { throw new ApplicationContextException("I/O error parsing bean definition source for " + getDisplayName(), ex); } } @Override protected void cancelRefresh(BeansException ex) { DefaultListableBeanFactory beanFactory = this.beanFactory; if (beanFactory != null) { beanFactory.setSerializationId(null); } super.cancelRefresh(ex); } @Override protected final void closeBeanFactory() { DefaultListableBeanFactory beanFactory = this.beanFactory; if (beanFactory != null) { beanFactory.setSerializationId(null); this.beanFactory = null; } } /** * 确定此上下文当前是否拥有Bean工厂 * <p> * 即是否至少刷新一次且尚未关闭 * * @return */ protected final boolean hasBeanFactory() { return (this.beanFactory != null); } @Override public final ConfigurableListableBeanFactory getBeanFactory() { DefaultListableBeanFactory beanFactory = this.beanFactory; if (beanFactory == null) { throw new IllegalStateException("BeanFactory not initialized or already closed - " + "call 'refresh' before accessing beans via the ApplicationContext"); } return beanFactory; } /** * Overridden to turn it into a no-op: With AbstractRefreshableApplicationContext, * {@link #getBeanFactory()} serves a strong assertion for an active context anyway. */ @Override protected void assertBeanFactoryActive() { } /** * Create an internal bean factory for this context. * Called for each {@link #refresh()} attempt. * <p>The default implementation creates a * {@link org.springframework.beans.factory.support.DefaultListableBeanFactory} * with the {@linkplain #getInternalParentBeanFactory() internal bean factory} of this * context's parent as parent bean factory. Can be overridden in subclasses, * for example to customize DefaultListableBeanFactory's settings. * * @return the bean factory for this context * @see org.springframework.beans.factory.support.DefaultListableBeanFactory#setAllowBeanDefinitionOverriding * @see org.springframework.beans.factory.support.DefaultListableBeanFactory#setAllowEagerClassLoading * @see org.springframework.beans.factory.support.DefaultListableBeanFactory#setAllowCircularReferences * @see org.springframework.beans.factory.support.DefaultListableBeanFactory#setAllowRawInjectionDespiteWrapping */ protected DefaultListableBeanFactory createBeanFactory() { return new DefaultListableBeanFactory(getInternalParentBeanFactory()); } /** * Customize the internal bean factory used by this context. * Called for each {@link #refresh()} attempt. * <p>The default implementation applies this context's * {@linkplain #setAllowBeanDefinitionOverriding "allowBeanDefinitionOverriding"} * and {@linkplain #setAllowCircularReferences "allowCircularReferences"} settings, * if specified. Can be overridden in subclasses to customize any of * {@link DefaultListableBeanFactory}'s settings. * * @param beanFactory the newly created bean factory for this context * @see DefaultListableBeanFactory#setAllowBeanDefinitionOverriding * @see DefaultListableBeanFactory#setAllowCircularReferences * @see DefaultListableBeanFactory#setAllowRawInjectionDespiteWrapping * @see DefaultListableBeanFactory#setAllowEagerClassLoading */ protected void customizeBeanFactory(DefaultListableBeanFactory beanFactory) { if (this.allowBeanDefinitionOverriding != null) { beanFactory.setAllowBeanDefinitionOverriding(this.allowBeanDefinitionOverriding); } if (this.allowCircularReferences != null) { beanFactory.setAllowCircularReferences(this.allowCircularReferences); } } /** * 通常通过委派一个或多个bean定义读取器,将beanDefinitions加载到给定的beanFactory中 * <p> * 会有多种实现:例如xml和annotation * * @param beanFactory 将beanDefinitions加载到的beanFactory * @throws BeansException 如果解析bean定义失败 * @throws IOException 如果加载bean定义文件失败 * @see org.springframework.beans.factory.support.PropertiesBeanDefinitionReader * @see org.springframework.beans.factory.xml.XmlBeanDefinitionReader */ protected abstract void loadBeanDefinitions(DefaultListableBeanFactory beanFactory) throws BeansException, IOException; }
35.327068
181
0.785996
93287917b3f4fd781facf01f9f165502cc41537b
519
package org.highmed.dsf.fhir.webservice.secure; import org.highmed.dsf.fhir.help.ResponseGenerator; import org.highmed.dsf.fhir.webservice.specification.NamingSystemService; import org.hl7.fhir.r4.model.NamingSystem; public class NamingSystemServiceSecure extends AbstractServiceSecure<NamingSystem, NamingSystemService> implements NamingSystemService { public NamingSystemServiceSecure(NamingSystemService delegate, ResponseGenerator responseGenerator) { super(delegate, responseGenerator); } }
34.6
104
0.828516
3bee1fc523432826342c8855ec27b9f275fc8862
1,201
package datawave.query.iterator; import org.apache.accumulo.core.data.Range; import org.apache.commons.jexl2.parser.ASTJexlScript; import datawave.query.function.JexlEvaluation; public class NestedQuery<T> { protected NestedIterator<T> iter; protected Range iterRange; protected ASTJexlScript script; protected String queryString; protected JexlEvaluation eval; public void setQuery(String query) { this.queryString = query; } public String getQuery() { return queryString; } public void setQueryScript(ASTJexlScript script) { this.script = script; } public ASTJexlScript getScript() { return script; } public void setRange(Range range) { this.iterRange = range; } public Range getRange() { return iterRange; } public void setIterator(NestedIterator<T> iter) { this.iter = iter; } public NestedIterator<T> getIter() { return iter; } public void setEvaluation(JexlEvaluation eval) { this.eval = eval; } public JexlEvaluation getEvaluation() { return eval; } }
21.446429
54
0.630308
4292d5ef2cd41309407bf97e75274fce8d61167c
1,144
package com.lys.utils; import java.sql.Date; import java.text.DateFormat; import java.text.SimpleDateFormat; import net.sf.json.JsonConfig; import net.sf.json.processors.JsonValueProcessor; /** * json 自我封装需要的类 * @author shuang */ public class JsonDateValueProcessor implements JsonValueProcessor { private DateFormat dateFormat; public JsonDateValueProcessor() { dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); } public DateFormat getDateFormat() { return dateFormat; } public void setDateFormat(DateFormat dateFormat) { this.dateFormat = dateFormat; } @Override public Object processArrayValue(Object value, JsonConfig jsonConfig) { return process(value, jsonConfig); } @Override public Object processObjectValue(String key, Object value,JsonConfig jsonConfig) { return process(value, jsonConfig); } private Object process(Object value, JsonConfig jsonConfig) { Object dateValue = value; if (dateValue instanceof Date) dateValue = new java.util.Date(((Date) dateValue).getTime()); if (dateValue instanceof java.util.Date) return dateFormat.format(dateValue); else return dateValue; } }
27.238095
83
0.766608
f2438782f7cd6916960158d5eeccf9d07c10af0c
1,484
/* * DISCLAIMER * * Copyright 2016 ArangoDB GmbH, Cologne, Germany * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * Copyright holder is ArangoDB GmbH, Cologne, Germany */ package deployments; import org.immutables.value.Value; /** * @author Michele Rastelli */ @Value.Immutable(builder = false) public abstract class ArangoVersion implements Comparable<ArangoVersion> { @Value.Parameter(order = 1) abstract int getMajor(); @Value.Parameter(order = 2) abstract int getMinor(); @Value.Parameter(order = 3) abstract int getPatch(); @Override public int compareTo(ArangoVersion o) { if (getMajor() < o.getMajor()) return -1; else if (getMajor() > o.getMajor()) return 1; else if (getMinor() < o.getMinor()) return -1; else if (getMinor() > o.getMinor()) return 1; else return Integer.compare(getPatch(), o.getPatch()); } }
26.981818
75
0.661051
80d4507af38ca4ff3b625b1b8e736cb0c74548ed
12,941
/* * Copyright 2018 Nokia Solutions and Networks * Licensed under the Apache License, Version 2.0, * see license.txt file for details. */ package org.rf.ide.core.testdata.model.table; import java.io.Serializable; import java.util.ArrayList; import java.util.Collections; import java.util.EnumSet; import java.util.List; import java.util.Set; import java.util.stream.Stream; import org.rf.ide.core.testdata.model.AModelElement; import org.rf.ide.core.testdata.model.ExecutableSetting; import org.rf.ide.core.testdata.model.FilePosition; import org.rf.ide.core.testdata.model.FileRegion; import org.rf.ide.core.testdata.model.ICommentHolder; import org.rf.ide.core.testdata.model.IDocumentationHolder; import org.rf.ide.core.testdata.model.ModelType; import org.rf.ide.core.testdata.text.read.IRobotTokenType; import org.rf.ide.core.testdata.text.read.recognizer.RobotToken; import org.rf.ide.core.testdata.text.read.recognizer.RobotTokenType; import com.google.common.base.Preconditions; public class LocalSetting<T> extends AModelElement<T> implements ICommentHolder, Serializable { private static final long serialVersionUID = 5810286313565051692L; public static final Set<ModelType> TEST_SETTING_TYPES = EnumSet.of(ModelType.TEST_CASE_DOCUMENTATION, ModelType.TEST_CASE_TAGS, ModelType.TEST_CASE_SETUP, ModelType.TEST_CASE_TEARDOWN, ModelType.TEST_CASE_TIMEOUT, ModelType.TEST_CASE_TEMPLATE, ModelType.TEST_CASE_SETTING_UNKNOWN); public static final Set<ModelType> TASK_SETTING_TYPES = EnumSet.of(ModelType.TASK_DOCUMENTATION, ModelType.TASK_TAGS, ModelType.TASK_SETUP, ModelType.TASK_TEARDOWN, ModelType.TASK_TIMEOUT, ModelType.TASK_TEMPLATE, ModelType.TASK_SETTING_UNKNOWN); public static final Set<ModelType> KEYWORD_SETTING_TYPES = EnumSet.of(ModelType.USER_KEYWORD_DOCUMENTATION, ModelType.USER_KEYWORD_TAGS, ModelType.USER_KEYWORD_TEARDOWN, ModelType.USER_KEYWORD_TIMEOUT, ModelType.USER_KEYWORD_ARGUMENTS, ModelType.USER_KEYWORD_RETURN, ModelType.USER_KEYWORD_SETTING_UNKNOWN); private ModelType modelType; private final List<RobotToken> tokens = new ArrayList<>(0); private final List<RobotToken> comments = new ArrayList<>(0); public LocalSetting(final ModelType modelType, final RobotToken declaration) { this.modelType = modelType; this.tokens.add(fixForTheType(Preconditions.checkNotNull(declaration), LocalSettingTokenTypes.getTokenType(modelType, 0))); } @Override public ModelType getModelType() { return modelType; } public void changeModelType(final ModelType type) { // firstly we remove types of tokens tied to old model type removeTypes(0); // then we change the type and properly add token types tied to new model type this.modelType = type; fixTypes(); } private void removeTypes(final int startingIndex) { final List<RobotTokenType> tokenTypes = LocalSettingTokenTypes.getPossibleTokenTypes(modelType); for (int i = startingIndex; i < tokens.size(); i++) { final RobotToken token = tokens.get(i); for (final RobotTokenType type : tokenTypes) { if (token.getTypes().contains(type)) { token.getTypes().removeIf(t -> t == type); } } } } @Override public boolean isPresent() { return !tokens.isEmpty(); } @Override public RobotToken getDeclaration() { return isPresent() ? tokens.get(0) : null; } @Override public FilePosition getBeginPosition() { return getDeclaration().getFilePosition(); } public List<RobotToken> getTokens() { return new ArrayList<>(tokens); } public List<RobotToken> getTokensWithoutDeclaration() { return new ArrayList<>(tokens.subList(1, tokens.size())); } public RobotToken getToken(final IRobotTokenType type) { return tokensOf(type).findFirst().orElse(null); } public Stream<RobotToken> tokensOf(final IRobotTokenType type) { return Stream.concat(tokens.stream(), comments.stream()).filter(token -> token.getTypes().contains(type)); } @Override public List<RobotToken> getElementTokens() { final List<RobotToken> tokens = new ArrayList<>(); if (isPresent()) { tokens.addAll(this.tokens); tokens.addAll(this.comments); } return tokens; } @Override public boolean removeElementToken(final int index) { return super.removeElementFromList(tokens, index); } @Override public void insertValueAt(final String value, final int position) { final RobotToken tokenToInsert = RobotToken.create(value); if (1 <= position && position <= tokens.size()) { removeTypes(position); tokens.add(position, tokenToInsert); fixTypes(); } else if (position > tokens.size()) { final int commentsIndex = position - tokens.size(); fixForTheType(tokenToInsert, commentsIndex == 0 ? RobotTokenType.START_HASH_COMMENT : RobotTokenType.COMMENT_CONTINUE); if (commentsIndex == 0) { comments.get(0).getTypes().remove(RobotTokenType.START_HASH_COMMENT); comments.get(0).getTypes().add(RobotTokenType.COMMENT_CONTINUE); } comments.add(commentsIndex, tokenToInsert); } } public void addToken(final RobotToken token) { this.tokens.add(fixType(token, tokens.size())); } private void fixTypes() { for (int i = 0; i < tokens.size(); i++) { fixType(tokens.get(i), i); } } private RobotToken fixType(final RobotToken token, final int index) { final List<IRobotTokenType> types = token.getTypes(); final IRobotTokenType type = LocalSettingTokenTypes.getTokenType(modelType, index); if (type != null) { types.remove(RobotTokenType.UNKNOWN); } if (!types.contains(type)) { types.add(0, type); } if (types.isEmpty()) { types.add(RobotTokenType.UNKNOWN); } return token; } public void addToken(final String tokenText) { final int index = tokens.size(); tokens.add(RobotToken.create(tokenText, LocalSettingTokenTypes.getTokenType(modelType, index))); } public void setToken(final String tokenText, final int index) { if (tokenText == null && 0 <= index && index < tokens.size()) { tokens.remove(index); } else if (tokenText != null) { for (int i = tokens.size(); i <= index; i++) { tokens.add(RobotToken.create("", LocalSettingTokenTypes.getTokenType(modelType, i))); } tokens.set(index, RobotToken.create(tokenText, LocalSettingTokenTypes.getTokenType(modelType, index))); } } public void setTokens(final List<String> tokenTexts) { while (tokens.size() > 1) { tokens.remove(tokens.size() - 1); } for (int i = 0; i < tokenTexts.size(); i++) { tokens.add(RobotToken.create(tokenTexts.get(i), LocalSettingTokenTypes.getTokenType(modelType, i + 1))); } } @Override public List<RobotToken> getComment() { return Collections.unmodifiableList(comments); } public void addCommentPart(final String commentToken) { addCommentPart(RobotToken.create(commentToken)); } @Override public void addCommentPart(final RobotToken rt) { fixComment(getComment(), rt); comments.add(rt); } @Override public void setComment(final String comment) { setComment(RobotToken.create(comment)); } @Override public void setComment(final RobotToken comment) { comments.clear(); addCommentPart(comment); } @Override public void removeCommentPart(final int index) { comments.remove(index); } @Override public void clearComment() { comments.clear(); } @Override public String toString() { return modelType.name(); } public <C> C adaptTo(final Class<C> clazz) { if (clazz == IDocumentationHolder.class && EnumSet .of(ModelType.TEST_CASE_DOCUMENTATION, ModelType.TASK_DOCUMENTATION, ModelType.USER_KEYWORD_DOCUMENTATION) .contains(modelType)) { return clazz.cast(new DocumentationHolderAdapter()); } else if (clazz == ExecutableSetting.class && EnumSet.of(ModelType.TEST_CASE_SETUP, ModelType.TASK_SETUP).contains(modelType)) { return clazz.cast(new ExecutableAdapter(true)); } else if (clazz == ExecutableSetting.class && EnumSet.of(ModelType.TEST_CASE_TEARDOWN, ModelType.TASK_TEARDOWN, ModelType.USER_KEYWORD_TEARDOWN) .contains(modelType)) { return clazz.cast(new ExecutableAdapter(false)); } return null; } private class ExecutableAdapter implements ExecutableSetting { private final boolean isSetup; public ExecutableAdapter(final boolean isSetup) { this.isSetup = isSetup; } @Override public RobotToken getDeclaration() { return LocalSetting.this.getDeclaration(); } @Override public RobotToken getKeywordName() { final List<RobotToken> tokens = getTokens(); return tokens.size() > 1 ? tokens.get(1) : null; } @Override public List<RobotToken> getArguments() { final List<RobotToken> tokens = getTokens(); final List<RobotToken> arguments = tokens.size() > 2 ? tokens.subList(2, tokens.size()) : new ArrayList<>(); return Collections.unmodifiableList(arguments); } @SuppressWarnings("unchecked") @Override public RobotExecutableRow<T> asExecutableRow() { final RobotExecutableRow<T> execRow = new RobotExecutableRow<>(); execRow.setParent(getParent()); execRow.setAction(getKeywordName().copy()); for (final RobotToken arg : getArguments()) { execRow.addArgument(arg.copy()); } for (final RobotToken c : getComment()) { execRow.addCommentPart(c.copy()); } return execRow; } @Override public boolean isSetup() { return isSetup; } @Override public boolean isTeardown() { return !isSetup; } } private class DocumentationHolderAdapter implements IDocumentationHolder { @Override public List<FileRegion> getContinuousRegions() { return new FileRegion.FileRegionSplitter().splitContinuousRegions(getElementTokens()); } @Override public IDocumentationHolder getCached() { return this; } @Override public FilePosition getBeginPosition() { return getDeclaration().getFilePosition(); } @Override public List<RobotToken> getDocumentationText() { return Collections.unmodifiableList(tokens.subList(1, tokens.size())); } @Override public void addDocumentationText(final RobotToken token) { token.getTypes().clear(); token.getTypes().add(LocalSettingTokenTypes.getTokenType(modelType, 1)); tokens.add(token); } @Override public void clearDocumentation() { while (tokens.size() > 1) { tokens.remove(tokens.size() - 1); } } @Override public boolean equals(final Object obj) { if (obj != null && obj.getClass() == DocumentationHolderAdapter.class) { final LocalSetting<?>.DocumentationHolderAdapter that = (LocalSetting<?>.DocumentationHolderAdapter) obj; return this.getOuterSettingObject().equals(that.getOuterSettingObject()); } return false; } @Override public int hashCode() { return getOuterSettingObject().hashCode(); } private LocalSetting<?> getOuterSettingObject() { return LocalSetting.this; } } }
35.070461
122
0.615254
bf0e8b8615ab1f75845530298242b3ced4eecb60
3,522
package io.syndesis.connector.jms.springboot; import javax.annotation.Generated; /** * Publish JMS Messages * * Generated by camel-package-maven-plugin - do not edit this file! */ @Generated("org.apache.camel.maven.connector.SpringBootAutoConfigurationMojo") public class ActiveMQPublishConnectorConfigurationCommon { /** * The maximum number of connections available to endpoints started under * this component */ private Integer connectionCount = 1; /** * The kind of destination to use */ private String destinationType = "queue"; /** * DestinationName is a JMS queue or topic name. By default the * destinationName is interpreted as a queue name. */ private String destinationName; /** * Flag used to enable/disable message persistence. */ private boolean persistent = true; /** * Broker URL */ private String brokerUrl; /** * Authorization credential user name */ private String username; /** * Authorization credential password */ private String password; /** * Client ID for durable subscriptions */ private String clientID; /** * Skip Certificate check for development environment */ private Boolean skipCertificateCheck; /** * AMQ Broker X.509 PEM Certificate */ private String brokerCertificate; /** * AMQ Client X.509 PEM Certificate */ private String clientCertificate; public Integer getConnectionCount() { return connectionCount; } public void setConnectionCount(Integer connectionCount) { this.connectionCount = connectionCount; } public String getDestinationType() { return destinationType; } public void setDestinationType(String destinationType) { this.destinationType = destinationType; } public String getDestinationName() { return destinationName; } public void setDestinationName(String destinationName) { this.destinationName = destinationName; } public boolean isPersistent() { return persistent; } public void setPersistent(boolean persistent) { this.persistent = persistent; } public String getBrokerUrl() { return brokerUrl; } public void setBrokerUrl(String brokerUrl) { this.brokerUrl = brokerUrl; } public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } public String getClientID() { return clientID; } public void setClientID(String clientID) { this.clientID = clientID; } public Boolean getSkipCertificateCheck() { return skipCertificateCheck; } public void setSkipCertificateCheck(Boolean skipCertificateCheck) { this.skipCertificateCheck = skipCertificateCheck; } public String getBrokerCertificate() { return brokerCertificate; } public void setBrokerCertificate(String brokerCertificate) { this.brokerCertificate = brokerCertificate; } public String getClientCertificate() { return clientCertificate; } public void setClientCertificate(String clientCertificate) { this.clientCertificate = clientCertificate; } }
23.959184
78
0.661272
eb7d9343472f25e814c408acccb9ceb07c37f002
54
package br.utfpr.crud; public class MenuBar { }
9
22
0.666667
559d6d804dce46a66b4c4ce916c43abae9fce9e5
725
package quimica.ufc.br.estequiometria.parser; import java.util.HashMap; import quimica.ufc.br.estequiometria.interactions.Interaction1Activity; import static quimica.ufc.br.estequiometria.InteractionAcitivity.ELEMENTS_HASH; /** * Look up table. Stores information about the atoms. * @author vladymirbezerra * */ public class LookUpTable { private HashMap<String, Integer> table = new HashMap<>(); private static LookUpTable instance; private LookUpTable() {} public static LookUpTable getTable() { if (null == instance) { instance = new LookUpTable(); } return instance; } /** * Obs.: Throw null exception */ public Double lookAtom(String name) { return ELEMENTS_HASH.get(name); } }
19.594595
79
0.729655
fc51aa7bf26c697bb684e3ddbbd5e8310471d6c7
1,234
package project; import java.io.*; class add { int a,b,c; double x,y,z; String k,l,m; add() { } add(int m,int n) { a=m; b=n; c=a+b; System.out.println(c); } add(double x1,double y1) { x=x1; y=y1; z=x+y; System.out.println(z); } add(String k1,String l1) { k=k1; l=l1; m=k+l; System.out.println(m); } public void main()throws IOException { int x,y,z; BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); System.out.println("Enter Integer Values:"); x=Integer.parseInt(br.readLine()); y=Integer.parseInt(br.readLine()); //System.out.println("Enter value"); add a=new add(x,y); double a1,b; System.out.println("Enter Double Values:"); a1=Double.parseDouble(br.readLine()); b=Double.parseDouble(br.readLine()); add a2=new add(a1,b); String k,l; System.out.println("Enter String Values:"); k=br.readLine(); l=br.readLine(); add a3=new add (k,l); } }
22.436364
80
0.483793
304d08798f6915e493b7365432ba8e97635bacba
3,025
package com.northgateps.nds.beis.ui.selenium.pagehelper; import java.util.Locale; import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.support.ui.Select; import com.northgateps.nds.beis.ui.selenium.pageobject.PersonalisedLandlordAddressPageObject; import com.northgateps.nds.platform.ui.selenium.PageObject; import com.northgateps.nds.platform.ui.selenium.core.BasePageHelper; import com.northgateps.nds.platform.ui.selenium.core.FormFiller; import com.northgateps.nds.platform.ui.selenium.core.PageHelper; @PageObject(pageObjectClass = PersonalisedLandlordAddressPageObject.class) public class PersonalisedLandlordAddressPageHelper extends BasePageHelper<PersonalisedLandlordAddressPageObject> implements PageHelper { // set default FormFiller { setFormFiller(new FormFiller() { @Override public void fill(BasePageHelper<?> pageHelper) { clickAnchorEnterAddressManually(); fillInForm("Flat 1, Projection West", "Merchants Place", "READING", "", "RG1 1ET"); } }); } public PersonalisedLandlordAddressPageHelper(WebDriver driver) { super(driver); } public PersonalisedLandlordAddressPageHelper(WebDriver driver, Locale locale) { super(driver, locale); } public void fillInForm(String line0, String line1, String town, String county, String postcode) { final PersonalisedLandlordAddressPageObject pageObject = getPageObject(); pageObject.setTextNdsInputLine0(line0); pageObject.setTextNdsInputLine1(line1); pageObject.setTextNdsInputTown(town); pageObject.setTextNdsInputCounty(county); pageObject.setTextNdsInputPostcode(postcode); getAddressCountryElement().selectByValue("GB"); } public void ClearForm() { final PersonalisedLandlordAddressPageObject pageObject = getPageObject(); pageObject.setTextNdsInputLine0(""); pageObject.setTextNdsInputLine1(""); pageObject.setTextNdsInputTown(""); pageObject.setTextNdsInputCounty(""); pageObject.setTextNdsInputPostcode(""); getAddressCountryElement().selectByValue(""); } @Override public PageHelper skipPage() { final PersonalisedLandlordAddressPageObject pageObject = getPageObject(); fillInForm(); pageObject.invalidateDcId(); pageObject.clickNext(); BasePageHelper.waitUntilPageLoading(getPageObject().getDriver()); return PageHelperFactory.build(getPageObject().getDcId(), getPageObject().getDriver(), getLocale()); } public void clickAnchorEnterAddressManually() { getPageObject().clickAnchorEnterAddressManually(); } public Select getAddressCountryElement() { Select dropdown = new Select( getPageObject().getDriver().findElement(By.id("exemptionDetails.landlordDetails.landlordAddress.country"))); return dropdown; } }
37.345679
136
0.715702
90c34d3dd3808ae210420716ab2afa905df14843
2,843
package com.hl.p2p.pojo; import java.math.BigDecimal; import java.util.Date; public class Paymentscheduledetail { private Long id; private BigDecimal bidamount; private Long bidId; private BigDecimal totalamount; private BigDecimal principal; private BigDecimal interest; private int monthindex; private Date deadline; private Long bidrequestId; private Date paydate; private int returntype; private Long paymentscheduleId; private Logininfo fromlogininfo; private Long tologininfoId; public Long getId() { return id; } public void setId(Long id) { this.id = id; } public BigDecimal getBidamount() { return bidamount; } public void setBidamount(BigDecimal bidamount) { this.bidamount = bidamount; } public Long getBidId() { return bidId; } public void setBidId(Long bidId) { this.bidId = bidId; } public BigDecimal getTotalamount() { return totalamount; } public void setTotalamount(BigDecimal totalamount) { this.totalamount = totalamount; } public BigDecimal getPrincipal() { return principal; } public void setPrincipal(BigDecimal principal) { this.principal = principal; } public BigDecimal getInterest() { return interest; } public void setInterest(BigDecimal interest) { this.interest = interest; } public int getMonthindex() { return monthindex; } public void setMonthindex(int monthindex) { this.monthindex = monthindex; } public Date getDeadline() { return deadline; } public void setDeadline(Date deadline) { this.deadline = deadline; } public Long getBidrequestId() { return bidrequestId; } public void setBidrequestId(Long bidrequestId) { this.bidrequestId = bidrequestId; } public Date getPaydate() { return paydate; } public void setPaydate(Date paydate) { this.paydate = paydate; } public Logininfo getFromlogininfo() { return fromlogininfo; } public void setFromlogininfo(Logininfo fromlogininfo) { this.fromlogininfo = fromlogininfo; } public int getReturntype() { return returntype; } public void setReturntype(int returntype) { this.returntype = returntype; } public Long getPaymentscheduleId() { return paymentscheduleId; } public void setPaymentscheduleId(Long paymentscheduleId) { this.paymentscheduleId = paymentscheduleId; } public Long getTologininfoId() { return tologininfoId; } public void setTologininfoId(Long tologininfoId) { this.tologininfoId = tologininfoId; } }
19.472603
62
0.642279
6afe3f8ac4d90f944552dd9852c3c6a5f4b10c6c
535
package com.nbs.iais.ms.meta.referential.common.messageing.events.statistical.program; import com.nbs.iais.ms.common.dto.impl.StatisticalProgramDTO; import com.nbs.iais.ms.common.dto.wrappers.DTOBoolean; import com.nbs.iais.ms.common.messaging.events.abstracts.AbstractEvent; public class RemoveStatisticalProgramLegislativeReferenceEvent extends AbstractEvent<StatisticalProgramDTO> { private static final long serialVersionUID = 200L; public RemoveStatisticalProgramLegislativeReferenceEvent() { super(); } }
35.666667
109
0.813084
4f5cead799d7a69547137a8c8fd102842eaf3f02
334
package com.github.skjolber.jsh; import java.io.IOException; import org.junit.Test; public class JsonStreamContextListenerTest extends AbstractHighlighterTest { @Test public void testHighlistSubtree() throws IOException { SubtreeJsonStreamContextListener l = new SubtreeJsonStreamContextListener(); handle(l, l); } }
19.647059
78
0.790419
a19bb287a128da7684cc6664440c0b4d5e06b926
2,856
package org.planetearth.words.repository; import java.util.List; import java.util.Set; import org.planetearth.words.domain.Word; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.data.jpa.repository.Query; import org.springframework.data.repository.query.Param; /** * Repository of Word Domain. * * @author Katsuyuki.T */ public interface WordRepository extends JpaRepository<Word, Long> { @Query("select w from Word w where w.id in :ids ") List<Word> findByIds(@Param("ids") Set<Long> ids); @Query("select w from Word w inner join w.context c where c.id = :contextId ") List<Word> findByContextId(@Param("contextId") Long contextId); @Query("select w from Word w where (w.notation like %:word% or w.reading like %:word% " + "or w.conversion like %:word% or w.abbreviation like %:word% or w.note like %:word%) " + "order by w.reading asc") List<Word> findContainsWord(@Param("word") String word); @Query("select w from Word w inner join w.context c where c.id in :contextIds order by w.reading asc") List<Word> findContainsWord(@Param("contextIds") Set<Long> contextIds); @Query("select w from Word w inner join w.context c where c.id in :contextIds " + "and (w.notation like %:word% or w.reading like %:word% or w.conversion like %:word% " + "or w.abbreviation like %:word% or w.note like %:word%) order by w.reading asc") List<Word> findContainsWord(@Param("contextIds") Set<Long> contextIds, @Param("word") String word); @Query("select w from Word w inner join w.context c where c.id in :contextIds " + "and (w.notation like %:word% or w.reading like %:word% or w.conversion like %:word% " + "or w.abbreviation like %:word% or w.note like %:word%) and w.id in :ids " + "order by w.reading asc") List<Word> findContainsWord(@Param("contextIds") Set<Long> contextIds, @Param("word") String word, @Param("ids") List<Long> ids); @Query("select w from Word w inner join w.context c where c.id = :contextId " + "and w.notation = :notation order by w.reading asc") Word findByNotation(@Param("contextId") Long contextId, @Param("notation") String notation); @Query("select w from Word w inner join w.context c where c.id in :contextIds " + "and w.notation = :notation order by w.reading asc") List<Word> findByNotation(@Param("contextIds") Set<Long> contextIds, @Param("notation") String notation); @Query("select w from Word w where (w.notation like %:word% or w.reading like %:word% " + "or w.conversion like %:word% or w.abbreviation like %:word% or w.note like %:word%) " + "and w.id in :ids order by w.reading asc") List<Word> findContainsWord(@Param("word") String word, @Param("ids") List<Long> ids); }
46.819672
106
0.672619
e038b0e58525cad680b2816d432ad18f6c3de526
2,689
package com.github.derrop.simplecommand.argument; import org.jetbrains.annotations.NotNull; import java.util.Arrays; import java.util.Collection; import java.util.Optional; import java.util.stream.Stream; public class CommandArgumentWrapper { private final CommandArgument<?>[] arguments; public CommandArgumentWrapper(CommandArgument<?>[] arguments) { this.arguments = arguments; } public CommandArgumentWrapper(Collection<CommandArgument<?>> arguments) { this(arguments.toArray(new CommandArgument[0])); } public Object[] array() { Object[] objects = new Object[this.arguments.length]; for (int i = 0; i < this.arguments.length; i++) { objects[i] = this.arguments[i].getAnswer(); } return objects; } public int length() { return this.arguments.length; } public ArgumentType<?> argumentType(int index) { return this.hasArgument(index) ? this.arguments[index].getAnswerType() : null; } public Object argument(int index) { return this.hasArgument(index) ? this.arguments[index].getAnswer() : null; } public boolean hasArgument(int index) { return this.arguments.length > index && index >= 0; } private Stream<CommandArgument<?>> argumentStream(String key) { return Arrays.stream(this.arguments) .filter(argument -> argument.getAnswerType().getUsageDisplay() != null) .filter(argument -> argument.getAnswerType().getUsageDisplay().equalsIgnoreCase(key)); } public Optional<ArgumentType<?>> argumentType(String key) { return this.argumentStream(key) .findFirst() .map(CommandArgument::getAnswerType); } public Optional<Object> optionalArgument(String key) { return this.argumentStream(key) .findFirst() .map(CommandArgument::getAnswer); } @NotNull public Object argument(String key) { return this.argumentStream(key) .findFirst() .map(CommandArgument::getAnswer) .orElseThrow(() -> new IllegalArgumentException("No argument with the key '" + key + "' has been provided")); } public Optional<Object> argument(Class<? extends ArgumentType<?>> answerTypeClass) { return Arrays.stream(this.arguments) .filter(argument -> answerTypeClass.isAssignableFrom(argument.getAnswerType().getClass())) .findFirst() .map(CommandArgument::getAnswer); } public boolean hasArgument(String key) { return this.optionalArgument(key).isPresent(); } }
31.635294
125
0.639271
58b1170aab2f2c736f601d5c2e4c7d7752c490fa
17,416
package com.ihs.odkate.base.utils; import android.app.Activity; import android.app.AlertDialog; import android.content.Context; import android.content.DialogInterface; import android.content.res.AssetManager; import android.util.Log; import com.ihs.odkate.base.Odkate; import com.ihs.odkate.base.R; import org.apache.commons.io.IOUtils; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import org.odk.collect.android.application.Collect; import org.odk.collect.android.listeners.DiskSyncListener; import org.odk.collect.android.tasks.DiskSyncTask; import org.w3c.dom.DOMException; import org.w3c.dom.Document; import org.w3c.dom.NamedNodeMap; import org.w3c.dom.Node; import org.w3c.dom.NodeList; import org.w3c.dom.Text; import org.xml.sax.SAXException; import java.io.BufferedWriter; import java.io.File; import java.io.FileOutputStream; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.io.Writer; import java.net.URI; import java.util.ArrayList; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.UUID; import javax.xml.parsers.ParserConfigurationException; import javax.xml.transform.TransformerException; import javax.xml.xpath.XPathConstants; /** * Created by Maimoona on 7/17/2017. */ public class OdkateUtils { public static void showErrorDialog(Context context, String message){ AlertDialog.Builder alertb = new AlertDialog.Builder(context); alertb.setMessage(message); alertb.setCancelable(true); alertb.setPositiveButton( R.string.data_saved_ok, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { dialog.cancel(); } }); AlertDialog alert = alertb.create(); alert.show(); } // todo see where and how it update app about sync; Also every time forms are updated it should run itself; // or if app runs first time /** * This should be called on every time application is initialized or * odk forms on disk are updated by an automated service or anything else * @param context * @param diskSyncCompleteListener */ public static void refreshFormIndices(Context context, DiskSyncListener diskSyncCompleteListener){ DiskSyncTask mDiskSyncTask = (DiskSyncTask) (context instanceof Activity? ((Activity)context).getLastNonConfigurationInstance() : null); if (mDiskSyncTask == null) { Log.i(context.getClass().getName(), "Starting new disk sync task"); mDiskSyncTask = new DiskSyncTask(); mDiskSyncTask.setDiskSyncListener(diskSyncCompleteListener); mDiskSyncTask.execute((Void[]) null); } } public static void copyAssetForms(Context context) { AssetManager assetManager = context.getAssets(); String assets[] = null; try { assets = assetManager.list("xforms"); String formsPath = Collect.FORMS_PATH; File dir = new File(formsPath); if (!dir.exists()) dir.mkdir(); for (int i = 0; i < assets.length; ++i) { if (assets[i].endsWith(".xml")) {// read xml forms only String assetPath = "xforms" + File.separator + assets[i]; String odkPath = formsPath + File.separator + assets[i]; String assetMediaPath = assetPath.replace(".xml","")+ "-media"; String odkMediaPath = odkPath.replace(".xml","")+ "-media"; // create media folder File odkmdir = new File(odkMediaPath); if (!odkmdir.exists()) odkmdir.mkdir(); // copy xform to form dir copyAssetFile(context, assetPath, odkPath); // copy xform to form media dir to keep backup of original xform to prevent field overrides affecting original version copyAssetFile(context, assetPath, odkMediaPath + File.separator + assets[i]); // copy media files String[] mediaAssets = assetManager.list(assetMediaPath); for (String med : mediaAssets) { copyAssetFile(context, assetMediaPath + File.separator + med, odkMediaPath + File.separator + med); } // copy form_definition.json InputStream in = null; Writer out = null; try { in = assetManager.open(assetPath); String xform = IOUtils.toString(in); JSONObject formDefinition = createFormDefinition(xform); out = new BufferedWriter(new FileWriter(odkMediaPath + File.separator + "form_definition.json", false)); out.write(formDefinition.toString().replace("\\/", "/")); in.close(); out.flush(); out.close(); } catch (Exception e) { Log.e("tag", e.getMessage()); } } } } catch (IOException ex) { Log.e("tag", "I/O Exception", ex); } catch (Exception e) { e.printStackTrace(); } // must run DiskFormLoader to update ODK form db to make sure forms exist or get removed refreshFormIndices(context, new DiskSyncListener() { @Override public void syncComplete(String result) { Log.v(getClass().getName(), "DiskSync COMPLETED "+result); } }); } public static void copyAssetFile(Context context, String from, String to) { AssetManager assetManager = context.getAssets(); InputStream in = null; OutputStream out = null; try { in = assetManager.open(from); String newFileName = to; out = new FileOutputStream(newFileName, false); byte[] buffer = new byte[1024]; int read; while ((read = in.read(buffer)) != -1) { out.write(buffer, 0, read); } in.close(); out.flush(); out.close(); } catch (Exception e) { Log.e("tag", e.getMessage()); } } public void writeToExternalSheet(){ /* todo how to write to external sheet overrides.put("id_key", "current");// add key to refer current record to pull data from. // leaving room for development to pull data from related or other entities incase needed File root = new File(Collect.FORMS_PATH+"/"+formId+"-media"); if (!root.exists()) { root.mkdirs(); } File existing = new File(root, "existing.csv"); existing.createNewFile(); // if file already exists will do nothing try (CSVWriter writer = new CSVWriter(new FileWriter(existing, false))) { String[] keysArray = new String[overrides.keySet().size()]; String[] valuesArray = new String[overrides.values().size()]; int counter = 0; for (Map.Entry<String, String> entry : overrides.entrySet()) { keysArray[counter] = entry.getKey(); valuesArray[counter] = entry.getValue(); counter++; } writer.writeNext(keysArray); writer.writeNext(valuesArray); } catch (IOException e) { e.printStackTrace(); }*/ } public static void copyXFormToBin(String formId, String entityId, Map<String, String> overrides) { try { if (overrides == null){ overrides = new HashMap<>(); } if (entityId == null || entityId.trim().isEmpty()){ entityId = UUID.randomUUID().toString(); } overrides.put("entityId", entityId); // pick xform from media backup to flush overrides String xformPath = Collect.FORMS_PATH+"/"+formId+"-media/"+formId+".xml"; Document doc = XmlUtils.readXml(xformPath); NodeList instanceSet = (NodeList) XmlUtils.query("//model/instance[1]", doc, XPathConstants.NODESET); if (instanceSet == null || instanceSet.getLength() == 0){ throw new RuntimeException("No node found at xpath '//model/instance[1]'. Make sure that xform has proper schema"); } Node instance = instanceSet.item(0); for (String field: overrides.keySet()) { NodeList requiredFieldSet = (NodeList) XmlUtils.query(".//"+field, instance, XPathConstants.NODESET); if (requiredFieldSet == null || requiredFieldSet.getLength() == 0){ Log.w(Odkate.class.getName(), "No node found in model instance with name "+field+". Make sure that xform has proper schema"); Node n = doc.createElement(field); Text text = doc.createTextNode(overrides.get(field)); n.appendChild(text); XmlUtils.getNextChild(instance).appendChild(n); continue; } else if (requiredFieldSet.getLength() > 1){ throw new RuntimeException("Multiple nodes found in model instance with name "+field+". Make sure that xform has proper schema"); } requiredFieldSet.item(0).setTextContent(overrides.get(field)); } // save to file where odk looks for forms XmlUtils.writeXml(doc, Collect.FORMS_PATH+"/"+formId+".xml"); } catch (ParserConfigurationException pce) { pce.printStackTrace(); } catch (TransformerException tfe) { tfe.printStackTrace(); } catch (IOException ioe) { ioe.printStackTrace(); } catch (SAXException sae) { sae.printStackTrace(); } } public static String getFormDefinition(String formName) throws Exception { return IOUtils.toString(new FileReader(getFormDefinitionPath(formName))); } public static String getFormDefinitionPath(String formName) { return Collect.FORMS_PATH+"/"+formName+"-media/form_definition.json"; } public static JSONObject createFormDefinition(String formXml) throws IOException { try{ Document doc = XmlUtils.parseXml(formXml); NodeList instanceSet = (NodeList) XmlUtils.query("//model/bind", doc, XPathConstants.NODESET); if (instanceSet == null || instanceSet.getLength() == 0){ throw new RuntimeException("No node found at xpath '//model/bind'. Make sure that xform has proper schema"); } NodeList rootNode = (NodeList) XmlUtils.query("//model/instance[1]/*[1]", doc, XPathConstants.NODESET); String rootNodeName = rootNode.item(0).getNodeName(); NodeList repeats = (NodeList) XmlUtils.query("//repeat[@nodeset]", doc, XPathConstants.NODESET); List<String> repeatPaths = new ArrayList<>(); for (int i = 0; i < repeats.getLength(); i++) { repeatPaths.add(repeats.item(i).getAttributes().getNamedItem("nodeset").getNodeValue()); } JSONArray fieldsList = xmlModelToJsonFieldDefinition(instanceSet); JSONObject form = getJsonForm(rootNodeName, fieldsList, repeatPaths); try{ String bindType = XmlUtils.getUniqueAttributeForPath("/"+form.getString("default_bind_path"), "bind_type", doc); if(bindType != null && !bindType.isEmpty()) { form.put("bind_type", bindType); } } catch (Exception e){ e.printStackTrace(); } try{ for (int j = 0; j < repeatPaths.size(); j++) { String sbindType = XmlUtils.getUniqueAttributeForPath("/"+repeatPaths.get(j), "bind_type", doc); if (sbindType != null && !sbindType.isEmpty()){ form.getJSONArray("sub_forms").getJSONObject(j).put("bind_type", sbindType); } } } catch (Exception e){ e.printStackTrace(); } JSONObject formDefinition = new JSONObject(); formDefinition.put("form", form); formDefinition.put("form_data_definition_version", XmlUtils.getUniqueAttributeForPath("/"+form.getString("default_bind_path"), "version", doc)); return formDefinition; } catch(Exception e){ e.printStackTrace(); } return null; } private static JSONArray xmlModelToJsonFieldDefinition(NodeList nodeList) throws DOMException, JSONException { JSONArray dataArr = new JSONArray(); for (int count = 0; count < nodeList.getLength(); count++) { Node tempNode = nodeList.item(count); if (tempNode.getNodeType() == Node.ELEMENT_NODE) { if (tempNode.hasChildNodes() && tempNode.getChildNodes().getLength() > 1) { throw new RuntimeException("Bind has multiple children nodes. Weird schema for Xform"); } else { JSONObject dataObject = new JSONObject(); NamedNodeMap attribs = tempNode.getAttributes(); String nodeset = attribs.getNamedItem("nodeset").getNodeValue(); dataObject.put("name", nodeset.substring(nodeset.lastIndexOf("/")+1)); dataObject.put("bind", nodeset); dataObject.put("type", attribs.getNamedItem("type").getNodeValue()); dataArr.put(dataObject); } } } return dataArr; } private static void addFormFieldObject(JSONObject form, JSONObject fieldNode) throws JSONException { if (!form.has("fields")){ form.put("fields", new JSONArray()); } JSONObject field = new JSONObject(); field.put("name", fieldNode.getString("name")); field.put("bind", "/model/instance"+fieldNode.getString("bind")); form.getJSONArray("fields").put(field); } private static JSONObject createFormObject(String rootNode, String bindPath) throws JSONException { if (bindPath.startsWith("/")){ bindPath = bindPath.substring(1); } JSONObject form = new JSONObject(); form.put("name", rootNode);//update this before saving form.put("bind_type", rootNode);//update this before saving form.put("default_bind_path", "/model/instance/"+bindPath); form.put("fields", new JSONArray()); JSONObject field=new JSONObject(); field.put("name", "id"); field.put("shouldLoadValue", true); form.getJSONArray("fields").put(field); return form; } private static String getRepeatPath(JSONObject field, List<String> repeatPaths) throws JSONException { String bind = field.getString("bind"); for (String rp : repeatPaths) { if(bind.startsWith(rp)){ return rp; } } return null; } private static JSONObject getJsonForm(String rootNode, JSONArray fieldNodeList, List<String> repeatPaths) throws JSONException{ JSONObject subFormMap = new JSONObject(); JSONObject form = createFormObject(rootNode, rootNode); for (int i = 0; i < fieldNodeList.length(); i++) { JSONObject fieldNode = fieldNodeList.getJSONObject(i); String subformPath = getRepeatPath(fieldNode, repeatPaths); if(subformPath == null){ addFormFieldObject(form, fieldNode); } else { JSONObject subF = subFormMap.has(subformPath)?subFormMap.getJSONObject(subformPath):null; if(subF == null){ String subformName = subformPath.substring(subformPath.lastIndexOf("/")+1); subF = createFormObject(subformName, subformPath); subFormMap.put(subformPath, subF); } addFormFieldObject(subF, fieldNode); } } JSONArray subForms = new JSONArray(); Iterator<String> it = subFormMap.keys(); while (it.hasNext()){ subForms.put(subFormMap.get(it.next())); } if(subForms.length()>0) { form.put("sub_forms", subForms); } return form; } }
39.944954
157
0.569706
aeb9af28983ea0e2fd4bd215a31d7fdb44593748
2,055
/* * Copyright (c) 2017 The Regents of the University of California. * All rights reserved. * * '$Author: crawl $' * '$Date: 2017-08-29 15:27:08 -0700 (Tue, 29 Aug 2017) $' * '$Revision: 1392 $' * * Permission is hereby granted, without written agreement and without * license or royalty fees, to use, copy, modify, and distribute this * software and its documentation for any purpose, provided that the above * copyright notice and the following two paragraphs appear in all copies * of this software. * * IN NO EVENT SHALL THE UNIVERSITY OF CALIFORNIA BE LIABLE TO ANY PARTY * FOR DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES * ARISING OUT OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF * THE UNIVERSITY OF CALIFORNIA HAS BEEN ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. * * THE UNIVERSITY OF CALIFORNIA SPECIFICALLY DISCLAIMS ANY WARRANTIES, * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE SOFTWARE * PROVIDED HEREUNDER IS ON AN "AS IS" BASIS, AND THE UNIVERSITY OF * CALIFORNIA HAS NO OBLIGATION TO PROVIDE MAINTENANCE, SUPPORT, UPDATES, * ENHANCEMENTS, OR MODIFICATIONS. * */ package org.kepler.webview.actor; import ptolemy.kernel.util.IllegalActionException; import ptolemy.kernel.util.NameDuplicationException; import ptolemy.kernel.util.NamedObj; import ptolemy.kernel.util.Settable; import ptolemy.kernel.util.StringAttribute; /** * TODO: this class necessary? * */ public class ParametersAttribute extends WebViewAttribute { public ParametersAttribute(NamedObj container, String name) throws IllegalActionException, NameDuplicationException { super(container, name); htmlFile.setExpression("web-view/parameters.html"); title.setExpression("Parameters"); StringAttribute position = new StringAttribute(this, "_webWindowProperties"); position.setExpression("{\"top\":0,\"left\":0}"); position.setVisibility(Settable.NONE); } }
37.363636
85
0.739173
e48a0c19031a6edd9437b8597623d5565a2b51f7
555
package entidades; public class Tbl_rolOpciones { private int idRolOpciones; private int idRol; private int idOpciones; public Tbl_rolOpciones() {} public int getIdRolOpciones() { return idRolOpciones; } public void setIdRolOpciones(int idRolOpciones) { this.idRolOpciones = idRolOpciones; } public int getIdRol() { return idRol; } public void setIdRol(int idRol) { this.idRol = idRol; } public int getIdOpciones() { return idOpciones; } public void setIdOpciones(int idOpciones) { this.idOpciones = idOpciones; } }
15.416667
50
0.726126
5f3ca35ef6288214ad5c002a225da022dedd94a8
3,359
package cc.boeters.bikeplanner.service; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.mchange.v2.c3p0.ComboPooledDataSource; import cc.boeters.bikeplanner.util.QueryUtil; public class BikeNodeService { /** * No route found exception message for astar_bbox. */ private static final String ERROR_VERTEX_WAS_NOT_FOUND = "vertex was not found."; private static final Logger LOG = LoggerFactory.getLogger(BikeNodeService.class); private final String nodesQuery = QueryUtil.getQuery("bikenodebbox"); private final String routeQuery = QueryUtil.getQuery("astar_bbox"); private final Double[] bboxRadiusAttempts = { 0.1, 1.0, 2.0, 5.0 }; private ComboPooledDataSource datasource; public BikeNodeService(ComboPooledDataSource cpds) { this.datasource = cpds; } public String getNodes(Double left, Double bottom, Double right, Double top) { try (Connection connection = datasource.getConnection()) { PreparedStatement prepareStatement = connection.prepareStatement(nodesQuery); prepareStatement.setDouble(1, left); prepareStatement.setDouble(2, bottom); prepareStatement.setDouble(3, right); prepareStatement.setDouble(4, top); long start = System.currentTimeMillis(); ResultSet executeQuery = prepareStatement.executeQuery(); if (executeQuery.next()) { String result = executeQuery.getString(1); executeQuery.close(); prepareStatement.close(); connection.close(); long stop = System.currentTimeMillis(); LOG.info("Nodes query took {} ms.", stop - start); return result; } } catch (SQLException e) { LOG.error("SQL error", e); } return null; } public String getRoute(Long from, Long to) { try (Connection connection = datasource.getConnection()) { for (Double bboxRadius : bboxRadiusAttempts) { LOG.info("Going to execute route (from {}, to {}) query with bbox radius value {}.", from, to, bboxRadius); String route = attemptRoute(from, to, bboxRadius, connection); if (route != null) { LOG.info("Found route for from {}, to {}.", from, to); connection.close(); return route; } } LOG.error("No route found: from {}, to {}.", from, to); connection.close(); } catch (SQLException e) { LOG.error("SQL error", e); } return null; } private String attemptRoute(Long from, Long to, Double bboxRadius, Connection connection) throws SQLException { try { PreparedStatement prepareStatement = connection.prepareStatement(routeQuery); prepareStatement.setDouble(1, bboxRadius); prepareStatement.setLong(2, from); prepareStatement.setLong(3, to); prepareStatement.setLong(4, from); prepareStatement.setLong(5, to); long start = System.currentTimeMillis(); ResultSet executeQuery = prepareStatement.executeQuery(); if (executeQuery.next()) { String result = executeQuery.getString(1); executeQuery.close(); prepareStatement.close(); long stop = System.currentTimeMillis(); LOG.info("Route query took {} ms.", stop - start); return result; } } catch (SQLException e) { if (e.getMessage().endsWith(ERROR_VERTEX_WAS_NOT_FOUND)) { // Lets try with a larger bbox. return null; } throw e; } return null; } }
31.392523
112
0.713308
90a09e71210e0dde60bc28ce76ba55a2a68a3243
1,485
package com.danisola.restify.url.types; import com.danisola.restify.url.RestParser; import com.danisola.restify.url.RestUrl; import org.junit.Test; import static com.danisola.restify.url.RestParserFactory.parser; import static com.danisola.restify.url.matchers.IsInvalid.isInvalid; import static com.danisola.restify.url.matchers.IsValid.isValid; import static com.danisola.restify.url.types.IntArrayVar.intArrayVar; import static org.hamcrest.Matchers.is; import static org.junit.Assert.assertThat; public class IntArrayVarTest { @Test public void whenValueIsCorrectThenIntegerArrayIsReturned() { RestParser parser = parser("/users/update?ids={}", intArrayVar("userIds")); RestUrl url = parser.parse("http://www.mail.com/users/update?ids=-3,8,9&ts=9379"); assertThat(url, isValid()); assertThat((Integer[]) url.variable("userIds"), is(new Integer[] {-3, 8, 9})); } @Test public void whenSomeValueIsNotIntegerThenUrlIsInvalid() { RestParser parser = parser("/users/update?ids={}", intArrayVar("userId")); RestUrl url = parser.parse("http://www.mail.com/users/update?ids=3,a,9&ts=9379"); assertThat(url, isInvalid()); } @Test public void whenVariableIsEmptyThenUrlIsInvalid() { RestParser parser = parser("/users/update?ids={}", intArrayVar("userId")); RestUrl url = parser.parse("http://www.mail.com/users/update?ids=&ts=9379"); assertThat(url, isInvalid()); } }
39.078947
90
0.709764
fa32cfc405c56d3d0295f54223e1123d6c46980a
4,199
/* * This file is part of SpongeAPI, licensed under the MIT License (MIT). * * Copyright (c) SpongePowered <https://www.spongepowered.org> * Copyright (c) contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package org.spongepowered.api.stats; /** * An enumeration of all available {@link Statistic}s from the vanilla game. */ public final class Statistics { public static final Statistic ANIMALS_BRED = null; public static final Statistic ARMOR_CLEANED = null; public static final Statistic BANNER_CLEANED = null; public static final Statistic BEACON_INTERACTION = null; public static final Statistic BOAT_DISTANCE = null; public static final Statistic BREWINGSTAND_INTERACTION = null; public static final Statistic CAKE_SLICES_EATEN = null; public static final Statistic CAULDRON_FILLED = null; public static final Statistic CAULDRON_USED = null; public static final Statistic CHEST_OPENED = null; public static final Statistic CLIMB_DISTANCE = null; public static final Statistic CRAFTING_TABLE_INTERACTION = null; public static final Statistic CROUCH_DISTANCE = null; public static final Statistic DAMAGE_DEALT = null; public static final Statistic DAMAGE_TAKEN = null; public static final Statistic DEATHS = null; public static final Statistic DISPENSER_INSPECTED = null; public static final Statistic DIVE_DISTANCE = null; public static final Statistic DROPPER_INSPECTED = null; public static final Statistic ENDERCHEST_OPENED = null; public static final Statistic FALL_DISTANCE = null; public static final Statistic FISH_CAUGHT = null; public static final Statistic FLOWER_POTTED = null; public static final Statistic FURNACE_INTERACTION = null; public static final Statistic FLY_DISTANCE = null; public static final Statistic HOPPER_INSPECTED = null; public static final Statistic HORSE_DISTANCE = null; public static final Statistic ITEMS_DROPPED = null; public static final Statistic ITEMS_ENCHANTED = null; public static final Statistic NOTEBLOCK_PLAYED = null; public static final Statistic NOTEBLOCK_TUNED = null; public static final Statistic JUMP = null; public static final Statistic JUNK_FISHED = null; public static final Statistic LEAVE_GAME = null; public static final Statistic MINECART_DISTANCE = null; public static final Statistic MOB_KILLS = null; public static final Statistic PIG_DISTANCE = null; public static final Statistic PLAYER_KILLS = null; public static final Statistic TIME_PLAYED = null; public static final Statistic RECORD_PLAYED = null; public static final Statistic SPRINT_DISTANCE = null; public static final Statistic SWIM_DISTANCE = null; public static final Statistic TALKED_TO_VILLAGER = null; public static final Statistic TIME_SINCE_DEATH = null; public static final Statistic TRADED_WITH_VILLAGER = null; public static final Statistic TRAPPED_CHEST_TRIGGERED = null; public static final Statistic TREASURE_FISHED = null; public static final Statistic WALK_DISTANCE = null; private Statistics() { } }
49.4
80
0.765182
8f52e79ed24201b694d5455a94ff9800702e0bba
3,605
package com.amazon.alexa.auto.setup.workflow.fragment; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; import android.app.Application; import android.view.View; import android.widget.TextView; import androidx.annotation.NonNull; import androidx.fragment.app.Fragment; import androidx.fragment.app.FragmentFactory; import androidx.fragment.app.testing.FragmentScenario; import androidx.lifecycle.MutableLiveData; import com.amazon.alexa.auto.apis.app.AlexaApp; import com.amazon.alexa.auto.apis.app.AlexaAppRootComponent; import com.amazon.alexa.auto.apis.auth.AuthState; import com.amazon.alexa.auto.apis.auth.AuthWorkflowData; import com.amazon.alexa.auto.setup.R; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.Mock; import org.mockito.MockedStatic; import org.mockito.Mockito; import org.mockito.MockitoAnnotations; import org.robolectric.RobolectricTestRunner; @RunWith(RobolectricTestRunner.class) public class CBLLoginFinishFragmentTest { @Mock Application mMockApplication; @Mock AlexaApp mMockAlexaApp; @Mock AlexaAppRootComponent mMockRootComponent; @Mock LoginViewModel mMockLoginViewModel; MutableLiveData<AuthWorkflowData> mAuthWorkflowData = new MutableLiveData<>(); @Before public void setup() { MockitoAnnotations.openMocks(this); when(mMockLoginViewModel.loginWorkflowState()).thenReturn(mAuthWorkflowData); } @Test public void testFragmentSetupFinishView() { FragmentScenario<CBLLoginFinishFragment> fragmentScenario = FragmentScenario.launchInContainer( CBLLoginFinishFragment.class, null, new CBLLoginFinishFragmentFactory()); fragmentScenario.onFragment(fragment -> { View view = fragment.getView(); assertNotNull(view); assertEquals(View.VISIBLE, view.findViewById(R.id.cbl_login_finished_layout).getVisibility()); }); } @Test public void testLoginFinishIsNotifiedToViewModel() { FragmentScenario<CBLLoginFinishFragment> fragmentScenario = FragmentScenario.launchInContainer( CBLLoginFinishFragment.class, null, new CBLLoginFinishFragmentFactory()); AuthWorkflowData loginFinished = new AuthWorkflowData(AuthState.CBL_Auth_Finished, null, null); mAuthWorkflowData.setValue(loginFinished); fragmentScenario.onFragment(fragment -> { View view = fragment.getView(); assertNotNull(view); verify(mMockLoginViewModel, times(1)).setupCompleted(); TextView finishView = view.findViewById(R.id.cbl_login_finished_btn); finishView.performClick(); verify(mMockLoginViewModel, times(1)).userFinishedLogin(); }); } /** * Fragment factory to inject mocks into Fragment. */ class CBLLoginFinishFragmentFactory extends FragmentFactory { @NonNull public Fragment instantiate(@NonNull ClassLoader classLoader, @NonNull String className) { try (MockedStatic<AlexaApp> staticMock = Mockito.mockStatic(AlexaApp.class)) { staticMock.when(() -> AlexaApp.from(mMockApplication)).thenReturn(mMockAlexaApp); when(mMockAlexaApp.getRootComponent()).thenReturn(mMockRootComponent); return new CBLLoginFinishFragment(mMockLoginViewModel, mMockApplication); } } } }
35
106
0.73509
24d512d85ccb5a5a0de0ad0197f8661c324592e2
2,538
/* * 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.jclouds.profitbricks.binder.loadbalancer; import static org.testng.Assert.assertEquals; import static org.testng.Assert.assertNotNull; import java.util.List; import com.google.common.collect.Lists; import org.jclouds.profitbricks.domain.LoadBalancer; import org.testng.annotations.Test; @Test(groups = "unit", testName = "UpdateLoadBalancerRequestBinderTest") public class UpdateLoadBalancerRequestBinderTest { @Test public void testDeregisterPayload() { UpdateLoadBalancerRequestBinder binder = new UpdateLoadBalancerRequestBinder(); List<String> serverIds = Lists.newArrayList(); serverIds.add("1"); serverIds.add("2"); LoadBalancer.Request.UpdatePayload payload = LoadBalancer.Request.updatingBuilder() .id("aaaaaaaa-bbbb-cccc-dddd-eeeeeeeeeeee") .name("load-balancer-name") .algorithm(LoadBalancer.Algorithm.ROUND_ROBIN) .ip("10.0.0.2") .build(); String actual = binder.createPayload(payload); assertNotNull(actual, "Binder returned null payload"); assertEquals(actual, expectedPayload); } private final String expectedPayload = (" <ws:updateLoadBalancer>\n" + " <request>\n" + " <loadBalancerId>aaaaaaaa-bbbb-cccc-dddd-eeeeeeeeeeee</loadBalancerId>\n" + " <loadBalancerName>load-balancer-name</loadBalancerName>\n" + " <loadBalancerAlgorithm>ROUND_ROBIN</loadBalancerAlgorithm>\n" + " <ip>10.0.0.2</ip> \n" + " </request>\n" + " </ws:updateLoadBalancer>").replaceAll("\\s+", ""); }
40.935484
102
0.670213
0efe9848e6ac3cb58fe66cd830922298c8d2d277
12,325
/* * Copyright 2004-2015 the Seasar Foundation and the Others. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, * either express or implied. See the License for the specific language * governing permissions and limitations under the License. */ package org.seasar.extension.jdbc.gen.internal.version; import java.io.File; import java.io.FilenameFilter; import java.util.ArrayList; import java.util.List; import javax.sql.DataSource; import org.seasar.extension.jdbc.gen.dialect.GenDialect; import org.seasar.extension.jdbc.gen.event.GenDdlEvent; import org.seasar.extension.jdbc.gen.event.GenDdlListener; import org.seasar.extension.jdbc.gen.internal.exception.NextVersionDirectoryExistsRuntimeException; import org.seasar.extension.jdbc.gen.internal.util.DefaultExcludesFilenameFilter; import org.seasar.extension.jdbc.gen.internal.util.FileUtil; import org.seasar.extension.jdbc.gen.internal.version.wrapper.DdlVersionDirectoryWrapper; import org.seasar.extension.jdbc.gen.version.DdlVersionDirectory; import org.seasar.extension.jdbc.gen.version.DdlVersionDirectoryTree; import org.seasar.extension.jdbc.gen.version.DdlVersionIncrementer; import org.seasar.extension.jdbc.gen.version.ManagedFile; import org.seasar.framework.log.Logger; /** * {@link DdlVersionIncrementer}の実装クラスです。 * * @author taedium */ public class DdlVersionIncrementerImpl implements DdlVersionIncrementer { /** ロガー */ protected static Logger logger = Logger .getLogger(DdlVersionIncrementerImpl.class); /** DDLのバージョンを管理するディレクトリ */ protected DdlVersionDirectoryTree ddlVersionDirectoryTree; /** バージョンディレクトリやファイルが生成されたイベントを受け取るためのリスナー */ protected GenDdlListener genDdlListener; /** 方言 */ protected GenDialect dialect; /** データソース */ protected DataSource dataSource; /** createディレクトリ名のリスト */ protected List<String> createDirNameList = new ArrayList<String>(); /** dropディレクトリ名のリスト */ protected List<String> dropDirNameList = new ArrayList<String>(); /** リカバリ対象のディレクトリのリスト */ protected List<DdlVersionDirectory> recoveryDirList = new ArrayList<DdlVersionDirectory>(); /** * インスタンスを構築します。 * * @param ddlVersionDirectoryTree * DDLのバージョンを管理するディレクトリ * @param genDdlListener * バージョンディレクトリやファイルが生成されたイベントを受け取るためのリスナー * @param dialect * 方言 * @param dataSource * データソース * @param createDirNameList * コピー非対象のcreateディレクトリ名のリスト * @param dropDirNameList * コピー非対象のdropディレクトリ名のリスト */ public DdlVersionIncrementerImpl( DdlVersionDirectoryTree ddlVersionDirectoryTree, GenDdlListener genDdlListener, GenDialect dialect, DataSource dataSource, List<String> createDirNameList, List<String> dropDirNameList) { if (ddlVersionDirectoryTree == null) { throw new NullPointerException("ddlVersionDirectoryTree"); } if (genDdlListener == null) { throw new NullPointerException("genDdlListener"); } if (dialect == null) { throw new NullPointerException("dialect"); } if (dataSource == null) { throw new NullPointerException("dataSource"); } if (createDirNameList == null) { throw new NullPointerException("createDirNameList"); } if (dropDirNameList == null) { throw new NullPointerException("dropDirNameList"); } this.ddlVersionDirectoryTree = ddlVersionDirectoryTree; this.genDdlListener = genDdlListener; this.dialect = dialect; this.dataSource = dataSource; this.createDirNameList.addAll(createDirNameList); this.dropDirNameList.addAll(dropDirNameList); } public void increment(String comment, Callback callback) { try { DdlVersionDirectory currentVersionDir = getCurrentDdlVersionDirectory(); DdlVersionDirectory nextVersionDir = getNextDdlVersionDirectory(currentVersionDir); copyDirectory(currentVersionDir, nextVersionDir); callback.execute(nextVersionDir); if (currentVersionDir.isFirstVersion()) { copyDropDirectory(nextVersionDir, currentVersionDir); } incrementVersionNo(comment); } catch (RuntimeException e) { recover(); throw e; } } /** * 現バージョンに対応するディレクトリを返します。 * * @return 現バージョンに対応するディレクトリ */ protected DdlVersionDirectory getCurrentDdlVersionDirectory() { DdlVersionDirectory currentVersionDir = ddlVersionDirectoryTree .getCurrentVersionDirectory(); makeDirectory(currentVersionDir); return currentVersionDir; } /** * 次バージョンに対応するディレクトリを返します。 * * @param currentVersionDir * 現バージョンに対応するディレクトリ * @return 次バージョンに対応するディレクトリ */ protected DdlVersionDirectory getNextDdlVersionDirectory( final DdlVersionDirectory currentVersionDir) { final DdlVersionDirectory nextVersionDir = ddlVersionDirectoryTree .getNextVersionDirectory(); if (nextVersionDir.exists()) { throw new NextVersionDirectoryExistsRuntimeException(nextVersionDir .asFile().getPath()); } DdlVersionDirectory wrapper = new DdlVersionDirectoryWrapper( nextVersionDir, genDdlListener, currentVersionDir, nextVersionDir) { @Override public boolean mkdir() { if (getManagedFile().exists()) { return false; } GenDdlEvent event = new GenDdlEvent(this, currentVersionDir, nextVersionDir); genDdlListener.preCreateNextVersionDir(event); boolean made = getManagedFile().mkdir(); if (made) { genDdlListener.postCreateNextVersionDir(event); } return made; } @Override public boolean delete() { if (!getManagedFile().exists()) { return false; } GenDdlEvent event = new GenDdlEvent(this, currentVersionDir, nextVersionDir); genDdlListener.preRemoveNextVersionDir(event); boolean deleted = super.delete(); if (deleted) { genDdlListener.postRemoveNextVersionDir(event); } return deleted; } }; makeDirectory(wrapper); return wrapper; } /** * バージョンディレクトリを作成します。 * * @param versionDir * バージョンディレクトリ */ protected void makeDirectory(DdlVersionDirectory versionDir) { if (versionDir.mkdirs()) { recoveryDirList.add(versionDir); } } /** * バージョンディレクトリをコピーします。 * * @param src * コピー元のバージョンディレクトリ * @param dest * コピー先のバージョンディレクトリ */ protected void copyDirectory(DdlVersionDirectory src, DdlVersionDirectory dest) { ManagedFile srcCreateDir = src.getCreateDirectory(); ManagedFile destCreateDir = dest.getCreateDirectory(); copyDir(srcCreateDir, destCreateDir, new PathFilenameFilter( srcCreateDir.asFile(), createDirNameList)); ManagedFile srcDropDir = src.getDropDirectory(); ManagedFile destDropDir = dest.getDropDirectory(); copyDir(srcDropDir, destDropDir, new PathFilenameFilter(srcDropDir .asFile(), dropDirNameList)); } /** * dropディレクトリを作成します。 * * @param src * コピー元のバージョンディレクトリ * @param dest * コピー先のバージョンディレクトリ */ protected void copyDropDirectory(DdlVersionDirectory src, DdlVersionDirectory dest) { ManagedFile srcDropDir = src.getDropDirectory(); ManagedFile destDropDir = dest.getDropDirectory(); copyDir(srcDropDir, destDropDir, new DefaultExcludesFilenameFilter()); } /** * ディレクトリをコピーします。 * * @param srcDir * コピー元のディレクトリ * @param destDir * コピー先のディレクトリ * @param filter * フィルタ */ protected void copyDir(ManagedFile srcDir, ManagedFile destDir, FilenameFilter filter) { destDir.mkdirs(); for (ManagedFile src : srcDir.listManagedFiles(filter)) { ManagedFile dest = destDir.createChild(src.getName()); if (src.isDirectory()) { copyDir(src, dest, filter); } else { dest.createNewFile(); FileUtil.copy(src.asFile(), dest.asFile()); } } } /** * 作成したバージョンディレクトリを削除します。 */ protected void recover() { for (DdlVersionDirectory dir : recoveryDirList) { if (!dir.exists()) { return; } try { deleteDir(dir); } catch (Exception e) { logger.log(e); } } } /** * ディレクトリを削除します。 * * @param dir * ディレクトリ */ protected void deleteDir(ManagedFile dir) { for (ManagedFile file : dir.listManagedFiles()) { if (file.isDirectory()) { deleteDir(file); file.delete(); } else { file.delete(); } } dir.delete(); } /** * バージョン番号を増分します。 * * @param comment * バージョンを増分する理由を示すコメント */ protected void incrementVersionNo(String comment) { ddlVersionDirectoryTree.getDdlInfoFile().applyNextVersionNo(comment); } /** * 除外対象のパスで始まるファイル名をフィルタします。 * * @author taedium */ protected static class PathFilenameFilter implements FilenameFilter { /** 除外対象パスのリスト */ protected List<String> excludePathList = new ArrayList<String>(); /** ファイル名のフィルタ */ protected FilenameFilter filenameFilter; /** * インスタンスを構築します。 * * @param baseDir * ベースディレクトリ * @param excludeDirNameList * 除外ディレクトリ名のリスト */ protected PathFilenameFilter(File baseDir, List<String> excludeDirNameList) { filenameFilter = new DefaultExcludesFilenameFilter(); setupFilterPathList(baseDir, excludeDirNameList); } /** * コピー対象外のパスのリストをセットアップします。 * * @param dir * ディレクトリ * @param dirNameList * ディレクトリ名のリスト */ protected void setupFilterPathList(File dir, List<String> dirNameList) { for (String name : dirNameList) { File file = new File(dir, name); excludePathList.add(FileUtil.getCanonicalPath(file)); } } public boolean accept(File dir, String name) { if (!filenameFilter.accept(dir, name)) { return false; } for (String path : excludePathList) { File file = new File(dir, name); if (FileUtil.getCanonicalPath(file).startsWith(path)) { return false; } } return true; } } }
33.13172
100
0.581258
a9165df18a17ae64b84a403956e47bcb9a1c669a
17,426
/* * Copyright Anatoly Starostin (c) 2017. */ package treeton.gui; import org.jdesktop.swingx.JXTree; import treeton.gui.util.MergedIcon; import treeton.prosody.corpus.Corpus; import treeton.prosody.corpus.CorpusEntry; import treeton.prosody.corpus.CorpusFolder; import treeton.prosody.corpus.CorpusListener; import javax.swing.*; import javax.swing.tree.*; import java.awt.*; import java.util.*; public class ProsodyCorpusTreePanel implements CorpusListener { private JXTree tree = new JXTree(); private DefaultTreeModel model = (DefaultTreeModel)tree.getModel(); private Map<CorpusFolder, DefaultMutableTreeNode> foldersToNodes = new HashMap<CorpusFolder, DefaultMutableTreeNode>(); private Map<CorpusEntry, Collection<DefaultMutableTreeNode>> entriesToNodes = new HashMap<CorpusEntry, Collection<DefaultMutableTreeNode>>(); private Corpus corpus; private MergedIcon manuallyEditedOpenFolderIcon; private MergedIcon manuallyEditedClosedFolderIcon; private MergedIcon manuallyEditedEntryIcon; private Set<CorpusFolder> manuallyEditedFolders = new HashSet<CorpusFolder>(); public void reload() { model.reload(); } public ProsodyCorpusTreePanel( Corpus corpus ) { this.corpus = corpus; importCorpus(); initGui(); corpus.addListener(this); } Comparator<DefaultMutableTreeNode> mutableTreeNodeComparator = new Comparator<DefaultMutableTreeNode>() { @Override public int compare(DefaultMutableTreeNode o1, DefaultMutableTreeNode o2) { return o1.getUserObject().toString().compareTo(o2.getUserObject().toString()); } }; private void importCorpus() { DefaultMutableTreeNode root = new DefaultMutableTreeNode(); model.setRoot(root); ArrayList<DefaultMutableTreeNode> childFolderNodes = new ArrayList<DefaultMutableTreeNode>(); for (CorpusFolder corpusFolder : corpus.getRootCorpusFolders()) { DefaultMutableTreeNode childNode = importFolder( corpusFolder); childFolderNodes.add( childNode ); } childFolderNodes.sort(mutableTreeNodeComparator); for (DefaultMutableTreeNode folderNode : childFolderNodes) { root.add( folderNode ); } } private DefaultMutableTreeNode importFolder( CorpusFolder folder ) { DefaultMutableTreeNode result = new DefaultMutableTreeNode(); result.setUserObject( folder ); foldersToNodes.put( folder, result ); boolean manualEdit = false; ArrayList<DefaultMutableTreeNode> childFolderNodes = new ArrayList<DefaultMutableTreeNode>(); for (CorpusFolder corpusFolder : folder.getChildFolders()) { DefaultMutableTreeNode childNode = importFolder( corpusFolder); childFolderNodes.add( childNode ); if( manuallyEditedFolders.contains( corpusFolder ) ) { manualEdit = true; } } ArrayList<DefaultMutableTreeNode> childEntryNodes = new ArrayList<DefaultMutableTreeNode>(); for (CorpusEntry corpusEntry : folder.getEntries()) { DefaultMutableTreeNode childNode = importEntry(corpusEntry); childEntryNodes.add( childNode ); if( corpusEntry.getManualEditionStamp() >= 0 ) { manualEdit = true; } } if( manualEdit ) { manuallyEditedFolders.add( folder ); } childFolderNodes.sort(mutableTreeNodeComparator); childEntryNodes.sort(mutableTreeNodeComparator); for (DefaultMutableTreeNode folderNode : childFolderNodes) { result.add( folderNode ); } for (DefaultMutableTreeNode entryNode : childEntryNodes) { result.add( entryNode ); } return result; } private DefaultMutableTreeNode importEntry( CorpusEntry entry ) { DefaultMutableTreeNode result = new DefaultMutableTreeNode(); result.setUserObject( entry ); if( !entriesToNodes.containsKey( entry ) ) { entriesToNodes.put( entry, new HashSet<DefaultMutableTreeNode>() ); } entriesToNodes.get( entry ).add(result); return result; } private void initGui(){ ToolTipManager.sharedInstance().registerComponent(tree); tree.setRootVisible(false); tree.expandPath(new TreePath(model.getRoot())); ToolTipManager.sharedInstance().registerComponent(tree); ToolTipManager.sharedInstance().setDismissDelay(ToolTipManager.sharedInstance().getDismissDelay()*4); DefaultTreeCellRenderer cellRenderer = new DefaultTreeCellRenderer(); ImageIcon img = GuiResources.getImageIcon("pencil.gif"); manuallyEditedOpenFolderIcon = new MergedIcon( cellRenderer.getDefaultOpenIcon(), img ); manuallyEditedClosedFolderIcon = new MergedIcon( cellRenderer.getDefaultClosedIcon(), img ); manuallyEditedEntryIcon = new MergedIcon( cellRenderer.getDefaultLeafIcon(), img ); tree.setCellRenderer(new DefaultTreeCellRenderer() { @Override public Component getTreeCellRendererComponent(JTree tree, Object value, boolean sel, boolean expanded, boolean leaf, int row, boolean hasFocus) { JLabel label = (JLabel) super.getTreeCellRendererComponent(tree, value, sel, expanded, leaf, row, hasFocus); DefaultMutableTreeNode node = (DefaultMutableTreeNode) value; if( node == null ) { return label; } if( node.getUserObject() instanceof CorpusFolder ) { if( manuallyEditedFolders.contains( node.getUserObject() )) { label.setIcon(expanded ? manuallyEditedOpenFolderIcon : manuallyEditedClosedFolderIcon); } else { label.setIcon( (expanded || leaf) ? getDefaultOpenIcon() : getDefaultClosedIcon() ); } label.setToolTipText(null); } else if( node.getUserObject() instanceof CorpusEntry ) { if( ((CorpusEntry) node.getUserObject()).getManualEditionStamp() >= 0 ) { label.setIcon(manuallyEditedEntryIcon); } if( entryTooltipProvider != null ) { label.setToolTipText(entryTooltipProvider.getTooltip( (CorpusEntry) node.getUserObject() )); } else { label.setToolTipText(null); } } return label; } }); } public JXTree getJXTree() { return tree; } @Override public void entryCreated(CorpusEntry entry) { assert false; // Пока что новые входы через gui не создаем } @Override public void entryDeleted(CorpusEntry entry, Collection<CorpusFolder> parentFolders ) { for (DefaultMutableTreeNode node : entriesToNodes.get(entry)) { model.removeNodeFromParent( node ); } entriesToNodes.remove(entry); for (CorpusFolder folder : parentFolders) { handleChildReload(folder); } } @Override public void entryNameChanged(CorpusEntry entry) { Collection<DefaultMutableTreeNode> treeNodes = entriesToNodes.get( entry ); for (DefaultMutableTreeNode treeNode : treeNodes) { model.removeNodeFromParent( treeNode ); } entriesToNodes.remove(entry); for (CorpusFolder folder : entry.getParentFolders()) { DefaultMutableTreeNode folderNode = foldersToNodes.get( folder ); int leftbound = folder.getChildFolders().size(); int newPlace = addChildNode( folderNode, importEntry( entry ), leftbound , leftbound + folder.getEntries().size() - 1 ); model.nodesWereInserted( folderNode, new int[] {newPlace} ); } } @Override public void entryTextChanged(CorpusEntry entry) { for (CorpusFolder corpusFolder : entry.getParentFolders()) { handleChildReload(corpusFolder); } Collection<DefaultMutableTreeNode> treeNodes = entriesToNodes.get( entry ); for (DefaultMutableTreeNode treeNode : treeNodes) { model.nodeChanged( treeNode ); } } @Override public void entryMetadataManuallyEdited(CorpusEntry entry) { for (CorpusFolder corpusFolder : entry.getParentFolders()) { handleManualEdit(corpusFolder); } Collection<DefaultMutableTreeNode> treeNodes = entriesToNodes.get( entry ); for (DefaultMutableTreeNode treeNode : treeNodes) { model.nodeChanged( treeNode ); } } private void handleManualEdit(CorpusFolder corpusFolder) { manuallyEditedFolders.add(corpusFolder); if( corpusFolder.getParentFolder() != null) { handleManualEdit( corpusFolder.getParentFolder() ); } DefaultMutableTreeNode treeNode = foldersToNodes.get( corpusFolder ); model.nodeChanged( treeNode ); } @Override public void entryMetadataReloaded(CorpusEntry entry) { for (CorpusFolder corpusFolder : entry.getParentFolders()) { handleChildReload(corpusFolder); } Collection<DefaultMutableTreeNode> treeNodes = entriesToNodes.get( entry ); for (DefaultMutableTreeNode treeNode : treeNodes) { model.nodeChanged( treeNode ); } } private void handleChildReload(CorpusFolder folder) { boolean manualEditDetected = false; for (CorpusFolder corpusFolder : folder.getChildFolders()) { if( manuallyEditedFolders.contains( corpusFolder ) ) { manualEditDetected = true; } } for (CorpusEntry corpusEntry : folder.getEntries()) { if( corpusEntry.getManualEditionStamp() >= 0 ) { manualEditDetected = true; } } if( manualEditDetected ) { manuallyEditedFolders.add(folder); } else if( manuallyEditedFolders.contains(folder) ){ manuallyEditedFolders.remove(folder); } if( folder.getParentFolder() != null) { handleChildReload(folder.getParentFolder()); } } @Override public void folderCreated(CorpusFolder folder) { CorpusFolder parentFolder = folder.getParentFolder(); DefaultMutableTreeNode parentNode; if( parentFolder == null ) { parentNode = (DefaultMutableTreeNode) model.getRoot(); } else { parentNode = foldersToNodes.get( parentFolder ); } assert parentNode != null; assert folder.getChildFolders().isEmpty() && folder.getEntries().isEmpty(); DefaultMutableTreeNode newNode = new DefaultMutableTreeNode(); newNode.setUserObject(folder); foldersToNodes.put( folder, newNode ); model.nodesWereInserted(parentNode, new int[]{addChildNode(parentNode, newNode, 0, parentFolder == null ? corpus.getRootCorpusFolders().size() - 1 : parentFolder.getChildFolders().size() - 1)}); } private int addChildNode(DefaultMutableTreeNode parentNode, DefaultMutableTreeNode childNode, int leftbound, int rightbound ) { if( rightbound == leftbound ) { parentNode.insert(childNode,leftbound); return leftbound; } DefaultMutableTreeNode firstNode = (DefaultMutableTreeNode) parentNode.getChildAt(leftbound); if( mutableTreeNodeComparator.compare( childNode, firstNode ) < 0 ) { parentNode.insert( childNode, leftbound ); return leftbound; } DefaultMutableTreeNode lastNode = (DefaultMutableTreeNode) parentNode.getChildAt(rightbound-1); if( mutableTreeNodeComparator.compare( childNode, lastNode ) > 0 ) { parentNode.insert(childNode,rightbound); return rightbound; } while( rightbound > leftbound ) { int middle = leftbound + ( rightbound - leftbound ) / 2; DefaultMutableTreeNode middleNode = (DefaultMutableTreeNode) parentNode.getChildAt(middle); int cmp = mutableTreeNodeComparator.compare( childNode, middleNode ); if( cmp == 0 ) { parentNode.insert( childNode, middle ); return middle; } else if( cmp < 0 ) { rightbound = middle; } else { leftbound = middle + 1; } } assert leftbound == rightbound; parentNode.insert(childNode,leftbound); return leftbound; } @Override public void folderNameChanged(CorpusFolder folder) { DefaultMutableTreeNode oldFolderNode = foldersToNodes.get( folder ); TreeNode[] pathArray = model.getPathToRoot(oldFolderNode); TreePath path = new TreePath(pathArray); boolean wasExpanded = tree.isExpanded(path); boolean wasSelected = tree.isPathSelected(path); model.removeNodeFromParent( oldFolderNode ); foldersToNodes.remove(folder); CorpusFolder parentFolder = folder.getParentFolder(); DefaultMutableTreeNode parentNode; if( parentFolder == null ) { parentNode = (DefaultMutableTreeNode) model.getRoot(); } else { parentNode = foldersToNodes.get( parentFolder ); } DefaultMutableTreeNode newFolderNode = new DefaultMutableTreeNode( folder ); foldersToNodes.put( folder, newFolderNode ); while( oldFolderNode.getChildCount() > 0 ) { newFolderNode.add((MutableTreeNode) oldFolderNode.getFirstChild()); } int newPlace = addChildNode( parentNode, newFolderNode, 0, parentFolder == null ? corpus.getRootCorpusFolders().size() - 1 : parentFolder.getChildFolders().size() - 1 ); model.nodesWereInserted( parentNode, new int[] {newPlace} ); if( wasExpanded ) { pathArray[pathArray.length-1] = newFolderNode; tree.expandPath( new TreePath(pathArray) ); } if( wasSelected ) { pathArray[pathArray.length-1] = newFolderNode; tree.addSelectionPath( new TreePath(pathArray) ); } } @Override public void folderParentChanged(CorpusFolder folder, CorpusFolder oldParent) { DefaultMutableTreeNode folderNode = foldersToNodes.get(folder); model.removeNodeFromParent(folderNode); CorpusFolder parentFolder = folder.getParentFolder(); DefaultMutableTreeNode parentNode; if( parentFolder == null ) { parentNode = (DefaultMutableTreeNode) model.getRoot(); } else { parentNode = foldersToNodes.get( parentFolder ); } assert parentNode != null; model.nodesWereInserted(parentNode, new int[]{addChildNode(parentNode, folderNode, 0, parentFolder == null ? corpus.getRootCorpusFolders().size() - 1 : parentFolder.getChildFolders().size() - 1)}); } @Override public void entryWasPlacedIntoFolder(CorpusEntry entry, CorpusFolder folder) { DefaultMutableTreeNode corpusFolderNode = foldersToNodes.get(folder); int leftbound = folder.getChildFolders().size(); int newPlace = addChildNode( corpusFolderNode, importEntry( entry ), leftbound , leftbound + folder.getEntries().size() - 1 ); model.nodesWereInserted( corpusFolderNode, new int[] {newPlace} ); if( entry.getManualEditionStamp() >= 0 ) { handleManualEdit( folder ); } } @Override public void entryWasRemovedFromFolder(CorpusEntry entry, CorpusFolder folder) { for (DefaultMutableTreeNode node : entriesToNodes.get(entry)) { if( ((DefaultMutableTreeNode)node.getParent()).getUserObject() == folder ) { model.removeNodeFromParent( node ); entriesToNodes.get(entry).remove(node); break; } } handleChildReload(folder); } @Override public void folderDeleted(CorpusFolder folder) { DefaultMutableTreeNode treeNode = foldersToNodes.get(folder); model.removeNodeFromParent( treeNode ); foldersToNodes.remove( folder ); } @Override public void corpusLabelChanged() { Component parent = tree.getParent(); while( parent != null ) { if( parent instanceof JInternalFrame ) { ((JInternalFrame)parent).setTitle( ((JInternalFrame)parent).getTitle() + ": " + corpus.getCorpusLabel() ); parent.revalidate(); break; } parent = parent.getParent(); } } @Override public void globalCorpusPropertyChanged(String propertyName) { // TODO не факт, что здесь что-то надо делать } public void onClose() { corpus.removeListener( this ); } // TODO scroll, select, find EntryTooltipProvider entryTooltipProvider; public void setEntryTooltipProvider(EntryTooltipProvider entryTooltipProvider) { this.entryTooltipProvider = entryTooltipProvider; } public interface EntryTooltipProvider { String getTooltip( CorpusEntry entry ); } }
35.782341
157
0.641513
3a5fbaa6a563b12afa2f071abb1776887aae2779
7,403
package com.kemal; import java.io.IOException; import java.nio.file.Path; import java.nio.file.Paths; import java.util.ArrayList; import java.util.List; import zemberek.morphology.TurkishMorphology; import zemberek.morphology.analysis.AnalysisFormatters; import zemberek.morphology.analysis.InformalAnalysisConverter; import zemberek.morphology.analysis.SentenceAnalysis; import zemberek.morphology.analysis.SingleAnalysis; import zemberek.morphology.analysis.SingleAnalysis.MorphemeGroup; import zemberek.morphology.analysis.WordAnalysis; import zemberek.morphology.lexicon.DictionaryItem; import zemberek.morphology.lexicon.RootLexicon; import zemberek.normalization.TurkishSentenceNormalizer; import zemberek.normalization.TurkishSpellChecker; import zemberek.tokenization.Token; import zemberek.tokenization.TurkishTokenizer; import zemberek.tokenization.antlr.TurkishLexer; public class Morphology { TurkishMorphology morphology; TurkishSentenceNormalizer normalizer; TurkishTokenizer tokenizer; TurkishSpellChecker spellChecker; public Morphology() { // TODO Auto-generated constructor stub this.morphology = TurkishMorphology.createWithDefaults(); Path lookupRoot = Paths.get("/home/kemal/.nlp/zemberek/normalization"); Path lmFile = Paths.get("/home/kemal/.nlp/zemberek/lm/lm.2gram.slm"); try { this.normalizer = new TurkishSentenceNormalizer(this.morphology, lookupRoot, lmFile); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } this.tokenizer = TurkishTokenizer.builder(). ignoreTypes(Token.Type.Punctuation,Token.Type.NewLine, Token.Type.SpaceTab).build(); try { this.spellChecker = new TurkishSpellChecker(this.morphology); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } public String analyze(String word) { String resultString = ""; WordAnalysis results = morphology.analyze(word); resultString += word + ":\n"; for (SingleAnalysis result : results) { resultString += result.formatLong() + "\n"; resultString += "Stems: " + result.getStems() + "\n"; resultString += "Lemmas: " + result.getLemmas() + "\n"; resultString += "Lexical Format: " + result.formatLexical() + "\n"; resultString += "Oflazer Style: " + AnalysisFormatters.OFLAZER_STYLE.format(result) + "\n"; } return resultString; } public String analyzeInformal(String sentence) { String resultString = ""; resultString += sentence + ":\n"; TurkishMorphology morphology = TurkishMorphology.builder() .setLexicon(RootLexicon.getDefault()) .useInformalAnalysis() .build(); List<SingleAnalysis> analyses = morphology .analyzeAndDisambiguate(sentence) .bestAnalysis(); for (SingleAnalysis a : analyses) { resultString += a.surfaceForm() + "\t: " + a + "\n"; } resultString += "Converting formal surface form:\n"; InformalAnalysisConverter converter = new InformalAnalysisConverter(morphology.getWordGenerator()); for (SingleAnalysis a : analyses) { resultString += converter.convert(a.surfaceForm(), a) + "\n"; } return resultString; } public String normalizeWord(String word) { String resultString = ""; resultString += word + ":\n"; resultString += "Correct form -> " + this.spellChecker.check(word) + "\n"; resultString += "Suggestions - > " + this.spellChecker.suggestForWord(word) + "\n"; return resultString; } public boolean spellCheck(String word) { return this.spellChecker.check(word); } public List<String> suggestForWord(String word) { return this.spellChecker.suggestForWord(word); } public String normalizeSentence(String sentence) { String resultString = ""; //resultString += sentence + ":\n"; resultString += this.normalizer.normalize(sentence); return resultString; } public List<String> tokenizeSentence(String sentence) { List<String> tokenList = new ArrayList<String>(); List<Token> tokens = this.tokenizer.tokenize(sentence); for (Token token : tokens) { tokenList.add(token.getText()); } return tokenList; } public String tokenizeSentenceTest(String sentence) { String resultString = ""; resultString += sentence + ":\n"; List<Token> tokens = this.tokenizer.tokenize(sentence); for (Token token : tokens) { resultString += token.getText() + " "; //resultString += token.getType() + " "; //System.out.println("Type = " + TurkishLexer.VOCABULARY.getDisplayName(token.getType())); } resultString += "\n"; return resultString; } /** * Method to try some words * @param word * @return */ public List<String> findLemmasOfGivenWord(String word) { try { WordAnalysis results = morphology.analyze(word); SingleAnalysis result = results.getAnalysisResults().get(0); List<String> lemmas = result.getLemmas(); return lemmas; } catch (Exception e) { System.out.println(e.getMessage()); return new ArrayList<String>(); } } /** * Method to try some words * @param word * @return */ public String findLemmaOfGivenWord(String word) { try { WordAnalysis results = morphology.analyze(word); SingleAnalysis result = results.getAnalysisResults().get(0); List<String> lemmas = result.getLemmas(); return lemmas.get(lemmas.size() - 1); } catch (Exception e) { System.out.println(e.getMessage()); return word; } } public String[] lemmatizeTweetWithDisambiguation(String tweet) { String resultString = ""; String resultString2 = ""; List<WordAnalysis> analysis = this.morphology.analyzeSentence(tweet); SentenceAnalysis after = morphology.disambiguate(tweet, analysis); for(SingleAnalysis newAnalysis: after.bestAnalysis()) { List<String> lemmas = newAnalysis.getLemmas(); DictionaryItem item = newAnalysis.getDictionaryItem(); String lemma = item.lemma; String currentWord1 = ""; String currentWord2 = ""; if(newAnalysis.isUnknown()) { currentWord1 = newAnalysis.getStem(); currentWord2 = currentWord1; } else if(item.secondaryPos.shortForm == "Mention") { currentWord1 = lemma.replace("?", "@"); currentWord2 = lemma.replace("?", "@"); } else if (item.secondaryPos.shortForm == "HashTag") { currentWord1 = lemma.replace("?", "#"); currentWord2 = lemma.replace("?", "#"); } else { currentWord1 = lemmas.get(lemmas.size()-1) + " "; currentWord2 = lemma; } resultString += currentWord1 + " "; resultString2 += currentWord2 + " "; } String[] results = {resultString, resultString2}; return results; } public void tryDisambiguation(String sentence) { System.out.println("Sentence = " + sentence); List<WordAnalysis> analysis = this.morphology.analyzeSentence(sentence); System.out.println("Before disambiguation."); for (WordAnalysis entry : analysis) { System.out.println("Word = " + entry.getInput()); for (SingleAnalysis single : entry) { System.out.println(single.formatLong()); } } System.out.println("\nAfter disambiguation."); SentenceAnalysis after = morphology.disambiguate(sentence, analysis); after.bestAnalysis().forEach(s-> System.out.println(s.formatLong())); } }
29.145669
99
0.68972
cb51883f3ff9979287ccf255a8a69c894e19b723
406
package com.jakduk.api.restcontroller.vo.gallery; import com.jakduk.api.common.Constants; /** * Created by pyohwanjang on 2017. 4. 14.. */ public class LinkedItemForm { private String itemId; // 아이템 ID private Constants.GALLERY_FROM_TYPE from; // 출처 public String getItemId() { return itemId; } public Constants.GALLERY_FROM_TYPE getFrom() { return from; } }
19.333333
51
0.674877
e1576b4a86c12e89b1cde32512a0f4ad23a9b38d
11,818
/** * Copyright 2014-2021 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package node.mgr.test.cert; import static com.webank.webase.node.mgr.tools.CertTools.byteToHex; import com.webank.webase.node.mgr.base.code.ConstantCode; import com.webank.webase.node.mgr.base.exception.NodeMgrException; import com.webank.webase.node.mgr.tools.NodeMgrTools; import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.InputStream; import java.security.InvalidAlgorithmParameterException; import java.security.InvalidKeyException; import java.security.NoSuchAlgorithmException; import java.security.NoSuchProviderException; import java.security.SignatureException; import java.security.cert.CertificateEncodingException; import java.security.cert.CertificateException; import java.security.cert.CertificateExpiredException; import java.security.cert.CertificateFactory; import java.security.cert.CertificateNotYetValidException; import java.security.cert.X509Certificate; import java.util.ArrayList; import java.util.Base64; import java.util.List; import org.fisco.bcos.sdk.crypto.CryptoSuite; import org.fisco.bcos.sdk.crypto.keypair.CryptoKeyPair; import org.fisco.bcos.sdk.crypto.keystore.PEMKeyStore; import org.fisco.bcos.sdk.model.CryptoType; import org.fisco.bcos.sdk.utils.Numeric; import org.junit.Test; import org.springframework.core.io.ClassPathResource; import org.springframework.util.Assert; import sun.security.ec.ECPublicKeyImpl; /** * test load non-guomi cert and guomi cert * using java.security.cert.CertificateFactory getInstance("X.509"); * 2019/12 * replace java.security.cert.CertificateFactory * with org.bouncycastle.jcajce.provider.asymmetric.x509.CertificateFactory */ public class ImportCertTest { private final static String head = "-----BEGIN CERTIFICATE-----\n" ; private final static String tail = "-----END CERTIFICATE-----\n" ; @Test public void testPubAddress() throws IOException, CertificateException, IllegalAccessException, InstantiationException { /** * @param: nodeCert * 只有节点证书才是ECC椭圆曲线,获取pub的方法和区块链的一致 * 其余的agency chain 的crt都是rsa方法,使用大素数方法计算,不一样 */ // need crt file InputStream node = new ClassPathResource("node.crt").getInputStream(); CertificateFactory cf = CertificateFactory.getInstance("X.509"); X509Certificate nodeCert = (X509Certificate) cf.generateCertificate(node); // rsa算法的公钥和ecc的不一样 ECPublicKeyImpl pub = (ECPublicKeyImpl) nodeCert.getPublicKey(); byte[] pubBytes = pub.getEncodedPublicValue(); String publicKey = Numeric.toHexStringNoPrefix(pubBytes); CryptoSuite cryptoSuite = new CryptoSuite(CryptoType.ECDSA_TYPE); String address = cryptoSuite.createKeyPair().getAddress(publicKey); byte[] addByteArray = cryptoSuite.createKeyPair().getAddress(pubBytes); System.out.println("byte[] : pub "); System.out.println(pubBytes); System.out.println("===================================="); System.out.println(publicKey); // 04e5e7efc9e8d5bed699313d5a0cd5b024b3c11811d50473b987b9429c2f6379742c88249a7a8ea64ab0e6f2b69fb8bb280454f28471e38621bea8f38be45bc42d System.out.println("byte[] to pub to address "); System.out.println(address); // f7b2c352e9a872d37a427601c162671202416dbc System.out.println("包含开头的04"); System.out.println(byteToHex(addByteArray)); } /** * address到底需不需要传入pub的开头的两位04 * 答案: 不需要,公钥是128位的 */ @Test public void testAddress() throws InvalidAlgorithmParameterException, NoSuchAlgorithmException, NoSuchProviderException { CryptoSuite cryptoSuite = new CryptoSuite(CryptoType.ECDSA_TYPE); CryptoKeyPair key = cryptoSuite.createKeyPair(); // 用byte[]穿进去获取公钥,就会可能多出一位0 System.out.println("=============原生的=============="); System.out.println(key.getHexPublicKey()); //64bytes BigInteger System.out.println(key.getAddress()); // System.out.println("===========通过转成hex后获取地址============"); // System.out.println(Numeric.toHexStringNoPrefix(key.getPublicKey())); //Hex后显示 // System.out.println(Keys.getAddress(Numeric.toHexStringNoPrefix(key.getPublicKey()))); // // System.out.println("===========通过byte[]============"); // System.out.println(Numeric.toHexStringNoPrefix(pubBytes)); // BigInteget=> byte[] => hex 多一位 // System.out.println(Keys.getAddress(Numeric.toHexStringNoPrefix(pubBytes))); // System.out.println("==============="); // System.out.println(Keys.getAddress(pubBytes)); } @Test public void testImport() throws IOException, CertificateException, NoSuchAlgorithmException, InvalidKeyException, SignatureException, NoSuchProviderException { // read from file is InputStream pem = new ClassPathResource("node.crt").getInputStream(); CertificateFactory cf = CertificateFactory.getInstance("X.509"); // agency's crt List<X509Certificate> certs = (List<X509Certificate>) cf.generateCertificates(pem); for(X509Certificate c: certs) { System.out.println(c.getSubjectDN()); } X509Certificate nodeCert = certs.get(0); // X509Certificate agencyCert = certs.get(1); // X509Certificate caCert = certs.get(2); // //只能验证上一级 // agencyCert.verify(caCert.getPublicKey()); // nodeCert.verify(agencyCert.getPublicKey()); /** * 根据subjectDN 获取证书类型,证书名字 */ } @Test public void getSingleCrtContent() throws IOException { // read from file is InputStream pem = new ClassPathResource("node.crt").getInputStream(); String certContent = getString(pem); List<String> list = new ArrayList<>(); String[] nodeCrtStrArray = certContent.split(head); for(int i = 0; i < nodeCrtStrArray.length; i++) { String[] nodeCrtStrArray2 = nodeCrtStrArray[i].split(tail); for(int j = 0; j < nodeCrtStrArray2.length; j++) { String ca = nodeCrtStrArray2[j]; if(ca.length() != 0) { list.add(formatStr(ca)); } } } for(String s: list) { System.out.println(s); System.out.println(); } } public static String formatStr(String string) { return string.substring(0, string.length() - 1); } public static String getString(InputStream inputStream) throws IOException { byte[] bytes = new byte[0]; bytes = new byte[inputStream.available()]; inputStream.read(bytes); String str = new String(bytes); return str; } public String getFingerPrint(X509Certificate cert)throws Exception { // 指纹 /** * Microsoft's presentation of certificates is a bit misleading * because it presents the fingerprint as if it was contained in the certificate * but actually Microsoft has to calculate the fingerprint, too. * This is especially misleading because a certificate actually has many fingerprints, * and Microsoft only displays the fingerprint it seems to use internally, i.e. the SHA-1 fingerprint. */ String finger = NodeMgrTools.getCertFingerPrint(cert.getEncoded()); System.out.println("指纹"); System.out.println(finger); return finger; } public static boolean isExpired2(X509Certificate cert) { try { cert.checkValidity(); return false; } catch (CertificateExpiredException e) { System.out.println("Certificate Expired"); return true; } catch (CertificateNotYetValidException e) { System.out.println("Certificate Not Yet Valid"); return true; } catch (Exception e) { System.out.println("Error checking Certificate Validity. See admin."); return true; } } /** * import guomi node cert list * @throws CertificateEncodingException */ @Test public void testLoadCertList() throws CertificateException, IOException { // need gmnode.crt file InputStream nodes = new ClassPathResource("sdk_node.crt").getInputStream(); org.bouncycastle.jcajce.provider.asymmetric.x509.CertificateFactory factory = new org.bouncycastle.jcajce.provider.asymmetric.x509.CertificateFactory(); List<X509Certificate> certs = (List<X509Certificate>) factory.engineGenerateCertificates(nodes); Assert.notNull(certs,"certs null"); certs.stream().forEach(c -> { System.out.println(c.getSubjectDN()); try { System.out.println(NodeMgrTools.getCertFingerPrint(c.getEncoded())); } catch (CertificateEncodingException e) { e.printStackTrace(); } }); } @Test public void testCRLF() { String headLF = "-----BEGIN PRIVATE KEY-----\n"; String headCRLF = "-----BEGIN PRIVATE KEY-----\r\n"; String hexLF = Numeric.toHexString(headLF.getBytes()); String hexCRLF = Numeric.toHexString(headCRLF.getBytes()); System.out.println("hexLF " + headLF.length()); System.out.println("hexLF " + hexLF); System.out.println("headCRLF " + headCRLF.length()); System.out.println("hexCRLF " + hexCRLF); String crlfContent = "-----BEGIN PRIVATE KEY-----\r\n" + "MIGHAgEAMBMGByqGSM49AgEGCCqBHM9VAYItBG0wawIBAQQgI2r2hDDWouOOm74a\r\n" + "GZoy4lvKg/J+AQCzewaR2JkBPZShRANCAATgeRpxTyvxl4yRIuK5j9iYEY/iibjF\r\n" + "xWdgl87or6vTcovHI5Wqy2Lye6zO68ZQ7iuIt37GaTxVNQ3fRzBM3sOX\r\n" + "-----END PRIVATE KEY-----"; String lfContent = "-----BEGIN PRIVATE KEY-----\n" + "MIGHAgEAMBMGByqGSM49AgEGCCqBHM9VAYItBG0wawIBAQQgI2r2hDDWouOOm74a\n" + "GZoy4lvKg/J+AQCzewaR2JkBPZShRANCAATgeRpxTyvxl4yRIuK5j9iYEY/iibjF\n" + "xWdgl87or6vTcovHI5Wqy2Lye6zO68ZQ7iuIt37GaTxVNQ3fRzBM3sOX\n" + "-----END PRIVATE KEY-----"; String crlfAddress; String lfAddress; try { PEMKeyStore pemKeyStore = new PEMKeyStore(new ByteArrayInputStream(crlfContent.getBytes())); PEMKeyStore pemKeyStore2 = new PEMKeyStore(new ByteArrayInputStream(lfContent.getBytes())); crlfAddress = Numeric.toHexStringNoPrefix(pemKeyStore.getKeyPair().getPublic().getEncoded()); lfAddress = Numeric.toHexStringNoPrefix(pemKeyStore2.getKeyPair().getPublic().getEncoded()); } catch (Exception e) { throw new NodeMgrException(ConstantCode.PEM_CONTENT_ERROR); } System.out.println("crlfAddress " + crlfAddress); System.out.println("lfAddress " + lfAddress); } @Test public void testEmptyPwdP12() { String emptyPwd = ""; String afterBase64 = Base64.getEncoder().encodeToString(emptyPwd.getBytes()); System.out.println("afterBase64: " + afterBase64); String afterDecode = new String(Base64.getDecoder().decode(afterBase64.getBytes())); System.out.println("afterDecode: " + afterDecode); } }
43.933086
172
0.670418
fc99dfd8db28fe5a2723b07d772954486ae60a3f
1,168
package com.gutotech.narutogame.utils; import android.content.Context; import android.content.SharedPreferences; public class SettingsUtils { public static final String BG_MUSIC_KEY = "bgMusicEnabled"; public static final String SOUND_KEY = "soundMusicEnabled"; public static final String NOTIFICATIONS_KEY = "notificationsEnabled"; public static final String HOME_TOUR_KEY = "TOUR_HOME_KEY"; public static final String BATTLE_TOUR_KEY = "BATTLE_GUIDE_KEY"; private static final String PREFERENCE_FILE_KEY = "com.gutotech.narutogame.PREFERENCE_FILE"; public static void set(Context context, String key, boolean newValue) { SharedPreferences sharedPref = context.getSharedPreferences( PREFERENCE_FILE_KEY, Context.MODE_PRIVATE); SharedPreferences.Editor editor = sharedPref.edit(); editor.putBoolean(key, newValue); editor.apply(); } public static boolean get(Context context, String key) { SharedPreferences sharedPref = context.getSharedPreferences( PREFERENCE_FILE_KEY, Context.MODE_PRIVATE); return sharedPref.getBoolean(key, true); } }
36.5
96
0.737158
a5e63d734927f77a254d3cba0e44df216b248fdd
273
package controllers; import be.objectify.deadbolt.java.actions.Group; import be.objectify.deadbolt.java.actions.Restrict; import play.mvc.*; @Restrict(@Group("Admin")) public class Application extends Controller { public Result index() { return ok(); } }
21
51
0.725275
e566766bc7ac21a1d09d4f3b4496a63737cdabd3
2,403
/* * Copyright 2016 Sam Sun <[email protected]> * * 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.samczsun.skype4j.internal.threads; import com.samczsun.skype4j.exceptions.handler.ErrorSource; import com.samczsun.skype4j.internal.SkypeImpl; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicInteger; public class AuthenticationChecker extends Thread { private static final Map<String, AtomicInteger> ID = new ConcurrentHashMap<>(); private SkypeImpl skype; private AtomicBoolean stop = new AtomicBoolean(false); public AuthenticationChecker(SkypeImpl skype) { super(String.format("Skype4J-AuthenticationChecker-%s-%s", skype.getUsername(), ID.computeIfAbsent(skype.getUsername(), str -> new AtomicInteger()).getAndIncrement())); this.skype = skype; } public void run() { while (skype.isLoggedIn() && !stop.get()) { long diff = (skype.getExpirationTime() - System.currentTimeMillis()); if (diff > 1800000) { //30 min if (stop.get()) { return; } try { Thread.sleep(diff / 2); } catch (InterruptedException ignored) { } } else { if (stop.get()) { return; } try { skype.reauthenticate(); } catch (Exception e) { skype.handleError(ErrorSource.REAUTHENTICATING, e, true); //Don't see why you need to return in a finally block. } finally { return; } } } } public void kill() { this.stop.set(true); } }
34.826087
176
0.601748
6caac94b6fb4457d34ec3cdd4ebc898f209cdcda
4,042
package arcs.android; import arcs.api.RuntimeSettings; import com.google.auto.value.AutoValue; import java.io.BufferedReader; import java.io.InputStreamReader; import java.util.Optional; import java.util.function.Function; import java.util.logging.Logger; import javax.inject.Inject; /** For Javascript-based Arcs runtime. */ public final class AndroidRuntimeSettings implements RuntimeSettings { // Equivalent to &log parameter private static final String LOG_LEVEL_PROPERTY = "debug.arcs.runtime.log"; // Equivalent to &explore-proxy parameter private static final String USE_DEV_SERVER_PROXY_PROPERTY = "debug.arcs.runtime.use_alds"; // The target shell to be loaded (on-device) or be connected (on-host) private static final String SHELL_URL_PROPERTY = "debug.arcs.runtime.shell_url"; // Default settings: // Logs the most information, loads the on-device pipes-shell // and not uses ALDS proxy. private static final int DEFAULT_LOG_LEVEL = 2; private static final boolean DEFAULT_USE_DEV_SERVER = false; private static final String DEFAULT_SHELL_URL = "file:///android_asset/index.html?"; private static final Logger logger = Logger.getLogger( AndroidRuntimeSettings.class.getName()); @AutoValue abstract static class Settings { abstract int logLevel(); abstract boolean useDevServerProxy(); abstract String shellUrl(); static Builder builder() { return new AutoValue_AndroidRuntimeSettings_Settings.Builder(); } @AutoValue.Builder abstract static class Builder { abstract Builder setLogLevel(int level); abstract Builder setUseDevServerProxy(boolean useDevServerProxy); abstract Builder setShellUrl(String shellUrl); abstract Settings build(); } } // Immutable configurations for this runtime settings instance. private final Settings settings; @Inject public AndroidRuntimeSettings() { settings = Settings.builder() .setLogLevel( getProperty(LOG_LEVEL_PROPERTY, Integer::valueOf, DEFAULT_LOG_LEVEL)) .setUseDevServerProxy( getProperty(USE_DEV_SERVER_PROXY_PROPERTY, Boolean::valueOf, DEFAULT_USE_DEV_SERVER)) .setShellUrl( getProperty(SHELL_URL_PROPERTY, String::valueOf, DEFAULT_SHELL_URL)) .build(); } @Override public int logLevel() { return settings.logLevel(); } @Override public boolean useDevServerProxy() { return settings.useDevServerProxy(); } @Override public String shellUrl() { return settings.shellUrl(); } /** * This API reads the specified <var>property</var>, converts the content to * the type of <var>T</var> via the <var>converter</var>, then returns the * result. * * If the result cannot be resolved i.e. thrown exception, the <var>defaultValue</var> * is returned instead. * * @param property Android property name to read. * @param converter Converts the type of property content from String to T. * @param defaultValue The returned data when either the property does not exist * or it's in ill format. * @param <T> The expected type of returned data. * @return the resolved content of property in type T. */ private <T> T getProperty(String property, Function<String, T> converter, T defaultValue) { try { // Property-read is granted at the public domain of selinux policies. Process process = Runtime.getRuntime().exec("getprop " + property); BufferedReader input = new BufferedReader(new InputStreamReader(process.getInputStream())); Optional<String> propertyValue = Optional.ofNullable(input.readLine()); input.close(); // The specified property does not exist. if (propertyValue.isPresent() && propertyValue.get().isEmpty()) { propertyValue = Optional.ofNullable(null); } return propertyValue.map(converter).orElse(defaultValue); } catch (Exception e) { logger.warning("illegal value of " + property); } return defaultValue; } }
35.769912
97
0.715982
f88c37349e43ca5fcfd184868929e4d09d7fffc1
7,583
package imoucheg.ihm; import imoucheg.app.App; import imoucheg.services.Services; import java.awt.BorderLayout; import java.awt.EventQueue; import java.awt.Font; import java.awt.SystemColor; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; import java.io.File; import java.io.FileReader; import java.io.IOException; import java.util.Locale; import java.util.Properties; import java.util.ResourceBundle; import javax.swing.ImageIcon; import javax.swing.JButton; import javax.swing.JFileChooser; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.SwingConstants; /** * Main Window * * @author ImoucheG * */ public class MainWindow { // Attributs private JFrame frmPimpmystorage; File fileChoose; File directoryDest; /** * Launch the application. */ public static void main(String[] args) { EventQueue.invokeLater(new Runnable() { public void run() { try { MainWindow window = new MainWindow(); window.frmPimpmystorage.setVisible(true); } catch (Exception e) { e.printStackTrace(); } } }); } /** * Create the application. */ public MainWindow() { initialize(); } /** * Initialize the contents of the frame. */ private void initialize() { try { // Default JFileChooser.setDefaultLocale(Locale.US); String textLbGenerateForClickBis = "Click here for launch the generation"; String textLbGenerateInit = "Please, choose your file and the directory path and click on"; String textLbGenerateFinishBis = "Good job ! Your files are generated in your directory."; String textBtnGenerateInit = "Generate"; ImageIcon imgIcon = new ImageIcon( "./src/main/resources/images/icon_pms.png"); String patthConfig = "./src/main/resources/properties/config.properties"; // Try to use properties try { try { FileReader reader = new FileReader(patthConfig); Properties resConfig = new Properties(); resConfig.load(reader); reader = new FileReader( resConfig.getProperty("pathImagesProperties")); Properties resImages = new Properties(); resImages.load(reader); reader = new FileReader( resConfig.getProperty("pathTextProperties")); Properties resText = new Properties(); resText.load(reader); switch (resConfig.getProperty("lang")) { case "US": JFileChooser.setDefaultLocale(new Locale("en", "US")); break; } textLbGenerateForClickBis = resText .getProperty("lbGenerateForClick"); textLbGenerateInit = resText.getProperty("lbGenerateInit"); textLbGenerateFinishBis = resText .getProperty("lbGenerateFinish"); textBtnGenerateInit = resText .getProperty("btnGenerateInit"); imgIcon = new ImageIcon(resImages.getProperty("pathImages") + resImages.getProperty("icon")); } catch (IOException e) { e.printStackTrace(); } } catch (Exception error) { error.printStackTrace(); } final String textLbGenerateForClick = textLbGenerateForClickBis; final String textLbGenerateFinish = textLbGenerateFinishBis; frmPimpmystorage = new JFrame(); frmPimpmystorage.setFont(new Font("Verdana", Font.PLAIN, 12)); frmPimpmystorage.setTitle("PimpMyStorage"); frmPimpmystorage.setBounds(100, 100, 500, 400); frmPimpmystorage.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frmPimpmystorage.setResizable(false); frmPimpmystorage.setIconImage(imgIcon.getImage()); JPanel panel = new JPanel(); panel.setBackground(SystemColor.window); frmPimpmystorage.getContentPane().add(panel, BorderLayout.CENTER); panel.setLayout(null); JButton btnGenerate = new JButton(textBtnGenerateInit); btnGenerate.setEnabled(false); final JLabel lblFile = new JLabel(""); lblFile.setBounds(361, 145, 113, 14); panel.add(lblFile); final JLabel lblDirectory = new JLabel(""); lblDirectory.setBounds(361, 235, 113, 14); panel.add(lblDirectory); JLabel lbGenerate = new JLabel(textLbGenerateInit); lbGenerate.setFont(new Font("Verdana", Font.PLAIN, 11)); lbGenerate.setBounds(40, 331, 340, 14); lbGenerate.setHorizontalAlignment(SwingConstants.RIGHT); panel.add(lbGenerate); JLabel lblChooseYourImage = new JLabel("Choose your image file :"); lblChooseYourImage.setFont(new Font("Verdana", Font.PLAIN, 11)); lblChooseYourImage.setBounds(10, 144, 149, 14); panel.add(lblChooseYourImage); JLabel lbTopWelcome = new JLabel("Welcome to"); lbTopWelcome.setFont(new Font("Verdana", Font.BOLD, 11)); lbTopWelcome.setBounds(10, 11, 86, 14); panel.add(lbTopWelcome); JLabel lblPimpmystorage = new JLabel("PimpMyStorage"); lblPimpmystorage.setForeground(SystemColor.textHighlight); lblPimpmystorage.setFont(new Font("Verdana", Font.BOLD, 11)); lblPimpmystorage.setBounds(92, 11, 114, 14); panel.add(lblPimpmystorage); JButton btnBrowse = new JButton("Browse"); btnBrowse.setBackground(SystemColor.control); // Listener btnBrowse.addMouseListener(new MouseAdapter() { @Override public void mouseClicked(MouseEvent arg0) { JFileChooser chooser = new JFileChooser(); ImagePreviewPanel preview = new ImagePreviewPanel(); chooser.setAccessory(preview); chooser.addPropertyChangeListener(preview); // Listener chooser.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent arg0) { fileChoose = chooser.getSelectedFile(); } }); chooser.showOpenDialog(panel); if (fileChoose != null) { lblFile.setText(fileChoose.getName()); if (directoryDest != null) { btnGenerate.setEnabled(true); Services.setTextLb(lbGenerate, textLbGenerateForClick); } } } }); btnBrowse.setBounds(240, 141, 89, 23); panel.add(btnBrowse); JLabel lblChooseYourPath = new JLabel( "Choose your directory path :"); lblChooseYourPath.setFont(new Font("Verdana", Font.PLAIN, 11)); lblChooseYourPath.setBounds(10, 234, 196, 14); panel.add(lblChooseYourPath); JButton button = new JButton("Browse"); button.setBackground(SystemColor.control); // Listener button.addMouseListener(new MouseAdapter() { @Override public void mouseClicked(MouseEvent e) { ChooseFile cf = new ChooseFile(true); directoryDest = cf.getFile(); if (directoryDest != null) { lblDirectory.setText(directoryDest.getName()); if (fileChoose != null) { btnGenerate.setEnabled(true); Services.setTextLb(lbGenerate, textLbGenerateForClick); } } } }); button.setBounds(240, 231, 89, 23); panel.add(button); btnGenerate.setBackground(SystemColor.activeCaption); // Listener btnGenerate.addMouseListener(new MouseAdapter() { @Override public void mouseClicked(MouseEvent e) { if (fileChoose != null && directoryDest != null) { App app = new App(); app.createFiles(fileChoose.getPath(), directoryDest.getPath()); Services.setTextLb(lbGenerate, textLbGenerateFinish); } } }); btnGenerate.setBounds(385, 327, 89, 23); panel.add(btnGenerate); } catch (Exception error) { error.printStackTrace(); } } }
31.205761
95
0.680469
a47f955489702836cdca25e7de0e3ee734b0c480
8,749
package cgeo.geocaching.network; import cgeo.geocaching.R; import cgeo.geocaching.StoredList; import cgeo.geocaching.cgeoapplication; import cgeo.geocaching.compatibility.Compatibility; import cgeo.geocaching.connector.ConnectorFactory; import cgeo.geocaching.files.LocalStorage; import cgeo.geocaching.utils.IOUtils; import cgeo.geocaching.utils.ImageHelper; import cgeo.geocaching.utils.Log; import ch.boye.httpclientandroidlib.HttpResponse; import org.apache.commons.lang3.StringUtils; import android.content.res.Resources; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.graphics.Point; import android.graphics.drawable.BitmapDrawable; import android.net.Uri; import android.text.Html; import java.io.BufferedInputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.util.Date; public class HtmlImage implements Html.ImageGetter { private static final String[] BLOCKED = new String[] { "gccounter.de", "gccounter.com", "cachercounter/?", "gccounter/imgcount.php", "flagcounter.com", "compteur-blog.net", "counter.digits.com", "andyhoppe", "besucherzaehler-homepage.de", "hitwebcounter.com", "kostenloser-counter.eu", "trendcounter.com", "hit-counter-download.com, gcwetterau.de/counter/newcounter.png" }; public static final String SHARED = "shared"; final private String geocode; /** * on error: return large error image, if <code>true</code>, otherwise empty 1x1 image */ final private boolean returnErrorImage; final private int listId; final private boolean onlySave; final private BitmapFactory.Options bfOptions; final private int maxWidth; final private int maxHeight; final private Resources resources; public HtmlImage(final String geocode, final boolean returnErrorImage, final int listId, final boolean onlySave) { this.geocode = geocode; this.returnErrorImage = returnErrorImage; this.listId = listId; this.onlySave = onlySave; bfOptions = new BitmapFactory.Options(); bfOptions.inTempStorage = new byte[16 * 1024]; bfOptions.inPreferredConfig = Bitmap.Config.RGB_565; Point displaySize = Compatibility.getDisplaySize(); this.maxWidth = displaySize.x - 25; this.maxHeight = displaySize.y - 25; this.resources = cgeoapplication.getInstance().getResources(); } @Override public BitmapDrawable getDrawable(final String url) { // Reject empty and counter images URL if (StringUtils.isBlank(url) || isCounter(url)) { return new BitmapDrawable(resources, getTransparent1x1Image()); } final boolean shared = url.contains("/images/icons/icon_"); final String pseudoGeocode = shared ? SHARED : geocode; Bitmap imagePre = loadImageFromStorage(url, pseudoGeocode, shared); // Download image and save it to the cache if (imagePre == null) { final String absoluteURL = makeAbsoluteURL(url); if (absoluteURL != null) { try { final File file = LocalStorage.getStorageFile(pseudoGeocode, url, true, true); final HttpResponse httpResponse = Network.getRequest(absoluteURL, null, file); if (httpResponse != null) { final int statusCode = httpResponse.getStatusLine().getStatusCode(); if (statusCode == 200) { LocalStorage.saveEntityToFile(httpResponse, file); } else if (statusCode == 304) { if (!file.setLastModified(System.currentTimeMillis())) { makeFreshCopy(file); } } } } catch (Exception e) { Log.e("HtmlImage.getDrawable (downloading from web)", e); } } } if (onlySave) { return null; } // now load the newly downloaded image if (imagePre == null) { imagePre = loadImageFromStorage(url, pseudoGeocode, shared); } // get image and return if (imagePre == null) { Log.d("HtmlImage.getDrawable: Failed to obtain image"); if (returnErrorImage) { imagePre = BitmapFactory.decodeResource(resources, R.drawable.image_not_loaded); } else { imagePre = getTransparent1x1Image(); } } return imagePre != null ? ImageHelper.scaleBitmapToFitDisplay(imagePre) : null; } /** * Make a fresh copy of the file to reset its timestamp. On some storage, it is impossible * to modify the modified time after the fact, in which case a brand new file must be * created if we want to be able to use the time as validity hint. * * See Android issue 1699. * * @param file the file to refresh */ private static void makeFreshCopy(final File file) { final File tempFile = new File(file.getParentFile(), file.getName() + "-temp"); file.renameTo(tempFile); LocalStorage.copy(tempFile, file); tempFile.delete(); } private Bitmap getTransparent1x1Image() { return BitmapFactory.decodeResource(resources, R.drawable.image_no_placement); } private Bitmap loadImageFromStorage(final String url, final String pseudoGeocode, final boolean forceKeep) { try { final File file = LocalStorage.getStorageFile(pseudoGeocode, url, true, false); final Bitmap image = loadCachedImage(file, forceKeep); if (image != null) { return image; } final File fileSec = LocalStorage.getStorageSecFile(pseudoGeocode, url, true); return loadCachedImage(fileSec, forceKeep); } catch (Exception e) { Log.w("HtmlImage.getDrawable (reading cache)", e); } return null; } private String makeAbsoluteURL(final String url) { // Check if uri is absolute or not, if not attach the connector hostname // FIXME: that should also include the scheme if (Uri.parse(url).isAbsolute()) { return url; } final String host = ConnectorFactory.getConnector(geocode).getHost(); if (StringUtils.isNotEmpty(host)) { final StringBuilder builder = new StringBuilder("http://"); builder.append(host); if (!StringUtils.startsWith(url, "/")) { // FIXME: explain why the result URL would be valid if the path does not start with // a '/', or signal an error. builder.append('/'); } builder.append(url); return builder.toString(); } return null; } private Bitmap loadCachedImage(final File file, final boolean forceKeep) { if (file.exists()) { if (listId >= StoredList.STANDARD_LIST_ID || file.lastModified() > (new Date().getTime() - (24 * 60 * 60 * 1000)) || forceKeep) { setSampleSize(file); final Bitmap image = BitmapFactory.decodeFile(file.getPath(), bfOptions); if (image == null) { Log.e("Cannot decode bitmap from " + file.getPath()); } return image; } } return null; } private void setSampleSize(final File file) { //Decode image size only BitmapFactory.Options options = new BitmapFactory.Options(); options.inJustDecodeBounds = true; BufferedInputStream stream = null; try { stream = new BufferedInputStream(new FileInputStream(file)); BitmapFactory.decodeStream(stream, null, options); } catch (FileNotFoundException e) { Log.e("HtmlImage.setSampleSize", e); } finally { IOUtils.closeQuietly(stream); } int scale = 1; if (options.outHeight > maxHeight || options.outWidth > maxWidth) { scale = Math.max(options.outHeight / maxHeight, options.outWidth / maxWidth); } bfOptions.inSampleSize = scale; } private static boolean isCounter(final String url) { for (String entry : BLOCKED) { if (StringUtils.containsIgnoreCase(url, entry)) { return true; } } return false; } }
36.302905
141
0.606698
0d5f4cf0dc4fb4479b4b0139cf47dea3c36c6788
343
package com.kgc.oop.designpatterns.Factory_mode.abstract_factory; /** * @author:杨涛 * 黑色动物生产工厂 * 生产黑色的猫、狗 */ public class BlackAnimalFactory implements IAanimalFactory{ @Override public ICat createCat() { return new BlackCat(); } @Override public IDog createDog() { return new BlackDog(); } }
18.052632
65
0.650146
f01101f25fb96832077faccd5f6457c91abb7d08
5,409
/* * The MIT License * * Copyright 2016 Universidad de los Andes - Departamento de Ingeniería de Sistemas. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package co.edu.uniandes.isis2503.zk.competitor.services; import co.edu.uniandes.isis2503.zk.competitor.models.CompetitorLogic; import co.edu.uniandes.isis2503.zk.competitor.models.dtos.CompetitorDTO; import java.util.List; import javax.ws.rs.DELETE; import javax.ws.rs.GET; import javax.ws.rs.POST; import javax.ws.rs.PUT; import javax.ws.rs.Path; import javax.ws.rs.PathParam; import javax.ws.rs.Produces; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; /** * * @author Luis Felipe Mendivelso Osorio <[email protected]> */ @Path("/competitors") @Produces(MediaType.APPLICATION_JSON) public class CompetitorServices { private final CompetitorLogic logic; public CompetitorServices() { this.logic = new CompetitorLogic(); } @POST @Produces(MediaType.APPLICATION_JSON) public Response createCompetitor(CompetitorDTO competitor) { try { competitor = logic.createCompetitor(competitor); return Response.status(200).header("Access-Control-Allow-Origin", "*").entity(competitor).build(); } catch (Exception e) { e.printStackTrace(); return Response.status(500).header("Access-Control-Allow-Origin", "*").entity("We found errors in your query, please contact the Web Admin.").build(); } } @PUT @Produces(MediaType.APPLICATION_JSON) public Response updateCompetitor(CompetitorDTO competitor) { try { competitor = logic.updateCompetitor(competitor); return Response.status(200).header("Access-Control-Allow-Origin", "*").entity(competitor).build(); } catch (Exception e) { e.printStackTrace(); return Response.status(500).header("Access-Control-Allow-Origin", "*").entity("We found errors in your query, please contact the Web Admin.").build(); } } @DELETE @Produces(MediaType.APPLICATION_JSON) public Response deleteCompetitor(CompetitorDTO competitor) { try { logic.deleteCompetitor(competitor); return Response.status(200).header("Access-Control-Allow-Origin", "*").entity("Sucessful: Competitor was deleted").build(); } catch (Exception e) { e.printStackTrace(); return Response.status(500).header("Access-Control-Allow-Origin", "*").entity("We found errors in your query, please contact the Web Admin.").build(); } } @GET @Path("/id={id}") @Produces(MediaType.APPLICATION_JSON) public Response getCompetitorById(@PathParam("id") Long id) { CompetitorDTO competitor = logic.getCompetitorById(id); if (competitor == null) { return Response.status(500).header("Access-Control-Allow-Origin", "*").entity("We found errors in your query, please contact the Web Admin.").build(); } else { return Response.status(200).header("Access-Control-Allow-Origin", "*").entity(competitor).build(); } } @GET @Path("/name={name}") @Produces(MediaType.APPLICATION_JSON) public Response getCompetitorByName(@PathParam("name") String name) { CompetitorDTO competitor = logic.getCompetitorByName(name); if (competitor == null) { return Response.status(500).header("Access-Control-Allow-Origin", "*").entity("We found errors in your query, please contact the Web Admin.").build(); } else { return Response.status(200).header("Access-Control-Allow-Origin", "*").entity(competitor).build(); } } @GET @Produces(MediaType.APPLICATION_JSON) public Response getCompetitors() { List<CompetitorDTO> competitors = logic.getCompetitors(); if (competitors == null) { return Response.status(500).header("Access-Control-Allow-Origin", "*").entity("We found errors in your query, please contact the Web Admin.").build(); } else if (competitors.isEmpty()) { return Response.status(200).header("Access-Control-Allow-Origin", "*").entity("No competitor Records.").build(); } else { return Response.status(200).header("Access-Control-Allow-Origin", "*").entity(competitors).build(); } } }
42.590551
162
0.685154
31238d7b40665d286b1e13ac214e52abef3fa7dc
2,284
package com.github.zhenwei.network.bio; import java.net.ServerSocket; import java.net.Socket; import java.nio.charset.StandardCharsets; import java.util.concurrent.LinkedBlockingQueue; import java.util.concurrent.ThreadPoolExecutor; import java.util.concurrent.TimeUnit; public class BioServer implements Runnable { /** * 服务端口号 */ int port = 0; /** * 工作线程 */ static final ThreadPoolExecutor workerThreadPool = new ThreadPoolExecutor(1, Math.max(1, Runtime.getRuntime().availableProcessors() >> 1), 10, TimeUnit.SECONDS, new LinkedBlockingQueue<>(200), new ThreadPoolExecutor.CallerRunsPolicy()); /** * 服务端线程池 */ static final ThreadPoolExecutor bossThreadPool = new ThreadPoolExecutor(1, 1, 1, TimeUnit.SECONDS, new LinkedBlockingQueue<>(1)); static final BioServer SERVER = new BioServer(); public static void server(int port) { bossThreadPool.execute(SERVER.setPort(port)); while (!bossThreadPool.isShutdown()) { } } @Override public void run() { try { //启动服务 ServerSocket serverSocket = new ServerSocket(port); System.out.println("服务端启动, port:" + port); for (; ; ) { //接收链接 Socket socket = serverSocket.accept(); //异步处理 BioServerHandler bioServerHandler = new BioServerHandler(); bioServerHandler.setSocket(socket); workerThreadPool.execute(bioServerHandler); } } catch (Exception e) { System.out.printf("create bio server port %s error", port); e.printStackTrace(); System.exit(0); } } /** * 设置端口号 * * @param port * @return */ public BioServer setPort(int port) { if (this.port == 0) { this.port = port; } return this; } static class BioServerHandler extends BaseBio implements Runnable { @Override public void run() { try { byte[] data = readMessage(); System.out.println("bio server 接收到消息为:" + new String(data, StandardCharsets.UTF_8)); sendMessage("i had received your message".getBytes(StandardCharsets.UTF_8)); System.out.println("bio server 已应答"); } catch (Exception e) { System.out.println("bio server receive message err"); e.printStackTrace(); } } } }
25.098901
92
0.648862
20c0f8f2a055430f5896f9844938c51ff5f75074
2,617
package parameterize; import java.util.ArrayList; import java.util.Arrays; import java.util.List; /** * Created by Edgar on 2016/4/6. * * @author Edgar Date 2016/4/6 */ public class FilteringApples { public static void main(String[] args) { List<Apple> inventory = Arrays .asList(new Apple(80, "green"), new Apple(155, "green"), new Apple(120, "red")); // [Apple{color='green', weight=80}, Apple{color='green', weight=155}] List<Apple> greenApples = filterApplesByColor(inventory, "green"); System.out.println(greenApples); // [Apple{color='red', weight=120}] List<Apple> redApples = filterApplesByColor(inventory, "red"); System.out.println(redApples); // [Apple{color='green', weight=80}, Apple{color='green', weight=155}] List<Apple> greenApples2 = filter(inventory, new AppleColorPredicate()); System.out.println(greenApples2); // [Apple{color='green', weight=155}] List<Apple> heavyApples = filter(inventory, new AppleWeightPredicate()); System.out.println(heavyApples); // [] List<Apple> redAndHeavyApples = filter(inventory, new AppleRedAndHeavyPredicate()); System.out.println(redAndHeavyApples); // [Apple{color='red', weight=120}] List<Apple> redApples2 = filter(inventory, new ApplePredicate() { public boolean test(Apple a){ return a.getColor().equals("red"); } }); System.out.println(redApples2); //using a lambda expression System.out.println(filter(inventory, apple -> apple.getColor().equals("red"))); } public static List<Apple> filter(List<Apple> inventory, ApplePredicate p){ List<Apple> result = new ArrayList<>(); for(Apple apple : inventory){ if(p.test(apple)){ result.add(apple); } } return result; } public static List<Apple> filterGreenApples(List<Apple> inventory) { List<Apple> result = new ArrayList<>(); for (Apple apple : inventory) { if ("green".equals(apple.getColor())) { result.add(apple); } } return result; } public static List<Apple> filterApplesByColor(List<Apple> inventory, String color) { List<Apple> result = new ArrayList<>(); for (Apple apple : inventory) { if (apple.getColor().equals(color)) { result.add(apple); } } return result; } public static List<Apple> filterApplesByWeight(List<Apple> inventory, int weight) { List<Apple> result = new ArrayList<>(); for (Apple apple : inventory) { if (apple.getWeight() > weight) { result.add(apple); } } return result; } }
28.445652
92
0.644249