code
stringlengths
5
1.04M
repo_name
stringlengths
7
108
path
stringlengths
6
299
language
stringclasses
1 value
license
stringclasses
15 values
size
int64
5
1.04M
package org.jsmart.zerocode.integrationtests.customassert; import org.jsmart.zerocode.core.engine.executor.javaapi.CustomAsserter; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.Map; /** * implement CustomAsserter interface method asserted(...) * or * implement your own flavoured method and pass it as below to the DSL: * e.g. * 1) * DSL: "key": "$CUSTOM.ASSERT:org.pkg...MyCustomComparator#myMethod:{\"expectDate\":\"2020-09-20\"}", * Java: public Boolean dateBetween(Map<String, Object> inputParamMap, Object actualDate) {...} * <p> * 2) * DSL: "actualDate": "$CUSTOM.ASSERT:org.pkg...MyCustomComparator#dateBetween:{\"fromDate\":\"2020-09-20\", \"toDate\":\"2021-09-20\"}", * Java: public Boolean dateBetween(Map<String, Object> inputParamMap, Object actualDate) {...} */ public class MyCustomComparator implements CustomAsserter { private static final Logger LOGGER = LoggerFactory.getLogger(MyCustomComparator.class); // --------------------------- // "public static" also good // --------------------------- public Boolean asserted(Map<String, Object> inputParamMap, Object actualFieldValue) { int expectLen = Integer.parseInt(inputParamMap.get("expectLen").toString()); return expectLen == actualFieldValue.toString().length(); } public Boolean assertLength(Map<String, Object> inputParamMap, Object actualFieldValue) { int expectLen = Integer.parseInt(inputParamMap.get("expectLen").toString()); int actualLength = actualFieldValue.toString().length(); boolean success = (expectLen == actualLength); if (!success) { LOGGER.error("\n" + "\t|\n" + "\t|\n" + "\t+---assertion error --> Actual length of {}}={} did not match expected length of {} \n" + "\t|\n" + "\t|\n", actualFieldValue, actualLength, expectLen); } return success; } public static Integer strLen(String input) { return 6; } public static Integer strLen(String input1, String inut2) { return 7; } }
authorjapps/zerocode
core/src/test/java/org/jsmart/zerocode/integrationtests/customassert/MyCustomComparator.java
Java
apache-2.0
2,219
/* * JBoss, Home of Professional Open Source * Copyright 2010, Red Hat, Inc., and individual contributors * by the @authors tag. See the copyright.txt in the distribution for a * full listing of individual contributors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.jboss.weld.tests.unit.deployment.structure.duplicit; import jakarta.enterprise.inject.Produces; public class Foo { @Produces public String get() { return "Foo!"; } }
weld/core
tests/src/test/java/org/jboss/weld/tests/unit/deployment/structure/duplicit/Foo.java
Java
apache-2.0
978
package org.schoellerfamily.gedbrowser.api.crud.test; import static org.assertj.core.api.BDDAssertions.then; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; import java.util.ArrayList; import java.util.List; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.schoellerfamily.gedbrowser.api.Application; import org.schoellerfamily.gedbrowser.api.controller.exception.DataSetNotFoundException; import org.schoellerfamily.gedbrowser.api.controller.exception.ObjectNotFoundException; import org.schoellerfamily.gedbrowser.api.crud.FamilyCrud; import org.schoellerfamily.gedbrowser.api.crud.PersonCrud; import org.schoellerfamily.gedbrowser.api.crud.SubmissionCrud; import org.schoellerfamily.gedbrowser.api.datamodel.ApiAttribute; import org.schoellerfamily.gedbrowser.api.datamodel.ApiSubmission; import org.schoellerfamily.gedbrowser.persistence.mongo.gedconvert.GedObjectToGedDocumentMongoConverter; import org.schoellerfamily.gedbrowser.persistence.mongo.loader.GedDocumentFileLoader; import org.schoellerfamily.gedbrowser.persistence.mongo.repository.RepositoryManagerMongo; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.test.context.TestPropertySource; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; /** * @author Dick Schoeller */ @RunWith(SpringJUnit4ClassRunner.class) @SpringBootTest(classes = Application.class, webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT) @TestPropertySource(properties = { "management.port=0" }) @SuppressWarnings("PMD.JUnitTestsShouldIncludeAssert") public class SubmissionCrudTest { /** Logger. */ private final transient Log logger = LogFactory.getLog(getClass()); /** */ @Autowired private transient GedDocumentFileLoader loader; /** */ @Autowired private transient GedObjectToGedDocumentMongoConverter toDocConverter; /** */ @Autowired private transient RepositoryManagerMongo repositoryManager; /** */ private SubmissionCrud crud; /** */ private CrudTestHelper helper; /** */ @Before public void setUp() { helper = new CrudTestHelper( new PersonCrud(loader, toDocConverter, repositoryManager), new FamilyCrud(loader, toDocConverter, repositoryManager)); crud = new SubmissionCrud(loader, toDocConverter, repositoryManager); } /** */ @Test public final void testGetSubmissionsGl120368() { logger.info("Beginning testGetSubmissionsGl120368"); final List<ApiSubmission> list = crud.readAll(helper.getDb()); final ApiSubmission firstSubmission = list.get(0); then(firstSubmission.getString()).isEqualTo("B1"); final ApiAttribute firstAttribute = firstSubmission.getAttributes() .get(0); then(firstAttribute.getType()).isEqualTo("attribute"); then(firstAttribute.getString()) .isEqualTo("Generations of descendants"); then(firstAttribute.getTail()).isEqualTo("2"); } /** */ @Test public final void testGetSubmissionsMiniSchoeller() { logger.info("Beginning testGetSubmissionsMiniSchoeller"); final List<ApiSubmission> list = crud.readAll("mini-schoeller"); assertTrue("should be no submissions", list.isEmpty()); } /** */ @Test public final void testGetSubmissionsGl120368B1() { logger.info("Beginning testGetSubmissionsGl120368B1"); final ApiSubmission submission = crud.readOne(helper.getDb(), "B1"); final ApiAttribute firstAttribute = submission.getAttributes().get(0); then(firstAttribute.getType()).isEqualTo("attribute"); then(firstAttribute.getString()) .isEqualTo("Generations of descendants"); then(firstAttribute.getTail()).isEqualTo("2"); } /** */ @Test public final void testGetSubmissionsGl120368Xyzzy() { logger.info("Beginning testGetSubmissionsGl120368Xyzzy"); try { final ApiSubmission submission = crud.readOne(helper.getDb(), "Xyzzy"); fail("The submission should not be found: " + submission.getString()); } catch (ObjectNotFoundException e) { assertEquals("Mismatched message", "Object Xyzzy of type submission not found", e.getMessage()); } } /** */ @Test public final void testCreateSubmissionsSimple() { logger.info("Beginning testCreateSubmissionsSimple"); final ApiSubmission inSubmission = new ApiSubmission("submission", ""); final ApiSubmission outSubmission = crud .createOne(helper.getDb(), inSubmission); then(outSubmission.getType()).isEqualTo(inSubmission.getType()); } /** */ @Test public final void testDeleteSubmission() { logger.info("Beginning testDeleteSubmission"); final ApiSubmission inSubmission = new ApiSubmission("submission", ""); final ApiSubmission outSubmission = crud .createOne(helper.getDb(), inSubmission); final String id = outSubmission.getString(); final ApiSubmission deletedSubmission = crud .deleteOne(helper.getDb(), id); then(deletedSubmission.getString()).isEqualTo(id); } /** */ @Test public final void testDeleteSubmissionNotFound() { logger.info("Beginning testDeleteSubmissionNotFound"); try { final ApiSubmission submission = crud .deleteOne(helper.getDb(), "XXXXXXX"); fail("The submission should not be found: " + submission.getString()); } catch (ObjectNotFoundException e) { assertEquals("Mismatched message", "Object XXXXXXX of type submission not found", e.getMessage()); } } /** */ @Test public final void testDeleteSubmissionDatabaseNotFound() { logger.info("Beginning testDeleteSubmissionDatabaseNotFound"); try { crud.deleteOne("XYZZY", "SUBM1"); fail("The dataset should not be found: XYZZY, when getting SUBM1"); } catch (DataSetNotFoundException e) { assertEquals("Mismatched message", "Data set XYZZY not found", e.getMessage()); } } /** */ @Test public final void testUpdateSubmissionWithNote() { logger.info("Beginning testUpdateSubmissionWithNote"); final List<ApiAttribute> attributes = new ArrayList<>(); attributes.add(new ApiAttribute("attribute", "Note", "first note")); final ApiSubmission inSubmission = new ApiSubmission("submission", "", attributes); final ApiSubmission outSubmission = crud .createOne(helper.getDb(), inSubmission); then(outSubmission.getType()).isEqualTo(inSubmission.getType()); final ApiAttribute aNote = new ApiAttribute("attribute", "Note", "this is a note"); outSubmission.getAttributes().add(aNote); final ApiSubmission updatedSubmission = crud.updateOne(helper.getDb(), outSubmission.getString(), outSubmission); assertEquals("attribute should be present", aNote, updatedSubmission.getAttributes().get(1)); } }
dickschoeller/gedbrowser
gedbrowserng/src/test/java/org/schoellerfamily/gedbrowser/api/crud/test/SubmissionCrudTest.java
Java
apache-2.0
7,674
/* * Copyright 2018 Red Hat, Inc. and/or its affiliates. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.kie.workbench.common.stunner.cm.backend; import java.io.IOException; import java.io.InputStream; import java.util.ArrayList; import java.util.Collections; import java.util.LinkedList; import java.util.List; import java.util.stream.Collectors; import java.util.stream.DoubleStream; import java.util.stream.IntStream; import java.util.stream.Stream; import java.util.stream.StreamSupport; import javax.enterprise.context.Dependent; import javax.inject.Inject; import org.kie.workbench.common.stunner.bpmn.backend.BaseDirectDiagramMarshaller; import org.kie.workbench.common.stunner.bpmn.backend.converters.TypedFactoryManager; import org.kie.workbench.common.stunner.bpmn.backend.converters.fromstunner.DefinitionsBuildingContext; import org.kie.workbench.common.stunner.bpmn.backend.converters.fromstunner.properties.PropertyWriterFactory; import org.kie.workbench.common.stunner.bpmn.backend.converters.tostunner.DefinitionResolver; import org.kie.workbench.common.stunner.bpmn.backend.workitem.service.WorkItemDefinitionBackendService; import org.kie.workbench.common.stunner.bpmn.definition.EndNoneEvent; import org.kie.workbench.common.stunner.bpmn.definition.SequenceFlow; import org.kie.workbench.common.stunner.bpmn.definition.StartNoneEvent; import org.kie.workbench.common.stunner.cm.CaseManagementDefinitionSet; import org.kie.workbench.common.stunner.cm.backend.converters.fromstunner.properties.CaseManagementPropertyWriterFactory; import org.kie.workbench.common.stunner.cm.definition.AdHocSubprocess; import org.kie.workbench.common.stunner.cm.definition.CaseManagementDiagram; import org.kie.workbench.common.stunner.cm.qualifiers.CaseManagementEditor; import org.kie.workbench.common.stunner.core.api.DefinitionManager; import org.kie.workbench.common.stunner.core.api.FactoryManager; import org.kie.workbench.common.stunner.core.backend.service.XMLEncoderDiagramMetadataMarshaller; import org.kie.workbench.common.stunner.core.diagram.Diagram; import org.kie.workbench.common.stunner.core.diagram.Metadata; import org.kie.workbench.common.stunner.core.graph.Edge; import org.kie.workbench.common.stunner.core.graph.Graph; import org.kie.workbench.common.stunner.core.graph.Node; import org.kie.workbench.common.stunner.core.graph.command.GraphCommandManager; import org.kie.workbench.common.stunner.core.graph.command.impl.GraphCommandFactory; import org.kie.workbench.common.stunner.core.graph.content.Bounds; import org.kie.workbench.common.stunner.core.graph.content.definition.DefinitionSet; import org.kie.workbench.common.stunner.core.graph.content.relationship.Child; import org.kie.workbench.common.stunner.core.graph.content.view.MagnetConnection; import org.kie.workbench.common.stunner.core.graph.content.view.View; import org.kie.workbench.common.stunner.core.graph.content.view.ViewConnector; import org.kie.workbench.common.stunner.core.graph.impl.EdgeImpl; import org.kie.workbench.common.stunner.core.rule.RuleManager; import org.kie.workbench.common.stunner.core.util.UUID; @Dependent @CaseManagementEditor public class CaseManagementDirectDiagramMarshaller extends BaseDirectDiagramMarshaller { private static final double GAP = 50.0; private static final double STAGE_GAP = 25.0; private static final double ORIGIN_X = 50.0; private static final double ORIGIN_Y = 50.0; private static final double EVENT_WIDTH = 55.0; private static final double EVENT_HEIGHT = 55.0; @Inject public CaseManagementDirectDiagramMarshaller(final XMLEncoderDiagramMetadataMarshaller diagramMetadataMarshaller, final DefinitionManager definitionManager, final RuleManager ruleManager, final WorkItemDefinitionBackendService workItemDefinitionService, final FactoryManager factoryManager, final GraphCommandFactory commandFactory, final GraphCommandManager commandManager) { super(diagramMetadataMarshaller, definitionManager, ruleManager, workItemDefinitionService, factoryManager, commandFactory, commandManager); } @Override @SuppressWarnings("unchecked") public String marshall(Diagram<Graph, Metadata> diagram) throws IOException { preMarshallProcess(diagram); return super.marshall(diagram); } @SuppressWarnings("unchecked") private void preMarshallProcess(final Diagram<Graph, Metadata> diagram) { Iterable<Node<View<?>, Edge>> nodes = diagram.getGraph().nodes(); StreamSupport.stream(nodes.spliterator(), false) .filter(node -> CaseManagementDiagram.class.isInstance(node.getContent().getDefinition())) .findAny().ifPresent(root -> { final Node<View, Edge<View, Node<View, Edge<View, Node<View, Edge>>>>> rootNode = (Node) root; // adjust the position of the elements final double stageWidth = adjustNodeBounds(rootNode); // create start event and end event final Node startNoneEvent = typedFactoryManager.newNode(UUID.uuid(), StartNoneEvent.class); ((View) startNoneEvent.getContent()).setBounds( Bounds.create(ORIGIN_X, ORIGIN_Y, ORIGIN_X + EVENT_WIDTH, ORIGIN_Y + EVENT_HEIGHT)); diagram.getGraph().addNode(startNoneEvent); createChild(UUID.uuid(), rootNode, startNoneEvent, 0); final double endNodeEventX = (ORIGIN_X + EVENT_WIDTH) + GAP + stageWidth; final Node endNoneEvent = typedFactoryManager.newNode(UUID.uuid(), EndNoneEvent.class); ((View) endNoneEvent.getContent()).setBounds( Bounds.create(endNodeEventX, ORIGIN_Y, endNodeEventX + EVENT_WIDTH, ORIGIN_Y + EVENT_HEIGHT)); diagram.getGraph().addNode(endNoneEvent); createChild(UUID.uuid(), rootNode, endNoneEvent, rootNode.getOutEdges().size()); // create sequence flow between stages buildChildEdge(rootNode); }); } @SuppressWarnings("unchecked") private void buildChildEdge(Node parentNode) { final List<Node> nodes = (List<Node>) parentNode.getOutEdges().stream() .map(e -> ((Edge) e).getTargetNode()).collect(Collectors.toList()); for (int i = 0, n = nodes.size() - 1; i < n; i++) { createEdge(UUID.uuid(), nodes.get(i), nodes.get(i + 1)); } } @SuppressWarnings("unchecked") private void createEdge(String uuid, Node sourceNode, Node targetNode) { final Edge<View<SequenceFlow>, Node> edge = typedFactoryManager.newEdge(uuid, SequenceFlow.class); edge.setSourceNode(sourceNode); edge.setTargetNode(targetNode); sourceNode.getOutEdges().add(edge); targetNode.getInEdges().add(edge); ViewConnector<SequenceFlow> content = (ViewConnector<SequenceFlow>) edge.getContent(); content.setSourceConnection(MagnetConnection.Builder.atCenter(sourceNode)); content.setTargetConnection(MagnetConnection.Builder.atCenter(targetNode)); } @SuppressWarnings("unchecked") private void createChild(String uuid, Node parent, Node child, int parentIndex) { final Edge<Child, Node> edge = new EdgeImpl<>(uuid); edge.setContent(new Child()); edge.setSourceNode(parent); edge.setTargetNode(child); parent.getOutEdges().add(parentIndex, edge); child.getInEdges().add(edge); } private double adjustNodeBounds(Node<View, Edge<View, Node<View, Edge<View, Node<View, Edge>>>>> rootNode) { final List<Node<View, Edge<View, Node<View, Edge>>>> stages = rootNode.getOutEdges().stream().map(Edge::getTargetNode) .filter(n -> AdHocSubprocess.class.isInstance(n.getContent().getDefinition())).collect(Collectors.toList()); if (stages.isEmpty()) { return 0.0; } // calculate stage width final double stageWidth = stages.stream().mapToDouble(stage -> stage.getOutEdges().stream().mapToDouble( edge -> edge.getTargetNode().getContent().getBounds().getWidth() + STAGE_GAP * 2) .max().orElse(stage.getContent().getBounds().getWidth())).max().getAsDouble(); // calculate stage height final double stageHeight = stages.stream().mapToDouble( stage -> { final double cHeight = stage.getOutEdges().stream().mapToDouble( edge -> edge.getTargetNode().getContent().getBounds().getHeight() + STAGE_GAP).sum() + STAGE_GAP; final double sHeight = stage.getContent().getBounds().getHeight(); return cHeight > sHeight ? cHeight : sHeight; }).max().getAsDouble(); // calculate stage x coordinates final List<Double> stageXs = DoubleStream.iterate(ORIGIN_X + EVENT_WIDTH + GAP, x -> x + stageWidth + GAP) .limit(stages.size()).boxed().collect(Collectors.toList()); IntStream.range(0, stages.size()).forEach(index -> { final Node<View, Edge<View, Node<View, Edge>>> node = stages.get(index); final double x = stageXs.get(index); // set stage bounds node.getContent().setBounds(Bounds.create(x, ORIGIN_Y, x + stageWidth, ORIGIN_Y + stageHeight)); // calculate stage child y coordinates final List<Double> childYs = new ArrayList<>(node.getOutEdges().size()); double heightSum = STAGE_GAP; for (Edge<View, Node<View, Edge>> edge : node.getOutEdges()) { childYs.add(heightSum); heightSum = heightSum + edge.getTargetNode().getContent().getBounds().getHeight() + STAGE_GAP; } IntStream.range(0, node.getOutEdges().size()).forEach(i -> { final Node<View, Edge> childNode = node.getOutEdges().get(i).getTargetNode(); final double cx = (stageWidth - childNode.getContent().getBounds().getWidth()) / 2.0; final double cy = childYs.get(i); // set stage child bounds childNode.getContent().setBounds( Bounds.create(cx, cy, cx + childNode.getContent().getBounds().getWidth(), cy + childNode.getContent().getBounds().getHeight())); }); }); return stages.size() * (stageWidth + GAP); } @Override public Graph<DefinitionSet, Node> unmarshall(Metadata metadata, InputStream inputStream) throws IOException { Graph<DefinitionSet, Node> graph = super.unmarshall(metadata, inputStream); postUnmarshallProcess(graph); return graph; } @SuppressWarnings("unchecked") private void postUnmarshallProcess(final Graph<DefinitionSet, Node> graph) { List<Node<View<?>, Edge>> nodes = StreamSupport.stream(graph.nodes().spliterator(), false) .map(n -> (Node<View<?>, Edge>) n).collect(Collectors.toList()); nodes.stream() .filter(node -> CaseManagementDiagram.class.isInstance(node.getContent().getDefinition())) .findAny().ifPresent(root -> { // remove sequence flow between stages deleteChildEdge(root); // remove start event and end event final Node<View<?>, Edge> startNode = root.getOutEdges().get(0).getTargetNode(); if (StartNoneEvent.class.isInstance(startNode.getContent().getDefinition())) { deleteChild(root, startNode); graph.removeNode(startNode.getUUID()); } final Node<View<?>, Edge> endNode = root.getOutEdges().get(root.getOutEdges().size() - 1).getTargetNode(); if (EndNoneEvent.class.isInstance(endNode.getContent().getDefinition())) { deleteChild(root, endNode); graph.removeNode(endNode.getUUID()); } // sort the child nodes in stages Stream<Node<View<?>, Edge<View, Node<View, Edge>>>> stageStream = root.getOutEdges().stream().map(Edge::getTargetNode); stageStream.filter(n -> AdHocSubprocess.class.isInstance(n.getContent().getDefinition())) .forEach(n -> Collections.sort(n.getOutEdges(), (e1, e2) -> { final double y1 = e1.getTargetNode().getContent().getBounds().getY(); final double y2 = e2.getTargetNode().getContent().getBounds().getY(); return Double.compare(y1, y2); })); }); } @SuppressWarnings("unchecked") private void deleteChildEdge(Node parentNode) { final List<Node> childNodes = new LinkedList<>(); parentNode.getOutEdges().stream().map(e -> ((Edge) e).getTargetNode()) .filter(n -> ((Node) n).getInEdges().size() == 1) .findAny().ifPresent(nd -> { Node node = (Node) nd; do { childNodes.add(node); } while ((node = deleteEdge(node)) != null); final List<Edge> childEdges = childNodes.stream() .map(n -> (Edge) parentNode.getOutEdges().stream().filter(e -> n.equals(((Edge) e).getTargetNode())).findAny().get()) .collect(Collectors.toList()); parentNode.getOutEdges().clear(); childEdges.forEach(e -> parentNode.getOutEdges().add(e)); }); } @SuppressWarnings("unchecked") private void deleteChild(Node parent, Node child) { parent.getOutEdges().stream().filter(edge -> child.equals(((Edge) edge).getTargetNode())) .findAny().ifPresent(edge -> { parent.getOutEdges().remove(edge); child.getInEdges().remove(edge); }); } @SuppressWarnings("unchecked") private Node deleteEdge(Node sourceNode) { final Edge targetEdge = (Edge) sourceNode.getOutEdges().stream().filter(edge -> (((Edge) edge).getContent() instanceof ViewConnector) && ((ViewConnector) ((Edge) edge).getContent()).getDefinition() instanceof SequenceFlow) .findAny().orElse(null); if (targetEdge != null) { final Node targetNode = targetEdge.getTargetNode(); sourceNode.getOutEdges().remove(targetEdge); targetNode.getInEdges().remove(targetEdge); return targetNode; } return null; } @Override @SuppressWarnings("unchecked") protected org.kie.workbench.common.stunner.cm.backend.converters.fromstunner.CaseManagementConverterFactory createFromStunnerConverterFactory( final Graph graph, final PropertyWriterFactory propertyWriterFactory) { return new org.kie.workbench.common.stunner.cm.backend.converters.fromstunner.CaseManagementConverterFactory( new DefinitionsBuildingContext(graph, CaseManagementDiagram.class), propertyWriterFactory); } @Override protected org.kie.workbench.common.stunner.cm.backend.converters.tostunner.CaseManagementConverterFactory createToStunnerConverterFactory( final DefinitionResolver definitionResolver, final TypedFactoryManager typedFactoryManager) { return new org.kie.workbench.common.stunner.cm.backend.converters.tostunner.CaseManagementConverterFactory( definitionResolver, typedFactoryManager); } @Override protected CaseManagementPropertyWriterFactory createPropertyWriterFactory() { return new CaseManagementPropertyWriterFactory(); } @Override protected Class<CaseManagementDefinitionSet> getDefinitionSetClass() { return CaseManagementDefinitionSet.class; } }
jhrcek/kie-wb-common
kie-wb-common-stunner/kie-wb-common-stunner-sets/kie-wb-common-stunner-case-mgmt/kie-wb-common-stunner-case-mgmt-backend/src/main/java/org/kie/workbench/common/stunner/cm/backend/CaseManagementDirectDiagramMarshaller.java
Java
apache-2.0
16,713
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.pig.impl.logicalLayer; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import org.apache.pig.PigException; import org.apache.pig.impl.plan.DependencyOrderWalker; import org.apache.pig.impl.plan.RequiredFields; import org.apache.pig.impl.plan.VisitorException; import org.apache.pig.impl.plan.optimizer.OptimizerException; import org.apache.pig.impl.util.Pair; import org.apache.pig.impl.logicalLayer.RelationalOperator; public class ColumnPruner extends LOVisitor { private Map<LogicalOperator, List<Pair<Integer,Integer>>> prunedColumnsMap; LogicalPlan plan; public ColumnPruner(LogicalPlan plan) { super(plan, new DependencyOrderWalker<LogicalOperator, LogicalPlan>(plan)); prunedColumnsMap = new HashMap<LogicalOperator, List<Pair<Integer,Integer>>>(); this.plan = plan; } public void addPruneMap(LogicalOperator op, List<Pair<Integer,Integer>> prunedColumns) { prunedColumnsMap.put(op, prunedColumns); } public boolean isEmpty() { return prunedColumnsMap.isEmpty(); } protected void prune(RelationalOperator lOp) throws VisitorException { List<LogicalOperator> predecessors = plan.getPredecessors(lOp); if (predecessors==null) { int errCode = 2187; throw new VisitorException("Cannot get predessors", errCode, PigException.BUG); } List<Pair<Integer, Integer>> columnsPruned = new ArrayList<Pair<Integer, Integer>>(); List<Pair<Integer, Integer>> columnsToPrune = new ArrayList<Pair<Integer, Integer>>(); for (int i=0;i<predecessors.size();i++) { RelationalOperator predecessor = (RelationalOperator)predecessors.get(i); if (prunedColumnsMap.containsKey(predecessor)) { List<Pair<Integer, Integer>> predColumnsToPrune = prunedColumnsMap.get(predecessor); if (predColumnsToPrune!=null) { for (int j=0;j<predColumnsToPrune.size();j++) { predColumnsToPrune.get(j).first = i; } columnsPruned.addAll(predColumnsToPrune); } } } try { if (lOp.getSchema()==null) { int errCode = 2189; throw new VisitorException("Expect schema", errCode, PigException.BUG); } // For every input column, check if it is pruned for (int i=0;i<lOp.getSchema().size();i++) { List<RequiredFields> relevantFieldsList = lOp.getRelevantInputs(0, i); // Check if this output do not need any inputs, if so, it is a constant field. // Since we never prune a constant field, so we continue without pruning boolean needNoInputs = true; if (relevantFieldsList==null) needNoInputs = true; else { for (RequiredFields relevantFields: relevantFieldsList) { if (relevantFields!=null && !relevantFields.needNoFields()) needNoInputs = false; } } if (needNoInputs) continue; boolean columnPruned = false; // For LOCogroup, one output can be pruned if all its relevant input are pruned except for "key" fields if (lOp instanceof LOCogroup) { List<RequiredFields> requiredFieldsList = lOp.getRequiredFields(); for (Pair<Integer, Integer> column : columnsPruned) { if (column.first == i-1) // Saw at least one input pruned { if (requiredFieldsList.get(i-1).getFields().contains(column)) { columnPruned = true; break; } } } } else { // If we see any of the relevant field of this column get pruned, // then we prune this column for this operator for (RequiredFields relevantFields: relevantFieldsList) { if (relevantFields == null) continue; if (relevantFields.getNeedAllFields()) break; for (Pair<Integer, Integer> relevantField: relevantFields.getFields()) { if (columnsPruned.contains(relevantField)) { columnPruned = true; } else { // For union, inconsistent pruning is possible (See PIG-1146) // We shall allow inconsistent pruning for union, and the pruneColumns method // in LOUnion will handle this inconsistency if (!(lOp instanceof LOUnion) && columnPruned==true) { int errCode = 2185; String msg = "Column $"+i+" of "+lOp+" inconsistent pruning"; throw new OptimizerException(msg, errCode, PigException.BUG); } } } } } if (columnPruned) columnsToPrune.add(new Pair<Integer, Integer>(0, i)); } LogicalOperator currentOp = lOp; // If it is LOCogroup, insert foreach to mimic pruning, because we have no way to prune // LOCogroup output only by pruning the inputs if (columnsPruned.size()!=0 && lOp instanceof LOCogroup) { List<Integer> columnsToProject = new ArrayList<Integer>(); for (int i=0;i<=predecessors.size();i++) { if (!columnsToPrune.contains(new Pair<Integer, Integer>(0, i))) columnsToProject.add(i); } currentOp = lOp.insertPlainForEachAfter(columnsToProject); } if (!columnsPruned.isEmpty()&&lOp.pruneColumns(columnsPruned)) { prunedColumnsMap.put(currentOp, columnsToPrune); } } catch (FrontendException e) { int errCode = 2188; throw new VisitorException("Cannot prune columns for "+lOp, errCode, PigException.BUG, e); } } protected void visit(LOCogroup cogroup) throws VisitorException { prune(cogroup); } protected void visit(LOCross cross) throws VisitorException { prune(cross); } protected void visit(LODistinct distinct) throws VisitorException { prune(distinct); } protected void visit(LOFilter filter) throws VisitorException { prune(filter); } protected void visit(LOForEach foreach) throws VisitorException { // The only case we should skip foreach is when this is the foreach // inserted after LOLoad to mimic pruning, then we put the prunedColumns entry // for that foreach, and we do not need to further visit this foreach here if (!prunedColumnsMap.containsKey(foreach)) prune(foreach); } protected void visit(LOJoin join) throws VisitorException { prune(join); } protected void visit(LOLimit limit) throws VisitorException { prune(limit); } protected void visit(LOSort sort) throws VisitorException { prune(sort); } protected void visit(LOSplit split) throws VisitorException { prune(split); } protected void visit(LOSplitOutput splitoutput) throws VisitorException { prune(splitoutput); } protected void visit(LOStore store) throws VisitorException { return; } protected void visit(LOStream stream) throws VisitorException { return; } protected void visit(LOUnion union) throws VisitorException { prune(union); return; } protected void visit(LOLoad lOp) throws VisitorException { return; } }
hirohanin/pig7hadoop21
src/org/apache/pig/impl/logicalLayer/ColumnPruner.java
Java
apache-2.0
9,623
package com.guilite.hostmonitor; import androidx.appcompat.app.AppCompatActivity; import android.os.Bundle; import android.app.Dialog; import android.app.PendingIntent; import android.content.Context; import android.content.Intent; import android.content.res.AssetManager; import android.hardware.usb.UsbManager; import android.net.Uri; import android.os.Environment; import android.util.Log; import android.view.View; import android.view.Window; import android.webkit.WebView; import android.widget.Button; import android.widget.Toast; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; public class MainActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); Initialize(); if(null == ms_thread_native){ ms_thread_native = new ThreadNative(); ms_thread_native.start(); } if(null == ms_manager){ ms_manager = (UsbManager) getSystemService(Context.USB_SERVICE); } if (null == ms_permissionIntent){ ms_permissionIntent = PendingIntent.getBroadcast(this, 0, new Intent("com.guilite.hostmonitor.usbserial.USB_PERMISSION"), 0); } if (null == ms_cp210x){ ms_cp210x = new UsbSerialCP210x(); } } public void ChangeViewState() { View view_0 = findViewById(R.id.id_monitor_view_0); if(null == view_0){ return; } if(View.GONE == view_0.getVisibility()){ view_0.setVisibility(View.VISIBLE); }else{ view_0.setVisibility(View.GONE); } } private void CopyAssetsToWorkFolder(String work_folder) { AssetManager assetManager = getAssets(); String[] files = null; try { files = assetManager.list(""); } catch (IOException e) { Log.e("tag", "Failed to get asset file list.", e); } if (files == null){ return; } for (String filename : files) { InputStream in = null; OutputStream out = null; try { in = assetManager.open(filename); File outFile = new File(work_folder, filename); out = new FileOutputStream(outFile); byte[] buffer = new byte[in.available()]; int read; while((read = in.read(buffer)) != -1){ out.write(buffer, 0, read); } } catch(IOException e) { Log.e("tag", "Failed to copy asset file: " + filename, e); } finally { if (in != null) { try { in.close(); } catch (IOException e) { Log.e("tag", "Failed to close InputStream", e); } } if (out != null) { try { out.close(); } catch (IOException e) { Log.e("tag", "Failed to close OutputStream", e); } } } } } private void Initialize() { if(ms_work_folder != null){ return; } showSourceCode(); File folder = new File(Environment.getExternalStorageDirectory() + File.separator + "idea4good"); ms_work_folder = folder.getPath() + File.separator; if(folder.exists()) { return; } if(folder.mkdirs()) { CopyAssetsToWorkFolder(ms_work_folder); } else { Log.e("tag", "Make work folder failed!"); } } public void ConnectUsbSerial(){ if(ms_cp210x.connection != null){ return; } String ret = ms_cp210x.connect(ms_manager, ms_permissionIntent, new UsbReadCallback() { @Override public void onReceive(byte[] data, int length) { ThreadNative.onReceiveData(data, length); } }) + "\n"; ret += ms_cp210x.setUsbCom(9600); Toast.makeText(this, ret, Toast.LENGTH_LONG).show(); } private void showSourceCode(){ sourceDialog= new Dialog(this); sourceDialog.requestWindowFeature(Window.FEATURE_NO_TITLE); sourceDialog.setContentView(R.layout.source_dialog); sourceDialog.setCancelable(true); sourceDialog.show(); webView = sourceDialog.findViewById(R.id.wb_webview); webView.setScrollbarFadingEnabled(false); webView.setHorizontalScrollBarEnabled(false); webView.getSettings().setJavaScriptEnabled(true); webView.loadUrl("https://github.com/idea4good/GuiLite"); buttonVideo = sourceDialog.findViewById(R.id.bt_watchVideo); buttonVideo.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Uri uri = Uri.parse("http://v.youku.com/v_show/id_XMzA5NTMzMTYyOA"); Intent intent = new Intent(Intent.ACTION_VIEW, uri); startActivity(intent); sourceDialog.dismiss(); } }); } private static ThreadNative ms_thread_native = null; public static String ms_work_folder = null; private static UsbManager ms_manager = null; private static PendingIntent ms_permissionIntent = null; private static UsbSerialCP210x ms_cp210x = null; private Dialog sourceDialog; private WebView webView; private Button buttonVideo; }
idea4good/GuiLiteSamples
HostMonitor/BuildAndroid/app/src/main/java/com/guilite/hostmonitor/MainActivity.java
Java
apache-2.0
5,766
/** * Copyright (C) 2009 - present by OpenGamma Inc. and the OpenGamma group of companies * * Please see distribution for license. */ package com.opengamma.financial.analytics.model.riskfactor.option; import java.util.HashSet; import java.util.Map; import java.util.Set; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.opengamma.analytics.financial.greeks.Greek; import com.opengamma.analytics.financial.greeks.GreekResultCollection; import com.opengamma.analytics.financial.riskfactor.GreekDataBundle; import com.opengamma.analytics.financial.riskfactor.GreekToPositionGreekConverter; import com.opengamma.analytics.financial.sensitivity.PositionGreek; import com.opengamma.analytics.financial.trade.OptionTradeData; import com.opengamma.analytics.math.function.Function1D; import com.opengamma.engine.ComputationTarget; import com.opengamma.engine.ComputationTargetSpecification; import com.opengamma.engine.function.AbstractFunction; import com.opengamma.engine.function.FunctionCompilationContext; import com.opengamma.engine.function.FunctionExecutionContext; import com.opengamma.engine.function.FunctionInputs; import com.opengamma.engine.target.ComputationTargetType; import com.opengamma.engine.value.ComputedValue; import com.opengamma.engine.value.ValueProperties; import com.opengamma.engine.value.ValueRequirement; import com.opengamma.engine.value.ValueSpecification; import com.opengamma.financial.analytics.greeks.AvailableGreeks; import com.opengamma.financial.analytics.greeks.AvailablePositionGreeks; /** * */ public class OptionGreekToPositionGreekConverterFunction extends AbstractFunction.NonCompiledInvoker { private static final Logger LOGGER = LoggerFactory.getLogger(OptionGreekToPositionGreekConverterFunction.class); private final Function1D<GreekDataBundle, Map<PositionGreek, Double>> _converter = new GreekToPositionGreekConverter(); // TODO pass in required greek rather than using the entire set @Override public Set<ComputedValue> execute(final FunctionExecutionContext executionContext, final FunctionInputs inputs, final ComputationTarget target, final Set<ValueRequirement> desiredValues) { final GreekResultCollection greekResultCollection = new GreekResultCollection(); Object greekResult; Greek greek; for (final String valueName : AvailableGreeks.getAllGreekNames()) { greekResult = inputs.getValue(valueName); if (greekResult == null) { LOGGER.warn("Could not get value for " + valueName); } if (!(greekResult instanceof Double)) { throw new IllegalArgumentException("Can only handle Double greeks."); } greek = AvailableGreeks.getGreekForValueRequirementName(valueName); greekResultCollection.put(greek, (Double) greekResult); } final GreekDataBundle dataBundle = new GreekDataBundle(greekResultCollection, null, new OptionTradeData(target.getPosition().getQuantity().doubleValue(), 25)); final Map<PositionGreek, Double> positionGreeks = _converter.evaluate(dataBundle); final Set<ComputedValue> results = new HashSet<>(); PositionGreek positionGreek; Double positionGreekResult; ValueSpecification resultSpecification; ComputedValue resultValue; final ComputationTargetSpecification targetSpec = target.toSpecification(); final ValueProperties properties = createValueProperties().get(); for (final ValueRequirement dV : desiredValues) { positionGreek = AvailablePositionGreeks.getPositionGreekForValueRequirementName(dV.getValueName()); positionGreekResult = positionGreeks.get(positionGreek); resultSpecification = new ValueSpecification(dV.getValueName(), targetSpec, properties); resultValue = new ComputedValue(resultSpecification, positionGreekResult); results.add(resultValue); } return results; } @Override public Set<ValueRequirement> getRequirements(final FunctionCompilationContext context, final ComputationTarget target, final ValueRequirement desiredValue) { final Set<ValueRequirement> requirements = new HashSet<>(); final ComputationTargetSpecification targetSpec = target.toSpecification(); for (final String valueName : AvailableGreeks.getAllGreekNames()) { requirements.add(new ValueRequirement(valueName, targetSpec)); } return requirements; } @Override public Set<ValueSpecification> getResults(final FunctionCompilationContext context, final ComputationTarget target) { final Set<ValueSpecification> results = new HashSet<>(); final ComputationTargetSpecification targetSpec = target.toSpecification(); final ValueProperties properties = createValueProperties().get(); for (final String valueName : AvailablePositionGreeks.getAllPositionGreekNames()) { results.add(new ValueSpecification(valueName, targetSpec, properties)); } return results; } @Override public String getShortName() { return "GreekToPositionGreekConverter"; } @Override public ComputationTargetType getTargetType() { return ComputationTargetType.POSITION; } }
McLeodMoores/starling
projects/financial/src/main/java/com/opengamma/financial/analytics/model/riskfactor/option/OptionGreekToPositionGreekConverterFunction.java
Java
apache-2.0
5,103
/* * Copyright (c) 2017 Otávio Santana and others * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * and Apache License v2.0 which accompanies this distribution. * The Eclipse Public License is available at http://www.eclipse.org/legal/epl-v10.html * and the Apache License v2.0 is available at http://www.opensource.org/licenses/apache2.0.php. * * You may elect to redistribute this code under either of these licenses. * * Contributors: * * Otavio Santana */ package org.jnosql.diana.redis.key; import org.jnosql.diana.driver.JsonbSupplier; import redis.clients.jedis.JedisPool; import javax.json.bind.Jsonb; import java.util.List; import java.util.Map; import java.util.Queue; import java.util.Set; import static java.util.Objects.requireNonNull; class DefaultRedisBucketManagerFactory implements RedisBucketManagerFactory { private static final Jsonb JSON = JsonbSupplier.getInstance().get(); private final JedisPool jedisPool; DefaultRedisBucketManagerFactory(JedisPool jedisPool) { this.jedisPool = jedisPool; } @Override public RedisBucketManager getBucketManager(String bucketName) { requireNonNull(bucketName, "bucket name is required"); return new RedisBucketManager(bucketName, JSON, jedisPool.getResource()); } @Override public <T> List<T> getList(String bucketName, Class<T> clazz) { requireNonNull(bucketName, "bucket name is required"); requireNonNull(clazz, "Class type is required"); return new RedisList<>(jedisPool.getResource(), clazz, bucketName); } @Override public <T> Set<T> getSet(String bucketName, Class<T> clazz) { requireNonNull(bucketName, "bucket name is required"); requireNonNull(clazz, "Class type is required"); return new RedisSet<>(jedisPool.getResource(), clazz, bucketName); } @Override public <T> Queue<T> getQueue(String bucketName, Class<T> clazz) { requireNonNull(bucketName, "bucket name is required"); requireNonNull(clazz, "Class type is required"); return new RedisQueue<>(jedisPool.getResource(), clazz, bucketName); } @Override public <K, V> Map<K, V> getMap(String bucketName, Class<K> keyValue, Class<V> valueValue) { requireNonNull(bucketName, "bucket name is required"); requireNonNull(valueValue, "Class type is required"); return new RedisMap<>(jedisPool.getResource(), keyValue, valueValue, bucketName); } @Override public SortedSet getSortedSet(String key) throws NullPointerException { requireNonNull(key, "key is required"); return new DefaultSortedSet(jedisPool.getResource(), key); } @Override public Counter getCounter(String key) throws NullPointerException { requireNonNull(key, "key is required"); return new DefaultCounter(key, jedisPool.getResource()); } @Override public void close() { jedisPool.close(); } @Override public String toString() { final StringBuilder sb = new StringBuilder("RedisBucketManagerFactory{"); sb.append("jedisPool=").append(jedisPool); sb.append('}'); return sb.toString(); } }
JNOSQL/diana-driver
redis-driver/src/main/java/org/jnosql/diana/redis/key/DefaultRedisBucketManagerFactory.java
Java
apache-2.0
3,327
/** * Copyright 2007-2015, Kaazing Corporation. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.mina.core; import java.io.IOException; /** * A unchecked version of {@link IOException}. * <p> * Please note that {@link RuntimeIoException} is different from * {@link IOException} in that doesn't trigger force session close, * while {@link IOException} forces disconnection. * * @author <a href="http://mina.apache.org">Apache MINA Project</a> */ public class RuntimeIoException extends RuntimeException { private static final long serialVersionUID = 9029092241311939548L; public RuntimeIoException() { super(); } public RuntimeIoException(String message) { super(message); } public RuntimeIoException(String message, Throwable cause) { super(message, cause); } public RuntimeIoException(Throwable cause) { super(cause); } }
chao-sun-kaazing/gateway
mina.core/core/src/main/java/org/apache/mina/core/RuntimeIoException.java
Java
apache-2.0
1,455
package org.nybatis.core.db.sql.sqlNode.expressionLanguage.node.operator.implement.equality; import org.nybatis.core.db.sql.sqlNode.expressionLanguage.node.Node; import org.nybatis.core.db.sql.sqlNode.expressionLanguage.node.constant.implement.BooleanValueNode; import org.nybatis.core.db.sql.sqlNode.expressionLanguage.node.operator.implement.EqualityNode; import org.nybatis.core.exception.unchecked.SqlParseException; public class NotEqualNode extends EqualityNode { public String toString() { return "!="; } public BooleanValueNode calculate( Node pre, Node post ) throws SqlParseException { return new BooleanValueNode ( ! new EqualNode().calculate( pre, post ).getValue() ); } }
NyBatis/NyBatisCore
src/main/java/org/nybatis/core/db/sql/sqlNode/expressionLanguage/node/operator/implement/equality/NotEqualNode.java
Java
apache-2.0
698
/* * Copyright 2013, WebGate Consulting AG * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at: * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or * implied. See the License for the specific language governing * permissions and limitations under the License. */ package org.openntf.xrest.xsp.servlet; import java.io.IOException; import java.io.PrintWriter; import java.io.Writer; import java.lang.reflect.Field; import java.net.URL; import java.util.HashSet; import java.util.List; import javax.faces.FacesException; import javax.faces.FactoryFinder; import javax.faces.context.FacesContext; import javax.faces.context.FacesContextFactory; import javax.faces.event.PhaseListener; import javax.faces.lifecycle.Lifecycle; import javax.servlet.ServletConfig; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.openntf.xrest.xsp.exec.ExecutorException; import org.openntf.xrest.xsp.exec.RouteProcessorExecutor; import org.openntf.xrest.xsp.exec.RouteProcessorExecutorFactory; import org.openntf.xrest.xsp.exec.impl.ContextImpl; import org.openntf.xrest.xsp.exec.output.ExecutorExceptionProcessor; import org.openntf.xrest.xsp.exec.output.JsonPayloadProcessor; import org.openntf.xrest.xsp.model.RouteProcessor; import org.openntf.xrest.xsp.model.Router; import org.openntf.xrest.xsp.names.UserAndGroupHandler; import org.openntf.xrest.xsp.yaml.YamlProducer; import com.ibm.commons.util.NotImplementedException; import com.ibm.commons.util.StringUtil; import com.ibm.commons.util.io.json.JsonException; import com.ibm.commons.util.io.json.JsonJavaFactory; import com.ibm.commons.util.io.json.JsonJavaObject; import com.ibm.commons.util.io.json.JsonParser; import com.ibm.domino.xsp.module.nsf.NotesContext; import com.ibm.xsp.application.ApplicationEx; import com.ibm.xsp.context.FacesContextEx; import com.ibm.xsp.controller.FacesController; import com.ibm.xsp.controller.FacesControllerFactoryImpl; import io.prometheus.client.CollectorRegistry; import io.prometheus.client.Histogram; import io.prometheus.client.Histogram.Timer; import io.prometheus.client.exporter.common.TextFormat; import lotus.domino.NotesException; import lotus.domino.Session; public class XRestAPIServlet extends HttpServlet { private static Lifecycle dummyLifeCycle = new Lifecycle() { @Override public void render(FacesContext context) throws FacesException { throw new NotImplementedException(); } @Override public void removePhaseListener(PhaseListener listener) { throw new NotImplementedException(); } @Override public PhaseListener[] getPhaseListeners() { throw new NotImplementedException(); } @Override public void execute(FacesContext context) throws FacesException { throw new NotImplementedException(); } @Override public void addPhaseListener(PhaseListener listener) { throw new NotImplementedException(); } }; /** * */ private static final long serialVersionUID = 1L; private ServletConfig config; private FacesContextFactory contextFactory; private RouterFactory routerFactory; private Histogram histogram; public XRestAPIServlet(final RouterFactory routerFactory) { this.routerFactory = routerFactory; } @Override public void init(final ServletConfig config) throws ServletException { this.config = config; contextFactory = (FacesContextFactory) FactoryFinder.getFactory(FactoryFinder.FACES_CONTEXT_FACTORY); } @Override protected void service(final HttpServletRequest req, final HttpServletResponse resp) throws ServletException, IOException { if (routerFactory.hasError()) { publishError(req, resp, routerFactory.getError()); return; } if (histogram == null) { histogram = routerFactory.buildHistogram(); } Timer timer = null; Router router = routerFactory.getRouter(); FacesContext fc = null; try { if (router.useFacesContext()) { fc = initContext(req, resp); FacesContextEx exc = (FacesContextEx) fc; ApplicationEx ape = exc.getApplicationEx(); if (ape.getController() == null) { FacesController controller = new FacesControllerFactoryImpl().createFacesController(getServletContext()); controller.init(null); } } String method = req.getMethod(); String path = req.getPathInfo(); if (router.isEnableCORS()) { processCORSHeaders(req, resp, router, method); } if (StringUtil.isEmpty(path)) { timer = processBuildInCommands(resp, req, router); } else { timer = processRouteProcessorBased(req, resp, method, path, fc); } } catch (ExecutorException ex) { try { ExecutorExceptionProcessor.INSTANCE.processExecutorException(ex, resp, router.isTrace()); } catch (Exception e) { e.printStackTrace(); } } catch (Exception ex) { try { ExecutorExceptionProcessor.INSTANCE.processGeneralException(500, ex, resp); } catch (Exception e) { e.printStackTrace(); } } finally { if (router.useFacesContext() && fc != null) { releaseContext(fc); } if (timer != null) { timer.observeDuration(); } } } private void processCORSHeaders(HttpServletRequest req, HttpServletResponse resp, Router router, String method) { if ("OPTIONS".equals(method)) { resp.addHeader("Access-Control-Allow-Headers", "origin, content-type, accept, " + router.getCORSTokenHeader()); } if (router.isCORSAllowCredentials()) { resp.addHeader("Access-Control-Allow-Credentials", "true"); } resp.addHeader("Access-Control-Allow-Origin", toColonValue(router.getCORSOrginValue())); resp.addHeader("Access-Control-Allow-Methods", toColonValue(router.getCORSAllowMethodValue())); } private String toColonValue(List<String> corsOrginValue) { StringBuilder sb = new StringBuilder(); if (corsOrginValue.isEmpty()) { return ""; } for (String value : corsOrginValue) { sb.append(value); sb.append(","); } return sb.substring(0, sb.length() - 1); } private Timer processBuildInCommands(final HttpServletResponse resp, final HttpServletRequest request, Router router) throws JsonException, IOException, ExecutorException, NotesException { Timer timer = null; String queryString = request.getQueryString(); if (StringUtil.isEmpty(queryString)) { throw new ExecutorException(500, "Path not found and no built-in command found.", request.getPathInfo(), "SERVLET"); } if ("yaml".equals(request.getQueryString())) { timer = histogram.labels("yaml", request.getMethod()).startTimer(); processYamlRequest(resp, request); return timer; } if ("swagger".equals(request.getQueryString())) { timer = histogram.labels("swagger", request.getMethod()).startTimer(); processSwaggerRequest(resp, request); return timer; } if ("login".equals(request.getQueryString())) { timer = histogram.labels("login", request.getMethod()).startTimer(); processLoginRequest(resp, request); return timer; } if ("metrics".equals(request.getQueryString())) { processMetricsRequest(resp, request); return timer; } if (queryString.startsWith("users")) { timer = histogram.labels("users",request.getMethod()).startTimer(); ContextImpl context = new ContextImpl(); NotesContext c = modifiyNotesContext(); context.addNotesContext(c).addRequest(request).addResponse(resp); UserAndGroupHandler handler = new UserAndGroupHandler( resp, router.getTypeAHeadResolverValue(), router.getUserInformationResolverValue(),context); handler.execute(queryString); return timer; } throw new ExecutorException(500, queryString +" is not a built-in command.", request.getPathInfo(), "SERVLET"); } private void processMetricsRequest(HttpServletResponse resp, HttpServletRequest request) throws IOException { resp.setStatus(HttpServletResponse.SC_OK); resp.setContentType(TextFormat.CONTENT_TYPE_004); Writer writer = resp.getWriter(); try { TextFormat.write004(writer, CollectorRegistry.defaultRegistry.metricFamilySamples()); writer.flush(); } finally { writer.close(); } } private void processLoginRequest(HttpServletResponse resp, HttpServletRequest request) throws ExecutorException { JsonJavaObject loginObject = new JsonJavaObject(); try { NotesContext c = NotesContext.getCurrentUnchecked(); Session ses = c.getCurrentSession(); loginObject.put("username", ses.getEffectiveUserName()); loginObject.put("groups", c.getGroupList()); loginObject.put("accesslevel", c.getCurrentDatabase().getCurrentAccessLevel()); loginObject.put("roles", c.getCurrentDatabase().queryAccessRoles(ses.getEffectiveUserName())); loginObject.put("email", c.getInetMail()); JsonPayloadProcessor.INSTANCE.processJsonPayload(loginObject, resp); return; } catch (Exception ex) { throw new ExecutorException(500, "Error during build response object", ex, request.getPathInfo(), "/?login"); } } private void processSwaggerRequest(final HttpServletResponse resp, final HttpServletRequest request) throws IOException { String path = request.getRequestURL().toString(); URL url = new URL(path + "?yaml"); URL urlSwagger = new URL(url.getProtocol(), url.getHost(), url.getPort(), "/xsp/.ibmxspres/.swaggerui/dist/index.html?url=" + url.toExternalForm()); resp.sendRedirect(urlSwagger.toExternalForm()); } private void processYamlRequest(final HttpServletResponse resp, final HttpServletRequest request) throws JsonException, IOException { Router router = routerFactory.getRouter(); PrintWriter pw = resp.getWriter(); YamlProducer yamlProducer = new YamlProducer(router, request, pw); yamlProducer.processYamlToPrintWriter(); pw.close(); } private Timer processRouteProcessorBased(final HttpServletRequest req, final HttpServletResponse resp, final String method, final String path, FacesContext fc) throws NotesException, IOException, ExecutorException { RouteProcessor rp = routerFactory.getRouter().find(method, path); if (rp != null) { Timer timer = histogram.labels(rp.getRoute(), rp.getMethod()).startTimer(); ContextImpl context = new ContextImpl(); NotesContext c = modifiyNotesContext(); context.addNotesContext(c).addRequest(req).addResponse(resp); context.addRouterVariables(rp.extractValuesFromPath(path)); context.addQueryStringVariables(rp.extractValuesFromQueryString(req.getQueryString())); context.setTrace(routerFactory.getRouter().isTrace()); context.addFacesContext(fc); context.addIdentityMapProvider(routerFactory.getRouter().getIdentityMapProviderValue()); if (req.getContentLength() > 0 && req.getContentType() != null && req.getContentType().toLowerCase().startsWith("application/json")) { try { JsonJavaFactory factory = JsonJavaFactory.instanceEx2; JsonJavaObject json = (JsonJavaObject) JsonParser.fromJson(factory, req.getReader()); context.addJsonPayload(json); } catch (JsonException jE) { jE.printStackTrace(); } } RouteProcessorExecutor executor = RouteProcessorExecutorFactory.getExecutor(method, path, context, rp); executor.execute(); return timer; } else { throw new ExecutorException(500, "Path not found", path, "SERVLET"); } } private void publishError(final HttpServletRequest req, final HttpServletResponse resp, final Throwable error) { error.printStackTrace(); } public void refresh() { routerFactory.refresh(); histogram = routerFactory.buildHistogram(); } public FacesContext initContext(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // Create a temporary FacesContext and make it available FacesContext context = contextFactory.getFacesContext(getServletConfig().getServletContext(), request, response, dummyLifeCycle); return context; } public void releaseContext(FacesContext context) throws ServletException, IOException { context.release(); } @Override public ServletConfig getServletConfig() { return config; } private NotesContext modifiyNotesContext() { NotesContext c = NotesContext.getCurrentUnchecked(); try { Field checkedSigners = NotesContext.class.getDeclaredField("checkedSigners"); checkedSigners.setAccessible(true); HashSet<?> signers = (HashSet<?>) checkedSigners.get(c); signers.clear(); } catch (SecurityException e) { e.printStackTrace(); } catch (NoSuchFieldException e) { e.printStackTrace(); } catch (IllegalArgumentException e) { e.printStackTrace(); } catch (IllegalAccessException e) { e.printStackTrace(); } c.setSignerSessionRights("WEB-INF/routes.groovy"); return c; } }
OpenNTF/SmartNSF
server/org.openntf.xrest.xsp/src/org/openntf/xrest/xsp/servlet/XRestAPIServlet.java
Java
apache-2.0
12,966
package org.skyscreamer.yoga.model; import java.io.IOException; public interface HierarchicalModel<T> { T getUnderlyingModel(); void finished() throws IOException; }
skyscreamer/yoga
yoga-core/src/main/java/org/skyscreamer/yoga/model/HierarchicalModel.java
Java
apache-2.0
178
package com.ratemarkt.models; import java.util.List; import javax.annotation.Nullable; import org.immutables.gson.Gson; import org.immutables.value.Value; @Gson.TypeAdapters @Value.Immutable public interface Room { @Nullable Integer getNumberOfAdults(); @Nullable List<Integer> getChildrenAges(); @Nullable String getRoomDescription(); @Value.Default default Integer getSequence() { return 1; } }
ratemarkt/ratemarkt-sdk
src/main/java/com/ratemarkt/models/Room.java
Java
apache-2.0
416
package com.spring.tx; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; @Service("cashier") public class CashierImpl implements Cashier { @Autowired private BookShopService bookShopService; @Transactional public void checkout(String username, List<String> isbns) { for(String isbn : isbns) { bookShopService.purchase(username, isbn); } } }
13732226055/codeBackup
myspring/myspring/src/main/java/com/spring/tx/CashierImpl.java
Java
apache-2.0
543
/* * Copyright (C) 2017 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.android.tools.build.bundletool; import com.android.tools.build.bundletool.commands.AddTransparencyCommand; import com.android.tools.build.bundletool.commands.BuildApksCommand; import com.android.tools.build.bundletool.commands.BuildBundleCommand; import com.android.tools.build.bundletool.commands.CheckTransparencyCommand; import com.android.tools.build.bundletool.commands.CommandHelp; import com.android.tools.build.bundletool.commands.DumpCommand; import com.android.tools.build.bundletool.commands.ExtractApksCommand; import com.android.tools.build.bundletool.commands.GetDeviceSpecCommand; import com.android.tools.build.bundletool.commands.GetSizeCommand; import com.android.tools.build.bundletool.commands.InstallApksCommand; import com.android.tools.build.bundletool.commands.InstallMultiApksCommand; import com.android.tools.build.bundletool.commands.ValidateBundleCommand; import com.android.tools.build.bundletool.commands.VersionCommand; import com.android.tools.build.bundletool.device.AdbServer; import com.android.tools.build.bundletool.device.DdmlibAdbServer; import com.android.tools.build.bundletool.flags.FlagParser; import com.android.tools.build.bundletool.flags.ParsedFlags; import com.android.tools.build.bundletool.model.version.BundleToolVersion; import com.google.common.collect.ImmutableList; import java.util.Optional; /** * Main entry point of the bundle tool. * * <p>Consider running with -Dsun.zip.disableMemoryMapping when dealing with large bundles. */ public class BundleToolMain { public static final String HELP_CMD = "help"; public static void main(String[] args) { main(args, Runtime.getRuntime()); } /** Parses the flags and routes to the appropriate command handler. */ static void main(String[] args, Runtime runtime) { final ParsedFlags flags; try { flags = new FlagParser().parse(args); } catch (FlagParser.FlagParseException e) { System.err.println("Error while parsing the flags: " + e.getMessage()); runtime.exit(1); return; } Optional<String> command = flags.getMainCommand(); if (!command.isPresent()) { System.err.println("Error: You have to specify a command."); help(); runtime.exit(1); return; } try { switch (command.get()) { case BuildBundleCommand.COMMAND_NAME: BuildBundleCommand.fromFlags(flags).execute(); break; case BuildApksCommand.COMMAND_NAME: try (AdbServer adbServer = DdmlibAdbServer.getInstance()) { BuildApksCommand.fromFlags(flags, adbServer).execute(); } break; case ExtractApksCommand.COMMAND_NAME: ExtractApksCommand.fromFlags(flags).execute(); break; case GetDeviceSpecCommand.COMMAND_NAME: // We have to destroy ddmlib resources at the end of the command. try (AdbServer adbServer = DdmlibAdbServer.getInstance()) { GetDeviceSpecCommand.fromFlags(flags, adbServer).execute(); } break; case InstallApksCommand.COMMAND_NAME: try (AdbServer adbServer = DdmlibAdbServer.getInstance()) { InstallApksCommand.fromFlags(flags, adbServer).execute(); } break; case InstallMultiApksCommand.COMMAND_NAME: try (AdbServer adbServer = DdmlibAdbServer.getInstance()) { InstallMultiApksCommand.fromFlags(flags, adbServer).execute(); } break; case ValidateBundleCommand.COMMAND_NAME: ValidateBundleCommand.fromFlags(flags).execute(); break; case DumpCommand.COMMAND_NAME: DumpCommand.fromFlags(flags).execute(); break; case GetSizeCommand.COMMAND_NAME: GetSizeCommand.fromFlags(flags).execute(); break; case VersionCommand.COMMAND_NAME: VersionCommand.fromFlags(flags, System.out).execute(); break; case AddTransparencyCommand.COMMAND_NAME: AddTransparencyCommand.fromFlags(flags).execute(); break; case CheckTransparencyCommand.COMMAND_NAME: try (AdbServer adbServer = DdmlibAdbServer.getInstance()) { CheckTransparencyCommand.fromFlags(flags, adbServer).execute(); } break; case HELP_CMD: if (flags.getSubCommand().isPresent()) { help(flags.getSubCommand().get(), runtime); } else { help(); } break; default: System.err.printf("Error: Unrecognized command '%s'.%n%n%n", command.get()); help(); runtime.exit(1); return; } } catch (Exception e) { System.err.println( "[BT:" + BundleToolVersion.getCurrentVersion() + "] Error: " + e.getMessage()); e.printStackTrace(); runtime.exit(1); return; } // Takes care of shutting down non-daemon threads in internal thread pools. runtime.exit(0); } /** Displays a general help. */ public static void help() { ImmutableList<CommandHelp> commandHelps = ImmutableList.of( BuildBundleCommand.help(), BuildApksCommand.help(), ExtractApksCommand.help(), GetDeviceSpecCommand.help(), InstallApksCommand.help(), InstallMultiApksCommand.help(), ValidateBundleCommand.help(), DumpCommand.help(), GetSizeCommand.help(), VersionCommand.help()); System.out.println("Synopsis: bundletool <command> ..."); System.out.println(); System.out.println("Use 'bundletool help <command>' to learn more about the given command."); System.out.println(); commandHelps.forEach(commandHelp -> commandHelp.printSummary(System.out)); } /** Displays help about a given command. */ public static void help(String commandName, Runtime runtime) { CommandHelp commandHelp; switch (commandName) { case BuildBundleCommand.COMMAND_NAME: commandHelp = BuildBundleCommand.help(); break; case BuildApksCommand.COMMAND_NAME: commandHelp = BuildApksCommand.help(); break; case ExtractApksCommand.COMMAND_NAME: commandHelp = ExtractApksCommand.help(); break; case GetDeviceSpecCommand.COMMAND_NAME: commandHelp = GetDeviceSpecCommand.help(); break; case InstallApksCommand.COMMAND_NAME: commandHelp = InstallApksCommand.help(); break; case InstallMultiApksCommand.COMMAND_NAME: commandHelp = InstallMultiApksCommand.help(); break; case ValidateBundleCommand.COMMAND_NAME: commandHelp = ValidateBundleCommand.help(); break; case DumpCommand.COMMAND_NAME: commandHelp = DumpCommand.help(); break; case GetSizeCommand.COMMAND_NAME: commandHelp = GetSizeCommand.help(); break; case AddTransparencyCommand.COMMAND_NAME: commandHelp = AddTransparencyCommand.help(); break; case CheckTransparencyCommand.COMMAND_NAME: commandHelp = CheckTransparencyCommand.help(); break; default: System.err.printf("Error: Unrecognized command '%s'.%n%n%n", commandName); help(); runtime.exit(1); return; } commandHelp.printDetails(System.out); } }
google/bundletool
src/main/java/com/android/tools/build/bundletool/BundleToolMain.java
Java
apache-2.0
8,020
/* * Copyright 2014 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. */ import org.vertx.java.core.AsyncResult; import org.vertx.java.core.Handler; import org.vertx.java.core.eventbus.Message; import org.vertx.java.core.json.JsonObject; import org.vertx.java.platform.Verticle; /** * Deploy module example. * * @author Jordan Halterman */ public class DeployExample extends Verticle { @Override public void start() { JsonObject message = new JsonObject() .putString("action", "deploy") .putString("group", "test") .putString("module", "net.kuujo~test-module~1.0") .putObject("config", new JsonObject().putString("foo", "bar")) .putNumber("instances", 4); vertx.eventBus().sendWithTimeout("cluster", message, 30000, new Handler<AsyncResult<Message<JsonObject>>>() { @Override public void handle(AsyncResult<Message<JsonObject>> result) { if (result.failed()) { container.logger().error(result.cause()); } else { container.logger().info("Successfully deployed module."); } } }); } }
bezda/xync
examples/deploy/DeployExample.java
Java
apache-2.0
1,656
package jp.zyyx.dynamicapp.bluetoothComponents.Bluetooth4LE.ClientProfile; import java.util.Collection; import java.util.HashMap; import java.util.ArrayList; import java.util.Iterator; import android.bluetooth.BluetoothDevice; import android.content.Context; import android.util.Log; import com.broadcom.bt.le.api.BleClientProfile; import com.broadcom.bt.le.api.BleGattID; import com.broadcom.bt.le.api.BleClientService; import com.broadcom.bt.le.api.BleCharacteristic; /* * Copyright (C) 2014 ZYYX, 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. */ public class BaseClientProfile extends BleClientProfile { private static String TAG = "BaseClientProfile"; // The type of process; public static final int PROCESS_TYPE_WRITE = 0; public static final int PROCESS_TYPE_READ = 1; // The type of value. public static final int VALUE_TYPE_UUID = 0; public static final int VALUE_TYPE_BOOLEAN = 1; public static final int VALUE_TYPE_2BIT = 2; public static final int VALUE_TYPE_NIBBLE = 3; public static final int VALUE_TYPE_8BIT = 4; public static final int VALUE_TYPE_16BIT = 5; public static final int VALUE_TYPE_24BIT = 6; public static final int VALUE_TYPE_32BIT = 7; public static final int VALUE_TYPE_UINT8 = 8; public static final int VALUE_TYPE_UINT12 = 9; public static final int VALUE_TYPE_UINT16 = 10; public static final int VALUE_TYPE_UINT24 = 11; public static final int VALUE_TYPE_UINT32 = 12; public static final int VALUE_TYPE_UINT40 = 13; public static final int VALUE_TYPE_UINT48 = 14; public static final int VALUE_TYPE_UINT64 = 15; public static final int VALUE_TYPE_UINT128 = 16; public static final int VALUE_TYPE_SINT8 = 17; public static final int VALUE_TYPE_SINT12 = 18; public static final int VALUE_TYPE_SINT16 = 19; public static final int VALUE_TYPE_SINT24 = 20; public static final int VALUE_TYPE_SINT32 = 21; public static final int VALUE_TYPE_SINT48 = 22; public static final int VALUE_TYPE_SINT64 = 23; public static final int VALUE_TYPE_SINT128 = 24; public static final int VALUE_TYPE_FLOAT32 = 25; public static final int VALUE_TYPE_FLOAT64 = 26; public static final int VALUE_TYPE_SFLOAT = 27; public static final int VALUE_TYPE_FLOAT = 28; public static final int VALUE_TYPE_DUNIT16 = 29; public static final int VALUE_TYPE_UTF8S = 30; public static final int VALUE_TYPE_UTF16S = 31; private HashMap<String, BleClientService> services = new HashMap<String, BleClientService>(); protected String value; protected int valueType; protected String serviceId; protected String characteristicId; protected String descriptorId; protected int procType; public BaseClientProfile(Context context, BleGattID uid) { super(context, uid); value = ""; valueType = 0; serviceId = ""; characteristicId = ""; descriptorId = ""; } protected void initialize() { ArrayList<BleClientService> services = new ArrayList<BleClientService>(); Collection<BleClientService> co = this.services.values(); for (Iterator<BleClientService> i = co.iterator(); i.hasNext();) { services.add((BleClientService)i.next()); } init(services, null); } protected void addService(BleClientService service) { this.services.put(service.getServiceId().toString(), service); } protected BleClientService getService(String serviceId) { return this.services.get(serviceId); } public void onInitialized(boolean success) { Log.d(TAG, "onInitialized"); if (success) { registerProfile(); } } public void onDeviceConnected(BluetoothDevice device) { Log.d(TAG, "onDeviceConnected"); refresh(device); } public void onDeviceDisconnected(BluetoothDevice device) { Log.d(TAG, "onDeviceDisconnected"); /*Intent intent = new Intent(); intent.setAction(FINDME_DISCONNECTED); intent.putExtra(BluetoothDevice.EXTRA_DEVICE, device.getAddress()); mContext.sendBroadcast(intent); connectBackground(device);*/ } public void onRefreshed(BluetoothDevice device) { Log.d(TAG, "onRefreshed"); BleClientService service = getService(this.serviceId); if(service == null) { // error return; } BleCharacteristic characteristic = service.getCharacteristic(device, new BleGattID(this.characteristicId)); if(this.procType == PROCESS_TYPE_WRITE) { characteristic.setValue(changeValue2writeValue()); service.writeCharacteristic(device, 0, characteristic); } else { service.readCharacteristic(device, characteristic); // byte[] bytValue = characteristic.getValue(); } /*Intent intent = new Intent(); intent.setAction(FINDME_CONNECTED); intent.putExtra(BluetoothDevice.EXTRA_DEVICE, device.getAddress()); mContext.sendBroadcast(intent);*/ } public void onProfileRegistered() { Log.d(TAG, "onProfileRegistered"); } public void onProfileDeregistered() { Log.d(TAG, "onProfileDeregistered"); notifyAll(); } public void onCharacteristicChanged(BluetoothDevice remoteDevice, BleCharacteristic characteristic) { Log.d(TAG, "onCharacteristicChanged"); } public void onWriteCharacteristicComplete(int status, BluetoothDevice remoteDevice, BleCharacteristic characteristic) { Log.d(TAG, "onWriteCharacteristicComplete"); } public void onReadCharacteristicComplete(BluetoothDevice remoteDevice, BleCharacteristic characteristic) { Log.d(TAG, "onReadCharacteristicComplete"); } public void writeValueForCharacteristic(BluetoothDevice device, String value, int valueType, String service, String characteristic) { this.value = value; this.valueType = valueType; // this.serviceId = serviceId; // this.characteristicId = characteristicId; this.procType = PROCESS_TYPE_WRITE; Log.d(TAG, "device:" + device.getName()); this.connect(device); } public void readValueForCharacteristic(BluetoothDevice device, String service, String characteristic, int valueType) { this.procType = PROCESS_TYPE_READ; } public void writeValueForDescriptor(BluetoothDevice device, String value, int valueType, String service, String characteristic, String descriptor) { this.procType = PROCESS_TYPE_WRITE; } public void readValueForDescriptor(BluetoothDevice device, String service, String characteristic, String descriptor, int valueType) { this.procType = PROCESS_TYPE_READ; } private byte[] changeValue2writeValue() { byte[] value = null; switch(this.valueType) { case VALUE_TYPE_UUID: break; case VALUE_TYPE_BOOLEAN: { byte bytValue = Byte.valueOf(this.value); value = new byte[1]; value[0] = bytValue; } break; case VALUE_TYPE_2BIT: break; case VALUE_TYPE_NIBBLE: break; case VALUE_TYPE_8BIT: break; case VALUE_TYPE_16BIT: break; case VALUE_TYPE_24BIT: break; case VALUE_TYPE_32BIT: break; case VALUE_TYPE_UINT8: { Integer ivalue = Integer.valueOf(this.value); int i = ivalue.intValue(); value = new byte[4]; value[0] = (byte)((i >>> 24 ) & 0xFF); value[1] = (byte)((i >>> 16 ) & 0xFF); value[2] = (byte)((i >>> 8 ) & 0xFF); value[3] = (byte)((i >>> 0 ) & 0xFF); } break; case VALUE_TYPE_UINT12: break; case VALUE_TYPE_UINT16: break; case VALUE_TYPE_UINT24: break; case VALUE_TYPE_UINT32: break; case VALUE_TYPE_UINT40: break; case VALUE_TYPE_UINT48: break; case VALUE_TYPE_UINT64: break; case VALUE_TYPE_UINT128: break; case VALUE_TYPE_SINT8: break; case VALUE_TYPE_SINT12: break; case VALUE_TYPE_SINT16: break; case VALUE_TYPE_SINT24: break; case VALUE_TYPE_SINT32: break; case VALUE_TYPE_SINT48: break; case VALUE_TYPE_SINT64: break; case VALUE_TYPE_SINT128: break; case VALUE_TYPE_FLOAT32: break; case VALUE_TYPE_FLOAT64: break; case VALUE_TYPE_SFLOAT: break; case VALUE_TYPE_FLOAT: break; case VALUE_TYPE_DUNIT16: break; case VALUE_TYPE_UTF8S: break; case VALUE_TYPE_UTF16S: break; } return value; } }
dynamicapp/dynamicapp
lib/Android/Library/src/jp/zyyx/dynamicapp/bluetoothComponents/Bluetooth4LE/ClientProfile/BaseClientProfile.java
Java
apache-2.0
8,889
/* ==================================================================== Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. See the NOTICE file distributed with this work for additional information regarding copyright ownership. The ASF licenses this file to You under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ==================================================================== */ package org.apache.poi.ss.formula.eval.forked; import static org.junit.Assert.assertEquals; import java.io.IOException; import org.apache.poi.hssf.usermodel.HSSFWorkbook; import org.apache.poi.ss.formula.IStabilityClassifier; import org.apache.poi.ss.formula.eval.NumberEval; import org.apache.poi.ss.usermodel.Row; import org.apache.poi.ss.usermodel.Sheet; import org.apache.poi.ss.usermodel.Workbook; import org.junit.Rule; import org.junit.Test; import org.junit.rules.ExpectedException; public class TestForkedEvaluator { @Rule public ExpectedException expectedEx = ExpectedException.none(); protected Workbook newWorkbook() { return new HSSFWorkbook(); } /** * set up a calculation workbook with input cells nicely segregated on a * sheet called "Inputs" */ protected Workbook createWorkbook() { Workbook wb = newWorkbook(); Sheet sheet1 = wb.createSheet("Inputs"); Sheet sheet2 = wb.createSheet("Calculations"); Row row; row = sheet2.createRow(0); row.createCell(0).setCellFormula("B1*Inputs!A1-Inputs!B1"); row.createCell(1).setCellValue(5.0); // Calculations!B1 // some default input values row = sheet1.createRow(0); row.createCell(0).setCellValue(2.0); // Inputs!A1 row.createCell(1).setCellValue(3.0); // Inputs!B1 return wb; } /** * Shows a basic use-case for {@link ForkedEvaluator} */ @Test public void testBasic() throws IOException { Workbook wb = createWorkbook(); // The stability classifier is useful to reduce memory consumption of caching logic IStabilityClassifier stabilityClassifier = new IStabilityClassifier() { @Override public boolean isCellFinal(int sheetIndex, int rowIndex, int columnIndex) { return sheetIndex == 1; } }; ForkedEvaluator fe1 = ForkedEvaluator.create(wb, stabilityClassifier, null); ForkedEvaluator fe2 = ForkedEvaluator.create(wb, stabilityClassifier, null); // fe1 and fe2 can be used concurrently on separate threads fe1.updateCell("Inputs", 0, 0, new NumberEval(4.0)); fe1.updateCell("Inputs", 0, 1, new NumberEval(1.1)); fe2.updateCell("Inputs", 0, 0, new NumberEval(1.2)); fe2.updateCell("Inputs", 0, 1, new NumberEval(2.0)); assertEquals(18.9, ((NumberEval) fe1.evaluate("Calculations", 0, 0)).getNumberValue(), 0.0); assertEquals(4.0, ((NumberEval) fe2.evaluate("Calculations", 0, 0)).getNumberValue(), 0.0); fe1.updateCell("Inputs", 0, 0, new NumberEval(3.0)); assertEquals(13.9, ((NumberEval) fe1.evaluate("Calculations", 0, 0)).getNumberValue(), 0.0); wb.close(); } /** * As of Sep 2009, the Forked evaluator can update values from existing cells (this is because * the underlying 'master' cell is used as a key into the calculation cache. Prior to the fix * for this bug, an attempt to update a missing cell would result in NPE. This junit tests for * a more meaningful error message.<br/> * * An alternate solution might involve allowing empty cells to be created as necessary. That * was considered less desirable because so far, the underlying 'master' workbook is strictly * <i>read-only</i> with respect to the ForkedEvaluator. */ @Test public void testMissingInputCellH() throws IOException { expectedEx.expect(UnsupportedOperationException.class); expectedEx.expectMessage("Underlying cell 'A2' is missing in master sheet."); Workbook wb = createWorkbook(); try { ForkedEvaluator fe = ForkedEvaluator.create(wb, null, null); // attempt update input at cell A2 (which is missing) fe.updateCell("Inputs", 1, 0, new NumberEval(4.0)); } finally { wb.close(); } } }
lvweiwolf/poi-3.16
src/testcases/org/apache/poi/ss/formula/eval/forked/TestForkedEvaluator.java
Java
apache-2.0
4,593
/* * Licensed to Julian Hyde under one or more contributor license * agreements. See the NOTICE file distributed with this work for * additional information regarding copyright ownership. Julian Hyde * 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 net.hydromatic.toolbox.checkstyle; import com.puppycrawl.tools.checkstyle.api.AbstractFileSetCheck; import java.io.File; import java.util.List; import java.util.regex.Pattern; /** * Checker that applies some custom checks to each file. */ public class HydromaticFileSetCheck extends AbstractFileSetCheck { private static final Pattern PATTERN1 = Pattern.compile(".*\\\\n\" \\+ .*"); private static final Pattern PATTERN2 = Pattern.compile("^\\{@link .*\\}$"); private static final Pattern PATTERN3 = Pattern.compile(".*@param +[^ ]+ *$"); private static final Pattern PATTERN4 = Pattern.compile(".* href=.*CALCITE-.*"); private static final Pattern PATTERN5 = Pattern.compile( ".*<a href=\"https://issues.apache.org/jira/browse/CALCITE-[0-9]+\">\\[CALCITE-[0-9]+\\].*"); boolean isProto(File file) { return file.getAbsolutePath().contains("/proto/") || file.getName().endsWith("Base64.java"); } static <E> E last(List<E> list) { return list.get(list.size() - 1); } void afterFile(File file, List<String> lines) { if (file.getName().endsWith(".java")) { String b = file.getName().replaceAll(".*/", ""); final String line = "// End " + b; if (!last(lines).equals(line) && !isProto(file)) { log(lines.size(), "Last line should be ''{0}''", line); } } } protected void processFiltered(File file, List<String> list) { boolean off = false; int endCount = 0; int maxLineLength = 80; final String path = file.getAbsolutePath() .replace('\\', '/'); // for windows if (path.contains("/calcite/")) { maxLineLength = 100; } int i = 0; for (String line : list) { ++i; if (line.contains("\t")) { log(i, "Tab"); } if (line.contains("CHECKSTYLE: ON")) { off = false; } if (line.contains("CHECKSTYLE: OFF")) { off = true; } if (off) { continue; } if (line.startsWith("// End ")) { if (endCount++ > 0) { log(i, "End seen more than once"); } } if (isMatches(PATTERN1, line)) { log(i, "Newline in string should be at end of line"); } if (line.contains("{@link")) { if (!line.contains("}")) { log(i, "Split @link"); } } if (line.endsWith("@Override")) { log(i, "@Override should not be on its own line"); } if (line.endsWith("<p>") && !isProto(file)) { log(i, "Orphan <p>. Make it the first line of a paragraph"); } if (line.contains("@") && !line.contains("@see") && line.length() > maxLineLength) { String s = line .replaceAll("^ *\\* *", "") .replaceAll(" \\*/$", "") .replaceAll("[;.,]$", "") .replaceAll("<li>", ""); if (!isMatches(PATTERN2, s) && !file.getName().endsWith("CalciteResource.java")) { log(i, "Javadoc line too long ({0} chars)", line.length()); } } if (isMatches(PATTERN3, line)) { log(i, "Parameter with no description"); } if (isMatches(PATTERN4, line) && !isMatches(PATTERN5, line)) { log(i, "Bad JIRA reference"); } if (file.getName().endsWith(".java") && (line.contains("(") || line.contains(")"))) { String s = deString(line); int o = 0; for (int j = 0; j < s.length(); j++) { char c = s.charAt(j); if (c == '(' && j > 0 && Character.isJavaIdentifierPart(s.charAt(j - 1))) { ++o; } else if (c == ')') { --o; } } if (o > 1) { log(i, "Open parentheses exceed closes by 2 or more"); } } } afterFile(file, list); } private boolean isMatches(Pattern pattern, String line) { return pattern.matcher(line).matches(); } static String deString(String line) { if (!line.contains("\"")) { return line; } final StringBuilder b = new StringBuilder(); int i = 0; outer: for (;;) { int j = line.indexOf('"', i); if (j < 0) { b.append(line, i, line.length()); return b.toString(); } b.append(line, i, j); for (int k = j + 1;;) { if (k >= line.length()) { b.append("string"); i = line.length(); continue outer; } char c = line.charAt(k++); switch (c) { case '\\': k++; break; case '"': b.append("string"); i = k; continue outer; } } } } public void fireErrors2(File fileName) { fireErrors(fileName.getAbsolutePath()); } } // End HydromaticFileSetCheck.java
julianhyde/toolbox
src/main/java/net/hydromatic/toolbox/checkstyle/HydromaticFileSetCheck.java
Java
apache-2.0
5,585
/** * 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.brixcms.web.tree; import org.apache.wicket.model.IDetachable; import java.io.Serializable; import java.util.List; public interface TreeNode extends IDetachable, Serializable { // -------------------------- OTHER METHODS -------------------------- public List<? extends TreeNode> getChildren(); public boolean isLeaf(); }
kbachl/brix-cms-backup
brix-core/src/main/java/org/brixcms/web/tree/TreeNode.java
Java
apache-2.0
910
package org.sistemafinanciero.rest; import java.math.BigInteger; 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.QueryParam; import javax.ws.rs.core.Response; import org.sistemafinanciero.entity.Agencia; @Path("/agencias") public interface AgenciaREST { @GET @Produces({ "application/xml", "application/json" }) public Response findAll(@QueryParam("estado") Boolean estado); @GET @Path("/{id}") @Produces({ "application/xml", "application/json" }) public Response findById(@PathParam("id") BigInteger id); @POST @Produces({ "application/xml", "application/json" }) public Response create(Agencia agencia); @PUT @Path("/{id}") @Produces({ "application/xml", "application/json" }) public Response update(@PathParam("id") BigInteger id, Agencia agencia); @GET @Path("/{id}/bovedas") @Produces({ "application/json" }) public Response getBovedasOfAgencia(@PathParam("id") BigInteger id); @GET @Path("/{id}/cajas") @Produces({ "application/json" }) public Response getCajasOfAgencia(@PathParam("id") BigInteger id); @GET @Path("/{id}/giros/enviados") @Produces({ "application/json" }) public Response getGirosEnviados(@PathParam("id") BigInteger id, @QueryParam("estado") String estadoGiro, @QueryParam("filterText") String filterText, @QueryParam("offset") Integer offset, @QueryParam("limit") Integer limit); @GET @Path("/{id}/giros/recibidos") @Produces({ "application/json" }) public Response getGirosRecibidos(@PathParam("id") BigInteger id, @QueryParam("estado") String estadoGiro, @QueryParam("filterText") String filterText, @QueryParam("offset") Integer offset, @QueryParam("limit") Integer limit); @GET @Path("/{id}/giros/enviados/count") @Produces({ "application/xml", "application/json" }) public Response countGirosEnviados(@PathParam("id") BigInteger id); @GET @Path("/{id}/giros/recibidos/count") @Produces({ "application/xml", "application/json" }) public Response countGirosRecibidos(@PathParam("id") BigInteger id); }
Softgreen/SISTCOOP_REST
src/main/java/org/sistemafinanciero/rest/AgenciaREST.java
Java
apache-2.0
2,273
package com.bytegriffin.get4j.ha; import java.util.Map; import org.apache.curator.framework.CuratorFramework; import org.apache.curator.framework.recipes.leader.LeaderSelector; import org.apache.curator.framework.recipes.leader.LeaderSelectorListenerAdapter; import org.apache.curator.shaded.com.google.common.collect.Maps; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import com.bytegriffin.get4j.probe.ProbeMasterChecker; import com.bytegriffin.get4j.util.NetHelper; import com.bytegriffin.get4j.util.Sleep; /** * ProbeMaster选举策略:采用Active-Standby模式<br> * 当在Probe模式下抓取同一个seed时,集群中只允许出现一个节点是Probe Master(Active),<br> * 其他Probe节点处于Standby。最先启动的Probe机器来充当Master,<br> * 一旦Probe Master退出或宕机,程序将自动在当前同一个seed集群<br> * 中选举新的Probe充当Master。注意:集群模式下需要每个节点配置probe选项。<br> * Interval:集群中只需一个节点配置即可。<br> * Probe:集群中所有机器都要配置。 */ public final class ProbeMasterElection extends LeaderSelectorListenerAdapter implements ProbeMasterChecker { private static final Logger logger = LogManager.getLogger(ProbeMasterElection.class); private static final ProbeMasterElection me = new ProbeMasterElection(); private static final String zk_probe_path_prefix = "/probe/"; private LeaderSelector leaderSelector; private String seedName; private static Map<String, ProbeMasterElection> probe_master_map = Maps.newHashMap(); private static Map<String, LeaderSelector> leader_selector_map = Maps.newHashMap(); private ProbeMasterElection(){ } public static ProbeMasterElection single(){ return me; } static ProbeMasterElection create(CuratorFramework client, String seedName){ ProbeMasterElection pms = new ProbeMasterElection(client, seedName); probe_master_map.put(seedName, pms); return pms; } static boolean checkMaster(String seedName){ ProbeMasterElection pms = probe_master_map.get(seedName); if(pms == null){ return false; } return pms.isActive(seedName); } /** * 设置选举 * @param client * @param seedName */ private ProbeMasterElection(CuratorFramework client, String seedName) { this.seedName = seedName; leaderSelector = new LeaderSelector(client, zk_probe_path_prefix + seedName, this); leaderSelector.autoRequeue(); leaderSelector.start(); leader_selector_map.put(seedName, leaderSelector); } @Override public void takeLeadership(CuratorFramework client) throws Exception { logger.info("种子[{}]集群中将节点[{}]被选举为Probe Master。", seedName, NetHelper.getClusterNodeName()); //循环占用本机充当Master,除非宕机或者退出等情况发生才进行新一轮选举。 while(true) { Sleep.seconds(Integer.MAX_VALUE); } } /** * 判断本机运行状态是否为Probe Master */ @Override public boolean isActive(String seedName) { return leader_selector_map.get(seedName).hasLeadership(); } }
bytegriffin/Get4J
get4j-cluster/src/main/java/com/bytegriffin/get4j/ha/ProbeMasterElection.java
Java
apache-2.0
3,154
/* * Copyright 2012-2017 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with * the License. A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR * CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions * and limitations under the License. */ package com.amazonaws.services.cognitoidp.model.transform; import javax.annotation.Generated; import com.amazonaws.SdkClientException; import com.amazonaws.services.cognitoidp.model.*; import com.amazonaws.protocol.*; import com.amazonaws.annotation.SdkInternalApi; /** * AdminConfirmSignUpRequestMarshaller */ @Generated("com.amazonaws:aws-java-sdk-code-generator") @SdkInternalApi public class AdminConfirmSignUpRequestMarshaller { private static final MarshallingInfo<String> USERPOOLID_BINDING = MarshallingInfo.builder(MarshallingType.STRING) .marshallLocation(MarshallLocation.PAYLOAD).marshallLocationName("UserPoolId").build(); private static final MarshallingInfo<String> USERNAME_BINDING = MarshallingInfo.builder(MarshallingType.STRING).marshallLocation(MarshallLocation.PAYLOAD) .marshallLocationName("Username").build(); private static final AdminConfirmSignUpRequestMarshaller instance = new AdminConfirmSignUpRequestMarshaller(); public static AdminConfirmSignUpRequestMarshaller getInstance() { return instance; } /** * Marshall the given parameter object. */ public void marshall(AdminConfirmSignUpRequest adminConfirmSignUpRequest, ProtocolMarshaller protocolMarshaller) { if (adminConfirmSignUpRequest == null) { throw new SdkClientException("Invalid argument passed to marshall(...)"); } try { protocolMarshaller.marshall(adminConfirmSignUpRequest.getUserPoolId(), USERPOOLID_BINDING); protocolMarshaller.marshall(adminConfirmSignUpRequest.getUsername(), USERNAME_BINDING); } catch (Exception e) { throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e); } } }
dagnir/aws-sdk-java
aws-java-sdk-cognitoidp/src/main/java/com/amazonaws/services/cognitoidp/model/transform/AdminConfirmSignUpRequestMarshaller.java
Java
apache-2.0
2,370
package com.fasterxml.jackson.failing; import java.util.concurrent.ConcurrentHashMap; import com.fasterxml.jackson.annotation.*; import com.fasterxml.jackson.databind.*; import com.fasterxml.jackson.databind.annotation.JsonDeserialize; import com.fasterxml.jackson.databind.annotation.JsonPOJOBuilder; public class ObjectIdWithBuilder1496Test extends BaseMapTest { @JsonIdentityInfo(generator=ObjectIdGenerators.PropertyGenerator.class, property="id") @JsonDeserialize(builder=POJOBuilder.class) static class POJO { private long id; public long getId() { return id; } private int var; public int getVar() { return var; } POJO (long id, int var) { this.id = id; this.var = var; } @Override public String toString() { return "id: " + id + ", var: " + var; } } @JsonIdentityInfo(generator=ObjectIdGenerators.PropertyGenerator.class, property="id") @JsonPOJOBuilder(withPrefix = "", buildMethodName="readFromCacheOrBuild") static final class POJOBuilder { // Standard builder stuff private long id; private int var; public POJOBuilder id(long _id) { id = _id; return this; } public POJOBuilder var(int _var) { var = _var; return this; } public POJO build() { return new POJO(id, var); } // Special build method for jackson deserializer that caches objects already deserialized private final static ConcurrentHashMap<Long, POJO> cache = new ConcurrentHashMap<>(); public POJO readFromCacheOrBuild() { POJO pojo = cache.get(id); if (pojo == null) { POJO newPojo = build(); pojo = cache.putIfAbsent(id, newPojo); if (pojo == null) { pojo = newPojo; } } return pojo; } } /* /********************************************************** /* Test methods /********************************************************** */ private final ObjectMapper MAPPER = newJsonMapper(); public void testBuilderId1496() throws Exception { POJO input = new POJOBuilder().id(123L).var(456).build(); String json = MAPPER.writeValueAsString(input); POJO result = MAPPER.readValue(json, POJO.class); assertNotNull(result); } }
FasterXML/jackson-databind
src/test/java/com/fasterxml/jackson/failing/ObjectIdWithBuilder1496Test.java
Java
apache-2.0
2,406
package de.frosner.datagenerator.gui.verifiers; import static org.fest.assertions.Assertions.assertThat; import static org.fest.swing.edt.GuiActionRunner.execute; import static org.mockito.Mockito.when; import static org.mockito.MockitoAnnotations.initMocks; import javax.swing.JComponent; import javax.swing.JTextField; import org.fest.swing.edt.FailOnThreadViolationRepaintManager; import org.fest.swing.edt.GuiQuery; import org.fest.swing.edt.GuiTask; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; import org.junit.experimental.categories.Category; import org.mockito.Mock; import de.frosner.datagenerator.testutils.SwingTests; @Category(SwingTests.class) public class InputVerifierTest { private JComponent _component; @Mock private InputVerifier _verifier; @BeforeClass public static void setUpOnce() { FailOnThreadViolationRepaintManager.install(); } @Before public void initTextField() { _component = execute(new GuiQuery<JComponent>() { @SuppressWarnings("serial") @Override public JComponent executeInEDT() { return new JTextField() { }; } }); } @Before public void initMockedVerifier() { initMocks(this); } @Test public void testVerifyComponent_boolean() { execute(new GuiTask() { @Override public void executeInEDT() { assertThat(_component.getBackground()).isEqualTo(InputVerifier.VALID_INPUT_WHITE); InputVerifier.verifyComponent(_component, false); assertThat(_component.getBackground()).isEqualTo(InputVerifier.INVALID_INPUT_RED); InputVerifier.verifyComponent(_component, true); assertThat(_component.getBackground()).isEqualTo(InputVerifier.VALID_INPUT_WHITE); } }); } @Test public void testVerifyComponent_verifier() { execute(new GuiTask() { @Override public void executeInEDT() { assertThat(_component.getBackground()).isEqualTo(InputVerifier.VALID_INPUT_WHITE); when(_verifier.verify()).thenReturn(false); InputVerifier.verifyComponent(_component, _verifier); assertThat(_component.getBackground()).isEqualTo(InputVerifier.INVALID_INPUT_RED); when(_verifier.verify()).thenReturn(true); InputVerifier.verifyComponent(_component, _verifier); assertThat(_component.getBackground()).isEqualTo(InputVerifier.VALID_INPUT_WHITE); } }); } }
FRosner/DataGenerator
src/test/java/de/frosner/datagenerator/gui/verifiers/InputVerifierTest.java
Java
apache-2.0
2,319
package com.goodgame.profiling.graphite_bifroest.systems.prefixtree; import java.util.ArrayDeque; import java.util.ArrayList; import java.util.Deque; import java.util.Iterator; import java.util.LinkedList; import java.util.List; import java.util.Map.Entry; import java.util.Queue; import java.util.concurrent.atomic.AtomicLong; import java.util.function.BiConsumer; import java.util.regex.Matcher; import java.util.regex.Pattern; import java.util.stream.Collectors; import org.apache.commons.lang3.StringUtils; import org.apache.commons.lang3.tuple.ImmutablePair; import org.apache.commons.lang3.tuple.Pair; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.json.JSONException; import org.json.JSONObject; import com.goodgame.profiling.commons.statistics.eventbus.EventBusManager; import com.goodgame.profiling.graphite_bifroest.systems.rebuilder.statistics.NewMetricInsertedEvent; import com.google.common.collect.Lists; public final class PrefixTree { private static final Logger log = LogManager.getLogger(); private static final Pattern replaceBracesPattern = Pattern.compile( "\\{([^}]+?)\\}" ); private final ObjectTrie<String, Long> trie = new ObjectTrie<>(); private static Queue<String> stringToKey( String string ) { Queue<String> queue = new LinkedList<>(); if ( !string.isEmpty() ) { String[] array = string.split( "\\." ); for ( int i = 0; i < array.length; i++ ) { queue.add( array[i] ); } } return queue; } public void addEntry( String metricName ) { trie.add( stringToKey( metricName ), System.currentTimeMillis() / 1000 ); } public void addEntry( String metricName, long timestamp ) { trie.add( stringToKey( metricName ), timestamp ); } public long findAge( final String prefix, final List<String> blacklist ) { log.entry( prefix, blacklist ); String regex = blacklist.stream() .map( s -> StringUtils.replace( s, ".", "\\." ) ) .collect( Collectors.joining( ")|(", "(^|\\.)(", ")($|\\.)" ) ); log.debug( "Regex: {}", regex ); final Pattern p = Pattern.compile( regex ); // Misuse AtomicLong as a LongHolder AtomicLong l = new AtomicLong( Long.MAX_VALUE ); forAllLeaves( (metric, age) -> { if ( !blacklist.isEmpty() && p.matcher(metric).find() ) { log.debug( "{} is blacklisted.", metric ); } else { if ( age < l.get() ) { l.set( age ); } } }, prefix ); return log.exit( l.get() ); } @Deprecated public Iterable<String> collectLeaves() { return new Iterable<String>() { @Override public Iterator<String> iterator() { return new Iterator<String>() { Iterator<Queue<String>> iter = trie.collectKeys().iterator(); @Override public boolean hasNext() { return iter.hasNext(); } @Override public String next() { return StringUtils.join( iter.next(), '.' ); } @Override public void remove() { iter.remove(); } }; } }; } public List<Pair<String, Boolean>> getPrefixesMatching( String query ) { String[] queryParts = StringUtils.splitPreserveAllTokens( query, '.' ); Pattern[] queryPartPatterns = new Pattern[queryParts.length]; List<Pair<String, Boolean>> results = new ArrayList<>(); for ( int i = 0; i < queryParts.length; i++ ) { String queryPart = queryParts[i]; queryPart = StringUtils.replace( queryPart, "*", ".*" ); queryPart = replaceBraces( queryPart ); queryPart = "^" + queryPart + "$"; queryPartPatterns[i] = Pattern.compile( queryPart ); } collectNodes( trie, 0, queryPartPatterns, new String[queryParts.length], results ); return results; } private void collectNodes( ObjectTrie<String, Long> node, int depth, Pattern[] queryPartPatterns, String[] matchedPatterns, List<Pair<String, Boolean>> results ) { if ( depth == queryPartPatterns.length ) { results.add( new ImmutablePair<String, Boolean>( StringUtils.join( matchedPatterns, ".", 0, depth ), node.isLeaf() ) ); return; } for ( Entry<String, ObjectTrie<String, Long>> entry : node.children() ) { if ( queryPartPatterns[depth].matcher( entry.getKey() ).find() ) { matchedPatterns[depth] = entry.getKey(); collectNodes( entry.getValue(), depth + 1, queryPartPatterns, matchedPatterns, results ); } } } private static String replaceBraces( String input ) { StringBuffer result = new StringBuffer(); Matcher m = replaceBracesPattern.matcher( input ); while ( m.find() ) { StringBuilder replacement = new StringBuilder(); replacement.append( '(' ); replacement.append( m.group( 1 ).replace( ',', '|' ) ); replacement.append( ')' ); m.appendReplacement( result, replacement.toString() ); } m.appendTail( result ); return result.toString(); } @Deprecated public static JSONObject toJSONObject( PrefixTree tree, String prefix ) { ObjectTrie<String, Long> subTrie = tree.trie.get( stringToKey( prefix ) ); if ( subTrie == null ) { // Empty tree, if prefix not found return new JSONObject(); } else { return toJSONObject( subTrie ); } } @Deprecated public static JSONObject toJSONObject( PrefixTree tree ) { return toJSONObject( tree.trie ); } @Deprecated private static JSONObject toJSONObject( ObjectTrie<String, Long> trie ) { JSONObject result = new JSONObject(); if ( trie.isLeaf() && trie.value() != null ) { result.put( "age", trie.value() ); } else { for ( Entry<String, ObjectTrie<String, Long>> entry : trie.children() ) { result.put( entry.getKey(), toJSONObject( entry.getValue() ) ); } } return result; } private static void forAllLeaves( BiConsumer<String, Long> consumer, ObjectTrie<String, Long> trie ) { trie.forAllLeaves( ( keyparts, value ) -> consumer.accept( keyparts.stream().collect( Collectors.joining(".") ), value ) ); } public void forAllLeaves( BiConsumer<String, Long> consumer ) { forAllLeaves( consumer, trie ); } public void forAllLeaves( BiConsumer<String, Long> consumer, String prefix ) { ObjectTrie<String, Long> subTrie = trie.get( stringToKey( prefix ) ); if ( subTrie != null ) { forAllLeaves( consumer, subTrie ); } } public static PrefixTree fromJSONObject( JSONObject json ) { return fromJSONObject( new PrefixTree(), new ArrayDeque<String>(), json ); } private static PrefixTree fromJSONObject( PrefixTree result, Deque<String> stack, JSONObject json ) { try { // Should only ever work if we are a leaf long age = json.getLong( "age" ); List<String> metricParts = new ArrayList<>( stack ); // Our stack holds the elements in reverse order Lists.reverse( metricParts ); result.trie.add( new ArrayDeque<>( metricParts ), age ); EventBusManager.fire( new NewMetricInsertedEvent() ); } catch ( JSONException e ) { if ( JSONObject.getNames( json ) == null ) { return result; } // Apparently, this is not a leaf for ( String name : JSONObject.getNames( json ) ) { stack.push( name ); result = fromJSONObject( result, stack, json.getJSONObject( name ) ); stack.pop(); } } return result; } }
Tetha/bifroest
bifroest/src/main/java/com/goodgame/profiling/graphite_bifroest/systems/prefixtree/PrefixTree.java
Java
apache-2.0
8,380
package com.sky.hsf1002.designpattern.State; /** * Created by hsf1002 on 2017/9/23. */ public class SleepingState extends State{ @Override public void writeProgramme(Work work) { System.out.println("sleeping: " + work.getHour() + ", having a dream."); } }
LoveGoogleLoveAndroid/design-pattern
app/src/main/java/com/sky/hsf1002/designpattern/State/SleepingState.java
Java
apache-2.0
279
/* * Data.java February 2014 * * Copyright (C) 2014, Niall Gallagher <[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 org.simpleframework.http.socket; /** * The <code>Data</code> interface represents a payload for a WebScoket * frame. It can hold either binary data or text data. For performance * binary frames are a better choice as all text frames need to be * encoded as UTF-8 from the native UCS2 format. * * @author Niall Gallagher * * @see org.simpleframework.http.socket.DataFrame */ public interface Data { /** * This returns the binary payload that is to be sent with a frame. * It contains no headers or other meta data. If the original data * was text this converts it to UTF-8. * * @return the binary payload to be sent with the frame */ byte[] getBinary(); /** * This returns the text payload that is to be sent with a frame. * It contains no header information or meta data. Caution should * be used with this method as binary payloads will encode to * garbage when decoded as UTF-8. * * @return the text payload to be sent with the frame */ String getText(); }
ggeorg/chillverse
simple-http/src/main/java/org/simpleframework/http/socket/Data.java
Java
apache-2.0
1,715
package com.alexvasilkov.events; import android.support.test.annotation.UiThreadTest; import com.alexvasilkov.events.Events.Background; import com.alexvasilkov.events.Events.Cache; import com.alexvasilkov.events.Events.Failure; import com.alexvasilkov.events.Events.Result; import com.alexvasilkov.events.Events.Status; import com.alexvasilkov.events.Events.Subscribe; import com.alexvasilkov.events.cache.MemoryCache; import org.junit.Test; /** * Tests valid and invalid subscription annotations combinations. */ public class AnnotationsTest extends AbstractTest { // ---------------------------------- // Valid annotations and combinations // ---------------------------------- @Test @UiThreadTest public void can_Subscribe() { registerAndUnregister(new Object() { @Subscribe(TASK_KEY) private void exec() {} }); } @Test @UiThreadTest public void can_Subscribe_Background() { registerAndUnregister(TargetSubscribeAndBackground.class); } @Test @UiThreadTest public void can_Subscribe_Cache() { registerAndUnregister(new Object() { @Cache(MemoryCache.class) @Subscribe(TASK_KEY) private void exec() {} }); } @Test @UiThreadTest public void can_Status() { registerAndUnregister(new Object() { @Status(TASK_KEY) private void exec(EventStatus status) {} }); } @Test @UiThreadTest public void can_Result() { registerAndUnregister(new Object() { @Result(TASK_KEY) private void exec() {} }); } @Test @UiThreadTest public void can_Failure() { registerAndUnregister(new Object() { @Failure(TASK_KEY) private void exec() {} }); } // ---------------------------------- // Invalid annotations // ---------------------------------- @Test(expected = EventsException.class) @UiThreadTest public void cannot_Background() { registerAndUnregister(new Object() { @Background private void exec() {} }); } @Test(expected = EventsException.class) @UiThreadTest public void cannot_Cache() { registerAndUnregister(new Object() { @Cache(MemoryCache.class) private void exec() {} }); } @Test(expected = EventsException.class) @UiThreadTest public void cannot_Subscribe_Background_NonStatic() { registerAndUnregister(new Object() { @Background @Subscribe(TASK_KEY) private void exec() {} }); } // ---------------------------------- // Invalid annotations for @Subscribe // ---------------------------------- @Test(expected = EventsException.class) @UiThreadTest public void cannot_Subscribe_Status() { registerAndUnregister(new Object() { @Subscribe(TASK_KEY) @Status(TASK_KEY) private void exec() {} }); } @Test(expected = EventsException.class) @UiThreadTest public void cannot_Subscribe_Result() { registerAndUnregister(new Object() { @Subscribe(TASK_KEY) @Result(TASK_KEY) private void exec() {} }); } @Test(expected = EventsException.class) @UiThreadTest public void cannot_Subscribe_Failure() { registerAndUnregister(new Object() { @Subscribe(TASK_KEY) @Failure(TASK_KEY) private void exec() {} }); } // ---------------------------------- // Invalid annotations for @Status // ---------------------------------- @Test(expected = EventsException.class) @UiThreadTest public void cannot_Status_Subscribe() { registerAndUnregister(new Object() { @Status(TASK_KEY) @Subscribe(TASK_KEY) private void exec(EventStatus status) {} }); } @Test(expected = EventsException.class) @UiThreadTest public void cannot_Status_Background() { registerAndUnregister(new Object() { @Status(TASK_KEY) @Background private void exec(EventStatus status) {} }); } @Test(expected = EventsException.class) @UiThreadTest public void cannot_Status_Cache() { registerAndUnregister(new Object() { @Status(TASK_KEY) @Cache(MemoryCache.class) private void exec(EventStatus status) {} }); } @Test(expected = EventsException.class) @UiThreadTest public void cannot_Status_Result() { registerAndUnregister(new Object() { @Status(TASK_KEY) @Result(TASK_KEY) private void exec(EventStatus status) {} }); } @Test(expected = EventsException.class) @UiThreadTest public void cannot_Status_Failure() { registerAndUnregister(new Object() { @Status(TASK_KEY) @Failure(TASK_KEY) private void exec(EventStatus status) {} }); } // ---------------------------------- // Invalid annotations for @Result // ---------------------------------- @Test(expected = EventsException.class) @UiThreadTest public void cannot_Result_Subscribe() { registerAndUnregister(new Object() { @Result(TASK_KEY) @Subscribe(TASK_KEY) private void exec() {} }); } @Test(expected = EventsException.class) @UiThreadTest public void cannot_Result_Background() { registerAndUnregister(new Object() { @Result(TASK_KEY) @Background private void exec() {} }); } @Test(expected = EventsException.class) @UiThreadTest public void cannot_Result_Cache() { registerAndUnregister(new Object() { @Result(TASK_KEY) @Cache(MemoryCache.class) private void exec() {} }); } @Test(expected = EventsException.class) @UiThreadTest public void cannot_Result_Status() { registerAndUnregister(new Object() { @Result(TASK_KEY) @Status(TASK_KEY) private void exec() {} }); } @Test(expected = EventsException.class) @UiThreadTest public void cannot_Result_Failure() { registerAndUnregister(new Object() { @Result(TASK_KEY) @Failure(TASK_KEY) private void exec() {} }); } // ---------------------------------- // Invalid annotations for @Failure // ---------------------------------- @Test(expected = EventsException.class) @UiThreadTest public void cannot_Failure_Subscribe() { registerAndUnregister(new Object() { @Failure(TASK_KEY) @Subscribe(TASK_KEY) private void exec() {} }); } @Test(expected = EventsException.class) @UiThreadTest public void cannot_Failure_Background() { registerAndUnregister(new Object() { @Failure(TASK_KEY) @Background private void exec() {} }); } @Test(expected = EventsException.class) @UiThreadTest public void cannot_Failure_Cache() { registerAndUnregister(new Object() { @Failure(TASK_KEY) @Cache(MemoryCache.class) private void exec() {} }); } @Test(expected = EventsException.class) @UiThreadTest public void cannot_Failure_Status() { registerAndUnregister(new Object() { @Failure(TASK_KEY) @Status(TASK_KEY) private void exec() {} }); } @Test(expected = EventsException.class) @UiThreadTest public void cannot_Failure_Result() { registerAndUnregister(new Object() { @Failure(TASK_KEY) @Result(TASK_KEY) private void exec() {} }); } // ---------------------------------- // Helper class // ---------------------------------- private static class TargetSubscribeAndBackground { @Background @Subscribe(TASK_KEY) private static void exec() {} } }
alexvasilkov/Events
library/src/androidTest/java/com/alexvasilkov/events/AnnotationsTest.java
Java
apache-2.0
8,341
package dev.jeka.core.api.file; import dev.jeka.core.api.utils.JkUtilsAssert; import dev.jeka.core.api.utils.JkUtilsIO; import dev.jeka.core.api.utils.JkUtilsPath; import java.io.Closeable; import java.io.IOException; import java.io.UncheckedIOException; import java.nio.file.*; import java.nio.file.attribute.BasicFileAttributes; import java.util.Arrays; import java.util.LinkedList; import java.util.List; import java.util.function.Function; import java.util.function.Predicate; import java.util.stream.Collectors; import java.util.stream.Stream; /** * Provides a view on files and sub-folders contained in a given directory or zip file. A * <code>JkPathTree</code> may have some include/exclude filters to include only * or exclude specified files.<br/> * When speaking about files contained in a {@link JkPathTree}, we mean all * files contained in its root directory or sub-directories, matching positively * the filter defined on it. * * @author Jerome Angibaud */ public final class JkPathTree implements Closeable { /** * Creates a {@link JkPathTree} having the specified root directory. */ public static JkPathTree of(Path rootDir) { return JkPathTree.of(rootDir, false); } /** * Creates a {@link JkPathTree} having the specified root directory. */ public static JkPathTree ofZip(Path zipFile) { return JkPathTree.of(zipFile.toAbsolutePath(), true); } private final RootHolder rootHolder; private final JkPathMatcher matcher; private static JkPathTree of(Path rootDir, boolean zip) { return of(rootDir, JkPathMatcher.ACCEPT_ALL, zip); } private static JkPathTree of(Path rootDirOrArchive, JkPathMatcher matcher, boolean zipFile) { final RootHolder rootHolder = zipFile ? RootHolder.ofZip(rootDirOrArchive) : RootHolder.ofDir(rootDirOrArchive); return new JkPathTree(rootHolder, matcher); } private JkPathTree(RootHolder rootHolder, JkPathMatcher matcher) { this.rootHolder = rootHolder; this.matcher = matcher; } /** * Returns the root directory. In case of zip archive it returns a directory entry * within the zip archive. */ public Path getRoot() { return rootHolder.get(); } /** * Returns root directory if this tree is a directory tree and returns a zip file if this * tree has been created from a zip file. */ public Path getRootDirOrZipFile() { return rootHolder.rootFile(); } /** * Returns the filter defined on this {@link JkPathTree}, never <code>null</code>. */ public JkPathMatcher getMatcher() { return matcher; } public boolean hasFilter() { return matcher == JkPathMatcher.ACCEPT_ALL; } /** * Returns true if a matcher has explicitly been defined on this tree. */ public boolean isDefineMatcher() { return this.matcher == JkPathMatcher.ACCEPT_ALL; } // ------------------------------- functional --------------------------------- private Predicate<Path> excludeRootFilter() { return path -> !path.equals(getRoot()); } private Function<Path, Path> relativePathFunction() { return path -> getRoot().relativize(path); } // ------------------------- check exists -------------------------------------- /** * Returns <code>true</code> if the root directory exists. */ public boolean exists() { return rootHolder.exists(); } /** * Creates root directory if not exists. */ public JkPathTree createIfNotExist() { this.rootHolder.createIfNotExist(); return this; } // ----------------------- iterate over files --------------------------------------------------- /** * Returns a path stream of all files of this tree. Returned paths are resolved against this tree root. * This means that if this tree root is absolute then streamed paths are absolute as well. * Note that the root folder is included in the returned stream. * If this method is called for a zip tree instance, then it should be closed or called within * <i>try-with-resources</i> statement in order to avoid resource leaks. */ public Stream<Path> stream(FileVisitOption ...options) { if(!exists()) { return new LinkedList<Path>().stream(); } final JkPathMatcher matcher = JkPathMatcher.of(this.matcher); return JkUtilsPath.walk(getRoot(), options) .filter(path -> matcher.matches(getRoot().relativize(path))) .onClose(() -> rootHolder.closeIfNeeded()); } /** * Same as {@link #getFiles()} but returning paths relative to this tree root. */ public List<Path> getRelativeFiles() { try(Stream<Path> stream = stream()) { return stream.filter(JkPathMatcher.ofNoDirectory().toPredicate()).map(relativePathFunction()).collect(Collectors.toList()); } } /** * Returns list of paths returned by {@link #stream(FileVisitOption...)} but excluding directories from the result. */ public List<Path> getFiles() { try (Stream<Path> stream = stream()) { return stream.filter(JkPathMatcher.ofNoDirectory().toPredicate()).collect(Collectors.toList()); } } // ---------------------- Navigate ----------------------------------------------------------- /** * Creates a {@link JkPathTree} having the specified relative path to this root as getRoot directory. * Note that the returned tree has no filter even if this tree has one. */ public JkPathTree goTo(String relativePath) { final Path path = getRoot().resolve(relativePath).normalize(); if (Files.exists(path) && !Files.isDirectory(path)) { throw new IllegalArgumentException(getRoot() + "/" + relativePath + " is not a directory"); } RootHolder rootHolder = new RootHolder(this.rootHolder.zipFile, path); return new JkPathTree(rootHolder, this.matcher); } /** * Assuming the root folder is relative, this creates an identical {@link JkPathTree} * but having the root as : [specified new root]/[former root] */ public JkPathTree resolvedTo(Path newRoot) { final Path path = newRoot.resolve(getRoot()).normalize(); RootHolder rootHolder = new RootHolder(this.rootHolder.zipFile, path); return new JkPathTree(rootHolder, this.matcher); } /** * Returns path relative to this root of the specified relative path. */ public Path get(String relativePath) { return getRoot().resolve(relativePath); } // ----------------------- Write in ---------------------------------------------------------------- /** * Copies the specified directory and its content at the root of this tree. */ public JkPathTree importDir(Path dirToCopy, CopyOption... copyOptions) { return importTree(JkPathTree.of(dirToCopy), copyOptions); } /** * Copies the content of the specified tree at the root of this one. * Specified dir to copy to might not exists. The structure of the specified tree * is preserved. * Note that the the root of the specified tree is not part of the copied content. */ public JkPathTree importTree(JkPathTree tree, CopyOption... copyOptions) { createIfNotExist(); if (tree.exists()) { tree.stream().filter(excludeRootFilter()).forEach(path -> { Path target = this.getRoot().resolve(tree.getRoot().relativize(path).toString()); if (Files.isDirectory(path)) { JkUtilsPath.createDirectories(target); } else { JkUtilsPath.copy(path, target, copyOptions); } }); } return this; } /** * Copies the specified files at the root of this tree. The copy is not recursive. */ public JkPathTree importFiles(Iterable<Path> files, StandardCopyOption ... copyOptions) { createIfNotExist(); Iterable<Path> paths = JkUtilsPath.disambiguate(files); for (final Path file : paths) { JkUtilsPath.copy(file, getRoot().resolve(file.getFileName()), copyOptions); } return this; } /** * Copies the specified file at the specified path within this tree. */ public JkPathTree importFile(Path src, String targetName, StandardCopyOption ... copyOptions) { createIfNotExist(); Path parentTarget = getRoot().resolve(targetName).getParent(); if (parentTarget != null && !Files.exists(parentTarget)) { JkUtilsPath.createDirectories(parentTarget); } JkUtilsPath.copy(src, getRoot().resolve(targetName), copyOptions); return this; } /** * Deletes each and every files in this tree except the root and files not matching this tree filter. */ public JkPathTree deleteContent() { if (!Files.exists(getRoot())) { return this; } JkUtilsPath.walkFileTree(getRoot(), new SimpleFileVisitor<Path>() { @Override public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) { return visitFile(file); } @Override public FileVisitResult postVisitDirectory(Path dir, IOException exc) { return visitDir(dir); } private FileVisitResult visitFile(Path path) { if (matcher.matches(getRoot().relativize(path))) { JkUtilsPath.deleteFile(path); } return FileVisitResult.CONTINUE; } private FileVisitResult visitDir(Path path) { if (!JkUtilsPath.isSameFile(getRoot(), path) && matcher.matches(getRoot().relativize(path)) && JkUtilsPath.listDirectChildren(path).isEmpty()) { JkUtilsPath.deleteFile(path); } return FileVisitResult.CONTINUE; } }); return this; } /** * Deletes root directory of this tree. */ public JkPathTree deleteRoot() { JkUtilsPath.walkFileTree(getRoot(), new SimpleFileVisitor<Path>() { @Override public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException { return visit(file); } @Override public FileVisitResult postVisitDirectory(Path dir, IOException exc) throws IOException { return visit(dir); } private FileVisitResult visit(Path path) { JkUtilsPath.deleteFile(path); return FileVisitResult.CONTINUE; } }); return this; } // ----------------------- Write out ---------------------------------------------------------------- /** * Zips the content of this tree to the specified destination file. If the specified destination file * already exists, the content of this tree is appended to the existing archive, overriding existing entries within the archive. */ public JkPathTree zipTo(Path destination) { if (destination.getParent() != null) { JkUtilsPath.createDirectories(destination.getParent()); } final Path zipRootEntry = JkUtilsPath.zipRoot(destination); try (Stream<Path> stream = this.stream()) { stream.filter(excludeRootFilter()).forEach(path -> { Path zipEntry = zipRootEntry.resolve(getRoot().relativize(path).toString()); if (!Files.exists(zipEntry) || !Files.isDirectory(zipEntry)) { JkUtilsPath.createDirectories(zipEntry.getParent()); JkUtilsPath.copy(path, zipEntry, StandardCopyOption.REPLACE_EXISTING); } }); zipRootEntry.getFileSystem().close(); } catch (IOException e) { throw new UncheckedIOException(e); } return this; } /** * Copies files contained in this {@link JkPathTree} to the specified directory. */ public int copyTo(Path destinationDir, CopyOption ... copyOptions) { if (!Files.exists(destinationDir)) { JkUtilsPath.createDirectories(destinationDir); } return JkUtilsPath.copyDirContent(getRoot(), destinationDir, matcher, copyOptions); } /** * Copies a single file contained in this {@link JkPathTree} to the specified directory. File name remains the same. * @param sourcePath The relative path of the source file from this tree root. */ public void copyFile(String sourcePath, Path destinationDir, CopyOption ... copyOptions) { if (!Files.exists(destinationDir)) { JkUtilsPath.createDirectories(destinationDir); } Path source = get(sourcePath); Path dest = destinationDir.getFileSystem().getPath(destinationDir.toString() + "/" + source.getFileName()); JkUtilsPath.copy(source, dest, copyOptions); } // ------------------------- Filter ---------------------------------------------- /** * Creates a copy of this {@link JkPathTree} augmented with the specified {@link JkPathMatcher} */ public JkPathTree andMatcher(PathMatcher pathMatcher) { return new JkPathTree(rootHolder, this.matcher.and(pathMatcher)); } /** * Creates a {@link JkPathTree} which is a copy of this {@link JkPathTree} * but the matcher is replaced with the specified one. */ public JkPathTree withMatcher(JkPathMatcher pathMatcher) { return new JkPathTree(rootHolder, pathMatcher); } /** * Creates a copy of this {@link JkPathTree} augmented with the specified pattern matcher. */ public JkPathTree andMatching(boolean positive, String... globPatterns) { return andMatching(positive, Arrays.asList(globPatterns)); } /** * Shorthand to <code>andMatching(true, globPatterns...)</code>. */ public JkPathTree andMatching(String... globPatterns) { return andMatching(true, globPatterns); } /** * Creates a copy of this {@link JkPathTree} augmented with the specified pattern matcher. */ public JkPathTree andMatching(boolean positive, Iterable<String> globPatterns) { return andMatcher(JkPathMatcher.of(positive, this.getRoot().getFileSystem(), globPatterns)); } // ------------------------ Misc --------------------------------------- /** * Returns the file count contained in this {@link JkPathTree} to concurrence to specified max count. * If the effective count is greater than max count, this method returns <code>max count + 1</code>. * This method is designed to stop file traversal as soon as count is greater than max. */ public int count(int max, boolean includeDirectories) { if (!exists()) { return 0; } return JkUtilsPath.childrenCount(getRoot(), max, includeDirectories, this.matcher); } public boolean containFiles() { return count(1, false) > 0; } /** * If the root of this tree is absolute then this method returns this tree. * If the root of this tree is relative then this method returns a tree having a getRoot * resolved from the specified path to this root. */ public JkPathTree resolve(Path path) { return new JkPathTree(rootHolder.resolve(path), this.matcher); } /** * Returns a {@link JkPathTreeSet} containing this tree as its single * element. */ public JkPathTreeSet toSet() { return JkPathTreeSet.of(this); } @Override public String toString() { return this.hasFilter() ? rootHolder + ":" + matcher : rootHolder.toString(); } /** * This method close the underlying file system. It is only significant for zip trees. * @throws IOException */ @Override public void close() { if (this.rootHolder.isZip()) { JkUtilsIO.closeQuietly(rootHolder.get().getFileSystem()); } } private static class RootHolder { final Path zipFile; Path dir; static RootHolder ofZip(Path zipFile) { JkUtilsAssert.argument(zipFile != null, "zip archive file can't be null."); JkUtilsAssert.argument(!Files.exists(zipFile) || !Files.isDirectory(zipFile), "Specified zip file " + zipFile + " can't be a directory"); return new RootHolder(zipFile, null); } static RootHolder ofDir(Path dir) { JkUtilsAssert.argument(dir != null, "Directory rootHolder tree can't be null."); JkUtilsAssert.argument(!Files.exists(dir) || Files.isDirectory(dir), "Specified zip file " + dir + " must be a directory"); return new RootHolder(null, dir); } private RootHolder(Path zipFile, Path root) { this.zipFile = zipFile; this.dir = root; } Path get() { if (isZip() && dir == null) { dir = JkUtilsPath.zipRoot(zipFile); } return dir; } void createIfNotExist() { if (zipFile == null) { if (!Files.exists(dir)) { JkUtilsPath.createDirectories(dir); } } else { if (!Files.exists(zipFile)) { JkUtilsPath.createDirectories(zipFile.getParent()); dir = JkUtilsPath.zipRoot(zipFile); } else if (dir == null) { dir = JkUtilsPath.zipRoot(zipFile); } else if (dir.getFileSystem().isOpen()) { JkUtilsPath.createDirectories(dir); } else { Path zipRoot = JkUtilsPath.zipRoot(zipFile); dir = zipRoot.getFileSystem().getPath(dir.toString()); } } } boolean exists() { if (!isZip()) { return Files.exists(dir); } if (!Files.exists(zipFile)) { return false; } if (dir == null) { return true; // zip rootHolder always exists } if (dir.getFileSystem().isOpen()) { return Files.exists(dir); } Path zipRoot = JkUtilsPath.zipRoot(zipFile); dir = zipRoot.getFileSystem().getPath(dir.toString()); return Files.exists(dir); } boolean isZip() { return zipFile != null; } void closeIfNeeded() { if (isZip() && dir != null) { try { dir.getFileSystem().close(); } catch (IOException e) { throw new UncheckedIOException(e); } } } RootHolder resolve(Path path) { if (isZip()) { return this; } return new RootHolder(null, path.resolve(dir)); } Path rootFile() { if (isZip()) { return this.zipFile; } return this.dir; } @Override public String toString() { return isZip() ? zipFile.toString() : dir.toString(); } } }
jerkar/jerkar
dev.jeka.core/src/main/java/dev/jeka/core/api/file/JkPathTree.java
Java
apache-2.0
19,613
package com.yueny.cropui.controller.web; import javax.servlet.http.HttpServletResponse; import com.yueny.blog.common.BlogConstant; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.CrossOrigin; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.ResponseBody; import com.yueny.blog.bo.model.document.ChartData; import com.yueny.blog.service.manager.ITagChartManagerService; import com.yueny.cropui.controller.BaseController; import com.yueny.rapid.data.resp.pojo.response.JsonNormalResponse; import com.yueny.rapid.lang.exception.DataVerifyAnomalyException; import com.yueny.superclub.util.web.security.contanst.WebAttributes; /** * 报表控制器 * * @author yueny09 <[email protected]> * * @DATE 2016年9月12日 下午8:17:40 * */ @Controller public class ChartsController extends BaseController { @Autowired private ITagChartManagerService tagQueryService; /** * 报表 */ @RequestMapping(value = "/charts/", method = { RequestMethod.GET }) public String articleWritePage(@RequestParam(value = "type", defaultValue = "1") final String type, final HttpServletResponse response) { setModelAttribute(WebAttributes.ACTION, "fks_chart"); return BlogConstant.WEB_PAGE_URI_PREFIX + "charts/fks_chart"; } /** * 报表数据 */ @RequestMapping(value = "/charts/front-end.json", method = { RequestMethod.POST }) @ResponseBody @CrossOrigin // 允许跨域 public JsonNormalResponse<ChartData> chartsFrontEndJson(final HttpServletResponse response) { final JsonNormalResponse<ChartData> res = new JsonNormalResponse<>(); try { // 从session中获取uid final String uid = "yuanyang"; final ChartData chartData = tagQueryService.getChartData(uid); res.setData(chartData); } catch (final DataVerifyAnomalyException e) { res.setCode(e.getErrorCode()); res.setMessage(e.getErrorMsg()); } return res; } }
yueny/cropui
web/src/main/java/com/yueny/cropui/controller/web/ChartsController.java
Java
apache-2.0
2,160
/* * Copyright (C) 2013 Square, 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 retrofit2; import android.os.Build; import android.os.Handler; import android.os.Looper; import java.lang.invoke.MethodHandles.Lookup; import java.lang.reflect.Constructor; import java.lang.reflect.Method; import java.util.List; import java.util.concurrent.Executor; import javax.annotation.Nullable; import static java.util.Arrays.asList; import static java.util.Collections.emptyList; import static java.util.Collections.singletonList; class Platform { private static final Platform PLATFORM = findPlatform(); static Platform get() { return PLATFORM; } private static Platform findPlatform() { try { Class.forName("android.os.Build"); if (Build.VERSION.SDK_INT != 0) { return new Android(); } } catch (ClassNotFoundException ignored) { } return new Platform(true); } private final boolean hasJava8Types; Platform(boolean hasJava8Types) { this.hasJava8Types = hasJava8Types; } @Nullable Executor defaultCallbackExecutor() { return null; } List<? extends CallAdapter.Factory> defaultCallAdapterFactories( @Nullable Executor callbackExecutor) { DefaultCallAdapterFactory executorFactory = new DefaultCallAdapterFactory(callbackExecutor); return hasJava8Types ? asList(CompletableFutureCallAdapterFactory.INSTANCE, executorFactory) : singletonList(executorFactory); } int defaultCallAdapterFactoriesSize() { return hasJava8Types ? 2 : 1; } List<? extends Converter.Factory> defaultConverterFactories() { return hasJava8Types ? singletonList(OptionalConverterFactory.INSTANCE) : emptyList(); } int defaultConverterFactoriesSize() { return hasJava8Types ? 1 : 0; } boolean isDefaultMethod(Method method) { return hasJava8Types && method.isDefault(); } @Nullable Object invokeDefaultMethod(Method method, Class<?> declaringClass, Object object, @Nullable Object... args) throws Throwable { // Because the service interface might not be public, we need to use a MethodHandle lookup // that ignores the visibility of the declaringClass. Constructor<Lookup> constructor = Lookup.class.getDeclaredConstructor(Class.class, int.class); constructor.setAccessible(true); return constructor.newInstance(declaringClass, -1 /* trusted */) .unreflectSpecial(method, declaringClass) .bindTo(object) .invokeWithArguments(args); } static final class Android extends Platform { Android() { super(Build.VERSION.SDK_INT >= 24); } @Override public Executor defaultCallbackExecutor() { return new MainThreadExecutor(); } static class MainThreadExecutor implements Executor { private final Handler handler = new Handler(Looper.getMainLooper()); @Override public void execute(Runnable r) { handler.post(r); } } } }
MaTriXy/retrofit
retrofit/src/main/java/retrofit2/Platform.java
Java
apache-2.0
3,491
/* * Copyright (c) 2010 Preemptive Labs / Andreas Bielk (http://preemptive.se) * * 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 se.preemptive.redis.testing; import se.preemptive.redis.RedisProtocolClient; import se.preemptive.redis.ResponseFuture; import java.util.concurrent.ExecutionException; public class TestProtocolClient { public static void main(String[] args) throws ExecutionException, InterruptedException { RedisProtocolClient c = new RedisProtocolClient(null); c.connect(); ResponseFuture future = c.send("PING"); System.out.println(future.get()); c.disconnect(); } }
wallrat/labs-redis
src/main/java/se/preemptive/redis/testing/TestProtocolClient.java
Java
apache-2.0
1,132
/* * Copyright 2013-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 org.cloudfoundry.client.v3.applications; import com.fasterxml.jackson.databind.annotation.JsonDeserialize; import org.immutables.value.Value; /** * The response payload for the Start Application operation */ @JsonDeserialize @Value.Immutable abstract class _StopApplicationResponse extends Application { }
cloudfoundry/cf-java-client
cloudfoundry-client/src/main/java/org/cloudfoundry/client/v3/applications/_StopApplicationResponse.java
Java
apache-2.0
941
/* * Copyright (c) 2011-2015, Peter Abeles. All Rights Reserved. * * This file is part of BoofCV (http://boofcv.org). * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package boofcv.alg.fiducial; import boofcv.alg.distort.LensDistortionOps; import boofcv.alg.geo.PerspectiveOps; import boofcv.alg.geo.WorldToCameraToPixel; import boofcv.struct.calib.IntrinsicParameters; import boofcv.struct.distort.PointTransform_F64; import georegression.geometry.RotationMatrixGenerator; import georegression.struct.point.Point2D_F64; import georegression.struct.point.Point3D_F64; import georegression.struct.se.Se3_F64; import georegression.struct.shapes.Quadrilateral_F64; import org.ejml.ops.MatrixFeatures; import org.junit.Test; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; /** * @author Peter Abeles */ public class TestQuadPoseEstimator { @Test public void basicTest() { IntrinsicParameters intrinsic = new IntrinsicParameters(500,550,0,400,300,800,600).fsetRadial(0.15,0.05); Se3_F64 expectedW2C = new Se3_F64(); expectedW2C.T.set(0.1,-0.05,4); RotationMatrixGenerator.eulerXYZ(0.03,0,0,expectedW2C.R); Quadrilateral_F64 quadPlane = new Quadrilateral_F64(-0.5,0.5,0.5,0.5,0.5,-0.5,-0.5,-0.5); Quadrilateral_F64 quadViewed = new Quadrilateral_F64(); WorldToCameraToPixel worldToPixel = PerspectiveOps.createWorldToPixel(intrinsic,expectedW2C); project(worldToPixel, quadPlane.a, quadViewed.a); project(worldToPixel, quadPlane.b, quadViewed.b); project(worldToPixel, quadPlane.c, quadViewed.c); project(worldToPixel, quadPlane.d, quadViewed.d); QuadPoseEstimator alg = new QuadPoseEstimator(1e-8,200); alg.setFiducial(-0.5,0.5,0.5,0.5,0.5,-0.5,-0.5,-0.5); alg.setIntrinsic(intrinsic); assertTrue(alg.process(quadViewed)); Se3_F64 found = alg.getWorldToCamera(); assertTrue(found.T.distance(expectedW2C.T)<1e-6); assertTrue(MatrixFeatures.isIdentical(found.R, expectedW2C.R,1e-6)); } private void project( WorldToCameraToPixel worldToPixel, Point2D_F64 p , Point2D_F64 v ) { worldToPixel.transform(new Point3D_F64(p.x,p.y,0),v); } @Test public void estimateP3P() { IntrinsicParameters intrinsic = new IntrinsicParameters(500,550,0,400,300,800,600); Se3_F64 fiducialToCamera = new Se3_F64(); fiducialToCamera.getT().set(0.2,-0.15,2); RotationMatrixGenerator.eulerXYZ(0.05,0.015,0.001,fiducialToCamera.R); QuadPoseEstimator alg = new QuadPoseEstimator(1e-8,200); alg.setIntrinsic(intrinsic); double r = 1.5; alg.setFiducial(r,-r, r,r, -r,r, -r,-r); WorldToCameraToPixel worldToPixel = PerspectiveOps.createWorldToPixel(intrinsic, fiducialToCamera); alg.listObs.add(worldToPixel.transform(alg.points[0].location)); alg.listObs.add(worldToPixel.transform(alg.points[1].location)); alg.listObs.add(worldToPixel.transform(alg.points[2].location)); alg.listObs.add(worldToPixel.transform(alg.points[3].location)); PointTransform_F64 pixelToNorm = LensDistortionOps.transformPoint(intrinsic).undistort_F64(true, false); for (int i = 0; i < 4; i++) { Point2D_F64 pixel = alg.listObs.get(i); pixelToNorm.compute(pixel.x,pixel.y,alg.points[i].observation); } for (int i = 0; i < 4; i++) { alg.bestError = Double.MAX_VALUE; alg.estimateP3P(i); assertEquals(0,alg.bestError,1e-6); assertTrue(alg.bestPose.T.distance(fiducialToCamera.T)<1e-6); assertTrue(MatrixFeatures.isIdentical(alg.bestPose.R, fiducialToCamera.R,1e-6)); } } @Test public void computeErrors() { IntrinsicParameters intrinsic = new IntrinsicParameters(500,550,0,400,300,800,600); Se3_F64 fiducialToCamera = new Se3_F64(); fiducialToCamera.getT().set(0.2,-0.15,2); RotationMatrixGenerator.eulerXYZ(0.05, 0.015, 0.001, fiducialToCamera.R); QuadPoseEstimator alg = new QuadPoseEstimator(1e-8,200); alg.setIntrinsic(intrinsic); double r = 1.5; alg.setFiducial(r,-r, r,r, -r,r, -r,-r); WorldToCameraToPixel worldToPixel = PerspectiveOps.createWorldToPixel(intrinsic, fiducialToCamera); for (int i = 0; i < 4; i++) { Point3D_F64 X = alg.points[i].location; alg.listObs.add(worldToPixel.transform(X)); } // perfect assertEquals(0,alg.computeErrors(fiducialToCamera),1e-8); // now with known errors for (int i = 0; i < 4; i++) { alg.listObs.get(i).x += 1.5; assertEquals(1.5,alg.computeErrors(fiducialToCamera),1e-8); alg.listObs.get(i).x -= 1.5; } } }
pacozaa/BoofCV
main/recognition/test/boofcv/alg/fiducial/TestQuadPoseEstimator.java
Java
apache-2.0
4,937
package com.cc.library.domain; import java.io.Serializable; public class Authorization implements Serializable{ private Integer aid; //管理员id private Integer sysSet; //系统设置权限 private Integer readerSet; //读者设置权限 private Integer bookSet; //图书设置权限 private Integer typeSet; //图书分类设置权限 private Integer borrowSet; //借阅设置权限 private Integer backSet; //归还设置权限 private Integer forfeitSet; //逾期设置权限 private Integer superSet; //超级管理权限 private Admin admin; public Admin getAdmin() { return admin; } public void setAdmin(Admin admin) { this.admin = admin; } public Integer getForfeitSet() { return forfeitSet; } public void setForfeitSet(Integer forfeitSet) { this.forfeitSet = forfeitSet; } public Integer getAid() { return aid; } public void setAid(Integer aid) { this.aid = aid; } public Integer getSysSet() { return sysSet; } public void setSysSet(Integer sysSet) { this.sysSet = sysSet; } public Integer getReaderSet() { return readerSet; } public void setReaderSet(Integer readerSet) { this.readerSet = readerSet; } public Integer getBookSet() { return bookSet; } public void setBookSet(Integer bookSet) { this.bookSet = bookSet; } public Integer getTypeSet() { return typeSet; } public void setTypeSet(Integer typeSet) { this.typeSet = typeSet; } public Integer getBorrowSet() { return borrowSet; } public void setBorrowSet(Integer borrowSet) { this.borrowSet = borrowSet; } public Integer getBackSet() { return backSet; } public void setBackSet(Integer backSet) { this.backSet = backSet; } public Integer getSuperSet() { return superSet; } public void setSuperSet(Integer superSet) { this.superSet = superSet; } public Authorization() { } }
cckevincyh/LibrarySystem
LibrarySystem/src/com/cc/library/domain/Authorization.java
Java
apache-2.0
1,848
/* * Copyright 2013 Radoslav Husár * * 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.jboss.test.clusterbench.web.jsf; import java.io.Serializable; //import java.util.Map; //import javax.faces.component.UIViewRoot; //import javax.faces.context.FacesContext; //import javax.servlet.http.HttpSession; import org.jboss.test.clusterbench.common.SerialBean; public class JsfManagedBean extends SerialBean implements Serializable { // public SomeBean() { // super(); // HttpSession ses = (HttpSession) FacesContext.getCurrentInstance().getExternalContext().getSession(true); // ses.getId(); // } // // @Override // public int getSerialAndIncrement() { // UIViewRoot viewRoot = FacesContext.getCurrentInstance().getViewRoot(); // Map<String, Object> map = viewRoot.getViewMap(true); // Object o = map.get(this.getClass().getName()); // SerialBean s; // // if (o == null) { // s = new SerialBean(); // } else { // s = (SerialBean) o; // } // // int toret = s.getSerial() + 1; // s.setSerial(toret); // // // Persist // map.put(this.getClass().getName(), s); // // System.out.println("I stored this: " + s.getSerial()); // // // return super.getSerialAndIncrement(); // } }
Ladicek/clusterbench
clusterbench-ee6-web/src/main/java/org/jboss/test/clusterbench/web/jsf/JsfManagedBean.java
Java
apache-2.0
1,840
/* ======================================================================== * PlantUML : a free UML diagram generator * ======================================================================== * * (C) Copyright 2009-2020, Arnaud Roques * * Project Info: https://plantuml.com * * If you like this project or if you find it useful, you can support us at: * * https://plantuml.com/patreon (only 1$ per month!) * https://plantuml.com/paypal * * This file is part of PlantUML. * * 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. * * * Original Author: Arnaud Roques */ package net.sourceforge.plantuml.project.core; import net.sourceforge.plantuml.project.time.Day; public class MomentImpl implements Moment { private final Day start; private final Day end; public MomentImpl(Day start, Day end) { this.start = start; this.end = end; } public Day getStart() { return start; } public Day getEnd() { return end; } }
talsma-ict/umldoclet
src/plantuml-asl/src/net/sourceforge/plantuml/project/core/MomentImpl.java
Java
apache-2.0
1,458
package com.testfabrik.webmate.javasdk.browsersession; import com.testfabrik.webmate.javasdk.Browser; import java.net.URI; import java.util.List; /** * Helpers for creating Expedition specifications. */ public class ExpeditionSpecFactory { /** * Create a live expedition spec that visits a list of URLs in the given browser. */ public static ExpeditionSpec makeUrlListExpeditionSpec(List<URI> urls, Browser browser) { return new LiveExpeditionSpec(new URLListDriverSpecification(urls), new BrowserSpecification(browser)); } }
webmate-io/webmate-sdk-java
src/main/java/com/testfabrik/webmate/javasdk/browsersession/ExpeditionSpecFactory.java
Java
apache-2.0
562
/* * Copyright (C) 2014 The Calrissian Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.calrissian.flowmix.core.support.window; import java.util.Comparator; import java.util.concurrent.LinkedBlockingDeque; import org.calrissian.flowmix.core.support.deque.LimitingDeque; import org.calrissian.flowmix.core.support.deque.LimitingPriorityDeque; import org.calrissian.flowmix.core.support.deque.PriorityBlockingDeque; import static java.util.Arrays.asList; import static java.util.Arrays.sort; public class SortedWindow extends Window { private Comparator<WindowItem> comparator; private boolean sortOnGet = false; public SortedWindow(String groupedIndex, Comparator<WindowItem> comparator, long size, boolean sortOnGet) { this.groupedIndex = groupedIndex; this.sortOnGet = sortOnGet; if(!sortOnGet) events = new LimitingPriorityDeque<WindowItem>(size, comparator); // WARNING else events = new LimitingDeque<WindowItem>(size); this.comparator = comparator; } /** * Used for count-based expiration */ public WindowItem expire() { return events.removeLast(); } public SortedWindow(String groupedIndex, Comparator<WindowItem> comparator, boolean sortOnGet) { this.groupedIndex = groupedIndex; this.sortOnGet = sortOnGet; if(!sortOnGet) events = new PriorityBlockingDeque<WindowItem>(comparator); else events = new LinkedBlockingDeque<WindowItem>(); this.comparator = comparator; } /** * Returns a sorted view of the events */ @Override public Iterable<WindowItem> getEvents() { if(sortOnGet) { WindowItem[] items = events.toArray(new WindowItem[]{}); sort(items, comparator); return asList(items); } else { return super.getEvents(); } } }
calrissian/flowmix
src/main/java/org/calrissian/flowmix/core/support/window/SortedWindow.java
Java
apache-2.0
2,319
/* * Copyright 2016 Karl Bennett * * 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 shiver.me.timbers.retrying.execution; import org.springframework.stereotype.Component; @Component public class RetryerAddIncludeMethodComponent extends RetryerAddIncludeMethod { }
shiver-me-timbers/smt-retrying-parent
smt-retrying-test/smt-retrying-aspect-integration/smt-retrying-aspect-test-components/src/main/java/shiver/me/timbers/retrying/execution/RetryerAddIncludeMethodComponent.java
Java
apache-2.0
787
/** * OLAT - Online Learning and Training<br> * http://www.olat.org * <p> * Licensed under the Apache License, Version 2.0 (the "License"); <br> * you may not use this file except in compliance with the License.<br> * 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,<br> * software distributed under the License is distributed on an "AS IS" BASIS, <br> * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. <br> * See the License for the specific language governing permissions and <br> * limitations under the License. * <p> * Copyright (c) 1999-2006 at Multimedia- & E-Learning Services (MELS),<br> * University of Zurich, Switzerland. * <p> */ package org.olat.data.commons.vfs; import java.util.List; import org.olat.data.commons.vfs.callbacks.VFSSecurityCallback; import org.olat.data.commons.vfs.filters.VFSItemFilter; /** * Description:<br> * TODO: Felix Jost Class Description for VirtualContainerImpl * <P> * Initial Date: 23.06.2005 <br> * * @author Felix Jost */ public class NamedContainerImpl extends AbstractVirtualContainer { final VFSContainer delegate; /** * @param name * @param delegate */ public NamedContainerImpl(String name, VFSContainer delegate) { super(name); this.delegate = delegate; } public VFSContainer getDelegate() { return delegate; } /** */ @Override public VFSContainer getParentContainer() { return delegate.getParentContainer(); } /** */ @Override public void setParentContainer(VFSContainer parentContainer) { delegate.setParentContainer(parentContainer); } /** */ @Override public List getItems() { // FIXME:fj:b add as listener to "change ownergroup" event, so that the access may be denied, if ownergroup of repoitem has changed. return delegate.getItems(); } /** */ @Override public List getItems(VFSItemFilter filter) { return delegate.getItems(filter); } /** */ @Override public VFSStatus copyFrom(VFSItem source) { return delegate.copyFrom(source); } /** */ @Override public VFSStatus canWrite() { return delegate.canWrite(); } /** */ @Override public VFSStatus canCopy() { return delegate.canCopy(); } /** */ @Override public VFSStatus rename(String newname) { throw new RuntimeException("unsupported"); } /** */ @Override public VFSStatus delete() { return delegate.delete(); } /** */ @Override public long getLastModified() { return delegate.getLastModified(); } /** * Be aware that this method can return tricky values: * <ul> * <li>If the path is '/', the named container itself is returned</li> * <li>for child elements, the item of the delegate object is returned</li> * </ul> * In the second case, the returned item does not know anymore that it was embedded in a named container. Thus, the isSame() method on the root element of the * resolved item is not the same as this object. */ @Override public VFSItem resolve(String path) { path = VFSManager.sanitizePath(path); if (path.equals("/")) return this; return delegate.resolve(path); } /** */ @Override public VFSContainer createChildContainer(String name) { return delegate.createChildContainer(name); } /** */ @Override public VFSLeaf createChildLeaf(String name) { return delegate.createChildLeaf(name); } /** */ @Override public String toString() { return "NamedContainer " + getName() + "-> " + delegate.toString(); } /** */ @Override public VFSSecurityCallback getLocalSecurityCallback() { return delegate.getLocalSecurityCallback(); } /** */ @Override public void setLocalSecurityCallback(VFSSecurityCallback secCallback) { delegate.setLocalSecurityCallback(secCallback); } /** */ @Override public boolean isSame(VFSItem vfsItem) { return delegate.isSame(vfsItem); } /** */ @Override public void setDefaultItemFilter(VFSItemFilter defaultFilter) { delegate.setDefaultItemFilter(defaultFilter); } /** */ @Override public VFSItemFilter getDefaultItemFilter() { return delegate.getDefaultItemFilter(); } }
huihoo/olat
OLAT-LMS/src/main/java/org/olat/data/commons/vfs/NamedContainerImpl.java
Java
apache-2.0
4,632
// 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.gerrit.acceptance.api.accounts; import static com.google.common.base.Preconditions.checkNotNull; import static com.google.common.truth.Truth.assertThat; import static com.google.common.truth.Truth.assertWithMessage; import static com.google.gerrit.acceptance.GitUtil.deleteRef; import static com.google.gerrit.acceptance.GitUtil.fetch; import static com.google.gerrit.gpg.PublicKeyStore.REFS_GPG_KEYS; import static com.google.gerrit.gpg.PublicKeyStore.keyToString; import static com.google.gerrit.gpg.testing.TestKeys.allValidKeys; import static com.google.gerrit.gpg.testing.TestKeys.validKeyWithExpiration; import static com.google.gerrit.gpg.testing.TestKeys.validKeyWithSecondUserId; import static com.google.gerrit.gpg.testing.TestKeys.validKeyWithoutExpiration; import static com.google.gerrit.server.StarredChangesUtil.DEFAULT_LABEL; import static com.google.gerrit.server.StarredChangesUtil.IGNORE_LABEL; import static com.google.gerrit.server.account.externalids.ExternalId.SCHEME_GPGKEY; import static com.google.gerrit.server.group.SystemGroupBackend.ANONYMOUS_USERS; import static com.google.gerrit.server.group.SystemGroupBackend.REGISTERED_USERS; import static java.nio.charset.StandardCharsets.UTF_8; import static java.util.stream.Collectors.toList; import static java.util.stream.Collectors.toSet; import static org.eclipse.jgit.lib.Constants.OBJ_BLOB; import com.google.common.collect.FluentIterable; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableMap; import com.google.common.collect.ImmutableSet; import com.google.common.collect.ImmutableSetMultimap; import com.google.common.collect.Iterables; import com.google.common.io.BaseEncoding; import com.google.common.util.concurrent.AtomicLongMap; import com.google.gerrit.acceptance.AbstractDaemonTest; import com.google.gerrit.acceptance.AccountCreator; import com.google.gerrit.acceptance.GerritConfig; import com.google.gerrit.acceptance.PushOneCommit; import com.google.gerrit.acceptance.Sandboxed; import com.google.gerrit.acceptance.TestAccount; import com.google.gerrit.acceptance.UseSsh; import com.google.gerrit.common.Nullable; import com.google.gerrit.common.TimeUtil; import com.google.gerrit.common.data.GlobalCapability; import com.google.gerrit.common.data.Permission; import com.google.gerrit.extensions.api.accounts.EmailInput; import com.google.gerrit.extensions.api.changes.AddReviewerInput; import com.google.gerrit.extensions.api.changes.ReviewInput; import com.google.gerrit.extensions.api.changes.StarsInput; import com.google.gerrit.extensions.api.config.ConsistencyCheckInfo; import com.google.gerrit.extensions.api.config.ConsistencyCheckInfo.ConsistencyProblemInfo; import com.google.gerrit.extensions.api.config.ConsistencyCheckInput; import com.google.gerrit.extensions.api.config.ConsistencyCheckInput.CheckAccountsInput; import com.google.gerrit.extensions.common.AccountInfo; import com.google.gerrit.extensions.common.ChangeInfo; import com.google.gerrit.extensions.common.GpgKeyInfo; import com.google.gerrit.extensions.common.SshKeyInfo; import com.google.gerrit.extensions.events.AccountIndexedListener; import com.google.gerrit.extensions.events.GitReferenceUpdatedListener; import com.google.gerrit.extensions.registration.DynamicSet; import com.google.gerrit.extensions.registration.RegistrationHandle; import com.google.gerrit.extensions.restapi.AuthException; import com.google.gerrit.extensions.restapi.BadRequestException; import com.google.gerrit.extensions.restapi.ResourceConflictException; import com.google.gerrit.extensions.restapi.ResourceNotFoundException; import com.google.gerrit.extensions.restapi.RestApiException; import com.google.gerrit.gpg.Fingerprint; import com.google.gerrit.gpg.PublicKeyStore; import com.google.gerrit.gpg.testing.TestKey; import com.google.gerrit.reviewdb.client.Account; import com.google.gerrit.reviewdb.client.AccountGroup; import com.google.gerrit.reviewdb.client.Change; import com.google.gerrit.reviewdb.client.Project; import com.google.gerrit.reviewdb.client.RefNames; import com.google.gerrit.server.Sequences; import com.google.gerrit.server.account.AccountConfig; import com.google.gerrit.server.account.AccountsUpdate; import com.google.gerrit.server.account.Emails; import com.google.gerrit.server.account.WatchConfig; import com.google.gerrit.server.account.WatchConfig.NotifyType; import com.google.gerrit.server.account.externalids.ExternalId; import com.google.gerrit.server.account.externalids.ExternalIds; import com.google.gerrit.server.account.externalids.ExternalIdsUpdate; import com.google.gerrit.server.git.ProjectConfig; import com.google.gerrit.server.group.InternalGroup; import com.google.gerrit.server.mail.Address; import com.google.gerrit.server.notedb.rebuild.ChangeRebuilderImpl; import com.google.gerrit.server.project.RefPattern; import com.google.gerrit.server.query.account.InternalAccountQuery; import com.google.gerrit.server.util.MagicBranch; import com.google.gerrit.testing.ConfigSuite; import com.google.gerrit.testing.FakeEmailSender.Message; import com.google.inject.Inject; import com.google.inject.Provider; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.util.ArrayList; import java.util.Arrays; import java.util.EnumSet; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Locale; import java.util.Map; import java.util.Set; import java.util.concurrent.atomic.AtomicBoolean; import org.bouncycastle.bcpg.ArmoredOutputStream; import org.bouncycastle.openpgp.PGPPublicKey; import org.bouncycastle.openpgp.PGPPublicKeyRing; import org.eclipse.jgit.api.errors.TransportException; import org.eclipse.jgit.internal.storage.dfs.InMemoryRepository; import org.eclipse.jgit.junit.TestRepository; import org.eclipse.jgit.lib.Config; import org.eclipse.jgit.lib.ObjectReader; import org.eclipse.jgit.lib.Ref; import org.eclipse.jgit.lib.RefUpdate; import org.eclipse.jgit.lib.Repository; import org.eclipse.jgit.revwalk.RevCommit; import org.eclipse.jgit.revwalk.RevWalk; import org.eclipse.jgit.transport.PushCertificateIdent; import org.eclipse.jgit.transport.PushResult; import org.eclipse.jgit.transport.RemoteRefUpdate; import org.eclipse.jgit.treewalk.TreeWalk; import org.junit.After; import org.junit.Before; import org.junit.Test; public class AccountIT extends AbstractDaemonTest { @ConfigSuite.Default public static Config enableSignedPushConfig() { Config cfg = new Config(); cfg.setBoolean("receive", null, "enableSignedPush", true); return cfg; } @Inject private Provider<PublicKeyStore> publicKeyStoreProvider; @Inject private AccountsUpdate.Server accountsUpdate; @Inject private ExternalIds externalIds; @Inject private ExternalIdsUpdate.User externalIdsUpdateFactory; @Inject private DynamicSet<AccountIndexedListener> accountIndexedListeners; @Inject private DynamicSet<GitReferenceUpdatedListener> refUpdateListeners; @Inject private Sequences seq; @Inject private Provider<InternalAccountQuery> accountQueryProvider; @Inject protected Emails emails; private AccountIndexedCounter accountIndexedCounter; private RegistrationHandle accountIndexEventCounterHandle; private RefUpdateCounter refUpdateCounter; private RegistrationHandle refUpdateCounterHandle; private ExternalIdsUpdate externalIdsUpdate; private List<ExternalId> savedExternalIds; @Before public void addAccountIndexEventCounter() { accountIndexedCounter = new AccountIndexedCounter(); accountIndexEventCounterHandle = accountIndexedListeners.add(accountIndexedCounter); } @After public void removeAccountIndexEventCounter() { if (accountIndexEventCounterHandle != null) { accountIndexEventCounterHandle.remove(); } } @Before public void addRefUpdateCounter() { refUpdateCounter = new RefUpdateCounter(); refUpdateCounterHandle = refUpdateListeners.add(refUpdateCounter); } @After public void removeRefUpdateCounter() { if (refUpdateCounterHandle != null) { refUpdateCounterHandle.remove(); } } @Before public void saveExternalIds() throws Exception { externalIdsUpdate = externalIdsUpdateFactory.create(); savedExternalIds = new ArrayList<>(); savedExternalIds.addAll(externalIds.byAccount(admin.id)); savedExternalIds.addAll(externalIds.byAccount(user.id)); } @After public void restoreExternalIds() throws Exception { if (savedExternalIds != null) { // savedExternalIds is null when we don't run SSH tests and the assume in // @Before in AbstractDaemonTest prevents this class' @Before method from // being executed. externalIdsUpdate.delete(externalIds.byAccount(admin.id)); externalIdsUpdate.delete(externalIds.byAccount(user.id)); externalIdsUpdate.insert(savedExternalIds); } } @After public void clearPublicKeyStore() throws Exception { try (Repository repo = repoManager.openRepository(allUsers)) { Ref ref = repo.exactRef(REFS_GPG_KEYS); if (ref != null) { RefUpdate ru = repo.updateRef(REFS_GPG_KEYS); ru.setForceUpdate(true); assertThat(ru.delete()).isEqualTo(RefUpdate.Result.FORCED); } } } @After public void deleteGpgKeys() throws Exception { String ref = REFS_GPG_KEYS; try (Repository repo = repoManager.openRepository(allUsers)) { if (repo.getRefDatabase().exactRef(ref) != null) { RefUpdate ru = repo.updateRef(ref); ru.setForceUpdate(true); assertWithMessage("Failed to delete " + ref) .that(ru.delete()) .isEqualTo(RefUpdate.Result.FORCED); } } } @Test public void create() throws Exception { Account.Id accountId = create(2); // account creation + external ID creation refUpdateCounter.assertRefUpdateFor( RefUpdateCounter.projectRef(allUsers, RefNames.refsUsers(accountId)), RefUpdateCounter.projectRef(allUsers, RefNames.REFS_EXTERNAL_IDS), RefUpdateCounter.projectRef(allUsers, RefNames.REFS_SEQUENCES + Sequences.NAME_ACCOUNTS)); } @Test @UseSsh public void createWithSshKeys() throws Exception { Account.Id accountId = create(3); // account creation + external ID creation + adding SSH keys refUpdateCounter.assertRefUpdateFor( ImmutableMap.of( RefUpdateCounter.projectRef(allUsers, RefNames.refsUsers(accountId)), 2, RefUpdateCounter.projectRef(allUsers, RefNames.REFS_EXTERNAL_IDS), 1, RefUpdateCounter.projectRef( allUsers, RefNames.REFS_SEQUENCES + Sequences.NAME_ACCOUNTS), 1)); } private Account.Id create(int expectedAccountReindexCalls) throws Exception { String name = "foo"; TestAccount foo = accountCreator.create(name); AccountInfo info = gApi.accounts().id(foo.id.get()).get(); assertThat(info.username).isEqualTo(name); assertThat(info.name).isEqualTo(name); accountIndexedCounter.assertReindexOf(foo, expectedAccountReindexCalls); assertUserBranch(foo.getId(), name, null); return foo.getId(); } @Test public void createAnonymousCoward() throws Exception { TestAccount anonymousCoward = accountCreator.create(); accountIndexedCounter.assertReindexOf(anonymousCoward); assertUserBranchWithoutAccountConfig(anonymousCoward.getId()); } @Test public void updateNonExistingAccount() throws Exception { Account.Id nonExistingAccountId = new Account.Id(999999); AtomicBoolean consumerCalled = new AtomicBoolean(); Account account = accountsUpdate.create().update(nonExistingAccountId, a -> consumerCalled.set(true)); assertThat(account).isNull(); assertThat(consumerCalled.get()).isFalse(); } @Test public void updateAccountWithoutAccountConfigNoteDb() throws Exception { TestAccount anonymousCoward = accountCreator.create(); assertUserBranchWithoutAccountConfig(anonymousCoward.getId()); String status = "OOO"; Account account = accountsUpdate.create().update(anonymousCoward.getId(), a -> a.setStatus(status)); assertThat(account).isNotNull(); assertThat(account.getFullName()).isNull(); assertThat(account.getStatus()).isEqualTo(status); assertUserBranch(anonymousCoward.getId(), null, status); } private void assertUserBranchWithoutAccountConfig(Account.Id accountId) throws Exception { assertUserBranch(accountId, null, null); } private void assertUserBranch( Account.Id accountId, @Nullable String name, @Nullable String status) throws Exception { try (Repository repo = repoManager.openRepository(allUsers); RevWalk rw = new RevWalk(repo); ObjectReader or = repo.newObjectReader()) { Ref ref = repo.exactRef(RefNames.refsUsers(accountId)); assertThat(ref).isNotNull(); RevCommit c = rw.parseCommit(ref.getObjectId()); long timestampDiffMs = Math.abs( c.getCommitTime() * 1000L - accountCache.get(accountId).getAccount().getRegisteredOn().getTime()); assertThat(timestampDiffMs).isAtMost(ChangeRebuilderImpl.MAX_WINDOW_MS); // Check the 'account.config' file. try (TreeWalk tw = TreeWalk.forPath(or, AccountConfig.ACCOUNT_CONFIG, c.getTree())) { if (name != null || status != null) { assertThat(tw).isNotNull(); Config cfg = new Config(); cfg.fromText(new String(or.open(tw.getObjectId(0), OBJ_BLOB).getBytes(), UTF_8)); assertThat(cfg.getString(AccountConfig.ACCOUNT, null, AccountConfig.KEY_FULL_NAME)) .isEqualTo(name); assertThat(cfg.getString(AccountConfig.ACCOUNT, null, AccountConfig.KEY_STATUS)) .isEqualTo(status); } else { // No account properties were set, hence an 'account.config' file was not created. assertThat(tw).isNull(); } } } } @Test public void get() throws Exception { AccountInfo info = gApi.accounts().id("admin").get(); assertThat(info.name).isEqualTo("Administrator"); assertThat(info.email).isEqualTo("[email protected]"); assertThat(info.username).isEqualTo("admin"); accountIndexedCounter.assertNoReindex(); } @Test public void getByIntId() throws Exception { AccountInfo info = gApi.accounts().id("admin").get(); AccountInfo infoByIntId = gApi.accounts().id(info._accountId).get(); assertThat(info.name).isEqualTo(infoByIntId.name); accountIndexedCounter.assertNoReindex(); } @Test public void self() throws Exception { AccountInfo info = gApi.accounts().self().get(); assertUser(info, admin); info = gApi.accounts().id("self").get(); assertUser(info, admin); accountIndexedCounter.assertNoReindex(); } @Test public void active() throws Exception { assertThat(gApi.accounts().id("user").getActive()).isTrue(); gApi.accounts().id("user").setActive(false); assertThat(gApi.accounts().id("user").getActive()).isFalse(); accountIndexedCounter.assertReindexOf(user); gApi.accounts().id("user").setActive(true); assertThat(gApi.accounts().id("user").getActive()).isTrue(); accountIndexedCounter.assertReindexOf(user); } @Test public void deactivateSelf() throws Exception { exception.expect(ResourceConflictException.class); exception.expectMessage("cannot deactivate own account"); gApi.accounts().self().setActive(false); } @Test public void deactivateNotActive() throws Exception { assertThat(gApi.accounts().id("user").getActive()).isTrue(); gApi.accounts().id("user").setActive(false); assertThat(gApi.accounts().id("user").getActive()).isFalse(); try { gApi.accounts().id("user").setActive(false); fail("Expected exception"); } catch (ResourceConflictException e) { assertThat(e.getMessage()).isEqualTo("account not active"); } gApi.accounts().id("user").setActive(true); } @Test public void starUnstarChange() throws Exception { PushOneCommit.Result r = createChange(); String triplet = project.get() + "~master~" + r.getChangeId(); refUpdateCounter.clear(); gApi.accounts().self().starChange(triplet); ChangeInfo change = info(triplet); assertThat(change.starred).isTrue(); assertThat(change.stars).contains(DEFAULT_LABEL); refUpdateCounter.assertRefUpdateFor( RefUpdateCounter.projectRef( allUsers, RefNames.refsStarredChanges(new Change.Id(change._number), admin.id))); gApi.accounts().self().unstarChange(triplet); change = info(triplet); assertThat(change.starred).isNull(); assertThat(change.stars).isNull(); refUpdateCounter.assertRefUpdateFor( RefUpdateCounter.projectRef( allUsers, RefNames.refsStarredChanges(new Change.Id(change._number), admin.id))); accountIndexedCounter.assertNoReindex(); } @Test public void starUnstarChangeWithLabels() throws Exception { PushOneCommit.Result r = createChange(); String triplet = project.get() + "~master~" + r.getChangeId(); refUpdateCounter.clear(); assertThat(gApi.accounts().self().getStars(triplet)).isEmpty(); assertThat(gApi.accounts().self().getStarredChanges()).isEmpty(); gApi.accounts() .self() .setStars(triplet, new StarsInput(ImmutableSet.of(DEFAULT_LABEL, "red", "blue"))); ChangeInfo change = info(triplet); assertThat(change.starred).isTrue(); assertThat(change.stars).containsExactly("blue", "red", DEFAULT_LABEL).inOrder(); assertThat(gApi.accounts().self().getStars(triplet)) .containsExactly("blue", "red", DEFAULT_LABEL) .inOrder(); List<ChangeInfo> starredChanges = gApi.accounts().self().getStarredChanges(); assertThat(starredChanges).hasSize(1); ChangeInfo starredChange = starredChanges.get(0); assertThat(starredChange._number).isEqualTo(r.getChange().getId().get()); assertThat(starredChange.starred).isTrue(); assertThat(starredChange.stars).containsExactly("blue", "red", DEFAULT_LABEL).inOrder(); refUpdateCounter.assertRefUpdateFor( RefUpdateCounter.projectRef( allUsers, RefNames.refsStarredChanges(new Change.Id(change._number), admin.id))); gApi.accounts() .self() .setStars( triplet, new StarsInput(ImmutableSet.of("yellow"), ImmutableSet.of(DEFAULT_LABEL, "blue"))); change = info(triplet); assertThat(change.starred).isNull(); assertThat(change.stars).containsExactly("red", "yellow").inOrder(); assertThat(gApi.accounts().self().getStars(triplet)).containsExactly("red", "yellow").inOrder(); starredChanges = gApi.accounts().self().getStarredChanges(); assertThat(starredChanges).hasSize(1); starredChange = starredChanges.get(0); assertThat(starredChange._number).isEqualTo(r.getChange().getId().get()); assertThat(starredChange.starred).isNull(); assertThat(starredChange.stars).containsExactly("red", "yellow").inOrder(); refUpdateCounter.assertRefUpdateFor( RefUpdateCounter.projectRef( allUsers, RefNames.refsStarredChanges(new Change.Id(change._number), admin.id))); accountIndexedCounter.assertNoReindex(); setApiUser(user); exception.expect(AuthException.class); exception.expectMessage("not allowed to get stars of another account"); gApi.accounts().id(Integer.toString((admin.id.get()))).getStars(triplet); } @Test public void starWithInvalidLabels() throws Exception { PushOneCommit.Result r = createChange(); String triplet = project.get() + "~master~" + r.getChangeId(); exception.expect(BadRequestException.class); exception.expectMessage("invalid labels: another invalid label, invalid label"); gApi.accounts() .self() .setStars( triplet, new StarsInput( ImmutableSet.of(DEFAULT_LABEL, "invalid label", "blue", "another invalid label"))); } @Test public void starWithDefaultAndIgnoreLabel() throws Exception { PushOneCommit.Result r = createChange(); String triplet = project.get() + "~master~" + r.getChangeId(); exception.expect(BadRequestException.class); exception.expectMessage( "The labels " + DEFAULT_LABEL + " and " + IGNORE_LABEL + " are mutually exclusive." + " Only one of them can be set."); gApi.accounts() .self() .setStars(triplet, new StarsInput(ImmutableSet.of(DEFAULT_LABEL, "blue", IGNORE_LABEL))); } @Test public void ignoreChangeBySetStars() throws Exception { TestAccount user2 = accountCreator.user2(); accountIndexedCounter.clear(); PushOneCommit.Result r = createChange(); AddReviewerInput in = new AddReviewerInput(); in.reviewer = user.email; gApi.changes().id(r.getChangeId()).addReviewer(in); in = new AddReviewerInput(); in.reviewer = user2.email; gApi.changes().id(r.getChangeId()).addReviewer(in); setApiUser(user); gApi.accounts().self().setStars(r.getChangeId(), new StarsInput(ImmutableSet.of(IGNORE_LABEL))); sender.clear(); setApiUser(admin); gApi.changes().id(r.getChangeId()).abandon(); List<Message> messages = sender.getMessages(); assertThat(messages).hasSize(1); assertThat(messages.get(0).rcpt()).containsExactly(user2.emailAddress); accountIndexedCounter.assertNoReindex(); } @Test public void addReviewerToIgnoredChange() throws Exception { PushOneCommit.Result r = createChange(); setApiUser(user); gApi.accounts().self().setStars(r.getChangeId(), new StarsInput(ImmutableSet.of(IGNORE_LABEL))); sender.clear(); setApiUser(admin); AddReviewerInput in = new AddReviewerInput(); in.reviewer = user.email; gApi.changes().id(r.getChangeId()).addReviewer(in); List<Message> messages = sender.getMessages(); assertThat(messages).hasSize(1); Message message = messages.get(0); assertThat(message.rcpt()).containsExactly(user.emailAddress); assertMailReplyTo(message, admin.email); accountIndexedCounter.assertNoReindex(); } @Test public void suggestAccounts() throws Exception { String adminUsername = "admin"; List<AccountInfo> result = gApi.accounts().suggestAccounts().withQuery(adminUsername).get(); assertThat(result).hasSize(1); assertThat(result.get(0).username).isEqualTo(adminUsername); List<AccountInfo> resultShortcutApi = gApi.accounts().suggestAccounts(adminUsername).get(); assertThat(resultShortcutApi).hasSize(result.size()); List<AccountInfo> emptyResult = gApi.accounts().suggestAccounts("unknown").get(); assertThat(emptyResult).isEmpty(); accountIndexedCounter.assertNoReindex(); } @Test public void addEmail() throws Exception { List<String> emails = ImmutableList.of("[email protected]", "[email protected]"); Set<String> currentEmails = getEmails(); for (String email : emails) { assertThat(currentEmails).doesNotContain(email); EmailInput input = newEmailInput(email); gApi.accounts().self().addEmail(input); accountIndexedCounter.assertReindexOf(admin); } resetCurrentApiUser(); assertThat(getEmails()).containsAllIn(emails); } @Test public void addInvalidEmail() throws Exception { List<String> emails = ImmutableList.of( // Missing domain part "new.email", // Missing domain part "new.email@", // Missing user part "@example.com", // Non-supported TLD (see tlds-alpha-by-domain.txt) "[email protected]"); for (String email : emails) { EmailInput input = newEmailInput(email); try { gApi.accounts().self().addEmail(input); fail("Expected BadRequestException for invalid email address: " + email); } catch (BadRequestException e) { assertThat(e).hasMessageThat().isEqualTo("invalid email address"); } } accountIndexedCounter.assertNoReindex(); } @Test public void cannotAddNonConfirmedEmailWithoutModifyAccountPermission() throws Exception { TestAccount account = accountCreator.create(name("user")); EmailInput input = newEmailInput("[email protected]"); setApiUser(user); exception.expect(AuthException.class); gApi.accounts().id(account.username).addEmail(input); } @Test public void cannotAddEmailAddressUsedByAnotherAccount() throws Exception { String email = "[email protected]"; EmailInput input = newEmailInput(email); gApi.accounts().self().addEmail(input); exception.expect(ResourceConflictException.class); exception.expectMessage("Identity 'mailto:" + email + "' in use by another account"); gApi.accounts().id(user.username).addEmail(input); } @Test @GerritConfig( name = "auth.registerEmailPrivateKey", value = "HsOc6l+2lhS9G7sE/RsnS7Z6GJjdRDX14co=" ) public void addEmailSendsConfirmationEmail() throws Exception { String email = "[email protected]"; EmailInput input = newEmailInput(email, false); gApi.accounts().self().addEmail(input); assertThat(sender.getMessages()).hasSize(1); Message m = sender.getMessages().get(0); assertThat(m.rcpt()).containsExactly(new Address(email)); } @Test public void deleteEmail() throws Exception { String email = "[email protected]"; EmailInput input = newEmailInput(email); gApi.accounts().self().addEmail(input); resetCurrentApiUser(); assertThat(getEmails()).contains(email); accountIndexedCounter.clear(); gApi.accounts().self().deleteEmail(input.email); accountIndexedCounter.assertReindexOf(admin); resetCurrentApiUser(); assertThat(getEmails()).doesNotContain(email); } @Test public void deleteEmailFromCustomExternalIdSchemes() throws Exception { String email = "[email protected]"; String extId1 = "foo:bar"; String extId2 = "foo:baz"; List<ExternalId> extIds = ImmutableList.of( ExternalId.createWithEmail(ExternalId.Key.parse(extId1), admin.id, email), ExternalId.createWithEmail(ExternalId.Key.parse(extId2), admin.id, email)); externalIdsUpdateFactory.create().insert(extIds); accountIndexedCounter.assertReindexOf(admin); assertThat( gApi.accounts().self().getExternalIds().stream().map(e -> e.identity).collect(toSet())) .containsAllOf(extId1, extId2); resetCurrentApiUser(); assertThat(getEmails()).contains(email); gApi.accounts().self().deleteEmail(email); accountIndexedCounter.assertReindexOf(admin); resetCurrentApiUser(); assertThat(getEmails()).doesNotContain(email); assertThat( gApi.accounts().self().getExternalIds().stream().map(e -> e.identity).collect(toSet())) .containsNoneOf(extId1, extId2); } @Test public void deleteEmailOfOtherUser() throws Exception { String email = "[email protected]"; EmailInput input = new EmailInput(); input.email = email; input.noConfirmation = true; gApi.accounts().id(user.id.get()).addEmail(input); accountIndexedCounter.assertReindexOf(user); setApiUser(user); assertThat(getEmails()).contains(email); // admin can delete email of user setApiUser(admin); gApi.accounts().id(user.id.get()).deleteEmail(email); accountIndexedCounter.assertReindexOf(user); setApiUser(user); assertThat(getEmails()).doesNotContain(email); // user cannot delete email of admin exception.expect(AuthException.class); exception.expectMessage("modify account not permitted"); gApi.accounts().id(admin.id.get()).deleteEmail(admin.email); } @Test public void lookUpByEmail() throws Exception { // exact match with scheme "mailto:" assertEmail(emails.getAccountFor(admin.email), admin); // exact match with other scheme String email = "[email protected]"; externalIdsUpdateFactory .create() .insert(ExternalId.createWithEmail(ExternalId.Key.parse("foo:bar"), admin.id, email)); assertEmail(emails.getAccountFor(email), admin); // wrong case doesn't match assertThat(emails.getAccountFor(admin.email.toUpperCase(Locale.US))).isEmpty(); // prefix doesn't match assertThat(emails.getAccountFor(admin.email.substring(0, admin.email.indexOf('@')))).isEmpty(); // non-existing doesn't match assertThat(emails.getAccountFor("[email protected]")).isEmpty(); // lookup several accounts by email at once ImmutableSetMultimap<String, Account.Id> byEmails = emails.getAccountsFor(admin.email, user.email); assertEmail(byEmails.get(admin.email), admin); assertEmail(byEmails.get(user.email), user); } @Test public void lookUpByPreferredEmail() throws Exception { // create an inconsistent account that has a preferred email without external ID String prefix = "foo.preferred"; String prefEmail = prefix + "@example.com"; TestAccount foo = accountCreator.create(name("foo")); accountsUpdate.create().update(foo.id, a -> a.setPreferredEmail(prefEmail)); // verify that the account is still found when using the preferred email to lookup the account ImmutableSet<Account.Id> accountsByPrefEmail = emails.getAccountFor(prefEmail); assertThat(accountsByPrefEmail).hasSize(1); assertThat(Iterables.getOnlyElement(accountsByPrefEmail)).isEqualTo(foo.id); // look up by email prefix doesn't find the account accountsByPrefEmail = emails.getAccountFor(prefix); assertThat(accountsByPrefEmail).isEmpty(); // look up by other case doesn't find the account accountsByPrefEmail = emails.getAccountFor(prefEmail.toUpperCase(Locale.US)); assertThat(accountsByPrefEmail).isEmpty(); } @Test public void putStatus() throws Exception { List<String> statuses = ImmutableList.of("OOO", "Busy"); AccountInfo info; for (String status : statuses) { gApi.accounts().self().setStatus(status); admin.status = status; info = gApi.accounts().self().get(); assertUser(info, admin); accountIndexedCounter.assertReindexOf(admin); } } @Test @Sandboxed public void fetchUserBranch() throws Exception { setApiUser(user); TestRepository<InMemoryRepository> allUsersRepo = cloneProject(allUsers, user); String userRefName = RefNames.refsUsers(user.id); // remove default READ permissions ProjectConfig cfg = projectCache.checkedGet(allUsers).getConfig(); cfg.getAccessSection(RefNames.REFS_USERS + "${" + RefPattern.USERID_SHARDED + "}", true) .remove(new Permission(Permission.READ)); saveProjectConfig(allUsers, cfg); // deny READ permission that is inherited from All-Projects deny(allUsers, RefNames.REFS + "*", Permission.READ, ANONYMOUS_USERS); // fetching user branch without READ permission fails try { fetch(allUsersRepo, userRefName + ":userRef"); fail("user branch is visible although no READ permission is granted"); } catch (TransportException e) { // expected because no READ granted on user branch } // allow each user to read its own user branch grant( allUsers, RefNames.REFS_USERS + "${" + RefPattern.USERID_SHARDED + "}", Permission.READ, false, REGISTERED_USERS); // fetch user branch using refs/users/YY/XXXXXXX fetch(allUsersRepo, userRefName + ":userRef"); Ref userRef = allUsersRepo.getRepository().exactRef("userRef"); assertThat(userRef).isNotNull(); // fetch user branch using refs/users/self fetch(allUsersRepo, RefNames.REFS_USERS_SELF + ":userSelfRef"); Ref userSelfRef = allUsersRepo.getRepository().getRefDatabase().exactRef("userSelfRef"); assertThat(userSelfRef).isNotNull(); assertThat(userSelfRef.getObjectId()).isEqualTo(userRef.getObjectId()); accountIndexedCounter.assertNoReindex(); // fetching user branch of another user fails String otherUserRefName = RefNames.refsUsers(admin.id); exception.expect(TransportException.class); exception.expectMessage("Remote does not have " + otherUserRefName + " available for fetch."); fetch(allUsersRepo, otherUserRefName + ":otherUserRef"); } @Test public void pushToUserBranch() throws Exception { TestRepository<InMemoryRepository> allUsersRepo = cloneProject(allUsers); fetch(allUsersRepo, RefNames.refsUsers(admin.id) + ":userRef"); allUsersRepo.reset("userRef"); PushOneCommit push = pushFactory.create(db, admin.getIdent(), allUsersRepo); push.to(RefNames.refsUsers(admin.id)).assertOkStatus(); accountIndexedCounter.assertReindexOf(admin); push = pushFactory.create(db, admin.getIdent(), allUsersRepo); push.to(RefNames.REFS_USERS_SELF).assertOkStatus(); accountIndexedCounter.assertReindexOf(admin); } @Test public void pushToUserBranchForReview() throws Exception { String userRefName = RefNames.refsUsers(admin.id); TestRepository<InMemoryRepository> allUsersRepo = cloneProject(allUsers); fetch(allUsersRepo, userRefName + ":userRef"); allUsersRepo.reset("userRef"); PushOneCommit push = pushFactory.create(db, admin.getIdent(), allUsersRepo); PushOneCommit.Result r = push.to(MagicBranch.NEW_CHANGE + userRefName); r.assertOkStatus(); accountIndexedCounter.assertNoReindex(); assertThat(r.getChange().change().getDest().get()).isEqualTo(userRefName); gApi.changes().id(r.getChangeId()).current().review(ReviewInput.approve()); gApi.changes().id(r.getChangeId()).current().submit(); accountIndexedCounter.assertReindexOf(admin); push = pushFactory.create(db, admin.getIdent(), allUsersRepo); r = push.to(MagicBranch.NEW_CHANGE + RefNames.REFS_USERS_SELF); r.assertOkStatus(); accountIndexedCounter.assertNoReindex(); assertThat(r.getChange().change().getDest().get()).isEqualTo(userRefName); gApi.changes().id(r.getChangeId()).current().review(ReviewInput.approve()); gApi.changes().id(r.getChangeId()).current().submit(); accountIndexedCounter.assertReindexOf(admin); } @Test public void pushAccountConfigToUserBranchForReviewAndSubmit() throws Exception { String userRef = RefNames.refsUsers(admin.id); TestRepository<InMemoryRepository> allUsersRepo = cloneProject(allUsers); fetch(allUsersRepo, userRef + ":userRef"); allUsersRepo.reset("userRef"); Config ac = getAccountConfig(allUsersRepo); ac.setString(AccountConfig.ACCOUNT, null, AccountConfig.KEY_STATUS, "out-of-office"); PushOneCommit.Result r = pushFactory .create( db, admin.getIdent(), allUsersRepo, "Update account config", AccountConfig.ACCOUNT_CONFIG, ac.toText()) .to(MagicBranch.NEW_CHANGE + userRef); r.assertOkStatus(); accountIndexedCounter.assertNoReindex(); assertThat(r.getChange().change().getDest().get()).isEqualTo(userRef); gApi.changes().id(r.getChangeId()).current().review(ReviewInput.approve()); gApi.changes().id(r.getChangeId()).current().submit(); accountIndexedCounter.assertReindexOf(admin); AccountInfo info = gApi.accounts().self().get(); assertThat(info.email).isEqualTo(admin.email); assertThat(info.name).isEqualTo(admin.fullName); assertThat(info.status).isEqualTo("out-of-office"); } @Test public void pushAccountConfigWithPrefEmailThatDoesNotExistAsExtIdToUserBranchForReviewAndSubmit() throws Exception { TestAccount foo = accountCreator.create(name("foo")); String userRef = RefNames.refsUsers(foo.id); accountIndexedCounter.clear(); TestRepository<InMemoryRepository> allUsersRepo = cloneProject(allUsers); fetch(allUsersRepo, userRef + ":userRef"); allUsersRepo.reset("userRef"); String email = "[email protected]"; Config ac = getAccountConfig(allUsersRepo); ac.setString(AccountConfig.ACCOUNT, null, AccountConfig.KEY_PREFERRED_EMAIL, email); PushOneCommit.Result r = pushFactory .create( db, admin.getIdent(), allUsersRepo, "Update account config", AccountConfig.ACCOUNT_CONFIG, ac.toText()) .to(MagicBranch.NEW_CHANGE + userRef); r.assertOkStatus(); accountIndexedCounter.assertNoReindex(); assertThat(r.getChange().change().getDest().get()).isEqualTo(userRef); setApiUser(foo); gApi.changes().id(r.getChangeId()).current().review(ReviewInput.approve()); gApi.changes().id(r.getChangeId()).current().submit(); accountIndexedCounter.assertReindexOf(foo); AccountInfo info = gApi.accounts().self().get(); assertThat(info.email).isEqualTo(email); assertThat(info.name).isEqualTo(foo.fullName); } @Test public void pushAccountConfigToUserBranchForReviewIsRejectedOnSubmitIfConfigIsInvalid() throws Exception { String userRef = RefNames.refsUsers(admin.id); TestRepository<InMemoryRepository> allUsersRepo = cloneProject(allUsers); fetch(allUsersRepo, userRef + ":userRef"); allUsersRepo.reset("userRef"); PushOneCommit.Result r = pushFactory .create( db, admin.getIdent(), allUsersRepo, "Update account config", AccountConfig.ACCOUNT_CONFIG, "invalid config") .to(MagicBranch.NEW_CHANGE + userRef); r.assertOkStatus(); accountIndexedCounter.assertNoReindex(); assertThat(r.getChange().change().getDest().get()).isEqualTo(userRef); gApi.changes().id(r.getChangeId()).current().review(ReviewInput.approve()); exception.expect(ResourceConflictException.class); exception.expectMessage( String.format( "invalid account configuration: commit '%s' has an invalid '%s' file for account '%s':" + " Invalid config file %s in commit %s", r.getCommit().name(), AccountConfig.ACCOUNT_CONFIG, admin.id, AccountConfig.ACCOUNT_CONFIG, r.getCommit().name())); gApi.changes().id(r.getChangeId()).current().submit(); } @Test public void pushAccountConfigToUserBranchForReviewIsRejectedOnSubmitIfPreferredEmailIsInvalid() throws Exception { String userRef = RefNames.refsUsers(admin.id); TestRepository<InMemoryRepository> allUsersRepo = cloneProject(allUsers); fetch(allUsersRepo, userRef + ":userRef"); allUsersRepo.reset("userRef"); String noEmail = "no.email"; Config ac = getAccountConfig(allUsersRepo); ac.setString(AccountConfig.ACCOUNT, null, AccountConfig.KEY_PREFERRED_EMAIL, noEmail); PushOneCommit.Result r = pushFactory .create( db, admin.getIdent(), allUsersRepo, "Update account config", AccountConfig.ACCOUNT_CONFIG, ac.toText()) .to(MagicBranch.NEW_CHANGE + userRef); r.assertOkStatus(); accountIndexedCounter.assertNoReindex(); assertThat(r.getChange().change().getDest().get()).isEqualTo(userRef); gApi.changes().id(r.getChangeId()).current().review(ReviewInput.approve()); exception.expect(ResourceConflictException.class); exception.expectMessage( String.format( "invalid account configuration: invalid preferred email '%s' for account '%s'", noEmail, admin.id)); gApi.changes().id(r.getChangeId()).current().submit(); } @Test public void pushAccountConfigToUserBranchForReviewIsRejectedOnSubmitIfOwnAccountIsDeactivated() throws Exception { String userRef = RefNames.refsUsers(admin.id); TestRepository<InMemoryRepository> allUsersRepo = cloneProject(allUsers); fetch(allUsersRepo, userRef + ":userRef"); allUsersRepo.reset("userRef"); Config ac = getAccountConfig(allUsersRepo); ac.setBoolean(AccountConfig.ACCOUNT, null, AccountConfig.KEY_ACTIVE, false); PushOneCommit.Result r = pushFactory .create( db, admin.getIdent(), allUsersRepo, "Update account config", AccountConfig.ACCOUNT_CONFIG, ac.toText()) .to(MagicBranch.NEW_CHANGE + userRef); r.assertOkStatus(); accountIndexedCounter.assertNoReindex(); assertThat(r.getChange().change().getDest().get()).isEqualTo(userRef); gApi.changes().id(r.getChangeId()).current().review(ReviewInput.approve()); exception.expect(ResourceConflictException.class); exception.expectMessage("invalid account configuration: cannot deactivate own account"); gApi.changes().id(r.getChangeId()).current().submit(); } @Test public void pushAccountConfigToUserBranchForReviewDeactivateOtherAccount() throws Exception { TestAccount foo = accountCreator.create(name("foo")); assertThat(gApi.accounts().id(foo.id.get()).getActive()).isTrue(); String userRef = RefNames.refsUsers(foo.id); accountIndexedCounter.clear(); InternalGroup adminGroup = groupCache.get(new AccountGroup.NameKey("Administrators")).orElse(null); grant(allUsers, userRef, Permission.PUSH, false, adminGroup.getGroupUUID()); grantLabel("Code-Review", -2, 2, allUsers, userRef, false, adminGroup.getGroupUUID(), false); grant(allUsers, userRef, Permission.SUBMIT, false, adminGroup.getGroupUUID()); TestRepository<InMemoryRepository> allUsersRepo = cloneProject(allUsers); fetch(allUsersRepo, userRef + ":userRef"); allUsersRepo.reset("userRef"); Config ac = getAccountConfig(allUsersRepo); ac.setBoolean(AccountConfig.ACCOUNT, null, AccountConfig.KEY_ACTIVE, false); PushOneCommit.Result r = pushFactory .create( db, admin.getIdent(), allUsersRepo, "Update account config", AccountConfig.ACCOUNT_CONFIG, ac.toText()) .to(MagicBranch.NEW_CHANGE + userRef); r.assertOkStatus(); accountIndexedCounter.assertNoReindex(); assertThat(r.getChange().change().getDest().get()).isEqualTo(userRef); gApi.changes().id(r.getChangeId()).current().review(ReviewInput.approve()); gApi.changes().id(r.getChangeId()).current().submit(); accountIndexedCounter.assertReindexOf(foo); assertThat(gApi.accounts().id(foo.id.get()).getActive()).isFalse(); } @Test public void pushWatchConfigToUserBranch() throws Exception { TestRepository<InMemoryRepository> allUsersRepo = cloneProject(allUsers); fetch(allUsersRepo, RefNames.refsUsers(admin.id) + ":userRef"); allUsersRepo.reset("userRef"); Config wc = new Config(); wc.setString( WatchConfig.PROJECT, project.get(), WatchConfig.KEY_NOTIFY, WatchConfig.NotifyValue.create(null, EnumSet.of(NotifyType.ALL_COMMENTS)).toString()); PushOneCommit push = pushFactory.create( db, admin.getIdent(), allUsersRepo, "Add project watch", WatchConfig.WATCH_CONFIG, wc.toText()); push.to(RefNames.REFS_USERS_SELF).assertOkStatus(); accountIndexedCounter.assertReindexOf(admin); String invalidNotifyValue = "]invalid["; wc.setString(WatchConfig.PROJECT, project.get(), WatchConfig.KEY_NOTIFY, invalidNotifyValue); push = pushFactory.create( db, admin.getIdent(), allUsersRepo, "Add invalid project watch", WatchConfig.WATCH_CONFIG, wc.toText()); PushOneCommit.Result r = push.to(RefNames.REFS_USERS_SELF); r.assertErrorStatus("invalid watch configuration"); r.assertMessage( String.format( "%s: Invalid project watch of account %d for project %s: %s", WatchConfig.WATCH_CONFIG, admin.getId().get(), project.get(), invalidNotifyValue)); } @Test public void pushAccountConfigToUserBranch() throws Exception { TestAccount oooUser = accountCreator.create("away", "[email protected]", "Ambrose Way"); setApiUser(oooUser); // Must clone as oooUser to ensure the push is allowed. TestRepository<InMemoryRepository> allUsersRepo = cloneProject(allUsers, oooUser); fetch(allUsersRepo, RefNames.refsUsers(oooUser.id) + ":userRef"); allUsersRepo.reset("userRef"); Config ac = getAccountConfig(allUsersRepo); ac.setString(AccountConfig.ACCOUNT, null, AccountConfig.KEY_STATUS, "out-of-office"); accountIndexedCounter.clear(); pushFactory .create( db, oooUser.getIdent(), allUsersRepo, "Update account config", AccountConfig.ACCOUNT_CONFIG, ac.toText()) .to(RefNames.refsUsers(oooUser.id)) .assertOkStatus(); accountIndexedCounter.assertReindexOf(oooUser); AccountInfo info = gApi.accounts().self().get(); assertThat(info.email).isEqualTo(oooUser.email); assertThat(info.name).isEqualTo(oooUser.fullName); assertThat(info.status).isEqualTo("out-of-office"); } @Test public void pushAccountConfigToUserBranchIsRejectedIfConfigIsInvalid() throws Exception { TestRepository<InMemoryRepository> allUsersRepo = cloneProject(allUsers); fetch(allUsersRepo, RefNames.refsUsers(admin.id) + ":userRef"); allUsersRepo.reset("userRef"); PushOneCommit.Result r = pushFactory .create( db, admin.getIdent(), allUsersRepo, "Update account config", AccountConfig.ACCOUNT_CONFIG, "invalid config") .to(RefNames.REFS_USERS_SELF); r.assertErrorStatus("invalid account configuration"); r.assertMessage( String.format( "commit '%s' has an invalid '%s' file for account '%s':" + " Invalid config file %s in commit %s", r.getCommit().name(), AccountConfig.ACCOUNT_CONFIG, admin.id, AccountConfig.ACCOUNT_CONFIG, r.getCommit().name())); accountIndexedCounter.assertNoReindex(); } @Test public void pushAccountConfigToUserBranchIsRejectedIfPreferredEmailIsInvalid() throws Exception { TestRepository<InMemoryRepository> allUsersRepo = cloneProject(allUsers); fetch(allUsersRepo, RefNames.refsUsers(admin.id) + ":userRef"); allUsersRepo.reset("userRef"); String noEmail = "no.email"; Config ac = getAccountConfig(allUsersRepo); ac.setString(AccountConfig.ACCOUNT, null, AccountConfig.KEY_PREFERRED_EMAIL, noEmail); PushOneCommit.Result r = pushFactory .create( db, admin.getIdent(), allUsersRepo, "Update account config", AccountConfig.ACCOUNT_CONFIG, ac.toText()) .to(RefNames.REFS_USERS_SELF); r.assertErrorStatus("invalid account configuration"); r.assertMessage( String.format("invalid preferred email '%s' for account '%s'", noEmail, admin.id)); accountIndexedCounter.assertNoReindex(); } @Test public void pushAccountConfigToUserBranchInvalidPreferredEmailButNotChanged() throws Exception { TestAccount foo = accountCreator.create(name("foo")); String userRef = RefNames.refsUsers(foo.id); String noEmail = "no.email"; accountsUpdate.create().update(foo.id, a -> a.setPreferredEmail(noEmail)); accountIndexedCounter.clear(); InternalGroup adminGroup = groupCache.get(new AccountGroup.NameKey("Administrators")).orElse(null); grant(allUsers, userRef, Permission.PUSH, false, adminGroup.getGroupUUID()); TestRepository<InMemoryRepository> allUsersRepo = cloneProject(allUsers); fetch(allUsersRepo, userRef + ":userRef"); allUsersRepo.reset("userRef"); String status = "in vacation"; Config ac = getAccountConfig(allUsersRepo); ac.setString(AccountConfig.ACCOUNT, null, AccountConfig.KEY_STATUS, status); pushFactory .create( db, admin.getIdent(), allUsersRepo, "Update account config", AccountConfig.ACCOUNT_CONFIG, ac.toText()) .to(userRef) .assertOkStatus(); accountIndexedCounter.assertReindexOf(foo); AccountInfo info = gApi.accounts().id(foo.id.get()).get(); assertThat(info.email).isEqualTo(noEmail); assertThat(info.name).isEqualTo(foo.fullName); assertThat(info.status).isEqualTo(status); } @Test public void pushAccountConfigToUserBranchIfPreferredEmailDoesNotExistAsExtId() throws Exception { TestAccount foo = accountCreator.create(name("foo")); String userRef = RefNames.refsUsers(foo.id); accountIndexedCounter.clear(); InternalGroup adminGroup = groupCache.get(new AccountGroup.NameKey("Administrators")).orElse(null); grant(allUsers, userRef, Permission.PUSH, false, adminGroup.getGroupUUID()); TestRepository<InMemoryRepository> allUsersRepo = cloneProject(allUsers); fetch(allUsersRepo, userRef + ":userRef"); allUsersRepo.reset("userRef"); String email = "[email protected]"; Config ac = getAccountConfig(allUsersRepo); ac.setString(AccountConfig.ACCOUNT, null, AccountConfig.KEY_PREFERRED_EMAIL, email); pushFactory .create( db, admin.getIdent(), allUsersRepo, "Update account config", AccountConfig.ACCOUNT_CONFIG, ac.toText()) .to(userRef) .assertOkStatus(); accountIndexedCounter.assertReindexOf(foo); AccountInfo info = gApi.accounts().id(foo.id.get()).get(); assertThat(info.email).isEqualTo(email); assertThat(info.name).isEqualTo(foo.fullName); } @Test public void pushAccountConfigToUserBranchIsRejectedIfOwnAccountIsDeactivated() throws Exception { TestRepository<InMemoryRepository> allUsersRepo = cloneProject(allUsers); fetch(allUsersRepo, RefNames.refsUsers(admin.id) + ":userRef"); allUsersRepo.reset("userRef"); Config ac = getAccountConfig(allUsersRepo); ac.setBoolean(AccountConfig.ACCOUNT, null, AccountConfig.KEY_ACTIVE, false); PushOneCommit.Result r = pushFactory .create( db, admin.getIdent(), allUsersRepo, "Update account config", AccountConfig.ACCOUNT_CONFIG, ac.toText()) .to(RefNames.REFS_USERS_SELF); r.assertErrorStatus("invalid account configuration"); r.assertMessage("cannot deactivate own account"); accountIndexedCounter.assertNoReindex(); } @Test public void pushAccountConfigToUserBranchDeactivateOtherAccount() throws Exception { TestAccount foo = accountCreator.create(name("foo")); assertThat(gApi.accounts().id(foo.id.get()).getActive()).isTrue(); String userRef = RefNames.refsUsers(foo.id); accountIndexedCounter.clear(); InternalGroup adminGroup = groupCache.get(new AccountGroup.NameKey("Administrators")).orElse(null); grant(allUsers, userRef, Permission.PUSH, false, adminGroup.getGroupUUID()); TestRepository<InMemoryRepository> allUsersRepo = cloneProject(allUsers); fetch(allUsersRepo, userRef + ":userRef"); allUsersRepo.reset("userRef"); Config ac = getAccountConfig(allUsersRepo); ac.setBoolean(AccountConfig.ACCOUNT, null, AccountConfig.KEY_ACTIVE, false); pushFactory .create( db, admin.getIdent(), allUsersRepo, "Update account config", AccountConfig.ACCOUNT_CONFIG, ac.toText()) .to(userRef) .assertOkStatus(); accountIndexedCounter.assertReindexOf(foo); assertThat(gApi.accounts().id(foo.id.get()).getActive()).isFalse(); } @Test @Sandboxed public void cannotCreateUserBranch() throws Exception { grant(allUsers, RefNames.REFS_USERS + "*", Permission.CREATE); grant(allUsers, RefNames.REFS_USERS + "*", Permission.PUSH); String userRef = RefNames.refsUsers(new Account.Id(seq.nextAccountId())); TestRepository<InMemoryRepository> allUsersRepo = cloneProject(allUsers); PushOneCommit.Result r = pushFactory.create(db, admin.getIdent(), allUsersRepo).to(userRef); r.assertErrorStatus(); assertThat(r.getMessage()).contains("Not allowed to create user branch."); try (Repository repo = repoManager.openRepository(allUsers)) { assertThat(repo.exactRef(userRef)).isNull(); } } @Test @Sandboxed public void createUserBranchWithAccessDatabaseCapability() throws Exception { allowGlobalCapabilities(REGISTERED_USERS, GlobalCapability.ACCESS_DATABASE); grant(allUsers, RefNames.REFS_USERS + "*", Permission.CREATE); grant(allUsers, RefNames.REFS_USERS + "*", Permission.PUSH); String userRef = RefNames.refsUsers(new Account.Id(seq.nextAccountId())); TestRepository<InMemoryRepository> allUsersRepo = cloneProject(allUsers); pushFactory.create(db, admin.getIdent(), allUsersRepo).to(userRef).assertOkStatus(); try (Repository repo = repoManager.openRepository(allUsers)) { assertThat(repo.exactRef(userRef)).isNotNull(); } } @Test @Sandboxed public void cannotCreateNonUserBranchUnderRefsUsersWithAccessDatabaseCapability() throws Exception { allowGlobalCapabilities(REGISTERED_USERS, GlobalCapability.ACCESS_DATABASE); grant(allUsers, RefNames.REFS_USERS + "*", Permission.CREATE); grant(allUsers, RefNames.REFS_USERS + "*", Permission.PUSH); String userRef = RefNames.REFS_USERS + "foo"; TestRepository<InMemoryRepository> allUsersRepo = cloneProject(allUsers); PushOneCommit.Result r = pushFactory.create(db, admin.getIdent(), allUsersRepo).to(userRef); r.assertErrorStatus(); assertThat(r.getMessage()).contains("Not allowed to create non-user branch under refs/users/."); try (Repository repo = repoManager.openRepository(allUsers)) { assertThat(repo.exactRef(userRef)).isNull(); } } @Test @Sandboxed public void createDefaultUserBranch() throws Exception { try (Repository repo = repoManager.openRepository(allUsers)) { assertThat(repo.exactRef(RefNames.REFS_USERS_DEFAULT)).isNull(); } grant(allUsers, RefNames.REFS_USERS_DEFAULT, Permission.CREATE); grant(allUsers, RefNames.REFS_USERS_DEFAULT, Permission.PUSH); TestRepository<InMemoryRepository> allUsersRepo = cloneProject(allUsers); pushFactory .create(db, admin.getIdent(), allUsersRepo) .to(RefNames.REFS_USERS_DEFAULT) .assertOkStatus(); try (Repository repo = repoManager.openRepository(allUsers)) { assertThat(repo.exactRef(RefNames.REFS_USERS_DEFAULT)).isNotNull(); } } @Test @Sandboxed public void cannotDeleteUserBranch() throws Exception { grant( allUsers, RefNames.REFS_USERS + "${" + RefPattern.USERID_SHARDED + "}", Permission.DELETE, true, REGISTERED_USERS); TestRepository<InMemoryRepository> allUsersRepo = cloneProject(allUsers); String userRef = RefNames.refsUsers(admin.id); PushResult r = deleteRef(allUsersRepo, userRef); RemoteRefUpdate refUpdate = r.getRemoteUpdate(userRef); assertThat(refUpdate.getStatus()).isEqualTo(RemoteRefUpdate.Status.REJECTED_OTHER_REASON); assertThat(refUpdate.getMessage()).contains("Not allowed to delete user branch."); try (Repository repo = repoManager.openRepository(allUsers)) { assertThat(repo.exactRef(userRef)).isNotNull(); } } @Test @Sandboxed public void deleteUserBranchWithAccessDatabaseCapability() throws Exception { allowGlobalCapabilities(REGISTERED_USERS, GlobalCapability.ACCESS_DATABASE); grant( allUsers, RefNames.REFS_USERS + "${" + RefPattern.USERID_SHARDED + "}", Permission.DELETE, true, REGISTERED_USERS); TestRepository<InMemoryRepository> allUsersRepo = cloneProject(allUsers); String userRef = RefNames.refsUsers(admin.id); PushResult r = deleteRef(allUsersRepo, userRef); RemoteRefUpdate refUpdate = r.getRemoteUpdate(userRef); assertThat(refUpdate.getStatus()).isEqualTo(RemoteRefUpdate.Status.OK); try (Repository repo = repoManager.openRepository(allUsers)) { assertThat(repo.exactRef(userRef)).isNull(); } assertThat(accountCache.getOrNull(admin.id)).isNull(); assertThat(accountQueryProvider.get().byDefault(admin.id.toString())).isEmpty(); } @Test public void addGpgKey() throws Exception { TestKey key = validKeyWithoutExpiration(); String id = key.getKeyIdString(); addExternalIdEmail(admin, "[email protected]"); assertKeyMapContains(key, addGpgKey(key.getPublicKeyArmored())); assertKeys(key); setApiUser(user); exception.expect(ResourceNotFoundException.class); exception.expectMessage(id); gApi.accounts().self().gpgKey(id).get(); } @Test public void reAddExistingGpgKey() throws Exception { addExternalIdEmail(admin, "[email protected]"); TestKey key = validKeyWithSecondUserId(); String id = key.getKeyIdString(); PGPPublicKey pk = key.getPublicKey(); GpgKeyInfo info = addGpgKey(armor(pk)).get(id); assertThat(info.userIds).hasSize(2); assertIteratorSize(2, getOnlyKeyFromStore(key).getUserIDs()); pk = PGPPublicKey.removeCertification(pk, "foo:myId"); info = addGpgKey(armor(pk)).get(id); assertThat(info.userIds).hasSize(1); assertIteratorSize(1, getOnlyKeyFromStore(key).getUserIDs()); } @Test public void addOtherUsersGpgKey_Conflict() throws Exception { // Both users have a matching external ID for this key. addExternalIdEmail(admin, "[email protected]"); externalIdsUpdate.insert(ExternalId.create("foo", "myId", user.getId())); accountIndexedCounter.assertReindexOf(user); TestKey key = validKeyWithSecondUserId(); addGpgKey(key.getPublicKeyArmored()); setApiUser(user); exception.expect(ResourceConflictException.class); exception.expectMessage("GPG key already associated with another account"); addGpgKey(key.getPublicKeyArmored()); } @Test public void listGpgKeys() throws Exception { List<TestKey> keys = allValidKeys(); List<String> toAdd = new ArrayList<>(keys.size()); for (TestKey key : keys) { addExternalIdEmail(admin, PushCertificateIdent.parse(key.getFirstUserId()).getEmailAddress()); toAdd.add(key.getPublicKeyArmored()); } gApi.accounts().self().putGpgKeys(toAdd, ImmutableList.<String>of()); assertKeys(keys); accountIndexedCounter.assertReindexOf(admin); } @Test public void deleteGpgKey() throws Exception { TestKey key = validKeyWithoutExpiration(); String id = key.getKeyIdString(); addExternalIdEmail(admin, "[email protected]"); addGpgKey(key.getPublicKeyArmored()); assertKeys(key); gApi.accounts().self().gpgKey(id).delete(); accountIndexedCounter.assertReindexOf(admin); assertKeys(); exception.expect(ResourceNotFoundException.class); exception.expectMessage(id); gApi.accounts().self().gpgKey(id).get(); } @Test public void addAndRemoveGpgKeys() throws Exception { for (TestKey key : allValidKeys()) { addExternalIdEmail(admin, PushCertificateIdent.parse(key.getFirstUserId()).getEmailAddress()); } TestKey key1 = validKeyWithoutExpiration(); TestKey key2 = validKeyWithExpiration(); TestKey key5 = validKeyWithSecondUserId(); Map<String, GpgKeyInfo> infos = gApi.accounts() .self() .putGpgKeys( ImmutableList.of(key1.getPublicKeyArmored(), key2.getPublicKeyArmored()), ImmutableList.of(key5.getKeyIdString())); assertThat(infos.keySet()).containsExactly(key1.getKeyIdString(), key2.getKeyIdString()); assertKeys(key1, key2); accountIndexedCounter.assertReindexOf(admin); infos = gApi.accounts() .self() .putGpgKeys( ImmutableList.of(key5.getPublicKeyArmored()), ImmutableList.of(key1.getKeyIdString())); assertThat(infos.keySet()).containsExactly(key1.getKeyIdString(), key5.getKeyIdString()); assertKeyMapContains(key5, infos); assertThat(infos.get(key1.getKeyIdString()).key).isNull(); assertKeys(key2, key5); accountIndexedCounter.assertReindexOf(admin); exception.expect(BadRequestException.class); exception.expectMessage("Cannot both add and delete key: " + keyToString(key2.getPublicKey())); infos = gApi.accounts() .self() .putGpgKeys( ImmutableList.of(key2.getPublicKeyArmored()), ImmutableList.of(key2.getKeyIdString())); } @Test public void addMalformedGpgKey() throws Exception { String key = "-----BEGIN PGP PUBLIC KEY BLOCK-----\n\ntest\n-----END PGP PUBLIC KEY BLOCK-----"; exception.expect(BadRequestException.class); exception.expectMessage("Failed to parse GPG keys"); addGpgKey(key); } @Test @UseSsh public void sshKeys() throws Exception { // // The test account should initially have exactly one ssh key List<SshKeyInfo> info = gApi.accounts().self().listSshKeys(); assertThat(info).hasSize(1); assertSequenceNumbers(info); SshKeyInfo key = info.get(0); String inital = AccountCreator.publicKey(admin.sshKey, admin.email); assertThat(key.sshPublicKey).isEqualTo(inital); accountIndexedCounter.assertNoReindex(); // Add a new key String newKey = AccountCreator.publicKey(AccountCreator.genSshKey(), admin.email); gApi.accounts().self().addSshKey(newKey); info = gApi.accounts().self().listSshKeys(); assertThat(info).hasSize(2); assertSequenceNumbers(info); accountIndexedCounter.assertReindexOf(admin); // Add an existing key (the request succeeds, but the key isn't added again) gApi.accounts().self().addSshKey(inital); info = gApi.accounts().self().listSshKeys(); assertThat(info).hasSize(2); assertSequenceNumbers(info); accountIndexedCounter.assertNoReindex(); // Add another new key String newKey2 = AccountCreator.publicKey(AccountCreator.genSshKey(), admin.email); gApi.accounts().self().addSshKey(newKey2); info = gApi.accounts().self().listSshKeys(); assertThat(info).hasSize(3); assertSequenceNumbers(info); accountIndexedCounter.assertReindexOf(admin); // Delete second key gApi.accounts().self().deleteSshKey(2); info = gApi.accounts().self().listSshKeys(); assertThat(info).hasSize(2); assertThat(info.get(0).seq).isEqualTo(1); assertThat(info.get(1).seq).isEqualTo(3); accountIndexedCounter.assertReindexOf(admin); } // reindex is tested by {@link AbstractQueryAccountsTest#reindex} @Test public void reindexPermissions() throws Exception { // admin can reindex any account setApiUser(admin); gApi.accounts().id(user.username).index(); accountIndexedCounter.assertReindexOf(user); // user can reindex own account setApiUser(user); gApi.accounts().self().index(); accountIndexedCounter.assertReindexOf(user); // user cannot reindex any account exception.expect(AuthException.class); exception.expectMessage("modify account not permitted"); gApi.accounts().id(admin.username).index(); } @Test @Sandboxed public void checkConsistency() throws Exception { allowGlobalCapabilities(REGISTERED_USERS, GlobalCapability.ACCESS_DATABASE); resetCurrentApiUser(); // Create an account with a preferred email. String username = name("foo"); String email = username + "@example.com"; TestAccount account = accountCreator.create(username, email, "Foo Bar"); ConsistencyCheckInput input = new ConsistencyCheckInput(); input.checkAccounts = new CheckAccountsInput(); ConsistencyCheckInfo checkInfo = gApi.config().server().checkConsistency(input); assertThat(checkInfo.checkAccountsResult.problems).isEmpty(); Set<ConsistencyProblemInfo> expectedProblems = new HashSet<>(); // Delete the external ID for the preferred email. This makes the account inconsistent since it // now doesn't have an external ID for its preferred email. externalIdsUpdate.delete(ExternalId.createEmail(account.getId(), email)); expectedProblems.add( new ConsistencyProblemInfo( ConsistencyProblemInfo.Status.ERROR, "Account '" + account.getId().get() + "' has no external ID for its preferred email '" + email + "'")); checkInfo = gApi.config().server().checkConsistency(input); assertThat(checkInfo.checkAccountsResult.problems).hasSize(expectedProblems.size()); assertThat(checkInfo.checkAccountsResult.problems).containsExactlyElementsIn(expectedProblems); } @Test public void internalQueryFindActiveAndInactiveAccounts() throws Exception { String name = name("foo"); assertThat(accountQueryProvider.get().byDefault(name)).isEmpty(); TestAccount foo1 = accountCreator.create(name + "-1"); assertThat(gApi.accounts().id(foo1.username).getActive()).isTrue(); TestAccount foo2 = accountCreator.create(name + "-2"); gApi.accounts().id(foo2.username).setActive(false); assertThat(gApi.accounts().id(foo2.username).getActive()).isFalse(); assertThat(accountQueryProvider.get().byDefault(name)).hasSize(2); } @Test public void checkMetaId() throws Exception { // metaId is set when account is loaded assertThat(accounts.get(admin.getId()).getMetaId()).isEqualTo(getMetaId(admin.getId())); // metaId is set when account is created AccountsUpdate au = accountsUpdate.create(); Account.Id accountId = new Account.Id(seq.nextAccountId()); Account account = au.insert(accountId, a -> {}); assertThat(account.getMetaId()).isEqualTo(getMetaId(accountId)); // metaId is set when account is updated Account updatedAccount = au.update(accountId, a -> a.setFullName("foo")); assertThat(account.getMetaId()).isNotEqualTo(updatedAccount.getMetaId()); assertThat(updatedAccount.getMetaId()).isEqualTo(getMetaId(accountId)); // metaId is set when account is replaced Account newAccount = new Account(accountId, TimeUtil.nowTs()); au.replace(newAccount); assertThat(updatedAccount.getMetaId()).isNotEqualTo(newAccount.getMetaId()); assertThat(newAccount.getMetaId()).isEqualTo(getMetaId(accountId)); } private EmailInput newEmailInput(String email, boolean noConfirmation) { EmailInput input = new EmailInput(); input.email = email; input.noConfirmation = noConfirmation; return input; } private EmailInput newEmailInput(String email) { return newEmailInput(email, true); } private String getMetaId(Account.Id accountId) throws IOException { try (Repository repo = repoManager.openRepository(allUsers); RevWalk rw = new RevWalk(repo); ObjectReader or = repo.newObjectReader()) { Ref ref = repo.exactRef(RefNames.refsUsers(accountId)); return ref != null ? ref.getObjectId().name() : null; } } @Test public void groups() throws Exception { assertGroups( admin.username, ImmutableList.of("Anonymous Users", "Registered Users", "Administrators")); // TODO: update when test user is fixed to be included in "Anonymous Users" and // "Registered Users" groups assertGroups(user.username, ImmutableList.of()); String group = createGroup("group"); String newUser = createAccount("user1", group); assertGroups(newUser, ImmutableList.of(group)); } private void assertGroups(String user, List<String> expected) throws Exception { List<String> actual = gApi.accounts().id(user).getGroups().stream().map(g -> g.name).collect(toList()); assertThat(actual).containsExactlyElementsIn(expected); } private void assertSequenceNumbers(List<SshKeyInfo> sshKeys) { int seq = 1; for (SshKeyInfo key : sshKeys) { assertThat(key.seq).isEqualTo(seq++); } } private PGPPublicKey getOnlyKeyFromStore(TestKey key) throws Exception { try (PublicKeyStore store = publicKeyStoreProvider.get()) { Iterable<PGPPublicKeyRing> keys = store.get(key.getKeyId()); assertThat(keys).hasSize(1); return keys.iterator().next().getPublicKey(); } } private static String armor(PGPPublicKey key) throws Exception { ByteArrayOutputStream out = new ByteArrayOutputStream(4096); try (ArmoredOutputStream aout = new ArmoredOutputStream(out)) { key.encode(aout); } return new String(out.toByteArray(), UTF_8); } private static void assertIteratorSize(int size, Iterator<?> it) { List<?> lst = ImmutableList.copyOf(it); assertThat(lst).hasSize(size); } private static void assertKeyMapContains(TestKey expected, Map<String, GpgKeyInfo> actualMap) { GpgKeyInfo actual = actualMap.get(expected.getKeyIdString()); assertThat(actual).isNotNull(); assertThat(actual.id).isNull(); actual.id = expected.getKeyIdString(); assertKeyEquals(expected, actual); } private void assertKeys(TestKey... expectedKeys) throws Exception { assertKeys(Arrays.asList(expectedKeys)); } private void assertKeys(Iterable<TestKey> expectedKeys) throws Exception { // Check via API. FluentIterable<TestKey> expected = FluentIterable.from(expectedKeys); Map<String, GpgKeyInfo> keyMap = gApi.accounts().self().listGpgKeys(); assertThat(keyMap.keySet()) .named("keys returned by listGpgKeys()") .containsExactlyElementsIn(expected.transform(TestKey::getKeyIdString)); for (TestKey key : expected) { assertKeyEquals(key, gApi.accounts().self().gpgKey(key.getKeyIdString()).get()); assertKeyEquals( key, gApi.accounts() .self() .gpgKey(Fingerprint.toString(key.getPublicKey().getFingerprint())) .get()); assertKeyMapContains(key, keyMap); } // Check raw external IDs. Account.Id currAccountId = atrScope.get().getUser().getAccountId(); Iterable<String> expectedFps = expected.transform(k -> BaseEncoding.base16().encode(k.getPublicKey().getFingerprint())); Iterable<String> actualFps = externalIds .byAccount(currAccountId, SCHEME_GPGKEY) .stream() .map(e -> e.key().id()) .collect(toSet()); assertThat(actualFps).named("external IDs in database").containsExactlyElementsIn(expectedFps); // Check raw stored keys. for (TestKey key : expected) { getOnlyKeyFromStore(key); } } private static void assertKeyEquals(TestKey expected, GpgKeyInfo actual) { String id = expected.getKeyIdString(); assertThat(actual.id).named(id).isEqualTo(id); assertThat(actual.fingerprint) .named(id) .isEqualTo(Fingerprint.toString(expected.getPublicKey().getFingerprint())); List<String> userIds = ImmutableList.copyOf(expected.getPublicKey().getUserIDs()); assertThat(actual.userIds).named(id).containsExactlyElementsIn(userIds); assertThat(actual.key).named(id).startsWith("-----BEGIN PGP PUBLIC KEY BLOCK-----\n"); assertThat(actual.status).isEqualTo(GpgKeyInfo.Status.TRUSTED); assertThat(actual.problems).isEmpty(); } private void addExternalIdEmail(TestAccount account, String email) throws Exception { checkNotNull(email); externalIdsUpdate.insert( ExternalId.createWithEmail(name("test"), email, account.getId(), email)); accountIndexedCounter.assertReindexOf(account); setApiUser(account); } private Map<String, GpgKeyInfo> addGpgKey(String armored) throws Exception { Map<String, GpgKeyInfo> gpgKeys = gApi.accounts().self().putGpgKeys(ImmutableList.of(armored), ImmutableList.<String>of()); accountIndexedCounter.assertReindexOf(gApi.accounts().self().get()); return gpgKeys; } private void assertUser(AccountInfo info, TestAccount account) throws Exception { assertThat(info.name).isEqualTo(account.fullName); assertThat(info.email).isEqualTo(account.email); assertThat(info.username).isEqualTo(account.username); assertThat(info.status).isEqualTo(account.status); } private Set<String> getEmails() throws RestApiException { return gApi.accounts().self().getEmails().stream().map(e -> e.email).collect(toSet()); } private void assertEmail(Set<Account.Id> accounts, TestAccount expectedAccount) { assertThat(accounts).hasSize(1); assertThat(Iterables.getOnlyElement(accounts)).isEqualTo(expectedAccount.getId()); } private Config getAccountConfig(TestRepository<?> allUsersRepo) throws Exception { Config ac = new Config(); try (TreeWalk tw = TreeWalk.forPath( allUsersRepo.getRepository(), AccountConfig.ACCOUNT_CONFIG, getHead(allUsersRepo.getRepository()).getTree())) { assertThat(tw).isNotNull(); ac.fromText( new String( allUsersRepo .getRevWalk() .getObjectReader() .open(tw.getObjectId(0), OBJ_BLOB) .getBytes(), UTF_8)); } return ac; } /** Checks if an account is indexed the correct number of times. */ private static class AccountIndexedCounter implements AccountIndexedListener { private final AtomicLongMap<Integer> countsByAccount = AtomicLongMap.create(); @Override public void onAccountIndexed(int id) { countsByAccount.incrementAndGet(id); } void clear() { countsByAccount.clear(); } long getCount(Account.Id accountId) { return countsByAccount.get(accountId.get()); } void assertReindexOf(TestAccount testAccount) { assertReindexOf(testAccount, 1); } void assertReindexOf(AccountInfo accountInfo) { assertReindexOf(new Account.Id(accountInfo._accountId), 1); } void assertReindexOf(TestAccount testAccount, int expectedCount) { assertThat(getCount(testAccount.id)).isEqualTo(expectedCount); assertThat(countsByAccount).hasSize(1); clear(); } void assertReindexOf(Account.Id accountId, int expectedCount) { assertThat(getCount(accountId)).isEqualTo(expectedCount); countsByAccount.remove(accountId.get()); } void assertNoReindex() { assertThat(countsByAccount).isEmpty(); } } private static class RefUpdateCounter implements GitReferenceUpdatedListener { private final AtomicLongMap<String> countsByProjectRefs = AtomicLongMap.create(); static String projectRef(Project.NameKey project, String ref) { return projectRef(project.get(), ref); } static String projectRef(String project, String ref) { return project + ":" + ref; } @Override public void onGitReferenceUpdated(Event event) { countsByProjectRefs.incrementAndGet(projectRef(event.getProjectName(), event.getRefName())); } void clear() { countsByProjectRefs.clear(); } long getCount(String projectRef) { return countsByProjectRefs.get(projectRef); } void assertRefUpdateFor(String... projectRefs) { Map<String, Integer> expectedRefUpdateCounts = new HashMap<>(); for (String projectRef : projectRefs) { expectedRefUpdateCounts.put(projectRef, 1); } assertRefUpdateFor(expectedRefUpdateCounts); } void assertRefUpdateFor(Map<String, Integer> expectedProjectRefUpdateCounts) { for (Map.Entry<String, Integer> e : expectedProjectRefUpdateCounts.entrySet()) { assertThat(getCount(e.getKey())).isEqualTo(e.getValue()); } assertThat(countsByProjectRefs).hasSize(expectedProjectRefUpdateCounts.size()); clear(); } } }
gerrit-review/gerrit
javatests/com/google/gerrit/acceptance/api/accounts/AccountIT.java
Java
apache-2.0
76,948
/* * Licensed to Metamarkets Group Inc. (Metamarkets) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. Metamarkets 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 io.druid.segment; import java.util.function.IntSupplier; /** * Could be used as a simple "row number supplier" for {@link RowPointer} implementations. */ public final class RowNumCounter implements IntSupplier { private int rowNum = 0; public RowNumCounter() { } public RowNumCounter(int initialRowNum) { this.rowNum = initialRowNum; } @Override public int getAsInt() { return rowNum; } public void increment() { rowNum++; } }
b-slim/druid
processing/src/main/java/io/druid/segment/RowNumCounter.java
Java
apache-2.0
1,290
package com.berico.dropwizard.nagios.checktasks; import com.bericotech.dropwizard.nagios.Level; import com.bericotech.dropwizard.nagios.MessagePayload; import com.bericotech.dropwizard.nagios.MessagePayloadBuilder; import com.bericotech.dropwizard.nagios.NagiosCheckTask; import com.google.common.collect.ImmutableMultimap; public class FailingCriticalTask extends NagiosCheckTask { public static final String TASKNAME = "critical-task"; public static final String MESSAGE = "critical"; public FailingCriticalTask() { super(TASKNAME); } @Override public MessagePayload performCheck(ImmutableMultimap<String, String> requestParameters) throws Throwable { return new MessagePayloadBuilder().withLevel(Level.CRITICAL).withMessage(MESSAGE).build(); } }
Berico-Technologies/Nagios-Dropwizard
src/integration-test/java/com/berico/dropwizard/nagios/checktasks/FailingCriticalTask.java
Java
apache-2.0
798
package me.tunsi.modeler; import java.io.IOException; import java.io.InputStream; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.commons.io.IOUtils; import me.tunsi.web.BaseServlet; @WebServlet(name = "pluginServlet", urlPatterns = "/service/editor/plugins") public class PluginServlet extends BaseServlet { /** * */ private static final long serialVersionUID = 4237631603242644804L; @Override protected void doInternal(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { InputStream pluginStream = this.getClass().getClassLoader().getResourceAsStream("plugins.xml"); resp.setContentType("application/xml"); IOUtils.write(IOUtils.toByteArray(pluginStream), resp.getOutputStream()); } }
tunsi/activiti-servlet3
src/main/java/me/tunsi/modeler/PluginServlet.java
Java
apache-2.0
894
/** * */ package uk.ac.manchester.cs.pronto.util; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Random; import java.util.Set; /** * <p>Title: SetUtils</p> * * <p>Description: * TODO Merge with org.mindswap.pellet.utils.SetUtils * </p> * * <p>Copyright: Copyright (c) 2007, 2008</p> * * <p>Company: Clark & Parsia, LLC. <http://www.clarkparsia.com></p> * * @author pavel */ public class SetUtils { public static void main(String[] args) { kSubsets(Arrays.asList(new Integer[] {1, 2, 3, 4, 5}), 3); } /** * Compute all unordered subsets of the length k. * * @param list * @param k * @return */ public static <T> Set<Set<T>> kSubsets(List<T> list, int k) { long max = numOfSubsets( list.size(), k ); Set<Set<T>> result = new HashSet<Set<T>>((int)max); for( int index = 0; index < max; index++ ) { result.add(subset( list, k, index )); } return result; } public static long numOfSubsets(int size, int k) { if( (0 == k) || (size == k) ) { return 1; } return numOfSubsets( size - 1, k - 1 ) + numOfSubsets( size - 1, k ); } public static <T> Set<T> subset(List<T> list, int k, long index) { int size = list.size(); Set<T> result = new HashSet<T>(); for( int slotValue = 1; slotValue <= size; slotValue++ ) { if( 0 == k) { break; } long threshold = numOfSubsets( size - slotValue, k - 1 ); if( index < threshold ) { //System.out.print( list.get(slotValue - 1) + "\t" ); result.add(list.get(slotValue - 1)); k--; } else if( index >= threshold ) { index = index - threshold; } } //System.out.println(); return result; } public static <T> void printAll(List<T> list, int k) { long max = numOfSubsets( list.size(), k ); for( int index = 0; index < max; index++ ) { subset( list, k, index ); } } /* * Computes intersection of a collection of sets */ public static <T> Set<T> intersection(Collection<Set<T>> sets) { Set<T> result = new HashSet<T>(); result.addAll( sets.iterator().next()); for (Set<T> set : sets) { result.retainAll( set ); } return result; } /* * Randomly picks an element from the set */ public static <T> T pickRandomElement(Set<T> set) { int rnd = (int) (Math.random() * (set.size() - 1)); Iterator<T> iter = set.iterator(); T result = iter.next(); for (; rnd > 0; rnd--) { result = iter.next(); } return result; } public static <T> Set<T> pickRandomSubset(Set<T> set, int size) { Random rnd = new Random(); List<T> list = new ArrayList<T>(set); /* * This might be inefficient if binomial coefficients get very large */ return SetUtils.subset( list, size, rnd.nextInt( biCoeff(set.size(), size) ) ); } /* * Simpler version */ public static <T> Set<T> pickRandomSubset2(Set<T> set, int size) { Random rnd = new Random(); Set<T> subset = new HashSet<T>(size); List<T> list = new ArrayList<T>(set); int index = 0; if (size >= set.size()) { return set; } for (int i = 0; i < size; i++) { index = rnd.nextInt(list.size()); subset.add( list.remove( index ) ); } return subset; } /* * WARNING: the function does not check that there exist that many subsets * of the given size. Checking would require computing of a binomial coefficient * which might be slow. Other approximations might be used (see Stirling approximation * for example). * Currently the function stops after stumbling over a number of duplicates */ public static <T> Set<Set<T>> pickRandomSubsets(Set<T> set, int size, int number) { Set<Set<T>> subsets = new HashSet<Set<T>>(number); int dups = 0; if (size > set.size()) { return null; } while (subsets.size() < number && dups < set.size()) { if (!subsets.add( pickRandomSubset2(set, size) )) { dups++; } else { dups = 0; } } return subsets; } /* * Computes binomial coefficient (n,k) */ public static int biCoeff(int n, int k) { if( (0 == k) || (n == k) ) { return 1; } return biCoeff( n - 1, k - 1 ) + biCoeff( n - 1, k ); } /** * Checks if two collections have a non-empty intersection */ public static <T> boolean intersects( Collection<T> collection1, Collection<T> collection2 ) { for (T elem : collection1) if (collection2.contains( elem )) return true; return false; } public static <T> Set<? extends T> intersection(Collection<? extends T> collection1 , Collection<? extends T> collection2) { HashSet<T> s = new HashSet<T>(collection1); s.retainAll( collection2 ); return s; } /* * Assuming that A is a smaller than B, this method computes A - B */ public static <T> Set<T> setDifference(Set<T> setA, Set<T> setB) { HashSet<T> s = new HashSet<T>(); for (T element : setA) { if (!setB.contains( element )) s.add( element ); } return s; } public static <T> Set<T> flatten(Set<Set<T>> sets) { HashSet<T> s = new HashSet<T>(sets.size() * 2); for (Set<T> set : sets) s.addAll( set ); return s; } }
klinovp/pronto
src/uk/ac/manchester/cs/pronto/util/SetUtils.java
Java
apache-2.0
5,307
/* * Copyright (c) 2017. Kaede <[email protected])> */ package moe.studio.log; import org.junit.Test; import static org.junit.Assert.*; /** * Example local unit test, which will execute on the development machine (host). * * @see <a href="http://d.android.com/tools/testing">Testing documentation</a> */ public class ExampleUnitTest { @Test public void addition_isCorrect() throws Exception { assertEquals(4, 2 + 2); } }
kaedea/b-log
logger/src/test/java/moe/kaede/log/ExampleUnitTest.java
Java
apache-2.0
453
/* * Copyright 2002-2013 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.web.socket; import java.util.List; /** * An interface for WebSocket handlers that support sub-protocols as defined in RFC 6455. * * @author Rossen Stoyanchev * @since 4.0 * @see WebSocketHandler * @see <a href="https://tools.ietf.org/html/rfc6455#section-1.9">RFC-6455 section 1.9</a> */ public interface SubProtocolCapable { /** * Return the list of supported sub-protocols. */ List<String> getSubProtocols(); }
spring-projects/spring-framework
spring-websocket/src/main/java/org/springframework/web/socket/SubProtocolCapable.java
Java
apache-2.0
1,081
/* * Copyright (c) 2017, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.wso2.siddhi.plugins.idea.sdk; import com.intellij.openapi.application.PathMacros; import com.intellij.openapi.util.SystemInfo; import com.intellij.openapi.util.io.FileUtil; import com.intellij.util.EnvironmentUtil; import com.intellij.util.PathUtil; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import org.wso2.siddhi.plugins.idea.SiddhiConstants; public class SiddhiEnvironmentUtil { private SiddhiEnvironmentUtil() { } @NotNull public static String getBinaryFileNameForPath(@NotNull String path) { String resultBinaryName = FileUtil.getNameWithoutExtension(PathUtil.getFileName(path)); return SystemInfo.isWindows ? resultBinaryName + ".bat" : resultBinaryName; } @Nullable public static String retrieveRepositoryPathFromEnvironment() { String path = EnvironmentUtil.getValue(SiddhiConstants.SIDDHI_REPOSITORY); return path != null ? path : PathMacros.getInstance().getValue(SiddhiConstants.SIDDHI_REPOSITORY); } }
RAVEENSR/Siddhi-Intellij-Plugin
src/main/java/org/wso2/siddhi/plugins/idea/sdk/SiddhiEnvironmentUtil.java
Java
apache-2.0
1,687
/* * Copyright 2016 Zot201 * * 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. */ @javax.annotation.ParametersAreNonnullByDefault @mcp.MethodsReturnNonnullByDefault package zotmc.onlysilver.util;
Zot201/OnlySilver
src/main/java/zotmc/onlysilver/util/package-info.java
Java
apache-2.0
704
/* * Copyright 2014-2016 by Cloudsoft Corporation Limited * * 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 blueprints; import java.io.File; import java.io.IOException; import java.util.concurrent.Callable; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicReference; import javax.ws.rs.core.Response; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.testng.annotations.BeforeClass; import org.testng.annotations.Parameters; import org.testng.annotations.Test; import com.google.common.base.Charsets; import com.google.common.base.Joiner; import com.google.common.collect.ImmutableMap; import com.google.common.io.Files; import org.apache.brooklyn.rest.client.BrooklynApi; import org.apache.brooklyn.rest.domain.Status; import org.apache.brooklyn.rest.domain.TaskSummary; import org.apache.brooklyn.util.exceptions.Exceptions; import org.apache.brooklyn.util.repeat.Repeater; import org.apache.brooklyn.util.time.Duration; public class BlueprintIntegrationTest { private static final Logger LOG = LoggerFactory.getLogger(BlueprintIntegrationTest.class); private static final String BLUEPRINT_DIRECTORY = "src/main/assembly/files/blueprints/"; String brooklynUrl; @BeforeClass(alwaysRun = true) @Parameters({"brooklyn"}) public void setSpec(String brooklyn) { brooklynUrl = brooklyn; LOG.info("Running {} in {}", getClass().getName(), brooklyn); } public void testBlueprintDeploys(String name) { BrooklynApi api = new BrooklynApi(brooklynUrl); LOG.info("Testing " + name); String blueprint = loadBlueprint(name); Response r = api.getApplicationApi().createFromYaml(blueprint); final TaskSummary task = BrooklynApi.getEntity(r, TaskSummary.class); final String application = task.getEntityId(); try { assertAppStatusEventually(api, application, Status.RUNNING); } finally { LOG.info("Stopping {} (deployed from {})", application, name); api.getEffectorApi().invoke(application, application, "stop", "never", ImmutableMap.<String, Object>of()); } } @Test(groups = "Integration") public void testNodeJsTodo() { testBlueprintDeploys(BLUEPRINT_DIRECTORY + "nodejs-todo.yaml"); } @Test(groups = "Integration") public void testCouchbase() { testBlueprintDeploys(BLUEPRINT_DIRECTORY + "couchbase.yaml"); } @Test(groups = "Integration") public void testCouchbaseWithPillofight() { testBlueprintDeploys(BLUEPRINT_DIRECTORY + "couchbase-with-pillowfight.yaml"); } @Test(groups = "Integration") public void testDockerfilMysql() { testBlueprintDeploys(BLUEPRINT_DIRECTORY + "dockerfile-mysql.yaml"); } @Test(groups = "Integration") public void testRiakWebappCluster() { testBlueprintDeploys(BLUEPRINT_DIRECTORY + "riak-webapp-cluster.yaml"); } @Test(groups = "Integration") public void testTomcatApplication() { testBlueprintDeploys(BLUEPRINT_DIRECTORY + "tomcat-application.yaml"); } @Test(groups = "Integration") public void testTomcatApplicationWithVolumes() { testBlueprintDeploys(BLUEPRINT_DIRECTORY + "tomcat-application-with-volumes.yaml"); } @Test(groups = "Integration") public void testTomcatClusterWithMysql() { testBlueprintDeploys(BLUEPRINT_DIRECTORY + "tomcat-cluster-with-mysql.yaml"); } @Test(groups = "Integration") public void testTomcatSolrApplication() { testBlueprintDeploys(BLUEPRINT_DIRECTORY + "tomcat-solr-application.yaml"); } private String loadBlueprint(String name) { try { return Joiner.on('\n').join(Files.readLines(new File(name), Charsets.UTF_8)); } catch (IOException e) { throw Exceptions.propagate(e); } } /** * Polls Brooklyn until the given application has the given status. Quits early if the application's * status is {@link brooklyn.rest.domain.Status#ERROR} or {@link brooklyn.rest.domain.Status#UNKNOWN} * and desiredStatus is something else. * @return the final polled status */ protected Status assertAppStatusEventually(final BrooklynApi api, final String application, final Status desiredStatus) { final AtomicReference<Status> appStatus = new AtomicReference<Status>(Status.UNKNOWN); final Duration timeout = Duration.of(10, TimeUnit.MINUTES); final boolean shortcutOnError = !Status.ERROR.equals(desiredStatus) && !Status.UNKNOWN.equals(desiredStatus); LOG.info("Waiting " + timeout + " for application " + application + " to be " + desiredStatus); boolean finalAppStatusKnown = Repeater.create("Waiting for application " + application + " status to be " + desiredStatus) .every(Duration.FIVE_SECONDS) .limitTimeTo(timeout) .rethrowExceptionImmediately() .until(new Callable<Boolean>() { @Override public Boolean call() throws Exception { Status status = api.getApplicationApi().get(application).getStatus(); LOG.debug("Application " + application + " status is: " + status); appStatus.set(status); return desiredStatus.equals(status) || (shortcutOnError && (Status.ERROR.equals(status) || Status.UNKNOWN.equals(status))); } }) .run(); if (appStatus.get().equals(desiredStatus)) { LOG.info("Application " + application + " is " + desiredStatus.name()); } else { String message = "Application is not " + desiredStatus.name() + " within " + timeout + ". Status is: " + appStatus.get(); LOG.error(message); throw new RuntimeException(message); } return appStatus.get(); } }
andreaturli/clocker
dist/src/test/java/blueprints/BlueprintIntegrationTest.java
Java
apache-2.0
6,570
// Copyright (c) 2017, Baidu.com, Inc. All Rights Reserved // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, // software distributed under the License is distributed on an // "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. package com.baidu.palo.broker.bos; /** * <p> * Holds basic metadata for a file stored in a {@link NativeFileSystemStore}. * </p> */ class FileMetadata { private final String key; private final long length; private final long lastModified; public FileMetadata(String key, long length, long lastModified) { this.key = key; this.length = length; this.lastModified = lastModified; } public String getKey() { return key; } public long getLength() { return length; } public long getLastModified() { return lastModified; } @Override public String toString() { return "FileMetadata[" + key + ", " + length + ", " + lastModified + "]"; } }
lingbin/palo
fs_brokers/baidu_bos_broker/src/com/baidu/palo/broker/bos/FileMetadata.java
Java
apache-2.0
1,387
package com.motetronica.apptutores; import android.content.Context; import android.support.test.InstrumentationRegistry; import android.support.test.runner.AndroidJUnit4; import org.junit.Test; import org.junit.runner.RunWith; import static org.junit.Assert.*; /** * Instrumentation test, which will execute on an Android device. * * @see <a href="http://d.android.com/tools/testing">Testing documentation</a> */ @RunWith(AndroidJUnit4.class) public class ExampleInstrumentedTest { @Test public void useAppContext() throws Exception { // Context of the app under test. Context appContext = InstrumentationRegistry.getTargetContext(); assertEquals("com.motetronica.apptutores", appContext.getPackageName()); } }
MOTEorg/AppTutores
app/src/androidTest/java/com/motetronica/apptutores/ExampleInstrumentedTest.java
Java
apache-2.0
756
/* * Licensed to The Apereo Foundation under one or more contributor license * agreements. See the NOTICE file distributed with this work for additional * information regarding copyright ownership. * * The Apereo Foundation 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 com.tle.web.scheduler; import com.tle.core.guice.Bind; import com.tle.core.scheduler.SchedulerService.Schedules; import com.tle.core.settings.service.ConfigurationService; import com.tle.web.freemarker.FreemarkerFactory; import com.tle.web.freemarker.annotations.ViewFactory; import com.tle.web.sections.SectionInfo; import com.tle.web.sections.SectionTree; import com.tle.web.sections.annotations.DirectEvent; import com.tle.web.sections.annotations.EventFactory; import com.tle.web.sections.annotations.EventHandlerMethod; import com.tle.web.sections.equella.annotation.PlugKey; import com.tle.web.sections.equella.layout.OneColumnLayout; import com.tle.web.sections.equella.layout.OneColumnLayout.OneColumnLayoutModel; import com.tle.web.sections.equella.receipt.ReceiptService; import com.tle.web.sections.equella.utils.KeyOption; import com.tle.web.sections.events.RenderEventContext; import com.tle.web.sections.events.SectionEvent; import com.tle.web.sections.events.js.EventGenerator; import com.tle.web.sections.render.GenericTemplateResult; import com.tle.web.sections.render.Label; import com.tle.web.sections.render.TemplateResult; import com.tle.web.sections.standard.Button; import com.tle.web.sections.standard.SingleSelectionList; import com.tle.web.sections.standard.annotations.Component; import com.tle.web.sections.standard.model.Option; import com.tle.web.sections.standard.model.SimpleHtmlListModel; import com.tle.web.settings.menu.SettingsUtils; import com.tle.web.template.Breadcrumbs; import com.tle.web.template.Decorations; import javax.inject.Inject; @Bind @SuppressWarnings("nls") public class RootScheduledTasksSettingsSection extends OneColumnLayout<OneColumnLayoutModel> { @PlugKey("scheduler.title") private static Label TITLE_LABEL; @PlugKey("save.receipt") private static Label SAVE_RECEIPT_LABEL; @PlugKey("hour.") private static String HOUR_KEY_PREFIX; @PlugKey("day.") private static String DAY_KEY_PREFIX; @ViewFactory private FreemarkerFactory viewFactory; @EventFactory private EventGenerator events; @Inject private ScheduledTasksPrivilegeTreeProvider securityProvider; @Inject private ReceiptService receiptService; @Inject private ConfigurationService configService; @Component private SingleSelectionList<Integer> dailyTaskHour; @Component private SingleSelectionList<Integer> weeklyTaskDay; @Component private SingleSelectionList<Integer> weeklyTaskHour; @Component @PlugKey("save") private Button saveButton; @Override public void registered(String id, SectionTree tree) { super.registered(id, tree); dailyTaskHour.setListModel(new RangeWithKeyPrefixListModel(0, 23, HOUR_KEY_PREFIX)); weeklyTaskDay.setListModel(new RangeWithKeyPrefixListModel(0, 6, DAY_KEY_PREFIX)); weeklyTaskHour.setListModel(new RangeWithKeyPrefixListModel(0, 23, HOUR_KEY_PREFIX)); saveButton.setClickHandler(events.getNamedHandler("save")); } @DirectEvent(priority = SectionEvent.PRIORITY_BEFORE_EVENTS) public void checkAuthorised(SectionInfo info) { securityProvider.checkAuthorised(); } @Override protected void addBreadcrumbsAndTitle( SectionInfo info, Decorations decorations, Breadcrumbs crumbs) { decorations.setTitle(TITLE_LABEL); crumbs.add(SettingsUtils.getBreadcrumb(info)); } @Override protected TemplateResult setupTemplate(RenderEventContext info) { Schedules s = configService.getProperties(new Schedules()); dailyTaskHour.setSelectedValue(info, s.getDailyTaskHour()); weeklyTaskDay.setSelectedValue(info, s.getWeeklyTaskDay()); weeklyTaskHour.setSelectedValue(info, s.getWeeklyTaskHour()); return new GenericTemplateResult( viewFactory.createNamedResult(BODY, "scheduler-settings.ftl", this)); } @EventHandlerMethod public void save(SectionInfo info) { Schedules s = new Schedules(); s.setDailyTaskHour(dailyTaskHour.getSelectedValue(info)); s.setWeeklyTaskDay(weeklyTaskDay.getSelectedValue(info)); s.setWeeklyTaskHour(weeklyTaskHour.getSelectedValue(info)); configService.setProperties(s); receiptService.setReceipt(SAVE_RECEIPT_LABEL); } public SingleSelectionList<Integer> getDailyTaskHour() { return dailyTaskHour; } public SingleSelectionList<Integer> getWeeklyTaskDay() { return weeklyTaskDay; } public SingleSelectionList<Integer> getWeeklyTaskHour() { return weeklyTaskHour; } public Button getSaveButton() { return saveButton; } @Override public Class<OneColumnLayout.OneColumnLayoutModel> getModelClass() { return OneColumnLayoutModel.class; } private static class RangeWithKeyPrefixListModel extends SimpleHtmlListModel<Integer> { private final String keyPrefix; public RangeWithKeyPrefixListModel(int from, int to, String keyPrefix) { this.keyPrefix = keyPrefix; for (int i = from; i <= to; i++) { add(i); } } @Override protected Option<Integer> convertToOption(Integer day) { return new KeyOption<Integer>(keyPrefix + day.intValue(), day.toString(), day); } } }
equella/Equella
Source/Plugins/Core/com.equella.core/src/com/tle/web/scheduler/RootScheduledTasksSettingsSection.java
Java
apache-2.0
5,914
/******************************************************************************* * Copyright 2011, 2012 Chris Banes. * * 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.job.view; import android.annotation.TargetApi; import android.util.Log; import android.view.View; import com.job.view.PullToRefreshBase.Mode; import com.job.view.PullToRefreshBase.State; @TargetApi(9) public final class OverscrollHelper { static final String LOG_TAG = "OverscrollHelper"; static final float DEFAULT_OVERSCROLL_SCALE = 1f; /** * Helper method for Overscrolling that encapsulates all of the necessary * function. * <p/> * This should only be used on AdapterView's such as ListView as it just * calls through to overScrollBy() with the scrollRange = 0. AdapterView's * do not have a scroll range (i.e. getScrollY() doesn't work). * * @param view - PullToRefreshView that is calling this. * @param deltaX - Change in X in pixels, passed through from from * overScrollBy call * @param scrollX - Current X scroll value in pixels before applying deltaY, * passed through from from overScrollBy call * @param deltaY - Change in Y in pixels, passed through from from * overScrollBy call * @param scrollY - Current Y scroll value in pixels before applying deltaY, * passed through from from overScrollBy call * @param isTouchEvent - true if this scroll operation is the result of a * touch event, passed through from from overScrollBy call */ public static void overScrollBy(final PullToRefreshBase<?> view, final int deltaX, final int scrollX, final int deltaY, final int scrollY, final boolean isTouchEvent) { overScrollBy(view, deltaX, scrollX, deltaY, scrollY, 0, isTouchEvent); } /** * Helper method for Overscrolling that encapsulates all of the necessary * function. This version of the call is used for Views that need to specify * a Scroll Range but scroll back to it's edge correctly. * * @param view - PullToRefreshView that is calling this. * @param deltaX - Change in X in pixels, passed through from from * overScrollBy call * @param scrollX - Current X scroll value in pixels before applying deltaY, * passed through from from overScrollBy call * @param deltaY - Change in Y in pixels, passed through from from * overScrollBy call * @param scrollY - Current Y scroll value in pixels before applying deltaY, * passed through from from overScrollBy call * @param scrollRange - Scroll Range of the View, specifically needed for * ScrollView * @param isTouchEvent - true if this scroll operation is the result of a * touch event, passed through from from overScrollBy call */ public static void overScrollBy(final PullToRefreshBase<?> view, final int deltaX, final int scrollX, final int deltaY, final int scrollY, final int scrollRange, final boolean isTouchEvent) { overScrollBy(view, deltaX, scrollX, deltaY, scrollY, scrollRange, 0, DEFAULT_OVERSCROLL_SCALE, isTouchEvent); } /** * Helper method for Overscrolling that encapsulates all of the necessary * function. This is the advanced version of the call. * * @param view - PullToRefreshView that is calling this. * @param deltaX - Change in X in pixels, passed through from from * overScrollBy call * @param scrollX - Current X scroll value in pixels before applying deltaY, * passed through from from overScrollBy call * @param deltaY - Change in Y in pixels, passed through from from * overScrollBy call * @param scrollY - Current Y scroll value in pixels before applying deltaY, * passed through from from overScrollBy call * @param scrollRange - Scroll Range of the View, specifically needed for * ScrollView * @param fuzzyThreshold - Threshold for which the values how fuzzy we * should treat the other values. Needed for WebView as it * doesn't always scroll back to it's edge. 0 = no fuzziness. * @param scaleFactor - Scale Factor for overscroll amount * @param isTouchEvent - true if this scroll operation is the result of a * touch event, passed through from from overScrollBy call */ public static void overScrollBy(final PullToRefreshBase<?> view, final int deltaX, final int scrollX, final int deltaY, final int scrollY, final int scrollRange, final int fuzzyThreshold, final float scaleFactor, final boolean isTouchEvent) { final int deltaValue, currentScrollValue, scrollValue; switch (view.getPullToRefreshScrollDirection()) { case HORIZONTAL: deltaValue = deltaX; scrollValue = scrollX; currentScrollValue = view.getScrollX(); break; case VERTICAL: default: deltaValue = deltaY; scrollValue = scrollY; currentScrollValue = view.getScrollY(); break; } // Check that OverScroll is enabled and that we're not currently // refreshing. if (view.isPullToRefreshOverScrollEnabled() && !view.isRefreshing()) { final Mode mode = view.getMode(); // Check that Pull-to-Refresh is enabled, and the event isn't from // touch if (mode.permitsPullToRefresh() && !isTouchEvent && deltaValue != 0) { final int newScrollValue = (deltaValue + scrollValue); if (PullToRefreshBase.DEBUG) { Log.d(LOG_TAG, "OverScroll. DeltaX: " + deltaX + ", ScrollX: " + scrollX + ", DeltaY: " + deltaY + ", ScrollY: " + scrollY + ", NewY: " + newScrollValue + ", ScrollRange: " + scrollRange + ", CurrentScroll: " + currentScrollValue); } if (newScrollValue < (0 - fuzzyThreshold)) { // Check the mode supports the overscroll direction, and // then move scroll if (mode.showHeaderLoadingLayout()) { // If we're currently at zero, we're about to start // overscrolling, so change the state if (currentScrollValue == 0) { view.setState(State.OVERSCROLLING); } view.setHeaderScroll((int) (scaleFactor * (currentScrollValue + newScrollValue))); } } else if (newScrollValue > (scrollRange + fuzzyThreshold)) { // Check the mode supports the overscroll direction, and // then move scroll if (mode.showFooterLoadingLayout()) { // If we're currently at zero, we're about to start // overscrolling, so change the state if (currentScrollValue == 0) { view.setState(State.OVERSCROLLING); } view.setHeaderScroll((int) (scaleFactor * (currentScrollValue + newScrollValue - scrollRange))); } } else if (Math.abs(newScrollValue) <= fuzzyThreshold || Math.abs(newScrollValue - scrollRange) <= fuzzyThreshold) { // Means we've stopped overscrolling, so scroll back to 0 view.setState(State.RESET); } } else if (isTouchEvent && State.OVERSCROLLING == view.getState()) { // This condition means that we were overscrolling from a fling, // but the user has touched the View and is now overscrolling // from touch instead. We need to just reset. view.setState(State.RESET); } } } static boolean isAndroidOverScrollEnabled(View view) { return view.getOverScrollMode() != View.OVER_SCROLL_NEVER; } }
JLUIT/ITJob
src/com/job/view/OverscrollHelper.java
Java
apache-2.0
8,015
package com.bbxyard.dp.template_method; /** * Created by bbxyard on 16-8-15. */ public class TemplateMethod { public static void main(String[] args) { AbstractClass obj = new ConcreteClass(); obj.run(); System.out.println("TemplateMethod.main.done!!"); } } abstract class AbstractClass { public void run() { System.out.println("AbstractClass.run.begin"); System.out.println("AbstractClass.run | invoke primitive-1 begin"); primitiveOperation1(); System.out.println("AbstractClass.run | invoke primitive-1 done"); System.out.println("AbstractClass.run | invoke primitive-2 BEGIN"); primitiveOperation2(); System.out.println("AbstractClass.run | invoke primitive-2 DONE"); System.out.println("AbstractClass.run.done"); } abstract void primitiveOperation1(); abstract void primitiveOperation2(); } class ConcreteClass extends AbstractClass { @Override void primitiveOperation1() { System.out.println("==> ConcreteClass.primitiveOperation1"); } @Override void primitiveOperation2() { System.out.println("==> ConcreteClass.primitiveOperation2"); } }
bbxyard/bbxyard
yard/workspace/dp/src/main/java/com/bbxyard/dp/template_method/TemplateMethod.java
Java
apache-2.0
1,203
/* * Copyright 2012-2017 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with * the License. A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR * CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions * and limitations under the License. */ package com.amazonaws.services.waf.model.waf_regional.transform; import java.util.List; import javax.annotation.Generated; import com.amazonaws.SdkClientException; import com.amazonaws.services.waf.model.*; import com.amazonaws.protocol.*; import com.amazonaws.annotation.SdkInternalApi; /** * SizeConstraintSetMarshaller */ @Generated("com.amazonaws:aws-java-sdk-code-generator") @SdkInternalApi public class SizeConstraintSetMarshaller { private static final MarshallingInfo<String> SIZECONSTRAINTSETID_BINDING = MarshallingInfo.builder(MarshallingType.STRING) .marshallLocation(MarshallLocation.PAYLOAD).marshallLocationName("SizeConstraintSetId").build(); private static final MarshallingInfo<String> NAME_BINDING = MarshallingInfo.builder(MarshallingType.STRING).marshallLocation(MarshallLocation.PAYLOAD) .marshallLocationName("Name").build(); private static final MarshallingInfo<List> SIZECONSTRAINTS_BINDING = MarshallingInfo.builder(MarshallingType.LIST) .marshallLocation(MarshallLocation.PAYLOAD).marshallLocationName("SizeConstraints").build(); private static final SizeConstraintSetMarshaller instance = new SizeConstraintSetMarshaller(); public static SizeConstraintSetMarshaller getInstance() { return instance; } /** * Marshall the given parameter object. */ public void marshall(SizeConstraintSet sizeConstraintSet, ProtocolMarshaller protocolMarshaller) { if (sizeConstraintSet == null) { throw new SdkClientException("Invalid argument passed to marshall(...)"); } try { protocolMarshaller.marshall(sizeConstraintSet.getSizeConstraintSetId(), SIZECONSTRAINTSETID_BINDING); protocolMarshaller.marshall(sizeConstraintSet.getName(), NAME_BINDING); protocolMarshaller.marshall(sizeConstraintSet.getSizeConstraints(), SIZECONSTRAINTS_BINDING); } catch (Exception e) { throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e); } } }
dagnir/aws-sdk-java
aws-java-sdk-waf/src/main/java/com/amazonaws/services/waf/model/waf_regional/transform/SizeConstraintSetMarshaller.java
Java
apache-2.0
2,662
/* * DomainSessionToken * Date of creation: 2011-02-22 * * Copyright (c) CompuGROUP Software GmbH, * This software is the confidential and proprietary information of * CompuGROUP Software GmbH. You shall not disclose such confidential * information and shall use it only in accordance with the terms of * the license agreement you entered into with CompuGROUP Software GmbH. */ package com.cg.ihe.doc; import javax.xml.bind.annotation.XmlType; import java.io.Serializable; /** * @author Ingo Hackl, AT */ @XmlType(namespace = "http://ihe.mdm.g3.cgm/domain") // @ComplexType(name = DomainSessionToken.SCHEMA_TYPE) TODO create PresentationDTO if needed public class DomainSessionToken implements Serializable{ private static final long serialVersionUID = 8429749127810323285L; private String domain; private String sessionToken; /** * */ public DomainSessionToken() { // } /** * @param domain . * @param sessionToken . */ public DomainSessionToken(String domain, String sessionToken) { this.domain = domain; this.sessionToken = sessionToken; } /** * GET. * * @return the domain */ public String getDomain() { return domain; } /** * GET. * * @return the sessionToken */ public String getSessionToken() { return sessionToken; } /** * SET. * * @param domain the domain to set */ public void setDomain(String domain) { this.domain = domain; } /** * SET. * * @param sessionToken the sessionToken to set */ public void setSessionToken(String sessionToken) { this.sessionToken = sessionToken; } }
jirikiml/GitTraining
GitTraining/src/com/cg/ihe/doc/DomainSessionToken.java
Java
apache-2.0
1,765
package com.atlassian.maven.plugins.jgitflow.extension.command; import java.util.List; import com.atlassian.jgitflow.core.GitFlowConfiguration; import com.atlassian.jgitflow.core.JGitFlow; import com.atlassian.jgitflow.core.JGitFlowReporter; import com.atlassian.jgitflow.core.command.JGitFlowCommand; import com.atlassian.jgitflow.core.exception.JGitFlowExtensionException; import com.atlassian.jgitflow.core.extension.ExtensionCommand; import com.atlassian.jgitflow.core.extension.ExtensionFailStrategy; import com.atlassian.maven.plugins.jgitflow.ReleaseContext; import com.atlassian.maven.plugins.jgitflow.helper.BranchHelper; import com.atlassian.maven.plugins.jgitflow.helper.PomUpdater; import com.atlassian.maven.plugins.jgitflow.helper.ProjectHelper; import com.atlassian.maven.plugins.jgitflow.provider.ContextProvider; import com.atlassian.maven.plugins.jgitflow.provider.JGitFlowProvider; import com.atlassian.maven.plugins.jgitflow.provider.ProjectCacheKey; import com.atlassian.maven.plugins.jgitflow.util.NamingUtil; import org.apache.commons.lang.StringUtils; import org.apache.maven.project.MavenProject; import org.codehaus.plexus.component.annotations.Component; import org.codehaus.plexus.component.annotations.Requirement; import org.eclipse.jgit.api.Git; @Component(role = UpdateFeaturePomsWithFinalVersionsCommand.class) public class UpdateFeaturePomsWithFinalVersionsCommand implements ExtensionCommand { @Requirement private ContextProvider contextProvider; @Requirement private JGitFlowProvider jGitFlowProvider; @Requirement private PomUpdater pomUpdater; @Requirement private ProjectHelper projectHelper; @Requirement private BranchHelper branchHelper; @Override public void execute(GitFlowConfiguration configuration, Git git, JGitFlowCommand gitFlowCommand, JGitFlowReporter reporter) throws JGitFlowExtensionException { String unprefixedBranchName = ""; try { ReleaseContext ctx = contextProvider.getContext(); if(!ctx.isEnableFeatureVersions()) { return; } JGitFlow flow = jGitFlowProvider.gitFlow(); unprefixedBranchName = branchHelper.getUnprefixedCurrentBranchName(); //reload the reactor projects for release List<MavenProject> branchProjects = branchHelper.getProjectsForCurrentBranch(); String featureVersion = NamingUtil.camelCaseOrSpaceToDashed(unprefixedBranchName); featureVersion = StringUtils.replace(featureVersion, "-", "_"); pomUpdater.removeFeatureVersionFromSnapshotVersions(ProjectCacheKey.FEATURE_FINISH_LABEL, featureVersion, branchProjects); projectHelper.commitAllPoms(flow.git(), branchProjects, ctx.getScmCommentPrefix() + "updating poms for " + featureVersion + " version" + ctx.getScmCommentSuffix()); } catch (Exception e) { throw new JGitFlowExtensionException("Error updating poms with feature versions for branch '" + unprefixedBranchName + "'"); } } @Override public ExtensionFailStrategy failStrategy() { return ExtensionFailStrategy.ERROR; } }
ctrimble/jgit-flow
jgitflow-maven-plugin/src/main/java/com/atlassian/maven/plugins/jgitflow/extension/command/UpdateFeaturePomsWithFinalVersionsCommand.java
Java
apache-2.0
3,240
package io.quarkus.it.main; import javax.inject.Inject; import org.junit.jupiter.api.AfterAll; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.TestInstance; import org.wildfly.common.Assert; import io.quarkus.it.arc.UnusedBean; import io.quarkus.test.junit.QuarkusTest; /** * Tests JUnit 5 extension when test lifecycle is PER_CLASS. This means extension events get fired in slightly different * order and Quarkus/Arc bootstrap and instance injection have to account for that. * * Test verifies that bootstrap works and that you can use injection even in before/after methods. */ @QuarkusTest @TestInstance(TestInstance.Lifecycle.PER_CLASS) public class JUnit5PerClassLifecycleTest { // any IP just to verify it was performed @Inject UnusedBean bean; @BeforeEach public void beforeEach() { Assertions.assertNotNull(bean); Assert.assertNotNull(bean.getInjectionPoint()); } @BeforeAll public void beforeAll() { Assertions.assertNotNull(bean); Assert.assertNotNull(bean.getInjectionPoint()); } @AfterEach public void afterEach() { Assertions.assertNotNull(bean); Assert.assertNotNull(bean.getInjectionPoint()); } @AfterAll public void afterAll() { Assertions.assertNotNull(bean); Assert.assertNotNull(bean.getInjectionPoint()); } @Test public void testQuarkusWasBootedAndInjectionWorks() { Assertions.assertNotNull(bean); Assert.assertNotNull(bean.getInjectionPoint()); } }
quarkusio/quarkus
integration-tests/main/src/test/java/io/quarkus/it/main/JUnit5PerClassLifecycleTest.java
Java
apache-2.0
1,716
/* * Copyright 2014-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with * the License. A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR * CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions * and limitations under the License. */ package com.amazonaws.services.iot1clickprojects.model; import javax.annotation.Generated; /** * <p/> */ @Generated("com.amazonaws:aws-java-sdk-code-generator") public class InternalFailureException extends com.amazonaws.services.iot1clickprojects.model.AWSIoT1ClickProjectsException { private static final long serialVersionUID = 1L; private String code; /** * Constructs a new InternalFailureException with the specified error message. * * @param message * Describes the error encountered. */ public InternalFailureException(String message) { super(message); } /** * @param code */ @com.fasterxml.jackson.annotation.JsonProperty("code") public void setCode(String code) { this.code = code; } /** * @return */ @com.fasterxml.jackson.annotation.JsonProperty("code") public String getCode() { return this.code; } /** * @param code * @return Returns a reference to this object so that method calls can be chained together. */ public InternalFailureException withCode(String code) { setCode(code); return this; } }
jentfoo/aws-sdk-java
aws-java-sdk-iot1clickprojects/src/main/java/com/amazonaws/services/iot1clickprojects/model/InternalFailureException.java
Java
apache-2.0
1,777
/* * Copyright 2013-present Facebook, 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.facebook.buck.jvm.java; import static java.nio.charset.StandardCharsets.UTF_8; import static org.hamcrest.CoreMatchers.equalTo; import static org.hamcrest.CoreMatchers.hasItem; import static org.hamcrest.CoreMatchers.is; import static org.hamcrest.CoreMatchers.not; import static org.hamcrest.Matchers.hasSize; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotEquals; import static org.junit.Assert.assertThat; import static org.junit.Assert.assertTrue; import static org.junit.Assume.assumeTrue; import com.facebook.buck.artifact_cache.ArtifactCache; import com.facebook.buck.artifact_cache.DirArtifactCacheTestUtil; import com.facebook.buck.artifact_cache.TestArtifactCaches; import com.facebook.buck.io.file.MorePaths; import com.facebook.buck.io.filesystem.ProjectFilesystem; import com.facebook.buck.io.filesystem.TestProjectFilesystems; import com.facebook.buck.json.HasJsonField; import com.facebook.buck.jvm.core.HasJavaAbi; import com.facebook.buck.jvm.java.testutil.AbiCompilationModeTest; import com.facebook.buck.model.BuildTarget; import com.facebook.buck.model.BuildTargetFactory; import com.facebook.buck.model.BuildTargets; import com.facebook.buck.rules.RuleKey; import com.facebook.buck.testutil.JsonMatcher; import com.facebook.buck.testutil.ProcessResult; import com.facebook.buck.testutil.TemporaryPaths; import com.facebook.buck.testutil.ZipArchive; import com.facebook.buck.testutil.integration.BuckBuildLog; import com.facebook.buck.testutil.integration.ProjectWorkspace; import com.facebook.buck.testutil.integration.TestDataHelper; import com.facebook.buck.testutil.integration.ZipInspector; import com.facebook.buck.util.ExitCode; import com.facebook.buck.util.ObjectMappers; import com.facebook.buck.util.environment.Platform; import com.facebook.buck.util.sha1.Sha1HashCode; import com.fasterxml.jackson.databind.JsonNode; import com.google.common.base.Strings; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableSet; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.nio.file.FileSystem; import java.nio.file.FileSystems; import java.nio.file.FileVisitResult; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.SimpleFileVisitor; import java.nio.file.StandardOpenOption; import java.nio.file.attribute.BasicFileAttributes; import java.nio.file.attribute.FileTime; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.List; import java.util.Optional; import java.util.Set; import java.util.jar.Attributes; import java.util.jar.JarInputStream; import java.util.jar.Manifest; import java.util.stream.Collectors; import java.util.zip.ZipEntry; import java.util.zip.ZipFile; import java.util.zip.ZipInputStream; import java.util.zip.ZipOutputStream; import org.hamcrest.Matchers; import org.junit.Before; import org.junit.Rule; import org.junit.Test; /** * Integration test that verifies that a {@link DefaultJavaLibrary} writes its ABI key as part of * compilation. */ public class DefaultJavaLibraryIntegrationTest extends AbiCompilationModeTest { @Rule public TemporaryPaths tmp = new TemporaryPaths(); @Rule public TemporaryPaths tmp2 = new TemporaryPaths(); private ProjectWorkspace workspace; private ProjectFilesystem filesystem; @Before public void setUp() throws InterruptedException { assumeTrue(Platform.detect() == Platform.MACOS || Platform.detect() == Platform.LINUX); filesystem = TestProjectFilesystems.createProjectFilesystem(tmp.getRoot()); } @Test public void testBuildJavaLibraryWithoutSrcsAndVerifyAbi() throws InterruptedException, IOException { setUpProjectWorkspaceForScenario("abi"); workspace.enableDirCache(); // Run `buck build`. BuildTarget target = BuildTargetFactory.newInstance("//:no_srcs"); ProcessResult buildResult = workspace.runBuckCommand("build", target.getFullyQualifiedName()); buildResult.assertSuccess("Successful build should exit with 0."); Path outputPath = BuildTargets.getGenPath( filesystem, target, "lib__%s__output/" + target.getShortName() + ".jar"); Path outputFile = workspace.getPath(outputPath); assertTrue(Files.exists(outputFile)); // TODO(mbolin): When we produce byte-for-byte identical JAR files across builds, do: // // HashCode hashOfOriginalJar = Files.hash(outputFile, Hashing.sha1()); // // And then compare that to the output when //:no_srcs is built again with --no-cache. long sizeOfOriginalJar = Files.size(outputFile); // This verifies that the ABI key was written correctly. workspace.verify(); // Verify the build cache. Path buildCache = workspace.getPath(filesystem.getBuckPaths().getCacheDir()); assertTrue(Files.isDirectory(buildCache)); ArtifactCache dirCache = TestArtifactCaches.createDirCacheForTest(workspace.getDestPath(), buildCache); int totalArtifactsCount = DirArtifactCacheTestUtil.getAllFilesInCache(dirCache).size(); assertEquals( "There should be two entries (a zip and metadata) per rule key type (default and input-" + "based) in the build cache.", 4, totalArtifactsCount); Sha1HashCode ruleKey = workspace.getBuildLog().getRuleKey(target.getFullyQualifiedName()); // Run `buck clean`. ProcessResult cleanResult = workspace.runBuckCommand("clean", "--keep-cache"); cleanResult.assertSuccess("Successful clean should exit with 0."); totalArtifactsCount = getAllFilesInPath(buildCache).size(); assertEquals("The build cache should still exist.", 4, totalArtifactsCount); // Corrupt the build cache! Path artifactZip = DirArtifactCacheTestUtil.getPathForRuleKey( dirCache, new RuleKey(ruleKey.asHashCode()), Optional.empty()); FileSystem zipFs = FileSystems.newFileSystem(artifactZip, /* loader */ null); Path outputInZip = zipFs.getPath("/" + outputPath); new ZipOutputStream(Files.newOutputStream(outputInZip, StandardOpenOption.TRUNCATE_EXISTING)) .close(); zipFs.close(); // Run `buck build` again. ProcessResult buildResult2 = workspace.runBuckCommand("build", target.getFullyQualifiedName()); buildResult2.assertSuccess("Successful build should exit with 0."); assertTrue(Files.isRegularFile(outputFile)); ZipFile outputZipFile = new ZipFile(outputFile.toFile()); assertEquals( "The output file will be an empty zip if it is read from the build cache.", 0, outputZipFile.stream().count()); outputZipFile.close(); // Run `buck clean` followed by `buck build` yet again, but this time, specify `--no-cache`. ProcessResult cleanResult2 = workspace.runBuckCommand("clean", "--keep-cache"); cleanResult2.assertSuccess("Successful clean should exit with 0."); ProcessResult buildResult3 = workspace.runBuckCommand("build", "--no-cache", target.getFullyQualifiedName()); buildResult3.assertSuccess(); outputZipFile = new ZipFile(outputFile.toFile()); assertNotEquals( "The contents of the file should no longer be pulled from the corrupted build cache.", 0, outputZipFile.stream().count()); outputZipFile.close(); assertEquals( "We cannot do a byte-for-byte comparision with the original JAR because timestamps might " + "have changed, but we verify that they are the same size, as a proxy.", sizeOfOriginalJar, Files.size(outputFile)); } @Test public void testBucksClasspathNotOnBuildClasspath() throws IOException { setUpProjectWorkspaceForScenario("guava_no_deps"); // Run `buck build`. ProcessResult buildResult = workspace.runBuckCommand("build", "//:foo"); buildResult.assertFailure( "Build should have failed since //:foo depends on Guava and " + "Args4j but does not include it in its deps."); workspace.verify(); } @Test public void testNoDepsCompilesCleanly() throws IOException { setUpProjectWorkspaceForScenario("guava_no_deps"); // Run `buck build`. ProcessResult buildResult = workspace.runBuckCommand("build", "//:bar"); buildResult.assertSuccess("Build should have succeeded."); workspace.verify(); } @Test public void testBuildJavaLibraryWithFirstOrder() throws IOException { setUpProjectWorkspaceForScenario("warn_on_transitive"); // Run `buck build`. ProcessResult buildResult = workspace.runBuckCommand("build", "//:raz", "-b", "FIRST_ORDER_ONLY"); buildResult.assertSpecialExitCode("invalid option -b", ExitCode.COMMANDLINE_ERROR); workspace.verify(); } @Test public void testBuildJavaLibraryExportsDirectoryEntries() throws IOException { setUpProjectWorkspaceForScenario("export_directory_entries"); // Run `buck build`. BuildTarget target = BuildTargetFactory.newInstance("//:empty_directory_entries"); ProcessResult buildResult = workspace.runBuckBuild(target.getFullyQualifiedName()); buildResult.assertSuccess(); Path outputFile = workspace.getPath( BuildTargets.getGenPath( filesystem, target, "lib__%s__output/" + target.getShortName() + ".jar")); assertTrue(Files.exists(outputFile)); ImmutableSet.Builder<String> jarContents = ImmutableSet.builder(); try (ZipFile zipFile = new ZipFile(outputFile.toFile())) { for (ZipEntry zipEntry : Collections.list(zipFile.entries())) { jarContents.add(zipEntry.getName()); } } // TODO(mread): Change the output to the intended output. assertEquals( jarContents.build(), ImmutableSet.of("META-INF/", "META-INF/MANIFEST.MF", "swag.txt", "yolo.txt")); workspace.verify(); } @Test public void testFileChangeThatDoesNotModifyAbiAvoidsRebuild() throws IOException { setUpProjectWorkspaceForScenario("rulekey_changed_while_abi_stable"); // Run `buck build`. BuildTarget bizTarget = BuildTargetFactory.newInstance("//:biz"); BuildTarget utilTarget = BuildTargetFactory.newInstance("//:util"); ProcessResult buildResult = workspace.runBuckCommand("build", bizTarget.getFullyQualifiedName()); buildResult.assertSuccess("Successful build should exit with 0."); Path utilRuleKeyPath = BuildTargets.getScratchPath(filesystem, utilTarget, ".%s/metadata/build/RULE_KEY"); String utilRuleKey = getContents(utilRuleKeyPath); Path utilAbiRuleKeyPath = BuildTargets.getScratchPath( filesystem, utilTarget, ".%s/metadata/build/INPUT_BASED_RULE_KEY"); String utilAbiRuleKey = getContents(utilAbiRuleKeyPath); Path bizRuleKeyPath = BuildTargets.getScratchPath(filesystem, bizTarget, ".%s/metadata/build/RULE_KEY"); String bizRuleKey = getContents(bizRuleKeyPath); Path bizAbiRuleKeyPath = BuildTargets.getScratchPath( filesystem, bizTarget, ".%s/metadata/build/INPUT_BASED_RULE_KEY"); String bizAbiRuleKey = getContents(bizAbiRuleKeyPath); Path utilOutputPath = BuildTargets.getGenPath( filesystem, utilTarget, "lib__%s__output/" + utilTarget.getShortName() + ".jar"); long utilJarSize = Files.size(workspace.getPath(utilOutputPath)); Path bizOutputPath = BuildTargets.getGenPath( filesystem, bizTarget, "lib__%s__output/" + bizTarget.getShortName() + ".jar"); FileTime bizJarLastModified = Files.getLastModifiedTime(workspace.getPath(bizOutputPath)); // TODO(mbolin): Run uber-biz.jar and verify it prints "Hello World!\n". // Edit Util.java in a way that does not affect its ABI. workspace.replaceFileContents("Util.java", "Hello World", "Hola Mundo"); // Run `buck build` again. ProcessResult buildResult2 = workspace.runBuckCommand("build", "//:biz"); buildResult2.assertSuccess("Successful build should exit with 0."); assertThat(utilRuleKey, not(equalTo(getContents(utilRuleKeyPath)))); assertThat(utilAbiRuleKey, not(equalTo(getContents(utilAbiRuleKeyPath)))); workspace.getBuildLog().assertTargetBuiltLocally(utilTarget.toString()); assertThat(bizRuleKey, not(equalTo(getContents(bizRuleKeyPath)))); assertEquals(bizAbiRuleKey, getContents(bizAbiRuleKeyPath)); workspace.getBuildLog().assertTargetHadMatchingInputRuleKey(bizTarget.toString()); assertThat( "util.jar should have been rewritten, so its file size should have changed.", utilJarSize, not(equalTo(Files.size(workspace.getPath(utilOutputPath))))); assertEquals( "biz.jar should not have been rewritten, so its last-modified time should be the same.", bizJarLastModified, Files.getLastModifiedTime(workspace.getPath(bizOutputPath))); // TODO(mbolin): Run uber-biz.jar and verify it prints "Hola Mundo!\n". // TODO(mbolin): This last scenario that is being tested would be better as a unit test. // Run `buck build` one last time. This ensures that a dependency java_library() rule (:util) // that is built via BuildRuleSuccess.Type.MATCHING_INPUT_BASED_RULE_KEY does not // explode when its dependent rule (:biz) invokes the dependency's getAbiKey() method as part of // its own getAbiKeyForDeps(). ProcessResult buildResult3 = workspace.runBuckCommand("build", "//:biz"); buildResult3.assertSuccess("Successful build should exit with 0."); } @Test public void testJavaLibraryOnlyDependsOnTheAbiVersionsOfItsDeps() throws IOException { compileAgainstAbisOnly(); setUpProjectWorkspaceForScenario("depends_only_on_abi_test"); workspace.enableDirCache(); // Build A ProcessResult firstBuildResult = workspace.runBuckBuild("//:a"); firstBuildResult.assertSuccess("Successful build should exit with 0."); // Perform clean ProcessResult cleanResult = workspace.runBuckCommand("clean", "--keep-cache"); cleanResult.assertSuccess("Successful clean should exit with 0."); // Edit A workspace.replaceFileContents("A.java", "getB", "getNewB"); // Rebuild A ProcessResult secondBuildResult = workspace.runBuckBuild("//:a"); secondBuildResult.assertSuccess("Successful build should exit with 0."); BuildTarget b = BuildTargetFactory.newInstance("//:b"); BuildTarget c = BuildTargetFactory.newInstance("//:c"); BuildTarget d = BuildTargetFactory.newInstance("//:d"); // Confirm that we got an input based rule key hit on B#abi, C#abi, D#abi workspace .getBuildLog() .assertTargetWasFetchedFromCache( b.withFlavors(HasJavaAbi.CLASS_ABI_FLAVOR).getFullyQualifiedName()); workspace .getBuildLog() .assertTargetWasFetchedFromCache( c.withFlavors(HasJavaAbi.CLASS_ABI_FLAVOR).getFullyQualifiedName()); workspace .getBuildLog() .assertTargetWasFetchedFromCache( d.withFlavors(HasJavaAbi.CLASS_ABI_FLAVOR).getFullyQualifiedName()); // Confirm that B, C, and D were not re-built workspace.getBuildLog().assertNoLogEntry(b.getFullyQualifiedName()); workspace.getBuildLog().assertNoLogEntry(c.getFullyQualifiedName()); workspace.getBuildLog().assertNoLogEntry(d.getFullyQualifiedName()); } @Test public void testCompileAgainstSourceOnlyAbisByDefault() throws IOException { compileAgainstAbisOnly(); setUpProjectWorkspaceForScenario("depends_only_on_abi_test"); ProcessResult result = workspace.runBuckBuild("--config", "java.abi_generation_mode=source_only", "//:a"); result.assertSuccess(); workspace.getBuildLog().assertTargetBuiltLocally("//:b#source-only-abi"); workspace.getBuildLog().assertTargetBuiltLocally("//:c#source-only-abi"); workspace.getBuildLog().assertTargetBuiltLocally("//:d#source-only-abi"); workspace.getBuildLog().assertTargetIsAbsent("//:b#source-abi"); workspace.getBuildLog().assertTargetIsAbsent("//:c#source-abi"); workspace.getBuildLog().assertTargetIsAbsent("//:d#source-abi"); } @Test public void testAnnotationProcessorDepChangeThatDoesNotModifyAbiCausesRebuild() throws IOException { setUpProjectWorkspaceForScenario("annotation_processors"); // Run `buck build` to create the dep file BuildTarget mainTarget = BuildTargetFactory.newInstance("//:main"); // Warm the used classes file ProcessResult buildResult = workspace.runBuckCommand("build", mainTarget.getFullyQualifiedName()); buildResult.assertSuccess("Successful build should exit with 0."); workspace.getBuildLog().assertTargetBuiltLocally("//:main"); workspace.getBuildLog().assertTargetBuiltLocally("//:annotation_processor"); workspace.getBuildLog().assertTargetBuiltLocally("//:util"); // Edit a dependency of the annotation processor in a way that doesn't change the ABI workspace.replaceFileContents("Util.java", "false", "true"); // Run `buck build` again. ProcessResult buildResult2 = workspace.runBuckCommand("build", "//:main"); buildResult2.assertSuccess("Successful build should exit with 0."); // If all goes well, we'll see //:annotation_processor's dep file on disk and not rebuild it, // but still rebuild //:main because the code of the annotation processor has changed workspace.getBuildLog().assertTargetBuiltLocally("//:util"); workspace.getBuildLog().assertTargetBuiltLocally("//:main"); workspace.getBuildLog().assertTargetHadMatchingInputRuleKey("//:annotation_processor_lib"); workspace.getBuildLog().assertTargetBuiltLocally("//:annotation_processor"); } @Test public void testAnnotationProcessorFileChangeThatDoesNotModifyAbiCausesRebuild() throws IOException { setUpProjectWorkspaceForScenario("annotation_processors"); // Run `buck build` to create the dep file BuildTarget mainTarget = BuildTargetFactory.newInstance("//:main"); // Warm the used classes file ProcessResult buildResult = workspace.runBuckCommand("build", mainTarget.getFullyQualifiedName()); buildResult.assertSuccess("Successful build should exit with 0."); workspace.getBuildLog().assertTargetBuiltLocally("//:main"); workspace.getBuildLog().assertTargetBuiltLocally("//:annotation_processor"); workspace.getBuildLog().assertTargetBuiltLocally("//:util"); // Edit a source file in the annotation processor in a way that doesn't change the ABI workspace.replaceFileContents("AnnotationProcessor.java", "false", "true"); // Run `buck build` again. ProcessResult buildResult2 = workspace.runBuckCommand("build", "//:main"); buildResult2.assertSuccess("Successful build should exit with 0."); // If all goes well, we'll rebuild //:annotation_processor because of the source change, // and then rebuild //:main because the code of the annotation processor has changed workspace.getBuildLog().assertTargetHadMatchingRuleKey("//:util"); workspace.getBuildLog().assertTargetBuiltLocally("//:main"); workspace.getBuildLog().assertTargetBuiltLocally("//:annotation_processor"); } @Test public void testAnnotationProcessorFileChangeThatDoesNotModifyCodeDoesNotCauseRebuild() throws IOException { setUpProjectWorkspaceForScenario("annotation_processors"); // Run `buck build` to create the dep file BuildTarget mainTarget = BuildTargetFactory.newInstance("//:main"); // Warm the used classes file ProcessResult buildResult = workspace.runBuckCommand("build", mainTarget.getFullyQualifiedName()); buildResult.assertSuccess("Successful build should exit with 0."); workspace.getBuildLog().assertTargetBuiltLocally("//:main"); workspace.getBuildLog().assertTargetBuiltLocally("//:annotation_processor"); workspace.getBuildLog().assertTargetBuiltLocally("//:util"); // Edit a source file in the annotation processor in a way that doesn't change the ABI workspace.replaceFileContents("AnnotationProcessor.java", "false", "false /* false */"); // Run `buck build` again. ProcessResult buildResult2 = workspace.runBuckCommand("build", "//:main"); buildResult2.assertSuccess("Successful build should exit with 0."); // If all goes well, we'll rebuild //:annotation_processor because of the source change, // and then rebuild //:main because the code of the annotation processor has changed workspace.getBuildLog().assertTargetHadMatchingRuleKey("//:util"); workspace.getBuildLog().assertTargetHadMatchingInputRuleKey("//:main"); workspace.getBuildLog().assertTargetHadMatchingInputRuleKey("//:annotation_processor"); workspace.getBuildLog().assertTargetBuiltLocally("//:annotation_processor_lib"); } @Test public void testFileChangeThatDoesNotModifyAbiOfAUsedClassAvoidsRebuild() throws IOException { setUpProjectWorkspaceForScenario("dep_file_rule_key"); // Run `buck build` to create the dep file BuildTarget bizTarget = BuildTargetFactory.newInstance("//:biz"); // Warm the used classes file ProcessResult buildResult = workspace.runBuckCommand("build", bizTarget.getFullyQualifiedName()); buildResult.assertSuccess("Successful build should exit with 0."); workspace.getBuildLog().assertTargetBuiltLocally("//:biz"); workspace.getBuildLog().assertTargetBuiltLocally("//:util"); // Edit MoreUtil.java in a way that changes its ABI workspace.replaceFileContents("MoreUtil.java", "printHelloWorld", "printHelloWorld2"); // Run `buck build` again. ProcessResult buildResult2 = workspace.runBuckCommand("build", "//:biz"); buildResult2.assertSuccess("Successful build should exit with 0."); // If all goes well, we'll fetch //:biz's dep file from the cache and realize we don't need // to rebuild it because //:biz didn't use MoreUtil. workspace.getBuildLog().assertTargetBuiltLocally("//:util"); workspace.getBuildLog().assertTargetHadMatchingDepfileRuleKey("//:biz"); } @Test public void testResourceFileChangeCanTakeAdvantageOfDepBasedKeys() throws IOException { setUpProjectWorkspaceForScenario("resource_in_dep_file"); // Warm the used classes file ProcessResult buildResult = workspace.runBuckCommand("build", ":main"); buildResult.assertSuccess("Successful build should exit with 0."); workspace.getBuildLog().assertTargetBuiltLocally("//:main"); workspace.getBuildLog().assertTargetBuiltLocally("//:util"); // Edit the unread_file.txt resource workspace.replaceFileContents("unread_file.txt", "hello", "goodbye"); // Run `buck build` again. ProcessResult buildResult2 = workspace.runBuckCommand("build", "//:main"); buildResult2.assertSuccess("Successful build should exit with 0."); // If all goes well, we'll fetch //:main's dep file from the cache and realize we don't need // to rebuild it because //:main didn't use unread_file. workspace.getBuildLog().assertTargetBuiltLocally("//:util"); workspace.getBuildLog().assertTargetHadMatchingDepfileRuleKey("//:main"); // Edit read_file.txt resource workspace.replaceFileContents("read_file.txt", "me", "you"); workspace.runBuckCommand("build", ":main").assertSuccess(); // Since that file was used during the compilation, we must rebuild workspace.getBuildLog().assertTargetBuiltLocally("//:util"); workspace.getBuildLog().assertTargetBuiltLocally("//:main"); } @Test public void testFileChangeThatDoesNotModifyAbiOfAUsedClassAvoidsRebuildEvenWithBuckClean() throws IOException { setUpProjectWorkspaceForScenario("dep_file_rule_key"); workspace.enableDirCache(); // Run `buck build` to warm the cache. BuildTarget bizTarget = BuildTargetFactory.newInstance("//:biz"); // Warm the used classes file ProcessResult buildResult = workspace.runBuckCommand("build", bizTarget.getFullyQualifiedName()); buildResult.assertSuccess("Successful build should exit with 0."); workspace.getBuildLog().assertTargetBuiltLocally("//:biz"); workspace.getBuildLog().assertTargetBuiltLocally("//:util"); // Run `buck clean` so that we're forced to fetch the dep file from the cache. ProcessResult cleanResult = workspace.runBuckCommand("clean", "--keep-cache"); cleanResult.assertSuccess("Successful clean should exit with 0."); // Edit MoreUtil.java in a way that changes its ABI workspace.replaceFileContents("MoreUtil.java", "printHelloWorld", "printHelloWorld2"); // Run `buck build` again. ProcessResult buildResult2 = workspace.runBuckCommand("build", "//:biz"); buildResult2.assertSuccess("Successful build should exit with 0."); // If all goes well, we'll fetch //:biz's dep file from the cache and realize we don't need // to rebuild it because //:biz didn't use MoreUtil. workspace.getBuildLog().assertTargetBuiltLocally("//:util"); workspace.getBuildLog().assertTargetWasFetchedFromCacheByManifestMatch("//:biz"); } // Yes, we actually had the bug against which this test is guarding. @Test public void testAddedSourceFileInvalidatesManifest() throws IOException { setUpProjectWorkspaceForScenario("manifest_key"); workspace.enableDirCache(); // Run `buck build` to warm the cache. BuildTarget mainTarget = BuildTargetFactory.newInstance("//:main"); // Warm the used classes file ProcessResult buildResult = workspace.runBuckCommand("build", mainTarget.getFullyQualifiedName()); buildResult.assertSuccess("Successful build should exit with 0."); workspace.getBuildLog().assertTargetBuiltLocally("//:main"); // Run `buck clean` so that we're forced to fetch the dep file from the cache. ProcessResult cleanResult = workspace.runBuckCommand("clean", "--keep-cache"); cleanResult.assertSuccess("Successful clean should exit with 0."); // Add a new source file workspace.writeContentsToPath( "package com.example; public class NewClass { }", "NewClass.java"); // Run `buck build` again. ProcessResult buildResult2 = workspace.runBuckCommand("build", mainTarget.getFullyQualifiedName()); buildResult2.assertSuccess("Successful build should exit with 0."); // The new source file should result in a different manifest being downloaded and thus a // cache miss. workspace.getBuildLog().assertTargetBuiltLocally("//:main"); } @Test public void testClassUsageFileOutput() throws IOException { setUpProjectWorkspaceForScenario("class_usage_file"); // Run `buck build`. BuildTarget bizTarget = BuildTargetFactory.newInstance("//:biz"); ProcessResult buildResult = workspace.runBuckCommand("build", bizTarget.getFullyQualifiedName()); buildResult.assertSuccess("Successful build should exit with 0."); Path bizClassUsageFilePath = BuildTargets.getGenPath(filesystem, bizTarget, "lib__%s__output/used-classes.json"); List<String> lines = Files.readAllLines(workspace.getPath(bizClassUsageFilePath), UTF_8); assertEquals("Expected just one line of JSON", 1, lines.size()); String utilJarPath; if (compileAgainstAbis.equals(TRUE)) { utilJarPath = MorePaths.pathWithPlatformSeparators("buck-out/gen/util#class-abi/util-abi.jar"); } else { utilJarPath = MorePaths.pathWithPlatformSeparators("buck-out/gen/lib__util__output/util.jar"); } String utilClassPath = MorePaths.pathWithPlatformSeparators("com/example/Util.class"); JsonNode jsonNode = ObjectMappers.READER.readTree(lines.get(0)); assertThat( jsonNode, new HasJsonField( utilJarPath, Matchers.equalTo( ObjectMappers.legacyCreate().valueToTree(new String[] {utilClassPath})))); } @Test public void testCanUseDepFileRuleKeysCrossCell() throws Exception { setUpProjectWorkspaceForScenario("class_usage_file_xcell"); Path crossCellRoot = setUpACrossCell("away_cell", workspace.getPath("away_cell")); // Run `buck build`. BuildTarget bizTarget = BuildTargetFactory.newInstance("//:biz"); workspace.runBuckBuild(bizTarget.getFullyQualifiedName()).assertSuccess(); BuckBuildLog cleanBuildLog = workspace.getBuildLog(); cleanBuildLog.assertTargetBuiltLocally("away_cell//util:util"); cleanBuildLog.assertTargetBuiltLocally("//:biz"); // Edit the file not used by the local target and assert we get a dep file hit workspace.replaceFileContents( crossCellRoot.resolve("util/MoreUtil.java").toString(), "//public_method", ""); workspace.runBuckBuild(bizTarget.getFullyQualifiedName()).assertSuccess(); BuckBuildLog depFileHitLog = workspace.getBuildLog(); depFileHitLog.assertTargetBuiltLocally("away_cell//util:util"); depFileHitLog.assertTargetHadMatchingDepfileRuleKey("//:biz"); // Now edit the file not used by the local target and assert we don't get a false cache hit workspace.replaceFileContents( crossCellRoot.resolve("util/Util.java").toString(), "//public_method", ""); workspace.runBuckBuild(bizTarget.getFullyQualifiedName()).assertSuccess(); BuckBuildLog depFileMissLog = workspace.getBuildLog(); depFileMissLog.assertTargetBuiltLocally("away_cell//util:util"); depFileMissLog.assertTargetBuiltLocally("//:biz"); } @Test public void testClassUsageFileOutputForCrossCell() throws Exception { setUpProjectWorkspaceForScenario("class_usage_file_xcell"); setUpACrossCell("away_cell", workspace.getPath("away_cell")); // Run `buck build`. BuildTarget bizTarget = BuildTargetFactory.newInstance("//:biz"); ProcessResult buildResult = workspace.runBuckBuild(bizTarget.getFullyQualifiedName()); buildResult.assertSuccess("Successful build should exit with 0."); Path bizClassUsageFilePath = BuildTargets.getGenPath(filesystem, bizTarget, "lib__%s__output/used-classes.json"); String usedClasses = getContents(workspace.getPath(bizClassUsageFilePath)); String utilJarPath; if (compileAgainstAbis.equals(TRUE)) { utilJarPath = MorePaths.pathWithPlatformSeparators( "/away_cell/buck-out/gen/util/util#class-abi/util-abi.jar"); } else { utilJarPath = MorePaths.pathWithPlatformSeparators( "/away_cell/buck-out/gen/util/lib__util__output/util.jar"); } String utilClassPath = MorePaths.pathWithPlatformSeparators("com/example/Util.class"); JsonMatcher expectedOutputMatcher = new JsonMatcher(String.format("{ \"%s\": [ \"%s\" ] }", utilJarPath, utilClassPath)); assertThat(usedClasses, expectedOutputMatcher); } @Test public void updatingAResourceWhichIsJavaLibraryCausesAJavaLibraryToBeRepacked() throws IOException { setUpProjectWorkspaceForScenario("resource_change_causes_repack"); // Run `buck build`. ProcessResult buildResult = workspace.runBuckCommand("build", "//:lib"); buildResult.assertSuccess("Successful build should exit with 0."); workspace.copyFile("ResClass.java.new", "ResClass.java"); workspace.resetBuildLogFile(); // The copied file changed the contents but not the ABI of :lib. Because :lib is included as a // resource of :res, it's expected that both :lib and :res are rebuilt (:lib because of a code // change, :res in order to repack the resource) buildResult = workspace.runBuckCommand("build", "//:lib"); buildResult.assertSuccess("Successful build should exit with 0."); workspace.getBuildLog().assertTargetBuiltLocally("//:res"); workspace.getBuildLog().assertTargetBuiltLocally("//:lib"); } @Test public void ensureProvidedDepsAreIncludedWhenCompilingButNotWhenPackaging() throws IOException { setUpProjectWorkspaceForScenario("provided_deps"); // Run `buck build`. BuildTarget binaryTarget = BuildTargetFactory.newInstance("//:binary"); BuildTarget binary2Target = BuildTargetFactory.newInstance("//:binary_2"); ProcessResult buildResult = workspace.runBuckCommand( "build", binaryTarget.getFullyQualifiedName(), binary2Target.getFullyQualifiedName()); buildResult.assertSuccess("Successful build should exit with 0."); for (Path filename : new Path[] { BuildTargets.getGenPath(filesystem, binaryTarget, "%s.jar"), BuildTargets.getGenPath(filesystem, binary2Target, "%s.jar") }) { Path file = workspace.getPath(filename); try (ZipArchive zipArchive = new ZipArchive(file, /* for writing? */ false)) { Set<String> allNames = zipArchive.getFileNames(); // Representative file from provided_deps we don't expect to be there. assertFalse(allNames.contains("org/junit/Test.class")); // Representative file from the deps that we do expect to be there. assertTrue(allNames.contains("com/google/common/collect/Sets.class")); // The file we built. assertTrue(allNames.contains("com/facebook/buck/example/Example.class")); } } } @Test public void ensureChangingDepFromProvidedToTransitiveTriggersRebuild() throws IOException { setUpProjectWorkspaceForScenario("provided_deps"); workspace.runBuckBuild("//:binary").assertSuccess("Successful build should exit with 0."); workspace.replaceFileContents("BUCK", "provided_deps = [\":junit\"],", ""); workspace.replaceFileContents("BUCK", "deps = [\":guava\"]", "deps = [ ':guava', ':junit' ]"); workspace.resetBuildLogFile(); workspace.runBuckBuild("//:binary").assertSuccess(); workspace.getBuildLog().assertTargetBuiltLocally("//:binary"); } @Test public void ensureThatSourcePathIsSetSensibly() throws IOException { setUpProjectWorkspaceForScenario("sourcepath"); ProcessResult result = workspace.runBuckBuild("//:b"); // This should fail, since we expect the symbol for A not to be found. result.assertFailure(); String stderr = result.getStderr(); assertTrue(stderr, stderr.contains("cannot find symbol")); } @Test public void testSaveClassFilesToDisk() throws IOException { setUpProjectWorkspaceForScenario("spool_class_files_to_disk"); BuildTarget target = BuildTargetFactory.newInstance("//:a"); ProcessResult result = workspace.runBuckBuild(target.getFullyQualifiedName()); result.assertSuccess(); Path classesDir = workspace.getPath(BuildTargets.getScratchPath(filesystem, target, "lib__%s__classes")); assertTrue(Files.exists(classesDir)); assertTrue(Files.isDirectory(classesDir)); ArrayList<String> classFiles = new ArrayList<>(); for (File file : classesDir.toFile().listFiles()) { classFiles.add(file.getName()); } assertThat( "There should be 2 class files saved to disk from the compiler", classFiles, hasSize(2)); assertThat(classFiles, hasItem("A.class")); assertThat(classFiles, hasItem("B.class")); } @Test public void testSpoolClassFilesDirectlyToJar() throws IOException { setUpProjectWorkspaceForScenario("spool_class_files_directly_to_jar"); BuildTarget target = BuildTargetFactory.newInstance("//:a"); ProcessResult result = workspace.runBuckBuild(target.getFullyQualifiedName()); result.assertSuccess(); Path classesDir = workspace.getPath(BuildTargets.getScratchPath(filesystem, target, "lib__%s__classes")); assertThat(Files.exists(classesDir), is(Boolean.TRUE)); assertThat( "There should be no class files in disk", ImmutableList.copyOf(classesDir.toFile().listFiles()), hasSize(0)); Path jarPath = workspace.getPath(BuildTargets.getGenPath(filesystem, target, "lib__%s__output/a.jar")); assertTrue(Files.exists(jarPath)); ZipInputStream zip = new ZipInputStream(new FileInputStream(jarPath.toFile())); assertThat(zip.getNextEntry().getName(), is("META-INF/")); assertThat(zip.getNextEntry().getName(), is("META-INF/MANIFEST.MF")); assertThat(zip.getNextEntry().getName(), is("A.class")); assertThat(zip.getNextEntry().getName(), is("B.class")); zip.close(); } @Test public void testSpoolClassFilesDirectlyToJarWithRemoveClasses() throws IOException { setUpProjectWorkspaceForScenario("spool_class_files_directly_to_jar_with_remove_classes"); BuildTarget target = BuildTargetFactory.newInstance("//:a"); ProcessResult result = workspace.runBuckBuild(target.getFullyQualifiedName()); result.assertSuccess(); Path classesDir = workspace.getPath(BuildTargets.getScratchPath(filesystem, target, "lib__%s__classes")); assertThat("Classes directory should exist.", Files.exists(classesDir), is(Boolean.TRUE)); assertThat( "No class files should be stored on disk.", Arrays.stream(classesDir.toFile().listFiles()) .filter(file -> file.getName().endsWith(".class")) .collect(Collectors.toList()), hasSize(0)); Path jarPath = workspace.getPath(BuildTargets.getGenPath(filesystem, target, "lib__%s__output/a.jar")); assertTrue(Files.exists(jarPath)); // Check that normal and member classes were removed as expected. ZipInspector zipInspector = new ZipInspector(jarPath); zipInspector.assertFileExists("test/pkg/A.class"); zipInspector.assertFileExists("test/pkg/B.class"); zipInspector.assertFileExists("test/pkg/C.class"); zipInspector.assertFileExists("test/pkg/RemovableZ.txt"); zipInspector.assertFileDoesNotExist("test/pkg/RemovableZ.class"); zipInspector.assertFileDoesNotExist("test/pkg/B$removableB.class"); zipInspector.assertFileDoesNotExist("test/pkg/C$deletableC.class"); } @Test public void testSaveClassFilesToDiskWithRemoveClasses() throws IOException { setUpProjectWorkspaceForScenario("spool_class_files_to_disk_remove_classes"); BuildTarget target = BuildTargetFactory.newInstance("//:a"); ProcessResult result = workspace.runBuckBuild(target.getFullyQualifiedName()); result.assertSuccess(); Path classesDir = workspace.getPath(BuildTargets.getScratchPath(filesystem, target, "lib__%s__classes")); assertThat("Classes directory should exist.", Files.exists(classesDir), is(Boolean.TRUE)); Path jarPath = workspace.getPath(BuildTargets.getGenPath(filesystem, target, "lib__%s__output/a.jar")); assertTrue("Jar should exist.", Files.exists(jarPath)); // Check that normal and member classes were removed as expected. ZipInspector zipInspector = new ZipInspector(jarPath); zipInspector.assertFileExists("test/pkg/A.class"); zipInspector.assertFileExists("test/pkg/B.class"); zipInspector.assertFileExists("test/pkg/RemovableC.txt"); zipInspector.assertFileDoesNotExist("test/pkg/RemovableC.class"); zipInspector.assertFileDoesNotExist("test/pkg/B$MemberD.class"); zipInspector.assertFileDoesNotExist("DeletableB.class"); } @Test public void testSpoolClassFilesDirectlyToJarWithAnnotationProcessorAndRemoveClasses() throws IOException { setUpProjectWorkspaceForScenario("spool_class_files_directly_to_jar_with_annotation_processor"); BuildTarget target = BuildTargetFactory.newInstance("//:a"); ProcessResult result = workspace.runBuckBuild(target.getFullyQualifiedName()); result.assertSuccess(); Path classesDir = workspace.getPath(BuildTargets.getScratchPath(filesystem, target, "lib__%s__classes")); assertThat(Files.exists(classesDir), is(Boolean.TRUE)); assertThat( "There should be no class files in disk", ImmutableList.copyOf(classesDir.toFile().listFiles()), hasSize(0)); Path sourcesDir = workspace.getPath(BuildTargets.getAnnotationPath(filesystem, target, "__%s_gen__")); assertThat(Files.exists(sourcesDir), is(Boolean.TRUE)); assertThat( "There should be two source files in disk, from the two generated classes.", ImmutableList.copyOf(sourcesDir.toFile().listFiles()), hasSize(2)); Path jarPath = workspace.getPath(BuildTargets.getGenPath(filesystem, target, "lib__%s__output/a.jar")); assertTrue(Files.exists(jarPath)); ZipInspector zipInspector = new ZipInspector(jarPath); zipInspector.assertFileDoesNotExist("ImmutableC.java"); zipInspector.assertFileExists("ImmutableC.class"); zipInspector.assertFileDoesNotExist("RemovableD.class"); zipInspector.assertFileExists("RemovableD"); } @Test public void shouldIncludeUserSuppliedManifestIfProvided() throws IOException { setUpProjectWorkspaceForScenario("manifest"); Manifest m = new Manifest(); Attributes attrs = new Attributes(); attrs.putValue("Data", "cheese"); m.getEntries().put("Example", attrs); m.write(System.out); Path path = workspace.buildAndReturnOutput("//:library"); try (InputStream is = Files.newInputStream(path); JarInputStream jis = new JarInputStream(is)) { Manifest manifest = jis.getManifest(); String value = manifest.getEntries().get("Example").getValue("Data"); assertEquals("cheese", value); } } @Test public void parseErrorsShouldBeReportedGracefully() throws IOException { setUpProjectWorkspaceForScenario("parse_errors"); ProcessResult result = workspace.runBuckBuild("//:errors"); assertThat(result.getStderr(), Matchers.stringContainsInOrder("illegal start of expression")); } @Test public void parseErrorsShouldBeReportedGracefullyWithAnnotationProcessors() throws IOException { setUpProjectWorkspaceForScenario("parse_errors_with_aps"); ProcessResult result = workspace.runBuckBuild("//:errors"); assertThat(result.getStderr(), Matchers.stringContainsInOrder("illegal start of expression")); } @Test public void parseErrorsShouldBeReportedGracefullyWithSourceOnlyAbi() throws IOException { setUpProjectWorkspaceForScenario("parse_errors"); ProcessResult result = workspace.runBuckBuild( "-c", "java.abi_generation_mode=source_only", "//:errors#source-only-abi"); assertThat(result.getStderr(), Matchers.stringContainsInOrder("illegal start of expression")); } @Test public void missingDepsShouldNotCrashSourceOnlyVerifier() throws IOException { setUpProjectWorkspaceForScenario("missing_deps"); ProcessResult result = workspace.runBuckBuild("-c", "java.abi_generation_mode=source_only", "//:errors"); result.assertFailure(); assertThat(result.getStderr(), Matchers.not(Matchers.stringContainsInOrder("Exception"))); } @Test public void badImportsShouldNotCrashBuck() throws IOException { setUpProjectWorkspaceForScenario("import_errors"); ProcessResult result = workspace.runBuckBuild("//:errors"); assertThat( result.getStderr(), Matchers.stringContainsInOrder( "class file for com.example.buck.library.dep.SuperSuper not found")); } @Test public void annotationProcessorCrashesShouldCrashBuck() throws IOException { setUpProjectWorkspaceForScenario("ap_crashes"); ProcessResult result = workspace.runBuckBuild("//:main"); assertThat( result.getStderr(), Matchers.stringContainsInOrder( "Build failed:", "The annotation processor com.example.buck.AnnotationProcessor has crashed.", "java.lang.RuntimeException: java.lang.IllegalArgumentException: Test crash! |\n| at com.example.buck.AnnotationProcessor.process(AnnotationProcessor.java:22) |\n| ...", // Buck frames have been stripped properly "Caused by: java.lang.IllegalArgumentException: Test crash!", // Without then stripping // out the caused // exception! " When running <javac>.", " When building rule //:main.")); } /** Asserts that the specified file exists and returns its contents. */ private String getContents(Path relativePathToFile) throws IOException { Path file = workspace.getPath(relativePathToFile); assertTrue(relativePathToFile + " should exist and be an ordinary file.", Files.exists(file)); String content = Strings.nullToEmpty(new String(Files.readAllBytes(file), UTF_8)).trim(); assertFalse(relativePathToFile + " should not be empty.", content.isEmpty()); return content; } private ImmutableList<Path> getAllFilesInPath(Path path) throws IOException { List<Path> allFiles = new ArrayList<>(); Files.walkFileTree( path, ImmutableSet.of(), Integer.MAX_VALUE, new SimpleFileVisitor<Path>() { @Override public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException { allFiles.add(file); return super.visitFile(file, attrs); } }); return ImmutableList.copyOf(allFiles); } private ProjectWorkspace setUpProjectWorkspaceForScenario(String scenario) throws IOException { workspace = TestDataHelper.createProjectWorkspaceForScenario(this, scenario, tmp); workspace.setUp(); setWorkspaceCompilationMode(workspace); return workspace; } private Path setUpACrossCell(String cellName, Path crossCellContents) throws IOException { File crossCellsRoot = tmp2.getRoot().resolve("cross_cells").toFile(); crossCellsRoot.mkdirs(); Path newCellLocation = crossCellsRoot.toPath().resolve(crossCellContents.getFileName()); Files.move(crossCellContents, newCellLocation); workspace.addBuckConfigLocalOption("repositories", cellName, newCellLocation.toString()); return newCellLocation; } }
clonetwin26/buck
test/com/facebook/buck/jvm/java/DefaultJavaLibraryIntegrationTest.java
Java
apache-2.0
46,336
/** * JBoss, Home of Professional Open Source. * Copyright 2014-2018 Red Hat, Inc., and individual contributors * as indicated by the @author tags. * * 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.jboss.pnc.rest.utils; import org.jboss.pnc.rest.restmodel.response.error.ErrorResponseRest; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; /** * @author <a href="mailto:[email protected]">Matej Lazar</a> */ public class ErrorResponse { public static Response toResponse(Exception e) { return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(new ErrorResponseRest(e)).type(MediaType.APPLICATION_JSON).build(); } }
jdcasey/pnc
rest/src/main/java/org/jboss/pnc/rest/utils/ErrorResponse.java
Java
apache-2.0
1,194
package haxe.ds; import haxe.root.*; @SuppressWarnings(value={"rawtypes", "unchecked"}) public class ObjectMap_iterator_398__Fun<K, V> extends haxe.lang.Function { public ObjectMap_iterator_398__Fun(haxe.root.Array<haxe.ds.ObjectMap> _g1, haxe.root.Array<java.lang.Object> i) { super(0, 0); this._g1 = _g1; this.i = i; } @Override public java.lang.Object __hx_invoke0_o() { V ret = ((haxe.ds.ObjectMap<K, V>) (((haxe.ds.ObjectMap) (this._g1.__get(0)) )) ).vals[((int) (haxe.lang.Runtime.toInt(this.i.__get(0))) )]; this.i.__set(0, ( ((int) (haxe.lang.Runtime.toInt(this.i.__get(0))) ) + 1 )); return ret; } public haxe.root.Array<haxe.ds.ObjectMap> _g1; public haxe.root.Array<java.lang.Object> i; }
Espigah/HaxeRepo
Learning/HaxeBinaries/jar/out/java/src/haxe/ds/ObjectMap_iterator_398__Fun.java
Java
apache-2.0
743
package net.etalia.crepuscolo.domain; import net.etalia.jalia.annotations.JsonIgnoreProperties; @JsonIgnoreProperties(ignoreUnknown=true) public interface Jsonable { }
EtaliaSA/crepuscolo
crepuscolo-core/src/main/java/net/etalia/crepuscolo/domain/Jsonable.java
Java
apache-2.0
171
// Copyright (C) 2012 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.googlesource.gerrit.plugins.branchnetwork.data; import com.google.common.cache.LoadingCache; import com.google.gerrit.extensions.events.GitReferenceUpdatedListener; import com.google.gerrit.extensions.events.NewProjectCreatedListener; import com.google.inject.Inject; import com.google.inject.name.Named; import com.googlesource.gerrit.plugins.branchnetwork.data.json.Commit; import java.util.List; public class GitCommitCacheRefresh implements GitReferenceUpdatedListener, NewProjectCreatedListener { private LoadingCache<String, List<Commit>> networkGraphDataCache; @Inject public GitCommitCacheRefresh( @Named(GitCommitCache.GRAPH_DATA_CACHE) final LoadingCache<String, List<Commit>> networkGraphDataCache) { this.networkGraphDataCache = networkGraphDataCache; } @Override public void onNewProjectCreated( com.google.gerrit.extensions.events.NewProjectCreatedListener.Event event) { networkGraphDataCache.refresh(event.getProjectName()); } @Override public void onGitReferenceUpdated(GitReferenceUpdatedListener.Event event) { if (event.getRefName().startsWith("refs/heads/")) { networkGraphDataCache.refresh(event.getProjectName()); } } }
GerritCodeReview/plugins_branch-network
src/main/java/com/googlesource/gerrit/plugins/branchnetwork/data/GitCommitCacheRefresh.java
Java
apache-2.0
1,836
/* * 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 /////////////// package com.hp.hpl.jena.ontology.impl; // Imports /////////////// import com.hp.hpl.jena.enhanced.*; import com.hp.hpl.jena.graph.*; import com.hp.hpl.jena.ontology.*; /** * <p> * Implementation of the exact qualified cardinality restriction * </p> * * @author Ian Dickinson, HP Labs * (<a href="mailto:[email protected]" >email</a>) * @version CVS $Id: CardinalityQRestrictionImpl.java,v 1.2 2009-10-06 13:04:42 ian_dickinson Exp $ */ public class CardinalityQRestrictionImpl extends QualifiedRestrictionImpl implements CardinalityQRestriction { // Constants ////////////////////////////////// // Static variables ////////////////////////////////// /** * A factory for generating QualifiedRestriction facets from nodes in enhanced graphs. * Note: should not be invoked directly by user code: use * {@link com.hp.hpl.jena.rdf.model.RDFNode#as as()} instead. */ @SuppressWarnings("hiding") public static Implementation factory = new Implementation() { @Override public EnhNode wrap( Node n, EnhGraph eg ) { if (canWrap( n, eg )) { return new CardinalityQRestrictionImpl( n, eg ); } else { throw new ConversionException( "Cannot convert node " + n + " to CardinalityQRestriction"); } } @Override public boolean canWrap( Node node, EnhGraph eg ) { return isCardinalityQRestriction( node, eg ); } }; public static boolean isCardinalityQRestriction( Node node, EnhGraph eg ) { // node will support being a QualifiedRestriction facet if it has rdf:type owl:Restriction or equivalent Profile profile = (eg instanceof OntModel) ? ((OntModel) eg).getProfile() : null; return (profile != null) && profile.isSupported( node, eg, CardinalityQRestriction.class ); } @Override public boolean isValid() { return isCardinalityQRestriction( asNode(), getGraph() ); } // Instance variables ////////////////////////////////// /** * <p> * Construct a qualified restriction node represented by the given node in the given graph. * </p> * * @param n The node that represents the resource * @param g The enh graph that contains n */ public CardinalityQRestrictionImpl( Node n, EnhGraph g ) { super( n, g ); } // Constructors ////////////////////////////////// // External signature methods ////////////////////////////////// /** * <p>Assert that this restriction restricts the property to have the given * cardinality. Any existing statements for <code>cardinalityQ</code> * will be removed.</p> * @param cardinality The cardinality of the restricted property * @exception OntProfileException If the {@link Profile#CARDINALITY_Q()} property is not supported in the current language profile. */ @Override public void setCardinalityQ( int cardinality ) { setPropertyValue( getProfile().CARDINALITY_Q(), "CARDINALITY_Q", getModel().createTypedLiteral( cardinality ) ); } /** * <p>Answer the cardinality of the restricted property.</p> * @return The cardinality of the restricted property * @exception OntProfileException If the {@link Profile#CARDINALITY_Q()} property is not supported in the current language profile. */ @Override public int getCardinalityQ() { return objectAsInt( getProfile().CARDINALITY_Q(), "CARDINALITY_Q" ); } /** * <p>Answer true if this property restriction has the given cardinality.</p> * @param cardinality The cardinality to test against * @return True if the given cardinality is the cardinality of the restricted property in this restriction * @exception OntProfileException If the {@link Profile#CARDINALITY_Q()} property is not supported in the current language profile. */ @Override public boolean hasCardinalityQ( int cardinality ) { return hasPropertyValue( getProfile().CARDINALITY_Q(), "CARDINALITY_Q", getModel().createTypedLiteral( cardinality ) ); } /** * <p>Remove the statement that this restriction has the given cardinality * for the restricted property. If this statement * is not true of the current model, nothing happens.</p> * @param cardinality A cardinality value to be removed from this restriction * @exception OntProfileException If the {@link Profile#CARDINALITY_Q()} property is not supported in the current language profile. */ @Override public void removeCardinalityQ( int cardinality ) { removePropertyValue( getProfile().CARDINALITY_Q(), "CARDINALITY_Q", getModel().createTypedLiteral( cardinality ) ); } // Internal implementation methods ////////////////////////////////// //============================================================================== // Inner class definitions //============================================================================== }
danc86/jena-core
src/main/java/com/hp/hpl/jena/ontology/impl/CardinalityQRestrictionImpl.java
Java
apache-2.0
5,936
package aodvstate; import interfaces.ILog.ILog; import interfaces.IOSOperations.IOSOperations; import interfaces.IState.IAodvState; import java.util.*; import java.net.*; /** * Class provide all the functions related to managing * the collection that hold route information * * @author : Rajiv Ramdhany, * @date : 11-aug-2007 * @email : [email protected] * * Modified by Rajiv Ramdhany * Date: 14/02/2007 * */ public class RouteList { public ConfigInfo cfgInfo; public IAodvState pStateComp; private IOSOperations osOps; private Map<InetAddress, RouteEntry> routeList; private int currUnexpiredRouteCount; /** * Constructor that creates the map object to hold data * * @param ConfigInfo cfg - config info object * @param CurrentInfo cfg - current info object */ public RouteList(IAodvState cur) { cfgInfo = (ConfigInfo) cur.getConnectedConfigInfo(); pStateComp = cur; osOps = cur.getConnectedOSOperations(); routeList = new HashMap<InetAddress, RouteEntry>(); currUnexpiredRouteCount = 0; } /** * Method to update a route entry object, given the key and the * object. If object is present, the existing is removed and new * object is inserted. Else inserted. Before inserting, a new * object is cloned from the given object * * @param InetAddress key - the key to search, i.e. IP address * @param RouteEntry entry - the entry to update */ public synchronized void update(InetAddress key, RouteEntry entry) throws Exception { RouteEntry oldEntry, clonedEntry; osOps = pStateComp.getConnectedOSOperations(); // remove the entry ( if there is an entry already, adjust // the unexpired route count ) oldEntry = (RouteEntry) routeList.get(key); if(oldEntry != null && oldEntry.routeStatusFlag == RouteEntry.ROUTE_STATUS_FLAG_VALID) { currUnexpiredRouteCount--; } // update kernel routing table // if kernel route is SET in old entry and also should SET for new entry if(oldEntry != null && oldEntry.kernelRouteSet && entry.routeStatusFlag == RouteEntry.ROUTE_STATUS_FLAG_VALID) { entry.kernelRouteSet = true; // if kernel route is NOT SET in old entry but should SET for new entry } else if((oldEntry == null || !oldEntry.kernelRouteSet) && entry.routeStatusFlag == RouteEntry.ROUTE_STATUS_FLAG_VALID) { // set kernel route entry.kernelRouteSet = true; osOps.addRoute(entry); // if kernel route is SET in old entry but should NOT SET in new entry } else if(oldEntry != null && oldEntry.kernelRouteSet && (entry.routeStatusFlag != RouteEntry.ROUTE_STATUS_FLAG_VALID)) { // remove the kernel route entry entry.kernelRouteSet = false; osOps.deleteRoute(entry); // if kernel route is NOT SET in old entry and also should NOT SET for new entry } else { entry.kernelRouteSet = false; } // clone the entry and add to list and adjust the unexpired route // count clonedEntry = entry.getCopy(); routeList.put(key, clonedEntry); if(clonedEntry.routeStatusFlag == RouteEntry.ROUTE_STATUS_FLAG_VALID) { currUnexpiredRouteCount++; } // update display pStateComp.getConnectedGUI().updateDisplay(); // log pStateComp.getLog().write(ILog.ACTIVITY_LOGGING, "Route List - Route updated, " + entry.toString()); } /** * Method to remove a route entry given the key. The method * removes the object and returns it; * * @param InetAddress key - the key to use to retrieve and delete * @return RouteEntry - the deleted object */ public synchronized RouteEntry remove(InetAddress key) { RouteEntry oldEntry; osOps = pStateComp.getConnectedOSOperations(); // if there is an entry, adjust the unexpired route count oldEntry = (RouteEntry) routeList.get(key); if(oldEntry != null && oldEntry.routeStatusFlag == RouteEntry.ROUTE_STATUS_FLAG_VALID) { currUnexpiredRouteCount--; } // update kernel routing table // if kernel route is SET in old entry then delete if(oldEntry != null && oldEntry.kernelRouteSet) { // remove the kernel route entry osOps.deleteRoute(oldEntry); } routeList.remove(key); // update display try { pStateComp.getConnectedGUI().updateDisplay(); } catch (Exception e) { e.printStackTrace(); } // log pStateComp.getLog().write(ILog.ACTIVITY_LOGGING, "Route List - Route removed, " + oldEntry.toString()); return oldEntry; } /** * Method to get a route entry object. Always returns a * clon of the original route entry object. * * @param InetAddress key - the key to use to retrieve * @return RouteEntry - the retrieved (cloned) object */ public synchronized RouteEntry get(InetAddress key) throws Exception { RouteEntry rte; rte = (RouteEntry) routeList.get(key); if(rte == null) return null; else { // always return a copy return rte.getCopy(); } } /** * Method to check whether there exist atleast one * unexpired routes. * @return boolean - true if atleast one unexpired * route else returns false */ public synchronized boolean doUnexpiredRoutesExist() { if(currUnexpiredRouteCount > 0) return true; return false; } public synchronized int getRouteCount() { return routeList.size(); } public synchronized RouteEntry[] getRouteArray() throws Exception { Object array[]; RouteEntry rtArray[]; int i; array = (routeList.values()).toArray(); if(array.length == 0) { return null; } rtArray = new RouteEntry[array.length]; for(i = 0; i < array.length; i++) { rtArray[i] = ((RouteEntry) array[i]).getCopy(); } return rtArray; } /** * * stop clean up kernel route table by removing routing entries discoevred using AODV * */ public synchronized void stop() { Object array[]; RouteEntry rte; int i; array = (routeList.values()).toArray(); for(i = 0; i < array.length; i++) { rte = (RouteEntry) array[i]; // remove kernel oute entry, if exist if(rte.kernelRouteSet) { osOps.deleteRoute(rte); } routeList.remove(rte.destIPAddr); } currUnexpiredRouteCount = 0; } }
ramdhany/AODV
AODVOverlay/aodvstate/RouteList.java
Java
apache-2.0
6,067
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.cassandra.service; import java.io.IOException; import java.net.InetAddress; import java.net.UnknownHostException; import java.util.List; import java.util.Map; import java.util.Set; import java.util.concurrent.ExecutionException; import org.apache.cassandra.dht.Range; import org.apache.cassandra.dht.Token; public interface StorageServiceMBean { /** * Retrieve the list of live nodes in the cluster, where "liveness" is * determined by the failure detector of the node being queried. * * @return set of IP addresses, as Strings */ public Set<String> getLiveNodes(); /** * Retrieve the list of unreachable nodes in the cluster, as determined * by this node's failure detector. * * @return set of IP addresses, as Strings */ public Set<String> getUnreachableNodes(); /** * Fetch a string representation of the token. * * @return a string token */ public String getToken(); /** * Retrieve a map of range to end points that describe the ring topology * of a Cassandra cluster. * * @return mapping of ranges to end points */ public Map<Range, List<String>> getRangeToEndPointMap(String keyspace); /** * Numeric load value. */ public double getLoad(); /** Human-readable load value */ public String getLoadString(); /** Human-readable load value. Keys are IP addresses. */ public Map<String, String> getLoadMap(); /** * Return the generation value for this node. * * @return generation number */ public int getCurrentGenerationNumber(); /** * This method returns the N endpoints that are responsible for storing the * specified key i.e for replication. * * @param key - key for which we need to find the endpoint return value - * the endpoint responsible for this key */ public List<InetAddress> getNaturalEndpoints(String key, String table); /** * Forces major compaction (all sstable files compacted) */ public void forceTableCompaction() throws IOException; /** * Forces major compaction on a single cf of a single keyspace */ public void forceTableCompaction(String ks, String... columnFamilies) throws IOException; /** * Trigger a cleanup of keys on all tables. */ public void forceTableCleanup() throws IOException; /** * Trigger a cleanup of keys on a single keyspace */ public void forceTableCleanup(String tableName, String... columnFamilies) throws IOException; /** * Takes the snapshot for a given table. * * @param tableName the name of the table. * @param tag the tag given to the snapshot (null is permissible) */ public void takeSnapshot(String tableName, String tag) throws IOException; /** * Takes a snapshot for every table. * * @param tag the tag given to the snapshot (null is permissible) */ public void takeAllSnapshot(String tag) throws IOException; /** * Takes a snapshot for every table. System table will be fully snapshotted, * column families in other keyspaces will be filtered using <code>cfNameRegExp</code> * @param cfNameRegExp regexp for column families selection for snapshot * @param tag the tag given to the snapshot (null is permissible) */ public void takeAllSnapshot(String cfNameRegExp, String tag) throws IOException; /** * Remove all the existing snapshots. */ public void clearSnapshot() throws IOException; /** * Flush all memtables for the given column families, or all columnfamilies for the given table * if none are explicitly listed. * @param tableName * @param columnFamilies * @throws IOException */ public void forceTableFlush(String tableName, String... columnFamilies) throws IOException; /** * Triggers proactive repair for given column families, or all columnfamilies for the given table * if none are explicitly listed. * @param tableName * @param columnFamilies * @throws IOException */ public void forceTableRepair(String tableName, String... columnFamilies) throws IOException; /** * transfer this node's data to other machines and remove it from service. */ public void decommission() throws InterruptedException; /** * @param newToken token to move this node to. * This node will unload its data onto its neighbors, and bootstrap to the new token. */ public void move(String newToken) throws IOException, InterruptedException; /** * This node will unload its data onto its neighbors, and bootstrap to share the range * of the most-loaded node in the ring. */ public void loadBalance() throws IOException, InterruptedException; /** * removeToken removes token (and all data associated with * enpoint that had it) from the ring */ public void removeToken(String token); /** set the logging level at runtime */ public void setLog4jLevel(String classQualifier, String level); /** get the operational mode (leaving, joining, normal, decommissioned, client) **/ public String getOperationMode(); /** makes node unavailable for writes, flushes memtables and replays commitlog. */ public void drain() throws IOException, InterruptedException, ExecutionException; /** force hint delivery to an endpoint **/ public void deliverHints(String host) throws UnknownHostException; public int getHintlogPlayBatchSize(); public void setHintlogPlayBatchSize(int newsize); void setHintlogPlayBatchBytes(long newsize); long getHintlogPlayBatchBytes(); /** * * @return currently configured value */ int getMemtableThroughput(); /** * MM: allow experiments with memtable throughout change at runtime * * @param throughputMBytes */ void setMemtableThroughput(int throughputMBytes); /** * * @return currently configured value */ double getMemtableOperations(); /** * MM: allow experiments with memtable operations change at runtime * * @param operations */ void setMemtableOperations(double operations); /** save row and key caches */ public void saveCaches() throws ExecutionException, InterruptedException; /** * given a list of tokens (representing the nodes in the cluster), returns * a mapping from "token -> %age of cluster owned by that token" */ public Map<Token, Float> getOwnership(); /** * @return */ float getConsistencyCheckProbability(); /** * @param p */ void setConsistencyCheckProbability(float p); /** * @return */ long getRecentReadRepairs(); /** * @return map of known endpoint locations. key: endpoint address, value datacenter:rack */ Map<String, String> getLocationsMap(); /** * @return map of known endpoint names. key: endpoint address, value: name */ Map<String, String> getEndpointNames(); /** * @return */ Map<Token, String> getPrettyTokenRing(); /** * @return */ String gossipInfo(); /** * */ void gossipStop(); /** * */ void gossipStart(); /** * */ void gossipPurgePersistent(); /** * @return */ int getMaxCommitLogSegmentsActive(); /** * @param maxCount */ void setMaxCommitLogSegmentsActive(int maxCount); /** * Resume node paused before joining the ring during bootstrap */ void completeBootstrap(); }
odnoklassniki/apache-cassandra
src/java/org/apache/cassandra/service/StorageServiceMBean.java
Java
apache-2.0
8,578
// Copyright 2021 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package com.google.api.ads.admanager.jaxws.v202105; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlSeeAlso; import javax.xml.bind.annotation.XmlType; /** * <p>Java class for SiteAction complex type. * * <p>The following schema fragment specifies the expected content contained within this class. * * <pre> * &lt;complexType name="SiteAction"> * &lt;complexContent> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType"> * &lt;sequence> * &lt;/sequence> * &lt;/restriction> * &lt;/complexContent> * &lt;/complexType> * </pre> * * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "SiteAction") @XmlSeeAlso({ SubmitSiteForApproval.class, DeactivateSite.class }) public abstract class SiteAction { }
googleads/googleads-java-lib
modules/dfp_appengine/src/main/java/com/google/api/ads/admanager/jaxws/v202105/SiteAction.java
Java
apache-2.0
1,447
/* * Copyright (c) 2013 ITOCHU Techno-Solutions Corporation. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package jp.co.ctc_g.jfw.core.util.porter; /** * <p> * このクラスは、あるオブジェクトからあるオブジェクトへ渡される単一の値とその識別子を表現します。 * このクラスは、{@link Porter#process()}内の処理において、ある種の伝達オブジェクトの役割を果たします。 * </p> * <p> * このクラスのインスタンスの典型的なライフサイクルは次の通りです。 * まず、{@link SourceStrategy#nextPair()}によりインスタンスが生成されます。 * 次に、{@link ManipulationFilter#manipulate(PortablePair)}により何らかのフィルタリング処理が行なわれます。 * この処理は複数回実行される可能性があります。 * 最後に、{@link DestinationStrategy#assign(PortablePair)}に渡されます。 * 一方で、このクラスは不変オブジェクトとして設計されているため、フィルタリング処理において他のインスタンスと差し替えられることがあります。 * </p> * <p> * PortablePairは不変オブジェクトとして設計されています。 * 移送される値とその識別子の両方またはいづれか一方が、可変オブジェクトである可能性もあります。 * このクラスはその可能性については感知せず、また、移送処理の主担当である{@link Porter}も基本的には感知しません。 * ただし、このような挙動は今後もそのようであることを保証するものではありませんし、 * 任意に拡張されたストラテジやフィルタがこの動作を期待することを推奨しません。 * </p> * <p> * また、このクラスのインスタンスの同値性及びハッシュ値は、内包される値と識別子に依存します。 * このクラスの{@link PortablePair#equals(Object)}メソッドは、内包される値と識別子のそれぞれに対してequalsメソッドを呼び出し、 * その結果が双方ともにtrueであった場合、同値であるとみなします。 * また、hashCodeもほぼ同様に、内包される値と識別子のそれぞれに対してhashCodeメソッドを呼び出し、その和をハッシュ値とします。 * </p> * @author ITOCHU Techno-Solutions Corporation. */ public class PortablePair { private final Object key; private final Object value; /** * PortablePairのインスタンスを生成します。 * この場合、識別子及び値はnullとして生成されます。 * 順序が重要になるような移送の場合には、このコンストラクタが利用される可能性があります。 */ public PortablePair() { this(null, null); } /** * PortablePairのインスタンスを生成します。 * この場合、識別子はnullとして生成されます。 * @param value 移送される値 */ public PortablePair(Object value) { this(null, value); } /** * PortablePairのインスタンスを生成します。 * 移送値及び識別子は省略することが許されるため、nullを渡すことができます。 * @param key 値の識別子 * @param value 移送される値 */ public PortablePair(Object key, Object value) { this.key = key; this.value = value; } /** * 設定されている移送値の識別子を返却します。 * PortablePairはこの識別子が実際にはどのような型であるかについては無関心です。 * この識別子の型を決定するのは{@link SourceStrategy}クラスです。 * @return 移送値の識別子となるオブジェクト */ public Object getKey() { return key; } /** * 設定されている移送値を返却します。 * PortablePairはこの移送値が実際にはどのような型であるかについては無関心です。 * この移送値の型を決定するのは{@link SourceStrategy}クラスです。 * @return 移送値として設定されているオブジェクト */ public Object getValue() { return value; } /** * このクラスのインスタンスの文字列表現です。 * 内包される値と識別子それぞれに対してtoString()メソッドを呼び出します。 * @see java.lang.Object#toString() * @return キー・バリュー形式の文字列 */ @Override public String toString() { StringBuilder description = new StringBuilder(); description.append(super.toString()).append(" {"); description.append("key = ").append(key != null ? key.toString() : "null"); description.append(", value = ").append(value != null ? value.toString() : "null").append("}"); return description.toString(); } /** * 同値性を比較します。 * 内包される値と識別子のそれぞれに対してequals()メソッドを呼び出し、 * その結果が双方ともにtrueであった場合、同値であるとみなします。 * また、値や識別子がnullとnullの場合でも、同値であるとみなします。 * つまり、 * <pre> * new PortablePair().equals(new PortablePair()); * </pre> * は<code>true</code>を返却します。 * @param another {@link PortablePair}のインスタンス * @return キー・バリューが同じかどうか * @see java.lang.Object#equals(java.lang.Object) */ @Override public boolean equals(Object another) { if (another == null) return false; if (!(another instanceof PortablePair)) return false; PortablePair friend = (PortablePair) another; boolean keyEquiv = (key == null && friend.getKey() == null) || (key != null && key.equals(friend.getKey())); boolean valueEquiv = (value == null && friend.getValue() == null) || (value != null && value.equals(friend.getValue())); return keyEquiv && valueEquiv; } /** * ハッシュ値を生成します。 * 内包される値と識別子のそれぞれに対してhashCode()メソッドを呼び出し、 * それぞれの結果の和をハッシュ値であるとします。 * @see java.lang.Object#hashCode() * @return ハッシュ値 */ @Override public int hashCode() { int hash = 1; hash = 31 + (key != null ? key.hashCode() : 0); hash = 31 + (value != null ? value.hashCode() : 0); return hash; } }
ctc-g/sinavi-jfw
util/jfw-util-core/src/main/java/jp/co/ctc_g/jfw/core/util/porter/PortablePair.java
Java
apache-2.0
7,316
// // Diese Datei wurde mit der JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.5-2 generiert // Siehe <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a> // �nderungen an dieser Datei gehen bei einer Neukompilierung des Quellschemas verloren. // Generiert: 2014.02.04 um 12:22:03 PM CET // package org.onvif.ver10.device.wsdl; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlRootElement; import javax.xml.bind.annotation.XmlType; /** * <p> * Java-Klasse f�r anonymous complex type. * * <p> * Das folgende Schemafragment gibt den erwarteten Content an, der in dieser Klasse enthalten ist. * * <pre> * <complexType> * <complexContent> * <restriction base="{http://www.w3.org/2001/XMLSchema}anyType"> * <sequence> * </sequence> * </restriction> * </complexContent> * </complexType> * </pre> * * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "") @XmlRootElement(name = "GetIPAddressFilter") public class GetIPAddressFilter { }
milg0/onvif-java-lib
src/org/onvif/ver10/device/wsdl/GetIPAddressFilter.java
Java
apache-2.0
1,165
/* * Copyright 2007-2008 Dave Griffith * * 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.jetbrains.plugins.groovy.codeInspection.control; import com.intellij.codeInspection.ProblemDescriptor; import com.intellij.openapi.project.Project; import com.intellij.psi.PsiElement; import com.intellij.psi.tree.IElementType; import com.intellij.util.IncorrectOperationException; import org.jetbrains.annotations.NotNull; import org.jetbrains.plugins.groovy.codeInspection.BaseInspection; import org.jetbrains.plugins.groovy.codeInspection.BaseInspectionVisitor; import org.jetbrains.plugins.groovy.codeInspection.GroovyFix; import org.jetbrains.plugins.groovy.codeInspection.utils.EquivalenceChecker; import org.jetbrains.plugins.groovy.codeInspection.utils.SideEffectChecker; import org.jetbrains.plugins.groovy.lang.lexer.GroovyTokenTypes; import org.jetbrains.plugins.groovy.lang.psi.api.statements.arguments.GrArgumentList; import org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.*; import org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.path.GrMethodCallExpression; import org.jetbrains.plugins.groovy.lang.psi.util.PsiUtil; public class GroovyConditionalCanBeConditionalCallInspection extends BaseInspection { @NotNull public String getDisplayName() { return "Conditional expression can be conditional call"; } @NotNull public String getGroupDisplayName() { return CONTROL_FLOW; } public String buildErrorString(Object... args) { return "Conditional expression can be call #loc"; } public GroovyFix buildFix(PsiElement location) { return new CollapseConditionalFix(); } private static class CollapseConditionalFix extends GroovyFix { @NotNull public String getName() { return "Replace with conditional call"; } public void doFix(Project project, ProblemDescriptor descriptor) throws IncorrectOperationException { final GrConditionalExpression expression = (GrConditionalExpression) descriptor.getPsiElement(); final GrBinaryExpression binaryCondition = (GrBinaryExpression)PsiUtil.skipParentheses(expression.getCondition(), false); final GrMethodCallExpression call; if (isInequality(binaryCondition)) { call = (GrMethodCallExpression) expression.getThenBranch(); } else { call = (GrMethodCallExpression) expression.getElseBranch(); } final GrReferenceExpression methodExpression = (GrReferenceExpression) call.getInvokedExpression(); final GrExpression qualifier = methodExpression.getQualifierExpression(); final String methodName = methodExpression.getReferenceName(); final GrArgumentList argumentList = call.getArgumentList(); if (argumentList == null) { return; } replaceExpression(expression, qualifier.getText() + "?." + methodName + argumentList.getText()); } } public BaseInspectionVisitor buildVisitor() { return new Visitor(); } private static class Visitor extends BaseInspectionVisitor { public void visitConditionalExpression(GrConditionalExpression expression) { super.visitConditionalExpression(expression); GrExpression condition = expression.getCondition(); final GrExpression thenBranch = expression.getThenBranch(); final GrExpression elseBranch = expression.getElseBranch(); if (condition == null || thenBranch == null || elseBranch == null) { return; } if (SideEffectChecker.mayHaveSideEffects(condition)) { return; } condition = (GrExpression)PsiUtil.skipParentheses(condition, false); if (!(condition instanceof GrBinaryExpression)) { return; } final GrBinaryExpression binaryCondition = (GrBinaryExpression) condition; final GrExpression lhs = binaryCondition.getLeftOperand(); final GrExpression rhs = binaryCondition.getRightOperand(); if (isInequality(binaryCondition) && isNull(elseBranch)) { if (isNull(lhs) && isCallTargeting(thenBranch, rhs) || isNull(rhs) && isCallTargeting(thenBranch, lhs)) { registerError(expression); } } if (isEquality(binaryCondition) && isNull(thenBranch)) { if (isNull(lhs) && isCallTargeting(elseBranch, rhs) || isNull(rhs) && isCallTargeting(elseBranch, lhs)) { registerError(expression); } } } private static boolean isCallTargeting(GrExpression call, GrExpression expression) { if (!(call instanceof GrMethodCallExpression)) { return false; } final GrMethodCallExpression callExpression = (GrMethodCallExpression) call; final GrExpression methodExpression = callExpression.getInvokedExpression(); if (!(methodExpression instanceof GrReferenceExpression)) { return false; } final GrReferenceExpression referenceExpression = (GrReferenceExpression) methodExpression; if (!GroovyTokenTypes.mDOT.equals(referenceExpression.getDotTokenType())) { return false; } return EquivalenceChecker.expressionsAreEquivalent(expression, referenceExpression.getQualifierExpression()); } } private static boolean isEquality(GrBinaryExpression binaryCondition) { final IElementType tokenType = binaryCondition.getOperationTokenType(); return GroovyTokenTypes.mEQUAL == tokenType; } private static boolean isInequality(GrBinaryExpression binaryCondition) { final IElementType tokenType = binaryCondition.getOperationTokenType(); return GroovyTokenTypes.mNOT_EQUAL == tokenType; } private static boolean isNull(GrExpression expression) { return "null".equals(expression.getText()); } }
joewalnes/idea-community
plugins/groovy/src/org/jetbrains/plugins/groovy/codeInspection/control/GroovyConditionalCanBeConditionalCallInspection.java
Java
apache-2.0
6,221
package mx.com.gm.sga.servicio; import java.util.List; import javax.ejb.Local; import mx.com.gm.sga.domain.Persona; @Local public interface PersonaService { public List<Persona> listarPersonas(); public Persona encontrarPersonaPorId(Persona persona); public Persona econtrarPersonaPorEmail(Persona persona); public void registrarPersona(Persona persona); public void modificarPersona(Persona persona); public void eliminarPersona(Persona persona); }
juanfcosanz/Java-EE
App Web/sga-jee/src/main/java/mx/com/gm/sga/servicio/PersonaService.java
Java
apache-2.0
466
/* * Copyright 2012 JBoss 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 org.drools.planner.core.domain.solution.cloner; import java.lang.reflect.Constructor; import java.lang.reflect.Field; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.util.ArrayList; import java.util.Collection; import java.util.Comparator; import java.util.HashMap; import java.util.HashSet; import java.util.IdentityHashMap; import java.util.LinkedHashMap; import java.util.LinkedHashSet; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Queue; import java.util.Set; import java.util.SortedMap; import java.util.SortedSet; import java.util.TreeMap; import java.util.TreeSet; import org.drools.planner.api.domain.solution.cloner.SolutionCloner; import org.drools.planner.core.domain.common.PropertyAccessor; import org.drools.planner.core.domain.solution.SolutionDescriptor; import org.drools.planner.core.solution.Solution; public class FieldAccessingSolutionCloner<SolutionG extends Solution> implements SolutionCloner<SolutionG> { protected SolutionDescriptor solutionDescriptor; protected Map<Class, Constructor> constructorCache = new HashMap<Class, Constructor>(); protected Map<Class, Field[]> fieldsCache = new HashMap<Class, Field[]>(); public FieldAccessingSolutionCloner(SolutionDescriptor solutionDescriptor) { this.solutionDescriptor = solutionDescriptor; } // ************************************************************************ // Worker methods // ************************************************************************ public SolutionG cloneSolution(SolutionG originalSolution) { return new FieldAccessingSolutionClonerRun().cloneSolution(originalSolution); } protected <C> Constructor<C> retrieveCachedConstructor(Class<C> clazz) throws NoSuchMethodException { Constructor<C> constructor = constructorCache.get(clazz); if (constructor == null) { constructor = clazz.getConstructor(); constructor.setAccessible(true); constructorCache.put(clazz, constructor); } return constructor; } protected <C> Field[] retrieveCachedFields(Class<C> clazz) { Field[]fields = fieldsCache.get(clazz); if (fields == null) { fields = clazz.getDeclaredFields(); for (Field field : fields) { // no need to reset because getDeclaredFields() creates new Field instances field.setAccessible(true); } fieldsCache.put(clazz, fields); } return fields; } protected class FieldAccessingSolutionClonerRun { protected Map<Object,Object> originalToCloneMap; protected Queue<Unprocessed> unprocessedQueue; protected SolutionG cloneSolution(SolutionG originalSolution) { unprocessedQueue = new LinkedList<Unprocessed>(); originalToCloneMap = new IdentityHashMap<Object, Object>( solutionDescriptor.getPlanningEntityCount(originalSolution) + 1); SolutionG cloneSolution = clone(originalSolution); processQueue(); validateCloneSolution(originalSolution, cloneSolution); return cloneSolution; } protected <C> C clone(C original) { if (original == null) { return null; } C existingClone = (C) originalToCloneMap.get(original); if (existingClone != null) { return existingClone; } Class<C> clazz = (Class<C>) original.getClass(); C clone = constructClone(clazz); originalToCloneMap.put(original, clone); copyFields(clazz, original, clone); return clone; } protected <C> C constructClone(Class<C> clazz) { try { Constructor<C> constructor = retrieveCachedConstructor(clazz); return constructor.newInstance(); // TODO Upgrade to JDK 1.7: catch (ReflectiveOperationException e) instead of these 4 } catch (InvocationTargetException e) { throw new IllegalStateException("The class (" + clazz + ") should have a no-arg constructor to create a clone.", e); } catch (NoSuchMethodException e) { throw new IllegalStateException("The class (" + clazz + ") should have a no-arg constructor to create a clone.", e); } catch (InstantiationException e) { throw new IllegalStateException("The class (" + clazz + ") should have a no-arg constructor to create a clone.", e); } catch (IllegalAccessException e) { throw new IllegalStateException("The class (" + clazz + ") should have a no-arg constructor to create a clone.", e); } } protected <C> void copyFields(Class<C> clazz, C original, C clone) { for (Field field : retrieveCachedFields(clazz)) { Object originalValue = getFieldValue(original, field); if (isDeepCloneField(field, originalValue)) { // Postpone filling in the fields unprocessedQueue.add(new Unprocessed(clone, field, originalValue)); } else { // Shallow copy setFieldValue(clone, field, originalValue); } } Class<? super C> superclass = clazz.getSuperclass(); if (superclass != null) { copyFields(superclass, original, clone); } } protected boolean isDeepCloneField(Field field, Object originalValue) { if (originalValue == null) { return false; } if (isFieldAnEntityPropertyOnSolution(field)) { return true; } if (isValueAnEntity(originalValue)) { return true; } return false; } protected boolean isFieldAnEntityPropertyOnSolution(Field field) { Class<?> declaringClass = field.getDeclaringClass(); if (declaringClass == ((Class) solutionDescriptor.getSolutionClass())) { String fieldName = field.getName(); // This assumes we're dealing with a simple getter/setter. // If that assumption is false, validateCloneSolution(...) fails-fast. if (solutionDescriptor.getEntityPropertyAccessorMap().get(fieldName) != null) { return true; } // This assumes we're dealing with a simple getter/setter. // If that assumption is false, validateCloneSolution(...) fails-fast. if (solutionDescriptor.getEntityCollectionPropertyAccessorMap().get(fieldName) != null) { return true; } } return false; } protected boolean isValueAnEntity(Object originalValue) { Class valueClass = originalValue.getClass(); if (solutionDescriptor.getPlanningEntityClassSet().contains(valueClass) || valueClass == ((Class) solutionDescriptor.getSolutionClass())) { return true; } return false; } protected void processQueue() { while (!unprocessedQueue.isEmpty()) { Unprocessed unprocessed = unprocessedQueue.remove(); process(unprocessed); } } protected void process(Unprocessed unprocessed) { Object cloneValue; if (unprocessed.originalValue instanceof Collection) { cloneValue = cloneCollection(unprocessed.field.getType(), (Collection<?>) unprocessed.originalValue); } else if (unprocessed.originalValue instanceof Map) { cloneValue = cloneMap(unprocessed.field.getType(), (Map<?,?>) unprocessed.originalValue); } else { cloneValue = clone(unprocessed.originalValue); } setFieldValue(unprocessed.bean, unprocessed.field, cloneValue); } protected <E> Collection<E> cloneCollection(Class<?> expectedType, Collection<E> originalCollection) { Collection<E> cloneCollection = constructCloneCollection(originalCollection); if (!expectedType.isInstance(cloneCollection)) { throw new IllegalStateException("The cloneCollectionClass (" + cloneCollection.getClass() + ") created for originalCollectionClass (" + originalCollection.getClass() + ") is not assignable to the field's type (" + expectedType + ")." + " Consider replacing the default " + SolutionCloner.class.getSimpleName() + "."); } for (E originalElement : originalCollection) { E cloneElement = clone(originalElement); cloneCollection.add(cloneElement); } return cloneCollection; } protected <E> Collection<E> constructCloneCollection(Collection<E> originalCollection) { if (originalCollection instanceof List) { if (originalCollection instanceof ArrayList) { return new ArrayList<E>(originalCollection.size()); } else if (originalCollection instanceof LinkedList) { return new LinkedList<E>(); } else { // Default List return new ArrayList<E>(originalCollection.size()); } } if (originalCollection instanceof Set) { if (originalCollection instanceof SortedSet) { Comparator<E> setComparator = ((SortedSet) originalCollection).comparator(); return new TreeSet<E>(setComparator); } else if (originalCollection instanceof LinkedHashSet) { return new LinkedHashSet<E>(originalCollection.size()); } else if (originalCollection instanceof HashSet) { return new HashSet<E>(originalCollection.size()); } else { // Default Set // Default to a LinkedHashSet to respect order return new LinkedHashSet<E>(originalCollection.size()); } } else { // Default collection return new ArrayList<E>(originalCollection.size()); } } protected <K,V> Map<K,V> cloneMap(Class<?> expectedType, Map<K,V> originalMap) { Map<K,V> cloneMap = constructCloneMap(originalMap); if (!expectedType.isInstance(cloneMap)) { throw new IllegalStateException("The cloneMapClass (" + cloneMap.getClass() + ") created for originalMapClass (" + originalMap.getClass() + ") is not assignable to the field's type (" + expectedType + ")." + " Consider replacing the default " + SolutionCloner.class.getSimpleName() + "."); } for (Map.Entry<K,V> originalEntry : originalMap.entrySet()) { K cloneKey = clone(originalEntry.getKey()); V cloneValue = clone(originalEntry.getValue()); cloneMap.put(cloneKey, cloneValue); } return cloneMap; } protected <K,V> Map<K,V> constructCloneMap(Map<K,V> originalMap) { // Normally a Map will never be selected for cloning, but extending implementations might anyway if (originalMap instanceof SortedMap) { Comparator setComparator = ((SortedMap) originalMap).comparator(); return new TreeMap<K,V>(setComparator); } else if (originalMap instanceof LinkedHashMap) { return new LinkedHashMap<K,V>(originalMap.size()); } else if (originalMap instanceof HashMap) { return new HashMap<K,V>(originalMap.size()); } else { // Default Map // Default to a LinkedHashMap to respect order return new LinkedHashMap<K,V>(originalMap.size()); } } /** * Fails fast if {@link #isFieldAnEntityPropertyOnSolution} assumptions were wrong. * @param originalSolution never null * @param cloneSolution never null */ protected void validateCloneSolution(SolutionG originalSolution, SolutionG cloneSolution) { for (PropertyAccessor propertyAccessor : solutionDescriptor.getEntityPropertyAccessorMap().values()) { Object originalProperty = propertyAccessor.executeGetter(originalSolution); if (originalProperty != null) { Object cloneProperty = propertyAccessor.executeGetter(cloneSolution); if (originalProperty == cloneProperty) { throw new IllegalStateException( "The solutionProperty (" + propertyAccessor.getName() + ") was not cloned as expected." + " The " + FieldAccessingSolutionCloner.class.getSimpleName() + " failed to recognize" + " that property's field, probably because its field name is different."); } } } for (PropertyAccessor propertyAccessor : solutionDescriptor.getEntityCollectionPropertyAccessorMap().values()) { Object originalProperty = propertyAccessor.executeGetter(originalSolution); if (originalProperty != null) { Object cloneProperty = propertyAccessor.executeGetter(cloneSolution); if (originalProperty == cloneProperty) { throw new IllegalStateException( "The solutionProperty (" + propertyAccessor.getName() + ") was not cloned as expected." + " The " + FieldAccessingSolutionCloner.class.getSimpleName() + " failed to recognize" + " that property's field, probably because its field name is different."); } } } } protected Object getFieldValue(Object bean, Field field) { try { return field.get(bean); } catch (IllegalAccessException e) { throw new IllegalStateException("The class (" + bean.getClass() + ") has a field (" + field + ") which can not be read to create a clone.", e); } } protected void setFieldValue(Object bean, Field field, Object value) { try { field.set(bean, value); } catch (IllegalAccessException e) { throw new IllegalStateException("The class (" + bean.getClass() + ") has a field (" + field + ") which can not be written with the value (" + value + ") to create a clone.", e); } } } protected static class Unprocessed { protected Object bean; protected Field field; protected Object originalValue; public Unprocessed(Object bean, Field field, Object originalValue) { this.bean = bean; this.field = field; this.originalValue = originalValue; } } }
elsam/drools-planner-old
drools-planner-core/src/main/java/org/drools/planner/core/domain/solution/cloner/FieldAccessingSolutionCloner.java
Java
apache-2.0
16,245
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /* package org.apache.taverna.lang.io; import java.io.InputStream; import java.io.OutputStream; import org.apache.log4j.Logger; /** * Copies an InputStream to an OutputStream. * * @author Tom Oinn */ public class StreamCopier extends Thread { private static Logger logger = Logger .getLogger(StreamCopier.class); InputStream is; OutputStream os; /** * Create a new StreamCopier which will, when started, copy the specified * InputStream to the specified OutputStream */ public StreamCopier(InputStream is, OutputStream os) { super("StreamCopier"); this.is = is; this.os = os; } /** * Start copying the stream, exits when the InputStream runs out of data */ public void run() { try { byte[] buffer = new byte[1024]; int bytesRead; while ((bytesRead = is.read(buffer)) != -1) { os.write(buffer, 0, bytesRead); } os.flush(); os.close(); } catch (Exception ex) { logger.error("Could not copy stream", ex); } } }
ThilinaManamgoda/incubator-taverna-workbench
taverna-io/src/main/java/org/apache/taverna/lang/io/StreamCopier.java
Java
apache-2.0
1,783
package com.wizecore.metrics; /** * Mark interface as persistent. */ public interface Persistent { void save(); }
wizecore/persistent-metrics
src/main/java/com/wizecore/metrics/Persistent.java
Java
apache-2.0
119
/** * 各种算法汇总目录 * string * array * stack * tree */ package org.glamey.training.codes;
glameyzhou/training
codes/src/main/java/org/glamey/training/codes/package-info.java
Java
apache-2.0
106
/* * Copyright 2017-2022 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with * the License. A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR * CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions * and limitations under the License. */ package com.amazonaws.services.glue.model.transform; import java.math.*; import javax.annotation.Generated; import com.amazonaws.services.glue.model.*; import com.amazonaws.transform.SimpleTypeJsonUnmarshallers.*; import com.amazonaws.transform.*; import com.fasterxml.jackson.core.JsonToken; import static com.fasterxml.jackson.core.JsonToken.*; /** * UpdateJsonClassifierRequest JSON Unmarshaller */ @Generated("com.amazonaws:aws-java-sdk-code-generator") public class UpdateJsonClassifierRequestJsonUnmarshaller implements Unmarshaller<UpdateJsonClassifierRequest, JsonUnmarshallerContext> { public UpdateJsonClassifierRequest unmarshall(JsonUnmarshallerContext context) throws Exception { UpdateJsonClassifierRequest updateJsonClassifierRequest = new UpdateJsonClassifierRequest(); int originalDepth = context.getCurrentDepth(); String currentParentElement = context.getCurrentParentElement(); int targetDepth = originalDepth + 1; JsonToken token = context.getCurrentToken(); if (token == null) token = context.nextToken(); if (token == VALUE_NULL) { return null; } while (true) { if (token == null) break; if (token == FIELD_NAME || token == START_OBJECT) { if (context.testExpression("Name", targetDepth)) { context.nextToken(); updateJsonClassifierRequest.setName(context.getUnmarshaller(String.class).unmarshall(context)); } if (context.testExpression("JsonPath", targetDepth)) { context.nextToken(); updateJsonClassifierRequest.setJsonPath(context.getUnmarshaller(String.class).unmarshall(context)); } } else if (token == END_ARRAY || token == END_OBJECT) { if (context.getLastParsedParentElement() == null || context.getLastParsedParentElement().equals(currentParentElement)) { if (context.getCurrentDepth() <= originalDepth) break; } } token = context.nextToken(); } return updateJsonClassifierRequest; } private static UpdateJsonClassifierRequestJsonUnmarshaller instance; public static UpdateJsonClassifierRequestJsonUnmarshaller getInstance() { if (instance == null) instance = new UpdateJsonClassifierRequestJsonUnmarshaller(); return instance; } }
aws/aws-sdk-java
aws-java-sdk-glue/src/main/java/com/amazonaws/services/glue/model/transform/UpdateJsonClassifierRequestJsonUnmarshaller.java
Java
apache-2.0
3,116
/* * Copyright 2017-2022 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with * the License. A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR * CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions * and limitations under the License. */ package com.amazonaws.services.lexmodelsv2.model.transform; import java.math.*; import javax.annotation.Generated; import com.amazonaws.services.lexmodelsv2.model.*; import com.amazonaws.transform.SimpleTypeJsonUnmarshallers.*; import com.amazonaws.transform.*; import static com.fasterxml.jackson.core.JsonToken.*; /** * DeleteSlotResult JSON Unmarshaller */ @Generated("com.amazonaws:aws-java-sdk-code-generator") public class DeleteSlotResultJsonUnmarshaller implements Unmarshaller<DeleteSlotResult, JsonUnmarshallerContext> { public DeleteSlotResult unmarshall(JsonUnmarshallerContext context) throws Exception { DeleteSlotResult deleteSlotResult = new DeleteSlotResult(); return deleteSlotResult; } private static DeleteSlotResultJsonUnmarshaller instance; public static DeleteSlotResultJsonUnmarshaller getInstance() { if (instance == null) instance = new DeleteSlotResultJsonUnmarshaller(); return instance; } }
aws/aws-sdk-java
aws-java-sdk-lexmodelsv2/src/main/java/com/amazonaws/services/lexmodelsv2/model/transform/DeleteSlotResultJsonUnmarshaller.java
Java
apache-2.0
1,576
package de.northernstars.mr.botcontrol.network; import java.io.StringReader; import java.io.StringWriter; import java.util.ArrayList; import java.util.List; import javax.xml.bind.JAXB; import de.northernstars.mr.botcontrol.core.protocol.BotProtocolSection; import de.northernstars.mr.botcontrol.network.protocol.NetBotProtocolSection; public class CommandPackage { private int commandProtocolRevision = 2;; private List<NetBotProtocolSection> sections = new ArrayList<NetBotProtocolSection>(); /** * Default constructor */ public CommandPackage() {} /** * Constructor * @param aProtocolRevision {@link Integer} protocol revision */ public CommandPackage(int aProtocolRevision){ commandProtocolRevision = aProtocolRevision; } /** * Adds a section * @param section {@link BotProtocolSection} to add */ public boolean addSection(NetBotProtocolSection section){ return sections.add(section); } /** * Removes a {@link BotProtocolSection} from list. * @param index {@link Integer} index to remove */ public NetBotProtocolSection removeSections(int index){ return sections.remove(index); } /** * @return the sections */ public List<NetBotProtocolSection> getSections() { return sections; } /** * @param sections the sections to set */ public void setSections(List<NetBotProtocolSection> sections) { this.sections = sections; } /** * @return the protocolRevision */ public int getCommandProtocolRevision() { return commandProtocolRevision; } /** * @param protocolRevision the protocolRevision to set */ public void setCommandProtocolRevision(int protocolRevision) { this.commandProtocolRevision = protocolRevision; } /** * Converts {@link CommandPackage} to xml data {@link String} * @return */ public String toXml(){ StringWriter writer = new StringWriter(); JAXB.marshal(this, writer); return writer.toString(); } /** * Converts xml data {@link String} to {@link CommandPackage} * @param xml xml data {@link String} * @return {@link CommandPackage} */ public static CommandPackage fromXML(String xml){ StringReader reader = new StringReader(xml); return JAXB.unmarshal(reader, CommandPackage.class); } }
NorthernStars/MR-Botcontrol
mrBotControl/src/de/northernstars/mr/botcontrol/network/CommandPackage.java
Java
apache-2.0
2,231
/* * Copyright 2019 Red Hat, Inc. and/or its affiliates. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.kie.workbench.common.stunner.bpmn.backend.converters.tostunner.textannotation; import org.eclipse.bpmn2.Bpmn2Factory; import org.eclipse.bpmn2.TextAnnotation; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.kie.workbench.common.stunner.bpmn.backend.converters.Result; import org.kie.workbench.common.stunner.bpmn.backend.converters.TypedFactoryManager; import org.kie.workbench.common.stunner.bpmn.backend.converters.tostunner.BpmnNode; import org.kie.workbench.common.stunner.bpmn.backend.converters.tostunner.properties.PropertyReaderFactory; import org.kie.workbench.common.stunner.bpmn.backend.converters.tostunner.properties.TextAnnotationPropertyReader; import org.kie.workbench.common.stunner.bpmn.definition.BPMNViewDefinition; import org.kie.workbench.common.stunner.core.graph.Edge; import org.kie.workbench.common.stunner.core.graph.Node; import org.kie.workbench.common.stunner.core.graph.content.view.View; import org.mockito.Mock; import org.mockito.runners.MockitoJUnitRunner; import static org.junit.Assert.assertEquals; import static org.mockito.Matchers.anyString; import static org.mockito.Matchers.eq; import static org.powermock.api.mockito.PowerMockito.when; @RunWith(MockitoJUnitRunner.class) public class TextAnnotationConverterTest { private TextAnnotationConverter tested; @Mock private TypedFactoryManager typedFactoryManager; @Mock private PropertyReaderFactory propertyReaderFactory; private TextAnnotation element; @Mock private Node<View<org.kie.workbench.common.stunner.bpmn.definition.TextAnnotation>, Edge> node; @Mock private View<org.kie.workbench.common.stunner.bpmn.definition.TextAnnotation> content; @Mock private org.kie.workbench.common.stunner.bpmn.definition.TextAnnotation def; @Mock private TextAnnotationPropertyReader reader; @Before public void setUp() { element = Bpmn2Factory.eINSTANCE.createTextAnnotation(); tested = new TextAnnotationConverter(typedFactoryManager, propertyReaderFactory); when(typedFactoryManager.newNode(anyString(), eq(org.kie.workbench.common.stunner.bpmn.definition.TextAnnotation.class))).thenReturn(node); when(node.getContent()).thenReturn(content); when(content.getDefinition()).thenReturn(def); when(propertyReaderFactory.of(element)).thenReturn(reader); } @Test public void convert() { final Result<BpmnNode> node = tested.convert(element); final Node<? extends View<? extends BPMNViewDefinition>, ?> value = node.value().value(); assertEquals(content, value.getContent()); assertEquals(def, value.getContent().getDefinition()); } }
Rikkola/kie-wb-common
kie-wb-common-stunner/kie-wb-common-stunner-sets/kie-wb-common-stunner-bpmn/kie-wb-common-stunner-bpmn-backend/src/test/java/org/kie/workbench/common/stunner/bpmn/backend/converters/tostunner/textannotation/TextAnnotationConverterTest.java
Java
apache-2.0
3,405
/* * Copyright 2014-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with * the License. A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR * CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions * and limitations under the License. */ package com.amazonaws.services.ec2.model; import java.io.Serializable; import javax.annotation.Generated; /** * <p> * Indicates whether an instance is configured for hibernation. * </p> * * @see <a href="http://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/LaunchTemplateHibernationOptions" * target="_top">AWS API Documentation</a> */ @Generated("com.amazonaws:aws-java-sdk-code-generator") public class LaunchTemplateHibernationOptions implements Serializable, Cloneable { /** * <p> * If this parameter is set to <code>true</code>, the instance is enabled for hibernation; otherwise, it is not * enabled for hibernation. * </p> */ private Boolean configured; /** * <p> * If this parameter is set to <code>true</code>, the instance is enabled for hibernation; otherwise, it is not * enabled for hibernation. * </p> * * @param configured * If this parameter is set to <code>true</code>, the instance is enabled for hibernation; otherwise, it is * not enabled for hibernation. */ public void setConfigured(Boolean configured) { this.configured = configured; } /** * <p> * If this parameter is set to <code>true</code>, the instance is enabled for hibernation; otherwise, it is not * enabled for hibernation. * </p> * * @return If this parameter is set to <code>true</code>, the instance is enabled for hibernation; otherwise, it is * not enabled for hibernation. */ public Boolean getConfigured() { return this.configured; } /** * <p> * If this parameter is set to <code>true</code>, the instance is enabled for hibernation; otherwise, it is not * enabled for hibernation. * </p> * * @param configured * If this parameter is set to <code>true</code>, the instance is enabled for hibernation; otherwise, it is * not enabled for hibernation. * @return Returns a reference to this object so that method calls can be chained together. */ public LaunchTemplateHibernationOptions withConfigured(Boolean configured) { setConfigured(configured); return this; } /** * <p> * If this parameter is set to <code>true</code>, the instance is enabled for hibernation; otherwise, it is not * enabled for hibernation. * </p> * * @return If this parameter is set to <code>true</code>, the instance is enabled for hibernation; otherwise, it is * not enabled for hibernation. */ public Boolean isConfigured() { return this.configured; } /** * Returns a string representation of this object. This is useful for testing and debugging. Sensitive data will be * redacted from this string using a placeholder value. * * @return A string representation of this object. * * @see java.lang.Object#toString() */ @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("{"); if (getConfigured() != null) sb.append("Configured: ").append(getConfigured()); sb.append("}"); return sb.toString(); } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (obj instanceof LaunchTemplateHibernationOptions == false) return false; LaunchTemplateHibernationOptions other = (LaunchTemplateHibernationOptions) obj; if (other.getConfigured() == null ^ this.getConfigured() == null) return false; if (other.getConfigured() != null && other.getConfigured().equals(this.getConfigured()) == false) return false; return true; } @Override public int hashCode() { final int prime = 31; int hashCode = 1; hashCode = prime * hashCode + ((getConfigured() == null) ? 0 : getConfigured().hashCode()); return hashCode; } @Override public LaunchTemplateHibernationOptions clone() { try { return (LaunchTemplateHibernationOptions) super.clone(); } catch (CloneNotSupportedException e) { throw new IllegalStateException("Got a CloneNotSupportedException from Object.clone() " + "even though we're Cloneable!", e); } } }
jentfoo/aws-sdk-java
aws-java-sdk-ec2/src/main/java/com/amazonaws/services/ec2/model/LaunchTemplateHibernationOptions.java
Java
apache-2.0
5,039
/* * Copyright 2000-2009 JetBrains s.r.o. * * 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.intellij.refactoring.inline; import com.intellij.openapi.diagnostic.Logger; import com.intellij.openapi.project.Project; import com.intellij.openapi.util.Ref; import com.intellij.openapi.wm.WindowManager; import com.intellij.psi.*; import com.intellij.psi.search.GlobalSearchScope; import com.intellij.psi.search.searches.ReferencesSearch; import com.intellij.psi.util.PsiTreeUtil; import com.intellij.psi.util.PsiUtil; import com.intellij.refactoring.BaseRefactoringProcessor; import com.intellij.refactoring.RefactoringBundle; import com.intellij.refactoring.rename.NonCodeUsageInfoFactory; import com.intellij.refactoring.util.TextOccurrencesUtil; import com.intellij.usageView.UsageInfo; import com.intellij.usageView.UsageViewDescriptor; import com.intellij.util.IncorrectOperationException; import com.intellij.util.containers.MultiMap; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.util.*; /** * @author yole */ public class InlineToAnonymousClassProcessor extends BaseRefactoringProcessor { private static final Logger LOG = Logger.getInstance("#com.intellij.refactoring.inline.InlineToAnonymousClassProcessor"); private PsiClass myClass; private final PsiCall myCallToInline; private final boolean myInlineThisOnly; private final boolean mySearchInComments; private final boolean mySearchInNonJavaFiles; protected InlineToAnonymousClassProcessor(Project project, PsiClass psiClass, @Nullable final PsiCall callToInline, boolean inlineThisOnly, final boolean searchInComments, final boolean searchInNonJavaFiles) { super(project); myClass = psiClass; myCallToInline = callToInline; myInlineThisOnly = inlineThisOnly; if (myInlineThisOnly) assert myCallToInline != null; mySearchInComments = searchInComments; mySearchInNonJavaFiles = searchInNonJavaFiles; } protected UsageViewDescriptor createUsageViewDescriptor(UsageInfo[] usages) { return new InlineViewDescriptor(myClass); } @NotNull protected UsageInfo[] findUsages() { if (myInlineThisOnly) { return new UsageInfo[] { new UsageInfo(myCallToInline) }; } Set<UsageInfo> usages = new HashSet<UsageInfo>(); for (PsiReference reference : ReferencesSearch.search(myClass)) { usages.add(new UsageInfo(reference.getElement())); } final String qName = myClass.getQualifiedName(); if (qName != null) { List<UsageInfo> nonCodeUsages = new ArrayList<UsageInfo>(); if (mySearchInComments) { TextOccurrencesUtil.addUsagesInStringsAndComments(myClass, qName, nonCodeUsages, new NonCodeUsageInfoFactory(myClass, qName)); } if (mySearchInNonJavaFiles) { GlobalSearchScope projectScope = GlobalSearchScope.projectScope(myClass.getProject()); TextOccurrencesUtil.addTextOccurences(myClass, qName, projectScope, nonCodeUsages, new NonCodeUsageInfoFactory(myClass, qName)); } usages.addAll(nonCodeUsages); } return usages.toArray(new UsageInfo[usages.size()]); } protected void refreshElements(PsiElement[] elements) { assert elements.length == 1; myClass = (PsiClass) elements [0]; } protected boolean isPreviewUsages(UsageInfo[] usages) { if (super.isPreviewUsages(usages)) return true; for(UsageInfo usage: usages) { if (isForcePreview(usage)) { WindowManager.getInstance().getStatusBar(myProject).setInfo(RefactoringBundle.message("occurrences.found.in.comments.strings.and.non.java.files")); return true; } } return false; } private static boolean isForcePreview(final UsageInfo usage) { if (usage.isNonCodeUsage) return true; PsiElement element = usage.getElement(); if (element != null) { PsiFile file = element.getContainingFile(); if (!(file instanceof PsiJavaFile)) { return true; } } return false; } protected boolean preprocessUsages(final Ref<UsageInfo[]> refUsages) { MultiMap<PsiElement, String> conflicts = getConflicts(refUsages.get()); if (!conflicts.isEmpty()) { return showConflicts(conflicts, refUsages.get()); } return super.preprocessUsages(refUsages); } public MultiMap<PsiElement, String> getConflicts(final UsageInfo[] usages) { final MultiMap<PsiElement, String> result = new MultiMap<PsiElement, String>(); ReferencedElementsCollector collector = new ReferencedElementsCollector() { protected void checkAddMember(@NotNull final PsiMember member) { if (PsiTreeUtil.isAncestor(myClass, member, false)) { return; } final PsiModifierList modifierList = member.getModifierList(); if (member.getContainingClass() == myClass.getSuperClass() && modifierList != null && modifierList.hasModifierProperty(PsiModifier.PROTECTED)) { // ignore access to protected members of superclass - they'll be accessible anyway return; } super.checkAddMember(member); } }; InlineMethodProcessor.addInaccessibleMemberConflicts(myClass, usages, collector, result); myClass.accept(new JavaRecursiveElementVisitor(){ @Override public void visitParameter(PsiParameter parameter) { super.visitParameter(parameter); if (PsiUtil.resolveClassInType(parameter.getType()) != myClass) return; for (PsiReference psiReference : ReferencesSearch.search(parameter)) { final PsiElement refElement = psiReference.getElement(); if (refElement instanceof PsiExpression) { final PsiReferenceExpression referenceExpression = PsiTreeUtil.getParentOfType(refElement, PsiReferenceExpression.class); if (referenceExpression != null && referenceExpression.getQualifierExpression() == refElement) { final PsiElement resolvedMember = referenceExpression.resolve(); if (resolvedMember != null && PsiTreeUtil.isAncestor(myClass, resolvedMember, false)) { if (resolvedMember instanceof PsiMethod) { if (myClass.findMethodsBySignature((PsiMethod)resolvedMember, true).length > 1) { //skip inherited methods continue; } } result.putValue(refElement, "Class cannot be inlined because a call to its member inside body"); } } } } } @Override public void visitNewExpression(PsiNewExpression expression) { super.visitNewExpression(expression); if (PsiUtil.resolveClassInType(expression.getType()) != myClass) return; result.putValue(expression, "Class cannot be inlined because a call to its constructor inside body"); } @Override public void visitMethodCallExpression(PsiMethodCallExpression expression) { super.visitMethodCallExpression(expression); final PsiReferenceExpression methodExpression = expression.getMethodExpression(); final PsiExpression qualifierExpression = methodExpression.getQualifierExpression(); if (qualifierExpression != null && PsiUtil.resolveClassInType(qualifierExpression.getType()) != myClass) return; final PsiElement resolved = methodExpression.resolve(); if (resolved instanceof PsiMethod) { final PsiMethod method = (PsiMethod)resolved; if ("getClass".equals(method.getName()) && method.getParameterList().getParametersCount() == 0) { result.putValue(methodExpression, "Result of getClass() invocation would be changed"); } } } }); return result; } protected void performRefactoring(UsageInfo[] usages) { final PsiClassType superType = getSuperType(myClass); LOG.assertTrue(superType != null); List<PsiElement> elementsToDelete = new ArrayList<PsiElement>(); List<PsiNewExpression> newExpressions = new ArrayList<PsiNewExpression>(); for(UsageInfo info: usages) { final PsiElement element = info.getElement(); if (element instanceof PsiNewExpression) { newExpressions.add((PsiNewExpression)element); } else if (element.getParent() instanceof PsiNewExpression) { newExpressions.add((PsiNewExpression) element.getParent()); } else { PsiImportStatement statement = PsiTreeUtil.getParentOfType(element, PsiImportStatement.class); if (statement != null && !myInlineThisOnly) { elementsToDelete.add(statement); } else { PsiTypeElement typeElement = PsiTreeUtil.getParentOfType(element, PsiTypeElement.class); if (typeElement != null) { replaceWithSuperType(typeElement, superType); } } } } Collections.sort(newExpressions, PsiUtil.BY_POSITION); for(PsiNewExpression newExpression: newExpressions) { replaceNewOrType(newExpression, superType); } for(PsiElement element: elementsToDelete) { try { if (element.isValid()) { element.delete(); } } catch (IncorrectOperationException e) { LOG.error(e); } } if (!myInlineThisOnly) { try { myClass.delete(); } catch(IncorrectOperationException e) { LOG.error(e); } } } private void replaceNewOrType(final PsiNewExpression psiNewExpression, final PsiClassType superType) { try { if (psiNewExpression.getArrayDimensions().length == 0 && psiNewExpression.getArrayInitializer() == null) { new InlineToAnonymousConstructorProcessor(myClass, psiNewExpression, superType).run(); } else { PsiJavaCodeReferenceElement element = JavaPsiFacade.getInstance(myClass.getProject()).getElementFactory().createClassReferenceElement(superType.resolve()); psiNewExpression.getClassReference().replace(element); } } catch (IncorrectOperationException e) { LOG.error(e); } } private void replaceWithSuperType(final PsiTypeElement typeElement, final PsiClassType superType) { PsiElementFactory factory = JavaPsiFacade.getInstance(myClass.getProject()).getElementFactory(); PsiClassType psiType = (PsiClassType) typeElement.getType(); PsiClassType.ClassResolveResult classResolveResult = psiType.resolveGenerics(); PsiType substType = classResolveResult.getSubstitutor().substitute(superType); assert classResolveResult.getElement() == myClass; try { typeElement.replace(factory.createTypeElement(substType)); } catch(IncorrectOperationException e) { LOG.error(e); } } @Nullable public static PsiClassType getSuperType(final PsiClass aClass) { PsiElementFactory factory = JavaPsiFacade.getInstance(aClass.getProject()).getElementFactory(); PsiClassType superType; PsiClass superClass = aClass.getSuperClass(); PsiClassType[] interfaceTypes = aClass.getImplementsListTypes(); if (interfaceTypes.length > 0 && !InlineToAnonymousClassHandler.isRedundantImplements(superClass, interfaceTypes [0])) { superType = interfaceTypes [0]; } else { PsiClassType[] classTypes = aClass.getExtendsListTypes(); if (classTypes.length > 0) { superType = classTypes [0]; } else { if (superClass == null) { //java.lang.Object was not found return null; } superType = factory.createType(superClass); } } return superType; } protected String getCommandName() { return RefactoringBundle.message("inline.to.anonymous.command.name", myClass.getQualifiedName()); } }
joewalnes/idea-community
java/java-impl/src/com/intellij/refactoring/inline/InlineToAnonymousClassProcessor.java
Java
apache-2.0
12,552
package com.bupt.poirot.pattern.singletonPattern; /** * Created by hui.chen on 11/25/16. */ public class MakeACaptain { private MakeACaptain() { } // can't use new directly // Bill Pugh's Solution private static class SingletonHelper { // Nested class is referenced after getCaptain() is called private static final MakeACaptain _captain = new MakeACaptain(); } public static MakeACaptain getSingleton() { return SingletonHelper._captain; } }
CPoirot3/JavaProgress
src/main/java/com/bupt/poirot/pattern/singletonPattern/MakeACaptain.java
Java
apache-2.0
496
/* Copyright (c) 2020 W.T.J. Riezebos * * 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 net.riezebos.thoth.commands; import static org.junit.Assert.assertEquals; import java.io.IOException; import java.io.UnsupportedEncodingException; import java.util.HashMap; import java.util.Map; import org.junit.Test; import net.riezebos.thoth.commands.util.CommandTest; import net.riezebos.thoth.configuration.ThothEnvironment; import net.riezebos.thoth.context.ContextDefinition; import net.riezebos.thoth.context.ContextManager; import net.riezebos.thoth.context.RepositoryDefinition; import net.riezebos.thoth.context.RepositoryType; import net.riezebos.thoth.exceptions.ContentManagerException; import net.riezebos.thoth.exceptions.ContextNotFoundException; import net.riezebos.thoth.exceptions.RenderException; import net.riezebos.thoth.exceptions.SkinManagerException; import net.riezebos.thoth.renderers.RenderResult; public class ManageContextsCommandTest extends CommandTest { @Test public void test() throws ContextNotFoundException, SkinManagerException, RenderException, UnsupportedEncodingException, ContentManagerException, IOException { ThothEnvironment thothEnvironment = setupContentManager(); ContextManager contextManager = thothEnvironment.getContextManager(); ManageContextsCommand manageContextsCommand = new ManageContextsCommand(thothEnvironment, this); Map<String, String> args = new HashMap<String, String>(); RenderResult renderResult = testCommand(manageContextsCommand, "/", CommandOperation.GET, "managecontexts", null, null, args); assertEquals(RenderResult.OK, renderResult); String[] jsonExists = new String[] {""}; // CREATEREPOSITORY args = new HashMap<String, String>(); args.put(ManageContextsCommand.OPERATION_ARGUMENT, ManageContextsCommand.CREATEREPOSITORY); args.put(ManageContextsCommand.ARG_NAME, "testrepos"); args.put(ManageContextsCommand.ARG_TYPE, "nop"); args.put(ManageContextsCommand.ARG_LOCATION, "somelocation"); args.put(ManageContextsCommand.ARG_USERNAME, "username"); args.put(ManageContextsCommand.ARG_PASSWORD, "password"); renderResult = testCommand(manageContextsCommand, "/", CommandOperation.POST, "managecontexts", null, jsonExists, args); RepositoryDefinition repositoryDefinition = contextManager.getRepositoryDefinition("testrepos"); assertEquals("somelocation", repositoryDefinition.getLocation()); assertEquals(RepositoryType.NOP, repositoryDefinition.getType()); assertEquals("username", repositoryDefinition.getUsername()); assertEquals("password", repositoryDefinition.getPassword()); // UPDATEEPOSITORY args = new HashMap<String, String>(); args.put(ManageContextsCommand.OPERATION_ARGUMENT, ManageContextsCommand.UPDATEEPOSITORY); args.put(ManageContextsCommand.ARG_NAME, "testrepos"); args.put(ManageContextsCommand.ARG_NEWNAME, "testreposnew"); args.put(ManageContextsCommand.ARG_TYPE, "git"); args.put(ManageContextsCommand.ARG_LOCATION, "somelocationnew"); args.put(ManageContextsCommand.ARG_USERNAME, "usernamenew"); args.put(ManageContextsCommand.ARG_PASSWORD, "passwordnew"); renderResult = testCommand(manageContextsCommand, "/", CommandOperation.POST, "managecontexts", null, jsonExists, args); repositoryDefinition = contextManager.getRepositoryDefinition("testreposnew"); assertEquals("somelocationnew", repositoryDefinition.getLocation()); assertEquals(RepositoryType.GIT, repositoryDefinition.getType()); assertEquals("usernamenew", repositoryDefinition.getUsername()); assertEquals("passwordnew", repositoryDefinition.getPassword()); // CREATECONTEXT args = new HashMap<String, String>(); args.put(ManageContextsCommand.OPERATION_ARGUMENT, ManageContextsCommand.CREATECONTEXT); args.put(ManageContextsCommand.ARG_NAME, "testcontext"); args.put(ManageContextsCommand.ARG_REPOSITORYNAME, "testreposnew"); args.put(ManageContextsCommand.ARG_BRANCH, "branch"); args.put(ManageContextsCommand.ARG_LIBRARYROOT, "/"); args.put(ManageContextsCommand.ARG_REFRESHINTERVAL, "60"); renderResult = testCommand(manageContextsCommand, "/", CommandOperation.POST, "managecontexts", null, jsonExists, args); ContextDefinition contextDefinition = contextManager.getContextDefinition("testcontext"); assertEquals("branch", contextDefinition.getBranch()); assertEquals("/", contextDefinition.getLibraryRoot()); assertEquals(60L, contextDefinition.getRefreshInterval()); assertEquals("testreposnew", contextDefinition.getRepositoryName()); // UPDATECONTEXT args = new HashMap<String, String>(); args.put(ManageContextsCommand.OPERATION_ARGUMENT, ManageContextsCommand.UPDATECONTEXT); args.put(ManageContextsCommand.ARG_NAME, "testcontext"); args.put(ManageContextsCommand.ARG_REPOSITORYNAME, "testreposnew"); args.put(ManageContextsCommand.ARG_BRANCH, "branchnew"); args.put(ManageContextsCommand.ARG_LIBRARYROOT, "/new"); args.put(ManageContextsCommand.ARG_REFRESHINTERVAL, "90"); renderResult = testCommand(manageContextsCommand, "/", CommandOperation.POST, "managecontexts", null, jsonExists, args); contextDefinition = contextManager.getContextDefinition("testcontext"); assertEquals("branchnew", contextDefinition.getBranch()); assertEquals("/new", contextDefinition.getLibraryRoot()); assertEquals(90L, contextDefinition.getRefreshInterval()); assertEquals("testreposnew", contextDefinition.getRepositoryName()); // DELETECONTEXT Map<String, ContextDefinition> contextDefinitions = contextManager.getContextDefinitions(); assertEquals(true, contextDefinitions.containsKey("testcontext")); args = new HashMap<String, String>(); args.put(ManageContextsCommand.OPERATION_ARGUMENT, ManageContextsCommand.DELETECONTEXT); args.put(ManageContextsCommand.ARG_NAME, "testcontext"); renderResult = testCommand(manageContextsCommand, "/", CommandOperation.POST, "managecontexts", null, jsonExists, args); contextDefinitions = contextManager.getContextDefinitions(); assertEquals(false, contextDefinitions.containsKey("testcontext")); // DELETEEPOSITORY Map<String, RepositoryDefinition> repositoryDefinitions = contextManager.getRepositoryDefinitions(); assertEquals(true, repositoryDefinitions.containsKey("testreposnew")); args = new HashMap<String, String>(); args.put(ManageContextsCommand.OPERATION_ARGUMENT, ManageContextsCommand.DELETEREPOSITORY); args.put(ManageContextsCommand.ARG_NAME, "testreposnew"); renderResult = testCommand(manageContextsCommand, "/", CommandOperation.POST, "managecontexts", null, jsonExists, args); repositoryDefinitions = contextManager.getRepositoryDefinitions(); assertEquals(false, repositoryDefinitions.containsKey("testreposnew")); } }
widoriezebos/Thoth
thoth-modules/thoth-core/src/test/java/net/riezebos/thoth/commands/ManageContextsCommandTest.java
Java
apache-2.0
7,412
package com.ctrip.xpipe.redis.proxy.monitor.session; import com.ctrip.xpipe.redis.core.monitor.BaseInstantaneousMetric; import com.ctrip.xpipe.redis.proxy.monitor.stats.AbstractStats; import com.ctrip.xpipe.utils.DateTimeUtils; import com.google.common.collect.Lists; import java.util.Arrays; import java.util.List; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicLong; /** * @author chen.zhu * <p> * Oct 29, 2018 */ public class DefaultSessionStats extends AbstractStats implements SessionStats { private AtomicLong inputBytes = new AtomicLong(0L); private AtomicLong outputBytes = new AtomicLong(0L); private BaseInstantaneousMetric inputMetric = new BaseInstantaneousMetric(); private BaseInstantaneousMetric outputMetric = new BaseInstantaneousMetric(); private volatile long lastUpdateTime = System.currentTimeMillis(); private AtomicBoolean flag = new AtomicBoolean(false); private List<AutoReadEvent> autoReadEvents = Lists.newLinkedList(); public DefaultSessionStats(ScheduledExecutorService scheduled) { super(scheduled); } @Override public void increaseInputBytes(long bytes) { updateLastTime(); inputBytes.getAndAdd(bytes); } @Override public void increaseOutputBytes(long bytes) { updateLastTime(); outputBytes.getAndAdd(bytes); } @Override public long lastUpdateTime() { return lastUpdateTime; } private void updateLastTime() { lastUpdateTime = System.currentTimeMillis(); } @Override public long getInputBytes() { return inputBytes.get(); } @Override public long getOutputBytes() { return outputBytes.get(); } @Override public long getInputInstantaneousBPS() { return inputMetric.getInstantaneousMetric(); } @Override public long getOutputInstantaneousBPS() { return outputMetric.getInstantaneousMetric(); } @Override public List<AutoReadEvent> getAutoReadEvents() { return autoReadEvents; } @Override protected void doStart() { updateLastTime(); super.doStart(); } @Override protected void doTask() { inputMetric.trackInstantaneousMetric(inputBytes.get()); outputMetric.trackInstantaneousMetric(outputBytes.get()); } @Override protected int getCheckIntervalMilli() { return 100; } @Override public void onInit() { } @Override public void onEstablished() { } @Override public void onWritable() { if(flag.compareAndSet(true, false)) { autoReadEvents.get(autoReadEvents.size() - 1).setEndTime(System.currentTimeMillis()); } } @Override public void onNotWritable() { if(flag.compareAndSet(false, true)) { autoReadEvents.add(new AutoReadEvent().setStartTime(System.currentTimeMillis())); } } @Override public String toString() { return "DefaultSessionStats{" + "inputBytes=" + inputBytes.get() + ", outputBytes=" + outputBytes.get() + ", inputMetric=" + inputMetric.getInstantaneousMetric() + ", outputMetric=" + outputMetric.getInstantaneousMetric() + ", lastUpdateTime=" + DateTimeUtils.timeAsString(lastUpdateTime) + ", autoReadEvents=" + Arrays.deepToString(autoReadEvents.toArray(new AutoReadEvent[0])) + '}'; } }
ctripcorp/x-pipe
redis/redis-proxy/src/main/java/com/ctrip/xpipe/redis/proxy/monitor/session/DefaultSessionStats.java
Java
apache-2.0
3,608
package com.mt.search.controller; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Configuration; import org.springframework.web.servlet.config.annotation.InterceptorRegistry; import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter; /** * Created by robertmurray on 9/27/17. */ @Configuration public class InterceptorConfig extends WebMvcConfigurerAdapter { @Autowired private SecurityInterceptor securityInterceptor; @Autowired private CrossSiteScriptingInterceptor crossSiteScriptingInterceptor; @Autowired private CORSInterceptor corsInterceptor; @Override public void addInterceptors(InterceptorRegistry registry) { registry.addInterceptor(securityInterceptor); registry.addInterceptor(corsInterceptor); registry.addInterceptor(crossSiteScriptingInterceptor); } }
robmurray/mtsearch
src/main/java/com/mt/search/controller/InterceptorConfig.java
Java
apache-2.0
920
package ru.job4j.bomberv2.models.factories; import ru.job4j.bomberv2.controllers.GameController; import ru.job4j.bomberv2.models.entities.Monster; import ru.job4j.bomberv2.models.playground.Field; /** * The class MonsterThreadFactory describes the thread of the monster. * * @author Alex Proshak ([email protected]) */ public class MonsterThreadFactory { /** * The static factory method of generating monster thread. * @param controller of the game. * @param field of thr game. * @return a thread for the monster. */ public static Thread getMonsterThread(final GameController controller, final Field field) { Thread monsterThread = new Thread(Monster.getMonster(controller, field)); monsterThread.setName("Monster"); monsterThread.setDaemon(true); return monsterThread; } }
OleksandrProshak/Alexandr_Proshak
Level_Junior/Part_002_Multithreading/7_Control_Tasks_Multithreading/src/main/java/ru/job4j/bomberv2/models/factories/MonsterThreadFactory.java
Java
apache-2.0
857
package org.ovirt.engine.api.restapi.resource.aaa; import static org.easymock.EasyMock.expect; import javax.ws.rs.WebApplicationException; import javax.ws.rs.core.UriInfo; import org.junit.Test; import org.ovirt.engine.api.model.Domain; import org.ovirt.engine.api.model.User; import org.ovirt.engine.api.restapi.resource.AbstractBackendSubResourceTest; import org.ovirt.engine.api.restapi.utils.DirectoryEntryIdUtils; import org.ovirt.engine.core.aaa.DirectoryUser; import org.ovirt.engine.core.common.queries.DirectoryIdQueryParameters; import org.ovirt.engine.core.common.queries.VdcQueryType; public class BackendDomainUserResourceTest extends AbstractBackendSubResourceTest<User, DirectoryUser, BackendDomainUserResource> { public BackendDomainUserResourceTest() { super(new BackendDomainUserResource(EXTERNAL_IDS[1], null)); } @Override protected void init () { super.init(); setUpParentExpectations(); } @Test public void testGet() throws Exception { UriInfo uriInfo = setUpBasicUriExpectations(); setUriInfo(uriInfo); setUpEntityQueryExpectations(1, false); control.replay(); verifyModel(resource.get(), 1); } @Override protected void verifyModel(User model, int index) { assertEquals(NAMES[index] + "@" + DOMAIN, model.getUserName()); } @Test public void testGetNotFound() throws Exception { UriInfo uriInfo = setUpBasicUriExpectations(); setUriInfo(uriInfo); setUpEntityQueryExpectations(1, true); control.replay(); try { resource.get(); fail("expected WebApplicationException"); } catch (WebApplicationException wae) { verifyNotFoundException(wae); } } private void setUpParentExpectations() { BackendDomainUsersResource parent = control.createMock(BackendDomainUsersResource.class); Domain domain = new Domain(); domain.setName(DOMAIN); expect(parent.getDirectory()).andReturn(domain).anyTimes(); resource.setParent(parent); } private void setUpEntityQueryExpectations(int index, boolean notFound) throws Exception { setUpGetEntityExpectations( VdcQueryType.GetDirectoryUserById, DirectoryIdQueryParameters.class, new String[] { "Domain", "Id" }, new Object[] { DOMAIN, DirectoryEntryIdUtils.decode(EXTERNAL_IDS[index]) }, notFound? null: getEntity(index) ); } @Override protected DirectoryUser getEntity(int index) { return new DirectoryUser(DOMAIN, NAMESPACE, DirectoryEntryIdUtils.decode(EXTERNAL_IDS[index]), NAMES[index], NAMES[index], ""); } }
OpenUniversity/ovirt-engine
backend/manager/modules/restapi/jaxrs/src/test/java/org/ovirt/engine/api/restapi/resource/aaa/BackendDomainUserResourceTest.java
Java
apache-2.0
2,801
/** * Copyright (c) 2007-2014 Kaazing Corporation. All rights reserved. * * 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.kaazing.gateway.client.impl.bridge; import org.kaazing.gateway.client.impl.bridge.XoaEvent.XoaEventKind; import org.kaazing.gateway.client.util.StringUtils; import java.beans.PropertyChangeSupport; import java.net.URI; import java.net.URL; import java.security.SecureRandom; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.atomic.AtomicInteger; import java.util.logging.Level; import java.util.logging.Logger; public class BridgeUtil { private static final String CLASS_NAME = BridgeUtil.class.getName(); private static final Logger LOG = Logger.getLogger(CLASS_NAME); private static final String SOA_MESSAGE = "soaMessage"; private static final String XOP_MESSAGE = "xopMessage"; private static Map<String, PropertyChangeSupport> schemeAuthorityToXopMap = new ConcurrentHashMap<>(); private static Map<Integer, Proxy> handlerIdToHtml5ObjectMap = new ConcurrentHashMap<>(); private static AtomicInteger sHtml5ObjectIdCounter = new AtomicInteger(new SecureRandom().nextInt(10000)); // package private static used for authenticating self for same origin code static Object token = null; public static Object getIdentifier() { LOG.exiting(CLASS_NAME, "getIdentifier", token); return token; } static void processEvent(XoaEvent event) { LOG.entering(CLASS_NAME, "dispatchEventToXoa", event); LOG.log(Level.FINEST, "SOA --> XOA: {1}", event); Integer handlerId = event.getHandlerId(); if (handlerId == null) { if (LOG.isLoggable(Level.FINE)) { LOG.fine("Null handlerId"); } return; } String eventType = event.getKind().toString(); Object[] params = event.getParams(); Object[] args = { handlerId, eventType, params }; PropertyChangeSupport xop = getCrossOriginProxy(handlerId); if (xop == null) { if (LOG.isLoggable(Level.FINE)) { LOG.fine("Null xop for handler " + handlerId); } return; } xop.firePropertyChange(SOA_MESSAGE, null, args); } public static void eventReceived(final Integer handlerId, final String eventType, final Object[] params) { LOG.entering(CLASS_NAME, "eventReceived", new Object[] { handlerId, eventType, params }); final Proxy obj = handlerIdToHtml5ObjectMap.get(handlerId); if (obj == null) { LOG.fine("Object by id: " + handlerId + " could not be located in the system"); return; } try { XoaEventKind name = XoaEventKind.getName(eventType); obj.eventReceived(handlerId, name, params); } finally { if (eventType.equals(XoaEvent.XoaEventKind.CLOSED) || eventType.equals(XoaEvent.XoaEventKind.ERROR)) { handlerIdToHtml5ObjectMap.remove(handlerId); } } } private static String getSchemeAuthority(URI uri) { return uri.getScheme() + "_" + uri.getAuthority(); } private static PropertyChangeSupport getCrossOriginProxy(Integer handlerId) { Proxy proxy = handlerIdToHtml5ObjectMap.get(handlerId); return getCrossOriginProxy(proxy); } private static PropertyChangeSupport getCrossOriginProxy(Proxy proxy) { return getCrossOriginProxy(proxy.getUri()); } private static PropertyChangeSupport getCrossOriginProxy(URI uri) { String schemeAuthority = getSchemeAuthority(uri); return getCrossOriginProxy(schemeAuthority); } private static PropertyChangeSupport getCrossOriginProxy(String schemeAuthority) { return schemeAuthorityToXopMap.get(schemeAuthority); } private static void initCrossOriginProxy(URI uri) throws Exception { LOG.entering(CLASS_NAME, "initCrossOriginProxy", new Object[] { uri }); PropertyChangeSupport xop = getCrossOriginProxy(uri); if (xop == null) { try { String scheme = uri.getScheme(); String jarUrl = scheme + "://" + uri.getAuthority(); if (scheme.equals("ws")) { jarUrl = jarUrl.replace("ws:", "http:"); } else if (scheme.equals("wss")) { jarUrl = jarUrl.replace("wss:", "https:"); } ClassLoaderFactory classLoaderFactory = ClassLoaderFactory.getInstance(); jarUrl += classLoaderFactory.getQueryParameters(); final String jarFileUrl = jarUrl; LOG.finest("jarFileUrl = " + StringUtils.stripControlCharacters(jarFileUrl)); ClassLoader loader = classLoaderFactory.createClassLoader(new URL(jarFileUrl), BridgeUtil.class.getClassLoader()); LOG.finest("Created remote proxy class loader: " + loader); Class<?> remoteProxyClass = loader.loadClass(classLoaderFactory.getCrossOriginProxyClass()); xop = (PropertyChangeSupport) remoteProxyClass.newInstance(); xop.addPropertyChangeListener(XOP_MESSAGE, evt -> { Object[] args = (Object[]) evt.getNewValue(); Integer proxyId = (Integer) args[0]; String eventType = (String) args[1]; Object[] params = (Object[]) args[2]; eventReceived(proxyId, eventType, params); }); schemeAuthorityToXopMap.put(getSchemeAuthority(uri), xop); } catch (Exception e) { String reason = "Unable to connect: the Gateway may not be running, a network route may be unavailable, or the Gateway may not be configured properly"; LOG.log(Level.WARNING, reason); LOG.log(Level.FINEST, reason, e); throw new Exception(reason); } } LOG.exiting(CLASS_NAME, "initCrossOriginProxy", xop); } static Proxy createProxy(URI uri, ProxyListener listener) throws Exception { LOG.entering(CLASS_NAME, "registerProxy", new Object[] { }); BridgeUtil.initCrossOriginProxy(uri); Integer handlerId = sHtml5ObjectIdCounter.getAndIncrement(); Proxy proxy = new Proxy(); proxy.setHandlerId(handlerId); proxy.setUri(uri); proxy.setListener(listener); handlerIdToHtml5ObjectMap.put(handlerId, proxy); return proxy; } }
spark/spark-sdk-android
cloudsdk/src/main/java/org/kaazing/gateway/client/impl/bridge/BridgeUtil.java
Java
apache-2.0
7,484
package com.jfixby.r3.fokker.unit.input; import java.util.ArrayList; import com.jfixby.r3.api.input.InputEvent; import com.jfixby.r3.api.ui.unit.input.CharTypedEvent; import com.jfixby.r3.api.ui.unit.input.KeyDownEvent; import com.jfixby.r3.api.ui.unit.input.KeyUpEvent; import com.jfixby.r3.api.ui.unit.input.MouseExitEvent; import com.jfixby.r3.api.ui.unit.input.MouseMovedEvent; import com.jfixby.r3.api.ui.unit.input.MouseScrolledEvent; import com.jfixby.r3.api.ui.unit.input.TouchDownEvent; import com.jfixby.r3.api.ui.unit.input.TouchDraggedEvent; import com.jfixby.r3.api.ui.unit.input.TouchUpEvent; import com.jfixby.r3.api.ui.unit.user.KeyboardInputEventListener; import com.jfixby.r3.api.ui.unit.user.MouseInputEventListener; import com.jfixby.r3.fokker.unit.cam.RedCamera; import com.jfixby.scarabei.api.collections.Collections; import com.jfixby.scarabei.api.err.Err; import com.jfixby.scarabei.api.floatn.Float2; import com.jfixby.scarabei.api.floatn.ReadOnlyFloat2; import com.jfixby.scarabei.api.geometry.Geometry; import com.jfixby.scarabei.api.input.Key; import com.jfixby.scarabei.api.input.MouseButton; public class UnitInputEventsDeliveryBox implements MouseMovedEvent, TouchDraggedEvent, TouchUpEvent, TouchDownEvent, MouseScrolledEvent, MouseExitEvent, CharTypedEvent, KeyUpEvent, KeyDownEvent { final PressedKeys pressed = new PressedKeys(); @Override public String toString () { if (this.is_key_down_event) { return "KeyDownEvent [" + this.key + "]"; } if (this.is_key_typed_event) { return "CharTypedEvent [" + this.char_typed + "]"; } if (this.is_key_up_event) { return "KeyUpEvent [" + this.key + "]"; } if (!this.is_within_aperture) { return "MouseExitEvent [" + this.canvas_point + "]"; } if (this.is_mouse_down) { return "TouchDownEvent [" + this.canvas_point + "]"; } if (this.is_mouse_up) { return "TouchUpEvent [" + this.canvas_point + "]"; } if (this.is_mouse_moved) { return "MouseMovedEvent [" + this.canvas_point + "]"; } if (this.is_mouse_dragged) { return "TouchDraggedEvent [" + this.canvas_point + "]"; } if (this.is_mouse_scrolled) { return "MouseScrolledEvent [" + this.scrolled + "]"; } Err.reportError("Unknown event: " + this.toStringOriginal()); return null; } final ArrayList<RedCamera> cameras_stack = new ArrayList<RedCamera>(); private InputEvent current_input_event; boolean keyboard_event = false; boolean is_key_typed_event = false; boolean is_key_down_event = false; boolean is_key_up_event = false; boolean is_mouse_scrolled = false; boolean mouse_event = false; boolean is_mouse_moved = false; boolean is_mouse_dragged = false; boolean is_mouse_down = false; boolean is_mouse_up = false; Key key; char char_typed; private double screen_x; private double screen_y; final Float2 canvas_point = Geometry.newFloat2(); boolean is_within_aperture = false; private int pointer_number; private MouseButton mouse_button; private int scrolled; public void put (final InputEvent input_event) { this.current_input_event = input_event; this.mouse_event = input_event.isMouseEvent(); this.screen_x = input_event.getScreenX(); this.screen_y = input_event.getScreenY(); this.is_mouse_moved = input_event.isMouseMovedEvent(); this.is_mouse_dragged = input_event.isMouseDraggedEvent(); this.is_mouse_down = input_event.isMouseDownEvent(); this.is_mouse_up = input_event.isMouseUpEvent(); this.is_mouse_scrolled = input_event.isMouseScrolled(); this.pointer_number = input_event.getPointerNumber(); this.mouse_button = input_event.getMouseButton(); this.scrolled = input_event.getScrollAmount(); this.keyboard_event = input_event.isKeyboardEvent(); this.is_key_typed_event = input_event.isKeyTypedEvent(); this.is_key_down_event = input_event.isKeyDownEvent(); this.is_key_up_event = input_event.isKeyUpEvent(); this.key = input_event.getKey(); this.char_typed = input_event.getCharTyped(); if (this.is_key_down_event) { this.pressed.press(this.key); } if (this.is_key_up_event) { this.pressed.release(this.key); } } public boolean containsKeyboardInputEvent () { return this.keyboard_event; } public boolean containsMouseInputEvent () { return this.mouse_event; } public boolean tryToDeliverTo (final KeyboardInputEventListener keyboard_listener) { if (this.is_key_down_event) { return keyboard_listener.onKeyDown(this); } if (this.is_key_up_event) { return keyboard_listener.onKeyUp(this); } if (this.is_key_typed_event) { return keyboard_listener.onCharTyped(this); } Err.reportError("Unknown event: " + this.current_input_event); return this.is_key_down_event; } public boolean tryToDeliverTo (final MouseInputEventListener mouse_listener) { if (!this.is_within_aperture) { mouse_listener.onMouseExit(this); return false; } if (this.is_mouse_moved) { return mouse_listener.onMouseMoved(this); } if (this.is_mouse_down) { return mouse_listener.onTouchDown(this); } if (this.is_mouse_up) { return mouse_listener.onTouchUp(this); } if (this.is_mouse_dragged) { return mouse_listener.onTouchDragged(this); } if (this.is_mouse_scrolled) { return mouse_listener.onMouseScrolled(this); } Err.reportError("Unknown event: " + this.current_input_event); return this.is_key_down_event; } public void stackInCamera (final RedCamera camera) { if (camera != null) { // L.d("stackInCamera", camera); this.cameras_stack.add(camera); camera.setStack(this.cameras_stack); this.canvas_point.setXY(this.screen_x, this.screen_y); this.is_within_aperture = camera.isWithinAperture(this.canvas_point); { camera.unProject(this.canvas_point); } } } public void stackOutCamera (final RedCamera camera) { if (camera != null) { if (this.cameras_stack.get(this.cameras_stack.size() - 1) == camera) { this.cameras_stack.remove(this.cameras_stack.size() - 1); camera.removeStack(); this.canvas_point.setXY(this.screen_x, this.screen_y); this.is_within_aperture = camera.isWithinAperture(this.canvas_point); { camera.unProject(this.canvas_point); } } else { Collections.newList(this.cameras_stack).print("cameras stack"); Err.reportError("Cameras stack is corrupted."); } } } public void checkStack () { if (!this.cameras_stack.isEmpty()) { Collections.newList(this.cameras_stack).print("cameras stack"); Err.reportError("Cameras stack is corrupted."); } } @Override public ReadOnlyFloat2 getCanvasPosition () { return this.canvas_point; } public String toStringOriginal () { return "UnitInputEventsDeliveryBox [cameras_stack=" + this.cameras_stack + ", current_input_event=" + this.current_input_event + ", keyboard_event=" + this.keyboard_event + ", is_key_typed_event=" + this.is_key_typed_event + ", is_key_down_event=" + this.is_key_down_event + ", is_key_up_event=" + this.is_key_up_event + ", is_mouse_scrolled=" + this.is_mouse_scrolled + ", mouse_event=" + this.mouse_event + ", is_mouse_moved=" + this.is_mouse_moved + ", is_mouse_dragged=" + this.is_mouse_dragged + ", is_mouse_down=" + this.is_mouse_down + ", is_mouse_up=" + this.is_mouse_up + ", key=" + this.key + ", char_typed=" + this.char_typed + ", screen_x=" + this.screen_x + ", screen_y=" + this.screen_y + ", canvas_point=" + this.canvas_point + ", pointer_number=" + this.pointer_number + ", mouse_button=" + this.mouse_button + ", scrolled=" + this.scrolled + "]"; } @Override public int getPointerNumber () { return this.pointer_number; } @Override public int getScrollValue () { return this.scrolled; } @Override public char getChar () { return this.char_typed; } @Override public Key getKey () { return this.key; } @Override public boolean isKeyPressed (final Key otherKey) { return this.pressed.isKeyPressed(otherKey); } public void markAllAllKeysReleased () { this.pressed.releaseAllKeys(); } @Override public boolean is (final Key other) { return this.getKey() == other; } }
JFixby/RedTriplane
fokker-core/src/com/jfixby/r3/fokker/unit/input/UnitInputEventsDeliveryBox.java
Java
apache-2.0
8,108
package com.dl7.downloaderlib.helper; import com.dl7.downloaderlib.DownloadListener; import com.dl7.downloaderlib.entity.FileInfo; import com.dl7.downloaderlib.model.DownloadStatus; import com.dl7.downloaderlib.service.DownloadThreadPool; /** * Created by long on 2016/5/26. * 封装下载监听器 */ public final class ListenerDecorator implements DownloadListener { private final DownloadListener mListener; private final boolean mIsUiThread; public ListenerDecorator(DownloadListener listener, boolean isUiThread) { this.mListener = listener; this.mIsUiThread = isUiThread; } @Override public void onStart(final FileInfo fileInfo) { fileInfo.setStatus(DownloadStatus.START); if (mIsUiThread) { MainHandler.runInMainThread(new Runnable() { @Override public void run() { mListener.onStart(fileInfo); } }); } else { mListener.onStart(fileInfo); } } @Override public void onUpdate(final FileInfo fileInfo) { fileInfo.setStatus(DownloadStatus.DOWNLOADING); if (mIsUiThread) { MainHandler.runInMainThread(new Runnable() { @Override public void run() { mListener.onUpdate(fileInfo); } }); } else { mListener.onUpdate(fileInfo); } } @Override public void onStop(final FileInfo fileInfo) { fileInfo.setStatus(DownloadStatus.STOP); if (mIsUiThread) { MainHandler.runInMainThread(new Runnable() { @Override public void run() { mListener.onStop(fileInfo); } }); } else { mListener.onStop(fileInfo); } } @Override public void onComplete(final FileInfo fileInfo) { fileInfo.setStatus(DownloadStatus.COMPLETE); if (mIsUiThread) { MainHandler.runInMainThread(new Runnable() { @Override public void run() { mListener.onComplete(fileInfo); } }); } else { mListener.onComplete(fileInfo); } DownloadThreadPool.getInstance().cancel(fileInfo.getUrl(), false); } @Override public void onCancel(final FileInfo fileInfo) { fileInfo.setStatus(DownloadStatus.CANCEL); if (mIsUiThread) { MainHandler.runInMainThread(new Runnable() { @Override public void run() { mListener.onCancel(fileInfo); } }); } else { mListener.onCancel(fileInfo); } DownloadThreadPool.getInstance().cancel(fileInfo.getUrl(), true); } @Override public void onError(final FileInfo fileInfo, final String errorMsg) { fileInfo.setStatus(DownloadStatus.ERROR); if (mIsUiThread) { MainHandler.runInMainThread(new Runnable() { @Override public void run() { mListener.onError(fileInfo, errorMsg); } }); } else { mListener.onError(fileInfo, errorMsg); } DownloadThreadPool.getInstance().cancel(fileInfo.getUrl(), false); } }
weiwenqiang/GitHub
MVP/MvpApp-master/downloaderLib/src/main/java/com/dl7/downloaderlib/helper/ListenerDecorator.java
Java
apache-2.0
3,424
/* * Copyright 2009-2016 University of Hildesheim, Software Systems Engineering * * 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 eu.qualimaster.monitoring.tracing; import java.io.Serializable; import java.util.Map; import eu.qualimaster.coordination.events.AlgorithmProfilingEvent.DetailMode; import eu.qualimaster.monitoring.systemState.NodeImplementationSystemPart; import eu.qualimaster.monitoring.systemState.PipelineNodeSystemPart; import eu.qualimaster.monitoring.systemState.SystemState; /** * Delegates tracing to multiple individual traces. * * @author Holger Eichelberger */ public class DelegatingTrace implements ITrace { private ITrace[] traces; /** * Creates a delegating trace. * * @param traces the traces to delegate to */ public DelegatingTrace(ITrace... traces) { this.traces = traces; } @Override public boolean isInitialized() { boolean initialized = true; for (ITrace t: traces) { initialized &= t.isInitialized(); } return initialized; } @Override public void close() { for (ITrace t: traces) { t.close(); } } @Override public void traceAlgorithm(PipelineNodeSystemPart node, NodeImplementationSystemPart alg, IParameterProvider parameters) { for (ITrace t: traces) { t.traceAlgorithm(node, alg, parameters); } } @Override public void traceInfrastructure(SystemState state, IParameterProvider parameters) { for (ITrace t: traces) { t.traceInfrastructure(state, parameters); } } @Override public void notifyNewSubTrace(Map<String, Serializable> settings) { for (ITrace t: traces) { t.notifyNewSubTrace(settings); } } @Override public void setTraceMode(DetailMode mode) { for (ITrace t: traces) { t.setTraceMode(mode); } } }
QualiMaster/Infrastructure
MonitoringLayer/src/eu/qualimaster/monitoring/tracing/DelegatingTrace.java
Java
apache-2.0
2,590
/* * Copyright 2011 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 org.grails.core.support.internal.tools; import groovy.lang.MetaClass; import groovy.lang.MetaClassRegistryChangeEvent; import groovy.lang.MetaClassRegistryChangeEventListener; /** * Simple class that reports when meta class changes and where (in what stack frame) those changes took place * * @author Graeme Rocher * @since 2.0 */ public class MetaClassChangeReporter implements MetaClassRegistryChangeEventListener{ /** * Called when the a constant MetaClass is updated. If the new MetaClass is null, then the MetaClass * is removed. Be careful, while this method is executed other updates may happen. If you want this * method thread safe, you have to take care of that by yourself. * * @param cmcu - the change event */ public void updateConstantMetaClass(MetaClassRegistryChangeEvent cmcu) { Class<?> classToUpdate = cmcu.getClassToUpdate(); MetaClass newMetaClass = cmcu.getNewMetaClass(); System.out.println("Class ["+classToUpdate+"] updated MetaClass to ["+newMetaClass+"]"); Thread.dumpStack(); } }
clockworkorange/grails-core
grails-core/src/main/groovy/org/grails/core/support/internal/tools/MetaClassChangeReporter.java
Java
apache-2.0
1,714
package com.extraslice.walknpay.ui; import com.extraslice.walknpay.R; import com.extraslice.walknpay.bl.Utilities; import android.app.Dialog; import android.app.Fragment; import android.content.Intent; import android.os.Bundle; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.view.Window; import android.view.View.OnClickListener; import android.widget.Button; import android.widget.TextView; public class LogoutFragment extends Fragment { public LogoutFragment(){} @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View rootView = inflater.inflate(R.layout.logout, container, false); final Dialog dialog = new Dialog(getActivity()); dialog.requestWindowFeature(Window.FEATURE_NO_TITLE); dialog.setContentView(R.layout.custom_alert); TextView text = (TextView) dialog.findViewById(R.id.alertTitle); text.setText(R.string.logoutalertmessage); Button dialogButton = (Button) dialog.findViewById(R.id.alertpositivebutton); // if button is clicked, close the custom dialog dialogButton.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { dialog.dismiss(); Intent n1=new Intent(getActivity(), LoginScreen.class); startActivity(n1); Utilities.rewards=0.00; Utilities.firstrun=false; Utilities.confirm_store=false; getActivity().finish(); } }); Button negativebutton = (Button) dialog.findViewById(R.id.alertnegativebutton); // if button is clicked, close the custom dialog negativebutton.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { Intent n1=new Intent(getActivity(), MenuActivity.class); startActivity(n1); dialog.dismiss(); } }); dialog.show(); return rootView; } }
athulyaor/extraslice_athulya
WalkNPay- sliding/src/com/extraslice/walknpay/ui/LogoutFragment.java
Java
apache-2.0
2,016
// Copyright 2000-2021 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package git4idea.ui.branch; import com.intellij.dvcs.DvcsUtil; import com.intellij.dvcs.push.ui.VcsPushDialog; import com.intellij.dvcs.ui.*; import com.intellij.icons.AllIcons; import com.intellij.ide.IdeBundle; import com.intellij.idea.ActionsBundle; import com.intellij.openapi.actionSystem.*; import com.intellij.openapi.fileEditor.FileDocumentManager; import com.intellij.openapi.project.DumbAwareAction; import com.intellij.openapi.project.Project; import com.intellij.openapi.ui.Messages; import com.intellij.openapi.util.NlsContexts; import com.intellij.openapi.util.NlsSafe; import com.intellij.openapi.util.Pair; import com.intellij.openapi.util.TextRange; import com.intellij.openapi.util.registry.Registry; import com.intellij.openapi.util.text.StringUtil; import com.intellij.openapi.vcs.IssueNavigationConfiguration; import com.intellij.util.containers.hash.LinkedHashMap; import com.intellij.util.ui.EmptyIcon; import git4idea.GitBranch; import git4idea.GitLocalBranch; import git4idea.GitProtectedBranchesKt; import git4idea.GitRemoteBranch; import git4idea.actions.GitOngoingOperationAction; import git4idea.branch.*; import git4idea.config.GitVcsSettings; import git4idea.config.UpdateMethod; import git4idea.fetch.GitFetchSupport; import git4idea.i18n.GitBundle; import git4idea.push.GitPushSource; import git4idea.rebase.GitRebaseSpec; import git4idea.repo.GitBranchTrackInfo; import git4idea.repo.GitRepository; import git4idea.repo.GitRepositoryManager; import git4idea.update.GitUpdateExecutionProcess; import icons.DvcsImplIcons; import org.jetbrains.annotations.Nls; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import javax.swing.*; import java.util.*; import java.util.function.Supplier; import static com.intellij.dvcs.DvcsUtil.disableActionIfAnyRepositoryIsFresh; import static com.intellij.dvcs.DvcsUtil.getShortHash; import static com.intellij.dvcs.ui.BranchActionGroupPopup.wrapWithMoreActionIfNeeded; import static com.intellij.dvcs.ui.BranchActionUtil.FAVORITE_BRANCH_COMPARATOR; import static com.intellij.dvcs.ui.BranchActionUtil.getNumOfTopShownBranches; import static com.intellij.util.ObjectUtils.notNull; import static com.intellij.util.containers.ContainerUtil.*; import static git4idea.GitReference.BRANCH_NAME_HASHING_STRATEGY; import static git4idea.GitUtil.HEAD; import static git4idea.branch.GitBranchType.LOCAL; import static git4idea.branch.GitBranchType.REMOTE; import static git4idea.ui.branch.GitBranchActionsUtilKt.*; import static java.util.Arrays.asList; import static one.util.streamex.StreamEx.of; public class GitBranchPopupActions { private final Project myProject; private final GitRepository myRepository; GitBranchPopupActions(Project project, GitRepository repository) { myProject = project; myRepository = repository; } ActionGroup createActions() { return createActions(null, null, false); } ActionGroup createActions(@Nullable LightActionGroup toInsert, @Nullable GitRepository specificRepository, boolean firstLevelGroup) { LightActionGroup popupGroup = new LightActionGroup(false); List<GitRepository> repositoryList = Collections.singletonList(myRepository); GitRebaseSpec rebaseSpec = GitRepositoryManager.getInstance(myProject).getOngoingRebaseSpec(); if (rebaseSpec != null && isSpecForRepo(rebaseSpec, myRepository)) { popupGroup.addAll(getRebaseActions()); } else { popupGroup.addAll(createPerRepoRebaseActions(myRepository)); } popupGroup.addAction(new GitNewBranchAction(myProject, repositoryList)); popupGroup.addAction(new CheckoutRevisionActions(myProject, repositoryList)); if (toInsert != null) { popupGroup.addAll(toInsert); } popupGroup.addSeparator(specificRepository == null ? GitBundle.message("branches.local.branches") : GitBundle.message("branches.local.branches.in.repo", DvcsUtil.getShortRepositoryName(specificRepository))); GitLocalBranch currentBranch = myRepository.getCurrentBranch(); GitBranchesCollection branchesCollection = myRepository.getBranches(); List<LocalBranchActions> localBranchActions = of(branchesCollection.getLocalBranches()) .filter(branch -> !branch.equals(currentBranch)) .map(branch -> new LocalBranchActions(myProject, repositoryList, branch.getName(), myRepository)) .sorted((b1, b2) -> { int delta = FAVORITE_BRANCH_COMPARATOR.compare(b1, b2); if (delta != 0) return delta; return StringUtil.naturalCompare(b1.myBranchName, b2.myBranchName); }) .toList(); int topShownBranches = getNumOfTopShownBranches(localBranchActions); if (currentBranch != null) { localBranchActions.add(0, new CurrentBranchActions(myProject, repositoryList, currentBranch.getName(), myRepository)); topShownBranches++; } // if there are only a few local favorites -> show all; for remotes it's better to show only favorites; wrapWithMoreActionIfNeeded(myProject, popupGroup, localBranchActions, topShownBranches, firstLevelGroup ? GitBranchPopup.SHOW_ALL_LOCALS_KEY : null, firstLevelGroup); popupGroup.addSeparator(specificRepository == null ? GitBundle.message("branches.remote.branches") : GitBundle.message("branches.remote.branches.in.repo", specificRepository)); List<RemoteBranchActions> remoteBranchActions = of(branchesCollection.getRemoteBranches()) .map(GitBranch::getName) .sorted(StringUtil::naturalCompare) .map(remoteName -> new RemoteBranchActions(myProject, repositoryList, remoteName, myRepository)) .toList(); wrapWithMoreActionIfNeeded(myProject, popupGroup, sorted(remoteBranchActions, FAVORITE_BRANCH_COMPARATOR), getNumOfTopShownBranches(remoteBranchActions), firstLevelGroup ? GitBranchPopup.SHOW_ALL_REMOTES_KEY : null); return popupGroup; } private static boolean isSpecForRepo(@NotNull GitRebaseSpec spec, @NotNull GitRepository repository) { Collection<GitRepository> repositoriesFromSpec = spec.getAllRepositories(); return repositoriesFromSpec.size() == 1 && repository.equals(getFirstItem(repositoriesFromSpec)); } @NotNull private static List<AnAction> createPerRepoRebaseActions(@NotNull GitRepository repository) { return mapNotNull(getRebaseActions(), action -> createRepositoryRebaseAction(action, repository)); } @NotNull static List<AnAction> getRebaseActions() { ActionGroup group = (ActionGroup)ActionManager.getInstance().getAction("Git.Ongoing.Rebase.Actions"); return asList(group.getChildren(null)); } @Nullable private static AnAction createRepositoryRebaseAction(@NotNull AnAction rebaseAction, @NotNull GitRepository repository) { if (!(rebaseAction instanceof GitOngoingOperationAction)) return null; GitOngoingOperationAction ongoingAction = (GitOngoingOperationAction)rebaseAction; DumbAwareAction repositoryAction = new DumbAwareAction() { @Override public void update(@NotNull AnActionEvent e) { e.getPresentation().setEnabledAndVisible(ongoingAction.isEnabled(repository)); } @Override public void actionPerformed(@NotNull AnActionEvent e) { ongoingAction.performInBackground(repository); } }; repositoryAction.getTemplatePresentation().copyFrom(rebaseAction.getTemplatePresentation()); return repositoryAction; } public static class GitNewBranchAction extends NewBranchAction<GitRepository> { public GitNewBranchAction(@NotNull Project project, @NotNull List<GitRepository> repositories) { super(project, repositories); } @Override public void actionPerformed(@NotNull AnActionEvent e) { createOrCheckoutNewBranch(myProject, myRepositories, HEAD); } } /** * Checkout manually entered tag or revision number. */ public static class CheckoutRevisionActions extends DumbAwareAction { private final Project myProject; private final List<GitRepository> myRepositories; CheckoutRevisionActions(Project project, List<GitRepository> repositories) { super(GitBundle.messagePointer("branches.checkout.tag.or.revision")); myProject = project; myRepositories = repositories; } @Override public void actionPerformed(@NotNull AnActionEvent e) { // TODO: on type check ref validity, on OK check ref existence. GitRefDialog dialog = new GitRefDialog(myProject, myRepositories, GitBundle.message("branches.checkout"), GitBundle.message("branches.enter.reference.branch.tag.name.or.commit.hash")); if (dialog.showAndGet()) { String reference = dialog.getReference(); GitBrancher brancher = GitBrancher.getInstance(myProject); brancher.checkout(reference, true, myRepositories, null); } } @Override public void update(@NotNull AnActionEvent e) { disableActionIfAnyRepositoryIsFresh(e, myRepositories, GitBundle.message("action.not.possible.in.fresh.repo.checkout")); } } /** * Actions available for local branches. */ public static class LocalBranchActions extends BranchActionGroup implements PopupElementWithAdditionalInfo { protected final Project myProject; protected final List<GitRepository> myRepositories; protected final @NlsSafe String myBranchName; @NotNull private final GitRepository mySelectedRepository; private final GitBranchManager myGitBranchManager; @NotNull private final GitBranchIncomingOutgoingManager myIncomingOutgoingManager; public LocalBranchActions(@NotNull Project project, @NotNull List<? extends GitRepository> repositories, @NotNull @NlsSafe String branchName, @NotNull GitRepository selectedRepository) { myProject = project; myRepositories = immutableList(repositories); myBranchName = branchName; mySelectedRepository = selectedRepository; myGitBranchManager = project.getService(GitBranchManager.class); myIncomingOutgoingManager = GitBranchIncomingOutgoingManager.getInstance(myProject); getTemplatePresentation().setText(myBranchName, false); // no mnemonics addTooltipText(getTemplatePresentation(), constructIncomingOutgoingTooltip(hasIncomingCommits(), hasOutgoingCommits())); setFavorite(myGitBranchManager.isFavorite(LOCAL, repositories.size() > 1 ? null : mySelectedRepository, myBranchName)); } @NotNull List<GitRepository> getRepositories() { return myRepositories; } @NotNull public String getBranchName() { return myBranchName; } @Nls(capitalization = Nls.Capitalization.Sentence) @Nullable public static String constructIncomingOutgoingTooltip(boolean incoming, boolean outgoing) { if (!incoming && !outgoing) return null; if (incoming && outgoing) { return GitBundle.message("branches.there.are.incoming.and.outgoing.commits"); } if (incoming) { return GitBundle.message("branches.there.are.incoming.commits"); } return GitBundle.message("branches.there.are.outgoing.commits"); } @Override public AnAction @NotNull [] getChildren(@Nullable AnActionEvent e) { return new AnAction[]{ new CheckoutAction(myProject, myRepositories, myBranchName), new CheckoutAsNewBranch(myProject, myRepositories, myBranchName), new CheckoutWithRebaseAction(myProject, myRepositories, myBranchName), new Separator(), new CompareAction(myProject, myRepositories, myBranchName), new ShowDiffWithBranchAction(myProject, myRepositories, myBranchName), new Separator(), new RebaseAction(myProject, myRepositories, myBranchName), new MergeAction(myProject, myRepositories, myBranchName, true), new Separator(), new UpdateSelectedBranchAction(myProject, myRepositories, myBranchName, hasIncomingCommits()), new PushBranchAction(myProject, myRepositories, myBranchName, hasOutgoingCommits()), new Separator(), new RenameBranchAction(myProject, myRepositories, myBranchName), new DeleteAction(myProject, myRepositories, myBranchName) }; } @Override @Nullable public String getInfoText() { return new GitMultiRootBranchConfig(myRepositories).getTrackedBranch(myBranchName); } @Override public void toggle() { super.toggle(); myGitBranchManager.setFavorite(LOCAL, chooseRepo(), myBranchName, isFavorite()); } @Nullable private GitRepository chooseRepo() { return myRepositories.size() > 1 ? null : mySelectedRepository; } @Override public boolean hasIncomingCommits() { return myIncomingOutgoingManager.hasIncomingFor(chooseRepo(), myBranchName); } @Override public boolean hasOutgoingCommits() { return myIncomingOutgoingManager.hasOutgoingFor(chooseRepo(), myBranchName); } public static class CheckoutAction extends DumbAwareAction { private final Project myProject; private final List<? extends GitRepository> myRepositories; private final String myBranchName; public CheckoutAction(@NotNull Project project, @NotNull List<? extends GitRepository> repositories, @NotNull String branchName) { super(GitBundle.messagePointer("branches.checkout")); myProject = project; myRepositories = repositories; myBranchName = branchName; } @Override public void actionPerformed(@NotNull AnActionEvent e) { checkoutBranch(myProject, myRepositories, myBranchName); } public static void checkoutBranch(@NotNull Project project, @NotNull List<? extends GitRepository> repositories, @NotNull String branchName) { GitBrancher brancher = GitBrancher.getInstance(project); brancher.checkout(branchName, false, repositories, null); } } private static class PushBranchAction extends DumbAwareAction implements CustomIconProvider { private final Project myProject; private final List<GitRepository> myRepositories; private final String myBranchName; private final boolean myHasCommitsToPush; PushBranchAction(@NotNull Project project, @NotNull List<GitRepository> repositories, @NotNull String branchName, boolean hasCommitsToPush) { super(ActionsBundle.messagePointer("action.Vcs.Push.text")); myProject = project; myRepositories = repositories; myBranchName = branchName; myHasCommitsToPush = hasCommitsToPush; } @Override public void update(@NotNull AnActionEvent e) { disableActionIfAnyRepositoryIsFresh(e, myRepositories, GitBundle.message("action.not.possible.in.fresh.repo.push")); } @Override public void actionPerformed(@NotNull AnActionEvent e) { GitLocalBranch localBranch = myRepositories.get(0).getBranches().findLocalBranch(myBranchName); assert localBranch != null; new VcsPushDialog(myProject, myRepositories, myRepositories, null, GitPushSource.create(localBranch)).show(); } @Nullable @Override public Icon getRightIcon() { return myHasCommitsToPush ? DvcsImplIcons.Outgoing : null; } } public static class RenameBranchAction extends DumbAwareAction { @NotNull private final Project myProject; @NotNull private final List<? extends GitRepository> myRepositories; @NotNull private final String myCurrentBranchName; RenameBranchAction(@NotNull Project project, @NotNull List<? extends GitRepository> repositories, @NotNull String currentBranchName) { super(ActionsBundle.messagePointer("action.RenameAction.text")); myProject = project; myRepositories = repositories; myCurrentBranchName = currentBranchName; } @Override public void actionPerformed(@NotNull AnActionEvent e) { rename(myProject, myRepositories, myCurrentBranchName); } public static void rename(@NotNull Project project, @NotNull List<? extends GitRepository> repositories, @NotNull String currentBranchName) { GitNewBranchOptions options = new GitNewBranchDialog(project, repositories, GitBundle.message("branches.rename.branch", currentBranchName), currentBranchName, false, false, false, false, GitBranchOperationType.RENAME).showAndGetOptions(); if (options != null) { GitBrancher brancher = GitBrancher.getInstance(project); brancher.renameBranch(currentBranchName, options.getName(), repositories); } } @Override public void update(@NotNull AnActionEvent e) { disableActionIfAnyRepositoryIsFresh(e, myRepositories, GitBundle.message("action.not.possible.in.fresh.repo.rename.branch")); } } private static class DeleteAction extends DumbAwareAction { private final Project myProject; private final List<? extends GitRepository> myRepositories; private final String myBranchName; DeleteAction(Project project, List<? extends GitRepository> repositories, String branchName) { super(IdeBundle.messagePointer("action.delete")); myProject = project; myRepositories = repositories; myBranchName = branchName; } @Override public void actionPerformed(@NotNull AnActionEvent e) { GitBrancher.getInstance(myProject) .deleteBranch(myBranchName, filter(myRepositories, repository -> !myBranchName.equals(repository.getCurrentBranchName()))); } } } public static class CurrentBranchActions extends LocalBranchActions { public CurrentBranchActions(@NotNull Project project, @NotNull List<? extends GitRepository> repositories, @NotNull String branchName, @NotNull GitRepository selectedRepository) { super(project, repositories, branchName, selectedRepository); setIcons(DvcsImplIcons.CurrentBranchFavoriteLabel, DvcsImplIcons.CurrentBranchLabel, AllIcons.Nodes.Favorite, AllIcons.Nodes.NotFavoriteOnHover); } @Override public AnAction @NotNull [] getChildren(@Nullable AnActionEvent e) { return new AnAction[]{ new CheckoutAsNewBranch(myProject, myRepositories, myBranchName), new Separator(), new ShowDiffWithBranchAction(myProject, myRepositories, myBranchName), new Separator(), new UpdateSelectedBranchAction(myProject, myRepositories, myBranchName, hasIncomingCommits()), new LocalBranchActions.PushBranchAction(myProject, myRepositories, myBranchName, hasOutgoingCommits()), new Separator(), new LocalBranchActions.RenameBranchAction(myProject, myRepositories, myBranchName), }; } } /** * Actions available for remote branches */ public static class RemoteBranchActions extends BranchActionGroup { private final Project myProject; private final List<? extends GitRepository> myRepositories; private final @NlsSafe String myBranchName; @NotNull private final GitRepository mySelectedRepository; @NotNull private final GitBranchManager myGitBranchManager; public RemoteBranchActions(@NotNull Project project, @NotNull List<? extends GitRepository> repositories, @NotNull @NlsSafe String branchName, @NotNull GitRepository selectedRepository) { myProject = project; myRepositories = repositories; myBranchName = branchName; mySelectedRepository = selectedRepository; myGitBranchManager = project.getService(GitBranchManager.class); getTemplatePresentation().setText(myBranchName, false); // no mnemonics setFavorite(myGitBranchManager.isFavorite(REMOTE, repositories.size() > 1 ? null : mySelectedRepository, myBranchName)); } @Override public void toggle() { super.toggle(); myGitBranchManager.setFavorite(REMOTE, myRepositories.size() > 1 ? null : mySelectedRepository, myBranchName, isFavorite()); } @Override public AnAction @NotNull [] getChildren(@Nullable AnActionEvent e) { return new AnAction[]{ new CheckoutRemoteBranchAction(myProject, myRepositories, myBranchName), new CheckoutAsNewBranch(myProject, myRepositories, myBranchName), new Separator(), new CompareAction(myProject, myRepositories, myBranchName), new ShowDiffWithBranchAction(myProject, myRepositories, myBranchName), new Separator(), new RebaseAction(myProject, myRepositories, myBranchName), new MergeAction(myProject, myRepositories, myBranchName, false), new Separator(), new PullWithRebaseAction(myProject, myRepositories, myBranchName), new PullWithMergeAction(myProject, myRepositories, myBranchName), new Separator(), new RemoteDeleteAction(myProject, myRepositories, myBranchName) }; } public static class CheckoutRemoteBranchAction extends DumbAwareAction { private final Project myProject; private final List<? extends GitRepository> myRepositories; private final String myRemoteBranchName; CheckoutRemoteBranchAction(@NotNull Project project, @NotNull List<? extends GitRepository> repositories, @NotNull String remoteBranchName) { super(GitBundle.messagePointer("branches.checkout")); myProject = project; myRepositories = repositories; myRemoteBranchName = remoteBranchName; } public static void checkoutRemoteBranch(@NotNull Project project, @NotNull List<? extends GitRepository> repositories, @NotNull String remoteBranchName) { GitRepository repository = repositories.get(0); GitRemoteBranch remoteBranch = Objects.requireNonNull(repository.getBranches().findRemoteBranch(remoteBranchName)); String suggestedLocalName = remoteBranch.getNameForRemoteOperations(); // can have remote conflict if git-svn is used - suggested local name will be equal to selected remote if (BRANCH_NAME_HASHING_STRATEGY.equals(remoteBranchName, suggestedLocalName)) { askNewBranchNameAndCheckout(project, repositories, remoteBranchName, suggestedLocalName); return; } Map<GitRepository, GitLocalBranch> conflictingLocalBranches = map2MapNotNull(repositories, r -> { GitLocalBranch local = r.getBranches().findLocalBranch(suggestedLocalName); return local != null ? Pair.create(r, local) : null; }); if (hasTrackingConflicts(conflictingLocalBranches, remoteBranchName)) { askNewBranchNameAndCheckout(project, repositories, remoteBranchName, suggestedLocalName); return; } boolean hasCommits = !conflictingLocalBranches.isEmpty() && checkCommitsUnderProgress(project, repositories, remoteBranchName, suggestedLocalName); if (hasCommits) { int result = Messages.showYesNoCancelDialog( GitBundle.message("local.branch.already.exists.and.has.commits.which.do.not.exist.in.remote", suggestedLocalName, remoteBranchName), GitBundle.message("checkout.0", remoteBranchName), GitBundle.message("checkout.and.rebase"), GitBundle.message("branches.drop.local.commits"), IdeBundle.message("button.cancel"), null); if (result == Messages.CANCEL) return; if (result == Messages.YES) { checkout(project, repositories, remoteBranchName, suggestedLocalName, true); return; } } GitBrancher brancher = GitBrancher.getInstance(project); brancher .checkoutNewBranchStartingFrom(suggestedLocalName, remoteBranchName, !conflictingLocalBranches.isEmpty(), repositories, null); } @Override public void actionPerformed(@NotNull AnActionEvent e) { checkoutRemoteBranch(myProject, myRepositories, myRemoteBranchName); } private static void askNewBranchNameAndCheckout(@NotNull Project project, @NotNull List<? extends GitRepository> repositories, @NotNull String remoteBranchName, @NotNull String suggestedLocalName) { //do not allow name conflicts GitNewBranchOptions options = new GitNewBranchDialog(project, repositories, GitBundle.message("branches.checkout.s", remoteBranchName), suggestedLocalName, false, true) .showAndGetOptions(); if (options == null) return; GitBrancher brancher = GitBrancher.getInstance(project); brancher.checkoutNewBranchStartingFrom(options.getName(), remoteBranchName, options.shouldReset(), repositories, null); } private static boolean hasTrackingConflicts(@NotNull Map<GitRepository, GitLocalBranch> conflictingLocalBranches, @NotNull String remoteBranchName) { return or(conflictingLocalBranches.keySet(), r -> { GitBranchTrackInfo trackInfo = GitBranchUtil.getTrackInfoForBranch(r, conflictingLocalBranches.get(r)); return trackInfo != null && !BRANCH_NAME_HASHING_STRATEGY.equals(remoteBranchName, trackInfo.getRemoteBranch().getName()); }); } } private static class PullBranchBaseAction extends DumbAwareAction { private final Project myProject; private final List<? extends GitRepository> myRepositories; private final String myRemoteBranchName; private final UpdateMethod myUpdateMethod; PullBranchBaseAction(@NotNull Project project, @NotNull List<? extends GitRepository> repositories, @NotNull String remoteBranchName, UpdateMethod updateMethod) { myProject = project; myRepositories = repositories; myRemoteBranchName = remoteBranchName; myUpdateMethod = updateMethod; } private static Map<GitRepository, GitBranchPair> configureTarget(List<? extends GitRepository> repositories, String branchName) { Map<GitRepository, GitBranchPair> map = new LinkedHashMap<>(); for (GitRepository repo : repositories) { GitLocalBranch currentBranch = repo.getCurrentBranch(); GitRemoteBranch remoteBranch = repo.getBranches().findRemoteBranch(branchName); if (currentBranch != null && remoteBranch != null) { map.put(repo, new GitBranchPair(currentBranch, remoteBranch)); } } return map; } @Override public void actionPerformed(@NotNull AnActionEvent e) { new GitUpdateExecutionProcess(myProject, myRepositories, configureTarget(myRepositories, myRemoteBranchName), myUpdateMethod, false) .execute(); } } private static class PullWithMergeAction extends PullBranchBaseAction { PullWithMergeAction(@NotNull Project project, @NotNull List<? extends GitRepository> repositories, @NotNull String branchName) { super(project, repositories, branchName, UpdateMethod.MERGE); Presentation presentation = getTemplatePresentation(); Supplier<@Nls String> text = GitBundle.messagePointer("branches.action.pull.into.branch.using.merge", getCurrentBranchTruncatedPresentation(project, repositories)); presentation.setText(text); Supplier<@Nls String> description = GitBundle.messagePointer("branches.action.pull.into.branch.using.merge.description", getCurrentBranchFullPresentation(project, repositories)); presentation.setDescription(description); addTooltipText(presentation, description.get()); } } private static class PullWithRebaseAction extends PullBranchBaseAction { PullWithRebaseAction(@NotNull Project project, @NotNull List<? extends GitRepository> repositories, @NotNull String branchName) { super(project, repositories, branchName, UpdateMethod.REBASE); Presentation presentation = getTemplatePresentation(); Supplier<@Nls String> text = GitBundle.messagePointer("branches.action.pull.into.branch.using.rebase", getCurrentBranchTruncatedPresentation(project, repositories)); presentation.setText(text); Supplier<@Nls String> description = GitBundle.messagePointer("branches.action.pull.into.branch.using.rebase.description", getCurrentBranchFullPresentation(project, repositories)); presentation.setDescription(description); addTooltipText(presentation, description.get()); } } private static class RemoteDeleteAction extends DumbAwareAction { private final Project myProject; private final List<? extends GitRepository> myRepositories; private final String myBranchName; RemoteDeleteAction(@NotNull Project project, @NotNull List<? extends GitRepository> repositories, @NotNull String branchName) { super(IdeBundle.messagePointer("action.delete")); myProject = project; myRepositories = repositories; myBranchName = branchName; } @Override public void actionPerformed(@NotNull AnActionEvent e) { GitBrancher brancher = GitBrancher.getInstance(myProject); brancher.deleteRemoteBranch(myBranchName, myRepositories); } @Override public void update(@NotNull AnActionEvent e) { e.getPresentation().setEnabled(!GitProtectedBranchesKt.isRemoteBranchProtected(myRepositories, myBranchName)); } } } private static class CheckoutAsNewBranch extends DumbAwareAction { private final Project myProject; private final List<? extends GitRepository> myRepositories; private final String myBranchName; CheckoutAsNewBranch(@NotNull Project project, @NotNull List<? extends GitRepository> repositories, @NotNull String branchName) { super(GitBundle.messagePointer("branches.new.branch.from.branch", getSelectedBranchTruncatedPresentation(project, branchName))); Supplier<@Nls String> description = GitBundle.messagePointer("branches.new.branch.from.branch.description", getSelectedBranchFullPresentation(branchName)); getTemplatePresentation().setDescription(description); addTooltipText(getTemplatePresentation(), description.get()); myProject = project; myRepositories = repositories; myBranchName = branchName; } @Override public void update(@NotNull AnActionEvent e) { disableActionIfAnyRepositoryIsFresh(e, myRepositories, DvcsBundle.message("action.not.possible.in.fresh.repo.new.branch")); } @Override public void actionPerformed(@NotNull AnActionEvent e) { createOrCheckoutNewBranch(myProject, myRepositories, myBranchName + "^0", GitBundle.message("action.Git.New.Branch.dialog.title", myBranchName)); } } private static class CompareAction extends DumbAwareAction { private final Project myProject; private final List<? extends GitRepository> myRepositories; private final String myBranchName; CompareAction(@NotNull Project project, @NotNull List<? extends GitRepository> repositories, @NotNull String branchName) { super(GitBundle.messagePointer("branches.compare.with.current")); myProject = project; myRepositories = repositories; myBranchName = branchName; } @Override public void actionPerformed(@NotNull AnActionEvent e) { FileDocumentManager.getInstance().saveAllDocuments(); GitBrancher brancher = GitBrancher.getInstance(myProject); brancher.compare(myBranchName, myRepositories); } @Override public void update(@NotNull AnActionEvent e) { String description = GitBundle.message("branches.show.commits.in", getSelectedBranchFullPresentation(myBranchName), getCurrentBranchFullPresentation(myProject, myRepositories)); Presentation presentation = e.getPresentation(); presentation.setDescription(description); addTooltipText(presentation, description); String text = GitBundle.message("branches.compare.with.branch", getCurrentBranchTruncatedPresentation(myProject, myRepositories)); presentation.setText(text); } } private static class ShowDiffWithBranchAction extends DumbAwareAction { private final Project myProject; private final List<? extends GitRepository> myRepositories; private final String myBranchName; ShowDiffWithBranchAction(@NotNull Project project, @NotNull List<? extends GitRepository> repositories, @NotNull String branchName) { super(GitBundle.messagePointer("branches.show.diff.with.working.tree")); myProject = project; myRepositories = repositories; myBranchName = branchName; } @Override public void actionPerformed(@NotNull AnActionEvent e) { GitBrancher.getInstance(myProject) .showDiffWithLocal(myBranchName, myRepositories); } @Override public void update(@NotNull AnActionEvent e) { e.getPresentation().setEnabledAndVisible(!new GitMultiRootBranchConfig(myRepositories).diverged()); String description = GitBundle.message("branches.compare.the.current.working.tree.with", getSelectedBranchFullPresentation(myBranchName)); e.getPresentation().setDescription(description); disableActionIfAnyRepositoryIsFresh(e, myRepositories, GitBundle.message("action.not.possible.in.fresh.repo.show.diff")); } } private static class MergeAction extends DumbAwareAction { private final Project myProject; private final List<? extends GitRepository> myRepositories; private final String myBranchName; private final boolean myLocalBranch; MergeAction(@NotNull Project project, @NotNull List<? extends GitRepository> repositories, @NotNull String branchName, boolean localBranch) { super(GitBundle.messagePointer("branches.merge.into.current")); myProject = project; myRepositories = repositories; myBranchName = branchName; myLocalBranch = localBranch; } @Override public void update(@NotNull AnActionEvent e) { Presentation presentation = e.getPresentation(); String description = GitBundle.message("branches.merge.into", getSelectedBranchFullPresentation(myBranchName), getCurrentBranchFullPresentation(myProject, myRepositories)); presentation.setDescription(description); addTooltipText(presentation, description); String name = GitBundle.message("branches.merge.into", getSelectedBranchTruncatedPresentation(myProject, myBranchName), getCurrentBranchTruncatedPresentation(myProject, myRepositories)); presentation.setText(name); } @Override public void actionPerformed(@NotNull AnActionEvent e) { GitBrancher brancher = GitBrancher.getInstance(myProject); brancher.merge(myBranchName, deleteOnMerge(), myRepositories); } private GitBrancher.DeleteOnMergeOption deleteOnMerge() { if (myLocalBranch && !myBranchName.equals("master")) { // NON-NLS return GitBrancher.DeleteOnMergeOption.PROPOSE; } return GitBrancher.DeleteOnMergeOption.NOTHING; } } private static class RebaseAction extends DumbAwareAction { private final Project myProject; private final List<? extends GitRepository> myRepositories; private final String myBranchName; RebaseAction(@NotNull Project project, @NotNull List<? extends GitRepository> repositories, @NotNull String branchName) { super(GitBundle.messagePointer("branches.rebase.current.onto.selected")); myProject = project; myRepositories = repositories; myBranchName = branchName; } @Override public void update(@NotNull AnActionEvent e) { boolean isOnBranch = and(myRepositories, GitRepository::isOnBranch); String description = isOnBranch ? GitBundle.message("branches.rebase.onto", getCurrentBranchFullPresentation(myProject, myRepositories), getSelectedBranchFullPresentation(myBranchName)) : GitBundle.message("branches.rebase.is.not.possible.in.the.detached.head.state"); Presentation presentation = e.getPresentation(); presentation.setDescription(description); addTooltipText(presentation, description); presentation.setEnabled(isOnBranch); String actionText = GitBundle.message( "branches.rebase.onto", getCurrentBranchTruncatedPresentation(myProject, myRepositories), getSelectedBranchTruncatedPresentation(myProject, myBranchName)); presentation.setText(actionText); } @Override public void actionPerformed(@NotNull AnActionEvent e) { GitBrancher brancher = GitBrancher.getInstance(myProject); brancher.rebase(myRepositories, myBranchName); } } private static class CheckoutWithRebaseAction extends DumbAwareAction { private final Project myProject; private final List<? extends GitRepository> myRepositories; private final String myBranchName; CheckoutWithRebaseAction(@NotNull Project project, @NotNull List<? extends GitRepository> repositories, @NotNull String branchName) { super(GitBundle.messagePointer("branches.checkout.and.rebase.onto.current")); myProject = project; myRepositories = repositories; myBranchName = branchName; } @Override public void update(@NotNull AnActionEvent e) { String description = GitBundle.message("branches.checkout.and.rebase.onto.in.one.step", getSelectedBranchFullPresentation(myBranchName), getCurrentBranchFullPresentation(myProject, myRepositories), myBranchName); Presentation presentation = e.getPresentation(); presentation.setDescription(description); addTooltipText(presentation, description); String text = GitBundle.message("branches.checkout.and.rebase.onto.branch", getCurrentBranchTruncatedPresentation(myProject, myRepositories)); presentation.setText(text); } @Override public void actionPerformed(@NotNull AnActionEvent e) { GitBrancher brancher = GitBrancher.getInstance(myProject); brancher.rebaseOnCurrent(myRepositories, myBranchName); } } private static class UpdateSelectedBranchAction extends DumbAwareAction implements CustomIconProvider { protected final Project myProject; protected final List<? extends GitRepository> myRepositories; protected final String myBranchName; protected final List<String> myBranchNameList; protected final boolean myHasIncoming; UpdateSelectedBranchAction(@NotNull Project project, @NotNull List<? extends GitRepository> repositories, @NotNull String branchName, boolean hasIncoming) { super(GitBundle.messagePointer("branches.update")); myProject = project; myRepositories = repositories; myBranchName = branchName; myBranchNameList = Collections.singletonList(branchName); myHasIncoming = hasIncoming; } @Override public void update(@NotNull AnActionEvent e) { Presentation presentation = e.getPresentation(); if (!hasRemotes(myProject)) { presentation.setEnabledAndVisible(false); return; } String branchPresentation = getSelectedBranchFullPresentation(myBranchName); String description = GitBundle.message("action.Git.Update.Selected.description", myBranchNameList.size(), GitVcsSettings.getInstance(myProject).getUpdateMethod().getName().toLowerCase(Locale.ROOT)); presentation.setDescription(description); if (GitFetchSupport.fetchSupport(myProject).isFetchRunning()) { presentation.setEnabled(false); presentation.setDescription(GitBundle.message("branches.update.is.already.running")); return; } boolean trackingInfosExist = isTrackingInfosExist(myBranchNameList, myRepositories); presentation.setEnabled(trackingInfosExist); if (!trackingInfosExist) { presentation.setDescription(GitBundle.message("branches.tracking.branch.doesn.t.configured.for.s", branchPresentation)); } } @Override public void actionPerformed(@NotNull AnActionEvent e) { updateBranches(myProject, myRepositories, myBranchNameList); } @Nullable @Override public Icon getRightIcon() { return myHasIncoming ? DvcsImplIcons.Incoming : null; } } static class TagActions extends BranchActionGroup { private final Project myProject; private final List<? extends GitRepository> myRepositories; private final String myTagName; TagActions(@NotNull Project project, @NotNull List<? extends GitRepository> repositories, @NotNull @NlsSafe String tagName) { myProject = project; myRepositories = repositories; myTagName = tagName; getTemplatePresentation().setText(tagName, false); // no mnemonics setIcons(EmptyIcon.ICON_16, EmptyIcon.ICON_16, EmptyIcon.ICON_16, EmptyIcon.ICON_16); // no favorites } @Override public AnAction @NotNull [] getChildren(@Nullable AnActionEvent e) { return new AnAction[]{ new DeleteTagAction(myProject, myRepositories, myTagName) }; } private static class DeleteTagAction extends DumbAwareAction { private final Project myProject; private final List<? extends GitRepository> myRepositories; private final String myTagName; DeleteTagAction(Project project, List<? extends GitRepository> repositories, String tagName) { super(IdeBundle.messagePointer("button.delete")); myProject = project; myRepositories = repositories; myTagName = tagName; } @Override public void actionPerformed(@NotNull AnActionEvent e) { GitBrancher brancher = GitBrancher.getInstance(myProject); brancher.deleteTag(myTagName, myRepositories); } } } @NlsSafe @NotNull private static String getCurrentBranchFullPresentation(@NotNull Project project, @NotNull Collection<? extends GitRepository> repositories) { return getCurrentBranchPresentation(project, repositories, false); } @NlsSafe @NotNull private static String getCurrentBranchTruncatedPresentation(@NotNull Project project, @NotNull Collection<? extends GitRepository> repositories) { return getCurrentBranchPresentation(project, repositories, true); } @Nls @NotNull private static String getCurrentBranchPresentation(@NotNull Project project, @NotNull Collection<? extends GitRepository> repositories, boolean truncateBranchName) { Set<String> currentBranches = map2Set(repositories, repo -> notNull(repo.getCurrentBranchName(), getShortHash(Objects.requireNonNull(repo.getCurrentRevision())))); if (currentBranches.size() == 1) { String fullBranchName = currentBranches.iterator().next(); return truncateBranchName ? getCurrentBranchTruncatedName(fullBranchName, project) : wrapWithQuotes(fullBranchName); } return GitBundle.message("branches.current.branch"); } @NlsSafe @NotNull private static String getSelectedBranchFullPresentation(@NlsSafe @NotNull String branchName) { return wrapWithQuotes(branchName); } private static final int MAX_BRANCH_NAME_LENGTH = 40; private static final int BRANCH_NAME_LENGHT_DELTA = 4; private static final int BRANCH_NAME_SUFFIX_LENGTH = 5; @NlsSafe @NotNull private static String getCurrentBranchTruncatedName(@NlsSafe @NotNull String branchName, @NotNull Project project) { return showFullBranchNamesInsteadOfCurrentSelected() ? wrapWithQuotes(StringUtil.escapeMnemonics(truncateBranchName(branchName, project))) : GitBundle.message("branches.current.branch.name"); } @NlsSafe @NotNull private static String getSelectedBranchTruncatedPresentation(@NotNull Project project, @NlsSafe @NotNull String branchName) { return showFullBranchNamesInsteadOfCurrentSelected() ? wrapWithQuotes(StringUtil.escapeMnemonics(truncateBranchName(branchName, project))) : GitBundle.message("branches.selected.branch.name"); } private static boolean showFullBranchNamesInsteadOfCurrentSelected() { return Registry.is("git.show.full.branch.name.instead.current.selected"); } @NlsSafe @NotNull static String truncateBranchName(@NotNull @NlsSafe String branchName, @NotNull Project project) { int branchNameLength = branchName.length(); if (branchNameLength <= MAX_BRANCH_NAME_LENGTH + BRANCH_NAME_LENGHT_DELTA) { return branchName; } IssueNavigationConfiguration issueNavigationConfiguration = IssueNavigationConfiguration.getInstance(project); List<IssueNavigationConfiguration.LinkMatch> issueMatches = issueNavigationConfiguration.findIssueLinks(branchName); if (issueMatches.size() != 0) { // never truncate the first occurrence of the issue id IssueNavigationConfiguration.LinkMatch firstMatch = issueMatches.get(0); TextRange firstMatchRange = firstMatch.getRange(); return truncateAndSaveIssueId(firstMatchRange, branchName, MAX_BRANCH_NAME_LENGTH, BRANCH_NAME_SUFFIX_LENGTH, BRANCH_NAME_LENGHT_DELTA); } return StringUtil.shortenTextWithEllipsis(branchName, MAX_BRANCH_NAME_LENGTH, BRANCH_NAME_SUFFIX_LENGTH, true); } @NlsSafe @NotNull static String truncateAndSaveIssueId(@NotNull TextRange issueIdRange, @NotNull String branchName, int maxBranchNameLength, int suffixLength, int delta) { String truncatedByDefault = StringUtil.shortenTextWithEllipsis(branchName, maxBranchNameLength, suffixLength, true); String issueId = issueIdRange.substring(branchName); if (truncatedByDefault.contains(issueId)) return truncatedByDefault; try { int branchNameLength = branchName.length(); int endOffset = issueIdRange.getEndOffset(); int startOffset = issueIdRange.getStartOffset(); // suffix intersects with the issue id if (endOffset >= branchNameLength - suffixLength - delta) { return StringUtil.shortenTextWithEllipsis(branchName, maxBranchNameLength, branchNameLength - startOffset, true); } String suffix = branchName.substring(branchNameLength - suffixLength); int prefixLength = maxBranchNameLength - suffixLength - issueId.length(); String prefixAndIssue; if (Math.abs(startOffset - prefixLength) <= delta) { prefixAndIssue = branchName.substring(0, endOffset); } else { String prefix = branchName.substring(0, prefixLength); prefixAndIssue = prefix + StringUtil.ELLIPSIS + issueId; } return prefixAndIssue + StringUtil.ELLIPSIS + suffix; } catch (Throwable e) { return truncatedByDefault; } } @NlsSafe @NotNull private static String wrapWithQuotes(@NlsSafe @NotNull String branchName) { return "'" + branchName + "'"; } /** * Adds a tooltip to action in the branches popup * * @see com.intellij.ui.popup.ActionStepBuilder#appendAction */ private static void addTooltipText(Presentation presentation, @NlsContexts.Tooltip String tooltipText) { presentation.putClientProperty(JComponent.TOOL_TIP_TEXT_KEY, tooltipText); } }
mdaniel/intellij-community
plugins/git4idea/src/git4idea/ui/branch/GitBranchPopupActions.java
Java
apache-2.0
50,412
/******************************************************************************* * Copyright (c) 2008-2010 Sonatype, Inc. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Sonatype, Inc. - initial API and implementation *******************************************************************************/ package org.eclipse.m2e.core.embedder; import java.util.Collection; import java.util.Collections; import java.util.HashSet; import java.util.IdentityHashMap; import java.util.Iterator; import java.util.LinkedHashSet; import java.util.List; import java.util.ListIterator; import java.util.Map; import org.sonatype.aether.RepositoryException; import org.sonatype.aether.collection.DependencyGraphTransformationContext; import org.sonatype.aether.collection.DependencyGraphTransformer; import org.sonatype.aether.collection.UnsolvableVersionConflictException; import org.sonatype.aether.graph.DependencyNode; import org.sonatype.aether.util.graph.DefaultDependencyNode; import org.sonatype.aether.util.graph.transformer.ConflictIdSorter; import org.sonatype.aether.util.graph.transformer.TransformationContextKeys; import org.sonatype.aether.version.Version; import org.sonatype.aether.version.VersionConstraint; class NearestVersionConflictResolver implements DependencyGraphTransformer { public DependencyNode transformGraph(DependencyNode node, DependencyGraphTransformationContext context) throws RepositoryException { List<?> sortedConflictIds = (List<?>) context.get(TransformationContextKeys.SORTED_CONFLICT_IDS); if(sortedConflictIds == null) { ConflictIdSorter sorter = new ConflictIdSorter(); sorter.transformGraph(node, context); sortedConflictIds = (List<?>) context.get(TransformationContextKeys.SORTED_CONFLICT_IDS); } Map<?, ?> conflictIds = (Map<?, ?>) context.get(TransformationContextKeys.CONFLICT_IDS); if(conflictIds == null) { throw new RepositoryException("conflict groups have not been identified"); } Map<DependencyNode, Integer> depths = new IdentityHashMap<DependencyNode, Integer>(conflictIds.size()); for(Object key : sortedConflictIds) { ConflictGroup group = new ConflictGroup(key); depths.clear(); selectVersion(node, null, 0, depths, group, conflictIds); pruneNonSelectedVersions(group, conflictIds); } return node; } private void selectVersion(DependencyNode node, DependencyNode parent, int depth, Map<DependencyNode, Integer> depths, ConflictGroup group, Map<?, ?> conflictIds) throws RepositoryException { Integer smallestDepth = depths.get(node); if(smallestDepth == null || smallestDepth.intValue() > depth) { depths.put(node, Integer.valueOf(depth)); } else { return; } Object key = conflictIds.get(node); if(group.key.equals(key)) { Position pos = new Position(parent, depth); if(parent != null) { group.positions.add(pos); } VersionConstraint constraint = node.getVersionConstraint(); boolean backtrack = false; boolean hardConstraint = !constraint.getRanges().isEmpty(); if(hardConstraint) { if(group.constraints.add(constraint)) { if(group.version != null && !constraint.containsVersion(group.version)) { backtrack = true; } } } if(isAcceptable(group, node.getVersion())) { group.candidates.put(node, pos); if(backtrack) { backtrack(group); } else if(group.version == null || isNearer(pos, node.getVersion(), group.position, group.version)) { group.winner = node; group.version = node.getVersion(); group.position = pos; } } else { if(backtrack) { backtrack(group); } return; } } depth++ ; for(DependencyNode child : node.getChildren()) { selectVersion(child, node, depth, depths, group, conflictIds); } } private boolean isAcceptable( ConflictGroup group, Version version ) { for ( VersionConstraint constraint : group.constraints ) { if ( !constraint.containsVersion( version ) ) { return false; } } return true; } private void backtrack(ConflictGroup group) throws UnsolvableVersionConflictException { group.winner = null; group.version = null; for(Iterator<Map.Entry<DependencyNode, Position>> it = group.candidates.entrySet().iterator(); it.hasNext();) { Map.Entry<DependencyNode, Position> entry = it.next(); Version version = entry.getKey().getVersion(); Position pos = entry.getValue(); if(!isAcceptable(group, version)) { it.remove(); } else if(group.version == null || isNearer(pos, version, group.position, group.version)) { group.winner = entry.getKey(); group.version = version; group.position = pos; } } if(group.version == null) { throw newFailure(group); } } private UnsolvableVersionConflictException newFailure(ConflictGroup group) { Collection<String> versions = new LinkedHashSet<String>(); for(VersionConstraint constraint : group.constraints) { versions.add(constraint.toString()); } return new UnsolvableVersionConflictException(group.key, versions); } private boolean isNearer(Position pos1, Version ver1, Position pos2, Version ver2) { if(pos1.depth < pos2.depth) { return true; } else if(pos1.depth == pos2.depth && pos1.parent == pos2.parent && ver1.compareTo(ver2) > 0) { return true; } return false; } private void pruneNonSelectedVersions(ConflictGroup group, Map<?, ?> conflictIds) { for(Position pos : group.positions) { ConflictNode conflictNode = null; for(ListIterator<DependencyNode> it = pos.parent.getChildren().listIterator(); it.hasNext();) { DependencyNode child = it.next(); Object key = conflictIds.get(child); if(group.key.equals(key)) { if(!group.pruned && group.position.depth == pos.depth && group.version.equals(child.getVersion())) { group.pruned = true; } else if(pos.equals(group.position)) { it.remove(); } else if(conflictNode == null) { conflictNode = new ConflictNode(child, group.winner); it.set(conflictNode); } else { it.remove(); if(conflictNode.getVersion().compareTo(child.getVersion()) < 0) { conflictNode.setDependency(child.getDependency()); conflictNode.setVersion(child.getVersion()); conflictNode.setVersionConstraint(child.getVersionConstraint()); conflictNode.setPremanagedVersion(child.getPremanagedVersion()); conflictNode.setRelocations(child.getRelocations()); } } } } } } static final class ConflictGroup { final Object key; final Collection<VersionConstraint> constraints = new HashSet<VersionConstraint>(); final Map<DependencyNode, Position> candidates = new IdentityHashMap<DependencyNode, Position>(32); DependencyNode winner; Version version; Position position; final Collection<Position> positions = new LinkedHashSet<Position>(); boolean pruned; public ConflictGroup(Object key) { this.key = key; this.position = new Position(null, Integer.MAX_VALUE); } @Override public String toString() { return key + " > " + version; //$NON-NLS-1$ } } static final class Position { final DependencyNode parent; final int depth; final int hash; public Position(DependencyNode parent, int depth) { this.parent = parent; this.depth = depth; hash = 31 * System.identityHashCode(parent) + depth; } @Override public boolean equals(Object obj) { if(this == obj) { return true; } else if(!(obj instanceof Position)) { return false; } Position that = (Position) obj; return this.parent == that.parent && this.depth == that.depth; } @Override public int hashCode() { return hash; } @Override public String toString() { return depth + " > " + parent; //$NON-NLS-1$ } } static final class ConflictNode extends DefaultDependencyNode { public ConflictNode(DependencyNode node, DependencyNode related) { super(node); setAliases(Collections.singletonList(related.getDependency().getArtifact())); } } }
deathknight0718/foliage
src/foliage-m2e/org.foliage.m2e.core/src/org/eclipse/m2e/core/embedder/NearestVersionConflictResolver.java
Java
apache-2.0
8,807
package org.w3c.dom.ls; /* * #%L * Matos * $Id:$ * $HeadURL:$ * %% * Copyright (C) 2010 - 2014 Orange SA * %% * 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. * #L% */ public interface LSParser { // Fields public static final short ACTION_APPEND_AS_CHILDREN = 1; public static final short ACTION_REPLACE_CHILDREN = 2; public static final short ACTION_INSERT_BEFORE = 3; public static final short ACTION_INSERT_AFTER = 4; public static final short ACTION_REPLACE = 5; // Methods public org.w3c.dom.Document parse(LSInput arg1) throws org.w3c.dom.DOMException, LSException; public void abort(); public LSParserFilter getFilter(); public void setFilter(LSParserFilter arg1); public org.w3c.dom.DOMConfiguration getDomConfig(); public boolean getAsync(); public boolean getBusy(); public org.w3c.dom.Document parseURI(java.lang.String arg1) throws org.w3c.dom.DOMException, LSException; public org.w3c.dom.Node parseWithContext(LSInput arg1, org.w3c.dom.Node arg2, short arg3) throws org.w3c.dom.DOMException, LSException; }
Orange-OpenSource/matos-profiles
matos-android/src/main/java/org/w3c/dom/ls/LSParser.java
Java
apache-2.0
1,581