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
|
---|---|---|---|---|---|
4203554d4942c93a7e69d69f8b02762f070d0275 | 1,962 | package de.spreclib.api.main;
import de.spreclib.model.longtermstorage.enums.LongTermStorageTemperature;
/**
* LongTermStorageTemperatureOption
*
* <p>To obtain the name of the ListOption e.g. for usage in GUIs use getStringRepresentation()
*
* @author Christopher Meyer
* @version 1.0
*/
public final class LongTermStorageTemperatureOption extends AbstractListOption {
private final LongTermStorageTemperature longTermStorageTemperature;
LongTermStorageTemperatureOption(LongTermStorageTemperature longTermStorageTemperature) {
this.longTermStorageTemperature = longTermStorageTemperature;
}
@Override
public String getStringRepresentation() {
return NAMES_DEFAULT.getString(this.longTermStorageTemperature.name());
}
@Override
LongTermStorageTemperature getContainedObject() {
return this.longTermStorageTemperature;
}
boolean hasTemperature(float temperatureCelsius) {
if (this.longTermStorageTemperature.hasValue(temperatureCelsius)) {
return true;
} else {
return false;
}
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result =
prime * result
+ ((longTermStorageTemperature == null) ? 0 : longTermStorageTemperature.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
LongTermStorageTemperatureOption other = (LongTermStorageTemperatureOption) obj;
if (longTermStorageTemperature != other.longTermStorageTemperature) {
return false;
}
return true;
}
@Override
public String toString() {
return "LongTermStorageTemperatureOption [longTermStorageTemperature="
+ longTermStorageTemperature
+ "]";
}
}
| 26.513514 | 98 | 0.685525 |
76d6d6bf6ad4fa96203508d34a9c5c523afe5bbf | 810 | package com.xu.dao;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.FileSystemXmlApplicationContext;
import org.springframework.jdbc.core.JdbcTemplate;
public class MyMain {
public static void main(String[] args) {
// TODO Auto-generated method stub
ApplicationContext ac = new FileSystemXmlApplicationContext("file:/Users/xuenhua/Documents/workspace/hello_gradle/src/main/resources/jdbc.xml");
//new ClassPathXmlApplicationContext("jdbc.xml");
//StudentManager sm= StudentManager.getInstance();
StudentManager sm2=(StudentManager) ac.getBean("studentManager");
JdbcTemplate j= sm2.getJdbcTemplate();
Student s=new Student("lisi",28,"119");
s.setJDBC(j);
s.addStudent(s);
s.getStudents();
}
}
| 31.153846 | 147 | 0.740741 |
647f8175474418e3af43467fcdc725498e3e7311 | 1,349 | package com.github.signer4j.gui.alert;
import javax.swing.JDialog;
import javax.swing.JOptionPane;
import com.github.signer4j.gui.utils.Images;
import com.github.signer4j.imp.Config;
public final class TokenLockedAlert {
private static final String MESSAGE_FORMAT = "Infelizmente seu dispositivo encontra-se BLOQUEADO.\n\n"
+ "A única forma de desbloqueá-lo é fazendo uso da sua senha de administração,\n"
+ "também conhecida como PUK.\n\n"
+ "Se você desconhece sua senha PUK, seu certificado foi perdido para sempre\n"
+ "e um novo certificado deverá ser providenciado.";
private static final String[] OPTIONS = {"ENTENDI"};
public static boolean display() {
return new TokenLockedAlert().show();
}
private final JOptionPane jop;
private TokenLockedAlert() {
jop = new JOptionPane(
MESSAGE_FORMAT,
JOptionPane.INFORMATION_MESSAGE,
JOptionPane.OK_OPTION,
Images.LOCK.asIcon(),
OPTIONS,
OPTIONS[0]
);
}
private boolean show() {
JDialog dialog = jop.createDialog("Dispositivo bloqueado");
dialog.setAlwaysOnTop(true);
dialog.setModal(true);
dialog.setIconImage(Config.getIcon());
dialog.setVisible(true);
dialog.dispose();
Object selectedValue = jop.getValue();
return OPTIONS[0].equals(selectedValue);
}
}
| 28.702128 | 104 | 0.700519 |
8417c2b17282864f8ff36bba6889457ff165ec21 | 3,039 | package com.github.pmoerenhout.atcommander.module._3gpp.commands;
import com.github.pmoerenhout.atcommander.AtCommander;
import com.github.pmoerenhout.atcommander.Command;
import com.github.pmoerenhout.atcommander.api.SerialException;
import com.github.pmoerenhout.atcommander.basic.commands.BaseCommand;
import com.github.pmoerenhout.atcommander.basic.commands.BaseResponse;
import com.github.pmoerenhout.atcommander.basic.commands.EmptyResponse;
import com.github.pmoerenhout.atcommander.basic.exceptions.ResponseException;
import com.github.pmoerenhout.atcommander.basic.exceptions.TimeoutException;
import com.github.pmoerenhout.atcommander.module.v250.commands.TestResponse;
public class GprsMobileStationClassCommand extends BaseCommand implements Command<BaseResponse> {
public static final String CLASS_A = "A";
public static final String CLASS_B = "B";
public static final String CLASS_C = "C";
public static final String CLASS_C_GPRS = "CG";
public static final String CLASS_C_GSM = "CC";
private static final String COMMAND_CGCLASS = "+CGCLASS";
private String clazz;
public GprsMobileStationClassCommand(final AtCommander atCommander) {
super(COMMAND_CGCLASS, atCommander);
}
public GprsMobileStationClassCommand(final AtCommander atCommander, final String clazz) {
super(COMMAND_CGCLASS, atCommander);
this.clazz = clazz;
if (isInvalidGprsMobileStationClass(clazz)) {
throw new IllegalArgumentException("Invalid GPRS Mobile Station Class: " + clazz);
}
}
public EmptyResponse set() throws SerialException, TimeoutException, ResponseException {
available.acquireUninterruptibly();
try {
final StringBuilder sb = new StringBuilder(AT);
sb.append(COMMAND_CGCLASS);
sb.append(EQUAL);
sb.append(DOUBLE_QUOTE);
sb.append(clazz);
sb.append(DOUBLE_QUOTE);
return new EmptyResponse(super.execute(sb.toString()));
} finally {
available.release();
}
}
public GprsMobileStationClassResponse read() throws SerialException, TimeoutException, ResponseException {
available.acquireUninterruptibly();
try {
final StringBuilder sb = new StringBuilder(AT);
sb.append(COMMAND_CGCLASS);
sb.append(QUERY);
return new GprsMobileStationClassResponse(super.execute(sb.toString()));
} finally {
available.release();
}
}
public TestResponse test() throws SerialException, TimeoutException, ResponseException {
available.acquireUninterruptibly();
try {
final StringBuilder sb = new StringBuilder(AT);
sb.append(COMMAND_CGCLASS);
sb.append(EQUAL);
sb.append(QUERY);
return new TestResponse(super.execute(sb.toString()));
} finally {
available.release();
}
}
private boolean isInvalidGprsMobileStationClass(final String clazz) {
if (CLASS_A.equals(clazz) || CLASS_B.equals(clazz) || CLASS_C.equals(clazz) || CLASS_C_GPRS.equals(clazz) || CLASS_C_GSM.equals(clazz)) {
return false;
}
return true;
}
}
| 35.752941 | 141 | 0.745969 |
df60070c06b403f6f6d95f7a91715e4ea2fcd27f | 2,303 | package auyar.pms;
/**
* Copyright 2017 Ahmet Uyar
* 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.
*/
/**
* sequential mergesort
* classical recursive mergesort algorithm
* sorting a long array
*
* @author Ahmet Uyar
*/
public class MergeSortSeq {
/**
* classical recursive merge sort algorithm
* first and last indexes are inclusive
*
* @param array the data array to be sorted
* @param first start index of the sub array to be sorted
* @param last last index of the sub array to be sorted (inclusive)
*/
public static void mergeSort(long array[], int first, int last) {
if (first == last) {
return;
}
int middle = (first + last) / 2;
mergeSort(array, middle + 1, last);
mergeSort(array, first, middle);
MergeSortUtil.merge(array, aux, first, middle + 1, last+1);
}
static long dd[] = {50, 70, 45, 30, 34, 78, 56, 10};
static long aux[];
public static void main(String[] args) {
aux = new long[dd.length];
mergeSort(dd, 0, dd.length - 1);
print(dd);
}
public static void print(long[] dd) {
for (int i = 0; i < dd.length; i++) {
System.out.print(dd[i] + ", ");
}
System.out.println("");
}
}
| 37.754098 | 132 | 0.667825 |
f04410dcd70af07479fa05aa879aa72bbac95d58 | 1,678 | /*
* Copyright (C) 2016 Li Jiangdong Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.ljd.news.domain.interactor;
import com.ljd.news.data.repository.AvatarDataRepository;
import com.ljd.news.domain.executor.PostExecutionThread;
import com.ljd.news.domain.executor.ThreadExecutor;
import javax.inject.Inject;
import rx.Observable;
public class GetWeChatNews extends UseCase {
private final AvatarDataRepository avatarDataRepository;
private static final String APP_KEY = "53b4892b3f764cc2a19e4896546aa8e8";
private static final int RAWS = 10;
private int page = 1;
@Inject
public GetWeChatNews(ThreadExecutor threadExecutor,
PostExecutionThread postExecutionThread,
AvatarDataRepository avatarDataRepository) {
super(threadExecutor, postExecutionThread);
this.avatarDataRepository = avatarDataRepository;
}
@Override
protected Observable buildUseCaseObservable() {
return avatarDataRepository.getWeChatNews(APP_KEY,page,RAWS,"Android");
}
public void setPage(int page) {
this.page = page;
}
}
| 32.269231 | 79 | 0.73242 |
4e375bbe6ed13573a19736d576427c43d622936d | 10,496 | /*******************************************************************************
* Copyright 2016 by the Department of Computer Science (University of Genova and University of Oxford)
*
* This file is part of LogMapC an extension of LogMap matcher for conservativity principle.
*
* LogMapC 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 3 of the License, or
* (at your option) any later version.
*
* LogMapC 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 LogMapC. If not, see <http://www.gnu.org/licenses/>.
******************************************************************************/
package visitor.ELnormalisation;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import org.semanticweb.owlapi.model.ClassExpressionType;
import org.semanticweb.owlapi.model.OWLAnnotationAssertionAxiom;
import org.semanticweb.owlapi.model.OWLAnnotationPropertyDomainAxiom;
import org.semanticweb.owlapi.model.OWLAnnotationPropertyRangeAxiom;
import org.semanticweb.owlapi.model.OWLAsymmetricObjectPropertyAxiom;
import org.semanticweb.owlapi.model.OWLAxiom;
import org.semanticweb.owlapi.model.OWLAxiomVisitor;
import org.semanticweb.owlapi.model.OWLAxiomVisitorEx;
import org.semanticweb.owlapi.model.OWLClass;
import org.semanticweb.owlapi.model.OWLClassAssertionAxiom;
import org.semanticweb.owlapi.model.OWLClassExpression;
import org.semanticweb.owlapi.model.OWLDataPropertyAssertionAxiom;
import org.semanticweb.owlapi.model.OWLDataPropertyDomainAxiom;
import org.semanticweb.owlapi.model.OWLDataPropertyRangeAxiom;
import org.semanticweb.owlapi.model.OWLDatatypeDefinitionAxiom;
import org.semanticweb.owlapi.model.OWLDeclarationAxiom;
import org.semanticweb.owlapi.model.OWLDifferentIndividualsAxiom;
import org.semanticweb.owlapi.model.OWLDisjointClassesAxiom;
import org.semanticweb.owlapi.model.OWLDisjointDataPropertiesAxiom;
import org.semanticweb.owlapi.model.OWLDisjointObjectPropertiesAxiom;
import org.semanticweb.owlapi.model.OWLDisjointUnionAxiom;
import org.semanticweb.owlapi.model.OWLEquivalentClassesAxiom;
import org.semanticweb.owlapi.model.OWLEquivalentDataPropertiesAxiom;
import org.semanticweb.owlapi.model.OWLEquivalentObjectPropertiesAxiom;
import org.semanticweb.owlapi.model.OWLFunctionalDataPropertyAxiom;
import org.semanticweb.owlapi.model.OWLFunctionalObjectPropertyAxiom;
import org.semanticweb.owlapi.model.OWLHasKeyAxiom;
import org.semanticweb.owlapi.model.OWLInverseFunctionalObjectPropertyAxiom;
import org.semanticweb.owlapi.model.OWLInverseObjectPropertiesAxiom;
import org.semanticweb.owlapi.model.OWLIrreflexiveObjectPropertyAxiom;
import org.semanticweb.owlapi.model.OWLNegativeDataPropertyAssertionAxiom;
import org.semanticweb.owlapi.model.OWLNegativeObjectPropertyAssertionAxiom;
import org.semanticweb.owlapi.model.OWLObjectPropertyAssertionAxiom;
import org.semanticweb.owlapi.model.OWLObjectPropertyDomainAxiom;
import org.semanticweb.owlapi.model.OWLObjectPropertyRangeAxiom;
import org.semanticweb.owlapi.model.OWLObjectUnionOf;
import org.semanticweb.owlapi.model.OWLReflexiveObjectPropertyAxiom;
import org.semanticweb.owlapi.model.OWLSameIndividualAxiom;
import org.semanticweb.owlapi.model.OWLSubAnnotationPropertyOfAxiom;
import org.semanticweb.owlapi.model.OWLSubClassOfAxiom;
import org.semanticweb.owlapi.model.OWLSubDataPropertyOfAxiom;
import org.semanticweb.owlapi.model.OWLSubObjectPropertyOfAxiom;
import org.semanticweb.owlapi.model.OWLSubPropertyChainOfAxiom;
import org.semanticweb.owlapi.model.OWLSymmetricObjectPropertyAxiom;
import org.semanticweb.owlapi.model.OWLTransitiveObjectPropertyAxiom;
import org.semanticweb.owlapi.model.SWRLRule;
import util.OntoUtil;
import util.Params;
public class OWLAxiomELNormVisitor implements OWLAxiomVisitorEx<OWLAxiom> {
public OWLClassExpressionELNormVisitor ceVis;
private ELNormaliser normaliser;
public OWLAxiomELNormVisitor(ELNormaliser normaliser){
this.normaliser = normaliser;
ceVis = new OWLClassExpressionELNormVisitor(normaliser);
}
@Override
public OWLAxiom visit(OWLAnnotationAssertionAxiom axiom) {
return null;
}
@Override
public OWLAxiom visit(OWLSubAnnotationPropertyOfAxiom axiom) {
return null;
}
@Override
public OWLAxiom visit(OWLAnnotationPropertyDomainAxiom axiom) {
return null;
}
@Override
public OWLAxiom visit(OWLAnnotationPropertyRangeAxiom axiom) {
return null;
}
@Override
public OWLAxiom visit(OWLDifferentIndividualsAxiom axiom) {
return null;
}
@Override
public OWLAxiom visit(OWLObjectPropertyAssertionAxiom axiom) {
return null;
}
@Override
public OWLAxiom visit(SWRLRule rule) {
return null;
}
@Override
public OWLAxiom visit(OWLSameIndividualAxiom axiom) {
return null;
}
@Override
public OWLAxiom visit(OWLSubPropertyChainOfAxiom axiom) {
return null;
}
@Override
public OWLAxiom visit(OWLDeclarationAxiom axiom) {
return null;
}
@Override
public OWLAxiom visit(OWLSubClassOfAxiom axiom) {
OWLAxiom newAxiom = axiom;
if(Params.verbosity > 1)
System.out.println(axiom.getClass() + " reduction");
OWLClassExpression sub = null, sup = null;
boolean modified = true;
if(!axiom.isGCI()){
sub = axiom.getSubClass();
if(sub.isOWLNothing())
return null;
}
else {
// EL terminologies do not allow complex class expressions as LHS
// if union, try to split in multiple subclassof axioms
if(axiom.getSubClass().getClassExpressionType().equals(
ClassExpressionType.OBJECT_UNION_OF)){
OWLAxiom tmpAx;
for (OWLClassExpression ce :
((OWLObjectUnionOf) axiom.getSubClass()).asDisjunctSet()) {
tmpAx = normaliser.normaliseAxiom(
ELNormaliser.dataFactory.getOWLSubClassOfAxiom(
ce, axiom.getSuperClass()));
if(tmpAx != null)
OntoUtil.addAxiomsToOntology(normaliser.normalisedOnto,
ELNormaliser.manager, Collections.singleton(tmpAx),
false);
}
}
return null;
}
sup = axiom.getSuperClass().accept(ceVis);
if(sup == null)
return null;
if(sup.equals(axiom.getSuperClass()))
modified = false;
if(modified)
newAxiom = ELNormaliser.dataFactory.getOWLSubClassOfAxiom(sub,
sup, axiom.getAnnotations());
return newAxiom;
}
@Override
public OWLAxiom visit(OWLNegativeObjectPropertyAssertionAxiom axiom) {
return null;
}
@Override
public OWLAxiom visit(OWLAsymmetricObjectPropertyAxiom axiom) {
return null;
}
@Override
public OWLAxiom visit(OWLReflexiveObjectPropertyAxiom axiom) {
return null;
}
@Override
public OWLAxiom visit(OWLDisjointClassesAxiom axiom) {
return null;
}
@Override
public OWLAxiom visit(OWLDisjointUnionAxiom axiom) {
return null;
}
@Override
public OWLAxiom visit(OWLEquivalentClassesAxiom axiom) {
OWLAxiom newAxiom = null;
if(Params.verbosity > 1)
System.out.println(axiom.getClass() + " reduction");
boolean modified = true;
List<OWLClassExpression> operands = axiom.getClassExpressionsAsList();
if(operands.size() <= 1)
return null;
if(operands.size() > 2)
throw new IllegalArgumentException("EL normaliser expects pairwise " +
"equivalent class axioms");
if(!operands.get(0).isClassExpressionLiteral() &&
!operands.get(1).isClassExpressionLiteral())
throw new IllegalArgumentException("EL normaliser expects at " +
"least an element to be atomic for equivalent class axioms");
List<OWLClassExpression> reducedOp = new ArrayList<OWLClassExpression>(2);
reducedOp.add(operands.get(0).accept(ceVis));
reducedOp.add(operands.get(1).accept(ceVis));
if(reducedOp.get(0) == null || reducedOp.get(1) == null)
return null;
if(reducedOp.get(0).equals(operands.get(0)) ||
reducedOp.get(1).equals(operands.get(1)))
modified = false;
if(modified)
return ELNormaliser.dataFactory.getOWLEquivalentClassesAxiom(
new HashSet<>(reducedOp),
axiom.getAnnotations());
return axiom;
}
@Override
public OWLAxiom visit(OWLDataPropertyDomainAxiom axiom) {
return null;
}
@Override
public OWLAxiom visit(OWLObjectPropertyDomainAxiom axiom) {
return null;
}
@Override
public OWLAxiom visit(OWLEquivalentObjectPropertiesAxiom axiom) {
return null;
}
@Override
public OWLAxiom visit(OWLNegativeDataPropertyAssertionAxiom axiom) {
return null;
}
@Override
public OWLAxiom visit(OWLDisjointDataPropertiesAxiom axiom) {
return null;
}
@Override
public OWLAxiom visit(OWLDisjointObjectPropertiesAxiom axiom) {
return null;
}
@Override
public OWLAxiom visit(OWLObjectPropertyRangeAxiom axiom) {
return null;
}
@Override
public OWLAxiom visit(OWLFunctionalObjectPropertyAxiom axiom) {
return null;
}
@Override
public OWLAxiom visit(OWLSubObjectPropertyOfAxiom axiom) {
return null;
}
@Override
public OWLAxiom visit(OWLSymmetricObjectPropertyAxiom axiom) {
return null;
}
@Override
public OWLAxiom visit(OWLDataPropertyRangeAxiom axiom) {
return null;
}
@Override
public OWLAxiom visit(OWLFunctionalDataPropertyAxiom axiom) {
return null;
}
@Override
public OWLAxiom visit(OWLEquivalentDataPropertiesAxiom axiom) {
return null;
}
@Override
public OWLAxiom visit(OWLClassAssertionAxiom axiom) {
return null;
}
@Override
public OWLAxiom visit(OWLDataPropertyAssertionAxiom axiom) {
return null;
}
@Override
public OWLAxiom visit(OWLTransitiveObjectPropertyAxiom axiom) {
return null;
}
@Override
public OWLAxiom visit(OWLIrreflexiveObjectPropertyAxiom axiom) {
return null;
}
@Override
public OWLAxiom visit(OWLSubDataPropertyOfAxiom axiom) {
return null;
}
@Override
public OWLAxiom visit(OWLInverseFunctionalObjectPropertyAxiom axiom) {
return null;
}
@Override
public OWLAxiom visit(OWLInverseObjectPropertiesAxiom axiom) {
return null;
}
@Override
public OWLAxiom visit(OWLHasKeyAxiom axiom) {
return null;
}
@Override
public OWLAxiom visit(OWLDatatypeDefinitionAxiom axiom) {
return null;
}
}
| 28.444444 | 103 | 0.768864 |
61e8745dfc8175b5176d495cfeb372e0d95f033d | 2,226 | /*
* Copyright (C) 2013 salesforce.com, 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.auraframework.impl.java.provider;
import org.auraframework.def.DefDescriptor;
import org.auraframework.def.TokenDescriptorProvider;
import org.auraframework.def.TokenDescriptorProviderDef;
import org.auraframework.def.TokensDef;
import org.auraframework.instance.Instance;
import org.auraframework.throwable.quickfix.QuickFixException;
import org.auraframework.util.json.Json;
import java.io.IOException;
/**
* Token descriptor instance
*/
public class TokenDescriptorProviderInstance implements Instance<TokenDescriptorProviderDef>, TokenDescriptorProvider {
private final TokenDescriptorProviderDef tokenDescriptorProviderDef;
private final TokenDescriptorProvider tokenDescriptorProvider;
public TokenDescriptorProviderInstance(TokenDescriptorProviderDef tokenDescriptorProviderDef,
TokenDescriptorProvider tokenDescriptorProvider) {
this.tokenDescriptorProviderDef = tokenDescriptorProviderDef;
this.tokenDescriptorProvider = tokenDescriptorProvider;
}
@Override
public DefDescriptor<TokenDescriptorProviderDef> getDescriptor() {
return this.tokenDescriptorProviderDef.getDescriptor();
}
@Override
public String getPath() {
throw new UnsupportedOperationException("TokenDescriptorProviderInstance does not support getPath() at this time.");
}
@Override
public void serialize(Json json) throws IOException {
}
@Override
public DefDescriptor<TokensDef> provide() throws QuickFixException {
return this.tokenDescriptorProvider.provide();
}
}
| 35.903226 | 124 | 0.764151 |
266b93db63bf7ff02390ba9583acea5a38649f0b | 276 | package com.suizhu.work.log.service;
import com.suizhu.common.core.service.IService;
import com.suizhu.work.entity.LogDoorway;
/**
* <p>
* 门店日志 服务类
* </p>
*
* @author GaoChao
* @since 2019-03-07
*/
public interface LogDoorwayService extends IService<LogDoorway> {
}
| 16.235294 | 65 | 0.713768 |
f6f69130ec9ba63427e3a3cf3bd9a035754c73b0 | 2,184 | package com.javacourse.springmvc.examples;
import java.util.Locale;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.boot.web.servlet.support.SpringBootServletInitializer;
import org.springframework.context.MessageSource;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.support.ReloadableResourceBundleMessageSource;
import org.springframework.web.servlet.LocaleResolver;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import org.springframework.web.servlet.i18n.LocaleChangeInterceptor;
import org.springframework.web.servlet.i18n.SessionLocaleResolver;
@SpringBootApplication()
@ComponentScan(basePackages= {"com.javacourse.springmvc.examples.controller"})
public class WebApplication extends SpringBootServletInitializer implements WebMvcConfigurer {
@Override
protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
return application.sources(WebApplication.class, SecurityConfig.class);
}
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(localeChangeInterceptor());
}
@Bean
public MessageSource messageSource() {
ReloadableResourceBundleMessageSource result = new ReloadableResourceBundleMessageSource();
result.setBasename("WEB-INF/messages");
result.setUseCodeAsDefaultMessage(true);
return result;
}
@Bean
public LocaleResolver localeResolver() {
SessionLocaleResolver slr = new SessionLocaleResolver();
slr.setDefaultLocale(Locale.ITALIAN);
return slr;
}
@Bean
public LocaleChangeInterceptor localeChangeInterceptor() {
LocaleChangeInterceptor lci = new LocaleChangeInterceptor();
lci.setParamName("lang");
return lci;
}
public static void main(String[] args) {
SpringApplication.run(new Class[] {WebApplication.class, SecurityConfig.class}, args);
}
}
| 36.4 | 94 | 0.825092 |
1f7b2fb53acc979e69e5087f37018ad310f88fa5 | 2,112 | package seedu.cakecollate.storage;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;
import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonRootName;
import seedu.cakecollate.commons.exceptions.IllegalValueException;
import seedu.cakecollate.model.CakeCollate;
import seedu.cakecollate.model.ReadOnlyCakeCollate;
import seedu.cakecollate.model.order.Order;
/**
* An Immutable CakeCollate that is serializable to JSON format.
*/
@JsonRootName(value = "cakecollate")
class JsonSerializableCakeCollate {
public static final String MESSAGE_DUPLICATE_ORDER = "Orders list contains duplicate order(s).";
private final List<JsonAdaptedOrder> orders = new ArrayList<>();
/**
* Constructs a {@code JsonSerializableCakeCollate} with the given orders.
*/
@JsonCreator
public JsonSerializableCakeCollate(@JsonProperty("orders") List<JsonAdaptedOrder> orders) {
this.orders.addAll(orders);
}
/**
* Converts a given {@code ReadOnlyCakeCollate} into this class for Jackson use.
*
* @param source future changes to this will not affect the created {@code JsonSerializableCakeCollate}.
*/
public JsonSerializableCakeCollate(ReadOnlyCakeCollate source) {
orders.addAll(source.getOrderList().stream().map(JsonAdaptedOrder::new).collect(Collectors.toList()));
}
/**
* Converts this cakecollate into the model's {@code CakeCollate} object.
*
* @throws IllegalValueException if there were any data constraints violated.
*/
public CakeCollate toModelType() throws IllegalValueException {
CakeCollate cakeCollate = new CakeCollate();
for (JsonAdaptedOrder jsonAdaptedOrder : orders) {
Order order = jsonAdaptedOrder.toModelType();
if (cakeCollate.hasOrder(order)) {
throw new IllegalValueException(MESSAGE_DUPLICATE_ORDER);
}
cakeCollate.addOrder(order);
}
return cakeCollate;
}
}
| 34.622951 | 110 | 0.723485 |
aea6cc5662b5519911ef0ef4f031abc4dc167135 | 636 | package com.team_htbr.a1617proj1bloeddonatie_app;
import android.util.Log;
import com.google.firebase.iid.FirebaseInstanceId;
import com.google.firebase.iid.FirebaseInstanceIdService;
/**
* Created by Ruben on 23/03/2017.
*/
public class MyFirebaseInstanceIDService extends FirebaseInstanceIdService {
private static final String TAG = "MyFirebaseInsIDService";
@Override
public void onTokenRefresh() {
//Get updated token
String refreshedToken = FirebaseInstanceId.getInstance().getToken();
Log.d(TAG, "New Token: " + refreshedToken);
//You can save the token into third party server to do anything you want
}
}
| 23.555556 | 76 | 0.775157 |
2b66e611f1925cd10e142efb54361dff3646d4f5 | 2,458 | package spreadsheet;
import limiter.Originator;
import spreadsheet.Programmer;
import spreadsheet.Summons;
import java.util.Comparator;
import java.util.PriorityQueue;
public class DefinedCompiler extends spreadsheet.Programmer {
public java.util.PriorityQueue<Summons> preppedDragon;
public java.util.Comparator<Summons> witness;
public synchronized void optiBeat() {
if (theMethodology != null) {
theMethodology.bentLengthwiseHour(theMethodology.makeFlyingDay() + 1);
if (theMethodology.makeFlyingDay() == theMethodology.goExecutiveHeight()) {
theMethodology.placedExpireWhen(this.bringOngoingBeat());
this.finalizationTechniques.addLast(theMethodology);
theMethodology = null;
this.deviceEnsign = true;
}
}
if (!preppedDragon.isEmpty() && theMethodology != null) {
int afootRetaining = theMethodology.goExecutiveHeight() - theMethodology.makeFlyingDay();
int knockoutLatter =
preppedDragon.peek().goExecutiveHeight() - preppedDragon.peek().makeFlyingDay();
if (knockoutLatter < afootRetaining) {
preppedDragon.add(theMethodology);
theMethodology = null;
this.deviceEnsign = true;
}
}
if (this.deviceEnsign && theMethodology == null) {
this.unansweredVariNow--;
if (unansweredVariNow == 0) {
this.deviceEnsign = false;
this.unansweredVariNow = Originator.SentYears;
}
} else {
if (theMethodology == null && !preppedDragon.isEmpty()) {
theMethodology = preppedDragon.poll();
unladenProceeding(theMethodology);
theMethodology.bentResumeHour(this.bringOngoingBeat());
}
}
}
public class FormalitiesPlacebo implements Comparator<Summons> {
public synchronized int compare(Summons c, Summons ap) {
int gUnresolved = c.goExecutiveHeight() - c.makeFlyingDay();
int apAdditional = ap.goExecutiveHeight() - ap.makeFlyingDay();
if (gUnresolved < apAdditional) {
return -1;
}
if (gUnresolved > apAdditional) {
return 1;
}
return 0;
}
}
public synchronized String synchronizerDescribe() {
return "SRT:";
}
public DefinedCompiler() {
this.witness = new FormalitiesPlacebo();
this.preppedDragon = new java.util.PriorityQueue<>(5, witness);
}
public synchronized void summonsInflowing(Summons operation) {
preppedDragon.add(operation);
}
}
| 28.252874 | 95 | 0.681041 |
bc941ae56f0dbb52238c3c791d3ce30996b0d40f | 797 | package com.udacity.gradle.jokedisplayer;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity {
public static final String jokeKey = "jokeKey";
private static final String LOG_TAG = MainActivity.class.getSimpleName();
@Override
protected void onCreate(Bundle savedInstanceState) {
Log.i(LOG_TAG, "onCreate: ");
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main_jokedisplay);
TextView jokeView = (TextView) findViewById(R.id.jokeTextView);
String joke = getIntent().getStringExtra(jokeKey);
Log.i(LOG_TAG, "onCreateView: " + joke);
jokeView.setText(joke);
}
}
| 30.653846 | 77 | 0.723965 |
8453f708db105fbe7a9cc6922b6060474b439d5c | 561 | public void trimAndWriteNewSff(OutputStream out) throws IOException {
TrimParser trimmer = new TrimParser();
SffParser.parseSFF(untrimmedSffFile, trimmer);
tempOut.close();
headerBuilder.withNoIndex().numberOfReads(numberOfTrimmedReads);
SffWriter.writeCommonHeader(headerBuilder.build(), out);
InputStream in = null;
try {
in = new FileInputStream(tempReadDataFile);
IOUtils.copyLarge(in, out);
} finally {
IOUtil.closeAndIgnoreErrors(in);
}
}
| 37.4 | 73 | 0.638146 |
41ebcb029650f077eaf32674c963ceebd6bbad90 | 564 | package jef.database.dialect.handler;
import jef.database.wrapper.clause.BindSql;
import jef.tools.PageLimit;
/**
* LimitHandler用于进行结果集限制。offset,limit的控制
*
* @author jiyi
*
*/
public interface LimitHandler {
/**
* 对于SQL语句进行结果集限制
*
* @param sql
* @param offsetLimit
* @return
*/
BindSql toPageSQL(String sql, PageLimit offsetLimit);
/**
* 对于SQL语句进行结果集限制
*
* @param sql
* @param offsetLimit
* @param isUnion
* @return
*/
BindSql toPageSQL(String sql, PageLimit offsetLimit, boolean isUnion);
}
| 17.625 | 72 | 0.652482 |
05582ddd7fe39d72c2bd93366100eb64ec70bfba | 21,174 | /*
* Copyright (C) 2019 Toshiba Corporation
* SPDX-License-Identifier: Apache-2.0
*/
package org.wcardinal.controller;
import java.security.Principal;
import java.util.Collection;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.concurrent.Callable;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import org.jdeferred.Promise;
import com.fasterxml.jackson.databind.node.ArrayNode;
import org.wcardinal.util.doc.ThreadSafe;
import org.wcardinal.util.thread.Scheduler;
import org.wcardinal.util.thread.Unlockable;
import org.wcardinal.util.thread.Unlocker;
/**
* Central interface to provide methods for controllers.
*/
public interface ControllerContext extends Unlockable {
/**
* Locks this controller.
*
* <p>Please note that all the fields and controllers belonging to the same controller instance share a lock.
* Thus, the followings is not necessary:
*
* <pre><code> {@literal @}Controller
* class MyController {
* {@literal @}Autowired
* SString name;
*
* {@literal @}Autowired
* SInteger score;
*
* {@literal @}OnChange("name")
* void onChange(){
* try( Unlocker unlocker = score.lock() ){ // Unnecessary
* score.set( 0 );
* }
* }
* }
* </code></pre>
*
* When the 'onChange' method is called, the 'name' field is locked.
* And the 'name' field, the 'score' field and the 'MyController' controller share a lock.
* The 'score' field, therefore, is locked at the time the 'onChange' method is called.
*
* The only exception to this is a component annotated with {@link org.wcardinal.controller.annotation.SharedComponent}.
* Shared components and fields on them do not share a lock with the others.
*
* Because shared components do not share a lock, the lock ordering is necessary to avoid concurrency issues.
* If locking a shared component and one of its parents at once is unavoidable, must lock a parent at first.
* And then lock a shared component.
*
* <pre><code> {@literal @}SharedComponent
* class MySharedComponent{}
*
* {@literal @}Controller
* class MyController {
* {@literal @}Autowired
* MySharedComponent component;
*
* void foo(){
* // At first lock itself, the parent of the 'this.component'
* try( Unlocker parent = lock() ) {
* // Then lock a shared component
* try( Unlocker child = component.lock() ) {
* // Do something here
* }
* }
* }
* }
* </code></pre>
*
* @return {@link org.wcardinal.util.thread.Unlocker Unlocker} instance for unlocking this lock
*/
@ThreadSafe
Unlocker lock();
/**
* Tries to lock this controller.
*
* @return true if succeeded
*/
@ThreadSafe
boolean tryLock();
/**
* Tries to lock this controller.
*
* @param timeout the timeout for this trial
* @param unit the unit of the timeout
* @return true if succeeded
*/
@ThreadSafe
boolean tryLock( final long timeout, final TimeUnit unit );
/**
* Returns true if this controller is locked.
*
* @return true if this controller is locked.
*/
@ThreadSafe
boolean isLocked();
/**
* Returns true if this controller is locked by the current thread.
*
* @return true if this controller is locked by the current thread.
*/
@ThreadSafe
boolean isLockedByCurrentThread();
/**
* Returns true if this controller is read-only.
*
* @return true if this controller is read-only.
*/
@ThreadSafe
boolean isReadOnly();
/**
* Returns true if this controller is non-null.
*
* @return true if this controller is non-null.
*/
@ThreadSafe
boolean isNonNull();
/**
* Returns true if this controller is historical.
*
* @return true if this controller is historical.
*/
@ThreadSafe
boolean isHistorical();
/**
* Unlocks this controller.
*/
@ThreadSafe
@Override
void unlock();
/**
* Returns the name of this controller.
*
* @return the name of this controller
*/
@ThreadSafe
String getName();
/**
* Returns the parent.
*
* @param <T> the type of parent
* @return the parent instance
*/
@ThreadSafe
<T> T getParent();
/**
* Returns the parent as a factory.
*
* @return the parent instance
*/
@ThreadSafe
Factory<?> getParentAsFactory();
/**
* Returns the parents.
*
* @param <T> the type of parents
* @return the parent instances
*/
@ThreadSafe
<T> Collection<T> getParents();
/**
* Returns the active page or null.
*
* @param <T> the type of the active page
* @return the active page
*/
@ThreadSafe
<T> T getActivePage();
/**
* Returns the first parameter of the specified key.
* The parameters are taken from the query string or posted form data.
*
* <pre><code> // HTML
* {@literal <script src="my-controller?name=John"></script>}
*
* // Java
* {@literal @}Controller
* class MyController {
* {@literal @}OnCreate
* void onCreate(){
* System.out.println( getParameter("name") ); // prints "John"
* }
* }
* </code></pre>
*
* @param key the key of the parameter
* @return the first parameter of the specified key
*/
@ThreadSafe
String getParameter( final String key );
/**
* Returns the parameters of the specified key.
* The parameters are taken from the query string or posted form data.
*
* <pre><code> // HTML
* {@literal <script src="my-controller?name=John"></script>}
*
* // Java
* {@literal @}Controller
* class MyController {
* {@literal @}OnCreate
* void onCreate(){
* System.out.println( Arrays.toString(getParameters("name")) ); // prints ["John"]
* }
* }
* </code></pre>
*
* @param key the key of the parameters
* @return the parameters of the specified key
*/
@ThreadSafe
String[] getParameters( final String key );
/**
* Returns the map of parameters.
* The parameters are taken from the query string or posted form data.
*
* <pre><code> // HTML
* {@literal <script src="my-controller?name=John"></script>}
*
* // Java
* {@literal @}Controller
* class MyController {
* {@literal @}OnCreate
* void onCreate(){
* System.out.println( getParameterMap("name") ); // prints {name=["John"]}
* }
* }
* </code></pre>
*
* @return the map of parameters
*/
@ThreadSafe
Map<String, String[]> getParameterMap();
/**
* Returns the factory parameters.
* The factory parameters are the parameters given to
* the method {@link org.wcardinal.controller.Factory#create(Object...)}.
*
* <pre><code> {@literal @}Controller
* class MyController {
* {@literal @}Autowired
* {@literal ComponentFactory<MyComponent>} factory;
*
* {@literal @}OnCreate
* void onCreate(){
* factory.create(1, "John");
* }
* }
*
* class MyComponent extends AbstractComponent {
* {@literal @}OnCreate
* void onCreate(){
* System.out.println( getFactoryParameters() ); // prints [1, "John"]
* }
* }
* </code></pre>
*
* @return the factory parameters.
*/
@ThreadSafe
ArrayNode getFactoryParameters();
/**
* Returns the attributes.
*
* @return the attributes.
*/
@ThreadSafe
ControllerAttributes getAttributes();
/**
* Returns the locale objects in decreasing order starting with the preferred locale.
*
* @return the locale objects
*/
@ThreadSafe
List<Locale> getLocales();
/**
* Returns the preferred locale.
*
* @return the preferred locale
*/
@ThreadSafe
Locale getLocale();
/**
* Shows this controller.
*/
@ThreadSafe
void show();
/**
* Hides this controller.
*/
@ThreadSafe
void hide();
/**
* Returns true if this controller is shown.
*
* @return true if this controller is shown.
*/
@ThreadSafe
boolean isShown();
/**
* Returns true if this controller is hidden.
*
* @return true if this controller is hidden.
*/
@ThreadSafe
boolean isHidden();
/**
* Returns the user's remote address.
*
* @return user's remote address
*/
@ThreadSafe
String getRemoteAddress();
/**
* Returns the user principle.
*
* @return user principle
*/
@ThreadSafe
Principal getPrincipal();
/**
* Returns the scheduler.
*
* @return the scheduler
*/
Scheduler getScheduler();
/**
* Requests to execute methods annotated with the {@link org.wcardinal.controller.annotation.OnTime} of the specified name.
*
* @param name method name specified by {@link org.wcardinal.controller.annotation.OnTime}
* @param parameters parameters to be passed to the specified methods
*
*/
@ThreadSafe
void execute( final String name, final Object... parameters );
/**
* Requests to execute the specified runnable.
*
* @param runnable runnable to be executed
* @return future
*
*/
@ThreadSafe
Future<?> execute( final Runnable runnable );
/**
* Requests to execute the specified callable.
*
* @param <T> return type of the specified callable
* @param callable callable to be executed
* @return future
*
*/
@ThreadSafe
<T> Future<T> execute( final Callable<T> callable );
/**
* Requests to call methods annotated with the {@link org.wcardinal.controller.annotation.OnTime} of the specified
* name after the specified delay and returns an ID of this request.
* Use the returned ID and {@link #cancel(long)} for canceling the request.
*
* @param name method name specified by {@link org.wcardinal.controller.annotation.OnTime}
* @param delay delay in milliseconds
* @param parameters parameters to be passed to the specified methods
* @return request ID
* @see #cancel()
* @see #cancel(long)
* @see #cancelAll()
*/
@ThreadSafe
long timeout( final String name, final long delay, final Object... parameters );
/**
* Requests to call the specified runnable after the specified delay and returns an ID of this request.
* Use the returned ID and {@link #cancel(long)} for canceling the request.
*
* @param runnable runnable to be executed
* @param delay delay in milliseconds
* @return request ID
* @see #cancel()
* @see #cancel(long)
* @see #cancelAll()
*/
@ThreadSafe
long timeout( final Runnable runnable, final long delay );
/**
* Requests to call the specified callable after the specified delay.
* Use the returned ID and {@link #cancel(long)} for canceling the request.
*
* @param <T> return type of the specified callable
* @param callable callable to be executed
* @param delay delay in milliseconds
* @return future
*
* @see #cancel()
* @see #cancel(long)
* @see #cancelAll()
*/
@ThreadSafe
<T> TimeoutFuture<T> timeout( final Callable<T> callable, final long delay );
/**
* Requests to call methods annotated with the {@link org.wcardinal.controller.annotation.OnTime} of the specified
* name at the specified interval and returns an ID of this request.
* Use the returned ID and {@link #cancel(long)}, or {@link #cancel()} for canceling the request.
* The first call is taking place after the milliseconds specified as the interval.
*
* @param name method name specified by {@link org.wcardinal.controller.annotation.OnTime}
* @param interval interval in milliseconds
* @return request ID
* @see #cancel()
* @see #cancel(long)
* @see #cancelAll()
*/
@ThreadSafe
long interval( final String name, final long interval );
/**
* Requests to call methods annotated with the {@link org.wcardinal.controller.annotation.OnTime} of the specified
* name at the specified interval after the 'startAfter' milliseconds and returns an ID of this request.
* Use the returned ID and {@link #cancel(long)}, or {@link #cancel()} for canceling the request.
* The first call is taking place after the 'startAfter' milliseconds.
*
* @param name method name specified by {@link org.wcardinal.controller.annotation.OnTime}
* @param startAfter delay of the first call in milliseconds
* @param interval interval in milliseconds
* @param parameters parameters to be passed to the specified methods
* @return request ID
* @see #cancel()
* @see #cancel(long)
* @see #cancelAll()
*/
@ThreadSafe
long interval( final String name, final long startAfter, final long interval, final Object... parameters );
/**
* Requests to call the specified runnable at the specified interval and returns an ID of this request.
* Use the returned ID and {@link #cancel(long)}, or {@link #cancel()} for canceling the request.
* The first call is taking place after the milliseconds specified as the interval.
*
* @param runnable runnable to be executed
* @param interval interval in milliseconds
* @return request ID
* @see #cancel()
* @see #cancel(long)
* @see #cancelAll()
*/
@ThreadSafe
long interval( final Runnable runnable, final long interval );
/**
* Requests to call the specified runnable at the specified interval after the 'startAfter' milliseconds and returns an ID of this request.
* Use the returned ID and {@link #cancel(long)}, or {@link #cancel()} for canceling the request.
* The first call is taking place after the 'startAfter' milliseconds.
*
* @param runnable runnable to be executed
* @param startAfter delay of the first call in milliseconds
* @param interval interval in milliseconds
* @return request ID
* @see #cancel()
* @see #cancel(long)
* @see #cancelAll()
*/
@ThreadSafe
long interval( final Runnable runnable, final long startAfter, final long interval );
/**
* Cancels the request of the specified ID issued by {@code timeout} or {@code interval} methods.
*
* @param id request ID
* @return true if succeeded
* @see #timeout(String, long, Object...)
* @see #timeout(Runnable, long)
* @see #timeout(Callable, long)
* @see #interval(String, long)
* @see #interval(String, long, long, Object...)
* @see #interval(Runnable, long)
* @see #interval(Runnable, long, long)
*/
@ThreadSafe
boolean cancel( final long id );
/**
* Cancels the current request issued by {@code timeout} or {@code interval} methods, or the current task.
* Under the hood, a thread local is used to distinguish requests/tasks.
*
* <pre><code> {@literal @}Controller
* class MyController extends AbstractController {
* {@literal @}OnCreate
* void onCreate(){
* interval( "update", 1000 );
* }
*
* {@literal @}OnTime
* void update(){
* // Stops the "update" by itself
* cancel();
* }
* }
* </code></pre>
*
* @return true if succeeded
* @see #timeout(String, long, Object...)
* @see #timeout(Runnable, long)
* @see #timeout(Callable, long)
* @see #interval(String, long)
* @see #interval(String, long, long, Object...)
* @see #interval(Runnable, long)
* @see #interval(Runnable, long, long)
*/
@ThreadSafe
boolean cancel();
/**
* Cancels the current task.
* Under the hood, a thread local is used to distinguish tasks.
*
* @param reason a cancel reason
* @return true if succeeded
*/
@ThreadSafe
boolean cancel( final String reason );
/**
* Cancels all requests issued by {@code timeout} or {@code interval} methods.
*
* @see #timeout(String, long, Object...)
* @see #timeout(Runnable, long)
* @see #timeout(Callable, long)
* @see #interval(String, long)
* @see #interval(String, long, long, Object...)
* @see #interval(Runnable, long)
* @see #interval(Runnable, long, long)
*/
@ThreadSafe
void cancelAll();
/**
* Returns true if the current task is canceled or if the current request issued by {@code timeout} or {@code interval} methods is canceled/non-existing.
* Under the hood, a thread local is used to distinguish requests/tasks
*
* @return true if the current task is canceled or if the current request issued by {@code timeout} or {@code interval} methods is canceled/non-existing
*/
@ThreadSafe
boolean isCanceled();
/**
* Returns true if the thread calling this method is the forefront executor of methods annotated with {@link org.wcardinal.controller.annotation.Tracked}.
*
* @return true if the thread calling this method is the forefront executor of methods annotated with {@link org.wcardinal.controller.annotation.Tracked}
*/
@ThreadSafe
boolean isHeadCall();
/**
* Triggers the event of the given name at browsers.
* Optional arguments are passed to browsers as event data.
*
* <pre><code> // JavaScript
* myController.on( 'hello', function( e, name ){
* console.log( name ); // prints 'John'
* });
*
* // Java
* {@literal @}Controller
* class MyController extends AbstractController {
* {@literal @}OnCreate
* void onCreate(){
* timeout( "hello", 5000 );
* }
*
* {@literal @}OnTime
* void hello(){
* trigger( "hello", "John" );
* }
* }
* </code></pre>
*
* @param name event name
* @param arguments event data
* @see #triggerAndWait(String, long, Object...)
* @see #triggerDirect(String, Object...)
*/
@ThreadSafe
void trigger( final String name, final Object... arguments );
/**
* Triggers the event of the given name at browsers directly.
* Only difference between {@link #trigger(String, Object...)} and this is this method sends trigger events directly
* by bypassing the most of the costly synchronization processes.
* Thus, in general, supposed to be faster than {@link #trigger(String, Object...)}.
* However, because of this, weak against network disconnections.
*
* @param name event name
* @param arguments event data
* @see #trigger(String, Object...)
* @see #triggerAndWait(String, long, Object...)
*/
@ThreadSafe
void triggerDirect( final String name, final Object... arguments );
/**
* Triggers the event of the specified name at browsers and waits for responses from browsers.
* Optional arguments are passed to browsers as event data.
* When a browser send back responses within a given period of time,
* the callback {@link org.jdeferred.DoneCallback} set to the {@link Promise#done(org.jdeferred.DoneCallback)} is called.
* Otherwise, the callback {@link org.jdeferred.FailCallback} set to the {@link Promise#fail(org.jdeferred.FailCallback)} is called.
*
* <pre><code> // JavaScript
* myController.on( 'hello', function( e, name ){
* console.log( name ); // prints 'John'
* return 'Hello, '+name;
* });
*
* // Java
* {@literal @}Controller
* class MyController extends AbstractController {
* {@literal @}OnCreate
* void onCreate(){
* timeout( "hello", 5000 );
* }
*
* {@literal @}OnTime
* void hello(){
* trigger( "hello", 3000, "John" )
* .done(new {@literal DoneCallback<List<JsonNode>>}(){
* public void onDone({@literal List<JsonNode>} result) {
* System.out.println( result.get( 0 ).asText() ); // prints "Hello, John"
* }
* });
* }
* }
* </code></pre>
*
* @param name event name
* @param timeout timeout for this trigger in milliseconds
* @param arguments event data
* @return promise instance
* @see #trigger(String, Object...)
* @see #triggerDirect(String, Object...)
*/
@ThreadSafe
TriggerResult triggerAndWait( final String name, final long timeout, final Object... arguments );
/**
* Requests to call methods annotated with the {@link org.wcardinal.controller.annotation.OnNotice} of the specified name.
* Notifications propagate to parents. To catch a notification triggered by a child, use a name prefixed with a child name.
*
* <pre><code> {@literal @}Component
* class MyComponent extends AbstractComponent {
* void notifyBar(){
* notify( "bar" );
* }
* }
*
* {@literal @}Controller
* class MyController {
* {@literal @}Autowired
* MyComponent foo;
*
* {@literal @}OnNotice("foo.bar")
* void onNotice(){
* // Called when the child 'foo' sends a 'bar' notification
* }
* }
* </code></pre>
*
* @param name notification name
* @param parameters notification parameters
* @see #notifyAsync(String, Object...)
*/
void notify( final String name, final Object... parameters );
/**
* Requests to call methods annotated with the {@link org.wcardinal.controller.annotation.OnNotice} of the specified name asynchronously.
* Notifications propagate to parents. To catch a notification triggered by a child, use a name prefixed with a child name.
*
* <pre><code> {@literal @}Component
* class MyComponent extends AbstractComponent {
* void notifyBar(){
* notifyAsync( "bar" );
* }
* }
*
* {@literal @}Controller
* class MyController {
* {@literal @}Autowired
* MyComponent foo;
*
* {@literal @}OnNotice("foo.bar")
* void onNotice(){
* // Called when the child 'foo' sends a 'bar' notification
* }
* }
* </code></pre>
*
* @param name notification name
* @param parameters notification parameters
* @see #notify(String, Object...)
*/
void notifyAsync( final String name, final Object... parameters );
/**
* Returns the session ID.
*
* @return the session ID
*/
String getSessionId();
/**
* Returns the sub session ID.
*
* @return the sub session ID
*/
String getSubSessionId();
}
| 27.787402 | 155 | 0.665628 |
1250ae0c8b902ecf2ad849b8621a9f246c9d9303 | 1,328 | package me.mrletsplay.mrcore.bukkitimpl.ui;
/**
* This class is used by UIMultiPages to define a basic, flexible layout which will then be parsed into the final chat message<br>
* This class is only available to the UIBuilderMultiPage/UIMultiPage
* @author MrLetsplay2003
*/
public class UILayoutMultiPage extends UILayout {
private int itemAmount = 0;
@Override
public UILayoutMultiPage addText(String text) {
super.addText(text);
return this;
}
@Override
public UILayoutMultiPage addElement(String element) {
super.addElement(element);
return this;
}
@Override
public UILayoutMultiPage newLine() {
super.newLine();
return this;
}
/**
* Adds multi page elements<br>
* These will later be replaced by the multi page element's layouts
* @param count The amount of elements to add
* @param includeNewLines Whether a {@link UILayoutMultiPage#newLine()} should be added before each element
* @return This UILayoutMultiPage instance
*/
public UILayoutMultiPage addPageElements(int count, boolean includeNewLines) {
itemAmount += count;
for(int i = 0; i < count; i++) {
getElements().add(new UILayoutElement(UILayoutElementType.MULTIPAGE_PAGE_ELEMENT).setProperty("newline", includeNewLines));
}
return this;
}
public int getItemAmount() {
return itemAmount;
}
}
| 26.56 | 130 | 0.741717 |
0ad2df355817f4762a68889490e3bda58280f4d3 | 129 | /**
* Пакет для выполнения задач по массивам.
* @author vzamylin
* @version 1
* @since 28.02.2018
*/
package ru.job4j.array; | 18.428571 | 42 | 0.674419 |
9a75aa45c314e5181c7ccea4f37304e9013ae5ea | 2,541 | /*
* #%L
* wcm.io
* %%
* Copyright (C) 2021 wcm.io
* %%
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* #L%
*/
package io.wcm.caravan.rhyme.osgi.sampleservice.impl.resource.errors;
import javax.ws.rs.BeanParam;
import javax.ws.rs.DefaultValue;
import javax.ws.rs.QueryParam;
import io.wcm.caravan.rhyme.osgi.sampleservice.api.collection.CollectionParameters;
import io.wcm.caravan.rhyme.osgi.sampleservice.api.errors.ErrorParameters;
/**
* An implementation of the {@link CollectionParameters} interface that
* contains JAX-RS annotations so it can be used as a {@link BeanParam}
* argument in a resource method signature
*/
public class ErrorParametersBean implements ErrorParameters {
@QueryParam("statusCode")
private Integer statusCode;
@QueryParam("message")
@DefaultValue("An exception during resource generation was simulated")
private String message;
@QueryParam("wrapException")
@DefaultValue("false")
private Boolean wrapException;
@Override
public Integer getStatusCode() {
return statusCode;
}
@Override
public String getMessage() {
return message;
}
@Override
public Boolean getWrapException() {
return wrapException;
}
static ErrorParametersBean clone(ErrorParameters other) {
if (other == null) {
return null;
}
ErrorParametersBean cloned = new ErrorParametersBean();
cloned.statusCode = other.getStatusCode();
cloned.message = other.getMessage();
cloned.wrapException = other.getWrapException();
return cloned;
}
public ErrorParametersBean withStatusCode(Integer value) {
ErrorParametersBean cloned = clone(this);
cloned.statusCode = value;
return cloned;
}
public ErrorParametersBean withMessage(String value) {
ErrorParametersBean cloned = clone(this);
cloned.message = value;
return cloned;
}
public ErrorParametersBean withWrapException(Boolean value) {
ErrorParametersBean cloned = clone(this);
cloned.wrapException = value;
return cloned;
}
}
| 25.158416 | 83 | 0.730028 |
1c60c3858888efa152547571bce9af6a7b541639 | 16,612 | /* $Id: FigStereotypesGroup.java 17741 2010-01-10 03:50:08Z bobtarling $
*******************************************************************************
* Copyright (c) 2009-2010 Contributors - see below
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Bob Tarling
*******************************************************************************
*
* Some portions of this file was previously release using the BSD License:
*/
// $Id: FigStereotypesGroup.java 17741 2010-01-10 03:50:08Z bobtarling $
// Copyright (c) 1996-2009 The Regents of the University of California. All
// Rights Reserved. Permission to use, copy, modify, and distribute this
// software and its documentation without fee, and without a written
// agreement is hereby granted, provided that the above copyright notice
// and this paragraph appear in all copies. This software program and
// documentation are copyrighted by The Regents of the University of
// California. The software program and documentation are supplied "AS
// IS", without any accompanying services from The Regents. The Regents
// does not warrant that the operation of the program will be
// uninterrupted or error-free. The end-user understands that the program
// was developed for research purposes and is advised not to rely
// exclusively on the program for any reason. IN NO EVENT SHALL THE
// UNIVERSITY OF CALIFORNIA BE LIABLE TO ANY PARTY FOR DIRECT, INDIRECT,
// SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES, INCLUDING LOST PROFITS,
// ARISING OUT OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF
// THE UNIVERSITY OF CALIFORNIA HAS BEEN ADVISED OF THE POSSIBILITY OF
// SUCH DAMAGE. THE UNIVERSITY OF CALIFORNIA SPECIFICALLY DISCLAIMS ANY
// WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
// MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE SOFTWARE
// PROVIDED HEREUNDER IS ON AN "AS IS" BASIS, AND THE UNIVERSITY OF
// CALIFORNIA HAS NO OBLIGATIONS TO PROVIDE MAINTENANCE, SUPPORT,
// UPDATES, ENHANCEMENTS, OR MODIFICATIONS.
package org.argouml.uml.diagram.ui;
import java.awt.Dimension;
import java.awt.Image;
import java.awt.Rectangle;
import java.beans.PropertyChangeEvent;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import org.apache.log4j.Logger;
import org.argouml.kernel.Project;
import org.argouml.model.AddAssociationEvent;
import org.argouml.model.Model;
import org.argouml.model.RemoveAssociationEvent;
import org.argouml.uml.diagram.DiagramSettings;
import org.tigris.gef.presentation.Fig;
import org.tigris.gef.presentation.FigRect;
import org.tigris.gef.presentation.FigText;
/**
* A Fig designed to be the child of some FigNode or FigEdge to display the
* stereotypes of the model element represented by the parent Fig.
* Currently, multiple stereotypes are shown stacked one on top of the other,
* each enclosed by guillemets.<p>
*
* The minimum width of this fig is the largest minimum width of its child
* figs. The minimum height of this fig is the total minimum height of its child
* figs.<p>
*
* The owner of this Fig is the UML element that is extended
* with the stereotypes. We are listening to changes to the model:
* addition and removal of stereotypes. <p>
*
* This fig supports showing one keyword
* as the first "stereotype" in the list. <p>
*
* There is no way to remove a keyword fig, once added. <p>
*
* TODO: Allow for UML2 style display where all stereotypes are displayed in
* the same guillemet pair and are delimited by commas. The style should be
* changeable by calling getOrientation(Orientation). The swidget Orientation
* class can be used for this.
* @author Bob Tarling
*/
public class FigStereotypesGroup extends ArgoFigGroup {
private Fig bigPort;
/**
* Logger.
*/
private static final Logger LOG =
Logger.getLogger(FigStereotypesGroup.class);
/**
* One UML keyword is allowed. These are not strictly stereotypes but are
* displayed as such. e.g. <<interface>>
*/
private String keyword;
private int stereotypeCount = 0;
private boolean hidingStereotypesWithIcon = false;
private void constructFigs(int x, int y, int w, int h) {
bigPort = new FigRect(x, y, w, h, LINE_COLOR, FILL_COLOR);
addFig(bigPort);
bigPort.setFilled(false);
/* Do not show border line, make transparent: */
setLineWidth(0);
setFilled(false);
}
/**
* The constructor.
*
* @param owner owning UML element
* @param bounds position and size
* @param settings render settings
*/
public FigStereotypesGroup(Object owner, Rectangle bounds,
DiagramSettings settings) {
super(owner, settings);
constructFigs(bounds.x, bounds.y, bounds.width, bounds.height);
Model.getPump().addModelEventListener(this, owner, "stereotype");
populate();
}
/*
* @see org.tigris.gef.presentation.Fig#removeFromDiagram()
*/
@Override
public void removeFromDiagram() {
/* Remove all items in the group,
* otherwise the model event listeners remain:
* TODO: Why does a FigGroup not do this? */
for (Object f : getFigs()) {
((Fig) f).removeFromDiagram();
}
super.removeFromDiagram();
Model.getPump()
.removeModelEventListener(this, getOwner(), "stereotype");
}
/**
* @return the bigport
* @deprecated for 0.27.2. For backward compatibility only. The visibility
* of this method will be changed to private in the next release
* when FigStereotypesCompartment is removed.
*/
@Deprecated
protected Fig getBigPort() {
return bigPort;
}
@Override
public void propertyChange(PropertyChangeEvent event) {
if (event instanceof AddAssociationEvent) {
AddAssociationEvent aae = (AddAssociationEvent) event;
if (event.getPropertyName().equals("stereotype")) {
Object stereotype = aae.getChangedValue();
if (findFig(stereotype) == null) {
FigText stereotypeTextFig =
new FigStereotype(stereotype,
getBoundsForNextStereotype(),
getSettings());
stereotypeCount++;
addFig(stereotypeTextFig);
reorderStereotypeFigs();
damage();
}
} else {
LOG.warn("Unexpected property " + event.getPropertyName());
}
}
if (event instanceof RemoveAssociationEvent) {
if (event.getPropertyName().equals("stereotype")) {
RemoveAssociationEvent rae = (RemoveAssociationEvent) event;
Object stereotype = rae.getChangedValue();
Fig f = findFig(stereotype);
if (f != null) {
removeFig(f);
f.removeFromDiagram(); // or vice versa?
--stereotypeCount;
}
} else {
LOG.warn("Unexpected property " + event.getPropertyName());
}
}
}
/**
* Keep the Figs which are likely invisible at the end of the list.
*/
private void reorderStereotypeFigs() {
List<Fig> allFigs = getFigs();
List<Fig> figsWithIcon = new ArrayList<Fig>();
List<Fig> figsWithOutIcon = new ArrayList<Fig>();
List<Fig> others = new ArrayList<Fig>();
// TODO: This doesn't do anything special with keywords.
// They should probably go first.
for (Fig f : allFigs) {
if (f instanceof FigStereotype) {
FigStereotype s = (FigStereotype) f;
if (getIconForStereotype(s) != null) {
figsWithIcon.add(s);
} else {
figsWithOutIcon.add(s);
}
} else {
others.add(f);
}
}
List<Fig> n = new ArrayList<Fig>();
n.addAll(others);
n.addAll(figsWithOutIcon);
n.addAll(figsWithIcon);
setFigs(n);
}
private FigStereotype findFig(Object stereotype) {
for (Object f : getFigs()) {
if (f instanceof FigStereotype) {
FigStereotype fs = (FigStereotype) f;
if (fs.getOwner() == stereotype) {
return fs;
}
}
}
return null;
}
/**
* Get all the child figs that represent the individual stereotypes
* @return a List of the stereotype Figs
*/
List<FigStereotype> getStereotypeFigs() {
final List<FigStereotype> stereotypeFigs =
new ArrayList<FigStereotype>();
for (Object f : getFigs()) {
if (f instanceof FigStereotype) {
FigStereotype fs = (FigStereotype) f;
stereotypeFigs.add(fs);
}
}
return stereotypeFigs;
}
private FigKeyword findFigKeyword() {
for (Object f : getFigs()) {
if (f instanceof FigKeyword) {
return (FigKeyword) f;
}
}
return null;
}
/**
* TODO: This should become private and only called from constructor
*
* @see org.argouml.uml.diagram.ui.FigCompartment#populate()
*/
public void populate() {
stereotypeCount = 0;
Object modelElement = getOwner();
if (modelElement == null) {
// TODO: This block can be removed after issue 4075 is tackled
LOG.debug("Cannot populate the stereotype compartment "
+ "unless the parent has an owner.");
return;
}
if (LOG.isDebugEnabled()) {
LOG.debug("Populating stereotypes compartment for "
+ Model.getFacade().getName(modelElement));
}
/* This will contain the Figs that we do not need anymore: */
Collection<Fig> removeCollection = new ArrayList<Fig>(getFigs());
//There is one fig more in the group than (stereotypes + keyword):
if (keyword != null) {
FigKeyword keywordFig = findFigKeyword();
if (keywordFig == null) {
// The keyword fig does not exist yet.
// Let's create one:
keywordFig =
new FigKeyword(keyword,
getBoundsForNextStereotype(),
getSettings());
// bounds not relevant here
addFig(keywordFig);
} else {
// The keyword fig already exists.
removeCollection.remove(keywordFig);
}
++stereotypeCount;
}
for (Object stereo : Model.getFacade().getStereotypes(modelElement)) {
FigStereotype stereotypeTextFig = findFig(stereo);
if (stereotypeTextFig == null) {
stereotypeTextFig =
new FigStereotype(stereo,
getBoundsForNextStereotype(),
getSettings());
// bounds not relevant here
addFig(stereotypeTextFig);
} else {
// The stereotype fig already exists.
removeCollection.remove(stereotypeTextFig);
}
++stereotypeCount;
}
//cleanup of unused FigText's
for (Fig f : removeCollection) {
if (f instanceof FigStereotype || f instanceof FigKeyword) {
removeFig(f);
}
}
reorderStereotypeFigs();
// remove all stereotypes that have a graphical icon
updateHiddenStereotypes();
}
/**
* Get the number of stereotypes contained in this group
* @return the number of stereotypes in this group
*/
public int getStereotypeCount() {
return stereotypeCount;
}
private Rectangle getBoundsForNextStereotype() {
return new Rectangle(
bigPort.getX() + 1,
bigPort.getY() + 1
+ (stereotypeCount
* ROWHEIGHT),
0,
ROWHEIGHT - 2);
}
private void updateHiddenStereotypes() {
List<Fig> figs = getFigs();
for (Fig f : figs) {
if (f instanceof FigStereotype) {
FigStereotype fs = (FigStereotype) f;
fs.setVisible(getIconForStereotype(fs) == null
|| !isHidingStereotypesWithIcon());
}
}
}
private Image getIconForStereotype(FigStereotype fs) {
// TODO: Find a way to replace this dependency on Project
Project project = getProject();
if (project == null) {
LOG.warn("getProject() returned null");
return null;
}
Object owner = fs.getOwner();
if (owner == null) {
// keywords which look like a stereotype (e.g. <<interface>>) have
// no owner
return null;
} else {
return project.getProfileConfiguration().getFigNodeStrategy()
.getIconForStereotype(owner);
}
}
/*
* @see org.tigris.gef.presentation.Fig#setBoundsImpl(int, int, int, int)
*/
@Override
protected void setBoundsImpl(int x, int y, int w, int h) {
Rectangle oldBounds = getBounds();
Dimension minimumSize = getMinimumSize();
int newW = Math.max(w, minimumSize.width);
int newH = Math.max(h, minimumSize.height);
int yy = y;
for (Fig fig : (Collection<Fig>) getFigs()) {
if (fig != bigPort) {
fig.setBounds(x, yy, newW,
fig.getMinimumSize().height);
yy += fig.getMinimumSize().height;
}
}
bigPort.setBounds(x, y, newW, newH);
calcBounds();
firePropChange("bounds", oldBounds, getBounds());
}
/**
* Allows a parent Fig to specify some keyword text to display amongst the
* stereotypes.
* An example of this usage is to display <<interface>>
* on FigInterface.
* @param word the text of the pseudo stereotype
*/
public void setKeyword(String word) {
keyword = word;
populate();
}
/**
* @return true if textual stereotypes are being hidden in preference to
* displaying icon.
*/
public boolean isHidingStereotypesWithIcon() {
return hidingStereotypesWithIcon;
}
/**
* Turn on/off textual stereotype display in preference to icon.
*
* @param hideStereotypesWithIcon true to hide textual stereotypes and
* show icon instead.
*/
public void setHidingStereotypesWithIcon(boolean hideStereotypesWithIcon) {
this.hidingStereotypesWithIcon = hideStereotypesWithIcon;
updateHiddenStereotypes();
}
@Override
public Dimension getMinimumSize() {
// if there are no stereotypes, we return (0,0), preventing
// double lines in the class (see issue 4939)
Dimension dim = null;
Object modelElement = getOwner();
if (modelElement != null) {
List<FigStereotype> stereos = getStereotypeFigs();
if (stereos.size() > 0 || keyword != null) {
int minWidth = 0;
int minHeight = 0;
//set new bounds for all included figs
for (Fig fig : (Collection<Fig>) getFigs()) {
if (fig.isVisible() && fig != bigPort) {
int fw = fig.getMinimumSize().width;
if (fw > minWidth) {
minWidth = fw;
}
minHeight += fig.getMinimumSize().height;
}
}
minHeight += 2; // 2 Pixel padding after compartment
dim = new Dimension(minWidth, minHeight);
}
}
if (dim == null) {
dim = new Dimension(0, 0);
}
return dim;
}
}
| 35.269639 | 80 | 0.58223 |
0049810e0d561465a497415952f580cc919fdec3 | 2,274 | /*
* Copyright Verizon Media, Licensed under the terms of the Apache License, Version 2.0. See LICENSE file in project root for terms.
*/
package com.yahoo.cubed.pipeline.launch;
import com.yahoo.cubed.pipeline.command.CommandExecutor;
import lombok.Getter;
import lombok.Setter;
import lombok.extern.slf4j.Slf4j;
/**
* Launch pipeline.
*/
@Slf4j
public class PipelineLauncher extends CommandExecutor<PipelineLauncher.LaunchStatus> {
private static final String OOZIE_JOB_ID_IDENTIFIER = "[[ID]]";
private static final String OOZIE_JOB_ID_FOR_BACKFILL_IDENTIFIER = "[[BACKFILLID]]";
/**
* Stores launch status.
*/
public static class LaunchStatus extends CommandExecutor.Status {
/** Oozie job ID. */
public String oozieJobId;
/** Oozie backfill job ID. */
public String oozieJobIdOfBackfill;
}
/**
* Create a new pipeline launch status.
*/
@Override
protected PipelineLauncher.LaunchStatus newStatus() {
return new PipelineLauncher.LaunchStatus();
}
@Getter @Setter
private String pipelineName;
@Getter @Setter
private String pipelineVersion;
@Getter @Setter
private String pipelineOwner;
@Getter @Setter
private String pipelineResourcePath;
@Getter @Setter
private String pipelineBackfillStartDate;
@Getter @Setter
private String pipelineOozieJobType;
@Getter @Setter
private String pipelineOozieBackfillJobType;
@Override
protected void checkInfoHook(String line, PipelineLauncher.LaunchStatus status) {
if (line.startsWith(OOZIE_JOB_ID_IDENTIFIER)) {
status.oozieJobId = line.substring(OOZIE_JOB_ID_IDENTIFIER.length());
} else if (line.startsWith(OOZIE_JOB_ID_FOR_BACKFILL_IDENTIFIER)) {
status.oozieJobIdOfBackfill = line.substring(OOZIE_JOB_ID_FOR_BACKFILL_IDENTIFIER.length());
}
};
@Override
protected void setCommand(ProcessBuilder processBuilder) {
processBuilder.command("sh", this.getScriptFileName(), this.getPipelineName(), this.getPipelineVersion(), this.getPipelineOwner(), this.getPipelineResourcePath(), this.pipelineBackfillStartDate, this.pipelineOozieJobType, this.pipelineOozieBackfillJobType);
}
}
| 33.940299 | 265 | 0.721196 |
1e62b0994783ca36a529ab3d460280a5d534f599 | 3,867 | /*
* 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.logging.log4j.util;
import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.condition.EnabledIfSystemProperty;
import org.junit.jupiter.api.parallel.ResourceLock;
import org.junit.jupiter.api.parallel.Resources;
import java.lang.reflect.Field;
import java.lang.reflect.Modifier;
import static org.junit.jupiter.api.Assertions.*;
/**
* Tests that the Unbox ring buffer size is configurable.
* Must be run in a separate process as the other UnboxTest or the last-run test will fail.
* Run this test on its own via {@code mvn --projects log4j-api test -Dtest=Unbox2ConfigurableTest} which will automatically
* enable the test, too.
*/
@EnabledIfSystemProperty(named = "test", matches = ".*Unbox2ConfigurableTest.*")
@ResourceLock(Resources.SYSTEM_PROPERTIES)
public class Unbox2ConfigurableTest {
@BeforeAll
public static void beforeClass() {
System.setProperty("log4j.unbox.ringbuffer.size", "65");
}
@AfterAll
public static void afterClass() throws Exception {
System.clearProperty("log4j.unbox.ringbuffer.size");
// ensure subsequent tests (which assume 32 slots) pass
final Field field = Unbox.class.getDeclaredField("RINGBUFFER_SIZE");
field.setAccessible(true); // make non-private
final Field modifierField = Field.class.getDeclaredField("modifiers");
modifierField.setAccessible(true);
modifierField.setInt(field, field.getModifiers() &~ Modifier.FINAL); // make non-final
field.set(null, 32); // reset to default
final Field threadLocalField = Unbox.class.getDeclaredField("threadLocalState");
threadLocalField.setAccessible(true);
final ThreadLocal<?> threadLocal = (ThreadLocal<?>) threadLocalField.get(null);
threadLocal.remove();
threadLocalField.set(null, new ThreadLocal<>());
}
@Test
public void testBoxConfiguredTo128Slots() {
// next power of 2 that is 65 or more
assertEquals(128, Unbox.getRingbufferSize());
}
@Test
public void testBoxSuccessfullyConfiguredTo128Slots() {
final int MAX = 128;
final StringBuilder[] probe = new StringBuilder[MAX * 3];
for (int i = 0; i <= probe.length - 8; ) {
probe[i++] = Unbox.box(true);
probe[i++] = Unbox.box('c');
probe[i++] = Unbox.box(Byte.MAX_VALUE);
probe[i++] = Unbox.box(Double.MAX_VALUE);
probe[i++] = Unbox.box(Float.MAX_VALUE);
probe[i++] = Unbox.box(Integer.MAX_VALUE);
probe[i++] = Unbox.box(Long.MAX_VALUE);
probe[i++] = Unbox.box(Short.MAX_VALUE);
}
for (int i = 0; i < probe.length - MAX; i++) {
assertSame(probe[i], probe[i + MAX], "probe[" + i +"], probe[" + (i + MAX) +"]");
for (int j = 1; j < MAX - 1; j++) {
assertNotSame(probe[i], probe[i + j], "probe[" + i +"], probe[" + (i + j) +"]");
}
}
}
} | 41.580645 | 124 | 0.668994 |
67d6b84f40bf732eee83633143c23e44daa66939 | 2,476 | package com.clsaa.dop.server.permission;
/**
* 权限管理的切面类
*
* @author lzy
*/
import com.clsaa.dop.server.permission.annotation.GetUserId;
import com.clsaa.dop.server.permission.annotation.PermissionName;
import com.clsaa.dop.server.permission.service.AuthenticationService;
import com.clsaa.dop.server.permission.service.PermissionService;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import java.lang.annotation.Annotation;
import java.lang.reflect.Method;
@Aspect
@Component
public class Authentication {
@Autowired
AuthenticationService authenticService;
@Autowired
PermissionService permissionService;
// 第一个参数: args(userId, ..)
// 第二个参数: args(*, userId, ..)
// 第三个参数: args(*, *, userId, ..)
@Pointcut("@annotation(com.clsaa.dop.server.permission.annotation.PermissionName)" )
public void getAnnotation() {
}
@Around("getAnnotation()&&@annotation(permissionName)")
public Object check(ProceedingJoinPoint pjp, PermissionName permissionName) {
Object obj ;
String name=permissionName.name();
Object[] args=pjp.getArgs();
Method method = MethodSignature.class.cast(pjp.getSignature()).getMethod();
StringBuilder userId = new StringBuilder();
Annotation[][] parameterAnnotations = method.getParameterAnnotations();
for (int argIndex = 0; argIndex < args.length; argIndex++) {
for (Annotation paramAnnotation : parameterAnnotations[argIndex]) {
if (!(paramAnnotation instanceof GetUserId)) {
continue;
}
userId.append(args[argIndex]);
}
}
if(userId.toString().isEmpty()) return false;
System.out.println("切入了 ,下面执行feign调用");
try {
if(permissionService.checkUserPermission(name,Long.parseLong(userId.toString())))
{
System.out.println("可以执行切点!!!!!!!!!!");
obj=pjp.proceed();
}
else
{
obj=false;
}
}
catch (Throwable throwable)
{
return throwable;
}
return obj;
}
}
| 28.790698 | 93 | 0.650242 |
ce36ddf4d0e628936252c5e6d370d132302efda9 | 2,547 | /**
* Copyright 2013 Canada Health Infoway, 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.
*
* Author: $LastChangedBy: tmcgrady $
* Last modified: $LastChangedDate: 2012-03-06 13:41:31 -0500 (Tue, 06 Mar 2012) $
* Revision: $LastChangedRevision: 5770 $
*/
package ca.infoway.messagebuilder.generator.mif2.vocabulary;
import java.util.List;
import org.simpleframework.xml.Attribute;
import org.simpleframework.xml.Element;
import org.simpleframework.xml.ElementList;
import org.simpleframework.xml.Namespace;
import org.simpleframework.xml.Root;
@Root(strict=false)
@Namespace(prefix="mif",reference="urn:hl7-org:v3/mif2")
public class MifCodeSystemConcept {
@Attribute(required=false,name="isSelectable")
private boolean selectable = true;
@Element(required=false)
private MifAnnotations annotations;
@ElementList(required=false,inline=true,entry="conceptRelationship")
private List<MifConceptRelationship> relationships;
@ElementList(required=false,inline=true,entry="printName")
private List<MifConceptPrintName> printNames;
@ElementList(required=false,inline=true,entry="code")
private List<MifCode> codes;
public boolean isSelectable() {
return selectable;
}
public void setSelectable(boolean selectable) {
this.selectable = selectable;
}
public MifAnnotations getAnnotations() {
return annotations;
}
public void setAnnotations(MifAnnotations annotations) {
this.annotations = annotations;
}
public List<MifConceptRelationship> getRelationships() {
return relationships;
}
public void setRelationships(List<MifConceptRelationship> relationships) {
this.relationships = relationships;
}
public List<MifConceptPrintName> getPrintNames() {
return printNames;
}
public void setPrintNames(List<MifConceptPrintName> printNames) {
this.printNames = printNames;
}
public List<MifCode> getCodes() {
return codes;
}
public void setCodes(List<MifCode> codes) {
this.codes = codes;
}
}
| 33.513158 | 83 | 0.742442 |
1bdc2163ee087552f9ec06cf05830fa6b9e8efe6 | 2,858 | package com.softicar.platform.db.structure.foreign.key;
import com.softicar.platform.db.core.table.DbTableName;
import com.softicar.platform.db.structure.table.IDbTableStructureFeature;
import java.util.List;
import java.util.Map;
/**
* Describes the structure of a foreign key of a database table.
*
* @author Oliver Richers
* @author Alexander Schmidt
*/
public interface IDbForeignKeyStructure extends IDbTableStructureFeature {
/**
* Returns a {@link List} of all {@link DbForeignKeyColumnPair} elements.
* <p>
* The order of the pairs in this list reflects the order in which the
* columns physically occur in the foreign key.
*
* @return all columns names (never null)
*/
List<DbForeignKeyColumnPair> getColumnPairs();
/**
* Returns a {@link List} of the physical names of the source columns
* covered by this foreign key.
* <p>
* The order of the columns in this list reflects the order in which the
* columns physically occur in the foreign key. This order is important when
* matching those columns to the columns in the target table.
*
* @return all columns names (never null)
*/
List<String> getColumns();
/**
* Returns a {@link List} of the physical names of the target columns
* covered by this foreign key.
* <p>
* The order of the columns in this list reflects the order in which the
* columns physically occur in the foreign key.
*
* @return all foreign columns names (never null)
*/
List<String> getForeignColumns();
/**
* Returns the name of the foreign database table.
*
* @return the name of the foreign database table (never null)
*/
DbTableName getForeignTableName();
/**
* Returns the physical name of the foreign column to which the column with
* the given physical name points.
*
* @param column
* the physical column name (never null)
* @return the physical name of the foreign column (may be null)
*/
String getForeignColumnName(String column);
/**
* Returns a {@link Map} that associates physical column names of the source
* table with referenced physical column names of the target table.
*
* @return a map of physical column names, with source table columns as
* keys, and foreign table columns as values (never null)
*/
Map<String, String> getColumnNameMap();
/**
* Returns the {@link DbForeignKeyAction} to perform upon deletion of the
* referenced record.
*
* @return the {@link DbForeignKeyAction} to perform upon deletion of the
* referenced record (never null)
*/
DbForeignKeyAction getOnDeleteAction();
/**
* Returns the {@link DbForeignKeyAction} to perform upon update of the
* referenced value.
*
* @return the {@link DbForeignKeyAction} to perform upon update of the
* referenced value (never null)
*/
DbForeignKeyAction getOnUpdateAction();
}
| 30.731183 | 77 | 0.714136 |
ecf785dc66b60e06c51705e2de8fb3f22cef8783 | 12,537 | package fr.insee.stamina.national;
import fr.insee.stamina.utils.Names;
import fr.insee.stamina.utils.XKOS;
import org.apache.jena.rdf.model.*;
import org.apache.jena.sparql.vocabulary.FOAF;
import org.apache.jena.vocabulary.DC;
import org.apache.jena.vocabulary.DCTerms;
import org.apache.jena.vocabulary.RDFS;
import org.apache.jena.vocabulary.SKOS;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.WorkbookFactory;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Iterator;
/**
* The <code>SBIModelMaker</code> class creates and saves the Jena model corresponding to the Dutch SBI 2008 classification.
*
* @author Franck Cotton
*/
public class SBIModelMaker {
/** Base local folder for reading and writing files */
public static String LOCAL_FOLDER = "src/main/resources/data/";
/** File name of the spreadsheet containing the SBI structure */
public static String SBI_FILE = "sbi 2008 versie 2016 engels.xls";
/** Base URI for the RDF resources belonging to NAICS */
public final static String BASE_URI = "http://stamina-project.org/codes/sbi2008/";
/** Base URI for the RDF resources belonging to the NACE-SBI correspondence */
public final static String NACE_SBI_BASE_URI = "http://stamina-project.org/codes/nacer2-sbi2008/";
/** Log4J2 logger */ // This must be before the configuration initialization
private static final Logger logger = LogManager.getLogger(SBIModelMaker.class);
/** Current Jena model */
private Model model = null;
/** RDF resource corresponding to the classification scheme */
Resource scheme = null;
/** List of RDF resources corresponding to the classification levels */
RDFList levelList = null;
/**
* Main method: reads the spreadsheet and creates the triplets in the model.
*/
public static void main(String[] args) throws Exception {
SBIModelMaker modelMaker = new SBIModelMaker();
// Creation of the classification and its levels
modelMaker.initializeModel();
modelMaker.createClassificationAndLevels();
modelMaker.populateScheme();
modelMaker.writeModel(LOCAL_FOLDER + "sbi2008.ttl");
modelMaker.initializeModel();
modelMaker.createNACESBIHierarchy();
modelMaker.writeModel(LOCAL_FOLDER + "nacer2-sbi2008.ttl");
}
/**
* Creates the statements corresponding to the classification items.
*
* @throws Exception In case of problem.
*/
private void populateScheme() throws Exception {
// Read the Excel file and create the classification items
InputStream sourceFile = new FileInputStream(LOCAL_FOLDER + SBI_FILE);
Sheet items = WorkbookFactory.create(sourceFile).getSheetAt(0);
try {sourceFile.close();} catch(Exception ignored) {}
Iterator<Row> rows = items.rowIterator ();
while (rows.hasNext() && rows.next().getRowNum() < 2); // Skip the header lines
while (rows.hasNext()) {
Row row = rows.next();
// The code and label are in the first cell, separated by the first space
String line = row.getCell(0, Row.MissingCellPolicy.CREATE_NULL_AS_BLANK).toString();
// Skip empty lines
if (line == null) continue;
int firstSpace = line.indexOf(' ');
String itemCode = line.substring(0, firstSpace);
String itemLabel = line.substring(firstSpace + 1).trim();
int level = getItemLevelDepth(itemCode);
// Create the resource representing the classification item (skos:Concept), with its code and label
Resource itemResource = model.createResource(getItemURI(itemCode), SKOS.Concept);
itemResource.addProperty(SKOS.notation, itemCode);
itemResource.addProperty(SKOS.prefLabel, itemLabel, "en");
// Attach the item to its level
Resource levelResource = (Resource) levelList.get(level - 1);
levelResource.addProperty(SKOS.member, itemResource);
// Attach the item to its classification
itemResource.addProperty(SKOS.inScheme, scheme);
if (level == 1) {
scheme.addProperty(SKOS.hasTopConcept, itemResource);
itemResource.addProperty(SKOS.topConceptOf, scheme);
}
// Attach the item to its parent item (for level > 1)
if (level > 1) {
Resource parentResource = model.createResource(getItemURI(getParentCode(itemCode)));
parentResource.addProperty(SKOS.narrower, itemResource);
itemResource.addProperty(SKOS.broader, parentResource);
}
}
}
/**
* Creates a model containing the resources representing the correspondence between NACE and SBI.
*/
private void createNACESBIHierarchy() throws Exception {
// Read the Excel file and create the classification items
InputStream sourceFile = new FileInputStream(SBI_FILE);
Sheet items = WorkbookFactory.create(sourceFile).getSheetAt(0);
try {sourceFile.close();} catch(Exception ignored) {}
// Creation of the correspondence table resource
Resource table = model.createResource(NACE_SBI_BASE_URI + "correspondence", XKOS.Correspondence);
table.addProperty(SKOS.definition, "Correspondence table between NACE Rev. 2 and SBI 2008");
table.addProperty(XKOS.compares, model.createResource(Names.getCSURI("NACE", "2")));
table.addProperty(XKOS.compares, model.createResource(BASE_URI + "sbi"));
Iterator<Row> rows = items.rowIterator ();
while (rows.hasNext() && rows.next().getRowNum() < 2); // Skip the header lines
while (rows.hasNext()) {
Row row = rows.next();
String line = row.getCell(0, Row.MissingCellPolicy.CREATE_NULL_AS_BLANK).toString();
if (line == null) continue;
int firstSpace = line.indexOf(' ');
String sbiCode = line.substring(0, firstSpace);
String naceCode = sbiToNACECode(sbiCode);
Resource association = model.createResource(NACE_SBI_BASE_URI + "association/" + naceCode + "-" + sbiCode, XKOS.ConceptAssociation);
association.addProperty(RDFS.label, "NACE Rev.2 " + naceCode + " - SBI 2008 " + sbiCode);
Resource naceItemResource = model.createResource(Names.getItemURI(naceCode, "NACE", "2"));
Resource sbiItemResource = model.createResource(getItemURI(sbiCode));
association.addProperty(XKOS.sourceConcept, naceItemResource);
association.addProperty(XKOS.targetConcept, sbiItemResource);
// TODO When is it exact match?
naceItemResource.addProperty(SKOS.narrowMatch, sbiItemResource);
sbiItemResource.addProperty(SKOS.broadMatch, naceItemResource);
table.addProperty(XKOS.madeOf, association);
}
}
/**
* Creates in the model the resources representing the classification and its levels.
*/
public void createClassificationAndLevels() {
// Create the resource representing the classification (skos:ConceptScheme)
scheme = model.createResource(BASE_URI + "sbi", SKOS.ConceptScheme);
scheme.addProperty(SKOS.prefLabel, model.createLiteral("Dutch Standaard Bedrijfsindeling (SBI) 2008", "en")); // TODO Not really English
scheme.addProperty(SKOS.notation, "SBI 2008"); // TODO What distinguishes annual versions?
scheme.addProperty(SKOS.definition, model.createLiteral("The Standard Industrial Classification is a classification of economic activities designed by the Central Bureau of Statistics of the Netherlands (CBS) that aims to provide a uniform classification of the economy for the benefit of detailed economic analyzes and statistics.", "en"));
scheme.addProperty(DC.publisher, model.createResource("http://www.cbs.nl"));
scheme.addProperty(DCTerms.issued, model.createTypedLiteral("2008-01-01", "http://www.w3.org/2001/XMLSchema#date"));
scheme.addProperty(DCTerms.modified, model.createTypedLiteral("2016-01-01", "http://www.w3.org/2001/XMLSchema#date"));
scheme.addProperty(FOAF.homepage, model.createResource("https://www.cbs.nl/en-gb/our-services/methods/classifications/activiteiten/standard-industrial-classifications--dutch-sbi-2008-nace-and-isic--"));
scheme.addProperty(XKOS.covers, model.createResource("http://eurovoc.europa.eu/5992"));
scheme.addProperty(XKOS.numberOfLevels, model.createTypedLiteral(5));
// Create the resources representing the levels (xkos:ClassificationLevel)
Resource level1 = model.createResource(BASE_URI + "/sections", XKOS.ClassificationLevel);
level1.addProperty(SKOS.prefLabel, model.createLiteral("SBI 2008 - level 1 - Sections", "en"));
level1.addProperty(XKOS.depth, model.createTypedLiteral(1));
level1.addProperty(XKOS.notationPattern, "[A-U]");
level1.addProperty(XKOS.organizedBy, model.createResource("http://stamina-project.org/concepts/sbi2008/section"));
Resource level2 = model.createResource(BASE_URI + "/divisions", XKOS.ClassificationLevel);
level2.addProperty(SKOS.prefLabel, model.createLiteral("SBI 2008 - level 2 - Divisions", "en"));
level2.addProperty(XKOS.depth, model.createTypedLiteral(2));
level2.addProperty(XKOS.notationPattern, "[0-9]{2}");
level2.addProperty(XKOS.organizedBy, model.createResource("http://stamina-project.org/concepts/sbi2008/division"));
Resource level3 = model.createResource(BASE_URI + "/groups", XKOS.ClassificationLevel);
level3.addProperty(SKOS.prefLabel, model.createLiteral("SBI 2008 - level 3 - Groups", "en"));
level3.addProperty(XKOS.depth, model.createTypedLiteral(3));
level3.addProperty(XKOS.notationPattern, "[0-9]{3}");
level3.addProperty(XKOS.organizedBy, model.createResource("http://stamina-project.org/concepts/sbi2008/group"));
Resource level4 = model.createResource(BASE_URI + "/classes", XKOS.ClassificationLevel);
level4.addProperty(SKOS.prefLabel, model.createLiteral("SBI 2008 - level 4 - Classes", "en"));
level4.addProperty(XKOS.depth, model.createTypedLiteral(4));
level4.addProperty(XKOS.notationPattern, "[0-9]{4}");
level4.addProperty(XKOS.organizedBy, model.createResource("http://stamina-project.org/concepts/sbi2008/class"));
Resource level5 = model.createResource(BASE_URI + "/subclasses", XKOS.ClassificationLevel);
level5.addProperty(SKOS.prefLabel, model.createLiteral("SBI 2008 - level 5 - Subclasses", "en"));
level5.addProperty(XKOS.depth, model.createTypedLiteral(5));
level5.addProperty(XKOS.notationPattern, "[0-9]{5}");
level5.addProperty(XKOS.organizedBy, model.createResource("http://stamina-project.org/concepts/sbi2008/subclass"));
// Attach the level list to the classification
levelList = model.createList(level1, level2, level3, level4, level5);
scheme.addProperty(XKOS.levels, levelList);
}
/**
* Initializes the Jena model and adds standard prefixes.
*/
private void initializeModel() {
try {
if (model != null) model.close(); // Just in case
} catch (Exception ignored) {}
model = ModelFactory.createDefaultModel();
model.setNsPrefix("rdfs", RDFS.getURI());
model.setNsPrefix("skos", SKOS.getURI());
model.setNsPrefix("xkos", XKOS.getURI());
logger.debug("Jena model initialized");
}
/**
* Writes the model to the output Turtle file.
*
* @throws IOException In case of problem writing the file
*/
private void writeModel(String fileName) throws IOException {
model.write(new FileOutputStream(fileName), "TTL");
// Close the model
model.close();
}
/**
* Computes the parent code for one given SBI code.
*/
private static String getParentCode(String code) {
if ((code.length() == 1) || (code.length() > 5)) return null;
if (code.length() == 2) return Names.getNACESectionForDivision(code);
// For codes of length 3 to 5, parent code is the child code truncated on the right
return code.substring(0, code.length() - 1);
}
/**
* Computes the NACE code corresponding to a SBI code.
*
* @param sbiCode A SBI code.
* @return The NACE code corresponding to the SBI code.
*/
public static String sbiToNACECode(String sbiCode) {
// TODO
return sbiCode;
}
/**
* Computes the URI of a SBI classification item.
*
* @param code The item code.
* @return The item URI.
*/
private static String getItemURI(String code) {
int level = getItemLevelDepth(code);
if (level == 1) return BASE_URI + "section/" + code;
if (level == 2) return BASE_URI + "division/" + code;
if (level == 3) return BASE_URI + "group/" + code;
if (level == 4) return BASE_URI + "class/" + code;
if (level == 5) return BASE_URI + "subclass/" + code; // TODO Check this
return null;
}
/**
* Returns the depth of the level to which an item belongs.
*
* @param code The item code.
* @return The depth of the level.
*/
public static int getItemLevelDepth(String code) {
return code.length();
}
}
| 41.376238 | 343 | 0.740369 |
f803af61d3f9ecaae05cd133c5db1e435b9ee3ea | 669 | package com.fernandocejas.android10.restrofit.enity;
import android.support.annotation.Nullable;
import com.google.auto.value.AutoValue;
import com.google.gson.Gson;
import com.google.gson.TypeAdapter;
import com.google.gson.annotations.SerializedName;
import java.util.Collection;
/**
* Created by jerry on Jan-18-18.
*/
@AutoValue
public abstract class GoogleGeoListEntityResponse {
@SerializedName("results")
@Nullable
public abstract Collection<GoogleGeoEntity> results();
public static TypeAdapter<GoogleGeoListEntityResponse> typeAdapter(Gson gson) {
return new AutoValue_GoogleGeoListEntityResponse.GsonTypeAdapter(gson);
}
}
| 25.730769 | 83 | 0.784753 |
647bbc728273eeafcc5df15ac0d3e6fbd61afe88 | 141 | package com.hive.apps.cleveler.cnc;
public class CNCStatus {
public double x = 0;
public double y = 0;
public double z = 0;
}
| 14.1 | 35 | 0.64539 |
6f3b6fcccfe24ed392d979c34cc91212e69d419a | 369 | package net.eduard.api.lib.storage.annotations;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Target({java.lang.annotation.ElementType.FIELD})
@Retention(RetentionPolicy.RUNTIME)
public @interface StorageReference {
boolean mapKey() default true;
boolean mapValue() default false;
}
| 26.357143 | 49 | 0.799458 |
34dcd53069e5c21f71271d217c5020148ba66a47 | 1,487 | package de.huddeldaddel.sudoku.game;
import java.util.Arrays;
public class FieldValidator {
private final Field field;
FieldValidator(Field field) {
this.field = field;
}
public boolean isCompleted() {
return (0 == field.getEmptyCellCount()) && isValid();
}
public boolean isValid() {
return isFieldValidRegardingBlocks() &&
isFieldValidRegardingColumns() &&
isFieldValidRegardingRows();
}
private boolean isFieldValidRegardingBlocks() {
for(int column=0; column<7; column+=3)
for(int row=0; row<7; row+=3)
if(!isSectionValid(field.getBlock(column, row)))
return false;
return true;
}
private boolean isFieldValidRegardingColumns() {
for(int column=0; column<9; column++)
if(!isSectionValid(field.getColumn(column)))
return false;
return true;
}
private boolean isFieldValidRegardingRows() {
for(int row=0; row<9; row++)
if(!isSectionValid(field.getRow(row)))
return false;
return true;
}
private boolean isSectionValid(int[] section) {
Arrays.sort(section);
int last = section[0];
for(int index = 1; index < 9; index++) {
if(section[index] > 0 && last == section[index])
return false;
last = section[index];
}
return true;
}
}
| 26.087719 | 64 | 0.564896 |
fba213794e345609cd270d18f86de0c736b37436 | 1,798 | package com.skydoves.preferenceroomdemo.utils;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;
import com.skydoves.preferenceroomdemo.R;
import com.skydoves.preferenceroomdemo.models.ItemProfile;
import java.util.ArrayList;
import java.util.List;
/**
* Developed by skydoves on 2017-11-26.
* Copyright (c) 2017 skydoves rights reserved.
*/
public class ListViewAdapter extends BaseAdapter {
private int layout;
private LayoutInflater inflater;
private List<ItemProfile> profileList;
public ListViewAdapter(Context context, int layout) {
this.profileList = new ArrayList<>();
this.layout = layout;
this.inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
@Override
public int getCount() {
return profileList.size();
}
@Override
public Object getItem(int i) {
return profileList.get(i);
}
@Override
public long getItemId(int i) {
return i;
}
public void addItem(ItemProfile itemProfile) {
this.profileList.add(itemProfile);
notifyDataSetChanged();
}
@Override
public View getView(int index, View view, ViewGroup viewGroup) {
if(view == null)
view = this.inflater.inflate(layout, viewGroup, false);
ItemProfile itemProfile = profileList.get(index);
TextView title = view.findViewById(R.id.item_profile_title);
title.setText(itemProfile.getTitle());
TextView content = view.findViewById(R.id.item_profile_content);
content.setText(itemProfile.getContent());
return view;
}
}
| 26.441176 | 99 | 0.690768 |
2bc0568dc2bd78e1be5ad619f8c7f87deb1b4396 | 3,308 | /**
* Copyright 5AM Solutions Inc, ESAC, ScenPro & SAIC
*
* Distributed under the OSI-approved BSD 3-Clause License.
* See http://ncip.github.com/caintegrator/LICENSE.txt for details.
*/
package gov.nih.nci.caintegrator.common;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
/**
* This is a static utility class used for doing math functions.
*/
public final class MathUtil {
private MathUtil() {
}
/**
* Calculates the standard deviation.
* @param values to calculate std dev for.
* @param mean of the values.
* @return standard deviation.
*/
public static Double standardDeviation(List<Double> values, Double mean) {
Double totalSquaredDeviations = 0.0;
for (Double value : values) {
totalSquaredDeviations += Math.pow(value - mean, 2);
}
return Math.sqrt(mean(totalSquaredDeviations, values.size()));
}
/**
* Calculates the median for the list of numbers.
*
* @param list
* of numbers to calculate median for.
* @return median value.
*/
public static Double medianDouble(List<Double> list) {
if (list.size() == 1) {
return list.get(0);
}
Collections.sort(list);
int middle = list.size() / 2;
if (list.size() % 2 == 1) {
return list.get(middle);
} else {
return (list.get(middle - 1) + list.get(middle)) / 2.0;
}
}
/**
* Retrieves mean value of the list of floats.
*
* @param totalValue total value of the number.
* @param numValues number of values.
* @return mean value.
*/
public static Double mean(Double totalValue, int numValues) {
return numValues != 0 ? totalValue / numValues : 0;
}
/**
* Calculates the standard deviation.
* @param values to calculate std dev for.
* @param mean of the values.
* @return standard deviation.
*/
public static Double standardDeviation(float[] values, float mean) {
double totalSquaredDeviations = 0.0;
for (float value : values) {
totalSquaredDeviations += Math.pow(value - mean, 2);
}
return Math.sqrt(mean(totalSquaredDeviations, values.length));
}
/**
* Calculates the median for the list of numbers.
*
* @param values of numbers to calculate median for.
* @return median value.
*/
public static float median(float[] values) {
if (values.length == 1) {
return values[0];
}
Arrays.sort(values);
int middle = values.length / 2;
if (values.length % 2 == 1) {
return values[middle];
} else {
return (values[middle - 1] + values[middle]) / 2.0f;
}
}
/**
* Retrieves mean value of the list of floats.
*
* @param values of values.
* @return mean value.
*/
public static float mean(float[] values) {
float totalNumber = 0.0f;
for (float value : values) {
totalNumber += value;
}
return values.length == 0 ? 0 : totalNumber / values.length;
}
}
| 29.017544 | 79 | 0.562576 |
f1159c20cf6cd1d1cbee6f0634e9b69ba26e5d7f | 801 | package Methods.exercises;
import java.util.Locale;
import java.util.Scanner;
public class VowelsCount {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
String input = scanner.nextLine().toLowerCase();
String output = countSingleString(input);
System.out.println(output.length());
}
private static String countSingleString(String input){
String singleString = "";
for (int i = 0; i < input.length() ; i++) {
if (input.charAt(i) == 'a' || input.charAt(i) == 'e' || input.charAt(i) == 'o'
|| input.charAt(i) == 'u'|| input.charAt(i) == 'y' || input.charAt(i) == 'i' ){
singleString += input.charAt(i);
}
}
return singleString;
}
}
| 29.666667 | 91 | 0.56804 |
1d913b99bc2acad46f310b36371d44c6467ebf97 | 3,850 | package com.chii.www.controller;
import com.chii.www.Tool.SafeCode;
import com.chii.www.pojo.PageBean;
import com.chii.www.pojo.Sct;
import com.chii.www.pojo.Student;
import com.chii.www.pojo.Teacher;
import com.chii.www.service.CourseService;
import com.chii.www.service.UserService;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.SessionAttributes;
import javax.servlet.http.HttpServletRequest;
@Controller
@SessionAttributes({"username"})//放到Session属性列表中,以便这个属性可以跨请求访问
@RequestMapping("teacher")
public class TeacherController {
@Autowired
private UserService userService;
@Autowired
private CourseService courseService;
@ModelAttribute
private void addAttributes(Model model) {
model.addAttribute("role", "teacher");
}
@RequestMapping("/teacherIndex")
public String teacherUrl() {
return "teacher/teacherIndex";
}
@RequestMapping("/TeacherInfo")
public String TeacherInfoUrl(@ModelAttribute("username") String tno, Model model) {
System.out.println(tno);
model.addAttribute("teacher", userService.getTeaInfoById(tno));
model.addAttribute("mode", "update");
model.addAttribute("courses", courseService.getAllCourseInfo());
return "Info/TeacherInfo";
}
@RequestMapping("/ChangePassword")
public String ChangePasswordUrl(@ModelAttribute("username") String tno, Model model) {
model.addAttribute("userno", tno);
return "Info/ChangePassword";
}
@RequestMapping("/studentuser")
public String studentuserUrl(Model model) {
return "teacher/studentuser";
}
@RequestMapping(value = "/AllStudentUser")
@ResponseBody
public PageBean AllStudentUser(@ModelAttribute("username") String tno, PageBean page) {
page.setKey(tno);
PageInfo<Sct> pi = courseService.getSctInfoByTeaId(page);
page.setCurrent(page.getCurrent());
page.setRowCount(page.getRowCount());
page.setRows(pi.getList());
page.setTotal(pi.getTotal());
return page;
}
@RequestMapping("/scoreupdate")
@ResponseBody
public int scoreupdate(Sct sct) {
courseService.updateGradeInfo(sct);
// return "redirect:/admin/score";
return sct.getGrade();
}
@RequestMapping("/help")
public String helpUrl(Model model) {
return "/teacher/help";
}
@RequestMapping("/update")
public String teacherupdate(Teacher teacher, HttpServletRequest request, Model model) {
//加密密码
if (teacher.getPassword() != null) {
String password = SafeCode.PasswordHash(teacher.getPassword(), teacher.getTno());
teacher.setPassword(password);
}
userService.updateTeaInfo(teacher);
String returnURL = request.getHeader("Referer");
// System.out.println(returnURL);
model.addAttribute("msg", "更新成功");
if (returnURL.contains("admin")) {
return "redirect:/admin/teacheruser";
} else {
return "redirect:/teacher/TeacherInfo";
}
}
@RequestMapping("/insert")
public String teacherinsert(Teacher teacher, Model model) {
//加入默认密码
String password = SafeCode.PasswordHash("c6274012383f2674afbff44a332a8896", teacher.getTno());
teacher.setPassword(password);
userService.insertTeaInfo(teacher);
model.addAttribute("msg", "插入成功");
return "redirect:/admin/teacheruser";
}
}
| 33.478261 | 102 | 0.691429 |
87242c68499d272c246fc1df086a9749c7202902 | 917 | package io.dactilo.sumbawa.spring.spreadsheets.converter.api;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.OutputStream;
/**
* Serialize and send a {@link Spreadsheet} into a stream.
*/
public interface SpreadsheetStreamer {
/**
* Serialize and send a {@link Spreadsheet} into a stream.
*
* @param outputStream The stream to send the results to
* @param spreadsheet The spreadsheet
* @throws IOException If any IO error occurs
*/
void streamSpreadsheet(OutputStream outputStream, Spreadsheet spreadsheet) throws IOException;
default byte[] toByteArray(Spreadsheet spreadsheet) throws IOException {
try(final ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream()) {
streamSpreadsheet(byteArrayOutputStream, spreadsheet);
return byteArrayOutputStream.toByteArray();
}
}
}
| 33.962963 | 98 | 0.728462 |
dfc26f08b77d26fa4134ca1625e747f2857beab0 | 32,219 | /*
* Copyright (c) 2003, 2010, Dave Kriewall
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification, are permitted provided that the
* following conditions are met:
*
* 1) Redistributions of source code must retain the above copyright notice, this list of conditions and the following
* disclaimer.
*
* 2) Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following
* disclaimer in the documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
* INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
* WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE
* USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package com.wrq.rearranger.settings;
import com.wrq.rearranger.Rearranger;
import com.wrq.rearranger.settings.attributeGroups.AttributeGroup;
import com.wrq.rearranger.settings.attributeGroups.ClassAttributes;
import com.wrq.rearranger.settings.attributeGroups.GetterSetterDefinition;
import com.wrq.rearranger.settings.attributeGroups.ItemAttributes;
import org.apache.log4j.Logger;
import org.jdom.Attribute;
import org.jdom.Document;
import org.jdom.Element;
import org.jdom.JDOMException;
import org.jdom.input.SAXBuilder;
import org.jdom.output.XMLOutputter;
import org.jdom.output.Format;
import java.io.*;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import java.util.LinkedList;
import java.util.ListIterator;
/**
* Holds two lists of rearrangement settings, one for the outer level classes, the other for class members. Each
* list contains objects of type CommonAttributes.
*/
public final class RearrangerSettings
{
// ------------------------------ FIELDS ------------------------------
// BEGINNING OF FIELDS
public static final Logger logger = Logger.getLogger("com.wrq.rearranger.settings.RearrangerSettings");
public static final int OVERLOADED_ORDER_RETAIN_ORIGINAL = 0;
public static final int OVERLOADED_ORDER_ASCENDING_PARAMETERS = 1;
public static final int OVERLOADED_ORDER_DESCENDING_PARAMETERS = 2;
private final List<AttributeGroup> itemOrderAttributeList;
private final List<AttributeGroup> classOrderAttributeList;
private RelatedMethodsSettings relatedMethodsSettings;
private boolean keepGettersSettersTogether;
private boolean keepGettersSettersWithProperty;
private boolean keepOverloadedMethodsTogether;
private String globalCommentPattern;
private boolean askBeforeRearranging;
private boolean rearrangeInnerClasses;
private boolean showParameterTypes;
private boolean showParameterNames;
private boolean showFields;
private boolean showTypeAfterMethod;
private boolean showRules;
private boolean showMatchedRules;
private boolean showComments;
private ForceBlankLineSetting afterClassLBrace;
private ForceBlankLineSetting afterClassRBrace;
private ForceBlankLineSetting beforeClassRBrace;
private ForceBlankLineSetting beforeMethodLBrace;
private ForceBlankLineSetting afterMethodLBrace;
private ForceBlankLineSetting afterMethodRBrace;
private ForceBlankLineSetting beforeMethodRBrace;
private boolean removeBlanksInsideCodeBlocks;
private ForceBlankLineSetting newlinesAtEOF;
private int overloadedOrder;
private GetterSetterDefinition defaultGSDefinition;
private List<PrimaryMethodSetting> primaryMethodList;
// -------------------------- STATIC METHODS --------------------------
static public int getIntAttribute(final Element me, final String attr)
{
return getIntAttribute(me, attr, 0);
}
static public boolean getBooleanAttribute(final Element me, final String attr)
{
return getBooleanAttribute(me, attr, false);
}
public static RearrangerSettings getDefaultSettings()
{
logger.debug("enter loadDefaultSettings");
URL settingsURL = Rearranger.class.getClassLoader().getResource("com/wrq/rearranger/defaultConfiguration.xml");
logger.debug("settings URL=" + settingsURL.getFile());
try
{
InputStream is = settingsURL.openStream();
return getSettingsFromStream(is);
}
catch (IOException e)
{
logger.debug("getDefaultSettings:" + e);
return null;
}
}
public static RearrangerSettings getSettingsFromStream(InputStream is)
{
Document document = null;
try
{
SAXBuilder builder = new SAXBuilder();
document = builder.build(is);
}
catch (JDOMException jde)
{
logger.debug("JDOM exception building document:" + jde);
return null;
}
catch (IOException e)
{
logger.debug("I/O exception building document:" + e);
return null;
}
finally {
if (is != null) {
try
{
is.close();
}
catch (IOException e)
{
}
}
}
Element app = document.getRootElement();
Element component = null;
if (app.getName().equals("application")) {
ListIterator li = app.getChildren().listIterator();
while (li.hasNext())
// for (Element child : (List)((java.util.List)app.getChildren()))
{
Element child = (Element) li.next();
if (child.getName().equals("component") &&
child.getAttribute("name") != null &&
child.getAttribute("name").getValue().equals(Rearranger.COMPONENT_NAME))
{
component = child;
break;
}
}
}
else {
if (app.getName().equals("component") &&
app.getAttribute("name") != null &&
app.getAttribute("name").getValue().equals(Rearranger.COMPONENT_NAME))
{
component = app;
}
}
if (component != null) {
Element rearranger = component.getChild(Rearranger.COMPONENT_NAME);
if (rearranger != null) {
RearrangerSettings rs = new RearrangerSettings();
rs.readExternal(rearranger);
return rs;
}
}
return null;
}
// Level 1 methods
/**
* @param entry JDOM element named "Rearranger" which contains setting values as attributes.
*/
public final void readExternal(final Element entry)
{
final Element items = entry.getChild("Items" );
final Element classes = entry.getChild("Classes");
final List itemList = items.getChildren();
final List classList = classes.getChildren();
ListIterator li;
li = itemList.listIterator();
while (li.hasNext())
// for (Element element : itemList)
{
Element element = (Element) li.next();
itemOrderAttributeList.add(((com.wrq.rearranger.settings.attributeGroups.AttributeGroup)ItemAttributes.readExternal(element)));
}
li = classList.listIterator();
// for (Element element : classList)
while (li.hasNext())
{
Element element = (Element) li.next();
classOrderAttributeList.add(((com.wrq.rearranger.settings.attributeGroups.AttributeGroup)ClassAttributes.readExternal(element)));
}
final Element gsd = entry.getChild("DefaultGetterSetterDefinition");
defaultGSDefinition = GetterSetterDefinition.readExternal(gsd);
final Element relatedItems = entry.getChild("RelatedMethods");
relatedMethodsSettings = RelatedMethodsSettings.readExternal(relatedItems);
keepGettersSettersTogether = getBooleanAttribute(entry, "KeepGettersSettersTogether", true );
keepGettersSettersWithProperty = getBooleanAttribute(entry, "KeepGettersSettersWithProperty", false);
keepOverloadedMethodsTogether = getBooleanAttribute(entry, "KeepOverloadedMethodsTogether", true );
final Attribute attr = RearrangerSettings.getAttribute(entry, "globalCommentPattern");
askBeforeRearranging = getBooleanAttribute(entry, "ConfirmBeforeRearranging", false );
rearrangeInnerClasses = getBooleanAttribute(entry, "RearrangeInnerClasses", false );
globalCommentPattern = (attr == null ? "" : ((java.lang.String)attr.getValue()) );
overloadedOrder = getIntAttribute(entry, "overloadedOrder", OVERLOADED_ORDER_RETAIN_ORIGINAL);
showParameterTypes = getBooleanAttribute(entry, "ShowParameterTypes", true );
showParameterNames = getBooleanAttribute(entry, "ShowParameterNames", true );
showFields = getBooleanAttribute(entry, "ShowFields", true );
showRules = getBooleanAttribute(entry, "ShowRules", false );
showMatchedRules = getBooleanAttribute(entry, "ShowMatchedRules", false );
showComments = getBooleanAttribute(entry, "ShowComments", false );
showTypeAfterMethod = getBooleanAttribute(entry, "ShowTypeAfterMethod", true );
removeBlanksInsideCodeBlocks = getBooleanAttribute(entry, "RemoveBlanksInsideCodeBlocks", false);
afterClassLBrace = ForceBlankLineSetting.readExternal(entry, false, true, ForceBlankLineSetting.CLASS_OBJECT, "AfterClassLBrace" );
afterClassRBrace = ForceBlankLineSetting.readExternal(entry, false, false, ForceBlankLineSetting.CLASS_OBJECT, "AfterClassRBrace" );
beforeClassRBrace = ForceBlankLineSetting.readExternal(entry, true, false, ForceBlankLineSetting.CLASS_OBJECT, "BeforeClassRBrace" );
beforeMethodLBrace = ForceBlankLineSetting.readExternal(entry, true, true, ForceBlankLineSetting.METHOD_OBJECT, "BeforeMethodLBrace" );
afterMethodLBrace = ForceBlankLineSetting.readExternal(entry, false, true, ForceBlankLineSetting.METHOD_OBJECT, "AfterMethodLBrace" );
afterMethodRBrace = ForceBlankLineSetting.readExternal(entry, false, false, ForceBlankLineSetting.METHOD_OBJECT, "AfterMethodRBrace");
beforeMethodRBrace = ForceBlankLineSetting.readExternal(entry, true, false, ForceBlankLineSetting.METHOD_OBJECT, "BeforeMethodRBrace");
newlinesAtEOF = ForceBlankLineSetting.readExternal(entry, false, false, ForceBlankLineSetting.EOF_OBJECT, "NewlinesAtEOF" );
}
// Level 2 methods
static public Attribute getAttribute(Element element, String attributeName)
{
if (element == null) return null;
return element.getAttribute(attributeName);
}
static public int getIntAttribute(final Element item, final String attributeName, int defaultValue)
{
if (item == null) return defaultValue;
final Attribute a = item.getAttribute(attributeName);
if (a == null) return defaultValue;
final String r = a.getValue();
if (r == null) return defaultValue;
if (r.length() == 0 ) return defaultValue;
return Integer.parseInt(r);
}
static public boolean getBooleanAttribute(final Element me, final String attr, boolean defaultValue)
{
if (me == null) return defaultValue;
final Attribute a = me.getAttribute(attr);
if (a == null) return defaultValue;
final String r = a.getValue();
if (r == null) return defaultValue;
return (r.equalsIgnoreCase("true"));
}
public static RearrangerSettings getSettingsFromFile(File f)
{
try
{
return getSettingsFromStream(new FileInputStream(f));
}
catch (FileNotFoundException e)
{
logger.debug("getSettingsFromFile:" + e);
}
return null;
}
// --------------------------- CONSTRUCTORS ---------------------------
// END OF ALL FIELDS
public RearrangerSettings()
{
itemOrderAttributeList = new ArrayList<AttributeGroup>();
classOrderAttributeList = new ArrayList<AttributeGroup>();
relatedMethodsSettings = new RelatedMethodsSettings();
keepGettersSettersTogether = false;
keepGettersSettersWithProperty= false;
keepOverloadedMethodsTogether = false;
globalCommentPattern = "";
overloadedOrder = OVERLOADED_ORDER_RETAIN_ORIGINAL;
askBeforeRearranging = false;
rearrangeInnerClasses = false;
showParameterTypes = true;
showParameterNames = false;
showFields = true;
showTypeAfterMethod = true;
showRules = false;
showMatchedRules = false;
showComments = false;
removeBlanksInsideCodeBlocks = false;
afterClassLBrace = new ForceBlankLineSetting(false, true, ForceBlankLineSetting.CLASS_OBJECT, "AfterClassLBrace" );
afterClassRBrace = new ForceBlankLineSetting(false, false, ForceBlankLineSetting.CLASS_OBJECT, "AfterClassRBrace" );
beforeClassRBrace = new ForceBlankLineSetting(true, false, ForceBlankLineSetting.CLASS_OBJECT, "BeforeClassRBrace" );
beforeMethodLBrace = new ForceBlankLineSetting(true, true, ForceBlankLineSetting.METHOD_OBJECT, "BeforeMethodLBrace");
afterMethodLBrace = new ForceBlankLineSetting(false, true, ForceBlankLineSetting.METHOD_OBJECT, "AfterMethodLBrace" );
beforeMethodRBrace = new ForceBlankLineSetting(true, false, ForceBlankLineSetting.METHOD_OBJECT, "BeforeMethodRBrace");
afterMethodRBrace = new ForceBlankLineSetting(false, false, ForceBlankLineSetting.METHOD_OBJECT, "AfterMethodRBrace" );
newlinesAtEOF = new ForceBlankLineSetting(false, false, ForceBlankLineSetting.EOF_OBJECT, "NewlinesAtEOF");
defaultGSDefinition = new GetterSetterDefinition();
primaryMethodList = new LinkedList<PrimaryMethodSetting>();
}
// --------------------- GETTER / SETTER METHODS ---------------------
public ForceBlankLineSetting getAfterClassLBrace()
{
return afterClassLBrace;
}
public ForceBlankLineSetting getAfterClassRBrace()
{
return afterClassRBrace;
}
public ForceBlankLineSetting getBeforeMethodLBrace()
{
return beforeMethodLBrace;
}
public ForceBlankLineSetting getAfterMethodLBrace()
{
return afterMethodLBrace;
}
public ForceBlankLineSetting getAfterMethodRBrace()
{
return afterMethodRBrace;
}
public ForceBlankLineSetting getBeforeClassRBrace()
{
return beforeClassRBrace;
}
public ForceBlankLineSetting getBeforeMethodRBrace()
{
return beforeMethodRBrace;
}
public final List<AttributeGroup> getClassOrderAttributeList()
{
return classOrderAttributeList;
}
public GetterSetterDefinition getDefaultGSDefinition()
{
return defaultGSDefinition;
}
// Level 1 methods
public String getGlobalCommentPattern()
{
return globalCommentPattern;
}
// Level 2 methods
public void setGlobalCommentPattern(String globalCommentPattern)
{
this.globalCommentPattern = globalCommentPattern;
}
// end of Level 2 methods
// end of Level 1 methods
public final List<AttributeGroup> getItemOrderAttributeList()
{
return itemOrderAttributeList;
}
public ForceBlankLineSetting getNewlinesAtEOF()
{
return newlinesAtEOF;
}
// Level 1 methods
public int getOverloadedOrder()
{
return overloadedOrder;
}
// Level 2 methods
public void setOverloadedOrder(int overloadedOrder)
{
this.overloadedOrder = overloadedOrder;
}
// end of Level 2 methods
// end of Level 1 methods
public RelatedMethodsSettings getExtractedMethodsSettings()
{
return relatedMethodsSettings;
}
// Level 1 methods
public boolean isAskBeforeRearranging()
{
return askBeforeRearranging;
}
// Level 2 methods
public void setAskBeforeRearranging(boolean askBeforeRearranging)
{
this.askBeforeRearranging = askBeforeRearranging;
}
public boolean isKeepGettersSettersTogether()
{
return keepGettersSettersTogether;
}
// Level 2 methods
public void setKeepGettersSettersTogether(boolean keepGettersSettersTogether)
{
this.keepGettersSettersTogether = keepGettersSettersTogether;
}
public boolean isKeepGettersSettersWithProperty()
{
return keepGettersSettersWithProperty;
}
public void setKeepGettersSettersWithProperty(boolean keepGettersSettersWithProperty)
{
this.keepGettersSettersWithProperty = keepGettersSettersWithProperty;
}
// end of Level 2 methods
// end of Level 1 methods
// Level 1 methods
public boolean isKeepOverloadedMethodsTogether()
{
return keepOverloadedMethodsTogether;
}
// Level 2 methods
public void setKeepOverloadedMethodsTogether(boolean keepOverloadedMethodsTogether)
{
this.keepOverloadedMethodsTogether = keepOverloadedMethodsTogether;
}
// end of Level 2 methods
// end of Level 1 methods
// Level 1 methods
public boolean isRearrangeInnerClasses()
{
return rearrangeInnerClasses;
}
public void setRearrangeInnerClasses(boolean rearrangeInnerClasses)
{
this.rearrangeInnerClasses = rearrangeInnerClasses;
}
// end of Level 2 methods
// end of Level 1 methods
// Level 1 methods
public boolean isRemoveBlanksInsideCodeBlocks()
{
return removeBlanksInsideCodeBlocks;
}
// Level 2 methods
public void setRemoveBlanksInsideCodeBlocks(boolean removeBlanksInsideCodeBlocks)
{
this.removeBlanksInsideCodeBlocks = removeBlanksInsideCodeBlocks;
}
public boolean isShowComments()
{
return showComments;
}
public void setShowComments(boolean showComments)
{
this.showComments = showComments;
}
// end of Level 2 methods
// end of Level 1 methods
// Level 1 methods
public boolean isShowFields()
{
return showFields;
}
// Level 2 methods
public void setShowFields(boolean showFields)
{
this.showFields = showFields;
}
public boolean isShowMatchedRules()
{
return showMatchedRules;
}
public void setShowMatchedRules(boolean showMatchedRules)
{
this.showMatchedRules = showMatchedRules;
}
public boolean isShowParameterNames()
{
return showParameterNames;
}
// Level 2 methods
public void setShowParameterNames(boolean showParameterNames)
{
this.showParameterNames = showParameterNames;
}
// end of Level 2 methods
// end of Level 1 methods
// Level 1 methods
public boolean isShowParameterTypes()
{
return showParameterTypes;
}
// Level 2 methods
public void setShowParameterTypes(boolean showParameterTypes)
{
this.showParameterTypes = showParameterTypes;
}
// end of Level 2 methods
// end of Level 1 methods
// Level 1 methods
public boolean isShowRules()
{
return showRules;
}
public void setShowRules(boolean showRules)
{
this.showRules = showRules;
}
// end of Level 2 methods
// end of Level 1 methods
public boolean isShowTypeAfterMethod()
{
return showTypeAfterMethod;
}
public void setShowTypeAfterMethod(boolean showTypeAfterMethod)
{
this.showTypeAfterMethod = showTypeAfterMethod;
}
// ------------------------ CANONICAL METHODS ------------------------
public boolean equals(final Object object)
{
if (!(object instanceof RearrangerSettings)) return false;
final RearrangerSettings rs = (RearrangerSettings) object;
if (rs.getClassOrderAttributeList().size() != getClassOrderAttributeList().size()) return false;
if (rs.getItemOrderAttributeList().size() != getItemOrderAttributeList().size() ) return false;
for (int i = 0; i < getClassOrderAttributeList().size(); i++)
{
if (!getClassOrderAttributeList().get(i).equals(rs.getClassOrderAttributeList().get(i))) return false;
}
for (int i = 0; i < getItemOrderAttributeList().size(); i++)
{
if (!getItemOrderAttributeList().get(i).equals(rs.getItemOrderAttributeList().get(i))) return false;
}
if (!rs.getExtractedMethodsSettings().equals(getExtractedMethodsSettings()) ) return false;
if (rs.isKeepGettersSettersTogether () != isKeepGettersSettersTogether ()) return false;
if (rs.isKeepGettersSettersWithProperty() != isKeepGettersSettersWithProperty()) return false;
if (rs.isKeepOverloadedMethodsTogether () != isKeepOverloadedMethodsTogether ()) return false;
if (rs.overloadedOrder != overloadedOrder ) return false;
if (!rs.globalCommentPattern.equals(globalCommentPattern) ) return false;
if (rs.askBeforeRearranging != askBeforeRearranging ) return false;
if (rs.rearrangeInnerClasses != rearrangeInnerClasses ) return false;
if (rs.showParameterTypes != showParameterTypes ) return false;
if (rs.showParameterNames != showParameterNames ) return false;
if (rs.showFields != showFields ) return false;
if (rs.showTypeAfterMethod != showTypeAfterMethod ) return false;
if (rs.showRules != showRules ) return false;
if (rs.showMatchedRules != showMatchedRules ) return false;
if (rs.showComments != showComments ) return false;
if (rs.removeBlanksInsideCodeBlocks != removeBlanksInsideCodeBlocks ) return false;
if (!rs.afterClassLBrace.equals (afterClassLBrace ) ) return false;
if (!rs.afterClassRBrace.equals (afterClassRBrace ) ) return false;
if (!rs.beforeClassRBrace.equals (beforeClassRBrace ) ) return false;
if (!rs.beforeMethodLBrace.equals(beforeMethodLBrace) ) return false;
if (!rs.afterMethodLBrace.equals(afterMethodLBrace) ) return false;
if (!rs.afterMethodRBrace.equals(afterMethodRBrace) ) return false;
if (!rs.beforeMethodRBrace.equals(beforeMethodRBrace) ) return false;
if (!rs.newlinesAtEOF.equals(newlinesAtEOF) ) return false;
if (!rs.defaultGSDefinition.equals(defaultGSDefinition) ) return false;
if (primaryMethodList.size() != rs.primaryMethodList.size() ) return false;
for (int i = 0; i < primaryMethodList.size(); i++)
{
PrimaryMethodSetting pms = primaryMethodList.get(i);
PrimaryMethodSetting rspms = rs.primaryMethodList.get(i);
if (!rspms.equals(pms)) return false;
}
return true;
}
// -------------------------- OTHER METHODS --------------------------
public final void addClass(final AttributeGroup ca, final int index)
{
if (classOrderAttributeList.size() < index)
{
classOrderAttributeList.add(ca);
}
else
{
classOrderAttributeList.add(index, ca);
}
}
public final void addItem(final AttributeGroup ia, final int index)
{
if (itemOrderAttributeList.size() < index)
{
itemOrderAttributeList.add(ia);
}
else
{
itemOrderAttributeList.add(index, ia);
}
}
public final RearrangerSettings deepCopy()
{
final RearrangerSettings result = new RearrangerSettings();
for (AttributeGroup itemAttributes : itemOrderAttributeList)
{
result.itemOrderAttributeList.add(itemAttributes.deepCopy());
}
for (AttributeGroup classAttributes : classOrderAttributeList)
{
result.classOrderAttributeList.add(classAttributes.deepCopy());
}
result.relatedMethodsSettings = relatedMethodsSettings.deepCopy();
result.keepGettersSettersTogether = keepGettersSettersTogether;
result.keepGettersSettersWithProperty = keepGettersSettersWithProperty;
result.keepOverloadedMethodsTogether = keepOverloadedMethodsTogether;
result.globalCommentPattern = globalCommentPattern;
result.overloadedOrder = overloadedOrder;
result.askBeforeRearranging = askBeforeRearranging;
result.rearrangeInnerClasses = rearrangeInnerClasses;
result.showParameterNames = showParameterNames;
result.showParameterTypes = showParameterTypes;
result.showFields = showFields;
result.showTypeAfterMethod = showTypeAfterMethod;
result.showRules = showRules;
result.showMatchedRules = showMatchedRules;
result.showComments = showComments;
result.removeBlanksInsideCodeBlocks = removeBlanksInsideCodeBlocks;
result.afterClassLBrace = afterClassLBrace.deepCopy ();
result.afterClassRBrace = afterClassRBrace.deepCopy ();
result.beforeClassRBrace = beforeClassRBrace.deepCopy ();
result.beforeMethodLBrace = beforeMethodLBrace.deepCopy();
result.afterMethodLBrace = afterMethodLBrace.deepCopy();
result.afterMethodRBrace = afterMethodRBrace.deepCopy();
result.beforeMethodRBrace = beforeMethodRBrace.deepCopy();
result.newlinesAtEOF = newlinesAtEOF.deepCopy();
result.defaultGSDefinition = defaultGSDefinition.deepCopy();
return result;
}
public void writeSettingsToFile(File f)
{
Element component = new Element("component");
component.setAttribute("name", Rearranger.COMPONENT_NAME);
Element r = new Element(Rearranger.COMPONENT_NAME);
component.getChildren().add(r);
writeExternal(r);
Format format = Format.getPrettyFormat();
XMLOutputter outputter = new XMLOutputter(format);
try
{
final FileOutputStream fileOutputStream = new FileOutputStream(f);
outputter.output(component, fileOutputStream);
fileOutputStream.close();
}
catch (IOException e)
{
throw new RuntimeException(e);
}
}
// end of Level 2 methods
// end of Level 1 methods
public final void writeExternal(final Element entry)
{
final Element items = new Element("Items" );
final Element classes = new Element("Classes");
entry.getChildren().add(items );
entry.getChildren().add(classes);
for (AttributeGroup item : itemOrderAttributeList)
{
item.writeExternal(items);
}
for (AttributeGroup attributes : classOrderAttributeList)
{
attributes.writeExternal(classes);
}
final Element gsd = new Element("DefaultGetterSetterDefinition");
entry.getChildren().add(gsd);
defaultGSDefinition.writeExternal(gsd);
final Element relatedItems = new Element("RelatedMethods");
entry.getChildren().add(relatedItems);
entry.setAttribute("KeepGettersSettersTogether", Boolean.valueOf(keepGettersSettersTogether).toString ());
entry.setAttribute("KeepGettersSettersWithProperty", Boolean.valueOf(keepGettersSettersWithProperty).toString());
entry.setAttribute("KeepOverloadedMethodsTogether", Boolean.valueOf(keepOverloadedMethodsTogether).toString());
entry.setAttribute("ConfirmBeforeRearranging", Boolean.valueOf(askBeforeRearranging).toString ());
entry.setAttribute("RearrangeInnerClasses", Boolean.valueOf(rearrangeInnerClasses).toString ());
entry.setAttribute("globalCommentPattern", globalCommentPattern );
entry.setAttribute("overloadedOrder", "" + overloadedOrder );
entry.setAttribute("ShowParameterTypes", Boolean.valueOf(showParameterTypes).toString ());
entry.setAttribute("ShowParameterNames", Boolean.valueOf(showParameterNames).toString ());
entry.setAttribute("ShowFields", Boolean.valueOf(showFields).toString ());
entry.setAttribute("ShowTypeAfterMethod", Boolean.valueOf(showTypeAfterMethod).toString ());
entry.setAttribute("ShowRules", Boolean.valueOf(showRules).toString ());
entry.setAttribute("ShowMatchedRules", Boolean.valueOf(showMatchedRules).toString ());
entry.setAttribute("ShowComments", Boolean.valueOf(showComments).toString ());
entry.setAttribute("RemoveBlanksInsideCodeBlocks", Boolean.valueOf(removeBlanksInsideCodeBlocks).toString ());
relatedMethodsSettings.writeExternal(relatedItems);
afterClassLBrace.writeExternal (entry);
afterClassRBrace.writeExternal (entry);
beforeClassRBrace.writeExternal (entry);
beforeMethodLBrace.writeExternal(entry);
afterMethodLBrace.writeExternal(entry);
afterMethodRBrace.writeExternal(entry);
beforeMethodRBrace.writeExternal(entry);
newlinesAtEOF.writeExternal(entry);
}
}
| 41.951823 | 207 | 0.626214 |
29fe0f3f56841ae4a19ba29187c706b6dac56e82 | 13,179 | /*
* 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.rya.accumulo;
//
//import com.google.common.collect.Iterators;
//import com.google.common.io.ByteArrayDataInput;
//import com.google.common.io.ByteStreams;
//import info.aduna.iteration.CloseableIteration;
//import org.apache.rya.api.RdfCloudTripleStoreConstants;
//import org.apache.rya.api.RdfCloudTripleStoreUtils;
//import org.apache.rya.api.persist.RdfDAOException;
//import org.apache.rya.api.utils.NullableStatementImpl;
//import org.apache.accumulo.core.client.*;
//import org.apache.accumulo.core.data.Key;
//import org.apache.accumulo.core.data.Range;
//import org.apache.accumulo.core.iterators.user.AgeOffFilter;
//import org.apache.accumulo.core.iterators.user.TimestampFilter;
//import org.apache.accumulo.core.security.Authorizations;
//import org.apache.hadoop.io.Text;
//import org.openrdf.model.Resource;
//import org.openrdf.model.Statement;
//import org.openrdf.model.URI;
//import org.openrdf.model.Value;
//import org.openrdf.query.BindingSet;
//import org.slf4j.Logger;
//import org.slf4j.LoggerFactory;
//
//import java.io.IOException;
//import java.util.Collection;
//import java.util.Collections;
//import java.util.HashSet;
//import java.util.Iterator;
//import java.util.Map.Entry;
//
//import static org.apache.rya.accumulo.AccumuloRdfConstants.ALL_AUTHORIZATIONS;
//import static org.apache.rya.api.RdfCloudTripleStoreConstants.TABLE_LAYOUT;
//import static org.apache.rya.api.RdfCloudTripleStoreUtils.writeValue;
//
//public class AccumuloRdfQueryIterator implements
// CloseableIteration<Entry<Statement, BindingSet>, RdfDAOException> {
//
// protected final Logger logger = LoggerFactory.getLogger(getClass());
//
// private boolean open = false;
// private Iterator result;
// private Resource[] contexts;
// private Collection<Entry<Statement, BindingSet>> statements;
// private int numOfThreads = 20;
//
// private RangeBindingSetEntries rangeMap = new RangeBindingSetEntries();
// private ScannerBase scanner;
// private boolean isBatchScanner = true;
// private Statement statement;
// Iterator<BindingSet> iter_bss = null;
//
// private boolean hasNext = true;
// private AccumuloRdfConfiguration conf;
// private TABLE_LAYOUT tableLayout;
// private Text context_txt;
//
// private DefineTripleQueryRangeFactory queryRangeFactory = new DefineTripleQueryRangeFactory();
//
// public AccumuloRdfQueryIterator(Collection<Entry<Statement, BindingSet>> statements, Connector connector, Resource... contexts)
// throws RdfDAOException {
// this(statements, connector, null, contexts);
// }
//
// public AccumuloRdfQueryIterator(Collection<Entry<Statement, BindingSet>> statements, Connector connector,
// AccumuloRdfConfiguration conf, Resource... contexts)
// throws RdfDAOException {
// this.statements = statements;
// this.contexts = contexts;
// this.conf = conf;
// initialize(connector);
// open = true;
// }
//
// public AccumuloRdfQueryIterator(Resource subject, URI predicate, Value object, Connector connector,
// AccumuloRdfConfiguration conf, Resource[] contexts) throws RdfDAOException {
// this(Collections.<Entry<Statement, BindingSet>>singleton(new RdfCloudTripleStoreUtils.CustomEntry<Statement, BindingSet>(
// new NullableStatementImpl(subject, predicate, object, contexts),
// null)), connector, conf, contexts);
// }
//
// protected void initialize(Connector connector)
// throws RdfDAOException {
// try {
// //TODO: We cannot span multiple tables here
// Collection<Range> ranges = new HashSet<Range>();
//
// result = Iterators.emptyIterator();
// Long startTime = conf.getStartTime();
// Long ttl = conf.getTtl();
//
// Resource context = null;
// for (Entry<Statement, BindingSet> stmtbs : statements) {
// Statement stmt = stmtbs.getKey();
// Resource subject = stmt.getSubject();
// URI predicate = stmt.getPredicate();
// Value object = stmt.getObject();
// context = stmt.getContext(); //TODO: assumes the same context for all statements
// logger.debug("Batch Scan, lookup subject[" + subject + "] predicate[" + predicate + "] object[" + object + "] combination");
//
// Entry<TABLE_LAYOUT, Range> entry = queryRangeFactory.defineRange(subject, predicate, object, conf);
// tableLayout = entry.getKey();
//// isTimeRange = isTimeRange || queryRangeFactory.isTimeRange();
// Range range = entry.getValue();
// ranges.add(range);
// rangeMap.ranges.add(new RdfCloudTripleStoreUtils.CustomEntry<Range, BindingSet>(range, stmtbs.getValue()));
// }
//
// Authorizations authorizations = AccumuloRdfConstants.ALL_AUTHORIZATIONS;
// String auth = conf.getAuth();
// if (auth != null) {
// authorizations = new Authorizations(auth.split(","));
// }
// String table = RdfCloudTripleStoreUtils.layoutToTable(tableLayout, conf);
// result = createScanner(connector, authorizations, table, context, startTime, ttl, ranges);
//// if (isBatchScanner) {
//// ((BatchScanner) scanner).setRanges(ranges);
//// } else {
//// for (Range range : ranges) {
//// ((Scanner) scanner).setRange(range); //TODO: Not good way of doing this
//// }
//// }
////
//// if (isBatchScanner) {
//// result = ((BatchScanner) scanner).iterator();
//// } else {
//// result = ((Scanner) scanner).iterator();
//// }
// } catch (Exception e) {
// throw new RdfDAOException(e);
// }
// }
//
// protected Iterator<Entry<Key, org.apache.accumulo.core.data.Value>> createScanner(Connector connector, Authorizations authorizations, String table, Resource context, Long startTime, Long ttl, Collection<Range> ranges) throws TableNotFoundException, IOException {
//// ShardedConnector shardedConnector = new ShardedConnector(connector, 4, ta)
// if (rangeMap.ranges.size() > (numOfThreads / 2)) { //TODO: Arbitrary number, make configurable
// BatchScanner scannerBase = connector.createBatchScanner(table, authorizations, numOfThreads);
// scannerBase.setRanges(ranges);
// populateScanner(context, startTime, ttl, scannerBase);
// return scannerBase.iterator();
// } else {
// isBatchScanner = false;
// Iterator<Entry<Key, org.apache.accumulo.core.data.Value>>[] iters = new Iterator[ranges.size()];
// int i = 0;
// for (Range range : ranges) {
// Scanner scannerBase = connector.createScanner(table, authorizations);
// populateScanner(context, startTime, ttl, scannerBase);
// scannerBase.setRange(range);
// iters[i] = scannerBase.iterator();
// i++;
// scanner = scannerBase; //TODO: Always overridden, but doesn't matter since Scanner doesn't need to be closed
// }
// return Iterators.concat(iters);
// }
//
// }
//
// protected void populateScanner(Resource context, Long startTime, Long ttl, ScannerBase scannerBase) throws IOException {
// if (context != null) { //default graph
// context_txt = new Text(writeValue(context));
// scannerBase.fetchColumnFamily(context_txt);
// }
//
//// if (!isQueryTimeBased(conf)) {
// if (startTime != null && ttl != null) {
//// scannerBase.setScanIterators(1, FilteringIterator.class.getName(), "filteringIterator");
//// scannerBase.setScanIteratorOption("filteringIterator", "0", TimeRangeFilter.class.getName());
//// scannerBase.setScanIteratorOption("filteringIterator", "0." + TimeRangeFilter.TIME_RANGE_PROP, ttl);
//// scannerBase.setScanIteratorOption("filteringIterator", "0." + TimeRangeFilter.START_TIME_PROP, startTime);
// IteratorSetting setting = new IteratorSetting(1, "fi", TimestampFilter.class.getName());
// TimestampFilter.setStart(setting, startTime, true);
// TimestampFilter.setEnd(setting, startTime + ttl, true);
// scannerBase.addScanIterator(setting);
// } else if (ttl != null) {
//// scannerBase.setScanIterators(1, FilteringIterator.class.getName(), "filteringIterator");
//// scannerBase.setScanIteratorOption("filteringIterator", "0", AgeOffFilter.class.getName());
//// scannerBase.setScanIteratorOption("filteringIterator", "0.ttl", ttl);
// IteratorSetting setting = new IteratorSetting(1, "fi", AgeOffFilter.class.getName());
// AgeOffFilter.setTTL(setting, ttl);
// scannerBase.addScanIterator(setting);
// }
//// }
// }
//
// @Override
// public void close() throws RdfDAOException {
// if (!open)
// return;
// verifyIsOpen();
// open = false;
// if (scanner != null && isBatchScanner) {
// ((BatchScanner) scanner).close();
// }
// }
//
// public void verifyIsOpen() throws RdfDAOException {
// if (!open) {
// throw new RdfDAOException("Iterator not open");
// }
// }
//
// @Override
// public boolean hasNext() throws RdfDAOException {
// try {
// if (!open)
// return false;
// verifyIsOpen();
// /**
// * For some reason, the result.hasNext returns false
// * once at the end of the iterator, and then true
// * for every subsequent call.
// */
// hasNext = (hasNext && result.hasNext());
// return hasNext || ((iter_bss != null) && iter_bss.hasNext());
// } catch (Exception e) {
// throw new RdfDAOException(e);
// }
// }
//
// @Override
// public Entry<Statement, BindingSet> next() throws RdfDAOException {
// try {
// if (!this.hasNext())
// return null;
//
// return getStatement(result, contexts);
// } catch (Exception e) {
// throw new RdfDAOException(e);
// }
// }
//
// public Entry<Statement, BindingSet> getStatement(
// Iterator<Entry<Key, org.apache.accumulo.core.data.Value>> rowResults,
// Resource... filterContexts) throws IOException {
// try {
// while (true) {
// if (iter_bss != null && iter_bss.hasNext()) {
// return new RdfCloudTripleStoreUtils.CustomEntry<Statement, BindingSet>(statement, iter_bss.next());
// }
//
// if (rowResults.hasNext()) {
// Entry<Key, org.apache.accumulo.core.data.Value> entry = rowResults.next();
// Key key = entry.getKey();
// ByteArrayDataInput input = ByteStreams.newDataInput(key.getRow().getBytes());
// statement = RdfCloudTripleStoreUtils.translateStatementFromRow(input, key.getColumnFamily(), tableLayout, RdfCloudTripleStoreConstants.VALUE_FACTORY);
// iter_bss = rangeMap.containsKey(key).iterator();
// } else
// break;
// }
// } catch (Exception e) {
// throw new IOException(e);
// }
// return null;
// }
//
// @Override
// public void remove() throws RdfDAOException {
// next();
// }
//
// public int getNumOfThreads() {
// return numOfThreads;
// }
//
// public void setNumOfThreads(int numOfThreads) {
// this.numOfThreads = numOfThreads;
// }
//
// public DefineTripleQueryRangeFactory getQueryRangeFactory() {
// return queryRangeFactory;
// }
//
// public void setQueryRangeFactory(DefineTripleQueryRangeFactory queryRangeFactory) {
// this.queryRangeFactory = queryRangeFactory;
// }
//}
| 44.224832 | 268 | 0.620381 |
90f4e391980e650c991352cca1619dcde8bbde35 | 2,042 | package expo.modules.updates.manifest;
import android.util.Log;
import org.json.JSONObject;
import java.util.HashMap;
import androidx.annotation.Nullable;
import expo.modules.updates.UpdatesConfiguration;
import expo.modules.updates.db.UpdatesDatabase;
public class ManifestMetadata {
private static final String TAG = ManifestMetadata.class.getSimpleName();
public static final String MANIFEST_SERVER_DEFINED_HEADERS_KEY = "serverDefinedHeaders";
public static final String MANIFEST_FILTERS_KEY = "manifestFilters";
private static @Nullable JSONObject getJSONObject(String key, UpdatesDatabase database, UpdatesConfiguration configuration) {
try {
String jsonString = database.jsonDataDao().loadJSONStringForKey(key, configuration.getScopeKey());
return jsonString != null ? new JSONObject(jsonString) : null;
} catch (Exception e) {
Log.e(TAG, "Error retrieving " + key + " from database", e);
return null;
}
}
public static @Nullable JSONObject getServerDefinedHeaders(UpdatesDatabase database, UpdatesConfiguration configuration) {
return getJSONObject(MANIFEST_SERVER_DEFINED_HEADERS_KEY, database, configuration);
}
public static @Nullable JSONObject getManifestFilters(UpdatesDatabase database, UpdatesConfiguration configuration) {
return getJSONObject(MANIFEST_FILTERS_KEY, database, configuration);
}
public static void saveMetadata(UpdateManifest updateManifest, UpdatesDatabase database, UpdatesConfiguration configuration) {
HashMap<String, String> fieldsToSet = new HashMap<>();
if (updateManifest.getServerDefinedHeaders() != null) {
fieldsToSet.put(MANIFEST_SERVER_DEFINED_HEADERS_KEY, updateManifest.getServerDefinedHeaders().toString());
}
if (updateManifest.getManifestFilters() != null) {
fieldsToSet.put(MANIFEST_FILTERS_KEY, updateManifest.getManifestFilters().toString());
}
if (fieldsToSet.size() > 0) {
database.jsonDataDao().setMultipleFields(fieldsToSet, configuration.getScopeKey());
}
}
}
| 39.269231 | 128 | 0.773751 |
ef59a0568f77de1c1f239871289aede51ecc5710 | 1,807 | package com.cooker.msgbus.core;
import com.google.common.base.Preconditions;
import java.util.Optional;
import java.util.StringJoiner;
/*
* 版权:
* 创建者: ykq
* 创建时间: 2018/09/06 下午4:48
* 功能描述: 获取参数,类型适配
* 修改历史:
*/
public interface IParams {
default String getString(String key){
return getString(key, null);
}
default int getInt(String key){
return getInt(key, 0);
}
default long getLong(String key){
return getLong(key, 0);
}
default boolean getBoolean(String key){
return getBoolean(key, false);
}
default float getFloat(String key) {return getFloat(key, 0.0f);}
default double getDouble(String key) {return getDouble(key, 0.0d);}
//获取拆分的字符串
default String[] getSplitStr(String delimiter, String key){
Optional<String> str = getStr2Optional(key, "");
if(str.isPresent()){
return str.get().split(delimiter);
}
return new String[]{};
}
default String getMergeStr(String delimiter, String... keys){
Preconditions.checkNotNull(keys);
StringJoiner sj = new StringJoiner(delimiter);
for (String key : keys){
Optional<String> val = getStr2Optional(key, "");
val.ifPresent(
(v)->{
sj.add(v);
}
);
}
return sj.toString();
}
String getString(String key, String dVal);
default Optional<String> getStr2Optional(String key, String dVal){
return Optional.ofNullable(getString(key, dVal));
}
long getLong(String key, long dVal);
int getInt(String key, int dVal);
boolean getBoolean(String key, boolean dVal);
float getFloat(String key, float dVal);
double getDouble(String key, double dVal);
}
| 28.68254 | 71 | 0.610404 |
92e7ff5c4d6e7c292c8f3d7a4be6b131b82390d8 | 7,429 | package net.id.incubus_core.datagen;
import com.google.common.base.Charsets;
import net.minecraft.item.Item;
import net.minecraft.util.registry.Registry;
import org.apache.commons.io.FileUtils;
import java.io.File;
import java.io.IOException;
@SuppressWarnings("unused")
public class RecipeJsonGen {
public static final String PATTERN_PATH = "pattern";
public static final String SMELTING_TEMPLATE = "{\n" +
" \"type\": \"minecraft:smelting\",\n" +
" \"ingredient\": {\n" +
" \"item\": \"component_0\"\n" +
" },\n" +
" \"result\": \"component_1\",\n" +
" \"experience\": component_2,\n" +
" \"cookingtime\": component_3\n" +
"}";
public static void genFurnaceRecipe(Metadata metadata, String name, Item input, Item output, float xp, int time) {
if(!metadata.allowRegen)
return;
genDynamicRecipe(
metadata,
name,
"smelting",
SMELTING_TEMPLATE,
new String[]{ Registry.ITEM.getId(input).toString(), Registry.ITEM.getId(output).toString(), String.valueOf(xp), String.valueOf(time)}
);
}
public static void genDynamicRecipe(Metadata metadata, String name, String category, String template, String[] components) {
if(!metadata.allowRegen)
return;
String output = "" + template;
for (int i = 0; i < components.length; i++) {
output = output.replace("component_" + i, components[i]);
}
try {
FileUtils.writeStringToFile(metadata.genDataJson(name, PATTERN_PATH + File.separator + category, Metadata.DataType.RECIPE), output, Charsets.UTF_8);
} catch (IOException e) {
e.printStackTrace();
}
}
public static void gen2x2Recipe(Metadata metadata, String name, Item in, Item out, int count) {
if(!metadata.allowRegen)
return;
String output = Registry.ITEM.getId(out).toString();
String input = Registry.ITEM.getId(in).toString();
String json = "{\n" +
" \"type\": \"minecraft:crafting_shaped\",\n" +
" \"pattern\": [\n" +
" \"##\",\n" +
" \"##\"\n" +
" ],\n" +
" \"key\": {\n" +
" \"#\": {\n" +
" \"item\": \"" + input + "\"\n" +
" }\n" +
" },\n" +
" \"result\": {\n" +
" \"item\": \"" + output + "\",\n" +
" \"count\": " + count + "\n" +
" }\n" +
"}";
try {
FileUtils.writeStringToFile(metadata.genDataJson(name, PATTERN_PATH, Metadata.DataType.RECIPE), json, Charsets.UTF_8);
} catch (IOException e) {
e.printStackTrace();
}
}
public static void gen3x3Recipe(Metadata metadata, String name, Item in, Item out, int count) {
if(!metadata.allowRegen)
return;
String output = Registry.ITEM.getId(out).toString();
String input = Registry.ITEM.getId(in).toString();
String json = "{\n" +
" \"type\": \"minecraft:crafting_shaped\",\n" +
" \"pattern\": [\n" +
" \"###\",\n" +
" \"###\",\n" +
" \"###\"\n" +
" ],\n" +
" \"key\": {\n" +
" \"#\": {\n" +
" \"item\": \"" + input + "\"\n" +
" }\n" +
" },\n" +
" \"result\": {\n" +
" \"item\": \"" + output + "\",\n" +
" \"count\": " + count + "\n" +
" }\n" +
"}";
try {
FileUtils.writeStringToFile(metadata.genDataJson(name, PATTERN_PATH, Metadata.DataType.RECIPE), json, Charsets.UTF_8);
} catch (IOException e) {
e.printStackTrace();
}
}
public static void genSlabRecipe(Metadata metadata, String name, Item in, Item out, int count) {
if(!metadata.allowRegen)
return;
String output = Registry.ITEM.getId(out).toString();
String input = Registry.ITEM.getId(in).toString();
String json = "{\n" +
" \"type\": \"minecraft:crafting_shaped\",\n" +
" \"pattern\": [\n" +
" \"###\"\n" +
" ],\n" +
" \"key\": {\n" +
" \"#\": {\n" +
" \"item\": \"" + input + "\"\n" +
" }\n" +
" },\n" +
" \"result\": {\n" +
" \"item\": \"" + output + "\",\n" +
" \"count\": " + count + "\n" +
" }\n" +
"}";
try {
FileUtils.writeStringToFile(metadata.genDataJson(name, PATTERN_PATH, Metadata.DataType.RECIPE), json, Charsets.UTF_8);
} catch (IOException e) {
e.printStackTrace();
}
}
public static void genStairsRecipe(Metadata metadata, String name, Item in, Item out, int count) {
if(!metadata.allowRegen)
return;
String output = Registry.ITEM.getId(out).toString();
String input = Registry.ITEM.getId(in).toString();
String json = "{\n" +
" \"type\": \"minecraft:crafting_shaped\",\n" +
" \"pattern\": [\n" +
" \"# \",\n" +
" \"## \",\n" +
" \"###\"\n" +
" ],\n" +
" \"key\": {\n" +
" \"#\": {\n" +
" \"item\": \"" + input + "\"\n" +
" }\n" +
" },\n" +
" \"result\": {\n" +
" \"item\": \"" + output + "\",\n" +
" \"count\": " + count + "\n" +
" }\n" +
"}";
try {
FileUtils.writeStringToFile(metadata.genDataJson(name, PATTERN_PATH, Metadata.DataType.RECIPE), json, Charsets.UTF_8);
} catch (IOException e) {
e.printStackTrace();
}
}
public static void genWallRecipe(Metadata metadata, String name, Item in, Item out, int count) {
if(!metadata.allowRegen)
return;
String output = Registry.ITEM.getId(out).toString();
String input = Registry.ITEM.getId(in).toString();
String json = "{\n" +
" \"type\": \"minecraft:crafting_shaped\",\n" +
" \"pattern\": [\n" +
" \"###\",\n" +
" \"###\"\n" +
" ],\n" +
" \"key\": {\n" +
" \"#\": {\n" +
" \"item\": \"" + input + "\"\n" +
" }\n" +
" },\n" +
" \"result\": {\n" +
" \"item\": \"" + output + "\",\n" +
" \"count\": " + count + "\n" +
" }\n" +
"}";
try {
FileUtils.writeStringToFile(metadata.genDataJson(name, PATTERN_PATH, Metadata.DataType.RECIPE), json, Charsets.UTF_8);
} catch (IOException e) {
e.printStackTrace();
}
}
}
| 34.235023 | 160 | 0.425225 |
52dc91767fd0ce072a7d541be6ed336795d90839 | 23,821 | // Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.openapi.wm.impl.status;
import com.intellij.ide.IdeEventQueue;
import com.intellij.notification.impl.IdeNotificationArea;
import com.intellij.openapi.Disposable;
import com.intellij.openapi.progress.ProgressIndicator;
import com.intellij.openapi.progress.TaskInfo;
import com.intellij.openapi.ui.MessageType;
import com.intellij.openapi.ui.popup.BalloonHandler;
import com.intellij.openapi.ui.popup.ListPopup;
import com.intellij.openapi.util.Couple;
import com.intellij.openapi.util.Disposer;
import com.intellij.openapi.util.Pair;
import com.intellij.openapi.util.SystemInfoRt;
import com.intellij.openapi.util.text.StringUtil;
import com.intellij.openapi.wm.*;
import com.intellij.openapi.wm.ex.ProgressIndicatorEx;
import com.intellij.openapi.wm.ex.StatusBarEx;
import com.intellij.ui.ClickListener;
import com.intellij.ui.SimpleColoredComponent;
import com.intellij.ui.awt.RelativePoint;
import com.intellij.ui.popup.NotificationPopup;
import com.intellij.util.ArrayUtilRt;
import com.intellij.util.Consumer;
import com.intellij.util.ui.*;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import javax.accessibility.Accessible;
import javax.accessibility.AccessibleContext;
import javax.accessibility.AccessibleRole;
import javax.swing.*;
import javax.swing.event.HyperlinkListener;
import java.awt.*;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.util.List;
import java.util.*;
public class IdeStatusBarImpl extends JComponent implements Accessible, StatusBarEx, IdeEventQueue.EventDispatcher {
private static final int MIN_ICON_HEIGHT = 18 + 1 + 1;
private final InfoAndProgressPanel myInfoAndProgressPanel;
private IdeFrame myFrame;
private enum Position {LEFT, RIGHT, CENTER}
private static final String uiClassID = "IdeStatusBarUI";
private final Map<String, WidgetBean> myWidgetMap = new HashMap<>();
private final List<String> myOrderedWidgets = new ArrayList<>();
private JPanel myLeftPanel;
private JPanel myRightPanel;
private JPanel myCenterPanel;
private Component myHoveredComponent;
private String myInfo;
private final List<String> myCustomComponentIds = new ArrayList<>();
private final Set<IdeStatusBarImpl> myChildren = new HashSet<>();
//private ToolWindowsWidget myToolWindowWidget;
private static class WidgetBean {
JComponent component;
Position position;
StatusBarWidget widget;
String anchor;
static WidgetBean create(@NotNull final StatusBarWidget widget,
@NotNull final Position position,
@NotNull final JComponent component,
@NotNull String anchor) {
final WidgetBean bean = new WidgetBean();
bean.widget = widget;
bean.position = position;
bean.component = component;
bean.anchor = anchor;
return bean;
}
}
@Override
public StatusBar findChild(Component c) {
Component eachParent = c;
IdeFrame frame = null;
while (eachParent != null) {
if (eachParent instanceof IdeFrame) {
frame = (IdeFrame)eachParent;
}
eachParent = eachParent.getParent();
}
return frame != null ? frame.getStatusBar() : this;
}
@Override
public void install(IdeFrame frame) {
myFrame = frame;
}
private void updateChildren(ChildAction action) {
for (IdeStatusBarImpl child : myChildren) {
action.update(child);
}
}
@FunctionalInterface
interface ChildAction {
void update(IdeStatusBarImpl child);
}
@Override
public StatusBar createChild() {
final IdeStatusBarImpl bar = new IdeStatusBarImpl(this);
myChildren.add(bar);
Disposer.register(bar, () -> myChildren.remove(bar));
for (String eachId : myOrderedWidgets) {
WidgetBean eachBean = myWidgetMap.get(eachId);
if (eachBean.widget instanceof StatusBarWidget.Multiframe) {
StatusBarWidget copy = ((StatusBarWidget.Multiframe)eachBean.widget).copy();
UIUtil.invokeLaterIfNeeded(() -> bar.addWidget(copy, eachBean.position, eachBean.anchor));
}
}
return bar;
}
@Override
public JComponent getComponent() {
return this;
}
private IdeStatusBarImpl(@Nullable IdeStatusBarImpl master) {
setLayout(new BorderLayout());
setBorder(JBUI.Borders.empty());
myInfoAndProgressPanel = new InfoAndProgressPanel();
addWidget(myInfoAndProgressPanel, Position.CENTER);
setOpaque(true);
updateUI();
if (master == null) {
addWidget(new ToolWindowsWidget(this), Position.LEFT);
}
enableEvents(AWTEvent.MOUSE_EVENT_MASK);
enableEvents(AWTEvent.MOUSE_MOTION_EVENT_MASK);
IdeEventQueue.getInstance().addPostprocessor(this, this);
}
public IdeStatusBarImpl() {
this(null);
}
@Override
public Dimension getPreferredSize() {
Dimension size = super.getPreferredSize();
if (size == null) return null;
Insets insets = getInsets();
int minHeight = insets.top + insets.bottom + MIN_ICON_HEIGHT;
return new Dimension(size.width, Math.max(size.height, minHeight));
}
@Override
public void addWidget(@NotNull final StatusBarWidget widget) {
UIUtil.invokeLaterIfNeeded(() -> addWidget(widget, Position.RIGHT, "__AUTODETECT__"));
}
@Override
public void addWidget(@NotNull final StatusBarWidget widget, @NotNull final String anchor) {
UIUtil.invokeLaterIfNeeded(() -> addWidget(widget, Position.RIGHT, anchor));
}
private void addWidget(@NotNull final StatusBarWidget widget, @NotNull final Position pos) {
UIUtil.invokeLaterIfNeeded(() -> addWidget(widget, pos, "__IGNORED__"));
}
@Override
public void addWidget(@NotNull final StatusBarWidget widget, @NotNull final Disposable parentDisposable) {
addWidget(widget);
Disposer.register(parentDisposable, () -> removeWidget(widget.ID()));
}
@Override
public void addWidget(@NotNull final StatusBarWidget widget, @NotNull String anchor, @NotNull final Disposable parentDisposable) {
addWidget(widget, anchor);
Disposer.register(parentDisposable, () -> removeWidget(widget.ID()));
}
public void removeCustomIndicationComponents() {
for (final String id : myCustomComponentIds) {
removeWidget(id);
}
myCustomComponentIds.clear();
}
@Override
public void addCustomIndicationComponent(@NotNull final JComponent c) {
final String customId = c.getClass().getName() + new Random().nextLong();
addWidget(new CustomStatusBarWidget() {
@Override
@NotNull
public String ID() {
return customId;
}
@Override
@Nullable
public WidgetPresentation getPresentation(@NotNull PlatformType type) {
return null;
}
@Override
public void install(@NotNull StatusBar statusBar) {
}
@Override
public void dispose() {
}
@Override
public JComponent getComponent() {
return c;
}
});
myCustomComponentIds.add(customId);
}
//@Override
//protected void processMouseMotionEvent(MouseEvent e) {
// final Point point = e.getPoint();
// if (myToolWindowWidget != null) {
// if(point.x < 42 && 0 <= point.y && point.y <= getHeight()) {
// myToolWindowWidget.mouseEntered();
// } else {
// myToolWindowWidget.mouseExited();
// }
// }
// super.processMouseMotionEvent(e);
//}
//@Override
//protected void processMouseEvent(MouseEvent e) {
// if (e.getID() == MouseEvent.MOUSE_EXITED && myToolWindowWidget != null) {
// if (!new Rectangle(0,0,22, getHeight()).contains(e.getPoint())) {
// myToolWindowWidget.mouseExited();
// }
// }
// super.processMouseEvent(e);
//}
@Override
public void removeCustomIndicationComponent(@NotNull final JComponent c) {
final Set<String> keySet = myWidgetMap.keySet();
final String[] keys = ArrayUtilRt.toStringArray(keySet);
for (final String key : keys) {
final WidgetBean value = myWidgetMap.get(key);
if (value.widget instanceof CustomStatusBarWidget && value.component == c) {
removeWidget(key);
myCustomComponentIds.remove(key);
}
}
}
@Override
public void dispose() {
myWidgetMap.clear();
myChildren.clear();
if (myLeftPanel != null) myLeftPanel.removeAll();
if (myRightPanel != null) myRightPanel.removeAll();
if (myCenterPanel != null) myCenterPanel.removeAll();
}
private void addWidget(@NotNull final StatusBarWidget widget, @NotNull final Position pos, @NotNull final String anchor) {
myOrderedWidgets.add(widget.ID());
JPanel panel;
if (pos == Position.RIGHT) {
if (myRightPanel == null) {
myRightPanel = new JPanel();
myRightPanel.setBorder(JBUI.Borders.emptyLeft(1));
myRightPanel.setLayout(new BoxLayout(myRightPanel, BoxLayout.X_AXIS) {
@Override
public void layoutContainer(Container target) {
super.layoutContainer(target);
for (Component component : target.getComponents()) {
if (component instanceof MemoryUsagePanel) {
Rectangle r = component.getBounds();
r.y = 0;
r.width += SystemInfoRt.isMac ? 4 : 0;
r.height = target.getHeight();
component.setBounds(r);
}
}
}
});
myRightPanel.setOpaque(false);
add(myRightPanel, BorderLayout.EAST);
}
panel = myRightPanel;
}
else if (pos == Position.LEFT) {
if (myLeftPanel == null) {
myLeftPanel = new JPanel();
myLeftPanel.setBorder(JBUI.Borders.empty(1, 4, 0, 1));
myLeftPanel.setLayout(new BoxLayout(myLeftPanel, BoxLayout.X_AXIS));
myLeftPanel.setOpaque(false);
add(myLeftPanel, BorderLayout.WEST);
}
panel = myLeftPanel;
}
else {
if (myCenterPanel == null) {
myCenterPanel = JBUI.Panels.simplePanel().andTransparent();
myCenterPanel.setBorder(JBUI.Borders.empty(1, 1, 0, 1));
add(myCenterPanel, BorderLayout.CENTER);
}
panel = myCenterPanel;
}
final JComponent c = wrap(widget);
if (Position.RIGHT == pos && panel.getComponentCount() > 0) {
String wid;
boolean before;
if (!anchor.equals("__AUTODETECT__")) {
final List<String> parts = StringUtil.split(anchor, " ");
if (parts.size() < 2 || !myWidgetMap.containsKey(parts.get(1))) {
wid = IdeNotificationArea.WIDGET_ID;
before = true;
}
else {
wid = parts.get(1);
before = "before".equalsIgnoreCase(parts.get(0));
}
}
else {
wid = IdeNotificationArea.WIDGET_ID;
before = true;
}
for (final String id : myWidgetMap.keySet()) {
if (id.equalsIgnoreCase(wid)) {
final WidgetBean bean = myWidgetMap.get(id);
int i = 0;
for (final Component component : myRightPanel.getComponents()) {
if (component == bean.component) {
if (before) {
panel.add(c, i);
}
else {
panel.add(c, i + 1);
}
installWidget(widget, pos, c, anchor);
return;
}
i++;
}
}
}
}
if (Position.LEFT == pos && panel.getComponentCount() == 0) {
c.setBorder(SystemInfoRt.isMac ? JBUI.Borders.empty(2, 0, 2, 4) : JBUI.Borders.empty());
}
panel.add(c);
installWidget(widget, pos, c, anchor);
if (widget instanceof StatusBarWidget.Multiframe) {
final StatusBarWidget.Multiframe mfw = (StatusBarWidget.Multiframe)widget;
updateChildren(child -> UIUtil.invokeLaterIfNeeded(() -> {
StatusBarWidget widgetCopy = mfw.copy();
child.addWidget(widgetCopy, pos, anchor);
}));
}
repaint();
}
@Override
public void setInfo(@Nullable final String s) {
setInfo(s, null);
}
@Override
public void setInfo(@Nullable final String s, @Nullable final String requestor) {
UIUtil.invokeLaterIfNeeded(() -> {
if (myInfoAndProgressPanel != null) {
Couple<String> pair = myInfoAndProgressPanel.setText(s, requestor);
myInfo = pair.first;
}
});
}
@Override
public String getInfo() {
return myInfo;
}
@Override
public void addProgress(@NotNull ProgressIndicatorEx indicator, @NotNull TaskInfo info) {
myInfoAndProgressPanel.addProgress(indicator, info);
}
@Override
public List<Pair<TaskInfo, ProgressIndicator>> getBackgroundProcesses() {
return myInfoAndProgressPanel.getBackgroundProcesses();
}
@Override
public void setProcessWindowOpen(final boolean open) {
myInfoAndProgressPanel.setProcessWindowOpen(open);
}
@Override
public boolean isProcessWindowOpen() {
return myInfoAndProgressPanel.isProcessWindowOpen();
}
@Override
public void startRefreshIndication(final String tooltipText) {
myInfoAndProgressPanel.setRefreshToolTipText(tooltipText);
myInfoAndProgressPanel.setRefreshVisible(true);
updateChildren(child -> child.startRefreshIndication(tooltipText));
}
@Override
public void stopRefreshIndication() {
myInfoAndProgressPanel.setRefreshVisible(false);
updateChildren(IdeStatusBarImpl::stopRefreshIndication);
}
@Override
public BalloonHandler notifyProgressByBalloon(@NotNull MessageType type, @NotNull String htmlBody) {
return notifyProgressByBalloon(type, htmlBody, null, null);
}
@Override
public BalloonHandler notifyProgressByBalloon(@NotNull MessageType type,
@NotNull String htmlBody,
@Nullable Icon icon,
@Nullable HyperlinkListener listener) {
return myInfoAndProgressPanel.notifyByBalloon(type, htmlBody, icon, listener);
}
@Override
public void fireNotificationPopup(@NotNull JComponent content, Color backgroundColor) {
new NotificationPopup(this, content, backgroundColor);
}
private void installWidget(@NotNull final StatusBarWidget widget,
@NotNull final Position pos,
@NotNull final JComponent c,
String anchor) {
myWidgetMap.put(widget.ID(), WidgetBean.create(widget, pos, c, anchor));
widget.install(this);
Disposer.register(this, widget);
}
private static JComponent wrap(@NotNull final StatusBarWidget widget) {
if (widget instanceof CustomStatusBarWidget) {
JComponent component = ((CustomStatusBarWidget)widget).getComponent();
if (component.getBorder() == null) {
component.setBorder(widget instanceof IconLikeCustomStatusBarWidget ? StatusBarWidget.WidgetBorder.ICON
: StatusBarWidget.WidgetBorder.INSTANCE);
}
if (component instanceof JLabel) {
// wrap with panel so it will fill entire status bar height
return UI.Panels.simplePanel(component);
}
return component;
}
final StatusBarWidget.WidgetPresentation presentation =
widget.getPresentation(SystemInfoRt.isMac ? StatusBarWidget.PlatformType.MAC : StatusBarWidget.PlatformType.DEFAULT);
assert presentation != null : "Presentation should not be null!";
JComponent wrapper;
if (presentation instanceof StatusBarWidget.IconPresentation) {
wrapper = new IconPresentationWrapper((StatusBarWidget.IconPresentation)presentation);
wrapper.setBorder(StatusBarWidget.WidgetBorder.ICON);
}
else if (presentation instanceof StatusBarWidget.TextPresentation) {
wrapper = new TextPresentationWrapper((StatusBarWidget.TextPresentation)presentation);
wrapper.setBorder(StatusBarWidget.WidgetBorder.INSTANCE);
}
else if (presentation instanceof StatusBarWidget.MultipleTextValuesPresentation) {
wrapper = new MultipleTextValuesPresentationWrapper((StatusBarWidget.MultipleTextValuesPresentation)presentation);
wrapper.setBorder(StatusBarWidget.WidgetBorder.WIDE);
}
else {
throw new IllegalArgumentException("Unable to find a wrapper for presentation: " + presentation.getClass().getSimpleName());
}
wrapper.putClientProperty(UIUtil.CENTER_TOOLTIP_DEFAULT, Boolean.TRUE);
return wrapper;
}
private void hoverComponent(@Nullable Component component) {
if (myHoveredComponent != null) {
myHoveredComponent.setBackground(null);
}
if (component != null && component.isEnabled()) {
component.setBackground(JBUI.CurrentTheme.ActionButton.hoverBackground());
}
myHoveredComponent = component;
}
@Override
public boolean dispatch(@NotNull AWTEvent e) {
if (e instanceof MouseEvent) {
Component component = ((MouseEvent)e).getComponent();
if (component == null) {
return false;
}
Point point = SwingUtilities.convertPoint(component, ((MouseEvent)e).getPoint(), myRightPanel);
Component widget = myRightPanel.getComponentAt(point);
hoverComponent(widget != myRightPanel ? widget : null);
}
return false;
}
@Override
public String getUIClassID() {
return uiClassID;
}
@SuppressWarnings("MethodOverloadsMethodOfSuperclass")
protected void setUI(StatusBarUI ui) {
super.setUI(ui);
}
@Override
public void updateUI() {
if (UIManager.get(getUIClassID()) != null) {
setUI((StatusBarUI)UIManager.getUI(this));
}
else {
setUI(new StatusBarUI());
}
}
@Override
protected Graphics getComponentGraphics(Graphics g) {
return JBSwingUtilities.runGlobalCGTransform(this, super.getComponentGraphics(g));
}
public StatusBarUI getUI() {
return (StatusBarUI)ui;
}
@Override
public void removeWidget(@NotNull final String id) {
assert EventQueue.isDispatchThread() : "Must be EDT";
final WidgetBean bean = myWidgetMap.get(id);
if (bean != null) {
if (Position.LEFT == bean.position) {
myLeftPanel.remove(bean.component);
}
else if (Position.RIGHT == bean.position) {
final Component[] components = myRightPanel.getComponents();
for (final Component c : components) {
if (c == bean.component) break;
}
myRightPanel.remove(bean.component);
}
else {
myCenterPanel.remove(bean.component);
}
myWidgetMap.remove(bean.widget.ID());
Disposer.dispose(bean.widget);
repaint();
}
updateChildren(child -> child.removeWidget(id));
myOrderedWidgets.remove(id);
}
@Override
public void updateWidgets() {
for (final String s : myWidgetMap.keySet()) {
updateWidget(s);
}
updateChildren(IdeStatusBarImpl::updateWidgets);
}
@Override
public void updateWidget(@NotNull final String id) {
UIUtil.invokeLaterIfNeeded(() -> {
final WidgetBean bean = myWidgetMap.get(id);
if (bean != null) {
if (bean.component instanceof StatusBarWrapper) {
((StatusBarWrapper)bean.component).beforeUpdate();
}
bean.component.repaint();
}
updateChildren(child -> child.updateWidget(id));
});
}
@Override
@Nullable
public StatusBarWidget getWidget(String id) {
WidgetBean bean = myWidgetMap.get(id);
return bean == null ? null : bean.widget;
}
@Nullable
public JComponent getWidgetComponent(@NotNull String id) {
WidgetBean bean = myWidgetMap.get(id);
return bean == null ? null : bean.component;
}
@FunctionalInterface
private interface StatusBarWrapper {
void beforeUpdate();
}
private static final class MultipleTextValuesPresentationWrapper extends SimpleColoredComponent implements StatusBarWrapper {
private final StatusBarWidget.MultipleTextValuesPresentation myPresentation;
private MultipleTextValuesPresentationWrapper(@NotNull final StatusBarWidget.MultipleTextValuesPresentation presentation) {
myPresentation = presentation;
setVisible(presentation.getSelectedValue() != null);
new ClickListener() {
@Override
public boolean onClick(@NotNull MouseEvent e, int clickCount) {
final ListPopup popup = myPresentation.getPopupStep();
if (popup == null) return false;
final Dimension dimension = popup.getContent().getPreferredSize();
final Point at = new Point(0, -dimension.height);
popup.show(new RelativePoint(e.getComponent(), at));
return true;
}
}.installOn(this);
}
@Override
public Font getFont() {
return SystemInfoRt.isMac ? JBUI.Fonts.label(11) : JBFont.label();
}
@Override
public void beforeUpdate() {
clear();
String value = myPresentation.getSelectedValue();
if (value != null) {
append(value);
}
setVisible(value != null);
setToolTipText(myPresentation.getTooltipText());
}
}
private static final class TextPresentationWrapper extends TextPanel implements StatusBarWrapper {
private final StatusBarWidget.TextPresentation myPresentation;
private final Consumer<MouseEvent> myClickConsumer;
private TextPresentationWrapper(@NotNull final StatusBarWidget.TextPresentation presentation) {
myPresentation = presentation;
myClickConsumer = myPresentation.getClickConsumer();
setTextAlignment(presentation.getAlignment());
setVisible(!myPresentation.getText().isEmpty());
addMouseListener(new MouseAdapter() {
@Override
public void mousePressed(final MouseEvent e) {
if (myClickConsumer != null && !e.isPopupTrigger() && MouseEvent.BUTTON1 == e.getButton()) {
myClickConsumer.consume(e);
}
}
});
}
@Override
public void beforeUpdate() {
String text = myPresentation.getText();
setText(text);
setVisible(!text.isEmpty());
setToolTipText(myPresentation.getTooltipText());
}
}
private static final class IconPresentationWrapper extends TextPanel.WithIconAndArrows implements StatusBarWrapper {
private final StatusBarWidget.IconPresentation myPresentation;
private final Consumer<MouseEvent> myClickConsumer;
private IconPresentationWrapper(@NotNull final StatusBarWidget.IconPresentation presentation) {
myPresentation = presentation;
myClickConsumer = myPresentation.getClickConsumer();
setTextAlignment(Component.CENTER_ALIGNMENT);
setIcon(myPresentation.getIcon());
setVisible(hasIcon());
addMouseListener(new MouseAdapter() {
@Override
public void mousePressed(final MouseEvent e) {
if (myClickConsumer != null && !e.isPopupTrigger() && MouseEvent.BUTTON1 == e.getButton()) {
myClickConsumer.consume(e);
}
}
});
}
@Override
public void beforeUpdate() {
setIcon(myPresentation.getIcon());
setVisible(hasIcon());
setToolTipText(myPresentation.getTooltipText());
}
}
@Override
public IdeFrame getFrame() {
return myFrame;
}
@Override
public AccessibleContext getAccessibleContext() {
if (accessibleContext == null) {
accessibleContext = new AccessibleIdeStatusBarImpl();
}
return accessibleContext;
}
protected class AccessibleIdeStatusBarImpl extends AccessibleJComponent {
@Override
public AccessibleRole getAccessibleRole() {
return AccessibleRole.PANEL;
}
}
}
| 31.719041 | 140 | 0.674447 |
f9308da944c615c6bc2b98262952ef479fc3ecd1 | 1,211 |
package org.iib.icdd2ams;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.nio.file.Path;
import java.nio.file.Paths;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.slf4j.Marker;
import org.slf4j.MarkerFactory;
public class ToSQLTemplate {
private static Logger logger = LoggerFactory.getLogger(ToSQLTemplate.class);
private static final Marker Reasoning_MARKER = MarkerFactory.getMarker("icdd2ams");
public static void main(String[] args) {
try {
Path path = Paths.get(".").toAbsolutePath().normalize();
String pathJar = path.toFile().getAbsolutePath() + "/src/main/resources/ams/sparql-generate.jar";
ProcessBuilder pb = new ProcessBuilder("java", "-jar", pathJar,"-dt");
pb.redirectErrorStream(true);
Process p = pb.start();
String line;
InputStream stdout = p.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(stdout));
while ((line = reader.readLine()) != null) {
System.out.println("Stdout: " + line);
}
} catch (Throwable t) {
logger.error(Reasoning_MARKER, t.getMessage(), t);
}
}
}
| 29.536585 | 103 | 0.695293 |
6910d033a9ff4f815dc3470a5d7a44a2b9330282 | 4,011 | package com.java.utils;
import java.io.UnsupportedEncodingException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.spec.SecretKeySpec;
public class TripleDesUtil {
private static Cipher cipher;
/*明文存储*/
private static byte[] deskey;
private static final String UNICODE_FORM="utf-8";
private TripleDesUtil() {
try {
if (cipher == null) {
cipher = Cipher.getInstance("DESede");
}
//deskey = Configuration.getValue("pa18.tripleDes.key");
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
} catch (NoSuchPaddingException e) {
e.printStackTrace();
}
}
public static String encrypt(String value, String desKey) {
byte[] bk = new byte[24];
if(desKey==null){
return null;
} else if(desKey.length()<24){
int hash = desKey.hashCode() & 0xFF;
for(int i=0;i<bk.length;i++){
//bk[i] =(desKey.hashCode() & 0xFF);
}
}
String result = null;
try {
SecretKeySpec key = new SecretKeySpec(desKey.getBytes(), 0, 24, "DESede");
cipher.init(Cipher.ENCRYPT_MODE, key);
byte[] str = cipher.doFinal(value.getBytes(UNICODE_FORM));
System.out.println("加密后的byte[]长度:"+str.length);
result = byte2hex(str);
System.out.println("转换String后的byte[]长度:"+result.getBytes().length);
} catch (InvalidKeyException e) {
e.printStackTrace();
} catch (IllegalBlockSizeException e) {
e.printStackTrace();
} catch (BadPaddingException e) {
e.printStackTrace();
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return result;
}
public static String decrypt(String value, String desKey) {
String result = null;
try {
byte[] str = hex2byte(value);
System.out.println("转换后的密文byte[]长度:"+str.length);
SecretKeySpec key = new SecretKeySpec(desKey.getBytes(), 0, 24, "DESede");
cipher.init(Cipher.DECRYPT_MODE, key);
result = new String(cipher.doFinal(str),UNICODE_FORM);
} catch (InvalidKeyException e) {
e.printStackTrace();
} catch (IllegalBlockSizeException e) {
e.printStackTrace();
} catch (BadPaddingException e) {
e.printStackTrace();
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return result;
}
// 将加密后的密文转换成16进制字符串
private static String byte2hex(byte[] b)
{
String hs = "";
String stmp = "";
for (int n = 0; n < b.length; n++)
{
stmp = (java.lang.Integer.toHexString(b[n] & 0XFF));
if (stmp.length() == 1)
hs = hs + "0" + stmp;
else
hs = hs + stmp;
//if (n < b.length - 1)
//hs = hs + ":";
}
return hs.toUpperCase();
}
// 将16进制密文字符串反转换为byte[]
private static byte[] hex2byte(String word) throws StringIndexOutOfBoundsException
{
byte[] b = word.getBytes();
if ((b.length % 2) != 0)
{
throw new StringIndexOutOfBoundsException();
}
byte[] b2 = new byte[b.length / 2];
for (int n = 0; n < b.length; n += 2)
{
String item = new String(b, n, 2);
b2[n / 2] = (byte) Integer.parseInt(item, 16);
}
return b2;
}
public static void main(String[] args) {
String desKey ="keykeykeykeykeykeykeykeykeykeykeykey";
TripleDesUtil util = new TripleDesUtil();
String conent = "fdasfas倒萨uisfads大无畏挖啊……&*%……¥¥¥shhhadshudguasdussdrrerereerweqrgfqweurgqwuerg8q3u4triwuqergftuiasefgiasdufgasdf";
System.out.println("原文:"+conent);
String descontentString = util.encrypt(conent, desKey);
System.out.println("密文:"+descontentString);
String content2 = util.decrypt(descontentString, desKey);
System.out.println("解密后的明文:"+content2);
}
}
| 27.472603 | 133 | 0.644228 |
49d400668d99e78623f82736f7b0955354cb234c | 1,059 | package com.github.kebbbnnn.nextbutton.util;
import java.util.HashMap;
import java.util.Map;
import java.util.Stack;
/**
* Created by kevinladan on 3/19/17.
*/
public class Utils {
public static boolean isValidExpression(String expression) {
Map<Character, Character> openClosePair = new HashMap<>();
openClosePair.put(')', '(');
openClosePair.put('}', '{');
openClosePair.put('[', ']');
Stack<Character> stack = new Stack<>();
for (char ch : expression.toCharArray()) {
if (openClosePair.containsKey(ch)) {
if (stack.pop() != openClosePair.get(ch)) {
return false;
}
} else if (openClosePair.values().contains(ch)) {
stack.push(ch);
}
}
return stack.isEmpty();
}
public static String removeClosePair(String s) {
return s.replaceAll("[\\[\\](){}]", "");
}
public static String removeWhiteSpace(String s) {
return s.replaceAll("\\s+", "");
}
}
| 27.153846 | 66 | 0.552408 |
84c2364642d23e69169750ed47f8280dd5cc89db | 464 | r#"package org.example;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
public final class ReturnNullableValue {
public static @NonNull java.util.Optional<String> getOpt() {
String ret = do_getOpt();
java.util.Optional<String> convRet = java.util.Optional.ofNullable(ret);
return convRet;
}
private static native @Nullable String do_getOpt();
private ReturnNullableValue() {}
}"#;
| 27.294118 | 80 | 0.715517 |
6a32d342657456f1406dab8c6432c4e33761d4d1 | 6,062 | package com.Da_Technomancer.essentials.blocks;
import com.Da_Technomancer.essentials.ESConfig;
import com.Da_Technomancer.essentials.Essentials;
import net.minecraft.core.BlockPos;
import net.minecraft.core.Direction;
import net.minecraft.core.particles.ParticleTypes;
import net.minecraft.nbt.CompoundTag;
import net.minecraft.network.chat.Component;
import net.minecraft.network.chat.TranslatableComponent;
import net.minecraft.network.protocol.Packet;
import net.minecraft.server.level.ServerLevel;
import net.minecraft.world.InteractionHand;
import net.minecraft.world.InteractionResult;
import net.minecraft.world.damagesource.DamageSource;
import net.minecraft.world.effect.MobEffectInstance;
import net.minecraft.world.effect.MobEffects;
import net.minecraft.world.entity.Entity;
import net.minecraft.world.entity.EntityType;
import net.minecraft.world.entity.LivingEntity;
import net.minecraft.world.entity.player.Player;
import net.minecraft.world.entity.projectile.WitherSkull;
import net.minecraft.world.item.ItemStack;
import net.minecraft.world.item.TooltipFlag;
import net.minecraft.world.item.context.BlockPlaceContext;
import net.minecraft.world.level.BlockGetter;
import net.minecraft.world.level.Explosion;
import net.minecraft.world.level.Level;
import net.minecraft.world.level.block.Block;
import net.minecraft.world.level.block.state.BlockState;
import net.minecraft.world.level.block.state.StateDefinition;
import net.minecraft.world.phys.BlockHitResult;
import net.minecraft.world.phys.EntityHitResult;
import net.minecraft.world.phys.HitResult;
import net.minecraftforge.api.distmarker.Dist;
import net.minecraftforge.api.distmarker.OnlyIn;
import net.minecraftforge.network.NetworkHooks;
import net.minecraftforge.registries.ObjectHolder;
import javax.annotation.Nullable;
import java.util.List;
import java.util.Random;
@ObjectHolder(Essentials.MODID)
public class WitherCannon extends Block{
@ObjectHolder("cannon_skull")
public static EntityType<CannonSkull> ENT_TYPE;
protected WitherCannon(){
super(ESBlocks.getRockProperty().strength(50F, 1200F));
String name = "wither_cannon";
setRegistryName(name);
ESBlocks.toRegister.add(this);
ESBlocks.blockAddQue(this);
registerDefaultState(defaultBlockState().setValue(ESProperties.REDSTONE_BOOL, false));
}
@Nullable
@Override
public BlockState getStateForPlacement(BlockPlaceContext context){
return defaultBlockState().setValue(ESProperties.FACING, context.getNearestLookingDirection());
}
@Override
protected void createBlockStateDefinition(StateDefinition.Builder<Block, BlockState> builder){
builder.add(ESProperties.FACING).add(ESProperties.REDSTONE_BOOL);
}
@Override
public InteractionResult use(BlockState state, Level worldIn, BlockPos pos, Player playerIn, InteractionHand hand, BlockHitResult hit){
if(ESConfig.isWrench(playerIn.getItemInHand(hand))){
if(!worldIn.isClientSide){
BlockState endState = state.cycle(ESProperties.FACING);//MCP note: cycle
worldIn.setBlockAndUpdate(pos, endState);
}
return InteractionResult.SUCCESS;
}
return InteractionResult.PASS;
}
@Override
public void appendHoverText(ItemStack stack, @Nullable BlockGetter world, List<Component> tooltip, TooltipFlag advanced){
tooltip.add(new TranslatableComponent("tt.essentials.wither_cannon"));
}
@Override
public void neighborChanged(BlockState state, Level world, BlockPos pos, Block block, BlockPos srcPos, boolean flag){
boolean powered = world.hasNeighborSignal(pos) || world.hasNeighborSignal(pos.above());
boolean wasActive = state.getValue(ESProperties.REDSTONE_BOOL);
if(powered && !wasActive){
world.scheduleTick(pos, this, 4);
world.setBlock(pos, state.setValue(ESProperties.REDSTONE_BOOL, true), 4);
}else if(!powered && wasActive){
world.setBlock(pos, state.setValue(ESProperties.REDSTONE_BOOL, false), 4);
}
}
@Override
public void tick(BlockState state, ServerLevel world, BlockPos pos, Random rand){
Direction dir = state.getValue(ESProperties.FACING);
BlockPos spawnPos = pos.relative(dir);
WitherSkull skull = new CannonSkull(ENT_TYPE, world);
skull.moveTo(spawnPos.getX() + 0.5D, spawnPos.getY() + 0.5D, spawnPos.getZ() + 0.5D, dir.toYRot() + 180, dir.getStepY() * -90);
skull.setDeltaMovement(dir.getStepX() / 5F, dir.getStepY() / 5F, dir.getStepZ() / 5F);
skull.xPower = dir.getStepX() / 20D;
skull.yPower = dir.getStepY() / 20D;
skull.zPower = dir.getStepZ() / 20D;
world.addFreshEntity(skull);
}
public static class CannonSkull extends WitherSkull{
private int lifespan = 60;
public CannonSkull(EntityType<CannonSkull> type, Level world){
super(type, world);
}
@Override
public void tick(){
super.tick();
if(!level.isClientSide && lifespan-- <= 0){
level.addAlwaysVisibleParticle(ParticleTypes.SMOKE, getX(), getY(), getZ(), 0, 0, 0);
remove(RemovalReason.DISCARDED);
}
}
@Override
public void addAdditionalSaveData(CompoundTag nbt){
super.addAdditionalSaveData(nbt);
nbt.putInt("lifetime", lifespan);
}
@Override
public void readAdditionalSaveData(CompoundTag nbt){
super.readAdditionalSaveData(nbt);
lifespan = nbt.getInt("lifetime");
}
@Override
protected void onHit(HitResult result){
if(!level.isClientSide){
if(result.getType() == HitResult.Type.ENTITY){
Entity entity = ((EntityHitResult) result).getEntity();
entity.hurt(DamageSource.MAGIC, 5F);
if(entity instanceof LivingEntity){
//Locked at normal difficulty duration, because this is a redstone component meant to be precise and utilized and not an evil monster that exists to stab you
((LivingEntity) entity).addEffect(new MobEffectInstance(MobEffects.WITHER, 200, 1));
}
}
//Ignore mob griefing- always use Explosion.Mode.DESTROY
level.explode(this, getX(), getY(), getZ(), 2F, false, Explosion.BlockInteraction.BREAK);
remove(RemovalReason.DISCARDED);
}
}
@Override
public Packet<?> getAddEntityPacket(){
return NetworkHooks.getEntitySpawningPacket(this);
}
}
}
| 36.739394 | 163 | 0.774002 |
2e96b0b77e83e5c79945e45f2cfb1db5ba593a2e | 14,251 | /*-
* ============LICENSE_START=======================================================
* SDC
* ================================================================================
* Copyright (C) 2017 AT&T Intellectual Property. 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.
* ============LICENSE_END=========================================================
*/
package org.openecomp.sdc.be.servlets;
import com.jcabi.aspects.Loggable;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.media.ArraySchema;
import io.swagger.v3.oas.annotations.media.Content;
import io.swagger.v3.oas.annotations.media.Schema;
import io.swagger.v3.oas.annotations.responses.ApiResponse;
import io.swagger.v3.oas.annotations.servers.Server;
import io.swagger.v3.oas.annotations.servers.Servers;
import io.swagger.v3.oas.annotations.tags.Tag;
import io.swagger.v3.oas.annotations.tags.Tags;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import javax.ws.rs.Consumes;
import javax.ws.rs.DELETE;
import javax.ws.rs.GET;
import javax.ws.rs.HeaderParam;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.QueryParam;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import org.eclipse.jetty.http.HttpStatus;
import org.openecomp.sdc.be.components.impl.aaf.AafPermission;
import org.openecomp.sdc.be.components.impl.aaf.PermissionAllowed;
import org.openecomp.sdc.be.impl.ComponentsUtils;
import org.openecomp.sdc.be.model.User;
import org.openecomp.sdc.be.user.Role;
import org.openecomp.sdc.be.user.UserBusinessLogic;
import org.openecomp.sdc.be.user.UserBusinessLogicExt;
import org.openecomp.sdc.common.api.Constants;
import org.openecomp.sdc.common.log.wrappers.Logger;
import org.springframework.stereotype.Controller;
@Loggable(prepend = true, value = Loggable.DEBUG, trim = false)
@Path("/v1/user")
@Tags({@Tag(name = "SDCE-2 APIs")})
@Servers({@Server(url = "/sdc2/rest")})
@Controller
public class UserAdminServlet extends BeGenericServlet {
private static final String UTF_8 = "UTF-8";
private static final String ROLE_DELIMITER = ",";
private static final Logger log = Logger.getLogger(UserAdminServlet.class);
private final UserBusinessLogic userBusinessLogic;
private final UserBusinessLogicExt userBusinessLogicExt;
UserAdminServlet(UserBusinessLogic userBusinessLogic, ComponentsUtils componentsUtils, UserBusinessLogicExt userBusinessLogicExt) {
super(userBusinessLogic, componentsUtils);
this.userBusinessLogic = userBusinessLogic;
this.userBusinessLogicExt = userBusinessLogicExt;
}
// retrieve all user details
@GET
@Path("/{userId}")
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
@Operation(description = "retrieve user details", method = "GET", summary = "Returns user details according to userId", responses = {
@ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = User.class)))),
@ApiResponse(responseCode = "200", description = "Returns user Ok"), @ApiResponse(responseCode = "404", description = "User not found"),
@ApiResponse(responseCode = "405", description = "Method Not Allowed"),
@ApiResponse(responseCode = "500", description = "Internal Server Error")})
@PermissionAllowed(AafPermission.PermNames.INTERNAL_ALL_VALUE)
public User get(@Parameter(description = "userId of user to get", required = true) @PathParam("userId") final String userId,
@Context final HttpServletRequest request) {
return userBusinessLogic.getUser(userId, false);
}
/////////////////////////////////////////////////////////////////////////////////////////////////////
@GET
@Path("/{userId}/role")
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
@Operation(description = "retrieve user role", summary = "Returns user role according to userId", responses = {
@ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = String.class)))),
@ApiResponse(responseCode = "200", description = "Returns user role Ok"), @ApiResponse(responseCode = "404", description = "User not found"),
@ApiResponse(responseCode = "405", description = "Method Not Allowed"),
@ApiResponse(responseCode = "500", description = "Internal Server Error")})
@PermissionAllowed(AafPermission.PermNames.INTERNAL_ALL_VALUE)
public String getRole(@Parameter(description = "userId of user to get", required = true) @PathParam("userId") final String userId,
@Context final HttpServletRequest request) {
User user = userBusinessLogic.getUser(userId, false);
return "{ \"role\" : \"" + user.getRole() + "\" }";
}
// update user role
@POST
@Path("/{userId}/role")
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
@Operation(description = "update user role", summary = "Update user role", responses = {
@ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = User.class)))),
@ApiResponse(responseCode = "200", description = "Update user OK"), @ApiResponse(responseCode = "400", description = "Invalid Content."),
@ApiResponse(responseCode = "403", description = "Missing information/Restricted operation"),
@ApiResponse(responseCode = "404", description = "User not found"), @ApiResponse(responseCode = "405", description = "Method Not Allowed"),
@ApiResponse(responseCode = "409", description = "User already exists"),
@ApiResponse(responseCode = "500", description = "Internal Server Error")})
@PermissionAllowed(AafPermission.PermNames.INTERNAL_ALL_VALUE)
public User updateUserRole(@Parameter(description = "userId of user to get", required = true) @PathParam("userId") final String userIdUpdateUser,
@Context final HttpServletRequest request,
@Parameter(description = "json describe the update role", required = true) UserRole newRole,
@HeaderParam(value = Constants.USER_ID_HEADER) String modifierUserId) {
return userBusinessLogic.updateUserRole(modifierUserId, userIdUpdateUser, newRole.getRole().name());
}
/////////////////////////////////////////////////////////////////////////////////////////////////////
@POST
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
@Operation(description = "add user", method = "POST", summary = "Provision new user", responses = {
@ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = User.class)))),
@ApiResponse(responseCode = "201", description = "New user created"), @ApiResponse(responseCode = "400", description = "Invalid Content."),
@ApiResponse(responseCode = "403", description = "Missing information"),
@ApiResponse(responseCode = "405", description = "Method Not Allowed"),
@ApiResponse(responseCode = "409", description = "User already exists"),
@ApiResponse(responseCode = "500", description = "Internal Server Error")})
public Response createUser(@Context final HttpServletRequest request,
@Parameter(description = "json describe the user", required = true) User newUser,
@HeaderParam(value = Constants.USER_ID_HEADER) String modifierAttId) {
log.debug("modifier id is {}", modifierAttId);
User user = userBusinessLogic.createUser(modifierAttId, newUser);
return Response.status(HttpStatus.CREATED_201).entity(user).build();
}
@GET
@Path("/authorize")
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
@Operation(description = "authorize", summary = "authorize user", responses = {
@ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = User.class)))),
@ApiResponse(responseCode = "200", description = "Returns user Ok"), @ApiResponse(responseCode = "403", description = "Restricted Access"),
@ApiResponse(responseCode = "500", description = "Internal Server Error")})
@PermissionAllowed(AafPermission.PermNames.INTERNAL_ALL_VALUE)
public User authorize(@HeaderParam(value = Constants.USER_ID_HEADER) String userId, @HeaderParam("HTTP_CSP_FIRSTNAME") String firstName,
@HeaderParam("HTTP_CSP_LASTNAME") String lastName, @HeaderParam("HTTP_CSP_EMAIL") String email)
throws UnsupportedEncodingException {
userId = userId != null ? URLDecoder.decode(userId, UTF_8) : null;
firstName = firstName != null ? URLDecoder.decode(firstName, UTF_8) : null;
lastName = lastName != null ? URLDecoder.decode(lastName, UTF_8) : null;
email = email != null ? URLDecoder.decode(email, UTF_8) : null;
User authUser = new User();
authUser.setUserId(userId);
authUser.setFirstName(firstName);
authUser.setLastName(lastName);
authUser.setEmail(email);
return userBusinessLogic.authorize(authUser);
}
@GET
@Path("/admins")
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
@Operation(description = "retrieve all administrators", method = "GET", summary = "Returns all administrators", responses = {
@ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = User.class)))),
@ApiResponse(responseCode = "200", description = "Returns user Ok"), @ApiResponse(responseCode = "405", description = "Method Not Allowed"),
@ApiResponse(responseCode = "500", description = "Internal Server Error")})
@PermissionAllowed(AafPermission.PermNames.INTERNAL_ALL_VALUE)
public List<User> getAdminsUser(@Context final HttpServletRequest request) {
return userBusinessLogic.getAllAdminUsers();
}
@GET
@Path("/users")
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
@Operation(description = "Retrieve the list of all active ASDC users or only group of users having specific roles.", method = "GET", summary = "Returns list of users with the specified roles, or all of users in the case of empty 'roles' header", responses = {
@ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = User.class)))),
@ApiResponse(responseCode = "200", description = "Returns users Ok"),
@ApiResponse(responseCode = "204", description = "No provisioned ASDC users of requested role"),
@ApiResponse(responseCode = "403", description = "Restricted Access"), @ApiResponse(responseCode = "400", description = "Missing content"),
@ApiResponse(responseCode = "500", description = "Internal Server Error")})
public List<User> getUsersList(@Context final HttpServletRequest request,
@Parameter(description = "Any active user's USER_ID ") @HeaderParam(Constants.USER_ID_HEADER) final String userId,
@Parameter(description = "TESTER,DESIGNER,PRODUCT_STRATEGIST,OPS,PRODUCT_MANAGER,GOVERNOR, ADMIN OR all users by not typing anything") @QueryParam("roles") final String roles) {
String url = request.getMethod() + " " + request.getRequestURI();
log.debug("Start handle request of {} modifier id is {}", url, userId);
List<String> rolesList = new ArrayList<>();
if (roles != null && !roles.trim().isEmpty()) {
String[] rolesArr = roles.split(ROLE_DELIMITER);
for (String role : rolesArr) {
rolesList.add(role.trim());
}
}
return userBusinessLogic.getUsersList(userId, rolesList, roles);
}
@DELETE
@Path("/{userId}")
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
@Operation(description = "delete user", summary = "Delete user", responses = {
@ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = User.class)))),
@ApiResponse(responseCode = "200", description = "Update deleted OK"), @ApiResponse(responseCode = "400", description = "Invalid Content."),
@ApiResponse(responseCode = "403", description = "Missing information"), @ApiResponse(responseCode = "404", description = "User not found"),
@ApiResponse(responseCode = "405", description = "Method Not Allowed"),
@ApiResponse(responseCode = "409", description = "Restricted operation"),
@ApiResponse(responseCode = "500", description = "Internal Server Error")})
@PermissionAllowed(AafPermission.PermNames.INTERNAL_ALL_VALUE)
public User deActivateUser(@Parameter(description = "userId of user to get", required = true) @PathParam("userId") final String userId,
@Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String modifierId) {
return userBusinessLogicExt.deActivateUser(modifierId, userId);
}
static class UserRole {
Role role;
public Role getRole() {
return role;
}
public void setRole(Role role) {
this.role = role;
}
}
}
| 58.167347 | 263 | 0.676163 |
145de9b71f9c2aa4262f5bae42d7d79aab7bd8b6 | 1,359 | package net.lazyio.oretree.impl;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import net.lazyio.oretree.api.IOreTree;
import net.lazyio.oretree.api.OreTreesAPI;
import net.lazyio.oretree.block.OreLeavesBlock;
import net.minecraft.util.ResourceLocation;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
public class OreTreeAPIImpl implements OreTreesAPI {
private static final HashMap<ResourceLocation, IOreTree> ORES_TREES = new HashMap<>();
private static final List<OreLeavesBlock> ORE_LEAVES_TINT = new ArrayList<>();
@Override
public void applyOreLeavesForBlockTint(OreLeavesBlock oreLeavesBlock) {
ORE_LEAVES_TINT.add(oreLeavesBlock);
}
@Override
public ImmutableList<OreLeavesBlock> getAppliedOreLeavesForTint() {
return ImmutableList.copyOf(ORE_LEAVES_TINT);
}
@Override
public void registerOre(ResourceLocation id, IOreTree oreIn) {
if (!ORES_TREES.containsKey(id)) {
ORES_TREES.put(id, oreIn);
}
}
@Override
public ImmutableMap<ResourceLocation, IOreTree> getRegisteredOreTrees() {
return ImmutableMap.copyOf(ORES_TREES);
}
@Override
public ImmutableList<IOreTree> getOreTrees() {
return ImmutableList.copyOf(ORES_TREES.values());
}
}
| 29.543478 | 90 | 0.738779 |
b43d349adc36bf0674a4edd0687ecf8f92a3e2db | 1,152 | package cs451;
import java.util.ArrayList;
public class PerfectLinks implements Links, Observer {
private StubbornLinks stb;
private Observer observer;
private ArrayList<Message> delivered;
public PerfectLinks(Observer observer){
this.stb = new StubbornLinks(this);
this.observer = observer;
this.delivered = new ArrayList<>();
}
@Override
public void send(Message message){
//System.out.println(String.format("Sending message %d, on link %s",message.getSeqNbr(),"PL"));
if(observer == null){
OutputWriter.writeBroadcast(message, true);
}
stb.send(message);
}
@Override
public void deliver(Message message){
//System.out.println(String.format("Delivering message %d, on link %s",message.getSeqNbr(),"PL"));
if (!delivered.contains(message)){
if(observer == null){
OutputWriter.writeDeliver(message, true);
} else {
observer.deliver(message);
}
delivered.add(message);
}
}
@Override
public void handleAck(Ack ack) { }
}
| 26.181818 | 106 | 0.605035 |
ed3f8f9f0c1851ddada11383e2525bab47736fee | 2,874 | package net.christophe.genin.monitor.domain.server;
import io.vertx.core.DeploymentOptions;
import io.vertx.core.json.JsonObject;
import io.vertx.ext.unit.Async;
import io.vertx.ext.unit.TestContext;
import io.vertx.ext.unit.junit.VertxUnitRunner;
import io.vertx.rxjava.core.Vertx;
import net.christophe.genin.monitor.domain.server.base.DbTest;
import net.christophe.genin.monitor.domain.server.base.NitriteDBManagemementTest;
import net.christophe.genin.monitor.domain.server.db.mysql.FlywayVerticle;
import org.junit.After;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import org.junit.runner.RunWith;
import rx.Observable;
@RunWith(VertxUnitRunner.class)
public class MysqlDatabaseTest extends DbTest {
private static DeploymentOptions option;
private Vertx vertx;
@BeforeClass
public static void first() throws Exception {
option = new NitriteDBManagemementTest(MysqlDatabaseTest.class).deleteAndGetOption();
}
@Before
public void before(TestContext context) {
vertx = Vertx.vertx();
Async async = context.async(3);
Observable.concat(
vertx.rxDeployVerticle(Database.class.getName(), option).toObservable(),
vertx.rxDeployVerticle(FlywayVerticle.class.getName(), option).toObservable()
).reduce("", (acc, s) -> s)
.subscribe(r -> {
async.countDown();
setAntiMonitorDS(context, async, vertx);
}, context::fail);
}
@After
public void after(TestContext context) {
vertx.close(context.asyncAssertSuccess());
}
@Test
public void should_health_respond_after_starting(TestContext context) {
Async async = context.async();
vertx.eventBus().<JsonObject>send(Database.HEALTH, new JsonObject(), msg -> {
try {
JsonObject body = msg.result().body();
context.assertNotNull(body);
context.assertEquals(true, body.getBoolean("mysql"));
context.assertNotNull(body.getJsonArray("health"));
async.complete();
} catch (Exception ex) {
context.fail(ex);
}
});
}
@Test
public void should_create_mysql_schema(TestContext context) {
Async async = context.async();
vertx.eventBus().<JsonObject>send(Database.MYSQL_CREATE_SCHEMA, new JsonObject(), msg -> {
try {
JsonObject body = msg.result().body();
context.assertNotNull(body);
context.assertEquals(true, body.getBoolean("active"));
context.assertEquals(true, body.getBoolean("creation"));
async.complete();
} catch (Exception ex) {
context.fail(ex);
}
});
}
}
| 32.659091 | 98 | 0.63396 |
4694166689da24d96d6303fadaa3fb9cc28f76bd | 1,253 | package com.cky.learnandroiddetails.UnitTestExample;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import com.cky.learnandroiddetails.R;
/*
* 参考http://stackoverflow.com/questions/2047261/using-android-test-framework
* http://evgenii.com/blog/testing-activity-in-android-studio-tutorial-part-1/
* */
public class TestUnitTestAct extends AppCompatActivity {
EditText mEditText;
TextView mTextView;
Button mButton;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_test_unit_test);
mEditText = (EditText) findViewById(R.id.edit_text);
mTextView = (TextView) findViewById(R.id.text_view);
mButton = (Button) findViewById(R.id.button);
mButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
String name = mEditText.getText().toString();
String s = String.format("Hello, %s", name);
mTextView.setText(s);
}
});
}
}
| 29.833333 | 77 | 0.689545 |
bd00b02665dba84d254fc1c1266253e10a315f63 | 166 |
public class Test {
@lombok.EqualsAndHashCode
class Car {
}
@lombok.EqualsAndHashCode(callSuper = true)
class Ferrari extends Car {
}
}
| 11.857143 | 46 | 0.626506 |
8fa5b5457151eb75d95dd5b80134a3c86e8f717b | 2,580 | package tads.tdm.mediaescolar.fragmets;
import android.tdm.mediaescolar.R;
import android.tdm.mediaescolar.adapter.ResultadoFinalListAdapter;
import android.tdm.mediaescolar.controller.MediaEscolarController;
import android.tdm.mediaescolar.model.MediaEscolar;
import android.os.Bundle;
import android.support.design.widget.Snackbar;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ListView;
import java.util.ArrayList;
import tads.tdm.mediaescolar.controller.MediaEscolarController;
public class ResultadoFinalFragment extends Fragment {
// Adapter
// dataSet com os dados
ArrayList<MediaEscolar> dataSet;
// ListView para apresentar os dados
ListView listView;
// Controller para buscar os dados no DB
MediaEscolarController controller;
// novo método na controller getResultadoFinal devolvendo um ArrayList
// Efeito de Animação da Lista
View view;
public ResultadoFinalFragment() {
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
@Override
public View onCreateView(LayoutInflater inflater,
ViewGroup container,
Bundle savedInstanceState) {
view = inflater.inflate(R.layout.fragment_resultado_final,
container,
false);
controller = new MediaEscolarController(getContext());
listView = view.findViewById(R.id.listview);
dataSet = controller.getAllResultadoFinal();
final ResultadoFinalListAdapter adapter =
new ResultadoFinalListAdapter(dataSet, getContext());
listView.setAdapter(adapter);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
MediaEscolar mediaEscolar = dataSet.get(position);
Snackbar.make(view, mediaEscolar.getMateria() +
"\n" + mediaEscolar.getSituacao() +
" Média Final: " +
mediaEscolar.getMediaFinal(), Snackbar.LENGTH_LONG)
.setAction("No action", null).show();
dataSet = controller.getAllResultadoFinal();
adapter.atualizarLista(dataSet);
}
});
return view;
}
} | 28.988764 | 94 | 0.666279 |
8257a050c6c700100c20d6ef4125b9a4426db1f4 | 2,350 | package com.github.gv2011.quarry.nfs.swing;
import static com.github.gv2011.util.ex.Exceptions.notYetImplementedException;
import static org.slf4j.LoggerFactory.getLogger;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import javax.swing.event.TreeModelEvent;
import javax.swing.event.TreeModelListener;
import javax.swing.tree.TreeModel;
import javax.swing.tree.TreePath;
import org.slf4j.Logger;
import com.github.gv2011.quarry.nfs.Invalidatable;
import com.github.gv2011.quarry.nfs.Node;
class NodeTreeModel implements TreeModel{
private static final Logger LOG = getLogger(NodeTreeModel.class);
private final Node root;
private final List<TreeModelListener> listeners = new ArrayList<>();
private final Invalidatable display;
NodeTreeModel(final Node root, final Invalidatable display) {
this.root = root;
this.display = display;
}
@Override
public Node getRoot() {
return root;
}
@Override
public Node getChild(final Object parent, final int index) {
return ((Node)parent).value(display).get().children().get(index);
}
@Override
public int getChildCount(final Object parent) {
final Node node = (Node)parent;
final Optional<Integer> count = node.value(display).map(v->v.children().size());
LOG.debug("{}: {} children.", node, count.map(Object::toString).orElse("unkown"));
return count.orElse(0);
}
@Override
public boolean isLeaf(final Object node) {
final boolean isLeaf = getChildCount(node)==0;
LOG.debug("{}: {}", node, isLeaf?"leaf":"not leaf");
return isLeaf;
}
@Override
public void valueForPathChanged(final TreePath path, final Object newValue) {
throw notYetImplementedException();
}
@Override
public int getIndexOfChild(final Object parent, final Object child) {
if(parent==null || child==null) return -1;
else return ((Node)parent).value(display).get().children().indexOf(child);
}
@Override
public void addTreeModelListener(final TreeModelListener l) {
listeners.add(l);
}
@Override
public void removeTreeModelListener(final TreeModelListener l) {
listeners.remove(l);
}
void invalidate() {
final TreeModelEvent e = new TreeModelEvent(null, new Object[]{});
for(final TreeModelListener l: listeners){
l.treeStructureChanged(e);
}
}
}
| 26.704545 | 86 | 0.722979 |
19ca51f7e7e33982cf315e26894cb7cab151657f | 6,204 | /*******************************************************************************
* * Copyright 2012 Impetus Infotech.
* *
* * 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.impetus.client.twitter.dao;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Query;
import com.impetus.client.twitter.entities.ExternalLinkRDBMS;
import com.impetus.client.twitter.entities.PreferenceRDBMS;
import com.impetus.client.twitter.entities.TweetRDBMS;
import com.impetus.client.twitter.entities.UserRDBMS;
/**
* Data access object class for implementation of twitter.
*
* @author amresh.singh
*/
public class TwitterService extends SuperDao implements Twitter
{
private EntityManager em;
private EntityManagerFactory emf;
private String pu;
public TwitterService(String persistenceUnitName)
{
this.pu = persistenceUnitName;
if (emf == null)
{
try
{
emf = createEntityManagerFactory(persistenceUnitName);
}
catch (Exception e)
{
}
}
}
@Override
public void createEntityManager()
{
if (em == null)
{
em = emf.createEntityManager();
}
}
@Override
public void closeEntityManager()
{
if (em != null)
{
em.close();
em = null;
}
}
@Override
public void close()
{
if (emf != null)
{
emf.close();
}
}
@Override
public void addUser(UserRDBMS user)
{
em.persist(user);
}
@Override
public void addUser(String userId, String name, String password, String relationshipStatus)
{
UserRDBMS user = new UserRDBMS(userId, name, password, relationshipStatus);
em.persist(user);
}
@Override
public void savePreference(String userId, PreferenceRDBMS preference)
{
UserRDBMS user = em.find(UserRDBMS.class, userId);
user.setPreference(preference);
em.persist(user);
}
@Override
public void addExternalLink(String userId, String linkId, String linkType, String linkAddress)
{
UserRDBMS user = em.find(UserRDBMS.class, userId);
user.addExternalLink(new ExternalLinkRDBMS(linkId, linkType, linkAddress));
em.persist(user);
}
@Override
public void addTweet(String userId, String tweetBody, String device)
{
UserRDBMS user = em.find(UserRDBMS.class, userId);
user.addTweet(new TweetRDBMS(tweetBody, device));
em.persist(user);
}
@Override
public void startFollowing(String userId, String friendUserId)
{
UserRDBMS user = em.find(UserRDBMS.class, userId);
UserRDBMS friend = em.find(UserRDBMS.class, friendUserId);
user.addFriend(friend);
em.persist(user);
friend.addFollower(user);
em.persist(friend);
}
@Override
public void addFollower(String userId, String followerUserId)
{
UserRDBMS user = em.find(UserRDBMS.class, userId);
UserRDBMS follower = em.find(UserRDBMS.class, followerUserId);
user.addFollower(follower);
em.persist(user);
}
@Override
public UserRDBMS findUserById(String userId)
{
UserRDBMS user = em.find(UserRDBMS.class, userId);
return user;
}
@Override
public void removeUser(UserRDBMS user)
{
em.remove(user);
}
@Override
public void mergeUser(UserRDBMS user)
{
em.merge(user);
}
@Override
public List<UserRDBMS> getAllUsers()
{
Query q = em.createQuery("select u from UserRDBMS u");
List<UserRDBMS> users = q.getResultList();
return users;
}
@Override
public List<TweetRDBMS> getAllTweets(String userId)
{
Query q = em.createQuery("select u from UserRDBMS u where u.userId =:userId");
q.setParameter("userId", userId);
List<UserRDBMS> users = q.getResultList();
if (users == null || users.isEmpty())
{
return null;
}
else
{
return users.get(0).getTweets();
}
}
@Override
public List<UserRDBMS> getFollowers(String userId)
{
Query q = em.createQuery("select u from UserRDBMS u where u.userId =:userId");
q.setParameter("userId", userId);
List<UserRDBMS> users = q.getResultList();
if (users == null || users.isEmpty())
{
return null;
}
return users.get(0).getFollowers();
}
@Override
public List<TweetRDBMS> findTweetByBody(String tweetBody)
{
Query q = em.createQuery("select u.tweet_body from UserRDBMS u where u.tweet_body like :body");
q.setParameter("body", tweetBody);
List<TweetRDBMS> tweets = q.getResultList();
return tweets;
}
@Override
public List<TweetRDBMS> findTweetByDevice(String deviceName)
{
Query q = em.createQuery("select u.tweeted_from from UserRDBMS u where u.tweeted_from like :device");
q.setParameter("device", deviceName);
List<TweetRDBMS> tweets = q.getResultList();
return tweets;
}
}
| 27.330396 | 110 | 0.582527 |
ff222a3f447b18787bf8ba33cad517b44bb38cae | 186 | public class UMUC_IntDemo {
public static void main(String[] args) {
int carCount = 123456;
System.out.print("The int carCount : ");
System.out.println(carCount);
}
}
| 18.6 | 44 | 0.655914 |
d8bab431ec1f7fd13b5806b5d80c28b12f65ca71 | 19,000 | package com.tngtech.jgiven.impl;
import static com.google.common.collect.Lists.newArrayList;
import static com.google.common.collect.Lists.reverse;
import static com.tngtech.jgiven.impl.ScenarioExecutor.State.FINISHED;
import static com.tngtech.jgiven.impl.ScenarioExecutor.State.STARTED;
import com.tngtech.jgiven.CurrentScenario;
import com.tngtech.jgiven.CurrentStep;
import com.tngtech.jgiven.annotation.Pending;
import com.tngtech.jgiven.annotation.ScenarioRule;
import com.tngtech.jgiven.annotation.ScenarioStage;
import com.tngtech.jgiven.attachment.Attachment;
import com.tngtech.jgiven.exception.FailIfPassedException;
import com.tngtech.jgiven.exception.JGivenMissingRequiredScenarioStateException;
import com.tngtech.jgiven.exception.JGivenUserException;
import com.tngtech.jgiven.impl.inject.ValueInjector;
import com.tngtech.jgiven.impl.intercept.NoOpScenarioListener;
import com.tngtech.jgiven.impl.intercept.ScenarioListener;
import com.tngtech.jgiven.impl.intercept.StageTransitionHandler;
import com.tngtech.jgiven.impl.intercept.StepInterceptorImpl;
import com.tngtech.jgiven.impl.util.FieldCache;
import com.tngtech.jgiven.impl.util.ReflectionUtil;
import com.tngtech.jgiven.integration.CanWire;
import com.tngtech.jgiven.report.model.InvocationMode;
import com.tngtech.jgiven.report.model.NamedArgument;
import java.lang.annotation.Annotation;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Main class of JGiven for executing scenarios.
*/
public class ScenarioExecutor {
private static final Logger log = LoggerFactory.getLogger(ScenarioExecutor.class);
enum State {
INIT,
STARTED,
FINISHED
}
private Object currentTopLevelStage;
private State state = State.INIT;
private boolean beforeScenarioMethodsExecuted;
/**
* Whether life cycle methods should be executed.
* This is only false for scenarios that are annotated with @NotImplementedYet
*/
private boolean executeLifeCycleMethods = true;
protected final Map<Class<?>, StageState> stages = new LinkedHashMap<>();
private final List<Object> scenarioRules = new ArrayList<>();
private final ValueInjector injector = new ValueInjector();
private StageCreator stageCreator = createStageCreator(new ByteBuddyStageClassCreator());
private ScenarioListener listener = new NoOpScenarioListener();
protected final StageTransitionHandler stageTransitionHandler = new StageTransitionHandlerImpl();
protected final StepInterceptorImpl methodInterceptor =
new StepInterceptorImpl(this, listener, stageTransitionHandler);
/**
* Set if an exception was thrown during the execution of the scenario and
* suppressStepExceptions is true.
*/
private Throwable failedException;
private boolean failIfPass;
/**
* Whether exceptions caught while executing steps should be thrown at the end
* of the scenario. Only relevant if suppressStepExceptions is true, because otherwise
* the exceptions are not caught at all.
*/
private boolean suppressExceptions;
/**
* Whether exceptions thrown while executing steps should be suppressed or not.
* Only relevant for normal executions of scenarios.
*/
private boolean suppressStepExceptions = true;
/**
* Create a new ScenarioExecutor instance.
*/
public ScenarioExecutor() {
injector.injectValueByType(ScenarioExecutor.class, this);
injector.injectValueByType(CurrentStep.class, new StepAccessImpl());
injector.injectValueByType(CurrentScenario.class, new ScenarioAccessImpl());
}
class StepAccessImpl implements CurrentStep {
@Override
public void addAttachment(Attachment attachment) {
listener.attachmentAdded(attachment);
}
@Override
public void setExtendedDescription(String extendedDescription) {
listener.extendedDescriptionUpdated(extendedDescription);
}
@Override
public void setName(String name) {
listener.stepNameUpdated(name);
}
@Override
public void setComment(String comment) {
listener.stepCommentUpdated(comment);
}
}
class ScenarioAccessImpl implements CurrentScenario {
@Override
public void addTag(Class<? extends Annotation> annotationClass, String... values) {
listener.tagAdded(annotationClass, values);
}
}
class StageTransitionHandlerImpl implements StageTransitionHandler {
@Override
public void enterStage(Object parentStage, Object childStage) throws Throwable {
if (parentStage == childStage || currentTopLevelStage == childStage) { // NOSONAR: reference comparison OK
return;
}
// if currentStage == null, this means that no stage at
// all has been executed, thus we call all beforeScenarioMethods
if (currentTopLevelStage == null) {
ensureBeforeScenarioMethodsAreExecuted();
} else {
// in case parentStage == null, this is the first top-level
// call on this stage, thus we have to call the afterStage methods
// from the current top level stage
if (parentStage == null) {
executeAfterStageMethods(currentTopLevelStage);
readScenarioState(currentTopLevelStage);
} else {
// as the parent stage is not null, we have a true child call
// thus we have to read the state from the parent stage
readScenarioState(parentStage);
// if there has been a child stage that was executed before
// and the new child stage is different, we have to execute
// the after stage methods of the previous child stage
StageState stageState = getStageState(parentStage);
if (stageState.currentChildStage != null && stageState.currentChildStage != childStage
&& !afterStageMethodsCalled(stageState.currentChildStage)) {
updateScenarioState(stageState.currentChildStage);
executeAfterStageMethods(stageState.currentChildStage);
readScenarioState(stageState.currentChildStage);
}
stageState.currentChildStage = childStage;
}
}
updateScenarioState(childStage);
executeBeforeStageMethods(childStage);
if (parentStage == null) {
currentTopLevelStage = childStage;
}
}
@Override
public void leaveStage(Object parentStage, Object childStage) throws Throwable {
if (parentStage == childStage || parentStage == null) {
return;
}
readScenarioState(childStage);
// in case we leave a child stage that itself had a child stage
// we have to execute the after stage method of that transitive child
StageState childState = getStageState(childStage);
if (childState.currentChildStage != null) {
updateScenarioState(childState.currentChildStage);
if (!getStageState(childState.currentChildStage).allAfterStageMethodsHaveBeenExecuted()) {
executeAfterStageMethods(childState.currentChildStage);
readScenarioState(childState.currentChildStage);
updateScenarioState(childStage);
}
childState.currentChildStage = null;
}
updateScenarioState(parentStage);
}
}
@SuppressWarnings("unchecked")
<T> T addStage(Class<T> stageClass) {
if (stages.containsKey(stageClass)) {
return (T) stages.get(stageClass).instance;
}
T result = stageCreator.createStage(stageClass, methodInterceptor);
methodInterceptor.enableMethodInterception(true);
stages.put(stageClass, new StageState(result, methodInterceptor));
gatherRules(result);
injectStages(result);
return result;
}
public void addIntroWord(String word) {
listener.introWordAdded(word);
}
@SuppressWarnings("unchecked")
private void gatherRules(Object stage) {
for (Field field : FieldCache.get(stage.getClass()).getFieldsWithAnnotation(ScenarioRule.class)) {
log.debug("Found rule in field {} ", field);
try {
scenarioRules.add(field.get(stage));
} catch (IllegalAccessException e) {
throw new RuntimeException("Error while reading field " + field, e);
}
}
}
private <T> void updateScenarioState(T t) {
try {
injector.updateValues(t);
} catch (JGivenMissingRequiredScenarioStateException e) {
if (!suppressExceptions) {
throw e;
}
}
}
private boolean afterStageMethodsCalled(Object stage) {
return getStageState(stage).allAfterStageMethodsHaveBeenExecuted();
}
//TODO: nicer stage search?
// What may happen if there is a common superclass to two distinct implementations? Is that even possible?
StageState getStageState(Object stage) {
Class<?> stageClass = stage.getClass();
StageState stageState = stages.get(stageClass);
while (stageState == null && stageClass != stageClass.getSuperclass()) {
stageState = stages.get(stageClass);
stageClass = stageClass.getSuperclass();
}
return stageState;
}
private void ensureBeforeScenarioMethodsAreExecuted() throws Throwable {
if (state != State.INIT) {
return;
}
state = STARTED;
methodInterceptor.enableMethodInterception(false);
try {
for (Object rule : scenarioRules) {
invokeRuleMethod(rule, "before");
}
beforeScenarioMethodsExecuted = true;
for (StageState stage : stages.values()) {
executeBeforeScenarioMethods(stage.instance);
}
} catch (Throwable e) {
failed(e);
finished();
throw e;
}
methodInterceptor.enableMethodInterception(true);
}
private void invokeRuleMethod(Object rule, String methodName) throws Throwable {
if (!executeLifeCycleMethods) {
return;
}
Optional<Method> optionalMethod = ReflectionUtil.findMethodTransitively(rule.getClass(), methodName);
if (!optionalMethod.isPresent()) {
log.debug("Class {} has no {} method, but was used as ScenarioRule!", rule.getClass(), methodName);
return;
}
try {
ReflectionUtil.invokeMethod(rule, optionalMethod.get(), " of rule class " + rule.getClass().getName());
} catch (JGivenUserException e) {
throw e.getCause();
}
}
private void executeBeforeScenarioMethods(Object stage) throws Throwable {
getStageState(stage).executeBeforeScenarioMethods(!executeLifeCycleMethods);
}
private void executeBeforeStageMethods(Object stage) throws Throwable {
getStageState(stage).executeBeforeStageMethods(!executeLifeCycleMethods);
}
private void executeAfterStageMethods(Object stage) throws Throwable {
getStageState(stage).executeAfterStageMethods(!executeLifeCycleMethods);
}
private void executeAfterScenarioMethods(Object stage) throws Throwable {
getStageState(stage).executeAfterScenarioMethods(!executeLifeCycleMethods);
}
public void readScenarioState(Object object) {
injector.readValues(object);
}
/**
* Used for DI frameworks to inject values into stages.
*/
public void wireSteps(CanWire canWire) {
for (StageState steps : stages.values()) {
canWire.wire(steps.instance);
}
}
/**
* Has to be called when the scenario is finished in order to execute after methods.
*/
public void finished() throws Throwable {
if (state == FINISHED) {
return;
}
State previousState = state;
state = FINISHED;
methodInterceptor.enableMethodInterception(false);
try {
if (previousState == STARTED) {
callFinishLifeCycleMethods();
}
} finally {
listener.scenarioFinished();
}
}
private void callFinishLifeCycleMethods() throws Throwable {
Throwable firstThrownException = failedException;
if (beforeScenarioMethodsExecuted) {
try {
if (currentTopLevelStage != null) {
executeAfterStageMethods(currentTopLevelStage);
}
} catch (Exception e) {
firstThrownException = logAndGetFirstException(firstThrownException, e);
}
for (StageState stage : reverse(newArrayList(stages.values()))) {
try {
executeAfterScenarioMethods(stage.instance);
} catch (Exception e) {
firstThrownException = logAndGetFirstException(firstThrownException, e);
}
}
}
for (Object rule : reverse(scenarioRules)) {
try {
invokeRuleMethod(rule, "after");
} catch (Exception e) {
firstThrownException = logAndGetFirstException(firstThrownException, e);
}
}
failedException = firstThrownException;
if (!suppressExceptions && failedException != null) {
throw failedException;
}
if (failIfPass && failedException == null) {
throw new FailIfPassedException();
}
}
private Throwable logAndGetFirstException(Throwable firstThrownException, Throwable newException) {
log.error(newException.getMessage(), newException);
return firstThrownException == null ? newException : firstThrownException;
}
/**
* Initialize the fields annotated with {@link ScenarioStage} in the test class.
*/
@SuppressWarnings("unchecked")
public void injectStages(Object stage) {
for (Field field : FieldCache.get(stage.getClass()).getFieldsWithAnnotation(ScenarioStage.class)) {
Object steps = addStage(field.getType());
ReflectionUtil.setField(field, stage, steps, ", annotated with @ScenarioStage");
}
}
public boolean hasFailed() {
return failedException != null;
}
public Throwable getFailedException() {
return failedException;
}
public void setFailedException(Exception e) {
failedException = e;
}
/**
* Handle ocurred exception and continue.
*/
public void failed(Throwable e) {
if (hasFailed()) {
log.error(e.getMessage(), e);
} else {
if (!failIfPass) {
listener.scenarioFailed(e);
}
methodInterceptor.disableMethodExecution();
failedException = e;
}
}
/**
* Starts a scenario with the given description.
*
* @param description the description of the scenario
*/
public void startScenario(String description) {
listener.scenarioStarted(description);
}
/**
* Starts the scenario with the given method and arguments.
* Derives the description from the method name.
*
* @param method the method that started the scenario
* @param arguments the test arguments with their parameter names
*/
public void startScenario(Class<?> testClass, Method method, List<NamedArgument> arguments) {
listener.scenarioStarted(testClass, method, arguments);
if (Config.config().dryRun()) {
methodInterceptor.setDefaultInvocationMode(InvocationMode.PENDING);
methodInterceptor.disableMethodExecution();
executeLifeCycleMethods = false;
suppressExceptions = true;
} else {
Pending annotation = extractPendingAnnotation(method);
if (annotation == null) {
methodInterceptor.setSuppressExceptions(suppressStepExceptions);
} else {
if (annotation.failIfPass()) {
failIfPass();
} else {
methodInterceptor.setDefaultInvocationMode(InvocationMode.PENDING);
if (!annotation.executeSteps()) {
methodInterceptor.disableMethodExecution();
executeLifeCycleMethods = false;
}
}
suppressExceptions = true;
}
}
}
private Pending extractPendingAnnotation(Method method) {
if (method.isAnnotationPresent(Pending.class)) {
return method.getAnnotation(Pending.class);
}
if (method.getDeclaringClass().isAnnotationPresent(Pending.class)) {
return method.getDeclaringClass().getAnnotation(Pending.class);
}
return null;
}
public void setListener(ScenarioListener listener) {
this.listener = listener;
methodInterceptor.setScenarioListener(listener);
}
public void failIfPass() {
failIfPass = true;
}
public void setSuppressStepExceptions(boolean suppressStepExceptions) {
this.suppressStepExceptions = suppressStepExceptions;
}
public void setSuppressExceptions(boolean suppressExceptions) {
this.suppressExceptions = suppressExceptions;
}
public void addSection(String sectionTitle) {
listener.sectionAdded(sectionTitle);
}
public void setStageCreator(StageCreator stageCreator) {
this.stageCreator = stageCreator;
}
public void setStageClassCreator(StageClassCreator stageClassCreator) {
this.stageCreator = createStageCreator(stageClassCreator);
}
private StageCreator createStageCreator(StageClassCreator stageClassCreator) {
return new DefaultStageCreator(new CachingStageClassCreator(stageClassCreator));
}
private static class StageState extends StageLifecycleManager {
final Object instance;
Object currentChildStage;
private StageState(Object instance, StepInterceptorImpl methodInterceptor) {
super(instance, methodInterceptor);
this.instance = instance;
}
}
}
| 35.250464 | 118 | 0.644053 |
3c256ec7d8bd7de87cab009e49921c338105b05a | 196 | package test;
import java.util.*;
public class MethodWithMappedClasses {
public <T> void copy(List<? super T> dest, List<T> src) {
throw new UnsupportedOperationException();
}
}
| 19.6 | 61 | 0.678571 |
e79f374df47f2b358cf90896b476d8de962124ae | 4,646 | /*
* Copyright 2021 The University of Manchester
*
* 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.acuity.visualisations.rawdatamodel.service.plots;
import com.acuity.visualisations.rawdatamodel.axes.AxisOptions;
import com.acuity.visualisations.rawdatamodel.filters.Filters;
import com.acuity.visualisations.rawdatamodel.filters.PopulationFilters;
import com.acuity.visualisations.rawdatamodel.trellis.grouping.ChartGroupByOptions;
import com.acuity.visualisations.rawdatamodel.trellis.grouping.ChartGroupByOptionsFiltered;
import com.acuity.visualisations.rawdatamodel.trellis.grouping.PopulationGroupByOptions;
import com.acuity.visualisations.rawdatamodel.util.Attributes;
import com.acuity.visualisations.rawdatamodel.vo.GroupByOption;
import com.acuity.visualisations.rawdatamodel.vo.Subject;
import com.acuity.visualisations.rawdatamodel.vo.compatibility.TrellisedOvertime;
import com.acuity.va.security.acl.domain.Datasets;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
/**
* Created by knml167 on 6/16/2017.
*/
public interface OverTimeChartSupportService<T, G extends Enum<G> & GroupByOption<T>> {
List<TrellisedOvertime<T, G>> getLineBarChart(Datasets datasets,
ChartGroupByOptionsFiltered<T, G> eventSettings,
Filters<T> filters, PopulationFilters populationFilters);
AxisOptions<G> getAvailableOverTimeChartXAxis(Datasets datasets, Filters<T> filters,
PopulationFilters populationFilters);
/**
* This method returns chart settings for population line on overtime charts
* */
default ChartGroupByOptions<Subject, PopulationGroupByOptions> getPopulationLineSettings(
ChartGroupByOptionsFiltered<T, G> eventSettings, Collection<T> filteredResult) {
final ChartGroupByOptions.GroupByOptionAndParams<T, G> xAxisOption = eventSettings.getSettings()
.getOptions().get(ChartGroupByOptions.ChartGroupBySetting.X_AXIS);
final GroupByOption.Params xAxisParams = xAxisOption == null ? null : xAxisOption.getParams();
final ChartGroupByOptions.ChartGroupBySettingsBuilder<Subject, PopulationGroupByOptions> populationOptions
= eventSettings.getSettings().limitedByPopulationTrellisOptions().toBuilder();
return xAxisOption == null ? populationOptions.build() : populationOptions
.withOption(ChartGroupByOptions.ChartGroupBySetting.X_AXIS,
PopulationGroupByOptions.ON_STUDY.getGroupByOptionAndParams(
(xAxisParams == null ? GroupByOption.Params.builder() : xAxisParams.toBuilder())
.with(GroupByOption.Param.BIN_INCL_DURATION, true)
.with(GroupByOption.Param.AXIS_START,
filteredResult.stream()
.map(e -> Attributes.get(xAxisOption, e))
.flatMap(e -> e instanceof Collection ? ((Collection) e).stream()
.map(t -> t) : Collections.singleton((Comparable) e).stream())
.min(Comparator.naturalOrder()).orElse(null))
.with(GroupByOption.Param.AXIS_END,
filteredResult.stream().map(e -> Attributes.get(xAxisOption, e))
.flatMap(e -> e instanceof Collection ? ((Collection) e).stream()
.map(t -> t) : Collections.singleton((Comparable) e).stream())
.max(Comparator.naturalOrder()).orElse(null))
.build()
))
.build();
}
}
| 57.358025 | 126 | 0.628067 |
074de8bd701181eb736a447d505949d34671d0fd | 315 | package edu.neu.cs5520.chatime.domain.interactors;
import edu.neu.cs5520.chatime.domain.interactors.base.Interactor;
public interface DailyCheckInInteractor extends Interactor {
interface Callback {
void onDailyCheckInSucceed(String message);
void onDailyCheckInFailed(String error);
}
}
| 26.25 | 65 | 0.771429 |
81c0252c1fd684574bb339b35a3c82eca3d5fa32 | 7,151 | package org.solovyev.android.tasks;
import android.app.Activity;
import android.content.Context;
import com.google.common.util.concurrent.FutureCallback;
import org.solovyev.android.Threads;
import org.solovyev.tasks.NamedTask;
import org.solovyev.tasks.Task;
import javax.annotation.Nonnull;
/**
* User: serso
* Date: 4/8/13
* Time: 9:50 PM
*/
/**
* Android tasks
*/
public final class Tasks extends org.solovyev.tasks.Tasks {
private Tasks() {
super();
}
/**
* The only difference from {@link Tasks#toFutureCallback(A, ContextCallback <A,V>)} is that all {@link ContextCallback}
* method calls will be done on UI thread (main application thread)
*
* @see Tasks#toFutureCallback(A, ContextCallback <A,V>)
*/
@Nonnull
public static <A extends Activity, V> FutureCallback<V> toUiThreadFutureCallback(@Nonnull A activity, @Nonnull ContextCallback<A, V> callback) {
return FutureCallbackAdapter.newUiThreadAdapter(activity, callback);
}
/**
* Method convert specified context <var>callback</var> to {@link com.google.common.util.concurrent.FutureCallback}.
*
* @param context context to be used in {@link ContextCallback} methods
* @param callback context callback
* @param <C> type of context
* @param <V> type of result
* @return {@link com.google.common.util.concurrent.FutureCallback} wrapper for specified <var>callback</var>
*/
@Nonnull
public static <C extends Context, V> FutureCallback<V> toFutureCallback(@Nonnull C context, @Nonnull ContextCallback<C, V> callback) {
return FutureCallbackAdapter.newAdapter(context, callback);
}
/**
* Method converts specified context <var>task</var> to {@link Task}
*
* @param context context to be used in {@link ContextCallback} methods
* @param task context task
* @param <C> type of context
* @param <V> type of result
* @return {@link Task} wrapper for specified <var>task</var>
*/
@Nonnull
public static <C extends Context, V> Task<V> toTask(@Nonnull C context, @Nonnull ContextTask<C, V> task) {
return TaskAdapter.newAdapter(context, task);
}
@Nonnull
public static <C extends Context, V> NamedTask<V> toTask(@Nonnull C context, @Nonnull NamedContextTask<C, V> task) {
return NamedTaskAdapter.newAdapter(context, task);
}
/**
* The only difference from {@link Tasks#toTask(C, ContextTask<C,V>)} is that all {@link ContextCallback}
* method calls will be done on UI thread (main application thread)
*
* @see Tasks#toTask(C, ContextTask<C,V>)
*/
@Nonnull
public static <A extends Activity, V> Task<V> toUiThreadTask(@Nonnull A activity, @Nonnull ContextTask<A, V> task) {
return TaskAdapter.newUiThreadTaskAdapter(activity, task);
}
@Nonnull
public static <A extends Activity, V> NamedTask<V> toUiThreadTask(@Nonnull A activity, @Nonnull NamedContextTask<A, V> task) {
return NamedTaskAdapter.newUiThreadAdapter(activity, task);
}
/*
**********************************************************************
*
* STATIC
*
**********************************************************************
*/
/**
* {@link ContextCallback} to {@link com.google.common.util.concurrent.FutureCallback} adapter
*/
private static final class FutureCallbackAdapter<C extends Context, V> extends ContextAwareFutureCallback<V, C> {
@Nonnull
private final ContextCallback<C, V> callback;
private final boolean onUiThread;
private FutureCallbackAdapter(@Nonnull C context, @Nonnull ContextCallback<C, V> callback, boolean onUiThread) {
super(context);
this.callback = callback;
this.onUiThread = onUiThread;
}
private static <A extends Activity, V> FutureCallbackAdapter<A, V> newUiThreadAdapter(@Nonnull A activity, @Nonnull ContextCallback<A, V> callback) {
return new FutureCallbackAdapter<A, V>(activity, callback, true);
}
private static <C extends Context, V> FutureCallbackAdapter<C, V> newAdapter(@Nonnull C context, @Nonnull ContextCallback<C, V> callback) {
return new FutureCallbackAdapter<C, V>(context, callback, false);
}
@Override
public void onSuccess(final V result) {
final C context = getContext();
if (context != null) {
if (onUiThread) {
final Activity activity = (Activity) context;
Threads.tryRunOnUiThread(activity, new Runnable() {
@Override
public void run() {
callback.onSuccess(context, result);
}
});
} else {
callback.onSuccess(context, result);
}
}
}
@Override
public void onFailure(final Throwable e) {
final C context = getContext();
if (context != null) {
if (onUiThread) {
Threads.tryRunOnUiThread((Activity) context, new Runnable() {
@Override
public void run() {
callback.onFailure(context, e);
}
});
} else {
callback.onFailure(context, e);
}
}
}
}
/**
* {@link ContextTask} to {@link Task} adapter
*/
private static final class TaskAdapter<C extends Context, V> implements Task<V> {
@Nonnull
private final ContextTask<C, V> task;
@Nonnull
private final FutureCallback<V> callback;
private TaskAdapter(@Nonnull ContextTask<C, V> task, @Nonnull FutureCallback<V> callback) {
this.task = task;
this.callback = callback;
}
@Nonnull
private static <A extends Activity, V> Task<V> newUiThreadTaskAdapter(@Nonnull A activity, @Nonnull ContextTask<A, V> task) {
return new TaskAdapter<A, V>(task, toUiThreadFutureCallback(activity, task));
}
@Nonnull
private static <C extends Context, V> Task<V> newAdapter(@Nonnull C context, @Nonnull ContextTask<C, V> task) {
return new TaskAdapter<C, V>(task, toFutureCallback(context, task));
}
@Override
public V call() throws Exception {
return task.call();
}
@Override
public void onSuccess(V result) {
callback.onSuccess(result);
}
@Override
public void onFailure(Throwable t) {
callback.onFailure(t);
}
}
private static final class NamedTaskAdapter<C extends Context, V> implements NamedTask<V> {
@Nonnull
private final NamedContextTask<C, V> namedTask;
@Nonnull
private final Task<V> task;
private NamedTaskAdapter(@Nonnull NamedContextTask<C, V> namedTask, @Nonnull Task<V> task) {
this.task = task;
this.namedTask = namedTask;
}
@Nonnull
private static <C extends Context, V> NamedTaskAdapter<C, V> newAdapter(@Nonnull C context, @Nonnull NamedContextTask<C, V> namedTask) {
return new NamedTaskAdapter<C, V>(namedTask, TaskAdapter.newAdapter(context, namedTask));
}
@Nonnull
private static <A extends Activity, V> NamedTaskAdapter<A, V> newUiThreadAdapter(@Nonnull A activity, @Nonnull NamedContextTask<A, V> namedTask) {
return new NamedTaskAdapter<A, V>(namedTask, TaskAdapter.newUiThreadTaskAdapter(activity, namedTask));
}
@Nonnull
@Override
public String getName() {
return namedTask.getName();
}
@Override
public V call() throws Exception {
return namedTask.call();
}
@Override
public void onSuccess(V result) {
task.onSuccess(result);
}
@Override
public void onFailure(Throwable t) {
task.onFailure(t);
}
}
}
| 29.427984 | 151 | 0.687316 |
6b9b84ae55d124bc94097d40413ff070da1a484f | 106 | package org.snomed.heathanalytics.ingestion;
public interface HealthDataIngestionSourceConfiguration {
}
| 21.2 | 57 | 0.867925 |
867d78769ab4d18758ba667200206fea9a400273 | 8,130 | /*
* Copyright (c) 2020 Squaredesk GmbH and Oliver Dotzauer.
*
* This program is distributed under the squaredesk open source license. See the LICENSE file
* distributed with this work for additional information regarding copyright ownership. You may also
* obtain a copy of the license at
*
* https://squaredesk.ch/license/oss/LICENSE
*
*/
package ch.squaredesk.nova.comm.http;
import ch.squaredesk.nova.metrics.Metrics;
import com.ning.http.client.AsyncHttpClient;
import com.ning.http.client.FluentCaseInsensitiveStringsMap;
import com.ning.http.client.Response;
import io.reactivex.Single;
import io.reactivex.functions.Function;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.InputStream;
import java.time.Duration;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import static java.util.Objects.requireNonNull;
public class RpcClient extends ch.squaredesk.nova.comm.rpc.RpcClient<String, RequestMessageMetaData, ReplyMessageMetaData>
implements HttpClientInstanceListener {
private static final Logger logger = LoggerFactory.getLogger(RpcClient.class);
private AsyncHttpClient client;
private Map<String, String> standardHeadersForAllRequests;
private boolean contentTypeInStandardHeaders;
protected RpcClient(String identifier,
AsyncHttpClient client,
Metrics metrics) {
super(Metrics.name("http", identifier), metrics);
this.client = client;
}
@Override
public <T, U> Single<RpcReply<U>> sendRequest(
T request,
RequestMessageMetaData requestMessageMetaData,
Function<T, String> requestTranscriber,
Function<String, U> replyTranscriber,
Duration timeout) {
return doRequest(
request, requestMessageMetaData, requestTranscriber,
response -> {
String responseBody = response.getResponseBody();
return responseBody == null || responseBody.trim().isEmpty() ? null : replyTranscriber.apply(responseBody);
},
timeout
);
}
public <T> Single<RpcReply<InputStream>> sendRequestAndRetrieveResponseAsStream(
T request,
RequestMessageMetaData requestMessageMetaData,
Function<T, String> requestTranscriber,
Duration timeout) {
return doRequest(
request, requestMessageMetaData, requestTranscriber,
Response::getResponseBodyAsStream,
timeout
);
}
private <T, U> Single<RpcReply<U>> doRequest(T request,
RequestMessageMetaData requestMessageMetaData,
Function<T, String> requestTranscriber,
Function<Response, U> responseMapper,
Duration timeout) {
String requestAsString;
try {
requestAsString = request != null ? requestTranscriber.apply(request) : null;
} catch (Exception e) {
return Single.error(e);
}
AsyncHttpClient.BoundRequestBuilder requestBuilder = createRequestBuilder(requestAsString, requestMessageMetaData, timeout);
return Single.<Response>create(
s -> {
try {
Response r = requestBuilder.execute().get(timeout.toMillis(), TimeUnit.MILLISECONDS);
s.onSuccess(r);
} catch (Exception e) {
s.onError(e);
}
})
.map(response -> {
ReplyMessageMetaData metaData = createMetaDataFromReply(requestMessageMetaData, response);
U result = responseMapper.apply(response);
metricsCollector.rpcCompleted(MetricsCollectorInfoCreator.createInfoFor(requestMessageMetaData.destination), result);
return new RpcReply<>(result, metaData);
})
;
}
private AsyncHttpClient.BoundRequestBuilder createRequestBuilder(String requestAsString, RequestMessageMetaData requestMessageMetaData, Duration timeout) {
requireNonNull(timeout, "timeout must not be null");
AsyncHttpClient.BoundRequestBuilder requestBuilder;
if (requestMessageMetaData.details.requestMethod == HttpRequestMethod.POST) {
requestBuilder = client.preparePost(requestMessageMetaData.destination.toString()).setBody(requestAsString);
} else if (requestMessageMetaData.details.requestMethod == HttpRequestMethod.PUT) {
requestBuilder = client.preparePut(requestMessageMetaData.destination.toString()).setBody(requestAsString);
} else if (requestMessageMetaData.details.requestMethod == HttpRequestMethod.PATCH) {
requestBuilder = client.preparePatch(requestMessageMetaData.destination.toString()).setBody(requestAsString);
} else if (requestMessageMetaData.details.requestMethod == HttpRequestMethod.OPTIONS) {
requestBuilder = client.prepareOptions(requestMessageMetaData.destination.toString()).setBody(requestAsString);
} else if (requestMessageMetaData.details.requestMethod == HttpRequestMethod.DELETE) {
requestBuilder = client.prepareDelete(requestMessageMetaData.destination.toString()).setBody(requestAsString);
} else {
requestBuilder = client.prepareGet(requestMessageMetaData.destination.toString());
}
addHeadersToRequest(standardHeadersForAllRequests, requestBuilder);
addHeadersToRequest(requestMessageMetaData.details.headers, requestBuilder);
if (!contentTypeInStandardHeaders && !headersContainContentType(requestMessageMetaData.details.headers)) {
requestBuilder.addHeader("Content-Type", "application/json; charset=utf-8");
}
return requestBuilder.setRequestTimeout((int)timeout.toMillis());
}
private static ReplyMessageMetaData createMetaDataFromReply(RequestMessageMetaData requestMessageMetaData, Response response) {
Map<String, String> headersToReturn;
FluentCaseInsensitiveStringsMap responseHeaders = response.getHeaders();
if (responseHeaders.isEmpty()) {
headersToReturn = Collections.emptyMap();
} else {
Map<String, String> headerMap = new HashMap<>(responseHeaders.size() + 1, 1.0f);
responseHeaders.forEach((key, valueList) -> headerMap.put(key, String.join(",", valueList)));
headersToReturn = headerMap;
}
return new ReplyMessageMetaData(
requestMessageMetaData.destination,
new ReplyInfo(response.getStatusCode(), headersToReturn));
}
void shutdown() {
if (this.client!=null) {
client.close();
}
}
public Map<String, String> getStandardHeadersForAllRequests() {
return standardHeadersForAllRequests;
}
public void setStandardHeadersForAllRequests(Map<String, String> standardHeadersForAllRequests) {
this.standardHeadersForAllRequests = new HashMap<>(standardHeadersForAllRequests);
this.contentTypeInStandardHeaders = headersContainContentType(this.standardHeadersForAllRequests);
}
private static boolean headersContainContentType (Map<String, String> headersToCheck) {
return headersToCheck!= null && headersToCheck.containsKey("Content-Type");
}
private static void addHeadersToRequest (Map<String, String> headersToAdd, AsyncHttpClient.BoundRequestBuilder requestBuilder) {
if (headersToAdd != null) {
headersToAdd.forEach(requestBuilder::setHeader);
}
}
@Override
public void httpClientInstanceCreated(AsyncHttpClient httpClient) {
if (this.client == null) {
logger.info("httpClient available, RpcClient functional");
}
this.client = httpClient;
}
}
| 43.945946 | 159 | 0.670357 |
2d6ef84e9f5be0ef2c5bd22b4009229c5c680bb9 | 6,512 | package mx.nic.rdap.store.model;
import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import mx.nic.rdap.core.db.Domain;
import mx.nic.rdap.core.db.DomainLabel;
import mx.nic.rdap.core.db.Entity;
import mx.nic.rdap.core.db.IpNetwork;
import mx.nic.rdap.core.db.Nameserver;
import mx.nic.rdap.sql.QueryGroup;
import mx.nic.rdap.sql.exception.IncompleteObjectException;
import mx.nic.rdap.sql.model.ZoneModel;
import mx.nic.rdap.sql.objects.DomainDbObj;
import mx.nic.rdap.sql.objects.IpNetworkDbObj;
/**
* Model for the {@link Domain} Object
*
*/
public class DomainStoreModel {
private final static Logger logger = Logger.getLogger(DomainStoreModel.class.getName());
private final static String QUERY_GROUP = "DomainStore";
private static QueryGroup queryGroup = null;
private static final String STORE_QUERY = "storeToDatabase";
private static final String STORE_IP_NETWORK_RELATION_QUERY = "storeDomainIpNetworkRelation";
public static void loadQueryGroup(String schema) {
try {
QueryGroup qG = new QueryGroup(QUERY_GROUP, schema);
setQueryGroup(qG);
} catch (IOException e) {
throw new RuntimeException("Error loading query group");
}
}
private static void setQueryGroup(QueryGroup qG) {
queryGroup = qG;
}
private static QueryGroup getQueryGroup() {
return queryGroup;
}
public static Long storeToDatabase(Domain domain, boolean useNameserverAsAttribute, Connection connection)
throws SQLException {
String query = getQueryGroup().getQuery(STORE_QUERY);
Long domainId;
isValidForStore((DomainDbObj) domain);
try (PreparedStatement statement = connection.prepareStatement(query, Statement.RETURN_GENERATED_KEYS)) {
fillPreparedStatement(statement, domain);
logger.log(Level.INFO, "Executing QUERY: " + statement.toString());
statement.executeUpdate();
ResultSet resultSet = statement.getGeneratedKeys();
resultSet.next();
domainId = resultSet.getLong(1);
domain.setId(domainId);
}
storeNestedObjects(domain, useNameserverAsAttribute, connection);
return domainId;
}
private static void storeNestedObjects(Domain domain, boolean useNameserverAsAttribute, Connection connection)
throws SQLException {
Long domainId = domain.getId();
RemarkStoreModel.storeDomainRemarksToDatabase(domain.getRemarks(), domainId, connection);
EventStoreModel.storeDomainEventsToDatabase(domain.getEvents(), domainId, connection);
StatusStoreModel.storeDomainStatusToDatabase(domain.getStatus(), domainId, connection);
LinkStoreModel.storeDomainLinksToDatabase(domain.getLinks(), domainId, connection);
if (domain.getSecureDNS() != null) {
domain.getSecureDNS().setDomainId(domainId);
SecureDNSStoreModel.storeToDatabase(domain.getSecureDNS(), connection);
}
PublicIdStoreModel.storePublicIdByDomain(domain.getPublicIds(), domain.getId(), connection);
VariantStoreModel.storeAllToDatabase(domain.getVariants(), domain.getId(), connection);
if (domain.getNameServers().size() > 0) {
if (useNameserverAsAttribute) {
NameserverStoreModel.storeDomainNameserversAsAttributesToDatabase(domain.getNameServers(), domainId,
connection);
} else {
storeDomainNameserversAsObjects(domain.getNameServers(), domainId, connection);
}
}
storeDomainEntities(domain.getEntities(), domainId, connection);
IpNetwork ipNetwork = domain.getIpNetwork();
if (ipNetwork != null) {
IpNetworkDbObj ipNetResult = IpNetworkStoreModel.getByHandle(ipNetwork.getHandle(), connection);
if (ipNetResult == null) {
throw new NullPointerException(
"IpNetwork: " + ipNetwork.getHandle() + "was not inserted previously to the database");
}
ipNetwork.setId(ipNetResult.getId());
storeDomainIpNetworkRelationToDatabase(domainId, ipNetwork.getId(), connection);
}
}
private static void storeDomainNameserversAsObjects(List<Nameserver> nameservers, Long domainId,
Connection connection) throws SQLException {
if (nameservers.size() > 0) {
validateDomainNameservers(nameservers, connection);
NameserverStoreModel.storeDomainNameserversToDatabase(nameservers, domainId, connection);
}
}
private static void validateDomainNameservers(List<Nameserver> nameservers, Connection connection)
throws SQLException {
for (Nameserver ns : nameservers) {
Long nsId = NameserverStoreModel.getByHandle(ns.getHandle(), connection).getId();
if (nsId == null) {
throw new NullPointerException(
"Nameserver: " + ns.getHandle() + "was not inserted previously to the database.");
}
ns.setId(nsId);
}
}
private static void storeDomainEntities(List<Entity> entities, Long domainId, Connection connection)
throws SQLException {
if (entities.size() > 0) {
EntityStoreModel.validateParentEntities(entities, connection);
RoleStoreModel.storeDomainEntityRoles(entities, domainId, connection);
}
}
private static void isValidForStore(DomainDbObj domain) throws IncompleteObjectException {
if (domain.getHandle() == null || domain.getHandle().isEmpty())
throw new IncompleteObjectException("handle", "Domain");
if (domain.getLdhName() == null || domain.getLdhName().isEmpty())
throw new IncompleteObjectException("ldhName", "Domain");
}
private static void storeDomainIpNetworkRelationToDatabase(Long domainId, Long ipNetworkId, Connection connection)
throws SQLException {
String query = getQueryGroup().getQuery(STORE_IP_NETWORK_RELATION_QUERY);
try (PreparedStatement statement = connection.prepareStatement(query)) {
statement.setLong(1, domainId);
statement.setLong(2, ipNetworkId);
logger.log(Level.INFO, "Excuting QUERY:" + statement.toString());
statement.executeUpdate();
}
}
private static void fillPreparedStatement(PreparedStatement preparedStatement, Domain domain) throws SQLException {
preparedStatement.setString(1, domain.getHandle());
String domName = domain.getLdhName();
String unicodeName = DomainLabel.nameToUnicode(domName);
preparedStatement.setString(2, unicodeName);
preparedStatement.setString(3, domain.getPort43());
preparedStatement.setInt(4, ZoneModel.getIdByZoneName(domain.getZone()));
}
}
| 37.860465 | 117 | 0.751229 |
2f0a1bd72f2969a2b258dbacf8101b73d16e49a2 | 1,690 | package net.tokensmith.otter.gateway.servlet.merger;
import helper.FixtureFactory;
import helper.fake.FakePresenter;
import net.tokensmith.otter.router.entity.io.Answer;
import org.junit.Before;
import org.junit.Test;
import javax.servlet.http.HttpServletRequest;
import java.util.Optional;
import static org.mockito.Mockito.any;
import static org.mockito.Mockito.eq;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.verify;
public class HttpServletRequestMergerTest {
private HttpServletRequestMerger subject;
@Before
public void setUp() {
subject = new HttpServletRequestMerger();
}
@Test
public void mergePresenterAndTemplateArePresent() throws Exception {
HttpServletRequest mockContainerRequest = mock(HttpServletRequest.class);
Answer answer = FixtureFactory.makeAnswer();
answer.setPresenter(Optional.of(new FakePresenter()));
answer.setTemplate(Optional.of("path/to/template.jsp"));
subject.merge(mockContainerRequest, answer);
verify(mockContainerRequest).setAttribute(subject.getPresenterAttr(), answer.getPresenter().get());
}
@Test
public void mergePresenterAndTemplateAreNotPresent() throws Exception {
HttpServletRequest mockContainerRequest = mock(HttpServletRequest.class);
Answer answer = FixtureFactory.makeAnswer();
answer.setPresenter(Optional.empty());
answer.setTemplate(Optional.empty());
subject.merge(mockContainerRequest, answer);
verify(mockContainerRequest, never()).setAttribute(eq(subject.getPresenterAttr()), any(String.class));
}
} | 30.727273 | 110 | 0.747337 |
9f05cf2cdd67ad7967182f8bf2814ceb5bc14b04 | 1,738 | /*
* Copyright 2021 ConsenSys AG.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
* an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
* specific language governing permissions and limitations under the License.
*/
package tech.pegasys.teku.cli;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import org.apache.commons.io.FileUtils;
public class TempDirUtils {
public static Path createTempDir() {
try {
return Files.createTempDirectory("teku_unit_test_");
} catch (IOException e) {
throw new RuntimeException(e);
}
}
public static boolean deleteDirLenient(Path dir, int maxDeleteAttempts, boolean throwIfFailed) {
IOException lastException = null;
for (int i = 0; i < maxDeleteAttempts; i++) {
try {
System.out.println("Deleting");
FileUtils.deleteDirectory(dir.toFile());
return true;
} catch (IOException e) {
lastException = e;
try {
Thread.sleep(1000);
} catch (InterruptedException interruptedException) {
throw new RuntimeException(interruptedException);
}
}
}
if (throwIfFailed) {
throw new AssertionError(
"Directory " + dir + " couldn't be deleted after " + maxDeleteAttempts + " attempts",
lastException);
} else {
return false;
}
}
}
| 31.035714 | 118 | 0.675489 |
8ff6291fbb8fe76cfec011fe789cd4a44a993ab8 | 3,034 | /*
* Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package jdk.internal.jrtfs;
import java.net.URISyntaxException;
import java.net.URL;
import java.nio.file.FileSystem;
import java.nio.file.FileSystems;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.security.AccessController;
import java.security.CodeSource;
import java.security.PrivilegedAction;
final class SystemImages {
private SystemImages() {}
static final String RUNTIME_HOME;
static final Path bootImagePath;
static final Path extImagePath;
static final Path appImagePath;
static {
PrivilegedAction<String> pa = SystemImages::findHome;
RUNTIME_HOME = AccessController.doPrivileged(pa);
FileSystem fs = FileSystems.getDefault();
bootImagePath = fs.getPath(RUNTIME_HOME, "lib", "modules", "bootmodules.jimage");
extImagePath = fs.getPath(RUNTIME_HOME, "lib", "modules", "extmodules.jimage");
appImagePath = fs.getPath(RUNTIME_HOME, "lib", "modules", "appmodules.jimage");
}
/**
* Returns the appropriate JDK home for this usage of the FileSystemProvider.
* When the CodeSource is null (null loader) then jrt:/ is the current runtime,
* otherwise the JDK home is located relative to jrt-fs.jar.
*/
private static String findHome() {
CodeSource cs = SystemImages.class.getProtectionDomain().getCodeSource();
if (cs == null)
return System.getProperty("java.home");
// assume loaded from $TARGETJDK/jrt-fs.jar
URL url = cs.getLocation();
if (!url.getProtocol().equalsIgnoreCase("file"))
throw new RuntimeException(url + " loaded in unexpected way");
try {
return Paths.get(url.toURI()).getParent().toString();
} catch (URISyntaxException e) {
throw new InternalError(e);
}
}
}
| 39.921053 | 89 | 0.708306 |
a6fa2ec070d27f47bb7448d694cdc7257d3fb584 | 6,495 | /*
* $Id: AttributeEvent.java,v 1.3 2004/07/15 02:11:01 cniles Exp $
*
* Copyright (c) 2004, Christian Niles, unit12.net
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* * Neither the name of Christian Niles, Unit12, nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
*/
package javanet.staxutils.events;
import javax.xml.namespace.QName;
import javax.xml.stream.Location;
import javax.xml.stream.events.Attribute;
/**
* {@link Attribute} event implementation.
*
* @author Christian Niles
* @version $Revision: 1.3 $
*/
public class AttributeEvent extends AbstractXMLEvent implements Attribute {
/**
* Whether the attribute was specified in the document. Defaults to
* <code>true</code>.
*/
private boolean specified = true;
/** The qualified attribute name. */
private QName name;
/** The normalized attribute value. */
private String value;
/**
* Type of attribute as specified in the DTD. Defaults to <code>CDATA</code> .
*/
private String dtdType = "CDATA";
/**
* Constructs an <code>AttributeEvent</code> with the specified name and
* value.
*
* @param name
* The qualified attribute name.
* @param value
* The attribute value.
*/
public AttributeEvent(QName name, String value) {
this.name = name;
this.value = value;
}
/**
* Constructs a new <code>AttributeEvent</code>.
*
* @param name
* The qualified attribute name.
* @param value
* The attribute value.
* @param specified
* Whether the attribute was specified in the document (
* <code>true</code), or inherited from a DTD or schema (
* <code>false</code>).
*/
public AttributeEvent(QName name, String value, boolean specified) {
this.name = name;
this.value = value;
this.specified = specified;
}
/**
* Constructs a new <code>AttributeEvent</code>.
*
* @param name
* The qualified attribute name.
* @param value
* The attribute value.
* @param location
* The {@link Location} of the attribute.
*/
public AttributeEvent(QName name, String value, Location location) {
super(location);
this.name = name;
this.value = value;
}
/**
* Constructs a new <code>AttributeEvent</code>.
*
* @param name
* The qualified attribute name.
* @param value
* The attribute value.
* @param location
* The {@link Location} of the attribute.
* @param schemaType
* The attribute type as specified in the schema.
*/
public AttributeEvent(QName name, String value, Location location, QName schemaType) {
super(location, schemaType);
this.name = name;
this.value = value;
}
/**
* Constructs a new <code>AttributeEvent</code>.
*
* @param name
* The qualified attribute name.
* @param value
* The attribute value.
* @param specified
* Whether the attribute was specified in the document (
* <code>true</code), or inherited from a DTD or schema (
* <code>false</code>).
* @param location
* The {@link Location} of the attribute.
* @param dtdType
* The attribute type as specified in the DTD.
* @param schemaType
* The attribute type as specified in the schema.
*/
public AttributeEvent(QName name, String value, boolean specified, String dtdType,
Location location, QName schemaType) {
super(location, schemaType);
this.name = name;
this.value = value;
this.specified = specified;
this.dtdType = dtdType;
}
/**
* Copy constructor that optionally allows the name and/or value to be
* changed.
*
* @param name
* The new attribute name, or <code>null</code> to use the name from
* the provided attribute.
* @param value
* The new attribute value, or <code>null</code> to use the value
* from the provided attribute.
* @param that
* The {@link Attribute} event to copy.
*/
public AttributeEvent(QName name, String value, Attribute that) {
super(that);
this.specified = that.isSpecified();
this.name = (name == null ? that.getName() : name);
this.value = (value == null ? that.getValue() : value);
this.dtdType = that.getDTDType();
}
/**
* Copy constructor.
*
* @param that
* The {@link Attribute} event to copy.
*/
public AttributeEvent(Attribute that) {
super(that);
this.specified = that.isSpecified();
this.name = that.getName();
this.value = that.getValue();
this.dtdType = that.getDTDType();
}
/** Returns {@link #ATTRIBUTE}. */
public int getEventType() {
return ATTRIBUTE;
}
public QName getName() {
return name;
}
public String getValue() {
return value;
}
public boolean isSpecified() {
return specified;
}
public String getDTDType() {
return dtdType;
}
} | 27.289916 | 88 | 0.644034 |
ea1652fb43f937cee04817a5dce754ebb63051be | 1,001 | /*
* Copyright 2006 Sun Microsystems, Inc. All rights reserved.
* SUN PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
*/
/*
* @(#)FullTimeEmployee.java 1.1 06/02/21
*/
package com.sun.ts.tests.ejb30.persistence.inheritance.mappedsc.descriptors;
import java.sql.Date;
/*
* FullTimeEmployee entity extends an MappedSuperClass while overriding
* mapping information.
*/
public class FullTimeEmployee extends Employee {
private float salary;
public FullTimeEmployee() {
}
public FullTimeEmployee(int id, String firstName, String lastName, Date hireDate,
float salary)
{
super(id, firstName, lastName, hireDate);
this.salary = salary;
}
// ===========================================================
// getters and setters for the state fields
public float getSalary() {
return salary;
}
public void setSalary(float salary) {
this.salary = salary;
}
}
| 22.244444 | 85 | 0.611389 |
09c4e6574c933db2e42d784cb35ab1d7d12d5bc6 | 4,061 | /**
* <a href="http://www.openolat.org">
* OpenOLAT - Online Learning and Training</a><br>
* <p>
* Licensed under the Apache License, Version 2.0 (the "License"); <br>
* you may not use this file except in compliance with the License.<br>
* You may obtain a copy of the License at the
* <a href="http://www.apache.org/licenses/LICENSE-2.0">Apache homepage</a>
* <p>
* Unless required by applicable law or agreed to in writing,<br>
* software distributed under the License is distributed on an "AS IS" BASIS, <br>
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. <br>
* See the License for the specific language governing permissions and <br>
* limitations under the License.
* <p>
* Initial code contributed and copyrighted by<br>
* frentix GmbH, http://www.frentix.com
* <p>
*/
package org.olat.modules.edusharing.manager;
import static org.assertj.core.api.Assertions.assertThat;
import java.util.List;
import java.util.UUID;
import org.junit.Test;
import org.olat.modules.edusharing.EdusharingHtmlElement;
/**
*
* Initial date: 10 Dec 2018<br>
* @author uhensler, [email protected], http://www.frentix.com
*
*/
public class EdusharingHtmlServiceImplTest {
EdusharingHtmlServiceImpl sut = new EdusharingHtmlServiceImpl();
@Test
public void shouldExtractEsNodes() {
String esNode1 = "<img id = '123' data-es_identifier='abc1' width='123' />";
String esNode2 = "<img id = '123' data-es_identifier='abc2' width='123'>";
String esNode3 = "<a href=\"https://frentix.com\" data-es_identifier='abc2'>";
String otherNode = "<img id = '123' data-es_id='abc' width='123'>";
String html = new StringBuilder()
.append("<div>")
.append(esNode1)
.append("some text")
.append(esNode2).append("description").append("</img>")
.append(otherNode)
.append(esNode3)
.append("</div>")
.toString();
List<String> nodes = sut.getNodes(html);
assertThat(nodes)
.containsExactlyInAnyOrder(esNode1, esNode2, esNode3)
.doesNotContain(otherNode);
}
@Test
public void shouldGetAttributeValues() {
String identifier = random();
String objectUrl = random();
String version = random();
String mimeType = random();
String mediaType = random();
String width = "100";
String hight = "200";
String node = new StringBuilder()
.append("<img id = '123' ")
.append("data-es_identifier='").append(identifier).append("' ")
.append("data-es_objecturl=\"").append(objectUrl).append("\" ")
.append("data-es_version='").append(version).append("' ")
.append("data-es_mimetype ='").append(mimeType).append("' ")
.append("data-es_mediatype='").append(mediaType).append("' ")
.append("data-es_width='").append(width).append("' ")
.append("data-es_height='").append(hight).append("' ")
.append("width='123'>")
.toString();
EdusharingHtmlElement htmlElement = sut.getHtmlElement(node);
assertThat(htmlElement.getIdentifier()).isEqualTo(identifier);
}
@Test
public void shouldDeleteEsNodes() {
String node1Identifier = "abc1" ;
String esNode1 = "<img id = '123' data-es_identifier='" + node1Identifier + "' width='123' />";
String esNode2 = "<img id = '123' data-es_identifier='abc2' width='123'>";
String esNode3 = "<a href=\"https://frentix.com\" data-es_identifier='abc2'>";
String otherNode = "<img id = '123' data-es_id='abc' width='123'>";
String html = new StringBuilder()
.append("<div>")
.append(esNode1)
.append("some text")
.append(esNode2).append("description").append("</img>")
.append(otherNode)
.append(esNode3)
.append("</div>")
.toString();
String expected = new StringBuilder()
.append("<div>")
.append("some text")
.append(esNode2).append("description").append("</img>")
.append(otherNode)
.append(esNode3)
.append("</div>")
.toString();
String cleaned = sut.deleteNode(html, esNode1);
assertThat(cleaned).isEqualTo(expected);
}
private String random() {
return UUID.randomUUID().toString();
}
}
| 32.230159 | 97 | 0.669786 |
2afc2d80061c4d74bf0bcbbaf973b98003f88668 | 1,719 | /**
* (c) Copyright 2016 Admios. The software in this package is published under the terms of the Apache License Version 2.0, a copy of which has been included with this distribution in the LICENSE.md file.
*/
package org.mule.modules.watsonalchemylanguage.automation.functional;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
import java.util.List;
import org.apache.commons.lang3.StringUtils;
import org.junit.Test;
import org.mule.modules.watsonalchemylanguage.model.TypedRelationsRequest;
import com.ibm.watson.developer_cloud.alchemy.v1.model.TypedRelation;
import com.ibm.watson.developer_cloud.alchemy.v1.model.TypedRelations;
public class TypedRelationsTestCases extends AbstractTestCases {
@Test
public void testWithURLCustomModel() {
TypedRelations typedRelations = getConnector().typedRelations(buildBasicRequest());
assertNotNull(typedRelations);
assertEquals(TestDataBuilder.TEST_URL_BLOG, typedRelations.getUrl());
testPrecenseOf(typedRelations.getTypedRelations(), TestDataBuilder.TEST_URL_BLOG_TYPE_RELATION);
}
private void testPrecenseOf(List<TypedRelation> relations, String... expectedRelations) {
String flatRelations = StringUtils.join(expectedRelations, ",");
int cont = 0;
for (TypedRelation relation : relations) {
if (flatRelations.contains(relation.getType())) {
cont++;
}
}
assertTrue(String.format("The response doesn't contains all the expect entities: %s", flatRelations),
cont >= expectedRelations.length);
}
private TypedRelationsRequest buildBasicRequest() {
return new TypedRelationsRequest(TestDataBuilder.TEST_URL_BLOG, "en-news", null);
}
}
| 36.574468 | 203 | 0.794066 |
fc6b3e2115c8d671d1e12f27154516e251e333d1 | 1,330 | package org.gt.connections.jdbc;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.gt.GenevereException;
import org.gt.pipeline.BaseReaderWriter;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.Map;
public abstract class JdbcReaderWriter extends BaseReaderWriter {
private static final Logger logger = LogManager.getLogger();
protected Connection conn;
private String jdbcUrl;
public void configure(Map<String, String> props) throws GenevereException {
jdbcUrl = props.get("jdbc_url");
}
public void terminate() throws GenevereException {
try {
this.conn.close();
} catch (SQLException ex) {
logger.error(ex);
throw new GenevereException("Could not terminate connection", ex);
}
}
public void connect(String username, String password) throws GenevereException {
try {
this.conn = DriverManager.getConnection(jdbcUrl, username, password);
this.conn.setAutoCommit(false);
logger.info("Connected to " + jdbcUrl);
} catch (SQLException ex) {
logger.error(ex);
throw new GenevereException("Could not connect to: " + jdbcUrl, ex);
}
}
}
| 30.227273 | 84 | 0.672932 |
fb607ada407f7ac725d604cef200b44ca8f6977b | 597 | package org.jboss.resteasy.spi;
import javax.ws.rs.container.AsyncResponse;
import java.util.concurrent.TimeUnit;
/**
* @author <a href="mailto:[email protected]">Bill Burke</a>
* @version $Revision: 1 $
*/
public interface ResteasyAsynchronousContext
{
boolean isSuspended();
ResteasyAsynchronousResponse getAsyncResponse();
ResteasyAsynchronousResponse suspend() throws IllegalStateException;
ResteasyAsynchronousResponse suspend(long millis) throws IllegalStateException;
ResteasyAsynchronousResponse suspend(long time, TimeUnit unit) throws IllegalStateException;
}
| 28.428571 | 95 | 0.798995 |
22aa2ce920d0245b84879322e326c8dd62022e0c | 19,554 | /*
* Copyright 2001-2006 LEARNING INFORMATION SYSTEMS PTY LIMITED
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/*
* ServerActiveHtml.java
*
* Created on 11 October 2001, 16:44
*/
package org.ntropa.build.html;
import java.util.Collections;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Properties;
import java.util.SortedSet;
import java.util.TreeSet;
import org.apache.commons.lang.builder.ToStringBuilder;
import org.apache.commons.lang.builder.ToStringStyle;
import org.ntropa.build.jsp.ApplicationFinder;
import org.ntropa.build.jsp.FinderSet;
import org.ntropa.build.jsp.JspSerializable;
import org.ntropa.build.jsp.JspUtility;
import org.ntropa.utility.CollectionsUtilities;
import org.ntropa.utility.StringUtilities;
/**
* This class is represents a parsed block of Server Active HTML.
*
* @author jdb
* @version $Id: ServerActiveHtml.java,v 1.24 2002/11/30 23:03:09 jdb Exp $
*/
public class ServerActiveHtml extends GenericDeserializable
implements Deserializable, JspSerializable {
private String _name ;
private String _templateName ;
private List _elements ;
private Element _implicitElement ;
public static final String IMPLICIT_ELEMENT_NAME = "-implicit" ;
// TODO: Revert to ntropa class names.
//private static final String DEFAULT_COMPONENT_CLASS = "org.ntropa.runtime.sao.BaseServerActiveObject" ;
private static final String DEFAULT_COMPONENT_CLASS = "com.studylink.sao.BaseServerActiveObject" ;
// TODO: Revert to ntropa class names.
//private static final String DEFAULT_COMPONENT_TYPE = "org.ntropa.runtime.sao.AbstractServerActiveObject" ;
private static final String DEFAULT_COMPONENT_TYPE = "com.studylink.sao.AbstractServerActiveObject" ;
/**
* Creates new ServerActiveHtml.
*
* @param name the name of the server active HTML section
* @param templateName the name of the template to search for
*/
public ServerActiveHtml( String name, String templateName ) {
if ( name == null )
throw new IllegalArgumentException( "Attempt to construct ServerActiveHtml with a null 'name' argument" ) ;
if ( name.equals( "" ) )
throw new IllegalArgumentException( "Attempt to construct ServerActiveHtml with an empty 'name' argument" ) ;
if ( templateName == null )
throw new IllegalArgumentException( "Attempt to construct ServerActiveHtml with a null 'templateName' argument" ) ;
if ( templateName.equals( "" ) )
throw new IllegalArgumentException( "Attempt to construct ServerActiveHtml with an empty 'templateName' argument" ) ;
_name = name.toLowerCase() ;
_templateName = templateName.toLowerCase() ;
}
/**
* Creates new ServerActiveHtml.
*
* @param name the name of the server active HTML section
*/
public ServerActiveHtml( String name ) throws ServerActiveHtmlException {
if ( name == null )
throw new IllegalArgumentException( "Attempt to construct ServerActiveHtml with a null name argument" ) ;
if ( name.equals( "" ) )
throw new IllegalArgumentException( "Attempt to construct ServerActiveHtml with an empty 'name' argument" ) ;
_name = name.toLowerCase() ;
_templateName = null ;
}
/** Prevent no-arg construction */
private ServerActiveHtml() {}
/**
* Return the name of this <code>ServerActiveHtml</code>
*
* @return String the name of this <code>ServerActiveHtml</code>
*/
public String getName() {
return _name ;
}
/**
* @return Return true if a template is linked to
*/
public boolean usesTemplate() {
return getTemplateName() != null ;
}
/**
* Return the name of the template linked to
*/
public String getTemplateName() {
return _templateName ;
}
/**
* Check for the implicit Element.
*
* @return Returns true if the implicit Element exists
*/
public boolean hasImplicitElement() {
return _implicitElement != null ;
}
/**
* Return the implicit Element.
*
* @return Returns the implicit Element if it exists otherwise
* returns null.
*/
public Element getImplicitElement() {
return _implicitElement ;
}
/**
* @return Returns the implicit Element, creating it if it does not exist
*/
private Element getImplicitElementCreateIfNull() {
if ( _implicitElement == null )
_implicitElement = new Element( IMPLICIT_ELEMENT_NAME ) ;
return _implicitElement ;
}
/**
* Return the count of <code>Element</code>s.
*
* Note: This excludes the implicit <code>Element</code>
*/
public int getElementCount( ) {
if ( _elements == null )
throw new IllegalStateException( "Called before template text had been set" ) ;
return _elements.size() ;
}
/**
* Check for the named <code>Element</code>.
*
* Note: Does not test for the implicit object.
*
* @return Returns true if the named <code>Element</code> is
* in the list of <code>Element</code>s maintained ny this
* <code>ServerActiveHtml</code>
*/
public boolean hasElement( String name ) {
if ( _elements == null )
return false ;
Iterator it = _elements.iterator() ;
while ( it.hasNext() )
if ( ((Element) it.next() ).getName().equals( name ) )
return true ;
return false ;
}
/**
* Return the named <code>Element</code>. If the <code>Element</code> is
* missing return null.
*
* Note: Does not test for the implicit object.
*
* @param name The name of the element to return.
*
* @return Return the Element if found otherwise returns null.
*/
public Element getElement( String name ) {
if ( _elements == null )
return null ;
Iterator it = _elements.iterator() ;
while ( it.hasNext() ) {
Element element = (Element) it.next() ;
if ( element.getName().equals( name ) )
return element ;
}
return null ;
}
/**
* Return the list of <code>Element</code>s.
*/
public List getElements() {
if ( _elements == null )
return Collections.EMPTY_LIST ;
return _elements ;
}
/**
* Return the first <code>ELement</code> found in a breadth-first traversal
* of this object's <code>Elements</code> and all descendant <code>Elements</code>.
*
* @param name The name of the element to find
* @return Return the first <code>Element</code> with named name or null. The search
* is breadth-first.
*/
public Element findElement( String name ) {
if ( name == null )
throw new IllegalArgumentException( "name was null" ) ;
Element found = null ;
for ( List candidates = getChildren() ; candidates.size() > 0 ; ) {
found = findElementFromCandiates( candidates, name ) ;
if ( found != null )
break ;
/* The new candidates are the Elements of the ServerActiveHtmls of the current Elements */
candidates = getNextLevelOfElements ( candidates ) ;
}
return found ;
}
private Element findElementFromCandiates( List candidates, String name ) {
for ( Iterator elements = candidates.iterator() ; elements.hasNext() ; ) {
Element e = ( Element ) elements.next() ;
if ( e.getName().equals( name ) )
return e ;
}
return null ;
}
private List getNextLevelOfElements( List elementList ) {
List result = new LinkedList() ;
for ( Iterator elements = elementList.iterator() ; elements.hasNext() ; ) {
for ( Iterator sahs = ( ( Element ) elements.next() ).getServerActiveHtmls().iterator() ; sahs.hasNext() ; ) {
result.addAll( ( ( ServerActiveHtml ) sahs.next() ).getChildren() ) ;
}
}
return result ;
}
/* ---- Implementation of JspSerializable --- */
/**
* As this will be used to write out the JSP we need to return
* all <code>Element</code>s including the implicit <code>Element</code>
*/
public List getChildren() {
/* Copy the list so the original does not change */
List children = new LinkedList( getElements() ) ;
if ( hasImplicitElement() )
children.add( getImplicitElement() ) ;
return children ;
}
public String getComponentTypeName() {
//FIXME: temporary.
return DEFAULT_COMPONENT_TYPE ;
}
/**
* Create the code to set up this object. See interface JspSerializable for details.
*
* @param objName The name of the object to create and initialise.
*
* @param buffer A <code>StringBuilder</code> to append set up code to
*
* @param finderSet A <code>FinderSet</code> used to look up information based
* on a certain context. The context is expected to be the current page location.
*/
public void getSetUpCode( String objName, StringBuilder buffer, FinderSet finderSet ) {
if ( finderSet == null )
throw new IllegalArgumentException(
"Attempt to invoke ServerActiveHtml.getSetUpCode with null finderSet" ) ;
ApplicationFinder appFinder = finderSet.getApplicationFinder() ;
if ( appFinder == null )
throw new IllegalArgumentException(
"Attempt to invoke ServerActiveHtml.getSetUpCode with null appFinder" ) ;
/*
* Ask the application data finder for the data for this named server active object.
*/
Properties appData = appFinder.getSaoData( getName() ) ;
String clazzName = DEFAULT_COMPONENT_CLASS ;
if ( appData != null ) {
clazzName = appFinder.getClazzName( appData ) ;
}
JspUtility.getObjectCreationCode( objName, clazzName, buffer ) ;
/*
* Now add the property setters.
*
* Note: This is not type safe. It's the responsibilty of the developer while
* configuring the sao to make sure a corresponding method signature exists.
*
* Currently we assume the argument is a String. Adding this property
*
* sao.my-sao-name.prop.newsFeedId = [email protected]
*
* will generate this code
*
* (DEFAULT_COMPONENT_CLASS) component_1.setNewsFeedId ( "[email protected]" ) ;
*/
if ( appData != null ) {
Properties props = CollectionsUtilities.getPropertiesSubset( appData, ApplicationFinder.PROPERTY_NAMES_PREFIX ) ;
/* Order the properties for unit testing */
if ( props != null ) {
SortedSet keys = new TreeSet( props.keySet() ) ;
Iterator it = keys.iterator() ;
while ( it.hasNext() ) {
String prop = (String) it.next() ;
String val = props.getProperty( prop ) ;
buffer.append(
"( ( " + clazzName + " ) " + objName + " ).set" + StringUtilities.capitaliseFirstLetter( prop ) +
//" ( \"" + JspUtility.jspEscape ( StringUtilities.escapeString ( val ) ) + "\" ) ;\n"
" ( " + JspUtility.makeSafeQuoted( val ) + " ) ;\n"
) ;
}
}
}
super.getSetUpCode( objName, buffer, finderSet ) ;
}
/**
* The complier selects the overloaded method to invoke at compile time so
* this will not invoke add ( Fragment ) but will invoke add ( Object )
*
* Object frag = new Fragment () ;
* sah.add ( frag ) ;
*
* This is awkward when using the return of Iterator.next () ;
*
* We solve this Java feature with this convenience method.
*
* @param deserializable an instance of <code>Deserializable</code>
*/
public void add( Deserializable deserializable ) {
if ( deserializable instanceof Fragment )
add( ( Fragment ) deserializable ) ;
else if ( deserializable instanceof ServerActiveHtml )
add( ( ServerActiveHtml ) deserializable ) ;
else if( deserializable instanceof Element )
add( ( Element ) deserializable ) ;
else if( deserializable instanceof Placeholder )
add( ( Fragment ) deserializable ) ;
else
throw new IllegalArgumentException( "Unhandled type: " + deserializable.getClass().getName() ) ;
}
/* --- Implementation of Deserializable --- */
/**
* A method to append a <code>Fragment</code> to an object,
* typically used in the deserialization of that object.
*
* When a <code>ServerActiveHtml</code> is asked to append a <code>Fragment</code>
* it delegates this to an implicit <code>Element</code> which is created on demand.
*/
public void add( Fragment fragment ) {
//System.out.println ("[ServerActiveHtml] add Fragment" );
/*
* If this <code>ServerActiveHtml</code> uses a template nothing
* it contains is relevant so we ignore it.
*/
// TEMP if ( usesTemplate () )
// TEMP return ;
getImplicitElementCreateIfNull().add( fragment ) ;
}
/**
* A method to add an <code>ServerActiveHtml</code> object to a
* <code>ServerActiveHtml</code> object.
*
* In this case we add the <code>ServerActiveHtml</code> to the implicit <code>Element</code>
*
*/
public void add( ServerActiveHtml child ) {
//System.out.println ("[ServerActiveHtml] add ServerActiveHtml" );
/*
* If this <code>ServerActiveHtml</code> uses a template nothing
* it contains is relevant so we ignore it.
* 02-9-5 jdb. No longer true, the children may be used when replacing Placeholders
*/
// TEMP if ( usesTemplate () )
// TEMP return ;
getImplicitElementCreateIfNull().add( child ) ;
}
/**
* A method to add an <code>Element</code> object to a
* <code>ServerActiveHtml</code> object.
*
* In this case we add the <code>Element</code> to the list of
* Elements.
*
* @param child The <code>Element</code> to add. If a child with the same
* name exists a <code>IllegalArgumentException</code> is thrown.
*
* @throws A <code>IllegalArgumentException</code> is thrown if this object
* already has an <code>Element</code> with the same name.
*/
public void add( Element child ) {
//System.out.println ("[ServerActiveHtml] add Element" );
/*
* If this <code>ServerActiveHtml</code> uses a template nothing
* it contains is relevant so we ignore it.
* 02-9-5 jdb. No longer true, the children may be used when replacing Placeholders
*/
// TEMP if ( usesTemplate () )
// TEMP return ;
if ( _elements == null )
_elements = new LinkedList() ;
/* Disallow duplicates (for now) */
if ( hasElement( child.getName() ) )
throw new IllegalArgumentException("[ServerActiveHtml]: Attempt to add duplicate Element: " + child.getName() );
_elements.add( child ) ;
}
/**
* A method to add a <code>Placeholder</code> to a deserializable object,
* used in the deserialization of objects from marked up html.
* <p>
* FIXME: Disallow this operation when the ServerActiveHtml has not been created
* for use in the parsing of a template.
* <p>
* In the majority of cases a Placeholder will be added directly to an Element
* because this is how MarkedUpHtmlParser operates when parsing a template. However
* in the use case of a intermediate template being used to provide a default for
* some elements then a Placeholder may be added. See Example B in the package documentation
* for details.
*
* @param placeholder The <code>Placeholder</code> to add.
*/
public void add( Placeholder placeholder ) {
getImplicitElementCreateIfNull().add( placeholder ) ;
}
public int hashCode() {
return 37 * getName().hashCode() + ( usesTemplate() ? 1 : 0 ) ;
}
/**
* Return true if the objects are the same class and
* have the same content.
*/
public boolean equals( Object obj ) {
if ( obj == null )
return false ;
if ( ! ( obj instanceof ServerActiveHtml ) )
return false ;
ServerActiveHtml sah = (ServerActiveHtml) obj ;
if ( ! sah.getName().equals( getName() ) )
return false ;
if ( sah.usesTemplate() != usesTemplate() )
return false ;
if ( usesTemplate() )
if ( ! sah.getTemplateName().equals( getTemplateName() ) )
return false ;
/* both null or equal if we get here */
if ( _implicitElement != null ) {
if ( ! _implicitElement.equals( sah._implicitElement ) )
return false ;
}
else if ( sah._implicitElement != null ) {
return false ;
}
/* both null or equal if we get here */
if ( _elements != null ) {
if ( ! _elements.equals( sah._elements ) )
return false ;
}
else if ( sah._elements != null ) {
return false ;
}
/* both null or equal if we get here */
if ( ! sah.getPlaceholders().equals( getPlaceholders() ) )
return false ;
return true ;
}
public String toString() {
return new ToStringBuilder (this, ToStringStyle.MULTI_LINE_STYLE ).
append ( "_name", _name).
append ( "_templateName", _templateName).
append ( "_elements", _elements ).
append ( "_implicitElement", _implicitElement ).
append ( "placeholders", getPlaceholders ()).
toString ();
}
}
| 33.425641 | 129 | 0.588882 |
330be58fe5afa8a14afbaa0a40e2bb20b1af24de | 354 | package com.boluozhai.snowflake.xgit.repository;
import java.net.URI;
import com.boluozhai.snowflake.xgit.XGitComponent;
import com.boluozhai.snowflake.xgit.XGitContext;
import com.boluozhai.snowflake.xgit.workspace.Workspace;
public interface Repository extends XGitComponent {
XGitContext context();
URI location();
Workspace getWorking();
}
| 19.666667 | 56 | 0.80791 |
83fde7cc7d9973e242f7d39eb33641cca1327dc3 | 1,706 | package com.aditya.personal.algorithmproblems.leetCode;
import java.util.LinkedList;
import java.util.Queue;
public class M_116_PopulatingNextRightPointersInEachNode {
class Node {
public int val;
public Node left;
public Node right;
public Node next;
public Node() {
}
public Node(int _val) {
val = _val;
}
public Node(int _val, Node _left, Node _right, Node _next) {
val = _val;
left = _left;
right = _right;
next = _next;
}
}
public Node connectRecursive(Node root) {
if (root != null && root.left != null && root.right != null) {
root.left.next = root.right;
if (root.next != null)
root.right.next = root.next.left;
connectRecursive(root.left);
connectRecursive(root.right);
}
return root;
}
public Node connectApproachLevelOrder(Node root) {
if (root == null)
return null;
Queue<Node> toProcess = new LinkedList<>();
toProcess.add(root);
while (!toProcess.isEmpty()) {
int size = toProcess.size();
for (int i = size; i > 0; i--) {
Node current = toProcess.poll();
if (i == 1) {
current.next = null;
} else
current.next = toProcess.peek();
if (current.left != null)
toProcess.add(current.left);
if (current.right != null)
toProcess.add(current.right);
}
}
return root;
}
}
| 22.746667 | 70 | 0.492966 |
ec45e58a410d078a6288bd45ad8c828eceef9f91 | 1,740 | package mg.rivolink.app.aruco.renderer;
import android.content.Context;
import android.view.MotionEvent;
import org.rajawali3d.Object3D;
import org.rajawali3d.lights.PointLight;
import org.rajawali3d.loader.LoaderOBJ;
import org.rajawali3d.loader.ParsingException;
import org.rajawali3d.renderer.Renderer;
import mg.rivolink.app.aruco.R;
public class Renderer3D extends Renderer {
private Object3D model;
private PointLight light;
public Renderer3D(Context context){
super(context);
setFrameRate(60);
}
@Override
protected void initScene(){
light = new PointLight();
light.setPosition(0, 0, 4);
light.setPower(3);
try {
LoaderOBJ objParser = new LoaderOBJ(mContext.getResources(), mTextureManager, R.raw.box_obj);
objParser.parse();
model = objParser.getParsedObject();
model.setPosition(0, 0, -10);
model.setVisible(false);
getCurrentScene().addLight(light);
getCurrentScene().addChild(model);
}
catch(ParsingException e){
e.printStackTrace();
}
}
public void transform(double tx, double ty, double tz, double yaw, double pitch, double roll){
/* Some bugs here
if(!model.isVisible())
model.setVisible(true);
model.setPosition(tx, ty, tz);
model.setOrientation(new Quaternion().fromEuler(
Math.toDegrees(yaw),
Math.toDegrees(pitch),
Math.toDegrees(roll)
));
*/
}
@Override
protected void render(long ellapsedRealtime, double deltaTime){
super.render(ellapsedRealtime, deltaTime);
//model.rotate(Vector3.Axis.Y, 0.5);
}
@Override
public void onOffsetsChanged(float x, float y, float z, float w, int i, int j){
// TODO: Implement this method
}
@Override
public void onTouchEvent(MotionEvent p1){
// TODO: Implement this method
}
}
| 22.307692 | 96 | 0.728736 |
e337e1efcc23dac9c752a61305cc15a2261e66c6 | 4,149 | package mchorse.mclib.client.gui.mclib;
import mchorse.mclib.client.gui.framework.elements.buttons.GuiButtonElement;
import mchorse.mclib.client.gui.framework.elements.buttons.GuiSlotElement;
import mchorse.mclib.client.gui.framework.elements.context.GuiSimpleContextMenu;
import mchorse.mclib.client.gui.framework.elements.input.GuiTextElement;
import mchorse.mclib.client.gui.framework.elements.keyframes.GuiDopeSheet;
import mchorse.mclib.client.gui.framework.elements.keyframes.GuiGraphView;
import mchorse.mclib.client.gui.framework.elements.keyframes.GuiKeyframesEditor;
import mchorse.mclib.client.gui.framework.elements.keyframes.GuiSheet;
import mchorse.mclib.client.gui.framework.elements.utils.GuiContext;
import mchorse.mclib.client.gui.utils.Icons;
import mchorse.mclib.client.gui.utils.keys.IKey;
import mchorse.mclib.utils.Color;
import mchorse.mclib.utils.keyframes.Keyframe;
import mchorse.mclib.utils.keyframes.KeyframeChannel;
import mchorse.mclib.utils.keyframes.KeyframeInterpolation;
import net.minecraft.client.Minecraft;
import net.minecraft.init.Items;
import net.minecraft.item.ItemStack;
public class GuiDebugPanel extends GuiDashboardPanel<GuiAbstractDashboard>
{
public GuiKeyframesEditor<GuiDopeSheet> dopesheet;
public GuiKeyframesEditor<GuiGraphView> graph;
public GuiButtonElement play;
public GuiSlotElement slot;
public GuiTextElement text;
public GuiDebugPanel(Minecraft mc, GuiAbstractDashboard dashboard)
{
super(mc, dashboard);
this.dopesheet = new GuiKeyframesEditor<GuiDopeSheet>(mc)
{
@Override
protected GuiDopeSheet createElement(Minecraft mc)
{
return new GuiDopeSheet(mc, this::fillData);
}
};
this.graph = new GuiKeyframesEditor<GuiGraphView>(mc)
{
@Override
protected GuiGraphView createElement(Minecraft mc)
{
return new GuiGraphView(mc, this::fillData);
}
};
KeyframeChannel channel = new KeyframeChannel();
channel.insert(0, 10);
Keyframe a = channel.get(channel.insert(20, 10));
channel.get(channel.insert(80, 0));
channel.get(channel.insert(100, 0));
a.interp = KeyframeInterpolation.BEZIER;
for (int i = 0; i < 5; i++)
{
KeyframeChannel c = new KeyframeChannel();
c.copy(channel);
this.dopesheet.graph.sheets.add(new GuiSheet("" + i, IKey.str("Test " + i), new Color((float) Math.random(), (float) Math.random(), (float) Math.random()).getRGBColor(), c));
}
this.dopesheet.graph.duration = 100;
this.graph.graph.setChannel(channel, 0x0088ff);
this.graph.graph.duration = 100;
this.dopesheet.flex().relative(this).y(0).wh(1F, 0.5F);
this.graph.flex().relative(this).y(0.5F).wh(1F, 0.5F);
this.slot = new GuiSlotElement(mc, 0, (t) -> {});
this.slot.flex().relative(this).x(0.5F).y(20).anchorX(0.5F);
this.slot.setStack(new ItemStack(Items.BAKED_POTATO, 42));
this.play = new GuiButtonElement(mc, IKey.str("Play me!"), null).background(false);
this.play.flex().relative(this).xy(10, 10).w(80);
this.text = new GuiTextElement(mc, 1000, null).background(false);
this.text.flex().relative(this).xy(10, 40).w(80);
this.add(this.graph, this.dopesheet);
this.add(this.slot, this.play, this.text);
this.context(() ->
{
GuiSimpleContextMenu contextMenu = new GuiSimpleContextMenu(mc);
for (int i = 0; i < 100; i++)
{
contextMenu.action(Icons.POSE, IKey.str("I came §8" + (i + 1)), null);
}
return contextMenu;
});
}
@Override
public boolean isClientSideOnly()
{
return true;
}
@Override
public void resize()
{
super.resize();
}
@Override
public void draw(GuiContext context)
{
super.draw(context);
this.text.background(System.currentTimeMillis() % 2000 < 1000);
}
} | 33.731707 | 186 | 0.657508 |
f76290ece8f09f6eeeafc814cb35442dd2542256 | 2,160 | package stackElimination;
import java.util.concurrent.atomic.AtomicReference;
public class LockFreeStack<T> implements MyStack<T>
{
AtomicReference<Node<T>> top = new AtomicReference<Node<T>>(null);
static int MIN_DELAY = 1, MAX_DELAY = 100;
Backoff backoff = new Backoff(MIN_DELAY, MAX_DELAY);
LockFreeStack(int min, int max)
{
MIN_DELAY = min;
MAX_DELAY = max;
}
protected boolean tryPush(Node<T> node)
{
Node<T> oldTop = top.get();
node.next = oldTop;
return (top.compareAndSet(oldTop, node));
}
@Override
public void push(T value) throws InterruptedException
{
Node<T> node = new Node<T>((T)value);
while(true)
{
if(tryPush(node))
{
return;
}
else
{
backoff.backoff();
}
}
}
protected Node<T> tryPop() throws Exception
{
Node<T> oldTop = top.get();
if(oldTop == null)
throw new Exception("Its empty!");
Node<T> newTop = oldTop.next;
if(top.compareAndSet(oldTop, newTop))
return oldTop;
else
return null;
}
@Override
public T pop() throws Exception, InterruptedException
{
while(true)
{
Node<T> returnNode = tryPop();
if(returnNode != null)
return returnNode.value;
else
backoff.backoff();
}
}
@Override
public String getStackInfo()
{
return MIN_DELAY + "," + MAX_DELAY;
}
}
| 29.189189 | 74 | 0.398611 |
a78abef3228254a0703961b943fa6a3e6a8a33ed | 1,614 | package ru.guar7387.servermodule.tasksfactory;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.List;
import ru.guar7387.servermodule.Logger;
import ru.guar7387.servermodule.api.ConnectionManager;
import ru.guar7387.servermodule.api.ConnectionRequest;
import ru.guar7387.servermodule.callbacks.ArticleCommentsCallback;
import ru.guar7387.servermodule.callbacks.Callback;
public class LoadArticleCommentsTask extends AbstractTask {
private static final String TAG = LoadArticleCommentsTask.class.getSimpleName();
private final ArticleCommentsCallback commentsCallback;
private final List<Integer> commentsIds;
public LoadArticleCommentsTask(int requestCode, ConnectionRequest request, ConnectionManager connectionManager,
ArticleCommentsCallback commentsCallback) {
super(requestCode, request, connectionManager, null);
this.commentsCallback = commentsCallback;
commentsIds = new ArrayList<>();
}
@Override
public void parseJson(JSONObject answer) {
Logger.log(TAG, "Answer - " + answer);
try {
JSONArray ids = answer.getJSONObject("response").getJSONArray("result");
for (int i = 0; i < ids.length(); i++) {
commentsIds.add(ids.getInt(i));
}
} catch (JSONException ignored) {
}
}
@Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
commentsCallback.onArticleCommentLoaded(commentsIds);
}
}
| 32.938776 | 115 | 0.710657 |
c446d4ca0b7107622bcd1c372df7864aa6ef66ee | 16,730 | /*
* 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.asterix.optimizer.rules;
import java.util.List;
import org.apache.asterix.om.functions.BuiltinFunctions;
import org.apache.commons.lang3.mutable.Mutable;
import org.apache.hyracks.algebricks.common.exceptions.AlgebricksException;
import org.apache.hyracks.algebricks.core.algebra.base.ILogicalExpression;
import org.apache.hyracks.algebricks.core.algebra.base.IOptimizationContext;
import org.apache.hyracks.algebricks.core.algebra.base.LogicalExpressionTag;
import org.apache.hyracks.algebricks.core.algebra.base.LogicalVariable;
import org.apache.hyracks.algebricks.core.algebra.expressions.AbstractFunctionCallExpression;
import org.apache.hyracks.algebricks.core.algebra.expressions.VariableReferenceExpression;
import org.apache.hyracks.algebricks.core.algebra.functions.FunctionIdentifier;
import org.apache.hyracks.algebricks.core.algebra.operators.logical.AbstractScanOperator;
import org.apache.hyracks.algebricks.core.algebra.properties.IProjectionFiltrationProperties;
import org.apache.hyracks.api.util.DebugParameters;
/**
* This rewrite at first look up for all the involved datasets when {@link #rewritePre(Mutable, IOptimizationContext)}
* is called. If the one or more datasets are either columnar or compacted,
* then, the {@link #rewritePost(Mutable, IOptimizationContext)} will push down all field accesses to the
* scan operator as projected expressions.
*/
public class PushFieldAccessToDataScanRule extends AbstractPushFieldAccessToDataScanRule {
@Override
protected boolean pushFunction(AbstractFunctionCallExpression funcExpr) {
// return BuiltinFunctions.FLAT_OBJECT_FIELD_ACCESS.equals(funcExpr.getFunctionIdentifier());
if (funcExpr.getFunctionIdentifier().equals(BuiltinFunctions.LT)) {
DebugParameters.instance().noOp();
}
return true;
}
@Override
protected void pushFilterDown(AbstractScanOperator changedScanOp, Mutable<ILogicalExpression> conditionRef,
IProjectionFiltrationProperties properties) {
ILogicalExpression condition = conditionRef.getValue();
if (changedScanOp.isPAX() || !isPushableCondition(condition)) {
return;
}
AbstractFunctionCallExpression conditionFunc = (AbstractFunctionCallExpression) condition;
ILogicalExpression arg1 = conditionFunc.getArguments().get(0).getValue();
ILogicalExpression arg2 = conditionFunc.getArguments().get(1).getValue();
List<LogicalVariable> pushedExprVars = changedScanOp.getScanVariables();
int index = pushedExprVars.size() - 1;
ILogicalExpression pushedExprVar = new VariableReferenceExpression(pushedExprVars.get(index));
if (arg1.equals(pushedExprVar)) {
changedScanOp.addFilterExpr(index, arg2);
} else if (arg2.equals(pushedExprVar)) {
changedScanOp.addFilterExpr(index, arg1);
}
}
private boolean isPushableCondition(ILogicalExpression expr) {
if (expr.getExpressionTag() != LogicalExpressionTag.FUNCTION_CALL) {
return false;
}
AbstractFunctionCallExpression funcExpr = (AbstractFunctionCallExpression) expr;
FunctionIdentifier functionIdentifier = funcExpr.getFunctionIdentifier();
LogicalExpressionTag arg1 = funcExpr.getArguments().get(0).getValue().getExpressionTag();
LogicalExpressionTag arg2 = funcExpr.getArguments().get(1).getValue().getExpressionTag();
return (BuiltinFunctions.EQ.equals(functionIdentifier) || BuiltinFunctions.GE.equals(functionIdentifier)
|| BuiltinFunctions.GT.equals(functionIdentifier) || BuiltinFunctions.LE.equals(functionIdentifier)
|| BuiltinFunctions.LT.equals(functionIdentifier))
&& (arg1 == LogicalExpressionTag.CONSTANT || arg2 == LogicalExpressionTag.CONSTANT);
}
@Override
protected boolean shouldApply(AbstractScanOperator scanOp) {
return scanOp.isColumnar() || scanOp.isCompacted();
}
//TODO copy if common expression
@Override
protected boolean wrapWithAccessor(LogicalVariable unnestProduced, LogicalVariable unnestSource,
AbstractFunctionCallExpression funcExpr, Mutable<ILogicalExpression> exprRef, IOptimizationContext context)
throws AlgebricksException {
// if (!shouldApply(changedScanOp)) {
// return false;
// }
//
// final int scanExprVarIndex = changedScanOp.getVariables().indexOf(unnestSource);
// final Mutable<ILogicalExpression> scanExprRef = changedScanOp.getProjectExpressions().get(scanExprVarIndex);
// final AbstractFunctionCallExpression fieldAccess = getVBFieldAccessor(scanExprRef);
// if (fieldAccess == null) {
// return false;
// }
// fieldAccess.getArguments().add(new MutableObject<>(ConstantExpressionUtil.createConstantExpression(-2)));
// final List<Mutable<ILogicalExpression>> toBePushedArgs =
// ((AbstractFunctionCallExpression) exprRef.getValue()).getArguments();
// for (int i = 1; i < toBePushedArgs.size(); i++) {
// fieldAccess.getArguments().add(new MutableObject<>(toBePushedArgs.get(i).getValue()));
// }
// exprRef.setValue(new VariableReferenceExpression(unnestProduced));
// changedScanOp.computeInputTypeEnvironment(context);
// return true;
return false;
}
@Override
protected boolean pushAsCommonExpression(LogicalVariable funcRootInputVar, Mutable<ILogicalExpression> exprRef,
IOptimizationContext context, IProjectionFiltrationProperties properties) throws AlgebricksException {
// AbstractScanOperator scan = properties.getScanOperator(funcRootInputVar);
// if (scan == null) {
// return false;
// }
// int exprIndex = scan.getVariables().indexOf(funcRootInputVar);
// AbstractFunctionCallExpression originalExpr =
// (AbstractFunctionCallExpression) scan.getProjectExpressions().get(exprIndex).getValue()
// .cloneExpression();
// AbstractFunctionCallExpression funcExpr = (AbstractFunctionCallExpression) exprRef.getValue();
// List<Mutable<ILogicalExpression>> originalExprArgs = originalExpr.getArguments();
// List<Mutable<ILogicalExpression>> exprArgs = funcExpr.getArguments();
// for (int i = 1; i < exprArgs.size(); i++) {
// originalExprArgs.add(exprArgs.get(i));
// }
// exprRef.setValue(originalExpr);
// return pushExpressionToScan(exprRef, context, properties);
return false;
}
private AbstractFunctionCallExpression getVBFieldAccessor(Mutable<ILogicalExpression> scanExprRef) {
ILogicalExpression expr = scanExprRef.getValue();
boolean found = BuiltinFunctions.FLAT_OBJECT_FIELD_ACCESS
.equals(((AbstractFunctionCallExpression) expr).getFunctionIdentifier());
while (expr.getExpressionTag() == LogicalExpressionTag.FUNCTION_CALL && !found) {
AbstractFunctionCallExpression funcExpr = (AbstractFunctionCallExpression) expr;
expr = funcExpr.getArguments().get(0).getValue();
found = BuiltinFunctions.FLAT_OBJECT_FIELD_ACCESS.equals(funcExpr.getFunctionIdentifier());
}
return found ? (AbstractFunctionCallExpression) expr : null;
}
// private boolean pushableDataset;
// private final List<LogicalVariable> recordVariables = new ArrayList<>();
// private final List<AbstractScanOperator> scanOps = new ArrayList<>();
// private final Map<LogicalVariable, AbstractScanOperator> pushedExpers = new HashMap<>();
// private AbstractScanOperator changedScanOp;
// private ILogicalOperator op;
//
// @Override
// public boolean rewritePre(Mutable<ILogicalOperator> opRef, IOptimizationContext context)
// throws AlgebricksException {
// final ILogicalOperator currentOp = opRef.getValue();
// if (currentOp.getOperatorTag() != LogicalOperatorTag.DATASOURCESCAN
// && currentOp.getOperatorTag() != LogicalOperatorTag.UNNEST_MAP) {
// return false;
// }
//
// final MetadataProvider mp = (MetadataProvider) context.getMetadataProvider();
// final AbstractScanOperator scan = (AbstractScanOperator) currentOp;
// final DataSource dataSource = CompactedDatasetUtil.getDatasourceInfo(mp, scan);
//
// if (dataSource == null) {
// return false;
// }
// final DataverseName dataverse = dataSource.getId().getDataverseName();
// final String dataset = dataSource.getId().getDatasourceName();
// setPushableDataset(mp.findDataset(dataverse, dataset), scan, dataSource);
// return false;
// }
//
// @Override
// public boolean rewritePost(Mutable<ILogicalOperator> opRef, IOptimizationContext context)
// throws AlgebricksException {
//
// if (!pushableDataset) {
// return false;
// }
//
// op = opRef.getValue();
// if (op.getOperatorTag() != LogicalOperatorTag.SELECT && op.getOperatorTag() != LogicalOperatorTag.ASSIGN) {
// return false;
// }
//
// final boolean changed;
// if (op.getOperatorTag() == LogicalOperatorTag.SELECT) {
// final SelectOperator selectOp = (SelectOperator) op;
// changed = pushFieldAccessExpression(selectOp.getCondition(), context);
// } else {
// final AssignOperator assignOp = (AssignOperator) op;
// changed = pushFieldAccessExpression(assignOp.getExpressions(), context);
// }
//
// if (changed) {
// context.computeAndSetTypeEnvironmentForOperator(changedScanOp);
// context.computeAndSetTypeEnvironmentForOperator(op);
// }
// return changed;
// }
//
// private boolean pushFieldAccessExpression(List<Mutable<ILogicalExpression>> exprList,
// IOptimizationContext context) {
//
// boolean changed = false;
// for (Mutable<ILogicalExpression> exprRef : exprList) {
// changed |= pushFieldAccessExpression(exprRef, context);
// }
// return changed;
// }
//
// private boolean pushFieldAccessExpression(Mutable<ILogicalExpression> exprRef, IOptimizationContext context) {
// final ILogicalExpression expr = exprRef.getValue();
// final boolean changed;
// if (expr.getExpressionTag() != LogicalExpressionTag.FUNCTION_CALL) {
// return false;
// }
//
// final AbstractFunctionCallExpression funcExpr = (AbstractFunctionCallExpression) expr;
//
// //Get root expression input variable in case it is nested field access
// final LogicalVariable funcRootInputVar = getRootExpressionInputVariable(funcExpr);
// //Check if it's a field access
// if (funcRootInputVar != null) {
// final int recordVarIndex = recordVariables.indexOf(funcRootInputVar);
// //Is funcRootInputVar originated from a data-scan operator?
// if (recordVarIndex >= 0) {
// changedScanOp = scanOps.get(recordVarIndex);
// pushExpressionToScan(exprRef, context);
// changed = true;
// } else {
// changed = false;
// }
// } else {
// //Descend to the arguments expressions to see if any can be pushed
// changed = pushFieldAccessExpression(funcExpr.getArguments(), context);
// }
//
// return changed;
// }
//
// private void pushExpressionToScan(Mutable<ILogicalExpression> exprRef, IOptimizationContext context) {
// //Add the corresponding variable to the scan operator
// final LogicalVariable newVar;
// final ILogicalExpression expr = exprRef.getValue();
// if (op.getOperatorTag() == LogicalOperatorTag.SELECT) {
// //Substitute the condition with new variable reference expression
// newVar = context.newVar();
// final VariableReferenceExpression varExpr = new VariableReferenceExpression(newVar);
// exprRef.setValue(varExpr);
// } else {
// //It's assign. Use the same assigned variable to avoid substituting for parent operators
// final AssignOperator assignOp = (AssignOperator) op;
// final int exprIndex = assignOp.getExpressions().indexOf(exprRef);
//
// if (exprIndex >= 0) {
// /*
// * Set the pushed down expression to a new
// * variable in the AssignOperator which is going to be removed out as it's not used
// */
// newVar = assignOp.getVariables().get(exprIndex);
// assignOp.getExpressions().get(exprIndex).setValue(new VariableReferenceExpression(newVar));
// assignOp.getVariables().set(exprIndex, context.newVar());
// } else {
// //Substitute the INNER expression with new variable reference expression
// newVar = context.newVar();
// final VariableReferenceExpression varExpr = new VariableReferenceExpression(newVar);
// exprRef.setValue(varExpr);
// }
// }
// //Add fieldAccessExpr to the scan
// changedScanOp.addProjectExpression(new MutableObject<>(expr), BuiltinType.ANY);
// changedScanOp.getVariables().add(newVar);
// pushedExpers.put(newVar, changedScanOp);
// }
//
// private void setPushableDataset(Dataset dataset, AbstractScanOperator scan, DataSource dataSource) {
// if (dataset != null && dataset.getDatasetType() == DatasetType.INTERNAL) {
// DatasetDataSource datasetDataSource = (DatasetDataSource) dataSource;
// pushableDataset |= datasetDataSource.isAllowPushdown();
// final LogicalVariable recordVar = datasetDataSource.getDataRecordVariable(scan.getVariables());
// scan.addPayloadExpression(new VariableReferenceExpression(recordVar));
// if (dataset.isColumnar()) {
// scan.setColumnar(true);
// } else {
// scan.setCompacted(true);
// }
// recordVariables.add(recordVar);
// scanOps.add(scan);
// }
// }
//
// private static LogicalVariable getRootExpressionInputVariable(AbstractFunctionCallExpression funcExpr) {
// ILogicalExpression currentExpr = funcExpr.getArguments().get(0).getValue();
// while (currentExpr.getExpressionTag() == LogicalExpressionTag.FUNCTION_CALL) {
// currentExpr = ((AbstractFunctionCallExpression) currentExpr).getArguments().get(0).getValue();
// }
//
// if (currentExpr.getExpressionTag() == LogicalExpressionTag.VARIABLE) {
// return ((VariableReferenceExpression) currentExpr).getVariableReference();
// }
// return null;
// }
}
| 52.776025 | 126 | 0.642857 |
f52ea48ea4076762936fd853f61d727c170d0eeb | 2,339 | package net.minecraft.util.profiling.jfr;
import java.net.SocketAddress;
import java.nio.file.Path;
import javax.annotation.Nullable;
import net.minecraft.resources.ResourceKey;
import net.minecraft.util.profiling.jfr.callback.ProfiledDuration;
import net.minecraft.world.level.ChunkPos;
import net.minecraft.world.level.Level;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
public interface JvmProfiler {
JvmProfiler INSTANCE = (JvmProfiler)(Runtime.class.getModule().getLayer().findModule("jdk.jfr").isPresent() ? JfrProfiler.getInstance() : new JvmProfiler.NoOpProfiler());
boolean start(Environment p_185347_);
Path stop();
boolean isRunning();
boolean isAvailable();
void onServerTick(float p_185342_);
void onPacketReceived(int p_185343_, int p_185344_, SocketAddress p_185345_, int p_185346_);
void onPacketSent(int p_185351_, int p_185352_, SocketAddress p_185353_, int p_185354_);
@Nullable
ProfiledDuration onWorldLoadedStarted();
@Nullable
ProfiledDuration onChunkGenerate(ChunkPos p_185348_, ResourceKey<Level> p_185349_, String p_185350_);
public static class NoOpProfiler implements JvmProfiler {
static final Logger LOGGER = LogManager.getLogger();
static final ProfiledDuration noOpCommit = () -> {
};
public boolean start(Environment p_185368_) {
LOGGER.warn("Attempted to start Flight Recorder, but it's not supported on this JVM");
return false;
}
public Path stop() {
throw new IllegalStateException("Attempted to stop Flight Recorder, but it's not supported on this JVM");
}
public boolean isRunning() {
return false;
}
public boolean isAvailable() {
return false;
}
public void onPacketReceived(int p_185363_, int p_185364_, SocketAddress p_185365_, int p_185366_) {
}
public void onPacketSent(int p_185375_, int p_185376_, SocketAddress p_185377_, int p_185378_) {
}
public void onServerTick(float p_185361_) {
}
public ProfiledDuration onWorldLoadedStarted() {
return noOpCommit;
}
@Nullable
public ProfiledDuration onChunkGenerate(ChunkPos p_185370_, ResourceKey<Level> p_185371_, String p_185372_) {
return null;
}
}
} | 30.776316 | 173 | 0.719111 |
9bba88f52543d3090a54af5e5d4cb0d451ce6a11 | 1,543 | package takt.repositories;
import takt.models.User;
import org.springframework.stereotype.Repository;
import java.util.ArrayList;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.logging.Level;
import java.util.logging.Logger;
@Repository
public class UserRepository {
private static final Logger LOGGER = Logger.getLogger(UserRepository.class.getName());
private final Map<String, User> userMap; // Map<id, User>
public UserRepository() {
this.userMap = new ConcurrentHashMap<>();
}
public void add(User user) {
if (isPresent(user))
userMap.replace(user.getId(), user);
else
userMap.put(user.getId(), user);
}
public User getWithId(String id) {
return userMap.get(id);
}
public User getWithSessionId(String sessionId) {
User user = null;
try {
user = getAllUsers().stream()
.filter(iUser -> iUser.getSessionId().equals(sessionId))
.findFirst()
.orElse(null);
} catch (Exception e) {
LOGGER.log(Level.SEVERE, "Cannot get user with session id " + sessionId + ": " + e.getMessage(), e);
}
return user;
}
public void remove(String id) {
userMap.remove(id);
}
private boolean isPresent(User user) {
return userMap.containsKey(user.getId());
}
private ArrayList<User> getAllUsers() {
return new ArrayList<User>(userMap.values());
}
} | 27.553571 | 112 | 0.618276 |
2f19a1115509c954754c9a5a6e0a3f3c2b136845 | 2,504 | /*
* Copyright 2020 SvenAugustus
*
* 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 xyz.flysium;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import java.util.List;
import org.junit.Assert;
import org.junit.jupiter.api.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
import xyz.flysium.dao.entity.User;
import xyz.flysium.dao.repository.UserMapper;
@RunWith(SpringRunner.class)
@SpringBootTest
class SpringbootApplicationTests {
@Autowired
private UserMapper userMapper;
@Test
public void selectList() {
System.out.println(("----- selectAll method test ------"));
List<User> userList = userMapper.selectList(null);
Assert.assertEquals(5, userList.size());
userList.forEach(System.out::println);
}
@Test
public void selectPage() {
System.out.println(("----- selectPage method test ------"));
Page<User> page = new Page<>(1, 10);
QueryWrapper<User> wrapper = new QueryWrapper<>();
// SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
// String d = simpleDateFormat.format(date);
// wrapper.eq("".equals(d), "created_at", d).orderByAsc("id");
wrapper.like("email", "test").orderByAsc("id");
IPage<User> userList = userMapper.selectPage(page, wrapper);
Assert.assertEquals(1, userList.getCurrent());//当前页数
Assert.assertEquals(10, userList.getSize());//当前页的数据量
Assert.assertEquals(5, userList.getTotal());//总查询结果量
Assert.assertEquals(1, userList.getPages());//总页数
// 具体查询的结果,返回值是List<T>
userList.getRecords().forEach(System.out::println);
}
}
| 37.373134 | 89 | 0.702077 |
03878f69d4ee256ff907ec0c5b046b9814557013 | 15,486 | // Copyright 2003-2005 Arthur van Hoff, Rick Blair
// Licensed under Apache License version 2.0
// Original license LGPL
package javax.jmdns.impl;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.util.HashMap;
import java.util.Map;
import javax.jmdns.impl.constants.DNSConstants;
import javax.jmdns.impl.constants.DNSRecordClass;
/**
* An outgoing DNS message.
*
* @author Arthur van Hoff, Rick Blair, Werner Randelshofer
*/
public final class DNSOutgoing extends DNSMessage {
public static class MessageOutputStream extends ByteArrayOutputStream {
private final DNSOutgoing _out;
private final int _offset;
/**
* Creates a new message stream, with a buffer capacity of the specified size, in bytes.
*
* @param size
* the initial size.
* @exception IllegalArgumentException
* if size is negative.
*/
MessageOutputStream(int size, DNSOutgoing out) {
this(size, out, 0);
}
MessageOutputStream(int size, DNSOutgoing out, int offset) {
super(size);
_out = out;
_offset = offset;
}
void writeByte(int value) {
this.write(value & 0xFF);
}
void writeBytes(String str, int off, int len) {
for (int i = 0; i < len; i++) {
writeByte(str.charAt(off + i));
}
}
void writeBytes(byte data[]) {
if (data != null) {
writeBytes(data, 0, data.length);
}
}
void writeBytes(byte data[], int off, int len) {
for (int i = 0; i < len; i++) {
writeByte(data[off + i]);
}
}
void writeShort(int value) {
writeByte(value >> 8);
writeByte(value);
}
void writeInt(int value) {
writeShort(value >> 16);
writeShort(value);
}
void writeUTF(String str, int off, int len) {
// compute utf length
int utflen = 0;
for (int i = 0; i < len; i++) {
int ch = str.charAt(off + i);
if ((ch >= 0x0001) && (ch <= 0x007F)) {
utflen += 1;
} else {
if (ch > 0x07FF) {
utflen += 3;
} else {
utflen += 2;
}
}
}
// write utf length
writeByte(utflen);
// write utf data
for (int i = 0; i < len; i++) {
int ch = str.charAt(off + i);
if ((ch >= 0x0001) && (ch <= 0x007F)) {
writeByte(ch);
} else {
if (ch > 0x07FF) {
writeByte(0xE0 | ((ch >> 12) & 0x0F));
writeByte(0x80 | ((ch >> 6) & 0x3F));
writeByte(0x80 | ((ch >> 0) & 0x3F));
} else {
writeByte(0xC0 | ((ch >> 6) & 0x1F));
writeByte(0x80 | ((ch >> 0) & 0x3F));
}
}
}
}
void writeName(String name) {
writeName(name, true);
}
void writeName(String name, boolean useCompression) {
String aName = name;
while (true) {
int n = aName.indexOf('.');
if (n < 0) {
n = aName.length();
}
if (n <= 0) {
writeByte(0);
return;
}
String label = aName.substring(0, n);
if (useCompression && USE_DOMAIN_NAME_COMPRESSION) {
Integer offset = _out._names.get(aName);
if (offset != null) {
int val = offset.intValue();
writeByte((val >> 8) | 0xC0);
writeByte(val & 0xFF);
return;
}
_out._names.put(aName, Integer.valueOf(this.size() + _offset));
writeUTF(label, 0, label.length());
} else {
writeUTF(label, 0, label.length());
}
aName = aName.substring(n);
if (aName.startsWith(".")) {
aName = aName.substring(1);
}
}
}
void writeQuestion(DNSQuestion question) {
writeName(question.getName());
writeShort(question.getRecordType().indexValue());
writeShort(question.getRecordClass().indexValue());
}
void writeRecord(DNSRecord rec, long now) {
writeName(rec.getName());
writeShort(rec.getRecordType().indexValue());
writeShort(rec.getRecordClass().indexValue() | ((rec.isUnique() && _out.isMulticast()) ? DNSRecordClass.CLASS_UNIQUE : 0));
writeInt((now == 0) ? rec.getTTL() : rec.getRemainingTTL(now));
// We need to take into account the 2 size bytes
MessageOutputStream record = new MessageOutputStream(512, _out, _offset + this.size() + 2);
rec.write(record);
byte[] byteArray = record.toByteArray();
writeShort(byteArray.length);
write(byteArray, 0, byteArray.length);
}
}
/**
* This can be used to turn off domain name compression. This was helpful for tracking problems interacting with other mdns implementations.
*/
public static boolean USE_DOMAIN_NAME_COMPRESSION = true;
Map<String, Integer> _names;
private int _maxUDPPayload;
private final MessageOutputStream _questionsBytes;
private final MessageOutputStream _answersBytes;
private final MessageOutputStream _authoritativeAnswersBytes;
private final MessageOutputStream _additionalsAnswersBytes;
private final static int HEADER_SIZE = 12;
private InetSocketAddress _destination;
/**
* Create an outgoing multicast query or response.
*
* @param flags
*/
public DNSOutgoing(int flags) {
this(flags, true, DNSConstants.MAX_MSG_TYPICAL);
}
/**
* Create an outgoing query or response.
*
* @param flags
* @param multicast
*/
public DNSOutgoing(int flags, boolean multicast) {
this(flags, multicast, DNSConstants.MAX_MSG_TYPICAL);
}
/**
* Create an outgoing query or response.
*
* @param flags
* @param multicast
* @param senderUDPPayload
* The sender's UDP payload size is the number of bytes of the largest UDP payload that can be reassembled and delivered in the sender's network stack.
*/
public DNSOutgoing(int flags, boolean multicast, int senderUDPPayload) {
super(flags, 0, multicast);
_names = new HashMap<String, Integer>();
_maxUDPPayload = (senderUDPPayload > 0 ? senderUDPPayload : DNSConstants.MAX_MSG_TYPICAL);
_questionsBytes = new MessageOutputStream(senderUDPPayload, this);
_answersBytes = new MessageOutputStream(senderUDPPayload, this);
_authoritativeAnswersBytes = new MessageOutputStream(senderUDPPayload, this);
_additionalsAnswersBytes = new MessageOutputStream(senderUDPPayload, this);
}
/**
* Get the forced destination address if a specific one was set.
*
* @return a forced destination address or null if no address is forced.
*/
public InetSocketAddress getDestination() {
return _destination;
}
/**
* Force a specific destination address if packet is sent.
*
* @param destination
* Set a destination address a packet should be sent to (instead the default one). You could use null to unset the forced destination.
*/
public void setDestination(InetSocketAddress destination) {
_destination = destination;
}
/**
* Return the number of byte available in the message.
*
* @return available space
*/
public int availableSpace() {
return _maxUDPPayload - HEADER_SIZE - _questionsBytes.size() - _answersBytes.size() - _authoritativeAnswersBytes.size() - _additionalsAnswersBytes.size();
}
/**
* Add a question to the message.
*
* @param rec
* @exception IOException
*/
public void addQuestion(DNSQuestion rec) throws IOException {
MessageOutputStream record = new MessageOutputStream(512, this);
record.writeQuestion(rec);
byte[] byteArray = record.toByteArray();
record.close();
if (byteArray.length < this.availableSpace()) {
_questions.add(rec);
_questionsBytes.write(byteArray, 0, byteArray.length);
} else {
throw new IOException("message full");
}
}
/**
* Add an answer if it is not suppressed.
*
* @param in
* @param rec
* @exception IOException
*/
public void addAnswer(DNSIncoming in, DNSRecord rec) throws IOException {
if ((in == null) || !rec.suppressedBy(in)) {
this.addAnswer(rec, 0);
}
}
/**
* Add an answer to the message.
*
* @param rec
* @param now
* @exception IOException
*/
public void addAnswer(DNSRecord rec, long now) throws IOException {
if (rec != null) {
if ((now == 0) || !rec.isExpired(now)) {
MessageOutputStream record = new MessageOutputStream(512, this);
record.writeRecord(rec, now);
byte[] byteArray = record.toByteArray();
record.close();
if (byteArray.length < this.availableSpace()) {
_answers.add(rec);
_answersBytes.write(byteArray, 0, byteArray.length);
} else {
throw new IOException("message full");
}
}
}
}
/**
* Add an authoritative answer to the message.
*
* @param rec
* @exception IOException
*/
public void addAuthorativeAnswer(DNSRecord rec) throws IOException {
MessageOutputStream record = new MessageOutputStream(512, this);
record.writeRecord(rec, 0);
byte[] byteArray = record.toByteArray();
record.close();
if (byteArray.length < this.availableSpace()) {
_authoritativeAnswers.add(rec);
_authoritativeAnswersBytes.write(byteArray, 0, byteArray.length);
} else {
throw new IOException("message full");
}
}
/**
* Add an additional answer to the record. Omit if there is no room.
*
* @param in
* @param rec
* @exception IOException
*/
public void addAdditionalAnswer(DNSIncoming in, DNSRecord rec) throws IOException {
MessageOutputStream record = new MessageOutputStream(512, this);
record.writeRecord(rec, 0);
byte[] byteArray = record.toByteArray();
record.close();
if (byteArray.length < this.availableSpace()) {
_additionals.add(rec);
_additionalsAnswersBytes.write(byteArray, 0, byteArray.length);
} else {
throw new IOException("message full");
}
}
/**
* Builds the final message buffer to be send and returns it.
*
* @return bytes to send.
*/
public byte[] data() {
long now = System.currentTimeMillis(); // System.currentTimeMillis()
_names.clear();
MessageOutputStream message = new MessageOutputStream(_maxUDPPayload, this);
message.writeShort(_multicast ? 0 : this.getId());
message.writeShort(this.getFlags());
message.writeShort(this.getNumberOfQuestions());
message.writeShort(this.getNumberOfAnswers());
message.writeShort(this.getNumberOfAuthorities());
message.writeShort(this.getNumberOfAdditionals());
for (DNSQuestion question : _questions) {
message.writeQuestion(question);
}
for (DNSRecord record : _answers) {
message.writeRecord(record, now);
}
for (DNSRecord record : _authoritativeAnswers) {
message.writeRecord(record, now);
}
for (DNSRecord record : _additionals) {
message.writeRecord(record, now);
}
byte[] result = message.toByteArray();
try {
message.close();
} catch (IOException exception) {}
return result;
}
/**
* Debugging.
*/
String print(boolean dump) {
StringBuilder buf = new StringBuilder();
buf.append(this.print());
if (dump) {
buf.append(this.print(this.data()));
}
return buf.toString();
}
@Override
public String toString() {
StringBuffer buf = new StringBuffer();
buf.append(isQuery() ? "dns[query:" : "dns[response:");
buf.append(" id=0x");
buf.append(Integer.toHexString(this.getId()));
if (this.getFlags() != 0) {
buf.append(", flags=0x");
buf.append(Integer.toHexString(this.getFlags()));
if (this.isResponse()) {
buf.append(":r");
}
if (this.isAuthoritativeAnswer()) {
buf.append(":aa");
}
if (this.isTruncated()) {
buf.append(":tc");
}
}
if (this.getNumberOfQuestions() > 0) {
buf.append(", questions=");
buf.append(this.getNumberOfQuestions());
}
if (this.getNumberOfAnswers() > 0) {
buf.append(", answers=");
buf.append(this.getNumberOfAnswers());
}
if (this.getNumberOfAuthorities() > 0) {
buf.append(", authorities=");
buf.append(this.getNumberOfAuthorities());
}
if (this.getNumberOfAdditionals() > 0) {
buf.append(", additionals=");
buf.append(this.getNumberOfAdditionals());
}
if (this.getNumberOfQuestions() > 0) {
buf.append("\nquestions:");
for (DNSQuestion question : _questions) {
buf.append("\n\t");
buf.append(question);
}
}
if (this.getNumberOfAnswers() > 0) {
buf.append("\nanswers:");
for (DNSRecord record : _answers) {
buf.append("\n\t");
buf.append(record);
}
}
if (this.getNumberOfAuthorities() > 0) {
buf.append("\nauthorities:");
for (DNSRecord record : _authoritativeAnswers) {
buf.append("\n\t");
buf.append(record);
}
}
if (this.getNumberOfAdditionals() > 0) {
buf.append("\nadditionals:");
for (DNSRecord record : _additionals) {
buf.append("\n\t");
buf.append(record);
}
}
buf.append("\nnames=");
buf.append(_names);
buf.append("]");
return buf.toString();
}
/**
* @return the maxUDPPayload
*/
public int getMaxUDPPayload() {
return this._maxUDPPayload;
}
}
| 32.465409 | 166 | 0.537195 |
72d02c9f250bdcda5394a407a3e69b89957b7ace | 2,633 | /**
* Copyright 1996-2014 FoxBPM 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.
*
* @author kenshin
*/
package org.foxbpm.engine.impl.util;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import org.foxbpm.engine.impl.expression.ExpressionMgmt;
import org.foxbpm.kernel.runtime.FlowNodeExecutionContext;
public class AssigneeUtil {
public static List<String> executionExpression(String expression,
FlowNodeExecutionContext executionContext) {
List<String> resultList = new ArrayList<String>();
Object result = null;
try{
result = ExpressionMgmt.execute(expression, executionContext);
}catch(Exception ex){
throw ExceptionUtil.getException("10304004");
}
if (result != null) {
if (result instanceof String) {
String[] dddStrings = result.toString().split(",");
int length = dddStrings.length;
for (int i = 0; i < length; i++) {
resultList.add(dddStrings[i]);
}
} else if (result instanceof Integer) {
resultList.add(result.toString());
} else if (result instanceof BigDecimal) {
resultList.add(result.toString());
} else if (result instanceof Collection) {
Collection<?> resultTempList = (Collection<?>) result;
for (Object resultObj : resultTempList) {
resultList.add(resultObj.toString());
}
}
}
return resultList;
}
public static List<String> executionExpressionObj(Object result) {
List<String> resultList = new ArrayList<String>();
if (result != null) {
if (result instanceof String) {
String[] dddStrings = result.toString().split(",");
for (int i = 0; i < dddStrings.length; i++) {
resultList.add(dddStrings[i]);
}
} else if (result instanceof Integer) {
resultList.add(result.toString());
} else if (result instanceof BigDecimal) {
resultList.add(result.toString());
} else if (result instanceof Collection) {
Collection<?> resultTempList = (Collection<?>) result;
for (Object resultObj : resultTempList) {
resultList.add(resultObj.toString());
}
}
}
return resultList;
}
}
| 30.264368 | 75 | 0.698823 |
5dbdc098d68cd1fea7834754a4aded91bf8ec956 | 2,700 | package org.codehaus.xfire.annotations;
import java.io.Serializable;
import org.codehaus.xfire.service.OperationInfo;
/**
* Represents an common representation of a web method annotation. Specifies that the given method is exposed as a Web
* Service operation, making it part of the Web Service�s public contract. A WebMethod annotation is required for each
* method that is published by the Web Service.
*
* @author Arjen Poutsma
*/
public class WebMethodAnnotation implements Serializable
{
private String action = "";
private String operationName = "";
private boolean exclude = false;
public boolean isExclude()
{
return exclude;
}
public void setExclude(boolean exclude)
{
this.exclude = exclude;
}
/**
* Returns the action for this operation. For SOAP bindings, this determines the value of the SOAPAction header.
*
* @return the action for this operation.
*/
public String getAction()
{
return action;
}
/**
* Sets the action for this operation. For SOAP bindings, this determines the value of the SOAPAction header.
*
* @param action the new action for this operation.
*/
public void setAction(String action)
{
this.action = action;
}
/**
* Returns the name of the wsdl:operation matching this method. By default the WSDL operation name will be the same
* as the Java method name.
*
* @return the name of the wsdl:operation matching this method.
*/
public String getOperationName()
{
return operationName;
}
/**
* Sets the name of the wsdl:operation matching this method. By default the WSDL operation name will be the same as
* the Java method name.
*
* @param operationName the new name of the wsdl:operation matching this method.
*/
public void setOperationName(String operationName)
{
this.operationName = operationName;
}
/**
* Populates the given operation info with the information contained in this annotation.
*
* @param operationInfo the operation info.
*/
public void populate(OperationInfo operationInfo)
{
if (operationName.length() != 0)
{
operationInfo.setName(operationName);
}
}
/**
* Returns a <code>String</code> representation of this <code>WebMethodAnnotation</code>.
*
* @return a string representation.
*/
public String toString()
{
return "WebMethodAnnotation{" +
"action='" + action + "'" +
", operationName='" + operationName + "'" +
"}";
}
}
| 27.55102 | 119 | 0.637407 |
119a0bdf8079af6496c89e111668a85fbbcdf41e | 2,530 | package com.choonster.testmod2.block;
import com.choonster.testmod2.TestMod2;
import net.minecraft.block.material.Material;
import net.minecraft.entity.Entity;
import net.minecraft.entity.item.EntityItem;
import net.minecraft.init.Blocks;
import net.minecraft.init.Items;
import net.minecraft.item.ItemStack;
import net.minecraft.util.IIcon;
import net.minecraft.world.IBlockAccess;
import net.minecraft.world.World;
import net.minecraftforge.fluids.BlockFluidClassic;
import net.minecraftforge.fluids.Fluid;
// A fluid Block that sends a server-wide chat message when an EntityItem collides with it
// Test for this thread: http://www.minecraftforum.net/forums/mapping-and-modding/minecraft-mods/modification-development/2439366-help-with-have-items-be-swaped-with-other-items
public class BlockCollisionTestFluid extends BlockFluidClassic {
public BlockCollisionTestFluid(Fluid fluid) {
super(fluid, Material.water);
setCreativeTab(TestMod2.tab);
setUnlocalizedName(fluid.getUnlocalizedName());
}
@Override
public IIcon getIcon(int side, int meta) {
return Blocks.flowing_water.getIcon(side, meta);
}
@Override
public int colorMultiplier(IBlockAccess p_149720_1_, int p_149720_2_, int p_149720_3_, int p_149720_4_) {
return 90019001;
}
@Override
public void onEntityCollidedWithBlock(World world, int x, int y, int z, Entity entity) {
if (!(entity instanceof EntityItem)) { // If the Entity isn't an EntityItem, return now
return;
}
EntityItem entityItem = (EntityItem) entity; // Cast the Entity to EntityItem
ItemStack stack = entityItem.getEntityItem(); // Get the EntityItem's ItemStack
if (stack.getItem() == Items.quartz) { // If the stack contains Nether Quartz,
double posX = entityItem.posX, posY = entityItem.posY, posZ = entityItem.posZ;
if (!world.isRemote) { // If this is the server
ItemStack newStack = stack.copy(); // Copy the stack
newStack.setItem(Items.baked_potato); // Replace its Item with Baked Potato
EntityItem newEntityItem = new EntityItem(world, posX, posY, posZ, newStack); // Create a new EntityItem at the same position
world.spawnEntityInWorld(newEntityItem); // Spawn it
entityItem.setDead(); // Kill the old one
}
world.playSoundAtEntity(entityItem, "game.tnt.primed", 1.0F, 1.0F); // Play a sound
for (int i = 0; i < 32; ++i) { // Spawn some particles
world.spawnParticle("portal", posX, posY + world.rand.nextDouble() * 2.0D, posZ, world.rand.nextGaussian(), 0.0D, world.rand.nextGaussian());
}
}
}
}
| 38.923077 | 177 | 0.75336 |
6e720bae852e87e7618ee7600c5b89ae853dcb7f | 7,998 | /**
*
*/
package com.vijitha.dao;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;
import com.vijitha.model.Book;
import com.vijitha.model.Standards;
import com.vijitha.util.DbConnection;
/**
* @author Vijitha
*
*/
public class StandardDao {
private Connection connection;
private String query = null;
public StandardDao(){
try {
connection=DbConnection.getConnection();
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public void checkStandard(Standards standard){
try {
PreparedStatement ps=connection.prepareStatement("select ref_no from standards where ref_no = ? ");
ps.setString(1, standard.getRefNo());
ResultSet rs=ps.executeQuery();
if(rs.next()){
updateStandard(standard);
}else{
addStandard(standard);
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public void addStandard(Standards standard){
try {
PreparedStatement ps=connection.prepareStatement("INSERT INTO standards (ref_no,type,edition,amendment,description,year_of_published,year_of_amended,enter_by,date_entered,location,keywords) VALUES(?,?,?,?,?,?,?,?,?,?,?);");
ps.setString(1, standard.getRefNo());
ps.setString(2, standard.getType());
ps.setInt(3, standard.getEdition());
ps.setString(4, standard.getAmendment());
ps.setString(5, standard.getDescription());
ps.setString(6, standard.getYearOfPublished());
ps.setString(7, standard.getYearOfAmended());
ps.setString(8, standard.getEnteredBy());
ps.setDate(9, new java.sql.Date(standard.getEnteredDate().getTime()));
ps.setString(10, standard.getLocation());
ps.setString(11, standard.getKeywords());
ps.executeUpdate();
//initializeBookCopies(standard);
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
//TODO implement book update function
public void updateStandard(Standards standard){
try {
PreparedStatement ps=connection.prepareStatement("UPDATE standards SET standards (ref_no=?,type=?,edition=?,amendment=?,description=?,year_of_published=?,year_of_amended=?,enter_by=?,date_entered=?,location=?,keywords=?);");
ps.setString(1, standard.getRefNo());
ps.setString(2, standard.getType());
ps.setInt(3, standard.getEdition());
ps.setString(4, standard.getAmendment());
ps.setString(5, standard.getDescription());
ps.setString(6, standard.getYearOfPublished());
ps.setString(7, standard.getYearOfAmended());
ps.setString(8, standard.getEnteredBy());
ps.setDate(9, new java.sql.Date(standard.getEnteredDate().getTime()));
ps.setString(10, standard.getLocation());
ps.setString(11, standard.getKeywords());
ps.executeUpdate();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
//TODO
public void deleteStandard(String id){
try {
PreparedStatement preparedStatement = connection.prepareStatement("DELETE FROM standards where ref_no=?");
// Parameters start with 1
preparedStatement.setString(1, id);
preparedStatement.executeUpdate();
} catch (SQLException e) {
e.printStackTrace();
}
}
public List<Standards> getAllStandards(){
List<Standards> standards=new ArrayList<Standards>();
try {
Statement st = connection.createStatement();
ResultSet rs=st.executeQuery("SELECT * FROM standards");
while(rs.next()){
Standards standard=new Standards();
standard.setRefNo(rs.getString("ref_no"));
standard.setType(rs.getString("type"));
standard.setEdition(rs.getInt("edition"));
standard.setAmendment(rs.getString("amendment"));
standard.setDescription(rs.getString("description"));
standard.setYearOfPublished(rs.getString("year_of_published"));
standard.setYearOfAmended(rs.getString("year_of_amended"));
standard.setEnteredBy(rs.getString("enter_by"));
standard.setEnteredDate(rs.getDate("date_entered"));
standard.setLocation(rs.getString("location"));
standard.setKeywords(rs.getString("keywords"));
standards.add(standard);
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println(standards.size() +" ::::::::::::::::::");
return standards;
}
public Standards getStandardById(String standardId){
Standards standard=new Standards();
try {
PreparedStatement ps=connection.prepareStatement("SELECT * FROM standards WHERE ref_no = ?");
ps.setString(1, standardId);
ResultSet rs=ps.executeQuery();
if(rs.next()){
standard.setRefNo(rs.getString("ref_no"));
standard.setType(rs.getString("type"));
standard.setEdition(rs.getInt("edition"));
standard.setAmendment(rs.getString("amendment"));
standard.setDescription(rs.getString("description"));
standard.setYearOfPublished(rs.getString("year_of_published"));
standard.setYearOfAmended(rs.getString("year_of_amended"));
standard.setEnteredBy(rs.getString("enter_by"));
standard.setEnteredDate(rs.getDate("date_entered"));
standard.setLocation(rs.getString("location"));
standard.setKeywords(rs.getString("keywords"));
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return standard;
}
public List<Standards> getSearchedStandards(String name,String criteria){
List<Standards> standards=new ArrayList<>();
System.out.println("+++++++++++++++++test++++++++++");
if(name.equals("") ){
System.out.println("+++++++++++++++++test2++++++++++");
query="SELECT * FROM standards";
}else {
switch (criteria) {
case "refno":
query="SELECT * FROM standards WHERE ref_no LIKE '%"+name+"%' ";
break;
case "description":
query="SELECT * FROM standards WHERE description LIKE '%"+name+"%' ";
break;
default:
break;
}
}
System.out.println(query);
try {
Statement st=connection.createStatement();
ResultSet rs=st.executeQuery(query);
while(rs.next()){
Standards standard=new Standards();
standard.setRefNo(rs.getString("ref_no"));
standard.setType(rs.getString("type"));
standard.setEdition(rs.getInt("edition"));
standard.setAmendment(rs.getString("amendment"));
standard.setDescription(rs.getString("description"));
standard.setYearOfPublished(rs.getString("year_of_published"));
standard.setYearOfAmended(rs.getString("year_of_amended"));
standard.setEnteredBy(rs.getString("enter_by"));
standard.setEnteredDate(rs.getDate("date_entered"));
standard.setLocation(rs.getString("location"));
standard.setKeywords(rs.getString("keywords"));
standards.add(standard);
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return standards;
}
public void initializeBookCopies(Book book){
try {
PreparedStatement ps=connection.prepareStatement("INSERT INTO book_copies_count (acc_no,total_copies,available_copies) VALUES(?,?,?);");
ps.setString(1, book.getId());
ps.setInt(2, book.getNoofBooks());
ps.setInt(3, book.getNoofBooks());
ps.executeUpdate();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public int getAvailableCopies(Book book){
int count=0;
try {
PreparedStatement ps=connection.prepareStatement("select available_copies from book_copies_count where acc_no = ? ");
ps.setString(1, book.getId());
ResultSet rs=ps.executeQuery();
if(rs.next()){
count=rs.getInt("available_copies");
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.print("count "+count);
return count;
}
}
| 30.643678 | 227 | 0.689797 |
34fbd66e17878006401206542b81cc0c44da3ec2 | 2,619 | /**
* Copyright (C) 2013 – 2016 SLUB Dresden & Avantgarde Labs GmbH (<[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.dswarm.converter.pipe.timing;
import com.codahale.metrics.MetricRegistry;
import com.codahale.metrics.Timer;
import com.codahale.metrics.Timer.Context;
import com.google.inject.Inject;
import com.google.inject.assistedinject.Assisted;
import com.google.inject.name.Named;
import org.culturegraph.mf.framework.Receiver;
import org.culturegraph.mf.framework.Sender;
import static com.codahale.metrics.MetricRegistry.name;
abstract class TimerBased<R extends Receiver> implements Sender<R> {
protected static final String OBJECT_PROCESS = "process";
protected static final String STREAM_RECORDS = "records";
protected static final String STREAM_ENTITIES = "entities";
protected static final String STREAM_LITERALS = "literals";
protected static final String XML_ENTITIES = "entities";
protected static final String XML_ELEMENTS = "elements";
protected static final String XML_CHARACTERS = "characters";
private final MetricRegistry registry;
private final String prefix;
private final Timer cumulativeTimer;
private R receiver;
@Inject
protected TimerBased(
@Named("Monitoring") final MetricRegistry registry,
@Assisted final String prefix) {
this.registry = registry;
this.prefix = prefix;
cumulativeTimer = registry.timer(name(prefix, "cumulative"));
}
@Override
public final <S extends R> S setReceiver(final S receiver) {
this.receiver = receiver;
return receiver;
}
public final R getReceiver() {
return receiver;
}
@Override
public void resetStream() {
if (receiver != null) {
receiver.resetStream();
}
}
@Override
public final void closeStream() {
if (receiver != null) {
final Context context = cumulativeTimer.time();
receiver.closeStream();
context.stop();
}
}
protected final TimingContext startMeasurement(final String qualifier) {
final Timer timer = registry.timer(name(prefix, qualifier));
return new TimingContext(timer.time(), cumulativeTimer.time());
}
}
| 30.453488 | 84 | 0.754105 |
c1eca344725a2e9097f3e65ead8db49a5cb91548 | 5,449 | package io.github.stefanosbou;
import io.vertx.core.DeploymentOptions;
import io.vertx.core.Vertx;
import io.vertx.core.json.JsonObject;
import io.vertx.ext.unit.Async;
import io.vertx.ext.unit.TestContext;
import io.vertx.ext.unit.junit.VertxUnitRunner;
import io.vertx.ext.web.client.WebClient;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import java.io.IOException;
import java.net.ServerSocket;
@RunWith(VertxUnitRunner.class)
public class TestApiEndpointVerticle {
Vertx vertx;
Integer port;
/**
* Before executing our test, let's deploy our verticle.
* <p/>
* This method instantiates a new Vertx and deploy the verticle. Then, it waits in the verticle has successfully
* completed its start sequence (thanks to `context.asyncAssertSuccess`).
*
* @param context the test context.
*/
@Before
public void setUp(TestContext context) throws IOException {
vertx = Vertx.vertx();
Async async = context.async();
// Let's configure the verticle to listen on the 'test' port (randomly picked).
// We create deployment options and set the _configuration_ json object:
ServerSocket socket = new ServerSocket(0);
port = socket.getLocalPort();
socket.close();
DeploymentOptions options = new DeploymentOptions()
.setConfig(new JsonObject().put("http.port", port)
);
vertx.deployVerticle(new ApiEndpointVerticle(), options, ar -> {
if (ar.succeeded()) {
async.complete();
} else {
context.fail(ar.cause());
}
});
}
/**
* This method, called after our test, just cleanup everything by closing the vert.x instance
*
* @param context the test context
*/
@After
public void tearDown(TestContext context) {
vertx.close(context.asyncAssertSuccess());
}
/**
* Let's ensure that our application behaves correctly.
*
* @param context the test context
*/
@Test
public void testApiIsProtected(TestContext context) {
Async async = context.async();
WebClient client = WebClient.create(vertx);
client.get(port, "localhost", "/api/orders").send(ar -> {
if (ar.succeeded()) {
if(ar.result().statusCode() == 401){
async.complete();
} else {
context.fail();
}
} else {
context.fail(ar.cause().getMessage());
}
});
}
@Test
public void testApiGetToken(TestContext context) {
Async async = context.async();
WebClient client = WebClient.create(vertx);
client.post(port, "localhost", "/api/token").send(ar -> {
if (ar.succeeded()) {
if(ar.result().statusCode() == 200){
async.complete();
} else {
context.fail();
}
} else {
context.fail(ar.cause().getMessage());
}
});
}
@Test
public void testApiPostMalformedOrder(TestContext context) {
Async async = context.async();
WebClient client = WebClient.create(vertx);
JsonObject malformedOrderJson = new JsonObject()
.put("user", "12345")
.put("currencyFrom", "EUR")
.put("currencyTo", "USD")
.put("amountSell", 1000)
.put("amountBuy", 747.1)
.put("rate", 0.7471)
.put("timePlaced", "24JAN15 10:27:44")
.put("originatingCountry", "US");
client.post(port, "localhost", "/api/token").send(ar -> {
if (ar.succeeded()) {
if(ar.result().statusCode() == 200){
client.post(port, "localhost", "/api/orders")
.putHeader("Authorization", "Bearer " + ar.result().bodyAsString())
.sendJsonObject(malformedOrderJson, res -> {
if (res.succeeded()) {
if(res.result().statusCode() == 400){
async.complete();
} else {
context.fail();
}
} else {
context.fail(res.cause().getMessage());
}
});
} else {
context.fail();
}
} else {
context.fail(ar.cause().getMessage());
}
});
}
@Test
public void testApiPostEmptyOrder(TestContext context) {
Async async = context.async();
WebClient client = WebClient.create(vertx);
client.post(port, "localhost", "/api/token").send(ar -> {
if (ar.succeeded()) {
if (ar.result().statusCode() == 200) {
client.post(port, "localhost", "/api/orders")
.putHeader("Authorization", "Bearer " + ar.result().bodyAsString())
.send(res -> {
if (res.succeeded()) {
if (res.result().statusCode() == 400) {
async.complete();
} else {
context.fail();
}
} else {
context.fail(res.cause().getMessage());
}
});
} else {
context.fail();
}
} else {
context.fail(ar.cause().getMessage());
}
});
}
} | 30.61236 | 115 | 0.532208 |
24cbc3919a6ae6ce1b1d60fb049773b5da7d0de4 | 1,083 | package i5.las2peer.services.cdService.data.util.table;
import static org.junit.Assert.assertEquals;
import java.util.List;
import org.junit.Test;
public class DataTableTest {
@Test
public void addTwoDoubleArray() {
double[] val1 = new double[]{1.0,2.0,3.0,4.0};
double[] val2 = new double[]{1.2,2.3,4.5,2.1};
DataTable table = new DataTable();
table.add(val1, val2);
List<TableRow> tableRows = table.getTableRows();
assertEquals(val1.length, tableRows.size());
assertEquals(String.valueOf(1.0), tableRows.get(0).getCells().get(0));
assertEquals(String.valueOf(1.2), tableRows.get(0).getCells().get(1));
assertEquals(String.valueOf(2.0), tableRows.get(1).getCells().get(0));
assertEquals(String.valueOf(2.3), tableRows.get(1).getCells().get(1));
assertEquals(String.valueOf(3.0), tableRows.get(2).getCells().get(0));
assertEquals(String.valueOf(4.5), tableRows.get(2).getCells().get(1));
assertEquals(String.valueOf(4.0), tableRows.get(3).getCells().get(0));
assertEquals(String.valueOf(2.1), tableRows.get(3).getCells().get(1));
}
}
| 31.852941 | 72 | 0.702678 |
7325fe1f359093a5899a62765a9e05a99c8b1f68 | 1,908 | import java.awt.*;
import java.awt.event.*;
import java.util.ArrayList;
public class BankInterface extends Frame implements ActionListener, Runnable {
private TextField RefNo_lbl;
private Button auth_pay;
private Button decline_pay;
private Label CardNo_lbl;
private Label Total_lbl;
Connector connect;
public BankInterface(Connector connect) {
this.connect = connect;
new Thread(this, "Bank Interface").start();
}
public void run() {
ArrayList<Object> message = (ArrayList<Object>) connect.receive();
setLayout(new FlowLayout());
auth_pay = new Button("Authorize");
add(auth_pay);
auth_pay.addActionListener(this);
decline_pay = new Button("Decline");
add(decline_pay);
decline_pay.addActionListener(this);
RefNo_lbl = new TextField(15);
add(RefNo_lbl);
RefNo_lbl.addActionListener(this);
CardNo_lbl = new Label("Card#: " + message.get(0).toString());
add(CardNo_lbl);
Total_lbl = new Label("Total: $" + message.get(1).toString());
add(Total_lbl);
setTitle("Bank Interface");
setSize(350, 100);
setLocation(500, 380);
setVisible(true);
}
@Override
public void actionPerformed(ActionEvent evt) {
ArrayList<Object> message = new ArrayList<>();
String btnLabel = evt.getActionCommand();
setVisible(false);
if (btnLabel.equals("Authorize")) {
message.add("authorized");
message.add(RefNo_lbl.getText());
connect.reply(message);
} else {
message.add("Declined");
connect.reply(message);
}
}
}
| 30.774194 | 78 | 0.553983 |
de97b89fdf67db8b7ae8b295e5e89815e0341562 | 482 | package jp.ats.liverwort.support.annotation;
import static java.lang.annotation.ElementType.METHOD;
import static java.lang.annotation.RetentionPolicy.RUNTIME;
import java.lang.annotation.Retention;
import java.lang.annotation.Target;
/**
* DTO の setter 情報を表すアノテーションです。
*
* @author 千葉 哲嗣
*/
@Target({ METHOD })
@Retention(RUNTIME)
public @interface DTOSetter {
/**
* カラム名
*
* @return カラム名
*/
String column();
/**
* 型
*
* @return 型
*/
Class<?> type();
}
| 15.0625 | 59 | 0.682573 |
80797bfd6a7e8e97892efe0e874c13998e667a04 | 14,863 | /*
* Copyright © 2021-present Arcade Data Ltd ([email protected])
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.arcadedb.utility;
import com.arcadedb.database.Binary;
import com.arcadedb.database.DatabaseFactory;
import com.arcadedb.log.LogManager;
import java.io.*;
import java.lang.management.ManagementFactory;
import java.lang.management.ThreadInfo;
import java.lang.management.ThreadMXBean;
import java.nio.channels.FileChannel;
import java.nio.file.FileSystem;
import java.nio.file.*;
import java.util.Locale;
import java.util.logging.Level;
import java.util.zip.GZIPOutputStream;
public class FileUtils {
public static final int KILOBYTE = 1024;
public static final int MEGABYTE = 1048576;
public static final int GIGABYTE = 1073741824;
public static final long TERABYTE = 1099511627776L;
public static final String UTF8_BOM = "\uFEFF";
private static final boolean useOldFileAPI;
static {
boolean oldAPI = false;
try {
Class.forName("java.nio.file.FileSystemException");
} catch (ClassNotFoundException ignore) {
oldAPI = true;
}
useOldFileAPI = oldAPI;
}
public static String getStringContent(final Object iValue) {
if (iValue == null)
return null;
final String s = iValue.toString();
if (s == null)
return null;
if (s.length() > 1 && (s.charAt(0) == '\'' && s.charAt(s.length() - 1) == '\'' || s.charAt(0) == '"' && s.charAt(s.length() - 1) == '"'))
return s.substring(1, s.length() - 1);
if (s.length() > 1 && (s.charAt(0) == '`' && s.charAt(s.length() - 1) == '`'))
return s.substring(1, s.length() - 1);
return s;
}
public static boolean isLong(final String iText) {
boolean isLong = true;
final int size = iText.length();
for (int i = 0; i < size && isLong; i++) {
final char c = iText.charAt(i);
isLong = isLong & ((c >= '0' && c <= '9'));
}
return isLong;
}
public static long getSizeAsNumber(final Object iSize) {
if (iSize == null)
throw new IllegalArgumentException("Size is null");
if (iSize instanceof Number)
return ((Number) iSize).longValue();
String size = iSize.toString();
boolean number = true;
for (int i = size.length() - 1; i >= 0; --i) {
final char c = size.charAt(i);
if (!Character.isDigit(c)) {
if (i > 0 || (c != '-' && c != '+'))
number = false;
break;
}
}
if (number)
return string2number(size).longValue();
else {
size = size.toUpperCase(Locale.ENGLISH);
int pos = size.indexOf("KB");
if (pos > -1)
return (long) (string2number(size.substring(0, pos)).floatValue() * KILOBYTE);
pos = size.indexOf("MB");
if (pos > -1)
return (long) (string2number(size.substring(0, pos)).floatValue() * MEGABYTE);
pos = size.indexOf("GB");
if (pos > -1)
return (long) (string2number(size.substring(0, pos)).floatValue() * GIGABYTE);
pos = size.indexOf("TB");
if (pos > -1)
return (long) (string2number(size.substring(0, pos)).floatValue() * TERABYTE);
pos = size.indexOf('B');
if (pos > -1)
return (long) string2number(size.substring(0, pos)).floatValue();
pos = size.indexOf('%');
if (pos > -1)
return (long) (-1 * string2number(size.substring(0, pos)).floatValue());
// RE-THROW THE EXCEPTION
throw new IllegalArgumentException("Size " + size + " has a unrecognizable format");
}
}
public static Number string2number(final String iText) {
if (iText.indexOf('.') > -1)
return Double.parseDouble(iText);
else
return Long.parseLong(iText);
}
public static String getSizeAsString(final long iSize) {
if (iSize > TERABYTE)
return String.format("%2.2fTB", (float) iSize / TERABYTE);
if (iSize > GIGABYTE)
return String.format("%2.2fGB", (float) iSize / GIGABYTE);
if (iSize > MEGABYTE)
return String.format("%2.2fMB", (float) iSize / MEGABYTE);
if (iSize > KILOBYTE)
return String.format("%2.2fKB", (float) iSize / KILOBYTE);
return iSize + "b";
}
public static void checkValidName(final String iFileName) throws IOException {
if (iFileName.contains("..") || iFileName.contains("/") || iFileName.contains("\\"))
throw new IOException("Invalid file name '" + iFileName + "'");
}
public static void deleteRecursively(final File rootFile) {
for (int attempt = 0; attempt < 3; attempt++) {
try {
if (rootFile.exists()) {
if (rootFile.isDirectory()) {
final File[] files = rootFile.listFiles();
if (files != null) {
for (File f : files) {
if (f.isFile()) {
Files.delete(Paths.get(f.getAbsolutePath()));
} else
deleteRecursively(f);
}
}
}
Files.delete(Paths.get(rootFile.getAbsolutePath()));
}
break;
} catch (IOException e) {
// if (System.getProperty("os.name").toLowerCase().contains("win")) {
// // AVOID LOCKING UNDER WINDOWS
// try {
// LogManager.instance()
// .log(rootFile, Level.WARNING, "Cannot delete directory '%s'. Forcing GC cleanup and try again (attempt=%d)", e, rootFile, attempt);
// System.gc();
// Thread.sleep(1000);
// } catch (Exception ex) {
// // IGNORE IT
// }
// } else
LogManager.instance().log(rootFile, Level.WARNING, "Cannot delete directory '%s'", e, rootFile);
}
}
}
public static void deleteFolderIfEmpty(final File dir) {
if (dir != null && dir.listFiles() != null && dir.listFiles().length == 0) {
deleteRecursively(dir);
}
}
public static boolean deleteFile(final File file) {
for (int attempt = 0; attempt < 3; attempt++) {
try {
if (file.exists())
Files.delete(file.toPath());
return true;
} catch (IOException e) {
// if (System.getProperty("os.name").toLowerCase().contains("win")) {
// // AVOID LOCKING UNDER WINDOWS
// try {
// LogManager.instance().log(file, Level.WARNING, "Cannot delete file '%s'. Forcing GC cleanup and try again (attempt=%d)", e, file, attempt);
// System.gc();
// Thread.sleep(1000);
// } catch (Exception ex) {
// // IGNORE IT
// }
// } else
LogManager.instance().log(file, Level.WARNING, "Cannot delete file '%s'", e, file);
}
}
return false;
}
@SuppressWarnings("resource")
public static final void copyFile(final File source, final File destination) throws IOException {
try (FileInputStream fis = new FileInputStream(source); FileOutputStream fos = new FileOutputStream(destination)) {
final FileChannel sourceChannel = fis.getChannel();
final FileChannel targetChannel = fos.getChannel();
sourceChannel.transferTo(0, sourceChannel.size(), targetChannel);
}
}
public static final void copyDirectory(final File source, final File destination) throws IOException {
if (!destination.exists())
destination.mkdirs();
for (File f : source.listFiles()) {
final File target = new File(destination.getAbsolutePath() + "/" + f.getName());
if (f.isFile())
copyFile(f, target);
else
copyDirectory(f, target);
}
}
public static boolean renameFile(File from, File to) throws IOException {
if (useOldFileAPI)
return from.renameTo(to);
final FileSystem fileSystem = FileSystems.getDefault();
final Path fromPath = fileSystem.getPath(from.getAbsolutePath());
final Path toPath = fileSystem.getPath(to.getAbsolutePath());
Files.move(fromPath, toPath);
return true;
}
public static String threadDump() {
final StringBuilder dump = new StringBuilder();
final ThreadMXBean threadMXBean = ManagementFactory.getThreadMXBean();
final ThreadInfo[] threadInfos = threadMXBean.getThreadInfo(threadMXBean.getAllThreadIds(), 100);
for (ThreadInfo threadInfo : threadInfos) {
dump.append('"');
dump.append(threadInfo.getThreadName());
dump.append("\" ");
final Thread.State state = threadInfo.getThreadState();
dump.append("\n java.lang.Thread.State: ");
dump.append(state);
final StackTraceElement[] stackTraceElements = threadInfo.getStackTrace();
for (final StackTraceElement stackTraceElement : stackTraceElements) {
dump.append("\n at ");
dump.append(stackTraceElement);
}
dump.append("\n\n");
}
return dump.toString();
}
public static String readFileAsString(final File file, final String iCharset) throws IOException {
try (FileInputStream is = new FileInputStream(file)) {
return readStreamAsString(is, iCharset, 0);
}
}
public static Binary readStreamAsBinary(final InputStream iStream) throws IOException {
final Binary buffer = new Binary();
final byte[] buf = new byte[1_000_000];
int numRead;
while ((numRead = iStream.read(buf)) != -1)
buffer.putByteArray(buf, numRead);
return buffer;
}
public static String readStreamAsString(final InputStream iStream, final String iCharset) throws IOException {
return readStreamAsString(iStream, iCharset, 0);
}
public static String readStreamAsString(final InputStream iStream, final String iCharset, final long limit) throws IOException {
final StringBuilder fileData = new StringBuilder(1000);
try (final BufferedReader reader = new BufferedReader(new InputStreamReader(iStream, iCharset))) {
final char[] buf = new char[1024];
int numRead;
while ((numRead = reader.read(buf)) != -1) {
String readData = String.valueOf(buf, 0, numRead);
if (fileData.length() == 0 && readData.startsWith(UTF8_BOM))
// SKIP UTF-8 BOM IF ANY
readData = readData.substring(1);
if (limit > 0 && fileData.length() + readData.length() > limit) {
// LIMIT REACHED
fileData.append(readData, 0, (int) (limit - fileData.length()));
break;
} else
fileData.append(readData);
if (limit > 0 && fileData.length() >= limit)
// LIMIT REACHED
break;
}
}
return fileData.toString();
}
public static void writeFile(final File iFile, final String iContent) throws IOException {
try (FileOutputStream fos = new FileOutputStream(iFile)) {
writeContentToStream(fos, iContent);
}
}
public static void writeContentToStream(final File file, final byte[] content) throws IOException {
try (FileOutputStream fos = new FileOutputStream(file)) {
fos.write(content);
}
}
public static void writeContentToStream(final OutputStream output, final String iContent) throws IOException {
try (final OutputStreamWriter os = new OutputStreamWriter(output, DatabaseFactory.getDefaultCharset());
final BufferedWriter writer = new BufferedWriter(os)) {
writer.write(iContent);
}
}
public static String encode(final String value, final String encoding) {
try {
return java.net.URLEncoder.encode(value, encoding);
} catch (UnsupportedEncodingException e) {
LogManager.instance().log(FileUtils.class, Level.SEVERE, "Error on using encoding " + encoding, e);
return value;
}
}
public static void gzipFile(final File sourceFile, final File destFile) throws IOException {
try (FileInputStream fis = new FileInputStream(sourceFile);
FileOutputStream fos = new FileOutputStream(destFile);
GZIPOutputStream gzipOS = new GZIPOutputStream(fos)) {
byte[] buffer = new byte[1024 * 1024];
int len;
while ((len = fis.read(buffer)) != -1) {
gzipOS.write(buffer, 0, len);
}
}
}
public static String escapeHTML(final String s) {
final StringBuilder out = new StringBuilder(Math.max(16, s.length()));
for (int i = 0; i < s.length(); i++) {
final char c = s.charAt(i);
if (c > 127 || c == '"' || c == '\'' || c == '<' || c == '>' || c == '&') {
out.append("&#");
out.append((int) c);
out.append(';');
} else {
out.append(c);
}
}
return out.toString();
}
public static String printWithLineNumbers(final String text) {
// COUNT TOTAL LINES FIRST
int totalLines = 1;
int maxWidth = 0;
int currWidth = 0;
for (int i = 0; i < text.length(); i++) {
final char current = text.charAt(i);
if (current == '\n') {
++totalLines;
if (currWidth > maxWidth)
maxWidth = currWidth;
currWidth = 0;
} else
++currWidth;
}
if (currWidth > maxWidth)
maxWidth = currWidth;
final int maxLineDigits = String.valueOf(totalLines).length();
final StringBuilder result = new StringBuilder();
// PRINT /10
for (int i = 0; i < maxLineDigits + 1; i++)
result.append(" ");
for (int i = 0; i < maxWidth; i++) {
String s = "" + i;
final char unit = s.charAt(s.length() - 1);
if (unit == '0') {
final char decimal = s.length() > 1 ? s.charAt(s.length() - 2) : ' ';
result.append(decimal);
} else
result.append(' ');
}
result.append("\n");
// PRINT UNITS
for (int i = 0; i < maxLineDigits + 1; i++)
result.append(" ");
for (int i = 0; i < maxWidth; i++) {
String s = "" + i;
final char unit = s.charAt(s.length() - 1);
result.append(unit);
}
result.append(String.format("\n%-" + maxLineDigits + "d: ", 1));
int line = 1;
for (int i = 0; i < text.length(); i++) {
final char current = text.charAt(i);
final Character next = i + 1 < text.length() ? text.charAt(i) : null;
if (current == '\n') {
++line;
result.append(String.format("\n%-" + maxLineDigits + "d: ", line));
} else if (current == '\r' && (next == null || next == '\n')) {
++line;
result.append(String.format("\n%-" + maxLineDigits + "d: ", line));
++i;
} else
result.append(current);
}
return result.toString();
}
}
| 32.594298 | 153 | 0.609971 |
ef02af84fb1f0b2b402073048067e99ff0db9b03 | 330 | package roth.lib.java.json;
@SuppressWarnings("serial")
public class JsonException extends RuntimeException
{
public JsonException(String message)
{
super(message);
}
public JsonException(Throwable cause)
{
super(cause);
}
public JsonException(String message, Throwable cause)
{
super(message, cause);
}
}
| 14.347826 | 54 | 0.730303 |
e1ab9efc9da650732854481bbf869b1ad0badbd6 | 293 | public class Car {
CarType.Model model;
public Car(CarType.Model model){
this.model = model;
}
public CarType.Model getModel(){
return this.model;
}
public void setModel(CarType.Model model){
this.model = model;
}
}
| 16.277778 | 46 | 0.549488 |
01c27df3790202d532d2386db8bafe588dde619b | 892 | package com.team2052.frckrawler.comparators;
import com.team2052.frckrawler.listitems.ListItem;
import com.team2052.frckrawler.listitems.elements.CompiledMetricListElement;
import java.util.Comparator;
public class SimpleValueCompiledComparator implements Comparator<ListItem> {
private boolean desc;
public SimpleValueCompiledComparator(boolean desc) {
this.desc = desc;
}
public SimpleValueCompiledComparator() {
this(false);
}
@Override
public int compare(ListItem lhs, ListItem rhs) {
double lhsVal = ((CompiledMetricListElement) lhs).compiledMetricValue.getCompiledValueJson().get("value").getAsDouble();
double rhsVal = ((CompiledMetricListElement) rhs).compiledMetricValue.getCompiledValueJson().get("value").getAsDouble();
return desc ? Double.compare(lhsVal, rhsVal) : Double.compare(rhsVal, lhsVal);
}
}
| 34.307692 | 128 | 0.746637 |
094b72433f5fecd17721c3f1935a4cbe666ea5c1 | 454 | package com.javaedge.design.pattern.behavioral.chainofresponsibility;
/**
* 批准者
*
* @author JavaEdge
* @date 2019/1/19
*/
public abstract class AbstractApprover {
protected AbstractApprover abstractApprover;
public void setNextApprover(AbstractApprover abstractApprover) {
this.abstractApprover = abstractApprover;
}
/**
* 发布
*
* @param course 课程
*/
public abstract void deploy(Course course) ;
}
| 18.916667 | 69 | 0.682819 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.