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
1315f86862f3bcc4f5e50b87bf5501d01c8773ad
847
package quickcache.storage; import java.io.IOException; import java.nio.file.Path; import java.util.Optional; import quickcache.commons.exceptions.DataConversionException; import quickcache.model.ReadOnlyQuickCache; import quickcache.model.ReadOnlyUserPrefs; import quickcache.model.UserPrefs; /** * API of the Storage component */ public interface Storage extends QuickCacheStorage, UserPrefsStorage { @Override Optional<UserPrefs> readUserPrefs() throws DataConversionException, IOException; @Override void saveUserPrefs(ReadOnlyUserPrefs userPrefs) throws IOException; @Override Path getQuickCacheFilePath(); @Override Optional<ReadOnlyQuickCache> readQuickCache() throws DataConversionException, IOException; @Override void saveQuickCache(ReadOnlyQuickCache quickCache) throws IOException; }
25.666667
94
0.799292
c53e8ea1f2f530fc3dcd2c625d90cedf17359fbf
1,849
/* * 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 com.fmi.oopjava.tokenizer.tests; import com.fmi.oopjava.client.Client; import com.fmi.oopjava.bankCard.BankCard; import com.fmi.oopjava.xmlSerializor.Storer; import org.junit.BeforeClass; import org.junit.Test; import static org.junit.Assert.*; /** * * @author Dimitar */ public class ClientsXMLstorerTest { private static Storer storer; private static Client client; private static BankCard card; private static BankCard card2; public ClientsXMLstorerTest() { } @BeforeClass public static void setUpClass() { storer = new Storer(); client = new Client("Dimitar", "mitko", new char[]{'1', '2', '3', '4', 'a', 'a'}, true, true); card = new BankCard("4563960122019991"); card2 = new BankCard("4563960122019992"); client.addCard(card.getCardNumber()); client.addCard(card2.getCardNumber()); card.addToken("1234243434269991"); card.addToken("1234243434269992"); card2.addToken("1234243434269991"); card2.addToken("1234243434269992"); } @Test public void testClientIO() { storer.writeObject(client, Client.class); Client c = (Client) storer.readObject("mitko", Client.class); assertEquals(client.getName(), c.getName()); assertEquals(client.getUsername(), c.getUsername()); } public void testReadingClient() { } @Test public void testCardIO() { storer.writeObject(card, BankCard.class); BankCard c = (BankCard) storer.readObject(card.getFileName(), BankCard.class); assertEquals(card.getCardNumber(), c.getCardNumber()); } }
28.015152
102
0.660357
d115224a8016c6dd9ae24c71a76fab406d0f5602
2,034
package ru.stqa.mfp.rest; import com.google.gson.Gson; import com.google.gson.JsonArray; import com.google.gson.JsonElement; import com.google.gson.JsonParser; import com.google.gson.reflect.TypeToken; import com.jayway.restassured.RestAssured; import org.testng.SkipException; import java.io.IOException; import java.util.Set; import static com.jayway.restassured.RestAssured.authentication; import static com.jayway.restassured.RestAssured.basic; public class TestBase { public void init() { authentication = basic("288f44776e7bec4bf44fdfeb1e646490", ""); } public Set<Issue> getIssues() throws IOException { String json = RestAssured.get("http://bugify.stqa.ru/api/issues.json").asString(); JsonElement parsed = new JsonParser().parse(json); JsonElement issues = parsed.getAsJsonObject().get("issues"); return new Gson().fromJson(issues, new TypeToken<Set<Issue>>(){}.getType()); } public int createIssue(Issue newIssue) throws IOException { String json = RestAssured.given() .parameter("subject", newIssue.getSubject()) .parameter("description", newIssue.getDescription()) .post("http://bugify.stqa.ru/api/issues.json").asString(); JsonElement parsed = new JsonParser().parse(json); return parsed.getAsJsonObject().get("issue_id").getAsInt(); } boolean isIssueOpen(int issueId) { String json = RestAssured.get("http://bugify.stqa.ru/api/issues/" + issueId + ".json").asString(); JsonElement parsed = new JsonParser().parse(json); JsonArray issues = parsed.getAsJsonObject().getAsJsonArray("issues"); String state_name = issues.get(0).getAsJsonObject().get("state_name").getAsString(); System.out.println(state_name); if ((state_name.equals("Resolved"))||(state_name.equals("Closed"))) { return false; } else return true; } public void skipIfNotFixed(int issueId) throws IOException { if (isIssueOpen(issueId)) { throw new SkipException("Ignored because of issue " + issueId); } } }
34.474576
102
0.714356
ce70a5b96bf54f4f4b624f5e068b8b92f77e4266
617
package org.javacore.pattern.filter; import java.util.ArrayList; import java.util.List; /** * className: CriteriaFemale * Package: org.javacore.pattern.filter * Description: * Author:znq * Date 19/1/8 下午2:58 */ public class CriteriaFemale implements Criteria { @Override public List<Person> meetCriteria(List<Person> persons) { List<Person> femalePersons = new ArrayList<Person>(); for (Person person : persons) { if (person.getGender().equalsIgnoreCase("FEMALE")) { femalePersons.add(person); } } return femalePersons; } }
23.730769
64
0.645057
10836eb4046862e4d7066523a6f4f83c30a26229
66
/** * @author gaoxue */ package com.github.gaoxue.gexcel.reader;
16.5
40
0.69697
7f91516f5676f97707ebd28c0a9bf7b2cb06637e
5,574
package com.meal.recs.model; import com.meal.recs.data.entity.IngredientEntity; import com.meal.recs.data.entity.RecipeEntity; import com.meal.recs.utility.Utilities; import lombok.Data; import lombok.NoArgsConstructor; import lombok.ToString; import org.apache.commons.lang3.ObjectUtils; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; /** * Created by gardiary on 25/01/19. */ @Data @ToString @NoArgsConstructor public class Recipe { private Long id; private String extId; private String name; private String image; private String recommendationMessage; private String description; private Time prepTime; private Time cookTime; private Integer servings; private Map<Long, Ingredient> ingredientsMap = new HashMap<>(); private List<Ingredient> ingredients = new ArrayList<>(); private List<String> directions; private List<Ingredient> neededIngredients = new ArrayList<>(); private Source source; private String sourceUrl; private String keyword; public Recipe(Long id, String name, String image) { this.id = id; this.name = name; this.image = image; } public Recipe(Long id, String name, String image, String description, Time prepTime, Time cookTime, Integer servings) { this.id = id; this.name = name; this.image = image; this.description = description; this.prepTime = prepTime; this.cookTime = cookTime; this.servings = servings; } public Recipe(RecipeEntity entity) { this.id = entity.getId(); this.name = entity.getName(); this.image = entity.getImage(); this.description = entity.getDescription(); this.prepTime = new Time(entity.getPrepTime(), entity.getPrepTimeUnit()); this.cookTime = new Time(entity.getCookTime(), entity.getCookTimeUnit()); this.servings = entity.getServings(); this.keyword = entity.getKeyword(); this.source = entity.getSource(); this.sourceUrl = entity.getSourceUrl(); this.extId = entity.getExtId(); if(ObjectUtils.isNotEmpty(entity.getDirections())) { this.directions = Utilities.jsonStringToObj(entity.getDirections(), List.class); } for(IngredientEntity ingredientEntity : entity.getIngredients()) { Ingredient ingredient = new Ingredient(ingredientEntity); this.ingredients.add(ingredient); addIngredient(ingredient); } } /*public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getPicture() { return picture; } public void setPicture(String picture) { this.picture = picture; } public String getRecommendationMessage() { return recommendationMessage; } public void setRecommendationMessage(String recommendationMessage) { this.recommendationMessage = recommendationMessage; } public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } public Time getPrepTime() { return prepTime; } public void setPrepTime(Time prepTime) { this.prepTime = prepTime; } public Time getCookTime() { return cookTime; } public void setCookTime(Time cookTime) { this.cookTime = cookTime; } public Integer getServings() { return servings; } public void setServings(Integer servings) { this.servings = servings; } public Map<Long, Ingredient> getIngredients() { return ingredients; } public void setIngredients(Map<Long, Ingredient> ingredients) { this.ingredients = ingredients; } public List<String> getDirections() { return directions; } public void setDirections(List<String> directions) { this.directions = directions; } public List<Ingredient> getNeededIngredients() { return neededIngredients; } public void setNeededIngredients(List<Ingredient> neededIngredients) { this.neededIngredients = neededIngredients; }*/ public void addIngredient(Ingredient ingredient) { if(ingredientsMap == null) { ingredientsMap = new HashMap<>(); } ingredientsMap.put(ingredient.getItem().getId(), ingredient); } public void addDirection(String direction) { if(directions == null) { directions = new ArrayList<>(); } directions.add(direction); } public String getNeededIngredientsAsHtml() { if(neededIngredients == null || neededIngredients.size() == 0) { return ""; } String html = ""; int i = 0; for(Ingredient ingredient : neededIngredients) { html += "<span>" + ingredient.getItem().getName() + "</span>"; i += 1; if(i < neededIngredients.size()) { html += "<br/>"; } } return html; } public void resetIngredientsState() { for(Map.Entry<Long, Ingredient> entry : ingredientsMap.entrySet()) { Ingredient ingredient = entry.getValue(); ingredient.setSelected(true); } } public void resetIngredientsState(boolean state) { for(Map.Entry<Long, Ingredient> entry : ingredientsMap.entrySet()) { Ingredient ingredient = entry.getValue(); ingredient.setSelected(state); } } /*@Override public String toString() { return "Recipe[" + "id=" + id + ", name='" + name + '\'' + ", picture='" + picture + '\'' + ", ingredients=" + ingredients + ", directions=" + directions + ']'; }*/ }
24.555066
121
0.672946
a942423cc5e0590bb1159465b5a1b6f5123ae000
290
// Copyright (C) 2019 Snild Dolkow // Licensed under the LICENSE. package com.example.cars; public abstract class Vehicle { protected final String make; protected final int numWheels; public Vehicle(String make, int numWheels) { this.make = make; this.numWheels = numWheels; } }
19.333333
45
0.737931
c02a622881419c53169ffface4d0c231a7c90be1
269
package org.sdoaj.jimgus.util.mesh; import org.sdoaj.jimgus.Jimgus; public class MeshFileHelper { private static final String prefix = "assets/" + Jimgus.MODID + "/objs/"; public static String getFilePath(String name) { return prefix + name; } }
22.416667
77
0.69145
590a73d26d511fc870757c5226e58def24d4c94a
965
package com.mpms.auth.shiro; import org.apache.shiro.SecurityUtils; import com.mpms.auth.shiro.UserRealm.ShiroUser; /** * 获得用户登录相关信息 * * @date 2015年11月3日 下午12:24:48 * @author luogang */ public class UserUtils { /** * 获取登录用户 * * @return * @date 2015年11月3日 下午3:40:45 * @author luogang */ public static ShiroUser getLoginUser() { ShiroUser shiroUser = null; try { shiroUser = (ShiroUser) SecurityUtils.getSubject().getPrincipal(); } catch (Exception e) { return null; } return shiroUser; } /** * 获取用户名 * * @return 用户名 * @date 2015年11月3日 下午3:40:27 * @author luogang */ public static String getLoginUserName() { return getLoginUser().getUserName(); } /** * 获取 登陆用户ID * * @return * @date 2016年1月20日 下午12:18:43 * @author libo */ public static Integer getLoginUserId() { ShiroUser loginedUser = getLoginUser(); if (null == loginedUser) { return null; } return loginedUser.getId(); } }
16.637931
69
0.651813
edf65ce1a12490ad91663cfdbf548f01da89c230
5,201
package eu.b24u.demo.rest.controllers; import com.jayway.restassured.RestAssured; import com.jayway.restassured.http.ContentType; import org.json.JSONObject; import org.junit.After; import org.junit.Before; import org.junit.Test; import org.springframework.http.HttpStatus; import java.util.LinkedHashMap; import java.util.Map; import static org.hamcrest.CoreMatchers.equalTo; import static org.junit.Assert.*; public class ProductControllerTest { String PORT = "8080"; String BASE_PATH = "http://localhost"; private Map<String, Object> params; @Before public void setUp() throws Exception { RestAssured.port = Integer.valueOf(PORT); RestAssured.baseURI = BASE_PATH; params = new LinkedHashMap<String, Object>(); } @After public void tearDown() throws Exception { } @Test public void setProductService() { } @Test public void getProduct() { //@formatter:off RestAssured. given().//log().all(). contentType(ContentType.JSON). accept(ContentType.JSON). params(params). header("Accept-Language", "pl"). //expect().log().all(). when(). get("/product/get/1"). then().statusCode(HttpStatus.OK.value()). log().all(true); //@formatter:on } @Test public void postProduct() { JSONObject requestParams = new JSONObject(); //requestParams.put("id", "200"); // Cast requestParams.put("version", "0"); requestParams.put("productId", "138192983"); requestParams.put("name", "eBook"); requestParams.put("price", "12.99"); //@formatter:off RestAssured. given().//log().all(). contentType(ContentType.JSON). accept(ContentType.JSON). params(params). header("Accept-Language", "pl"). body(requestParams.toString()). //expect().log().all(). when(). post("/product/post"). then().statusCode(HttpStatus.OK.value()). log().all(true); //@formatter:on } @Test public void putProduct() { JSONObject requestParams = new JSONObject(); //requestParams.put("id", "200"); // Cast requestParams.put("version", "0"); requestParams.put("productId", "138192983"); requestParams.put("name", "eBook"); requestParams.put("price", "12.99"); //@formatter:off RestAssured. given().//log().all(). contentType(ContentType.JSON). accept(ContentType.JSON). params(params). header("Accept-Language", "pl"). body(requestParams.toString()). //expect().log().all(). when(). put("/product/put/2"). then().statusCode(HttpStatus.OK.value()). log().all(true); //@formatter:on requestParams = new JSONObject(); //requestParams.put("id", "200"); // Cast requestParams.put("version", "0"); requestParams.put("productId", "138192983"); requestParams.put("name", "Czekolada Wedel 95% Gorzka"); requestParams.put("price", "12.99"); //@formatter:off RestAssured. given().//log().all(). contentType(ContentType.JSON). accept(ContentType.JSON). params(params). header("Accept-Language", "pl"). body(requestParams.toString()). //expect().log().all(). when(). put("/product/put/2"). then().statusCode(HttpStatus.OK.value()). log().all(true); //@formatter:on } @Test public void deleteProduct() { //@formatter:off RestAssured. given().//log().all(). contentType(ContentType.JSON). accept(ContentType.JSON). params(params). header("Accept-Language", "pl"). //expect().log().all(). when(). delete("/product/delete/1"); //then().statusCode(HttpStatus.OK.value()). //log().all(true); //@formatter:on //@formatter:off RestAssured. given().//log().all(). contentType(ContentType.JSON). accept(ContentType.JSON). params(params). header("Accept-Language", "pl"). //expect().log().all(). when(). get("/product/get/1"). then().statusCode(HttpStatus.OK.value()). log().all(true); //@formatter:on } @Test public void edit() { } @Test public void newProduct() { } @Test public void saveProduct() { } @Test public void delete() { } }
29.055866
64
0.501057
daee99c1b6ccafea4b42fa78fc8384de617baa44
6,345
/* * 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.syncope.client.console.pages; import java.io.Serializable; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.HashMap; import java.util.List; import java.util.Map; import org.apache.syncope.client.console.panels.Realm; import org.apache.syncope.client.console.rest.RealmRestClient; import org.apache.syncope.common.lib.to.RealmTO; import org.apache.wicket.MarkupContainer; import org.apache.wicket.ajax.AjaxRequestTarget; import org.apache.wicket.ajax.markup.html.AjaxLink; import org.apache.wicket.event.Broadcast; import org.apache.wicket.event.IEvent; import org.apache.wicket.markup.html.WebMarkupContainer; import org.apache.wicket.markup.html.basic.Label; import org.apache.wicket.markup.html.panel.Fragment; import org.apache.wicket.markup.repeater.RepeatingView; import org.apache.wicket.model.PropertyModel; import org.apache.wicket.request.mapper.parameter.PageParameters; import org.apache.wicket.spring.injection.annot.SpringBean; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class Realms extends BasePage { private static final long serialVersionUID = -1100228004207271270L; protected static final Logger LOG = LoggerFactory.getLogger(Realms.class); @SpringBean private RealmRestClient realmRestClient; private final WebMarkupContainer content; public Realms(final PageParameters parameters) { super(parameters); final List<RealmTO> realms = realmRestClient.list(); Collections.sort(realms, new RealmNameComparator()); add(getParentMap(realms), 0L, Realms.this); content = new WebMarkupContainer("content"); content.setOutputMarkupId(true); add(content); content.add(new Label("header", "Root realm")); content.add(new Label("body", "Root realm")); } private void add(final Map<Long, List<RealmTO>> parentMap, final Long key, final MarkupContainer container) { final RepeatingView listItems = new RepeatingView("list"); container.add(listItems); for (final RealmTO realm : parentMap.get(key)) { final Fragment fragment; final AjaxLink<Void> link = new AjaxLink<Void>("link") { private static final long serialVersionUID = 1L; @Override public void onClick(final AjaxRequestTarget target) { send(Realms.this, Broadcast.EXACT, new ControlSidebarClick<>(realm, target)); } }; link.add(new Label("name", new PropertyModel<String>(realm, "name"))); if (parentMap.containsKey(realm.getKey()) && !parentMap.get(realm.getKey()).isEmpty()) { fragment = new Fragment(String.valueOf(realm.getKey()), "withChildren", Realms.this); add(parentMap, realm.getKey(), fragment); } else { fragment = new Fragment(String.valueOf(realm.getKey()), "withoutChildren", Realms.this); } fragment.add(link); listItems.add(fragment); } } private Map<Long, List<RealmTO>> getParentMap(final List<RealmTO> realms) { final Map<Long, List<RealmTO>> res = new HashMap<>(); res.put(0L, new ArrayList<RealmTO>()); final Map<Long, List<RealmTO>> cache = new HashMap<>(); for (RealmTO realm : realms) { if (res.containsKey(realm.getParent())) { res.get(realm.getParent()).add(realm); final List<RealmTO> children = new ArrayList<>(); res.put(realm.getKey(), children); if (cache.containsKey(realm.getKey())) { children.addAll(cache.get(realm.getKey())); cache.remove(realm.getKey()); } } else if (cache.containsKey(realm.getParent())) { cache.get(realm.getParent()).add(realm); } else { final List<RealmTO> children = new ArrayList<>(); children.add(realm); cache.put(realm.getParent(), children); } } return res; } private static class RealmNameComparator implements Comparator<RealmTO>, Serializable { private static final long serialVersionUID = 7085057398406518811L; @Override public int compare(final RealmTO r1, final RealmTO r2) { return r1.getName().compareTo(r2.getName()); } } @Override public void onEvent(final IEvent<?> event) { super.onEvent(event); if (event.getPayload() instanceof ControlSidebarClick) { @SuppressWarnings("unchecked") final ControlSidebarClick<RealmTO> controlSidebarClick = ControlSidebarClick.class.cast(event.getPayload()); content.addOrReplace(new Label("header", controlSidebarClick.getObj().getName())); content.addOrReplace(new Realm("body", controlSidebarClick.getObj())); controlSidebarClick.getTarget().add(content); } } private static class ControlSidebarClick<T> { private final AjaxRequestTarget target; private final T obj; public ControlSidebarClick( final T obj, final AjaxRequestTarget target) { this.obj = obj; this.target = target; } public T getObj() { return obj; } public AjaxRequestTarget getTarget() { return target; } } }
35.646067
120
0.655477
2cde310be7e2bde4225c17cd67364a6b04196328
4,603
package seedu.address.itinerary.logic.parser; import static org.junit.jupiter.api.Assertions.assertEquals; import static seedu.address.testutil.Assert.assertThrows; import org.junit.jupiter.api.Test; import seedu.address.itinerary.logic.commands.SearchCommand; import seedu.address.logic.commands.Command; import seedu.address.logic.parser.Parser; import seedu.address.logic.parser.exceptions.ParseException; class SearchCommandParserTest { public static final String TITLE_DESC_SEARCH = " title/title"; public static final String DATE_DESC_SEARCH = " date/13071997"; public static final String TIME_DESC_SEARCH = " time/2000"; public static final String LOCATION_DESC_SEARCH = " l/location"; private SearchCommandParser parser = new SearchCommandParser(); private String outcome = "Processing...\n" + "Done!\n" + "Here are the events that matches the details. ( ͡° ͜ʖ ͡°)"; @Test public void parse_validArgs_returnsSearchCommand() { assertEquals(SearchCommand.MESSAGE_SUCCESS, outcome); } @Test public void parse_missingParts_failure() { // no field specified assertParseFailure(parser, "title/", SearchCommand.MESSAGE_USAGE); // no field specified assertParseFailure(parser, "date/", SearchCommand.MESSAGE_USAGE); // no field specified assertParseFailure(parser, "time/", SearchCommand.MESSAGE_USAGE); // no field specified assertParseFailure(parser, "location/", SearchCommand.MESSAGE_USAGE); // no wrong prefix specified assertParseFailure(parser, "by/", SearchCommand.MESSAGE_USAGE); // no details given assertParseFailure(parser, "", SearchCommand.MESSAGE_USAGE); // random string given assertParseFailure(parser, "hello world!", SearchCommand.MESSAGE_USAGE); // index given assertParseFailure(parser, "420", SearchCommand.MESSAGE_USAGE); } @Test public void parse_invalidCheck_condition() { assertThrows(ParseException.class, () -> parser.parse(SearchCommand.COMMAND_WORD)); assertThrows(ParseException.class, () -> parser.parse(SearchCommand.COMMAND_WORD + " by/none")); assertThrows(ParseException.class, () -> parser.parse(SearchCommand.COMMAND_WORD + " y/priority")); assertThrows(ParseException.class, () -> parser.parse(SearchCommand.COMMAND_WORD + " y/")); assertThrows(ParseException.class, () -> parser.parse(SearchCommand.COMMAND_WORD + " 1")); assertThrows(ParseException.class, () -> parser.parse(SearchCommand.COMMAND_WORD + " date/2450")); assertThrows(ParseException.class, () -> parser.parse(SearchCommand.COMMAND_WORD + " date/08/09/2019")); assertThrows(ParseException.class, () -> parser.parse(SearchCommand.COMMAND_WORD + " date/29022019")); assertThrows(ParseException.class, () -> parser.parse(SearchCommand.COMMAND_WORD + " time/2450")); assertThrows(ParseException.class, () -> parser.parse(SearchCommand.COMMAND_WORD + " time/-1000")); assertThrows(ParseException.class, () -> parser.parse(SearchCommand.COMMAND_WORD + " l/000000000000000000000")); } @Test public void parse_allFieldsSpecified_success() throws ParseException { // Single field checks parser.parse(TITLE_DESC_SEARCH); parser.parse(DATE_DESC_SEARCH); parser.parse(TIME_DESC_SEARCH); parser.parse(LOCATION_DESC_SEARCH); // This means that regardless of the words in the front, the prefix takes preecedence parser.parse(SearchCommand.COMMAND_WORD + " words before" + LOCATION_DESC_SEARCH + TIME_DESC_SEARCH); parser.parse(SearchCommand.COMMAND_WORD + " words before" + TITLE_DESC_SEARCH + TIME_DESC_SEARCH); parser.parse(SearchCommand.COMMAND_WORD + " words before" + TITLE_DESC_SEARCH + LOCATION_DESC_SEARCH); } /** * Asserts that the parsing of {@code userInput} by {@code parser} is unsuccessful and the error message * equals to {@code expectedMessage}. */ public static void assertParseFailure(Parser<? extends Command> parser, String userInput, String expectedMessage) { try { parser.parse(userInput); throw new AssertionError("The expected ParseException was not thrown."); } catch (ParseException pe) { assertEquals(expectedMessage, pe.getMessage()); } } }
37.120968
119
0.679122
dc4a948005f9ef04ac0b1ef1941433b67e4ba064
18,780
// Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.jetbrains.python.sdk.skeletons; import com.google.common.collect.ImmutableMap; import com.google.gson.*; import com.google.gson.annotations.SerializedName; import com.intellij.execution.ExecutionException; import com.intellij.execution.configurations.GeneralCommandLine; import com.intellij.execution.process.BaseProcessHandler; import com.intellij.execution.process.CapturingProcessHandler; import com.intellij.execution.process.ProcessOutput; import com.intellij.openapi.diagnostic.Logger; import com.intellij.openapi.progress.ProgressIndicator; import com.intellij.openapi.projectRoots.Sdk; import com.intellij.openapi.util.text.StringUtil; import com.intellij.openapi.vfs.LocalFileSystem; import com.intellij.openapi.vfs.VirtualFile; import com.intellij.util.ArrayUtil; import com.intellij.util.Time; import com.intellij.util.containers.ContainerUtil; import com.jetbrains.python.PythonHelpersLocator; import com.jetbrains.python.sdk.InvalidSdkException; import com.jetbrains.python.sdk.PySdkUtil; import com.jetbrains.python.sdk.PythonEnvUtil; import com.jetbrains.python.sdk.flavors.PythonSdkFlavor; import org.jetbrains.annotations.NonNls; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.io.*; import java.nio.charset.StandardCharsets; import java.util.*; /** * This class serves two purposes. First, it's a wrapper around "generator3" helper script * that is used to generate stub ".py" definitions for binary modules. The wrapper helps to * launch it using multitude of existing options (see {@link #commandBuilder()}), communicate * with a running generator instance and interpret its results. Second, it's an extension * necessary to customize generation steps for various interpreter flavors supported in PyCharm, * first of all, remote ones (see {@link com.jetbrains.python.remote.PyRemoteSkeletonGeneratorFactory} EP). * <p> * Conceptually there are two distinct modes for launching the generator: * <ul> * <li>In the main mode it actually produces stubs for binaries either explicitly specified or * automatically discovered in {@code sys.path}. As generation goes it communicates with * the IDE in JSON chunks containing progress indication, log messages and intermediate results, e.g. * <p>{@code {"type": "progress", "text": "_hashlib", "fraction": 0.2, "minor": true}}</p> * or * <p>{"type": "generation_result", "module_origin": "/usr/lib/python2.7/lib-dynload/_hashlib.so", "module_name": "_hashlib", "generation_status": "GENERATED"}</p> * <p> * To fully support this mode with real-time progress indication all inheritors must support * reading process' stdout/stderr interactively line by line by implementing * {@link #runProcessWithLineOutputListener(String, List, Map, String, int, LineWiseProcessOutputListener)}. * The provided {@link LineWiseProcessOutputListener} will handle all the service lines written to stdout. * <p> * Example of generator invocation in the main mode: * <pre> * {@code * new PySkeletonGenerator(skeletonsPath, sdk, workingDir) * .commandBuilder() * // customize command line options and environment * .runGeneration(progressIndicator) * } * </pre> * </li> * <li> * The second mode is intended for all the other commands supported by the script but not directly related to generation, e.g. * listing source files found in {@code sys.path} and zipping them in an archive (which is used by some remote interpreters). * These commands normally don't use any special service commands and don't have intermediate results, therefore one can * simply run them as: * <pre> * {@code * new PySkeletonGenerator(skeletonsPath, sdk, workingDir) * .commandBuilder() * // customize command line options and environment * .runProcess() * } * and manually interpret process' output and exit code as needed. * </pre> * </li> * * @see Builder */ public class PySkeletonGenerator { private static class Run { static final Logger LOG = Logger.getInstance(Run.class); } protected static final Logger LOG = Logger.getInstance(PySkeletonGenerator.class); protected static final String GENERATOR3 = "generator3/__main__.py"; @NonNls public static final String STATE_MARKER_FILE = ".state.json"; @NonNls public static final String BLACKLIST_FILE_NAME = ".blacklist"; private static final Gson ourGson = new GsonBuilder().create(); protected final Sdk mySdk; @Nullable private final String myCurrentFolder; private final String mySkeletonsPath; /** * @param skeletonPath path where skeletons should be generated * @param pySdk SDK * @param currentFolder current folder (some flavors may search for binary files there) or null if unknown */ // TODO get rid of skeletonPath and currentFolder parameters and configure generator explicitly with builder public PySkeletonGenerator(String skeletonPath, @NotNull final Sdk pySdk, @Nullable final String currentFolder) { mySkeletonsPath = skeletonPath; mySdk = pySdk; myCurrentFolder = currentFolder; } @NotNull public final Builder commandBuilder() { final Builder builder = new Builder(); if (myCurrentFolder != null) { builder.workingDir(myCurrentFolder); } return builder; } /** * Builder object serving as a facade for the command-line interface of the generator, * allowing to additionally customize how it's going to be launched and performing the * default initialization before the run. */ public final class Builder { private final List<String> myExtraSysPath = new ArrayList<>(); private final List<String> myAssemblyRefs = new ArrayList<>(); private final List<String> myExtraArgs = new ArrayList<>(); private String myWorkingDir; private String myTargetModuleName; private String myTargetModulePath; private boolean myPrebuilt = false; private int myTimeout; private String myStdin; private Builder() { } @NotNull public Builder extraSysPath(@NotNull List<String> roots) { myExtraSysPath.addAll(roots); return this; } @NotNull public Builder assemblyRefs(@NotNull List<String> assemblyRefs) { myAssemblyRefs.addAll(assemblyRefs); return this; } @NotNull public Builder extraArgs(@NotNull List<String> args) { myExtraArgs.addAll(args); return this; } @NotNull public Builder extraArgs(String @NotNull ... args) { return extraArgs(Arrays.asList(args)); } @NotNull public Builder workingDir(@NotNull String path) { myWorkingDir = path; return this; } @NotNull public Builder inPrebuildingMode() { myPrebuilt = true; return this; } @NotNull public Builder targetModule(@NotNull String name, @Nullable String path) { myTargetModuleName = name; myTargetModulePath = path; return this; } @NotNull public Builder timeout(int timeout) { myTimeout = timeout; return this; } @NotNull public Builder stdin(@NotNull String content) { myStdin = content; return this; } @Nullable public String getStdin() { return myStdin; } @NotNull public List<String> getCommandLine() { final List<String> commandLine = new ArrayList<>(); commandLine.add(mySdk.getHomePath()); commandLine.add(PythonHelpersLocator.getHelperPath(GENERATOR3)); commandLine.add("-d"); commandLine.add(mySkeletonsPath); if (!ContainerUtil.isEmpty(myAssemblyRefs)) { commandLine.add("-c"); commandLine.add(StringUtil.join(myAssemblyRefs, ";")); } if (!ContainerUtil.isEmpty(myExtraSysPath)) { commandLine.add("-s"); commandLine.add(StringUtil.join(myExtraSysPath, File.pathSeparator)); } commandLine.addAll(myExtraArgs); if (StringUtil.isNotEmpty(myTargetModuleName)) { commandLine.add(myTargetModuleName); if (StringUtil.isNotEmpty(myTargetModulePath)) { commandLine.add(myTargetModulePath); } } return commandLine; } @NotNull public Map<String, String> getEnvironment() { Map<String, String> env = new HashMap<>(); final PythonSdkFlavor flavor = PythonSdkFlavor.getFlavor(mySdk); final String flavorPathParam = flavor != null ? flavor.envPathParam() : null; // TODO Investigate whether it's possible to pass this directory as an ordinary "extraSysPath" entry if (myWorkingDir != null && flavorPathParam != null) { env = PySdkUtil.mergeEnvVariables(env, ImmutableMap.of(flavorPathParam, myWorkingDir)); } env = PySdkUtil.mergeEnvVariables(env, PySdkUtil.activateVirtualEnv(mySdk)); PythonEnvUtil.setPythonDontWriteBytecode(env); if (myPrebuilt) { env.put("IS_PREGENERATED_SKELETONS", "1"); } return env; } @NotNull public String getWorkingDir() throws InvalidSdkException { if (myWorkingDir != null) { return myWorkingDir; } final String binaryPath = mySdk.getHomePath(); if (binaryPath == null) throw new InvalidSdkException("Broken home path for " + mySdk.getName()); return new File(binaryPath).getParent(); } public int getTimeout(int defaultTimeout) { return myTimeout > 0 ? myTimeout : defaultTimeout; } /** * @param ensureSuccess throw {@link InvalidSdkException} containing additional diagnostic on process non-zero exit code. * You might want to disable it for commands where non-zero exit code is possible for situations other * than misconfigured interpreter or execution error in order to inspect the output manually. */ @NotNull public ProcessOutput runProcess(boolean ensureSuccess) throws InvalidSdkException { return PySkeletonGenerator.this.runProcess(this, ensureSuccess); } @NotNull public List<GenerationResult> runGeneration(@Nullable ProgressIndicator indicator) throws InvalidSdkException, ExecutionException { return PySkeletonGenerator.this.runGeneration(this, indicator); } } @NotNull protected List<GenerationResult> runGeneration(@NotNull Builder builder, @Nullable ProgressIndicator indicator) throws InvalidSdkException, ExecutionException { final List<GenerationResult> results = new ArrayList<>(); final LineWiseProcessOutputListener listener = new LineWiseProcessOutputListener() { @Override public void onStdoutLine(@NotNull String line) { if (indicator != null) { indicator.checkCanceled(); } final String trimmed = line.trim(); if (trimmed.startsWith("{")) { final JsonObject controlMessage; try { controlMessage = ourGson.fromJson(trimmed, JsonObject.class); } catch (JsonSyntaxException e) { LOG.warn("Malformed control message: " + line); return; } final String msgType = controlMessage.get("type").getAsString(); if (msgType.equals("progress") && indicator != null) { final JsonElement text = controlMessage.get("text"); if (text != null) { if (controlMessage.get("minor").getAsBoolean()) { indicator.setText2(text.getAsString()); } else { indicator.setText(text.getAsString()); } } final JsonElement fraction = controlMessage.get("fraction"); if (fraction != null) { indicator.setIndeterminate(false); indicator.setFraction(fraction.getAsDouble()); } } else if (msgType.equals("log")) { final String level = controlMessage.get("level").getAsString(); final String message = controlMessage.get("message").getAsString(); if (level.equals("info")) { Run.LOG.info(message); } else if (level.equals("debug")) { Run.LOG.debug(message); } else if (level.equals("trace")) { Run.LOG.trace(message); } } else if (msgType.equals("generation_result")) { results.add(ourGson.fromJson(trimmed, GenerationResult.class)); } } } @Override public void onStderrLine(@NotNull String line) { Run.LOG.info(StringUtil.trimTrailing(line)); } }; final ProcessOutput output = runProcessWithLineOutputListener(builder.getWorkingDir(), builder.getCommandLine(), builder.getEnvironment(), builder.myStdin, builder.getTimeout(Time.MINUTE * 20), listener); if (output.getExitCode() != 0) { throw new InvalidSdkException(formatGeneratorFailureMessage(output)); } return results; } @NotNull protected ProcessOutput runProcess(@NotNull Builder builder, boolean ensureSuccess) throws InvalidSdkException { final ProcessOutput output = getProcessOutput(builder.getWorkingDir(), ArrayUtil.toStringArray(builder.getCommandLine()), builder.getStdin(), builder.getEnvironment(), builder.getTimeout(Time.MINUTE * 10)); if (ensureSuccess && output.getExitCode() != 0) { throw new InvalidSdkException(formatGeneratorFailureMessage(output)); } return output; } public void finishSkeletonsGeneration() { } public boolean exists(@NotNull final String name) { return new File(name).exists(); } @NotNull protected ProcessOutput runProcessWithLineOutputListener(@NotNull String homePath, @NotNull List<String> cmd, @NotNull Map<String, String> env, @Nullable String stdin, int timeout, @NotNull LineWiseProcessOutputListener listener) throws ExecutionException, InvalidSdkException { final GeneralCommandLine commandLine = new GeneralCommandLine(cmd) .withWorkDirectory(homePath) .withEnvironment(env); final CapturingProcessHandler handler = new CapturingProcessHandler(commandLine); if (stdin != null) { sendLineToProcessInput(handler, stdin); } handler.addProcessListener(new LineWiseProcessOutputListener.Adapter(listener)); return handler.runProcess(timeout); } public String getSkeletonsPath() { return mySkeletonsPath; } public void prepare() { } protected ProcessOutput getProcessOutput(String homePath, String @NotNull [] commandLine, @Nullable String stdin, Map<String, String> extraEnv, int timeout) throws InvalidSdkException { final byte[] bytes = stdin != null ? stdin.getBytes(StandardCharsets.UTF_8) : null; return PySdkUtil.getProcessOutput(homePath, commandLine, extraEnv, timeout, bytes, true); } @NotNull private String formatGeneratorFailureMessage(@NotNull ProcessOutput process) { final StringBuilder sb = new StringBuilder("failed to run ").append(GENERATOR3).append(" for ").append(mySdk.getHomePath()); if (process.isTimeout()) { sb.append(": timed out."); } else { sb.append(", exit code ") .append(process.getExitCode()) .append(", stderr: \n-----\n"); for (String line : process.getStderrLines()) { sb.append(line).append("\n"); } sb.append("-----"); } return sb.toString(); } public boolean deleteOrLog(@NotNull File item) { boolean deleted = item.delete(); if (!deleted) LOG.warn("Failed to delete skeleton file " + item.getAbsolutePath()); return deleted; } public void refreshGeneratedSkeletons() { VirtualFile skeletonsVFile = LocalFileSystem.getInstance().refreshAndFindFileByPath(getSkeletonsPath()); assert skeletonsVFile != null; skeletonsVFile.refresh(false, true); } public enum GenerationStatus { UP_TO_DATE, GENERATED, COPIED, FAILED, } @SuppressWarnings("unused") public static class GenerationResult { @SerializedName("module_name") private String myModuleName; @SerializedName("module_origin") private String myModuleOrigin; @SerializedName("generation_status") private GenerationStatus myGenerationStatus; @NotNull public String getModuleName() { return myModuleName; } @NotNull public String getModuleOrigin() { return myModuleOrigin; } @NotNull public GenerationStatus getGenerationStatus() { return myGenerationStatus; } public boolean isBuiltin() { return myModuleOrigin.equals("(built-in)"); } } protected static void sendLineToProcessInput(@NotNull BaseProcessHandler<?> handler, @NotNull String line) throws ExecutionException { final OutputStream input = handler.getProcessInput(); if (input != null) { try { sendLineToStream(input, line); } catch (IOException e) { throw new ExecutionException(e); } } else { LOG.warn("Process " + handler.getCommandLine() + " can't accept any input"); } } protected static void sendLineToStream(@NotNull OutputStream input, @NotNull String line) throws IOException { // Using platform-specific notion of a line separator (PrintStream, PrintWriter, BufferedWriter#newLine()) is // unreliable in case of remote interpreters where target and host OS might differ. // Closing the underlying input stream should be handled by its owner. @SuppressWarnings("IOResourceOpenedButNotSafelyClosed") final BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(input, StandardCharsets.UTF_8)); writer.write(line); writer.write('\n'); writer.flush(); } }
37.939394
163
0.659744
ae9c6bb80faffc7cc4201f3897df7780b73cdc5a
1,604
package com.vaga.java.leetcode.string; import org.testng.annotations.DataProvider; import org.testng.annotations.Test; import static org.assertj.core.api.Assertions.assertThat; /** * @author vaga * @version 2020/3/10 4:35 下午 * @description * 125. 验证回文串 */ public class PalindromeTest { @DataProvider(name = "data") public static Object[][] dataset() { return new Object[][]{ {"A man, a plan, a canal: Panama", true}, {"OP", false}, {"race a car", false}, {"", true}, }; } @Test(dataProvider = "data") public void palindrome(String s, boolean expected) { assertThat(isPalindrome(s)).isEqualTo(expected); } public boolean isPalindrome(String s) { if (null == s || s.equals("")) return true; int left = 0; int right = s.length() - 1; while ( left < right) { if (!isValid(s.charAt(left))) { left++; continue; } if (!isValid(s.charAt(right))) { right--; continue; } if (Character.toLowerCase(s.charAt(left)) == Character.toLowerCase(s.charAt(right))) { left++; right--; } else { return false; } } return true; } private boolean isValid(char c) { if ((c >= 0 && c <= 9) || (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z')) { return true; } return false; } }
25.460317
98
0.469451
0b8d04ddde91a6988de034502124d20b8c161500
752
/* *############################################################################# *#------------------------------ ServerInterface ----------------------------------- *# *# @author Joshua Landron *# @date 01Jun2019 *# @version 9Jun2019 *# *# Built as part of CSS434 with Dr. Munehiro Fukuda, Spring 2019 *# *############################################################################# */ import java.rmi.*; public interface ServerInterface extends Remote { public FileContents download(String client, String filename, String mode) throws RemoteException; public boolean upload(String client, String filename, FileContents contents) throws RemoteException; public void shutDownServer() throws RemoteException; }
32.695652
104
0.506649
3fd102e5c583140f5d068c13389e6a6391bbb0f6
1,919
package org.wso2.carbon.bpmn.rest.api.repository; import com.fasterxml.jackson.databind.annotation.JsonSerialize; import org.activiti.engine.repository.Deployment; import org.activiti.rest.common.util.DateToStringSerializer; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlRootElement; import java.util.Date; @XmlRootElement(name = "deployment") @XmlAccessorType(XmlAccessType.FIELD) public class DeploymentResponse { String id; String name; @JsonSerialize(using = DateToStringSerializer.class, as=Date.class) Date deploymentTime; String category; String url; String tenantId; public DeploymentResponse(){} public DeploymentResponse(Deployment deployment, String url){ setId(deployment.getId()); setName(deployment.getName()); setDeploymentTime(deployment.getDeploymentTime()); setCategory(deployment.getCategory()); setTenantId(deployment.getTenantId()); setUrl(url); } public String getId() { return id; } public void setId(String id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public Date getDeploymentTime() { return deploymentTime; } public void setDeploymentTime(Date deploymentTime) { this.deploymentTime = deploymentTime; } public String getCategory() { return category; } public void setCategory(String category) { this.category = category; } public String getUrl() { return url; } public void setUrl(String url) { this.url = url; } public String getTenantId() { return tenantId; } public void setTenantId(String tenantId) { this.tenantId = tenantId; } }
23.120482
71
0.671183
0097058b8a2f3e9efb83a4377b5a5f199d5f59cd
76
package org.zstack.sdk.sns; public class RemoveSNSSmsReceiverResult { }
9.5
41
0.776316
2fc4018889d32500962966b7b9f657502ca69da0
11,978
/* * 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 ar.nex.jpa; import java.io.Serializable; import javax.persistence.Query; import javax.persistence.EntityNotFoundException; import javax.persistence.criteria.CriteriaQuery; import javax.persistence.criteria.Root; import ar.nex.entity.empleado.Persona; import java.util.ArrayList; import java.util.List; import ar.nex.entity.empresa.Empresa; import ar.nex.entity.empleado.Empleado; import ar.nex.entity.ubicacion.Contacto; import ar.nex.jpa.exceptions.NonexistentEntityException; import javax.persistence.EntityManager; import javax.persistence.EntityManagerFactory; /** * * @author Renzo */ public class ContactoJpaController implements Serializable { public ContactoJpaController(EntityManagerFactory emf) { this.emf = emf; } private EntityManagerFactory emf = null; public EntityManager getEntityManager() { return emf.createEntityManager(); } public void create(Contacto contacto) { if (contacto.getPersonaList() == null) { contacto.setPersonaList(new ArrayList<Persona>()); } if (contacto.getEmpresaList() == null) { contacto.setEmpresaList(new ArrayList<Empresa>()); } if (contacto.getEmpleadoList() == null) { contacto.setEmpleadoList(new ArrayList<Empleado>()); } EntityManager em = null; try { em = getEntityManager(); em.getTransaction().begin(); List<Persona> attachedPersonaList = new ArrayList<Persona>(); for (Persona personaListPersonaToAttach : contacto.getPersonaList()) { personaListPersonaToAttach = em.getReference(personaListPersonaToAttach.getClass(), personaListPersonaToAttach.getIdPersona()); attachedPersonaList.add(personaListPersonaToAttach); } contacto.setPersonaList(attachedPersonaList); List<Empresa> attachedEmpresaList = new ArrayList<Empresa>(); for (Empresa empresaListEmpresaToAttach : contacto.getEmpresaList()) { empresaListEmpresaToAttach = em.getReference(empresaListEmpresaToAttach.getClass(), empresaListEmpresaToAttach.getIdEmpresa()); attachedEmpresaList.add(empresaListEmpresaToAttach); } contacto.setEmpresaList(attachedEmpresaList); List<Empleado> attachedEmpleadoList = new ArrayList<Empleado>(); for (Empleado empleadoListEmpleadoToAttach : contacto.getEmpleadoList()) { empleadoListEmpleadoToAttach = em.getReference(empleadoListEmpleadoToAttach.getClass(), empleadoListEmpleadoToAttach.getIdPersona()); attachedEmpleadoList.add(empleadoListEmpleadoToAttach); } contacto.setEmpleadoList(attachedEmpleadoList); em.persist(contacto); for (Persona personaListPersona : contacto.getPersonaList()) { personaListPersona.getContactoList().add(contacto); personaListPersona = em.merge(personaListPersona); } for (Empresa empresaListEmpresa : contacto.getEmpresaList()) { empresaListEmpresa.getContactoList().add(contacto); empresaListEmpresa = em.merge(empresaListEmpresa); } for (Empleado empleadoListEmpleado : contacto.getEmpleadoList()) { empleadoListEmpleado.getContactoList().add(contacto); empleadoListEmpleado = em.merge(empleadoListEmpleado); } em.getTransaction().commit(); } finally { if (em != null) { em.close(); } } } public void edit(Contacto contacto) throws NonexistentEntityException, Exception { EntityManager em = null; try { em = getEntityManager(); em.getTransaction().begin(); Contacto persistentContacto = em.find(Contacto.class, contacto.getIdContacto()); List<Persona> personaListOld = persistentContacto.getPersonaList(); List<Persona> personaListNew = contacto.getPersonaList(); List<Empresa> empresaListOld = persistentContacto.getEmpresaList(); List<Empresa> empresaListNew = contacto.getEmpresaList(); List<Empleado> empleadoListOld = persistentContacto.getEmpleadoList(); List<Empleado> empleadoListNew = contacto.getEmpleadoList(); List<Persona> attachedPersonaListNew = new ArrayList<Persona>(); for (Persona personaListNewPersonaToAttach : personaListNew) { personaListNewPersonaToAttach = em.getReference(personaListNewPersonaToAttach.getClass(), personaListNewPersonaToAttach.getIdPersona()); attachedPersonaListNew.add(personaListNewPersonaToAttach); } personaListNew = attachedPersonaListNew; contacto.setPersonaList(personaListNew); List<Empresa> attachedEmpresaListNew = new ArrayList<Empresa>(); for (Empresa empresaListNewEmpresaToAttach : empresaListNew) { empresaListNewEmpresaToAttach = em.getReference(empresaListNewEmpresaToAttach.getClass(), empresaListNewEmpresaToAttach.getIdEmpresa()); attachedEmpresaListNew.add(empresaListNewEmpresaToAttach); } empresaListNew = attachedEmpresaListNew; contacto.setEmpresaList(empresaListNew); List<Empleado> attachedEmpleadoListNew = new ArrayList<Empleado>(); for (Empleado empleadoListNewEmpleadoToAttach : empleadoListNew) { empleadoListNewEmpleadoToAttach = em.getReference(empleadoListNewEmpleadoToAttach.getClass(), empleadoListNewEmpleadoToAttach.getIdPersona()); attachedEmpleadoListNew.add(empleadoListNewEmpleadoToAttach); } empleadoListNew = attachedEmpleadoListNew; contacto.setEmpleadoList(empleadoListNew); contacto = em.merge(contacto); for (Persona personaListOldPersona : personaListOld) { if (!personaListNew.contains(personaListOldPersona)) { personaListOldPersona.getContactoList().remove(contacto); personaListOldPersona = em.merge(personaListOldPersona); } } for (Persona personaListNewPersona : personaListNew) { if (!personaListOld.contains(personaListNewPersona)) { personaListNewPersona.getContactoList().add(contacto); personaListNewPersona = em.merge(personaListNewPersona); } } for (Empresa empresaListOldEmpresa : empresaListOld) { if (!empresaListNew.contains(empresaListOldEmpresa)) { empresaListOldEmpresa.getContactoList().remove(contacto); empresaListOldEmpresa = em.merge(empresaListOldEmpresa); } } for (Empresa empresaListNewEmpresa : empresaListNew) { if (!empresaListOld.contains(empresaListNewEmpresa)) { empresaListNewEmpresa.getContactoList().add(contacto); empresaListNewEmpresa = em.merge(empresaListNewEmpresa); } } for (Empleado empleadoListOldEmpleado : empleadoListOld) { if (!empleadoListNew.contains(empleadoListOldEmpleado)) { empleadoListOldEmpleado.getContactoList().remove(contacto); empleadoListOldEmpleado = em.merge(empleadoListOldEmpleado); } } for (Empleado empleadoListNewEmpleado : empleadoListNew) { if (!empleadoListOld.contains(empleadoListNewEmpleado)) { empleadoListNewEmpleado.getContactoList().add(contacto); empleadoListNewEmpleado = em.merge(empleadoListNewEmpleado); } } em.getTransaction().commit(); } catch (Exception ex) { String msg = ex.getLocalizedMessage(); if (msg == null || msg.length() == 0) { Long id = contacto.getIdContacto(); if (findContacto(id) == null) { throw new NonexistentEntityException("The contacto with id " + id + " no longer exists."); } } throw ex; } finally { if (em != null) { em.close(); } } } public void destroy(Long id) throws NonexistentEntityException { EntityManager em = null; try { em = getEntityManager(); em.getTransaction().begin(); Contacto contacto; try { contacto = em.getReference(Contacto.class, id); contacto.getIdContacto(); } catch (EntityNotFoundException enfe) { throw new NonexistentEntityException("The contacto with id " + id + " no longer exists.", enfe); } List<Persona> personaList = contacto.getPersonaList(); for (Persona personaListPersona : personaList) { personaListPersona.getContactoList().remove(contacto); personaListPersona = em.merge(personaListPersona); } List<Empresa> empresaList = contacto.getEmpresaList(); for (Empresa empresaListEmpresa : empresaList) { empresaListEmpresa.getContactoList().remove(contacto); empresaListEmpresa = em.merge(empresaListEmpresa); } List<Empleado> empleadoList = contacto.getEmpleadoList(); for (Empleado empleadoListEmpleado : empleadoList) { empleadoListEmpleado.getContactoList().remove(contacto); empleadoListEmpleado = em.merge(empleadoListEmpleado); } em.remove(contacto); em.getTransaction().commit(); } finally { if (em != null) { em.close(); } } } public List<Contacto> findContactoEntities() { return findContactoEntities(true, -1, -1); } public List<Contacto> findContactoEntities(int maxResults, int firstResult) { return findContactoEntities(false, maxResults, firstResult); } private List<Contacto> findContactoEntities(boolean all, int maxResults, int firstResult) { EntityManager em = getEntityManager(); try { CriteriaQuery cq = em.getCriteriaBuilder().createQuery(); cq.select(cq.from(Contacto.class)); Query q = em.createQuery(cq); if (!all) { q.setMaxResults(maxResults); q.setFirstResult(firstResult); } return q.getResultList(); } finally { em.close(); } } public Contacto findContacto(Long id) { EntityManager em = getEntityManager(); try { return em.find(Contacto.class, id); } finally { em.close(); } } public int getContactoCount() { EntityManager em = getEntityManager(); try { CriteriaQuery cq = em.getCriteriaBuilder().createQuery(); Root<Contacto> rt = cq.from(Contacto.class); cq.select(em.getCriteriaBuilder().count(rt)); Query q = em.createQuery(cq); return ((Long) q.getSingleResult()).intValue(); } finally { em.close(); } } }
45.89272
159
0.608198
4cd73d30ab5161db7f1d84abe2d5282c1016deee
1,953
package aitoa.utils.logs; import aitoa.utils.Configuration; import aitoa.utils.ConsoleIO; /** The entry point for post-processing the data */ public final class PostProcessor { /** * The main routine * * @param args * the command line arguments */ public static void main(final String[] args) { final Class<?>[] classes = { // EndResults.class, // EndResultStatistics.class, // ErtEcdf.class, // IOHProfiler.class,// }; final String[] choices = new String[classes.length]; for (int i = classes.length; (--i) >= 0;) { choices[i] = classes[i].getSimpleName(); } final String choice = "choice";//$NON-NLS-1$ ConsoleIO.stdout(s -> { s.println("Welcome to the AITOA Result Post-Processor"); //$NON-NLS-1$ for (final String c : choices) { s.print(" -choice=");//$NON-NLS-1$ s.print(c); s.print(": execute the ");//$NON-NLS-1$ s.print(c); s.println(" utility.");//$NON-NLS-1$ } }); Configuration.putCommandLine(args); final String selected = Configuration.getString(choice); if (selected != null) { Class<?> taken = null; for (int i = choices.length; (--i) >= 0;) { if (choices[i].equalsIgnoreCase(selected)) { taken = classes[i]; break; } } if (taken == null) { ConsoleIO.stdout( '\'' + selected + "' is not a valid choice.");//$NON-NLS-1$ return; } try { taken.getMethod("main", String[].class)//$NON-NLS-1$ .invoke(null, ((Object) (args))); } catch (final Throwable error) { ConsoleIO.stderr("Error when invoking the '"//$NON-NLS-1$ + selected + "' tool.", //$NON-NLS-1$ error); System.exit(1); } } } /** forbidden */ private PostProcessor() { throw new UnsupportedOperationException(); } }
26.04
76
0.544803
90c4b4de3e5261ab8c62aca7070987195c9408c7
47
public aspect A { declare @type: T: @Foo; }
9.4
25
0.595745
bd0ace90a108dcc470a6c32a048e163938ce1971
1,344
//Controller.java //(C) Joseph Mack 2011, jmack (at) wm7d (dot) net, released under GPL v3 (or any later version) //inspired by Joseph Bergin's MVC gui at http://csis.pace.edu/~bergin/mvc/mvcgui.html //Controller is a Listener class Controller implements java.awt.event.ActionListener { //Joe: Controller has Model and View hardwired in Model model; View view; Controller() { System.out.println ("Controller()"); } //Controller() //invoked when a button is pressed public void actionPerformed(java.awt.event.ActionEvent e){ //uncomment to see what action happened at view /* System.out.println ("Controller: The " + e.getActionCommand() + " button is clicked at " + new java.util.Date(e.getWhen()) + " with e.paramString " + e.paramString() ); */ System.out.println("Controller: acting on Model"); model.incrementValue(); } //actionPerformed() //Joe I should be able to add any model/view with the correct API //but here I can only add Model/View public void addModel(Model m){ System.out.println("Controller: adding model"); this.model = m; } //addModel() public void addView(View v){ System.out.println("Controller: adding view"); this.view = v; } //addView() public void initModel(int x){ model.setValue(x); } //initModel() } //Controller
29.217391
96
0.675595
b877c29527f17d9fb2a1b7d319ed37373f1b4557
1,416
/* * Copyright 2011-2021 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.appng.api.model; import java.util.Arrays; import java.util.List; /** * Defines the different types a {@link Subject} can be of. * * @author Matthias Müller */ public enum UserType { /** * Type for local users, which are completely configured within appNG, including their credentials. */ LOCAL_USER, /** * A global user, which is known by appNG, but the credentials are managed by an external system (e.g. LDAP or * NTLM/Kerberos). */ GLOBAL_USER, /** * A global group (without specific users), which is known by appNG, but the credentials are managed by an external * system (e.g. LDAP or NTLM/Kerberos). */ GLOBAL_GROUP; public static List<String> names() { return Arrays.asList(LOCAL_USER.name(), GLOBAL_USER.name(), GLOBAL_GROUP.name()); } }
28.32
116
0.717514
642c1a6b44c6865df49c3aeaa547249cf24d5ceb
692
package cn.gyw.backend.web.utils; import cn.gyw.components.web.utils.JwtTokenUtil; import org.junit.Test; import static org.junit.Assert.assertEquals; public class JwtTokenUtilTest { @Test public void testGetToken() { System.out.println(JwtTokenUtil.getToken("1001")); System.out.println(JwtTokenUtil.getToken("1002")); } @Test public void testGetUserId() { assertEquals("1001", JwtTokenUtil.getUserId( "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJhdWQiOiIxMDAxIn0.mfd9Q4HRQMRr36aGHlIOn4wV6934_rU24gjRMRrSnTM")); assertEquals("1002", JwtTokenUtil.getUserId( "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJhdWQiOiIxMDAyIn0.vjp1rJb6jwxoyg1dqArEQfUSyo9nbtttPYsxJfGYf4c")); } }
27.68
109
0.800578
cdaf2bce7328ba8b573e5bd4e7e1fdf80dc8c762
655
class Solution { public ListNode insertionSortList(ListNode head) { ListNode dummy = new ListNode(0); ListNode prev = dummy; // the last (largest) of the sorted list while (head != null) { // current inserting node ListNode next = head.next; // cache next inserting node if (prev.val >= head.val) // `prev` >= current inserting node prev = dummy; // move `prev` to the front while (prev.next != null && prev.next.val < head.val) prev = prev.next; head.next = prev.next; prev.next = head; head = next; // update current inserting node } return dummy.next; } }
32.75
68
0.6
cd7ca7c42b88b1338afcacd38f2083104f55d222
1,338
package com.cpq.app001; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.cloud.client.discovery.EnableDiscoveryClient; import org.springframework.cloud.openfeign.EnableFeignClients; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RestController; import java.util.Map; @SpringBootApplication @EnableDiscoveryClient @EnableFeignClients @RestController public class App01Application { @Autowired App02Feign app02Feign; public static void main(String[] args) { SpringApplication.run(App01Application.class, args); } @GetMapping("/test01/get") public String test01Get(){ return "test01/get"; } @PostMapping("/test01/post") public Object test01Post(@RequestBody Map<String, String> map){ map.put("app", "app001"); return map; } @PostMapping("/test01/test02/post") public Object test0102Post(@RequestBody Map<String, String> map){ map.put("feign", "feign"); return app02Feign.test02Post(map); } }
29.086957
72
0.754858
e9d2cce24b9c1723f9484a7eba3f6d79e4b5a4d6
2,072
package de.tum.in.www1.artemis.service.connectors.bamboo.dto; import java.util.List; public class ApplicationLinksDTO { private List<ApplicationLinkDTO> applicationLinks; public List<ApplicationLinkDTO> getApplicationLinks() { return applicationLinks; } public void setApplicationLinks(List<ApplicationLinkDTO> applicationLinks) { this.applicationLinks = applicationLinks; } public static class ApplicationLinkDTO { private String id; private String name; private String description; private String type; private String rpcUrl; private String displayUrl; private boolean primary; private boolean system; public String getId() { return id; } public void setId(String id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } public String getType() { return type; } public void setType(String type) { this.type = type; } public String getRpcUrl() { return rpcUrl; } public void setRpcUrl(String rpcUrl) { this.rpcUrl = rpcUrl; } public String getDisplayUrl() { return displayUrl; } public void setDisplayUrl(String displayUrl) { this.displayUrl = displayUrl; } public boolean isPrimary() { return primary; } public void setPrimary(boolean primary) { this.primary = primary; } public boolean isSystem() { return system; } public void setSystem(boolean system) { this.system = system; } } }
20.72
80
0.560328
f88708ecd13fa2725f084584652568d2044b9388
8,967
package com.bkhech.home.practice; import com.alibaba.fastjson.JSONObject; import com.bkhech.home.practice.entity.AccountState; import com.bkhech.home.practice.utils.DateTimeFormatterUtils; import com.bkhech.home.practice.utils.RandomStringUtil; import org.junit.Test; import org.springframework.util.DigestUtils; import java.math.BigInteger; import java.time.LocalDateTime; import java.time.ZoneId; import java.util.Date; import java.util.HashMap; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ThreadLocalRandom; import java.util.concurrent.atomic.AtomicInteger; import java.util.stream.IntStream; import java.util.stream.Stream; /** * @author guowm * @date 2018/11/26 */ public class BaseTests { /** * 串行情况下,没差。并行情况下,有差别。 * * 第二行输出的一直是: * AAA * BBB * CCC * 而第一种输出的情况不确定。应为是并行处理。 * 其实两者完成的功能类似,主要区别在并行处理上,forEach是并行处理的,forEachOrder是按顺序处理的,显然前者速度更快 * * @see // https://blog.csdn.net/zhangshk_/article/details/80773161 */ @Test public void forEachTest() { //1.串行 IntStream.range(1, 20).forEach(i -> { Stream.of("AAA","BBB","CCC").forEach(s->System.out.println("Output forEach :"+s)); Stream.of("AAA","BBB","CCC").forEachOrdered(s->System.out.println("Output forEachOrdered:"+s)); System.out.println("====================="); try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } }); //2.并行 IntStream.range(1, 20).forEach(i -> { Stream.of("AAA","BBB","CCC").parallel().forEach(s->System.out.println("Output parallel forEach :"+s)); Stream.of("AAA","BBB","CCC").parallel().forEachOrdered(s->System.out.println("Output parallel forEachOrdered:"+s)); System.out.println("====================="); try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } }); } /** * Map Test */ @Test public void mapTest() { Map<Integer, Integer> map = new HashMap<>(5); IntStream.range(1,14).forEach(i -> { map.put(i,i); System.out.println("i = " + i); String a = RandomStringUtil.getAlphaNumeric(9); System.out.println("map = " + a); }); } @Test public void baseTest() { int h = "111111111111".hashCode(); System.out.println(h); System.out.println("h = " + toBinaryAutoPadding32Bit(h)); final int i = h >>> 16; System.out.println("i = " + toBinaryAutoPadding32Bit(i)); int ret = h ^ i; System.out.println("r = " + toBinaryAutoPadding32Bit(ret)); } private String toBinaryAutoPadding32Bit(int h) { final String binaryString = Integer.toBinaryString(h); StringBuilder sb = new StringBuilder(); for (int i = 0; i < 32 - binaryString.length(); i++) { sb.append("0"); } sb.append(binaryString); return sb.toString(); } /** * ThreadLocalRandom * @throws InterruptedException */ @Test public void threadLocalRandomTest() throws InterruptedException { AtomicInteger atomicInteger = new AtomicInteger(0); while (true) { int i = ThreadLocalRandom.current().nextInt(1, 7); System.out.println("i = " + i); atomicInteger.incrementAndGet(); if (atomicInteger.get() ==20 ) { break; } Thread.sleep(1000); } } @Test public void localTimeTest(){ int banHour = Integer.parseInt(" 2 小时 ".replace("小时", "").trim()); String tenYearsLater = new Date().toInstant().atZone(ZoneId.systemDefault()) .plusHours(banHour) .format(DateTimeFormatterUtils.LOCAL_DATE_TIME); System.out.println("tenYearsLater = " + tenYearsLater); AccountState accountState = new AccountState(); JSONObject dataJson = new JSONObject(); dataJson.put("banTime", System.currentTimeMillis()/1000 - 60 * 60); long banTime = dataJson.containsKey("banTime") ? dataJson.getLongValue("banTime") * 1000L : 0L; long chatBanTime = dataJson.containsKey("chatBanTime") ? dataJson.getLongValue("chatBanTime") * 1000L : 0L; if (banTime > System.currentTimeMillis()) { Date banDate = new Date(banTime); accountState.setBan(true); accountState.setBanTime(LocalDateTime.ofInstant(banDate.toInstant(), ZoneId.systemDefault()).format(DateTimeFormatterUtils.LOCAL_DATE_TIME)); } if (chatBanTime > System.currentTimeMillis()) { Date chatBanDate = new Date(chatBanTime); accountState.setChatBan(true); accountState.setChatBanTime(LocalDateTime.ofInstant(chatBanDate.toInstant(), ZoneId.systemDefault()).format(DateTimeFormatterUtils.LOCAL_DATE_TIME)); } System.out.println("accountState = " + accountState); } @Test public void testMd5DigestAsHex() { String s = DigestUtils.md5DigestAsHex("key=23&ydt=37d".getBytes()); System.out.println("s = " + s); } @Test public void unsigned() { long i = Integer.toUnsignedLong(-233); System.out.println("i = " + i); String s = Integer.toUnsignedString(-233); System.out.println("s = " + s); long a = 0xffffffffL; System.out.println("a = " + a); BigInteger bigInteger = new BigInteger("ffffffff", 16); System.out.println("bigInteger = " + bigInteger.toString()); System.out.println("bigInteger = " + bigInteger.toString(2)); System.out.println("bigInteger = " + bigInteger.toString(16)); int cc = -12 >> 2; System.out.println("cc = " + cc); BigInteger integer = new BigInteger(String.valueOf(cc)); String s1 = integer.toString(2); System.out.println("s1 = " + s1); BigInteger byteInteger = new BigInteger("00111111111111111111111111111101", 2); System.out.println("byteInteger = " + byteInteger.toString()); /** * 取余。 * 使用 & 来进行取余的算法比使用 / 效率高很多, * 虽然只能对2^n的数值进行取余计算, * 但是在JDK源码中也是经常被使用到,比如说HashMap中判断key在Hash桶中的位置。 */ int aMod = 33; int mod1 = aMod & 15; int mod2 = aMod % 16; System.out.println("mod1 = " + mod1); System.out.println("mod2 = " + mod2); /** * 求相反数 */ int aa = 1000; long bb = ~aa + 1; System.out.println("bb = " + bb); /** * 求绝对值 */ int aaa = -3000000; System.out.println("aaa >> 31 = " + (aaa >> 31)); int bbb = aaa >> 31 == 0 ? aaa : (~aaa + 1); System.out.println("bbb = " + bbb); /** * 原文地址:https://blog.csdn.net/Leon_cx/article/details/81911183 * 生成第一个大于或者等于a的满足2^n的数 * * 这个标题可能显得不那么容易理解,下面结合场景来解释一下。 * * 在HashMap中我们需要生成一个Hash桶,用来存储键值对(或者说存储链表)。 * 当我们查询一个key的时候,会计算出这个key的hashCode,然后根据这个hashCode来计算出这个key在hash桶中的落点, * 由于上面介绍的使用 & 来取余效率比 % 效率高,所以HashMap中根据hashCode计算落点使用的是 & 来取余。 * 使用 & 取余有一个局限性就是除数必须是2^n,所以hash桶的size必须是2^n。 * 由于HashMap的构造器支持传入一个初始的hash桶size,所以HashMap需要对用户传入的size进行处理,生成一个第一个大于size的并且满足2^n的数。 * 这个算法的使用场景介绍完毕了,那么再来看一下算法实现: * * 循环判断 * public static final int tableSizeFor(int cap) { * int size = 1; * while (size < cap) { * size *= 2; * } * return size; * } * | 运算符实现 * public static final int tableSizeFor(int cap) { * int n = cap - 1; * n |= n >>> 1; * n |= n >>> 2; * n |= n >>> 4; * n |= n >>> 8; * n |= n >>> 16; * return (n < 0) ? 1 : (n >= MAXIMUM_CAPACITY) ? MAXIMUM_CAPACITY : n + 1; * } * HashMap就是使用这个算法来修改用户使用构造器传进来的size的,这个算法是使用移位和或结合来实现的,性能上比循环判断要好。 */ Map map = new HashMap(2); Map concurrentMap = new ConcurrentHashMap(2); System.out.println("tableSizeFor() = " + tableSizeFor(6)); int aaaa=232; //0000 0000 1110 1000 System.out.println("aaaa = " + Integer.toBinaryString(aaaa)); //强转变为8位:11101000(原码),十进制等于-24 System.out.println("aaaa = " + (byte) aaaa); /** * 位溢出 */ byte dd = (byte)128; System.out.println("dd = " + dd); } int tableSizeFor(int cap) { int n = cap - 1; n |= n >>> 1; System.out.println("n = " + n); n |= n >>> 2; n |= n >>> 4; n |= n >>> 8; n |= n >>> 16; return n + 1; } }
32.48913
161
0.559496
ea8860d55e8901f450baf3b327cd4d6849257139
418
import java.io.IOException; import java.util.Scanner; public class Main1060 { public static void main(String[] args) throws IOException { Scanner ler = new Scanner(System.in); int c = 0; for(int i = 0; i < 6; i++){ double a = ler.nextDouble(); if(a > 0){ c++; } } System.out.println(c + " valores positivos"); } }
20.9
63
0.507177
6dc32c1766c36a03bfaa6372c8d8400be3760f60
1,417
/* * 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 layout.views.project; import javax.swing.*; /** * * @author tug70 */ public class NewClass extends JFrame{ private JList<String> countryList; public NewClass() { //create the model and add elements DefaultListModel<String> listModel = new DefaultListModel<>(); //create the list countryList = new JList<>(listModel); add(countryList); listModel.addElement("USA"); listModel.addElement("India"); listModel.addElement("Vietnam"); listModel.addElement("Canada"); listModel.addElement("Denmark"); listModel.addElement("France"); listModel.addElement("Great Britain"); listModel.addElement("Japan"); ; this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); this.setTitle("JList Example"); this.setSize(200,200); this.setLocationRelativeTo(null); this.setVisible(true); } public static void main(String[] args) { SwingUtilities.invokeLater(new Runnable() { @Override public void run() { new NewClass(); } }); } }
28.918367
80
0.587862
c3e5d6023f665ed6ea55eb4700960196e2f401e0
573
package com.cmd.report.inputs.arguments_validators; import org.junit.Test; import static org.junit.jupiter.api.Assertions.assertThrows; public class DateValidatorTest { @Test public void should_give_an_exception_when_dates_arguments_are_Wrong() throws InvalidInputException{ String[] args= {"order_report", "202-05-10", "2020-08-04", "Email", "waruni@gmail.com" }; DateValidator dateValidator = new DateValidator(args); assertThrows(InvalidInputException.class, () ->{ dateValidator.validateArgument(); }); } }
28.65
103
0.712042
6ccafac8325ef1cae02c0df5fdd9076d0ec9cced
664
package mekanism.common.inventory.container.tile; import mekanism.common.registries.MekanismContainerTypes; import mekanism.common.tile.TileEntityEnergyCube; import net.minecraft.entity.player.PlayerInventory; import net.minecraft.network.PacketBuffer; public class EnergyCubeContainer extends MekanismTileContainer<TileEntityEnergyCube> { public EnergyCubeContainer(int id, PlayerInventory inv, TileEntityEnergyCube tile) { super(MekanismContainerTypes.ENERGY_CUBE, id, inv, tile); } public EnergyCubeContainer(int id, PlayerInventory inv, PacketBuffer buf) { this(id, inv, getTileFromBuf(buf, TileEntityEnergyCube.class)); } }
39.058824
88
0.801205
9852d3b44dc764464a6aa0e48b98f5af20aa4798
7,421
package Programming; import Vendor.Trainmaster; import Moot.MethodsRobot; import java.io.IOException; import java.util.Collections; import java.util.LinkedList; import static java.util.Collections.sort; import static java.lang.String.format; public abstract class Controller { private static final String synX678String = "\n"; private static final String synX677String = "%-7s%16d%19d"; private static final String synX676String = " to file."; private static final String synX675String = "Unable to write "; private static final String synX674String = "\n"; private static final String synX673String = ":"; private static final String synX672String = "T"; private static final String synX671String = "%-5s%3s"; private static final int synX670int = -1469771284; private static final String synX669String = " to file."; private static final String synX668String = "Unable to write "; private static final String synX667String = "\n"; private static final String synX666String = "\n"; private static final String synX665String = "\n"; private static final int synX664int = 265424188; private static final String synX663String = " to file."; private static final String synX662String = "Unable to write "; private static final String synX661String = "\n"; private static final String synX660String = "\n"; private static final String synX659String = "Turnaround Time"; private static final String synX658String = "Waiting Time"; private static final String synX657String = "Process"; private static final String synX656String = "%-7s%16s%19s"; private static final String synX655String = "\n"; private static final double synX654double = 0.08968178792207593; private static final String synX653String = "hf8AXUPCro2ztguh"; private static final double synX652double = 0.2933893003485343; private static final int synX651int = 1940557639; private static final int synX650int = 1940115298; private static final int synX649int = 0; private static final String synX648String = "ts"; private static final String synX647String = "3Eeahae7hRWDuT"; private static final boolean synX646boolean = false; private static final double synX645double = 0.7199744439052471; private static final boolean synX644boolean = true; private static final double synX643double = 0.20776037483329357; private int flowIndicate = 0; protected Programming.System ongoingWork = null; public static final int HourPurity = 4; protected int maintainingBallaJuncture = 0; protected boolean variWaving = false; protected int mediocreReversionMoment = 0; protected int fairPostponeYear = 0; protected java.util.LinkedList<System> undergoneMethodologies = null; protected int queuingMoment = 0; protected int flowingSentence = 0; protected boolean isMoving = false; public static final String minimalSlot = "oz9oNPYvJ9Lwt"; public Controller() { this.isMoving = (false); this.flowingSentence = (0); this.queuingMoment = (0); this.fairPostponeYear = (0); this.mediocreReversionMoment = (0); this.flowIndicate = (-1); this.undergoneMethodologies = (new java.util.LinkedList<>()); this.variWaving = (true); } public synchronized void originateConfiguration() { double curb; curb = (synX643double); this.isMoving = (synX644boolean); this.maintainingBallaJuncture = (Trainmaster.DischargeDays); this.nbsBegin(); } public synchronized void pointSynchronizer() { double hokkianeseRadius; hokkianeseRadius = (synX645double); this.isMoving = (synX646boolean); this.publicationAssessment(); } public synchronized boolean goIsMoving() { String premium; premium = (synX647String); return isMoving; } public synchronized int catchFinalizeSueScale() { String minutesWide; minutesWide = (synX648String); if (undergoneMethodologies.isEmpty()) { return synX649int; } else { return undergoneMethodologies.size(); } } public synchronized int obtainLiveTic() { int pettyIndentured; pettyIndentured = (synX650int); return flowIndicate; } public synchronized void putPrevailingClick(int prevalentScore) { int pinioned; pinioned = (synX651int); this.flowIndicate = (prevalentScore); } public synchronized double conveyRegularHopeAmount() { double restricts; restricts = (synX652double); return (double) this.fairPostponeYear / this.undergoneMethodologies.size(); } public synchronized double takeMeanUpturnPeriod() { String threshold; threshold = (synX653String); return (double) this.mediocreReversionMoment / this.undergoneMethodologies.size(); } public synchronized void publicationAssessment() { double confine; confine = (synX654double); try { java.lang.String cope; sort(undergoneMethodologies); MethodsRobot.ExportationPapers.write(synX655String); System.out.println(); cope = (format(synX656String, synX657String, synX658String, synX659String)); MethodsRobot.ExportationPapers.write(cope + synX660String); System.out.println(cope); for (Programming.System postscript : undergoneMethodologies) synx76(postscript); MethodsRobot.ExportationPapers.write(synX661String); System.out.println(); } catch (java.io.IOException combatants) { System.out.println((synX662String + this.configurationDiscover() + synX663String)); } } public synchronized void nbsBegin() { int profitability; profitability = (synX664int); try { MethodsRobot.ExportationPapers.write(synX665String); System.out.println(); MethodsRobot.ExportationPapers.write( (synX666String + this.configurationDiscover() + synX667String)); System.out.println(this.configurationDiscover()); } catch (java.io.IOException voto) { System.out.println((synX668String + this.configurationDiscover() + synX669String)); } } public synchronized void onusServe(Programming.System vig) { int apexSure; apexSure = (synX670int); try { java.lang.String mechanisms; mechanisms = (format( synX671String, (synX672String + (this.obtainLiveTic()) + synX673String), vig.drawName())); MethodsRobot.ExportationPapers.write(mechanisms + synX674String); System.out.println(mechanisms); } catch (java.io.IOException officio) { System.out.println((synX675String + this.configurationDiscover() + synX676String)); } } public abstract java.lang.String configurationDiscover(); public abstract void optiBeat(); public abstract void methodologyArrival(Programming.System march); private synchronized void synx76(System postscript) { int stayAgain; int convinceOverPeriod; java.lang.String negotiations; stayAgain = ((postscript.fetchWithdrawBeginning() - postscript.conveyAdoptAmount() - postscript.drawBossScope())); convinceOverPeriod = (postscript.fetchWithdrawBeginning() - postscript.conveyAdoptAmount()); this.fairPostponeYear += (stayAgain); this.mediocreReversionMoment += (convinceOverPeriod); negotiations = (format(synX677String, postscript.drawName(), stayAgain, convinceOverPeriod)); MethodsRobot.ExportationPapers.write(negotiations + synX678String); System.out.println(negotiations); } }
36.55665
97
0.727126
1d7b81167720adec36ffedd1ebefef643c72f4c9
3,913
package fr.adrienbrault.idea.symfony2plugin.templating.annotation; import com.intellij.psi.PsiElement; import com.intellij.psi.util.PsiTreeUtil; import com.intellij.util.containers.ContainerUtil; import com.jetbrains.php.lang.documentation.phpdoc.psi.PhpDocComment; import com.jetbrains.php.lang.psi.elements.Method; import com.jetbrains.php.lang.psi.elements.PhpPsiElement; import de.espend.idea.php.annotation.extension.PhpAnnotationDocTagAnnotator; import de.espend.idea.php.annotation.extension.parameter.PhpAnnotationDocTagAnnotatorParameter; import fr.adrienbrault.idea.symfony2plugin.Settings; import fr.adrienbrault.idea.symfony2plugin.Symfony2ProjectComponent; import fr.adrienbrault.idea.symfony2plugin.TwigHelper; import fr.adrienbrault.idea.symfony2plugin.templating.PhpTemplateAnnotator; import fr.adrienbrault.idea.symfony2plugin.templating.util.TwigUtil; import fr.adrienbrault.idea.symfony2plugin.util.PhpElementsUtil; import java.util.Arrays; import java.util.Collection; import java.util.HashSet; import java.util.regex.Matcher; import java.util.regex.Pattern; /** * @author Daniel Espendiller <daniel@espendiller.net> */ public class TemplateAnnotationAnnotator implements PhpAnnotationDocTagAnnotator { @Override public void annotate(PhpAnnotationDocTagAnnotatorParameter parameter) { if(!Symfony2ProjectComponent.isEnabled(parameter.getProject()) || !Settings.getInstance(parameter.getProject()).phpAnnotateTemplateAnnotation || !PhpElementsUtil.isEqualClassName(parameter.getAnnotationClass(), TwigHelper.TEMPLATE_ANNOTATION_CLASS)) { return; } PhpPsiElement phpDocAttrList = parameter.getPhpDocTag().getFirstPsiChild(); if(phpDocAttrList == null) { return; } String tagValue = phpDocAttrList.getText(); Collection<String> templateNames = new HashSet<>(); // @Template("FooBundle:Folder:foo.html.twig") // @Template("FooBundle:Folder:foo.html.twig", "asdas") // @Template(tag="name") Matcher matcher = Pattern.compile("\\(\"(.*)\"").matcher(tagValue); if (matcher.find()) { templateNames.add(matcher.group(1)); } else { // find template name on last method PhpDocComment docComment = PsiTreeUtil.getParentOfType(parameter.getPhpDocTag(), PhpDocComment.class); if(null == docComment) { return; } Method method = PsiTreeUtil.getNextSiblingOfType(docComment, Method.class); if(null == method || !method.getName().endsWith("Action")) { return; } String[] controllerMethodShortcut = TwigUtil.getControllerMethodShortcut(method); if(controllerMethodShortcut != null) { templateNames.addAll(Arrays.asList(controllerMethodShortcut)); } } if(templateNames.size() == 0) { return; } for (String templateName : templateNames) { if (TwigHelper.getTemplatePsiElements(parameter.getProject(), templateName).length > 0) { return; } } // find html target, as this this our first priority for end users condition String templateName = ContainerUtil.find(templateNames, s -> s.toLowerCase().endsWith(".html.twig")); // fallback on first item if(templateName == null) { templateName = templateNames.iterator().next(); } // add fix to doc tag PsiElement firstChild = parameter.getPhpDocTag().getFirstChild(); if(null == firstChild) { return; } parameter.getHolder() .createWarningAnnotation(firstChild.getTextRange(), "Create Template") .registerFix(new PhpTemplateAnnotator.CreateTemplateFix(templateName)) ; } }
37.990291
115
0.681063
6c00162eb80d49864a394e8d76f0086058b7885f
768
// Decompiled by Jad v1.5.8e. Copyright 2001 Pavel Kouznetsov. // Jad home page: http://www.geocities.com/kpdus/jad.html // Decompiler options: braces fieldsfirst space lnc package android.support.v4.net; import java.net.Socket; // Referenced classes of package android.support.v4.net: // n, o class m implements n { m() { } public void a() { o.a(); } public void a(int i) { o.a(i); } public void a(int i, int j) { o.a(i, j); } public void a(Socket socket) { o.a(socket); } public int b() { return o.b(); } public void b(int i) { o.b(i); } public void b(Socket socket) { o.b(socket); } }
13.963636
62
0.513021
17548b15a5bb9d482ef81f4ca72830fee684e548
798
package test.test; import java.beans.PropertyEditorSupport; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Date; public class DatePropertyEditor extends PropertyEditorSupport { private String format = "YYYY-MM-dd"; public String getFormat() { return format; } public void setFormat(String format) { this.format = format; } @Override public void setAsText(String text) throws IllegalArgumentException { System.out.println("text:" + text); SimpleDateFormat simpleDateFormat = new SimpleDateFormat(format); try { Date date = simpleDateFormat.parse(text); this.setValue(date); } catch (ParseException e) { e.printStackTrace(); } } }
24.9375
73
0.660401
a518a736d3366d55abe296f3d59e8c87d61577c7
255
package com.coolweather.android.gson; /** * Created by Lv on 2018/11/6. * 定义Gson aqi 实体类 api中 会包含控件的质量情况 */ public class AQI { public AQICity city; public class AQICity{ public String aqi ; public String pm25; } }
15.9375
38
0.619608
77991504adf9ff28f89b5ae126335edcec3edcb3
11,723
package com.tspeiz.modules.common.service.impl; import java.math.BigDecimal; import java.util.List; import java.util.Map; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import com.tspeiz.modules.common.bean.AdviceBean; import com.tspeiz.modules.common.bean.D2pOrderBean; import com.tspeiz.modules.common.bean.weixin.MobileSpecial; import com.tspeiz.modules.common.dao.newrelease.IBusinessMessageBeanDao; import com.tspeiz.modules.common.dao.newrelease.IDistCodeDao; import com.tspeiz.modules.common.dao.newrelease.IDoctorDetailInfoDao; import com.tspeiz.modules.common.dao.newrelease.IHospitalDetailInfoDao; import com.tspeiz.modules.common.dao.newrelease.IStandardDepartmentInfoDao; import com.tspeiz.modules.common.dao.newrelease.IUserBillRecordDao; import com.tspeiz.modules.common.dao.release2.IBusinessD2dReferralOrderDao; import com.tspeiz.modules.common.dao.release2.IBusinessD2pConsultationRequestDao; import com.tspeiz.modules.common.dao.release2.IBusinessD2pFastaskOrderDao; import com.tspeiz.modules.common.dao.release2.IBusinessD2pReportOrderDao; import com.tspeiz.modules.common.dao.release2.IBusinessD2pTelOrderDao; import com.tspeiz.modules.common.dao.release2.IBusinessD2pTuwenOrderDao; import com.tspeiz.modules.common.dao.release2.IBusinessT2pTuwenOrderDao; import com.tspeiz.modules.common.dao.release2.ISystemWarmthInfoDao; import com.tspeiz.modules.common.dao.release2.IUserMedicalRecordDao; import com.tspeiz.modules.common.dao.release2.IUserWarmthInfoDao; import com.tspeiz.modules.common.entity.newrelease.DistCode; import com.tspeiz.modules.common.entity.newrelease.HospitalDetailInfo; import com.tspeiz.modules.common.entity.newrelease.StandardDepartmentInfo; import com.tspeiz.modules.common.entity.newrelease.UserBillRecord; import com.tspeiz.modules.common.entity.release2.BusinessD2dReferralOrder; import com.tspeiz.modules.common.entity.release2.BusinessD2pConsultationRequest; import com.tspeiz.modules.common.entity.release2.BusinessD2pFastaskOrder; import com.tspeiz.modules.common.entity.release2.BusinessD2pReportOrder; import com.tspeiz.modules.common.entity.release2.BusinessD2pTelOrder; import com.tspeiz.modules.common.entity.release2.BusinessD2pTuwenOrder; import com.tspeiz.modules.common.entity.release2.BusinessT2pTuwenOrder; import com.tspeiz.modules.common.entity.release2.SystemWarmthInfo; import com.tspeiz.modules.common.entity.release2.UserMedicalRecord; import com.tspeiz.modules.common.entity.release2.UserWarmthInfo; import com.tspeiz.modules.common.service.ID2pService; @Service public class D2pServiceImpl implements ID2pService{ @Autowired private IBusinessD2pFastaskOrderDao businessD2pFastaskOrderDao; @Autowired private IBusinessD2pTelOrderDao businessD2pTelOrderDao; @Autowired private IBusinessD2pTuwenOrderDao businessD2pTuwenOrderDao; @Autowired private IBusinessD2pReportOrderDao businessD2pReportOrderDao; @Autowired private ISystemWarmthInfoDao systemWarmthInfoDao; @Autowired private IUserWarmthInfoDao userWarmthInfoDao; @Autowired private IUserMedicalRecordDao userMedicalRecordDao; @Autowired private IDoctorDetailInfoDao doctorDetailInfoDao; @Autowired private IBusinessMessageBeanDao businessMessageBeanDao; @Autowired private IStandardDepartmentInfoDao standardDepartmentInfoDao; @Autowired private IHospitalDetailInfoDao hospitalDetailInfoDao; @Autowired private IDistCodeDao distCodeDao; @Autowired private IBusinessD2pConsultationRequestDao businessD2pConsultationRequestDao; @Autowired private IBusinessD2dReferralOrderDao businessD2pReferralOrderDao; @Autowired private IBusinessT2pTuwenOrderDao businessT2pTuwenOrderDao; public Map<String, Object> queryd2pteldatas(Map<String, Object> querymap, Integer start, Integer length) { // TODO Auto-generated method stub return businessD2pTelOrderDao.queryd2pteldatas(querymap,start,length); } public Map<String, Object> queryd2ptuwendatas(Map<String, Object> querymap, Integer start, Integer length) { // TODO Auto-generated method stub return businessD2pTuwenOrderDao.queryd2ptuwendatas(querymap,start,length); } public Map<String, Object> queryd2pfastaskdatas( Map<String, Object> querymap, Integer start, Integer length) { // TODO Auto-generated method stub return businessD2pFastaskOrderDao.queryd2pfastaskdatas(querymap,start,length); } public Map<String, Object> queryd2preportdatas( Map<String, Object> querymap, Integer start, Integer length) { // TODO Auto-generated method stub return businessD2pReportOrderDao.queryd2preportdatas(querymap,start,length); } public Map<String, Object> queryd2pconreqdatas( Map<String, Object> querymap, Integer start, Integer length) { // TODO Auto-generated method stub return businessD2pConsultationRequestDao.queryd2pconreqdatas(querymap, start, length); } public D2pOrderBean queryOrderDetailInfo(Integer oid, Integer otype) { // TODO Auto-generated method stub return businessD2pTelOrderDao.queryOrderDetailInfo(oid,otype); } public Integer saveBusinessD2pFastAskOrder(BusinessD2pFastaskOrder forder) { // TODO Auto-generated method stub return businessD2pFastaskOrderDao.save(forder); } public BusinessD2pFastaskOrder queryd2pfastaskorderbyid(Integer oid) { // TODO Auto-generated method stub return businessD2pFastaskOrderDao.find(oid); } public void updated2pfastaskorder(BusinessD2pFastaskOrder order) { // TODO Auto-generated method stub businessD2pFastaskOrderDao.update(order); } public Integer saveBusinessPatientReportOrder(BusinessD2pReportOrder order) { // TODO Auto-generated method stub return businessD2pReportOrderDao.save(order); } public List<BusinessD2pReportOrder> queryd2preportordersbyuserid( Integer userid) { // TODO Auto-generated method stub return businessD2pReportOrderDao.queryd2preportordersbyuserid(userid); } public BusinessD2pReportOrder queryd2preportorderbyconditions( String subUserUuid, Integer docid) { // TODO Auto-generated method stub return businessD2pReportOrderDao.queryd2preportorderbyconditions(subUserUuid, docid); } public List<SystemWarmthInfo> querysystemwarms() { // TODO Auto-generated method stub return systemWarmthInfoDao.querysystemwarms(); } public Integer saveUserWarmthInfo(UserWarmthInfo uw) { // TODO Auto-generated method stub return userWarmthInfoDao.save(uw); } public UserWarmthInfo queryuserwarminfo(Integer id) { // TODO Auto-generated method stub return userWarmthInfoDao.find(id); } public void updateuserwarminfo(UserWarmthInfo uw) { // TODO Auto-generated method stub userWarmthInfoDao.update(uw); } public List<D2pOrderBean> querymyorders(Integer userid, String ltype, Integer pageNo, Integer pageSize) { // TODO Auto-generated method stub return businessD2pTelOrderDao.querymyorders(userid, ltype, pageNo, pageSize); } public List<UserMedicalRecord> queryusermedicalrecords(String subUserUuid) { // TODO Auto-generated method stub return userMedicalRecordDao.queryusermedicalrecords(subUserUuid); } public Integer saveUserMedicalRecord(UserMedicalRecord record) { // TODO Auto-generated method stub return userMedicalRecordDao.save(record); } public Integer querydoctorwarms(Integer docid) { // TODO Auto-generated method stub return userWarmthInfoDao.querydoctorwarms(docid); } public BusinessD2pReportOrder queryd2preportorderbyid(Integer id) { // TODO Auto-generated method stub return businessD2pReportOrderDao.find(id); } public BusinessD2pTuwenOrder queryd2ptuwenorderbyid(Integer id) { // TODO Auto-generated method stub return businessD2pTuwenOrderDao.find(id); } public BusinessD2pTelOrder queryd2ptelorderbyid(Integer id) { // TODO Auto-generated method stub return businessD2pTelOrderDao.find(id); } public List<MobileSpecial> querydoctors(String search, String serviceid, String depid, String distcode, Integer _pageNo, Integer pageSize) { // TODO Auto-generated method stub return doctorDetailInfoDao.querydoctors(search, serviceid, depid, distcode, _pageNo, pageSize); } public List<AdviceBean> newlyadvices(Integer userId) { // TODO Auto-generated method stub return businessMessageBeanDao.newlyadvices(userId); } public Integer saveBusinessD2pTelOrder(BusinessD2pTelOrder order) { // TODO Auto-generated method stub return businessD2pTelOrderDao.save(order); } public Integer saveBusinessD2pTuwenOrder(BusinessD2pTuwenOrder order) { // TODO Auto-generated method stub return businessD2pTuwenOrderDao.save(order); } public List<StandardDepartmentInfo> querystanddeps(String ispage, String ishot, Integer pageNo, Integer pageSize) { // TODO Auto-generated method stub return standardDepartmentInfoDao.querystanddeps(ispage, ishot, pageNo, pageSize); } public List<HospitalDetailInfo> querynearhoses(String ispage, String htype, String distcode, Integer _pageNo, Integer _pageSize) { // TODO Auto-generated method stub return hospitalDetailInfoDao.querynearhoses(ispage, htype, distcode, _pageNo, _pageSize); } public void updated2ptuwenorder(BusinessD2pTuwenOrder order) { // TODO Auto-generated method stub businessD2pTuwenOrderDao.update(order); } public void updated2ptelorder(BusinessD2pTelOrder order) { // TODO Auto-generated method stub businessD2pTelOrderDao.update(order); } public List<UserWarmthInfo> querydoctorwarms_list(Integer docid, Integer pageNo, Integer pageSize) { // TODO Auto-generated method stub return userWarmthInfoDao.querydoctorwarms_list(docid, pageNo, pageSize); } public List<DistCode> gainArea(String type, String parentCode) { // TODO Auto-generated method stub return distCodeDao.gainArea(type, parentCode); } public BusinessD2pConsultationRequest queryd2pconreqorderbyid(Integer oid) { // TODO Auto-generated method stub return businessD2pConsultationRequestDao.find(oid); } public void updated2pconreqorder(BusinessD2pConsultationRequest order) { // TODO Auto-generated method stub businessD2pConsultationRequestDao.update(order); } public Map<String, Object> queryd2preferdatas(Map<String, Object> querymap, Integer start, Integer length) { // TODO Auto-generated method stub return businessD2pReferralOrderDao.queryd2preferdatas(querymap, start, length); } public BusinessT2pTuwenOrder querybusinesst2ptuwenById(Integer id) { // TODO Auto-generated method stub return businessT2pTuwenOrderDao.find(id); } public void updatet2ptuwen(BusinessT2pTuwenOrder order) { // TODO Auto-generated method stub businessT2pTuwenOrderDao.update(order); } public BusinessD2dReferralOrder queryd2dreferralOrderbyId(Integer id) { // TODO Auto-generated method stub return businessD2pReferralOrderDao.find(id); } public void updated2dreferralOrder(BusinessD2dReferralOrder order) { // TODO Auto-generated method stub businessD2pReferralOrderDao.update(order); } public Integer saveBusinessD2dReferralOrder(BusinessD2dReferralOrder order) { // TODO Auto-generated method stub return businessD2pReferralOrderDao.save(order); } public void updateBusinessD2dReferralOrder(BusinessD2dReferralOrder order) { // TODO Auto-generated method stub businessD2pReferralOrderDao.update(order); } public BusinessD2dReferralOrder queryBusinessD2pReferralOrderByUuid( String orderUuid) { // TODO Auto-generated method stub return businessD2pReferralOrderDao.queryBusinessD2pReferralOrderByUuid(orderUuid); } @Override public MobileSpecial queryBusinessD2dReferralOrderByUserId(Integer docid) { // TODO Auto-generated method stub return businessD2pReferralOrderDao.queryBusinessD2dReferralOrderByUserId(docid); } }
37.215873
97
0.820609
d29ffc83de9f291913b924f66c8880b894e2e879
658
package com.github.mahui53541.graduation; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.EnableAutoConfiguration; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.context.annotation.ComponentScan; import tk.mybatis.spring.annotation.MapperScan; @SpringBootApplication @MapperScan("com.github.mahui53541.graduation.mapper") @ComponentScan(basePackages = "com.github.mahui53541.graduation") @EnableAutoConfiguration public class GraduationApplication { public static void main(String[] args) { SpringApplication.run(GraduationApplication.class, args); } }
34.631579
70
0.846505
f7d5e22ff47ec125f00fe831ce8886c9ca429542
3,953
package com.example.android.mybaking; import android.content.Context; import android.content.SharedPreferences; import android.os.Bundle; import android.support.v4.app.FragmentManager; import android.support.v7.app.AppCompatActivity; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import android.widget.Toast; import com.google.gson.Gson; public class Activity_RecipeDetail extends AppCompatActivity implements OnStepClickListener{ Recipe recipe; private boolean isTwoPane; static String SHARED_PREFERENCES_NAME="com.example.android.bakingapp"; static String RECIPE_NAME_KEY="recipeName"; static String INGREDIENTS_KEY="recipeIngredients"; private int mClickedItemIndex = 0; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_recipe_detail); recipe = (Recipe) getIntent().getParcelableExtra("recipe"); setTitle(recipe.getName()); getSupportActionBar().setDisplayHomeAsUpEnabled(true); FragmentManager fm = getSupportFragmentManager(); if(savedInstanceState != null){ mClickedItemIndex = savedInstanceState.getInt("mClickedItemIndex"); } if(findViewById(R.id.separatorView) !=null){ isTwoPane=true; Bundle bundle1 = new Bundle(); bundle1.putInt("index",mClickedItemIndex); bundle1.putString("step_title",recipe.getSteps().get(mClickedItemIndex).getShortDescription()); bundle1.putBoolean("isTwoPane",isTwoPane); bundle1.putParcelableArrayList("steps",recipe.getSteps()); Fragment_StepDescription stepDescriptionFrag = new Fragment_StepDescription(); stepDescriptionFrag.setArguments(bundle1); fm.beginTransaction() .add(R.id.recipe_step_frame, stepDescriptionFrag) .commit(); } else{ isTwoPane=false; } Bundle bundle2 = new Bundle(); bundle2.putParcelable("recipe", getIntent().getParcelableExtra("recipe")); bundle2.putBoolean("isTwoPane",isTwoPane); bundle2.putInt("mClickedItemIndex", mClickedItemIndex); Fragment_RecipeDetail recipeDetail = new Fragment_RecipeDetail(); recipeDetail.setArguments(bundle2); fm.beginTransaction() .add(R.id.recipe_detail_frame, recipeDetail) .commit(); } @Override public boolean onCreateOptionsMenu(Menu menu) { MenuInflater inflater = getMenuInflater(); inflater.inflate(R.menu.menu_recipe_detail, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { // Respond to the action bar's Up/Home button case android.R.id.home: finish(); return true; case R.id.addToWidget: SharedPreferences preferences = this.getSharedPreferences(SHARED_PREFERENCES_NAME, Context.MODE_PRIVATE); Gson gson = new Gson(); String json = gson.toJson(recipe.getIngredients()); preferences.edit().putString(RECIPE_NAME_KEY, recipe.getName()).apply(); preferences.edit().putString(INGREDIENTS_KEY, json).apply(); BakingAppWidgetProvider.sendRefreshBroadcast(this); Toast.makeText(this, "Added to Widget", Toast.LENGTH_SHORT).show(); return true; } return super.onOptionsItemSelected(item); } @Override public void onClick(int index) { mClickedItemIndex = index; } @Override protected void onSaveInstanceState(Bundle outState) { super.onSaveInstanceState(outState); outState.putInt("mClickedItemIndex", mClickedItemIndex); } }
33.218487
121
0.664559
13d2f0eeeb806014be8221fa924baafe44ab0964
660
package example5.springpatterns; import example5.springpatterns.corona.model.Patient; import example5.springpatterns.corona.services.doctors.Священник; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.context.ConfigurableApplicationContext; @SpringBootApplication public class SpringPatternsJokerApplication { public static void main(String[] args) { ConfigurableApplicationContext context = SpringApplication.run(SpringPatternsJokerApplication.class, args); context.getBean(Священник.class).исцелять(Patient.builder().build()); } }
34.736842
115
0.824242
b7b531de414b439cff9b620f8d69d038660e892c
1,953
package com.xelitexirish.elitedeveloperbot.utils; import java.io.IOException; import java.util.logging.FileHandler; import java.util.logging.Logger; import java.util.logging.SimpleFormatter; public class BotLogger { static Logger logger = Logger.getLogger("logs.txt"); static Logger messageLogger = Logger.getLogger("messageLogger.txt"); static FileHandler fileHandler; static FileHandler fileHandlerMessage; public static void initLogger(){ try { fileHandler = new FileHandler("logs.log", true); fileHandlerMessage = new FileHandler("messageLogger.log", true); logger.addHandler(fileHandler); messageLogger.addHandler(fileHandlerMessage); SimpleFormatter formatter = new SimpleFormatter(); fileHandler.setFormatter(formatter); fileHandlerMessage.setFormatter(formatter); } catch (IOException e) { e.printStackTrace(); } } public static void log(String heading, String message){ logger.info("[" + heading.toUpperCase() + "]: " + message); } public static void command(String title, String username){ messageLog("command: " + title, "Issued by player: " + username); } public static void messageLog(String heading, String message){ messageLogger.info("[" + heading.toUpperCase() + "]: " + message); } private static void log(String LogMessage) { System.out.println(LogMessage); } public static void info(String log) { log("[Elite Developer Bot] " + log); log("info", log); } public static void error(String log) { log("[Elite Developer Bot: ERROR] " + log); } public static void debug(String log) { log("[Elite Developer Bot: DEBUG] " + log); } public static void debug(String log, Exception exception) { debug(log); exception.printStackTrace(); } }
29.149254
76
0.644137
10473828525f07d03ed0f07bf326a1bb28927c62
882
package docu.journal.model; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonView; import lombok.Data; import java.util.Map; @Data public class CaseFile { @JsonView(Views.Public.class) private String caseYear; @JsonView(Views.Public.class) private String caseSequenceNumber; @JsonView(Views.Internal.class) private String title; @JsonView(Views.PublicData.class) public String publicTitle; @SuppressWarnings("unchecked") @JsonProperty("caseFile") private void unpackNeste(Map<String, Object> brand) { this.caseYear = (String) brand.get("caseYear"); this.caseSequenceNumber = (String) brand.get("caseSequenceNumber"); this.title = (String) brand.get("title"); this.publicTitle = (String) brand.get("publicTitle"); } }
28.451613
76
0.688209
ff1f7dc5a2a8aee421a67f03f888972c5fb6604c
4,579
/* * Copyright (C) 2015 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.android.systemui.recents; import android.content.Context; import android.graphics.Rect; import android.os.IBinder; import android.os.RemoteException; import android.util.EventLog; import android.util.Log; import android.util.SparseArray; import com.android.systemui.EventLogConstants; import com.android.systemui.EventLogTags; import com.android.systemui.recents.events.EventBus; import com.android.systemui.recents.events.activity.DockedFirstAnimationFrameEvent; import com.android.systemui.recents.events.activity.DockedTopTaskEvent; import com.android.systemui.recents.events.activity.RecentsActivityStartingEvent; import com.android.systemui.recents.events.component.SetWaitingForTransitionStartEvent; import com.android.systemui.recents.events.ui.RecentsDrawnEvent; import com.android.systemui.recents.misc.ForegroundThread; /** * An implementation of the system user's Recents interface to be called remotely by secondary * users. */ public class RecentsSystemUser extends IRecentsSystemUserCallbacks.Stub { private static final String TAG = "RecentsSystemUser"; private Context mContext; private RecentsImpl mImpl; private final SparseArray<IRecentsNonSystemUserCallbacks> mNonSystemUserRecents = new SparseArray<>(); public RecentsSystemUser(Context context, RecentsImpl impl) { mContext = context; mImpl = impl; } @Override public void registerNonSystemUserCallbacks(final IBinder nonSystemUserCallbacks, final int userId) { try { final IRecentsNonSystemUserCallbacks callback = IRecentsNonSystemUserCallbacks.Stub.asInterface(nonSystemUserCallbacks); nonSystemUserCallbacks.linkToDeath(new IBinder.DeathRecipient() { @Override public void binderDied() { mNonSystemUserRecents.removeAt(mNonSystemUserRecents.indexOfValue(callback)); EventLog.writeEvent(EventLogTags.SYSUI_RECENTS_CONNECTION, EventLogConstants.SYSUI_RECENTS_CONNECTION_SYSTEM_UNREGISTER_USER, userId); } }, 0); mNonSystemUserRecents.put(userId, callback); EventLog.writeEvent(EventLogTags.SYSUI_RECENTS_CONNECTION, EventLogConstants.SYSUI_RECENTS_CONNECTION_SYSTEM_REGISTER_USER, userId); } catch (RemoteException e) { Log.e(TAG, "Failed to register NonSystemUserCallbacks", e); } } public IRecentsNonSystemUserCallbacks getNonSystemUserRecentsForUser(int userId) { return mNonSystemUserRecents.get(userId); } @Override public void updateRecentsVisibility(boolean visible) { ForegroundThread.getHandler().post(() -> { mImpl.onVisibilityChanged(mContext, visible); }); } @Override public void startScreenPinning(int taskId) { ForegroundThread.getHandler().post(() -> { mImpl.onStartScreenPinning(mContext, taskId); }); } @Override public void sendRecentsDrawnEvent() { EventBus.getDefault().post(new RecentsDrawnEvent()); } @Override public void sendDockingTopTaskEvent(int dragMode, Rect initialRect) throws RemoteException { EventBus.getDefault().post(new DockedTopTaskEvent(dragMode, initialRect)); } @Override public void sendLaunchRecentsEvent() throws RemoteException { EventBus.getDefault().post(new RecentsActivityStartingEvent()); } @Override public void sendDockedFirstAnimationFrameEvent() throws RemoteException { EventBus.getDefault().post(new DockedFirstAnimationFrameEvent()); } @Override public void setWaitingForTransitionStartEvent(boolean waitingForTransitionStart) { EventBus.getDefault().post(new SetWaitingForTransitionStartEvent( waitingForTransitionStart)); } }
37.532787
97
0.718497
a88271acf716fa6f6286ef4bdcaadc5d92df75f6
2,485
package com.sonar.vishal.ui.structure.barcode; import com.sonar.vishal.medico.common.message.common.Constant; import com.sonar.vishal.ui.component.Component; import com.sonar.vishal.ui.definition.GenerateStructure; import com.sonar.vishal.ui.structure.ProductStructure; import com.sonar.vishal.ui.util.BarcodeUtil; import com.sonar.vishal.ui.util.UIConstant; import com.vaadin.server.ExternalResource; import com.vaadin.server.Page; import com.vaadin.ui.Alignment; import com.vaadin.ui.Image; import com.vaadin.ui.Notification; import com.vaadin.ui.UI; import com.vaadin.ui.VerticalLayout; import com.vaadin.ui.Window; import com.vaadin.ui.Window.CloseEvent; import com.vaadin.ui.Window.CloseListener; public class ProductBarcodeStructure extends ProductStructure implements GenerateStructure { private VerticalLayout windowLayout; private Window window; public ProductBarcodeStructure() { window = new Window(); windowLayout = new VerticalLayout(); window.setContent(windowLayout); window.setSizeFull(); } @Override public void generate() { Notification notification; if (getSelectedProduct() == null) { notification = Component.getInstance().getFailureNotification(Constant.ERROR, UIConstant.PLEASE_SELECT_ROW_GENERATE); notification.show(Page.getCurrent()); return; } String message = String.valueOf(getSelectedProduct().getId()) + UIConstant.QR_SEPERATOR + getSelectedProduct().getDescription(); String imageUrl = BarcodeUtil.generateBarcode(message, 300, 300); if (imageUrl != null) { imageUrl = BarcodeUtil.IMAGE_INDEX_URL + imageUrl; setupWindow(imageUrl); UI.getCurrent().addWindow(window); } else { notification = Component.getInstance().getFailureNotification(Constant.ERROR, UIConstant.ERROR_GENERATING_BARCODE); notification.show(Page.getCurrent()); } } private void setupWindow(String imageUrl) { ExternalResource imageSource = new ExternalResource(imageUrl); String barcodeDesc = UIConstant.MEDICO + UIConstant.BARCODE_SEPERATOR + getSelectedProduct().getDescription(); Image image = new Image(barcodeDesc, imageSource); windowLayout.addComponents(image); windowLayout.setComponentAlignment(image, Alignment.MIDDLE_CENTER); window.addCloseListener(new CloseListener() { private static final long serialVersionUID = 1L; @Override public void windowClose(CloseEvent e) { windowLayout.removeAllComponents(); getTable().deselectAll(); setSelectedProduct(null); } }); } }
34.513889
130
0.782294
7949ea410f7fce61011e62da1825b5d7ff4a3c30
460
package es.uniovi.asw.service; import es.uniovi.asw.model.Participant; public interface ParticipantService { public void deleteAllParticipants(); public Participant findParticipant(String dni); public void updateParticipant(Participant participant); public void deleteParticipantByDni(String dni); public void addParticipant(Participant participant); public void init(); public Participant findLogableUser(String usuario, String password); }
21.904762
69
0.808696
9826a92e2004debd407c1e8446a8b4256ee493c0
1,557
package org.ovirt.engine.api.restapi.types; import org.ovirt.engine.api.model.Storage; import org.ovirt.engine.api.model.StorageType; import org.ovirt.engine.api.model.VolumeGroup; public class StorageVolumeGroupMapper { @Mapping(from = org.ovirt.engine.core.common.businessentities.StorageDomain.class, to = Storage.class) public static Storage map(org.ovirt.engine.core.common.businessentities.StorageDomain entity, Storage template) { Storage model = template != null ? template : new Storage(); model.setId(entity.getStorage()); model.setType(StorageDomainMapper.map(entity.getStorageType(), null)); model.setVolumeGroup(new VolumeGroup()); model.getVolumeGroup().setId(entity.getStorage()); return model; } @Mapping(from = Storage.class, to = org.ovirt.engine.core.common.businessentities.StorageDomain.class) public static org.ovirt.engine.core.common.businessentities.StorageDomain map(Storage model, org.ovirt.engine.core.common.businessentities.StorageDomain template) { org.ovirt.engine.core.common.businessentities.StorageDomain entity = template != null ? template : new org.ovirt.engine.core.common.businessentities.StorageDomain(); entity.setStorage(model.getId()); if (model.isSetType()) { StorageType storageType = StorageType.fromValue(model.getType()); if (storageType != null) { entity.setStorageType(StorageDomainMapper.map(storageType, null)); } } return entity; } }
47.181818
173
0.715478
528d6e3f5de6650112452fbad9095230f4019746
4,851
/* * Copyright (c) 2016 EMC Corporation * All Rights Reserved */ package com.emc.storageos.db.event; import java.net.URI; import java.util.Calendar; import java.util.Iterator; import java.util.List; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.TimeUnit; import org.apache.commons.lang.StringUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.emc.storageos.coordinator.client.service.CoordinatorClient; import com.emc.storageos.db.client.DbClient; import com.emc.storageos.db.client.model.ActionableEvent; import com.emc.storageos.services.util.NamedScheduledThreadPoolExecutor; import com.google.common.collect.Lists; import com.netflix.astyanax.util.TimeUUIDUtils; /** * Deletes events that are over {@link #EVENT_TTL_MINS_PROPERTY} old at periodic intervals */ public class ActionableEventScrubberExecutor { private static final Logger log = LoggerFactory.getLogger(ActionableEventScrubberExecutor.class); private static final String EVENT_TTL_MINS_PROPERTY = "event_ttl"; private static final String EVENT_CLEAN_INTERVAL_PROPERTY = "event_clean_interval"; private final static long MIN_TO_MICROSECS = 60 * 1000 * 1000; private final static long MINI_TO_MICROSECS = 1000; private final static long MINIMUM_PERIOD_MINS = 60; private final static int DELETE_BATCH_SIZE = 100; private ScheduledExecutorService _executor = new NamedScheduledThreadPoolExecutor("ActionableEventScrubber", 1); private DbClient dbClient; private CoordinatorClient coordinator; public void start() { _executor.scheduleWithFixedDelay(new Runnable() { @Override public void run() { deleteOldEvents(); } }, 1, getConfigProperty(EVENT_CLEAN_INTERVAL_PROPERTY, MINIMUM_PERIOD_MINS), TimeUnit.MINUTES); log.info("Started Actionable Event Scrubber"); } public DbClient getDbClient() { return dbClient; } public void setDbClient(DbClient dbClient) { this.dbClient = dbClient; } public CoordinatorClient getCoordinator() { return coordinator; } public void setCoordinator(CoordinatorClient coordinator) { this.coordinator = coordinator; } private void deleteOldEvents() { log.info("Looking for completed events older than {} minutes", getConfigProperty(EVENT_TTL_MINS_PROPERTY, MINIMUM_PERIOD_MINS)); long eventLifetimeMicroSeconds = getConfigProperty(EVENT_TTL_MINS_PROPERTY, MINIMUM_PERIOD_MINS) * MIN_TO_MICROSECS; long currentTimeMicroseconds = TimeUUIDUtils.getMicrosTimeFromUUID(TimeUUIDUtils.getUniqueTimeUUIDinMicros()); long startTimeMicroSec = currentTimeMicroseconds - eventLifetimeMicroSeconds; Calendar startTimeMarker = Calendar.getInstance(); startTimeMarker.setTimeInMillis(startTimeMicroSec / MINI_TO_MICROSECS); List<URI> ids = dbClient.queryByType(ActionableEvent.class, true); Iterator<ActionableEvent> events = dbClient.queryIterativeObjects(ActionableEvent.class, ids, true); List<ActionableEvent> toBeDeleted = Lists.newArrayList(); while (events.hasNext()) { ActionableEvent event = events.next(); if (event.getCreationTime().after(startTimeMarker)) { continue; } if (event != null && !ActionableEvent.Status.pending.name().equalsIgnoreCase(event.getEventStatus()) && !ActionableEvent.Status.failed.name().equalsIgnoreCase(event.getEventStatus())) { toBeDeleted.add(event); } if (toBeDeleted.size() >= DELETE_BATCH_SIZE) { log.info("Deleting {} Actionable Events", toBeDeleted.size()); dbClient.markForDeletion(toBeDeleted); toBeDeleted.clear(); } } if (!toBeDeleted.isEmpty()) { log.info("Deleting {} Actionable Events", toBeDeleted.size()); dbClient.markForDeletion(toBeDeleted); } log.info("delete completed actionable events successfully"); } private long getConfigProperty(String propertyName, long minimumValue) { String value = coordinator.getPropertyInfo().getProperty(propertyName); if (value != null && StringUtils.isNotBlank(value)) { try { return Math.max(Long.valueOf(value), minimumValue); } catch (Exception e) { log.error("Configuration property " + propertyName + " invalid number, using minimum value of " + minimumValue, e); return minimumValue; } } else { log.error("Configuration property " + propertyName + " not found, using minimum value of " + minimumValue); return minimumValue; } } }
40.425
136
0.693465
ea1c3325d6848fb2d99780b74b8f2275e90b70c3
6,948
package io.unlaunch.engine; import io.unlaunch.UnlaunchFeature; import io.unlaunch.utils.MurmurHash3; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.*; import java.util.concurrent.atomic.AtomicReference; /** * This class contains the logic for feature flag evaluation. * * @author umermansoor * @author jawad */ public class Evaluator { private static final Logger logger = LoggerFactory.getLogger(Evaluator.class); public UnlaunchFeature evaluate(FeatureFlag flag, UnlaunchUser user) { AtomicReference<String> evaluationReasonRef = new AtomicReference<>("UNSET"); // TODO hack, please fix me Variation v = evaluateInternal(flag, user, evaluationReasonRef); return UnlaunchFeature.create(flag.getKey(), v.getKey(), v.getProperties(), evaluationReasonRef.get()); } /** * Match user attribute values with rules one by one in the order they are defined. * The first rule defined has the highest priority and so on. * Returns variation defined for the rule if the user attribute values matches all the conditions in the rule. * Returns default rule variation if user not matches with any rule. * Returns off variation if flag is not active. * * @param flag * @param user * @return */ private Variation evaluateInternal(FeatureFlag flag, UnlaunchUser user, AtomicReference<String> evaluationReasonRef /* hack, remove this */) { if (flag == null) { throw new IllegalArgumentException("unlaunchFlag must not be null"); } if (user == null) { throw new IllegalArgumentException("user must not be null"); } Variation variationToServe; String evaluationReason = ""; if (!flag.isEnabled()) { logger.debug("FLAG_DISABLED, {}, OFF_VARIATION is served to user {}", flag.getKey(), user.getId()); variationToServe = flag.getOffVariation(); evaluationReason = "Default Variation served. Because the flag is disabled."; } else if (!checkDependencies(flag, user)) { logger.info("PREREQUISITE_FAILED for flag {}, OFF_VARIATION is served to user {}", flag.getKey(), user.getId()); variationToServe = flag.getOffVariation(); evaluationReason = "Default Variation served. Because Pre-requisite failed. "; } else if ((variationToServe = getVariationIfUserInAllowList(flag, user)) != null) { logger.info("USER_IN_TARGET_USER for flag {}, VARIATION {} is served to user {}", flag.getKey(), variationToServe, user.getId()); evaluationReason = "Target User rules matched for identity: " + user.getId(); } else { int bucketNumber = getBucket(user.getId(), flag.getKey()); // TODO Extract into its own method for (Rule rule : flag.getRules()) { if (variationToServe == null && !rule.isIsDefault() && rule.matches(user)) { variationToServe = getVariationToServeByRule(rule, bucketNumber); logger.debug( "RULE_MATCHED for flag {}, {} Target Rule is served to user {}", flag.getKey(), variationToServe.getKey(), user.getId() ); evaluationReason = "Targeting Rule (priority #" + rule.getPriority() + ") matched."; break; } } // No variation matched by rule. Use the default rule. if (variationToServe == null) { Rule defaultRule = flag.getDefaultRule(); variationToServe = getVariationToServeByRule(defaultRule, bucketNumber); logger.debug( "RULE_NOT_MATCHED for flag {}, {} Default Rule is served to user {}", flag.getKey(), variationToServe.getKey(), user.getId() ); evaluationReason = "Default Rule served. This is because the flag is Enabled and Target User and " + "Targeting Rules didn't match."; } } if (evaluationReasonRef != null) { evaluationReasonRef.set(evaluationReason); // TODO hack, please fix me. } return variationToServe; } /** * @param featureFlag * @param user * @return */ private boolean checkDependencies(FeatureFlag featureFlag, UnlaunchUser user) { Map<FeatureFlag, Variation> prerequisiteFlags = featureFlag.getPrerequisiteFlags(); if (prerequisiteFlags == null || prerequisiteFlags.isEmpty()) { return true; } for (FeatureFlag prerequisiteFlag : prerequisiteFlags.keySet()) { Variation variation = evaluateInternal(prerequisiteFlag, user, null); if (!variation.getKey().equals(prerequisiteFlags.get(prerequisiteFlag).getKey())) { logger.info("PREREQUISITE_FAILED,{},{}", prerequisiteFlag.getKey(), user.getId()); return false; } } return true; } int getBucket(String userId, String featureId) { if (userId == null || featureId == null) { throw new IllegalArgumentException("userId and featureId must not be null"); } String key = userId + featureId; long hash = getHash(key); return (int) (Math.abs(hash % 100) + 1); } private long getHash(String key) { return MurmurHash3.murmurhash3_x86_32(key, 0, key.length(), 0); } private Variation getVariationIfUserInAllowList(FeatureFlag flag, UnlaunchUser user) { for (Variation variation : flag.getVariations()) { if (variation.getAllowList() != null) { Set<String> allowList = new HashSet<>(Arrays.asList(variation.getAllowList().split(","))); if (allowList.contains(user.getId())) { return variation; } } } return null; } private Variation getVariationToServeByRule(Rule rule, int bucketNumber) { Variation variationToServe; int sum = 0; for (Variation variation : rule.getVariations()) { sum += variation.getRolloutPercentage(); variationToServe = isVariationAvailable(sum, bucketNumber) ? variation : null; if (variationToServe != null) { return variationToServe; } } logger.warn("return null variationToServe. Something went wrong. Rule {}, bucketNumber {}", rule, bucketNumber); return null; } private boolean isVariationAvailable(int rolloutPercent, int bucket) { return bucket <= rolloutPercent; } }
36.1875
124
0.596431
807d6cf121aeebac25b5221fc36ddbfc455a72d0
1,780
package com.huazie.frame.jersey.client.request.impl; import com.huazie.frame.common.slf4j.FleaLogger; import com.huazie.frame.common.slf4j.impl.FleaLoggerProxy; import com.huazie.frame.jersey.client.request.RequestConfig; import com.huazie.frame.jersey.client.request.RequestModeEnum; import com.huazie.frame.jersey.common.data.FleaJerseyRequest; import com.huazie.frame.jersey.common.data.FleaJerseyResponse; import javax.ws.rs.client.Entity; import javax.ws.rs.client.WebTarget; /** * <p> PUT请求 </p> * * @author huazie * @version 1.0.0 * @since 1.0.0 */ public class PutFleaRequest extends FleaRequest { private static final FleaLogger LOGGER = FleaLoggerProxy.getProxyInstance(PutFleaRequest.class); /** * <p> 不带参数的构造方法 </p> * * @since 1.0.0 */ public PutFleaRequest() { } /** * <p> 带参数的构造方法 </p> * * @param config 请求配置 * @since 1.0.0 */ public PutFleaRequest(RequestConfig config) { super(config); } @Override protected void init() { modeEnum = RequestModeEnum.PUT; } @Override protected FleaJerseyResponse request(WebTarget target, FleaJerseyRequest request) throws Exception { Object obj = null; if (LOGGER.isDebugEnabled()) { obj = new Object() {}; LOGGER.debug1(obj, "PUT Request, Start"); } Entity<FleaJerseyRequest> entity = Entity.entity(request, toMediaType()); FleaJerseyResponse response = target.request(toMediaType()).put(entity, FleaJerseyResponse.class); if (LOGGER.isDebugEnabled()) { LOGGER.debug1(obj, "PUT Request, FleaJerseyResponse = {}", response); LOGGER.debug1(obj, "PUT Request, End"); } return response; } }
26.567164
106
0.657865
46627288dbe38f91c16b0efe9a56761ce66255e3
1,797
package com.hui.UnionFindD; /** * @author: shenhaizhilong * @date: 2018/12/2 20:45 * * union by size * */ public class UnionFindII { private int count; private int[] parents; private int[] size; // init public UnionFindII(int capacity) { this.count = capacity; parents = new int[count]; size = new int[count]; for (int i = 0; i < capacity; i++) { parents[i] = i; size[i] = 1; } } // find it's parent public int find(int i) { while (parents[i] != i) { parents[i] = parents[parents[i]]; i = parents[i]; } return parents[i]; } // union by size public boolean union(int p, int q) { int pp = find(p); int pq = find(q); if(pp == pq)return false; if(size[pp] < size[pq]) { parents[pp] = pq; size[pq] += size[pp]; }else { parents[pq] = pp; size[pp] += size[pq]; } return true; } // judge whether p and q is in the same set. public boolean isConnected(int p, int q) { int pp = find(p); int pq = find(q); return pp == pq; } /** * * @return the count of set */ public int getCount() { return this.count; } /** * * @param i * @return the size of set which i belong to */ public int getSize(int i) { return size[find(i)]; } // re -init public void clear() { for (int i = 0; i < count; i++) { parents[i] = i; size[i] = 1; } } }
19.117021
50
0.421814
364966acffda6144d00616ea2e2a61ee80b457ca
1,112
package ru.matevosyan.start; import java.util.ArrayList; /** * Class StubInput implements interface Input and created for testing the programs system input. * Created on 07.12.2016. * @since 1.0 * @version 1.0 * @author Matevosyan Vardan */ public class StubInput implements Input { /** * Instance variable answer for using to save input parameters for testing StartUI class. */ private String[] answers; /** * Element position in an instance variable answer. */ private int position = 0; /** * Constructor for StubInput. * @param answers for imitation user answer */ public StubInput(String[] answers) { this.answers = answers; } /** * Override interface Inputs method ask. * @param question use for showing messages to user * @return imitation user answers */ @Override public String ask(String question) { return answers[position++]; } @Override public int ask(String question, ArrayList<Integer> range) { return Integer.valueOf(answers[position++]); } }
20.981132
96
0.646583
b4a814549bc740a5d7854cce0caa8313f153b849
858
package de.softknk.model.util; import de.softknk.main.AppSettings; import de.softknk.main.SoftknkioApp; public interface MapPoint { static double randomX(double radius) { if (SoftknkioApp.matchfield == null) { return -((AppSettings.MAP_WIDTH - AppSettings.WINDOW_WIDTH) / 2) + Math.random() * (AppSettings.MAP_WIDTH - 2 * radius); } else { return SoftknkioApp.matchfield.getX() + Math.random() * (AppSettings.MAP_WIDTH - radius); } } static double randomY(double radius) { if (SoftknkioApp.matchfield == null) { return -((AppSettings.MAP_HEIGHT - AppSettings.WINDOW_HEIGHT) / 2) + Math.random() * (AppSettings.MAP_HEIGHT - radius * 2); } else { return SoftknkioApp.matchfield.getY() + Math.random() * (AppSettings.MAP_HEIGHT - radius); } } }
35.75
135
0.63986
0a3ceae7f6ce35e58eb0afc35c98aeb84536d42d
1,337
/* * 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.tika.pipes.fetcher; import java.io.IOException; import java.io.InputStream; import org.apache.tika.exception.TikaException; import org.apache.tika.metadata.Metadata; /** * This class extracts a range of bytes from a given fetch key. */ public interface RangeFetcher extends Fetcher { //At some point, Tika 3.x?, we may want to add optional ranges to the fetchKey? InputStream fetch(String fetchKey, long startOffset, long endOffset, Metadata metadata) throws TikaException, IOException; }
38.2
91
0.756918
d7dec9f681261b2a350cd1c15a751e718cbb06ec
484
package org.panda.controller; import com.alibaba.druid.stat.DruidStatManagerFacade; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RestController; @RestController public class TestControllrt { @GetMapping("/hi") public String getHi() { return "hi"; } @GetMapping("/druid/stat") public Object druidStat(){ return DruidStatManagerFacade.getInstance().getDataSourceStatDataList(); } }
25.473684
80
0.739669
76703f29b3dfe4540e71794e30e489c7d5db9c39
2,145
/* * 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 com.alipay.sofa.registry.server.session.converter.pb; import com.alipay.sofa.registry.common.model.client.pb.RegisterResponsePb; import com.alipay.sofa.registry.core.model.RegisterResponse; import org.junit.Assert; import org.junit.Test; public class RegisterResponseConvertorTest { @Test public void test() { Assert.assertNull(RegisterResponseConvertor.convert2Pb(null)); Assert.assertNull(RegisterResponseConvertor.convert2Java(null)); RegisterResponse registerJava = new RegisterResponse(); registerJava.setVersion(100); registerJava.setRegistId("testRegisterId"); registerJava.setMessage("testMsg"); registerJava.setSuccess(true); registerJava.setRefused(true); RegisterResponsePb pb = RegisterResponseConvertor.convert2Pb(registerJava); RegisterResponse convertJava = RegisterResponseConvertor.convert2Java(pb); Assert.assertEquals(registerJava.getVersion(), convertJava.getVersion()); Assert.assertEquals(registerJava.getMessage(), convertJava.getMessage()); Assert.assertEquals(registerJava.isSuccess(), convertJava.isSuccess()); Assert.assertEquals(registerJava.getRegistId(), convertJava.getRegistId()); Assert.assertEquals(registerJava.isRefused(), convertJava.isRefused()); Assert.assertEquals(registerJava.toString(), convertJava.toString()); } }
43.77551
79
0.77669
554b75a3dc5399e27205a1aeb27c1efc179cb7cd
21,639
/* * Licensed to Elasticsearch under one or more contributor * license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright * ownership. Elasticsearch licenses this file to you under * the Apache License, Version 2.0 (the "License"); you may * not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.elasticsearch.gateway; import org.elasticsearch.action.admin.indices.flush.SyncedFlushResponse; import org.elasticsearch.action.admin.indices.stats.ShardStats; import org.elasticsearch.cluster.metadata.IndexMetaData; import org.elasticsearch.cluster.node.DiscoveryNode; import org.elasticsearch.cluster.routing.UnassignedInfo; import org.elasticsearch.cluster.service.ClusterService; import org.elasticsearch.common.Priority; import org.elasticsearch.common.breaker.CircuitBreaker; import org.elasticsearch.common.breaker.CircuitBreakingException; import org.elasticsearch.common.settings.Settings; import org.elasticsearch.index.Index; import org.elasticsearch.index.IndexService; import org.elasticsearch.index.IndexSettings; import org.elasticsearch.index.seqno.ReplicationTracker; import org.elasticsearch.index.seqno.RetentionLease; import org.elasticsearch.index.shard.IndexShard; import org.elasticsearch.indices.IndicesService; import org.elasticsearch.indices.recovery.PeerRecoveryTargetService; import org.elasticsearch.indices.recovery.RecoveryState; import org.elasticsearch.plugins.Plugin; import org.elasticsearch.test.ESIntegTestCase; import org.elasticsearch.test.InternalSettingsPlugin; import org.elasticsearch.test.InternalTestCluster; import org.elasticsearch.test.transport.MockTransportService; import org.elasticsearch.transport.TransportService; import java.util.Arrays; import java.util.Collection; import java.util.Set; import java.util.concurrent.CountDownLatch; import java.util.stream.Collectors; import java.util.stream.IntStream; import static org.elasticsearch.test.hamcrest.ElasticsearchAssertions.assertAcked; import static org.hamcrest.Matchers.allOf; import static org.hamcrest.Matchers.empty; import static org.hamcrest.Matchers.equalTo; import static org.hamcrest.Matchers.hasItem; import static org.hamcrest.Matchers.hasSize; import static org.hamcrest.Matchers.not; @ESIntegTestCase.ClusterScope(scope = ESIntegTestCase.Scope.TEST, numDataNodes = 0) public class ReplicaShardAllocatorIT extends ESIntegTestCase { @Override protected Collection<Class<? extends Plugin>> nodePlugins() { return Arrays.asList(MockTransportService.TestPlugin.class, InternalSettingsPlugin.class); } /** * Verify that if we found a new copy where it can perform a no-op recovery, * then we will cancel the current recovery and allocate replica to the new copy. */ public void testPreferCopyCanPerformNoopRecovery() throws Exception { String indexName = "test"; String nodeWithPrimary = internalCluster().startNode(); assertAcked( client().admin().indices().prepareCreate(indexName) .setSettings(Settings.builder() .put(IndexSettings.INDEX_SOFT_DELETES_SETTING.getKey(), true) .put(IndexMetaData.SETTING_NUMBER_OF_SHARDS, 1) .put(IndexMetaData.SETTING_NUMBER_OF_REPLICAS, 1) .put(IndexSettings.FILE_BASED_RECOVERY_THRESHOLD_SETTING.getKey(), 1.0f) .put(IndexService.RETENTION_LEASE_SYNC_INTERVAL_SETTING.getKey(), "100ms") .put(IndexService.GLOBAL_CHECKPOINT_SYNC_INTERVAL_SETTING.getKey(), "100ms") .put(UnassignedInfo.INDEX_DELAYED_NODE_LEFT_TIMEOUT_SETTING.getKey(), "1ms"))); String nodeWithReplica = internalCluster().startDataOnlyNode(); Settings nodeWithReplicaSettings = internalCluster().dataPathSettings(nodeWithReplica); ensureGreen(indexName); indexRandom(randomBoolean(), randomBoolean(), randomBoolean(), IntStream.range(0, between(100, 500)) .mapToObj(n -> client().prepareIndex(indexName).setSource("f", "v")).collect(Collectors.toList())); client().admin().indices().prepareFlush(indexName).get(); if (randomBoolean()) { indexRandom(randomBoolean(), false, randomBoolean(), IntStream.range(0, between(0, 80)) .mapToObj(n -> client().prepareIndex(indexName).setSource("f", "v")).collect(Collectors.toList())); } ensureActivePeerRecoveryRetentionLeasesAdvanced(indexName); internalCluster().stopRandomNode(InternalTestCluster.nameFilter(nodeWithReplica)); if (randomBoolean()) { client().admin().indices().prepareForceMerge(indexName).setFlush(true).get(); } CountDownLatch blockRecovery = new CountDownLatch(1); CountDownLatch recoveryStarted = new CountDownLatch(1); MockTransportService transportServiceOnPrimary = (MockTransportService) internalCluster().getInstance(TransportService.class, nodeWithPrimary); transportServiceOnPrimary.addSendBehavior((connection, requestId, action, request, options) -> { if (PeerRecoveryTargetService.Actions.FILES_INFO.equals(action)) { recoveryStarted.countDown(); try { blockRecovery.await(); } catch (InterruptedException e) { Thread.currentThread().interrupt(); } } connection.sendRequest(requestId, action, request, options); }); internalCluster().startDataOnlyNode(); recoveryStarted.await(); nodeWithReplica = internalCluster().startDataOnlyNode(nodeWithReplicaSettings); // AllocationService only calls GatewayAllocator if there're unassigned shards assertAcked(client().admin().indices().prepareCreate("dummy-index").setWaitForActiveShards(0)); ensureGreen(indexName); assertThat(internalCluster().nodesInclude(indexName), hasItem(nodeWithReplica)); assertNoOpRecoveries(indexName); blockRecovery.countDown(); transportServiceOnPrimary.clearAllRules(); } /** * Ensure that we fetch the latest shard store from the primary when a new node joins so we won't cancel the current recovery * for the copy on the newly joined node unless we can perform a noop recovery with that node. */ public void testRecentPrimaryInformation() throws Exception { String indexName = "test"; String nodeWithPrimary = internalCluster().startNode(); assertAcked( client().admin().indices().prepareCreate(indexName) .setSettings(Settings.builder() .put(IndexMetaData.SETTING_NUMBER_OF_SHARDS, 1) .put(IndexMetaData.SETTING_NUMBER_OF_REPLICAS, 1) .put(IndexSettings.FILE_BASED_RECOVERY_THRESHOLD_SETTING.getKey(), 0.1f) .put(IndexService.GLOBAL_CHECKPOINT_SYNC_INTERVAL_SETTING.getKey(), "100ms") .put(IndexService.RETENTION_LEASE_SYNC_INTERVAL_SETTING.getKey(), "100ms") .put(UnassignedInfo.INDEX_DELAYED_NODE_LEFT_TIMEOUT_SETTING.getKey(), "1ms"))); String nodeWithReplica = internalCluster().startDataOnlyNode(); DiscoveryNode discoNodeWithReplica = internalCluster().getInstance(ClusterService.class, nodeWithReplica).localNode(); Settings nodeWithReplicaSettings = internalCluster().dataPathSettings(nodeWithReplica); ensureGreen(indexName); indexRandom(randomBoolean(), false, randomBoolean(), IntStream.range(0, between(10, 100)) .mapToObj(n -> client().prepareIndex(indexName).setSource("f", "v")).collect(Collectors.toList())); assertBusy(() -> { SyncedFlushResponse syncedFlushResponse = client().admin().indices().prepareSyncedFlush(indexName).get(); assertThat(syncedFlushResponse.successfulShards(), equalTo(2)); }); internalCluster().stopRandomNode(InternalTestCluster.nameFilter(nodeWithReplica)); if (randomBoolean()) { indexRandom(randomBoolean(), false, randomBoolean(), IntStream.range(0, between(10, 100)) .mapToObj(n -> client().prepareIndex(indexName).setSource("f", "v")).collect(Collectors.toList())); } CountDownLatch blockRecovery = new CountDownLatch(1); CountDownLatch recoveryStarted = new CountDownLatch(1); MockTransportService transportServiceOnPrimary = (MockTransportService) internalCluster().getInstance(TransportService.class, nodeWithPrimary); transportServiceOnPrimary.addSendBehavior((connection, requestId, action, request, options) -> { if (PeerRecoveryTargetService.Actions.FILES_INFO.equals(action)) { recoveryStarted.countDown(); try { blockRecovery.await(); } catch (InterruptedException e) { Thread.currentThread().interrupt(); } } connection.sendRequest(requestId, action, request, options); }); String newNode = internalCluster().startDataOnlyNode(); recoveryStarted.await(); // Index more documents and flush to destroy sync_id and remove the retention lease (as file_based_recovery_threshold reached). indexRandom(randomBoolean(), randomBoolean(), randomBoolean(), IntStream.range(0, between(50, 200)) .mapToObj(n -> client().prepareIndex(indexName).setSource("f", "v")).collect(Collectors.toList())); client().admin().indices().prepareFlush(indexName).get(); assertBusy(() -> { for (ShardStats shardStats : client().admin().indices().prepareStats(indexName).get().getShards()) { for (RetentionLease lease : shardStats.getRetentionLeaseStats().retentionLeases().leases()) { assertThat(lease.id(), not(equalTo(ReplicationTracker.getPeerRecoveryRetentionLeaseId(discoNodeWithReplica.getId())))); } } }); // AllocationService only calls GatewayAllocator if there are unassigned shards assertAcked(client().admin().indices().prepareCreate("dummy-index").setWaitForActiveShards(0) .setSettings(Settings.builder().put("index.routing.allocation.require.attr", "not-found"))); internalCluster().startDataOnlyNode(nodeWithReplicaSettings); // need to wait for events to ensure the reroute has happened since we perform it async when a new node joins. client().admin().cluster().prepareHealth(indexName).setWaitForYellowStatus().setWaitForEvents(Priority.LANGUID).get(); blockRecovery.countDown(); ensureGreen(indexName); assertThat(internalCluster().nodesInclude(indexName), hasItem(newNode)); for (RecoveryState recovery : client().admin().indices().prepareRecoveries(indexName).get().shardRecoveryStates().get(indexName)) { if (recovery.getPrimary() == false) { assertThat(recovery.getIndex().fileDetails(), not(empty())); } } transportServiceOnPrimary.clearAllRules(); } public void testFullClusterRestartPerformNoopRecovery() throws Exception { int numOfReplicas = randomIntBetween(1, 2); internalCluster().ensureAtLeastNumDataNodes(numOfReplicas + 2); String indexName = "test"; assertAcked( client().admin().indices().prepareCreate(indexName) .setSettings(Settings.builder() .put(IndexSettings.INDEX_SOFT_DELETES_SETTING.getKey(), true) .put(IndexMetaData.SETTING_NUMBER_OF_SHARDS, 1) .put(IndexSettings.INDEX_TRANSLOG_FLUSH_THRESHOLD_SIZE_SETTING.getKey(), randomIntBetween(10, 100) + "kb") .put(IndexMetaData.SETTING_NUMBER_OF_REPLICAS, numOfReplicas) .put(IndexSettings.FILE_BASED_RECOVERY_THRESHOLD_SETTING.getKey(), 0.5) .put(IndexService.GLOBAL_CHECKPOINT_SYNC_INTERVAL_SETTING.getKey(), "100ms") .put(IndexService.RETENTION_LEASE_SYNC_INTERVAL_SETTING.getKey(), "100ms"))); ensureGreen(indexName); indexRandom(randomBoolean(), randomBoolean(), randomBoolean(), IntStream.range(0, between(200, 500)) .mapToObj(n -> client().prepareIndex(indexName).setSource("f", "v")).collect(Collectors.toList())); client().admin().indices().prepareFlush(indexName).get(); indexRandom(randomBoolean(), false, randomBoolean(), IntStream.range(0, between(0, 80)) .mapToObj(n -> client().prepareIndex(indexName).setSource("f", "v")).collect(Collectors.toList())); if (randomBoolean()) { client().admin().indices().prepareForceMerge(indexName).get(); } ensureActivePeerRecoveryRetentionLeasesAdvanced(indexName); if (randomBoolean()) { assertAcked(client().admin().indices().prepareClose(indexName)); } assertAcked(client().admin().cluster().prepareUpdateSettings() .setPersistentSettings(Settings.builder().put("cluster.routing.allocation.enable", "primaries").build())); internalCluster().fullRestart(); ensureYellow(indexName); assertAcked(client().admin().cluster().prepareUpdateSettings() .setPersistentSettings(Settings.builder().putNull("cluster.routing.allocation.enable").build())); ensureGreen(indexName); assertNoOpRecoveries(indexName); } public void testPreferCopyWithHighestMatchingOperations() throws Exception { String indexName = "test"; internalCluster().startMasterOnlyNode(); internalCluster().startDataOnlyNodes(3); assertAcked( client().admin().indices().prepareCreate(indexName) .setSettings(Settings.builder() .put(IndexSettings.INDEX_SOFT_DELETES_SETTING.getKey(), true) .put(IndexMetaData.SETTING_NUMBER_OF_SHARDS, 1) .put(IndexSettings.INDEX_TRANSLOG_FLUSH_THRESHOLD_SIZE_SETTING.getKey(), randomIntBetween(10, 100) + "kb") .put(IndexMetaData.SETTING_NUMBER_OF_REPLICAS, 1) .put(IndexSettings.FILE_BASED_RECOVERY_THRESHOLD_SETTING.getKey(), 3.0) .put(IndexService.GLOBAL_CHECKPOINT_SYNC_INTERVAL_SETTING.getKey(), "100ms") .put(UnassignedInfo.INDEX_DELAYED_NODE_LEFT_TIMEOUT_SETTING.getKey(), "0ms") .put(IndexService.RETENTION_LEASE_SYNC_INTERVAL_SETTING.getKey(), "100ms"))); ensureGreen(indexName); indexRandom(randomBoolean(), randomBoolean(), randomBoolean(), IntStream.range(0, between(200, 500)) .mapToObj(n -> client().prepareIndex(indexName).setSource("f", "v")).collect(Collectors.toList())); client().admin().indices().prepareFlush(indexName).get(); String nodeWithLowerMatching = randomFrom(internalCluster().nodesInclude(indexName)); Settings nodeWithLowerMatchingSettings = internalCluster().dataPathSettings(nodeWithLowerMatching); internalCluster().stopRandomNode(InternalTestCluster.nameFilter(nodeWithLowerMatching)); ensureGreen(indexName); indexRandom(randomBoolean(), false, randomBoolean(), IntStream.range(0, between(1, 100)) .mapToObj(n -> client().prepareIndex(indexName).setSource("f", "v")).collect(Collectors.toList())); ensureActivePeerRecoveryRetentionLeasesAdvanced(indexName); String nodeWithHigherMatching = randomFrom(internalCluster().nodesInclude(indexName)); Settings nodeWithHigherMatchingSettings = internalCluster().dataPathSettings(nodeWithHigherMatching); internalCluster().stopRandomNode(InternalTestCluster.nameFilter(nodeWithHigherMatching)); indexRandom(randomBoolean(), false, randomBoolean(), IntStream.range(0, between(0, 100)) .mapToObj(n -> client().prepareIndex(indexName).setSource("f", "v")).collect(Collectors.toList())); assertAcked(client().admin().cluster().prepareUpdateSettings() .setPersistentSettings(Settings.builder().put("cluster.routing.allocation.enable", "primaries").build())); nodeWithLowerMatching = internalCluster().startNode(nodeWithLowerMatchingSettings); nodeWithHigherMatching = internalCluster().startNode(nodeWithHigherMatchingSettings); assertAcked(client().admin().cluster().prepareUpdateSettings() .setPersistentSettings(Settings.builder().putNull("cluster.routing.allocation.enable").build())); ensureGreen(indexName); assertThat(internalCluster().nodesInclude(indexName), allOf(hasItem(nodeWithHigherMatching), not(hasItem(nodeWithLowerMatching)))); } /** * Make sure that we do not repeatedly cancel an ongoing recovery for a noop copy on a broken node. */ public void testDoNotCancelRecoveryForBrokenNode() throws Exception { internalCluster().startMasterOnlyNode(); String nodeWithPrimary = internalCluster().startDataOnlyNode(); String indexName = "test"; assertAcked(client().admin().indices().prepareCreate(indexName).setSettings(Settings.builder() .put(IndexMetaData.SETTING_NUMBER_OF_SHARDS, 1).put(IndexMetaData.SETTING_NUMBER_OF_REPLICAS, 0) .put(IndexService.GLOBAL_CHECKPOINT_SYNC_INTERVAL_SETTING.getKey(), "100ms") .put(IndexService.RETENTION_LEASE_SYNC_INTERVAL_SETTING.getKey(), "100ms"))); indexRandom(randomBoolean(), randomBoolean(), randomBoolean(), IntStream.range(0, between(200, 500)) .mapToObj(n -> client().prepareIndex(indexName).setSource("f", "v")).collect(Collectors.toList())); client().admin().indices().prepareFlush(indexName).get(); String brokenNode = internalCluster().startDataOnlyNode(); MockTransportService transportService = (MockTransportService) internalCluster().getInstance(TransportService.class, nodeWithPrimary); CountDownLatch newNodeStarted = new CountDownLatch(1); transportService.addSendBehavior((connection, requestId, action, request, options) -> { if (action.equals(PeerRecoveryTargetService.Actions.TRANSLOG_OPS)) { if (brokenNode.equals(connection.getNode().getName())) { try { newNodeStarted.await(); } catch (InterruptedException e) { throw new AssertionError(e); } throw new CircuitBreakingException("not enough memory for indexing", 100, 50, CircuitBreaker.Durability.TRANSIENT); } } connection.sendRequest(requestId, action, request, options); }); assertAcked(client().admin().indices().prepareUpdateSettings(indexName) .setSettings(Settings.builder().put(IndexMetaData.SETTING_NUMBER_OF_REPLICAS, 1))); internalCluster().startDataOnlyNode(); newNodeStarted.countDown(); ensureGreen(indexName); transportService.clearAllRules(); } private void ensureActivePeerRecoveryRetentionLeasesAdvanced(String indexName) throws Exception { assertBusy(() -> { Index index = resolveIndex(indexName); Set<String> activeRetentionLeaseIds = clusterService().state().routingTable().index(index).shard(0).shards().stream() .map(shardRouting -> ReplicationTracker.getPeerRecoveryRetentionLeaseId(shardRouting.currentNodeId())) .collect(Collectors.toSet()); for (String node : internalCluster().nodesInclude(indexName)) { IndexService indexService = internalCluster().getInstance(IndicesService.class, node).indexService(index); if (indexService != null) { for (IndexShard shard : indexService) { assertThat(shard.getLastSyncedGlobalCheckpoint(), equalTo(shard.seqNoStats().getMaxSeqNo())); Set<RetentionLease> activeRetentionLeases = shard.getPeerRecoveryRetentionLeases().stream() .filter(lease -> activeRetentionLeaseIds.contains(lease.id())).collect(Collectors.toSet()); assertThat(activeRetentionLeases, hasSize(activeRetentionLeaseIds.size())); for (RetentionLease lease : activeRetentionLeases) { assertThat(lease.retainingSequenceNumber(), equalTo(shard.getLastSyncedGlobalCheckpoint() + 1)); } } } } }); } private void assertNoOpRecoveries(String indexName) { for (RecoveryState recovery : client().admin().indices().prepareRecoveries(indexName).get().shardRecoveryStates().get(indexName)) { if (recovery.getPrimary() == false) { assertThat(recovery.getIndex().fileDetails(), empty()); assertThat(recovery.getTranslog().totalLocal(), equalTo(recovery.getTranslog().totalOperations())); } } } }
60.444134
139
0.687278
6bdf5787b6992406e128addf7cc8d95b44871823
527
package com.fastcampus.mobility.repository; import com.fastcampus.mobility.dto.VehicleDto; import com.fastcampus.mobility.dto.search.VehicleSearchDto; import java.util.List; import java.util.Optional; import org.springframework.data.domain.Page; import org.springframework.data.domain.Pageable; public interface VehicleRepositoryCustom { Page<VehicleDto> findBySearchCondition(VehicleSearchDto vehicleSearchDto, Pageable pageable); List<VehicleDto> findByBulkSearchCondition(VehicleSearchDto vehicleSearchDto); }
31
80
0.83871
c98d6f9473debe8c84994c9d4cd8b114a8cca5e0
1,697
/* * Copyright (c) 2004, PostgreSQL Global Development Group * See the LICENSE file in the project root for more information. */ // Copyright (c) 2004, Open Cloud Limited. package com.amazon.redshift.core.v3; import com.amazon.redshift.core.ResultCursor; import com.amazon.redshift.core.Utils; import java.lang.ref.PhantomReference; /** * V3 ResultCursor implementation in terms of backend Portals. This holds the state of a single * Portal. We use a PhantomReference managed by our caller to handle resource cleanup. * * @author Oliver Jowett (oliver@opencloud.com) */ class Portal implements ResultCursor { Portal(SimpleQuery query, String portalName) { this.query = query; this.portalName = portalName; this.encodedName = Utils.encodeUTF8(portalName); } public void close() { if (cleanupRef != null) { cleanupRef.clear(); cleanupRef.enqueue(); cleanupRef = null; } } String getPortalName() { return portalName; } byte[] getEncodedPortalName() { return encodedName; } SimpleQuery getQuery() { return query; } void setCleanupRef(PhantomReference<?> cleanupRef) { this.cleanupRef = cleanupRef; } public String toString() { return portalName; } // Holding on to a reference to the generating query has // the nice side-effect that while this Portal is referenced, // so is the SimpleQuery, so the underlying statement won't // be closed while the portal is open (the backend closes // all open portals when the statement is closed) private final SimpleQuery query; private final String portalName; private final byte[] encodedName; private PhantomReference<?> cleanupRef; }
25.712121
95
0.71538
6deed0009555095c71118c33d444100005a0b03e
6,888
package exper; import hbaseusage.CooccurenceTableDriver; import java.io.BufferedWriter; import java.io.File; import java.io.FileWriter; import java.io.IOException; import java.util.ArrayList; import java.util.HashSet; import java.util.List; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.hbase.client.HTable; import org.apache.hadoop.hbase.client.Put; import org.apache.hadoop.hbase.io.ImmutableBytesWritable; import org.apache.hadoop.hbase.mapreduce.TableReducer; import org.apache.hadoop.hbase.util.Bytes; import org.apache.hadoop.io.IntWritable; import org.apache.hadoop.io.LongWritable; import org.apache.hadoop.io.MapWritable; import org.apache.hadoop.io.Text; import org.apache.hadoop.io.Writable; import org.apache.hadoop.mapreduce.Mapper; import org.apache.hadoop.mapreduce.Reducer; import org.apache.hadoop.mapreduce.Mapper.Context; public class CooccurrenceDriver { public static class CooccurrenceMapper extends Mapper<LongWritable, Text, Text, MapWritable>{ @Override public void map(LongWritable key, Text value, Context context) throws IOException, InterruptedException { //File file = new File("/home/cloudera/Documents/5.txt"); //FileWriter fw = new FileWriter(file.getAbsoluteFile(), true); //BufferedWriter bw = new BufferedWriter(fw); String line = value.toString(); String [] array = line.split("[ \n\t\r]+"); //bw.write("array_size = " + array.length); //for(int i = 0; i < array.length; ++i) // bw.write(" " + array[i]); //bw.write("\n--------"); //bw.close(); List<String> words = new ArrayList<String>(); // for(int i = 0; i < array.length; i = i + 2) { // array[i] = normalize(array[i]); // } for(int i = 1; i < array.length; ) { if(i + 2 < array.length && (array[i].equals("R") && array[i+2].equals("A") || array[i].equals("A") && array[i+2].equals("N") || array[i].equals("V") && array[i+2].equals("T")) ) { words.add(array[i-1] + " " + array[i+1]); i = i + 4; } else { words.add(array[i-1]); i = i + 2; } } //find cooccurences in tweet if(words.size() > 0) { //String keyWord = words.get(0); int window_size = GeneralDriver.getWindowSize(); //Map<String, Map<String, Integer>> bigMap = new HashMap<String, Map<String,Integer>>(); //for all words HashSet<String> wordset = new HashSet<String>(words); for(String keyword : wordset) { ArrayList<Integer> indList = indexOfAll(keyword, words); //Map<String, Integer> mp = new HashMap<String, Integer>(); MapWritable mp = new MapWritable(); for(int ind = 0; ind < indList.size(); ++ind) { //working inside left word window for(int k = 1; k <= window_size; ++k) { int pos = indList.get(ind) - k; if(pos >= 0 && pos < words.size()) { IntWritable c = (IntWritable)mp.get(words.get(pos)); mp.put(new Text(words.get(pos)), c == null ? new IntWritable(1) : new IntWritable(c.get() + 1)); } } //working inside write word position for(int k = 1; k <= window_size; ++k) { int pos = indList.get(ind) + k; if(pos >= 0 && pos < words.size()) { IntWritable c = (IntWritable)mp.get(words.get(pos)); mp.put(new Text(words.get(pos)), c == null ? new IntWritable(1) : new IntWritable(c.get() + 1)); } } } ////write to context //bigMap.put(keyword, mp); context.write(new Text(keyword), mp); } } //bw.close(); } //delete symbols which occur more than twice together // private String normalize(String str) { // String norm_str = (str.length() > 2) ? str.substring(0, 2) : str; // for(int i = 2; i < str.length(); ++i) { // if(str.charAt(i) != str.charAt(i-1) || str.charAt(i) != str.charAt(i-2)) { // norm_str = norm_str.concat(((Character)str.charAt(i)).toString()); // } // } // return norm_str; // } private ArrayList<Integer> indexOfAll(String obj, List<String> list){ ArrayList<Integer> indexList = new ArrayList<Integer>(); for (int i = 0; i < list.size(); i++) if(obj.equals(list.get(i))) indexList.add(i); return indexList; } } public static class CooccurrenceReducer extends TableReducer<Text, MapWritable, ImmutableBytesWritable> { public void reduce(Text key, Iterable<MapWritable> values, Context context) throws IOException, InterruptedException { MapWritable resMap = null; for(MapWritable curMap : values) { if(resMap == null) { resMap = new MapWritable(curMap); continue; } for(Writable prim_key : curMap.keySet()) { if(resMap.containsKey(prim_key)) { int num1 = ((IntWritable)resMap.get(prim_key)).get(); int num2 = ((IntWritable)curMap.get(prim_key)).get(); resMap.put(prim_key, new IntWritable(num1 + num2)); } else resMap.put(prim_key, curMap.get(prim_key)); } } for(Writable sec_key: resMap.keySet()) { //System.out.println(key.toString() + " " + sec_key.toString()); //context.write(key, new Text(sec_key.toString() + " " + resMap.get(sec_key).toString())); //addRecord(CooccurenceTableDriver.getHBaseConf(), "CooccurenceTable", key.toString(), "cooccurrence", sec_key.toString(), resMap.get(sec_key).toString()); //addRecord(CooccurenceTableDriver.getHBaseConf(), "CooccurenceTable", key.toString(), "cooccurrence", sec_key.toString(), resMap.get(sec_key).toString()); Put put = new Put(Bytes.toBytes(key.toString())); put.add(Bytes.toBytes("cooccurrence"), Bytes.toBytes(sec_key.toString()), Bytes.toBytes(resMap.get(sec_key).toString())); System.out.println("CooccurrenceTable_cooccurrence: key = " + key.toString() + " sec_key = " + sec_key.toString() + " value = " + resMap.get(sec_key).toString()); context.write(null, put); } //for(MapWritable mp : values) { // for(Writable t : mp.keySet()) // context.write(key, new Text(t.toString() + " " + mp.get(t).toString())); //} } // public void addRecord(Configuration conf, String tableName, String rowKey, // String family, String qualifier, String value) { // try { // HTable table = new HTable(conf, tableName); // Put put = new Put(Bytes.toBytes(rowKey)); // put.add(Bytes.toBytes(family), Bytes.toBytes(qualifier), // Bytes.toBytes(value)); // table.put(put); // System.out.println("insert record " + rowKey + " to table " // + tableName + " ok."); // table.close(); // } catch (IOException e) { // e.printStackTrace(); // } // } } }
34.44
166
0.607578
95f6459c6824b472ee85de99e45f36d3a0b2c90c
1,660
/** * Copyright 2016 StreamSets Inc. * * Licensed under 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 com.streamsets.pipeline.config; import com.streamsets.pipeline.api.Label; import com.streamsets.pipeline.lib.hashing.HashingUtil; public enum ChecksumAlgorithm implements Label { //Adler32, Siphash24, CRC and CRC32 are not supported for guavas < 14.0 (There are some stages which use guavas 11) MD5(HashingUtil.HashType.MD5), SHA1(HashingUtil.HashType.SHA1), SHA256(HashingUtil.HashType.SHA256), SHA512(HashingUtil.HashType.SHA512), MURMUR3_32(HashingUtil.HashType.MURMUR3_32), MURMUR3_128(HashingUtil.HashType.MURMUR3_128), ; HashingUtil.HashType hashType; ChecksumAlgorithm(HashingUtil.HashType hashType) { this.hashType = hashType; } public String getLabel() { return hashType.name(); } public HashingUtil.HashType getHashType() { return this.hashType; } }
33.2
117
0.759036
de5dffbe17fc46468fc44038a3146b8fcf30a8a1
709
package sooth; @SuppressWarnings("ALL") public class ExpressionTest { static ExpressionTest mainTest; ExpressionTest instanceTest; int field = 5; public static void main(String[] args) { int five = 5; ExpressionTest test = new ExpressionTest(); mainTest = test; mainTest.mk(); int ten = five + five; // break here } static int[] arrayOfIntegers; public void mk() { instanceTest = this; int local = 8; int ten = local + 6; // break here ExpressionTest asLocal = this; } public static final class StaticClass { static int Hello = 5; static String Text = "Text Here"; } } @SuppressWarnings("ALL") class StaticClass { static int a = 5; }
18.657895
47
0.651622
db342a6cdbf0b549686590ea9d2e5f5e3b42823d
1,240
package dev.jshfx.base.jshell; import org.fxmisc.richtext.CodeArea; import dev.jshfx.fxmisc.richtext.CompletionItem; public class CommandCompletionItem extends CompletionItem { private CodeArea codeArea; private int anchor; private String continuation; private String commandName; private String name; private boolean replace; public CommandCompletionItem(CodeArea codeArea, int anchor, String continuation, String commandName, String name, boolean replace) { this.codeArea = codeArea; this.anchor = anchor; this.continuation = continuation; this.commandName = commandName; this.name = name; this.replace = replace; } public String getCommandName() { return commandName; } public String getName() { return name; } public String getDocKey() { return commandName + "." + name; } @Override public void complete() { if (replace) { codeArea.replaceText(anchor, codeArea.getCaretPosition(), continuation); } else { codeArea.insertText(anchor, continuation); } } @Override public String toString() { return name; } }
23.846154
117
0.641935
d5e0a4ea1d30adef7f4d77d7df5903605e684ee9
3,095
package io.github.macfja.citiesborder; import com.sampullara.cli.Args; import com.sampullara.cli.Argument; import java.io.File; import java.io.IOException; import java.util.Arrays; import java.util.logging.Level; import java.util.logging.Logger; /** * Class Main. * The CLI entry point * * @author MacFJA */ public class Main { /** * The OSM PBF raw file path */ @Argument(alias = "i") public String input; /** * The CitiesBorder file path */ @Argument(alias = "o") public String output; /** * The level of administration relation to keep */ @Argument(alias = "l") public Integer level = 8; /** * The city name to search */ @Argument(alias = "s") public String search; /** * If specified, the generation of CitiesBorder file will be skip */ @Argument(value = "search-only", alias = "S") public boolean searchOnly = false; /** * The path where the result of the Osmosis will be put */ protected String tmpPath; /** * The application logger */ protected Logger logger = Logger.getLogger(Main.class.getName()); public static void main(String[] args) { Main app = new Main(); if (!Worker.validateDependency("com.sampullara.cli.Args")) { app.logger.log(Level.SEVERE, "There are missing dependencies for the application to run."); System.exit(1); return; } app.run(args); } /** * Constructor. */ public Main() { tmpPath = System.getProperty("java.io.tmpdir") + File.separator + "io.github.macfja.cities-border" + File.separator + "osmosis.xml"; } /** * Run all action according to the args * @param args List of cli arguments */ public void run(String[] args) { Args.parseOrExit(this, args); if (input != null) { logger.log(Level.INFO, "Start Osmosis transformation"); try { Worker.runOsmosis(tmpPath, input, level); } catch (RuntimeException e) { logger.log(Level.SEVERE, e.getMessage()); logger.log(Level.INFO, "Osmosis transformation aborted."); } logger.log(Level.INFO, "End Osmosis transformation"); } if (output != null && !searchOnly) { logger.log(Level.INFO, "Start file generation"); try { Worker.runBuildCitiesBorderFile(tmpPath, output, false); } catch (Exception e) { logger.log(Level.SEVERE, e.getMessage()); } logger.log(Level.INFO, "End file generation"); } if (search != null && output != null) { logger.log(Level.INFO, "Start border searching"); try { System.out.println(Arrays.asList(Worker.search(output, search))); } catch (IOException e) { logger.log(Level.SEVERE, e.getMessage()); } logger.log(Level.INFO, "End border searching"); } } }
28.136364
140
0.568336
de9b91c178859ec1e4373e64594e1ffbb3311733
1,487
/* * Copyright 2017 TieFaces. * Licensed under MIT */ package org.tiefaces.components.websheet.dataobjects; import org.apache.poi.xssf.usermodel.XSSFColor; /** * The Class XColor. */ public class XColor { /** The xssf color. */ private XSSFColor xssfColor; /** The alpha. */ private double alpha = 0; /** * Instantiates a new x color. * * @param seriesColor * the series color */ public XColor(final XSSFColor seriesColor) { super(); this.xssfColor = seriesColor; } /** * Instantiates a new x color. * * @param seriesColor * the series color * @param palpha * the alpha */ public XColor(final XSSFColor seriesColor, final double palpha) { super(); this.xssfColor = seriesColor; this.alpha = palpha; } /** * Gets the xssf color. * * @return the xssf color */ public final XSSFColor getXssfColor() { return xssfColor; } /** * Sets the series color. * * @param pxssfColor * the new series color */ public final void setSeriesColor(final XSSFColor pxssfColor) { this.xssfColor = pxssfColor; } /** * Gets the alpha. * * @return the alpha */ public final double getAlpha() { return alpha; } /** * Sets the alpha. * * @param palpha * the new alpha */ public final void setAlpha(final double palpha) { this.alpha = palpha; } }
17.091954
67
0.581036
360836fa45989ed47aee4103e0ef404911d2f459
2,585
package techreborn.blocks; import java.util.List; import java.util.Random; import cpw.mods.fml.relauncher.Side; import cpw.mods.fml.relauncher.SideOnly; import net.minecraft.block.Block; import net.minecraft.block.material.Material; import net.minecraft.client.renderer.texture.IIconRegister; import net.minecraft.creativetab.CreativeTabs; import net.minecraft.item.Item; import net.minecraft.item.ItemStack; import net.minecraft.util.IIcon; import net.minecraft.util.MathHelper; import net.minecraftforge.common.util.ForgeDirection; import techreborn.client.TechRebornCreativeTabMisc; import techreborn.init.ModBlocks; import techreborn.utils.RecipeUtils; public class BlockStorage extends Block { public static ItemStack getStorageBlockByName(String name, int count) { int meta = RecipeUtils.getArrayPos(types, name); if (meta == -1) return BlockStorage2.getStorageBlockByName(name, count); return new ItemStack(ModBlocks.storage, count, meta); } public static ItemStack getStorageBlockByName(String name) { return getStorageBlockByName(name, 1); } public static final String[] types = new String[] { "silver", "aluminium", "titanium", "chromium", "steel", "brass", "lead", "electrum", "zinc", "platinum", "tungsten", "nickel", "invar", "osmium", "iridium" }; private IIcon[] textures; public BlockStorage(Material material) { super(material); setBlockName("techreborn.storage"); setCreativeTab(TechRebornCreativeTabMisc.instance); setHardness(2f); ModBlocks.blocksToCut.add(this); } @Override public Item getItemDropped(int par1, Random random, int par2) { return Item.getItemFromBlock(this); } @Override @SideOnly(Side.CLIENT) public void getSubBlocks(Item item, CreativeTabs creativeTabs, List list) { for (int meta = 0; meta < types.length; meta++) { list.add(new ItemStack(item, 1, meta)); } } @Override public int damageDropped(int metaData) { return metaData; } @Override @SideOnly(Side.CLIENT) public void registerBlockIcons(IIconRegister iconRegister) { this.textures = new IIcon[types.length]; for (int i = 0; i < types.length; i++) { textures[i] = iconRegister.registerIcon("techreborn:" + "storage/" + types[i] + "_block"); } } @Override @SideOnly(Side.CLIENT) public IIcon getIcon(int side, int metaData) { metaData = MathHelper.clamp_int(metaData, 0, types.length - 1); if (ForgeDirection.getOrientation(side) == ForgeDirection.UP || ForgeDirection.getOrientation(side) == ForgeDirection.DOWN) { return textures[metaData]; } else { return textures[metaData]; } } }
29.044944
117
0.746228
21cb53f0911eb3d5261526aa77609e4aa6f750b2
91
package main; public enum PrimeMode { MODE_COUNT, MODE_BATCHED, MODE_BATCHED_HASHMAP }
11.375
23
0.791209
7ea051de6f8a0eaebc90fd57edff3646650ed5ef
367
package com.blannoo.adventofcode.day10; import org.assertj.core.api.Assertions; import org.junit.Test; import java.util.Arrays; public class SequencerTest { @Test public void test() throws Exception { Assertions.assertThat(new Sequencer().generate("1,2,3")) .isEqualTo(Arrays.asList(49, 44, 50, 44, 51, 17, 31, 73, 47, 23)); } }
26.214286
82
0.6703
6126660a4b02cb34c450d7f6e52d968aa997bab5
4,014
//If you're reading this, I just want to let you know that this is awesome!!! package me.aravind.connect4; import javafx.application.Application; import javafx.application.Platform; import javafx.event.ActionEvent; import javafx.event.EventHandler; import javafx.fxml.FXMLLoader; import javafx.scene.Parent; import javafx.scene.Scene; import javafx.scene.control.*; import javafx.scene.layout.GridPane; import javafx.scene.layout.Pane; import javafx.scene.layout.Region; import javafx.stage.Stage; public class Main extends Application { private Controller controller; @Override public void start(Stage primaryStage) throws Exception{ FXMLLoader loader = new FXMLLoader(getClass().getResource("game.fxml")); GridPane rootGridPane = loader.load(); controller = loader.getController(); controller.createPlayground(); MenuBar menuBar = createMenu(); menuBar.prefWidthProperty().bind(primaryStage.widthProperty()); Pane menuPane = (Pane) rootGridPane.getChildren().get(0); menuPane.getChildren().add(menuBar); Scene scene = new Scene(rootGridPane); primaryStage.setScene(scene); primaryStage.setTitle("Connect4"); primaryStage.setResizable(false); primaryStage.show(); } private MenuBar createMenu(){ Menu fileMenu = new Menu("File"); MenuItem newGame = new MenuItem("New Game"); newGame.setOnAction(event -> controller.resetGame()); MenuItem resetGame = new MenuItem("Reset Game"); resetGame.setOnAction(event -> controller.resetGame()); SeparatorMenuItem separatorMenuItem = new SeparatorMenuItem(); MenuItem exitGame = new MenuItem("Exit Game"); exitGame.setOnAction(event -> exitGame()); fileMenu.getItems().addAll(newGame, resetGame, separatorMenuItem, exitGame); Menu helpMenu = new Menu("Help"); MenuItem aboutGame = new MenuItem("About Game"); aboutGame.setOnAction(event -> aboutConnect4()); SeparatorMenuItem separator = new SeparatorMenuItem(); MenuItem aboutMe = new MenuItem("About Me"); aboutMe.setOnAction(event -> aboutMe()); helpMenu.getItems().addAll(aboutGame, aboutMe); MenuBar menuBar = new MenuBar(); menuBar.getMenus().addAll(fileMenu, helpMenu); return menuBar; } private void aboutMe() { Alert alert = new Alert(Alert.AlertType.INFORMATION); alert.setTitle("About The Developer"); alert.setHeaderText("Aravind Venugopal"); alert.setContentText("I love to play around with code, especially in Java and create applications. " + "Connect 4 is one of them. " + "In my free time, I like to spend time with my family or with my computer."); alert.getDialogPane().setMinHeight(Region.USE_PREF_SIZE); alert.show(); } private void aboutConnect4() { Alert alert = new Alert(Alert.AlertType.INFORMATION); alert.setTitle("About Connect4 Game"); alert.setHeaderText("How to Play?"); alert.setContentText("Connect Four is a two-player connection game in which the " + "players first choose a color and then take turns dropping colored discs " + "from the top into a seven-column, six-row vertically suspended grid. " + "The pieces fall straight down, occupying the next available space within the column. " + "The objective of the game is to be the first to form a horizontal, vertical, " + "or diagonal line of four of one's own discs. Connect Four is a solved game. " + "The first player can always win by playing the right moves."); alert.getDialogPane().setMinHeight(Region.USE_PREF_SIZE); alert.show(); } private void exitGame() { Platform.exit(); System.exit(0); } public static void main(String[] args) { launch(args); } }
38.970874
110
0.663926
f26c50313a01117b2f1e4947e12f394b0f0fef69
3,492
/** * Copyright 2016 Lloyd Torres * * 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.lloydtorres.stately.wa; import android.app.Dialog; import android.content.DialogInterface; import android.os.Bundle; import android.view.LayoutInflater; import android.view.View; import android.widget.RadioGroup; import androidx.appcompat.app.AlertDialog; import com.lloydtorres.stately.R; import com.lloydtorres.stately.core.DetachDialogFragment; import com.lloydtorres.stately.helpers.RaraHelper; /** * Created by Lloyd on 2016-02-02. * This dialog displays voting options for a WA resolution. */ public class VoteDialog extends DetachDialogFragment { public static final String DIALOG_TAG = "fragment_vote_dialog"; public static final int VOTE_FOR = 0; public static final int VOTE_AGAINST = 1; public static final int VOTE_UNDECIDED = 2; private RadioGroup voteToggleState; private int choice; public VoteDialog() { } public void setChoice(int c) { choice = c; } @Override public Dialog onCreateDialog(Bundle savedInstanceState) { LayoutInflater inflater = getActivity().getLayoutInflater(); View dialogView = inflater.inflate(R.layout.fragment_vote_dialog, null); voteToggleState = dialogView.findViewById(R.id.vote_radio_group); switch (choice) { case VOTE_FOR: voteToggleState.check(R.id.vote_radio_for); break; case VOTE_AGAINST: voteToggleState.check(R.id.vote_radio_against); break; default: voteToggleState.check(R.id.vote_radio_undecided); break; } DialogInterface.OnClickListener dialogListener = new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { submitVote(); } }; AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(getContext(), RaraHelper.getThemeMaterialDialog(getContext())); dialogBuilder.setTitle(R.string.wa_vote_dialog_title) .setView(dialogView) .setPositiveButton(R.string.wa_vote_dialog_submit, dialogListener) .setNegativeButton(R.string.explore_negative, null); return dialogBuilder.create(); } /** * Calls ResolutionActivity's own submitVote logic. */ private void submitVote() { int mode; switch (voteToggleState.getCheckedRadioButtonId()) { case R.id.vote_radio_for: mode = VOTE_FOR; break; case R.id.vote_radio_against: mode = VOTE_AGAINST; break; default: mode = VOTE_UNDECIDED; break; } if (mode != choice) { ((ResolutionActivity) getActivity()).submitVote(mode); } } }
31.745455
96
0.652921
4a5f545ffe7efc960fea066b2c7863c0667ceeb2
282
package uni.mobile.mobileapp.rest.callbacks; import androidx.annotation.NonNull; import java.util.List; import uni.mobile.mobileapp.rest.House; public interface HouseCallback { void onSuccess(@NonNull List<House> value); //void onError(@NonNull Throwable throwable); }
20.142857
49
0.77305
585331260050b90621294b009048ba0ee98a9e45
4,840
package online.himakeit.qrcodekit.util; import android.content.Context; import android.os.Build; import android.os.Environment; import android.os.StatFs; import java.io.File; /** * @author:LiXueLong * @date:2018/3/29 * @mail1:skylarklxlong@outlook.com * @mail2:li_xuelong@126.com * @des:sd卡路径 */ public class SDCardUtils { public static String getSDCardPublicDir(String type) { return Environment .getExternalStoragePublicDirectory(type) .getAbsolutePath(); } /** * /storage/emulated/0 * * @param context * @return */ public static String getSDCardDir(Context context) { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { return getExternalFilesDir(context); } return getSDCardPublicDir(Environment.DIRECTORY_DCIM); } /** * /data/data/<application package>/cache * * @param context * @return */ public static String getCacheDir(Context context) { return context.getCacheDir().getPath(); } /** * /data/data/<application package>/files * * @param context * @return */ public static String getFilesDir(Context context) { return context.getFilesDir().getPath(); } /** * /data/data/<application package>/databases * * @param context * @param dbName * @return */ public static String getDataBaseDir(Context context, String dbName) { return context.getDatabasePath(dbName).getPath(); } /** * /storage/emulated/0/Android/data/你的应用包名/cache/(APP卸载后,数据会被删除) * * @param context * @return */ public static String getExternalCacheDir(Context context) { return context.getExternalCacheDir().getPath(); } /** * /storage/emulated/0/Android/data/你的应用的包名/files/(APP卸载后,数据会被删除) * * @param context * @return */ public static String getExternalFilesDir(Context context) { return context.getExternalFilesDir(null).getPath(); } /** * 自动选择Flies路径,若SD卡存在并且不能移除则用SD卡存储 * * @param context * @return */ public static String getAutoFilesPath(Context context) { String filesPath; if (ExistSDCard() && !SDCardRemovable()) { filesPath = getExternalFilesDir(context); } else { filesPath = getFilesDir(context); } return filesPath; } /** * 自动选择Cache路径,若SD卡存在并且不能移除则用SD卡存储 * * @param context * @return */ public static String getAutoCachePath(Context context) { String cachePath; if (ExistSDCard() && !SDCardRemovable()) { cachePath = getExternalCacheDir(context); } else { cachePath = getCacheDir(context); } return cachePath; } /** * 检查SD卡是否存在 * * @return */ public static boolean ExistSDCard() { return Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState()); } /** * 检查SD卡是否能被移除 * * @return */ public static boolean SDCardRemovable() { return Environment.isExternalStorageRemovable(); } /** * 获取内部存储剩余空间 * * @return */ public static long getFreeSpace() { return Environment.getExternalStorageDirectory().getFreeSpace(); } /** * 获取内部存储可用空间 * * @return */ public static long getUsableSpace() { return Environment.getExternalStorageDirectory().getUsableSpace(); } /** * 获取内部存储总空间 * * @return */ public static long getTotalSpace() { return Environment.getExternalStorageDirectory().getTotalSpace(); } /** * 计算SD卡的剩余空间 * * @return 返回-1,说明没有安装sd卡 */ public static long getFreeDiskSpace() { String status = Environment.getExternalStorageState(); long freeSpace = 0; if (status.equals(Environment.MEDIA_MOUNTED)) { try { File path = Environment.getExternalStorageDirectory(); StatFs stat = new StatFs(path.getPath()); long blockSize; long availableBlocks; if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR2) { blockSize = stat.getBlockSizeLong(); availableBlocks = stat.getAvailableBlocksLong(); } else { blockSize = stat.getBlockSize(); availableBlocks = stat.getAvailableBlocks(); } freeSpace = availableBlocks * blockSize; } catch (Exception e) { e.printStackTrace(); } } else { return -1; } return (freeSpace); } }
24.568528
87
0.577479
521cc17703a18f6e4aebe1ef5d1fec84f8178fcc
663
/* * Copyright (c) 2016-2021 Association of Universities for Research in Astronomy, Inc. (AURA) * For license information see LICENSE or https://opensource.org/licenses/BSD-3-Clause */ package edu.gemini.seqexec.server.gnirs; public enum DetectorState { Inactive("Deactivate", false), Active("Activate", true); // Why are the values verbs? final String name; final boolean active; DetectorState(String name, boolean active) { this.name = name; this.active = active; } @Override public String toString() { return this.name; } public boolean getActive() { return this.active; } }
22.862069
93
0.657617
ea45e063247c5ac46a1262b5a1c1bc1b80b11dc0
1,743
package meta.tg; import meta.CyanMetaobjectNumber; import meta.ICompilerAction_dpa; import meta.ICompiler_dsa; public class CyanMetaobjectNumberIP extends CyanMetaobjectNumber { public CyanMetaobjectNumberIP(){ super(); } @Override public String[] getSuffixNames() { return new String[] { "IP", "Ip", "ip" }; } @Override public void dpa_parse(ICompilerAction_dpa compilerAction, String code){ String currentNumber = new String(); String completeIP = new String(); code = code.substring(0, code.length()-2); int n = code.length(); int underscoreCount = 0; for(int i = 0; i < n; i++){ char c = code.charAt(i); if(!Character.isDigit(c)){ if(c != '_'){ addError("Malformed expression: IP metaobject must contain only numbers and underscores"); return ; } else{ underscoreCount++; int aux = Integer.parseInt(currentNumber); if(aux < 0 || aux > 255){ addError("Invalid IP address: each number must be in the range 0..255"); return ; } else{ completeIP += currentNumber; if(underscoreCount <= 3) completeIP += "."; currentNumber = ""; } } }else{ currentNumber += c; } if(underscoreCount > 4){ addError("Invalid IP address: address must contain exactly four numbers"); return ; } } setInfo(new StringBuffer("IPAddress( \"" + completeIP + "\")")); } @Override public StringBuffer dsa_codeToAdd(ICompiler_dsa compiler_dsa) { return (StringBuffer ) getInfo(); } @Override public String getPackageOfType() { return "tg"; } @Override public String getPrototypeOfType() { return "IPAddress"; } }
22.934211
96
0.620195
2bd70971db0bbc2543717cc54be2681ae1324da6
302
package org.springframework.roo.addon.web.mvc.views.components; /** * This enumerate represent all possible field types that can be * displayed on generated views. * * @author Juan Carlos García * @since 2.0 */ public enum FieldTypes { TEXT, NUMBER, BOOLEAN, DATE, ENUM, REFERENCE, LIST; }
20.133333
64
0.721854
59b2de6d1251692a1139d77c7b2c6a9fa547459a
626
package br.com.matheusbodo.rspt.entity.enums; public enum GuitarcadeGame { DUCKS_REDUX("Ducks Redux"), GONE_WAILING("Gone Wailing"), HARMONIC_HEIST("Harmonic Heist"), HURTIN_HURDLES("Hurtin Hurdles"), NINJA_SLIDE("Ninja Slide"), NINJA_WARRIORS("Ninja Warriors"), RETURN_CASTLE_CHORDEAD("Return to the Castle of Chordead"), SCALE_RACER("Scale Racer"), STAR_CHORDS("Star Chords"), STRING_SKIP_SALOON("String Skip Saloon"), TEMPLE_OF_BENDS("Temple of Bends"); private String caption; private GuitarcadeGame(String caption) { this.caption = caption; } public String getCaption() { return caption; } }
22.357143
60
0.747604
40269e957b1b64d1812ec32d9c1e1eba96971923
344
package com.lordjoe.ui.timeeditor; import javax.swing.*; /** * com.lordjoe.ui.timeeditor.JTimeStampComponent * * @author Steve Lewis * @date Dec 28, 2007 */ public class JTimeStampComponent extends JPanel { public static JTimeStampComponent[] EMPTY_ARRAY = {}; public static Class THIS_CLASS = JTimeStampComponent.class; }
19.111111
63
0.729651
b118c63d95b700e9d5d0bb51ef76982c9cfaa764
1,564
/******************************************************************************* * Copyright 2010 Atos Worldline SAS * * Licensed by Atos Worldline SAS under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * Atos Worldline SAS licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ package net.awl.edoc.pdfa.font; import java.awt.Font; import java.awt.FontFormatException; import java.io.FileInputStream; public class ValidateType1 { public static void main(String[] args) throws Exception { try { Font.createFont(Font.TYPE1_FONT, new FileInputStream( "/usr/share/fonts/default/Type1/a010015l.pfb")); // Font.createFont(Font.TYPE1_FONT, new // FileInputStream("resources/bad_type_1.pfb")); } catch (FontFormatException e) { // throw exception if invalid true type e.printStackTrace(); } } }
39.1
85
0.65665
e92d8e26b4ef8883affbe52db46441f7a96c1f87
4,246
package de.renew.engine.simulator; import de.renew.engine.searcher.Finder; import de.renew.engine.searcher.Searchable; import de.renew.engine.searcher.Searcher; import de.renew.engine.searcher.Triggerable; import java.util.Collection; public class SimulatorHelper { /** * Search a given searchable, making sure to register * dependencies. The given triggerable might be triggered * as soon as this method begins its work. In that case * the result of this search should be discarded. * The finder will only be informed of bindings that * can be executed without advancing the time. * * @param finder the finder that will be informed about * possible bindings * @param searchable the object to be searched * @param triggerable the object that will be notified * when an object changes, if that object is relavant to this * search process **/ public static void searchOnce(Searcher searcher, Finder finder, Searchable searchable, Triggerable triggerable) { assert SimulationThreadPool.isSimulationThread() : "is not in a simulation thread"; // Perform the search. searcher.searchAndRecover(new CheckTimeFinder(finder), searchable, triggerable); } /** * This method checks a searchable for enabledness. * A searcher must be provided for this method. The method * uses the given triggerable to store a new set of triggers. */ public static boolean isFirable(Searchable searchable, Triggerable triggerable, Searcher searcher) { assert SimulationThreadPool.isSimulationThread() : "is not in a simulation thread"; EnablednessFinder finder = new EnablednessFinder(); searchOnce(searcher, finder, searchable, triggerable); return finder.isEnabled(); } /** * This method checks a searchable for enabledness. It * uses the given triggerable to store a new set of triggers. */ public static boolean isFirable(Searchable searchable, Triggerable triggerable) { assert SimulationThreadPool.isSimulationThread() : "is not in a simulation thread"; Searcher searcher = new Searcher(); return isFirable(searchable, triggerable, searcher); } /** * This method collects all bindings for a searchable. * A searcher must be provided for this method. The method * uses the given triggerable to store a new set of triggers. * By using triggerables other than those associated with the * searchable, it is possible to keep more triggers than * with the searchable's triggers. This is required because the * searchable might only be interested in its own enabledness, * but not in all its bindings. * * @see de.renew.engine.simulator.Binding * * @param searchable the searchable whose binding will be determined * @param triggerable the triggerable that get notified as soon as * the search result becomes invalid * @param searcher the searcher that performs the search * @return an enumeration of bindings */ public static Collection<Binding> findAllBindings(Searchable searchable, Triggerable triggerable, Searcher searcher) { assert SimulationThreadPool.isSimulationThread() : "is not in a simulation thread"; CollectingFinder finder = new CollectingFinder(); searchOnce(searcher, finder, searchable, triggerable); return finder.bindings(); } /** * This method collects all bindings for a searchable. It * uses the given triggerable to store a new set of triggers. */ public static Collection<Binding> findAllBindings(Searchable searchable, Triggerable triggerable) { assert SimulationThreadPool.isSimulationThread() : "is not in a simulation thread"; Searcher searcher = new Searcher(); return findAllBindings(searchable, triggerable, searcher); } }
43.773196
91
0.660151
6c204ed040b4b6537412fab7731f3eee4a3bfcc4
2,748
/* * 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.lucene.search; import java.io.IOException; import java.util.Collection; import org.apache.lucene.util.MathUtil; /** * Utility class to propagate scoring information in {@link BooleanQuery}, which * compute the score as the sum of the scores of its matching clauses. * This helps propagate information about the maximum produced score */ final class MaxScoreSumPropagator { private final int numClauses; private final Scorer[] scorers; MaxScoreSumPropagator(Collection<? extends Scorer> scorerList) throws IOException { numClauses = scorerList.size(); scorers = scorerList.toArray(new Scorer[numClauses]); } void advanceShallow(int target) throws IOException { for (Scorer s : scorers) { if (s.docID() < target) { s.advanceShallow(target); } } } float getMaxScore(int upTo) throws IOException { double maxScore = 0; for (Scorer s : scorers) { if (s.docID() <= upTo) { maxScore += s.getMaxScore(upTo); } } return scoreSumUpperBound(maxScore); } private float scoreSumUpperBound(double sum) { if (numClauses <= 2) { // When there are only two clauses, the sum is always the same regardless // of the order. return (float) sum; } // The error of sums depends on the order in which values are summed up. In // order to avoid this issue, we compute an upper bound of the value that // the sum may take. If the max relative error is b, then it means that two // sums are always within 2*b of each other. // For conjunctions, we could skip this error factor since the order in which // scores are summed up is predictable, but in practice, this wouldn't help // much since the delta that is introduced by this error factor is usually // cancelled by the float cast. double b = MathUtil.sumRelativeErrorBound(numClauses); return (float) ((1.0 + 2 * b) * sum); } }
35.688312
85
0.70706
d41041ccdb513bf330e2e59372306b24eae4c0c9
14,578
package com.jainnews.jainnewsapp; import android.content.DialogInterface; import android.content.Intent; import android.content.pm.PackageManager; import android.os.Build; import android.os.Bundle; import android.util.Log; import android.view.MenuItem; import android.view.View; import android.widget.ImageView; import android.widget.ProgressBar; import android.widget.Toast; import androidx.annotation.NonNull; import androidx.appcompat.app.ActionBarDrawerToggle; import androidx.appcompat.app.AlertDialog; import androidx.appcompat.app.AppCompatActivity; import androidx.appcompat.widget.Toolbar; import androidx.core.app.ActivityCompat; import androidx.core.content.ContextCompat; import androidx.core.view.GravityCompat; import androidx.drawerlayout.widget.DrawerLayout; import androidx.recyclerview.widget.LinearLayoutManager; import androidx.recyclerview.widget.RecyclerView; import com.android.volley.Request; import com.android.volley.Response; import com.android.volley.VolleyError; import com.android.volley.toolbox.JsonArrayRequest; import com.jainnews.jainnewsapp.adapters.BookAdapter; import com.jainnews.jainnewsapp.adapters.NewsAdapter; import com.jainnews.jainnewsapp.adapters.VideoAdapter; import com.jainnews.jainnewsapp.navigation.AudioActivity; import com.jainnews.jainnewsapp.navigation.BookActivity; import com.jainnews.jainnewsapp.navigation.ContactActivity; import com.jainnews.jainnewsapp.navigation.DharamshalaActivity; import com.jainnews.jainnewsapp.navigation.MemberActivity; import com.jainnews.jainnewsapp.navigation.NewsActivity; import com.jainnews.jainnewsapp.navigation.VideoActivity; import com.jainnews.jainnewsapp.utils.MySingleton; import com.jainnews.jainnewsapp.utils.ipUtil; import com.google.android.material.navigation.NavigationView; import com.synnapps.carouselview.CarouselView; import com.synnapps.carouselview.ImageListener; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import java.util.Objects; import static android.Manifest.permission.INTERNET; public class HomePage extends AppCompatActivity implements NavigationView.OnNavigationItemSelectedListener { private RecyclerView recyclerViewNews, recyclerViewVideo ,recyclerViewBook; private RecyclerView.Adapter adapter; private ProgressBar progressBar; private String news_url = ipUtil.getIp() + "android_api/routes/getNews.php"; private String videos_url = ipUtil.getIp() + "android_api/routes/getVideo.php"; private String books_url = ipUtil.getIp() + "android_api/routes/getBooks.php"; CarouselView carouselView; int[] sampleImages = {R.drawable.zero, R.drawable.one, R.drawable.two, R.drawable.three }; private static final int PERMISSION_REQUEST_CODE = 200; public static JSONArray newsArray, videosArray, booksArray; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_home_page); Toolbar toolbar = findViewById(R.id.toolbar); setSupportActionBar(toolbar); Objects.requireNonNull(getSupportActionBar()).setTitle("Home"); DrawerLayout drawer = findViewById(R.id.drawer_layout); ActionBarDrawerToggle toggle = new ActionBarDrawerToggle( this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close); drawer.addDrawerListener(toggle); toggle.syncState(); NavigationView navigationView = findViewById(R.id.nav_view); navigationView.setNavigationItemSelectedListener(this); progressBar = findViewById(R.id.progressHome); progressBar.setVisibility(View.VISIBLE); carouselView = findViewById(R.id.carouselView); carouselView.setPageCount(sampleImages.length); carouselView.setImageListener(new ImageListener() { @Override public void setImageForPosition(int position, ImageView imageView) { imageView.setImageResource(sampleImages[position]); } }); recyclerViewNews = findViewById(R.id.trendingNewsRV); recyclerViewNews.setHasFixedSize(true); recyclerViewNews.setLayoutManager(new LinearLayoutManager(this, LinearLayoutManager.HORIZONTAL, false)); recyclerViewVideo = findViewById(R.id.trendingVideosRV); recyclerViewVideo.setHasFixedSize(true); recyclerViewVideo.setLayoutManager(new LinearLayoutManager(this, LinearLayoutManager.HORIZONTAL, false)); recyclerViewBook = findViewById(R.id.trendingBooksRV); recyclerViewBook.setHasFixedSize(true); recyclerViewBook.setLayoutManager(new LinearLayoutManager(this, LinearLayoutManager.HORIZONTAL, false)); if (!checkPermission()) { requestPermission(); } else { addTrendingNews(); addTrendingVideos(); addTrendingBooks(); } (findViewById(R.id.newsMore)).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { startActivity(new Intent(HomePage.this, NewsActivity.class)); } }); (findViewById(R.id.videosMore)).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { startActivity(new Intent(HomePage.this, VideoActivity.class)); } }); (findViewById(R.id.booksMore)).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { startActivity(new Intent(HomePage.this, BookActivity.class)); } }); } private boolean checkPermission() { int result = ContextCompat.checkSelfPermission(getApplicationContext(), INTERNET); return result == PackageManager.PERMISSION_GRANTED ; } private void requestPermission() { ActivityCompat.requestPermissions(this, new String[]{INTERNET}, PERMISSION_REQUEST_CODE); } @Override public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) { if (grantResults.length > 0 && PERMISSION_REQUEST_CODE == requestCode) { boolean linternetAccepted = grantResults[0] == PackageManager.PERMISSION_GRANTED; if (linternetAccepted) Toast.makeText(getApplicationContext(), "Permission Granted.", Toast.LENGTH_LONG).show(); else { Toast.makeText(getApplicationContext(), "Permission denied.", Toast.LENGTH_LONG).show(); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { if (shouldShowRequestPermissionRationale(INTERNET)) { showMessageOKCancel( new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { requestPermissions(new String[]{INTERNET}, PERMISSION_REQUEST_CODE); } }); } } } } } private void showMessageOKCancel(DialogInterface.OnClickListener okListener) { new AlertDialog.Builder(HomePage.this) .setMessage("You need to allow access to the permissions") .setPositiveButton("OK", okListener) .setNegativeButton("Cancel", null) .create() .show(); } private void addTrendingNews() { JsonArrayRequest jsonArrayRequest = new JsonArrayRequest( Request.Method.GET, news_url, null, new Response.Listener<JSONArray>() { @Override public void onResponse(JSONArray response) { try { newsArray = new JSONArray(); for(int i = 0; i < 5 && i != response.length(); i++){ newsArray.put(response.get(i)); } }catch (JSONException e) { e.printStackTrace(); } adapter = new NewsAdapter(HomePage.this, response); recyclerViewNews.setAdapter(adapter); Log.d("JSON RESPONSE: ", response.toString()); } }, new Response.ErrorListener(){ @Override public void onErrorResponse(VolleyError error){ // Do something when error occurred Toast.makeText(getApplicationContext(), "Problem connecting to the server.", Toast.LENGTH_SHORT).show(); } } ); // Access the RequestQueue through your singleton class. MySingleton.getInstance(this).addToRequestQueue(jsonArrayRequest); } private void addTrendingVideos() { JsonArrayRequest jsonArrayRequest = new JsonArrayRequest( Request.Method.GET, videos_url, null, new Response.Listener<JSONArray>() { @Override public void onResponse(JSONArray response) { try { videosArray = new JSONArray(); for(int i = 0; i < 5 && i != response.length(); i++){ videosArray.put(response.get(i)); } }catch (JSONException e) { e.printStackTrace(); } adapter = new VideoAdapter(HomePage.this, response); recyclerViewVideo.setAdapter(adapter); } }, new Response.ErrorListener(){ @Override public void onErrorResponse(VolleyError error){ // Do something when error occurred } } ); // Access the RequestQueue through your singleton class. MySingleton.getInstance(this).addToRequestQueue(jsonArrayRequest); } private void addTrendingBooks() { JsonArrayRequest jsonArrayRequest = new JsonArrayRequest( Request.Method.GET, books_url, null, new Response.Listener<JSONArray>() { @Override public void onResponse(JSONArray response) { try { booksArray = new JSONArray(); for(int i = 0; i < 5 && i != response.length(); i++){ booksArray.put(response.get(i)); } }catch (JSONException e) { e.printStackTrace(); } adapter = new BookAdapter(HomePage.this, response); recyclerViewBook.setAdapter(adapter); progressBar.setVisibility(View.GONE); } }, new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError error) { progressBar.setVisibility(View.GONE); } } ); // Access the RequestQueue through your singleton class. MySingleton.getInstance(this).addToRequestQueue(jsonArrayRequest); } public static JSONArray getNewsArray(){ return newsArray; } public static JSONArray getVideosArray(){ return videosArray; } public static JSONArray getBooksArray(){ return booksArray; } public static JSONObject getNewsObject(int id){ try { return newsArray.getJSONObject(id); } catch (JSONException e) { e.printStackTrace(); } return null; } @Override public void onBackPressed() { DrawerLayout drawer = findViewById(R.id.drawer_layout); if (drawer.isDrawerOpen(GravityCompat.START)) { drawer.closeDrawer(GravityCompat.START); } else { moveTaskToBack(true); } } @Override public boolean onNavigationItemSelected(MenuItem item) { // Handle navigation view item clicks here. int id = item.getItemId(); if (id == R.id.nav_home) { startActivity(new Intent(HomePage.this, HomePage.class)); } else if (id == R.id.nav_news){ startActivity(new Intent(HomePage.this, NewsActivity.class)); } else if (id == R.id.nav_audio) { startActivity(new Intent(HomePage.this, AudioActivity.class)); } else if (id == R.id.nav_video){ startActivity(new Intent(HomePage.this, VideoActivity.class)); }else if (id == R.id.nav_books){ startActivity(new Intent(HomePage.this, BookActivity.class)); }else if (id == R.id.nav_dharmashala){ startActivity(new Intent(HomePage.this, DharamshalaActivity.class)); }else if (id == R.id.nav_member){ startActivity(new Intent(HomePage.this, MemberActivity.class)); }else if (id == R.id.nav_contact){ startActivity(new Intent(HomePage.this, ContactActivity.class)); } // else if(id == R.id.nav_exit){ // closeAppAndLogOut(); // } DrawerLayout drawer = findViewById(R.id.drawer_layout); drawer.closeDrawer(GravityCompat.START); return true; } // private void closeAppAndLogOut() { // SharedPreferences sharedPref = getSharedPreferences("loginDetails", Context.MODE_PRIVATE); // sharedPref.edit().clear().commit(); // Toast.makeText(getApplicationContext(), "Logout successfull", Toast.LENGTH_SHORT).show(); // } }
40.270718
129
0.596995
14107237dc1ce3c1f02b870d85b240754826bbac
71,688
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * */ package org.apache.directory.fortress.core.impl; import java.util.Collection; import java.util.List; import java.util.Map; import java.util.Set; import org.apache.directory.fortress.core.AdminMgr; import org.apache.directory.fortress.core.GlobalErrIds; import org.apache.directory.fortress.core.ReviewMgr; import org.apache.directory.fortress.core.ReviewMgrFactory; import org.apache.directory.fortress.core.SecurityException; import org.apache.directory.fortress.core.model.PermObj; import org.apache.directory.fortress.core.model.Permission; import org.apache.directory.fortress.core.model.PermissionAttribute; import org.apache.directory.fortress.core.model.PermissionAttributeSet; import org.apache.directory.fortress.core.model.Role; import org.apache.directory.fortress.core.model.RoleConstraint; import org.apache.directory.fortress.core.model.SDSet; import org.apache.directory.fortress.core.model.Session; import org.apache.directory.fortress.core.model.User; import org.apache.directory.fortress.core.model.UserRole; import org.apache.directory.fortress.core.util.LogUtil; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import junit.framework.Test; import junit.framework.TestCase; import junit.framework.TestSuite; /** * ReviewMgrImpl Tester. * * @author <a href="mailto:dev@directory.apache.org">Apache Directory Project</a> * @version 1.0 */ public class ReviewMgrImplTest extends TestCase { private static final String CLS_NM = ReviewMgrImplTest.class.getName(); private static final Logger LOG = LoggerFactory.getLogger( CLS_NM ); private static Session adminSess = null; public ReviewMgrImplTest( String name ) { super( name ); } public static Test suite() { TestSuite suite = new TestSuite(); /* suite.addTest( new ReviewMgrImplTest( "testReadPermissionOp" ) ); suite.addTest( new ReviewMgrImplTest( "testFindPermissionOps" ) ); suite.addTest( new ReviewMgrImplTest( "testReadPermissionObj" ) ); suite.addTest( new ReviewMgrImplTest( "testFindPermissionObjs" ) ); suite.addTest( new ReviewMgrImplTest( "testReadRole" ) ); suite.addTest( new ReviewMgrImplTest( "testFindRoles" ) ); suite.addTest( new ReviewMgrImplTest( "testReadUser" ) ); suite.addTest( new ReviewMgrImplTest( "testFindUsers" ) ); suite.addTest( new ReviewMgrImplTest( "testAssignedRoles" ) ); suite.addTest( new ReviewMgrImplTest( "testAuthorizedUsers" ) ); suite.addTest( new ReviewMgrImplTest( "testAuthorizedRoles" ) ); suite.addTest( new ReviewMgrImplTest( "testRolePermissions" ) ); suite.addTest( new ReviewMgrImplTest( "testUserPermissions" ) ); suite.addTest( new ReviewMgrImplTest( "testPermissionRoles" ) ); suite.addTest( new ReviewMgrImplTest( "testAuthorizedPermissionRoles" ) ); suite.addTest( new ReviewMgrImplTest( "testPermissionUsers" ) ); suite.addTest( new ReviewMgrImplTest( "testAuthorizedPermissionUsers" ) ); suite.addTest( new ReviewMgrImplTest( "testFindSsdSets" ) ); suite.addTest( new ReviewMgrImplTest( "testFindDsdSets" ) ); */ //suite.addTest( new ReviewMgrImplTest( "testReadUserRoleConstraint" ) ); //suite.addTest( new ReviewMgrImplTest( "testFindRoleConstraints" ) ); suite.addTest( new ReviewMgrImplTest( "testAssignedUserRoleConstraints" ) ); return suite; } public void setUp() throws Exception { super.setUp(); } public void tearDown() throws Exception { super.tearDown(); } public static Test suitex() { return new TestSuite( ReviewMgrImplTest.class ); } public void testReadPermissionOp() { // public Permission readPermission(Permission permOp) readPermissionOps( "RD-PRM-OPS TOB1 OPS_TOP1_UPD", PermTestData.OBJS_TOB1, PermTestData.OPS_TOP1_UPD ); readPermissionOps( "RD-PRM-OPS TOB1 TOP2", PermTestData.OBJS_TOB2, PermTestData.OPS_TOP2 ); readPermissionOps( "RD-PRM-OPS TOB1 TOP3", PermTestData.OBJS_TOB3, PermTestData.OPS_TOP3 ); } /** * @param msg * @param pObjArray * @param pOpArray */ public static void readPermissionOps( String msg, String[][] pObjArray, String[][] pOpArray ) { Permission pOp = new Permission(); LogUtil.logIt( msg ); try { ReviewMgr reviewMgr = getManagedReviewMgr(); for ( String[] objs : pObjArray ) { for ( String[] ops : pOpArray ) { pOp = new Permission(); pOp.setObjName( PermTestData.getName( objs ) ); pOp.setOpName( PermTestData.getName( ops ) ); pOp.setObjId( PermTestData.getObjId( ops ) ); Permission entity = reviewMgr.readPermission( pOp ); assertNotNull( entity ); PermTestData.assertEquals( PermTestData.getName( objs ), entity, ops ); LOG.debug( "readPermissionOps object name [" + pOp.getObjName() + "] operation name [" + pOp.getOpName() + "] objectId [" + pOp.getObjId() + "] successful" ); } } } catch ( SecurityException ex ) { LOG.error( "readPermissionOps object name [" + pOp.getObjName() + "] operation name [" + pOp.getOpName() + "] objectId [" + pOp.getObjId() + "] caught SecurityException rc=" + ex.getErrorId() + ", msg=" + ex.getMessage() + ex ); fail( ex.getMessage() ); } } public void testReadPermissionAttributeSets() { readPermissionAttributeSet( "RD-PA-SET TPASET1", PermTestData.TPA_SET_1_NAME, PermTestData.loadPermissionAttributes(PermTestData.PA_TPSASET1) ); Set<PermissionAttribute> paSetTwoPas = PermTestData.loadPermissionAttributes(PermTestData.PA_TPSASET2); paSetTwoPas.addAll(PermTestData.loadPermissionAttributes(PermTestData.PA_TPSASET2_ADDITIONAL)); readPermissionAttributeSet( "RD-PA-SET TPASET2", PermTestData.TPA_SET_2_NAME, paSetTwoPas); } public static void readPermissionAttributeSet( String msg, String name, Set<PermissionAttribute> permAttributes ) { LogUtil.logIt( msg ); try { ReviewMgr reviewMgr = getManagedReviewMgr(); PermissionAttributeSet entity = reviewMgr.readPermAttributeSet(new PermissionAttributeSet(name)); assertNotNull(entity); assertEquals(name, entity.getName()); assertEquals(PermTestData.TPA_SET_TYPE, entity.getType()); for(PermissionAttribute pa : permAttributes){ assertTrue(entity.getAttributes().contains(pa)); } LOG.debug( "readPermissionAttributeSet name [" + name + "] successful" ); } catch ( SecurityException ex ) { LOG.error( "readPermissionAttributeSet name [" + name + "] caught SecurityException rc=" + ex.getErrorId() + ", msg=" + ex.getMessage() + ex ); fail( ex.getMessage() ); } } public void testReadPASetFromPermission() { readPASetFromPermission( "RD-PASET-FROM-POP TOB_1 TOP_1", PermTestData.TPA_SET_1_NAME, "TOB1_1", PermTestData.OPS_TOP1[0] ); } public static void readPASetFromPermission( String msg, String paSetName, String obj, String[] op ) { LogUtil.logIt(msg); try { ReviewMgr reviewMgr = getManagedReviewMgr(); Permission pop = PermTestData.getOp( obj, op ); Permission entity = reviewMgr.readPermission(pop); assertTrue(paSetName, entity.getPaSets().contains(paSetName)); LOG.debug( "readPASetFromPermission name [" + paSetName + "] successful" ); } catch ( SecurityException ex ) { LOG.error( "readPASetFromPermission name [" + paSetName + "] caught SecurityException rc=" + ex.getErrorId() + ", msg=" + ex.getMessage(), ex ); fail( ex.getMessage() ); } } public void testFindPermissionOps() { // public List<Permission> findPermissions(Permission permOp) searchPermissionOps( "FND-PRM-OPS TOB1 OPS_TOP1_UPD", TestUtils.getSrchValue( PermTestData.getName( PermTestData.OPS_TOP1_UPD[0] ) ), PermTestData.OBJS_TOB1, PermTestData.OPS_TOP1_UPD ); searchPermissionOps( "FND-PRM-OPS TOB2 TOP2", TestUtils.getSrchValue( PermTestData.getName( PermTestData.OPS_TOP2[0] ) ), PermTestData.OBJS_TOB2, PermTestData.OPS_TOP2 ); searchPermissionOps( "FND-PRM-OPS TOB3 TOP3", TestUtils.getSrchValue( PermTestData.getName( PermTestData.OPS_TOP3[0] ) ), PermTestData.OBJS_TOB3, PermTestData.OPS_TOP3 ); } /** * @param msg * @param srchValue * @param pObjArray */ public static void searchPermissionOps( String msg, String srchValue, String[][] pObjArray, String[][] pOpArray ) { LogUtil.logIt( msg ); Permission pOp; try { ReviewMgr reviewMgr = getManagedReviewMgr(); for ( String[] obj : pObjArray ) { for ( String[] op : pOpArray ) { pOp = new Permission(); pOp.setObjName( PermTestData.getName( obj ) ); pOp.setOpName( srchValue ); List<Permission> ops = reviewMgr.findPermissions( pOp ); assertNotNull( ops ); assertTrue( CLS_NM + "searchPermissionOps srchValue [" + srchValue + "] list size check", pOpArray.length == ops.size() ); int indx = ops.indexOf( new Permission( PermTestData.getName( obj ), PermTestData.getName( op ), PermTestData.getObjId( op ) ) ); if ( indx != -1 ) { Permission entity = ops.get( indx ); assertNotNull( entity ); PermTestData.assertEquals( PermTestData.getName( obj ), entity, op ); LOG.debug( "searchPermissionOps objName [" + entity.getObjName() + "] operation name [" + entity.getOpName() + "] successful" ); } else { msg = "searchPermissionOps srchValue [" + srchValue + "] failed list search"; LogUtil.logIt( msg ); fail( msg ); } } } } catch ( SecurityException ex ) { LOG.error( "searchPermissionOps srchValue [" + srchValue + "] caught SecurityException rc=" + ex.getErrorId() + ", msg=" + ex.getMessage(), ex ); fail( ex.getMessage() ); } } public void testReadPermissionObj() { // public Permission readPermission(Permission permOp) readPermissionObjs( "RD-PRM-OBJS TOB1", PermTestData.OBJS_TOB1 ); readPermissionObjs( "RD-PRM-OBJS TOB2", PermTestData.OBJS_TOB2 ); readPermissionObjs( "RD-PRM-OBJS TOB3", PermTestData.OBJS_TOB3 ); readPermissionObjs( "RD-PRM-OBJS TOB4_UPD", PermTestData.OBJS_TOB4_UPD ); } /** * @param msg * @param pArray */ public static void readPermissionObjs( String msg, String[][] pArray ) { PermObj pObj = new PermObj(); LogUtil.logIt( msg ); try { ReviewMgr reviewMgr = getManagedReviewMgr(); for ( String[] objs : pArray ) { pObj = new PermObj(); pObj.setObjName( PermTestData.getName( objs ) ); PermObj entity = reviewMgr.readPermObj( pObj ); assertNotNull( entity ); PermTestData.assertEquals( entity, objs ); LOG.debug( "readPermissionObjs object name [" + pObj.getObjName() + "] successful" ); } } catch ( SecurityException ex ) { LOG.error( "readPermissionOps object name [" + pObj.getObjName() + "] caught SecurityException rc=" + ex.getErrorId() + ", msg=" + ex.getMessage() + ex ); fail( ex.getMessage() ); } } public void testFindPermissionObjs() { // public List<Permission> findPermissions(Permission permOp) searchPermissionObjs( "FND-PRM-OBJS TOB1", TestUtils.getSrchValue( PermTestData.getName( PermTestData.OBJS_TOB1[0] ) ), PermTestData.OBJS_TOB1 ); searchPermissionObjs( "FND-PRM-OBJS TOB2", TestUtils.getSrchValue( PermTestData.getName( PermTestData.OBJS_TOB2[0] ) ), PermTestData.OBJS_TOB2 ); searchPermissionObjs( "FND-PRM-OBJS TOB3", TestUtils.getSrchValue( PermTestData.getName( PermTestData.OBJS_TOB3[0] ) ), PermTestData.OBJS_TOB3 ); searchPermissionObjs( "FND-PRM-OBJS TOB4_UPD", TestUtils.getSrchValue( PermTestData.getName( PermTestData.OBJS_TOB4_UPD[0] ) ), PermTestData.OBJS_TOB4_UPD ); } /** * @param msg * @param srchValue * @param pArray */ public static void searchPermissionObjs( String msg, String srchValue, String[][] pArray ) { LogUtil.logIt( msg ); try { ReviewMgr reviewMgr = getManagedReviewMgr(); List<PermObj> objs = reviewMgr.findPermObjs( new PermObj( srchValue ) ); assertNotNull( objs ); assertTrue( CLS_NM + "searchPermissionObjs srchValue [" + srchValue + "] list size check", pArray.length == objs.size() ); for ( String[] obj : pArray ) { int indx = objs.indexOf( new PermObj( PermTestData.getName( obj ) ) ); if ( indx != -1 ) { PermObj entity = objs.get( indx ); assertNotNull( entity ); PermTestData.assertEquals( entity, obj ); LOG.debug( "searchPermissionObjs [" + entity.getObjName() + "] successful" ); } else { msg = "searchPermissionObjs srchValue [" + srchValue + "] failed list search"; LogUtil.logIt( msg ); fail( msg ); } } } catch ( SecurityException ex ) { LOG.error( "searchPermissionObjs srchValue [" + srchValue + "] caught SecurityException rc=" + ex.getErrorId() + ", msg=" + ex.getMessage(), ex ); fail( ex.getMessage() ); } } public void testReadRole() { // public Role readRole(Role role) readRoles( "RD-RLS TR1", RoleTestData.ROLES_TR1 ); readRoles( "RD-RLS TR2", RoleTestData.ROLES_TR2 ); readRoles( "RD-RLS TR3", RoleTestData.ROLES_TR3 ); readRoles( "RD-RLS TR4_UPD", RoleTestData.ROLES_TR4_UPD ); } /** * Determine if old fortress regression test cases are loaded in this directory and must be torn down. * * @param msg * @param rArray */ public static boolean teardownRequired( String msg, String[][] rArray ) { // default return is 'true': boolean tearDown = true; String methodName = ".teardownRequired"; LogUtil.logIt( msg ); try { ReviewMgr reviewMgr = getManagedReviewMgr(); for ( String[] rle : rArray ) { Role entity = reviewMgr.readRole( new Role( RoleTestData.getName( rle ) ) ); RoleTestData.assertEquals( entity, rle ); } // if we get to here it means that old test data must be removed from directory. } catch ( SecurityException ex ) { // This is the expected when teardown is not required: if ( ex.getErrorId() == GlobalErrIds.ROLE_NOT_FOUND ) { // did not find old test data no need to teardown tearDown = false; } else { // Something unexpected occurred here, Report as warning to the logger: String warning = methodName + " caught SecurityException=" + ex.getMessage(); LOG.warn( warning ); // TODO: Determine if it would be better to throw a SecurityException here. } } LOG.info( methodName + ":" + tearDown ); return tearDown; } /** * * @param msg * @param rArray */ public static void readRoles( String msg, String[][] rArray ) { LogUtil.logIt( msg ); try { ReviewMgr reviewMgr = getManagedReviewMgr(); for ( String[] rle : rArray ) { Role entity = reviewMgr.readRole( new Role( RoleTestData.getName( rle ) ) ); RoleTestData.assertEquals( entity, rle ); LOG.debug( "readRoles [" + entity.getName() + "] successful" ); } } catch ( SecurityException ex ) { LOG.error( "readRoles caught SecurityException=" + ex.getMessage(), ex ); fail( ex.getMessage() ); } } /** * RMT06 * * @throws org.apache.directory.fortress.core.SecurityException */ public void testFindRoles() { // public List<Role> findRoles(String searchVal) searchRoles( "SRCH-RLS TR1", TestUtils.getSrchValue( RoleTestData.getName( RoleTestData.ROLES_TR1[0] ) ), RoleTestData.ROLES_TR1 ); searchRoles( "SRCH-RLS TR2", TestUtils.getSrchValue( RoleTestData.getName( RoleTestData.ROLES_TR2[0] ) ), RoleTestData.ROLES_TR2 ); searchRoles( "SRCH-RLS TR3", TestUtils.getSrchValue( RoleTestData.getName( RoleTestData.ROLES_TR3[0] ) ), RoleTestData.ROLES_TR3 ); searchRoles( "SRCH-RLS TR4_UPD", TestUtils.getSrchValue( RoleTestData.getName( RoleTestData.ROLES_TR4[0] ) ), RoleTestData.ROLES_TR4_UPD ); } /** * * @param msg * @param srchValue * @param rArray */ public static void searchRoles( String msg, String srchValue, String[][] rArray ) { LogUtil.logIt( msg ); try { ReviewMgr reviewMgr = getManagedReviewMgr(); List<Role> roles = reviewMgr.findRoles( srchValue ); assertNotNull( roles ); assertTrue( CLS_NM + "searchRoles list size check", rArray.length == roles.size() ); for ( String[] rle : rArray ) { int indx = roles.indexOf( new Role( RoleTestData.getName( rle ) ) ); if ( indx != -1 ) { Role entity = roles.get( indx ); assertNotNull( entity ); RoleTestData.assertEquals( entity, rle ); LOG.debug( "searchRoles [" + entity.getName() + "] successful" ); } else { msg = "searchRoles srchValue [" + srchValue + "] failed list search"; LogUtil.logIt( msg ); fail( msg ); } } } catch ( SecurityException ex ) { LOG.error( "searchRoles srchValue [" + srchValue + "] caught SecurityException rc=" + ex.getErrorId() + ", msg=" + ex.getMessage(), ex ); fail( ex.getMessage() ); } } public void testReadUser() { // public User readUser(User user) readUsers( "READ-USRS TU1_UPD", UserTestData.USERS_TU1_UPD ); readUsers( "READ-USRS TU3", UserTestData.USERS_TU3 ); readUsers( "READ-USRS TU4", UserTestData.USERS_TU4 ); readUsers( "READ-USRS TU5", UserTestData.USERS_TU5 ); readUsers( "READ-USRS TU8", UserTestData.USERS_TU8_SSD ); readUsers( "READ-USRS TU9", UserTestData.USERS_TU9_SSD_HIER ); readUsers( "READ-USRS TU10", UserTestData.USERS_TU10_SSD_HIER ); readUsers( "READ-USRS TU11", UserTestData.USERS_TU11_SSD_HIER ); readUsers( "READ-USRS TU12", UserTestData.USERS_TU12_DSD ); readUsers( "READ-USRS TU13", UserTestData.USERS_TU13_DSD_HIER ); readUsers( "READ-USRS TU14", UserTestData.USERS_TU14_DSD_HIER ); readUsers( "READ-USRS TU15", UserTestData.USERS_TU15_DSD_HIER ); } /** * * @param msg * @param uArray */ public static void readUsers( String msg, String[][] uArray ) { LogUtil.logIt( msg ); try { ReviewMgr reviewMgr = getManagedReviewMgr(); for ( String[] usr : uArray ) { User entity = reviewMgr.readUser( new User( UserTestData.getUserId( usr ) ) ); assertNotNull( entity ); UserTestData.assertEquals( entity, usr ); LOG.debug( "readUsers userId [" + entity.getUserId() + "] successful" ); } } catch ( SecurityException ex ) { LOG.error( "readUsers caught SecurityException rc=" + ex.getErrorId() + ", msg=" + ex.getMessage(), ex ); fail( ex.getMessage() ); } } public void testFindUsers() { // public List<User> findUsers(User user) searchUsers( "SRCH-USRS TU1_UPD", TestUtils.getSrchValue( UserTestData.getUserId( UserTestData.USERS_TU1[0] ) ), UserTestData.USERS_TU1_UPD ); searchUsers( "SRCH-USRS TU3", TestUtils.getSrchValue( UserTestData.getUserId( UserTestData.USERS_TU3[0] ) ), UserTestData.USERS_TU3 ); searchUsers( "SRCH-USRS TU4", TestUtils.getSrchValue( UserTestData.getUserId( UserTestData.USERS_TU4[0] ) ), UserTestData.USERS_TU4 ); searchUsers( "SRCH-USRS TU5", TestUtils.getSrchValue( UserTestData.getUserId( UserTestData.USERS_TU5[0] ) ), UserTestData.USERS_TU5 ); searchUsers( "SRCH-USRS TU8", TestUtils.getSrchValue( UserTestData.getUserId( UserTestData.USERS_TU8_SSD[0] ) ), UserTestData.USERS_TU8_SSD ); searchUsers( "SRCH-USRS TU9", TestUtils.getSrchValue( UserTestData.getUserId( UserTestData.USERS_TU9_SSD_HIER[0] ) ), UserTestData.USERS_TU9_SSD_HIER ); searchUsers( "SRCH-USRS TU10", TestUtils.getSrchValue( UserTestData.getUserId( UserTestData.USERS_TU10_SSD_HIER[0] ) ), UserTestData.USERS_TU10_SSD_HIER ); searchUsers( "SRCH-USRS TU11", TestUtils.getSrchValue( UserTestData.getUserId( UserTestData.USERS_TU11_SSD_HIER[0] ) ), UserTestData.USERS_TU11_SSD_HIER ); searchUsers( "SRCH-USRS TU12", TestUtils.getSrchValue( UserTestData.getUserId( UserTestData.USERS_TU12_DSD[0] ) ), UserTestData.USERS_TU12_DSD ); searchUsers( "SRCH-USRS TU13", TestUtils.getSrchValue( UserTestData.getUserId( UserTestData.USERS_TU13_DSD_HIER[0] ) ), UserTestData.USERS_TU13_DSD_HIER ); searchUsers( "SRCH-USRS TU14", TestUtils.getSrchValue( UserTestData.getUserId( UserTestData.USERS_TU14_DSD_HIER[0] ) ), UserTestData.USERS_TU14_DSD_HIER ); searchUsers( "SRCH-USRS TU15", TestUtils.getSrchValue( UserTestData.getUserId( UserTestData.USERS_TU15_DSD_HIER[0] ) ), UserTestData.USERS_TU15_DSD_HIER ); } /** * * @param msg * @param srchValue * @param uArray */ public static void searchUsers( String msg, String srchValue, String[][] uArray ) { LogUtil.logIt( msg ); try { ReviewMgr reviewMgr = getManagedReviewMgr(); List<User> users = reviewMgr.findUsers( new User( srchValue ) ); assertNotNull( users ); assertTrue( "searchUsers list size check", uArray.length == users.size() ); for ( String[] usr : uArray ) { int indx = users.indexOf( new User( UserTestData.getUserId( usr ) ) ); if ( indx != -1 ) { User entity = users.get( indx ); assertNotNull( entity ); UserTestData.assertEquals( entity, usr ); LOG.debug( "searchUsers userId [" + entity.getUserId() + "] successful" ); } else { msg = "searchUsers srchValue [" + srchValue + "] failed list search"; LogUtil.logIt( msg ); fail( msg ); } } } catch ( SecurityException ex ) { LOG.error( "searchUsers srchValue [" + srchValue + "] caught SecurityException rc=" + ex.getErrorId() + ", msg=" + ex.getMessage(), ex ); fail( ex.getMessage() ); } } public void testAssignedRoles() { // public List<UserRole> assignedRoles(User userId) assignedRoles( "ASGN-RLS TU1_UPD TR1", UserTestData.USERS_TU1_UPD, RoleTestData.ROLES_TR1 ); //assignedRoles("ASGN-RLS TU3 TR2", UserTestData.USERS_TU3, RoleTestData.ROLES_TR2); assignedRoles( "ASGN-RLS TU4 TR2", UserTestData.USERS_TU4, RoleTestData.ROLES_TR2 ); assignedRoles( "ASGN-RLS TU3 TR3", UserTestData.USERS_TU3, RoleTestData.ROLES_TR3 ); } /** * @param msg * @param uArray * @param rArray */ public static void assignedRoles( String msg, String[][] uArray, String[][] rArray ) { LogUtil.logIt( msg ); try { ReviewMgr reviewMgr = getManagedReviewMgr(); for ( String[] usr : uArray ) { User user = reviewMgr.readUser( new User( UserTestData.getUserId( usr ) ) ); assertNotNull( user ); List<UserRole> uRoles = reviewMgr.assignedRoles( user ); assertTrue( CLS_NM + "assignedRoles list size check", rArray.length == uRoles.size() ); for ( String[] url : rArray ) { int indx = uRoles.indexOf( RoleTestData.getUserRole( UserTestData.getUserId( usr ), url ) ); if ( indx != -1 ) { UserRole uRole = uRoles.get( indx ); assertNotNull( uRole ); RoleTestData.assertEquals( UserTestData.getUserId( usr ), uRole, url ); LOG.debug( "assignedRoles userId [" + uRole.getUserId() + "] role [" + uRole.getName() + "] successful" ); } else { msg = "assignedRoles userId [" + user.getUserId() + "] role [" + RoleTestData.getName( url ) + "] failed list search"; LogUtil.logIt( msg ); fail( msg ); } } } } catch ( SecurityException ex ) { LOG.error( "assignedRoles caught SecurityException rc=" + ex.getErrorId() + ", msg=" + ex.getMessage(), ex ); fail( ex.getMessage() ); } } /** * */ public void testAuthorizedRoles() { // public Set<String> authorizedRoles(User user) authorizedRoles( "AUTHZ-RLS TU18 TR6 DESC", UserTestData.USERS_TU18U_TR6_DESC ); authorizedRoles( "AUTHZ-RLS TU19 TR7 ASC", UserTestData.USERS_TU19U_TR7_ASC ); } /** * * @param msg * @param uArray */ public static void authorizedRoles( String msg, String[][] uArray ) { LogUtil.logIt( msg ); try { ReviewMgr reviewMgr = getManagedReviewMgr(); for ( String[] usr : uArray ) { User user = reviewMgr.readUser( new User( UserTestData.getUserId( usr ) ) ); assertNotNull( user ); // Get the authorized roles for this user: Collection<String> authZRoles = UserTestData.getAuthorizedRoles( usr ); // If there are any assigned roles, add them to list of authorized. Set<String> asgnRoles = UserTestData.getAssignedRoles( usr ); assertNotNull( asgnRoles ); assertTrue( asgnRoles.size() > 0 ); for ( String asgnRole : asgnRoles ) { authZRoles.add( asgnRole ); } // Retrieve actual roles authorized to User according to LDAP: Set<String> actualRoles = reviewMgr.authorizedRoles( user ); assertNotNull( actualRoles ); assertTrue( actualRoles.size() > 0 ); // The two list sizes better match or fail the test case. assertTrue( CLS_NM + "authorizedRoles list size test case", authZRoles.size() == actualRoles.size() ); // For each authorized role found in User test data, check to see if it was found in LDAP for User. If not fail the test case. for ( String roleName : authZRoles ) { assertTrue( CLS_NM + ".authorizedRoles userId [" + user.getUserId() + "] role [" + roleName + "] not found", actualRoles.contains( roleName ) ); } } } catch ( SecurityException ex ) { LOG.error( "assignedRoles caught SecurityException rc=" + ex.getErrorId() + ", msg=" + ex.getMessage(), ex ); fail( ex.getMessage() ); } } public void testAuthorizedUsers() { // public List<User> authorizedUsers(Role role) authorizedUsers( "ATHZ-USRS TR1 TU1_UPD", RoleTestData.ROLES_TR1, UserTestData.USERS_TU1_UPD ); authorizedUsers( "ATHZ-USRS TR2 TU4", RoleTestData.ROLES_TR2, UserTestData.USERS_TU4 ); authorizedUsers( "ATHZ-USRS TR3 TU3", RoleTestData.ROLES_TR3, UserTestData.USERS_TU3 ); } /** * @param msg * @param rArray * @param uArray */ public static void authorizedUsers( String msg, String[][] rArray, String[][] uArray ) { LogUtil.logIt( msg ); try { ReviewMgr reviewMgr = getManagedReviewMgr(); for ( String[] rle : rArray ) { List<User> users = reviewMgr.authorizedUsers( new Role( RoleTestData.getName( rle ) ) ); assertNotNull( users ); //LOG.debug("authorizedUsers list source size=" + uArray.length + " ldap size=" + users.size()); assertTrue( CLS_NM + "authorizedUsers list size check", uArray.length == users.size() ); for ( String[] usr : uArray ) { int indx = users.indexOf( UserTestData.getUser( usr ) ); if ( indx != -1 ) { User user = users.get( indx ); assertNotNull( user ); UserTestData.assertEquals( user, usr ); LOG.debug( "authorizedUsers role name [" + RoleTestData.getName( rle ) + "] userId [" + user.getUserId() + "] successful" ); } else { msg = "authorizedUsers role [" + RoleTestData.getName( rle ) + "] user [" + UserTestData.getUserId( usr ) + "] failed list search"; LogUtil.logIt( msg ); fail( msg ); } } } } catch ( SecurityException ex ) { LOG.error( "authorizedUsers caught SecurityException rc=" + ex.getErrorId() + ", msg=" + ex.getMessage(), ex ); fail( ex.getMessage() ); } } public void testAuthorizedUsersHier() { // public List<User> authorizedUsers(Role role) authorizedUsersHier( "ATHZ-USRS-HIER TR6 TU18", RoleTestData.TR6_AUTHORIZED_USERS ); authorizedUsersHier( "ATHZ-USRS-HIER TR7 TU19", RoleTestData.TR7_AUTHORIZED_USERS ); } /** * * @param msg * @param roleMap */ public static void authorizedUsersHier( String msg, Map roleMap ) { LogUtil.logIt( msg ); try { ReviewMgr reviewMgr = getManagedReviewMgr(); // create iterator based on rolemap: // iterate over every role entry found in map: for ( Object o : roleMap.entrySet() ) { Map.Entry pairs = ( Map.Entry ) o; String roleName = ( String ) pairs.getKey(); String szValidUsers = ( String ) pairs.getValue(); Set<String> userSet = TestUtils.getSets( szValidUsers ); assertNotNull( userSet ); assertTrue( userSet.size() > 0 ); List<User> actualUsers = reviewMgr.authorizedUsers( new Role( roleName ) ); assertNotNull( actualUsers ); assertTrue( actualUsers.size() > 0 ); // Ensure the two list sizes match or fail the test case. assertTrue( CLS_NM + "authorizedUsersHier failed list size test case", userSet.size() == actualUsers.size() ); // for each valid user expected, ensure it actually pulled from API: for ( String userId : userSet ) { User validUser = new User( userId ); assertTrue( CLS_NM + ".authorizedUsersHier failed authorizedUsers test, role [" + roleName + "] does not have user [" + validUser.getUserId() + "] as authorized", actualUsers.contains( validUser ) ); } } } catch ( SecurityException ex ) { LOG.error( "authorizedUsersHier caught SecurityException rc=" + ex.getErrorId() + ", msg=" + ex.getMessage(), ex ); fail( ex.getMessage() ); } } public void testRolePermissions() { // public List<Permission> rolePermissions(Role role) rolePermissions( "ATHRZ-RLE-PRMS TR1 TOB1 TOP1_UPD", RoleTestData.ROLES_TR1, PermTestData.OBJS_TOB1, PermTestData.OPS_TOP1_UPD ); } /** * @param msg * @param rArray * @param pObjArray * @param pOpArray */ public static void rolePermissions( String msg, String[][] rArray, String[][] pObjArray, String[][] pOpArray ) { LogUtil.logIt( msg ); try { ReviewMgr reviewMgr = getManagedReviewMgr(); for ( String[] rle : rArray ) { Role role = RoleTestData.getRole( rle ); List<Permission> perms = reviewMgr.rolePermissions( role ); assertNotNull( perms ); assertTrue( CLS_NM + "rolePermissions list size check", pOpArray.length * pObjArray.length == perms.size() ); for ( String[] obj : pObjArray ) { for ( String[] op : pOpArray ) { int indx = perms.indexOf( new Permission( PermTestData.getName( obj ), PermTestData.getName( op ), PermTestData.getObjId( op ) ) ); if ( indx != -1 ) { Permission pOp = perms.get( indx ); assertNotNull( pOp ); PermTestData.assertEquals( PermTestData.getName( obj ), pOp, op ); LOG.debug( "rolePermissions role name [" + role.getName() + "] perm objName [" + PermTestData.getName( obj ) + "] operationName [" + PermTestData.getName( op ) + "] successful" ); } else { msg = "rolePermissions role name [" + role.getName() + "] perm objName [" + PermTestData.getName( obj ) + "] operationName [" + PermTestData.getName( op ) + "] failed list search"; LogUtil.logIt( msg ); fail( msg ); } } } } } catch ( SecurityException ex ) { LOG.error( "rolePermissions caught SecurityException rc=" + ex.getErrorId() + ", msg=" + ex.getMessage(), ex ); fail( ex.getMessage() ); } } public void testPermissionRoles() { // public List<Role> permissionRoles(Permission perm) permissionRoles( "PRM-RLS TOB1 TOP1 TR1", PermTestData.OBJS_TOB1, PermTestData.OPS_TOP1, RoleTestData.ROLES_TR1 ); } /** * @param msg * @param pObjArray * @param pOpArray * @param rArray */ public static void permissionRoles( String msg, String[][] pObjArray, String[][] pOpArray, String[][] rArray ) { LogUtil.logIt( msg ); Permission pOp; try { ReviewMgr reviewMgr = getManagedReviewMgr(); for ( String[] obj : pObjArray ) { for ( String[] op : pOpArray ) { pOp = new Permission(); pOp.setObjName( PermTestData.getName( obj ) ); pOp.setOpName( PermTestData.getName( op ) ); pOp.setObjId( PermTestData.getObjId( op ) ); List<String> roles = reviewMgr.permissionRoles( pOp ); assertNotNull( roles ); assertTrue( CLS_NM + "permissionRoles permission object [" + pOp.getObjName() + "] operationName [" + pOp.getOpName() + "] objectId [" + pOp.getObjId() + "]", rArray.length == roles.size() ); for ( String[] rle : rArray ) { int indx = roles.indexOf( RoleTestData.getName( rle ) ); if ( indx != -1 ) { String roleNm = roles.get( indx ); assertEquals( CLS_NM + ".permissionRoles failed compare role name", RoleTestData.getName( rle ), roleNm ); LOG.debug( ".permissionRoles permission objName [" + pOp.getObjName() + "] operationName [" + pOp.getOpName() + "] objectId [" + pOp.getObjId() + "] roleNm [" + roleNm + "] successful" ); } else { msg = "permissionRoles permission objName [" + pOp.getObjName() + "] operationName [" + pOp.getOpName() + "] objectId [" + pOp.getObjId() + "] role [" + RoleTestData.getName( rle ) + "] failed list search"; LogUtil.logIt( msg ); fail( msg ); } } } } } catch ( SecurityException ex ) { LOG.error( "permissionRoles caught SecurityException rc=" + ex.getErrorId() + ", msg=" + ex.getMessage(), ex ); fail( ex.getMessage() ); } } /** * */ public void testAuthorizedPermissionRoles() { // public Set<String> authorizedPermissionRoles(Permission perm) authorizedPermissionRoles( "AUTHZ PRM-RLES TOB6 TOP5 TR5B", PermTestData.OBJS_TOB6, PermTestData.OPS_TOP5, RoleTestData.ROLES_TR5B ); } /** * * @param msg * @param pObjArray * @param pOpArray * @param rArray */ public static void authorizedPermissionRoles( String msg, String[][] pObjArray, String[][] pOpArray, String[][] rArray ) { LogUtil.logIt( msg ); Permission pOp; try { ReviewMgr reviewMgr = getManagedReviewMgr(); for ( String[] obj : pObjArray ) { int i = 0; for ( String[] op : pOpArray ) { pOp = new Permission(); pOp.setObjName( PermTestData.getName( obj ) ); pOp.setOpName( PermTestData.getName( op ) ); pOp.setObjId( PermTestData.getObjId( op ) ); Set<String> roles = reviewMgr.authorizedPermissionRoles( pOp ); assertNotNull( roles ); int expectedAuthZedRoles = i + 1; assertTrue( CLS_NM + "authorizedPermissionRoles permission object [" + pOp.getObjName() + "] operationName [" + pOp.getOpName() + "] objectId [" + pOp.getObjId() + "]", expectedAuthZedRoles == roles.size() ); int j = 1; for ( String[] rle : rArray ) { String roleName = RoleTestData.getName( rle ); if ( j++ <= expectedAuthZedRoles ) { assertTrue( CLS_NM + "authorizedPermissionRoles roleName [" + roleName + "] should be authorized for operationName [" + pOp.getOpName() + "] objectId [" + pOp.getObjId() + "]", roles.contains( roleName ) ); } else { assertTrue( CLS_NM + "authorizedPermissionRoles roleName [" + roleName + "] should not be authorized for operationName [" + pOp.getOpName() + "] objectId [" + pOp.getObjId() + "]", !roles.contains( roleName ) ); } } i++; } } } catch ( SecurityException ex ) { LOG.error( "authorizedPermissionRoles caught SecurityException rc=" + ex.getErrorId() + ", msg=" + ex.getMessage(), ex ); fail( ex.getMessage() ); } } public void testPermissionUsers() { // public List<User> permissionUsers(Permission perm) permissionUsers( "PRM-USRS TOB1 TOP1 TU1_UPD", PermTestData.OBJS_TOB1, PermTestData.OPS_TOP1, UserTestData.USERS_TU1_UPD ); } /** * @param msg * @param pObjArray * @param pOpArray * @param uArray */ public static void permissionUsers( String msg, String[][] pObjArray, String[][] pOpArray, String[][] uArray ) { LogUtil.logIt( msg ); Permission pOp; try { ReviewMgr reviewMgr = getManagedReviewMgr(); for ( String[] obj : pObjArray ) { for ( String[] op : pOpArray ) { pOp = new Permission(); pOp.setObjName( PermTestData.getName( obj ) ); pOp.setOpName( PermTestData.getName( op ) ); pOp.setObjId( PermTestData.getObjId( op ) ); List<String> users = reviewMgr.permissionUsers( pOp ); assertNotNull( users ); assertTrue( CLS_NM + "permissionUsers permission object [" + pOp.getObjName() + "] operationName [" + pOp.getOpName() + "] objectId [" + pOp.getObjId() + "]", uArray.length == users.size() ); for ( String[] usr : uArray ) { int indx = users.indexOf( RoleTestData.getName( usr ) ); if ( indx != -1 ) { String userId = users.get( indx ); assertEquals( CLS_NM + ".permissionUsers failed compare userId", UserTestData.getUserId( usr ), userId ); LOG.debug( "permissionUsers permission objName [" + pOp.getObjName() + "] operationName [" + pOp.getOpName() + "] objectId [" + pOp.getObjId() + "] userId [" + userId + "] successful" ); } else { msg = "permissionUsers permission objName [" + pOp.getObjName() + "] operationName [" + pOp.getOpName() + "] objectId [" + pOp.getObjId() + "] userId [" + UserTestData.getUserId( usr ) + "] failed list search"; LogUtil.logIt( msg ); fail( msg ); } } } } } catch ( SecurityException ex ) { LOG.error( "permissionUsers caught SecurityException rc=" + ex.getErrorId() + ", msg=" + ex.getMessage(), ex ); fail( ex.getMessage() ); } } /** * */ public void testAuthorizedPermissionUsers() { // public Set<String> authorizedPermissionUsers(Permission perm) authorizedPermissionUsers( "AUTHZ PRM-USRS TOB6 TOP5 TU20", PermTestData.OBJS_TOB6, PermTestData.OPS_TOP5, UserTestData.USERS_TU20U_TR5B ); } /** * * @param msg * @param pObjArray * @param pOpArray * @param uArray */ public static void authorizedPermissionUsers( String msg, String[][] pObjArray, String[][] pOpArray, String[][] uArray ) { LogUtil.logIt( msg ); Permission pOp; try { ReviewMgr reviewMgr = getManagedReviewMgr(); for ( String[] obj : pObjArray ) { int i = 0; for ( String[] op : pOpArray ) { pOp = new Permission(); pOp.setObjName( PermTestData.getName( obj ) ); pOp.setOpName( PermTestData.getName( op ) ); pOp.setObjId( PermTestData.getObjId( op ) ); Set<String> users = reviewMgr.authorizedPermissionUsers( pOp ); assertNotNull( users ); int expectedAuthZedUsers = i + 1; assertTrue( CLS_NM + "authorizedPermissionUsers permission object [" + pOp.getObjName() + "] operationName [" + pOp.getOpName() + "] objectId [" + pOp.getObjId() + "]", expectedAuthZedUsers == users.size() ); int j = 1; for ( String[] usr : uArray ) { String userId = UserTestData.getUserId( usr ); if ( j++ <= expectedAuthZedUsers ) { assertTrue( CLS_NM + "authorizedPermissionUsers userId [" + userId + "] should be authorized for operationName [" + pOp.getOpName() + "] objectId [" + pOp.getObjId() + "]", users.contains( userId ) ); } else { assertTrue( CLS_NM + "authorizedPermissionUsers userId [" + userId + "] should not be authorized for operationName [" + pOp.getOpName() + "] objectId [" + pOp.getObjId() + "]", !users.contains( userId ) ); } } i++; } } } catch ( SecurityException ex ) { LOG.error( "authorizedPermissionUsers caught SecurityException rc=" + ex.getErrorId() + ", msg=" + ex.getMessage(), ex ); fail( ex.getMessage() ); } } public void testUserPermissions() { // public List <Permission> userPermissions(User user) userPermissions( "USR-PRMS TU1_UPD TOB1 TOP1_UPD", UserTestData.USERS_TU1_UPD, PermTestData.OBJS_TOB1, PermTestData.OPS_TOP1_UPD ); userPermissions( "USR-PRMS TU3 TOB3 TOP3", UserTestData.USERS_TU3, PermTestData.OBJS_TOB3, PermTestData.OPS_TOP3 ); userPermissions( "USR-PRMS TU4 TOB2 TOP2", UserTestData.USERS_TU4, PermTestData.OBJS_TOB2, PermTestData.OPS_TOP2 ); } /** * @param msg * @param uArray * @param pObjArray * @param pOpArray */ public static void userPermissions( String msg, String[][] uArray, String[][] pObjArray, String[][] pOpArray ) { LogUtil.logIt( msg ); try { ReviewMgr reviewMgr = getManagedReviewMgr(); for ( String[] usr : uArray ) { User user = UserTestData.getUser( usr ); List<Permission> perms = reviewMgr.userPermissions( user ); assertNotNull( perms ); assertTrue( CLS_NM + "userPermissions list size check", pOpArray.length * pObjArray.length == perms.size() ); for ( String[] obj : pObjArray ) { for ( String[] op : pOpArray ) { int indx = perms.indexOf( new Permission( PermTestData.getName( obj ), PermTestData.getName( op ), PermTestData.getObjId( op ) ) ); if ( indx != -1 ) { Permission pOp = perms.get( indx ); assertNotNull( pOp ); PermTestData.assertEquals( PermTestData.getName( obj ), pOp, op ); LOG.debug( "userPermissions userId [" + user.getUserId() + "] perm objName [" + PermTestData.getName( obj ) + "] operationName [" + PermTestData.getName( op ) + "] successful" ); } else { msg = "userPermissions userId [" + user.getUserId() + "] perm objName [" + PermTestData.getName( obj ) + "] operationName [" + PermTestData.getName( op ) + "] failed list search"; LogUtil.logIt( msg ); fail( msg ); } } } } } catch ( SecurityException ex ) { LOG.error( "userPermissions caught SecurityException rc=" + ex.getErrorId() + ", msg=" + ex.getMessage(), ex ); fail( ex.getMessage() ); } } public void testFindRoleNms() { // public List<String> findRoles(String searchVal, int limit) searchRolesNms( "SRCH-RLNMS TR1", TestUtils.getSrchValue( RoleTestData.getName( RoleTestData.ROLES_TR1[0] ) ), RoleTestData.ROLES_TR1 ); searchRolesNms( "SRCH-RLNMS TR2", TestUtils.getSrchValue( RoleTestData.getName( RoleTestData.ROLES_TR2[0] ) ), RoleTestData.ROLES_TR2 ); searchRolesNms( "SRCH-RLNMS TR3", TestUtils.getSrchValue( RoleTestData.getName( RoleTestData.ROLES_TR3[0] ) ), RoleTestData.ROLES_TR3 ); searchRolesNms( "SRCH-RLNMS TR4_UPD", TestUtils.getSrchValue( RoleTestData.getName( RoleTestData.ROLES_TR4[0] ) ), RoleTestData.ROLES_TR4_UPD ); } /** * * @param msg * @param srchValue * @param rArray */ public static void searchRolesNms( String msg, String srchValue, String[][] rArray ) { LogUtil.logIt( msg ); try { ReviewMgr reviewMgr = getManagedReviewMgr(); List<String> roles = reviewMgr.findRoles( srchValue, rArray.length ); assertNotNull( roles ); assertTrue( CLS_NM + "searchRolesNms list size check", rArray.length == roles.size() ); for ( String[] rle : rArray ) { int indx = roles.indexOf( RoleTestData.getName( rle ) ); if ( indx != -1 ) { String roleNm = roles.get( indx ); assertNotNull( roleNm ); assertEquals( CLS_NM + ".searchRolesNms failed compare role name", RoleTestData.getName( rle ), roleNm ); } else { msg = "searchRolesNms srchValue [" + srchValue + "] failed list search"; LogUtil.logIt( msg ); fail( msg ); } } } catch ( SecurityException ex ) { LOG.error( "searchRolesNms srchValue [" + srchValue + "] caught SecurityException rc=" + ex.getErrorId() + ", msg=" + ex.getMessage(), ex ); fail( ex.getMessage() ); } } public void testFindUserIds() { // public List<String> findUsers(User user, int limit) searchUserIds( "SRCH-USRIDS TU1_UPD", TestUtils.getSrchValue( UserTestData.getUserId( UserTestData.USERS_TU1[0] ) ), UserTestData.USERS_TU1_UPD ); searchUserIds( "SRCH-USRIDS TU3", TestUtils.getSrchValue( UserTestData.getUserId( UserTestData.USERS_TU3[0] ) ), UserTestData.USERS_TU3 ); searchUserIds( "SRCH-USRIDS TU4", TestUtils.getSrchValue( UserTestData.getUserId( UserTestData.USERS_TU4[0] ) ), UserTestData.USERS_TU4 ); } /** * * @param msg * @param srchValue * @param uArray */ public static void searchUserIds( String msg, String srchValue, String[][] uArray ) { LogUtil.logIt( msg ); try { ReviewMgr reviewMgr = getManagedReviewMgr(); List<String> users = reviewMgr.findUsers( new User( srchValue ), uArray.length ); assertNotNull( users ); assertTrue( CLS_NM + "searchUserIds list size check", uArray.length == users.size() ); for ( String[] usr : uArray ) { int indx = users.indexOf( UserTestData.getUserId( usr ) ); if ( indx != -1 ) { String userId = users.get( indx ); assertNotNull( userId ); assertEquals( CLS_NM + ".searchUserIds failed compare user userId", UserTestData.getUserId( usr ) .toUpperCase(), userId.toUpperCase() ); } else { msg = "searchUserIds srchValue [" + srchValue + "] failed list search"; LogUtil.logIt( msg ); fail( msg ); } } } catch ( SecurityException ex ) { LOG.error( "searchUserIds srchValue [" + srchValue + "] caught SecurityException rc=" + ex.getErrorId() + ", msg=" + ex.getMessage(), ex ); fail( ex.getMessage() ); } } public void testAuthorizedUserIds() { // public List<String> authorizedUsers(Role role, int limit) assignedUserIds( "ATHZ-USRS TR1 TU1_UPD", RoleTestData.ROLES_TR1, UserTestData.USERS_TU1_UPD ); assignedUserIds( "ATHZ-USRS TR2 TU4", RoleTestData.ROLES_TR2, UserTestData.USERS_TU4 ); assignedUserIds( "ATHZ-USRS TR3 TU3", RoleTestData.ROLES_TR3, UserTestData.USERS_TU3 ); } /** * @param msg * @param rArray * @param uArray */ public static void assignedUserIds( String msg, String[][] rArray, String[][] uArray ) { LogUtil.logIt( msg ); try { ReviewMgr reviewMgr = getManagedReviewMgr(); for ( String[] rle : rArray ) { List<String> users = reviewMgr.assignedUsers( new Role( RoleTestData.getName( rle ) ), uArray.length ); assertNotNull( users ); assertTrue( CLS_NM + ".assignedUserIds list size check", uArray.length == users.size() ); for ( String[] usr : uArray ) { users.indexOf( UserTestData.getUserId( usr ) ); // todo - figure out how to compare userid dns with userids: } } } catch ( SecurityException ex ) { LOG.error( "assignedUserIds caught SecurityException rc=" + ex.getErrorId() + ", msg=" + ex.getMessage(), ex ); fail( ex.getMessage() ); } } public void testAssignedRoleNms() { // public List<String> assignedRoles(String userId) assignedRoleNms( "ASGN-RLS TU1_UPD TR1", UserTestData.USERS_TU1_UPD, RoleTestData.ROLES_TR1 ); //assignedRoles("ASGN-RLS TU3 TR2", UserTestData.USERS_TU3, RoleTestData.ROLES_TR2); assignedRoleNms( "ASGN-RLS TU4 TR2", UserTestData.USERS_TU4, RoleTestData.ROLES_TR2 ); assignedRoleNms( "ASGN-RLS TU3 TR3", UserTestData.USERS_TU3, RoleTestData.ROLES_TR3 ); } /** * @param msg * @param uArray * @param rArray */ public static void assignedRoleNms( String msg, String[][] uArray, String[][] rArray ) { LogUtil.logIt( msg ); try { ReviewMgr reviewMgr = getManagedReviewMgr(); for ( String[] usr : uArray ) { List<String> uRoles = reviewMgr.assignedRoles( UserTestData.getUserId( usr ) ); assertNotNull( uRoles ); assertTrue( CLS_NM + "assignedRoleNms list size check", rArray.length == uRoles.size() ); for ( String[] url : rArray ) { int indx = uRoles.indexOf( RoleTestData.getName( url ) ); if ( indx != -1 ) { String uRole = uRoles.get( indx ); assertNotNull( uRole ); assertEquals( CLS_NM + ".assignedRoleNms failed compare role name", RoleTestData.getName( url ), uRole ); } else { msg = "assignedRoleNms userId [" + UserTestData.getUserId( usr ) + "] role [" + RoleTestData.getName( url ) + "] failed list search"; LogUtil.logIt( msg ); fail( msg ); } } } } catch ( SecurityException ex ) { LOG.error( "assignedRoleNms caught SecurityException rc=" + ex.getErrorId() + ", msg=" + ex.getMessage(), ex ); fail( ex.getMessage() ); } } public void testFindSsdSets() { searchSsdSets( "SRCH-SSD T1", TestUtils.getSrchValue( RoleTestData.getName( RoleTestData.SSD_T1[0] ), RoleTestData.getName( RoleTestData.SSD_T1[0] ).length() - 1 ), RoleTestData.SSD_T1 ); searchSsdSets( "SRCH-SSD T4", TestUtils.getSrchValue( RoleTestData.getName( RoleTestData.SSD_T4[0] ), RoleTestData.getName( RoleTestData.SSD_T4[0] ).length() - 1 ), RoleTestData.SSD_T4 ); searchSsdSets( "SRCH-SSD T5", TestUtils.getSrchValue( RoleTestData.getName( RoleTestData.SSD_T5[0] ), RoleTestData.getName( RoleTestData.SSD_T5[0] ).length() - 1 ), RoleTestData.SSD_T5 ); searchSsdSets( "SRCH-SSD T6", TestUtils.getSrchValue( RoleTestData.getName( RoleTestData.SSD_T6[0] ), RoleTestData.getName( RoleTestData.SSD_T6[0] ).length() - 1 ), RoleTestData.SSD_T6 ); } /** * * @param msg * @param srchValue * @param sArray */ public static void searchSsdSets( String msg, String srchValue, String[][] sArray ) { LogUtil.logIt( msg ); try { ReviewMgr reviewMgr = getManagedReviewMgr(); SDSet sdSet = new SDSet(); sdSet.setName( srchValue ); List<SDSet> sdSetList = reviewMgr.ssdSets( sdSet ); assertNotNull( sdSetList ); } catch ( SecurityException ex ) { LOG.error( "searchRoles searchSsdSets [" + srchValue + "] caught SecurityException rc=" + ex.getErrorId() + ", msg=" + ex.getMessage(), ex ); fail( ex.getMessage() ); } } public void testFindDsdSets() { searchDsdSets( "SRCH-DSD T1", TestUtils.getSrchValue( RoleTestData.getName( RoleTestData.DSD_T1[0] ), RoleTestData.getName( RoleTestData.DSD_T1[0] ).length() - 1 ), RoleTestData.DSD_T1 ); searchDsdSets( "SRCH-DSD T4", TestUtils.getSrchValue( RoleTestData.getName( RoleTestData.DSD_T4[0] ), RoleTestData.getName( RoleTestData.DSD_T4[0] ).length() - 1 ), RoleTestData.DSD_T4 ); searchDsdSets( "SRCH-DSD T5", TestUtils.getSrchValue( RoleTestData.getName( RoleTestData.DSD_T5[0] ), RoleTestData.getName( RoleTestData.DSD_T5[0] ).length() - 1 ), RoleTestData.DSD_T5 ); searchDsdSets( "SRCH-DSD T6", TestUtils.getSrchValue( RoleTestData.getName( RoleTestData.DSD_T6[0] ), RoleTestData.getName( RoleTestData.DSD_T6[0] ).length() - 1 ), RoleTestData.DSD_T6 ); } /** * * @param msg * @param srchValue * @param sArray */ public static void searchDsdSets( String msg, String srchValue, String[][] sArray ) { LogUtil.logIt( msg ); try { ReviewMgr reviewMgr = getManagedReviewMgr(); SDSet sdSet = new SDSet(); sdSet.setName( srchValue ); List<SDSet> sdSetList = reviewMgr.ssdSets( sdSet ); assertNotNull( sdSetList ); } catch ( SecurityException ex ) { LOG.error( "searchRoles searchDsdSets [" + srchValue + "] caught SecurityException rc=" + ex.getErrorId() + ", msg=" + ex.getMessage(), ex ); fail( ex.getMessage() ); } } public void testReadUserRoleConstraint() { readUserRoleConstraint( "RD-URC TU1 TR1", UserTestData.USERS_TU1[0], RoleTestData.ROLES_TR1[1], URATestData .getRC( URATestData.URC_T1 ) ); } public static void readUserRoleConstraint( String msg, String[] usr, String[] rle, RoleConstraint rc ) { LogUtil.logIt( msg ); try { ReviewMgr reviewMgr = getManagedReviewMgr(); User user = UserTestData.getUser( usr ); Role role = RoleTestData.getRole( rle ); List<UserRole> urs = reviewMgr.assignedRoles(user); boolean uraFound = false; boolean urcFound = false; for(UserRole ur : urs){ if(ur.getName().equals(role.getName())){ uraFound = true; List<RoleConstraint> rcs = ur.getRoleConstraints(); for(RoleConstraint r : rcs){ if(r.getKey().equals(rc.getKey())){ urcFound = true; assertEquals(rc.getType(), r.getType()); assertEquals(rc.getValue(), r.getValue()); assertNotNull( r.getId() ); } } } } if(!uraFound){ fail("User Role Assignment Not Found"); } if(!urcFound){ fail("User Role Constraint Not Found"); } LOG.debug( "readUserRoleConstraint value [" + rc.getValue() + "] successful" ); } catch ( SecurityException ex ) { LOG.error( "readUserRoleConstraint value [" + rc.getValue() + "] caught SecurityException rc=" + ex.getErrorId() + ", msg=" + ex.getMessage(), ex ); fail( ex.getMessage() ); } } public void testAssignedUserRoleConstraints() { assignUserRoleConstraints( "ASSGN-USER-ROLE-CONSTRAINTS TR18 ABAC", RoleTestData.ROLE_CONSTRAINTS_TR18_ABAC ); assignUserRoleConstraintsKey( "ASSGN-USER-ROLE-CONSTRAINTS WKEY TR18 ABAC", RoleTestData.ROLE_CONSTRAINTS_TR18_ABAC ); } private void assignUserRoleConstraints( String msg, String[][] urArray ) { LogUtil.logIt( msg ); try { ReviewMgr reviewMgr = ReviewMgrImplTest.getManagedReviewMgr(); for ( String[] urConstraint : urArray ) { UserRole uRole = RoleTestData.getUserRoleConstraintAbac( urConstraint ); RoleConstraint constraint = uRole.getConstraints().get( 0 ); List<User> users = reviewMgr.assignedUsers( new Role( uRole.getName() ), constraint ); assertTrue( users.size() > 0 ); } } catch ( SecurityException ex ) { LOG.error( "assignUserRoleConstraints caught SecurityException rc=" + ex.getErrorId() + ", msg=" + ex.getMessage(), ex ); fail( ex.getMessage() ); } } private void assignUserRoleConstraintsKey( String msg, String[][] urArray ) { LogUtil.logIt( msg ); try { ReviewMgr reviewMgr = ReviewMgrImplTest.getManagedReviewMgr(); for ( String[] urConstraint : urArray ) { UserRole uRole = RoleTestData.getUserRoleConstraintAbac( urConstraint ); RoleConstraint constraint = uRole.getConstraints().get( 0 ); List<UserRole> uRoles = reviewMgr.assignedUsers( new Role( uRole.getName() ), RoleConstraint.RCType.USER, constraint.getKey()); assertTrue( "curly, moe, larry", uRoles.size() == 3 ); } } catch ( SecurityException ex ) { LOG.error( "assignUserRoleConstraintsKey caught SecurityException rc=" + ex.getErrorId() + ", msg=" + ex.getMessage(), ex ); fail( ex.getMessage() ); } } public void testFindRoleConstraints() { findRoleConstraints( "SRCH-RCS TU1 TR1", UserTestData.USERS_TU1[0][0], PermTestData.getOp("TOB1_1", PermTestData.OPS_TOP1_UPD[0]), URATestData.getRC(URATestData.URC_T1).getType() ); findUserRoleWithConstraints( "SRCH-RCS TR1", RoleTestData.ROLES_TR1[1][0], URATestData.getRC( URATestData.URC_T1 ).getType(), URATestData.getRC( URATestData.URC_T1 ).getKey() ); findUserRoleWithConstraints( "SRCH-RCS TR18 ABAC", RoleTestData.ROLES_ABAC_WASHERS[0][0], RoleConstraint.RCType.USER, RoleTestData.ROLE_CONSTRAINTS_TR18_ABAC[0][2] ); findUserRoleWithConstraints( "SRCH-RCS TR18 ABAC", RoleTestData.ROLES_ABAC_TELLERS[0][0], RoleConstraint.RCType.USER, RoleTestData.ROLE_CONSTRAINTS_TR18_ABAC[0][2] ); } public static void findUserRoleWithConstraints( String msg, String role, RoleConstraint.RCType rcType, String keyName ) { LogUtil.logIt(msg); try { ReviewMgr reviewMgr = getManagedReviewMgr(); List<UserRole> urs = reviewMgr.assignedUsers( new Role(role), rcType, keyName); assertNotNull( "findUserRoleWithConstraints no results", urs ); assertTrue(urs.size() > 0); assertTrue(urs.get(0).getRoleConstraints().size() > 0); LOG.debug( "findUserRoleWithConstraints paSetName [" + keyName + "] successful" ); } catch ( SecurityException ex ) { LOG.error( "findUserRoleWithConstraints paSetName [" + keyName + "] caught SecurityException rc=" + ex.getErrorId() + ", msg=" + ex.getMessage(), ex ); fail( ex.getMessage() ); } } public static void findRoleConstraints( String msg, String usr, Permission permission, RoleConstraint.RCType rcType ) { LogUtil.logIt(msg); try { ReviewMgr reviewMgr = getManagedReviewMgr(); List<RoleConstraint> rcs = reviewMgr.findRoleConstraints(new User(usr), permission, rcType); assertTrue("no constraints found for user:" + usr, rcs.size() > 0); assertTrue("invalid constraint type", rcs.get(0).getType().equals( rcType ) ); LOG.debug( "findRoleConstraints permission [" + permission.getObjName() + "." + permission.getOpName() + "] successful" ); } catch ( SecurityException ex ) { LOG.error( "findRoleConstraints permission [" + permission.getObjName() + "." + permission.getOpName() + "] caught SecurityException rc=" + ex.getErrorId() + ", msg=" + ex.getMessage(), ex ); fail( ex.getMessage() ); } } public void testDeassignRoleWithRoleConstraint() throws SecurityException{ AdminMgr adminMgr = AdminMgrImplTest.getManagedAdminMgr(); adminMgr.deassignUser( new UserRole( UserTestData.USERS_TU1[0][0], RoleTestData.ROLES_TR1[1][0] ) ); ReviewMgr reviewMgr = getManagedReviewMgr(); reviewMgr.assignedRoles( new User( UserTestData.USERS_TU1[0][0] ) ); adminMgr.assignUser( new UserRole( UserTestData.USERS_TU1[0][0], RoleTestData.ROLES_TR1[1][0] ) ); } /** * * @return * @throws org.apache.directory.fortress.core.SecurityException */ public static ReviewMgr getManagedReviewMgr() throws SecurityException { if ( FortressJUnitTest.isAdminEnabled() && adminSess == null ) { adminSess = DelegatedMgrImplTest.createAdminSession(); } return ReviewMgrFactory.createInstance( TestUtils.getContext(), adminSess ); } }
39.893155
186
0.539463
312344a9bf0930760b4f06df025c4e5944975835
225
int mod = 13; // Neko prastevilo, ki predstavlja sistem private int FastPow (int a, long e) { int rez = 1; while (e > 0) { if (e % 2 == 1) { rez = (rez * a) % mod; } a = a * a % mod; e /= 2; } return rez; }
15
56
0.502222
71548e0bc7c97eb720147c6c81c43e5cf79cdc77
8,897
package at.favre.lib.dali.builder; import android.content.Context; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.util.Log; import androidx.collection.LruCache; import com.jakewharton.disklrucache.DiskLruCache; import java.io.BufferedOutputStream; import java.io.File; import java.io.IOException; import java.io.OutputStream; import at.favre.lib.dali.BuildConfig; import at.favre.lib.dali.util.BenchmarkUtil; import at.favre.lib.dali.util.BuilderUtil; import at.favre.lib.dali.util.LegacySDKUtil; import at.favre.lib.dali.util.Precondition; /** * A simple tow level cache with a * a fast memory and a slow disk layer. */ public class TwoLevelCache { private static final String TAG = TwoLevelCache.class.getSimpleName(); private static final int DISK_CACHE_SIZE_BYTE = 1024 * 1024 * 10; private static final int MEMORY_CACHE_SIZE_FACTOR = 10; private static final String DISK_CACHE_FOLDER_NAME = "dali_diskcache"; private static final int IO_BUFFER_SIZE_BYTE = 1024 * 8; private static final Bitmap.CompressFormat FORMAT = Bitmap.CompressFormat.PNG; private DiskLruCache diskLruCache; private BitmapLruMemoryCache memoryCache; private Context ctx; private boolean useMemoryCache; private boolean useDiskCache; private boolean debugMode; private int diskCacheSizeByte; private String diskCacheFolderName; private int memoryCacheSizeByte; public TwoLevelCache(Context ctx) { this.ctx = ctx.getApplicationContext(); this.useMemoryCache = true; this.useDiskCache = true; this.debugMode = false; this.diskCacheSizeByte = DISK_CACHE_SIZE_BYTE; this.diskCacheFolderName = DISK_CACHE_FOLDER_NAME; this.memoryCacheSizeByte = (int) Runtime.getRuntime().maxMemory() / MEMORY_CACHE_SIZE_FACTOR; } public TwoLevelCache(Context ctx, boolean useMemoryCache, boolean useDiskCache, int diskCacheSizeByte, String diskCacheFolderName, int memoryCacheSizeByte, boolean debugMode) { this.ctx = ctx; this.useMemoryCache = useMemoryCache; this.useDiskCache = useDiskCache; this.debugMode = debugMode; this.diskCacheSizeByte = diskCacheSizeByte; this.diskCacheFolderName = diskCacheFolderName; this.memoryCacheSizeByte = memoryCacheSizeByte; } public DiskLruCache getDiskCache() { if (diskLruCache == null) { try { diskLruCache = DiskLruCache.open(new File(LegacySDKUtil.getCacheDir(ctx), diskCacheFolderName), BuildConfig.VERSION_CODE, 1, diskCacheSizeByte); } catch (Exception e) { Log.e(TAG, "Could not create disk cache", e); } } return diskLruCache; } public BitmapLruMemoryCache getMemoryCache() { if (memoryCache == null) { memoryCache = new BitmapLruMemoryCache(memoryCacheSizeByte, debugMode); } return memoryCache; } public Bitmap get(String cacheKey) { Bitmap cache = null; if (useMemoryCache) { if ((cache = getFromMemoryCache(cacheKey)) != null) { BuilderUtil.logVerbose(TAG, "found in memory cache (key: " + cacheKey + ")", debugMode); return cache; } } if (useDiskCache) { if ((cache = getFromDiskCache(cacheKey)) != null) { if (useMemoryCache) { putBitmapToMemoryCache(cache, cacheKey); } BuilderUtil.logVerbose(TAG, "found in disk cache (key: " + cacheKey + ")", debugMode); } } return cache; } public boolean putInCache(Bitmap bitmap, String cacheKey) { boolean memoryResult = false, diskresult = false; if (useMemoryCache) { memoryResult = putBitmapToMemoryCache(bitmap, cacheKey); } if (useDiskCache) { diskresult = putBitmapToDiskCache(bitmap, cacheKey); } BuilderUtil.logVerbose(TAG, "could put in memoryCache: " + memoryResult + ", could put in disk cache: " + diskresult + " (key: " + cacheKey + ")", debugMode); return (memoryResult || !useMemoryCache) && (diskresult || !useDiskCache); } public Bitmap getFromMemoryCache(String cacheKey) { Precondition.checkArgument("memory cache disabled", useMemoryCache); if (getMemoryCache() != null) { return getMemoryCache().get(cacheKey); } return null; } public boolean putBitmapToMemoryCache(Bitmap bitmap, String cacheKey) { Precondition.checkArgument("memory cache disabled", useMemoryCache); if (getMemoryCache() != null) { try { getMemoryCache().put(cacheKey, bitmap); } catch (Throwable t) { Log.e(TAG, "Could not put to memory cache", t); } } return false; } public Bitmap getFromDiskCache(String cacheKey) { Precondition.checkArgument("disk cache disabled", useDiskCache); if (getDiskCache() != null) { try { DiskLruCache.Snapshot snapshot = getDiskCache().get(cacheKey); if (snapshot != null) { return BitmapFactory.decodeStream(snapshot.getInputStream(0)); } } catch (IOException e) { Log.w(TAG, "Could not read from disk cache", e); } } return null; } public boolean putBitmapToDiskCache(Bitmap bitmap, String cacheKey) { Precondition.checkArgument("disk cache disabled", useDiskCache); if (getDiskCache() != null) { OutputStream out = null; try { DiskLruCache.Editor editor = getDiskCache().edit(cacheKey); if (editor != null) { out = new BufferedOutputStream(editor.newOutputStream(0), IO_BUFFER_SIZE_BYTE); if (bitmap.compress(FORMAT, 100, out)) { editor.commit(); return true; } else { Log.w(TAG, "Could not compress png for disk cache"); editor.abort(); } } } catch (Exception e) { Log.w(TAG, "Could not write outputstream for disk cache", e); } finally { if (out != null) { try { out.close(); } catch (IOException e) { Log.w(TAG, "Could not close outputstream while writing cache", e); } } } } return false; } public synchronized void clear() { clearMemoryCache(); clearDiskCache(); } public synchronized void clearMemoryCache() { if (memoryCache != null) { memoryCache.evictAll(); memoryCache = null; } } public synchronized void clearDiskCache() { if (diskLruCache != null) { try { diskLruCache.delete(); } catch (IOException e) { Log.w(TAG, "Could not clear diskcache", e); } diskLruCache = null; } } /** * Removes the value connected to the given key * from all levels of the cache. Will not throw an * exception on fail. * * @param cacheKey */ public void purge(String cacheKey) { try { if (useMemoryCache) { if (memoryCache != null) { memoryCache.remove(cacheKey); } } if (useDiskCache) { if (diskLruCache != null) { diskLruCache.remove(cacheKey); } } } catch (Exception e) { Log.w(TAG, "Could not remove entry in cache purge", e); } } private static class BitmapLruMemoryCache extends LruCache<String, Bitmap> { /** * @param maxSizeInBytes for caches that do not override {@link #sizeOf}, this is * the maximum number of entries in the cache. For all other caches, * this is the maximum sum of the sizes of the entries in this cache. */ public BitmapLruMemoryCache(int maxSizeInBytes, boolean debugMode) { super(maxSizeInBytes); BuilderUtil.logDebug(TAG, "Create memory cache with " + BenchmarkUtil.getScalingUnitByteSize(maxSizeInBytes), debugMode); } @Override protected int sizeOf(String key, Bitmap bitmap) { // The cache size will be measured in bytes rather than number of items. return LegacySDKUtil.byteSizeOf(bitmap); } } }
33.958015
180
0.589412
75f871de16050f3364a2b92e9a08481e463df909
922
package com.brentcroft.gtd.adapter.model.fx; import java.util.ArrayList; import java.util.List; import com.brentcroft.gtd.adapter.model.AbstractGuiObject; import com.brentcroft.gtd.adapter.model.GuiObject; import com.brentcroft.gtd.adapter.model.GuiObjectConsultant; import com.brentcroft.gtd.camera.CameraObjectManager; import com.brentcroft.util.xpath.gob.Gob; import javafx.scene.Scene; /** * Created by Alaric on 15/07/2017. */ public class FxSceneGuiObject< T extends Scene > extends AbstractGuiObject< T > { public FxSceneGuiObject( T go, Gob parent, GuiObjectConsultant< T > guiObjectConsultant, CameraObjectManager objectManager ) { super( go, parent, guiObjectConsultant, objectManager ); } @Override public List< GuiObject< ? > > loadChildren() { List< GuiObject< ? > > children = new ArrayList<>(); children.add( getManager().adapt( getObject().getRoot(), this ) ); return children; } }
27.117647
125
0.759219
8e0d3bcfa6884fc66088bed2d144e3d0aa0a026d
6,820
/* Copyright (c) 2012 Javier Ramirez-Ledesma Distributed under the MIT License (license terms are at http://opensource.org/licenses/MIT). */ package msti.ospfv2.fsmVecino; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.concurrent.ScheduledFuture; import msti.fsm.FSMContexto; import msti.io.Sesion; import msti.ospfv2.fsmInterfaz.FSMContextoOSPFv2Interfaz; import msti.ospfv2.mensaje.IMensajeOSPFv2LSA; import msti.ospfv2.mensaje.IMensajeOSPFv2LinkStateAdvertisementHeader; import msti.ospfv2.mensaje.MensajeOSPFv2DatabaseDescription; public class FSMContextoOSPFv2Vecino extends FSMContexto { private String estadoAdjacencia; //InactivityTimer private ScheduledFuture temporizadorInactivity; //EnvioDDPconIMMSTimer private ScheduledFuture temporizadorDDPconIMMS; //LinkStateRequestListTimer private ScheduledFuture temporizadorLinkStateRequestList; private boolean isMaster; private boolean AllDatabaseDescriptionPacketSent; private int ddSequenceNumber; private MensajeOSPFv2DatabaseDescription ultimoDDPEnviado; private int neighborID; private byte neighborPriority; private int neighborIPAddress; private byte neighborOptions; private int neighborDesignatedRouter; private int neighborBackupDesignatedRouter; //map: LinkStateID, lsa private Map<Long,IMensajeOSPFv2LSA> linkStateRetransmissionList; private Map<Long,IMensajeOSPFv2LSA> databaseSummaryList; //map: LinkStateID, header private Map<Long, IMensajeOSPFv2LinkStateAdvertisementHeader> linkStateRequestList; private FSMContextoOSPFv2Interfaz contextoInterfaz; //private Sesion sesion; public FSMContextoOSPFv2Vecino() { super(); setEstadoAdjacencia(""); setTemporizadorInactivity(null); setTemporizadorDDPconIMMS(null); setTemporizadorLinkStateRequestList(null); setMaster(false); //1 Master, 0 Slave setAllDatabaseDescriptionPacketSent(false); setDdSequenceNumber(-1); //-1 o 0 ??? setUltimoDDPEnviado(null); setNeighborID(0); setNeighborPriority((byte) 0); setNeighborIPAddress(0); //IP? como la saco? setNeighborOptions((byte)0); setNeighborDesignatedRouter(0); //ip del DR setNeighborBackupDesignatedRouter(0); //ip del BDR setLinkStateRetransmissionList( new HashMap<Long,IMensajeOSPFv2LSA>()); setDatabaseSummaryList( new HashMap<Long,IMensajeOSPFv2LSA>()); setLinkStateRequestList( new HashMap<Long,IMensajeOSPFv2LinkStateAdvertisementHeader>()); //setSesion(null); } public String getEstadoAdjacencia() { return estadoAdjacencia; } public void setEstadoAdjacencia(String estadoAdjacencia) { this.estadoAdjacencia = estadoAdjacencia; } public ScheduledFuture getTemporizadorInactivity() { return temporizadorInactivity; } public void setTemporizadorInactivity(ScheduledFuture temporizadorInactivity) { this.temporizadorInactivity = temporizadorInactivity; } public ScheduledFuture getTemporizadorDDPconIMMS() { return temporizadorDDPconIMMS; } public void setTemporizadorDDPconIMMS(ScheduledFuture temporizadorDDPconIMMS) { this.temporizadorDDPconIMMS = temporizadorDDPconIMMS; } public boolean isMaster() { return isMaster; } public void setMaster(boolean isMaster) { this.isMaster = isMaster; } public int getDdSequenceNumber() { return ddSequenceNumber; } public void setDdSequenceNumber(int ddSequenceNumber) { this.ddSequenceNumber = ddSequenceNumber; } public int getNeighborID() { return neighborID; } public void setNeighborID(int neighborID) { this.neighborID = neighborID; } public byte getNeighborPriority() { return neighborPriority; } public void setNeighborPriority(byte neighborPriority) { this.neighborPriority = neighborPriority; } public int getNeighborIPAddress() { return neighborIPAddress; } public void setNeighborIPAddress(int neighborIPAddress) { this.neighborIPAddress = neighborIPAddress; } public byte getNeighborOptions() { return neighborOptions; } public void setNeighborOptions(byte neighborOptions) { this.neighborOptions = neighborOptions; } public int getNeighborDesignatedRouter() { return neighborDesignatedRouter; } public void setNeighborDesignatedRouter(int neighborDesignatedRouter) { this.neighborDesignatedRouter = neighborDesignatedRouter; } public int getNeighborBackupDesignatedRouter() { return neighborBackupDesignatedRouter; } public void setNeighborBackupDesignatedRouter( int neighborBackupDesignatedRouter) { this.neighborBackupDesignatedRouter = neighborBackupDesignatedRouter; } public Map<Long,IMensajeOSPFv2LSA> getLinkStateRetransmissionList() { return linkStateRetransmissionList; } public void setLinkStateRetransmissionList( Map<Long,IMensajeOSPFv2LSA> linkStateRetransmissionList) { this.linkStateRetransmissionList = linkStateRetransmissionList; } public Map<Long,IMensajeOSPFv2LSA> getDatabaseSummaryList() { return databaseSummaryList; } public void setDatabaseSummaryList(Map<Long,IMensajeOSPFv2LSA> databaseSummaryList) { this.databaseSummaryList = databaseSummaryList; } public Map<Long,IMensajeOSPFv2LinkStateAdvertisementHeader> getLinkStateRequestList() { return linkStateRequestList; } public void setLinkStateRequestList(Map<Long,IMensajeOSPFv2LinkStateAdvertisementHeader> linkStateRequestList) { this.linkStateRequestList = linkStateRequestList; } public FSMContextoOSPFv2Interfaz getContextoInterfaz() { return contextoInterfaz; } public void setContextoInterfaz(FSMContextoOSPFv2Interfaz contextoInterfaz) { this.contextoInterfaz = contextoInterfaz; } /*public Sesion getSesion() { return sesion; } public void setSesion(Sesion sesion) { this.sesion = sesion; }*/ public ScheduledFuture getTemporizadorLinkStateRequestList() { return temporizadorLinkStateRequestList; } public void setTemporizadorLinkStateRequestList( ScheduledFuture temporizadorLinkStateRequestList) { this.temporizadorLinkStateRequestList = temporizadorLinkStateRequestList; } public boolean isAllDatabaseDescriptionPacketSent() { return AllDatabaseDescriptionPacketSent; } public void setAllDatabaseDescriptionPacketSent( boolean allDatabaseDescriptionPacketSent) { AllDatabaseDescriptionPacketSent = allDatabaseDescriptionPacketSent; } public MensajeOSPFv2DatabaseDescription getUltimoDDPEnviado() { return ultimoDDPEnviado; } public void setUltimoDDPEnviado(MensajeOSPFv2DatabaseDescription ultimoDDPEnviado) { this.ultimoDDPEnviado = ultimoDDPEnviado; } }
27.611336
114
0.779765
3df43cf19194e88df6e71d65efd86037fd5ca1c2
2,009
/* * This file is generated by jOOQ. */ package com.github.mahjong.league.repo.jdbc.generated; import com.github.mahjong.league.repo.jdbc.generated.tables.Invitation; import com.github.mahjong.league.repo.jdbc.generated.tables.JoinRequest; import com.github.mahjong.league.repo.jdbc.generated.tables.League; import com.github.mahjong.league.repo.jdbc.generated.tables.LeagueGame; import com.github.mahjong.league.repo.jdbc.generated.tables.LeaguePlayer; import com.github.mahjong.league.repo.jdbc.generated.tables.SchemaVersion; import javax.annotation.Generated; /** * Convenience access to all tables in public */ @Generated( value = { "http://www.jooq.org", "jOOQ version:3.10.5" }, comments = "This class is generated by jOOQ" ) @SuppressWarnings({ "all", "unchecked", "rawtypes" }) public class Tables { /** * The table <code>public.invitation</code>. */ public static final Invitation INVITATION = com.github.mahjong.league.repo.jdbc.generated.tables.Invitation.INVITATION; /** * The table <code>public.join_request</code>. */ public static final JoinRequest JOIN_REQUEST = com.github.mahjong.league.repo.jdbc.generated.tables.JoinRequest.JOIN_REQUEST; /** * The table <code>public.league</code>. */ public static final League LEAGUE = com.github.mahjong.league.repo.jdbc.generated.tables.League.LEAGUE; /** * The table <code>public.league_game</code>. */ public static final LeagueGame LEAGUE_GAME = com.github.mahjong.league.repo.jdbc.generated.tables.LeagueGame.LEAGUE_GAME; /** * The table <code>public.league_player</code>. */ public static final LeaguePlayer LEAGUE_PLAYER = com.github.mahjong.league.repo.jdbc.generated.tables.LeaguePlayer.LEAGUE_PLAYER; /** * The table <code>public.schema_version</code>. */ public static final SchemaVersion SCHEMA_VERSION = com.github.mahjong.league.repo.jdbc.generated.tables.SchemaVersion.SCHEMA_VERSION; }
33.483333
137
0.727227
eccb476b6370776ec0c55e8ace3c04672b8665c4
3,096
package org.corfudb.runtime.view.replication; import io.netty.buffer.ByteBuf; import io.netty.buffer.Unpooled; import org.corfudb.infrastructure.LogUnitServer; import org.corfudb.infrastructure.LogUnitServerAssertions; import org.corfudb.infrastructure.TestLayoutBuilder; import org.corfudb.infrastructure.TestServerRouter; import org.corfudb.protocols.wireprotocol.CorfuMsg; import org.corfudb.protocols.wireprotocol.CorfuMsgType; import org.corfudb.protocols.wireprotocol.DataType; import org.corfudb.protocols.wireprotocol.ILogData; import org.corfudb.protocols.wireprotocol.IMetadata; import org.corfudb.protocols.wireprotocol.LogData; import org.corfudb.protocols.wireprotocol.TokenResponse; import org.corfudb.protocols.wireprotocol.WriteMode; import org.corfudb.protocols.wireprotocol.WriteRequest; import org.corfudb.runtime.CorfuRuntime; import org.corfudb.runtime.clients.LogUnitClient; import org.corfudb.runtime.exceptions.DataOutrankedException; import org.corfudb.runtime.exceptions.OverwriteException; import org.corfudb.runtime.view.Layout; import org.corfudb.runtime.view.stream.IStreamView; import org.corfudb.util.serializer.Serializers; import org.junit.Test; import java.util.Collections; import java.util.UUID; import java.util.concurrent.atomic.AtomicInteger; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; /** Test the chain replication protocol. * * Created by mwei on 4/11/17. */ public class QuorumReplicationProtocolTest extends AbstractReplicationProtocolTest { public static final UUID testClientId = UUID.nameUUIDFromBytes("TEST_CLIENT".getBytes()); /** {@inheritDoc} */ @Override IReplicationProtocol getProtocol() { return new QuorumReplicationProtocol(new AlwaysHoleFillPolicy()); } /** {@inheritDoc} */ @Override void setupNodes() { addServer(SERVERS.PORT_0); addServer(SERVERS.PORT_1); addServer(SERVERS.PORT_2); bootstrapAllServers(new TestLayoutBuilder() .addLayoutServer(SERVERS.PORT_0) .addSequencer(SERVERS.PORT_0) .buildSegment() .setReplicationMode(Layout.ReplicationMode.QUORUM_REPLICATION) .buildStripe() .addLogUnit(SERVERS.PORT_0) .addLogUnit(SERVERS.PORT_1) .addLogUnit(SERVERS.PORT_2) .addToSegment() .addToLayout() .build()); getRuntime().setCacheDisabled(true); getManagementServer(SERVERS.PORT_0).shutdown(); getManagementServer(SERVERS.PORT_1).shutdown(); getManagementServer(SERVERS.PORT_2).shutdown(); } @Override public void overwriteThrowsException() throws Exception { // currently we don't give full waranties if two clients race for the same position during the 1-phase quorum write. // this is just assertion for wrong code, but in general this operation could do harm super.overwriteThrowsException(); } }
35.586207
124
0.73708
4d45449c606799116e2b2b6dc1e12376a4463a45
4,684
/* * Copyright 2015-2017 OpenCB * * 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.opencb.opencga.storage.app.cli.server.executors; import org.apache.commons.lang3.StringUtils; import org.opencb.opencga.storage.app.cli.CommandExecutor; import org.opencb.opencga.storage.app.cli.server.AdminCliOptionsParser; import org.opencb.opencga.storage.app.cli.server.options.ServerCommandOptions; import org.opencb.opencga.storage.core.config.StorageConfiguration; import org.opencb.opencga.storage.server.rest.RestStorageServer; import org.slf4j.Logger; import javax.ws.rs.client.Client; import javax.ws.rs.client.ClientBuilder; import javax.ws.rs.client.WebTarget; import javax.ws.rs.core.Response; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; /** * Created by imedina on 30/12/15. */ public class RestCommandExecutor { // extends CommandExecutor { ServerCommandOptions.RestServerCommandOptions restServerCommandOptions; StorageConfiguration configuration; Logger logger; public RestCommandExecutor(ServerCommandOptions.RestServerCommandOptions restServerCommandOptions, StorageConfiguration configuration, Logger logger) { this.restServerCommandOptions = restServerCommandOptions; this.configuration = configuration; this.logger = logger; } // private AdminCliOptionsParser.RestCommandOptions restCommandOptions; // // public RestCommandExecutor(AdminCliOptionsParser.RestCommandOptions restCommandOptions) { // super(restCommandOptions.commonOptions); // this.restCommandOptions = restCommandOptions; // } // // @Override // public void execute() throws Exception { // logger.debug("Executing REST command line"); // // String subCommandString = restCommandOptions.getParsedSubCommand(); // switch (subCommandString) { // case "start": // start(); // break; // case "stop": // stop(); // break; // case "status": // status(); // break; // default: // logger.error("Subcommand not valid"); // break; // } // } public void start() throws Exception { StorageConfiguration storageConfiguration = configuration; if (StringUtils.isNotEmpty(restServerCommandOptions.commonOptions.configFile)) { Path path = Paths.get(restServerCommandOptions.commonOptions.configFile); if (Files.exists(path)) { storageConfiguration = StorageConfiguration.load(Files.newInputStream(path)); } } // Setting CLI params in the StorageConfiguration if (restServerCommandOptions.port > 0) { storageConfiguration.getServer().setRest(restServerCommandOptions.port); } if (StringUtils.isNotEmpty(restServerCommandOptions.commonOptions.storageEngine)) { storageConfiguration.setDefaultStorageEngineId(restServerCommandOptions.commonOptions.storageEngine); } if (StringUtils.isNotEmpty(restServerCommandOptions.authManager)) { storageConfiguration.getServer().setAuthManager(restServerCommandOptions.authManager); } // Server crated and started RestStorageServer server = new RestStorageServer(storageConfiguration); server.start(); server.blockUntilShutdown(); logger.info("Shutting down OpenCGA Storage REST server"); } public void stop() { int port = configuration.getServer().getRest(); if (restServerCommandOptions.port > 0) { port = restServerCommandOptions.port; } Client client = ClientBuilder.newClient(); WebTarget target = client.target("http://localhost:" + port) .path("opencga") .path("webservices") .path("rest") .path("admin") .path("stop"); Response response = target.request().get(); logger.info(response.toString()); } public void status() { } }
36.030769
113
0.672289
f15cc8c236fc2901d22c651e91f04c3f35809627
329
package dev.sheldan.abstracto.activity.service; import dev.sheldan.abstracto.activity.models.CustomActivity; public interface ActivityService { void switchToOtherActivity(); void switchToActivity(CustomActivity activity); net.dv8tion.jda.api.entities.Activity matchActivity(CustomActivity activity, String text); }
32.9
94
0.81459
fe6396941f5be00b7173c6f9613ac61afb5e2df3
24,587
/* * 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. */ /* * This code was generated by https://github.com/googleapis/google-api-java-client-services/ * Modify at your own risk. */ package com.google.api.services.dfareporting.model; /** * Contains properties of a Campaign Manager campaign. * * <p> This is the Java data model class that specifies how to parse/serialize into the JSON that is * transmitted over HTTP when working with the DCM/DFA Reporting And Trafficking API. For a detailed * explanation see: * <a href="https://developers.google.com/api-client-library/java/google-http-java-client/json">https://developers.google.com/api-client-library/java/google-http-java-client/json</a> * </p> * * @author Google, Inc. */ @SuppressWarnings("javadoc") public final class Campaign extends com.google.api.client.json.GenericJson { /** * Account ID of this campaign. This is a read-only field that can be left blank. * The value may be {@code null}. */ @com.google.api.client.util.Key @com.google.api.client.json.JsonString private java.lang.Long accountId; /** * Ad blocking settings for this campaign. * The value may be {@code null}. */ @com.google.api.client.util.Key private AdBlockingConfiguration adBlockingConfiguration; /** * Additional creative optimization configurations for the campaign. * The value may be {@code null}. */ @com.google.api.client.util.Key private java.util.List<CreativeOptimizationConfiguration> additionalCreativeOptimizationConfigurations; /** * Advertiser group ID of the associated advertiser. * The value may be {@code null}. */ @com.google.api.client.util.Key @com.google.api.client.json.JsonString private java.lang.Long advertiserGroupId; /** * Advertiser ID of this campaign. This is a required field. * The value may be {@code null}. */ @com.google.api.client.util.Key @com.google.api.client.json.JsonString private java.lang.Long advertiserId; /** * Dimension value for the advertiser ID of this campaign. This is a read-only, auto-generated * field. * The value may be {@code null}. */ @com.google.api.client.util.Key private DimensionValue advertiserIdDimensionValue; /** * Whether this campaign has been archived. * The value may be {@code null}. */ @com.google.api.client.util.Key private java.lang.Boolean archived; /** * Audience segment groups assigned to this campaign. Cannot have more than 300 segment groups. * The value may be {@code null}. */ @com.google.api.client.util.Key private java.util.List<AudienceSegmentGroup> audienceSegmentGroups; static { // hack to force ProGuard to consider AudienceSegmentGroup used, since otherwise it would be stripped out // see https://github.com/google/google-api-java-client/issues/543 com.google.api.client.util.Data.nullOf(AudienceSegmentGroup.class); } /** * Billing invoice code included in the Campaign Manager client billing invoices associated with * the campaign. * The value may be {@code null}. */ @com.google.api.client.util.Key private java.lang.String billingInvoiceCode; /** * Click-through URL suffix override properties for this campaign. * The value may be {@code null}. */ @com.google.api.client.util.Key private ClickThroughUrlSuffixProperties clickThroughUrlSuffixProperties; /** * Arbitrary comments about this campaign. Must be less than 256 characters long. * The value may be {@code null}. */ @com.google.api.client.util.Key private java.lang.String comment; /** * Information about the creation of this campaign. This is a read-only field. * The value may be {@code null}. */ @com.google.api.client.util.Key private LastModifiedInfo createInfo; /** * List of creative group IDs that are assigned to the campaign. * The value may be {@code null}. */ @com.google.api.client.util.Key @com.google.api.client.json.JsonString private java.util.List<java.lang.Long> creativeGroupIds; /** * Creative optimization configuration for the campaign. * The value may be {@code null}. */ @com.google.api.client.util.Key private CreativeOptimizationConfiguration creativeOptimizationConfiguration; /** * Click-through event tag ID override properties for this campaign. * The value may be {@code null}. */ @com.google.api.client.util.Key private DefaultClickThroughEventTagProperties defaultClickThroughEventTagProperties; /** * The default landing page ID for this campaign. * The value may be {@code null}. */ @com.google.api.client.util.Key @com.google.api.client.json.JsonString private java.lang.Long defaultLandingPageId; /** * Date on which the campaign will stop running. On insert, the end date must be today or a future * date. The end date must be later than or be the same as the start date. If, for example, you * set 6/25/2015 as both the start and end dates, the effective campaign run date is just that day * only, 6/25/2015. The hours, minutes, and seconds of the end date should not be set, as doing so * will result in an error. This is a required field. * The value may be {@code null}. */ @com.google.api.client.util.Key private com.google.api.client.util.DateTime endDate; /** * Overrides that can be used to activate or deactivate advertiser event tags. * The value may be {@code null}. */ @com.google.api.client.util.Key private java.util.List<EventTagOverride> eventTagOverrides; /** * External ID for this campaign. * The value may be {@code null}. */ @com.google.api.client.util.Key private java.lang.String externalId; /** * ID of this campaign. This is a read-only auto-generated field. * The value may be {@code null}. */ @com.google.api.client.util.Key @com.google.api.client.json.JsonString private java.lang.Long id; /** * Dimension value for the ID of this campaign. This is a read-only, auto-generated field. * The value may be {@code null}. */ @com.google.api.client.util.Key private DimensionValue idDimensionValue; /** * Identifies what kind of resource this is. Value: the fixed string "dfareporting#campaign". * The value may be {@code null}. */ @com.google.api.client.util.Key private java.lang.String kind; /** * Information about the most recent modification of this campaign. This is a read-only field. * The value may be {@code null}. */ @com.google.api.client.util.Key private LastModifiedInfo lastModifiedInfo; /** * Name of this campaign. This is a required field and must be less than 256 characters long and * unique among campaigns of the same advertiser. * The value may be {@code null}. */ @com.google.api.client.util.Key private java.lang.String name; /** * Whether Nielsen reports are enabled for this campaign. * The value may be {@code null}. */ @com.google.api.client.util.Key private java.lang.Boolean nielsenOcrEnabled; /** * Date on which the campaign starts running. The start date can be any date. The hours, minutes, * and seconds of the start date should not be set, as doing so will result in an error. This is a * required field. * The value may be {@code null}. */ @com.google.api.client.util.Key private com.google.api.client.util.DateTime startDate; /** * Subaccount ID of this campaign. This is a read-only field that can be left blank. * The value may be {@code null}. */ @com.google.api.client.util.Key @com.google.api.client.json.JsonString private java.lang.Long subaccountId; /** * Campaign trafficker contact emails. * The value may be {@code null}. */ @com.google.api.client.util.Key private java.util.List<java.lang.String> traffickerEmails; /** * Account ID of this campaign. This is a read-only field that can be left blank. * @return value or {@code null} for none */ public java.lang.Long getAccountId() { return accountId; } /** * Account ID of this campaign. This is a read-only field that can be left blank. * @param accountId accountId or {@code null} for none */ public Campaign setAccountId(java.lang.Long accountId) { this.accountId = accountId; return this; } /** * Ad blocking settings for this campaign. * @return value or {@code null} for none */ public AdBlockingConfiguration getAdBlockingConfiguration() { return adBlockingConfiguration; } /** * Ad blocking settings for this campaign. * @param adBlockingConfiguration adBlockingConfiguration or {@code null} for none */ public Campaign setAdBlockingConfiguration(AdBlockingConfiguration adBlockingConfiguration) { this.adBlockingConfiguration = adBlockingConfiguration; return this; } /** * Additional creative optimization configurations for the campaign. * @return value or {@code null} for none */ public java.util.List<CreativeOptimizationConfiguration> getAdditionalCreativeOptimizationConfigurations() { return additionalCreativeOptimizationConfigurations; } /** * Additional creative optimization configurations for the campaign. * @param additionalCreativeOptimizationConfigurations additionalCreativeOptimizationConfigurations or {@code null} for none */ public Campaign setAdditionalCreativeOptimizationConfigurations(java.util.List<CreativeOptimizationConfiguration> additionalCreativeOptimizationConfigurations) { this.additionalCreativeOptimizationConfigurations = additionalCreativeOptimizationConfigurations; return this; } /** * Advertiser group ID of the associated advertiser. * @return value or {@code null} for none */ public java.lang.Long getAdvertiserGroupId() { return advertiserGroupId; } /** * Advertiser group ID of the associated advertiser. * @param advertiserGroupId advertiserGroupId or {@code null} for none */ public Campaign setAdvertiserGroupId(java.lang.Long advertiserGroupId) { this.advertiserGroupId = advertiserGroupId; return this; } /** * Advertiser ID of this campaign. This is a required field. * @return value or {@code null} for none */ public java.lang.Long getAdvertiserId() { return advertiserId; } /** * Advertiser ID of this campaign. This is a required field. * @param advertiserId advertiserId or {@code null} for none */ public Campaign setAdvertiserId(java.lang.Long advertiserId) { this.advertiserId = advertiserId; return this; } /** * Dimension value for the advertiser ID of this campaign. This is a read-only, auto-generated * field. * @return value or {@code null} for none */ public DimensionValue getAdvertiserIdDimensionValue() { return advertiserIdDimensionValue; } /** * Dimension value for the advertiser ID of this campaign. This is a read-only, auto-generated * field. * @param advertiserIdDimensionValue advertiserIdDimensionValue or {@code null} for none */ public Campaign setAdvertiserIdDimensionValue(DimensionValue advertiserIdDimensionValue) { this.advertiserIdDimensionValue = advertiserIdDimensionValue; return this; } /** * Whether this campaign has been archived. * @return value or {@code null} for none */ public java.lang.Boolean getArchived() { return archived; } /** * Whether this campaign has been archived. * @param archived archived or {@code null} for none */ public Campaign setArchived(java.lang.Boolean archived) { this.archived = archived; return this; } /** * Audience segment groups assigned to this campaign. Cannot have more than 300 segment groups. * @return value or {@code null} for none */ public java.util.List<AudienceSegmentGroup> getAudienceSegmentGroups() { return audienceSegmentGroups; } /** * Audience segment groups assigned to this campaign. Cannot have more than 300 segment groups. * @param audienceSegmentGroups audienceSegmentGroups or {@code null} for none */ public Campaign setAudienceSegmentGroups(java.util.List<AudienceSegmentGroup> audienceSegmentGroups) { this.audienceSegmentGroups = audienceSegmentGroups; return this; } /** * Billing invoice code included in the Campaign Manager client billing invoices associated with * the campaign. * @return value or {@code null} for none */ public java.lang.String getBillingInvoiceCode() { return billingInvoiceCode; } /** * Billing invoice code included in the Campaign Manager client billing invoices associated with * the campaign. * @param billingInvoiceCode billingInvoiceCode or {@code null} for none */ public Campaign setBillingInvoiceCode(java.lang.String billingInvoiceCode) { this.billingInvoiceCode = billingInvoiceCode; return this; } /** * Click-through URL suffix override properties for this campaign. * @return value or {@code null} for none */ public ClickThroughUrlSuffixProperties getClickThroughUrlSuffixProperties() { return clickThroughUrlSuffixProperties; } /** * Click-through URL suffix override properties for this campaign. * @param clickThroughUrlSuffixProperties clickThroughUrlSuffixProperties or {@code null} for none */ public Campaign setClickThroughUrlSuffixProperties(ClickThroughUrlSuffixProperties clickThroughUrlSuffixProperties) { this.clickThroughUrlSuffixProperties = clickThroughUrlSuffixProperties; return this; } /** * Arbitrary comments about this campaign. Must be less than 256 characters long. * @return value or {@code null} for none */ public java.lang.String getComment() { return comment; } /** * Arbitrary comments about this campaign. Must be less than 256 characters long. * @param comment comment or {@code null} for none */ public Campaign setComment(java.lang.String comment) { this.comment = comment; return this; } /** * Information about the creation of this campaign. This is a read-only field. * @return value or {@code null} for none */ public LastModifiedInfo getCreateInfo() { return createInfo; } /** * Information about the creation of this campaign. This is a read-only field. * @param createInfo createInfo or {@code null} for none */ public Campaign setCreateInfo(LastModifiedInfo createInfo) { this.createInfo = createInfo; return this; } /** * List of creative group IDs that are assigned to the campaign. * @return value or {@code null} for none */ public java.util.List<java.lang.Long> getCreativeGroupIds() { return creativeGroupIds; } /** * List of creative group IDs that are assigned to the campaign. * @param creativeGroupIds creativeGroupIds or {@code null} for none */ public Campaign setCreativeGroupIds(java.util.List<java.lang.Long> creativeGroupIds) { this.creativeGroupIds = creativeGroupIds; return this; } /** * Creative optimization configuration for the campaign. * @return value or {@code null} for none */ public CreativeOptimizationConfiguration getCreativeOptimizationConfiguration() { return creativeOptimizationConfiguration; } /** * Creative optimization configuration for the campaign. * @param creativeOptimizationConfiguration creativeOptimizationConfiguration or {@code null} for none */ public Campaign setCreativeOptimizationConfiguration(CreativeOptimizationConfiguration creativeOptimizationConfiguration) { this.creativeOptimizationConfiguration = creativeOptimizationConfiguration; return this; } /** * Click-through event tag ID override properties for this campaign. * @return value or {@code null} for none */ public DefaultClickThroughEventTagProperties getDefaultClickThroughEventTagProperties() { return defaultClickThroughEventTagProperties; } /** * Click-through event tag ID override properties for this campaign. * @param defaultClickThroughEventTagProperties defaultClickThroughEventTagProperties or {@code null} for none */ public Campaign setDefaultClickThroughEventTagProperties(DefaultClickThroughEventTagProperties defaultClickThroughEventTagProperties) { this.defaultClickThroughEventTagProperties = defaultClickThroughEventTagProperties; return this; } /** * The default landing page ID for this campaign. * @return value or {@code null} for none */ public java.lang.Long getDefaultLandingPageId() { return defaultLandingPageId; } /** * The default landing page ID for this campaign. * @param defaultLandingPageId defaultLandingPageId or {@code null} for none */ public Campaign setDefaultLandingPageId(java.lang.Long defaultLandingPageId) { this.defaultLandingPageId = defaultLandingPageId; return this; } /** * Date on which the campaign will stop running. On insert, the end date must be today or a future * date. The end date must be later than or be the same as the start date. If, for example, you * set 6/25/2015 as both the start and end dates, the effective campaign run date is just that day * only, 6/25/2015. The hours, minutes, and seconds of the end date should not be set, as doing so * will result in an error. This is a required field. * @return value or {@code null} for none */ public com.google.api.client.util.DateTime getEndDate() { return endDate; } /** * Date on which the campaign will stop running. On insert, the end date must be today or a future * date. The end date must be later than or be the same as the start date. If, for example, you * set 6/25/2015 as both the start and end dates, the effective campaign run date is just that day * only, 6/25/2015. The hours, minutes, and seconds of the end date should not be set, as doing so * will result in an error. This is a required field. * @param endDate endDate or {@code null} for none */ public Campaign setEndDate(com.google.api.client.util.DateTime endDate) { this.endDate = endDate; return this; } /** * Overrides that can be used to activate or deactivate advertiser event tags. * @return value or {@code null} for none */ public java.util.List<EventTagOverride> getEventTagOverrides() { return eventTagOverrides; } /** * Overrides that can be used to activate or deactivate advertiser event tags. * @param eventTagOverrides eventTagOverrides or {@code null} for none */ public Campaign setEventTagOverrides(java.util.List<EventTagOverride> eventTagOverrides) { this.eventTagOverrides = eventTagOverrides; return this; } /** * External ID for this campaign. * @return value or {@code null} for none */ public java.lang.String getExternalId() { return externalId; } /** * External ID for this campaign. * @param externalId externalId or {@code null} for none */ public Campaign setExternalId(java.lang.String externalId) { this.externalId = externalId; return this; } /** * ID of this campaign. This is a read-only auto-generated field. * @return value or {@code null} for none */ public java.lang.Long getId() { return id; } /** * ID of this campaign. This is a read-only auto-generated field. * @param id id or {@code null} for none */ public Campaign setId(java.lang.Long id) { this.id = id; return this; } /** * Dimension value for the ID of this campaign. This is a read-only, auto-generated field. * @return value or {@code null} for none */ public DimensionValue getIdDimensionValue() { return idDimensionValue; } /** * Dimension value for the ID of this campaign. This is a read-only, auto-generated field. * @param idDimensionValue idDimensionValue or {@code null} for none */ public Campaign setIdDimensionValue(DimensionValue idDimensionValue) { this.idDimensionValue = idDimensionValue; return this; } /** * Identifies what kind of resource this is. Value: the fixed string "dfareporting#campaign". * @return value or {@code null} for none */ public java.lang.String getKind() { return kind; } /** * Identifies what kind of resource this is. Value: the fixed string "dfareporting#campaign". * @param kind kind or {@code null} for none */ public Campaign setKind(java.lang.String kind) { this.kind = kind; return this; } /** * Information about the most recent modification of this campaign. This is a read-only field. * @return value or {@code null} for none */ public LastModifiedInfo getLastModifiedInfo() { return lastModifiedInfo; } /** * Information about the most recent modification of this campaign. This is a read-only field. * @param lastModifiedInfo lastModifiedInfo or {@code null} for none */ public Campaign setLastModifiedInfo(LastModifiedInfo lastModifiedInfo) { this.lastModifiedInfo = lastModifiedInfo; return this; } /** * Name of this campaign. This is a required field and must be less than 256 characters long and * unique among campaigns of the same advertiser. * @return value or {@code null} for none */ public java.lang.String getName() { return name; } /** * Name of this campaign. This is a required field and must be less than 256 characters long and * unique among campaigns of the same advertiser. * @param name name or {@code null} for none */ public Campaign setName(java.lang.String name) { this.name = name; return this; } /** * Whether Nielsen reports are enabled for this campaign. * @return value or {@code null} for none */ public java.lang.Boolean getNielsenOcrEnabled() { return nielsenOcrEnabled; } /** * Whether Nielsen reports are enabled for this campaign. * @param nielsenOcrEnabled nielsenOcrEnabled or {@code null} for none */ public Campaign setNielsenOcrEnabled(java.lang.Boolean nielsenOcrEnabled) { this.nielsenOcrEnabled = nielsenOcrEnabled; return this; } /** * Date on which the campaign starts running. The start date can be any date. The hours, minutes, * and seconds of the start date should not be set, as doing so will result in an error. This is a * required field. * @return value or {@code null} for none */ public com.google.api.client.util.DateTime getStartDate() { return startDate; } /** * Date on which the campaign starts running. The start date can be any date. The hours, minutes, * and seconds of the start date should not be set, as doing so will result in an error. This is a * required field. * @param startDate startDate or {@code null} for none */ public Campaign setStartDate(com.google.api.client.util.DateTime startDate) { this.startDate = startDate; return this; } /** * Subaccount ID of this campaign. This is a read-only field that can be left blank. * @return value or {@code null} for none */ public java.lang.Long getSubaccountId() { return subaccountId; } /** * Subaccount ID of this campaign. This is a read-only field that can be left blank. * @param subaccountId subaccountId or {@code null} for none */ public Campaign setSubaccountId(java.lang.Long subaccountId) { this.subaccountId = subaccountId; return this; } /** * Campaign trafficker contact emails. * @return value or {@code null} for none */ public java.util.List<java.lang.String> getTraffickerEmails() { return traffickerEmails; } /** * Campaign trafficker contact emails. * @param traffickerEmails traffickerEmails or {@code null} for none */ public Campaign setTraffickerEmails(java.util.List<java.lang.String> traffickerEmails) { this.traffickerEmails = traffickerEmails; return this; } @Override public Campaign set(String fieldName, Object value) { return (Campaign) super.set(fieldName, value); } @Override public Campaign clone() { return (Campaign) super.clone(); } }
32.826435
182
0.715378
4bb664373c56de65208ac33459074874bbafbf10
4,147
//! //! @title Binary Sanctity //! @author Jonathan Smith //! Course Section: CMIS201-HYB2 (Seidel) //! @file StringUtil.java //! @description Collection of utility functions for working with strings. //! import java.util.HashMap; import java.util.regex.Pattern; public class StringUtil { private static HashMap<String, Pattern> compiledPatterns = new HashMap<>(); // Compares two strings, even if either of them are null public static int compare(String a, String b) { if (equals(a, b)) { return 0; } if (a == null) { return Integer.MAX_VALUE; } else if (b == null) { return Integer.MIN_VALUE; } return a.compareTo(b); } // Compares two strings for equality, even if either of them are null public static boolean equals(String a, String b) { if (a == null && b == null) { return true; } else if ((a == null) != (b == null)) { // One of the strings is null. return false; } return a.equals(b); } public static String escape(String s, boolean full) { if (s == null || s.isEmpty()) { return s; } StringBuilder sb = new StringBuilder(); for (int i = 0; i < s.length(); ++i) { char c = s.charAt(i); int code = (int)c; if (c == '\\') { sb.append("\\\\"); } else if (code == 0xa) { sb.append("\\n"); } else if (code == 0xd) { sb.append("\\r"); } else if (code == 0x9) { sb.append("\\t"); } else { if (full && (code < 0x20 || code > 0x7e)) { sb.append(String.format("\\x%02x", code)); } else { sb.append(c); } } } return sb.toString(); } public static String escape(String s) { return escape(s, false); } public static String escapeFull(String s) { return escape(s, true); } // Returns true if a string matches the given regex pattern public static boolean isMatch(String s, String pattern, boolean compiled) { if (s == null) { return false; } if (compiled) { Pattern compiledPattern = null; if (!compiledPatterns.containsKey(pattern)) { compiledPattern = Pattern.compile(pattern); compiledPatterns.put(pattern, compiledPattern); } else { compiledPattern = compiledPatterns.get(pattern); } return compiledPattern.matcher(s).matches(); } return (Pattern.matches(pattern, s)); } public static boolean isMatch(String s, String pattern) { return isMatch(s, pattern, false); } // Returns true of a string is null or empty public static boolean isNullOrEmpty(String s) { return (s == null || s.isEmpty()); } // Returns true if a string is null, empty, or only whitespace public static boolean isNullOrWhiteSpace(String s) { return (s == null || isWhiteSpace(s)); } // Returns true if a string is empty or consists of nothing but whitespace public static boolean isWhiteSpace(String s) { if (s == null) { return false; } if (s.isEmpty()) { return true; } for (int i = 0; i < s.length(); ++i) { if (!Character.isWhitespace(s.charAt(i))) { return false; } } return true; } // Adds newlines to strings to wrap long text without breaking words public static String wordWrap(String s, int columns, int startPosition) { StringBuilder sb = new StringBuilder(s); int i = startPosition; while (i + columns < sb.length() && (i = sb.lastIndexOf(" ", i + columns)) != -1) { sb.replace(i, i + 1, "\n"); } return sb.toString(); } // Adds newlines to strings to wrap long text without breaking words public static String wordWrap(String s, int columns) { return wordWrap(s, columns, 0); } // Adds newlines to strings to wrap long text without breaking words public static String wordWrap(String s) { return wordWrap(s, 80); } }
20.631841
77
0.566675
d3fe97cdfb03daf51e85cbeb2bdaf283553c3857
5,399
/** * Copyright &copy 2012 Thomas Galvin - All Rights Reserved. */ package galvin.swing; import java.awt.GridBagConstraints; import java.awt.GridBagLayout; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.JComboBox; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.JSpinner; import javax.swing.SpinnerNumberModel; import org.joda.time.LocalDate; import org.joda.time.LocalDateTime; public class SimpleDateWidget extends JPanel { private JComboBox monthComboBox = new JComboBox( new String[] { "January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December" } ); private JComboBox daysInMonthComboBox = new JComboBox(); private SpinnerNumberModel yearModel = new SpinnerNumberModel( 0, 0, 9999, 1 ); private JSpinner yearField = new JSpinner( yearModel ); private static final int[] DAYS_IN_MONTH = new int[] { 31, //jan 29, //feb 31, //mar 30, //apr 31, //may 30, //jun 31, //jul 31, //aug 30, //sep 31, //oct 30, //nov 31, //dec }; public SimpleDateWidget() { super( new GridBagLayout() ); yearField.setEditor(new JSpinner.NumberEditor(yearField,"#")); GridBagConstraints constraints = new GridBagConstraints(); constraints.gridx = 0; constraints.gridy = 0; constraints.weightx = 1.0; constraints.fill = GridBagConstraints.HORIZONTAL; constraints.anchor = GridBagConstraints.EAST; add( new JLabel(), constraints ); constraints.gridx++; constraints.weightx = 0; constraints.fill = GridBagConstraints.NONE; add( monthComboBox, constraints ); constraints.gridx++; add( daysInMonthComboBox, constraints ); constraints.gridx++; add( yearField, constraints ); setDate( new LocalDate() ); new LocalActionListener(); } public LocalDate getDate() { Number num = yearModel.getNumber(); int year = num == null ? 0 : num.intValue(); LocalDate result = new LocalDate( year, monthComboBox.getSelectedIndex() + 1, daysInMonthComboBox.getSelectedIndex() + 1 ); return result; } public LocalDateTime getDateTime() { Number num = yearModel.getNumber(); int year = num == null ? 0 : num.intValue(); LocalDateTime result = new LocalDateTime( year, monthComboBox.getSelectedIndex() + 1, daysInMonthComboBox.getSelectedIndex() + 1, 0, 0, 0 ); return result; } public void setDate( LocalDate date ) { if( date != null ) { yearModel.setValue( date.getYear() ); monthComboBox.setSelectedItem( date.getMonthOfYear() - 1 ); setupDays(); daysInMonthComboBox.setSelectedIndex( date.getDayOfMonth() - 1 ); } else { setDate( new LocalDate( 0, 01, 01 ) ); } } public void setDateTime( LocalDateTime date ) { if( date != null ) { setDate( date.toLocalDate() ); } else { setDate( null ); } } public void now(){ setDate( new LocalDate() ); } public void epoc(){ setDate( new LocalDate( 1970, 1, 1 ) ); } @Override public void setToolTipText( String text ) { super.setToolTipText( text ); daysInMonthComboBox.setToolTipText( text ); monthComboBox.setToolTipText( text ); yearField.setToolTipText( text ); } private void setupDays() { int index = daysInMonthComboBox.getSelectedIndex(); daysInMonthComboBox.removeAllItems(); int count = DAYS_IN_MONTH[ monthComboBox.getSelectedIndex()]; for(int i = 1; i <= count; i++) { daysInMonthComboBox.addItem( i ); } index = Math.min( count - 1, index ); daysInMonthComboBox.setSelectedIndex( index ); } private class LocalActionListener implements ActionListener { public LocalActionListener() { monthComboBox.addActionListener( this ); } public void actionPerformed( ActionEvent e ) { Object source = e.getSource(); if( source == monthComboBox ) { setupDays(); } } } public static void main( String[] args ) { try { ApplicationWindow window = new ApplicationWindow( "Testing date widget" ); SimpleDateWidget widget = new SimpleDateWidget(); window.getContentPane().add( widget ); window.pack(); window.center(); window.setVisible( true ); } catch( Throwable t ) { t.printStackTrace(); } } }
26.082126
93
0.538989
5e4889656e3018bda6cbbdff6485e52e622117ba
2,787
package net.glowstone.command; import org.bukkit.Bukkit; import org.bukkit.ChatColor; import org.bukkit.Location; import org.bukkit.command.CommandSender; import org.bukkit.command.CommandTarget; import org.bukkit.command.CommandUtils; import org.bukkit.command.defaults.BukkitCommand; import org.bukkit.entity.Entity; import org.bukkit.entity.Player; import java.util.List; import java.util.Collections; public class TeleportCommand extends BukkitCommand { private static final Entity[] NO_ENTITY = new Entity[0]; @SuppressWarnings("unchecked") public TeleportCommand() { super("teleport", "Teleports entities to coordinates relative to the sender", "/teleport <target> <x> <y> <z> [<y-rot> <x-rot>]", (List)Collections.emptyList()); setPermission("glowstone.command.teleport"); } @Override public boolean execute(CommandSender sender, String commandLabel, String[] args) { if (!testPermission(sender)) return true; if (args.length < 4 || args.length == 5) { sender.sendMessage(ChatColor.RED + "Usage: " + usageMessage); return false; } if (!(sender instanceof Player)) { sender.sendMessage("This command can only be executed by physical objects."); return false; } Player player = (Player) sender; Entity[] targets; if (args[0].length() > 0 && args[0].charAt(0) == '@') { targets = new CommandTarget(args[0]).getMatched(player.getLocation()); } else { Player targetPlayer = Bukkit.getPlayerExact(args[0]); targets = targetPlayer == null ? NO_ENTITY : new Entity[]{targetPlayer}; } if (targets.length == 0) { sender.sendMessage(ChatColor.RED + "There's no entity matching the target."); } else { for (Entity target : targets) { String x = args[1], y = args[2], z = args[3]; Location initial = player.getLocation(); Location targetLocation = CommandUtils.getLocation(initial, x, y, z); if (args.length > 4) { String yaw = args[4], pitch = args[5]; targetLocation = CommandUtils.getRotation(target.getLocation(), yaw, pitch); } else { targetLocation.setYaw(target.getLocation().getYaw()); targetLocation.setPitch(target.getLocation().getPitch()); } target.teleport(targetLocation); player.sendMessage("Teleported " + target.getName() + " to " + targetLocation.getX() + " " + targetLocation.getY() + " " + targetLocation.getZ()); } } return true; } }
38.708333
162
0.597058
4340d3f367d1acee5385f400dc6577023c5920ff
889
package statemachine; public abstract class State { public StateID stateID; public StateMachine stateMachine; protected State(StateID stateID) { this.stateID = stateID; } /** * this method gets called at the start when the state becomes the currentState in the statemachine */ protected void enter() { } /** * this method gets called at the end when the state gets removed as the currentState in the statemachine */ protected void leave() { } /** * this method gets called first every program loop while the state is the currentState in the statemachine */ protected void checkForStateSwitch() { } /** * this method gets called second every program loop while the state is the currentState in the statemachine */ protected void logic() { } }
19.755556
112
0.63892
f4950c87f77e7ae4d74b3dc1151ebaf6a44e2562
15,443
package com.rackspace.ceres.app.web; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.anyString; import static org.mockito.ArgumentMatchers.eq; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.verifyNoInteractions; import static org.mockito.Mockito.verifyNoMoreInteractions; import static org.mockito.Mockito.when; import com.rackspace.ceres.app.config.AppProperties; import com.rackspace.ceres.app.config.DownsampleProperties; import com.rackspace.ceres.app.downsample.Aggregator; import com.rackspace.ceres.app.model.Metadata; import com.rackspace.ceres.app.model.QueryData; import com.rackspace.ceres.app.model.QueryResult; import com.rackspace.ceres.app.services.QueryService; import com.rackspace.ceres.app.validation.RequestValidator; import io.micrometer.core.instrument.MeterRegistry; import io.micrometer.core.instrument.cumulative.CumulativeCounter; import io.micrometer.core.instrument.simple.SimpleMeterRegistry; import java.time.Duration; import java.time.Instant; import java.util.List; import java.util.Map; import org.apache.commons.lang3.RandomStringUtils; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.autoconfigure.web.reactive.AutoConfigureWebFlux; import org.springframework.boot.test.autoconfigure.web.reactive.AutoConfigureWebTestClient; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.boot.test.mock.mockito.MockBean; import org.springframework.test.annotation.DirtiesContext; import org.springframework.test.annotation.DirtiesContext.ClassMode; import org.springframework.test.context.ActiveProfiles; import org.springframework.test.web.reactive.server.WebTestClient; import reactor.core.publisher.Flux; import reactor.test.StepVerifier; @ActiveProfiles(profiles = {"test", "query"}) @SpringBootTest(classes = {QueryController.class, AppProperties.class, RestWebExceptionHandler.class, DownsampleProperties.class, SimpleMeterRegistry.class}) @AutoConfigureWebTestClient @AutoConfigureWebFlux @DirtiesContext(classMode = ClassMode.BEFORE_EACH_TEST_METHOD) public class QueryControllerTest { @MockBean QueryService queryService; @Autowired MeterRegistry meterRegistry; @Autowired private WebTestClient webTestClient; @MockBean RequestValidator requestValidator; @Test public void testQueryApiWithMetricName() { Map<String, String> queryTags = Map .of("os", "linux", "deployment", "dev", "host", "h-1"); Map<Instant, Double> values = Map.of(Instant.now(), 111.0); List<QueryResult> queryResults = List .of(new QueryResult().setData(new QueryData().setMetricName("cpu-idle").setTags(queryTags).setTenant("t-1") .setValues(values)).setMetadata(new Metadata().setAggregator(Aggregator.raw))); when(queryService.queryRaw(anyString(), anyString(), eq(null), any(), any(), any())) .thenReturn(Flux.fromIterable(queryResults)); Flux<QueryResult> result = webTestClient.get() .uri(uriBuilder -> uriBuilder.path("/api/query") .queryParam("metricName", "cpu-idle") .queryParam("tag", "os=linux") .queryParam("start", "1d-ago") .build()) .header("X-Tenant", "t-1") .exchange().expectStatus().isOk() .returnResult(QueryResult.class).getResponseBody(); double count = meterRegistry.get("ceres.query").tag("type", "raw").counter().count(); assertThat(count).isEqualTo(1.0); StepVerifier.create(result).assertNext(queryResult -> { assertThat(meterRegistry.get("ceres.query").tag("type", "raw").counter().count()).isEqualTo(1); assertThat(queryResult.getData()).isEqualTo(queryResults.get(0).getData()); assertThat(queryResult.getMetadata().getAggregator()).isEqualTo(Aggregator.raw); }).verifyComplete(); } @Test public void testQueryApiWithMetricGroup() { final String metricGroup = RandomStringUtils.randomAlphabetic(5); Map<String, String> queryTags = Map .of("os", "linux", "deployment", "dev", "host", "h-1", "metricGroup", metricGroup); Map<Instant, Double> values = Map.of(Instant.now(), 111.0); List<QueryResult> queryResults = List .of(new QueryResult().setData(new QueryData().setMetricName("cpu-idle").setTags(queryTags).setTenant("t-1") .setValues(values)).setMetadata(new Metadata().setAggregator(Aggregator.raw))); when(queryService.queryRaw(anyString(), eq(null), anyString(), any(), any(), any())) .thenReturn(Flux.fromIterable(queryResults)); Flux<QueryResult> result = webTestClient.get() .uri(uriBuilder -> uriBuilder.path("/api/query") .queryParam("metricGroup", metricGroup) .queryParam("tag", "os=linux") .queryParam("start", "1d-ago") .build()) .header("X-Tenant", "t-1") .exchange().expectStatus().isOk() .returnResult(QueryResult.class).getResponseBody(); StepVerifier.create(result).assertNext(queryResult -> { assertThat(queryResult.getData()).isEqualTo(queryResults.get(0).getData()); assertThat(queryResult.getMetadata().getAggregator()).isEqualTo(Aggregator.raw); assertThat(queryResult.getData().getTags().get("metricGroup")).isEqualTo(metricGroup); }).verifyComplete(); } @Test public void testQueryApiWithAggregator() { final String metricGroup = RandomStringUtils.randomAlphabetic(5); Map<String, String> queryTags = Map .of("os", "linux", "deployment", "dev", "host", "h-1","metricGroup", metricGroup); Map<Instant, Double> values = Map.of(Instant.now(), 111.0); List<QueryResult> queryResults = List .of(new QueryResult() .setData( new QueryData() .setMetricName("cpu-idle") .setTags(queryTags) .setTenant("t-1") .setValues(values)) .setMetadata( new Metadata() .setAggregator(Aggregator.min) .setGranularity(Duration.ofMinutes(1)) .setStartTime(Instant.ofEpochSecond(1605611015)) .setEndTime(Instant.ofEpochSecond(1605697439)))); when(queryService.queryDownsampled(anyString(), anyString(), eq(null), any(), any(), any(), any(), any())) .thenReturn(Flux.fromIterable(queryResults)); Flux<QueryResult> result = webTestClient.get() .uri(uriBuilder -> uriBuilder.path("/api/query") .queryParam("metricName", "cpu-idle") .queryParam("tag", "os=linux,deployment=dev,host=h-1,metricGroup="+metricGroup) .queryParam("start", "1605611015") .queryParam("end", "1605697439") .queryParam("aggregator", "min") .queryParam("granularity", "pt1m") .build()) .header("X-Tenant", "t-1") .exchange().expectStatus().isOk() .returnResult(QueryResult.class).getResponseBody(); StepVerifier.create(result).assertNext(queryResult -> { assertThat(queryResult.getData()).isEqualTo(queryResults.get(0).getData()); assertThat(queryResult.getMetadata()).isEqualTo(queryResults.get(0).getMetadata()); assertThat(queryResult.getData().getTags().get("metricGroup")).isEqualTo(metricGroup); }).verifyComplete(); verify(queryService) .queryDownsampled("t-1", "cpu-idle", null, Aggregator.min, Duration.ofMinutes(1), queryTags, Instant.ofEpochSecond(1605611015), Instant.ofEpochSecond(1605697439)); verifyNoMoreInteractions(queryService); } @Test public void testQueryApiWithAggregatorWithMetricGroup() { final String metricGroup = RandomStringUtils.randomAlphabetic(5); Map<String, String> queryTags = Map .of("os", "linux", "deployment", "dev", "host", "h-1", "metricGroup", metricGroup); Map<Instant, Double> values = Map.of(Instant.now(), 111.0); List<QueryResult> queryResults = List .of(new QueryResult() .setData( new QueryData() .setMetricName("cpu-idle") .setTags(queryTags) .setTenant("t-1") .setValues(values)) .setMetadata( new Metadata() .setAggregator(Aggregator.min) .setGranularity(Duration.ofMinutes(1)) .setStartTime(Instant.ofEpochSecond(1605611015)) .setEndTime(Instant.ofEpochSecond(1605697439)))); when(queryService.queryDownsampled(anyString(), eq(null), anyString(), any(), any(), any(), any(), any())) .thenReturn(Flux.fromIterable(queryResults)); Flux<QueryResult> result = webTestClient.get() .uri(uriBuilder -> uriBuilder.path("/api/query") .queryParam("metricGroup", metricGroup) .queryParam("tag", "os=linux,deployment=dev,host=h-1,metricGroup="+metricGroup) .queryParam("start", "1605611015") .queryParam("end", "1605697439") .queryParam("aggregator", "min") .queryParam("granularity", "pt1m") .build()) .header("X-Tenant", "t-1") .exchange().expectStatus().isOk() .returnResult(QueryResult.class).getResponseBody(); StepVerifier.create(result).assertNext(queryResult -> { assertThat(queryResult.getData()).isEqualTo(queryResults.get(0).getData()); assertThat(queryResult.getMetadata()).isEqualTo(queryResults.get(0).getMetadata()); assertThat(queryResult.getData().getTags().get("metricGroup")).isEqualTo(queryResults.get(0).getData().getTags().get("metricGroup")); }).verifyComplete(); verify(queryService) .queryDownsampled("t-1", null, metricGroup, Aggregator.min, Duration.ofMinutes(1), queryTags, Instant.ofEpochSecond(1605611015), Instant.ofEpochSecond(1605697439)); verifyNoMoreInteractions(queryService); } @Test public void testQueryApiWithAggregatorAndMissingGranularity() { Map<String, String> queryTags = Map.of("os", "linux", "deployment", "dev", "host", "h-1"); Map<Instant, Double> values = Map.of(Instant.now(), 111.0); List<QueryResult> queryResults = List .of(new QueryResult() .setData( new QueryData() .setMetricName("cpu-idle") .setTags(queryTags) .setTenant("t-1") .setValues(values)) .setMetadata( new Metadata() .setAggregator(Aggregator.min) .setGranularity(Duration.ofMinutes(1)) .setStartTime(Instant.ofEpochSecond(1605611015)) .setEndTime(Instant.ofEpochSecond(1605697439)))); when(queryService.queryDownsampled(anyString(), anyString(), eq(null), any(), any(), any(), any(), any())) .thenReturn(Flux.fromIterable(queryResults)); Flux<QueryResult> result = webTestClient.get() .uri(uriBuilder -> uriBuilder.path("/api/query") .queryParam("metricName", "cpu-idle") .queryParam("tag", "os=linux,deployment=dev,host=h-1,") .queryParam("start", "1605611015") .queryParam("end", "1605697439") .queryParam("aggregator", "max") .build()) .header("X-Tenant", "t-1") .exchange().expectStatus().isOk() .returnResult(QueryResult.class).getResponseBody(); assertThat(result).isNotNull(); double count = ((CumulativeCounter) meterRegistry.getMeters().get(0)).count(); assertThat(count).isEqualTo(1.0); StepVerifier.create(result).assertNext(queryResult -> { assertThat(queryResult.getData()).isEqualTo(queryResults.get(0).getData()); assertThat(queryResult.getMetadata()).isEqualTo(queryResults.get(0).getMetadata()); }).verifyComplete(); verify(queryService) .queryDownsampled("t-1", "cpu-idle", null, Aggregator.max, Duration.ofMinutes(2), queryTags, Instant.ofEpochSecond(1605611015), Instant.ofEpochSecond(1605697439)); verifyNoMoreInteractions(queryService); } @Test public void testQueryApiWithNoTenantInHeaderAndParam() { webTestClient.get() .uri(uriBuilder -> uriBuilder.path("/api/query") .queryParam("metricName", "cpu-idle") .queryParam("tag", "os=linux") .queryParam("start", "1d-ago") .build()) .exchange().expectStatus().isBadRequest() .expectBody() .jsonPath("$.status").isEqualTo(400); verifyNoInteractions(queryService); } @Test public void testQueryApiWithMetricNameAndMetricGroup() { final String metricGroup = RandomStringUtils.randomAlphabetic(5); webTestClient.get() .uri(uriBuilder -> uriBuilder.path("/api/query") .queryParam("metricName", "cpu-idle") .queryParam("metricGroup", metricGroup) .queryParam("tag", "os=linux") .queryParam("start", "1d-ago") .build()) .exchange().expectStatus().isBadRequest() .expectBody() .jsonPath("$.status").isEqualTo(400); } @Test public void testQueryApiWithNoMetricNameAndMetricGroup() { webTestClient.get() .uri(uriBuilder -> uriBuilder.path("/api/query") .queryParam("tag", "os=linux") .queryParam("start", "1d-ago") .build()) .exchange().expectStatus().isBadRequest() .expectBody() .jsonPath("$.status").isEqualTo(400); verifyNoInteractions(queryService); } @Test public void testQueryApiWithOutStart() { final String metricGroup = RandomStringUtils.randomAlphabetic(5); webTestClient.get() .uri(uriBuilder -> uriBuilder.path("/api/query") .queryParam("metricName", "cpu-idle") .queryParam("metricGroup", metricGroup) .queryParam("tag", "os=linux") .build()) .exchange().expectStatus().isBadRequest() .expectBody() .jsonPath("$.status").isEqualTo(400); verifyNoInteractions(queryService); } @Test public void testQueryApiWithInvalidAggregator() { final String metricGroup = RandomStringUtils.randomAlphabetic(5); webTestClient.get() .uri(uriBuilder -> uriBuilder.path("/api/query") .queryParam("metricName", "cpu-idle") .queryParam("metricGroup", metricGroup) .queryParam("tag", "os=linux") .queryParam("aggregator", "test") .build()) .exchange().expectStatus().isBadRequest() .expectBody() .jsonPath("$.status").isEqualTo(400); verifyNoInteractions(queryService); } @Test public void testQueryApiWithInvalidTagName() { final String metricGroup = RandomStringUtils.randomAlphabetic(5); webTestClient.get() .uri(uriBuilder -> uriBuilder.path("/api/query") .queryParam("metricName", "cpu-idle") .queryParam("metricGroup", metricGroup) .queryParam("tag", "test") .queryParam("aggregator", "min") .build()) .exchange().expectStatus().isBadRequest() .expectBody() .jsonPath("$.status").isEqualTo(400); verifyNoInteractions(queryService); } }
40.962865
139
0.655572
f1fc46f9563716d20754720dc7d71a796359b67a
166
package org.opencompare.database; import org.opencompare.explorable.Conflict; public interface ConflictFilter { boolean include(Conflict conflict); }
16.6
43
0.759036
99a66c380e57d633ede83af8585f1dbfdd97698a
178
public class Square extends Rectangle { public Square() { super(); } public Square(double x ,double y , double side){ super (x,y,side,side); } }
17.8
52
0.567416
6ab00916e49ce2ea4efd89478439f7aad4961704
2,825
/* * 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 sensorapp; import java.sql.SQLException; import sensorapp.station.ConcreteDisplay.StationUI; /** * * @author leo */ public class SensorApp { public static void main(String[] args) throws SQLException { /* Set the Nimbus look and feel */ //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) "> /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel. * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html */ try { for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) { if ("Nimbus".equals(info.getName())) { javax.swing.UIManager.setLookAndFeel(info.getClassName()); break; } } } catch (ClassNotFoundException ex) { java.util.logging.Logger.getLogger(StationUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (InstantiationException ex) { java.util.logging.Logger.getLogger(StationUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (IllegalAccessException ex) { java.util.logging.Logger.getLogger(StationUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (javax.swing.UnsupportedLookAndFeelException ex) { java.util.logging.Logger.getLogger(StationUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } //</editor-fold> /* Create and display the form */ StationUI station = StationUI.getInstance(); station.setVisible(true); // // Sensor sensor1 = Station.getInstance().createSensor("Temp1", SensorType.TEMPERATURE.toString(), new Location()); //// System.out.println(sensor1); //// Station.getInstance().startSensor(sensor1); // Sensor sensor2 = Station.getInstance().createSensor("Humi1", SensorType.HUMIDITY.toString(), new Location()); //// System.out.println(sensor2); //// Station.getInstance().startSensor(sensor2); // Sensor sensor3 = Station.getInstance().createSensor("Press1", SensorType.PRESSURE.toString(), new Location()); //// System.out.println(sensor3); //// Station.getInstance().startSensor(sensor3); // Sensor sensor4 = Station.getInstance().createSensor("Wind1", SensorType.WIND_VELOCITY.toString(), new Location()); //// System.out.println(sensor4); //// Station.getInstance().startSensor(sensor4); } }
45.564516
124
0.655929
378a7dfe8eaff89df80e68f14bf06f8db87810ba
335
package com.github.ayltai.hknews.data.model; import lombok.Getter; public final class Pageable { @Getter private Sort sort; @Getter private int offset; @Getter private int pageSize; @Getter private int pageNumber; @Getter private boolean paged; @Getter private boolean unpaged; }
13.958333
44
0.668657
2984dec593553fb7128df91af4341acb0df932c7
8,849
/* * Hibernate, Relational Persistence for Idiomatic Java * * Copyright (c) 2011, Red Hat Inc. or third-party contributors as * indicated by the @author tags or express copyright attribution * statements applied by the authors. All third-party contributions are * distributed under license by Red Hat Inc. * * This copyrighted material is made available to anyone wishing to use, modify, * copy, or redistribute it subject to the terms and conditions of the GNU * Lesser General Public License, as published by the Free Software Foundation. * * 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 Lesser General Public License * for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this distribution; if not, write to: * Free Software Foundation, Inc. * 51 Franklin Street, Fifth Floor * Boston, MA 02110-1301 USA */ package org.hibernate.test.annotations.referencedcolumnname; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import java.math.BigDecimal; import java.util.Iterator; import org.hibernate.Session; import org.hibernate.Transaction; import org.hibernate.criterion.Restrictions; import org.hibernate.testing.junit4.BaseCoreFunctionalTestCase; import org.junit.Test; /** * @author Emmanuel Bernard */ public class ReferencedColumnNameTest extends BaseCoreFunctionalTestCase { @Test public void testManyToOne() throws Exception { Session s; Transaction tx; s = openSession(); tx = s.beginTransaction(); Postman pm = new Postman( "Bob", "A01" ); House house = new House(); house.setPostman( pm ); house.setAddress( "Rue des pres" ); s.persist( pm ); s.persist( house ); tx.commit(); s.close(); s = openSession(); tx = s.beginTransaction(); house = (House) s.get( House.class, house.getId() ); assertNotNull( house.getPostman() ); assertEquals( "Bob", house.getPostman().getName() ); pm = house.getPostman(); s.delete( house ); s.delete( pm ); tx.commit(); s.close(); } @Test public void testOneToMany() throws Exception { Session s; Transaction tx; s = openSession(); tx = s.beginTransaction(); Rambler rambler = new Rambler( "Emmanuel" ); Bag bag = new Bag( "0001", rambler ); rambler.getBags().add( bag ); s.persist( rambler ); tx.commit(); s.close(); s = openSession(); tx = s.beginTransaction(); bag = (Bag) s.createQuery( "select b from Bag b left join fetch b.owner" ).uniqueResult(); assertNotNull( bag ); assertNotNull( bag.getOwner() ); rambler = (Rambler) s.createQuery( "select r from Rambler r left join fetch r.bags" ).uniqueResult(); assertNotNull( rambler ); assertNotNull( rambler.getBags() ); assertEquals( 1, rambler.getBags().size() ); s.delete( rambler.getBags().iterator().next() ); s.delete( rambler ); tx.commit(); s.close(); } @Test public void testUnidirectionalOneToMany() throws Exception { Session s; Transaction tx; s = openSession(); tx = s.beginTransaction(); Clothes clothes = new Clothes( "underwear", "interesting" ); Luggage luggage = new Luggage( "Emmanuel", "Cabin Luggage" ); luggage.getHasInside().add( clothes ); s.persist( luggage ); tx.commit(); s.close(); s = openSession(); tx = s.beginTransaction(); luggage = (Luggage) s.createQuery( "select l from Luggage l left join fetch l.hasInside" ).uniqueResult(); assertNotNull( luggage ); assertNotNull( luggage.getHasInside() ); assertEquals( 1, luggage.getHasInside().size() ); s.delete( luggage.getHasInside().iterator().next() ); s.delete( luggage ); tx.commit(); s.close(); } @Test public void testManyToMany() throws Exception { Session s; Transaction tx; s = openSession(); tx = s.beginTransaction(); House whiteHouse = new House(); whiteHouse.setAddress( "1600 Pennsylvania Avenue, Washington" ); Inhabitant bill = new Inhabitant(); bill.setName( "Bill Clinton" ); Inhabitant george = new Inhabitant(); george.setName( "George W Bush" ); s.persist( george ); s.persist( bill ); whiteHouse.getHasInhabitants().add( bill ); whiteHouse.getHasInhabitants().add( george ); //bill.getLivesIn().add( whiteHouse ); //george.getLivesIn().add( whiteHouse ); s.persist( whiteHouse ); tx.commit(); s = openSession(); tx = s.beginTransaction(); whiteHouse = (House) s.get( House.class, whiteHouse.getId() ); assertNotNull( whiteHouse ); assertEquals( 2, whiteHouse.getHasInhabitants().size() ); tx.commit(); s.clear(); tx = s.beginTransaction(); bill = (Inhabitant) s.get( Inhabitant.class, bill.getId() ); assertNotNull( bill ); assertEquals( 1, bill.getLivesIn().size() ); assertEquals( whiteHouse.getAddress(), bill.getLivesIn().iterator().next().getAddress() ); whiteHouse = bill.getLivesIn().iterator().next(); s.delete( whiteHouse ); Iterator it = whiteHouse.getHasInhabitants().iterator(); while ( it.hasNext() ) { s.delete( it.next() ); } tx.commit(); s.close(); } @Test public void testManyToOneReferenceManyToOne() throws Exception { Item item = new Item(); item.setId( 1 ); Vendor vendor = new Vendor(); vendor.setId( 1 ); ItemCost cost = new ItemCost(); cost.setCost( new BigDecimal(1) ); cost.setId( 1 ); cost.setItem( item ); cost.setVendor( vendor ); WarehouseItem wItem = new WarehouseItem(); wItem.setDefaultCost( cost ); wItem.setId( 1 ); wItem.setItem( item ); wItem.setQtyInStock( new BigDecimal(1) ); wItem.setVendor( vendor ); Session s = openSession( ); s.getTransaction().begin(); s.persist( item ); s.persist( vendor ); s.persist( cost ); s.persist( wItem ); s.flush(); s.clear(); wItem = (WarehouseItem) s.get(WarehouseItem.class, wItem.getId() ); assertNotNull( wItem.getDefaultCost().getItem() ); s.getTransaction().rollback(); s.close(); } @Test public void testManyToOneInsideComponentReferencedColumn() { HousePlaces house = new HousePlaces(); house.places = new Places(); house.places.livingRoom = new Place(); house.places.livingRoom.name = "First"; house.places.livingRoom.owner = "mine"; house.places.kitchen = new Place(); house.places.kitchen.name = "Kitchen 1"; house.neighbourPlaces = new Places(); house.neighbourPlaces.livingRoom = new Place(); house.neighbourPlaces.livingRoom.name = "Neighbour"; house.neighbourPlaces.livingRoom.owner = "his"; house.neighbourPlaces.kitchen = new Place(); house.neighbourPlaces.kitchen.name = "His Kitchen"; Session s = openSession(); Transaction tx = s.beginTransaction(); s.save( house ); s.flush(); HousePlaces get = (HousePlaces) s.get( HousePlaces.class, house.id ); assertEquals( house.id, get.id ); HousePlaces uniqueResult = (HousePlaces) s.createQuery( "from HousePlaces h where h.places.livingRoom.name='First'" ).uniqueResult(); assertNotNull( uniqueResult ); assertEquals( uniqueResult.places.livingRoom.name, "First" ); assertEquals( uniqueResult.places.livingRoom.owner, "mine" ); uniqueResult = (HousePlaces) s.createQuery( "from HousePlaces h where h.places.livingRoom.owner=:owner" ) .setParameter( "owner", "mine" ).uniqueResult(); assertNotNull( uniqueResult ); assertEquals( uniqueResult.places.livingRoom.name, "First" ); assertEquals( uniqueResult.places.livingRoom.owner, "mine" ); assertNotNull( s.createCriteria( HousePlaces.class ).add( Restrictions.eq( "places.livingRoom.owner", "mine" ) ) .uniqueResult() ); // override uniqueResult = (HousePlaces) s .createQuery( "from HousePlaces h where h.neighbourPlaces.livingRoom.owner='his'" ).uniqueResult(); assertNotNull( uniqueResult ); assertEquals( uniqueResult.neighbourPlaces.livingRoom.name, "Neighbour" ); assertEquals( uniqueResult.neighbourPlaces.livingRoom.owner, "his" ); uniqueResult = (HousePlaces) s.createQuery( "from HousePlaces h where h.neighbourPlaces.livingRoom.name=:name" ) .setParameter( "name", "Neighbour" ).uniqueResult(); assertNotNull( uniqueResult ); assertEquals( uniqueResult.neighbourPlaces.livingRoom.name, "Neighbour" ); assertEquals( uniqueResult.neighbourPlaces.livingRoom.owner, "his" ); assertNotNull( s.createCriteria( HousePlaces.class ) .add( Restrictions.eq( "neighbourPlaces.livingRoom.owner", "his" ) ).uniqueResult() ); tx.rollback(); } @Override protected Class[] getAnnotatedClasses() { return new Class[]{ House.class, Postman.class, Bag.class, Rambler.class, Luggage.class, Clothes.class, Inhabitant.class, Item.class, ItemCost.class, Vendor.class, WarehouseItem.class, Place.class, HousePlaces.class }; } }
30.513793
114
0.702226