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
|
---|---|---|---|---|---|
9095cb5c63e41b6a65a8f94d9ef21144d80c2fa9 | 504 |
package org.openecomp.ncomp.sirius.manager.agent.servers.monitoring.south.logging;
import org.openecomp.entity.EcompOperationEnum;
public enum SouthBoundApiOperationEnum implements EcompOperationEnum {
SouthBoundApi_logs("SouthBoundApi@logs"),
SouthBoundApi_metrics("SouthBoundApi@metrics"),
SouthBoundApi_properties("SouthBoundApi@properties") ;
private String n;
private SouthBoundApiOperationEnum(String n) {
this.n = n;
}
@Override
public String toString() {
return n;
}
}
| 20.16 | 82 | 0.78373 |
b46c447484cf659d63f3eb48a5a8d19a087fe5c7 | 2,035 | /*
* Copyright 2019 Wultra s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.getlime.security.powerauth.networking.model.response;
/**
* Response object for endpoints returning data encrypted by ECIES.
*
* @author Roman Strobl, [email protected]
*/
public class EciesEncryptedResponse {
private String encryptedData;
private String mac;
/**
* Default constructor.
*/
public EciesEncryptedResponse() {
}
/**
* Constructor with Base64 encoded encrypted data and MAC of key and data.
* @param encryptedData Encrypted data.
* @param mac MAC of key and data.
*/
public EciesEncryptedResponse(String encryptedData, String mac) {
this.encryptedData = encryptedData;
this.mac = mac;
}
/**
* Get Base64 encoded encrypted data payload.
* @return Encrypted data.
*/
public String getEncryptedData() {
return encryptedData;
}
/**
* Set Base64 encoded encrypted data payload.
* @param encryptedData Encrypted data.
*/
public void setEncryptedData(String encryptedData) {
this.encryptedData = encryptedData;
}
/**
* Get Base64 encoded MAC signature of the response.
* @return MAC of the response.
*/
public String getMac() {
return mac;
}
/**
* Set Base64 encoded MAC signature of the response.
* @param mac MAC of the response.
*/
public void setMac(String mac) {
this.mac = mac;
}
}
| 26.428571 | 78 | 0.663391 |
595f534c39260b561274dad8c41263c4d798bdf4 | 2,724 |
package org.springframework.web.jsf;
import javax.faces.application.NavigationHandler;
import javax.faces.context.FacesContext;
import org.junit.Test;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.support.StaticListableBeanFactory;
import org.springframework.lang.Nullable;
import static org.junit.Assert.*;
/**
* @author Colin Sampaleanu
*/
public class DelegatingNavigationHandlerTests {
private final MockFacesContext facesContext = new MockFacesContext();
private final StaticListableBeanFactory beanFactory = new StaticListableBeanFactory();
private final TestNavigationHandler origNavHandler = new TestNavigationHandler();
private final DelegatingNavigationHandlerProxy delNavHandler = new DelegatingNavigationHandlerProxy(origNavHandler) {
@Override
protected BeanFactory getBeanFactory(FacesContext facesContext) {
return beanFactory;
}
};
@Test
public void handleNavigationWithoutDecoration() {
TestNavigationHandler targetHandler = new TestNavigationHandler();
beanFactory.addBean("jsfNavigationHandler", targetHandler);
delNavHandler.handleNavigation(facesContext, "fromAction", "myViewId");
assertEquals("fromAction", targetHandler.lastFromAction);
assertEquals("myViewId", targetHandler.lastOutcome);
}
@Test
public void handleNavigationWithDecoration() {
TestDecoratingNavigationHandler targetHandler = new TestDecoratingNavigationHandler();
beanFactory.addBean("jsfNavigationHandler", targetHandler);
delNavHandler.handleNavigation(facesContext, "fromAction", "myViewId");
assertEquals("fromAction", targetHandler.lastFromAction);
assertEquals("myViewId", targetHandler.lastOutcome);
// Original handler must have been invoked as well...
assertEquals("fromAction", origNavHandler.lastFromAction);
assertEquals("myViewId", origNavHandler.lastOutcome);
}
static class TestNavigationHandler extends NavigationHandler {
private String lastFromAction;
private String lastOutcome;
@Override
public void handleNavigation(FacesContext facesContext, String fromAction, String outcome) {
lastFromAction = fromAction;
lastOutcome = outcome;
}
}
static class TestDecoratingNavigationHandler extends DecoratingNavigationHandler {
private String lastFromAction;
private String lastOutcome;
@Override
public void handleNavigation(FacesContext facesContext, @Nullable String fromAction,
@Nullable String outcome, @Nullable NavigationHandler originalNavigationHandler) {
lastFromAction = fromAction;
lastOutcome = outcome;
if (originalNavigationHandler != null) {
originalNavigationHandler.handleNavigation(facesContext, fromAction, outcome);
}
}
}
}
| 29.608696 | 118 | 0.804332 |
6f95b11ba1d389a9a6988566b0d126e6b5cc112d | 5,439 | package com.iwbfly.myhttp.logging;
import com.iwbfly.myhttp.http.Request;
import com.iwbfly.myhttp.http.Response;
import com.iwbfly.myhttp.reflection.MyhttpRequest;
import com.iwbfly.myhttp.utils.Util;
import java.io.*;
import java.util.*;
import java.util.logging.Level;
import static com.iwbfly.myhttp.utils.Util.valuesOrEmpty;
/**
* @auther: pangyajun
* @create: 2021/12/1 15:24
**/
public abstract class Logger {
public abstract void log(String formart, Object... args);
public void logRequest(Request request, MyhttpRequest myhttpRequest) {
Logger.Level loggerLevel = myhttpRequest.getLoggerLevel();
boolean headerLog = false;
boolean bodyLog = false;
log("---> %s %s HTTP/1.1", request.httpMethod().name(), request.url());
Message message = new Message();
Map<String, Collection<String>> logHeaders = null;
if (request.headers().size() > 0 && loggerLevel.ordinal() > Level.BASIC.ordinal()) {
headerLog = true;
logHeaders = clone(request.headers());
message.setVariable(logHeaders);
}
String bodyText = "";
int bodyLength = 0;
if (request.requestBody().asBytes() != null) {
bodyLog = true;
bodyLength = request.requestBody().asBytes().length;
bodyText = request.charset() != null
? new String(request.requestBody().asBytes(), request.charset())
: null;
message.setMessage(bodyText);
}
myhttpRequest.getInterceptorChain().requestLog(message);
bodyText = message.getMessage();
if (headerLog && logHeaders != null && logHeaders.size() > 0) {
log("---> HEADER START");
for (String field : logHeaders.keySet()) {
for (String value : valuesOrEmpty(logHeaders, field)) {
log("%s: %s", field, value);
}
}
log("---> HEADER END");
}
if (bodyLog) {
log("---> END HTTP BODY (%s)", bodyText);
}
log("---> END HTTP (%s-byte body)", bodyLength);
}
public Response logAndRebufferResponse(Response response, long elapsedTime, MyhttpRequest myhttpRequest) throws IOException {
Logger.Level loggerLevel = myhttpRequest.getLoggerLevel();
String reason = response.reason() != null ? " " + response.reason() : "";
int status = response.status();
boolean headerLog = false;
boolean bodyLog = false;
Message message = new Message();
log("<--- HTTP/1.1 %s%s (%sms)", status, reason, elapsedTime);
Map<String, Collection<String>> logHeaders = null;
if (response.headers().size() > 0 && loggerLevel.ordinal() > Level.BASIC.ordinal()) {
headerLog = true;
logHeaders = clone(response.headers());
message.setVariable(logHeaders);
}
int bodyLength = 0;
String bodyText = "";
byte[] bodyData = null;
if (response.body() != null && !(status == 204 || status == 205)) {
bodyLog = true;
bodyData = Util.toByteArray(response.body().asInputStream());
bodyLength = bodyData.length;
bodyText = response.request().charset() != null
? new String(bodyData, response.request().charset())
: null;
message.setMessage(bodyText);
}
myhttpRequest.getInterceptorChain().responseLog(message);
bodyText = message.getMessage();
if (headerLog && logHeaders != null && logHeaders.size() > 0) {
log("<--- HEADER START");
for (String field : logHeaders.keySet()) {
for (String value : valuesOrEmpty(logHeaders, field)) {
log("%s: %s", field, value);
}
}
log("<--- HEADER END");
}
if (bodyLog) {
log("<--- END HTTP BODY (%s)", bodyText);
log("<--- END HTTP (%s-byte body)", bodyLength);
return response.toBuilder().body(bodyData).build();
} else {
log("<--- END HTTP (%s-byte body)", bodyLength);
}
return response;
}
Map<String, Collection<String>> clone(Map<String, Collection<String>> headers) {
Map<String, Collection<String>> logHeaders = new HashMap<>();
for (String field : headers.keySet()) {
List list = new ArrayList();
logHeaders.put(field, list);
for (String value : valuesOrEmpty(headers, field)) {
list.add(value);
}
}
return logHeaders;
}
public IOException logIOException(IOException ioe, long elapsedTime) {
log("<--- ERROR %s: %s (%sms)", ioe.getClass().getSimpleName(),
ioe.getMessage(),
elapsedTime);
StringWriter sw = new StringWriter();
ioe.printStackTrace(new PrintWriter(sw));
log("%s", sw.toString());
log("<--- END ERROR");
return ioe;
}
public enum Level {
/**
* No logging.
*/
NONE,
/**
* Log only the request method and URL and the response status code and execution time.
*/
BASIC,
/**
* Log the headers, body, and metadata for both requests and responses.
*/
FULL
}
}
| 37 | 129 | 0.553227 |
1d35a91cf072da7497b570b074eeaafdf9571bb7 | 7,907 | package com.github.guignol.indrah.utils;
import com.github.guignol.indrah.command.CommandOutput;
import com.github.guignol.indrah.command.FileStageCommand;
import com.github.guignol.indrah.model.*;
import org.jetbrains.annotations.NotNull;
import java.nio.file.Path;
import java.util.List;
import java.util.function.Consumer;
import java.util.function.Predicate;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import static com.github.guignol.indrah.command.ApplyPatchCommand.Executor;
public class StageUtils {
private static final Predicate<String> noContextLine = line -> line.startsWith("+") || line.startsWith("-");
public static void stage(Executor executor,
List<DiffLine> selectedLines,
boolean unstage,
Consumer<CommandOutput> callbackForShortcut) {
// パッチを作らずにファイル全体をstage/unstageする場合
if (StageUtils.doStageFile(executor.getCurrentDirectory(), selectedLines, unstage, callbackForShortcut)) {
return;
}
// 変化を全く含まない場合
if (StageUtils.nothingToDo(selectedLines)) {
return;
}
final DiffLine startLine = selectedLines.get(0);
final DiffLine endLine = ListUtils.last(selectedLines);
final Range range = new Range(startLine.indexInHunk, endLine.indexInHunk);
// 選択範囲のhunkはすべて同じであることを前提
final Hunk targetHunk = startLine.hunk.copy();
// hunk全体を選択した場合
if (range.contains(noContextRange(targetHunk))) {
System.out.println("hunk全体を選択");
final String patchForHunk = startLine.diff.header + targetHunk.toString();
executor.execute(patchForHunk, unstage, null);
return;
}
if (shouldRemoveSignForNNLAEOF(startLine.diff, targetHunk, range, unstage)) {
final String command = removeSignForNNLAEOF(startLine, range, unstage);
executor.execute(command, unstage, null);
} else if (UnstageUtils.needsWorkaround(startLine.diff, unstage)) {
// ①hunkを全てunstageする
// ②選択行の後を全てstageする
// ③選択行の前を全てstageする
UnstageUtils.unstageWorkaround(executor, startLine, endLine);
} else {
// 通常時
final String command = PatchUtils.makePatch(
startLine.diff.header,
targetHunk,
range,
unstage
);
executor.execute(command, unstage, null);
}
}
public static boolean doStageFile(Path root,
List<DiffLine> selectedLines,
boolean unstage,
Consumer<CommandOutput> callback) {
final Diff targetDiff = selectedLines.get(0).diff;
/*
・新規追加された空ファイル
・ファイル削除
・リネーム
・バイナリ https://stackoverflow.com/questions/17152171/git-cannot-apply-binary-patch-without-full-index-line
*/
final boolean headerOnly = targetDiff.hunks.isEmpty();
if (headerOnly ||
// ファイル全体を選択
selectedLines.size() == targetDiff.hunks.stream().mapToInt(hunk -> hunk.lines.size()).sum()) {
switch (targetDiff.summary.status) {
case Renamed:
new FileStageCommand(root, unstage, targetDiff.summary.names.before(), targetDiff.summary.names.after()).call(callback);
break;
default:
new FileStageCommand(root, unstage, targetDiff.summary.names.any()).call(callback);
break;
}
return true;
}
return false;
}
public static FileStageCommand getFileStageCommand(Path root,
boolean unstage,
List<Diff> targets) {
final String[] files = targets.stream().map(diff -> diff.summary).flatMap(summary -> {
switch (summary.status) {
case Renamed:
return Stream.of(summary.names.before(), summary.names.after());
default:
return Stream.of(summary.names.any());
}
}).toArray(String[]::new);
return new FileStageCommand(root, unstage, files);
}
public static boolean nothingToDo(Hunk hunk, Range range) {
if (!range.exists()) {
return true;
}
List<String> selectedLines = hunk.lines.subList(range.begin, range.end + 1);
return noLineToDo(selectedLines);
}
public static boolean nothingToDo(List<DiffLine> diffLines) {
final List<String> selectedLines = diffLines
.stream()
.map(diffLine -> diffLine.line)
.collect(Collectors.toList());
return noLineToDo(selectedLines);
}
public static boolean noLineToDo(List<String> selectedLines) {
return selectedLines.stream().noneMatch(noContextLine);
}
public static Range noContextRange(Hunk targetHunk) {
final List<String> lines = targetHunk.lines;
final int first = ListUtils.findIndex(lines, noContextLine);
final int last = ListUtils.findLastIndex(lines, noContextLine);
return new Range(first, last);
}
public static boolean shouldRemoveSignForNNLAEOF(Diff diff, Hunk hunk, Range selectedRange, boolean unstage) {
return shouldRemoveSignForNNLAEOF(stageNewFile(diff), hunk, selectedRange, unstage);
}
public static boolean shouldRemoveSignForNNLAEOF(boolean newFile, Hunk hunk, Range selectedRange, boolean unstage) {
// \ No newline at end of file近傍のプラスまたはマイナスの塊を全て含まない場合
// (一部でも近傍の塊を含む場合は、\ No newline at end of fileは有意味)
// stageの場合を例にとると、
// 選択されないプラス行は削除されるため、その後の\ No newline at end of fileは無意味で不要となり、
// 選択されないマイナス行は空白始まりとして残るため、その後の\ No newline at end of fileは有意味なまま
final Range targetRange = unstage ? hunk.endEdgeMinusLines() : hunk.endEdgePlusLines();
if (!targetRange.exists()) {
return false;
}
if (!unstage && newFile) {
// 新規ファイルのstageの場合、\ No newline at end of fileは末尾行が無ければ削除する
// そのほうが挙動として直感的だと思う
return !selectedRange.contains(targetRange.end);
} else {
return !selectedRange.containsPartially(targetRange);
}
}
@NotNull
public static String removeSignForNNLAEOF(DiffLine startLine, Range range, boolean unstage) {
final Hunk targetHunk = startLine.hunk.copy();
// 不要な\ No newline at end of fileを削除する
final Range edgeRange = unstage ? targetHunk.endEdgeMinusLines() : targetHunk.endEdgePlusLines();
final int removed = edgeRange.end + 1;
targetHunk.lines.remove(removed);
final Range adjusted;
if (range.end < removed) {
// この行の塊の前だけがstageされる場合、rangeは何も変わらない
adjusted = range;
} else {
// この行の塊の後だけがstageされる場合、rangeが1つずつ減る
adjusted = range.offset(-1);
}
return PatchUtils.makePatch(
startLine.diff.header,
targetHunk,
adjusted,
unstage
);
}
/**
* 新規追加ファイルかどうか
*/
static boolean stageNewFile(Diff diff) {
final List<String> diffHeaderLines = diff.headerLines();
for (String headerLine : diffHeaderLines) {
if (headerLine.startsWith(DiffHeader.Prefix.MINUS_DEV_NULL)) {
return true;
}
}
return false;
}
}
| 40.341837 | 141 | 0.586063 |
2e9b9fce6362a3a6a19c5140bb5ade31ccadc827 | 420 | package com.zup.lucasciscar.cartaoproposta.dto.response;
public class CarteiraClientResponse {
private Resultado resultado;
private String id;
public enum Resultado {
ASSOCIADA, FALHA;
}
public CarteiraClientResponse(Resultado resultado, String id) {
this.resultado = resultado;
this.id = id;
}
public Resultado getResultado() {
return resultado;
}
}
| 20 | 67 | 0.669048 |
09df8385023ab0f248a3fe36de5769a0c184fe91 | 923 | package com.company.demo.core;
import com.haulmont.cuba.core.global.Events;
import com.haulmont.cuba.core.sys.events.*;
import org.slf4j.Logger;
import org.springframework.context.event.EventListener;
import org.springframework.stereotype.Component;
import javax.inject.Inject;
@Component
public class MyAppLifecycleBean {
@Inject
private Logger log;
// event type is defined by annotation parameter
@EventListener(AppContextInitializedEvent.class)
// run after all platform listeners
@Order(Events.LOWEST_PLATFORM_PRECEDENCE + 100)
protected void appInitialized() {
log.info("Initialized");
}
// event type is defined by method parameter
@EventListener
protected void appStarted(AppContextStartedEvent event) {
log.info("Started");
}
@EventListener
protected void appStopped(AppContextStoppedEvent event) {
log.info("Stopped");
}
} | 26.371429 | 61 | 0.732394 |
548d2ebcb6a4c969f668a2be004d6327a57e1219 | 5,001 | package seedu.zookeep.model.animal;
import static java.util.Objects.requireNonNull;
import static seedu.zookeep.commons.util.CollectionUtil.requireAllNonNull;
import java.util.Comparator;
import java.util.Iterator;
import java.util.List;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.collections.transformation.SortedList;
import seedu.zookeep.model.animal.exceptions.AnimalNotFoundException;
import seedu.zookeep.model.animal.exceptions.DuplicateAnimalException;
/**
* A list of animals that enforces uniqueness between its elements and does not allow nulls.
* An animal is considered unique by comparing using {@code Animal#isSameAnimal(Animal)}.
* As such, adding and updating of
* animals uses Animal#isSameAnimal(Animal) for equality so as to ensure that the animal being added or updated is
* unique in terms of identity in the UniqueAnimalList. However, the removal of an animal uses Animal#equals(Object) so
* as to ensure that the animal with exactly the same fields will be removed.
*
* Supports a minimal set of list operations.
*
* @see Animal#isSameAnimal(Animal)
*/
public class UniqueAnimalList implements Iterable<Animal> {
private final ObservableList<Animal> internalList = FXCollections.observableArrayList();
private final ObservableList<Animal> internalUnmodifiableList =
FXCollections.unmodifiableObservableList(internalList);
/**
* Returns true if the list contains an equivalent animal as the given argument.
*/
public boolean contains(Animal toCheck) {
requireNonNull(toCheck);
return internalList.stream().anyMatch(toCheck::isSameAnimal);
}
/**
* Adds an animal to the list.
* The animal must not already exist in the list.
*/
public void add(Animal toAdd) {
requireNonNull(toAdd);
if (contains(toAdd)) {
throw new DuplicateAnimalException();
}
internalList.add(toAdd);
}
/**
* Replaces the animal {@code target} in the list with {@code editedAnimal}.
* {@code target} must exist in the list.
* The animal identity of {@code editedAnimal} must not be the same as another existing animal in the list.
*/
public void setAnimal(Animal target, Animal editedAnimal) {
requireAllNonNull(target, editedAnimal);
int index = internalList.indexOf(target);
if (index == -1) {
throw new AnimalNotFoundException();
}
if (!target.isSameAnimal(editedAnimal) && contains(editedAnimal)) {
throw new DuplicateAnimalException();
}
internalList.set(index, editedAnimal);
}
/**
* Removes the equivalent animal from the list.
* The animal must exist in the list.
*/
public void remove(Animal toRemove) {
requireNonNull(toRemove);
if (!internalList.remove(toRemove)) {
throw new AnimalNotFoundException();
}
}
public void setAnimals(UniqueAnimalList replacement) {
requireNonNull(replacement);
internalList.setAll(replacement.internalList);
}
/**
* Replaces the contents of this list with {@code animals}.
* {@code animals} must not contain duplicate animals.
*/
public void setAnimals(List<Animal> animals) {
requireAllNonNull(animals);
if (!animalsAreUnique(animals)) {
throw new DuplicateAnimalException();
}
internalList.setAll(animals);
}
/**
* Replaces the contents of this list with a sorted list instead.
*/
public void sortAnimals(AnimalComparator animalComparator) {
Comparator<Animal> comparator = animalComparator.getAnimalComparator();
SortedList<Animal> sortedList = internalList.sorted(comparator);
internalList.setAll(sortedList);
}
/**
* Returns the backing list as an unmodifiable {@code ObservableList}.
*/
public ObservableList<Animal> asUnmodifiableObservableList() {
return internalUnmodifiableList;
}
@Override
public Iterator<Animal> iterator() {
return internalList.iterator();
}
@Override
public boolean equals(Object other) {
return other == this // short circuit if same object
|| (other instanceof UniqueAnimalList // instanceof handles nulls
&& internalList.equals(((UniqueAnimalList) other).internalList));
}
@Override
public int hashCode() {
return internalList.hashCode();
}
/**
* Returns true if {@code animals} contains only unique animals.
*/
private boolean animalsAreUnique(List<Animal> animals) {
for (int i = 0; i < animals.size() - 1; i++) {
for (int j = i + 1; j < animals.size(); j++) {
if (animals.get(i).isSameAnimal(animals.get(j))) {
return false;
}
}
}
return true;
}
}
| 33.34 | 119 | 0.665467 |
a39495ac432179edb4456e4323487dbff685d424 | 1,136 | package org.odk.collect.android.augmentedreality.scan;
import android.app.Activity;
import android.app.Dialog;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.util.Log;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import com.android.volley.toolbox.ImageLoader;
import org.odk.collect.android.R;
import org.odk.collect.android.augmentedreality.koneksi.VolleySingletonImage;
/**
* Created by Septiawan Aji Pradan on 6/5/2017.
*/
public class CustomModalDetailForm extends Dialog {
private Activity activity;
private String namaForm;
private String totalIsian;
private TextView namaFormTv,totalIsianTv;
CustomModalDetailForm(Activity activity,String namaForm,String totalIsian){
super(activity);
this.activity = activity;
this.namaForm = namaForm;
this.totalIsian = totalIsian;
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.dialog_detail_kuesioner);
}
}
| 27.707317 | 79 | 0.762324 |
85f898255892fad117839fe78ddae4207d22313a | 3,500 | /*
* Copyright 2021 Red Hat, Inc. and/or its affiliates.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.kie.kogito.codegen.rules;
import org.drools.modelcompiler.builder.QueryModel;
import org.kie.internal.ruleunit.RuleUnitDescription;
import org.kie.kogito.codegen.api.GeneratedFile;
import org.kie.kogito.codegen.api.GeneratedFileType;
import org.kie.kogito.codegen.api.context.KogitoBuildContext;
import org.kie.kogito.codegen.api.template.InvalidTemplateException;
import com.github.javaparser.ast.CompilationUnit;
import com.github.javaparser.ast.body.ClassOrInterfaceDeclaration;
import com.github.javaparser.ast.body.ConstructorDeclaration;
import com.github.javaparser.ast.expr.StringLiteralExpr;
import com.github.javaparser.ast.type.ClassOrInterfaceType;
public class QueryEventDrivenExecutorGenerator extends AbstractQueryEntrypointGenerator {
private final String dataType;
private final String returnType;
public QueryEventDrivenExecutorGenerator(RuleUnitDescription ruleUnit, QueryModel query, KogitoBuildContext context) {
super(ruleUnit, query, context, "EventDrivenExecutor", "EventDrivenExecutor");
this.dataType = ruleUnit.getCanonicalName() + (context.hasDI() ? "" : "DTO");
this.returnType = String.format("java.util.List<%s>", query.getBindings().size() != 1
? queryClassName + ".Result"
: query.getBindings().values().iterator().next().getCanonicalName());
}
@Override
public GeneratedFile generate() {
CompilationUnit cu = generator.compilationUnitOrThrow("Could not create CompilationUnit");
ClassOrInterfaceDeclaration classDecl = cu.findFirst(ClassOrInterfaceDeclaration.class)
.orElseThrow(() -> new InvalidTemplateException(generator, "Cannot find class declaration"));
classDecl.setName(targetClassName);
classDecl.findAll(ClassOrInterfaceType.class).forEach(this::interpolateClassOrInterfaceType);
classDecl.findAll(ConstructorDeclaration.class).forEach(this::interpolateConstructorDeclaration);
classDecl.findAll(StringLiteralExpr.class).forEach(this::interpolateStringLiteral);
return new GeneratedFile(GeneratedFileType.SOURCE, generatedFilePath(), cu.toString());
}
private void interpolateClassOrInterfaceType(ClassOrInterfaceType input) {
input.setName(interpolatedTypeNameFrom(input.getNameAsString()));
}
private void interpolateConstructorDeclaration(ConstructorDeclaration input) {
input.setName(interpolatedTypeNameFrom(input.getNameAsString()));
}
private void interpolateStringLiteral(StringLiteralExpr input) {
input.setString(input.getValue().replace("$name$", queryName));
}
private String interpolatedTypeNameFrom(String input) {
return input.replace("$QueryType$", queryClassName)
.replace("$DataType$", dataType)
.replace("$ReturnType$", returnType);
}
}
| 45.454545 | 122 | 0.75 |
e1375d230002ef4bac62809d90babd91f5115e1d | 3,865 | package io.renren.modules.netty.handle;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.channel.group.ChannelGroup;
import io.netty.channel.group.DefaultChannelGroup;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;
import io.netty.util.concurrent.GlobalEventExecutor;
import io.renren.common.utils.SpringContextUtils;
import io.renren.modules.common.domain.RedisCacheKeyConstant;
import io.renren.modules.common.service.IRedisService;
import io.renren.modules.netty.domain.WebSocketRequestDomain;
import io.renren.modules.netty.domain.WebSocketResponseDomain;
import io.renren.modules.netty.enums.WebSocketActionTypeEnum;
import io.renren.modules.netty.service.INettyService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
@Slf4j
public class WebSocketServerHandler extends SimpleChannelInboundHandler<TextWebSocketFrame> {
private static int onlineUserInitCapacity;
public WebSocketServerHandler(int onlineUserInitCapacity) {
WebSocketServerHandler.onlineUserInitCapacity = onlineUserInitCapacity;
}
/**
* 在线用户
*/
public static final ChannelGroup ONLINE_USER_GROUP = new DefaultChannelGroup(GlobalEventExecutor.INSTANCE);
/**
* mobile:channel
*/
public static Map<String, Channel> ONLINE_USER_CHANNEL_MAP = new HashMap<>(onlineUserInitCapacity);
/**
* 存储在线 mobile
*/
public static List<String> ONLINE_USER_WITH_MOBILE = new ArrayList<>(onlineUserInitCapacity);
@Override
public void channelRead0(ChannelHandlerContext ctx, TextWebSocketFrame textWebSocketFrame) {
Channel channel = ctx.channel();
String msgContent = textWebSocketFrame.text();
TextWebSocketFrame socketFrame;
WebSocketRequestDomain requestDomain;
if (StringUtils.isBlank(msgContent) || null == (requestDomain = JSONObject.parseObject(msgContent, WebSocketRequestDomain.class))) {
socketFrame = new TextWebSocketFrame("无效的请求参数");
} else {
WebSocketActionTypeEnum webSocketAction = requestDomain.getWebSocketAction();
INettyService iNettyService = SpringContextUtils.getBean(INettyService.class);
WebSocketResponseDomain responseDomain = iNettyService.handleWebSocketRequest(webSocketAction, channel, requestDomain.getToken(), requestDomain.getContent());
socketFrame = new TextWebSocketFrame(JSON.toJSONString(responseDomain));
}
channel.writeAndFlush(socketFrame);
}
/**
* 客户上线处理: 获取客户端的 channel,并且放到ChannelGroup中去进行管理
*/
@Override
public void handlerAdded(ChannelHandlerContext ctx) {
Channel channel = ctx.channel();
String longText = channel.id().asLongText();
log.info("Channel[{}]已上线!", longText);
SpringContextUtils.getBean(IRedisService.class).putHashKey(RedisCacheKeyConstant.ONLINE_CHANNEL, longText, "");
ONLINE_USER_GROUP.add(channel);
}
/**
* 客户下线处理:剔除用户
*
* @param ctx
*/
@Override
public void handlerRemoved(ChannelHandlerContext ctx) {
Channel channel = ctx.channel();
log.info("Channel[{}]已下线!", channel.id().asLongText());
SpringContextUtils.getBean(INettyService.class).optimizeChannel(channel);
}
/**
* 发生异常之后关闭连接(关闭channel),随后从ChannelGroup中移除
*
* @param ctx
* @param cause
*/
@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
//TODO 清除在线的该用户?
log.error("Web Socket 异常...", cause);
ctx.channel().close();
}
} | 37.524272 | 170 | 0.732471 |
0d647f8e9a7109d2b5825f43ef31b655f8693ec4 | 2,705 | package si.matjazcerkvenik.test.restws.library;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import javax.ws.rs.Consumes;
import javax.ws.rs.DELETE;
import javax.ws.rs.GET;
import javax.ws.rs.PUT;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.UriInfo;
import javax.xml.bind.JAXBElement;
/**
* http://localhost:8080/REST/service/library
* http://localhost:8080/REST/service/library/1
* http://localhost:8080/REST/service/library/count
* http://localhost:8080/REST/service/library/countx
*
*/
@Path("library")
public class LibraryService {
@Context
private UriInfo uriInfo;
private static HashMap<Integer, Book> books = new HashMap<Integer, Book>();
public static int lastBookId = 0;
/** Return the list of all books */
@GET
@Produces({ MediaType.TEXT_XML, MediaType.APPLICATION_XML })
public List<Book> getAllBooks() {
List<Book> list = new ArrayList<Book>();
list.addAll(books.values());
return list;
}
/** Return the book with id */
@GET
@Path("{id}")
@Produces({ MediaType.TEXT_XML, MediaType.APPLICATION_XML })
public Book getBook(@PathParam("id") String id) {
Book b = books.get(Integer.valueOf(id));
if (b != null) {
return b;
} else {
// throw new RuntimeException("getBook(): Book with id " + id
// + " not found");
return null;
}
}
/** Return number of books as plain text */
@GET
@Path("count")
@Produces(MediaType.TEXT_PLAIN)
public String getCount() {
return String.valueOf(books.size());
}
/** Return number of books as xml */
@GET
@Path("countx")
@Produces(MediaType.TEXT_XML)
public BookCounter getCountX() {
BookCounter c = new BookCounter();
c.setCount(books.size());
return c;
}
/** Create new book */
@PUT
@Consumes(MediaType.APPLICATION_XML)
public Response newBook(JAXBElement<Book> book) {
Book b = book.getValue();
b.setId(lastBookId++);
if (!books.containsKey(b.getId())) {
books.put(b.getId(), b);
} else {
b = null;
}
Response res;
if (b == null) {
res = Response.noContent().build();
} else {
res = Response.created(uriInfo.getAbsolutePath()).build();
}
return res;
}
/** Delete a book with id */
@DELETE
@Path("{id}")
public Response deleteBook(@PathParam("id") Integer id) {
Book b = books.remove(id);
Response res;
if (b == null) {
res = Response.notModified("object not found").build();
// throw new RuntimeException("Delete: Book with id " + id + " not
// found");
} else {
res = Response.ok().build();
}
return res;
}
}
| 21.64 | 76 | 0.673198 |
8b8a23a3970f9b0bc643ce5d7536a99681ba9ee1 | 882 | package clinic.programming.training;
import java.util.List;
import java.util.ArrayList;
import org.apache.commons.lang3.StringUtils;
public class Application {
public int countWords(String words){
String[] separatedWords = StringUtils.split(words, ' ');
return separatedWords == null ? 0 : separatedWords.length;
}
public void greeting(){
List<String> list = new ArrayList<>();
list.add("greeting!");
list.forEach(System.out::println);
}
public Application() {
System.out.println ("Inside Application");
}
// method main(): ALWAYS the APPLICATION entry point
public static void main (String[] args) {
System.out.println ("Starting Application");
Application app = new Application();
app.greeting();
int count = app.countWords("hello my friends!");
System.out.println("there are " + count + " words");
}
} | 27.5625 | 61 | 0.678005 |
c6097bb7efc24b3797e70b7ddbc9bc8382c085d6 | 1,150 | package com.rs.game.npc.combat.impl;
import com.rs.game.Animation;
import com.rs.game.Entity;
import com.rs.game.Graphics;
import com.rs.game.npc.NPC;
import com.rs.game.npc.combat.CombatScript;
import com.rs.game.npc.combat.NPCCombatDefinitions;
import com.rs.game.player.Player;
import com.rs.utils.Utils;
public class TokHaarKetDillCombat extends CombatScript {
@Override
public Object[] getKeys() {
return new Object[] { "TokHaar-Ket-Dill" };
}
@Override
public int attack(NPC npc, Entity target) {
NPCCombatDefinitions defs = npc.getCombatDefinitions();
if (Utils.random(6) == 0) {
delayHit(npc, 0, target, getRegularHit(npc, Utils.random(npc.getMaxHit(NPCCombatDefinitions.MELEE) + 1)));
target.setNextGraphics(new Graphics(2999));
if (target instanceof Player) {
Player playerTarget = (Player) target;
playerTarget.getPackets().sendGameMessage("The TokHaar-Ket-Dill slams it's tail to the ground.");
}
} else {
delayHit(npc, 0, target, getMeleeHit(npc, getMaxHit(npc, npc.getAttackStyle(), target)));
}
npc.setNextAnimation(new Animation(defs.getAttackEmote()));
return npc.getAttackSpeed();
}
}
| 31.944444 | 109 | 0.737391 |
f34846bbf1719f3610eab054352ab7874c938a0f | 2,702 | package com.sayee.sxsy.common.utils;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.sayee.sxsy.common.mapper.JsonMapper;
import java.io.PrintStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
public class JsonUtil {
static JsonMapper defaultMapper = new JsonMapper();
public static String toJson(Object obj)
{
return defaultMapper.toJson(obj);
}
public static String toJson(Object obj, boolean fillterSlash)
{
if (fillterSlash) {
return fillterSlash(defaultMapper.toJson(obj));
}
return defaultMapper.toJson(obj);
}
private static String fillterSlash(String orgi) {
if (StringUtils.isBlank(orgi)) {
return orgi;
}
StringBuffer strb = new StringBuffer();
for (int i = 0; i < orgi.length(); i++) {
System.out.println(orgi.charAt(i));
if (orgi.charAt(i) == '\\')
strb.append(new char[] { '\\', '\\' });
else {
strb.append(orgi.charAt(i));
}
}
return strb.toString();
}
// public static <T> T toBean(String json, Class<T> clz)
// {
// return defaultMapper.toBean(json, clz);
// }
public static <T> List<T> toList(String json, Class<T> clz)
{
@SuppressWarnings("unchecked")
List<T> ts = (List<T>) JSONArray.parseArray(json, clz);
return ts;
}
@Deprecated
public static List jsonToStringList(String json)
{
return toList(json, String.class);
}
@Deprecated
public static List jsonToMapList(String json)
{
return toList(json, HashMap.class);
}
public static String map2Json(Map map)
{
StringBuilder sb = new StringBuilder("{");
Set keys = map.keySet();
for (Iterator localIterator = keys.iterator(); localIterator.hasNext(); ) { Object k = localIterator.next();
sb.append("\"");
sb.append(k.toString());
sb.append("\"");
sb.append(":");
Object v = map.get(k);
if ((v instanceof Map)) {
sb.append(map2Json((Map)v));
} else if ((v instanceof Number)) {
sb.append(v.toString());
} else {
sb.append("\"");
sb.append(v.toString());
sb.append("\"");
}
sb.append(",");
}
if (sb.length() > 1) {
return sb.substring(0, sb.length() - 1) + "}";
}
return "}";
}
}
| 26.23301 | 116 | 0.545522 |
09fa07dbeb491ba632295ee28abc464a43431e21 | 1,159 | package gov.cdc.usds.simplereport.db.repository;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
import gov.cdc.usds.simplereport.db.model.SupportedDisease;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.IncorrectResultSizeDataAccessException;
class SupportedDiseaseRepositoryTest extends BaseRepositoryTest {
@Autowired private SupportedDiseaseRepository _repo;
@Test
void findSupportedDiseaseByNameContains_successful() {
SupportedDisease covid = _repo.findSupportedDiseaseByNameContains("COVID");
assertEquals("96741-4", covid.getLoinc());
}
@Test
void findSupportedDiseaseByNameContains_needsConclusiveSearchTerm() {
Throwable caught =
assertThrows(
IncorrectResultSizeDataAccessException.class,
() -> {
_repo.findSupportedDiseaseByNameContains("Flu");
});
assertTrue(caught.getMessage().contains("query did not return a unique result: 2"));
}
}
| 35.121212 | 88 | 0.772217 |
26ea4cbff19117e233023c69e3ff91fd75a324b9 | 1,626 | package com.github.microwww.security.cli;
import com.fasterxml.jackson.annotation.JsonIgnore;
import java.util.ArrayList;
import java.util.List;
public class AjaxMessage<T> {
private List<String> errors;
private List<String> warns;
private String message;
private T data;
private transient Object object;
public boolean isSuccess() {
return errors == null || errors.isEmpty();
}
public List<String> getErrors() {
return errors;
}
public void setErrors(List<String> errors) {
this.errors = errors;
}
public List<String> getWarns() {
return warns;
}
public void setWarns(List<String> warns) {
this.warns = warns;
}
public AjaxMessage addWarn(String warn) {
if (this.warns == null) {
this.warns = new ArrayList<>();
}
this.warns.add(warn);
return this;
}
public AjaxMessage addError(String error) {
if (this.errors == null) {
this.errors = new ArrayList<>();
}
this.errors.add(error);
return this;
}
public String getMessage() {
return message;
}
public AjaxMessage setMessage(String message) {
this.message = message;
return this;
}
public T getData() {
return data;
}
public AjaxMessage setData(T data) {
this.data = data;
return this;
}
@JsonIgnore
public Object getObject() {
return object;
}
public AjaxMessage setObject(Object object) {
this.object = object;
return this;
}
}
| 19.829268 | 51 | 0.586101 |
4f049739e17ff6469e9d4b1806908a1de5f3e573 | 1,418 | package com.amazonaws.greengrass.cddsensehat.leds.arrays;
/*
public class MacOSSenseHatLEDArray implements SenseHatLEDArray {
private final JavaFXLEDArray javaFXLEDArray;
private SenseHatLEDImage senseHatLEDImage;
@Inject
public MacOSSenseHatLEDArray(JavaFXLEDArray javaFXLEDArray) {
this.javaFXLEDArray = javaFXLEDArray;
}
public SenseHatLEDImage get() {
return senseHatLEDImage;
}
public void put(SenseHatLEDImage senseHatLEDImage) {
this.senseHatLEDImage = senseHatLEDImage;
SenseHatLEDImage temp = new SenseHatLEDImage(senseHatLEDImage.getSenseHatLEDs());
SenseHatLEDOrientation orientation = senseHatLEDImage.getSenseHatLEDOrientation();
// Adjust orientation for our JavaFX view
if (orientation.equals(SenseHatLEDOrientation.NORMAL)) {
temp.setSenseHatLEDOrientation(SenseHatLEDOrientation.CCW_90);
} else if (orientation.equals(SenseHatLEDOrientation.CW_90)) {
temp.setSenseHatLEDOrientation(SenseHatLEDOrientation.NORMAL);
} else if (orientation.equals(SenseHatLEDOrientation.UPSIDE_DOWN)) {
temp.setSenseHatLEDOrientation(SenseHatLEDOrientation.CW_90);
} else if (orientation.equals(SenseHatLEDOrientation.CCW_90)) {
temp.setSenseHatLEDOrientation(SenseHatLEDOrientation.UPSIDE_DOWN);
}
javaFXLEDArray.draw(temp);
}
}
*/
| 36.358974 | 90 | 0.735543 |
001959db1d917beb5194ab32a5b574a8b596cb1d | 241 | package com.a9032676.fpstd.exception;
public class Undefined extends RuntimeException {
private Undefined() {
super("** Exception: fpstd.undefined");
}
public static Undefined undefined() { return new Undefined(); }
}
| 21.909091 | 67 | 0.692946 |
38ad36f74d6bb59458aa13d59147ce4b799fe5de | 1,856 | package feta.readnet;
import feta.FetaOptions;
import feta.network.Link;
import org.json.simple.JSONObject;
import java.io.*;
import java.util.ArrayList;
public abstract class ReadNet {
public ArrayList<Link> links_;
LinkBuilder lb_;
public String sep_;
String networkInput_;
boolean removeDuplicates_=true;
public ReadNet(FetaOptions options){
links_= new ArrayList<Link>();
sep_=options.inSep_;
networkInput_=options.netInputFile_;
if (options.directedInput_) {
lb_= new DirectedLinkBuilder();
} else lb_= new UndirectedLinkBuilder();
}
public final void readNetwork(){
int linkno = 1;
try {
FileInputStream fstream = new FileInputStream(networkInput_);
DataInputStream dstream = new DataInputStream(fstream);
BufferedReader br = new BufferedReader(new InputStreamReader(dstream));
String line;
while ((line = br.readLine()) != null) {
line = line.trim();
if (line.length() == 0)
continue;
Link link = parseLine(line, linkno);
// aint got time for loops
if (link.sourceNode_.equals(link.destNode_)) {
System.out.println("Self Loop at time "+link.time_+"!");
continue;
}
// if (removeDuplicates_ && links_.contains(link))
// continue;
links_.add(link);
}
} catch (FileNotFoundException e) {
System.err.println("Cannot read network. File "+networkInput_+" not found.");
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
public abstract Link parseLine(String line, long linkno);
}
| 30.933333 | 89 | 0.574892 |
7c30fe29674db06ca7b6693615f163f3a680ad51 | 5,608 | /**
*
*/
package com.perforce.p4java.impl.generic.core;
import java.util.Date;
import java.util.Map;
import com.perforce.p4java.Log;
import com.perforce.p4java.core.ILabelSummary;
import com.perforce.p4java.impl.mapbased.MapKeys;
/**
* Default implementation of the ILabelSumamry interface.
*/
public class LabelSummary extends ServerResource implements ILabelSummary {
protected static final String LOCKED_VALUE = "locked";
protected static final String UNLOCKED_VALUE = "unlocked";
protected static final String AUTORELOAD_VALUE = "autoreload";
protected static final String NOAUTORELOAD_VALUE = "noautoreload";
protected String name = null;
protected String ownerName = null;
protected Date lastAccess = null;
protected Date lastUpdate = null;
protected String description = null;
protected String revisionSpec = null;
protected boolean locked = false;
protected boolean unloaded = false;
protected boolean autoreload = false;
/**
* Default constructor -- set all fields to null or false.
*/
public LabelSummary() {
super(false, false);
}
/**
* Construct an empty LabelSummary and appropriately initialize
* the ServerResource superclass fields according to whether this
* summary a summary only or part of the full Label class.
*/
public LabelSummary(boolean summaryOnly) {
super(!summaryOnly, !summaryOnly);
}
/**
* Construct a LabelSummary from a map returned from the Perforce server's
* getLabelSummaryList.<p>
*
* If the map is null, this is equivalent to calling the default constructor.
*/
public LabelSummary(Map<String, Object> map) {
super(false, false);
if (map != null) {
try {
this.name = (String) map.get(MapKeys.LABEL_LC_KEY);
this.description = (String) map.get(MapKeys.DESCRIPTION_KEY);
if (this.description != null) {
this.description = this.description.trim();
}
this.ownerName = (String) map.get(MapKeys.OWNER_KEY);
this.lastUpdate = new Date(Long.parseLong((String) map
.get(MapKeys.UPDATE_KEY)) * 1000);
this.lastAccess = new Date(Long.parseLong((String) map
.get(MapKeys.ACCESS_KEY)) * 1000);
this.revisionSpec = (String) map.get(MapKeys.REVISION_KEY);
String optStr = (String) map.get(MapKeys.OPTIONS_KEY);
if (optStr != null) {
String[] optParts = optStr.split("\\s+");
if (optParts != null && optParts.length > 0) {
for (String optPart : optParts) {
if (optPart.equalsIgnoreCase(LOCKED_VALUE)) {
this.locked = true;
} else if (optPart.equalsIgnoreCase(UNLOCKED_VALUE)) {
this.locked = false;
} else if (optPart.equalsIgnoreCase(AUTORELOAD_VALUE)) {
this.autoreload = true;
} else if (optPart.equalsIgnoreCase(NOAUTORELOAD_VALUE)) {
this.autoreload = false;
}
}
}
}
if (map.get("IsUnloaded") != null
&& ((String) map.get("IsUnloaded")).equals("1")) {
this.unloaded = true;
}
} catch (Throwable thr) {
Log.error("Unexpected exception in LabelSummary constructor: "
+ thr.getLocalizedMessage());
Log.exception(thr);
}
}
}
/**
* @see com.perforce.p4java.core.ILabelSummary#getName()
*/
public String getName() {
return name;
}
/**
* @see com.perforce.p4java.core.ILabelSummary#setName(java.lang.String)
*/
public void setName(String name) {
this.name = name;
}
/**
* @see com.perforce.p4java.core.ILabelSummary#getOwnerName()
*/
public String getOwnerName() {
return ownerName;
}
/**
* @see com.perforce.p4java.core.ILabelSummary#setOwnerName(java.lang.String)
*/
public void setOwnerName(String ownerName) {
this.ownerName = ownerName;
}
/**
* @see com.perforce.p4java.core.ILabelSummary#getLastAccess()
*/
public Date getLastAccess() {
return lastAccess;
}
/**
* @see com.perforce.p4java.core.ILabelSummary#setLastAccess(java.util.Date)
*/
public void setLastAccess(Date lastAccess) {
this.lastAccess = lastAccess;
}
/**
* @see com.perforce.p4java.core.ILabelSummary#getLastUpdate()
*/
public Date getLastUpdate() {
return lastUpdate;
}
/**
* @see com.perforce.p4java.core.ILabelSummary#setLastUpdate(java.util.Date)
*/
public void setLastUpdate(Date lastUpdate) {
this.lastUpdate = lastUpdate;
}
/**
* @see com.perforce.p4java.core.ILabelSummary#getDescription()
*/
public String getDescription() {
return description;
}
/**
* @see com.perforce.p4java.core.ILabelSummary#setDescription(java.lang.String)
*/
public void setDescription(String description) {
this.description = description;
}
/**
* @see com.perforce.p4java.core.ILabelSummary#getRevisionSpec()
*/
public String getRevisionSpec() {
return revisionSpec;
}
/**
* @see com.perforce.p4java.core.ILabelSummary#setRevisionSpec(java.lang.String)
*/
public void setRevisionSpec(String revisionSpec) {
this.revisionSpec = revisionSpec;
}
/**
* @see com.perforce.p4java.core.ILabelSummary#isLocked()
*/
public boolean isLocked() {
return locked;
}
/**
* @see com.perforce.p4java.core.ILabelSummary#setLocked(boolean)
*/
public void setLocked(boolean locked) {
this.locked = locked;
}
/**
* @see com.perforce.p4java.core.ILabelSummary#isAutoReload()
*/
public boolean isAutoReload() {
return autoreload;
}
/**
* @see com.perforce.p4java.core.ILabelSummary#setAutoReload(boolean)
*/
public void setAutoReload(boolean autoreload) {
this.autoreload = autoreload;
}
/**
* @see com.perforce.p4java.core.ILabelSummary#isUnloaded()
*/
public boolean isUnloaded() {
return unloaded;
}
}
| 25.375566 | 81 | 0.694009 |
65dd02dc9a19427b9dd04e58ee9575cfd037293c | 5,704 | //---------------------------------------------------------------------------------
//
// BlackBerry Extensions
// Copyright (c) 2008-2012 Vincent Simonetti
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated
// documentation files (the "Software"), to deal in the Software without restriction, including without limitation
// the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and
// to permit persons to whom the Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
//
//---------------------------------------------------------------------------------
//
package rebuild.comp.net.rim.device.api.ui.picker;
import java.util.Enumeration;
import java.util.Vector;
import javax.microedition.io.file.FileSystemRegistry;
import net.rim.device.api.ui.Screen;
import net.rim.device.api.ui.UiApplication;
import rebuild.BBXResource;
/**
* FilePicker implementation for all OS versions
*/
final class FilePickerImpl extends FilePicker
{
static net.rim.device.api.i18n.ResourceBundle resources;
static
{
FilePickerImpl.resources = net.rim.device.api.i18n.ResourceBundle.getBundle(BBXResource.BUNDLE_ID, BBXResource.BUNDLE_NAME);
}
private int version;
boolean excludeDRMForwardLock;
String rootPath;
private String[] filters;
private Listener listener;
private FilePickerUI currentFPui;
public FilePickerImpl(int version)
{
this.version = version;
this.excludeDRMForwardLock = false;
}
public void cancel()
{
if(this.currentFPui != null)
{
this.currentFPui.resetSelectedFile();
this.currentFPui.close();
}
}
public void excludeDRMForwardLocked(boolean exclude)
{
if(this.version < VERSION_7)
{
throw new UnsupportedOperationException();
}
else
{
this.excludeDRMForwardLock = exclude;
}
}
public void setFilter(String filterString)
{
if(filterString == null)
{
this.filters = null;
}
else
{
Vector v = new Vector();
while(filterString.length() > 0)
{
int index = filterString.indexOf(':');
if(index == -1)
{
v.addElement(filterString);
filterString = "";
}
else
{
v.addElement(filterString.substring(0, index));
filterString = filterString.substring(index);
}
}
filters = new String[v.size()];
v.copyInto(filters);
}
}
public void setListener(Listener listener)
{
this.listener = listener;
}
public void setPath(String defaultPath)
{
//Could do checks for validity but the value that will be passed in will be the same as the value returned to the listener, so it will always be valid. If it isn't then the UI will complain.
this.rootPath = defaultPath;
}
public void setTitle(String title)
{
if(this.version < VERSION_6)
{
throw new UnsupportedOperationException();
}
else
{
//TODO
}
}
public void setView(int view)
{
if(this.version < VERSION_6)
{
throw new UnsupportedOperationException();
}
else
{
//TODO
}
}
public String show()
{
//Create picker
final FilePickerUI fpui;
switch(version)
{
case VERSION_5:
fpui = new FilePickerUI5(this);
break;
case VERSION_6:
//TODO
case VERSION_7:
//TODO
default:
throw new UnsupportedOperationException();
}
this.currentFPui = fpui;
//Get UI application
final UiApplication app = UiApplication.getUiApplication();
//Push screen on display
if(UiApplication.isEventDispatchThread())
{
app.pushModalScreen((Screen)fpui);
}
else
{
app.invokeAndWait(new Runnable()
{
public void run()
{
app.pushModalScreen((Screen)fpui);
}
});
}
//Process results
this.currentFPui = null;
if(this.listener != null)
{
this.listener.selectionDone(fpui.getSelectedFile());
}
return fpui.getSelectedFile();
}
//Helper functions
static String friendlyName(String name)
{
String[] roots = FilePickerImpl.resources.getStringArray(BBXResource.FILEPICKER_FRIENDLY_ROOTS_SRC);
String[] rootsF = FilePickerImpl.resources.getStringArray(BBXResource.FILEPICKER_FRIENDLY_ROOTS);
for(int i = roots.length - 1; i >= 0; i--)
{
if(name.equals(roots[i]))
{
return rootsF[i];
}
}
return name;
}
static String[] getRoots()
{
Enumeration en = FileSystemRegistry.listRoots();
Vector v = new Vector();
while(en.hasMoreElements())
{
v.addElement(en.nextElement());
}
String[] str = new String[v.size()];
v.copyInto(str);
int l = v.size();
for(int i = 0; i < l; i++)
{
str[i] = str[i].substring(0, str[i].length() - 1);
}
return str;
}
//All that is really needed by the FilePicker from the UI
interface FilePickerUI
{
public String getSelectedFile();
public void resetSelectedFile();
public void close();
}
}
| 24.8 | 193 | 0.650596 |
57ed4f926f19d9c54b4dd53193266bb985a40393 | 2,262 | package com.gtxc.practice.hackerrank;
/*
Created by gt at 3:36 AM on Monday, February 14, 2022.
Project: practice, Package: com.gtxc.practice.hackerrank.
*/
import java.util.Arrays;
import java.util.Scanner;
public class ArrayGame {
public static boolean canWin(int leap, int[] game) {
// Return true if you can win the game; otherwise, return false.
// return recursiveApproach(leap, game, 0);
int[] cumsum = new int[game.length + 1];
cumsum[0] = 0;
for (int i = 0; i < game.length; ++i) {
if (game[i] == 0) {
continue;
}
cumsum[i+1] += cumsum[i] + game[i];
}
int cumsummax = Arrays.stream(cumsum).max().getAsInt();
if (leap <= cumsummax && cumsummax > 0) {
return false;
}
int n = 0;
while (true) {
if (n >= game.length || n+leap >= game.length || n+1 >= game.length) {
return true;
}
if (n < 0 || game[n] == 1) {
return false;
}
game[n] = 1;
if (n+1 < game.length && game[n+1] == 0) {
++n;
} else if (n-1 > 0 && game[n-1] == 0) {
--n;
} else if (n+leap < game.length && game[n+leap] == 0) {
n += leap;
}
}
}
private static boolean recursiveApproach(int leap, int[] game, int i) {
if (i >= game.length) {
return true;
}
if (i < 0 || game[i] == 1) {
return false;
}
game[i] = 1;
return recursiveApproach(leap, game, i+1) ||
recursiveApproach(leap, game, i-1) ||
recursiveApproach(leap, game, i+leap);
}
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int q = scan.nextInt();
while (q-- > 0) {
int n = scan.nextInt();
int leap = scan.nextInt();
int[] game = new int[n];
for (int i = 0; i < n; i++) {
game[i] = scan.nextInt();
}
System.out.println( (canWin(leap, game)) ? "YES" : "NO" );
}
scan.close();
}
}
| 27.253012 | 82 | 0.453581 |
85a98465b40e9e9760777b058ba5012d698341d6 | 2,017 | /**
* Copyright (C) 2012 Google, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.onebusaway.uk.naptan.csv;
import static org.junit.Assert.assertEquals;
import java.io.File;
import java.io.IOException;
import java.util.List;
import org.junit.Test;
import org.onebusaway.csv_entities.CsvEntityReader;
import org.onebusaway.csv_entities.ListEntityHandler;
import org.onebusaway.csv_entities.schema.AnnotationDrivenEntitySchemaFactory;
public class NaPTANStopTest {
@Test
public void test() throws IOException {
CsvEntityReader reader = new CsvEntityReader();
reader.setInputLocation(new File(
"src/test/resources/org/onebusaway/uk/naptan/csv/test_data"));
AnnotationDrivenEntitySchemaFactory entitySchema = new AnnotationDrivenEntitySchemaFactory();
entitySchema.addPackageToScan("org.onebusaway.uk.naptan.csv");
reader.setEntitySchemaFactory(entitySchema);
ListEntityHandler<NaPTANStop> stopHandler = new ListEntityHandler<NaPTANStop>();
reader.addEntityHandler(stopHandler);
reader.readEntities(NaPTANStop.class);
reader.close();
List<NaPTANStop> stops = stopHandler.getValues();
assertEquals(2, stops.size());
NaPTANStop stop = stops.get(0);
assertEquals("010000001", stop.getAtcoCode());
assertEquals("bstpgit", stop.getNaptanCode());
assertEquals("Cassell Road", stop.getCommonName());
assertEquals(-2.51685, stop.getLongitude(), 1e-5);
assertEquals(51.48441, stop.getLatitude(), 1e-5);
}
}
| 37.351852 | 97 | 0.752603 |
36aca431d0b29ca5cb63155c578d5c5a199cadcc | 1,896 | package co.cargoai.sqs.internal;
import co.cargoai.sqs.api.SqsMessagePollerProperties;
import lombok.RequiredArgsConstructor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import software.amazon.awssdk.services.sqs.SqsClient;
import software.amazon.awssdk.services.sqs.model.Message;
import software.amazon.awssdk.services.sqs.model.ReceiveMessageRequest;
import software.amazon.awssdk.services.sqs.model.ReceiveMessageResponse;
import java.util.Collections;
import java.util.List;
/**
* Fetches a batch of messages from SQS.
*/
@RequiredArgsConstructor
class SqsMessageFetcher {
private static final Logger logger = LoggerFactory.getLogger(SqsMessageFetcher.class);
private final SqsClient sqsClient;
private final SqsMessagePollerProperties properties;
List<Message> fetchMessages() {
logger.debug("fetching messages from SQS queue {}", properties.getQueueUrl());
ReceiveMessageRequest request = ReceiveMessageRequest.builder()
.maxNumberOfMessages(properties.getBatchSize())
.queueUrl(properties.getQueueUrl())
.waitTimeSeconds((int) properties.getWaitTime().getSeconds())
.build();
ReceiveMessageResponse result = sqsClient.receiveMessage(request);
if (result.sdkHttpResponse() == null) {
logger.error("cannot determine success from response for SQS queue {}: {}",
properties.getQueueUrl(),
result.sdkHttpResponse());
return Collections.emptyList();
}
if (result.sdkHttpResponse().statusCode() != 200) {
logger.error("got error response from SQS queue {}: {}",
properties.getQueueUrl(),
result.sdkHttpResponse());
return Collections.emptyList();
}
logger.debug("polled {} messages from SQS queue {}",
result.messages().size(),
properties.getQueueUrl());
return result.messages();
}
}
| 32.135593 | 88 | 0.7173 |
f53978d74ef3149c6c9e179a1b340d7a884cd1c0 | 2,808 | /*
* WiFi Analyzer
* Copyright (C) 2016 VREM Software Development <[email protected]>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>
*/
package com.aqnote.app.wifi.settings;
import android.app.ActionBar;
import android.view.MenuItem;
import com.aqnote.app.wifi.BuildConfig;
import com.aqnote.app.wifi.R;
import com.aqnote.app.wifi.RobolectricUtil;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.robolectric.Robolectric;
import org.robolectric.RobolectricTestRunner;
import org.robolectric.annotation.Config;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
@RunWith(RobolectricTestRunner.class)
@Config(constants = BuildConfig.class)
public class SettingActivityTest {
private SettingActivity fixture;
@Before
public void setUp() {
RobolectricUtil.INSTANCE.getMainActivity();
fixture = Robolectric.setupActivity(SettingActivity.class);
}
@Test
public void testTitle() throws Exception {
// setup
String expected = fixture.getResources().getString(R.string.action_settings);
// execute
ActionBar actual = fixture.getActionBar();
// validate
assertNotNull(actual);
assertEquals(expected, actual.getTitle());
}
@Test
public void testOnOptionsItemSelectedWithHome() throws Exception {
// setup
MenuItem menuItem = mock(MenuItem.class);
when(menuItem.getItemId()).thenReturn(android.R.id.home);
// execute
boolean actual = fixture.onOptionsItemSelected(menuItem);
// validate
assertTrue(actual);
verify(menuItem).getItemId();
}
@Test
public void testOnOptionsItemSelected() throws Exception {
// setup
MenuItem menuItem = mock(MenuItem.class);
// execute
boolean actual = fixture.onOptionsItemSelected(menuItem);
// validate
assertFalse(actual);
}
} | 32.275862 | 85 | 0.721866 |
cd9d002aa30e16512cab178ba3b93b2b309c4811 | 197 | package vendor.exceptions;
public class BadFormatException extends Exception {
public BadFormatException(){
super();
}
public BadFormatException(String message){
super(message);
}
}
| 14.071429 | 51 | 0.741117 |
22c96bffd6bbf978cc3f94780454a563a59b10fb | 2,169 | package string;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
/**
* 93. Restore IP Addresses
* <p>
* Given a string containing only digits, restore it by returning all possible valid IP address combinations.
* <p>
* Example:
* Input: "25525511135"
* Output: ["255.255.11.135", "255.255.111.35"]
* <p>
* Created by zjm on 2019/9/12 22:33
*/
public class RestoreIPAddresses {
//在输入字符串中加入三个点,将字符串分为四段,每一段必须合法,求所有可能的情况
//使用动态规划,每组排除首字母是0的超过两位的数字,
public List<String> restoreIpAddresses(String s) {
if(s.length() < 4 || s.length() > 12) {
return Collections.EMPTY_LIST;
}
List<String> res = new ArrayList();
dfs(s, 0, new String(), res);
return res;
}
private void dfs(String s, int start, String item, List<String> res) {
if(start == 3 && isValid(s)) {
res.add(item + s);
return;
}
for(int i = 0; i < 3 && i < s.length() - 1; i++) {
String sub = s.substring(0, i+1);
if(isValid(sub)) {
dfs(s.substring(i+1, s.length()), start+1, item+sub+".", res);
}
}
}
private boolean isValid(String s) {
if(s.charAt(0) == '0') {
return s.equals("0");
}
int n = Integer.valueOf(s);
if(n <= 255 && n > 0) {
return true;
}
return false;
}
public List<String> restoreIpAddressesFaster(String s) {
List<String> res = new ArrayList<String>();
helper(s, 0, "", res);
return res;
}
public void helper(String s, int n, String out, List<String> res) {
if (n == 4) {
if (s.isEmpty()) {
res.add(out);
}
return;
}
for (int k = 1; k < 4; ++k) {
if (s.length() < k) break;
int val = Integer.parseInt(s.substring(0, k));
//010转成整数变成10,长度和原来的字符串长度不相等
if (val > 255 || k != String.valueOf(val).length()) continue;
helper(s.substring(k), n + 1, out + s.substring(0, k) + (n == 3 ? "" : "."), res);
}
}
}
| 27.807692 | 109 | 0.510834 |
8269ea14a143bacedfd57e8ec3f1c690a597836d | 1,280 | package org.fun4j.compiler.expressions;
import org.fun4j.compiler.Expression;
import org.objectweb.asm.MethodVisitor;
/**
* A Lookup expression.
* Represents Function objects that are looked up from the local map of a function instance.
*/
public class LookupLocal extends Expression {
String strName = null;
Expression eName = null;
public LookupLocal(final String o) {
lineIncrement = 0;
this.strName = o;
}
public LookupLocal(final Expression e) {
lineIncrement = 0;
this.eName = e;
}
public String toString() {
String displayName = null;
if (strName != null) {
displayName = strName;
}
else {
displayName = eName.toString();
}
return "(lookupLocal " + displayName + ")";
}
public void compile(final MethodVisitor mv) {
writeLineInfo(mv);
mv.visitVarInsn(ALOAD, 0);
if (strName != null) {
mv.visitLdcInsn(strName);
}
else {
eName.compile(mv);
mv.visitTypeInsn(CHECKCAST, "java/lang/String");
}
mv.visitMethodInsn(INVOKEVIRTUAL, "org/fun4j/compiler/BaseFunction", "lookupLocal", "(Ljava/lang/String;)Lorg/fun4j/Function;");
}
} | 24.615385 | 136 | 0.600781 |
b631c3b60c2e5b0d6a2650c1fc64516661def92a | 2,581 | package com.negusoft.holoaccent.example.fragment;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.ActionMode;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AbsListView.MultiChoiceModeListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import com.negusoft.holoaccent.example.R;
public class ListFragment extends Fragment implements OnItemClickListener {
private ListView mListView;
private ActionMode mActionMode;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View result = inflater.inflate(R.layout.list, null);
mListView = (ListView)result.findViewById(R.id.listView);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(getActivity(),
R.layout.list_item_multiple_choice,
android.R.id.text1,
getResources().getStringArray(R.array.list_items));
mListView.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
mListView.setAdapter(adapter);
mListView.setOnItemClickListener(this);
mListView.setMultiChoiceModeListener(mMultiChoiceModeListener);
mListView.setFastScrollEnabled(true);
mListView.setFastScrollAlwaysVisible(true);
return result;
}
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
if (mActionMode != null) {
if (mListView.getCheckedItemCount() == 0)
mActionMode.finish();
} else {
getActivity().startActionMode(mMultiChoiceModeListener);
}
}
private MultiChoiceModeListener mMultiChoiceModeListener = new MultiChoiceModeListener() {
@Override
public boolean onActionItemClicked(ActionMode mode, MenuItem item) {
return true;
}
@Override
public boolean onCreateActionMode(ActionMode mode, Menu menu) {
MenuInflater inflater = mode.getMenuInflater();
inflater.inflate(R.menu.spinner, menu);
return true;
}
@Override
public void onDestroyActionMode(ActionMode mode) {
mActionMode = null;
for (int pos = 0; pos < mListView.getCount(); pos++)
mListView.setItemChecked(pos, false);
}
@Override
public boolean onPrepareActionMode(ActionMode mode, Menu menu) {
mActionMode = mode;
return false;
}
@Override
public void onItemCheckedStateChanged(ActionMode mode, int position, long id, boolean checked) {
}};
}
| 29.666667 | 100 | 0.772569 |
b67f16f38729fd5d5e93076dbb4bbfe9ddb6af72 | 409 | package com.airfranceklm.amt.yaml.list;
import com.airfranceklm.amt.yaml.YamlBinding;
import com.airfranceklm.amt.yaml.YamlReadable;
import java.util.List;
@YamlReadable
public class StringListBean {
private List<String> coll;
public List<String> getColl() {
return coll;
}
@YamlBinding("stringList")
public void setColl(List<String> coll) {
this.coll = coll;
}
}
| 19.47619 | 46 | 0.696822 |
64d2a6cdbe1447d5863a42442eb8e1ef50431bfb | 4,680 | /*
* Copyright (C) 2016 [email protected]
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.chzz.library;
import android.util.Base64;
import java.io.IOException;
import java.io.InputStream;
import java.security.DigestInputStream;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
/**
* Create by h4de5ing 2016/5/7 007
* checked
*/
public class CipherUtils {
public static String encode(String input) {
try {
MessageDigest messageDigest = MessageDigest.getInstance("MD5");
byte[] inputByteArray = input.getBytes();
messageDigest.update(inputByteArray);
byte[] resultByteArray = messageDigest.digest();
char[] hexDigits = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'};
char[] resultCharArray = new char[resultByteArray.length * 2];
int index = 0;
for (byte b : resultByteArray) {
resultCharArray[index++] = hexDigits[b >>> 4 & 0xf];
resultCharArray[index++] = hexDigits[b & 0xf];
}
return new String(resultCharArray);
} catch (NoSuchAlgorithmException e) {
return null;
}
}
public static String encode(InputStream in) {
int bufferSize = 256 * 1024;
DigestInputStream digestInputStream = null;
try {
MessageDigest messageDigest = MessageDigest.getInstance("MD5");
digestInputStream = new DigestInputStream(in, messageDigest);
byte[] buffer = new byte[bufferSize];
while (digestInputStream.read(buffer) > 0) ;
messageDigest = digestInputStream.getMessageDigest();
byte[] resultByteArray = messageDigest.digest();
char[] hexDigits = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'};
char[] resultCharArray = new char[resultByteArray.length * 2];
int index = 0;
for (byte b : resultByteArray) {
resultCharArray[index++] = hexDigits[b >>> 4 & 0xf];
resultCharArray[index++] = hexDigits[b & 0xf];
}
return new String(resultCharArray);
} catch (NoSuchAlgorithmException e) {
return null;
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (digestInputStream != null)
digestInputStream.close();
} catch (Exception e) {
e.printStackTrace();
}
}
return null;
}
public static String base64Encode(String str) {
return Base64.encodeToString(str.getBytes(), Base64.DEFAULT);
}
public static String base64Decode(String str) {
return Base64.decode(str.getBytes(), Base64.DEFAULT).toString();
}
public static String XorEncode(String str,String privatekey) {
int[] snNum = new int[str.length()];
String result = "";
String temp = "";
for (int i = 0, j = 0; i < str.length(); i++, j++) {
if (j == privatekey.length())
j = 0;
snNum[i] = str.charAt(i) ^ privatekey.charAt(j);
}
for (int k = 0; k < str.length(); k++) {
if (snNum[k] < 10) {
temp = "00" + snNum[k];
} else {
if (snNum[k] < 100) {
temp = "0" + snNum[k];
}
}
result += temp;
}
return result;
}
public static String XorDecode(String str,String privateKey) {
char[] snNum = new char[str.length() / 3];
String result = "";
for (int i = 0, j = 0; i < str.length() / 3; i++, j++) {
if (j == privateKey.length())
j = 0;
int n = Integer.parseInt(str.substring(i * 3, i * 3 + 3));
snNum[i] = (char) ((char) n ^ privateKey.charAt(j));
}
for (int k = 0; k < str.length() / 3; k++) {
result += snNum[k];
}
return result;
}
}
| 34.666667 | 112 | 0.543803 |
dff5210b803a36ac998eb06fcd9d469ed53872cc | 6,840 | /*
* Copyright 2006-2018 Prowide
*
* 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.prowidesoftware.swift.utils;
import com.prowidesoftware.deprecation.DeprecationUtils;
import com.prowidesoftware.deprecation.ProwideDeprecated;
import com.prowidesoftware.deprecation.TargetYear;
import com.prowidesoftware.swift.model.SwiftBlock2Input;
import com.prowidesoftware.swift.model.SwiftMessage;
import com.prowidesoftware.swift.model.SwiftTagListBlock;
import com.prowidesoftware.swift.model.Tag;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.Validate;
import java.util.ArrayList;
import java.util.List;
/**
* Utility methods for test cases
*
* @author www.prowidesoftware.com
*/
public class TestUtils {
// Suppress default constructor for noninstantiability
private TestUtils() {
throw new AssertionError();
}
public static SwiftMessage createMT(final int type) {
final SwiftMessage result = new SwiftMessage(true);
final SwiftBlock2Input b2 = new SwiftBlock2Input();
b2.setMessageType(Integer.toString(type));
b2.setInput(true);
b2.setMessagePriority("N");
b2.setDeliveryMonitoring("2");
b2.setObsolescencePeriod("020");
b2.setReceiverAddress("12345612XXXX");
result.setBlock2(b2);
return result;
}
private static final String MTXXXMESSAGE = "Use new MTxxx plus the append methods instead.";
/**
* create a message of given type, initialize blocks and add in order tags param in block 4
*
* @deprecated use new MTxxx instead of this
*/
@Deprecated
@ProwideDeprecated(phase4=TargetYear._2019)
public static SwiftMessage createMT(final int i, final Tag ... tags ) {
DeprecationUtils.phase3(TestUtils.class, "createMT(int, Tag...)", MTXXXMESSAGE);
final SwiftMessage result = createMT(i);
if (tags != null && tags.length>0) {
for (final Tag t:tags) {
result.getBlock4().append(t);
}
}
return result;
}
/**
* @deprecated use new MTxxx instead of this
*/
@Deprecated
@ProwideDeprecated(phase4=TargetYear._2019)
public static SwiftMessage createMT(final int i, final SwiftTagListBlock ... blocks ) {
DeprecationUtils.phase3(TestUtils.class, "createMT(int, SwiftTagListBlock...)", MTXXXMESSAGE);
final SwiftMessage result = createMT(i);
if (blocks != null && blocks.length>0) {
for (final SwiftTagListBlock b:blocks) {
result.getBlock4().getTags().addAll(b.getTags());
}
}
return result;
}
/**
* Adds the given tags in the message, surrounded with sequence boundaries for given sequence name.
*/
public static SwiftMessage addSeq(final SwiftMessage msg, final String sequenceIdentifier, final Tag ... tags) {
msg.getBlock4().append(new Tag("16R", sequenceIdentifier));
if (tags != null && tags.length>0) {
for (final Tag t:tags) {
msg.getBlock4().append(t);
}
}
msg.getBlock4().append(new Tag("16S", sequenceIdentifier));
return msg;
}
/**
* enclose tags in B4 with the given 16R/S tags.
* additional tags, if any, are added right after the first 16R:sequenceIdentifier
*/
public static SwiftMessage enclose(final SwiftMessage msg, final String sequenceIdentifier, final Tag ... tags) {
final List<Tag> block4 = msg.getBlock4().getTags();
block4.add(0, new Tag("16R", sequenceIdentifier));
if (tags != null && tags.length>0) {
for (int i=tags.length-1;i>=0;i--) {
block4.add(1, tags[i]);
}
}
block4.add(new Tag("16S", sequenceIdentifier));
return msg;
}
/**
* @deprecated use new MTnnn instead
*/
@Deprecated
@ProwideDeprecated(phase4=TargetYear._2019)
public static SwiftMessage createMTwithEmptyTags(final int i, final String ... tags) {
DeprecationUtils.phase3(TestUtils.class, "createMTwithEmptyTags(int, String...)", MTXXXMESSAGE);
final SwiftMessage r = createMT(i, (Tag[])null);
if (tags != null && tags.length>0) {
for (final String n : tags) {
r.getBlock4().append(new Tag(n, "ignored"));
}
}
return r;
}
/**
* Returns the array of tags enclosed in 16RS with the given qualifier
* @param startEnd16rs qualifier for 16RS tag
* @param tags tags to include
* @return the created array of tags
* @deprecated use directly MTXXX.SequenceX.newInstance(Tag ...)
*/
@Deprecated
@ProwideDeprecated(phase4=TargetYear._2019)
public static Tag[] newSeq(final String startEnd16rs, final Tag ... tags ) {
DeprecationUtils.phase3(TestUtils.class, "newSeq(String, Tag...)", MTXXXMESSAGE);
final ArrayList<Tag> result = new ArrayList<>();
result.add(new Tag("16R", startEnd16rs));
if (tags != null && tags.length>0) {
for (final Tag t : tags) {
result.add(t);
}
}
result.add(new Tag("16S", startEnd16rs));
return (Tag[]) result.toArray(new Tag[result.size()]);
}
/**
* Returns an array of empty value tags enclosed in 16RS with the given qualifier
* @param startEnd16rs qualifier for 16RS tag
* @param tagnames tag names to create
* @return the created array of tag objects
* @deprecated use directly MTXXX.SequenceX.newInstance(Tag ...)
*/
@Deprecated
@ProwideDeprecated(phase4=TargetYear._2019)
public static Tag[] newSeq(final String startEnd16rs, final String ... tagnames ) {
DeprecationUtils.phase3(TestUtils.class, "newSeq(String, String...)", MTXXXMESSAGE);
final ArrayList<Tag> result = new ArrayList<>();
result.add(new Tag("16R", startEnd16rs));
if (tagnames != null && tagnames.length>0) {
for (final String name : tagnames) {
result.add(new Tag(name, ""));
}
}
result.add(new Tag("16S", startEnd16rs));
return (Tag[]) result.toArray(new Tag[result.size()]);
}
/**
* Appends block to the block4 of the given message.
* @param m the message that will be appended the block
* @param block block to append
* @throws java.lang.IllegalArgumentException if m or block is null
*/
public static void append(final SwiftMessage m, final SwiftTagListBlock block) {
Validate.notNull(m, "message must not be null");
Validate.notNull(block, "block must not be null");
m.getBlock4().append(block);
}
/**
* Patches a simple XPath to make it work in XMLUnit asserts
*/
public static String patch(final String xpath) {
StringBuilder result = new StringBuilder();
for (String s : StringUtils.split(xpath, "/")) {
result.append("/*[local-name()='"+ s + "']");
}
return result.toString();
}
}
| 33.203883 | 114 | 0.712573 |
7672f4a23b5e8c46a5087c90ae832410d2b556b6 | 14,980 | package org.ovirt.engine.api.restapi.resource;
import java.util.List;
import java.util.Set;
import javax.ws.rs.core.HttpHeaders;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.UriInfo;
import org.ovirt.engine.api.common.util.DetailHelper;
import org.ovirt.engine.api.common.util.DetailHelper.Detail;
import org.ovirt.engine.api.common.util.LinkHelper;
import org.ovirt.engine.api.model.Action;
import org.ovirt.engine.api.model.CdRom;
import org.ovirt.engine.api.model.CdRoms;
import org.ovirt.engine.api.model.Disk;
import org.ovirt.engine.api.model.Disks;
import org.ovirt.engine.api.model.NIC;
import org.ovirt.engine.api.model.Nics;
import org.ovirt.engine.api.model.Statistic;
import org.ovirt.engine.api.model.Statistics;
import org.ovirt.engine.api.model.Ticket;
import org.ovirt.engine.api.model.VM;
import org.ovirt.engine.core.common.VdcObjectType;
import org.ovirt.engine.api.resource.ActionResource;
import org.ovirt.engine.api.resource.AssignedPermissionsResource;
import org.ovirt.engine.api.resource.AssignedTagsResource;
import org.ovirt.engine.api.resource.CreationResource;
import org.ovirt.engine.api.resource.DevicesResource;
import org.ovirt.engine.api.resource.SnapshotsResource;
import org.ovirt.engine.api.resource.StatisticsResource;
import org.ovirt.engine.api.resource.VmResource;
import org.ovirt.engine.api.restapi.resource.AbstractBackendResource.EntityIdResolver;
import org.ovirt.engine.api.restapi.resource.AbstractBackendResource.QueryIdResolver;
import org.ovirt.engine.core.common.action.ChangeVMClusterParameters;
import org.ovirt.engine.core.common.action.HibernateVmParameters;
import org.ovirt.engine.core.common.action.MigrateVmParameters;
import org.ovirt.engine.core.common.action.MigrateVmToServerParameters;
import org.ovirt.engine.core.common.action.MoveVmParameters;
import org.ovirt.engine.core.common.action.RemoveVmFromPoolParameters;
import org.ovirt.engine.core.common.action.RunVmOnceParams;
import org.ovirt.engine.core.common.action.SetVmTicketParameters;
import org.ovirt.engine.core.common.action.ShutdownVmParameters;
import org.ovirt.engine.core.common.action.StopVmParameters;
import org.ovirt.engine.core.common.action.StopVmTypeEnum;
import org.ovirt.engine.core.common.action.VdcActionParametersBase;
import org.ovirt.engine.core.common.action.VdcActionType;
import org.ovirt.engine.core.common.action.VmManagementParametersBase;
import org.ovirt.engine.core.common.action.VmOperationParameterBase;
import org.ovirt.engine.core.common.businessentities.VDS;
import org.ovirt.engine.core.common.businessentities.VDSGroup;
import org.ovirt.engine.core.common.businessentities.storage_domains;
import org.ovirt.engine.core.common.businessentities.VmStatic;
import org.ovirt.engine.core.common.interfaces.SearchType;
import org.ovirt.engine.core.common.queries.GetAllDisksByVmIdParameters;
import org.ovirt.engine.core.common.queries.GetPermissionsForObjectParameters;
import org.ovirt.engine.core.common.queries.GetVmByVmIdParameters;
import org.ovirt.engine.core.common.queries.VdcQueryType;
import org.ovirt.engine.core.compat.Guid;
import static org.ovirt.engine.core.utils.Ticketing.GenerateOTP;
import static org.ovirt.engine.api.restapi.resource.BackendVmsResource.SUB_COLLECTIONS;
public class BackendVmResource extends
AbstractBackendActionableResource<VM, org.ovirt.engine.core.common.businessentities.VM> implements
VmResource {
private static final long DEFAULT_TICKET_EXPIRY = 120 * 60; // 2 hours
private BackendVmsResource parent;
public BackendVmResource(String id, BackendVmsResource parent) {
super(id, VM.class, org.ovirt.engine.core.common.businessentities.VM.class, SUB_COLLECTIONS);
this.parent = parent;
}
@Override
public VM get() {
return performGet(VdcQueryType.GetVmByVmId, new GetVmByVmIdParameters(guid));
}
@Override
public VM update(VM incoming) {
if (incoming.isSetCluster() && (incoming.getCluster().isSetId() || incoming.getCluster().isSetName())) {
Guid clusterId = lookupClusterId(incoming);
if(!clusterId.toString().equals(get().getCluster().getId())){
performAction(VdcActionType.ChangeVMCluster,
new ChangeVMClusterParameters(clusterId, guid));
}
}
//if the user updated the host within placement-policy, but supplied host-name rather than the host-id (legal) -
//resolve the host's ID, because it will be needed down the line
if (incoming.isSetPlacementPolicy() && incoming.getPlacementPolicy().isSetHost()
&& incoming.getPlacementPolicy().getHost().isSetName() && !incoming.getPlacementPolicy().getHost().isSetId()) {
incoming.getPlacementPolicy().getHost().setId(getHostId(incoming.getPlacementPolicy().getHost().getName()));
}
return performUpdate(incoming,
new QueryIdResolver(VdcQueryType.GetVmByVmId, GetVmByVmIdParameters.class),
VdcActionType.UpdateVm,
new UpdateParametersProvider());
}
private String getHostId(String hostName) {
return getEntity(VDS.class, SearchType.VDS, "Hosts: name=" + hostName).getId().toString();
}
protected Guid lookupClusterId(VM vm) {
return vm.getCluster().isSetId() ? asGuid(vm.getCluster().getId())
:
getEntity(VDSGroup.class,
SearchType.Cluster,
"Cluster: name=" + vm.getCluster().getName()).getId();
}
@Override
public DevicesResource<CdRom, CdRoms> getCdRomsResource() {
return inject(new BackendCdRomsResource(guid,
VdcQueryType.GetVmByVmId,
new GetVmByVmIdParameters(guid)));
}
@Override
public DevicesResource<Disk, Disks> getDisksResource() {
return inject(new BackendDisksResource(guid,
VdcQueryType.GetAllDisksByVmId,
new GetAllDisksByVmIdParameters(guid)));
}
@Override
public DevicesResource<NIC, Nics> getNicsResource() {
return inject(new BackendVmNicsResource(guid));
}
@Override
public SnapshotsResource getSnapshotsResource() {
return inject(new BackendSnapshotsResource(guid));
}
@Override
public AssignedTagsResource getTagsResource() {
return inject(new BackendVmTagsResource(id));
}
@Override
public AssignedPermissionsResource getPermissionsResource() {
return inject(new BackendAssignedPermissionsResource(guid,
VdcQueryType.GetPermissionsForObject,
new GetPermissionsForObjectParameters(guid),
VM.class,
VdcObjectType.VM));
}
@Override
public CreationResource getCreationSubresource(String ids) {
return inject(new BackendCreationResource(ids));
}
@Override
public ActionResource getActionSubresource(String action, String ids) {
return inject(new BackendActionResource(action, ids));
}
@Override
public StatisticsResource getStatisticsResource() {
EntityIdResolver resolver = new QueryIdResolver(VdcQueryType.GetVmByVmId, GetVmByVmIdParameters.class);
VmStatisticalQuery query = new VmStatisticalQuery(resolver, newModel(id));
return inject(new BackendStatisticsResource<VM, org.ovirt.engine.core.common.businessentities.VM>(entityType, guid, query));
}
@Override
public Response migrate(Action action) {
boolean forceMigration = action.isSetForce() ? action.isForce() : false;
if (!action.isSetHost()) {
return doAction(VdcActionType.MigrateVm,
new MigrateVmParameters(forceMigration, guid),
action);
} else {
return doAction(VdcActionType.MigrateVmToServer,
new MigrateVmToServerParameters(forceMigration, guid, getHostId(action)),
action);
}
}
@Override
public Response shutdown(Action action) {
// REVISIT add waitBeforeShutdown Action paramater
// to api schema before next sub-milestone
return doAction(VdcActionType.ShutdownVm,
new ShutdownVmParameters(guid, true),
action);
}
@Override
public Response start(Action action) {
RunVmOnceParams params = new RunVmOnceParams(guid);
if (action.isSetPause() && action.isPause()) {
params.setRunAndPause(true);
}
if (action.isSetVm()) {
VM vm = action.getVm();
if (vm.isSetPlacementPolicy() && vm.getPlacementPolicy().isSetHost()) {
validateParameters(vm.getPlacementPolicy(), "host.id|name");
params.setDestinationVdsId(getHostId(vm.getPlacementPolicy().getHost()));
}
params = map(vm, params);
}
return doAction(VdcActionType.RunVmOnce, setReinitializeSysPrep(params), action);
}
private VdcActionParametersBase setReinitializeSysPrep(RunVmOnceParams params) {
//REVISE when BE supports default val. for RunVmOnceParams.privateReinitialize
org.ovirt.engine.core.common.businessentities.VM vm = getEntity(org.ovirt.engine.core.common.businessentities.VM.class,
VdcQueryType.GetVmByVmId,
new GetVmByVmIdParameters(guid),
"VM");
if(vm.getvm_os().isWindows() && vm.getIsFirstRun()) {
params.setReinitialize(true);
}
return params;
}
@Override
public Response stop(Action action) {
return doAction(VdcActionType.StopVm,
new StopVmParameters(guid, StopVmTypeEnum.NORMAL),
action);
}
@Override
public Response suspend(Action action) {
return doAction(VdcActionType.HibernateVm,
new HibernateVmParameters(guid),
action);
}
@Override
public Response detach(Action action) {
return doAction(VdcActionType.RemoveVmFromPool,
new RemoveVmFromPoolParameters(guid),
action);
}
@Override
public Response export(Action action) {
validateParameters(action, "storageDomain.id|name");
MoveVmParameters params = new MoveVmParameters(guid, getStorageDomainId(action));
if (action.isSetExclusive() && action.isExclusive()) {
params.setForceOverride(true);
}
if (action.isSetDiscardSnapshots() && action.isDiscardSnapshots()) {
params.setCopyCollapse(true);
}
return doAction(VdcActionType.ExportVm, params, action);
}
@Override
public Response move(Action action) {
validateParameters(action, "storageDomain.id|name");
return doAction(VdcActionType.MoveVm,
new MoveVmParameters(guid, getStorageDomainId(action)),
action);
}
protected Guid getStorageDomainId(Action action) {
if (action.getStorageDomain().isSetId()) {
return asGuid(action.getStorageDomain().getId());
} else {
return lookupStorageDomainIdByName(action.getStorageDomain().getName());
}
}
protected Guid lookupStorageDomainIdByName(String name) {
return getEntity(storage_domains.class, SearchType.StorageDomain, "Storage: name=" + name).getId();
}
@Override
public Response ticket(Action action) {
return doAction(VdcActionType.SetVmTicket,
new SetVmTicketParameters(guid,
getTicketValue(action),
getTicketExpiry(action)),
action);
}
protected String getTicketValue(Action action) {
if (!ensureTicket(action).isSetValue()) {
action.getTicket().setValue(GenerateOTP());
}
return action.getTicket().getValue();
}
protected int getTicketExpiry(Action action) {
if (!ensureTicket(action).isSetExpiry()) {
action.getTicket().setExpiry(DEFAULT_TICKET_EXPIRY);
}
return action.getTicket().getExpiry().intValue();
}
protected Ticket ensureTicket(Action action) {
if (!action.isSetTicket()) {
action.setTicket(new Ticket());
}
return action.getTicket();
}
protected RunVmOnceParams map(VM vm, RunVmOnceParams params) {
return getMapper(VM.class, RunVmOnceParams.class).map(vm, params);
}
@Override
protected VM populate(VM model, org.ovirt.engine.core.common.businessentities.VM entity) {
Set<Detail> details = DetailHelper.getDetails(getHttpHeaders());
parent.addInlineDetails(details, model);
addStatistics(model, entity, uriInfo, httpHeaders);
return model;
}
VM addStatistics(VM model, org.ovirt.engine.core.common.businessentities.VM entity, UriInfo ui, HttpHeaders httpHeaders) {
if (DetailHelper.include(httpHeaders, "statistics")) {
model.setStatistics(new Statistics());
VmStatisticalQuery query = new VmStatisticalQuery(newModel(model.getId()));
List<Statistic> statistics = query.getStatistics(entity);
for (Statistic statistic : statistics) {
LinkHelper.addLinks(ui, statistic, query.getParentType());
}
model.getStatistics().getStatistics().addAll(statistics);
}
return model;
}
protected class UpdateParametersProvider implements
ParametersProvider<VM, org.ovirt.engine.core.common.businessentities.VM> {
@Override
public VdcActionParametersBase getParameters(VM incoming,
org.ovirt.engine.core.common.businessentities.VM entity) {
VmStatic updated = getMapper(modelType, VmStatic.class).map(incoming,
entity.getStaticData());
return new VmManagementParametersBase(updated);
}
}
@Override
public Response cancelMigration(Action action) {
return doAction(VdcActionType.CancelMigrateVm,
new VmOperationParameterBase(guid), action);
}
}
| 41.611111 | 132 | 0.65247 |
55bf98466a927e1abde87197607516c995e9a6fc | 538 | package io.mykit.wechat.mp.beans.json.menu;
import io.mykit.wechat.mp.beans.json.base.BaseJsonBean;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.NoArgsConstructor;
/**
* @Author: liuyazhuang
* @Date: 2018/7/19 12:51
* @Description: 微信的菜单信息
*/
@NoArgsConstructor
@Data
@EqualsAndHashCode(callSuper = false)
@AllArgsConstructor
public class WxMenuBean extends BaseJsonBean {
private static final long serialVersionUID = -7579267534455759647L;
private String menuid;
}
| 22.416667 | 71 | 0.784387 |
865ac4c82e9bfff2eecc2c355e2bec8fb3085541 | 3,701 | /*
* (C) Copyright IBM Corp. 2012, 2016 All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.ibm.jaggr.core.impl;
import org.junit.Assert;
import org.junit.Test;
import java.net.URI;
import java.net.URISyntaxException;
public class ForcedErrorResponseTest {
@Test
public void testConstructor() throws Exception {
ForcedErrorResponse test = new ForcedErrorResponse("500");
Assert.assertEquals(500, test.peekStatus());
Assert.assertEquals(1, test.getCount());
Assert.assertEquals(0, test.getSkip());
Assert.assertEquals(null, test.getResponseBody());
test = new ForcedErrorResponse("500 3");
Assert.assertEquals(500, test.peekStatus());
Assert.assertEquals(3, test.getCount());
Assert.assertEquals(0, test.getSkip());
Assert.assertEquals(null, test.getResponseBody());
test = new ForcedErrorResponse("500 3 5");
Assert.assertEquals(500, test.peekStatus());
Assert.assertEquals(3, test.getCount());
Assert.assertEquals(5, test.getSkip());
Assert.assertEquals(null, test.getResponseBody());
test = new ForcedErrorResponse("500 3 5 file://c:/error.html");
Assert.assertEquals(500, test.peekStatus());
Assert.assertEquals(3, test.getCount());
Assert.assertEquals(5, test.getSkip());
Assert.assertEquals(new URI("file://c:/error.html"), test.getResponseBody());
test = new ForcedErrorResponse("500 file://c:/error.html");
Assert.assertEquals(500, test.peekStatus());
Assert.assertEquals(1, test.getCount());
Assert.assertEquals(0, test.getSkip());
Assert.assertEquals(new URI("file://c:/error.html"), test.getResponseBody());
test = new ForcedErrorResponse("500 2 file://c:/error.html");
Assert.assertEquals(500, test.peekStatus());
Assert.assertEquals(2, test.getCount());
Assert.assertEquals(0, test.getSkip());
Assert.assertEquals(new URI("file://c:/error.html"), test.getResponseBody());
}
@Test (expected=URISyntaxException.class)
public void testConstructorErrors1() throws Exception {
new ForcedErrorResponse("500 file:// error.html");
}
@Test (expected=NumberFormatException.class)
public void testConstructorErrors2() throws Exception {
new ForcedErrorResponse("foo");
}
@Test (expected=NumberFormatException.class)
public void testConstructorErrors3() throws Exception {
new ForcedErrorResponse("");
}
@Test
public void testGetStatus() throws Exception{
ForcedErrorResponse test = new ForcedErrorResponse("500");
Assert.assertEquals(500, test.getStatus());
Assert.assertEquals(-1, test.getStatus());
Assert.assertEquals(-1, test.getStatus());
test = new ForcedErrorResponse("500 2");
Assert.assertEquals(500, test.getStatus());
Assert.assertEquals(500, test.getStatus());
Assert.assertEquals(-1, test.getStatus());
Assert.assertEquals(-1, test.getStatus());
test = new ForcedErrorResponse("500 2 1");
Assert.assertEquals(0, test.getStatus());
Assert.assertEquals(500, test.getStatus());
Assert.assertEquals(500, test.getStatus());
Assert.assertEquals(-1, test.getStatus());
Assert.assertEquals(-1, test.getStatus());
}
}
| 35.247619 | 80 | 0.713321 |
9adc61d7cde7b6ac496c6233865fae8d404cdb47 | 736 | package systems.rcd.enonic.datatoolbox;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import com.google.common.io.ByteSource;
public class TemporaryFileByteSource
extends ByteSource
{
private File file;
public TemporaryFileByteSource( File file )
{
this.file = file;
}
@Override
public long size()
throws IOException
{
if ( !file.isFile() )
{
throw new FileNotFoundException( file.toString() );
}
return file.length();
}
@Override
public InputStream openStream()
throws IOException
{
return new TemporaryFileInputStream( file );
}
}
| 19.368421 | 63 | 0.644022 |
89756caec6ead2f1709956e50d7a41d9f73889aa | 413 | /**
* Contains the operand implementation of java-based usage of the Filter DSL used in limited cases where Java-side
* evaluation of these Filter DSL expressions is needed.
*
* Expression hierarchies are created by the {@link de.quinscape.automaton.runtime.filter.JavaFilterTransformer} but
* can also be used to write such expressions "by hand".
*
*/
package de.quinscape.automaton.runtime.filter.impl;
| 41.3 | 116 | 0.774818 |
f8b46c8ae810d02e8d3e0773d4693ffb61b98581 | 1,873 | package com.seanyj.mysamples.service;
import android.app.NotificationManager;
import android.app.Service;
import android.content.Intent;
import android.os.Binder;
import android.os.IBinder;
import androidx.annotation.Nullable;
public class MyService extends Service {
private NotificationManager mNotificationManager;
private boolean canRun = true;
private String retString = null;
private final IBinder mBinder = new MyBinder();
public class MyBinder extends Binder {
MyService getService() {
return MyService.this;
}
}
@Nullable
@Override
public IBinder onBind(Intent intent) {
mNotificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
displayNotificationMessage("service started");
return mBinder;
}
@Override
public void onCreate() {
// Thread thread = new Thread(null, new ServiceWorder(), "backgroundService");
// thread.start();
super.onCreate();
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
mNotificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
// displayNotificationMessage("service started", true);
return super.onStartCommand(intent, flags, startId);
}
@Override
public void onDestroy() {
stopForeground(true);
canRun = false;
super.onDestroy();
}
public String getImage(String url) {
return "19";
}
public String getRetString() {
return retString;
}
public boolean loginValidate(String userName, String password) throws Exception {
String uriStr = "http://www.renyugang.cn/blog/admin/admin_check.jsp";
boolean ret = false;
return true;
}
void displayNotificationMessage(String msg) {
}
}
| 27.144928 | 92 | 0.675921 |
64affdc7217c79e48e702805c218e1e83a76ec47 | 295 | package com.github.lit.support.data.domain;
/**
* @author liulu
* @version v1.0
* date 2018-12-21 18:58
*/
public interface Pageable {
int getPageNum();
int getPageSize();
int getOffset();
Sort getSort();
default boolean isCount() {
return true;
}
}
| 11.8 | 43 | 0.6 |
b5199bbdb5369879d47f1ed0bf3f2130fc329853 | 2,177 | /*
* Copyright 2018 - 2021 Paul Hagedorn (Panzer1119)
*
* 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 de.codemakers.swing.frame;
import de.codemakers.base.util.interfaces.Formattable;
import java.util.LinkedList;
import java.util.Queue;
public class JFrameTitle implements Formattable<JFrameTitleFormatter> {
private final boolean isIDE;
private String Name;
private String version;
private final Queue<Object> prefixes = new LinkedList<>();
private final Queue<Object> suffixes = new LinkedList<>();
public JFrameTitle(boolean isIDE, String Name, String version) {
this.isIDE = isIDE;
this.Name = Name;
this.version = version;
}
public boolean isIDE() {
return isIDE;
}
public String getName() {
return Name;
}
public JFrameTitle setName(String name) {
Name = name;
return this;
}
public String getVersion() {
return version;
}
public JFrameTitle setVersion(String version) {
this.version = version;
return this;
}
public Queue<Object> getPrefixes() {
return prefixes;
}
public Queue<Object> getSuffixes() {
return suffixes;
}
@Override
public String format(JFrameTitleFormatter format) throws Exception {
return format.format(this);
}
@Override
public String toString() {
return "JFrameTitle{" + "isIDE=" + isIDE + ", Name='" + Name + '\'' + ", version='" + version + '\'' + ", prefixes=" + prefixes + ", suffixes=" + suffixes + '}';
}
}
| 27.556962 | 169 | 0.632522 |
6b65250e6354d72e9d2e9ae62f52826521894626 | 3,965 | // Targeted by JavaCPP version 1.5.5-SNAPSHOT: DO NOT EDIT THIS FILE
package org.bytedeco.dnnl;
import java.nio.*;
import org.bytedeco.javacpp.*;
import org.bytedeco.javacpp.annotation.*;
import static org.bytedeco.javacpp.presets.javacpp.*;
import org.bytedeco.opencl.*;
import static org.bytedeco.opencl.global.OpenCL.*;
import static org.bytedeco.dnnl.global.dnnl.*;
/** \} dnnl_api_batch_normalization
<p>
* \addtogroup dnnl_api_layer_normalization
* \{
<p>
* A descriptor of a Layer Normalization operation. */
@Properties(inherit = org.bytedeco.dnnl.presets.dnnl.class)
public class dnnl_layer_normalization_desc_t extends Pointer {
static { Loader.load(); }
/** Default native constructor. */
public dnnl_layer_normalization_desc_t() { super((Pointer)null); allocate(); }
/** Native array allocator. Access with {@link Pointer#position(long)}. */
public dnnl_layer_normalization_desc_t(long size) { super((Pointer)null); allocateArray(size); }
/** Pointer cast constructor. Invokes {@link Pointer#Pointer(Pointer)}. */
public dnnl_layer_normalization_desc_t(Pointer p) { super(p); }
private native void allocate();
private native void allocateArray(long size);
@Override public dnnl_layer_normalization_desc_t position(long position) {
return (dnnl_layer_normalization_desc_t)super.position(position);
}
@Override public dnnl_layer_normalization_desc_t getPointer(long i) {
return new dnnl_layer_normalization_desc_t((Pointer)this).position(position + i);
}
/** The kind of primitive. Used for self-identifying the primitive
* descriptor. Must be #dnnl_layer_normalization. */
public native @Cast("dnnl_primitive_kind_t") int primitive_kind(); public native dnnl_layer_normalization_desc_t primitive_kind(int setter);
/** The kind of propagation. Possible values: #dnnl_forward_training,
* #dnnl_forward_inference, #dnnl_backward, and #dnnl_backward_data. */
public native @Cast("dnnl_prop_kind_t") int prop_kind(); public native dnnl_layer_normalization_desc_t prop_kind(int setter);
/** Source and destination memory descriptor. */
public native @ByRef dnnl_memory_desc_t data_desc(); public native dnnl_layer_normalization_desc_t data_desc(dnnl_memory_desc_t setter);
/** Source and destination gradient memory descriptor. */
///
public native @ByRef dnnl_memory_desc_t diff_data_desc(); public native dnnl_layer_normalization_desc_t diff_data_desc(dnnl_memory_desc_t setter);
/** Scale and shift data and gradient memory descriptors.
*
* Scaleshift memory descriptor uses 2D #dnnl_ab
* format[2, normalized_dim] where 1-st dimension contains gamma parameter,
* 2-nd dimension contains beta parameter. Normalized_dim is equal to the
* last logical dimension of the data tensor across which normalization is
* performed. */
public native @ByRef dnnl_memory_desc_t data_scaleshift_desc(); public native dnnl_layer_normalization_desc_t data_scaleshift_desc(dnnl_memory_desc_t setter);
///
public native @ByRef dnnl_memory_desc_t diff_data_scaleshift_desc(); public native dnnl_layer_normalization_desc_t diff_data_scaleshift_desc(dnnl_memory_desc_t setter);
/** Mean and variance data memory descriptors.
*
* Statistics (mean and variance) memory descriptor is the k-dimensional tensor
* where k is equal to data_tensor_ndims - 1 and may have any plain
* (stride[last_dim] == 1) user-provided format. */
public native @ByRef dnnl_memory_desc_t stat_desc(); public native dnnl_layer_normalization_desc_t stat_desc(dnnl_memory_desc_t setter);
/** Layer normalization epsilon parameter. */
public native float layer_norm_epsilon(); public native dnnl_layer_normalization_desc_t layer_norm_epsilon(float setter);
public native @Cast("unsigned") int flags(); public native dnnl_layer_normalization_desc_t flags(int setter);
}
| 54.315068 | 172 | 0.759899 |
585ab2a76e9d82e9b2e09a8939a3e461d013646e | 183 | package com.dodo.xinyue.core.net.callback;
/**
* IError
*
* @author DoDo
* @date 2017/8/31
*/
public interface IError {
void onError(int code, String msg);
}
| 13.071429 | 43 | 0.601093 |
63844074f5f31932af0eec93f700618461942cfc | 24,558 | /*
* Copyright 2008-2019 Hippo B.V. (http://www.onehippo.com)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.hippoecm.repository.query.lucene;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import javax.jcr.NamespaceException;
import javax.jcr.PropertyType;
import javax.jcr.RepositoryException;
import javax.jcr.nodetype.NoSuchNodeTypeException;
import javax.jcr.nodetype.NodeType;
import javax.jcr.nodetype.NodeTypeIterator;
import javax.jcr.nodetype.NodeTypeManager;
import org.apache.jackrabbit.core.id.NodeId;
import org.apache.jackrabbit.core.query.lucene.FieldNames;
import org.apache.jackrabbit.core.query.lucene.NamespaceMappings;
import org.apache.jackrabbit.spi.Name;
import org.apache.jackrabbit.spi.commons.conversion.IllegalNameException;
import org.apache.jackrabbit.spi.commons.name.NameConstants;
import org.apache.lucene.index.Term;
import org.apache.lucene.search.BooleanClause.Occur;
import org.apache.lucene.search.BooleanQuery;
import org.apache.lucene.search.MatchAllDocsQuery;
import org.apache.lucene.search.Query;
import org.apache.lucene.search.TermQuery;
import org.hippoecm.repository.jackrabbit.InternalHippoSession;
import org.hippoecm.repository.security.FacetAuthConstants;
import org.hippoecm.repository.security.HippoAccessManager;
import org.hippoecm.repository.security.domain.DomainRule;
import org.hippoecm.repository.security.domain.FacetAuthDomain;
import org.hippoecm.repository.security.domain.QFacetRule;
import org.onehippo.repository.security.SessionDelegateUser;
import org.onehippo.repository.security.StandardPermissionNames;
import org.onehippo.repository.security.User;
import org.onehippo.repository.util.JcrConstants;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import static org.hippoecm.repository.query.lucene.QueryHelper.createNoHitsQuery;
import static org.hippoecm.repository.query.lucene.QueryHelper.isMatchAllDocsQuery;
import static org.hippoecm.repository.query.lucene.QueryHelper.isNoHitsQuery;
import static org.hippoecm.repository.query.lucene.QueryHelper.negateQuery;
import static org.onehippo.repository.util.JcrConstants.JCR_MIXIN_TYPES;
import static org.onehippo.repository.util.JcrConstants.JCR_PRIMARY_TYPE;
public class AuthorizationQuery {
/**
* The logger instance for this class
*/
private static final Logger log = LoggerFactory.getLogger(AuthorizationQuery.class);
private static final String MESSAGE_ZEROMATCH_QUERY = "returning a match zero nodes query";
public static final String NODETYPE = "nodetype";
public static final String NODENAME = "nodename";
private static final Collection<String> UNINDEXED_TYPE_FACETS = new HashSet<>();
static {
UNINDEXED_TYPE_FACETS.add(JcrConstants.NT_SYSTEM);
UNINDEXED_TYPE_FACETS.add(JcrConstants.NT_VERSION_STORAGE);
UNINDEXED_TYPE_FACETS.add(JcrConstants.NT_VERSION_HISTORY);
UNINDEXED_TYPE_FACETS.add(JcrConstants.NT_VERSION);
UNINDEXED_TYPE_FACETS.add(JcrConstants.NT_FROZEN_NODE);
UNINDEXED_TYPE_FACETS.add(JcrConstants.NT_VERSIONED_CHILD);
UNINDEXED_TYPE_FACETS.add(JcrConstants.NT_VERSION_LABELS);
}
/**
* The lucene query
*/
private final BooleanQuery query;
public static AuthorizationQuery matchAll = new AuthorizationQuery(new MatchAllDocsQuery());
private AuthorizationQuery(final Query query) {
this.query = new BooleanQuery(true);
this.query.add(query, Occur.MUST);
}
public AuthorizationQuery(final Set<FacetAuthDomain> facetAuthDomains,
final NamespaceMappings nsMappings,
final ServicingIndexingConfiguration indexingConfig,
final NodeTypeManager ntMgr,
final InternalHippoSession internalSession) throws RepositoryException {
// set the max clauses for booleans higher than the default 1024.
BooleanQuery.setMaxClauseCount(Integer.MAX_VALUE);
if (internalSession.isSystemSession()) {
this.query = new BooleanQuery(true);
this.query.add(new MatchAllDocsQuery(), Occur.MUST);
} else {
User user = internalSession.getUser();
final Set<String> memberships;
final Set<String> userIds;
if (user != null) {
memberships = user.getMemberships();
if (user instanceof SessionDelegateUser) {
userIds = ((SessionDelegateUser)user).getIds();
} else {
userIds = new HashSet<>();
userIds.add(user.getId());
}
} else {
memberships = Collections.emptySet();
userIds = Collections.emptySet();
}
long start = System.currentTimeMillis();
this.query = initQuery(facetAuthDomains,
userIds,
memberships,
internalSession,
indexingConfig,
nsMappings,
ntMgr);
log.info("Creating authorization query for user '{}' took {} ms. Query: {}", internalSession.getUserID(), (System.currentTimeMillis() - start), query);
}
}
private BooleanQuery initQuery(final Set<FacetAuthDomain> facetAuthDomains,
final Set<String> userIds,
final Set<String> memberships,
final InternalHippoSession session,
final ServicingIndexingConfiguration indexingConfig,
final NamespaceMappings nsMappings,
final NodeTypeManager ntMgr) throws RepositoryException {
final HippoAccessManager hippoAccessManager = session.getAccessControlManager();
BooleanQuery authQuery = new BooleanQuery(true);
for (final FacetAuthDomain facetAuthDomain : facetAuthDomains) {
if (!facetAuthDomain.getResolvedPrivileges().contains(StandardPermissionNames.JCR_READ)) {
continue;
}
final Set<DomainRule> domainRules = facetAuthDomain.getRules();
for (final DomainRule domainRule : domainRules) {
BooleanQuery facetQuery = new BooleanQuery(true);
for (final QFacetRule facetRule : domainRule.getFacetRules()) {
Query q = getFacetRuleQuery(facetRule, userIds, memberships, facetAuthDomain.getRoles(), indexingConfig, nsMappings, session, ntMgr);
if (isNoHitsQuery(q)) {
log.debug("Found a no hits query in facetRule '{}'. Since facet rules are AND-ed with other " +
"facet rules, we can short circuit the domain rule '{}' as it does not match any node.",
facetRule, domainRule);
facetQuery = new BooleanQuery(true);
facetQuery.add(q, Occur.MUST);
break;
}
log.debug("Adding to FacetQuery: FacetRuleQuery = {}", q);
log.debug("FacetRuleQuery has {} clauses.", (q instanceof BooleanQuery) ? ((BooleanQuery)q).getClauses().length : 1);
facetQuery.add(q, Occur.MUST);
}
log.debug("Adding to Authorization query: FacetQuery = {}", facetQuery);
log.debug("FacetQuery has {} clauses.", facetQuery.getClauses().length);
if (facetQuery.getClauses().length == 1 && isMatchAllDocsQuery(facetQuery.getClauses()[0].getQuery())) {
log.info("found a MatchAllDocsQuery that will be OR-ed with other constraints for user '{}'. This means, the user can read " +
"everywhere. Short circuit the auth query and return MatchAllDocsQuery", session.getUserID());
// directly return the BooleanQuery that only contains the MatchAllDocsQuery : This is more efficient
return facetQuery;
} else if (facetQuery.getClauses().length == 1 && isNoHitsQuery(facetQuery.getClauses()[0].getQuery())) {
log.debug("No hits query does not add any new information for the authorization query so far " +
"since gets OR-ed. Hence can be skipped.");
} else {
authQuery.add(facetQuery, Occur.SHOULD);
}
}
}
if (authQuery.getClauses().length == 0) {
// read nowhere
authQuery.add(new MatchAllDocsQuery(), Occur.MUST_NOT);
}
// add the implicit reads query
final Set<NodeId> implicitReads = hippoAccessManager.getImplicitReads();
if (implicitReads.size() > 0) {
final BooleanQuery implicitReadsQuery = new BooleanQuery(true);
for (NodeId implicitRead : implicitReads) {
implicitReadsQuery.add(new TermQuery(new Term(FieldNames.UUID, implicitRead.toString())), Occur.SHOULD);
}
authQuery.add(implicitReadsQuery, Occur.SHOULD);
}
log.debug("Authorization query is : " + authQuery);
log.debug("Authorization query has {} clauses", authQuery.getClauses().length);
return authQuery;
}
private Query getFacetRuleQuery(final QFacetRule facetRule,
final Set<String> userIds,
final Set<String> memberships,
final Set<String> roles,
final ServicingIndexingConfiguration indexingConfig,
final NamespaceMappings nsMappings,
final InternalHippoSession session,
final NodeTypeManager ntMgr) {
String value = facetRule.getValue();
if (facetRule.isReferenceRule() && !facetRule.referenceExists()) {
if (facetRule.isEqual()) {
// non existing reference and equals says true, so no hits
return createNoHitsQuery();
} else {
// non existing reference and equals says false, so only hits
return new MatchAllDocsQuery();
}
}
switch (facetRule.getType()) {
case PropertyType.STRING:
Name facetName = facetRule.getFacetName();
try {
if (NameConstants.JCR_UUID.equals(facetName)) {
// note no check required for isFacetOptional since every node has a uuid
if (facetRule.isEqual()) {
// only allow one *single* node (not the descendants because those might not be readable)
final Query tq = new TermQuery(new Term(FieldNames.UUID, value));
return tq;
} else {
// disallow *all* descendant nodes below the node with UUID = value because our access mngr
// is hierarchical: you cannot read nodes below a node you are not allowed to read
final Query tq = new TermQuery(new Term(ServicingFieldNames.HIPPO_UUIDS, value));
return negateQuery(tq);
}
}
if (NameConstants.JCR_PATH.equals(facetName)) {
final Query tq = new TermQuery(new Term(ServicingFieldNames.HIPPO_UUIDS, value));
// note no check required for isFacetOptional since every node has a uuid
if (facetRule.isEqual()) {
return tq;
} else {
return negateQuery(tq);
}
} else if (indexingConfig.isFacet(facetName)) {
String fieldName = ServicingNameFormat.getInternalFacetName(facetName, nsMappings);
String internalNameTerm = nsMappings.translateName(facetName);
Query tq;
if (FacetAuthConstants.WILDCARD.equals(value)) {
tq = new TermQuery(new Term(ServicingFieldNames.FACET_PROPERTIES_SET, internalNameTerm));
} else if (FacetAuthConstants.EXPANDER_USER.equals(value)) {
tq = expandUser(fieldName, userIds);
} else if (FacetAuthConstants.EXPANDER_ROLE.equals(value)) {
tq = expandRole(fieldName, roles);
} else if (FacetAuthConstants.EXPANDER_GROUP.equals(value)) {
tq = expandGroup(fieldName, memberships);
} else {
tq = new TermQuery(new Term(fieldName, value));
}
if (facetRule.isFacetOptional()) {
BooleanQuery bq = new BooleanQuery(true);
// all the docs that do *not* have the property:
Query docsThatMissPropertyQuery = negateQuery(
new TermQuery(new Term(ServicingFieldNames.FACET_PROPERTIES_SET, internalNameTerm)));
bq.add(docsThatMissPropertyQuery, Occur.SHOULD);
// and OR that one with the equals
if (facetRule.isEqual()) {
bq.add(tq, Occur.SHOULD);
return bq;
} else {
Query not = negateQuery(tq);
bq.add(not, Occur.SHOULD);
return bq;
}
} else {
// Property MUST exist and it MUST (or MUST NOT) equal the value,
// depending on QFacetRule#isEqual.
if (facetRule.isEqual()) {
return tq;
} else {
return negateQuery(tq);
}
}
} else {
log.warn("Property " + facetName.getNamespaceURI() + ":" + facetName.getLocalName() + " not allowed for faceted search. " +
"Add the property to the indexing configuration to be defined as FACET");
}
} catch (IllegalNameException e) {
log.error(e.toString());
}
break;
case PropertyType.NAME:
String nodeNameString = facetRule.getFacet();
if (UNINDEXED_TYPE_FACETS.contains(value) &&
(NODETYPE.equalsIgnoreCase(nodeNameString) ||
JCR_PRIMARY_TYPE.equals(nodeNameString) ||
JCR_MIXIN_TYPES.equals(nodeNameString))) {
if (facetRule.isEqual()) {
// every document that is indexed is *not* one of the UNINDEXED_TYPE_FACETS
// hence non is equal
return createNoHitsQuery();
} else {
// every document that is indexed is *not* one of the UNINDEXED_TYPE_FACETS
// hence all are unequal
return new MatchAllDocsQuery();
}
}
if (FacetAuthConstants.WILDCARD.equals(value)) {
if (facetRule.isEqual()) {
return new MatchAllDocsQuery();
} else {
return createNoHitsQuery();
}
} else if (NODETYPE.equalsIgnoreCase(nodeNameString)) {
return getNodeTypeDescendantQuery(facetRule, ntMgr, session, nsMappings);
} else if (NODENAME.equalsIgnoreCase(nodeNameString)) {
return getNodeNameQuery(facetRule, userIds, roles, memberships, nsMappings);
} else {
try {
if (JCR_PRIMARY_TYPE.equals(nodeNameString)) {
return getNodeTypeQuery(ServicingFieldNames.HIPPO_PRIMARYTYPE, facetRule, session, nsMappings);
} else if (JCR_MIXIN_TYPES.equals(nodeNameString)) {
return getNodeTypeQuery(ServicingFieldNames.HIPPO_MIXINTYPE, facetRule, session, nsMappings);
} else {
log.error("Ignoring facetrule with facet '" + nodeNameString + "'. hippo:facet must be either 'nodetype', 'jcr:primaryType' " +
"or 'jcr:mixinTypes' when hipposys:type = Name.");
}
} catch (IllegalNameException ine) {
log.warn("Illegal name in facet rule", ine);
} catch (NamespaceException ne) {
log.warn("Namespace exception in facet rule", ne);
}
}
break;
}
log.error("Incorrect FacetRule: returning a match zero nodes query");
return createNoHitsQuery();
}
private Query getNodeTypeDescendantQuery(final QFacetRule facetRule,
final NodeTypeManager ntMgr,
final InternalHippoSession session,
final NamespaceMappings nsMappings) {
List<Term> terms = new ArrayList<Term>();
try {
NodeType base = ntMgr.getNodeType(facetRule.getValue());
terms.add(getTerm(base, session, nsMappings));
// now search for all node types that are derived from base
NodeTypeIterator allTypes = ntMgr.getAllNodeTypes();
while (allTypes.hasNext()) {
NodeType nt = allTypes.nextNodeType();
NodeType[] superTypes = nt.getSupertypes();
if (Arrays.asList(superTypes).contains(base)) {
terms.add(getTerm(nt, session, nsMappings));
}
}
} catch (NoSuchNodeTypeException e) {
log.error("invalid nodetype" + e.getMessage() + "\n" + MESSAGE_ZEROMATCH_QUERY);
} catch (RepositoryException e) {
log.error("invalid nodetype" + e.getMessage() + "\n" + MESSAGE_ZEROMATCH_QUERY);
}
if (terms.size() == 0) {
// exception occured
if (facetRule.isEqual()) {
return createNoHitsQuery();
} else {
return new MatchAllDocsQuery();
}
}
Query query;
if (terms.size() == 1) {
query = new TermQuery(terms.get(0));
} else {
BooleanQuery b = new BooleanQuery(true);
for (final Term term : terms) {
b.add(new TermQuery(term), Occur.SHOULD);
}
query = b;
}
if (facetRule.isEqual()) {
return query;
} else {
return negateQuery(query);
}
}
private Term getTerm(NodeType nt, InternalHippoSession session, NamespaceMappings nsMappings) throws IllegalNameException, NamespaceException {
String ntName = getNtName(nt.getName(), session, nsMappings);
if (nt.isMixin()) {
return new Term(ServicingFieldNames.HIPPO_MIXINTYPE, ntName);
} else {
return new Term(ServicingFieldNames.HIPPO_PRIMARYTYPE, ntName);
}
}
private Query getNodeTypeQuery(String luceneFieldName, QFacetRule facetRule, InternalHippoSession session, NamespaceMappings nsMappings) throws IllegalNameException, NamespaceException {
String termValue = facetRule.getValue();
String name = getNtName(termValue, session, nsMappings);
Query nodetypeQuery = new TermQuery(new Term(luceneFieldName, name));
if (facetRule.isEqual()) {
return nodetypeQuery;
} else {
return negateQuery(nodetypeQuery);
}
}
private String getNtName(String value, InternalHippoSession session, NamespaceMappings nsMappings) throws IllegalNameException, NamespaceException {
Name n = session.getQName(value);
return nsMappings.translateName(n);
}
public BooleanQuery getQuery() {
return query;
}
private Query getNodeNameQuery(QFacetRule facetRule, Set<String> userIds, Set<String> roles, Set<String> memberShips, final NamespaceMappings nsMappings) {
try {
String fieldName = ServicingNameFormat.getInternalFacetName(NameConstants.JCR_NAME, nsMappings);
String value = facetRule.getValue();
Query nodeNameQuery;
if (FacetAuthConstants.WILDCARD.equals(value)) {
if (facetRule.isEqual()) {
return new MatchAllDocsQuery();
} else {
return createNoHitsQuery();
}
} else if (FacetAuthConstants.EXPANDER_USER.equals(value)) {
nodeNameQuery = expandUser(fieldName, userIds);
} else if (FacetAuthConstants.EXPANDER_ROLE.equals(value)) {
nodeNameQuery = expandRole(fieldName, userIds);
} else if (FacetAuthConstants.EXPANDER_GROUP.equals(value)) {
nodeNameQuery = expandGroup(fieldName, userIds);
} else {
nodeNameQuery = new TermQuery(new Term(fieldName, value));
}
if (facetRule.isEqual()) {
return nodeNameQuery;
} else {
return negateQuery(nodeNameQuery);
}
} catch (IllegalNameException e) {
log.error("Failed to create node name query: " + e);
return createNoHitsQuery();
}
}
private Query expandUser(final String field, final Set<String> userIds) {
if (userIds.isEmpty()) {
return createNoHitsQuery();
}
// optimize the single-user principal case
if (userIds.size() == 1) {
String userId = userIds.iterator().next();
return new TermQuery(new Term(field, userId));
} else {
BooleanQuery b = new BooleanQuery(true);
for (String userId : userIds) {
Term term = new Term(field, userId);
b.add(new TermQuery(term), Occur.SHOULD);
}
return b;
}
}
private Query expandGroup(final String field, final Set<String> memberships) {
// boolean OR query of groups
if (memberships.isEmpty()) {
return createNoHitsQuery();
}
BooleanQuery b = new BooleanQuery(true);
for (String groupName : memberships) {
Term term = new Term(field, groupName);
b.add(new TermQuery(term), Occur.SHOULD);
}
return b;
}
private Query expandRole(final String field, final Set<String> roles) {
// boolean Or query of roles
if (roles.size() == 0) {
return createNoHitsQuery();
}
BooleanQuery b = new BooleanQuery(true);
for (String role : roles) {
Term term = new Term(field, role);
b.add(new TermQuery(term), Occur.SHOULD);
}
return b;
}
@Override
public String toString() {
return "authorisation query: " + query.toString();
}
}
| 48.058708 | 190 | 0.57297 |
ac5c6111f822d96444622bd02411412a6013c833 | 5,477 | package ru.sdroman.carstore.models;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.Table;
/**
* @author sdroman
* @since 06.2018
*/
@Entity
@Table(name = "car")
public class Car {
/**
* Id.
*/
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "id", nullable = false, updatable = false)
private int id;
/**
* Name.
*/
@Column(name = "year")
private String year;
/**
* Body.
*/
@ManyToOne
@JoinColumn(name = "id_body")
private Body body;
/**
* Model.
*/
@ManyToOne
@JoinColumn(name = "id_model")
private Model model;
/**
* Engine.
*/
@ManyToOne
@JoinColumn(name = "id_engine")
private Engine engine;
/**
* DriveType.
*/
@ManyToOne
@JoinColumn(name = "id_drivetype")
private DriveType driveType;
/**
* Transmission.
*/
@ManyToOne
@JoinColumn(name = "id_transmission")
private Transmission transmission;
/**
* Constructor.
*/
public Car() {
}
/**
* Constructs the new Car object.
*
* @param id int
*/
public Car(int id) {
this.id = id;
}
/**
* Returns id.
*
* @return int id
*/
public int getId() {
return id;
}
/**
* Sets id.
*
* @param id int
*/
public void setId(int id) {
this.id = id;
}
/**
* Returns year.
*
* @return String
*/
public String getYear() {
return year;
}
/**
* Sets year.
*
* @param year String
*/
public void setYear(String year) {
this.year = year;
}
/**
* Returns body.
*
* @return Body
*/
public Body getBody() {
return body;
}
/**
* Sets body.
*
* @param body Body
*/
public void setBody(Body body) {
this.body = body;
}
/**
* Returns model.
*
* @return Model model
*/
public Model getModel() {
return model;
}
/**
* Sets model.
*
* @param model Model
*/
public void setModel(Model model) {
this.model = model;
}
/**
* Returns engine.
*
* @return Engine
*/
public Engine getEngine() {
return engine;
}
/**
* Sets engine.
*
* @param engine Engine
*/
public void setEngine(Engine engine) {
this.engine = engine;
}
/**
* Returns drive type.
*
* @return DriveType
*/
public DriveType getDriveType() {
return driveType;
}
/**
* Sets drivetype.
*
* @param driveType DriveType
*/
public void setDriveType(DriveType driveType) {
this.driveType = driveType;
}
/**
* Returns transaction.
*
* @return Transmission
*/
public Transmission getTransmission() {
return transmission;
}
/**
* Sets transaction.
*
* @param transmission Transmission
*/
public void setTransmission(Transmission transmission) {
this.transmission = transmission;
}
/**
* Equals.
*
* @param o Object
* @return true if equal
*/
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
Car car = (Car) o;
if (id != car.id) {
return false;
}
if (year != null ? !year.equals(car.year) : car.year != null) {
return false;
}
if (body != null ? !body.equals(car.body) : car.body != null) {
return false;
}
if (model != null ? !model.equals(car.model) : car.model != null) {
return false;
}
if (engine != null ? !engine.equals(car.engine) : car.engine != null) {
return false;
}
if (driveType != null ? !driveType.equals(car.driveType) : car.driveType != null) {
return false;
}
return transmission != null ? transmission.equals(car.transmission) : car.transmission == null;
}
/**
* HashCode.
*
* @return int
*/
@Override
public int hashCode() {
int result = id;
result = 31 * result + (year != null ? year.hashCode() : 0);
result = 31 * result + (body != null ? body.hashCode() : 0);
result = 31 * result + (model != null ? model.hashCode() : 0);
result = 31 * result + (engine != null ? engine.hashCode() : 0);
result = 31 * result + (driveType != null ? driveType.hashCode() : 0);
result = 31 * result + (transmission != null ? transmission.hashCode() : 0);
return result;
}
@Override
public String toString() {
return "Car{"
+ "id=" + id
+ ", year='" + year + '\''
+ ", body=" + body
+ ", model=" + model
+ ", engine=" + engine
+ ", driveType=" + driveType
+ ", transmission=" + transmission
+ '}';
}
}
| 19.701439 | 103 | 0.49644 |
52d49a0525f986108e76a8ced6a6dd0def4aa231 | 2,855 | /**********************************************************\
| |
| hprose |
| |
| Official WebSite: http://www.hprose.com/ |
| http://www.hprose.org/ |
| |
\**********************************************************/
/**********************************************************\
* *
* LinkedCaseInsensitiveMap.java *
* *
* LinkedCaseInsensitiveMap class for Java. *
* *
* LastModified: Aug 4, 2016 *
* Author: Ma Bingyao <[email protected]> *
* *
\**********************************************************/
package net.hasor.libs.com.hprose.utils;
import java.util.HashMap;
import java.util.LinkedHashMap;
public class LinkedCaseInsensitiveMap<K, V> extends LinkedHashMap<K, V> {
private final HashMap<String, K> caseInsensitiveKeys;
public LinkedCaseInsensitiveMap(int initialCapacity, float loadFactor) {
super(initialCapacity, loadFactor);
this.caseInsensitiveKeys = new HashMap<String, K>();
}
public LinkedCaseInsensitiveMap(int initialCapacity) {
super(initialCapacity);
this.caseInsensitiveKeys = new HashMap<String, K>();
}
public LinkedCaseInsensitiveMap() {
super();
this.caseInsensitiveKeys = new HashMap<String, K>();
}
public LinkedCaseInsensitiveMap(int initialCapacity, float loadFactor, boolean accessOrder) {
super(initialCapacity, loadFactor, accessOrder);
this.caseInsensitiveKeys = new HashMap<String, K>();
}
private String convertKey(Object key) {
return ((key instanceof char[]) ? new String((char[]) key) : key.toString()).toLowerCase();
}
@Override
public V put(K key, V value) {
this.caseInsensitiveKeys.put(convertKey(key), key);
return super.put(key, value);
}
@Override
public boolean containsKey(Object key) {
return (key instanceof String && this.caseInsensitiveKeys.containsKey(convertKey(key)));
}
@Override
public V get(Object key) {
return super.get(this.caseInsensitiveKeys.get(convertKey(key)));
}
@Override
public V remove(Object key) {
return super.remove(this.caseInsensitiveKeys.remove(convertKey(key)));
}
@Override
public void clear() {
this.caseInsensitiveKeys.clear();
super.clear();
}
} | 43.923077 | 99 | 0.475306 |
b5973e6701f1bb1f5e57981d9241d35dc1500908 | 9,532 | package org.foo.app;
import org.apache.felix.scr.annotations.Activate;
import org.apache.felix.scr.annotations.Component;
import org.apache.felix.scr.annotations.Deactivate;
import org.apache.felix.scr.annotations.Service;
import org.apache.felix.scr.annotations.Reference;
import org.apache.felix.scr.annotations.ReferenceCardinality;
import org.apache.karaf.shell.commands.Command;
import org.apache.karaf.shell.commands.Argument;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.onlab.packet.Ethernet;
import org.onlab.packet.IPv4;
import org.onlab.packet.MacAddress;
import org.onosproject.cli.AbstractShellCommand;
import org.onosproject.core.ApplicationId;
import org.onosproject.core.CoreService;
import org.onosproject.net.packet.PacketContext;
import org.onosproject.net.packet.PacketPriority;
import org.onosproject.net.packet.PacketProcessor;
import org.onosproject.net.packet.PacketService;
import org.onosproject.net.meter.*;
import org.onosproject.net.ElementId;
import org.onosproject.net.DeviceId;
import org.onosproject.net.flow.FlowRule;
import org.onosproject.net.flow.FlowRuleEvent;
import org.onosproject.net.flow.FlowRuleListener;
import org.onosproject.net.flow.FlowRuleService;
import org.onosproject.net.flow.DefaultFlowRule;
import org.onosproject.net.flow.DefaultTrafficSelector;
import org.onosproject.net.flow.DefaultTrafficTreatment;
import org.onosproject.net.flow.TrafficSelector;
import org.onosproject.net.flow.TrafficTreatment;
import org.onosproject.net.flow.criteria.Criterion;
import org.onosproject.net.flow.*;
import org.onosproject.net.flow.criteria.Criterion.Type;
import org.onosproject.net.flow.criteria.EthCriterion;
import org.onosproject.net.flowobjective.DefaultForwardingObjective;
import org.onosproject.net.flowobjective.FlowObjectiveService;
import org.onosproject.net.flowobjective.ForwardingObjective;
import static org.onosproject.net.flow.FlowRuleEvent.Type.RULE_REMOVED;
import static org.onosproject.net.flow.criteria.Criterion.Type.ETH_SRC;
import static org.onosproject.net.flow.criteria.Criterion.Type.VLAN_VID;
import static org.onosproject.net.flow.FlowRuleEvent.Type.*;
import java.util.Objects;
import java.util.Optional;
import java.util.Timer;
import java.util.TimerTask;
import java.util.concurrent.TimeUnit;
import java.util.*;
import java.io.*;
import com.google.common.collect.HashMultimap;
import org.foo.app.QosApliedMeters;
/**
* CLI para interactuar con qosVPLS.
*/
@Command(scope = "onos", name = "qosVpls", description = "Commands to add qos to Vpls")
public class QosVplsCommand extends AbstractShellCommand {
protected CoreService coreService;
protected FlowRuleService flowRuleService;
@Argument(index = 0, name = "command", description = "Command name (add-qos|"
+ "delete-qos|show|clean)", required = true, multiValued = false)
String command = null;
@Argument(index = 1, name = "deviceId", description = "The id of the device where apply the Meter", required = false, multiValued = false)
String switchName = null;
@Argument(index = 2, name = "idMeter", description = "The id of the Meter", required = false, multiValued = false)
String idMeter = null;
@Argument(index = 3, name = "portMeter", description = "The port where applies the Meter", required = false, multiValued = false)
String portMeter = null;
@Argument(index = 4, name = "vlanMeter", description = "The vlan who applies the Meter", required = false, multiValued = false)
String vlanMeter = null;
@Override
protected void execute() {
QosVplsCommandEnum enumCommand = QosVplsCommandEnum
.enumFromString(command);
QosApliedMeters qosApliedMeters = QosApliedMeters.getInstance();
if (enumCommand != null) {
switch (enumCommand) {
case ADD_QOS:
add_qos(switchName, idMeter, portMeter, vlanMeter);
break;
case DELETE_QOS:
delete_qos(switchName, idMeter, portMeter, vlanMeter);
break;
case SHOW:
qosApliedMeters.show();
break;
case CLEAN:
clear();
print("Qos cleaned");
break;
default:
print("Command not found");
}
} else {
print("Command not found");
}
}
/**
* Anade mecanismo de qos .
*
* @param switchName el nombre del switch donde aplicar mecanismo QoS
* @param idMeter el identificador del meter que quiere aplicar mecanismo QoS
* @param portMeter el puerto donde se quiere aplicar mecanismo QoS
* @param vlanMeter etiqueta vlan que sobre la que aplicar mecanismo QoS
*/
private void add_qos(String switchName, String idMeter, String portMeter,
String vlanMeter) {
QosApliedMeters qosApliedMeters = QosApliedMeters.getInstance();
QosOldFlows qosOldFlows = QosOldFlows.getInstance();
if (coreService == null) {
coreService = get(CoreService.class);
}
if (flowRuleService == null) {
flowRuleService = get(FlowRuleService.class);
}
if (switchName == null) {
print("Introduce deviceId");
} else {
if (idMeter == null) {
print("Introduce port");
} else {
if (portMeter == null) {
print("Introduce meter");
} else {
if (vlanMeter == null) {
vlanMeter = "-1";
}
DeviceId deviceIdentificador = null;
deviceIdentificador = deviceIdentificador
.deviceId(switchName);
MeterId meterId = null;
meterId = MeterId.meterId(Long.parseLong(idMeter));
ApplicationId appId = coreService.getAppId("org.foo.app");
ApplicationId appIntentId = coreService
.getAppId("org.onosproject.net.intent");
QosMeter meterToAdd = new QosMeter(idMeter, portMeter,
vlanMeter);
/* compureba primero si existe ese meter, sino existe lo
*mete y añade flows
*/
if (qosApliedMeters.addElement(switchName, idMeter,
portMeter, vlanMeter) == true) {
for (FlowEntry flowEntry : flowRuleService
.getFlowEntries(deviceIdentificador)) {
Criterion criterioPort = flowEntry.selector()
.getCriterion(Criterion.Type.IN_PORT);
Criterion criterioVlan = flowEntry.selector()
.getCriterion(Criterion.Type.VLAN_VID);
String port_in = " ";
String vlan = "-1";
if (criterioPort != null) {
port_in = criterioPort.toString().split(":")[1];
}
if (criterioVlan != null) {
vlan = criterioVlan.toString().split(":")[1];
}
if (flowEntry.appId() == appIntentId.id()
&& port_in.equals(portMeter)
&& vlan.equals(vlanMeter)) {
TrafficTreatment newTreatment = DefaultTrafficTreatment
.builder()
.addTreatment(flowEntry.treatment())
.meter(meterId).build();
FlowRule newFlow = DefaultFlowRule
.builder()
.withSelector(flowEntry.selector())
.withTreatment(newTreatment)
.forDevice(flowEntry.deviceId())
.makePermanent()
.fromApp(appId)
.withPriority(flowEntry.priority() + 50)
.build();
flowRuleService.applyFlowRules(newFlow);
qosOldFlows.addFlow(newFlow, "" + switchName
+ "" + meterToAdd.toString());
}
}
}
}
}
}
}
/**
* Elimina mecanismo de qos .
*
* @param switchName el nombre del switch donde eliminar mecanismo QoS
* @param idMeter el identificador del meter que quiere eliminar mecanismo QoS
* @param portMeter el puerto donde se quiere eliminar mecanismo QoS
* @param vlanMeter etiqueta vlan que sobre la que eliminar mecanismo QoS
*/
private void delete_qos(String switchName, String idMeter,
String portMeter, String vlanMeter) {
QosApliedMeters qosApliedMeters = QosApliedMeters.getInstance();
QosOldFlows qosOldFlows = QosOldFlows.getInstance();
if (coreService == null) {
coreService = get(CoreService.class);
}
if (flowRuleService == null) {
flowRuleService = get(FlowRuleService.class);
}
if (switchName == null) {
print("Introduce deviceId");
} else {
if (idMeter == null) {
print("Introduce port");
} else {
if (portMeter == null) {
print("Introduce meter");
} else {
if (vlanMeter == null) {
vlanMeter = "-1";
}
QosMeter meterToDelete = new QosMeter(idMeter, portMeter,
vlanMeter);
ArrayList<FlowRule> flowRulesToDelete = qosOldFlows.getMapaOldFlows().get("" + switchName + ""
+ meterToDelete.toString());
/* Borro la entrada del meter borrar ningun flow pq si se
*borra uno y llega la señal de REMOVED a un meter
*guardado lo va a volver a crear al verlo en el mapa
*/
qosApliedMeters.delElement(switchName, idMeter, portMeter,
vlanMeter);
if (flowRulesToDelete != null) {
for (FlowRule flowRuleToDelete : flowRulesToDelete) {
flowRuleService.removeFlowRules(flowRuleToDelete);
}
// borro todos los oldflows
qosOldFlows.getMapaOldFlows().remove("" + switchName + ""
+ meterToDelete.toString());
}
// Borro todpos los flows del mapa de flows.
}
}
}
}
/**
* Elimina todos los mecanismos de QoS.
*/
private void clear() {
QosApliedMeters qosApliedMeters = QosApliedMeters.getInstance();
QosOldFlows qosOldFlows = QosOldFlows.getInstance();
if (coreService == null) {
coreService = get(CoreService.class);
}
if (flowRuleService == null) {
flowRuleService = get(FlowRuleService.class);
}
qosOldFlows.clear();
qosApliedMeters.clear();
ApplicationId appId = coreService.getAppId("org.foo.app");
flowRuleService.removeFlowRulesById(appId);
}
}
| 35.303704 | 139 | 0.706882 |
c7423914f73f40ce2cdd677f894c6c4d333dee6a | 613 | package business;
public class Seat {
private int row;
private int col;
private int price;
private AirPlane ap;
public Seat(){
ap = new AirPlane();
}
public int getRow() {
return row;
}
public void setRow(int row) {
this.row = row;
}
public int getCol() {
return col;
}
public void setCol(int col) {
this.col = col;
}
public int getPrice() {
return price;
}
public void setPrice(int price) {
this.price = price;
}
public AirPlane getAp() {
return ap;
}
public void setAp(AirPlane ap) {
this.ap = ap;
}
}
| 15.717949 | 35 | 0.572594 |
83e4586c4308f0ae1c133c27600369691ec2f73a | 298 | package org.spring.springboot.dao;
import org.spring.springboot.domain.City;
import org.springframework.data.mongodb.repository.ReactiveMongoRepository;
import org.springframework.stereotype.Repository;
@Repository
public interface CityRepository extends ReactiveMongoRepository<City, Long> {
}
| 27.090909 | 77 | 0.848993 |
a199790e0685aae8d2dd466825b6924661d783cc | 3,512 | package com.togo.c_sms.Adapters;
import android.app.Activity;
import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import com.blogspot.atifsoftwares.animatoolib.Animatoo;
import com.togo.c_sms.Activity.GroupCreateActivity;
import com.togo.c_sms.Activity.GroupDetailActivity;
import com.togo.c_sms.Activity.MessageWriteActivity;
import com.togo.c_sms.Helper.DialogHelper;
import com.togo.c_sms.Models.Group;
import com.togo.c_sms.R;
import java.util.List;
public class GroupListAdapter extends RecyclerView.Adapter<GroupListAdapter.MyViewHolder> {
private Context mContext;
private Activity activity;
List<Group> mData;
public GroupListAdapter(Context mContext, List<Group> mData,Activity activity) {
this.mContext = mContext;
this.mData = mData;
this.activity = activity;
}
@NonNull
@Override
public MyViewHolder onCreateViewHolder(@NonNull final ViewGroup viewGroup, int i) {
View view;
final LayoutInflater inflater = LayoutInflater.from(mContext);
view = inflater.inflate(R.layout.item_group_list,viewGroup, false);
final MyViewHolder viewHolder = new MyViewHolder(view);
viewHolder.grpitem.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(mContext, GroupDetailActivity.class);
intent.putExtra("gname", mData.get(viewHolder.getAdapterPosition()).getName());
intent.putExtra("user_hash", mData.get(viewHolder.getAdapterPosition()).getHash());
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
mContext.startActivity(intent);
Animatoo.animateSlideLeft(activity);
}
});
viewHolder.grpitem.setOnLongClickListener(new View.OnLongClickListener() {
@Override
public boolean onLongClick(View view) {
DialogHelper dialogHelper = new DialogHelper(activity, mContext);
dialogHelper.groupOption(mData.get(viewHolder.getAdapterPosition()).getHash(),mData.get(viewHolder.getAdapterPosition()).getName(),mData.get(viewHolder.getAdapterPosition()).getUid());
return false;
}
});
return viewHolder;
}
@Override
public void onBindViewHolder(@NonNull MyViewHolder myViewHolder, int i) {
myViewHolder.gname.setText(mData.get(i).getName());
myViewHolder.countperson.setText(mData.get(i).getNumbers());
}
@Override
public int getItemCount() {
return mData.size();
}
public static class MyViewHolder extends RecyclerView.ViewHolder {
private TextView gname, countperson;
private RelativeLayout grpitem;
public MyViewHolder(@NonNull View itemView) {
super(itemView);
gname = itemView.findViewById(R.id.gname);
grpitem = itemView.findViewById(R.id.gritem);
countperson = itemView.findViewById(R.id.countperson);
}
}
}
| 37.763441 | 205 | 0.677107 |
f4ae37fcc9a030e99197c11837413a5ee2e65534 | 2,801 | /*
* MIT License
*
* Copyright (c) 2019 blombler008
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package com.github.blombler008.teamspeak3bot.example.v2;
import com.github.blombler008.teamspeak3bot.commands.*;
public class ExampleCommand extends CommandExecutor {
/**
* NOTE: You cannot change the name of the method ...
* <p>
* If the command (in this case "example") is send to the bot you this method runs
* the parameters you get are:
* - source: from where this command is executed
* - id: the id of the client send the command to the bot(NOTE: Console have the id -1)
* - commandLabel: the name of the name (in this case "example")
* - args: the arguments send with the command
* (eg. me > bot: example hi there)
* - source = client
* - id = my client id from the teamspeak
* - commandLabel = "example"
* - args = {"hi", "there"}
*/
@Override
public void run(CommandSender source, Command cmd, String commandLabel, String[] args) {
int clId = cmd.getInvokerId();
int chId = cmd.getChannelId();
if (source instanceof ConsoleCommandSender)
source.sendMessage(chId, clId, "This happens when a Console messages the bot with the command!");
if (source instanceof ClientCommandSender)
source.sendMessage(chId, clId, "This happens when a client entered a command the bot!");
if (source instanceof ServerCommandSender)
source.sendMessage(chId, clId, "This happens when a client entered a command in the public server chat!");
if (source instanceof ChannelCommandSender)
source.sendMessage(chId, clId, "This happens when a client entered a command in the channel chat!");
}
}
| 43.092308 | 118 | 0.702606 |
8d3d35b3530ae4f7569dfa0b247184e0274ca7aa | 1,233 | package com.smartcodeltd.jenkinsci.plugins.build_monitor.tasks.configuration;
import net.serenitybdd.screenplay.Actor;
import net.serenitybdd.screenplay.Task;
import net.serenitybdd.screenplay.actions.SelectFromOptions;
import net.serenitybdd.screenplay.jenkins.user_interface.ViewConfigurationPage;
import net.serenitybdd.screenplayx.actions.Scroll;
import net.thucydides.core.annotations.Step;
import static net.serenitybdd.screenplay.Tasks.instrumented;
public class DisplayBadgesFrom implements Task {
public static DisplayBadgesFrom theLastBuild() {
return instrumented(DisplayBadgesFrom.class, "Last Build");
}
public static DisplayBadgesFrom theLastCompletedBuild() {
return instrumented(DisplayBadgesFrom.class, "Last Completed Build");
}
@Step("{0} selects to display badges from #text")
@Override
public <T extends Actor> void performAs(T actor) {
actor.attemptsTo(
Scroll.to(ViewConfigurationPage.Display_Badges_From),
SelectFromOptions.byVisibleText(text).from(ViewConfigurationPage.Display_Badges_From)
);
}
public DisplayBadgesFrom(String text) {
this.text = text;
}
private final String text;
}
| 34.25 | 101 | 0.752636 |
a87ff12c7af2db7ccfc297d67e2ee5c488f2963f | 411 | package cn.elvea.platform.commons.utils;
import lombok.extern.slf4j.Slf4j;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
/**
* IpUtilsTests
*
* @author elvea
* @since 0.0.1
*/
@Slf4j
public class IpUtilsTests {
@Test
public void test() throws Exception {
String ipAddress = IpUtils.getLocalIpAddress();
Assertions.assertNotNull(ipAddress);
}
}
| 17.869565 | 55 | 0.698297 |
9ae632986c597a61ff28ee4df971b26137a799f8 | 591 | package io.alapierre.jcr.exceptions;
/**
* Created 12.02.2020 copyright original authors 2020
*
* @author Adrian Lapierre {@literal <[email protected]>}
*/
public class DataIntegrityViolationException extends DataAccessException {
public DataIntegrityViolationException() {
}
public DataIntegrityViolationException(String message) {
super(message);
}
public DataIntegrityViolationException(String message, Throwable cause) {
super(message, cause);
}
public DataIntegrityViolationException(Throwable cause) {
super(cause);
}
}
| 24.625 | 77 | 0.71912 |
43045df7089300ccab8db2a00ec272d952d5cb73 | 4,419 | package org.jboss.jube.maven;
import org.apache.maven.archiver.MavenArchiveConfiguration;
import org.apache.maven.artifact.repository.ArtifactRepository;
import org.apache.maven.execution.MavenSession;
import org.apache.maven.plugin.assembly.AssemblerConfigurationSource;
import org.apache.maven.project.MavenProject;
import org.apache.maven.shared.filtering.MavenFileFilter;
import java.io.File;
import java.util.Collections;
import java.util.List;
public class JubeArchiveConfigurationSource implements AssemblerConfigurationSource {
private final MavenProject project;
private final MavenSession mavenSession;
private final MavenArchiveConfiguration archiveConfiguration;
private final MavenFileFilter mavenFilter;
private String[] descriptors;
private String[] descriptorRefs;
public JubeArchiveConfigurationSource(MavenProject project, MavenSession mavenSession, MavenArchiveConfiguration archiveConfiguration, MavenFileFilter mavenFilter, String[] descriptors, String[] descriptorRefs) {
this.project = project;
this.mavenSession = mavenSession;
this.archiveConfiguration = archiveConfiguration;
this.mavenFilter = mavenFilter;
this.descriptors = descriptors;
this.descriptorRefs = descriptorRefs;
}
public String[] getDescriptors() {
return descriptors;
}
public String[] getDescriptorReferences() {
return descriptorRefs;
}
// ============================================================================================
public File getOutputDirectory() {
return new File(project.getBasedir(), "target/jube");
}
public File getWorkingDirectory() {
return new File(project.getBasedir(), "target/jube-work");
}
public File getTemporaryRootDirectory() {
return new File(project.getBasedir(), "target/jube-tmp");
}
public String getFinalName() {
return project.getBuild().getFinalName();
//return ".";
}
public ArtifactRepository getLocalRepository() {
return getMavenSession().getLocalRepository();
}
public MavenFileFilter getMavenFileFilter() {
return mavenFilter;
}
// Maybe use injection
public List<MavenProject> getReactorProjects() {
return project.getCollectedProjects();
}
// Maybe use injection
public List<ArtifactRepository> getRemoteRepositories() {
return project.getRemoteArtifactRepositories();
}
public MavenSession getMavenSession() {
return mavenSession;
}
public MavenArchiveConfiguration getJarArchiveConfiguration() {
return archiveConfiguration;
}
// X
public String getEncoding() {
return project.getProperties().getProperty("project.build.sourceEncoding");
}
// X
public String getEscapeString() {
return null;
}
// X
public MavenProject getProject() {
return project;
}
// X
public File getBasedir() {
return project.getBasedir();
}
// X
public boolean isIgnoreDirFormatExtensions() {
return true;
}
// X
public boolean isDryRun() {
return false;
}
// X
public String getClassifier() {
return null;
}
// X
public List<String> getFilters() {
return Collections.emptyList();
}
// X
public File getDescriptorSourceDirectory() {
return null;
}
// X
public File getArchiveBaseDirectory() {
return null;
}
// X
public String getDescriptorId() {
return null;
}
// X
public String getDescriptor() {
return null;
}
// X
public String getTarLongFileMode() {
return "warn";
}
// X
public File getSiteDirectory() {
return null;
}
// X
public boolean isSiteIncluded() {
return false;
}
// X
public boolean isAssemblyIdAppended() {
return false;
}
// X
public boolean isIgnoreMissingDescriptor() {
return false;
}
// X: (maybe inject MavenArchiveConfiguration)
public String getArchiverConfig() {
return null;
}
public boolean isUpdateOnly() {
return false;
}
public boolean isUseJvmChmod() {
return false;
}
public boolean isIgnorePermissions() {
return true;
}
}
| 23.758065 | 216 | 0.642679 |
5a9132529a4914065560f203148d0dbaa8665288 | 3,734 | /*
* Copyright 2020 Anton Novikau
*
* 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 boringyuri.api.adapter;
import androidx.annotation.NonNull;
/**
* <p>Converts Java or Kotlin objects to {@code String} and back.</p>
* <p>
* By default Boring YURI knows how to serialize and deserialize only
* primitives, primitive wrappers, {@code String} and {@code Uri}.
* If the standard conversion is not appropriate or it is required
* to use some non standard type in the uri builder, implement this
* interface and use it as in the examples below:
* </p>
* <pre><code>
* public class RectAdapter implements BoringTypeAdapter<Rect> {
*
* @NonNull
* public String serialize(@NonNull Rect rect) {
* return rect.left + ";" + rect.top + ";" + rect.right + ";" + rect.bottom;
* }
*
* @NonNull
* public Rect deserialize(@NonNull String rect) {
* String[] vertices = rect.splint(";");
*
* return new Rect(
* Integer.parseInt(vertices[0]),
* Integer.parseInt(vertices[1]),
* Integer.parseInt(vertices[2]),
* Integer.parseInt(vertices[3]));
* }
*
* }
* </code></pre>
* <p>To use the custom type adapter there are two possible ways:</p>
* <ol>
* <li>
* Use {@link TypeAdapter} annotation for the class that must be converted.
* This way works good for the custom types that belong to your code.
* <pre><code>
* @TypeAdapter(UserTypeAdapter.class)
* public class User {
*
* public final String firstName;
* public final String lastName;
*
* public User(String firstName, String lastName) {
* this.firstName = firstName;
* this.lastName = lastName;
* }
*
* }
* </code></pre>
* </li>
* <li>
* Use {@link TypeAdapter} annotation for in combination with
* {@link boringyuri.api.Param} or {@link boringyuri.api.Path} in uri builder
* method signature or in data class getter method
* <pre><code>
* @UriFactory(scheme = "https", authority = "example.com")
* public interface ImageApi {
*
* @UriBuilder("select_rect")
* public Uri buildHighlightUri(@Param @TypeAdapter(RectAdapter.class) Rect highlightArea);
*
* }
* </code></pre>
* <pre><code>
* @UriData
* public interface HighlightData {
*
* @Param
* @TypeAdapter(RectAdapter.class)
* Rect getHighlightArea();
*
* }
* </code></pre>
* </li>
* </ol>
*
* @param <T> Type to convert into String and back into the object.
*/
public interface BoringTypeAdapter<T> {
/**
* Converts {@code original} object of the specified type {@code T} to {@code String}.
*/
@NonNull
String serialize(@NonNull T value);
/**
* Converts the given {@code String} back to the object of the specified type {@code T}.
*/
@NonNull
T deserialize(@NonNull String value);
}
| 33.339286 | 112 | 0.592662 |
14b01904baacf4aa7f94f4c4ace4a65907f60c4a | 354 | package lee.todo.Activity;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import lee.todo.R;
public class SettingActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.setting_layout);
}
}
| 22.125 | 56 | 0.757062 |
56b44fc0d7ab3d54bbe91ed3672171ac752677cd | 185 | package datastructure.Stack;
/**
* Created by joybar on 29/10/17.
*/
public class CustomStack {
private long[] a;
private int size; //栈数组的大小
private int top; //栈顶
}
| 15.416667 | 33 | 0.632432 |
8ecbbb6d93607244e9cb4a1ec602ff4f1c29a300 | 1,070 | package com.example.nirbhay.Police;
public class CrimeRecords {
private Double latitude, longitude;
private int threatLevel;
private String crimeNo;
public CrimeRecords(){
}
public CrimeRecords(Double latitude, Double longitude, int threatLevel, String crimeNo) {
this.latitude = latitude;
this.longitude = longitude;
this.threatLevel = threatLevel;
this.crimeNo = crimeNo;
}
public Double getLatitude() {
return latitude;
}
public void setLatitude(Double latitude) {
this.latitude = latitude;
}
public Double getLongitude() {
return longitude;
}
public void setLongitude(Double longitude) {
this.longitude = longitude;
}
public int getThreatLevel() {
return threatLevel;
}
public void setThreatLevel(int threatLevel) {
this.threatLevel = threatLevel;
}
public String getCrimeNo() {
return crimeNo;
}
public void setCrimeNo(String crimeNo) {
this.crimeNo = crimeNo;
}
}
| 20.980392 | 93 | 0.637383 |
3e55d4283334d05fc6af5a733b933c20d603bf96 | 1,161 | /*
* 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.nepal.auctionhouse.entity;
/**
*
* @author Suzn
*/
public final class LotMeta {
private int id;
private Auction auction;
private Lot lot;
public LotMeta() {
auction = new Auction();
lot = new Lot();
}
/**
* @return the id
*/
public int getId() {
return id;
}
/**
* @param id the id to set
*/
public void setId(int id) {
this.id = id;
}
/**
* @return the auction
*/
public Auction getAuction() {
return auction;
}
/**
* @param auction the auction to set
*/
public void setAuction(Auction auction) {
this.auction = auction;
}
/**
* @return the lot
*/
public Lot getLot() {
return lot;
}
/**
* @param lot the lot to set
*/
public void setLot(Lot lot) {
this.lot = lot;
}
}
| 17.590909 | 80 | 0.503015 |
3c38f8b316f19b2593bc25c9d96b1566688d62e1 | 4,665 | // Copyright (c) 2008 The Board of Trustees of The Leland Stanford Junior University
// Copyright (c) 2011, 2012 Open Networking Foundation
// Copyright (c) 2012, 2013 Big Switch Networks, Inc.
// This library was generated by the LoxiGen Compiler.
// See the file LICENSE.txt which should have been included in the source distribution
// Automatically generated by LOXI from template const_set_serializer.java
// Do not modify
package org.projectfloodlight.openflow.protocol.ver15;
import org.projectfloodlight.openflow.protocol.*;
import org.projectfloodlight.openflow.protocol.action.*;
import org.projectfloodlight.openflow.protocol.actionid.*;
import org.projectfloodlight.openflow.protocol.bsntlv.*;
import org.projectfloodlight.openflow.protocol.errormsg.*;
import org.projectfloodlight.openflow.protocol.meterband.*;
import org.projectfloodlight.openflow.protocol.instruction.*;
import org.projectfloodlight.openflow.protocol.instructionid.*;
import org.projectfloodlight.openflow.protocol.match.*;
import org.projectfloodlight.openflow.protocol.stat.*;
import org.projectfloodlight.openflow.protocol.oxm.*;
import org.projectfloodlight.openflow.protocol.oxs.*;
import org.projectfloodlight.openflow.protocol.queueprop.*;
import org.projectfloodlight.openflow.types.*;
import org.projectfloodlight.openflow.util.*;
import org.projectfloodlight.openflow.exceptions.*;
import org.projectfloodlight.openflow.protocol.OFBsnEnhancedHashType;
import java.util.Set;
import io.netty.buffer.ByteBuf;
import com.google.common.hash.PrimitiveSink;
import java.util.EnumSet;
import java.util.Collections;
public class OFBsnEnhancedHashTypeSerializerVer15 {
public final static long BSN_ENHANCED_HASH_L2_VAL = 0x1L;
public final static long BSN_ENHANCED_HASH_L3_VAL = 0x2L;
public final static long BSN_ENHANCED_HASH_L2GRE_VAL = 0x4L;
public final static long BSN_ENHANCED_HASH_MPLS_VAL = 0x8L;
public final static long BSN_ENHANCED_HASH_GTP_VAL = 0x10L;
public final static long BSN_ENHANCED_HASH_SYMMETRIC_VAL = 0x20L;
public static Set<OFBsnEnhancedHashType> readFrom(ByteBuf bb) throws OFParseError {
try {
return ofWireValue(bb.readLong());
} catch (IllegalArgumentException e) {
throw new OFParseError(e);
}
}
public static void writeTo(ByteBuf bb, Set<OFBsnEnhancedHashType> set) {
bb.writeLong(toWireValue(set));
}
public static void putTo(Set<OFBsnEnhancedHashType> set, PrimitiveSink sink) {
sink.putLong(toWireValue(set));
}
public static Set<OFBsnEnhancedHashType> ofWireValue(long val) {
EnumSet<OFBsnEnhancedHashType> set = EnumSet.noneOf(OFBsnEnhancedHashType.class);
if((val & BSN_ENHANCED_HASH_L2_VAL) != 0)
set.add(OFBsnEnhancedHashType.BSN_ENHANCED_HASH_L2);
if((val & BSN_ENHANCED_HASH_L3_VAL) != 0)
set.add(OFBsnEnhancedHashType.BSN_ENHANCED_HASH_L3);
if((val & BSN_ENHANCED_HASH_L2GRE_VAL) != 0)
set.add(OFBsnEnhancedHashType.BSN_ENHANCED_HASH_L2GRE);
if((val & BSN_ENHANCED_HASH_MPLS_VAL) != 0)
set.add(OFBsnEnhancedHashType.BSN_ENHANCED_HASH_MPLS);
if((val & BSN_ENHANCED_HASH_GTP_VAL) != 0)
set.add(OFBsnEnhancedHashType.BSN_ENHANCED_HASH_GTP);
if((val & BSN_ENHANCED_HASH_SYMMETRIC_VAL) != 0)
set.add(OFBsnEnhancedHashType.BSN_ENHANCED_HASH_SYMMETRIC);
return Collections.unmodifiableSet(set);
}
public static long toWireValue(Set<OFBsnEnhancedHashType> set) {
long wireValue = 0;
for(OFBsnEnhancedHashType e: set) {
switch(e) {
case BSN_ENHANCED_HASH_L2:
wireValue |= BSN_ENHANCED_HASH_L2_VAL;
break;
case BSN_ENHANCED_HASH_L3:
wireValue |= BSN_ENHANCED_HASH_L3_VAL;
break;
case BSN_ENHANCED_HASH_L2GRE:
wireValue |= BSN_ENHANCED_HASH_L2GRE_VAL;
break;
case BSN_ENHANCED_HASH_MPLS:
wireValue |= BSN_ENHANCED_HASH_MPLS_VAL;
break;
case BSN_ENHANCED_HASH_GTP:
wireValue |= BSN_ENHANCED_HASH_GTP_VAL;
break;
case BSN_ENHANCED_HASH_SYMMETRIC:
wireValue |= BSN_ENHANCED_HASH_SYMMETRIC_VAL;
break;
default:
throw new IllegalArgumentException("Illegal enum value for type OFBsnEnhancedHashType in version 1.5: " + e);
}
}
return wireValue;
}
}
| 42.027027 | 129 | 0.699893 |
d9fea0e62654cb0d4236311e8a7c97c5896879ae | 246 | package com.modelagemConceitual.repositories;
import org.springframework.data.jpa.repository.JpaRepository;
import com.modelagemConceitual.domain.ItemPedido;
public interface ItemPedidoRepository extends JpaRepository<ItemPedido, Integer>{
}
| 24.6 | 81 | 0.857724 |
ddb46d7d9d9739601797afa8120b39c35aa7bc0a | 1,191 | package core.util.utilities;
import java.util.UUID;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.BufferedOutputStream;
import org.apache.commons.codec.binary.Base64;
public final class FileUtil{
public static String getDocumentBase64(byte[] bytesContent){
byte[] base64=null;
String base64Str = "";
try {
base64 = Base64.encodeBase64(bytesContent);
base64Str = new String(base64, "UTF-8");
} catch (Throwable e) {
e.printStackTrace();
return "";
}
return base64Str;
}
public static File getFileFromBase64(String base64, String extension){
try {
byte[] decoded = Base64.decodeBase64(base64);
File file = File.createTempFile("temp_"+UUID.randomUUID().toString(), extension);
BufferedOutputStream writer = new BufferedOutputStream(new FileOutputStream(file));
writer.write(decoded);
writer.flush();
writer.close();
return file;
}catch(Exception e){
e.printStackTrace();
return null;
}
}
} | 29.775 | 95 | 0.61293 |
4de94bebcc97b25410557320f48bb6db60100eb8 | 2,970 | /*
* Copyright 2016 Karl Bennett
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package shiver.me.timbers.waiting;
import org.junit.Test;
import shiver.me.timbers.waiting.validation.ValidResult;
import java.util.concurrent.Callable;
import static java.util.concurrent.TimeUnit.MILLISECONDS;
import static org.hamcrest.Matchers.is;
import static org.junit.Assert.assertThat;
import static org.mockito.BDDMockito.given;
import static org.mockito.Mockito.atLeast;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static shiver.me.timbers.data.random.RandomStrings.someString;
public abstract class AbstractITWaiterWaitFor implements ITWaiterWaitFor {
private final ValidResult validator = new ValidResult();
@Test
@Override
public void Can_wait_until_valid_result_is_returned() throws Throwable {
final Callable callable = mock(Callable.class);
final Object expected = "valid";
// Given
given(callable.call()).willReturn(someString(), someString(), expected);
// When
final Object actual = waitFor(500L, MILLISECONDS, validator).waitForMethod(callable);
// Then
assertThat(actual, is(expected));
verify(callable, times(3)).call();
}
@Test
@Override
public void Can_wait_until_time_out_for_valid_result_when_an_invalid_result_is_always_returned() throws Throwable {
final Callable callable = mock(Callable.class);
final Object expected = someString();
// Given
given(callable.call()).willReturn(expected);
// When
final Object actual = waitFor(200L, MILLISECONDS, validator).waitForMethod(callable);
// Then
assertThat(actual, is(expected));
verify(callable, atLeast(2)).call();
}
@Test
@Override
public void Can_wait_until_time_out_for_valid_result_when_an_invalid_result_is_always_returned_and_an_exception_was_thrown() throws Throwable {
final Callable callable = mock(Callable.class);
final Object expected = someString();
// Given
given(callable.call()).willThrow(new Exception()).willReturn(expected);
// When
final Object actual = waitFor(200L, MILLISECONDS, validator).waitForMethod(callable);
// Then
assertThat(actual, is(expected));
verify(callable, atLeast(2)).call();
}
}
| 31.263158 | 147 | 0.714478 |
2d03d06a862e8a996179af484b0ca696c275c90f | 1,685 | /*
* 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.geode.management.internal.cli.shell.jline;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import jline.UnixTerminal;
/**
* This is re-write of UnixTerminal with stty process spawn removed. There is no process named stty
* in windows (non-cygwin process) so that part is commented, also since erase is already applied
* within gfsh script when running under cygwin backspaceDeleteSwitched is hard-coded as true
*
* To know exact changed please see UnixTerminal code.
*
*
*/
public class CygwinMinttyTerminal extends UnixTerminal {
String encoding = System.getProperty("input.encoding", "UTF-8");
InputStreamReader replayReader;
public CygwinMinttyTerminal() throws Exception {}
@Override
public void init() throws Exception {
}
@Override
public void restore() throws Exception {
reset();
}
}
| 33.039216 | 100 | 0.761424 |
be9b33913d8c2df0adae2838787199d500d08186 | 3,643 | package mcjty.rftoolsdim.network;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import mcjty.lib.network.NetworkTools;
import mcjty.lib.varia.Logging;
import mcjty.rftoolsdim.dimensions.DimensionInformation;
import mcjty.rftoolsdim.dimensions.ModDimensions;
import mcjty.rftoolsdim.dimensions.description.DimensionDescriptor;
import net.minecraft.client.Minecraft;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.network.PacketBuffer;
import net.minecraftforge.common.DimensionManager;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
/**
* Sync dimension IDs and RfToolsDimensionManager data from server to client.
*/
public class DimensionSyncPacket {
private final Map<Integer, DimensionDescriptor> dimensions;
private final Map<Integer, DimensionInformation> dimensionInformation;
public DimensionSyncPacket() {
this.dimensions = new HashMap<>();
this.dimensionInformation = new HashMap<>();
}
public DimensionSyncPacket(Map<Integer, DimensionDescriptor> dimensions, Map<Integer, DimensionInformation> dimensionInformation) {
this.dimensions = dimensions;
this.dimensionInformation = dimensionInformation;
}
public void consumePacket(ByteBuf data) {
int size = data.readInt();
for (int i = 0 ; i < size ; i++) {
int id = data.readInt();
PacketBuffer buffer = new PacketBuffer(data);
NBTTagCompound tagCompound;
try {
tagCompound = buffer.readCompoundTag();
} catch (IOException e) {
e.printStackTrace();
return;
}
DimensionDescriptor descriptor = new DimensionDescriptor(tagCompound);
dimensions.put(id, descriptor);
}
size = data.readInt();
for (int i = 0 ; i < size ; i++) {
int id = data.readInt();
String name = NetworkTools.readString(data);
DimensionInformation dimInfo = new DimensionInformation(name, dimensions.get(id), data);
dimensionInformation.put(id, dimInfo);
}
}
public ByteBuf getData() {
ByteBuf data = Unpooled.buffer();
data.writeInt(dimensions.size());
for (Map.Entry<Integer,DimensionDescriptor> me : dimensions.entrySet()) {
data.writeInt(me.getKey());
NBTTagCompound tagCompound = new NBTTagCompound();
me.getValue().writeToNBT(tagCompound);
PacketBuffer buffer = new PacketBuffer(data);
buffer.writeCompoundTag(tagCompound);
}
data.writeInt(dimensionInformation.size());
for (Map.Entry<Integer, DimensionInformation> me : dimensionInformation.entrySet()) {
data.writeInt(me.getKey());
DimensionInformation dimInfo = me.getValue();
NetworkTools.writeString(data, dimInfo.getName());
dimInfo.toBytes(data);
}
return data;
}
public void execute() {
// Only do this on client side.
StringBuilder builder = new StringBuilder();
for (int id : dimensions.keySet()) {
builder.append(id);
builder.append(' ');
if (!DimensionManager.isDimensionRegistered(id)) {
DimensionManager.registerDimension(id, ModDimensions.rftoolsType);
}
}
Logging.log("DimensionSyncPacket: Registering: " + builder.toString());
Minecraft.getMinecraft().addScheduledTask(() -> SyncDimensionInfoHelper.syncDimensionManagerFromServer(dimensions, dimensionInformation));
}
}
| 37.947917 | 146 | 0.657151 |
64b6e332921cfd7c1413621928ef65b5bc80d3d9 | 2,390 | /*
* Copyright 2017 Huawei Technologies Co., Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.openo.sdno.model.servicemodel.tepath;
import static org.junit.Assert.assertEquals;
import java.io.IOException;
import java.util.Map;
import org.junit.Before;
import org.junit.Test;
public class TePathQueryKeyTest {
@Before
public void setUp() throws Exception {
}
@Test
public void test() throws IOException {
TePathQueryKey tePathQueryKey = new TePathQueryKey("vpnId", "srcNeId", "destNeId", "srcAcId", "destAcId");
tePathQueryKey.setVpnId("newVpnId");
tePathQueryKey.setSrcNeId("newSrcNeId");
tePathQueryKey.setDestNeId("newDestNeId");
tePathQueryKey.setSrcAcId("newSrcAcId");
tePathQueryKey.setDestAcId("newDestAcId");
assertEquals(tePathQueryKey.getVpnId(), "newVpnId");
assertEquals(tePathQueryKey.getSrcNeId(), "newSrcNeId");
assertEquals(tePathQueryKey.getDestNeId(), "newDestNeId");
assertEquals(tePathQueryKey.getSrcAcId(), "newSrcAcId");
assertEquals(tePathQueryKey.getDestAcId(), "newDestAcId");
Map<String, String> params = tePathQueryKey.getParams();
assertEquals(params.get("vpnId"), "newVpnId");
assertEquals(params.get("srcNeId"), "newSrcNeId");
assertEquals(params.get("destNeId"), "newDestNeId");
assertEquals(params.get("srcAcId"), "newSrcAcId");
assertEquals(params.get("destAcId"), "newDestAcId");
Map<String, Object> params2 = tePathQueryKey.getObjectParams();
assertEquals(params2.get("vpnId"), "newVpnId");
assertEquals(params2.get("srcNeId"), "newSrcNeId");
assertEquals(params2.get("destNeId"), "newDestNeId");
assertEquals(params2.get("srcAcId"), "newSrcAcId");
assertEquals(params2.get("destAcId"), "newDestAcId");
}
}
| 37.936508 | 114 | 0.698745 |
6c0fb71ab4e645f383aaa97c9bf26ef44c579fe5 | 2,357 | /*
* Copyright © 2019 Cask Data, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package io.cdap.cdap.spi.metadata;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableSet;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.reflect.TypeToken;
import io.cdap.cdap.api.metadata.MetadataScope;
import io.cdap.cdap.proto.codec.NamespacedEntityIdCodec;
import io.cdap.cdap.proto.id.NamespaceId;
import io.cdap.cdap.proto.id.NamespacedEntityId;
import org.junit.Assert;
import org.junit.Test;
import java.util.Collections;
import java.util.List;
public class MetadataMutationCodecTest {
@Test
public void testMetadataMutationCodec() {
List<MetadataMutation> mutations =
ImmutableList.of(
new MetadataMutation.Create(NamespaceId.DEFAULT.toMetadataEntity(),
new Metadata(MetadataScope.SYSTEM, ImmutableSet.of("tag1", "val1")),
Collections.emptyMap()),
new MetadataMutation.Drop(NamespaceId.DEFAULT.toMetadataEntity()),
new MetadataMutation.Remove(NamespaceId.DEFAULT.toMetadataEntity()),
new MetadataMutation.Update(NamespaceId.DEFAULT.toMetadataEntity(), new Metadata(MetadataScope.SYSTEM,
ImmutableSet.of("newtag"))));
Gson gson = new GsonBuilder()
.registerTypeAdapter(NamespacedEntityId.class, new NamespacedEntityIdCodec())
.registerTypeAdapter(Metadata.class, new MetadataCodec())
.registerTypeAdapter(MetadataMutation.class, new MetadataMutationCodec())
.create();
String json = gson.toJson(mutations);
Assert.assertEquals(mutations, gson.fromJson(json, new TypeToken<List<MetadataMutation>>() { }.getType()));
}
}
| 40.637931 | 118 | 0.710649 |
d1f455d8614d937f821fbb010e0dbca6f6d6b992 | 3,755 | package com.codepath.apps.restclienttemplate;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import com.bumptech.glide.load.resource.bitmap.CircleCrop;
import com.codepath.apps.restclienttemplate.models.Tweet;
import com.codepath.apps.restclienttemplate.models.User;
import com.loopj.android.http.JsonHttpResponseHandler;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.parceler.Parcels;
import butterknife.BindView;
import butterknife.ButterKnife;
import cz.msebera.android.httpclient.Header;
public class TweetComposeActivity extends AppCompatActivity {
final static int Max_Tweet_length = 140;
TwitterClient client;
@BindView(R.id.etTweet)
TextView etTweet;
@BindView(R.id.tvusername)
TextView tvusername;
@BindView(R.id.tvuserscreenName)
TextView tvuserscreenName;
@BindView(R.id.btTweet)
Button btTweet;
@BindView(R.id.ivProfileImage)
ImageView ivProfileImage;
@BindView(R.id.ivclose)
ImageView ivclose;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_tweet_compose);
client = TwitterApp.getRestClient(this);
ButterKnife.bind(this);
String user_profile_image_url = getIntent().getStringExtra("user_profile_image_url");
String user_screenName = getIntent().getStringExtra("user_screenName");
String username = getIntent().getStringExtra("username");
Log.d("username",user_screenName);
tvusername.setText(username);
tvuserscreenName.setText("@"+user_screenName);
GlideApp.with(this)
.load(user_profile_image_url)
.transform(new CircleCrop())
.into(ivProfileImage);
ivclose.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent i = new Intent(TweetComposeActivity.this,TimelineActivity.class);
startActivity(i);
}
});
btTweet.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
String contentTweet = etTweet.getText().toString();
if(contentTweet.isEmpty()){
Toast.makeText(TweetComposeActivity.this,"Votre Tweet est vide",Toast.LENGTH_SHORT).show();
return;
}
if (contentTweet.length()>Max_Tweet_length){
Toast.makeText(TweetComposeActivity.this,"Votre Tweet est trop long",Toast.LENGTH_SHORT).show();
return;
}
client.composeTweet(contentTweet, new JsonHttpResponseHandler(){
@Override
public void onSuccess(int statusCode, Header[] headers, JSONObject response) {
Log.d("tweet",response.toString());
Intent data = new Intent(TweetComposeActivity.this,TimelineActivity.class);
setResult(RESULT_OK, data);
finish();
}
@Override
public void onFailure(int statusCode, Header[] headers, String responseString, Throwable throwable) {
Log.d("TwitterClient","Error "+responseString);
}
});
}
});
}
}
| 31.291667 | 121 | 0.636751 |
d487f27afa81c5042b9954bbf58cb88b0bce5458 | 4,244 | package ru.progrm_jarvis.reflector.bytecode.mirror;
import javassist.CtClass;
import javassist.NotFoundException;
import lombok.val;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.*;
import static ru.progrm_jarvis.reflector.TestUtil.getCtClass;
import static ru.progrm_jarvis.reflector.bytecode.mirror.ClassMemberMirrorer.mirrorerOf;
class BytecodeMirroringTaskTest {
private static final int VALUE_1337 = 1337;
@Test
@SuppressWarnings("ConstantConditions")
void testRun() throws NotFoundException {
{
val abstractClassImpl2CtClass = getCtClass(AbstractClassImpl2.class);
BytecodeMirroringTask.builder()
// target
.target(getCtClass(getClass().getTypeName().concat("$TargetClass")))
// delegators
.delegator(getCtClass(Interface1.class))
.delegator(getCtClass(Interface2.class))
// implementation details
.method(mirrorerOf(getCtClass(AbstractClassImpl1.class).getDeclaredMethod("i1")))
.method(mirrorerOf(getCtClass(InterfaceImpl.class).getDeclaredMethod("i2")))
.method(mirrorerOf(abstractClassImpl2CtClass.getDeclaredMethod("iPlusPlus")))
.method(mirrorerOf(abstractClassImpl2CtClass.getDeclaredMethod("getLeet")))
// fields
.field(mirrorerOf(abstractClassImpl2CtClass.getDeclaredField("VALUE1")))
.field(mirrorerOf(abstractClassImpl2CtClass.getDeclaredField("i")))
// callback
.callback(CtClass::toClass)
// build and run
.build()
.run();
}
// create instance
val instance = new TargetClass();
@SuppressWarnings("RedundantCast") // used for suppressing compile-time errors due to incompatible types
val instanceObject = (Object) instance;
assertThrows(ExistingMethodReturn.class, instance::existingMethod);
// Interface1
assertTrue(instanceObject instanceof Interface1);
{
val castInstance = (Interface1) instanceObject;
assertThrows(I1Return.class, castInstance::i1);
}
// Interface2
assertTrue(instanceObject instanceof Interface2);
{
val castInstance = (Interface2) instanceObject;
assertThrows(I2Return.class, castInstance::i2);
assertEquals(VALUE_1337, castInstance.getLeet());
int i = 0;
for (int j = 0; j < 10; j++) {
assertEquals(i++, castInstance.iPlusPlus());
}
}
}
private interface Interface1 {
void i1();
}
private interface Interface2 {
void i2();
int iPlusPlus();
int getLeet();
}
private abstract static class AbstractClassImpl1 implements Interface1 {
@Override
public void i1() {
throw new I1Return();
}
}
private interface InterfaceImpl extends Interface2 {
@Override
default void i2() {
throw new I2Return();
}
}
private abstract static class AbstractClassImpl2 implements Interface2{
private final int VALUE1 = VALUE_1337;
private int i = 0;
@Override
public int iPlusPlus() {
return i++;
}
@Override
public int getLeet() {
return VALUE1;
}
}
private static final class TargetClass {
public void existingMethod() {
throw new ExistingMethodReturn();
}
}
/*
Used to indicate that the method is working correctly when it returns void
*/
private static final class ExistingMethodReturn extends RuntimeException {}
/*
Used to indicate that the method is working correctly when it returns void
*/
private static final class I1Return extends RuntimeException {}
/*
Used to indicate that the method is working correctly when it returns void
*/
private static final class I2Return extends RuntimeException {}
} | 31.205882 | 112 | 0.611923 |
dc5f1bc9dd8c5f663e23a68d58870d134a2c0db2 | 252 | package io.github.zutherb.appstash.shop.ui.event.cart;
import io.github.zutherb.appstash.shop.ui.event.AjaxEvent;
/**
* @author zutherb
* <p>
* marker interface
*/
public interface CartChangeEvent extends AjaxEvent { /* NOOP */
}
| 21 | 63 | 0.686508 |
0508b1e3f95570839c83dccf3014be67c8b07a32 | 7,026 | /* DO NOT EDIT */
/* This file was generated from team_groups.stone */
package com.dropbox.core.v2.team;
import com.dropbox.core.stone.StoneSerializers;
import com.dropbox.core.stone.StructSerializer;
import com.fasterxml.jackson.core.JsonGenerationException;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.core.JsonToken;
import java.io.IOException;
import java.util.List;
class GroupMembersRemoveArg extends IncludeMembersArg {
// struct GroupMembersRemoveArg
protected final GroupSelector group;
protected final List<UserSelectorArg> users;
/**
*
* @param group Group from which users will be removed. Must not be {@code
* null}.
* @param users List of users to be removed from the group. Must not
* contain a {@code null} item and not be {@code null}.
* @param returnMembers Whether to return the list of members in the group.
* Note that the default value will cause all the group members to be
* returned in the response. This may take a long time for large groups.
*
* @throws IllegalArgumentException If any argument does not meet its
* preconditions.
*/
public GroupMembersRemoveArg(GroupSelector group, List<UserSelectorArg> users, boolean returnMembers) {
super(returnMembers);
if (group == null) {
throw new IllegalArgumentException("Required value for 'group' is null");
}
this.group = group;
if (users == null) {
throw new IllegalArgumentException("Required value for 'users' is null");
}
for (UserSelectorArg x : users) {
if (x == null) {
throw new IllegalArgumentException("An item in list 'users' is null");
}
}
this.users = users;
}
/**
* The default values for unset fields will be used.
*
* @param group Group from which users will be removed. Must not be {@code
* null}.
* @param users List of users to be removed from the group. Must not
* contain a {@code null} item and not be {@code null}.
*
* @throws IllegalArgumentException If any argument does not meet its
* preconditions.
*/
public GroupMembersRemoveArg(GroupSelector group, List<UserSelectorArg> users) {
this(group, users, true);
}
/**
* Group from which users will be removed.
*
* @return value for this field, never {@code null}.
*/
public GroupSelector getGroup() {
return group;
}
/**
* List of users to be removed from the group.
*
* @return value for this field, never {@code null}.
*/
public List<UserSelectorArg> getUsers() {
return users;
}
@Override
public int hashCode() {
int hash = java.util.Arrays.hashCode(new Object [] {
group,
users
});
hash = (31 * super.hashCode()) + hash;
return hash;
}
@Override
public boolean equals(Object obj) {
if (obj == this) {
return true;
}
// be careful with inheritance
else if (obj.getClass().equals(this.getClass())) {
GroupMembersRemoveArg other = (GroupMembersRemoveArg) obj;
return ((this.group == other.group) || (this.group.equals(other.group)))
&& ((this.users == other.users) || (this.users.equals(other.users)))
&& (this.returnMembers == other.returnMembers)
;
}
else {
return false;
}
}
@Override
public String toString() {
return Serializer.INSTANCE.serialize(this, false);
}
/**
* Returns a String representation of this object formatted for easier
* readability.
*
* <p> The returned String may contain newlines. </p>
*
* @return Formatted, multiline String representation of this object
*/
public String toStringMultiline() {
return Serializer.INSTANCE.serialize(this, true);
}
/**
* For internal use only.
*/
static final class Serializer extends StructSerializer<GroupMembersRemoveArg> {
public static final Serializer INSTANCE = new Serializer();
@Override
public void serialize(GroupMembersRemoveArg value, JsonGenerator g, boolean collapse) throws IOException, JsonGenerationException {
if (!collapse) {
g.writeStartObject();
}
g.writeFieldName("group");
GroupSelector.Serializer.INSTANCE.serialize(value.group, g);
g.writeFieldName("users");
StoneSerializers.list(UserSelectorArg.Serializer.INSTANCE).serialize(value.users, g);
g.writeFieldName("return_members");
StoneSerializers.boolean_().serialize(value.returnMembers, g);
if (!collapse) {
g.writeEndObject();
}
}
@Override
public GroupMembersRemoveArg deserialize(JsonParser p, boolean collapsed) throws IOException, JsonParseException {
GroupMembersRemoveArg value;
String tag = null;
if (!collapsed) {
expectStartObject(p);
tag = readTag(p);
}
if (tag == null) {
GroupSelector f_group = null;
List<UserSelectorArg> f_users = null;
Boolean f_returnMembers = true;
while (p.getCurrentToken() == JsonToken.FIELD_NAME) {
String field = p.getCurrentName();
p.nextToken();
if ("group".equals(field)) {
f_group = GroupSelector.Serializer.INSTANCE.deserialize(p);
}
else if ("users".equals(field)) {
f_users = StoneSerializers.list(UserSelectorArg.Serializer.INSTANCE).deserialize(p);
}
else if ("return_members".equals(field)) {
f_returnMembers = StoneSerializers.boolean_().deserialize(p);
}
else {
skipValue(p);
}
}
if (f_group == null) {
throw new JsonParseException(p, "Required field \"group\" missing.");
}
if (f_users == null) {
throw new JsonParseException(p, "Required field \"users\" missing.");
}
value = new GroupMembersRemoveArg(f_group, f_users, f_returnMembers);
}
else {
throw new JsonParseException(p, "No subtype found that matches tag: \"" + tag + "\"");
}
if (!collapsed) {
expectEndObject(p);
}
return value;
}
}
}
| 35.13 | 139 | 0.575149 |
f4764fa43575c0d45efc00d70dc10fcb07046a93 | 9,229 | package com.mobius.software.android.iotbroker.main.iot_protocols.amqp.classes.headerapi;
import com.mobius.software.android.iotbroker.main.iot_protocols.amqp.classes.codes.AMQPType;
import com.mobius.software.android.iotbroker.main.iot_protocols.amqp.classes.codes.HeaderCodes;
import com.mobius.software.android.iotbroker.main.iot_protocols.amqp.classes.codes.SectionCodes;
import com.mobius.software.android.iotbroker.main.iot_protocols.amqp.classes.codes.StateCodes;
import com.mobius.software.android.iotbroker.main.iot_protocols.amqp.classes.exceptions.MalformedHeaderException;
import com.mobius.software.android.iotbroker.main.iot_protocols.amqp.classes.headeramqp.AMQPAttach;
import com.mobius.software.android.iotbroker.main.iot_protocols.amqp.classes.headeramqp.AMQPBegin;
import com.mobius.software.android.iotbroker.main.iot_protocols.amqp.classes.headeramqp.AMQPClose;
import com.mobius.software.android.iotbroker.main.iot_protocols.amqp.classes.headeramqp.AMQPDetach;
import com.mobius.software.android.iotbroker.main.iot_protocols.amqp.classes.headeramqp.AMQPDisposition;
import com.mobius.software.android.iotbroker.main.iot_protocols.amqp.classes.headeramqp.AMQPEnd;
import com.mobius.software.android.iotbroker.main.iot_protocols.amqp.classes.headeramqp.AMQPFlow;
import com.mobius.software.android.iotbroker.main.iot_protocols.amqp.classes.headeramqp.AMQPOpen;
import com.mobius.software.android.iotbroker.main.iot_protocols.amqp.classes.headeramqp.AMQPTransfer;
import com.mobius.software.android.iotbroker.main.iot_protocols.amqp.classes.headersasl.SASLChallenge;
import com.mobius.software.android.iotbroker.main.iot_protocols.amqp.classes.headersasl.SASLInit;
import com.mobius.software.android.iotbroker.main.iot_protocols.amqp.classes.headersasl.SASLMechanisms;
import com.mobius.software.android.iotbroker.main.iot_protocols.amqp.classes.headersasl.SASLOutcome;
import com.mobius.software.android.iotbroker.main.iot_protocols.amqp.classes.headersasl.SASLResponse;
import com.mobius.software.android.iotbroker.main.iot_protocols.amqp.classes.sections.AMQPData;
import com.mobius.software.android.iotbroker.main.iot_protocols.amqp.classes.sections.AMQPFooter;
import com.mobius.software.android.iotbroker.main.iot_protocols.amqp.classes.sections.AMQPProperties;
import com.mobius.software.android.iotbroker.main.iot_protocols.amqp.classes.sections.AMQPSection;
import com.mobius.software.android.iotbroker.main.iot_protocols.amqp.classes.sections.AMQPSequence;
import com.mobius.software.android.iotbroker.main.iot_protocols.amqp.classes.sections.AMQPValue;
import com.mobius.software.android.iotbroker.main.iot_protocols.amqp.classes.sections.ApplicationProperties;
import com.mobius.software.android.iotbroker.main.iot_protocols.amqp.classes.sections.DeliveryAnnotations;
import com.mobius.software.android.iotbroker.main.iot_protocols.amqp.classes.sections.MessageAnnotations;
import com.mobius.software.android.iotbroker.main.iot_protocols.amqp.classes.sections.MessageHeader;
import com.mobius.software.android.iotbroker.main.iot_protocols.amqp.classes.tlv.api.TLVAmqp;
import com.mobius.software.android.iotbroker.main.iot_protocols.amqp.classes.tlv.api.TLVFactory;
import com.mobius.software.android.iotbroker.main.iot_protocols.amqp.classes.tlv.compound.TLVList;
import com.mobius.software.android.iotbroker.main.iot_protocols.amqp.classes.tlv.described.AMQPAccepted;
import com.mobius.software.android.iotbroker.main.iot_protocols.amqp.classes.tlv.described.AMQPModified;
import com.mobius.software.android.iotbroker.main.iot_protocols.amqp.classes.tlv.described.AMQPOutcome;
import com.mobius.software.android.iotbroker.main.iot_protocols.amqp.classes.tlv.described.AMQPReceived;
import com.mobius.software.android.iotbroker.main.iot_protocols.amqp.classes.tlv.described.AMQPRejected;
import com.mobius.software.android.iotbroker.main.iot_protocols.amqp.classes.tlv.described.AMQPReleased;
import com.mobius.software.android.iotbroker.main.iot_protocols.amqp.classes.tlv.described.AMQPState;
import io.netty.buffer.ByteBuf;
/**
* Mobius Software LTD
* Copyright 2015-2017, Mobius Software LTD
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software 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 software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
public class AMQPFactory {
public static AMQPHeader getAMQP(ByteBuf buf) {
TLVAmqp list = TLVFactory.getTlv(buf);
if (!list.getCode().equals(AMQPType.LIST_0) && list.getCode().equals(AMQPType.LIST_8)
&& list.getCode().equals(AMQPType.LIST_32))
throw new MalformedHeaderException("Received amqp-header with malformed arguments");
AMQPHeader header = null;
Byte byteCode = list.getConstructor().getDescriptorCode();
HeaderCodes code = HeaderCodes.valueOf(byteCode);
switch (code) {
case ATTACH:
header = new AMQPAttach();
break;
case BEGIN:
header = new AMQPBegin();
break;
case CLOSE:
header = new AMQPClose();
break;
case DETACH:
header = new AMQPDetach();
break;
case DISPOSITION:
header = new AMQPDisposition();
break;
case END:
header = new AMQPEnd();
break;
case FLOW:
header = new AMQPFlow();
break;
case OPEN:
header = new AMQPOpen();
break;
case TRANSFER:
header = new AMQPTransfer();
break;
default:
throw new MalformedHeaderException("Received amqp-header with unrecognized performative");
}
header.fillArguments((TLVList) list);
return header;
}
public static AMQPHeader getSASL(ByteBuf buf) {
TLVAmqp list = TLVFactory.getTlv(buf);
if (!list.getCode().equals(AMQPType.LIST_0) && list.getCode().equals(AMQPType.LIST_8)
&& list.getCode().equals(AMQPType.LIST_32))
throw new MalformedHeaderException("Received sasl-header with malformed arguments");
AMQPHeader header = null;
Byte byteCode = list.getConstructor().getDescriptorCode();
HeaderCodes code = HeaderCodes.valueOf(byteCode);
switch (code) {
case CHALLENGE:
header = new SASLChallenge();
break;
case INIT:
header = new SASLInit();
break;
case MECHANISMS:
header = new SASLMechanisms();
break;
case OUTCOME:
header = new SASLOutcome();
break;
case RESPONSE:
header = new SASLResponse();
break;
default:
throw new MalformedHeaderException("Received sasl-header with unrecognized arguments code");
}
header.fillArguments((TLVList) list);
return header;
}
public static AMQPSection getSection(ByteBuf buf) {
TLVAmqp value = TLVFactory.getTlv(buf);
AMQPSection section = null;
Byte byteCode = value.getConstructor().getDescriptorCode();
SectionCodes code = SectionCodes.valueOf(byteCode);
switch (code) {
case APPLICATION_PROPERTIES:
section = new ApplicationProperties();
break;
case DATA:
section = new AMQPData();
break;
case DELIVERY_ANNOTATIONS:
section = new DeliveryAnnotations();
break;
case FOOTER:
section = new AMQPFooter();
break;
case HEADER:
section = new MessageHeader();
break;
case MESSAGE_ANNOTATIONS:
section = new MessageAnnotations();
break;
case PROPERTIES:
section = new AMQPProperties();
break;
case SEQUENCE:
section = new AMQPSequence();
break;
case VALUE:
section = new AMQPValue();
break;
default:
throw new MalformedHeaderException("Received header with unrecognized message section code");
}
section.fill(value);
return section;
}
public static AMQPState getState(TLVList list) {
AMQPState state = null;
Byte byteCode = list.getConstructor().getDescriptorCode();
StateCodes code = StateCodes.valueOf(byteCode);
switch (code) {
case ACCEPTED:
state = new AMQPAccepted();
break;
case MODIFIED:
state = new AMQPModified();
break;
case RECEIVED:
state = new AMQPReceived();
break;
case REJECTED:
state = new AMQPRejected();
break;
case RELEASED:
state = new AMQPReleased();
break;
default:
throw new MalformedHeaderException("Received header with unrecognized state code");
}
return state;
}
public static AMQPOutcome getOutcome(TLVList list) {
AMQPOutcome outcome = null;
Byte byteCode = list.getConstructor().getDescriptorCode();
StateCodes code = StateCodes.valueOf(byteCode);
switch (code) {
case ACCEPTED:
outcome = new AMQPAccepted();
break;
case MODIFIED:
outcome = new AMQPModified();
break;
case REJECTED:
outcome = new AMQPRejected();
break;
case RELEASED:
outcome = new AMQPReleased();
break;
default:
throw new MalformedHeaderException("Received header with unrecognized outcome code");
}
return outcome;
}
}
| 36.768924 | 113 | 0.777657 |
e6acd60feee17f2f754daa1dacf1b506ee43ad52 | 2,454 | import static org.junit.jupiter.api.Assertions.*;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
public class PetShopTest {
private PetShop petShop;
@BeforeEach
public void setUp() {
petShop = new PetShop();
}
// testes para os casos em que alguma exceção será lançada.
@Test
public void testCadastrarAnimalNomeInvalido() {
assertThrows(IllegalArgumentException.class,
() -> petShop.cadastrarAnimal(null, "Gato", 10));
assertThrows(IllegalArgumentException.class,
() -> petShop.cadastrarAnimal("", "Gato", 10));
assertThrows(IllegalArgumentException.class,
() -> petShop.cadastrarAnimal(" ", "Gato", 10));
}
@Test
public void testCadastrarAnimalEspecieInvalida() {
assertThrows(IllegalArgumentException.class,
() -> petShop.cadastrarAnimal("Julieta", null, 10));
assertThrows(IllegalArgumentException.class,
() -> petShop.cadastrarAnimal("Julieta", "", 10));
assertThrows(IllegalArgumentException.class,
() -> petShop.cadastrarAnimal("Julieta", " ", 10));
}
@Test
public void testCadastrarAnimalIdadeInvalida() {
assertThrows(IllegalArgumentException.class,
() -> petShop.cadastrarAnimal("Julieta", "Gato", -1));
}
// testes para casos válidos.
@Test
public void testCadastrarAnimalValido() {
assertTrue(petShop.cadastrarAnimal("Julieta", "Gato", 8));
assertFalse(petShop.cadastrarAnimal("Julieta", "Cachorro", 10));
}
@Test
public void testAnimalExiste() {
assertFalse(petShop.animalExiste("Aderbaldo"));
petShop.cadastrarAnimal("Aderbaldo", "Gato", 8);
assertTrue(petShop.animalExiste("Aderbaldo"));
assertTrue(petShop.animalExiste("AdErBaLdO"));
}
@Test
public void testMediaIdade() {
assertEquals(0, petShop.mediaIdade(), 0.01);
petShop.cadastrarAnimal("Aderbaldo", "Gato", 8);
petShop.cadastrarAnimal("Aderbaldo", "Sapo", 5); // não deve cadastrar, pois já existe.
assertEquals(8, petShop.mediaIdade(), 0.0001);
petShop.cadastrarAnimal("Julieta", "Cachorro", 3);
petShop.cadastrarAnimal("Garfield", "Gato", 5);
assertEquals(5.3, petShop.mediaIdade(), 0.04);
}
@Test
public void testTotalAnimaisCadastrados() {
assertEquals(0, petShop.totalAnimaisCadastrados());
petShop.cadastrarAnimal("Aderbaldo", "Gato", 8);
assertEquals(1, petShop.totalAnimaisCadastrados());
petShop.cadastrarAnimal("Aderbaldo", "Gato", 3);
assertEquals(1, petShop.totalAnimaisCadastrados());
}
}
| 29.214286 | 89 | 0.716789 |
86392ccdca6f74e679007adc2065d2ff5ee6fd5f | 5,512 |
package com.carlosfilipe.zup.bootcamp.fase3.controller;
import java.io.BufferedReader;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.carlosfilipe.zup.bootcamp.fase3.config.Config;
import com.carlosfilipe.zup.bootcamp.fase3.dao.ContaDAO;
import com.carlosfilipe.zup.bootcamp.fase3.model.Conta;
import com.carlosfilipe.zup.bootcamp.fase3.model.Usuario;
import com.jayway.jsonpath.JsonPathException;
import org.springframework.boot.json.JsonParseException;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import net.minidev.json.JSONObject;
@RestController
public class ContaController {
static ContaDAO contaDAO = Application.context.getBean("ContaDAO", ContaDAO.class);
@GetMapping("/")
public String root() {
return "Bem vindo ao Instagram API";
}
@PostMapping("/inscrever-se")
public Object inscreverSe(HttpServletRequest request, HttpServletResponse response, @RequestBody String body)
throws IOException, JsonPathException {
JSONObject json = new JSONObject();
response.setContentType("application/json");
int result = 0;
try {
result = contaDAO.insert(json.getAsString("nomeUsuario"), json.getAsString("senha"),
json.getAsString("email"), json.getAsString("nome"));
} catch (DuplicateKeyException e) {
return "Usuario existe";
}
if (result == 1) {
String body1 = new String(Files.readAllBytes(Paths.get(Config.getConfig("mail.verify.path1"))),
StandardCharsets.UTF_8);
String body2 = new String(Files.readAllBytes(Paths.get(Config.getConfig("mail.verify.path2"))),
StandardCharsets.UTF_8);
String verify = contaDAO.getLinkVerificação(json.getAsString("nomeUsuario"));
String email = contaDAO.getEmail(json.getAsString("nomeUsuario"));
return "true";
}
else
return "Falha no registro";
}
@GetMapping("/verificar/reenviar/{nomeUsuario}")
public String reenviar(@PathVariable("nomeUsuario") String nomeUsuario) throws IOException {
String body1 = new String(Files.readAllBytes(Paths.get(Config.getConfig("mail.verify.path1"))),
StandardCharsets.UTF_8);
String body2 = new String(Files.readAllBytes(Paths.get(Config.getConfig("mail.verify.path2"))),
StandardCharsets.UTF_8);
String verify = contaDAO.getLinkVerificação(nomeUsuario);
String email = contaDAO.getEmail(nomeUsuario);
return "Feito";
}
@GetMapping("/verificar/{nomeUsuario}/{hash}")
public String verificar(@PathVariable("nomeUsuario") String nomeUsuario, @PathVariable("hash") String hash) {
return contaDAO.verificar(nomeUsuario, hash);
}
@GetMapping("/conta")
public Conta conta() {
String nomeUsuario = SecurityContextHolder.getContext().getAuthentication().getName();
return contaDAO.getConta(nomeUsuario);
}
@PutMapping("/conta/atualizarInfo")
public String atualizarInfo(HttpServletRequest request, @RequestBody String body) throws IOException,
JsonParseException {
String nomeUsuario = SecurityContextHolder.getContext().getAuthentication().getName();
JSONObject json = new JSONObject();
Conta conta = new Conta();
conta.setNomeUsuario(json.getAsString("nomeUsuario"));
conta.setEmail(json.getAsString("email"));
conta.setNome(json.getAsString("nome"));
if (contaDAO.atualizarInfo(nomeUsuario, conta) == 1)
return "{\"resultado\":\"sucesso\"}";
else
return "{\"resultado\":\"erro\"}";
}
@PutMapping("/conta/atualizarSenha")
public String atualizarSenha(HttpServletRequest request) throws JsonParseException, IOException {
String nomeUsuario = SecurityContextHolder.getContext().getAuthentication().getName();
StringBuffer buffer = new StringBuffer();
String line = null;
BufferedReader reader = request.getReader();
while ((line = reader.readLine()) != null)
buffer.append(line);
JSONObject json = new JSONObject();
if (contaDAO.atualizarSenha(nomeUsuario, json.getAsString("senha")) == 1)
return "{\"resultado\":\"sucesso\"}";
else
return "{\"resultado\":\"erro\"}";
}
@GetMapping(value = "/buscar/usuario", params= "buscar")
public List<Usuario> buscarUsuario(@RequestParam("buscar") String palavraChave) {
String usuarioAtual = SecurityContextHolder.getContext().getAuthentication().getName();
return contaDAO.buscarUsuario(palavraChave, usuarioAtual);
}
@GetMapping("/segue/{username}")
public String segue(@PathVariable("username") String username) {
String currentUser = SecurityContextHolder.getContext().getAuthentication().getName();
return "{\"follow_status\":\"" + contaDAO.segue(currentUser, username) + "\"}";
}
} | 39.942029 | 113 | 0.721335 |
82f88e9b94040b8ba6b1be88f7183944ac9c4ccf | 1,139 | package com.codepath.simpletodo;
import com.raizlabs.android.dbflow.annotation.Column;
import com.raizlabs.android.dbflow.annotation.PrimaryKey;
import com.raizlabs.android.dbflow.annotation.Table;
import com.raizlabs.android.dbflow.structure.BaseModel;
/**
* Created by praniti on 8/20/17.
*/
//Table name: ToDoItem
@Table(database = ToDoDatabase.class)
public class ToDoItem extends BaseModel {
@Column
@PrimaryKey
private int position;
@Column
private String name;
@Column
private String date;
@Column
private String priority;
public int getPosition() {
return position;
}
public void setPosition(int position) {
this.position = position;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getDate() {
return date;
}
public void setDate(String date) {
this.date = date;
}
public String getPriority() {
return priority;
}
public void setPriority(String priority) {
this.priority = priority;
}
}
| 18.672131 | 57 | 0.652327 |
bb48a95fec641d75c8360b5e1ea4800e9c748ddb | 1,997 | package com.krevin.crockpod.alarm;
import android.content.Context;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.TextView;
import com.android.volley.toolbox.ImageLoader;
import com.android.volley.toolbox.NetworkImageView;
import com.krevin.crockpod.R;
import com.krevin.crockpod.podcast.Podcast;
class PodcastArrayAdapter extends ArrayAdapter<Podcast> {
private final ImageLoader mImageLoader;
PodcastArrayAdapter(@NonNull Context context, ImageLoader imageLoader) {
super(context, R.layout.podcast_search_item);
mImageLoader = imageLoader;
}
@NonNull
@Override
public View getView(int position, @Nullable View convertView, @NonNull ViewGroup parent) {
View view = getView(convertView, parent);
TextView titleView = view.findViewById(R.id.podcast_search_item_title);
TextView authorView = view.findViewById(R.id.podcast_search_item_author);
NetworkImageView logoView = view.findViewById(R.id.podcast_search_item_logo);
if (position % 2 == 0) {
view.setBackgroundColor(getContext().getResources().getColor(R.color.colorAlmostPrimary, null));
} else {
view.setBackgroundColor(getContext().getResources().getColor(R.color.colorPrimary, null));
}
Podcast podcast = getItem(position);
if (podcast != null) {
titleView.setText(podcast.getName());
authorView.setText(podcast.getAuthor());
logoView.setImageUrl(podcast.getLogoUrlSmall(), mImageLoader);
}
return view;
}
private View getView(View convertView, ViewGroup parent) {
return convertView == null ?
LayoutInflater.from(getContext()).inflate(R.layout.podcast_search_item, parent, false) :
convertView;
}
} | 36.309091 | 108 | 0.712068 |
e3b85b4658d5ff486e518526bcc6b150fbf9dee6 | 6,154 | package it.spid.cie.oidc.helper;
import com.nimbusds.jose.jwk.JWKSet;
import java.net.URI;
import java.net.URLEncoder;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.net.http.HttpResponse.BodyHandlers;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import org.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import it.spid.cie.oidc.exception.OIDCException;
import it.spid.cie.oidc.model.FederationEntity;
import it.spid.cie.oidc.util.JSONUtil;
import it.spid.cie.oidc.util.Validator;
public class OAuth2Helper {
public static final String JWT_BARRIER = "urn:ietf:params:oauth:client-assertion-type:jwt-bearer";
private static final Logger logger = LoggerFactory.getLogger(OAuth2Helper.class);
private final JWTHelper jwtHelper;
public OAuth2Helper(JWTHelper jwtHelper) {
this.jwtHelper = jwtHelper;
}
/**
* Obtain the Access Token from the Authorization Code
*
* @see <a href="https://tools.ietf.org/html/rfc6749#section-4.1.3">
* https://tools.ietf.org/html/rfc6749#section-4.1.3</a>
*
* @param redirectUrl
* @param state
* @param code
* @param issuerId
* @param clientConf the "well known" configuration of the federation entity making
* the request
* @param tokenEndpointUrl
* @param codeVerifier
* @return
* @throws Exception
*/
public JSONObject performAccessTokenRequest(
String redirectUrl, String state, String code, String issuerId,
FederationEntity clientConf, String tokenEndpointUrl, String codeVerifier)
throws OIDCException {
if (clientConf == null || Validator.isNullOrEmpty(tokenEndpointUrl)) {
throw new OIDCException(
String.format(
"Invalid clientConf %s or tokenEndpoint %s", clientConf,
tokenEndpointUrl));
}
try {
// create client assertion (JWS Token)
JSONObject payload = new JSONObject()
.put("iss", clientConf.getSubject())
.put("sub", clientConf.getSubject())
.put("aud", JSONUtil.asJSONArray(tokenEndpointUrl))
.put("iat", JWTHelper.getIssuedAt())
.put("exp", JWTHelper.getExpiresOn())
.put("jti", UUID.randomUUID().toString());
JWKSet jwkSet = JWTHelper.getJWKSetFromJSON(clientConf.getJwks());
String clientAssertion = jwtHelper.createJWS(payload, jwkSet);
// Body Parameters
Map<String, Object> params = new HashMap<>();
params.put("grant_type", "authorization_code");
params.put("redirect_uri", redirectUrl);
params.put("client_id", clientConf.getSubject());
params.put("state", state);
params.put("code", code);
params.put("code_verifier", codeVerifier);
params.put("client_assertion_type", JWT_BARRIER);
params.put("client_assertion", clientAssertion);
if (logger.isDebugEnabled()) {
logger.debug(
"Access Token Request for {}: {}", state, buildPostBody(params));
}
// POST
HttpRequest request = HttpRequest.newBuilder()
.uri(new URI(tokenEndpointUrl))
.POST(HttpRequest.BodyPublishers.ofString(buildPostBody(params)))
.header("Content-Type", "application/x-www-form-urlencoded")
.build();
// TODO: timeout from options?
HttpResponse<String> response = HttpClient.newBuilder()
.build()
.send(request, BodyHandlers.ofString());
if (response.statusCode() != 200) {
logger.error(
"Something went wrong with {}: {}", state, response.statusCode());
}
else {
try {
return new JSONObject(response.body());
}
catch(Exception e) {
logger.error(
"Something went wrong with {}: {}", state, e.getMessage());
}
}
return new JSONObject();
}
catch (Exception e) {
throw new OIDCException(e);
}
}
public void sendRevocationRequest(
String token, String clientId, String revocationUrl,
FederationEntity clientConf)
throws OIDCException {
if (clientConf == null || Validator.isNullOrEmpty(revocationUrl)) {
throw new OIDCException(
String.format(
"Invalid clientConf %s or revocationUrl %s", clientConf,
revocationUrl));
}
try {
// create client assertion (JWS Token)
JSONObject payload = new JSONObject()
.put("iss", clientId)
.put("sub", clientId)
.put("aud", JSONUtil.asJSONArray(revocationUrl))
.put("iat", JWTHelper.getIssuedAt())
.put("exp", JWTHelper.getExpiresOn())
.put("jti", UUID.randomUUID().toString());
JWKSet jwkSet = JWTHelper.getJWKSetFromJSON(clientConf.getJwks());
String clientAssertion = jwtHelper.createJWS(payload, jwkSet);
// Body Parameters
Map<String, Object> params = new HashMap<>();
params.put("token", token);
params.put("client_id", clientId);
params.put("client_assertion", clientAssertion);
params.put("client_assertion_type", JWT_BARRIER);
if (logger.isDebugEnabled()) {
logger.debug("Send Token Revocation: {}", buildPostBody(params));
}
// POST
HttpRequest request = HttpRequest.newBuilder()
.uri(new URI(revocationUrl))
.POST(HttpRequest.BodyPublishers.ofString(buildPostBody(params)))
.header("Content-Type", "application/x-www-form-urlencoded")
.build();
//TODO timeout from options
HttpResponse<String> response = HttpClient.newBuilder()
.build()
.send(request, BodyHandlers.ofString());
if (response.statusCode() != 200) {
logger.error(
"Token revocation failed: {}", response.statusCode());
}
}
catch (Exception e) {
throw new OIDCException(e);
}
}
private static String buildPostBody(Map<String, Object> params) {
if (params == null || params.isEmpty()) {
return "";
}
boolean first = true;
StringBuilder sb = new StringBuilder(params.size() * 3);
for (Map.Entry<String, Object> param : params.entrySet()) {
if (first) {
first = false;
}
else {
sb.append("&");
}
sb.append(
URLEncoder.encode(param.getKey().toString(), StandardCharsets.UTF_8));
sb.append("=");
if (param.getValue() != null) {
sb.append(
URLEncoder.encode(
param.getValue().toString(), StandardCharsets.UTF_8));
}
}
return sb.toString();
}
}
| 26.991228 | 99 | 0.69142 |
d939e96fd16dd26569ed5926ce0ac0344921485b | 1,016 | package com.berry.oss.dao.entity;
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableId;
import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.experimental.Accessors;
import java.io.Serializable;
import java.util.Date;
/**
* <p>
* 防盗链,http referer 白名单设置
* </p>
*
* @author HiCooper
* @since 2019-09-24
*/
@Data
@EqualsAndHashCode(callSuper = false)
@Accessors(chain = true)
public class RefererInfo implements Serializable {
private static final long serialVersionUID = 1L;
/**
* 主键id
*/
@TableId(value = "id", type = IdType.AUTO)
private Integer id;
/**
* bucket id
*/
private String bucketId;
/**
* 白名单
*/
private String whiteList;
/**
* 黑名单
*/
private String blackList;
/**
* 允许空 Referer
*/
private Boolean allowEmpty;
/**
* 创建时间
*/
private Date createTime;
/**
* 更新时间
*/
private Date updateTime;
}
| 15.875 | 52 | 0.622047 |
348649fc06acf1a625aab55bd2223f86079e5324 | 519 | package rip.orbit.hcteams.chat;
import rip.orbit.hcteams.HCF;
import rip.orbit.hcteams.chat.listeners.ChatListener;
import java.util.concurrent.atomic.AtomicInteger;
public class ChatHandler {
private static AtomicInteger publicMessagesSent = new AtomicInteger();
public ChatHandler() {
HCF.getInstance().getServer().getPluginManager().registerEvents(new ChatListener(), HCF.getInstance());
}
public static AtomicInteger getPublicMessagesSent() {
return publicMessagesSent;
}
} | 27.315789 | 111 | 0.751445 |
0bffde487921b171b34ca6d4f2f91227236591bb | 1,395 | package com.example.leeyonghun.x11test.restapi;
import com.example.leeyonghun.x11test.AppApplication;
import com.google.gson.JsonArray;
import com.google.gson.JsonObject;
import org.json.JSONObject;
import retrofit2.Call;
import retrofit2.http.Body;
import retrofit2.http.GET;
import retrofit2.http.Headers;
import retrofit2.http.POST;
import retrofit2.http.Path;
import retrofit2.http.Query;
public interface CoinAPI {
/*BitCoin*/
@GET("/api/addrs/{address}/utxo")
Call<JsonArray> btcUnspentOutput(@Path("address") String address);
@GET("/api/addr/{address}/balance")
Call<String> getBalanceBtc(@Path("address") String address);
/*BitcoinCash*/
@GET("/api/addrs/{address}/utxo")
Call<JsonArray> bchUnspentOutput(@Path("address") String address);
@GET("/api/addr/{address}/balance")
Call<String> getBalanceBch(@Path("address") String address);
/*Qtum*/
@GET("/outputs/unspent/{address}")
Call<JsonArray> qtumUnspentOutput(@Path("address") String address);
/*Litecoin*/
@GET("/api/addrs/{address}/utxo")
Call<JsonArray> liteUnspentOutput(@Path("address") String address);
@GET("/api/addr/{address}/balance")
Call<String> getBalanceLite(@Path("address") String address);
@Headers("Content-Type: application/json")
@POST("/api/tx/send")
Call<JsonObject> sendRawTransaction(@Body JsonObject body);
}
| 27.352941 | 71 | 0.712545 |
53f6fa824a61cd59edc5e9187c72989624d1f6e7 | 1,505 | package com.funnytoday.seoul.seoulgo.mainImageplay;
import android.app.Activity;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.view.Window;
import android.widget.TextView;
import com.funnytoday.seoul.seoulgo.R;
/**
* Created by 박상돈 on 2016-09-09.
*/
public class ImageOneTimeActivity extends Activity {
private String location;
private TextView place_one_time_explain;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
setContentView(R.layout.image_one_time);
setFinishOnTouchOutside(true);
location = getIntent().getStringExtra("LOCATION"); // 경복궁 , 창경궁, 덕수궁
place_one_time_explain = (TextView) findViewById(R.id.place_one_time_explain);
if (location.equals("경복궁")) {
place_one_time_explain.setText(getString(R.string.place_one_explain_time));
} else if (location.equals("창경궁")) {
place_one_time_explain.setText(getString(R.string.place_two_explain_time));
} else if (location.equals("덕수궁")) {
place_one_time_explain.setText(getString(R.string.place_three_explain_time));
} else if (location.equals("창덕궁")) {
place_one_time_explain.setText(getString(R.string.place_four_explain_time));
}
}
} | 29.509804 | 89 | 0.718937 |
ae5c4910ac3004d11fd6e85e4734994f46e64d19 | 2,198 | /*
* Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
* or more contributor license agreements. Licensed under the Elastic License
* 2.0 and the Server Side Public License, v 1; you may not use this file except
* in compliance with, at your election, the Elastic License 2.0 or the Server
* Side Public License, v 1.
*/
package org.elasticsearch.client.security;
import org.elasticsearch.client.Validatable;
import org.elasticsearch.client.ValidationException;
import org.elasticsearch.core.Nullable;
import java.util.Objects;
import java.util.Optional;
/**
* Request to retrieve information of service accounts
*/
public final class GetServiceAccountsRequest implements Validatable {
@Nullable
private final String namespace;
@Nullable
private final String serviceName;
public GetServiceAccountsRequest(@Nullable String namespace, @Nullable String serviceName) {
this.namespace = namespace;
this.serviceName = serviceName;
}
public GetServiceAccountsRequest(String namespace) {
this(namespace, null);
}
public GetServiceAccountsRequest() {
this(null, null);
}
public String getNamespace() {
return namespace;
}
public String getServiceName() {
return serviceName;
}
@Override
public Optional<ValidationException> validate() {
if (namespace == null && serviceName != null) {
final ValidationException validationException = new ValidationException();
validationException.addValidationError("cannot specify service-name without namespace");
return Optional.of(validationException);
} else {
return Optional.empty();
}
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
GetServiceAccountsRequest that = (GetServiceAccountsRequest) o;
return Objects.equals(namespace, that.namespace) && Objects.equals(serviceName, that.serviceName);
}
@Override
public int hashCode() {
return Objects.hash(namespace, serviceName);
}
}
| 30.109589 | 106 | 0.691538 |
036fec0f25029fa2d5a78904082b43106fabe036 | 6,840 | /**
* Copyright 2015 Palantir Technologies, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.palantir.giraffe.file.base;
import static com.google.common.base.Preconditions.checkNotNull;
import java.io.IOException;
import java.nio.channels.SeekableByteChannel;
import java.nio.file.AccessMode;
import java.nio.file.DirectoryStream;
import java.nio.file.DirectoryStream.Filter;
import java.nio.file.LinkOption;
import java.nio.file.OpenOption;
import java.nio.file.Path;
import java.nio.file.ProviderMismatchException;
import java.nio.file.attribute.BasicFileAttributes;
import java.nio.file.attribute.FileAttribute;
import java.nio.file.attribute.FileAttributeView;
import java.nio.file.spi.FileSystemProvider;
import java.util.Map;
import java.util.Set;
import com.palantir.giraffe.file.base.attribute.AnnotatedFileAttributeView;
import com.palantir.giraffe.file.base.attribute.DynamicAttributeAccessor;
import com.palantir.giraffe.file.base.attribute.FileAttributeViewFactory;
import com.palantir.giraffe.file.base.attribute.FileAttributeViewRegistry;
/**
* An abstract {@link FileSystemProvider} implementation that provides common
* functionality and additional structure for subclasses.
*
* @author bkeyes
*
* @param <P> the type of path used by the provider's file systems
*/
public abstract class BaseFileSystemProvider<P extends BasePath<P>> extends FileSystemProvider {
private final Class<P> pathClass;
protected BaseFileSystemProvider(Class<P> pathClass) {
this.pathClass = checkNotNull(pathClass, "pathClass must be non-null");
}
void fileSystemClosed(BaseFileSystem<P> fileSystem) {
// nothing to do here
}
public final boolean isCompatible(Path p) {
return pathClass.isInstance(p);
}
public final P checkPath(Path p) {
if (p == null) {
throw new NullPointerException("path cannot be null");
} else if (!pathClass.isInstance(p)) {
String type = p.getClass().getName();
throw new ProviderMismatchException("incompatible with path of type " + type);
} else {
return pathClass.cast(p);
}
}
@Override
public void delete(Path path) throws IOException {
P file = checkPath(path);
file.getFileSystem().delete(file);
}
@Override
public boolean isHidden(Path path) throws IOException {
P file = checkPath(path);
return file.getFileSystem().isHidden(file);
}
@Override
public void checkAccess(Path path, AccessMode... modes) throws IOException {
P file = checkPath(path);
file.getFileSystem().checkAccess(file, modes);
}
@Override
public boolean isSameFile(Path path, Path path2) throws IOException {
P file = checkPath(path);
if (file.equals(path2)) {
return true;
} else if (!isCompatible(path2)) {
return false;
} else {
return file.getFileSystem().isSameFile(file, checkPath(path2));
}
}
@Override
public <V extends FileAttributeView> V getFileAttributeView(Path path, Class<V> type,
LinkOption... options) {
FileAttributeViewFactory<?> factory = getViewRegistry(path).getByViewType(type);
return type.cast(factory.newView(path, options));
}
@Override
public SeekableByteChannel newByteChannel(Path path, Set<? extends OpenOption> options,
FileAttribute<?>... attrs) throws IOException {
P file = checkPath(path);
return file.getFileSystem().newByteChannel(file, options, attrs);
}
@Override
public DirectoryStream<Path> newDirectoryStream(Path dir, Filter<? super Path> filter)
throws IOException {
P path = checkPath(dir);
return path.getFileSystem().newDirectoryStream(path, filter);
}
@Override
public void createDirectory(Path dir, FileAttribute<?>... attrs) throws IOException {
P path = checkPath(dir);
path.getFileSystem().createDirectory(path, attrs);
}
@Override
public <A extends BasicFileAttributes> A readAttributes(Path path, Class<A> type,
LinkOption... options) throws IOException {
FileAttributeViewFactory<?> factory = getViewRegistry(path).getByAttributesType(type);
return type.cast(factory.newView(path, options).readAttributes());
}
@Override
public final Map<String, Object> readAttributes(Path path, String viewAndAttributes,
LinkOption... options) throws IOException {
String[] parts = parseAttributeSpec(viewAndAttributes);
FileAttributeViewFactory<?> factory = getViewRegistry(path).getByViewName(parts[0]);
AnnotatedFileAttributeView view = factory.newView(path, options);
return new DynamicAttributeAccessor(view).readAttributes(parts[1]);
}
@Override
public void setAttribute(Path path, String attribute, Object value, LinkOption... options)
throws IOException {
String[] parts = parseAttributeSpec(attribute);
FileAttributeViewFactory<?> factory = getViewRegistry(path).getByViewName(parts[0]);
AnnotatedFileAttributeView view = factory.newView(path, options);
new DynamicAttributeAccessor(view).setAttribute(parts[1], value);
}
private FileAttributeViewRegistry getViewRegistry(Path path) {
return checkPath(path).getFileSystem().fileAttributeViews();
}
/**
* Parses a {@code [view:]attributes} string into an two-element array. The first
* element is the view, or "basic" if the view is not included. The second
* element is the comma-separated attribute list.
*
* @throws IllegalArgumentException if the attributes list is empty
*/
private static String[] parseAttributeSpec(String viewAndAttributes) {
String view = "basic";
String attributes = viewAndAttributes;
int split = viewAndAttributes.indexOf(':');
if (split >= 0) {
view = viewAndAttributes.substring(0, split);
attributes = viewAndAttributes.substring(split + 1);
}
if (attributes.isEmpty()) {
throw new IllegalArgumentException("no attributes specified");
}
return new String[] { view, attributes };
}
}
| 36.774194 | 96 | 0.692982 |
311c1ae5a6bd92a8bfe8abb45ef5f8e3b1f5b7c0 | 1,598 | package com.jerusalem.goods.controller.web;
import com.jerusalem.goods.entity.CategoryEntity;
import com.jerusalem.goods.service.CategoryService;
import com.jerusalem.goods.vo.Category2Vo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import java.util.List;
import java.util.Map;
/****
* @Author: jerusalem
* @Description: IndexController
* 前端页面跳转控制器
* @Date 2020/5/28 13:52
*****/
@Controller
public class IndexController {
@Autowired
private CategoryService categoryService;
/***
* 跳转到首页
* @param model
* @return
*/
@GetMapping({"/","/index.html"})
public String indexPage(Model model){
//查出所有的一级分类
List<CategoryEntity> categoryList = categoryService.getCategoryLevelOne();
model.addAttribute("categorys",categoryList);
return "index";
}
/***
* 获取三级分类数据树(首页)
* @return
*/
@ResponseBody
@GetMapping("/index/category.json")
public Map<String, List<Category2Vo>> getCategoryJson(){
/**
* 调用相关方法
* getCategoryJsonWithSpringCache():整合使用 SpringCache
* getCategoryJson():特殊处理,整合各种高级锁
*/
Map<String, List<Category2Vo>> categoryMap = categoryService.getCategoryJsonWithSpringCache();
// Map<String, List<Category2Vo>> categoryMap = categoryService.getCategoryJson();
return categoryMap;
}
}
| 27.551724 | 102 | 0.694618 |
050084652bfab6d26a22e707823dce23a32904bf | 22,138 | package io.opensphere.core.appl.versions.controller;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URL;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.Objects;
import java.util.Properties;
import java.util.stream.Collectors;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.filefilter.TrueFileFilter;
import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;
import io.opensphere.core.Toolbox;
import io.opensphere.core.appl.versions.AutoUpdateToolbox;
import io.opensphere.core.appl.versions.AutoUpdateToolboxUtils;
import io.opensphere.core.appl.versions.DescriptorUtils;
import io.opensphere.core.appl.versions.FileDescriptor;
import io.opensphere.core.appl.versions.InstallDescriptor;
import io.opensphere.core.appl.versions.VersionComparator;
import io.opensphere.core.appl.versions.model.AutoUpdatePreferences;
import io.opensphere.core.appl.versions.view.AutoUpdateDialog;
import io.opensphere.core.util.Service;
import io.opensphere.core.util.io.StreamReader;
import io.opensphere.core.util.lang.StringUtilities;
import io.opensphere.core.util.lang.ThreadUtilities;
import io.opensphere.core.util.net.UrlUtilities;
import io.opensphere.core.util.swing.EventQueueUtilities;
import io.opensphere.core.util.taskactivity.CancellableTaskActivity;
import io.opensphere.core.util.taskactivity.TaskActivity;
/**
* The controller used to manage state in auto-update transactions.
*/
public class AutoUpdateController implements Service
{
/** The {@link Logger} instance used to capture output. */
private static final Logger LOG = Logger.getLogger(AutoUpdateController.class);
/** Number of times a file should try to be downloaded. */
private static final int DEFAULT_DOWNLOAD_ATTEMPTS = 2;
/** A comparator used to examine two versions. */
private static final VersionComparator VERSION_COMPARATOR = new VersionComparator();
/** The model in which preferences are stored. */
private AutoUpdatePreferences myModel;
/** The toolbox through which auto-update state is accessed. */
private AutoUpdateToolbox myAutoUpdateToolbox;
/** The toolbox through which auto-update state is accessed. */
private final Toolbox myToolbox;
/**
* Creates a new auto update controller, initialized with the supplied
* toolbox.
*
* @param toolbox the toolbox through which application state is accessed.
*/
public AutoUpdateController(Toolbox toolbox)
{
super();
myToolbox = toolbox;
}
/**
* {@inheritDoc}
*
* @see io.opensphere.core.util.Service#open()
*/
@Override
public void open()
{
myAutoUpdateToolbox = AutoUpdateToolboxUtils.getAutoUpdateToolboxToolbox(myToolbox);
myModel = myAutoUpdateToolbox.getPreferences();
Properties properties = loadLaunchConfiguration();
myModel.setNewestLocalVersion(properties.getProperty("newest.version"));
}
/**
* {@inheritDoc}
*
* @see io.opensphere.core.util.Service#close()
*/
@Override
public void close()
{
/* intentionally blank */
}
/**
* Checks the configured remote system for updates, and if a newer version
* is available, prompts the user to download and install the latest
* version.
*
* @param notifyUpToDate a flag used to allow the check to notify the user
* that the application is already up to date (true will notify,
* false will complete silently).
*/
public void checkForUpdates(boolean notifyUpToDate)
{
ThreadUtilities.runBackground(() ->
{
if (myModel.isAutoUpdateEnabled())
{
if (isNewVersionAvailable())
{
EventQueueUtilities.runOnEDT(() -> promptAndUpdate());
}
else if (notifyUpToDate)
{
EventQueueUtilities.runOnEDT(() ->
{
final JFrame parent = myToolbox.getUIRegistry().getMainFrameProvider().get();
JOptionPane.showMessageDialog(parent,
"The installed version of the application is the most current available!",
"Application up to date", JOptionPane.INFORMATION_MESSAGE);
});
}
}
});
}
/**
* Tests to determine if a newer version is available on the remote system.
*
* @return true if the remote system contains a version newer than the
* latest local version, false otherwise.
*/
private boolean isNewVersionAvailable()
{
String localNewestVersion = myModel.getNewestLocalVersion();
if (StringUtils.isNotBlank(localNewestVersion))
{
LOG.info("Newest installed version: " + localNewestVersion);
updateNewestRemoteVersion();
String remoteNewestVersion = myModel.getNewestRemoteVersion();
return VERSION_COMPARATOR.compare(localNewestVersion, remoteNewestVersion) < 0;
}
LOG.warn("Unable to determine local version, skipping auto-update.");
return false;
}
/**
* Shows the update dialog.
*/
private void promptAndUpdate()
{
final JFrame parent = myToolbox.getUIRegistry().getMainFrameProvider().get();
LOG.info("Prompting the user to determine if a new version should be downloaded.");
String newestRemoteVersion = myModel.getNewestRemoteVersion();
if (AutoUpdateDialog.showConfirmDialog(myToolbox.getPreferencesRegistry(), parent, newestRemoteVersion) < 2)
{
LOG.info("Downloading new version.");
ThreadUtilities.runBackground(() ->
{
String updateUrlString = AutoUpdateUtils.getUrlString(myModel.getAutoUpdateProtocol(),
myModel.getAutoUpdateHostname(), myModel.getUpdateUrl() + "install_descriptor.json");
updateUrlString = AutoUpdateUtils.substituteUrl(updateUrlString, newestRemoteVersion);
URL updateURL = UrlUtilities.toURL(updateUrlString);
String installConfirmation = installUpdateFiles(updateURL)
? "Successfully installed version " + newestRemoteVersion
: "Failed to install version " + newestRemoteVersion;
LOG.info(installConfirmation);
});
}
}
/** Gets the new version from the server. */
private void updateNewestRemoteVersion()
{
String urlString = AutoUpdateUtils.getUrlString(myModel.getAutoUpdateProtocol(), myModel.getAutoUpdateHostname(),
myModel.getLatestVersionUrl());
LOG.info("Checking remote endpoint '" + urlString + "' for new version.");
URL newVersionURL = UrlUtilities.toURL(urlString);
try (InputStream result = AutoUpdateUtils.performRequest(newVersionURL, myToolbox))
{
if (result != null)
{
String version = new StreamReader(result).readStreamIntoString(StringUtilities.DEFAULT_CHARSET).trim();
LOG.info("Remote endpoint's newest version is '" + version + "'");
myModel.setNewestRemoteVersion(version);
}
else
{
LOG.error("Unable to perform request for remote version.");
}
}
catch (IOException e)
{
LOG.error("Unable to perform request for remote version.", e);
}
}
/**
* Copies or downloads all files listed in the update's install descriptor.
*
* @param installDescriptorURL the URL of the install descriptor for the
* update
* @return boolean value if all files were installed properly
*/
public boolean installUpdateFiles(URL installDescriptorURL)
{
InstallDescriptor installDescriptor = AutoUpdateUtils.getUpdateInstallDescriptor(installDescriptorURL);
try (CancellableTaskActivity ta = CancellableTaskActivity.createActive("Downloading update"))
{
String installVersion = myModel.getNewestRemoteVersion();
String installDescriptorPath = Paths
.get(myModel.getInstallDirectory().getAbsolutePath(), installVersion, "install_descriptor.json").toString();
downloadUpdateFile(installDescriptorURL, installDescriptorPath);
InstallProgressTracker installTracker = new InstallProgressTracker();
LOG.info("Downloading / installing new version from remote server: " + installVersion);
myToolbox.getUIRegistry().getMenuBarRegistry().addTaskActivity(ta);
// get the newest version files on the local system to copy files
// from
File previousVersionDirectory = new File(myModel.getInstallDirectory(), myModel.getNewestLocalVersion());
Collection<File> localFiles = FileUtils.listFiles(previousVersionDirectory, TrueFileFilter.TRUE, TrueFileFilter.TRUE);
double fileCount = installDescriptor.getFiles().size();
String updateUrlPrefix = AutoUpdateUtils.substituteUrl(AutoUpdateUtils.getUrlString(myModel.getAutoUpdateProtocol(),
myModel.getAutoUpdateHostname(), myModel.getUpdateUrl()), installVersion);
for (FileDescriptor fileDescriptor : installDescriptor.getFiles())
{
if (ta.isCancelled())
{
LOG.info("User cancelled download. Cleaning up.");
Path versionDirectory = Paths.get(myModel.getInstallDirectory().getAbsolutePath(), installVersion)
.normalize();
try
{
Files.walk(versionDirectory).sorted(Comparator.reverseOrder()).map(Path::toFile).peek(LOG::debug)
.forEach(File::delete);
}
catch (IOException e)
{
LOG.error("Unable to cleanup '" + versionDirectory.toString() + "' after requested cancel", e);
}
return false;
}
String newFilePath = createNewFilePath(fileDescriptor, installVersion);
File previousVersionFile = DescriptorUtils.getMatchForFile(fileDescriptor, localFiles);
if (previousVersionFile != null)
{
copyFile(installTracker, previousVersionFile, fileDescriptor, newFilePath);
}
else
{
downloadFile(installTracker, updateUrlPrefix, fileDescriptor, newFilePath);
}
FileUtils.getFile(newFilePath).setExecutable(fileDescriptor.getExecutable(), false);
ta.setProgress(installTracker.getFilesRetrieved() / fileCount);
}
EventQueueUtilities.invokeLater(() ->
{
LOG.info("Updating newest version property to " + installVersion);
updateProperty("newest.version", installVersion);
showChooseVersionDialog();
});
ta.setComplete(true);
LOG.info("Downloaded " + installTracker.getBytesDownloaded() + " bytes");
LOG.info("Copied " + installTracker.getBytesCopied() + " bytes");
LOG.info("Retrieved " + installTracker.getFilesRetrieved() + " files");
}
return true;
}
/**
* Copies the named file from a previous installation to avoid downloading a
* new copy.
*
* @param installTracker the tracker in which progress is maintained.
* @param sourceFile the file to copy.
* @param fileDescriptor the file descriptor describing the target file.
* @param newFilePath the location to which the file will be copied.
*/
private void copyFile(InstallProgressTracker installTracker, File sourceFile, FileDescriptor fileDescriptor,
String newFilePath)
{
LOG.info("Copying " + fileDescriptor.getFileName());
try
{
installTracker.addToBytesCopied(FileUtils.sizeOf(sourceFile));
installTracker.incrementRetrievedFiles();
Files.copy(sourceFile.toPath(), Paths.get(newFilePath), StandardCopyOption.REPLACE_EXISTING);
}
catch (IOException e)
{
LOG.error("Failed to copy " + fileDescriptor.getFileName() + " from " + sourceFile.getParent(), e);
}
}
/**
* Copies the named file from a URL to the supplied path.
*
* @param installTracker the tracker in which progress is maintained.
* @param urlPrefix the prefix to use to construct file URLs for retrieval.
* @param fileDescriptor the file descriptor describing the target file.
* @param newFilePath the location to which the file will be copied.
*/
private void downloadFile(InstallProgressTracker installTracker, String urlPrefix, FileDescriptor fileDescriptor,
String newFilePath)
{
LOG.info("Downloading " + fileDescriptor.getFileName());
int downloadAttempts = 0;
String downloadFileChecksum = null;
do
{
try (TaskActivity ta = TaskActivity.createActive("Downloading " + fileDescriptor.getFileName()))
{
myToolbox.getUIRegistry().getMenuBarRegistry().addTaskActivity(ta);
URL downloadUrl = getDownloadUrl(urlPrefix, fileDescriptor);
downloadUpdateFile(downloadUrl, newFilePath);
downloadAttempts++;
installTracker.incrementRetrievedFiles();
File file = new File(newFilePath);
installTracker.addToBytesDownloaded(FileUtils.sizeOf(file));
downloadFileChecksum = DescriptorUtils.createChecksum(file);
ta.setComplete(true);
}
}
while (!fileDescriptor.getChecksum().equals(downloadFileChecksum) && downloadAttempts <= DEFAULT_DOWNLOAD_ATTEMPTS);
}
/**
* Retrieves the file from the supplied URL, and saves it to the supplied
* path.
*
* @param fileUrl the URL of the file to retrieve.
* @param fileTargetPath the path to which to save the file.
*/
public void downloadUpdateFile(URL fileUrl, String fileTargetPath)
{
try (InputStream responseStream = AutoUpdateUtils.performRequest(fileUrl, myToolbox))
{
if (responseStream != null)
{
FileUtils.copyInputStreamToFile(responseStream, new File(fileTargetPath));
}
else
{
LOG.warn("Failed to get file from " + fileUrl.toString());
}
}
catch (IOException e)
{
LOG.error("Failed to get file from " + fileUrl.toString(), e);
}
}
/**
* Creates the target file path string for an update file.
*
* @param fileDescriptor the descriptor for an update file
* @param version the version in which the file is / will be located.
* @return the target file path string
*/
private String createNewFilePath(FileDescriptor fileDescriptor, String version)
{
// create the new version directory in the OpenSphere folder
String newVersionPath = new File(myModel.getInstallDirectory(), version).toString();
FileUtils.getFile(newVersionPath, "plugins").mkdirs();
String newFilePath = Paths.get(newVersionPath, fileDescriptor.getTargetPath(), fileDescriptor.getFileName()).toString();
if (!fileDescriptor.getTargetPath().equals("."))
{
// make any necessary folders in the new version folder
FileUtils.getFile(newVersionPath, fileDescriptor.getTargetPath()).mkdirs();
}
return newFilePath;
}
/**
* Shows the dialog for the user to choose a preferred version of the
* application.
*/
private void showChooseVersionDialog()
{
String newestRemoteVersion = myModel.getNewestRemoteVersion();
String chooseVersionMessage = "Version " + newestRemoteVersion + " has finished downloading." + System.lineSeparator()
+ "The new version will be used the next time the application is launched." + System.lineSeparator()
+ "Would you like to restart with the new version now?";
updateProperty("preferred.version", newestRemoteVersion);
int response = JOptionPane.showConfirmDialog(myToolbox.getUIRegistry().getMainFrameProvider().get(), chooseVersionMessage,
"Would you like to restart?", JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE);
if (response == JOptionPane.YES_OPTION)
{
myToolbox.getSystemToolbox().requestRestart();
}
}
/**
* Updates a configuration property.
*
* @param propertyKey the property key
* @param propertyValue the property value
*/
private void updateProperty(String propertyKey, String propertyValue)
{
if (!propertyValue.isEmpty())
{
Properties loadLaunchConfiguration = loadLaunchConfiguration();
loadLaunchConfiguration.setProperty(propertyKey, propertyValue);
storeLaunchConfiguration(loadLaunchConfiguration);
}
}
/**
* Constructs a download URL to access the file described by the supplied
* descriptor.
*
* @param updateUrlPrefix the URL prefix to apply to the file for generating
* the download URL.
* @param fileDescriptor the descriptor of the file to download.
* @return a URL to access the described file.
*/
private URL getDownloadUrl(String updateUrlPrefix, FileDescriptor fileDescriptor)
{
String remoteFilePath = fileDescriptor.getTargetPath() + "/" + fileDescriptor.getFileName();
if (remoteFilePath.startsWith("."))
{
remoteFilePath = remoteFilePath.substring(1);
}
if (remoteFilePath.startsWith("/"))
{
remoteFilePath = remoteFilePath.substring(1);
}
if (!myModel.getUpdateUrl().endsWith("/"))
{
remoteFilePath = "/" + remoteFilePath;
}
return UrlUtilities.toURL(updateUrlPrefix + remoteFilePath);
}
/**
* Gets the path of the launch configuration file.
*
* @return the absolute path of the launch configuration file.
*/
private String getLaunchConfigurationFilePath()
{
return Paths.get(myModel.getInstallDirectory().getAbsolutePath(), myModel.getLaunchConfigurationFilename())
.toAbsolutePath().toString();
}
/**
* Loads the launch configuration properties from the configured file. If
* the file cannot be found, an empty container is returned.
*
* @return the {@link Properties} object containing the launch configuration
* read from the filesystem.
*/
public Properties loadLaunchConfiguration()
{
Properties properties = new Properties();
String launchConfigurationFilePath = getLaunchConfigurationFilePath();
try (InputStream input = new FileInputStream(launchConfigurationFilePath))
{
properties.load(input);
}
catch (IOException e)
{
LOG.error("There was a problem loading properties from '" + launchConfigurationFilePath + "'", e);
}
return properties;
}
/**
* Stores the current launch configuration to the configured file.
*
* @param properties the properties to store into the launch configuration.
*/
public void storeLaunchConfiguration(Properties properties)
{
String launchConfigurationFilePath = getLaunchConfigurationFilePath();
try (OutputStream output = new FileOutputStream(launchConfigurationFilePath))
{
properties.store(output, "config settings");
}
catch (IOException e)
{
LOG.error("There was a problem storing properties to '" + launchConfigurationFilePath + "'", e);
}
}
/**
* Gets the versions which are available to the user in their install
* directory.
*
* @return the version options
*/
public List<String> getVersionOptions()
{
LOG.info("Searching " + myModel.getInstallDirectory() + " for versions of the application");
Path installDirectory = myModel.getInstallDirectory().toPath();
try
{
return Files.walk(installDirectory).filter(t -> t.getFileName().toString().equals("install_descriptor.json"))
.map(Path::toUri).map(AutoUpdateUtils::toDescriptor).filter(Objects::nonNull).map(AutoUpdateUtils::toVersion)
.sorted(Comparator.reverseOrder()).collect(Collectors.toList());
}
catch (IOException e)
{
LOG.error("Unable to search directory '" + myModel.getInstallDirectory().toString() + "'", e);
return Collections.emptyList();
}
}
/**
* Deletes the version from the file system.
*
* @param versionDirectory the path of the version within the filesystem.
* @throws IOException if the folder cannot be deleted.
*/
public void deleteVersionFromFilesystem(Path versionDirectory) throws IOException
{
Files.walk(versionDirectory).sorted(Comparator.reverseOrder()).map(Path::toFile).peek(LOG::debug).forEach(File::delete);
}
}
| 39.888288 | 130 | 0.642922 |
cd8275b1b102ec9d0722caf38100a362204fe59f | 2,061 | package com.siziksu.marvel.common;
import android.content.Context;
import android.net.ConnectivityManager;
import android.net.Network;
import android.net.NetworkInfo;
import android.os.Build;
import com.siziksu.marvel.common.model.Connection;
public final class ConnectionManager {
private final Context context;
public ConnectionManager(Context context) {
this.context = context;
}
public Connection getConnection() {
ConnectivityManager connectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = null;
if (connectivityManager != null) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
Network[] networks = connectivityManager.getAllNetworks();
for (Network mNetwork : networks) {
networkInfo = connectivityManager.getNetworkInfo(mNetwork);
if (networkInfo.getState().equals(NetworkInfo.State.CONNECTED)) {
break;
}
}
} else {
NetworkInfo[] networkInfos = connectivityManager.getAllNetworkInfo();
if (networkInfos != null) {
for (NetworkInfo info : networkInfos) {
if (info.getState() == NetworkInfo.State.CONNECTED) {
networkInfo = info;
break;
}
}
}
}
}
if (networkInfo != null
&& networkInfo.getDetailedState() != NetworkInfo.DetailedState.DISCONNECTED
&& networkInfo.getState() != NetworkInfo.State.DISCONNECTED
&& networkInfo.getDetailedState() != NetworkInfo.DetailedState.CONNECTING
&& networkInfo.getState() != NetworkInfo.State.CONNECTING) {
return new Connection(true, networkInfo.getTypeName());
} else {
return new Connection(false, null);
}
}
}
| 38.166667 | 127 | 0.58952 |
893edc2235c0592127d4981e9c5f23950c7a12f1 | 1,425 | package criptografia;
public class CifraCesar implements Cifra{
private int n;
public CifraCesar(int n){
this.n = n;
}
@Override
public String cifrar(String mensagem) {
String output = "";
for (int i=0; i < mensagem.length(); i++) {
char c_atual = mensagem.charAt(i);
char c_cifrado;
if (c_atual >= 97 && c_atual <= 122) {
c_cifrado = (char) ((c_atual - 97 + this.n)%26 + 97);
}
else if (c_atual >= 65 && c_atual <= 90) {
c_cifrado = (char) ((c_atual - 65 + this.n)%26 + 65);
}
else {
c_cifrado = c_atual;
}
output += c_cifrado;
}
return output;
}
@Override
public String decifrar(String mensagem) {
String output = "";
for (int i=0; i < mensagem.length(); i++) {
char c_atual = mensagem.charAt(i);
char c_cifrado;
if (c_atual >= 97 && c_atual <= 122) {
c_cifrado = (char) ((c_atual - 97 + (26 - this.n))%26 + 97);
}
else if (c_atual >= 65 && c_atual <= 90) {
c_cifrado = (char) ((c_atual - 65 + (26 - this.n))%26 + 65);
}
else {
c_cifrado = c_atual;
}
output += c_cifrado;
}
return output;
}
}
| 26.388889 | 76 | 0.446316 |
b43a96d6fa529b26bf878ea39909838f6f559b5e | 396 | package com.ng.vis.component;
import com.artemis.Component;
/**
* (c) 2016 Abhishek Aryan
*
* @author Abhishek Aryan
* @since 12/30/2015.
*
*/
public class PhysicsOrigin extends Component {
public float originX, originY;
public PhysicsOrigin(){
}
public PhysicsOrigin(float originX,float originY){
this.originX=originX;
this.originY =originY;
}
}
| 15.230769 | 54 | 0.661616 |
54f9d36c766bcd12e101728436074c11ff60a422 | 67 | package com.zestic.authy.app.entity.user;
public class Access {
}
| 13.4 | 41 | 0.761194 |
c404954255db475f728233ca55a7871fe5267f4f | 727 | package grafioschtrader.entities;
import java.util.Date;
import javax.annotation.Generated;
import javax.persistence.metamodel.SingularAttribute;
import javax.persistence.metamodel.StaticMetamodel;
@Generated(value = "org.hibernate.jpamodelgen.JPAMetaModelEntityProcessor")
@StaticMetamodel(Auditable.class)
public abstract class Auditable_ {
public static volatile SingularAttribute<Auditable, Date> lastModifiedTime;
public static volatile SingularAttribute<Auditable, Date> creationTime;
public static volatile SingularAttribute<Auditable, Integer> createdBy;
public static volatile SingularAttribute<Auditable, Integer> lastModifiedBy;
public static volatile SingularAttribute<Auditable, Integer> version;
}
| 36.35 | 78 | 0.84044 |
96307c08e1b691d1d7c006a918fb48d93fba7987 | 4,446 | package com.example.neilyi.advancedhybridframework.hybride.imp;
import android.content.Intent;
import android.net.Uri;
import android.text.TextUtils;
import com.example.neilyi.advancedhybridframework.hybride.BridgeCallback;
import com.example.neilyi.advancedhybridframework.hybride.HybridHandler;
import com.example.neilyi.advancedhybridframework.hybride.utils.HybridConstans;
import com.example.neilyi.web.view.AdvancedWebView;
import com.example.neilyi.advancedhybridframework.base.WebBaseActivity;
import org.json.JSONObject;
import java.net.URISyntaxException;
/**
* Url类型Hybrid处理类
*
* Created by NeilYi on 2017/7/24.
*/
public class UrlTypeHandler implements HybridHandler {
@Override
public String getHandlerType() {
return HybridConstans.URL_TASK;
}
@Override
public AdvancedWebView getWebView() {
return null;
}
@Override
public boolean handerCallTask(WebBaseActivity activity, String actionStr, JSONObject jsonObject, AdvancedWebView webview) {
return false;
}
@Override
public boolean handerFetchTask(WebBaseActivity activity, String actionStr, JSONObject jsonObject, BridgeCallback callback) {
return false;
}
@Override
public boolean handerUrlTask(WebBaseActivity activity, String url) {
if (null == activity || activity.isFinishing() || TextUtils.isEmpty(url)) {
return false;
}
try {
if (url.startsWith("tel:")) {
Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
activity.startActivity(intent);
return true;
} else if (url.startsWith("smsto:")) {
Intent it = new Intent(Intent.ACTION_SENDTO, Uri.parse(url));
it.putExtra("sms_body", "");
activity.startActivity(it);
return true;
} else if (url.startsWith("mailto:")) {
Intent it = new Intent(Intent.ACTION_SENDTO, Uri.parse(url));
activity.startActivity(it);
return true;
} else if (url.indexOf("sms:") != -1) {
String strSMSTel = url.substring(url.indexOf("sms:") + 4);
Uri uriSMSTel = Uri.parse("smsto:" + strSMSTel);
Intent iSMS = new Intent(Intent.ACTION_SENDTO, uriSMSTel);
activity.startActivity(iSMS);
return true;
} else if (url.startsWith("mqqwpa:")) {
Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
activity.startActivity(intent);
return true;
} else if (url.startsWith("cmpay:")) {
Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
activity.startActivity(intent);
return true;
} else if (url.startsWith("lingxi:") || url.startsWith("migulive:")) {
Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
activity.startActivity(intent);
return true;
} else if (url.contains("weixin://wap/pay")) {
Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
activity.startActivity(intent);
return true;
} else if (url.startsWith("alipays://")) {
Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
activity.startActivity(intent);
return true;
} else if (url.startsWith("intent://")) {
Intent intent;
try {
intent = Intent.parseUri(url, Intent.URI_INTENT_SCHEME);
// forbid launching activities without BROWSABLE category
intent.addCategory("android.intent.category.BROWSABLE");
// forbid explicit call
intent.setComponent(null);
// forbid intent with selector intent
intent.setSelector(null);
// start the activity by the intent
activity.startActivityIfNeeded(intent, -1);
} catch (URISyntaxException exception) {
exception.printStackTrace();
}
return true;
}
} catch (RuntimeException e) {
e.printStackTrace();
}
return false;
}
}
| 39.345133 | 128 | 0.587494 |
554d80b14be73c3aa77701ae7305085f26aea9c5 | 12,428 | /*
* Copyright (c) 2008-2018, Hazelcast, Inc. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.hazelcast.client.replicatedmap;
import com.hazelcast.client.config.ClientConfig;
import com.hazelcast.client.config.ClientNetworkConfig;
import com.hazelcast.client.test.TestHazelcastFactory;
import com.hazelcast.core.HazelcastInstance;
import com.hazelcast.core.ReplicatedMap;
import com.hazelcast.nio.Address;
import com.hazelcast.test.AssertTask;
import com.hazelcast.test.HazelcastParallelClassRunner;
import com.hazelcast.test.HazelcastTestSupport;
import com.hazelcast.test.annotation.ParallelTest;
import com.hazelcast.test.annotation.QuickTest;
import org.junit.After;
import org.junit.Test;
import org.junit.experimental.categories.Category;
import org.junit.runner.RunWith;
import java.lang.reflect.Field;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
@RunWith(HazelcastParallelClassRunner.class)
@Category({QuickTest.class, ParallelTest.class})
public class DummyClientReplicatedMapTest extends HazelcastTestSupport {
private TestHazelcastFactory hazelcastFactory = new TestHazelcastFactory();
@After
public void cleanup() {
hazelcastFactory.terminateAll();
}
@Test
public void testGet() throws Exception {
HazelcastInstance instance1 = hazelcastFactory.newHazelcastInstance();
HazelcastInstance instance2 = hazelcastFactory.newHazelcastInstance();
HazelcastInstance client = hazelcastFactory.newHazelcastClient(getClientConfig(instance1));
ReplicatedMap<String, String> map = client.getReplicatedMap(randomMapName());
String key = generateKeyOwnedBy(instance2);
int partitionId = instance2.getPartitionService().getPartition(key).getPartitionId();
setPartitionId(map, partitionId);
String value = randomString();
map.put(key, value);
assertEquals(value, map.get(key));
}
@Test
public void testIsEmpty() throws Exception {
HazelcastInstance instance1 = hazelcastFactory.newHazelcastInstance();
HazelcastInstance instance2 = hazelcastFactory.newHazelcastInstance();
HazelcastInstance client = hazelcastFactory.newHazelcastClient(getClientConfig(instance1));
final ReplicatedMap<String, String> map = client.getReplicatedMap(randomMapName());
String key = generateKeyOwnedBy(instance2);
int partitionId = instance1.getPartitionService().getPartition(key).getPartitionId();
setPartitionId(map, partitionId);
String value = randomString();
map.put(key, value);
assertTrueEventually(new AssertTask() {
@Override
public void run() {
assertFalse(map.isEmpty());
}
});
}
@Test
public void testKeySet() throws Exception {
HazelcastInstance instance1 = hazelcastFactory.newHazelcastInstance();
HazelcastInstance instance2 = hazelcastFactory.newHazelcastInstance();
HazelcastInstance client = hazelcastFactory.newHazelcastClient(getClientConfig(instance1));
final ReplicatedMap<String, String> map = client.getReplicatedMap(randomMapName());
final String key = generateKeyOwnedBy(instance2);
final String value = randomString();
int partitionId = instance1.getPartitionService().getPartition(key).getPartitionId();
setPartitionId(map, partitionId);
map.put(key, value);
assertTrueEventually(new AssertTask() {
@Override
public void run() {
Collection<String> keySet = map.keySet();
assertEquals(1, keySet.size());
assertEquals(key, keySet.iterator().next());
}
});
}
@Test
public void testEntrySet() throws Exception {
HazelcastInstance instance1 = hazelcastFactory.newHazelcastInstance();
HazelcastInstance instance2 = hazelcastFactory.newHazelcastInstance();
HazelcastInstance client = hazelcastFactory.newHazelcastClient(getClientConfig(instance1));
final ReplicatedMap<String, String> map = client.getReplicatedMap(randomMapName());
final String key = generateKeyOwnedBy(instance2);
final String value = randomString();
int partitionId = instance1.getPartitionService().getPartition(key).getPartitionId();
setPartitionId(map, partitionId);
map.put(key, value);
assertTrueEventually(new AssertTask() {
@Override
public void run() {
Set<Map.Entry<String, String>> entries = map.entrySet();
assertEquals(1, entries.size());
Map.Entry<String, String> entry = entries.iterator().next();
assertEquals(key, entry.getKey());
assertEquals(value, entry.getValue());
}
});
}
@Test
public void testValues() throws Exception {
HazelcastInstance instance1 = hazelcastFactory.newHazelcastInstance();
HazelcastInstance instance2 = hazelcastFactory.newHazelcastInstance();
HazelcastInstance client = hazelcastFactory.newHazelcastClient(getClientConfig(instance1));
final ReplicatedMap<String, String> map = client.getReplicatedMap(randomMapName());
final String key = generateKeyOwnedBy(instance2);
final String value = randomString();
int partitionId = instance1.getPartitionService().getPartition(key).getPartitionId();
setPartitionId(map, partitionId);
map.put(key, value);
assertTrueEventually(new AssertTask() {
@Override
public void run() {
Collection<String> values = map.values();
assertEquals(1, values.size());
assertEquals(value, values.iterator().next());
}
});
}
@Test
public void testContainsKey() throws Exception {
HazelcastInstance instance1 = hazelcastFactory.newHazelcastInstance();
HazelcastInstance instance2 = hazelcastFactory.newHazelcastInstance();
HazelcastInstance client = hazelcastFactory.newHazelcastClient(getClientConfig(instance1));
ReplicatedMap<String, String> map = client.getReplicatedMap(randomMapName());
final String key = generateKeyOwnedBy(instance2);
int partitionId = instance1.getPartitionService().getPartition(key).getPartitionId();
setPartitionId(map, partitionId);
String value = randomString();
map.put(key, value);
assertTrue(map.containsKey(key));
}
@Test
public void testContainsValue() throws Exception {
HazelcastInstance instance1 = hazelcastFactory.newHazelcastInstance();
HazelcastInstance instance2 = hazelcastFactory.newHazelcastInstance();
HazelcastInstance client = hazelcastFactory.newHazelcastClient(getClientConfig(instance1));
final ReplicatedMap<String, String> map = client.getReplicatedMap(randomMapName());
final String key = generateKeyOwnedBy(instance2);
int partitionId = instance1.getPartitionService().getPartition(key).getPartitionId();
setPartitionId(map, partitionId);
final String value = randomString();
map.put(key, value);
assertTrueEventually(new AssertTask() {
@Override
public void run() {
assertTrue(map.containsValue(value));
}
});
}
@Test
public void testSize() throws Exception {
HazelcastInstance instance1 = hazelcastFactory.newHazelcastInstance();
HazelcastInstance instance2 = hazelcastFactory.newHazelcastInstance();
HazelcastInstance client = hazelcastFactory.newHazelcastClient(getClientConfig(instance1));
final ReplicatedMap<String, String> map = client.getReplicatedMap(randomMapName());
String key = generateKeyOwnedBy(instance2);
int partitionId = instance1.getPartitionService().getPartition(key).getPartitionId();
setPartitionId(map, partitionId);
String value = randomString();
map.put(key, value);
assertTrueEventually(new AssertTask() {
@Override
public void run() {
assertEquals(1, map.size());
}
});
}
@Test
public void testClear() throws Exception {
HazelcastInstance instance1 = hazelcastFactory.newHazelcastInstance();
HazelcastInstance instance2 = hazelcastFactory.newHazelcastInstance();
HazelcastInstance client = hazelcastFactory.newHazelcastClient(getClientConfig(instance1));
final ReplicatedMap<String, String> map = client.getReplicatedMap(randomMapName());
String key = generateKeyOwnedBy(instance2);
int partitionId = instance1.getPartitionService().getPartition(key).getPartitionId();
setPartitionId(map, partitionId);
String value = randomString();
map.put(key, value);
map.clear();
assertTrueEventually(new AssertTask() {
@Override
public void run() {
assertEquals(0, map.size());
}
});
}
@Test
public void testRemove() throws Exception {
HazelcastInstance instance1 = hazelcastFactory.newHazelcastInstance();
HazelcastInstance instance2 = hazelcastFactory.newHazelcastInstance();
HazelcastInstance client = hazelcastFactory.newHazelcastClient(getClientConfig(instance1));
final ReplicatedMap<String, String> map = client.getReplicatedMap(randomMapName());
String key = generateKeyOwnedBy(instance2);
int partitionId = instance1.getPartitionService().getPartition(key).getPartitionId();
setPartitionId(map, partitionId);
String value = randomString();
map.put(key, value);
map.remove(key);
assertTrueEventually(new AssertTask() {
@Override
public void run() {
assertEquals(0, map.size());
}
});
}
@Test
public void testPutAll() throws Exception {
HazelcastInstance instance1 = hazelcastFactory.newHazelcastInstance();
HazelcastInstance instance2 = hazelcastFactory.newHazelcastInstance();
HazelcastInstance client = hazelcastFactory.newHazelcastClient(getClientConfig(instance1));
final ReplicatedMap<String, String> map = client.getReplicatedMap(randomMapName());
String key = generateKeyOwnedBy(instance2);
int partitionId = instance1.getPartitionService().getPartition(key).getPartitionId();
setPartitionId(map, partitionId);
String value = randomString();
HashMap<String, String> m = new HashMap<String, String>();
m.put(key, value);
map.putAll(m);
assertEquals(value, map.get(key));
}
private ClientConfig getClientConfig(HazelcastInstance instance) {
Address address = instance.getCluster().getLocalMember().getAddress();
String addressString = address.getHost() + ":" + address.getPort();
ClientConfig dummyClientConfig = new ClientConfig();
ClientNetworkConfig networkConfig = new ClientNetworkConfig();
networkConfig.setSmartRouting(false);
networkConfig.addAddress(addressString);
dummyClientConfig.setNetworkConfig(networkConfig);
return dummyClientConfig;
}
private void setPartitionId(ReplicatedMap<String, String> map, int partitionId) throws Exception {
Class<?> clazz = map.getClass();
Field targetPartitionId = clazz.getDeclaredField("targetPartitionId");
targetPartitionId.setAccessible(true);
targetPartitionId.setInt(map, partitionId);
}
}
| 40.482085 | 102 | 0.689572 |
6806b5a4d33b04e2b92ed9f51526ee678b82a872 | 406 | package br.com.zup.bootcamp.client.response;
public class AssociateWalletResponse {
private final String resultado;
private final String id;
public AssociateWalletResponse(String resultado, String id) {
this.resultado = resultado;
this.id = id;
}
public String getResultado() {
return resultado;
}
public String getId() {
return id;
}
}
| 19.333333 | 65 | 0.650246 |
0d3723330d8f469d42147417b401d478557a7adf | 1,666 | package com.social.goalapp.data.network.model;
/**
* Created by Aravindraj on 11/6/2017.
*/
import java.util.List;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
public class Commentt {
@SerializedName("id")
@Expose
private Integer id;
@SerializedName("blogid")
@Expose
private Integer blogid;
@SerializedName("comment")
@Expose
private String comment;
@SerializedName("commentlikes")
@Expose
private List<Commentlike> commentlikes = null;
@SerializedName("date_created")
@Expose
private String dateCreated;
@SerializedName("date_modified")
@Expose
private String dateModified;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public Integer getBlogid() {
return blogid;
}
public void setBlogid(Integer blogid) {
this.blogid = blogid;
}
public String getComment() {
return comment;
}
public void setComment(String comment) {
this.comment = comment;
}
public List<Commentlike> getCommentlikes() {
return commentlikes;
}
public void setCommentlikes(List<Commentlike> commentlikes) {
this.commentlikes = commentlikes;
}
public String getDateCreated() {
return dateCreated;
}
public void setDateCreated(String dateCreated) {
this.dateCreated = dateCreated;
}
public String getDateModified() {
return dateModified;
}
public void setDateModified(String dateModified) {
this.dateModified = dateModified;
}
} | 21.088608 | 65 | 0.651261 |
1168677373cacb8491621160b5c99293709e9db6 | 323 | /**
* Наблюдатель.
* <b>Тип: поведенческий </b>
* Определяет зависимость "один ко многим" между объектами так, что когда один объект меняет своё
* состояние, все зависимые объекты оповещаются и обновляются автоматически.
*
* @author Andrey Kharintsev on 10.01.2019
*/
package ru.ajana.work.pattern.behavior.observer; | 35.888889 | 97 | 0.755418 |
cea2df4b0eacaedfd8253c03d0c49caf63d1f767 | 43 | package ru.shemplo.infosearch.spellcheck;
| 21.5 | 42 | 0.837209 |
ff3b39efe7da930dc6c6a6b0002378473f7b4e19 | 6,404 | /*
* Copyright © 2017-2020 factcast.org
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.factcast.store.internal;
import static org.assertj.core.api.Assertions.*;
import static org.mockito.Mockito.*;
import java.util.Collection;
import java.util.Collections;
import java.util.Optional;
import java.util.UUID;
import java.util.concurrent.atomic.AtomicReference;
import java.util.function.Supplier;
import lombok.NonNull;
import lombok.val;
import org.factcast.core.Fact;
import org.factcast.core.snap.Snapshot;
import org.factcast.core.snap.SnapshotId;
import org.factcast.core.spec.FactSpec;
import org.factcast.core.store.FactStore;
import org.factcast.core.subscription.SubscriptionRequest;
import org.factcast.core.subscription.SubscriptionRequestTO;
import org.factcast.core.subscription.observer.FactObserver;
import org.factcast.store.internal.StoreMetrics.OP;
import org.factcast.store.internal.tail.PGTailIndexManager;
import org.factcast.store.test.AbstractFactStoreTest;
import org.factcast.store.test.IntegrationTest;
import org.junit.jupiter.api.*;
import org.junit.jupiter.api.extension.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.jdbc.Sql;
import org.springframework.test.context.jdbc.SqlConfig;
import org.springframework.test.context.junit.jupiter.SpringExtension;
@ContextConfiguration(classes = {PgTestConfiguration.class})
@Sql(scripts = "/test_schema.sql", config = @SqlConfig(separator = "#"))
@ExtendWith(SpringExtension.class)
@IntegrationTest
public class PgFactStoreTest extends AbstractFactStoreTest {
@Autowired FactStore fs;
@Autowired PgMetrics metrics;
@Autowired PGTailIndexManager tailManager;
@Override
protected FactStore createStoreToTest() {
return fs;
}
@Test
void testGetSnapshotMetered() {
Optional<Snapshot> snapshot = store.getSnapshot(SnapshotId.of("xxx", UUID.randomUUID()));
assertThat(snapshot).isEmpty();
verify(metrics).time(same(OP.GET_SNAPSHOT), any(Supplier.class));
}
@Test
void testClearSnapshotMetered() {
val id = SnapshotId.of("xxx", UUID.randomUUID());
store.clearSnapshot(id);
verify(metrics).time(same(OP.CLEAR_SNAPSHOT), any(Runnable.class));
}
@Test
void testSetSnapshotMetered() {
val id = SnapshotId.of("xxx", UUID.randomUUID());
val snap = new Snapshot(id, UUID.randomUUID(), "foo".getBytes(), false);
store.setSnapshot(snap);
verify(metrics).time(same(OP.SET_SNAPSHOT), any(Runnable.class));
}
@Nested
class FastForward {
@NonNull UUID id = UUID.randomUUID();
@NonNull UUID id2 = UUID.randomUUID();
AtomicReference<UUID> fwd = new AtomicReference<>();
@NonNull
FactObserver obs =
new FactObserver() {
@Override
public void onNext(@NonNull Fact element) {
System.out.println("onNext " + element);
}
@Override
public void onCatchup() {
System.out.println("onCatchup");
}
@Override
public void onFastForward(UUID factIdToFfwdTo) {
fwd.set(factIdToFfwdTo);
System.out.println("ffwd " + factIdToFfwdTo);
}
};
@NonNull Collection<FactSpec> spec = Collections.singletonList(FactSpec.ns("ns1"));
@BeforeEach
void setup() {
store.publish(
Collections.singletonList(Fact.builder().id(id).ns("ns1").buildWithoutPayload()));
// have some more facts in the database
store.publish(
Collections.singletonList(Fact.builder().ns("unrelated").buildWithoutPayload()));
// update the highwatermarks
tailManager.triggerTailCreation();
}
@Test
void testFfwdFromScratch() {
SubscriptionRequest scratch = SubscriptionRequest.catchup(spec).fromScratch();
store.subscribe(SubscriptionRequestTO.forFacts(scratch), obs).awaitCatchup();
// no ffwd because we found one.
assertThat(fwd.get()).isNull();
SubscriptionRequest tail = SubscriptionRequest.catchup(spec).from(id);
store.subscribe(SubscriptionRequestTO.forFacts(tail), obs).awaitCatchup();
// now, we expect a ffwd here
assertThat(fwd.get()).isNotNull();
}
@Test
void doesNotRewind() {
// now insert a fresh one
store.publish(
Collections.singletonList(Fact.builder().id(id2).ns("ns1").buildWithoutPayload()));
SubscriptionRequest newtail = SubscriptionRequest.catchup(spec).from(id);
store.subscribe(SubscriptionRequestTO.forFacts(newtail), obs).awaitCatchup();
// no ffwd because we got a new one (id2)
assertThat(fwd.get()).isNull();
////
SubscriptionRequest emptyTail = SubscriptionRequest.catchup(spec).from(id2);
store.subscribe(SubscriptionRequestTO.forFacts(emptyTail), obs).awaitCatchup();
// still no ffwd because the ffwd target is smaller than id2
assertThat(fwd.get()).isNull();
}
@Test
void movedTarget() {
spec = Collections.singletonList(FactSpec.ns("noneOfThese"));
SubscriptionRequest mt = SubscriptionRequest.catchup(spec).fromScratch();
store.subscribe(SubscriptionRequestTO.forFacts(mt), obs).awaitCatchup();
// ffwd expected
assertThat(fwd.get()).isNotNull();
UUID first = fwd.get();
// publish unrelated stuff and update ffwd target
store.publish(
Collections.singletonList(Fact.builder().ns("unrelated").buildWithoutPayload()));
tailManager.triggerTailCreation();
SubscriptionRequest further = SubscriptionRequest.catchup(spec).from(id2);
store.subscribe(SubscriptionRequestTO.forFacts(further), obs).awaitCatchup();
// now it should ffwd again to the last unrelated one
assertThat(fwd.get()).isNotNull().isNotEqualTo(first);
}
}
}
| 33.354167 | 93 | 0.711743 |
6f52b6310c19c7cc74d15186c08b3dad5e418bb2 | 15,592 | /*
* 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.brooklyn.entity.nosql.riak;
import java.util.Arrays;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import javax.annotation.Nullable;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.google.common.base.Function;
import com.google.common.base.Functions;
import com.google.common.base.Preconditions;
import com.google.common.net.HostAndPort;
import org.jclouds.net.domain.IpPermission;
import org.jclouds.net.domain.IpProtocol;
import org.apache.brooklyn.api.location.Location;
import org.apache.brooklyn.api.location.MachineProvisioningLocation;
import org.apache.brooklyn.api.sensor.AttributeSensor;
import org.apache.brooklyn.core.entity.Entities;
import org.apache.brooklyn.core.location.access.BrooklynAccessUtils;
import org.apache.brooklyn.core.location.cloud.CloudLocationConfig;
import org.apache.brooklyn.core.sensor.AttributeSensorAndConfigKey;
import org.apache.brooklyn.enricher.stock.Enrichers;
import org.apache.brooklyn.entity.software.base.SoftwareProcessImpl;
import org.apache.brooklyn.entity.webapp.WebAppServiceMethods;
import org.apache.brooklyn.feed.http.HttpFeed;
import org.apache.brooklyn.feed.http.HttpPollConfig;
import org.apache.brooklyn.feed.http.HttpValueFunctions;
import org.apache.brooklyn.location.jclouds.JcloudsMachineLocation;
import org.apache.brooklyn.location.jclouds.JcloudsSshMachineLocation;
import org.apache.brooklyn.location.jclouds.networking.JcloudsLocationSecurityGroupCustomizer;
import org.apache.brooklyn.util.collections.MutableList;
import org.apache.brooklyn.util.core.config.ConfigBag;
import org.apache.brooklyn.util.guava.Functionals;
import org.apache.brooklyn.util.net.Cidr;
import org.apache.brooklyn.util.time.Duration;
public class RiakNodeImpl extends SoftwareProcessImpl implements RiakNode {
private static final Logger LOG = LoggerFactory.getLogger(RiakNodeImpl.class);
private transient HttpFeed httpFeed;
@Override
public RiakNodeDriver getDriver() {
return (RiakNodeDriver) super.getDriver();
}
@Override
public Class<RiakNodeDriver> getDriverInterface() {
return RiakNodeDriver.class;
}
@Override
public void init() {
super.init();
// fail fast if config files not avail
Entities.getRequiredUrlConfig(this, RIAK_VM_ARGS_TEMPLATE_URL);
Entities.getRequiredUrlConfig(this, RIAK_APP_CONFIG_TEMPLATE_URL);
Integer defaultMaxOpenFiles = RIAK_MAX_OPEN_FILES.getDefaultValue();
Integer maxOpenFiles = getConfig(RiakNode.RIAK_MAX_OPEN_FILES);
Preconditions.checkArgument(maxOpenFiles >= defaultMaxOpenFiles , "Specified number of open files : %s : is less than the required minimum",
maxOpenFiles, defaultMaxOpenFiles);
}
@SuppressWarnings("rawtypes")
public boolean isPackageDownloadUrlProvided() {
AttributeSensorAndConfigKey[] downloadProperties = { DOWNLOAD_URL_RHEL_CENTOS, DOWNLOAD_URL_UBUNTU, DOWNLOAD_URL_DEBIAN };
for (AttributeSensorAndConfigKey property : downloadProperties) {
if (!((ConfigurationSupportInternal) config()).getRaw(property).isAbsent()) {
return true;
}
}
return false;
}
@Override
protected Map<String, Object> obtainProvisioningFlags(@SuppressWarnings("rawtypes") MachineProvisioningLocation location) {
ConfigBag result = ConfigBag.newInstance(super.obtainProvisioningFlags(location));
result.configure(CloudLocationConfig.OS_64_BIT, true);
return result.getAllConfig();
}
@Override
protected Collection<Integer> getRequiredOpenPorts() {
Integer erlangRangeStart = config().get(ERLANG_PORT_RANGE_START);
Integer erlangRangeEnd = config().get(ERLANG_PORT_RANGE_END);
sensors().set(ERLANG_PORT_RANGE_START, erlangRangeStart);
sensors().set(ERLANG_PORT_RANGE_END, erlangRangeEnd);
return super.getRequiredOpenPorts();
}
// Called after machine is provisioned, but before the driver tries to install Riak
@Override
protected void preStart() {
super.preStart();
boolean configureInternalNetworking = Boolean.TRUE.equals(config().get(CONFIGURE_INTERNAL_NETWORKING));
if (configureInternalNetworking) {
configureInternalNetworking();
}
}
private void configureInternalNetworking() {
Location location = getDriver().getLocation();
if (!(location instanceof JcloudsSshMachineLocation)) {
LOG.info("Not running in a JcloudsSshMachineLocation, not adding IP permissions to {}", this);
return;
}
JcloudsMachineLocation machine = (JcloudsMachineLocation) location;
JcloudsLocationSecurityGroupCustomizer customizer = JcloudsLocationSecurityGroupCustomizer.getInstance(getApplicationId());
String cidr = Cidr.UNIVERSAL.toString(); // TODO configure with a more restrictive CIDR
Collection<IpPermission> permissions = MutableList.<IpPermission>builder()
.add(IpPermission.builder()
.ipProtocol(IpProtocol.TCP)
.fromPort(sensors().get(ERLANG_PORT_RANGE_START))
.toPort(sensors().get(ERLANG_PORT_RANGE_END))
.cidrBlock(cidr)
.build())
.add(IpPermission.builder()
.ipProtocol(IpProtocol.TCP)
.fromPort(config().get(HANDOFF_LISTENER_PORT))
.toPort(config().get(HANDOFF_LISTENER_PORT))
.cidrBlock(cidr)
.build())
.add(IpPermission.builder()
.ipProtocol(IpProtocol.TCP)
.fromPort(config().get(EPMD_LISTENER_PORT))
.toPort(config().get(EPMD_LISTENER_PORT))
.cidrBlock(cidr)
.build())
.build();
LOG.debug("Applying custom security groups to {}: {}", machine, permissions);
customizer.addPermissionsToLocation(machine, permissions);
}
@Override
public void connectSensors() {
super.connectSensors();
connectServiceUpIsRunning();
HostAndPort accessible = BrooklynAccessUtils.getBrooklynAccessibleAddress(this, getRiakWebPort());
if (isHttpMonitoringEnabled()) {
HttpFeed.Builder httpFeedBuilder = HttpFeed.builder()
.entity(this)
.period(500, TimeUnit.MILLISECONDS)
.baseUri(String.format("http://%s/stats", accessible.toString()))
.poll(new HttpPollConfig<Integer>(NODE_GETS)
.onSuccess(HttpValueFunctions.jsonContents("node_gets", Integer.class))
.onFailureOrException(Functions.constant(-1)))
.poll(new HttpPollConfig<Integer>(NODE_GETS_TOTAL)
.onSuccess(HttpValueFunctions.jsonContents("node_gets_total", Integer.class))
.onFailureOrException(Functions.constant(-1)))
.poll(new HttpPollConfig<Integer>(NODE_PUTS)
.onSuccess(HttpValueFunctions.jsonContents("node_puts", Integer.class))
.onFailureOrException(Functions.constant(-1)))
.poll(new HttpPollConfig<Integer>(NODE_PUTS_TOTAL)
.onSuccess(HttpValueFunctions.jsonContents("node_puts_total", Integer.class))
.onFailureOrException(Functions.constant(-1)))
.poll(new HttpPollConfig<Integer>(VNODE_GETS)
.onSuccess(HttpValueFunctions.jsonContents("vnode_gets", Integer.class))
.onFailureOrException(Functions.constant(-1)))
.poll(new HttpPollConfig<Integer>(VNODE_GETS_TOTAL)
.onSuccess(HttpValueFunctions.jsonContents("vnode_gets_total", Integer.class))
.onFailureOrException(Functions.constant(-1)))
.poll(new HttpPollConfig<Integer>(VNODE_PUTS)
.onSuccess(HttpValueFunctions.jsonContents("vnode_puts", Integer.class))
.onFailureOrException(Functions.constant(-1)))
.poll(new HttpPollConfig<Integer>(VNODE_PUTS_TOTAL)
.onSuccess(HttpValueFunctions.jsonContents("vnode_puts_total", Integer.class))
.onFailureOrException(Functions.constant(-1)))
.poll(new HttpPollConfig<Integer>(READ_REPAIRS_TOTAL)
.onSuccess(HttpValueFunctions.jsonContents("read_repairs_total", Integer.class))
.onFailureOrException(Functions.constant(-1)))
.poll(new HttpPollConfig<Integer>(COORD_REDIRS_TOTAL)
.onSuccess(HttpValueFunctions.jsonContents("coord_redirs_total", Integer.class))
.onFailureOrException(Functions.constant(-1)))
.poll(new HttpPollConfig<Integer>(MEMORY_PROCESSES_USED)
.onSuccess(HttpValueFunctions.jsonContents("memory_processes_used", Integer.class))
.onFailureOrException(Functions.constant(-1)))
.poll(new HttpPollConfig<Integer>(SYS_PROCESS_COUNT)
.onSuccess(HttpValueFunctions.jsonContents("sys_process_count", Integer.class))
.onFailureOrException(Functions.constant(-1)))
.poll(new HttpPollConfig<Integer>(PBC_CONNECTS)
.onSuccess(HttpValueFunctions.jsonContents("pbc_connects", Integer.class))
.onFailureOrException(Functions.constant(-1)))
.poll(new HttpPollConfig<Integer>(PBC_ACTIVE)
.onSuccess(HttpValueFunctions.jsonContents("pbc_active", Integer.class))
.onFailureOrException(Functions.constant(-1)))
.poll(new HttpPollConfig<List<String>>(RING_MEMBERS)
.onSuccess(Functionals.chain(
HttpValueFunctions.jsonContents("ring_members", String[].class),
new Function<String[], List<String>>() {
@Nullable
@Override
public List<String> apply(@Nullable String[] strings) {
return Arrays.asList(strings);
}
}
))
.onFailureOrException(Functions.constant(Arrays.asList(new String[0]))));
for (AttributeSensor<Integer> sensor : ONE_MINUTE_SENSORS) {
httpFeedBuilder.poll(new HttpPollConfig<Integer>(sensor)
.period(Duration.ONE_MINUTE)
.onSuccess(HttpValueFunctions.jsonContents(sensor.getName().substring(5), Integer.class))
.onFailureOrException(Functions.constant(-1)));
}
httpFeed = httpFeedBuilder.build();
}
enrichers().add(Enrichers.builder().combining(NODE_GETS, NODE_PUTS).computingSum().publishing(NODE_OPS).build());
enrichers().add(Enrichers.builder().combining(NODE_GETS_TOTAL, NODE_PUTS_TOTAL).computingSum().publishing(NODE_OPS_TOTAL).build());
WebAppServiceMethods.connectWebAppServerPolicies(this);
}
@Override
public void disconnectSensors() {
super.disconnectSensors();
if (httpFeed != null) {
httpFeed.stop();
}
disconnectServiceUpIsRunning();
}
@Override
public void joinCluster(String nodeName) {
getDriver().joinCluster(nodeName);
}
@Override
public void leaveCluster() {
getDriver().leaveCluster();
}
@Override
public void removeNode(String nodeName) {
getDriver().removeNode(nodeName);
}
@Override
public void bucketTypeCreate(String bucketTypeName, String bucketTypeProperties) {
getDriver().bucketTypeCreate(bucketTypeName, bucketTypeProperties);
}
@Override
public List<String> bucketTypeList() {
return getDriver().bucketTypeList();
}
@Override
public List<String> bucketTypeStatus(String bucketTypeName) {
return getDriver().bucketTypeStatus(bucketTypeName);
}
@Override
public void bucketTypeUpdate(String bucketTypeName, String bucketTypeProperties) {
getDriver().bucketTypeUpdate(bucketTypeName, bucketTypeProperties);
}
@Override
public void bucketTypeActivate(String bucketTypeName) {
getDriver().bucketTypeActivate(bucketTypeName);
}
@Override
public void recoverFailedNode(String nodeName) {
getDriver().recoverFailedNode(nodeName);
}
protected boolean isHttpMonitoringEnabled() {
return Boolean.TRUE.equals(getConfig(USE_HTTP_MONITORING));
}
@Override
public Integer getRiakWebPort() {
return getAttribute(RiakNode.RIAK_WEB_PORT);
}
@Override
public Integer getRiakPbPort() {
return getAttribute(RiakNode.RIAK_PB_PORT);
}
@Override
public Integer getHandoffListenerPort() {
return getConfig(RiakNode.HANDOFF_LISTENER_PORT);
}
@Override
public Integer getEpmdListenerPort() {
return getConfig(RiakNode.EPMD_LISTENER_PORT);
}
@Override
public Integer getErlangPortRangeStart() {
return getAttribute(RiakNode.ERLANG_PORT_RANGE_START);
}
@Override
public Integer getErlangPortRangeEnd() {
return getAttribute(RiakNode.ERLANG_PORT_RANGE_END);
}
@Override
public Boolean isSearchEnabled() {
return getConfig(RiakNode.SEARCH_ENABLED);
}
@Override
public Integer getSearchSolrPort() {
return getConfig(RiakNode.SEARCH_SOLR_PORT);
}
@Override
public Integer getSearchSolrJmxPort() {
return getConfig(RiakNode.SEARCH_SOLR_JMX_PORT);
}
@Override
public String getMajorVersion() {
return getFullVersion().substring(0, 3);
}
@Override
public String getFullVersion() {
return getConfig(RiakNode.SUGGESTED_VERSION);
}
@Override
public String getOsMajorVersion() {
return getDriver().getOsMajorVersion();
}
}
| 42.835165 | 148 | 0.648409 |
ec35d56ad89f725881b5425926a0857308e54dff | 610 | package sgf.gateway.model.metadata.activities.modeling;
import org.junit.Test;
import sgf.gateway.model.ModelEqualsMethodTest;
import sgf.gateway.model.metadata.Taxonomy;
import sgf.gateway.model.metadata.TopicImpl;
public class TopicImplEqualsEqualsTest extends ModelEqualsMethodTest {
public Object createObjectUnderTest() {
return new TopicImpl();
}
@Test
public void testName() {
testEqualContractForAttribute("name", "walter", "hugo");
}
@Test
public void testType() {
testEqualContractForAttribute("type", Taxonomy.GCMD, Taxonomy.ISO);
}
}
| 22.592593 | 75 | 0.722951 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.