hexsha
stringlengths
40
40
size
int64
8
1.04M
content
stringlengths
8
1.04M
avg_line_length
float64
2.24
100
max_line_length
int64
4
1k
alphanum_fraction
float64
0.25
0.97
2a4f295070193f5d287b3caf511520b06cac8c86
109
package Graphics.Components.Listeners; public interface KeyPressListener { void keyPressed(int code); }
18.166667
38
0.788991
7d3fe577338170b6a98c07fa7de06f85ce25e84e
1,467
package edu.uiowa.icts.bluebutton.json; /* * #%L * blue-button Spring MVC Web App * %% * Copyright (C) 2014 - 2015 University of Iowa Institute for Clinical and Translational Science (ICTS) * %% * 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% */ import java.util.List; public class FindSearchProperties { private List<ISubgroup> list; public FindSearchProperties(List<ISubgroup> list){ this.list = list; } public List<ISubgroup> getListWithSearchIds() { Integer counter = 0; List<ISubgroup> list = this.list; for(ISubgroup i : list){ if(i.getSubgridInterface().size() >0){ i.setId(i.getSearchFieldName().concat(counter.toString())); for(ISubgroup iSub : i.getSubgridInterface()){ iSub.setParent(i.getId()); iSub.setId(i.getSearchFieldName().concat((++counter).toString())); } } else{ i.setId(i.getSearchFieldName().concat(counter.toString())); counter++; } } return list; } }
27.679245
103
0.698705
7e8aa099befebb58f20e64ddd715bc5645bb4f58
10,822
package com.sf.xts.api.sdk.interactive.profile; import java.util.List; import com.google.gson.annotations.Expose; import com.google.gson.annotations.SerializedName; public class Dealer { @SerializedName("DealerId") @Expose private String dealerId; @SerializedName("DealerName") @Expose private String dealerName; @SerializedName("BranchId") @Expose private String branchId; @SerializedName("EmailId") @Expose private String emailId; @SerializedName("PAN") @Expose private String pAN; @SerializedName("IncludeInAutoSquareoff") @Expose private Boolean includeInAutoSquareoff; @SerializedName("IncludeInAutoSquareoffBlock") @Expose private Boolean includeInAutoSquareoffBlock; @SerializedName("OrderTypesAssigned") @Expose private Number orderTypesAssigned; @SerializedName("ProductsAssigned") @Expose private Number productsAssigned; @SerializedName("Pincode") @Expose private String pincode; @SerializedName("ResidentialAddress") @Expose private String residentialAddress; @SerializedName("LastUpdatedOn") @Expose private String lastUpdatedOn; @SerializedName("CreatedOn") @Expose private String createdOn; @SerializedName("CreatedBy") @Expose private String createdBy; @SerializedName("CreatedPrivilegeBy") @Expose private Number createdPrivilegeBy; @SerializedName("Count") @Expose private Number count; @SerializedName("DealerExchangeDetailsList") @Expose private List<DealerExchangeDetailsList> dealerExchangeDetailsList = null; @SerializedName("LastUpdatedBy") @Expose private String lastUpdatedBy; @SerializedName("MobileNumber") @Expose private String mobileNumber; @SerializedName("IsInvestorClient") @Expose private Boolean isInvestorClient; @SerializedName("AllowedProOrder") @Expose private Boolean allowedProOrder; @SerializedName("ProClientId") @Expose private String proClientId; @SerializedName("DealerCredentialObj") @Expose private DealerCredentialObj dealerCredentialObj; @SerializedName("ClientDealerMappingList") @Expose private List<ClientDealerMappingList_> clientDealerMappingList = null; /** * it return dealerId * @return String */ public String getDealerId() { return dealerId; } /** * it set the dealerId * @param dealerId String */ public void setDealerId(String dealerId) { this.dealerId = dealerId; } /** * it return dealerName * @return String */ public String getDealerName() { return dealerName; } /** * it set the dealerName * @param dealerName String */ public void setDealerName(String dealerName) { this.dealerName = dealerName; } /** * it return branchId * @return String */ public String getBranchId() { return branchId; } /** * it set the branchId * @param branchId String */ public void setBranchId(String branchId) { this.branchId = branchId; } /** * it return emailId * @return String */ public String getEmailId() { return emailId; } /** * it set the emailId * @param emailId String */ public void setEmailId(String emailId) { this.emailId = emailId; } /** * it return pAN * @return String */ public String getPAN() { return pAN; } /** * it set the pAN * @param pAN String */ public void setPAN(String pAN) { this.pAN = pAN; } /** * it return includeInAutoSquareoff * @return Boolean */ public Boolean getIncludeInAutoSquareoff() { return includeInAutoSquareoff; } /** * it set the includeInAutoSquareoff * @param includeInAutoSquareoff Boolean */ public void setIncludeInAutoSquareoff(Boolean includeInAutoSquareoff) { this.includeInAutoSquareoff = includeInAutoSquareoff; } /** * it return includeInAutoSquareoffBlock * @return Boolean */ public Boolean getIncludeInAutoSquareoffBlock() { return includeInAutoSquareoffBlock; } /** * it set the includeInAutoSquareoffBlock * @param includeInAutoSquareoffBlock Boolean */ public void setIncludeInAutoSquareoffBlock(Boolean includeInAutoSquareoffBlock) { this.includeInAutoSquareoffBlock = includeInAutoSquareoffBlock; } /** * it return orderTypesAssigned * @return Number */ public Number getOrderTypesAssigned() { return orderTypesAssigned; } /** * it set the orderTypesAssigned * @param orderTypesAssigned Number */ public void setOrderTypesAssigned(Number orderTypesAssigned) { this.orderTypesAssigned = orderTypesAssigned; } /** * it return productsAssigned * @return Number */ public Number getProductsAssigned() { return productsAssigned; } /** * it set the productsAssigned * @param productsAssigned Number */ public void setProductsAssigned(Number productsAssigned) { this.productsAssigned = productsAssigned; } /** * it return pincode * @return String */ public String getPincode() { return pincode; } /** * it set the pincode * @param pincode String */ public void setPincode(String pincode) { this.pincode = pincode; } /** * it return residentialAddress * @return String */ public String getResidentialAddress() { return residentialAddress; } /** * it set the residentialAddress * @param residentialAddress String */ public void setResidentialAddress(String residentialAddress) { this.residentialAddress = residentialAddress; } /** * it return lastUpdatedOn * @return String */ public String getLastUpdatedOn() { return lastUpdatedOn; } /** * it set the lastUpdatedOn * @param lastUpdatedOn String */ public void setLastUpdatedOn(String lastUpdatedOn) { this.lastUpdatedOn = lastUpdatedOn; } /** * it return createdOn * @return String */ public String getCreatedOn() { return createdOn; } /** * it set the createdOn * @param createdOn String */ public void setCreatedOn(String createdOn) { this.createdOn = createdOn; } /** * it return createdBy * @return String */ public String getCreatedBy() { return createdBy; } /** * it set the createdBy * @param createdBy String */ public void setCreatedBy(String createdBy) { this.createdBy = createdBy; } /** * it return createdPrivilegeBy * @return Number */ public Number getCreatedPrivilegeBy() { return createdPrivilegeBy; } /** * it set the createdPrivilegeBy * @param createdPrivilegeBy Number */ public void setCreatedPrivilegeBy(Number createdPrivilegeBy) { this.createdPrivilegeBy = createdPrivilegeBy; } /** * it return count * @return Number */ public Number getCount() { return count; } /** * it set the count * @param count Number */ public void setCount(Number count) { this.count = count; } /** * it return dealerExchangeDetailsList * @return dealerExchangeDetailsList */ public List<DealerExchangeDetailsList> getDealerExchangeDetailsList() { return dealerExchangeDetailsList; } /** * it set the dealerExchangeDetailsList * @param dealerExchangeDetailsList dealerExchangeDetailsList */ public void setDealerExchangeDetailsList(List<DealerExchangeDetailsList> dealerExchangeDetailsList) { this.dealerExchangeDetailsList = dealerExchangeDetailsList; } /** * it return lastUpdatedBy * @return String */ public String getLastUpdatedBy() { return lastUpdatedBy; } /** * it set the lastUpdatedBy * @param lastUpdatedBy String */ public void setLastUpdatedBy(String lastUpdatedBy) { this.lastUpdatedBy = lastUpdatedBy; } /** * it return mobileNumber * @return String */ public String getMobileNumber() { return mobileNumber; } /** * it set the mobileNumber * @param mobileNumber String */ public void setMobileNumber(String mobileNumber) { this.mobileNumber = mobileNumber; } /** * it return isInvestorClient * @return Boolean */ public Boolean getIsInvestorClient() { return isInvestorClient; } /** * it set the isInvestorClient * @param isInvestorClient Boolean */ public void setIsInvestorClient(Boolean isInvestorClient) { this.isInvestorClient = isInvestorClient; } /** * it return allowedProOrder * @return Boolean */ public Boolean getAllowedProOrder() { return allowedProOrder; } /** * it set the allowedProOrder * @param allowedProOrder Boolean */ public void setAllowedProOrder(Boolean allowedProOrder) { this.allowedProOrder = allowedProOrder; } /** * it return proClientId * @return String */ public String getProClientId() { return proClientId; } /** * it set the proClientId * @param proClientId String */ public void setProClientId(String proClientId) { this.proClientId = proClientId; } /** * it return dealerCredentialObj * @return DealerCredentialObj */ public DealerCredentialObj getDealerCredentialObj() { return dealerCredentialObj; } /** * it set the dealerCredentialObj * @param dealerCredentialObj DealerCredentialObj */ public void setDealerCredentialObj(DealerCredentialObj dealerCredentialObj) { this.dealerCredentialObj = dealerCredentialObj; } /** * it return List of clientDealerMappingList * @return List of clientDealerMappingList */ public List<ClientDealerMappingList_> getClientDealerMappingList() { return clientDealerMappingList; } /** * it set the List of clientDealerMappingList * @param clientDealerMappingList List of clientDealerMappingList */ public void setClientDealerMappingList(List<ClientDealerMappingList_> clientDealerMappingList) { this.clientDealerMappingList = clientDealerMappingList; } }
23.025532
105
0.638884
1afa7763ca30ea80d29c2adbbd2c97e573623000
2,039
package nl.mvdr.game.jinput; import lombok.AccessLevel; import lombok.Getter; import lombok.NonNull; import lombok.RequiredArgsConstructor; import net.java.games.input.Component; import net.java.games.input.Component.Identifier.Axis; import net.java.games.input.Component.POV; /** * Mapping value for a single input. * * @author Martijn van de Rijdt */ @RequiredArgsConstructor public class InputMapping { /** Component. */ @Getter(AccessLevel.PACKAGE) @NonNull private final Component component; /** The value the component must have in order to count as pressed.. */ private final float pressedValue; /** @return whether the input is pressed */ boolean isPressed() { return component.getPollData() == pressedValue; } /** {@inheritDoc} */ @Override public String toString() { String result; if (component.getIdentifier() == Axis.POV) { // d-pad result = toStringDPad(); } else { result = component.getName(); } return result; } /** @return toString value in case this mapping corresponds to a d-pad component */ private String toStringDPad() { String result; if (pressedValue == POV.UP) { result = "D-pad up"; } else if (pressedValue == POV.UP_RIGHT) { result = "D-pad up-right"; } else if (pressedValue == POV.RIGHT) { result = "D-pad right"; } else if (pressedValue == POV.DOWN_RIGHT) { result = "D-pad down-right"; } else if (pressedValue == POV.DOWN) { result = "D-pad down"; } else if (pressedValue == POV.DOWN_LEFT) { result = "D-pad down-left"; } else if (pressedValue == POV.LEFT) { result = "D-pad left"; } else if (pressedValue == POV.UP_LEFT) { result = "D-pad up-left"; } else { // unknown value result = "D-pad"; } return result; } }
29.128571
87
0.577734
b6e4d520e4fbd3ab4ef9d8b280a90b3437839cad
5,811
package com.github.nagyesta.demo.nla.state.elevator; import com.github.nagyesta.demo.nla.state.building.AbstractPlace; import com.github.nagyesta.demo.nla.state.building.Attitude; import com.github.nagyesta.demo.nla.state.building.Building; import com.github.nagyesta.demo.nla.state.people.Person; import java.util.*; import java.util.stream.Collectors; public class ElevatorCar extends AbstractPlace implements MutableElevator { public static final double SLOW_TURNS_TO_FAST_TURNS = 0.5D; public static final int DISTANCE_TO_TURNS_MOVING_SLOW = 2; public static final double SAFE_SLOW_DOWN_DISTANCE = 0.5D; public static final double SAFE_SPEED_UP_DISTANCE = 0.5D; public static final double SLOW_ONLY_DISTANCE = SAFE_SPEED_UP_DISTANCE * 2 + SAFE_SLOW_DOWN_DISTANCE; private final SortedSet<Integer> buttonsPressedInCar; private final Set<Integer> plannedStops; private final ElevatorStepCounter stepCounter; private final ElevatorProgramSupport elevatorProgramSupport; private ElevatorStatus status; private boolean justClosedDoor = false; public ElevatorCar(final Building building, final int index, final String name, final int totalCapacity) { super(building, index, name, 0, totalCapacity); this.buttonsPressedInCar = new TreeSet<>(); this.plannedStops = new TreeSet<>(); this.status = ElevatorStatus.STOPPED; this.stepCounter = new ElevatorStepCounter(); this.elevatorProgramSupport = new ElevatorProgramSupport(building.getBuildingDimensions()); } @Override public void accept(final Person person) { super.accept(person); this.buttonsPressedInCar.addAll(person.pressButton()); } @Override public boolean isIdle() { return elevatorProgramSupport.isIdle(); } @Override public SortedSet<Integer> getButtonsPressedInCar() { return Collections.unmodifiableSortedSet(buttonsPressedInCar); } @Override public Set<Integer> getPlannedStops() { return Collections.unmodifiableSet(plannedStops); } @Override public ElevatorStepCounter getStepCounter() { return stepCounter; } @Override public boolean canGoFast(final double fromFloor, final int toFloor) { return elevatorProgramSupport.calculateDistance(fromFloor, toFloor) > SLOW_ONLY_DISTANCE; } @Override public void overwriteProgramStoppingOn(final SortedSet<Integer> floors) { if (!Objects.requireNonNull(floors).isEmpty() && !canSafelyStopOnFloor(floors.first())) { final String set = floors.stream() .map(getBuilding()::floor) .map(AbstractPlace::getName) .map(String::trim) .collect(Collectors.joining(", ")); final String going = plannedStops.stream() .map(getBuilding()::floor) .map(AbstractPlace::getName) .map(String::trim) .collect(Collectors.joining(", ")); throw new IllegalStateException("Elevator " + getName() + " - Cannot stop on floor " + set + ", as destinations floors are " + going + ". Keeping program as-is."); } plannedStops.clear(); if (floors.isEmpty()) { elevatorProgramSupport.programTravelToFloor(this, getFloorIndex(), this.getFloorIndex()); } else { elevatorProgramSupport.generateProgramForDestinations(this, floors); plannedStops.addAll(floors); } } @Override public void removeButtonPressOnArrival() { this.buttonsPressedInCar.remove((int) getFloorIndex()); this.plannedStops.remove((int) getFloorIndex()); this.justClosedDoor = true; } @Override public void setFloorIndex(final double floorIndex) { super.setFloorIndex(floorIndex); } @Override public void nextTurn(final int turnIndex) { this.population().forEach(p -> p.nextTurn(turnIndex)); elevatorProgramSupport.nextTurn(this); } @Override public void setAttitude(final Attitude attitude) { super.setAttitude(attitude); } @Override public ElevatorStatus getStatus() { return status; } public void setStatus(final ElevatorStatus elevatorStatus) { this.status = elevatorStatus; this.justClosedDoor = false; } @Override public boolean justClosedDoor() { return justClosedDoor; } @Override public boolean canMove() { return true; } @Override public boolean canSafelyStopOnFloor(final int floorIndex) { final Attitude movementNeeded = Attitude.forMovement(getFloorIndex(), floorIndex); if (oppositeDirection(movementNeeded)) { return false; } else if (!status.isMoving()) { return true; } else if (status.isMovingSlow()) { return !hasDoorOnFloor(floorIndex); } else { return elevatorProgramSupport.calculateDistance(getFloorIndex(), floorIndex) > SAFE_SLOW_DOWN_DISTANCE; } } @Override public boolean hasDoorOnFloor(final int floorIndex) { return elevatorProgramSupport.hasDoorOnFloor(getFloorIndex(), floorIndex); } @Override public boolean isAboveFloor(final int floorIndex) { return floorIndex < getFloorIndex(); } @Override public boolean isBelowFloor(final int floorIndex) { return floorIndex > getFloorIndex(); } private boolean oppositeDirection(final Attitude movementNeeded) { return getAttitude() != Attitude.CONSTANT && movementNeeded != Attitude.CONSTANT && getAttitude() != movementNeeded; } }
34.182353
115
0.667355
4c550e6aee58199893d25e5dbef680a00c5a3b71
459
package com.riis.common.rest.dto; import java.io.Serializable; import java.util.List; public class WorkflowResponseGroupDto implements Serializable { private static final long serialVersionUID = -843010430817009247L; private List<WorkflowResponseItemDto> items; public List<WorkflowResponseItemDto> getItems() { return items; } public void setItems(List<WorkflowResponseItemDto> items) { this.items = items; } }
21.857143
70
0.736383
bf7be9c0ecc33c11660bf2fbbda7c12396d349db
1,155
package aqours.codeiq.c3314.labo; public class Test01 { public static void main(String[] args) { try { main2(); } catch(Throwable e) { e.printStackTrace(); } } private static int[] al = new int[] { 1, 1, 2, 3, 5, 9, 15, 26, 45, 78, 135, 234, 406, 704, 1222, 2120, 3679, 6385, 11081, 19232, 33379, 57933, 100550, 174519, 302903, 525734, 912493, 1583775, 2748893, 4771144, }; private static void main2() { int[] a = al; for(int c = 0; c < 10; c++) { a = kaisa2(a); for(int v : a) { System.out.println("" + v); } System.out.println(""); } } private static int[] kaisa(int[] src) { int[] dest = new int[src.length]; dest[0] = src[0]; for(int index = 1; index < src.length; index++) { dest[index] = src[index] - src[index - 1]; } return dest; } private static int[] kaisa2(int[] src) { int[] dest = new int[src.length]; dest[0] = src[0]; dest[1] = src[1]; for(int index = 2; index < src.length; index++) { dest[index] = src[index] - src[index - 1] - src[index - 2]; } return dest; } }
14.085366
62
0.527273
1c70c43538a44b985ff0e290c68ed2bb24572eb8
7,162
package com.gempukku.swccgo.cards.set201.dark; import com.gempukku.swccgo.cards.AbstractNormalEffect; import com.gempukku.swccgo.cards.GameConditions; import com.gempukku.swccgo.cards.effects.usage.OncePerBattleEffect; import com.gempukku.swccgo.cards.effects.usage.OncePerGameEffect; import com.gempukku.swccgo.common.*; import com.gempukku.swccgo.filters.Filters; import com.gempukku.swccgo.game.PhysicalCard; import com.gempukku.swccgo.game.SwccgGame; import com.gempukku.swccgo.logic.TriggerConditions; import com.gempukku.swccgo.logic.actions.CancelCardActionBuilder; import com.gempukku.swccgo.logic.actions.RequiredGameTextTriggerAction; import com.gempukku.swccgo.logic.actions.TopLevelGameTextAction; import com.gempukku.swccgo.logic.effects.AddUntilEndOfBattleModifierEffect; import com.gempukku.swccgo.logic.effects.LoseForceEffect; import com.gempukku.swccgo.logic.effects.RetrieveCardIntoHandEffect; import com.gempukku.swccgo.logic.effects.choose.DeployCardFromReserveDeckEffect; import com.gempukku.swccgo.logic.modifiers.ModifierFlag; import com.gempukku.swccgo.logic.modifiers.SpecialFlagModifier; import com.gempukku.swccgo.logic.timing.Effect; import com.gempukku.swccgo.logic.timing.EffectResult; import java.util.Collections; import java.util.LinkedList; import java.util.List; /** * Set: Set 1 * Type: Effect * Title: Jabba's Haven */ public class Card201_031 extends AbstractNormalEffect { public Card201_031() { super(Side.DARK, 4, PlayCardZoneOption.YOUR_SIDE_OF_TABLE, "Jabba's Haven", Uniqueness.UNIQUE); setLore("Jabba has won the service of many of his guards and other henchbeings through games of chance."); setGameText("If a Jabba's Palace site on table, deploy on table. The Camp is canceled. May [download] Nal Hutta. Once per battle, may lose 1 Force; your battle destiny modifiers affect your total battle destiny instead. Once per game, may retrieve a non-[Maintenance] alien or [Independent] starship into hand. [Immune to Alter]"); addIcons(Icon.VIRTUAL_SET_1); addImmuneToCardTitle(Title.Alter); } @Override protected boolean checkGameTextDeployRequirements(String playerId, SwccgGame game, PhysicalCard self, PlayCardOptionId playCardOptionId, boolean asReact) { return GameConditions.canSpotLocation(game, Filters.Jabbas_Palace_site); } @Override protected List<RequiredGameTextTriggerAction> getGameTextRequiredBeforeTriggers(final SwccgGame game, Effect effect, final PhysicalCard self, int gameTextSourceCardId) { GameTextActionId gameTextActionId = GameTextActionId.OTHER_CARD_ACTION_1; // Check condition(s) if ((TriggerConditions.isPlayingCard(game, effect, Filters.The_Camp)) && GameConditions.canCancelCardBeingPlayed(game, self, effect)) { RequiredGameTextTriggerAction action = new RequiredGameTextTriggerAction(self, gameTextSourceCardId, gameTextActionId); // Build action using common utility CancelCardActionBuilder.buildCancelCardBeingPlayedAction(action, effect); return Collections.singletonList(action); } return null; } @Override protected List<RequiredGameTextTriggerAction> getGameTextRequiredAfterTriggers(SwccgGame game, final EffectResult effectResult, final PhysicalCard self, int gameTextSourceCardId) { GameTextActionId gameTextActionId = GameTextActionId.OTHER_CARD_ACTION_1; // Check condition(s) if (TriggerConditions.isTableChanged(game, effectResult) && GameConditions.canTargetToCancel(game, self, Filters.The_Camp)) { final RequiredGameTextTriggerAction action = new RequiredGameTextTriggerAction(self, gameTextSourceCardId, gameTextActionId); // Build action using common utility CancelCardActionBuilder.buildCancelCardAction(action, Filters.The_Camp, Title.The_Camp); return Collections.singletonList(action); } return null; } @Override protected List<TopLevelGameTextAction> getGameTextTopLevelActions(final String playerId, SwccgGame game, final PhysicalCard self, int gameTextSourceCardId) { List<TopLevelGameTextAction> actions = new LinkedList<TopLevelGameTextAction>(); GameTextActionId gameTextActionId = GameTextActionId.JABBAS_HAVEN__DOWNLOAD_NAL_HUTTA; // Check condition(s) if (GameConditions.canDeployCardFromReserveDeck(game, playerId, self, gameTextActionId, Title.Nal_Hutta)) { final TopLevelGameTextAction action = new TopLevelGameTextAction(self, gameTextSourceCardId, gameTextActionId); action.setText("Deploy Nal Hutta from Reserve Deck"); // Perform result(s) action.appendEffect( new DeployCardFromReserveDeckEffect(action, Filters.Nal_Hutta_system, true)); actions.add(action); } gameTextActionId = GameTextActionId.OTHER_CARD_ACTION_2; // Check condition(s) if (GameConditions.isOncePerBattle(game, self, playerId, gameTextSourceCardId, gameTextActionId)) { final TopLevelGameTextAction action = new TopLevelGameTextAction(self, gameTextSourceCardId, gameTextActionId); action.setText("Change your battle destiny modifiers"); action.setActionMsg("Make " + playerId + "'s battle destiny modifiers affect " + playerId + "'s total battle destiny instead"); // Update usage limit(s) action.appendUsage( new OncePerBattleEffect(action)); // Pay cost(s) action.appendCost( new LoseForceEffect(action, playerId, 1, true)); // Perform result(s) action.appendEffect( new AddUntilEndOfBattleModifierEffect(action, new SpecialFlagModifier(self, ModifierFlag.BATTLE_DESTINY_MODIFIERS_AFFECT_TOTAL_BATTLE_DESTINY_INSTEAD, playerId), "Makes " + playerId + "'s battle destiny modifiers affect " + playerId + "'s total battle destiny instead")); actions.add(action); } gameTextActionId = GameTextActionId.JABBAS_HAVEN__RETRIEVE_CARD_INTO_HAND; // Check condition(s) if (GameConditions.isOncePerGame(game, self, gameTextActionId) && GameConditions.hasLostPile(game, playerId)) { final TopLevelGameTextAction action = new TopLevelGameTextAction(self, gameTextSourceCardId, gameTextActionId); action.setText("Retrieve card into hand"); action.setActionMsg("Retrieve a non-[Maintenance] alien or [Independent] starship into hand"); // Update usage limit(s) action.appendUsage( new OncePerGameEffect(action)); // Perform result(s) action.appendEffect( new RetrieveCardIntoHandEffect(action, playerId, Filters.or(Filters.and(Filters.alien, Filters.not(Icon.MAINTENANCE)), Filters.and(Filters.starship, Icon.INDEPENDENT)))); actions.add(action); } return actions; } }
51.898551
339
0.724239
1b9882d21a20d9cc70cd8d91e99dc4c437e81913
8,595
package org.firstinspires.ftc.teamcode; import com.qualcomm.robotcore.eventloop.opmode.Autonomous; import org.firstinspires.ftc.robotcore.external.ClassFactory; import org.firstinspires.ftc.robotcore.external.Func; import org.firstinspires.ftc.robotcore.external.navigation.Acceleration; import org.firstinspires.ftc.robotcore.external.navigation.AngleUnit; import org.firstinspires.ftc.robotcore.external.navigation.AxesOrder; import org.firstinspires.ftc.robotcore.external.navigation.AxesReference; import org.firstinspires.ftc.robotcore.external.navigation.Orientation; import java.util.Locale; /* This program will go straight hit the capball and park the bot at the center vertex */ @Autonomous(name="D-Bot Crater marker test", group="XtremeV") public class DBotAuto4_test extends DBotBase { private static final String TFOD_MODEL_ASSET = "RoverRuckus.tflite"; private static final String LABEL_GOLD_MINERAL = "Gold Mineral"; private static final String LABEL_SILVER_MINERAL = "Silver Mineral"; private static final String CENTER_POSITION ="Center"; private static final String LEFT_POSITION ="Left"; private static final String RIGHT_POSITION ="Right"; // State used for updating telemetry private Orientation angles; private Acceleration gravity; private double headingResetValue; private String position; //private static final String VUFORIA_KEY = "AVVrDYb/////AAABmT0TlZXDYE3gpf/zMjQrOgACsYT0LcTPCkhjAmq0XO3HT0RdGx2eP+Lwumhftz4e/g28CBGg1HmaFfy5kW9ioO4UGDeokDyxRfqWjNQwKG3BanmjCXxMxACaJ7iom5J3o4ylWNmuiyxsK8n1fFf2dVsTUsvUI7aRxqTahnIqqRJRsGmxld18eHy/ZhHfIjOyifi4svZUQiput21/jAloTx0sTnnrpR1Y/xGOz+68sGuXIgLZHpAQSoZnXiczGKdahGXOg3n6dXlQPIiASE1kHp253CTwO40l1HHN083m4wYjP4FCl/9TH3tb0Wj/Ccmlhfz2omhnZQKOBe7RsIxRk+PuEGkIe5hCs/lV9+yf9iBm"; //private VuforiaLocalizer vuforia; //private TFObjectDetector tfod; @Override public void runOpMode() { robot.init(hardwareMap); //sleep(2000); initVuforia(); if (ClassFactory.getInstance().canCreateTFObjectDetector()) { initTfod(); } else { telemetry.addData("Sorry!", "This device is not compatible with TFOD"); telemetry.update(); } // Send telemetry message to signify robotrt waiting; telemetry.addData("Status", "Ready to run"); // telemetry.update(); // Wait for the game to start (driver presses PLAY) waitForStart(); this.headingResetValue = this.getAbsoluteHeading(); //position = getGoldPositionHardCode(); position = getGoldPosition(); sleep(200); latchUp(1.0,5.5); stopRobot(); sleep(50); //turn to the right 45 degree call turn_to_heading(45); //turn to the left 45 degree call turn_to_heading(0); //its relative to previous turn //to move forward 10 inches call move_forward(10,0.3); //to move back 10 inches call move_forward(10, 0, -0.3); //to move sideways to the right by 4 inches call move_sideways(90, 0.3, 4); //to move sideways to left by 4 inches call move_sideways(180, 0.3, 4) if (position.equals("Right")) removeRight(); else if (position.equals("Center")) removeCenter(); else if(position.equals("Left")) removeLeft(); else removeLeft(); // Start the logging of measured acceleration stopRobot(); } public void removeCenter() { move_right( 0.3, 6); turn_to_heading(90); sleep(50); move_forward( 0.40, 20); sleep(50); move_back( 0.40, 12); sleep(50); move_left(.3,40); sleep(50); turn_to_heading(315); sleep(50); goToCrater(); } public void removeLeft() { move_back(0.3,2); sleep(50); move_right(0.3,12); sleep(50); turn_to_heading(135); sleep(50); move_left(0.3,34); sleep(50); move_back(0.3,20); sleep(50); turn_to_heading(320); sleep(50); goToCrater(); } public void removeRight() { move_right(0.3, 2); sleep(5); //move_forward(1,0.3); move_forward(0.3,1); sleep(50); turn_to_heading(45); //move_sideways(90, 0.3, 40); sleep(50); move_forward(0.3,1.5); sleep(50); move_right( 0.3, 30); sleep(50); move_left( 0.3, 20); sleep(50); turn_to_heading(90); sleep(50); move_forward(0.3,4); sleep(50); move_left(.3,40); sleep(50); turn_to_heading(315); sleep(50); goToCrater(); } private void goToCrater() { move_sideways_by_range(90,0.3,3.5); sleep(50); move_forward(0.3,40); sleep(100); move_forward_by_range(0.3,10); sleep(50); move_right_by_range(0.3,3); sleep(50); markerDrop(); sleep(50); move_back(0.3,50); //move_backward_by_range(0.3,55); sleep(50); move_sideways_by_range(-90,0.3,6); sleep(50); turn_to_heading(135); move_left(0.3,3); sleep(50); //move_forward_by_range(0.3,20); move_forward(0.3,17); robot.AA.setPower(0.5); robot.AE.setPower(0.4); sleep(500); } void composeTelemetry() { // At the beginning of each telemetry update, grab a bunch of data // from the IMU that we will then display in separate lines. telemetry.addAction(new Runnable() { @Override public void run() { // Acquiring the angles is relatively expensive; we don't want // to do that in each of the three items that need that info, as that's // three times the necessary expense. angles = robot.imu.getAngularOrientation(AxesReference.INTRINSIC, AxesOrder.ZYX, AngleUnit.DEGREES); gravity = robot.imu.getGravity(); } }); telemetry.addLine() .addData("status", new Func<String>() { @Override public String value() { return robot.imu.getSystemStatus().toShortString(); } }) .addData("calib", new Func<String>() { @Override public String value() { return robot.imu.getCalibrationStatus().toString(); } }); telemetry.addLine() .addData("heading", new Func<String>() { @Override public String value() { return formatAngle(angles.angleUnit, angles.firstAngle); } }) .addData("roll", new Func<String>() { @Override public String value() { return formatAngle(angles.angleUnit, angles.secondAngle); } }) .addData("pitch", new Func<String>() { @Override public String value() { return formatAngle(angles.angleUnit, angles.thirdAngle); } }); telemetry.addLine() .addData("grvty", new Func<String>() { @Override public String value() { return gravity.toString(); } }) .addData("mag", new Func<String>() { @Override public String value() { return String.format(Locale.getDefault(), "%.3f", Math.sqrt(gravity.xAccel*gravity.xAccel + gravity.yAccel*gravity.yAccel + gravity.zAccel*gravity.zAccel)); } }); } String formatAngle(AngleUnit angleUnit, double angle) { return formatDegrees(AngleUnit.DEGREES.fromUnit(angleUnit, angle)); } String formatDegrees(double degrees){ return String.format(Locale.getDefault(), "%.1f", AngleUnit.DEGREES.normalize(degrees)); } private double getAbsoluteHeading() { return robot.imu.getAngularOrientation(AxesReference.INTRINSIC , AxesOrder.ZYX, AngleUnit.DEGREES).firstAngle; } private double getRelativeHeading() { return this.getAbsoluteHeading() - this.headingResetValue; } }
33.185328
431
0.585224
8b477dbfdb377db432475dec476d0822288c7735
446
package com.xx.shop.service; import com.xx.shop.common.ProductDetail; import com.xx.shop.dto.ProductPageDto; import com.xx.shop.entity.Product; import java.util.List; public interface ProductService { ProductPageDto queryProList(int pageSize, int pageIndex, String order, boolean isAsc); List<Product> queryListByCate(int pageSize, int pageIndex, int cateId, String order, boolean isAsc); ProductDetail getDetail(long proId); }
26.235294
104
0.780269
8ce7d5710a1d124c3115b4f7debdbe8c8f06cde9
609
package com.chenwt.admin.business.domain.entity; import lombok.Getter; import lombok.Setter; import org.springframework.data.annotation.CreatedDate; import javax.persistence.*; import java.util.Date; /** * @class:CustomerTeam * @campany:zkzj * @author:chenwt * @date:2019-05-17 14:50 * @description: */ @Entity @Table(name="customer_team") @Getter @Setter public class CustomerTeam { @Id @GeneratedValue(strategy= GenerationType.IDENTITY) private Long id; private Long leaderId; private Long customerId; private Integer level; @CreatedDate private Date createDate; }
19.03125
55
0.732348
fad997a418d92eb931dc70d6a65182ab3b0f7cae
3,435
package main.java.Chapter11.Multithreaded.Programming; import main.java.Chapter11.Multithreaded.Programming.Children.ExtendedThread; import main.java.Chapter11.Multithreaded.Programming.Children.RunnableThread; import static java.lang.Thread.NORM_PRIORITY; import static java.lang.Thread.currentThread; public class JavaThreads { /* Multithreading system in java is built upon the JavaThreads class and Runnable interface. Some methods defined in JavaThreads class 1. getName - Obtain a thread's name 2. getPriority - Obtain a thread's priority 3. isAlive - Determine if a thread is still running 4. join - Wait for a thread to terminate 5. run - Entry point for the thread 6. sleep - Suspend a thread for a period of time 7. notify - Wakes up a thread that called wait() on the same object 8. notifyAll = wakes up all threads that called wait() on the same object. 9. start - Start a thread by calling its run method. */ /*main method generates the main thread Child threads will be generated from main thread. main thread must typically be terminated last */ public static void main(String args[]){ // currentThread() returns a reference to the thread it was ran on Thread t = currentThread(); // will display Program is being executed on threadThread[main,5,main]. [name of thread, priority, group thread belongs too] System.out.println("Program is being executed on thread" + t); /* getState can return 1. BLOCKED - A thread that has suspended execution because it is waiting to acquire a lock 2. NEW - A thread that has not begun execution 3. RUNNABLE - A thread that is running will run when it is granted CPU 4. TERMINATE - A thread that has completed excecution 5. TIMED_WAITING - a thread that is put on hold for a certain period of time (Thread.sleep(1000) 6. WAITING - A thread that is waiting for some action to occur. */ System.out.println("Thread state is " + t.getState()); System.out.println("Thread is called " + t.getName()); System.out.println("Thread ID is " + t.getId()); System.out.println("Thread is alive: " + t.isAlive()); RunnableThread r = new RunnableThread(); ExtendedThread e = new ExtendedThread(); e.start(); r.startThread(); // priority can be set to 1 (least priority) to 10 (highest priority) e.setPriority(7); //NORM_PRIORITY sets thread priority to default value of 5 r.setThreadPriority(NORM_PRIORITY); System.out.println("ExtendedThread is alive: " + e.isAlive()); System.out.println("RunnableThread is alive: " + r.threadIsAlive()); try{ for (int i = 0; i < 5; i++ ){ System.out.println("Loop in " + t.getName() +" has run " + i + " times"); t.sleep( 700); } //wait for e and r threads to terminate. e.join(); r.joinThread(); System.out.println("ExtendedThread is alive: " + e.isAlive()); System.out.println("RunnableThread is alive: " + r.threadIsAlive()); } catch (InterruptedException i){ System.out.println("Main was interrupted"); } } }
48.380282
133
0.63115
80389806e36707e1ef7edad094f05cee61fa84d3
6,493
package org.cyclops.integratedtunnels; import com.google.common.collect.Lists; import net.minecraft.item.ItemGroup; import net.minecraftforge.api.distmarker.Dist; import net.minecraftforge.api.distmarker.OnlyIn; import net.minecraftforge.common.MinecraftForge; import net.minecraftforge.event.RegistryEvent; import net.minecraftforge.fml.common.Mod; import net.minecraftforge.fml.event.lifecycle.FMLCommonSetupEvent; import net.minecraftforge.fml.javafmlmod.FMLJavaModLoadingContext; import org.apache.logging.log4j.Level; import org.cyclops.cyclopscore.config.ConfigHandler; import org.cyclops.cyclopscore.infobook.IInfoBookRegistry; import org.cyclops.cyclopscore.init.ItemGroupMod; import org.cyclops.cyclopscore.init.ModBaseVersionable; import org.cyclops.cyclopscore.proxy.IClientProxy; import org.cyclops.cyclopscore.proxy.ICommonProxy; import org.cyclops.integrateddynamics.IntegratedDynamics; import org.cyclops.integrateddynamics.api.part.aspect.IAspect; import org.cyclops.integrateddynamics.core.part.aspect.AspectRegistry; import org.cyclops.integrateddynamics.infobook.OnTheDynamicsOfIntegrationBook; import org.cyclops.integratedtunnels.api.world.IBlockBreakHandlerRegistry; import org.cyclops.integratedtunnels.api.world.IBlockPlaceHandlerRegistry; import org.cyclops.integratedtunnels.capability.ingredient.TunnelIngredientComponentCapabilities; import org.cyclops.integratedtunnels.capability.network.FluidNetworkConfig; import org.cyclops.integratedtunnels.capability.network.ItemNetworkConfig; import org.cyclops.integratedtunnels.capability.network.TunnelNetworkCapabilityConstructors; import org.cyclops.integratedtunnels.core.part.ContainerInterfaceSettingsConfig; import org.cyclops.integratedtunnels.core.world.BlockBreakHandlerRegistry; import org.cyclops.integratedtunnels.core.world.BlockBreakHandlers; import org.cyclops.integratedtunnels.core.world.BlockBreakPlaceRegistry; import org.cyclops.integratedtunnels.core.world.BlockPlaceHandlers; import org.cyclops.integratedtunnels.item.ItemDummyPickAxeConfig; import org.cyclops.integratedtunnels.part.PartTypes; import org.cyclops.integratedtunnels.part.aspect.TunnelAspects; import org.cyclops.integratedtunnels.part.aspect.listproxy.TunnelValueTypeListProxyFactories; import org.cyclops.integratedtunnels.proxy.ClientProxy; import org.cyclops.integratedtunnels.proxy.CommonProxy; /** * The main mod class of this mod. * @author rubensworks (aka kroeserr) * */ @Mod(Reference.MOD_ID) public class IntegratedTunnels extends ModBaseVersionable<IntegratedTunnels> { /** * The unique instance of this mod. */ public static IntegratedTunnels _instance; public IntegratedTunnels() { super(Reference.MOD_ID, (instance) -> _instance = instance); // Registries getRegistryManager().addRegistry(IBlockBreakHandlerRegistry.class, BlockBreakHandlerRegistry.getInstance()); getRegistryManager().addRegistry(IBlockPlaceHandlerRegistry.class, BlockBreakPlaceRegistry.getInstance()); FMLJavaModLoadingContext.get().getModEventBus().addListener(this::onRegistriesCreate); } public void onRegistriesCreate(RegistryEvent.NewRegistry event) { TunnelIngredientComponentCapabilities.load(); TunnelAspects.load(); PartTypes.load(); BlockBreakHandlers.load(); BlockPlaceHandlers.load(); } @Override protected void setup(FMLCommonSetupEvent event) { super.setup(event); MinecraftForge.EVENT_BUS.register(new TunnelNetworkCapabilityConstructors()); // Initialize info book IntegratedDynamics._instance.getRegistryManager().getRegistry(IInfoBookRegistry.class) .registerSection( OnTheDynamicsOfIntegrationBook.getInstance(), "info_book.integrateddynamics.manual", "/data/" + Reference.MOD_ID + "/info/tunnels_info.xml"); IntegratedDynamics._instance.getRegistryManager().getRegistry(IInfoBookRegistry.class) .registerSection( OnTheDynamicsOfIntegrationBook.getInstance(), "info_book.integrateddynamics.tutorials", "/data/" + Reference.MOD_ID + "/info/tunnels_tutorials.xml"); // Register value list proxies TunnelValueTypeListProxyFactories.load(); // Inject aspects into ID parts AspectRegistry.getInstance().register(org.cyclops.integrateddynamics.core.part.PartTypes.NETWORK_READER, Lists.newArrayList( TunnelAspects.Read.Item.LONG_COUNT, TunnelAspects.Read.Item.LONG_COUNTMAX, TunnelAspects.Read.Item.LIST_ITEMSTACKS, TunnelAspects.Read.Item.OPERATOR_GETITEMCOUNT, TunnelAspects.Read.Item.INTEGER_INTERFACES, TunnelAspects.Read.Fluid.LONG_COUNT, TunnelAspects.Read.Fluid.LONG_COUNTMAX, TunnelAspects.Read.Fluid.LIST_FLUIDSTACKS, TunnelAspects.Read.Fluid.OPERATOR_GETFLUIDCOUNT, TunnelAspects.Read.Fluid.INTEGER_INTERFACES )); } @Override public ItemGroup constructDefaultItemGroup() { return new ItemGroupMod(this, () -> RegistryEntries.ITEM_PART_INTERFACE); } @Override public void onConfigsRegister(ConfigHandler configHandler) { super.onConfigsRegister(configHandler); configHandler.addConfigurable(new GeneralConfig()); configHandler.addConfigurable(new ItemNetworkConfig()); configHandler.addConfigurable(new FluidNetworkConfig()); configHandler.addConfigurable(new ItemDummyPickAxeConfig()); configHandler.addConfigurable(new ContainerInterfaceSettingsConfig()); } @Override @OnlyIn(Dist.CLIENT) protected IClientProxy constructClientProxy() { return new ClientProxy(); } @Override protected ICommonProxy constructCommonProxy() { return new CommonProxy(); } /** * Log a new info message for this mod. * @param message The message to show. */ public static void clog(String message) { clog(Level.INFO, message); } /** * Log a new message of the given level for this mod. * @param level The level in which the message must be shown. * @param message The message to show. */ public static void clog(Level level, String message) { IntegratedTunnels._instance.getLoggerHelper().log(level, message); } }
41.890323
132
0.749884
76aaf000b3a6f4436e7ade1028fff3f58c706481
16,928
/* * Copyright (c) 2010-2016 William Bittle http://www.dyn4j.org/ * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, are permitted * provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, this list of conditions * and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright notice, this list of conditions * and the following disclaimer in the documentation and/or other materials provided with the * distribution. * * Neither the name of dyn4j nor the names of its contributors may be used to endorse or * promote products derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER * IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package org.dyn4j.collision; import junit.framework.TestCase; import org.dyn4j.collision.narrowphase.Gjk; import org.dyn4j.collision.narrowphase.Raycast; import org.dyn4j.geometry.Capsule; import org.dyn4j.geometry.Circle; import org.dyn4j.geometry.Convex; import org.dyn4j.geometry.Ellipse; import org.dyn4j.geometry.Geometry; import org.dyn4j.geometry.HalfEllipse; import org.dyn4j.geometry.Polygon; import org.dyn4j.geometry.Ray; import org.dyn4j.geometry.Rectangle; import org.dyn4j.geometry.Segment; import org.dyn4j.geometry.Slice; import org.dyn4j.geometry.Transform; import org.dyn4j.geometry.Triangle; import org.dyn4j.geometry.Vector2; import org.junit.Test; /** * Test cases for the {@link Gjk#raycast(Ray, double, Convex, Transform, Raycast)} * method. * @author William Bittle * @version 3.4.0 * @since 2.0.0 */ public class GjkRaycastTest { /** * Tests a successful raycast against a {@link Rectangle}. */ @Test public void raycastRectangle() { Ray ray = new Ray(new Vector2(), new Vector2(1.0, 0.0)); Gjk gjk = new Gjk(); Rectangle r = Geometry.createRectangle(1.0, 1.0); Transform t = new Transform(); t.translate(2.0, 0.0); Raycast raycast = new Raycast(); // successful test boolean collision = gjk.raycast(ray, 0.0, r, t, raycast); TestCase.assertTrue(collision); Vector2 point = raycast.getPoint(); Vector2 normal = raycast.getNormal(); TestCase.assertEquals(1.500, point.x, 1.0e-3); TestCase.assertEquals(0.000, point.y, 1.0e-3); TestCase.assertEquals(-1.000, normal.x, 1.0e-3); TestCase.assertEquals(0.000, normal.y, 1.0e-3); TestCase.assertEquals(1.500, raycast.getDistance(), 1.0e-3); raycast.clear(); // length test TestCase.assertFalse(gjk.raycast(ray, 1.4, r, t, raycast)); TestCase.assertTrue(gjk.raycast(ray, 1.6, r, t, raycast)); // opposite direction test ray.getDirectionVector().negate(); TestCase.assertFalse(gjk.raycast(ray, 0.0, r, t, raycast)); // non-intersection case ray.getDirectionVector().set(new Vector2(1.0, 1.0)); TestCase.assertFalse(gjk.raycast(ray, 0.0, r, t, raycast)); // start at center case (or any point within the convex shape) ray.getStart().set(t.getTransformed(r.getCenter())); TestCase.assertFalse(gjk.raycast(ray, 0.0, r, t, raycast)); } /** * Tests a successful raycast against a {@link Polygon}. */ @Test public void raycastPolygon() { Vector2 d = new Vector2(1.0, 1.0); d.normalize(); Ray ray = new Ray(d); Gjk gjk = new Gjk(); Convex c = Geometry.createUnitCirclePolygon(5, 1.0); Transform t = new Transform(); t.translate(2.0, 1.0); Raycast raycast = new Raycast(); // successful test boolean collision = gjk.raycast(ray, 0.0, c, t, raycast); TestCase.assertTrue(collision); Vector2 point = raycast.getPoint(); Vector2 normal = raycast.getNormal(); TestCase.assertEquals(1.190, point.x, 1.0e-3); TestCase.assertEquals(1.190, point.y, 1.0e-3); TestCase.assertEquals(-1.000, normal.x, 1.0e-3); TestCase.assertEquals(0.000, normal.y, 1.0e-3); TestCase.assertEquals(1.684, raycast.getDistance(), 1.0e-3); raycast.clear(); // length test TestCase.assertFalse(gjk.raycast(ray, 1.4, c, t, raycast)); TestCase.assertTrue(gjk.raycast(ray, 1.7, c, t, raycast)); // opposite direction test ray.getDirectionVector().negate(); TestCase.assertFalse(gjk.raycast(ray, 0.0, c, t, raycast)); // non-intersection case ray.getDirectionVector().set(new Vector2(1.0, 2.0)); TestCase.assertFalse(gjk.raycast(ray, 0.0, c, t, raycast)); // start at center case (or any point within the convex shape) ray.getStart().set(t.getTransformed(c.getCenter())); TestCase.assertFalse(gjk.raycast(ray, 0.0, c, t, raycast)); } /** * Tests a successful raycast against a {@link Triangle}. */ @Test public void raycastTriangle() { Vector2 d = new Vector2(2.0, 1.0); d.normalize(); Ray ray = new Ray(d); Gjk gjk = new Gjk(); Convex c = Geometry.createEquilateralTriangle(1.0); Transform t = new Transform(); t.translate(2.0, 1.0); Raycast raycast = new Raycast(); // successful test boolean collision = gjk.raycast(ray, 0.0, c, t, raycast); TestCase.assertTrue(collision); Vector2 point = raycast.getPoint(); Vector2 normal = raycast.getNormal(); TestCase.assertEquals(1.458, point.x, 1.0e-3); TestCase.assertEquals(0.729, point.y, 1.0e-3); TestCase.assertEquals(-0.866, normal.x, 1.0e-3); TestCase.assertEquals(0.5, normal.y, 1.0e-3); TestCase.assertEquals(1.631, raycast.getDistance(), 1.0e-3); raycast.clear(); // length test TestCase.assertFalse(gjk.raycast(ray, 1.4, c, t, raycast)); TestCase.assertTrue(gjk.raycast(ray, 1.7, c, t, raycast)); // opposite direction test ray.getDirectionVector().negate(); TestCase.assertFalse(gjk.raycast(ray, 0.0, c, t, raycast)); // non-intersection case ray.getDirectionVector().set(new Vector2(1.0, 2.0)); TestCase.assertFalse(gjk.raycast(ray, 0.0, c, t, raycast)); // start at center case (or any point within the convex shape) ray.getStart().set(t.getTransformed(c.getCenter())); TestCase.assertFalse(gjk.raycast(ray, 0.0, c, t, raycast)); } /** * Tests a successful raycast against a {@link Circle}. */ @Test public void raycastCircle() { Vector2 d = new Vector2(2.0, 1.0); Ray ray = new Ray(d); Gjk gjk = new Gjk(); Convex c = Geometry.createCircle(0.5); Transform t = new Transform(); t.translate(2.0, 0.5); Raycast raycast = new Raycast(); // successful test boolean collision = gjk.raycast(ray, 0.0, c, t, raycast); TestCase.assertTrue(collision); Vector2 point = raycast.getPoint(); Vector2 normal = raycast.getNormal(); TestCase.assertEquals(1.599, point.x, 1.0e-3); TestCase.assertEquals(0.799, point.y, 1.0e-3); TestCase.assertEquals(-0.800, normal.x, 1.0e-3); TestCase.assertEquals(0.599, normal.y, 1.0e-3); TestCase.assertEquals(1.788, raycast.getDistance(), 1.0e-3); raycast.clear(); // length test TestCase.assertFalse(gjk.raycast(ray, 1.7, c, t, raycast)); TestCase.assertTrue(gjk.raycast(ray, 1.8, c, t, raycast)); // opposite direction test ray.getDirectionVector().negate(); TestCase.assertFalse(gjk.raycast(ray, 0.0, c, t, raycast)); // non-intersection case ray.getDirectionVector().set(new Vector2(1.0, 2.0)); TestCase.assertFalse(gjk.raycast(ray, 0.0, c, t, raycast)); // start at center case (or any point within the convex shape) ray.getStart().set(t.getTransformed(c.getCenter())); TestCase.assertFalse(gjk.raycast(ray, 0.0, c, t, raycast)); } /** * Tests a successful raycast against a {@link Ellipse}. * @since 3.1.5 */ @Test public void raycastEllipse() { Vector2 d = new Vector2(2.0, 1.0); d.normalize(); Ray ray = new Ray(d); Gjk gjk = new Gjk(); Convex c = new Ellipse(1.0, 0.5); Transform t = new Transform(); t.translate(2.1, 1.0); Raycast raycast = new Raycast(); // successful test boolean collision = gjk.raycast(ray, 0.0, c, t, raycast); TestCase.assertTrue(collision); Vector2 point = raycast.getPoint(); Vector2 normal = raycast.getNormal(); TestCase.assertEquals( 1.699, point.x, 1.0e-3); TestCase.assertEquals( 0.849, point.y, 1.0e-3); TestCase.assertEquals(-0.548, normal.x, 1.0e-3); TestCase.assertEquals(-0.836, normal.y, 1.0e-3); TestCase.assertEquals( 1.900, raycast.getDistance(), 1.0e-3); raycast.clear(); // length test TestCase.assertFalse(gjk.raycast(ray, 1.7, c, t, raycast)); TestCase.assertTrue(gjk.raycast(ray, 1.95, c, t, raycast)); // opposite direction test ray.getDirectionVector().negate(); TestCase.assertFalse(gjk.raycast(ray, 0.0, c, t, raycast)); // non-intersection case ray.getDirectionVector().set(new Vector2(1.0, 2.0)); TestCase.assertFalse(gjk.raycast(ray, 0.0, c, t, raycast)); // start at center case (or any point within the convex shape) ray.getStart().set(t.getTransformed(c.getCenter())); TestCase.assertFalse(gjk.raycast(ray, 0.0, c, t, raycast)); } /** * Tests a successful raycast against a {@link HalfEllipse}. * @since 3.1.5 */ @Test public void raycastHalfEllipse() { Ray ray = new Ray(new Vector2(Math.toRadians(130))); Gjk gjk = new Gjk(); Convex c = new HalfEllipse(0.8, 0.25); Transform t = new Transform(); t.translate(-1.0, 0.8); Raycast raycast = new Raycast(); // successful test boolean collision = gjk.raycast(ray, 0.0, c, t, raycast); TestCase.assertTrue(collision); Vector2 point = raycast.getPoint(); Vector2 normal = raycast.getNormal(); TestCase.assertEquals(-0.671, point.x, 1.0e-3); TestCase.assertEquals( 0.800, point.y, 1.0e-3); TestCase.assertEquals( 0.000, normal.x, 1.0e-3); TestCase.assertEquals(-1.000, normal.y, 1.0e-3); TestCase.assertEquals( 1.044, raycast.getDistance(), 1.0e-3); raycast.clear(); // length test TestCase.assertFalse(gjk.raycast(ray, 0.7, c, t, raycast)); TestCase.assertTrue(gjk.raycast(ray, 1.2, c, t, raycast)); // opposite direction test ray.getDirectionVector().negate(); TestCase.assertFalse(gjk.raycast(ray, 0.0, c, t, raycast)); // non-intersection case ray.getDirectionVector().set(new Vector2(Math.toRadians(120))); TestCase.assertFalse(gjk.raycast(ray, 0.0, c, t, raycast)); // start at center case (or any point within the convex shape) ray.getStart().set(t.getTransformed(c.getCenter())); TestCase.assertFalse(gjk.raycast(ray, 0.0, c, t, raycast)); } /** * Tests a successful raycast against a {@link Slice}. * @since 3.1.5 */ @Test public void raycastSlice() { Ray ray = new Ray(new Vector2(Math.toRadians(-30))); Gjk gjk = new Gjk(); Convex c = new Slice(0.5, Math.toRadians(60)); Transform t = new Transform(); t.translate(1.0, -0.8); Raycast raycast = new Raycast(); // successful test boolean collision = gjk.raycast(ray, 0.0, c, t, raycast); TestCase.assertTrue(collision); Vector2 point = raycast.getPoint(); Vector2 normal = raycast.getNormal(); TestCase.assertEquals( 1.192, point.x, 1.0e-3); TestCase.assertEquals(-0.688, point.y, 1.0e-3); TestCase.assertEquals(-0.500, normal.x, 1.0e-3); TestCase.assertEquals( 0.866, normal.y, 1.0e-3); TestCase.assertEquals( 1.377, raycast.getDistance(), 1.0e-3); raycast.clear(); // length test TestCase.assertFalse(gjk.raycast(ray, 1.3, c, t, raycast)); TestCase.assertTrue(gjk.raycast(ray, 1.5, c, t, raycast)); // opposite direction test ray.getDirectionVector().negate(); TestCase.assertFalse(gjk.raycast(ray, 0.0, c, t, raycast)); // non-intersection case ray.getDirectionVector().set(new Vector2(Math.toRadians(-45))); TestCase.assertFalse(gjk.raycast(ray, 0.0, c, t, raycast)); // start at center case (or any point within the convex shape) ray.getStart().set(t.getTransformed(c.getCenter())); TestCase.assertFalse(gjk.raycast(ray, 0.0, c, t, raycast)); } /** * Tests a successful raycast against a {@link Capsule}. * @since 3.1.5 */ @Test public void raycastCapsule() { Ray ray = new Ray(new Vector2(Math.toRadians(-130))); Gjk gjk = new Gjk(); Convex c = new Capsule(1.0, 0.5); Transform t = new Transform(); t.translate(-1.0, -0.8); Raycast raycast = new Raycast(); // successful test boolean collision = gjk.raycast(ray, 0.0, c, t, raycast); TestCase.assertTrue(collision); Vector2 point = raycast.getPoint(); Vector2 normal = raycast.getNormal(); TestCase.assertEquals(-0.547, point.x, 1.0e-3); TestCase.assertEquals(-0.652, point.y, 1.0e-3); TestCase.assertEquals( 0.816, normal.x, 1.0e-3); TestCase.assertEquals( 0.577, normal.y, 1.0e-3); TestCase.assertEquals( 0.852, raycast.getDistance(), 1.0e-3); raycast.clear(); // length test TestCase.assertFalse(gjk.raycast(ray, 0.7, c, t, raycast)); TestCase.assertTrue(gjk.raycast(ray, 0.9, c, t, raycast)); // opposite direction test ray.getDirectionVector().negate(); TestCase.assertFalse(gjk.raycast(ray, 0.0, c, t, raycast)); // non-intersection case ray.getDirectionVector().set(new Vector2(Math.toRadians(-115))); TestCase.assertFalse(gjk.raycast(ray, 0.0, c, t, raycast)); // start at center case (or any point within the convex shape) ray.getStart().set(t.getTransformed(c.getCenter())); TestCase.assertFalse(gjk.raycast(ray, 0.0, c, t, raycast)); } /** * Tests a successful raycast against a {@link Segment}. */ @Test public void raycastSegment() { Vector2 d = new Vector2(2.0, 1.0); d.normalize(); Ray ray = new Ray(d); Gjk gjk = new Gjk(); Convex c = Geometry.createHorizontalSegment(1.0); Transform t = new Transform(); t.translate(2.0, 1.0); Raycast raycast = new Raycast(); // successful test boolean collision = gjk.raycast(ray, 0.0, c, t, raycast); TestCase.assertTrue(collision); Vector2 point = raycast.getPoint(); Vector2 normal = raycast.getNormal(); TestCase.assertEquals(2.000, point.x, 1.0e-3); TestCase.assertEquals(1.000, point.y, 1.0e-3); TestCase.assertEquals(0.000, normal.x, 1.0e-3); TestCase.assertEquals(-1.000, normal.y, 1.0e-3); TestCase.assertEquals(2.236, raycast.getDistance(), 1.0e-3); raycast.clear(); // length test TestCase.assertFalse(gjk.raycast(ray, 2.2, c, t, raycast)); TestCase.assertTrue(gjk.raycast(ray, 2.4, c, t, raycast)); // opposite direction test ray.getDirectionVector().negate(); TestCase.assertFalse(gjk.raycast(ray, 0.0, c, t, raycast)); // non-intersection case ray.getDirectionVector().set(new Vector2(1.0, 2.0)); TestCase.assertFalse(gjk.raycast(ray, 0.0, c, t, raycast)); // start at center case (or any point within the convex shape) ray.getStart().set(t.getTransformed(c.getCenter())); TestCase.assertFalse(gjk.raycast(ray, 0.0, c, t, raycast)); } /** * Tests the raycast method using a parallel segment. */ @Test public void raycastParallelSegment() { Vector2 d = new Vector2(1.0, 0.0); d.normalize(); Ray ray = new Ray(d); Gjk gjk = new Gjk(); Convex c = Geometry.createHorizontalSegment(1.0); Transform t = new Transform(); t.translate(2.0, 0.0); Raycast raycast = new Raycast(); // successful test boolean collision = gjk.raycast(ray, 0.0, c, t, raycast); TestCase.assertTrue(collision); Vector2 point = raycast.getPoint(); Vector2 normal = raycast.getNormal(); TestCase.assertEquals(1.500, point.x, 1.0e-3); TestCase.assertEquals(0.000, point.y, 1.0e-3); TestCase.assertEquals(-1.000, normal.x, 1.0e-3); TestCase.assertEquals(0.000, normal.y, 1.0e-3); TestCase.assertEquals(1.500, raycast.getDistance(), 1.0e-3); raycast.clear(); // length test TestCase.assertFalse(gjk.raycast(ray, 1.4, c, t, raycast)); TestCase.assertTrue(gjk.raycast(ray, 2.0, c, t, raycast)); // opposite direction test ray.getDirectionVector().negate(); TestCase.assertFalse(gjk.raycast(ray, 0.0, c, t, raycast)); // non-intersection case ray.getStart().set(new Vector2(0.0, 1.0)); TestCase.assertFalse(gjk.raycast(ray, 0.0, c, t, raycast)); // start at center case (or any point within the convex shape) ray.getStart().set(t.getTransformed(c.getCenter())); TestCase.assertFalse(gjk.raycast(ray, 0.0, c, t, raycast)); } }
33.257367
105
0.685846
65bd0b943ddb1f8f2e8608bd9e87faca8899fb13
9,118
/* * Copyright (c) 2018 Google Inc. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ /* * @test * @run junit DelegatingIteratorForEachRemaining */ import org.junit.Assert; import org.junit.Test; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.Iterator; import java.util.Map; import java.util.Objects; import java.util.Set; import java.util.Spliterator; import java.util.function.BiConsumer; import java.util.function.BiFunction; import java.util.function.Consumer; import java.util.function.Function; import java.util.function.Predicate; import java.util.stream.Stream; public class DelegatingIteratorForEachRemaining { static abstract class ForwardingIterator<E> implements Iterator<E> { private final Iterator<E> delegate; protected ForwardingIterator(Iterator<E> delegate) { this.delegate = Objects.requireNonNull(delegate); } @Override public boolean hasNext() { return delegate.hasNext(); } @Override public E next() { return delegate.next(); } @Override public void remove() { delegate.remove(); } @Override public void forEachRemaining(Consumer<? super E> action) { delegate.forEachRemaining(action); } } static final class ThrowingIterator<E> extends ForwardingIterator<E> { public ThrowingIterator(Iterator<E> delegate) { super(delegate); } @Override public void forEachRemaining(Consumer<? super E> action) { throw new UnsupportedOperationException(); } } static abstract class ForwardingSet<E> implements Set<E> { private final Set<E> delegate; protected ForwardingSet(Set<E> delegate) { this.delegate = Objects.requireNonNull(delegate); } @Override public int size() { return delegate.size(); } @Override public boolean isEmpty() { return delegate.isEmpty(); } @Override public boolean contains(Object o) { return delegate.contains(o); } @Override public Iterator<E> iterator() { return delegate.iterator(); } @Override public Object[] toArray() { return delegate.toArray(); } @Override public <T> T[] toArray( T[] ts) { return delegate.toArray(ts); } @Override public boolean add(E e) { return delegate.add(e); } @Override public boolean remove(Object o) { return delegate.remove(o); } @Override public boolean containsAll( Collection<?> c) { return delegate.containsAll(c); } @Override public boolean addAll( Collection<? extends E> c) { return delegate.addAll(c); } @Override public boolean retainAll( Collection<?> c) { return delegate.retainAll(c); } @Override public boolean removeAll( Collection<?> c) { return delegate.removeAll(c); } @Override public void clear() { delegate.clear(); } @Override public boolean equals(Object o) { return delegate.equals(o); } @Override public int hashCode() { return delegate.hashCode(); } @Override public Spliterator<E> spliterator() { return delegate.spliterator(); } @Override public boolean removeIf(Predicate<? super E> filter) { return delegate.removeIf(filter); } @Override public Stream<E> stream() { return delegate.stream(); } @Override public Stream<E> parallelStream() { return delegate.parallelStream(); } @Override public void forEach(Consumer<? super E> action) { delegate.forEach(action); } } static class ThrowingSet<E> extends ForwardingSet<E> { public ThrowingSet(Set<E> delegate) { super(delegate); } @Override public ThrowingIterator<E> iterator() { return new ThrowingIterator<>(super.iterator()); } } static abstract class ForwardingMap<K, V> implements Map<K, V> { private final Map<K, V> delegate; public ForwardingMap(Map<K, V> delegate) { this.delegate = delegate; } @Override public int size() { return delegate.size(); } @Override public boolean isEmpty() { return delegate.isEmpty(); } @Override public boolean containsKey(Object o) { return delegate.containsKey(o); } @Override public boolean containsValue(Object o) { return delegate.containsValue(o); } @Override public V get(Object o) { return delegate.get(o); } @Override public V put(K k, V v) { return delegate.put(k, v); } @Override public V remove(Object o) { return delegate.remove(o); } @Override public void putAll(Map<? extends K, ? extends V> map) { delegate.putAll(map); } @Override public void clear() { delegate.clear(); } @Override public Set<K> keySet() { return delegate.keySet(); } @Override public Collection<V> values() { return delegate.values(); } @Override public Set<Entry<K, V>> entrySet() { return delegate.entrySet(); } @Override public boolean equals(Object o) { return delegate.equals(o); } @Override public int hashCode() { return delegate.hashCode(); } @Override public V getOrDefault(Object key, V defaultValue) { return delegate.getOrDefault(key, defaultValue); } @Override public void forEach(BiConsumer<? super K, ? super V> action) { delegate.forEach(action); } @Override public void replaceAll(BiFunction<? super K, ? super V, ? extends V> function) { delegate.replaceAll(function); } @Override public V putIfAbsent(K key, V value) { return delegate.putIfAbsent(key, value); } @Override public boolean remove(Object key, Object value) { return delegate.remove(key, value); } @Override public boolean replace(K key, V oldValue, V newValue) { return delegate.replace(key, oldValue, newValue); } @Override public V replace(K key, V value) { return delegate.replace(key, value); } @Override public V computeIfAbsent(K key, Function<? super K, ? extends V> mappingFunction) { return delegate.computeIfAbsent(key, mappingFunction); } @Override public V computeIfPresent(K key, BiFunction<? super K, ? super V, ? extends V> remappingFunction) { return delegate.computeIfPresent(key, remappingFunction); } @Override public V compute(K key, BiFunction<? super K, ? super V, ? extends V> remappingFunction) { return delegate.compute(key, remappingFunction); } @Override public V merge(K key, V value, BiFunction<? super V, ? super V, ? extends V> remappingFunction) { return delegate.merge(key, value, remappingFunction); } } static class ThrowingMap<K, V> extends ForwardingMap<K, V> { public ThrowingMap(Map<K, V> delegate) { super(delegate); } @Override public ThrowingSet<Entry<K, V>> entrySet() { return new ThrowingSet<>(super.entrySet()); } @Override public Set<K> keySet() { return new ThrowingSet(super.keySet()); } } static<E> void assertThrowingIterator(Iterator<E> iterator) { try { iterator.forEachRemaining((entry) -> {}); Assert.fail(); } catch (UnsupportedOperationException expected) { } } private static Map<String, Object> map() { Map<String, Object> map = new HashMap<>(); map.put("name", "Bill"); map.put("age", 23); return new ThrowingMap<>(map); } @Test public void testUnwrapped() { assertThrowingIterator(map().entrySet().iterator()); assertThrowingIterator(map().keySet().iterator()); } @Test public void test_unmodifiableMap_entrySet() { assertThrowingIterator(Collections.unmodifiableMap(map()).entrySet().iterator()); } @Test public void test_checkedMap_entrySet() { assertThrowingIterator(Collections.checkedMap(map(), String.class, Object.class).entrySet().iterator()); } @Test public void test_entrySet_checkedSet() { Set<Map.Entry<String, Object>> entrySet = map().entrySet(); Class clazz = entrySet.iterator().next().getClass(); assertThrowingIterator(Collections.checkedSet(entrySet, clazz).iterator()); } }
45.819095
177
0.669664
2d367afa7e5dfd6fb3c0ec7dc454894677d452ff
537
package estudos.aula44.figuras; public class Cubo extends Figura3D{ private double lado; public Cubo() { super.setTipo("Figura3D"); } public double getLado() { return lado; } public void setLado(double lado) { this.lado = lado; } @Override public double calcularVolume() { return Math.pow(lado, 3); } @Override public double calcularArea() { return 6*Math.pow(lado, 2); } @Override public String toString() { return super.toString()+"\nArea: "+calcularArea()+"\nVolume: "+calcularVolume(); } }
15.342857
82
0.670391
a1b63a671bc4faf42ae3d20bead95d7c809e0f2a
696
package json_product_shop.json1.utils; import javax.validation.ConstraintViolation; import javax.validation.Validation; import javax.validation.Validator; import java.util.Set; public class ValidationUtilImpl implements ValidationUtil { private Validator validator; public ValidationUtilImpl(){ this.validator = Validation.buildDefaultValidatorFactory() .getValidator(); } @Override public <T> boolean isValid(T entity) { return this.validator.validate(entity).isEmpty(); } @Override public <T> Set<ConstraintViolation<T>> violations(T entity) { return this.validator.validate(entity); } }
26.769231
67
0.691092
c79099058079953ee2c5e5501a9dbaa97f87c4d4
2,336
package com.github.sandor_balazs.sentiment_analysis.parser; import java.io.File; import java.io.IOException; import javax.xml.bind.JAXBContext; import javax.xml.bind.JAXBException; import javax.xml.bind.Marshaller; import javax.xml.bind.UnmarshallerHandler; import javax.xml.parsers.ParserConfigurationException; import javax.xml.parsers.SAXParserFactory; import org.xml.sax.InputSource; import org.xml.sax.SAXException; import org.xml.sax.XMLFilter; import com.github.sandor_balazs.sentiment_analysis.util.NamespaceFilter; public abstract class AbstractXmlParser { public static Object unmarshal(String path, String contextPath, String namespace) throws JAXBException, SAXException, ParserConfigurationException, IOException { UnmarshallerHandler unmarshallerHandler = JAXBContext .newInstance(contextPath).createUnmarshaller() .getUnmarshallerHandler(); XMLFilter xmlFilter = new NamespaceFilter(namespace); xmlFilter.setParent( SAXParserFactory.newInstance().newSAXParser().getXMLReader()); xmlFilter.setContentHandler(unmarshallerHandler); xmlFilter.parse(new InputSource(Thread.currentThread() .getContextClassLoader().getResource(path).getPath())); return unmarshallerHandler.getResult(); } public static Object unmarshal(InputSource inputSource, String contextPath, String namespace) throws JAXBException, SAXException, ParserConfigurationException, IOException { UnmarshallerHandler unmarshallerHandler = JAXBContext .newInstance(contextPath).createUnmarshaller() .getUnmarshallerHandler(); XMLFilter xmlFilter = new NamespaceFilter(namespace); xmlFilter.setParent( SAXParserFactory.newInstance().newSAXParser().getXMLReader()); xmlFilter.setContentHandler(unmarshallerHandler); xmlFilter.parse(inputSource); return unmarshallerHandler.getResult(); } public static void marshal(Object object, File file, String contextPath) throws JAXBException { JAXBContext context = JAXBContext.newInstance(contextPath); Marshaller marshaller = context.createMarshaller(); marshaller.marshal(object, file); } }
41.714286
85
0.725171
02d26fc5c90a1c949ed04ce4e7f05cf62916469a
702
package com.google.firebase.auth; import android.support.annotation.NonNull; import android.support.annotation.Nullable; public final class FirebaseAuthUserCollisionException extends FirebaseAuthException { private AuthCredential zzlzd; public FirebaseAuthUserCollisionException(@NonNull String str, @NonNull String str2) { super(str, str2); this.zzlzd = null; } public FirebaseAuthUserCollisionException(@NonNull String str, @NonNull String str2, @NonNull AuthCredential authCredential) { super(str, str2); this.zzlzd = authCredential; } @Nullable public final AuthCredential getUpdatedCredential() { return this.zzlzd; } }
29.25
130
0.735043
c79834096edddf4c7309cbb7b0416e57ea756f85
314
package com.github.diegopacheco.sandbox.java.netflixoss.karyon.poc.common; import io.netty.buffer.ByteBuf; import io.reactivex.netty.protocol.http.server.HttpServerRequest; import rx.Observable; public interface AuthenticationService { Observable<Boolean> authenticate(HttpServerRequest<ByteBuf> request); }
31.4
74
0.83121
22982694ce8bf94ed22a297e372e58bc6a8dcbe5
964
package com.gruelbox.transactionoutbox.acceptance; import com.gruelbox.transactionoutbox.Dialect; import java.time.Duration; import org.testcontainers.containers.JdbcDatabaseContainer; import org.testcontainers.containers.MySQLContainer; import org.testcontainers.junit.jupiter.Container; import org.testcontainers.junit.jupiter.Testcontainers; @SuppressWarnings("WeakerAccess") @Testcontainers class TestMySql5 extends AbstractAcceptanceTest { @Container @SuppressWarnings("rawtypes") private static final JdbcDatabaseContainer container = new MySQLContainer<>("mysql:5").withStartupTimeout(Duration.ofHours(1)); @Override protected ConnectionDetails connectionDetails() { return ConnectionDetails.builder() .dialect(Dialect.MY_SQL_5) .driverClassName("com.mysql.cj.jdbc.Driver") .url(container.getJdbcUrl()) .user(container.getUsername()) .password(container.getPassword()) .build(); } }
32.133333
78
0.770747
db9f974c95d91edd7e41f24ae960f35b716c861c
1,548
package com.redhat.service.bridge.manager.actions.connectors; import java.util.Map; import javax.enterprise.context.ApplicationScoped; import org.eclipse.microprofile.config.inject.ConfigProperty; import com.redhat.service.bridge.actions.ActionTransformer; import com.redhat.service.bridge.actions.kafkatopic.KafkaTopicAction; import com.redhat.service.bridge.infra.models.actions.BaseAction; @ApplicationScoped public class SlackActionTransformer implements ActionTransformer { @ConfigProperty(name = "managed-connectors.topic-name") String topicName; @Override public BaseAction transform(BaseAction action, String bridgeId, String customerId, String processorId) { BaseAction resolvedAction = new BaseAction(); Map<String, String> newParameters = resolvedAction.getParameters(); newParameters.putAll(action.getParameters()); resolvedAction.setType(KafkaTopicAction.TYPE); resolvedAction.setName(action.getName()); newParameters.put(KafkaTopicAction.TOPIC_PARAM, generateKafkaTopicName(processorId)); return resolvedAction; } // Currently, it's just a fixed topic for testing purposes. // When https://issues.redhat.com/browse/MGDOBR-168 is ready, we can generate one for connector // once we use a single topic for every connector there will be no need of having a different // one per connector https://issues.redhat.com/browse/MGDSTRM-5977 private String generateKafkaTopicName(String processorId) { return topicName; } }
36
108
0.763566
9ab79a3bafd6e1058788e463773cdf625c8549bb
1,304
/** * Copyright (c) 2018, salesforce.com, inc. * All rights reserved. * SPDX-License-Identifier: BSD-3-Clause * For full license text, see the LICENSE file in the repo root or https://opensource.org/licenses/BSD-3-Clause */ package com.demandware.carbonj.service.engine; import com.demandware.carbonj.service.events.CarbonjEvent; class BlackListedQueryEvent implements CarbonjEvent { private final String target; private String from; private String until; private String now; private final String type = "blacklisted"; private final long time; public BlackListedQueryEvent(String target, String from, String until, String now) { this.target = target; this.from = from; this.until = until; this.now = now; time = System.currentTimeMillis(); } public BlackListedQueryEvent(String target) { this.target = target; time = System.currentTimeMillis(); } public String getTarget() { return target; } public String getFrom() { return from; } public String getUntil() { return until; } public String getNow() { return now; } public String getType() { return type; } public long getTime() { return time; } }
23.285714
111
0.641871
5707dfa7937b1ad9d58cf5306643f8022c57d1d8
5,806
package seedu.address.model.booking; import static java.time.temporal.ChronoUnit.DAYS; import static seedu.address.commons.util.CollectionUtil.requireAllNonNull; import java.time.LocalDate; import java.util.Objects; public class Booking { private static Integer nextAvailableId; // Identity fields private final Integer id; private final Integer roomId; private final Integer personId; private final LocalDate startDate; private final LocalDate endDate; private final boolean isActive; /** * Every field must be present and not null. Used for creating a new Booking with a unique id. */ public Booking(Integer roomId, Integer personId, LocalDate startDate, LocalDate endDate, boolean isActive) { requireAllNonNull(roomId, personId, startDate, endDate); this.roomId = roomId; this.personId = personId; this.startDate = startDate; this.endDate = endDate; this.isActive = isActive; this.id = nextAvailableId; nextAvailableId += 1; } /** * Every field must be present and not null. Used for creating a Booking with an existing id. */ public Booking(Integer roomId, Integer personId, LocalDate startDate, LocalDate endDate, boolean isActive, Integer id) { requireAllNonNull(roomId, personId, startDate, endDate, id); this.roomId = roomId; this.personId = personId; this.startDate = startDate; this.endDate = endDate; this.isActive = isActive; this.id = id; } /** * Sets next available id to be used */ public static void setNextAvailableId(Integer id) { Booking.nextAvailableId = id; } public Integer getId() { return id; } public Integer getRoomId() { return roomId; } public Integer getPersonId() { return personId; } public LocalDate getStartDate() { return startDate; } public LocalDate getEndDate() { return endDate; } public boolean isActive() { return isActive; } /** * Returns the number of the nights of a booking. */ public int getDuration() { long noOfDaysBetween = DAYS.between(startDate, endDate); int duration = (int) noOfDaysBetween; return duration; } /** * Returns true if two booking conflict with each other. * * @param otherBooking Another Booking object. * @return a boolean. */ public boolean hasConflict(Booking otherBooking) { if (!otherBooking.getRoomId().equals(getRoomId())) { return false; } if (isActive() == false || otherBooking.isActive() == false) { return false; } LocalDate start = getStartDate(); LocalDate end = getEndDate(); LocalDate otherBookingStart = otherBooking.getStartDate(); LocalDate otherBookingEnd = otherBooking.getEndDate(); return otherBookingStart.isBefore(end) && otherBookingEnd.isAfter(start); } /** * Returns true if Booking has overlap with given {@code startDate} and {@code endDate} */ public boolean hasOverlap(LocalDate startDate, LocalDate endDate) { if (this.startDate.isEqual(startDate) || this.endDate.isEqual(endDate) || this.endDate.isEqual(startDate) || this.startDate.isEqual(endDate)) { return true; } return isActive && startDate.isBefore(this.endDate) && endDate.isAfter(this.startDate); } /** * Returns true if the room id, person id, start date, end date are the same. * @param otherBooking the other booking to compare. */ public boolean isSameBooking(Booking otherBooking) { if (otherBooking.equals(this)) { return true; } return otherBooking.getRoomId().equals(getRoomId()) && otherBooking.getPersonId().equals(getPersonId()) && otherBooking.getStartDate().equals(getStartDate()) && otherBooking.getEndDate().equals(getEndDate()) && otherBooking.isActive() == isActive(); } /** * Returns true if both bookings have the same identity and data fields. * This defines a stronger notion of equality between two persons. */ @Override public boolean equals(Object other) { if (other == this) { return true; } if (!(other instanceof Booking)) { return false; } Booking otherBooking = (Booking) other; return otherBooking.getId().equals(getId()) && otherBooking.getRoomId().equals(getRoomId()) && otherBooking.getPersonId().equals(getPersonId()) && otherBooking.getStartDate().equals(getStartDate()) && otherBooking.getEndDate().equals(getEndDate()) && otherBooking.isActive() == isActive(); } @Override public int hashCode() { // use this method for custom fields hashing instead of implementing your own return Objects.hash(roomId, personId, startDate, endDate, isActive); } @Override public String toString() { final StringBuilder builder = new StringBuilder(); builder.append("Id: ") .append(getId()) .append(" Room Id: ") .append(getRoomId()) .append(" Person Id: ") .append(getPersonId()) .append(" Start Date: ") .append(getStartDate()) .append(" End Date: ") .append(getEndDate()) .append(" Archived: ") .append(!isActive()); return builder.toString(); } }
30.557895
112
0.604203
9e897731532250046569ccd9dd89631d21368af7
528
/* * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. */ package com.microsoft.azuretools.authmanage.srvpri.rest; import com.microsoft.azuretools.sdkmanage.AzureManagerBase; public class GraphRestHelper extends RestHelperBase { public GraphRestHelper(AzureManagerBase preAccessTokenAzureManager, String tenantId) { setRequestFactory(new GraphRequestFactory(preAccessTokenAzureManager, tenantId)); } }
33
95
0.799242
13c89578a916f0c2713f92256454538eae03c4fd
53,050
package org.openbaton.nse.api; import org.apache.tomcat.util.bcel.classfile.Constant; import org.openbaton.catalogue.mano.common.Ip; import org.openbaton.catalogue.mano.descriptor.InternalVirtualLink; import org.openbaton.catalogue.mano.descriptor.VNFComponent; import org.openbaton.catalogue.mano.descriptor.VirtualDeploymentUnit; import org.openbaton.catalogue.mano.record.NetworkServiceRecord; import org.openbaton.catalogue.mano.record.VNFCInstance; import org.openbaton.catalogue.mano.record.VirtualNetworkFunctionRecord; import org.openbaton.catalogue.nfvo.viminstances.BaseVimInstance; import org.openbaton.catalogue.nfvo.viminstances.OpenstackVimInstance; import org.openbaton.catalogue.nfvo.networks.BaseNetwork; import org.openbaton.catalogue.security.Project; import org.openbaton.nse.adapters.openstack.NeutronQoSExecutor; import org.openbaton.nse.adapters.openstack.NeutronQoSHandler; import org.openbaton.nse.monitoring.ZabbixChecker; import org.openbaton.nse.monitoring.ZabbixPluginCaller; import org.openbaton.nse.utils.api.NetworkStatistic; import org.openbaton.nse.utils.openstack.*; import org.openbaton.nse.utils.openbaton.OpenBatonTools; import org.openbaton.nse.properties.NfvoProperties; import org.openbaton.nse.properties.NseProperties; import org.openbaton.nse.utils.api.NetworkOverview; import org.openbaton.sdk.NFVORequestor; import org.openbaton.sdk.NfvoRequestorBuilder; import org.openbaton.sdk.api.exception.SDKException; import org.openstack4j.api.OSClient; import org.openstack4j.model.compute.Server; import org.openstack4j.model.network.Port; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.CrossOrigin; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; import java.io.FileNotFoundException; import java.lang.reflect.Array; import java.util.*; /** * Created by lgr on 3/1/18. */ @RestController public class Api { private static Logger logger = LoggerFactory.getLogger(Api.class); private NetworkOverview osOverview = new NetworkOverview(); private NetworkStatistic osStatistic = new NetworkStatistic(); //private ArrayList<VimInstance> vim_list = new ArrayList<>(); private final List<BaseVimInstance> vim_list = Collections.synchronizedList(new ArrayList<>()); //private ArrayList<VirtualNetworkFunctionRecord> vnfr_list = new ArrayList<>(); private final List<VirtualNetworkFunctionRecord> vnfr_list = Collections.synchronizedList(new ArrayList<>()); @SuppressWarnings("unused") @Autowired private ZabbixChecker zabbixChecker; @SuppressWarnings("unused") @Autowired private NeutronQoSHandler neutron_handler; @SuppressWarnings("unused") @Autowired private OpenStackTools osTools; @SuppressWarnings("unused") @Autowired private OpenBatonTools obTools; private HashMap<Integer, String> vim_hashes = new HashMap<>(); private HashMap<Integer, ArrayList<String>> int_vim_map = new HashMap<>(); @SuppressWarnings("unused") @Autowired private NfvoProperties nfvo_configuration; @SuppressWarnings("unused") @Autowired private NseProperties nse_configuration; public List<VirtualNetworkFunctionRecord> getVnfr_list() { return vnfr_list; } public List<BaseVimInstance> getVim_list() { return vim_list; } // Function so signal the API that there is the need to pull latest data from a VIM instance public void notifyChange(String external_vim_id) { for (int int_vim_id : int_vim_map.keySet()) { ArrayList<String> ext_vims = int_vim_map.get(int_vim_id); if (ext_vims.contains(external_vim_id)) { //logger.debug("Generating new hash for : " + int_vim_id); vim_hashes.put(int_vim_id, UUID.randomUUID().toString()); this.updateNetworkOverview(); return; } } //logger.warn("Did not found " + external_vim_id + " in : " + int_vim_map.toString()); } @CrossOrigin(origins = "*") @RequestMapping("/overview") @SuppressWarnings("unused") public NetworkOverview getOverview() { updateNetworkOverview(); return this.osOverview; } @CrossOrigin(origins = "*") @RequestMapping("/statistics") @SuppressWarnings("unused") public NetworkStatistic getStatistic( @RequestParam(value = "history", defaultValue = "1") String history) { Integer length = Integer.parseInt(history); return zabbixChecker.getStatistic(); } // Method to be called by the NSE-GUI to apply bandwidth limitations directly on a whole network @CrossOrigin(origins = "*") @RequestMapping("/assign-net-policy") @SuppressWarnings("unused") public void assignNetPolicy( @RequestParam(value = "project", defaultValue = "project_id") String project, @RequestParam(value = "vim", defaultValue = "vim_id") String vim, @RequestParam(value = "net", defaultValue = "net_id") String net, @RequestParam(value = "policy", defaultValue = "no_policy") String policy) { logger.debug( "Received assign QoS policy request for vim : " + vim + " in project " + project + " network : " + net + " policy : " + policy); synchronized (vim_list) { for (BaseVimInstance v : vim_list) { if (v.getId().equals(vim)) { if (OpenstackVimInstance.class.isInstance(v)) { OpenstackVimInstance osV = (OpenstackVimInstance) v; NFVORequestor nfvoRequestor = obTools.getNFVORequestor( nfvo_configuration.getIp(), nfvo_configuration.getPort(), project, nse_configuration.getService().getKey()); OSClient tmp_os = osTools.getOSClient(osV); String token = osTools.getAuthToken(tmp_os, osV); String neutron_access = osTools.getNeutronEndpoint(osV); Map<String, String> creds = obTools.getDatacenterCredentials(nfvoRequestor, v.getId()); creds.put("neutron", neutron_access); NeutronQoSExecutor neutron_executor = new NeutronQoSExecutor(neutron_handler, token, v, creds); neutron_executor.assignQoSPolicyToNetwork(net, policy); } else { logger.warn("VIM type " + v.getType() + " not supported yet"); } } } this.notifyChange(vim); } } // Method to be called by the NSE-GUI to apply bandwidth limitations directly on a port @CrossOrigin(origins = "*") @RequestMapping("/assign-port-policy") @SuppressWarnings("unused") public void assignPortPolicy( @RequestParam(value = "project", defaultValue = "project_id") String project, @RequestParam(value = "vim", defaultValue = "vim_id") String vim, @RequestParam(value = "port", defaultValue = "port_id") String port, @RequestParam(value = "policy", defaultValue = "no_policy") String policy) { logger.debug( "Received assign QoS policy request for vim : " + vim + " in project " + project + " port : " + port + " policy : " + policy); synchronized (vim_list) { for (BaseVimInstance v : vim_list) { if (v.getId().equals(vim)) { if (OpenstackVimInstance.class.isInstance(v)) { OpenstackVimInstance osV = (OpenstackVimInstance) v; NFVORequestor nfvoRequestor = obTools.getNFVORequestor( nfvo_configuration.getIp(), nfvo_configuration.getPort(), project, nse_configuration.getService().getKey()); OSClient tmp_os = osTools.getOSClient(osV); String token = osTools.getAuthToken(tmp_os, osV); String neutron_access = osTools.getNeutronEndpoint(osV); Map<String, String> creds = obTools.getDatacenterCredentials(nfvoRequestor, v.getId()); creds.put("neutron", neutron_access); NeutronQoSExecutor neutron_executor = new NeutronQoSExecutor(neutron_handler, token, v, creds); neutron_executor.assignQoSPolicyToPort(port, policy); } else { logger.warn("VIM type " + v.getType() + " not supported yet"); } } } this.notifyChange(vim); } } // Method to be called by the NSE-GUI to delete QoS policies @CrossOrigin(origins = "*") @RequestMapping("/policy-delete") @SuppressWarnings("unused") public void deletePolicy( @RequestParam(value = "project", defaultValue = "project_id") String project, @RequestParam(value = "id", defaultValue = "policy_id") String id, @RequestParam(value = "vim", defaultValue = "vim_id") String vim) { logger.debug( "Received delete QoS policy request for vim : " + vim + " in project " + project + " policy : " + id); synchronized (vim_list) { for (BaseVimInstance v : vim_list) { if (v.getId().equals(vim)) { if (OpenstackVimInstance.class.isInstance(v)) { OpenstackVimInstance osV = (OpenstackVimInstance) v; NFVORequestor nfvoRequestor = obTools.getNFVORequestor( nfvo_configuration.getIp(), nfvo_configuration.getPort(), project, nse_configuration.getService().getKey()); OSClient tmp_os = osTools.getOSClient(osV); String token = osTools.getAuthToken(tmp_os, osV); String neutron_access = osTools.getNeutronEndpoint(osV); Map<String, String> creds = obTools.getDatacenterCredentials(nfvoRequestor, v.getId()); creds.put("neutron", neutron_access); NeutronQoSExecutor neutron_executor = new NeutronQoSExecutor(neutron_handler, token, v, creds); neutron_executor.deleteQoSPolicy(id); } else { logger.warn("VIM type " + v.getType() + " not supported yet"); } } } this.notifyChange(vim); } } // Method to be called by the NSE-GUI to delete QoS policies @CrossOrigin(origins = "*") @RequestMapping("/bandwidth-rule-delete") @SuppressWarnings("unused") public void deleteBandwidthRule( @RequestParam(value = "project", defaultValue = "project_id") String project, @RequestParam(value = "policy_id", defaultValue = "policy_id") String policy_id, @RequestParam(value = "rule_id", defaultValue = "rule_id") String rule_id, @RequestParam(value = "vim", defaultValue = "vim_id") String vim) { logger.debug( "Received delete bandwidth rule request for vim : " + vim + " in project " + project + " policy : " + policy_id + " rule : " + rule_id); synchronized (vim_list) { for (BaseVimInstance v : vim_list) { if (v.getId().equals(vim)) { if (OpenstackVimInstance.class.isInstance(v)) { OpenstackVimInstance osV = (OpenstackVimInstance) v; NFVORequestor nfvoRequestor = obTools.getNFVORequestor( nfvo_configuration.getIp(), nfvo_configuration.getPort(), project, nse_configuration.getService().getKey()); OSClient tmp_os = osTools.getOSClient(osV); String token = osTools.getAuthToken(tmp_os, osV); String neutron_access = osTools.getNeutronEndpoint(osV); Map<String, String> creds = obTools.getDatacenterCredentials(nfvoRequestor, v.getId()); creds.put("neutron", neutron_access); NeutronQoSExecutor neutron_executor = new NeutronQoSExecutor(neutron_handler, token, v, creds); neutron_executor.deleteBandwidthRule(rule_id, policy_id); } else { logger.warn("VIM type " + v.getType() + " not supported yet"); } } } this.notifyChange(vim); } } // Method to be called by the NSE-GUI to create QoS policies @CrossOrigin(origins = "*") @RequestMapping("/minimum-bandwidth-rule-create") @SuppressWarnings("unused") public void createMinimumBandwidthRule( @RequestParam(value = "project", defaultValue = "project_id") String project, @RequestParam(value = "id", defaultValue = "policy_id") String id, @RequestParam(value = "type", defaultValue = "minimum_bandwidth_rule") String type, @RequestParam(value = "kbps", defaultValue = "0") String kbps, @RequestParam(value = "direction", defaultValue = "egress") String direction, @RequestParam(value = "vim", defaultValue = "vim_id") String vim) { if (!kbps.matches("[0-9]+")) { logger.error( "Cannot create bandwidth rule with max_kbps : \"" + kbps + "\" please enter a valid number"); return; } logger.debug( "Received create minimum bandwidth rule request for vim : " + vim + " in project " + project); logger.debug( "Policy id : " + id + " type : " + type + " min_kbps : " + kbps); OpenStackMinimumBandwidthRule rule = new OpenStackMinimumBandwidthRule(); rule.setType(type); rule.setMin_kbps(new Integer(kbps)); rule.setDirection(direction); synchronized (vim_list) { for (BaseVimInstance v : vim_list) { if (v.getId().equals(vim)) { if (OpenstackVimInstance.class.isInstance(v)) { OpenstackVimInstance osV = (OpenstackVimInstance) v; NFVORequestor nfvoRequestor = obTools.getNFVORequestor( nfvo_configuration.getIp(), nfvo_configuration.getPort(), project, nse_configuration.getService().getKey()); OSClient tmp_os = osTools.getOSClient(osV); String token = osTools.getAuthToken(tmp_os, osV); String neutron_access = osTools.getNeutronEndpoint(osV); Map<String, String> creds = obTools.getDatacenterCredentials(nfvoRequestor, v.getId()); creds.put("neutron", neutron_access); NeutronQoSExecutor neutron_executor = new NeutronQoSExecutor(neutron_handler, token, v, creds); neutron_executor.createBandwidthRule(rule, id); } else { logger.warn("VIM type " + v.getType() + " not supported yet"); } } } this.notifyChange(vim); } } // Method to be called by the NSE-GUI to create QoS policies @CrossOrigin(origins = "*") @RequestMapping("/bandwidth-rule-create") @SuppressWarnings("unused") public void createBandwidthRule( @RequestParam(value = "project", defaultValue = "project_id") String project, @RequestParam(value = "id", defaultValue = "policy_id") String id, @RequestParam(value = "type", defaultValue = "bandwidth_limit_rule") String type, @RequestParam(value = "burst", defaultValue = "0") String burst, @RequestParam(value = "kbps", defaultValue = "0") String kbps, @RequestParam(value = "direction", defaultValue = "egress") String direction, @RequestParam(value = "vim", defaultValue = "vim_id") String vim) { if (!burst.matches("[0-9]+")) { logger.error( "Cannot create bandwidth rule with max_kbps : \"" + burst + "\" please enter a valid number"); return; } if (!kbps.matches("[0-9]+")) { logger.error( "Cannot create bandwidth rule with max_kbps : \"" + kbps + "\" please enter a valid number"); return; } logger.debug( "Received create bandwidth rule request for vim : " + vim + " in project " + project); logger.debug( "Policy id : " + id + " type : " + type + " max_kbps : " + kbps + " burst : " + burst); OpenStackBandwidthRule rule = new OpenStackBandwidthRule(); rule.setMax_burst_kbps(new Integer(burst)); rule.setType(type); rule.setMax_kbps(new Integer(kbps)); rule.setDirection(direction); synchronized (vim_list) { for (BaseVimInstance v : vim_list) { if (v.getId().equals(vim)) { if (OpenstackVimInstance.class.isInstance(v)) { OpenstackVimInstance osV = (OpenstackVimInstance) v; NFVORequestor nfvoRequestor = obTools.getNFVORequestor( nfvo_configuration.getIp(), nfvo_configuration.getPort(), project, nse_configuration.getService().getKey()); OSClient tmp_os = osTools.getOSClient(osV); String token = osTools.getAuthToken(tmp_os, osV); String neutron_access = osTools.getNeutronEndpoint(osV); Map<String, String> creds = obTools.getDatacenterCredentials(nfvoRequestor, v.getId()); creds.put("neutron", neutron_access); NeutronQoSExecutor neutron_executor = new NeutronQoSExecutor(neutron_handler, token, v, creds); neutron_executor.createBandwidthRule(rule, id); } else { logger.warn("VIM type " + v.getType() + " not supported yet"); } } } this.notifyChange(vim); } } // Method to be called by the NSE-GUI to create QoS policies @CrossOrigin(origins = "*") @RequestMapping("/policy-create") @SuppressWarnings("unused") public void createPolicy( @RequestParam(value = "project", defaultValue = "project_id") String project, @RequestParam(value = "name", defaultValue = "name") String name, @RequestParam(value = "type", defaultValue = "bandwidth_limit_rule") String type, @RequestParam(value = "burst", defaultValue = "0") String burst, @RequestParam(value = "kbps", defaultValue = "0") String kbps, @RequestParam(value = "vim", defaultValue = "vim_id") String vim) { if (!burst.matches("[0-9]+")) { logger.error( "Cannot create QoS policy with max_burst_kbps : \"" + burst + "\" please enter a valid number"); return; } if (!kbps.matches("[0-9]+")) { logger.error( "Cannot create QoS policy with max_kbps : \"" + kbps + "\" please enter a valid number"); return; } logger.debug("Received create QoS policy request for vim : " + vim + " in project " + project); logger.debug( "Name : " + name + " type : " + type + " max_kbps : " + kbps + " burst : " + burst); OpenStackQoSPolicy policy = new OpenStackQoSPolicy(); policy.setName(name); ArrayList<OpenStackBandwidthRule> rules = new ArrayList<>(); rules.add(new OpenStackBandwidthRule(burst, kbps, type)); policy.setRules(rules); synchronized (vim_list) { for (BaseVimInstance v : vim_list) { if (v.getId().equals(vim)) { if (OpenstackVimInstance.class.isInstance(v)) { OpenstackVimInstance osV = (OpenstackVimInstance) v; NFVORequestor nfvoRequestor = obTools.getNFVORequestor( nfvo_configuration.getIp(), nfvo_configuration.getPort(), project, nse_configuration.getService().getKey()); OSClient tmp_os = osTools.getOSClient(osV); String token = osTools.getAuthToken(tmp_os, osV); String neutron_access = osTools.getNeutronEndpoint(osV); Map<String, String> creds = obTools.getDatacenterCredentials(nfvoRequestor, v.getId()); creds.put("neutron", neutron_access); NeutronQoSExecutor neutron_executor = new NeutronQoSExecutor(neutron_handler, token, v, creds); neutron_executor.createQoSPolicy(policy); } else { logger.warn("VIM type " + v.getType() + " not supported yet"); } } } this.notifyChange(vim); } } // Method to be called by the NSE-GUI to list networks @CrossOrigin(origins = "*") @RequestMapping("/list-ports") @SuppressWarnings("unused") public ArrayList<OpenStackPort> listPorts( @RequestParam(value = "project", defaultValue = "project_id") String project, @RequestParam(value = "vim", defaultValue = "vim_id") String vim) { logger.debug("Received port list request for vim : " + vim + " in project " + project); ArrayList<OpenStackPort> port_list = new ArrayList<>(); synchronized (vim_list) { for (BaseVimInstance v : vim_list) { if (v.getId().equals(vim)) { if (OpenstackVimInstance.class.isInstance(v)) { OpenstackVimInstance osV = (OpenstackVimInstance) v; NFVORequestor nfvoRequestor = obTools.getNFVORequestor( nfvo_configuration.getIp(), nfvo_configuration.getPort(), project, nse_configuration.getService().getKey()); OSClient tmp_os = osTools.getOSClient(osV); String token = osTools.getAuthToken(tmp_os, osV); String neutron_access = osTools.getNeutronEndpoint(osV); Map<String, String> creds = obTools.getDatacenterCredentials(nfvoRequestor, v.getId()); creds.put("neutron", neutron_access); NeutronQoSExecutor neutron_executor = new NeutronQoSExecutor(neutron_handler, token, v, creds); port_list = neutron_executor.listPorts(); } else { logger.warn("VIM type " + v.getType() + " not supported yet"); } } } return port_list; } } // Method to be called by the NSE-GUI to list networks @CrossOrigin(origins = "*") @RequestMapping("/list-networks") @SuppressWarnings("unused") public ArrayList<OpenStackNetwork> listNetworks( @RequestParam(value = "project", defaultValue = "project_id") String project, @RequestParam(value = "vim", defaultValue = "vim_id") String vim) { logger.debug("Received network list request for vim : " + vim + " in project " + project); ArrayList<OpenStackNetwork> net_list = new ArrayList<>(); synchronized (vim_list) { for (BaseVimInstance v : vim_list) { if (v.getId().equals(vim)) { if (OpenstackVimInstance.class.isInstance(v)) { OpenstackVimInstance osV = (OpenstackVimInstance) v; NFVORequestor nfvoRequestor = obTools.getNFVORequestor( nfvo_configuration.getIp(), nfvo_configuration.getPort(), project, nse_configuration.getService().getKey()); OSClient tmp_os = osTools.getOSClient(osV); String token = osTools.getAuthToken(tmp_os, osV); String neutron_access = osTools.getNeutronEndpoint(osV); Map<String, String> creds = obTools.getDatacenterCredentials(nfvoRequestor, v.getId()); creds.put("neutron", neutron_access); NeutronQoSExecutor neutron_executor = new NeutronQoSExecutor(neutron_handler, token, v, creds); net_list = neutron_executor.listNetworks(); } else { logger.warn("VIM type " + v.getType() + " not supported yet"); } } } return net_list; } } // Method to be called by the NSE-GUI to list QoS policies @CrossOrigin(origins = "*") @RequestMapping("/list-qos-policies") @SuppressWarnings("unused") public ArrayList<OpenStackQoSPolicy> listQoSPolicies( @RequestParam(value = "project", defaultValue = "project_id") String project, @RequestParam(value = "vim", defaultValue = "vim_id") String vim) { logger.debug("Received list QoS policy list for vim : " + vim + " in project " + project); ArrayList<OpenStackQoSPolicy> qos_policy_list = new ArrayList<>(); synchronized (vim_list) { for (BaseVimInstance v : vim_list) { if (v.getId().equals(vim)) { if (OpenstackVimInstance.class.isInstance(v)) { OpenstackVimInstance osV = (OpenstackVimInstance) v; NFVORequestor nfvoRequestor = obTools.getNFVORequestor( nfvo_configuration.getIp(), nfvo_configuration.getPort(), project, nse_configuration.getService().getKey()); OSClient tmp_os = osTools.getOSClient(osV); String token = osTools.getAuthToken(tmp_os, osV); String neutron_access = osTools.getNeutronEndpoint(osV); Map<String, String> creds = obTools.getDatacenterCredentials(nfvoRequestor, v.getId()); creds.put("neutron", neutron_access); NeutronQoSExecutor neutron_executor = new NeutronQoSExecutor(neutron_handler, token, v, creds); qos_policy_list = neutron_executor.getNeutronQosRules(); } else { logger.warn("VIM type " + v.getType() + " not supported yet"); } } } return qos_policy_list; } } // Method to be called by the NSE-GUI to scale out @CrossOrigin(origins = "*") @RequestMapping("/scale-out") @SuppressWarnings("unused") public void scaleOut( @RequestParam(value = "project", defaultValue = "project_id") String project_id, @RequestParam(value = "vnfr", defaultValue = "vnfr_id") String vnfr_id) { logger.debug( "Received SCALE out request for vnfr " + vnfr_id + " belonging to project " + project_id); try { NFVORequestor nfvoRequestor = obTools.getNFVORequestor( nfvo_configuration.getIp(), nfvo_configuration.getPort(), project_id, nse_configuration.getService().getKey()); synchronized (vnfr_list) { for (VirtualNetworkFunctionRecord vnfr : vnfr_list) { if (vnfr.getId().equals(vnfr_id)) { boolean scaled = false; for (VirtualDeploymentUnit vdu : vnfr.getVdu()) { if (scaled) break; if (vdu.getVnfc_instance().size() < vdu.getScale_in_out() && (vdu.getVnfc().iterator().hasNext())) { VNFComponent vnfComponent = vdu.getVnfc().iterator().next(); nfvoRequestor .getNetworkServiceRecordAgent() .createVNFCInstance( vnfr.getParent_ns_id(), vnfr.getId(), vnfComponent, new ArrayList<>(vdu.getVimInstanceName())); scaled = true; } } return; } } } } catch (SDKException e) { logger.error("Problem instantiating NFVORequestor"); } //catch (FileNotFoundException e) { //logger.error("Problem scaling"); //} } // Method to be called by the NSE-GUI to scale in @CrossOrigin(origins = "*") @RequestMapping("/scale-in") @SuppressWarnings("unused") public void scaleIn( @RequestParam(value = "project", defaultValue = "project_id") String project_id, @RequestParam(value = "vnfci", defaultValue = "vnfci_hostname") String vnfci_hostname, @RequestParam(value = "vnfr", defaultValue = "vnfr_id") String vnfr_id) { logger.debug( "Received SCALE in request for vnfr " + vnfr_id + " belonging to project " + project_id); try { NFVORequestor nfvoRequestor = obTools.getNFVORequestor( nfvo_configuration.getIp(), nfvo_configuration.getPort(), project_id, nse_configuration.getService().getKey()); synchronized (vnfr_list) { for (VirtualNetworkFunctionRecord vnfr : vnfr_list) { if (vnfr.getId().equals(vnfr_id)) { boolean scaled = false; for (VirtualDeploymentUnit vdu : vnfr.getVdu()) { if (scaled) break; Set<VNFCInstance> vnfcInstancesToRemove = new HashSet<>(); for (VNFCInstance vnfcInstance : vdu.getVnfc_instance()) { if (vnfcInstance.getState() == null || vnfcInstance.getState().toLowerCase().equals("active")) { vnfcInstancesToRemove.add(vnfcInstance); } } if (vnfcInstancesToRemove.size() > 1 && vnfcInstancesToRemove.iterator().hasNext()) { // If no specific vnfci id to remove has been set use the default way and remove a random one.. VNFCInstance vnfcInstance_remove = null; if (vnfci_hostname.equals("vnfci_hostname")) { vnfcInstance_remove = vnfcInstancesToRemove.iterator().next(); } else { for (VNFCInstance currVnfci : vnfcInstancesToRemove) { if (currVnfci.getHostname().equals(vnfci_hostname)) { vnfcInstance_remove = currVnfci; } } } if (vnfcInstance_remove == null) { logger.warn( "Not found VNFCInstance in VDU " + vdu.getId() + " that could be removed"); break; } nfvoRequestor .getNetworkServiceRecordAgent() .deleteVNFCInstance( vnfr.getParent_ns_id(), vnfr.getId(), vdu.getId(), vnfcInstance_remove.getId()); scaled = true; notifyChange(vnfcInstance_remove.getVim_id()); } } return; } } } } catch (SDKException e) { logger.error("Problem instantiating NFVORequestor"); } //catch (FileNotFoundException e) { //logger.error("Problem scaling"); // } } private void updateNetworkOverview() { NFVORequestor nfvo_nsr_req; NFVORequestor nfvo_default_req; // Check if there were changes on the VIM ( machines scaled in-out, new nsrs or deleted nsrs ) ArrayList<Integer> vims_no_update = new ArrayList<>(); if (this.osOverview != null) { if (this.osOverview.getVim_hashes() != null) { for (Integer int_vim_id : osOverview.getVim_hashes().keySet()) { if (vim_hashes.containsKey(int_vim_id)) { // Check for differences if (osOverview.getVim_hashes().get(int_vim_id).equals(vim_hashes.get(int_vim_id))) { vims_no_update.add(int_vim_id); } } } } } // Set up a variable which contains the already processed vims, we distinguish via the auth_url + user + tenant here // to avoid contacting the same infrastructure used in different projects. ArrayList<Integer> processed_vims = new ArrayList<>(); // Set up a map containing all the vim ids listed to the internal generated hash, therefor we use the latest // network overview HashMap<Integer, ArrayList<String>> vim_map = osOverview.getVims(); // if its empty, just use an empty HashMap if (vim_map == null) { vim_map = new HashMap<>(); } // Set up a map containing all external vim ids together with their names HashMap<String, String> vim_name_map = new HashMap<>(); // Set up a map containing all external vim ids together with their names HashMap<String, String> vim_type_map = new HashMap<>(); // Set up a map containing all external vim ids together with their projects in which they are used HashMap<String, ArrayList<String>> vim_project_map = new HashMap<>(); // Set up a map containing all internal vim hashs and related node information ( openstack only currently) HashMap<Integer, ArrayList<String>> node_map = new HashMap<>(); // Set up a map containing all projects ids together with their names HashMap<String, String> project_id_map = new HashMap<>(); // Set up a map containing all projects together with a list of nsr ids HashMap<String, ArrayList<String>> project_nsr_map = new HashMap<>(); // Set up a map containing all projects ids together with their names HashMap<String, String> nsr_name_map = new HashMap<>(); // Set up a map containing all projects together with a list of nsr ids HashMap<String, ArrayList<String>> nsr_vnfr_map = new HashMap<>(); // Set up a map containing all vnf names with their ids HashMap<String, String> vnfr_name_map = new HashMap<>(); // Set up a map containing the vnfs and their networks from Open Baton side ( virtual link records ) HashMap<String, ArrayList<String>> vnfr_vlr_map = new HashMap<>(); // Set up a map containing all vlr ids together with their names HashMap<String, String> vlr_name_map = new HashMap<>(); // Set up a map containing all vlr ids together with their assigned bandwidth qualities HashMap<String, String> vlr_quality_map = new HashMap<>(); // Set up a map containing all vnfs and their vdus HashMap<String, ArrayList<String>> vnfr_vdu_map = new HashMap<>(); // Set up a a map containing the names of each vdu listed by their ids HashMap<String, String> vdu_name_map = new HashMap<>(); // Set up a map containing the vdu and their vnfcis HashMap<String, ArrayList<String>> vdu_vnfci_map = new HashMap<>(); // Set up a map containing the vnfci names with their ids ( These are the host names in the end ) HashMap<String, String> vnfci_name_map = new HashMap<>(); // Set up a map containing all vnfci hostnames with their related vnf id HashMap<String, String> vnfci_vnfr_map = new HashMap<>(); // Set up a map containing the ips of each vnfci HashMap<String, ArrayList<String>> vnfci_ip_map = new HashMap<>(); // Set up a map containing the names of the networks for each ip HashMap<String, String> ip_name_map = new HashMap<>(); // Set up a map containing the ips of the networks/ip ids HashMap<String, String> ip_addresses_map = new HashMap<>(); // Set up a map containing the vnfci ids together with their vim ids.. HashMap<String, Integer> vnfci_vim_map = new HashMap<>(); // Set up a map containing the vdu id together with the maximum number of vnfc instances HashMap<String, Integer> vdu_scale_map = new HashMap<>(); // ###### OpenStack related // Set up a map containing the OpenStack port ids listed to the internal hash of the vim HashMap<Integer, ArrayList<String>> port_id_map = osOverview.getOs_port_ids(); if (port_id_map == null) { port_id_map = new HashMap<>(); } // Set up a map containing the OpenStack port ids together with all their ip addresses HashMap<String, ArrayList<String>> port_ip_map = osOverview.getOs_port_ips(); if (port_ip_map == null) { port_ip_map = new HashMap<>(); } // A list of ips which have to be checked for ports + subnets + nets ( listed by internal hash..) HashMap<Integer, ArrayList<String>> ips_to_be_checked = new HashMap<>(); // A simple map which saves the reference to the osclients ( via a vim instaces ) HashMap<Integer, BaseVimInstance> os_vim_map = new HashMap<>(); // Set up a map containing the OpenStack port ids listed with their parent network id HashMap<String, String> port_net_map = this.osOverview.getOs_port_net_map(); if (port_net_map == null) { port_net_map = new HashMap<>(); } // Set up a map containing the OpenStack network ids listed with their names HashMap<String, String> net_name_map = new HashMap<>(); // Set up a map containing the vnfci ids listed with their related hypervisor/ compute node HashMap<String, String> vnfci_hypervisor_map = this.osOverview.getVnfci_hypervisors(); if (vnfci_hypervisor_map == null) { vnfci_hypervisor_map = new HashMap<>(); } // Set up a map containing the vlr id together with the external network id HashMap<String, String> vlr_ext_net_map = new HashMap<>(); // Set up a map containing the internal vim identifier and a hash HashMap<Integer, String> vim_hash_map = new HashMap<>(); this.osOverview = new NetworkOverview(); try { nfvo_default_req = NfvoRequestorBuilder.create() .nfvoIp(nfvo_configuration.getIp()) .nfvoPort(Integer.parseInt(nfvo_configuration.getPort())) .username(nfvo_configuration.getUsername()) .password(nfvo_configuration.getPassword()) .sslEnabled(nfvo_configuration.getSsl().isEnabled()) .version("1") .build(); // Iterate over all projects and collect all NSRs for (Project project : nfvo_default_req.getProjectAgent().findAll()) { //logger.debug("Checking project : " + project.getName()); nfvo_nsr_req = obTools.getNFVORequestor( nfvo_configuration.getIp(), nfvo_configuration.getPort(), project.getId(), nse_configuration.getService().getKey()); List<NetworkServiceRecord> nsr_list = nfvo_nsr_req.getNetworkServiceRecordAgent().findAll(); if (!nsr_list.isEmpty()) { project_id_map.put(project.getId(), project.getName()); } // ################################################### for (NetworkServiceRecord nsr : nsr_list) { nsr_name_map.put(nsr.getId(), nsr.getName()); ArrayList<String> tmp_nsrs; if (project_nsr_map.containsKey(project.getId())) { tmp_nsrs = project_nsr_map.get(project.getId()); tmp_nsrs.add(nsr.getId()); } else { tmp_nsrs = new ArrayList<>(); tmp_nsrs.add(nsr.getId()); project_nsr_map.put(project.getId(), tmp_nsrs); } for (VirtualNetworkFunctionRecord vnfr : nsr.getVnfr()) { // Remove all occurences matching the old id synchronized (vnfr_list) { for (int x = 0; x < vnfr_list.size(); x++) { VirtualNetworkFunctionRecord int_vnfr = vnfr_list.get(x); if (int_vnfr.getId().equals(vnfr.getId())) { vnfr_list.remove(int_vnfr); } } vnfr_list.add(vnfr); } vnfr_name_map.put(vnfr.getId(), vnfr.getName()); ArrayList<String> tmp_vnfs; if (nsr_vnfr_map.containsKey(nsr.getId())) { tmp_vnfs = nsr_vnfr_map.get(nsr.getId()); tmp_vnfs.add(vnfr.getId()); } else { tmp_vnfs = new ArrayList<>(); tmp_vnfs.add(vnfr.getId()); nsr_vnfr_map.put(nsr.getId(), tmp_vnfs); } for (InternalVirtualLink vlr : vnfr.getVirtual_link()) { ArrayList<String> tmp_vlrs; if (vnfr_vlr_map.containsKey(vnfr.getId())) { tmp_vlrs = vnfr_vlr_map.get(vnfr.getId()); tmp_vlrs.add(vlr.getId()); } else { tmp_vlrs = new ArrayList<>(); tmp_vlrs.add(vlr.getId()); vnfr_vlr_map.put(vnfr.getId(), tmp_vlrs); } vlr_name_map.put(vlr.getId(), vlr.getName()); for (String qosParam : vlr.getQos()) { if (qosParam.contains("minimum") || qosParam.contains("maximum") || qosParam.contains("policy")) { vlr_quality_map.put(vlr.getId(), vlr.getQos().toString()); } } } for (VirtualDeploymentUnit vdu : vnfr.getVdu()) { vdu_scale_map.put(vdu.getId(), vdu.getScale_in_out()); ArrayList<String> tmp_vdus; if (vnfr_vdu_map.containsKey(vnfr.getId())) { tmp_vdus = vnfr_vdu_map.get(vnfr.getId()); tmp_vdus.add(vdu.getId()); } else { tmp_vdus = new ArrayList<>(); tmp_vdus.add(vdu.getId()); vnfr_vdu_map.put(vnfr.getId(), tmp_vdus); } vdu_name_map.put(vdu.getId(), vdu.getName()); for (VNFCInstance vnfci : vdu.getVnfc_instance()) { vnfci_name_map.put(vnfci.getId(), vnfci.getHostname()); vnfci_vnfr_map.put(vnfci.getHostname(), vnfr.getId()); ArrayList<String> tmp_vnfcis; if (vdu_vnfci_map.containsKey(vdu.getId())) { tmp_vnfcis = vdu_vnfci_map.get(vdu.getId()); tmp_vnfcis.add(vnfci.getId()); } else { tmp_vnfcis = new ArrayList<>(); tmp_vnfcis.add(vnfci.getId()); vdu_vnfci_map.put(vdu.getId(), tmp_vnfcis); } BaseVimInstance tmp_vim = obTools.getVimInstance(nfvo_nsr_req, vnfci.getVim_id()); if (OpenstackVimInstance.class.isInstance(tmp_vim)) { OpenstackVimInstance tmp_os_vim = (OpenstackVimInstance) tmp_vim; for (int x = 0; x < vim_list.size(); x++) { BaseVimInstance vim = vim_list.get(x); if (vim.getId().equals(tmp_vim.getId())) { vim_list.remove(vim); } } vim_list.add(tmp_vim); ArrayList<String> tmp_list; if (vim_project_map.containsKey(tmp_vim.getId())) { tmp_list = vim_project_map.get(tmp_vim.getId()); if (!tmp_list.contains(project.getId())) { tmp_list.add(project.getId()); } } else { tmp_list = new ArrayList<>(); tmp_list.add(project.getId()); vim_project_map.put(tmp_vim.getId(), tmp_list); } // Generate an identifier internally to not distinguish vims by their internal id but at other crucial information to avoid contacting the same infrastructure int vim_identifier = (tmp_vim.getAuthUrl() + tmp_os_vim.getUsername() + tmp_os_vim.getTenant()) .hashCode() & 0xfffffff; if (!vim_name_map.containsKey(tmp_vim.getId())) { vim_name_map.put(tmp_vim.getId(), tmp_vim.getName()); vim_type_map.put(tmp_vim.getId(), tmp_vim.getType()); for (BaseNetwork n : tmp_os_vim.getNetworks()) { net_name_map.put(n.getExtId(), n.getName()); } } ArrayList<String> vlrs = vnfr_vlr_map.get(vnfr.getId()); for (BaseNetwork n : tmp_vim.getNetworks()) { for (String vlr_id : vlrs) { if (vlr_name_map.get(vlr_id).equals(n.getName())) { vlr_ext_net_map.put(vlr_id, n.getExtId()); } } } vnfci_vim_map.put(vnfci.getId(), vim_identifier); for (Ip ip : vnfci.getIps()) { ip_name_map.put(ip.getId(), ip.getNetName()); ip_addresses_map.put(ip.getId(), ip.getIp()); ArrayList<String> tmp_ips; if (vnfci_ip_map.containsKey(vnfci.getId())) { tmp_ips = vnfci_ip_map.get(vnfci.getId()); tmp_ips.add(ip.getId()); } else { tmp_ips = new ArrayList<>(); tmp_ips.add(ip.getId()); vnfci_ip_map.put(vnfci.getId(), tmp_ips); } ArrayList<String> tmp_ip_list; if (ips_to_be_checked.containsKey(vim_identifier)) { tmp_ip_list = ips_to_be_checked.get(vim_identifier); tmp_ip_list.add(ip.getIp()); } else { tmp_ip_list = new ArrayList<>(); tmp_ip_list.add(ip.getIp()); ips_to_be_checked.put(vim_identifier, tmp_ip_list); } } if (!processed_vims.contains(vim_identifier)) { processed_vims.add(vim_identifier); ArrayList<String> tmp_vim_ids = new ArrayList<>(); tmp_vim_ids.add(tmp_vim.getId()); vim_map.put(vim_identifier, tmp_vim_ids); int_vim_map.put(vim_identifier, tmp_vim_ids); if (tmp_vim.getType().equals("openstack")) { OSClient tmp_os = osTools.getOSClient(tmp_os_vim); //if (!os_client_map.containsKey(vim_identifier)) { // os_client_map.put(vim_identifier, tmp_os); //} if (!os_vim_map.containsKey(vim_identifier)) { os_vim_map.put(vim_identifier, tmp_vim); } Map<String, String> tmp_computeNodeMap = osTools.getComputeNodeMap(tmp_os); if (tmp_computeNodeMap != null) { // We collect all involved compute nodes ArrayList<String> tmp_node_names = new ArrayList<>(); for (String key : tmp_computeNodeMap.keySet()) { tmp_node_names.add(key); } node_map.put(vim_identifier, tmp_node_names); } } } else { // in this case we already found the vim via the internal generated hash and only need to append the vim id to the hash in the map ArrayList<String> vim_ids = vim_map.get(vim_identifier); if (!vim_ids.contains(tmp_vim.getId())) { vim_ids.add(tmp_vim.getId()); } } } } } } } } //this.osOverview.setCurrent_hash(new String(this.curr_hash)); this.osOverview.setVims(vim_map); this.osOverview.setVim_names(vim_name_map); this.osOverview.setVim_types(vim_type_map); this.osOverview.setVim_projects(vim_project_map); this.osOverview.setOs_nodes(node_map); this.osOverview.setProjects(project_id_map); this.osOverview.setNsrs(project_nsr_map); this.osOverview.setNsr_names(nsr_name_map); this.osOverview.setVnfr_names(vnfr_name_map); this.osOverview.setNsr_vnfrs(nsr_vnfr_map); this.osOverview.setVnfr_vlrs(vnfr_vlr_map); this.osOverview.setVlr_names(vlr_name_map); this.osOverview.setVlr_qualities(vlr_quality_map); this.osOverview.setVnfr_vdus(vnfr_vdu_map); this.osOverview.setVdu_names(vdu_name_map); this.osOverview.setVdu_vnfcis(vdu_vnfci_map); this.osOverview.setVnfci_names(vnfci_name_map); this.osOverview.setVnfci_vnfr(vnfci_vnfr_map); this.osOverview.setVnfci_ips(vnfci_ip_map); this.osOverview.setVdu_scale(vdu_scale_map); this.osOverview.setIp_names(ip_name_map); this.osOverview.setIp_addresses(ip_addresses_map); this.osOverview.setVnfci_vims(vnfci_vim_map); // TODO : Switch to threads to collect information of the infrastructure ( should become way faster ) for (Integer i : node_map.keySet()) { if (!vims_no_update.contains(i)) { // clear old entries //String new_hash = UUID.randomUUID().toString(); //vim_hash_map.put(i, new_hash); //vim_hashes.put(i, new_hash); if (os_vim_map.containsKey(i)) { if (OpenstackVimInstance.class.isInstance(os_vim_map.get(i))) { OpenstackVimInstance osV = (OpenstackVimInstance) os_vim_map.get(i); OSClient os_client = osTools.getOSClient(osV); HashMap<String, ArrayList<String>> tmp_portMap = osTools.getPortIps(os_client, ips_to_be_checked.get(i)); //logger.debug(tmp_portMap.toString()); // remove all old entries if (port_id_map.containsKey(i)) { for (String key : port_id_map.get(i)) { port_ip_map.remove(key); //net_name_map.remove(port_net_map.get(key)); port_net_map.remove(key); } // remove entry itself port_id_map.remove(i); } if (tmp_portMap != null) { for (String p_id : tmp_portMap.keySet()) { ArrayList<String> tmp_port_ids; if (port_id_map.containsKey(i)) { tmp_port_ids = port_id_map.get(i); if (!tmp_port_ids.contains(p_id)) { tmp_port_ids.add(p_id); } } else { tmp_port_ids = new ArrayList<>(); tmp_port_ids.add(p_id); port_id_map.put(i, tmp_port_ids); } } } for (String key : tmp_portMap.keySet()) { port_ip_map.put(key, tmp_portMap.get(key)); } //port_ip_map = tmp_portMap; // Collect information about the compute nodes... // TODO : Clear the vnfci_hypervisor map as done for the port ip + port id + port net maps for (Server s : os_client.compute().servers().list()) { for (String vnfci_id : vnfci_name_map.keySet()) { if (vnfci_name_map.get(vnfci_id).equals(s.getName())) { //vnf_host_compute_map.put(vnfr.getName(), s.getHypervisorHostname()); vnfci_hypervisor_map.put(s.getName(), s.getHypervisorHostname()); } } } } } } else { vim_hash_map.put(i, vim_hashes.get(i)); } } // TODO : collect information about the os networks, to be able to integrate with the Open Baton view on resources for (Integer i : port_id_map.keySet()) { if (!vims_no_update.contains(i)) { if (os_vim_map.containsKey(i)) { if (OpenstackVimInstance.class.isInstance(os_vim_map.get(i))) { OpenstackVimInstance osV = (OpenstackVimInstance) os_vim_map.get(i); OSClient os_client = osTools.getOSClient(osV); for (String p_id : port_id_map.get(i)) { // TODO : avoid contacting the infrastructure to often, maybe there is a better way of collecting all information in before Port p = os_client.networking().port().get(p_id); if (p != null) { port_net_map.put(p_id, p.getNetworkId()); } } } } //for(Network n : tmp_os.networking().network().list()){ // net_name_map.put(n.getId(),n.getId()); //} } } // Well we should collect the network names together with their id's //this.osOverview.setVim_hashes(vim_hash_map); this.osOverview.setOs_port_ids(port_id_map); this.osOverview.setOs_port_ips(port_ip_map); this.osOverview.setOs_port_net_map(port_net_map); this.osOverview.setOs_net_names(net_name_map); this.osOverview.setVnfci_hypervisors(vnfci_hypervisor_map); this.osOverview.setVlr_ext_networks(vlr_ext_net_map); for (Integer i : node_map.keySet()) { if (!vims_no_update.contains(i)) { // clear old entries String new_hash = UUID.randomUUID().toString(); vim_hash_map.put(i, new_hash); vim_hashes.put(i, new_hash); } } this.osOverview.setVim_hashes(vim_hash_map); if (nse_configuration.getZabbix()) { for (String host : vnfci_name_map.values()) { zabbixChecker.addHost(host); } } //zabbix.startPolling(hosts, metrics); //zabbix.pollValues(hosts, metrics); //this.int_vim_map = vim_map; // In the very end add the hosts and hypervisors which did not belong to any NSR //this.osOverview.setNodes(complete_computeNodeMap); //this.osOverview.setProjects(project_nsr_map); //logger.debug("updated overview"); } catch (SDKException e) { logger.error("Problem instantiating NFVORequestor"); } //catch (FileNotFoundException e) { //e.printStackTrace(); //} } }
45.614789
176
0.601188
30f5513bf776c60f159b814338c04f5b275aeb45
857
package ch.petikoch.tools.taskgraphtool.ui; import com.vaadin.annotations.AutoGenerated; import com.vaadin.annotations.DesignRoot; import com.vaadin.ui.Button; import com.vaadin.ui.ComboBox; import com.vaadin.ui.TextField; import com.vaadin.ui.VerticalLayout; import com.vaadin.ui.declarative.Design; /** * !! DO NOT EDIT THIS FILE !! * * This class is generated by Vaadin Designer and will be overwritten. * * Please make a subclass with logic and additional interfaces as needed, * e.g class LoginView extends LoginDesign implements View { } */ @DesignRoot @AutoGenerated @SuppressWarnings("serial") public class DesignNodeDeletionForm extends VerticalLayout { protected ComboBox<String> comboBox; protected TextField textField; protected Button deleteButton; public DesignNodeDeletionForm() { Design.read(this); } }
27.645161
73
0.766628
cbc57f1122c7106f88fe9aa2f421c7ed2c93c8ae
575
package io.mail7.sdk.util; public class ErrorResponse { private String message; private String status; /** * * @return The Status */ public String getStatus() { return status == null ? status : ""; } /** * * @param status The Status */ public void setStatus(final String status) { this.status = status; } /** * * @return The message */ public String getMessage() { return message == null ? message : ""; } /** * * @param message The Message */ public void setMessage(final String message) { this.message = message; } }
14.74359
47
0.615652
4438fe59bf71ec38a9cb8c064421cc789660ff25
857
package de.deutschebahn.bahnhoflive.util; import android.graphics.drawable.Drawable; import android.graphics.drawable.LevelListDrawable; import android.text.Html.ImageGetter; import android.widget.TextView; import de.deutschebahn.bahnhoflive.R; public class TextViewImageGetter implements ImageGetter { TextView tv; private int width; public TextViewImageGetter (TextView v, int width) { tv = v; this.width = width; } @Override public Drawable getDrawable(String source){ LevelListDrawable d = new LevelListDrawable(); Drawable empty = tv.getResources().getDrawable(R.drawable.placeholder); d.addLevel(0, 0, empty); d.setBounds(0, 0, empty.getIntrinsicWidth(), empty.getIntrinsicHeight()); new LoadImage().execute(source, d, tv, width); return d; } }
28.566667
82
0.69895
41ce8733df828d95d6378500045bb8833885a12e
1,968
package de.t7soft.android.t7home.smarthome.util; import java.security.KeyStore; import java.security.KeyStoreException; import java.security.NoSuchAlgorithmException; import java.security.cert.CertificateException; import java.security.cert.X509Certificate; import javax.net.ssl.TrustManager; import javax.net.ssl.TrustManagerFactory; import javax.net.ssl.X509TrustManager; public class EasyX509TrustManager implements X509TrustManager { private X509TrustManager standardTrustManager = null; /** * Constructor for EasyX509TrustManager. */ public EasyX509TrustManager(KeyStore keystore) throws NoSuchAlgorithmException, KeyStoreException { super(); TrustManagerFactory factory = TrustManagerFactory .getInstance(TrustManagerFactory.getDefaultAlgorithm()); factory.init(keystore); TrustManager[] trustmanagers = factory.getTrustManagers(); if (trustmanagers.length == 0) { throw new NoSuchAlgorithmException("no trust manager found"); } this.standardTrustManager = (X509TrustManager) trustmanagers[0]; } /** * @see javax.net.ssl.X509TrustManager#checkClientTrusted(X509Certificate[], * String authType) */ @Override public void checkClientTrusted(X509Certificate[] certificates, String authType) throws CertificateException { standardTrustManager.checkClientTrusted(certificates, authType); } /** * @see javax.net.ssl.X509TrustManager#checkServerTrusted(X509Certificate[], * String authType) */ @Override public void checkServerTrusted(X509Certificate[] certificates, String authType) throws CertificateException { if ((certificates != null) && (certificates.length == 1)) { certificates[0].checkValidity(); } else { standardTrustManager.checkServerTrusted(certificates, authType); } } /** * @see javax.net.ssl.X509TrustManager#getAcceptedIssuers() */ @Override public X509Certificate[] getAcceptedIssuers() { return this.standardTrustManager.getAcceptedIssuers(); } }
29.818182
77
0.775915
3454af73023d00570583d5d59bab0acc9ee5ab81
1,934
/* * 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 WARRANTIESOR 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.aries.application.modelling; /* Base interface for a model of a requirement, or need for something, such as a bundle, * package or service. */ public interface Consumer { /** * Return the resource type * @return the resource type, such as BUNDLE, PACKAGE, SERVICE, OTHER */ ResourceType getType(); /** * This is not the same as the filter which you might get, say, by parsing a blueprint * reference. It is more specific - and usable at runtime. * * @return String filter matching every property required by this consumer */ String getAttributeFilter(); /** * Whether the resources consumed can be multiple. * @return true if multiple resources can be consumed. */ boolean isMultiple(); /** * Whether the resource consumed can be optional. * @return true if optional. */ boolean isOptional(); /** * Whether the provider object satisfies the consume criteria. * @param capability The provider capability * @return true if the capability satisfies the consuming criteria. */ boolean isSatisfied(Provider capability); }
32.233333
89
0.719235
72c551b2bf4f6771aaa22a17be81f031c10fcce3
14,965
package org.cloudifysource.quality.iTests.test.cli.cloudify.cloud.ec2.examples; import iTests.framework.utils.JGitUtils; import iTests.framework.utils.LogUtils; import iTests.framework.utils.ScriptUtils; import iTests.framework.utils.WebUtils; import org.cloudifysource.dsl.internal.CloudifyConstants; import org.cloudifysource.dsl.rest.response.InvokeServiceCommandResponse; import org.cloudifysource.quality.iTests.framework.utils.CommandInvoker; import org.cloudifysource.quality.iTests.test.AbstractTestSupport; import org.cloudifysource.quality.iTests.test.cli.cloudify.CommandTestUtils; import org.cloudifysource.quality.iTests.test.cli.cloudify.cloud.NewAbstractCloudTest; import org.cloudifysource.restclient.InvocationResult; import org.cloudifysource.restclient.exceptions.RestClientException; import org.openspaces.admin.pu.DeploymentStatus; import org.testng.Assert; import org.testng.annotations.AfterClass; import org.testng.annotations.BeforeClass; import org.testng.annotations.Test; import java.io.File; import java.io.IOException; import java.net.URL; import java.util.ArrayList; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.regex.Matcher; import java.util.regex.Pattern; /** * User: yohana * Date: 12/8/13 * Time: 1:44 PM */ public class Ec2XAP9xApplicationTest extends NewAbstractCloudTest { private static final String LOCAL_GIT_REPO_PATH = ScriptUtils.getBuildPath() + "/git-recipes-" + Ec2XAP9xApplicationTest.class.getSimpleName(); private static final String XAP9X_MANAGEMENT = "xap-management"; private static final String SG_VALIDATOR = "sgvalidator"; private static final String XAP9X_PATH = LOCAL_GIT_REPO_PATH+"/apps/xap9x-tiny/"; private static final String SG_VALIDATOR_PATH = CommandTestUtils.getPath("src/main/resources/apps/cloudify/recipes/sgvalidator"); private static final String APP_NAME = "xap9x-tiny"; private static final String BRANCH_NAME = "master"; private static final String PUURL = "https://s3-eu-west-1.amazonaws.com/gigaspaces-maven-repository-eu/com/gigaspaces/quality/sgtest/apps/listeners/Space/3.0.0-SNAPSHOT/Space-3.0.0-SNAPSHOT.jar"; private static final String DEPLOYPU_COMMAND = "deploy-pu pu-using-deploy-pu "+PUURL+" partitioned-sync2backup 1 1 0 0"; private static final String UNDEPLOYGRID_DEPLOYPU_COMMAND = "undeploy-grid pu-using-deploy-pu"; private static final String DEPLOYPUBASIC_COMMAND = "deploy-pu-basic "+PUURL; private static final String UNDEPLOYGRID_DEPLOYPUBASIC_COMMAND = "undeploy-grid Space-3.0.0-SNAPSHOT.jar"; private static final String DEPLOYGRID_COMMAND = "deploy-grid pu-using-deploy-grid partitioned-sync2backup 1 1 0 0"; private static final String UNDEPLOYGRID_DEPLOYGRID_COMMAND = "undeploy-grid pu-using-deploy-grid"; private static final String DEPLOYGRIDBASIC_COMMAND = "deploy-grid-basic puusing-deploygridbasic"; private static final String UNDEPLOYGRID_DEPLOYGRIDBASIC_COMMAND = "undeploy-grid puusing-deploygridbasic"; //This grid is already deployed by the recipe but we need these lines for validateInstance and undeploy command private static final String DEPLOYGRID_MYDATAGRID_COMMAND = "deploy-grid-basic myDataGrid"; // partitioned-sync2backup 1 0 1 1 private static final String UNDEPLOYGRID_MYDATAGRID_COMMAND = "undeploy-grid myDataGrid"; @Override protected String getCloudName() { return "ec2"; } @Override protected boolean isReusableCloud() { return false; } @BeforeClass(alwaysRun = true) protected void prepareTest() throws Exception { //Checkout Recipes if (!(new File(LOCAL_GIT_REPO_PATH).exists())) { String remotePath = "https://github.com/CloudifySource/cloudify-recipes.git"; JGitUtils.clone(LOCAL_GIT_REPO_PATH, remotePath, BRANCH_NAME); } super.bootstrap(); } @AfterClass(alwaysRun = true) protected void teardown() throws Exception { super.teardown(); } @Test(timeOut = AbstractTestSupport.DEFAULT_TEST_TIMEOUT * 4, enabled = true) public void testXAP9xRecipe() throws Exception { InvocationResult result; InvokeServiceCommandResponse response; //Install and verify xap-management String installationLog = installApplicationAndWait(XAP9X_PATH, APP_NAME);//installAndVerify(XAP9X_MANAGEMENT_PATH,XAP9X_MANAGEMENT); verifyPUInstallation(APP_NAME); Pattern pattern = Pattern.compile("/\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}] - xap-management-1 START invoked"); // Regex for ip to match in the log of xap-management installation Matcher matcher = pattern.matcher(installationLog); if (!matcher.find()) { throw new Exception("Unable to find lookuplocator's ip in the log: "+installationLog); } String managementPrivateIP = matcher.group(0); String lookuplocators = managementPrivateIP.substring(managementPrivateIP.indexOf("/")+1, managementPrivateIP.indexOf("]"))+":4242"; log("Using lookuplocators: "+lookuplocators); //Install and verify sgvalidator installAndVerify(SG_VALIDATOR_PATH,SG_VALIDATOR); // First validate and undeploy myDataGrid that the container-service deploy validateInstance(lookuplocators,DEPLOYGRID_MYDATAGRID_COMMAND); //undeploy-grid response = customCommand(UNDEPLOYGRID_MYDATAGRID_COMMAND, XAP9X_MANAGEMENT, APP_NAME); result = getCustomCommandResult(response); Assert.assertEquals(result.getInvocationStatus(), CloudifyConstants.InvocationStatus.SUCCESS); //deploy-pu response = customCommand(DEPLOYPU_COMMAND, XAP9X_MANAGEMENT, APP_NAME); result = getCustomCommandResult(response); Assert.assertEquals(result.getInvocationStatus(), CloudifyConstants.InvocationStatus.SUCCESS); validateInstance(lookuplocators,DEPLOYPU_COMMAND); //undeploy-grid response = customCommand(UNDEPLOYGRID_DEPLOYPU_COMMAND, XAP9X_MANAGEMENT, APP_NAME); result = getCustomCommandResult(response); Assert.assertEquals(result.getInvocationStatus(), CloudifyConstants.InvocationStatus.SUCCESS); //deploy-pu-basic response = customCommand(DEPLOYPUBASIC_COMMAND, XAP9X_MANAGEMENT, APP_NAME); result = getCustomCommandResult(response); Assert.assertEquals(result.getInvocationStatus(), CloudifyConstants.InvocationStatus.SUCCESS); validateInstance(lookuplocators,DEPLOYPUBASIC_COMMAND); //undeploy-grid response = customCommand(UNDEPLOYGRID_DEPLOYPUBASIC_COMMAND, XAP9X_MANAGEMENT, APP_NAME); result = getCustomCommandResult(response); Assert.assertEquals(result.getInvocationStatus(), CloudifyConstants.InvocationStatus.SUCCESS); //deploy-grid response = customCommand(DEPLOYGRID_COMMAND, XAP9X_MANAGEMENT, APP_NAME); result = getCustomCommandResult(response); Assert.assertEquals(result.getInvocationStatus(), CloudifyConstants.InvocationStatus.SUCCESS); validateInstance(lookuplocators,DEPLOYGRID_COMMAND); //undeploy-grid response = customCommand(UNDEPLOYGRID_DEPLOYGRID_COMMAND, XAP9X_MANAGEMENT, APP_NAME); result = getCustomCommandResult(response); Assert.assertEquals(result.getInvocationStatus(), CloudifyConstants.InvocationStatus.SUCCESS); //deploy-grid response = customCommand(DEPLOYGRIDBASIC_COMMAND, XAP9X_MANAGEMENT, APP_NAME); result = getCustomCommandResult(response); Assert.assertEquals(result.getInvocationStatus(), CloudifyConstants.InvocationStatus.SUCCESS); validateInstance(lookuplocators,DEPLOYGRIDBASIC_COMMAND); //undeploy-grid response = customCommand(UNDEPLOYGRID_DEPLOYGRIDBASIC_COMMAND, XAP9X_MANAGEMENT, APP_NAME); result = getCustomCommandResult(response); Assert.assertEquals(result.getInvocationStatus(), CloudifyConstants.InvocationStatus.SUCCESS); String uninstallOutput = uninstallAndVerify(); } private void validateInstance(String lookuplocators, String deploypuCommand) throws Exception { String gridname; String partitions, backups, maxPerVM, maxPerMachine; String[] deployCmdArr = deploypuCommand.split(" "); if (deployCmdArr[0].equals("deploy-pu")) { gridname = deployCmdArr[1]; partitions = deployCmdArr[4]; backups = deployCmdArr[5]; maxPerVM = deployCmdArr[6]; maxPerMachine = deployCmdArr[7]; } else if (deployCmdArr[0].equals("deploy-grid")) { gridname = deployCmdArr[1]; partitions = deployCmdArr[3]; backups = deployCmdArr[4]; maxPerVM = deployCmdArr[5]; maxPerMachine = deployCmdArr[6]; } else if (deployCmdArr[0].equals("deploy-pu-basic")) { File file = new File(PUURL); gridname = file.getName(); partitions = "1"; backups = "0"; maxPerVM = "1"; maxPerMachine = "1"; } else if (deployCmdArr[0].equals("deploy-grid-basic")) { gridname = deployCmdArr[1]; partitions = "1"; backups = "1"; maxPerVM = "0"; maxPerMachine = "0"; } else { throw new Exception("Unknown command. Please recheck the command or add it to validateInstance function."); } InvokeServiceCommandResponse response; InvocationResult result; String appName = "default"; String numOfInstances = String.valueOf(Integer.valueOf(partitions)*(1+Integer.valueOf(backups))); response = customCommand("get-datagrid-instances "+gridname+" "+lookuplocators+" "+numOfInstances, SG_VALIDATOR, appName); result = getCustomCommandResult(response); Assert.assertEquals(result.getInvocationStatus(), CloudifyConstants.InvocationStatus.SUCCESS); Assert.assertEquals(result.getResult(),numOfInstances); response = customCommand("get-datagrid-deploymentstatus "+gridname+" "+lookuplocators+" "+numOfInstances, SG_VALIDATOR, appName); result = getCustomCommandResult(response); Assert.assertEquals(result.getInvocationStatus(), CloudifyConstants.InvocationStatus.SUCCESS); Assert.assertEquals(result.getResult(), String.valueOf(DeploymentStatus.INTACT)); response = customCommand("get-datagrid-partitions "+gridname+" "+lookuplocators+" "+numOfInstances, SG_VALIDATOR, appName); result = getCustomCommandResult(response); Assert.assertEquals(result.getInvocationStatus(), CloudifyConstants.InvocationStatus.SUCCESS); Assert.assertEquals(result.getResult(),partitions); response = customCommand("get-datagrid-backups "+gridname+" "+lookuplocators+" "+numOfInstances, SG_VALIDATOR, appName); result = getCustomCommandResult(response); Assert.assertEquals(result.getInvocationStatus(), CloudifyConstants.InvocationStatus.SUCCESS); Assert.assertEquals(result.getResult(),backups); response = customCommand("get-datagrid-maxinstancespermachine "+gridname+" "+lookuplocators+" "+numOfInstances, SG_VALIDATOR, appName); result = getCustomCommandResult(response); Assert.assertEquals(result.getInvocationStatus(), CloudifyConstants.InvocationStatus.SUCCESS); Assert.assertEquals(result.getResult(),maxPerMachine); response = customCommand("get-datagrid-maxinstancespervm "+gridname+" "+lookuplocators+" "+numOfInstances, SG_VALIDATOR, appName); result = getCustomCommandResult(response); Assert.assertEquals(result.getInvocationStatus(), CloudifyConstants.InvocationStatus.SUCCESS); Assert.assertEquals(result.getResult(),maxPerVM); } private String uninstallAndVerify() throws Exception { uninstallServiceAndWait(SG_VALIDATOR); String log = uninstallApplicationAndWait(APP_NAME, false, 25); super.scanForLeakedAgentNodes(); return log; } private InvokeServiceCommandResponse customCommand(String commandStr, String serviceName, String appName) throws IOException, InterruptedException, RestClientException { String[] commandArr = commandStr.split(" "); String command=commandStr; List<String> params = new ArrayList<String>(); log("Invoking command: "+command); if (commandArr.length > 1) { command = commandArr[0]; for (int i=1 ; i<commandArr.length ; i++) { params.add(commandArr[i]); } } CommandInvoker commandInvoker = new CommandInvoker(getRestUrl()); return commandInvoker.restInvokeServiceCommand(appName, serviceName, command, params); } private InvocationResult getCustomCommandResult(InvokeServiceCommandResponse response) throws Exception { Map<String, InvocationResult> results = parseInvocationResults(response.getInvocationResultPerInstance()); if (results.values().size() != 1) { throw new Exception("Custom command returns more than 1 result"); } return ((InvocationResult)results.values().toArray()[0]); } private String installAndVerify(String servicePath, String serviceName) throws Exception { String result = installServiceAndWait(servicePath, serviceName,25); verifyPUInstallation(serviceName); return result; } private void verifyPUInstallation(String appName) throws Exception { LogUtils.log("verifying successful installation"); String restUrl = getRestUrl(); final URL appURL = new URL(restUrl + "/admin/ProcessingUnits/Names/"+appName+""); AbstractTestSupport.assertTrue(WebUtils.isURLAvailable(appURL)); } private Map<String, InvocationResult> parseInvocationResults( final Map<String, Map<String, String>> restInvocationResultsPerInstance) { final Map<String, InvocationResult> invocationResultsMap = new LinkedHashMap<String, InvocationResult>(); for (final Map.Entry<String, Map<String, String>> entry : restInvocationResultsPerInstance.entrySet()) { final String instanceName = entry.getKey(); final Map<String, String> restInvocationResult = entry.getValue(); invocationResultsMap.put(instanceName, parseInvocationResult(restInvocationResult)); } return invocationResultsMap; } private InvocationResult parseInvocationResult(final Map<String, String> restInvocationResult) { InvocationResult invocationResult = null; if (restInvocationResult != null) { invocationResult = InvocationResult.createInvocationResult(restInvocationResult); } return invocationResult; } protected void log(String msg) { LogUtils.log(msg); } }
50.050167
199
0.721951
8e925511df0226bdeecc35db7cd3ea0b4c8f0310
309
package es.uca.cromuca.repositories; import es.uca.cromuca.entities.Especie; import es.uca.cromuca.entities.Ubicacion; import org.springframework.data.jpa.repository.JpaRepository; public interface UbicacionRepository extends JpaRepository<Ubicacion, Long> { Ubicacion findByEspecie(Especie especie); }
30.9
77
0.828479
fc1e7b197f36cd3fe39c03bf6e05ee087472ea70
1,193
package cn.ibestcode.easiness.exception.handler; import lombok.extern.slf4j.Slf4j; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.MessageSource; import org.springframework.context.i18n.LocaleContextHolder; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import java.util.HashMap; import java.util.Map; @Slf4j public abstract class AbstractExceptionHandler { @Autowired(required = false) protected MessageSource messageSource; protected ResponseEntity<Object> commonExceptionHandler(Throwable throwable, String codeName, String msgName) { Map<String, Object> result = new HashMap<>(); log.warn(throwable.getClass().getName()); log.warn(throwable.getMessage()); String code = throwable.getMessage(); String msgKey = throwable.getClass().getSimpleName() + "." + code; String msg; if (messageSource != null) { msg = messageSource.getMessage(msgKey, null, code, LocaleContextHolder.getLocale()); } else { msg = code; } result.put(codeName, code); result.put(msgName, msg); return new ResponseEntity<>(result, HttpStatus.OK); } }
32.243243
113
0.748533
fc08aff52a0983f93e7875a5f26ed7bff85d0083
1,473
package edu.rosehulman.sunz1.rosechat.activities; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import edu.rosehulman.sunz1.rosechat.R; import edu.rosehulman.sunz1.rosechat.adapters.InvitationAdapter; /** * Created by agarwaa on 14-Aug-17. */ public class InvitationActivity extends AppCompatActivity { final private String DEBUG_KEY = "Debug"; // FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser(); InvitationAdapter mAdapter; private Callback mCallback; public InvitationActivity(){ //Default constructor } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_invitation); RecyclerView recyclerView = (RecyclerView)findViewById(R.id.invitation_recyclerView); recyclerView.setLayoutManager(new LinearLayoutManager(this)); recyclerView.setHasFixedSize(true); mAdapter = new InvitationAdapter(this, mCallback); recyclerView.setAdapter(mAdapter); } @Override protected void onStart() { super.onStart(); } @Override protected void onStop() { super.onStop(); } public interface Callback { // TODO: Update argument type and name void onInvitationSelected(String invitation); } }
27.277778
93
0.720299
222e4f3e161c7e22f002b48a09b4e70f6ae675cb
325
package com.packtpub.configuration.mapping; import lombok.Data; import org.springframework.boot.context.properties.ConfigurationProperties; import org.springframework.stereotype.Component; @Data @Component @ConfigurationProperties("middleware") public class Middleware { private String apiKey; private int port; }
21.666667
75
0.815385
acf6082599163329b12c331079d9ed296388fdfe
3,389
package airtraffic.app; import static org.apache.commons.lang3.StringUtils.left; import static org.apache.commons.lang3.StringUtils.repeat; import java.sql.ResultSet; import java.sql.SQLException; import org.beryx.textio.TextTerminal; import airtraffic.ReportContext; import airtraffic.reports.CarrierReports; import airtraffic.reports.ReportException; /** * Provides methods for executing each of the carrier reports. * * @author Tony Piazza <tony@piazzaconsulting.com> */ public class CarrierReportsApp extends AbstractReportsApp { public static void main(String[] args) throws Exception { new CarrierReportsApp().executeSelectedReport(); } public void reportMostCancelledFlightsByCarrier(ReportContext context) { CarrierReports impl = getBean(CarrierReports.class, readStyle()); context.setYear(readYear()) .setLimit(readLimit(10, 1, 100)); TextTerminal<?> terminal = context.getTerminal(); terminal.println("Carrier\t\t\t\t Count"); terminal.println("-----------------------------------------"); try (ResultSet rs = impl.reportMostCancelledFlightsByCarrier(context)) { while(rs.next()) { terminal.printf("%-24s\t%,8d\n", left(rs.getString("Name"), 24), rs.getInt("TotalFlights")); } } catch (SQLException e) { throw new ReportException(e); } } public void reportCarrierMetrics(ReportContext context) { CarrierReports impl = getBean(CarrierReports.class, readStyle()); context.setYear(readYear()); TextTerminal<?> terminal = context.getTerminal(); terminal.print("Code Carrier Name "); terminal.println("Total Cancelled % Diverted % Airports"); terminal.println(repeat("-", 94)); try (ResultSet rs = impl.reportCarrierMetrics(context)) { while(rs.next()) { terminal.printf(" %2s %-30s %,9d %6.1f %6.1f %,5d\n", rs.getString("Code"), left(rs.getString("Name"), 30), rs.getInt("TotalFlights"), rs.getDouble("CancellationRate") * 100.0, rs.getDouble("DiversionRate") * 100.0, rs.getInt("TotalAirports")); } } catch (SQLException e) { throw new ReportException(e); } } public void reportCarriersWithHighestCancellationRate(ReportContext context) { CarrierReports impl = getBean(CarrierReports.class, readStyle()); context.setYear(readYear()) .setLimit(readLimit(10, 1, 100)); TextTerminal<?> terminal = context.getTerminal(); terminal.println("Carrier Rate"); terminal.println("---------------------------------------"); try (ResultSet rs = impl.reportCarriersWithHighestCancellationRate(context)) { while(rs.next()) { terminal.printf("%-30s\t%6.1f\n", left(rs.getString("Name"), 30), rs.getDouble("CancellationRate") * 100.0); } } catch (SQLException e) { throw new ReportException(e); } } }
39.406977
92
0.565063
3b21e0340791be2276fce6364321e7778f44d9a8
1,898
package pl.grzeslowski.jsupla.protocol.api.structs.cs; import pl.grzeslowski.jsupla.protocol.api.calltypes.ClientServerCallType; import java.util.Arrays; import static pl.grzeslowski.jsupla.Preconditions.checkArrayLength; import static pl.grzeslowski.jsupla.protocol.api.calltypes.ClientServerCallType.SUPLA_CS_CALL_CHANNEL_SET_VALUE; import static pl.grzeslowski.jsupla.protocol.api.consts.JavaConsts.BYTE_SIZE; import static pl.grzeslowski.jsupla.protocol.api.consts.ProtoConsts.SUPLA_CHANNELVALUE_SIZE; @Deprecated public final class SuplaChannelNewValue implements ClientServer { public static final int SIZE = BYTE_SIZE + SUPLA_CHANNELVALUE_SIZE; public final byte channelId; public final byte[] value; public SuplaChannelNewValue(byte channelId, byte[] value) { this.channelId = channelId; this.value = checkArrayLength(value, SUPLA_CHANNELVALUE_SIZE); } @Override public ClientServerCallType callType() { return SUPLA_CS_CALL_CHANNEL_SET_VALUE; } @Override public int size() { return SIZE; } @Override public boolean equals(final Object o) { if (this == o) { return true; } if (!(o instanceof SuplaChannelNewValue)) { return false; } final SuplaChannelNewValue that = (SuplaChannelNewValue) o; if (channelId != that.channelId) { return false; } return Arrays.equals(value, that.value); } @Override public final int hashCode() { int result = (int) channelId; result = 31 * result + Arrays.hashCode(value); return result; } @Override public String toString() { return "SuplaChannelNewValue{" + "channelId=" + channelId + ", value=" + Arrays.toString(value) + '}'; } }
29.2
112
0.659642
312d8eebac8fa8f7a4d44c8a24e758b79a80eb12
368
package io.github.hakkelt.generator; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; @Retention(RetentionPolicy.SOURCE) @Target({ ElementType.METHOD, ElementType.TYPE }) public @interface CollectedReplacements { Replacements[] value() default {}; }
28.307692
49
0.804348
ab77b33f3ec551a8b216035b64f42d8925a5ab45
407
package com.xyyh.edc.meta.repository; import java.util.Optional; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.data.querydsl.QuerydslPredicateExecutor; import com.xyyh.edc.meta.entity.Table; public interface TableRepository extends JpaRepository<Table, Long>, QuerydslPredicateExecutor<Table> { public Optional<Table> findByName(String name); }
29.071429
104
0.80344
6c1ccdcbf3c8643b418f90837304557a2d55d507
3,443
/* * Copyright 2019 trivago N.V. * * 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.trivago.cluecumber.json.processors; import com.google.gson.Gson; import com.google.gson.JsonElement; import com.trivago.cluecumber.json.pojo.Element; import com.trivago.cluecumber.json.pojo.Report; import com.trivago.cluecumber.json.pojo.Tag; import io.gsonfire.PostProcessor; import javax.inject.Inject; import javax.inject.Singleton; import java.util.ArrayList; import java.util.List; import java.util.stream.Collectors; import java.util.stream.Stream; @Singleton public class ReportJsonPostProcessor implements PostProcessor<Report> { private final List<String> featureUris; @Inject public ReportJsonPostProcessor() { featureUris = new ArrayList<>(); } @Override public void postDeserialize(final Report report, final JsonElement jsonElement, final Gson gson) { addFeatureIndex(report); addFeatureInformationToScenarios(report); mergeBackgroundScenarios(report); } private void addFeatureInformationToScenarios(final Report report) { List<Tag> reportTags = report.getTags(); String featureName = report.getName(); String featureUri = report.getUri(); int featureIndex = report.getFeatureIndex(); for (Element element : report.getElements()) { element.setFeatureUri(report.getUri()); element.setFeatureName(featureName); element.setFeatureIndex(featureIndex); if (reportTags.size() > 0) { List<Tag> mergedTags = Stream.concat(element.getTags().stream(), reportTags.stream()) .distinct() .collect(Collectors.toList()); element.setTags(mergedTags); } } } private void mergeBackgroundScenarios(final Report report) { List<Element> cleanedUpElements = new ArrayList<>(); Element currentBackgroundElement = null; for (Element element : report.getElements()) { if (element.getType().equalsIgnoreCase("background")) { currentBackgroundElement = element; } else { if (currentBackgroundElement != null) { element.getSteps().addAll(0, currentBackgroundElement.getSteps()); } cleanedUpElements.add(element); } } report.setElements(cleanedUpElements); } private void addFeatureIndex(final Report report) { if (report == null) return; String featureName = report.getName(); if (!featureUris.contains(featureName)) { featureUris.add(featureName); } report.setFeatureIndex(featureUris.indexOf(featureName)); } @Override public void postSerialize(final JsonElement jsonElement, final Report report, final Gson gson) { // not used } }
34.777778
102
0.66686
347d057da4085b029851e8013989f65678b0533c
10,341
package app.cap.ajm; import android.content.Context; import android.content.SharedPreferences; import android.os.Build; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.content.Intent; import android.os.Handler; import android.database.Cursor; import android.util.Log; import android.view.View; import android.widget.ProgressBar; import android.widget.Toast; import android.net.NetworkInfo; import android.net.ConnectivityManager; import com.firebase.geofire.GeoFire; import com.firebase.geofire.GeoLocation; import com.firebase.geofire.core.GeoHash; import com.google.firebase.database.DatabaseReference; import com.google.firebase.database.FirebaseDatabase; import java.io.InputStream; import java.util.Arrays; import java.util.HashMap; import java.util.Map; import app.cap.ajm.Adapter.ListAdapter; import app.cap.ajm.Adapter.WeatherDBHelper; import jxl.Sheet; import jxl.Workbook; public class SplashActivity extends AppCompatActivity { private WeatherDBHelper weatherDBHelper; private ListAdapter listAdapter; private Handler handler; private ProgressBar progressBar; private GeoFire geoFire, geoFire1; private DatabaseReference ref; private static final String TAG = SplashActivity.class.getSimpleName(); @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_splash); progressBar = (ProgressBar) findViewById(R.id.progressBar); progressBar.setProgress(0); progressBar.setVisibility(View.VISIBLE); ConnectivityManager connectivityManager = (ConnectivityManager) this.getSystemService(Context.CONNECTIVITY_SERVICE); final NetworkInfo activeNetwork = connectivityManager.getActiveNetworkInfo(); final boolean isConnected = activeNetwork != null && activeNetwork.isConnectedOrConnecting(); /*엑셀파일 자바로 가져오기*/ //this.listAdapter = new ListAdapter(this); //listAdapter.open(); //Cursor cursor = listAdapter.fetchAllList(); //Log.w("How many places? ", String.valueOf(cursor.getCount())); //if (cursor.getCount() == 0) // excelToList(); //listAdapter.close(); //cursor.close(); /*엑셀파일 자바로 가져오기 (날씨 정보 SQLite 저장용!)*/ this.weatherDBHelper = new WeatherDBHelper(this); weatherDBHelper.open(); Cursor cursor = weatherDBHelper.fetchAllList(); Log.w("How many Value?:", String.valueOf(cursor.getCount())); if (cursor.getCount() == 0) excelToWeather(); weatherDBHelper.close(); cursor.close(); handler = new Handler(); handler.postDelayed(new Runnable() { @Override public void run() { progressBar.setProgress(25); if (!isConnected) {Toast.makeText(getApplicationContext(), getString(R.string.no_internet_conection), Toast.LENGTH_LONG).show();} /*Firebase 데이터 삭제*/ //ref = FirebaseDatabase.getInstance().getReference(); //ref.child("geofire").removeValue(); //ref.child("location").removeValue(); /*엑셀파일 Firebase로 저장*/ //ListToFirebase(); /*테스트 만들기*/ //DatabaseReference databaseReference = FirebaseDatabase.getInstance().getReference(); //String pushId = databaseReference.child("geofire").push().getKey(); //String pushId1 = databaseReference.child("location").push().getKey(); //geoFire = new GeoFire(databaseReference.child("geofire")); //geoFire.setLocation(pushId, new GeoLocation(37.260163, 127.024974)); //GeoHash geoHash = new GeoHash(37.260163, 127.024974); //Map<String, Object>updates = new HashMap<>(); //updates.put("location/"+ pushId1 + "/geohash", geoHash.getGeoHashString()); //updates.put("location/"+ pushId1 + "/name", "테스트"); //updates.put("geofire/" + pushId + "/g", geoHash.getGeoHashString()); //updates.put("geofire/"+ pushId + "/l", Arrays.asList(37.260163, 127.024974)); //databaseReference.updateChildren(updates); progressBar.setProgress(50); SharedPreferences mPref = getSharedPreferences("isFirst", MODE_PRIVATE); Boolean bfirst = mPref.getBoolean("isFirst", true); progressBar.setProgress(100); if (bfirst && Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { SharedPreferences.Editor editor = mPref.edit(); editor.putBoolean("isFirst", false).apply(); Intent intent = new Intent(SplashActivity.this, PermissionActivity.class); SplashActivity.this.startActivity(intent); SplashActivity.this.finish(); Log.w("Splash", "first"); } else { Intent intent = new Intent(SplashActivity.this, MainActivity.class); SplashActivity.this.startActivity(intent); SplashActivity.this.finish(); } } }, 3000); } private void excelToList() { Workbook workbook = null; try { InputStream is = getBaseContext().getResources().getAssets().open("pois.xls"); workbook = Workbook.getWorkbook(is); if (workbook != null) { Sheet sheet = workbook.getSheet(0); if (sheet != null) { int nMaxColumn = sheet.getColumns(); int nRowStartIndex = 0; int nRowEndIndex = sheet.getColumn(nMaxColumn - 1).length - 1; int nColumnStartIndex = 0; listAdapter.open(); for (int nRow = nRowStartIndex + 1; nRow <= nRowEndIndex; nRow++) { String content_nm = sheet.getCell(nColumnStartIndex, nRow).getContents(); String coor_x = sheet.getCell(nColumnStartIndex + 1, nRow).getContents(); String coor_y = sheet.getCell(nColumnStartIndex + 2, nRow).getContents(); listAdapter.createList(content_nm, coor_x, coor_y); } listAdapter.close(); } else { Log.i(TAG, "Sheet is null!!"); } } else { Log.i(TAG, "WorkBook is null!!"); } } catch (Exception e) { e.printStackTrace(); } finally { if (workbook != null) { workbook.close(); } } } private void excelToWeather(){ Workbook workbook = null; try{ InputStream is = getBaseContext().getResources().getAssets().open("weathers.xls"); workbook = Workbook.getWorkbook(is); if (workbook != null) { Sheet sheet = workbook.getSheet(0); if (sheet != null) { int nMaxColumn = sheet.getColumns(); int nRowStartIndex = 0; int nRowEndIndex = sheet.getColumn(nMaxColumn - 1).length - 1; int nColumnStartIndex = 0; weatherDBHelper.open(); for (int nRow = nRowStartIndex - 1; nRow <= nRowEndIndex; nRow++) { String key = sheet.getCell(nColumnStartIndex, nRow).getContents(); String value = sheet.getCell(nColumnStartIndex + 1, nRow).getContents(); weatherDBHelper.createList(key, value); } weatherDBHelper.close(); } else { Log.i(TAG, "Sheet is null!!"); } }else{ Log.i(TAG, "Woorkbook is null!!!"); } }catch (Exception e){ e.printStackTrace(); }finally { if (workbook != null) { workbook.close(); } } } private void ListToFirebase() { try { DatabaseReference databaseReference = FirebaseDatabase.getInstance().getReference(); listAdapter = new ListAdapter(this); listAdapter.open(); Cursor cursor = listAdapter.fetchAllList(); cursor.moveToFirst(); try { while (!cursor.isAfterLast()){ String name = cursor.getString(cursor.getColumnIndex(listAdapter.KEY_CONTENT_NAME)); String lat = cursor.getString(cursor.getColumnIndex(listAdapter.KEY_COORDINATE_X)); String lng = cursor.getString(cursor.getColumnIndex(listAdapter.KEY_COORDINATE_Y)); String pushId = databaseReference.child("geofire").push().getKey(); geoFire = new GeoFire(databaseReference.child("geofire")); geoFire.setLocation(pushId, new GeoLocation(Double.parseDouble(lat),Double.parseDouble(lng))); GeoHash geoHash = new GeoHash(Double.parseDouble(lat),Double.parseDouble(lng)); Map<String, Object>updates = new HashMap<>(); updates.put("location/"+ pushId + "/geohash", geoHash.getGeoHashString()); updates.put("location/"+ pushId + "/name", name); updates.put("geofire/" + pushId + "/g", geoHash.getGeoHashString()); updates.put("geofire/"+ pushId + "/l", Arrays.asList(Double.parseDouble(lat),Double.parseDouble(lng))); databaseReference.updateChildren(updates); cursor.moveToNext(); } cursor.close(); listAdapter.close(); } catch (Exception e) { e.printStackTrace(); Toast.makeText(getApplicationContext(), "오류 발생" + e, Toast.LENGTH_LONG).show(); } } catch (Exception e) { e.printStackTrace(); Toast.makeText(getApplicationContext(), "오류 발생" + e, Toast.LENGTH_LONG).show(); } } }
45.355263
145
0.572188
394ed20f7679f665de2bd6c50138cd5a4984364d
3,083
package com.jlnu.lang.realtimeinfo.fragment; import android.os.Bundle; import android.support.v4.app.Fragment; import android.support.v4.view.ViewPager; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.Toolbar; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import com.jlnu.lang.realtimeinfo.R; import com.jlnu.lang.realtimeinfo.adapter.NewsViewPagerAdapter; import com.jlnu.lang.realtimeinfo.custom.ChildViewPager; import com.jlnu.lang.realtimeinfo.ui.PagerSlidingTabStrip; import java.util.ArrayList; import java.util.List; import butterknife.Bind; import butterknife.ButterKnife; /** * Created by qn on 2017/3/6. */ public class NewsFragment extends Fragment implements ChildViewPager.OnSingleTouchListener{ @Bind(R.id.news_vp) ViewPager newsVp; @Bind(R.id.tab_strip) PagerSlidingTabStrip tabStrip; @Bind(R.id.toolbar) Toolbar toolbar; private NewsViewPagerAdapter mNewsVpAdapter; private String[] keys; private List<Fragment> mFragments; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); initData(); } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View view = inflater.inflate(R.layout.fragment_news, container, false); ButterKnife.bind(this, view); initViews(); return view; } private void initData() { keys = new String[]{"头条", "社会", "国内", "国际", "娱乐", "体育", "军事", "科技", "财经", "时尚"}; mFragments = new ArrayList<>(); for (String key : keys) { NewsItemFragment fragment = new NewsItemFragment(); Bundle bundle = new Bundle(); bundle.putString("news_key", key); fragment.setArguments(bundle); mFragments.add(fragment); } } private void initViews() { initToolbar(); initViewPager(); initTabStrip(); } private void initToolbar() { toolbar.setBackgroundColor(getResources().getColor(R.color.toolbar_black)); toolbar.setTitle(""); ((AppCompatActivity)getActivity()).setSupportActionBar(toolbar); } private void initViewPager() { mNewsVpAdapter = new NewsViewPagerAdapter(getFragmentManager()); mNewsVpAdapter.setData(keys, mFragments); newsVp.setAdapter(mNewsVpAdapter); newsVp.setOffscreenPageLimit(1); } private void initTabStrip() { tabStrip.setViewPager(newsVp); tabStrip.setOnPageChangeListener(new ViewPager.OnPageChangeListener() { @Override public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) { } @Override public void onPageSelected(int position) { } @Override public void onPageScrollStateChanged(int state) { } }); } @Override public void onSingleTouch() { } }
28.284404
103
0.668505
5ae0d52658fba1cdcf215c5c893260302a6716e3
474
package com.jn.agileway.zip.format; public class ArchiveFormatNotFoundException extends RuntimeException{ public ArchiveFormatNotFoundException() { super(); } public ArchiveFormatNotFoundException(String message) { super(message); } public ArchiveFormatNotFoundException(String message, Throwable cause) { super(message, cause); } public ArchiveFormatNotFoundException(Throwable cause) { super(cause); } }
23.7
76
0.706751
31f9f857830fbf331511f29e72b1ef5442343263
1,382
/* * 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.ignite.cluster; import org.jetbrains.annotations.Nullable; /** * Cluster start node result information. */ public interface ClusterStartNodeResult { /** * Gets host name. * * @return Host name. */ public String getHostName(); /** * Gets result of success or failure. * * @return Success or failure. <code>True</code> if success. */ public boolean isSuccess(); /** * Gets error message if any. * * @return Error massage. */ @Nullable public String getError(); }
29.404255
75
0.688857
784ee8faddfef48399537012a4cbf604776b4561
10,619
/*L * Copyright SAIC * * Distributed under the OSI-approved BSD 3-Clause License. * See http://ncip.github.com/cabio/LICENSE.txt for details. */ package gov.nih.nci.system.dao.impl.search.service; import gov.nih.nci.indexgen.SearchAPIProperties; import gov.nih.nci.search.SearchResult; import gov.nih.nci.search.SummaryResult; import gov.nih.nci.search.Sort; import gov.nih.nci.system.dao.impl.search.FreestyleLMException; import java.io.File; import java.io.FileFilter; import java.io.IOException; import java.util.ArrayList; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import org.apache.log4j.Logger; import org.apache.lucene.analysis.standard.StandardAnalyzer; import org.apache.lucene.document.Document; import org.apache.lucene.document.Field; import org.apache.lucene.queryParser.MultiFieldQueryParser; import org.apache.lucene.queryParser.ParseException; import org.apache.lucene.queryParser.QueryParser; import org.apache.lucene.search.Hits; import org.apache.lucene.search.IndexSearcher; import org.apache.lucene.search.ParallelMultiSearcher; import org.apache.lucene.search.Query; import org.apache.lucene.search.Searcher; import org.apache.lucene.search.SortField; import org.apache.lucene.store.FSDirectory; /** * Performs full text searches on a Lucene-based index. * * @author Shaziya Muhsin * @author <a href="mailto:rokickik@mail.nih.gov">Konrad Rokicki</a> */ public class FullTextSearch implements Searchable { private static final Logger log = Logger.getLogger(FullTextSearch.class); private static final SearchAPIProperties prop = SearchAPIProperties.getInstance(); /** * Performs a full text search for a given String. */ public List<SearchResult> query(String searchString) throws FreestyleLMException { return query(searchString, null, new Sort()); } /** * Performs a text based search for a given String. * Allows sorting of the results. */ public List<SearchResult> query(String searchString, Sort sort) throws FreestyleLMException { return query(searchString, null, sort); } /** * Performs a text based search for a given String in the given class. */ public List<SearchResult> query(String searchString, String className) throws FreestyleLMException { return query(searchString, className, new Sort()); } /** * Performs a text based search for a given String in the given class. * Allows sorting of the results. */ public List<SearchResult> query(String searchString, String className, Sort sort) throws FreestyleLMException { return luceneSearch(searchString, className, sort, false); } /** * Performs a text based search for a given String. */ public List<SummaryResult> querySummary(String searchString) throws FreestyleLMException { return luceneSearch(searchString, null, null, true); } /** * Returns the index location. * @return * @throws Exception */ private String getIndexLocation() { String indexFileLocation = prop.getIndexLocation(); log.debug("Index Location: "+ indexFileLocation); return indexFileLocation; } /** * Returns a list of subdirectories located within the given root directory. * @param indexRoot * @return * @throws Exception */ private File[] getDirectoryList(String indexRoot) { File dir = new File(indexRoot); FileFilter fileFilter = new FileFilter(){ public boolean accept(File file){ return file.isDirectory(); } }; return dir.listFiles(fileFilter); } /** * Creates a ParellelMultiSearcher for all the indexes. * @return * @throws Exception */ private Searcher getIndexSearcher() throws FreestyleLMException { File[] files = getDirectoryList(getIndexLocation()); IndexSearcher[] searchers = new IndexSearcher[files.length]; try { for(int i=0; i< files.length; i++){ searchers[i] = new IndexSearcher(FSDirectory.getDirectory(files[i])); } return new ParallelMultiSearcher(searchers); } catch (IOException e) { throw new FreestyleLMException("Error creating index searcher",e); } } /** * Creates a Searcher for the given class. * @return * @throws Exception */ private Searcher getIndexSearcher(Class<?> clazz) throws FreestyleLMException { String indexFileLocation = prop.getIndexLocation(); try { return new IndexSearcher(indexFileLocation+"/"+clazz.getName()); } catch (IOException e) { throw new FreestyleLMException("Error creating index searcher",e); } } /** * Performs a search and returns the Hits. * @param searchString * @param className * @param sort * @return * @throws FreestyleLMException */ private List luceneSearch(String searchString, String className, Sort sort, boolean summarize) throws FreestyleLMException { List results = null; Searcher searcher = null; if (className != null) { try { searcher = getIndexSearcher(Class.forName(className)); } catch (ClassNotFoundException e) { throw new FreestyleLMException("No such class: "+className); } } else { searcher = getIndexSearcher(); } try { QueryParser parser = new MultiFieldQueryParser( prop.getIndexedFields(), new StandardAnalyzer()); Query query = parser.parse(searchString); Hits hits = null; if(sort != null && sort.getSortByClassName()) { SortField field = new SortField("_hibernate_class", SortField.STRING, !sort.getAscOrder()); hits = searcher.search(query, new org.apache.lucene.search.Sort(field)); } else { hits = searcher.search(query); } if (summarize) { results = getSearchSummary(hits, searchString); } else { results = getSearchResults(hits, searchString); } searcher.close(); } catch (ParseException e) { throw new FreestyleLMException( "Error parsing search string: "+searchString,e); } catch (IOException e) { throw new FreestyleLMException( "Error accessing FreestyleLM indexes", e); } return results; } /** * Returns a List of SearchResult objects for the specified Hits * @param hits * @param searchString * @return * @throws Exception */ private List<SummaryResult> getSearchSummary(Hits hits, String searchString) throws FreestyleLMException { Map<String, SummaryResult> counts = new HashMap<String, SummaryResult>(); for(int i=0; i<hits.length(); i++) { Document doc = null; try { doc = hits.doc(i); } catch (IOException e) { throw new FreestyleLMException("Error retrieving document #" +i+" for search "+searchString,e); } String className = doc.getField("_hibernate_class").stringValue(); SummaryResult count = null; if (!counts.containsKey(className)) { count = new SummaryResult(); count.setClassName(className); counts.put(className, count); } else { count = counts.get(className); } count.setHits(count.getHits() + 1); } List<SummaryResult> results = new ArrayList<SummaryResult>(); results.addAll(counts.values()); return results; } /** * Returns a List of SearchResult objects for the specified Hits * @param hits * @param searchString * @return * @throws Exception */ public List<SearchResult> getSearchResults(Hits hits, String searchString) throws FreestyleLMException { List<SearchResult> resultList = new ArrayList<SearchResult>(); for(int i=0; i<hits.length(); i++) { Document doc = null; try { doc = hits.doc(i); } catch (IOException e) { throw new FreestyleLMException("Error retrieving document #" +i+" for search "+searchString,e); } int num = i +1; SearchResult result = getSearchResult(doc); result.setKeyword(searchString); result.setHit(num); resultList.add(result); } return resultList; } /** * Returns a SearchResult object for a given document * @param doc * @param i * @param keyword * @return */ private SearchResult getSearchResult(Document doc) { SearchResult result = new SearchResult(); HashMap<String,String> properties = new HashMap<String, String>(); for(Iterator it = doc.getFields().iterator(); it.hasNext(); ){ Field field = (Field)it.next(); properties.put(field.name(), field.stringValue()); if(field.name().equalsIgnoreCase("_hibernate_class")){ result.setClassName(field.stringValue()); } if(field.name().equalsIgnoreCase("id")){ result.setId(field.stringValue()); } } result.setProperties(properties); return result; } }
33.184375
87
0.569074
cecf1fd9e3f4502c5b86105c1d05823c29a7427c
12,857
/* * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER. * * Copyright 2014 Oracle and/or its affiliates. All rights reserved. * * Oracle and Java are registered trademarks of Oracle and/or its affiliates. * Other names may be trademarks of their respective owners. * * The contents of this file are subject to the terms of either the GNU * General Public License Version 2 only ("GPL") or the Common * Development and Distribution License("CDDL") (collectively, the * "License"). You may not use this file except in compliance with the * License. You can obtain a copy of the License at * http://www.netbeans.org/cddl-gplv2.html * or nbbuild/licenses/CDDL-GPL-2-CP. See the License for the * specific language governing permissions and limitations under the * License. When distributing the software, include this License Header * Notice in each file and include the License file at * nbbuild/licenses/CDDL-GPL-2-CP. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the GPL Version 2 section of the License file that * accompanied this code. If applicable, add the following below the * License Header, with the fields enclosed by brackets [] replaced by * your own identifying information: * "Portions Copyrighted [year] [name of copyright owner]" * * If you wish your version of this file to be governed by only the CDDL * or only the GPL Version 2, indicate your decision by adding * "[Contributor] elects to include this software in this distribution * under the [CDDL or GPL Version 2] license." If you do not indicate a * single choice of license, a recipient has the option to distribute * your version of this file under either the CDDL, the GPL Version 2 or * to extend the choice of license to its licensees as provided above. * However, if you add GPL Version 2 code and therefore, elected the GPL * Version 2 license, then the option applies only if the new code is * made subject to such option by the copyright holder. * * Contributor(s): * * Portions Copyrighted 2014 Sun Microsystems, Inc. */ package org.netbeans.modules.remote.impl.fs; import java.io.BufferedReader; import java.io.File; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.concurrent.ExecutionException; import java.util.concurrent.Future; import org.netbeans.modules.nativeexecution.api.ExecutionEnvironment; import org.netbeans.modules.nativeexecution.api.NativeProcess; import org.netbeans.modules.nativeexecution.api.NativeProcessBuilder; import org.netbeans.modules.nativeexecution.api.util.CommonTasksSupport; import org.netbeans.modules.nativeexecution.api.util.ConnectionManager; import org.netbeans.modules.nativeexecution.api.util.ProcessUtils; import org.netbeans.modules.remote.impl.RemoteLogger; import org.openide.util.RequestProcessor; /** */ public class RemoteFileZipper { private final ExecutionEnvironment execEnv; private final RemoteFileSystem fileSystem; private final RequestProcessor rp; private final Map<String, Worker> workers = new HashMap<>(); private final Object workersLock = new Object(); public RemoteFileZipper(ExecutionEnvironment execEnv, RemoteFileSystem fileSystem) { this.execEnv = execEnv; this.fileSystem = fileSystem; // throughput is set to 1 to prevent making all channels busy for a long time rp = new RequestProcessor(getClass().getSimpleName() + ' ' + execEnv, 1); //NOI18N } public void schedule(File zipFile, File zipPartFile, String path, Collection<String> extensions) { synchronized (workersLock) { Worker worker = workers.get(path); if (worker == null) { worker = new Worker(zipFile, zipPartFile, path, extensions); workers.put(path, worker); rp.post(worker); } else { // TODO: consider whatto do } } } private class Worker implements Runnable { private final File zipFile; private final File zipPartFile; private final String path; private final Collection<String> extensions; public Worker(File zipFile, File zipPartFile, String path, Collection<String> extensions) { this.zipFile = zipFile; this.zipPartFile = zipPartFile; this.path = path; this.extensions = extensions; } @Override public void run() { if (!ConnectionManager.getInstance().isConnectedTo(execEnv)) { return; } String oldName = Thread.currentThread().getName(); Thread.currentThread().setName(RemoteFileZipper.class.getSimpleName() + ' ' + execEnv + ": zipping " + path); //NOI18N try { zip(); } finally { Thread.currentThread().setName(oldName); synchronized (workersLock) { workers.remove(path); } } } private void zip() { long time; // // Zip directory on remote host // time = System.currentTimeMillis(); StringBuilder script = new StringBuilder("TZ=UTC; export TZ; F=`mktemp /tmp/rfs_warmup_XXXXXXXX.zip`; if [ $? -eq 0 ]; then echo ZIP=$F; rm -rf $F; "); //NOI18N boolean all; if (extensions == null || extensions.isEmpty()) { all = true; } else { String next = extensions.iterator().next(); all = (next == null) || next.equals("*"); // NOI18N } if (all) { script.append("zip -rq $F \"").append(path).append("\""); // NOI18N } else { script.append("find ").append(path); // NOI18N boolean first = true; for (String ext : extensions) { if (first) { first = false; } else { script. append(" -o "); // NOI18N } script. append(" -name \"*.").append(ext).append("\""); // NOI18N } script.append(" | xargs zip -rq $F "); // NOI18N } script.append("; echo RC=$?; fi"); //NOI18N NativeProcessBuilder processBuilder = NativeProcessBuilder.newProcessBuilder(execEnv); processBuilder.setExecutable("sh").setWorkingDirectory("/").setArguments("-c", script.toString()); //NOI18N NativeProcess process = null; try { process = processBuilder.call(); } catch (IOException ex) { RemoteLogger.fine(ex); RemoteLogger.info("Warmup: error zipping {0}:{1} can't launch remote process", //NOI18N execEnv, path); return; } Future<List<String>> stderrFuture = ProcessUtils.readProcessErrorAsync(process); String remoteZipPath = null; int rc = -1; // Output should be like the following: // ZIP=/tmp/tmp.xLDawcYe5M // RC=0 try (BufferedReader rdr = new BufferedReader(new InputStreamReader(process.getInputStream()))) { String line; while ((line = rdr.readLine()) != null) { if (remoteZipPath == null) { if (line.startsWith("ZIP=")) { //NOI18N remoteZipPath = line.substring(4); fileSystem.deleteOnDisconnect(remoteZipPath); } else { // NOI18N RemoteLogger.info("Warmup: error zipping {0} at {1}: unexpected output: {2}", //NOI18N path, execEnv, line); // don't return here, read the rest of the output first } } else if (line.startsWith("RC=")) { //NOI18N try { rc = Integer.parseInt(line.substring(3)); } catch (NumberFormatException ex) { RemoteLogger.info("Warmup: error zipping {0} at {1}: unexpected output: {2}", //NOI18N path, execEnv, line); // don't return here, read the rest of the output first } } } } catch (IOException ex) { RemoteLogger.fine(ex); RemoteLogger.info("Warmup: error zipping {0}:{1} error reading script output: {2}", //NOI18N execEnv, path, ex.getLocalizedMessage()); } if (rc == -1 || remoteZipPath == null) { // unexpected process output or its absence // error message should be printed by the code above return; } int shrc = -1; List<String> stderr = Collections.emptyList(); try { shrc = process.waitFor(); stderr = stderrFuture.get(); } catch (InterruptedException | ExecutionException ex) { RemoteLogger.fine(ex); RemoteLogger.info("Warmup: error zipping {0}:{1} {2} {3}", //NOI18N execEnv, path, ex.getClass().getSimpleName(), ex.getLocalizedMessage()); return; } if (shrc != 0 || rc != 0) { RemoteLogger.info("Warmup: error zipping {0}:{1} {2}", //NOI18N execEnv, path, merge(stderr)); return; } RemoteLogger.fine("zipping {0} at {1} took {2}", //NOI18N path, execEnv, System.currentTimeMillis() - time); try { // // Download zip from remote host // time = System.currentTimeMillis(); zipPartFile.getParentFile().mkdirs(); Future<Integer> task = CommonTasksSupport.downloadFile(remoteZipPath, execEnv, zipPartFile.getAbsolutePath(), new PrintWriter(System.err)); rc = -1; try { rc = task.get(); } catch (InterruptedException ex) { // nothing } catch (ExecutionException ex) { ex.printStackTrace(System.err); } if (rc != 0) { if (rc != 0) { RemoteLogger.info("Warmup: error downloading {0}:{1} to {2}, rc={3}", //NOI18N execEnv, remoteZipPath, zipPartFile.getAbsolutePath(), rc); return; } } RemoteLogger.fine("downloading {0}:{1} to {2} took {3} ms", //NOI18N execEnv, path, zipPartFile.getAbsolutePath(), System.currentTimeMillis() - time); if (!zipPartFile.renameTo(zipFile)) { RemoteLogger.info("Warmup: error renaming {0} to {1}", //NOI18N zipPartFile.getAbsolutePath(), zipFile.getAbsolutePath()); } } finally { // Remove temp. zip file from remote host time = System.currentTimeMillis(); Future<Integer> task = CommonTasksSupport.rmFile(execEnv, remoteZipPath, new PrintWriter(System.err)); rc = -1; try { rc = task.get(); } catch (InterruptedException ex) { // nothing } catch (ExecutionException ex) { ex.printStackTrace(System.err); } RemoteLogger.fine("removing {0} at {1} finished with rc={2} and took {3} ms", //NOI18N remoteZipPath, execEnv, rc, System.currentTimeMillis() - time); } } } private static String merge(List<String> outputLines) { StringBuilder sb = new StringBuilder(); if (outputLines != null) { for (String line : outputLines) { if (sb.length() > 0) { sb.append('\n'); //NOI18N } sb.append(line); } } return sb.toString(); } }
43.435811
172
0.549195
1ab3c106dec9d79c3f7eadd296e1505cda59bf65
4,240
package edu.utah.bmi.simple.gui.task; import edu.utah.bmi.nlp.core.GUITask; import edu.utah.bmi.nlp.sql.EDAO; import edu.utah.bmi.nlp.sql.RecordRow; import edu.utah.bmi.nlp.sql.RecordRowIterator; import edu.utah.bmi.simple.gui.core.ExcelExporter2; import edu.utah.bmi.simple.gui.entry.TaskFX; import edu.utah.bmi.simple.gui.entry.TasksFX; import javafx.application.Platform; import org.apache.commons.io.FileUtils; import java.io.File; import java.io.IOException; import java.text.SimpleDateFormat; import java.util.Date; /** * @author Jianlin Shi * Created on 2/13/17. */ @Deprecated //because the outputs have been split to multiple tables. this won't work in new table structure. public class Export2Excel2 extends GUITask { protected String outputDB, annotator, outputTable; private File exportDir; private String sql, count; private int sampleSize = 0; protected Export2Excel2() { } public Export2Excel2(TasksFX tasks) { initiate(tasks); } protected void initiate(TasksFX tasks, String... paras) { if (!Platform.isFxApplicationThread()) { guiEnabled = false; } updateGUIMessage("Initiate configurations.."); TaskFX config = tasks.getTask("settings"); outputDB = config.getValue(ConfigKeys.writeDBConfigFileName); outputTable = config.getValue(ConfigKeys.snippetResultTableName); config = tasks.getTask(ConfigKeys.maintask); annotator = config.getValue(ConfigKeys.annotator); config = tasks.getTask("export"); String configString = config.getValue(ConfigKeys.excelDir); sql = config.getValue("excel/sql"); String value = config.getValue("excel/sampleSize").trim(); sampleSize = value.length() > 0 ? Integer.parseInt(value) : sampleSize; // count = config.getValue("excel/count"); exportDir = new File(configString); if (!exportDir.exists()) { try { FileUtils.forceMkdir(exportDir); } catch (IOException e) { e.printStackTrace(); } } } @Override protected Object call() throws Exception { GUITask task = this; if (!new File(outputDB).exists()) { updateGUIMessage("Database " + outputDB + " not exist"); return null; } // Update UI here. boolean res = false; EDAO dao = EDAO.getInstance(new File(outputDB)); if (sql.toLowerCase().indexOf("where") == -1) { sql += " WHERE RUN_ID=" + getLastRunIdofAnnotator(dao, outputTable, annotator); } String tmp = sql.toLowerCase(); count = "SELECT COUNT(*) " + sql.substring(tmp.indexOf(" from ")) + " AND TYPE LIKE '%_Doc'"; RecordRow recordRow = dao.queryRecord(count); int total = Integer.parseInt(recordRow.getValueByColumnId(1) + ""); if (sampleSize > 0 && total > sampleSize) total = sampleSize; File excel = new File(exportDir, "exported_" + annotator + "_" + new SimpleDateFormat("yyyy_MM_dd_HH_mm").format(new Date()) + ".xlsx"); ExcelExporter2 excelExporter = new ExcelExporter2(dao, sql, total, task); excelExporter.export(excel); updateGUIProgress(1, 1); return null; } public int getLastRunIdofAnnotator(EDAO dao, String outputTable, String annotator) { int id = -1; RecordRowIterator recordRowIter = dao.queryRecordsFromPstmt("maxRunIDofAnnotator", outputTable, annotator); if (recordRowIter.hasNext()) { RecordRow recordRow = recordRowIter.next(); if (recordRow != null && recordRow.getValueByColumnId(1) != null) id = (int) recordRow.getValueByColumnId(1); } return id; } public int getLastLogRunId(EDAO dao, String annotator) { int id = -1; RecordRowIterator recordRowIter = dao.queryRecordsFromPstmt("lastLogRunID", annotator); if (recordRowIter.hasNext()) { RecordRow recordRow = recordRowIter.next(); if (recordRow != null) id = (int) recordRow.getValueByColumnId(1); } return id; } }
31.176471
115
0.633726
434bf71bed2c202cf8ee2d0bbab174897c2aeb27
2,293
package com.redhat.cloud.notifications.templates; import com.redhat.cloud.notifications.models.EmailSubscriptionType; import io.quarkus.qute.CheckedTemplate; import io.quarkus.qute.TemplateInstance; // Name needs to be "Compliance" to read templates from resources/templates/Compliance public class Compliance implements EmailTemplate { private static final String COMPLIANCE_BELOW_THRESHOLD = "compliance-below-threshold"; private static final String REPORT_UPLOAD_FAILED = "report-upload-failed"; @Override public TemplateInstance getTitle(String eventType, EmailSubscriptionType type) { if (type == EmailSubscriptionType.INSTANT) { if (eventType.equals(COMPLIANCE_BELOW_THRESHOLD)) { return Templates.complianceBelowThresholdEmailTitle(); } else if (eventType.equals(REPORT_UPLOAD_FAILED)) { return Templates.reportUploadFailedEmailTitle(); } } return Templates.dailyEmailTitle(); } @Override public TemplateInstance getBody(String eventType, EmailSubscriptionType type) { if (type == EmailSubscriptionType.INSTANT) { if (eventType.equals(COMPLIANCE_BELOW_THRESHOLD)) { return Templates.complianceBelowThresholdEmailBody(); } else if (eventType.equals(REPORT_UPLOAD_FAILED)) { return Templates.reportUploadFailedEmailBody(); } } return Templates.dailyEmailBody(); } @Override public boolean isSupported(String eventType, EmailSubscriptionType type) { return true; } @Override public boolean isEmailSubscriptionSupported(EmailSubscriptionType type) { return true; } @CheckedTemplate(requireTypeSafeExpressions = false) public static class Templates { public static native TemplateInstance complianceBelowThresholdEmailTitle(); public static native TemplateInstance reportUploadFailedEmailTitle(); public static native TemplateInstance complianceBelowThresholdEmailBody(); public static native TemplateInstance reportUploadFailedEmailBody(); public static native TemplateInstance dailyEmailTitle(); public static native TemplateInstance dailyEmailBody(); } }
34.742424
90
0.718273
21b438e136cde1de997f3b587af29ea385260c73
92
package com.acme.architecture.testing.example.dummy; public class DummyExampleRequest { }
15.333333
52
0.815217
a5db834e24b4c3c7e6256a32fd7bb76d218ddd9b
1,480
package com.ps.webservice.data; import java.lang.System.Logger; import java.sql.*; import org.springframework.stereotype.Component; @Component public class JDPCSqlLiteConnection { Connection connect = null; //"jdbc:mysql:https://s3.amazonaws.com/paeonsystemdb/paeonsystems.db"; //private final String urlConnection = "jdbc:mysql://paeonsystemsdb.c7vhptgacbd2.us-east-1.rds.amazonaws.com:3306/paeonsystemsdb?user=psdb&password=paeonsystems12345"; //jdbc:awsathena://AwsRegion=[Region];UID=[AccessKey];PWD= [SecretKey];S3OutputLocation=[Output];[Property1]=[Value1]; [Property2]=[Value2] public Connection getDatabaseConnection() { final String urlHost = "//paeonsystemsdb.c7vhptgacbd2.us-east-1.rds.amazonaws.com"; final String userName = "psdb"; final String password = "cookie92"; final String database = "paeonsystemsdb"; try { if(!isRetryFailed(connect)) { connect = DriverManager.getConnection("jdbc:mysql:"+urlHost+":3306/"+database+"?user="+userName+"&password="+password +"?characterEncoding=utf8"); } } catch(Exception e) { System.out.println(e.getCause().getClass()+ "" + e.getMessage()); } return connect; } private boolean isRetryFailed(Connection connect) throws Exception { boolean isTimedOut = true; int timeOut = DriverManager.getLoginTimeout(); if( connect == null || timeOut > 0) { //connect = DriverManager.getConnection(urlConnection); isTimedOut = false; } return isTimedOut; } }
32.173913
168
0.727703
a338871a2e86a3c972258b60bcfd4e657e0d40e6
781
package org.fastlight.aop.annotation; import java.lang.annotation.Annotation; import java.lang.annotation.Documented; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; import org.fastlight.aop.handler.FastAspectHandler; /** * 自动生成 SPI 文件 * * @author ychost@outlook.com * @date 2021-03-28 */ @Retention(RetentionPolicy.SOURCE) @Target({ElementType.TYPE}) @Documented public @interface FastAspectAround { /** * 会自动生成方法覆盖 support,只要方法或者类包含该注解就运行标注的 handler */ Class<? extends Annotation> support() default FastNone.class; /** * 指定切面的拦截顺序,优先取 override 的 order() 方法,然后取这个 */ int order() default FastAspectHandler.DEFAULT_ORDER; }
24.40625
65
0.74904
41a6075b009dcd4f6635b26a15d9613ee2a75faa
354
package org.murphy.consumer; import org.murphy.service.DataService; public class ClientMain { public static void main(String[] args) { Client client = new Client("localhost", 8888); DataService proxyObject = client.getProxyObject(DataService.class); System.out.println(proxyObject.getData(new Integer(1234567890))); } }
29.5
75
0.717514
e53fa1cb9d084359d2376db9aebff1b66d40ca1b
1,300
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package exchangecurrency; /** University of Maryland: University College CMSC495 Group 2 Class : ExchangeCurrencyDB Created on : Apr 23, 2016 Author : Brandon Trexler */ public class Currency { private String code; private Double rate; private String lastUpdated; //Default constructor public Currency(){ } //Real constructor public Currency(String code, Double rate, String lastUpdated) { this.code = code; this.rate = rate; this.lastUpdated = lastUpdated; } //Setters public void setCode(String code) { this.code = code; } public void setRate(Double rate) { this.rate = rate; } public void setDate(String lastUpdated) { this.lastUpdated = lastUpdated; } //Getters public String getCode() { return this.code; } public Double getRate() { return this.rate; } public String getLastUpdated() { return this.lastUpdated; } }
22.033898
80
0.585385
1e3b9336782845dcfca456929cf7327b81618a2b
10,377
/* * Copyright 2019 GridGain Systems, Inc. and Contributors. * * Licensed under the GridGain Community Edition License (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.gridgain.com/products/software/community-edition/gridgain-community-edition-license * * 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.ignite.internal.processors.cache.distributed.dht; import java.util.ArrayList; import java.util.Collection; import java.util.UUID; import org.apache.ignite.Ignite; import org.apache.ignite.IgniteCache; import org.apache.ignite.cache.CachePeekMode; import org.apache.ignite.cache.CacheWriteSynchronizationMode; import org.apache.ignite.cache.affinity.Affinity; import org.apache.ignite.cache.affinity.rendezvous.RendezvousAffinityFunction; import org.apache.ignite.cluster.ClusterNode; import org.apache.ignite.configuration.CacheConfiguration; import org.apache.ignite.configuration.IgniteConfiguration; import org.apache.ignite.internal.IgniteKernal; import org.apache.ignite.internal.processors.cache.distributed.near.GridNearCacheAdapter; import org.apache.ignite.internal.util.typedef.F; import org.apache.ignite.internal.util.typedef.G; import org.apache.ignite.lang.IgniteBiTuple; import org.apache.ignite.testframework.MvccFeatureChecker; import org.apache.ignite.testframework.junits.common.GridCommonAbstractTest; import org.apache.ignite.transactions.Transaction; import org.junit.Test; import static org.apache.ignite.cache.CacheAtomicityMode.TRANSACTIONAL; import static org.apache.ignite.cache.CacheMode.PARTITIONED; /** * Unit tests for dht entry. */ public class GridCacheDhtEntrySelfTest extends GridCommonAbstractTest { /** Grid count. */ private static final int GRID_CNT = 2; /** {@inheritDoc} */ @Override protected IgniteConfiguration getConfiguration(String igniteInstanceName) throws Exception { IgniteConfiguration cfg = super.getConfiguration(igniteInstanceName); CacheConfiguration cacheCfg = defaultCacheConfiguration(); cacheCfg.setCacheMode(PARTITIONED); cacheCfg.setAffinity(new RendezvousAffinityFunction(false, 10)); cacheCfg.setBackups(0); cacheCfg.setWriteSynchronizationMode(CacheWriteSynchronizationMode.FULL_SYNC); cacheCfg.setAtomicityMode(TRANSACTIONAL); cfg.setCacheConfiguration(cacheCfg); return cfg; } /** {@inheritDoc} */ @Override protected void beforeTestsStarted() throws Exception { super.beforeTestsStarted(); startGridsMultiThreaded(GRID_CNT); } /** {@inheritDoc} */ @SuppressWarnings({"SizeReplaceableByIsEmpty"}) @Override protected void beforeTest() throws Exception { MvccFeatureChecker.skipIfNotSupported(MvccFeatureChecker.Feature.NEAR_CACHE); for (int i = 0; i < GRID_CNT; i++) { assert near(grid(i)).size() == 0 : "Near cache size is not zero for grid: " + i; assert dht(grid(i)).size() == 0 : "DHT cache size is not zero for grid: " + i; assert near(grid(i)).localSize() == 0 : "Near cache is not empty for grid: " + i; assert dht(grid(i)).isEmpty() : "DHT cache is not empty for grid: " + i; } } /** {@inheritDoc} */ @Override protected void afterTest() throws Exception { for (int i = 0; i < GRID_CNT; i++) { near(grid(i)).removeAll(); assertEquals("Near cache size is not zero for grid: " + i, 0, near(grid(i)).size()); assertEquals("DHT cache size is not zero for grid: " + i, 0, dht(grid(i)).size()); assert near(grid(i)).localSize() == 0 : "Near cache is not empty for grid: " + i; assert dht(grid(i)).isEmpty() : "DHT cache is not empty for grid: " + i; } for (int i = 0; i < GRID_CNT; i++) { Transaction tx = grid(i).transactions().tx(); if (tx != null) tx.close(); } } /** * @param g Grid. * @return Near cache. */ private IgniteCache<Integer, String> near(Ignite g) { return g.cache(DEFAULT_CACHE_NAME); } /** * @param g Grid. * @return Dht cache. */ @SuppressWarnings({"unchecked"}) private GridDhtCacheAdapter<Integer, String> dht(Ignite g) { return ((GridNearCacheAdapter)((IgniteKernal)g).internalCache(DEFAULT_CACHE_NAME)).dht(); } /** * @param nodeId Node ID. * @return Grid. */ private Ignite grid(UUID nodeId) { return G.ignite(nodeId); } /** @throws Exception If failed. */ @Test public void testClearWithReaders() throws Exception { Integer key = 1; IgniteBiTuple<ClusterNode, ClusterNode> t = getNodes(key); ClusterNode primary = t.get1(); ClusterNode other = t.get2(); IgniteCache<Integer, String> near0 = near(grid(primary.id())); IgniteCache<Integer, String> near1 = near(grid(other.id())); assert near0 != near1; GridDhtCacheAdapter<Integer, String> dht0 = dht(grid(primary.id())); GridDhtCacheAdapter<Integer, String> dht1 = dht(grid(other.id())); // Put on primary node. String val = "v1"; near0.put(key, val); GridDhtCacheEntry e0 = (GridDhtCacheEntry)dht0.peekEx(key); GridDhtCacheEntry e1 = (GridDhtCacheEntry)dht1.peekEx(key); assert e0 == null || e0.readers().isEmpty(); assert e1 == null || e1.readers().isEmpty(); // Get value on other node. assertEquals(val, near1.get(key)); e0 = (GridDhtCacheEntry)dht0.peekEx(key); e1 = (GridDhtCacheEntry)dht1.peekEx(key); assert e0 != null; assert e0.readers().contains(other.id()); assert e1 == null || e1.readers().isEmpty(); assert !internalCache(near0).clearLocally(key); assertEquals(1, near0.localSize(CachePeekMode.ALL)); assertEquals(1, dht0.size()); assertEquals(1, near1.localSize(CachePeekMode.ALL)); assertEquals(0, dht1.size()); } /** @throws Exception If failed. */ @Test public void testRemoveWithReaders() throws Exception { Integer key = 1; IgniteBiTuple<ClusterNode, ClusterNode> t = getNodes(key); ClusterNode primary = t.get1(); ClusterNode other = t.get2(); IgniteCache<Integer, String> near0 = near(grid(primary.id())); IgniteCache<Integer, String> near1 = near(grid(other.id())); assert near0 != near1; GridDhtCacheAdapter<Integer, String> dht0 = dht(grid(primary.id())); GridDhtCacheAdapter<Integer, String> dht1 = dht(grid(other.id())); // Put on primary node. String val = "v1"; near0.put(key, val); GridDhtCacheEntry e0 = (GridDhtCacheEntry)dht0.peekEx(key); GridDhtCacheEntry e1 = (GridDhtCacheEntry)dht1.peekEx(key); assert e0 == null || e0.readers().isEmpty(); assert e1 == null || e1.readers().isEmpty(); // Get value on other node. assertEquals(val, near1.get(key)); e0 = (GridDhtCacheEntry)dht0.peekEx(key); e1 = (GridDhtCacheEntry)dht1.peekEx(key); assert e0 != null; assert e0.readers().contains(other.id()); assert e1 == null || e1.readers().isEmpty(); assert near0.remove(key); assertEquals(0, near0.size()); assertEquals(0, dht0.size()); assertEquals(0, near1.size()); assertEquals(0, dht1.size()); } /** @throws Exception If failed. */ @Test public void testEvictWithReaders() throws Exception { Integer key = 1; IgniteBiTuple<ClusterNode, ClusterNode> t = getNodes(key); ClusterNode primary = t.get1(); ClusterNode other = t.get2(); IgniteCache<Integer, String> near0 = near(grid(primary.id())); IgniteCache<Integer, String> near1 = near(grid(other.id())); assert near0 != near1; GridDhtCacheAdapter<Integer, String> dht0 = dht(grid(primary.id())); GridDhtCacheAdapter<Integer, String> dht1 = dht(grid(other.id())); // Put on primary node. String val = "v1"; near0.put(key, val); GridDhtCacheEntry e0 = (GridDhtCacheEntry)dht0.peekEx(key); GridDhtCacheEntry e1 = (GridDhtCacheEntry)dht1.peekEx(key); assert e0 == null || e0.readers().isEmpty(); assert e1 == null || e1.readers().isEmpty(); // Get value on other node. assertEquals(val, near1.get(key)); e0 = (GridDhtCacheEntry)dht0.peekEx(key); e1 = (GridDhtCacheEntry)dht1.peekEx(key); assert e0 != null; assert e0.readers().contains(other.id()); assert e1 == null || e1.readers().isEmpty(); assert !e0.evictInternal(dht0.nextVersion(), null, false); assertEquals(1, near0.localSize(CachePeekMode.ALL)); assertEquals(1, dht0.localSize(null)); assertEquals(1, near1.localSize(CachePeekMode.ALL)); assertEquals(0, dht1.localSize(null)); assert !e0.evictInternal(dht0.nextVersion(), null, false); assertEquals(1, near0.localSize(CachePeekMode.ALL)); assertEquals(1, dht0.localSize(null)); assertEquals(1, near1.localSize(CachePeekMode.ALL)); assertEquals(0, dht1.localSize(null)); } /** * @param key Key. * @return For the given key pair {primary node, some other node}. */ private IgniteBiTuple<ClusterNode, ClusterNode> getNodes(Integer key) { Affinity<Integer> aff = grid(0).affinity(DEFAULT_CACHE_NAME); int part = aff.partition(key); ClusterNode primary = aff.mapPartitionToNode(part); assert primary != null; Collection<ClusterNode> nodes = new ArrayList<>(grid(0).cluster().nodes()); nodes.remove(primary); ClusterNode other = F.first(nodes); assert other != null; assert !F.eqNodes(primary, other); return F.t(primary, other); } }
32.942857
106
0.647971
41cbbd948b719989c3d40e271cc4dad1b53db798
3,363
package org.camunda.platform7.extension.graphql; import com.fasterxml.jackson.databind.ObjectMapper; import graphql.ExecutionResult; import org.camunda.bpm.engine.runtime.ProcessInstance; import org.camunda.platform7.extension.graphql.infratest.bpm.BaseTest; import org.camunda.platform7.extension.graphql.infratest.bpm.services.WeatherCheckService; import org.camunda.platform7.extension.graphql.infratest.comparators.Comparators; import org.camunda.platform7.extension.graphql.infratest.comparators.DateExpressionMatcher; import org.camunda.platform7.extension.graphql.infratest.comparators.IsANumberExpressionMatcher; import org.camunda.platform7.extension.graphql.infratest.comparators.IsPresentExpressionMatcher; import org.camunda.platform7.extension.graphql.infratest.scenarios.BDD; import org.junit.Test; import org.skyscreamer.jsonassert.comparator.CustomComparator; import org.springframework.beans.factory.annotation.Autowired; import static java.lang.Thread.sleep; import static org.mockito.Mockito.reset; import static org.mockito.Mockito.when; import static org.skyscreamer.jsonassert.JSONAssert.assertEquals; import static org.skyscreamer.jsonassert.JSONCompareMode.STRICT; public class IncidentTest extends BaseTest { private static final String PROCESS_KEY = "weather-process"; private static final String BUSINESS_KEY = "985569948"; @Autowired private WeatherCheckService service; private ProcessInstance processInstance; private final CustomComparator comparators = Comparators.comparators(STRICT, IsANumberExpressionMatcher.isNumeric( "incidents[0].id"), DateExpressionMatcher.isDate( "incidents[0].incidentTimestamp"), IsANumberExpressionMatcher.isNumeric("incidents[0].executionId"), IsANumberExpressionMatcher.isNumeric("incidents[0].causeIncidentId"), IsANumberExpressionMatcher.isNumeric("incidents[0].rootCauseIncidentId"), IsANumberExpressionMatcher.isNumeric("incidents[0].jobDefinitionId"), IsANumberExpressionMatcher.isNumeric("incidents[0].processInstanceId"), IsPresentExpressionMatcher.isPresent("incidents[0].processDefinitionId"), IsANumberExpressionMatcher.isNumeric("incidents[0].configuration") ); @Override public void setUp() throws Exception { super.setUp(); scenario.load("incident-scenarios.json"); reset(this.service); when(service.checkWeather()).thenThrow(new Exception("Exception to generate a incident")); processInstance = runtimeService.startProcessInstanceByKey(PROCESS_KEY, BUSINESS_KEY); } @Test public void shouldReturnTheIncidentWhenDelegateThrowAException() throws Exception { BDD.Given("a query to search a incident by processId"); String graphqlQuery = "query to find a incident by process id"; String queryWithProcessId = query(graphqlQuery).replace("idIncidentProcess", processInstance.getId()); BDD.When("graphql is called"); sleep(3000); ExecutionResult executionResult = graphQL.execute(queryWithProcessId); String result = new ObjectMapper().writeValueAsString(executionResult.getData()); BDD.Then("the result should be"); assertEquals(s("should return one incident"), result, comparators); } }
50.954545
114
0.765983
66ce2006696282bb1204d770de19784df6951381
2,082
package io.basc.framework.util.page; import java.util.stream.Stream; import io.basc.framework.lang.Nullable; public class SharedPaginations<T> extends SharedPagination<T> implements Paginations<T> { private static final long serialVersionUID = 1L; private Paginations<T> paginations; public SharedPaginations() { } public SharedPaginations(Paginations<T> paginations) { this(paginations, paginations); } public SharedPaginations(Page<Long, T> currentPage, @Nullable Paginations<T> paginations) { super(currentPage); this.paginations = paginations; } @Override public Paginations<T> jumpTo(Long cursorId, long count) { Paginations<T> pages = this.paginations.jumpTo(cursorId); if (pages instanceof SharedPaginations) { return pages; } return new SharedPaginations<>(pages); } @Override public Paginations<T> shared() { return this; } @Override public Paginations<T> jumpToPage(long pageNumber) { Paginations<T> pages = this.paginations.jumpToPage(pageNumber); if (pages instanceof SharedPaginations) { return pages; } return new SharedPaginations<>(pages); } @Override public Paginations<T> jumpToPage(long pageNumber, long count) { Paginations<T> pages = this.paginations.jumpToPage(pageNumber, count); if (pages instanceof SharedPaginations) { return pages; } return new SharedPaginations<>(pages); } @Override public Paginations<T> previous() { Paginations<T> pages = this.paginations.previous(); if (pages instanceof SharedPaginations) { return pages; } return new SharedPaginations<>(pages); } @Override public Paginations<T> limit(long maxPageNumber) { Paginations<T> pages = this.paginations.limit(maxPageNumber); if (pages instanceof SharedPaginations) { return pages; } return new SharedPaginations<>(pages); } @Override public Stream<? extends Pages<Long, T>> pages() { return paginations.pages(); } public Paginations<T> getPaginations() { return paginations; } public void setPaginations(Paginations<T> paginations) { this.paginations = paginations; } }
24.209302
92
0.740634
d66d5d3086145c2f45b6133edafa1becd0158166
8,540
/* OpenRemote, the Home of the Digital Home. * Copyright 2008-2012, OpenRemote Inc. * * See the contributors.txt file in the distribution for a * full listing of individual contributors. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package org.openremote.modeler.client.widget.uidesigner; import java.util.ArrayList; import java.util.List; import org.openremote.modeler.client.event.SubmitEvent; import org.openremote.modeler.client.listener.FormResetListener; import org.openremote.modeler.client.listener.FormSubmitListener; import org.openremote.modeler.client.proxy.BeanModelDataBase; import org.openremote.modeler.client.widget.FormWindow; import org.openremote.modeler.domain.Group; import org.openremote.modeler.domain.GroupRef; import org.openremote.modeler.domain.ScreenPair; import org.openremote.modeler.domain.ScreenPairRef; import org.openremote.modeler.touchpanel.TouchPanelDefinition; import com.extjs.gxt.ui.client.data.BeanModel; import com.extjs.gxt.ui.client.event.Events; import com.extjs.gxt.ui.client.event.FormEvent; import com.extjs.gxt.ui.client.event.Listener; import com.extjs.gxt.ui.client.event.MessageBoxEvent; import com.extjs.gxt.ui.client.store.ListStore; import com.extjs.gxt.ui.client.widget.CheckBoxListView; import com.extjs.gxt.ui.client.widget.ContentPanel; import com.extjs.gxt.ui.client.widget.Dialog; import com.extjs.gxt.ui.client.widget.MessageBox; import com.extjs.gxt.ui.client.widget.button.Button; import com.extjs.gxt.ui.client.widget.form.AdapterField; import com.extjs.gxt.ui.client.widget.form.TextField; import com.extjs.gxt.ui.client.widget.layout.FitLayout; /** * The window to edit group properties. */ public class GroupEditWindow extends FormWindow { private TextField<String> nameField = null; private CheckBoxListView<BeanModel> screenPairListView = null; private BeanModel groupRefBeanModel = null; public GroupEditWindow(BeanModel groupRefBeanModel) { this.groupRefBeanModel = groupRefBeanModel; setHeading("Edit Group"); setSize(370, 260); createFields(); createButtons(); add(form); form.setLabelWidth(50); form.setFieldWidth(260); show(); } private void createFields() { GroupRef groupRef = (GroupRef) groupRefBeanModel.getBean(); nameField = new TextField<String>(); nameField.setName("name"); nameField.setFieldLabel("Name"); nameField.setAllowBlank(false); if (groupRef.getGroup().getName() != null) { nameField.setValue(groupRef.getGroup().getName()); } AdapterField screenField = new AdapterField(createScreenPairList(groupRef)); screenField.setFieldLabel("Screen"); form.add(nameField); form.add(screenField); } private ContentPanel createScreenPairList(GroupRef groupRef) { TouchPanelDefinition touchPanel = groupRef.getPanel().getTouchPanelDefinition(); ContentPanel screenContainer = new ContentPanel(); screenContainer.setHeaderVisible(false); screenContainer.setWidth(260); screenContainer.setHeight(150); screenContainer.setLayout(new FitLayout()); // overflow-auto style is for IE hack. screenContainer.addStyleName("overflow-auto"); screenPairListView = new CheckBoxListView<BeanModel>(); ListStore<BeanModel> store = new ListStore<BeanModel>(); List<BeanModel> otherModels = new ArrayList<BeanModel>(); List<BeanModel> screenPairModels = BeanModelDataBase.screenTable.loadAll(); List<BeanModel> selectedModels = new ArrayList<BeanModel>(); for (ScreenPairRef screenRef: groupRef.getGroup().getScreenRefs()) { selectedModels.add(screenRef.getScreen().getBeanModel()); } for (BeanModel screenPairModel : screenPairModels) { if (((ScreenPair) screenPairModel.getBean()).getTouchPanelDefinition().equals(touchPanel)) { store.add(screenPairModel); } else if (((ScreenPair) screenPairModel.getBean()).getTouchPanelDefinition().getCanvas().equals(touchPanel.getCanvas())){ otherModels.add(screenPairModel); } } store.add(otherModels); for (BeanModel selectedModel : selectedModels) { screenPairListView.setChecked(selectedModel, true); } screenPairListView.setStore(store); screenPairListView.setDisplayProperty("panelName"); screenPairListView.setStyleAttribute("overflow", "auto"); screenPairListView.setSelectStyle("screen-view-item-sel"); screenContainer.add(screenPairListView); return screenContainer; } private void createButtons() { Button submitBtn = new Button("Submit"); Button resetBtn = new Button("Reset"); submitBtn.addSelectionListener(new FormSubmitListener(form, submitBtn)); resetBtn.addSelectionListener(new FormResetListener(form)); form.addButton(submitBtn); form.addButton(resetBtn); addBeforSubmitListener(); } private void addBeforSubmitListener() { form.addListener(Events.BeforeSubmit, new Listener<FormEvent>() { public void handleEvent(FormEvent be) { List<BeanModel> storeModels = screenPairListView.getStore().getModels(); List<BeanModel> screenPairModels = screenPairListView.getChecked(); Group group = ((GroupRef) groupRefBeanModel.getBean()).getGroup(); storeModels.removeAll(screenPairModels); String screenNames = ""; for (BeanModel beanModel : storeModels) { for (ScreenPairRef screenPairRef : group.getScreenRefs()) { if (screenPairRef.getScreen() == beanModel.getBean() && screenPairRef.getScreen().getRefCount() == 1) { screenNames = screenNames + screenPairRef.getScreen().getName() + ","; } } } if (!"".equals(screenNames)) { screenNames = screenNames.substring(0, screenNames.lastIndexOf(",")); MessageBox.confirm("Confirm delete screens", "Are you sure you want to delete " + screenNames + "?", new Listener<MessageBoxEvent>() { public void handleEvent(MessageBoxEvent be) { if (be.getButtonClicked().getItemId().equals(Dialog.YES)) { confirmSubmit(); } else if (be.getButtonClicked().getItemId().equals(Dialog.NO)) { return; } } }); } else { confirmSubmit(); } } private void confirmSubmit() { Group group = ((GroupRef) groupRefBeanModel.getBean()).getGroup(); TouchPanelDefinition touchPanelDefinition = ((GroupRef) groupRefBeanModel.getBean()).getPanel().getTouchPanelDefinition(); for (ScreenPairRef screenPairRef : group.getScreenRefs()) { screenPairRef.getScreen().releaseRef(); } group.getScreenRefs().clear(); group.setName(nameField.getValue()); List<BeanModel> screenPairModels = screenPairListView.getChecked(); if (screenPairModels.size() > 0) { for (BeanModel screenPairModel : screenPairModels) { ScreenPairRef screenPairRef = new ScreenPairRef((ScreenPair) screenPairModel.getBean()); screenPairRef.setTouchPanelDefinition(touchPanelDefinition); screenPairRef.setGroup(group); group.addScreenRef(screenPairRef); } } fireEvent(SubmitEvent.SUBMIT, new SubmitEvent(groupRefBeanModel)); } }); } }
44.479167
150
0.66534
29b6278d3e168c2f12eb609d533c493983d0109f
4,101
package algraph.view; import algraph.model.EdgeModel; import algraph.model.NodeModel; import algraph.utils.*; public class GraphView { public final int MAX_NODES = 15; private static final int RADIUS = 25; private int currentNumberNodes = 0; private int visibleNodes = 0; public NodeView nodes[]; public EdgeView edge[][]; public GraphView() { } /* * Update the nodes coordinates based on the visibleNodes. * Update edge based on the new nodes coordinates. */ private void coordinates() { //update points coordinates for(int i = 0; i < MAX_NODES && this.nodes[i].isVisible; i++) { Point newCoord = new Point(550+250*Math.cos(Math.PI*2*i/this.visibleNodes), 300-250*Math.sin(Math.PI*2*i/this.visibleNodes)); this.nodes[i].setPosition(newCoord); } //update edges for(int i = 0; i < MAX_NODES; i++) { for(int j = 0; j < MAX_NODES; j++) { if(this.getEdge(i, j) != null) { this.insertEdge(i,j); this.insertEdge(j,i); } } } } public GraphView (int numberNodes) { this.nodes = new NodeView[MAX_NODES]; this.currentNumberNodes = numberNodes; this.visibleNodes = numberNodes; //crea grafo for(int i = 0; i<MAX_NODES; i++) { if(i < numberNodes) { Point coordinates = new Point(550+250*Math.cos(Math.PI*2*i/numberNodes), 300-250*Math.sin(Math.PI*2*i/numberNodes)); NodeModel tmp = new NodeModel(i); this.nodes[i] = new NodeView(tmp, coordinates); } else this.nodes[i] = new NodeView(); } this.edge = new EdgeView[MAX_NODES][MAX_NODES]; for(int i=0; i<MAX_NODES; i++) { for(int z=0; z<MAX_NODES; z++) { this.edge[i][z] = null; } } } /* * @param node = inserted node */ public void insertNode(NodeModel node) { this.currentNumberNodes++; this.visibleNodes++; Point center = new Point(550+250*Math.cos(Math.PI*2*node.getIndex()/this.currentNumberNodes), 300-250*Math.sin(Math.PI*2*node.getIndex()/this.currentNumberNodes)); this.nodes[node.getIndex()] = new NodeView(node, center); this.coordinates(); } /* * @param node = deleted node */ public void deleteNode(NodeModel node) { this.currentNumberNodes--; this.visibleNodes--; this.nodes[node.getIndex()].setIsVisible(false); } /* * @param edge = inserted edge */ public void insertEdge(EdgeModel edge) { if(edge.getStartNode() != edge.getEndNode()) { Point centerStart = new Point(this.nodes[edge.getStartNode().getIndex()].getPosX(), this.nodes[edge.getStartNode().getIndex()].getPosY()); Point centerEnd = new Point(this.nodes[edge.getEndNode().getIndex()].getPosX(), this.nodes[edge.getEndNode().getIndex()].getPosY()); this.edge[edge.getStartNode().getIndex()][edge.getEndNode().getIndex()] = new EdgeView(centerStart,centerEnd,RADIUS); this.edge[edge.getEndNode().getIndex()][edge.getStartNode().getIndex()] = new EdgeView(centerEnd,centerStart,RADIUS); } } /* * start = start node * end = end node * graph[start][end] = edge */ public void insertEdge(int start, int end) { Point centerStart = new Point(this.nodes[start].getPosX(), this.nodes[start].getPosY()); Point centerEnd = new Point(this.nodes[end].getPosX(), this.nodes[end].getPosY()); this.edge[start][end] = new EdgeView(centerStart,centerEnd,RADIUS); this.edge[end][start] = new EdgeView(centerEnd,centerStart,RADIUS); } public void deleteEdge(EdgeModel edge) { this.edge[edge.getStartNode().getIndex()][edge.getEndNode().getIndex()] = null; this.edge[edge.getEndNode().getIndex()][edge.getStartNode().getIndex()] = null; } public void deleteEdge(int start, int end) { this.edge[start][end] = null; this.edge[end][start] = null; } public NodeView getNode(int n) { return this.nodes[n]; } public NodeView getNode(NodeModel u) { return this.nodes[u.getIndex()]; } public EdgeView getEdge(int u, int v) { return this.edge[u][v]; } public EdgeView getEdge(NodeModel u, NodeModel v) { if(this.edge[u.getIndex()][v.getIndex()] != null) return this.edge[u.getIndex()][v.getIndex()]; else return null; } }
28.089041
165
0.67008
6471ee3c6f85eeaef11b8d9a2f982dcad747c57c
818
package com.dastanapps.dastanlib.utils; import android.graphics.drawable.Drawable; import android.graphics.drawable.GradientDrawable; import android.graphics.drawable.StateListDrawable; public class DrawableUtils { public static StateListDrawable createSelector(Drawable normalIconDrawable, Drawable selectedIconDrawable) { StateListDrawable res = new StateListDrawable(); res.addState(new int[]{ android.R.attr.state_selected }, selectedIconDrawable); res.addState(new int[]{}, normalIconDrawable); return res; } public static GradientDrawable createGradientDrawable(int[] colors) { GradientDrawable shape = new GradientDrawable(GradientDrawable.Orientation.LEFT_RIGHT, colors); shape.setShape(GradientDrawable.RECTANGLE); return shape; } }
37.181818
112
0.759169
538461f9865286f4603f5e8e1bd262553b1f228a
5,319
package rusting.entities.units; import mindustry.gen.UnitEntity; public class RustingUnitEntity extends UnitEntity { /* @Override public boolean damaged(){ return this.health != this.maxHealth || this.shieldChargef() < 1; } @Override public void heal(float number){ if(number != null){ if(this.health >= this.maxHealth){ if(this.vRecharge <= 0.8 && this.sBroken) this.vRecharge += 0.003; else if(this.shieldChargef() < 1){ //increase the unit's shield depending on how much the unit is being healed for relative to the unit's health this.vShield = Mathf.clamp(number/this.maxHealth + this.vShield, 0, this.sLimit); //if the unit isn't healing itself from this, or the healing is at the same or lower rate as the unit heals itself, don't display shield if(number > this.type.health/this.HPS/6000 && this.eAlpha < 0.2) this.shieldAlphaf(0.25); } } else{ this.health += number; this.clampHealth(); } } else{ this.health = this.maxHealth; } } @Override collision(Bullet b){ if(b != null && b.type.healPercent > 0) { this.hitShield(0.05); this.damagePierce(b.type.healPercent * 2 + this.type.armor); } } public void hitShield(float number){ if(this.vShield >= 1){ this.DR = 1.1; this.vShield -= number; this.shieldAlphaf(number); if(this.vShield < 1 && !this.sBroken){ this.sBroken = true; this.vRecharge = 0; voidPop.at(this.x, this.y, 0, [this, 5, this.hitSize + 3, this.eAlpha]); } else this.vRecharge += 0.01; } else{ this.DR = Mathf.slerpDelta(this.DR, 0, 0.005); this.vShield = 0; } } public float shieldAlphaf(float number){ if(number != null) this.eAlpha = Mathf.clamp(this.eAlpha + number, 0, 1); else return this.eAlpha; } public float shieldCharge(float number){ return this.vShield; } public float shieldChargef(){ return this.vShield/this.sLimit; } public String vstring(){ if(this.sBroken === true) return "Shield Shattered"; else return "Void Shield Charge"; } @Override public void damage(float number){ if(number > 0){ this.hitShield(number >= this.type.armor * 5 ? 1 : 0.5); if(number < this.type.health * 12.5 || number > this.type.health * 50) number = number * (1 - this.DR); else number = number * (1 - this.DR * 0.5); this.super$damage(Mathf.clamp(number, 0, number)); } else this.shieldAlphaf(1); if(number <= 0) this.hitTime = 1; } @Override public void apply(StatusEffect status, float time){ if(status != StatusEffects.none && status != null && !this.isImmune(status)){ if(status.damage <= 0) super.apply(status, time); else if(status.permanent == true) this.heal(Math.abs(status.damage) * 60); else if(this.DR <= 0.75 && this.shield <= 1 && status.damage > 0) super.apply(status, time); } } @Override public void update(){ super.update(); if(Mathf.chance(Time.delta)){ if(this.maxHealth != this.type.health){ this.DR = Mathf.clamp(this.DR + 0.1, 0, 1); this.maxHealth = this.type.health; } if(this.damaged()) this.healFract(this.HPS/6000); this.DR = Mathf.slerpDelta(this.DR, 0, 0.01); if(!this.sBroken) this.vShield = Mathf.slerpDelta(this.vShield, this.sLimit, 0.001); this.eAlpha = Mathf.slerpDelta(this.eAlpha, 0, 0.01); if(this.vRecharge < 1 && this.sBroken) this.vRecharge += 0.003; else if(this.sBroken) this.sBroken = false; this.dCol1.a = this.vShield/2.15 * this.eAlpha * Mathf.clamp(Math.round(this.vShield), 0, 1); this.dCol2.a = this.eAlpha * Mathf.clamp(Math.round(this.vShield), 0, 1); } } @Override public void draw(){ super.draw(); if(this.eAlpha > 0) Fill.light(this.x, this.y, 5, this.hitSize * 1.25, dCol1, dCol2); for(let i = 0; i < this.vShield; i++){ //use this variable instead of vShield when drawing. float i2 = (this.vShield - i)/this.sLimit; //Size of circle in addition to the unit's hitSize float circleSize = (i2 - 1) * 3 * i; //clamped from 0 to 1 float scaling = Mathf.clamp(i2 * sLimit, 0, 1); Draw.color(Color.valueOf("#9c7ae1"),Color.valueOf("#231841"), scaling); Draw.alpha(0.1 + scaling/2 * (circleSize * shieldChargef()/(3 * i) != null ? 1 - -circleSize * this.shieldChargef()/(3 * i) : 0.1) * 2); if(scaling != 1) Lines.swirl(x, y, this.hitSize + circleSize, scaling, this.rotation); else Lines.circle(x, y, hitSize + circleSize); } } @Override public void killed() { super.killed(); } */ }
34.993421
156
0.547095
ebf2abb12dae04e208949b89c5391884b9a2ef5b
105
package pl.mfilix.design.patterns.behavioral.command; public interface I_Order { void execute(); }
15
53
0.752381
e8a40631246f7ba68059194633fa22799ec9a104
4,272
package org.tdar.struts.action.dataset; import java.io.InputStream; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Set; import org.apache.commons.collections4.CollectionUtils; import org.springframework.beans.factory.annotation.Autowired; import org.tdar.core.bean.resource.Dataset; import org.tdar.core.bean.resource.Project; import org.tdar.core.bean.resource.datatable.DataTable; import org.tdar.core.bean.resource.datatable.DataTableColumn; import org.tdar.core.service.SerializationService; import org.tdar.core.service.resource.DataTableService; import org.tdar.core.service.resource.DatasetService; import org.tdar.db.datatable.ImportColumn; import org.tdar.struts.action.resource.AbstractResourceViewAction; import org.tdar.struts_base.action.TdarActionException; import org.tdar.utils.PersistableUtils; public abstract class AbstractDatasetViewAction<D extends Dataset> extends AbstractResourceViewAction<D> { private static final long serialVersionUID = -7657008098263870208L; private Long dataTableId; private InputStream xmlStream; private DataTable dataTable; private String dataTableColumnJson; @Autowired private transient DataTableService dataTableService; @Autowired private transient DatasetService datasetService; @Autowired private transient SerializationService serializationService; /** * @return The output of the xml request to the database wrapped in a stream */ public InputStream getXmlStream() { return xmlStream; } @Override protected void loadCustomViewMetadata() throws TdarActionException { super.loadCustomViewMetadata(); List<Map<String, Object>> result = new ArrayList<>(); if (PersistableUtils.isNotNullOrTransient(getDataTable())) { for (ImportColumn dtc : getDataTable().getSortedDataTableColumnsByImportOrder()) { Map<String, Object> col = new HashMap<>(); col.put("simpleName", ((DataTableColumn)dtc).getJsSimpleName()); col.put("displayName", dtc.getDisplayName()); result.add(col); } } try { setDataTableColumnJson(serializationService.convertToJson(result)); } catch (Exception e) { getLogger().error("cannot convert to JSON: {}", e); } } public void setDataTable(DataTable dataTable) { this.dataTable = dataTable; } public DataTable getDataTable() { getLogger().trace(dataTable + " dtID:" + dataTableId); if (dataTable == null) { if (dataTableId != null) { this.dataTable = dataTableService.find(dataTableId); } else { Set<DataTable> dataTables = ((Dataset) getResource()).getDataTables(); if (!CollectionUtils.isEmpty(dataTables)) { dataTable = dataTables.iterator().next(); } } } return dataTable; } public void setDataTableId(Long dataTableId) { if (PersistableUtils.isNullOrTransient(dataTableId)) { getLogger().error("Trying to set data table id to null or -1: " + dataTableId); return; } this.dataTableId = dataTableId; // this.dataTable = dataTableService.find(dataTableId); } public Long getDataTableId() { return dataTableId; } public void setXmlStream(InputStream xmlStream) { this.xmlStream = xmlStream; } public String getDataTableColumnJson() { return dataTableColumnJson; } public void setDataTableColumnJson(String dataTableColumnJson) { this.dataTableColumnJson = dataTableColumnJson; } public boolean isMappingFeatureEnabled() { if (PersistableUtils.isNullOrTransient(getPersistable())) { return false; } if (datasetService.hasMappedCollection(getPersistable()) == false) { return false; } for (DataTable dt : getPersistable().getDataTables()) { if (!CollectionUtils.isEmpty(dt.getFilenameColumns())) { return true; } } return false; } }
33.637795
106
0.667603
31f40f7f1108bf40107fa998f7c75f5aa0363f62
3,790
package client; import server.dao.ActivityTypeDao; import server.entity.*; import server.service.*; import javax.swing.*; import java.awt.*; import java.sql.SQLException; import java.text.ParseException; import java.text.SimpleDateFormat; public class CustomerReviewForm extends JFrame { private JTextField username; private JTextField brandName; private JButton goBackButton; private JButton leaveAReviewButton; private JPanel leaveAReviewPanel; private JTextField reviewContent; private JTextField dateField; private JFrame jFrame; User user; public CustomerReviewForm() { leaveAReviewButton.addActionListener(e -> { try { submit(); } catch (ParseException|SQLException|NullPointerException ex) { ex.printStackTrace(); JOptionPane.showMessageDialog(this, "This activity is not supported by this brand's loyalty program."); jFrame.setVisible(false); } }); goBackButton.addActionListener(e-> { // CustomerRewardActivitiesCreation customerRewardActivitiesCreation = new CustomerRewardActivitiesCreation(); // customerRewardActivitiesCreation.selectRewardActivity(user); jFrame.setVisible(false); }); } public void leaveAReviewForm(User user) { this.user = user; jFrame = new JFrame("Customer: Leave a review"); jFrame.setPreferredSize(new Dimension(500, 500)); jFrame.setResizable(false); jFrame.add(leaveAReviewPanel); jFrame.setDefaultCloseOperation(EXIT_ON_CLOSE); jFrame.pack(); jFrame.setVisible(true); jFrame.setLocationRelativeTo(null); } public void submit() throws ParseException, SQLException { try { String activity_code = new ActivityTypeDao().findActivityCodeByName("Write a review"); Brand brand = new BrandService().getBrandInfoByUserName(brandName.getText()); LoyaltyProgram loyaltyProgram = new LoyaltyProgramService().fetchLoyaltyProgramByBrand(brand.getBrand_id()); RewardEarningRules rewardEarningRules = new RewardEarningService().getReRulesByLoyaltyProgramActivityCode(loyaltyProgram, activity_code); Customer customer = new CustomerService().getCustomerInfoByUserName(user.getUserName()); LoyaltyActivityLog loyaltyActivityLog = new LoyaltyActivityLog(); loyaltyActivityLog.setActivity_code(activity_code); loyaltyActivityLog.setCustomer_id(customer.getId()); loyaltyActivityLog.setReward_earning_code(rewardEarningRules.getRewardEarningCode()); loyaltyActivityLog.setPoints_gained(rewardEarningRules.getRePoints()); loyaltyActivityLog.setSummary(reviewContent.getText()); loyaltyActivityLog.setLoyalty_program_id(loyaltyProgram.getLoyaltyProgramId()); loyaltyActivityLog.setCreated_at(new SimpleDateFormat("MM/dd/yyyy").parse(dateField.getText())); LoyaltyActivityService loyaltyActivityService = new LoyaltyActivityService(); String resp = loyaltyActivityService.createReview(loyaltyActivityLog); JOptionPane.showMessageDialog(this, resp); // CustomerRewardActivitiesCreation customerRewardActivitiesCreation = new CustomerRewardActivitiesCreation(); // customerRewardActivitiesCreation.selectRewardActivity(user); jFrame.setVisible(false); } catch (SQLException|NullPointerException exception) { System.out.println("exception raised."); JOptionPane.showMessageDialog(this, "This activity is not supported by this brand's loyalty program."); jFrame.setVisible(false); } } }
45.662651
149
0.704749
4391c1f5268ec731fc263b7c6871d34d1cebbf64
17,083
package co.cask.coopr.store.cluster; import co.cask.coopr.cluster.Cluster; import co.cask.coopr.cluster.ClusterSummary; import co.cask.coopr.cluster.Node; import co.cask.coopr.scheduler.task.ClusterJob; import co.cask.coopr.scheduler.task.ClusterTask; import co.cask.coopr.scheduler.task.JobId; import co.cask.coopr.scheduler.task.TaskId; import co.cask.coopr.spec.ProvisionerAction; import co.cask.coopr.store.DBConnectionPool; import co.cask.coopr.store.DBHelper; import co.cask.coopr.store.DBPut; import co.cask.coopr.store.DBQueryExecutor; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.IOException; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.SQLException; import java.util.List; import java.util.Set; /** * A full view of the cluster store backed by a sql database. */ public class SQLClusterStore implements ClusterStore { private static final Logger LOG = LoggerFactory.getLogger(SQLClusterStore.class); private final DBQueryExecutor dbQueryExecutor; private final DBConnectionPool dbConnectionPool; private final ClusterStoreView systemView; SQLClusterStore(DBConnectionPool dbConnectionPool, DBQueryExecutor dbQueryExecutor) { this.dbConnectionPool = dbConnectionPool; this.dbQueryExecutor = dbQueryExecutor; this.systemView = new SQLSystemClusterStoreView(dbConnectionPool, dbQueryExecutor); } @Override public ClusterJob getClusterJob(JobId jobId) throws IOException { try { Connection conn = dbConnectionPool.getConnection(); try { PreparedStatement statement = conn.prepareStatement("SELECT job FROM jobs WHERE job_num=? AND cluster_id=?"); try { statement.setLong(1, jobId.getJobNum()); statement.setLong(2, Long.parseLong(jobId.getClusterId())); return dbQueryExecutor.getQueryItem(statement, ClusterJob.class); } finally { statement.close(); } } finally { conn.close(); } } catch (SQLException e) { LOG.error("Exception getting cluster job {}", jobId, e); throw new IOException("Exception getting cluster job " + jobId, e); } } @Override public void writeClusterJob(ClusterJob clusterJob) throws IOException { JobId jobId = JobId.fromString(clusterJob.getJobId()); long clusterId = Long.parseLong(jobId.getClusterId()); try { Connection conn = dbConnectionPool.getConnection(); try { byte[] jobBytes = dbQueryExecutor.toBytes(clusterJob, ClusterJob.class); DBPut jobPut = new ClusterJobDBPut(clusterJob, jobBytes, jobId, clusterId); jobPut.executePut(conn); } finally { conn.close(); } } catch (SQLException e) { throw new IOException(e); } } @Override public void deleteClusterJob(JobId jobId) throws IOException { try { Connection conn = dbConnectionPool.getConnection(); try { PreparedStatement statement = conn.prepareStatement("DELETE FROM jobs WHERE job_num=? AND cluster_id=?"); try { statement.setLong(1, jobId.getJobNum()); statement.setLong(2, Long.parseLong(jobId.getClusterId())); statement.executeUpdate(); } finally { statement.close(); } } finally { conn.close(); } } catch (SQLException e) { throw new IOException(e); } } @Override public ClusterTask getClusterTask(TaskId taskId) throws IOException { try { Connection conn = dbConnectionPool.getConnection(); try { PreparedStatement statement = conn.prepareStatement("SELECT task FROM tasks WHERE task_num=? AND cluster_id=? AND job_num=?"); try { statement.setLong(1, taskId.getTaskNum()); statement.setLong(2, Long.parseLong(taskId.getClusterId())); statement.setLong(3, taskId.getJobNum()); return dbQueryExecutor.getQueryItem(statement, ClusterTask.class); } finally { statement.close(); } } finally { conn.close(); } } catch (SQLException e) { LOG.error("Exception getting cluster task {}", taskId, e); throw new IOException("Exception getting cluster task " + taskId, e); } } @Override public List<ClusterTask> getClusterTasks(ClusterTaskFilter filter) throws IOException { try { Connection conn = dbConnectionPool.getConnection(); try { StringBuilder builder = new StringBuilder("SELECT task FROM tasks WHERE status = ? AND type IN (?,?)") .append(addFilter("tenant_id = ", filter.getTenantId())) .append(addFilter("user_id = ", filter.getUserId())) .append(addFilter("cluster_id = ", filter.getClusterId())) .append(addFilter("cluster_template_name = ", filter.getClusterTemplate())) .append(" ORDER BY status_time ASC"); PreparedStatement statement = conn.prepareStatement(builder.toString()); try { int index = initializeFilter(statement, ClusterTask.Status.COMPLETE.name(), 1); index = initializeFilter(statement, ProvisionerAction.CREATE.name(), index); index = initializeFilter(statement, ProvisionerAction.DELETE.name(), index); index = initializeFilter(statement, filter.getTenantId(), index); index = initializeFilter(statement, filter.getUserId(), index); index = initializeFilter(statement, filter.getClusterId(), index); initializeFilter(statement, filter.getClusterTemplate(), index); return dbQueryExecutor.getQueryList(statement, ClusterTask.class); } finally { statement.close(); } } finally { conn.close(); } } catch (SQLException e) { LOG.error("Exception getting cluster tasks by filters {}", filter, e); throw new IOException("Exception getting cluster tasks by filters " + filter, e); } } private String addFilter(String key, Object value) { if (value == null) { return ""; } return String.format(" AND %s?", key); } private int initializeFilter(PreparedStatement statement, String value, int index) throws SQLException { if (value == null) { return index; } statement.setString(index, value); return ++index; } @Override public void writeClusterTask(ClusterTask clusterTask) throws IOException { TaskId taskId = TaskId.fromString(clusterTask.getTaskId()); long clusterId = Long.parseLong(taskId.getClusterId()); try { Connection conn = dbConnectionPool.getConnection(); try { byte[] taskBytes = dbQueryExecutor.toBytes(clusterTask, ClusterTask.class); DBPut taskPut = new ClusterTaskDBPut(clusterTask, taskBytes, taskId, clusterId); taskPut.executePut(conn); } finally { conn.close(); } } catch (SQLException e) { throw new IOException(e); } } @Override public void deleteClusterTask(TaskId taskId) throws IOException { try { Connection conn = dbConnectionPool.getConnection(); try { PreparedStatement statement = conn.prepareStatement("DELETE FROM tasks WHERE task_num=? AND cluster_id=? AND job_num=?"); statement.setLong(1, taskId.getTaskNum()); statement.setLong(2, Long.parseLong(taskId.getClusterId())); statement.setLong(3, taskId.getJobNum()); try { statement.executeUpdate(); } finally { statement.close(); } } finally { conn.close(); } } catch (SQLException e) { throw new IOException(e); } } @Override public Node getNode(String nodeId) throws IOException { try { Connection conn = dbConnectionPool.getConnection(); try { PreparedStatement statement = conn.prepareStatement("SELECT node FROM nodes WHERE id=? "); statement.setString(1, nodeId); try { return dbQueryExecutor.getQueryItem(statement, Node.class); } finally { statement.close(); } } finally { conn.close(); } } catch (SQLException e) { throw new IOException(e); } } @Override public void writeNode(Node node) throws IOException { try { Connection conn = dbConnectionPool.getConnection(); try { byte[] nodeBytes = dbQueryExecutor.toBytes(node, Node.class); DBPut nodePut = new NodeDBPut(node, nodeBytes); nodePut.executePut(conn); } finally { conn.close(); } } catch (SQLException e) { throw new IOException(e); } } @Override public void deleteNode(String nodeId) throws IOException { try { Connection conn = dbConnectionPool.getConnection(); try { PreparedStatement statement = conn.prepareStatement("DELETE FROM nodes WHERE id=? "); try { statement.setString(1, nodeId); statement.executeUpdate(); } finally { statement.close(); } } finally { conn.close(); } } catch (SQLException e) { throw new IOException(e); } } @Override public Set<ClusterTask> getRunningTasks(long timestamp) throws IOException { try { Connection conn = dbConnectionPool.getConnection(); try { PreparedStatement statement = conn.prepareStatement("SELECT task FROM tasks WHERE status = ? AND submit_time < ?"); statement.setString(1, ClusterTask.Status.IN_PROGRESS.name()); statement.setTimestamp(2, DBHelper.getTimestamp(timestamp)); try { return dbQueryExecutor.getQuerySet(statement, ClusterTask.class); } finally { statement.close(); } } finally { conn.close(); } } catch (SQLException e) { throw new IOException(e); } } @Override public Set<Cluster> getExpiringClusters(long timestamp) throws IOException { try { Connection conn = dbConnectionPool.getConnection(); try { PreparedStatement statement = conn.prepareStatement("SELECT cluster FROM clusters WHERE status IN (?, ?) AND expire_time < ?"); statement.setString(1, Cluster.Status.ACTIVE.name()); statement.setString(2, Cluster.Status.INCOMPLETE.name()); statement.setTimestamp(3, DBHelper.getTimestamp(timestamp)); try { return dbQueryExecutor.getQuerySet(statement, Cluster.class); } finally { statement.close(); } } finally { conn.close(); } } catch (SQLException e) { throw new IOException(e); } } @Override public List<Cluster> getAllClusters() throws IOException { return systemView.getAllClusters(); } @Override public List<ClusterSummary> getAllClusterSummaries() throws IOException { return systemView.getAllClusterSummaries(); } @Override public List<ClusterSummary> getAllClusterSummaries(Set<Cluster.Status> states) throws IOException { return systemView.getAllClusterSummaries(states); } @Override public List<Cluster> getNonTerminatedClusters() throws IOException { return systemView.getNonTerminatedClusters(); } @Override public Cluster getCluster(String clusterId) throws IOException { return systemView.getCluster(clusterId); } @Override public boolean clusterExists(String clusterId) throws IOException { return systemView.clusterExists(clusterId); } @Override public void writeCluster(Cluster cluster) throws IllegalAccessException, IOException { systemView.writeCluster(cluster); } @Override public void deleteCluster(String clusterId) throws IOException { systemView.deleteCluster(clusterId); } @Override public List<ClusterJob> getClusterJobs(String clusterId, int limit) throws IOException { return systemView.getClusterJobs(clusterId, limit); } @Override public Set<Node> getClusterNodes(String clusterId) throws IOException { return systemView.getClusterNodes(clusterId); } private class ClusterJobDBPut extends DBPut { private final ClusterJob clusterJob; private final byte[] jobBytes; private final JobId jobId; private final long clusterId; private ClusterJobDBPut(ClusterJob clusterJob, byte[] jobBytes, JobId jobId, long clusterId) { this.clusterJob = clusterJob; this.jobBytes = jobBytes; this.jobId = jobId; this.clusterId = clusterId; } @Override public PreparedStatement createUpdateStatement(Connection conn) throws SQLException { PreparedStatement updateStatement = conn.prepareStatement("UPDATE jobs SET job=?, status=? WHERE job_num=? AND cluster_id=?"); updateStatement.setBytes(1, jobBytes); updateStatement.setString(2, clusterJob.getJobStatus().name()); updateStatement.setLong(3, jobId.getJobNum()); updateStatement.setLong(4, clusterId); return updateStatement; } @Override public PreparedStatement createInsertStatement(Connection conn) throws SQLException { PreparedStatement statement = conn.prepareStatement( "INSERT INTO jobs (job_num, cluster_id, status, create_time, job) VALUES (?, ?, ?, ?, ?)"); statement.setLong(1, jobId.getJobNum()); statement.setLong(2, clusterId); statement.setString(3, clusterJob.getJobStatus().name()); statement.setTimestamp(4, DBHelper.getTimestamp(System.currentTimeMillis())); statement.setBytes(5, jobBytes); return statement; } } private class ClusterTaskDBPut extends DBPut { private final ClusterTask clusterTask; private final byte[] taskBytes; private final TaskId taskId; private final long clusterId; private ClusterTaskDBPut(ClusterTask clusterTask, byte[] taskBytes, TaskId taskId, long clusterId) { this.clusterTask = clusterTask; this.taskBytes = taskBytes; this.taskId = taskId; this.clusterId = clusterId; } @Override public PreparedStatement createUpdateStatement(Connection conn) throws SQLException { PreparedStatement statement = conn.prepareStatement( "UPDATE tasks SET task=?, status=?, submit_time=?, status_time=?, type=?, " + "cluster_template_name=?, user_id=?, tenant_id=?" + " WHERE task_num=? AND job_num=? AND cluster_id=?"); statement.setBytes(1, dbQueryExecutor.toBytes(clusterTask, ClusterTask.class)); statement.setString(2, clusterTask.getStatus().name()); statement.setTimestamp(3, DBHelper.getTimestamp(clusterTask.getSubmitTime())); statement.setTimestamp(4, DBHelper.getTimestamp(clusterTask.getStatusTime())); statement.setString(5, clusterTask.getTaskName().name()); statement.setString(6, clusterTask.getClusterTemplateName()); statement.setString(7, clusterTask.getAccount().getUserId()); statement.setString(8, clusterTask.getAccount().getTenantId()); statement.setLong(9, taskId.getTaskNum()); statement.setLong(10, taskId.getJobNum()); statement.setLong(11, clusterId); return statement; } @Override public PreparedStatement createInsertStatement(Connection conn) throws SQLException { PreparedStatement statement = conn.prepareStatement( "INSERT INTO tasks (task_num, job_num, cluster_id, status, submit_time, task, type, " + "cluster_template_name, user_id, tenant_id)" + " VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)"); statement.setLong(1, taskId.getTaskNum()); statement.setLong(2, taskId.getJobNum()); statement.setLong(3, clusterId); statement.setString(4, clusterTask.getStatus().name()); statement.setTimestamp(5, DBHelper.getTimestamp(clusterTask.getSubmitTime())); statement.setBytes(6, taskBytes); statement.setString(7, clusterTask.getTaskName().name()); statement.setString(8, clusterTask.getClusterTemplateName()); statement.setString(9, clusterTask.getAccount().getUserId()); statement.setString(10, clusterTask.getAccount().getTenantId()); return statement; } } private class NodeDBPut extends DBPut { private final Node node; private final byte[] nodeBytes; private NodeDBPut(Node node, byte[] nodeBytes) { this.node = node; this.nodeBytes = nodeBytes; } @Override public PreparedStatement createUpdateStatement(Connection conn) throws SQLException { PreparedStatement statement = conn.prepareStatement("UPDATE nodes SET node=? WHERE id=?"); statement.setBytes(1, nodeBytes); statement.setString(2, node.getId()); return statement; } @Override public PreparedStatement createInsertStatement(Connection conn) throws SQLException { PreparedStatement statement = conn.prepareStatement( "INSERT INTO nodes (id, cluster_id, node) VALUES (?, ?, ?)"); statement.setString(1, node.getId()); statement.setLong(2, Long.parseLong(node.getClusterId())); statement.setBytes(3, nodeBytes); return statement; } } }
35.22268
117
0.674764
bf3ef27192e712e7ccbc0a7e0ea60842b91e44a2
719
package br.com.jacksontenorio8.Aula; /* * Crie uma variável que ira guardar o valor de um salário, sendo os valores das porcentagens: * 30% * 15% * 5% * A cada vez que você calcular guarde o resultado em uma variável * Imprima o resultado e reutilize a variável que guarda o resultado para o novo calculo, repetindo o processo. * */ public class PorcentagemSalario { public static void main(String[] args) { double salario = 5000; double resultado = salario * 0.3; System.out.println("30% é: " + resultado); resultado = salario * 0.15; System.out.println("15% é: " + resultado); resultado = salario * 0.05; System.out.println("5% é: " + resultado); } }
31.26087
110
0.656467
3cd2dc727ecfb3b659687e3bbba7db2cbe1757ec
6,351
/* * Copyright 2012 John Crygier * Copyright 2012 gitblit.com * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.gitblit.tests; import java.io.FileInputStream; import java.util.HashMap; import java.util.Map; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; import com.gitblit.IStoredSettings; import com.gitblit.auth.LdapAuthProvider; import com.gitblit.manager.RuntimeManager; import com.gitblit.manager.UserManager; import com.gitblit.models.UserModel; import com.gitblit.tests.mock.MemorySettings; import com.unboundid.ldap.listener.InMemoryDirectoryServer; import com.unboundid.ldap.listener.InMemoryDirectoryServerConfig; import com.unboundid.ldap.listener.InMemoryListenerConfig; import com.unboundid.ldif.LDIFReader; /** * An Integration test for LDAP that tests going against an in-memory UnboundID * LDAP server. * * @author jcrygier * */ public class LdapAuthenticationTest extends GitblitUnitTest { private static final String RESOURCE_DIR = "src/test/resources/ldap/"; private LdapAuthProvider ldap; static int ldapPort = 1389; @BeforeClass public static void createInMemoryLdapServer() throws Exception { InMemoryDirectoryServerConfig config = new InMemoryDirectoryServerConfig("dc=MyDomain"); config.addAdditionalBindCredentials("cn=Directory Manager", "password"); config.setListenerConfigs(InMemoryListenerConfig.createLDAPConfig("default", ldapPort)); config.setSchema(null); InMemoryDirectoryServer ds = new InMemoryDirectoryServer(config); ds.importFromLDIF(true, new LDIFReader(new FileInputStream(RESOURCE_DIR + "sampledata.ldif"))); ds.startListening(); } @Before public void newLdapAuthentication() { ldap = newLdapAuthentication(getSettings()); } public LdapAuthProvider newLdapAuthentication(IStoredSettings settings) { RuntimeManager runtime = new RuntimeManager(settings, GitBlitSuite.BASEFOLDER).start(); UserManager users = new UserManager(runtime).start(); LdapAuthProvider ldap = new LdapAuthProvider(); ldap.setup(runtime, users); return ldap; } private MemorySettings getSettings() { Map<String, Object> backingMap = new HashMap<String, Object>(); backingMap.put("realm.userService", RESOURCE_DIR + "users.conf"); backingMap.put("realm.ldap.server", "ldap://localhost:" + ldapPort); backingMap.put("realm.ldap.domain", ""); backingMap.put("realm.ldap.username", "cn=Directory Manager"); backingMap.put("realm.ldap.password", "password"); backingMap.put("realm.ldap.backingUserService", "users.conf"); backingMap.put("realm.ldap.maintainTeams", "true"); backingMap.put("realm.ldap.accountBase", "OU=Users,OU=UserControl,OU=MyOrganization,DC=MyDomain"); backingMap.put("realm.ldap.accountPattern", "(&(objectClass=person)(sAMAccountName=${username}))"); backingMap.put("realm.ldap.groupBase", "OU=Groups,OU=UserControl,OU=MyOrganization,DC=MyDomain"); backingMap.put("realm.ldap.groupPattern", "(&(objectClass=group)(member=${dn}))"); backingMap.put("realm.ldap.admins", "UserThree @Git_Admins \"@Git Admins\""); backingMap.put("realm.ldap.displayName", "displayName"); backingMap.put("realm.ldap.email", "email"); MemorySettings ms = new MemorySettings(backingMap); return ms; } @Test public void testAuthenticate() { UserModel userOneModel = ldap.authenticate("UserOne", "userOnePassword".toCharArray()); assertNotNull(userOneModel); assertNotNull(userOneModel.getTeam("git_admins")); assertNotNull(userOneModel.getTeam("git_users")); assertTrue(userOneModel.canAdmin); UserModel userOneModelFailedAuth = ldap.authenticate("UserOne", "userTwoPassword".toCharArray()); assertNull(userOneModelFailedAuth); UserModel userTwoModel = ldap.authenticate("UserTwo", "userTwoPassword".toCharArray()); assertNotNull(userTwoModel); assertNotNull(userTwoModel.getTeam("git_users")); assertNull(userTwoModel.getTeam("git_admins")); assertNotNull(userTwoModel.getTeam("git admins")); assertTrue(userTwoModel.canAdmin); UserModel userThreeModel = ldap.authenticate("UserThree", "userThreePassword".toCharArray()); assertNotNull(userThreeModel); assertNotNull(userThreeModel.getTeam("git_users")); assertNull(userThreeModel.getTeam("git_admins")); assertTrue(userThreeModel.canAdmin); } @Test public void testDisplayName() { UserModel userOneModel = ldap.authenticate("UserOne", "userOnePassword".toCharArray()); assertNotNull(userOneModel); assertEquals("User One", userOneModel.displayName); // Test more complicated scenarios - concat MemorySettings ms = getSettings(); ms.put("realm.ldap.displayName", "${personalTitle}. ${givenName} ${surname}"); ldap = newLdapAuthentication(ms); userOneModel = ldap.authenticate("UserOne", "userOnePassword".toCharArray()); assertNotNull(userOneModel); assertEquals("Mr. User One", userOneModel.displayName); } @Test public void testEmail() { UserModel userOneModel = ldap.authenticate("UserOne", "userOnePassword".toCharArray()); assertNotNull(userOneModel); assertEquals("userone@gitblit.com", userOneModel.emailAddress); // Test more complicated scenarios - concat MemorySettings ms = getSettings(); ms.put("realm.ldap.email", "${givenName}.${surname}@gitblit.com"); ldap = newLdapAuthentication(ms); userOneModel = ldap.authenticate("UserOne", "userOnePassword".toCharArray()); assertNotNull(userOneModel); assertEquals("User.One@gitblit.com", userOneModel.emailAddress); } @Test public void testLdapInjection() { // Inject so "(&(objectClass=person)(sAMAccountName=${username}))" becomes "(&(objectClass=person)(sAMAccountName=*)(userPassword=userOnePassword))" // Thus searching by password UserModel userOneModel = ldap.authenticate("*)(userPassword=userOnePassword", "userOnePassword".toCharArray()); assertNull(userOneModel); } }
38.259036
150
0.765864
59b10e667780c032e9ef7484aae8ba3dc00556e2
422
package com.jbetfairng.entities; public class LimitOnCloseOrder { private double liability; private double price; public double getLiability() { return liability; } public void setLiability(double liability) { this.liability = liability; } public double getPrice() { return price; } public void setPrice(double price) { this.price = price; } }
17.583333
48
0.635071
8652721ffbec128f903d34ae552b756e45e5446c
5,176
package de.fkg.ultimate.war.game.screens; import com.badlogic.gdx.Gdx; import com.badlogic.gdx.Screen; import com.badlogic.gdx.graphics.GL20; import com.badlogic.gdx.graphics.OrthographicCamera; import com.badlogic.gdx.graphics.g2d.Sprite; import com.badlogic.gdx.graphics.g2d.SpriteBatch; import com.badlogic.gdx.maps.MapLayer; import com.badlogic.gdx.maps.MapObjects; import com.badlogic.gdx.maps.objects.RectangleMapObject; import com.badlogic.gdx.maps.tiled.TiledMap; import com.badlogic.gdx.maps.tiled.TiledMapRenderer; import com.badlogic.gdx.maps.tiled.TmxMapLoader; import com.badlogic.gdx.maps.tiled.renderers.OrthogonalTiledMapRenderer; import com.badlogic.gdx.math.Intersector; import com.badlogic.gdx.math.Rectangle; import com.badlogic.gdx.utils.Array; import com.badlogic.gdx.utils.Pool; import de.fkg.ultimate.war.game.characters.*; import de.fkg.ultimate.war.game.characters.Character; import de.fkg.ultimate.war.game.de.fkg.ultimate.war.game.input.DesktopInput; import java.util.Random; /** * Created by mkvr on 28.05.15. */ public class MainGameScreen implements Screen { private SpriteBatch batch; private TiledMap tiledMap; private OrthographicCamera camera; private TiledMapRenderer tiledMapRenderer; private Player player; private int scrollTrack = 0; private final Array<Enemy> activeEnemies; // bullet pool. private final Pool<Enemy> enemyPool = new Pool<Enemy>() { @Override protected Enemy newObject() { return new Enemy(); } }; public MainGameScreen(){ batch = new SpriteBatch(); player = new Player(100, 300); activeEnemies = new Array<Enemy>(); Gdx.input.setInputProcessor(new DesktopInput(player)); float w = Gdx.graphics.getWidth(); float h = Gdx.graphics.getHeight(); camera = new OrthographicCamera(); camera.setToOrtho(false, w, h); camera.update(); tiledMap = new TmxMapLoader().load("debug_level_one.tmx"); tiledMapRenderer = new OrthogonalTiledMapRenderer(tiledMap); } @Override public void show() { } @Override public void render(float delta) { Gdx.gl.glClearColor(1, 0, 0, 1); Gdx.gl.glBlendFunc(GL20.GL_SRC_ALPHA, GL20.GL_ONE_MINUS_SRC_ALPHA); Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT); camera.update(); tiledMapRenderer.setView(camera); tiledMapRenderer.render(); Sprite playerSprite = player.getCurrentFrame(delta); detectCollision(); batch.begin(); batch.draw(playerSprite, player.xPosition, player.yPosition); drawEnemies(delta); batch.end(); camera.translate(0,1); scrollTrack++; Random rnd = new Random(); if(rnd.nextInt(100) == 1) spawnEnemy(); } private void spawnEnemy(){ Enemy mob = enemyPool.obtain(); Random r = new Random(); Character character = new EnemyOgre(r.nextInt(Gdx.graphics.getWidth())-64, Gdx.graphics.getHeight()-64); mob.init(character); activeEnemies.add(mob); } private void drawEnemies(float delta){ for(Enemy enemy : activeEnemies){ Sprite enemySprite = enemy.character.getCurrentFrame(delta); enemySprite.flip(false, true); enemy.character.yPosition -= 2; enemy.update(delta); batch.draw(enemySprite, enemy.character.xPosition, enemy.character.yPosition); } } private void detectCollision(){ int objectLayerId = 2; MapLayer collisionObjectLayer = tiledMap.getLayers().get(objectLayerId); MapObjects objects = collisionObjectLayer.getObjects(); Rectangle playerRectangle = new Rectangle(player.xPosition, player.yPosition + scrollTrack, player.width, player.height); // there are several other types, Rectangle is probably the most common one for (RectangleMapObject rectangleObject : objects.getByType(RectangleMapObject.class)) { Rectangle rectangle = rectangleObject.getRectangle(); if (Intersector.overlaps(rectangle, playerRectangle)) { player.yPosition--; if(player.yPosition == 0) player.die(); } } detectEnemyCollision(); } private void detectEnemyCollision(){ Rectangle playerRectangle = new Rectangle(player.xPosition, player.yPosition + scrollTrack, player.width, player.height); for(Enemy enemy : activeEnemies){ Rectangle enemyRectangle = new Rectangle(enemy.character.xPosition, enemy.character.yPosition + scrollTrack, enemy.character.width, enemy.character.height); if (Intersector.overlaps(enemyRectangle, playerRectangle)) { player.die(); } } } @Override public void resize(int width, int height) { } @Override public void pause() { } @Override public void resume() { } @Override public void hide() { } @Override public void dispose() { } }
32.149068
129
0.659003
6c6319c3a1c021eb079b6658814d9032259ca4b8
279
/** * * Class BookCategory$Factory.java * * Generated by KMFStudio at 29 June 2003 12:59:43 * Visit http://www.cs.ukc.ac.uk/kmf * */ package library; public interface BookCategory$Factory extends LibraryFactory { /** Default builder */ public Object build(); }
14.684211
51
0.681004
6c00314a7e5454fbf9143c4c331a6f61e00898be
20,785
/** * 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.pulsar.tests.integration.cli; import static org.testng.Assert.assertEquals; import static org.testng.Assert.assertFalse; import static org.testng.Assert.assertTrue; import static org.testng.Assert.fail; import java.util.concurrent.TimeUnit; import java.util.UUID; import lombok.Cleanup; import org.apache.http.client.methods.CloseableHttpResponse; import org.apache.http.client.methods.HttpGet; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClients; import org.apache.http.util.EntityUtils; import org.apache.pulsar.client.api.Consumer; import org.apache.pulsar.client.api.Message; import org.apache.pulsar.client.api.Producer; import org.apache.pulsar.client.api.PulsarClient; import org.apache.pulsar.client.api.PulsarClientException; import org.apache.pulsar.client.api.Schema; import org.apache.pulsar.common.naming.NamespaceName; import org.apache.pulsar.common.naming.TopicName; import org.apache.pulsar.functions.api.examples.pojo.Tick; import org.apache.pulsar.tests.integration.containers.BrokerContainer; import org.apache.pulsar.tests.integration.docker.ContainerExecException; import org.apache.pulsar.tests.integration.docker.ContainerExecResult; import org.apache.pulsar.tests.integration.suites.PulsarTestSuite; import org.apache.pulsar.tests.integration.topologies.PulsarCluster; import org.testng.Assert; import org.testng.annotations.Test; /** * Test Pulsar CLI. */ public class CLITest extends PulsarTestSuite { @Test public void testDeprecatedCommands() throws Exception { String tenantName = "test-deprecated-commands"; ContainerExecResult result = pulsarCluster.runAdminCommandOnAnyBroker("--help"); assertFalse(result.getStdout().isEmpty()); assertFalse(result.getStdout().contains("Usage: properties ")); result = pulsarCluster.runAdminCommandOnAnyBroker( "properties", "create", tenantName, "--allowed-clusters", pulsarCluster.getClusterName(), "--admin-roles", "admin" ); assertTrue(result.getStderr().contains("deprecated")); result = pulsarCluster.runAdminCommandOnAnyBroker( "properties", "list"); assertTrue(result.getStdout().contains(tenantName)); result = pulsarCluster.runAdminCommandOnAnyBroker( "tenants", "list"); assertTrue(result.getStdout().contains(tenantName)); } @Test public void testGetTopicListCommand() throws Exception { ContainerExecResult result; final String namespaceLocalName = "list-topics-" + randomName(8); result = pulsarCluster.createNamespace(namespaceLocalName); final String namespace = "public/" + namespaceLocalName; assertEquals(0, result.getExitCode()); PulsarClient client = PulsarClient.builder().serviceUrl(pulsarCluster.getPlainTextServiceUrl()).build(); final String persistentTopicName = TopicName.get( "persistent", NamespaceName.get(namespace), "get_topics_mode_" + UUID.randomUUID()).toString(); final String nonPersistentTopicName = TopicName.get( "non-persistent", NamespaceName.get(namespace), "get_topics_mode_" + UUID.randomUUID()).toString(); Producer<byte[]> producer1 = client.newProducer() .topic(persistentTopicName) .create(); Producer<byte[]> producer2 = client.newProducer() .topic(nonPersistentTopicName) .create(); BrokerContainer container = pulsarCluster.getAnyBroker(); result = container.execCmd( PulsarCluster.ADMIN_SCRIPT, "topics", "list", namespace); assertTrue(result.getStdout().contains(persistentTopicName)); assertTrue(result.getStdout().contains(nonPersistentTopicName)); result = container.execCmd( PulsarCluster.ADMIN_SCRIPT, "topics", "list", "--topic-domain", "persistent", namespace); assertTrue(result.getStdout().contains(persistentTopicName)); assertFalse(result.getStdout().contains(nonPersistentTopicName)); result = container.execCmd( PulsarCluster.ADMIN_SCRIPT, "topics", "list", "--topic-domain", "non_persistent", namespace); assertFalse(result.getStdout().contains(persistentTopicName)); assertTrue(result.getStdout().contains(nonPersistentTopicName)); try { container.execCmd( PulsarCluster.ADMIN_SCRIPT, "topics", "list", "--topic-domain", "none", namespace); fail(); } catch (ContainerExecException ignore) { } producer1.close(); producer2.close(); } @Test public void testCreateSubscriptionCommand() throws Exception { String topic = "testCreateSubscriptionCommmand"; String subscriptionPrefix = "subscription-"; int i = 0; for (BrokerContainer container : pulsarCluster.getBrokers()) { ContainerExecResult result = container.execCmd( PulsarCluster.ADMIN_SCRIPT, "topics", "create-subscription", "persistent://public/default/" + topic, "--subscription", "" + subscriptionPrefix + i ); result.assertNoOutput(); i++; } } @Test public void testCreateUpdateSubscriptionWithPropertiesCommand() throws Exception { String topic = "testCreateSubscriptionCommmand"; String subscriptionPrefix = "subscription-"; int i = 0; for (BrokerContainer container : pulsarCluster.getBrokers()) { ContainerExecResult result = container.execCmd( PulsarCluster.ADMIN_SCRIPT, "topics", "create-subscription", "-p", "a=b", "-p", "c=d", "persistent://public/default/" + topic, "--subscription", "" + subscriptionPrefix + i ); result.assertNoOutput(); ContainerExecResult resultUpdate = container.execCmd( PulsarCluster.ADMIN_SCRIPT, "topics", "update-subscription-properties", "-p", "a=e", "persistent://public/default/" + topic, "--subscription", "" + subscriptionPrefix + i ); resultUpdate.assertNoOutput(); ContainerExecResult resultClear = container.execCmd( PulsarCluster.ADMIN_SCRIPT, "topics", "update-subscription-properties", "-c", "persistent://public/default/" + topic, "--subscription", "" + subscriptionPrefix + i ); resultClear.assertNoOutput(); i++; } } @Test public void testTopicTerminationOnTopicsWithoutConnectedConsumers() throws Exception { String topicName = "persistent://public/default/test-topic-termination"; BrokerContainer container = pulsarCluster.getAnyBroker(); container.execCmd( PulsarCluster.ADMIN_SCRIPT, "topics", "create", topicName); ContainerExecResult result = container.execCmd( PulsarCluster.CLIENT_SCRIPT, "produce", "-m", "\"test topic termination\"", "-n", "1", topicName); assertTrue(result.getStdout().contains("1 messages successfully produced")); // terminate the topic result = container.execCmd( PulsarCluster.ADMIN_SCRIPT, "topics", "terminate", topicName); assertTrue(result.getStdout().contains("Topic successfully terminated at")); // try to produce should fail try { pulsarCluster.getAnyBroker().execCmd(PulsarCluster.CLIENT_SCRIPT, "produce", "-m", "\"test topic termination\"", "-n", "1", topicName); fail("Command should have exited with non-zero"); } catch (ContainerExecException e) { assertTrue(e.getResult().getStdout().contains("Topic was already terminated")); } } @Test public void testPropertiesCLI() throws Exception { final BrokerContainer container = pulsarCluster.getAnyBroker(); final String namespace = "public/default"; ContainerExecResult result = container.execCmd( PulsarCluster.ADMIN_SCRIPT, "namespaces", "set-property", "-k", "a", "-v", "a", namespace); assertTrue(result.getStdout().isEmpty()); result = container.execCmd( PulsarCluster.ADMIN_SCRIPT, "namespaces", "get-property", "-k", "a", namespace); assertTrue(result.getStdout().contains("a")); result = container.execCmd( PulsarCluster.ADMIN_SCRIPT, "namespaces", "remove-property", "-k", "a", namespace); assertTrue(result.getStdout().contains("a")); result = container.execCmd( PulsarCluster.ADMIN_SCRIPT, "namespaces", "remove-property", "-k", "a", namespace); assertTrue(result.getStdout().contains("null")); result = container.execCmd( PulsarCluster.ADMIN_SCRIPT, "namespaces", "set-properties", "-p", "a=a,b=b,c=c", namespace); assertTrue(result.getStdout().isEmpty()); result = container.execCmd( PulsarCluster.ADMIN_SCRIPT, "namespaces", "get-properties", namespace); assertFalse(result.getStdout().isEmpty()); result = container.execCmd( PulsarCluster.ADMIN_SCRIPT, "namespaces", "clear-properties", namespace); assertTrue(result.getStdout().isEmpty()); try { container.execCmd( PulsarCluster.ADMIN_SCRIPT, "bookies", "set-bookie-rack", "-b", "localhost:8082", "-r", ""); fail("Command should have exited with non-zero"); } catch (ContainerExecException e) { assertEquals(e.getResult().getStderr(), "rack name is invalid, it should not be null, empty or '/'\n\n"); } try { container.execCmd( PulsarCluster.ADMIN_SCRIPT, "namespaces", "set-schema-autoupdate-strategy", namespace); } catch (ContainerExecException e) { assertEquals(e.getResult().getStderr(), "Either --compatibility or --disabled must be specified\n\n"); } } @Test public void testSchemaCLI() throws Exception { BrokerContainer container = pulsarCluster.getAnyBroker(); String topicName = "persistent://public/default/test-schema-cli"; ContainerExecResult result = container.execCmd( PulsarCluster.CLIENT_SCRIPT, "produce", "-m", "\"test topic schema\"", "-n", "1", topicName); assertTrue(result.getStdout().contains("1 messages successfully produced")); result = container.execCmd( PulsarCluster.ADMIN_SCRIPT, "schemas", "upload", topicName, "-f", "/pulsar/conf/schema_example.conf" ); result.assertNoOutput(); // get schema result = container.execCmd( PulsarCluster.ADMIN_SCRIPT, "schemas", "get", topicName); assertTrue(result.getStdout().contains("\"type\": \"STRING\"")); // delete the schema result = container.execCmd( PulsarCluster.ADMIN_SCRIPT, "schemas", "delete", topicName); result.assertNoOutput(); // get schema again try { container.execCmd(PulsarCluster.ADMIN_SCRIPT, "schemas", "get", "persistent://public/default/test-schema-cli" ); fail("Command should have exited with non-zero"); } catch (ContainerExecException e) { assertTrue(e.getResult().getStderr().contains("Schema not found")); } try { container.execCmd( PulsarCluster.ADMIN_SCRIPT, "schemas", "extract", "--jar", "/pulsar/examples/api-examples.jar", "--type", "xml", "--classname", "org.apache.pulsar.functions.api.examples.pojo.Tick", topicName); fail("Command should have exited with non-zero"); } catch (ContainerExecException e) { assertEquals(e.getResult().getStderr(), "Invalid schema type xml. Valid options are: avro, json\n\n"); } } @Test public void testSetInfiniteRetention() throws Exception { ContainerExecResult result; String namespace = "get-and-set-retention" + randomName(8); pulsarCluster.createNamespace(namespace); String[] setCommand = { "namespaces", "set-retention", "public/" + namespace, "--size", "-1", "--time", "-1" }; result = pulsarCluster.runAdminCommandOnAnyBroker(setCommand); result.assertNoOutput(); String[] getCommand = { "namespaces", "get-retention", "public/" + namespace }; result = pulsarCluster.runAdminCommandOnAnyBroker(getCommand); assertTrue( result.getStdout().contains("\"retentionTimeInMinutes\" : -1"), result.getStdout()); assertTrue( result.getStdout().contains("\"retentionSizeInMB\" : -1"), result.getStdout()); } // authorization related tests @Test public void testGrantPermissionsAuthorizationDisabled() throws Exception { ContainerExecResult result; String namespace = "grant-permissions-" + randomName(8); result = pulsarCluster.createNamespace(namespace); assertEquals(0, result.getExitCode()); String[] grantCommand = { "namespaces", "grant-permission", "public/" + namespace, "--actions", "produce", "--role", "test-role" }; try { pulsarCluster.runAdminCommandOnAnyBroker(grantCommand); } catch (ContainerExecException cee) { result = cee.getResult(); assertTrue(result.getStderr().contains("HTTP 501 Not Implemented"), result.getStderr()); } } @Test public void testJarPojoSchemaUploadAvro() throws Exception { ContainerExecResult containerExecResult = pulsarCluster.runAdminCommandOnAnyBroker( "schemas", "extract", "--jar", "/pulsar/examples/api-examples.jar", "--type", "avro", "--classname", "org.apache.pulsar.functions.api.examples.pojo.Tick", "persistent://public/default/pojo-avro"); Assert.assertEquals(containerExecResult.getExitCode(), 0); testPublishAndConsume("persistent://public/default/pojo-avro", "avro", Schema.AVRO(Tick.class)); } @Test public void testJarPojoSchemaUploadJson() throws Exception { ContainerExecResult containerExecResult = pulsarCluster.runAdminCommandOnAnyBroker( "schemas", "extract", "--jar", "/pulsar/examples/api-examples.jar", "--type", "json", "--classname", "org.apache.pulsar.functions.api.examples.pojo.Tick", "persistent://public/default/pojo-json"); Assert.assertEquals(containerExecResult.getExitCode(), 0); testPublishAndConsume("persistent://public/default/pojo-json", "json", Schema.JSON(Tick.class)); } private void testPublishAndConsume(String topic, String sub, Schema type) throws PulsarClientException { @Cleanup PulsarClient client = PulsarClient.builder().serviceUrl(pulsarCluster.getPlainTextServiceUrl()).build(); @Cleanup Producer<Tick> producer = client.newProducer(type) .topic(topic + "-message") .create(); @Cleanup Consumer<Tick> consumer = client.newConsumer(type) .topic(topic + "-message") .subscriptionName(sub) .subscribe(); final int numOfMessages = 10; for (int i = 1; i < numOfMessages; ++i) { producer.send(new Tick(i, "Stock_" + i, 100 + i, 110 + i)); } for (int i = 1; i < numOfMessages; ++i) { Tick expected = new Tick(i, "Stock_" + i, 100 + i, 110 + i); Message<Tick> receive = consumer.receive(5, TimeUnit.SECONDS); Assert.assertEquals(receive.getValue(), expected); } } @Test public void testListNonPersistentTopicsCmd() throws Exception { String persistentTopic = "test-list-non-persistent-topic"; ContainerExecResult result = pulsarCluster.runAdminCommandOnAnyBroker("topics", "create", persistentTopic); assertEquals(result.getExitCode(), 0); HttpGet get = new HttpGet(pulsarCluster.getHttpServiceUrl() + "/admin/v2/non-persistent/public/default"); try (CloseableHttpClient client = HttpClients.createDefault(); CloseableHttpResponse response = client.execute(get)) { assertFalse(EntityUtils.toString(response.getEntity()).contains(persistentTopic)); } } @Test public void testGenerateDocForModule() throws Exception { String[] moduleNames = { "clusters", "tenants", "brokers", "broker-stats", "namespaces", "topics", "schemas", "bookies", "functions", "ns-isolation-policy", "resource-quotas", "functions", "sources", "sinks" }; BrokerContainer container = pulsarCluster.getAnyBroker(); for (int i = 0; i < moduleNames.length; i++) { ContainerExecResult result = container.execCmd( PulsarCluster.ADMIN_SCRIPT, "documents", "generate", moduleNames[i]); Assert.assertTrue(result.getStdout().contains("------------\n\n# " + moduleNames[i])); } } }
36.337413
117
0.564061
73c3c76ee9ad79a48944da87f0fe0f303485cf76
1,515
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package poo; import java.util.Scanner; /** * * @author Tutui */ public class Principal { /** * @param args the command line arguments */ public static void main(String[] args) { Dado dado1 = new Dado(); Dado dado2 = new Dado(); Jogador x = new Jogador(100); int op; while(true){ System.out.println("...Bem vindo ao JOGO DE DADOS 3000..."); System.out.println("1. Jogar"); System.out.println("2. Imprimir saldo"); System.out.println("3. Imprimir estatísticas"); System.out.println("4. Sair"); Scanner teclado = new Scanner(System.in); op = teclado.nextInt(); switch(op){ case 1: case 2: System.out.println("Você possui" + x.getSaldo() + "reais."); break; case 3: System.out.println("Estatística do dado 1:"); dado1.imprimirEstatisticas(); System.out.println("Estatística do dado 2:"); dado2.imprimirEstatisticas(); break; case 4: return; } } } }
26.578947
80
0.481188
381dbeb7a5d096f02d68c5ac5f3dbe9c9f98bbf6
4,835
package org.seqcode.genome.sequence.seqfunctions; import java.util.ArrayList; import java.util.List; import org.seqcode.genome.location.Point; import org.seqcode.genome.location.Region; import org.seqcode.genome.location.ScoredPoint; import org.seqcode.genome.location.ScoredStrandedPoint; import org.seqcode.genome.sequence.ScoredSequence; import org.seqcode.genome.sequence.SequenceGenerator; import org.seqcode.genome.sequence.SequenceUtils; /** * Create a composite scoring function of a particular type of SeqFunction * * @author mahony * * @param <F> SeqFunction */ public class CompositeSeqFunction<F extends SeqFunction> { F function; int width; double [][] means; double [][] variances; double [][][] rawScores; List<ScoredSequence> scoredSeqs; int zeroOffset=0; public CompositeSeqFunction(F fn, int width, int zeroOffset){ function = fn; this.width = width; means = new double[function.scoreDimension()][width]; variances = new double[function.scoreDimension()][width]; for(int i=0; i<function.scoreDimension(); i++) for(int j=0; j<width; j++){ means[i][j]=0; variances[i][j]=0; } this.scoredSeqs = new ArrayList<ScoredSequence>(); this.zeroOffset = zeroOffset; } //Accessors public int getWidth(){return width;} public double[][] getMeans(){return means;} public double[][] getVariances(){return variances;} public int getNumSeqs(){return scoredSeqs.size();} public F getFunction(){return function;} public int getZeroOffset(){return zeroOffset;} public double[][][] getAllScores(){return rawScores;} /** * Add sequences (possibly weighted) to the composite list * @param points */ public void addSequencesFromPoints(List<Point> points, SequenceGenerator seqgen){ for(Point p : points){ double weight = 1; char strand = '+'; if(p instanceof ScoredStrandedPoint){ strand = p.getStrand(); weight = ((ScoredPoint)p).getScore(); } Region r = new Region(p.getGenome(), p.getChrom(), p.getLocation()-(width/2)+1, p.getLocation()+(width/2)); String seq = seqgen.execute(r); //Handle minus strand regions if(strand=='-') seq = SequenceUtils.reverseComplement(seq); //Ignore regions that are too short (presumably because they are at the edge of the chromosome) if(seq.length()==width){ scoredSeqs.add(new ScoredSequence(seq, weight)); } } } /** * Add equally weighted sequences to the composite list * @param seqs */ public void addSequences(List<String> seqs){ for(String s : seqs){ if(s.length()==width){ scoredSeqs.add(new ScoredSequence(s, 1.0)); } } } /** * Add weighted sequences to the composite list * @param seqs */ public void addScoredSequences(List<ScoredSequence> sseqs){ scoredSeqs.addAll(sseqs); } /** * Populate the composite profile with regions of a fixed width around points * @param points */ public void populate(){ try{ int numSeqs = 0; double normTotal=0; //Weighted mean for(ScoredSequence s : scoredSeqs){ if(s.getSeq().length()==width){ numSeqs++; normTotal+=s.getScore(); double[][] tmpScores = function.score(s.getSeq()); for(int i=0; i<function.scoreDimension(); i++) for(int j=0; j<width; j++) means[i][j]+=(tmpScores[i][j]*s.getScore()); } } for(int i=0; i<function.scoreDimension(); i++) for(int j=0; j<width; j++) means[i][j] = means[i][j]/normTotal; //Init the raw scores rawScores = new double[function.scoreDimension()][width][numSeqs]; //Weighted variance & raw scores int sx=0; for(ScoredSequence s : scoredSeqs){ if(s.getSeq().length()==width){ double[][] tmpScores = function.score(s.getSeq()); for(int i=0; i<function.scoreDimension(); i++) for(int j=0; j<width; j++){ variances[i][j]+=s.getScore()*(tmpScores[i][j]-means[i][j])*(tmpScores[i][j]-means[i][j]); rawScores[i][j][sx]=tmpScores[i][j]; } sx++; } } for(int i=0; i<function.scoreDimension(); i++) for(int j=0; j<width; j++) variances[i][j] = variances[i][j]/normTotal; } catch (SeqFunctionException e) { e.printStackTrace(); } } public void printFunctionMeans(){ String[] labels = function.dimensionLabels(); for(int i=0; i<function.scoreDimension(); i++){ System.out.print(labels[i]); for(int j=0; j<width; j++) System.out.print("\t"+means[i][j]); System.out.println(""); } } public void printFunctionVariances(){ String[] labels = function.dimensionLabels(); for(int i=0; i<function.scoreDimension(); i++){ System.out.print(labels[i]); for(int j=0; j<width; j++) System.out.print("\t"+variances[i][j]); System.out.println(""); } } }
27.947977
110
0.64757
9ac28d91dfd1106a11165d2e17283d3d21f55661
2,230
/* * ============================================================================= * * Copyright (c) 2007-2010, The JASYPT team (http://www.jasypt.org) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * ============================================================================= */ package org.jasypt.encryption.pbe.config; /** * <p> * Common interface for config classes applicable to * {@link org.jasypt.encryption.pbe.StandardPBEStringEncryptor} objects. * This interface extends {@link PBEConfig} to add config parameters specific * to String encryption. * </p> * <p> * This interface lets the user create new <tt>PBEConfig</tt> * classes which retrieve values for this parameters from different * (and maybe more secure) sources (remote servers, LDAP, other databases...), * and do this transparently for the encryptor object. * </p> * <p> * The config objects passed to an encryptor <u>will only be queried once</u> * for each configuration parameter, and this will happen * during the initialization of the encryptor object. * </p> * <p> * For a default implementation, see {@link SimpleStringPBEConfig}. * </p> * * @since 1.3 * * @author Daniel Fern&aacute;ndez * */ public interface StringPBEConfig extends PBEConfig { /** * <p> * This parameter lets the user specify the form in which String output * will be encoded. Available encoding types are: * </p> * <ul> * <li><tt><b>base64</b></tt> (default)</li> * <li><tt><b>hexadecimal</b></tt></li> * </ul> * * @return The name of the encoding type for String output */ public String getStringOutputType(); }
31.408451
80
0.62287
6c93589331bfa05c055def2a269b42802ce508ba
2,982
/* * Copyright (c) 2014 Jeffrey Bian * * Permission is hereby granted, free of charge, to any person obtaining * a copy of this software and associated documentation files (the * "Software"), to deal in the Software without restriction, including * without limitation the rights to use, copy, modify, merge, publish, * distribute, sublicense, and/or sell copies of the Software, and to * permit persons to whom the Software is furnished to do so, subject to * the following conditions: * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * */ package com.taibaisoft.chip8.platform; public class CmdArgs { private String[] args_ = null; private ArgDef[] defs_ = null; private int len_ = 0; private String lastError_ = ""; public CmdArgs(ArgDef[] defs, String[] args) { defs_ = defs; args_ = args; if (args_!=null) len_ = args_.length; } private int ArgValueStart = 0; private ArgDef getMatchedDef(String arg, int start) { if (start==2) { for (ArgDef def : defs_) { if ( arg.substring(start).startsWith(def.name) ) { ArgValueStart = start+def.name.length(); return def; } } } else { // start==1, short match for (ArgDef def : defs_) { if ( arg.substring(start).startsWith(def.alias) ) { ArgValueStart = start+def.alias.length(); return def; } } } return null; } public String getLastError() { return lastError_; } public Arg getNext(int index) { if (args_==null || index>=len_ || index <0) { return null; } Arg v = new Arg(); String s = args_[index].trim(); ArgDef md = null; if (s.startsWith("--")) { md = getMatchedDef(s, 2); } else if (s.startsWith("-")) { md = getMatchedDef(s, 1); } if (md != null) { v.argName = md.name; if (md.value > 0) { if (ArgValueStart == s.length()) { // Not written together, proceed to next arg if (index < len_ - 1) { index++; v.argVal = args_[index].trim(); } else { lastError_ = "Option " + v.argName + " missing mandatory value."; v= null; } } else { v.argVal = s.substring(ArgValueStart); } } } else { // No matching v.argName = ""; v.argVal = s; } if (index==len_-1) { v.nextIndex = -1; } else { v.nextIndex = index+1; } return v; } }
27.611111
74
0.622066
1742e362f82565e053c9f3cadedd5a89a4baa064
413
package kr.starbridge.web.domain.bridge.service; import kr.starbridge.web.domain.bridge.entity.PlayerEntity; import java.util.Optional; public interface PlayerService { /** * 플레이어 플래그 * @param id * @return */ Optional<PlayerEntity> getPlayerFlag(String id); /** * save * @param playerEntity * @return */ PlayerEntity save(PlayerEntity playerEntity); }
17.956522
59
0.653753
e0ab257da4491969ae884687be2ab3c4b17ba338
7,508
/* * Copyright 2015 Valeriy Filatov. * * 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 ru.fly.client.ui; import com.google.gwt.core.client.GWT; import com.google.gwt.dom.client.Element; import com.google.gwt.dom.client.Style; import com.google.gwt.user.client.DOM; import com.google.gwt.user.client.ui.Widget; import ru.fly.client.F; import java.util.HashMap; import java.util.Map; /** * User: fil * Date: 05.08.13 * Time: 23:05 */ public class Component extends Widget{ private final ComponentDecor decor = GWT.create(ComponentDecor.class); private Map<String, Object> data; private boolean firstAttached = false; private boolean disabled = false; protected int width; protected int height; private FElement maskEl; public Component(Element el){ setElement(el); } protected void onAfterFirstAttach(){ if(disabled) disable(); } public FElement getElement() { return super.getElement().cast(); } @Override protected void onAttach() { super.onAttach(); if(!firstAttached){ onAfterFirstAttach(); firstAttached = true; } } public Style getStyle(){ return getElement().getStyle(); } public Component withPixelsize(int width, int height) { setPixelSize(width, height); return this; } public void setWidth(int width){ setPixelSize(width, -1); } public Component withWidth(int width){ setWidth(width); return this; } public int getWidth(){ return getWidth(false); } public int getWidth(boolean client){ int w = getElement().getWidth(client); return w > 0 ? w : this.width; } public void setHeight(int height){ setPixelSize(-1, height); } public Component withHeight(int height){ setHeight(height); return this; } public int getHeight(){ return getHeight(false); } public int getHeight(boolean client){ int h = getElement().getHeight(client); return h > 0 ? h : this.height; } public void clearHeight() { getElement().clearHeight(); } public void setLeft(int left){ getElement().setLeft(left); } public void clearLeft(){ getElement().clearLeft(); } public void setRight(int right){ getElement().setRight(right); } public void clearRight(){ getElement().clearRight(); } public void setTop(int top){ getElement().setTop(top); } public void clearTop(){ getElement().clearTop(); } public void setBottom(int bottom){ getElement().setBottom(bottom); } public void clearBottom(){ getElement().clearBottom(); } public void setPosition(int left, int top){ setLeft(left); setTop(top); } public void setVisibility(boolean value){ if(value) getStyle().clearVisibility(); else getStyle().setVisibility(Style.Visibility.HIDDEN); } public void setOpacity(double val){ getStyle().setOpacity(val); } public Component withOpacity(double val){ setOpacity(val); return this; } public void setMargin(int val){ getElement().setMargin(val); } public void setPadding(int val){ getElement().setPadding(val); } public Component withMargin(int val){ setMargin(val); return this; } public void setMarginLeft(int val){ getElement().setMarginLeft(val); } public Component withMarginLeft(int val){ setMarginLeft(val); return this; } public void setMarginRight(int val){ getElement().setMarginRight(val); } public Component withMarginRight(int val){ setMarginRight(val); return this; } public void setMarginTop(int val){ getElement().setMarginTop(val); } public Component withMarginTop(int val){ setMarginTop(val); return this; } public void setMarginBottom(int val){ getElement().setMarginBottom(val); } public Component withMarginBottom(int val){ setMarginBottom(val); return this; } public int getMarginLeft(){ Integer ret = F.asInteger(getStyle().getMarginLeft()); return ret == null ? 0 : ret; } public void setFloatLeft(){ getStyle().setFloat(Style.Float.LEFT); } public void setFloatRight(){ getStyle().setFloat(Style.Float.RIGHT); } public Component withFloatLeft(){ setFloatLeft(); return this; } public Component withFloatRight(){ setFloatRight(); return this; } public void setZIndex(int index){ getStyle().setZIndex(index); } public void setEnabled(boolean val){ disabled = !val; if(val){ removeStyleName(decor.css().disabled()); }else{ addStyleName(decor.css().disabled()); } } public void enable(){ setEnabled(true); } public void disable(){ setEnabled(false); } public boolean isEnabled(){ return !disabled; } public void mask(){ if(maskEl == null){ maskEl = DOM.createDiv().cast(); maskEl.setClassName(decor.css().mask()); FElement bgEl = DOM.createDiv().cast(); bgEl.setClassName(decor.css().maskBg()); maskEl.appendChild(bgEl); FElement runnerEl = DOM.createDiv().cast(); runnerEl.setClassName(decor.css().maskRunner()); maskEl.appendChild(runnerEl); } String position = getStyle().getPosition(); if(position == null || position.isEmpty() || Style.Position.STATIC.name().equalsIgnoreCase(position)){ maskEl.setAttribute("f-old-position", position); getStyle().setPosition(Style.Position.RELATIVE); } getElement().appendChild(maskEl); } public void unmask(){ if(maskEl == null) { return; } String oldPosition = maskEl.getAttribute("f-old-position"); if(oldPosition != null && !oldPosition.isEmpty()){ getStyle().setProperty("position", oldPosition); } maskEl.removeFromParent(); } public void setData(String key, Object val){ if(data == null) { data = new HashMap<String, Object>(); } data.put(key, val); } public Object getData(String key){ if(data == null) { return null; } return data.get(key); } @Override public void setPixelSize(int width, int height) { if(width >= 0) { this.width = width; } if(height >= 0) { this.height = height; } super.setPixelSize(width, height); } }
23.389408
110
0.593633
6c6853cd8b4849c1a55eee955c04d25c3c874f14
5,957
/* * Copyright 2002-2019 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.test.context.junit4; import java.io.IOException; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.util.concurrent.atomic.AtomicInteger; import org.junit.Ignore; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runner.Runner; import org.junit.runners.Parameterized; import org.junit.runners.Parameterized.Parameters; import org.springframework.test.annotation.Repeat; import org.springframework.test.annotation.Timed; import org.springframework.test.context.TestExecutionListeners; import org.springframework.util.ClassUtils; import static org.assertj.core.api.Assertions.assertThat; import static org.springframework.test.context.junit4.JUnitTestingUtils.runTestsAndAssertCounters; /** * Verifies proper handling of the following in conjunction with the * {@link SpringRunner}: * <ul> * <li>Spring's {@link Repeat @Repeat}</li> * <li>Spring's {@link Timed @Timed}</li> * </ul> * * @author Sam Brannen * @since 3.0 */ @RunWith(Parameterized.class) public class RepeatedSpringRunnerTests { protected static final AtomicInteger invocationCount = new AtomicInteger(); private final Class<?> testClass; private final int expectedFailureCount; private final int expectedStartedCount; private final int expectedFinishedCount; private final int expectedInvocationCount; @Parameters(name = "{0}") public static Object[][] repetitionData() { return new Object[][]{// {NonAnnotatedRepeatedTestCase.class.getSimpleName(), 0, 1, 1, 1},// {DefaultRepeatValueRepeatedTestCase.class.getSimpleName(), 0, 1, 1, 1},// {NegativeRepeatValueRepeatedTestCase.class.getSimpleName(), 0, 1, 1, 1},// {RepeatedFiveTimesRepeatedTestCase.class.getSimpleName(), 0, 1, 1, 5},// {RepeatedFiveTimesViaMetaAnnotationRepeatedTestCase.class.getSimpleName(), 0, 1, 1, 5},// {TimedRepeatedTestCase.class.getSimpleName(), 3, 4, 4, (5 + 1 + 4 + 10)} // }; } public RepeatedSpringRunnerTests(String testClassName, int expectedFailureCount, int expectedTestStartedCount, int expectedTestFinishedCount, int expectedInvocationCount) throws Exception { this.testClass = ClassUtils.forName(getClass().getName() + "." + testClassName, getClass().getClassLoader()); this.expectedFailureCount = expectedFailureCount; this.expectedStartedCount = expectedTestStartedCount; this.expectedFinishedCount = expectedTestFinishedCount; this.expectedInvocationCount = expectedInvocationCount; } protected Class<? extends Runner> getRunnerClass() { return SpringRunner.class; } @Test public void assertRepetitions() throws Exception { invocationCount.set(0); runTestsAndAssertCounters(getRunnerClass(), this.testClass, expectedStartedCount, expectedFailureCount, expectedFinishedCount, 0, 0); assertThat(invocationCount.get()).as("invocations for [" + testClass + "]:").isEqualTo(expectedInvocationCount); } @TestExecutionListeners({}) public abstract static class AbstractRepeatedTestCase { protected void incrementInvocationCount() throws IOException { invocationCount.incrementAndGet(); } } public static final class NonAnnotatedRepeatedTestCase extends AbstractRepeatedTestCase { @Test @Timed(millis = 10000) public void nonAnnotated() throws Exception { incrementInvocationCount(); } } public static final class DefaultRepeatValueRepeatedTestCase extends AbstractRepeatedTestCase { @Test @Repeat @Timed(millis = 10000) public void defaultRepeatValue() throws Exception { incrementInvocationCount(); } } public static final class NegativeRepeatValueRepeatedTestCase extends AbstractRepeatedTestCase { @Test @Repeat(-5) @Timed(millis = 10000) public void negativeRepeatValue() throws Exception { incrementInvocationCount(); } } public static final class RepeatedFiveTimesRepeatedTestCase extends AbstractRepeatedTestCase { @Test @Repeat(5) public void repeatedFiveTimes() throws Exception { incrementInvocationCount(); } } @Repeat(5) @Retention(RetentionPolicy.RUNTIME) private static @interface RepeatedFiveTimes { } public static final class RepeatedFiveTimesViaMetaAnnotationRepeatedTestCase extends AbstractRepeatedTestCase { @Test @RepeatedFiveTimes public void repeatedFiveTimes() throws Exception { incrementInvocationCount(); } } /** * Unit tests for claims raised in <a href="https://jira.spring.io/browse/SPR-6011" target="_blank">SPR-6011</a>. */ @Ignore("TestCase classes are run manually by the enclosing test class") public static final class TimedRepeatedTestCase extends AbstractRepeatedTestCase { @Test @Timed(millis = 1000) @Repeat(5) public void repeatedFiveTimesButDoesNotExceedTimeout() throws Exception { incrementInvocationCount(); } @Test @Timed(millis = 10) @Repeat(1) public void singleRepetitionExceedsTimeout() throws Exception { incrementInvocationCount(); Thread.sleep(15); } @Test @Timed(millis = 20) @Repeat(4) public void firstRepetitionOfManyExceedsTimeout() throws Exception { incrementInvocationCount(); Thread.sleep(25); } @Test @Timed(millis = 100) @Repeat(10) public void collectiveRepetitionsExceedTimeout() throws Exception { incrementInvocationCount(); Thread.sleep(11); } } }
30.085859
118
0.762296
4833e53477ce9308fdbf76a4028863d19d09508c
5,056
/* * Copyright 2019-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 * * 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.aot.context.annotation; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.util.Collections; import java.util.List; import java.util.Map; import java.util.function.Supplier; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.springframework.beans.BeansException; import org.springframework.beans.factory.BeanCreationException; import org.springframework.beans.factory.config.BeanPostProcessor; import org.springframework.beans.factory.config.ConfigurableBeanFactory; import org.springframework.beans.factory.config.DestructionAwareBeanPostProcessor; import org.springframework.context.annotation.CommonAnnotationBeanPostProcessor; import org.springframework.core.Ordered; import org.springframework.util.ReflectionUtils; /** * A {@link BeanPostProcessor} that provides the same init/destroy callback features than * {@link CommonAnnotationBeanPostProcessor} using a pre-computed list. * * @author Stephane Nicoll */ public class InitDestroyBeanPostProcessor implements BeanPostProcessor, DestructionAwareBeanPostProcessor, Ordered { private static final Log logger = LogFactory.getLog(InitDestroyBeanPostProcessor.class); private final ConfigurableBeanFactory beanFactory; private final Map<String, List<String>> initMethods; private final Map<String, List<String>> destroyMethods; public InitDestroyBeanPostProcessor(ConfigurableBeanFactory beanFactory, Map<String, List<String>> initMethods, Map<String, List<String>> destroyMethods) { this.beanFactory = beanFactory; this.initMethods = initMethods; this.destroyMethods = destroyMethods; } @Override public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException { List<String> methodNames = this.initMethods.getOrDefault(beanName, Collections.emptyList()); for (String methodName : methodNames) { invokeInitMethod(bean, beanName, methodName); } return bean; } private void invokeInitMethod(Object bean, String beanName, String methodName) { Method method = findMethod(bean, methodName, () -> getBeanType(beanName)); if (logger.isTraceEnabled()) { logger.trace("Invoking init method on bean '" + beanName + "': " + method); } try { invokeMethod(bean, method); } catch (InvocationTargetException ex) { throw new BeanCreationException(beanName, "Invocation of init method failed", ex.getTargetException()); } catch (Throwable ex) { throw new BeanCreationException(beanName, "Failed to invoke init method", ex); } } @Override public void postProcessBeforeDestruction(Object bean, String beanName) throws BeansException { List<String> methodNames = this.destroyMethods.getOrDefault(beanName, Collections.emptyList()); for (String methodName : methodNames) { invokeDestroyMethod(bean, beanName, methodName); } } private void invokeDestroyMethod(Object bean, String beanName, String methodName) { Method method = findMethod(bean, methodName, () -> getBeanType(beanName)); if (logger.isTraceEnabled()) { logger.trace("Invoking destroy method on bean '" + beanName + "': " + method); } try { invokeMethod(bean, method); } catch (InvocationTargetException ex) { String msg = "Destroy method on bean with name '" + beanName + "' threw an exception"; if (logger.isDebugEnabled()) { logger.warn(msg, ex.getTargetException()); } else { logger.warn(msg + ": " + ex.getTargetException()); } } catch (Throwable ex) { logger.warn("Failed to invoke destroy method on bean with name '" + beanName + "'", ex); } } private Class<?> getBeanType(String beanName) { return (this.beanFactory.containsBean(beanName)) ? this.beanFactory.getMergedBeanDefinition(beanName).getResolvableType().toClass() : Object.class; } @Override public int getOrder() { return Ordered.LOWEST_PRECEDENCE; } private Method findMethod(Object bean, String methodName, Supplier<Class<?>> beanTypeSupplier) { Method method = ReflectionUtils.findMethod(bean.getClass(), methodName); if (method != null) { return method; } return ReflectionUtils.findMethod(beanTypeSupplier.get(), methodName); } private void invokeMethod(Object target, Method method) throws InvocationTargetException, IllegalAccessException { ReflectionUtils.makeAccessible(method); method.invoke(target, (Object[]) null); } }
35.858156
116
0.762658
d2d7d350f20be7c5d63d28dd1a1c1d466751fe46
1,884
package mrghastien.thermocraft.common.blocks.machines.boiler; import mrghastien.thermocraft.common.blocks.MachineBlock; import mrghastien.thermocraft.common.registries.ModTileEntities; import net.minecraft.core.BlockPos; import net.minecraft.core.Direction; import net.minecraft.world.level.Level; import net.minecraft.world.level.block.Block; import net.minecraft.world.level.block.entity.BlockEntity; import net.minecraft.world.level.block.entity.BlockEntityTicker; import net.minecraft.world.level.block.entity.BlockEntityType; import net.minecraft.world.level.block.state.BlockState; import net.minecraft.world.level.block.state.StateDefinition; import net.minecraft.world.level.block.state.properties.BlockStateProperties; import net.minecraft.world.level.material.Material; import net.minecraftforge.common.util.ForgeSoundType; import javax.annotation.Nonnull; import javax.annotation.Nullable; public class BoilerBlock extends MachineBlock { public BoilerBlock() { super(Properties.of(Material.METAL).sound(ForgeSoundType.METAL)); registerDefaultState(stateDefinition.any().setValue(BlockStateProperties.HORIZONTAL_FACING, Direction.NORTH).setValue(BlockStateProperties.LIT, false)); } @Override protected void createBlockStateDefinition(StateDefinition.Builder<Block, BlockState> builder) { builder.add(BlockStateProperties.HORIZONTAL_FACING, BlockStateProperties.LIT); } @Nullable @Override public BlockEntity newBlockEntity(@Nonnull BlockPos blockPos, @Nonnull BlockState blockState) { return new BoilerBlockEntity(blockPos, blockState); } @Nullable @Override public <A extends BlockEntity> BlockEntityTicker<A> getTicker(@Nonnull Level level, @Nonnull BlockState state, @Nonnull BlockEntityType<A> type) { return createTicker(level, type, ModTileEntities.BOILER.get()); } }
41.866667
160
0.798301
46b617dfdadc16ae1b4937e80cc2e79fce1a4666
5,485
/* * Copyright 2020 Matthew Denton * * 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 me.masstrix.eternalnature.core.temperature.modifier; import me.masstrix.eternalnature.util.ConfigUtil; import me.masstrix.eternalnature.util.WorldTime; import org.bukkit.World; import org.bukkit.configuration.ConfigurationSection; import org.bukkit.craftbukkit.libs.org.apache.commons.lang3.StringUtils; import org.bukkit.craftbukkit.libs.org.apache.commons.lang3.math.NumberUtils; import java.util.HashMap; import java.util.Map; public class TimeTemperature implements TemperatureModifier { public static final int TIME_IN_DAY = 24000; private final Map<Integer, Double> TIMES = new HashMap<>(); private double fallback = 0; /** * Loads the data from a configuration section and adds it to this modifier. This will * also remove all previously added times. * * @param section section to load. */ public void load(ConfigurationSection section) { if (section == null) return; ConfigUtil util = new ConfigUtil(section); for (String time : section.getKeys(false)) { int timeExact = WorldTime.MID_DAY.getTime(); if (StringUtils.isNumeric(time)) { // Exact time timeExact = Integer.parseInt(time); } else { // World based time WorldTime worldTime = WorldTime.find(time); if (worldTime != null) { timeExact = worldTime.getTime(); } } put(timeExact, util.getDouble(time)); } } /** * Puts a new value in for the time modifier. If the provided * time is invalid it will be ignored. * * @param time time of day for this modifier. This has to be * between 0 and 24000. * @param temp temperature to emit at this time. * @return an instance of this TimeTemperature. */ public TimeTemperature put(WorldTime time, double temp) { TIMES.put(time.getTime(), temp); fallback = temp; return this; } /** * Puts a new value in for the time modifier. If the provided * time is invalid it will be ignored. * * @param time time of day for this modifier. This has to be * between 0 and 24000. * @param temp temperature to emit at this time. * @return an instance of this TimeTemperature. */ public TimeTemperature put(int time, double temp) { if (time <= TIME_IN_DAY && time >= 0) { TIMES.put(time, temp); fallback = temp; } return this; } @Override public double getEmission() { return fallback; } /** * @return all the stored times and temperatures as a map. */ public Map<Integer, Double> getTimes() { return TIMES; } /** * Gets the worlds temperature based on the modifiers applied * for this time modifier. * * @param world world to get the emission for. * @return the emission value for this world. */ public double getLocalTemp(World world) { if (TIMES.size() <= 1 || world == null) return fallback; return getEmission((int) world.getTime()); } /** * Returns the temperature based on the from and to points between * between time. This will make the values linearly ease between * each other. * * @param time time to get the emission value for. * @return the emission value for that time. */ private double getEmission(int time) { int from = -1, to = -1; int smallest = Integer.MAX_VALUE; int largest = Integer.MIN_VALUE; for (int v : TIMES.keySet()) { if (v == time) { from = v; to = v; break; } if (v < smallest) smallest = v; if (v > largest) largest = v; // From if (from == -1 || v < time && time - v < time - from) { from = v; continue; } // To if (to == -1 || v > time && v - time < to - time) { to = v; } } // Update wrapping points. if (to < from) to = smallest; if (from > time) { to = from; from = largest; } // Gets the distance between to and from nodes int disFrom= from > time ? (TIME_IN_DAY - from) + time : time - from; int disTo = to < from && from <= time ? (TIME_IN_DAY + to) - time : to - time; // Gets the max distance value double maxDis = disFrom + disTo; double percentFrom = disTo / maxDis; double percentTo = disFrom / maxDis; return from == to ? TIMES.get(to) : TIMES.get(from) * percentFrom + TIMES.get(to) * percentTo; } }
31.342857
102
0.582862
39998e414e5f700dfc8b7be8a34cc110552dfddb
3,459
package com.loneboat.spacesloth.main.content.partsystem; import com.badlogic.gdx.Gdx; import com.badlogic.gdx.utils.Json; import com.badlogic.gdx.utils.JsonValue; import com.loneboat.spacesloth.main.SpaceSloth; import java.util.ArrayList; import java.util.HashMap; import java.util.Random; /** * com.loneboat.spacesloth.main.content.systems * Created by Dubpub on 8/30/2015. * * This class is solely responsible for handling the player's parts of their ship. * */ public class PartFactory { private static Random rand; private static SpaceSloth game; public static Json SeriesA; public static HashMap<String, Part> parts; public static class Property { private String key; private String value; private Property() {} public void setKey(String key) { this.key = key; } public void setValue(String value) { this.value = value; } public String getKey() { return key; } public Object getValue() { return value; } public float asFloat() { return Float.parseFloat(value); } } private PartFactory() {} public static PartFactory function(SpaceSloth game) { PartFactory.game = game; rand = new Random(); SeriesA = new Json(); parts = new HashMap<String, Part>(); ArrayList<?> list = SeriesA.fromJson(ArrayList.class, Gdx.files.internal("Parts/Series.json")); for(Object o : list) { if(o instanceof JsonValue) { JsonValue v = (JsonValue) o; Part temp = new Part(); temp.setRank(v.getString(0)); temp.setHealth(v.getFloat(1)); temp.setRepairFactor(v.getFloat(2)); temp.setCost(v.getDouble(3)); temp.setVisible(v.getBoolean(4)); temp.setLocalName(v.getString(5)); temp.setFileName(v.getString(6)); temp.setRGB(v.getString(7)); temp.setAlpha(v.getFloat(8)); temp.setShortHand(v.getString(9)); temp.setPartType(PartType.valueOf(v.getString(10))); if(v.get(11) != null && v.get(11).isArray()) { JsonValue propertyArray = v.get(11); int size = propertyArray.size; // This part has an array of properties, iterate it. for(int i = 0; i < size; i++) { Property property = SeriesA.fromJson(Property.class, v.get(11).get(i).toString()); temp.addProperty(property); } } parts.put(temp.getShortHand(), temp); } } game.getLogger().info("Loaded " + parts.size() + " parts!"); return new PartFactory(); } public static Part fetchPart(String key) { if(parts.containsKey(key)) return parts.get(key); return null; } public static Part fetchIncrementPart(Part toReplace) { return null; } public static Part fetchRandomPart(PartType pa) { Object[] values = parts.values().toArray(); Part randomPartOfType; do { randomPartOfType = (Part) values[rand.nextInt(values.length)]; } while(!randomPartOfType.getPartType().equals(pa)); return randomPartOfType; } }
31.445455
106
0.566349
ea20556b242e3c36337a2cced3899e7d1174fbd4
1,608
package at.ac.tuwien.dp.datascience.importer.csv; import at.ac.tuwien.dp.datascience.domain.entity.State; import at.ac.tuwien.dp.datascience.importer.data.StateDictionary; import org.apache.commons.csv.CSVFormat; import org.apache.commons.csv.CSVParser; import org.apache.commons.csv.CSVRecord; import org.apache.commons.io.IOUtils; import org.springframework.stereotype.Component; import java.io.IOException; import java.io.InputStream; import java.net.URISyntaxException; import java.net.URL; import java.nio.file.Files; import java.nio.file.Paths; import java.util.ArrayList; import java.util.List; import java.util.stream.Collectors; /** * Created by christoph on 16.05.17. */ @Component public class StateParser { private static final CSVFormat CSV_FORMAT = CSVFormat.EXCEL.withDelimiter(';'); public StateDictionary parse() throws IOException, URISyntaxException { try(InputStream input = getClass().getClassLoader().getResourceAsStream("OGD_f1197_Bev_Jahresdurchschn_1_C-B00-0.csv")) { List<String> lines = IOUtils.readLines(input, "UTF-8"); String content = lines.stream().skip(2).collect(Collectors.joining("\n")); List<State> states = new ArrayList<>(); for (CSVRecord record : CSVParser.parse(content, CSV_FORMAT)) { String code = record.get(0); String rawState = record.get(1); String state = rawState.substring(0, rawState.lastIndexOf(" ")); states.add(new State(code, state)); } return StateDictionary.of(states); } } }
34.212766
129
0.700249
442a72313b440a4da907a44ba5736ad80460c3ea
570
package com.muxter.ProxyPattern.virtual; import java.awt.*; import java.net.URL; /** * Created by matao on 10/02/2017. */ public class ImageIcon implements Icon { private URL imageURL; private String name; public ImageIcon(URL imageURL, String name) { this.imageURL = imageURL; this.name = name; } @Override public int getIconWidth() { return 0; } @Override public int getIconHeight() { return 0; } @Override public void paintIcon(Component c, Graphics g, int x, int y) { } }
16.764706
66
0.617544
f4b226188ca9fdf03dbc3c6787917fd139adee51
7,823
package org.imp.jvm.visitors; import org.imp.jvm.parser.Expr; import org.imp.jvm.types.BuiltInType; import org.imp.jvm.types.ImpType; import org.objectweb.asm.Label; import org.objectweb.asm.Opcodes; import org.objectweb.asm.Type; import org.objectweb.asm.commons.GeneratorAdapter; /** * Helper functions for CodegenVisitor. */ public class BinaryExprVisitor { public static void concatenateStrings(GeneratorAdapter ga, Expr.Binary expr, CodegenVisitor visitor) { ga.visitTypeInsn(Opcodes.NEW, "java/lang/StringBuilder"); ga.visitInsn(Opcodes.DUP); ga.visitMethodInsn(Opcodes.INVOKESPECIAL, "java/lang/StringBuilder", "<init>", "()V", false); expr.left.accept(visitor); String leftExprDescriptor = expr.left.realType.getDescriptor(); String descriptor = "(" + leftExprDescriptor + ")Ljava/lang/StringBuilder;"; ga.visitMethodInsn(Opcodes.INVOKEVIRTUAL, "java/lang/StringBuilder", "append", descriptor, false); expr.right.accept(visitor); String rightExprDescriptor = expr.right.realType.getDescriptor(); descriptor = "(" + rightExprDescriptor + ")Ljava/lang/StringBuilder;"; ga.visitMethodInsn(Opcodes.INVOKEVIRTUAL, "java/lang/StringBuilder", "append", descriptor, false); ga.visitMethodInsn(Opcodes.INVOKEVIRTUAL, "java/lang/StringBuilder", "toString", "()Ljava/lang/String;", false); } /** * Generates short-circuiting logical and behavior. * `expr.right` must never be executed if `expr.left` does not evaluate to true. */ public static void logicalAnd(GeneratorAdapter ga, Expr.Binary expr, CodegenVisitor visitor) { Label falseLabel = new Label(); // short-circuit evaluation, if left is false, skip remaining clauses and return "false" Label successLabel = new Label(); // both clauses are truthy, return "true" expr.left.accept(visitor); // get the truthiness of the left expression ga.ifZCmp(GeneratorAdapter.EQ, falseLabel); // if first expression is false, return early expr.right.accept(visitor); // get the truthiness of the right expression ga.ifZCmp(GeneratorAdapter.EQ, falseLabel); // if second expression is false, return false ga.push(true); // success ga.goTo(successLabel); // skip to end // if either case failed, return false ga.mark(falseLabel); ga.push(false); // if both cases pass, return true ga.mark(successLabel); } /** * Generates standard logical or behavior. * `expr.right` should only be executed if `expr.left` is false. */ public static void logicalOr(GeneratorAdapter ga, Expr.Binary expr, CodegenVisitor visitor) { Label falseLabel = new Label(); // short-circuit evaluation, if left is false, skip remaining clauses and return "false" Label successLabel = new Label(); // both clauses are truthy, return "true" Label endLabel = new Label(); expr.left.accept(visitor); // get the truthiness of the left expression ga.ifZCmp(GeneratorAdapter.NE, successLabel); // if first expression is true, return true // else, fallthrough to second expression expr.right.accept(visitor); // get the truthiness of the right expression ga.ifZCmp(GeneratorAdapter.NE, successLabel); // if second expression is false, return false ga.goTo(falseLabel); ga.mark(successLabel); ga.push(true); ga.goTo(endLabel); // skip to end // if either case failed, return false ga.mark(falseLabel); ga.push(false); // if both cases pass, return true ga.mark(endLabel); } public static void relational(GeneratorAdapter ga, Expr.Binary expr, CodegenVisitor visitor) { // Currently, only primitive comparisons are implemented var left = expr.left; var right = expr.right; // Cast to the "bigger" type int lWide = BuiltInType.widenings.getOrDefault((BuiltInType) left.realType, -1); int rWide = BuiltInType.widenings.getOrDefault((BuiltInType) right.realType, -1); var lType = Type.getType(left.realType.getDescriptor()); var rType = Type.getType(right.realType.getDescriptor()); var cmpType = lType; if (lWide != -1 && rWide != -1) { if (lWide > rWide) { left.accept(visitor); right.accept(visitor); ga.cast(rType, lType); } else if (lWide < rWide) { left.accept(visitor); ga.cast(lType, rType); right.accept(visitor); cmpType = rType; } else { // no cast needed left.accept(visitor); right.accept(visitor); } } else { // Todo: better define the operator rules with overloads etc // here be booleans left.accept(visitor); right.accept(visitor); } Label endLabel = new Label(); Label falseLabel = new Label(); int opcode = switch (expr.operator.type()) { case EQUAL -> GeneratorAdapter.NE; case NOTEQUAL -> GeneratorAdapter.EQ; case LT -> GeneratorAdapter.GT; case GT -> GeneratorAdapter.LT; case LE -> GeneratorAdapter.GE; case GE -> GeneratorAdapter.LE; default -> throw new IllegalStateException("Unexpected value: " + expr.operator.type()); }; // if false, jump to falseLabel ga.ifCmp(cmpType, opcode, falseLabel); // else set true and jump to endLabel ga.push(true); ga.goTo(endLabel); ga.mark(falseLabel); ga.push(false); ga.mark(endLabel); } public static void arithmetic(GeneratorAdapter ga, Expr.Binary expr, CodegenVisitor visitor) { var left = expr.left; var right = expr.right; ImpType goalType = expr.realType; if (left.realType.equals(right.realType)) { expr.left.accept(visitor); expr.right.accept(visitor); } else { // the types don't match if (left.realType == BuiltInType.INT && right.realType == BuiltInType.FLOAT) { expr.left.accept(visitor); ga.visitInsn(Opcodes.I2F); expr.right.accept(visitor); goalType = BuiltInType.FLOAT; } else if (left.realType == BuiltInType.FLOAT && right.realType == BuiltInType.INT) { expr.left.accept(visitor); expr.right.accept(visitor); ga.visitInsn(Opcodes.I2F); goalType = BuiltInType.FLOAT; } else if (left.realType == BuiltInType.INT && right.realType == BuiltInType.DOUBLE) { expr.left.accept(visitor); ga.visitInsn(Opcodes.I2D); expr.right.accept(visitor); goalType = BuiltInType.DOUBLE; } else if (left.realType == BuiltInType.DOUBLE && right.realType == BuiltInType.INT) { expr.left.accept(visitor); expr.right.accept(visitor); ga.visitInsn(Opcodes.I2D); goalType = BuiltInType.DOUBLE; } } int op = switch (expr.operator.type()) { case ADD -> goalType.getAddOpcode(); case SUB -> goalType.getSubtractOpcode(); case MUL -> goalType.getMultiplyOpcode(); case DIV -> goalType.getDivideOpcode(); // Todo: Modulus case MOD -> 0; case LT, GT, LE, GE -> 0; default -> throw new IllegalStateException("Unexpected value: " + expr.operator.type()); }; ga.visitInsn(op); } }
40.324742
128
0.609868
8693341d41a3254e4fe07c08efb9fe40404a7244
3,539
/** * Copyright 2015 SPeCS. * * 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. under the License. */ package org.specs.matlabprocessorprinter.printers; import java.io.PrintStream; import java.util.Arrays; import java.util.List; import org.specs.MatlabIR.MatlabNode.MatlabNode; import org.specs.MatlabIR.MatlabNode.nodes.root.FileNode; import org.specs.MatlabIR.MatlabNode.nodes.root.FunctionNode; import org.specs.MatlabIR.MatlabNodePass.CommonPassData; import org.specs.MatlabIR.MatlabNodePass.FunctionIdentification; import org.specs.MatlabIR.MatlabNodePass.interfaces.MatlabNodePass; import org.specs.matisselib.DefaultRecipes; import org.specs.matisselib.PreTypeInferenceServices; import org.specs.matisselib.passmanager.PassManager; import org.specs.matisselib.services.WideScopeService; import org.specs.matisselib.services.naming.CommonNamingService; import org.specs.matisselib.services.reporting.NodeReportService; import org.specs.matisselib.services.widescope.MockWideScopeService; import org.specs.matlabprocessorprinter.CodeGenerationSettings; import org.specs.matlabprocessorprinter.ContentPage; import org.suikasoft.jOptions.Interfaces.DataStore; import pt.up.fe.specs.util.providers.StringProvider; public abstract class DirectCodePrinter implements CodePrinter { @Override public List<ContentPage> getCode(String code, DataStore setup, FileNode file, PrintStream reportStream, CodeGenerationSettings settings) { WideScopeService projectWideScope = new MockWideScopeService(file); for (MatlabNode function : file.getFunctions()) { FunctionNode functionNode = ((FunctionNode) function); String functionName = functionNode.getFunctionName(); if (settings.applyPasses()) { CommonPassData passData = new CommonPassData("dummy"); passData.add(PassManager.NODE_REPORTING, new NodeReportService(reportStream, "file.m", StringProvider.newInstance(code))); WideScopeService wideScope = projectWideScope .withFunctionIdentification(projectWideScope .getUserFunction( new FunctionIdentification(file.getFilename() + ".m", functionName), functionName) .get()); passData.add(PreTypeInferenceServices.COMMON_NAMING, new CommonNamingService(wideScope, file)); for (MatlabNodePass pass : DefaultRecipes.DefaultMatlabASTTypeInferenceRecipe.getPasses()) { function = pass.apply(function, passData); } assert functionNode == function; } } String astCode = getAstCode(file); return Arrays.asList(new ContentPage("AST", astCode, getContentType())); } protected abstract String getContentType(); protected abstract String getAstCode(FileNode file); }
42.638554
118
0.707262
d87f8781fb71c3cefbede325b75b56ea9c3e5b93
651
package org.akj.springboot.common.exception; import java.io.Serializable; import lombok.Getter; import lombok.Setter; @Setter @Getter public class BusinessException extends RuntimeException implements Serializable { /** * serialVersionUID */ private static final long serialVersionUID = 7160449079887288990L; private String message = null; private String code = null; public BusinessException(String code, String message) { super(message); this.code = code; this.message = message; } public BusinessException(String message, String code, Throwable e) { super(message, e); this.message = message; this.code = code; } }
19.147059
81
0.751152
6acb86a838307ba76da163599289e29d8aeb61ea
3,316
package net.pbrennan.Lander_2009; import java.awt.Color; import java.awt.Graphics; import java.awt.Graphics2D; import java.awt.Image; import java.awt.Toolkit; import java.awt.geom.AffineTransform; public class LMSprite { private Image m_LMImage; private int width; private int height; private int half_width; private int half_height; private int paintCounter = 0; // number of times the LM has been painted. private int flashPeriod = 25; // number of times to paint the LM till we flash the running light. public LMSprite() { m_LMImage = Toolkit.getDefaultToolkit().createImage("images/LMSprite.png"); while (m_LMImage.getHeight(null) == -1) {}; width = m_LMImage.getWidth(null); half_width = width / 2; height = m_LMImage.getHeight(null); half_height = height / 2; } public void draw(Graphics g, int centerX, int centerY, double angleDegrees, double scale, Color color, double throttle) { double nangle = -angleDegrees * 3.14159265359 / 180.0 ; double scalefactor = scale * 0.005; // TODO: do better. Magic numbers! Boolean paintLight = false; if (scale < 2.0) scale = 2.0; if (scale <= 2.0) { g.setColor(color); g.fillRect((int)(centerX-scale), (int)(centerY-scale), (int)(scale*2), (int)(scale*2)); paintLight = false; } else { Graphics2D g2d = (Graphics2D)g; AffineTransform t = AffineTransform.getTranslateInstance(centerX, centerY); t.concatenate(AffineTransform.getRotateInstance(nangle)); t.concatenate(AffineTransform.getScaleInstance(scalefactor, scalefactor)); t.concatenate(AffineTransform.getTranslateInstance(-half_width, -half_height)); g2d.drawImage(m_LMImage, t, null); // Draw a reticle around the spacecraft. int left = (int)(centerX-scale); int right = (int)(centerX+scale); int top = (int)(centerY-scale); int btm = (int)(centerY+scale); int incr = Math.min(10, right-left); g.setColor(color); g.drawLine(left, top, left+incr, top); g.drawLine(left, top, left, top+incr); g.drawLine(left, btm, left+incr, btm); g.drawLine(left, btm, left, btm-incr); g.drawLine(right, top, right-incr, top); g.drawLine(right, top, right, top+incr); g.drawLine(right, btm, right-incr, btm); g.drawLine(right, btm, right, btm-incr); paintLight = true; } // Add the LM Tracking light. if ((++paintCounter >= flashPeriod) && paintLight) { paintCounter = 0; double L = 0.425 * scale; double x = centerX + L * Math.sin(nangle); double y = centerY - L * Math.cos(nangle); double R = 0.025 * scale; g.setColor(Color.WHITE); g.fillOval((int)(x-R),(int)(y-R),(int)(R*2),(int)(R*2)); } } }
36.43956
102
0.547045
687a2b4c837d8984aa1624424a1022261241271c
480
class Solution { public boolean XXX(int[] nums) { int start = 0; int end = 1; int maxPos = 0; while (start < end) { for (int i = start; i < end; i++) { maxPos = Math.max(maxPos, i + nums[i]); if (maxPos >= nums.length - 1) { return true; } } start = end; end = maxPos + nums[maxPos]; } return false; } }
21.818182
55
0.383333
ff4596b8dbec2886e6729d9001cd5cc7dadd0513
1,494
package com.pliance.app; import java.io.FileInputStream; import java.security.KeyStore; import java.security.KeyStoreException; import java.util.UUID; import junit.framework.TestCase; import pliance.sdk.IPlianceClient; import pliance.sdk.PlianceClientFactory; public abstract class TestBase extends TestCase { protected PlianceClientFactory _factory; protected IPlianceClient _client; protected String _secret; protected String _issuer; protected String _url; protected KeyStore _certificate; protected String _id; protected TestBase() throws Exception { _secret = "2bb80d537b1da3e38bd30361aa855686bde0eacd7162fef6a25fe97bf527a25b"; _issuer = "Demo"; _url = "https://local.pliance.io/"; _id = UUID.randomUUID().toString(); _certificate = KeyStore.getInstance("PKCS12"); _certificate.load(new FileInputStream("client.pfx"), "".toCharArray()); _factory = createFactory(); _client = _factory.create("Adam", "42"); } protected PlianceClientFactory createFactory() throws Exception { return new PlianceClientFactory(_secret, _issuer, _url, _certificate); } protected void Sync() throws Exception { Thread.sleep(200, 0); } protected <T extends Throwable> void assertThrows(Class<T> exceptionType, Action<Exception> func) throws Exception { try { func.accept(); throw new Exception(exceptionType.getTypeName() + " wasn't thrown"); } catch (Exception ex) { if (exceptionType.isInstance(ex)) { return; } else { throw ex; } } } }
28.188679
117
0.751673
549ccda857f1e775e8f326be26313a874c07c3f5
5,502
package com.comcast.cdn.traffic_control.traffic_router.core.hashing; import com.comcast.cdn.traffic_control.traffic_router.core.hash.ConsistentHasher; import com.comcast.cdn.traffic_control.traffic_router.core.hash.DefaultHashable; import com.comcast.cdn.traffic_control.traffic_router.core.hash.Hashable; import com.comcast.cdn.traffic_control.traffic_router.core.hash.MD5HashFunction; import com.comcast.cdn.traffic_control.traffic_router.core.hash.NumberSearcher; import org.junit.Before; import org.junit.Test; import org.mockito.InjectMocks; import org.mockito.Mock; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Random; import static org.hamcrest.Matchers.greaterThan; import static org.hamcrest.Matchers.lessThan; import static org.hamcrest.core.AnyOf.anyOf; import static org.hamcrest.core.IsEqual.equalTo; import static org.junit.Assert.assertThat; import static org.mockito.MockitoAnnotations.initMocks; public class ConsistentHasherTest { @Mock MD5HashFunction md5HashFunction = new MD5HashFunction(); @Mock NumberSearcher numberSearcher = new NumberSearcher(); @InjectMocks DefaultHashable hashable1 = new DefaultHashable(); @InjectMocks DefaultHashable hashable2 = new DefaultHashable(); @InjectMocks DefaultHashable hashable3 = new DefaultHashable(); List<DefaultHashable> hashables = new ArrayList<DefaultHashable>(); @InjectMocks ConsistentHasher consistentHasher; @Before public void before() { hashable1.generateHashes("hashId1", 100); hashable2.generateHashes("hashId2", 100); hashable3.generateHashes("hashId3", 100); hashables.add(hashable1); hashables.add(hashable2); hashables.add(hashable3); initMocks(this); } @Test public void itHashes() throws Exception { DefaultHashable hashable = consistentHasher.selectHashable(hashables, "some-string", false); assertThat(hashable, anyOf(equalTo(hashable1), equalTo(hashable2), equalTo(hashable3))); DefaultHashable nextHashable = consistentHasher.selectHashable(hashables, "some-string", false); assertThat(nextHashable, equalTo(hashable)); } @Test public void itHashesMoreThanOne() throws Exception { List<DefaultHashable> results = consistentHasher.selectHashables(hashables, 2, "some-string", false); assertThat(results.size(), equalTo(2)); assertThat(results.get(0), anyOf(equalTo(hashable1), equalTo(hashable2), equalTo(hashable3))); assertThat(results.get(1), anyOf(equalTo(hashable1), equalTo(hashable2), equalTo(hashable3))); assertThat(consistentHasher.selectHashables(hashables, 2, "some-string", false), equalTo(results)); assertThat(consistentHasher.selectHashables(hashables, 2000000000, "some-string", true), equalTo(hashables)); } @Test public void itemsMigrateFromSmallerToLargerBucket() { List<String> randomPaths = new ArrayList<>(); for (int i = 0; i < 10000; i++) { randomPaths.add(generateRandomPath()); } Hashable smallerBucket = new DefaultHashable().generateHashes("Small One", 10000); Hashable largerBucket = new DefaultHashable().generateHashes("Larger bucket", 90000); List<Hashable> buckets = new ArrayList<>(); buckets.add(smallerBucket); buckets.add(largerBucket); Map<Hashable, List<String>> hashedPaths = new HashMap<>(); hashedPaths.put(smallerBucket, new ArrayList<String>()); hashedPaths.put(largerBucket, new ArrayList<String>()); for (String randomPath : randomPaths) { Hashable hashable = consistentHasher.selectHashable(buckets, randomPath, false); hashedPaths.get(hashable).add(randomPath); } Hashable grownBucket = new DefaultHashable().generateHashes("Small One", 20000); Hashable shrunkBucket = new DefaultHashable().generateHashes("Larger bucket", 80000); List<Hashable> changedBuckets = new ArrayList<>(); changedBuckets.add(grownBucket); changedBuckets.add(shrunkBucket); Map<Hashable, List<String>> rehashedPaths = new HashMap<>(); rehashedPaths.put(grownBucket, new ArrayList<String>()); rehashedPaths.put(shrunkBucket, new ArrayList<String>()); for (String randomPath : randomPaths) { Hashable hashable = consistentHasher.selectHashable(changedBuckets, randomPath, false); rehashedPaths.get(hashable).add(randomPath); } assertThat(rehashedPaths.get(grownBucket).size(), greaterThan(hashedPaths.get(smallerBucket).size())); assertThat(rehashedPaths.get(shrunkBucket).size(), lessThan(hashedPaths.get(largerBucket).size())); for (String path : hashedPaths.get(smallerBucket)) { assertThat(rehashedPaths.get(grownBucket).contains(path), equalTo(true)); } for (String path : rehashedPaths.get(shrunkBucket)) { assertThat(hashedPaths.get(largerBucket).contains(path), equalTo(true)); } } String alphanumericCharacters = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWZYZ"; String exampleValidPathCharacters = alphanumericCharacters + "/=;()-."; Random random = new Random(1462307930227L); String generateRandomPath() { int pathLength = 60 + random.nextInt(61); StringBuilder stringBuilder = new StringBuilder("/"); for (int i = 0; i < 4; i++) { int index = random.nextInt(alphanumericCharacters.length()); stringBuilder.append(alphanumericCharacters.charAt(index)); } stringBuilder.append("/"); for (int i = 0; i < pathLength; i++) { int index = random.nextInt(exampleValidPathCharacters.length()); stringBuilder.append(exampleValidPathCharacters.charAt(index)); } return stringBuilder.toString(); } }
35.727273
111
0.770265
dca15d707123dd22e4ccdf8c2abf83d8e5496523
47,489
package net.thevpc.nuts.runtime.core.format.text.bloc; import net.thevpc.nuts.*; import net.thevpc.nuts.runtime.bundles.parsers.StringReaderExt; import net.thevpc.nuts.runtime.core.format.text.parser.DefaultNutsTextPlain; import java.io.BufferedReader; import java.io.IOException; import java.io.StringReader; import java.io.UncheckedIOException; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import net.thevpc.nuts.runtime.standalone.util.NutsWorkspaceUtils; import net.thevpc.nuts.spi.NutsComponent; import net.thevpc.nuts.NutsCodeFormat; import net.thevpc.nuts.spi.NutsSupportLevelContext; public class BashBlocTextFormatter implements NutsCodeFormat { private NutsWorkspace ws; private NutsTextManager factory; public BashBlocTextFormatter(NutsWorkspace ws) { this.ws = ws; factory = NutsWorkspaceUtils.defaultSession(ws).text(); } @Override public int getSupportLevel(NutsSupportLevelContext<String> context) { String s = context.getConstraints(); switch (s) { case "sh": case "bash": case "csh": case "zsh": case "ksh":{ return NutsComponent.DEFAULT_SUPPORT; } case "system": { switch (NutsShellFamily.getCurrent()) { case SH: case BASH: case CSH: case ZSH: case KSH:{ return NutsComponent.DEFAULT_SUPPORT + 10; } } return NutsComponent.DEFAULT_SUPPORT; } } return NutsComponent.NO_SUPPORT; } @Override public NutsText tokenToText(String text, String nodeType, NutsSession session) { factory.setSession(session); return factory.ofPlain(text); } private NutsText[] parseCommandLine_readSimpleQuotes(StringReaderExt ar, NutsSession session) { StringBuilder sb = new StringBuilder(); sb.append(ar.nextChar()); //quote! List<NutsText> ret = new ArrayList<>(); while (ar.hasNext()) { char c = ar.peekChar(); if (c == '\\') { StringBuilder sb2 = new StringBuilder(); sb2.append(ar.nextChar()); if (sb.length() > 0) { ret.add(factory.ofStyled(sb.toString(), NutsTextStyle.string(2))); sb.setLength(0); } if (ar.hasNext()) { sb2.append(ar.nextChar()); } ret.add(factory.ofStyled(sb2.toString(), NutsTextStyle.separator())); break; } else if (c == '\'') { sb.append(ar.nextChar()); break; } else { sb.append(ar.nextChar()); } } if (sb.length() > 0) { ret.add(factory.ofStyled(sb.toString(), NutsTextStyle.string(2))); sb.setLength(0); } return ret.toArray(new NutsText[0]); } private NutsText[] parseCommandLine_readWord(StringReaderExt ar, NutsSession session) { StringBuilder sb = new StringBuilder(); List<NutsText> ret = new ArrayList<>(); boolean inLoop = true; boolean endsWithSep = false; while (inLoop && ar.hasNext()) { char c = ar.peekChar(); switch (c) { case '\\': { if (sb.length() > 0) { ret.add(factory.ofPlain(sb.toString())); sb.setLength(0); } ret.addAll(Arrays.asList(parseCommandLine_readAntiSlash(ar, session))); break; } case ';': { endsWithSep = true; inLoop = false; break; } case ':': { endsWithSep = true; inLoop = false; break; } case '$': case '`': case '\"': case '\'': case '(': case ')': case '[': case ']': case '{': case '}': case '<': case '>': case '&': case '|': case '*': case '?': case '#': case '=': case '~': case '!': { inLoop = false; break; } default: { if (c <= 32) { endsWithSep = true; inLoop = false; } else { sb.append(ar.nextChar()); } } } } if (sb.length() > 0) { ret.add(factory.ofPlain(sb.toString())); sb.setLength(0); } if (ret.isEmpty()) { throw new IllegalArgumentException("was not expecting " + ar.peekChar() + " as part of word"); } if (ret.get(0).getType() == NutsTextType.PLAIN && isOption(((NutsTextPlain) ret.get(0)).getText())) { ret.set(0, factory.ofStyled(ret.get(0), NutsTextStyle.option())); } return ret.toArray(new NutsText[0]); } private static NutsText[] parseCommandLine_readAntiSlash(StringReaderExt ar, NutsSession session) { StringBuilder sb2 = new StringBuilder(); sb2.append(ar.nextChar()); if (ar.hasNext()) { sb2.append(ar.nextChar()); } NutsTextManager factory = session.text(); return new NutsText[]{factory.ofStyled(sb2.toString(), NutsTextStyle.separator())}; } private NutsText[] parseCommandLine_readDollar(StringReaderExt ar, NutsSession session) { if (ar.peekChars("$((")) { return parseCommandLine_readDollarPar2(ar, session); } StringBuilder sb2 = new StringBuilder(); if (ar.hasNext(1)) { switch (ar.peekChar(1)) { case '(': { return parseCommandLine_readDollarPar2(ar, session); } case '{': { return parseCommandLine_readDollarCurlyBrackets(ar, session); } case '*': case '?': case '@': case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': { sb2.append(ar.nextChar()); sb2.append(ar.nextChar()); return new NutsText[]{factory.ofStyled(sb2.toString(), NutsTextStyle.separator())}; } } } ar.nextChar(); while (ar.hasNext()) { char c = ar.peekChar(); if (Character.isAlphabetic(c) || Character.isDigit(c) || c == '_') { sb2.append(ar.nextChar()); } else { break; } } if (sb2.length() > 0) { return new NutsText[]{ factory.ofStyled("$", NutsTextStyle.separator()), factory.ofStyled(sb2.toString(), NutsTextStyle.keyword(4)),}; } return new NutsText[]{ factory.ofStyled("$", NutsTextStyle.separator()),}; } private NutsText[] parseCommandLine_readDoubleQuotes(StringReaderExt ar, NutsSession session) { List<NutsText> ret = new ArrayList<>(); factory.setSession(session); StringBuilder sb = new StringBuilder(); ret.add(factory.ofStyled(String.valueOf(ar.nextChar()), NutsTextStyle.string())); while (ar.hasNext()) { char c = ar.peekChar(); if (c == '\\') { if (sb.length() > 0) { ret.add(factory.ofStyled(sb.toString(), NutsTextStyle.string())); sb.setLength(0); } ret.addAll(Arrays.asList(parseCommandLine_readAntiSlash(ar, session))); } else if (c == '$') { if (sb.length() > 0) { ret.add(factory.ofStyled(sb.toString(), NutsTextStyle.string())); sb.setLength(0); } ret.addAll(Arrays.asList(parseCommandLine_readDollar(ar, session))); } else if (c == '\"') { if (sb.length() > 0) { ret.add(factory.ofStyled(sb.toString(), NutsTextStyle.string())); sb.setLength(0); } ret.add(factory.ofStyled(String.valueOf(ar.nextChar()), NutsTextStyle.string())); break; } else { sb.append(ar.nextChar()); } } if (sb.length() > 0) { ret.add(factory.ofStyled(sb.toString(), NutsTextStyle.string())); sb.setLength(0); } return ret.toArray(new NutsText[0]); } private enum TokenType{ ENV,WORD,SPACE,QUOTES,SEPARATORS,OTHER,EMPTY } private static TokenType resolveTokenType(NutsText n) { if (n instanceof DefaultNutsTextPlain) { String text = ((DefaultNutsTextPlain) n).getText(); if (text.length() > 0) { char c = text.charAt(0); switch (c) { case '\"': case '\'': case '`': { return TokenType.QUOTES; } case ';': case '&': case '|': case '(': case ')': case '[': case ']': case ',': return TokenType.SEPARATORS; default: { if (Character.isWhitespace(c)) { return TokenType.SPACE; } return TokenType.WORD; } } }else{ return TokenType.EMPTY; } } return TokenType.OTHER; } private static boolean isWhites(NutsText n) { if (n instanceof DefaultNutsTextPlain) { if (Character.isWhitespace(((DefaultNutsTextPlain) n).getText().charAt(0))) { return true; } } return false; } private static int indexOfFirstWord(List<NutsText> all, int from) { for (int i = from; i < all.size(); i++) { NutsText n = all.get(i); switch (resolveTokenType(n)){ case SPACE: case SEPARATORS: case ENV:{ break; } case WORD:{ if (i == all.size() - 1) { return i; } NutsText p = all.get(i + 1); switch (resolveTokenType(n)) { case SPACE: case SEPARATORS:{ return i; } } break; } } } return -1; } private NutsText[] parseCommandLine_readAntiQuotes(StringReaderExt ar, NutsSession session) { List<NutsText> all = new ArrayList<>(); factory.setSession(session); all.add(factory.ofStyled(String.valueOf(ar.nextChar()), NutsTextStyle.separator())); boolean inLoop = true; boolean wasSpace = true; while (inLoop && ar.hasNext()) { char c = ar.peekChar(); switch (c) { case '`': { wasSpace = false; all.add(factory.ofStyled(String.valueOf(ar.nextChar()), NutsTextStyle.separator())); inLoop = false; break; } default: { wasSpace = parseCommandLineStep(ar, all, 1, wasSpace, session); } } } return all.toArray(new NutsText[0]); } private NutsText[] parseCommandLine_readDollarPar(NutsWorkspace ws, StringReaderExt ar, NutsSession session) { List<NutsText> all = new ArrayList<>(); factory.setSession(session); all.add(factory.ofStyled(String.valueOf(ar.nextChar()) + ar.nextChar(), NutsTextStyle.separator())); boolean inLoop = true; boolean wasSpace = false; while (inLoop && ar.hasNext()) { char c = ar.peekChar(); switch (c) { case ')': { all.add(factory.ofStyled(String.valueOf(ar.nextChar()), NutsTextStyle.separator())); inLoop = false; break; } default: { wasSpace = parseCommandLineStep(ar, all, 2, wasSpace, session); } } } return all.toArray(new NutsText[0]); } private NutsText[] parseCommandLine_readDollarPar2(StringReaderExt ar, NutsSession session) { List<NutsText> all = new ArrayList<>(); factory.setSession(session); all.add(factory.ofStyled(String.valueOf(ar.nextChar()) + ar.nextChar() + ar.nextChar(), NutsTextStyle.separator())); boolean inLoop = true; boolean wasSpace = true; while (inLoop && ar.hasNext()) { char c = ar.peekChar(); switch (c) { case '+': case '-': case '*': case '/': case '%': { wasSpace = false; all.add(factory.ofStyled(String.valueOf(ar.nextChars(2)), NutsTextStyle.operator())); break; } case ')': { if (ar.peekChars(2).equals("))")) { wasSpace = false; all.add(factory.ofStyled(String.valueOf(ar.nextChars(2)), NutsTextStyle.separator())); inLoop = false; } else { wasSpace = parseCommandLineStep(ar, all, 2, wasSpace, session); } break; } default: { wasSpace = parseCommandLineStep(ar, all, 2, wasSpace, session); } } } return all.toArray(new NutsText[0]); } private NutsText[] parseCommandLine_readDollarCurlyBrackets(StringReaderExt ar, NutsSession session) { List<NutsText> all = new ArrayList<>(); factory.setSession(session); all.add(factory.ofStyled(String.valueOf(ar.nextChar()) + ar.nextChar(), NutsTextStyle.separator())); boolean inLoop = true; int startIndex = 0; boolean expectedName = true; boolean wasSpace = true; while (inLoop && ar.hasNext()) { char c = ar.peekChar(); switch (c) { case '}': { all.add(factory.ofStyled(String.valueOf(ar.nextChar()), NutsTextStyle.separator())); inLoop = false; break; } default: { startIndex = all.size(); wasSpace = parseCommandLineStep(ar, all, -1, wasSpace, session); if (expectedName) { expectedName = false; if (all.size() > startIndex) { TokenType t = resolveTokenType(all.get(startIndex)); if (t==TokenType.ENV || t==TokenType.WORD) { all.set(startIndex, factory.ofStyled(all.get(startIndex), NutsTextStyle.keyword(4))); wasSpace = false; } } } } } } return all.toArray(new NutsText[0]); } private NutsText[] parseCommandLine_readPar2(StringReaderExt ar, NutsSession session) { List<NutsText> all = new ArrayList<>(); factory.setSession(session); all.add(factory.ofStyled(String.valueOf(ar.nextChar()) + ar.nextChar(), NutsTextStyle.separator())); boolean inLoop = true; boolean wasSpace = true; while (inLoop && ar.hasNext()) { char c = ar.peekChar(); switch (c) { case ')': { if (ar.peekChars(2).equals("))")) { all.add(factory.ofStyled(String.valueOf(ar.nextChars(2)), NutsTextStyle.separator())); inLoop = false; } else { wasSpace = parseCommandLineStep(ar, all, 2, wasSpace, session); } break; } default: { wasSpace = parseCommandLineStep(ar, all, 2, wasSpace, session); } } } return all.toArray(new NutsText[0]); } /** * return is space * * @param ar ar * @param all all * @param startIndex startIndex * @param wasSpace wasSpace * @return is space */ private boolean parseCommandLineStep(StringReaderExt ar, List<NutsText> all, int startIndex, boolean wasSpace, NutsSession session) { char c = ar.peekChar(); if (c <= 32) { all.addAll(Arrays.asList(StringReaderExtUtils.readSpaces(session, ar))); return true; } switch (c) { case '\'': { all.addAll(Arrays.asList(parseCommandLine_readSimpleQuotes(ar, session))); break; } case '`': { all.addAll(Arrays.asList(parseCommandLine_readAntiQuotes(ar, session))); break; } case '"': { all.addAll(Arrays.asList(parseCommandLine_readDoubleQuotes(ar, session))); break; } case '$': { all.addAll(Arrays.asList(parseCommandLine_readDollar(ar, session))); break; } case ';': { all.add(factory.ofStyled(String.valueOf(ar.nextChar()), NutsTextStyle.separator())); break; } case ':': { all.add(factory.ofStyled(String.valueOf(ar.nextChar()), NutsTextStyle.separator(2))); break; } case '|': { if (ar.peekChars(2).equals("||")) { all.add(factory.ofStyled(ar.nextChars(2), NutsTextStyle.separator())); } else { all.add(factory.ofStyled(String.valueOf(ar.nextChar()), NutsTextStyle.separator())); } break; } case '&': { if (ar.peekChars(2).equals("&&")) { all.add(factory.ofStyled(ar.nextChars(2), NutsTextStyle.separator())); } else if (ar.peekChars(3).equals("&>>")) { all.add(factory.ofStyled(ar.nextChars(3), NutsTextStyle.separator())); } else if (ar.peekChars(2).equals("&>")) { all.add(factory.ofStyled(ar.nextChars(2), NutsTextStyle.separator())); } else { all.add(factory.ofStyled(String.valueOf(ar.nextChar()), NutsTextStyle.separator())); } break; } case '>': { if (ar.peekChars(2).equals(">>")) { all.add(factory.ofStyled(ar.nextChars(2), NutsTextStyle.separator())); } else if (ar.peekChars(2).equals(">&")) { all.add(factory.ofStyled(ar.nextChars(2), NutsTextStyle.separator())); } else { all.add(factory.ofStyled(String.valueOf(ar.nextChar()), NutsTextStyle.separator())); } break; } case '<': { if (ar.peekChars(2).equals("<<")) { all.add(factory.ofStyled(ar.nextChars(2), NutsTextStyle.separator())); } else { StringBuilder sb = new StringBuilder(); sb.append(ar.peekChar(0)); boolean ok = true; int i = 1; while (ok && ar.isAvailable(i)) { char c1 = ar.peekChar(i); if (c1 == '>') { sb.append(c1); break; } else if (c1 == '-' || c1 == '+' || Character.isAlphabetic(c1)) { sb.append(c1); } else { ok = false; } i++; } if (sb.charAt(sb.length() - 1) != '>') { ok = false; } if (ok) { String s = ar.nextChars(sb.length()); String s0 = s.substring(1, s.length() - 1); if (isSynopsysOption(s0)) { all.add(factory.ofStyled("<", NutsTextStyle.input())); all.add(factory.ofStyled(s0, NutsTextStyle.option())); all.add(factory.ofStyled(">", NutsTextStyle.input())); } else if (isSynopsysWord(s0)) { all.add(factory.ofStyled("<", NutsTextStyle.input())); all.add(factory.ofStyled(s0, NutsTextStyle.input())); all.add(factory.ofStyled(">", NutsTextStyle.input())); } else { all.add(factory.ofStyled(String.valueOf(ar.nextChar()), NutsTextStyle.separator())); } } else { all.add(factory.ofStyled(String.valueOf(ar.nextChar()), NutsTextStyle.separator())); } } break; } case '(': { if (ar.peekChars("((")) { all.addAll(Arrays.asList(parseCommandLine_readPar2(ar, session))); } else { all.add(factory.ofStyled(String.valueOf(ar.nextChar()), NutsTextStyle.separator())); } } case ')': case '{': case '}': case '~': case '!': { all.add(factory.ofStyled(String.valueOf(ar.nextChar()), NutsTextStyle.separator())); break; } case '*': case '?': case '[': case ']': case '=': { all.add(factory.ofStyled(String.valueOf(ar.nextChar()), NutsTextStyle.separator())); break; } case '#': { if (wasSpace) { StringBuilder sb = new StringBuilder(); while (ar.hasNext()) { c = ar.peekChar(); if (c == '\n') { break; } else if (c == '\r') { break; } else { sb.append(ar.nextChar()); } } all.add(factory.ofStyled(sb.toString(), NutsTextStyle.comments())); } else { all.add(factory.ofStyled(String.valueOf(ar.nextChar()), NutsTextStyle.separator())); } break; } default: { if (startIndex >= 0) { boolean first = all.size() == startIndex; all.addAll(Arrays.asList(parseCommandLine_readWord(ar, session))); if (first) { int i = indexOfFirstWord(all, startIndex); if (i >= 0) { all.set(i, factory.ofStyled(all.get(i), NutsTextStyle.keyword())); } } } else { all.addAll(Arrays.asList(parseCommandLine_readWord(ar, session))); } } } return false; } private NutsText[] parseCommandLine(String commandLineString, NutsSession session) { StringReaderExt ar = new StringReaderExt(commandLineString); List<NutsText> all = new ArrayList<>(); boolean wasSpace = true; while (ar.hasNext()) { wasSpace = parseCommandLineStep(ar, all, 0, wasSpace, session); } return all.toArray(new NutsText[0]); } private static boolean isSynopsysOption(String s2) { return ((s2.startsWith("--") && isSynopsysWord(s2.substring(2))) || (s2.startsWith("++") && isSynopsysWord(s2.substring(2))) || (s2.startsWith("-") && isSynopsysWord(s2.substring(1))) || (s2.startsWith("+") && isSynopsysWord(s2.substring(1))) || (s2.startsWith("--!") && isSynopsysWord(s2.substring(3))) || (s2.startsWith("++!") && isSynopsysWord(s2.substring(3))) || (s2.startsWith("-!") && isSynopsysWord(s2.substring(2))) || (s2.startsWith("+!") && isSynopsysWord(s2.substring(2))) || (s2.startsWith("--~") && isSynopsysWord(s2.substring(3))) || (s2.startsWith("++~") && isSynopsysWord(s2.substring(3))) || (s2.startsWith("-~") && isSynopsysWord(s2.substring(2))) || (s2.startsWith("+~") && isSynopsysWord(s2.substring(2)))); } private static boolean isOption(String s2) { return ((s2.startsWith("-")) || (s2.startsWith("+"))); } private static boolean isSynopsysWord(String s) { if (s.length() > 0) { if (!Character.isAlphabetic(s.charAt(0))) { return false; } if (!Character.isAlphabetic(s.charAt(0))) { return false; } for (int i = 0; i < s.length(); i++) { if (Character.isAlphabetic(s.charAt(i))) { //ok } else if (s.charAt(i) == '-') { if (s.charAt(i - 1) == '-') { return false; } } else { return false; } } return true; } return true; } @Override public NutsText stringToText(String text, NutsSession session) { factory.setSession(session); List<NutsText> all = new ArrayList<>(); BufferedReader reader = new BufferedReader(new StringReader(text)); String line = null; boolean first = true; while (true) { try { if ((line = reader.readLine()) == null) { break; } } catch (IOException ex) { throw new UncheckedIOException(ex); } if (first) { first = false; } else { all.add(factory.ofPlain("\n")); } all.add(commandToNode(line, session)); } return factory.ofList(all).simplify(); } public NutsText next(StringReaderExt reader, boolean exitOnClosedCurlBrace, boolean exitOnClosedPar, boolean exitOnDblQuote, boolean exitOnAntiQuote, NutsSession session) { boolean lineStart = true; List<NutsText> all = new ArrayList<>(); NutsTextManager factory = session.text(); boolean exit = false; while (!exit && reader.hasNext()) { switch (reader.peekChar()) { case '}': { lineStart = false; if (exitOnClosedCurlBrace) { exit = true; } else { all.add(factory.ofStyled( reader.nextChars(1), NutsTextStyle.separator() )); } break; } case ')': { lineStart = false; if (exitOnClosedPar) { exit = true; } else { all.add(factory.ofStyled( reader.nextChars(1), NutsTextStyle.separator() )); } break; } case '>': { lineStart = false; if (reader.isAvailable(2) && reader.peekChar() == '>') { all.add(factory.ofStyled( reader.nextChars(2), NutsTextStyle.separator() )); } else { all.add(factory.ofStyled( reader.nextChars(1), NutsTextStyle.separator() )); } break; } case '&': { lineStart = false; if (reader.isAvailable(2) && reader.peekChar() == '&') { all.add(factory.ofStyled( reader.nextChars(2), NutsTextStyle.separator() )); } else if (reader.isAvailable(2) && reader.peekChar() == '>') { all.add(factory.ofStyled( reader.nextChars(2), NutsTextStyle.separator() )); } else if (reader.isAvailable(2) && reader.peekChar() == '<') { all.add(factory.ofStyled( reader.nextChars(2), NutsTextStyle.separator() )); } else { all.add(factory.ofStyled( reader.nextChars(1), NutsTextStyle.separator() )); } break; } case '|': { lineStart = false; if (reader.isAvailable(2) && reader.peekChar() == '|') { all.add(factory.ofStyled( reader.nextChars(2), NutsTextStyle.separator() )); } else { all.add(factory.ofStyled( reader.nextChars(1), NutsTextStyle.separator() )); } break; } case ';': { all.add(factory.ofStyled( reader.nextChars(1), NutsTextStyle.separator() )); lineStart = true; break; } case '\n': { if (reader.isAvailable(2) && reader.peekChar() == '\r') { all.add(factory.ofStyled( reader.nextChars(2), NutsTextStyle.separator() )); } else { all.add(factory.ofStyled( reader.nextChars(1), NutsTextStyle.separator() )); } lineStart = true; break; } case '<': { lineStart = false; StringBuilder sb = new StringBuilder(); if (reader.isAvailable(3)) { int index = 0; sb.append(reader.peekChar(index)); index++; boolean ok = false; while (reader.isAvailable(index)) { char c = reader.peekChar(index); if (c == '>') { sb.append(c); ok = true; break; } else if (Character.isAlphabetic(c) || c == '-') { sb.append(c); } else { break; } index++; } if (ok) { reader.nextChars(sb.length()); all.add(factory.ofStyled( sb.toString(), NutsTextStyle.input() )); break; } else { all.add(factory.ofStyled( reader.nextChars(1), NutsTextStyle.separator() )); } } else if (reader.isAvailable(2) && reader.peekChar() == '<') { all.add(factory.ofStyled( reader.nextChars(2), NutsTextStyle.separator() )); } else { all.add(factory.ofStyled( reader.nextChars(1), NutsTextStyle.separator() )); } break; } case '\\': { lineStart = false; all.add(factory.ofStyled( reader.nextChars(2), NutsTextStyle.separator(2) )); break; } case '\"': { lineStart = false; all.add(nextDoubleQuotes(reader, session)); break; } case '`': { lineStart = false; if (exitOnAntiQuote) { exit = true; } else { List<NutsText> a = new ArrayList<>(); a.add(factory.ofStyled(reader.nextChars(1), NutsTextStyle.string())); a.add(next(reader, false, false, false, true, session)); if (reader.hasNext() && reader.peekChar() == '`') { a.add(factory.ofStyled(reader.nextChars(1), NutsTextStyle.string())); } else { exit = true; } all.add(factory.ofList(a).simplify()); } break; } case '\'': { lineStart = false; StringBuilder sb = new StringBuilder(); sb.append(reader.nextChar()); boolean end = false; while (!end && reader.hasNext()) { switch (reader.peekChar()) { case '\\': { sb.append(reader.nextChars(2)); break; } case '\'': { sb.append(reader.nextChar()); end = true; break; } default: { sb.append(reader.nextChar()); break; } } } all.add(factory.ofStyled(sb.toString(), NutsTextStyle.string())); break; } case '$': { lineStart = false; if (reader.isAvailable(2)) { char c = reader.peekChar(1); switch (c) { case '(': { break; } case '{': { break; } case '$': case '*': case '@': case '-': case '?': case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': { all.add(factory.ofStyled(reader.nextChars(2), NutsTextStyle.string())); break; } default: { if (Character.isAlphabetic(reader.peekChar(1))) { StringBuilder sb = new StringBuilder(); sb.append(reader.nextChar()); while (reader.hasNext() && (Character.isAlphabetic(reader.peekChar()) || reader.peekChar() == '_')) { sb.append(reader.nextChar()); } all.add(factory.ofStyled(sb.toString(), NutsTextStyle.variable())); } else { all.add(factory.ofStyled(reader.nextChars(1), NutsTextStyle.separator())); } } } } else { all.add(factory.ofStyled(reader.nextChars(1), NutsTextStyle.string())); } break; } case 0: case 1: case 2: case 3: case 4: case 5: case 6: case 7: case 8: case 9: case 11: case 12: case 13: case 14: case 15: case 16: case 17: case 18: case 19: case 20: case 21: case 22: case 23: case 24: case 25: case 26: case 27: case 28: case 29: case 30: case 31: case 33: { StringBuilder whites = new StringBuilder(); while (reader.hasNext() && Character.isWhitespace(reader.peekChar())) { whites.append(reader.nextChar()); } all.add(factory.ofPlain(whites.toString())); break; } default: { StringBuilder sb = new StringBuilder(); sb.append(reader.nextChar()); while (reader.hasNext()) { char c2 = reader.peekChar(); boolean accept = true; switch (c2) { case '$': case '<': case '>': case '&': case '|': case '{': case '}': case '(': case ')': case '[': case ']': case '*': case '+': case '?': case '\\': { accept = false; break; } default: { if (c2 <= 32) { accept = false; } else { sb.append(reader.nextChar()); } } } if (!accept) { break; } } if (lineStart && !reader.hasNext() || Character.isWhitespace(reader.peekChar())) { //command name NutsTextStyle keyword1 = NutsTextStyle.keyword(2); switch (sb.toString()) { case "if": case "while": case "do": case "fi": case "elif": case "then": case "else": { keyword1 = NutsTextStyle.keyword(); break; } case "cp": case "ls": case "ll": case "rm": case "pwd": case "echo": { keyword1 = NutsTextStyle.keyword(3); break; } } all.add(factory.ofStyled(sb.toString(), keyword1)); } else { all.add(factory.ofPlain(sb.toString())); } lineStart = false; break; } } } return factory.ofList(all).simplify(); } private NutsText nextDollar(StringReaderExt reader, NutsSession session) { NutsTextManager factory = session.text(); if (reader.isAvailable(2)) { char c = reader.peekChar(1); switch (c) { case '(': { List<NutsText> a = new ArrayList<>(); a.add(factory.ofStyled(reader.nextChars(1), NutsTextStyle.separator())); a.add(next(reader, false, true, false, false, session)); if (reader.hasNext() && reader.peekChar() == ')') { a.add(factory.ofStyled(reader.nextChars(1), NutsTextStyle.separator())); } return factory.ofList(a).simplify(); } case '{': { List<NutsText> a = new ArrayList<>(); a.add(factory.ofStyled(reader.nextChars(1), NutsTextStyle.separator())); a.add(next(reader, true, false, false, false, session)); if (reader.hasNext() && reader.peekChar() == ')') { a.add(factory.ofStyled(reader.nextChars(1), NutsTextStyle.separator())); } return factory.ofList(a).simplify(); } case '$': case '*': case '@': case '-': case '?': case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': { return factory.ofStyled(reader.nextChars(2), NutsTextStyle.string()); } default: { if (Character.isAlphabetic(reader.peekChar(1))) { StringBuilder sb = new StringBuilder(); sb.append(reader.nextChar()); while (reader.hasNext() && (Character.isAlphabetic(reader.peekChar()) || reader.peekChar() == '_')) { sb.append(reader.nextChar()); } return factory.ofStyled(sb.toString(), NutsTextStyle.variable()); } else { return factory.ofStyled(reader.nextChars(1), NutsTextStyle.separator()); } } } } else { return factory.ofStyled(reader.nextChars(1), NutsTextStyle.string()); } } public NutsText nextDoubleQuotes(StringReaderExt reader, NutsSession session) { List<NutsText> all = new ArrayList<>(); NutsTextManager factory = session.text(); boolean exit = false; StringBuilder sb = new StringBuilder(); sb.append(reader.nextChar()); while (!exit && reader.hasNext()) { switch (reader.peekChar()) { case '\\': { sb.append(reader.nextChars(2)); break; } case '\"': { sb.append(reader.nextChars(1)); exit = true; break; } case '$': { if (sb.length() > 0) { all.add(factory.ofStyled(sb.toString(), NutsTextStyle.string())); sb.setLength(0); } all.add(nextDollar(reader, session)); } case '`': { if (sb.length() > 0) { all.add(factory.ofStyled(sb.toString(), NutsTextStyle.string())); sb.setLength(0); } List<NutsText> a = new ArrayList<>(); a.add(factory.ofStyled(reader.nextChars(1), NutsTextStyle.string())); a.add(next(reader, false, false, false, true, session)); if (reader.hasNext() && reader.peekChar() == '`') { a.add(factory.ofStyled(reader.nextChars(1), NutsTextStyle.string())); } else { exit = true; } all.add(factory.ofList(a).simplify()); break; } default: { sb.append(reader.nextChars(1)); } } } if (sb.length() > 0) { all.add(factory.ofStyled(sb.toString(), NutsTextStyle.string())); sb.setLength(0); } return factory.ofList(all).simplify(); } public NutsText commandToNode(String text, NutsSession session) { factory.setSession(session); return factory.ofList(parseCommandLine(text, session)); } }
39.475478
176
0.401651
75b7c9bc464a0e7908b08b142d538965ca4176dd
1,164
package com.decucin.blog.config; import com.decucin.blog.handler.LoginIntercepter; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Configuration; import org.springframework.web.servlet.config.annotation.CorsRegistry; import org.springframework.web.servlet.config.annotation.InterceptorRegistry; import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; /** * @author :decucin * @date :Created in 2021/10/19 17:46 * @description:WebMVC配置,主要处理跨域问题 * @modified By: * @version: 1.0$ */ @Configuration public class WebMVCConfig implements WebMvcConfigurer { @Autowired private LoginIntercepter loginIntercepter; @Override public void addCorsMappings(CorsRegistry registry) { // 跨域配置,将前端项目部署在3000端口 registry.addMapping("/**").allowedOrigins("http://localhost:3000"); } @Override public void addInterceptors(InterceptorRegistry registry) { registry.addInterceptor(loginIntercepter) .addPathPatterns("/test") .excludePathPatterns("/login") .excludePathPatterns("/register"); } }
31.459459
77
0.737113
1b5d7478484408c51266b367b99223bf349a1b69
3,638
package cn.z201.redis; import lombok.extern.slf4j.Slf4j; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.redis.core.RedisTemplate; import org.springframework.data.redis.core.script.DefaultRedisScript; import org.springframework.stereotype.Service; import java.time.Duration; import java.util.*; import java.util.concurrent.TimeUnit; /** * @author z201.coding@gmail.com **/ @Service @Slf4j public class DistributedLockRedisTool { private static String LOCK_PREFIX = "lock:"; @Autowired private RedisTemplate redisTemplate; /** * 尝试获取分布式锁,设置重试次数 * * @param key * @param value * @param retries * @param timeout * @return */ public boolean lock(String key, String value, int retries, long timeout) { Boolean result = Boolean.FALSE; // 最多重试三次 if (retries > 3) { retries = 3; } if (retries > 0) { for (int i = 0; i < retries; i++) { result = lock(key, value, timeout); if (!result) { // 可以考虑线程随眠 i++; } } } return result; } /** * 设置锁,设置过期时间 * * @param key * @param value * @param timeout * @return */ public boolean lock(String key, String value, long timeout) { return tryLock(key, value, timeout, TimeUnit.SECONDS, 1, TimeUnit.SECONDS); } /** * 尝试获取分布式锁,并设置获取锁的超时时间 * * @param key 分布式锁 key * @param value 分布式锁 value * @param expireTime 锁的超时时间,防止死锁 * @param expireTimeUnit 锁的超时时间单位 * @param acquireTimeout 尝试获取锁的等待时间,如果在时间范围内获取锁失败,就结束获取锁 * @param acquireTimeoutUnit 尝试获取锁的等待时间单位 * @return 是否成功获取分布式锁 */ public boolean tryLock(String key, String value, long expireTime, TimeUnit expireTimeUnit, int acquireTimeout, TimeUnit acquireTimeoutUnit) { try { // 尝试自旋获取锁,等待配置的一段时间,如果在时间范围内获取锁失败,就结束获取锁 long end = System.currentTimeMillis() + acquireTimeoutUnit.toMillis(acquireTimeout); while (System.currentTimeMillis() < end) { // 尝试获取锁 Boolean result = redisTemplate.opsForValue().setIfAbsent(LOCK_PREFIX + key, value, expireTime, expireTimeUnit); // 验证是否成功获取锁 if (Objects.equals(Boolean.TRUE, result)) { log.info("tryLock success {} {} ", key, value); return true; } // 睡眠 50 毫秒 Thread.sleep(100); } } catch (InterruptedException e) { Thread.currentThread().interrupt(); } catch (Exception e) { log.error("tryLock {} {} error {}", key, value, e.getMessage()); } log.info("tryLock fail {} {} ", key, value); return false; } public boolean unlock(String key, String value) { String script = "if redis.call('get',KEYS[1]) == ARGV[1]" + "then" + " return redis.call('del',KEYS[1])" + "else " + " return 0 " + "end"; String[] args = new String[]{value}; DefaultRedisScript<Long> redisScript = new DefaultRedisScript<>(script, Long.class); Object result = redisTemplate.execute(redisScript, Collections.singletonList(LOCK_PREFIX + key), args); if (Objects.equals(result, 1L)) { log.info("unlock ok"); return true; } return false; } }
30.830508
145
0.556899
abc67bad53c54942d37275528b75fd19b5ddfd93
829
package com.jetpack.workermanager; import android.content.Context; import androidx.annotation.NonNull; import androidx.work.Worker; import androidx.work.WorkerParameters; import java.io.IOException; public class DownloadWorker extends Worker { public DownloadWorker(Context context, WorkerParameters params) { super(context, params); } @NonNull @Override public Result doWork() { for (int i = 0; i < 100; ++i) { if (isStopped()) { break; } try { downloadSynchronously("https://www.google.com"); } catch (IOException e) { return Result.failure(); } } return Result.success(); } private void downloadSynchronously(String url) throws IOException { } }
22.405405
71
0.599517
ee314df01b3863b1320fba05ad750d16ccbdbb21
3,775
/* * Copyright 2017 Red Hat, Inc. and/or its affiliates. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.kie.workbench.common.stunner.core.client.definition.adapter.binding; import java.util.HashMap; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.kie.workbench.common.stunner.core.definition.property.PropertyType; import org.kie.workbench.common.stunner.core.definition.property.type.BooleanType; import org.kie.workbench.common.stunner.core.definition.property.type.StringType; import org.mockito.runners.MockitoJUnitRunner; import static org.junit.Assert.assertEquals; import static org.mockito.Mockito.verify; @RunWith(MockitoJUnitRunner.class) public class ClientBindablePropertyAdapterTest extends AbstractClientBindableAdapterTest { private ClientBindablePropertyAdapter clientBindablePropertyAdapter; private final HashMap<Class, String> typesFieldNames = new HashMap<>(); private final HashMap<Class, PropertyType> types = new HashMap<>(); private final HashMap<Class, String> captionFieldNames = new HashMap<>(); private final HashMap<Class, String> descFieldNames = new HashMap<>(); private final HashMap<Class, String> readOnlyFieldNames = new HashMap<>(); private final HashMap<Class, String> optionalFieldNames = new HashMap<>(); private final HashMap<Class, String> valueFieldNames = new HashMap<>(); private final HashMap<Class, String> allowedFieldNames = new HashMap<>(); @Before @Override public void init() { super.init(); clientBindablePropertyAdapter = new ClientBindablePropertyAdapter(translationService); clientBindablePropertyAdapter.setBindings(typesFieldNames, types, captionFieldNames, descFieldNames, readOnlyFieldNames, optionalFieldNames, valueFieldNames, allowedFieldNames); } @Test public void test() { String description = clientBindablePropertyAdapter.getDescription(model); verify(translationService).getPropertyDescription(model.getClass().getName()); assertEquals(PROPERTY_DESCRIPTION, description); String caption = clientBindablePropertyAdapter.getCaption(model); verify(translationService).getPropertyCaption(model.getClass().getName()); assertEquals(PROPERTY_CAPTION, caption); } @Test public void testDefaultTypes() { types.put(Foo.class, new StringType()); types.put(Bar.class, new BooleanType()); final PropertyType fooType = clientBindablePropertyAdapter.getType(new Foo()); final PropertyType barType = clientBindablePropertyAdapter.getType(new Bar()); assertEquals(StringType.class, fooType.getClass()); assertEquals(BooleanType.class, barType.getClass()); } private static final class Foo { } private static final class Bar { } }
39.322917
94
0.672053
4ada4a5a10bed8b670d5a03ea7f4d7aa0dd567d3
1,037
package edu.gemini.collection; import java.util.SortedSet; import java.util.TreeSet; /** * Класс для демонстрации компараторов */ public class Main { public static void main(String[] args) { // Создаем объект класса SortedSet - стандартный класс для сортируемой коллекции // В качесве элементов - строки SortedSet<String> tr = new TreeSet<String>(); // Добавляем стандартные типы - строки tr.add("Павел"); tr.add("Петр"); tr.add("Андрей"); // И печатаем их for(String s: tr) { System.out.println(s); } // Создаем объект класса SortedSet - стандартный класс для сортируемой коллекции // В качестве элементов - свой класс SortedSet<MyClass> mt = new TreeSet<MyClass>(); // Добавляем НЕ стандартные типы mt.add(new MyClass("Павел")); mt.add(new MyClass("Петр")); mt.add(new MyClass("Андрей")); for(MyClass s: mt) { System.out.println(s); } } }
24.690476
88
0.593057
6daeb6aa528b0ea21a34aef02d24f74ca295ae66
682
package platinpython.vfxgenerator.util.registries; import net.minecraft.tileentity.TileEntityType; import net.minecraftforge.fml.RegistryObject; import platinpython.vfxgenerator.tileentity.VFXGeneratorTileEntity; import platinpython.vfxgenerator.util.RegistryHandler; public class TileEntityRegistry { public static void register() { } public static final RegistryObject<TileEntityType<VFXGeneratorTileEntity>> VFX_GENERATOR = RegistryHandler.TILE_ENTITY_TYPES.register( "vfx_generator", () -> TileEntityType.Builder.of(VFXGeneratorTileEntity::new, BlockRegistry.VFX_GENERATOR.get()) .build(null)); }
35.894737
138
0.747801
ac4a2fd94cd1f2d5943866f45aee8cbd6c48d5b2
3,345
/* * Copyright (c) 2020, Luis Felipe Sosa Alvarez. All rights reserved. * Use is subject to license terms. * * GESOFT-WORKFLOW-BACKEND */ package cl.com.gesoft.workflow.model; import javax.persistence.*; import javax.validation.constraints.NotEmpty; import javax.validation.constraints.NotNull; import javax.validation.constraints.Positive; import javax.validation.constraints.Size; import java.io.Serializable; import java.util.Objects; /** * The Class ProjectType. * * @autor Luis Felipe Sosa Alvarez luisfsosa@gmail.com */ @Entity @Table(name = "gwf_project_type") public class ProjectType implements Serializable, Cloneable { private static final long serialVersionUID = -2063100163493295742L; /** * Gets serial version uid. * * @return the serial version uid */ public static long getSerialVersionUID() { return serialVersionUID; } /** The id. */ @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Integer id; @Column(name = "name", nullable = false) @NotEmpty(message = "Name is required") @Size(max = 80) private String name; @Column(name = "duration" ,nullable = false) @NotNull(message = "Duration is required") @Positive @Size(max = 2) private Integer duration; /** * Gets the id. * * @return the id */ public Integer getId() { return id; } /** * Sets the id. * * @param id the new id */ public void setId(Integer id) { this.id = id; } /** * Gets the name. * * @return the name */ public String getName() { return name; } /** * Name. * * @param name the first name * @return the group */ public void setName(String name) { this.name = name; } /** * Gets duration. * * @return the duration */ public Integer getDuration() { return duration; } /** * Sets duration. * * @param duration the duration */ public void setDuration(Integer duration) { this.duration = duration; } /** * Equals. * * @param o the o * @return true, if successful */ @Override public boolean equals(Object o) { if (this == o) { return true; } if (!(o instanceof ProjectType)) { return false; } return id != null && Objects.equals(getId(), ((ProjectType) o).getId()); } /** * Hash code. * * @return the int */ @Override public int hashCode() { return Objects.hash(getId()); } /** * To Clone. * * @return the Group */ @Override public ProjectType clone() { ProjectType clon = null; try { clon = (ProjectType) super.clone(); } catch (CloneNotSupportedException e) { System.out.println(" no se puede duplicar"); } return clon; } /** * To string. * * @return the string */ @Override public String toString() { return "ProjectType{" + "id=" + getId() + ", name='" + getName() + "'" + ", duration='" + getDuration() + "'" + "}"; } }
20.02994
80
0.5429
29dc84358ef705b949425e33b12ce6149ea581f9
7,911
/* * Copyright 2002-2015 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.springframework.reactive.web.dispatch.method; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.Optional; import org.reactivestreams.Publisher; import reactor.Publishers; import reactor.fn.tuple.Tuple; import reactor.rx.Streams; import org.springframework.core.DefaultParameterNameDiscoverer; import org.springframework.core.GenericTypeResolver; import org.springframework.core.MethodParameter; import org.springframework.core.ParameterNameDiscoverer; import org.springframework.http.server.ReactiveServerHttpRequest; import org.springframework.util.ReflectionUtils; import org.springframework.web.method.HandlerMethod; /** * @author Rossen Stoyanchev */ public class InvocableHandlerMethod extends HandlerMethod { private List<HandlerMethodArgumentResolver> argumentResolvers = new ArrayList<>(); private ParameterNameDiscoverer parameterNameDiscoverer = new DefaultParameterNameDiscoverer(); public InvocableHandlerMethod(HandlerMethod handlerMethod) { super(handlerMethod); } public void setHandlerMethodArgumentResolvers(List<HandlerMethodArgumentResolver> resolvers) { this.argumentResolvers.clear(); this.argumentResolvers.addAll(resolvers); } public Publisher<Object> invokeForRequest(ReactiveServerHttpRequest request, Object... providedArgs) { List<Publisher<Object>> argPublishers = getMethodArguments(request, providedArgs); Publisher<Object[]> argValues = (!argPublishers.isEmpty() ? Streams.zip(argPublishers, this::unwrapOptionalArgValues) : Publishers.just(new Object[0])); return Publishers.map(argValues, args -> { if (logger.isTraceEnabled()) { logger.trace("Invoking [" + getBeanType().getSimpleName() + "." + getMethod().getName() + "] method with arguments " + Collections.singletonList(argPublishers)); } Object returnValue = null; try { returnValue = doInvoke(args); if (logger.isTraceEnabled()) { logger.trace("Method [" + getMethod().getName() + "] returned " + "[" + returnValue + "]"); } } catch (Exception ex) { // TODO: how to best handle error inside map? (also wrapping hides original ex) throw new IllegalStateException(ex); } return returnValue; }); } private List<Publisher<Object>> getMethodArguments(ReactiveServerHttpRequest request, Object... providedArgs) { MethodParameter[] parameters = getMethodParameters(); List<Publisher<Object>> valuePublishers = new ArrayList<>(parameters.length); for (int i = 0; i < parameters.length; i++) { MethodParameter parameter = parameters[i]; parameter.initParameterNameDiscovery(this.parameterNameDiscoverer); GenericTypeResolver.resolveParameterType(parameter, getBean().getClass()); Object value = resolveProvidedArgument(parameter, providedArgs); if (value != null) { valuePublishers.add(Publishers.just(value)); continue; } boolean resolved = false; for (HandlerMethodArgumentResolver resolver : this.argumentResolvers) { if (resolver.supportsParameter(parameter)) { try { valuePublishers.add(resolver.resolveArgument(parameter, request)); resolved = true; break; } catch (Exception ex) { String msg = buildArgErrorMessage("Error resolving argument", i); valuePublishers.add(Publishers.error(new IllegalStateException(msg, ex))); break; } } } if (!resolved) { String msg = buildArgErrorMessage("No suitable resolver for argument", i); valuePublishers.add(Publishers.error(new IllegalStateException(msg))); break; } } return valuePublishers; } private String buildArgErrorMessage(String message, int index) { MethodParameter param = getMethodParameters()[index]; message += " [" + index + "] [type=" + param.getParameterType().getName() + "]"; return getDetailedErrorMessage(message); } protected String getDetailedErrorMessage(String message) { return message + "\n" + "HandlerMethod details: \n" + "Controller [" + getBeanType().getName() + "]\n" + "Method [" + getBridgedMethod().toGenericString() + "]\n"; } private Object resolveProvidedArgument(MethodParameter parameter, Object... providedArgs) { if (providedArgs == null) { return null; } for (Object providedArg : providedArgs) { if (parameter.getParameterType().isInstance(providedArg)) { return providedArg; } } return null; } private void unwrapOptionalArgValues(Object[] args) { for (int i = 0; i < args.length; i++) { if (args[i] instanceof Optional) { Optional optional = (Optional) args[i]; args[i] = optional.isPresent() ? optional.get() : null; } } } private Object[] unwrapOptionalArgValues(Tuple tuple) { Object[] args = new Object[tuple.size()]; for (int i = 0; i < tuple.size(); i++) { args[i] = tuple.get(i); if (args[i] instanceof Optional) { Optional optional = (Optional) args[i]; args[i] = optional.isPresent() ? optional.get() : null; } } return args; } protected Object doInvoke(Object... args) throws Exception { ReflectionUtils.makeAccessible(getBridgedMethod()); try { return getBridgedMethod().invoke(getBean(), args); } catch (IllegalArgumentException ex) { assertTargetBean(getBridgedMethod(), getBean(), args); throw new IllegalStateException(getInvocationErrorMessage(ex.getMessage(), args), ex); } catch (InvocationTargetException ex) { // Unwrap for HandlerExceptionResolvers ... Throwable targetException = ex.getTargetException(); if (targetException instanceof RuntimeException) { throw (RuntimeException) targetException; } else if (targetException instanceof Error) { throw (Error) targetException; } else if (targetException instanceof Exception) { throw (Exception) targetException; } else { String msg = getInvocationErrorMessage("Failed to invoke controller method", args); throw new IllegalStateException(msg, targetException); } } } private void assertTargetBean(Method method, Object targetBean, Object[] args) { Class<?> methodDeclaringClass = method.getDeclaringClass(); Class<?> targetBeanClass = targetBean.getClass(); if (!methodDeclaringClass.isAssignableFrom(targetBeanClass)) { String msg = "The mapped controller method class '" + methodDeclaringClass.getName() + "' is not an instance of the actual controller bean instance '" + targetBeanClass.getName() + "'. If the controller requires proxying " + "(e.g. due to @Transactional), please use class-based proxying."; throw new IllegalStateException(getInvocationErrorMessage(msg, args)); } } private String getInvocationErrorMessage(String message, Object[] resolvedArgs) { StringBuilder sb = new StringBuilder(getDetailedErrorMessage(message)); sb.append("Resolved arguments: \n"); for (int i=0; i < resolvedArgs.length; i++) { sb.append("[").append(i).append("] "); if (resolvedArgs[i] == null) { sb.append("[null] \n"); } else { sb.append("[type=").append(resolvedArgs[i].getClass().getName()).append("] "); sb.append("[value=").append(resolvedArgs[i]).append("]\n"); } } return sb.toString(); } }
34.099138
96
0.719378